slack-term 1.41.1 → 1.42.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 If}from"node:module";var Cf=Object.create;var{getPrototypeOf:_f,defineProperty:ia,getOwnPropertyNames:$f}=Object;var aa=Object.prototype.hasOwnProperty;function Ff(e){return this[e]}var Af,Tf,ca=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var s=t?Af??=new WeakMap:Tf??=new WeakMap,r=s.get(e);if(r)return r}n=e!=null?Cf(_f(e)):{};let i=t||!e||!e.__esModule||!aa.call(e,"default")?ia(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of $f(e))if(!aa.call(i,a))ia(i,a,{get:Ff.bind(e,a),enumerable:!0})}if(o)s.set(e,i);return i};var la=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ln=If(import.meta.url);var $a=la(function(zy,_a){_a.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 Qa=la(function(vD,Za){Za.exports=function(t){if(t===void 0)t=2;if(t>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+t+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var n=Error.prepareStackTrace;Error.prepareStackTrace=function(s,r){return r};var o=Error().stack;if(Error.prepareStackTrace=n,o!==null&&typeof o==="object")return o[t]?o[t].getFileName():void 0}});import{createHash as rm}from"crypto";import{existsSync as rf,readFileSync as af,mkdirSync as im,realpathSync as am,writeFileSync as cf}from"fs";import{homedir as zd}from"os";import{join as Nt,resolve as cm}from"path";import{notStrictEqual as mp,strictEqual as yp}from"assert";var Of={right:vf,center:Lf};class da{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((o)=>o.split("\t")),n=0;return t.forEach((o)=>{if(o.length>1&&Je.stringWidth(o[0])>n)n=Math.min(Math.floor(this.width*0.5),Je.stringWidth(o[0]))}),t.forEach((o)=>{this.div(...o.map((s,r)=>({text:s.trim(),padding:this.measurePadding(s),width:r===0&&o.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=Je.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach((t)=>{this.rowToString(t,e)}),e.filter((t)=>!t.hidden).map((t)=>t.text).join(`
5
- `)}rowToString(e,t){return this.rasterize(e).forEach((n,o)=>{let s="";n.forEach((r,i)=>{let{width:a}=e[i],c=this.negatePadding(e[i]),l=r;if(c>Je.stringWidth(r))l+=" ".repeat(c-Je.stringWidth(r));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=Of[e[i].align];if(l=d(l,c),Je.stringWidth(l)<c)l+=" ".repeat((a||0)-Je.stringWidth(l)-1)}let u=e[i].padding||[0,0,0,0];if(u[3])s+=" ".repeat(u[3]);if(s+=ua(e[i],l,"| "),s+=l,s+=ua(e[i],l," |"),u[1])s+=" ".repeat(u[1]);if(o===0&&t.length>0)s=this.renderInline(s,t[t.length-1])}),t.push({text:s.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),o=n?n[0].length:0,s=t.text,r=Je.stringWidth(s.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,s+e;if(o<r)return e;return t.hidden=!0,s.trimRight()+" ".repeat(o-r)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),o;return e.forEach((s,r)=>{if(s.width=n[r],this.wrap)o=Je.wrap(s.text,this.negatePadding(s),{hard:!0}).split(`
3
+ import{createRequire as Jf}from"node:module";var Lf=Object.create;var{getPrototypeOf:Nf,defineProperty:da,getOwnPropertyNames:Mf}=Object;var fa=Object.prototype.hasOwnProperty;function jf(e){return this[e]}var Wf,Uf,pa=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var s=t?Wf??=new WeakMap:Uf??=new WeakMap,r=s.get(e);if(r)return r}n=e!=null?Lf(Nf(e)):{};let i=t||!e||!e.__esModule||!fa.call(e,"default")?da(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Mf(e))if(!fa.call(i,a))da(i,a,{get:jf.bind(e,a),enumerable:!0})}if(o)s.set(e,i);return i};var ha=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ln=Jf(import.meta.url);var Oa=ha(function(iw,Ia){Ia.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 oc=ha(function(Gw,sc){sc.exports=function(t){if(t===void 0)t=2;if(t>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+t+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var n=Error.prepareStackTrace;Error.prepareStackTrace=function(s,r){return r};var o=Error().stack;if(Error.prepareStackTrace=n,o!==null&&typeof o==="object")return o[t]?o[t].getFileName():void 0}});import{createHash as ym}from"crypto";import{existsSync as hf,readFileSync as gf,mkdirSync as wm,realpathSync as Dm,writeFileSync as mf}from"fs";import{homedir as tf}from"os";import{join as Mt,resolve as bm}from"path";import{notStrictEqual as Fp,strictEqual as Ap}from"assert";var Kf={right:zf,center:Gf};class ma{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((o)=>o.split("\t")),n=0;return t.forEach((o)=>{if(o.length>1&&Me.stringWidth(o[0])>n)n=Math.min(Math.floor(this.width*0.5),Me.stringWidth(o[0]))}),t.forEach((o)=>{this.div(...o.map((s,r)=>({text:s.trim(),padding:this.measurePadding(s),width:r===0&&o.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=Me.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach((t)=>{this.rowToString(t,e)}),e.filter((t)=>!t.hidden).map((t)=>t.text).join(`
5
+ `)}rowToString(e,t){return this.rasterize(e).forEach((n,o)=>{let s="";n.forEach((r,i)=>{let{width:a}=e[i],c=this.negatePadding(e[i]),l=r;if(c>Me.stringWidth(r))l+=" ".repeat(c-Me.stringWidth(r));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=Kf[e[i].align];if(l=d(l,c),Me.stringWidth(l)<c)l+=" ".repeat((a||0)-Me.stringWidth(l)-1)}let u=e[i].padding||[0,0,0,0];if(u[3])s+=" ".repeat(u[3]);if(s+=ga(e[i],l,"| "),s+=l,s+=ga(e[i],l," |"),u[1])s+=" ".repeat(u[1]);if(o===0&&t.length>0)s=this.renderInline(s,t[t.length-1])}),t.push({text:s.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),o=n?n[0].length:0,s=t.text,r=Me.stringWidth(s.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,s+e;if(o<r)return e;return t.hidden=!0,s.trimRight()+" ".repeat(o-r)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),o;return e.forEach((s,r)=>{if(s.width=n[r],this.wrap)o=Me.wrap(s.text,this.negatePadding(s),{hard:!0}).split(`
6
6
  `);else o=s.text.split(`
7
- `);if(s.border)o.unshift("."+"-".repeat(this.negatePadding(s)+2)+"."),o.push("'"+"-".repeat(this.negatePadding(s)+2)+"'");if(s.padding)o.unshift(...Array(s.padding[0]||0).fill("")),o.push(...Array(s.padding[2]||0).fill(""));o.forEach((i,a)=>{if(!t[a])t.push([]);let c=t[a];for(let l=0;l<r;l++)if(c[l]===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((r)=>r.width||Je.stringWidth(r.text));let t=e.length,n=this.width,o=e.map((r)=>{if(r.width)return t--,n-=r.width,r.width;return}),s=t?Math.floor(n/t):0;return o.map((r,i)=>{if(r===void 0)return Math.max(s,Rf(e[i]));return r})}}function ua(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function Rf(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Pf(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function vf(e,t){e=e.trim();let n=Je.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function Lf(e,t){e=e.trim();let n=Je.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Je;function fa(e,t){return Je=t,new da({width:(e===null||e===void 0?void 0:e.width)||Pf(),wrap:e===null||e===void 0?void 0:e.wrap})}function qo({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 Bf=qo();function Wt(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(Bf,"")}var pa=161,ha=1114109,ga=[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],ma=12288,ya=65510,Da=[12288,12288,65281,65376,65504,65510];var wa=4352,ba=262141,Ho=[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 Ss=(e,t)=>{let n=0,o=Math.floor(e.length/2)-1;while(n<=o){let s=Math.floor((n+o)/2),r=s*2;if(t<e[r])o=s-1;else if(t>e[r+1])n=s+1;else return!0}return!1};var ka=19968,[Nf,Mf]=jf(Ho);function jf(e){let t=e[0],n=e[1];for(let o=0;o<e.length;o+=2){let s=e[o],r=e[o+1];if(ka>=s&&ka<=r)return[s,r];if(r-s>n-t)t=s,n=r}return[t,n]}var xa=(e)=>{if(e<pa||e>ha)return!1;return Ss(ga,e)},Ea=(e)=>{if(e<ma||e>ya)return!1;return Ss(Da,e)};var Sa=(e)=>{if(e>=Nf&&e<=Mf)return!0;if(e<wa||e>ba)return!1;return Ss(Ho,e)};function Wf(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function Ca(e,{ambiguousAsWide:t=!1}={}){if(Wf(e),Ea(e)||Sa(e)||t&&xa(e))return 2;return 1}var Fa=ca($a(),1),Uf=new Intl.Segmenter,Jf=/^\p{Default_Ignorable_Code_Point}$/u;function ot(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(!o)e=Wt(e);if(e.length===0)return 0;let s=0,r={ambiguousAsWide:!n};for(let{segment:i}of Uf.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(Jf.test(i))continue;if(Fa.default().test(i)){s+=2;continue}s+=Ca(a,r)}return s}var Aa=(e=0)=>(t)=>`\x1B[${t+e}m`,Ta=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,Ia=(e=0)=>(t,n,o)=>`\x1B[${38+e};2;${t};${n};${o}m`,he={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]}},Vy=Object.keys(he.modifier),Kf=Object.keys(he.color),qf=Object.keys(he.bgColor),Zy=[...Kf,...qf];function Hf(){let e=new Map;for(let[t,n]of Object.entries(he)){for(let[o,s]of Object.entries(n))he[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[o]=he[o],e.set(s[0],s[1]);Object.defineProperty(he,t,{value:n,enumerable:!1})}return Object.defineProperty(he,"codes",{value:e,enumerable:!1}),he.color.close="\x1B[39m",he.bgColor.close="\x1B[49m",he.color.ansi=Aa(),he.color.ansi256=Ta(),he.color.ansi16m=Ia(),he.bgColor.ansi=Aa(10),he.bgColor.ansi256=Ta(10),he.bgColor.ansi16m=Ia(10),Object.defineProperties(he,{rgbToAnsi256:{value(t,n,o){if(t===n&&n===o){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[o]=n;if(o.length===3)o=[...o].map((r)=>r+r).join("");let s=Number.parseInt(o,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:(t)=>he.rgbToAnsi256(...he.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,o,s;if(t>=232)n=((t-232)*10+8)/255,o=n,s=n;else{t-=16;let a=t%36;n=Math.floor(t/36)/5,o=Math.floor(a/6)/5,s=a%6/5}let r=Math.max(n,o,s)*2;if(r===0)return 30;let i=30+(Math.round(s)<<2|Math.round(o)<<1|Math.round(n));if(r===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,o)=>he.ansi256ToAnsi(he.rgbToAnsi256(t,n,o)),enumerable:!1},hexToAnsi:{value:(t)=>he.ansi256ToAnsi(he.hexToAnsi256(t)),enumerable:!1}}),he}var zf=Hf(),Oa=zf;var _s=new Set(["\x1B","›"]),Gf=39,Go="\x07",va="[",Yf="]",La="m",Cs=`${Yf}8;;`,Ra=(e)=>`${_s.values().next().value}${va}${e}${La}`,Pa=(e)=>`${_s.values().next().value}${Cs}${e}${Go}`,Xf=(e)=>e.split(" ").map((t)=>ot(t)),zo=(e,t,n)=>{let o=[...t],s=!1,r=!1,i=ot(Wt(e.at(-1)));for(let[a,c]of o.entries()){let l=ot(c);if(i+l<=n)e[e.length-1]+=c;else e.push(c),i=0;if(_s.has(c))s=!0,r=o.slice(a+1,a+1+Cs.length).join("")===Cs;if(s){if(r){if(c===Go)s=!1,r=!1}else if(c===La)s=!1;continue}if(i+=l,i===n&&a<o.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},Vf=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(ot(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},Zf=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let o="",s,r,i=Xf(e),a=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)a[a.length-1]=a.at(-1).trimStart();let h=ot(a.at(-1));if(d!==0){if(h>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),h=0;if(h>0||n.trim===!1)a[a.length-1]+=" ",h++}if(n.hard&&i[d]>t){let g=t-h,p=1+Math.floor((i[d]-g-1)/t);if(Math.floor((i[d]-1)/t)<p)a.push("");zo(a,f,t);continue}if(h+i[d]>t&&h>0&&i[d]>0){if(n.wordWrap===!1&&h<t){zo(a,f,t);continue}a.push("")}if(h+i[d]>t&&n.wordWrap===!1){zo(a,f,t);continue}a[a.length-1]+=f}if(n.trim!==!1)a=a.map((d)=>Vf(d));let c=a.join(`
8
- `),l=[...c],u=0;for(let[d,f]of l.entries()){if(o+=f,_s.has(f)){let{groups:g}=new RegExp(`(?:\\${va}(?<code>\\d+)m|\\${Cs}(?<uri>.*)${Go})`).exec(c.slice(u))||{groups:{}};if(g.code!==void 0){let p=Number.parseFloat(g.code);s=p===Gf?void 0:p}else if(g.uri!==void 0)r=g.uri.length===0?void 0:g.uri}let h=Oa.codes.get(Number(s));if(l[d+1]===`
9
- `){if(r)o+=Pa("");if(s&&h)o+=Ra(h)}else if(f===`
10
- `){if(s&&h)o+=Ra(s);if(r)o+=Pa(r)}u+=f.length}return o};function Yo(e,t,n){return String(e).normalize().replaceAll(`\r
7
+ `);if(s.border)o.unshift("."+"-".repeat(this.negatePadding(s)+2)+"."),o.push("'"+"-".repeat(this.negatePadding(s)+2)+"'");if(s.padding)o.unshift(...Array(s.padding[0]||0).fill("")),o.push(...Array(s.padding[2]||0).fill(""));o.forEach((i,a)=>{if(!t[a])t.push([]);let c=t[a];for(let l=0;l<r;l++)if(c[l]===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((r)=>r.width||Me.stringWidth(r.text));let t=e.length,n=this.width,o=e.map((r)=>{if(r.width)return t--,n-=r.width,r.width;return}),s=t?Math.floor(n/t):0;return o.map((r,i)=>{if(r===void 0)return Math.max(s,qf(e[i]));return r})}}function ga(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function qf(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Hf(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function zf(e,t){e=e.trim();let n=Me.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function Gf(e,t){e=e.trim();let n=Me.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Me;function ya(e,t){return Me=t,new ma({width:(e===null||e===void 0?void 0:e.width)||Hf(),wrap:e===null||e===void 0?void 0:e.wrap})}function Yo({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 Yf=Yo();function Ut(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(Yf,"")}var wa=161,Da=1114109,ba=[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],ka=12288,xa=65510,Ea=[12288,12288,65281,65376,65504,65510];var Sa=4352,Ca=262141,Xo=[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 _s=(e,t)=>{let n=0,o=Math.floor(e.length/2)-1;while(n<=o){let s=Math.floor((n+o)/2),r=s*2;if(t<e[r])o=s-1;else if(t>e[r+1])n=s+1;else return!0}return!1};var _a=19968,[Xf,Vf]=Zf(Xo);function Zf(e){let t=e[0],n=e[1];for(let o=0;o<e.length;o+=2){let s=e[o],r=e[o+1];if(_a>=s&&_a<=r)return[s,r];if(r-s>n-t)t=s,n=r}return[t,n]}var $a=(e)=>{if(e<wa||e>Da)return!1;return _s(ba,e)},Fa=(e)=>{if(e<ka||e>xa)return!1;return _s(Ea,e)};var Aa=(e)=>{if(e>=Xf&&e<=Vf)return!0;if(e<Sa||e>Ca)return!1;return _s(Xo,e)};function Qf(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function Ta(e,{ambiguousAsWide:t=!1}={}){if(Qf(e),Fa(e)||Aa(e)||t&&$a(e))return 2;return 1}var Ra=pa(Oa(),1),ep=new Intl.Segmenter,tp=/^\p{Default_Ignorable_Code_Point}$/u;function tt(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(!o)e=Ut(e);if(e.length===0)return 0;let s=0,r={ambiguousAsWide:!n};for(let{segment:i}of ep.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(tp.test(i))continue;if(Ra.default().test(i)){s+=2;continue}s+=Ta(a,r)}return s}var Pa=(e=0)=>(t)=>`\x1B[${t+e}m`,va=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,Ba=(e=0)=>(t,n,o)=>`\x1B[${38+e};2;${t};${n};${o}m`,le={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]}},uw=Object.keys(le.modifier),np=Object.keys(le.color),sp=Object.keys(le.bgColor),dw=[...np,...sp];function op(){let e=new Map;for(let[t,n]of Object.entries(le)){for(let[o,s]of Object.entries(n))le[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[o]=le[o],e.set(s[0],s[1]);Object.defineProperty(le,t,{value:n,enumerable:!1})}return Object.defineProperty(le,"codes",{value:e,enumerable:!1}),le.color.close="\x1B[39m",le.bgColor.close="\x1B[49m",le.color.ansi=Pa(),le.color.ansi256=va(),le.color.ansi16m=Ba(),le.bgColor.ansi=Pa(10),le.bgColor.ansi256=va(10),le.bgColor.ansi16m=Ba(10),Object.defineProperties(le,{rgbToAnsi256:{value(t,n,o){if(t===n&&n===o){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[o]=n;if(o.length===3)o=[...o].map((r)=>r+r).join("");let s=Number.parseInt(o,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:(t)=>le.rgbToAnsi256(...le.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,o,s;if(t>=232)n=((t-232)*10+8)/255,o=n,s=n;else{t-=16;let a=t%36;n=Math.floor(t/36)/5,o=Math.floor(a/6)/5,s=a%6/5}let r=Math.max(n,o,s)*2;if(r===0)return 30;let i=30+(Math.round(s)<<2|Math.round(o)<<1|Math.round(n));if(r===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,o)=>le.ansi256ToAnsi(le.rgbToAnsi256(t,n,o)),enumerable:!1},hexToAnsi:{value:(t)=>le.ansi256ToAnsi(le.hexToAnsi256(t)),enumerable:!1}}),le}var rp=op(),La=rp;var Fs=new Set(["\x1B","›"]),ip=39,Zo="\x07",ja="[",ap="]",Wa="m",$s=`${ap}8;;`,Na=(e)=>`${Fs.values().next().value}${ja}${e}${Wa}`,Ma=(e)=>`${Fs.values().next().value}${$s}${e}${Zo}`,cp=(e)=>e.split(" ").map((t)=>tt(t)),Vo=(e,t,n)=>{let o=[...t],s=!1,r=!1,i=tt(Ut(e.at(-1)));for(let[a,c]of o.entries()){let l=tt(c);if(i+l<=n)e[e.length-1]+=c;else e.push(c),i=0;if(Fs.has(c))s=!0,r=o.slice(a+1,a+1+$s.length).join("")===$s;if(s){if(r){if(c===Zo)s=!1,r=!1}else if(c===Wa)s=!1;continue}if(i+=l,i===n&&a<o.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},lp=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(tt(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},up=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let o="",s,r,i=cp(e),a=[""];for(let[d,p]of e.split(" ").entries()){if(n.trim!==!1)a[a.length-1]=a.at(-1).trimStart();let h=tt(a.at(-1));if(d!==0){if(h>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),h=0;if(h>0||n.trim===!1)a[a.length-1]+=" ",h++}if(n.hard&&i[d]>t){let y=t-h,f=1+Math.floor((i[d]-y-1)/t);if(Math.floor((i[d]-1)/t)<f)a.push("");Vo(a,p,t);continue}if(h+i[d]>t&&h>0&&i[d]>0){if(n.wordWrap===!1&&h<t){Vo(a,p,t);continue}a.push("")}if(h+i[d]>t&&n.wordWrap===!1){Vo(a,p,t);continue}a[a.length-1]+=p}if(n.trim!==!1)a=a.map((d)=>lp(d));let c=a.join(`
8
+ `),l=[...c],u=0;for(let[d,p]of l.entries()){if(o+=p,Fs.has(p)){let{groups:y}=new RegExp(`(?:\\${ja}(?<code>\\d+)m|\\${$s}(?<uri>.*)${Zo})`).exec(c.slice(u))||{groups:{}};if(y.code!==void 0){let f=Number.parseFloat(y.code);s=f===ip?void 0:f}else if(y.uri!==void 0)r=y.uri.length===0?void 0:y.uri}let h=La.codes.get(Number(s));if(l[d+1]===`
9
+ `){if(r)o+=Ma("");if(s&&h)o+=Na(h)}else if(p===`
10
+ `){if(s&&h)o+=Na(s);if(r)o+=Ma(r)}u+=p.length}return o};function Qo(e,t,n){return String(e).normalize().replaceAll(`\r
11
11
  `,`
12
12
  `).split(`
13
- `).map((o)=>Zf(o,t,n)).join(`
14
- `)}function Xo(e){return fa(e,{stringWidth:ot,stripAnsi:Wt,wrap:Yo})}import{dirname as Ba,resolve as Na}from"path";import{readdirSync as Qf,statSync as ep}from"fs";function Vo(e,t){let n=Na(".",e),o;if(!ep(n).isDirectory())n=Ba(n);while(!0){if(o=t(n,Qf(n)),o)return Na(n,o);if(n=Ba(o=n),o===n)break}}import{inspect as Dp}from"util";import{fileURLToPath as tc}from"url";import{format as sp}from"util";import{normalize as op,resolve as rp}from"path";function Ut(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",o=!1,s=e.match(/^-+/);for(let r=s?s[0].length:0;r<e.length;r++){let i=e.charAt(r);if(o)o=!1,i=i.toUpperCase();if(r!==0&&(i==="-"||i==="_"))o=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function $s(e,t){let n=e.toLowerCase();t=t||"-";let o="";for(let s=0;s<e.length;s++){let r=n.charAt(s),i=e.charAt(s);if(r!==i&&s>0)o+=`${t}${n.charAt(s)}`;else o+=i}return o}function Fs(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 Ma(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,o=null,s=null,r=[];for(let i=0;i<e.length;i++){if(n=o,o=e.charAt(i),o===" "&&!s){if(n!==" ")t++;continue}if(o===s)s=null;else if((o==="'"||o==='"')&&!s)s=o;if(!r[t])r[t]="";r[t]+=o}return r}var Xe;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(Xe||(Xe={}));var ft;class Qo{constructor(e){ft=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),o=Ma(e),s=typeof e==="string",r=tp(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||[],l=n.envPrefix,u=i["populate--"],d=u?"--":"_",f=Object.create(null),h=Object.create(null),g=n.__||ft.format,p={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},m=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,D=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(b){let S=typeof b==="object"?b.key:b,R=Object.keys(b).map(function(F){return{boolean:"bools",string:"strings",number:"numbers"}[F]}).filter(Boolean).pop();if(R)p[R][S]=!0;p.arrays[S]=!0,p.keys.push(S)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(b){p.bools[b]=!0,p.keys.push(b)}),[].concat(n.string||[]).filter(Boolean).forEach(function(b){p.strings[b]=!0,p.keys.push(b)}),[].concat(n.number||[]).filter(Boolean).forEach(function(b){p.numbers[b]=!0,p.keys.push(b)}),[].concat(n.count||[]).filter(Boolean).forEach(function(b){p.counts[b]=!0,p.keys.push(b)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(b){p.normalize[b]=!0,p.keys.push(b)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([b,S])=>{if(typeof S==="number")p.nargs[b]=S,p.keys.push(b)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([b,S])=>{if(typeof S==="function")p.coercions[b]=S,p.keys.push(b)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(b){p.configs[b]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([b,S])=>{if(typeof S==="boolean"||typeof S==="function")p.configs[b]=S})}ie(n.key,r,n.default,p.arrays),Object.keys(a).forEach(function(b){(p.aliases[b]||[]).forEach(function(S){a[S]=a[b]})});let w=null;Ko();let k=[],x=Object.assign(Object.create(null),{_:[]}),C={};for(let b=0;b<o.length;b++){let S=o[b],R=S.replace(/^-{3,}/,"---"),F,E,G,j,V,Ce;if(S!=="--"&&/^-/.test(S)&&Q(S))I(S);else if(R.match(/^---+(=|$)/)){I(S);continue}else if(S.match(/^--.+=/)||!i["short-option-groups"]&&S.match(/^-.+=/)){if(j=S.match(/^--?([^=]+)=([\s\S]*)$/),j!==null&&Array.isArray(j)&&j.length>=3)if(B(j[1],p.arrays))b=M(b,j[1],o,j[2]);else if(B(j[1],p.nargs)!==!1)b=A(b,j[1],o,j[2]);else X(j[1],j[2],!0)}else if(S.match(D)&&i["boolean-negation"]){if(j=S.match(D),j!==null&&Array.isArray(j)&&j.length>=2)E=j[1],X(E,B(E,p.arrays)?[!1]:!1)}else if(S.match(/^--.+/)||!i["short-option-groups"]&&S.match(/^-[^-]+/)){if(j=S.match(/^--?(.+)/),j!==null&&Array.isArray(j)&&j.length>=2)if(E=j[1],B(E,p.arrays))b=M(b,E,o);else if(B(E,p.nargs)!==!1)b=A(b,E,o);else if(V=o[b+1],V!==void 0&&(!V.match(/^-/)||V.match(m))&&!B(E,p.bools)&&!B(E,p.counts))X(E,V),b++;else if(/^(true|false)$/.test(V))X(E,V),b++;else X(E,ne(E))}else if(S.match(/^-.\..+=/)){if(j=S.match(/^-([^=]+)=([\s\S]*)$/),j!==null&&Array.isArray(j)&&j.length>=3)X(j[1],j[2])}else if(S.match(/^-.\..+/)&&!S.match(m)){if(V=o[b+1],j=S.match(/^-(.\..+)/),j!==null&&Array.isArray(j)&&j.length>=2)if(E=j[1],V!==void 0&&!V.match(/^-/)&&!B(E,p.bools)&&!B(E,p.counts))X(E,V),b++;else X(E,ne(E))}else if(S.match(/^-[^-]+/)&&!S.match(m)){G=S.slice(1,-1).split(""),F=!1;for(let Pe=0;Pe<G.length;Pe++){if(V=S.slice(Pe+2),G[Pe+1]&&G[Pe+1]==="="){if(Ce=S.slice(Pe+3),E=G[Pe],B(E,p.arrays))b=M(b,E,o,Ce);else if(B(E,p.nargs)!==!1)b=A(b,E,o,Ce);else X(E,Ce);F=!0;break}if(V==="-"){X(G[Pe],V);continue}if(/[A-Za-z]/.test(G[Pe])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(V)&&B(V,p.bools)===!1){X(G[Pe],V),F=!0;break}if(G[Pe+1]&&G[Pe+1].match(/\W/)){X(G[Pe],V),F=!0;break}else X(G[Pe],ne(G[Pe]))}if(E=S.slice(-1)[0],!F&&E!=="-")if(B(E,p.arrays))b=M(b,E,o);else if(B(E,p.nargs)!==!1)b=A(b,E,o);else if(V=o[b+1],V!==void 0&&(!/^(-|--)[^-]/.test(V)||V.match(m))&&!B(E,p.bools)&&!B(E,p.counts))X(E,V),b++;else if(/^(true|false)$/.test(V))X(E,V),b++;else X(E,ne(E))}else if(S.match(/^-[0-9]$/)&&S.match(m)&&B(S.slice(1),p.bools))E=S.slice(1),X(E,ne(E));else if(S==="--"){k=o.slice(b+1);break}else if(i["halt-at-non-option"]){k=o.slice(b);break}else I(S)}if(le(x,!0),le(x,!1),P(x),te(),z(x,p.aliases,a,!0),se(x),i["set-placeholder-key"])U(x);if(Object.keys(p.counts).forEach(function(b){if(!N(x,b.split(".")))X(b,0)}),u&&k.length)x[d]=[];if(k.forEach(function(b){x[d].push(b)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(x).filter((b)=>b!=="--"&&b.includes("-")).forEach((b)=>{delete x[b]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((b)=>r[b])).forEach((b)=>{if(i["camel-case-expansion"]&&b.includes("-"))delete x[b.split(".").map((S)=>Ut(S)).join(".")];delete x[b]});function I(b){let S=T("_",b);if(typeof S==="string"||typeof S==="number")x._.push(S)}function A(b,S,R,F){let E,G=B(S,p.nargs);if(G=typeof G!=="number"||isNaN(G)?1:G,G===0){if(!Ee(F))w=Error(g("Argument unexpected for: %s",S));return X(S,ne(S)),b}let j=Ee(F)?0:1;if(i["nargs-eats-options"]){if(R.length-(b+1)+j<G)w=Error(g("Not enough arguments following: %s",S));j=G}else{for(E=b+1;E<R.length;E++)if(!R[E].match(/^-[^0-9]/)||R[E].match(m)||Q(R[E]))j++;else break;if(j<G)w=Error(g("Not enough arguments following: %s",S))}let V=Math.min(j,G);if(!Ee(F)&&V>0)X(S,F),V--;for(E=b+1;E<V+b+1;E++)X(S,R[E]);return b+V}function M(b,S,R,F){let E=[],G=F||R[b+1],j=B(S,p.nargs);if(B(S,p.bools)&&!/^(true|false)$/.test(G))E.push(!0);else if(Ee(G)||Ee(F)&&/^-/.test(G)&&!m.test(G)&&!Q(G)){if(a[S]!==void 0){let V=a[S];E=Array.isArray(V)?V:[V]}}else{if(!Ee(F))E.push(L(S,F,!0));for(let V=b+1;V<R.length;V++){if(!i["greedy-arrays"]&&E.length>0||j&&typeof j==="number"&&E.length>=j)break;if(G=R[V],/^-/.test(G)&&!m.test(G)&&!Q(G))break;b=V,E.push(L(S,G,s))}}if(typeof j==="number"&&(j&&E.length<j||isNaN(j)&&E.length===0))w=Error(g("Not enough arguments following: %s",S));return X(S,E),b}function X(b,S,R=s){if(/-/.test(b)&&i["camel-case-expansion"]){let G=b.split(".").map(function(j){return Ut(j)}).join(".");re(b,G)}let F=L(b,S,R),E=b.split(".");if(q(x,E,F),p.aliases[b])p.aliases[b].forEach(function(G){let j=G.split(".");q(x,j,F)});if(E.length>1&&i["dot-notation"])(p.aliases[E[0]]||[]).forEach(function(G){let j=G.split("."),V=[].concat(E);if(V.shift(),j=j.concat(V),!(p.aliases[b]||[]).includes(j.join(".")))q(x,j,F)});if(B(b,p.normalize)&&!B(b,p.arrays))[b].concat(p.aliases[b]||[]).forEach(function(j){Object.defineProperty(C,j,{enumerable:!0,get(){return S},set(V){S=typeof V==="string"?ft.normalize(V):V}})})}function re(b,S){if(!(p.aliases[b]&&p.aliases[b].length))p.aliases[b]=[S],f[S]=!0;if(!(p.aliases[S]&&p.aliases[S].length))re(S,b)}function L(b,S,R){if(R)S=np(S);if(B(b,p.bools)||B(b,p.counts)){if(typeof S==="string")S=S==="true"}let F=Array.isArray(S)?S.map(function(E){return T(b,E)}):T(b,S);if(B(b,p.counts)&&(Ee(F)||typeof F==="boolean"))F=Zo();if(B(b,p.normalize)&&B(b,p.arrays))if(Array.isArray(S))F=S.map((E)=>ft.normalize(E));else F=ft.normalize(S);return F}function T(b,S){if(!i["parse-positional-numbers"]&&b==="_")return S;if(!B(b,p.strings)&&!B(b,p.bools)&&!Array.isArray(S)){if(Fs(S)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${S}`)))||!Ee(S)&&B(b,p.numbers))S=Number(S)}return S}function P(b){let S=Object.create(null);z(S,p.aliases,a),Object.keys(p.configs).forEach(function(R){let F=b[R]||S[R];if(F)try{let E=null,G=ft.resolve(ft.cwd(),F),j=p.configs[R];if(typeof j==="function"){try{E=j(G)}catch(V){E=V}if(E instanceof Error){w=E;return}}else E=ft.require(G);W(E)}catch(E){if(E.name==="PermissionDenied")w=E;else if(b[R])w=Error(g("Invalid JSON config file: %s",F))}})}function W(b,S){Object.keys(b).forEach(function(R){let F=b[R],E=S?S+"."+R:R;if(typeof F==="object"&&F!==null&&!Array.isArray(F)&&i["dot-notation"])W(F,E);else if(!N(x,E.split("."))||B(E,p.arrays)&&i["combine-arrays"])X(E,F)})}function te(){if(typeof c<"u")c.forEach(function(b){W(b)})}function le(b,S){if(typeof l>"u")return;let R=typeof l==="string"?l:"",F=ft.env();Object.keys(F).forEach(function(E){if(R===""||E.lastIndexOf(R,0)===0){let G=E.split("__").map(function(j,V){if(V===0)j=j.substring(R.length);return Ut(j)});if((S&&p.configs[G.join(".")]||!S)&&!N(b,G))X(G.join("."),F[E])}})}function se(b){let S,R=new Set;Object.keys(b).forEach(function(F){if(!R.has(F)){if(S=B(F,p.coercions),typeof S==="function")try{let E=T(F,S(b[F]));[].concat(p.aliases[F]||[],F).forEach((G)=>{R.add(G),b[G]=E})}catch(E){w=E}}})}function U(b){return p.keys.forEach((S)=>{if(~S.indexOf("."))return;if(typeof b[S]>"u")b[S]=void 0}),b}function z(b,S,R,F=!1){Object.keys(R).forEach(function(E){if(!N(b,E.split("."))){if(q(b,E.split("."),R[E]),F)h[E]=!0;(S[E]||[]).forEach(function(G){if(N(b,G.split(".")))return;q(b,G.split("."),R[E])})}})}function N(b,S){let R=b;if(!i["dot-notation"])S=[S.join(".")];S.slice(0,-1).forEach(function(E){R=R[E]||{}});let F=S[S.length-1];if(typeof R!=="object")return!1;else return F in R}function q(b,S,R){let F=b;if(!i["dot-notation"])S=[S.join(".")];S.slice(0,-1).forEach(function(Ce){if(Ce=ja(Ce),typeof F==="object"&&F[Ce]===void 0)F[Ce]={};if(typeof F[Ce]!=="object"||Array.isArray(F[Ce])){if(Array.isArray(F[Ce]))F[Ce].push({});else F[Ce]=[F[Ce],{}];F=F[Ce][F[Ce].length-1]}else F=F[Ce]});let E=ja(S[S.length-1]),G=B(S.join("."),p.arrays),j=Array.isArray(R),V=i["duplicate-arguments-array"];if(!V&&B(E,p.nargs)){if(V=!0,!Ee(F[E])&&p.nargs[E]===1||Array.isArray(F[E])&&F[E].length===p.nargs[E])F[E]=void 0}if(R===Zo())F[E]=Zo(F[E]);else if(Array.isArray(F[E]))if(V&&G&&j)F[E]=i["flatten-duplicate-arrays"]?F[E].concat(R):(Array.isArray(F[E][0])?F[E]:[F[E]]).concat([R]);else if(!V&&Boolean(G)===Boolean(j))F[E]=R;else F[E]=F[E].concat([R]);else if(F[E]===void 0&&G)F[E]=j?R:[R];else if(V&&!(F[E]===void 0||B(E,p.counts)||B(E,p.bools)))F[E]=[F[E],R];else F[E]=R}function ie(...b){b.forEach(function(S){Object.keys(S||{}).forEach(function(R){if(p.aliases[R])return;p.aliases[R]=[].concat(r[R]||[]),p.aliases[R].concat(R).forEach(function(F){if(/-/.test(F)&&i["camel-case-expansion"]){let E=Ut(F);if(E!==R&&p.aliases[R].indexOf(E)===-1)p.aliases[R].push(E),f[E]=!0}}),p.aliases[R].concat(R).forEach(function(F){if(F.length>1&&/[A-Z]/.test(F)&&i["camel-case-expansion"]){let E=$s(F,"-");if(E!==R&&p.aliases[R].indexOf(E)===-1)p.aliases[R].push(E),f[E]=!0}}),p.aliases[R].forEach(function(F){p.aliases[F]=[R].concat(p.aliases[R].filter(function(E){return F!==E}))})})})}function B(b,S){let R=[].concat(p.aliases[b]||[],b),F=Object.keys(S),E=R.find((G)=>F.includes(G));return E?S[E]:!1}function ae(b){let S=Object.keys(p);return[].concat(S.map((F)=>p[F])).some(function(F){return Array.isArray(F)?F.includes(b):F[b]})}function st(b,...S){return[].concat(...S).some(function(F){let E=b.match(F);return E&&ae(E[1])})}function O(b){if(b.match(m)||!b.match(/^-[^-]+/))return!1;let S=!0,R,F=b.slice(1).split("");for(let E=0;E<F.length;E++){if(R=b.slice(E+2),!ae(F[E])){S=!1;break}if(F[E+1]&&F[E+1]==="="||R==="-"||/[A-Za-z]/.test(F[E])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(R)||F[E+1]&&F[E+1].match(/\W/))break}return S}function Q(b){return i["unknown-options-as-args"]&&ue(b)}function ue(b){if(b=b.replace(/^-{3,}/,"--"),b.match(m))return!1;if(O(b))return!1;return!st(b,/^-+([^=]+?)=[\s\S]*$/,D,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function ne(b){if(!B(b,p.bools)&&!B(b,p.counts)&&`${b}`in a)return a[b];else return Fe(be(b))}function Fe(b){return{[Xe.BOOLEAN]:!0,[Xe.STRING]:"",[Xe.NUMBER]:void 0,[Xe.ARRAY]:[]}[b]}function be(b){let S=Xe.BOOLEAN;if(B(b,p.strings))S=Xe.STRING;else if(B(b,p.numbers))S=Xe.NUMBER;else if(B(b,p.bools))S=Xe.BOOLEAN;else if(B(b,p.arrays))S=Xe.ARRAY;return S}function Ee(b){return b===void 0}function Ko(){Object.keys(p.counts).find((b)=>{if(B(b,p.arrays))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",b)),!0;else if(B(b,p.nargs))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",b)),!0;return!1})}return{aliases:Object.assign({},p.aliases),argv:Object.assign(C,x),configuration:i,defaulted:Object.assign({},h),error:w,newAliases:Object.assign({},f)}}}function tp(e){let t=[],n=Object.create(null),o=!0;Object.keys(e).forEach(function(s){t.push([].concat(e[s],s))});while(o){o=!1;for(let s=0;s<t.length;s++)for(let r=s+1;r<t.length;r++)if(t[s].filter(function(a){return t[r].indexOf(a)!==-1}).length){t[s]=t[s].concat(t[r]),t.splice(r,1),o=!0;break}}return t.forEach(function(s){s=s.filter(function(i,a,c){return c.indexOf(i)===a});let r=s.pop();if(r!==void 0&&typeof r==="string")n[r]=s}),n}function Zo(e){return e!==void 0?e+1:1}function ja(e){if(e==="__proto__")return"___proto___";return e}function np(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 ip}from"fs";import{createRequire as Wa}from"node:module";var er,tr,nr,Ua=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Ja=(tr=(er=process===null||process===void 0?void 0:process.versions)===null||er===void 0?void 0:er.node)!==null&&tr!==void 0?tr:(nr=process===null||process===void 0?void 0:process.version)===null||nr===void 0?void 0:nr.slice(1);if(Ja){if(Number(Ja.match(/^([^.]+)/)[1])<Ua)throw Error(`yargs parser supports a minimum Node.js version of ${Ua}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var ap=process?process.env:{},Ka=Wa?Wa(import.meta.url):void 0,qa=new Qo({cwd:process.cwd,env:()=>ap,format:sp,normalize:op,resolve:rp,require:(e)=>{if(typeof Ka<"u")return Ka(e);else if(e.match(/\.json$/))return JSON.parse(ip(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),Bn=function(t,n){return qa.parse(t.slice(),n).argv};Bn.detailed=function(e,t){return qa.parse(e.slice(),t)};Bn.camelCase=Ut;Bn.decamelize=$s;Bn.looksLikeNumber=Fs;var sr=Bn;import{basename as wp,dirname as bp,extname as kp,relative as xp,resolve as ec,join as Ep}from"path";function Ha(){if(cp())return 0;return 1}function cp(){return lp()&&!process.defaultApp}function lp(){return!!process.versions.electron}function or(e){return e.slice(Ha()+1)}function za(){return process.argv[Ha()]}import{readFileSync as up,statSync as dp,writeFile as fp}from"fs";import{format as pp}from"util";import{resolve as hp}from"path";var Ga={fs:{readFileSync:up,writeFile:fp},format:pp,resolve:hp,exists:(e)=>{try{return dp(e).isFile()}catch(t){return!1}}};var rt;class Ya{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 rt.format.apply(rt.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),o=e.shift(),s=function(){};if(typeof e[e.length-1]==="function")s=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let r=o===1?t:n;if(this.cache[this.locale][t])r=this.cache[this.locale][t][o===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:s});else s();let i=[r];if(~r.indexOf("%d"))i.push(o);return rt.format.apply(rt.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(o,s){let r=t[s+1];if(n+=o,typeof r<"u")n+="%s"}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){if(this.writeQueue.push(e),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],{directory:n,locale:o,cb:s}=t,r=this._resolveLocaleFile(n,o),i=JSON.stringify(this.cache[o],null,2);rt.fs.writeFile(r,i,"utf-8",function(a){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();s(a)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(rt.fs.readFileSync)e=JSON.parse(rt.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=rt.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let o=rt.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(o))n=o}return n}_fileExistsSync(e){return rt.exists(e)}}function Xa(e,t){rt=t;let n=new Ya(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 gp=(e)=>Xa(e,Ga),Va=gp;var nc=ca(Qa(),1);import{createRequire as Sp}from"node:module";import{readFileSync as Cp,readdirSync as _p}from"node:fs";var rr=tc(import.meta.url),$p=rr.substring(0,rr.lastIndexOf("node_modules")),Fp=Sp(import.meta.url),ir={assert:{notStrictEqual:mp,strictEqual:yp},cliui:Xo,findUp:Vo,getEnv:(e)=>process.env[e],inspect:Dp,getProcessArgvBin:za,mainFilename:$p||process.cwd(),Parser:sr,path:{basename:wp,dirname:bp,extname:kp,relative:xp,resolve:ec,join:Ep},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:Cp,readdirSync:_p,require:Fp,getCallerFile:()=>{let e=nc.default(3);return e.match(/^file:\/\//)?tc(e):e},stringWidth:ot,y18n:Va({directory:ec(rr,"../../../locales"),updateFiles:!1})};function ve(e,t,n,o){n.assert.notStrictEqual(e,t,o)}function ar(e,t){t.assert.strictEqual(typeof e,"string")}function hn(e){return Object.keys(e)}function pe(e){return!!e&&!!e.then&&typeof e.then==="function"}class ke extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,ke)}}function kt(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),o=/\.*[\][<>]/g,s=n.shift();if(!s)throw Error(`No command found in: ${e}`);let r={cmd:s.replace(o,""),demanded:[],optional:[]};return n.forEach((i,a)=>{let c=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&a===n.length-1)c=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(o,"").split("|"),variadic:c});else r.demanded.push({cmd:i.replace(o,"").split("|"),variadic:c})}),r}var Ap=["first","second","third","fourth","fifth","sixth"];function J(e,t,n){function o(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[kt(`cmd ${e}`),t,n]}try{let s=0,[r,i,a]=o(),c=[].slice.call(i);while(c.length&&c[c.length-1]===void 0)c.pop();let l=a||c.length;if(l<r.demanded.length)throw new ke(`Not enough arguments provided. Expected ${r.demanded.length} but received ${c.length}.`);let u=r.demanded.length+r.optional.length;if(l>u)throw new ke(`Too many arguments provided. Expected max ${u} but received ${l}.`);r.demanded.forEach((d)=>{let f=c.shift(),h=sc(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)oc(h,d.cmd,s);s+=1}),r.optional.forEach((d)=>{if(c.length===0)return;let f=c.shift(),h=sc(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)oc(h,d.cmd,s);s+=1})}catch(s){console.warn(s.stack)}}function sc(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function oc(e,t,n){throw new ke(`Invalid ${Ap[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class cr{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,o=!1){if(J("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let s=0;s<e.length;s++){if(typeof e[s]!=="function")throw Error("middleware must be a function");let r=e[s];r.applyBeforeValidation=t,r.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let s=e;s.applyBeforeValidation=t,s.global=n,s.mutates=o,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((o)=>{let s=[...n[t]||[],t];if(!o.option)return!0;else return!s.includes(o.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function rc(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function Jt(e,t,n,o){return n.reduce((s,r)=>{if(r.applyBeforeValidation!==o)return s;if(r.mutates){if(r.applied)return s;r.applied=!0}if(pe(s))return s.then((i)=>Promise.all([i,r(i,t)])).then(([i,a])=>Object.assign(i,a));else{let i=r(s,t);return pe(i)?i.then((a)=>Object.assign(s,a)):Object.assign(s,i)}},e)}function Kt(e,t,n=(o)=>{throw o}){try{let o=Tp(e)?e():e;return pe(o)?o.then((s)=>t(s)):t(o)}catch(o){return n(o)}}function Tp(e){return typeof e==="function"}var gn=/(^\*)|(^\$0)/;class ac{constructor(e,t,n,o){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=o,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,o){o=o||{},this.requireCache.add(n);let s=this.shim.path.resolve(this.shim.path.dirname(n),e),r=this.shim.readdirSync(s,{recursive:o.recurse?!0:!1});if(!Array.isArray(o.extensions))o.extensions=["js"];let i=typeof o.visit==="function"?o.visit:(a)=>a;for(let a of r){let c=a.toString();if(o.exclude){let u=!1;if(typeof o.exclude==="function")u=o.exclude(c);else u=o.exclude.test(c);if(u)continue}if(o.include){let u=!1;if(typeof o.include==="function")u=o.include(c);else u=o.include.test(c);if(!u)continue}let l=!1;for(let u of o.extensions)if(c.endsWith(u))l=!0;if(l){let u=this.shim.path.join(s,c),d=t(u),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,u,c)){if(this.requireCache.has(u))continue;else this.requireCache.add(u);if(!f.command)f.command=this.shim.path.basename(u,this.shim.path.extname(u));this.addHandler(f)}}}}addHandler(e,t,n,o,s,r){let i=[],a=rc(s);if(o=o||(()=>{}),Array.isArray(e))if(Ip(e))[e,...i]=e;else for(let c of e)this.addHandler(c);else if(Rp(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(ic(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let c=kt(e);i=i.map((d)=>kt(d).cmd);let l=!1,u=[c.cmd].concat(i).filter((d)=>{if(gn.test(d))return l=!0,!1;return!0});if(u.length===0&&l)u.push("$0");if(l)c.cmd=u[0],i=u.slice(1),e=e.replace(gn,c.cmd);if(i.forEach((d)=>{this.aliasMap[d]=c.cmd}),t!==!1)this.usage.command(e,t,l,i,r);if(this.handlers[c.cmd]={original:e,description:t,handler:o,builder:n||{},middlewares:a,deprecated:r,demanded:c.demanded,optional:c.optional},l)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,o,s,r){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,a=t.getInternalMethods().getContext(),c=a.commands.slice(),l=!e;if(e)a.commands.push(e),a.fullCommands.push(i.original);let u=this.applyBuilderUpdateUsageAndParse(l,i,t,n.aliases,c,o,s,r);return pe(u)?u.then((d)=>this.applyMiddlewareAndGetResult(l,i,d.innerArgv,a,s,d.aliases,t)):this.applyMiddlewareAndGetResult(l,i,u.innerArgv,a,s,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,o,s,r,i,a){let c=t.builder,l=n;if(As(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(o),a);if(pe(u))return u.then((d)=>(l=lc(d)?d:n,this.parseAndUpdateUsage(e,t,l,s,r,i)))}else if(Op(c))n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(o),Object.keys(t.builder).forEach((u)=>{l.option(u,c[u])});return this.parseAndUpdateUsage(e,t,l,s,r,i)}parseAndUpdateUsage(e,t,n,o,s,r){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(o,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,s,r);return pe(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=gn.test(t.original)?t.original.replace(gn,"").trim():t.original,o=e.filter((s)=>!gn.test(s));return o.push(n),`$0 ${o.join(" ")}`}handleValidationAndGetResult(e,t,n,o,s,r,i,a){if(!r.getInternalMethods().getHasOutput()){let c=r.getInternalMethods().runValidation(s,a,r.parsed.error,e);n=Kt(n,(l)=>(c(l),l))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let c=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,c,!1,!1),n=Jt(n,r,i,!1),n=Kt(n,(l)=>{let u=t.handler(l);return pe(u)?u.then(()=>l):l}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(pe(n)&&!r.getInternalMethods().hasParseCallback())n.catch((l)=>{try{r.getInternalMethods().getUsageInstance().fail(null,l)}catch(u){}})}if(!e)o.commands.pop(),o.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,o,s,r,i){let a={};if(s)return n;if(!i.getInternalMethods().getHasOutput())a=this.populatePositionals(t,n,o,i);let c=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=Jt(n,i,c,!0);return pe(l)?l.then((u)=>this.handleValidationAndGetResult(e,t,u,o,r,i,c,a)):this.handleValidationAndGetResult(e,t,l,o,r,i,c,a)}populatePositionals(e,t,n,o){t._=t._.slice(n.commands.length);let s=e.demanded.slice(0),r=e.optional.slice(0),i={};this.validation.positionalCount(s.length,t._.length);while(s.length){let a=s.shift();this.populatePositional(a,t,i)}while(r.length){let a=r.shift();this.populatePositional(a,t,i)}return t._=n.commands.concat(t._.map((a)=>""+a)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),o),i}populatePositional(e,t,n){let o=e.cmd[0];if(e.variadic)n[o]=t._.splice(0).map(String);else if(t._.length)n[o]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=kt(e);return n.demanded.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r,t.demand[s]=!0}),n.optional.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r}),t}postProcessPositionals(e,t,n,o){let s=Object.assign({},o.getOptions());s.default=Object.assign(n.default,s.default);for(let c of Object.keys(n.alias))s.alias[c]=(s.alias[c]||[]).concat(n.alias[c]);s.array=s.array.concat(n.array),s.config={};let r=[];if(Object.keys(t).forEach((c)=>{t[c].map((l)=>{if(s.configuration["unknown-options-as-args"])s.key[c]=!0;r.push(`--${c}`),r.push(l)})}),!r.length)return;let i=Object.assign({},s.configuration,{"populate--":!1}),a=this.shim.Parser.detailed(r,Object.assign({},s,{configuration:i}));if(a.error)o.getInternalMethods().getUsageInstance().fail(a.error.message,a.error);else{let c=Object.keys(t);Object.keys(t).forEach((l)=>{c.push(...a.aliases[l])}),Object.keys(a.argv).forEach((l)=>{if(c.includes(l)){if(!t[l])t[l]=a.argv[l];if(!this.isInConfigs(o,l)&&!this.isDefaulted(o,l)&&Object.prototype.hasOwnProperty.call(e,l)&&Object.prototype.hasOwnProperty.call(a.argv,l)&&(Array.isArray(e[l])||Array.isArray(a.argv[l])))e[l]=[].concat(e[l],a.argv[l]);else e[l]=a.argv[l]}})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some((o)=>Object.prototype.hasOwnProperty.call(o,t))||n.some((o)=>Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=gn.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(As(t))return t(e,!0);else if(!ic(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let o of[e,t,n]){if(typeof o==="string"||o===!1)return o;ve(o,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();ve(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 cc(e,t,n,o){return new ac(e,t,n,o)}function ic(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function Ip(e){return e.every((t)=>typeof t==="string")}function As(e){return typeof e==="function"}function Op(e){return typeof e==="object"}function Rp(e){return typeof e==="object"&&!Array.isArray(e)}function xt(e={},t=()=>!0){let n={};return hn(e).forEach((o)=>{if(t(o,e[o]))n[o]=e[o]}),n}function Et(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 Pp(e){return typeof e==="boolean"}function dc(e,t){let n=t.y18n.__,o={},s=[];o.failFn=function(T){s.push(T)};let r=null,i=null,a=!0;o.showHelpOnFail=function(T=!0,P){let[W,te]=typeof T==="string"?[!0,T]:[T,P];if(e.getInternalMethods().isGlobalContext())i=te;return r=te,a=W,o};let c=!1;o.fail=function(T,P){let W=e.getInternalMethods().getLoggerInstance();if(s.length)for(let te=s.length-1;te>=0;--te){let le=s[te];if(Pp(le)){if(P)throw P;else if(T)throw Error(T)}else le(T,P,o)}else{if(e.getExitProcess())Et(!0);if(!c){if(c=!0,a)e.showHelp("error"),W.error();if(T||P)W.error(T||P);let te=r||i;if(te){if(T||P)W.error("");W.error(te)}}if(P=P||new ke(T),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,P);else throw P}};let l=[],u=!1;o.usage=(L,T)=>{if(L===null)return u=!0,l=[],o;return u=!1,l.push([L,T||""]),o},o.getUsage=()=>l,o.getUsageDisabled=()=>u,o.getPositionalGroupName=()=>n("Positionals:");let d=[];o.example=(L,T)=>{d.push([L,T||""])};let f=[];o.command=function(T,P,W,te,le=!1){if(W)f=f.map((se)=>(se[2]=!1,se));f.push([T,P||"",W,te,le])},o.getCommands=()=>f;let h={};o.describe=function(T,P){if(Array.isArray(T))T.forEach((W)=>{o.describe(W,P)});else if(typeof T==="object")Object.keys(T).forEach((W)=>{o.describe(W,T[W])});else h[T]=P},o.getDescriptions=()=>h;let g=[];o.epilog=(L)=>{g.push(L)};let p=!1,m;o.wrap=(L)=>{p=!0,m=L},o.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!p)m=M(),p=!0;return m};let D="__yargsString__:";o.deferY18nLookup=(L)=>D+L,o.help=function(){if(x)return x;k();let T=e.customScriptName?e.$0:t.path.basename(e.$0),P=e.getDemandedOptions(),W=e.getDemandedCommands(),te=e.getDeprecatedOptions(),le=e.getGroups(),se=e.getOptions(),U=[];U=U.concat(Object.keys(h)),U=U.concat(Object.keys(P)),U=U.concat(Object.keys(W)),U=U.concat(Object.keys(se.default)),U=U.filter(I),U=Object.keys(U.reduce((O,Q)=>{if(Q!=="_")O[Q]=!0;return O},{}));let z=o.getWrap(),N=t.cliui({width:z,wrap:!!z});if(!u){if(l.length)l.forEach((O)=>{if(N.div({text:`${O[0].replace(/\$0/g,T)}`}),O[1])N.div({text:`${O[1]}`,padding:[1,0,0,0]})}),N.div();else if(f.length){let O=null;if(W._)O=`${T} <${n("command")}>
15
- `;else O=`${T} [${n("command")}]
16
- `;N.div(`${O}`)}}if(f.length>1||f.length===1&&!f[0][2]){N.div(n("Commands:"));let O=e.getInternalMethods().getContext(),Q=O.commands.length?`${O.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((ne,Fe)=>ne[0].localeCompare(Fe[0]));let ue=T?`${T} `:"";f.forEach((ne)=>{let Fe=`${ue}${Q}${ne[0].replace(/^\$0 ?/,"")}`;N.span({text:Fe,padding:[0,2,0,2],width:w(f,z,`${T}${Q}`)+4},{text:ne[1]});let be=[];if(ne[2])be.push(`[${n("default")}]`);if(ne[3]&&ne[3].length)be.push(`[${n("aliases:")} ${ne[3].join(", ")}]`);if(ne[4])if(typeof ne[4]==="string")be.push(`[${n("deprecated: %s",ne[4])}]`);else be.push(`[${n("deprecated")}]`);if(be.length)N.div({text:be.join(" "),padding:[0,0,0,2],align:"right"});else N.div()}),N.div()}let q=(Object.keys(se.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);U=U.filter((O)=>!e.parsed.newAliases[O]&&q.every((Q)=>(se.alias[Q]||[]).indexOf(O)===-1));let ie=n("Options:");if(!le[ie])le[ie]=[];C(U,se.alias,le,ie);let B=(O)=>/^--/.test(Ts(O)),ae=Object.keys(le).filter((O)=>le[O].length>0).map((O)=>{let Q=le[O].filter(I).map((ue)=>{if(q.includes(ue))return ue;for(let ne=0,Fe;(Fe=q[ne])!==void 0;ne++)if((se.alias[Fe]||[]).includes(ue))return Fe;return ue});return{groupName:O,normalizedKeys:Q}}).filter(({normalizedKeys:O})=>O.length>0).map(({groupName:O,normalizedKeys:Q})=>{let ue=Q.reduce((ne,Fe)=>(ne[Fe]=[Fe].concat(se.alias[Fe]||[]).map((be)=>{if(O===o.getPositionalGroupName())return be;else return(/^[0-9]$/.test(be)?se.boolean.includes(Fe)?"-":"--":be.length>1?"--":"-")+be}).sort((be,Ee)=>B(be)===B(Ee)?0:B(be)?1:-1).join(", "),ne),{});return{groupName:O,normalizedKeys:Q,switches:ue}});if(ae.filter(({groupName:O})=>O!==o.getPositionalGroupName()).some(({normalizedKeys:O,switches:Q})=>!O.every((ue)=>B(Q[ue]))))ae.filter(({groupName:O})=>O!==o.getPositionalGroupName()).forEach(({normalizedKeys:O,switches:Q})=>{O.forEach((ue)=>{if(B(Q[ue]))Q[ue]=vp(Q[ue],4)})});if(ae.forEach(({groupName:O,normalizedKeys:Q,switches:ue})=>{N.div(O),Q.forEach((ne)=>{let Fe=ue[ne],be=h[ne]||"",Ee=null;if(be.includes(D))be=n(be.substring(D.length));if(se.boolean.includes(ne))Ee=`[${n("boolean")}]`;if(se.count.includes(ne))Ee=`[${n("count")}]`;if(se.string.includes(ne))Ee=`[${n("string")}]`;if(se.normalize.includes(ne))Ee=`[${n("string")}]`;if(se.array.includes(ne))Ee=`[${n("array")}]`;if(se.number.includes(ne))Ee=`[${n("number")}]`;let Ko=(R)=>typeof R==="string"?`[${n("deprecated: %s",R)}]`:`[${n("deprecated")}]`,b=[ne in te?Ko(te[ne]):null,Ee,ne in P?`[${n("required")}]`:null,se.choices&&se.choices[ne]?`[${n("choices:")} ${o.stringifiedValues(se.choices[ne])}]`:null,A(se.default[ne],se.defaultDescription[ne])].filter(Boolean).join(" ");N.span({text:Ts(Fe),padding:[0,2,0,2+uc(Fe)],width:w(ue,z)+4},be);let S=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(b&&!S)N.div({text:b,padding:[0,0,0,2],align:"right"});else N.div()}),N.div()}),d.length)N.div(n("Examples:")),d.forEach((O)=>{O[0]=O[0].replace(/\$0/g,T)}),d.forEach((O)=>{if(O[1]==="")N.div({text:O[0],padding:[0,2,0,2]});else N.div({text:O[0],padding:[0,2,0,2],width:w(d,z)+4},{text:O[1]})}),N.div();if(g.length>0){let O=g.map((Q)=>Q.replace(/\$0/g,T)).join(`
17
- `);N.div(`${O}
18
- `)}return N.toString().replace(/\s*$/,"")};function w(L,T,P){let W=0;if(!Array.isArray(L))L=Object.values(L).map((te)=>[te]);if(L.forEach((te)=>{W=Math.max(t.stringWidth(P?`${P} ${Ts(te[0])}`:Ts(te[0]))+uc(te[0]),W)}),T)W=Math.min(W,parseInt((T*0.5).toString(),10));return W}function k(){let L=e.getDemandedOptions(),T=e.getOptions();(Object.keys(T.alias)||[]).forEach((P)=>{T.alias[P].forEach((W)=>{if(h[W])o.describe(P,h[W]);if(W in L)e.demandOption(P,L[W]);if(T.boolean.includes(W))e.boolean(P);if(T.count.includes(W))e.count(P);if(T.string.includes(W))e.string(P);if(T.normalize.includes(W))e.normalize(P);if(T.array.includes(W))e.array(P);if(T.number.includes(W))e.number(P)})})}let x;o.cacheHelpMessage=function(){x=this.help()},o.clearCachedHelpMessage=function(){x=void 0},o.hasCachedHelpMessage=function(){return!!x};function C(L,T,P,W){let te=[],le=null;return Object.keys(P).forEach((se)=>{te=te.concat(P[se])}),L.forEach((se)=>{if(le=[se].concat(T[se]),!le.some((U)=>te.indexOf(U)!==-1))P[W].push(se)}),te}function I(L){return e.getOptions().hiddenOptions.indexOf(L)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}o.showHelp=(L)=>{let T=e.getInternalMethods().getLoggerInstance();if(!L)L="error";(typeof L==="function"?L:T[L])(o.help())},o.functionDescription=(L)=>["(",L.name?t.Parser.decamelize(L.name,"-"):n("generated-value"),")"].join(""),o.stringifiedValues=function(T,P){let W="",te=P||", ",le=[].concat(T);if(!T||!le.length)return W;return le.forEach((se)=>{if(W.length)W+=te;W+=JSON.stringify(se)}),W};function A(L,T){let P=`[${n("default:")} `;if(L===void 0&&!T)return null;if(T)P+=T;else switch(typeof L){case"string":P+=`"${L}"`;break;case"object":P+=JSON.stringify(L);break;default:P+=L}return`${P}]`}function M(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let X=null;o.version=(L)=>{X=L},o.showVersion=(L)=>{let T=e.getInternalMethods().getLoggerInstance();if(!L)L="error";(typeof L==="function"?L:T[L])(X)},o.reset=function(T){return r=null,c=!1,l=[],u=!1,g=[],d=[],f=[],h=xt(h,(P)=>!T[P]),o};let re=[];return o.freeze=function(){re.push({failMessage:r,failureOutput:c,usages:l,usageDisabled:u,epilogs:g,examples:d,commands:f,descriptions:h})},o.unfreeze=function(T=!1){let P=re.pop();if(!P)return;if(T)h={...P.descriptions,...h},f=[...P.commands,...f],l=[...P.usages,...l],d=[...P.examples,...d],g=[...P.epilogs,...g];else({failMessage:r,failureOutput:c,usages:l,usageDisabled:u,epilogs:g,examples:d,commands:f,descriptions:h}=P)},o}function lr(e){return typeof e==="object"}function vp(e,t){return lr(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function uc(e){return lr(e)?e.indentation:0}function Ts(e){return lr(e)?e.text:e}var fc=`###-begin-{{app_name}}-completions-###
13
+ `).map((o)=>up(o,t,n)).join(`
14
+ `)}function er(e){return ya(e,{stringWidth:tt,stripAnsi:Ut,wrap:Qo})}import{dirname as Ua,resolve as Ja}from"path";import{readdirSync as dp,statSync as fp}from"fs";function tr(e,t){let n=Ja(".",e),o;if(!fp(n).isDirectory())n=Ua(n);while(!0){if(o=t(n,dp(n)),o)return Ja(n,o);if(n=Ua(o=n),o===n)break}}import{inspect as Tp}from"util";import{fileURLToPath as ic}from"url";import{format as gp}from"util";import{normalize as mp,resolve as yp}from"path";function Jt(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",o=!1,s=e.match(/^-+/);for(let r=s?s[0].length:0;r<e.length;r++){let i=e.charAt(r);if(o)o=!1,i=i.toUpperCase();if(r!==0&&(i==="-"||i==="_"))o=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function As(e,t){let n=e.toLowerCase();t=t||"-";let o="";for(let s=0;s<e.length;s++){let r=n.charAt(s),i=e.charAt(s);if(r!==i&&s>0)o+=`${t}${n.charAt(s)}`;else o+=i}return o}function Ts(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 Ka(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,o=null,s=null,r=[];for(let i=0;i<e.length;i++){if(n=o,o=e.charAt(i),o===" "&&!s){if(n!==" ")t++;continue}if(o===s)s=null;else if((o==="'"||o==='"')&&!s)s=o;if(!r[t])r[t]="";r[t]+=o}return r}var ze;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(ze||(ze={}));var ft;class sr{constructor(e){ft=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),o=Ka(e),s=typeof e==="string",r=pp(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||[],l=n.envPrefix,u=i["populate--"],d=u?"--":"_",p=Object.create(null),h=Object.create(null),y=n.__||ft.format,f={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:[]},g=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,w=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(b){let E=typeof b==="object"?b.key:b,N=Object.keys(b).map(function(I){return{boolean:"bools",string:"strings",number:"numbers"}[I]}).filter(Boolean).pop();if(N)f[N][E]=!0;f.arrays[E]=!0,f.keys.push(E)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(b){f.bools[b]=!0,f.keys.push(b)}),[].concat(n.string||[]).filter(Boolean).forEach(function(b){f.strings[b]=!0,f.keys.push(b)}),[].concat(n.number||[]).filter(Boolean).forEach(function(b){f.numbers[b]=!0,f.keys.push(b)}),[].concat(n.count||[]).filter(Boolean).forEach(function(b){f.counts[b]=!0,f.keys.push(b)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(b){f.normalize[b]=!0,f.keys.push(b)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([b,E])=>{if(typeof E==="number")f.nargs[b]=E,f.keys.push(b)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([b,E])=>{if(typeof E==="function")f.coercions[b]=E,f.keys.push(b)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(b){f.configs[b]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([b,E])=>{if(typeof E==="boolean"||typeof E==="function")f.configs[b]=E})}ut(n.key,r,n.default,f.arrays),Object.keys(a).forEach(function(b){(f.aliases[b]||[]).forEach(function(E){a[E]=a[b]})});let D=null;Go();let k=[],S=Object.assign(Object.create(null),{_:[]}),C={};for(let b=0;b<o.length;b++){let E=o[b],N=E.replace(/^-{3,}/,"---"),I,x,q,j,Y,ke;if(E!=="--"&&/^-/.test(E)&&V(E))F(E);else if(N.match(/^---+(=|$)/)){F(E);continue}else if(E.match(/^--.+=/)||!i["short-option-groups"]&&E.match(/^-.+=/)){if(j=E.match(/^--?([^=]+)=([\s\S]*)$/),j!==null&&Array.isArray(j)&&j.length>=3)if(G(j[1],f.arrays))b=O(b,j[1],o,j[2]);else if(G(j[1],f.nargs)!==!1)b=A(b,j[1],o,j[2]);else B(j[1],j[2],!0)}else if(E.match(w)&&i["boolean-negation"]){if(j=E.match(w),j!==null&&Array.isArray(j)&&j.length>=2)x=j[1],B(x,G(x,f.arrays)?[!1]:!1)}else if(E.match(/^--.+/)||!i["short-option-groups"]&&E.match(/^-[^-]+/)){if(j=E.match(/^--?(.+)/),j!==null&&Array.isArray(j)&&j.length>=2)if(x=j[1],G(x,f.arrays))b=O(b,x,o);else if(G(x,f.nargs)!==!1)b=A(b,x,o);else if(Y=o[b+1],Y!==void 0&&(!Y.match(/^-/)||Y.match(g))&&!G(x,f.bools)&&!G(x,f.counts))B(x,Y),b++;else if(/^(true|false)$/.test(Y))B(x,Y),b++;else B(x,ee(x))}else if(E.match(/^-.\..+=/)){if(j=E.match(/^-([^=]+)=([\s\S]*)$/),j!==null&&Array.isArray(j)&&j.length>=3)B(j[1],j[2])}else if(E.match(/^-.\..+/)&&!E.match(g)){if(Y=o[b+1],j=E.match(/^-(.\..+)/),j!==null&&Array.isArray(j)&&j.length>=2)if(x=j[1],Y!==void 0&&!Y.match(/^-/)&&!G(x,f.bools)&&!G(x,f.counts))B(x,Y),b++;else B(x,ee(x))}else if(E.match(/^-[^-]+/)&&!E.match(g)){q=E.slice(1,-1).split(""),I=!1;for(let Oe=0;Oe<q.length;Oe++){if(Y=E.slice(Oe+2),q[Oe+1]&&q[Oe+1]==="="){if(ke=E.slice(Oe+3),x=q[Oe],G(x,f.arrays))b=O(b,x,o,ke);else if(G(x,f.nargs)!==!1)b=A(b,x,o,ke);else B(x,ke);I=!0;break}if(Y==="-"){B(q[Oe],Y);continue}if(/[A-Za-z]/.test(q[Oe])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(Y)&&G(Y,f.bools)===!1){B(q[Oe],Y),I=!0;break}if(q[Oe+1]&&q[Oe+1].match(/\W/)){B(q[Oe],Y),I=!0;break}else B(q[Oe],ee(q[Oe]))}if(x=E.slice(-1)[0],!I&&x!=="-")if(G(x,f.arrays))b=O(b,x,o);else if(G(x,f.nargs)!==!1)b=A(b,x,o);else if(Y=o[b+1],Y!==void 0&&(!/^(-|--)[^-]/.test(Y)||Y.match(g))&&!G(x,f.bools)&&!G(x,f.counts))B(x,Y),b++;else if(/^(true|false)$/.test(Y))B(x,Y),b++;else B(x,ee(x))}else if(E.match(/^-[0-9]$/)&&E.match(g)&&G(E.slice(1),f.bools))x=E.slice(1),B(x,ee(x));else if(E==="--"){k=o.slice(b+1);break}else if(i["halt-at-non-option"]){k=o.slice(b);break}else F(E)}if(ne(S,!0),ne(S,!1),R(S),W(),et(S,f.aliases,a,!0),te(S),i["set-placeholder-key"])ge(S);if(Object.keys(f.counts).forEach(function(b){if(!oe(S,b.split(".")))B(b,0)}),u&&k.length)S[d]=[];if(k.forEach(function(b){S[d].push(b)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(S).filter((b)=>b!=="--"&&b.includes("-")).forEach((b)=>{delete S[b]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((b)=>r[b])).forEach((b)=>{if(i["camel-case-expansion"]&&b.includes("-"))delete S[b.split(".").map((E)=>Jt(E)).join(".")];delete S[b]});function F(b){let E=_("_",b);if(typeof E==="string"||typeof E==="number")S._.push(E)}function A(b,E,N,I){let x,q=G(E,f.nargs);if(q=typeof q!=="number"||isNaN(q)?1:q,q===0){if(!De(I))D=Error(y("Argument unexpected for: %s",E));return B(E,ee(E)),b}let j=De(I)?0:1;if(i["nargs-eats-options"]){if(N.length-(b+1)+j<q)D=Error(y("Not enough arguments following: %s",E));j=q}else{for(x=b+1;x<N.length;x++)if(!N[x].match(/^-[^0-9]/)||N[x].match(g)||V(N[x]))j++;else break;if(j<q)D=Error(y("Not enough arguments following: %s",E))}let Y=Math.min(j,q);if(!De(I)&&Y>0)B(E,I),Y--;for(x=b+1;x<Y+b+1;x++)B(E,N[x]);return b+Y}function O(b,E,N,I){let x=[],q=I||N[b+1],j=G(E,f.nargs);if(G(E,f.bools)&&!/^(true|false)$/.test(q))x.push(!0);else if(De(q)||De(I)&&/^-/.test(q)&&!g.test(q)&&!V(q)){if(a[E]!==void 0){let Y=a[E];x=Array.isArray(Y)?Y:[Y]}}else{if(!De(I))x.push(P(E,I,!0));for(let Y=b+1;Y<N.length;Y++){if(!i["greedy-arrays"]&&x.length>0||j&&typeof j==="number"&&x.length>=j)break;if(q=N[Y],/^-/.test(q)&&!g.test(q)&&!V(q))break;b=Y,x.push(P(E,q,s))}}if(typeof j==="number"&&(j&&x.length<j||isNaN(j)&&x.length===0))D=Error(y("Not enough arguments following: %s",E));return B(E,x),b}function B(b,E,N=s){if(/-/.test(b)&&i["camel-case-expansion"]){let q=b.split(".").map(function(j){return Jt(j)}).join(".");U(b,q)}let I=P(b,E,N),x=b.split(".");if(Ie(S,x,I),f.aliases[b])f.aliases[b].forEach(function(q){let j=q.split(".");Ie(S,j,I)});if(x.length>1&&i["dot-notation"])(f.aliases[x[0]]||[]).forEach(function(q){let j=q.split("."),Y=[].concat(x);if(Y.shift(),j=j.concat(Y),!(f.aliases[b]||[]).includes(j.join(".")))Ie(S,j,I)});if(G(b,f.normalize)&&!G(b,f.arrays))[b].concat(f.aliases[b]||[]).forEach(function(j){Object.defineProperty(C,j,{enumerable:!0,get(){return E},set(Y){E=typeof Y==="string"?ft.normalize(Y):Y}})})}function U(b,E){if(!(f.aliases[b]&&f.aliases[b].length))f.aliases[b]=[E],p[E]=!0;if(!(f.aliases[E]&&f.aliases[E].length))U(E,b)}function P(b,E,N){if(N)E=hp(E);if(G(b,f.bools)||G(b,f.counts)){if(typeof E==="string")E=E==="true"}let I=Array.isArray(E)?E.map(function(x){return _(b,x)}):_(b,E);if(G(b,f.counts)&&(De(I)||typeof I==="boolean"))I=nr();if(G(b,f.normalize)&&G(b,f.arrays))if(Array.isArray(E))I=E.map((x)=>ft.normalize(x));else I=ft.normalize(E);return I}function _(b,E){if(!i["parse-positional-numbers"]&&b==="_")return E;if(!G(b,f.strings)&&!G(b,f.bools)&&!Array.isArray(E)){if(Ts(E)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${E}`)))||!De(E)&&G(b,f.numbers))E=Number(E)}return E}function R(b){let E=Object.create(null);et(E,f.aliases,a),Object.keys(f.configs).forEach(function(N){let I=b[N]||E[N];if(I)try{let x=null,q=ft.resolve(ft.cwd(),I),j=f.configs[N];if(typeof j==="function"){try{x=j(q)}catch(Y){x=Y}if(x instanceof Error){D=x;return}}else x=ft.require(q);L(x)}catch(x){if(x.name==="PermissionDenied")D=x;else if(b[N])D=Error(y("Invalid JSON config file: %s",I))}})}function L(b,E){Object.keys(b).forEach(function(N){let I=b[N],x=E?E+"."+N:N;if(typeof I==="object"&&I!==null&&!Array.isArray(I)&&i["dot-notation"])L(I,x);else if(!oe(S,x.split("."))||G(x,f.arrays)&&i["combine-arrays"])B(x,I)})}function W(){if(typeof c<"u")c.forEach(function(b){L(b)})}function ne(b,E){if(typeof l>"u")return;let N=typeof l==="string"?l:"",I=ft.env();Object.keys(I).forEach(function(x){if(N===""||x.lastIndexOf(N,0)===0){let q=x.split("__").map(function(j,Y){if(Y===0)j=j.substring(N.length);return Jt(j)});if((E&&f.configs[q.join(".")]||!E)&&!oe(b,q))B(q.join("."),I[x])}})}function te(b){let E,N=new Set;Object.keys(b).forEach(function(I){if(!N.has(I)){if(E=G(I,f.coercions),typeof E==="function")try{let x=_(I,E(b[I]));[].concat(f.aliases[I]||[],I).forEach((q)=>{N.add(q),b[q]=x})}catch(x){D=x}}})}function ge(b){return f.keys.forEach((E)=>{if(~E.indexOf("."))return;if(typeof b[E]>"u")b[E]=void 0}),b}function et(b,E,N,I=!1){Object.keys(N).forEach(function(x){if(!oe(b,x.split("."))){if(Ie(b,x.split("."),N[x]),I)h[x]=!0;(E[x]||[]).forEach(function(q){if(oe(b,q.split(".")))return;Ie(b,q.split("."),N[x])})}})}function oe(b,E){let N=b;if(!i["dot-notation"])E=[E.join(".")];E.slice(0,-1).forEach(function(x){N=N[x]||{}});let I=E[E.length-1];if(typeof N!=="object")return!1;else return I in N}function Ie(b,E,N){let I=b;if(!i["dot-notation"])E=[E.join(".")];E.slice(0,-1).forEach(function(ke){if(ke=qa(ke),typeof I==="object"&&I[ke]===void 0)I[ke]={};if(typeof I[ke]!=="object"||Array.isArray(I[ke])){if(Array.isArray(I[ke]))I[ke].push({});else I[ke]=[I[ke],{}];I=I[ke][I[ke].length-1]}else I=I[ke]});let x=qa(E[E.length-1]),q=G(E.join("."),f.arrays),j=Array.isArray(N),Y=i["duplicate-arguments-array"];if(!Y&&G(x,f.nargs)){if(Y=!0,!De(I[x])&&f.nargs[x]===1||Array.isArray(I[x])&&I[x].length===f.nargs[x])I[x]=void 0}if(N===nr())I[x]=nr(I[x]);else if(Array.isArray(I[x]))if(Y&&q&&j)I[x]=i["flatten-duplicate-arrays"]?I[x].concat(N):(Array.isArray(I[x][0])?I[x]:[I[x]]).concat([N]);else if(!Y&&Boolean(q)===Boolean(j))I[x]=N;else I[x]=I[x].concat([N]);else if(I[x]===void 0&&q)I[x]=j?N:[N];else if(Y&&!(I[x]===void 0||G(x,f.counts)||G(x,f.bools)))I[x]=[I[x],N];else I[x]=N}function ut(...b){b.forEach(function(E){Object.keys(E||{}).forEach(function(N){if(f.aliases[N])return;f.aliases[N]=[].concat(r[N]||[]),f.aliases[N].concat(N).forEach(function(I){if(/-/.test(I)&&i["camel-case-expansion"]){let x=Jt(I);if(x!==N&&f.aliases[N].indexOf(x)===-1)f.aliases[N].push(x),p[x]=!0}}),f.aliases[N].concat(N).forEach(function(I){if(I.length>1&&/[A-Z]/.test(I)&&i["camel-case-expansion"]){let x=As(I,"-");if(x!==N&&f.aliases[N].indexOf(x)===-1)f.aliases[N].push(x),p[x]=!0}}),f.aliases[N].forEach(function(I){f.aliases[I]=[N].concat(f.aliases[N].filter(function(x){return I!==x}))})})})}function G(b,E){let N=[].concat(f.aliases[b]||[],b),I=Object.keys(E),x=N.find((q)=>I.includes(q));return x?E[x]:!1}function dt(b){let E=Object.keys(f);return[].concat(E.map((I)=>f[I])).some(function(I){return Array.isArray(I)?I.includes(b):I[b]})}function hn(b,...E){return[].concat(...E).some(function(I){let x=b.match(I);return x&&dt(x[1])})}function M(b){if(b.match(g)||!b.match(/^-[^-]+/))return!1;let E=!0,N,I=b.slice(1).split("");for(let x=0;x<I.length;x++){if(N=b.slice(x+2),!dt(I[x])){E=!1;break}if(I[x+1]&&I[x+1]==="="||N==="-"||/[A-Za-z]/.test(I[x])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(N)||I[x+1]&&I[x+1].match(/\W/))break}return E}function V(b){return i["unknown-options-as-args"]&&re(b)}function re(b){if(b=b.replace(/^-{3,}/,"--"),b.match(g))return!1;if(M(b))return!1;return!hn(b,/^-+([^=]+?)=[\s\S]*$/,w,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function ee(b){if(!G(b,f.bools)&&!G(b,f.counts)&&`${b}`in a)return a[b];else return Se(me(b))}function Se(b){return{[ze.BOOLEAN]:!0,[ze.STRING]:"",[ze.NUMBER]:void 0,[ze.ARRAY]:[]}[b]}function me(b){let E=ze.BOOLEAN;if(G(b,f.strings))E=ze.STRING;else if(G(b,f.numbers))E=ze.NUMBER;else if(G(b,f.bools))E=ze.BOOLEAN;else if(G(b,f.arrays))E=ze.ARRAY;return E}function De(b){return b===void 0}function Go(){Object.keys(f.counts).find((b)=>{if(G(b,f.arrays))return D=Error(y("Invalid configuration: %s, opts.count excludes opts.array.",b)),!0;else if(G(b,f.nargs))return D=Error(y("Invalid configuration: %s, opts.count excludes opts.narg.",b)),!0;return!1})}return{aliases:Object.assign({},f.aliases),argv:Object.assign(C,S),configuration:i,defaulted:Object.assign({},h),error:D,newAliases:Object.assign({},p)}}}function pp(e){let t=[],n=Object.create(null),o=!0;Object.keys(e).forEach(function(s){t.push([].concat(e[s],s))});while(o){o=!1;for(let s=0;s<t.length;s++)for(let r=s+1;r<t.length;r++)if(t[s].filter(function(a){return t[r].indexOf(a)!==-1}).length){t[s]=t[s].concat(t[r]),t.splice(r,1),o=!0;break}}return t.forEach(function(s){s=s.filter(function(i,a,c){return c.indexOf(i)===a});let r=s.pop();if(r!==void 0&&typeof r==="string")n[r]=s}),n}function nr(e){return e!==void 0?e+1:1}function qa(e){if(e==="__proto__")return"___proto___";return e}function hp(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 wp}from"fs";import{createRequire as Ha}from"node:module";var or,rr,ir,za=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Ga=(rr=(or=process===null||process===void 0?void 0:process.versions)===null||or===void 0?void 0:or.node)!==null&&rr!==void 0?rr:(ir=process===null||process===void 0?void 0:process.version)===null||ir===void 0?void 0:ir.slice(1);if(Ga){if(Number(Ga.match(/^([^.]+)/)[1])<za)throw Error(`yargs parser supports a minimum Node.js version of ${za}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var Dp=process?process.env:{},Ya=Ha?Ha(import.meta.url):void 0,Xa=new sr({cwd:process.cwd,env:()=>Dp,format:gp,normalize:mp,resolve:yp,require:(e)=>{if(typeof Ya<"u")return Ya(e);else if(e.match(/\.json$/))return JSON.parse(wp(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),Nn=function(t,n){return Xa.parse(t.slice(),n).argv};Nn.detailed=function(e,t){return Xa.parse(e.slice(),t)};Nn.camelCase=Jt;Nn.decamelize=As;Nn.looksLikeNumber=Ts;var ar=Nn;import{basename as Ip,dirname as Op,extname as Rp,relative as Pp,resolve as rc,join as vp}from"path";function Va(){if(bp())return 0;return 1}function bp(){return kp()&&!process.defaultApp}function kp(){return!!process.versions.electron}function cr(e){return e.slice(Va()+1)}function Za(){return process.argv[Va()]}import{readFileSync as xp,statSync as Ep,writeFile as Sp}from"fs";import{format as Cp}from"util";import{resolve as _p}from"path";var Qa={fs:{readFileSync:xp,writeFile:Sp},format:Cp,resolve:_p,exists:(e)=>{try{return Ep(e).isFile()}catch(t){return!1}}};var nt;class ec{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 nt.format.apply(nt.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),o=e.shift(),s=function(){};if(typeof e[e.length-1]==="function")s=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let r=o===1?t:n;if(this.cache[this.locale][t])r=this.cache[this.locale][t][o===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:s});else s();let i=[r];if(~r.indexOf("%d"))i.push(o);return nt.format.apply(nt.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(o,s){let r=t[s+1];if(n+=o,typeof r<"u")n+="%s"}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){if(this.writeQueue.push(e),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],{directory:n,locale:o,cb:s}=t,r=this._resolveLocaleFile(n,o),i=JSON.stringify(this.cache[o],null,2);nt.fs.writeFile(r,i,"utf-8",function(a){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();s(a)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(nt.fs.readFileSync)e=JSON.parse(nt.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=nt.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let o=nt.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(o))n=o}return n}_fileExistsSync(e){return nt.exists(e)}}function tc(e,t){nt=t;let n=new ec(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 $p=(e)=>tc(e,Qa),nc=$p;var ac=pa(oc(),1);import{createRequire as Bp}from"node:module";import{readFileSync as Lp,readdirSync as Np}from"node:fs";var lr=ic(import.meta.url),Mp=lr.substring(0,lr.lastIndexOf("node_modules")),jp=Bp(import.meta.url),ur={assert:{notStrictEqual:Fp,strictEqual:Ap},cliui:er,findUp:tr,getEnv:(e)=>process.env[e],inspect:Tp,getProcessArgvBin:Za,mainFilename:Mp||process.cwd(),Parser:ar,path:{basename:Ip,dirname:Op,extname:Rp,relative:Pp,resolve:rc,join:vp},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:Lp,readdirSync:Np,require:jp,getCallerFile:()=>{let e=ac.default(3);return e.match(/^file:\/\//)?ic(e):e},stringWidth:tt,y18n:nc({directory:rc(lr,"../../../locales"),updateFiles:!1})};function Re(e,t,n,o){n.assert.notStrictEqual(e,t,o)}function dr(e,t){t.assert.strictEqual(typeof e,"string")}function gn(e){return Object.keys(e)}function ce(e){return!!e&&!!e.then&&typeof e.then==="function"}class ye extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,ye)}}function kt(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),o=/\.*[\][<>]/g,s=n.shift();if(!s)throw Error(`No command found in: ${e}`);let r={cmd:s.replace(o,""),demanded:[],optional:[]};return n.forEach((i,a)=>{let c=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&a===n.length-1)c=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(o,"").split("|"),variadic:c});else r.demanded.push({cmd:i.replace(o,"").split("|"),variadic:c})}),r}var Wp=["first","second","third","fourth","fifth","sixth"];function J(e,t,n){function o(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[kt(`cmd ${e}`),t,n]}try{let s=0,[r,i,a]=o(),c=[].slice.call(i);while(c.length&&c[c.length-1]===void 0)c.pop();let l=a||c.length;if(l<r.demanded.length)throw new ye(`Not enough arguments provided. Expected ${r.demanded.length} but received ${c.length}.`);let u=r.demanded.length+r.optional.length;if(l>u)throw new ye(`Too many arguments provided. Expected max ${u} but received ${l}.`);r.demanded.forEach((d)=>{let p=c.shift(),h=cc(p);if(d.cmd.filter((f)=>f===h||f==="*").length===0)lc(h,d.cmd,s);s+=1}),r.optional.forEach((d)=>{if(c.length===0)return;let p=c.shift(),h=cc(p);if(d.cmd.filter((f)=>f===h||f==="*").length===0)lc(h,d.cmd,s);s+=1})}catch(s){console.warn(s.stack)}}function cc(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function lc(e,t,n){throw new ye(`Invalid ${Wp[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class fr{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,o=!1){if(J("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let s=0;s<e.length;s++){if(typeof e[s]!=="function")throw Error("middleware must be a function");let r=e[s];r.applyBeforeValidation=t,r.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let s=e;s.applyBeforeValidation=t,s.global=n,s.mutates=o,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((o)=>{let s=[...n[t]||[],t];if(!o.option)return!0;else return!s.includes(o.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function uc(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function Kt(e,t,n,o){return n.reduce((s,r)=>{if(r.applyBeforeValidation!==o)return s;if(r.mutates){if(r.applied)return s;r.applied=!0}if(ce(s))return s.then((i)=>Promise.all([i,r(i,t)])).then(([i,a])=>Object.assign(i,a));else{let i=r(s,t);return ce(i)?i.then((a)=>Object.assign(s,a)):Object.assign(s,i)}},e)}function qt(e,t,n=(o)=>{throw o}){try{let o=Up(e)?e():e;return ce(o)?o.then((s)=>t(s)):t(o)}catch(o){return n(o)}}function Up(e){return typeof e==="function"}var mn=/(^\*)|(^\$0)/;class fc{constructor(e,t,n,o){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=o,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,o){o=o||{},this.requireCache.add(n);let s=this.shim.path.resolve(this.shim.path.dirname(n),e),r=this.shim.readdirSync(s,{recursive:o.recurse?!0:!1});if(!Array.isArray(o.extensions))o.extensions=["js"];let i=typeof o.visit==="function"?o.visit:(a)=>a;for(let a of r){let c=a.toString();if(o.exclude){let u=!1;if(typeof o.exclude==="function")u=o.exclude(c);else u=o.exclude.test(c);if(u)continue}if(o.include){let u=!1;if(typeof o.include==="function")u=o.include(c);else u=o.include.test(c);if(!u)continue}let l=!1;for(let u of o.extensions)if(c.endsWith(u))l=!0;if(l){let u=this.shim.path.join(s,c),d=t(u),p=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(p,u,c)){if(this.requireCache.has(u))continue;else this.requireCache.add(u);if(!p.command)p.command=this.shim.path.basename(u,this.shim.path.extname(u));this.addHandler(p)}}}}addHandler(e,t,n,o,s,r){let i=[],a=uc(s);if(o=o||(()=>{}),Array.isArray(e))if(Jp(e))[e,...i]=e;else for(let c of e)this.addHandler(c);else if(qp(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(dc(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let c=kt(e);i=i.map((d)=>kt(d).cmd);let l=!1,u=[c.cmd].concat(i).filter((d)=>{if(mn.test(d))return l=!0,!1;return!0});if(u.length===0&&l)u.push("$0");if(l)c.cmd=u[0],i=u.slice(1),e=e.replace(mn,c.cmd);if(i.forEach((d)=>{this.aliasMap[d]=c.cmd}),t!==!1)this.usage.command(e,t,l,i,r);if(this.handlers[c.cmd]={original:e,description:t,handler:o,builder:n||{},middlewares:a,deprecated:r,demanded:c.demanded,optional:c.optional},l)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,o,s,r){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,a=t.getInternalMethods().getContext(),c=a.commands.slice(),l=!e;if(e)a.commands.push(e),a.fullCommands.push(i.original);let u=this.applyBuilderUpdateUsageAndParse(l,i,t,n.aliases,c,o,s,r);return ce(u)?u.then((d)=>this.applyMiddlewareAndGetResult(l,i,d.innerArgv,a,s,d.aliases,t)):this.applyMiddlewareAndGetResult(l,i,u.innerArgv,a,s,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,o,s,r,i,a){let c=t.builder,l=n;if(Is(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(o),a);if(ce(u))return u.then((d)=>(l=hc(d)?d:n,this.parseAndUpdateUsage(e,t,l,s,r,i)))}else if(Kp(c))n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(o),Object.keys(t.builder).forEach((u)=>{l.option(u,c[u])});return this.parseAndUpdateUsage(e,t,l,s,r,i)}parseAndUpdateUsage(e,t,n,o,s,r){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(o,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,s,r);return ce(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=mn.test(t.original)?t.original.replace(mn,"").trim():t.original,o=e.filter((s)=>!mn.test(s));return o.push(n),`$0 ${o.join(" ")}`}handleValidationAndGetResult(e,t,n,o,s,r,i,a){if(!r.getInternalMethods().getHasOutput()){let c=r.getInternalMethods().runValidation(s,a,r.parsed.error,e);n=qt(n,(l)=>(c(l),l))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let c=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,c,!1,!1),n=Kt(n,r,i,!1),n=qt(n,(l)=>{let u=t.handler(l);return ce(u)?u.then(()=>l):l}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(ce(n)&&!r.getInternalMethods().hasParseCallback())n.catch((l)=>{try{r.getInternalMethods().getUsageInstance().fail(null,l)}catch(u){}})}if(!e)o.commands.pop(),o.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,o,s,r,i){let a={};if(s)return n;if(!i.getInternalMethods().getHasOutput())a=this.populatePositionals(t,n,o,i);let c=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=Kt(n,i,c,!0);return ce(l)?l.then((u)=>this.handleValidationAndGetResult(e,t,u,o,r,i,c,a)):this.handleValidationAndGetResult(e,t,l,o,r,i,c,a)}populatePositionals(e,t,n,o){t._=t._.slice(n.commands.length);let s=e.demanded.slice(0),r=e.optional.slice(0),i={};this.validation.positionalCount(s.length,t._.length);while(s.length){let a=s.shift();this.populatePositional(a,t,i)}while(r.length){let a=r.shift();this.populatePositional(a,t,i)}return t._=n.commands.concat(t._.map((a)=>""+a)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),o),i}populatePositional(e,t,n){let o=e.cmd[0];if(e.variadic)n[o]=t._.splice(0).map(String);else if(t._.length)n[o]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=kt(e);return n.demanded.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r,t.demand[s]=!0}),n.optional.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r}),t}postProcessPositionals(e,t,n,o){let s=Object.assign({},o.getOptions());s.default=Object.assign(n.default,s.default);for(let c of Object.keys(n.alias))s.alias[c]=(s.alias[c]||[]).concat(n.alias[c]);s.array=s.array.concat(n.array),s.config={};let r=[];if(Object.keys(t).forEach((c)=>{t[c].map((l)=>{if(s.configuration["unknown-options-as-args"])s.key[c]=!0;r.push(`--${c}`),r.push(l)})}),!r.length)return;let i=Object.assign({},s.configuration,{"populate--":!1}),a=this.shim.Parser.detailed(r,Object.assign({},s,{configuration:i}));if(a.error)o.getInternalMethods().getUsageInstance().fail(a.error.message,a.error);else{let c=Object.keys(t);Object.keys(t).forEach((l)=>{c.push(...a.aliases[l])}),Object.keys(a.argv).forEach((l)=>{if(c.includes(l)){if(!t[l])t[l]=a.argv[l];if(!this.isInConfigs(o,l)&&!this.isDefaulted(o,l)&&Object.prototype.hasOwnProperty.call(e,l)&&Object.prototype.hasOwnProperty.call(a.argv,l)&&(Array.isArray(e[l])||Array.isArray(a.argv[l])))e[l]=[].concat(e[l],a.argv[l]);else e[l]=a.argv[l]}})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some((o)=>Object.prototype.hasOwnProperty.call(o,t))||n.some((o)=>Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=mn.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(Is(t))return t(e,!0);else if(!dc(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let o of[e,t,n]){if(typeof o==="string"||o===!1)return o;Re(o,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();Re(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 pc(e,t,n,o){return new fc(e,t,n,o)}function dc(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function Jp(e){return e.every((t)=>typeof t==="string")}function Is(e){return typeof e==="function"}function Kp(e){return typeof e==="object"}function qp(e){return typeof e==="object"&&!Array.isArray(e)}function xt(e={},t=()=>!0){let n={};return gn(e).forEach((o)=>{if(t(o,e[o]))n[o]=e[o]}),n}function Et(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 Hp(e){return typeof e==="boolean"}function mc(e,t){let n=t.y18n.__,o={},s=[];o.failFn=function(_){s.push(_)};let r=null,i=null,a=!0;o.showHelpOnFail=function(_=!0,R){let[L,W]=typeof _==="string"?[!0,_]:[_,R];if(e.getInternalMethods().isGlobalContext())i=W;return r=W,a=L,o};let c=!1;o.fail=function(_,R){let L=e.getInternalMethods().getLoggerInstance();if(s.length)for(let W=s.length-1;W>=0;--W){let ne=s[W];if(Hp(ne)){if(R)throw R;else if(_)throw Error(_)}else ne(_,R,o)}else{if(e.getExitProcess())Et(!0);if(!c){if(c=!0,a)e.showHelp("error"),L.error();if(_||R)L.error(_||R);let W=r||i;if(W){if(_||R)L.error("");L.error(W)}}if(R=R||new ye(_),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,R);else throw R}};let l=[],u=!1;o.usage=(P,_)=>{if(P===null)return u=!0,l=[],o;return u=!1,l.push([P,_||""]),o},o.getUsage=()=>l,o.getUsageDisabled=()=>u,o.getPositionalGroupName=()=>n("Positionals:");let d=[];o.example=(P,_)=>{d.push([P,_||""])};let p=[];o.command=function(_,R,L,W,ne=!1){if(L)p=p.map((te)=>(te[2]=!1,te));p.push([_,R||"",L,W,ne])},o.getCommands=()=>p;let h={};o.describe=function(_,R){if(Array.isArray(_))_.forEach((L)=>{o.describe(L,R)});else if(typeof _==="object")Object.keys(_).forEach((L)=>{o.describe(L,_[L])});else h[_]=R},o.getDescriptions=()=>h;let y=[];o.epilog=(P)=>{y.push(P)};let f=!1,g;o.wrap=(P)=>{f=!0,g=P},o.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!f)g=O(),f=!0;return g};let w="__yargsString__:";o.deferY18nLookup=(P)=>w+P,o.help=function(){if(S)return S;k();let _=e.customScriptName?e.$0:t.path.basename(e.$0),R=e.getDemandedOptions(),L=e.getDemandedCommands(),W=e.getDeprecatedOptions(),ne=e.getGroups(),te=e.getOptions(),ge=[];ge=ge.concat(Object.keys(h)),ge=ge.concat(Object.keys(R)),ge=ge.concat(Object.keys(L)),ge=ge.concat(Object.keys(te.default)),ge=ge.filter(F),ge=Object.keys(ge.reduce((M,V)=>{if(V!=="_")M[V]=!0;return M},{}));let et=o.getWrap(),oe=t.cliui({width:et,wrap:!!et});if(!u){if(l.length)l.forEach((M)=>{if(oe.div({text:`${M[0].replace(/\$0/g,_)}`}),M[1])oe.div({text:`${M[1]}`,padding:[1,0,0,0]})}),oe.div();else if(p.length){let M=null;if(L._)M=`${_} <${n("command")}>
15
+ `;else M=`${_} [${n("command")}]
16
+ `;oe.div(`${M}`)}}if(p.length>1||p.length===1&&!p[0][2]){oe.div(n("Commands:"));let M=e.getInternalMethods().getContext(),V=M.commands.length?`${M.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)p=p.sort((ee,Se)=>ee[0].localeCompare(Se[0]));let re=_?`${_} `:"";p.forEach((ee)=>{let Se=`${re}${V}${ee[0].replace(/^\$0 ?/,"")}`;oe.span({text:Se,padding:[0,2,0,2],width:D(p,et,`${_}${V}`)+4},{text:ee[1]});let me=[];if(ee[2])me.push(`[${n("default")}]`);if(ee[3]&&ee[3].length)me.push(`[${n("aliases:")} ${ee[3].join(", ")}]`);if(ee[4])if(typeof ee[4]==="string")me.push(`[${n("deprecated: %s",ee[4])}]`);else me.push(`[${n("deprecated")}]`);if(me.length)oe.div({text:me.join(" "),padding:[0,0,0,2],align:"right"});else oe.div()}),oe.div()}let Ie=(Object.keys(te.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);ge=ge.filter((M)=>!e.parsed.newAliases[M]&&Ie.every((V)=>(te.alias[V]||[]).indexOf(M)===-1));let ut=n("Options:");if(!ne[ut])ne[ut]=[];C(ge,te.alias,ne,ut);let G=(M)=>/^--/.test(Os(M)),dt=Object.keys(ne).filter((M)=>ne[M].length>0).map((M)=>{let V=ne[M].filter(F).map((re)=>{if(Ie.includes(re))return re;for(let ee=0,Se;(Se=Ie[ee])!==void 0;ee++)if((te.alias[Se]||[]).includes(re))return Se;return re});return{groupName:M,normalizedKeys:V}}).filter(({normalizedKeys:M})=>M.length>0).map(({groupName:M,normalizedKeys:V})=>{let re=V.reduce((ee,Se)=>(ee[Se]=[Se].concat(te.alias[Se]||[]).map((me)=>{if(M===o.getPositionalGroupName())return me;else return(/^[0-9]$/.test(me)?te.boolean.includes(Se)?"-":"--":me.length>1?"--":"-")+me}).sort((me,De)=>G(me)===G(De)?0:G(me)?1:-1).join(", "),ee),{});return{groupName:M,normalizedKeys:V,switches:re}});if(dt.filter(({groupName:M})=>M!==o.getPositionalGroupName()).some(({normalizedKeys:M,switches:V})=>!M.every((re)=>G(V[re]))))dt.filter(({groupName:M})=>M!==o.getPositionalGroupName()).forEach(({normalizedKeys:M,switches:V})=>{M.forEach((re)=>{if(G(V[re]))V[re]=zp(V[re],4)})});if(dt.forEach(({groupName:M,normalizedKeys:V,switches:re})=>{oe.div(M),V.forEach((ee)=>{let Se=re[ee],me=h[ee]||"",De=null;if(me.includes(w))me=n(me.substring(w.length));if(te.boolean.includes(ee))De=`[${n("boolean")}]`;if(te.count.includes(ee))De=`[${n("count")}]`;if(te.string.includes(ee))De=`[${n("string")}]`;if(te.normalize.includes(ee))De=`[${n("string")}]`;if(te.array.includes(ee))De=`[${n("array")}]`;if(te.number.includes(ee))De=`[${n("number")}]`;let Go=(N)=>typeof N==="string"?`[${n("deprecated: %s",N)}]`:`[${n("deprecated")}]`,b=[ee in W?Go(W[ee]):null,De,ee in R?`[${n("required")}]`:null,te.choices&&te.choices[ee]?`[${n("choices:")} ${o.stringifiedValues(te.choices[ee])}]`:null,A(te.default[ee],te.defaultDescription[ee])].filter(Boolean).join(" ");oe.span({text:Os(Se),padding:[0,2,0,2+gc(Se)],width:D(re,et)+4},me);let E=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(b&&!E)oe.div({text:b,padding:[0,0,0,2],align:"right"});else oe.div()}),oe.div()}),d.length)oe.div(n("Examples:")),d.forEach((M)=>{M[0]=M[0].replace(/\$0/g,_)}),d.forEach((M)=>{if(M[1]==="")oe.div({text:M[0],padding:[0,2,0,2]});else oe.div({text:M[0],padding:[0,2,0,2],width:D(d,et)+4},{text:M[1]})}),oe.div();if(y.length>0){let M=y.map((V)=>V.replace(/\$0/g,_)).join(`
17
+ `);oe.div(`${M}
18
+ `)}return oe.toString().replace(/\s*$/,"")};function D(P,_,R){let L=0;if(!Array.isArray(P))P=Object.values(P).map((W)=>[W]);if(P.forEach((W)=>{L=Math.max(t.stringWidth(R?`${R} ${Os(W[0])}`:Os(W[0]))+gc(W[0]),L)}),_)L=Math.min(L,parseInt((_*0.5).toString(),10));return L}function k(){let P=e.getDemandedOptions(),_=e.getOptions();(Object.keys(_.alias)||[]).forEach((R)=>{_.alias[R].forEach((L)=>{if(h[L])o.describe(R,h[L]);if(L in P)e.demandOption(R,P[L]);if(_.boolean.includes(L))e.boolean(R);if(_.count.includes(L))e.count(R);if(_.string.includes(L))e.string(R);if(_.normalize.includes(L))e.normalize(R);if(_.array.includes(L))e.array(R);if(_.number.includes(L))e.number(R)})})}let S;o.cacheHelpMessage=function(){S=this.help()},o.clearCachedHelpMessage=function(){S=void 0},o.hasCachedHelpMessage=function(){return!!S};function C(P,_,R,L){let W=[],ne=null;return Object.keys(R).forEach((te)=>{W=W.concat(R[te])}),P.forEach((te)=>{if(ne=[te].concat(_[te]),!ne.some((ge)=>W.indexOf(ge)!==-1))R[L].push(te)}),W}function F(P){return e.getOptions().hiddenOptions.indexOf(P)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}o.showHelp=(P)=>{let _=e.getInternalMethods().getLoggerInstance();if(!P)P="error";(typeof P==="function"?P:_[P])(o.help())},o.functionDescription=(P)=>["(",P.name?t.Parser.decamelize(P.name,"-"):n("generated-value"),")"].join(""),o.stringifiedValues=function(_,R){let L="",W=R||", ",ne=[].concat(_);if(!_||!ne.length)return L;return ne.forEach((te)=>{if(L.length)L+=W;L+=JSON.stringify(te)}),L};function A(P,_){let R=`[${n("default:")} `;if(P===void 0&&!_)return null;if(_)R+=_;else switch(typeof P){case"string":R+=`"${P}"`;break;case"object":R+=JSON.stringify(P);break;default:R+=P}return`${R}]`}function O(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let B=null;o.version=(P)=>{B=P},o.showVersion=(P)=>{let _=e.getInternalMethods().getLoggerInstance();if(!P)P="error";(typeof P==="function"?P:_[P])(B)},o.reset=function(_){return r=null,c=!1,l=[],u=!1,y=[],d=[],p=[],h=xt(h,(R)=>!_[R]),o};let U=[];return o.freeze=function(){U.push({failMessage:r,failureOutput:c,usages:l,usageDisabled:u,epilogs:y,examples:d,commands:p,descriptions:h})},o.unfreeze=function(_=!1){let R=U.pop();if(!R)return;if(_)h={...R.descriptions,...h},p=[...R.commands,...p],l=[...R.usages,...l],d=[...R.examples,...d],y=[...R.epilogs,...y];else({failMessage:r,failureOutput:c,usages:l,usageDisabled:u,epilogs:y,examples:d,commands:p,descriptions:h}=R)},o}function pr(e){return typeof e==="object"}function zp(e,t){return pr(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function gc(e){return pr(e)?e.indentation:0}function Os(e){return pr(e)?e.text:e}var yc=`###-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
- `,pc=`#compdef {{app_name}}
47
+ `,wc=`#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 hc{constructor(e,t,n,o){var s,r,i;this.yargs=e,this.usage=t,this.command=n,this.shim=o,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((s=this.shim.getEnv("SHELL"))===null||s===void 0?void 0:s.includes("zsh"))||((r=this.shim.getEnv("ZSH_NAME"))===null||r===void 0?void 0:r.includes("zsh")))!==null&&i!==void 0?i:!1}defaultCompletion(e,t,n,o){let s=this.command.getCommandHandlers();for(let i=0,a=e.length;i<a;++i)if(s[e[i]]&&s[e[i]].builder){let c=s[e[i]].builder;if(As(c)){this.indexAfterLastReset=i+1;let l=this.yargs.getInternalMethods().reset();return c(l,!0),l.argv}}let r=[];this.commandCompletions(r,e,n),this.optionCompletions(r,e,t,n),this.choicesFromOptionsCompletions(r,e,t,n),this.choicesFromPositionalsCompletions(r,e,t,n),o(null,r)}commandCompletions(e,t,n){let o=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&o[o.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((s)=>{let r=kt(s[0]).cmd;if(t.indexOf(r)===-1)if(!this.zshShell)e.push(r);else{let i=s[1]||"";e.push(r.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,o){if((o.match(/^-/)||o===""&&e.length===0)&&!this.previousArgHasChoices(t)){let s=this.yargs.getOptions(),r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(s.key).forEach((i)=>{let a=!!s.configuration["boolean-negation"]&&s.boolean.includes(i);if(!r.includes(i)&&!s.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,a))this.completeOptionKey(i,e,o,a&&!!s.default[i])})}}choicesFromOptionsCompletions(e,t,n,o){if(this.previousArgHasChoices(t)){let s=this.getPreviousArgChoices(t);if(s&&s.length>0)e.push(...s.map((r)=>r.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,o){if(o===""&&e.length>0&&this.previousArgHasChoices(t))return;let s=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=s[n._.length-r-1];if(!i)return;let a=this.yargs.getOptions().choices[i]||[];for(let c of a)if(c.startsWith(o))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 o=t.replace(/^-+/,""),s=this.yargs.getOptions(),r=[o,...this.yargs.getAliases()[o]||[]],i;for(let a of r)if(Object.prototype.hasOwnProperty.call(s.key,a)&&Array.isArray(s.choices[a])){i=s.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 o=(s)=>e.indexOf((/^[^0-9]$/.test(s)?"-":"--")+s)!==-1;if(o(t))return!0;if(n&&o(`no-${t}`))return!0;if(this.aliases){for(let s of this.aliases[t])if(o(s))return!0}return!1}completeOptionKey(e,t,n,o){var s,r,i,a;let c=e;if(this.zshShell){let f=this.usage.getDescriptions(),h=(r=(s=this===null||this===void 0?void 0:this.aliases)===null||s===void 0?void 0:s[e])===null||r===void 0?void 0:r.find((m)=>{let D=f[m];return typeof D==="string"&&D.length>0}),g=h?f[h]:void 0,p=(a=(i=f[e])!==null&&i!==void 0?i:g)!==null&&a!==void 0?a:"";c=`${e.replace(/:/g,"\\:")}:${p.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let l=(f)=>/^--/.test(f),u=(f)=>/^[^0-9]$/.test(f),d=!l(n)&&u(e)?"-":"--";if(t.push(d+c),o)t.push(d+"no-"+c)}customCompletion(e,t,n,o){if(ve(this.customCompletionFunction,null,this.shim),Bp(this.customCompletionFunction)){let s=this.customCompletionFunction(n,t);if(pe(s))return s.then((r)=>{this.shim.process.nextTick(()=>{o(null,r)})}).catch((r)=>{this.shim.process.nextTick(()=>{o(r,void 0)})});return o(null,s)}else if(Np(this.customCompletionFunction))return this.customCompletionFunction(n,t,(s=o)=>this.defaultCompletion(e,t,n,s),(s)=>{o(null,s)});else return this.customCompletionFunction(n,t,(s)=>{o(null,s)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",o=this.yargs.parse(e,!0),s=this.customCompletionFunction?(r)=>this.customCompletion(e,r,n,t):(r)=>this.defaultCompletion(e,r,n,t);return pe(o)?o.then(s):s(o)}generateCompletionScript(e,t){let n=this.zshShell?pc:fc,o=this.shim.path.basename(e);if(e.match(/\.js$/))e=`./${e}`;return n=n.replace(/{{app_name}}/g,o),n=n.replace(/{{completion_command}}/g,t),n.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}}function gc(e,t,n,o){return new hc(e,t,n,o)}function Bp(e){return e.length<3}function Np(e){return e.length>3}function mc(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],o;for(o=0;o<=t.length;o++)n[o]=[o];let s;for(s=0;s<=e.length;s++)n[0][s]=s;for(o=1;o<=t.length;o++)for(s=1;s<=e.length;s++)if(t.charAt(o-1)===e.charAt(s-1))n[o][s]=n[o-1][s-1];else if(o>1&&s>1&&t.charAt(o-2)===e.charAt(s-1)&&t.charAt(o-1)===e.charAt(s-2))n[o][s]=n[o-2][s-2]+1;else n[o][s]=Math.min(n[o-1][s-1]+1,Math.min(n[o][s-1]+1,n[o-1][s]+1));return n[t.length][e.length]}var yc=["$0","--","_"];function Dc(e,t,n){let o=n.y18n.__,s=n.y18n.__n,r={};r.nonOptionCount=function(d){let f=e.getDemandedCommands(),g=d._.length+(d["--"]?d["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(f._&&(g<f._.min||g>f._.max)){if(g<f._.min)if(f._.minMsg!==void 0)t.fail(f._.minMsg?f._.minMsg.replace(/\$0/g,g.toString()).replace(/\$1/,f._.min.toString()):null);else t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",g,g.toString(),f._.min.toString()));else if(g>f._.max)if(f._.maxMsg!==void 0)t.fail(f._.maxMsg?f._.maxMsg.replace(/\$0/g,g.toString()).replace(/\$1/,f._.max.toString()):null);else t.fail(s("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",g,g.toString(),f._.max.toString()))}},r.positionalCount=function(d,f){if(f<d)t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",f,f+"",d+""))},r.requiredArguments=function(d,f){let h=null;for(let g of Object.keys(f))if(!Object.prototype.hasOwnProperty.call(d,g)||typeof d[g]>"u")h=h||{},h[g]=f[g];if(h){let g=[];for(let m of Object.keys(h)){let D=h[m];if(D&&g.indexOf(D)<0)g.push(D)}let p=g.length?`
75
- ${g.join(`
76
- `)}`:"";t.fail(s("Missing required argument: %s","Missing required arguments: %s",Object.keys(h).length,Object.keys(h).join(", ")+p))}},r.unknownArguments=function(d,f,h,g,p=!0){var m;let D=e.getInternalMethods().getCommandInstance().getCommands(),w=[],k=e.getInternalMethods().getContext();if(Object.keys(d).forEach((x)=>{if(!yc.includes(x)&&!Object.prototype.hasOwnProperty.call(h,x)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),x)&&!r.isValidAndSomeAliasIsNotNew(x,f))w.push(x)}),p&&(k.commands.length>0||D.length>0||g))d._.slice(k.commands.length).forEach((x)=>{if(!D.includes(""+x))w.push(""+x)});if(p){let C=((m=e.getDemandedCommands()._)===null||m===void 0?void 0:m.max)||0,I=k.commands.length+C;if(I<d._.length)d._.slice(I).forEach((A)=>{if(A=String(A),!k.commands.includes(A)&&!w.includes(A))w.push(A)})}if(w.length)t.fail(s("Unknown argument: %s","Unknown arguments: %s",w.length,w.map((x)=>x.trim()?x:`"${x}"`).join(", ")))},r.unknownCommands=function(d){let f=e.getInternalMethods().getCommandInstance().getCommands(),h=[],g=e.getInternalMethods().getContext();if(g.commands.length>0||f.length>0)d._.slice(g.commands.length).forEach((p)=>{if(!f.includes(""+p))h.push(""+p)});if(h.length>0)return t.fail(s("Unknown command: %s","Unknown commands: %s",h.length,h.join(", "))),!0;else return!1},r.isValidAndSomeAliasIsNotNew=function(d,f){if(!Object.prototype.hasOwnProperty.call(f,d))return!1;let h=e.parsed.newAliases;return[d,...f[d]].some((g)=>!Object.prototype.hasOwnProperty.call(h,g)||!h[d])},r.limitedChoices=function(d){let f=e.getOptions(),h={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((m)=>{if(yc.indexOf(m)===-1&&Object.prototype.hasOwnProperty.call(f.choices,m))[].concat(d[m]).forEach((D)=>{if(f.choices[m].indexOf(D)===-1&&D!==void 0)h[m]=(h[m]||[]).concat(D)})});let g=Object.keys(h);if(!g.length)return;let p=o("Invalid values:");g.forEach((m)=>{p+=`
77
- ${o("Argument: %s, Given: %s, Choices: %s",m,t.stringifiedValues(h[m]),t.stringifiedValues(f.choices[m]))}`}),t.fail(p)};let i={};r.implies=function(d,f){if(J("<string|object> [array|number|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.implies(h,d[h])});else{if(e.global(d),!i[d])i[d]=[];if(Array.isArray(f))f.forEach((h)=>r.implies(d,h));else ve(f,void 0,n),i[d].push(f)}},r.getImplied=function(){return i};function a(u,d){let f=Number(d);if(d=isNaN(f)?d:f,typeof d==="number")d=u._.length>=d;else if(d.match(/^--no-.+/))d=d.match(/^--no-(.+)/)[1],d=!Object.prototype.hasOwnProperty.call(u,d);else d=Object.prototype.hasOwnProperty.call(u,d);return d}r.implications=function(d){let f=[];if(Object.keys(i).forEach((h)=>{let g=h;(i[h]||[]).forEach((p)=>{let m=g,D=p;if(m=a(d,m),p=a(d,p),m&&!p)f.push(` ${g} -> ${D}`)})}),f.length){let h=`${o("Implications failed:")}
78
- `;f.forEach((g)=>{h+=g}),t.fail(h)}};let c={};r.conflicts=function(d,f){if(J("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.conflicts(h,d[h])});else{if(e.global(d),!c[d])c[d]=[];if(Array.isArray(f))f.forEach((h)=>r.conflicts(d,h));else c[d].push(f)}},r.getConflicting=()=>c,r.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(c[f])c[f].forEach((h)=>{if(h&&d[f]!==void 0&&d[h]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(c).forEach((f)=>{c[f].forEach((h)=>{if(h&&d[n.Parser.camelCase(f)]!==void 0&&d[n.Parser.camelCase(h)]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})})},r.recommendCommands=function(d,f){f=f.sort((m,D)=>D.length-m.length);let g=null,p=1/0;for(let m=0,D;(D=f[m])!==void 0;m++){let w=mc(d,D);if(w<=3&&w<p)p=w,g=D}if(g)t.fail(o("Did you mean %s?",g))},r.reset=function(d){return i=xt(i,(f)=>!d[f]),c=xt(c,(f)=>!d[f]),r};let l=[];return r.freeze=function(){l.push({implied:i,conflicting:c})},r.unfreeze=function(){let d=l.pop();ve(d,void 0,n),{implied:i,conflicting:c}=d},r}var ur=[],Nn;function Mn(e,t,n,o){Nn=o;let s={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return s;let r=/\.json|\..*rc$/.test(e.extends),i=null;if(!r)try{i=import.meta.resolve(e.extends)}catch(a){return e}else i=jp(t,e.extends);Mp(i),ur.push(i),s=r?JSON.parse(Nn.readFileSync(i,"utf8")):o.require(e.extends),delete e.extends,s=Mn(s,Nn.path.dirname(i),n,Nn)}return ur=[],n?wc(s,e):Object.assign({},s,e)}function Mp(e){if(ur.indexOf(e)>-1)throw new ke(`Circular extended configurations: '${e}'.`)}function jp(e,t){return Nn.path.resolve(e,t)}function wc(e,t){let n={};function o(s){return s&&typeof s==="object"&&!Array.isArray(s)}Object.assign(n,e);for(let s of Object.keys(t))if(o(t[s])&&o(n[s]))n[s]=wc(e[s],t[s]);else n[s]=t[s];return n}var K=function(e,t,n,o,s){if(o==="m")throw TypeError("Private method is not writable");if(o==="a"&&!s)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?s.call(e,n):s?s.value=n:t.set(e,n),n},y=function(e,t,n,o){if(n==="a"&&!o)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?o:n==="a"?o.call(e):o?o.value:t.get(e)},xe,qt,jn,Be,Ke,Is,St,Ht,Os,Ve,Rs,Ze,ut,qe,Qe,Ps,zt,_e,Y,vs,Ls,He,Gt,mn,Yt,Ct,Bs,Z,Xt,Vt,Zt,ee,Ns,dt,me;function Mc(e){return(t=[],n=e.process.cwd(),o)=>{let s=new jc(t,n,o,e);return Object.defineProperty(s,"argv",{get:()=>s.parse(),enumerable:!0}),s.help(),s.version(),s}}var bc=Symbol("copyDoubleDash"),kc=Symbol("copyDoubleDash"),dr=Symbol("deleteFromParserHintObject"),xc=Symbol("emitWarning"),Ec=Symbol("freeze"),Sc=Symbol("getDollarZero"),Qt=Symbol("getParserConfiguration"),Cc=Symbol("getUsageConfiguration"),fr=Symbol("guessLocale"),_c=Symbol("guessVersion"),$c=Symbol("parsePositionalNumbers"),pr=Symbol("pkgUp"),_t=Symbol("populateParserHintArray"),yn=Symbol("populateParserHintSingleValueDictionary"),hr=Symbol("populateParserHintArrayDictionary"),gr=Symbol("populateParserHintDictionary"),mr=Symbol("sanitizeKey"),yr=Symbol("setKey"),Dr=Symbol("unfreeze"),Fc=Symbol("validateAsync"),Ac=Symbol("getCommandInstance"),Tc=Symbol("getContext"),Ic=Symbol("getHasOutput"),Oc=Symbol("getLoggerInstance"),Rc=Symbol("getParseContext"),Pc=Symbol("getUsageInstance"),vc=Symbol("getValidationInstance"),Ms=Symbol("hasParseCallback"),Lc=Symbol("isGlobalContext"),en=Symbol("postProcess"),Bc=Symbol("rebase"),wr=Symbol("reset"),Wn=Symbol("runYargsParserAndExecuteCommands"),br=Symbol("runValidation"),Nc=Symbol("setHasOutput"),tn=Symbol("kTrackManuallySetKeys"),Wp="en_US";class jc{constructor(e=[],t,n,o){this.customScriptName=!1,this.parsed=!1,xe.set(this,void 0),qt.set(this,void 0),jn.set(this,{commands:[],fullCommands:[]}),Be.set(this,null),Ke.set(this,null),Is.set(this,"show-hidden"),St.set(this,null),Ht.set(this,!0),Os.set(this,{}),Ve.set(this,!0),Rs.set(this,[]),Ze.set(this,void 0),ut.set(this,{}),qe.set(this,!1),Qe.set(this,null),Ps.set(this,!0),zt.set(this,void 0),_e.set(this,""),Y.set(this,void 0),vs.set(this,void 0),Ls.set(this,{}),He.set(this,null),Gt.set(this,null),mn.set(this,{}),Yt.set(this,{}),Ct.set(this,void 0),Bs.set(this,!1),Z.set(this,void 0),Xt.set(this,!1),Vt.set(this,!1),Zt.set(this,!1),ee.set(this,void 0),Ns.set(this,{}),dt.set(this,null),me.set(this,void 0),K(this,Z,o,"f"),K(this,Ct,e,"f"),K(this,qt,t,"f"),K(this,vs,n,"f"),K(this,Ze,new cr(this),"f"),this.$0=this[Sc](),this[wr](),K(this,xe,y(this,xe,"f"),"f"),K(this,ee,y(this,ee,"f"),"f"),K(this,me,y(this,me,"f"),"f"),K(this,Y,y(this,Y,"f"),"f"),y(this,Y,"f").showHiddenOpt=y(this,Is,"f"),K(this,zt,this[kc](),"f"),y(this,Z,"f").y18n.setLocale(Wp)}addHelpOpt(e,t){if(J("[string|boolean] [string]",[e,t],arguments.length),y(this,Qe,"f"))this[dr](y(this,Qe,"f")),K(this,Qe,null,"f");if(e===!1&&t===void 0)return this;return K(this,Qe,typeof e==="string"?e:"help","f"),this.boolean(y(this,Qe,"f")),this.describe(y(this,Qe,"f"),t||y(this,ee,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(J("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:y(this,Is,"f");return this.boolean(n),this.describe(n,t||y(this,ee,"f").deferY18nLookup("Show hidden options")),y(this,Y,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return J("<object|string|array> [string|array]",[e,t],arguments.length),this[hr](this.alias.bind(this),"alias",e,t),this}array(e){return J("<array|string>",[e],arguments.length),this[_t]("array",e),this[tn](e),this}boolean(e){return J("<array|string>",[e],arguments.length),this[_t]("boolean",e),this[tn](e),this}check(e,t){return J("<function> [boolean]",[e,t],arguments.length),this.middleware((n,o)=>Kt(()=>e(n,o.getOptions()),(s)=>{if(!s)y(this,ee,"f").fail(y(this,Z,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof s==="string"||s instanceof Error)y(this,ee,"f").fail(s.toString(),s);return n},(s)=>(y(this,ee,"f").fail(s.message?s.message:s.toString(),s),n)),!1,t),this}choices(e,t){return J("<object|string|array> [string|array]",[e,t],arguments.length),this[hr](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(J("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new ke("coerce callback must be provided");for(let o of e)this.coerce(o,t);return this}else if(typeof e==="object"){for(let o of Object.keys(e))this.coerce(o,e[o]);return this}if(!t)throw new ke("coerce callback must be provided");let n=e;return y(this,Y,"f").key[n]=!0,y(this,Ze,"f").addCoerceMiddleware((o,s)=>{var r;let i=(r=s.getAliases()[n])!==null&&r!==void 0?r:[],a=[n,...i].filter((c)=>Object.prototype.hasOwnProperty.call(o,c));if(a.length===0)return o;return Kt(()=>t(o[a[0]]),(c)=>(a.forEach((l)=>{o[l]=c}),o),(c)=>{throw new ke(c.message)})},n),this}conflicts(e,t){return J("<string|object> [string|array]",[e,t],arguments.length),y(this,me,"f").conflicts(e,t),this}config(e="config",t,n){if(J("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=Mn(e,y(this,qt,"f"),this[Qt]()["deep-merge-config"]||!1,y(this,Z,"f")),y(this,Y,"f").configObjects=(y(this,Y,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||y(this,ee,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((o)=>{y(this,Y,"f").config[o]=n||!0}),this}completion(e,t,n){if(J("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(K(this,Ke,e||y(this,Ke,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(y(this,Ke,"f"),t),n)y(this,Be,"f").registerFunction(n);return this}command(e,t,n,o,s,r){return J("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,o,s,r],arguments.length),y(this,xe,"f").addHandler(e,t,n,o,s,r),this}commands(e,t,n,o,s,r){return this.command(e,t,n,o,s,r)}commandDir(e,t){J("<string> [object]",[e,t],arguments.length);let n=y(this,vs,"f")||y(this,Z,"f").require;return y(this,xe,"f").addDirectory(e,n,y(this,Z,"f").getCallerFile(),t),this}count(e){return J("<array|string>",[e],arguments.length),this[_t]("count",e),this[tn](e),this}default(e,t,n){if(J("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)ar(e,y(this,Z,"f")),y(this,Y,"f").defaultDescription[e]=n;if(typeof t==="function"){if(ar(e,y(this,Z,"f")),!y(this,Y,"f").defaultDescription[e])y(this,Y,"f").defaultDescription[e]=y(this,ee,"f").functionDescription(t);t=t.call()}return this[yn](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,o){if(J("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,o],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),y(this,Y,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:o},this}demand(e,t,n){if(Array.isArray(t))t.forEach((o)=>{ve(n,!0,y(this,Z,"f")),this.demandOption(o,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")ve(n,!0,y(this,Z,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((o)=>{ve(n,!0,y(this,Z,"f")),this.demandOption(o,n)});else if(typeof n==="string")this.demandOption(e,n);else if(n===!0||typeof n>"u")this.demandOption(e);return this}demandOption(e,t){return J("<object|string|array> [string]",[e,t],arguments.length),this[yn](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return J("<string> [string|boolean]",[e,t],arguments.length),y(this,Y,"f").deprecatedOptions[e]=t,this}describe(e,t){return J("<object|string|array> [string]",[e,t],arguments.length),this[yr](e,!0),y(this,ee,"f").describe(e,t),this}detectLocale(e){return J("<boolean>",[e],arguments.length),K(this,Ht,e,"f"),this}env(e){if(J("[string|boolean]",[e],arguments.length),e===!1)delete y(this,Y,"f").envPrefix;else y(this,Y,"f").envPrefix=e||"";return this}epilogue(e){return J("<string>",[e],arguments.length),y(this,ee,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(J("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else y(this,ee,"f").example(e,t);return this}exit(e,t){if(K(this,qe,!0,"f"),K(this,St,t,"f"),y(this,Ve,"f"))y(this,Z,"f").process.exit(e)}exitProcess(e=!0){return J("[boolean]",[e],arguments.length),K(this,Ve,e,"f"),this}fail(e){if(J("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new ke("Invalid first argument. Expected function or boolean 'false'");return y(this,ee,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(J("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,o)=>{y(this,Be,"f").getCompletion(e,(s,r)=>{if(s)o(s);else n(r)})});else return y(this,Be,"f").getCompletion(e,t)}getDemandedOptions(){return J([],0),y(this,Y,"f").demandedOptions}getDemandedCommands(){return J([],0),y(this,Y,"f").demandedCommands}getDeprecatedOptions(){return J([],0),y(this,Y,"f").deprecatedOptions}getDetectLocale(){return y(this,Ht,"f")}getExitProcess(){return y(this,Ve,"f")}getGroups(){return Object.assign({},y(this,ut,"f"),y(this,Yt,"f"))}getHelp(){if(K(this,qe,!0,"f"),!y(this,ee,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[Wn](y(this,Ct,"f"),void 0,void 0,0,!0);if(pe(t))return t.then(()=>y(this,ee,"f").help())}let e=y(this,xe,"f").runDefaultBuilderOn(this);if(pe(e))return e.then(()=>y(this,ee,"f").help())}return Promise.resolve(y(this,ee,"f").help())}getOptions(){return y(this,Y,"f")}getStrict(){return y(this,Xt,"f")}getStrictCommands(){return y(this,Vt,"f")}getStrictOptions(){return y(this,Zt,"f")}global(e,t){if(J("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)y(this,Y,"f").local=y(this,Y,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!y(this,Y,"f").local.includes(n))y(this,Y,"f").local.push(n)});return this}group(e,t){J("<string|array> <string>",[e,t],arguments.length);let n=y(this,Yt,"f")[t]||y(this,ut,"f")[t];if(y(this,Yt,"f")[t])delete y(this,Yt,"f")[t];let o={};return y(this,ut,"f")[t]=(n||[]).concat(e).filter((s)=>{if(o[s])return!1;return o[s]=!0}),this}hide(e){return J("<string>",[e],arguments.length),y(this,Y,"f").hiddenOptions.push(e),this}implies(e,t){return J("<string|object> [number|string|array]",[e,t],arguments.length),y(this,me,"f").implies(e,t),this}locale(e){if(J("[string]",[e],arguments.length),e===void 0)return this[fr](),y(this,Z,"f").y18n.getLocale();return K(this,Ht,!1,"f"),y(this,Z,"f").y18n.setLocale(e),this}middleware(e,t,n){return y(this,Ze,"f").addMiddleware(e,!!t,n)}nargs(e,t){return J("<string|object|array> [number]",[e,t],arguments.length),this[yn](this.nargs.bind(this),"narg",e,t),this}normalize(e){return J("<array|string>",[e],arguments.length),this[_t]("normalize",e),this}number(e){return J("<array|string>",[e],arguments.length),this[_t]("number",e),this[tn](e),this}option(e,t){if(J("<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[tn](e),y(this,dt,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[xc](['"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(y(this,Y,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let o=t.demand||t.required||t.require;if(o)this.demand(e,o);if(t.demandOption)this.demandOption(e,typeof t.demandOption==="string"?t.demandOption:void 0);if(t.conflicts)this.conflicts(e,t.conflicts);if("default"in t)this.default(e,t.default);if(t.implies!==void 0)this.implies(e,t.implies);if(t.nargs!==void 0)this.nargs(e,t.nargs);if(t.config)this.config(e,t.configParser);if(t.normalize)this.normalize(e);if(t.choices)this.choices(e,t.choices);if(t.coerce)this.coerce(e,t.coerce);if(t.group)this.group(e,t.group);if(t.boolean||t.type==="boolean"){if(this.boolean(e),t.alias)this.boolean(t.alias)}if(t.array||t.type==="array"){if(this.array(e),t.alias)this.array(t.alias)}if(t.number||t.type==="number"){if(this.number(e),t.alias)this.number(t.alias)}if(t.string||t.type==="string"){if(this.string(e),t.alias)this.string(t.alias)}if(t.count||t.type==="count")this.count(e);if(typeof t.global==="boolean")this.global(e,t.global);if(t.defaultDescription)y(this,Y,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let s=t.describe||t.description||t.desc,r=y(this,ee,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(r,e)||typeof s==="string")this.describe(e,s);if(t.hidden)this.hide(e);if(t.requiresArg)this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){if(J("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[Ec](),typeof e>"u")e=y(this,Ct,"f");if(typeof t==="object")K(this,Gt,t,"f"),t=n;if(typeof t==="function")K(this,He,t,"f"),t=!1;if(!t)K(this,Ct,e,"f");if(y(this,He,"f"))K(this,Ve,!1,"f");let o=this[Wn](e,!!t),s=this.parsed;if(y(this,Be,"f").setParsed(this.parsed),pe(o))return o.then((r)=>{if(y(this,He,"f"))y(this,He,"f").call(this,y(this,St,"f"),r,y(this,_e,"f"));return r}).catch((r)=>{if(y(this,He,"f"))y(this,He,"f")(r,this.parsed.argv,y(this,_e,"f"));throw r}).finally(()=>{this[Dr](),this.parsed=s});else{if(y(this,He,"f"))y(this,He,"f").call(this,y(this,St,"f"),o,y(this,_e,"f"));this[Dr](),this.parsed=s}return o}parseAsync(e,t,n){let o=this.parse(e,t,n);return!pe(o)?Promise.resolve(o):o}parseSync(e,t,n){let o=this.parse(e,t,n);if(pe(o))throw new ke(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return o}parserConfiguration(e){return J("<object>",[e],arguments.length),K(this,Ls,e,"f"),this}pkgConf(e,t){J("<string> [string]",[e,t],arguments.length);let n=null,o=this[pr](t||y(this,qt,"f"));if(o[e]&&typeof o[e]==="object")n=Mn(o[e],t||y(this,qt,"f"),this[Qt]()["deep-merge-config"]||!1,y(this,Z,"f")),y(this,Y,"f").configObjects=(y(this,Y,"f").configObjects||[]).concat(n);return this}positional(e,t){J("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=xt(t,(r,i)=>{if(r==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(r)});let o=y(this,jn,"f").fullCommands[y(this,jn,"f").fullCommands.length-1],s=o?y(this,xe,"f").cmdToParseOptions(o):{array:[],alias:{},default:{},demand:{}};return hn(s).forEach((r)=>{let i=s[r];if(Array.isArray(i)){if(i.indexOf(e)!==-1)t[r]=!0}else if(i[e]&&!(r in t))t[r]=i[e]}),this.group(e,y(this,ee,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return J("[boolean]",[e],arguments.length),K(this,Bs,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(J("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&y(this,Y,"f").narg[e])return this;else this[yn](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return J("[string] [string]",[e,t],arguments.length),e=e||this.$0,y(this,zt,"f").log(y(this,Be,"f").generateCompletionScript(e,t||y(this,Ke,"f")||"completion")),this}showHelp(e){if(J("[string|function]",[e],arguments.length),K(this,qe,!0,"f"),!y(this,ee,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[Wn](y(this,Ct,"f"),void 0,void 0,0,!0);if(pe(n))return n.then(()=>{y(this,ee,"f").showHelp(e)}),this}let t=y(this,xe,"f").runDefaultBuilderOn(this);if(pe(t))return t.then(()=>{y(this,ee,"f").showHelp(e)}),this}return y(this,ee,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return J("[boolean|string] [string]",[e,t],arguments.length),y(this,ee,"f").showHelpOnFail(e,t),this}showVersion(e){return J("[string|function]",[e],arguments.length),y(this,ee,"f").showVersion(e),this}skipValidation(e){return J("<array|string>",[e],arguments.length),this[_t]("skipValidation",e),this}strict(e){return J("[boolean]",[e],arguments.length),K(this,Xt,e!==!1,"f"),this}strictCommands(e){return J("[boolean]",[e],arguments.length),K(this,Vt,e!==!1,"f"),this}strictOptions(e){return J("[boolean]",[e],arguments.length),K(this,Zt,e!==!1,"f"),this}string(e){return J("<array|string>",[e],arguments.length),this[_t]("string",e),this[tn](e),this}terminalWidth(){return J([],0),y(this,Z,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return J("<object>",[e],arguments.length),K(this,Ht,!1,"f"),y(this,Z,"f").y18n.updateLocale(e),this}usage(e,t,n,o){if(J("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,o],arguments.length),t!==void 0)if(ve(e,null,y(this,Z,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,o);else throw new ke(".usage() description must start with $0 if being used as alias for .command()");else return y(this,ee,"f").usage(e),this}usageConfiguration(e){return J("<object>",[e],arguments.length),K(this,Ns,e,"f"),this}version(e,t,n){if(J("[boolean|string] [string] [string]",[e,t,n],arguments.length),y(this,dt,"f"))this[dr](y(this,dt,"f")),y(this,ee,"f").version(void 0),K(this,dt,null,"f");if(arguments.length===0)n=this[_c](),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 K(this,dt,typeof e==="string"?e:"version","f"),t=t||y(this,ee,"f").deferY18nLookup("Show version number"),y(this,ee,"f").version(n||void 0),this.boolean(y(this,dt,"f")),this.describe(y(this,dt,"f"),t),this}wrap(e){return J("<number|null|undefined>",[e],arguments.length),y(this,ee,"f").wrap(e),this}[(xe=new WeakMap,qt=new WeakMap,jn=new WeakMap,Be=new WeakMap,Ke=new WeakMap,Is=new WeakMap,St=new WeakMap,Ht=new WeakMap,Os=new WeakMap,Ve=new WeakMap,Rs=new WeakMap,Ze=new WeakMap,ut=new WeakMap,qe=new WeakMap,Qe=new WeakMap,Ps=new WeakMap,zt=new WeakMap,_e=new WeakMap,Y=new WeakMap,vs=new WeakMap,Ls=new WeakMap,He=new WeakMap,Gt=new WeakMap,mn=new WeakMap,Yt=new WeakMap,Ct=new WeakMap,Bs=new WeakMap,Z=new WeakMap,Xt=new WeakMap,Vt=new WeakMap,Zt=new WeakMap,ee=new WeakMap,Ns=new WeakMap,dt=new WeakMap,me=new WeakMap,bc)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[kc](){return{log:(...e)=>{if(!this[Ms]())console.log(...e);if(K(this,qe,!0,"f"),y(this,_e,"f").length)K(this,_e,y(this,_e,"f")+`
80
- `,"f");K(this,_e,y(this,_e,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[Ms]())console.error(...e);if(K(this,qe,!0,"f"),y(this,_e,"f").length)K(this,_e,y(this,_e,"f")+`
81
- `,"f");K(this,_e,y(this,_e,"f")+e.join(" "),"f")}}}[dr](e){hn(y(this,Y,"f")).forEach((t)=>{if(((o)=>o==="configObjects")(t))return;let n=y(this,Y,"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 y(this,ee,"f").getDescriptions()[e]}[xc](e,t,n){if(!y(this,Os,"f")[n])y(this,Z,"f").process.emitWarning(e,t),y(this,Os,"f")[n]=!0}[Ec](){y(this,Rs,"f").push({options:y(this,Y,"f"),configObjects:y(this,Y,"f").configObjects.slice(0),exitProcess:y(this,Ve,"f"),groups:y(this,ut,"f"),strict:y(this,Xt,"f"),strictCommands:y(this,Vt,"f"),strictOptions:y(this,Zt,"f"),completionCommand:y(this,Ke,"f"),output:y(this,_e,"f"),exitError:y(this,St,"f"),hasOutput:y(this,qe,"f"),parsed:this.parsed,parseFn:y(this,He,"f"),parseContext:y(this,Gt,"f")}),y(this,ee,"f").freeze(),y(this,me,"f").freeze(),y(this,xe,"f").freeze(),y(this,Ze,"f").freeze()}[Sc](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(y(this,Z,"f").process.argv()[0]))t=y(this,Z,"f").process.argv().slice(1,2);else t=y(this,Z,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let o=this[Bc](y(this,qt,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&o.length<n.length?o:n}).join(" ").trim(),y(this,Z,"f").getEnv("_")&&y(this,Z,"f").getProcessArgvBin()===y(this,Z,"f").getEnv("_"))e=y(this,Z,"f").getEnv("_").replace(`${y(this,Z,"f").path.dirname(y(this,Z,"f").process.execPath())}/`,"");return e}[Qt](){return y(this,Ls,"f")}[Cc](){return y(this,Ns,"f")}[fr](){if(!y(this,Ht,"f"))return;let e=y(this,Z,"f").getEnv("LC_ALL")||y(this,Z,"f").getEnv("LC_MESSAGES")||y(this,Z,"f").getEnv("LANG")||y(this,Z,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[_c](){return this[pr]().version||"unknown"}[$c](e){let t=e["--"]?e["--"]:e._;for(let n=0,o;(o=t[n])!==void 0;n++)if(y(this,Z,"f").Parser.looksLikeNumber(o)&&Number.isSafeInteger(Math.floor(parseFloat(`${o}`))))t[n]=Number(o);return e}[pr](e){let t=e||"*";if(y(this,mn,"f")[t])return y(this,mn,"f")[t];let n={};try{let o=e||y(this,Z,"f").mainFilename;if(y(this,Z,"f").path.extname(o))o=y(this,Z,"f").path.dirname(o);let s=y(this,Z,"f").findUp(o,(r,i)=>{if(i.includes("package.json"))return"package.json";else return});ve(s,void 0,y(this,Z,"f")),n=JSON.parse(y(this,Z,"f").readFileSync(s,"utf8"))}catch(o){}return y(this,mn,"f")[t]=n||{},y(this,mn,"f")[t]}[_t](e,t){t=[].concat(t),t.forEach((n)=>{n=this[mr](n),y(this,Y,"f")[e].push(n)})}[yn](e,t,n,o){this[gr](e,t,n,o,(s,r,i)=>{y(this,Y,"f")[s][r]=i})}[hr](e,t,n,o){this[gr](e,t,n,o,(s,r,i)=>{y(this,Y,"f")[s][r]=(y(this,Y,"f")[s][r]||[]).concat(i)})}[gr](e,t,n,o,s){if(Array.isArray(n))n.forEach((r)=>{e(r,o)});else if(((r)=>typeof r==="object")(n))for(let r of hn(n))e(r,n[r]);else s(t,this[mr](n),o)}[mr](e){if(e==="__proto__")return"___proto___";return e}[yr](e,t){return this[yn](this[yr].bind(this),"key",e,t),this}[Dr](){var e,t,n,o,s,r,i,a,c,l,u,d;let f=y(this,Rs,"f").pop();ve(f,void 0,y(this,Z,"f"));let h;e=this,t=this,n=this,o=this,s=this,r=this,i=this,a=this,c=this,l=this,u=this,d=this,{options:{set value(g){K(e,Y,g,"f")}}.value,configObjects:h,exitProcess:{set value(g){K(t,Ve,g,"f")}}.value,groups:{set value(g){K(n,ut,g,"f")}}.value,output:{set value(g){K(o,_e,g,"f")}}.value,exitError:{set value(g){K(s,St,g,"f")}}.value,hasOutput:{set value(g){K(r,qe,g,"f")}}.value,parsed:this.parsed,strict:{set value(g){K(i,Xt,g,"f")}}.value,strictCommands:{set value(g){K(a,Vt,g,"f")}}.value,strictOptions:{set value(g){K(c,Zt,g,"f")}}.value,completionCommand:{set value(g){K(l,Ke,g,"f")}}.value,parseFn:{set value(g){K(u,He,g,"f")}}.value,parseContext:{set value(g){K(d,Gt,g,"f")}}.value}=f,y(this,Y,"f").configObjects=h,y(this,ee,"f").unfreeze(),y(this,me,"f").unfreeze(),y(this,xe,"f").unfreeze(),y(this,Ze,"f").unfreeze()}[Fc](e,t){return Kt(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[Ac].bind(this),getContext:this[Tc].bind(this),getHasOutput:this[Ic].bind(this),getLoggerInstance:this[Oc].bind(this),getParseContext:this[Rc].bind(this),getParserConfiguration:this[Qt].bind(this),getUsageConfiguration:this[Cc].bind(this),getUsageInstance:this[Pc].bind(this),getValidationInstance:this[vc].bind(this),hasParseCallback:this[Ms].bind(this),isGlobalContext:this[Lc].bind(this),postProcess:this[en].bind(this),reset:this[wr].bind(this),runValidation:this[br].bind(this),runYargsParserAndExecuteCommands:this[Wn].bind(this),setHasOutput:this[Nc].bind(this)}}[Ac](){return y(this,xe,"f")}[Tc](){return y(this,jn,"f")}[Ic](){return y(this,qe,"f")}[Oc](){return y(this,zt,"f")}[Rc](){return y(this,Gt,"f")||{}}[Pc](){return y(this,ee,"f")}[vc](){return y(this,me,"f")}[Ms](){return!!y(this,He,"f")}[Lc](){return y(this,Ps,"f")}[en](e,t,n,o){if(n)return e;if(pe(e))return e;if(!t)e=this[bc](e);if(this[Qt]()["parse-positional-numbers"]||this[Qt]()["parse-positional-numbers"]===void 0)e=this[$c](e);if(o)e=Jt(e,this,y(this,Ze,"f").getMiddleware(),!1);return e}[wr](e={}){K(this,Y,y(this,Y,"f")||{},"f");let t={};t.local=y(this,Y,"f").local||[],t.configObjects=y(this,Y,"f").configObjects||[];let n={};t.local.forEach((r)=>{n[r]=!0,(e[r]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(y(this,Yt,"f"),Object.keys(y(this,ut,"f")).reduce((r,i)=>{let a=y(this,ut,"f")[i].filter((c)=>!(c in n));if(a.length>0)r[i]=a;return r},{})),K(this,ut,{},"f");let o=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],s=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(o.forEach((r)=>{t[r]=(y(this,Y,"f")[r]||[]).filter((i)=>!n[i])}),s.forEach((r)=>{t[r]=xt(y(this,Y,"f")[r],(i)=>!n[i])}),t.envPrefix=y(this,Y,"f").envPrefix,K(this,Y,t,"f"),K(this,ee,y(this,ee,"f")?y(this,ee,"f").reset(n):dc(this,y(this,Z,"f")),"f"),K(this,me,y(this,me,"f")?y(this,me,"f").reset(n):Dc(this,y(this,ee,"f"),y(this,Z,"f")),"f"),K(this,xe,y(this,xe,"f")?y(this,xe,"f").reset():cc(y(this,ee,"f"),y(this,me,"f"),y(this,Ze,"f"),y(this,Z,"f")),"f"),!y(this,Be,"f"))K(this,Be,gc(this,y(this,ee,"f"),y(this,xe,"f"),y(this,Z,"f")),"f");return y(this,Ze,"f").reset(),K(this,Ke,null,"f"),K(this,_e,"","f"),K(this,St,null,"f"),K(this,qe,!1,"f"),this.parsed=!1,this}[Bc](e,t){return y(this,Z,"f").path.relative(e,t)}[Wn](e,t,n,o=0,s=!1){var r,i,a,c;let l=!!n||s;e=e||y(this,Ct,"f"),y(this,Y,"f").__=y(this,Z,"f").y18n.__,y(this,Y,"f").configuration=this[Qt]();let u=!!y(this,Y,"f").configuration["populate--"],d=Object.assign({},y(this,Y,"f").configuration,{"populate--":!0}),f=y(this,Z,"f").Parser.detailed(e,Object.assign({},y(this,Y,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),h=Object.assign(f.argv,y(this,Gt,"f")),g=void 0,p=f.aliases,m=!1,D=!1;if(Object.keys(h).forEach((w)=>{if(w===y(this,Qe,"f")&&h[w])m=!0;else if(w===y(this,dt,"f")&&h[w])D=!0}),h.$0=this.$0,this.parsed=f,o===0)y(this,ee,"f").clearCachedHelpMessage();try{if(this[fr](),t)return this[en](h,u,!!n,!1);if(y(this,Qe,"f")){if([y(this,Qe,"f")].concat(p[y(this,Qe,"f")]||[]).filter((I)=>I.length>1).includes(""+h._[h._.length-1]))h._.pop(),m=!0}K(this,Ps,!1,"f");let w=y(this,xe,"f").getCommands(),k=((r=y(this,Be,"f"))===null||r===void 0?void 0:r.completionKey)?[(i=y(this,Be,"f"))===null||i===void 0?void 0:i.completionKey,...(c=this.getAliases()[(a=y(this,Be,"f"))===null||a===void 0?void 0:a.completionKey])!==null&&c!==void 0?c:[]].some((C)=>Object.prototype.hasOwnProperty.call(h,C)):!1,x=m||k||s;if(h._.length){if(w.length){let C;for(let I=o||0,A;h._[I]!==void 0;I++)if(A=String(h._[I]),w.includes(A)&&A!==y(this,Ke,"f")){let M=y(this,xe,"f").runCommand(A,this,f,I+1,s,m||D||s);return this[en](M,u,!!n,!1)}else if(!C&&A!==y(this,Ke,"f")){C=A;break}if(!y(this,xe,"f").hasDefaultCommand()&&y(this,Bs,"f")&&C&&!x)y(this,me,"f").recommendCommands(C,w)}if(y(this,Ke,"f")&&h._.includes(y(this,Ke,"f"))&&!k){if(y(this,Ve,"f"))Et(!0);this.showCompletionScript(),this.exit(0)}}if(y(this,xe,"f").hasDefaultCommand()&&!x){let C=y(this,xe,"f").runCommand(null,this,f,0,s,m||D||s);return this[en](C,u,!!n,!1)}if(k){if(y(this,Ve,"f"))Et(!0);e=[].concat(e);let C=e.slice(e.indexOf(`--${y(this,Be,"f").completionKey}`)+1);return y(this,Be,"f").getCompletion(C,(I,A)=>{if(I)throw new ke(I.message);(A||[]).forEach((M)=>{y(this,zt,"f").log(M)}),this.exit(0)}),this[en](h,!u,!!n,!1)}if(!y(this,qe,"f")){if(m){if(y(this,Ve,"f"))Et(!0);l=!0,this.showHelp((C)=>{y(this,zt,"f").log(C),this.exit(0)})}else if(D){if(y(this,Ve,"f"))Et(!0);l=!0,y(this,ee,"f").showVersion("log"),this.exit(0)}}if(!l&&y(this,Y,"f").skipValidation.length>0)l=Object.keys(h).some((C)=>y(this,Y,"f").skipValidation.indexOf(C)>=0&&h[C]===!0);if(!l){if(f.error)throw new ke(f.error.message);if(!k){let C=this[br](p,{},f.error);if(!n)g=Jt(h,this,y(this,Ze,"f").getMiddleware(),!0);if(g=this[Fc](C,g!==null&&g!==void 0?g:h),pe(g)&&!n)g=g.then(()=>Jt(h,this,y(this,Ze,"f").getMiddleware(),!1))}}}catch(w){if(w instanceof ke)y(this,ee,"f").fail(w.message,w);else throw w}return this[en](g!==null&&g!==void 0?g:h,u,!!n,!0)}[br](e,t,n,o){let s={...this.getDemandedOptions()};return(r)=>{if(n)throw new ke(n.message);y(this,me,"f").nonOptionCount(r),y(this,me,"f").requiredArguments(r,s);let i=!1;if(y(this,Vt,"f"))i=y(this,me,"f").unknownCommands(r);if(y(this,Xt,"f")&&!i)y(this,me,"f").unknownArguments(r,e,t,!!o);else if(y(this,Zt,"f"))y(this,me,"f").unknownArguments(r,e,{},!1,!1);y(this,me,"f").limitedChoices(r),y(this,me,"f").implications(r),y(this,me,"f").conflicting(r)}}[Nc](){K(this,qe,!0,"f")}[tn](e){if(typeof e==="string")y(this,Y,"f").key[e]=!0;else for(let t of e)y(this,Y,"f").key[t]=!0}}function lc(e){return!!e&&typeof e.getInternalMethods==="function"}var Up=Mc(ir),Wc=Up;var Jp=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,Kp=/[\t\n\v\f\r (*_~]/;function qp(e){let t=e.split(""),n=(s,r)=>{for(let i=s;i<r;i++)if(t[i]!==`
74
+ `;class Dc{constructor(e,t,n,o){var s,r,i;this.yargs=e,this.usage=t,this.command=n,this.shim=o,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((s=this.shim.getEnv("SHELL"))===null||s===void 0?void 0:s.includes("zsh"))||((r=this.shim.getEnv("ZSH_NAME"))===null||r===void 0?void 0:r.includes("zsh")))!==null&&i!==void 0?i:!1}defaultCompletion(e,t,n,o){let s=this.command.getCommandHandlers();for(let i=0,a=e.length;i<a;++i)if(s[e[i]]&&s[e[i]].builder){let c=s[e[i]].builder;if(Is(c)){this.indexAfterLastReset=i+1;let l=this.yargs.getInternalMethods().reset();return c(l,!0),l.argv}}let r=[];this.commandCompletions(r,e,n),this.optionCompletions(r,e,t,n),this.choicesFromOptionsCompletions(r,e,t,n),this.choicesFromPositionalsCompletions(r,e,t,n),o(null,r)}commandCompletions(e,t,n){let o=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&o[o.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((s)=>{let r=kt(s[0]).cmd;if(t.indexOf(r)===-1)if(!this.zshShell)e.push(r);else{let i=s[1]||"";e.push(r.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,o){if((o.match(/^-/)||o===""&&e.length===0)&&!this.previousArgHasChoices(t)){let s=this.yargs.getOptions(),r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(s.key).forEach((i)=>{let a=!!s.configuration["boolean-negation"]&&s.boolean.includes(i);if(!r.includes(i)&&!s.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,a))this.completeOptionKey(i,e,o,a&&!!s.default[i])})}}choicesFromOptionsCompletions(e,t,n,o){if(this.previousArgHasChoices(t)){let s=this.getPreviousArgChoices(t);if(s&&s.length>0)e.push(...s.map((r)=>r.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,o){if(o===""&&e.length>0&&this.previousArgHasChoices(t))return;let s=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=s[n._.length-r-1];if(!i)return;let a=this.yargs.getOptions().choices[i]||[];for(let c of a)if(c.startsWith(o))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 o=t.replace(/^-+/,""),s=this.yargs.getOptions(),r=[o,...this.yargs.getAliases()[o]||[]],i;for(let a of r)if(Object.prototype.hasOwnProperty.call(s.key,a)&&Array.isArray(s.choices[a])){i=s.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 o=(s)=>e.indexOf((/^[^0-9]$/.test(s)?"-":"--")+s)!==-1;if(o(t))return!0;if(n&&o(`no-${t}`))return!0;if(this.aliases){for(let s of this.aliases[t])if(o(s))return!0}return!1}completeOptionKey(e,t,n,o){var s,r,i,a;let c=e;if(this.zshShell){let p=this.usage.getDescriptions(),h=(r=(s=this===null||this===void 0?void 0:this.aliases)===null||s===void 0?void 0:s[e])===null||r===void 0?void 0:r.find((g)=>{let w=p[g];return typeof w==="string"&&w.length>0}),y=h?p[h]:void 0,f=(a=(i=p[e])!==null&&i!==void 0?i:y)!==null&&a!==void 0?a:"";c=`${e.replace(/:/g,"\\:")}:${f.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let l=(p)=>/^--/.test(p),u=(p)=>/^[^0-9]$/.test(p),d=!l(n)&&u(e)?"-":"--";if(t.push(d+c),o)t.push(d+"no-"+c)}customCompletion(e,t,n,o){if(Re(this.customCompletionFunction,null,this.shim),Yp(this.customCompletionFunction)){let s=this.customCompletionFunction(n,t);if(ce(s))return s.then((r)=>{this.shim.process.nextTick(()=>{o(null,r)})}).catch((r)=>{this.shim.process.nextTick(()=>{o(r,void 0)})});return o(null,s)}else if(Xp(this.customCompletionFunction))return this.customCompletionFunction(n,t,(s=o)=>this.defaultCompletion(e,t,n,s),(s)=>{o(null,s)});else return this.customCompletionFunction(n,t,(s)=>{o(null,s)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",o=this.yargs.parse(e,!0),s=this.customCompletionFunction?(r)=>this.customCompletion(e,r,n,t):(r)=>this.defaultCompletion(e,r,n,t);return ce(o)?o.then(s):s(o)}generateCompletionScript(e,t){let n=this.zshShell?wc:yc,o=this.shim.path.basename(e);if(e.match(/\.js$/))e=`./${e}`;return n=n.replace(/{{app_name}}/g,o),n=n.replace(/{{completion_command}}/g,t),n.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}}function bc(e,t,n,o){return new Dc(e,t,n,o)}function Yp(e){return e.length<3}function Xp(e){return e.length>3}function kc(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],o;for(o=0;o<=t.length;o++)n[o]=[o];let s;for(s=0;s<=e.length;s++)n[0][s]=s;for(o=1;o<=t.length;o++)for(s=1;s<=e.length;s++)if(t.charAt(o-1)===e.charAt(s-1))n[o][s]=n[o-1][s-1];else if(o>1&&s>1&&t.charAt(o-2)===e.charAt(s-1)&&t.charAt(o-1)===e.charAt(s-2))n[o][s]=n[o-2][s-2]+1;else n[o][s]=Math.min(n[o-1][s-1]+1,Math.min(n[o][s-1]+1,n[o-1][s]+1));return n[t.length][e.length]}var xc=["$0","--","_"];function Ec(e,t,n){let o=n.y18n.__,s=n.y18n.__n,r={};r.nonOptionCount=function(d){let p=e.getDemandedCommands(),y=d._.length+(d["--"]?d["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(p._&&(y<p._.min||y>p._.max)){if(y<p._.min)if(p._.minMsg!==void 0)t.fail(p._.minMsg?p._.minMsg.replace(/\$0/g,y.toString()).replace(/\$1/,p._.min.toString()):null);else t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",y,y.toString(),p._.min.toString()));else if(y>p._.max)if(p._.maxMsg!==void 0)t.fail(p._.maxMsg?p._.maxMsg.replace(/\$0/g,y.toString()).replace(/\$1/,p._.max.toString()):null);else t.fail(s("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",y,y.toString(),p._.max.toString()))}},r.positionalCount=function(d,p){if(p<d)t.fail(s("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",p,p+"",d+""))},r.requiredArguments=function(d,p){let h=null;for(let y of Object.keys(p))if(!Object.prototype.hasOwnProperty.call(d,y)||typeof d[y]>"u")h=h||{},h[y]=p[y];if(h){let y=[];for(let g of Object.keys(h)){let w=h[g];if(w&&y.indexOf(w)<0)y.push(w)}let f=y.length?`
75
+ ${y.join(`
76
+ `)}`:"";t.fail(s("Missing required argument: %s","Missing required arguments: %s",Object.keys(h).length,Object.keys(h).join(", ")+f))}},r.unknownArguments=function(d,p,h,y,f=!0){var g;let w=e.getInternalMethods().getCommandInstance().getCommands(),D=[],k=e.getInternalMethods().getContext();if(Object.keys(d).forEach((S)=>{if(!xc.includes(S)&&!Object.prototype.hasOwnProperty.call(h,S)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),S)&&!r.isValidAndSomeAliasIsNotNew(S,p))D.push(S)}),f&&(k.commands.length>0||w.length>0||y))d._.slice(k.commands.length).forEach((S)=>{if(!w.includes(""+S))D.push(""+S)});if(f){let C=((g=e.getDemandedCommands()._)===null||g===void 0?void 0:g.max)||0,F=k.commands.length+C;if(F<d._.length)d._.slice(F).forEach((A)=>{if(A=String(A),!k.commands.includes(A)&&!D.includes(A))D.push(A)})}if(D.length)t.fail(s("Unknown argument: %s","Unknown arguments: %s",D.length,D.map((S)=>S.trim()?S:`"${S}"`).join(", ")))},r.unknownCommands=function(d){let p=e.getInternalMethods().getCommandInstance().getCommands(),h=[],y=e.getInternalMethods().getContext();if(y.commands.length>0||p.length>0)d._.slice(y.commands.length).forEach((f)=>{if(!p.includes(""+f))h.push(""+f)});if(h.length>0)return t.fail(s("Unknown command: %s","Unknown commands: %s",h.length,h.join(", "))),!0;else return!1},r.isValidAndSomeAliasIsNotNew=function(d,p){if(!Object.prototype.hasOwnProperty.call(p,d))return!1;let h=e.parsed.newAliases;return[d,...p[d]].some((y)=>!Object.prototype.hasOwnProperty.call(h,y)||!h[d])},r.limitedChoices=function(d){let p=e.getOptions(),h={};if(!Object.keys(p.choices).length)return;Object.keys(d).forEach((g)=>{if(xc.indexOf(g)===-1&&Object.prototype.hasOwnProperty.call(p.choices,g))[].concat(d[g]).forEach((w)=>{if(p.choices[g].indexOf(w)===-1&&w!==void 0)h[g]=(h[g]||[]).concat(w)})});let y=Object.keys(h);if(!y.length)return;let f=o("Invalid values:");y.forEach((g)=>{f+=`
77
+ ${o("Argument: %s, Given: %s, Choices: %s",g,t.stringifiedValues(h[g]),t.stringifiedValues(p.choices[g]))}`}),t.fail(f)};let i={};r.implies=function(d,p){if(J("<string|object> [array|number|string]",[d,p],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.implies(h,d[h])});else{if(e.global(d),!i[d])i[d]=[];if(Array.isArray(p))p.forEach((h)=>r.implies(d,h));else Re(p,void 0,n),i[d].push(p)}},r.getImplied=function(){return i};function a(u,d){let p=Number(d);if(d=isNaN(p)?d:p,typeof d==="number")d=u._.length>=d;else if(d.match(/^--no-.+/))d=d.match(/^--no-(.+)/)[1],d=!Object.prototype.hasOwnProperty.call(u,d);else d=Object.prototype.hasOwnProperty.call(u,d);return d}r.implications=function(d){let p=[];if(Object.keys(i).forEach((h)=>{let y=h;(i[h]||[]).forEach((f)=>{let g=y,w=f;if(g=a(d,g),f=a(d,f),g&&!f)p.push(` ${y} -> ${w}`)})}),p.length){let h=`${o("Implications failed:")}
78
+ `;p.forEach((y)=>{h+=y}),t.fail(h)}};let c={};r.conflicts=function(d,p){if(J("<string|object> [array|string]",[d,p],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.conflicts(h,d[h])});else{if(e.global(d),!c[d])c[d]=[];if(Array.isArray(p))p.forEach((h)=>r.conflicts(d,h));else c[d].push(p)}},r.getConflicting=()=>c,r.conflicting=function(d){if(Object.keys(d).forEach((p)=>{if(c[p])c[p].forEach((h)=>{if(h&&d[p]!==void 0&&d[h]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",p,h))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(c).forEach((p)=>{c[p].forEach((h)=>{if(h&&d[n.Parser.camelCase(p)]!==void 0&&d[n.Parser.camelCase(h)]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",p,h))})})},r.recommendCommands=function(d,p){p=p.sort((g,w)=>w.length-g.length);let y=null,f=1/0;for(let g=0,w;(w=p[g])!==void 0;g++){let D=kc(d,w);if(D<=3&&D<f)f=D,y=w}if(y)t.fail(o("Did you mean %s?",y))},r.reset=function(d){return i=xt(i,(p)=>!d[p]),c=xt(c,(p)=>!d[p]),r};let l=[];return r.freeze=function(){l.push({implied:i,conflicting:c})},r.unfreeze=function(){let d=l.pop();Re(d,void 0,n),{implied:i,conflicting:c}=d},r}var hr=[],Mn;function jn(e,t,n,o){Mn=o;let s={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return s;let r=/\.json|\..*rc$/.test(e.extends),i=null;if(!r)try{i=import.meta.resolve(e.extends)}catch(a){return e}else i=Zp(t,e.extends);Vp(i),hr.push(i),s=r?JSON.parse(Mn.readFileSync(i,"utf8")):o.require(e.extends),delete e.extends,s=jn(s,Mn.path.dirname(i),n,Mn)}return hr=[],n?Sc(s,e):Object.assign({},s,e)}function Vp(e){if(hr.indexOf(e)>-1)throw new ye(`Circular extended configurations: '${e}'.`)}function Zp(e,t){return Mn.path.resolve(e,t)}function Sc(e,t){let n={};function o(s){return s&&typeof s==="object"&&!Array.isArray(s)}Object.assign(n,e);for(let s of Object.keys(t))if(o(t[s])&&o(n[s]))n[s]=Sc(e[s],t[s]);else n[s]=t[s];return n}var K=function(e,t,n,o,s){if(o==="m")throw TypeError("Private method is not writable");if(o==="a"&&!s)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?s.call(e,n):s?s.value=n:t.set(e,n),n},m=function(e,t,n,o){if(n==="a"&&!o)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?o:n==="a"?o.call(e):o?o.value:t.get(e)},we,Ht,Wn,ve,je,Rs,St,zt,Ps,Ge,vs,Ye,at,We,Xe,Bs,Gt,xe,z,Ls,Ns,Ue,Yt,yn,Xt,Ct,Ms,X,Vt,Zt,Qt,Q,js,ct,de;function Kc(e){return(t=[],n=e.process.cwd(),o)=>{let s=new qc(t,n,o,e);return Object.defineProperty(s,"argv",{get:()=>s.parse(),enumerable:!0}),s.help(),s.version(),s}}var Cc=Symbol("copyDoubleDash"),_c=Symbol("copyDoubleDash"),gr=Symbol("deleteFromParserHintObject"),$c=Symbol("emitWarning"),Fc=Symbol("freeze"),Ac=Symbol("getDollarZero"),en=Symbol("getParserConfiguration"),Tc=Symbol("getUsageConfiguration"),mr=Symbol("guessLocale"),Ic=Symbol("guessVersion"),Oc=Symbol("parsePositionalNumbers"),yr=Symbol("pkgUp"),_t=Symbol("populateParserHintArray"),wn=Symbol("populateParserHintSingleValueDictionary"),wr=Symbol("populateParserHintArrayDictionary"),Dr=Symbol("populateParserHintDictionary"),br=Symbol("sanitizeKey"),kr=Symbol("setKey"),xr=Symbol("unfreeze"),Rc=Symbol("validateAsync"),Pc=Symbol("getCommandInstance"),vc=Symbol("getContext"),Bc=Symbol("getHasOutput"),Lc=Symbol("getLoggerInstance"),Nc=Symbol("getParseContext"),Mc=Symbol("getUsageInstance"),jc=Symbol("getValidationInstance"),Ws=Symbol("hasParseCallback"),Wc=Symbol("isGlobalContext"),tn=Symbol("postProcess"),Uc=Symbol("rebase"),Er=Symbol("reset"),Un=Symbol("runYargsParserAndExecuteCommands"),Sr=Symbol("runValidation"),Jc=Symbol("setHasOutput"),nn=Symbol("kTrackManuallySetKeys"),Qp="en_US";class qc{constructor(e=[],t,n,o){this.customScriptName=!1,this.parsed=!1,we.set(this,void 0),Ht.set(this,void 0),Wn.set(this,{commands:[],fullCommands:[]}),ve.set(this,null),je.set(this,null),Rs.set(this,"show-hidden"),St.set(this,null),zt.set(this,!0),Ps.set(this,{}),Ge.set(this,!0),vs.set(this,[]),Ye.set(this,void 0),at.set(this,{}),We.set(this,!1),Xe.set(this,null),Bs.set(this,!0),Gt.set(this,void 0),xe.set(this,""),z.set(this,void 0),Ls.set(this,void 0),Ns.set(this,{}),Ue.set(this,null),Yt.set(this,null),yn.set(this,{}),Xt.set(this,{}),Ct.set(this,void 0),Ms.set(this,!1),X.set(this,void 0),Vt.set(this,!1),Zt.set(this,!1),Qt.set(this,!1),Q.set(this,void 0),js.set(this,{}),ct.set(this,null),de.set(this,void 0),K(this,X,o,"f"),K(this,Ct,e,"f"),K(this,Ht,t,"f"),K(this,Ls,n,"f"),K(this,Ye,new fr(this),"f"),this.$0=this[Ac](),this[Er](),K(this,we,m(this,we,"f"),"f"),K(this,Q,m(this,Q,"f"),"f"),K(this,de,m(this,de,"f"),"f"),K(this,z,m(this,z,"f"),"f"),m(this,z,"f").showHiddenOpt=m(this,Rs,"f"),K(this,Gt,this[_c](),"f"),m(this,X,"f").y18n.setLocale(Qp)}addHelpOpt(e,t){if(J("[string|boolean] [string]",[e,t],arguments.length),m(this,Xe,"f"))this[gr](m(this,Xe,"f")),K(this,Xe,null,"f");if(e===!1&&t===void 0)return this;return K(this,Xe,typeof e==="string"?e:"help","f"),this.boolean(m(this,Xe,"f")),this.describe(m(this,Xe,"f"),t||m(this,Q,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(J("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:m(this,Rs,"f");return this.boolean(n),this.describe(n,t||m(this,Q,"f").deferY18nLookup("Show hidden options")),m(this,z,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return J("<object|string|array> [string|array]",[e,t],arguments.length),this[wr](this.alias.bind(this),"alias",e,t),this}array(e){return J("<array|string>",[e],arguments.length),this[_t]("array",e),this[nn](e),this}boolean(e){return J("<array|string>",[e],arguments.length),this[_t]("boolean",e),this[nn](e),this}check(e,t){return J("<function> [boolean]",[e,t],arguments.length),this.middleware((n,o)=>qt(()=>e(n,o.getOptions()),(s)=>{if(!s)m(this,Q,"f").fail(m(this,X,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof s==="string"||s instanceof Error)m(this,Q,"f").fail(s.toString(),s);return n},(s)=>(m(this,Q,"f").fail(s.message?s.message:s.toString(),s),n)),!1,t),this}choices(e,t){return J("<object|string|array> [string|array]",[e,t],arguments.length),this[wr](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(J("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new ye("coerce callback must be provided");for(let o of e)this.coerce(o,t);return this}else if(typeof e==="object"){for(let o of Object.keys(e))this.coerce(o,e[o]);return this}if(!t)throw new ye("coerce callback must be provided");let n=e;return m(this,z,"f").key[n]=!0,m(this,Ye,"f").addCoerceMiddleware((o,s)=>{var r;let i=(r=s.getAliases()[n])!==null&&r!==void 0?r:[],a=[n,...i].filter((c)=>Object.prototype.hasOwnProperty.call(o,c));if(a.length===0)return o;return qt(()=>t(o[a[0]]),(c)=>(a.forEach((l)=>{o[l]=c}),o),(c)=>{throw new ye(c.message)})},n),this}conflicts(e,t){return J("<string|object> [string|array]",[e,t],arguments.length),m(this,de,"f").conflicts(e,t),this}config(e="config",t,n){if(J("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=jn(e,m(this,Ht,"f"),this[en]()["deep-merge-config"]||!1,m(this,X,"f")),m(this,z,"f").configObjects=(m(this,z,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||m(this,Q,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((o)=>{m(this,z,"f").config[o]=n||!0}),this}completion(e,t,n){if(J("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(K(this,je,e||m(this,je,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(m(this,je,"f"),t),n)m(this,ve,"f").registerFunction(n);return this}command(e,t,n,o,s,r){return J("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,o,s,r],arguments.length),m(this,we,"f").addHandler(e,t,n,o,s,r),this}commands(e,t,n,o,s,r){return this.command(e,t,n,o,s,r)}commandDir(e,t){J("<string> [object]",[e,t],arguments.length);let n=m(this,Ls,"f")||m(this,X,"f").require;return m(this,we,"f").addDirectory(e,n,m(this,X,"f").getCallerFile(),t),this}count(e){return J("<array|string>",[e],arguments.length),this[_t]("count",e),this[nn](e),this}default(e,t,n){if(J("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)dr(e,m(this,X,"f")),m(this,z,"f").defaultDescription[e]=n;if(typeof t==="function"){if(dr(e,m(this,X,"f")),!m(this,z,"f").defaultDescription[e])m(this,z,"f").defaultDescription[e]=m(this,Q,"f").functionDescription(t);t=t.call()}return this[wn](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,o){if(J("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,o],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),m(this,z,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:o},this}demand(e,t,n){if(Array.isArray(t))t.forEach((o)=>{Re(n,!0,m(this,X,"f")),this.demandOption(o,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")Re(n,!0,m(this,X,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((o)=>{Re(n,!0,m(this,X,"f")),this.demandOption(o,n)});else if(typeof n==="string")this.demandOption(e,n);else if(n===!0||typeof n>"u")this.demandOption(e);return this}demandOption(e,t){return J("<object|string|array> [string]",[e,t],arguments.length),this[wn](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return J("<string> [string|boolean]",[e,t],arguments.length),m(this,z,"f").deprecatedOptions[e]=t,this}describe(e,t){return J("<object|string|array> [string]",[e,t],arguments.length),this[kr](e,!0),m(this,Q,"f").describe(e,t),this}detectLocale(e){return J("<boolean>",[e],arguments.length),K(this,zt,e,"f"),this}env(e){if(J("[string|boolean]",[e],arguments.length),e===!1)delete m(this,z,"f").envPrefix;else m(this,z,"f").envPrefix=e||"";return this}epilogue(e){return J("<string>",[e],arguments.length),m(this,Q,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(J("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else m(this,Q,"f").example(e,t);return this}exit(e,t){if(K(this,We,!0,"f"),K(this,St,t,"f"),m(this,Ge,"f"))m(this,X,"f").process.exit(e)}exitProcess(e=!0){return J("[boolean]",[e],arguments.length),K(this,Ge,e,"f"),this}fail(e){if(J("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new ye("Invalid first argument. Expected function or boolean 'false'");return m(this,Q,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(J("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,o)=>{m(this,ve,"f").getCompletion(e,(s,r)=>{if(s)o(s);else n(r)})});else return m(this,ve,"f").getCompletion(e,t)}getDemandedOptions(){return J([],0),m(this,z,"f").demandedOptions}getDemandedCommands(){return J([],0),m(this,z,"f").demandedCommands}getDeprecatedOptions(){return J([],0),m(this,z,"f").deprecatedOptions}getDetectLocale(){return m(this,zt,"f")}getExitProcess(){return m(this,Ge,"f")}getGroups(){return Object.assign({},m(this,at,"f"),m(this,Xt,"f"))}getHelp(){if(K(this,We,!0,"f"),!m(this,Q,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[Un](m(this,Ct,"f"),void 0,void 0,0,!0);if(ce(t))return t.then(()=>m(this,Q,"f").help())}let e=m(this,we,"f").runDefaultBuilderOn(this);if(ce(e))return e.then(()=>m(this,Q,"f").help())}return Promise.resolve(m(this,Q,"f").help())}getOptions(){return m(this,z,"f")}getStrict(){return m(this,Vt,"f")}getStrictCommands(){return m(this,Zt,"f")}getStrictOptions(){return m(this,Qt,"f")}global(e,t){if(J("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)m(this,z,"f").local=m(this,z,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!m(this,z,"f").local.includes(n))m(this,z,"f").local.push(n)});return this}group(e,t){J("<string|array> <string>",[e,t],arguments.length);let n=m(this,Xt,"f")[t]||m(this,at,"f")[t];if(m(this,Xt,"f")[t])delete m(this,Xt,"f")[t];let o={};return m(this,at,"f")[t]=(n||[]).concat(e).filter((s)=>{if(o[s])return!1;return o[s]=!0}),this}hide(e){return J("<string>",[e],arguments.length),m(this,z,"f").hiddenOptions.push(e),this}implies(e,t){return J("<string|object> [number|string|array]",[e,t],arguments.length),m(this,de,"f").implies(e,t),this}locale(e){if(J("[string]",[e],arguments.length),e===void 0)return this[mr](),m(this,X,"f").y18n.getLocale();return K(this,zt,!1,"f"),m(this,X,"f").y18n.setLocale(e),this}middleware(e,t,n){return m(this,Ye,"f").addMiddleware(e,!!t,n)}nargs(e,t){return J("<string|object|array> [number]",[e,t],arguments.length),this[wn](this.nargs.bind(this),"narg",e,t),this}normalize(e){return J("<array|string>",[e],arguments.length),this[_t]("normalize",e),this}number(e){return J("<array|string>",[e],arguments.length),this[_t]("number",e),this[nn](e),this}option(e,t){if(J("<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[nn](e),m(this,ct,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[$c](['"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(m(this,z,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let o=t.demand||t.required||t.require;if(o)this.demand(e,o);if(t.demandOption)this.demandOption(e,typeof t.demandOption==="string"?t.demandOption:void 0);if(t.conflicts)this.conflicts(e,t.conflicts);if("default"in t)this.default(e,t.default);if(t.implies!==void 0)this.implies(e,t.implies);if(t.nargs!==void 0)this.nargs(e,t.nargs);if(t.config)this.config(e,t.configParser);if(t.normalize)this.normalize(e);if(t.choices)this.choices(e,t.choices);if(t.coerce)this.coerce(e,t.coerce);if(t.group)this.group(e,t.group);if(t.boolean||t.type==="boolean"){if(this.boolean(e),t.alias)this.boolean(t.alias)}if(t.array||t.type==="array"){if(this.array(e),t.alias)this.array(t.alias)}if(t.number||t.type==="number"){if(this.number(e),t.alias)this.number(t.alias)}if(t.string||t.type==="string"){if(this.string(e),t.alias)this.string(t.alias)}if(t.count||t.type==="count")this.count(e);if(typeof t.global==="boolean")this.global(e,t.global);if(t.defaultDescription)m(this,z,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let s=t.describe||t.description||t.desc,r=m(this,Q,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(r,e)||typeof s==="string")this.describe(e,s);if(t.hidden)this.hide(e);if(t.requiresArg)this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){if(J("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[Fc](),typeof e>"u")e=m(this,Ct,"f");if(typeof t==="object")K(this,Yt,t,"f"),t=n;if(typeof t==="function")K(this,Ue,t,"f"),t=!1;if(!t)K(this,Ct,e,"f");if(m(this,Ue,"f"))K(this,Ge,!1,"f");let o=this[Un](e,!!t),s=this.parsed;if(m(this,ve,"f").setParsed(this.parsed),ce(o))return o.then((r)=>{if(m(this,Ue,"f"))m(this,Ue,"f").call(this,m(this,St,"f"),r,m(this,xe,"f"));return r}).catch((r)=>{if(m(this,Ue,"f"))m(this,Ue,"f")(r,this.parsed.argv,m(this,xe,"f"));throw r}).finally(()=>{this[xr](),this.parsed=s});else{if(m(this,Ue,"f"))m(this,Ue,"f").call(this,m(this,St,"f"),o,m(this,xe,"f"));this[xr](),this.parsed=s}return o}parseAsync(e,t,n){let o=this.parse(e,t,n);return!ce(o)?Promise.resolve(o):o}parseSync(e,t,n){let o=this.parse(e,t,n);if(ce(o))throw new ye(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return o}parserConfiguration(e){return J("<object>",[e],arguments.length),K(this,Ns,e,"f"),this}pkgConf(e,t){J("<string> [string]",[e,t],arguments.length);let n=null,o=this[yr](t||m(this,Ht,"f"));if(o[e]&&typeof o[e]==="object")n=jn(o[e],t||m(this,Ht,"f"),this[en]()["deep-merge-config"]||!1,m(this,X,"f")),m(this,z,"f").configObjects=(m(this,z,"f").configObjects||[]).concat(n);return this}positional(e,t){J("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=xt(t,(r,i)=>{if(r==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(r)});let o=m(this,Wn,"f").fullCommands[m(this,Wn,"f").fullCommands.length-1],s=o?m(this,we,"f").cmdToParseOptions(o):{array:[],alias:{},default:{},demand:{}};return gn(s).forEach((r)=>{let i=s[r];if(Array.isArray(i)){if(i.indexOf(e)!==-1)t[r]=!0}else if(i[e]&&!(r in t))t[r]=i[e]}),this.group(e,m(this,Q,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return J("[boolean]",[e],arguments.length),K(this,Ms,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(J("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&m(this,z,"f").narg[e])return this;else this[wn](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return J("[string] [string]",[e,t],arguments.length),e=e||this.$0,m(this,Gt,"f").log(m(this,ve,"f").generateCompletionScript(e,t||m(this,je,"f")||"completion")),this}showHelp(e){if(J("[string|function]",[e],arguments.length),K(this,We,!0,"f"),!m(this,Q,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[Un](m(this,Ct,"f"),void 0,void 0,0,!0);if(ce(n))return n.then(()=>{m(this,Q,"f").showHelp(e)}),this}let t=m(this,we,"f").runDefaultBuilderOn(this);if(ce(t))return t.then(()=>{m(this,Q,"f").showHelp(e)}),this}return m(this,Q,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return J("[boolean|string] [string]",[e,t],arguments.length),m(this,Q,"f").showHelpOnFail(e,t),this}showVersion(e){return J("[string|function]",[e],arguments.length),m(this,Q,"f").showVersion(e),this}skipValidation(e){return J("<array|string>",[e],arguments.length),this[_t]("skipValidation",e),this}strict(e){return J("[boolean]",[e],arguments.length),K(this,Vt,e!==!1,"f"),this}strictCommands(e){return J("[boolean]",[e],arguments.length),K(this,Zt,e!==!1,"f"),this}strictOptions(e){return J("[boolean]",[e],arguments.length),K(this,Qt,e!==!1,"f"),this}string(e){return J("<array|string>",[e],arguments.length),this[_t]("string",e),this[nn](e),this}terminalWidth(){return J([],0),m(this,X,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return J("<object>",[e],arguments.length),K(this,zt,!1,"f"),m(this,X,"f").y18n.updateLocale(e),this}usage(e,t,n,o){if(J("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,o],arguments.length),t!==void 0)if(Re(e,null,m(this,X,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,o);else throw new ye(".usage() description must start with $0 if being used as alias for .command()");else return m(this,Q,"f").usage(e),this}usageConfiguration(e){return J("<object>",[e],arguments.length),K(this,js,e,"f"),this}version(e,t,n){if(J("[boolean|string] [string] [string]",[e,t,n],arguments.length),m(this,ct,"f"))this[gr](m(this,ct,"f")),m(this,Q,"f").version(void 0),K(this,ct,null,"f");if(arguments.length===0)n=this[Ic](),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 K(this,ct,typeof e==="string"?e:"version","f"),t=t||m(this,Q,"f").deferY18nLookup("Show version number"),m(this,Q,"f").version(n||void 0),this.boolean(m(this,ct,"f")),this.describe(m(this,ct,"f"),t),this}wrap(e){return J("<number|null|undefined>",[e],arguments.length),m(this,Q,"f").wrap(e),this}[(we=new WeakMap,Ht=new WeakMap,Wn=new WeakMap,ve=new WeakMap,je=new WeakMap,Rs=new WeakMap,St=new WeakMap,zt=new WeakMap,Ps=new WeakMap,Ge=new WeakMap,vs=new WeakMap,Ye=new WeakMap,at=new WeakMap,We=new WeakMap,Xe=new WeakMap,Bs=new WeakMap,Gt=new WeakMap,xe=new WeakMap,z=new WeakMap,Ls=new WeakMap,Ns=new WeakMap,Ue=new WeakMap,Yt=new WeakMap,yn=new WeakMap,Xt=new WeakMap,Ct=new WeakMap,Ms=new WeakMap,X=new WeakMap,Vt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,Q=new WeakMap,js=new WeakMap,ct=new WeakMap,de=new WeakMap,Cc)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[_c](){return{log:(...e)=>{if(!this[Ws]())console.log(...e);if(K(this,We,!0,"f"),m(this,xe,"f").length)K(this,xe,m(this,xe,"f")+`
80
+ `,"f");K(this,xe,m(this,xe,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[Ws]())console.error(...e);if(K(this,We,!0,"f"),m(this,xe,"f").length)K(this,xe,m(this,xe,"f")+`
81
+ `,"f");K(this,xe,m(this,xe,"f")+e.join(" "),"f")}}}[gr](e){gn(m(this,z,"f")).forEach((t)=>{if(((o)=>o==="configObjects")(t))return;let n=m(this,z,"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 m(this,Q,"f").getDescriptions()[e]}[$c](e,t,n){if(!m(this,Ps,"f")[n])m(this,X,"f").process.emitWarning(e,t),m(this,Ps,"f")[n]=!0}[Fc](){m(this,vs,"f").push({options:m(this,z,"f"),configObjects:m(this,z,"f").configObjects.slice(0),exitProcess:m(this,Ge,"f"),groups:m(this,at,"f"),strict:m(this,Vt,"f"),strictCommands:m(this,Zt,"f"),strictOptions:m(this,Qt,"f"),completionCommand:m(this,je,"f"),output:m(this,xe,"f"),exitError:m(this,St,"f"),hasOutput:m(this,We,"f"),parsed:this.parsed,parseFn:m(this,Ue,"f"),parseContext:m(this,Yt,"f")}),m(this,Q,"f").freeze(),m(this,de,"f").freeze(),m(this,we,"f").freeze(),m(this,Ye,"f").freeze()}[Ac](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(m(this,X,"f").process.argv()[0]))t=m(this,X,"f").process.argv().slice(1,2);else t=m(this,X,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let o=this[Uc](m(this,Ht,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&o.length<n.length?o:n}).join(" ").trim(),m(this,X,"f").getEnv("_")&&m(this,X,"f").getProcessArgvBin()===m(this,X,"f").getEnv("_"))e=m(this,X,"f").getEnv("_").replace(`${m(this,X,"f").path.dirname(m(this,X,"f").process.execPath())}/`,"");return e}[en](){return m(this,Ns,"f")}[Tc](){return m(this,js,"f")}[mr](){if(!m(this,zt,"f"))return;let e=m(this,X,"f").getEnv("LC_ALL")||m(this,X,"f").getEnv("LC_MESSAGES")||m(this,X,"f").getEnv("LANG")||m(this,X,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[Ic](){return this[yr]().version||"unknown"}[Oc](e){let t=e["--"]?e["--"]:e._;for(let n=0,o;(o=t[n])!==void 0;n++)if(m(this,X,"f").Parser.looksLikeNumber(o)&&Number.isSafeInteger(Math.floor(parseFloat(`${o}`))))t[n]=Number(o);return e}[yr](e){let t=e||"*";if(m(this,yn,"f")[t])return m(this,yn,"f")[t];let n={};try{let o=e||m(this,X,"f").mainFilename;if(m(this,X,"f").path.extname(o))o=m(this,X,"f").path.dirname(o);let s=m(this,X,"f").findUp(o,(r,i)=>{if(i.includes("package.json"))return"package.json";else return});Re(s,void 0,m(this,X,"f")),n=JSON.parse(m(this,X,"f").readFileSync(s,"utf8"))}catch(o){}return m(this,yn,"f")[t]=n||{},m(this,yn,"f")[t]}[_t](e,t){t=[].concat(t),t.forEach((n)=>{n=this[br](n),m(this,z,"f")[e].push(n)})}[wn](e,t,n,o){this[Dr](e,t,n,o,(s,r,i)=>{m(this,z,"f")[s][r]=i})}[wr](e,t,n,o){this[Dr](e,t,n,o,(s,r,i)=>{m(this,z,"f")[s][r]=(m(this,z,"f")[s][r]||[]).concat(i)})}[Dr](e,t,n,o,s){if(Array.isArray(n))n.forEach((r)=>{e(r,o)});else if(((r)=>typeof r==="object")(n))for(let r of gn(n))e(r,n[r]);else s(t,this[br](n),o)}[br](e){if(e==="__proto__")return"___proto___";return e}[kr](e,t){return this[wn](this[kr].bind(this),"key",e,t),this}[xr](){var e,t,n,o,s,r,i,a,c,l,u,d;let p=m(this,vs,"f").pop();Re(p,void 0,m(this,X,"f"));let h;e=this,t=this,n=this,o=this,s=this,r=this,i=this,a=this,c=this,l=this,u=this,d=this,{options:{set value(y){K(e,z,y,"f")}}.value,configObjects:h,exitProcess:{set value(y){K(t,Ge,y,"f")}}.value,groups:{set value(y){K(n,at,y,"f")}}.value,output:{set value(y){K(o,xe,y,"f")}}.value,exitError:{set value(y){K(s,St,y,"f")}}.value,hasOutput:{set value(y){K(r,We,y,"f")}}.value,parsed:this.parsed,strict:{set value(y){K(i,Vt,y,"f")}}.value,strictCommands:{set value(y){K(a,Zt,y,"f")}}.value,strictOptions:{set value(y){K(c,Qt,y,"f")}}.value,completionCommand:{set value(y){K(l,je,y,"f")}}.value,parseFn:{set value(y){K(u,Ue,y,"f")}}.value,parseContext:{set value(y){K(d,Yt,y,"f")}}.value}=p,m(this,z,"f").configObjects=h,m(this,Q,"f").unfreeze(),m(this,de,"f").unfreeze(),m(this,we,"f").unfreeze(),m(this,Ye,"f").unfreeze()}[Rc](e,t){return qt(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[Pc].bind(this),getContext:this[vc].bind(this),getHasOutput:this[Bc].bind(this),getLoggerInstance:this[Lc].bind(this),getParseContext:this[Nc].bind(this),getParserConfiguration:this[en].bind(this),getUsageConfiguration:this[Tc].bind(this),getUsageInstance:this[Mc].bind(this),getValidationInstance:this[jc].bind(this),hasParseCallback:this[Ws].bind(this),isGlobalContext:this[Wc].bind(this),postProcess:this[tn].bind(this),reset:this[Er].bind(this),runValidation:this[Sr].bind(this),runYargsParserAndExecuteCommands:this[Un].bind(this),setHasOutput:this[Jc].bind(this)}}[Pc](){return m(this,we,"f")}[vc](){return m(this,Wn,"f")}[Bc](){return m(this,We,"f")}[Lc](){return m(this,Gt,"f")}[Nc](){return m(this,Yt,"f")||{}}[Mc](){return m(this,Q,"f")}[jc](){return m(this,de,"f")}[Ws](){return!!m(this,Ue,"f")}[Wc](){return m(this,Bs,"f")}[tn](e,t,n,o){if(n)return e;if(ce(e))return e;if(!t)e=this[Cc](e);if(this[en]()["parse-positional-numbers"]||this[en]()["parse-positional-numbers"]===void 0)e=this[Oc](e);if(o)e=Kt(e,this,m(this,Ye,"f").getMiddleware(),!1);return e}[Er](e={}){K(this,z,m(this,z,"f")||{},"f");let t={};t.local=m(this,z,"f").local||[],t.configObjects=m(this,z,"f").configObjects||[];let n={};t.local.forEach((r)=>{n[r]=!0,(e[r]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(m(this,Xt,"f"),Object.keys(m(this,at,"f")).reduce((r,i)=>{let a=m(this,at,"f")[i].filter((c)=>!(c in n));if(a.length>0)r[i]=a;return r},{})),K(this,at,{},"f");let o=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],s=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(o.forEach((r)=>{t[r]=(m(this,z,"f")[r]||[]).filter((i)=>!n[i])}),s.forEach((r)=>{t[r]=xt(m(this,z,"f")[r],(i)=>!n[i])}),t.envPrefix=m(this,z,"f").envPrefix,K(this,z,t,"f"),K(this,Q,m(this,Q,"f")?m(this,Q,"f").reset(n):mc(this,m(this,X,"f")),"f"),K(this,de,m(this,de,"f")?m(this,de,"f").reset(n):Ec(this,m(this,Q,"f"),m(this,X,"f")),"f"),K(this,we,m(this,we,"f")?m(this,we,"f").reset():pc(m(this,Q,"f"),m(this,de,"f"),m(this,Ye,"f"),m(this,X,"f")),"f"),!m(this,ve,"f"))K(this,ve,bc(this,m(this,Q,"f"),m(this,we,"f"),m(this,X,"f")),"f");return m(this,Ye,"f").reset(),K(this,je,null,"f"),K(this,xe,"","f"),K(this,St,null,"f"),K(this,We,!1,"f"),this.parsed=!1,this}[Uc](e,t){return m(this,X,"f").path.relative(e,t)}[Un](e,t,n,o=0,s=!1){var r,i,a,c;let l=!!n||s;e=e||m(this,Ct,"f"),m(this,z,"f").__=m(this,X,"f").y18n.__,m(this,z,"f").configuration=this[en]();let u=!!m(this,z,"f").configuration["populate--"],d=Object.assign({},m(this,z,"f").configuration,{"populate--":!0}),p=m(this,X,"f").Parser.detailed(e,Object.assign({},m(this,z,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),h=Object.assign(p.argv,m(this,Yt,"f")),y=void 0,f=p.aliases,g=!1,w=!1;if(Object.keys(h).forEach((D)=>{if(D===m(this,Xe,"f")&&h[D])g=!0;else if(D===m(this,ct,"f")&&h[D])w=!0}),h.$0=this.$0,this.parsed=p,o===0)m(this,Q,"f").clearCachedHelpMessage();try{if(this[mr](),t)return this[tn](h,u,!!n,!1);if(m(this,Xe,"f")){if([m(this,Xe,"f")].concat(f[m(this,Xe,"f")]||[]).filter((F)=>F.length>1).includes(""+h._[h._.length-1]))h._.pop(),g=!0}K(this,Bs,!1,"f");let D=m(this,we,"f").getCommands(),k=((r=m(this,ve,"f"))===null||r===void 0?void 0:r.completionKey)?[(i=m(this,ve,"f"))===null||i===void 0?void 0:i.completionKey,...(c=this.getAliases()[(a=m(this,ve,"f"))===null||a===void 0?void 0:a.completionKey])!==null&&c!==void 0?c:[]].some((C)=>Object.prototype.hasOwnProperty.call(h,C)):!1,S=g||k||s;if(h._.length){if(D.length){let C;for(let F=o||0,A;h._[F]!==void 0;F++)if(A=String(h._[F]),D.includes(A)&&A!==m(this,je,"f")){let O=m(this,we,"f").runCommand(A,this,p,F+1,s,g||w||s);return this[tn](O,u,!!n,!1)}else if(!C&&A!==m(this,je,"f")){C=A;break}if(!m(this,we,"f").hasDefaultCommand()&&m(this,Ms,"f")&&C&&!S)m(this,de,"f").recommendCommands(C,D)}if(m(this,je,"f")&&h._.includes(m(this,je,"f"))&&!k){if(m(this,Ge,"f"))Et(!0);this.showCompletionScript(),this.exit(0)}}if(m(this,we,"f").hasDefaultCommand()&&!S){let C=m(this,we,"f").runCommand(null,this,p,0,s,g||w||s);return this[tn](C,u,!!n,!1)}if(k){if(m(this,Ge,"f"))Et(!0);e=[].concat(e);let C=e.slice(e.indexOf(`--${m(this,ve,"f").completionKey}`)+1);return m(this,ve,"f").getCompletion(C,(F,A)=>{if(F)throw new ye(F.message);(A||[]).forEach((O)=>{m(this,Gt,"f").log(O)}),this.exit(0)}),this[tn](h,!u,!!n,!1)}if(!m(this,We,"f")){if(g){if(m(this,Ge,"f"))Et(!0);l=!0,this.showHelp((C)=>{m(this,Gt,"f").log(C),this.exit(0)})}else if(w){if(m(this,Ge,"f"))Et(!0);l=!0,m(this,Q,"f").showVersion("log"),this.exit(0)}}if(!l&&m(this,z,"f").skipValidation.length>0)l=Object.keys(h).some((C)=>m(this,z,"f").skipValidation.indexOf(C)>=0&&h[C]===!0);if(!l){if(p.error)throw new ye(p.error.message);if(!k){let C=this[Sr](f,{},p.error);if(!n)y=Kt(h,this,m(this,Ye,"f").getMiddleware(),!0);if(y=this[Rc](C,y!==null&&y!==void 0?y:h),ce(y)&&!n)y=y.then(()=>Kt(h,this,m(this,Ye,"f").getMiddleware(),!1))}}}catch(D){if(D instanceof ye)m(this,Q,"f").fail(D.message,D);else throw D}return this[tn](y!==null&&y!==void 0?y:h,u,!!n,!0)}[Sr](e,t,n,o){let s={...this.getDemandedOptions()};return(r)=>{if(n)throw new ye(n.message);m(this,de,"f").nonOptionCount(r),m(this,de,"f").requiredArguments(r,s);let i=!1;if(m(this,Zt,"f"))i=m(this,de,"f").unknownCommands(r);if(m(this,Vt,"f")&&!i)m(this,de,"f").unknownArguments(r,e,t,!!o);else if(m(this,Qt,"f"))m(this,de,"f").unknownArguments(r,e,{},!1,!1);m(this,de,"f").limitedChoices(r),m(this,de,"f").implications(r),m(this,de,"f").conflicting(r)}}[Jc](){K(this,We,!0,"f")}[nn](e){if(typeof e==="string")m(this,z,"f").key[e]=!0;else for(let t of e)m(this,z,"f").key[t]=!0}}function hc(e){return!!e&&typeof e.getInternalMethods==="function"}var eh=Kc(ur),Hc=eh;var th=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,nh=/[\t\n\v\f\r (*_~]/;function sh(e){let t=e.split(""),n=(s,r)=>{for(let i=s;i<r;i++)if(t[i]!==`
82
82
  `)t[i]="\x00"},o=0;while(o<e.length){let r=o===0||e[o-1]===`
83
83
  `?/^ {0,3}(?:(`{3,})[^`\n]*|(~{3,})[^\n]*)(?=\n|$)/.exec(e.slice(o)):null;if(r){let a=r[1]??r[2],c=new RegExp(`
84
84
  {0,3}${a[0]==="`"?"`":"~"}{${a.length},}[ ]*\r?(?=
85
85
  |$)`,"g");c.lastIndex=o+r[0].length;let l=c.exec(e),u=l?l.index+l[0].length:e.length;n(o,u),o=u;continue}let i=e[o];if(i==="\\"){o+=2;continue}if(i==="`"){let a=0;while(e[o+a]==="`")a++;let c=o+a,l=-1;while(c<e.length){if(e[c]===`
86
- `&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(c)))break;if(e[c]!=="`"){c++;continue}let u=0;while(e[c+u]==="`")u++;if(u===a){l=c+u;break}c+=u}if(l<0){o+=a;continue}n(o,l),o=l;continue}if(i==="["){let a=/^\[(?:\\.|[^\]\\\n])*\]\([^()\s]*\)/.exec(e.slice(o));if(a){n(o,o+a[0].length),o+=a[0].length;continue}}o++}return t.join("")}function Hp(e,{markdown:t=!0}={}){let n=t?qp(e):e,o=[];for(let s of n.matchAll(Jp)){let r=s[0];if(r.startsWith("<"))continue;let i=s.index??0,a=i>0?n[i-1]:"";if(a&&!Kp.test(a))o.push({url:r,side:"before",char:e[i-1]});let c=r.match(/[^\x00-\x7f]|>/);if(c)o.push({url:r,side:"after",char:c[0]})}return o}function Ne(e,t=!1,n=console.error,{sides:o=["before","after"],markdown:s=!0}={}){let r=Hp(e,{markdown:s}).filter((l)=>o.includes(l.side));if(!r.length)return;let i=r.map((l)=>l.side==="before"?`${JSON.stringify(l.url)} (glued to ${JSON.stringify(l.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(l.url)} (runs into ${JSON.stringify(l.char)} after it)`),a=r.some((l)=>l.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",c=`Ambiguous URL boundary: ${i.join(", ")}. ${a}Put the URL on its own line, or wrap it as <url> / <url|label>. Use --allow-url-adjacent to warn only.`;if(!t)throw Error(c);n(`Warning: ${c}`)}import{existsSync as Jn,readFileSync as Er,writeFileSync as kr,mkdirSync as qc,chmodSync as Uc}from"node:fs";import{homedir as zp}from"node:os";import{join as nn,dirname as Sr}from"node:path";function Cr(){return process.env.HOME||zp()}function Hc(){return nn(Cr(),".config","slack-cli","profiles.json")}function js(){return nn(process.cwd(),".slack-cli","workspace")}function Ws(){return nn(Cr(),".slack-cli","workspace")}function Kn(){let e=Hc();if(!Jn(e))return{profiles:{}};return JSON.parse(Er(e,"utf8"))}function Gp(e){let t=Hc();if(qc(Sr(t),{recursive:!0}),process.platform!=="win32"&&Jn(t))Uc(t,384);if(kr(t,JSON.stringify(e,null,2)+`
87
- `,{mode:384}),process.platform!=="win32")Uc(t,384)}function Dn(e){if(!Jn(e))return;return Er(e,"utf8").trim()||void 0}function Jc(e,t){let n=Sr(e);qc(n,{recursive:!0});let o=nn(n,".gitignore");if(!Jn(o))kr(o,`*
88
- `);kr(e,t+`
89
- `)}function Yp(e){let t={};for(let n of e.split(`
90
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function Kc(e){if(!Jn(e))return{};try{return Yp(Er(e,"utf8"))}catch{return{}}}function xr(e,t){let n=Cr(),o=e;while(!0){for(let i of[nn(o,".slack-term",".env.local"),nn(o,".env.local")]){let a=Kc(i);for(let c of t)if(a[c])return a[c]}if(o===n)break;let r=Sr(o);if(r===o)break;o=r}let s=Kc(nn(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function _r(){let e=Kn(),t=Dn(js()),n=Dn(Ws()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=Un(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function Un(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 zc(e){let t=Kn();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],Gp(t)}function Gc(e,t=!1){let n=Kn();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)Jc(Ws(),e);else Jc(js(),e)}function qn(e){let n=Kn().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=xr(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
91
- `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=xr(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let a=process.env.SLACK_WORKSPACE;if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let c=Dn(js());if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=Dn(Ws());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
86
+ `&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(c)))break;if(e[c]!=="`"){c++;continue}let u=0;while(e[c+u]==="`")u++;if(u===a){l=c+u;break}c+=u}if(l<0){o+=a;continue}n(o,l),o=l;continue}if(i==="["){let a=/^\[(?:\\.|[^\]\\\n])*\]\([^()\s]*\)/.exec(e.slice(o));if(a){n(o,o+a[0].length),o+=a[0].length;continue}}o++}return t.join("")}function oh(e,{markdown:t=!0}={}){let n=t?sh(e):e,o=[];for(let s of n.matchAll(th)){let r=s[0];if(r.startsWith("<"))continue;let i=s.index??0,a=i>0?n[i-1]:"";if(a&&!nh.test(a))o.push({url:r,side:"before",char:e[i-1]});let c=r.match(/[^\x00-\x7f]|>/);if(c)o.push({url:r,side:"after",char:c[0]})}return o}function Be(e,t=!1,n=console.error,{sides:o=["before","after"],markdown:s=!0}={}){let r=oh(e,{markdown:s}).filter((l)=>o.includes(l.side));if(!r.length)return;let i=r.map((l)=>l.side==="before"?`${JSON.stringify(l.url)} (glued to ${JSON.stringify(l.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(l.url)} (runs into ${JSON.stringify(l.char)} after it)`),a=r.some((l)=>l.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",c=`Ambiguous URL boundary: ${i.join(", ")}. ${a}Put the URL on its own line, or wrap it as <url> / <url|label>. Use --allow-url-adjacent to warn only.`;if(!t)throw Error(c);n(`Warning: ${c}`)}import{existsSync as Kn,readFileSync as $r,writeFileSync as Cr,mkdirSync as Xc,chmodSync as zc}from"node:fs";import{homedir as rh}from"node:os";import{join as sn,dirname as Fr}from"node:path";function Ar(){return process.env.HOME||rh()}function Vc(){return sn(Ar(),".config","slack-cli","profiles.json")}function Us(){return sn(process.cwd(),".slack-cli","workspace")}function Js(){return sn(Ar(),".slack-cli","workspace")}function qn(){let e=Vc();if(!Kn(e))return{profiles:{}};return JSON.parse($r(e,"utf8"))}function ih(e){let t=Vc();if(Xc(Fr(t),{recursive:!0}),process.platform!=="win32"&&Kn(t))zc(t,384);if(Cr(t,JSON.stringify(e,null,2)+`
87
+ `,{mode:384}),process.platform!=="win32")zc(t,384)}function Dn(e){if(!Kn(e))return;return $r(e,"utf8").trim()||void 0}function Gc(e,t){let n=Fr(e);Xc(n,{recursive:!0});let o=sn(n,".gitignore");if(!Kn(o))Cr(o,`*
88
+ `);Cr(e,t+`
89
+ `)}function ah(e){let t={};for(let n of e.split(`
90
+ `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function Yc(e){if(!Kn(e))return{};try{return ah($r(e,"utf8"))}catch{return{}}}function _r(e,t){let n=Ar(),o=e;while(!0){for(let i of[sn(o,".slack-term",".env.local"),sn(o,".env.local")]){let a=Yc(i);for(let c of t)if(a[c])return a[c]}if(o===n)break;let r=Fr(o);if(r===o)break;o=r}let s=Yc(sn(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function Tr(){let e=qn(),t=Dn(Us()),n=Dn(Js()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=Jn(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function Jn(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 Zc(e){let t=qn();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],ih(t)}function Qc(e,t=!1){let n=qn();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)Gc(Js(),e);else Gc(Us(),e)}function Hn(e){let n=qn().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=_r(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
91
+ `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=_r(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let a=process.env.SLACK_WORKSPACE;if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let c=Dn(Us());if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=Dn(Js());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
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 @@ ${g.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-term/.env.local")}function ze(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function $r(e){let t=Kn(),n=t.profiles;if(e)return Un(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=xr(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return Un(t,r);let i=Dn(js());if(i)return Un(t,i);let a=Dn(Ws());if(a)return Un(t,a);return}import{existsSync as bn,readFileSync as Js,writeFileSync as Xc,mkdirSync as Vc,chmodSync as Us}from"node:fs";import{homedir as Xp}from"node:os";import{join as wn,dirname as Ar}from"node:path";function Tr(){return process.env.HOME||Xp()}function Zc(){return wn(Tr(),".config","slack-cli","profiles.json")}function Ir(){return wn(process.cwd(),".slack-cli","workspace")}function Or(){return wn(Tr(),".slack-cli","workspace")}function xn(){let e=Zc();if(!bn(e))return{profiles:{}};return JSON.parse(Js(e,"utf8"))}function Rr(e){let t=Zc();if(Vc(Ar(t),{recursive:!0}),process.platform!=="win32"&&bn(t))Us(t,384);if(Xc(t,JSON.stringify(e,null,2)+`
101
- `,{mode:384}),process.platform!=="win32")Us(t,384)}function kn(e){if(!bn(e))return;return Js(e,"utf8").trim()||void 0}function Vp(e){let t={};for(let n of e.split(`
102
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function Yc(e){if(!bn(e))return{};try{return Vp(Js(e,"utf8"))}catch{return{}}}function Fr(e,t){let n=Tr(),o=e;while(!0){for(let i of[wn(o,".slack-term",".env.local"),wn(o,".env.local")]){let a=Yc(i);for(let c of t)if(a[c])return a[c]}if(o===n)break;let r=Ar(o);if(r===o)break;o=r}let s=Yc(wn(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function Pr(e,t){Vc(Ar(e),{recursive:!0});let n=bn(e)?Js(e,"utf8"):"",o=n?n.split(`
103
- `):[];for(let[s,r]of Object.entries(t)){let i=o.findIndex((c)=>{let l=c.trim();return l.startsWith(s+"=")||l.startsWith(s+" =")}),a=`${s}=${r}`;if(i!==-1)o[i]=a;else o.push(a)}if(process.platform!=="win32"&&bn(e))Us(e,384);if(Xc(e,o.join(`
100
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function Je(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Ir(e){let t=qn(),n=t.profiles;if(e)return Jn(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=_r(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return Jn(t,r);let i=Dn(Us());if(i)return Jn(t,i);let a=Dn(Js());if(a)return Jn(t,a);return}import{existsSync as kn,readFileSync as qs,writeFileSync as tl,mkdirSync as nl,chmodSync as Ks}from"node:fs";import{homedir as ch}from"node:os";import{join as bn,dirname as Rr}from"node:path";function Pr(){return process.env.HOME||ch()}function sl(){return bn(Pr(),".config","slack-cli","profiles.json")}function vr(){return bn(process.cwd(),".slack-cli","workspace")}function Br(){return bn(Pr(),".slack-cli","workspace")}function En(){let e=sl();if(!kn(e))return{profiles:{}};return JSON.parse(qs(e,"utf8"))}function Lr(e){let t=sl();if(nl(Rr(t),{recursive:!0}),process.platform!=="win32"&&kn(t))Ks(t,384);if(tl(t,JSON.stringify(e,null,2)+`
101
+ `,{mode:384}),process.platform!=="win32")Ks(t,384)}function xn(e){if(!kn(e))return;return qs(e,"utf8").trim()||void 0}function lh(e){let t={};for(let n of e.split(`
102
+ `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function el(e){if(!kn(e))return{};try{return lh(qs(e,"utf8"))}catch{return{}}}function Or(e,t){let n=Pr(),o=e;while(!0){for(let i of[bn(o,".slack-term",".env.local"),bn(o,".env.local")]){let a=el(i);for(let c of t)if(a[c])return a[c]}if(o===n)break;let r=Rr(o);if(r===o)break;o=r}let s=el(bn(n,".slack-term",".env.local"));for(let r of t)if(s[r])return s[r];return}function Nr(e,t){nl(Rr(e),{recursive:!0});let n=kn(e)?qs(e,"utf8"):"",o=n?n.split(`
103
+ `):[];for(let[s,r]of Object.entries(t)){let i=o.findIndex((c)=>{let l=c.trim();return l.startsWith(s+"=")||l.startsWith(s+" =")}),a=`${s}=${r}`;if(i!==-1)o[i]=a;else o.push(a)}if(process.platform!=="win32"&&kn(e))Ks(e,384);if(tl(e,o.join(`
104
104
  `).trimEnd()+`
105
- `,{mode:384}),process.platform!=="win32")Us(e,384)}function zn(){let e=xn(),t=kn(Ir()),n=kn(Or()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=Hn(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function Ks(e,t){let n=xn();if(t.identity&&t.cookie){n.users??={};let o=n.users[t.identity]??{};n.users[t.identity]={...o,cookie:t.cookie};let{cookie:s,...r}=t;n.profiles[e]=r}else n.profiles[e]=t;Rr(n)}function vr(e,t){let n=xn(),o=n.profiles[e];if(!o)throw Error(`Profile not found: ${e}`);if(o.identity)n.users??={},n.users[o.identity]={...n.users[o.identity]??{},cookie:t};else o.cookie=t;Rr(n)}function Qc(e,t,n){let o=xn();o.users??={},o.users[e]={...o.users[e]??{},cookie:t,...n?{source:n}:{}},Rr(o)}function Hn(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 el(e){let n=xn().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=Fr(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
106
- `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=Fr(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let a=process.env.SLACK_WORKSPACE;if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let c=kn(Ir());if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=kn(Or());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
105
+ `,{mode:384}),process.platform!=="win32")Ks(e,384)}function Gn(){let e=En(),t=xn(vr()),n=xn(Br()),o=t??n;return Object.entries(e.profiles).map(([s,r])=>{let i=zn(e,s);return{name:s,profile:{...r,...i?{cookie:i}:{}},current:s===o}})}function Hs(e,t){let n=En();if(t.identity&&t.cookie){n.users??={};let o=n.users[t.identity]??{};n.users[t.identity]={...o,cookie:t.cookie};let{cookie:s,...r}=t;n.profiles[e]=r}else n.profiles[e]=t;Lr(n)}function Mr(e,t){let n=En(),o=n.profiles[e];if(!o)throw Error(`Profile not found: ${e}`);if(o.identity)n.users??={},n.users[o.identity]={...n.users[o.identity]??{},cookie:t};else o.cookie=t;Lr(n)}function ol(e,t,n){let o=En();o.users??={},o.users[e]={...o.users[e]??{},cookie:t,...n?{source:n}:{}},Lr(o)}function zn(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 rl(e){let n=En().profiles,o=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let s=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(s&&o.length===0)return s;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(r&&o.length>0){let u=Or(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
106
+ `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=Or(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let a=process.env.SLACK_WORKSPACE;if(a){let u=n[a];if(!u)throw Error(`Workspace "${a}" not found. Available: ${o.join(", ")||"(none)"}`);return u.token}let c=xn(vr());if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=xn(Br());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(o.length>0)throw Error(`Workspace not selected (${o.join(", ")} available).
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,31 +112,31 @@ ${g.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-term/.env.local")}function qs(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function $t(e){let t=xn(),n=t.profiles;if(e)return Hn(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=Fr(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return Hn(t,r);let i=kn(Ir());if(i)return Hn(t,i);let a=kn(Or());if(a)return Hn(t,a);return}function Hs(e){let t=[],n=(r)=>{if(!r)return;let i=t[t.length-1];if(i?.type==="text")i.text+=r;else t.push({type:"text",text:r})},o=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,s=0;for(let r of e.matchAll(o)){let i=r.index??0;if(n(e.slice(s,i)),r[1]){t.push(r[2]?{type:"link",url:r[1],text:r[2]}:{type:"link",url:r[1]}),s=i+r[0].length;continue}let a=r[0];while(/[.,:;!?'"*_~]$/.test(a)||a.endsWith(")")&&tl(a,"(")<tl(a,")"))a=a.slice(0,-1);t.push({type:"link",url:a}),s=i+a.length}return n(e.slice(s)),t}function tl(e,t){return e.split(t).length-1}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 Br(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function Nr(e,t,n,o){o=e.startsWith("xoxc-")?o??$t():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Br()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new it(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new it(60,t);if(a==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
115
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function zs(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function $t(e){let t=En(),n=t.profiles;if(e)return zn(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let s=Or(process.cwd(),["SLACK_COOKIE"]);if(s)return s;let r=process.env.SLACK_WORKSPACE;if(r)return zn(t,r);let i=xn(vr());if(i)return zn(t,i);let a=xn(Br());if(a)return zn(t,a);return}function Gs(e){let t=[],n=(r)=>{if(!r)return;let i=t[t.length-1];if(i?.type==="text")i.text+=r;else t.push({type:"text",text:r})},o=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,s=0;for(let r of e.matchAll(o)){let i=r.index??0;if(n(e.slice(s,i)),r[1]){t.push(r[2]?{type:"link",url:r[1],text:r[2]}:{type:"link",url:r[1]}),s=i+r[0].length;continue}let a=r[0];while(/[.,:;!?'"*_~]$/.test(a)||a.endsWith(")")&&il(a,"(")<il(a,")"))a=a.slice(0,-1);t.push({type:"link",url:a}),s=i+a.length}return n(e.slice(s)),t}function il(e,t){return e.split(t).length-1}class st 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 Wr(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function Ur(e,t,n,o){o=e.startsWith("xoxc-")?o??$t():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Wr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new st(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new st(60,t);if(a==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
116
116
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
117
117
  Or replace the token with an xoxp- user token:
118
118
  slack auth login`);if((a==="missing_scope"||a==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${a}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${a} — ${a==="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"}.
119
119
  Tailing/DMing people and listing users need a user session, not a bot token.
120
120
  Switch workspace: slack auth ls then slack auth use <name>
121
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${a}`)}return i}async function Zp(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Br()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new it(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new it(60,t);if((a==="invalid_auth"||a==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
121
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${a}`)}return i}async function uh(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Wr()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new st(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new st(60,t);if((a==="invalid_auth"||a==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
122
122
  Import from Slack desktop: slack auth login`);if((a==="invalid_auth"||a==="not_authed")&&!o)throw Error(`${t} also requires the xoxd session cookie.
123
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${a}`)}return i}function Qp(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return Zp(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function Ae(e,t,n,o){let s=new URLSearchParams(n).toString();return Nr(e,`${t}?${s}`,{method:"GET"},o)}function Mr(e,t,n,o){return Nr(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function rl(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return Nr(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function Yn(e,t,n){return rl(e,"agents.sessions.setStatus",{...t,status:n})}function jr(e,t,n){return rl(e,"agents.sessions.rename",{...t,title:n})}async function En(e,t){let n=await Ae(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function il(e,t){t=e.startsWith("xoxc-")?t??$t():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${Br()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new it(isNaN(i)?60:i,"auth.test")}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function al(e,t,n){let o=await Ae(e,"bots.info",{bot:t},n);return{appId:o.bot?.app_id??"",userId:o.bot?.user_id??""}}async function Xn(e,t,n=20,o,s,r,i){let a={channel:t,limit:String(n)};if(o!==void 0)a.oldest=o;if(s!==void 0)a.cursor=s;if(i)a.inclusive="true";return Ae(e,"conversations.history",a,r)}async function cl(e,t,n,o=50,s){return Ae(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function zs(e,t,n,o,s){await Mr(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function ll(e,t,n,o){return((await Ae(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Gs(e,t,n,o,s){await Mr(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function eh(e,t,n){let s=(await Mr(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function ul(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await Ae(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function Lr(e,t,n,o){let s=await ul(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function Gn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function nl(e,t){let n=Gn(e.name??""),o=Gn(e.real_name??e.profile?.real_name??""),s=Gn(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var dl=200;async function th(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await Ae(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(nl(f,t))return{id:f.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,a=0,c=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await Ae(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=dl){c=!0;break}s.add(h),i++;let g;try{g=(await Ae(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof it)throw p;a++;continue}if(g&&nl(g,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:a,capped:c}}if(c)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:a,capped:c}}function nh(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
123
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${a}`)}return i}function dh(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return uh(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function Ce(e,t,n,o){let s=new URLSearchParams(n).toString();return Ur(e,`${t}?${s}`,{method:"GET"},o)}function Jr(e,t,n,o){return Ur(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function ul(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return Ur(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function Xn(e,t,n){return ul(e,"agents.sessions.setStatus",{...t,status:n})}function Kr(e,t,n){return ul(e,"agents.sessions.rename",{...t,title:n})}async function Sn(e,t){let n=await Ce(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function dl(e,t){t=e.startsWith("xoxc-")?t??$t():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${Wr()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new st(isNaN(i)?60:i,"auth.test")}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function fl(e,t,n){let o=await Ce(e,"bots.info",{bot:t},n);return{appId:o.bot?.app_id??"",userId:o.bot?.user_id??""}}async function Vn(e,t,n=20,o,s,r,i){let a={channel:t,limit:String(n)};if(o!==void 0)a.oldest=o;if(s!==void 0)a.cursor=s;if(i)a.inclusive="true";return Ce(e,"conversations.history",a,r)}async function pl(e,t,n,o=50,s){return Ce(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function Ys(e,t,n,o,s){await Jr(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function hl(e,t,n,o){return((await Ce(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Xs(e,t,n,o,s){await Jr(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function fh(e,t,n){let s=(await Jr(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function gl(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await Ce(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function jr(e,t,n,o){let s=await gl(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function Yn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function al(e,t){let n=Yn(e.name??""),o=Yn(e.real_name??e.profile?.real_name??""),s=Yn(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var ml=200;async function ph(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await Ce(e,"users.list",u,n);for(let p of d.members??[]){if(o++,p.id)s.add(p.id);if(al(p,t))return{id:p.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,a=0,c=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await Ce(e,"conversations.list",u,n);for(let p of d.channels??[]){let h=p.user;if(!h||s.has(h))continue;if(i>=ml){c=!0;break}s.add(h),i++;let y;try{y=(await Ce(e,"users.info",{user:h},n)).user}catch(f){if(f instanceof st)throw f;a++;continue}if(y&&al(y,t))return{id:h,dm:String(p.id??""),workspaceCount:o,connectCount:i,skipped:a,capped:c}}if(c)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:a,capped:c}}function hh(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
124
124
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
125
- Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${dl} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
125
+ Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${ml} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
126
126
  `+(o.length?`This search was incomplete: ${o.join("; ")}.
127
127
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
128
128
  DMed you they cannot be found by name at all. Look them up and use their ID:
129
- slack user ls --external`)}function Wr(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function sh(e){return Wr(e)?.channel}function sl(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function ol(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Ys(e,t,n){let o=sh(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(sl(t))return t;if(ol(t))return Lr(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&sl(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=Gn(r);if(s){if(ol(r))return Lr(e,r,n);let l=await Ae(e,"auth.test",{},n);if(i==="you"||i==="me"||Gn(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await ul(e,f,n)||eh(e,f,n)}let d=await th(e,i,n);if(!d.id)throw nh(t,d);if(d.dm)return d.dm;return Lr(e,d.id,n,t)}let a=r.toLowerCase(),c="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)l.cursor=c;let u=await Ae(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===a)return String(d.id??"");if(c=u.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function Xs(e,t,n){try{let o=await Ae(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Vs(e,t,n){try{let o=await Ae(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function Zs(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await Ae(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function Ur(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await Ae(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function Jr(e,t,n){return Ae(e,"users.info",{user:t},n)}async function fl(e,t,n){return Ae(e,"conversations.info",{channel:t},n)}async function pl(e,t){let n=await Qp(e,"client.boot",{},t),o=typeof n.url==="string"?n.url:void 0;if(!o){let r=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${r}`)}let s=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:o,selfId:typeof s.id==="string"?s.id:""}}var oh=["chat:write","im:write"],rh=["im:history","im:read"];async function Qs(e){let{userId:t,botId:n,team:o,scopes:s}=await il(e),r="";if(n)try{r=(await al(e,n)).appId}catch{r=""}let i=(l)=>s.includes(l),a=oh.filter((l)=>!i(l)),c=rh.filter((l)=>!i(l));return{canSend:a.length===0,canReceiveReplies:c.length===0,ok:a.length===0&&c.length===0,botUserId:t,appId:r,team:o,grantedScopes:s,missingSendScopes:a,missingReplyScopes:c}}function hl(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function eo(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let s=["✓ Bot DM scopes are complete (send + read replies)."," Two-way replies also require the Messages Tab, which is not API-detectable.",' If recipients see "Sending messages to this app is turned off", enable it:',` ${n} → App Home → "Messages Tab" ON + "Allow users to send messages".`];return t?s:[...s,...hl(e)]}let o=[];if(!e.canSend)o.push(`⚠ This bot CANNOT send DMs — missing scope(s): ${e.missingSendScopes.join(", ")}.`);else o.push("⚠ This bot can send DMs, but the user's replies will NOT be readable.");return o.push(" Make escalation DMs two-way:"),o.push(` 1. ${n} → App Home → enable "Messages Tab" and check`),o.push(' "Allow users to send Slash commands and messages".'),o.push(` 2. OAuth & Permissions → add Bot Token Scopes: ${[...e.missingSendScopes,...e.missingReplyScopes].join(", ")}`),o.push(" 3. Reinstall the app to apply the new scopes."),t?o:[...o,...hl(e)]}import{createInterface as Me}from"node:readline/promises";import{join as Qr,resolve as Ih}from"node:path";import{homedir as Oh}from"node:os";import{readdirSync as Qn,readFileSync as Zn,existsSync as Ge,copyFileSync as Hr,mkdtempSync as Dl,rmSync as wl}from"node:fs";import{homedir as no,tmpdir as bl}from"node:os";import{join as ce,dirname as ch}from"node:path";import{pbkdf2Sync as to,createDecipheriv as kl,createHash as lh,timingSafeEqual as uh}from"node:crypto";import{execSync as xl,execFileSync as dh}from"node:child_process";function Vn(e,t){let n=0,o=0,s=t;while(s<e.length){let r=e[s++];if(n+=(r&127)*2**o,(r&128)===0)break;o+=7}return{value:n,pos:s}}function ih(e){let t=0,n=0,o=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**o,(i&128)===0)break;o+=7}let s=Buffer.allocUnsafe(n),r=0;while(t<e.length&&r<n){let i=e[t++],a=i&3;if(a===0){let c=i>>2;if(c>=60){let l=c-59;c=0;for(let u=0;u<l;u++)c+=e[t++]*2**(8*u)}c+=1,e.copy(s,r,t,t+c),t+=c,r+=c}else{let c,l;if(a===1)c=4+(i>>2&7),l=(i>>5&7)*256+e[t++];else if(a===2)c=1+(i>>2),l=e[t]+e[t+1]*256,t+=2;else c=1+(i>>2),l=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let u=r-l;for(let d=0;d<c&&r<n;d++)s[r++]=s[u++]}}return r===n?s:s.subarray(0,r)}function Kr(e,t){let n=Vn(e,t),o=Vn(e,n.pos);return{handle:{offset:n.value,size:o.value},pos:o.pos}}function gl(e,t){let{offset:n,size:o}=t,s=e.subarray(n,n+o);return e[n+o]===1?ih(s):Buffer.from(s)}function ah(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,o=[],s=0,r=Buffer.alloc(0);while(s<n){let i=Vn(e,s),a=Vn(e,i.pos),c=Vn(e,a.pos);s=c.pos;let l=i.value,u=a.value,d=c.value,f=e.subarray(s,s+u);s+=u;let h=e.subarray(s,s+d);s+=d,r=Buffer.concat([r.subarray(0,l),f]),o.push(h)}return o}function ml(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=Kr(e,t),o=Kr(e,n.pos),s=gl(e,o.handle),r=[];for(let i of ah(s))try{let{handle:a}=Kr(i,0);r.push(gl(e,a))}catch{}return Buffer.concat(r)}catch{return Buffer.alloc(0)}}function yl(){let e=process.env.HOME??no();if(process.platform==="darwin")return[ce(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[ce(e,".config","Slack","Local Storage","leveldb"),ce(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),ce(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??ce(e,"AppData","Roaming");return[ce(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function fh(){let e=process.env.HOME??no();if(process.platform==="darwin")return ce(e,"Library","Application Support","Slack","Cookies");return""}function ph(e,t){if(e.length<35||e.slice(0,3).toString()!=="v10")throw Error("Not a v10 encrypted cookie");let n=e.slice(19,35),o=e.slice(35),s=kl("aes-128-cbc",t,n);return s.setAutoPadding(!0),Buffer.concat([s.update(o),s.final()]).toString("utf8")}function hh(){if(process.platform!=="darwin")return;let e=fh();if(!Ge(e))return;let t;try{t=xl('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=to(t,"saltysalt",1003,16,"sha1");try{let{default:o}=Ln("bun:sqlite"),s=new o(e,{readonly:!0}),r=s.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(s.close(),!r)return;return ph(Buffer.from(r.encrypted_value),n)}catch{return}}function El(e){if(!Ge(e))return[];let t=Qn(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,o=(i)=>{let a=n.get(i);if(a!==void 0)return a;let c="";try{let l=Zn(ce(e,i));c=i.endsWith(".ldb")?ml(l).toString("latin1")||l.toString("latin1"):l.toString("latin1")}catch{c=""}return n.set(i,c),c},s=new Map;for(let i of t){let a=o(i);for(let c of a.matchAll(/"token":"(xoxc-[^"]+)"/g)){let l=c[1],u=l.split("-")[1]??"";if(!u||l.length<40)continue;let d=Math.max(0,c.index-2000),f=Math.min(a.length,c.index+2000),h=a.slice(d,f),g=h.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),p=h.match(/"(?:team_name|name)":"([^"]{2,60})"/),m=s.get(u);if(!m||l.length>m.token.length){let D={token:l,teamId:u},w=g?.[1]??m?.url,k=p?.[1]??m?.teamName;if(w)D.url=w;if(k)D.teamName=k;s.set(u,D)}}}let r=t.map((i)=>o(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of s.values()){if(i.teamName)continue;let a=r.indexOf(i.teamId);if(a!==-1){let c=Math.max(0,a-500),l=Math.min(r.length,a+500),d=r.slice(c,l).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){i.teamName=d[1];continue}}if(!i.teamName&&i.url){let c=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(c){let l=r.indexOf(c);if(l!==-1){let u=Math.max(0,l-500),d=Math.min(r.length,l+500),h=r.slice(u,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(h?.[1]){i.teamName=h[1];continue}}i.teamName=c.split("-").map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}}}return[...s.values()]}async function zr(e){let t=e??yl().find(Ge);if(!t)throw Error(`Slack desktop app LevelDB not found at:
130
- ${yl().join(`
129
+ slack user ls --external`)}function qr(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function gh(e){return qr(e)?.channel}function cl(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function ll(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Vs(e,t,n){let o=gh(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(cl(t))return t;if(ll(t))return jr(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&cl(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=Yn(r);if(s){if(ll(r))return jr(e,r,n);let l=await Ce(e,"auth.test",{},n);if(i==="you"||i==="me"||Yn(l.user??"")===i){let p=l.user_id;if(!p)throw Error("auth.test did not return user_id");return await gl(e,p,n)||fh(e,p,n)}let d=await ph(e,i,n);if(!d.id)throw hh(t,d);if(d.dm)return d.dm;return jr(e,d.id,n,t)}let a=r.toLowerCase(),c="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)l.cursor=c;let u=await Ce(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===a)return String(d.id??"");if(c=u.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function Zs(e,t,n){try{let o=await Ce(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Qs(e,t,n){try{let o=await Ce(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function eo(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await Ce(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function Hr(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await Ce(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function zr(e,t,n){return Ce(e,"users.info",{user:t},n)}async function yl(e,t,n){return Ce(e,"conversations.info",{channel:t},n)}async function wl(e,t){let n=await dh(e,"client.boot",{},t),o=typeof n.url==="string"?n.url:void 0;if(!o){let r=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${r}`)}let s=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:o,selfId:typeof s.id==="string"?s.id:""}}var mh=["chat:write","im:write"],yh=["im:history","im:read"];async function to(e){let{userId:t,botId:n,team:o,scopes:s}=await dl(e),r="";if(n)try{r=(await fl(e,n)).appId}catch{r=""}let i=(l)=>s.includes(l),a=mh.filter((l)=>!i(l)),c=yh.filter((l)=>!i(l));return{canSend:a.length===0,canReceiveReplies:c.length===0,ok:a.length===0&&c.length===0,botUserId:t,appId:r,team:o,grantedScopes:s,missingSendScopes:a,missingReplyScopes:c}}function Dl(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function no(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let s=["✓ Bot DM scopes are complete (send + read replies)."," Two-way replies also require the Messages Tab, which is not API-detectable.",' If recipients see "Sending messages to this app is turned off", enable it:',` ${n} → App Home → "Messages Tab" ON + "Allow users to send messages".`];return t?s:[...s,...Dl(e)]}let o=[];if(!e.canSend)o.push(`⚠ This bot CANNOT send DMs — missing scope(s): ${e.missingSendScopes.join(", ")}.`);else o.push("⚠ This bot can send DMs, but the user's replies will NOT be readable.");return o.push(" Make escalation DMs two-way:"),o.push(` 1. ${n} → App Home → enable "Messages Tab" and check`),o.push(' "Allow users to send Slash commands and messages".'),o.push(` 2. OAuth & Permissions → add Bot Token Scopes: ${[...e.missingSendScopes,...e.missingReplyScopes].join(", ")}`),o.push(" 3. Reinstall the app to apply the new scopes."),t?o:[...o,...Dl(e)]}import{createInterface as Le}from"node:readline/promises";import{join as si,resolve as Jh}from"node:path";import{homedir as Kh}from"node:os";import{readdirSync as es,readFileSync as Qn,existsSync as Ke,copyFileSync as Xr,mkdtempSync as El,rmSync as Sl}from"node:fs";import{homedir as oo,tmpdir as Cl}from"node:os";import{join as se,dirname as bh}from"node:path";import{pbkdf2Sync as so,createDecipheriv as _l,createHash as kh,timingSafeEqual as xh}from"node:crypto";import{execSync as $l,execFileSync as Eh}from"node:child_process";function Zn(e,t){let n=0,o=0,s=t;while(s<e.length){let r=e[s++];if(n+=(r&127)*2**o,(r&128)===0)break;o+=7}return{value:n,pos:s}}function wh(e){let t=0,n=0,o=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**o,(i&128)===0)break;o+=7}let s=Buffer.allocUnsafe(n),r=0;while(t<e.length&&r<n){let i=e[t++],a=i&3;if(a===0){let c=i>>2;if(c>=60){let l=c-59;c=0;for(let u=0;u<l;u++)c+=e[t++]*2**(8*u)}c+=1,e.copy(s,r,t,t+c),t+=c,r+=c}else{let c,l;if(a===1)c=4+(i>>2&7),l=(i>>5&7)*256+e[t++];else if(a===2)c=1+(i>>2),l=e[t]+e[t+1]*256,t+=2;else c=1+(i>>2),l=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let u=r-l;for(let d=0;d<c&&r<n;d++)s[r++]=s[u++]}}return r===n?s:s.subarray(0,r)}function Gr(e,t){let n=Zn(e,t),o=Zn(e,n.pos);return{handle:{offset:n.value,size:o.value},pos:o.pos}}function bl(e,t){let{offset:n,size:o}=t,s=e.subarray(n,n+o);return e[n+o]===1?wh(s):Buffer.from(s)}function Dh(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,o=[],s=0,r=Buffer.alloc(0);while(s<n){let i=Zn(e,s),a=Zn(e,i.pos),c=Zn(e,a.pos);s=c.pos;let l=i.value,u=a.value,d=c.value,p=e.subarray(s,s+u);s+=u;let h=e.subarray(s,s+d);s+=d,r=Buffer.concat([r.subarray(0,l),p]),o.push(h)}return o}function kl(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=Gr(e,t),o=Gr(e,n.pos),s=bl(e,o.handle),r=[];for(let i of Dh(s))try{let{handle:a}=Gr(i,0);r.push(bl(e,a))}catch{}return Buffer.concat(r)}catch{return Buffer.alloc(0)}}function xl(){let e=process.env.HOME??oo();if(process.platform==="darwin")return[se(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[se(e,".config","Slack","Local Storage","leveldb"),se(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),se(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??se(e,"AppData","Roaming");return[se(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function Sh(){let e=process.env.HOME??oo();if(process.platform==="darwin")return se(e,"Library","Application Support","Slack","Cookies");return""}function Ch(e,t){if(e.length<35||e.slice(0,3).toString()!=="v10")throw Error("Not a v10 encrypted cookie");let n=e.slice(19,35),o=e.slice(35),s=_l("aes-128-cbc",t,n);return s.setAutoPadding(!0),Buffer.concat([s.update(o),s.final()]).toString("utf8")}function _h(){if(process.platform!=="darwin")return;let e=Sh();if(!Ke(e))return;let t;try{t=$l('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=so(t,"saltysalt",1003,16,"sha1");try{let{default:o}=Ln("bun:sqlite"),s=new o(e,{readonly:!0}),r=s.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(s.close(),!r)return;return Ch(Buffer.from(r.encrypted_value),n)}catch{return}}function Fl(e){if(!Ke(e))return[];let t=es(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,o=(i)=>{let a=n.get(i);if(a!==void 0)return a;let c="";try{let l=Qn(se(e,i));c=i.endsWith(".ldb")?kl(l).toString("latin1")||l.toString("latin1"):l.toString("latin1")}catch{c=""}return n.set(i,c),c},s=new Map;for(let i of t){let a=o(i);for(let c of a.matchAll(/"token":"(xoxc-[^"]+)"/g)){let l=c[1],u=l.split("-")[1]??"";if(!u||l.length<40)continue;let d=Math.max(0,c.index-2000),p=Math.min(a.length,c.index+2000),h=a.slice(d,p),y=h.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),f=h.match(/"(?:team_name|name)":"([^"]{2,60})"/),g=s.get(u);if(!g||l.length>g.token.length){let w={token:l,teamId:u},D=y?.[1]??g?.url,k=f?.[1]??g?.teamName;if(D)w.url=D;if(k)w.teamName=k;s.set(u,w)}}}let r=t.map((i)=>o(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of s.values()){if(i.teamName)continue;let a=r.indexOf(i.teamId);if(a!==-1){let c=Math.max(0,a-500),l=Math.min(r.length,a+500),d=r.slice(c,l).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){i.teamName=d[1];continue}}if(!i.teamName&&i.url){let c=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(c){let l=r.indexOf(c);if(l!==-1){let u=Math.max(0,l-500),d=Math.min(r.length,l+500),h=r.slice(u,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(h?.[1]){i.teamName=h[1];continue}}i.teamName=c.split("-").map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}}}return[...s.values()]}async function Vr(e){let t=e??xl().find(Ke);if(!t)throw Error(`Slack desktop app LevelDB not found at:
130
+ ${xl().join(`
131
131
  `)}
132
- Is Slack installed and opened at least once?`);let n=El(t),o=e?void 0:hh();if(o)for(let s of n)s.cookie=o;return n}function gh(e,t){try{return JSON.parse(Zn(ce(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function Gr(){let e=Yr();if(!e||!Ge(e))return[];let t=["Default",...Qn(e).filter((o)=>o.startsWith("Profile "))],n=[];for(let o of t){let s=ce(e,o,"Local Storage","leveldb"),r=El(s);if(r.length===0)continue;let i=gh(e,o);n.push({profileDir:o,...i?{email:i}:{},label:Sl(e,o),sessions:r})}return n}function qr(e,t,n,o=!1){let s=(r,i)=>{try{let a=kl("aes-128-cbc",t,r);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 l=lh("sha256").update(n).digest();if(uh(c.subarray(0,32),l)){let u=c.subarray(32).toString("utf8");if(u.startsWith("xoxd-"))return u}}return}catch{return}};return s(Buffer.alloc(16,32),e.slice(3))??(o&&e.length>=35?s(e.slice(19,35),e.slice(35)):void 0)}function Sl(e,t){let n=(o,s)=>{if(o&&s)return`${o} (${s})`;return o||s||t};try{let s=JSON.parse(Zn(ce(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(s&&(s.name||s.user_name))return n(s.name??"",s.user_name??"")}catch{}try{let s=JSON.parse(Zn(ce(e,t,"Preferences"),"utf8")).profile;return n(s?.name??"",s?.user_name??"")}catch{return t}}function Yr(){let e=process.env.HOME??no();if(process.platform==="darwin")return ce(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return ce(process.env.XDG_CONFIG_HOME??ce(e,".config"),"google-chrome");return""}function mh(){try{return dh("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function es(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=Yr();if(!Ge(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=xl('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=to(i,"saltysalt",1003,16,"sha1")}let n=["Default",...Qn(e).filter((i)=>i.startsWith("Profile "))],o=[],s,r=!1;for(let i of n){let a=[ce(e,i,"Network","Cookies"),ce(e,i,"Cookies")].find(Ge);if(!a)continue;let c=Dl(ce(bl(),"slack-chrome-cookies-")),l=ce(c,"Cookies");try{if(Hr(a,l),Ge(`${a}-wal`))Hr(`${a}-wal`,`${l}-wal`);let{default:u}=Ln("bun:sqlite"),d=new u(l,{readonly:!0}),f;try{f=d.prepare("SELECT encrypted_value, value, host_key FROM cookies WHERE name='d' AND (host_key='slack.com' OR host_key LIKE '%.slack.com') LIMIT 1").get()}finally{d.close()}if(!f)continue;let h=Buffer.from(f.encrypted_value),g=h.subarray(0,3).toString(),p;if(g==="v20")throw Error("Chrome cookie uses unsupported v20 app-bound encryption.");if(process.platform==="linux"){if(!h.length&&f.value?.startsWith("xoxd-"))p=f.value;else if(g==="v10")p=qr(h,to("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(g==="v11"){if(!s){let m=mh();if(m)s=to(m,"saltysalt",1,16,"sha1")}if(s)p=qr(h,s,f.host_key);else r=!0}}else if(g==="v10"&&t)p=qr(h,t,f.host_key,!0);else if(g!=="v10")throw Error("Unknown cookie encryption prefix.");if(p)o.push({profileDir:i,profileName:Sl(e,i),cookie:p})}catch(u){if(u instanceof Error&&(u.message.includes("unsupported v20")||u.message.includes("Unknown cookie")))throw u}finally{wl(c,{recursive:!0,force:!0})}}if(r&&o.length===0)throw Error("Chrome v11 cookie key is unavailable. Install secret-tool and unlock the GNOME keyring, or use slack auth firefox.");return{candidates:o,totalProfiles:n.length}}async function Xr(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=Yr();if(!Ge(e))throw Error("Chrome profile directory was not found.");let t=new Map(es().candidates.map((s)=>[s.profileDir,s.cookie])),n=new Map,o=["Default",...Qn(e).filter((s)=>s.startsWith("Profile "))];for(let s of o){let r=ce(e,s,"Local Storage","leveldb");if(!Ge(r))continue;let i;try{i=await zr(r)}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(s);if(c)a.cookie=c;n.set(a.teamId,a)}}return[...n.values()]}function yh(){let e=process.env.HOME??no();if(process.platform==="darwin")return[ce(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[ce(e,".mozilla","firefox"),ce(e,"snap","firefox","common",".mozilla","firefox"),ce(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[ce(process.env.APPDATA??ce(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function Dh(e){let t=ce(e,"profiles.ini"),n=Ge(t)?t:ce(ch(e),"profiles.ini"),o={};if(!Ge(n))return o;try{let s=Zn(n,"utf8"),r="",i="";for(let a of s.split(`
133
- `)){let c=a.trim();if(c.startsWith("[")){r="",i="";continue}let l=c.indexOf("=");if(l===-1)continue;let u=c.slice(0,l).trim().toLowerCase(),d=c.slice(l+1).trim();if(u==="name")r=d;if(u==="path")i=d.split(/[\\/]/).pop()??d;if(r&&i)o[i]=r,r="",i=""}}catch{}return o}function so(){let e=[];for(let t of yh().filter(Ge)){let n=Dh(t),o;try{o=Qn(t)}catch{continue}for(let s of o){let r=ce(t,s,"cookies.sqlite");if(!Ge(r))continue;let i=Dl(ce(bl(),"slack-firefox-cookies-")),a=ce(i,"cookies.sqlite");try{Hr(r,a);let{default:c}=Ln("bun:sqlite"),l=new c(a,{readonly:!0}),u=l.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(l.close(),!u?.value||!u.value.startsWith("xoxd-"))continue;let d=n[s]??s;e.push({profileDir:s,profileName:d,cookie:u.value})}catch{}finally{wl(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as Vr,writeFileSync as Zr,mkdirSync as wh,existsSync as ts,rmSync as bh}from"node:fs";import{join as et}from"node:path";import{createDecipheriv as oo}from"node:crypto";import{spawnSync as kh}from"node:child_process";var xh=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),Eh=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),Sh=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),at="C:\\ProgramData\\slack-term-abe";function Ch(){let e=process.env.LOCALAPPDATA??et(process.env.USERPROFILE??"","AppData","Local");return et(e,"Google","Chrome","User Data")}var _h=String.raw`try {
132
+ Is Slack installed and opened at least once?`);let n=Fl(t),o=e?void 0:_h();if(o)for(let s of n)s.cookie=o;return n}function $h(e,t){try{return JSON.parse(Qn(se(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function Zr(){let e=Qr();if(!e||!Ke(e))return[];let t=["Default",...es(e).filter((o)=>o.startsWith("Profile "))],n=[];for(let o of t){let s=se(e,o,"Local Storage","leveldb"),r=Fl(s);if(r.length===0)continue;let i=$h(e,o);n.push({profileDir:o,...i?{email:i}:{},label:Al(e,o),sessions:r})}return n}function Yr(e,t,n,o=!1){let s=(r,i)=>{try{let a=_l("aes-128-cbc",t,r);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 l=kh("sha256").update(n).digest();if(xh(c.subarray(0,32),l)){let u=c.subarray(32).toString("utf8");if(u.startsWith("xoxd-"))return u}}return}catch{return}};return s(Buffer.alloc(16,32),e.slice(3))??(o&&e.length>=35?s(e.slice(19,35),e.slice(35)):void 0)}function Al(e,t){let n=(o,s)=>{if(o&&s)return`${o} (${s})`;return o||s||t};try{let s=JSON.parse(Qn(se(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(s&&(s.name||s.user_name))return n(s.name??"",s.user_name??"")}catch{}try{let s=JSON.parse(Qn(se(e,t,"Preferences"),"utf8")).profile;return n(s?.name??"",s?.user_name??"")}catch{return t}}function Qr(){let e=process.env.HOME??oo();if(process.platform==="darwin")return se(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return se(process.env.XDG_CONFIG_HOME??se(e,".config"),"google-chrome");return""}function Fh(){try{return Eh("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function ts(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=Qr();if(!Ke(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=$l('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=so(i,"saltysalt",1003,16,"sha1")}let n=["Default",...es(e).filter((i)=>i.startsWith("Profile "))],o=[],s,r=!1;for(let i of n){let a=[se(e,i,"Network","Cookies"),se(e,i,"Cookies")].find(Ke);if(!a)continue;let c=El(se(Cl(),"slack-chrome-cookies-")),l=se(c,"Cookies");try{if(Xr(a,l),Ke(`${a}-wal`))Xr(`${a}-wal`,`${l}-wal`);let{default:u}=Ln("bun:sqlite"),d=new u(l,{readonly:!0}),p;try{p=d.prepare("SELECT encrypted_value, value, host_key FROM cookies WHERE name='d' AND (host_key='slack.com' OR host_key LIKE '%.slack.com') LIMIT 1").get()}finally{d.close()}if(!p)continue;let h=Buffer.from(p.encrypted_value),y=h.subarray(0,3).toString(),f;if(y==="v20")throw Error("Chrome cookie uses unsupported v20 app-bound encryption.");if(process.platform==="linux"){if(!h.length&&p.value?.startsWith("xoxd-"))f=p.value;else if(y==="v10")f=Yr(h,so("peanuts","saltysalt",1,16,"sha1"),p.host_key);else if(y==="v11"){if(!s){let g=Fh();if(g)s=so(g,"saltysalt",1,16,"sha1")}if(s)f=Yr(h,s,p.host_key);else r=!0}}else if(y==="v10"&&t)f=Yr(h,t,p.host_key,!0);else if(y!=="v10")throw Error("Unknown cookie encryption prefix.");if(f)o.push({profileDir:i,profileName:Al(e,i),cookie:f})}catch(u){if(u instanceof Error&&(u.message.includes("unsupported v20")||u.message.includes("Unknown cookie")))throw u}finally{Sl(c,{recursive:!0,force:!0})}}if(r&&o.length===0)throw Error("Chrome v11 cookie key is unavailable. Install secret-tool and unlock the GNOME keyring, or use slack auth firefox.");return{candidates:o,totalProfiles:n.length}}async function ei(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=Qr();if(!Ke(e))throw Error("Chrome profile directory was not found.");let t=new Map(ts().candidates.map((s)=>[s.profileDir,s.cookie])),n=new Map,o=["Default",...es(e).filter((s)=>s.startsWith("Profile "))];for(let s of o){let r=se(e,s,"Local Storage","leveldb");if(!Ke(r))continue;let i;try{i=await Vr(r)}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(s);if(c)a.cookie=c;n.set(a.teamId,a)}}return[...n.values()]}function Ah(){let e=process.env.HOME??oo();if(process.platform==="darwin")return[se(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[se(e,".mozilla","firefox"),se(e,"snap","firefox","common",".mozilla","firefox"),se(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[se(process.env.APPDATA??se(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function Th(e){let t=se(e,"profiles.ini"),n=Ke(t)?t:se(bh(e),"profiles.ini"),o={};if(!Ke(n))return o;try{let s=Qn(n,"utf8"),r="",i="";for(let a of s.split(`
133
+ `)){let c=a.trim();if(c.startsWith("[")){r="",i="";continue}let l=c.indexOf("=");if(l===-1)continue;let u=c.slice(0,l).trim().toLowerCase(),d=c.slice(l+1).trim();if(u==="name")r=d;if(u==="path")i=d.split(/[\\/]/).pop()??d;if(r&&i)o[i]=r,r="",i=""}}catch{}return o}function ro(){let e=[];for(let t of Ah().filter(Ke)){let n=Th(t),o;try{o=es(t)}catch{continue}for(let s of o){let r=se(t,s,"cookies.sqlite");if(!Ke(r))continue;let i=El(se(Cl(),"slack-firefox-cookies-")),a=se(i,"cookies.sqlite");try{Xr(r,a);let{default:c}=Ln("bun:sqlite"),l=new c(a,{readonly:!0}),u=l.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(l.close(),!u?.value||!u.value.startsWith("xoxd-"))continue;let d=n[s]??s;e.push({profileDir:s,profileName:d,cookie:u.value})}catch{}finally{Sl(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as ti,writeFileSync as ni,mkdirSync as Ih,existsSync as ns,rmSync as Oh}from"node:fs";import{join as Ve}from"node:path";import{createDecipheriv as io}from"node:crypto";import{spawnSync as Rh}from"node:child_process";var Ph=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),vh=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),Bh=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),ot="C:\\ProgramData\\slack-term-abe";function Lh(){let e=process.env.LOCALAPPDATA??Ve(process.env.USERPROFILE??"","AppData","Local");return Ve(e,"Google","Chrome","User Data")}var Nh=String.raw`try {
134
134
  Add-Type -AssemblyName System.Security
135
135
  $d = [IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\in.bin')
136
136
  $o = [Security.Cryptography.ProtectedData]::Unprotect($d, $null, 'CurrentUser')
137
137
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\sys.bin', $o)
138
138
  } catch { Set-Content 'C:\ProgramData\slack-term-abe\dpapi.err' ($_.Exception.Message) }
139
- `,$h=String.raw`try {
139
+ `,Mh=String.raw`try {
140
140
  Add-Type -TypeDefinition @'
141
141
  using System; using System.Runtime.InteropServices;
142
142
  public static class NC {
@@ -152,7 +152,7 @@ public static class NC {
152
152
  '@
153
153
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\cng.bin', [NC]::Dec([IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\eak.bin')))
154
154
  } catch { Set-Content 'C:\ProgramData\slack-term-abe\cng.err' ($_.Exception.Message) }
155
- `;function Fh(e,t){let n=(o)=>`'${o.replace(/'/g,"''")}'`;return String.raw`
155
+ `;function jh(e,t){let n=(o)=>`'${o.replace(/'/g,"''")}'`;return String.raw`
156
156
  $ErrorActionPreference = 'Stop'
157
157
  Add-Type -AssemblyName System.Security
158
158
  $work = 'C:\ProgramData\slack-term-abe'
@@ -218,59 +218,59 @@ icacls "$work\Cookies" /grant "$($u):(R)" | Out-Null
218
218
  if (Test-Path "$work\cng.bin") { icacls "$work\cng.bin" /grant "$($u):(R)" | Out-Null }
219
219
  Write-Host 'OK'
220
220
  try { Stop-Transcript | Out-Null } catch {}
221
- `}function Ah(e,t){let o=4+e.readUInt32LE(0)+4,s=e[o];if(s===1||s===2){let r=e.subarray(o+1,o+13),i=e.subarray(o+13,o+45),a=e.subarray(o+45,o+61),c=s===1?oo("aes-256-gcm",xh,r):oo("chacha20-poly1305",Eh,r,{authTagLength:16});return c.setAuthTag(a),Buffer.concat([c.update(i),c.final()])}if(s===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let r=e.subarray(o+33,o+45),i=e.subarray(o+45,o+77),a=e.subarray(o+77,o+93),c=Buffer.from(t.map((u,d)=>u^Sh[d])),l=oo("aes-256-gcm",c,r);return l.setAuthTag(a),Buffer.concat([l.update(i),l.final()])}throw Error(`Unsupported app-bound key flag: ${s}`)}function Th(e,t){let n=t.subarray(3,15),o=t.subarray(15,t.length-16),s=t.subarray(t.length-16),r=oo("aes-256-gcm",e,n);return r.setAuthTag(s),Buffer.concat([r.update(o),r.final()]).subarray(32).toString("utf8")}async function Cl(e){if(process.platform!=="win32")throw Error("Windows-only");let t=Ch();if(!ts(et(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);wh(at,{recursive:!0});let n=et(at,"extract.ps1");Zr(n,Fh(t,e)),Zr(et(at,"inner_dpapi.ps1"),_h),Zr(et(at,"inner_cng.ps1"),$h);let o=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,s=kh("powershell",["-NoProfile","-Command",o],{encoding:"utf8",windowsHide:!0});if(s.status!==0&&s.error)throw Error(`Failed to launch elevated helper: ${s.error.message}`);let r=et(at,"out.bin"),i=et(at,"Cookies");if(!ts(r)||!ts(i)){let a=ts(et(at,"log.txt"))?Vr(et(at,"log.txt"),"utf8").split(`
222
- `).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=Vr(r),c=ts(et(at,"cng.bin"))?Vr(et(at,"cng.bin")):void 0,l=Ah(a,c),{Database:u}=Ln("bun:sqlite"),d=new u(i,{readonly:!0}),f=d.query("SELECT encrypted_value v FROM cookies WHERE name = char(100) AND host_key LIKE char(37,115,108,97,99,107,37) LIMIT 1").get();if(d.close(),!f)throw Error("no Slack `d` cookie in that Chrome profile");let h=Buffer.from(f.v);if(h.subarray(0,3).toString()!=="v20")throw Error(`unexpected cookie version ${h.subarray(0,3).toString("latin1")}`);let g=Th(l,h);if(!g.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return g}finally{if(!process.env.SLACK_KEEP_ABE)bh(at,{recursive:!0,force:!0})}}var Rh=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],Ph=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function Sn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function vh(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:Rh}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function Lh(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:Ph}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function Ft(e,t){return(await e.question(t)).trim()}async function ns(e,t){if(t)return!0;if(!e)return!1;let n=await Ft(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function sn(e,t,n,o){console.error("Verifying token...");let s=await En(t,o),r=Sn(s.team),i;if(n)i=n;else if(e)i=await Ft(e,`Workspace name [${r}]: `)||r;else i=r;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-term/.env.local (current directory, slack-specific)"),console.log(" 3) ~/.slack-term/.env.local (global, available everywhere)"),console.log(" 4) profiles.json (multi-workspace: slack auth use)"),console.log("");let c=await Ft(e,"Choice [1/2/3/4, Enter=1]: ");if(c==="2")a=Qr(process.cwd(),".slack-term",".env.local");else if(c==="3")a=Qr(Oh(),".slack-term",".env.local");else if(c==="4")a=null;else a=Qr(process.cwd(),".env.local")}if(a===null)if(Ks(i,{token:t,...s,...o?{cookie:o}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${s.team} (${s.user})`),process.env.SLACK_MCP_XOXP_TOKEN)console.log(""),console.log("Warning: SLACK_MCP_XOXP_TOKEN is set — it conflicts with profiles."),console.log(" Unset it: unset SLACK_MCP_XOXP_TOKEN (and remove from ~/.zshrc / ~/.bashrc)");else console.log(` Run: slack auth use -g ${i}`);else{let c={SLACK_TOKEN:t};if(o)c.SLACK_COOKIE=o;Pr(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 ei(e,t=!1,n="auto",o=!1){console.error("Scanning Slack desktop app...");let s=await zr();if(s.length===0)console.error("No sessions found. Make sure Slack is installed and you have signed in at least once."),process.exit(1);if(process.platform==="linux"&&n!=="none"&&s.some((r)=>!r.cookie)&&await ns(e,t)){let r=[];if(n!=="chrome")for(let i of so())r.push({source:"Firefox",profileName:i.profileName,cookie:i.cookie});if(n==="chrome"||n==="all"||n==="auto"&&r.length===0)try{for(let i of es().candidates)r.push({source:"Chrome",profileName:i.profileName,cookie:i.cookie})}catch(i){console.error(i instanceof Error?i.message:String(i))}if(r.length===1){for(let i of s)i.cookie??=r[0].cookie;console.log(`Found Slack session cookie in ${r[0].source} profile: ${r[0].profileName}`)}else if(r.length>1)console.log("Multiple browser sessions found. Choose one later with slack auth chrome or slack auth firefox.");if(s.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await ti(s,e,o)}async function ti(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let o=e[0],s=o.teamName??o.teamId;console.log(`Found workspace: ${s}${o.cookie?" (+ xoxd cookie)":""}`),await sn(t,o.token,Sn(s),o.cookie),console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- token: slack auth login");return}for(let o of e){let s=o.teamName??o.teamId,r=Sn(s);Ks(r,{token:o.token,team:s,teamId:o.teamId,url:o.url??"",user:"",...o.cookie?{cookie:o.cookie}:{}}),console.log(`Added workspace "${r}": ${s}${o.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let o=Sn(e[0].teamName??e[0].teamId);console.log(`Run: slack auth use -g ${o}`)}else console.log("Run: slack auth ls then: slack auth use -g <name>");console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- user token by re-running: slack auth login")}async function _l(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 Ft(e,"Choice [1/2]: ")==="2"?"bot":"user",o=n==="user"?"xoxp-":"xoxb-",s=n==="user"?"User OAuth Token":"Bot User OAuth Token";console.log(""),console.log("Find your token here:"),console.log(" https://api.slack.com/apps"),console.log(" -> Select your app -> OAuth & Permissions"),console.log(` -> Copy the "${s}" (starts with ${o})`),console.log("");let r=await Ft(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(o))console.error(`Expected a ${o} token, got: ${r.slice(0,10)}...`),process.exit(1);await sn(e,r)}async function ro(e,t){let n=t==="user"?vh():Lh(),o=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",s=t==="user"?"xoxp-":"xoxb-";if(t==="bot")console.log("Note: bot tokens cannot use search:read (user-only scope)."),console.log(" The news and search commands will not work with a bot token."),console.log("");console.log("Step 1 -Create your Slack app:"),console.log(" Open: https://api.slack.com/apps"),console.log(' Click "Create New App" -> "From a manifest" -> select your workspace'),console.log(" Paste this manifest (JSON tab):"),console.log(""),console.log("-------------------------------------------------------------"),console.log(n),console.log("-------------------------------------------------------------"),console.log(""),console.log('Step 2 -Install: "Install App" -> "Install to Workspace" -> Authorize'),console.log(""),console.log("Step 3 -Copy your token:"),console.log(` OAuth & Permissions -> ${o}`),console.log("");let r=await Ft(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(s))console.error(`Expected a ${s} token, got: ${r.slice(0,10)}...`),process.exit(1);await sn(e,r)}async function Bh(e,t){let n=Gr();if(n.length===0)console.error("No Slack session found in Chrome. Sign in to Slack in Chrome (app.slack.com) and retry."),process.exit(1);let o=e.profile.token.split("-")[1],s=n.find((r)=>r.sessions.some((i)=>i.teamId===o));if(!s&&t){if(s=n.find((r)=>r.email===t||r.profileDir===t||r.profileDir===`Profile ${t}`),!s)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((r)=>r.email??r.profileDir).join(", ")}`),process.exit(1)}if(!s)if(n.length===1)s=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((c,l)=>console.log(` ${l+1}) ${c.email??c.label} [${c.profileDir}]`));let r=Me({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${n.length}]: `)).trim();r.close();let a=parseInt(i,10)-1;if(isNaN(a)||a<0||a>=n.length)console.error("Invalid choice."),process.exit(1);s=n[a]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),n.forEach((r)=>console.error(` slack auth cookie -w ${e.name} --profile "${r.email??r.profileDir}"`)),process.exit(1);console.log(`Using Chrome profile: ${s.email??s.label} [${s.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await Cl(s.profileDir)}catch(r){console.error(`
223
- Could not extract the cookie automatically: ${r instanceof Error?r.message:String(r)}`),console.error("Fallback (manual): Chrome > DevTools (F12) > Application > Cookies > https://app.slack.com > copy the `d` value,"),console.error("then set it via an env file: SLACK_COOKIE=xoxd-... (in .slack-term/.env.local)"),process.exit(1)}}async function $l(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=zn();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((i)=>i.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((i)=>i.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let r=t.find((i)=>i.current);if(r)n=r.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((l,u)=>console.log(` ${u+1}) ${l.name} (${l.profile.team})`));let i=Me({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 o=t.find((r)=>r.name===n);if(o.profile.token.startsWith("xoxb-")){console.error(`
221
+ `}function Wh(e,t){let o=4+e.readUInt32LE(0)+4,s=e[o];if(s===1||s===2){let r=e.subarray(o+1,o+13),i=e.subarray(o+13,o+45),a=e.subarray(o+45,o+61),c=s===1?io("aes-256-gcm",Ph,r):io("chacha20-poly1305",vh,r,{authTagLength:16});return c.setAuthTag(a),Buffer.concat([c.update(i),c.final()])}if(s===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let r=e.subarray(o+33,o+45),i=e.subarray(o+45,o+77),a=e.subarray(o+77,o+93),c=Buffer.from(t.map((u,d)=>u^Bh[d])),l=io("aes-256-gcm",c,r);return l.setAuthTag(a),Buffer.concat([l.update(i),l.final()])}throw Error(`Unsupported app-bound key flag: ${s}`)}function Uh(e,t){let n=t.subarray(3,15),o=t.subarray(15,t.length-16),s=t.subarray(t.length-16),r=io("aes-256-gcm",e,n);return r.setAuthTag(s),Buffer.concat([r.update(o),r.final()]).subarray(32).toString("utf8")}async function Tl(e){if(process.platform!=="win32")throw Error("Windows-only");let t=Lh();if(!ns(Ve(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);Ih(ot,{recursive:!0});let n=Ve(ot,"extract.ps1");ni(n,jh(t,e)),ni(Ve(ot,"inner_dpapi.ps1"),Nh),ni(Ve(ot,"inner_cng.ps1"),Mh);let o=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,s=Rh("powershell",["-NoProfile","-Command",o],{encoding:"utf8",windowsHide:!0});if(s.status!==0&&s.error)throw Error(`Failed to launch elevated helper: ${s.error.message}`);let r=Ve(ot,"out.bin"),i=Ve(ot,"Cookies");if(!ns(r)||!ns(i)){let a=ns(Ve(ot,"log.txt"))?ti(Ve(ot,"log.txt"),"utf8").split(`
222
+ `).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=ti(r),c=ns(Ve(ot,"cng.bin"))?ti(Ve(ot,"cng.bin")):void 0,l=Wh(a,c),{Database:u}=Ln("bun:sqlite"),d=new u(i,{readonly:!0}),p=d.query("SELECT encrypted_value v FROM cookies WHERE name = char(100) AND host_key LIKE char(37,115,108,97,99,107,37) LIMIT 1").get();if(d.close(),!p)throw Error("no Slack `d` cookie in that Chrome profile");let h=Buffer.from(p.v);if(h.subarray(0,3).toString()!=="v20")throw Error(`unexpected cookie version ${h.subarray(0,3).toString("latin1")}`);let y=Uh(l,h);if(!y.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return y}finally{if(!process.env.SLACK_KEEP_ABE)Oh(ot,{recursive:!0,force:!0})}}var qh=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],Hh=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function Cn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function zh(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:qh}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function Gh(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:Hh}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function Ft(e,t){return(await e.question(t)).trim()}async function ss(e,t){if(t)return!0;if(!e)return!1;let n=await Ft(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function on(e,t,n,o){console.error("Verifying token...");let s=await Sn(t,o),r=Cn(s.team),i;if(n)i=n;else if(e)i=await Ft(e,`Workspace name [${r}]: `)||r;else i=r;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-term/.env.local (current directory, slack-specific)"),console.log(" 3) ~/.slack-term/.env.local (global, available everywhere)"),console.log(" 4) profiles.json (multi-workspace: slack auth use)"),console.log("");let c=await Ft(e,"Choice [1/2/3/4, Enter=1]: ");if(c==="2")a=si(process.cwd(),".slack-term",".env.local");else if(c==="3")a=si(Kh(),".slack-term",".env.local");else if(c==="4")a=null;else a=si(process.cwd(),".env.local")}if(a===null)if(Hs(i,{token:t,...s,...o?{cookie:o}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${s.team} (${s.user})`),process.env.SLACK_MCP_XOXP_TOKEN)console.log(""),console.log("Warning: SLACK_MCP_XOXP_TOKEN is set — it conflicts with profiles."),console.log(" Unset it: unset SLACK_MCP_XOXP_TOKEN (and remove from ~/.zshrc / ~/.bashrc)");else console.log(` Run: slack auth use -g ${i}`);else{let c={SLACK_TOKEN:t};if(o)c.SLACK_COOKIE=o;Nr(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 oi(e,t=!1,n="auto",o=!1){console.error("Scanning Slack desktop app...");let s=await Vr();if(s.length===0)console.error("No sessions found. Make sure Slack is installed and you have signed in at least once."),process.exit(1);if(process.platform==="linux"&&n!=="none"&&s.some((r)=>!r.cookie)&&await ss(e,t)){let r=[];if(n!=="chrome")for(let i of ro())r.push({source:"Firefox",profileName:i.profileName,cookie:i.cookie});if(n==="chrome"||n==="all"||n==="auto"&&r.length===0)try{for(let i of ts().candidates)r.push({source:"Chrome",profileName:i.profileName,cookie:i.cookie})}catch(i){console.error(i instanceof Error?i.message:String(i))}if(r.length===1){for(let i of s)i.cookie??=r[0].cookie;console.log(`Found Slack session cookie in ${r[0].source} profile: ${r[0].profileName}`)}else if(r.length>1)console.log("Multiple browser sessions found. Choose one later with slack auth chrome or slack auth firefox.");if(s.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await ri(s,e,o)}async function ri(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let o=e[0],s=o.teamName??o.teamId;console.log(`Found workspace: ${s}${o.cookie?" (+ xoxd cookie)":""}`),await on(t,o.token,Cn(s),o.cookie),console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- token: slack auth login");return}for(let o of e){let s=o.teamName??o.teamId,r=Cn(s);Hs(r,{token:o.token,team:s,teamId:o.teamId,url:o.url??"",user:"",...o.cookie?{cookie:o.cookie}:{}}),console.log(`Added workspace "${r}": ${s}${o.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let o=Cn(e[0].teamName??e[0].teamId);console.log(`Run: slack auth use -g ${o}`)}else console.log("Run: slack auth ls then: slack auth use -g <name>");console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- user token by re-running: slack auth login")}async function Il(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 Ft(e,"Choice [1/2]: ")==="2"?"bot":"user",o=n==="user"?"xoxp-":"xoxb-",s=n==="user"?"User OAuth Token":"Bot User OAuth Token";console.log(""),console.log("Find your token here:"),console.log(" https://api.slack.com/apps"),console.log(" -> Select your app -> OAuth & Permissions"),console.log(` -> Copy the "${s}" (starts with ${o})`),console.log("");let r=await Ft(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(o))console.error(`Expected a ${o} token, got: ${r.slice(0,10)}...`),process.exit(1);await on(e,r)}async function ao(e,t){let n=t==="user"?zh():Gh(),o=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",s=t==="user"?"xoxp-":"xoxb-";if(t==="bot")console.log("Note: bot tokens cannot use search:read (user-only scope)."),console.log(" The news and search commands will not work with a bot token."),console.log("");console.log("Step 1 -Create your Slack app:"),console.log(" Open: https://api.slack.com/apps"),console.log(' Click "Create New App" -> "From a manifest" -> select your workspace'),console.log(" Paste this manifest (JSON tab):"),console.log(""),console.log("-------------------------------------------------------------"),console.log(n),console.log("-------------------------------------------------------------"),console.log(""),console.log('Step 2 -Install: "Install App" -> "Install to Workspace" -> Authorize'),console.log(""),console.log("Step 3 -Copy your token:"),console.log(` OAuth & Permissions -> ${o}`),console.log("");let r=await Ft(e,"Paste your token: ");if(!r)console.error("No token provided."),process.exit(1);if(!r.startsWith(s))console.error(`Expected a ${s} token, got: ${r.slice(0,10)}...`),process.exit(1);await on(e,r)}async function Yh(e,t){let n=Zr();if(n.length===0)console.error("No Slack session found in Chrome. Sign in to Slack in Chrome (app.slack.com) and retry."),process.exit(1);let o=e.profile.token.split("-")[1],s=n.find((r)=>r.sessions.some((i)=>i.teamId===o));if(!s&&t){if(s=n.find((r)=>r.email===t||r.profileDir===t||r.profileDir===`Profile ${t}`),!s)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((r)=>r.email??r.profileDir).join(", ")}`),process.exit(1)}if(!s)if(n.length===1)s=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((c,l)=>console.log(` ${l+1}) ${c.email??c.label} [${c.profileDir}]`));let r=Le({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${n.length}]: `)).trim();r.close();let a=parseInt(i,10)-1;if(isNaN(a)||a<0||a>=n.length)console.error("Invalid choice."),process.exit(1);s=n[a]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),n.forEach((r)=>console.error(` slack auth cookie -w ${e.name} --profile "${r.email??r.profileDir}"`)),process.exit(1);console.log(`Using Chrome profile: ${s.email??s.label} [${s.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await Tl(s.profileDir)}catch(r){console.error(`
223
+ Could not extract the cookie automatically: ${r instanceof Error?r.message:String(r)}`),console.error("Fallback (manual): Chrome > DevTools (F12) > Application > Cookies > https://app.slack.com > copy the `d` value,"),console.error("then set it via an env file: SLACK_COOKIE=xoxd-... (in .slack-term/.env.local)"),process.exit(1)}}async function Ol(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=Gn();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((i)=>i.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((i)=>i.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let r=t.find((i)=>i.current);if(r)n=r.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((l,u)=>console.log(` ${u+1}) ${l.name} (${l.profile.team})`));let i=Le({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 o=t.find((r)=>r.name===n);if(o.profile.token.startsWith("xoxb-")){console.error(`
224
224
  Workspace "${n}" uses a bot token (xoxb-). A Chrome session cookie only
225
225
  `+`augments a user session token (xoxc-) — it has no effect on a bot token, so user-level
226
- `+"actions (tail @user, DMs, listing users) would still fail.");let r=t.filter((i)=>i.profile.token.startsWith("xoxc-")||i.profile.token.startsWith("xoxp-"));if(r.length>0)console.error(` Target a user-token workspace instead: ${r.map((i)=>i.name).join(", ")}`),console.error(` slack auth chrome -w ${r[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let s;if(process.platform==="win32")s=await Bh(o,e.profile);else{if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let r=e.yes?void 0:Me({input:process.stdin,output:process.stdout});try{if(!await ns(r,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{r?.close()}if(console.log("Scanning Chrome profiles for Slack session..."),process.platform==="darwin")console.log("macOS may show a dialog asking for your login password — click Allow.");let i,a;try{({candidates:i,totalProfiles:a}=es())}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)s=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((h,g)=>console.log(` ${g+1}) ${h.profileName} [${h.profileDir}]`)),console.log("");let l=Me({input:process.stdin,output:process.stdout}),u=i.length===1?" [Enter=1]":"",d=(await l.question(`Choice [1-${i.length}]${u}: `)).trim();l.close();let f=d===""&&i.length===1?0:parseInt(d,10)-1;if(isNaN(f)||f<0||f>=i.length)console.error("Invalid choice."),process.exit(1);s=i[f].cookie}}vr(n,s),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function ni(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=Gr();if(t.length===0)console.error("No Slack session found in Chrome."),console.error(" Open Slack in Chrome (https://app.slack.com) and sign in, then retry."),process.exit(1);let n;if(e.profile){let r=e.profile,i=t.find((a)=>a.email===r||a.profileDir===r||a.profileDir===`Profile ${r}`);if(!i)console.error(`Chrome profile "${r}" 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,l)=>console.log(` ${l+1}) ${c.email??c.label} [${c.profileDir}] (${c.sessions.length} workspace${c.sessions.length!==1?"s":""})`));let r=Me({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${t.length}]: `)).trim();r.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((r)=>console.error(` slack auth login chrome --profile "${r.email??r.profileDir}"`)),process.exit(1);let o=n.email??n.label??n.profileDir,s;if(process.platform==="darwin")try{let{candidates:r}=es();s=r.find((i)=>i.profileDir===n.profileDir)?.cookie??r[0]?.cookie}catch{}if(s)Qc(o,s,`chrome:${n.profileDir}`);for(let r of n.sessions){let i=r.teamName??r.teamId,a=Sn(i);Ks(a,{token:r.token,team:i,teamId:r.teamId,url:r.url??"",user:"",identity:o}),console.log(`Added workspace "${a}": ${i} (identity: ${o})`)}if(console.log(""),s)console.log(`Captured xoxd cookie for ${o} — shared across its ${n.sessions.length} workspace(s).`),console.log("RTM WebSocket mode is now available: slack tail @you");else console.log("Note: no xoxd cookie captured (LocalStorage yields the token only; the cookie is"),console.log("encrypted at rest on this platform). Some features (RTM, drafts, search fallback) need it."),console.log(" Attach it from your live browser — e.g. a CDP read via rech — or paste it:"),console.log(` slack auth cookie --workspace ${Sn(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 si(e={}){let t=zn();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((u,d)=>console.log(` ${d+1}) ${u.name} (${u.profile.team})`));let a=Me({input:process.stdin,output:process.stdout}),c=(await a.question("Choice: ")).trim();a.close();let l=parseInt(c,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let o=e.yes?void 0:Me({input:process.stdin,output:process.stdout});try{if(!await ns(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.close()}console.log("Scanning Firefox profiles for Slack session...");let s=so();if(s.length===0)console.error("No Slack session found in Firefox. Possible reasons:"),console.error(" - Firefox is not installed"),console.error(" - You are not logged in to Slack in Firefox"),process.exit(1);let r;if(s.length===1)r=s[0].cookie,console.log(`Found session in Firefox profile: ${s[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),s.forEach((l,u)=>console.log(` ${u+1}) ${l.profileName} [${l.profileDir}]`));let i=Me({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>=s.length)console.error("Invalid choice."),process.exit(1);r=s[c].cookie}vr(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Fl(e={}){if(e.token){await sn(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let s of process.stdin)n.push(s);let o=Buffer.concat(n).toString("utf8").trim();if(!o)console.error("No token provided on stdin."),process.exit(1);await sn(null,o,e.name);return}let t=Me({input:process.stdin,output:process.stdout});try{await _l(t)}finally{t.close()}}async function Al(e={}){let t=Me({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await ro(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 Ft(t,"Choice [1/2, Enter=1]: ");await ro(t,n==="2"?"bot":"user")}finally{t.close()}}function Tl(e={}){let t=(s,r)=>{if(/[\r\n]/.test(r))throw Error(`Invalid newline in ${s}.`);return`${s}=${/^[A-Za-z0-9._=-]+$/.test(r)?r:JSON.stringify(r)}`},n=[t("SLACK_TOKEN",el(e.workspace))],o=$t(e.workspace);if(o)n.push(t("SLACK_COOKIE",o));if(!e.workspace){let s=qs();if(s)n.push(t("SLACK_BOT_TOKEN",s))}console.log(n.join(`
227
- `))}function Il(e){let t=zn(),n=e.workspace?t.find((s)=>s.name===e.workspace):t.find((s)=>s.current)??(t.length===1?t[0]:void 0);if(!n)throw Error(e.workspace?`Workspace "${e.workspace}" not found. Run: slack auth ls`:"Select a workspace with slack auth use <name>, or pass --workspace <name>.");if(!n.profile.cookie)throw Error(`Workspace "${n.name}" has no session cookie. Run: slack auth chrome -w ${n.name} or slack auth firefox -w ${n.name}`);let o=Ih(e.envfile);Pr(o,{SLACK_TOKEN:n.profile.token,SLACK_COOKIE:n.profile.cookie}),console.log(`Saved token and cookie for workspace "${n.name}" to ${o}`)}async function ss(e={}){let t=zn();if(t.length>0){console.log("Currently logged in:");for(let{name:o,profile:s,current:r}of t)console.log(` ${r?"*":" "} ${o} ${s.team} (${s.user||"unknown"})`);console.log(""),console.log("Adding another workspace:"),console.log("")}if([e.fromChrome,e.fromFirefox,e.fromAll].filter(Boolean).length>1)throw Error("Choose only one browser source: --from-chrome, --from-firefox, or --from-all.");if(e.fromChrome&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Me({input:process.stdin,output:process.stdout}):void 0;try{if(!await ns(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let s=await Xr();if(s.length===0)throw Error("No Slack session token found in Chrome profiles.");await ti(s,o,!0)}finally{o?.close()}return}if(e.fromAll&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Me({input:process.stdin,output:process.stdout}):void 0;try{try{await ei(o,e.yes??!1,"all",!0)}catch(s){if(!(s instanceof Error)||!s.message.startsWith("Slack desktop app LevelDB not found"))throw s;if(!await ns(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await Xr();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");if(r.every((i)=>!i.cookie)){let i=so();if(i.length===1)for(let a of r)a.cookie=i[0].cookie}await ti(r,o,!0)}}finally{o?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let o=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(o!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Me({input:process.stdin,output:process.stdout}):void 0;try{await ei(s,e.yes??!1,o,!0)}finally{s?.close()}return}if(e.token){await sn(null,e.token,e.name);return}if(!process.stdin.isTTY){let o=[];for await(let r of process.stdin)o.push(r);let s=Buffer.concat(o).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await sn(null,s,e.name);return}console.log("How would you like to authenticate with Slack?"),console.log(""),console.log(" 1) Slack desktop app - import session token"),console.log(" Reads the xoxc- token directly from the installed app."),console.log(" Token: all platforms | xoxd cookie: macOS, or Chrome/Firefox on Linux"),console.log(""),console.log(" 2) Chrome browser - import workspaces"),console.log(" Reads xoxc- tokens from Chrome, grouped by account."),console.log(" Token: all platforms | xoxd cookie: macOS only"),console.log(""),console.log(" 3) Connect existing Slack app [recommended if you have one]"),console.log(" Paste a token from an app you already created."),console.log(""),console.log(" 4) Create new Slack app - user token (xoxp-)"),console.log(" Guided setup with manifest. Full access including search."),console.log(""),console.log(" 5) Create new Slack app - bot token (xoxb-)"),console.log(" Bot is invited to channels. Search and news unavailable."),console.log("");let n=Me({input:process.stdin,output:process.stdout});try{let o=await Ft(n,"Choice [1/2/3/4/5]: ");if(console.log(""),o==="1")await ei(n,e.yes??!1);else if(o==="2"){n.close(),await ni();return}else if(o==="3")await _l(n);else if(o==="4")await ro(n,"user");else if(o==="5")await ro(n,"bot");else console.error(`Invalid choice: "${o}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function io(e,t,n,o){let s=t,r=[],i=s,a=0;while(!0){let c=i.indexOf("<@U",a);if(c===-1)break;let l=i.slice(c+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);a=c+1}for(let c of r){if(!n.has(c))n.set(c,await Vs(e,c,o));let l=n.get(c)??c;s=s.replaceAll(`<@${c}>`,`@${l}`),s=s.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${l}`)}return s}function ao(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=i[r.getUTCDay()]??"",l=a[r.getUTCMonth()]??"";return`${c}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function Rl(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Nh(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),a=String(o.getUTCHours()).padStart(2,"0"),c=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${a}:${c}:${l}.${u}`}async function Mh(e,t,n){let o=typeof t.ts==="string"?t.ts:"0.000000",s=Nh(o),r="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,h]=await Xs(e,d);n.set(f,h)}r=n.get(f)??d}else if(typeof t.username==="string")r=t.username;let i=typeof t.text==="string"?t.text:"",c=ao(await io(e,i,n)).split(`
226
+ `+"actions (tail @user, DMs, listing users) would still fail.");let r=t.filter((i)=>i.profile.token.startsWith("xoxc-")||i.profile.token.startsWith("xoxp-"));if(r.length>0)console.error(` Target a user-token workspace instead: ${r.map((i)=>i.name).join(", ")}`),console.error(` slack auth chrome -w ${r[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let s;if(process.platform==="win32")s=await Yh(o,e.profile);else{if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let r=e.yes?void 0:Le({input:process.stdin,output:process.stdout});try{if(!await ss(r,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{r?.close()}if(console.log("Scanning Chrome profiles for Slack session..."),process.platform==="darwin")console.log("macOS may show a dialog asking for your login password — click Allow.");let i,a;try{({candidates:i,totalProfiles:a}=ts())}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)s=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((h,y)=>console.log(` ${y+1}) ${h.profileName} [${h.profileDir}]`)),console.log("");let l=Le({input:process.stdin,output:process.stdout}),u=i.length===1?" [Enter=1]":"",d=(await l.question(`Choice [1-${i.length}]${u}: `)).trim();l.close();let p=d===""&&i.length===1?0:parseInt(d,10)-1;if(isNaN(p)||p<0||p>=i.length)console.error("Invalid choice."),process.exit(1);s=i[p].cookie}}Mr(n,s),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function ii(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=Zr();if(t.length===0)console.error("No Slack session found in Chrome."),console.error(" Open Slack in Chrome (https://app.slack.com) and sign in, then retry."),process.exit(1);let n;if(e.profile){let r=e.profile,i=t.find((a)=>a.email===r||a.profileDir===r||a.profileDir===`Profile ${r}`);if(!i)console.error(`Chrome profile "${r}" 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,l)=>console.log(` ${l+1}) ${c.email??c.label} [${c.profileDir}] (${c.sessions.length} workspace${c.sessions.length!==1?"s":""})`));let r=Le({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${t.length}]: `)).trim();r.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((r)=>console.error(` slack auth login chrome --profile "${r.email??r.profileDir}"`)),process.exit(1);let o=n.email??n.label??n.profileDir,s;if(process.platform==="darwin")try{let{candidates:r}=ts();s=r.find((i)=>i.profileDir===n.profileDir)?.cookie??r[0]?.cookie}catch{}if(s)ol(o,s,`chrome:${n.profileDir}`);for(let r of n.sessions){let i=r.teamName??r.teamId,a=Cn(i);Hs(a,{token:r.token,team:i,teamId:r.teamId,url:r.url??"",user:"",identity:o}),console.log(`Added workspace "${a}": ${i} (identity: ${o})`)}if(console.log(""),s)console.log(`Captured xoxd cookie for ${o} — shared across its ${n.sessions.length} workspace(s).`),console.log("RTM WebSocket mode is now available: slack tail @you");else console.log("Note: no xoxd cookie captured (LocalStorage yields the token only; the cookie is"),console.log("encrypted at rest on this platform). Some features (RTM, drafts, search fallback) need it."),console.log(" Attach it from your live browser — e.g. a CDP read via rech — or paste it:"),console.log(` slack auth cookie --workspace ${Cn(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 ai(e={}){let t=Gn();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((u,d)=>console.log(` ${d+1}) ${u.name} (${u.profile.team})`));let a=Le({input:process.stdin,output:process.stdout}),c=(await a.question("Choice: ")).trim();a.close();let l=parseInt(c,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let o=e.yes?void 0:Le({input:process.stdin,output:process.stdout});try{if(!await ss(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.close()}console.log("Scanning Firefox profiles for Slack session...");let s=ro();if(s.length===0)console.error("No Slack session found in Firefox. Possible reasons:"),console.error(" - Firefox is not installed"),console.error(" - You are not logged in to Slack in Firefox"),process.exit(1);let r;if(s.length===1)r=s[0].cookie,console.log(`Found session in Firefox profile: ${s[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),s.forEach((l,u)=>console.log(` ${u+1}) ${l.profileName} [${l.profileDir}]`));let i=Le({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>=s.length)console.error("Invalid choice."),process.exit(1);r=s[c].cookie}Mr(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Rl(e={}){if(e.token){await on(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let s of process.stdin)n.push(s);let o=Buffer.concat(n).toString("utf8").trim();if(!o)console.error("No token provided on stdin."),process.exit(1);await on(null,o,e.name);return}let t=Le({input:process.stdin,output:process.stdout});try{await Il(t)}finally{t.close()}}async function Pl(e={}){let t=Le({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await ao(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 Ft(t,"Choice [1/2, Enter=1]: ");await ao(t,n==="2"?"bot":"user")}finally{t.close()}}function vl(e={}){let t=(s,r)=>{if(/[\r\n]/.test(r))throw Error(`Invalid newline in ${s}.`);return`${s}=${/^[A-Za-z0-9._=-]+$/.test(r)?r:JSON.stringify(r)}`},n=[t("SLACK_TOKEN",rl(e.workspace))],o=$t(e.workspace);if(o)n.push(t("SLACK_COOKIE",o));if(!e.workspace){let s=zs();if(s)n.push(t("SLACK_BOT_TOKEN",s))}console.log(n.join(`
227
+ `))}function Bl(e){let t=Gn(),n=e.workspace?t.find((s)=>s.name===e.workspace):t.find((s)=>s.current)??(t.length===1?t[0]:void 0);if(!n)throw Error(e.workspace?`Workspace "${e.workspace}" not found. Run: slack auth ls`:"Select a workspace with slack auth use <name>, or pass --workspace <name>.");if(!n.profile.cookie)throw Error(`Workspace "${n.name}" has no session cookie. Run: slack auth chrome -w ${n.name} or slack auth firefox -w ${n.name}`);let o=Jh(e.envfile);Nr(o,{SLACK_TOKEN:n.profile.token,SLACK_COOKIE:n.profile.cookie}),console.log(`Saved token and cookie for workspace "${n.name}" to ${o}`)}async function os(e={}){let t=Gn();if(t.length>0){console.log("Currently logged in:");for(let{name:o,profile:s,current:r}of t)console.log(` ${r?"*":" "} ${o} ${s.team} (${s.user||"unknown"})`);console.log(""),console.log("Adding another workspace:"),console.log("")}if([e.fromChrome,e.fromFirefox,e.fromAll].filter(Boolean).length>1)throw Error("Choose only one browser source: --from-chrome, --from-firefox, or --from-all.");if(e.fromChrome&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Le({input:process.stdin,output:process.stdout}):void 0;try{if(!await ss(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let s=await ei();if(s.length===0)throw Error("No Slack session token found in Chrome profiles.");await ri(s,o,!0)}finally{o?.close()}return}if(e.fromAll&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Le({input:process.stdin,output:process.stdout}):void 0;try{try{await oi(o,e.yes??!1,"all",!0)}catch(s){if(!(s instanceof Error)||!s.message.startsWith("Slack desktop app LevelDB not found"))throw s;if(!await ss(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await ei();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");if(r.every((i)=>!i.cookie)){let i=ro();if(i.length===1)for(let a of r)a.cookie=i[0].cookie}await ri(r,o,!0)}}finally{o?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let o=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(o!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Le({input:process.stdin,output:process.stdout}):void 0;try{await oi(s,e.yes??!1,o,!0)}finally{s?.close()}return}if(e.token){await on(null,e.token,e.name);return}if(!process.stdin.isTTY){let o=[];for await(let r of process.stdin)o.push(r);let s=Buffer.concat(o).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await on(null,s,e.name);return}console.log("How would you like to authenticate with Slack?"),console.log(""),console.log(" 1) Slack desktop app - import session token"),console.log(" Reads the xoxc- token directly from the installed app."),console.log(" Token: all platforms | xoxd cookie: macOS, or Chrome/Firefox on Linux"),console.log(""),console.log(" 2) Chrome browser - import workspaces"),console.log(" Reads xoxc- tokens from Chrome, grouped by account."),console.log(" Token: all platforms | xoxd cookie: macOS only"),console.log(""),console.log(" 3) Connect existing Slack app [recommended if you have one]"),console.log(" Paste a token from an app you already created."),console.log(""),console.log(" 4) Create new Slack app - user token (xoxp-)"),console.log(" Guided setup with manifest. Full access including search."),console.log(""),console.log(" 5) Create new Slack app - bot token (xoxb-)"),console.log(" Bot is invited to channels. Search and news unavailable."),console.log("");let n=Le({input:process.stdin,output:process.stdout});try{let o=await Ft(n,"Choice [1/2/3/4/5]: ");if(console.log(""),o==="1")await oi(n,e.yes??!1);else if(o==="2"){n.close(),await ii();return}else if(o==="3")await Il(n);else if(o==="4")await ao(n,"user");else if(o==="5")await ao(n,"bot");else console.error(`Invalid choice: "${o}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function co(e,t,n,o){let s=t,r=[],i=s,a=0;while(!0){let c=i.indexOf("<@U",a);if(c===-1)break;let l=i.slice(c+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);a=c+1}for(let c of r){if(!n.has(c))n.set(c,await Qs(e,c,o));let l=n.get(c)??c;s=s.replaceAll(`<@${c}>`,`@${l}`),s=s.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${l}`)}return s}function lo(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=i[r.getUTCDay()]??"",l=a[r.getUTCMonth()]??"";return`${c}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function Nl(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Xh(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),a=String(o.getUTCHours()).padStart(2,"0"),c=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${a}:${c}:${l}.${u}`}async function Vh(e,t,n){let o=typeof t.ts==="string"?t.ts:"0.000000",s=Xh(o),r="?";if(typeof t.user==="string"){let d=t.user,p="@"+d;if(!n.has(p)){let[,h]=await Zs(e,d);n.set(p,h)}r=n.get(p)??d}else if(typeof t.username==="string")r=t.username;let i=typeof t.text==="string"?t.text:"",c=lo(await co(e,i,n)).split(`
228
228
  `),l=c[0]+(c.length>1?`
229
229
  `+c.slice(1).map((d)=>` ${d}`).join(`
230
- `):""),u=Rl(t)?"↳ ":"";return`${s} ${u}@${r}: ${l}`}async function jh(e,t,n,o,s,r,i,a){if(a?.aborted)return;return new Promise((c)=>{let l=new e(n);a?.addEventListener("abort",()=>{l.close(),c()},{once:!0}),l.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
231
- `)}),l.addEventListener("close",()=>c()),l.addEventListener("error",()=>c()),l.addEventListener("message",(u)=>{(async()=>{try{let d;try{d=JSON.parse(String(u.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){l.send(JSON.stringify({type:"pong",reply_to:d.id??0}));return}if(f!=="message")return;if((typeof d.channel==="string"?d.channel:"")!==o)return;let g=typeof d.ts==="string"?d.ts:"";if(!g||r.has(g))return;let p=typeof d.subtype==="string"?d.subtype:"";if(p==="message_changed"||p==="message_deleted")return;if(s.thread){if((typeof d.thread_ts==="string"?d.thread_ts:g)!==s.thread&&g!==s.thread)return}if(s.watchThread&&Rl(d)){if((typeof d.thread_ts==="string"?d.thread_ts:"")!==s.watchThread)return}if(s.me&&s.myUserId){if(!(typeof d.text==="string"?d.text:"").includes(`<@${s.myUserId}>`))return}if(r.add(g),r.size>1000){let D=r.values().next().value;if(D!==void 0)r.delete(D)}let m=await Mh(t,d,i);process.stdout.write(m+`
230
+ `):""),u=Nl(t)?"↳ ":"";return`${s} ${u}@${r}: ${l}`}async function Zh(e,t,n,o,s,r,i,a){if(a?.aborted)return;return new Promise((c)=>{let l=new e(n);a?.addEventListener("abort",()=>{l.close(),c()},{once:!0}),l.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
231
+ `)}),l.addEventListener("close",()=>c()),l.addEventListener("error",()=>c()),l.addEventListener("message",(u)=>{(async()=>{try{let d;try{d=JSON.parse(String(u.data))}catch{return}let p=typeof d.type==="string"?d.type:"";if(p==="ping"){l.send(JSON.stringify({type:"pong",reply_to:d.id??0}));return}if(p!=="message")return;if((typeof d.channel==="string"?d.channel:"")!==o)return;let y=typeof d.ts==="string"?d.ts:"";if(!y||r.has(y))return;let f=typeof d.subtype==="string"?d.subtype:"";if(f==="message_changed"||f==="message_deleted")return;if(s.thread){if((typeof d.thread_ts==="string"?d.thread_ts:y)!==s.thread&&y!==s.thread)return}if(s.watchThread&&Nl(d)){if((typeof d.thread_ts==="string"?d.thread_ts:"")!==s.watchThread)return}if(s.me&&s.myUserId){if(!(typeof d.text==="string"?d.text:"").includes(`<@${s.myUserId}>`))return}if(r.add(y),r.size>1000){let w=r.values().next().value;if(w!==void 0)r.delete(w)}let g=await Vh(t,d,i);process.stdout.write(g+`
232
232
  `)}catch(d){process.stderr.write(`RTM message error: ${d instanceof Error?d.message:String(d)}
233
- `)}})()})})}var Ol=3,Wh=2000,oi={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:pl,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function Pl(e,t,n,o,s,r,i){let a=oi.getWebSocket();if(!a)return;for(let c=0;c<Ol;c++){if(i?.aborted)return;try{let{wsUrl:l}=await oi.clientBoot(e,t);await jh(a,e,l,n,o,s,r,i)}catch{}if(i?.aborted)return;if(c<Ol-1)await oi.sleep(Wh)}}function vl(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 ct={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:Pl};function pt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function ri(e){return Array.isArray(e)?e:[]}function Ll(e){return Number(e)||0}function Bl(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Uh(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),a=String(o.getUTCHours()).padStart(2,"0"),c=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${a}:${c}:${l}.${u}`}async function Jh(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:"0.000000",i=Uh(r),a="?";if(typeof t.user==="string"){let g=t.user,p="@"+g;if(!n.has(p)){let[,m]=await Xs(e,g,s);n.set(p,m)}a=n.get(p)??g}else if(typeof t.username==="string")a=t.username;let c=typeof t.text==="string"?t.text:"",u=ao(await io(e,c,n,s)).split(`
233
+ `)}})()})})}var Ll=3,Qh=2000,ci={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:wl,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function Ml(e,t,n,o,s,r,i){let a=ci.getWebSocket();if(!a)return;for(let c=0;c<Ll;c++){if(i?.aborted)return;try{let{wsUrl:l}=await ci.clientBoot(e,t);await Zh(a,e,l,n,o,s,r,i)}catch{}if(i?.aborted)return;if(c<Ll-1)await ci.sleep(Qh)}}function jl(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 rt={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:Ml};function pt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function li(e){return Array.isArray(e)?e:[]}function Wl(e){return Number(e)||0}function Ul(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function eg(e){let[t,n="000000"]=e.split("."),o=new Date(Number(t)*1000),s=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),a=String(o.getUTCHours()).padStart(2,"0"),c=String(o.getUTCMinutes()).padStart(2,"0"),l=String(o.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${s}-${r}-${i}T${a}:${c}:${l}.${u}`}async function tg(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:"0.000000",i=eg(r),a="?";if(typeof t.user==="string"){let y=t.user,f="@"+y;if(!n.has(f)){let[,g]=await Zs(e,y,s);n.set(f,g)}a=n.get(f)??y}else if(typeof t.username==="string")a=t.username;let c=typeof t.text==="string"?t.text:"",u=lo(await co(e,c,n,s)).split(`
234
234
  `),d=u[0]+(u.length>1?`
235
- `+u.slice(1).map((g)=>` ${g}`).join(`
236
- `):""),f=Bl(t)?"↳ ":"",h=o?`${o} @${a}`:`@${a}`;return`${i} ${f}${h}: ${d}`}async function Kh(e,t,n,o,s,r,i){let a=pt(await Xn(e,t,20,i?void 0:n||void 0,i,o.cookie)),c=ri(a.messages).map(pt).reverse(),l=pt(a.response_metadata),u=a.has_more===!0&&typeof l.next_cursor==="string"?l.next_cursor:void 0,d=[];if(o.watchThread&&!i){let m=pt(await cl(e,t,o.watchThread,50,o.cookie));d=ri(m.messages).map(pt).filter((D)=>(typeof D.ts==="string"?D.ts:"")!==o.watchThread)}let f=[...c.map((m)=>({m,fromHistory:!0})),...d.map((m)=>({m,fromHistory:!1}))].sort((m,D)=>Ll(typeof m.m.ts==="string"?m.m.ts:"")-Ll(typeof D.m.ts==="string"?D.m.ts:"")),h=[],g=n,p=!1;for(let{m,fromHistory:D}of f){let w=typeof m.ts==="string"?m.ts:"";if(!w||s.has(w))continue;let k=typeof m.subtype==="string"?m.subtype:"";if(k==="message_changed"||k==="message_deleted")continue;if(o.thread){if((typeof m.thread_ts==="string"?m.thread_ts:w)!==o.thread&&w!==o.thread)continue}if(o.watchThread&&Bl(m)){if((typeof m.thread_ts==="string"?m.thread_ts:"")!==o.watchThread)continue}if(o.me&&o.myUserId){if(!(typeof m.text==="string"?m.text:"").includes(`<@${o.myUserId}>`))continue}if(s.add(w),s.size>1000){let C=s.values().next().value;if(C!==void 0)s.delete(C)}if(h.push(await Jh(e,m,r,void 0,o.cookie)),D)g=w;let x=typeof m.user==="string"?m.user:"";if(!o.myUserId||x!==o.myUserId)p=!0}return{newCursor:g,lines:h,hasMore:a.has_more===!0,nextPageCursor:u,emittedOther:p}}function qh(e){if(e.includes("slack.com")){let t=Wr(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 Nl(e,t,n={},o){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
235
+ `+u.slice(1).map((y)=>` ${y}`).join(`
236
+ `):""),p=Ul(t)?"↳ ":"",h=o?`${o} @${a}`:`@${a}`;return`${i} ${p}${h}: ${d}`}async function ng(e,t,n,o,s,r,i){let a=pt(await Vn(e,t,20,i?void 0:n||void 0,i,o.cookie)),c=li(a.messages).map(pt).reverse(),l=pt(a.response_metadata),u=a.has_more===!0&&typeof l.next_cursor==="string"?l.next_cursor:void 0,d=[];if(o.watchThread&&!i){let g=pt(await pl(e,t,o.watchThread,50,o.cookie));d=li(g.messages).map(pt).filter((w)=>(typeof w.ts==="string"?w.ts:"")!==o.watchThread)}let p=[...c.map((g)=>({m:g,fromHistory:!0})),...d.map((g)=>({m:g,fromHistory:!1}))].sort((g,w)=>Wl(typeof g.m.ts==="string"?g.m.ts:"")-Wl(typeof w.m.ts==="string"?w.m.ts:"")),h=[],y=n,f=!1;for(let{m:g,fromHistory:w}of p){let D=typeof g.ts==="string"?g.ts:"";if(!D||s.has(D))continue;let k=typeof g.subtype==="string"?g.subtype:"";if(k==="message_changed"||k==="message_deleted")continue;if(o.thread){if((typeof g.thread_ts==="string"?g.thread_ts:D)!==o.thread&&D!==o.thread)continue}if(o.watchThread&&Ul(g)){if((typeof g.thread_ts==="string"?g.thread_ts:"")!==o.watchThread)continue}if(o.me&&o.myUserId){if(!(typeof g.text==="string"?g.text:"").includes(`<@${o.myUserId}>`))continue}if(s.add(D),s.size>1000){let C=s.values().next().value;if(C!==void 0)s.delete(C)}if(h.push(await tg(e,g,r,void 0,o.cookie)),w)y=D;let S=typeof g.user==="string"?g.user:"";if(!o.myUserId||S!==o.myUserId)f=!0}return{newCursor:y,lines:h,hasMore:a.has_more===!0,nextPageCursor:u,emittedOther:f}}function sg(e){if(e.includes("slack.com")){let t=qr(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 Jl(e,t,n={},o){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
237
237
  Cross-channel mention streaming is not yet supported.
238
- Use: slack tail "#channel" --me`),process.exit(1);if(!t)console.error("Usage: slack tail <#channel|@user>\n Run `slack tail --help` for details."),process.exit(1);let s=await Ys(e,t,n.cookie),r=n.interval??60000,i=n.timeout?ct.now()+vl(n.timeout)*1000:1/0,a=new Map,c=new Set;try{let p=pt(await fl(e,s,n.cookie));if(pt(p.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(p){let m=p instanceof Error?p.message:String(p);if(m.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(m.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(m.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: ${m}`)}let l="";if(n.since){let p=vl(n.since);l=(ct.now()/1000-p).toFixed(6)}else{let p=pt(await Xn(e,s,1,void 0,void 0,n.cookie)),m=ri(p.messages).map(pt);if(m.length>0&&typeof m[0]?.ts==="string")l=m[0].ts,c.add(l);else l=(ct.now()/1000).toFixed(6)}let u;if(n.me||n.exitOnMessage)u=(await En(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=qh(n.watchThread)}catch(p){console.error(p instanceof Error?p.message:String(p)),process.exit(1)}let f={...n.thread!==void 0?{thread:n.thread}:{},...d!==void 0?{watchThread:d}:{},...n.me!==void 0?{me:n.me}:{},...u!==void 0?{myUserId:u}:{},...n.cookie!==void 0?{cookie:n.cookie}:{}};if(e.startsWith("xoxc-")&&n.cookie!==void 0&&n.noRtm!==!0&&n.since===void 0&&n.timeout===void 0&&n.exitOnMessage!==!0){if(await ct.tailRTM(e,n.cookie,s,f,c,a,o),o?.aborted)return;console.error("RTM unavailable — switching to polling.")}let h=!0,g=ct.now();while(!o?.aborted){if(ct.now()>=i)return;let p=!1;try{let w=ct.now()-g,k=r>0&&w>r*5,x,C=!0;do{let{newCursor:I,lines:A,nextPageCursor:M,emittedOther:X}=await Kh(e,s,l,f,c,a,x);if(l=I,h&&C&&n.since&&A.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
239
- `);C=!1;for(let re of A)process.stdout.write(re+`
240
- `);if(X)p=!0;x=k?M:void 0}while(x);h=!1}catch(D){if(D instanceof it){console.error(`Warning: Slack rate limit hit — backing off for ${D.retryAfter}s`),await ct.sleep(D.retryAfter*1000);continue}throw D}if(n.exitOnMessage&&p)return;g=ct.now();let m=i-ct.now();if(m<=0)return;await ct.sleep(Math.min(r,m))}}import{spawn as Hh}from"node:child_process";import{constants as Ml}from"node:os";var zh=["processing","active","suspended","closed"];function jl(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?qs():process.env[e];if(!t?.startsWith("xoxb-"))throw Error("Agent commands require a bot token (xoxb). Set SLACK_BOT_TOKEN or --bot-token-env NAME; user tokens are refused.");return t}function Wl(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function Ul(e,t,n){let{ref:o,threadTs:s}=n(t);if(!s||!/^\d{10}\.\d{6}$/.test(s))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Ys(e,o),thread_ts:s}}function ii(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function Gh(e,t,n,o){let s,r,i,a,c,l=!1,u=!1,d=1,f=(p)=>{if(r)return;if(r=p,l=!0,s&&s.exitCode===null&&s.signalCode===null)s.kill(p),i=setTimeout(()=>s?.kill("SIGKILL"),5000)},h=()=>f("SIGINT"),g=()=>f("SIGTERM");process.on("SIGINT",h),process.on("SIGTERM",g);try{if(u=!0,await Yn(e,t,"processing"),!l&&o.title!==void 0)await jr(e,t,o.title);if(!l){s=Hh(n[0],n.slice(1),{stdio:"inherit"});let p=new Promise((m)=>{s.once("error",()=>{console.error("agent: could not start command"),m(127)}),s.once("exit",(D,w)=>{m(D??(w?128+Ml.signals[w]:1))})});a=setInterval(()=>{if(l||c)return;c=Yn(e,t,"processing").then(()=>{}).catch((m)=>ii("heartbeat failed; retrying on next tick",m)).finally(()=>{c=void 0})},o.every*1000),d=await p}}catch(p){ii("could not start agent session",p)}finally{if(l=!0,clearInterval(a),clearTimeout(i),await c,u)try{await Yn(e,t,o.close?"closed":"active")}catch(p){if(ii("final status clear failed",p),d===0)d=1}process.removeListener("SIGINT",h),process.removeListener("SIGTERM",g)}return r?128+Ml.signals[r]:d}function Jl(e,t){let n=(o)=>o.positional("target",{type:"string",demandOption:!0,describe:"Thread root: raw channel ID:ts (avoids listing), #channel:ts, or permalink"}).option("title",{type:"string",describe:"Rename the session (1–200 characters)"}).option("bot-token-env",{type:"string",describe:"Environment variable holding an agent-enabled app's xoxb token (default SLACK_BOT_TOKEN); requires chat:write and channel membership"});return e.command("status <target> <status>","Set a bot agent session's status",(o)=>n(o).positional("status",{type:"string",choices:zh,demandOption:!0}),async(o)=>{Wl(o.title);let s=jl(o["bot-token-env"]),r=await Ul(s,o.target,t);if(await Yn(s,r,o.status),o.title!==void 0)await jr(s,r,o.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(o)=>n(o).parserConfiguration({"populate--":!0}).option("every",{type:"number",default:300,describe:"Heartbeat seconds (>0 and <3600); processing expires after one hour"}).option("close",{type:"boolean",default:!1,describe:"Finish with closed instead of active (also on failure or interrupt)"}),async(o)=>{if(Wl(o.title),!Number.isFinite(o.every)||o.every<=0||o.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let s=process.argv.indexOf("--"),r=s<0?[]:process.argv.slice(s+1);if(!r[0])throw Error("agent run requires -- <command...>");let i=jl(o["bot-token-env"]),a=await Ul(i,o.target,t);process.exitCode=await Gh(i,a,r,{every:o.every,close:o.close,...o.title!==void 0?{title:o.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}var $e=[{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"}],ht=$e.length,At="question";var Tt=["ja","en"];function li(e,t=process.env){for(let[r,i]of[[e.flag,"flag"],[t.SLACK_TERM_LANG,"env"]]){if(r===void 0||r.trim()==="")continue;let a=r.trim().toLowerCase();return Tt.includes(a)?{lang:a,source:i}:null}let n=(e.readerLocales??[]).map(Kl);if(n.length&&n[0]&&n.every((r)=>r===n[0]))return{lang:n[0],source:"readers"};let o=ui((e.content??[]).join(`
241
- `));if(o)return{lang:o,source:"content"};let s=Kl(t.LC_ALL||t.LC_MESSAGES||t.LANG);if(s)return{lang:s,source:"system"};return{lang:"ja",source:"default"}}function Kl(e){let t=(e??"").toLowerCase();return Tt.find((n)=>t===n||/^[_.\-@]/.test(t.slice(n.length))&&t.startsWith(n))??null}function ui(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 Ye={ja:{instructionReactionThread:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_",instructionReactionHere:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_",instructionTextThread:"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_",instructionTextHere:"_このメッセージに返信してください。本文がそのまま回答になります。_",overflowNote:"_11 番目以降はリアクションがないので、返信で答えてください。_",otherThread:`${":question: "}その他 — スレッドで返信してください`,otherHere:`${":question: "}その他 — このメッセージに返信してください`,invalidPrefix:"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ",answeredVia:(e,t)=>`_${e}で回答済み${t?` (${t})`:""}_`,howReaction:(e)=>`リアクション ${e}`,howReply:"返信",howReplyN:(e)=>`返信 (${e})`,voidStamp:(e)=>`_無効${e?`: ${e}`:""} — この質問への回答は受け付けません。_`,supersededBy:(e)=>`↪ 新しい質問: ${e}`},en:{instructionReactionThread:"_Press one of the reactions below to answer. If none fits, reply in this message's *thread* (ordinary channel posts are not picked up as answers)._",instructionReactionHere:"_Press one of the reactions below to answer. If none fits, reply to this message._",instructionTextThread:"_Reply in this message's *thread* — your reply is the answer (ordinary channel posts are not picked up as answers)._",instructionTextHere:"_Reply to this message — your reply is the answer._",overflowNote:"_Choices 11 and up have no reaction — answer them with a reply._",otherThread:`${":question: "}Other — reply in the thread`,otherHere:`${":question: "}Other — reply to this message`,invalidPrefix:"_:warning: Several choices are selected, so this is not counted as an answer — keep only one: ",answeredVia:(e,t)=>`_Answered by ${e}${t?` (${t})`:""}_`,howReaction:(e)=>`reaction ${e}`,howReply:"reply",howReplyN:(e)=>`reply (${e})`,voidStamp:(e)=>`_Void${e?`: ${e}`:""} — this question no longer takes answers._`,supersededBy:(e)=>`↪ Replaced by: ${e}`}};function Yh(e){return e!==void 0&&(e.startsWith(":question: ")||e.startsWith("❓ "))}var co="_";function Hl(e){if(e===void 0||!e.endsWith(co))return null;return Tt.find((t)=>e.startsWith(Ye[t].invalidPrefix))??null}function lo(e){let t=e.split(`
242
- `),n=t[t.length-2];if(!Hl(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function uo(e,t,n="ja"){let o=e.split(`
243
- `);if(o.length<2)return e;if(lo(e).length)o.splice(o.length-2,1);if(t.length)o.splice(o.length-1,0,`${Ye[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${co}`);let s=o.join(`
244
- `);return s===e?e:s}function ql(e){return Hl(e)!==null}var di="white_check_mark",rs=`:${di}: `,fi="no_entry_sign",ci=`:${fi}: `,Xh=/^【[^】]*(?:作废|作廢|superseded|void)[^】]*】/i;function pi(e){return`:${$e[e].name}:`}function zl(e,t){let n=$e[t];for(let o of[pi(t),n.glyph]){if(e.startsWith(`${o} `))return e.slice(o.length+1);if(e===o)return""}return null}function Vh(e){return $e.some((t,n)=>zl(e,n)!==null)}function Le(e){return e.replace(/\s*\n\s*/g," ")}function hi(e,t,n,o,s,r="ja"){let i=Ye[r],a=[`:question: *${e}*`];if(t)a.push("",t);if(n.length){if(a.push(""),a.push(...n.map((c,l)=>`${pi(l)} ${Le(c)}`)),a.push(s?i.otherThread:i.otherHere),o.length)a.push(""),a.push(...o.map((c,l)=>`(${l+11}) ${Le(c)}`)),a.push(i.overflowNote);a.push(""),a.push(s?i.instructionReactionThread:i.instructionReactionHere)}else a.push(""),a.push(s?i.instructionTextThread:i.instructionTextHere);return a.join(`
245
- `)}function Gl(e,t,n,o="ja",s){let r=t.answer.split(`
238
+ Use: slack tail "#channel" --me`),process.exit(1);if(!t)console.error("Usage: slack tail <#channel|@user>\n Run `slack tail --help` for details."),process.exit(1);let s=await Vs(e,t,n.cookie),r=n.interval??60000,i=n.timeout?rt.now()+jl(n.timeout)*1000:1/0,a=new Map,c=new Set;try{let f=pt(await yl(e,s,n.cookie));if(pt(f.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(f){let g=f instanceof Error?f.message:String(f);if(g.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(g.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(g.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: ${g}`)}let l="";if(n.since){let f=jl(n.since);l=(rt.now()/1000-f).toFixed(6)}else{let f=pt(await Vn(e,s,1,void 0,void 0,n.cookie)),g=li(f.messages).map(pt);if(g.length>0&&typeof g[0]?.ts==="string")l=g[0].ts,c.add(l);else l=(rt.now()/1000).toFixed(6)}let u;if(n.me||n.exitOnMessage)u=(await Sn(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=sg(n.watchThread)}catch(f){console.error(f instanceof Error?f.message:String(f)),process.exit(1)}let p={...n.thread!==void 0?{thread:n.thread}:{},...d!==void 0?{watchThread:d}:{},...n.me!==void 0?{me:n.me}:{},...u!==void 0?{myUserId:u}:{},...n.cookie!==void 0?{cookie:n.cookie}:{}};if(e.startsWith("xoxc-")&&n.cookie!==void 0&&n.noRtm!==!0&&n.since===void 0&&n.timeout===void 0&&n.exitOnMessage!==!0){if(await rt.tailRTM(e,n.cookie,s,p,c,a,o),o?.aborted)return;console.error("RTM unavailable — switching to polling.")}let h=!0,y=rt.now();while(!o?.aborted){if(rt.now()>=i)return;let f=!1;try{let D=rt.now()-y,k=r>0&&D>r*5,S,C=!0;do{let{newCursor:F,lines:A,nextPageCursor:O,emittedOther:B}=await ng(e,s,l,p,c,a,S);if(l=F,h&&C&&n.since&&A.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
239
+ `);C=!1;for(let U of A)process.stdout.write(U+`
240
+ `);if(B)f=!0;S=k?O:void 0}while(S);h=!1}catch(w){if(w instanceof st){console.error(`Warning: Slack rate limit hit — backing off for ${w.retryAfter}s`),await rt.sleep(w.retryAfter*1000);continue}throw w}if(n.exitOnMessage&&f)return;y=rt.now();let g=i-rt.now();if(g<=0)return;await rt.sleep(Math.min(r,g))}}import{spawn as og}from"node:child_process";import{constants as Kl}from"node:os";var rg=["processing","active","suspended","closed"];function ql(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?zs():process.env[e];if(!t?.startsWith("xoxb-"))throw Error("Agent commands require a bot token (xoxb). Set SLACK_BOT_TOKEN or --bot-token-env NAME; user tokens are refused.");return t}function Hl(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function zl(e,t,n){let{ref:o,threadTs:s}=n(t);if(!s||!/^\d{10}\.\d{6}$/.test(s))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Vs(e,o),thread_ts:s}}function ui(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function ig(e,t,n,o){let s,r,i,a,c,l=!1,u=!1,d=1,p=(f)=>{if(r)return;if(r=f,l=!0,s&&s.exitCode===null&&s.signalCode===null)s.kill(f),i=setTimeout(()=>s?.kill("SIGKILL"),5000)},h=()=>p("SIGINT"),y=()=>p("SIGTERM");process.on("SIGINT",h),process.on("SIGTERM",y);try{if(u=!0,await Xn(e,t,"processing"),!l&&o.title!==void 0)await Kr(e,t,o.title);if(!l){s=og(n[0],n.slice(1),{stdio:"inherit"});let f=new Promise((g)=>{s.once("error",()=>{console.error("agent: could not start command"),g(127)}),s.once("exit",(w,D)=>{g(w??(D?128+Kl.signals[D]:1))})});a=setInterval(()=>{if(l||c)return;c=Xn(e,t,"processing").then(()=>{}).catch((g)=>ui("heartbeat failed; retrying on next tick",g)).finally(()=>{c=void 0})},o.every*1000),d=await f}}catch(f){ui("could not start agent session",f)}finally{if(l=!0,clearInterval(a),clearTimeout(i),await c,u)try{await Xn(e,t,o.close?"closed":"active")}catch(f){if(ui("final status clear failed",f),d===0)d=1}process.removeListener("SIGINT",h),process.removeListener("SIGTERM",y)}return r?128+Kl.signals[r]:d}function Gl(e,t){let n=(o)=>o.positional("target",{type:"string",demandOption:!0,describe:"Thread root: raw channel ID:ts (avoids listing), #channel:ts, or permalink"}).option("title",{type:"string",describe:"Rename the session (1–200 characters)"}).option("bot-token-env",{type:"string",describe:"Environment variable holding an agent-enabled app's xoxb token (default SLACK_BOT_TOKEN); requires chat:write and channel membership"});return e.command("status <target> <status>","Set a bot agent session's status",(o)=>n(o).positional("status",{type:"string",choices:rg,demandOption:!0}),async(o)=>{Hl(o.title);let s=ql(o["bot-token-env"]),r=await zl(s,o.target,t);if(await Xn(s,r,o.status),o.title!==void 0)await Kr(s,r,o.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(o)=>n(o).parserConfiguration({"populate--":!0}).option("every",{type:"number",default:300,describe:"Heartbeat seconds (>0 and <3600); processing expires after one hour"}).option("close",{type:"boolean",default:!1,describe:"Finish with closed instead of active (also on failure or interrupt)"}),async(o)=>{if(Hl(o.title),!Number.isFinite(o.every)||o.every<=0||o.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let s=process.argv.indexOf("--"),r=s<0?[]:process.argv.slice(s+1);if(!r[0])throw Error("agent run requires -- <command...>");let i=ql(o["bot-token-env"]),a=await zl(i,o.target,t);process.exitCode=await ig(i,a,r,{every:o.every,close:o.close,...o.title!==void 0?{title:o.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}var Ee=[{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"}],ht=Ee.length,At="question";var Tt=["ja","en"];function pi(e,t=process.env){for(let[r,i]of[[e.flag,"flag"],[t.SLACK_TERM_LANG,"env"]]){if(r===void 0||r.trim()==="")continue;let a=r.trim().toLowerCase();return Tt.includes(a)?{lang:a,source:i}:null}let n=(e.readerLocales??[]).map(Yl);if(n.length&&n[0]&&n.every((r)=>r===n[0]))return{lang:n[0],source:"readers"};let o=hi((e.content??[]).join(`
241
+ `));if(o)return{lang:o,source:"content"};let s=Yl(t.LC_ALL||t.LC_MESSAGES||t.LANG);if(s)return{lang:s,source:"system"};return{lang:"ja",source:"default"}}function Yl(e){let t=(e??"").toLowerCase();return Tt.find((n)=>t===n||/^[_.\-@]/.test(t.slice(n.length))&&t.startsWith(n))??null}function hi(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 qe={ja:{instructionReactionThread:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_",instructionReactionHere:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_",instructionTextThread:"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_",instructionTextHere:"_このメッセージに返信してください。本文がそのまま回答になります。_",overflowNote:"_11 番目以降はリアクションがないので、返信で答えてください。_",otherThread:`${":question: "}その他 — スレッドで返信してください`,otherHere:`${":question: "}その他 — このメッセージに返信してください`,invalidPrefix:"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ",answeredVia:(e,t)=>`_${e}で回答済み${t?` (${t})`:""}_`,howReaction:(e)=>`リアクション ${e}`,howReply:"返信",howReplyN:(e)=>`返信 (${e})`,voidStamp:(e)=>`_無効${e?`: ${e}`:""} — この質問への回答は受け付けません。_`,supersededBy:(e)=>`↪ 新しい質問: ${e}`},en:{instructionReactionThread:"_Press one of the reactions below to answer. If none fits, reply in this message's *thread* (ordinary channel posts are not picked up as answers)._",instructionReactionHere:"_Press one of the reactions below to answer. If none fits, reply to this message._",instructionTextThread:"_Reply in this message's *thread* — your reply is the answer (ordinary channel posts are not picked up as answers)._",instructionTextHere:"_Reply to this message — your reply is the answer._",overflowNote:"_Choices 11 and up have no reaction — answer them with a reply._",otherThread:`${":question: "}Other — reply in the thread`,otherHere:`${":question: "}Other — reply to this message`,invalidPrefix:"_:warning: Several choices are selected, so this is not counted as an answer — keep only one: ",answeredVia:(e,t)=>`_Answered by ${e}${t?` (${t})`:""}_`,howReaction:(e)=>`reaction ${e}`,howReply:"reply",howReplyN:(e)=>`reply (${e})`,voidStamp:(e)=>`_Void${e?`: ${e}`:""} — this question no longer takes answers._`,supersededBy:(e)=>`↪ Replaced by: ${e}`}};function ag(e){return e!==void 0&&(e.startsWith(":question: ")||e.startsWith("❓ "))}var uo="_";function Vl(e){if(e===void 0||!e.endsWith(uo))return null;return Tt.find((t)=>e.startsWith(qe[t].invalidPrefix))??null}function fo(e){let t=e.split(`
242
+ `),n=t[t.length-2];if(!Vl(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function po(e,t,n="ja"){let o=e.split(`
243
+ `);if(o.length<2)return e;if(fo(e).length)o.splice(o.length-2,1);if(t.length)o.splice(o.length-1,0,`${qe[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${uo}`);let s=o.join(`
244
+ `);return s===e?e:s}function Xl(e){return Vl(e)!==null}var gi="white_check_mark",is=`:${gi}: `,mi="no_entry_sign",fi=`:${mi}: `,cg=/^【[^】]*(?:作废|作廢|superseded|void)[^】]*】/i;function yi(e){return`:${Ee[e].name}:`}function Zl(e,t){let n=Ee[t];for(let o of[yi(t),n.glyph]){if(e.startsWith(`${o} `))return e.slice(o.length+1);if(e===o)return""}return null}function lg(e){return Ee.some((t,n)=>Zl(e,n)!==null)}function _e(e){return e.replace(/\s*\n\s*/g," ")}function wi(e,t,n,o,s,r="ja"){let i=qe[r],a=[`:question: *${e}*`];if(t)a.push("",t);if(n.length){if(a.push(""),a.push(...n.map((c,l)=>`${yi(l)} ${_e(c)}`)),a.push(s?i.otherThread:i.otherHere),o.length)a.push(""),a.push(...o.map((c,l)=>`(${l+11}) ${_e(c)}`)),a.push(i.overflowNote);a.push(""),a.push(s?i.instructionReactionThread:i.instructionReactionHere)}else a.push(""),a.push(s?i.instructionTextThread:i.instructionTextHere);return a.join(`
245
+ `)}function Ql(e,t,n,o="ja",s){let r=t.answer.split(`
246
246
  `).map((a)=>`> ${a}`).join(`
247
- `),i=`${rs}*${e}*
248
- ${Ye[o].answeredVia(t.how,n)}
247
+ `),i=`${is}*${e}*
248
+ ${qe[o].answeredVia(t.how,n)}
249
249
 
250
250
  ${r}`;if(s?.body)i+=`
251
251
 
252
252
  ${s.body}`;if(s?.chosenLine)i+=`
253
253
 
254
- ${s.chosenLine}`;return i}function Yl(e,t){let n=gt(e);if(n.kind!=="open")return;let o={};if(n.body)o.body=n.body;if(t!==void 0&&t>=1){if(t<=n.reactable.length)o.chosenLine=`${pi(t-1)} ${Le(n.reactable[t-1])}`;else if(t-ht<=n.overflow.length&&t>ht)o.chosenLine=`(${t}) ${Le(n.overflow[t-ht-1])}`}return o.body||o.chosenLine?o:void 0}function Xl(e,t,n="ja",o,s){let r=Ye[n],i=`${ci}*${e}*
255
- ${r.voidStamp(Le(t.trim()))}`;if(s)i+=`
254
+ ${s.chosenLine}`;return i}function eu(e,t){let n=gt(e);if(n.kind!=="open")return;let o={};if(n.body)o.body=n.body;if(t!==void 0&&t>=1){if(t<=n.reactable.length)o.chosenLine=`${yi(t-1)} ${_e(n.reactable[t-1])}`;else if(t-ht<=n.overflow.length&&t>ht)o.chosenLine=`(${t}) ${_e(n.overflow[t-ht-1])}`}return o.body||o.chosenLine?o:void 0}function tu(e,t,n="ja",o,s){let r=qe[n],i=`${fi}*${e}*
255
+ ${r.voidStamp(_e(t.trim()))}`;if(s)i+=`
256
256
  ${r.supersededBy(s)}`;if(o)i+=`
257
257
 
258
- ${o}`;return i}function Vl(e){if(!e.startsWith(":question: "))return null;let t=e.slice(11),n=t.match(/^\*([\s\S]+?)\*(?=\s|$)/);if(!n)return null;let o=t.slice(n[0].length),s=!1;for(let r of Tt){let i=Ye[r];for(let c of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere])if(o.includes(c))s=!0;for(let c of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere,i.overflowNote,i.otherThread,i.otherHere])o=o.split(c).join(" ");let a=o.indexOf(i.invalidPrefix);if(a>=0){let c=o.indexOf(co,a+i.invalidPrefix.length);o=o.slice(0,a)+" "+(c>=0?o.slice(c+co.length):"")}}if(!s)return null;return{question:n[1],body:o.replace(/[ \t]{3,}/g," ").trim()}}function Zl(e){if(!e[0]?.startsWith(rs))return-1;let t=(n)=>!!n&&(n.startsWith("> ")||n.startsWith("&gt; "));for(let n=1;n+2<e.length;n++){let o=e[n];if(o.length>1&&o.startsWith("_")&&o.endsWith("_")&&e[n+1]===""&&t(e[n+2]))return n}return-1}function Ql(e){let t=e.split(`
259
- `),n=Zl(t),s=((n>0?t[n]:t[1])??"").match(/^_(?:返信|Answered by reply)(?: \((\d+)\))?/);if(!s)return{byReply:!1};return s[1]?{byReply:!0,n:Number(s[1])}:{byReply:!0}}function os(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function fo(e){if(!e.trim())return"本文が空です (bot 投稿や添付のみのメッセージかもしれません)";let t=e.split(`
260
- `),n=t[t.length-1]??"";if(e.startsWith(rs))return"回答済みマーク付きですが、引用された回答本文が見つかりません";if(!/_$/.test(n))return"末尾が `ask` の案内文ではありません — このメッセージは `slack ask` で投稿されたものではないか、本文が編集されています";if(!t[0].startsWith(":question: ")&&!t[0].startsWith("*"))return"先頭が質問文 (太字) ではありません — 本文が編集されている可能性があります";return"選択肢の並びを読み取れません — 番号が 1 から連番になっていないか、本文が編集されています"}function gt(e){let t=e.split(`
261
- `),n=(m)=>e.startsWith(`${m}*`)&&t.some((D,w)=>w>0&&D.length>1&&D.startsWith("_")&&D.endsWith("_"));if(n(ci)){let m=t.findIndex((x,C)=>C>0&&x.startsWith("_")&&x.endsWith("_")),D=os(t.slice(0,m>0?m:1).join(`
262
- `).slice(ci.length).replace(/^\*/,"").replace(/\*$/,"")),w=m>0?t[m].replace(/^_|_$/g,""):"",k=m>0?t[m+1]?.match(/^↪ [^::]*[::] (.+)$/)?.[1]:void 0;return k?{kind:"void",question:D,reason:w,supersededBy:k}:{kind:"void",question:D,reason:w}}let o=t[0].match(Xh)?e.match(/:question: \*([^\n]*?)\*/):null;if(o)return{kind:"void",question:os(o[1]),reason:os(t[0])};if(n(rs)){let m=(C)=>C.startsWith("> ")?C.slice(2):C.startsWith("&gt; ")?C.slice(5):null,D=Zl(t),w;if(D>0){w=[];for(let C=D+2;C<t.length;C++){let I=m(t[C]);if(I===null)break;w.push(I)}}else w=t.map(m).filter((C)=>C!==null);let k=os(t.slice(0,D>0?D:1).join(`
263
- `).slice(rs.length).replace(/^\*/,"").replace(/\*$/,"")),x=w.map(os).join(`
264
- `);if(!x)return{kind:"other"};return{kind:"resolved",question:k,answer:x}}let s=t[t.length-1]??"",r,i,a=Tt.find((m)=>[Ye[m].instructionReactionThread,Ye[m].instructionReactionHere,Ye[m].instructionTextThread,Ye[m].instructionTextHere].includes(s));if(!a)return{kind:"other"};let c=Ye[a];r=s===c.instructionReactionThread||s===c.instructionTextThread,i=s===c.instructionReactionThread||s===c.instructionReactionHere;let l=t[0].startsWith(":question: ")?t[0].slice(11):t[0];if(t[0]=l,!t[0].startsWith("*"))return{kind:"other"};let u=0;while(u<t.length&&!(t[u].endsWith("*")&&(u>0||t[0].length>1)))u++;if(u>=t.length)return{kind:"other"};let d=t.slice(0,u+1).join(`
265
- `).replace(/^\*/,"").replace(/\*$/,""),f=[],h=[],g=t.length-1;if(ql(t[g-1]))g--;if(i){let m=t.length-2;if(ql(t[m]))m--;if(t[m]!=="")return{kind:"other"};if(m--,t[m]===c.overflowNote){m--;while(m>=0&&/^\(\d+\) /.test(t[m]))h.unshift(t[m].replace(/^\(\d+\) /,"")),m--;if(t[m]!=="")return{kind:"other"};m--}if(Yh(t[m]))m--;let D=[];while(m>=0){let w=t[m];if(!Vh(w))break;D.unshift(w),m--}if(!D.length||D.length>ht)return{kind:"other"};for(let w=0;w<D.length;w++){let k=zl(D[w],w);if(k===null)return{kind:"other"};f.push(k)}if(t[m]!=="")return{kind:"other"};if(m<u+1)return{kind:"other"};g=m;for(let w=0;w<h.length;w++)if(!t.includes(`(${w+11}) ${h[w]}`))return{kind:"other"}}let p=t.slice(u+1,g).join(`
266
- `).replace(/^\n+|\n+$/g,"");return{kind:"open",question:d,body:p,reactable:f,overflow:h,threadOnly:r,lang:a}}function ai(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function eu(e,t,n){let o=Array.from({length:n},(r,i)=>i===n-1?t:""),s=gi(e,o);return s.kind==="chosen"&&s.index===n}function gi(e,t){let n=ai(e);if(!n)return{kind:"none"};let o=t.map(ai),s=new Set;o.forEach((l,u)=>{if(l&&l===n)s.add(u+1)}),$e.forEach((l,u)=>{if(u<t.length&&e.trim()===l.glyph)s.add(u+1)});let r=0,i="",a=n.match(/^(\d{1,2})$/);if(a)r=Number(a[1]);else if(a=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(r=Number(a[1]),i=ai(a[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(r>=1&&r<=t.length&&(i===""||i===o[r-1]))s.add(r);let c=[...s].sort((l,u)=>l-u);if(!c.length)return{kind:"none"};if(c.length>1)return{kind:"ambiguous",indexes:c};return{kind:"chosen",index:c[0]}}var mi=[{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"}],Qb=mi.length;var Zh=["ja","en"];var tu={ja:{instructionReactionThread:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_",instructionReactionHere:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_",instructionTextThread:"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_",instructionTextHere:"_このメッセージに返信してください。本文がそのまま回答になります。_",overflowNote:"_11 番目以降はリアクションがないので、返信で答えてください。_",otherThread:`${":question: "}その他 — スレッドで返信してください`,otherHere:`${":question: "}その他 — このメッセージに返信してください`,invalidPrefix:"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ",answeredVia:(e,t)=>`_${e}で回答済み${t?` (${t})`:""}_`,howReaction:(e)=>`リアクション ${e}`,howReply:"返信",howReplyN:(e)=>`返信 (${e})`,voidStamp:(e)=>`_無効${e?`: ${e}`:""} — この質問への回答は受け付けません。_`,supersededBy:(e)=>`↪ 新しい質問: ${e}`},en:{instructionReactionThread:"_Press one of the reactions below to answer. If none fits, reply in this message's *thread* (ordinary channel posts are not picked up as answers)._",instructionReactionHere:"_Press one of the reactions below to answer. If none fits, reply to this message._",instructionTextThread:"_Reply in this message's *thread* — your reply is the answer (ordinary channel posts are not picked up as answers)._",instructionTextHere:"_Reply to this message — your reply is the answer._",overflowNote:"_Choices 11 and up have no reaction — answer them with a reply._",otherThread:`${":question: "}Other — reply in the thread`,otherHere:`${":question: "}Other — reply to this message`,invalidPrefix:"_:warning: Several choices are selected, so this is not counted as an answer — keep only one: ",answeredVia:(e,t)=>`_Answered by ${e}${t?` (${t})`:""}_`,howReaction:(e)=>`reaction ${e}`,howReply:"reply",howReplyN:(e)=>`reply (${e})`,voidStamp:(e)=>`_Void${e?`: ${e}`:""} — this question no longer takes answers._`,supersededBy:(e)=>`↪ Replaced by: ${e}`}};var nu="_";function su(e){if(e===void 0||!e.endsWith(nu))return null;return Zh.find((t)=>e.startsWith(tu[t].invalidPrefix))??null}function yi(e){let t=e.split(`
267
- `),n=t[t.length-2];if(!su(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function ou(e,t,n="ja"){let o=e.split(`
268
- `);if(o.length<2)return e;if(yi(e).length)o.splice(o.length-2,1);if(t.length)o.splice(o.length-1,0,`${tu[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${nu}`);let s=o.join(`
269
- `);return s===e?e:s}function ru(e){return su(e)!==null}var Qh="white_check_mark",e0=`:${Qh}: `,eg="no_entry_sign",t0=`:${eg}: `;var lt=mi,Cn=lt.length,as="ballot_box_with_ballot",Di=`:${as}: `,au="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",cu="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",po="_締切: ",ho="_",bi="bar_chart",wi=`:${bi}: `;function go(e){return`:${lt[e].name}:`}function iu(e,t){for(let n of[go(t),lt[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function tg(e){return lt.some((t,n)=>e.startsWith(`${go(n)} `)||e.startsWith(`${t.glyph} `))}function is(e){return e.replace(/\s*\n\s*/g," ")}function lu(e,t,n,o={}){let s=!!o.multi,r=o.deadline??"",i=o.invalid??[];if(!n.length||n.length>Cn)throw Error(`poll needs 1..${Cn} choices, got ${n.length}`);let a=[`${Di}*${e}*`];if(t)a.push("",t);if(a.push(""),a.push(...n.map((c,l)=>`${go(l)} ${is(c)}`)),a.push(""),r)a.push(`${po}${is(r)}${ho}`);return a.push(s?cu:au),ou(a.join(`
270
- `),s?[]:i)}function uu(e,t){let n=t.reduce((s,r)=>s+r.count,0),o=[`${wi}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return o.push(...t.map((s,r)=>`${go(r)} ×${s.count} ${is(s.choice)}`)),o.join(`
271
- `)}function cs(e){let t=e.split(`
272
- `);if(e.startsWith(wi)){let f=t[0].slice(wi.length).replace(/^\*/,"").replace(/\*$/,""),h=[];for(let g=0;g<lt.length;g++){let p=t.map((D)=>iu(D,g)).find((D)=>D!==null&&D.startsWith("×"));if(p===void 0)break;let m=/^×(\d+) (.*)$/.exec(p);if(!m)return{kind:"other"};h.push({choice:m[2],count:Number(m[1])})}if(!h.length)return{kind:"other"};return{kind:"closed",question:f,tallies:h}}let n=t[t.length-1]??"",o;if(n===au)o=!1;else if(n===cu)o=!0;else return{kind:"other"};if(t[0].startsWith(Di))t[0]=t[0].slice(Di.length);if(!t[0].startsWith("*"))return{kind:"other"};let s=0;while(s<t.length&&!(t[s].endsWith("*")&&(s>0||t[0].length>1)))s++;if(s>=t.length)return{kind:"other"};let r=t.slice(0,s+1).join(`
273
- `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,a=yi(e);if(ru(t[i]))i--;let c="",l=t[i];if(l!==void 0&&l.startsWith(po)&&l.endsWith(ho)&&l.length>po.length+ho.length)c=l.slice(po.length,-ho.length),i--;if(t[i]!=="")return{kind:"other"};i--;let u=[];while(i>=0){let f=t[i];if(!tg(f))break;u.unshift(f),i--}if(!u.length||u.length>Cn)return{kind:"other"};let d=[];for(let f=0;f<u.length;f++){let h=iu(u[f],f);if(h===null)return{kind:"other"};d.push(h)}if(t[i]!=="")return{kind:"other"};if(i<s+1)return{kind:"other"};return{kind:"open",question:r,choices:d,multi:o,deadline:c,invalid:a}}function du(e,t,n,o){let s=new Map(t.map((l)=>[l.name,l.users])),r=e.map((l,u)=>(s.get(lt[u].name)??[]).filter((d)=>!n.has(d))),i=[];if(!o){let l=new Map;for(let u of r)for(let d of u)l.set(d,(l.get(d)??0)+1);for(let[u,d]of l)if(d>1)i.push(u)}let a=new Set(i),c=r.map((l)=>l.filter((u)=>!a.has(u)));return{tallies:e.map((l,u)=>({choice:l,count:c[u].length})),voters:c,ambiguous:i}}function ng(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var fu={isTestEnv:()=>ng(),sleep:(e)=>fu.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function sg(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 mo(e,t,n,o=sg()){for(let s=0;s<e.length;s++){let r=!0;try{await t(e[s])}catch(i){r=!1,n(e[s],i)}if(r&&o>0&&s<e.length-1)await fu.sleep(o)}}var pu=["text","select","user","link","date","number","checkbox"];function gu(e){let t=e.split(":"),n=(t[0]??"").trim(),o=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!pu.includes(o))throw Error(`--col ${e}: unknown type "${o}" (expected one of ${pu.join(", ")})`);if(o==="select"){let s=(t.slice(2).join(":")||"").split(",").map((r)=>r.trim()).filter(Boolean);if(!s.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:o,choices:s}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:o}}var hu=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function mu(e){if(!e.length)throw Error("at least one --col is required (the first one is the primary text column)");if(e[0].type!=="text")throw Error(`the first --col is the primary column and must be text, got ${e[0].type}`);return e.map((t,n)=>{let o={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)o.is_primary_column=!0;if(t.type==="select")o.options={format:"single_select",choices:t.choices.map((s,r)=>({value:s,label:s,color:hu[r%hu.length]}))};if(t.type==="user")o.options={format:"single_entity"};return o})}function yu(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((o)=>{let s=o??{},i=((s.options??{}).choices??[]).map((a)=>{let c=a??{};return{value:String(c.value??""),label:String(c.label??c.value??"")}});return{id:String(s.id??""),key:String(s.key??""),name:String(s.name??""),type:String(s.type??""),choices:i}})}function ki(e,t){let n=e.find((o)=>o.name===t)??e.find((o)=>o.key===t)??e.find((o)=>o.id===t);if(!n)throw Error(`no column "${t}" in this list (columns: ${e.map((o)=>o.name||o.key).join(", ")})`);return n}function xi(e,t){switch(e.type){case"text":return{rich_text:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:t}]}]}]};case"select":{let n=e.choices.find((o)=>o.value===t||o.label===t);if(!n)throw Error(`"${t}" is not an option of ${e.name} (options: ${e.choices.map((o)=>o.label).join(", ")})`);return{select:[n.value]}}case"user":return{user:[t]};case"link":return{link:[{original_url:t,display_as_url:!0}]};case"date":return{date:[t]};case"number":{let n=Number(t);if(!Number.isFinite(n))throw Error(`${e.name}: "${t}" is not a number`);return{number:[n]}}case"checkbox":case"todo_completed":if(!["true","false"].includes(t))throw Error(`${e.name}: expected true or false, got "${t}"`);return{checkbox:t==="true"};default:throw Error(`writing a ${e.type} column (${e.name}) from the CLI is not supported`)}}function Ei(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 Du(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as bu}from"node:child_process";import{chmodSync as og,mkdirSync as rg}from"node:fs";import{homedir as ig,hostname as ag}from"node:os";import{basename as cg,dirname as lg,join as ug}from"node:path";function Ci(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var ku={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function dg(e){try{let n=(bu("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:cg(n[2].trim())}}catch{return}}function fg(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=dg(e);if(!n)return;if(ku[n.comm])return n;e=n.ppid}return}function wu(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function xu(e=process.env){let t={pid:process.pid,host:pg(),cwd:process.cwd()},n=e.SLACK_TERM_AGENT_CLI||void 0;if(!n&&e.AI_AGENT)n=e.AI_AGENT.split("_")[0]||void 0;if(!n&&e.CLAUDECODE==="1")n="claude-code";let o=wu(e.SLACK_TERM_AGENT_PID)??wu(e.CLAUDE_PID);if(!o||!n){let i=fg();if(i)o??=i.pid,n??=ku[i.comm]}if(n)t.cli=n;if(o)t.agentPid=o;let s=e.SLACK_TERM_AGENT_SESSION||e.CLAUDE_CODE_SESSION_ID;if(s)t.sessionId=s;let r=hg(t.cwd);if(r)t.gitBranch=r;return t}function pg(){try{return ag()}catch{return""}}function hg(e){try{let t=bu("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var gg="slack_term_sent";function Eu(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:gg,event_payload:n}}function _n(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return ug(process.env.HOME||ig(),".config","slack-cli","sent.sqlite")}function mg(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=Ln("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 yg=`
258
+ ${o}`;return i}function nu(e){if(!e.startsWith(":question: "))return null;let t=e.slice(11),n=t.match(/^\*([\s\S]+?)\*(?=\s|$)/);if(!n)return null;let o=t.slice(n[0].length),s=!1;for(let r of Tt){let i=qe[r];for(let c of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere])if(o.includes(c))s=!0;for(let c of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere,i.overflowNote,i.otherThread,i.otherHere])o=o.split(c).join(" ");let a=o.indexOf(i.invalidPrefix);if(a>=0){let c=o.indexOf(uo,a+i.invalidPrefix.length);o=o.slice(0,a)+" "+(c>=0?o.slice(c+uo.length):"")}}if(!s)return null;return{question:n[1],body:o.replace(/[ \t]{3,}/g," ").trim()}}function su(e){if(!e[0]?.startsWith(is))return-1;let t=(n)=>!!n&&(n.startsWith("> ")||n.startsWith("&gt; "));for(let n=1;n+2<e.length;n++){let o=e[n];if(o.length>1&&o.startsWith("_")&&o.endsWith("_")&&e[n+1]===""&&t(e[n+2]))return n}return-1}function ou(e){let t=e.split(`
259
+ `),n=su(t),s=((n>0?t[n]:t[1])??"").match(/^_(?:返信|Answered by reply)(?: \((\d+)\))?/);if(!s)return{byReply:!1};return s[1]?{byReply:!0,n:Number(s[1])}:{byReply:!0}}function rs(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function as(e){if(!e.trim())return"本文が空です (bot 投稿や添付のみのメッセージかもしれません)";let t=e.split(`
260
+ `),n=t[t.length-1]??"";if(e.startsWith(is))return"回答済みマーク付きですが、引用された回答本文が見つかりません";if(!/_$/.test(n))return"末尾が `ask` の案内文ではありません — このメッセージは `slack ask` で投稿されたものではないか、本文が編集されています";if(!t[0].startsWith(":question: ")&&!t[0].startsWith("*"))return"先頭が質問文 (太字) ではありません — 本文が編集されている可能性があります";return"選択肢の並びを読み取れません — 番号が 1 から連番になっていないか、本文が編集されています"}function gt(e){let t=e.split(`
261
+ `),n=(g)=>e.startsWith(`${g}*`)&&t.some((w,D)=>D>0&&w.length>1&&w.startsWith("_")&&w.endsWith("_"));if(n(fi)){let g=t.findIndex((S,C)=>C>0&&S.startsWith("_")&&S.endsWith("_")),w=rs(t.slice(0,g>0?g:1).join(`
262
+ `).slice(fi.length).replace(/^\*/,"").replace(/\*$/,"")),D=g>0?t[g].replace(/^_|_$/g,""):"",k=g>0?t[g+1]?.match(/^↪ [^::]*[::] (.+)$/)?.[1]:void 0;return k?{kind:"void",question:w,reason:D,supersededBy:k}:{kind:"void",question:w,reason:D}}let o=t[0].match(cg)?e.match(/:question: \*([^\n]*?)\*/):null;if(o)return{kind:"void",question:rs(o[1]),reason:rs(t[0])};if(n(is)){let g=(C)=>C.startsWith("> ")?C.slice(2):C.startsWith("&gt; ")?C.slice(5):null,w=su(t),D;if(w>0){D=[];for(let C=w+2;C<t.length;C++){let F=g(t[C]);if(F===null)break;D.push(F)}}else D=t.map(g).filter((C)=>C!==null);let k=rs(t.slice(0,w>0?w:1).join(`
263
+ `).slice(is.length).replace(/^\*/,"").replace(/\*$/,"")),S=D.map(rs).join(`
264
+ `);if(!S)return{kind:"other"};return{kind:"resolved",question:k,answer:S}}let s=t[t.length-1]??"",r,i,a=Tt.find((g)=>[qe[g].instructionReactionThread,qe[g].instructionReactionHere,qe[g].instructionTextThread,qe[g].instructionTextHere].includes(s));if(!a)return{kind:"other"};let c=qe[a];r=s===c.instructionReactionThread||s===c.instructionTextThread,i=s===c.instructionReactionThread||s===c.instructionReactionHere;let l=t[0].startsWith(":question: ")?t[0].slice(11):t[0];if(t[0]=l,!t[0].startsWith("*"))return{kind:"other"};let u=0;while(u<t.length&&!(t[u].endsWith("*")&&(u>0||t[0].length>1)))u++;if(u>=t.length)return{kind:"other"};let d=t.slice(0,u+1).join(`
265
+ `).replace(/^\*/,"").replace(/\*$/,""),p=[],h=[],y=t.length-1;if(Xl(t[y-1]))y--;if(i){let g=t.length-2;if(Xl(t[g]))g--;if(t[g]!=="")return{kind:"other"};if(g--,t[g]===c.overflowNote){g--;while(g>=0&&/^\(\d+\) /.test(t[g]))h.unshift(t[g].replace(/^\(\d+\) /,"")),g--;if(t[g]!=="")return{kind:"other"};g--}if(ag(t[g]))g--;let w=[];while(g>=0){let D=t[g];if(!lg(D))break;w.unshift(D),g--}if(!w.length||w.length>ht)return{kind:"other"};for(let D=0;D<w.length;D++){let k=Zl(w[D],D);if(k===null)return{kind:"other"};p.push(k)}if(t[g]!=="")return{kind:"other"};if(g<u+1)return{kind:"other"};y=g;for(let D=0;D<h.length;D++)if(!t.includes(`(${D+11}) ${h[D]}`))return{kind:"other"}}let f=t.slice(u+1,y).join(`
266
+ `).replace(/^\n+|\n+$/g,"");return{kind:"open",question:d,body:f,reactable:p,overflow:h,threadOnly:r,lang:a}}function di(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function ru(e,t,n){let o=Array.from({length:n},(r,i)=>i===n-1?t:""),s=Di(e,o);return s.kind==="chosen"&&s.index===n}function Di(e,t){let n=di(e);if(!n)return{kind:"none"};let o=t.map(di),s=new Set;o.forEach((l,u)=>{if(l&&l===n)s.add(u+1)}),Ee.forEach((l,u)=>{if(u<t.length&&e.trim()===l.glyph)s.add(u+1)});let r=0,i="",a=n.match(/^(\d{1,2})$/);if(a)r=Number(a[1]);else if(a=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(r=Number(a[1]),i=di(a[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(r>=1&&r<=t.length&&(i===""||i===o[r-1]))s.add(r);let c=[...s].sort((l,u)=>l-u);if(!c.length)return{kind:"none"};if(c.length>1)return{kind:"ambiguous",indexes:c};return{kind:"chosen",index:c[0]}}var bi=[{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"}],f0=bi.length;var ug=["ja","en"];var iu={ja:{instructionReactionThread:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージの *スレッド* で返信してください (チャンネルへの通常投稿は回答として拾いません)。_",instructionReactionHere:"_下のリアクションを 1 つ押すと回答になります。当てはまるものがなければ、このメッセージに返信してください。_",instructionTextThread:"_このメッセージの *スレッド* で返信してください。本文がそのまま回答になります (チャンネルへの通常投稿は回答として拾いません)。_",instructionTextHere:"_このメッセージに返信してください。本文がそのまま回答になります。_",overflowNote:"_11 番目以降はリアクションがないので、返信で答えてください。_",otherThread:`${":question: "}その他 — スレッドで返信してください`,otherHere:`${":question: "}その他 — このメッセージに返信してください`,invalidPrefix:"_:warning: 同時に複数選ばれているため回答として数えていません — どれか 1 つだけ残してください: ",answeredVia:(e,t)=>`_${e}で回答済み${t?` (${t})`:""}_`,howReaction:(e)=>`リアクション ${e}`,howReply:"返信",howReplyN:(e)=>`返信 (${e})`,voidStamp:(e)=>`_無効${e?`: ${e}`:""} — この質問への回答は受け付けません。_`,supersededBy:(e)=>`↪ 新しい質問: ${e}`},en:{instructionReactionThread:"_Press one of the reactions below to answer. If none fits, reply in this message's *thread* (ordinary channel posts are not picked up as answers)._",instructionReactionHere:"_Press one of the reactions below to answer. If none fits, reply to this message._",instructionTextThread:"_Reply in this message's *thread* — your reply is the answer (ordinary channel posts are not picked up as answers)._",instructionTextHere:"_Reply to this message — your reply is the answer._",overflowNote:"_Choices 11 and up have no reaction — answer them with a reply._",otherThread:`${":question: "}Other — reply in the thread`,otherHere:`${":question: "}Other — reply to this message`,invalidPrefix:"_:warning: Several choices are selected, so this is not counted as an answer — keep only one: ",answeredVia:(e,t)=>`_Answered by ${e}${t?` (${t})`:""}_`,howReaction:(e)=>`reaction ${e}`,howReply:"reply",howReplyN:(e)=>`reply (${e})`,voidStamp:(e)=>`_Void${e?`: ${e}`:""} — this question no longer takes answers._`,supersededBy:(e)=>`↪ Replaced by: ${e}`}};var au="_";function cu(e){if(e===void 0||!e.endsWith(au))return null;return ug.find((t)=>e.startsWith(iu[t].invalidPrefix))??null}function ki(e){let t=e.split(`
267
+ `),n=t[t.length-2];if(!cu(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((o)=>o[1])}function lu(e,t,n="ja"){let o=e.split(`
268
+ `);if(o.length<2)return e;if(ki(e).length)o.splice(o.length-2,1);if(t.length)o.splice(o.length-1,0,`${iu[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${au}`);let s=o.join(`
269
+ `);return s===e?e:s}function uu(e){return cu(e)!==null}var dg="white_check_mark",p0=`:${dg}: `,fg="no_entry_sign",h0=`:${fg}: `;var it=bi,_n=it.length,ls="ballot_box_with_ballot",xi=`:${ls}: `,fu="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",pu="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",ho="_締切: ",go="_",Si="bar_chart",Ei=`:${Si}: `;function mo(e){return`:${it[e].name}:`}function du(e,t){for(let n of[mo(t),it[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function pg(e){return it.some((t,n)=>e.startsWith(`${mo(n)} `)||e.startsWith(`${t.glyph} `))}function cs(e){return e.replace(/\s*\n\s*/g," ")}function hu(e,t,n,o={}){let s=!!o.multi,r=o.deadline??"",i=o.invalid??[];if(!n.length||n.length>_n)throw Error(`poll needs 1..${_n} choices, got ${n.length}`);let a=[`${xi}*${e}*`];if(t)a.push("",t);if(a.push(""),a.push(...n.map((c,l)=>`${mo(l)} ${cs(c)}`)),a.push(""),r)a.push(`${ho}${cs(r)}${go}`);return a.push(s?pu:fu),lu(a.join(`
270
+ `),s?[]:i)}function gu(e,t){let n=t.reduce((s,r)=>s+r.count,0),o=[`${Ei}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return o.push(...t.map((s,r)=>`${mo(r)} ×${s.count} ${cs(s.choice)}`)),o.join(`
271
+ `)}function us(e){let t=e.split(`
272
+ `);if(e.startsWith(Ei)){let p=t[0].slice(Ei.length).replace(/^\*/,"").replace(/\*$/,""),h=[];for(let y=0;y<it.length;y++){let f=t.map((w)=>du(w,y)).find((w)=>w!==null&&w.startsWith("×"));if(f===void 0)break;let g=/^×(\d+) (.*)$/.exec(f);if(!g)return{kind:"other"};h.push({choice:g[2],count:Number(g[1])})}if(!h.length)return{kind:"other"};return{kind:"closed",question:p,tallies:h}}let n=t[t.length-1]??"",o;if(n===fu)o=!1;else if(n===pu)o=!0;else return{kind:"other"};if(t[0].startsWith(xi))t[0]=t[0].slice(xi.length);if(!t[0].startsWith("*"))return{kind:"other"};let s=0;while(s<t.length&&!(t[s].endsWith("*")&&(s>0||t[0].length>1)))s++;if(s>=t.length)return{kind:"other"};let r=t.slice(0,s+1).join(`
273
+ `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,a=ki(e);if(uu(t[i]))i--;let c="",l=t[i];if(l!==void 0&&l.startsWith(ho)&&l.endsWith(go)&&l.length>ho.length+go.length)c=l.slice(ho.length,-go.length),i--;if(t[i]!=="")return{kind:"other"};i--;let u=[];while(i>=0){let p=t[i];if(!pg(p))break;u.unshift(p),i--}if(!u.length||u.length>_n)return{kind:"other"};let d=[];for(let p=0;p<u.length;p++){let h=du(u[p],p);if(h===null)return{kind:"other"};d.push(h)}if(t[i]!=="")return{kind:"other"};if(i<s+1)return{kind:"other"};return{kind:"open",question:r,choices:d,multi:o,deadline:c,invalid:a}}function mu(e,t,n,o){let s=new Map(t.map((l)=>[l.name,l.users])),r=e.map((l,u)=>(s.get(it[u].name)??[]).filter((d)=>!n.has(d))),i=[];if(!o){let l=new Map;for(let u of r)for(let d of u)l.set(d,(l.get(d)??0)+1);for(let[u,d]of l)if(d>1)i.push(u)}let a=new Set(i),c=r.map((l)=>l.filter((u)=>!a.has(u)));return{tallies:e.map((l,u)=>({choice:l,count:c[u].length})),voters:c,ambiguous:i}}function hg(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var yu={isTestEnv:()=>hg(),sleep:(e)=>yu.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function gg(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 yo(e,t,n,o=gg()){for(let s=0;s<e.length;s++){let r=!0;try{await t(e[s])}catch(i){r=!1,n(e[s],i)}if(r&&o>0&&s<e.length-1)await yu.sleep(o)}}var wu=["text","select","user","link","date","number","checkbox"];function bu(e){let t=e.split(":"),n=(t[0]??"").trim(),o=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!wu.includes(o))throw Error(`--col ${e}: unknown type "${o}" (expected one of ${wu.join(", ")})`);if(o==="select"){let s=(t.slice(2).join(":")||"").split(",").map((r)=>r.trim()).filter(Boolean);if(!s.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:o,choices:s}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:o}}var Du=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function ku(e){if(!e.length)throw Error("at least one --col is required (the first one is the primary text column)");if(e[0].type!=="text")throw Error(`the first --col is the primary column and must be text, got ${e[0].type}`);return e.map((t,n)=>{let o={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)o.is_primary_column=!0;if(t.type==="select")o.options={format:"single_select",choices:t.choices.map((s,r)=>({value:s,label:s,color:Du[r%Du.length]}))};if(t.type==="user")o.options={format:"single_entity"};return o})}function xu(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((o)=>{let s=o??{},i=((s.options??{}).choices??[]).map((a)=>{let c=a??{};return{value:String(c.value??""),label:String(c.label??c.value??"")}});return{id:String(s.id??""),key:String(s.key??""),name:String(s.name??""),type:String(s.type??""),choices:i}})}function Ci(e,t){let n=e.find((o)=>o.name===t)??e.find((o)=>o.key===t)??e.find((o)=>o.id===t);if(!n)throw Error(`no column "${t}" in this list (columns: ${e.map((o)=>o.name||o.key).join(", ")})`);return n}function _i(e,t){switch(e.type){case"text":return{rich_text:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:t}]}]}]};case"select":{let n=e.choices.find((o)=>o.value===t||o.label===t);if(!n)throw Error(`"${t}" is not an option of ${e.name} (options: ${e.choices.map((o)=>o.label).join(", ")})`);return{select:[n.value]}}case"user":return{user:[t]};case"link":return{link:[{original_url:t,display_as_url:!0}]};case"date":return{date:[t]};case"number":{let n=Number(t);if(!Number.isFinite(n))throw Error(`${e.name}: "${t}" is not a number`);return{number:[n]}}case"checkbox":case"todo_completed":if(!["true","false"].includes(t))throw Error(`${e.name}: expected true or false, got "${t}"`);return{checkbox:t==="true"};default:throw Error(`writing a ${e.type} column (${e.name}) from the CLI is not supported`)}}function $i(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 Eu(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as Ai}from"node:child_process";import{chmodSync as mg,existsSync as Cu,mkdirSync as yg}from"node:fs";import{homedir as wg,hostname as Dg}from"node:os";import{basename as _u,dirname as bg,join as kg}from"node:path";function Do(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var wo={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function xg(e){try{let n=(Ai("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:_u(n[2].trim())}}catch{return}}function Eg(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=xg(e);if(!n)return;if(wo[n.comm])return n;e=n.ppid}return}function Su(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function $u(e=process.env){let t={pid:process.pid,host:Sg(),cwd:process.cwd()},n=e.SLACK_TERM_AGENT_CLI||void 0;if(!n&&e.AI_AGENT)n=e.AI_AGENT.split("_")[0]||void 0;if(!n&&e.CLAUDECODE==="1")n="claude-code";let o=Su(e.SLACK_TERM_AGENT_PID)??Su(e.CLAUDE_PID);if(!o||!n){let i=Eg();if(i)o??=i.pid,n??=wo[i.comm]}if(n)t.cli=n;if(o)t.agentPid=o;let s=e.SLACK_TERM_AGENT_SESSION||e.CLAUDE_CODE_SESSION_ID;if(s)t.sessionId=s;let r=Cg(t.cwd);if(r)t.gitBranch=r;return t}function Sg(){try{return Dg()}catch{return""}}function Cg(e){try{let t=Ai("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var _g="slack_term_sent";function Fu(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:_g,event_payload:n}}function lt(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return kg(process.env.HOME||wg(),".config","slack-cli","sent.sqlite")}function $g(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=Ln("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 Fg=`
274
274
  CREATE TABLE IF NOT EXISTS sent (
275
275
  id INTEGER PRIMARY KEY AUTOINCREMENT,
276
276
  kind TEXT NOT NULL,
@@ -293,160 +293,167 @@ CREATE TABLE IF NOT EXISTS sent (
293
293
  collected_at INTEGER,
294
294
  answer TEXT,
295
295
  answer_exit INTEGER,
296
- delivered_at INTEGER
296
+ delivered_at INTEGER,
297
+ delivered_answer TEXT,
298
+ delivered_cursor TEXT
297
299
  );
298
300
  CREATE INDEX IF NOT EXISTS sent_msg ON sent(channel, ts);
299
301
  CREATE INDEX IF NOT EXISTS sent_at ON sent(sent_at);
300
- `;function Su(){let e=_n();try{rg(lg(e),{recursive:!0})}catch{}let t=mg(e);if(!t)return;try{og(e,384)}catch{}try{return t.exec(yg),t}catch{try{t.close()}catch{}return}}function Cu(e){if(!Ci())return!1;let t=Su();if(!t)return console.error(` (送信ログに記録できませんでした: ${yo} — ${_n()})`),!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)
301
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.kind,e.team??null,e.channel,e.target??null,e.ts,e.threadTs??null,e.permalink??null,e.text,Date.now(),n.pid,n.agentPid??null,n.host||null,n.cwd,n.gitBranch??null,n.cli??null,n.sessionId??null,e.asBot?1:0),!0}catch(n){return console.error(` (送信ログに記録できませんでした: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var yo="送信ログを開けません: SQLite が使えないランタイムです (bun、または node >= 22.5 の node:sqlite が必要)";function _i(e){let t=Su();if(!t)return;try{let n=[],o=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),o.push(`%${Si(e.text)}%`);if(e.channel)n.push("(channel = ? OR target = ?)"),o.push(e.channel,e.channel);if(e.sinceMs!==void 0)n.push("sent_at >= ?"),o.push(e.sinceMs);if(e.session)n.push("session_id LIKE ? ESCAPE '\\'"),o.push(`${Si(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),o.push(`${Si(e.cwd)}%`);if(e.kind)n.push("kind = ?"),o.push(e.kind);let s=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return o.push(e.limit??50),t.prepare(s).all(...o)}finally{try{t.close()}catch{}}}function Si(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function $i(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let s={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*s}let o=Date.parse(e);return Number.isNaN(o)?void 0:o}class mt 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 Ti(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function Fu(e,t,n,o){o=e.startsWith("xoxc-")?o??$t():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Ti()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new mt(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new mt(60,t);if(a==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
302
+ `;function bo(){let e=lt();try{yg(bg(e),{recursive:!0})}catch{}let t=$g(e);if(!t)return;try{mg(e,384)}catch{}try{t.exec(Fg);for(let n of["delivered_answer TEXT","delivered_cursor TEXT"])try{t.exec(`ALTER TABLE sent ADD COLUMN ${n}`)}catch{}return t}catch{try{t.close()}catch{}return}}function Au(e){if(!Do())return!1;let t=bo();if(!t)return console.error(` (送信ログに記録できませんでした: ${ds} — ${lt()})`),!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)
303
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.kind,e.team??null,e.channel,e.target??null,e.ts,e.threadTs??null,e.permalink??null,e.text,Date.now(),n.pid,n.agentPid??null,n.host||null,n.cwd,n.gitBranch??null,n.cli??null,n.sessionId??null,e.asBot?1:0),!0}catch(n){return console.error(` (送信ログに記録できませんでした: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var ds="送信ログを開けません: SQLite が使えないランタイムです (bun、または node >= 22.5 の node:sqlite が必要)";function Ti(e){let t=bo();if(!t)return;try{let n=[],o=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),o.push(`%${Fi(e.text)}%`);if(e.channel)n.push("(channel = ? OR target = ?)"),o.push(e.channel,e.channel);if(e.sinceMs!==void 0)n.push("sent_at >= ?"),o.push(e.sinceMs);if(e.session)n.push("session_id LIKE ? ESCAPE '\\'"),o.push(`${Fi(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),o.push(`${Fi(e.cwd)}%`);if(e.kind)n.push("kind = ?"),o.push(e.kind);let s=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return o.push(e.limit??50),t.prepare(s).all(...o)}finally{try{t.close()}catch{}}}function Fi(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function ko(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let s={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*s}let o=Date.parse(e);return Number.isNaN(o)?void 0:o}function Tu(e,...t){if(!Do()||!Cu(lt()))return;let n=bo();if(!n)return;try{n.prepare(e).run(...t)}catch{}finally{try{n.close()}catch{}}}function Ii(e,t,n,o){let s=Date.now();Tu(`UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer = ?, answer_exit = 0,
304
+ delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
305
+ WHERE kind = 'ask' AND channel = ? AND ts = ?`,s,n,s,n,o,e,t)}function Iu(e,t,n,o){Tu(`UPDATE sent SET delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
306
+ WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,o,e,t)}function Ou(e){if(!Cu(lt()))return[];let t=bo();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 Ru(e){let t=e.agent_pid??e.pid;if(!Ag(t))return!1;try{let o=(Ai("ps",["-o","lstart=,comm=","-p",String(t)],{encoding:"utf8",timeout:2000}).stdout??"").trim(),s=Date.parse(o.slice(0,24));if(!Number.isNaN(s)&&s>e.sent_at+1000)return!1;let r=_u(o.slice(24).trim()),i=new Set(Object.values(wo));if(e.cli&&i.has(e.cli)&&r&&wo[r]!==e.cli)return!1}catch{}return!0}function Ag(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}class mt 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 Pi(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}async function Bu(e,t,n,o){o=e.startsWith("xoxc-")?o??$t():void 0;let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Pi()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new mt(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new mt(60,t);if(a==="invalid_auth"&&e.startsWith("xoxc-")&&!o)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
302
307
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
303
308
  Or replace the token with an xoxp- user token:
304
309
  slack auth login`);if((a==="missing_scope"||a==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${a}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${a} — ${a==="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"}.
305
310
  Tailing/DMing people and listing users need a user session, not a bot token.
306
311
  Switch workspace: slack auth ls then slack auth use <name>
307
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${a}`)}return i}async function Dg(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Ti()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new mt(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new mt(60,t);if((a==="invalid_auth"||a==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
312
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${a}`)}return i}async function Tg(e,t,n,o){let s={};if(o)s.Cookie=`d=${o}`;let r=await fetch(`${Pi()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...s}});if(r.status===429){let a=parseInt(r.headers.get("retry-after")??"60",10);throw new mt(isNaN(a)?60:a,t)}let i=await r.json();if(i.ok!==!0){let a=i.error??"unknown";if(a==="ratelimited")throw new mt(60,t);if((a==="invalid_auth"||a==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
308
313
  Import from Slack desktop: slack auth login`);if((a==="invalid_auth"||a==="not_authed")&&!o)throw Error(`${t} also requires the xoxd session cookie.
309
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${a}`)}return i}function It(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return Dg(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function fe(e,t,n,o){let s=new URLSearchParams(n).toString();return Fu(e,`${t}?${s}`,{method:"GET"},o)}function Se(e,t,n,o){return Fu(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function Ii(e,t){let n=await fe(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function $n(e,t){t=e.startsWith("xoxc-")?t??$t():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${Ti()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new mt(isNaN(i)?60:i,"auth.test")}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function je(e,t,n=20,o,s,r,i){let a={channel:t,limit:String(n)};if(o!==void 0)a.oldest=o;if(s!==void 0)a.cursor=s;if(i)a.inclusive="true";return fe(e,"conversations.history",a,r)}async function Ie(e,t,n,o=50,s){return fe(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function Au(e,t,n){return fe(e,"files.info",{file:t},n)}async function Tu(e,t={},n){let o={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)o.types=t.types;if(t.channel)o.channel=t.channel;if(t.user)o.user=t.user;return fe(e,"files.list",o,n)}async function Iu(e,t,n,o){let s={name:t,schema:n};if(o)s.todo_mode=!0;return await Se(e,"slackLists.create",s)}async function Oi(e,t,n={}){let o={list_id:t};if(n.limit)o.limit=n.limit;if(n.cursor)o.cursor=n.cursor;if(n.includeList)o.include_list=!0;return await Se(e,"slackLists.items.list",o)}async function Ou(e,t,n){return await Se(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function Ru(e,t,n,o){let s={list_id:t,access_level:n};if(o.userIds?.length)s.user_ids=o.userIds;if(o.channelIds?.length)s.channel_ids=o.channelIds;return await Se(e,"slackLists.access.set",s)}async function Pu(e,t,n){return await Se(e,"slackLists.items.update",{list_id:t,cells:n})}async function vu(e,t,n={},o){let s={list_id:t};if(n.limit)s.limit=String(n.limit);if(n.cursor)s.cursor=n.cursor;return It(e,"lists.records.list",s,o)}async function Lu(e,t,n,o,s){return fe(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(o,1))},s)}async function Bu(e,t,n){return Lu(e,t,100,1,n)}async function Ri(e,t,n,o){let r=1,i=[],a={ok:!0,messages:{}};while(!0){let l=await Lu(e,t,100,r,o),u=ls(l,["messages","matches"]),d=Array.isArray(u)?u:[];i.push(...d);let f=Number(ls(l,["messages","paging","pages"])??1);if(a=l,d.length===0||r>=f||i.length>=n)break;r+=1}let c=a;if(!c.messages)c.messages={};return c.messages.matches=i.slice(0,n),c}async function rn(e,t,n,o,s,r,i,a){let c=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(o!==void 0)c.thread_ts=o;if(s&&o!==void 0)c.reply_broadcast=!0;return(await Nu(e,"chat.postMessage",c,a,r)).ts??""}function wg(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function Nu(e,t,n,o,s){if(!o)return Se(e,t,n,s);try{return await Se(e,t,{...n,metadata:o},s)}catch(r){if(!wg(r))throw r;return Se(e,t,n,s)}}async function Mu(e,t,n,o,s,r){let i={channel:t,text:n,post_at:o,blocks:[{type:"markdown",text:n}]};if(s!==void 0)i.thread_ts=s;return(await Se(e,"chat.scheduleMessage",i,r)).scheduled_message_id??""}async function ju(e,t,n){let o={};if(t)o.channel=t;return fe(e,"chat.scheduledMessages.list",o,n)}async function Wu(e,t,n,o){await Se(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},o)}async function Fn(e,t,n,o){return(await fe(e,"chat.getPermalink",{channel:t,message_ts:n},o)).permalink??""}async function yt(e,t,n,o,s,r,i){return(await Nu(e,"chat.update",r?{channel:t,ts:n,text:o}:{channel:t,ts:n,text:o,blocks:[{type:"markdown",text:o}]},i,s)).ts??n}async function Uu(e,t,n,o){await Se(e,"chat.delete",{channel:t,ts:n},o)}async function Ju(e,t,n,o,s=200,r){let i={channel:t,ts:n,limit:String(s)};if(o!==void 0)i.cursor=o;return fe(e,"conversations.replies",i,r)}async function Pi(e,t,n,o){await Se(e,"pins.add",{channel:t,timestamp:n},o)}async function Ot(e,t,n,o,s){await Se(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function Ku(e,t,n,o){return((await fe(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function an(e,t,n,o,s){await Se(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function qu(e,t,n=!1,o){let s=await Se(e,"conversations.create",{name:t,is_private:n},o);return{id:s.channel?.id??"",name:s.channel?.name??t}}async function Hu(e,t,n,o){let s=await Se(e,"conversations.rename",{channel:t,name:n},o);return{id:s.channel?.id??t,name:s.channel?.name??n}}async function zu(e,t,n,o){await Se(e,"conversations.invite",{channel:t,users:n.join(",")},o)}async function us(e,t){let n=[],o="";while(!0){let s={limit:"200",types:"public_channel,private_channel,im,mpim"};if(o)s.cursor=o;let r=await fe(e,"conversations.list",s,t);if(n.push(...r.channels??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{channels:n}}async function Dt(e,t,n){let s=(await Se(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function Gu(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await fe(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function Fi(e,t,n,o){let s=await Gu(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function on(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function _u(e,t){let n=on(e.name??""),o=on(e.real_name??e.profile?.real_name??""),s=on(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var Yu=200;async function Xu(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await fe(e,"users.list",u,n);for(let f of d.members??[]){if(o++,f.id)s.add(f.id);if(_u(f,t))return{id:f.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,a=0,c=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await fe(e,"conversations.list",u,n);for(let f of d.channels??[]){let h=f.user;if(!h||s.has(h))continue;if(i>=Yu){c=!0;break}s.add(h),i++;let g;try{g=(await fe(e,"users.info",{user:h},n)).user}catch(p){if(p instanceof mt)throw p;a++;continue}if(g&&_u(g,t))return{id:h,dm:String(f.id??""),workspaceCount:o,connectCount:i,skipped:a,capped:c}}if(c)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:a,capped:c}}function Vu(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
314
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${a}`)}return i}function It(e,t,n={},o){let s=new URLSearchParams({token:e,...n});return Tg(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()},o)}function ae(e,t,n,o){let s=new URLSearchParams(n).toString();return Bu(e,`${t}?${s}`,{method:"GET"},o)}function be(e,t,n,o){return Bu(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},o)}async function vi(e,t){let n=await ae(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function $n(e,t){t=e.startsWith("xoxc-")?t??$t():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let o=await fetch(`${Pi()}/auth.test`,{method:"GET",headers:n});if(o.status===429){let i=parseInt(o.headers.get("retry-after")??"60",10);throw new mt(isNaN(i)?60:i,"auth.test")}let s=o.headers.get("x-oauth-scopes")??"",r=await o.json();if(r.ok!==!0)throw Error(`Slack error on auth.test: ${r.error??"unknown"}`);return{userId:r.user_id??"",user:r.user??"",botId:r.bot_id??"",team:r.team??"",url:r.url??"",scopes:s.split(",").map((i)=>i.trim()).filter(Boolean)}}async function He(e,t,n=20,o,s,r,i){let a={channel:t,limit:String(n)};if(o!==void 0)a.oldest=o;if(s!==void 0)a.cursor=s;if(i)a.inclusive="true";return ae(e,"conversations.history",a,r)}async function Pe(e,t,n,o=50,s){return ae(e,"conversations.replies",{channel:t,ts:n,limit:String(o)},s)}async function Lu(e,t,n){return ae(e,"files.info",{file:t},n)}async function Nu(e,t={},n){let o={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)o.types=t.types;if(t.channel)o.channel=t.channel;if(t.user)o.user=t.user;return ae(e,"files.list",o,n)}async function Mu(e,t,n,o){let s={name:t,schema:n};if(o)s.todo_mode=!0;return await be(e,"slackLists.create",s)}async function Bi(e,t,n={}){let o={list_id:t};if(n.limit)o.limit=n.limit;if(n.cursor)o.cursor=n.cursor;if(n.includeList)o.include_list=!0;return await be(e,"slackLists.items.list",o)}async function ju(e,t,n){return await be(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function Wu(e,t,n,o){let s={list_id:t,access_level:n};if(o.userIds?.length)s.user_ids=o.userIds;if(o.channelIds?.length)s.channel_ids=o.channelIds;return await be(e,"slackLists.access.set",s)}async function Uu(e,t,n){return await be(e,"slackLists.items.update",{list_id:t,cells:n})}async function Ju(e,t,n={},o){let s={list_id:t};if(n.limit)s.limit=String(n.limit);if(n.cursor)s.cursor=n.cursor;return It(e,"lists.records.list",s,o)}async function Ku(e,t,n,o,s){return ae(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(o,1))},s)}async function qu(e,t,n){return Ku(e,t,100,1,n)}async function Li(e,t,n,o){let r=1,i=[],a={ok:!0,messages:{}};while(!0){let l=await Ku(e,t,100,r,o),u=fs(l,["messages","matches"]),d=Array.isArray(u)?u:[];i.push(...d);let p=Number(fs(l,["messages","paging","pages"])??1);if(a=l,d.length===0||r>=p||i.length>=n)break;r+=1}let c=a;if(!c.messages)c.messages={};return c.messages.matches=i.slice(0,n),c}async function an(e,t,n,o,s,r,i,a){let c=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(o!==void 0)c.thread_ts=o;if(s&&o!==void 0)c.reply_broadcast=!0;return(await Hu(e,"chat.postMessage",c,a,r)).ts??""}function Ig(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function Hu(e,t,n,o,s){if(!o)return be(e,t,n,s);try{return await be(e,t,{...n,metadata:o},s)}catch(r){if(!Ig(r))throw r;return be(e,t,n,s)}}async function zu(e,t,n,o,s,r){let i={channel:t,text:n,post_at:o,blocks:[{type:"markdown",text:n}]};if(s!==void 0)i.thread_ts=s;return(await be(e,"chat.scheduleMessage",i,r)).scheduled_message_id??""}async function Gu(e,t,n){let o={};if(t)o.channel=t;return ae(e,"chat.scheduledMessages.list",o,n)}async function Yu(e,t,n,o){await be(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},o)}async function Fn(e,t,n,o){return(await ae(e,"chat.getPermalink",{channel:t,message_ts:n},o)).permalink??""}async function yt(e,t,n,o,s,r,i){return(await Hu(e,"chat.update",r?{channel:t,ts:n,text:o}:{channel:t,ts:n,text:o,blocks:[{type:"markdown",text:o}]},i,s)).ts??n}async function Xu(e,t,n,o){await be(e,"chat.delete",{channel:t,ts:n},o)}async function Vu(e,t,n,o,s=200,r){let i={channel:t,ts:n,limit:String(s)};if(o!==void 0)i.cursor=o;return ae(e,"conversations.replies",i,r)}async function Ni(e,t,n,o){await be(e,"pins.add",{channel:t,timestamp:n},o)}async function Ot(e,t,n,o,s){await be(e,"reactions.add",{channel:t,timestamp:n,name:o},s)}async function Zu(e,t,n,o){return((await ae(e,"reactions.get",{channel:t,timestamp:n,full:"true"},o)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function cn(e,t,n,o,s){await be(e,"reactions.remove",{channel:t,timestamp:n,name:o},s)}async function Qu(e,t,n=!1,o){let s=await be(e,"conversations.create",{name:t,is_private:n},o);return{id:s.channel?.id??"",name:s.channel?.name??t}}async function ed(e,t,n,o){let s=await be(e,"conversations.rename",{channel:t,name:n},o);return{id:s.channel?.id??t,name:s.channel?.name??n}}async function td(e,t,n,o){await be(e,"conversations.invite",{channel:t,users:n.join(",")},o)}async function ps(e,t){let n=[],o="";while(!0){let s={limit:"200",types:"public_channel,private_channel,im,mpim"};if(o)s.cursor=o;let r=await ae(e,"conversations.list",s,t);if(n.push(...r.channels??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{channels:n}}async function wt(e,t,n){let s=(await be(e,"conversations.open",{users:t},n)).channel?.id;if(!s)throw Error(`Failed to open DM with user ${t}`);return s}async function nd(e,t,n){let o="";while(!0){let s={types:"im",limit:"200"};if(o)s.cursor=o;let r=await ae(e,"conversations.list",s,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(o=r.response_metadata?.next_cursor??"",!o)break}return""}async function Oi(e,t,n,o){let s=await nd(e,t,n);if(s)return s;let r=o?`${o} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function rn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Pu(e,t){let n=rn(e.name??""),o=rn(e.real_name??e.profile?.real_name??""),s=rn(e.profile?.display_name??"");return n===t||o===t||!!s&&s===t}var sd=200;async function od(e,t,n){let o=0,s=new Set,r="";while(!0){let u={limit:"200"};if(r)u.cursor=r;let d=await ae(e,"users.list",u,n);for(let p of d.members??[]){if(o++,p.id)s.add(p.id);if(Pu(p,t))return{id:p.id??"",workspaceCount:o,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,a=0,c=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await ae(e,"conversations.list",u,n);for(let p of d.channels??[]){let h=p.user;if(!h||s.has(h))continue;if(i>=sd){c=!0;break}s.add(h),i++;let y;try{y=(await ae(e,"users.info",{user:h},n)).user}catch(f){if(f instanceof mt)throw f;a++;continue}if(y&&Pu(y,t))return{id:h,dm:String(p.id??""),workspaceCount:o,connectCount:i,skipped:a,capped:c}}if(c)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:o,connectCount:i,skipped:a,capped:c}}function rd(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
310
315
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
311
- Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${Yu} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
316
+ Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,o=[];if(t.capped)o.push(`stopped after ${sd} Slack Connect DM partners, so there may be more`);if(t.skipped)o.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
312
317
  `+(o.length?`This search was incomplete: ${o.join("; ")}.
313
318
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
314
319
  DMed you they cannot be found by name at all. Look them up and use their ID:
315
- slack user ls --external`)}async function wt(e,t,n){let o=t.startsWith("@")?t.slice(1):t;if(Ai(o))return o;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let s=on(o),r=await fe(e,"auth.test",{},n);if(s==="you"||s==="me"||on(r.user??"")===s){if(!r.user_id)throw Error("auth.test did not return user_id");return r.user_id}let i=await Xu(e,s,n);if(i.id)return i.id;throw Vu(t,i)}function Rt(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function bg(e){return Rt(e)?.channel}function $u(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function Ai(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function ye(e,t,n){let o=bg(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if($u(t))return t;if(Ai(t))return Fi(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&$u(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=on(r);if(s){if(Ai(r))return Fi(e,r,n);let l=await fe(e,"auth.test",{},n);if(i==="you"||i==="me"||on(l.user??"")===i){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await Gu(e,f,n)||Dt(e,f,n)}let d=await Xu(e,i,n);if(!d.id)throw Vu(t,d);if(d.dm)return d.dm;return Fi(e,d.id,n,t)}let a=r.toLowerCase(),c="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)l.cursor=c;let u=await fe(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===a)return String(d.id??"");if(c=u.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function ds(e,t,n){try{let o=await fe(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function Te(e,t,n){try{let o=await fe(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function Zu(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await fe(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function Qu(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await fe(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function ed(e,t={},n){let o={limit:String(t.limit??50)};if(t.filter)o.filter=t.filter;if(t.cursor)o.cursor=t.cursor;return It(e,"saved.list",o,n)}async function fs(e,t){return It(e,"drafts.list",{},t)}async function td(e,t,n,o){let{randomUUID:s}=await import("node:crypto"),r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Hs(n)}]}]);return It(e,"drafts.create",{client_msg_id:s(),destinations:JSON.stringify([{channel_id:t}]),blocks:r,file_ids:JSON.stringify([]),is_from_composer:"true"},o)}async function nd(e,t,n,o,s){let r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Hs(o)}]}]),i=(Date.now()/1000).toFixed(6);return It(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:r,file_ids:JSON.stringify([])},s)}async function sd(e,t,n){return It(e,"conversations.info",{channel:t},n)}async function ps(e,t,n){return fe(e,"users.info",{user:t},n)}async function od(e,t,n){try{let o=await fe(e,"users.info",{user:t,include_locale:"true"},n);return typeof o.user?.locale==="string"?o.user.locale:void 0}catch{return}}async function cn(e,t,n){return fe(e,"conversations.info",{channel:t},n)}async function rd(e,t,n){let o=(Date.now()/1000).toFixed(6);return It(e,"drafts.delete",{draft_id:t,client_last_updated_ts:o},n)}async function vi(e,t){let n=await It(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function id(e,t,n,o={},s){let{statSync:r,readFileSync:i}=await import("node:fs"),{basename:a}=await import("node:path"),c=r(n),l=a(n),u=await fe(e,"files.getUploadURLExternal",{filename:l,length:String(c.size)},s),{upload_url:d,file_id:f}=u;if(!d||!f)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let h=i(n),g=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:h});if(!g.ok)throw Error(`Upload PUT failed: ${g.status} ${g.statusText}`);let p={files:[{id:f,title:o.title??l}],channel_id:t};if(o.threadTs)p.thread_ts=o.threadTs;if(o.initialComment)p.initial_comment=o.initialComment;let m=await Se(e,"files.completeUploadExternal",p,s),D={fileId:f},w=m.files?.[0]?.permalink;if(w)D.permalink=w;return D}function ls(e,t){let n=e;for(let o of t){if(n===void 0||n===null)return;if(typeof o==="number"){if(!Array.isArray(n))return;n=n[o]??void 0}else{if(typeof n!=="object"||Array.isArray(n))return;n=n[o]}}return n}var cd=["todo","saved","completed","archived"],hs=(e)=>typeof e==="string"?e:"",ad=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function ld(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return(Array.isArray(t.saved_items)?t.saved_items:[]).filter((o)=>!!o&&typeof o==="object"&&!Array.isArray(o)).map((o)=>({channel:hs(o.item_id),ts:hs(o.ts),due:ad(o.date_due),completed:ad(o.date_completed),todoState:hs(o.todo_state),state:hs(o.state),archived:o.is_archived===!0,itemType:hs(o.item_type)}))}function ud(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 Do(e){return e.completed>0||e.state==="completed"}function dd(e,t,n){let o=Do(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${o} no due date`;let s=!Do(e)&&e.due<t?" OVERDUE":"";return`${o} due ${n(e.due)}${s}`}function fd(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as Tg,readFileSync as Ig}from"node:fs";import{homedir as Og}from"node:os";import{join as Rg}from"node:path";import{existsSync as kg,mkdirSync as xg,readFileSync as Eg,writeFileSync as Sg}from"node:fs";import{homedir as Cg}from"node:os";import{dirname as _g,join as $g}from"node:path";var Fg=3600000,wo={now:()=>Date.now(),path:()=>$g(process.env.HOME||Cg(),".config","slack-cli","cache.json")},bo=!0,Pt;function pd(){return{channels:{},users:{}}}function Li(){if(Pt)return Pt;if(Pt=pd(),!bo)return Pt;try{let e=wo.path();if(!kg(e))return Pt;let t=JSON.parse(Eg(e,"utf8"));for(let n of["channels","users"]){let o=t?.[n];if(!o||typeof o!=="object"||Array.isArray(o))continue;for(let[s,r]of Object.entries(o))if(r&&typeof r==="object"&&typeof r.value==="string"&&typeof r.expires==="number")Pt[n][s]={value:r.value,expires:r.expires}}}catch{Pt=pd()}return Pt}function Ag(e){if(!bo)return;try{let t=wo.path();xg(_g(t),{recursive:!0}),Sg(t,JSON.stringify(e,null,2)+`
316
- `)}catch{}}function hd(e,t){return e?`${e} ${t}`:void 0}function ko(e,t,n){if(!bo)return;let o=hd(t,n);if(!o)return;let s=Li()[e][o];if(!s)return;if(s.expires<=wo.now()){delete Li()[e][o];return}return s.value}function xo(e,t,n,o,s=Fg){if(!bo)return;let r=hd(t,n);if(!r)return;let i=Li();i[e][r]={value:o,expires:wo.now()+s},Ag(i)}var Bi={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"}},An=["done","dropped","doing","pending"],Dd=["alert","needs-discussion","waiting","blocked"];function Pg(){return Rg(process.env.HOME||Og(),".config","slack-cli","todo.json")}function Eo(e){return e.replace(/^:+|:+$/g,"")}function gs(e=Pg()){let t={marker:Bi.marker,progress:{...Bi.progress},flags:{...Bi.flags}};try{if(!Tg(e))return t;let n=JSON.parse(Ig(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=Eo(n.marker.trim());for(let o of An){let s=n.progress?.[o];if(typeof s==="string"&&s.trim())t.progress[o]=Eo(s.trim())}for(let o of Dd){let s=n.flags?.[o];if(typeof s==="string"&&s.trim())t.flags[o]=Eo(s.trim())}}catch{}return t}function gd(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${Eo(e)}:`}function wd(e,t,n={}){let o=n.shared===!0,s=(a)=>gd(a,o),r=(a)=>gd(a,o,!0),i=[];if(e==="untriaged")i.push(s(t.marker),...An.map((a)=>r(t.progress[a])));else if(e==="stuck")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped),`(${Dd.map((a)=>s(t.flags[a])).join(" OR ")})`);else if(e==="open")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped));else{let a=An.indexOf(e);i.push(s(t.progress[e]));for(let c of An.slice(0,a))i.push(r(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 vg=3,Lg={sleep:(e)=>Bg()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Bg(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function We(e,t,n=vg){for(let o=0;;o++)try{return await t()}catch(s){if(!(s instanceof it))throw s;if(o>=n)throw Error(`Slack rate limit hit on ${e} — gave up after ${n} retries. Try again in a minute.`);console.error(`Warning: Slack rate limit hit on ${e} — backing off for ${s.retryAfter}s`),await Lg.sleep(s.retryAfter*1000)}}var md=new Map;async function bd(e,t){let n=md.get(e);if(n)return n;let o=await We("auth.test",()=>En(e,t)),s={userId:o.userId,teamId:o.teamId};return md.set(e,s),s}async function kd(e,t){return(await bd(e,t)).userId}async function Ni(e,t){try{return(await bd(e,t)).teamId}catch{return""}}async function Mi(e,t,n,o){if(!t.startsWith("#"))return n(e,t,o);let s=await Ni(e,o),r=ko("channels",s,t);if(r)return r;let i=await We("resolveChannel",()=>n(e,t,o));return xo("channels",s,t,i),i}async function xd(e,t,n,o){let s=await Ni(e,o),r=ko("users",s,t);if(r)return r;let i=await We("users.info",()=>n(e,t,o));if(i&&i!==t)xo("users",s,t,i);return i}async function Ed(e,t,n,o){let s=await Ni(e,o),r=ko("users",s,`tz:${t}`);if(r)return r==="?"?null:r;let i=null;try{let a=await We("users.info",()=>n(e,t,o));if(a?.user?.is_bot===!0||t==="USLACKBOT")return yd(s,t,null);let c=a?.user?.tz;i=typeof c==="string"&&c?c:null}catch{return null}return yd(s,t,i)}function yd(e,t,n){return xo("users",e,`tz:${t}`,n??"?"),n}async function Sd(e,t,n,o,s,r){let i=s.progress[o],a=await kd(e,r),c=await We("reactions.get",()=>ll(e,t,n,r)),l=new Set(c.filter((h)=>h.users.includes(a)).map((h)=>h.name)),u=An.map((h)=>s.progress[h]).filter((h)=>l.has(h));if(u.length===1&&u[0]===i)return{noop:!0,removed:[],leftover:[]};if(!l.has(i))await We("reactions.add",()=>zs(e,t,n,i,r));let d=[],f=[];for(let h of u){if(h===i)continue;try{await We("reactions.remove",()=>Gs(e,t,n,h,r)),d.push(h)}catch{f.push(h)}}return{noop:!1,added:o,removed:d,leftover:f}}async function Cd(e,t,n,o,s,r,i){let a=s.flags[o];if(r)await We("reactions.remove",()=>Gs(e,t,n,a,i));else await We("reactions.add",()=>zs(e,t,n,a,i));return a}var ji=1000;async function _d(e,t,n,o={}){let s=o.limit??ji,r=o.cookie,i=await kd(e,r),a=An.map((f)=>n.progress[f]),c=[],l=0,u,d=!1;while(l<s){let f=Math.min(200,s-l),h=await We("conversations.history",()=>Xn(e,t,f,void 0,u,r)),g=h.messages??[];l+=g.length;for(let p of g){let m=String(p.ts??"");if(!m)continue;let D=new Set((p.reactions??[]).filter((k)=>(k.users??[]).map(String).includes(i)).map((k)=>String(k.name??""))),w=a.filter((k)=>D.has(k));if(w.length<2)continue;c.push({ts:m,text:String(p.text??"").split(`
317
- `)[0]??"",emoji:w,keep:w[0]})}if(u=h.response_metadata?.next_cursor||void 0,!u||g.length===0)break;if(l>=s){d=!0;break}}if(o.fix)for(let f of c)try{try{await We("reactions.add",()=>zs(e,t,f.ts,f.keep,r))}catch(h){if(!(h instanceof Error)||!/already_reacted/.test(h.message))throw h}for(let h of f.emoji){if(h===f.keep)continue;await We("reactions.remove",()=>Gs(e,t,f.ts,h,r))}f.fixed=!0}catch(h){f.fixed=!1,f.error=h instanceof Error?h.message:String(h)}return{scanned:l,findings:c,truncated:d}}var Ng=!0,Mg;function Wi(e){if(Ng=e,!e)Mg=void 0}function Oe(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
318
- `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function Tn(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var In=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},Re=(e)=>typeof e==="string"?e:"";function jg(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>Re(In(In(n).message).text)).filter(Boolean).join(`
319
- `)}function Ui(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(In).map((n)=>{let o=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),s=In(In((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:o,unfurl:!o&&!!Re(n.original_url),author_id:Re(n.author_id)||Re(In(s.message).user)||null,author_name:Re(n.author_name)||null,channel_id:Re(n.channel_id)||Re(s.channel)||null,ts:Re(n.ts)||Re(s.ts)||null,title:Re(n.title)||null,text:Re(n.text)||jg(n)||Re(n.pretext)||Re(n.fallback),permalink:Re(n.from_url)||Re(n.title_link)||Re(n.original_url)||null}})}function $d(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let o=n.author_name??n.author_id,s=n.shared?`↪ shared message${o?` from @${o}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,r=n.text?n.text.replace(/\n+$/,"").split(`
320
+ slack user ls --external`)}async function Dt(e,t,n){let o=t.startsWith("@")?t.slice(1):t;if(Ri(o))return o;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let s=rn(o),r=await ae(e,"auth.test",{},n);if(s==="you"||s==="me"||rn(r.user??"")===s){if(!r.user_id)throw Error("auth.test did not return user_id");return r.user_id}let i=await od(e,s,n);if(i.id)return i.id;throw rd(t,i)}function Rt(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],o=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,s=e.indexOf("?"),r=s>=0?new URLSearchParams(e.slice(s)):void 0,i=r?.get("thread_ts")??void 0,l={channel:r?.get("cid")??void 0??n};if(o)l.ts=o;if(i)l.threadTs=i;return l}function Og(e){return Rt(e)?.channel}function vu(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function Ri(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function fe(e,t,n){let o=Og(t);if(o)return o;if(!t.startsWith("@")&&!t.startsWith("#")){if(vu(t))return t;if(Ri(t))return Oi(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&vu(t.slice(1)))return t.slice(1);let s=t.startsWith("@"),r=t.slice(1),i=rn(r);if(s){if(Ri(r))return Oi(e,r,n);let l=await ae(e,"auth.test",{},n);if(i==="you"||i==="me"||rn(l.user??"")===i){let p=l.user_id;if(!p)throw Error("auth.test did not return user_id");return await nd(e,p,n)||wt(e,p,n)}let d=await od(e,i,n);if(!d.id)throw rd(t,d);if(d.dm)return d.dm;return Oi(e,d.id,n,t)}let a=r.toLowerCase(),c="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)l.cursor=c;let u=await ae(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===a)return String(d.id??"");if(c=u.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function hs(e,t,n){try{let o=await ae(e,"users.info",{user:t},n),s=o.user?.profile?.display_name,r=s&&s.length>0?s:o.user?.real_name??o.user?.name??t,i=o.user?.name??t;return[r,i]}catch{return[t,t]}}async function $e(e,t,n){try{let o=await ae(e,"users.info",{user:t},n),s=o.user?.profile?.display_name;if(s&&s.length>0)return s;return o.user?.real_name??o.user?.name??t}catch{return t}}async function id(e,t){let n=[],o="";while(!0){let s={limit:"200"};if(o)s.cursor=o;let r=await ae(e,"users.list",s,t);if(n.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return{members:n}}async function ad(e,t,n){let o=[],s="";while(!0){let r={channel:t,limit:"200"};if(s)r.cursor=s;let i=await ae(e,"conversations.members",r,n);if(o.push(...i.members??[]),s=i.response_metadata?.next_cursor??"",!s)break}return o}async function cd(e,t={},n){let o={limit:String(t.limit??50)};if(t.filter)o.filter=t.filter;if(t.cursor)o.cursor=t.cursor;return It(e,"saved.list",o,n)}async function gs(e,t){return It(e,"drafts.list",{},t)}async function ld(e,t,n,o){let{randomUUID:s}=await import("node:crypto"),r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Gs(n)}]}]);return It(e,"drafts.create",{client_msg_id:s(),destinations:JSON.stringify([{channel_id:t}]),blocks:r,file_ids:JSON.stringify([]),is_from_composer:"true"},o)}async function ud(e,t,n,o,s){let r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Gs(o)}]}]),i=(Date.now()/1000).toFixed(6);return It(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:r,file_ids:JSON.stringify([])},s)}async function dd(e,t,n){return It(e,"conversations.info",{channel:t},n)}async function ms(e,t,n){return ae(e,"users.info",{user:t},n)}async function fd(e,t,n){try{let o=await ae(e,"users.info",{user:t,include_locale:"true"},n);return typeof o.user?.locale==="string"?o.user.locale:void 0}catch{return}}async function ln(e,t,n){return ae(e,"conversations.info",{channel:t},n)}async function pd(e,t,n){let o=(Date.now()/1000).toFixed(6);return It(e,"drafts.delete",{draft_id:t,client_last_updated_ts:o},n)}async function Mi(e,t){let n=await It(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function hd(e,t,n,o={},s){let{statSync:r,readFileSync:i}=await import("node:fs"),{basename:a}=await import("node:path"),c=r(n),l=a(n),u=await ae(e,"files.getUploadURLExternal",{filename:l,length:String(c.size)},s),{upload_url:d,file_id:p}=u;if(!d||!p)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let h=i(n),y=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:h});if(!y.ok)throw Error(`Upload PUT failed: ${y.status} ${y.statusText}`);let f={files:[{id:p,title:o.title??l}],channel_id:t};if(o.threadTs)f.thread_ts=o.threadTs;if(o.initialComment)f.initial_comment=o.initialComment;let g=await be(e,"files.completeUploadExternal",f,s),w={fileId:p},D=g.files?.[0]?.permalink;if(D)w.permalink=D;return w}function fs(e,t){let n=e;for(let o of t){if(n===void 0||n===null)return;if(typeof o==="number"){if(!Array.isArray(n))return;n=n[o]??void 0}else{if(typeof n!=="object"||Array.isArray(n))return;n=n[o]}}return n}var md=["todo","saved","completed","archived"],ys=(e)=>typeof e==="string"?e:"",gd=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function yd(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return(Array.isArray(t.saved_items)?t.saved_items:[]).filter((o)=>!!o&&typeof o==="object"&&!Array.isArray(o)).map((o)=>({channel:ys(o.item_id),ts:ys(o.ts),due:gd(o.date_due),completed:gd(o.date_completed),todoState:ys(o.todo_state),state:ys(o.state),archived:o.is_archived===!0,itemType:ys(o.item_type)}))}function wd(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 xo(e){return e.completed>0||e.state==="completed"}function Dd(e,t,n){let o=xo(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${o} no due date`;let s=!xo(e)&&e.due<t?" OVERDUE":"";return`${o} due ${n(e.due)}${s}`}function bd(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as Ug,readFileSync as Jg}from"node:fs";import{homedir as Kg}from"node:os";import{join as qg}from"node:path";import{existsSync as Rg,mkdirSync as Pg,readFileSync as vg,writeFileSync as Bg}from"node:fs";import{homedir as Lg}from"node:os";import{dirname as Ng,join as Mg}from"node:path";var jg=3600000,Eo={now:()=>Date.now(),path:()=>Mg(process.env.HOME||Lg(),".config","slack-cli","cache.json")},So=!0,Pt;function kd(){return{channels:{},users:{}}}function ji(){if(Pt)return Pt;if(Pt=kd(),!So)return Pt;try{let e=Eo.path();if(!Rg(e))return Pt;let t=JSON.parse(vg(e,"utf8"));for(let n of["channels","users"]){let o=t?.[n];if(!o||typeof o!=="object"||Array.isArray(o))continue;for(let[s,r]of Object.entries(o))if(r&&typeof r==="object"&&typeof r.value==="string"&&typeof r.expires==="number")Pt[n][s]={value:r.value,expires:r.expires}}}catch{Pt=kd()}return Pt}function Wg(e){if(!So)return;try{let t=Eo.path();Pg(Ng(t),{recursive:!0}),Bg(t,JSON.stringify(e,null,2)+`
321
+ `)}catch{}}function xd(e,t){return e?`${e} ${t}`:void 0}function Co(e,t,n){if(!So)return;let o=xd(t,n);if(!o)return;let s=ji()[e][o];if(!s)return;if(s.expires<=Eo.now()){delete ji()[e][o];return}return s.value}function _o(e,t,n,o,s=jg){if(!So)return;let r=xd(t,n);if(!r)return;let i=ji();i[e][r]={value:o,expires:Eo.now()+s},Wg(i)}var Wi={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"}},An=["done","dropped","doing","pending"],_d=["alert","needs-discussion","waiting","blocked"];function Hg(){return qg(process.env.HOME||Kg(),".config","slack-cli","todo.json")}function $o(e){return e.replace(/^:+|:+$/g,"")}function ws(e=Hg()){let t={marker:Wi.marker,progress:{...Wi.progress},flags:{...Wi.flags}};try{if(!Ug(e))return t;let n=JSON.parse(Jg(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=$o(n.marker.trim());for(let o of An){let s=n.progress?.[o];if(typeof s==="string"&&s.trim())t.progress[o]=$o(s.trim())}for(let o of _d){let s=n.flags?.[o];if(typeof s==="string"&&s.trim())t.flags[o]=$o(s.trim())}}catch{}return t}function Ed(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${$o(e)}:`}function $d(e,t,n={}){let o=n.shared===!0,s=(a)=>Ed(a,o),r=(a)=>Ed(a,o,!0),i=[];if(e==="untriaged")i.push(s(t.marker),...An.map((a)=>r(t.progress[a])));else if(e==="stuck")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped),`(${_d.map((a)=>s(t.flags[a])).join(" OR ")})`);else if(e==="open")i.push(s(t.marker),r(t.progress.done),r(t.progress.dropped));else{let a=An.indexOf(e);i.push(s(t.progress[e]));for(let c of An.slice(0,a))i.push(r(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 zg=3,Gg={sleep:(e)=>Yg()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Yg(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Ne(e,t,n=zg){for(let o=0;;o++)try{return await t()}catch(s){if(!(s instanceof st))throw s;if(o>=n)throw Error(`Slack rate limit hit on ${e} — gave up after ${n} retries. Try again in a minute.`);console.error(`Warning: Slack rate limit hit on ${e} — backing off for ${s.retryAfter}s`),await Gg.sleep(s.retryAfter*1000)}}var Sd=new Map;async function Fd(e,t){let n=Sd.get(e);if(n)return n;let o=await Ne("auth.test",()=>Sn(e,t)),s={userId:o.userId,teamId:o.teamId};return Sd.set(e,s),s}async function Ad(e,t){return(await Fd(e,t)).userId}async function Ui(e,t){try{return(await Fd(e,t)).teamId}catch{return""}}async function Ji(e,t,n,o){if(!t.startsWith("#"))return n(e,t,o);let s=await Ui(e,o),r=Co("channels",s,t);if(r)return r;let i=await Ne("resolveChannel",()=>n(e,t,o));return _o("channels",s,t,i),i}async function Td(e,t,n,o){let s=await Ui(e,o),r=Co("users",s,t);if(r)return r;let i=await Ne("users.info",()=>n(e,t,o));if(i&&i!==t)_o("users",s,t,i);return i}async function Id(e,t,n,o){let s=await Ui(e,o),r=Co("users",s,`tz:${t}`);if(r)return r==="?"?null:r;let i=null;try{let a=await Ne("users.info",()=>n(e,t,o));if(a?.user?.is_bot===!0||t==="USLACKBOT")return Cd(s,t,null);let c=a?.user?.tz;i=typeof c==="string"&&c?c:null}catch{return null}return Cd(s,t,i)}function Cd(e,t,n){return _o("users",e,`tz:${t}`,n??"?"),n}async function Od(e,t,n,o,s,r){let i=s.progress[o],a=await Ad(e,r),c=await Ne("reactions.get",()=>hl(e,t,n,r)),l=new Set(c.filter((h)=>h.users.includes(a)).map((h)=>h.name)),u=An.map((h)=>s.progress[h]).filter((h)=>l.has(h));if(u.length===1&&u[0]===i)return{noop:!0,removed:[],leftover:[]};if(!l.has(i))await Ne("reactions.add",()=>Ys(e,t,n,i,r));let d=[],p=[];for(let h of u){if(h===i)continue;try{await Ne("reactions.remove",()=>Xs(e,t,n,h,r)),d.push(h)}catch{p.push(h)}}return{noop:!1,added:o,removed:d,leftover:p}}async function Rd(e,t,n,o,s,r,i){let a=s.flags[o];if(r)await Ne("reactions.remove",()=>Xs(e,t,n,a,i));else await Ne("reactions.add",()=>Ys(e,t,n,a,i));return a}var Ki=1000;async function Pd(e,t,n,o={}){let s=o.limit??Ki,r=o.cookie,i=await Ad(e,r),a=An.map((p)=>n.progress[p]),c=[],l=0,u,d=!1;while(l<s){let p=Math.min(200,s-l),h=await Ne("conversations.history",()=>Vn(e,t,p,void 0,u,r)),y=h.messages??[];l+=y.length;for(let f of y){let g=String(f.ts??"");if(!g)continue;let w=new Set((f.reactions??[]).filter((k)=>(k.users??[]).map(String).includes(i)).map((k)=>String(k.name??""))),D=a.filter((k)=>w.has(k));if(D.length<2)continue;c.push({ts:g,text:String(f.text??"").split(`
322
+ `)[0]??"",emoji:D,keep:D[0]})}if(u=h.response_metadata?.next_cursor||void 0,!u||y.length===0)break;if(l>=s){d=!0;break}}if(o.fix)for(let p of c)try{try{await Ne("reactions.add",()=>Ys(e,t,p.ts,p.keep,r))}catch(h){if(!(h instanceof Error)||!/already_reacted/.test(h.message))throw h}for(let h of p.emoji){if(h===p.keep)continue;await Ne("reactions.remove",()=>Xs(e,t,p.ts,h,r))}p.fixed=!0}catch(h){p.fixed=!1,p.error=h instanceof Error?h.message:String(h)}return{scanned:l,findings:c,truncated:d}}var Xg=!0,Vg;function qi(e){if(Xg=e,!e)Vg=void 0}function Fe(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
323
+ `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function Tn(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var In=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},Ae=(e)=>typeof e==="string"?e:"";function Zg(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>Ae(In(In(n).message).text)).filter(Boolean).join(`
324
+ `)}function Hi(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(In).map((n)=>{let o=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),s=In(In((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:o,unfurl:!o&&!!Ae(n.original_url),author_id:Ae(n.author_id)||Ae(In(s.message).user)||null,author_name:Ae(n.author_name)||null,channel_id:Ae(n.channel_id)||Ae(s.channel)||null,ts:Ae(n.ts)||Ae(s.ts)||null,title:Ae(n.title)||null,text:Ae(n.text)||Zg(n)||Ae(n.pretext)||Ae(n.fallback),permalink:Ae(n.from_url)||Ae(n.title_link)||Ae(n.original_url)||null}})}function vd(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let o=n.author_name??n.author_id,s=n.shared?`↪ shared message${o?` from @${o}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,r=n.text?n.text.replace(/\n+$/,"").split(`
320
325
  `).map((a)=>`
321
326
  │ ${a}`).join(""):"",i=n.permalink?`
322
327
  ${n.permalink}`:"";return`
323
- ${s}${r}${i}`}).join("")}var Fd=new Set(["send","ask","poll","vote","edit","delete","react","upload","schedule send","schedule rm","pinlog new","pinlog set","pinlog note","pinlog pin","todo set","todo flag","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"]),Wg={channels:"channel",ch:"channel"};function Ug(e){let[t="",n=""]=e.map(String),o=Wg[t]??t;return Fd.has(o)||Fd.has(`${o} ${n}`)}function Jg(e,t){return String(e[0]??"")==="ask"&&t.ls===!0}function Ad(e,t,n){let o=n.botTokenSource;if(!o||n.globalPaths.includes(o))return null;if(n.slackTokenSet||n.activeTokenIsBot)return null;if(!Ug(e)||Jg(e,t)||t["as-bot"]===!0)return null;let s=o==="shell"?"exported in the environment":`set in ${o}`,r="as-bot"in t;return[`Error: refusing to act as YOU — SLACK_BOT_TOKEN is ${s}, but \`${e.slice(0,2).join(" ")}\` would use your user session, not the bot.`,r?" 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(`
324
- `)}function ln(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function vt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Kg(e,t){let n=ln(t),o=vt(e.profile);for(let r of[e.name,e.real_name,o.display_name,o.real_name])if(typeof r==="string"&&r&&ln(r)===n)return!0;let s=typeof o.email==="string"?o.email.toLowerCase():"";return s!==""&&s===t.toLowerCase()}function qg(e){let t=vt(e.profile),n=new Set;for(let o of[t.display_name,e.real_name,e.name,t.real_name])if(typeof o==="string"&&o){let s=ln(o);if(s.length>=2)n.add(s)}return[...n]}function Hg(e,t){let n=ln(e),o,s=!1;for(let r of t){let i=typeof r.id==="string"?r.id:"";if(!i)continue;for(let a of qg(r)){let c=-1;if(n===a)c=e.length;else for(let l of Id)if(e.length>l.length&&e.endsWith(l)&&ln(e.slice(0,e.length-l.length))===a){c=e.length-l.length;break}if(c<0)continue;if(!o||a.length>o.formLen)o={userId:i,matchLen:c,formLen:a.length,display:qi(r)},s=!1;else if(a.length===o.formLen&&o.userId!==i)s=!0}}if(!o)return;return s?"ambiguous":{userId:o.userId,matchLen:o.matchLen,display:o.display}}async function Lt(e,t,n,o){let s=`[${Od}ー]+`,r=`${s}(?:[._-]+${s})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${r})`,"gu"),a=new Set;for(let w of t.matchAll(i))a.add(w[1]);if(a.size===0)return{text:t,resolved:[],unresolved:[]};let c=new Map;for(let w of a)c.set(w,{status:"pending"});let l=(w)=>{for(let k of a){if(c.get(k).status!=="pending")continue;if(Ki(k)){let x=Hg(k,w);if(x==="ambiguous")c.set(k,{status:"ambiguous"});else if(x)c.set(k,{status:"resolved",userId:x.userId,matchLen:x.matchLen,display:x.display})}else{let x=w.filter((I)=>Kg(I,k)),C=new Set(x.map((I)=>typeof I.id==="string"?I.id:"").filter(Boolean));if(C.size===1){let I=x.find((A)=>typeof A.id==="string");c.set(k,{status:"resolved",userId:I.id,matchLen:k.length,display:qi(I)})}else if(C.size>1)c.set(k,{status:"ambiguous"})}}},u=!1;try{let w=await Zs(e,o);l((w.members??[]).map(vt)),u=!0}catch{u=!1}let d=[...a].some((w)=>c.get(w).status==="pending"),f=!1,h=!0;if(d&&n){f=!0;try{let w=await Ur(e,n,o),k=[];for(let x of w){let C=vt(await Jr(e,x,o)),I=vt(C.user);if(typeof I.id!=="string")I.id=x;k.push(I)}l(k)}catch{h=!1}}let g=u&&(n?f&&h:!0),p=[],m=[];for(let w of a){let k=c.get(w);if(k.status==="resolved")p.push({surface:`@${w.slice(0,k.matchLen)}`,display:k.display,userId:k.userId});else if(k.status==="ambiguous")m.push({surface:`@${w}`,reason:"ambiguous"});else m.push({surface:`@${w}`,reason:g?"no-match":"unavailable"})}return{text:t.replace(i,(w,k)=>{let x=c.get(k);if(x&&x.status==="resolved")return`<@${x.userId}>${k.slice(x.matchLen)}`;return w}),resolved:p,unresolved:m}}function ms(e){let t=[],n=!1;for(let o of e)if(o.reason==="ambiguous")t.push(`${o.surface} matches multiple people — not tagged, sent as plain text (use <@USERID> to tag)`);else if(o.reason==="unavailable"){if(n)continue;t.push("could not fetch the user list (users:read missing or an API/connection error) — @mentions not tagged, sent as plain text"),n=!0}else t.push(`${o.surface} matched no one — not tagged, sent as plain text`);return t}async function Td(e,t,n,o={}){let s=o.warn??((i)=>process.stderr.write(`${i}
325
- `)),r=await Lt(e,t,n,o.cookie);for(let i of ms(r.unresolved))s(`warn: ${i}`);return r.text}var Id=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],Od="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function Ki(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function zg(e){let t=[],n=new RegExp(`([${Od}]{1,12})(${Id.join("|")})`,"gu");for(let o of e.matchAll(n))t.push({ref:o[1],honorific:o[2]});for(let o of e.matchAll(/\b(?:dear|hi|hello|hey)\b[ \t]+([A-Z][A-Za-z'’-]{1,20})/gi))t.push({ref:o[1],honorific:""});for(let o of e.matchAll(/(?:^|\n)[ \t]*([A-Z][A-Za-z'’-]{1,20}),/g))t.push({ref:o[1],honorific:""});return t}function Gg(e){let t=vt(e.profile),n=new Set;for(let o of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof o!=="string"||!o)continue;for(let s of[o,...o.split(/\s+/)]){let r=ln(s);if(r.length>=2)n.add(r)}}return[...n]}function Yg(e,t){let n=ln(e);if(n.length<2)return;for(let o of t)if(n===o)return o;if(Ki(e)){for(let o of t)if(n.includes(o)||o.includes(n))return o}return}function qi(e){return[vt(e.profile).display_name,e.real_name,e.name].filter((o)=>typeof o==="string"&&o!=="")[0]??String(e.id??"?")}async function Rd(e,t,n){let o=zg(t);if(o.length===0)return[];let s=new Set;for(let l of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))s.add(l[1]);let i=((await Zs(e,n)).members??[]).map(vt).filter((l)=>l.deleted!==!0&&l.is_bot!==!0&&l.id!=="USLACKBOT").map((l)=>({id:typeof l.id==="string"?l.id:"",forms:Gg(l),display:qi(l)})).filter((l)=>l.id!==""),a=[],c=new Set;for(let{ref:l,honorific:u}of o)for(let d of i){let f=Yg(l,d.forms);if(!f)continue;if(s.has(d.id)||c.has(d.id))break;c.add(d.id),a.push({surface:Ki(l)?`${f}${u}`:l,display:d.display,userId:d.id});break}return a}async function un(e,t,n,o){let s=t,r=[],i=s,a=0;while(!0){let c=i.indexOf("<@U",a);if(c===-1)break;let l=i.slice(c+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);a=c+1}for(let c of r){if(!n.has(c))n.set(c,await Vs(e,c,o));let l=n.get(c)??c;s=s.replaceAll(`<@${c}>`,`@${l}`),s=s.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${l}`)}return s}function On(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=i[r.getUTCDay()]??"",l=a[r.getUTCMonth()]??"";return`${c}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function Pd(e,t=new Date){let n=new Date(e*1000),o=Ji(t),s=Ji(new Date(t.getTime()-86400000)),r=Ji(n);if(r===o)return"Today";if(r===s)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 Ji(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function So(e){let t=new Date(e*1000),n=t.getFullYear(),o=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}`}var Xg=/[A-Za-z0-9_-]{32,}/g;function ys(e){return e.replace(Xg,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function Hi(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",o=!!t&&Vg(t),s=o?t:n,r=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),a,c;try{let h=new Intl.DateTimeFormat("en-GB",{timeZone:s,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});c=h.format(e),a=Number(h.formatToParts(e).find((g)=>g.type==="hour")?.value??"12")}catch{return null}let l=r>i?a>=r||a<i:a>=r&&a<i,u=o?`${s}, recipient`:`${s}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${c} (${u})`;if(!l)return d;return`${d}
326
- ⚠ QUIET HOURS (${r}:00-${i}:00) — this will buzz a phone.${o?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function Vg(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as vd}from"node:fs";import{isatty as Ld}from"node:tty";import{format as Bd}from"node:util";var Zg=new Int32Array(new SharedArrayBuffer(4)),Qg=141;function Nd(e,t){let n=Buffer.from(t,"utf8"),o=0;while(o<n.length)try{o+=vd(e,n,o,n.length-o)}catch(s){let r=s.code;if(r==="EAGAIN"||r==="EWOULDBLOCK"){Atomics.wait(Zg,0,0,2);continue}if(r==="EPIPE")process.exit(Qg);if(e!==2)try{vd(2,`slack: cannot write output (${r??String(s)}); output is incomplete
327
- `)}catch{}process.exit(1)}}function Md(){if(!Ld(1))console.log=(...e)=>Nd(1,Bd(...e)+`
328
- `),console.info=console.log;if(!Ld(2))console.error=(...e)=>Nd(2,Bd(...e)+`
329
- `),console.warn=console.error}import{closeSync as jd,mkdirSync as em,openSync as Wd,readFileSync as Rn,statSync as Ud,unlinkSync as Co,writeFileSync as Jd}from"node:fs";import{homedir as tm}from"node:os";import{join as Kd}from"node:path";var ws="Pinlog · 最終更新";function zi(e){let t=new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Tokyo",hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).formatToParts(e),n=(s)=>t.find((r)=>r.type===s)?.value??"??",o=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${o}:${n("minute")} JST`}function nm(e){return`_${ws} ${zi(e)} · 更新はスレッドに_`}var Gi=new RegExp(`(^|\\n+)_?${ws} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function Pn(e){return Gi.test(e)}function bs(e){return e.replace(Gi,"")}function Yi(e,t){return`${bs(e).trimEnd()}
328
+ ${s}${r}${i}`}).join("")}var Bd=new Set(["send","ask","poll","vote","edit","delete","react","upload","schedule send","schedule rm","pinlog new","pinlog set","pinlog note","pinlog pin","todo set","todo flag","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"]),Qg={channels:"channel",ch:"channel"};function em(e){let[t="",n=""]=e.map(String),o=Qg[t]??t;return Bd.has(o)||Bd.has(`${o} ${n}`)}function tm(e,t){return String(e[0]??"")==="ask"&&t.ls===!0}function Ld(e,t,n){let o=n.botTokenSource;if(!o||n.globalPaths.includes(o))return null;if(n.slackTokenSet||n.activeTokenIsBot)return null;if(!em(e)||tm(e,t)||t["as-bot"]===!0)return null;let s=o==="shell"?"exported in the environment":`set in ${o}`,r="as-bot"in t;return[`Error: refusing to act as YOU — SLACK_BOT_TOKEN is ${s}, but \`${e.slice(0,2).join(" ")}\` would use your user session, not the bot.`,r?" 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(`
329
+ `)}function un(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function vt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function nm(e,t){let n=un(t),o=vt(e.profile);for(let r of[e.name,e.real_name,o.display_name,o.real_name])if(typeof r==="string"&&r&&un(r)===n)return!0;let s=typeof o.email==="string"?o.email.toLowerCase():"";return s!==""&&s===t.toLowerCase()}function sm(e){let t=vt(e.profile),n=new Set;for(let o of[t.display_name,e.real_name,e.name,t.real_name])if(typeof o==="string"&&o){let s=un(o);if(s.length>=2)n.add(s)}return[...n]}function om(e,t){let n=un(e),o,s=!1;for(let r of t){let i=typeof r.id==="string"?r.id:"";if(!i)continue;for(let a of sm(r)){let c=-1;if(n===a)c=e.length;else for(let l of Md)if(e.length>l.length&&e.endsWith(l)&&un(e.slice(0,e.length-l.length))===a){c=e.length-l.length;break}if(c<0)continue;if(!o||a.length>o.formLen)o={userId:i,matchLen:c,formLen:a.length,display:Yi(r)},s=!1;else if(a.length===o.formLen&&o.userId!==i)s=!0}}if(!o)return;return s?"ambiguous":{userId:o.userId,matchLen:o.matchLen,display:o.display}}async function Bt(e,t,n,o){let s=`[${jd}ー]+`,r=`${s}(?:[._-]+${s})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${r})`,"gu"),a=new Set;for(let D of t.matchAll(i))a.add(D[1]);if(a.size===0)return{text:t,resolved:[],unresolved:[]};let c=new Map;for(let D of a)c.set(D,{status:"pending"});let l=(D)=>{for(let k of a){if(c.get(k).status!=="pending")continue;if(Gi(k)){let S=om(k,D);if(S==="ambiguous")c.set(k,{status:"ambiguous"});else if(S)c.set(k,{status:"resolved",userId:S.userId,matchLen:S.matchLen,display:S.display})}else{let S=D.filter((F)=>nm(F,k)),C=new Set(S.map((F)=>typeof F.id==="string"?F.id:"").filter(Boolean));if(C.size===1){let F=S.find((A)=>typeof A.id==="string");c.set(k,{status:"resolved",userId:F.id,matchLen:k.length,display:Yi(F)})}else if(C.size>1)c.set(k,{status:"ambiguous"})}}},u=!1;try{let D=await eo(e,o);l((D.members??[]).map(vt)),u=!0}catch{u=!1}let d=[...a].some((D)=>c.get(D).status==="pending"),p=!1,h=!0;if(d&&n){p=!0;try{let D=await Hr(e,n,o),k=[];for(let S of D){let C=vt(await zr(e,S,o)),F=vt(C.user);if(typeof F.id!=="string")F.id=S;k.push(F)}l(k)}catch{h=!1}}let y=u&&(n?p&&h:!0),f=[],g=[];for(let D of a){let k=c.get(D);if(k.status==="resolved")f.push({surface:`@${D.slice(0,k.matchLen)}`,display:k.display,userId:k.userId});else if(k.status==="ambiguous")g.push({surface:`@${D}`,reason:"ambiguous"});else g.push({surface:`@${D}`,reason:y?"no-match":"unavailable"})}return{text:t.replace(i,(D,k)=>{let S=c.get(k);if(S&&S.status==="resolved")return`<@${S.userId}>${k.slice(S.matchLen)}`;return D}),resolved:f,unresolved:g}}function Fo(e){let t=[],n=!1;for(let o of e)if(o.reason==="ambiguous")t.push(`${o.surface} matches multiple people — not tagged, sent as plain text (use <@USERID> to tag)`);else if(o.reason==="unavailable"){if(n)continue;t.push("could not fetch the user list (users:read missing or an API/connection error) — @mentions not tagged, sent as plain text"),n=!0}else t.push(`${o.surface} matched no one — not tagged, sent as plain text`);return t}async function Nd(e,t,n,o={}){let s=o.warn??((i)=>process.stderr.write(`${i}
330
+ `)),r=await Bt(e,t,n,o.cookie);for(let i of Fo(r.unresolved))s(`warn: ${i}`);return r.text}var Md=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],jd="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function Gi(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function rm(e){let t=[],n=new RegExp(`([${jd}]{1,12})(${Md.join("|")})`,"gu");for(let o of e.matchAll(n))t.push({ref:o[1],honorific:o[2]});for(let o of e.matchAll(/\b(?:dear|hi|hello|hey)\b[ \t]+([A-Z][A-Za-z'’-]{1,20})/gi))t.push({ref:o[1],honorific:""});for(let o of e.matchAll(/(?:^|\n)[ \t]*([A-Z][A-Za-z'’-]{1,20}),/g))t.push({ref:o[1],honorific:""});return t}function im(e){let t=vt(e.profile),n=new Set;for(let o of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof o!=="string"||!o)continue;for(let s of[o,...o.split(/\s+/)]){let r=un(s);if(r.length>=2)n.add(r)}}return[...n]}function am(e,t){let n=un(e);if(n.length<2)return;for(let o of t)if(n===o)return o;if(Gi(e)){for(let o of t)if(n.includes(o)||o.includes(n))return o}return}function Yi(e){return[vt(e.profile).display_name,e.real_name,e.name].filter((o)=>typeof o==="string"&&o!=="")[0]??String(e.id??"?")}async function Wd(e,t,n){let o=rm(t);if(o.length===0)return[];let s=new Set;for(let l of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))s.add(l[1]);let i=((await eo(e,n)).members??[]).map(vt).filter((l)=>l.deleted!==!0&&l.is_bot!==!0&&l.id!=="USLACKBOT").map((l)=>({id:typeof l.id==="string"?l.id:"",forms:im(l),display:Yi(l)})).filter((l)=>l.id!==""),a=[],c=new Set;for(let{ref:l,honorific:u}of o)for(let d of i){let p=am(l,d.forms);if(!p)continue;if(s.has(d.id)||c.has(d.id))break;c.add(d.id),a.push({surface:Gi(l)?`${p}${u}`:l,display:d.display,userId:d.id});break}return a}async function dn(e,t,n,o){let s=t,r=[],i=s,a=0;while(!0){let c=i.indexOf("<@U",a);if(c===-1)break;let l=i.slice(c+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)r.push(d);a=c+1}for(let c of r){if(!n.has(c))n.set(c,await Qs(e,c,o));let l=n.get(c)??c;s=s.replaceAll(`<@${c}>`,`@${l}`),s=s.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${l}`)}return s}function On(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,o)=>{let s=Number(n);if(!Number.isFinite(s))return o??"date";let r=new Date(s*1000);if(Number.isNaN(r.getTime()))return o??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=i[r.getUTCDay()]??"",l=a[r.getUTCMonth()]??"";return`${c}, ${l} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function Ud(e,t=new Date){let n=new Date(e*1000),o=zi(t),s=zi(new Date(t.getTime()-86400000)),r=zi(n);if(r===o)return"Today";if(r===s)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 zi(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Ds(e){let t=new Date(e*1000),n=t.getFullYear(),o=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}`}var cm=/[A-Za-z0-9_-]{32,}/g;function bs(e){return e.replace(cm,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function Xi(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",o=!!t&&lm(t),s=o?t:n,r=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),a,c;try{let h=new Intl.DateTimeFormat("en-GB",{timeZone:s,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});c=h.format(e),a=Number(h.formatToParts(e).find((y)=>y.type==="hour")?.value??"12")}catch{return null}let l=r>i?a>=r||a<i:a>=r&&a<i,u=o?`${s}, recipient`:`${s}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${c} (${u})`;if(!l)return d;return`${d}
331
+ ⚠ QUIET HOURS (${r}:00-${i}:00) — this will buzz a phone.${o?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function lm(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as Jd}from"node:fs";import{isatty as Kd}from"node:tty";import{format as qd}from"node:util";var um=new Int32Array(new SharedArrayBuffer(4)),dm=141;function Hd(e,t){let n=Buffer.from(t,"utf8"),o=0;while(o<n.length)try{o+=Jd(e,n,o,n.length-o)}catch(s){let r=s.code;if(r==="EAGAIN"||r==="EWOULDBLOCK"){Atomics.wait(um,0,0,2);continue}if(r==="EPIPE")process.exit(dm);if(e!==2)try{Jd(2,`slack: cannot write output (${r??String(s)}); output is incomplete
332
+ `)}catch{}process.exit(1)}}function zd(){if(!Kd(1))console.log=(...e)=>Hd(1,qd(...e)+`
333
+ `),console.info=console.log;if(!Kd(2))console.error=(...e)=>Hd(2,qd(...e)+`
334
+ `),console.warn=console.error}import{closeSync as Gd,mkdirSync as fm,openSync as Yd,readFileSync as Rn,statSync as Xd,unlinkSync as Ao,writeFileSync as Vd}from"node:fs";import{homedir as pm}from"node:os";import{join as Zd}from"node:path";var xs="Pinlog · 最終更新";function Vi(e){let t=new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Tokyo",hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).formatToParts(e),n=(s)=>t.find((r)=>r.type===s)?.value??"??",o=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${o}:${n("minute")} JST`}function hm(e){return`_${xs} ${Vi(e)} · 更新はスレッドに_`}var Zi=new RegExp(`(^|\\n+)_?${xs} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function Pn(e){return Zi.test(e)}function Es(e){return e.replace(Zi,"")}function Qi(e,t){return`${Es(e).trimEnd()}
330
335
 
331
- ${nm(t)}`}function Xi(e){let n=e.match(Gi)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class Ds extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function sm(){return Kd(process.env.HOME||tm(),".config","slack-cli","locks")}function qd(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 om(e,t){let n=`${e}.break`,o=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
332
- `,s;try{s=Wd(n,"wx"),Jd(s,o)}catch(r){if(r.code!=="EEXIST")throw r;try{let i=Rn(n,"utf8");if((/^pid=\d+/.test(i)?!qd(i):Date.now()-Ud(n).mtimeMs>1e4)&&Rn(n,"utf8")===i)Co(n)}catch{}return}try{if(Rn(e,"utf8")===t)Co(e)}catch{}finally{jd(s);try{if(Rn(n,"utf8")===o)Co(n)}catch{}}}function Hd(e,t={}){let n=t.dir??sm(),o=t.staleMs??120000;em(n,{recursive:!0});let s=Kd(n,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.lock`),r=`pid=${process.pid} since=${new Date().toISOString()} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
333
- `;for(let i=0;i<3;i++)try{let a=Wd(s,"wx");Jd(a,r),jd(a);let c=!0,l=()=>{if(!c)return;c=!1;try{if(Rn(s,"utf8")===r)Co(s)}catch{}};return process.once("exit",l),l}catch(a){if(a.code!=="EEXIST")throw a;let c,l;try{c=Rn(s,"utf8"),l=Date.now()-Ud(s).mtimeMs}catch{continue}if(/^pid=\d+/.test(c)?!qd(c):l>o){om(s,c);continue}throw new Ds(c.trim().replace(/ nonce=\S+/,"")||"another process")}throw new Ds("another process")}function tt(e,t){return`${e}:${t}`}function _o(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}var lf=new Map,Vi=new Map,ea=[Nt(zd(),".slack-cli",".env.local"),Nt(zd(),".config/slack-cli",".env")];function $o(e){if(!rf(e))return;let t=af(e,"utf8");for(let n of t.split(`
334
- `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(ea.includes(e))Vi.set(r,[...Vi.get(r)??[],{path:e,val:i}]);if(!(r in process.env))process.env[r]=i,lf.set(r,e)}}function lm(e){im(e,{recursive:!0});let t=Nt(e,".gitignore");if(!rf(t))cf(t,`*
335
- `)}function um(){for(let e of ea)$o(e);$o(Nt(process.cwd(),".slack-cli",".env.local")),$o(Nt(process.cwd(),".env.local")),$o(Nt(process.cwd(),".env"))}function dm(e){return rm("sha256").update(e).digest("hex")}function _(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function H(e){return Array.isArray(e)?e:[]}function To(e){return Number(e.ts??0)}async function uf(e,t,n){let o=t.user;if(typeof o==="string"){if(!n.has(o))n.set(o,await Te(e,o));return n.get(o)??o}return typeof t.username==="string"?t.username:"bot"}function Zi(e){let t=new Date(e*1000),n=t.getUTCFullYear(),o=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),r=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),a=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}:${a}`}function Io(e){let[t,n="000000"]=e.split("."),o=Number(t),s=new Date(o*1000),r=s.getUTCFullYear(),i=String(s.getUTCMonth()+1).padStart(2,"0"),a=String(s.getUTCDate()).padStart(2,"0"),c=String(s.getUTCHours()).padStart(2,"0"),l=String(s.getUTCMinutes()).padStart(2,"0"),u=String(s.getUTCSeconds()).padStart(2,"0"),d=n.padEnd(6,"0").slice(0,6);return`${r}-${i}-${a}T${c}:${l}:${u}.${d}`}function ta(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 fm(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?ta(e):e}async function Lo(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:`${To(t)}.000000`,i=Io(r),a="?";if(typeof t.user==="string"){let k=t.user,x="@"+k;if(!n.has(x)){let C=await xd(e,k,async(I,A,M)=>(await ds(I,A,M))[1],s);n.set(x,C)}a=n.get(x)??k}else if(typeof t.username==="string")a=t.username;let c=typeof t.text==="string"?t.text:"",u=On(await un(e,c,n,s)).split(`
336
+ ${hm(t)}`}function ea(e){let n=e.match(Zi)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class ks extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function gm(){return Zd(process.env.HOME||pm(),".config","slack-cli","locks")}function Qd(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 mm(e,t){let n=`${e}.break`,o=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
337
+ `,s;try{s=Yd(n,"wx"),Vd(s,o)}catch(r){if(r.code!=="EEXIST")throw r;try{let i=Rn(n,"utf8");if((/^pid=\d+/.test(i)?!Qd(i):Date.now()-Xd(n).mtimeMs>1e4)&&Rn(n,"utf8")===i)Ao(n)}catch{}return}try{if(Rn(e,"utf8")===t)Ao(e)}catch{}finally{Gd(s);try{if(Rn(n,"utf8")===o)Ao(n)}catch{}}}function ef(e,t={}){let n=t.dir??gm(),o=t.staleMs??120000;fm(n,{recursive:!0});let s=Zd(n,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.lock`),r=`pid=${process.pid} since=${new Date().toISOString()} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
338
+ `;for(let i=0;i<3;i++)try{let a=Yd(s,"wx");Vd(a,r),Gd(a);let c=!0,l=()=>{if(!c)return;c=!1;try{if(Rn(s,"utf8")===r)Ao(s)}catch{}};return process.once("exit",l),l}catch(a){if(a.code!=="EEXIST")throw a;let c,l;try{c=Rn(s,"utf8"),l=Date.now()-Xd(s).mtimeMs}catch{continue}if(/^pid=\d+/.test(c)?!Qd(c):l>o){mm(s,c);continue}throw new ks(c.trim().replace(/ nonce=\S+/,"")||"another process")}throw new ks("another process")}function Ze(e,t){return`${e}:${t}`}function To(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}var yf=new Map,ta=new Map,ra=[Mt(tf(),".slack-cli",".env.local"),Mt(tf(),".config/slack-cli",".env")];function Io(e){if(!hf(e))return;let t=gf(e,"utf8");for(let n of t.split(`
339
+ `)){let o=n.trim();if(!o||o.startsWith("#"))continue;let s=o.indexOf("=");if(s===-1)continue;let r=o.slice(0,s).trim(),i=o.slice(s+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(ra.includes(e))ta.set(r,[...ta.get(r)??[],{path:e,val:i}]);if(!(r in process.env))process.env[r]=i,yf.set(r,e)}}function km(e){wm(e,{recursive:!0});let t=Mt(e,".gitignore");if(!hf(t))mf(t,`*
340
+ `)}function xm(){for(let e of ra)Io(e);Io(Mt(process.cwd(),".slack-cli",".env.local")),Io(Mt(process.cwd(),".env.local")),Io(Mt(process.cwd(),".env"))}function Em(e){return ym("sha256").update(e).digest("hex")}function T(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function H(e){return Array.isArray(e)?e:[]}function Po(e){return Number(e.ts??0)}async function wf(e,t,n){let o=t.user;if(typeof o==="string"){if(!n.has(o))n.set(o,await $e(e,o));return n.get(o)??o}return typeof t.username==="string"?t.username:"bot"}function na(e){let t=new Date(e*1000),n=t.getUTCFullYear(),o=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),r=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),a=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${o}-${s} ${r}:${i}:${a}`}function vo(e){let[t,n="000000"]=e.split("."),o=Number(t),s=new Date(o*1000),r=s.getUTCFullYear(),i=String(s.getUTCMonth()+1).padStart(2,"0"),a=String(s.getUTCDate()).padStart(2,"0"),c=String(s.getUTCHours()).padStart(2,"0"),l=String(s.getUTCMinutes()).padStart(2,"0"),u=String(s.getUTCSeconds()).padStart(2,"0"),d=n.padEnd(6,"0").slice(0,6);return`${r}-${i}-${a}T${c}:${l}:${u}.${d}`}function ia(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 Sm(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?ia(e):e}async function Mo(e,t,n,o,s){let r=typeof t.ts==="string"?t.ts:`${Po(t)}.000000`,i=vo(r),a="?";if(typeof t.user==="string"){let k=t.user,S="@"+k;if(!n.has(S)){let C=await Td(e,k,async(F,A,O)=>(await hs(F,A,O))[1],s);n.set(S,C)}a=n.get(S)??k}else if(typeof t.username==="string")a=t.username;let c=typeof t.text==="string"?t.text:"",u=On(await dn(e,c,n,s)).split(`
336
341
  `),d=u[0]+(u.length>1?`
337
342
  `+u.slice(1).map((k)=>` ${k}`).join(`
338
- `):""),f=o?`${o} @${a}`:`@${a}`,h=H(t.reactions).map(_).map((k)=>{let x=typeof k.name==="string"?k.name:"",C=Number(k.count??H(k.users).length??0);return x?`:${x}:\xD7${C}`:""}).filter(Boolean).join(" "),g=H(t.files).map(_).map((k)=>{let x=typeof k.name==="string"?k.name:typeof k.title==="string"?k.title:"(file)",C=typeof k.size==="number"?` (${Bo(k.size)})`:"",I=typeof k.id==="string"?` [${k.id}]`:"";return`
339
- \uD83D\uDCCE ${x}${C}${I}`}).join(""),p=Number(t.reply_count??0),m=p>0?` [+${p} ${p===1?"reply":"replies"}]`:"",D=await Promise.all(Ui(t).map(async(k)=>({...k,text:k.text?On(await un(e,k.text,n,s)):""}))),w=(h?`
340
- ${h}`:"")+g+$d(D,Io);return`${i} ${f}: ${d}${m}${w}`}function Bo(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function pm(e){return H(e.files).map(_).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 df(e){let t=pm(e),n=Ui(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:H(e.reactions).map(_).map((o)=>({name:o.name??null,count:o.count??null,users:Array.isArray(o.users)?o.users:[]}))}:{},...e.reply_count!==void 0?{reply_count:e.reply_count}:{},...e.reply_users_count!==void 0?{reply_users_count:e.reply_users_count}:{},...e.latest_reply!==void 0?{latest_reply:e.latest_reply}:{},...t.length>0?{files:t}:{},...n.length>0?{attachments:n}:{}}}async function hm(e,t,n,o,s){let r=[];for(let i of n){let a=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let c=await Ie(e,t,i.ts,200,s),l=H(c.messages).map(_);a=l[l.length-1]??i}if(a.user!==o)r.push(i)}return r}async function gm(e,t,n,o="text",s=!1,r){let i=Rt(t),a=await ye(e,t,r),c=new Map,u=await(async()=>{if(i?.threadTs){let f=await Ie(e,a,i.threadTs,n,r);return H(f.messages).map(_)}let d=await je(e,a,n,void 0,void 0,r);return H(d.messages).map(_).reverse()})();if(s){let{userId:d}=await Ii(e,r);u=await hm(e,a,u,d,r)}if(o==="jsonl"){for(let d of u)console.log(JSON.stringify(df(d)));return}for(let d of u)console.log(await Lo(e,d,c,void 0,r))}async function mm(e,t,n,o,s="text",r){let i=await ye(e,t,r),a=await Ie(e,i,fm(n),o,r),c=H(a.messages).map(_);if(s==="jsonl"){for(let u of c)console.log(JSON.stringify(df(u)));return}let l=new Map;for(let u of c)console.log(await Lo(e,u,l,void 0,r))}async function ym(e){let t=await us(e),n=H(t.channels).map(_).filter((s)=>s.is_member===!0).sort((s,r)=>Number(r.updated??0)-Number(s.updated??0)).slice(0,10),o=new Map;for(let s of n){let r=String(s.id??""),i=typeof s.name==="string"?s.name:typeof s.user==="string"?s.user:r,a=await je(e,r,5),c=H(a.messages).map(_).filter((l)=>l.subtype===void 0||l.subtype===null).filter((l)=>{let u=typeof l.text==="string"?l.text:"";return u.length>0&&!u.startsWith("<@")}).slice(0,3).reverse();if(c.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let l of c){let u=await uf(e,l,o),d=(typeof l.text==="string"?l.text:"").split(`
341
- `)[0]??"",f=await un(e,d,o);console.log(` ${u}: ${f}`)}}}async function Dm(e,t){let n=await Bu(e,"to:me"),o=H(ls(n,["messages","matches"])).map(_).slice(0,t),s=new Map,r=[];for(let i of o){let a=Pd(To(i)),c=r[r.length-1];if(c?.label===a)c.msgs.push(i);else r.push({label:a,msgs:[i]})}for(let i=0;i<r.length;i++){let{label:a,msgs:c}=r[i];if(i>0)console.log("");console.log(` ${a}`),console.log(" ----------------------------");for(let l of[...c].reverse()){let u=_(l.channel),d=u.is_im===!0,f=typeof u.name==="string"?u.name:"dm",h;if(d&&f.startsWith("U")){let g="@"+f;if(!s.has(g)){let[,p]=await ds(e,f);s.set(g,p)}h=`@${s.get(g)??f}`}else if(d)h=`@${f}`;else h=`#${f}`;console.log(await Lo(e,l,s,h))}}}async function wm(e,t,n,o,s="text",r){let i=await us(e,r),a=H(i.channels).map(_).filter((c)=>o||c.is_member===!0).filter((c)=>{if(!n)return!0;return(typeof c.name==="string"?c.name:"").toLowerCase().includes(n.toLowerCase())}).sort((c,l)=>Number(l.updated??0)-Number(c.updated??0)).slice(0,t);if(s==="jsonl"){for(let c of a)console.log(JSON.stringify(c));return}for(let c of a){let l=String(c.id??""),u=typeof c.name==="string"?c.name:typeof c.user==="string"?c.user:l,d=c.is_im===!0,f=c.is_mpim===!0,h=d||f?"@":"#",g=c.is_member===!0?"":" (not joined)",p=typeof _(c.purpose).value==="string"?String(_(c.purpose).value):"",m=p?` ${p.split(`
342
- `)[0]?.slice(0,60)}`:"";console.log(`${h}${u} ${l}${g}${m}`)}}function bm(e){let t=(s)=>s.startsWith("xoxp-")||s.startsWith("xoxc-"),n=_r(),o=n.find((s)=>s.profile.token===e);if(!o)return;return n.find((s)=>t(s.profile.token)&&s.profile.teamId===o.profile.teamId)}async function ff(e,t,n,o,s){let r=e,i=s,a;try{a=await Ri(r,t,n,i)}catch(u){let d=u instanceof Error?u.message:String(u);if(e.startsWith("xoxb-")&&d.includes("not_allowed_token_type")){let f=bm(e);if(f)console.error(`Note: search.messages needs a user token \u2014 the active profile is a bot token (xoxb-); falling back to profile "${f.name}".`),r=f.profile.token,i=f.profile.cookie,a=await Ri(r,t,n,i);else console.error(`Error: search requires a user token (xoxp-/xoxc-) \u2014 the active profile is a bot token (xoxb-), which Slack rejects for search.messages.
343
+ `):""),p=o?`${o} @${a}`:`@${a}`,h=H(t.reactions).map(T).map((k)=>{let S=typeof k.name==="string"?k.name:"",C=Number(k.count??H(k.users).length??0);return S?`:${S}:\xD7${C}`:""}).filter(Boolean).join(" "),y=H(t.files).map(T).map((k)=>{let S=typeof k.name==="string"?k.name:typeof k.title==="string"?k.title:"(file)",C=typeof k.size==="number"?` (${jo(k.size)})`:"",F=typeof k.id==="string"?` [${k.id}]`:"";return`
344
+ \uD83D\uDCCE ${S}${C}${F}`}).join(""),f=Number(t.reply_count??0),g=f>0?` [+${f} ${f===1?"reply":"replies"}]`:"",w=await Promise.all(Hi(t).map(async(k)=>({...k,text:k.text?On(await dn(e,k.text,n,s)):""}))),D=(h?`
345
+ ${h}`:"")+y+vd(w,vo);return`${i} ${p}: ${d}${g}${D}`}function jo(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function Cm(e){return H(e.files).map(T).map((t)=>({id:t.id??null,name:t.name??t.title??null,mimetype:t.mimetype??null,size:t.size??null,url_private_download:t.url_private_download??t.url_private??null,permalink:t.permalink??null}))}function Df(e){let t=Cm(e),n=Hi(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:H(e.reactions).map(T).map((o)=>({name:o.name??null,count:o.count??null,users:Array.isArray(o.users)?o.users:[]}))}:{},...e.reply_count!==void 0?{reply_count:e.reply_count}:{},...e.reply_users_count!==void 0?{reply_users_count:e.reply_users_count}:{},...e.latest_reply!==void 0?{latest_reply:e.latest_reply}:{},...t.length>0?{files:t}:{},...n.length>0?{attachments:n}:{}}}async function _m(e,t,n,o,s){let r=[];for(let i of n){let a=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let c=await Pe(e,t,i.ts,200,s),l=H(c.messages).map(T);a=l[l.length-1]??i}if(a.user!==o)r.push(i)}return r}async function $m(e,t,n,o="text",s=!1,r){let i=Rt(t),a=await fe(e,t,r),c=new Map,u=await(async()=>{if(i?.threadTs){let p=await Pe(e,a,i.threadTs,n,r);return H(p.messages).map(T)}let d=await He(e,a,n,void 0,void 0,r);return H(d.messages).map(T).reverse()})();if(s){let{userId:d}=await vi(e,r);u=await _m(e,a,u,d,r)}if(o==="jsonl"){for(let d of u)console.log(JSON.stringify(Df(d)));return}for(let d of u)console.log(await Mo(e,d,c,void 0,r))}async function Fm(e,t,n,o,s="text",r){let i=await fe(e,t,r),a=await Pe(e,i,Sm(n),o,r),c=H(a.messages).map(T);if(s==="jsonl"){for(let u of c)console.log(JSON.stringify(Df(u)));return}let l=new Map;for(let u of c)console.log(await Mo(e,u,l,void 0,r))}async function Am(e){let t=await ps(e),n=H(t.channels).map(T).filter((s)=>s.is_member===!0).sort((s,r)=>Number(r.updated??0)-Number(s.updated??0)).slice(0,10),o=new Map;for(let s of n){let r=String(s.id??""),i=typeof s.name==="string"?s.name:typeof s.user==="string"?s.user:r,a=await He(e,r,5),c=H(a.messages).map(T).filter((l)=>l.subtype===void 0||l.subtype===null).filter((l)=>{let u=typeof l.text==="string"?l.text:"";return u.length>0&&!u.startsWith("<@")}).slice(0,3).reverse();if(c.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let l of c){let u=await wf(e,l,o),d=(typeof l.text==="string"?l.text:"").split(`
346
+ `)[0]??"",p=await dn(e,d,o);console.log(` ${u}: ${p}`)}}}async function Tm(e,t){let n=await qu(e,"to:me"),o=H(fs(n,["messages","matches"])).map(T).slice(0,t),s=new Map,r=[];for(let i of o){let a=Ud(Po(i)),c=r[r.length-1];if(c?.label===a)c.msgs.push(i);else r.push({label:a,msgs:[i]})}for(let i=0;i<r.length;i++){let{label:a,msgs:c}=r[i];if(i>0)console.log("");console.log(` ${a}`),console.log(" ----------------------------");for(let l of[...c].reverse()){let u=T(l.channel),d=u.is_im===!0,p=typeof u.name==="string"?u.name:"dm",h;if(d&&p.startsWith("U")){let y="@"+p;if(!s.has(y)){let[,f]=await hs(e,p);s.set(y,f)}h=`@${s.get(y)??p}`}else if(d)h=`@${p}`;else h=`#${p}`;console.log(await Mo(e,l,s,h))}}}async function Im(e,t,n,o,s="text",r){let i=await ps(e,r),a=H(i.channels).map(T).filter((c)=>o||c.is_member===!0).filter((c)=>{if(!n)return!0;return(typeof c.name==="string"?c.name:"").toLowerCase().includes(n.toLowerCase())}).sort((c,l)=>Number(l.updated??0)-Number(c.updated??0)).slice(0,t);if(s==="jsonl"){for(let c of a)console.log(JSON.stringify(c));return}for(let c of a){let l=String(c.id??""),u=typeof c.name==="string"?c.name:typeof c.user==="string"?c.user:l,d=c.is_im===!0,p=c.is_mpim===!0,h=d||p?"@":"#",y=c.is_member===!0?"":" (not joined)",f=typeof T(c.purpose).value==="string"?String(T(c.purpose).value):"",g=f?` ${f.split(`
347
+ `)[0]?.slice(0,60)}`:"";console.log(`${h}${u} ${l}${y}${g}`)}}function Om(e){let t=(s)=>s.startsWith("xoxp-")||s.startsWith("xoxc-"),n=Tr(),o=n.find((s)=>s.profile.token===e);if(!o)return;return n.find((s)=>t(s.profile.token)&&s.profile.teamId===o.profile.teamId)}async function bf(e,t,n,o,s){let r=e,i=s,a;try{a=await Li(r,t,n,i)}catch(u){let d=u instanceof Error?u.message:String(u);if(e.startsWith("xoxb-")&&d.includes("not_allowed_token_type")){let p=Om(e);if(p)console.error(`Note: search.messages needs a user token \u2014 the active profile is a bot token (xoxb-); falling back to profile "${p.name}".`),r=p.profile.token,i=p.profile.cookie,a=await Li(r,t,n,i);else console.error(`Error: search requires a user token (xoxp-/xoxc-) \u2014 the active profile is a bot token (xoxb-), which Slack rejects for search.messages.
343
348
  `+` Add a user-token profile: slack auth login (or slack auth login --token <token>)
344
- Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw u}if(o){console.log(JSON.stringify(a,null,2));return}let c=H(ls(a,["messages","matches"])).map(_),l=new Map;for(let u of c){let d=_(u.channel),f=d.is_im===!0,h=typeof d.name==="string"?d.name:"dm",g;if(f&&h.startsWith("U")){let p="@"+h;if(!l.has(p)){let[,m]=await ds(r,h,i);l.set(p,m)}g=`@${l.get(p)??h}`}else if(f)g=`@${h}`;else g=`#${h}`;console.log(await Lo(r,u,l,g,i))}}async function pf(e,t,n,o){let{ref:s,ts:r}=jt(t);if(!r)console.error("Error: target must embed a message ts (e.g. #chan:1700000000.000100 or a Slack permalink URL)"),process.exit(2);return{channelId:n??await Mi(e,s,ye,o),ts:r}}async function km(e,t){let n=gs(),o={};if(!t.mine)o.shared=!0;if(t.in)o.in=t.in;if(t.from)o.from=t.from;let s=wd(t.state,n,o);if(!t.json){let r=await Ue(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${Mo(r)} \xB7 matching ${i})`),console.error(`(query: ${s})`)}await We("search.messages",()=>ff(e,s,t.count,t.json,t.cookie))}async function xm(e,t){let n=gs(),{channelId:o,ts:s}=await pf(e,t.target,t.channelId,t.cookie),r=await Sd(e,o,s,t.state,n,t.cookie);if(r.noop){console.log(`= Already ${t.state} (ts: ${s})`);return}let i=r.removed.length?`, removed ${r.removed.map((a)=>`:${a}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${s})${i}`),r.leftover.length)console.error(`\u26A0 ${r.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 Em(e,t){let n=gs(),{channelId:o,ts:s}=await pf(e,t.target,t.channelId,t.cookie),r=await Cd(e,o,s,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${r}: (ts: ${s})`)}async function Sm(e,t){let n=gs(),o=t.channelId??await Mi(e,t.channel,ye,t.cookie),s={limit:t.limit};if(t.fix)s.fix=!0;if(t.cookie)s.cookie=t.cookie;let r=await _d(e,o,n,s);if(r.findings.length===0)console.log(`\u2713 No multi-state tasks in ${r.scanned} message(s).`);else{for(let i of r.findings){let 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}] ${v(i.text).slice(0,60)}`)}console.log(`${r.findings.length} multi-state task(s) in ${r.scanned} message(s).`)}if(r.truncated)console.error(`\u26A0 Scan limit reached (${t.limit} messages) \u2014 older history was NOT checked. Raise it with --limit N.`)}async function Cm(e,t,n,o){let s=Math.floor(Date.now()/1000)-t*86400,r=await us(e),i=H(r.channels).map(_).filter((u)=>u.is_member===!0&&u.is_im!==!0&&u.is_mpim!==!0).filter((u)=>{if(!o)return!0;return(typeof u.name==="string"?u.name:"").toLowerCase().includes(o.toLowerCase())}).sort((u,d)=>Number(d.updated??0)-Number(u.updated??0)),a=new Map,c=0,l=0;for(let u of i){let d=String(u.id??""),f=typeof u.name==="string"?u.name:d,h;try{h=await je(e,d,n)}catch(p){console.error(` SKIP #${f}: ${p.message}`);continue}let g=H(h.messages).map(_).filter((p)=>(p.subtype===void 0||p.subtype===null)&&To(p)>=s);if(g.length===0)continue;l+=1,c+=g.length,console.log(`## #${f} (${g.length} msgs)
345
- `);for(let p of[...g].reverse()){let m=await uf(e,p,a),D=typeof p.text==="string"?p.text:"",k=On(await un(e,D,a)).split(`
346
- `).join(" \u21B5 ");console.log(`[${So(To(p))}] ${m}: ${k}`)}console.log("")}console.error(`Dumped ${c} messages across ${l} channels (cutoff: ${t}d)`)}function _m(e){let t=[];function n(o){if(typeof o==="string"){t.push(o);return}if(Array.isArray(o)){for(let s of o)n(s);return}if(o&&typeof o==="object"){let s=o;if(typeof s.text==="string"){t.push(s.text);return}if(s.type==="link"&&typeof s.url==="string"){t.push(s.url);return}if(Array.isArray(s.elements))n(s.elements);else if(Array.isArray(s.content))n(s.content)}}for(let o of e)n(o);return t.join("").trim()}async function na(e,t,n){let o=new Map;return async(s)=>{if(!s)return"(unknown)";if(o.has(s))return o.get(s);try{let r=await sd(e,s,t),i=_(r.channel),a;if(i.is_im===!0){let c=typeof i.user==="string"?i.user:"";if(!c||c===n)a="@self";else{let[l]=await ds(e,c);a=`@${l}`}}else a=`#${typeof i.name==="string"?i.name:s}`;return o.set(s,a),a}catch{return s}}}function sa(e){let t=_(H(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function Oo(e){return _m(H(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function $m(e,t,n=!1){let o=await fs(e,t),s=H(o.drafts??o.messages??[]).map(_).filter((l)=>l.is_deleted!==!0),r=n?s:s.filter((l)=>l.is_sent!==!0);if(r.length===0){console.log(n?"No drafts.":"No pending drafts. Run with --all to include sent.");return}let i="";try{({userId:i}=await vi(e,t))}catch{}let a=await na(e,t,i),c=new Map;for(let l of r){let u=sa(l),d=Oo(l),f=Number(l.date_created??l.date_create??0),h=f?Zi(f):"?",g=await a(u),p=typeof l.id==="string"?l.id:"",m=l.is_sent===!0?" [SENT]":"",D=On(await un(e,d,c));console.log(`-- ${p} ${g} [${h}]${m}`);for(let w of D.split(`
347
- `))console.log(` ${w}`)}}async function Fm(e,t,n){let o=[],s;do{let u=_(await ed(e,{filter:n.filter,limit:Math.min(n.limit,100),cursor:s},t));o.push(...ld(u));let d=_(u.response_metadata).next_cursor;s=typeof d==="string"&&d?d:void 0}while(s&&o.length<n.limit);let r=ud(o).slice(0,n.limit);if(r.length===0){(n.json?console.error:console.log)(`No ${n.filter==="todo"?"to-dos":`${n.filter} items`}.`);return}let i="",a="";try{({url:i,userId:a}=await $n(e,t))}catch{}let c=await na(e,t,a),l=Date.now()/1000;for(let u of r){let d;if(u.channel&&u.ts)try{let D=_(await Ie(e,u.channel,u.ts,1,t));d=H(D.messages).map(_).find((w)=>w.ts===u.ts)}catch{}let f=u.channel&&u.ts?i?fd(i,u.channel,u.ts):`${u.channel}:${u.ts}`:"";if(n.json){console.log(JSON.stringify({...u,done:Do(u),permalink:f,user:d?.user??null,text:d?.text??null}));continue}let h=u.channel?await c(u.channel):`(${u.itemType||"item"})`,g=typeof d?.user==="string"?`@${await Te(e,d.user,t)}: `:"",p=typeof d?.text==="string"?d.text.split(`
348
- `)[0]??"":"(message not readable)",m=p.length>100?`${p.slice(0,100)}\u2026`:p;if(console.log(`${dd(u,l,So)} ${v(h)}`),console.log(` ${v(g+m)}`),f)console.log(` ${f}`)}}async function Am(e,t,n){let o=await fs(e,t),s=H(o.drafts).map(_).find((g)=>String(g.id)===n);if(!s)console.error(`Draft not found: ${n}`),process.exit(1);let r="";try{({userId:r}=await vi(e,t))}catch{}let i=await na(e,t,r),a=sa(s),c=Oo(s),l=Number(s.date_created??0),u=String(s.last_updated_ts??"?"),d=await i(a),h=On(await un(e,c,new Map));console.log(`id: ${s.id}`),console.log(`channel: ${d} (${a})`),console.log(`created: ${l?Zi(l):"?"}`),console.log(`updated: ${Zi(Number(u.split(".")[0]))}`),console.log(`status: ${s.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(h)}function ge(...e){return dm(e.join(`
349
- `)).slice(0,4)}function v(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var Tm={"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 de(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,o,s]=n;switch(s){case"missing_scope":return`Error: token lacks the ${Tm[o]??"the required"} scope (needed for ${o}). Add it to your Slack App's User Token Scopes (or Bot Token Scopes if you use a bot token / --as-bot) \u2014 it must be on the token type the CLI actually uses \u2014 then reinstall to the workspace.`;case"invalid_name":return"Error: not a valid emoji shortcode \u2014 use the name without colons (e.g. white_check_mark), and make sure it exists in the workspace.";case"already_reacted":return"Error: you've already added that reaction to the message.";case"no_reaction":return"Error: that reaction isn't on the message \u2014 nothing to remove.";case"message_not_found":return"Error: no message found at that timestamp in the channel \u2014 check the target ts/permalink.";case"channel_not_found":return"Error: channel not found \u2014 check the target.";default:return t}}async function No(e,t,n){if(!t.startsWith("D"))return null;try{let o=await jo(e,t,n);if(!o)return null;return await Ed(e,o,ps,n)}catch{return null}}function De(e,t,n,o,s=new Date){for(let i of n)console.log(i);let r=Hi(s,o);if(r)console.log(r);if(e!==void 0)console.error(`Code mismatch (got ${e}, expected ${t})`);console.error(`Rerun with --code=${t}`),process.exit(1)}function jt(e){let t=Rt(e);if(t)return t.ts?{ref:t.channel,ts:t.ts}:{ref:t.channel};if(e.startsWith("#")||e.startsWith("@")){let n=e.indexOf(":");if(n>0){let o=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(o))return{ref:e.slice(0,n),ts:o};if(/^\d{4}-\d{2}-\d{2}T/.test(o))return{ref:e.slice(0,n),ts:ta(o)}}}return{ref:e}}function vn(e,t=!0){let n=Rt(e);if(n){if(!t)return{ref:n.channel};let s=n.threadTs??n.ts;return s?{ref:n.channel,threadTs:s}:{ref:n.channel}}let o=e.indexOf(":");if(o>0){let s=e.slice(o+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,o),threadTs:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,o),threadTs:ta(s)}}return{ref:e}}async function Mt(e,t,n,o){let s=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=_(await cn(e,t,o)),a=_(i.channel);if(a.is_im===!0){let c=typeof a.user==="string"?a.user:"";s=c?`@${await Te(e,c,o)}`:t}else s=typeof a.name==="string"?`#${a.name}`:t}catch{s=t}return s===t?t:`${s} (${t})`}async function Ue(e,t){try{return await $n(e,t)}catch{return null}}function bt(e,t){let n;return async()=>{if(n===void 0)n=await Ue(e,t);return n}}function pn(e){if(!Ci())return{record:()=>{}};let t=xu();return{metadata:Eu(e,t),record:(n)=>{Cu({...n,kind:e,attribution:t})}}}function Im(e){let t=v(e.text.split(`
350
- `)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,o=[e.cli??"?",e.session_id?`session=${e.session_id}`:"",e.agent_pid?`pid=${e.agent_pid}`:`pid=${e.pid}`,e.git_branch?`branch=${e.git_branch}`:"",`cwd=${e.cwd}`].filter(Boolean).join(" ");return`${So(e.sent_at/1000)} ${e.kind.padEnd(4)} ${v(e.target??e.channel)} ${n}
349
+ Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw u}if(o){console.log(JSON.stringify(a,null,2));return}let c=H(fs(a,["messages","matches"])).map(T),l=new Map;for(let u of c){let d=T(u.channel),p=d.is_im===!0,h=typeof d.name==="string"?d.name:"dm",y;if(p&&h.startsWith("U")){let f="@"+h;if(!l.has(f)){let[,g]=await hs(r,h,i);l.set(f,g)}y=`@${l.get(f)??h}`}else if(p)y=`@${h}`;else y=`#${h}`;console.log(await Mo(r,u,l,y,i))}}async function kf(e,t,n,o){let{ref:s,ts:r}=Wt(t);if(!r)console.error("Error: target must embed a message ts (e.g. #chan:1700000000.000100 or a Slack permalink URL)"),process.exit(2);return{channelId:n??await Ji(e,s,fe,o),ts:r}}async function Rm(e,t){let n=ws(),o={};if(!t.mine)o.shared=!0;if(t.in)o.in=t.in;if(t.from)o.from=t.from;let s=$d(t.state,n,o);if(!t.json){let r=await Te(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${Uo(r)} \xB7 matching ${i})`),console.error(`(query: ${s})`)}await Ne("search.messages",()=>bf(e,s,t.count,t.json,t.cookie))}async function Pm(e,t){let n=ws(),{channelId:o,ts:s}=await kf(e,t.target,t.channelId,t.cookie),r=await Od(e,o,s,t.state,n,t.cookie);if(r.noop){console.log(`= Already ${t.state} (ts: ${s})`);return}let i=r.removed.length?`, removed ${r.removed.map((a)=>`:${a}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${s})${i}`),r.leftover.length)console.error(`\u26A0 ${r.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 vm(e,t){let n=ws(),{channelId:o,ts:s}=await kf(e,t.target,t.channelId,t.cookie),r=await Rd(e,o,s,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${r}: (ts: ${s})`)}async function Bm(e,t){let n=ws(),o=t.channelId??await Ji(e,t.channel,fe,t.cookie),s={limit:t.limit};if(t.fix)s.fix=!0;if(t.cookie)s.cookie=t.cookie;let r=await Pd(e,o,n,s);if(r.findings.length===0)console.log(`\u2713 No multi-state tasks in ${r.scanned} message(s).`);else{for(let i of r.findings){let 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}] ${v(i.text).slice(0,60)}`)}console.log(`${r.findings.length} multi-state task(s) in ${r.scanned} message(s).`)}if(r.truncated)console.error(`\u26A0 Scan limit reached (${t.limit} messages) \u2014 older history was NOT checked. Raise it with --limit N.`)}async function Lm(e,t,n,o){let s=Math.floor(Date.now()/1000)-t*86400,r=await ps(e),i=H(r.channels).map(T).filter((u)=>u.is_member===!0&&u.is_im!==!0&&u.is_mpim!==!0).filter((u)=>{if(!o)return!0;return(typeof u.name==="string"?u.name:"").toLowerCase().includes(o.toLowerCase())}).sort((u,d)=>Number(d.updated??0)-Number(u.updated??0)),a=new Map,c=0,l=0;for(let u of i){let d=String(u.id??""),p=typeof u.name==="string"?u.name:d,h;try{h=await He(e,d,n)}catch(f){console.error(` SKIP #${p}: ${f.message}`);continue}let y=H(h.messages).map(T).filter((f)=>(f.subtype===void 0||f.subtype===null)&&Po(f)>=s);if(y.length===0)continue;l+=1,c+=y.length,console.log(`## #${p} (${y.length} msgs)
350
+ `);for(let f of[...y].reverse()){let g=await wf(e,f,a),w=typeof f.text==="string"?f.text:"",k=On(await dn(e,w,a)).split(`
351
+ `).join(" \u21B5 ");console.log(`[${Ds(Po(f))}] ${g}: ${k}`)}console.log("")}console.error(`Dumped ${c} messages across ${l} channels (cutoff: ${t}d)`)}function Nm(e){let t=[];function n(o){if(typeof o==="string"){t.push(o);return}if(Array.isArray(o)){for(let s of o)n(s);return}if(o&&typeof o==="object"){let s=o;if(typeof s.text==="string"){t.push(s.text);return}if(s.type==="link"&&typeof s.url==="string"){t.push(s.url);return}if(Array.isArray(s.elements))n(s.elements);else if(Array.isArray(s.content))n(s.content)}}for(let o of e)n(o);return t.join("").trim()}async function aa(e,t,n){let o=new Map;return async(s)=>{if(!s)return"(unknown)";if(o.has(s))return o.get(s);try{let r=await dd(e,s,t),i=T(r.channel),a;if(i.is_im===!0){let c=typeof i.user==="string"?i.user:"";if(!c||c===n)a="@self";else{let[l]=await hs(e,c);a=`@${l}`}}else a=`#${typeof i.name==="string"?i.name:s}`;return o.set(s,a),a}catch{return s}}}function ca(e){let t=T(H(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function Bo(e){return Nm(H(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function Mm(e,t,n=!1){let o=await gs(e,t),s=H(o.drafts??o.messages??[]).map(T).filter((l)=>l.is_deleted!==!0),r=n?s:s.filter((l)=>l.is_sent!==!0);if(r.length===0){console.log(n?"No drafts.":"No pending drafts. Run with --all to include sent.");return}let i="";try{({userId:i}=await Mi(e,t))}catch{}let a=await aa(e,t,i),c=new Map;for(let l of r){let u=ca(l),d=Bo(l),p=Number(l.date_created??l.date_create??0),h=p?na(p):"?",y=await a(u),f=typeof l.id==="string"?l.id:"",g=l.is_sent===!0?" [SENT]":"",w=On(await dn(e,d,c));console.log(`-- ${f} ${y} [${h}]${g}`);for(let D of w.split(`
352
+ `))console.log(` ${D}`)}}async function jm(e,t,n){let o=[],s;do{let u=T(await cd(e,{filter:n.filter,limit:Math.min(n.limit,100),cursor:s},t));o.push(...yd(u));let d=T(u.response_metadata).next_cursor;s=typeof d==="string"&&d?d:void 0}while(s&&o.length<n.limit);let r=wd(o).slice(0,n.limit);if(r.length===0){(n.json?console.error:console.log)(`No ${n.filter==="todo"?"to-dos":`${n.filter} items`}.`);return}let i="",a="";try{({url:i,userId:a}=await $n(e,t))}catch{}let c=await aa(e,t,a),l=Date.now()/1000;for(let u of r){let d;if(u.channel&&u.ts)try{let w=T(await Pe(e,u.channel,u.ts,1,t));d=H(w.messages).map(T).find((D)=>D.ts===u.ts)}catch{}let p=u.channel&&u.ts?i?bd(i,u.channel,u.ts):`${u.channel}:${u.ts}`:"";if(n.json){console.log(JSON.stringify({...u,done:xo(u),permalink:p,user:d?.user??null,text:d?.text??null}));continue}let h=u.channel?await c(u.channel):`(${u.itemType||"item"})`,y=typeof d?.user==="string"?`@${await $e(e,d.user,t)}: `:"",f=typeof d?.text==="string"?d.text.split(`
353
+ `)[0]??"":"(message not readable)",g=f.length>100?`${f.slice(0,100)}\u2026`:f;if(console.log(`${Dd(u,l,Ds)} ${v(h)}`),console.log(` ${v(y+g)}`),p)console.log(` ${p}`)}}async function Wm(e,t,n){let o=await gs(e,t),s=H(o.drafts).map(T).find((y)=>String(y.id)===n);if(!s)console.error(`Draft not found: ${n}`),process.exit(1);let r="";try{({userId:r}=await Mi(e,t))}catch{}let i=await aa(e,t,r),a=ca(s),c=Bo(s),l=Number(s.date_created??0),u=String(s.last_updated_ts??"?"),d=await i(a),h=On(await dn(e,c,new Map));console.log(`id: ${s.id}`),console.log(`channel: ${d} (${a})`),console.log(`created: ${l?na(l):"?"}`),console.log(`updated: ${na(Number(u.split(".")[0]))}`),console.log(`status: ${s.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(h)}function ue(...e){return Em(e.join(`
354
+ `)).slice(0,4)}function v(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var Um={"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 ie(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,o,s]=n;switch(s){case"missing_scope":return`Error: token lacks the ${Um[o]??"the required"} scope (needed for ${o}). Add it to your Slack App's User Token Scopes (or Bot Token Scopes if you use a bot token / --as-bot) \u2014 it must be on the token type the CLI actually uses \u2014 then reinstall to the workspace.`;case"invalid_name":return"Error: not a valid emoji shortcode \u2014 use the name without colons (e.g. white_check_mark), and make sure it exists in the workspace.";case"already_reacted":return"Error: you've already added that reaction to the message.";case"no_reaction":return"Error: that reaction isn't on the message \u2014 nothing to remove.";case"message_not_found":return"Error: no message found at that timestamp in the channel \u2014 check the target ts/permalink.";case"channel_not_found":return"Error: channel not found \u2014 check the target.";default:return t}}async function Wo(e,t,n){if(!t.startsWith("D"))return null;try{let o=await Jo(e,t,n);if(!o)return null;return await Id(e,o,ms,n)}catch{return null}}function pe(e,t,n,o,s=new Date){for(let i of n)console.log(i);let r=Xi(s,o);if(r)console.log(r);if(e!==void 0)console.error(`Code mismatch (got ${e}, expected ${t})`);console.error(`Rerun with --code=${t}`),process.exit(1)}function Wt(e){let t=Rt(e);if(t)return t.ts?{ref:t.channel,ts:t.ts}:{ref:t.channel};if(e.startsWith("#")||e.startsWith("@")){let n=e.indexOf(":");if(n>0){let o=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(o))return{ref:e.slice(0,n),ts:o};if(/^\d{4}-\d{2}-\d{2}T/.test(o))return{ref:e.slice(0,n),ts:ia(o)}}}return{ref:e}}function Bn(e,t=!0){let n=Rt(e);if(n){if(!t)return{ref:n.channel};let s=n.threadTs??n.ts;return s?{ref:n.channel,threadTs:s}:{ref:n.channel}}let o=e.indexOf(":");if(o>0){let s=e.slice(o+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,o),threadTs:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,o),threadTs:ia(s)}}return{ref:e}}async function jt(e,t,n,o){let s=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=T(await ln(e,t,o)),a=T(i.channel);if(a.is_im===!0){let c=typeof a.user==="string"?a.user:"";s=c?`@${await $e(e,c,o)}`:t}else s=typeof a.name==="string"?`#${a.name}`:t}catch{s=t}return s===t?t:`${s} (${t})`}async function Te(e,t){try{return await $n(e,t)}catch{return null}}function bt(e,t){let n;return async()=>{if(n===void 0)n=await Te(e,t);return n}}function pn(e){if(!Do())return{record:()=>{}};let t=$u();return{metadata:Fu(e,t),record:(n)=>{Au({...n,kind:e,attribution:t})}}}function Jm(e){let t=v(e.text.split(`
355
+ `)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,o=[e.cli??"?",e.session_id?`session=${e.session_id}`:"",e.agent_pid?`pid=${e.agent_pid}`:`pid=${e.pid}`,e.git_branch?`branch=${e.git_branch}`:"",`cwd=${e.cwd}`].filter(Boolean).join(" ");return`${Ds(e.sent_at/1000)} ${e.kind.padEnd(4)} ${v(e.target??e.channel)} ${n}
351
356
  ${t}
352
- ${v(o)}`}function Mo(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let o=v(e.user||e.userId||"?"),s=e.userId?` (${e.userId})`:"",r=e.team?` \u2014 ${v(e.team)}`:"";return`@${o}${s}${r}${n}`}function we(e,t={}){return` ${"From:".padEnd(t.pad??6)}${Mo(e,t.asBot)}`}async function Qi(e,t,n=60,o){let s=typeof t.user==="string"?await Te(e,t.user,o):typeof t.username==="string"?t.username:"?",r=ys((typeof t.text==="string"?t.text:"").split(`
353
- `)[0]??""),i=r.length>n?`${r.slice(0,n)}\u2026`:r,a=typeof t.ts==="string"?t.ts:"";return`${a?Io(a).slice(0,16).replace("T"," "):""} @${s}${i?`: ${i}`:""}`}async function Om(e,t,n,o){let s=n.find((r)=>String(r.ts)===t)??n[0];if(!s)return t;return Qi(e,s,40,o)}function Gd(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Rm(e,t){let n=Gd(e),o=Gd(t);if(!n||!o)return 0;if(n===o)return 1;let s=(l)=>{let u=new Map;for(let d=0;d<l.length-1;d++){let f=l.slice(d,d+2);u.set(f,(u.get(f)??0)+1)}return u},r=s(n),i=s(o);if(r.size===0||i.size===0)return 0;let a=0;for(let[l,u]of r){let d=i.get(l);if(d)a+=Math.min(u,d)}let c=Yd(r)+Yd(i);return c===0?0:2*a/c}function Yd(e){let t=0;for(let n of e.values())t+=n;return t}async function Xd(e,t,n,o){let s=ze();if(!s)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
354
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(o)return{botToken:s};let{ref:r}=jt(e);if(!r.startsWith("@"))return{botToken:s};try{let i=await wt(t,r,n);return{botToken:s,channelId:await Dt(s,i)}}catch(i){console.error(`Error: could not resolve ${v(r)} to the bot's DM.
357
+ ${v(o)}`}function Uo(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let o=v(e.user||e.userId||"?"),s=e.userId?` (${e.userId})`:"",r=e.team?` \u2014 ${v(e.team)}`:"";return`@${o}${s}${r}${n}`}function he(e,t={}){return` ${"From:".padEnd(t.pad??6)}${Uo(e,t.asBot)}`}async function sa(e,t,n=60,o){let s=typeof t.user==="string"?await $e(e,t.user,o):typeof t.username==="string"?t.username:"?",r=bs((typeof t.text==="string"?t.text:"").split(`
358
+ `)[0]??""),i=r.length>n?`${r.slice(0,n)}\u2026`:r,a=typeof t.ts==="string"?t.ts:"";return`${a?vo(a).slice(0,16).replace("T"," "):""} @${s}${i?`: ${i}`:""}`}async function Km(e,t,n,o){let s=n.find((r)=>String(r.ts)===t)??n[0];if(!s)return t;return sa(e,s,40,o)}function nf(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function qm(e,t){let n=nf(e),o=nf(t);if(!n||!o)return 0;if(n===o)return 1;let s=(l)=>{let u=new Map;for(let d=0;d<l.length-1;d++){let p=l.slice(d,d+2);u.set(p,(u.get(p)??0)+1)}return u},r=s(n),i=s(o);if(r.size===0||i.size===0)return 0;let a=0;for(let[l,u]of r){let d=i.get(l);if(d)a+=Math.min(u,d)}let c=sf(r)+sf(i);return c===0?0:2*a/c}function sf(e){let t=0;for(let n of e.values())t+=n;return t}async function of(e,t,n,o){let s=Je();if(!s)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
359
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(o)return{botToken:s};let{ref:r}=Wt(e);if(!r.startsWith("@"))return{botToken:s};try{let i=await Dt(t,r,n);return{botToken:s,channelId:await wt(s,i)}}catch(i){console.error(`Error: could not resolve ${v(r)} to the bot's DM.
355
360
  ${i instanceof Error?i.message:String(i)}
356
- `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function Pm(e,t){let n=bt(e,t.cookie),{ref:o,ts:s}=jt(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await ye(e,o,t.cookie);let i=await Ie(e,r,s,1,t.cookie),c=H(i.messages).map(_).find((I)=>String(I.ts)===s);if(!c)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof c.text==="string"?c.text:"",u=t.mentionCookie??t.cookie,d=t.mentions?await Td(t.mentionToken??e,t.newText,r,u?{cookie:u}:{}):t.newText;Ne(d,t.allowUrlAdjacent);let f=gt(l).kind,h=gt(d).kind,g=cs(l).kind!=="other",p=g?cs(d).kind==="other":f!=="other"&&(h==="other"||f!=="open"&&h==="open");if(p&&!t.force)console.error(`Error: this message is ${g?"a `slack poll`":`a \`slack ask\` question (${f==="open"?"open":f==="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"}.
357
- `+(g?" Edit it anyway with --force.":` To retire it: slack ask --void='${t.target}' --reason '\u2026'
358
- Edit it anyway with --force.`)),process.exit(1);let m=p,D=await n(),w=m?ge("force-edit-ask-poll",l,d,D?.userId??""):ge(l,d,D?.userId??"");if(t.code!==w)De(t.code,w,[...m?[`\u26A0 --force: rewriting a \`slack ${g?"poll":"ask"}\` message by hand \u2014 collect may no longer read it back`]:[],"--- Editing as -------------------------------",we(D,{asBot:t.asBot}),"--- Original message -------------------------",...l.split(`
359
- `).map((I)=>` ${I}`),"--- Replacing with ---------------------------",...d.split(`
360
- `).map((I)=>` ${I}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let k=pn("edit"),x=f!=="other"||h!=="other"||g||cs(d).kind!=="other",C=await yt(e,r,s,d,t.cookie,x?!0:void 0,k.metadata);console.log(`\u2713 Edited (ts: ${C})`),k.record({team:D?.team,channel:r,target:t.target,ts:s,text:d,asBot:t.asBot})}async function vm(e,t){let n=bt(e,t.cookie),{ref:o,ts:s}=jt(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await ye(e,o,t.cookie);let i=await Ie(e,r,s,1,t.cookie),c=H(i.messages).map(_).find((f)=>String(f.ts)===s);if(!c)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof c.text==="string"?c.text:"",u=await n(),d=ge(r,s,l,u?.userId??"");if(t.code!==d){let f=await Mt(e,r,o,t.cookie);De(t.code,d,["--- Deleting message -------------------------",we(u,{asBot:t.asBot}),` \u2192 ${f} at ${Io(s)}`,...l.split(`
361
- `).map((h)=>` ${h}`),"---------------------------------------------"])}await Uu(e,r,s,t.cookie),console.log(`\u2713 Deleted (ts: ${s})`)}function Bt(e){return`'${e.replace(/'/g,"'\\''")}'`}async function oa(e,t,n){let o=_o(t);if(o)return{...o,ref:o.channel};let{ref:s,ts:r}=jt(t);if(!r)console.error(`Error: ${v(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 ${Bt(t)}`),process.exit(2);return{channel:await ye(e,s,n),ts:r,ref:s}}async function Lm(e,t,n,o){let s=_(await Ie(e,t,n,1,o)),r=H(s.messages).map(_).find((i)=>String(i.ts)===n);if(!r)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return r}function Fo(e,t){if(t!==void 0)try{return af(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:Oe(e)}var Vd=40000;function Ro(e,t){if(t.length>Vd)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${Vd}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function Po(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof mt)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function hf(e,t){let n=Hi(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function Bm(e,t){let{ref:n,ts:o}=jt(t.target);if(o||_o(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 ${Bt(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(Ne(t.state,t.allowUrlAdjacent),t.log!==void 0)Ne(t.log,t.allowUrlAdjacent),Ro("reason",t.log);let s=`${t.workspace?` -w ${Bt(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,r=bt(e,t.cookie),i=await ye(e,n,t.cookie),a=await r(),c=ge("pinlog-create",i,t.state,t.log??"",a?.userId??""),l=new Date,u=Yi(t.state,l);if(Ro("HEAD (state + footer)",u),t.code!==c){let p=await Mt(e,i,n,t.cookie),m=(await gf(e,i,200,t.cookie)).found;De(t.code,c,["--- New pinlog -------------------------------",we(a,{asBot:t.asBot}),` \u2192 ${p} \u2014 NEW top-level message, then pinned`,...m.length?[`\u26A0 ${m.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...m.slice(0,5).map((D)=>` ${tt(i,String(D.ts))} ${mf(String(D.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...u.split(`
362
- `).map((D)=>` ${v(D)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
363
- `).map((D)=>` ${v(D)}`)]:[],"---------------------------------------------"])}let d=pn("send"),f;try{f=await rn(e,i,u,void 0,!1,t.cookie,!0,d.metadata)}catch(p){if(Po(p))console.error(`\u2717 HEAD was NOT posted: ${de(p)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${de(p)}
364
- Check before retrying, or you will have two boards: slack pinlog ls ${Bt(t.target)}${s}`);process.exit(1)}if(!f)console.error("\u2717 Slack accepted the post but returned no ts \u2014 check the channel before retrying, it may have landed."),process.exit(1);d.record({team:a?.team,channel:i,target:t.target,ts:f,text:u,asBot:t.asBot});let h=tt(i,f);console.log(`\u2713 Posted HEAD: ${h}`);let g=hf(l,"this new top-level post notified everyone who follows the channel");if(g)console.error(g);try{await Pi(e,i,f,t.cookie),console.log("\u2713 Pinned")}catch(p){let m=p instanceof Error?p.message:String(p),D=/missing_scope/.test(m)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:de(p);console.error(`\u26A0 NOT pinned: ${D}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${h}${s}`)}if(t.log)try{let p=await rn(e,i,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${p})`)}catch(p){let m=ge("pinlog-log",i,f,t.log,a?.userId??"");console.error(`${Po(p)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${de(p)}
361
+ `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function Hm(e,t){let n=bt(e,t.cookie),{ref:o,ts:s}=Wt(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await fe(e,o,t.cookie);let i=await Pe(e,r,s,1,t.cookie),c=H(i.messages).map(T).find((F)=>String(F.ts)===s);if(!c)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof c.text==="string"?c.text:"",u=t.mentionCookie??t.cookie,d=t.mentions?await Nd(t.mentionToken??e,t.newText,r,u?{cookie:u}:{}):t.newText;Be(d,t.allowUrlAdjacent);let p=gt(l).kind,h=gt(d).kind,y=us(l).kind!=="other",f=y?us(d).kind==="other":p!=="other"&&(h==="other"||p!=="open"&&h==="open");if(f&&!t.force)console.error(`Error: this message is ${y?"a `slack poll`":`a \`slack ask\` question (${p==="open"?"open":p==="resolved"?"answered":"void"})`}, and ${y||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"}.
362
+ `+(y?" Edit it anyway with --force.":` To retire it: slack ask --void='${t.target}' --reason '\u2026'
363
+ Edit it anyway with --force.`)),process.exit(1);let g=f,w=await n(),D=g?ue("force-edit-ask-poll",l,d,w?.userId??""):ue(l,d,w?.userId??"");if(t.code!==D)pe(t.code,D,[...g?[`\u26A0 --force: rewriting a \`slack ${y?"poll":"ask"}\` message by hand \u2014 collect may no longer read it back`]:[],"--- Editing as -------------------------------",he(w,{asBot:t.asBot}),"--- Original message -------------------------",...l.split(`
364
+ `).map((F)=>` ${F}`),"--- Replacing with ---------------------------",...d.split(`
365
+ `).map((F)=>` ${F}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let k=pn("edit"),S=p!=="other"||h!=="other"||y||us(d).kind!=="other",C=await yt(e,r,s,d,t.cookie,S?!0:void 0,k.metadata);console.log(`\u2713 Edited (ts: ${C})`),k.record({team:w?.team,channel:r,target:t.target,ts:s,text:d,asBot:t.asBot})}async function zm(e,t){let n=bt(e,t.cookie),{ref:o,ts:s}=Wt(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let r;if(t.channelId)r=t.channelId;else r=await fe(e,o,t.cookie);let i=await Pe(e,r,s,1,t.cookie),c=H(i.messages).map(T).find((p)=>String(p.ts)===s);if(!c)console.error(`Message not found at ts=${s} in channel ${r}`),process.exit(1);let l=typeof c.text==="string"?c.text:"",u=await n(),d=ue(r,s,l,u?.userId??"");if(t.code!==d){let p=await jt(e,r,o,t.cookie);pe(t.code,d,["--- Deleting message -------------------------",he(u,{asBot:t.asBot}),` \u2192 ${p} at ${vo(s)}`,...l.split(`
366
+ `).map((h)=>` ${h}`),"---------------------------------------------"])}await Xu(e,r,s,t.cookie),console.log(`\u2713 Deleted (ts: ${s})`)}function Nt(e){return`'${e.replace(/'/g,"'\\''")}'`}async function la(e,t,n){let o=To(t);if(o)return{...o,ref:o.channel};let{ref:s,ts:r}=Wt(t);if(!r)console.error(`Error: ${v(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 ${Nt(t)}`),process.exit(2);return{channel:await fe(e,s,n),ts:r,ref:s}}async function Gm(e,t,n,o){let s=T(await Pe(e,t,n,1,o)),r=H(s.messages).map(T).find((i)=>String(i.ts)===n);if(!r)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return r}function Oo(e,t){if(t!==void 0)try{return gf(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:Fe(e)}var rf=40000;function Lo(e,t){if(t.length>rf)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${rf}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function No(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof mt)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function xf(e,t){let n=Xi(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function Ym(e,t){let{ref:n,ts:o}=Wt(t.target);if(o||To(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 ${Nt(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(Be(t.state,t.allowUrlAdjacent),t.log!==void 0)Be(t.log,t.allowUrlAdjacent),Lo("reason",t.log);let s=`${t.workspace?` -w ${Nt(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,r=bt(e,t.cookie),i=await fe(e,n,t.cookie),a=await r(),c=ue("pinlog-create",i,t.state,t.log??"",a?.userId??""),l=new Date,u=Qi(t.state,l);if(Lo("HEAD (state + footer)",u),t.code!==c){let f=await jt(e,i,n,t.cookie),g=(await Ef(e,i,200,t.cookie)).found;pe(t.code,c,["--- New pinlog -------------------------------",he(a,{asBot:t.asBot}),` \u2192 ${f} \u2014 NEW top-level message, then pinned`,...g.length?[`\u26A0 ${g.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...g.slice(0,5).map((w)=>` ${Ze(i,String(w.ts))} ${Sf(String(w.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...u.split(`
367
+ `).map((w)=>` ${v(w)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
368
+ `).map((w)=>` ${v(w)}`)]:[],"---------------------------------------------"])}let d=pn("send"),p;try{p=await an(e,i,u,void 0,!1,t.cookie,!0,d.metadata)}catch(f){if(No(f))console.error(`\u2717 HEAD was NOT posted: ${ie(f)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${ie(f)}
369
+ Check before retrying, or you will have two boards: slack pinlog ls ${Nt(t.target)}${s}`);process.exit(1)}if(!p)console.error("\u2717 Slack accepted the post but returned no ts \u2014 check the channel before retrying, it may have landed."),process.exit(1);d.record({team:a?.team,channel:i,target:t.target,ts:p,text:u,asBot:t.asBot});let h=Ze(i,p);console.log(`\u2713 Posted HEAD: ${h}`);let y=xf(l,"this new top-level post notified everyone who follows the channel");if(y)console.error(y);try{await Ni(e,i,p,t.cookie),console.log("\u2713 Pinned")}catch(f){let g=f instanceof Error?f.message:String(f),w=/missing_scope/.test(g)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:ie(f);console.error(`\u26A0 NOT pinned: ${w}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${h}${s}`)}if(t.log)try{let f=await an(e,i,t.log,p,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${f})`)}catch(f){let g=ue("pinlog-log",i,p,t.log,a?.userId??"");console.error(`${No(f)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${ie(f)}
365
370
  The board IS posted. Retry just the reason (check the thread first):
366
- slack pinlog note ${h} ${Bt(Tn(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${s} --code=${m}`),process.exit(1)}}async function Zd(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(Ne(t.log,t.allowUrlAdjacent),t.state!==void 0)Ne(t.state,t.allowUrlAdjacent);Ro("log line",t.log);let n=bt(e,t.cookie),{channel:o,ts:s,ref:r}=await oa(e,t.target,t.cookie);try{Hd(`pinlog-${o}-${s}`)}catch(D){if(!(D instanceof Ds))throw D;console.error(`Error: another update of ${tt(o,s)} is running (${D.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await Lm(e,o,s,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(!Pn(a)&&!t.adopt)console.error(`Error: the message at ${tt(o,s)} is not a pinlog HEAD (no "${ws}" footer).
367
- `+" 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(),l=tt(o,s),u=new Date,d=`${t.workspace?` -w ${Bt(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=ge("pinlog-log",o,s,t.log,c?.userId??""),h=`slack pinlog note ${l} ${Bt(Tn(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,g=hf(u,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==f){let D=await Mt(e,o,r,t.cookie);De(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",we(c,{asBot:t.asBot}),` \u2192 ${D}, thread of ${l}`,...t.log.split(`
368
- `).map((w)=>` ${v(w)}`),"---------------------------------------------"])}}else{let D=Yi(t.state,u);Ro("new HEAD (state + footer)",D);let w=!Pn(a),k=ge("pinlog-update",o,s,a,t.state,t.log,c?.userId??"");if(t.code!==k){let C=await Mt(e,o,r,t.cookie),I=bs(a).trim()===bs(t.state).trim();De(t.code,k,["--- Updating pinlog --------------------------",we(c,{asBot:t.asBot}),` \u2192 ${C}, ${l}`,"--- Current HEAD -----------------------------",...a.split(`
369
- `).map((A)=>` ${v(A)}`),"--- New HEAD (edited in place \u2014 silent) ------",...D.split(`
371
+ slack pinlog note ${h} ${Nt(Tn(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${s} --code=${g}`),process.exit(1)}}async function af(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(Be(t.log,t.allowUrlAdjacent),t.state!==void 0)Be(t.state,t.allowUrlAdjacent);Lo("log line",t.log);let n=bt(e,t.cookie),{channel:o,ts:s,ref:r}=await la(e,t.target,t.cookie);try{ef(`pinlog-${o}-${s}`)}catch(w){if(!(w instanceof ks))throw w;console.error(`Error: another update of ${Ze(o,s)} is running (${w.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await Gm(e,o,s,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(!Pn(a)&&!t.adopt)console.error(`Error: the message at ${Ze(o,s)} is not a pinlog HEAD (no "${xs}" footer).
372
+ `+" 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(),l=Ze(o,s),u=new Date,d=`${t.workspace?` -w ${Nt(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,p=ue("pinlog-log",o,s,t.log,c?.userId??""),h=`slack pinlog note ${l} ${Nt(Tn(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${p}`,y=xf(u,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==p){let w=await jt(e,o,r,t.cookie);pe(t.code,p,["--- Pinlog log reply (HEAD unchanged) --------",he(c,{asBot:t.asBot}),` \u2192 ${w}, thread of ${l}`,...t.log.split(`
373
+ `).map((D)=>` ${v(D)}`),"---------------------------------------------"])}}else{let w=Qi(t.state,u);Lo("new HEAD (state + footer)",w);let D=!Pn(a),k=ue("pinlog-update",o,s,a,t.state,t.log,c?.userId??"");if(t.code!==k){let C=await jt(e,o,r,t.cookie),F=Es(a).trim()===Es(t.state).trim();pe(t.code,k,["--- Updating pinlog --------------------------",he(c,{asBot:t.asBot}),` \u2192 ${C}, ${l}`,"--- Current HEAD -----------------------------",...a.split(`
374
+ `).map((A)=>` ${v(A)}`),"--- New HEAD (edited in place \u2014 silent) ------",...w.split(`
370
375
  `).map((A)=>` ${v(A)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
371
- `).map((A)=>` ${v(A)}`),"---------------------------------------------",...I?["\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 x=pn("edit");try{await yt(e,o,s,D,t.cookie,!0,x.metadata)}catch(C){let I=C instanceof Error?C.message:String(C),A=/cant_update_message/.test(I)?`
372
- Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",M=Po(C)?`\u2717 HEAD was NOT updated: ${de(C)}${A}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${de(C)}
373
- Check it first: slack pinlog get ${l}${d}`;console.error(`${M}
374
- The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}x.record({team:c?.team,channel:o,target:t.target,ts:s,text:D,asBot:t.asBot}),console.log(`\u2713 HEAD updated: ${l}`)}let p=pn("send"),m;try{m=await rn(e,o,t.log,s,!1,t.cookie,!0,p.metadata)}catch(D){let w=Po(D);console.error((w?`\u2717 Log reply was NOT posted: ${de(D)}
375
- `:`\u26A0 UNKNOWN whether the log reply was posted: ${de(D)}
376
- `)+(t.logOnly?"":` The HEAD IS updated \u2014 only the log line ${w?"is":"may be"} missing.
377
- `)+(w?"":` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${l}${d}
378
- `)+` Retry just the log line${w?"":" (only if it is not there)"}:
379
- ${h}`),process.exit(1)}if(p.record({team:c?.team,channel:o,target:t.target,ts:m,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${m})`),g)console.error(g)}function Qd(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Nm(e){return zi(new Date(Number(e.split(".")[0])*1000))}async function Mm(e,t,n,o){if(typeof t.user==="string"){let r=n.get(t.user);if(r!==void 0)return r;let i;try{i=await Te(e,t.user,o)}catch{i=t.user}return n.set(t.user,i),i}let s=_(t.bot_profile);if(typeof s.name==="string")return s.name;return typeof t.username==="string"?t.username:"bot"}async function jm(e,t,n,o){let{channel:s,ts:r}=await oa(e,t,n),i=[],a,c=0;do{let p=_(await Ju(e,s,r,a,200,n));for(let D of H(p.messages).map(_)){if(String(D.ts)===r&&i.some((w)=>String(w.ts)===r))continue;i.push(D)}let m=_(p.response_metadata).next_cursor;a=typeof m==="string"&&m?m:void 0,c++}while(a&&c<50);let l=a===void 0,u=i.find((p)=>String(p.ts)===r);if(!u)console.error(`Error: no message at ts=${r} in ${s}.`),process.exit(1);let d=typeof u.text==="string"?u.text:"",f=i.filter((p)=>String(p.ts)!==r);if(o){console.log(JSON.stringify({id:tt(s,r),isPinlog:Pn(d),updated:Xi(d),complete:l,head:d,log:f.map((p)=>({ts:String(p.ts),user:p.user??null,text:typeof p.text==="string"?p.text:""}))}));return}if(!Pn(d))console.error(`\u26A0 ${tt(s,r)} has no "${ws}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${tt(s,r)} ===`);for(let p of Qd(d).split(`
380
- `))console.log(v(p));let h=l?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${f.length}${h}) ===`);let g=new Map;for(let p of f){let m=typeof p.text==="string"?p.text:"",D=v(await Mm(e,p,g,n)),w=Qd(m).split(`
381
- `).map((k)=>v(k));console.log(`${Nm(String(p.ts))} @${D}: ${w[0]??""}`);for(let k of w.slice(1))console.log(` ${k}`)}}async function gf(e,t,n,o){let s=0,r,i=[];do{let a=_(await je(e,t,Math.min(200,n-s),void 0,r,o)),c=H(a.messages).map(_);s+=c.length;for(let u of c)if(typeof u.text==="string"&&Pn(u.text))i.push(u);let l=_(a.response_metadata).next_cursor;r=typeof l==="string"&&l?l:void 0}while(r&&s<n);return{found:i,scanned:s}}function mf(e){return v(bs(e).split(`
382
- `).find((t)=>t.trim())??"").slice(0,80)}async function Wm(e,t,n,o){let{ref:s,ts:r}=jt(t);if(r||_o(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${Bt(t)}`),process.exit(2);let i=await ye(e,s,o),{found:a,scanned:c}=await gf(e,i,n,o),l=await Mt(e,i,s,o);if(a.length===0){console.log(`No pinlogs in the last ${c} messages of ${l}.${c>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let u of a){let d=String(u.ts),f=tt(i,d),h=String(u.text),g=H(u.pinned_to).some((D)=>D===i)?"\uD83D\uDCCC":" ",p=mf(h),m=typeof u.reply_count==="number"?u.reply_count:0;console.log(`${g} ${f} updated ${Xi(h)??"?"} log ${m}`),console.log(` ${p}`)}}async function Um(e,t,n){let{channel:o,ts:s}=await oa(e,t,n);try{await Pi(e,o,s,n),console.log(`\u2713 Pinned ${tt(o,s)}`)}catch(r){let i=r instanceof Error?r.message:String(r);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${tt(o,s)}`);return}console.error(`\u2717 NOT pinned: ${de(r)}`),process.exit(1)}}async function Jm(e,t){let{ref:n,ts:o}=jt(t.target);if(!o)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let s=t.emoji.replace(/^:|:$/g,""),r;if(t.channelId)r=t.channelId;else r=await ye(e,n,t.cookie);if(t.remove)await an(e,r,o,s,t.cookie),console.log(`\u2713 Removed :${s}: (ts: ${o})`);else await Ot(e,r,o,s,t.cookie),console.log(`\u2713 Reacted :${s}: (ts: ${o})`)}async function ra(e,t,n,o){if(!n||!t.startsWith("D"))return!1;try{let s=_(await cn(e,t,o)),r=_(s.channel);return r.is_im===!0&&r.user===n}catch{return!1}}function Km(e){let t=new Set;for(let n of e){if(typeof n.user==="string")t.add(n.user);if(typeof n.parent_user_id==="string")t.add(n.parent_user_id);for(let o of H(n.reply_users))if(typeof o==="string")t.add(o)}return t}async function qm(e,t,n){if(!t.startsWith("D"))return;try{let o=_(_(await cn(e,t,n)).channel);return o.is_im===!0&&typeof o.user==="string"?o.user:void 0}catch{return}}async function Hm(e,t){let{ref:n,threadTs:o}=vn(t.target),s=t.cookie,r=bt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Dt(e,t.userId,s);else i=await ye(e,n,s);if(!t.asBot&&await ra(e,i,(await r())?.userId,s))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
383
- `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let a=Oe(t.message);Ne(a,t.allowUrlAdjacent);let c=a,l=null;if(t.mentions){l=await Lt(t.mentionToken??e,a,i,t.mentionCookie),c=l.text;for(let A of ms(l.unresolved))console.error(`\u26A0 ${v(A)}`)}let u=[];if(l&&(l.resolved.length>0||l.unresolved.length>0)){u.push("--- Mentions ---------------------------------");for(let A of l.resolved)u.push(` \u2713 ${v(A.surface)} \u2192 @${v(A.display)} (${A.userId}) \u2014 will notify`);for(let A of l.unresolved){let M=A.reason==="ambiguous"?"ambiguous":A.reason==="unavailable"?"lookup unavailable":"no match";u.push(` \u26A0 ${v(A.surface)} \u2014 plain text, NOT notified (${M})`)}}let d="",f="?",h=[],g,p,m;if(o)try{let A=await Ie(e,i,o,100,s);h=H(A.messages).map(_);let M=h[h.length-1];d=typeof M?.text==="string"?M.text:"",g=typeof M?.user==="string"?M.user:void 0,p=typeof M?.bot_id==="string"?M.bot_id:void 0,m=typeof M?.ts==="string"?M.ts:void 0}catch{}else try{let A=await je(e,i,1,void 0,void 0,s),M=H(A.messages).map(_),X=M.filter((L)=>L.subtype===void 0||L.subtype===null)[0];d=typeof X?.text==="string"?X.text:"",f=typeof X?.user==="string"?await Te(e,X.user,s):typeof X?.username==="string"?X.username:"?";let re=M[0];g=typeof re?.user==="string"?re.user:void 0,p=typeof re?.bot_id==="string"?re.bot_id:void 0,m=typeof re?.ts==="string"?re.ts:void 0}catch{}try{let A=o?Km(h):new Set([await qm(e,i,s)].filter((M)=>!!M));for(let M of await Rd(t.mentionToken??e,c,t.mentionCookie)){if(A.has(M.userId))continue;console.error(`\u26A0 possible untagged mention: ${v(M.surface)} \u2014 @${v(M.display)} won't be notified (did you mean <@${M.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&m&&(g||p))try{let A=await r();if(!!A&&(!!g&&!!A.userId&&A.userId===g||!!p&&!!A.botId&&A.botId===p)){let X=`slack edit "#${i}:${m}" "<\u65B0\u3057\u3044\u672C\u6587>" --channel-id ${i}`;try{let re=await Fn(e,i,m,s);if(re)X=`slack edit "${re}" "<\u65B0\u3057\u3044\u672C\u6587>"`}catch{}console.error("\u26A0 \u76F8\u624B\u306F\u307E\u3060\u8FD4\u4FE1\u3057\u3066\u3044\u307E\u305B\u3093(\u6700\u5F8C\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u3042\u306A\u305F\u306E\u3082\u306E\u3067\u3059)\u3002"),console.error(" \u9023\u6295\u3092\u907F\u3051\u308B\u305F\u3081\u3001\u65B0\u898F\u9001\u4FE1\u3067\u306A\u304F\u76F4\u524D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306E edit \u3092\u691C\u8A0E\u3057\u3066\u304F\u3060\u3055\u3044:"),console.error(` ${X}`),console.error(" \u3053\u306E\u307E\u307E\u9001\u4FE1\u3059\u308B\u5834\u5408\u306F --code=XXXX \u3067\u78BA\u5B9A\u3002")}}catch{}if(o&&h.length){let A={sim:0,msg:null};for(let M of h){let X=typeof M.text==="string"?M.text:"";if(!X)continue;let re=Rm(c,X);if(re>A.sim)A={sim:re,msg:M}}if(A.msg&&A.sim>=0.82){let M=Math.round(A.sim*100);console.error(`\u26A0 possible duplicate: ${M}% similar to an existing thread message \u2014 ${await Qi(e,A.msg,60,s)}`)}}let D=await r(),w=await No(e,i,s),k=ge(i,o??"",d,c,D?.userId??"");if(t.code!==k){let A=await Mt(e,i,n,s),M=we(D,{asBot:t.asBot});if(o){let X=await Om(e,o,h,s),re=h.slice(-3),L=re.length?await Promise.all(re.map(async(T)=>` ${await Qi(e,T,60,s)}`)):[" (thread context unavailable)"];De(t.code,k,["--- Recent messages in thread ----------------",...L,...u,"--- Sending ----------------------------------",M,` \u2192 ${A} thread of ${X} \u2014 THREAD REPLY`,` Message: ${c}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}else De(t.code,k,["--- Last message in channel ------------------",` ${f}: ${ys(d.split(`
384
- `)[0]??"").slice(0,100)}`,...u,"--- Sending ----------------------------------",M,` \u2192 ${A} \u2014 NEW top-level message`,` Message: ${c}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}let x=pn("send"),C=await rn(e,i,c,o,t.broadcast,s,void 0,x.metadata),I="";try{I=await Fn(e,i,C,s)}catch{}if(x.record({team:(await r())?.team,channel:i,target:t.target,ts:C,threadTs:o,permalink:I,text:c,asBot:t.asBot}),I)console.log(`\u2713 Sent: ${I}`);else console.log(`\u2713 Sent (ts: ${C})`);if(t.asBot&&i.startsWith("D"))try{let A=await Qs(e);if(!A.ok)for(let M of eo(A,!0))console.error(M);else{let M=A.appId?`https://api.slack.com/apps/${A.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${M} \u2192 App Home.`)}}catch{}}var zm=2,oe=3,Gm=4,Ym=5,yf=6,Xm=1.618033988749895,Vm=1000,Zm=5000,ef=8,Qm=(e)=>new Promise((t)=>setTimeout(t,e)),Df=new Set(["thread_broadcast"]),ey=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function xs(e){let t=new Set;return{text:e.replace(ey,(o,s)=>{let r=s.toLowerCase();return t.add(r),`<!${r}>`}),kinds:t}}async function jo(e,t,n){if(!t.startsWith("D"))return;try{let o=_(await cn(e,t,n)),s=_(o.channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function wf(e,t,n,o){let s=new Map;if(t.threadParentTs||t.replyCount!==0)try{let a=_(await Ie(e,t.channelId,t.threadParentTs??t.ts,100,t.cookie));for(let c of H(a.messages).map(_))s.set(String(c.ts),c)}catch(a){console.error(` (\u30B9\u30EC\u30C3\u30C9\u306E\u8FFD\u8A18\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${a instanceof Error?a.message:String(a)})`)}if(!t.threadOnly&&!t.threadParentTs)try{let a=_(await je(e,t.channelId,30,t.ts,void 0,t.cookie,!0)),c=H(a.messages).map(_),l=c.filter((u)=>Number(u.ts)>Number(t.ts)&&(t.askerBotId&&u.bot_id===t.askerBotId||t.askerUserId&&u.user===t.askerUserId)).reduce((u,d)=>Math.min(u,Number(d.ts)),1/0);for(let u of c)if(Number(u.ts)<l&&!s.has(String(u.ts)))s.set(String(u.ts),u)}catch(a){console.error(` (DM \u306E\u8FFD\u8A18\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${a instanceof Error?a.message:String(a)})`)}let r=[...s.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"||Df.has(a.subtype)).filter((a)=>typeof a.text==="string"&&a.text.trim()!=="").sort((a,c)=>Number(a.ts)-Number(c.ts)).filter((a)=>!o(a)),i=[];for(let a of r){let c="";try{c=await Fn(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 dn(...e){return e.filter((t)=>!!t).reduce((t,n)=>!t||Number(n)>Number(t)?n:t,"")}async function fn(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}:{},notes:n.notes,cursor:n.cursor,permalink:t.shown}));return}if(n.notes.length){console.error(` \u30B9\u30EC\u30C3\u30C9\u306E\u8FFD\u8A18 ${n.notes.length} \u4EF6 (\u56DE\u7B54\u3068\u306F\u5225):`);for(let o of n.notes){let s=o.user;try{s=await Te(e,o.user,t.cookie)}catch{}for(let[r,i]of o.text.split(`
385
- `).entries())console.error(` ${r?" ".repeat(v(s).length+2):`${v(s)}: `}${v(i)}`)}}if(n.status==="answered")console.error(` \u3053\u306E\u5F8C\u306E\u8FFD\u8A18\u3092\u62FE\u3046: ${ks(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}async function bf(e,t){let{channelId:n,ts:o,question:s,reactable:r,threadOnly:i,audience:a,broadcast:c,cookie:l,timeout:u,shown:d}=t,f=Ye[t.lang],{askerUserId:h,askerBotId:g}=t,p=(U)=>typeof U==="string"&&!!U&&U!==h&&(c||a.has(U)),m,D,w,k=(U)=>{let z=typeof U.text==="string"?gt(U.text):void 0;if(z?.kind==="void")w=z;return!!w},x,C="";function I(U){let z=H(U.reactions).map(_),N=[];for(let q=0;q<r.length;q++){let ie=z.find((ae)=>ae.name===$e[q].name),B=ie?H(ie.users).filter(p):[];if(B.length)N.push({index:q,users:B})}return N}async function A(U,z){let N=typeof U.text==="string"?U.text:"";if(!N)return;let q=uo(N,z,t.lang);if(q===N)return;try{await yt(e,n,o,q,l,!0)}catch(ie){console.error(` (\u8CEA\u554F\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${ie instanceof Error?ie.message:String(ie)})`)}}let M=new Set;function X(U){let z=H(U.reactions).map(_).find((N)=>N.name===At);for(let N of z?H(z.users).filter(p):[]){if(M.has(N))continue;M.add(N),console.error(` (<@${N}> \u304C \u2753 \u305D\u306E\u4ED6 \u3092\u62BC\u3057\u307E\u3057\u305F\u3002\u8FD4\u4FE1\u3092\u5F85\u3061\u307E\u3059)`)}}async function re(U){if(r.length)X(U);let z=I(U);if(z.length<=1&&lo(typeof U.text==="string"?U.text:"").length)await A(U,[]);if(!z.length)return null;if(z.length===1){let{index:ae,users:st}=z[0];return{answer:r[ae],how:f.howReaction($e[ae].glyph),who:st[0],choice:ae+1}}let N=z.map((ae)=>$e[ae.index].glyph).join(" / "),q=new Map;for(let ae of z)for(let st of ae.users)q.set(st,(q.get(st)??0)+1);let ie=[...q].filter(([,ae])=>ae>1).map(([ae])=>ae);console.error(ie.length?` (${N} \u304C\u540C\u6642\u306B\u9078\u3070\u308C\u3066\u3044\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`:` (\u56DE\u7B54\u304C\u5206\u304B\u308C\u3066\u3044\u307E\u3059: ${N}\u3002\u3069\u3061\u3089\u304B\u4E00\u65B9\u306B\u305D\u308D\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`);let B=ie.sort();return await A(U,B),null}let L=[...r,...t.overflow];function T(U,z=1/0){let N=[...U].sort((q,ie)=>Number(q.ts)-Number(ie.ts));for(let q of N){if(!(Number(q.ts)>Number(o)))continue;if(t.after&&!(Number(q.ts)>Number(t.after)))continue;if(!p(q.user))continue;if(typeof q.subtype==="string"&&!Df.has(q.subtype))continue;if(Number(q.ts)>=z)break;let ie=typeof q.text==="string"?q.text.trim():"";if(!ie)continue;if(!L.length)return{answer:ie,how:f.howReply,who:q.user,ts:String(q.ts)};let B=gi(ie,L);if(B.kind==="chosen")return{answer:L[B.index-1],how:f.howReplyN(B.index),who:q.user,ts:String(q.ts),choice:B.index};let ae=B.kind==="ambiguous";if(!x||x.ambiguous&&!ae||x.ambiguous===ae&&Number(q.ts)<Number(x.ts))x={text:ie,who:typeof q.user==="string"?q.user:"",ts:String(q.ts),ambiguous:ae}}return null}async function P(){if(x=void 0,t.threadParentTs){let q=_(await Ie(e,n,t.threadParentTs,100,l)),ie=H(q.messages).map(_),B=ie.find((ae)=>ae.ts===o);if(B){if(m=Number(B.reply_count)||0,typeof B.text==="string")D=B.text;if(k(B))return null;let ae=await re(B);if(ae)return ae}return T(ie)}let U=_(await je(e,n,30,o,void 0,l,!0)),z=H(U.messages).map(_),N=z.find((q)=>q.ts===o);if(N){if(m=Number(N.reply_count)||0,typeof N.text==="string")D=N.text;if(k(N))return null}if(N){let q=await re(N);if(q)return q}if(!i){let q=z.filter((B)=>Number(B.ts)>Number(o)&&(g&&B.bot_id===g||h&&B.user===h)).reduce((B,ae)=>Math.min(B,Number(ae.ts)),1/0),ie=T(z,q);if(ie)return ie}if(N&&Number(N.reply_count)>0){let q=_(await Ie(e,n,o,30,l)),ie=T(H(q.messages).map(_));if(ie)return ie}return null}async function W(U){for(let N=0;N<r.length;N++)try{await an(e,n,o,$e[N].name,l)}catch{}let z="";if(U.who)try{z=await Te(e,U.who,l)}catch{z=U.who}if(z)console.error(` \u56DE\u7B54\u8005: ${v(z)}`);try{let N=D?Yl(D,U.choice):void 0;await yt(e,n,o,Gl(s,U,z,t.lang,N),l,!0);try{await Ot(e,n,o,di,l),await an(e,n,o,At,l)}catch{}}catch(N){console.error(` (\u5143\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u66F4\u65B0\u306B\u5931\u6557: ${N instanceof Error?N.message:String(N)})`)}}let te=Date.now()+u*1000,le=0,se=Vm;for(;;){let U=null;try{U=await P(),le=0}catch(z){if(le++,le>=ef)console.error(`Error: Slack \u3078\u306E\u554F\u3044\u5408\u308F\u305B\u306B ${le} \u56DE\u9023\u7D9A\u3067\u5931\u6557\u3057\u307E\u3057\u305F: ${z instanceof Error?z.message:String(z)}`),process.exit(oe);console.error(` (Slack \u30A8\u30E9\u30FC ${le}/${ef}, \u518D\u8A66\u884C\u3057\u307E\u3059: ${z instanceof Error?z.message:String(z)})`)}if(w){if(kf(w,d),t.json)await fn(e,t,{status:"void",answer:null,reason:w.reason,...w.supersededBy?{supersededBy:w.supersededBy}:{},notes:[],cursor:dn(o,t.after)});process.exit(yf)}if(U){let z=await wf(e,{channelId:n,ts:o,threadOnly:i,replyCount:m,isAnswerer:p,askerUserId:h,askerBotId:g,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...l?{cookie:l}:{}},t.after,(q)=>q.ts===U.ts);await W(U);let N={status:"answered",answer:U.answer,how:U.how,notes:z,cursor:dn(o,t.after,U.ts,...z.map((q)=>q.ts))};if(U.who)N.who=U.who;await fn(e,t,N),process.exit(0)}if(x&&!x.ambiguous){let z=x.who;try{if(z)z=await Te(e,z,l)}catch{}if(console.error(` (${v(z)} \u304C\u9078\u629E\u80A2\u5916\u306E\u8FD4\u4FE1\u3092\u3057\u307E\u3057\u305F \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u672C\u6587\u3092 stdout \u306B\u51FA\u3057\u307E\u3059)`),console.error(` \u9078\u629E\u80A2: ${L.map((N,q)=>`${q+1}. ${v(Le(N))}`).join(" ")}`),console.error(` ${d}`),console.error(` \u3053\u306E\u8FD4\u4FE1\u306E\u5F8C\u3092\u5F85\u3064: ${ks(d,t.asBot,x.ts)}`),t.json)await fn(e,t,{status:"freetext",answer:x.text,who:x.who,notes:[],cursor:dn(o,t.after,x.ts)});else console.log(x.text);process.exit(Ym)}if(x&&x.ts!==C){C=x.ts;let z=x.who;try{if(z)z=await Te(e,z,l)}catch{}console.error(` (${v(z)} \u306E\u8FD4\u4FE1\u306F\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3057\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`),console.error(` \u300C${v(x.text)}\u300D`)}if(Date.now()>=te)break;await Qm(Math.min(se,Math.max(0,te-Date.now()))),se=Math.min(se*Xm,Zm)}if(x){if(console.error("Error: \u8FD4\u4FE1\u306F\u3042\u308A\u307E\u3057\u305F\u304C\u3001\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3059\u308B\u305F\u3081\u78BA\u5B9A\u3067\u304D\u307E\u305B\u3093 (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)"),console.error(` \u8FD4\u4FE1: \u300C${v(x.text)}\u300D`),console.error(` \u9078\u629E\u80A2: ${L.map((U,z)=>`${z+1}. ${v(Le(U))}`).join(" ")}`),console.error(` ${d}`),console.error(` \u8FD4\u7B54\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${ks(d,t.asBot,t.after)}`),t.json)await fn(e,t,{status:"ambiguous",answer:null,notes:[],cursor:dn(o,t.after)});process.exit(Gm)}if(u===0)console.error(`\u307E\u3060\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093: ${d}`);else console.error(`Error: ${u}s \u4EE5\u5185\u306B\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)`),console.error(` ${d}`),console.error(` \u3042\u3068\u3067\u56DE\u53CE\u3059\u308B: ${ks(d,t.asBot,t.after)}`);if(t.json)await fn(e,t,{status:"timeout",answer:null,notes:[],cursor:dn(o,t.after)});process.exit(zm)}function ks(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function ty(e,t){let{ref:n,threadTs:o}=vn(t.target,!1),s=t.cookie,r=bt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Dt(e,t.userId,s);else i=await ye(e,n,s);let a=(await r())?.userId??"",c=await jo(e,i,s);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.
386
- `+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let l=xs(Oe(t.question)),u=xs(Oe(t.body??"")),d=new Set([...l.kinds,...u.kinds]);for(let O of`${l.text}
387
- ${u.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))d.add(O[1]);let f=t.mentionToken??e,h=await Lt(f,l.text,i,t.mentionCookie),g=u.text?await Lt(f,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},p=h.text,m=g.text,D=[...h.resolved,...g.resolved],w=[...h.unresolved,...g.unresolved];for(let O of ms(w))console.error(`\u26A0 ${v(O)}`);let k=d.size>0,x=new Set(D.map((O)=>O.userId).filter((O)=>O!==a)),C=new Map(D.map((O)=>[O.userId,O.display]));for(let O of`${p}
388
- ${m}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)){let Q=O[1];if(Q===a||x.has(Q))continue;x.add(Q),C.set(Q,await Te(f,Q,t.mentionCookie))}let I;if(k)I=`anyone in ${n} (${[...d].map((O)=>`@${O}`).join(", ")})`;else{if(!x.size&&c&&c!==a)x.add(c),C.set(c,await Te(e,c,s));if(!x.size)console.error("Error: `ask` will not post a question nobody is addressed to \u2014 no one is tagged.\n"+(w.length?` (${w.map((O)=>v(O.surface)).join(", ")} matched no one, so it names nobody.)
389
- `:"")+` Tag the person who should answer: slack ask '${t.target}' '@alice ${t.question}' ...
376
+ `).map((A)=>` ${v(A)}`),"---------------------------------------------",...F?["\u26A0 The state text is unchanged \u2014 only the footer time moves. Replies are for real changes."]:[],...D?["\u26A0 Adopting: this message has no pinlog footer yet \u2014 it becomes a board now."]:[]])}let S=pn("edit");try{await yt(e,o,s,w,t.cookie,!0,S.metadata)}catch(C){let F=C instanceof Error?C.message:String(C),A=/cant_update_message/.test(F)?`
377
+ Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",O=No(C)?`\u2717 HEAD was NOT updated: ${ie(C)}${A}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${ie(C)}
378
+ Check it first: slack pinlog get ${l}${d}`;console.error(`${O}
379
+ The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}S.record({team:c?.team,channel:o,target:t.target,ts:s,text:w,asBot:t.asBot}),console.log(`\u2713 HEAD updated: ${l}`)}let f=pn("send"),g;try{g=await an(e,o,t.log,s,!1,t.cookie,!0,f.metadata)}catch(w){let D=No(w);console.error((D?`\u2717 Log reply was NOT posted: ${ie(w)}
380
+ `:`\u26A0 UNKNOWN whether the log reply was posted: ${ie(w)}
381
+ `)+(t.logOnly?"":` The HEAD IS updated \u2014 only the log line ${D?"is":"may be"} missing.
382
+ `)+(D?"":` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${l}${d}
383
+ `)+` Retry just the log line${D?"":" (only if it is not there)"}:
384
+ ${h}`),process.exit(1)}if(f.record({team:c?.team,channel:o,target:t.target,ts:g,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${g})`),y)console.error(y)}function cf(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Xm(e){return Vi(new Date(Number(e.split(".")[0])*1000))}async function Vm(e,t,n,o){if(typeof t.user==="string"){let r=n.get(t.user);if(r!==void 0)return r;let i;try{i=await $e(e,t.user,o)}catch{i=t.user}return n.set(t.user,i),i}let s=T(t.bot_profile);if(typeof s.name==="string")return s.name;return typeof t.username==="string"?t.username:"bot"}async function Zm(e,t,n,o){let{channel:s,ts:r}=await la(e,t,n),i=[],a,c=0;do{let f=T(await Vu(e,s,r,a,200,n));for(let w of H(f.messages).map(T)){if(String(w.ts)===r&&i.some((D)=>String(D.ts)===r))continue;i.push(w)}let g=T(f.response_metadata).next_cursor;a=typeof g==="string"&&g?g:void 0,c++}while(a&&c<50);let l=a===void 0,u=i.find((f)=>String(f.ts)===r);if(!u)console.error(`Error: no message at ts=${r} in ${s}.`),process.exit(1);let d=typeof u.text==="string"?u.text:"",p=i.filter((f)=>String(f.ts)!==r);if(o){console.log(JSON.stringify({id:Ze(s,r),isPinlog:Pn(d),updated:ea(d),complete:l,head:d,log:p.map((f)=>({ts:String(f.ts),user:f.user??null,text:typeof f.text==="string"?f.text:""}))}));return}if(!Pn(d))console.error(`\u26A0 ${Ze(s,r)} has no "${xs}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${Ze(s,r)} ===`);for(let f of cf(d).split(`
385
+ `))console.log(v(f));let h=l?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${p.length}${h}) ===`);let y=new Map;for(let f of p){let g=typeof f.text==="string"?f.text:"",w=v(await Vm(e,f,y,n)),D=cf(g).split(`
386
+ `).map((k)=>v(k));console.log(`${Xm(String(f.ts))} @${w}: ${D[0]??""}`);for(let k of D.slice(1))console.log(` ${k}`)}}async function Ef(e,t,n,o){let s=0,r,i=[];do{let a=T(await He(e,t,Math.min(200,n-s),void 0,r,o)),c=H(a.messages).map(T);s+=c.length;for(let u of c)if(typeof u.text==="string"&&Pn(u.text))i.push(u);let l=T(a.response_metadata).next_cursor;r=typeof l==="string"&&l?l:void 0}while(r&&s<n);return{found:i,scanned:s}}function Sf(e){return v(Es(e).split(`
387
+ `).find((t)=>t.trim())??"").slice(0,80)}async function Qm(e,t,n,o){let{ref:s,ts:r}=Wt(t);if(r||To(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${Nt(t)}`),process.exit(2);let i=await fe(e,s,o),{found:a,scanned:c}=await Ef(e,i,n,o),l=await jt(e,i,s,o);if(a.length===0){console.log(`No pinlogs in the last ${c} messages of ${l}.${c>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let u of a){let d=String(u.ts),p=Ze(i,d),h=String(u.text),y=H(u.pinned_to).some((w)=>w===i)?"\uD83D\uDCCC":" ",f=Sf(h),g=typeof u.reply_count==="number"?u.reply_count:0;console.log(`${y} ${p} updated ${ea(h)??"?"} log ${g}`),console.log(` ${f}`)}}async function ey(e,t,n){let{channel:o,ts:s}=await la(e,t,n);try{await Ni(e,o,s,n),console.log(`\u2713 Pinned ${Ze(o,s)}`)}catch(r){let i=r instanceof Error?r.message:String(r);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${Ze(o,s)}`);return}console.error(`\u2717 NOT pinned: ${ie(r)}`),process.exit(1)}}async function ty(e,t){let{ref:n,ts:o}=Wt(t.target);if(!o)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let s=t.emoji.replace(/^:|:$/g,""),r;if(t.channelId)r=t.channelId;else r=await fe(e,n,t.cookie);if(t.remove)await cn(e,r,o,s,t.cookie),console.log(`\u2713 Removed :${s}: (ts: ${o})`);else await Ot(e,r,o,s,t.cookie),console.log(`\u2713 Reacted :${s}: (ts: ${o})`)}async function ua(e,t,n,o){if(!n||!t.startsWith("D"))return!1;try{let s=T(await ln(e,t,o)),r=T(s.channel);return r.is_im===!0&&r.user===n}catch{return!1}}function ny(e){let t=new Set;for(let n of e){if(typeof n.user==="string")t.add(n.user);if(typeof n.parent_user_id==="string")t.add(n.parent_user_id);for(let o of H(n.reply_users))if(typeof o==="string")t.add(o)}return t}async function sy(e,t,n){if(!t.startsWith("D"))return;try{let o=T(T(await ln(e,t,n)).channel);return o.is_im===!0&&typeof o.user==="string"?o.user:void 0}catch{return}}async function oy(e,t){let{ref:n,threadTs:o}=Bn(t.target),s=t.cookie,r=bt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await wt(e,t.userId,s);else i=await fe(e,n,s);if(!t.asBot&&await ua(e,i,(await r())?.userId,s))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
388
+ `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let a=Fe(t.message);Be(a,t.allowUrlAdjacent);let c=a,l=null;if(t.mentions){l=await Bt(t.mentionToken??e,a,i,t.mentionCookie),c=l.text;for(let A of Fo(l.unresolved))console.error(`\u26A0 ${v(A)}`)}let u=[];if(l&&(l.resolved.length>0||l.unresolved.length>0)){u.push("--- Mentions ---------------------------------");for(let A of l.resolved)u.push(` \u2713 ${v(A.surface)} \u2192 @${v(A.display)} (${A.userId}) \u2014 will notify`);for(let A of l.unresolved){let O=A.reason==="ambiguous"?"ambiguous":A.reason==="unavailable"?"lookup unavailable":"no match";u.push(` \u26A0 ${v(A.surface)} \u2014 plain text, NOT notified (${O})`)}}let d="",p="?",h=[],y,f,g;if(o)try{let A=await Pe(e,i,o,100,s);h=H(A.messages).map(T);let O=h[h.length-1];d=typeof O?.text==="string"?O.text:"",y=typeof O?.user==="string"?O.user:void 0,f=typeof O?.bot_id==="string"?O.bot_id:void 0,g=typeof O?.ts==="string"?O.ts:void 0}catch{}else try{let A=await He(e,i,1,void 0,void 0,s),O=H(A.messages).map(T),B=O.filter((P)=>P.subtype===void 0||P.subtype===null)[0];d=typeof B?.text==="string"?B.text:"",p=typeof B?.user==="string"?await $e(e,B.user,s):typeof B?.username==="string"?B.username:"?";let U=O[0];y=typeof U?.user==="string"?U.user:void 0,f=typeof U?.bot_id==="string"?U.bot_id:void 0,g=typeof U?.ts==="string"?U.ts:void 0}catch{}try{let A=o?ny(h):new Set([await sy(e,i,s)].filter((O)=>!!O));for(let O of await Wd(t.mentionToken??e,c,t.mentionCookie)){if(A.has(O.userId))continue;console.error(`\u26A0 possible untagged mention: ${v(O.surface)} \u2014 @${v(O.display)} won't be notified (did you mean <@${O.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&g&&(y||f))try{let A=await r();if(!!A&&(!!y&&!!A.userId&&A.userId===y||!!f&&!!A.botId&&A.botId===f)){let B=`slack edit "#${i}:${g}" "<\u65B0\u3057\u3044\u672C\u6587>" --channel-id ${i}`;try{let U=await Fn(e,i,g,s);if(U)B=`slack edit "${U}" "<\u65B0\u3057\u3044\u672C\u6587>"`}catch{}console.error("\u26A0 \u76F8\u624B\u306F\u307E\u3060\u8FD4\u4FE1\u3057\u3066\u3044\u307E\u305B\u3093(\u6700\u5F8C\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u3042\u306A\u305F\u306E\u3082\u306E\u3067\u3059)\u3002"),console.error(" \u9023\u6295\u3092\u907F\u3051\u308B\u305F\u3081\u3001\u65B0\u898F\u9001\u4FE1\u3067\u306A\u304F\u76F4\u524D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306E edit \u3092\u691C\u8A0E\u3057\u3066\u304F\u3060\u3055\u3044:"),console.error(` ${B}`),console.error(" \u3053\u306E\u307E\u307E\u9001\u4FE1\u3059\u308B\u5834\u5408\u306F --code=XXXX \u3067\u78BA\u5B9A\u3002")}}catch{}if(o&&h.length){let A={sim:0,msg:null};for(let O of h){let B=typeof O.text==="string"?O.text:"";if(!B)continue;let U=qm(c,B);if(U>A.sim)A={sim:U,msg:O}}if(A.msg&&A.sim>=0.82){let O=Math.round(A.sim*100);console.error(`\u26A0 possible duplicate: ${O}% similar to an existing thread message \u2014 ${await sa(e,A.msg,60,s)}`)}}let w=await r(),D=await Wo(e,i,s),k=ue(i,o??"",d,c,w?.userId??"");if(t.code!==k){let A=await jt(e,i,n,s),O=he(w,{asBot:t.asBot});if(o){let B=await Km(e,o,h,s),U=h.slice(-3),P=U.length?await Promise.all(U.map(async(_)=>` ${await sa(e,_,60,s)}`)):[" (thread context unavailable)"];pe(t.code,k,["--- Recent messages in thread ----------------",...P,...u,"--- Sending ----------------------------------",O,` \u2192 ${A} thread of ${B} \u2014 THREAD REPLY`,` Message: ${c}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],D)}else pe(t.code,k,["--- Last message in channel ------------------",` ${p}: ${bs(d.split(`
389
+ `)[0]??"").slice(0,100)}`,...u,"--- Sending ----------------------------------",O,` \u2192 ${A} \u2014 NEW top-level message`,` Message: ${c}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],D)}let S=pn("send"),C=await an(e,i,c,o,t.broadcast,s,void 0,S.metadata),F="";try{F=await Fn(e,i,C,s)}catch{}if(S.record({team:(await r())?.team,channel:i,target:t.target,ts:C,threadTs:o,permalink:F,text:c,asBot:t.asBot}),F)console.log(`\u2713 Sent: ${F}`);else console.log(`\u2713 Sent (ts: ${C})`);if(t.asBot&&i.startsWith("D"))try{let A=await to(e);if(!A.ok)for(let O of no(A,!0))console.error(O);else{let O=A.appId?`https://api.slack.com/apps/${A.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${O} \u2192 App Home.`)}}catch{}}var ry=2,Z=3,iy=4,ay=5,Cf=6,cy=1.618033988749895,ly=1000,uy=5000,lf=8,dy=(e)=>new Promise((t)=>setTimeout(t,e)),_f=new Set(["thread_broadcast"]),fy=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function $f(e){if(!e.length)return;let t=e.map((n)=>{let o=v(n.surface);if(n.reason==="unavailable")return`${o}: could not fetch the user list or channel members (users:read missing or an API/connection error)`;if(n.reason==="ambiguous")return`${o}: matches multiple people \u2014 use an explicit <@USERID> tag`;return`${o}: matched no one`});console.error(`Error: \`ask\` will not post with unresolved answerer tags.
390
+ ${t.join(`
391
+ `)}`),process.exit(Z)}function Ss(e){let t=new Set;return{text:e.replace(fy,(o,s)=>{let r=s.toLowerCase();return t.add(r),`<!${r}>`}),kinds:t}}async function Jo(e,t,n){if(!t.startsWith("D"))return;try{let o=T(await ln(e,t,n)),s=T(o.channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function Ff(e,t,n,o){let s=new Map;if(t.threadParentTs||t.replyCount!==0)try{let a=T(await Pe(e,t.channelId,t.threadParentTs??t.ts,100,t.cookie));for(let c of H(a.messages).map(T))s.set(String(c.ts),c)}catch(a){console.error(` (\u30B9\u30EC\u30C3\u30C9\u306E\u8FFD\u8A18\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${a instanceof Error?a.message:String(a)})`)}if(!t.threadOnly&&!t.threadParentTs)try{let a=T(await He(e,t.channelId,30,t.ts,void 0,t.cookie,!0)),c=H(a.messages).map(T),l=c.filter((u)=>Number(u.ts)>Number(t.ts)&&(t.askerBotId&&u.bot_id===t.askerBotId||t.askerUserId&&u.user===t.askerUserId)).reduce((u,d)=>Math.min(u,Number(d.ts)),1/0);for(let u of c)if(Number(u.ts)<l&&!s.has(String(u.ts)))s.set(String(u.ts),u)}catch(a){console.error(` (DM \u306E\u8FFD\u8A18\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${a instanceof Error?a.message:String(a)})`)}let r=[...s.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"||_f.has(a.subtype)).filter((a)=>typeof a.text==="string"&&a.text.trim()!=="").sort((a,c)=>Number(a.ts)-Number(c.ts)).filter((a)=>!o(a)),i=[];for(let a of r){let c="";try{c=await Fn(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 Lt(...e){return e.filter((t)=>!!t).reduce((t,n)=>!t||Number(n)>Number(t)?n:t,"")}async function fn(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}:{},notes:n.notes,cursor:n.cursor,permalink:t.shown}));return}if(n.notes.length){console.error(` \u30B9\u30EC\u30C3\u30C9\u306E\u8FFD\u8A18 ${n.notes.length} \u4EF6 (\u56DE\u7B54\u3068\u306F\u5225):`);for(let o of n.notes){let s=o.user;try{s=await $e(e,o.user,t.cookie)}catch{}for(let[r,i]of o.text.split(`
392
+ `).entries())console.error(` ${r?" ".repeat(v(s).length+2):`${v(s)}: `}${v(i)}`)}}if(n.status==="answered")console.error(` \u3053\u306E\u5F8C\u306E\u8FFD\u8A18\u3092\u62FE\u3046: ${vn(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}function Af(e,t,n=!1){let{channelId:o,ts:s,reactable:r,threadOnly:i,audience:a,broadcast:c,cookie:l}=t,u=qe[t.lang],d={},{askerUserId:p,askerBotId:h}=t,y=(B)=>typeof B==="string"&&!!B&&B!==p&&(c||a.has(B)),f=(B)=>{if(d.replyCount=Number(B.reply_count)||0,typeof B.text==="string")d.ownText=B.text},g=(B)=>{let U=typeof B.text==="string"?gt(B.text):void 0;if(U?.kind==="void")d.voided=U;return!!d.voided};function w(B){let U=H(B.reactions).map(T),P=[];for(let _=0;_<r.length;_++){let R=U.find((W)=>W.name===Ee[_].name),L=R?H(R.users).filter(y):[];if(L.length)P.push({index:_,users:L})}return P}async function D(B,U){if(n)return;let P=typeof B.text==="string"?B.text:"";if(!P)return;let _=po(P,U,t.lang);if(_===P)return;try{await yt(e,o,s,_,l,!0)}catch(R){console.error(` (\u8CEA\u554F\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${R instanceof Error?R.message:String(R)})`)}}let k=new Set;function S(B){let U=H(B.reactions).map(T).find((P)=>P.name===At);for(let P of U?H(U.users).filter(y):[]){if(k.has(P))continue;if(k.add(P),!n)console.error(` (<@${P}> \u304C \u2753 \u305D\u306E\u4ED6 \u3092\u62BC\u3057\u307E\u3057\u305F\u3002\u8FD4\u4FE1\u3092\u5F85\u3061\u307E\u3059)`)}}async function C(B){if(r.length)S(B);let U=w(B);if(U.length<=1&&fo(typeof B.text==="string"?B.text:"").length)await D(B,[]);if(!U.length)return null;if(U.length===1){let{index:W,users:ne}=U[0];return{answer:r[W],how:u.howReaction(Ee[W].glyph),who:ne[0],choice:W+1}}let P=U.map((W)=>Ee[W.index].glyph).join(" / "),_=new Map;for(let W of U)for(let ne of W.users)_.set(ne,(_.get(ne)??0)+1);let R=[..._].filter(([,W])=>W>1).map(([W])=>W);if(!n)console.error(R.length?` (${P} \u304C\u540C\u6642\u306B\u9078\u3070\u308C\u3066\u3044\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`:` (\u56DE\u7B54\u304C\u5206\u304B\u308C\u3066\u3044\u307E\u3059: ${P}\u3002\u3069\u3061\u3089\u304B\u4E00\u65B9\u306B\u305D\u308D\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`);let L=R.sort();return await D(B,L),null}let F=[...r,...t.overflow];function A(B,U=1/0){let P=[...B].sort((_,R)=>Number(_.ts)-Number(R.ts));for(let _ of P){if(!(Number(_.ts)>Number(s)))continue;if(t.after&&!(Number(_.ts)>Number(t.after)))continue;if(!y(_.user))continue;if(typeof _.subtype==="string"&&!_f.has(_.subtype))continue;if(Number(_.ts)>=U)break;let R=typeof _.text==="string"?_.text.trim():"";if(!R)continue;if(!F.length)return{answer:R,how:u.howReply,who:_.user,ts:String(_.ts)};let L=Di(R,F);if(L.kind==="chosen")return{answer:F[L.index-1],how:u.howReplyN(L.index),who:_.user,ts:String(_.ts),choice:L.index};let W=L.kind==="ambiguous",ne=d.unchosen;if(!ne||ne.ambiguous&&!W||ne.ambiguous===W&&Number(_.ts)<Number(ne.ts))d.unchosen={text:R,who:typeof _.user==="string"?_.user:"",ts:String(_.ts),ambiguous:W}}return null}async function O(){if(delete d.unchosen,t.threadParentTs){let _=T(await Pe(e,o,t.threadParentTs,100,l)),R=H(_.messages).map(T),L=R.find((W)=>W.ts===s);if(L){if(f(L),g(L))return null;let W=await C(L);if(W)return W}return A(R)}let B=T(await He(e,o,30,s,void 0,l,!0)),U=H(B.messages).map(T),P=U.find((_)=>_.ts===s);if(P){if(f(P),g(P))return null}if(P){let _=await C(P);if(_)return _}if(!i){let _=U.filter((L)=>Number(L.ts)>Number(s)&&(h&&L.bot_id===h||p&&L.user===p)).reduce((L,W)=>Math.min(L,Number(W.ts)),1/0),R=A(U,_);if(R)return R}if(P&&Number(P.reply_count)>0){let _=T(await Pe(e,o,s,30,l)),R=A(H(_.messages).map(T));if(R)return R}return null}return{poll:O,state:d,isAnswerer:y,candidates:F}}async function Tf(e,t){let{channelId:n,ts:o,question:s,reactable:r,threadOnly:i,cookie:a,timeout:c,shown:l}=t,{askerUserId:u,askerBotId:d}=t,{poll:p,state:h,isAnswerer:y,candidates:f}=Af(e,t),g="";async function w(F){for(let O=0;O<r.length;O++)try{await cn(e,n,o,Ee[O].name,a)}catch{}let A="";if(F.who)try{A=await $e(e,F.who,a)}catch{A=F.who}if(A)console.error(` \u56DE\u7B54\u8005: ${v(A)}`);try{let O=h.ownText?eu(h.ownText,F.choice):void 0;await yt(e,n,o,Ql(s,F,A,t.lang,O),a,!0);try{await Ot(e,n,o,gi,a),await cn(e,n,o,At,a)}catch{}}catch(O){console.error(` (\u5143\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u66F4\u65B0\u306B\u5931\u6557: ${O instanceof Error?O.message:String(O)})`)}}let D=Date.now()+c*1000,k=0,S=ly,C;for(;;){let F=null;try{F=await p(),k=0}catch(O){if(k++,k>=lf)console.error(`Error: Slack \u3078\u306E\u554F\u3044\u5408\u308F\u305B\u306B ${k} \u56DE\u9023\u7D9A\u3067\u5931\u6557\u3057\u307E\u3057\u305F: ${O instanceof Error?O.message:String(O)}`),process.exit(Z);console.error(` (Slack \u30A8\u30E9\u30FC ${k}/${lf}, \u518D\u8A66\u884C\u3057\u307E\u3059: ${O instanceof Error?O.message:String(O)})`)}C=h.unchosen;let A=h.voided;if(A){if(If(A,l),t.json)await fn(e,t,{status:"void",answer:null,reason:A.reason,...A.supersededBy?{supersededBy:A.supersededBy}:{},notes:[],cursor:Lt(o,t.after)});process.exit(Cf)}if(F){let O=await Ff(e,{channelId:n,ts:o,threadOnly:i,replyCount:h.replyCount,isAnswerer:y,askerUserId:u,askerBotId:d,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...a?{cookie:a}:{}},t.after,(U)=>U.ts===F.ts);await w(F);let B={status:"answered",answer:F.answer,how:F.how,notes:O,cursor:Lt(o,t.after,F.ts,...O.map((U)=>U.ts))};if(Ii(n,o,F.answer,B.cursor),F.who)B.who=F.who;await fn(e,t,B),process.exit(0)}if(C&&!C.ambiguous){let O=C.who;try{if(O)O=await $e(e,O,a)}catch{}if(console.error(` (${v(O)} \u304C\u9078\u629E\u80A2\u5916\u306E\u8FD4\u4FE1\u3092\u3057\u307E\u3057\u305F \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u672C\u6587\u3092 stdout \u306B\u51FA\u3057\u307E\u3059)`),console.error(` \u9078\u629E\u80A2: ${f.map((B,U)=>`${U+1}. ${v(_e(B))}`).join(" ")}`),console.error(` ${l}`),console.error(` \u3053\u306E\u8FD4\u4FE1\u306E\u5F8C\u3092\u5F85\u3064: ${vn(l,t.asBot,C.ts)}`),Iu(n,o,C.text,Lt(o,t.after,C.ts)),t.json)await fn(e,t,{status:"freetext",answer:C.text,who:C.who,notes:[],cursor:Lt(o,t.after,C.ts)});else console.log(C.text);process.exit(ay)}if(C&&C.ts!==g){g=C.ts;let O=C.who;try{if(O)O=await $e(e,O,a)}catch{}console.error(` (${v(O)} \u306E\u8FD4\u4FE1\u306F\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3057\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`),console.error(` \u300C${v(C.text)}\u300D`)}if(Date.now()>=D)break;await dy(Math.min(S,Math.max(0,D-Date.now()))),S=Math.min(S*cy,uy)}if(C){if(console.error("Error: \u8FD4\u4FE1\u306F\u3042\u308A\u307E\u3057\u305F\u304C\u3001\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3059\u308B\u305F\u3081\u78BA\u5B9A\u3067\u304D\u307E\u305B\u3093 (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)"),console.error(` \u8FD4\u4FE1: \u300C${v(C.text)}\u300D`),console.error(` \u9078\u629E\u80A2: ${f.map((F,A)=>`${A+1}. ${v(_e(F))}`).join(" ")}`),console.error(` ${l}`),console.error(` \u8FD4\u7B54\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${vn(l,t.asBot,t.after)}`),t.json)await fn(e,t,{status:"ambiguous",answer:null,notes:[],cursor:Lt(o,t.after)});process.exit(iy)}if(c===0)console.error(`\u307E\u3060\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093: ${l}`);else console.error(`Error: ${c}s \u4EE5\u5185\u306B\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)`),console.error(` ${l}`),console.error(` \u3042\u3068\u3067\u56DE\u53CE\u3059\u308B: ${vn(l,t.asBot,t.after)}`);if(t.json)await fn(e,t,{status:"timeout",answer:null,notes:[],cursor:Lt(o,t.after)});process.exit(ry)}function vn(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function py(e,t){let{ref:n,threadTs:o}=Bn(t.target,!1),s=t.cookie,r=bt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await wt(e,t.userId,s);else i=await fe(e,n,s);let a=(await r())?.userId??"",c=await Jo(e,i,s);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.
393
+ `+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let l=Ss(Fe(t.question)),u=Ss(Fe(t.body??"")),d=new Set([...l.kinds,...u.kinds]);for(let M of`${l.text}
394
+ ${u.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))d.add(M[1]);let p=t.mentionToken??e,h=await Bt(p,l.text,i,t.mentionCookie),y=u.text?await Bt(p,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},f=h.text,g=y.text,w=[...h.resolved,...y.resolved],D=[...h.unresolved,...y.unresolved];$f(D);let k=d.size>0,S=new Set(w.map((M)=>M.userId).filter((M)=>M!==a)),C=new Map(w.map((M)=>[M.userId,M.display]));for(let M of`${f}
395
+ ${g}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)){let V=M[1];if(V===a||S.has(V))continue;S.add(V),C.set(V,await $e(p,V,t.mentionCookie))}let F;if(k)F=`anyone in ${n} (${[...d].map((M)=>`@${M}`).join(", ")})`;else{if(!S.size&&c&&c!==a)S.add(c),C.set(c,await $e(e,c,s));if(!S.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}' ...
390
396
  Or open it to the whole channel: slack ask '${t.target}' '@here ${t.question}' ...
391
- (In a 1:1 DM the other person counts automatically.)`),process.exit(oe);I=[...x].map((O)=>`@${v(C.get(O)??O)} (${O})`).join(", ")}let A=t.choices.map(Oe),M=A.slice(0,ht),X=A.slice(ht),re=!i.startsWith("D")||!!o,L=k?[]:await Promise.all([...x].map((O)=>od(f,O,t.mentionCookie))),T=li({flag:t.lang,readerLocales:L,content:[p,m,...M,...X]});if(!T)console.error(`Error: unsupported language "${v(t.lang??process.env.SLACK_TERM_LANG??"")}" \u2014 use one of: ${Tt.join(", ")}`),process.exit(oe);let P=T.lang,W=hi(p,m,M,X,re,P);Ne(W,t.allowUrlAdjacent);let te="",le="?";try{let O=await je(e,i,1,void 0,void 0,s),Q=H(O.messages).map(_).filter((ue)=>ue.subtype===void 0||ue.subtype===null)[0];te=typeof Q?.text==="string"?Q.text:"",le=typeof Q?.user==="string"?await Te(e,Q.user,s):typeof Q?.username==="string"?Q.username:"?"}catch{}let se=await r(),U=await No(e,i,s),z=ge(i,o??"",te,W,se?.userId??"",...t.voidAfter?["reask",`${t.voidAfter.channelId}:${t.voidAfter.ts}`,t.voidAfter.reason]:[]);if(t.code!==z){let O=await Mt(e,i,n,s),Q=M.length?["--- Choices (seeded as reactions) ------------",...M.map((ue,ne)=>` ${$e[ne].glyph} ${Le(ue)}`),...X.map((ue,ne)=>` (${ne+11}) ${Le(ue)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];De(t.code,z,["--- Last message in channel ------------------",` ${le}: ${ys(te.split(`
392
- `)[0]??"").slice(0,100)}`,...Q,"--- Asking -----------------------------------",we(se,{asBot:t.asBot}),` \u2192 ${O}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${p}`,` Answerable by: ${I}`,` Via: ${re?"reactions or thread replies":"reactions or replies in this DM"}`,...t.voidAfter?[` Then \u7121\u52B9\u5316: ${v(t.voidAfter.link)} (reason: ${v(t.voidAfter.reason||"none")}) \u2014 replaced by this question`]:[],` Language: ${P} (${{flag:"--lang",env:"SLACK_TERM_LANG",readers:"answerers' Slack locale",content:"the question's text",system:"system locale",default:"default"}[T.source]}; override with --lang)`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],U)}let N=pn("ask"),q=await rn(e,i,W,o,!1,s,!0,N.metadata);await mo([...M.map((O,Q)=>$e[Q].name),At],(O)=>Ot(e,i,q,O,s),(O,Q)=>{let ue=Q instanceof Error?Q.message:String(Q);if(O===At)console.error(` (marker ${O} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${ue})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${O} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${ue})`)});let ie="";try{ie=await Fn(e,i,q,s)}catch{}let B=ie||`${i}:${q}`;if(console.error(`\u2713 Asked: ${B}`),N.record({team:se?.team,channel:i,target:t.target,ts:q,threadTs:o,permalink:ie,text:W,asBot:t.asBot}),t.voidAfter){if(!await Ef(e,t.voidAfter,t.voidAfter.reason,B,s))console.error(` \u26A0 \u65B0\u3057\u3044\u8CEA\u554F\u306F\u51FA\u307E\u3057\u305F\u304C\u3001\u53E4\u3044\u8CEA\u554F\u3092\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F \u2014 \u624B\u3067: slack ask --void='${v(t.voidAfter.link)}' --superseded-by='${B}'`)}if(!t.wait){console.log(ks(B,!!t.asBot));return}let ae=t.timeout??3600;console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${ae}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let st={channelId:i,ts:q,question:p,reactable:M,overflow:X,threadOnly:re,lang:P,audience:x,broadcast:k,askerUserId:se?.userId??"",askerBotId:se?.botId??"",timeout:ae,shown:B,asBot:!!t.asBot,json:!!t.json};if(o)st.threadParentTs=o;if(s)st.cookie=s;await bf(e,st)}function kf(e,t){if(console.error(`\u3053\u306E\u8CEA\u554F\u306F\u7121\u52B9\u3067\u3059 \u2014 \u56DE\u7B54\u3055\u308C\u308B\u3053\u3068\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u5F85\u3064\u306E\u3092\u3084\u3081\u3066\u304F\u3060\u3055\u3044: ${v(t)}`),e.reason)console.error(` ${v(e.reason)}`);if(e.supersededBy)console.error(` \u65B0\u3057\u3044\u8CEA\u554F: ${v(e.supersededBy)}`)}async function vo(e,t,n){let o=Rt(t),s,r,i;if(o?.ts)s=o.channel,r=o.ts,i=o.threadTs&&o.threadTs!==o.ts?o.threadTs:void 0;else{let l=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!l)return null;s=l[1],r=l[2]}let a;if(i){let l=_(await Ie(e,s,i,100,n));a=H(l.messages).map(_).find((u)=>u.ts===r)}else{let l=_(await je(e,s,1,r,void 0,n,!0));a=H(l.messages).map(_).find((u)=>u.ts===r)}let c={channelId:s,ts:r};if(i)c.threadTs=i;if(a)c.msg=a;return c}async function xf(e,t,n,o,s){let r=v(t),i=await vo(e,t,s);if(!i)return console.error(`\u2717 ${r}: permalink (\u307E\u305F\u306F 'C\u2026:1700000000.000100') \u3067\u306F\u3042\u308A\u307E\u305B\u3093`),null;if(!i.msg)return console.error(`\u2717 ${r}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`),null;let a=i.msg;if(!(!!n?.userId&&a.user===n.userId||!!n?.botId&&a.bot_id===n.botId))return console.error(`\u2717 ${r}: \u81EA\u5206\uFF08${Mo(n,o)}\uFF09\u304C\u6295\u7A3F\u3057\u305F\u8CEA\u554F\u3067\u306F\u3042\u308A\u307E\u305B\u3093`+`${o?"":" \u2014 bot \u304C\u51FA\u3057\u305F\u8CEA\u554F\u306A\u3089 --as-bot \u3067"}`),null;let l=typeof a.text==="string"?a.text:"",u=gt(l);if(u.kind==="void")return"void";if(u.kind==="resolved")return console.error(`\u2717 ${r}: \u56DE\u7B54\u6E08\u307F\u306E\u8CEA\u554F\u3067\u3059\uFF08\u56DE\u7B54: ${v(u.answer.split(`
393
- `)[0]??"")}\uFF09\u2014 \u5909\u66F4\u3067\u304D\u307E\u305B\u3093`),null;if(u.kind!=="open")return console.error(`\u2717 ${r}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093 \u2014 ${fo(l)}`),null;let d={link:t,channelId:i.channelId,ts:i.ts,parsed:u,msg:a};if(i.threadTs)d.threadTs=i.threadTs;return d}async function ny(e,t,n,o){let s=(i)=>typeof i==="string"&&i!==n?.userId;if(H(t.msg.reactions).map(_).some((i)=>$e.some((a)=>a.name===i.name)&&H(i.users).some(s)))return!0;if(Number(t.msg.reply_count)>0){let i=_(await Ie(e,t.channelId,t.ts,100,o));if(H(i.messages).map(_).some((a)=>Number(a.ts)>Number(t.ts)&&s(a.user)&&!a.bot_id))return!0}if(t.channelId.startsWith("D")){let i=_(await je(e,t.channelId,30,t.ts,void 0,o,!0));if(H(i.messages).map(_).some((a)=>Number(a.ts)>Number(t.ts)&&s(a.user)&&!a.bot_id))return!0}return!1}async function sy(e,t){let n=await Ue(e,t.cookie),o=await xf(e,t.link,n,t.asBot,t.cookie);if(o==="void")console.error(`\u2717 ${v(t.link)}: \u7121\u52B9\u5316\u6E08\u307F\u306E\u8CEA\u554F\u306F\u7DE8\u96C6\u3067\u304D\u307E\u305B\u3093`),process.exit(oe);if(!o)process.exit(oe);let s=o.parsed,r=async(x)=>{let C=xs(Oe(x));return(await Lt(t.mentionToken,C.text,o.channelId,t.mentionCookie)).text},i=t.question!==void 0?await r(t.question):s.question,a=t.body!==void 0?await r(t.body):s.body,c=[...s.reactable,...s.overflow],l=t.choices?t.choices.map(Oe):c,u=JSON.stringify(l.map(Le))!==JSON.stringify(c.map(Le));if(u&&await ny(e,o,n,t.cookie))console.error(`\u2717 \u3053\u306E\u8CEA\u554F\u306B\u306F\u3082\u3046\u56DE\u7B54\uFF08\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u304B\u8FD4\u4FE1\uFF09\u304C\u3042\u308A\u307E\u3059 \u2014 \u9078\u629E\u80A2\u3092\u5909\u3048\u308B\u3068\u3001\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306E\u610F\u5473\u304C\u5909\u308F\u3063\u3066\u3057\u307E\u3044\u307E\u3059\u3002
397
+ (In a 1:1 DM the other person counts automatically.)`),process.exit(Z);F=[...S].map((M)=>`@${v(C.get(M)??M)} (${M})`).join(", ")}let A=t.choices.map(Fe),O=A.slice(0,ht),B=A.slice(ht),U=!i.startsWith("D")||!!o,P=k?[]:await Promise.all([...S].map((M)=>fd(p,M,t.mentionCookie))),_=pi({flag:t.lang,readerLocales:P,content:[f,g,...O,...B]});if(!_)console.error(`Error: unsupported language "${v(t.lang??process.env.SLACK_TERM_LANG??"")}" \u2014 use one of: ${Tt.join(", ")}`),process.exit(Z);let R=_.lang,L=wi(f,g,O,B,U,R);Be(L,t.allowUrlAdjacent);let W="",ne="?";try{let M=await He(e,i,1,void 0,void 0,s),V=H(M.messages).map(T).filter((re)=>re.subtype===void 0||re.subtype===null)[0];W=typeof V?.text==="string"?V.text:"",ne=typeof V?.user==="string"?await $e(e,V.user,s):typeof V?.username==="string"?V.username:"?"}catch{}let te=await r(),ge=await Wo(e,i,s),et=ue(i,o??"",W,L,te?.userId??"",...t.voidAfter?["reask",`${t.voidAfter.channelId}:${t.voidAfter.ts}`,t.voidAfter.reason]:[]);if(t.code!==et){let M=await jt(e,i,n,s),V=O.length?["--- Choices (seeded as reactions) ------------",...O.map((re,ee)=>` ${Ee[ee].glyph} ${_e(re)}`),...B.map((re,ee)=>` (${ee+11}) ${_e(re)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];pe(t.code,et,["--- Last message in channel ------------------",` ${ne}: ${bs(W.split(`
398
+ `)[0]??"").slice(0,100)}`,...V,"--- Asking -----------------------------------",he(te,{asBot:t.asBot}),` \u2192 ${M}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${f}`,` Answerable by: ${F}`,` Via: ${U?"reactions or thread replies":"reactions or replies in this DM"}`,...t.voidAfter?[` Then \u7121\u52B9\u5316: ${v(t.voidAfter.link)} (reason: ${v(t.voidAfter.reason||"none")}) \u2014 replaced by this question`]:[],` Language: ${R} (${{flag:"--lang",env:"SLACK_TERM_LANG",readers:"answerers' Slack locale",content:"the question's text",system:"system locale",default:"default"}[_.source]}; override with --lang)`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],ge)}let oe=pn("ask"),Ie=await an(e,i,L,o,!1,s,!0,oe.metadata);await yo([...O.map((M,V)=>Ee[V].name),At],(M)=>Ot(e,i,Ie,M,s),(M,V)=>{let re=V instanceof Error?V.message:String(V);if(M===At)console.error(` (marker ${M} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${re})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${M} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${re})`)});let ut="";try{ut=await Fn(e,i,Ie,s)}catch{}let G=ut||`${i}:${Ie}`;if(console.error(`\u2713 Asked: ${G}`),oe.record({team:te?.team,channel:i,target:t.target,ts:Ie,threadTs:o,permalink:ut,text:L,asBot:t.asBot}),t.voidAfter){if(!await Rf(e,t.voidAfter,t.voidAfter.reason,G,s))console.error(` \u26A0 \u65B0\u3057\u3044\u8CEA\u554F\u306F\u51FA\u307E\u3057\u305F\u304C\u3001\u53E4\u3044\u8CEA\u554F\u3092\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F \u2014 \u624B\u3067: slack ask --void='${v(t.voidAfter.link)}' --superseded-by='${G}'`)}if(!t.wait){console.log(vn(G,!!t.asBot));return}let dt=t.timeout??3600;console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${dt}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let hn={channelId:i,ts:Ie,question:f,reactable:O,overflow:B,threadOnly:U,lang:R,audience:S,broadcast:k,askerUserId:te?.userId??"",askerBotId:te?.botId??"",timeout:dt,shown:G,asBot:!!t.asBot,json:!!t.json};if(o)hn.threadParentTs=o;if(s)hn.cookie=s;await Tf(e,hn)}function If(e,t){if(console.error(`\u3053\u306E\u8CEA\u554F\u306F\u7121\u52B9\u3067\u3059 \u2014 \u56DE\u7B54\u3055\u308C\u308B\u3053\u3068\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u5F85\u3064\u306E\u3092\u3084\u3081\u3066\u304F\u3060\u3055\u3044: ${v(t)}`),e.reason)console.error(` ${v(e.reason)}`);if(e.supersededBy)console.error(` \u65B0\u3057\u3044\u8CEA\u554F: ${v(e.supersededBy)}`)}async function oa(e,t,n){let o=Rt(t),s,r,i;if(o?.ts)s=o.channel,r=o.ts,i=o.threadTs&&o.threadTs!==o.ts?o.threadTs:void 0;else{let a=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!a)return null;s=a[1],r=a[2]}return Ko(e,{channelId:s,ts:r,threadTs:i},n)}async function Ko(e,t,n){let{channelId:o,ts:s}=t,r=t.threadTs&&t.threadTs!==t.ts?t.threadTs:void 0,i;if(r){let c=T(await Pe(e,o,r,100,n));i=H(c.messages).map(T).find((l)=>l.ts===s)}else{let c=T(await He(e,o,1,s,void 0,n,!0));i=H(c.messages).map(T).find((l)=>l.ts===s)}let a={channelId:o,ts:s};if(r)a.threadTs=r;if(i)a.msg=i;return a}async function Of(e,t,n,o,s){let r=v(t),i=await oa(e,t,s);if(!i)return console.error(`\u2717 ${r}: permalink (\u307E\u305F\u306F 'C\u2026:1700000000.000100') \u3067\u306F\u3042\u308A\u307E\u305B\u3093`),null;if(!i.msg)return console.error(`\u2717 ${r}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`),null;let a=i.msg;if(!(!!n?.userId&&a.user===n.userId||!!n?.botId&&a.bot_id===n.botId))return console.error(`\u2717 ${r}: \u81EA\u5206\uFF08${Uo(n,o)}\uFF09\u304C\u6295\u7A3F\u3057\u305F\u8CEA\u554F\u3067\u306F\u3042\u308A\u307E\u305B\u3093`+`${o?"":" \u2014 bot \u304C\u51FA\u3057\u305F\u8CEA\u554F\u306A\u3089 --as-bot \u3067"}`),null;let l=typeof a.text==="string"?a.text:"",u=gt(l);if(u.kind==="void")return"void";if(u.kind==="resolved")return console.error(`\u2717 ${r}: \u56DE\u7B54\u6E08\u307F\u306E\u8CEA\u554F\u3067\u3059\uFF08\u56DE\u7B54: ${v(u.answer.split(`
399
+ `)[0]??"")}\uFF09\u2014 \u5909\u66F4\u3067\u304D\u307E\u305B\u3093`),null;if(u.kind!=="open")return console.error(`\u2717 ${r}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093 \u2014 ${as(l)}`),null;let d={link:t,channelId:i.channelId,ts:i.ts,parsed:u,msg:a};if(i.threadTs)d.threadTs=i.threadTs;return d}async function hy(e,t,n,o){let s=(i)=>typeof i==="string"&&i!==n?.userId;if(H(t.msg.reactions).map(T).some((i)=>Ee.some((a)=>a.name===i.name)&&H(i.users).some(s)))return!0;if(Number(t.msg.reply_count)>0){let i=T(await Pe(e,t.channelId,t.ts,100,o));if(H(i.messages).map(T).some((a)=>Number(a.ts)>Number(t.ts)&&s(a.user)&&!a.bot_id))return!0}if(t.channelId.startsWith("D")){let i=T(await He(e,t.channelId,30,t.ts,void 0,o,!0));if(H(i.messages).map(T).some((a)=>Number(a.ts)>Number(t.ts)&&s(a.user)&&!a.bot_id))return!0}return!1}async function gy(e,t){let n=await Te(e,t.cookie),o=await Of(e,t.link,n,t.asBot,t.cookie);if(o==="void")console.error(`\u2717 ${v(t.link)}: \u7121\u52B9\u5316\u6E08\u307F\u306E\u8CEA\u554F\u306F\u7DE8\u96C6\u3067\u304D\u307E\u305B\u3093`),process.exit(Z);if(!o)process.exit(Z);let s=o.parsed,r=async(S)=>{let C=Ss(Fe(S)),F=await Bt(t.mentionToken,C.text,o.channelId,t.mentionCookie);return $f(F.unresolved),F.text},i=t.question!==void 0?await r(t.question):s.question,a=t.body!==void 0?await r(t.body):s.body,c=[...s.reactable,...s.overflow],l=t.choices?t.choices.map(Fe):c,u=JSON.stringify(l.map(_e))!==JSON.stringify(c.map(_e));if(u&&await hy(e,o,n,t.cookie))console.error(`\u2717 \u3053\u306E\u8CEA\u554F\u306B\u306F\u3082\u3046\u56DE\u7B54\uFF08\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u304B\u8FD4\u4FE1\uFF09\u304C\u3042\u308A\u307E\u3059 \u2014 \u9078\u629E\u80A2\u3092\u5909\u3048\u308B\u3068\u3001\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306E\u610F\u5473\u304C\u5909\u308F\u3063\u3066\u3057\u307E\u3044\u307E\u3059\u3002
394
400
  `+` \u8CEA\u554F\u6587\u3068\u672C\u6587\u306F\u5909\u3048\u3089\u308C\u307E\u3059\u3002\u9078\u629E\u80A2\u3092\u5909\u3048\u308B\u306A\u3089\u7121\u52B9\u5316\u3057\u3066\u51FA\u3057\u76F4\u3057\u3066\u304F\u3060\u3055\u3044:
395
- `+` slack ask --void='${v(t.link)}' --reask${t.asBot?" --as-bot":""} \u2026`),process.exit(oe);if(!([...`${i}
396
- ${a}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].some((x)=>x[1]!==n?.userId)||/<!(?:here|channel|everyone)/.test(`${i}
397
- ${a}`)||o.channelId.startsWith("D")))console.error("\u2717 \u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u8CEA\u554F\u306B\u306A\u308A\u307E\u3059 \u2014 \u56DE\u7B54\u3067\u304D\u308B\u4EBA\u3092 @ \u3067\u6B8B\u3057\u3066\u304F\u3060\u3055\u3044"),process.exit(oe);let h=t.lang?li({flag:t.lang})?.lang??s.lang:s.lang,g=l.slice(0,ht),p=l.slice(ht),m=typeof o.msg.text==="string"?o.msg.text:"",D=hi(i,a,g,p,s.threadOnly,h),w=lo(m);if(w.length)D=uo(D,w,h);if(Ne(D,t.allowUrlAdjacent),D===m){console.error("\u5909\u66F4\u306F\u3042\u308A\u307E\u305B\u3093\u3002");return}let k=ge("ask-edit",`${o.channelId}:${o.ts}`,D,n?.userId??"");if(t.code!==k){let x=(C,I,A)=>I===A?[` ${C}: (unchanged)`]:[` ${C}:`,...I.split(`
398
- `).map((M)=>` - ${M}`),...A.split(`
399
- `).map((M)=>` + ${M}`)];De(t.code,k,["--- Editing question --------------------------",we(n,{asBot:t.asBot}),` ${v(t.link)}`,...x("Question",s.question,i),...x("Body",s.body,a),...u?[" Choices (nobody has answered yet \u2014 pills are re-seeded):",...c.map((C,I)=>` - ${I+1}. ${Le(C)}`),...l.map((C,I)=>` + ${I+1}. ${Le(C)}`)]:[" Choices: (unchanged)"],...h!==s.lang?[` Language: ${s.lang} \u2192 ${h} (the instructions are rewritten)`]:[],"----------------------------------------------"])}if(await yt(e,o.channelId,o.ts,D,t.cookie,!0),u){for(let x of[...s.reactable.map((C,I)=>$e[I].name),At])try{await an(e,o.channelId,o.ts,x,t.cookie)}catch{}await mo([...g.map((x,C)=>$e[C].name),At],(x)=>Ot(e,o.channelId,o.ts,x,t.cookie),(x,C)=>console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${x} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${C instanceof Error?C.message:String(C)})`))}console.error(`\u2713 \u7DE8\u96C6\u3057\u307E\u3057\u305F: ${v(t.link)}`)}async function oy(e,t){let n={kind:"ask",limit:t.limit};if(t.channel)n.channel=t.channel;let o=_i(n);if(!o)console.error(`Error: ${yo}
400
- (${_n()})`),process.exit(oe);let s;if(t.stale){if(s=$i(t.stale),s===void 0)console.error(`Error: --stale needs a duration like 24h / 3d (got ${v(t.stale)})`),process.exit(oe)}let r=[];for(let a of o){if(s!==void 0&&a.sent_at>s)continue;let c=a.as_bot?e.bot:e.user,l=a.permalink||`${a.channel}:${a.ts}`,u="unknown",d=(a.text.split(`
401
- `)[0]??"").replace(/^:question: /,""),f;if(c)try{let g=await vo(c,`${a.channel}:${a.ts}`,a.as_bot?void 0:e.cookie);if(!g?.msg)u="gone";else{let p=gt(typeof g.msg.text==="string"?g.msg.text:"");if(u=p.kind==="resolved"?"answered":p.kind==="other"?"edited":p.kind,p.kind!=="other"&&p.question)d=p.question;if(p.kind==="resolved")f=p.answer}}catch{u="unknown"}if(t.state!=="all"&&u!==t.state)continue;let h={state:u,age_h:Math.round((Date.now()-a.sent_at)/3600000),asBot:!!a.as_bot,channel:a.channel,target:a.target??a.channel,link:l,question:Le(d)};if(f!==void 0)h.answer=f;r.push(h)}if(t.json)console.log(JSON.stringify(r));else{for(let a of r)console.log(`${a.state.padEnd(8)} ${String(a.age_h).padStart(4)}h ${a.asBot?"bot ":"user"} ${v(a.target)} ${a.link}
401
+ `+` slack ask --void='${v(t.link)}' --reask${t.asBot?" --as-bot":""} \u2026`),process.exit(Z);if(!([...`${i}
402
+ ${a}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].some((S)=>S[1]!==n?.userId)||/<!(?:here|channel|everyone)/.test(`${i}
403
+ ${a}`)||o.channelId.startsWith("D")))console.error("\u2717 \u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u8CEA\u554F\u306B\u306A\u308A\u307E\u3059 \u2014 \u56DE\u7B54\u3067\u304D\u308B\u4EBA\u3092 @ \u3067\u6B8B\u3057\u3066\u304F\u3060\u3055\u3044"),process.exit(Z);let h=t.lang?pi({flag:t.lang})?.lang??s.lang:s.lang,y=l.slice(0,ht),f=l.slice(ht),g=typeof o.msg.text==="string"?o.msg.text:"",w=wi(i,a,y,f,s.threadOnly,h),D=fo(g);if(D.length)w=po(w,D,h);if(Be(w,t.allowUrlAdjacent),w===g){console.error("\u5909\u66F4\u306F\u3042\u308A\u307E\u305B\u3093\u3002");return}let k=ue("ask-edit",`${o.channelId}:${o.ts}`,w,n?.userId??"");if(t.code!==k){let S=(C,F,A)=>F===A?[` ${C}: (unchanged)`]:[` ${C}:`,...F.split(`
404
+ `).map((O)=>` - ${O}`),...A.split(`
405
+ `).map((O)=>` + ${O}`)];pe(t.code,k,["--- Editing question --------------------------",he(n,{asBot:t.asBot}),` ${v(t.link)}`,...S("Question",s.question,i),...S("Body",s.body,a),...u?[" Choices (nobody has answered yet \u2014 pills are re-seeded):",...c.map((C,F)=>` - ${F+1}. ${_e(C)}`),...l.map((C,F)=>` + ${F+1}. ${_e(C)}`)]:[" Choices: (unchanged)"],...h!==s.lang?[` Language: ${s.lang} \u2192 ${h} (the instructions are rewritten)`]:[],"----------------------------------------------"])}if(await yt(e,o.channelId,o.ts,w,t.cookie,!0),u){for(let S of[...s.reactable.map((C,F)=>Ee[F].name),At])try{await cn(e,o.channelId,o.ts,S,t.cookie)}catch{}await yo([...y.map((S,C)=>Ee[C].name),At],(S)=>Ot(e,o.channelId,o.ts,S,t.cookie),(S,C)=>console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${S} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${C instanceof Error?C.message:String(C)})`))}console.error(`\u2713 \u7DE8\u96C6\u3057\u307E\u3057\u305F: ${v(t.link)}`)}async function my(e,t){let n={kind:"ask",limit:t.limit};if(t.channel)n.channel=t.channel;let o=Ti(n);if(!o)console.error(`Error: ${ds}
406
+ (${lt()})`),process.exit(Z);let s;if(t.stale){if(s=ko(t.stale),s===void 0)console.error(`Error: --stale needs a duration like 24h / 3d (got ${v(t.stale)})`),process.exit(Z)}let r=[];for(let a of o){if(s!==void 0&&a.sent_at>s)continue;let c=a.as_bot?e.bot:e.user,l=a.permalink||`${a.channel}:${a.ts}`,u="unknown",d=(a.text.split(`
407
+ `)[0]??"").replace(/^:question: /,""),p;if(c)try{let y=await Ko(c,{channelId:a.channel,ts:a.ts,threadTs:a.thread_ts??void 0},a.as_bot?void 0:e.cookie);if(!y.msg)u="gone";else{let f=gt(typeof y.msg.text==="string"?y.msg.text:"");if(u=f.kind==="resolved"?"answered":f.kind==="other"?"edited":f.kind,f.kind!=="other"&&f.question)d=f.question;if(f.kind==="resolved")p=f.answer}}catch{u="unknown"}if(t.state!=="all"&&u!==t.state)continue;let h={state:u,age_h:Math.round((Date.now()-a.sent_at)/3600000),asBot:!!a.as_bot,channel:a.channel,target:a.target??a.channel,link:l,question:_e(d)};if(p!==void 0)h.answer=p;r.push(h)}if(t.json)console.log(JSON.stringify(r));else{for(let a of r)console.log(`${a.state.padEnd(8)} ${String(a.age_h).padStart(4)}h ${a.asBot?"bot ":"user"} ${v(a.target)} ${a.link}
402
408
  ${v(a.question).slice(0,100)}`);console.error(`${r.length} question(s)${t.state==="all"?"":` in state "${t.state}"`}${t.stale?`, older than ${t.stale}`:""}.`)}let i=r.filter((a)=>a.state==="open");if(t.stale&&i.length)for(let a of[!1,!0]){let c=i.filter((l)=>l.asBot===a);if(!c.length)continue;console.error(`\u7121\u52B9\u5316\u3059\u308B\u306A\u3089 (${c.length} \u4EF6, ${a?"bot":"user"}):
403
- slack ask ${c.map((l)=>`--void='${l.link}'`).join(" ")} --reason 'stale'${a?" --as-bot":""}`)}}async function Ef(e,t,n,o,s){let r=v(t.link);try{let i=Xl(t.parsed.question,n,t.parsed.lang,t.parsed.body||void 0,o);await yt(e,t.channelId,t.ts,i,s,!0)}catch(i){return console.error(`\u2717 ${r}: \u66F8\u304D\u63DB\u3048\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${i instanceof Error?i.message:String(i)}`),!1}for(let i of[...t.parsed.reactable.map((a,c)=>$e[c].name),At])try{await an(e,t.channelId,t.ts,i,s)}catch{}try{await Ot(e,t.channelId,t.ts,fi,s)}catch(i){console.error(` (${r}: \uD83D\uDEAB \u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${i instanceof Error?i.message:String(i)})`)}return console.error(`\u2713 \u7121\u52B9\u5316: ${r}`),!0}async function ry(e,t){let n=await Ue(e,t.cookie);if(t.supersededBy){let a=v(t.supersededBy),c=!1;try{let l=await vo(e,t.supersededBy,t.cookie);if(c=!!l?.msg,!l)console.error(`Error: --superseded-by must be a message permalink (or 'C\u2026:1700000000.000100'): ${a}`),process.exit(oe)}catch(l){console.error(`Error: --superseded-by \u3092\u78BA\u8A8D\u3067\u304D\u307E\u305B\u3093: ${a} (${l instanceof Error?l.message:String(l)})`),process.exit(oe)}if(!c)console.error(`Error: --superseded-by \u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${a}`),process.exit(oe)}let o=[],s=0;for(let a of t.links){let c=v(a),l=await vo(e,a,t.cookie);if(!l){console.error(`\u2717 ${c}: permalink (\u307E\u305F\u306F 'C\u2026:1700000000.000100') \u3067\u306F\u3042\u308A\u307E\u305B\u3093`),s++;continue}if(!l.msg){console.error(`\u2717 ${c}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`),s++;continue}let u=l.msg;if(!(!!n?.userId&&u.user===n.userId||!!n?.botId&&u.bot_id===n.botId)){console.error(`\u2717 ${c}: \u81EA\u5206\uFF08${Mo(n,t.asBot)}\uFF09\u304C\u6295\u7A3F\u3057\u305F\u8CEA\u554F\u3067\u306F\u306A\u3044\u306E\u3067\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093`+`${t.asBot?"":" \u2014 bot \u304C\u51FA\u3057\u305F\u8CEA\u554F\u306A\u3089 --as-bot \u3067"}`),s++;continue}let f=typeof u.text==="string"?u.text:"",h=gt(f),g=!1;if(h.kind==="void"){console.error(`- ${c}: \u3059\u3067\u306B\u7121\u52B9\u5316\u6E08\u307F\u3067\u3059\uFF08\u4F55\u3082\u3057\u307E\u305B\u3093\uFF09`);continue}if(h.kind==="resolved"){console.error(`\u2717 ${c}: \u56DE\u7B54\u6E08\u307F\u306E\u8CEA\u554F\u306F\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093\uFF08\u56DE\u7B54: ${v(h.answer.split(`
404
- `)[0]??"")}\uFF09`),s++;continue}if(h.kind!=="open"){let m=Vl(f);if(!m){console.error(`\u2717 ${c}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093 \u2014 ${fo(f)}`),s++;continue}let D=H(u.reactions).map(_).filter((w)=>H(w.users).includes(n?.userId??"\x00")).map((w)=>$e.findIndex((k)=>k.name===w.name)).filter((w)=>w>=0);h={kind:"open",question:m.question,body:m.body,reactable:Array.from({length:D.length?Math.max(...D)+1:0},()=>""),overflow:[],threadOnly:!0,lang:ui(f)??"ja"},g=!0}let p=H(u.reactions).map(_).filter((m)=>typeof m.name==="string"&&$e.some((D)=>D.name===m.name)).filter((m)=>H(m.users).some((D)=>D!==n?.userId)).map((m)=>`:${String(m.name)}:`);o.push({link:a,channelId:l.channelId,ts:l.ts,text:f,parsed:h,pressed:p,...g?{unreadable:g}:{}})}if(!o.length)console.error(s?"\u7121\u52B9\u5316\u3067\u304D\u308B\u8CEA\u554F\u304C\u3042\u308A\u307E\u305B\u3093\u3002":"\u4F55\u3082\u3059\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u305B\u3093\u3002"),process.exit(s?oe:0);let r=ge("ask-void",...o.map((a)=>`${a.channelId}:${a.ts}`),t.reason,t.supersededBy??"",n?.userId??"");if(t.code!==r)De(t.code,r,["--- \u7121\u52B9\u5316 (void) -------------------------------",we(n,{asBot:t.asBot}),` Reason: ${t.reason?v(t.reason):"(none)"}`,...t.supersededBy?[` Replaced: ${v(t.supersededBy)}`]:[],` ${o.length} question(s):`,...o.map((a)=>` \u2022 ${v(a.link)}
409
+ slack ask ${c.map((l)=>`--void='${l.link}'`).join(" ")} --reason 'stale'${a?" --as-bot":""}`)}}async function yy(e,t){let n=Ou(t.sinceMs);if(!n)console.error(`Error: ${ds}
410
+ (${lt()})`),process.exit(Z);let o=t.channel?n.filter((l)=>l.channel===t.channel||l.target===t.channel):n,s=[],r={unanswered:0,ambiguous:0,resolved:0,void:0},i=[],a=e.user?(await Te(e.user,e.cookie))?.team??"":e.bot?(await Te(e.bot))?.team??"":"",c=new Map;for(let l of o){if(l.team&&a&&l.team!==a){c.set(l.team,(c.get(l.team)??0)+1);continue}let u=l.permalink||`${l.channel}:${l.ts}`,d=!!l.as_bot,p=d?e.bot:e.user;if(!p){i.push(`${u}: ${d?"--as-bot \u3067\u805E\u3044\u305F\u8CEA\u554F\u3067\u3059\u304C bot token \u304C\u3042\u308A\u307E\u305B\u3093":"user token \u304C\u3042\u308A\u307E\u305B\u3093"}`);continue}let h=d?void 0:e.cookie,y=l.delivered_cursor??void 0;try{let f={channelId:l.channel,ts:l.ts,threadTs:l.thread_ts??void 0},g=await Ko(p,f,h);if(!g.msg){i.push(`${u}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093 (\u524A\u9664?)`);continue}let w=await Pf(p,{channelId:l.channel,ts:l.ts,msg:g.msg},h),D=w.parsed;if(D.kind==="resolved"){r.resolved++;continue}if(D.kind==="void"){r.void++;continue}if(D.kind==="other"){i.push(`${u}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u3081\u307E\u305B\u3093 \u2014 ${as(w.text)}`);continue}if(!w.audience.size&&!w.broadcast){i.push(`${u}: \u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u8CEA\u554F\u3067\u3059`);continue}let k=vf(w,D,f,{timeout:0,link:u,asBot:d,json:!1,cookie:h,after:y}),S=Af(p,k,!0),C=await S.poll(),F=S.state.unchosen;if(S.state.voided){r.void++;continue}let A=vn(u,d,y),O={row:l,link:u,question:D.question,collect:A,alive:Ru(l)};if(C)s.push({...O,answer:C.answer,how:C.how,freeText:!1});else if(F&&!F.ambiguous&&F.text!==l.delivered_answer)s.push({...O,answer:F.text,how:"\u8FD4\u4FE1 (\u9078\u629E\u80A2\u5916)",freeText:!0});else if(F?.ambiguous)r.ambiguous++;else r.unanswered++}catch(f){i.push(`${u}: ${f instanceof Error?f.message:String(f)}`)}}if(t.json)for(let l of s){let u=l.row;console.log(JSON.stringify({id:u.id,link:l.link,channel:u.channel,ts:u.ts,asked_at:u.sent_at,question:l.question,answer:l.answer,how:l.how,free_text:l.freeText,sender:{session_id:u.session_id??null,cli:u.cli??null,agent_pid:u.agent_pid??null,pid:u.pid,alive:l.alive,cwd:u.cwd,git_branch:u.git_branch??null,host:u.host??null},delivered_at:u.delivered_at??null,collect:l.collect}))}else{let l=new Map;for(let u of s){let d=u.row.session_id?`session ${u.row.session_id}`:`pid ${u.row.agent_pid??u.row.pid}`;l.set(d,[...l.get(d)??[],u])}for(let[u,d]of l){let p=d[0].row;console.log(`${v(u)} ${v(p.cli??"?")} pid ${p.agent_pid??p.pid} ${d[0].alive?"(alive)":"(gone)"}${p.git_branch?` branch=${v(p.git_branch)}`:""} cwd=${v(p.cwd)}`);for(let h of d)console.log(` ${v(h.link)} (${Ds(h.row.sent_at/1000)})`),console.log(` Q: ${v(_e(h.question))}`),console.log(` A: ${v(_e(h.answer))} \u2014 ${v(h.how)}${h.freeText?" \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093":""}`),console.log(` collect: ${v(h.collect)}`)}}for(let l of i)console.error(` (${v(l)})`);for(let[l,u]of c)console.error(` (${u} \u4EF6\u306F\u5225\u306E\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u300C${v(l)}\u300D\u306E\u8CEA\u554F\u3067\u3059 \u2014 slack -w <name> ask --pending \u3067\u78BA\u8A8D)`);console.error(`${s.length} \u4EF6\u304C\u56DE\u7B54\u6E08\u307F\u30FB\u672A\u56DE\u53CE, ${r.unanswered} \u4EF6\u304C\u672A\u56DE\u7B54`+(r.ambiguous?`, ${r.ambiguous} \u4EF6\u306F\u8FD4\u4FE1\u304C\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4 (\u672A\u78BA\u5B9A)`:"")+(r.resolved?`, ${r.resolved} \u4EF6\u306F \u2705 \u56DE\u53CE\u6E08\u307F`:"")+(r.void?`, ${r.void} \u4EF6\u306F\u7121\u52B9\u5316\u6E08\u307F`:"")+` \u2014 ${o.length} \u4EF6\u306E\u672A\u56DE\u53CE\u306E\u8CEA\u554F\u3092\u78BA\u8A8D (log: ${lt()})`)}async function Rf(e,t,n,o,s){let r=v(t.link);try{let i=tu(t.parsed.question,n,t.parsed.lang,t.parsed.body||void 0,o);await yt(e,t.channelId,t.ts,i,s,!0)}catch(i){return console.error(`\u2717 ${r}: \u66F8\u304D\u63DB\u3048\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${i instanceof Error?i.message:String(i)}`),!1}for(let i of[...t.parsed.reactable.map((a,c)=>Ee[c].name),At])try{await cn(e,t.channelId,t.ts,i,s)}catch{}try{await Ot(e,t.channelId,t.ts,mi,s)}catch(i){console.error(` (${r}: \uD83D\uDEAB \u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${i instanceof Error?i.message:String(i)})`)}return console.error(`\u2713 \u7121\u52B9\u5316: ${r}`),!0}async function wy(e,t){let n=await Te(e,t.cookie);if(t.supersededBy){let a=v(t.supersededBy),c=!1;try{let l=await oa(e,t.supersededBy,t.cookie);if(c=!!l?.msg,!l)console.error(`Error: --superseded-by must be a message permalink (or 'C\u2026:1700000000.000100'): ${a}`),process.exit(Z)}catch(l){console.error(`Error: --superseded-by \u3092\u78BA\u8A8D\u3067\u304D\u307E\u305B\u3093: ${a} (${l instanceof Error?l.message:String(l)})`),process.exit(Z)}if(!c)console.error(`Error: --superseded-by \u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${a}`),process.exit(Z)}let o=[],s=0;for(let a of t.links){let c=v(a),l=await oa(e,a,t.cookie);if(!l){console.error(`\u2717 ${c}: permalink (\u307E\u305F\u306F 'C\u2026:1700000000.000100') \u3067\u306F\u3042\u308A\u307E\u305B\u3093`),s++;continue}if(!l.msg){console.error(`\u2717 ${c}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`),s++;continue}let u=l.msg;if(!(!!n?.userId&&u.user===n.userId||!!n?.botId&&u.bot_id===n.botId)){console.error(`\u2717 ${c}: \u81EA\u5206\uFF08${Uo(n,t.asBot)}\uFF09\u304C\u6295\u7A3F\u3057\u305F\u8CEA\u554F\u3067\u306F\u306A\u3044\u306E\u3067\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093`+`${t.asBot?"":" \u2014 bot \u304C\u51FA\u3057\u305F\u8CEA\u554F\u306A\u3089 --as-bot \u3067"}`),s++;continue}let p=typeof u.text==="string"?u.text:"",h=gt(p),y=!1;if(h.kind==="void"){console.error(`- ${c}: \u3059\u3067\u306B\u7121\u52B9\u5316\u6E08\u307F\u3067\u3059\uFF08\u4F55\u3082\u3057\u307E\u305B\u3093\uFF09`);continue}if(h.kind==="resolved"){console.error(`\u2717 ${c}: \u56DE\u7B54\u6E08\u307F\u306E\u8CEA\u554F\u306F\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093\uFF08\u56DE\u7B54: ${v(h.answer.split(`
411
+ `)[0]??"")}\uFF09`),s++;continue}if(h.kind!=="open"){let g=nu(p);if(!g){console.error(`\u2717 ${c}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093 \u2014 ${as(p)}`),s++;continue}let w=H(u.reactions).map(T).filter((D)=>H(D.users).includes(n?.userId??"\x00")).map((D)=>Ee.findIndex((k)=>k.name===D.name)).filter((D)=>D>=0);h={kind:"open",question:g.question,body:g.body,reactable:Array.from({length:w.length?Math.max(...w)+1:0},()=>""),overflow:[],threadOnly:!0,lang:hi(p)??"ja"},y=!0}let f=H(u.reactions).map(T).filter((g)=>typeof g.name==="string"&&Ee.some((w)=>w.name===g.name)).filter((g)=>H(g.users).some((w)=>w!==n?.userId)).map((g)=>`:${String(g.name)}:`);o.push({link:a,channelId:l.channelId,ts:l.ts,text:p,parsed:h,pressed:f,...y?{unreadable:y}:{}})}if(!o.length)console.error(s?"\u7121\u52B9\u5316\u3067\u304D\u308B\u8CEA\u554F\u304C\u3042\u308A\u307E\u305B\u3093\u3002":"\u4F55\u3082\u3059\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u305B\u3093\u3002"),process.exit(s?Z:0);let r=ue("ask-void",...o.map((a)=>`${a.channelId}:${a.ts}`),t.reason,t.supersededBy??"",n?.userId??"");if(t.code!==r)pe(t.code,r,["--- \u7121\u52B9\u5316 (void) -------------------------------",he(n,{asBot:t.asBot}),` Reason: ${t.reason?v(t.reason):"(none)"}`,...t.supersededBy?[` Replaced: ${v(t.supersededBy)}`]:[],` ${o.length} question(s):`,...o.map((a)=>` \u2022 ${v(a.link)}
405
412
  ${v(a.parsed.question.split(`
406
413
  `)[0]??"").slice(0,100)}`+(a.pressed.length?`
407
414
  (already pressed: ${a.pressed.join(" ")} \u2014 left in place, never collected)`:"")+(a.unreadable?`
408
- \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 \u2753 come off; a \uD83D\uDEAB reaction is added.",...s?[` (${s} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let i=0;for(let a of o)if(!await Ef(e,a,t.reason,t.supersededBy,t.cookie))i++;process.exit(i||s?oe:0)}async function iy(e,t){let n=Rt(t.link),o,s,r;if(n?.ts)o=n.channel,s=n.ts,r=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let 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').
409
- `+` Got: ${v(t.link)}`),process.exit(oe);o=g[1],s=g[2]}let i;if(r){let g=_(await Ie(e,o,r,100,t.cookie));i=H(g.messages).map(_).find((p)=>p.ts===s)}else{let g=_(await je(e,o,1,s,void 0,t.cookie,!0));i=H(g.messages).map(_).find((p)=>p.ts===s)}if(!i)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${v(t.link)}`),process.exit(oe);let a=typeof i.text==="string"?i.text:"",c=gt(a);if(c.kind==="other")console.error("Error: \u3053\u308C\u306F `slack ask` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093\u3002\n"+` \u7406\u7531: ${fo(a)}
415
+ \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 \u2753 come off; a \uD83D\uDEAB reaction is added.",...s?[` (${s} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let i=0;for(let a of o)if(!await Rf(e,a,t.reason,t.supersededBy,t.cookie))i++;process.exit(i||s?Z:0)}async function Dy(e,t){let n=Rt(t.link),o,s,r;if(n?.ts)o=n.channel,s=n.ts,r=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let f=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!f)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
416
+ `+` Got: ${v(t.link)}`),process.exit(Z);o=f[1],s=f[2]}let i=await Ko(e,{channelId:o,ts:s,threadTs:r},t.cookie);if(!i.msg)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${v(t.link)}`),process.exit(Z);let a=i.msg,c=await Pf(e,{channelId:o,ts:s,msg:a},t.cookie),{text:l,parsed:u,audience:d,broadcast:p,askerUserId:h,askerBotId:y}=c;if(u.kind==="other")console.error("Error: \u3053\u308C\u306F `slack ask` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093\u3002\n"+` \u7406\u7531: ${as(l)}
410
417
  ${v(t.link)}
411
- `+` (\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306F\u6B8B\u3063\u3066\u3044\u307E\u3059: slack read '${v(t.link)}' \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059)`),process.exit(oe);let l=typeof i.user==="string"?i.user:"",u=typeof i.bot_id==="string"?i.bot_id:"",d=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(a),f=new Set;for(let g of a.matchAll(/<@([UW][A-Z0-9]+)>/g))if(g[1]!==l)f.add(g[1]);if(!f.size&&!d){let g=await jo(e,o,t.cookie);if(g&&g!==l)f.add(g)}if(c.kind==="void"){if(kf(c,t.link),t.json)await fn(e,{json:!0,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"void",answer:null,reason:c.reason,...c.supersededBy?{supersededBy:c.supersededBy}:{},notes:[],cursor:dn(s,t.after)});process.exit(yf)}if(c.kind==="resolved"){console.error(`\u2713 \u56DE\u7B54\u6E08\u307F: ${v(c.question)}`);let g=typeof _(i.edited).ts==="string"?String(_(i.edited).ts):void 0,p=Ql(a),m=!1,D=(x)=>{if(m||!p.byReply)return!1;if(g&&Number(x.ts)>Number(g))return!1;let C=typeof x.text==="string"?x.text.trim():"",I=C===c.answer||p.n!==void 0&&(new RegExp(`^[(\uFF08]?${p.n}(?![0-9])`).test(C)||eu(C,c.answer,p.n));if(I)m=!0;return I},w=t.after,k=[];if(f.size||d){let x=(C)=>typeof C==="string"&&!!C&&C!==l&&(d||f.has(C));k=await wf(e,{channelId:o,ts:s,threadOnly:!!r||!o.startsWith("D"),replyCount:Number(i.reply_count)||0,isAnswerer:x,askerUserId:l,askerBotId:u,...r?{threadParentTs:r}:{},...t.cookie?{cookie:t.cookie}:{}},w,D)}await fn(e,{json:t.json,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"answered",answer:c.answer,notes:k,cursor:dn(s,w,...k.map((x)=>x.ts))});return}if(!f.size&&!d)console.error(`Error: \u3053\u306E\u8CEA\u554F\u306F\u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u6709\u52B9\u306A\u56DE\u7B54\u8005\u3092\u5224\u5B9A\u3067\u304D\u307E\u305B\u3093: ${v(t.link)}`),process.exit(oe);if(t.timeout>0)console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${t.timeout}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let h={channelId:o,ts:s,question:c.question,reactable:c.reactable,overflow:c.overflow,threadOnly:c.threadOnly,lang:c.lang,audience:f,broadcast:d,askerUserId:l,askerBotId:u,timeout:t.timeout,shown:t.link,asBot:t.asBot,json:t.json};if(r)h.threadParentTs=r;if(t.cookie)h.cookie=t.cookie;if(t.after)h.after=t.after;await bf(e,h)}var nt=3;function ay(e){return`slack poll --results='${e}'`}async function cy(e,t){let{ref:n,threadTs:o}=vn(t.target,!1),s=t.cookie,r=bt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Dt(e,t.userId,s);else i=await ye(e,n,s);let a=(await r())?.userId??"",c=await jo(e,i,s);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.
412
- `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let l=xs(Oe(t.question)),u=xs(Oe(t.body??"")),d=t.mentionToken??e,f=await Lt(d,l.text,i,t.mentionCookie),h=u.text?await Lt(d,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},g=f.text,p=h.text;for(let P of ms([...f.unresolved,...h.unresolved]))console.error(`\u26A0 ${v(P)}`);let m=t.choices.map(Oe),D=!!t.multi,w=t.until??"",k=lu(g,p,m,{multi:D,deadline:w});Ne(k,t.allowUrlAdjacent);let x="",C="?";try{let P=await je(e,i,1,void 0,void 0,s),W=H(P.messages).map(_).filter((te)=>te.subtype===void 0||te.subtype===null)[0];x=typeof W?.text==="string"?W.text:"",C=typeof W?.user==="string"?await Te(e,W.user,s):typeof W?.username==="string"?W.username:"?"}catch{}let I=await r(),A=await No(e,i,s),M=ge(i,o??"",x,k,I?.userId??"");if(t.code!==M){let P=await Mt(e,i,n,s);De(t.code,M,["--- Last message in channel ------------------",` ${C}: ${ys(x.split(`
413
- `)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...m.map((W,te)=>` ${lt[te].glyph} ${is(W)}`),"--- Posting ----------------------------------",we(I,{asBot:t.asBot}),` \u2192 ${P}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${g}`,` Rule: ${D?"1 \u4EBA \u4F55\u7968\u3067\u3082 (--multi)":"1 \u4EBA 1 \u7968"}${w?` \u2014 \u7DE0\u5207 ${w}`:""}`," Note: \u3042\u306A\u305F\u81EA\u8EAB\u306E\u7968\u306F\u6570\u3048\u307E\u305B\u3093 (\u30D4\u30EB\u306F\u3042\u306A\u305F\u304C\u4ED8\u3051\u305F\u7A2E\u306A\u306E\u3067\u533A\u5225\u3067\u304D\u307E\u305B\u3093)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],A)}let X=pn("poll"),re=await rn(e,i,k,o,!1,s,!0,X.metadata);await mo([as,...m.map((P,W)=>lt[W].name)],(P)=>Ot(e,i,re,P,s),(P,W)=>{let te=W instanceof Error?W.message:String(W);if(P===as)console.error(` (marker ${P} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${te})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${P} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${te})`)});let L="";try{L=await Fn(e,i,re,s)}catch{}let T=L||`${i}:${re}`;console.error(`\u2713 Posted: ${T}`),X.record({team:I?.team,channel:i,target:t.target,ts:re,threadTs:o,permalink:L,text:k,asBot:t.asBot}),console.log(ay(T)),console.error(` \u7DE0\u3081\u5207\u308B: slack poll --close='${T}'${t.asBot?" --as-bot":""}`)}async function ly(e,t,n){let o=Rt(t),s,r,i;if(o?.ts)s=o.channel,r=o.ts,i=o.threadTs&&o.threadTs!==o.ts?o.threadTs:void 0;else{let 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').
414
- `+` Got: ${v(t)}`),process.exit(nt);s=c[1],r=c[2]}let a;if(i){let c=_(await Ie(e,s,i,100,n));a=H(c.messages).map(_).find((l)=>l.ts===r)}else{let c=_(await je(e,s,1,r,void 0,n,!0));a=H(c.messages).map(_).find((l)=>l.ts===r)}if(!a)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${v(t)}`),process.exit(nt);return{channelId:s,ts:r,msg:a}}function tf(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,o)=>`${lt[o].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function uy(e,t){let{channelId:n,ts:o,msg:s}=await ly(e,t.link,t.cookie),r=typeof s.text==="string"?s.text:"",i=cs(r);if(i.kind==="other")console.error("Error: \u3053\u308C\u306F `slack poll` \u306E\u6295\u7968\u3067\u306F\u3042\u308A\u307E\u305B\u3093 (\u7968\u306E\u6570\u3048\u65B9\u304C\u5206\u304B\u308A\u307E\u305B\u3093)\u3002\n"+` ${v(t.link)}`),process.exit(nt);if(i.kind==="closed"){console.error(`\u2713 \u6295\u7968\u7D42\u4E86: ${v(i.question)}`);for(let h of tf(i.tallies))console.log(h);return}let a=new Set;if(typeof s.user==="string"&&s.user)a.add(s.user);let c=await Ku(e,n,o,t.cookie),l=du(i.choices,c,a,i.multi);console.error(`${v(i.question)}${i.deadline?` (\u7DE0\u5207 ${i.deadline})`:""}`);for(let h of tf(l.tallies))console.log(h);let u=l.tallies.reduce((h,g)=>h+g.count,0);if(console.error(` \u8A08 ${u} \u7968${i.multi?" (\u8907\u6570\u9078\u629E\u53EF)":""}`),t.names)for(let h=0;h<l.voters.length;h++){if(!l.voters[h].length)continue;let g=await Promise.all(l.voters[h].map((p)=>Te(e,p,t.cookie)));console.error(` ${lt[h].glyph} ${g.map((p)=>`@${v(p)}`).join(", ")}`)}let d=i.multi?[]:l.ambiguous,f=uo(r,d);if(f!==r&&!t.noNotify)try{await yt(t.writeToken??e,n,o,f,t.writeToken?t.writeCookie:t.cookie,!0)}catch(h){console.error(` (\u6295\u7968\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${h instanceof Error?h.message:String(h)})
415
- `+" \u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u66F8\u304D\u63DB\u3048\u3089\u308C\u308B\u306E\u306F\u6295\u7A3F\u8005\u3060\u3051\u3067\u3059 \u2014 bot \u304C\u6295\u7A3F\u3057\u305F\u6295\u7968\u306A\u3089 --as-bot \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002")}if(l.ambiguous.length){let h=await Promise.all(l.ambiguous.map((g)=>Te(e,g,t.cookie)));console.error(`\u26A0 1 \u4EBA 1 \u7968\u306A\u306E\u306B\u8907\u6570\u62BC\u3057\u3066\u3044\u308B\u4EBA\u304C\u3044\u307E\u3059 (\u7121\u52B9\u7968): ${h.map((g)=>`@${v(g)}`).join(", ")}`)}if(!t.close)return;await yt(t.writeToken??e,n,o,uu(i.question,l.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await Ot(t.writeToken??e,n,o,bi,t.writeToken?t.writeCookie:t.cookie),await an(t.writeToken??e,n,o,as,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 \u6295\u7968\u3092\u7DE0\u3081\u5207\u308A\u307E\u3057\u305F: ${v(t.link)}`)}async function dy(e){let t=await Qs(e);for(let n of eo(t,!1))console.log(n);if(!t.ok)process.exit(1)}function Ao(){let e=ze();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
416
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function nf(e,t,n,o){let s=await wt(n,e,o);return Dt(t,s)}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 hy(e,t){Ne(t.message,t.allowUrlAdjacent);let n=bt(e,t.cookie),{ref:o,threadTs:s}=vn(t.target),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await Dt(e,t.userId,t.cookie);else r=await ye(e,o,t.cookie);let i=fy(t.at),a=new Date(i*1000).toISOString(),c=await n();if(!t.asBot&&await ra(e,r,c?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
417
- `+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let l=ge(r,t.message,String(i),c?.userId??""),u=t.targetOverride?` [${t.targetOverride} \u2192 ${r}]`:"";if(t.code!==l){let f=await No(e,r,t.cookie);De(t.code,l,["--- Scheduling message -----------------------",we(c,{asBot:t.asBot,pad:9}),` To: ${o}${s?` (thread ${s})`:""}${u}`,` At: ${py(i)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(i*1000))}let d=await Mu(e,r,t.message,i,s,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${a})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
418
+ `+` (\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306F\u6B8B\u3063\u3066\u3044\u307E\u3059: slack read '${v(t.link)}' \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059)`),process.exit(Z);if(u.kind==="void"){if(If(u,t.link),t.json)await fn(e,{json:!0,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"void",answer:null,reason:u.reason,...u.supersededBy?{supersededBy:u.supersededBy}:{},notes:[],cursor:Lt(s,t.after)});process.exit(Cf)}if(u.kind==="resolved"){console.error(`\u2713 \u56DE\u7B54\u6E08\u307F: ${v(u.question)}`);let f=typeof T(a.edited).ts==="string"?String(T(a.edited).ts):void 0,g=ou(l),w=!1,D=(F)=>{if(w||!g.byReply)return!1;if(f&&Number(F.ts)>Number(f))return!1;let A=typeof F.text==="string"?F.text.trim():"",O=A===u.answer||g.n!==void 0&&(new RegExp(`^[(\uFF08]?${g.n}(?![0-9])`).test(A)||ru(A,u.answer,g.n));if(O)w=!0;return O},k=t.after,S=[];if(d.size||p){let F=(A)=>typeof A==="string"&&!!A&&A!==h&&(p||d.has(A));S=await Ff(e,{channelId:o,ts:s,threadOnly:!!r||!o.startsWith("D"),replyCount:Number(a.reply_count)||0,isAnswerer:F,askerUserId:h,askerBotId:y,...r?{threadParentTs:r}:{},...t.cookie?{cookie:t.cookie}:{}},k,D)}let C=Lt(s,k,...S.map((F)=>F.ts));await fn(e,{json:t.json,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"answered",answer:u.answer,notes:S,cursor:C}),Ii(o,s,u.answer,C);return}if(!d.size&&!p)console.error(`Error: \u3053\u306E\u8CEA\u554F\u306F\u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u6709\u52B9\u306A\u56DE\u7B54\u8005\u3092\u5224\u5B9A\u3067\u304D\u307E\u305B\u3093: ${v(t.link)}`),process.exit(Z);if(t.timeout>0)console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${t.timeout}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);await Tf(e,vf(c,u,{channelId:o,ts:s,threadTs:r},t))}async function Pf(e,t,n){let{msg:o}=t,s=typeof o.text==="string"?o.text:"",r=gt(s),i=typeof o.user==="string"?o.user:"",a=typeof o.bot_id==="string"?o.bot_id:"",c=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(s),l=new Set;for(let u of s.matchAll(/<@([UW][A-Z0-9]+)>/g))if(u[1]!==i)l.add(u[1]);if(r.kind!=="other"&&!l.size&&!c){let u=await Jo(e,t.channelId,n);if(u&&u!==i)l.add(u)}return{text:s,parsed:r,audience:l,broadcast:c,askerUserId:i,askerBotId:a}}function vf(e,t,n,o){let s={channelId:n.channelId,ts:n.ts,question:t.question,reactable:t.reactable,overflow:t.overflow,threadOnly:t.threadOnly,lang:t.lang,audience:e.audience,broadcast:e.broadcast,askerUserId:e.askerUserId,askerBotId:e.askerBotId,timeout:o.timeout,shown:o.link,asBot:o.asBot,json:o.json};if(n.threadTs)s.threadParentTs=n.threadTs;if(o.cookie)s.cookie=o.cookie;if(o.after)s.after=o.after;return s}var Qe=3;function by(e){return`slack poll --results='${e}'`}async function ky(e,t){let{ref:n,threadTs:o}=Bn(t.target,!1),s=t.cookie,r=bt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await wt(e,t.userId,s);else i=await fe(e,n,s);let a=(await r())?.userId??"",c=await Jo(e,i,s);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.
419
+ `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let l=Ss(Fe(t.question)),u=Ss(Fe(t.body??"")),d=t.mentionToken??e,p=await Bt(d,l.text,i,t.mentionCookie),h=u.text?await Bt(d,u.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},y=p.text,f=h.text;for(let R of Fo([...p.unresolved,...h.unresolved]))console.error(`\u26A0 ${v(R)}`);let g=t.choices.map(Fe),w=!!t.multi,D=t.until??"",k=hu(y,f,g,{multi:w,deadline:D});Be(k,t.allowUrlAdjacent);let S="",C="?";try{let R=await He(e,i,1,void 0,void 0,s),L=H(R.messages).map(T).filter((W)=>W.subtype===void 0||W.subtype===null)[0];S=typeof L?.text==="string"?L.text:"",C=typeof L?.user==="string"?await $e(e,L.user,s):typeof L?.username==="string"?L.username:"?"}catch{}let F=await r(),A=await Wo(e,i,s),O=ue(i,o??"",S,k,F?.userId??"");if(t.code!==O){let R=await jt(e,i,n,s);pe(t.code,O,["--- Last message in channel ------------------",` ${C}: ${bs(S.split(`
420
+ `)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...g.map((L,W)=>` ${it[W].glyph} ${cs(L)}`),"--- Posting ----------------------------------",he(F,{asBot:t.asBot}),` \u2192 ${R}${o?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${y}`,` Rule: ${w?"1 \u4EBA \u4F55\u7968\u3067\u3082 (--multi)":"1 \u4EBA 1 \u7968"}${D?` \u2014 \u7DE0\u5207 ${D}`:""}`," Note: \u3042\u306A\u305F\u81EA\u8EAB\u306E\u7968\u306F\u6570\u3048\u307E\u305B\u3093 (\u30D4\u30EB\u306F\u3042\u306A\u305F\u304C\u4ED8\u3051\u305F\u7A2E\u306A\u306E\u3067\u533A\u5225\u3067\u304D\u307E\u305B\u3093)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],A)}let B=pn("poll"),U=await an(e,i,k,o,!1,s,!0,B.metadata);await yo([ls,...g.map((R,L)=>it[L].name)],(R)=>Ot(e,i,U,R,s),(R,L)=>{let W=L instanceof Error?L.message:String(L);if(R===ls)console.error(` (marker ${R} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${W})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${R} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${W})`)});let P="";try{P=await Fn(e,i,U,s)}catch{}let _=P||`${i}:${U}`;console.error(`\u2713 Posted: ${_}`),B.record({team:F?.team,channel:i,target:t.target,ts:U,threadTs:o,permalink:P,text:k,asBot:t.asBot}),console.log(by(_)),console.error(` \u7DE0\u3081\u5207\u308B: slack poll --close='${_}'${t.asBot?" --as-bot":""}`)}async function xy(e,t,n){let o=Rt(t),s,r,i;if(o?.ts)s=o.channel,r=o.ts,i=o.threadTs&&o.threadTs!==o.ts?o.threadTs:void 0;else{let 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').
421
+ `+` Got: ${v(t)}`),process.exit(Qe);s=c[1],r=c[2]}let a;if(i){let c=T(await Pe(e,s,i,100,n));a=H(c.messages).map(T).find((l)=>l.ts===r)}else{let c=T(await He(e,s,1,r,void 0,n,!0));a=H(c.messages).map(T).find((l)=>l.ts===r)}if(!a)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${v(t)}`),process.exit(Qe);return{channelId:s,ts:r,msg:a}}function uf(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,o)=>`${it[o].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function Ey(e,t){let{channelId:n,ts:o,msg:s}=await xy(e,t.link,t.cookie),r=typeof s.text==="string"?s.text:"",i=us(r);if(i.kind==="other")console.error("Error: \u3053\u308C\u306F `slack poll` \u306E\u6295\u7968\u3067\u306F\u3042\u308A\u307E\u305B\u3093 (\u7968\u306E\u6570\u3048\u65B9\u304C\u5206\u304B\u308A\u307E\u305B\u3093)\u3002\n"+` ${v(t.link)}`),process.exit(Qe);if(i.kind==="closed"){console.error(`\u2713 \u6295\u7968\u7D42\u4E86: ${v(i.question)}`);for(let h of uf(i.tallies))console.log(h);return}let a=new Set;if(typeof s.user==="string"&&s.user)a.add(s.user);let c=await Zu(e,n,o,t.cookie),l=mu(i.choices,c,a,i.multi);console.error(`${v(i.question)}${i.deadline?` (\u7DE0\u5207 ${i.deadline})`:""}`);for(let h of uf(l.tallies))console.log(h);let u=l.tallies.reduce((h,y)=>h+y.count,0);if(console.error(` \u8A08 ${u} \u7968${i.multi?" (\u8907\u6570\u9078\u629E\u53EF)":""}`),t.names)for(let h=0;h<l.voters.length;h++){if(!l.voters[h].length)continue;let y=await Promise.all(l.voters[h].map((f)=>$e(e,f,t.cookie)));console.error(` ${it[h].glyph} ${y.map((f)=>`@${v(f)}`).join(", ")}`)}let d=i.multi?[]:l.ambiguous,p=po(r,d);if(p!==r&&!t.noNotify)try{await yt(t.writeToken??e,n,o,p,t.writeToken?t.writeCookie:t.cookie,!0)}catch(h){console.error(` (\u6295\u7968\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${h instanceof Error?h.message:String(h)})
422
+ `+" \u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u66F8\u304D\u63DB\u3048\u3089\u308C\u308B\u306E\u306F\u6295\u7A3F\u8005\u3060\u3051\u3067\u3059 \u2014 bot \u304C\u6295\u7A3F\u3057\u305F\u6295\u7968\u306A\u3089 --as-bot \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002")}if(l.ambiguous.length){let h=await Promise.all(l.ambiguous.map((y)=>$e(e,y,t.cookie)));console.error(`\u26A0 1 \u4EBA 1 \u7968\u306A\u306E\u306B\u8907\u6570\u62BC\u3057\u3066\u3044\u308B\u4EBA\u304C\u3044\u307E\u3059 (\u7121\u52B9\u7968): ${h.map((y)=>`@${v(y)}`).join(", ")}`)}if(!t.close)return;await yt(t.writeToken??e,n,o,gu(i.question,l.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await Ot(t.writeToken??e,n,o,Si,t.writeToken?t.writeCookie:t.cookie),await cn(t.writeToken??e,n,o,ls,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 \u6295\u7968\u3092\u7DE0\u3081\u5207\u308A\u307E\u3057\u305F: ${v(t.link)}`)}async function Sy(e){let t=await to(e);for(let n of no(t,!1))console.log(n);if(!t.ok)process.exit(1)}function Ro(){let e=Je();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
423
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function df(e,t,n,o){let s=await Dt(n,e,o);return wt(t,s)}function Cy(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 _y(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 $y(e,t){Be(t.message,t.allowUrlAdjacent);let n=bt(e,t.cookie),{ref:o,threadTs:s}=Bn(t.target),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await wt(e,t.userId,t.cookie);else r=await fe(e,o,t.cookie);let i=Cy(t.at),a=new Date(i*1000).toISOString(),c=await n();if(!t.asBot&&await ua(e,r,c?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
424
+ `+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let l=ue(r,t.message,String(i),c?.userId??""),u=t.targetOverride?` [${t.targetOverride} \u2192 ${r}]`:"";if(t.code!==l){let p=await Wo(e,r,t.cookie);pe(t.code,l,["--- Scheduling message -----------------------",he(c,{asBot:t.asBot,pad:9}),` To: ${o}${s?` (thread ${s})`:""}${u}`,` At: ${_y(i)}`,` Message: ${t.message}`,"---------------------------------------------"],p,new Date(i*1000))}let d=await zu(e,r,t.message,i,s,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${a})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
418
425
  `+` slack schedule ls --as-bot
419
- slack schedule rm '${t.target}' ${d} --as-bot`),r.startsWith("D"))try{let f=await Qs(e);if(!f.ok)for(let h of eo(f,!0))console.error(h);else{let h=f.appId?`https://api.slack.com/apps/${f.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${h} \u2192 App Home.`)}}catch{}}}async function sf(e,t,n,o){let s;if(n)s=n;else if(t)s=await ye(e,t,o);let i=(await ju(e,s,o)).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(`
420
- `)[0]?.slice(0,80)??""}`)}}async function of(e,t){let n;if(t.channelId)n=t.channelId;else n=await ye(e,t.target,t.cookie);let o=await Ue(e,t.cookie),s=ge(n,t.id,o?.userId??"");if(t.code!==s)De(t.code,s,["--- Deleting scheduled message ---------------",we(o,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await Wu(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function gy(e,t){if(t.comment!==void 0)Ne(t.comment,t.allowUrlAdjacent);let n=bt(e,t.cookie),{statSync:o,existsSync:s}=await import("fs"),{basename:r}=await import("path");for(let g of t.filePaths)if(!s(g))console.error(`Error: file not found: ${g}`),process.exit(1);let{ref:i,threadTs:a}=vn(t.target),c;if(t.channelId)c=t.channelId;else if(t.userId)c=await Dt(e,t.userId,t.cookie);else c=await ye(e,i,t.cookie);if(await ra(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 l=t.filePaths.length>1,u=t.filePaths.map((g)=>{let p=r(g),m=l?p:t.title??p;return{fp:g,filename:p,title:m,sizeFmt:Bo(o(g).size)}}),d=await n(),f=ge(c,...u.flatMap((g)=>[g.fp,g.title]),d?.userId??"");if(t.code!==f){let g=` To: ${i}${a?` (thread ${a})`:""}`,p=l?[`--- Uploading ${u.length} files ------------------------`,we(d,{pad:7}),g,...u.map((m)=>` ${m.filename} (${m.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",we(d,{pad:7}),g,` File: ${u[0].fp}`,` Title: ${u[0].title}`,` Size: ${u[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];De(t.code,f,p)}let h=u.length;for(let g=0;g<h;g++){let p=u[g],m={title:p.title};if(a!==void 0)m.threadTs=a;if(t.comment!==void 0&&g===0)m.initialComment=t.comment;let{fileId:D,permalink:w}=await id(e,c,p.fp,m,t.cookie),k=h>1?`[${g+1}/${h}] `:"";console.log(`${k}\u2713 Uploaded (file_id: ${D}${w?`, url: ${w}`:""})`)}}async function my(e,t,n){let o=n.channel?await ye(e,n.channel,t):void 0,s=[],r=1,i=1;do{let c={page:r,count:200};if(n.types)c.types=n.types;if(o)c.channel=o;if(n.user)c.user=n.user;let l=_(await Tu(e,c,t));for(let u of H(l.files))s.push(_(u));i=Number(_(l.paging).pages??1),r++}while(s.length<n.limit&&r<=i);let a=s.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 l=String(c.id??""),u=typeof c.name==="string"?c.name:typeof c.title==="string"?c.title:l,d=typeof c.filetype==="string"?c.filetype:"?",f=typeof c.size==="number"?Bo(c.size):"";console.log(`${l} ${d.padEnd(7)} ${f.padStart(9)} ${u}`)}}function Wo(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 yy(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(_(n).text??_(n).name??_(n).value??"")).filter(Boolean).join(", ");for(let n of["rich_text","select","user","date","number","checkbox","email","phone"]){let o=e[n];if(o!=null)return typeof o==="object"?JSON.stringify(o):String(o)}return""}async function Dy(e,t,n,o){let s=Wo(n);if(!s)throw Error(`Not a list ID or list URL: ${n}
421
- `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let r=[],i;do{let c={limit:200};if(i)c.cursor=i;let l=o.asBot?await Oi(Es(),s,c):_(await vu(e,s,c,t));for(let d of H(l.items??l.records))r.push(_(d));let u=_(l.response_metadata).next_cursor;i=typeof u==="string"&&u?u:void 0}while(i&&r.length<o.limit);let a=r.slice(0,o.limit);if(o.format==="jsonl"){for(let c of a)console.log(JSON.stringify(c));return}for(let c of a){let l=String(c.id??""),u=H(c.fields).map(_).map((d)=>{let f=String(d.key??d.column_id??"?"),h=yy(d);return h?`${f}=${h}`:""}).filter(Boolean);console.log(`${l} ${u.join(" | ")}`)}}function Es(){let e=ze();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
422
- `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function Uo(e){let t=[];try{t=(await $n(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).
423
- `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function wy(e,t){try{let n=await Ii(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function Sf(e,t){let n=await Oi(e,t,{limit:1,includeList:!0}),o=yu(_(n.list));if(!o.length)throw Error(`could not read the column schema of list ${t}`);return o}function Jo(e){console.error(de(e)),process.exit(1)}async function by(e){let t=e.cols.map(gu),n=mu(t),o=Es();await Uo(o);let s=await Ue(o),r=ge("lists-create",e.name,JSON.stringify(n),String(e.todo),s?.userId??"");if(e.code!==r)De(e.code,r,["--- Creating Slack List ----------------------",we(s,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((c,l)=>` column: ${c.name} (${c.type}${c.choices?`: ${c.choices.join("/")}`:""})${l===0?" [primary]":""}`),` todo: ${e.todo?"on (adds Completed / Assignee / Due date)":"off"}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let i;try{i=await Iu(o,e.name,n,e.todo)}catch(c){Jo(c)}let a=String(i.list_id??_(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${a})`),console.log(await wy(o,a))}async function ky(e){let t=Wo(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=Es();await Uo(n);let o=await Sf(n,t),r=[{col:o.find((u)=>u.type==="text")??o[0],value:e.text},...Ei(e.sets).map((u)=>({col:ki(o,u.col),value:u.value}))],i=r.map((u)=>({column_id:u.col.id,...xi(u.col,u.value)})),a=await Ue(n),c=ge("lists-add",t,JSON.stringify(i),a?.userId??"");if(e.code!==c)De(e.code,c,["--- Adding a row to Slack List ---------------",we(a,{asBot:!0,pad:9}),` list: ${t}`,...r.map((u)=>` ${(u.col.name||u.col.key).padEnd(8)} ${u.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let l;try{l=await Ou(n,t,i)}catch(u){Jo(u)}console.log(`\u2713 Added row ${String(_(l.item).id??"")} ${e.text}`)}async function xy(e){let t=Wo(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=Es();await Uo(n);let o=await Sf(n,t),s=Ei(e.sets).map((c)=>({col:ki(o,c.col),value:c.value}));if(e.done!==void 0){let c=Du(o);if(!c)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);s.push({col:{...c,type:"checkbox"},value:String(e.done)})}if(!s.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let r=s.map((c)=>({row_id:e.row,column_id:c.col.id,...xi(c.col,c.value)})),i=await Ue(n),a=ge("lists-set",t,e.row,JSON.stringify(r),i?.userId??"");if(e.code!==a)De(e.code,a,["--- Updating Slack List row -----------------",we(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...s.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 Pu(n,t,r)}catch(c){Jo(c)}console.log(`\u2713 Updated row ${e.row}`)}async function Ey(e){let t=Wo(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=Es();await Uo(n);let o=e.users.length?e.users:e.channels,s=await Ue(n),r=ge("lists-share",t,e.level,o.join(","),s?.userId??"");if(e.code!==r)De(e.code,r,["--- Sharing Slack List ----------------------",we(s,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${o.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await Ru(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){Jo(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${o.join(", ")}`)}function Sy(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 Cy(e,t,n,o){let s=Sy(n);if(!s)throw Error(`Not a file ID or file permalink: ${n}
424
- `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let r=_(await Au(e,s,t)),i=_(r.file),a=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:s,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 ${s}`);let l={Authorization:`Bearer ${e}`};if(t)l.Cookie=`d=${t}`;let u=await fetch(c,{headers:l});if(!u.ok)throw Error(`Download failed: HTTP ${u.status} ${u.statusText}`);let d=Buffer.from(await u.arrayBuffer()),{statSync:f,existsSync:h}=await import("fs"),{basename:g}=await import("path"),p=o??a;if(o&&h(o)&&f(o).isDirectory())p=Nt(o,g(a));cf(p,d),console.log(`\u2713 Downloaded ${a} (${Bo(d.length)}) \u2192 ${p}`)}async function _y(){Md(),um();let e=(s)=>qn(s.workspace),t=(s)=>$r(s.workspace),n={state:{type:"string",choices:["open","untriaged","pending","doing","done","dropped","stuck"],default:"open",describe:"open (default) = marked and not done/dropped; untriaged = marked with no progress; stuck = unfinished with a reason flag"},in:{type:"string",describe:"Limit to a channel (#chan)"},from:{type:"string",describe:"Limit to a sender (@user, or 'me') \u2014 usually the person a task is waiting on"},n:{alias:"count",type:"number",default:50,describe:"Max results"},json:{type:"boolean",default:!1}},o=async(s,r)=>{let i={state:s.state??"open",mine:r||s.mine===!0,count:s.n??50,json:s.json===!0};if(s.in)i.in=s.in;if(s.from)i.from=s.from;let a=t(s);if(a)i.cookie=a;await km(e(s),i)};await Wc(or(process.argv)).scriptName("slack").showHelpOnFail(!1).fail((s,r,i)=>{if(r)console.error(r.message),process.exit(1);console.error(s),console.error(""),i.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).middleware(async(s)=>{let r=String((s._??[])[0]??"");if(!r||r==="auth"||r==="login"||r==="agent"||r==="sent")return;try{let i=qn(s.workspace),a=ze(),c=Ad(s._??[],s,{botTokenSource:a?lf.get("SLACK_BOT_TOKEN")??Vi.get("SLACK_BOT_TOKEN")?.find((l)=>l.val===a)?.path??"shell":void 0,globalPaths:ea,slackTokenSet:!!process.env.SLACK_TOKEN,activeTokenIsBot:!!a&&i===a});if(c)console.error(c),process.exit(2)}catch(i){if((i instanceof Error?i.message:String(i)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
425
- `),await ss(),process.exit(0);throw i}},!0).command("agent","Bot agent session status and command heartbeat",(s)=>Jl(s,vn)).command(["read [target]","msgs [target]"],"Browse messages",(s)=>s.positional("target",{type:"string",describe:"#channel, @user, or URL"}).option("limit",{alias:"n",type:"number",default:20,describe:"Number of messages"}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("unreplied",{type:"boolean",default:!1,describe:"Only messages whose last word (incl. thread replies) is not yours \u2014 i.e. awaiting your answer"}),async(s)=>{let r=e(s),i=s.json?"jsonl":s.format;if(s.target)await gm(r,s.target,s.limit,i,s.unreplied,t(s));else await ym(r)}).command("thread <target> <ts>","Show thread messages",(s)=>s.positional("target",{type:"string",demandOption:!0}).positional("ts",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:100}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(s)=>{let r=s.json?"jsonl":s.format;await mm(e(s),s.target,s.ts,s.limit,r,t(s))}).command(["channel","channels","ch"],"Channel commands",(s)=>s.command(["ls","list"],"List channels",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("all",{type:"boolean",default:!1}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{await wm(e(r),r.limit,r.filter,r.all,r.json?"jsonl":r.format,t(r))}).command("get <channel>","Show channel details",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(r)=>{let i=e(r),a=t(r),c=r.channel,l=c.startsWith("#")||c.startsWith("@")||c.startsWith("C")||c.startsWith("G")||c.startsWith("D")?c:`#${c}`,u=await ye(i,l,a),d=_(await cn(i,u,a)),f=_(d.channel),h=typeof f.name==="string"?f.name:u,p=f.is_im===!0?"@":"#",m=String(_(f.purpose).value??""),D=String(_(f.topic).value??""),w=f.num_members??f.member_count??"";if(console.log(`${p}${h} ${u}`),D)console.log(`topic: ${D}`);if(m)console.log(`purpose: ${m}`);if(w)console.log(`members: ${w}`);console.log(`private: ${f.is_private===!0}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"Channel name (Slack lowercases it; no spaces)"}).option("private",{type:"boolean",default:!1,describe:"Create a private channel"}).option("invite",{type:"string",array:!0,default:[],describe:"Users to invite after creating (@handle or Uxxxx, repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{let i=e(r),a=t(r),c=r.name.replace(/^#/,"").toLowerCase(),l=r.private===!0,u=r.invite.filter(Boolean),d=await Ue(i,a),f=ge(c,String(l),u.join(","),d?.userId??"");if(r.code!==f)De(r.code,f,["--- Creating channel -------------------------",we(d,{pad:9}),` name: ${l?"\uD83D\uDD12 ":"#"}${c}`,` private: ${l}`,...u.length?[` invite: ${u.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let h;try{h=await qu(i,c,l,a)}catch(g){console.error(g instanceof Error?g.message:String(g)),process.exit(1)}if(console.log(`\u2713 Created ${l?"\uD83D\uDD12 ":"#"}${h.name} (${h.id})`),u.length){let g=[];for(let p of u)try{g.push(p.startsWith("U")||p.startsWith("W")?p:await wt(i,p,a))}catch(m){console.error(` ! could not resolve ${p}: ${m instanceof Error?m.message:String(m)}`)}for(let p of g)try{let m=_(await ps(i,p,a)),D=_(m.user);if(D.is_ultra_restricted===!0)console.error(`\u26A0 ${p} is a single-channel guest \u2014 Slack restricts them to their one existing channel; this invite will likely report success but not actually add them.`);else if(D.is_restricted===!0)console.error(`\u26A0 ${p} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(g.length)try{await zu(i,h.id,g,a),console.log(`\u2713 Invited ${g.length} member${g.length===1?"":"s"}`)}catch(p){console.error(` ! invite failed: ${p instanceof Error?p.message:String(p)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name, name, or channel ID (C\u2026/G\u2026)"}).positional("new-name",{type:"string",demandOption:!0,describe:"New channel name (Slack lowercases it; no spaces)"}).option("dry-run",{type:"boolean",default:!1,describe:"Resolve the channel and print old -> new without renaming"}).option("code",{type:"string",describe:"Safety hash to confirm rename"}),async(r)=>{let i=e(r),a=t(r),c=r.channel;if(c.startsWith("@"))console.error(`Error: ${c} is a DM \u2014 only channels can be renamed.`),process.exit(1);let l=c.startsWith("#")||/^[CG][A-Z0-9]{8,}$/.test(c)?c:`#${c}`,u=r.newName.replace(/^#/,"").toLowerCase(),d,f;try{d=await ye(i,l,a)}catch(m){console.error(`Error: could not resolve channel ${c}: ${m instanceof Error?m.message:String(m)}`),process.exit(1)}try{let m=_(_(await cn(i,d,a)).channel);if(m.is_im===!0||m.is_mpim===!0)console.error(`Error: ${d} is a DM \u2014 only channels can be renamed.`),process.exit(1);f=typeof m.name==="string"?m.name:l.replace(/^#/,"")}catch(m){let D=m instanceof Error?m.message:String(m);if(/channel_not_found/.test(D))console.error(`Error: could not resolve channel ${c}: channel not found (or not visible to this token).`),process.exit(1);f=l.replace(/^#/,"")}if(r.dryRun===!0){console.log(`#${f} -> #${u} (${d})`),console.log("(dry run \u2014 conversations.rename not called)");return}let h=await Ue(i,a),g=ge("rename",d,u,h?.userId??"");if(r.code!==g)De(r.code,g,["--- Renaming channel -------------------------",we(h,{pad:9}),` channel: ${d}`,` from: #${f}`,` to: #${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let p;try{p=await Hu(i,d,u,a)}catch(m){let w=(m instanceof Error?m.message:String(m)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],k={name_taken:`Error: a channel named #${u} already exists.`,invalid_name:`Error: "${u}" is not a valid channel name (lowercase letters, numbers, hyphens, underscores; max 80 chars).`,invalid_name_specials:`Error: "${u}" contains characters Slack doesn't allow in channel names.`,invalid_name_maxlength:`Error: "${u}" is too long (max 80 chars).`,invalid_name_required:"Error: the new channel name can't be empty.",not_authorized:`Error: this token isn't allowed to rename #${f} (workspace settings may restrict renaming to admins or the channel creator).`,not_in_channel:`Error: this token isn't a member of #${f} \u2014 join it first.`,is_archived:`Error: #${f} is archived \u2014 unarchive it before renaming.`};console.error((w&&k[w])??de(m)),process.exit(1)}console.log(`\u2713 Renamed #${f} -> #${p.name} (${p.id})`)}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(s)=>s.command(["ls","list"],"List workspace members",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("format",{type:"string",choices:["text","jsonl","yaml"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("external",{type:"boolean",default:!1,describe:"Also include people reachable only through Slack Connect shared channels \u2014 they are in ANOTHER workspace, so users.list never returns them (costs one API call per shared channel)"}),async(r)=>{let i=r.json?"jsonl":r.format,a=e(r),c=t(r),l=await Zu(a,c),u=r.filter?.toLowerCase(),d=H(l.members).map(_);if(r.external){let p=new Set(d.map((k)=>String(k.id))),m=_(await us(a,c)),D=H(m.channels).map(_).filter((k)=>k.is_ext_shared===!0&&!!k.name),w=new Set;for(let k of D)try{for(let x of await Qu(a,String(k.id),c))if(!p.has(x))w.add(x)}catch{}for(let k of w)try{let x=_(await ps(a,k,c)),C=_(x.user);if(C.id)d.push(C)}catch{}}let f=d.filter((p)=>p.deleted!==!0&&p.is_bot!==!0&&String(p.id)!=="USLACKBOT").filter((p)=>{if(!u)return!0;let m=String(p.name??"").toLowerCase(),D=String(_(p.profile).real_name??"").toLowerCase(),w=String(_(p.profile).email??"").toLowerCase();return m.includes(u)||D.includes(u)||w.includes(u)}).slice(0,r.limit);if(i==="jsonl"){for(let p of f)console.log(JSON.stringify(p));return}if(i==="yaml"){for(let p of f){let m=function(D,w=""){if(D===null)return"null";if(typeof D==="string")return D.includes(`
426
+ slack schedule rm '${t.target}' ${d} --as-bot`),r.startsWith("D"))try{let p=await to(e);if(!p.ok)for(let h of no(p,!0))console.error(h);else{let h=p.appId?`https://api.slack.com/apps/${p.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${h} \u2192 App Home.`)}}catch{}}}async function ff(e,t,n,o){let s;if(n)s=n;else if(t)s=await fe(e,t,o);let i=(await Gu(e,s,o)).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(`
427
+ `)[0]?.slice(0,80)??""}`)}}async function pf(e,t){let n;if(t.channelId)n=t.channelId;else n=await fe(e,t.target,t.cookie);let o=await Te(e,t.cookie),s=ue(n,t.id,o?.userId??"");if(t.code!==s)pe(t.code,s,["--- Deleting scheduled message ---------------",he(o,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await Yu(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function Fy(e,t){if(t.comment!==void 0)Be(t.comment,t.allowUrlAdjacent);let n=bt(e,t.cookie),{statSync:o,existsSync:s}=await import("fs"),{basename:r}=await import("path");for(let y of t.filePaths)if(!s(y))console.error(`Error: file not found: ${y}`),process.exit(1);let{ref:i,threadTs:a}=Bn(t.target),c;if(t.channelId)c=t.channelId;else if(t.userId)c=await wt(e,t.userId,t.cookie);else c=await fe(e,i,t.cookie);if(await ua(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 l=t.filePaths.length>1,u=t.filePaths.map((y)=>{let f=r(y),g=l?f:t.title??f;return{fp:y,filename:f,title:g,sizeFmt:jo(o(y).size)}}),d=await n(),p=ue(c,...u.flatMap((y)=>[y.fp,y.title]),d?.userId??"");if(t.code!==p){let y=` To: ${i}${a?` (thread ${a})`:""}`,f=l?[`--- Uploading ${u.length} files ------------------------`,he(d,{pad:7}),y,...u.map((g)=>` ${g.filename} (${g.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",he(d,{pad:7}),y,` File: ${u[0].fp}`,` Title: ${u[0].title}`,` Size: ${u[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];pe(t.code,p,f)}let h=u.length;for(let y=0;y<h;y++){let f=u[y],g={title:f.title};if(a!==void 0)g.threadTs=a;if(t.comment!==void 0&&y===0)g.initialComment=t.comment;let{fileId:w,permalink:D}=await hd(e,c,f.fp,g,t.cookie),k=h>1?`[${y+1}/${h}] `:"";console.log(`${k}\u2713 Uploaded (file_id: ${w}${D?`, url: ${D}`:""})`)}}async function Ay(e,t,n){let o=n.channel?await fe(e,n.channel,t):void 0,s=[],r=1,i=1;do{let c={page:r,count:200};if(n.types)c.types=n.types;if(o)c.channel=o;if(n.user)c.user=n.user;let l=T(await Nu(e,c,t));for(let u of H(l.files))s.push(T(u));i=Number(T(l.paging).pages??1),r++}while(s.length<n.limit&&r<=i);let a=s.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 l=String(c.id??""),u=typeof c.name==="string"?c.name:typeof c.title==="string"?c.title:l,d=typeof c.filetype==="string"?c.filetype:"?",p=typeof c.size==="number"?jo(c.size):"";console.log(`${l} ${d.padEnd(7)} ${p.padStart(9)} ${u}`)}}function qo(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 Ty(e){if(typeof e.text==="string"&&e.text)return e.text;let t=e.value;if(typeof t==="string"||typeof t==="number"||typeof t==="boolean")return String(t);if(Array.isArray(t))return t.map((n)=>typeof n==="string"?n:String(T(n).text??T(n).name??T(n).value??"")).filter(Boolean).join(", ");for(let n of["rich_text","select","user","date","number","checkbox","email","phone"]){let o=e[n];if(o!=null)return typeof o==="object"?JSON.stringify(o):String(o)}return""}async function Iy(e,t,n,o){let s=qo(n);if(!s)throw Error(`Not a list ID or list URL: ${n}
428
+ `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let r=[],i;do{let c={limit:200};if(i)c.cursor=i;let l=o.asBot?await Bi(Cs(),s,c):T(await Ju(e,s,c,t));for(let d of H(l.items??l.records))r.push(T(d));let u=T(l.response_metadata).next_cursor;i=typeof u==="string"&&u?u:void 0}while(i&&r.length<o.limit);let a=r.slice(0,o.limit);if(o.format==="jsonl"){for(let c of a)console.log(JSON.stringify(c));return}for(let c of a){let l=String(c.id??""),u=H(c.fields).map(T).map((d)=>{let p=String(d.key??d.column_id??"?"),h=Ty(d);return h?`${p}=${h}`:""}).filter(Boolean);console.log(`${l} ${u.join(" | ")}`)}}function Cs(){let e=Je();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
429
+ `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function Ho(e){let t=[];try{t=(await $n(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).
430
+ `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function Oy(e,t){try{let n=await vi(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function Bf(e,t){let n=await Bi(e,t,{limit:1,includeList:!0}),o=xu(T(n.list));if(!o.length)throw Error(`could not read the column schema of list ${t}`);return o}function zo(e){console.error(ie(e)),process.exit(1)}async function Ry(e){let t=e.cols.map(bu),n=ku(t),o=Cs();await Ho(o);let s=await Te(o),r=ue("lists-create",e.name,JSON.stringify(n),String(e.todo),s?.userId??"");if(e.code!==r)pe(e.code,r,["--- Creating Slack List ----------------------",he(s,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((c,l)=>` column: ${c.name} (${c.type}${c.choices?`: ${c.choices.join("/")}`:""})${l===0?" [primary]":""}`),` todo: ${e.todo?"on (adds Completed / Assignee / Due date)":"off"}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let i;try{i=await Mu(o,e.name,n,e.todo)}catch(c){zo(c)}let a=String(i.list_id??T(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${a})`),console.log(await Oy(o,a))}async function Py(e){let t=qo(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=Cs();await Ho(n);let o=await Bf(n,t),r=[{col:o.find((u)=>u.type==="text")??o[0],value:e.text},...$i(e.sets).map((u)=>({col:Ci(o,u.col),value:u.value}))],i=r.map((u)=>({column_id:u.col.id,..._i(u.col,u.value)})),a=await Te(n),c=ue("lists-add",t,JSON.stringify(i),a?.userId??"");if(e.code!==c)pe(e.code,c,["--- Adding a row to Slack List ---------------",he(a,{asBot:!0,pad:9}),` list: ${t}`,...r.map((u)=>` ${(u.col.name||u.col.key).padEnd(8)} ${u.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let l;try{l=await ju(n,t,i)}catch(u){zo(u)}console.log(`\u2713 Added row ${String(T(l.item).id??"")} ${e.text}`)}async function vy(e){let t=qo(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=Cs();await Ho(n);let o=await Bf(n,t),s=$i(e.sets).map((c)=>({col:Ci(o,c.col),value:c.value}));if(e.done!==void 0){let c=Eu(o);if(!c)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);s.push({col:{...c,type:"checkbox"},value:String(e.done)})}if(!s.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let r=s.map((c)=>({row_id:e.row,column_id:c.col.id,..._i(c.col,c.value)})),i=await Te(n),a=ue("lists-set",t,e.row,JSON.stringify(r),i?.userId??"");if(e.code!==a)pe(e.code,a,["--- Updating Slack List row -----------------",he(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...s.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 Uu(n,t,r)}catch(c){zo(c)}console.log(`\u2713 Updated row ${e.row}`)}async function By(e){let t=qo(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=Cs();await Ho(n);let o=e.users.length?e.users:e.channels,s=await Te(n),r=ue("lists-share",t,e.level,o.join(","),s?.userId??"");if(e.code!==r)pe(e.code,r,["--- Sharing Slack List ----------------------",he(s,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${o.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await Wu(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){zo(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${o.join(", ")}`)}function Ly(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 Ny(e,t,n,o){let s=Ly(n);if(!s)throw Error(`Not a file ID or file permalink: ${n}
431
+ `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let r=T(await Lu(e,s,t)),i=T(r.file),a=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:s,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 ${s}`);let l={Authorization:`Bearer ${e}`};if(t)l.Cookie=`d=${t}`;let u=await fetch(c,{headers:l});if(!u.ok)throw Error(`Download failed: HTTP ${u.status} ${u.statusText}`);let d=Buffer.from(await u.arrayBuffer()),{statSync:p,existsSync:h}=await import("fs"),{basename:y}=await import("path"),f=o??a;if(o&&h(o)&&p(o).isDirectory())f=Mt(o,y(a));mf(f,d),console.log(`\u2713 Downloaded ${a} (${jo(d.length)}) \u2192 ${f}`)}async function My(){zd(),xm();let e=(s)=>Hn(s.workspace),t=(s)=>Ir(s.workspace),n={state:{type:"string",choices:["open","untriaged","pending","doing","done","dropped","stuck"],default:"open",describe:"open (default) = marked and not done/dropped; untriaged = marked with no progress; stuck = unfinished with a reason flag"},in:{type:"string",describe:"Limit to a channel (#chan)"},from:{type:"string",describe:"Limit to a sender (@user, or 'me') \u2014 usually the person a task is waiting on"},n:{alias:"count",type:"number",default:50,describe:"Max results"},json:{type:"boolean",default:!1}},o=async(s,r)=>{let i={state:s.state??"open",mine:r||s.mine===!0,count:s.n??50,json:s.json===!0};if(s.in)i.in=s.in;if(s.from)i.from=s.from;let a=t(s);if(a)i.cookie=a;await Rm(e(s),i)};await Hc(cr(process.argv)).scriptName("slack").showHelpOnFail(!1).fail((s,r,i)=>{if(r)console.error(r.message),process.exit(1);console.error(s),console.error(""),i.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).middleware(async(s)=>{let r=String((s._??[])[0]??"");if(!r||r==="auth"||r==="login"||r==="agent"||r==="sent")return;try{let i=Hn(s.workspace),a=Je(),c=Ld(s._??[],s,{botTokenSource:a?yf.get("SLACK_BOT_TOKEN")??ta.get("SLACK_BOT_TOKEN")?.find((l)=>l.val===a)?.path??"shell":void 0,globalPaths:ra,slackTokenSet:!!process.env.SLACK_TOKEN,activeTokenIsBot:!!a&&i===a});if(c)console.error(c),process.exit(2)}catch(i){if((i instanceof Error?i.message:String(i)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
432
+ `),await os(),process.exit(0);throw i}},!0).command("agent","Bot agent session status and command heartbeat",(s)=>Gl(s,Bn)).command(["read [target]","msgs [target]"],"Browse messages",(s)=>s.positional("target",{type:"string",describe:"#channel, @user, or URL"}).option("limit",{alias:"n",type:"number",default:20,describe:"Number of messages"}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("unreplied",{type:"boolean",default:!1,describe:"Only messages whose last word (incl. thread replies) is not yours \u2014 i.e. awaiting your answer"}),async(s)=>{let r=e(s),i=s.json?"jsonl":s.format;if(s.target)await $m(r,s.target,s.limit,i,s.unreplied,t(s));else await Am(r)}).command("thread <target> <ts>","Show thread messages",(s)=>s.positional("target",{type:"string",demandOption:!0}).positional("ts",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:100}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(s)=>{let r=s.json?"jsonl":s.format;await Fm(e(s),s.target,s.ts,s.limit,r,t(s))}).command(["channel","channels","ch"],"Channel commands",(s)=>s.command(["ls","list"],"List channels",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("all",{type:"boolean",default:!1}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{await Im(e(r),r.limit,r.filter,r.all,r.json?"jsonl":r.format,t(r))}).command("get <channel>","Show channel details",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(r)=>{let i=e(r),a=t(r),c=r.channel,l=c.startsWith("#")||c.startsWith("@")||c.startsWith("C")||c.startsWith("G")||c.startsWith("D")?c:`#${c}`,u=await fe(i,l,a),d=T(await ln(i,u,a)),p=T(d.channel),h=typeof p.name==="string"?p.name:u,f=p.is_im===!0?"@":"#",g=String(T(p.purpose).value??""),w=String(T(p.topic).value??""),D=p.num_members??p.member_count??"";if(console.log(`${f}${h} ${u}`),w)console.log(`topic: ${w}`);if(g)console.log(`purpose: ${g}`);if(D)console.log(`members: ${D}`);console.log(`private: ${p.is_private===!0}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"Channel name (Slack lowercases it; no spaces)"}).option("private",{type:"boolean",default:!1,describe:"Create a private channel"}).option("invite",{type:"string",array:!0,default:[],describe:"Users to invite after creating (@handle or Uxxxx, repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{let i=e(r),a=t(r),c=r.name.replace(/^#/,"").toLowerCase(),l=r.private===!0,u=r.invite.filter(Boolean),d=await Te(i,a),p=ue(c,String(l),u.join(","),d?.userId??"");if(r.code!==p)pe(r.code,p,["--- Creating channel -------------------------",he(d,{pad:9}),` name: ${l?"\uD83D\uDD12 ":"#"}${c}`,` private: ${l}`,...u.length?[` invite: ${u.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let h;try{h=await Qu(i,c,l,a)}catch(y){console.error(y instanceof Error?y.message:String(y)),process.exit(1)}if(console.log(`\u2713 Created ${l?"\uD83D\uDD12 ":"#"}${h.name} (${h.id})`),u.length){let y=[];for(let f of u)try{y.push(f.startsWith("U")||f.startsWith("W")?f:await Dt(i,f,a))}catch(g){console.error(` ! could not resolve ${f}: ${g instanceof Error?g.message:String(g)}`)}for(let f of y)try{let g=T(await ms(i,f,a)),w=T(g.user);if(w.is_ultra_restricted===!0)console.error(`\u26A0 ${f} 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(w.is_restricted===!0)console.error(`\u26A0 ${f} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(y.length)try{await td(i,h.id,y,a),console.log(`\u2713 Invited ${y.length} member${y.length===1?"":"s"}`)}catch(f){console.error(` ! invite failed: ${f instanceof Error?f.message:String(f)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(r)=>r.positional("channel",{type:"string",demandOption:!0,describe:"#name, name, or channel ID (C\u2026/G\u2026)"}).positional("new-name",{type:"string",demandOption:!0,describe:"New channel name (Slack lowercases it; no spaces)"}).option("dry-run",{type:"boolean",default:!1,describe:"Resolve the channel and print old -> new without renaming"}).option("code",{type:"string",describe:"Safety hash to confirm rename"}),async(r)=>{let i=e(r),a=t(r),c=r.channel;if(c.startsWith("@"))console.error(`Error: ${c} is a DM \u2014 only channels can be renamed.`),process.exit(1);let l=c.startsWith("#")||/^[CG][A-Z0-9]{8,}$/.test(c)?c:`#${c}`,u=r.newName.replace(/^#/,"").toLowerCase(),d,p;try{d=await fe(i,l,a)}catch(g){console.error(`Error: could not resolve channel ${c}: ${g instanceof Error?g.message:String(g)}`),process.exit(1)}try{let g=T(T(await ln(i,d,a)).channel);if(g.is_im===!0||g.is_mpim===!0)console.error(`Error: ${d} is a DM \u2014 only channels can be renamed.`),process.exit(1);p=typeof g.name==="string"?g.name:l.replace(/^#/,"")}catch(g){let w=g instanceof Error?g.message:String(g);if(/channel_not_found/.test(w))console.error(`Error: could not resolve channel ${c}: channel not found (or not visible to this token).`),process.exit(1);p=l.replace(/^#/,"")}if(r.dryRun===!0){console.log(`#${p} -> #${u} (${d})`),console.log("(dry run \u2014 conversations.rename not called)");return}let h=await Te(i,a),y=ue("rename",d,u,h?.userId??"");if(r.code!==y)pe(r.code,y,["--- Renaming channel -------------------------",he(h,{pad:9}),` channel: ${d}`,` from: #${p}`,` to: #${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let f;try{f=await ed(i,d,u,a)}catch(g){let D=(g instanceof Error?g.message:String(g)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],k={name_taken:`Error: a channel named #${u} already exists.`,invalid_name:`Error: "${u}" is not a valid channel name (lowercase letters, numbers, hyphens, underscores; max 80 chars).`,invalid_name_specials:`Error: "${u}" contains characters Slack doesn't allow in channel names.`,invalid_name_maxlength:`Error: "${u}" is too long (max 80 chars).`,invalid_name_required:"Error: the new channel name can't be empty.",not_authorized:`Error: this token isn't allowed to rename #${p} (workspace settings may restrict renaming to admins or the channel creator).`,not_in_channel:`Error: this token isn't a member of #${p} \u2014 join it first.`,is_archived:`Error: #${p} is archived \u2014 unarchive it before renaming.`};console.error((D&&k[D])??ie(g)),process.exit(1)}console.log(`\u2713 Renamed #${p} -> #${f.name} (${f.id})`)}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(s)=>s.command(["ls","list"],"List workspace members",(r)=>r.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("format",{type:"string",choices:["text","jsonl","yaml"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("external",{type:"boolean",default:!1,describe:"Also include people reachable only through Slack Connect shared channels \u2014 they are in ANOTHER workspace, so users.list never returns them (costs one API call per shared channel)"}),async(r)=>{let i=r.json?"jsonl":r.format,a=e(r),c=t(r),l=await id(a,c),u=r.filter?.toLowerCase(),d=H(l.members).map(T);if(r.external){let f=new Set(d.map((k)=>String(k.id))),g=T(await ps(a,c)),w=H(g.channels).map(T).filter((k)=>k.is_ext_shared===!0&&!!k.name),D=new Set;for(let k of w)try{for(let S of await ad(a,String(k.id),c))if(!f.has(S))D.add(S)}catch{}for(let k of D)try{let S=T(await ms(a,k,c)),C=T(S.user);if(C.id)d.push(C)}catch{}}let p=d.filter((f)=>f.deleted!==!0&&f.is_bot!==!0&&String(f.id)!=="USLACKBOT").filter((f)=>{if(!u)return!0;let g=String(f.name??"").toLowerCase(),w=String(T(f.profile).real_name??"").toLowerCase(),D=String(T(f.profile).email??"").toLowerCase();return g.includes(u)||w.includes(u)||D.includes(u)}).slice(0,r.limit);if(i==="jsonl"){for(let f of p)console.log(JSON.stringify(f));return}if(i==="yaml"){for(let f of p){let g=function(w,D=""){if(w===null)return"null";if(typeof w==="string")return w.includes(`
426
433
  `)?`|
427
- ${D.split(`
434
+ ${w.split(`
428
435
  `).join(`
429
- `)}`:D;if(typeof D!=="object")return String(D);if(Array.isArray(D))return D.map((k)=>`
430
- ${w} - ${m(k,w+" ")}`).join("");return Object.entries(D).map(([k,x])=>`
431
- ${w} ${k}: ${m(x,w+" ")}`).join("")};console.log("---");for(let[D,w]of Object.entries(p))console.log(`${D}: ${m(w)}`)}return}let h=Intl.DateTimeFormat().resolvedOptions().timeZone,g=f.length?String(_(H(l.members).map(_)[0]??{}).team_id??""):"";for(let p of f){let m=_(p.profile),D=String(p.name??p.id),w=String(p.id??""),k=String(m.display_name||""),x=String(m.real_name||""),C=String(m.email||""),I=String(p.tz??""),M=[...new Set([k,x].filter((P)=>P&&P!==D))].join(" / "),X=I&&I!==h?I:"",re=String(p.team_id??""),L=p.is_stranger===!0||g&&re&&re!==g?`external:${re||"?"}`:p.is_ultra_restricted===!0?"single-channel guest":p.is_restricted===!0?"guest":"",T=[C,X].filter(Boolean).join(" ");console.log(`@${D} ${w} ${M}${T?" "+T:""}${L?` [${L}]`:""}`)}}).command("get <user>","Show user details",(r)=>r.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(r)=>{let i=e(r),a=t(r),c=r.user.startsWith("@")?r.user:`@${r.user}`,l="";try{l=await wt(i,c,a)}catch(A){console.error(A instanceof Error?A.message:String(A)),process.exit(1)}let u=_(await ps(i,l,a)),d=_(u.user),f=_(d.profile),h=Intl.DateTimeFormat().resolvedOptions().timeZone,g=String(d.name??l),p=String(d.id??l),m=String(f.display_name||""),D=String(f.real_name||""),w=String(f.email||""),k=String(d.tz??""),x=String(f.phone||""),C=String(f.title||"");console.log(`@${g} ${p}`);let I=[...new Set([m,D].filter((A)=>A&&A!==g))];if(I.length)console.log(`name: ${I.join(" / ")}`);if(w)console.log(`email: ${w}`);if(x)console.log(`phone: ${x}`);if(C)console.log(`title: ${C}`);if(k&&k!==h)console.log(`tz: ${k}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(s)=>s.option("limit",{alias:"l",type:"number",default:20}),async(s)=>{await Dm(e(s),s.limit)}).command("search <query>","Full-text search",(s)=>s.positional("query",{type:"string",demandOption:!0}).option("count",{alias:"n",type:"number",default:100}).option("json",{type:"boolean",default:!1,describe:"Output raw JSON"}),async(s)=>{await ff(e(s),s.query,s.count,s.json,t(s))}).command("send <target> <message>","Send a message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Send via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient and can be two-way"}).option("broadcast",{type:"boolean",default:!1,describe:`Also send to channel: broadcast a threaded reply back to the channel (Slack's "Also send to #channel" checkbox). Only effective with a thread target.`}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real <@USERID> mentions (on by default; resolves via users.list, then channel members for Slack Connect guests). Unresolved handles stay as plain text. The confirm preview shows the converted message before sending. Disable with --no-mentions for literal @text."}),async(s)=>{if(!String(s.message??"").trim())console.error("Error: message is empty"),process.exit(1);let r={target:s.target,message:s.message,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];if(s.broadcast)r.broadcast=!0;if(s.mentions!==!1){r.mentions=!0,r.mentionToken=e(s);let a=t(s);if(a)r.mentionCookie=a}let i;if(s["as-bot"]){let a=ze();if(!a)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
432
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!r.channelId&&!r.userId&&r.target.startsWith("@"))try{r.userId=await wt(e(s),r.target,t(s))}catch(c){console.error(`Error: could not resolve ${r.target} to a user for the bot DM.
436
+ `)}`:w;if(typeof w!=="object")return String(w);if(Array.isArray(w))return w.map((k)=>`
437
+ ${D} - ${g(k,D+" ")}`).join("");return Object.entries(w).map(([k,S])=>`
438
+ ${D} ${k}: ${g(S,D+" ")}`).join("")};console.log("---");for(let[w,D]of Object.entries(f))console.log(`${w}: ${g(D)}`)}return}let h=Intl.DateTimeFormat().resolvedOptions().timeZone,y=p.length?String(T(H(l.members).map(T)[0]??{}).team_id??""):"";for(let f of p){let g=T(f.profile),w=String(f.name??f.id),D=String(f.id??""),k=String(g.display_name||""),S=String(g.real_name||""),C=String(g.email||""),F=String(f.tz??""),O=[...new Set([k,S].filter((R)=>R&&R!==w))].join(" / "),B=F&&F!==h?F:"",U=String(f.team_id??""),P=f.is_stranger===!0||y&&U&&U!==y?`external:${U||"?"}`:f.is_ultra_restricted===!0?"single-channel guest":f.is_restricted===!0?"guest":"",_=[C,B].filter(Boolean).join(" ");console.log(`@${w} ${D} ${O}${_?" "+_:""}${P?` [${P}]`:""}`)}}).command("get <user>","Show user details",(r)=>r.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(r)=>{let i=e(r),a=t(r),c=r.user.startsWith("@")?r.user:`@${r.user}`,l="";try{l=await Dt(i,c,a)}catch(A){console.error(A instanceof Error?A.message:String(A)),process.exit(1)}let u=T(await ms(i,l,a)),d=T(u.user),p=T(d.profile),h=Intl.DateTimeFormat().resolvedOptions().timeZone,y=String(d.name??l),f=String(d.id??l),g=String(p.display_name||""),w=String(p.real_name||""),D=String(p.email||""),k=String(d.tz??""),S=String(p.phone||""),C=String(p.title||"");console.log(`@${y} ${f}`);let F=[...new Set([g,w].filter((A)=>A&&A!==y))];if(F.length)console.log(`name: ${F.join(" / ")}`);if(D)console.log(`email: ${D}`);if(S)console.log(`phone: ${S}`);if(C)console.log(`title: ${C}`);if(k&&k!==h)console.log(`tz: ${k}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(s)=>s.option("limit",{alias:"l",type:"number",default:20}),async(s)=>{await Tm(e(s),s.limit)}).command("search <query>","Full-text search",(s)=>s.positional("query",{type:"string",demandOption:!0}).option("count",{alias:"n",type:"number",default:100}).option("json",{type:"boolean",default:!1,describe:"Output raw JSON"}),async(s)=>{await bf(e(s),s.query,s.count,s.json,t(s))}).command("send <target> <message>","Send a message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Send via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient and can be two-way"}).option("broadcast",{type:"boolean",default:!1,describe:`Also send to channel: broadcast a threaded reply back to the channel (Slack's "Also send to #channel" checkbox). Only effective with a thread target.`}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real <@USERID> mentions (on by default; resolves via users.list, then channel members for Slack Connect guests). Unresolved handles stay as plain text. The confirm preview shows the converted message before sending. Disable with --no-mentions for literal @text."}),async(s)=>{if(!String(s.message??"").trim())console.error("Error: message is empty"),process.exit(1);let r={target:s.target,message:s.message,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];if(s.broadcast)r.broadcast=!0;if(s.mentions!==!1){r.mentions=!0,r.mentionToken=e(s);let a=t(s);if(a)r.mentionCookie=a}let i;if(s["as-bot"]){let a=Je();if(!a)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
439
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!r.channelId&&!r.userId&&r.target.startsWith("@"))try{r.userId=await Dt(e(s),r.target,t(s))}catch(c){console.error(`Error: could not resolve ${r.target} to a user for the bot DM.
433
440
  ${c instanceof Error?c.message:String(c)}
434
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}i=a,r.asBot=!0}else{i=e(s);let a=t(s);if(a)r.cookie=a}try{await Hm(i,r)}catch(a){console.error(de(a)),process.exit(1)}}).command("ask [target] [question] [choices..]","Ask a question with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions (confirm-hash safety gate). Lifecycle: --waitFor=<link> collect, --void=<link> \u7121\u52B9\u5316 (verb aliases: `ask collect <link>`, `ask void <link\u2026>`)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --waitFor)"}).positional("question",{type:"string",describe:"The question. Must @tag whoever may answer (@alice), or the whole channel (@here / @channel / @everyone) \u2014 only their answer counts. In a 1:1 DM the other party counts automatically."}).positional("choices",{type:"string",array:!0,describe:"Up to 10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply."}).option("code",{type:"string",describe:"Safety hash to confirm the ask"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("lang",{type:"string",choices:[...Tt],describe:"Language of the instructions in the posted body. Default: $SLACK_TERM_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 (\u7121\u52B9\u5316, `slack ask void`) \u2014 stop waiting."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted. Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: 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:"\u7121\u52B9\u5316: 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("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: 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("json",{type:"boolean",default:!1,describe:"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"}),async(s)=>{if(s.ls){let m=(()=>{try{return e(s)}catch{return}})(),D={};if(m)D.user=m;let w=ze();if(w)D.bot=w;let k=t(s);if(k)D.cookie=k;let x={state:String(s.state??"open"),json:!!s.json,limit:Number(s.limit)||50};if(s.stale)x.stale=String(s.stale);if(s.channel)x.channel=String(s.channel);await oy(D,x);return}let r=(m)=>{if(!m){let w=t(s);return w?{token:e(s),cookie:w}:{token:e(s)}}let D=ze();if(!D)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
435
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);return{token:D}},i=s.target!==void 0&&s.target!=="void"&&s.target!=="collect"?String(s.target):void 0,a=[s.question,...s.choices??[]].filter((m)=>m!==void 0).map(String);if(s.edit){if(s.void||s.wait||s.waitFor)console.error("Error: --edit changes one open question \u2014 do not combine it with --void/--wait/--waitFor."),process.exit(oe);let{token:m,cookie:D}=r(!!s["as-bot"]),w={link:String(s.edit),asBot:!!s["as-bot"],mentionToken:e(s),allowUrlAdjacent:!!s["allow-url-adjacent"]};if(i!==void 0)w.question=i;if(a.length)w.choices=a.map((x)=>x.trim()).filter(Boolean);if(s.body!==void 0)w.body=String(s.body);if(s.lang)w.lang=String(s.lang);if(s.code)w.code=String(s.code);if(D)w.cookie=D;let k=t(s);if(k)w.mentionCookie=k;try{await sy(m,w)}catch(x){console.error(de(x)),process.exit(oe)}return}let c,l=(s.void??[]).map(String).filter(Boolean);if(s.reask){if(l.length!==1||s.target==="void")console.error("Error: --reask goes with exactly one --void=<permalink> (the question to replace)."),process.exit(oe);if(s.waitFor)console.error("Error: --reask posts a new question \u2014 --wait works, --waitFor does not."),process.exit(oe);let{token:m,cookie:D}=r(!!s["as-bot"]),w=await Ue(m,D),k=await xf(m,l[0],w,!!s["as-bot"],D);if(k==="void")console.error(`\u2717 ${v(l[0])}: \u3059\u3067\u306B\u7121\u52B9\u5316\u6E08\u307F\u3067\u3059 \u2014 \u65B0\u3057\u304F\u805E\u304F\u306A\u3089\u666E\u901A\u306B slack ask \u3067`),process.exit(oe);if(!k)process.exit(oe);if(c={...k,reason:Oe(String(s.reason??"")).trim()},s.target=k.threadTs?`${k.channelId}:${k.threadTs}`:k.channelId,s["channel-id"]=k.channelId,s.question=i??Tn(k.parsed.question),s.choices=a.length?a:[...k.parsed.reactable,...k.parsed.overflow].map(Tn),s.body===void 0&&k.parsed.body)s.body=Tn(k.parsed.body);if(!s.lang)s.lang=k.parsed.lang;s.void=void 0}if(!c&&(s.target==="void"||l.length)){let m=s.target==="void"?[s.question,...s.choices??[]]:[];if(s.target!=="void"&&(s.target||s.question||s.choices?.length))console.error("Error: --void voids existing questions \u2014 do not also pass a target/question/choices."),process.exit(oe);let D=[...l,...m.map((C)=>String(C??""))].filter(Boolean);if(!D.length)console.error("Error: --void=<permalink> \u2014 which question(s)?"),process.exit(oe);if(s.wait||s.waitFor)console.error("Error: --void voids existing questions \u2014 do not also pass --wait/--waitFor."),process.exit(oe);let w,k;if(s["as-bot"]){let C=ze();if(!C)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
436
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);w=C}else w=e(s),k=t(s);let x={links:D,reason:Oe(String(s.reason??"")).trim(),asBot:!!s["as-bot"]};if(s["superseded-by"])x.supersededBy=String(s["superseded-by"]);if(s.code)x.code=String(s.code);if(k)x.cookie=k;try{await ry(w,x)}catch(C){console.error(de(C)),process.exit(oe)}return}if(s.target==="collect"){if(!s.question||s.choices?.length)console.error("Error: slack ask collect <permalink> \u2014 exactly one question."),process.exit(oe);s.waitFor=String(s.question),s.target=void 0,s.question=void 0}let u=s.waitFor?String(s.waitFor):"",d=Number(s.timeout);if(!Number.isFinite(d)||d<0||d===0&&!u)console.error("Error: --timeout must be a positive number of seconds"),process.exit(oe);if(u){if(s.target||s.question||s.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(oe);let m,D;if(s["as-bot"]){let w=ze();if(!w)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
437
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);m=w}else m=e(s),D=t(s);try{let w={link:u,timeout:d,asBot:!!s["as-bot"],json:!!s.json};if(D)w.cookie=D;if(s.after){let k=String(s.after);if(!/^\d{10}\.\d{6}$/.test(k))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${v(k)})`),process.exit(oe);w.after=k}await iy(m,w)}catch(w){console.error(de(w)),process.exit(oe)}return}if(!s.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(oe);let f=String(s.question??"").trim();if(!f)console.error("Error: question is empty"),process.exit(oe);let h={allowUrlAdjacent:s["allow-url-adjacent"],target:s.target,question:f,choices:(s.choices??[]).map((m)=>String(m).trim()).filter(Boolean),timeout:d};if(s.code)h.code=s.code;if(s.body)h.body=s.body;if(s.lang)h.lang=String(s.lang);if(s.wait)h.wait=!0;if(s.json)h.json=!0;if(c)h.voidAfter=c;if(s["channel-id"])h.channelId=s["channel-id"];if(s["user-id"])h.userId=s["user-id"];h.mentionToken=e(s);let g=t(s);if(g)h.mentionCookie=g;let p;if(s["as-bot"]){let m=ze();if(!m)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
438
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);if(!h.channelId&&!h.userId&&h.target.startsWith("@"))try{h.userId=await wt(e(s),h.target,t(s))}catch(D){console.error(`Error: could not resolve ${h.target} to a user for the bot DM.
439
- ${D instanceof Error?D.message:String(D)}
440
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(oe)}p=m,h.asBot=!0}else{p=e(s);let m=t(s);if(m)h.cookie=m}try{await ty(p,h)}catch(m){console.error(de(m)),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)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --results/--close)"}).positional("question",{type:"string",describe:"The question. @tags are optional here \u2014 unlike `ask`, a poll needs no addressee: anyone who can see it may vote."}).positional("choices",{type:"string",array:!0,describe:"2..10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions for voters to click"}).option("multi",{type:"boolean",default:!1,describe:"Let one person pick several choices (default: 1 \u4EBA 1 \u7968)"}).option("until",{type:"string",describe:"Deadline shown in the message (display only \u2014 closing is still `--close`)"}).option("results",{type:"string",describe:"Count an existing poll: pass its permalink. Posts nothing; only edit is the invalid-ballot notice in the poll itself (--no-notify to suppress)."}).option("close",{type:"string",describe:"Count an existing poll AND freeze the tally into the message. Only the poster can do this."}).option("names",{type:"boolean",default:!1,describe:"Also list who voted for what (stderr)"}).option("no-notify",{type:"boolean",default:!1,describe:"With --results: do not write the invalid-ballot notice back into the message (keeps it strictly read-only)"}).option("code",{type:"string",describe:"Safety hash to confirm the post"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Post via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient \u2014 and so YOUR OWN vote counts, since the seeds are then the bot's"}),async(s)=>{let r=s.close?String(s.close):s.results?String(s.results):"";if(s.results&&s.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(nt);let i=()=>{let f=ze();if(!f)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
441
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(nt);return f};if(r){if(s.target||s.question||s.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(nt);let f=e(s),h=t(s);try{let g={link:r};if(s.close)g.close=!0;if(s.names)g.names=!0;if(s["no-notify"])g.noNotify=!0;if(h)g.cookie=h;if(s["as-bot"])g.writeToken=i();await uy(f,g)}catch(g){console.error(de(g)),process.exit(nt)}return}if(!s.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(nt);let a=String(s.question??"").trim();if(!a)console.error("Error: question is empty"),process.exit(nt);let c=(s.choices??[]).map((f)=>String(f).trim()).filter(Boolean);if(c.length<2||c.length>Cn)console.error(`Error: poll needs 2..${Cn} choices (got ${c.length}). For a free-text question use \`slack ask\`.`),process.exit(nt);let l={target:s.target,question:a,choices:c};if(s.multi)l.multi=!0;if(s.until)l.until=String(s.until);if(s.code)l.code=s.code;if(s.body)l.body=s.body;if(s["allow-url-adjacent"])l.allowUrlAdjacent=!0;if(s["channel-id"])l.channelId=s["channel-id"];if(s["user-id"])l.userId=s["user-id"];l.mentionToken=e(s);let u=t(s);if(u)l.mentionCookie=u;let d;if(s["as-bot"]){let f=i();if(!l.channelId&&!l.userId&&l.target.startsWith("@"))try{l.userId=await wt(e(s),l.target,t(s))}catch(h){console.error(`Error: could not resolve ${l.target} to a user for the bot DM.
442
- ${h instanceof Error?h.message:String(h)}
443
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(nt)}d=f,l.asBot=!0}else{d=e(s);let f=t(s);if(f)l.cookie=f}try{await cy(d,l)}catch(f){console.error(de(f)),process.exit(nt)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(s)=>s.positional("query",{type:"string",describe:"Substring of the message text (case-insensitive)"}).option("channel",{type:"string",describe:"Channel/DM id (C\u2026/D\u2026) or the target as typed (#eng, @bob)"}).option("since",{type:"string",describe:"Only newer than this: 30m, 2h, 7d, 1w, or an ISO date"}).option("session",{type:"string",describe:"Agent session id (prefix match)"}).option("cwd",{type:"string",describe:"Working directory the sender ran in (prefix match)"}).option("kind",{type:"string",choices:["send","ask","poll","edit"],describe:"Only this kind of write"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per line (every recorded field)"}).option("count",{alias:"n",type:"number",default:50,describe:"Max rows (newest first)"}),(s)=>{let r;if(s.since!==void 0){if(r=$i(String(s.since)),r===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${v(String(s.since))})`),process.exit(1)}let i={limit:Number(s.count)||50};if(s.query)i.text=String(s.query);if(s.channel)i.channel=String(s.channel);if(r!==void 0)i.sinceMs=r;if(s.session)i.session=String(s.session);if(s.cwd){let c=cm(String(s.cwd));try{i.cwd=am(c)}catch{i.cwd=c}}if(s.kind)i.kind=s.kind;let a=_i(i);if(!a)console.error(`Error: ${yo}
444
- (${_n()})`),process.exit(1);if(s.json){for(let c of a)console.log(JSON.stringify(c));return}if(!a.length){console.error(`No sent messages match (log: ${_n()}).`);return}for(let c of a)console.log(Im(c))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(s)=>s,async()=>{let s=ze();if(!s)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
445
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await dy(s)}).command("schedule","Manage scheduled messages",(s)=>s.command("send <target> <message>","Schedule a message for later delivery",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("at",{type:"string",demandOption:!0,describe:"Delivery time (ISO datetime or Unix ts)"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Schedule via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. Without it a scheduled DM to yourself is posted by you, and Slack never notifies you of your own message \u2014 it fires into silence."}),async(r)=>{if(!String(r.message??"").trim())console.error("Error: message is empty"),process.exit(1);let i={target:r.target,message:r.message,at:r.at};if(r.code)i.code=r.code;if(r["allow-url-adjacent"])i.allowUrlAdjacent=!0;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["user-id"])i.userId=r["user-id"],i.targetOverride=`--user-id ${r["user-id"]}`;let a;if(r["as-bot"]){let c=Ao();if(!i.channelId&&!i.userId&&i.target.startsWith("@"))try{i.userId=await wt(e(r),i.target,t(r))}catch(l){console.error(`Error: could not resolve ${i.target} to a user for the bot DM.
441
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}i=a,r.asBot=!0}else{i=e(s);let a=t(s);if(a)r.cookie=a}try{await oy(i,r)}catch(a){console.error(ie(a)),process.exit(1)}}).command("ask [target] [question] [choices..]","Ask a question with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions (confirm-hash safety gate). Lifecycle: --waitFor=<link> collect, --void=<link> \u7121\u52B9\u5316 (verb aliases: `ask collect <link>`, `ask void <link\u2026>`)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --waitFor)"}).positional("question",{type:"string",describe:"The question. Must @tag whoever may answer (@alice), or the whole channel (@here / @channel / @everyone) \u2014 only their answer counts. In a 1:1 DM the other party counts automatically."}).positional("choices",{type:"string",array:!0,describe:"Up to 10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply."}).option("code",{type:"string",describe:"Safety hash to confirm the ask"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("lang",{type:"string",choices:[...Tt],describe:"Language of the instructions in the posted body. Default: $SLACK_TERM_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 (\u7121\u52B9\u5316, `slack ask void`) \u2014 stop waiting."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted. Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: 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:"\u7121\u52B9\u5316: 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: --since 7d, --channel, --json."}).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("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(s)=>{if(s.ls||s.pending){if(s.ls&&s.pending)console.error("Error: --ls and --pending are separate lists \u2014 pick one."),process.exit(Z);let f=(()=>{try{return e(s)}catch{return}})(),g={};if(f)g.user=f;let w=Je();if(w)g.bot=w;let D=t(s);if(D)g.cookie=D;if(s.pending){if(s.target||s.question||s.waitFor||s.wait||s.void||s.edit)console.error("Error: --pending reads the local log \u2014 do not also pass a target/question or another ask action."),process.exit(Z);let S=ko(String(s.since));if(S===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${v(String(s.since))})`),process.exit(Z);let C={sinceMs:S,json:!!s.json};if(s.channel)C.channel=String(s.channel);try{await yy(g,C)}catch(F){console.error(ie(F)),process.exit(Z)}return}let k={state:String(s.state??"open"),json:!!s.json,limit:Number(s.limit)||50};if(s.stale)k.stale=String(s.stale);if(s.channel)k.channel=String(s.channel);await my(g,k);return}let r=(f)=>{if(!f){let w=t(s);return w?{token:e(s),cookie:w}:{token:e(s)}}let g=Je();if(!g)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
442
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Z);return{token:g}},i=s.target!==void 0&&s.target!=="void"&&s.target!=="collect"?String(s.target):void 0,a=[s.question,...s.choices??[]].filter((f)=>f!==void 0).map(String);if(s.edit){if(s.void||s.wait||s.waitFor)console.error("Error: --edit changes one open question \u2014 do not combine it with --void/--wait/--waitFor."),process.exit(Z);let{token:f,cookie:g}=r(!!s["as-bot"]),w={link:String(s.edit),asBot:!!s["as-bot"],mentionToken:f,allowUrlAdjacent:!!s["allow-url-adjacent"]};if(i!==void 0)w.question=i;if(a.length)w.choices=a.map((D)=>D.trim()).filter(Boolean);if(s.body!==void 0)w.body=String(s.body);if(s.lang)w.lang=String(s.lang);if(s.code)w.code=String(s.code);if(g)w.cookie=g,w.mentionCookie=g;try{await gy(f,w)}catch(D){console.error(ie(D)),process.exit(Z)}return}let c,l=(s.void??[]).map(String).filter(Boolean);if(s.reask){if(l.length!==1||s.target==="void")console.error("Error: --reask goes with exactly one --void=<permalink> (the question to replace)."),process.exit(Z);if(s.waitFor)console.error("Error: --reask posts a new question \u2014 --wait works, --waitFor does not."),process.exit(Z);let{token:f,cookie:g}=r(!!s["as-bot"]),w=await Te(f,g),D=await Of(f,l[0],w,!!s["as-bot"],g);if(D==="void")console.error(`\u2717 ${v(l[0])}: \u3059\u3067\u306B\u7121\u52B9\u5316\u6E08\u307F\u3067\u3059 \u2014 \u65B0\u3057\u304F\u805E\u304F\u306A\u3089\u666E\u901A\u306B slack ask \u3067`),process.exit(Z);if(!D)process.exit(Z);if(c={...D,reason:Fe(String(s.reason??"")).trim()},s.target=D.threadTs?`${D.channelId}:${D.threadTs}`:D.channelId,s["channel-id"]=D.channelId,s.question=i??Tn(D.parsed.question),s.choices=a.length?a:[...D.parsed.reactable,...D.parsed.overflow].map(Tn),s.body===void 0&&D.parsed.body)s.body=Tn(D.parsed.body);if(!s.lang)s.lang=D.parsed.lang;s.void=void 0}if(!c&&(s.target==="void"||l.length)){let f=s.target==="void"?[s.question,...s.choices??[]]:[];if(s.target!=="void"&&(s.target||s.question||s.choices?.length))console.error("Error: --void voids existing questions \u2014 do not also pass a target/question/choices."),process.exit(Z);let g=[...l,...f.map((S)=>String(S??""))].filter(Boolean);if(!g.length)console.error("Error: --void=<permalink> \u2014 which question(s)?"),process.exit(Z);if(s.wait||s.waitFor)console.error("Error: --void voids existing questions \u2014 do not also pass --wait/--waitFor."),process.exit(Z);let w,D;if(s["as-bot"]){let S=Je();if(!S)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
443
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Z);w=S}else w=e(s),D=t(s);let k={links:g,reason:Fe(String(s.reason??"")).trim(),asBot:!!s["as-bot"]};if(s["superseded-by"])k.supersededBy=String(s["superseded-by"]);if(s.code)k.code=String(s.code);if(D)k.cookie=D;try{await wy(w,k)}catch(S){console.error(ie(S)),process.exit(Z)}return}if(s.target==="collect"){if(!s.question||s.choices?.length)console.error("Error: slack ask collect <permalink> \u2014 exactly one question."),process.exit(Z);s.waitFor=String(s.question),s.target=void 0,s.question=void 0}let u=s.waitFor?String(s.waitFor):"",d=Number(s.timeout);if(!Number.isFinite(d)||d<0||d===0&&!u)console.error("Error: --timeout must be a positive number of seconds"),process.exit(Z);if(u){if(s.target||s.question||s.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(Z);let f,g;if(s["as-bot"]){let w=Je();if(!w)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
444
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Z);f=w}else f=e(s),g=t(s);try{let w={link:u,timeout:d,asBot:!!s["as-bot"],json:!!s.json};if(g)w.cookie=g;if(s.after){let D=String(s.after);if(!/^\d{10}\.\d{6}$/.test(D))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${v(D)})`),process.exit(Z);w.after=D}await Dy(f,w)}catch(w){console.error(ie(w)),process.exit(Z)}return}if(!s.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(Z);let p=String(s.question??"").trim();if(!p)console.error("Error: question is empty"),process.exit(Z);let h={allowUrlAdjacent:s["allow-url-adjacent"],target:s.target,question:p,choices:(s.choices??[]).map((f)=>String(f).trim()).filter(Boolean),timeout:d};if(s.code)h.code=s.code;if(s.body)h.body=s.body;if(s.lang)h.lang=String(s.lang);if(s.wait)h.wait=!0;if(s.json)h.json=!0;if(c)h.voidAfter=c;if(s["channel-id"])h.channelId=s["channel-id"];if(s["user-id"])h.userId=s["user-id"];let y;if(s["as-bot"]){let f=Je();if(!f)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
445
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Z);if(!h.channelId&&!h.userId&&h.target.startsWith("@"))try{h.userId=await Dt(f,h.target)}catch(g){console.error(`Error: could not resolve ${h.target} to a user for the bot DM.
446
+ ${g instanceof Error?g.message:String(g)}
447
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(Z)}y=f,h.mentionToken=f,h.asBot=!0}else{y=e(s),h.mentionToken=y;let f=t(s);if(f)h.cookie=f,h.mentionCookie=f}try{await py(y,h)}catch(f){console.error(ie(f)),process.exit(Z)}}).command(["poll [target] [question] [choices..]","vote [target] [question] [choices..]"],"Post a poll with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions, then count them (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --results/--close)"}).positional("question",{type:"string",describe:"The question. @tags are optional here \u2014 unlike `ask`, a poll needs no addressee: anyone who can see it may vote."}).positional("choices",{type:"string",array:!0,describe:"2..10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions for voters to click"}).option("multi",{type:"boolean",default:!1,describe:"Let one person pick several choices (default: 1 \u4EBA 1 \u7968)"}).option("until",{type:"string",describe:"Deadline shown in the message (display only \u2014 closing is still `--close`)"}).option("results",{type:"string",describe:"Count an existing poll: pass its permalink. Posts nothing; only edit is the invalid-ballot notice in the poll itself (--no-notify to suppress)."}).option("close",{type:"string",describe:"Count an existing poll AND freeze the tally into the message. Only the poster can do this."}).option("names",{type:"boolean",default:!1,describe:"Also list who voted for what (stderr)"}).option("no-notify",{type:"boolean",default:!1,describe:"With --results: do not write the invalid-ballot notice back into the message (keeps it strictly read-only)"}).option("code",{type:"string",describe:"Safety hash to confirm the post"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Post via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient \u2014 and so YOUR OWN vote counts, since the seeds are then the bot's. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(s)=>{let r=s.close?String(s.close):s.results?String(s.results):"";if(s.results&&s.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(Qe);let i=()=>{let d=Je();if(!d)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
448
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(Qe);return d};if(r){if(s.target||s.question||s.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(Qe);let d=e(s),p=t(s);try{let h={link:r};if(s.close)h.close=!0;if(s.names)h.names=!0;if(s["no-notify"])h.noNotify=!0;if(p)h.cookie=p;if(s["as-bot"])h.writeToken=i();await Ey(d,h)}catch(h){console.error(ie(h)),process.exit(Qe)}return}if(!s.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(Qe);let a=String(s.question??"").trim();if(!a)console.error("Error: question is empty"),process.exit(Qe);let c=(s.choices??[]).map((d)=>String(d).trim()).filter(Boolean);if(c.length<2||c.length>_n)console.error(`Error: poll needs 2..${_n} choices (got ${c.length}). For a free-text question use \`slack ask\`.`),process.exit(Qe);let l={target:s.target,question:a,choices:c};if(s.multi)l.multi=!0;if(s.until)l.until=String(s.until);if(s.code)l.code=s.code;if(s.body)l.body=s.body;if(s["allow-url-adjacent"])l.allowUrlAdjacent=!0;if(s["channel-id"])l.channelId=s["channel-id"];if(s["user-id"])l.userId=s["user-id"];let u;if(s["as-bot"]){let d=i();if(!l.channelId&&!l.userId&&l.target.startsWith("@"))try{l.userId=await Dt(d,l.target)}catch(p){console.error(`Error: could not resolve ${l.target} to a user for the bot DM.
449
+ ${p instanceof Error?p.message:String(p)}
450
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(Qe)}u=d,l.mentionToken=d,l.asBot=!0}else{u=e(s),l.mentionToken=u;let d=t(s);if(d)l.cookie=d,l.mentionCookie=d}try{await ky(u,l)}catch(d){console.error(ie(d)),process.exit(Qe)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(s)=>s.positional("query",{type:"string",describe:"Substring of the message text (case-insensitive)"}).option("channel",{type:"string",describe:"Channel/DM id (C\u2026/D\u2026) or the target as typed (#eng, @bob)"}).option("since",{type:"string",describe:"Only newer than this: 30m, 2h, 7d, 1w, or an ISO date"}).option("session",{type:"string",describe:"Agent session id (prefix match)"}).option("cwd",{type:"string",describe:"Working directory the sender ran in (prefix match)"}).option("kind",{type:"string",choices:["send","ask","poll","edit"],describe:"Only this kind of write"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per line (every recorded field)"}).option("count",{alias:"n",type:"number",default:50,describe:"Max rows (newest first)"}),(s)=>{let r;if(s.since!==void 0){if(r=ko(String(s.since)),r===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${v(String(s.since))})`),process.exit(1)}let i={limit:Number(s.count)||50};if(s.query)i.text=String(s.query);if(s.channel)i.channel=String(s.channel);if(r!==void 0)i.sinceMs=r;if(s.session)i.session=String(s.session);if(s.cwd){let c=bm(String(s.cwd));try{i.cwd=Dm(c)}catch{i.cwd=c}}if(s.kind)i.kind=s.kind;let a=Ti(i);if(!a)console.error(`Error: ${ds}
451
+ (${lt()})`),process.exit(1);if(s.json){for(let c of a)console.log(JSON.stringify(c));return}if(!a.length){console.error(`No sent messages match (log: ${lt()}).`);return}for(let c of a)console.log(Jm(c))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(s)=>s,async()=>{let s=Je();if(!s)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
452
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await Sy(s)}).command("schedule","Manage scheduled messages",(s)=>s.command("send <target> <message>","Schedule a message for later delivery",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("at",{type:"string",demandOption:!0,describe:"Delivery time (ISO datetime or Unix ts)"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Schedule via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. Without it a scheduled DM to yourself is posted by you, and Slack never notifies you of your own message \u2014 it fires into silence."}),async(r)=>{if(!String(r.message??"").trim())console.error("Error: message is empty"),process.exit(1);let i={target:r.target,message:r.message,at:r.at};if(r.code)i.code=r.code;if(r["allow-url-adjacent"])i.allowUrlAdjacent=!0;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["user-id"])i.userId=r["user-id"],i.targetOverride=`--user-id ${r["user-id"]}`;let a;if(r["as-bot"]){let c=Ro();if(!i.channelId&&!i.userId&&i.target.startsWith("@"))try{i.userId=await Dt(e(r),i.target,t(r))}catch(l){console.error(`Error: could not resolve ${i.target} to a user for the bot DM.
446
453
  ${l instanceof Error?l.message:String(l)}
447
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}a=c,i.asBot=!0}else{a=e(r);let c=t(r);if(c)i.cookie=c}await hy(a,i)}).command(["ls","list"],"List pending scheduled messages",(r)=>r.positional("target",{type:"string",describe:"#channel to filter by"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"List what the BOT token scheduled. A message from `schedule send --as-bot` belongs to the app, so the user token's listing does not contain it \u2014 and an invisible pending message cannot be cancelled."}),async(r)=>{let i=r.target;if(r["as-bot"]){let a=Ao(),c=r["channel-id"];if(!c&&i?.startsWith("@"))c=await nf(i,a,e(r),t(r));await sf(a,i,c);return}await sf(e(r),i,r["channel-id"],t(r))}).command("rm <target> <id>","Delete a scheduled message",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#channel or @user"}).positional("id",{type:"string",demandOption:!0,describe:"Scheduled message ID"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Cancel a message scheduled with `schedule send --as-bot`. It belongs to the bot token, so the user token cannot delete it."}),async(r)=>{let i={target:r.target,id:r.id};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["as-bot"]){let c=Ao();if(!i.channelId&&i.target.startsWith("@"))i.channelId=await nf(i.target,c,e(r),t(r));i.asBot=!0,await of(c,i);return}let a=t(r);if(a)i.cookie=a;await of(e(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("newText",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm edit"}).option("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("channel-id",{type:"string",describe:"Raw channel ID"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens in the new text to real <@USERID> mentions (on by default). Unresolved handles stay as plain text. Disable with --no-mentions for literal @text."}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED to correct a message the bot posted: Slack only lets a token edit its OWN messages, so a bot-authored message is uneditable by the user token and chat.update returns cant_update_message. Address it by permalink or --channel-id; an @user target resolves against the BOT's DM list, which is where a bot-authored DM actually lives."}),async(s)=>{let r={target:s.target,newText:s.newText,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.force)r.force=!0;if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s.mentions!==!1)r.mentions=!0;let i;if(s["as-bot"]){let a=await Xd(r.target,e(s),t(s),r.channelId);if(i=a.botToken,a.channelId&&!r.channelId)r.channelId=a.channelId;r.asBot=!0,r.mentionToken=e(s);let c=t(s);if(c)r.mentionCookie=c}else{i=e(s);let a=t(s);if(a)r.cookie=a}await Pm(i,r)}).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).option("code",{type:"string",describe:"Safety hash to confirm delete"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Delete as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED for a message the bot posted: chat.delete refuses another token's message exactly as chat.update does."}),async(s)=>{let r={target:s.target};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];let i;if(s["as-bot"]){let a=await Xd(r.target,e(s),t(s),r.channelId);if(i=a.botToken,a.channelId&&!r.channelId)r.channelId=a.channelId;r.asBot=!0}else{i=e(s);let a=t(s);if(a)r.cookie=a}await vm(i,r)}).command("pinlog","Pinned status board: the pinned top-level message is the current state (edited in place, silent); each change is one thread reply (the log, notifies)",(s)=>{let r={type:"boolean",default:!1,describe:"Act via the bot token (xoxb / SLACK_BOT_TOKEN). A board the bot created can only be updated --as-bot: Slack lets a token edit only its own messages."},i=async(c)=>{if(c["as-bot"]){let u=Ao();if(typeof c.workspace==="string"){let d=t(c),[f,h]=await Promise.all([$n(e(c),d),$n(u)]);if(f.url!==h.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${h.url}, but -w ${c.workspace} is ${f.url}.
448
- Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:u,asBot:!0}}let l=t(c);return{token:e(c),...l?{cookie:l}:{},asBot:!1}},a=(c)=>{console.error(de(c)),process.exit(1)};return s.command("new <channel> [state] [reason]","Post a NEW board in a channel and pin it \u2014 the state is the top-level message; prints the board's id (C\u2026:ts)",(c)=>c.positional("channel",{type:"string",demandOption:!0,describe:"#chan or channel ID"}).positional("state",{type:"string",describe:"The whole state (\\n for newlines), or use --file"}).positional("reason",{type:"string",describe:"Optional: why the board exists \u2014 its first thread reply"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <channel> is the reason"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog new "#gtm" "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u672A"',"preview, then rerun with --code"),async(c)=>{let l=c.file!==void 0;if(l&&c.state!==void 0&&c.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let u=l?Fo(void 0,c.file):Fo(c.state,void 0),d=l?c.state:c.reason;if(u===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let f=await i(c),h={target:c.channel,state:u,asBot:f.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(d!==void 0)h.log=Oe(d);if(f.cookie)h.cookie=f.cookie;if(typeof c.workspace==="string")h.workspace=c.workspace;if(c.code)h.code=c.code;await Bm(f.token,h).catch(a)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(c)=>c.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("state",{type:"string",describe:"The WHOLE new state, not a diff (or --file)"}).positional("reason",{type:"string",describe:"One short line: what changed and why (required)"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <board> is the reason"}).option("adopt",{type:"boolean",default:!1,describe:"Allow a message WITHOUT the pinlog footer: turn a hand-run board into one"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog set <board-link> "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u6E08" "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"").example('slack pinlog set <board-link> --file board.md "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"state from a file"),async(c)=>{let l=c.file!==void 0;if(l&&c.state!==void 0&&c.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let u=l?Fo(void 0,c.file):Fo(c.state,void 0),d=l?c.state:c.reason;if(u===void 0||d===void 0)console.error("Error: `pinlog set` needs the whole new state AND the reason: slack pinlog set <board> '<state>' '<reason>'\n Only a reason, state unchanged: slack pinlog note <board> '<reason>'"),process.exit(2);let f=await i(c),h={target:c.board,state:u,log:Oe(d),adopt:c.adopt,asBot:f.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(typeof c.workspace==="string")h.workspace=c.workspace;if(f.cookie)h.cookie=f.cookie;if(c.code)h.code=c.code;await Zd(f.token,h).catch(a)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(c)=>c.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("reason",{type:"string",demandOption:!0,describe:"One short line, e.g. still blocked \u2014 chased X"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r),async(c)=>{let l=await i(c),u={target:c.board,log:Oe(c.reason),logOnly:!0,asBot:l.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(typeof c.workspace==="string")u.workspace=c.workspace;if(l.cookie)u.cookie=l.cookie;if(c.code)u.code=c.code;await Zd(l.token,u).catch(a)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(c)=>c.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or C\u2026:ts"}).option("json",{type:"boolean",default:!1,describe:"One JSON object: {id, isPinlog, updated, head, log[]}"}).option("as-bot",r),async(c)=>{let l=await i(c);await jm(l.token,c.board,l.cookie,c.json).catch(a)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(c)=>c.positional("channel",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:500,describe:"How many recent channel messages to scan"}).option("as-bot",r),async(c)=>{let l=await i(c);await Wm(l.token,c.channel,c.limit,l.cookie).catch(a)}).command("pin <board>",!1,(c)=>c.positional("board",{type:"string",demandOption:!0}).option("as-bot",r),async(c)=>{let l=await i(c);await Um(l.token,c.board,l.cookie).catch(a)}).demandCommand(1,"Pick one: ls | get | new | set | note")},()=>{}).command("react <target> <emoji>","Add (or --remove) an emoji reaction \u2014 a lightweight ack that doesn't grow the thread",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("emoji",{type:"string",demandOption:!0,describe:"Emoji shortcode without colons (e.g. eyes, white_check_mark, hourglass)"}).option("remove",{type:"boolean",default:!1,describe:"Remove the reaction instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(s)=>{let r={target:s.target,emoji:s.emoji};if(s.remove)r.remove=!0;if(s["channel-id"])r.channelId=s["channel-id"];let i=t(s);if(i)r.cookie=i;try{await Jm(e(s),r)}catch(a){console.error(de(a)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)Wi(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(r)=>r.options(n).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(r)=>{await o(r,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("state",{type:"string",demandOption:!0,choices:["pending","doing","done","dropped"]}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,state:r.state};if(r["channel-id"])i.channelId=r["channel-id"];let a=t(r);if(a)i.cookie=a;try{await xm(e(r),i)}catch(c){console.error(de(c)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("flag",{type:"string",demandOption:!0,choices:["alert","needs-discussion","waiting","blocked"],describe:"waiting = the other party in this conversation owes a reply; blocked = stuck on something outside it"}).option("remove",{type:"boolean",default:!1,describe:"Remove the flag instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,flag:r.flag};if(r.remove)i.remove=!0;if(r["channel-id"])i.channelId=r["channel-id"];let a=t(r);if(a)i.cookie=a;try{await Em(e(r),i)}catch(c){console.error(de(c)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(r)=>r.option("in",{type:"string",demandOption:!0,describe:"Channel to scan (#chan)"}).option("fix",{type:"boolean",default:!1,describe:"Repair findings (keeps the highest-priority state)"}).option("limit",{type:"number",default:ji,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={channel:r.in,limit:r.limit};if(r.fix)i.fix=!0;if(r["channel-id"])i.channelId=r["channel-id"];let a=t(r);if(a)i.cookie=a;await Sm(e(r),i)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)Wi(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(r)=>r.options(n),async(r)=>{await o(r,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}),async(s)=>{let r={target:s.target,filePaths:s.file};if(s.title)r.title=s.title;if(s.comment)r.comment=s.comment;if(s["allow-url-adjacent"])r.allowUrlAdjacent=!0;if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];let i=t(s);if(i)r.cookie=i;await gy(e(s),r)}).command("files","File commands",(s)=>s.command(["ls","list"],"List files visible to you (files.list)",(r)=>r.option("limit",{alias:"l",type:"number",default:100,describe:"Max files to list"}).option("type",{alias:"t",type:"string",describe:"Slack type filter: images, pdfs, gdocs, snippets, zips, spaces, all"}).option("channel",{alias:"c",type:"string",describe:"Only files in this channel (#name, @user, ID, or permalink)"}).option("user",{alias:"u",type:"string",describe:"Only files from this raw user ID"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{let i={limit:r.limit,format:r.json?"jsonl":r.format};if(r.type)i.types=r.type;if(r.channel)i.channel=r.channel;if(r.user)i.user=r.user;await my(e(r),t(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(s)=>s.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"List name"}).option("col",{type:"string",array:!0,default:[],describe:"Column name:type (text|select|user|link|date|number|checkbox); select takes name:select:a,b,c. First is the primary text column. Repeatable"}).option("todo",{type:"boolean",default:!1,describe:"Todo mode: adds Completed / Assignee / Due date columns"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{try{let i={name:r.name,cols:r.col,todo:r.todo===!0};if(r.code!==void 0)i.code=r.code;await by(i)}catch(i){console.error(de(i)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("text",{type:"string",demandOption:!0,describe:"Primary (first text) column value"}).option("set",{type:"string",array:!0,default:[],describe:"Other cells: column=value (repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm add"}),async(r)=>{try{let i={list:r.list,text:r.text,sets:r.set};if(r.code!==void 0)i.code=r.code;await ky(i)}catch(i){console.error(de(i)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("row",{type:"string",demandOption:!0,describe:"Row id (Rec\u2026), as printed by lists add / lists <ref>"}).option("set",{type:"string",array:!0,default:[],describe:"column=value (repeatable)"}).option("done",{type:"boolean",describe:"Check the row off (--no-done to uncheck); needs a todo-mode list"}).option("code",{type:"string",describe:"Safety hash to confirm update"}),async(r)=>{try{let i={list:r.list,row:r.row,sets:r.set};if(r.done!==void 0)i.done=r.done;if(r.code!==void 0)i.code=r.code;await xy(i)}catch(i){console.error(de(i)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).option("user",{type:"string",array:!0,default:[],describe:"User ID (U\u2026), repeatable"}).option("channel",{type:"string",array:!0,default:[],describe:"Channel ID (C\u2026), repeatable"}).option("level",{type:"string",choices:["read","write","owner"],default:"write"}).option("code",{type:"string",describe:"Safety hash to confirm share"}),async(r)=>{try{let i={list:r.list,users:r.user,channels:r.channel,level:r.level};if(r.code!==void 0)i.code=r.code;await Ey(i)}catch(i){console.error(de(i)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(r)=>r.positional("ref",{type:"string",demandOption:!0,describe:"List URL (\u2026/lists/<TEAM>/<F-id>) or bare F-id"}).option("limit",{alias:"l",type:"number",default:100,describe:"Max rows to show"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl (raw records)"}).option("as-bot",{type:"boolean",default:!1,describe:"Read with the bot token (SLACK_BOT_TOKEN, lists:read) via the public API instead of the user session"}),async(r)=>{let i=r.json?"jsonl":r.format;try{let a=r.asBot===!0;await Dy(a?"":e(r),a?void 0:t(r),r.ref,{limit:r.limit,format:i,asBot:a})}catch(a){console.error(de(a)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(s)=>s.positional("ref",{type:"string",demandOption:!0,describe:"File ID (F\u2026) or Slack file permalink"}).positional("dest",{type:"string",describe:"Output path or directory (default: ./<filename>)"}),async(s)=>{await Cy(e(s),t(s),s.ref,s.dest)}).command("dump","Bulk export channel history as markdown",(s)=>s.option("days",{alias:"d",type:"number",default:7,describe:"Days of history"}).option("limit",{alias:"l",type:"number",default:200}).option("filter",{alias:"f",type:"string",describe:"Filter channel names"}),async(s)=>{await Cm(e(s),s.days,s.limit,s.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (read-only; requires xoxc desktop token). Not `slack todo` (reaction tasks)",(s)=>s.command(["$0","ls","list"],"List your To-dos, soonest due first",(r)=>r.option("filter",{type:"string",choices:[...cd],default:"todo",describe:"todo = open to-dos; saved = everything saved; completed; archived"}).option("limit",{alias:"n",type:"number",default:50,describe:"At most this many items"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per item (raw fields + permalink + message text)"}),async(r)=>{if(!Number.isInteger(r.limit)||r.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${r.limit}).`),process.exit(2);await Fm(e(r),t(r),{filter:r.filter,limit:r.limit,json:r.json})})).command("drafts","Manage message drafts (requires xoxc desktop token)",(s)=>s.command(["$0","ls","list"],"List pending drafts",(r)=>r.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(r)=>{await $m(e(r),t(r),r.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(r)=>r.positional("channel",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),a=t(r),c=r.text.join(" ");if(!c)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);Ne(c,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await ye(i,r.channel,a),u=await td(i,l,c,a);console.log(`\u2713 Draft created (id: ${_(u.draft).id??"?"})`)}).command("get <id>","Show a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}),async(r)=>{await Am(e(r),t(r),r.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("code",{type:"string"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),a=t(r),c=r.text.join(" ");if(!c)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);Ne(c,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await fs(i,a),u=H(l.drafts).map(_).find((p)=>String(p.id)===r.id);if(!u)console.error(`Draft not found: ${r.id}`),process.exit(1);let d=Oo(u),f=await Ue(i,a),h=ge(d,c,f?.userId??"");if(r.code!==h)De(r.code,h,["--- Editing draft as -------------------------",we(f),"--- Current draft ----------------------------",...d.split(`
449
- `).map((p)=>` ${p}`),"--- Replacing with ---------------------------",...c.split(`
450
- `).map((p)=>` ${p}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let g=await nd(i,r.id,sa(u),c,a);console.log(`\u2713 Draft updated (id: ${_(g.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(r)=>{let i=e(r),a=t(r),c=await fs(i,a),l=H(c.drafts).map(_).find((h)=>String(h.id)===r.id);if(!l)console.error(`Draft not found: ${r.id}`),process.exit(1);let u=Oo(l),d=await Ue(i,a),f=ge(r.id,u,d?.userId??"");if(r.code!==f)De(r.code,f,["\u2500-- Deleting draft \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",we(d),` id: ${r.id}`,...u.split(`
451
- `).map((h)=>` ${h}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await rd(i,r.id,a),console.log(`\u2713 Draft deleted (id: ${r.id})`)})).command("auth","Authentication and workspace management",(s)=>s.command("token","Print the active token (or save one with --token)",(r)=>r.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(r)=>{if(r.token===void 0){console.log(qn(r.workspace));return}await Fl({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(r)=>{let i=qn(r.workspace),a=i.startsWith("xoxc-")?$r(r.workspace):void 0,c=[["SLACK_TOKEN",i]];if(a)c.push(["SLACK_COOKIE",a]);let l=c.map(([u,d])=>{if(/[\r\n\0']/.test(d))throw Error(`Cannot export ${u}: unsupported characters in credential`);return`${u}='${d}'`});console.log(l.join(`
452
- `))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(r)=>r.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(r)=>{await Al({...r.bot!==void 0?{bot:r.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(r)=>r.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(i)=>i.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(i)=>{await ni({...i.profile!==void 0?{profile:i.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(i)=>i.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(i)=>{await si({...i.workspace!==void 0?{workspace:i.workspace}:{}})}).option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}).option("from-desktop",{type:"boolean",default:!1,describe:"Import the Slack Desktop token without scanning a browser"}).option("from-chrome",{type:"boolean",default:!1,describe:"Import the desktop token and Chrome cookie"}).option("from-firefox",{type:"boolean",default:!1,describe:"Import the desktop token and Firefox cookie"}).option("from-all",{type:"boolean",default:!1,describe:"Import the desktop token and scan Chrome and Firefox"}).command("$0",!1,()=>{},async(i)=>{await ss({...i.token!==void 0?{token:i.token}:{},...i.name!==void 0?{name:i.name}:{},yes:i.yes,fromDesktop:i.fromDesktop,fromChrome:i.fromChrome,fromFirefox:i.fromFirefox,fromAll:i.fromAll})}),async(r)=>{await ss({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{},yes:r.yes,fromDesktop:r.fromDesktop,fromChrome:r.fromChrome,fromFirefox:r.fromFirefox,fromAll:r.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>Tl({...r.workspace!==void 0?{workspace:r.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(r)=>r.option("envfile",{type:"string",demandOption:!0,describe:"Destination env file (e.g. ./.env.local)"}).option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>Il({envfile:r.envfile,...r.workspace!==void 0?{workspace:r.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let r=_r();if(r.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:i,profile:a,current:c}of r)console.log(`${c?"* ":" "}${i} ${a.team} (${a.user}) ${a.url??""}`)}).command("use <name>","Switch active workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(r)=>{if(!r.g)lm(Nt(process.cwd(),".slack-cli"));Gc(r.name,r.g),console.log(`Switched to workspace "${r.name}" ${r.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}),(r)=>{zc(r.name),console.log(`Removed workspace "${r.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("profile",{type:"string",alias:"p",describe:"Chrome profile email or dir (Windows, when several have a session)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await $l({...r.workspace!==void 0?{workspace:r.workspace}:{},...r.profile!==void 0?{profile:r.profile}:{},yes:r.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await si({...r.workspace!==void 0?{workspace:r.workspace}:{},yes:r.yes})}).command("$0",!1,()=>{},()=>{s.showHelp(),process.exit(0)})).command("tail [target]","Stream new messages in real time (like tail -f)",(s)=>s.positional("target",{type:"string",describe:"#channel or @user to follow"}).option("since",{type:"string",describe:"Backfill from N ago (e.g. 10m, 2h, 1d)"}).option("thread",{type:"string",describe:"Follow a single thread by timestamp"}).option("watch-thread",{type:"string",describe:"Watch the channel's top-level timeline AND one thread's replies together (ts or permalink)"}).option("me",{type:"boolean",default:!1,describe:"Filter to messages that mention you"}).option("interval",{type:"number",default:60000,describe:"Poll interval in ms (default 60s; use --interval=3000 for near-real-time)"}).option("timeout",{type:"string",describe:"Auto-stop after this long (e.g. 30m, 2h). Exit code 0 even if nothing arrived."}).option("exit-on-message",{type:"boolean",default:!1,describe:"Stop as soon as the first new message from someone else arrives (wait-for-reply)"}).option("rtm",{type:"boolean",default:!0,describe:"Use RTM WebSocket when available (xoxc + cookie); pass --no-rtm to force polling"}),async(s)=>{let r=e(s),i=t(s),a=new AbortController;process.on("SIGINT",()=>{a.abort(),process.exit(0)}),await Nl(r,s.target,{...s.since!==void 0?{since:s.since}:{},...s.thread!==void 0?{thread:s.thread}:{},...s["watch-thread"]!==void 0?{watchThread:s["watch-thread"]}:{},me:s.me,interval:s.interval,...s.timeout!==void 0?{timeout:s.timeout}:{},...s["exit-on-message"]===!0?{exitOnMessage:!0}:{},...i!==void 0?{cookie:i}:{},...s.rtm===!1?{noRtm:!0}:{}},a.signal)}).command("login",!1,(s)=>s.option("token",{type:"string"}).option("name",{type:"string"}).option("yes",{type:"boolean",default:!1}).option("from-desktop",{type:"boolean",default:!1}).option("from-chrome",{type:"boolean",default:!1}).option("from-firefox",{type:"boolean",default:!1}).option("from-all",{type:"boolean",default:!1}),async(s)=>{await ss({...s.token!==void 0?{token:s.token}:{},...s.name!==void 0?{name:s.name}:{},yes:s.yes,fromDesktop:s.fromDesktop,fromChrome:s.fromChrome,fromFirefox:s.fromFirefox,fromAll:s.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}_y().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
454
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}a=c,i.asBot=!0}else{a=e(r);let c=t(r);if(c)i.cookie=c}await $y(a,i)}).command(["ls","list"],"List pending scheduled messages",(r)=>r.positional("target",{type:"string",describe:"#channel to filter by"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"List what the BOT token scheduled. A message from `schedule send --as-bot` belongs to the app, so the user token's listing does not contain it \u2014 and an invisible pending message cannot be cancelled."}),async(r)=>{let i=r.target;if(r["as-bot"]){let a=Ro(),c=r["channel-id"];if(!c&&i?.startsWith("@"))c=await df(i,a,e(r),t(r));await ff(a,i,c);return}await ff(e(r),i,r["channel-id"],t(r))}).command("rm <target> <id>","Delete a scheduled message",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#channel or @user"}).positional("id",{type:"string",demandOption:!0,describe:"Scheduled message ID"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Cancel a message scheduled with `schedule send --as-bot`. It belongs to the bot token, so the user token cannot delete it."}),async(r)=>{let i={target:r.target,id:r.id};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"],i.targetOverride=`--channel-id ${r["channel-id"]}`;if(r["as-bot"]){let c=Ro();if(!i.channelId&&i.target.startsWith("@"))i.channelId=await df(i.target,c,e(r),t(r));i.asBot=!0,await pf(c,i);return}let a=t(r);if(a)i.cookie=a;await pf(e(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("newText",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm edit"}).option("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("channel-id",{type:"string",describe:"Raw channel ID"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens in the new text to real <@USERID> mentions (on by default). Unresolved handles stay as plain text. Disable with --no-mentions for literal @text."}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED to correct a message the bot posted: Slack only lets a token edit its OWN messages, so a bot-authored message is uneditable by the user token and chat.update returns cant_update_message. Address it by permalink or --channel-id; an @user target resolves against the BOT's DM list, which is where a bot-authored DM actually lives."}),async(s)=>{let r={target:s.target,newText:s.newText,allowUrlAdjacent:s["allow-url-adjacent"]};if(s.force)r.force=!0;if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s.mentions!==!1)r.mentions=!0;let i;if(s["as-bot"]){let a=await of(r.target,e(s),t(s),r.channelId);if(i=a.botToken,a.channelId&&!r.channelId)r.channelId=a.channelId;r.asBot=!0,r.mentionToken=e(s);let c=t(s);if(c)r.mentionCookie=c}else{i=e(s);let a=t(s);if(a)r.cookie=a}await Hm(i,r)}).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).option("code",{type:"string",describe:"Safety hash to confirm delete"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Delete as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED for a message the bot posted: chat.delete refuses another token's message exactly as chat.update does."}),async(s)=>{let r={target:s.target};if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];let i;if(s["as-bot"]){let a=await of(r.target,e(s),t(s),r.channelId);if(i=a.botToken,a.channelId&&!r.channelId)r.channelId=a.channelId;r.asBot=!0}else{i=e(s);let a=t(s);if(a)r.cookie=a}await zm(i,r)}).command("pinlog","Pinned status board: the pinned top-level message is the current state (edited in place, silent); each change is one thread reply (the log, notifies)",(s)=>{let r={type:"boolean",default:!1,describe:"Act via the bot token (xoxb / SLACK_BOT_TOKEN). A board the bot created can only be updated --as-bot: Slack lets a token edit only its own messages."},i=async(c)=>{if(c["as-bot"]){let u=Ro();if(typeof c.workspace==="string"){let d=t(c),[p,h]=await Promise.all([$n(e(c),d),$n(u)]);if(p.url!==h.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${h.url}, but -w ${c.workspace} is ${p.url}.
455
+ Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:u,asBot:!0}}let l=t(c);return{token:e(c),...l?{cookie:l}:{},asBot:!1}},a=(c)=>{console.error(ie(c)),process.exit(1)};return s.command("new <channel> [state] [reason]","Post a NEW board in a channel and pin it \u2014 the state is the top-level message; prints the board's id (C\u2026:ts)",(c)=>c.positional("channel",{type:"string",demandOption:!0,describe:"#chan or channel ID"}).positional("state",{type:"string",describe:"The whole state (\\n for newlines), or use --file"}).positional("reason",{type:"string",describe:"Optional: why the board exists \u2014 its first thread reply"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <channel> is the reason"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog new "#gtm" "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u672A"',"preview, then rerun with --code"),async(c)=>{let l=c.file!==void 0;if(l&&c.state!==void 0&&c.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let u=l?Oo(void 0,c.file):Oo(c.state,void 0),d=l?c.state:c.reason;if(u===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let p=await i(c),h={target:c.channel,state:u,asBot:p.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(d!==void 0)h.log=Fe(d);if(p.cookie)h.cookie=p.cookie;if(typeof c.workspace==="string")h.workspace=c.workspace;if(c.code)h.code=c.code;await Ym(p.token,h).catch(a)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(c)=>c.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("state",{type:"string",describe:"The WHOLE new state, not a diff (or --file)"}).positional("reason",{type:"string",describe:"One short line: what changed and why (required)"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <board> is the reason"}).option("adopt",{type:"boolean",default:!1,describe:"Allow a message WITHOUT the pinlog footer: turn a hand-run board into one"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog set <board-link> "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u6E08" "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"").example('slack pinlog set <board-link> --file board.md "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"state from a file"),async(c)=>{let l=c.file!==void 0;if(l&&c.state!==void 0&&c.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let u=l?Oo(void 0,c.file):Oo(c.state,void 0),d=l?c.state:c.reason;if(u===void 0||d===void 0)console.error("Error: `pinlog set` needs the whole new state AND the reason: slack pinlog set <board> '<state>' '<reason>'\n Only a reason, state unchanged: slack pinlog note <board> '<reason>'"),process.exit(2);let p=await i(c),h={target:c.board,state:u,log:Fe(d),adopt:c.adopt,asBot:p.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(typeof c.workspace==="string")h.workspace=c.workspace;if(p.cookie)h.cookie=p.cookie;if(c.code)h.code=c.code;await af(p.token,h).catch(a)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(c)=>c.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("reason",{type:"string",demandOption:!0,describe:"One short line, e.g. still blocked \u2014 chased X"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r),async(c)=>{let l=await i(c),u={target:c.board,log:Fe(c.reason),logOnly:!0,asBot:l.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(typeof c.workspace==="string")u.workspace=c.workspace;if(l.cookie)u.cookie=l.cookie;if(c.code)u.code=c.code;await af(l.token,u).catch(a)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(c)=>c.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or C\u2026:ts"}).option("json",{type:"boolean",default:!1,describe:"One JSON object: {id, isPinlog, updated, head, log[]}"}).option("as-bot",r),async(c)=>{let l=await i(c);await Zm(l.token,c.board,l.cookie,c.json).catch(a)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(c)=>c.positional("channel",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:500,describe:"How many recent channel messages to scan"}).option("as-bot",r),async(c)=>{let l=await i(c);await Qm(l.token,c.channel,c.limit,l.cookie).catch(a)}).command("pin <board>",!1,(c)=>c.positional("board",{type:"string",demandOption:!0}).option("as-bot",r),async(c)=>{let l=await i(c);await ey(l.token,c.board,l.cookie).catch(a)}).demandCommand(1,"Pick one: ls | get | new | set | note")},()=>{}).command("react <target> <emoji>","Add (or --remove) an emoji reaction \u2014 a lightweight ack that doesn't grow the thread",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("emoji",{type:"string",demandOption:!0,describe:"Emoji shortcode without colons (e.g. eyes, white_check_mark, hourglass)"}).option("remove",{type:"boolean",default:!1,describe:"Remove the reaction instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(s)=>{let r={target:s.target,emoji:s.emoji};if(s.remove)r.remove=!0;if(s["channel-id"])r.channelId=s["channel-id"];let i=t(s);if(i)r.cookie=i;try{await ty(e(s),r)}catch(a){console.error(ie(a)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)qi(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(r)=>r.options(n).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(r)=>{await o(r,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("state",{type:"string",demandOption:!0,choices:["pending","doing","done","dropped"]}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,state:r.state};if(r["channel-id"])i.channelId=r["channel-id"];let a=t(r);if(a)i.cookie=a;try{await Pm(e(r),i)}catch(c){console.error(ie(c)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("flag",{type:"string",demandOption:!0,choices:["alert","needs-discussion","waiting","blocked"],describe:"waiting = the other party in this conversation owes a reply; blocked = stuck on something outside it"}).option("remove",{type:"boolean",default:!1,describe:"Remove the flag instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,flag:r.flag};if(r.remove)i.remove=!0;if(r["channel-id"])i.channelId=r["channel-id"];let a=t(r);if(a)i.cookie=a;try{await vm(e(r),i)}catch(c){console.error(ie(c)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(r)=>r.option("in",{type:"string",demandOption:!0,describe:"Channel to scan (#chan)"}).option("fix",{type:"boolean",default:!1,describe:"Repair findings (keeps the highest-priority state)"}).option("limit",{type:"number",default:Ki,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={channel:r.in,limit:r.limit};if(r.fix)i.fix=!0;if(r["channel-id"])i.channelId=r["channel-id"];let a=t(r);if(a)i.cookie=a;await Bm(e(r),i)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)qi(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(r)=>r.options(n),async(r)=>{await o(r,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}),async(s)=>{let r={target:s.target,filePaths:s.file};if(s.title)r.title=s.title;if(s.comment)r.comment=s.comment;if(s["allow-url-adjacent"])r.allowUrlAdjacent=!0;if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];let i=t(s);if(i)r.cookie=i;await Fy(e(s),r)}).command("files","File commands",(s)=>s.command(["ls","list"],"List files visible to you (files.list)",(r)=>r.option("limit",{alias:"l",type:"number",default:100,describe:"Max files to list"}).option("type",{alias:"t",type:"string",describe:"Slack type filter: images, pdfs, gdocs, snippets, zips, spaces, all"}).option("channel",{alias:"c",type:"string",describe:"Only files in this channel (#name, @user, ID, or permalink)"}).option("user",{alias:"u",type:"string",describe:"Only files from this raw user ID"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{let i={limit:r.limit,format:r.json?"jsonl":r.format};if(r.type)i.types=r.type;if(r.channel)i.channel=r.channel;if(r.user)i.user=r.user;await Ay(e(r),t(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(s)=>s.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"List name"}).option("col",{type:"string",array:!0,default:[],describe:"Column name:type (text|select|user|link|date|number|checkbox); select takes name:select:a,b,c. First is the primary text column. Repeatable"}).option("todo",{type:"boolean",default:!1,describe:"Todo mode: adds Completed / Assignee / Due date columns"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{try{let i={name:r.name,cols:r.col,todo:r.todo===!0};if(r.code!==void 0)i.code=r.code;await Ry(i)}catch(i){console.error(ie(i)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("text",{type:"string",demandOption:!0,describe:"Primary (first text) column value"}).option("set",{type:"string",array:!0,default:[],describe:"Other cells: column=value (repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm add"}),async(r)=>{try{let i={list:r.list,text:r.text,sets:r.set};if(r.code!==void 0)i.code=r.code;await Py(i)}catch(i){console.error(ie(i)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("row",{type:"string",demandOption:!0,describe:"Row id (Rec\u2026), as printed by lists add / lists <ref>"}).option("set",{type:"string",array:!0,default:[],describe:"column=value (repeatable)"}).option("done",{type:"boolean",describe:"Check the row off (--no-done to uncheck); needs a todo-mode list"}).option("code",{type:"string",describe:"Safety hash to confirm update"}),async(r)=>{try{let i={list:r.list,row:r.row,sets:r.set};if(r.done!==void 0)i.done=r.done;if(r.code!==void 0)i.code=r.code;await vy(i)}catch(i){console.error(ie(i)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).option("user",{type:"string",array:!0,default:[],describe:"User ID (U\u2026), repeatable"}).option("channel",{type:"string",array:!0,default:[],describe:"Channel ID (C\u2026), repeatable"}).option("level",{type:"string",choices:["read","write","owner"],default:"write"}).option("code",{type:"string",describe:"Safety hash to confirm share"}),async(r)=>{try{let i={list:r.list,users:r.user,channels:r.channel,level:r.level};if(r.code!==void 0)i.code=r.code;await By(i)}catch(i){console.error(ie(i)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(r)=>r.positional("ref",{type:"string",demandOption:!0,describe:"List URL (\u2026/lists/<TEAM>/<F-id>) or bare F-id"}).option("limit",{alias:"l",type:"number",default:100,describe:"Max rows to show"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl (raw records)"}).option("as-bot",{type:"boolean",default:!1,describe:"Read with the bot token (SLACK_BOT_TOKEN, lists:read) via the public API instead of the user session"}),async(r)=>{let i=r.json?"jsonl":r.format;try{let a=r.asBot===!0;await Iy(a?"":e(r),a?void 0:t(r),r.ref,{limit:r.limit,format:i,asBot:a})}catch(a){console.error(ie(a)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(s)=>s.positional("ref",{type:"string",demandOption:!0,describe:"File ID (F\u2026) or Slack file permalink"}).positional("dest",{type:"string",describe:"Output path or directory (default: ./<filename>)"}),async(s)=>{await Ny(e(s),t(s),s.ref,s.dest)}).command("dump","Bulk export channel history as markdown",(s)=>s.option("days",{alias:"d",type:"number",default:7,describe:"Days of history"}).option("limit",{alias:"l",type:"number",default:200}).option("filter",{alias:"f",type:"string",describe:"Filter channel names"}),async(s)=>{await Lm(e(s),s.days,s.limit,s.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (read-only; requires xoxc desktop token). Not `slack todo` (reaction tasks)",(s)=>s.command(["$0","ls","list"],"List your To-dos, soonest due first",(r)=>r.option("filter",{type:"string",choices:[...md],default:"todo",describe:"todo = open to-dos; saved = everything saved; completed; archived"}).option("limit",{alias:"n",type:"number",default:50,describe:"At most this many items"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per item (raw fields + permalink + message text)"}),async(r)=>{if(!Number.isInteger(r.limit)||r.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${r.limit}).`),process.exit(2);await jm(e(r),t(r),{filter:r.filter,limit:r.limit,json:r.json})})).command("drafts","Manage message drafts (requires xoxc desktop token)",(s)=>s.command(["$0","ls","list"],"List pending drafts",(r)=>r.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(r)=>{await Mm(e(r),t(r),r.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(r)=>r.positional("channel",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),a=t(r),c=r.text.join(" ");if(!c)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);Be(c,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await fe(i,r.channel,a),u=await ld(i,l,c,a);console.log(`\u2713 Draft created (id: ${T(u.draft).id??"?"})`)}).command("get <id>","Show a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}),async(r)=>{await Wm(e(r),t(r),r.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("code",{type:"string"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),a=t(r),c=r.text.join(" ");if(!c)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);Be(c,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await gs(i,a),u=H(l.drafts).map(T).find((f)=>String(f.id)===r.id);if(!u)console.error(`Draft not found: ${r.id}`),process.exit(1);let d=Bo(u),p=await Te(i,a),h=ue(d,c,p?.userId??"");if(r.code!==h)pe(r.code,h,["--- Editing draft as -------------------------",he(p),"--- Current draft ----------------------------",...d.split(`
456
+ `).map((f)=>` ${f}`),"--- Replacing with ---------------------------",...c.split(`
457
+ `).map((f)=>` ${f}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let y=await ud(i,r.id,ca(u),c,a);console.log(`\u2713 Draft updated (id: ${T(y.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(r)=>{let i=e(r),a=t(r),c=await gs(i,a),l=H(c.drafts).map(T).find((h)=>String(h.id)===r.id);if(!l)console.error(`Draft not found: ${r.id}`),process.exit(1);let u=Bo(l),d=await Te(i,a),p=ue(r.id,u,d?.userId??"");if(r.code!==p)pe(r.code,p,["\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",he(d),` id: ${r.id}`,...u.split(`
458
+ `).map((h)=>` ${h}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await pd(i,r.id,a),console.log(`\u2713 Draft deleted (id: ${r.id})`)})).command("auth","Authentication and workspace management",(s)=>s.command("token","Print the active token (or save one with --token)",(r)=>r.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(r)=>{if(r.token===void 0){console.log(Hn(r.workspace));return}await Rl({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(r)=>{let i=Hn(r.workspace),a=i.startsWith("xoxc-")?Ir(r.workspace):void 0,c=[["SLACK_TOKEN",i]];if(a)c.push(["SLACK_COOKIE",a]);let l=c.map(([u,d])=>{if(/[\r\n\0']/.test(d))throw Error(`Cannot export ${u}: unsupported characters in credential`);return`${u}='${d}'`});console.log(l.join(`
459
+ `))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(r)=>r.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(r)=>{await Pl({...r.bot!==void 0?{bot:r.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(r)=>r.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(i)=>i.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(i)=>{await ii({...i.profile!==void 0?{profile:i.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(i)=>i.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(i)=>{await ai({...i.workspace!==void 0?{workspace:i.workspace}:{}})}).option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}).option("from-desktop",{type:"boolean",default:!1,describe:"Import the Slack Desktop token without scanning a browser"}).option("from-chrome",{type:"boolean",default:!1,describe:"Import the desktop token and Chrome cookie"}).option("from-firefox",{type:"boolean",default:!1,describe:"Import the desktop token and Firefox cookie"}).option("from-all",{type:"boolean",default:!1,describe:"Import the desktop token and scan Chrome and Firefox"}).command("$0",!1,()=>{},async(i)=>{await os({...i.token!==void 0?{token:i.token}:{},...i.name!==void 0?{name:i.name}:{},yes:i.yes,fromDesktop:i.fromDesktop,fromChrome:i.fromChrome,fromFirefox:i.fromFirefox,fromAll:i.fromAll})}),async(r)=>{await os({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{},yes:r.yes,fromDesktop:r.fromDesktop,fromChrome:r.fromChrome,fromFirefox:r.fromFirefox,fromAll:r.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>vl({...r.workspace!==void 0?{workspace:r.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(r)=>r.option("envfile",{type:"string",demandOption:!0,describe:"Destination env file (e.g. ./.env.local)"}).option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>Bl({envfile:r.envfile,...r.workspace!==void 0?{workspace:r.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let r=Tr();if(r.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:i,profile:a,current:c}of r)console.log(`${c?"* ":" "}${i} ${a.team} (${a.user}) ${a.url??""}`)}).command("use <name>","Switch active workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(r)=>{if(!r.g)km(Mt(process.cwd(),".slack-cli"));Qc(r.name,r.g),console.log(`Switched to workspace "${r.name}" ${r.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}),(r)=>{Zc(r.name),console.log(`Removed workspace "${r.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("profile",{type:"string",alias:"p",describe:"Chrome profile email or dir (Windows, when several have a session)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await Ol({...r.workspace!==void 0?{workspace:r.workspace}:{},...r.profile!==void 0?{profile:r.profile}:{},yes:r.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await ai({...r.workspace!==void 0?{workspace:r.workspace}:{},yes:r.yes})}).command("$0",!1,()=>{},()=>{s.showHelp(),process.exit(0)})).command("tail [target]","Stream new messages in real time (like tail -f)",(s)=>s.positional("target",{type:"string",describe:"#channel or @user to follow"}).option("since",{type:"string",describe:"Backfill from N ago (e.g. 10m, 2h, 1d)"}).option("thread",{type:"string",describe:"Follow a single thread by timestamp"}).option("watch-thread",{type:"string",describe:"Watch the channel's top-level timeline AND one thread's replies together (ts or permalink)"}).option("me",{type:"boolean",default:!1,describe:"Filter to messages that mention you"}).option("interval",{type:"number",default:60000,describe:"Poll interval in ms (default 60s; use --interval=3000 for near-real-time)"}).option("timeout",{type:"string",describe:"Auto-stop after this long (e.g. 30m, 2h). Exit code 0 even if nothing arrived."}).option("exit-on-message",{type:"boolean",default:!1,describe:"Stop as soon as the first new message from someone else arrives (wait-for-reply)"}).option("rtm",{type:"boolean",default:!0,describe:"Use RTM WebSocket when available (xoxc + cookie); pass --no-rtm to force polling"}),async(s)=>{let r=e(s),i=t(s),a=new AbortController;process.on("SIGINT",()=>{a.abort(),process.exit(0)}),await Jl(r,s.target,{...s.since!==void 0?{since:s.since}:{},...s.thread!==void 0?{thread:s.thread}:{},...s["watch-thread"]!==void 0?{watchThread:s["watch-thread"]}:{},me:s.me,interval:s.interval,...s.timeout!==void 0?{timeout:s.timeout}:{},...s["exit-on-message"]===!0?{exitOnMessage:!0}:{},...i!==void 0?{cookie:i}:{},...s.rtm===!1?{noRtm:!0}:{}},a.signal)}).command("login",!1,(s)=>s.option("token",{type:"string"}).option("name",{type:"string"}).option("yes",{type:"boolean",default:!1}).option("from-desktop",{type:"boolean",default:!1}).option("from-chrome",{type:"boolean",default:!1}).option("from-firefox",{type:"boolean",default:!1}).option("from-all",{type:"boolean",default:!1}),async(s)=>{await os({...s.token!==void 0?{token:s.token}:{},...s.name!==void 0?{name:s.name}:{},yes:s.yes,fromDesktop:s.fromDesktop,fromChrome:s.fromChrome,fromFirefox:s.fromFirefox,fromAll:s.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}My().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});