slack-term 1.51.0 → 1.51.2

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 rm}from"node:module";var Qg=Object.create;var{getPrototypeOf:em,defineProperty:Zc,getOwnPropertyNames:tm}=Object;var Qc=Object.prototype.hasOwnProperty;function nm(e){return this[e]}var sm,om,el=(e,t,n)=>{var s=e!=null&&typeof e==="object";if(s){var o=t?sm??=new WeakMap:om??=new WeakMap,r=o.get(e);if(r)return r}n=e!=null?Qg(em(e)):{};let i=t||!e||!e.__esModule||!Qc.call(e,"default")?Zc(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let l of tm(e))if(!Qc.call(i,l))Zc(i,l,{get:nm.bind(e,l),enumerable:!0})}if(s)o.set(e,i);return i};var tl=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ps=rm(import.meta.url);var wl=tl(function(Ix,bl){bl.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 ql=tl(function(kS,Kl){Kl.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(o,r){return r};var s=Error().stack;if(Error.prepareStackTrace=n,s!==null&&typeof s==="object")return s[t]?s[t].getFileName():void 0}});import{createHash as Ag}from"crypto";import{existsSync as Fg,readFileSync as Hc,mkdirSync as K0,realpathSync as q0,writeFileSync as Tg}from"fs";import{homedir as Wc}from"os";import{dirname as H0,join as Tt,resolve as z0}from"path";import{notStrictEqual as Km,strictEqual as qm}from"assert";var im={right:lm,center:um};class sl{constructor(e){var t;this.width=e.width,this.wrap=(t=e.wrap)!==null&&t!==void 0?t:!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==="string")return this.applyLayoutDSL(e[0]);let t=e.map((n)=>{if(typeof n==="string")return this.colFromString(n);return n});return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==="string"&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
3
+ import{createRequire as cm}from"node:module";var nm=Object.create;var{getPrototypeOf:sm,defineProperty:sl,getOwnPropertyNames:om}=Object;var ol=Object.prototype.hasOwnProperty;function rm(e){return this[e]}var im,am,rl=(e,t,n)=>{var s=e!=null&&typeof e==="object";if(s){var o=t?im??=new WeakMap:am??=new WeakMap,r=o.get(e);if(r)return r}n=e!=null?nm(sm(e)):{};let i=t||!e||!e.__esModule||!ol.call(e,"default")?sl(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let l of om(e))if(!ol.call(i,l))sl(i,l,{get:rm.bind(e,l),enumerable:!0})}if(s)o.set(e,i);return i};var il=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ps=cm(import.meta.url);var _l=il(function(Px,Sl){Sl.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 Xl=il(function(SS,Gl){Gl.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(o,r){return r};var s=Error().stack;if(Error.prepareStackTrace=n,s!==null&&typeof s==="object")return s[t]?s[t].getFileName():void 0}});import{createHash as Og}from"crypto";import{existsSync as Rg,readFileSync as Vc,mkdirSync as z0,realpathSync as Y0,writeFileSync as Ig}from"fs";import{homedir as Hc}from"os";import{dirname as G0,join as Ot,resolve as X0}from"path";import{notStrictEqual as zm,strictEqual as Ym}from"assert";var lm={right:fm,center:pm};class cl{constructor(e){var t;this.width=e.width,this.wrap=(t=e.wrap)!==null&&t!==void 0?t:!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==="string")return this.applyLayoutDSL(e[0]);let t=e.map((n)=>{if(typeof n==="string")return this.colFromString(n);return n});return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==="string"&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
4
4
  `).map((s)=>s.split("\t")),n=0;return t.forEach((s)=>{if(s.length>1&&Ze.stringWidth(s[0])>n)n=Math.min(Math.floor(this.width*0.5),Ze.stringWidth(s[0]))}),t.forEach((s)=>{this.div(...s.map((o,r)=>({text:o.trim(),padding:this.measurePadding(o),width:r===0&&s.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=Ze.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach((t)=>{this.rowToString(t,e)}),e.filter((t)=>!t.hidden).map((t)=>t.text).join(`
5
- `)}rowToString(e,t){return this.rasterize(e).forEach((n,s)=>{let o="";n.forEach((r,i)=>{let{width:l}=e[i],u=this.negatePadding(e[i]),c=r;if(u>Ze.stringWidth(r))c+=" ".repeat(u-Ze.stringWidth(r));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=im[e[i].align];if(c=d(c,u),Ze.stringWidth(c)<u)c+=" ".repeat((l||0)-Ze.stringWidth(c)-1)}let a=e[i].padding||[0,0,0,0];if(a[3])o+=" ".repeat(a[3]);if(o+=nl(e[i],c,"| "),o+=c,o+=nl(e[i],c," |"),a[1])o+=" ".repeat(a[1]);if(s===0&&t.length>0)o=this.renderInline(o,t[t.length-1])}),t.push({text:o.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),s=n?n[0].length:0,o=t.text,r=Ze.stringWidth(o.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,o+e;if(s<r)return e;return t.hidden=!0,o.trimRight()+" ".repeat(s-r)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),s;return e.forEach((o,r)=>{if(o.width=n[r],this.wrap)s=Ze.wrap(o.text,this.negatePadding(o),{hard:!0}).split(`
5
+ `)}rowToString(e,t){return this.rasterize(e).forEach((n,s)=>{let o="";n.forEach((r,i)=>{let{width:l}=e[i],u=this.negatePadding(e[i]),c=r;if(u>Ze.stringWidth(r))c+=" ".repeat(u-Ze.stringWidth(r));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=lm[e[i].align];if(c=d(c,u),Ze.stringWidth(c)<u)c+=" ".repeat((l||0)-Ze.stringWidth(c)-1)}let a=e[i].padding||[0,0,0,0];if(a[3])o+=" ".repeat(a[3]);if(o+=al(e[i],c,"| "),o+=c,o+=al(e[i],c," |"),a[1])o+=" ".repeat(a[1]);if(s===0&&t.length>0)o=this.renderInline(o,t[t.length-1])}),t.push({text:o.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),s=n?n[0].length:0,o=t.text,r=Ze.stringWidth(o.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,o+e;if(s<r)return e;return t.hidden=!0,o.trimRight()+" ".repeat(s-r)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),s;return e.forEach((o,r)=>{if(o.width=n[r],this.wrap)s=Ze.wrap(o.text,this.negatePadding(o),{hard:!0}).split(`
6
6
  `);else s=o.text.split(`
7
- `);if(o.border)s.unshift("."+"-".repeat(this.negatePadding(o)+2)+"."),s.push("'"+"-".repeat(this.negatePadding(o)+2)+"'");if(o.padding)s.unshift(...Array(o.padding[0]||0).fill("")),s.push(...Array(o.padding[2]||0).fill(""));s.forEach((i,l)=>{if(!t[l])t.push([]);let u=t[l];for(let c=0;c<r;c++)if(u[c]===void 0)u.push("");u.push(i)})}),t}negatePadding(e){let t=e.width||0;if(e.padding)t-=(e.padding[3]||0)+(e.padding[1]||0);if(e.border)t-=4;return t}columnWidths(e){if(!this.wrap)return e.map((r)=>r.width||Ze.stringWidth(r.text));let t=e.length,n=this.width,s=e.map((r)=>{if(r.width)return t--,n-=r.width,r.width;return}),o=t?Math.floor(n/t):0;return s.map((r,i)=>{if(r===void 0)return Math.max(o,am(e[i]));return r})}}function nl(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function am(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function cm(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function lm(e,t){e=e.trim();let n=Ze.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function um(e,t){e=e.trim();let n=Ze.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Ze;function ol(e,t){return Ze=t,new sl({width:(e===null||e===void 0?void 0:e.width)||cm(),wrap:e===null||e===void 0?void 0:e.wrap})}function Yr({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 dm=Yr();function fn(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(dm,"")}var rl=161,il=1114109,al=[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],cl=12288,ll=65510,ul=[12288,12288,65281,65376,65504,65510];var dl=4352,fl=262141,Gr=[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 ro=(e,t)=>{let n=0,s=Math.floor(e.length/2)-1;while(n<=s){let o=Math.floor((n+s)/2),r=o*2;if(t<e[r])s=o-1;else if(t>e[r+1])n=o+1;else return!0}return!1};var pl=19968,[fm,pm]=hm(Gr);function hm(e){let t=e[0],n=e[1];for(let s=0;s<e.length;s+=2){let o=e[s],r=e[s+1];if(pl>=o&&pl<=r)return[o,r];if(r-o>n-t)t=o,n=r}return[t,n]}var hl=(e)=>{if(e<rl||e>il)return!1;return ro(al,e)},gl=(e)=>{if(e<cl||e>ll)return!1;return ro(ul,e)};var ml=(e)=>{if(e>=fm&&e<=pm)return!0;if(e<dl||e>fl)return!1;return ro(Gr,e)};function gm(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function yl(e,{ambiguousAsWide:t=!1}={}){if(gm(e),gl(e)||ml(e)||t&&hl(e))return 2;return 1}var Dl=el(wl(),1),mm=new Intl.Segmenter,ym=/^\p{Default_Ignorable_Code_Point}$/u;function ht(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:s=!1}=t;if(!s)e=fn(e);if(e.length===0)return 0;let o=0,r={ambiguousAsWide:!n};for(let{segment:i}of mm.segment(e)){let l=i.codePointAt(0);if(l<=31||l>=127&&l<=159)continue;if(l>=8203&&l<=8207||l===65279)continue;if(l>=768&&l<=879||l>=6832&&l<=6911||l>=7616&&l<=7679||l>=8400&&l<=8447||l>=65056&&l<=65071)continue;if(l>=55296&&l<=57343)continue;if(l>=65024&&l<=65039)continue;if(ym.test(i))continue;if(Dl.default().test(i)){o+=2;continue}o+=yl(l,r)}return o}var kl=(e=0)=>(t)=>`\x1B[${t+e}m`,xl=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,Sl=(e=0)=>(t,n,s)=>`\x1B[${38+e};2;${t};${n};${s}m`,xe={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]}},Nx=Object.keys(xe.modifier),bm=Object.keys(xe.color),wm=Object.keys(xe.bgColor),Mx=[...bm,...wm];function Dm(){let e=new Map;for(let[t,n]of Object.entries(xe)){for(let[s,o]of Object.entries(n))xe[s]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[s]=xe[s],e.set(o[0],o[1]);Object.defineProperty(xe,t,{value:n,enumerable:!1})}return Object.defineProperty(xe,"codes",{value:e,enumerable:!1}),xe.color.close="\x1B[39m",xe.bgColor.close="\x1B[49m",xe.color.ansi=kl(),xe.color.ansi256=xl(),xe.color.ansi16m=Sl(),xe.bgColor.ansi=kl(10),xe.bgColor.ansi256=xl(10),xe.bgColor.ansi16m=Sl(10),Object.defineProperties(xe,{rgbToAnsi256:{value(t,n,s){if(t===n&&n===s){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(s/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[s]=n;if(s.length===3)s=[...s].map((r)=>r+r).join("");let o=Number.parseInt(s,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:(t)=>xe.rgbToAnsi256(...xe.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,s,o;if(t>=232)n=((t-232)*10+8)/255,s=n,o=n;else{t-=16;let l=t%36;n=Math.floor(t/36)/5,s=Math.floor(l/6)/5,o=l%6/5}let r=Math.max(n,s,o)*2;if(r===0)return 30;let i=30+(Math.round(o)<<2|Math.round(s)<<1|Math.round(n));if(r===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,s)=>xe.ansi256ToAnsi(xe.rgbToAnsi256(t,n,s)),enumerable:!1},hexToAnsi:{value:(t)=>xe.ansi256ToAnsi(xe.hexToAnsi256(t)),enumerable:!1}}),xe}var km=Dm(),_l=km;var ao=new Set(["\x1B","›"]),xm=39,Vr="\x07",Cl="[",Sm="]",Al="m",io=`${Sm}8;;`,El=(e)=>`${ao.values().next().value}${Cl}${e}${Al}`,$l=(e)=>`${ao.values().next().value}${io}${e}${Vr}`,_m=(e)=>e.split(" ").map((t)=>ht(t)),Xr=(e,t,n)=>{let s=[...t],o=!1,r=!1,i=ht(fn(e.at(-1)));for(let[l,u]of s.entries()){let c=ht(u);if(i+c<=n)e[e.length-1]+=u;else e.push(u),i=0;if(ao.has(u))o=!0,r=s.slice(l+1,l+1+io.length).join("")===io;if(o){if(r){if(u===Vr)o=!1,r=!1}else if(u===Al)o=!1;continue}if(i+=c,i===n&&l<s.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},Em=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(ht(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},$m=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let s="",o,r,i=_m(e),l=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)l[l.length-1]=l.at(-1).trimStart();let p=ht(l.at(-1));if(d!==0){if(p>=t&&(n.wordWrap===!1||n.trim===!1))l.push(""),p=0;if(p>0||n.trim===!1)l[l.length-1]+=" ",p++}if(n.hard&&i[d]>t){let g=t-p,h=1+Math.floor((i[d]-g-1)/t);if(Math.floor((i[d]-1)/t)<h)l.push("");Xr(l,f,t);continue}if(p+i[d]>t&&p>0&&i[d]>0){if(n.wordWrap===!1&&p<t){Xr(l,f,t);continue}l.push("")}if(p+i[d]>t&&n.wordWrap===!1){Xr(l,f,t);continue}l[l.length-1]+=f}if(n.trim!==!1)l=l.map((d)=>Em(d));let u=l.join(`
8
- `),c=[...u],a=0;for(let[d,f]of c.entries()){if(s+=f,ao.has(f)){let{groups:g}=new RegExp(`(?:\\${Cl}(?<code>\\d+)m|\\${io}(?<uri>.*)${Vr})`).exec(u.slice(a))||{groups:{}};if(g.code!==void 0){let h=Number.parseFloat(g.code);o=h===xm?void 0:h}else if(g.uri!==void 0)r=g.uri.length===0?void 0:g.uri}let p=_l.codes.get(Number(o));if(c[d+1]===`
9
- `){if(r)s+=$l("");if(o&&p)s+=El(p)}else if(f===`
10
- `){if(o&&p)s+=El(o);if(r)s+=$l(r)}a+=f.length}return s};function Zr(e,t,n){return String(e).normalize().replaceAll(`\r
7
+ `);if(o.border)s.unshift("."+"-".repeat(this.negatePadding(o)+2)+"."),s.push("'"+"-".repeat(this.negatePadding(o)+2)+"'");if(o.padding)s.unshift(...Array(o.padding[0]||0).fill("")),s.push(...Array(o.padding[2]||0).fill(""));s.forEach((i,l)=>{if(!t[l])t.push([]);let u=t[l];for(let c=0;c<r;c++)if(u[c]===void 0)u.push("");u.push(i)})}),t}negatePadding(e){let t=e.width||0;if(e.padding)t-=(e.padding[3]||0)+(e.padding[1]||0);if(e.border)t-=4;return t}columnWidths(e){if(!this.wrap)return e.map((r)=>r.width||Ze.stringWidth(r.text));let t=e.length,n=this.width,s=e.map((r)=>{if(r.width)return t--,n-=r.width,r.width;return}),o=t?Math.floor(n/t):0;return s.map((r,i)=>{if(r===void 0)return Math.max(o,um(e[i]));return r})}}function al(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function um(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function dm(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function fm(e,t){e=e.trim();let n=Ze.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function pm(e,t){e=e.trim();let n=Ze.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Ze;function ll(e,t){return Ze=t,new cl({width:(e===null||e===void 0?void 0:e.width)||dm(),wrap:e===null||e===void 0?void 0:e.wrap})}function Gr({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 hm=Gr();function fn(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes("›"))return e;return e.replace(hm,"")}var ul=161,dl=1114109,fl=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],pl=12288,hl=65510,gl=[12288,12288,65281,65376,65504,65510];var ml=4352,yl=262141,Xr=[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 ro=(e,t)=>{let n=0,s=Math.floor(e.length/2)-1;while(n<=s){let o=Math.floor((n+s)/2),r=o*2;if(t<e[r])s=o-1;else if(t>e[r+1])n=o+1;else return!0}return!1};var bl=19968,[gm,mm]=ym(Xr);function ym(e){let t=e[0],n=e[1];for(let s=0;s<e.length;s+=2){let o=e[s],r=e[s+1];if(bl>=o&&bl<=r)return[o,r];if(r-o>n-t)t=o,n=r}return[t,n]}var wl=(e)=>{if(e<ul||e>dl)return!1;return ro(fl,e)},Dl=(e)=>{if(e<pl||e>hl)return!1;return ro(gl,e)};var kl=(e)=>{if(e>=gm&&e<=mm)return!0;if(e<ml||e>yl)return!1;return ro(Xr,e)};function bm(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function xl(e,{ambiguousAsWide:t=!1}={}){if(bm(e),Dl(e)||kl(e)||t&&wl(e))return 2;return 1}var El=rl(_l(),1),wm=new Intl.Segmenter,Dm=/^\p{Default_Ignorable_Code_Point}$/u;function ht(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:s=!1}=t;if(!s)e=fn(e);if(e.length===0)return 0;let o=0,r={ambiguousAsWide:!n};for(let{segment:i}of wm.segment(e)){let l=i.codePointAt(0);if(l<=31||l>=127&&l<=159)continue;if(l>=8203&&l<=8207||l===65279)continue;if(l>=768&&l<=879||l>=6832&&l<=6911||l>=7616&&l<=7679||l>=8400&&l<=8447||l>=65056&&l<=65071)continue;if(l>=55296&&l<=57343)continue;if(l>=65024&&l<=65039)continue;if(Dm.test(i))continue;if(El.default().test(i)){o+=2;continue}o+=xl(l,r)}return o}var $l=(e=0)=>(t)=>`\x1B[${t+e}m`,Cl=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,Al=(e=0)=>(t,n,s)=>`\x1B[${38+e};2;${t};${n};${s}m`,Se={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]}},Bx=Object.keys(Se.modifier),km=Object.keys(Se.color),xm=Object.keys(Se.bgColor),jx=[...km,...xm];function Sm(){let e=new Map;for(let[t,n]of Object.entries(Se)){for(let[s,o]of Object.entries(n))Se[s]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[s]=Se[s],e.set(o[0],o[1]);Object.defineProperty(Se,t,{value:n,enumerable:!1})}return Object.defineProperty(Se,"codes",{value:e,enumerable:!1}),Se.color.close="\x1B[39m",Se.bgColor.close="\x1B[49m",Se.color.ansi=$l(),Se.color.ansi256=Cl(),Se.color.ansi16m=Al(),Se.bgColor.ansi=$l(10),Se.bgColor.ansi256=Cl(10),Se.bgColor.ansi16m=Al(10),Object.defineProperties(Se,{rgbToAnsi256:{value(t,n,s){if(t===n&&n===s){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(s/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[s]=n;if(s.length===3)s=[...s].map((r)=>r+r).join("");let o=Number.parseInt(s,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:(t)=>Se.rgbToAnsi256(...Se.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,s,o;if(t>=232)n=((t-232)*10+8)/255,s=n,o=n;else{t-=16;let l=t%36;n=Math.floor(t/36)/5,s=Math.floor(l/6)/5,o=l%6/5}let r=Math.max(n,s,o)*2;if(r===0)return 30;let i=30+(Math.round(o)<<2|Math.round(s)<<1|Math.round(n));if(r===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,s)=>Se.ansi256ToAnsi(Se.rgbToAnsi256(t,n,s)),enumerable:!1},hexToAnsi:{value:(t)=>Se.ansi256ToAnsi(Se.hexToAnsi256(t)),enumerable:!1}}),Se}var _m=Sm(),Fl=_m;var ao=new Set(["\x1B","›"]),Em=39,Zr="\x07",Rl="[",$m="]",Il="m",io=`${$m}8;;`,Tl=(e)=>`${ao.values().next().value}${Rl}${e}${Il}`,Ol=(e)=>`${ao.values().next().value}${io}${e}${Zr}`,Cm=(e)=>e.split(" ").map((t)=>ht(t)),Vr=(e,t,n)=>{let s=[...t],o=!1,r=!1,i=ht(fn(e.at(-1)));for(let[l,u]of s.entries()){let c=ht(u);if(i+c<=n)e[e.length-1]+=u;else e.push(u),i=0;if(ao.has(u))o=!0,r=s.slice(l+1,l+1+io.length).join("")===io;if(o){if(r){if(u===Zr)o=!1,r=!1}else if(u===Il)o=!1;continue}if(i+=c,i===n&&l<s.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},Am=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(ht(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},Fm=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let s="",o,r,i=Cm(e),l=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)l[l.length-1]=l.at(-1).trimStart();let p=ht(l.at(-1));if(d!==0){if(p>=t&&(n.wordWrap===!1||n.trim===!1))l.push(""),p=0;if(p>0||n.trim===!1)l[l.length-1]+=" ",p++}if(n.hard&&i[d]>t){let g=t-p,h=1+Math.floor((i[d]-g-1)/t);if(Math.floor((i[d]-1)/t)<h)l.push("");Vr(l,f,t);continue}if(p+i[d]>t&&p>0&&i[d]>0){if(n.wordWrap===!1&&p<t){Vr(l,f,t);continue}l.push("")}if(p+i[d]>t&&n.wordWrap===!1){Vr(l,f,t);continue}l[l.length-1]+=f}if(n.trim!==!1)l=l.map((d)=>Am(d));let u=l.join(`
8
+ `),c=[...u],a=0;for(let[d,f]of c.entries()){if(s+=f,ao.has(f)){let{groups:g}=new RegExp(`(?:\\${Rl}(?<code>\\d+)m|\\${io}(?<uri>.*)${Zr})`).exec(u.slice(a))||{groups:{}};if(g.code!==void 0){let h=Number.parseFloat(g.code);o=h===Em?void 0:h}else if(g.uri!==void 0)r=g.uri.length===0?void 0:g.uri}let p=Fl.codes.get(Number(o));if(c[d+1]===`
9
+ `){if(r)s+=Ol("");if(o&&p)s+=Tl(p)}else if(f===`
10
+ `){if(o&&p)s+=Tl(o);if(r)s+=Ol(r)}a+=f.length}return s};function Qr(e,t,n){return String(e).normalize().replaceAll(`\r
11
11
  `,`
12
12
  `).split(`
13
- `).map((s)=>$m(s,t,n)).join(`
14
- `)}function Qr(e){return ol(e,{stringWidth:ht,stripAnsi:fn,wrap:Zr})}import{dirname as Fl,resolve as Tl}from"path";import{readdirSync as Cm,statSync as Am}from"fs";function ei(e,t){let n=Tl(".",e),s;if(!Am(n).isDirectory())n=Fl(n);while(!0){if(s=t(n,Cm(n)),s)return Tl(n,s);if(n=Fl(s=n),s===n)break}}import{inspect as Hm}from"util";import{fileURLToPath as zl}from"url";import{format as Om}from"util";import{normalize as Rm,resolve as Im}from"path";function pn(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",s=!1,o=e.match(/^-+/);for(let r=o?o[0].length:0;r<e.length;r++){let i=e.charAt(r);if(s)s=!1,i=i.toUpperCase();if(r!==0&&(i==="-"||i==="_"))s=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function co(e,t){let n=e.toLowerCase();t=t||"-";let s="";for(let o=0;o<e.length;o++){let r=n.charAt(o),i=e.charAt(o);if(r!==i&&o>0)s+=`${t}${n.charAt(o)}`;else s+=i}return s}function lo(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 Ol(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,s=null,o=null,r=[];for(let i=0;i<e.length;i++){if(n=s,s=e.charAt(i),s===" "&&!o){if(n!==" ")t++;continue}if(s===o)o=null;else if((s==="'"||s==='"')&&!o)o=s;if(!r[t])r[t]="";r[t]+=s}return r}var rt;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(rt||(rt={}));var Ot;class ni{constructor(e){Ot=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),s=Ol(e),o=typeof e==="string",r=Fm(Object.assign(Object.create(null),n.alias)),i=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),l=Object.assign(Object.create(null),n.default),u=n.configObjects||[],c=n.envPrefix,a=i["populate--"],d=a?"--":"_",f=Object.create(null),p=Object.create(null),g=n.__||Ot.format,h={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]+)$/,y=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(_){let F=typeof _==="object"?_.key:_,J=Object.keys(_).map(function(I){return{boolean:"bools",string:"strings",number:"numbers"}[I]}).filter(Boolean).pop();if(J)h[J][F]=!0;h.arrays[F]=!0,h.keys.push(F)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(_){h.bools[_]=!0,h.keys.push(_)}),[].concat(n.string||[]).filter(Boolean).forEach(function(_){h.strings[_]=!0,h.keys.push(_)}),[].concat(n.number||[]).filter(Boolean).forEach(function(_){h.numbers[_]=!0,h.keys.push(_)}),[].concat(n.count||[]).filter(Boolean).forEach(function(_){h.counts[_]=!0,h.keys.push(_)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(_){h.normalize[_]=!0,h.keys.push(_)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([_,F])=>{if(typeof F==="number")h.nargs[_]=F,h.keys.push(_)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([_,F])=>{if(typeof F==="function")h.coercions[_]=F,h.keys.push(_)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(_){h.configs[_]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([_,F])=>{if(typeof F==="boolean"||typeof F==="function")h.configs[_]=F})}oe(n.key,r,n.default,h.arrays),Object.keys(l).forEach(function(_){(h.aliases[_]||[]).forEach(function(F){l[F]=l[_]})});let w=null;zr();let x=[],D=Object.assign(Object.create(null),{_:[]}),E={};for(let _=0;_<s.length;_++){let F=s[_],J=F.replace(/^-{3,}/,"---"),I,A,ee,X,se,Ie;if(F!=="--"&&/^-/.test(F)&&ie(F))C(F);else if(J.match(/^---+(=|$)/)){C(F);continue}else if(F.match(/^--.+=/)||!i["short-option-groups"]&&F.match(/^-.+=/)){if(X=F.match(/^--?([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)if(U(X[1],h.arrays))_=k(_,X[1],s,X[2]);else if(U(X[1],h.nargs)!==!1)_=S(_,X[1],s,X[2]);else O(X[1],X[2],!0)}else if(F.match(y)&&i["boolean-negation"]){if(X=F.match(y),X!==null&&Array.isArray(X)&&X.length>=2)A=X[1],O(A,U(A,h.arrays)?[!1]:!1)}else if(F.match(/^--.+/)||!i["short-option-groups"]&&F.match(/^-[^-]+/)){if(X=F.match(/^--?(.+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(A=X[1],U(A,h.arrays))_=k(_,A,s);else if(U(A,h.nargs)!==!1)_=S(_,A,s);else if(se=s[_+1],se!==void 0&&(!se.match(/^-/)||se.match(m))&&!U(A,h.bools)&&!U(A,h.counts))O(A,se),_++;else if(/^(true|false)$/.test(se))O(A,se),_++;else O(A,W(A))}else if(F.match(/^-.\..+=/)){if(X=F.match(/^-([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)O(X[1],X[2])}else if(F.match(/^-.\..+/)&&!F.match(m)){if(se=s[_+1],X=F.match(/^-(.\..+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(A=X[1],se!==void 0&&!se.match(/^-/)&&!U(A,h.bools)&&!U(A,h.counts))O(A,se),_++;else O(A,W(A))}else if(F.match(/^-[^-]+/)&&!F.match(m)){ee=F.slice(1,-1).split(""),I=!1;for(let Je=0;Je<ee.length;Je++){if(se=F.slice(Je+2),ee[Je+1]&&ee[Je+1]==="="){if(Ie=F.slice(Je+3),A=ee[Je],U(A,h.arrays))_=k(_,A,s,Ie);else if(U(A,h.nargs)!==!1)_=S(_,A,s,Ie);else O(A,Ie);I=!0;break}if(se==="-"){O(ee[Je],se);continue}if(/[A-Za-z]/.test(ee[Je])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(se)&&U(se,h.bools)===!1){O(ee[Je],se),I=!0;break}if(ee[Je+1]&&ee[Je+1].match(/\W/)){O(ee[Je],se),I=!0;break}else O(ee[Je],W(ee[Je]))}if(A=F.slice(-1)[0],!I&&A!=="-")if(U(A,h.arrays))_=k(_,A,s);else if(U(A,h.nargs)!==!1)_=S(_,A,s);else if(se=s[_+1],se!==void 0&&(!/^(-|--)[^-]/.test(se)||se.match(m))&&!U(A,h.bools)&&!U(A,h.counts))O(A,se),_++;else if(/^(true|false)$/.test(se))O(A,se),_++;else O(A,W(A))}else if(F.match(/^-[0-9]$/)&&F.match(m)&&U(F.slice(1),h.bools))A=F.slice(1),O(A,W(A));else if(F==="--"){x=s.slice(_+1);break}else if(i["halt-at-non-option"]){x=s.slice(_);break}else C(F)}if(q(D,!0),q(D,!1),j(D),B(),te(D,h.aliases,l,!0),z(D),i["set-placeholder-key"])R(D);if(Object.keys(h.counts).forEach(function(_){if(!Q(D,_.split(".")))O(_,0)}),a&&x.length)D[d]=[];if(x.forEach(function(_){D[d].push(_)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(D).filter((_)=>_!=="--"&&_.includes("-")).forEach((_)=>{delete D[_]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((_)=>r[_])).forEach((_)=>{if(i["camel-case-expansion"]&&_.includes("-"))delete D[_.split(".").map((F)=>pn(F)).join(".")];delete D[_]});function C(_){let F=v("_",_);if(typeof F==="string"||typeof F==="number")D._.push(F)}function S(_,F,J,I){let A,ee=U(F,h.nargs);if(ee=typeof ee!=="number"||isNaN(ee)?1:ee,ee===0){if(!Ae(I))w=Error(g("Argument unexpected for: %s",F));return O(F,W(F)),_}let X=Ae(I)?0:1;if(i["nargs-eats-options"]){if(J.length-(_+1)+X<ee)w=Error(g("Not enough arguments following: %s",F));X=ee}else{for(A=_+1;A<J.length;A++)if(!J[A].match(/^-[^0-9]/)||J[A].match(m)||ie(J[A]))X++;else break;if(X<ee)w=Error(g("Not enough arguments following: %s",F))}let se=Math.min(X,ee);if(!Ae(I)&&se>0)O(F,I),se--;for(A=_+1;A<se+_+1;A++)O(F,J[A]);return _+se}function k(_,F,J,I){let A=[],ee=I||J[_+1],X=U(F,h.nargs);if(U(F,h.bools)&&!/^(true|false)$/.test(ee))A.push(!0);else if(Ae(ee)||Ae(I)&&/^-/.test(ee)&&!m.test(ee)&&!ie(ee)){if(l[F]!==void 0){let se=l[F];A=Array.isArray(se)?se:[se]}}else{if(!Ae(I))A.push(L(F,I,!0));for(let se=_+1;se<J.length;se++){if(!i["greedy-arrays"]&&A.length>0||X&&typeof X==="number"&&A.length>=X)break;if(ee=J[se],/^-/.test(ee)&&!m.test(ee)&&!ie(ee))break;_=se,A.push(L(F,ee,o))}}if(typeof X==="number"&&(X&&A.length<X||isNaN(X)&&A.length===0))w=Error(g("Not enough arguments following: %s",F));return O(F,A),_}function O(_,F,J=o){if(/-/.test(_)&&i["camel-case-expansion"]){let ee=_.split(".").map(function(X){return pn(X)}).join(".");P(_,ee)}let I=L(_,F,J),A=_.split(".");if(M(D,A,I),h.aliases[_])h.aliases[_].forEach(function(ee){let X=ee.split(".");M(D,X,I)});if(A.length>1&&i["dot-notation"])(h.aliases[A[0]]||[]).forEach(function(ee){let X=ee.split("."),se=[].concat(A);if(se.shift(),X=X.concat(se),!(h.aliases[_]||[]).includes(X.join(".")))M(D,X,I)});if(U(_,h.normalize)&&!U(_,h.arrays))[_].concat(h.aliases[_]||[]).forEach(function(X){Object.defineProperty(E,X,{enumerable:!0,get(){return F},set(se){F=typeof se==="string"?Ot.normalize(se):se}})})}function P(_,F){if(!(h.aliases[_]&&h.aliases[_].length))h.aliases[_]=[F],f[F]=!0;if(!(h.aliases[F]&&h.aliases[F].length))P(F,_)}function L(_,F,J){if(J)F=Tm(F);if(U(_,h.bools)||U(_,h.counts)){if(typeof F==="string")F=F==="true"}let I=Array.isArray(F)?F.map(function(A){return v(_,A)}):v(_,F);if(U(_,h.counts)&&(Ae(I)||typeof I==="boolean"))I=ti();if(U(_,h.normalize)&&U(_,h.arrays))if(Array.isArray(F))I=F.map((A)=>Ot.normalize(A));else I=Ot.normalize(F);return I}function v(_,F){if(!i["parse-positional-numbers"]&&_==="_")return F;if(!U(_,h.strings)&&!U(_,h.bools)&&!Array.isArray(F)){if(lo(F)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${F}`)))||!Ae(F)&&U(_,h.numbers))F=Number(F)}return F}function j(_){let F=Object.create(null);te(F,h.aliases,l),Object.keys(h.configs).forEach(function(J){let I=_[J]||F[J];if(I)try{let A=null,ee=Ot.resolve(Ot.cwd(),I),X=h.configs[J];if(typeof X==="function"){try{A=X(ee)}catch(se){A=se}if(A instanceof Error){w=A;return}}else A=Ot.require(ee);H(A)}catch(A){if(A.name==="PermissionDenied")w=A;else if(_[J])w=Error(g("Invalid JSON config file: %s",I))}})}function H(_,F){Object.keys(_).forEach(function(J){let I=_[J],A=F?F+"."+J:J;if(typeof I==="object"&&I!==null&&!Array.isArray(I)&&i["dot-notation"])H(I,A);else if(!Q(D,A.split("."))||U(A,h.arrays)&&i["combine-arrays"])O(A,I)})}function B(){if(typeof u<"u")u.forEach(function(_){H(_)})}function q(_,F){if(typeof c>"u")return;let J=typeof c==="string"?c:"",I=Ot.env();Object.keys(I).forEach(function(A){if(J===""||A.lastIndexOf(J,0)===0){let ee=A.split("__").map(function(X,se){if(se===0)X=X.substring(J.length);return pn(X)});if((F&&h.configs[ee.join(".")]||!F)&&!Q(_,ee))O(ee.join("."),I[A])}})}function z(_){let F,J=new Set;Object.keys(_).forEach(function(I){if(!J.has(I)){if(F=U(I,h.coercions),typeof F==="function")try{let A=v(I,F(_[I]));[].concat(h.aliases[I]||[],I).forEach((ee)=>{J.add(ee),_[ee]=A})}catch(A){w=A}}})}function R(_){return h.keys.forEach((F)=>{if(~F.indexOf("."))return;if(typeof _[F]>"u")_[F]=void 0}),_}function te(_,F,J,I=!1){Object.keys(J).forEach(function(A){if(!Q(_,A.split("."))){if(M(_,A.split("."),J[A]),I)p[A]=!0;(F[A]||[]).forEach(function(ee){if(Q(_,ee.split(".")))return;M(_,ee.split("."),J[A])})}})}function Q(_,F){let J=_;if(!i["dot-notation"])F=[F.join(".")];F.slice(0,-1).forEach(function(A){J=J[A]||{}});let I=F[F.length-1];if(typeof J!=="object")return!1;else return I in J}function M(_,F,J){let I=_;if(!i["dot-notation"])F=[F.join(".")];F.slice(0,-1).forEach(function(Ie){if(Ie=Rl(Ie),typeof I==="object"&&I[Ie]===void 0)I[Ie]={};if(typeof I[Ie]!=="object"||Array.isArray(I[Ie])){if(Array.isArray(I[Ie]))I[Ie].push({});else I[Ie]=[I[Ie],{}];I=I[Ie][I[Ie].length-1]}else I=I[Ie]});let A=Rl(F[F.length-1]),ee=U(F.join("."),h.arrays),X=Array.isArray(J),se=i["duplicate-arguments-array"];if(!se&&U(A,h.nargs)){if(se=!0,!Ae(I[A])&&h.nargs[A]===1||Array.isArray(I[A])&&I[A].length===h.nargs[A])I[A]=void 0}if(J===ti())I[A]=ti(I[A]);else if(Array.isArray(I[A]))if(se&&ee&&X)I[A]=i["flatten-duplicate-arrays"]?I[A].concat(J):(Array.isArray(I[A][0])?I[A]:[I[A]]).concat([J]);else if(!se&&Boolean(ee)===Boolean(X))I[A]=J;else I[A]=I[A].concat([J]);else if(I[A]===void 0&&ee)I[A]=X?J:[J];else if(se&&!(I[A]===void 0||U(A,h.counts)||U(A,h.bools)))I[A]=[I[A],J];else I[A]=J}function oe(..._){_.forEach(function(F){Object.keys(F||{}).forEach(function(J){if(h.aliases[J])return;h.aliases[J]=[].concat(r[J]||[]),h.aliases[J].concat(J).forEach(function(I){if(/-/.test(I)&&i["camel-case-expansion"]){let A=pn(I);if(A!==J&&h.aliases[J].indexOf(A)===-1)h.aliases[J].push(A),f[A]=!0}}),h.aliases[J].concat(J).forEach(function(I){if(I.length>1&&/[A-Z]/.test(I)&&i["camel-case-expansion"]){let A=co(I,"-");if(A!==J&&h.aliases[J].indexOf(A)===-1)h.aliases[J].push(A),f[A]=!0}}),h.aliases[J].forEach(function(I){h.aliases[I]=[J].concat(h.aliases[J].filter(function(A){return I!==A}))})})})}function U(_,F){let J=[].concat(h.aliases[_]||[],_),I=Object.keys(F),A=J.find((ee)=>I.includes(ee));return A?F[A]:!1}function de(_){let F=Object.keys(h);return[].concat(F.map((I)=>h[I])).some(function(I){return Array.isArray(I)?I.includes(_):I[_]})}function re(_,...F){return[].concat(...F).some(function(I){let A=_.match(I);return A&&de(A[1])})}function K(_){if(_.match(m)||!_.match(/^-[^-]+/))return!1;let F=!0,J,I=_.slice(1).split("");for(let A=0;A<I.length;A++){if(J=_.slice(A+2),!de(I[A])){F=!1;break}if(I[A+1]&&I[A+1]==="="||J==="-"||/[A-Za-z]/.test(I[A])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(J)||I[A+1]&&I[A+1].match(/\W/))break}return F}function ie(_){return i["unknown-options-as-args"]&&G(_)}function G(_){if(_=_.replace(/^-{3,}/,"--"),_.match(m))return!1;if(K(_))return!1;return!re(_,/^-+([^=]+?)=[\s\S]*$/,y,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function W(_){if(!U(_,h.bools)&&!U(_,h.counts)&&`${_}`in l)return l[_];else return he(we(_))}function he(_){return{[rt.BOOLEAN]:!0,[rt.STRING]:"",[rt.NUMBER]:void 0,[rt.ARRAY]:[]}[_]}function we(_){let F=rt.BOOLEAN;if(U(_,h.strings))F=rt.STRING;else if(U(_,h.numbers))F=rt.NUMBER;else if(U(_,h.bools))F=rt.BOOLEAN;else if(U(_,h.arrays))F=rt.ARRAY;return F}function Ae(_){return _===void 0}function zr(){Object.keys(h.counts).find((_)=>{if(U(_,h.arrays))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",_)),!0;else if(U(_,h.nargs))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",_)),!0;return!1})}return{aliases:Object.assign({},h.aliases),argv:Object.assign(E,D),configuration:i,defaulted:Object.assign({},p),error:w,newAliases:Object.assign({},f)}}}function Fm(e){let t=[],n=Object.create(null),s=!0;Object.keys(e).forEach(function(o){t.push([].concat(e[o],o))});while(s){s=!1;for(let o=0;o<t.length;o++)for(let r=o+1;r<t.length;r++)if(t[o].filter(function(l){return t[r].indexOf(l)!==-1}).length){t[o]=t[o].concat(t[r]),t.splice(r,1),s=!0;break}}return t.forEach(function(o){o=o.filter(function(i,l,u){return u.indexOf(i)===l});let r=o.pop();if(r!==void 0&&typeof r==="string")n[r]=o}),n}function ti(e){return e!==void 0?e+1:1}function Rl(e){if(e==="__proto__")return"___proto___";return e}function Tm(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 vm}from"fs";import{createRequire as Il}from"node:module";var si,oi,ri,vl=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Pl=(oi=(si=process===null||process===void 0?void 0:process.versions)===null||si===void 0?void 0:si.node)!==null&&oi!==void 0?oi:(ri=process===null||process===void 0?void 0:process.version)===null||ri===void 0?void 0:ri.slice(1);if(Pl){if(Number(Pl.match(/^([^.]+)/)[1])<vl)throw Error(`yargs parser supports a minimum Node.js version of ${vl}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var Pm=process?process.env:{},Ll=Il?Il(import.meta.url):void 0,Nl=new ni({cwd:process.cwd,env:()=>Pm,format:Om,normalize:Rm,resolve:Im,require:(e)=>{if(typeof Ll<"u")return Ll(e);else if(e.match(/\.json$/))return JSON.parse(vm(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),hs=function(t,n){return Nl.parse(t.slice(),n).argv};hs.detailed=function(e,t){return Nl.parse(e.slice(),t)};hs.camelCase=pn;hs.decamelize=co;hs.looksLikeNumber=lo;var ii=hs;import{basename as zm,dirname as Ym,extname as Gm,relative as Xm,resolve as Hl,join as Vm}from"path";function Ml(){if(Lm())return 0;return 1}function Lm(){return Nm()&&!process.defaultApp}function Nm(){return!!process.versions.electron}function ai(e){return e.slice(Ml()+1)}function Bl(){return process.argv[Ml()]}import{readFileSync as Mm,statSync as Bm,writeFile as jm}from"fs";import{format as Wm}from"util";import{resolve as Jm}from"path";var jl={fs:{readFileSync:Mm,writeFile:jm},format:Wm,resolve:Jm,exists:(e)=>{try{return Bm(e).isFile()}catch(t){return!1}}};var gt;class Wl{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 gt.format.apply(gt.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),s=e.shift(),o=function(){};if(typeof e[e.length-1]==="function")o=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let r=s===1?t:n;if(this.cache[this.locale][t])r=this.cache[this.locale][t][s===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:o});else o();let i=[r];if(~r.indexOf("%d"))i.push(s);return gt.format.apply(gt.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(s,o){let r=t[o+1];if(n+=s,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:s,cb:o}=t,r=this._resolveLocaleFile(n,s),i=JSON.stringify(this.cache[s],null,2);gt.fs.writeFile(r,i,"utf-8",function(l){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();o(l)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(gt.fs.readFileSync)e=JSON.parse(gt.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=gt.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let s=gt.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(s))n=s}return n}_fileExistsSync(e){return gt.exists(e)}}function Jl(e,t){gt=t;let n=new Wl(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 Um=(e)=>Jl(e,jl),Ul=Um;var Yl=el(ql(),1);import{createRequire as Zm}from"node:module";import{readFileSync as Qm,readdirSync as ey}from"node:fs";var ci=zl(import.meta.url),ty=ci.substring(0,ci.lastIndexOf("node_modules")),ny=Zm(import.meta.url),li={assert:{notStrictEqual:Km,strictEqual:qm},cliui:Qr,findUp:ei,getEnv:(e)=>process.env[e],inspect:Hm,getProcessArgvBin:Bl,mainFilename:ty||process.cwd(),Parser:ii,path:{basename:zm,dirname:Ym,extname:Gm,relative:Xm,resolve:Hl,join:Vm},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:Qm,readdirSync:ey,require:ny,getCallerFile:()=>{let e=Yl.default(3);return e.match(/^file:\/\//)?zl(e):e},stringWidth:ht,y18n:Ul({directory:Hl(ci,"../../../locales"),updateFiles:!1})};function Ue(e,t,n,s){n.assert.notStrictEqual(e,t,s)}function ui(e,t){t.assert.strictEqual(typeof e,"string")}function Jn(e){return Object.keys(e)}function De(e){return!!e&&!!e.then&&typeof e.then==="function"}class $e extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,$e)}}function qt(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),s=/\.*[\][<>]/g,o=n.shift();if(!o)throw Error(`No command found in: ${e}`);let r={cmd:o.replace(s,""),demanded:[],optional:[]};return n.forEach((i,l)=>{let u=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&l===n.length-1)u=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(s,"").split("|"),variadic:u});else r.demanded.push({cmd:i.replace(s,"").split("|"),variadic:u})}),r}var sy=["first","second","third","fourth","fifth","sixth"];function V(e,t,n){function s(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[qt(`cmd ${e}`),t,n]}try{let o=0,[r,i,l]=s(),u=[].slice.call(i);while(u.length&&u[u.length-1]===void 0)u.pop();let c=l||u.length;if(c<r.demanded.length)throw new $e(`Not enough arguments provided. Expected ${r.demanded.length} but received ${u.length}.`);let a=r.demanded.length+r.optional.length;if(c>a)throw new $e(`Too many arguments provided. Expected max ${a} but received ${c}.`);r.demanded.forEach((d)=>{let f=u.shift(),p=Gl(f);if(d.cmd.filter((h)=>h===p||h==="*").length===0)Xl(p,d.cmd,o);o+=1}),r.optional.forEach((d)=>{if(u.length===0)return;let f=u.shift(),p=Gl(f);if(d.cmd.filter((h)=>h===p||h==="*").length===0)Xl(p,d.cmd,o);o+=1})}catch(o){console.warn(o.stack)}}function Gl(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function Xl(e,t,n){throw new $e(`Invalid ${sy[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class di{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,s=!1){if(V("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let o=0;o<e.length;o++){if(typeof e[o]!=="function")throw Error("middleware must be a function");let r=e[o];r.applyBeforeValidation=t,r.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let o=e;o.applyBeforeValidation=t,o.global=n,o.mutates=s,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((s)=>{let o=[...n[t]||[],t];if(!s.option)return!0;else return!o.includes(s.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function Vl(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function hn(e,t,n,s){return n.reduce((o,r)=>{if(r.applyBeforeValidation!==s)return o;if(r.mutates){if(r.applied)return o;r.applied=!0}if(De(o))return o.then((i)=>Promise.all([i,r(i,t)])).then(([i,l])=>Object.assign(i,l));else{let i=r(o,t);return De(i)?i.then((l)=>Object.assign(o,l)):Object.assign(o,i)}},e)}function gn(e,t,n=(s)=>{throw s}){try{let s=oy(e)?e():e;return De(s)?s.then((o)=>t(o)):t(s)}catch(s){return n(s)}}function oy(e){return typeof e==="function"}var Un=/(^\*)|(^\$0)/;class Ql{constructor(e,t,n,s){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=s,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,s){s=s||{},this.requireCache.add(n);let o=this.shim.path.resolve(this.shim.path.dirname(n),e),r=this.shim.readdirSync(o,{recursive:s.recurse?!0:!1});if(!Array.isArray(s.extensions))s.extensions=["js"];let i=typeof s.visit==="function"?s.visit:(l)=>l;for(let l of r){let u=l.toString();if(s.exclude){let a=!1;if(typeof s.exclude==="function")a=s.exclude(u);else a=s.exclude.test(u);if(a)continue}if(s.include){let a=!1;if(typeof s.include==="function")a=s.include(u);else a=s.include.test(u);if(!a)continue}let c=!1;for(let a of s.extensions)if(u.endsWith(a))c=!0;if(c){let a=this.shim.path.join(o,u),d=t(a),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,a,u)){if(this.requireCache.has(a))continue;else this.requireCache.add(a);if(!f.command)f.command=this.shim.path.basename(a,this.shim.path.extname(a));this.addHandler(f)}}}}addHandler(e,t,n,s,o,r){let i=[],l=Vl(o);if(s=s||(()=>{}),Array.isArray(e))if(ry(e))[e,...i]=e;else for(let u of e)this.addHandler(u);else if(ay(e)){let u=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(u===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)u=[].concat(u).concat(e.aliases);this.addHandler(u,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(Zl(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let u=qt(e);i=i.map((d)=>qt(d).cmd);let c=!1,a=[u.cmd].concat(i).filter((d)=>{if(Un.test(d))return c=!0,!1;return!0});if(a.length===0&&c)a.push("$0");if(c)u.cmd=a[0],i=a.slice(1),e=e.replace(Un,u.cmd);if(i.forEach((d)=>{this.aliasMap[d]=u.cmd}),t!==!1)this.usage.command(e,t,c,i,r);if(this.handlers[u.cmd]={original:e,description:t,handler:s,builder:n||{},middlewares:l,deprecated:r,demanded:u.demanded,optional:u.optional},c)this.defaultCommand=this.handlers[u.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,s,o,r){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,l=t.getInternalMethods().getContext(),u=l.commands.slice(),c=!e;if(e)l.commands.push(e),l.fullCommands.push(i.original);let a=this.applyBuilderUpdateUsageAndParse(c,i,t,n.aliases,u,s,o,r);return De(a)?a.then((d)=>this.applyMiddlewareAndGetResult(c,i,d.innerArgv,l,o,d.aliases,t)):this.applyMiddlewareAndGetResult(c,i,a.innerArgv,l,o,a.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,s,o,r,i,l){let u=t.builder,c=n;if(uo(u)){n.getInternalMethods().getUsageInstance().freeze();let a=u(n.getInternalMethods().reset(s),l);if(De(a))return a.then((d)=>(c=tu(d)?d:n,this.parseAndUpdateUsage(e,t,c,o,r,i)))}else if(iy(u))n.getInternalMethods().getUsageInstance().freeze(),c=n.getInternalMethods().reset(s),Object.keys(t.builder).forEach((a)=>{c.option(a,u[a])});return this.parseAndUpdateUsage(e,t,c,o,r,i)}parseAndUpdateUsage(e,t,n,s,o,r){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(s,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,o,r);return De(i)?i.then((l)=>({aliases:n.parsed.aliases,innerArgv:l})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=Un.test(t.original)?t.original.replace(Un,"").trim():t.original,s=e.filter((o)=>!Un.test(o));return s.push(n),`$0 ${s.join(" ")}`}handleValidationAndGetResult(e,t,n,s,o,r,i,l){if(!r.getInternalMethods().getHasOutput()){let u=r.getInternalMethods().runValidation(o,l,r.parsed.error,e);n=gn(n,(c)=>(u(c),c))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let u=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,u,!1,!1),n=hn(n,r,i,!1),n=gn(n,(c)=>{let a=t.handler(c);return De(a)?a.then(()=>c):c}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(De(n)&&!r.getInternalMethods().hasParseCallback())n.catch((c)=>{try{r.getInternalMethods().getUsageInstance().fail(null,c)}catch(a){}})}if(!e)s.commands.pop(),s.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,s,o,r,i){let l={};if(o)return n;if(!i.getInternalMethods().getHasOutput())l=this.populatePositionals(t,n,s,i);let u=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),c=hn(n,i,u,!0);return De(c)?c.then((a)=>this.handleValidationAndGetResult(e,t,a,s,r,i,u,l)):this.handleValidationAndGetResult(e,t,c,s,r,i,u,l)}populatePositionals(e,t,n,s){t._=t._.slice(n.commands.length);let o=e.demanded.slice(0),r=e.optional.slice(0),i={};this.validation.positionalCount(o.length,t._.length);while(o.length){let l=o.shift();this.populatePositional(l,t,i)}while(r.length){let l=r.shift();this.populatePositional(l,t,i)}return t._=n.commands.concat(t._.map((l)=>""+l)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),s),i}populatePositional(e,t,n){let s=e.cmd[0];if(e.variadic)n[s]=t._.splice(0).map(String);else if(t._.length)n[s]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=qt(e);return n.demanded.forEach((s)=>{let[o,...r]=s.cmd;if(s.variadic)t.array.push(o),t.default[o]=[];t.alias[o]=r,t.demand[o]=!0}),n.optional.forEach((s)=>{let[o,...r]=s.cmd;if(s.variadic)t.array.push(o),t.default[o]=[];t.alias[o]=r}),t}postProcessPositionals(e,t,n,s){let o=Object.assign({},s.getOptions());o.default=Object.assign(n.default,o.default);for(let u of Object.keys(n.alias))o.alias[u]=(o.alias[u]||[]).concat(n.alias[u]);o.array=o.array.concat(n.array),o.config={};let r=[];if(Object.keys(t).forEach((u)=>{t[u].map((c)=>{if(o.configuration["unknown-options-as-args"])o.key[u]=!0;r.push(`--${u}`),r.push(c)})}),!r.length)return;let i=Object.assign({},o.configuration,{"populate--":!1}),l=this.shim.Parser.detailed(r,Object.assign({},o,{configuration:i}));if(l.error)s.getInternalMethods().getUsageInstance().fail(l.error.message,l.error);else{let u=Object.keys(t);Object.keys(t).forEach((c)=>{u.push(...l.aliases[c])}),Object.keys(l.argv).forEach((c)=>{if(u.includes(c)){if(!t[c])t[c]=l.argv[c];if(!this.isInConfigs(s,c)&&!this.isDefaulted(s,c)&&Object.prototype.hasOwnProperty.call(e,c)&&Object.prototype.hasOwnProperty.call(l.argv,c)&&(Array.isArray(e[c])||Array.isArray(l.argv[c])))e[c]=[].concat(e[c],l.argv[c]);else e[c]=l.argv[c]}})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some((s)=>Object.prototype.hasOwnProperty.call(s,t))||n.some((s)=>Object.prototype.hasOwnProperty.call(s,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=Un.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(uo(t))return t(e,!0);else if(!Zl(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let s of[e,t,n]){if(typeof s==="string"||s===!1)return s;Ue(s,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();Ue(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 eu(e,t,n,s){return new Ql(e,t,n,s)}function Zl(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function ry(e){return e.every((t)=>typeof t==="string")}function uo(e){return typeof e==="function"}function iy(e){return typeof e==="object"}function ay(e){return typeof e==="object"&&!Array.isArray(e)}function Ht(e={},t=()=>!0){let n={};return Jn(e).forEach((s)=>{if(t(s,e[s]))n[s]=e[s]}),n}function zt(e){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((t)=>{let n=t;if(n._handle&&n.isTTY&&typeof n._handle.setBlocking==="function")n._handle.setBlocking(e)})}function cy(e){return typeof e==="boolean"}function su(e,t){let n=t.y18n.__,s={},o=[];s.failFn=function(v){o.push(v)};let r=null,i=null,l=!0;s.showHelpOnFail=function(v=!0,j){let[H,B]=typeof v==="string"?[!0,v]:[v,j];if(e.getInternalMethods().isGlobalContext())i=B;return r=B,l=H,s};let u=!1;s.fail=function(v,j){let H=e.getInternalMethods().getLoggerInstance();if(o.length)for(let B=o.length-1;B>=0;--B){let q=o[B];if(cy(q)){if(j)throw j;else if(v)throw Error(v)}else q(v,j,s)}else{if(e.getExitProcess())zt(!0);if(!u){if(u=!0,l)e.showHelp("error"),H.error();if(v||j)H.error(v||j);let B=r||i;if(B){if(v||j)H.error("");H.error(B)}}if(j=j||new $e(v),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,j);else throw j}};let c=[],a=!1;s.usage=(L,v)=>{if(L===null)return a=!0,c=[],s;return a=!1,c.push([L,v||""]),s},s.getUsage=()=>c,s.getUsageDisabled=()=>a,s.getPositionalGroupName=()=>n("Positionals:");let d=[];s.example=(L,v)=>{d.push([L,v||""])};let f=[];s.command=function(v,j,H,B,q=!1){if(H)f=f.map((z)=>(z[2]=!1,z));f.push([v,j||"",H,B,q])},s.getCommands=()=>f;let p={};s.describe=function(v,j){if(Array.isArray(v))v.forEach((H)=>{s.describe(H,j)});else if(typeof v==="object")Object.keys(v).forEach((H)=>{s.describe(H,v[H])});else p[v]=j},s.getDescriptions=()=>p;let g=[];s.epilog=(L)=>{g.push(L)};let h=!1,m;s.wrap=(L)=>{h=!0,m=L},s.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!h)m=k(),h=!0;return m};let y="__yargsString__:";s.deferY18nLookup=(L)=>y+L,s.help=function(){if(D)return D;x();let v=e.customScriptName?e.$0:t.path.basename(e.$0),j=e.getDemandedOptions(),H=e.getDemandedCommands(),B=e.getDeprecatedOptions(),q=e.getGroups(),z=e.getOptions(),R=[];R=R.concat(Object.keys(p)),R=R.concat(Object.keys(j)),R=R.concat(Object.keys(H)),R=R.concat(Object.keys(z.default)),R=R.filter(C),R=Object.keys(R.reduce((K,ie)=>{if(ie!=="_")K[ie]=!0;return K},{}));let te=s.getWrap(),Q=t.cliui({width:te,wrap:!!te});if(!a){if(c.length)c.forEach((K)=>{if(Q.div({text:`${K[0].replace(/\$0/g,v)}`}),K[1])Q.div({text:`${K[1]}`,padding:[1,0,0,0]})}),Q.div();else if(f.length){let K=null;if(H._)K=`${v} <${n("command")}>
13
+ `).map((s)=>Fm(s,t,n)).join(`
14
+ `)}function ei(e){return ll(e,{stringWidth:ht,stripAnsi:fn,wrap:Qr})}import{dirname as vl,resolve as Pl}from"path";import{readdirSync as Tm,statSync as Om}from"fs";function ti(e,t){let n=Pl(".",e),s;if(!Om(n).isDirectory())n=vl(n);while(!0){if(s=t(n,Tm(n)),s)return Pl(n,s);if(n=vl(s=n),s===n)break}}import{inspect as Gm}from"util";import{fileURLToPath as Zl}from"url";import{format as vm}from"util";import{normalize as Pm,resolve as Lm}from"path";function pn(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",s=!1,o=e.match(/^-+/);for(let r=o?o[0].length:0;r<e.length;r++){let i=e.charAt(r);if(s)s=!1,i=i.toUpperCase();if(r!==0&&(i==="-"||i==="_"))s=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function co(e,t){let n=e.toLowerCase();t=t||"-";let s="";for(let o=0;o<e.length;o++){let r=n.charAt(o),i=e.charAt(o);if(r!==i&&o>0)s+=`${t}${n.charAt(o)}`;else s+=i}return s}function lo(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 Ll(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,s=null,o=null,r=[];for(let i=0;i<e.length;i++){if(n=s,s=e.charAt(i),s===" "&&!o){if(n!==" ")t++;continue}if(s===o)o=null;else if((s==="'"||s==='"')&&!o)o=s;if(!r[t])r[t]="";r[t]+=s}return r}var rt;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(rt||(rt={}));var Rt;class si{constructor(e){Rt=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),s=Ll(e),o=typeof e==="string",r=Rm(Object.assign(Object.create(null),n.alias)),i=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),l=Object.assign(Object.create(null),n.default),u=n.configObjects||[],c=n.envPrefix,a=i["populate--"],d=a?"--":"_",f=Object.create(null),p=Object.create(null),g=n.__||Rt.format,h={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]+)$/,y=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(_){let F=typeof _==="object"?_.key:_,J=Object.keys(_).map(function(I){return{boolean:"bools",string:"strings",number:"numbers"}[I]}).filter(Boolean).pop();if(J)h[J][F]=!0;h.arrays[F]=!0,h.keys.push(F)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(_){h.bools[_]=!0,h.keys.push(_)}),[].concat(n.string||[]).filter(Boolean).forEach(function(_){h.strings[_]=!0,h.keys.push(_)}),[].concat(n.number||[]).filter(Boolean).forEach(function(_){h.numbers[_]=!0,h.keys.push(_)}),[].concat(n.count||[]).filter(Boolean).forEach(function(_){h.counts[_]=!0,h.keys.push(_)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(_){h.normalize[_]=!0,h.keys.push(_)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([_,F])=>{if(typeof F==="number")h.nargs[_]=F,h.keys.push(_)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([_,F])=>{if(typeof F==="function")h.coercions[_]=F,h.keys.push(_)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(_){h.configs[_]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([_,F])=>{if(typeof F==="boolean"||typeof F==="function")h.configs[_]=F})}oe(n.key,r,n.default,h.arrays),Object.keys(l).forEach(function(_){(h.aliases[_]||[]).forEach(function(F){l[F]=l[_]})});let w=null;Yr();let x=[],D=Object.assign(Object.create(null),{_:[]}),E={};for(let _=0;_<s.length;_++){let F=s[_],J=F.replace(/^-{3,}/,"---"),I,A,ee,X,se,Ie;if(F!=="--"&&/^-/.test(F)&&ie(F))C(F);else if(J.match(/^---+(=|$)/)){C(F);continue}else if(F.match(/^--.+=/)||!i["short-option-groups"]&&F.match(/^-.+=/)){if(X=F.match(/^--?([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)if(U(X[1],h.arrays))_=k(_,X[1],s,X[2]);else if(U(X[1],h.nargs)!==!1)_=S(_,X[1],s,X[2]);else O(X[1],X[2],!0)}else if(F.match(y)&&i["boolean-negation"]){if(X=F.match(y),X!==null&&Array.isArray(X)&&X.length>=2)A=X[1],O(A,U(A,h.arrays)?[!1]:!1)}else if(F.match(/^--.+/)||!i["short-option-groups"]&&F.match(/^-[^-]+/)){if(X=F.match(/^--?(.+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(A=X[1],U(A,h.arrays))_=k(_,A,s);else if(U(A,h.nargs)!==!1)_=S(_,A,s);else if(se=s[_+1],se!==void 0&&(!se.match(/^-/)||se.match(m))&&!U(A,h.bools)&&!U(A,h.counts))O(A,se),_++;else if(/^(true|false)$/.test(se))O(A,se),_++;else O(A,W(A))}else if(F.match(/^-.\..+=/)){if(X=F.match(/^-([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)O(X[1],X[2])}else if(F.match(/^-.\..+/)&&!F.match(m)){if(se=s[_+1],X=F.match(/^-(.\..+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(A=X[1],se!==void 0&&!se.match(/^-/)&&!U(A,h.bools)&&!U(A,h.counts))O(A,se),_++;else O(A,W(A))}else if(F.match(/^-[^-]+/)&&!F.match(m)){ee=F.slice(1,-1).split(""),I=!1;for(let Je=0;Je<ee.length;Je++){if(se=F.slice(Je+2),ee[Je+1]&&ee[Je+1]==="="){if(Ie=F.slice(Je+3),A=ee[Je],U(A,h.arrays))_=k(_,A,s,Ie);else if(U(A,h.nargs)!==!1)_=S(_,A,s,Ie);else O(A,Ie);I=!0;break}if(se==="-"){O(ee[Je],se);continue}if(/[A-Za-z]/.test(ee[Je])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(se)&&U(se,h.bools)===!1){O(ee[Je],se),I=!0;break}if(ee[Je+1]&&ee[Je+1].match(/\W/)){O(ee[Je],se),I=!0;break}else O(ee[Je],W(ee[Je]))}if(A=F.slice(-1)[0],!I&&A!=="-")if(U(A,h.arrays))_=k(_,A,s);else if(U(A,h.nargs)!==!1)_=S(_,A,s);else if(se=s[_+1],se!==void 0&&(!/^(-|--)[^-]/.test(se)||se.match(m))&&!U(A,h.bools)&&!U(A,h.counts))O(A,se),_++;else if(/^(true|false)$/.test(se))O(A,se),_++;else O(A,W(A))}else if(F.match(/^-[0-9]$/)&&F.match(m)&&U(F.slice(1),h.bools))A=F.slice(1),O(A,W(A));else if(F==="--"){x=s.slice(_+1);break}else if(i["halt-at-non-option"]){x=s.slice(_);break}else C(F)}if(q(D,!0),q(D,!1),j(D),B(),te(D,h.aliases,l,!0),z(D),i["set-placeholder-key"])R(D);if(Object.keys(h.counts).forEach(function(_){if(!Q(D,_.split(".")))O(_,0)}),a&&x.length)D[d]=[];if(x.forEach(function(_){D[d].push(_)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(D).filter((_)=>_!=="--"&&_.includes("-")).forEach((_)=>{delete D[_]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((_)=>r[_])).forEach((_)=>{if(i["camel-case-expansion"]&&_.includes("-"))delete D[_.split(".").map((F)=>pn(F)).join(".")];delete D[_]});function C(_){let F=v("_",_);if(typeof F==="string"||typeof F==="number")D._.push(F)}function S(_,F,J,I){let A,ee=U(F,h.nargs);if(ee=typeof ee!=="number"||isNaN(ee)?1:ee,ee===0){if(!Ae(I))w=Error(g("Argument unexpected for: %s",F));return O(F,W(F)),_}let X=Ae(I)?0:1;if(i["nargs-eats-options"]){if(J.length-(_+1)+X<ee)w=Error(g("Not enough arguments following: %s",F));X=ee}else{for(A=_+1;A<J.length;A++)if(!J[A].match(/^-[^0-9]/)||J[A].match(m)||ie(J[A]))X++;else break;if(X<ee)w=Error(g("Not enough arguments following: %s",F))}let se=Math.min(X,ee);if(!Ae(I)&&se>0)O(F,I),se--;for(A=_+1;A<se+_+1;A++)O(F,J[A]);return _+se}function k(_,F,J,I){let A=[],ee=I||J[_+1],X=U(F,h.nargs);if(U(F,h.bools)&&!/^(true|false)$/.test(ee))A.push(!0);else if(Ae(ee)||Ae(I)&&/^-/.test(ee)&&!m.test(ee)&&!ie(ee)){if(l[F]!==void 0){let se=l[F];A=Array.isArray(se)?se:[se]}}else{if(!Ae(I))A.push(L(F,I,!0));for(let se=_+1;se<J.length;se++){if(!i["greedy-arrays"]&&A.length>0||X&&typeof X==="number"&&A.length>=X)break;if(ee=J[se],/^-/.test(ee)&&!m.test(ee)&&!ie(ee))break;_=se,A.push(L(F,ee,o))}}if(typeof X==="number"&&(X&&A.length<X||isNaN(X)&&A.length===0))w=Error(g("Not enough arguments following: %s",F));return O(F,A),_}function O(_,F,J=o){if(/-/.test(_)&&i["camel-case-expansion"]){let ee=_.split(".").map(function(X){return pn(X)}).join(".");P(_,ee)}let I=L(_,F,J),A=_.split(".");if(M(D,A,I),h.aliases[_])h.aliases[_].forEach(function(ee){let X=ee.split(".");M(D,X,I)});if(A.length>1&&i["dot-notation"])(h.aliases[A[0]]||[]).forEach(function(ee){let X=ee.split("."),se=[].concat(A);if(se.shift(),X=X.concat(se),!(h.aliases[_]||[]).includes(X.join(".")))M(D,X,I)});if(U(_,h.normalize)&&!U(_,h.arrays))[_].concat(h.aliases[_]||[]).forEach(function(X){Object.defineProperty(E,X,{enumerable:!0,get(){return F},set(se){F=typeof se==="string"?Rt.normalize(se):se}})})}function P(_,F){if(!(h.aliases[_]&&h.aliases[_].length))h.aliases[_]=[F],f[F]=!0;if(!(h.aliases[F]&&h.aliases[F].length))P(F,_)}function L(_,F,J){if(J)F=Im(F);if(U(_,h.bools)||U(_,h.counts)){if(typeof F==="string")F=F==="true"}let I=Array.isArray(F)?F.map(function(A){return v(_,A)}):v(_,F);if(U(_,h.counts)&&(Ae(I)||typeof I==="boolean"))I=ni();if(U(_,h.normalize)&&U(_,h.arrays))if(Array.isArray(F))I=F.map((A)=>Rt.normalize(A));else I=Rt.normalize(F);return I}function v(_,F){if(!i["parse-positional-numbers"]&&_==="_")return F;if(!U(_,h.strings)&&!U(_,h.bools)&&!Array.isArray(F)){if(lo(F)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${F}`)))||!Ae(F)&&U(_,h.numbers))F=Number(F)}return F}function j(_){let F=Object.create(null);te(F,h.aliases,l),Object.keys(h.configs).forEach(function(J){let I=_[J]||F[J];if(I)try{let A=null,ee=Rt.resolve(Rt.cwd(),I),X=h.configs[J];if(typeof X==="function"){try{A=X(ee)}catch(se){A=se}if(A instanceof Error){w=A;return}}else A=Rt.require(ee);H(A)}catch(A){if(A.name==="PermissionDenied")w=A;else if(_[J])w=Error(g("Invalid JSON config file: %s",I))}})}function H(_,F){Object.keys(_).forEach(function(J){let I=_[J],A=F?F+"."+J:J;if(typeof I==="object"&&I!==null&&!Array.isArray(I)&&i["dot-notation"])H(I,A);else if(!Q(D,A.split("."))||U(A,h.arrays)&&i["combine-arrays"])O(A,I)})}function B(){if(typeof u<"u")u.forEach(function(_){H(_)})}function q(_,F){if(typeof c>"u")return;let J=typeof c==="string"?c:"",I=Rt.env();Object.keys(I).forEach(function(A){if(J===""||A.lastIndexOf(J,0)===0){let ee=A.split("__").map(function(X,se){if(se===0)X=X.substring(J.length);return pn(X)});if((F&&h.configs[ee.join(".")]||!F)&&!Q(_,ee))O(ee.join("."),I[A])}})}function z(_){let F,J=new Set;Object.keys(_).forEach(function(I){if(!J.has(I)){if(F=U(I,h.coercions),typeof F==="function")try{let A=v(I,F(_[I]));[].concat(h.aliases[I]||[],I).forEach((ee)=>{J.add(ee),_[ee]=A})}catch(A){w=A}}})}function R(_){return h.keys.forEach((F)=>{if(~F.indexOf("."))return;if(typeof _[F]>"u")_[F]=void 0}),_}function te(_,F,J,I=!1){Object.keys(J).forEach(function(A){if(!Q(_,A.split("."))){if(M(_,A.split("."),J[A]),I)p[A]=!0;(F[A]||[]).forEach(function(ee){if(Q(_,ee.split(".")))return;M(_,ee.split("."),J[A])})}})}function Q(_,F){let J=_;if(!i["dot-notation"])F=[F.join(".")];F.slice(0,-1).forEach(function(A){J=J[A]||{}});let I=F[F.length-1];if(typeof J!=="object")return!1;else return I in J}function M(_,F,J){let I=_;if(!i["dot-notation"])F=[F.join(".")];F.slice(0,-1).forEach(function(Ie){if(Ie=Nl(Ie),typeof I==="object"&&I[Ie]===void 0)I[Ie]={};if(typeof I[Ie]!=="object"||Array.isArray(I[Ie])){if(Array.isArray(I[Ie]))I[Ie].push({});else I[Ie]=[I[Ie],{}];I=I[Ie][I[Ie].length-1]}else I=I[Ie]});let A=Nl(F[F.length-1]),ee=U(F.join("."),h.arrays),X=Array.isArray(J),se=i["duplicate-arguments-array"];if(!se&&U(A,h.nargs)){if(se=!0,!Ae(I[A])&&h.nargs[A]===1||Array.isArray(I[A])&&I[A].length===h.nargs[A])I[A]=void 0}if(J===ni())I[A]=ni(I[A]);else if(Array.isArray(I[A]))if(se&&ee&&X)I[A]=i["flatten-duplicate-arrays"]?I[A].concat(J):(Array.isArray(I[A][0])?I[A]:[I[A]]).concat([J]);else if(!se&&Boolean(ee)===Boolean(X))I[A]=J;else I[A]=I[A].concat([J]);else if(I[A]===void 0&&ee)I[A]=X?J:[J];else if(se&&!(I[A]===void 0||U(A,h.counts)||U(A,h.bools)))I[A]=[I[A],J];else I[A]=J}function oe(..._){_.forEach(function(F){Object.keys(F||{}).forEach(function(J){if(h.aliases[J])return;h.aliases[J]=[].concat(r[J]||[]),h.aliases[J].concat(J).forEach(function(I){if(/-/.test(I)&&i["camel-case-expansion"]){let A=pn(I);if(A!==J&&h.aliases[J].indexOf(A)===-1)h.aliases[J].push(A),f[A]=!0}}),h.aliases[J].concat(J).forEach(function(I){if(I.length>1&&/[A-Z]/.test(I)&&i["camel-case-expansion"]){let A=co(I,"-");if(A!==J&&h.aliases[J].indexOf(A)===-1)h.aliases[J].push(A),f[A]=!0}}),h.aliases[J].forEach(function(I){h.aliases[I]=[J].concat(h.aliases[J].filter(function(A){return I!==A}))})})})}function U(_,F){let J=[].concat(h.aliases[_]||[],_),I=Object.keys(F),A=J.find((ee)=>I.includes(ee));return A?F[A]:!1}function de(_){let F=Object.keys(h);return[].concat(F.map((I)=>h[I])).some(function(I){return Array.isArray(I)?I.includes(_):I[_]})}function re(_,...F){return[].concat(...F).some(function(I){let A=_.match(I);return A&&de(A[1])})}function K(_){if(_.match(m)||!_.match(/^-[^-]+/))return!1;let F=!0,J,I=_.slice(1).split("");for(let A=0;A<I.length;A++){if(J=_.slice(A+2),!de(I[A])){F=!1;break}if(I[A+1]&&I[A+1]==="="||J==="-"||/[A-Za-z]/.test(I[A])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(J)||I[A+1]&&I[A+1].match(/\W/))break}return F}function ie(_){return i["unknown-options-as-args"]&&G(_)}function G(_){if(_=_.replace(/^-{3,}/,"--"),_.match(m))return!1;if(K(_))return!1;return!re(_,/^-+([^=]+?)=[\s\S]*$/,y,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function W(_){if(!U(_,h.bools)&&!U(_,h.counts)&&`${_}`in l)return l[_];else return he(De(_))}function he(_){return{[rt.BOOLEAN]:!0,[rt.STRING]:"",[rt.NUMBER]:void 0,[rt.ARRAY]:[]}[_]}function De(_){let F=rt.BOOLEAN;if(U(_,h.strings))F=rt.STRING;else if(U(_,h.numbers))F=rt.NUMBER;else if(U(_,h.bools))F=rt.BOOLEAN;else if(U(_,h.arrays))F=rt.ARRAY;return F}function Ae(_){return _===void 0}function Yr(){Object.keys(h.counts).find((_)=>{if(U(_,h.arrays))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",_)),!0;else if(U(_,h.nargs))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",_)),!0;return!1})}return{aliases:Object.assign({},h.aliases),argv:Object.assign(E,D),configuration:i,defaulted:Object.assign({},p),error:w,newAliases:Object.assign({},f)}}}function Rm(e){let t=[],n=Object.create(null),s=!0;Object.keys(e).forEach(function(o){t.push([].concat(e[o],o))});while(s){s=!1;for(let o=0;o<t.length;o++)for(let r=o+1;r<t.length;r++)if(t[o].filter(function(l){return t[r].indexOf(l)!==-1}).length){t[o]=t[o].concat(t[r]),t.splice(r,1),s=!0;break}}return t.forEach(function(o){o=o.filter(function(i,l,u){return u.indexOf(i)===l});let r=o.pop();if(r!==void 0&&typeof r==="string")n[r]=o}),n}function ni(e){return e!==void 0?e+1:1}function Nl(e){if(e==="__proto__")return"___proto___";return e}function Im(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 Nm}from"fs";import{createRequire as Ml}from"node:module";var oi,ri,ii,Bl=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,jl=(ri=(oi=process===null||process===void 0?void 0:process.versions)===null||oi===void 0?void 0:oi.node)!==null&&ri!==void 0?ri:(ii=process===null||process===void 0?void 0:process.version)===null||ii===void 0?void 0:ii.slice(1);if(jl){if(Number(jl.match(/^([^.]+)/)[1])<Bl)throw Error(`yargs parser supports a minimum Node.js version of ${Bl}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var Mm=process?process.env:{},Wl=Ml?Ml(import.meta.url):void 0,Jl=new si({cwd:process.cwd,env:()=>Mm,format:vm,normalize:Pm,resolve:Lm,require:(e)=>{if(typeof Wl<"u")return Wl(e);else if(e.match(/\.json$/))return JSON.parse(Nm(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),hs=function(t,n){return Jl.parse(t.slice(),n).argv};hs.detailed=function(e,t){return Jl.parse(e.slice(),t)};hs.camelCase=pn;hs.decamelize=co;hs.looksLikeNumber=lo;var ai=hs;import{basename as Xm,dirname as Vm,extname as Zm,relative as Qm,resolve as Vl,join as ey}from"path";function Ul(){if(Bm())return 0;return 1}function Bm(){return jm()&&!process.defaultApp}function jm(){return!!process.versions.electron}function ci(e){return e.slice(Ul()+1)}function Kl(){return process.argv[Ul()]}import{readFileSync as Wm,statSync as Jm,writeFile as Um}from"fs";import{format as Km}from"util";import{resolve as qm}from"path";var ql={fs:{readFileSync:Wm,writeFile:Um},format:Km,resolve:qm,exists:(e)=>{try{return Jm(e).isFile()}catch(t){return!1}}};var gt;class Hl{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 gt.format.apply(gt.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),s=e.shift(),o=function(){};if(typeof e[e.length-1]==="function")o=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let r=s===1?t:n;if(this.cache[this.locale][t])r=this.cache[this.locale][t][s===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:o});else o();let i=[r];if(~r.indexOf("%d"))i.push(s);return gt.format.apply(gt.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(s,o){let r=t[o+1];if(n+=s,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:s,cb:o}=t,r=this._resolveLocaleFile(n,s),i=JSON.stringify(this.cache[s],null,2);gt.fs.writeFile(r,i,"utf-8",function(l){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();o(l)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(gt.fs.readFileSync)e=JSON.parse(gt.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=gt.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let s=gt.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(s))n=s}return n}_fileExistsSync(e){return gt.exists(e)}}function zl(e,t){gt=t;let n=new Hl(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 Hm=(e)=>zl(e,ql),Yl=Hm;var Ql=rl(Xl(),1);import{createRequire as ty}from"node:module";import{readFileSync as ny,readdirSync as sy}from"node:fs";var li=Zl(import.meta.url),oy=li.substring(0,li.lastIndexOf("node_modules")),ry=ty(import.meta.url),ui={assert:{notStrictEqual:zm,strictEqual:Ym},cliui:ei,findUp:ti,getEnv:(e)=>process.env[e],inspect:Gm,getProcessArgvBin:Kl,mainFilename:oy||process.cwd(),Parser:ai,path:{basename:Xm,dirname:Vm,extname:Zm,relative:Qm,resolve:Vl,join:ey},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:ny,readdirSync:sy,require:ry,getCallerFile:()=>{let e=Ql.default(3);return e.match(/^file:\/\//)?Zl(e):e},stringWidth:ht,y18n:Yl({directory:Vl(li,"../../../locales"),updateFiles:!1})};function Ue(e,t,n,s){n.assert.notStrictEqual(e,t,s)}function di(e,t){t.assert.strictEqual(typeof e,"string")}function Jn(e){return Object.keys(e)}function ke(e){return!!e&&!!e.then&&typeof e.then==="function"}class $e extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,$e)}}function Ht(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),s=/\.*[\][<>]/g,o=n.shift();if(!o)throw Error(`No command found in: ${e}`);let r={cmd:o.replace(s,""),demanded:[],optional:[]};return n.forEach((i,l)=>{let u=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&l===n.length-1)u=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(s,"").split("|"),variadic:u});else r.demanded.push({cmd:i.replace(s,"").split("|"),variadic:u})}),r}var iy=["first","second","third","fourth","fifth","sixth"];function V(e,t,n){function s(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[Ht(`cmd ${e}`),t,n]}try{let o=0,[r,i,l]=s(),u=[].slice.call(i);while(u.length&&u[u.length-1]===void 0)u.pop();let c=l||u.length;if(c<r.demanded.length)throw new $e(`Not enough arguments provided. Expected ${r.demanded.length} but received ${u.length}.`);let a=r.demanded.length+r.optional.length;if(c>a)throw new $e(`Too many arguments provided. Expected max ${a} but received ${c}.`);r.demanded.forEach((d)=>{let f=u.shift(),p=eu(f);if(d.cmd.filter((h)=>h===p||h==="*").length===0)tu(p,d.cmd,o);o+=1}),r.optional.forEach((d)=>{if(u.length===0)return;let f=u.shift(),p=eu(f);if(d.cmd.filter((h)=>h===p||h==="*").length===0)tu(p,d.cmd,o);o+=1})}catch(o){console.warn(o.stack)}}function eu(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function tu(e,t,n){throw new $e(`Invalid ${iy[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class fi{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,s=!1){if(V("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let o=0;o<e.length;o++){if(typeof e[o]!=="function")throw Error("middleware must be a function");let r=e[o];r.applyBeforeValidation=t,r.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let o=e;o.applyBeforeValidation=t,o.global=n,o.mutates=s,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((s)=>{let o=[...n[t]||[],t];if(!s.option)return!0;else return!o.includes(s.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function nu(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function hn(e,t,n,s){return n.reduce((o,r)=>{if(r.applyBeforeValidation!==s)return o;if(r.mutates){if(r.applied)return o;r.applied=!0}if(ke(o))return o.then((i)=>Promise.all([i,r(i,t)])).then(([i,l])=>Object.assign(i,l));else{let i=r(o,t);return ke(i)?i.then((l)=>Object.assign(o,l)):Object.assign(o,i)}},e)}function gn(e,t,n=(s)=>{throw s}){try{let s=ay(e)?e():e;return ke(s)?s.then((o)=>t(o)):t(s)}catch(s){return n(s)}}function ay(e){return typeof e==="function"}var Un=/(^\*)|(^\$0)/;class ou{constructor(e,t,n,s){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=s,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,s){s=s||{},this.requireCache.add(n);let o=this.shim.path.resolve(this.shim.path.dirname(n),e),r=this.shim.readdirSync(o,{recursive:s.recurse?!0:!1});if(!Array.isArray(s.extensions))s.extensions=["js"];let i=typeof s.visit==="function"?s.visit:(l)=>l;for(let l of r){let u=l.toString();if(s.exclude){let a=!1;if(typeof s.exclude==="function")a=s.exclude(u);else a=s.exclude.test(u);if(a)continue}if(s.include){let a=!1;if(typeof s.include==="function")a=s.include(u);else a=s.include.test(u);if(!a)continue}let c=!1;for(let a of s.extensions)if(u.endsWith(a))c=!0;if(c){let a=this.shim.path.join(o,u),d=t(a),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,a,u)){if(this.requireCache.has(a))continue;else this.requireCache.add(a);if(!f.command)f.command=this.shim.path.basename(a,this.shim.path.extname(a));this.addHandler(f)}}}}addHandler(e,t,n,s,o,r){let i=[],l=nu(o);if(s=s||(()=>{}),Array.isArray(e))if(cy(e))[e,...i]=e;else for(let u of e)this.addHandler(u);else if(uy(e)){let u=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(u===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)u=[].concat(u).concat(e.aliases);this.addHandler(u,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(su(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let u=Ht(e);i=i.map((d)=>Ht(d).cmd);let c=!1,a=[u.cmd].concat(i).filter((d)=>{if(Un.test(d))return c=!0,!1;return!0});if(a.length===0&&c)a.push("$0");if(c)u.cmd=a[0],i=a.slice(1),e=e.replace(Un,u.cmd);if(i.forEach((d)=>{this.aliasMap[d]=u.cmd}),t!==!1)this.usage.command(e,t,c,i,r);if(this.handlers[u.cmd]={original:e,description:t,handler:s,builder:n||{},middlewares:l,deprecated:r,demanded:u.demanded,optional:u.optional},c)this.defaultCommand=this.handlers[u.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,s,o,r){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,l=t.getInternalMethods().getContext(),u=l.commands.slice(),c=!e;if(e)l.commands.push(e),l.fullCommands.push(i.original);let a=this.applyBuilderUpdateUsageAndParse(c,i,t,n.aliases,u,s,o,r);return ke(a)?a.then((d)=>this.applyMiddlewareAndGetResult(c,i,d.innerArgv,l,o,d.aliases,t)):this.applyMiddlewareAndGetResult(c,i,a.innerArgv,l,o,a.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,s,o,r,i,l){let u=t.builder,c=n;if(uo(u)){n.getInternalMethods().getUsageInstance().freeze();let a=u(n.getInternalMethods().reset(s),l);if(ke(a))return a.then((d)=>(c=iu(d)?d:n,this.parseAndUpdateUsage(e,t,c,o,r,i)))}else if(ly(u))n.getInternalMethods().getUsageInstance().freeze(),c=n.getInternalMethods().reset(s),Object.keys(t.builder).forEach((a)=>{c.option(a,u[a])});return this.parseAndUpdateUsage(e,t,c,o,r,i)}parseAndUpdateUsage(e,t,n,s,o,r){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(s,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,o,r);return ke(i)?i.then((l)=>({aliases:n.parsed.aliases,innerArgv:l})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=Un.test(t.original)?t.original.replace(Un,"").trim():t.original,s=e.filter((o)=>!Un.test(o));return s.push(n),`$0 ${s.join(" ")}`}handleValidationAndGetResult(e,t,n,s,o,r,i,l){if(!r.getInternalMethods().getHasOutput()){let u=r.getInternalMethods().runValidation(o,l,r.parsed.error,e);n=gn(n,(c)=>(u(c),c))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let u=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,u,!1,!1),n=hn(n,r,i,!1),n=gn(n,(c)=>{let a=t.handler(c);return ke(a)?a.then(()=>c):c}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(ke(n)&&!r.getInternalMethods().hasParseCallback())n.catch((c)=>{try{r.getInternalMethods().getUsageInstance().fail(null,c)}catch(a){}})}if(!e)s.commands.pop(),s.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,s,o,r,i){let l={};if(o)return n;if(!i.getInternalMethods().getHasOutput())l=this.populatePositionals(t,n,s,i);let u=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),c=hn(n,i,u,!0);return ke(c)?c.then((a)=>this.handleValidationAndGetResult(e,t,a,s,r,i,u,l)):this.handleValidationAndGetResult(e,t,c,s,r,i,u,l)}populatePositionals(e,t,n,s){t._=t._.slice(n.commands.length);let o=e.demanded.slice(0),r=e.optional.slice(0),i={};this.validation.positionalCount(o.length,t._.length);while(o.length){let l=o.shift();this.populatePositional(l,t,i)}while(r.length){let l=r.shift();this.populatePositional(l,t,i)}return t._=n.commands.concat(t._.map((l)=>""+l)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),s),i}populatePositional(e,t,n){let s=e.cmd[0];if(e.variadic)n[s]=t._.splice(0).map(String);else if(t._.length)n[s]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=Ht(e);return n.demanded.forEach((s)=>{let[o,...r]=s.cmd;if(s.variadic)t.array.push(o),t.default[o]=[];t.alias[o]=r,t.demand[o]=!0}),n.optional.forEach((s)=>{let[o,...r]=s.cmd;if(s.variadic)t.array.push(o),t.default[o]=[];t.alias[o]=r}),t}postProcessPositionals(e,t,n,s){let o=Object.assign({},s.getOptions());o.default=Object.assign(n.default,o.default);for(let u of Object.keys(n.alias))o.alias[u]=(o.alias[u]||[]).concat(n.alias[u]);o.array=o.array.concat(n.array),o.config={};let r=[];if(Object.keys(t).forEach((u)=>{t[u].map((c)=>{if(o.configuration["unknown-options-as-args"])o.key[u]=!0;r.push(`--${u}`),r.push(c)})}),!r.length)return;let i=Object.assign({},o.configuration,{"populate--":!1}),l=this.shim.Parser.detailed(r,Object.assign({},o,{configuration:i}));if(l.error)s.getInternalMethods().getUsageInstance().fail(l.error.message,l.error);else{let u=Object.keys(t);Object.keys(t).forEach((c)=>{u.push(...l.aliases[c])}),Object.keys(l.argv).forEach((c)=>{if(u.includes(c)){if(!t[c])t[c]=l.argv[c];if(!this.isInConfigs(s,c)&&!this.isDefaulted(s,c)&&Object.prototype.hasOwnProperty.call(e,c)&&Object.prototype.hasOwnProperty.call(l.argv,c)&&(Array.isArray(e[c])||Array.isArray(l.argv[c])))e[c]=[].concat(e[c],l.argv[c]);else e[c]=l.argv[c]}})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some((s)=>Object.prototype.hasOwnProperty.call(s,t))||n.some((s)=>Object.prototype.hasOwnProperty.call(s,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=Un.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(uo(t))return t(e,!0);else if(!su(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let s of[e,t,n]){if(typeof s==="string"||s===!1)return s;Ue(s,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();Ue(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 ru(e,t,n,s){return new ou(e,t,n,s)}function su(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function cy(e){return e.every((t)=>typeof t==="string")}function uo(e){return typeof e==="function"}function ly(e){return typeof e==="object"}function uy(e){return typeof e==="object"&&!Array.isArray(e)}function zt(e={},t=()=>!0){let n={};return Jn(e).forEach((s)=>{if(t(s,e[s]))n[s]=e[s]}),n}function Yt(e){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((t)=>{let n=t;if(n._handle&&n.isTTY&&typeof n._handle.setBlocking==="function")n._handle.setBlocking(e)})}function dy(e){return typeof e==="boolean"}function cu(e,t){let n=t.y18n.__,s={},o=[];s.failFn=function(v){o.push(v)};let r=null,i=null,l=!0;s.showHelpOnFail=function(v=!0,j){let[H,B]=typeof v==="string"?[!0,v]:[v,j];if(e.getInternalMethods().isGlobalContext())i=B;return r=B,l=H,s};let u=!1;s.fail=function(v,j){let H=e.getInternalMethods().getLoggerInstance();if(o.length)for(let B=o.length-1;B>=0;--B){let q=o[B];if(dy(q)){if(j)throw j;else if(v)throw Error(v)}else q(v,j,s)}else{if(e.getExitProcess())Yt(!0);if(!u){if(u=!0,l)e.showHelp("error"),H.error();if(v||j)H.error(v||j);let B=r||i;if(B){if(v||j)H.error("");H.error(B)}}if(j=j||new $e(v),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,j);else throw j}};let c=[],a=!1;s.usage=(L,v)=>{if(L===null)return a=!0,c=[],s;return a=!1,c.push([L,v||""]),s},s.getUsage=()=>c,s.getUsageDisabled=()=>a,s.getPositionalGroupName=()=>n("Positionals:");let d=[];s.example=(L,v)=>{d.push([L,v||""])};let f=[];s.command=function(v,j,H,B,q=!1){if(H)f=f.map((z)=>(z[2]=!1,z));f.push([v,j||"",H,B,q])},s.getCommands=()=>f;let p={};s.describe=function(v,j){if(Array.isArray(v))v.forEach((H)=>{s.describe(H,j)});else if(typeof v==="object")Object.keys(v).forEach((H)=>{s.describe(H,v[H])});else p[v]=j},s.getDescriptions=()=>p;let g=[];s.epilog=(L)=>{g.push(L)};let h=!1,m;s.wrap=(L)=>{h=!0,m=L},s.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!h)m=k(),h=!0;return m};let y="__yargsString__:";s.deferY18nLookup=(L)=>y+L,s.help=function(){if(D)return D;x();let v=e.customScriptName?e.$0:t.path.basename(e.$0),j=e.getDemandedOptions(),H=e.getDemandedCommands(),B=e.getDeprecatedOptions(),q=e.getGroups(),z=e.getOptions(),R=[];R=R.concat(Object.keys(p)),R=R.concat(Object.keys(j)),R=R.concat(Object.keys(H)),R=R.concat(Object.keys(z.default)),R=R.filter(C),R=Object.keys(R.reduce((K,ie)=>{if(ie!=="_")K[ie]=!0;return K},{}));let te=s.getWrap(),Q=t.cliui({width:te,wrap:!!te});if(!a){if(c.length)c.forEach((K)=>{if(Q.div({text:`${K[0].replace(/\$0/g,v)}`}),K[1])Q.div({text:`${K[1]}`,padding:[1,0,0,0]})}),Q.div();else if(f.length){let K=null;if(H._)K=`${v} <${n("command")}>
15
15
  `;else K=`${v} [${n("command")}]
16
- `;Q.div(`${K}`)}}if(f.length>1||f.length===1&&!f[0][2]){Q.div(n("Commands:"));let K=e.getInternalMethods().getContext(),ie=K.commands.length?`${K.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((W,he)=>W[0].localeCompare(he[0]));let G=v?`${v} `:"";f.forEach((W)=>{let he=`${G}${ie}${W[0].replace(/^\$0 ?/,"")}`;Q.span({text:he,padding:[0,2,0,2],width:w(f,te,`${v}${ie}`)+4},{text:W[1]});let we=[];if(W[2])we.push(`[${n("default")}]`);if(W[3]&&W[3].length)we.push(`[${n("aliases:")} ${W[3].join(", ")}]`);if(W[4])if(typeof W[4]==="string")we.push(`[${n("deprecated: %s",W[4])}]`);else we.push(`[${n("deprecated")}]`);if(we.length)Q.div({text:we.join(" "),padding:[0,0,0,2],align:"right"});else Q.div()}),Q.div()}let M=(Object.keys(z.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);R=R.filter((K)=>!e.parsed.newAliases[K]&&M.every((ie)=>(z.alias[ie]||[]).indexOf(K)===-1));let oe=n("Options:");if(!q[oe])q[oe]=[];E(R,z.alias,q,oe);let U=(K)=>/^--/.test(fo(K)),de=Object.keys(q).filter((K)=>q[K].length>0).map((K)=>{let ie=q[K].filter(C).map((G)=>{if(M.includes(G))return G;for(let W=0,he;(he=M[W])!==void 0;W++)if((z.alias[he]||[]).includes(G))return he;return G});return{groupName:K,normalizedKeys:ie}}).filter(({normalizedKeys:K})=>K.length>0).map(({groupName:K,normalizedKeys:ie})=>{let G=ie.reduce((W,he)=>(W[he]=[he].concat(z.alias[he]||[]).map((we)=>{if(K===s.getPositionalGroupName())return we;else return(/^[0-9]$/.test(we)?z.boolean.includes(he)?"-":"--":we.length>1?"--":"-")+we}).sort((we,Ae)=>U(we)===U(Ae)?0:U(we)?1:-1).join(", "),W),{});return{groupName:K,normalizedKeys:ie,switches:G}});if(de.filter(({groupName:K})=>K!==s.getPositionalGroupName()).some(({normalizedKeys:K,switches:ie})=>!K.every((G)=>U(ie[G]))))de.filter(({groupName:K})=>K!==s.getPositionalGroupName()).forEach(({normalizedKeys:K,switches:ie})=>{K.forEach((G)=>{if(U(ie[G]))ie[G]=ly(ie[G],4)})});if(de.forEach(({groupName:K,normalizedKeys:ie,switches:G})=>{Q.div(K),ie.forEach((W)=>{let he=G[W],we=p[W]||"",Ae=null;if(we.includes(y))we=n(we.substring(y.length));if(z.boolean.includes(W))Ae=`[${n("boolean")}]`;if(z.count.includes(W))Ae=`[${n("count")}]`;if(z.string.includes(W))Ae=`[${n("string")}]`;if(z.normalize.includes(W))Ae=`[${n("string")}]`;if(z.array.includes(W))Ae=`[${n("array")}]`;if(z.number.includes(W))Ae=`[${n("number")}]`;let zr=(J)=>typeof J==="string"?`[${n("deprecated: %s",J)}]`:`[${n("deprecated")}]`,_=[W in B?zr(B[W]):null,Ae,W in j?`[${n("required")}]`:null,z.choices&&z.choices[W]?`[${n("choices:")} ${s.stringifiedValues(z.choices[W])}]`:null,S(z.default[W],z.defaultDescription[W])].filter(Boolean).join(" ");Q.span({text:fo(he),padding:[0,2,0,2+nu(he)],width:w(G,te)+4},we);let F=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(_&&!F)Q.div({text:_,padding:[0,0,0,2],align:"right"});else Q.div()}),Q.div()}),d.length)Q.div(n("Examples:")),d.forEach((K)=>{K[0]=K[0].replace(/\$0/g,v)}),d.forEach((K)=>{if(K[1]==="")Q.div({text:K[0],padding:[0,2,0,2]});else Q.div({text:K[0],padding:[0,2,0,2],width:w(d,te)+4},{text:K[1]})}),Q.div();if(g.length>0){let K=g.map((ie)=>ie.replace(/\$0/g,v)).join(`
16
+ `;Q.div(`${K}`)}}if(f.length>1||f.length===1&&!f[0][2]){Q.div(n("Commands:"));let K=e.getInternalMethods().getContext(),ie=K.commands.length?`${K.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((W,he)=>W[0].localeCompare(he[0]));let G=v?`${v} `:"";f.forEach((W)=>{let he=`${G}${ie}${W[0].replace(/^\$0 ?/,"")}`;Q.span({text:he,padding:[0,2,0,2],width:w(f,te,`${v}${ie}`)+4},{text:W[1]});let De=[];if(W[2])De.push(`[${n("default")}]`);if(W[3]&&W[3].length)De.push(`[${n("aliases:")} ${W[3].join(", ")}]`);if(W[4])if(typeof W[4]==="string")De.push(`[${n("deprecated: %s",W[4])}]`);else De.push(`[${n("deprecated")}]`);if(De.length)Q.div({text:De.join(" "),padding:[0,0,0,2],align:"right"});else Q.div()}),Q.div()}let M=(Object.keys(z.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);R=R.filter((K)=>!e.parsed.newAliases[K]&&M.every((ie)=>(z.alias[ie]||[]).indexOf(K)===-1));let oe=n("Options:");if(!q[oe])q[oe]=[];E(R,z.alias,q,oe);let U=(K)=>/^--/.test(fo(K)),de=Object.keys(q).filter((K)=>q[K].length>0).map((K)=>{let ie=q[K].filter(C).map((G)=>{if(M.includes(G))return G;for(let W=0,he;(he=M[W])!==void 0;W++)if((z.alias[he]||[]).includes(G))return he;return G});return{groupName:K,normalizedKeys:ie}}).filter(({normalizedKeys:K})=>K.length>0).map(({groupName:K,normalizedKeys:ie})=>{let G=ie.reduce((W,he)=>(W[he]=[he].concat(z.alias[he]||[]).map((De)=>{if(K===s.getPositionalGroupName())return De;else return(/^[0-9]$/.test(De)?z.boolean.includes(he)?"-":"--":De.length>1?"--":"-")+De}).sort((De,Ae)=>U(De)===U(Ae)?0:U(De)?1:-1).join(", "),W),{});return{groupName:K,normalizedKeys:ie,switches:G}});if(de.filter(({groupName:K})=>K!==s.getPositionalGroupName()).some(({normalizedKeys:K,switches:ie})=>!K.every((G)=>U(ie[G]))))de.filter(({groupName:K})=>K!==s.getPositionalGroupName()).forEach(({normalizedKeys:K,switches:ie})=>{K.forEach((G)=>{if(U(ie[G]))ie[G]=fy(ie[G],4)})});if(de.forEach(({groupName:K,normalizedKeys:ie,switches:G})=>{Q.div(K),ie.forEach((W)=>{let he=G[W],De=p[W]||"",Ae=null;if(De.includes(y))De=n(De.substring(y.length));if(z.boolean.includes(W))Ae=`[${n("boolean")}]`;if(z.count.includes(W))Ae=`[${n("count")}]`;if(z.string.includes(W))Ae=`[${n("string")}]`;if(z.normalize.includes(W))Ae=`[${n("string")}]`;if(z.array.includes(W))Ae=`[${n("array")}]`;if(z.number.includes(W))Ae=`[${n("number")}]`;let Yr=(J)=>typeof J==="string"?`[${n("deprecated: %s",J)}]`:`[${n("deprecated")}]`,_=[W in B?Yr(B[W]):null,Ae,W in j?`[${n("required")}]`:null,z.choices&&z.choices[W]?`[${n("choices:")} ${s.stringifiedValues(z.choices[W])}]`:null,S(z.default[W],z.defaultDescription[W])].filter(Boolean).join(" ");Q.span({text:fo(he),padding:[0,2,0,2+au(he)],width:w(G,te)+4},De);let F=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(_&&!F)Q.div({text:_,padding:[0,0,0,2],align:"right"});else Q.div()}),Q.div()}),d.length)Q.div(n("Examples:")),d.forEach((K)=>{K[0]=K[0].replace(/\$0/g,v)}),d.forEach((K)=>{if(K[1]==="")Q.div({text:K[0],padding:[0,2,0,2]});else Q.div({text:K[0],padding:[0,2,0,2],width:w(d,te)+4},{text:K[1]})}),Q.div();if(g.length>0){let K=g.map((ie)=>ie.replace(/\$0/g,v)).join(`
17
17
  `);Q.div(`${K}
18
- `)}return Q.toString().replace(/\s*$/,"")};function w(L,v,j){let H=0;if(!Array.isArray(L))L=Object.values(L).map((B)=>[B]);if(L.forEach((B)=>{H=Math.max(t.stringWidth(j?`${j} ${fo(B[0])}`:fo(B[0]))+nu(B[0]),H)}),v)H=Math.min(H,parseInt((v*0.5).toString(),10));return H}function x(){let L=e.getDemandedOptions(),v=e.getOptions();(Object.keys(v.alias)||[]).forEach((j)=>{v.alias[j].forEach((H)=>{if(p[H])s.describe(j,p[H]);if(H in L)e.demandOption(j,L[H]);if(v.boolean.includes(H))e.boolean(j);if(v.count.includes(H))e.count(j);if(v.string.includes(H))e.string(j);if(v.normalize.includes(H))e.normalize(j);if(v.array.includes(H))e.array(j);if(v.number.includes(H))e.number(j)})})}let D;s.cacheHelpMessage=function(){D=this.help()},s.clearCachedHelpMessage=function(){D=void 0},s.hasCachedHelpMessage=function(){return!!D};function E(L,v,j,H){let B=[],q=null;return Object.keys(j).forEach((z)=>{B=B.concat(j[z])}),L.forEach((z)=>{if(q=[z].concat(v[z]),!q.some((R)=>B.indexOf(R)!==-1))j[H].push(z)}),B}function C(L){return e.getOptions().hiddenOptions.indexOf(L)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}s.showHelp=(L)=>{let v=e.getInternalMethods().getLoggerInstance();if(!L)L="error";(typeof L==="function"?L:v[L])(s.help())},s.functionDescription=(L)=>["(",L.name?t.Parser.decamelize(L.name,"-"):n("generated-value"),")"].join(""),s.stringifiedValues=function(v,j){let H="",B=j||", ",q=[].concat(v);if(!v||!q.length)return H;return q.forEach((z)=>{if(H.length)H+=B;H+=JSON.stringify(z)}),H};function S(L,v){let j=`[${n("default:")} `;if(L===void 0&&!v)return null;if(v)j+=v;else switch(typeof L){case"string":j+=`"${L}"`;break;case"object":j+=JSON.stringify(L);break;default:j+=L}return`${j}]`}function k(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let O=null;s.version=(L)=>{O=L},s.showVersion=(L)=>{let v=e.getInternalMethods().getLoggerInstance();if(!L)L="error";(typeof L==="function"?L:v[L])(O)},s.reset=function(v){return r=null,u=!1,c=[],a=!1,g=[],d=[],f=[],p=Ht(p,(j)=>!v[j]),s};let P=[];return s.freeze=function(){P.push({failMessage:r,failureOutput:u,usages:c,usageDisabled:a,epilogs:g,examples:d,commands:f,descriptions:p})},s.unfreeze=function(v=!1){let j=P.pop();if(!j)return;if(v)p={...j.descriptions,...p},f=[...j.commands,...f],c=[...j.usages,...c],d=[...j.examples,...d],g=[...j.epilogs,...g];else({failMessage:r,failureOutput:u,usages:c,usageDisabled:a,epilogs:g,examples:d,commands:f,descriptions:p}=j)},s}function fi(e){return typeof e==="object"}function ly(e,t){return fi(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function nu(e){return fi(e)?e.indentation:0}function fo(e){return fi(e)?e.text:e}var ou=`###-begin-{{app_name}}-completions-###
18
+ `)}return Q.toString().replace(/\s*$/,"")};function w(L,v,j){let H=0;if(!Array.isArray(L))L=Object.values(L).map((B)=>[B]);if(L.forEach((B)=>{H=Math.max(t.stringWidth(j?`${j} ${fo(B[0])}`:fo(B[0]))+au(B[0]),H)}),v)H=Math.min(H,parseInt((v*0.5).toString(),10));return H}function x(){let L=e.getDemandedOptions(),v=e.getOptions();(Object.keys(v.alias)||[]).forEach((j)=>{v.alias[j].forEach((H)=>{if(p[H])s.describe(j,p[H]);if(H in L)e.demandOption(j,L[H]);if(v.boolean.includes(H))e.boolean(j);if(v.count.includes(H))e.count(j);if(v.string.includes(H))e.string(j);if(v.normalize.includes(H))e.normalize(j);if(v.array.includes(H))e.array(j);if(v.number.includes(H))e.number(j)})})}let D;s.cacheHelpMessage=function(){D=this.help()},s.clearCachedHelpMessage=function(){D=void 0},s.hasCachedHelpMessage=function(){return!!D};function E(L,v,j,H){let B=[],q=null;return Object.keys(j).forEach((z)=>{B=B.concat(j[z])}),L.forEach((z)=>{if(q=[z].concat(v[z]),!q.some((R)=>B.indexOf(R)!==-1))j[H].push(z)}),B}function C(L){return e.getOptions().hiddenOptions.indexOf(L)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}s.showHelp=(L)=>{let v=e.getInternalMethods().getLoggerInstance();if(!L)L="error";(typeof L==="function"?L:v[L])(s.help())},s.functionDescription=(L)=>["(",L.name?t.Parser.decamelize(L.name,"-"):n("generated-value"),")"].join(""),s.stringifiedValues=function(v,j){let H="",B=j||", ",q=[].concat(v);if(!v||!q.length)return H;return q.forEach((z)=>{if(H.length)H+=B;H+=JSON.stringify(z)}),H};function S(L,v){let j=`[${n("default:")} `;if(L===void 0&&!v)return null;if(v)j+=v;else switch(typeof L){case"string":j+=`"${L}"`;break;case"object":j+=JSON.stringify(L);break;default:j+=L}return`${j}]`}function k(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let O=null;s.version=(L)=>{O=L},s.showVersion=(L)=>{let v=e.getInternalMethods().getLoggerInstance();if(!L)L="error";(typeof L==="function"?L:v[L])(O)},s.reset=function(v){return r=null,u=!1,c=[],a=!1,g=[],d=[],f=[],p=zt(p,(j)=>!v[j]),s};let P=[];return s.freeze=function(){P.push({failMessage:r,failureOutput:u,usages:c,usageDisabled:a,epilogs:g,examples:d,commands:f,descriptions:p})},s.unfreeze=function(v=!1){let j=P.pop();if(!j)return;if(v)p={...j.descriptions,...p},f=[...j.commands,...f],c=[...j.usages,...c],d=[...j.examples,...d],g=[...j.epilogs,...g];else({failMessage:r,failureOutput:u,usages:c,usageDisabled:a,epilogs:g,examples:d,commands:f,descriptions:p}=j)},s}function pi(e){return typeof e==="object"}function fy(e,t){return pi(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function au(e){return pi(e)?e.indentation:0}function fo(e){return pi(e)?e.text:e}var lu=`###-begin-{{app_name}}-completions-###
19
19
  #
20
20
  # yargs command completion script
21
21
  #
@@ -44,7 +44,7 @@ _{{app_name}}_yargs_completions()
44
44
  }
45
45
  complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
46
46
  ###-end-{{app_name}}-completions-###
47
- `,ru=`#compdef {{app_name}}
47
+ `,uu=`#compdef {{app_name}}
48
48
  ###-begin-{{app_name}}-completions-###
49
49
  #
50
50
  # yargs command completion script
@@ -71,24 +71,24 @@ else
71
71
  compdef _{{app_name}}_yargs_completions {{app_name}}
72
72
  fi
73
73
  ###-end-{{app_name}}-completions-###
74
- `;class iu{constructor(e,t,n,s){var o,r,i;this.yargs=e,this.usage=t,this.command=n,this.shim=s,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((o=this.shim.getEnv("SHELL"))===null||o===void 0?void 0:o.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,s){let o=this.command.getCommandHandlers();for(let i=0,l=e.length;i<l;++i)if(o[e[i]]&&o[e[i]].builder){let u=o[e[i]].builder;if(uo(u)){this.indexAfterLastReset=i+1;let c=this.yargs.getInternalMethods().reset();return u(c,!0),c.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),s(null,r)}commandCompletions(e,t,n){let s=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&s[s.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((o)=>{let r=qt(o[0]).cmd;if(t.indexOf(r)===-1)if(!this.zshShell)e.push(r);else{let i=o[1]||"";e.push(r.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,s){if((s.match(/^-/)||s===""&&e.length===0)&&!this.previousArgHasChoices(t)){let o=this.yargs.getOptions(),r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(o.key).forEach((i)=>{let l=!!o.configuration["boolean-negation"]&&o.boolean.includes(i);if(!r.includes(i)&&!o.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,l))this.completeOptionKey(i,e,s,l&&!!o.default[i])})}}choicesFromOptionsCompletions(e,t,n,s){if(this.previousArgHasChoices(t)){let o=this.getPreviousArgChoices(t);if(o&&o.length>0)e.push(...o.map((r)=>r.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,s){if(s===""&&e.length>0&&this.previousArgHasChoices(t))return;let o=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=o[n._.length-r-1];if(!i)return;let l=this.yargs.getOptions().choices[i]||[];for(let u of l)if(u.startsWith(s))e.push(u.replace(/:/g,"\\:"))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],n="";if(!t.startsWith("-")&&e.length>1)n=t,t=e[e.length-2];if(!t.startsWith("-"))return;let s=t.replace(/^-+/,""),o=this.yargs.getOptions(),r=[s,...this.yargs.getAliases()[s]||[]],i;for(let l of r)if(Object.prototype.hasOwnProperty.call(o.key,l)&&Array.isArray(o.choices[l])){i=o.choices[l];break}if(i)return i.filter((l)=>!n||l.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let s=(o)=>e.indexOf((/^[^0-9]$/.test(o)?"-":"--")+o)!==-1;if(s(t))return!0;if(n&&s(`no-${t}`))return!0;if(this.aliases){for(let o of this.aliases[t])if(s(o))return!0}return!1}completeOptionKey(e,t,n,s){var o,r,i,l;let u=e;if(this.zshShell){let f=this.usage.getDescriptions(),p=(r=(o=this===null||this===void 0?void 0:this.aliases)===null||o===void 0?void 0:o[e])===null||r===void 0?void 0:r.find((m)=>{let y=f[m];return typeof y==="string"&&y.length>0}),g=p?f[p]:void 0,h=(l=(i=f[e])!==null&&i!==void 0?i:g)!==null&&l!==void 0?l:"";u=`${e.replace(/:/g,"\\:")}:${h.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let c=(f)=>/^--/.test(f),a=(f)=>/^[^0-9]$/.test(f),d=!c(n)&&a(e)?"-":"--";if(t.push(d+u),s)t.push(d+"no-"+u)}customCompletion(e,t,n,s){if(Ue(this.customCompletionFunction,null,this.shim),dy(this.customCompletionFunction)){let o=this.customCompletionFunction(n,t);if(De(o))return o.then((r)=>{this.shim.process.nextTick(()=>{s(null,r)})}).catch((r)=>{this.shim.process.nextTick(()=>{s(r,void 0)})});return s(null,o)}else if(fy(this.customCompletionFunction))return this.customCompletionFunction(n,t,(o=s)=>this.defaultCompletion(e,t,n,o),(o)=>{s(null,o)});else return this.customCompletionFunction(n,t,(o)=>{s(null,o)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",s=this.yargs.parse(e,!0),o=this.customCompletionFunction?(r)=>this.customCompletion(e,r,n,t):(r)=>this.defaultCompletion(e,r,n,t);return De(s)?s.then(o):o(s)}generateCompletionScript(e,t){let n=this.zshShell?ru:ou,s=this.shim.path.basename(e);if(e.match(/\.js$/))e=`./${e}`;return n=n.replace(/{{app_name}}/g,s),n=n.replace(/{{completion_command}}/g,t),n.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}}function au(e,t,n,s){return new iu(e,t,n,s)}function dy(e){return e.length<3}function fy(e){return e.length>3}function cu(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],s;for(s=0;s<=t.length;s++)n[s]=[s];let o;for(o=0;o<=e.length;o++)n[0][o]=o;for(s=1;s<=t.length;s++)for(o=1;o<=e.length;o++)if(t.charAt(s-1)===e.charAt(o-1))n[s][o]=n[s-1][o-1];else if(s>1&&o>1&&t.charAt(s-2)===e.charAt(o-1)&&t.charAt(s-1)===e.charAt(o-2))n[s][o]=n[s-2][o-2]+1;else n[s][o]=Math.min(n[s-1][o-1]+1,Math.min(n[s][o-1]+1,n[s-1][o]+1));return n[t.length][e.length]}var lu=["$0","--","_"];function uu(e,t,n){let s=n.y18n.__,o=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(o("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(o("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(o("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 p=null;for(let g of Object.keys(f))if(!Object.prototype.hasOwnProperty.call(d,g)||typeof d[g]>"u")p=p||{},p[g]=f[g];if(p){let g=[];for(let m of Object.keys(p)){let y=p[m];if(y&&g.indexOf(y)<0)g.push(y)}let h=g.length?`
74
+ `;class du{constructor(e,t,n,s){var o,r,i;this.yargs=e,this.usage=t,this.command=n,this.shim=s,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((o=this.shim.getEnv("SHELL"))===null||o===void 0?void 0:o.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,s){let o=this.command.getCommandHandlers();for(let i=0,l=e.length;i<l;++i)if(o[e[i]]&&o[e[i]].builder){let u=o[e[i]].builder;if(uo(u)){this.indexAfterLastReset=i+1;let c=this.yargs.getInternalMethods().reset();return u(c,!0),c.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),s(null,r)}commandCompletions(e,t,n){let s=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&s[s.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((o)=>{let r=Ht(o[0]).cmd;if(t.indexOf(r)===-1)if(!this.zshShell)e.push(r);else{let i=o[1]||"";e.push(r.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,s){if((s.match(/^-/)||s===""&&e.length===0)&&!this.previousArgHasChoices(t)){let o=this.yargs.getOptions(),r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(o.key).forEach((i)=>{let l=!!o.configuration["boolean-negation"]&&o.boolean.includes(i);if(!r.includes(i)&&!o.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,l))this.completeOptionKey(i,e,s,l&&!!o.default[i])})}}choicesFromOptionsCompletions(e,t,n,s){if(this.previousArgHasChoices(t)){let o=this.getPreviousArgChoices(t);if(o&&o.length>0)e.push(...o.map((r)=>r.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,s){if(s===""&&e.length>0&&this.previousArgHasChoices(t))return;let o=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=o[n._.length-r-1];if(!i)return;let l=this.yargs.getOptions().choices[i]||[];for(let u of l)if(u.startsWith(s))e.push(u.replace(/:/g,"\\:"))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],n="";if(!t.startsWith("-")&&e.length>1)n=t,t=e[e.length-2];if(!t.startsWith("-"))return;let s=t.replace(/^-+/,""),o=this.yargs.getOptions(),r=[s,...this.yargs.getAliases()[s]||[]],i;for(let l of r)if(Object.prototype.hasOwnProperty.call(o.key,l)&&Array.isArray(o.choices[l])){i=o.choices[l];break}if(i)return i.filter((l)=>!n||l.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let s=(o)=>e.indexOf((/^[^0-9]$/.test(o)?"-":"--")+o)!==-1;if(s(t))return!0;if(n&&s(`no-${t}`))return!0;if(this.aliases){for(let o of this.aliases[t])if(s(o))return!0}return!1}completeOptionKey(e,t,n,s){var o,r,i,l;let u=e;if(this.zshShell){let f=this.usage.getDescriptions(),p=(r=(o=this===null||this===void 0?void 0:this.aliases)===null||o===void 0?void 0:o[e])===null||r===void 0?void 0:r.find((m)=>{let y=f[m];return typeof y==="string"&&y.length>0}),g=p?f[p]:void 0,h=(l=(i=f[e])!==null&&i!==void 0?i:g)!==null&&l!==void 0?l:"";u=`${e.replace(/:/g,"\\:")}:${h.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let c=(f)=>/^--/.test(f),a=(f)=>/^[^0-9]$/.test(f),d=!c(n)&&a(e)?"-":"--";if(t.push(d+u),s)t.push(d+"no-"+u)}customCompletion(e,t,n,s){if(Ue(this.customCompletionFunction,null,this.shim),hy(this.customCompletionFunction)){let o=this.customCompletionFunction(n,t);if(ke(o))return o.then((r)=>{this.shim.process.nextTick(()=>{s(null,r)})}).catch((r)=>{this.shim.process.nextTick(()=>{s(r,void 0)})});return s(null,o)}else if(gy(this.customCompletionFunction))return this.customCompletionFunction(n,t,(o=s)=>this.defaultCompletion(e,t,n,o),(o)=>{s(null,o)});else return this.customCompletionFunction(n,t,(o)=>{s(null,o)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",s=this.yargs.parse(e,!0),o=this.customCompletionFunction?(r)=>this.customCompletion(e,r,n,t):(r)=>this.defaultCompletion(e,r,n,t);return ke(s)?s.then(o):o(s)}generateCompletionScript(e,t){let n=this.zshShell?uu:lu,s=this.shim.path.basename(e);if(e.match(/\.js$/))e=`./${e}`;return n=n.replace(/{{app_name}}/g,s),n=n.replace(/{{completion_command}}/g,t),n.replace(/{{app_path}}/g,e)}registerFunction(e){this.customCompletionFunction=e}setParsed(e){this.aliases=e.aliases}}function fu(e,t,n,s){return new du(e,t,n,s)}function hy(e){return e.length<3}function gy(e){return e.length>3}function pu(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],s;for(s=0;s<=t.length;s++)n[s]=[s];let o;for(o=0;o<=e.length;o++)n[0][o]=o;for(s=1;s<=t.length;s++)for(o=1;o<=e.length;o++)if(t.charAt(s-1)===e.charAt(o-1))n[s][o]=n[s-1][o-1];else if(s>1&&o>1&&t.charAt(s-2)===e.charAt(o-1)&&t.charAt(s-1)===e.charAt(o-2))n[s][o]=n[s-2][o-2]+1;else n[s][o]=Math.min(n[s-1][o-1]+1,Math.min(n[s][o-1]+1,n[s-1][o]+1));return n[t.length][e.length]}var hu=["$0","--","_"];function gu(e,t,n){let s=n.y18n.__,o=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(o("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(o("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(o("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 p=null;for(let g of Object.keys(f))if(!Object.prototype.hasOwnProperty.call(d,g)||typeof d[g]>"u")p=p||{},p[g]=f[g];if(p){let g=[];for(let m of Object.keys(p)){let y=p[m];if(y&&g.indexOf(y)<0)g.push(y)}let h=g.length?`
75
75
  ${g.join(`
76
- `)}`:"";t.fail(o("Missing required argument: %s","Missing required arguments: %s",Object.keys(p).length,Object.keys(p).join(", ")+h))}},r.unknownArguments=function(d,f,p,g,h=!0){var m;let y=e.getInternalMethods().getCommandInstance().getCommands(),w=[],x=e.getInternalMethods().getContext();if(Object.keys(d).forEach((D)=>{if(!lu.includes(D)&&!Object.prototype.hasOwnProperty.call(p,D)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),D)&&!r.isValidAndSomeAliasIsNotNew(D,f))w.push(D)}),h&&(x.commands.length>0||y.length>0||g))d._.slice(x.commands.length).forEach((D)=>{if(!y.includes(""+D))w.push(""+D)});if(h){let E=((m=e.getDemandedCommands()._)===null||m===void 0?void 0:m.max)||0,C=x.commands.length+E;if(C<d._.length)d._.slice(C).forEach((S)=>{if(S=String(S),!x.commands.includes(S)&&!w.includes(S))w.push(S)})}if(w.length)t.fail(o("Unknown argument: %s","Unknown arguments: %s",w.length,w.map((D)=>D.trim()?D:`"${D}"`).join(", ")))},r.unknownCommands=function(d){let f=e.getInternalMethods().getCommandInstance().getCommands(),p=[],g=e.getInternalMethods().getContext();if(g.commands.length>0||f.length>0)d._.slice(g.commands.length).forEach((h)=>{if(!f.includes(""+h))p.push(""+h)});if(p.length>0)return t.fail(o("Unknown command: %s","Unknown commands: %s",p.length,p.join(", "))),!0;else return!1},r.isValidAndSomeAliasIsNotNew=function(d,f){if(!Object.prototype.hasOwnProperty.call(f,d))return!1;let p=e.parsed.newAliases;return[d,...f[d]].some((g)=>!Object.prototype.hasOwnProperty.call(p,g)||!p[d])},r.limitedChoices=function(d){let f=e.getOptions(),p={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((m)=>{if(lu.indexOf(m)===-1&&Object.prototype.hasOwnProperty.call(f.choices,m))[].concat(d[m]).forEach((y)=>{if(f.choices[m].indexOf(y)===-1&&y!==void 0)p[m]=(p[m]||[]).concat(y)})});let g=Object.keys(p);if(!g.length)return;let h=s("Invalid values:");g.forEach((m)=>{h+=`
76
+ `)}`:"";t.fail(o("Missing required argument: %s","Missing required arguments: %s",Object.keys(p).length,Object.keys(p).join(", ")+h))}},r.unknownArguments=function(d,f,p,g,h=!0){var m;let y=e.getInternalMethods().getCommandInstance().getCommands(),w=[],x=e.getInternalMethods().getContext();if(Object.keys(d).forEach((D)=>{if(!hu.includes(D)&&!Object.prototype.hasOwnProperty.call(p,D)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),D)&&!r.isValidAndSomeAliasIsNotNew(D,f))w.push(D)}),h&&(x.commands.length>0||y.length>0||g))d._.slice(x.commands.length).forEach((D)=>{if(!y.includes(""+D))w.push(""+D)});if(h){let E=((m=e.getDemandedCommands()._)===null||m===void 0?void 0:m.max)||0,C=x.commands.length+E;if(C<d._.length)d._.slice(C).forEach((S)=>{if(S=String(S),!x.commands.includes(S)&&!w.includes(S))w.push(S)})}if(w.length)t.fail(o("Unknown argument: %s","Unknown arguments: %s",w.length,w.map((D)=>D.trim()?D:`"${D}"`).join(", ")))},r.unknownCommands=function(d){let f=e.getInternalMethods().getCommandInstance().getCommands(),p=[],g=e.getInternalMethods().getContext();if(g.commands.length>0||f.length>0)d._.slice(g.commands.length).forEach((h)=>{if(!f.includes(""+h))p.push(""+h)});if(p.length>0)return t.fail(o("Unknown command: %s","Unknown commands: %s",p.length,p.join(", "))),!0;else return!1},r.isValidAndSomeAliasIsNotNew=function(d,f){if(!Object.prototype.hasOwnProperty.call(f,d))return!1;let p=e.parsed.newAliases;return[d,...f[d]].some((g)=>!Object.prototype.hasOwnProperty.call(p,g)||!p[d])},r.limitedChoices=function(d){let f=e.getOptions(),p={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((m)=>{if(hu.indexOf(m)===-1&&Object.prototype.hasOwnProperty.call(f.choices,m))[].concat(d[m]).forEach((y)=>{if(f.choices[m].indexOf(y)===-1&&y!==void 0)p[m]=(p[m]||[]).concat(y)})});let g=Object.keys(p);if(!g.length)return;let h=s("Invalid values:");g.forEach((m)=>{h+=`
77
77
  ${s("Argument: %s, Given: %s, Choices: %s",m,t.stringifiedValues(p[m]),t.stringifiedValues(f.choices[m]))}`}),t.fail(h)};let i={};r.implies=function(d,f){if(V("<string|object> [array|number|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((p)=>{r.implies(p,d[p])});else{if(e.global(d),!i[d])i[d]=[];if(Array.isArray(f))f.forEach((p)=>r.implies(d,p));else Ue(f,void 0,n),i[d].push(f)}},r.getImplied=function(){return i};function l(a,d){let f=Number(d);if(d=isNaN(f)?d:f,typeof d==="number")d=a._.length>=d;else if(d.match(/^--no-.+/))d=d.match(/^--no-(.+)/)[1],d=!Object.prototype.hasOwnProperty.call(a,d);else d=Object.prototype.hasOwnProperty.call(a,d);return d}r.implications=function(d){let f=[];if(Object.keys(i).forEach((p)=>{let g=p;(i[p]||[]).forEach((h)=>{let m=g,y=h;if(m=l(d,m),h=l(d,h),m&&!h)f.push(` ${g} -> ${y}`)})}),f.length){let p=`${s("Implications failed:")}
78
- `;f.forEach((g)=>{p+=g}),t.fail(p)}};let u={};r.conflicts=function(d,f){if(V("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((p)=>{r.conflicts(p,d[p])});else{if(e.global(d),!u[d])u[d]=[];if(Array.isArray(f))f.forEach((p)=>r.conflicts(d,p));else u[d].push(f)}},r.getConflicting=()=>u,r.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(u[f])u[f].forEach((p)=>{if(p&&d[f]!==void 0&&d[p]!==void 0)t.fail(s("Arguments %s and %s are mutually exclusive",f,p))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(u).forEach((f)=>{u[f].forEach((p)=>{if(p&&d[n.Parser.camelCase(f)]!==void 0&&d[n.Parser.camelCase(p)]!==void 0)t.fail(s("Arguments %s and %s are mutually exclusive",f,p))})})},r.recommendCommands=function(d,f){f=f.sort((m,y)=>y.length-m.length);let g=null,h=1/0;for(let m=0,y;(y=f[m])!==void 0;m++){let w=cu(d,y);if(w<=3&&w<h)h=w,g=y}if(g)t.fail(s("Did you mean %s?",g))},r.reset=function(d){return i=Ht(i,(f)=>!d[f]),u=Ht(u,(f)=>!d[f]),r};let c=[];return r.freeze=function(){c.push({implied:i,conflicting:u})},r.unfreeze=function(){let d=c.pop();Ue(d,void 0,n),{implied:i,conflicting:u}=d},r}var pi=[],gs;function ms(e,t,n,s){gs=s;let o={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return o;let r=/\.json|\..*rc$/.test(e.extends),i=null;if(!r)try{i=import.meta.resolve(e.extends)}catch(l){return e}else i=hy(t,e.extends);py(i),pi.push(i),o=r?JSON.parse(gs.readFileSync(i,"utf8")):s.require(e.extends),delete e.extends,o=ms(o,gs.path.dirname(i),n,gs)}return pi=[],n?du(o,e):Object.assign({},o,e)}function py(e){if(pi.indexOf(e)>-1)throw new $e(`Circular extended configurations: '${e}'.`)}function hy(e,t){return gs.path.resolve(e,t)}function du(e,t){let n={};function s(o){return o&&typeof o==="object"&&!Array.isArray(o)}Object.assign(n,e);for(let o of Object.keys(t))if(s(t[o])&&s(n[o]))n[o]=du(e[o],t[o]);else n[o]=t[o];return n}var Z=function(e,t,n,s,o){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!o)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?o.call(e,n):o?o.value=n:t.set(e,n),n},b=function(e,t,n,s){if(n==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(e):s?s.value:t.get(e)},Ce,mn,ys,ze,Qe,po,Yt,yn,ho,it,go,at,St,et,ct,mo,bn,ve,ne,yo,bo,tt,wn,Kn,Dn,Gt,wo,ae,kn,xn,Sn,ue,Do,_t,_e;function Ou(e){return(t=[],n=e.process.cwd(),s)=>{let o=new Ru(t,n,s,e);return Object.defineProperty(o,"argv",{get:()=>o.parse(),enumerable:!0}),o.help(),o.version(),o}}var fu=Symbol("copyDoubleDash"),pu=Symbol("copyDoubleDash"),hi=Symbol("deleteFromParserHintObject"),hu=Symbol("emitWarning"),gu=Symbol("freeze"),mu=Symbol("getDollarZero"),_n=Symbol("getParserConfiguration"),yu=Symbol("getUsageConfiguration"),gi=Symbol("guessLocale"),bu=Symbol("guessVersion"),wu=Symbol("parsePositionalNumbers"),mi=Symbol("pkgUp"),Xt=Symbol("populateParserHintArray"),qn=Symbol("populateParserHintSingleValueDictionary"),yi=Symbol("populateParserHintArrayDictionary"),bi=Symbol("populateParserHintDictionary"),wi=Symbol("sanitizeKey"),Di=Symbol("setKey"),ki=Symbol("unfreeze"),Du=Symbol("validateAsync"),ku=Symbol("getCommandInstance"),xu=Symbol("getContext"),Su=Symbol("getHasOutput"),_u=Symbol("getLoggerInstance"),Eu=Symbol("getParseContext"),$u=Symbol("getUsageInstance"),Cu=Symbol("getValidationInstance"),ko=Symbol("hasParseCallback"),Au=Symbol("isGlobalContext"),En=Symbol("postProcess"),Fu=Symbol("rebase"),xi=Symbol("reset"),bs=Symbol("runYargsParserAndExecuteCommands"),Si=Symbol("runValidation"),Tu=Symbol("setHasOutput"),$n=Symbol("kTrackManuallySetKeys"),gy="en_US";class Ru{constructor(e=[],t,n,s){this.customScriptName=!1,this.parsed=!1,Ce.set(this,void 0),mn.set(this,void 0),ys.set(this,{commands:[],fullCommands:[]}),ze.set(this,null),Qe.set(this,null),po.set(this,"show-hidden"),Yt.set(this,null),yn.set(this,!0),ho.set(this,{}),it.set(this,!0),go.set(this,[]),at.set(this,void 0),St.set(this,{}),et.set(this,!1),ct.set(this,null),mo.set(this,!0),bn.set(this,void 0),ve.set(this,""),ne.set(this,void 0),yo.set(this,void 0),bo.set(this,{}),tt.set(this,null),wn.set(this,null),Kn.set(this,{}),Dn.set(this,{}),Gt.set(this,void 0),wo.set(this,!1),ae.set(this,void 0),kn.set(this,!1),xn.set(this,!1),Sn.set(this,!1),ue.set(this,void 0),Do.set(this,{}),_t.set(this,null),_e.set(this,void 0),Z(this,ae,s,"f"),Z(this,Gt,e,"f"),Z(this,mn,t,"f"),Z(this,yo,n,"f"),Z(this,at,new di(this),"f"),this.$0=this[mu](),this[xi](),Z(this,Ce,b(this,Ce,"f"),"f"),Z(this,ue,b(this,ue,"f"),"f"),Z(this,_e,b(this,_e,"f"),"f"),Z(this,ne,b(this,ne,"f"),"f"),b(this,ne,"f").showHiddenOpt=b(this,po,"f"),Z(this,bn,this[pu](),"f"),b(this,ae,"f").y18n.setLocale(gy)}addHelpOpt(e,t){if(V("[string|boolean] [string]",[e,t],arguments.length),b(this,ct,"f"))this[hi](b(this,ct,"f")),Z(this,ct,null,"f");if(e===!1&&t===void 0)return this;return Z(this,ct,typeof e==="string"?e:"help","f"),this.boolean(b(this,ct,"f")),this.describe(b(this,ct,"f"),t||b(this,ue,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(V("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:b(this,po,"f");return this.boolean(n),this.describe(n,t||b(this,ue,"f").deferY18nLookup("Show hidden options")),b(this,ne,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return V("<object|string|array> [string|array]",[e,t],arguments.length),this[yi](this.alias.bind(this),"alias",e,t),this}array(e){return V("<array|string>",[e],arguments.length),this[Xt]("array",e),this[$n](e),this}boolean(e){return V("<array|string>",[e],arguments.length),this[Xt]("boolean",e),this[$n](e),this}check(e,t){return V("<function> [boolean]",[e,t],arguments.length),this.middleware((n,s)=>gn(()=>e(n,s.getOptions()),(o)=>{if(!o)b(this,ue,"f").fail(b(this,ae,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof o==="string"||o instanceof Error)b(this,ue,"f").fail(o.toString(),o);return n},(o)=>(b(this,ue,"f").fail(o.message?o.message:o.toString(),o),n)),!1,t),this}choices(e,t){return V("<object|string|array> [string|array]",[e,t],arguments.length),this[yi](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(V("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new $e("coerce callback must be provided");for(let s of e)this.coerce(s,t);return this}else if(typeof e==="object"){for(let s of Object.keys(e))this.coerce(s,e[s]);return this}if(!t)throw new $e("coerce callback must be provided");let n=e;return b(this,ne,"f").key[n]=!0,b(this,at,"f").addCoerceMiddleware((s,o)=>{var r;let i=(r=o.getAliases()[n])!==null&&r!==void 0?r:[],l=[n,...i].filter((u)=>Object.prototype.hasOwnProperty.call(s,u));if(l.length===0)return s;return gn(()=>t(s[l[0]]),(u)=>(l.forEach((c)=>{s[c]=u}),s),(u)=>{throw new $e(u.message)})},n),this}conflicts(e,t){return V("<string|object> [string|array]",[e,t],arguments.length),b(this,_e,"f").conflicts(e,t),this}config(e="config",t,n){if(V("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=ms(e,b(this,mn,"f"),this[_n]()["deep-merge-config"]||!1,b(this,ae,"f")),b(this,ne,"f").configObjects=(b(this,ne,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||b(this,ue,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((s)=>{b(this,ne,"f").config[s]=n||!0}),this}completion(e,t,n){if(V("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(Z(this,Qe,e||b(this,Qe,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(b(this,Qe,"f"),t),n)b(this,ze,"f").registerFunction(n);return this}command(e,t,n,s,o,r){return V("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,s,o,r],arguments.length),b(this,Ce,"f").addHandler(e,t,n,s,o,r),this}commands(e,t,n,s,o,r){return this.command(e,t,n,s,o,r)}commandDir(e,t){V("<string> [object]",[e,t],arguments.length);let n=b(this,yo,"f")||b(this,ae,"f").require;return b(this,Ce,"f").addDirectory(e,n,b(this,ae,"f").getCallerFile(),t),this}count(e){return V("<array|string>",[e],arguments.length),this[Xt]("count",e),this[$n](e),this}default(e,t,n){if(V("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)ui(e,b(this,ae,"f")),b(this,ne,"f").defaultDescription[e]=n;if(typeof t==="function"){if(ui(e,b(this,ae,"f")),!b(this,ne,"f").defaultDescription[e])b(this,ne,"f").defaultDescription[e]=b(this,ue,"f").functionDescription(t);t=t.call()}return this[qn](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,s){if(V("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,s],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),b(this,ne,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:s},this}demand(e,t,n){if(Array.isArray(t))t.forEach((s)=>{Ue(n,!0,b(this,ae,"f")),this.demandOption(s,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")Ue(n,!0,b(this,ae,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((s)=>{Ue(n,!0,b(this,ae,"f")),this.demandOption(s,n)});else if(typeof n==="string")this.demandOption(e,n);else if(n===!0||typeof n>"u")this.demandOption(e);return this}demandOption(e,t){return V("<object|string|array> [string]",[e,t],arguments.length),this[qn](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return V("<string> [string|boolean]",[e,t],arguments.length),b(this,ne,"f").deprecatedOptions[e]=t,this}describe(e,t){return V("<object|string|array> [string]",[e,t],arguments.length),this[Di](e,!0),b(this,ue,"f").describe(e,t),this}detectLocale(e){return V("<boolean>",[e],arguments.length),Z(this,yn,e,"f"),this}env(e){if(V("[string|boolean]",[e],arguments.length),e===!1)delete b(this,ne,"f").envPrefix;else b(this,ne,"f").envPrefix=e||"";return this}epilogue(e){return V("<string>",[e],arguments.length),b(this,ue,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(V("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else b(this,ue,"f").example(e,t);return this}exit(e,t){if(Z(this,et,!0,"f"),Z(this,Yt,t,"f"),b(this,it,"f"))b(this,ae,"f").process.exit(e)}exitProcess(e=!0){return V("[boolean]",[e],arguments.length),Z(this,it,e,"f"),this}fail(e){if(V("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new $e("Invalid first argument. Expected function or boolean 'false'");return b(this,ue,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(V("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,s)=>{b(this,ze,"f").getCompletion(e,(o,r)=>{if(o)s(o);else n(r)})});else return b(this,ze,"f").getCompletion(e,t)}getDemandedOptions(){return V([],0),b(this,ne,"f").demandedOptions}getDemandedCommands(){return V([],0),b(this,ne,"f").demandedCommands}getDeprecatedOptions(){return V([],0),b(this,ne,"f").deprecatedOptions}getDetectLocale(){return b(this,yn,"f")}getExitProcess(){return b(this,it,"f")}getGroups(){return Object.assign({},b(this,St,"f"),b(this,Dn,"f"))}getHelp(){if(Z(this,et,!0,"f"),!b(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[bs](b(this,Gt,"f"),void 0,void 0,0,!0);if(De(t))return t.then(()=>b(this,ue,"f").help())}let e=b(this,Ce,"f").runDefaultBuilderOn(this);if(De(e))return e.then(()=>b(this,ue,"f").help())}return Promise.resolve(b(this,ue,"f").help())}getOptions(){return b(this,ne,"f")}getStrict(){return b(this,kn,"f")}getStrictCommands(){return b(this,xn,"f")}getStrictOptions(){return b(this,Sn,"f")}global(e,t){if(V("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)b(this,ne,"f").local=b(this,ne,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!b(this,ne,"f").local.includes(n))b(this,ne,"f").local.push(n)});return this}group(e,t){V("<string|array> <string>",[e,t],arguments.length);let n=b(this,Dn,"f")[t]||b(this,St,"f")[t];if(b(this,Dn,"f")[t])delete b(this,Dn,"f")[t];let s={};return b(this,St,"f")[t]=(n||[]).concat(e).filter((o)=>{if(s[o])return!1;return s[o]=!0}),this}hide(e){return V("<string>",[e],arguments.length),b(this,ne,"f").hiddenOptions.push(e),this}implies(e,t){return V("<string|object> [number|string|array]",[e,t],arguments.length),b(this,_e,"f").implies(e,t),this}locale(e){if(V("[string]",[e],arguments.length),e===void 0)return this[gi](),b(this,ae,"f").y18n.getLocale();return Z(this,yn,!1,"f"),b(this,ae,"f").y18n.setLocale(e),this}middleware(e,t,n){return b(this,at,"f").addMiddleware(e,!!t,n)}nargs(e,t){return V("<string|object|array> [number]",[e,t],arguments.length),this[qn](this.nargs.bind(this),"narg",e,t),this}normalize(e){return V("<array|string>",[e],arguments.length),this[Xt]("normalize",e),this}number(e){return V("<array|string>",[e],arguments.length),this[Xt]("number",e),this[$n](e),this}option(e,t){if(V("<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[$n](e),b(this,_t,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[hu](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
79
- `),void 0,"versionWarning");if(b(this,ne,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let s=t.demand||t.required||t.require;if(s)this.demand(e,s);if(t.demandOption)this.demandOption(e,typeof t.demandOption==="string"?t.demandOption:void 0);if(t.conflicts)this.conflicts(e,t.conflicts);if("default"in t)this.default(e,t.default);if(t.implies!==void 0)this.implies(e,t.implies);if(t.nargs!==void 0)this.nargs(e,t.nargs);if(t.config)this.config(e,t.configParser);if(t.normalize)this.normalize(e);if(t.choices)this.choices(e,t.choices);if(t.coerce)this.coerce(e,t.coerce);if(t.group)this.group(e,t.group);if(t.boolean||t.type==="boolean"){if(this.boolean(e),t.alias)this.boolean(t.alias)}if(t.array||t.type==="array"){if(this.array(e),t.alias)this.array(t.alias)}if(t.number||t.type==="number"){if(this.number(e),t.alias)this.number(t.alias)}if(t.string||t.type==="string"){if(this.string(e),t.alias)this.string(t.alias)}if(t.count||t.type==="count")this.count(e);if(typeof t.global==="boolean")this.global(e,t.global);if(t.defaultDescription)b(this,ne,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let o=t.describe||t.description||t.desc,r=b(this,ue,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(r,e)||typeof o==="string")this.describe(e,o);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(V("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[gu](),typeof e>"u")e=b(this,Gt,"f");if(typeof t==="object")Z(this,wn,t,"f"),t=n;if(typeof t==="function")Z(this,tt,t,"f"),t=!1;if(!t)Z(this,Gt,e,"f");if(b(this,tt,"f"))Z(this,it,!1,"f");let s=this[bs](e,!!t),o=this.parsed;if(b(this,ze,"f").setParsed(this.parsed),De(s))return s.then((r)=>{if(b(this,tt,"f"))b(this,tt,"f").call(this,b(this,Yt,"f"),r,b(this,ve,"f"));return r}).catch((r)=>{if(b(this,tt,"f"))b(this,tt,"f")(r,this.parsed.argv,b(this,ve,"f"));throw r}).finally(()=>{this[ki](),this.parsed=o});else{if(b(this,tt,"f"))b(this,tt,"f").call(this,b(this,Yt,"f"),s,b(this,ve,"f"));this[ki](),this.parsed=o}return s}parseAsync(e,t,n){let s=this.parse(e,t,n);return!De(s)?Promise.resolve(s):s}parseSync(e,t,n){let s=this.parse(e,t,n);if(De(s))throw new $e(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return s}parserConfiguration(e){return V("<object>",[e],arguments.length),Z(this,bo,e,"f"),this}pkgConf(e,t){V("<string> [string]",[e,t],arguments.length);let n=null,s=this[mi](t||b(this,mn,"f"));if(s[e]&&typeof s[e]==="object")n=ms(s[e],t||b(this,mn,"f"),this[_n]()["deep-merge-config"]||!1,b(this,ae,"f")),b(this,ne,"f").configObjects=(b(this,ne,"f").configObjects||[]).concat(n);return this}positional(e,t){V("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=Ht(t,(r,i)=>{if(r==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(r)});let s=b(this,ys,"f").fullCommands[b(this,ys,"f").fullCommands.length-1],o=s?b(this,Ce,"f").cmdToParseOptions(s):{array:[],alias:{},default:{},demand:{}};return Jn(o).forEach((r)=>{let i=o[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,b(this,ue,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return V("[boolean]",[e],arguments.length),Z(this,wo,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(V("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&b(this,ne,"f").narg[e])return this;else this[qn](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return V("[string] [string]",[e,t],arguments.length),e=e||this.$0,b(this,bn,"f").log(b(this,ze,"f").generateCompletionScript(e,t||b(this,Qe,"f")||"completion")),this}showHelp(e){if(V("[string|function]",[e],arguments.length),Z(this,et,!0,"f"),!b(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[bs](b(this,Gt,"f"),void 0,void 0,0,!0);if(De(n))return n.then(()=>{b(this,ue,"f").showHelp(e)}),this}let t=b(this,Ce,"f").runDefaultBuilderOn(this);if(De(t))return t.then(()=>{b(this,ue,"f").showHelp(e)}),this}return b(this,ue,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return V("[boolean|string] [string]",[e,t],arguments.length),b(this,ue,"f").showHelpOnFail(e,t),this}showVersion(e){return V("[string|function]",[e],arguments.length),b(this,ue,"f").showVersion(e),this}skipValidation(e){return V("<array|string>",[e],arguments.length),this[Xt]("skipValidation",e),this}strict(e){return V("[boolean]",[e],arguments.length),Z(this,kn,e!==!1,"f"),this}strictCommands(e){return V("[boolean]",[e],arguments.length),Z(this,xn,e!==!1,"f"),this}strictOptions(e){return V("[boolean]",[e],arguments.length),Z(this,Sn,e!==!1,"f"),this}string(e){return V("<array|string>",[e],arguments.length),this[Xt]("string",e),this[$n](e),this}terminalWidth(){return V([],0),b(this,ae,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return V("<object>",[e],arguments.length),Z(this,yn,!1,"f"),b(this,ae,"f").y18n.updateLocale(e),this}usage(e,t,n,s){if(V("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,s],arguments.length),t!==void 0)if(Ue(e,null,b(this,ae,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,s);else throw new $e(".usage() description must start with $0 if being used as alias for .command()");else return b(this,ue,"f").usage(e),this}usageConfiguration(e){return V("<object>",[e],arguments.length),Z(this,Do,e,"f"),this}version(e,t,n){if(V("[boolean|string] [string] [string]",[e,t,n],arguments.length),b(this,_t,"f"))this[hi](b(this,_t,"f")),b(this,ue,"f").version(void 0),Z(this,_t,null,"f");if(arguments.length===0)n=this[bu](),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 Z(this,_t,typeof e==="string"?e:"version","f"),t=t||b(this,ue,"f").deferY18nLookup("Show version number"),b(this,ue,"f").version(n||void 0),this.boolean(b(this,_t,"f")),this.describe(b(this,_t,"f"),t),this}wrap(e){return V("<number|null|undefined>",[e],arguments.length),b(this,ue,"f").wrap(e),this}[(Ce=new WeakMap,mn=new WeakMap,ys=new WeakMap,ze=new WeakMap,Qe=new WeakMap,po=new WeakMap,Yt=new WeakMap,yn=new WeakMap,ho=new WeakMap,it=new WeakMap,go=new WeakMap,at=new WeakMap,St=new WeakMap,et=new WeakMap,ct=new WeakMap,mo=new WeakMap,bn=new WeakMap,ve=new WeakMap,ne=new WeakMap,yo=new WeakMap,bo=new WeakMap,tt=new WeakMap,wn=new WeakMap,Kn=new WeakMap,Dn=new WeakMap,Gt=new WeakMap,wo=new WeakMap,ae=new WeakMap,kn=new WeakMap,xn=new WeakMap,Sn=new WeakMap,ue=new WeakMap,Do=new WeakMap,_t=new WeakMap,_e=new WeakMap,fu)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[pu](){return{log:(...e)=>{if(!this[ko]())console.log(...e);if(Z(this,et,!0,"f"),b(this,ve,"f").length)Z(this,ve,b(this,ve,"f")+`
78
+ `;f.forEach((g)=>{p+=g}),t.fail(p)}};let u={};r.conflicts=function(d,f){if(V("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((p)=>{r.conflicts(p,d[p])});else{if(e.global(d),!u[d])u[d]=[];if(Array.isArray(f))f.forEach((p)=>r.conflicts(d,p));else u[d].push(f)}},r.getConflicting=()=>u,r.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(u[f])u[f].forEach((p)=>{if(p&&d[f]!==void 0&&d[p]!==void 0)t.fail(s("Arguments %s and %s are mutually exclusive",f,p))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(u).forEach((f)=>{u[f].forEach((p)=>{if(p&&d[n.Parser.camelCase(f)]!==void 0&&d[n.Parser.camelCase(p)]!==void 0)t.fail(s("Arguments %s and %s are mutually exclusive",f,p))})})},r.recommendCommands=function(d,f){f=f.sort((m,y)=>y.length-m.length);let g=null,h=1/0;for(let m=0,y;(y=f[m])!==void 0;m++){let w=pu(d,y);if(w<=3&&w<h)h=w,g=y}if(g)t.fail(s("Did you mean %s?",g))},r.reset=function(d){return i=zt(i,(f)=>!d[f]),u=zt(u,(f)=>!d[f]),r};let c=[];return r.freeze=function(){c.push({implied:i,conflicting:u})},r.unfreeze=function(){let d=c.pop();Ue(d,void 0,n),{implied:i,conflicting:u}=d},r}var hi=[],gs;function ms(e,t,n,s){gs=s;let o={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return o;let r=/\.json|\..*rc$/.test(e.extends),i=null;if(!r)try{i=import.meta.resolve(e.extends)}catch(l){return e}else i=yy(t,e.extends);my(i),hi.push(i),o=r?JSON.parse(gs.readFileSync(i,"utf8")):s.require(e.extends),delete e.extends,o=ms(o,gs.path.dirname(i),n,gs)}return hi=[],n?mu(o,e):Object.assign({},o,e)}function my(e){if(hi.indexOf(e)>-1)throw new $e(`Circular extended configurations: '${e}'.`)}function yy(e,t){return gs.path.resolve(e,t)}function mu(e,t){let n={};function s(o){return o&&typeof o==="object"&&!Array.isArray(o)}Object.assign(n,e);for(let o of Object.keys(t))if(s(t[o])&&s(n[o]))n[o]=mu(e[o],t[o]);else n[o]=t[o];return n}var Z=function(e,t,n,s,o){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!o)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?o.call(e,n):o?o.value=n:t.set(e,n),n},b=function(e,t,n,s){if(n==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(e):s?s.value:t.get(e)},Ce,mn,ys,ze,Qe,po,Gt,yn,ho,it,go,at,St,et,ct,mo,bn,ve,ne,yo,bo,tt,wn,Kn,Dn,Xt,wo,ae,kn,xn,Sn,ue,Do,_t,Ee;function Lu(e){return(t=[],n=e.process.cwd(),s)=>{let o=new Nu(t,n,s,e);return Object.defineProperty(o,"argv",{get:()=>o.parse(),enumerable:!0}),o.help(),o.version(),o}}var yu=Symbol("copyDoubleDash"),bu=Symbol("copyDoubleDash"),gi=Symbol("deleteFromParserHintObject"),wu=Symbol("emitWarning"),Du=Symbol("freeze"),ku=Symbol("getDollarZero"),_n=Symbol("getParserConfiguration"),xu=Symbol("getUsageConfiguration"),mi=Symbol("guessLocale"),Su=Symbol("guessVersion"),_u=Symbol("parsePositionalNumbers"),yi=Symbol("pkgUp"),Vt=Symbol("populateParserHintArray"),qn=Symbol("populateParserHintSingleValueDictionary"),bi=Symbol("populateParserHintArrayDictionary"),wi=Symbol("populateParserHintDictionary"),Di=Symbol("sanitizeKey"),ki=Symbol("setKey"),xi=Symbol("unfreeze"),Eu=Symbol("validateAsync"),$u=Symbol("getCommandInstance"),Cu=Symbol("getContext"),Au=Symbol("getHasOutput"),Fu=Symbol("getLoggerInstance"),Tu=Symbol("getParseContext"),Ou=Symbol("getUsageInstance"),Ru=Symbol("getValidationInstance"),ko=Symbol("hasParseCallback"),Iu=Symbol("isGlobalContext"),En=Symbol("postProcess"),vu=Symbol("rebase"),Si=Symbol("reset"),bs=Symbol("runYargsParserAndExecuteCommands"),_i=Symbol("runValidation"),Pu=Symbol("setHasOutput"),$n=Symbol("kTrackManuallySetKeys"),by="en_US";class Nu{constructor(e=[],t,n,s){this.customScriptName=!1,this.parsed=!1,Ce.set(this,void 0),mn.set(this,void 0),ys.set(this,{commands:[],fullCommands:[]}),ze.set(this,null),Qe.set(this,null),po.set(this,"show-hidden"),Gt.set(this,null),yn.set(this,!0),ho.set(this,{}),it.set(this,!0),go.set(this,[]),at.set(this,void 0),St.set(this,{}),et.set(this,!1),ct.set(this,null),mo.set(this,!0),bn.set(this,void 0),ve.set(this,""),ne.set(this,void 0),yo.set(this,void 0),bo.set(this,{}),tt.set(this,null),wn.set(this,null),Kn.set(this,{}),Dn.set(this,{}),Xt.set(this,void 0),wo.set(this,!1),ae.set(this,void 0),kn.set(this,!1),xn.set(this,!1),Sn.set(this,!1),ue.set(this,void 0),Do.set(this,{}),_t.set(this,null),Ee.set(this,void 0),Z(this,ae,s,"f"),Z(this,Xt,e,"f"),Z(this,mn,t,"f"),Z(this,yo,n,"f"),Z(this,at,new fi(this),"f"),this.$0=this[ku](),this[Si](),Z(this,Ce,b(this,Ce,"f"),"f"),Z(this,ue,b(this,ue,"f"),"f"),Z(this,Ee,b(this,Ee,"f"),"f"),Z(this,ne,b(this,ne,"f"),"f"),b(this,ne,"f").showHiddenOpt=b(this,po,"f"),Z(this,bn,this[bu](),"f"),b(this,ae,"f").y18n.setLocale(by)}addHelpOpt(e,t){if(V("[string|boolean] [string]",[e,t],arguments.length),b(this,ct,"f"))this[gi](b(this,ct,"f")),Z(this,ct,null,"f");if(e===!1&&t===void 0)return this;return Z(this,ct,typeof e==="string"?e:"help","f"),this.boolean(b(this,ct,"f")),this.describe(b(this,ct,"f"),t||b(this,ue,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(V("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:b(this,po,"f");return this.boolean(n),this.describe(n,t||b(this,ue,"f").deferY18nLookup("Show hidden options")),b(this,ne,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return V("<object|string|array> [string|array]",[e,t],arguments.length),this[bi](this.alias.bind(this),"alias",e,t),this}array(e){return V("<array|string>",[e],arguments.length),this[Vt]("array",e),this[$n](e),this}boolean(e){return V("<array|string>",[e],arguments.length),this[Vt]("boolean",e),this[$n](e),this}check(e,t){return V("<function> [boolean]",[e,t],arguments.length),this.middleware((n,s)=>gn(()=>e(n,s.getOptions()),(o)=>{if(!o)b(this,ue,"f").fail(b(this,ae,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof o==="string"||o instanceof Error)b(this,ue,"f").fail(o.toString(),o);return n},(o)=>(b(this,ue,"f").fail(o.message?o.message:o.toString(),o),n)),!1,t),this}choices(e,t){return V("<object|string|array> [string|array]",[e,t],arguments.length),this[bi](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(V("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new $e("coerce callback must be provided");for(let s of e)this.coerce(s,t);return this}else if(typeof e==="object"){for(let s of Object.keys(e))this.coerce(s,e[s]);return this}if(!t)throw new $e("coerce callback must be provided");let n=e;return b(this,ne,"f").key[n]=!0,b(this,at,"f").addCoerceMiddleware((s,o)=>{var r;let i=(r=o.getAliases()[n])!==null&&r!==void 0?r:[],l=[n,...i].filter((u)=>Object.prototype.hasOwnProperty.call(s,u));if(l.length===0)return s;return gn(()=>t(s[l[0]]),(u)=>(l.forEach((c)=>{s[c]=u}),s),(u)=>{throw new $e(u.message)})},n),this}conflicts(e,t){return V("<string|object> [string|array]",[e,t],arguments.length),b(this,Ee,"f").conflicts(e,t),this}config(e="config",t,n){if(V("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=ms(e,b(this,mn,"f"),this[_n]()["deep-merge-config"]||!1,b(this,ae,"f")),b(this,ne,"f").configObjects=(b(this,ne,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||b(this,ue,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((s)=>{b(this,ne,"f").config[s]=n||!0}),this}completion(e,t,n){if(V("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(Z(this,Qe,e||b(this,Qe,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(b(this,Qe,"f"),t),n)b(this,ze,"f").registerFunction(n);return this}command(e,t,n,s,o,r){return V("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,s,o,r],arguments.length),b(this,Ce,"f").addHandler(e,t,n,s,o,r),this}commands(e,t,n,s,o,r){return this.command(e,t,n,s,o,r)}commandDir(e,t){V("<string> [object]",[e,t],arguments.length);let n=b(this,yo,"f")||b(this,ae,"f").require;return b(this,Ce,"f").addDirectory(e,n,b(this,ae,"f").getCallerFile(),t),this}count(e){return V("<array|string>",[e],arguments.length),this[Vt]("count",e),this[$n](e),this}default(e,t,n){if(V("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)di(e,b(this,ae,"f")),b(this,ne,"f").defaultDescription[e]=n;if(typeof t==="function"){if(di(e,b(this,ae,"f")),!b(this,ne,"f").defaultDescription[e])b(this,ne,"f").defaultDescription[e]=b(this,ue,"f").functionDescription(t);t=t.call()}return this[qn](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,s){if(V("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,s],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),b(this,ne,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:s},this}demand(e,t,n){if(Array.isArray(t))t.forEach((s)=>{Ue(n,!0,b(this,ae,"f")),this.demandOption(s,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")Ue(n,!0,b(this,ae,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((s)=>{Ue(n,!0,b(this,ae,"f")),this.demandOption(s,n)});else if(typeof n==="string")this.demandOption(e,n);else if(n===!0||typeof n>"u")this.demandOption(e);return this}demandOption(e,t){return V("<object|string|array> [string]",[e,t],arguments.length),this[qn](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return V("<string> [string|boolean]",[e,t],arguments.length),b(this,ne,"f").deprecatedOptions[e]=t,this}describe(e,t){return V("<object|string|array> [string]",[e,t],arguments.length),this[ki](e,!0),b(this,ue,"f").describe(e,t),this}detectLocale(e){return V("<boolean>",[e],arguments.length),Z(this,yn,e,"f"),this}env(e){if(V("[string|boolean]",[e],arguments.length),e===!1)delete b(this,ne,"f").envPrefix;else b(this,ne,"f").envPrefix=e||"";return this}epilogue(e){return V("<string>",[e],arguments.length),b(this,ue,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(V("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else b(this,ue,"f").example(e,t);return this}exit(e,t){if(Z(this,et,!0,"f"),Z(this,Gt,t,"f"),b(this,it,"f"))b(this,ae,"f").process.exit(e)}exitProcess(e=!0){return V("[boolean]",[e],arguments.length),Z(this,it,e,"f"),this}fail(e){if(V("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new $e("Invalid first argument. Expected function or boolean 'false'");return b(this,ue,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(V("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,s)=>{b(this,ze,"f").getCompletion(e,(o,r)=>{if(o)s(o);else n(r)})});else return b(this,ze,"f").getCompletion(e,t)}getDemandedOptions(){return V([],0),b(this,ne,"f").demandedOptions}getDemandedCommands(){return V([],0),b(this,ne,"f").demandedCommands}getDeprecatedOptions(){return V([],0),b(this,ne,"f").deprecatedOptions}getDetectLocale(){return b(this,yn,"f")}getExitProcess(){return b(this,it,"f")}getGroups(){return Object.assign({},b(this,St,"f"),b(this,Dn,"f"))}getHelp(){if(Z(this,et,!0,"f"),!b(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[bs](b(this,Xt,"f"),void 0,void 0,0,!0);if(ke(t))return t.then(()=>b(this,ue,"f").help())}let e=b(this,Ce,"f").runDefaultBuilderOn(this);if(ke(e))return e.then(()=>b(this,ue,"f").help())}return Promise.resolve(b(this,ue,"f").help())}getOptions(){return b(this,ne,"f")}getStrict(){return b(this,kn,"f")}getStrictCommands(){return b(this,xn,"f")}getStrictOptions(){return b(this,Sn,"f")}global(e,t){if(V("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)b(this,ne,"f").local=b(this,ne,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!b(this,ne,"f").local.includes(n))b(this,ne,"f").local.push(n)});return this}group(e,t){V("<string|array> <string>",[e,t],arguments.length);let n=b(this,Dn,"f")[t]||b(this,St,"f")[t];if(b(this,Dn,"f")[t])delete b(this,Dn,"f")[t];let s={};return b(this,St,"f")[t]=(n||[]).concat(e).filter((o)=>{if(s[o])return!1;return s[o]=!0}),this}hide(e){return V("<string>",[e],arguments.length),b(this,ne,"f").hiddenOptions.push(e),this}implies(e,t){return V("<string|object> [number|string|array]",[e,t],arguments.length),b(this,Ee,"f").implies(e,t),this}locale(e){if(V("[string]",[e],arguments.length),e===void 0)return this[mi](),b(this,ae,"f").y18n.getLocale();return Z(this,yn,!1,"f"),b(this,ae,"f").y18n.setLocale(e),this}middleware(e,t,n){return b(this,at,"f").addMiddleware(e,!!t,n)}nargs(e,t){return V("<string|object|array> [number]",[e,t],arguments.length),this[qn](this.nargs.bind(this),"narg",e,t),this}normalize(e){return V("<array|string>",[e],arguments.length),this[Vt]("normalize",e),this}number(e){return V("<array|string>",[e],arguments.length),this[Vt]("number",e),this[$n](e),this}option(e,t){if(V("<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[$n](e),b(this,_t,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[wu](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
79
+ `),void 0,"versionWarning");if(b(this,ne,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let s=t.demand||t.required||t.require;if(s)this.demand(e,s);if(t.demandOption)this.demandOption(e,typeof t.demandOption==="string"?t.demandOption:void 0);if(t.conflicts)this.conflicts(e,t.conflicts);if("default"in t)this.default(e,t.default);if(t.implies!==void 0)this.implies(e,t.implies);if(t.nargs!==void 0)this.nargs(e,t.nargs);if(t.config)this.config(e,t.configParser);if(t.normalize)this.normalize(e);if(t.choices)this.choices(e,t.choices);if(t.coerce)this.coerce(e,t.coerce);if(t.group)this.group(e,t.group);if(t.boolean||t.type==="boolean"){if(this.boolean(e),t.alias)this.boolean(t.alias)}if(t.array||t.type==="array"){if(this.array(e),t.alias)this.array(t.alias)}if(t.number||t.type==="number"){if(this.number(e),t.alias)this.number(t.alias)}if(t.string||t.type==="string"){if(this.string(e),t.alias)this.string(t.alias)}if(t.count||t.type==="count")this.count(e);if(typeof t.global==="boolean")this.global(e,t.global);if(t.defaultDescription)b(this,ne,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let o=t.describe||t.description||t.desc,r=b(this,ue,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(r,e)||typeof o==="string")this.describe(e,o);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(V("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[Du](),typeof e>"u")e=b(this,Xt,"f");if(typeof t==="object")Z(this,wn,t,"f"),t=n;if(typeof t==="function")Z(this,tt,t,"f"),t=!1;if(!t)Z(this,Xt,e,"f");if(b(this,tt,"f"))Z(this,it,!1,"f");let s=this[bs](e,!!t),o=this.parsed;if(b(this,ze,"f").setParsed(this.parsed),ke(s))return s.then((r)=>{if(b(this,tt,"f"))b(this,tt,"f").call(this,b(this,Gt,"f"),r,b(this,ve,"f"));return r}).catch((r)=>{if(b(this,tt,"f"))b(this,tt,"f")(r,this.parsed.argv,b(this,ve,"f"));throw r}).finally(()=>{this[xi](),this.parsed=o});else{if(b(this,tt,"f"))b(this,tt,"f").call(this,b(this,Gt,"f"),s,b(this,ve,"f"));this[xi](),this.parsed=o}return s}parseAsync(e,t,n){let s=this.parse(e,t,n);return!ke(s)?Promise.resolve(s):s}parseSync(e,t,n){let s=this.parse(e,t,n);if(ke(s))throw new $e(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return s}parserConfiguration(e){return V("<object>",[e],arguments.length),Z(this,bo,e,"f"),this}pkgConf(e,t){V("<string> [string]",[e,t],arguments.length);let n=null,s=this[yi](t||b(this,mn,"f"));if(s[e]&&typeof s[e]==="object")n=ms(s[e],t||b(this,mn,"f"),this[_n]()["deep-merge-config"]||!1,b(this,ae,"f")),b(this,ne,"f").configObjects=(b(this,ne,"f").configObjects||[]).concat(n);return this}positional(e,t){V("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=zt(t,(r,i)=>{if(r==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(r)});let s=b(this,ys,"f").fullCommands[b(this,ys,"f").fullCommands.length-1],o=s?b(this,Ce,"f").cmdToParseOptions(s):{array:[],alias:{},default:{},demand:{}};return Jn(o).forEach((r)=>{let i=o[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,b(this,ue,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return V("[boolean]",[e],arguments.length),Z(this,wo,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(V("<array|string|object> [number]",[e],arguments.length),typeof e==="string"&&b(this,ne,"f").narg[e])return this;else this[qn](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return V("[string] [string]",[e,t],arguments.length),e=e||this.$0,b(this,bn,"f").log(b(this,ze,"f").generateCompletionScript(e,t||b(this,Qe,"f")||"completion")),this}showHelp(e){if(V("[string|function]",[e],arguments.length),Z(this,et,!0,"f"),!b(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[bs](b(this,Xt,"f"),void 0,void 0,0,!0);if(ke(n))return n.then(()=>{b(this,ue,"f").showHelp(e)}),this}let t=b(this,Ce,"f").runDefaultBuilderOn(this);if(ke(t))return t.then(()=>{b(this,ue,"f").showHelp(e)}),this}return b(this,ue,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return V("[boolean|string] [string]",[e,t],arguments.length),b(this,ue,"f").showHelpOnFail(e,t),this}showVersion(e){return V("[string|function]",[e],arguments.length),b(this,ue,"f").showVersion(e),this}skipValidation(e){return V("<array|string>",[e],arguments.length),this[Vt]("skipValidation",e),this}strict(e){return V("[boolean]",[e],arguments.length),Z(this,kn,e!==!1,"f"),this}strictCommands(e){return V("[boolean]",[e],arguments.length),Z(this,xn,e!==!1,"f"),this}strictOptions(e){return V("[boolean]",[e],arguments.length),Z(this,Sn,e!==!1,"f"),this}string(e){return V("<array|string>",[e],arguments.length),this[Vt]("string",e),this[$n](e),this}terminalWidth(){return V([],0),b(this,ae,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return V("<object>",[e],arguments.length),Z(this,yn,!1,"f"),b(this,ae,"f").y18n.updateLocale(e),this}usage(e,t,n,s){if(V("<string|null|undefined> [string|boolean] [function|object] [function]",[e,t,n,s],arguments.length),t!==void 0)if(Ue(e,null,b(this,ae,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,s);else throw new $e(".usage() description must start with $0 if being used as alias for .command()");else return b(this,ue,"f").usage(e),this}usageConfiguration(e){return V("<object>",[e],arguments.length),Z(this,Do,e,"f"),this}version(e,t,n){if(V("[boolean|string] [string] [string]",[e,t,n],arguments.length),b(this,_t,"f"))this[gi](b(this,_t,"f")),b(this,ue,"f").version(void 0),Z(this,_t,null,"f");if(arguments.length===0)n=this[Su](),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 Z(this,_t,typeof e==="string"?e:"version","f"),t=t||b(this,ue,"f").deferY18nLookup("Show version number"),b(this,ue,"f").version(n||void 0),this.boolean(b(this,_t,"f")),this.describe(b(this,_t,"f"),t),this}wrap(e){return V("<number|null|undefined>",[e],arguments.length),b(this,ue,"f").wrap(e),this}[(Ce=new WeakMap,mn=new WeakMap,ys=new WeakMap,ze=new WeakMap,Qe=new WeakMap,po=new WeakMap,Gt=new WeakMap,yn=new WeakMap,ho=new WeakMap,it=new WeakMap,go=new WeakMap,at=new WeakMap,St=new WeakMap,et=new WeakMap,ct=new WeakMap,mo=new WeakMap,bn=new WeakMap,ve=new WeakMap,ne=new WeakMap,yo=new WeakMap,bo=new WeakMap,tt=new WeakMap,wn=new WeakMap,Kn=new WeakMap,Dn=new WeakMap,Xt=new WeakMap,wo=new WeakMap,ae=new WeakMap,kn=new WeakMap,xn=new WeakMap,Sn=new WeakMap,ue=new WeakMap,Do=new WeakMap,_t=new WeakMap,Ee=new WeakMap,yu)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[bu](){return{log:(...e)=>{if(!this[ko]())console.log(...e);if(Z(this,et,!0,"f"),b(this,ve,"f").length)Z(this,ve,b(this,ve,"f")+`
80
80
  `,"f");Z(this,ve,b(this,ve,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[ko]())console.error(...e);if(Z(this,et,!0,"f"),b(this,ve,"f").length)Z(this,ve,b(this,ve,"f")+`
81
- `,"f");Z(this,ve,b(this,ve,"f")+e.join(" "),"f")}}}[hi](e){Jn(b(this,ne,"f")).forEach((t)=>{if(((s)=>s==="configObjects")(t))return;let n=b(this,ne,"f")[t];if(Array.isArray(n)){if(n.includes(e))n.splice(n.indexOf(e),1)}else if(typeof n==="object")delete n[e]}),delete b(this,ue,"f").getDescriptions()[e]}[hu](e,t,n){if(!b(this,ho,"f")[n])b(this,ae,"f").process.emitWarning(e,t),b(this,ho,"f")[n]=!0}[gu](){b(this,go,"f").push({options:b(this,ne,"f"),configObjects:b(this,ne,"f").configObjects.slice(0),exitProcess:b(this,it,"f"),groups:b(this,St,"f"),strict:b(this,kn,"f"),strictCommands:b(this,xn,"f"),strictOptions:b(this,Sn,"f"),completionCommand:b(this,Qe,"f"),output:b(this,ve,"f"),exitError:b(this,Yt,"f"),hasOutput:b(this,et,"f"),parsed:this.parsed,parseFn:b(this,tt,"f"),parseContext:b(this,wn,"f")}),b(this,ue,"f").freeze(),b(this,_e,"f").freeze(),b(this,Ce,"f").freeze(),b(this,at,"f").freeze()}[mu](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(b(this,ae,"f").process.argv()[0]))t=b(this,ae,"f").process.argv().slice(1,2);else t=b(this,ae,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let s=this[Fu](b(this,mn,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&s.length<n.length?s:n}).join(" ").trim(),b(this,ae,"f").getEnv("_")&&b(this,ae,"f").getProcessArgvBin()===b(this,ae,"f").getEnv("_"))e=b(this,ae,"f").getEnv("_").replace(`${b(this,ae,"f").path.dirname(b(this,ae,"f").process.execPath())}/`,"");return e}[_n](){return b(this,bo,"f")}[yu](){return b(this,Do,"f")}[gi](){if(!b(this,yn,"f"))return;let e=b(this,ae,"f").getEnv("LC_ALL")||b(this,ae,"f").getEnv("LC_MESSAGES")||b(this,ae,"f").getEnv("LANG")||b(this,ae,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[bu](){return this[mi]().version||"unknown"}[wu](e){let t=e["--"]?e["--"]:e._;for(let n=0,s;(s=t[n])!==void 0;n++)if(b(this,ae,"f").Parser.looksLikeNumber(s)&&Number.isSafeInteger(Math.floor(parseFloat(`${s}`))))t[n]=Number(s);return e}[mi](e){let t=e||"*";if(b(this,Kn,"f")[t])return b(this,Kn,"f")[t];let n={};try{let s=e||b(this,ae,"f").mainFilename;if(b(this,ae,"f").path.extname(s))s=b(this,ae,"f").path.dirname(s);let o=b(this,ae,"f").findUp(s,(r,i)=>{if(i.includes("package.json"))return"package.json";else return});Ue(o,void 0,b(this,ae,"f")),n=JSON.parse(b(this,ae,"f").readFileSync(o,"utf8"))}catch(s){}return b(this,Kn,"f")[t]=n||{},b(this,Kn,"f")[t]}[Xt](e,t){t=[].concat(t),t.forEach((n)=>{n=this[wi](n),b(this,ne,"f")[e].push(n)})}[qn](e,t,n,s){this[bi](e,t,n,s,(o,r,i)=>{b(this,ne,"f")[o][r]=i})}[yi](e,t,n,s){this[bi](e,t,n,s,(o,r,i)=>{b(this,ne,"f")[o][r]=(b(this,ne,"f")[o][r]||[]).concat(i)})}[bi](e,t,n,s,o){if(Array.isArray(n))n.forEach((r)=>{e(r,s)});else if(((r)=>typeof r==="object")(n))for(let r of Jn(n))e(r,n[r]);else o(t,this[wi](n),s)}[wi](e){if(e==="__proto__")return"___proto___";return e}[Di](e,t){return this[qn](this[Di].bind(this),"key",e,t),this}[ki](){var e,t,n,s,o,r,i,l,u,c,a,d;let f=b(this,go,"f").pop();Ue(f,void 0,b(this,ae,"f"));let p;e=this,t=this,n=this,s=this,o=this,r=this,i=this,l=this,u=this,c=this,a=this,d=this,{options:{set value(g){Z(e,ne,g,"f")}}.value,configObjects:p,exitProcess:{set value(g){Z(t,it,g,"f")}}.value,groups:{set value(g){Z(n,St,g,"f")}}.value,output:{set value(g){Z(s,ve,g,"f")}}.value,exitError:{set value(g){Z(o,Yt,g,"f")}}.value,hasOutput:{set value(g){Z(r,et,g,"f")}}.value,parsed:this.parsed,strict:{set value(g){Z(i,kn,g,"f")}}.value,strictCommands:{set value(g){Z(l,xn,g,"f")}}.value,strictOptions:{set value(g){Z(u,Sn,g,"f")}}.value,completionCommand:{set value(g){Z(c,Qe,g,"f")}}.value,parseFn:{set value(g){Z(a,tt,g,"f")}}.value,parseContext:{set value(g){Z(d,wn,g,"f")}}.value}=f,b(this,ne,"f").configObjects=p,b(this,ue,"f").unfreeze(),b(this,_e,"f").unfreeze(),b(this,Ce,"f").unfreeze(),b(this,at,"f").unfreeze()}[Du](e,t){return gn(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[ku].bind(this),getContext:this[xu].bind(this),getHasOutput:this[Su].bind(this),getLoggerInstance:this[_u].bind(this),getParseContext:this[Eu].bind(this),getParserConfiguration:this[_n].bind(this),getUsageConfiguration:this[yu].bind(this),getUsageInstance:this[$u].bind(this),getValidationInstance:this[Cu].bind(this),hasParseCallback:this[ko].bind(this),isGlobalContext:this[Au].bind(this),postProcess:this[En].bind(this),reset:this[xi].bind(this),runValidation:this[Si].bind(this),runYargsParserAndExecuteCommands:this[bs].bind(this),setHasOutput:this[Tu].bind(this)}}[ku](){return b(this,Ce,"f")}[xu](){return b(this,ys,"f")}[Su](){return b(this,et,"f")}[_u](){return b(this,bn,"f")}[Eu](){return b(this,wn,"f")||{}}[$u](){return b(this,ue,"f")}[Cu](){return b(this,_e,"f")}[ko](){return!!b(this,tt,"f")}[Au](){return b(this,mo,"f")}[En](e,t,n,s){if(n)return e;if(De(e))return e;if(!t)e=this[fu](e);if(this[_n]()["parse-positional-numbers"]||this[_n]()["parse-positional-numbers"]===void 0)e=this[wu](e);if(s)e=hn(e,this,b(this,at,"f").getMiddleware(),!1);return e}[xi](e={}){Z(this,ne,b(this,ne,"f")||{},"f");let t={};t.local=b(this,ne,"f").local||[],t.configObjects=b(this,ne,"f").configObjects||[];let n={};t.local.forEach((r)=>{n[r]=!0,(e[r]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(b(this,Dn,"f"),Object.keys(b(this,St,"f")).reduce((r,i)=>{let l=b(this,St,"f")[i].filter((u)=>!(u in n));if(l.length>0)r[i]=l;return r},{})),Z(this,St,{},"f");let s=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],o=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(s.forEach((r)=>{t[r]=(b(this,ne,"f")[r]||[]).filter((i)=>!n[i])}),o.forEach((r)=>{t[r]=Ht(b(this,ne,"f")[r],(i)=>!n[i])}),t.envPrefix=b(this,ne,"f").envPrefix,Z(this,ne,t,"f"),Z(this,ue,b(this,ue,"f")?b(this,ue,"f").reset(n):su(this,b(this,ae,"f")),"f"),Z(this,_e,b(this,_e,"f")?b(this,_e,"f").reset(n):uu(this,b(this,ue,"f"),b(this,ae,"f")),"f"),Z(this,Ce,b(this,Ce,"f")?b(this,Ce,"f").reset():eu(b(this,ue,"f"),b(this,_e,"f"),b(this,at,"f"),b(this,ae,"f")),"f"),!b(this,ze,"f"))Z(this,ze,au(this,b(this,ue,"f"),b(this,Ce,"f"),b(this,ae,"f")),"f");return b(this,at,"f").reset(),Z(this,Qe,null,"f"),Z(this,ve,"","f"),Z(this,Yt,null,"f"),Z(this,et,!1,"f"),this.parsed=!1,this}[Fu](e,t){return b(this,ae,"f").path.relative(e,t)}[bs](e,t,n,s=0,o=!1){var r,i,l,u;let c=!!n||o;e=e||b(this,Gt,"f"),b(this,ne,"f").__=b(this,ae,"f").y18n.__,b(this,ne,"f").configuration=this[_n]();let a=!!b(this,ne,"f").configuration["populate--"],d=Object.assign({},b(this,ne,"f").configuration,{"populate--":!0}),f=b(this,ae,"f").Parser.detailed(e,Object.assign({},b(this,ne,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),p=Object.assign(f.argv,b(this,wn,"f")),g=void 0,h=f.aliases,m=!1,y=!1;if(Object.keys(p).forEach((w)=>{if(w===b(this,ct,"f")&&p[w])m=!0;else if(w===b(this,_t,"f")&&p[w])y=!0}),p.$0=this.$0,this.parsed=f,s===0)b(this,ue,"f").clearCachedHelpMessage();try{if(this[gi](),t)return this[En](p,a,!!n,!1);if(b(this,ct,"f")){if([b(this,ct,"f")].concat(h[b(this,ct,"f")]||[]).filter((C)=>C.length>1).includes(""+p._[p._.length-1]))p._.pop(),m=!0}Z(this,mo,!1,"f");let w=b(this,Ce,"f").getCommands(),x=((r=b(this,ze,"f"))===null||r===void 0?void 0:r.completionKey)?[(i=b(this,ze,"f"))===null||i===void 0?void 0:i.completionKey,...(u=this.getAliases()[(l=b(this,ze,"f"))===null||l===void 0?void 0:l.completionKey])!==null&&u!==void 0?u:[]].some((E)=>Object.prototype.hasOwnProperty.call(p,E)):!1,D=m||x||o;if(p._.length){if(w.length){let E;for(let C=s||0,S;p._[C]!==void 0;C++)if(S=String(p._[C]),w.includes(S)&&S!==b(this,Qe,"f")){let k=b(this,Ce,"f").runCommand(S,this,f,C+1,o,m||y||o);return this[En](k,a,!!n,!1)}else if(!E&&S!==b(this,Qe,"f")){E=S;break}if(!b(this,Ce,"f").hasDefaultCommand()&&b(this,wo,"f")&&E&&!D)b(this,_e,"f").recommendCommands(E,w)}if(b(this,Qe,"f")&&p._.includes(b(this,Qe,"f"))&&!x){if(b(this,it,"f"))zt(!0);this.showCompletionScript(),this.exit(0)}}if(b(this,Ce,"f").hasDefaultCommand()&&!D){let E=b(this,Ce,"f").runCommand(null,this,f,0,o,m||y||o);return this[En](E,a,!!n,!1)}if(x){if(b(this,it,"f"))zt(!0);e=[].concat(e);let E=e.slice(e.indexOf(`--${b(this,ze,"f").completionKey}`)+1);return b(this,ze,"f").getCompletion(E,(C,S)=>{if(C)throw new $e(C.message);(S||[]).forEach((k)=>{b(this,bn,"f").log(k)}),this.exit(0)}),this[En](p,!a,!!n,!1)}if(!b(this,et,"f")){if(m){if(b(this,it,"f"))zt(!0);c=!0,this.showHelp((E)=>{b(this,bn,"f").log(E),this.exit(0)})}else if(y){if(b(this,it,"f"))zt(!0);c=!0,b(this,ue,"f").showVersion("log"),this.exit(0)}}if(!c&&b(this,ne,"f").skipValidation.length>0)c=Object.keys(p).some((E)=>b(this,ne,"f").skipValidation.indexOf(E)>=0&&p[E]===!0);if(!c){if(f.error)throw new $e(f.error.message);if(!x){let E=this[Si](h,{},f.error);if(!n)g=hn(p,this,b(this,at,"f").getMiddleware(),!0);if(g=this[Du](E,g!==null&&g!==void 0?g:p),De(g)&&!n)g=g.then(()=>hn(p,this,b(this,at,"f").getMiddleware(),!1))}}}catch(w){if(w instanceof $e)b(this,ue,"f").fail(w.message,w);else throw w}return this[En](g!==null&&g!==void 0?g:p,a,!!n,!0)}[Si](e,t,n,s){let o={...this.getDemandedOptions()};return(r)=>{if(n)throw new $e(n.message);b(this,_e,"f").nonOptionCount(r),b(this,_e,"f").requiredArguments(r,o);let i=!1;if(b(this,xn,"f"))i=b(this,_e,"f").unknownCommands(r);if(b(this,kn,"f")&&!i)b(this,_e,"f").unknownArguments(r,e,t,!!s);else if(b(this,Sn,"f"))b(this,_e,"f").unknownArguments(r,e,{},!1,!1);b(this,_e,"f").limitedChoices(r),b(this,_e,"f").implications(r),b(this,_e,"f").conflicting(r)}}[Tu](){Z(this,et,!0,"f")}[$n](e){if(typeof e==="string")b(this,ne,"f").key[e]=!0;else for(let t of e)b(this,ne,"f").key[t]=!0}}function tu(e){return!!e&&typeof e.getInternalMethods==="function"}var my=Ou(li),Iu=my;var yy=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,by=/[\t\n\v\f\r (*_~]/;function wy(e){let t=e.split(""),n=(o,r)=>{for(let i=o;i<r;i++)if(t[i]!==`
81
+ `,"f");Z(this,ve,b(this,ve,"f")+e.join(" "),"f")}}}[gi](e){Jn(b(this,ne,"f")).forEach((t)=>{if(((s)=>s==="configObjects")(t))return;let n=b(this,ne,"f")[t];if(Array.isArray(n)){if(n.includes(e))n.splice(n.indexOf(e),1)}else if(typeof n==="object")delete n[e]}),delete b(this,ue,"f").getDescriptions()[e]}[wu](e,t,n){if(!b(this,ho,"f")[n])b(this,ae,"f").process.emitWarning(e,t),b(this,ho,"f")[n]=!0}[Du](){b(this,go,"f").push({options:b(this,ne,"f"),configObjects:b(this,ne,"f").configObjects.slice(0),exitProcess:b(this,it,"f"),groups:b(this,St,"f"),strict:b(this,kn,"f"),strictCommands:b(this,xn,"f"),strictOptions:b(this,Sn,"f"),completionCommand:b(this,Qe,"f"),output:b(this,ve,"f"),exitError:b(this,Gt,"f"),hasOutput:b(this,et,"f"),parsed:this.parsed,parseFn:b(this,tt,"f"),parseContext:b(this,wn,"f")}),b(this,ue,"f").freeze(),b(this,Ee,"f").freeze(),b(this,Ce,"f").freeze(),b(this,at,"f").freeze()}[ku](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(b(this,ae,"f").process.argv()[0]))t=b(this,ae,"f").process.argv().slice(1,2);else t=b(this,ae,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let s=this[vu](b(this,mn,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&s.length<n.length?s:n}).join(" ").trim(),b(this,ae,"f").getEnv("_")&&b(this,ae,"f").getProcessArgvBin()===b(this,ae,"f").getEnv("_"))e=b(this,ae,"f").getEnv("_").replace(`${b(this,ae,"f").path.dirname(b(this,ae,"f").process.execPath())}/`,"");return e}[_n](){return b(this,bo,"f")}[xu](){return b(this,Do,"f")}[mi](){if(!b(this,yn,"f"))return;let e=b(this,ae,"f").getEnv("LC_ALL")||b(this,ae,"f").getEnv("LC_MESSAGES")||b(this,ae,"f").getEnv("LANG")||b(this,ae,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[Su](){return this[yi]().version||"unknown"}[_u](e){let t=e["--"]?e["--"]:e._;for(let n=0,s;(s=t[n])!==void 0;n++)if(b(this,ae,"f").Parser.looksLikeNumber(s)&&Number.isSafeInteger(Math.floor(parseFloat(`${s}`))))t[n]=Number(s);return e}[yi](e){let t=e||"*";if(b(this,Kn,"f")[t])return b(this,Kn,"f")[t];let n={};try{let s=e||b(this,ae,"f").mainFilename;if(b(this,ae,"f").path.extname(s))s=b(this,ae,"f").path.dirname(s);let o=b(this,ae,"f").findUp(s,(r,i)=>{if(i.includes("package.json"))return"package.json";else return});Ue(o,void 0,b(this,ae,"f")),n=JSON.parse(b(this,ae,"f").readFileSync(o,"utf8"))}catch(s){}return b(this,Kn,"f")[t]=n||{},b(this,Kn,"f")[t]}[Vt](e,t){t=[].concat(t),t.forEach((n)=>{n=this[Di](n),b(this,ne,"f")[e].push(n)})}[qn](e,t,n,s){this[wi](e,t,n,s,(o,r,i)=>{b(this,ne,"f")[o][r]=i})}[bi](e,t,n,s){this[wi](e,t,n,s,(o,r,i)=>{b(this,ne,"f")[o][r]=(b(this,ne,"f")[o][r]||[]).concat(i)})}[wi](e,t,n,s,o){if(Array.isArray(n))n.forEach((r)=>{e(r,s)});else if(((r)=>typeof r==="object")(n))for(let r of Jn(n))e(r,n[r]);else o(t,this[Di](n),s)}[Di](e){if(e==="__proto__")return"___proto___";return e}[ki](e,t){return this[qn](this[ki].bind(this),"key",e,t),this}[xi](){var e,t,n,s,o,r,i,l,u,c,a,d;let f=b(this,go,"f").pop();Ue(f,void 0,b(this,ae,"f"));let p;e=this,t=this,n=this,s=this,o=this,r=this,i=this,l=this,u=this,c=this,a=this,d=this,{options:{set value(g){Z(e,ne,g,"f")}}.value,configObjects:p,exitProcess:{set value(g){Z(t,it,g,"f")}}.value,groups:{set value(g){Z(n,St,g,"f")}}.value,output:{set value(g){Z(s,ve,g,"f")}}.value,exitError:{set value(g){Z(o,Gt,g,"f")}}.value,hasOutput:{set value(g){Z(r,et,g,"f")}}.value,parsed:this.parsed,strict:{set value(g){Z(i,kn,g,"f")}}.value,strictCommands:{set value(g){Z(l,xn,g,"f")}}.value,strictOptions:{set value(g){Z(u,Sn,g,"f")}}.value,completionCommand:{set value(g){Z(c,Qe,g,"f")}}.value,parseFn:{set value(g){Z(a,tt,g,"f")}}.value,parseContext:{set value(g){Z(d,wn,g,"f")}}.value}=f,b(this,ne,"f").configObjects=p,b(this,ue,"f").unfreeze(),b(this,Ee,"f").unfreeze(),b(this,Ce,"f").unfreeze(),b(this,at,"f").unfreeze()}[Eu](e,t){return gn(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[$u].bind(this),getContext:this[Cu].bind(this),getHasOutput:this[Au].bind(this),getLoggerInstance:this[Fu].bind(this),getParseContext:this[Tu].bind(this),getParserConfiguration:this[_n].bind(this),getUsageConfiguration:this[xu].bind(this),getUsageInstance:this[Ou].bind(this),getValidationInstance:this[Ru].bind(this),hasParseCallback:this[ko].bind(this),isGlobalContext:this[Iu].bind(this),postProcess:this[En].bind(this),reset:this[Si].bind(this),runValidation:this[_i].bind(this),runYargsParserAndExecuteCommands:this[bs].bind(this),setHasOutput:this[Pu].bind(this)}}[$u](){return b(this,Ce,"f")}[Cu](){return b(this,ys,"f")}[Au](){return b(this,et,"f")}[Fu](){return b(this,bn,"f")}[Tu](){return b(this,wn,"f")||{}}[Ou](){return b(this,ue,"f")}[Ru](){return b(this,Ee,"f")}[ko](){return!!b(this,tt,"f")}[Iu](){return b(this,mo,"f")}[En](e,t,n,s){if(n)return e;if(ke(e))return e;if(!t)e=this[yu](e);if(this[_n]()["parse-positional-numbers"]||this[_n]()["parse-positional-numbers"]===void 0)e=this[_u](e);if(s)e=hn(e,this,b(this,at,"f").getMiddleware(),!1);return e}[Si](e={}){Z(this,ne,b(this,ne,"f")||{},"f");let t={};t.local=b(this,ne,"f").local||[],t.configObjects=b(this,ne,"f").configObjects||[];let n={};t.local.forEach((r)=>{n[r]=!0,(e[r]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(b(this,Dn,"f"),Object.keys(b(this,St,"f")).reduce((r,i)=>{let l=b(this,St,"f")[i].filter((u)=>!(u in n));if(l.length>0)r[i]=l;return r},{})),Z(this,St,{},"f");let s=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],o=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(s.forEach((r)=>{t[r]=(b(this,ne,"f")[r]||[]).filter((i)=>!n[i])}),o.forEach((r)=>{t[r]=zt(b(this,ne,"f")[r],(i)=>!n[i])}),t.envPrefix=b(this,ne,"f").envPrefix,Z(this,ne,t,"f"),Z(this,ue,b(this,ue,"f")?b(this,ue,"f").reset(n):cu(this,b(this,ae,"f")),"f"),Z(this,Ee,b(this,Ee,"f")?b(this,Ee,"f").reset(n):gu(this,b(this,ue,"f"),b(this,ae,"f")),"f"),Z(this,Ce,b(this,Ce,"f")?b(this,Ce,"f").reset():ru(b(this,ue,"f"),b(this,Ee,"f"),b(this,at,"f"),b(this,ae,"f")),"f"),!b(this,ze,"f"))Z(this,ze,fu(this,b(this,ue,"f"),b(this,Ce,"f"),b(this,ae,"f")),"f");return b(this,at,"f").reset(),Z(this,Qe,null,"f"),Z(this,ve,"","f"),Z(this,Gt,null,"f"),Z(this,et,!1,"f"),this.parsed=!1,this}[vu](e,t){return b(this,ae,"f").path.relative(e,t)}[bs](e,t,n,s=0,o=!1){var r,i,l,u;let c=!!n||o;e=e||b(this,Xt,"f"),b(this,ne,"f").__=b(this,ae,"f").y18n.__,b(this,ne,"f").configuration=this[_n]();let a=!!b(this,ne,"f").configuration["populate--"],d=Object.assign({},b(this,ne,"f").configuration,{"populate--":!0}),f=b(this,ae,"f").Parser.detailed(e,Object.assign({},b(this,ne,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),p=Object.assign(f.argv,b(this,wn,"f")),g=void 0,h=f.aliases,m=!1,y=!1;if(Object.keys(p).forEach((w)=>{if(w===b(this,ct,"f")&&p[w])m=!0;else if(w===b(this,_t,"f")&&p[w])y=!0}),p.$0=this.$0,this.parsed=f,s===0)b(this,ue,"f").clearCachedHelpMessage();try{if(this[mi](),t)return this[En](p,a,!!n,!1);if(b(this,ct,"f")){if([b(this,ct,"f")].concat(h[b(this,ct,"f")]||[]).filter((C)=>C.length>1).includes(""+p._[p._.length-1]))p._.pop(),m=!0}Z(this,mo,!1,"f");let w=b(this,Ce,"f").getCommands(),x=((r=b(this,ze,"f"))===null||r===void 0?void 0:r.completionKey)?[(i=b(this,ze,"f"))===null||i===void 0?void 0:i.completionKey,...(u=this.getAliases()[(l=b(this,ze,"f"))===null||l===void 0?void 0:l.completionKey])!==null&&u!==void 0?u:[]].some((E)=>Object.prototype.hasOwnProperty.call(p,E)):!1,D=m||x||o;if(p._.length){if(w.length){let E;for(let C=s||0,S;p._[C]!==void 0;C++)if(S=String(p._[C]),w.includes(S)&&S!==b(this,Qe,"f")){let k=b(this,Ce,"f").runCommand(S,this,f,C+1,o,m||y||o);return this[En](k,a,!!n,!1)}else if(!E&&S!==b(this,Qe,"f")){E=S;break}if(!b(this,Ce,"f").hasDefaultCommand()&&b(this,wo,"f")&&E&&!D)b(this,Ee,"f").recommendCommands(E,w)}if(b(this,Qe,"f")&&p._.includes(b(this,Qe,"f"))&&!x){if(b(this,it,"f"))Yt(!0);this.showCompletionScript(),this.exit(0)}}if(b(this,Ce,"f").hasDefaultCommand()&&!D){let E=b(this,Ce,"f").runCommand(null,this,f,0,o,m||y||o);return this[En](E,a,!!n,!1)}if(x){if(b(this,it,"f"))Yt(!0);e=[].concat(e);let E=e.slice(e.indexOf(`--${b(this,ze,"f").completionKey}`)+1);return b(this,ze,"f").getCompletion(E,(C,S)=>{if(C)throw new $e(C.message);(S||[]).forEach((k)=>{b(this,bn,"f").log(k)}),this.exit(0)}),this[En](p,!a,!!n,!1)}if(!b(this,et,"f")){if(m){if(b(this,it,"f"))Yt(!0);c=!0,this.showHelp((E)=>{b(this,bn,"f").log(E),this.exit(0)})}else if(y){if(b(this,it,"f"))Yt(!0);c=!0,b(this,ue,"f").showVersion("log"),this.exit(0)}}if(!c&&b(this,ne,"f").skipValidation.length>0)c=Object.keys(p).some((E)=>b(this,ne,"f").skipValidation.indexOf(E)>=0&&p[E]===!0);if(!c){if(f.error)throw new $e(f.error.message);if(!x){let E=this[_i](h,{},f.error);if(!n)g=hn(p,this,b(this,at,"f").getMiddleware(),!0);if(g=this[Eu](E,g!==null&&g!==void 0?g:p),ke(g)&&!n)g=g.then(()=>hn(p,this,b(this,at,"f").getMiddleware(),!1))}}}catch(w){if(w instanceof $e)b(this,ue,"f").fail(w.message,w);else throw w}return this[En](g!==null&&g!==void 0?g:p,a,!!n,!0)}[_i](e,t,n,s){let o={...this.getDemandedOptions()};return(r)=>{if(n)throw new $e(n.message);b(this,Ee,"f").nonOptionCount(r),b(this,Ee,"f").requiredArguments(r,o);let i=!1;if(b(this,xn,"f"))i=b(this,Ee,"f").unknownCommands(r);if(b(this,kn,"f")&&!i)b(this,Ee,"f").unknownArguments(r,e,t,!!s);else if(b(this,Sn,"f"))b(this,Ee,"f").unknownArguments(r,e,{},!1,!1);b(this,Ee,"f").limitedChoices(r),b(this,Ee,"f").implications(r),b(this,Ee,"f").conflicting(r)}}[Pu](){Z(this,et,!0,"f")}[$n](e){if(typeof e==="string")b(this,ne,"f").key[e]=!0;else for(let t of e)b(this,ne,"f").key[t]=!0}}function iu(e){return!!e&&typeof e.getInternalMethods==="function"}var wy=Lu(ui),Mu=wy;var Dy=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,ky=/[\t\n\v\f\r (*_~]/;function xy(e){let t=e.split(""),n=(o,r)=>{for(let i=o;i<r;i++)if(t[i]!==`
82
82
  `)t[i]="\x00"},s=0;while(s<e.length){let r=s===0||e[s-1]===`
83
83
  `?/^ {0,3}(?:(`{3,})[^`\n]*|(~{3,})[^\n]*)(?=\n|$)/.exec(e.slice(s)):null;if(r){let l=r[1]??r[2],u=new RegExp(`
84
84
  {0,3}${l[0]==="`"?"`":"~"}{${l.length},}[ ]*\r?(?=
85
85
  |$)`,"g");u.lastIndex=s+r[0].length;let c=u.exec(e),a=c?c.index+c[0].length:e.length;n(s,a),s=a;continue}let i=e[s];if(i==="\\"){s+=2;continue}if(i==="`"){let l=0;while(e[s+l]==="`")l++;let u=s+l,c=-1;while(u<e.length){if(e[u]===`
86
- `&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(u)))break;if(e[u]!=="`"){u++;continue}let a=0;while(e[u+a]==="`")a++;if(a===l){c=u+a;break}u+=a}if(c<0){s+=l;continue}n(s,c),s=c;continue}if(i==="["){let l=/^\[(?:\\.|[^\]\\\n])*\]\([^()\s]*\)/.exec(e.slice(s));if(l){n(s,s+l[0].length),s+=l[0].length;continue}}s++}return t.join("")}function Dy(e,{markdown:t=!0}={}){let n=t?wy(e):e,s=[];for(let o of n.matchAll(yy)){let r=o[0];if(r.startsWith("<"))continue;let i=o.index??0,l=i>0?n[i-1]:"";if(l&&!by.test(l))s.push({url:r,side:"before",char:e[i-1]});let u=r.match(/[^\x00-\x7f]|>/);if(u)s.push({url:r,side:"after",char:u[0]})}return s}function Ke(e,t=!1,n=console.error,{sides:s=["before","after"],markdown:o=!0}={}){let r=Dy(e,{markdown:o}).filter((c)=>s.includes(c.side));if(!r.length)return;let i=r.map((c)=>c.side==="before"?`${JSON.stringify(c.url)} (glued to ${JSON.stringify(c.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(c.url)} (runs into ${JSON.stringify(c.char)} after it)`),l=r.some((c)=>c.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",u=`Ambiguous URL boundary: ${i.join(", ")}. ${l}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(u);n(`Warning: ${u}`)}import{existsSync as Ds,readFileSync as $i,writeFileSync as _i,mkdirSync as Nu,chmodSync as vu}from"node:fs";import{homedir as ky}from"node:os";import{join as Cn,dirname as Ci}from"node:path";function Ai(){return process.env.HOME||ky()}function Mu(){return Cn(Ai(),".config","slack-cli","profiles.json")}function xo(){return Cn(process.cwd(),".slack-cli","workspace")}function So(){return Cn(Ai(),".slack-cli","workspace")}function ks(){let e=Mu();if(!Ds(e))return{profiles:{}};return JSON.parse($i(e,"utf8"))}function xy(e){let t=Mu();if(Nu(Ci(t),{recursive:!0}),process.platform!=="win32"&&Ds(t))vu(t,384);if(_i(t,JSON.stringify(e,null,2)+`
87
- `,{mode:384}),process.platform!=="win32")vu(t,384)}function Hn(e){if(!Ds(e))return;return $i(e,"utf8").trim()||void 0}function Pu(e,t){let n=Ci(e);Nu(n,{recursive:!0});let s=Cn(n,".gitignore");if(!Ds(s))_i(s,`*
88
- `);_i(e,t+`
89
- `)}function Sy(e){let t={};for(let n of e.split(`
90
- `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),i=s.slice(o+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function Lu(e){if(!Ds(e))return{};try{return Sy($i(e,"utf8"))}catch{return{}}}function Ei(e,t){let n=Ai(),s=e;while(!0){for(let i of[Cn(s,".slack-term",".env.local"),Cn(s,".env.local")]){let l=Lu(i);for(let u of t)if(l[u])return l[u]}if(s===n)break;let r=Ci(s);if(r===s)break;s=r}let o=Lu(Cn(n,".slack-term",".env.local"));for(let r of t)if(o[r])return o[r];return}function Fi(){let e=ks(),t=Hn(xo()),n=Hn(So()),s=t??n;return Object.entries(e.profiles).map(([o,r])=>{let i=ws(e,o);return{name:o,profile:{...r,...i?{cookie:i}:{}},current:o===s}})}function ws(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 Bu(e){let t=ks();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],xy(t)}function ju(e,t=!1){let n=ks();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)Pu(So(),e);else Pu(xo(),e)}function xs(e){let n=ks().profiles,s=Object.keys(n);if(e){let a=n[e];if(!a)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let o=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(o&&s.length===0)return o;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((a)=>a&&!a.startsWith("xoxb-"));if(r&&s.length>0){let a=Ei(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==a){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
91
- `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=Ei(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let l=process.env.SLACK_WORKSPACE;if(l){let a=n[l];if(!a)throw Error(`Workspace "${l}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}let u=Hn(xo());if(u){let a=n[u];if(!a)throw Error(`Workspace "${u}" (from .slack-cli/workspace) not found in profiles.`);return a.token}let c=Hn(So());if(c){let a=n[c];if(!a)throw Error(`Workspace "${c}" (from ~/.slack-cli/workspace) not found in profiles.`);return a.token}if(s.length>0)throw Error(`Workspace not selected (${s.join(", ")} available).
86
+ `&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(u)))break;if(e[u]!=="`"){u++;continue}let a=0;while(e[u+a]==="`")a++;if(a===l){c=u+a;break}u+=a}if(c<0){s+=l;continue}n(s,c),s=c;continue}if(i==="["){let l=/^\[(?:\\.|[^\]\\\n])*\]\([^()\s]*\)/.exec(e.slice(s));if(l){n(s,s+l[0].length),s+=l[0].length;continue}}s++}return t.join("")}function Sy(e,{markdown:t=!0}={}){let n=t?xy(e):e,s=[];for(let o of n.matchAll(Dy)){let r=o[0];if(r.startsWith("<"))continue;let i=o.index??0,l=i>0?n[i-1]:"";if(l&&!ky.test(l))s.push({url:r,side:"before",char:e[i-1]});let u=r.match(/[^\x00-\x7f]|>/);if(u)s.push({url:r,side:"after",char:u[0]})}return s}function Ke(e,t=!1,n=console.error,{sides:s=["before","after"],markdown:o=!0}={}){let r=Sy(e,{markdown:o}).filter((c)=>s.includes(c.side));if(!r.length)return;let i=r.map((c)=>c.side==="before"?`${JSON.stringify(c.url)} (glued to ${JSON.stringify(c.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(c.url)} (runs into ${JSON.stringify(c.char)} after it)`),l=r.some((c)=>c.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",u=`Ambiguous URL boundary: ${i.join(", ")}. ${l}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(u);n(`Warning: ${u}`)}import{existsSync as Ds,readFileSync as Ci,writeFileSync as Ei,mkdirSync as Ju,chmodSync as Bu}from"node:fs";import{homedir as _y}from"node:os";import{join as Cn,dirname as Ai}from"node:path";function Fi(){return process.env.HOME||_y()}function Uu(){return Cn(Fi(),".config","slack-cli","profiles.json")}function xo(){return Cn(process.cwd(),".slack-cli","workspace")}function So(){return Cn(Fi(),".slack-cli","workspace")}function ks(){let e=Uu();if(!Ds(e))return{profiles:{}};return JSON.parse(Ci(e,"utf8"))}function Ey(e){let t=Uu();if(Ju(Ai(t),{recursive:!0}),process.platform!=="win32"&&Ds(t))Bu(t,384);if(Ei(t,JSON.stringify(e,null,2)+`
87
+ `,{mode:384}),process.platform!=="win32")Bu(t,384)}function Hn(e){if(!Ds(e))return;return Ci(e,"utf8").trim()||void 0}function ju(e,t){let n=Ai(e);Ju(n,{recursive:!0});let s=Cn(n,".gitignore");if(!Ds(s))Ei(s,`*
88
+ `);Ei(e,t+`
89
+ `)}function $y(e){let t={};for(let n of e.split(`
90
+ `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),i=s.slice(o+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function Wu(e){if(!Ds(e))return{};try{return $y(Ci(e,"utf8"))}catch{return{}}}function $i(e,t){let n=Fi(),s=e;while(!0){for(let i of[Cn(s,".slack-term",".env.local"),Cn(s,".env.local")]){let l=Wu(i);for(let u of t)if(l[u])return l[u]}if(s===n)break;let r=Ai(s);if(r===s)break;s=r}let o=Wu(Cn(n,".slack-term",".env.local"));for(let r of t)if(o[r])return o[r];return}function Ti(){let e=ks(),t=Hn(xo()),n=Hn(So()),s=t??n;return Object.entries(e.profiles).map(([o,r])=>{let i=ws(e,o);return{name:o,profile:{...r,...i?{cookie:i}:{}},current:o===s}})}function ws(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 Ku(e){let t=ks();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],Ey(t)}function qu(e,t=!1){let n=ks();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)ju(So(),e);else ju(xo(),e)}function xs(e){let n=ks().profiles,s=Object.keys(n);if(e){let a=n[e];if(!a)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let o=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(o&&s.length===0)return o;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((a)=>a&&!a.startsWith("xoxb-"));if(r&&s.length>0){let a=$i(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==a){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
91
+ `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=$i(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let l=process.env.SLACK_WORKSPACE;if(l){let a=n[l];if(!a)throw Error(`Workspace "${l}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}let u=Hn(xo());if(u){let a=n[u];if(!a)throw Error(`Workspace "${u}" (from .slack-cli/workspace) not found in profiles.`);return a.token}let c=Hn(So());if(c){let a=n[c];if(!a)throw Error(`Workspace "${c}" (from ~/.slack-cli/workspace) not found in profiles.`);return a.token}if(s.length>0)throw Error(`Workspace not selected (${s.join(", ")} available).
92
92
  Select locally: slack auth use <name> (writes .slack-cli/workspace)
93
93
  Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
94
94
  Run one of:
@@ -97,13 +97,13 @@ ${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 Ne(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Ti(e){let t=ks(),n=t.profiles;if(e)return ws(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 o=Ei(process.cwd(),["SLACK_COOKIE"]);if(o)return o;let r=process.env.SLACK_WORKSPACE;if(r)return ws(t,r);let i=Hn(xo());if(i)return ws(t,i);let l=Hn(So());if(l)return ws(t,l);return}import{existsSync as Yn,readFileSync as Eo,writeFileSync as Ju,mkdirSync as Uu,chmodSync as _o}from"node:fs";import{homedir as _y}from"node:os";import{join as zn,dirname as Ri}from"node:path";function Ii(){return process.env.HOME||_y()}function Ku(){return zn(Ii(),".config","slack-cli","profiles.json")}function vi(){return zn(process.cwd(),".slack-cli","workspace")}function Pi(){return zn(Ii(),".slack-cli","workspace")}function Xn(){let e=Ku();if(!Yn(e))return{profiles:{}};return JSON.parse(Eo(e,"utf8"))}function Li(e){let t=Ku();if(Uu(Ri(t),{recursive:!0}),process.platform!=="win32"&&Yn(t))_o(t,384);if(Ju(t,JSON.stringify(e,null,2)+`
101
- `,{mode:384}),process.platform!=="win32")_o(t,384)}function Gn(e){if(!Yn(e))return;return Eo(e,"utf8").trim()||void 0}function Ey(e){let t={};for(let n of e.split(`
102
- `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),i=s.slice(o+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function Wu(e){if(!Yn(e))return{};try{return Ey(Eo(e,"utf8"))}catch{return{}}}function Oi(e,t){let n=Ii(),s=e;while(!0){for(let i of[zn(s,".slack-term",".env.local"),zn(s,".env.local")]){let l=Wu(i);for(let u of t)if(l[u])return l[u]}if(s===n)break;let r=Ri(s);if(r===s)break;s=r}let o=Wu(zn(n,".slack-term",".env.local"));for(let r of t)if(o[r])return o[r];return}function Ni(e,t){Uu(Ri(e),{recursive:!0});let n=Yn(e)?Eo(e,"utf8"):"",s=n?n.split(`
103
- `):[];for(let[o,r]of Object.entries(t)){let i=s.findIndex((u)=>{let c=u.trim();return c.startsWith(o+"=")||c.startsWith(o+" =")}),l=`${o}=${r}`;if(i!==-1)s[i]=l;else s.push(l)}if(process.platform!=="win32"&&Yn(e))_o(e,384);if(Ju(e,s.join(`
100
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function Le(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Oi(e){let t=ks(),n=t.profiles;if(e)return ws(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 o=$i(process.cwd(),["SLACK_COOKIE"]);if(o)return o;let r=process.env.SLACK_WORKSPACE;if(r)return ws(t,r);let i=Hn(xo());if(i)return ws(t,i);let l=Hn(So());if(l)return ws(t,l);return}import{existsSync as Yn,readFileSync as Eo,writeFileSync as zu,mkdirSync as Yu,chmodSync as _o}from"node:fs";import{homedir as Cy}from"node:os";import{join as zn,dirname as Ii}from"node:path";function vi(){return process.env.HOME||Cy()}function Gu(){return zn(vi(),".config","slack-cli","profiles.json")}function Pi(){return zn(process.cwd(),".slack-cli","workspace")}function Li(){return zn(vi(),".slack-cli","workspace")}function Xn(){let e=Gu();if(!Yn(e))return{profiles:{}};return JSON.parse(Eo(e,"utf8"))}function Ni(e){let t=Gu();if(Yu(Ii(t),{recursive:!0}),process.platform!=="win32"&&Yn(t))_o(t,384);if(zu(t,JSON.stringify(e,null,2)+`
101
+ `,{mode:384}),process.platform!=="win32")_o(t,384)}function Gn(e){if(!Yn(e))return;return Eo(e,"utf8").trim()||void 0}function Ay(e){let t={};for(let n of e.split(`
102
+ `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),i=s.slice(o+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[r]=i}return t}function Hu(e){if(!Yn(e))return{};try{return Ay(Eo(e,"utf8"))}catch{return{}}}function Ri(e,t){let n=vi(),s=e;while(!0){for(let i of[zn(s,".slack-term",".env.local"),zn(s,".env.local")]){let l=Hu(i);for(let u of t)if(l[u])return l[u]}if(s===n)break;let r=Ii(s);if(r===s)break;s=r}let o=Hu(zn(n,".slack-term",".env.local"));for(let r of t)if(o[r])return o[r];return}function Mi(e,t){Yu(Ii(e),{recursive:!0});let n=Yn(e)?Eo(e,"utf8"):"",s=n?n.split(`
103
+ `):[];for(let[o,r]of Object.entries(t)){let i=s.findIndex((u)=>{let c=u.trim();return c.startsWith(o+"=")||c.startsWith(o+" =")}),l=`${o}=${r}`;if(i!==-1)s[i]=l;else s.push(l)}if(process.platform!=="win32"&&Yn(e))_o(e,384);if(zu(e,s.join(`
104
104
  `).trimEnd()+`
105
- `,{mode:384}),process.platform!=="win32")_o(e,384)}function _s(){let e=Xn(),t=Gn(vi()),n=Gn(Pi()),s=t??n;return Object.entries(e.profiles).map(([o,r])=>{let i=Ss(e,o);return{name:o,profile:{...r,...i?{cookie:i}:{}},current:o===s}})}function $o(e,t){let n=Xn();if(t.identity&&t.cookie){n.users??={};let s=n.users[t.identity]??{};n.users[t.identity]={...s,cookie:t.cookie};let{cookie:o,...r}=t;n.profiles[e]=r}else n.profiles[e]=t;Li(n)}function Mi(e,t){let n=Xn(),s=n.profiles[e];if(!s)throw Error(`Profile not found: ${e}`);if(s.identity)n.users??={},n.users[s.identity]={...n.users[s.identity]??{},cookie:t};else s.cookie=t;Li(n)}function qu(e,t,n){let s=Xn();s.users??={},s.users[e]={...s.users[e]??{},cookie:t,...n?{source:n}:{}},Li(s)}function Ss(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 Hu(e){let n=Xn().profiles,s=Object.keys(n);if(e){let a=n[e];if(!a)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let o=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(o&&s.length===0)return o;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((a)=>a&&!a.startsWith("xoxb-"));if(r&&s.length>0){let a=Oi(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==a){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
106
- `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=Oi(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let l=process.env.SLACK_WORKSPACE;if(l){let a=n[l];if(!a)throw Error(`Workspace "${l}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}let u=Gn(vi());if(u){let a=n[u];if(!a)throw Error(`Workspace "${u}" (from .slack-cli/workspace) not found in profiles.`);return a.token}let c=Gn(Pi());if(c){let a=n[c];if(!a)throw Error(`Workspace "${c}" (from ~/.slack-cli/workspace) not found in profiles.`);return a.token}if(s.length>0)throw Error(`Workspace not selected (${s.join(", ")} available).
105
+ `,{mode:384}),process.platform!=="win32")_o(e,384)}function _s(){let e=Xn(),t=Gn(Pi()),n=Gn(Li()),s=t??n;return Object.entries(e.profiles).map(([o,r])=>{let i=Ss(e,o);return{name:o,profile:{...r,...i?{cookie:i}:{}},current:o===s}})}function $o(e,t){let n=Xn();if(t.identity&&t.cookie){n.users??={};let s=n.users[t.identity]??{};n.users[t.identity]={...s,cookie:t.cookie};let{cookie:o,...r}=t;n.profiles[e]=r}else n.profiles[e]=t;Ni(n)}function Bi(e,t){let n=Xn(),s=n.profiles[e];if(!s)throw Error(`Profile not found: ${e}`);if(s.identity)n.users??={},n.users[s.identity]={...n.users[s.identity]??{},cookie:t};else s.cookie=t;Ni(n)}function Xu(e,t,n){let s=Xn();s.users??={},s.users[e]={...s.users[e]??{},cookie:t,...n?{source:n}:{}},Ni(s)}function Ss(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 Vu(e){let n=Xn().profiles,s=Object.keys(n);if(e){let a=n[e];if(!a)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let o=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(o&&s.length===0)return o;let r=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((a)=>a&&!a.startsWith("xoxb-"));if(r&&s.length>0){let a=Ri(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(r!==a){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
106
+ `+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=Ri(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let l=process.env.SLACK_WORKSPACE;if(l){let a=n[l];if(!a)throw Error(`Workspace "${l}" not found. Available: ${s.join(", ")||"(none)"}`);return a.token}let u=Gn(Pi());if(u){let a=n[u];if(!a)throw Error(`Workspace "${u}" (from .slack-cli/workspace) not found in profiles.`);return a.token}let c=Gn(Li());if(c){let a=n[c];if(!a)throw Error(`Workspace "${c}" (from ~/.slack-cli/workspace) not found in profiles.`);return a.token}if(s.length>0)throw Error(`Workspace not selected (${s.join(", ")} available).
107
107
  Select locally: slack auth use <name> (writes .slack-cli/workspace)
108
108
  Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
109
109
  Run one of:
@@ -112,34 +112,34 @@ ${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 Co(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Vt(e){let t=Xn(),n=t.profiles;if(e)return Ss(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 o=Oi(process.cwd(),["SLACK_COOKIE"]);if(o)return o;let r=process.env.SLACK_WORKSPACE;if(r)return Ss(t,r);let i=Gn(vi());if(i)return Ss(t,i);let l=Gn(Pi());if(l)return Ss(t,l);return}function Ao(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})},s=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,o=0;for(let r of e.matchAll(s)){let i=r.index??0;if(n(e.slice(o,i)),r[1]){t.push(r[2]?{type:"link",url:r[1],text:r[2]}:{type:"link",url:r[1]}),o=i+r[0].length;continue}let l=r[0];while(/[.,:;!?'"*_~]$/.test(l)||l.endsWith(")")&&zu(l,"(")<zu(l,")"))l=l.slice(0,-1);t.push({type:"link",url:l}),o=i+l.length}return n(e.slice(o)),t}function zu(e,t){return e.split(t).length-1}var $y={"&":"&amp;","<":"&lt;",">":"&gt;"};function Cy(e){if(typeof e!=="string"||!/^[0-9a-f]+(-[0-9a-f]+)*$/i.test(e))return[];let t=e.split("-").map((o)=>parseInt(o,16)),n=String.fromCodePoint(...t),s=String.fromCodePoint(...t.filter((o)=>o!==65039));return n===s?[n]:[n,s]}function Ay(e){let t=[],n=(r)=>{for(let i of r)if(i===`
116
- `)t.push(null);else if(!/\s/u.test(i))t.push(...$y[i]??i)},s=(r)=>{switch(r.type){case"text":n(String(r.text??""));break;case"link":case"message_mention":n(String(r.url??""));break;case"user":n(String(r.user_id??""));break;case"channel":n(String(r.channel_id??""));break;case"usergroup":n(String(r.usergroup_id??""));break;case"broadcast":n(String(r.range??""));break;case"emoji":t.push([`:${String(r.name??"")}:`,...Cy(r.unicode)].filter((i)=>i!=="::"));break;default:break}},o=(r)=>{let i=Array.isArray(r.elements)?r.elements:[];if(r.type==="rich_text_list"||r.type==="rich_text")i.forEach((l,u)=>{if(u>0)t.push(null);o(l)});else i.forEach(s)};return e.forEach((r,i)=>{if(i>0)t.push(null);let l=r;if(l.type==="rich_text")o(l)}),t}function Fy(e,t,n){if(typeof t==="string"){let o=n;while(o<e.length&&e[o]!==t)o++;return o<e.length?[o,1]:[-1,0]}let s=[-1,0];for(let o of t){let r=[...o];for(let i=n;i+r.length<=e.length&&(s[0]<0||i<s[0]);i++)if(r.every((l,u)=>e[i+u]===l)){s=[i,r.length];break}}return s}function Ty(e,t){if(e.includes(`
117
- `)||!Array.isArray(t)||!t.some((g)=>g?.type==="rich_text"))return e;let n=Ay(t);if(!n.includes(null))return e;let s=[...e],o=t[0].elements,i=t[t.length-1].elements,l=Array.isArray(o)&&o[0]?.type==="rich_text_preformatted",u=Array.isArray(i)&&i[i.length-1]?.type==="rich_text_preformatted",c=0,a=-1,d=l,f=[];for(let g of n){if(g===null){d=!0;continue}let[h,m]=Fy(s,g,c);if(h<0)return e;if(d)f.push([a+1,h]),d=!1;a=h+m-1,c=h+m}if((d||u)&&a>=0)f.push([a+1,s.length]);let p=/^(?:[-*+•]|\d{1,9}[.)]|&gt;|>)$/;for(let[g,h]of f){let m=g;if(s.lastIndexOf("<",g-1)>s.lastIndexOf(">",g-1)){let x=s.indexOf(">",g);if(x!==-1&&x<h)m=x+1}let y="",w=g===0;while(m<h)if(s[m]===" "){let x=m;while(x<h&&s[x]===" ")x++;if(w&&p.test(y))w=!1;else{let D=x-m<=2?x-m:1;for(let E=m;E<m+D;E++)s[E]=`
118
- `;w=!0}y="",m=x}else y+=s[m],m++}return s.join("")}function Fo(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.text==="string")t.text=Ty(t.text,t.blocks)}class qe 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 ji(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}var Oy=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();async function Vu(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof qe)||n+s.retryAfter>Oy)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function Wi(e,t,n,s){return Vu(()=>Ry(e,t,n,s))}async function Ry(e,t,n,s){s=e.startsWith("xoxc-")?s??Vt():void 0;let o={};if(s)o.Cookie=`d=${s}`;let r=await fetch(`${ji()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(r.status===429){let l=parseInt(r.headers.get("retry-after")??"60",10);throw new qe(isNaN(l)?60:l,t)}let i=await r.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new qe(60,t);if(l==="invalid_auth"&&e.startsWith("xoxc-")&&!s)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
115
+ `+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function Co(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Zt(e){let t=Xn(),n=t.profiles;if(e)return Ss(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 o=Ri(process.cwd(),["SLACK_COOKIE"]);if(o)return o;let r=process.env.SLACK_WORKSPACE;if(r)return Ss(t,r);let i=Gn(Pi());if(i)return Ss(t,i);let l=Gn(Li());if(l)return Ss(t,l);return}function Ao(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})},s=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,o=0;for(let r of e.matchAll(s)){let i=r.index??0;if(n(e.slice(o,i)),r[1]){t.push(r[2]?{type:"link",url:r[1],text:r[2]}:{type:"link",url:r[1]}),o=i+r[0].length;continue}let l=r[0];while(/[.,:;!?'"*_~]$/.test(l)||l.endsWith(")")&&Zu(l,"(")<Zu(l,")"))l=l.slice(0,-1);t.push({type:"link",url:l}),o=i+l.length}return n(e.slice(o)),t}function Zu(e,t){return e.split(t).length-1}var Fy={"&":"&amp;","<":"&lt;",">":"&gt;"};function Ty(e){if(typeof e!=="string"||!/^[0-9a-f]+(-[0-9a-f]+)*$/i.test(e))return[];let t=e.split("-").map((o)=>parseInt(o,16)),n=String.fromCodePoint(...t),s=String.fromCodePoint(...t.filter((o)=>o!==65039));return n===s?[n]:[n,s]}function Oy(e){let t=[],n=(r)=>{for(let i of r)if(i===`
116
+ `)t.push(null);else if(!/\s/u.test(i))t.push(...Fy[i]??i)},s=(r)=>{switch(r.type){case"text":n(String(r.text??""));break;case"link":case"message_mention":n(String(r.url??""));break;case"user":n(String(r.user_id??""));break;case"channel":n(String(r.channel_id??""));break;case"usergroup":n(String(r.usergroup_id??""));break;case"broadcast":n(String(r.range??""));break;case"emoji":t.push([`:${String(r.name??"")}:`,...Ty(r.unicode)].filter((i)=>i!=="::"));break;default:break}},o=(r)=>{let i=Array.isArray(r.elements)?r.elements:[];if(r.type==="rich_text_list"||r.type==="rich_text")i.forEach((l,u)=>{if(u>0)t.push(null);o(l)});else i.forEach(s)};return e.forEach((r,i)=>{if(i>0)t.push(null);let l=r;if(l.type==="rich_text")o(l)}),t}function Ry(e,t,n){if(typeof t==="string"){let o=n;while(o<e.length&&e[o]!==t)o++;return o<e.length?[o,1]:[-1,0]}let s=[-1,0];for(let o of t){let r=[...o];for(let i=n;i+r.length<=e.length&&(s[0]<0||i<s[0]);i++)if(r.every((l,u)=>e[i+u]===l)){s=[i,r.length];break}}return s}function Iy(e,t){if(e.includes(`
117
+ `)||!Array.isArray(t)||!t.some((g)=>g?.type==="rich_text"))return e;let n=Oy(t);if(!n.includes(null))return e;let s=[...e],o=t[0].elements,i=t[t.length-1].elements,l=Array.isArray(o)&&o[0]?.type==="rich_text_preformatted",u=Array.isArray(i)&&i[i.length-1]?.type==="rich_text_preformatted",c=0,a=-1,d=l,f=[];for(let g of n){if(g===null){d=!0;continue}let[h,m]=Ry(s,g,c);if(h<0)return e;if(d)f.push([a+1,h]),d=!1;a=h+m-1,c=h+m}if((d||u)&&a>=0)f.push([a+1,s.length]);let p=/^(?:[-*+•]|\d{1,9}[.)]|&gt;|>)$/;for(let[g,h]of f){let m=g;if(s.lastIndexOf("<",g-1)>s.lastIndexOf(">",g-1)){let x=s.indexOf(">",g);if(x!==-1&&x<h)m=x+1}let y="",w=g===0;while(m<h)if(s[m]===" "){let x=m;while(x<h&&s[x]===" ")x++;if(w&&p.test(y))w=!1;else{let D=x-m<=2?x-m:1;for(let E=m;E<m+D;E++)s[E]=`
118
+ `;w=!0}y="",m=x}else y+=s[m],m++}return s.join("")}function Fo(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.text==="string")t.text=Iy(t.text,t.blocks)}class qe 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 Wi(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}var vy=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();async function nd(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof qe)||n+s.retryAfter>vy)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function Ji(e,t,n,s){return nd(()=>Py(e,t,n,s))}async function Py(e,t,n,s){s=e.startsWith("xoxc-")?s??Zt():void 0;let o={};if(s)o.Cookie=`d=${s}`;let r=await fetch(`${Wi()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(r.status===429){let l=parseInt(r.headers.get("retry-after")??"60",10);throw new qe(isNaN(l)?60:l,t)}let i=await r.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new qe(60,t);if(l==="invalid_auth"&&e.startsWith("xoxc-")&&!s)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
119
119
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
120
120
  Or replace the token with an xoxp- user token:
121
121
  slack auth login`);if((l==="missing_scope"||l==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${l}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${l} — ${l==="cannot_dm_bot"?`you're authenticated as a bot, so "@you" is the bot itself and it can't DM itself`:"this bot token lacks the user scope this action needs"}.
122
122
  Tailing/DMing people and listing users need a user session, not a bot token.
123
123
  Switch workspace: slack auth ls then slack auth use <name>
124
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${l}`)}return i}function Iy(e,t,n,s){return Vu(()=>vy(e,t,n,s))}async function vy(e,t,n,s){let o={};if(s)o.Cookie=`d=${s}`;let r=await fetch(`${ji()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(r.status===429){let l=parseInt(r.headers.get("retry-after")??"60",10);throw new qe(isNaN(l)?60:l,t)}let i=await r.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new qe(60,t);if((l==="invalid_auth"||l==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
124
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${l}`)}return i}function Ly(e,t,n,s){return nd(()=>Ny(e,t,n,s))}async function Ny(e,t,n,s){let o={};if(s)o.Cookie=`d=${s}`;let r=await fetch(`${Wi()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(r.status===429){let l=parseInt(r.headers.get("retry-after")??"60",10);throw new qe(isNaN(l)?60:l,t)}let i=await r.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new qe(60,t);if((l==="invalid_auth"||l==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
125
125
  Import from Slack desktop: slack auth login`);if((l==="invalid_auth"||l==="not_authed")&&!s)throw Error(`${t} also requires the xoxd session cookie.
126
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${l}`)}return i}function Py(e,t,n={},s){let o=new URLSearchParams({token:e,...n});return Iy(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()},s)}function Fe(e,t,n,s){let o=new URLSearchParams(n).toString();return Wi(e,`${t}?${o}`,{method:"GET"},s)}function Ji(e,t,n,s){return Wi(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function Zu(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return Wi(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function $s(e,t,n){return Zu(e,"agents.sessions.setStatus",{...t,status:n})}function Ui(e,t,n){return Zu(e,"agents.sessions.rename",{...t,title:n})}async function Vn(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 Qu(e,t){t=e.startsWith("xoxc-")?t??Vt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let s=await fetch(`${ji()}/auth.test`,{method:"GET",headers:n});if(s.status===429){let i=parseInt(s.headers.get("retry-after")??"60",10);throw new qe(isNaN(i)?60:i,"auth.test")}let o=s.headers.get("x-oauth-scopes")??"",r=await s.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:o.split(",").map((i)=>i.trim()).filter(Boolean)}}async function ed(e,t,n){let s=await Fe(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function An(e,t,n=20,s,o,r,i){let l={channel:t,limit:String(n)};if(s!==void 0)l.oldest=s;if(o!==void 0)l.cursor=o;if(i)l.inclusive="true";return Ki(await Fe(e,"conversations.history",l,r))}function Ki(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let s of n)Fo(s);return e}async function td(e,t,n,s=50,o){return Ki(await Fe(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},o))}async function nd(e,t,n,s={},o){let r={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)r.oldest=s.oldest;if(s.cursor!==void 0)r.cursor=s.cursor;return Ki(await Fe(e,"conversations.replies",r,o))}async function sd(e,t,n){let s=[],o="";do{let r={limit:"200",types:t,exclude_archived:"true"};if(o)r.cursor=o;let i=await Fe(e,"users.conversations",r,n);s.push(...i.channels??[]),o=i.response_metadata?.next_cursor??""}while(o);return s}async function To(e,t,n,s,o){await Ji(e,"reactions.add",{channel:t,timestamp:n,name:s},o)}async function od(e,t,n,s){return((await Fe(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Oo(e,t,n,s,o){await Ji(e,"reactions.remove",{channel:t,timestamp:n,name:s},o)}async function Ly(e,t,n){let o=(await Ji(e,"conversations.open",{users:t},n)).channel?.id;if(!o)throw Error(`Failed to open DM with user ${t}`);return o}async function rd(e,t,n){let s="";while(!0){let o={types:"im",limit:"200"};if(s)o.cursor=s;let r=await Fe(e,"conversations.list",o,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(s=r.response_metadata?.next_cursor??"",!s)break}return""}async function Bi(e,t,n,s){let o=await rd(e,t,n);if(o)return o;let r=s?`${s} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function Es(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Yu(e,t){let n=Es(e.name??""),s=Es(e.real_name??e.profile?.real_name??""),o=Es(e.profile?.display_name??"");return n===t||s===t||!!o&&o===t}var id=200;async function Ny(e,t,n){let s=0,o=new Set,r="";while(!0){let a={limit:"200"};if(r)a.cursor=r;let d=await Fe(e,"users.list",a,n);for(let f of d.members??[]){if(s++,f.id)o.add(f.id);if(Yu(f,t))return{id:f.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,l=0,u=!1,c="";while(!0){let a={types:"im",limit:"200"};if(c)a.cursor=c;let d=await Fe(e,"conversations.list",a,n);for(let f of d.channels??[]){let p=f.user;if(!p||o.has(p))continue;if(i>=id){u=!0;break}o.add(p),i++;let g;try{g=(await Fe(e,"users.info",{user:p},n)).user}catch(h){if(h instanceof qe)throw h;l++;continue}if(g&&Yu(g,t))return{id:p,dm:String(f.id??""),workspaceCount:s,connectCount:i,skipped:l,capped:u}}if(u)break;if(c=d.response_metadata?.next_cursor??"",!c)break}return{id:"",workspaceCount:s,connectCount:i,skipped:l,capped:u}}function My(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
126
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${l}`)}return i}function My(e,t,n={},s){let o=new URLSearchParams({token:e,...n});return Ly(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()},s)}function Fe(e,t,n,s){let o=new URLSearchParams(n).toString();return Ji(e,`${t}?${o}`,{method:"GET"},s)}function Ui(e,t,n,s){return Ji(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function sd(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return Ji(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function $s(e,t,n){return sd(e,"agents.sessions.setStatus",{...t,status:n})}function Ki(e,t,n){return sd(e,"agents.sessions.rename",{...t,title:n})}async function Vn(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 od(e,t){t=e.startsWith("xoxc-")?t??Zt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let s=await fetch(`${Wi()}/auth.test`,{method:"GET",headers:n});if(s.status===429){let i=parseInt(s.headers.get("retry-after")??"60",10);throw new qe(isNaN(i)?60:i,"auth.test")}let o=s.headers.get("x-oauth-scopes")??"",r=await s.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:o.split(",").map((i)=>i.trim()).filter(Boolean)}}async function rd(e,t,n){let s=await Fe(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function An(e,t,n=20,s,o,r,i){let l={channel:t,limit:String(n)};if(s!==void 0)l.oldest=s;if(o!==void 0)l.cursor=o;if(i)l.inclusive="true";return qi(await Fe(e,"conversations.history",l,r))}function qi(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let s of n)Fo(s);return e}async function id(e,t,n,s=50,o){return qi(await Fe(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},o))}async function ad(e,t,n,s={},o){let r={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)r.oldest=s.oldest;if(s.cursor!==void 0)r.cursor=s.cursor;return qi(await Fe(e,"conversations.replies",r,o))}async function Hi(e,t,n){let s=[],o="";do{let r={limit:"200",types:t,exclude_archived:"true"};if(o)r.cursor=o;let i=await Fe(e,"users.conversations",r,n);s.push(...i.channels??[]),o=i.response_metadata?.next_cursor??""}while(o);return s}async function To(e,t,n,s,o){await Ui(e,"reactions.add",{channel:t,timestamp:n,name:s},o)}async function cd(e,t,n,s){return((await Fe(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Oo(e,t,n,s,o){await Ui(e,"reactions.remove",{channel:t,timestamp:n,name:s},o)}async function By(e,t,n){let o=(await Ui(e,"conversations.open",{users:t},n)).channel?.id;if(!o)throw Error(`Failed to open DM with user ${t}`);return o}async function ld(e,t,n){let s="";while(!0){let o={types:"im",limit:"200"};if(s)o.cursor=s;let r=await Fe(e,"conversations.list",o,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(s=r.response_metadata?.next_cursor??"",!s)break}return""}async function ji(e,t,n,s){let o=await ld(e,t,n);if(o)return o;let r=s?`${s} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function Es(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Qu(e,t){let n=Es(e.name??""),s=Es(e.real_name??e.profile?.real_name??""),o=Es(e.profile?.display_name??"");return n===t||s===t||!!o&&o===t}var ud=200;async function jy(e,t,n){let s=0,o=new Set,r="";while(!0){let a={limit:"200"};if(r)a.cursor=r;let d=await Fe(e,"users.list",a,n);for(let f of d.members??[]){if(s++,f.id)o.add(f.id);if(Qu(f,t))return{id:f.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,l=0,u=!1,c="";while(!0){let a={types:"im",limit:"200"};if(c)a.cursor=c;let d=await Fe(e,"conversations.list",a,n);for(let f of d.channels??[]){let p=f.user;if(!p||o.has(p))continue;if(i>=ud){u=!0;break}o.add(p),i++;let g;try{g=(await Fe(e,"users.info",{user:p},n)).user}catch(h){if(h instanceof qe)throw h;l++;continue}if(g&&Qu(g,t))return{id:p,dm:String(f.id??""),workspaceCount:s,connectCount:i,skipped:l,capped:u}}if(u)break;if(c=d.response_metadata?.next_cursor??"",!c)break}return{id:"",workspaceCount:s,connectCount:i,skipped:l,capped:u}}function Wy(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
127
127
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
128
- Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,s=[];if(t.capped)s.push(`stopped after ${id} Slack Connect DM partners, so there may be more`);if(t.skipped)s.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
128
+ Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,s=[];if(t.capped)s.push(`stopped after ${ud} Slack Connect DM partners, so there may be more`);if(t.skipped)s.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
129
129
  `+(s.length?`This search was incomplete: ${s.join("; ")}.
130
130
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
131
131
  DMed you they cannot be found by name at all. Look them up and use their ID:
132
- slack user ls --external`)}function qi(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,o=e.indexOf("?"),r=o>=0?new URLSearchParams(e.slice(o)):void 0,i=r?.get("thread_ts")??void 0,c={channel:r?.get("cid")??void 0??n};if(s)c.ts=s;if(i)c.threadTs=i;return c}function By(e){return qi(e)?.channel}function Gu(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function Xu(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Ro(e,t,n){let s=By(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(Gu(t))return t;if(Xu(t))return Bi(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Gu(t.slice(1)))return t.slice(1);let o=t.startsWith("@"),r=t.slice(1),i=Es(r);if(o){if(Xu(r))return Bi(e,r,n);let c=await Fe(e,"auth.test",{},n);if(i==="you"||i==="me"||Es(c.user??"")===i){let f=c.user_id;if(!f)throw Error("auth.test did not return user_id");return await rd(e,f,n)||Ly(e,f,n)}let d=await Ny(e,i,n);if(!d.id)throw My(t,d);if(d.dm)return d.dm;return Bi(e,d.id,n,t)}let l=r.toLowerCase(),u="";while(!0){let c={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(u)c.cursor=u;let a=await Fe(e,"conversations.list",c,n);for(let d of a.channels??[])if(String(d.name??"").toLowerCase()===l)return String(d.id??"");if(u=a.response_metadata?.next_cursor??"",!u)break}throw Error(`channel not found: ${t}`)}async function Io(e,t,n){try{let s=await Fe(e,"users.info",{user:t},n),o=s.user?.profile?.display_name,r=o&&o.length>0?o:s.user?.real_name??s.user?.name??t,i=s.user?.name??t;return[r,i]}catch{return[t,t]}}async function Zn(e,t,n){try{let s=await Fe(e,"users.info",{user:t},n),o=s.user?.profile?.display_name;if(o&&o.length>0)return o;return s.user?.real_name??s.user?.name??t}catch{return t}}async function vo(e,t){let n=[],s="";while(!0){let o={limit:"200"};if(s)o.cursor=s;let r=await Fe(e,"users.list",o,t);if(n.push(...r.members??[]),s=r.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function Hi(e,t,n){let s=[],o="";while(!0){let r={channel:t,limit:"200"};if(o)r.cursor=o;let i=await Fe(e,"conversations.members",r,n);if(s.push(...i.members??[]),o=i.response_metadata?.next_cursor??"",!o)break}return s}async function zi(e,t,n){return Fe(e,"users.info",{user:t},n)}async function ad(e,t,n){return Fe(e,"conversations.info",{channel:t},n)}async function cd(e,t){let n=await Py(e,"client.boot",{},t),s=typeof n.url==="string"?n.url:void 0;if(!s){let r=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${r}`)}let o=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:s,selfId:typeof o.id==="string"?o.id:""}}var jy=["chat:write","im:write"],Wy=["im:history","im:read"];async function Po(e){let{userId:t,botId:n,team:s,scopes:o}=await Qu(e),r="";if(n)try{r=(await ed(e,n)).appId}catch{r=""}let i=(c)=>o.includes(c),l=jy.filter((c)=>!i(c)),u=Wy.filter((c)=>!i(c));return{canSend:l.length===0,canReceiveReplies:u.length===0,ok:l.length===0&&u.length===0,botUserId:t,appId:r,team:s,grantedScopes:o,missingSendScopes:l,missingReplyScopes:u}}function ld(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function Lo(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let o=["✓ 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?o:[...o,...ld(e)]}let s=[];if(!e.canSend)s.push(`⚠ This bot CANNOT send DMs — missing scope(s): ${e.missingSendScopes.join(", ")}.`);else s.push("⚠ This bot can send DMs, but the user's replies will NOT be readable.");return s.push(" Make escalation DMs two-way:"),s.push(` 1. ${n} → App Home → enable "Messages Tab" and check`),s.push(' "Allow users to send Slash commands and messages".'),s.push(` 2. OAuth & Permissions → add Bot Token Scopes: ${[...e.missingSendScopes,...e.missingReplyScopes].join(", ")}`),s.push(" 3. Reinstall the app to apply the new scopes."),t?s:[...s,...ld(e)]}import{createInterface as Ye}from"node:readline/promises";import{join as sa,resolve as pb}from"node:path";import{homedir as hb}from"node:os";import{readdirSync as Fs,readFileSync as As,existsSync as nt,copyFileSync as Xi,mkdtempSync as pd,rmSync as hd}from"node:fs";import{homedir as Mo,tmpdir as gd}from"node:os";import{join as me,dirname as Ky}from"node:path";import{pbkdf2Sync as No,createDecipheriv as md,createHash as qy,timingSafeEqual as Hy}from"node:crypto";import{execSync as yd,execFileSync as zy}from"node:child_process";function Cs(e,t){let n=0,s=0,o=t;while(o<e.length){let r=e[o++];if(n+=(r&127)*2**s,(r&128)===0)break;s+=7}return{value:n,pos:o}}function Jy(e){let t=0,n=0,s=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**s,(i&128)===0)break;s+=7}let o=Buffer.allocUnsafe(n),r=0;while(t<e.length&&r<n){let i=e[t++],l=i&3;if(l===0){let u=i>>2;if(u>=60){let c=u-59;u=0;for(let a=0;a<c;a++)u+=e[t++]*2**(8*a)}u+=1,e.copy(o,r,t,t+u),t+=u,r+=u}else{let u,c;if(l===1)u=4+(i>>2&7),c=(i>>5&7)*256+e[t++];else if(l===2)u=1+(i>>2),c=e[t]+e[t+1]*256,t+=2;else u=1+(i>>2),c=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let a=r-c;for(let d=0;d<u&&r<n;d++)o[r++]=o[a++]}}return r===n?o:o.subarray(0,r)}function Yi(e,t){let n=Cs(e,t),s=Cs(e,n.pos);return{handle:{offset:n.value,size:s.value},pos:s.pos}}function ud(e,t){let{offset:n,size:s}=t,o=e.subarray(n,n+s);return e[n+s]===1?Jy(o):Buffer.from(o)}function Uy(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,s=[],o=0,r=Buffer.alloc(0);while(o<n){let i=Cs(e,o),l=Cs(e,i.pos),u=Cs(e,l.pos);o=u.pos;let c=i.value,a=l.value,d=u.value,f=e.subarray(o,o+a);o+=a;let p=e.subarray(o,o+d);o+=d,r=Buffer.concat([r.subarray(0,c),f]),s.push(p)}return s}function dd(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=Yi(e,t),s=Yi(e,n.pos),o=ud(e,s.handle),r=[];for(let i of Uy(o))try{let{handle:l}=Yi(i,0);r.push(ud(e,l))}catch{}return Buffer.concat(r)}catch{return Buffer.alloc(0)}}function fd(){let e=process.env.HOME??Mo();if(process.platform==="darwin")return[me(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[me(e,".config","Slack","Local Storage","leveldb"),me(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),me(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??me(e,"AppData","Roaming");return[me(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function Yy(){let e=process.env.HOME??Mo();if(process.platform==="darwin")return me(e,"Library","Application Support","Slack","Cookies");return""}function Gy(e,t){if(e.length<35||e.slice(0,3).toString()!=="v10")throw Error("Not a v10 encrypted cookie");let n=e.slice(19,35),s=e.slice(35),o=md("aes-128-cbc",t,n);return o.setAutoPadding(!0),Buffer.concat([o.update(s),o.final()]).toString("utf8")}function Xy(){if(process.platform!=="darwin")return;let e=Yy();if(!nt(e))return;let t;try{t=yd('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=No(t,"saltysalt",1003,16,"sha1");try{let{default:s}=ps("bun:sqlite"),o=new s(e,{readonly:!0}),r=o.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(o.close(),!r)return;return Gy(Buffer.from(r.encrypted_value),n)}catch{return}}function bd(e){if(!nt(e))return[];let t=Fs(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,s=(i)=>{let l=n.get(i);if(l!==void 0)return l;let u="";try{let c=As(me(e,i));u=i.endsWith(".ldb")?dd(c).toString("latin1")||c.toString("latin1"):c.toString("latin1")}catch{u=""}return n.set(i,u),u},o=new Map;for(let i of t){let l=s(i);for(let u of l.matchAll(/"token":"(xoxc-[^"]+)"/g)){let c=u[1],a=c.split("-")[1]??"";if(!a||c.length<40)continue;let d=Math.max(0,u.index-2000),f=Math.min(l.length,u.index+2000),p=l.slice(d,f),g=p.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),h=p.match(/"(?:team_name|name)":"([^"]{2,60})"/),m=o.get(a);if(!m||c.length>m.token.length){let y={token:c,teamId:a},w=g?.[1]??m?.url,x=h?.[1]??m?.teamName;if(w)y.url=w;if(x)y.teamName=x;o.set(a,y)}}}let r=t.map((i)=>s(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of o.values()){if(i.teamName)continue;let l=r.indexOf(i.teamId);if(l!==-1){let u=Math.max(0,l-500),c=Math.min(r.length,l+500),d=r.slice(u,c).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){i.teamName=d[1];continue}}if(!i.teamName&&i.url){let u=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(u){let c=r.indexOf(u);if(c!==-1){let a=Math.max(0,c-500),d=Math.min(r.length,c+500),p=r.slice(a,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(p?.[1]){i.teamName=p[1];continue}}i.teamName=u.split("-").map((a)=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ")}}}return[...o.values()]}async function Vi(e){let t=e??fd().find(nt);if(!t)throw Error(`Slack desktop app LevelDB not found at:
133
- ${fd().join(`
132
+ slack user ls --external`)}function zi(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,o=e.indexOf("?"),r=o>=0?new URLSearchParams(e.slice(o)):void 0,i=r?.get("thread_ts")??void 0,c={channel:r?.get("cid")??void 0??n};if(s)c.ts=s;if(i)c.threadTs=i;return c}function Jy(e){return zi(e)?.channel}function ed(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function td(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Ro(e,t,n){let s=Jy(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(ed(t))return t;if(td(t))return ji(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&ed(t.slice(1)))return t.slice(1);let o=t.startsWith("@"),r=t.slice(1),i=Es(r);if(o){if(td(r))return ji(e,r,n);let c=await Fe(e,"auth.test",{},n);if(i==="you"||i==="me"||Es(c.user??"")===i){let f=c.user_id;if(!f)throw Error("auth.test did not return user_id");return await ld(e,f,n)||By(e,f,n)}let d=await jy(e,i,n);if(!d.id)throw Wy(t,d);if(d.dm)return d.dm;return ji(e,d.id,n,t)}let l=r.toLowerCase(),u="";while(!0){let c={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(u)c.cursor=u;let a=await Fe(e,"conversations.list",c,n);for(let d of a.channels??[])if(String(d.name??"").toLowerCase()===l)return String(d.id??"");if(u=a.response_metadata?.next_cursor??"",!u)break}throw Error(`channel not found: ${t}`)}async function Io(e,t,n){try{let s=await Fe(e,"users.info",{user:t},n),o=s.user?.profile?.display_name,r=o&&o.length>0?o:s.user?.real_name??s.user?.name??t,i=s.user?.name??t;return[r,i]}catch{return[t,t]}}async function Zn(e,t,n){try{let s=await Fe(e,"users.info",{user:t},n),o=s.user?.profile?.display_name;if(o&&o.length>0)return o;return s.user?.real_name??s.user?.name??t}catch{return t}}async function vo(e,t){let n=[],s="";while(!0){let o={limit:"200"};if(s)o.cursor=s;let r=await Fe(e,"users.list",o,t);if(n.push(...r.members??[]),s=r.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function Yi(e,t,n){let s=[],o="";while(!0){let r={channel:t,limit:"200"};if(o)r.cursor=o;let i=await Fe(e,"conversations.members",r,n);if(s.push(...i.members??[]),o=i.response_metadata?.next_cursor??"",!o)break}return s}async function Gi(e,t,n){return Fe(e,"users.info",{user:t},n)}async function Po(e,t,n){return Fe(e,"conversations.info",{channel:t},n)}async function dd(e,t){let n=await My(e,"client.boot",{},t),s=typeof n.url==="string"?n.url:void 0;if(!s){let r=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${r}`)}let o=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:s,selfId:typeof o.id==="string"?o.id:""}}var Uy=["chat:write","im:write"],Ky=["im:history","im:read"];async function Lo(e){let{userId:t,botId:n,team:s,scopes:o}=await od(e),r="";if(n)try{r=(await rd(e,n)).appId}catch{r=""}let i=(c)=>o.includes(c),l=Uy.filter((c)=>!i(c)),u=Ky.filter((c)=>!i(c));return{canSend:l.length===0,canReceiveReplies:u.length===0,ok:l.length===0&&u.length===0,botUserId:t,appId:r,team:s,grantedScopes:o,missingSendScopes:l,missingReplyScopes:u}}function fd(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 o=["✓ 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?o:[...o,...fd(e)]}let s=[];if(!e.canSend)s.push(`⚠ This bot CANNOT send DMs — missing scope(s): ${e.missingSendScopes.join(", ")}.`);else s.push("⚠ This bot can send DMs, but the user's replies will NOT be readable.");return s.push(" Make escalation DMs two-way:"),s.push(` 1. ${n} → App Home → enable "Messages Tab" and check`),s.push(' "Allow users to send Slash commands and messages".'),s.push(` 2. OAuth & Permissions → add Bot Token Scopes: ${[...e.missingSendScopes,...e.missingReplyScopes].join(", ")}`),s.push(" 3. Reinstall the app to apply the new scopes."),t?s:[...s,...fd(e)]}import{createInterface as Ye}from"node:readline/promises";import{join as ra,resolve as mb}from"node:path";import{homedir as yb}from"node:os";import{readdirSync as Fs,readFileSync as As,existsSync as nt,copyFileSync as Zi,mkdtempSync as md,rmSync as yd}from"node:fs";import{homedir as Bo,tmpdir as bd}from"node:os";import{join as me,dirname as zy}from"node:path";import{pbkdf2Sync as Mo,createDecipheriv as wd,createHash as Yy,timingSafeEqual as Gy}from"node:crypto";import{execSync as Dd,execFileSync as Xy}from"node:child_process";function Cs(e,t){let n=0,s=0,o=t;while(o<e.length){let r=e[o++];if(n+=(r&127)*2**s,(r&128)===0)break;s+=7}return{value:n,pos:o}}function qy(e){let t=0,n=0,s=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**s,(i&128)===0)break;s+=7}let o=Buffer.allocUnsafe(n),r=0;while(t<e.length&&r<n){let i=e[t++],l=i&3;if(l===0){let u=i>>2;if(u>=60){let c=u-59;u=0;for(let a=0;a<c;a++)u+=e[t++]*2**(8*a)}u+=1,e.copy(o,r,t,t+u),t+=u,r+=u}else{let u,c;if(l===1)u=4+(i>>2&7),c=(i>>5&7)*256+e[t++];else if(l===2)u=1+(i>>2),c=e[t]+e[t+1]*256,t+=2;else u=1+(i>>2),c=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let a=r-c;for(let d=0;d<u&&r<n;d++)o[r++]=o[a++]}}return r===n?o:o.subarray(0,r)}function Xi(e,t){let n=Cs(e,t),s=Cs(e,n.pos);return{handle:{offset:n.value,size:s.value},pos:s.pos}}function pd(e,t){let{offset:n,size:s}=t,o=e.subarray(n,n+s);return e[n+s]===1?qy(o):Buffer.from(o)}function Hy(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,s=[],o=0,r=Buffer.alloc(0);while(o<n){let i=Cs(e,o),l=Cs(e,i.pos),u=Cs(e,l.pos);o=u.pos;let c=i.value,a=l.value,d=u.value,f=e.subarray(o,o+a);o+=a;let p=e.subarray(o,o+d);o+=d,r=Buffer.concat([r.subarray(0,c),f]),s.push(p)}return s}function hd(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=Xi(e,t),s=Xi(e,n.pos),o=pd(e,s.handle),r=[];for(let i of Hy(o))try{let{handle:l}=Xi(i,0);r.push(pd(e,l))}catch{}return Buffer.concat(r)}catch{return Buffer.alloc(0)}}function gd(){let e=process.env.HOME??Bo();if(process.platform==="darwin")return[me(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[me(e,".config","Slack","Local Storage","leveldb"),me(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),me(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??me(e,"AppData","Roaming");return[me(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function Vy(){let e=process.env.HOME??Bo();if(process.platform==="darwin")return me(e,"Library","Application Support","Slack","Cookies");return""}function Zy(e,t){if(e.length<35||e.slice(0,3).toString()!=="v10")throw Error("Not a v10 encrypted cookie");let n=e.slice(19,35),s=e.slice(35),o=wd("aes-128-cbc",t,n);return o.setAutoPadding(!0),Buffer.concat([o.update(s),o.final()]).toString("utf8")}function Qy(){if(process.platform!=="darwin")return;let e=Vy();if(!nt(e))return;let t;try{t=Dd('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=Mo(t,"saltysalt",1003,16,"sha1");try{let{default:s}=ps("bun:sqlite"),o=new s(e,{readonly:!0}),r=o.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(o.close(),!r)return;return Zy(Buffer.from(r.encrypted_value),n)}catch{return}}function kd(e){if(!nt(e))return[];let t=Fs(e).filter((i)=>i.endsWith(".ldb")||i.endsWith(".log"));if(t.length===0)return[];let n=new Map,s=(i)=>{let l=n.get(i);if(l!==void 0)return l;let u="";try{let c=As(me(e,i));u=i.endsWith(".ldb")?hd(c).toString("latin1")||c.toString("latin1"):c.toString("latin1")}catch{u=""}return n.set(i,u),u},o=new Map;for(let i of t){let l=s(i);for(let u of l.matchAll(/"token":"(xoxc-[^"]+)"/g)){let c=u[1],a=c.split("-")[1]??"";if(!a||c.length<40)continue;let d=Math.max(0,u.index-2000),f=Math.min(l.length,u.index+2000),p=l.slice(d,f),g=p.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),h=p.match(/"(?:team_name|name)":"([^"]{2,60})"/),m=o.get(a);if(!m||c.length>m.token.length){let y={token:c,teamId:a},w=g?.[1]??m?.url,x=h?.[1]??m?.teamName;if(w)y.url=w;if(x)y.teamName=x;o.set(a,y)}}}let r=t.map((i)=>s(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of o.values()){if(i.teamName)continue;let l=r.indexOf(i.teamId);if(l!==-1){let u=Math.max(0,l-500),c=Math.min(r.length,l+500),d=r.slice(u,c).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){i.teamName=d[1];continue}}if(!i.teamName&&i.url){let u=i.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(u){let c=r.indexOf(u);if(c!==-1){let a=Math.max(0,c-500),d=Math.min(r.length,c+500),p=r.slice(a,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(p?.[1]){i.teamName=p[1];continue}}i.teamName=u.split("-").map((a)=>a.charAt(0).toUpperCase()+a.slice(1)).join(" ")}}}return[...o.values()]}async function Qi(e){let t=e??gd().find(nt);if(!t)throw Error(`Slack desktop app LevelDB not found at:
133
+ ${gd().join(`
134
134
  `)}
135
- Is Slack installed and opened at least once?`);let n=bd(t),s=e?void 0:Xy();if(s)for(let o of n)o.cookie=s;return n}function Vy(e,t){try{return JSON.parse(As(me(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function Zi(){let e=Qi();if(!e||!nt(e))return[];let t=["Default",...Fs(e).filter((s)=>s.startsWith("Profile "))],n=[];for(let s of t){let o=me(e,s,"Local Storage","leveldb"),r=bd(o);if(r.length===0)continue;let i=Vy(e,s);n.push({profileDir:s,...i?{email:i}:{},label:wd(e,s),sessions:r})}return n}function Gi(e,t,n,s=!1){let o=(r,i)=>{try{let l=md("aes-128-cbc",t,r);l.setAutoPadding(!0);let u=Buffer.concat([l.update(i),l.final()]);if(u.subarray(0,5).toString()==="xoxd-")return u.toString("utf8");if(u.length>=37){let c=qy("sha256").update(n).digest();if(Hy(u.subarray(0,32),c)){let a=u.subarray(32).toString("utf8");if(a.startsWith("xoxd-"))return a}}return}catch{return}};return o(Buffer.alloc(16,32),e.slice(3))??(s&&e.length>=35?o(e.slice(19,35),e.slice(35)):void 0)}function wd(e,t){let n=(s,o)=>{if(s&&o)return`${s} (${o})`;return s||o||t};try{let o=JSON.parse(As(me(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(o&&(o.name||o.user_name))return n(o.name??"",o.user_name??"")}catch{}try{let o=JSON.parse(As(me(e,t,"Preferences"),"utf8")).profile;return n(o?.name??"",o?.user_name??"")}catch{return t}}function Qi(){let e=process.env.HOME??Mo();if(process.platform==="darwin")return me(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return me(process.env.XDG_CONFIG_HOME??me(e,".config"),"google-chrome");return""}function Zy(){try{return zy("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=Qi();if(!nt(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=yd('security find-generic-password -a Chrome -s "Chrome Safe Storage" -w',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return{candidates:[],totalProfiles:0}}if(!i)return{candidates:[],totalProfiles:0};t=No(i,"saltysalt",1003,16,"sha1")}let n=["Default",...Fs(e).filter((i)=>i.startsWith("Profile "))],s=[],o,r=!1;for(let i of n){let l=[me(e,i,"Network","Cookies"),me(e,i,"Cookies")].find(nt);if(!l)continue;let u=pd(me(gd(),"slack-chrome-cookies-")),c=me(u,"Cookies");try{if(Xi(l,c),nt(`${l}-wal`))Xi(`${l}-wal`,`${c}-wal`);let{default:a}=ps("bun:sqlite"),d=new a(c,{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 p=Buffer.from(f.encrypted_value),g=p.subarray(0,3).toString(),h;if(g==="v20")throw Error("Chrome cookie uses unsupported v20 app-bound encryption.");if(process.platform==="linux"){if(!p.length&&f.value?.startsWith("xoxd-"))h=f.value;else if(g==="v10")h=Gi(p,No("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(g==="v11"){if(!o){let m=Zy();if(m)o=No(m,"saltysalt",1,16,"sha1")}if(o)h=Gi(p,o,f.host_key);else r=!0}}else if(g==="v10"&&t)h=Gi(p,t,f.host_key,!0);else if(g!=="v10")throw Error("Unknown cookie encryption prefix.");if(h)s.push({profileDir:i,profileName:wd(e,i),cookie:h})}catch(a){if(a instanceof Error&&(a.message.includes("unsupported v20")||a.message.includes("Unknown cookie")))throw a}finally{hd(u,{recursive:!0,force:!0})}}if(r&&s.length===0)throw Error("Chrome v11 cookie key is unavailable. Install secret-tool and unlock the GNOME keyring, or use slack auth firefox.");return{candidates:s,totalProfiles:n.length}}async function ea(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=Qi();if(!nt(e))throw Error("Chrome profile directory was not found.");let t=new Map(Ts().candidates.map((o)=>[o.profileDir,o.cookie])),n=new Map,s=["Default",...Fs(e).filter((o)=>o.startsWith("Profile "))];for(let o of s){let r=me(e,o,"Local Storage","leveldb");if(!nt(r))continue;let i;try{i=await Vi(r)}catch{continue}for(let l of i){if(n.has(l.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let u=t.get(o);if(u)l.cookie=u;n.set(l.teamId,l)}}return[...n.values()]}function Qy(){let e=process.env.HOME??Mo();if(process.platform==="darwin")return[me(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[me(e,".mozilla","firefox"),me(e,"snap","firefox","common",".mozilla","firefox"),me(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[me(process.env.APPDATA??me(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function eb(e){let t=me(e,"profiles.ini"),n=nt(t)?t:me(Ky(e),"profiles.ini"),s={};if(!nt(n))return s;try{let o=As(n,"utf8"),r="",i="";for(let l of o.split(`
136
- `)){let u=l.trim();if(u.startsWith("[")){r="",i="";continue}let c=u.indexOf("=");if(c===-1)continue;let a=u.slice(0,c).trim().toLowerCase(),d=u.slice(c+1).trim();if(a==="name")r=d;if(a==="path")i=d.split(/[\\/]/).pop()??d;if(r&&i)s[i]=r,r="",i=""}}catch{}return s}function Bo(){let e=[];for(let t of Qy().filter(nt)){let n=eb(t),s;try{s=Fs(t)}catch{continue}for(let o of s){let r=me(t,o,"cookies.sqlite");if(!nt(r))continue;let i=pd(me(gd(),"slack-firefox-cookies-")),l=me(i,"cookies.sqlite");try{Xi(r,l);let{default:u}=ps("bun:sqlite"),c=new u(l,{readonly:!0}),a=c.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(c.close(),!a?.value||!a.value.startsWith("xoxd-"))continue;let d=n[o]??o;e.push({profileDir:o,profileName:d,cookie:a.value})}catch{}finally{hd(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as ta,writeFileSync as na,mkdirSync as tb,existsSync as Os,rmSync as nb}from"node:fs";import{join as lt}from"node:path";import{createDecipheriv as jo}from"node:crypto";import{spawnSync as sb}from"node:child_process";var ob=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),rb=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),ib=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),mt="C:\\ProgramData\\slack-term-abe";function ab(){let e=process.env.LOCALAPPDATA??lt(process.env.USERPROFILE??"","AppData","Local");return lt(e,"Google","Chrome","User Data")}var cb=String.raw`try {
135
+ Is Slack installed and opened at least once?`);let n=kd(t),s=e?void 0:Qy();if(s)for(let o of n)o.cookie=s;return n}function eb(e,t){try{return JSON.parse(As(me(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function ea(){let e=ta();if(!e||!nt(e))return[];let t=["Default",...Fs(e).filter((s)=>s.startsWith("Profile "))],n=[];for(let s of t){let o=me(e,s,"Local Storage","leveldb"),r=kd(o);if(r.length===0)continue;let i=eb(e,s);n.push({profileDir:s,...i?{email:i}:{},label:xd(e,s),sessions:r})}return n}function Vi(e,t,n,s=!1){let o=(r,i)=>{try{let l=wd("aes-128-cbc",t,r);l.setAutoPadding(!0);let u=Buffer.concat([l.update(i),l.final()]);if(u.subarray(0,5).toString()==="xoxd-")return u.toString("utf8");if(u.length>=37){let c=Yy("sha256").update(n).digest();if(Gy(u.subarray(0,32),c)){let a=u.subarray(32).toString("utf8");if(a.startsWith("xoxd-"))return a}}return}catch{return}};return o(Buffer.alloc(16,32),e.slice(3))??(s&&e.length>=35?o(e.slice(19,35),e.slice(35)):void 0)}function xd(e,t){let n=(s,o)=>{if(s&&o)return`${s} (${o})`;return s||o||t};try{let o=JSON.parse(As(me(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(o&&(o.name||o.user_name))return n(o.name??"",o.user_name??"")}catch{}try{let o=JSON.parse(As(me(e,t,"Preferences"),"utf8")).profile;return n(o?.name??"",o?.user_name??"")}catch{return t}}function ta(){let e=process.env.HOME??Bo();if(process.platform==="darwin")return me(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return me(process.env.XDG_CONFIG_HOME??me(e,".config"),"google-chrome");return""}function tb(){try{return Xy("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=ta();if(!nt(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=Dd('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=Mo(i,"saltysalt",1003,16,"sha1")}let n=["Default",...Fs(e).filter((i)=>i.startsWith("Profile "))],s=[],o,r=!1;for(let i of n){let l=[me(e,i,"Network","Cookies"),me(e,i,"Cookies")].find(nt);if(!l)continue;let u=md(me(bd(),"slack-chrome-cookies-")),c=me(u,"Cookies");try{if(Zi(l,c),nt(`${l}-wal`))Zi(`${l}-wal`,`${c}-wal`);let{default:a}=ps("bun:sqlite"),d=new a(c,{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 p=Buffer.from(f.encrypted_value),g=p.subarray(0,3).toString(),h;if(g==="v20")throw Error("Chrome cookie uses unsupported v20 app-bound encryption.");if(process.platform==="linux"){if(!p.length&&f.value?.startsWith("xoxd-"))h=f.value;else if(g==="v10")h=Vi(p,Mo("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(g==="v11"){if(!o){let m=tb();if(m)o=Mo(m,"saltysalt",1,16,"sha1")}if(o)h=Vi(p,o,f.host_key);else r=!0}}else if(g==="v10"&&t)h=Vi(p,t,f.host_key,!0);else if(g!=="v10")throw Error("Unknown cookie encryption prefix.");if(h)s.push({profileDir:i,profileName:xd(e,i),cookie:h})}catch(a){if(a instanceof Error&&(a.message.includes("unsupported v20")||a.message.includes("Unknown cookie")))throw a}finally{yd(u,{recursive:!0,force:!0})}}if(r&&s.length===0)throw Error("Chrome v11 cookie key is unavailable. Install secret-tool and unlock the GNOME keyring, or use slack auth firefox.");return{candidates:s,totalProfiles:n.length}}async function na(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=ta();if(!nt(e))throw Error("Chrome profile directory was not found.");let t=new Map(Ts().candidates.map((o)=>[o.profileDir,o.cookie])),n=new Map,s=["Default",...Fs(e).filter((o)=>o.startsWith("Profile "))];for(let o of s){let r=me(e,o,"Local Storage","leveldb");if(!nt(r))continue;let i;try{i=await Qi(r)}catch{continue}for(let l of i){if(n.has(l.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let u=t.get(o);if(u)l.cookie=u;n.set(l.teamId,l)}}return[...n.values()]}function nb(){let e=process.env.HOME??Bo();if(process.platform==="darwin")return[me(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[me(e,".mozilla","firefox"),me(e,"snap","firefox","common",".mozilla","firefox"),me(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[me(process.env.APPDATA??me(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function sb(e){let t=me(e,"profiles.ini"),n=nt(t)?t:me(zy(e),"profiles.ini"),s={};if(!nt(n))return s;try{let o=As(n,"utf8"),r="",i="";for(let l of o.split(`
136
+ `)){let u=l.trim();if(u.startsWith("[")){r="",i="";continue}let c=u.indexOf("=");if(c===-1)continue;let a=u.slice(0,c).trim().toLowerCase(),d=u.slice(c+1).trim();if(a==="name")r=d;if(a==="path")i=d.split(/[\\/]/).pop()??d;if(r&&i)s[i]=r,r="",i=""}}catch{}return s}function jo(){let e=[];for(let t of nb().filter(nt)){let n=sb(t),s;try{s=Fs(t)}catch{continue}for(let o of s){let r=me(t,o,"cookies.sqlite");if(!nt(r))continue;let i=md(me(bd(),"slack-firefox-cookies-")),l=me(i,"cookies.sqlite");try{Zi(r,l);let{default:u}=ps("bun:sqlite"),c=new u(l,{readonly:!0}),a=c.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(c.close(),!a?.value||!a.value.startsWith("xoxd-"))continue;let d=n[o]??o;e.push({profileDir:o,profileName:d,cookie:a.value})}catch{}finally{yd(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as sa,writeFileSync as oa,mkdirSync as ob,existsSync as Os,rmSync as rb}from"node:fs";import{join as lt}from"node:path";import{createDecipheriv as Wo}from"node:crypto";import{spawnSync as ib}from"node:child_process";var ab=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),cb=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),lb=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),mt="C:\\ProgramData\\slack-term-abe";function ub(){let e=process.env.LOCALAPPDATA??lt(process.env.USERPROFILE??"","AppData","Local");return lt(e,"Google","Chrome","User Data")}var db=String.raw`try {
137
137
  Add-Type -AssemblyName System.Security
138
138
  $d = [IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\in.bin')
139
139
  $o = [Security.Cryptography.ProtectedData]::Unprotect($d, $null, 'CurrentUser')
140
140
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\sys.bin', $o)
141
141
  } catch { Set-Content 'C:\ProgramData\slack-term-abe\dpapi.err' ($_.Exception.Message) }
142
- `,lb=String.raw`try {
142
+ `,fb=String.raw`try {
143
143
  Add-Type -TypeDefinition @'
144
144
  using System; using System.Runtime.InteropServices;
145
145
  public static class NC {
@@ -155,7 +155,7 @@ public static class NC {
155
155
  '@
156
156
  [IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\cng.bin', [NC]::Dec([IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\eak.bin')))
157
157
  } catch { Set-Content 'C:\ProgramData\slack-term-abe\cng.err' ($_.Exception.Message) }
158
- `;function ub(e,t){let n=(s)=>`'${s.replace(/'/g,"''")}'`;return String.raw`
158
+ `;function pb(e,t){let n=(s)=>`'${s.replace(/'/g,"''")}'`;return String.raw`
159
159
  $ErrorActionPreference = 'Stop'
160
160
  Add-Type -AssemblyName System.Security
161
161
  $work = 'C:\ProgramData\slack-term-abe'
@@ -221,44 +221,44 @@ icacls "$work\Cookies" /grant "$($u):(R)" | Out-Null
221
221
  if (Test-Path "$work\cng.bin") { icacls "$work\cng.bin" /grant "$($u):(R)" | Out-Null }
222
222
  Write-Host 'OK'
223
223
  try { Stop-Transcript | Out-Null } catch {}
224
- `}function db(e,t){let s=4+e.readUInt32LE(0)+4,o=e[s];if(o===1||o===2){let r=e.subarray(s+1,s+13),i=e.subarray(s+13,s+45),l=e.subarray(s+45,s+61),u=o===1?jo("aes-256-gcm",ob,r):jo("chacha20-poly1305",rb,r,{authTagLength:16});return u.setAuthTag(l),Buffer.concat([u.update(i),u.final()])}if(o===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let r=e.subarray(s+33,s+45),i=e.subarray(s+45,s+77),l=e.subarray(s+77,s+93),u=Buffer.from(t.map((a,d)=>a^ib[d])),c=jo("aes-256-gcm",u,r);return c.setAuthTag(l),Buffer.concat([c.update(i),c.final()])}throw Error(`Unsupported app-bound key flag: ${o}`)}function fb(e,t){let n=t.subarray(3,15),s=t.subarray(15,t.length-16),o=t.subarray(t.length-16),r=jo("aes-256-gcm",e,n);return r.setAuthTag(o),Buffer.concat([r.update(s),r.final()]).subarray(32).toString("utf8")}async function Dd(e){if(process.platform!=="win32")throw Error("Windows-only");let t=ab();if(!Os(lt(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);tb(mt,{recursive:!0});let n=lt(mt,"extract.ps1");na(n,ub(t,e)),na(lt(mt,"inner_dpapi.ps1"),cb),na(lt(mt,"inner_cng.ps1"),lb);let s=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,o=sb("powershell",["-NoProfile","-Command",s],{encoding:"utf8",windowsHide:!0});if(o.status!==0&&o.error)throw Error(`Failed to launch elevated helper: ${o.error.message}`);let r=lt(mt,"out.bin"),i=lt(mt,"Cookies");if(!Os(r)||!Os(i)){let l=Os(lt(mt,"log.txt"))?ta(lt(mt,"log.txt"),"utf8").split(`
225
- `).filter((u)=>u.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${l?` (${l.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let l=ta(r),u=Os(lt(mt,"cng.bin"))?ta(lt(mt,"cng.bin")):void 0,c=db(l,u),{Database:a}=ps("bun:sqlite"),d=new a(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 p=Buffer.from(f.v);if(p.subarray(0,3).toString()!=="v20")throw Error(`unexpected cookie version ${p.subarray(0,3).toString("latin1")}`);let g=fb(c,p);if(!g.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return g}finally{if(!process.env.SLACK_KEEP_ABE)nb(mt,{recursive:!0,force:!0})}}var gb=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],mb=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function Qn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function yb(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:gb}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function bb(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:mb}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function Zt(e,t){return(await e.question(t)).trim()}async function Rs(e,t){if(t)return!0;if(!e)return!1;let n=await Zt(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function Fn(e,t,n,s){console.error("Verifying token...");let o=await Vn(t,s),r=Qn(o.team),i;if(n)i=n;else if(e)i=await Zt(e,`Workspace name [${r}]: `)||r;else i=r;let l=null;if(e){console.log(""),console.log("Where to save the token?"),console.log(" 1) ./.env.local (current directory) [default]"),console.log(" 2) ./.slack-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 u=await Zt(e,"Choice [1/2/3/4, Enter=1]: ");if(u==="2")l=sa(process.cwd(),".slack-term",".env.local");else if(u==="3")l=sa(hb(),".slack-term",".env.local");else if(u==="4")l=null;else l=sa(process.cwd(),".env.local")}if(l===null)if($o(i,{token:t,...o,...s?{cookie:s}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${o.team} (${o.user})`),process.env.SLACK_MCP_XOXP_TOKEN)console.log(""),console.log("Warning: SLACK_MCP_XOXP_TOKEN is set — it conflicts with profiles."),console.log(" Unset it: unset SLACK_MCP_XOXP_TOKEN (and remove from ~/.zshrc / ~/.bashrc)");else console.log(` Run: slack auth use -g ${i}`);else{let u={SLACK_TOKEN:t};if(s)u.SLACK_COOKIE=s;Ni(l,u),console.log(`Saved token to ${l}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return i}async function oa(e,t=!1,n="auto",s=!1){console.error("Scanning Slack desktop app...");let o=await Vi();if(o.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"&&o.some((r)=>!r.cookie)&&await Rs(e,t)){let r=[];if(n!=="chrome")for(let i of Bo())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 o)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(o.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await ra(o,e,s)}async function ra(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let s=e[0],o=s.teamName??s.teamId;console.log(`Found workspace: ${o}${s.cookie?" (+ xoxd cookie)":""}`),await Fn(t,s.token,Qn(o),s.cookie),console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- token: slack auth login");return}for(let s of e){let o=s.teamName??s.teamId,r=Qn(o);$o(r,{token:s.token,team:o,teamId:s.teamId,url:s.url??"",user:"",...s.cookie?{cookie:s.cookie}:{}}),console.log(`Added workspace "${r}": ${o}${s.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let s=Qn(e[0].teamName??e[0].teamId);console.log(`Run: slack auth use -g ${s}`)}else console.log("Run: slack auth ls then: slack auth use -g <name>");console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- user token by re-running: slack auth login")}async function kd(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 Zt(e,"Choice [1/2]: ")==="2"?"bot":"user",s=n==="user"?"xoxp-":"xoxb-",o=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 "${o}" (starts with ${s})`),console.log("");let r=await Zt(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 Fn(e,r)}async function Wo(e,t){let n=t==="user"?yb():bb(),s=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",o=t==="user"?"xoxp-":"xoxb-";if(t==="bot")console.log("Note: bot tokens cannot use search:read (user-only scope)."),console.log(" The news and search commands will not work with a bot token."),console.log("");console.log("Step 1 -Create your Slack app:"),console.log(" Open: https://api.slack.com/apps"),console.log(' Click "Create New App" -> "From a manifest" -> select your workspace'),console.log(" Paste this manifest (JSON tab):"),console.log(""),console.log("-------------------------------------------------------------"),console.log(n),console.log("-------------------------------------------------------------"),console.log(""),console.log('Step 2 -Install: "Install App" -> "Install to Workspace" -> Authorize'),console.log(""),console.log("Step 3 -Copy your token:"),console.log(` OAuth & Permissions -> ${s}`),console.log("");let r=await Zt(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 Fn(e,r)}async function wb(e,t){let n=Zi();if(n.length===0)console.error("No Slack session found in Chrome. Sign in to Slack in Chrome (app.slack.com) and retry."),process.exit(1);let s=e.profile.token.split("-")[1],o=n.find((r)=>r.sessions.some((i)=>i.teamId===s));if(!o&&t){if(o=n.find((r)=>r.email===t||r.profileDir===t||r.profileDir===`Profile ${t}`),!o)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((r)=>r.email??r.profileDir).join(", ")}`),process.exit(1)}if(!o)if(n.length===1)o=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((u,c)=>console.log(` ${c+1}) ${u.email??u.label} [${u.profileDir}]`));let r=Ye({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${n.length}]: `)).trim();r.close();let l=parseInt(i,10)-1;if(isNaN(l)||l<0||l>=n.length)console.error("Invalid choice."),process.exit(1);o=n[l]}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: ${o.email??o.label} [${o.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await Dd(o.profileDir)}catch(r){console.error(`
226
- 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 xd(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=_s();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((c,a)=>console.log(` ${a+1}) ${c.name} (${c.profile.team})`));let i=Ye({input:process.stdin,output:process.stdout}),l=(await i.question("Choice: ")).trim();i.close();let u=parseInt(l,10)-1;if(isNaN(u)||u<0||u>=t.length)console.error("Invalid choice."),process.exit(1);n=t[u].name}}let s=t.find((r)=>r.name===n);if(s.profile.token.startsWith("xoxb-")){console.error(`
224
+ `}function hb(e,t){let s=4+e.readUInt32LE(0)+4,o=e[s];if(o===1||o===2){let r=e.subarray(s+1,s+13),i=e.subarray(s+13,s+45),l=e.subarray(s+45,s+61),u=o===1?Wo("aes-256-gcm",ab,r):Wo("chacha20-poly1305",cb,r,{authTagLength:16});return u.setAuthTag(l),Buffer.concat([u.update(i),u.final()])}if(o===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let r=e.subarray(s+33,s+45),i=e.subarray(s+45,s+77),l=e.subarray(s+77,s+93),u=Buffer.from(t.map((a,d)=>a^lb[d])),c=Wo("aes-256-gcm",u,r);return c.setAuthTag(l),Buffer.concat([c.update(i),c.final()])}throw Error(`Unsupported app-bound key flag: ${o}`)}function gb(e,t){let n=t.subarray(3,15),s=t.subarray(15,t.length-16),o=t.subarray(t.length-16),r=Wo("aes-256-gcm",e,n);return r.setAuthTag(o),Buffer.concat([r.update(s),r.final()]).subarray(32).toString("utf8")}async function Sd(e){if(process.platform!=="win32")throw Error("Windows-only");let t=ub();if(!Os(lt(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);ob(mt,{recursive:!0});let n=lt(mt,"extract.ps1");oa(n,pb(t,e)),oa(lt(mt,"inner_dpapi.ps1"),db),oa(lt(mt,"inner_cng.ps1"),fb);let s=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,o=ib("powershell",["-NoProfile","-Command",s],{encoding:"utf8",windowsHide:!0});if(o.status!==0&&o.error)throw Error(`Failed to launch elevated helper: ${o.error.message}`);let r=lt(mt,"out.bin"),i=lt(mt,"Cookies");if(!Os(r)||!Os(i)){let l=Os(lt(mt,"log.txt"))?sa(lt(mt,"log.txt"),"utf8").split(`
225
+ `).filter((u)=>u.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${l?` (${l.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let l=sa(r),u=Os(lt(mt,"cng.bin"))?sa(lt(mt,"cng.bin")):void 0,c=hb(l,u),{Database:a}=ps("bun:sqlite"),d=new a(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 p=Buffer.from(f.v);if(p.subarray(0,3).toString()!=="v20")throw Error(`unexpected cookie version ${p.subarray(0,3).toString("latin1")}`);let g=gb(c,p);if(!g.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return g}finally{if(!process.env.SLACK_KEEP_ABE)rb(mt,{recursive:!0,force:!0})}}var bb=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],wb=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function Qn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Db(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:bb}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function kb(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:wb}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function Qt(e,t){return(await e.question(t)).trim()}async function Rs(e,t){if(t)return!0;if(!e)return!1;let n=await Qt(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function Fn(e,t,n,s){console.error("Verifying token...");let o=await Vn(t,s),r=Qn(o.team),i;if(n)i=n;else if(e)i=await Qt(e,`Workspace name [${r}]: `)||r;else i=r;let l=null;if(e){console.log(""),console.log("Where to save the token?"),console.log(" 1) ./.env.local (current directory) [default]"),console.log(" 2) ./.slack-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 u=await Qt(e,"Choice [1/2/3/4, Enter=1]: ");if(u==="2")l=ra(process.cwd(),".slack-term",".env.local");else if(u==="3")l=ra(yb(),".slack-term",".env.local");else if(u==="4")l=null;else l=ra(process.cwd(),".env.local")}if(l===null)if($o(i,{token:t,...o,...s?{cookie:s}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${o.team} (${o.user})`),process.env.SLACK_MCP_XOXP_TOKEN)console.log(""),console.log("Warning: SLACK_MCP_XOXP_TOKEN is set — it conflicts with profiles."),console.log(" Unset it: unset SLACK_MCP_XOXP_TOKEN (and remove from ~/.zshrc / ~/.bashrc)");else console.log(` Run: slack auth use -g ${i}`);else{let u={SLACK_TOKEN:t};if(s)u.SLACK_COOKIE=s;Mi(l,u),console.log(`Saved token to ${l}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return i}async function ia(e,t=!1,n="auto",s=!1){console.error("Scanning Slack desktop app...");let o=await Qi();if(o.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"&&o.some((r)=>!r.cookie)&&await Rs(e,t)){let r=[];if(n!=="chrome")for(let i of jo())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 o)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(o.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await aa(o,e,s)}async function aa(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let s=e[0],o=s.teamName??s.teamId;console.log(`Found workspace: ${o}${s.cookie?" (+ xoxd cookie)":""}`),await Fn(t,s.token,Qn(o),s.cookie),console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- token: slack auth login");return}for(let s of e){let o=s.teamName??s.teamId,r=Qn(o);$o(r,{token:s.token,team:o,teamId:s.teamId,url:s.url??"",user:"",...s.cookie?{cookie:s.cookie}:{}}),console.log(`Added workspace "${r}": ${o}${s.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let s=Qn(e[0].teamName??e[0].teamId);console.log(`Run: slack auth use -g ${s}`)}else console.log("Run: slack auth ls then: slack auth use -g <name>");console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- user token by re-running: slack auth login")}async function _d(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 Qt(e,"Choice [1/2]: ")==="2"?"bot":"user",s=n==="user"?"xoxp-":"xoxb-",o=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 "${o}" (starts with ${s})`),console.log("");let r=await Qt(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 Fn(e,r)}async function Jo(e,t){let n=t==="user"?Db():kb(),s=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",o=t==="user"?"xoxp-":"xoxb-";if(t==="bot")console.log("Note: bot tokens cannot use search:read (user-only scope)."),console.log(" The news and search commands will not work with a bot token."),console.log("");console.log("Step 1 -Create your Slack app:"),console.log(" Open: https://api.slack.com/apps"),console.log(' Click "Create New App" -> "From a manifest" -> select your workspace'),console.log(" Paste this manifest (JSON tab):"),console.log(""),console.log("-------------------------------------------------------------"),console.log(n),console.log("-------------------------------------------------------------"),console.log(""),console.log('Step 2 -Install: "Install App" -> "Install to Workspace" -> Authorize'),console.log(""),console.log("Step 3 -Copy your token:"),console.log(` OAuth & Permissions -> ${s}`),console.log("");let r=await Qt(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 Fn(e,r)}async function xb(e,t){let n=ea();if(n.length===0)console.error("No Slack session found in Chrome. Sign in to Slack in Chrome (app.slack.com) and retry."),process.exit(1);let s=e.profile.token.split("-")[1],o=n.find((r)=>r.sessions.some((i)=>i.teamId===s));if(!o&&t){if(o=n.find((r)=>r.email===t||r.profileDir===t||r.profileDir===`Profile ${t}`),!o)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((r)=>r.email??r.profileDir).join(", ")}`),process.exit(1)}if(!o)if(n.length===1)o=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((u,c)=>console.log(` ${c+1}) ${u.email??u.label} [${u.profileDir}]`));let r=Ye({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${n.length}]: `)).trim();r.close();let l=parseInt(i,10)-1;if(isNaN(l)||l<0||l>=n.length)console.error("Invalid choice."),process.exit(1);o=n[l]}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: ${o.email??o.label} [${o.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await Sd(o.profileDir)}catch(r){console.error(`
226
+ 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 Ed(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=_s();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((c,a)=>console.log(` ${a+1}) ${c.name} (${c.profile.team})`));let i=Ye({input:process.stdin,output:process.stdout}),l=(await i.question("Choice: ")).trim();i.close();let u=parseInt(l,10)-1;if(isNaN(u)||u<0||u>=t.length)console.error("Invalid choice."),process.exit(1);n=t[u].name}}let s=t.find((r)=>r.name===n);if(s.profile.token.startsWith("xoxb-")){console.error(`
227
227
  Workspace "${n}" uses a bot token (xoxb-). A Chrome session cookie only
228
228
  `+`augments a user session token (xoxc-) — it has no effect on a bot token, so user-level
229
- `+"actions (tail @user, DMs, listing users) would still fail.");let 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 o;if(process.platform==="win32")o=await wb(s,e.profile);else{if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let r=e.yes?void 0:Ye({input:process.stdin,output:process.stdout});try{if(!await Rs(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,l;try{({candidates:i,totalProfiles:l}=Ts())}catch(u){console.error(`Failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${l} profile${l!==1?"s":""}). Possible reasons:`),console.error(" - You denied the keychain dialog (try running again and click Allow)"),console.error(" - Chrome is not installed or has no Slack session"),console.error(" - You're not logged in to Slack in Chrome"),process.exit(1);if(i.length===1&&l<=1)o=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let u=i.length===1?`Found 1 Slack session across ${l} Chrome profiles:`:`Found ${i.length} Slack sessions across ${l} Chrome profiles:`;console.log(u),i.forEach((p,g)=>console.log(` ${g+1}) ${p.profileName} [${p.profileDir}]`)),console.log("");let c=Ye({input:process.stdin,output:process.stdout}),a=i.length===1?" [Enter=1]":"",d=(await c.question(`Choice [1-${i.length}]${a}: `)).trim();c.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);o=i[f].cookie}}Mi(n,o),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function ia(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=Zi();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((l)=>l.email===r||l.profileDir===r||l.profileDir===`Profile ${r}`);if(!i)console.error(`Chrome profile "${r}" has no Slack session. Available:`),t.forEach((l)=>console.error(` - ${l.email??l.label} [${l.profileDir}] (${l.sessions.length} workspace${l.sessions.length!==1?"s":""})`)),process.exit(1);n=i}else if(t.length===1)n=t[0];else if(process.stdin.isTTY){console.log("Found Slack sessions in multiple Chrome profiles:"),t.forEach((u,c)=>console.log(` ${c+1}) ${u.email??u.label} [${u.profileDir}] (${u.sessions.length} workspace${u.sessions.length!==1?"s":""})`));let r=Ye({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${t.length}]: `)).trim();r.close();let l=parseInt(i,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),t.forEach((r)=>console.error(` slack auth login chrome --profile "${r.email??r.profileDir}"`)),process.exit(1);let s=n.email??n.label??n.profileDir,o;if(process.platform==="darwin")try{let{candidates:r}=Ts();o=r.find((i)=>i.profileDir===n.profileDir)?.cookie??r[0]?.cookie}catch{}if(o)qu(s,o,`chrome:${n.profileDir}`);for(let r of n.sessions){let i=r.teamName??r.teamId,l=Qn(i);$o(l,{token:r.token,team:i,teamId:r.teamId,url:r.url??"",user:"",identity:s}),console.log(`Added workspace "${l}": ${i} (identity: ${s})`)}if(console.log(""),o)console.log(`Captured xoxd cookie for ${s} — shared across its ${n.sessions.length} workspace(s).`),console.log("RTM WebSocket mode is now available: slack tail @you");else console.log("Note: no xoxd cookie captured (LocalStorage yields the token only; the cookie is"),console.log("encrypted at rest on this platform). Some features (RTM, drafts, search fallback) need it."),console.log(" Attach it from your live browser — e.g. a CDP read via rech — or paste it:"),console.log(` slack auth cookie --workspace ${Qn(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 aa(e={}){let t=_s();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((l)=>l.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((l)=>l.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let i=t.find((l)=>l.current);if(i)n=i.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((a,d)=>console.log(` ${d+1}) ${a.name} (${a.profile.team})`));let l=Ye({input:process.stdin,output:process.stdout}),u=(await l.question("Choice: ")).trim();l.close();let c=parseInt(u,10)-1;if(isNaN(c)||c<0||c>=t.length)console.error("Invalid choice."),process.exit(1);n=t[c].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let s=e.yes?void 0:Ye({input:process.stdin,output:process.stdout});try{if(!await Rs(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{s?.close()}console.log("Scanning Firefox profiles for Slack session...");let o=Bo();if(o.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(o.length===1)r=o[0].cookie,console.log(`Found session in Firefox profile: ${o[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),o.forEach((c,a)=>console.log(` ${a+1}) ${c.profileName} [${c.profileDir}]`));let i=Ye({input:process.stdin,output:process.stdout}),l=(await i.question("Choice: ")).trim();i.close();let u=parseInt(l,10)-1;if(isNaN(u)||u<0||u>=o.length)console.error("Invalid choice."),process.exit(1);r=o[u].cookie}Mi(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Sd(e={}){if(e.token){await Fn(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let o of process.stdin)n.push(o);let s=Buffer.concat(n).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await Fn(null,s,e.name);return}let t=Ye({input:process.stdin,output:process.stdout});try{await kd(t)}finally{t.close()}}async function _d(e={}){let t=Ye({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await Wo(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 Zt(t,"Choice [1/2, Enter=1]: ");await Wo(t,n==="2"?"bot":"user")}finally{t.close()}}function Ed(e={}){let t=(o,r)=>{if(/[\r\n]/.test(r))throw Error(`Invalid newline in ${o}.`);return`${o}=${/^[A-Za-z0-9._=-]+$/.test(r)?r:JSON.stringify(r)}`},n=[t("SLACK_TOKEN",Hu(e.workspace))],s=Vt(e.workspace);if(s)n.push(t("SLACK_COOKIE",s));if(!e.workspace){let o=Co();if(o)n.push(t("SLACK_BOT_TOKEN",o))}console.log(n.join(`
230
- `))}function $d(e){let t=_s(),n=e.workspace?t.find((o)=>o.name===e.workspace):t.find((o)=>o.current)??(t.length===1?t[0]:void 0);if(!n)throw Error(e.workspace?`Workspace "${e.workspace}" not found. Run: slack auth ls`:"Select a workspace with slack auth use <name>, or pass --workspace <name>.");if(!n.profile.cookie)throw Error(`Workspace "${n.name}" has no session cookie. Run: slack auth chrome -w ${n.name} or slack auth firefox -w ${n.name}`);let s=pb(e.envfile);Ni(s,{SLACK_TOKEN:n.profile.token,SLACK_COOKIE:n.profile.cookie}),console.log(`Saved token and cookie for workspace "${n.name}" to ${s}`)}async function Is(e={}){let t=_s();if(t.length>0){console.log("Currently logged in:");for(let{name:s,profile:o,current:r}of t)console.log(` ${r?"*":" "} ${s} ${o.team} (${o.user||"unknown"})`);console.log(""),console.log("Adding another workspace:"),console.log("")}if([e.fromChrome,e.fromFirefox,e.fromAll].filter(Boolean).length>1)throw Error("Choose only one browser source: --from-chrome, --from-firefox, or --from-all.");if(e.fromChrome&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{if(!await Rs(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let o=await ea();if(o.length===0)throw Error("No Slack session token found in Chrome profiles.");await ra(o,s,!0)}finally{s?.close()}return}if(e.fromAll&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{try{await oa(s,e.yes??!1,"all",!0)}catch(o){if(!(o instanceof Error)||!o.message.startsWith("Slack desktop app LevelDB not found"))throw o;if(!await Rs(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await ea();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");if(r.every((i)=>!i.cookie)){let i=Bo();if(i.length===1)for(let l of r)l.cookie=i[0].cookie}await ra(r,s,!0)}}finally{s?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let s=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(s!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{await oa(o,e.yes??!1,s,!0)}finally{o?.close()}return}if(e.token){await Fn(null,e.token,e.name);return}if(!process.stdin.isTTY){let s=[];for await(let r of process.stdin)s.push(r);let o=Buffer.concat(s).toString("utf8").trim();if(!o)console.error("No token provided on stdin."),process.exit(1);await Fn(null,o,e.name);return}console.log("How would you like to authenticate with Slack?"),console.log(""),console.log(" 1) Slack desktop app - import session token"),console.log(" Reads the xoxc- token directly from the installed app."),console.log(" Token: all platforms | xoxd cookie: macOS, or Chrome/Firefox on Linux"),console.log(""),console.log(" 2) Chrome browser - import workspaces"),console.log(" Reads xoxc- tokens from Chrome, grouped by account."),console.log(" Token: all platforms | xoxd cookie: macOS only"),console.log(""),console.log(" 3) Connect existing Slack app [recommended if you have one]"),console.log(" Paste a token from an app you already created."),console.log(""),console.log(" 4) Create new Slack app - user token (xoxp-)"),console.log(" Guided setup with manifest. Full access including search."),console.log(""),console.log(" 5) Create new Slack app - bot token (xoxb-)"),console.log(" Bot is invited to channels. Search and news unavailable."),console.log("");let n=Ye({input:process.stdin,output:process.stdout});try{let s=await Zt(n,"Choice [1/2/3/4/5]: ");if(console.log(""),s==="1")await oa(n,e.yes??!1);else if(s==="2"){n.close(),await ia();return}else if(s==="3")await kd(n);else if(s==="4")await Wo(n,"user");else if(s==="5")await Wo(n,"bot");else console.error(`Invalid choice: "${s}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function Jo(e,t,n,s){let o=t,r=[],i=o,l=0;while(!0){let u=i.indexOf("<@U",l);if(u===-1)break;let c=i.slice(u+2),a=c.search(/[>|]/),d=a===-1?c:c.slice(0,a);if(d.length>=9)r.push(d);l=u+1}for(let u of r){if(!n.has(u))n.set(u,await Zn(e,u,s));let c=n.get(u)??u;o=o.replaceAll(`<@${u}>`,`@${c}`),o=o.replace(new RegExp(`<@${u}\\|[^>]*>`,"g"),`@${c}`)}return o}function Uo(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let o=Number(n);if(!Number.isFinite(o))return s??"date";let r=new Date(o*1000);if(Number.isNaN(r.getTime()))return s??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=i[r.getUTCDay()]??"",c=l[r.getUTCMonth()]??"";return`${u}, ${c} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function Ad(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Db(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),o=s.getUTCFullYear(),r=String(s.getUTCMonth()+1).padStart(2,"0"),i=String(s.getUTCDate()).padStart(2,"0"),l=String(s.getUTCHours()).padStart(2,"0"),u=String(s.getUTCMinutes()).padStart(2,"0"),c=String(s.getUTCSeconds()).padStart(2,"0"),a=n.padEnd(6,"0").slice(0,6);return`${o}-${r}-${i}T${l}:${u}:${c}.${a}`}async function kb(e,t,n){let s=typeof t.ts==="string"?t.ts:"0.000000",o=Db(s),r="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,p]=await Io(e,d);n.set(f,p)}r=n.get(f)??d}else if(typeof t.username==="string")r=t.username;let i=typeof t.text==="string"?t.text:"",u=Uo(await Jo(e,i,n)).split(`
229
+ `+"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 o;if(process.platform==="win32")o=await xb(s,e.profile);else{if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let r=e.yes?void 0:Ye({input:process.stdin,output:process.stdout});try{if(!await Rs(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,l;try{({candidates:i,totalProfiles:l}=Ts())}catch(u){console.error(`Failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${l} profile${l!==1?"s":""}). Possible reasons:`),console.error(" - You denied the keychain dialog (try running again and click Allow)"),console.error(" - Chrome is not installed or has no Slack session"),console.error(" - You're not logged in to Slack in Chrome"),process.exit(1);if(i.length===1&&l<=1)o=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let u=i.length===1?`Found 1 Slack session across ${l} Chrome profiles:`:`Found ${i.length} Slack sessions across ${l} Chrome profiles:`;console.log(u),i.forEach((p,g)=>console.log(` ${g+1}) ${p.profileName} [${p.profileDir}]`)),console.log("");let c=Ye({input:process.stdin,output:process.stdout}),a=i.length===1?" [Enter=1]":"",d=(await c.question(`Choice [1-${i.length}]${a}: `)).trim();c.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);o=i[f].cookie}}Bi(n,o),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function ca(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=ea();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((l)=>l.email===r||l.profileDir===r||l.profileDir===`Profile ${r}`);if(!i)console.error(`Chrome profile "${r}" has no Slack session. Available:`),t.forEach((l)=>console.error(` - ${l.email??l.label} [${l.profileDir}] (${l.sessions.length} workspace${l.sessions.length!==1?"s":""})`)),process.exit(1);n=i}else if(t.length===1)n=t[0];else if(process.stdin.isTTY){console.log("Found Slack sessions in multiple Chrome profiles:"),t.forEach((u,c)=>console.log(` ${c+1}) ${u.email??u.label} [${u.profileDir}] (${u.sessions.length} workspace${u.sessions.length!==1?"s":""})`));let r=Ye({input:process.stdin,output:process.stdout}),i=(await r.question(`Choice [1-${t.length}]: `)).trim();r.close();let l=parseInt(i,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),t.forEach((r)=>console.error(` slack auth login chrome --profile "${r.email??r.profileDir}"`)),process.exit(1);let s=n.email??n.label??n.profileDir,o;if(process.platform==="darwin")try{let{candidates:r}=Ts();o=r.find((i)=>i.profileDir===n.profileDir)?.cookie??r[0]?.cookie}catch{}if(o)Xu(s,o,`chrome:${n.profileDir}`);for(let r of n.sessions){let i=r.teamName??r.teamId,l=Qn(i);$o(l,{token:r.token,team:i,teamId:r.teamId,url:r.url??"",user:"",identity:s}),console.log(`Added workspace "${l}": ${i} (identity: ${s})`)}if(console.log(""),o)console.log(`Captured xoxd cookie for ${s} — shared across its ${n.sessions.length} workspace(s).`),console.log("RTM WebSocket mode is now available: slack tail @you");else console.log("Note: no xoxd cookie captured (LocalStorage yields the token only; the cookie is"),console.log("encrypted at rest on this platform). Some features (RTM, drafts, search fallback) need it."),console.log(" Attach it from your live browser — e.g. a CDP read via rech — or paste it:"),console.log(` slack auth cookie --workspace ${Qn(n.sessions[0].teamName??n.sessions[0].teamId)}`);console.log(""),console.log("Select a workspace: slack auth use <name> (see: slack auth ls)")}async function la(e={}){let t=_s();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((l)=>l.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((l)=>l.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let i=t.find((l)=>l.current);if(i)n=i.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((a,d)=>console.log(` ${d+1}) ${a.name} (${a.profile.team})`));let l=Ye({input:process.stdin,output:process.stdout}),u=(await l.question("Choice: ")).trim();l.close();let c=parseInt(u,10)-1;if(isNaN(c)||c<0||c>=t.length)console.error("Invalid choice."),process.exit(1);n=t[c].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let s=e.yes?void 0:Ye({input:process.stdin,output:process.stdout});try{if(!await Rs(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{s?.close()}console.log("Scanning Firefox profiles for Slack session...");let o=jo();if(o.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(o.length===1)r=o[0].cookie,console.log(`Found session in Firefox profile: ${o[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),o.forEach((c,a)=>console.log(` ${a+1}) ${c.profileName} [${c.profileDir}]`));let i=Ye({input:process.stdin,output:process.stdout}),l=(await i.question("Choice: ")).trim();i.close();let u=parseInt(l,10)-1;if(isNaN(u)||u<0||u>=o.length)console.error("Invalid choice."),process.exit(1);r=o[u].cookie}Bi(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function $d(e={}){if(e.token){await Fn(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let o of process.stdin)n.push(o);let s=Buffer.concat(n).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await Fn(null,s,e.name);return}let t=Ye({input:process.stdin,output:process.stdout});try{await _d(t)}finally{t.close()}}async function Cd(e={}){let t=Ye({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await Jo(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 Qt(t,"Choice [1/2, Enter=1]: ");await Jo(t,n==="2"?"bot":"user")}finally{t.close()}}function Ad(e={}){let t=(o,r)=>{if(/[\r\n]/.test(r))throw Error(`Invalid newline in ${o}.`);return`${o}=${/^[A-Za-z0-9._=-]+$/.test(r)?r:JSON.stringify(r)}`},n=[t("SLACK_TOKEN",Vu(e.workspace))],s=Zt(e.workspace);if(s)n.push(t("SLACK_COOKIE",s));if(!e.workspace){let o=Co();if(o)n.push(t("SLACK_BOT_TOKEN",o))}console.log(n.join(`
230
+ `))}function Fd(e){let t=_s(),n=e.workspace?t.find((o)=>o.name===e.workspace):t.find((o)=>o.current)??(t.length===1?t[0]:void 0);if(!n)throw Error(e.workspace?`Workspace "${e.workspace}" not found. Run: slack auth ls`:"Select a workspace with slack auth use <name>, or pass --workspace <name>.");if(!n.profile.cookie)throw Error(`Workspace "${n.name}" has no session cookie. Run: slack auth chrome -w ${n.name} or slack auth firefox -w ${n.name}`);let s=mb(e.envfile);Mi(s,{SLACK_TOKEN:n.profile.token,SLACK_COOKIE:n.profile.cookie}),console.log(`Saved token and cookie for workspace "${n.name}" to ${s}`)}async function Is(e={}){let t=_s();if(t.length>0){console.log("Currently logged in:");for(let{name:s,profile:o,current:r}of t)console.log(` ${r?"*":" "} ${s} ${o.team} (${o.user||"unknown"})`);console.log(""),console.log("Adding another workspace:"),console.log("")}if([e.fromChrome,e.fromFirefox,e.fromAll].filter(Boolean).length>1)throw Error("Choose only one browser source: --from-chrome, --from-firefox, or --from-all.");if(e.fromChrome&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{if(!await Rs(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let o=await na();if(o.length===0)throw Error("No Slack session token found in Chrome profiles.");await aa(o,s,!0)}finally{s?.close()}return}if(e.fromAll&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{try{await ia(s,e.yes??!1,"all",!0)}catch(o){if(!(o instanceof Error)||!o.message.startsWith("Slack desktop app LevelDB not found"))throw o;if(!await Rs(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await na();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");if(r.every((i)=>!i.cookie)){let i=jo();if(i.length===1)for(let l of r)l.cookie=i[0].cookie}await aa(r,s,!0)}}finally{s?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let s=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(s!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{await ia(o,e.yes??!1,s,!0)}finally{o?.close()}return}if(e.token){await Fn(null,e.token,e.name);return}if(!process.stdin.isTTY){let s=[];for await(let r of process.stdin)s.push(r);let o=Buffer.concat(s).toString("utf8").trim();if(!o)console.error("No token provided on stdin."),process.exit(1);await Fn(null,o,e.name);return}console.log("How would you like to authenticate with Slack?"),console.log(""),console.log(" 1) Slack desktop app - import session token"),console.log(" Reads the xoxc- token directly from the installed app."),console.log(" Token: all platforms | xoxd cookie: macOS, or Chrome/Firefox on Linux"),console.log(""),console.log(" 2) Chrome browser - import workspaces"),console.log(" Reads xoxc- tokens from Chrome, grouped by account."),console.log(" Token: all platforms | xoxd cookie: macOS only"),console.log(""),console.log(" 3) Connect existing Slack app [recommended if you have one]"),console.log(" Paste a token from an app you already created."),console.log(""),console.log(" 4) Create new Slack app - user token (xoxp-)"),console.log(" Guided setup with manifest. Full access including search."),console.log(""),console.log(" 5) Create new Slack app - bot token (xoxb-)"),console.log(" Bot is invited to channels. Search and news unavailable."),console.log("");let n=Ye({input:process.stdin,output:process.stdout});try{let s=await Qt(n,"Choice [1/2/3/4/5]: ");if(console.log(""),s==="1")await ia(n,e.yes??!1);else if(s==="2"){n.close(),await ca();return}else if(s==="3")await _d(n);else if(s==="4")await Jo(n,"user");else if(s==="5")await Jo(n,"bot");else console.error(`Invalid choice: "${s}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function Uo(e,t,n,s){let o=t,r=[],i=o,l=0;while(!0){let u=i.indexOf("<@U",l);if(u===-1)break;let c=i.slice(u+2),a=c.search(/[>|]/),d=a===-1?c:c.slice(0,a);if(d.length>=9)r.push(d);l=u+1}for(let u of r){if(!n.has(u))n.set(u,await Zn(e,u,s));let c=n.get(u)??u;o=o.replaceAll(`<@${u}>`,`@${c}`),o=o.replace(new RegExp(`<@${u}\\|[^>]*>`,"g"),`@${c}`)}return o}function Ko(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let o=Number(n);if(!Number.isFinite(o))return s??"date";let r=new Date(o*1000);if(Number.isNaN(r.getTime()))return s??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=i[r.getUTCDay()]??"",c=l[r.getUTCMonth()]??"";return`${u}, ${c} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function Od(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Sb(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),o=s.getUTCFullYear(),r=String(s.getUTCMonth()+1).padStart(2,"0"),i=String(s.getUTCDate()).padStart(2,"0"),l=String(s.getUTCHours()).padStart(2,"0"),u=String(s.getUTCMinutes()).padStart(2,"0"),c=String(s.getUTCSeconds()).padStart(2,"0"),a=n.padEnd(6,"0").slice(0,6);return`${o}-${r}-${i}T${l}:${u}:${c}.${a}`}async function _b(e,t,n){let s=typeof t.ts==="string"?t.ts:"0.000000",o=Sb(s),r="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,p]=await Io(e,d);n.set(f,p)}r=n.get(f)??d}else if(typeof t.username==="string")r=t.username;let i=typeof t.text==="string"?t.text:"",u=Ko(await Uo(e,i,n)).split(`
231
231
  `),c=u[0]+(u.length>1?`
232
232
  `+u.slice(1).map((d)=>` ${d}`).join(`
233
- `):""),a=Ad(t)?"↳ ":"";return`${o} ${a}@${r}: ${c}`}async function xb(e,t,n,s,o,r,i,l){if(l?.aborted)return;return new Promise((u)=>{let c=new e(n);l?.addEventListener("abort",()=>{c.close(),u()},{once:!0}),c.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
234
- `)}),c.addEventListener("close",()=>u()),c.addEventListener("error",()=>u()),c.addEventListener("message",(a)=>{(async()=>{try{let d;try{d=JSON.parse(String(a.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){c.send(JSON.stringify({type:"pong",reply_to:d.id??0}));return}if(f!=="message")return;if((typeof d.channel==="string"?d.channel:"")!==s)return;let g=typeof d.ts==="string"?d.ts:"";if(!g||r.has(g))return;let h=typeof d.subtype==="string"?d.subtype:"";if(h==="message_changed"||h==="message_deleted")return;if(o.thread){if((typeof d.thread_ts==="string"?d.thread_ts:g)!==o.thread&&g!==o.thread)return}if(o.watchThread&&Ad(d)){if((typeof d.thread_ts==="string"?d.thread_ts:"")!==o.watchThread)return}if(o.me&&o.myUserId){if(!(typeof d.text==="string"?d.text:"").includes(`<@${o.myUserId}>`))return}if(r.add(g),r.size>1000){let y=r.values().next().value;if(y!==void 0)r.delete(y)}let m=await kb(t,d,i);process.stdout.write(m+`
233
+ `):""),a=Od(t)?"↳ ":"";return`${o} ${a}@${r}: ${c}`}async function Eb(e,t,n,s,o,r,i,l){if(l?.aborted)return;return new Promise((u)=>{let c=new e(n);l?.addEventListener("abort",()=>{c.close(),u()},{once:!0}),c.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
234
+ `)}),c.addEventListener("close",()=>u()),c.addEventListener("error",()=>u()),c.addEventListener("message",(a)=>{(async()=>{try{let d;try{d=JSON.parse(String(a.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){c.send(JSON.stringify({type:"pong",reply_to:d.id??0}));return}if(f!=="message")return;if((typeof d.channel==="string"?d.channel:"")!==s)return;let g=typeof d.ts==="string"?d.ts:"";if(!g||r.has(g))return;let h=typeof d.subtype==="string"?d.subtype:"";if(h==="message_changed"||h==="message_deleted")return;if(o.thread){if((typeof d.thread_ts==="string"?d.thread_ts:g)!==o.thread&&g!==o.thread)return}if(o.watchThread&&Od(d)){if((typeof d.thread_ts==="string"?d.thread_ts:"")!==o.watchThread)return}if(o.me&&o.myUserId){if(!(typeof d.text==="string"?d.text:"").includes(`<@${o.myUserId}>`))return}if(r.add(g),r.size>1000){let y=r.values().next().value;if(y!==void 0)r.delete(y)}let m=await _b(t,d,i);process.stdout.write(m+`
235
235
  `)}catch(d){process.stderr.write(`RTM message error: ${d instanceof Error?d.message:String(d)}
236
- `)}})()})})}var Cd=3,Sb=2000,ca={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:cd,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function Fd(e,t,n,s,o,r,i){let l=ca.getWebSocket();if(!l)return;for(let u=0;u<Cd;u++){if(i?.aborted)return;try{let{wsUrl:c}=await ca.clientBoot(e,t);await xb(l,e,c,n,s,o,r,i)}catch{}if(i?.aborted)return;if(u<Cd-1)await ca.sleep(Sb)}}function Qt(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 yt={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:Fd};function Rt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function la(e){return Array.isArray(e)?e:[]}function Td(e){return Number(e)||0}function Od(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function _b(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),o=s.getUTCFullYear(),r=String(s.getUTCMonth()+1).padStart(2,"0"),i=String(s.getUTCDate()).padStart(2,"0"),l=String(s.getUTCHours()).padStart(2,"0"),u=String(s.getUTCMinutes()).padStart(2,"0"),c=String(s.getUTCSeconds()).padStart(2,"0"),a=n.padEnd(6,"0").slice(0,6);return`${o}-${r}-${i}T${l}:${u}:${c}.${a}`}async function Eb(e,t,n,s,o){let r=typeof t.ts==="string"?t.ts:"0.000000",i=_b(r),l="?";if(typeof t.user==="string"){let g=t.user,h="@"+g;if(!n.has(h)){let[,m]=await Io(e,g,o);n.set(h,m)}l=n.get(h)??g}else if(typeof t.username==="string")l=t.username;let u=typeof t.text==="string"?t.text:"",a=Uo(await Jo(e,u,n,o)).split(`
236
+ `)}})()})})}var Td=3,$b=2000,ua={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:dd,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function Rd(e,t,n,s,o,r,i){let l=ua.getWebSocket();if(!l)return;for(let u=0;u<Td;u++){if(i?.aborted)return;try{let{wsUrl:c}=await ua.clientBoot(e,t);await Eb(l,e,c,n,s,o,r,i)}catch{}if(i?.aborted)return;if(u<Td-1)await ua.sleep($b)}}function en(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 yt={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:Rd};function It(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function da(e){return Array.isArray(e)?e:[]}function Id(e){return Number(e)||0}function vd(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Cb(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),o=s.getUTCFullYear(),r=String(s.getUTCMonth()+1).padStart(2,"0"),i=String(s.getUTCDate()).padStart(2,"0"),l=String(s.getUTCHours()).padStart(2,"0"),u=String(s.getUTCMinutes()).padStart(2,"0"),c=String(s.getUTCSeconds()).padStart(2,"0"),a=n.padEnd(6,"0").slice(0,6);return`${o}-${r}-${i}T${l}:${u}:${c}.${a}`}async function Ab(e,t,n,s,o){let r=typeof t.ts==="string"?t.ts:"0.000000",i=Cb(r),l="?";if(typeof t.user==="string"){let g=t.user,h="@"+g;if(!n.has(h)){let[,m]=await Io(e,g,o);n.set(h,m)}l=n.get(h)??g}else if(typeof t.username==="string")l=t.username;let u=typeof t.text==="string"?t.text:"",a=Ko(await Uo(e,u,n,o)).split(`
237
237
  `),d=a[0]+(a.length>1?`
238
238
  `+a.slice(1).map((g)=>` ${g}`).join(`
239
- `):""),f=Od(t)?"↳ ":"",p=s?`${s} @${l}`:`@${l}`;return`${i} ${f}${p}: ${d}`}async function $b(e,t,n,s,o,r,i){let l=Rt(await An(e,t,20,i?void 0:n||void 0,i,s.cookie)),u=la(l.messages).map(Rt).reverse(),c=Rt(l.response_metadata),a=l.has_more===!0&&typeof c.next_cursor==="string"?c.next_cursor:void 0,d=[];if(s.watchThread&&!i){let m=Rt(await td(e,t,s.watchThread,50,s.cookie));d=la(m.messages).map(Rt).filter((y)=>(typeof y.ts==="string"?y.ts:"")!==s.watchThread)}let f=[...u.map((m)=>({m,fromHistory:!0})),...d.map((m)=>({m,fromHistory:!1}))].sort((m,y)=>Td(typeof m.m.ts==="string"?m.m.ts:"")-Td(typeof y.m.ts==="string"?y.m.ts:"")),p=[],g=n,h=!1;for(let{m,fromHistory:y}of f){let w=typeof m.ts==="string"?m.ts:"";if(!w||o.has(w))continue;let x=typeof m.subtype==="string"?m.subtype:"";if(x==="message_changed"||x==="message_deleted")continue;if(s.thread){if((typeof m.thread_ts==="string"?m.thread_ts:w)!==s.thread&&w!==s.thread)continue}if(s.watchThread&&Od(m)){if((typeof m.thread_ts==="string"?m.thread_ts:"")!==s.watchThread)continue}if(s.me&&s.myUserId){if(!(typeof m.text==="string"?m.text:"").includes(`<@${s.myUserId}>`))continue}if(o.add(w),o.size>1000){let E=o.values().next().value;if(E!==void 0)o.delete(E)}if(p.push(await Eb(e,m,r,void 0,s.cookie)),y)g=w;let D=typeof m.user==="string"?m.user:"";if(!s.myUserId||D!==s.myUserId)h=!0}return{newCursor:g,lines:p,hasMore:l.has_more===!0,nextPageCursor:a,emittedOther:h}}function Cb(e){if(e.includes("slack.com")){let t=qi(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 Rd(e,t,n={},s){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
239
+ `):""),f=vd(t)?"↳ ":"",p=s?`${s} @${l}`:`@${l}`;return`${i} ${f}${p}: ${d}`}async function Fb(e,t,n,s,o,r,i){let l=It(await An(e,t,20,i?void 0:n||void 0,i,s.cookie)),u=da(l.messages).map(It).reverse(),c=It(l.response_metadata),a=l.has_more===!0&&typeof c.next_cursor==="string"?c.next_cursor:void 0,d=[];if(s.watchThread&&!i){let m=It(await id(e,t,s.watchThread,50,s.cookie));d=da(m.messages).map(It).filter((y)=>(typeof y.ts==="string"?y.ts:"")!==s.watchThread)}let f=[...u.map((m)=>({m,fromHistory:!0})),...d.map((m)=>({m,fromHistory:!1}))].sort((m,y)=>Id(typeof m.m.ts==="string"?m.m.ts:"")-Id(typeof y.m.ts==="string"?y.m.ts:"")),p=[],g=n,h=!1;for(let{m,fromHistory:y}of f){let w=typeof m.ts==="string"?m.ts:"";if(!w||o.has(w))continue;let x=typeof m.subtype==="string"?m.subtype:"";if(x==="message_changed"||x==="message_deleted")continue;if(s.thread){if((typeof m.thread_ts==="string"?m.thread_ts:w)!==s.thread&&w!==s.thread)continue}if(s.watchThread&&vd(m)){if((typeof m.thread_ts==="string"?m.thread_ts:"")!==s.watchThread)continue}if(s.me&&s.myUserId){if(!(typeof m.text==="string"?m.text:"").includes(`<@${s.myUserId}>`))continue}if(o.add(w),o.size>1000){let E=o.values().next().value;if(E!==void 0)o.delete(E)}if(p.push(await Ab(e,m,r,void 0,s.cookie)),y)g=w;let D=typeof m.user==="string"?m.user:"";if(!s.myUserId||D!==s.myUserId)h=!0}return{newCursor:g,lines:p,hasMore:l.has_more===!0,nextPageCursor:a,emittedOther:h}}function Tb(e){if(e.includes("slack.com")){let t=zi(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 Pd(e,t,n={},s){if(n.me&&!t)console.error(`slack tail --me requires a <target> channel.
240
240
  Cross-channel mention streaming is not yet supported.
241
- Use: slack tail "#channel" --me`),process.exit(1);if(!t)console.error("Usage: slack tail <#channel|@user>\n Run `slack tail --help` for details."),process.exit(1);let o=await Ro(e,t,n.cookie),r=n.interval??60000,i=n.timeout?yt.now()+Qt(n.timeout)*1000:1/0,l=new Map,u=new Set;try{let h=Rt(await ad(e,o,n.cookie));if(Rt(h.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(h){let m=h instanceof Error?h.message:String(h);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 c="";if(n.since){let h=Qt(n.since);c=(yt.now()/1000-h).toFixed(6)}else{let h=Rt(await An(e,o,1,void 0,void 0,n.cookie)),m=la(h.messages).map(Rt);if(m.length>0&&typeof m[0]?.ts==="string")c=m[0].ts,u.add(c);else c=(yt.now()/1000).toFixed(6)}let a;if(n.me||n.exitOnMessage)a=(await Vn(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=Cb(n.watchThread)}catch(h){console.error(h instanceof Error?h.message:String(h)),process.exit(1)}let f={...n.thread!==void 0?{thread:n.thread}:{},...d!==void 0?{watchThread:d}:{},...n.me!==void 0?{me:n.me}:{},...a!==void 0?{myUserId:a}:{},...n.cookie!==void 0?{cookie:n.cookie}:{}};if(e.startsWith("xoxc-")&&n.cookie!==void 0&&n.noRtm!==!0&&n.since===void 0&&n.timeout===void 0&&n.exitOnMessage!==!0){if(await yt.tailRTM(e,n.cookie,o,f,u,l,s),s?.aborted)return;console.error("RTM unavailable — switching to polling.")}let p=!0,g=yt.now();while(!s?.aborted){if(yt.now()>=i)return;let h=!1;try{let w=yt.now()-g,x=r>0&&w>r*5,D,E=!0;do{let{newCursor:C,lines:S,nextPageCursor:k,emittedOther:O}=await $b(e,o,c,f,u,l,D);if(c=C,p&&E&&n.since&&S.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
241
+ Use: slack tail "#channel" --me`),process.exit(1);if(!t)console.error("Usage: slack tail <#channel|@user>\n Run `slack tail --help` for details."),process.exit(1);let o=await Ro(e,t,n.cookie),r=n.interval??60000,i=n.timeout?yt.now()+en(n.timeout)*1000:1/0,l=new Map,u=new Set;try{let h=It(await Po(e,o,n.cookie));if(It(h.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(h){let m=h instanceof Error?h.message:String(h);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 c="";if(n.since){let h=en(n.since);c=(yt.now()/1000-h).toFixed(6)}else{let h=It(await An(e,o,1,void 0,void 0,n.cookie)),m=da(h.messages).map(It);if(m.length>0&&typeof m[0]?.ts==="string")c=m[0].ts,u.add(c);else c=(yt.now()/1000).toFixed(6)}let a;if(n.me||n.exitOnMessage)a=(await Vn(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=Tb(n.watchThread)}catch(h){console.error(h instanceof Error?h.message:String(h)),process.exit(1)}let f={...n.thread!==void 0?{thread:n.thread}:{},...d!==void 0?{watchThread:d}:{},...n.me!==void 0?{me:n.me}:{},...a!==void 0?{myUserId:a}:{},...n.cookie!==void 0?{cookie:n.cookie}:{}};if(e.startsWith("xoxc-")&&n.cookie!==void 0&&n.noRtm!==!0&&n.since===void 0&&n.timeout===void 0&&n.exitOnMessage!==!0){if(await yt.tailRTM(e,n.cookie,o,f,u,l,s),s?.aborted)return;console.error("RTM unavailable — switching to polling.")}let p=!0,g=yt.now();while(!s?.aborted){if(yt.now()>=i)return;let h=!1;try{let w=yt.now()-g,x=r>0&&w>r*5,D,E=!0;do{let{newCursor:C,lines:S,nextPageCursor:k,emittedOther:O}=await Fb(e,o,c,f,u,l,D);if(c=C,p&&E&&n.since&&S.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
242
242
  `);E=!1;for(let P of S)process.stdout.write(P+`
243
- `);if(O)h=!0;D=x?k:void 0}while(D);p=!1}catch(y){if(y instanceof qe){console.error(`Warning: Slack rate limit hit — backing off for ${y.retryAfter}s`),await yt.sleep(y.retryAfter*1000);continue}throw y}if(n.exitOnMessage&&h)return;g=yt.now();let m=i-yt.now();if(m<=0)return;await yt.sleep(Math.min(r,m))}}import{existsSync as Ab,mkdirSync as Ld,readFileSync as fa,renameSync as Fb,unlinkSync as Id,writeFileSync as pa}from"node:fs";import{dirname as Nd}from"node:path";class ua extends Error{}function vd(e){let t=e,n=(Array.isArray(t.messages)?t.messages:[]).filter((o)=>!!o&&typeof o==="object"&&!Array.isArray(o)),s=t.has_more===!0?t.response_metadata?.next_cursor:void 0;return typeof s==="string"&&s?{messages:n,nextCursor:s}:{messages:n}}function Md(e,t){return{async listChannels(){return(await sd(e,"public_channel,private_channel,im,mpim",t)).flatMap((s)=>{if(!s||typeof s!=="object"||Array.isArray(s)||typeof s.id!=="string")return[];let o=s.is_im===!0;return[{id:s.id,name:ce(s.name)||s.id,isIm:o,...s.is_mpim===!0?{isMpim:!0}:{},...o&&typeof s.user==="string"?{user:s.user}:{}}]})},history:async(n,s,o)=>vd(await An(e,n,200,s,o,t)),replies:async(n,s,o,r)=>vd(await nd(e,n,s,{oldest:o,...r?{cursor:r}:{}},t)),userName:(n)=>Zn(e,n,t)}}var Tb="https://github.com/snomiao/slack-term/blob/main/worker/README.md",Ob=1.618,Rb=25,Ko=2000,Ib=8,fe={now:()=>Date.now(),sleep:(e,t)=>new Promise((n)=>{if(t?.aborted)return n();let s=()=>{clearTimeout(o),n()},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})}),out:(e)=>{process.stdout.write(e+`
243
+ `);if(O)h=!0;D=x?k:void 0}while(D);p=!1}catch(y){if(y instanceof qe){console.error(`Warning: Slack rate limit hit — backing off for ${y.retryAfter}s`),await yt.sleep(y.retryAfter*1000);continue}throw y}if(n.exitOnMessage&&h)return;g=yt.now();let m=i-yt.now();if(m<=0)return;await yt.sleep(Math.min(r,m))}}import{existsSync as Ob,mkdirSync as Bd,readFileSync as ha,renameSync as Rb,unlinkSync as Ld,writeFileSync as ga}from"node:fs";import{dirname as jd}from"node:path";class fa extends Error{}function Nd(e){let t=e,n=(Array.isArray(t.messages)?t.messages:[]).filter((o)=>!!o&&typeof o==="object"&&!Array.isArray(o)),s=t.has_more===!0?t.response_metadata?.next_cursor:void 0;return typeof s==="string"&&s?{messages:n,nextCursor:s}:{messages:n}}function Wd(e,t){return{async listChannels(n){let s;if(n){s=[];for(let o of n){let r=await Po(e,o,t),i=r.channel;if(i&&i.is_member!==!1)s.push(r.channel)}}else try{s=await Hi(e,"public_channel,private_channel,im,mpim",t)}catch(o){if(!/missing_scope/.test(o instanceof Error?o.message:String(o)))throw o;s=[];let r=[];for(let i of["public_channel","private_channel","im","mpim"])try{s.push(...await Hi(e,i,t))}catch(l){if(!/missing_scope/.test(l instanceof Error?l.message:String(l)))throw l;r.push(i)}fe.err(`slack stream: no scope to list ${r.join(", ")} — watching the rest`)}return s.flatMap((o)=>{if(!o||typeof o!=="object"||Array.isArray(o)||typeof o.id!=="string")return[];let r=o.is_im===!0;return[{id:o.id,name:ce(o.name)||o.id,isIm:r,...o.is_mpim===!0?{isMpim:!0}:{},...r&&typeof o.user==="string"?{user:o.user}:{}}]})},history:async(n,s,o)=>Nd(await An(e,n,200,s,o,t)),replies:async(n,s,o,r)=>Nd(await ad(e,n,s,{oldest:o,...r?{cursor:r}:{}},t)),userName:(n)=>Zn(e,n,t)}}var Ib="https://github.com/snomiao/slack-term/blob/main/worker/README.md",vb=1.618,Pb=25,qo=2000,Lb=8,fe={now:()=>Date.now(),sleep:(e,t)=>new Promise((n)=>{if(t?.aborted)return n();let s=()=>{clearTimeout(o),n()},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})}),out:(e)=>{process.stdout.write(e+`
244
244
  `)},err:(e)=>{process.stderr.write(e+`
245
- `)},pidAlive:(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}};function qo(e,t,n){return Math.min(n,Math.round(t*Math.pow(Ob,Math.max(0,e-1))))}var vb=["invalid_auth","not_authed","token_revoked","token_expired","account_inactive","no_permission"],Pb=["channel_not_found","not_in_channel","missing_scope","is_archived"];class en extends Error{}function Ge(e){return e instanceof Error?e.message:String(e)}function da(e){let t=Ge(e);if(vb.some((n)=>t.includes(n)))return"fatal";if(Pb.some((n)=>t.includes(n)))return"channel";return"transient"}var ce=(e)=>typeof e==="string"?e:"",ge=(e)=>Number(e)||0,bt=(e)=>e.toFixed(6),Lb=new Set(["message_changed","message_deleted","channel_join","channel_leave","group_join","group_leave"]);function Nb(e){let t=[ce(e.text)];if(Array.isArray(e.attachments)){for(let n of e.attachments)if(n&&typeof n==="object"&&!Array.isArray(n))t.push(ce(n.pretext),ce(n.text),ce(n.fallback))}return t.filter(Boolean).join(`
246
- `)}function Mb(e,t,n,s){let r=`${e.endsWith("/")?e:e+"/"}archives/${t}/p${n.replace(".","")}`;return s&&s!==n?`${r}?thread_ts=${s}&cid=${t}`:r}function Bb(e,t){if(!Ab(e))return{version:1,identity:t,channels:{}};let n;try{n=JSON.parse(fa(e,"utf8"))}catch(o){throw new en(`state file ${e} is unreadable (${Ge(o)}); move it aside to start fresh`)}if(!(n&&typeof n==="object"&&n.version===1&&n.channels&&typeof n.channels==="object"&&Object.values(n.channels).every((o)=>o&&typeof o.since==="string"&&typeof o.cursor==="string"&&o.threads&&typeof o.threads==="object")))throw new en(`state file ${e} is not a slack stream state; move it aside to start fresh`);if(n.identity!==t)throw new en(`state file ${e} belongs to identity ${n.identity}, not ${t}; pass a different --state`);return n}function It(e,t){Ld(Nd(e),{recursive:!0});let n=`${e}.tmp-${process.pid}`;pa(n,JSON.stringify(t)),Fb(n,e)}function jb(e){let t=`${e}.lock`;Ld(Nd(t),{recursive:!0});let n=()=>{try{if(fa(t,"utf8").trim()===String(process.pid))Id(t)}catch{}};try{pa(t,String(process.pid),{flag:"wx"})}catch{let s=Number(fa(t,"utf8").trim());if(s&&fe.pidAlive(s))throw new en(`another slack stream (pid ${s}) already uses ${e}`);Id(t),pa(t,String(process.pid),{flag:"wx"})}return n}async function Pd(e,t){let n=e.names.get(t);if(n===void 0)n=await e.client.userName(t),e.names.set(t,n);return n}async function ha(e,t,n,s,o){if(Lb.has(ce(n.subtype)))return!1;let r=ce(n.user),i=ce(n.bot_id),l=e.opts.repliesTo,u=ce(n.thread_ts);if(s&&l&&u&&(l.has(r)||l.has(i))){let y=e.state.joined??={};y[`${t.id}:${u}`]=Math.max(y[`${t.id}:${u}`]??0,ge(ce(n.ts)))}if(r&&e.opts.selfUsers.has(r)||i&&e.opts.selfBots.has(i))return!1;e.opts.grep.lastIndex=0;let c=e.opts.grep.test(Nb(n))?"grep":s&&l&&await Wb(e,t,l,n,o)?"replies-to":void 0;if(!c)return!1;let a=ce(n.ts),d=`${t.id}:${a}`;if(e.state.seen?.[d]!==void 0)return!1;if(e.opts.relay&&!e.opts.once)(e.state.seen??={})[d]=ge(a);let f=ce(n.thread_ts)||null,p=r||i,g=r?await Pd(e,r):ce(n.username)||ce(n.bot_profile?.name)||i,h=t.isIm?`@${t.user?await Pd(e,t.user):t.id}`:t.isMpim?t.name:`#${t.name}`,m={type:s?"reply":"message",channel:{id:t.id,name:h},ts:a,thread_ts:f,user:{id:p,name:g},text:ce(n.text).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),permalink:Mb(e.opts.teamUrl,t.id,a,f??void 0),match:c};return e.opts.json?fe.out(JSON.stringify(m)):fe.out(Jb(m)),e.opts.onMatch?.(m,Array.isArray(n.files)?n.files.length:0),e.matches++,!0}async function Wb(e,t,n,s,o){if(n.has(ce(s.parent_user_id)))return!0;let r=ce(s.thread_ts),i=Bd(e,t,n,r,o);if(i!==void 0)return i;let l=`${t.id}:${r}`,u=e.notJoined?.get(l);if(u!==void 0&&u>=ge(ce(s.ts)))return!1;let c=u!==void 0?bt(u):"0";return ga(e,t,n,r,await Ho((a)=>e.client.replies(t.id,r,c,a))),e.state.joined?.[l]!==void 0}function Bd(e,t,n,s,o){if(e.state.joined?.[`${t.id}:${s}`]!==void 0)return!0;if(!o)return;if(n.has(ce(o.user))||n.has(ce(o.bot_id)))return!0;let r=Array.isArray(o.reply_users)?o.reply_users.map((l)=>ce(l)):void 0;if(r?.some((l)=>n.has(l)))return!0;let i=typeof o.reply_users_count==="number"?o.reply_users_count:void 0;if(r&&(i!==void 0?i<=r.length:r.length<5))return!1;return}function ga(e,t,n,s,o){let r=`${t.id}:${s}`,i=o.filter((u)=>n.has(ce(u.user))||n.has(ce(u.bot_id))).map((u)=>ge(ce(u.ts)));if(i.length){let u=e.state.joined??={};u[r]=Math.max(u[r]??0,...i),e.notJoined?.delete(r);return}let l=Math.max(e.notJoined?.get(r)??0,...o.map((u)=>ge(ce(u.ts))));(e.notJoined??=new Map).set(r,l)}function Jb(e){let t=new Date(ge(e.ts)*1000).toISOString().replace(/\.\d+Z$/,"Z"),n=e.type==="reply"?"↳ ":"",s=e.text.split(`
245
+ `)},pidAlive:(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}};function Ho(e,t,n){return Math.min(n,Math.round(t*Math.pow(vb,Math.max(0,e-1))))}var Nb=["invalid_auth","not_authed","token_revoked","token_expired","account_inactive","no_permission"],Mb=["channel_not_found","not_in_channel","missing_scope","is_archived"];class tn extends Error{}function Ge(e){return e instanceof Error?e.message:String(e)}function pa(e){let t=Ge(e);if(Nb.some((n)=>t.includes(n)))return"fatal";if(Mb.some((n)=>t.includes(n)))return"channel";return"transient"}var ce=(e)=>typeof e==="string"?e:"",ge=(e)=>Number(e)||0,bt=(e)=>e.toFixed(6),Bb=new Set(["message_changed","message_deleted","channel_join","channel_leave","group_join","group_leave"]);function jb(e){let t=[ce(e.text)];if(Array.isArray(e.attachments)){for(let n of e.attachments)if(n&&typeof n==="object"&&!Array.isArray(n))t.push(ce(n.pretext),ce(n.text),ce(n.fallback))}return t.filter(Boolean).join(`
246
+ `)}function Wb(e,t,n,s){let r=`${e.endsWith("/")?e:e+"/"}archives/${t}/p${n.replace(".","")}`;return s&&s!==n?`${r}?thread_ts=${s}&cid=${t}`:r}function Jb(e,t){if(!Ob(e))return{version:1,identity:t,channels:{}};let n;try{n=JSON.parse(ha(e,"utf8"))}catch(o){throw new tn(`state file ${e} is unreadable (${Ge(o)}); move it aside to start fresh`)}if(!(n&&typeof n==="object"&&n.version===1&&n.channels&&typeof n.channels==="object"&&Object.values(n.channels).every((o)=>o&&typeof o.since==="string"&&typeof o.cursor==="string"&&o.threads&&typeof o.threads==="object")))throw new tn(`state file ${e} is not a slack stream state; move it aside to start fresh`);if(n.identity!==t)throw new tn(`state file ${e} belongs to identity ${n.identity}, not ${t}; pass a different --state`);return n}function vt(e,t){Bd(jd(e),{recursive:!0});let n=`${e}.tmp-${process.pid}`;ga(n,JSON.stringify(t)),Rb(n,e)}function Ub(e){let t=`${e}.lock`;Bd(jd(t),{recursive:!0});let n=()=>{try{if(ha(t,"utf8").trim()===String(process.pid))Ld(t)}catch{}};try{ga(t,String(process.pid),{flag:"wx"})}catch{let s=Number(ha(t,"utf8").trim());if(s&&fe.pidAlive(s))throw new tn(`another slack stream (pid ${s}) already uses ${e}`);Ld(t),ga(t,String(process.pid),{flag:"wx"})}return n}async function Md(e,t){let n=e.names.get(t);if(n===void 0)n=await e.client.userName(t),e.names.set(t,n);return n}async function ma(e,t,n,s,o){if(Bb.has(ce(n.subtype)))return!1;let r=ce(n.user),i=ce(n.bot_id),l=e.opts.repliesTo,u=ce(n.thread_ts);if(s&&l&&u&&(l.has(r)||l.has(i))){let y=e.state.joined??={};y[`${t.id}:${u}`]=Math.max(y[`${t.id}:${u}`]??0,ge(ce(n.ts)))}if(r&&e.opts.selfUsers.has(r)||i&&e.opts.selfBots.has(i))return!1;e.opts.grep.lastIndex=0;let c=e.opts.grep.test(jb(n))?"grep":s&&l&&await Kb(e,t,l,n,o)?"replies-to":void 0;if(!c)return!1;let a=ce(n.ts),d=`${t.id}:${a}`;if(e.state.seen?.[d]!==void 0)return!1;if(e.opts.relay&&!e.opts.once)(e.state.seen??={})[d]=ge(a);let f=ce(n.thread_ts)||null,p=r||i,g=r?await Md(e,r):ce(n.username)||ce(n.bot_profile?.name)||i,h=t.isIm?`@${t.user?await Md(e,t.user):t.id}`:t.isMpim?t.name:`#${t.name}`,m={type:s?"reply":"message",channel:{id:t.id,name:h},ts:a,thread_ts:f,user:{id:p,name:g},text:ce(n.text).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"),permalink:Wb(e.opts.teamUrl,t.id,a,f??void 0),match:c};return e.opts.json?fe.out(JSON.stringify(m)):fe.out(qb(m)),e.opts.onMatch?.(m,Array.isArray(n.files)?n.files.length:0),e.matches++,!0}async function Kb(e,t,n,s,o){if(n.has(ce(s.parent_user_id)))return!0;let r=ce(s.thread_ts),i=Jd(e,t,n,r,o);if(i!==void 0)return i;let l=`${t.id}:${r}`,u=e.notJoined?.get(l);if(u!==void 0&&u>=ge(ce(s.ts)))return!1;let c=u!==void 0?bt(u):"0";return ya(e,t,n,r,await zo((a)=>e.client.replies(t.id,r,c,a))),e.state.joined?.[l]!==void 0}function Jd(e,t,n,s,o){if(e.state.joined?.[`${t.id}:${s}`]!==void 0)return!0;if(!o)return;if(n.has(ce(o.user))||n.has(ce(o.bot_id)))return!0;let r=Array.isArray(o.reply_users)?o.reply_users.map((l)=>ce(l)):void 0;if(r?.some((l)=>n.has(l)))return!0;let i=typeof o.reply_users_count==="number"?o.reply_users_count:void 0;if(r&&(i!==void 0?i<=r.length:r.length<5))return!1;return}function ya(e,t,n,s,o){let r=`${t.id}:${s}`,i=o.filter((u)=>n.has(ce(u.user))||n.has(ce(u.bot_id))).map((u)=>ge(ce(u.ts)));if(i.length){let u=e.state.joined??={};u[r]=Math.max(u[r]??0,...i),e.notJoined?.delete(r);return}let l=Math.max(e.notJoined?.get(r)??0,...o.map((u)=>ge(ce(u.ts))));(e.notJoined??=new Map).set(r,l)}function qb(e){let t=new Date(ge(e.ts)*1000).toISOString().replace(/\.\d+Z$/,"Z"),n=e.type==="reply"?"↳ ":"",s=e.text.split(`
247
247
  `).join(`
248
248
  `);return`${t} ${e.channel.name} ${n}@${e.user.name}: ${s}
249
- ${e.permalink}`}async function Ho(e){let t=[],n;do{let s=await e(n);t.push(...s.messages),n=s.nextCursor}while(n);return t}async function Ub(e,t,n,s=!0){let o=e.state.channels[t.id],r=n-(e.opts.settleSec??5),i=n-e.opts.threadWindowSec,l=ge(o.cursor),u=s?Math.min(l,i):l,c=(await Ho((f)=>e.client.history(t.id,bt(u),f))).sort((f,p)=>ge(ce(f.ts))-ge(ce(p.ts))),a=e.opts.repliesTo?new Map(c.map((f)=>[ce(f.ts),f])):void 0,d=c.at(-1);if(d&&ge(ce(d.ts))>ge(o.latest??"0"))o.latest=ce(d.ts);if(s)o.scanned=bt(n);for(let f of c){let p=ge(ce(f.ts));if(p<=l||p>r)continue;let g=ce(f.thread_ts),h=await ha(e,t,f,g!==""&&g!==ce(f.ts),g?a?.get(g):void 0);if(o.cursor=ce(f.ts),h)It(e.opts.statePath,e.state)}if(ge(o.cursor)<r)o.cursor=bt(r);for(let f of c){let p=ce(f.ts),g=ge(ce(f.latest_reply));if(!g||ce(f.thread_ts)!==p)continue;let h=ge(o.threads[p]??o.since);if(g<=h)continue;let m=e.opts.repliesTo,y=m!==void 0&&Bd(e,t,m,p,f)===void 0,w=y?Math.min(h,e.notJoined?.get(`${t.id}:${p}`)??0):h,x=(await Ho((D)=>e.client.replies(t.id,p,bt(w),D))).sort((D,E)=>ge(ce(D.ts))-ge(ce(E.ts)));if(y)ga(e,t,m,p,x);for(let D of x){let E=ge(ce(D.ts));if(ce(D.ts)===p||E<=h||E>r)continue;let C=ce(D.subtype)!=="thread_broadcast"&&await ha(e,t,D,!0,f);if(o.threads[p]=ce(D.ts),C)It(e.opts.statePath,e.state)}o.threads[p]=bt(Math.max(ge(o.threads[p]??"0"),Math.min(g,r)))}for(let f of Object.keys(o.threads))if(ge(f)<i)delete o.threads[f];It(e.opts.statePath,e.state)}async function Kb(e,t,n){let s,o,r,i=e.opts.repliesTo,l=`${t.id}:${n.thread_ts??""}`;if(i&&n.thread_ts&&e.state.joined?.[l]===void 0){let g=Math.min(e.notJoined?.get(l)??0,ge(n.ts)-1),h=await Ho((m)=>e.client.replies(t.id,n.thread_ts,bt(g),m));if(s=h.find((m)=>ce(m.ts)===n.ts),o=h.find((m)=>ce(m.ts)===n.thread_ts),s)ga(e,t,i,n.thread_ts,h)}for(let g=0;g<5&&!s;g++){let h=await e.client.replies(t.id,n.thread_ts??n.ts,bt(ge(n.ts)-1),r);if(s=h.messages.find((m)=>ce(m.ts)===n.ts),o??=n.thread_ts?h.messages.find((m)=>ce(m.ts)===n.thread_ts):void 0,r=h.nextCursor,!r)break}if(!s)return!1;let u=ce(s.thread_ts),c=e.state.channels[t.id],d=u!==""&&u!==n.ts&&ce(s.subtype)!=="thread_broadcast"?c?.threads[u]:c?.cursor;if(d!==void 0&&ge(n.ts)<=ge(d))return!0;let f=Object.keys(e.state.joined??{}).length;if(await ha(e,t,s,u!==""&&u!==n.ts,o)||Object.keys(e.state.joined??{}).length!==f)It(e.opts.statePath,e.state);return!0}var qb=2592000;function Hb(e,t){if(!e.joined)return;for(let[n,s]of Object.entries(e.joined))if(s<t)delete e.joined[n];if(!Object.keys(e.joined).length)delete e.joined}function zb(e,t){if(!e.seen)return;for(let[n,s]of Object.entries(e.seen))if(s<t)delete e.seen[n];if(!Object.keys(e.seen).length)delete e.seen}var Yb=10;function Gb(e,t,n){if(!(t>0))return e;let s=60000/t,o=-1/0,r=async()=>{let i=fe.now();o=Math.max(o,i);let l=o-i-(Yb-1)*s;if(o+=s,l>0)await fe.sleep(l,n)};return{listChannels:()=>e.listChannels(),userName:(i)=>e.userName(i),history:async(i,l,u)=>(await r(),e.history(i,l,u)),replies:async(i,l,u,c)=>(await r(),e.replies(i,l,u,c))}}function Xb(e,t,n,s){let o=n-s.windowSec,r=(f)=>t.channels[f.id],i=(f)=>r(f)?.scanned!==void 0&&ge(r(f).latest??"0")<o,l=(f)=>s.once||r(f)?.scanned===void 0||n-ge(r(f).scanned)>=s.periodSec,u=new Map,c=e.filter((f)=>!i(f)),a=s.once||s.periodSec<=s.intervalSec?1/0:Math.max(1,Math.ceil(c.length*s.intervalSec/s.periodSec)),d=c.filter(l).sort((f,p)=>ge(r(f)?.scanned??"0")-ge(r(p)?.scanned??"0")).slice(0,a);for(let f of d)u.set(f.id,"full");for(let f of e){if(u.has(f.id))continue;u.set(f.id,i(f)&&(f.isIm||f.isMpim)&&!l(f)?"skip":"cursor")}return u}async function jd(e,t){let n=t.maxFailures??(t.once?3:12),s=t.backoffBaseMs??2000,o=t.backoffCapMs??300000,r=t.refreshEvery??10,i=t.once?void 0:t.relay;if(!i&&!t.once)fe.err(`slack stream: WARNING: polling mode (${t.pollReason??"no relay configured"}) — this is the fallback, `+`not the intended setup: matches arrive up to ${Math.round(t.intervalMs/1000)}s late (replies under older parents up to ${Math.round(Math.max(t.threadScanSec??180,t.intervalMs/1000))}s) and every cycle spends Slack API calls. For real time, set up the relay (slack relay init) and set SLACK_RELAY_URL + SLACK_RELAY_TOKEN: ${Tb}`);e=Gb(e,t.callsPerMin??40,t.signal);let l,u=new AbortController,c=()=>u.abort();t.signal?.addEventListener("abort",c,{once:!0});try{l=jb(t.statePath);let a=Bb(t.statePath,t.identity),d=t.repliesTo?[...t.repliesTo].sort().join(","):void 0;if(a.joinedBy!==d)delete a.joined;if(d)a.joinedBy=d;else delete a.joinedBy;let f={opts:t,client:e,state:a,names:new Map,matches:0},p=new Set,g=[],h=fe.now()/1000,m=h,y="",w=0,x=0,D=-1/0,E=0,C=(M)=>{fe.err(`slack stream: rate limited — waiting ${M.retryAfter}s`),E=Math.max(E,fe.now()+M.retryAfter*1000)},S=async(M)=>{if(g=(await e.listChannels()).filter((de)=>!t.channels||t.channels.includes(de.id)),t.channels){for(let de of t.channels)if(!g.some((re)=>re.id===de))throw new en(`--channel ${de}: the identity is not a member of it`)}let U=Object.keys(a.channels).length===0;for(let de of g){if(a.channels[de.id])continue;let K=Math.min(U||x===0?M:m,t.sinceSec!==void 0?h-t.sinceSec:1/0);a.channels[de.id]={since:bt(K),cursor:bt(K),threads:{}}}m=M,It(t.statePath,a)};if(t.sinceSec!==void 0)a.channels={},delete a.seen,delete a.relay;let k={queue:[],retry:[],inflight:void 0,onDrain:void 0,handled:0,live:void 0,full:!1},O=new AbortController,P=()=>O.abort(),L=(M,oe="")=>{if(k.live===M)return;k.live=M,fe.err(M?`slack stream: relay connected${oe?` (${oe})`:""} — polling every ${Math.round(Math.max(t.intervalMs,i.reconcileMs)/1000)}s as a safety net`:`slack stream: relay unavailable${oe?` (${oe})`:""} — polling every ${Math.round(t.intervalMs/1000)}s`),P()},v=async(M)=>{let oe=t.sinceSec===void 0&&a.relay?.url===M.url?{seq:a.relay.seq,...a.relay.epoch?{epoch:a.relay.epoch}:{}}:{seq:0},U=0,de=()=>k.queue.length+k.retry.length+(k.inflight?1:0);while(!u.signal.aborted){while(de()>=Ko/2&&!u.signal.aborted)await new Promise((W)=>{let he=()=>W();k.onDrain=()=>{u.signal.removeEventListener("abort",he),W()},u.signal.addEventListener("abort",he,{once:!0})});if(u.signal.aborted)return;let re=new AbortController,K=()=>re.abort();u.signal.addEventListener("abort",K,{once:!0});let ie=!1,G="stream closed";try{await M.subscribe(oe,re.signal,{hello:(W)=>{if(U=0,W.gap)k.full=!0;if(W.gap||a.relay?.url!==M.url||a.relay.epoch!==W.epoch){a.relay={url:M.url,seq:W.seq,...W.epoch?{epoch:W.epoch}:{}},k.handled=Math.min(k.handled,W.seq);for(let he of[...k.queue,...k.retry,...k.inflight?[k.inflight]:[]])he.seq=Math.min(he.seq,W.seq)}oe={seq:W.seq,...W.epoch?{epoch:W.epoch}:{}},L(!0,W.via)},bell:(W,he)=>{if(ie)return;if(de()>=Ko){fe.err(`slack stream: relay backlog over ${Ko} — pausing the relay until it drains`),ie=!0,re.abort(),L(!1,"paused while its backlog drains");return}oe={...oe,seq:W},k.queue.push({seq:W,bell:he,tries:0,dueMs:0}),P()}})}catch(W){if(W instanceof ua){if(k.live)L(!1,Ge(W));k.live=!1,fe.err(`slack stream: relay disabled for this run: ${Ge(W)} — check SLACK_RELAY_TOKEN`);return}G=Ge(W)}finally{u.signal.removeEventListener("abort",K)}if(u.signal.aborted)return;if(ie)continue;L(!1,G),U++,await fe.sleep(qo(U,2000,60000),u.signal)}};if(i)v(i);let j=async(M)=>{if(t.channels&&!t.channels.includes(M.channel))return!0;if(M.kind==="reaction"){if(!t.reactions||M.self&&t.selfUsers.has(M.self))return!0;if(M.user&&t.selfUsers.has(M.user))return!0;let de={type:"reaction",channel:{id:M.channel},ts:M.ts,user:{id:M.user??""}};return fe.out(t.json?JSON.stringify(de):`reaction ${M.channel} ${M.ts} by ${M.user??"?"}`),!0}let oe=g.find((de)=>de.id===M.channel);if(!oe){if(fe.now()/1000-m<60)return!1;await S(fe.now()/1000),oe=g.find((de)=>de.id===M.channel)}let U=oe&&a.channels[oe.id];if(!oe||!U||p.has(oe.id))return!0;if(ge(M.ts)<ge(U.since))return!0;if(M.self&&t.selfUsers.has(M.self)){if(t.repliesTo?.has(M.self)&&M.thread_ts){let de=a.joined??={},re=`${oe.id}:${M.thread_ts}`;de[re]=Math.max(de[re]??0,ge(M.ts)),f.notJoined?.delete(re),It(t.statePath,a)}return!0}return Kb(f,oe,M)},H=()=>{if(!a.relay||a.relay.url!==i?.url)return;let M=[...k.queue,...k.retry,...k.inflight?[k.inflight]:[]].map((oe)=>oe.seq);a.relay.seq=Math.max(0,M.length?Math.min(...M)-1:Math.max(a.relay.seq,k.handled))},B=async()=>{let M=fe.now(),oe=k.retry.filter((re)=>re.dueMs<=M);if(oe.length)k.retry=k.retry.filter((re)=>re.dueMs>M),k.queue=[...oe,...k.queue].sort((re,K)=>re.seq-K.seq);let U=0;while(k.queue.length&&U<Rb&&!t.signal?.aborted&&fe.now()>=E){let re=k.queue.shift();k.inflight=re,U++;let K,ie;try{K=await j(re.bell)}catch(G){if(G instanceof qe){C(G),re.dueMs=E,k.retry.push(re),k.inflight=void 0;break}K=!1,ie=G}if(k.inflight=void 0,ie!==void 0&&/thread_not_found|message_not_found/.test(Ge(ie)))ie=void 0;if(ie!==void 0&&da(ie)==="channel")fe.err(`slack stream: relay bell for ${re.bell.channel} dropped: ${Ge(ie)}`),K=!0;if(ie===void 0&&Q)fe.err("slack stream: relay bell reads recovered"),Q=!1;if(K)k.handled=Math.max(k.handled,re.seq);else if(ie!==void 0){if(re.fails=(re.fails??0)+1,!Q)fe.err(`slack stream: relay bell for ${re.bell.channel} failed (${Ge(ie)}) — retrying`);Q=!0,re.dueMs=fe.now()+qo(re.fails,1500,60000),k.retry.push(re)}else if(++re.tries>=Ib)fe.err(`slack stream: relay bell for ${re.bell.channel} abandoned after ${re.tries} tries (not visible) — only the poll can find it now`),k.handled=Math.max(k.handled,re.seq);else re.dueMs=fe.now()+qo(re.tries,1500,60000),k.retry.push(re)}if(k.onDrain&&k.queue.length+k.retry.length<Ko/2)k.onDrain(),k.onDrain=void 0;let de=a.relay?.seq;if(H(),U||a.relay?.seq!==de)It(t.statePath,a)},q=()=>k.live===!0&&i?Math.max(t.intervalMs,i.reconcileMs):t.intervalMs,z=()=>{let M=fe.now();return(M>=D+q()||k.full)&&M>=E},R=()=>k.queue.length>0||k.retry.some((M)=>M.dueMs<=fe.now()),te=!1,Q=!1;while(!t.signal?.aborted){if(z()&&!(te&&R())){k.full=!1;let U=fe.now()/1000;try{if(x%r===0)await S(U);let de=Math.max(0,t.threadScanSec??180),re=Xb(g.filter((K)=>!p.has(K.id)),a,U,{windowSec:t.threadWindowSec,periodSec:de,intervalSec:q()/1000,once:t.once});for(let K of g){if(t.signal?.aborted)break;if(p.has(K.id))continue;let ie=re.get(K.id)??"full";if(ie==="skip")continue;for(;;)try{let G=a.channels[K.id],W=ie==="cursor"&&G.scanned!==void 0&&ge(G.latest??"0")<U-t.threadWindowSec&&U-ge(G.scanned)>=de;if(await Ub(f,K,U,ie==="full"),W)G.scanned=bt(U),It(t.statePath,a);break}catch(G){if(G instanceof qe){if(C(G),await fe.sleep(E-fe.now(),t.signal),t.signal?.aborted)break;continue}if(da(G)==="channel"){p.add(K.id),y=Ge(G),fe.err(`slack stream: skipping ${K.isIm?K.id:"#"+K.name} (${K.id}): ${Ge(G)}`);break}throw G}}if(g.length>0&&g.every((K)=>p.has(K.id)))throw new en(`every channel failed — nothing left to watch (last: ${y})`);if(w>0)fe.err(`slack stream: recovered after ${w} failed attempt(s)`);w=0}catch(de){if(de instanceof en||da(de)==="fatal")return fe.err(`slack stream: fatal: ${Ge(de)}`),3;if(w++,w>=n)return fe.err(`slack stream: giving up after ${w} consecutive failures: ${Ge(de)}`),3;let re=qo(w,s,o);fe.err(`slack stream: ${Ge(de)} — reconnecting in ${(re/1000).toFixed(1)}s (attempt ${w}/${n})`),await fe.sleep(re,t.signal),k.full=!0;continue}if(x++,zb(a,U-t.threadWindowSec-86400),Hb(a,U-qb),t.once){if(It(t.statePath,a),f.matches===0)fe.err(`slack stream: no matches in ${g.length-p.size} channel(s)`);return f.matches>0?0:2}D=U*1000,te=!0}if(t.signal?.aborted)break;let M=fe.now(),oe=Math.max(E,k.queue.length||k.full?M:Math.min(D+q(),...k.retry.map((U)=>U.dueMs)));if(oe>M){O=new AbortController;let U=O,de=()=>U.abort();t.signal?.addEventListener("abort",de,{once:!0}),await fe.sleep(oe-M,U.signal),t.signal?.removeEventListener("abort",de)}if(z()&&!(te&&R()))continue;await B(),te=!1}return 0}catch(a){return fe.err(`slack stream: fatal: ${Ge(a)}`),3}finally{u.abort(),t.signal?.removeEventListener("abort",c),l?.()}}class Wd extends Error{}function Vb(e,t){let n;while((n=e.indexOf(`
249
+ ${e.permalink}`}async function zo(e){let t=[],n;do{let s=await e(n);t.push(...s.messages),n=s.nextCursor}while(n);return t}async function Hb(e,t,n,s=!0){let o=e.state.channels[t.id],r=n-(e.opts.settleSec??5),i=n-e.opts.threadWindowSec,l=ge(o.cursor),u=s?Math.min(l,i):l,c=(await zo((f)=>e.client.history(t.id,bt(u),f))).sort((f,p)=>ge(ce(f.ts))-ge(ce(p.ts))),a=e.opts.repliesTo?new Map(c.map((f)=>[ce(f.ts),f])):void 0,d=c.at(-1);if(d&&ge(ce(d.ts))>ge(o.latest??"0"))o.latest=ce(d.ts);if(s)o.scanned=bt(n);for(let f of c){let p=ge(ce(f.ts));if(p<=l||p>r)continue;let g=ce(f.thread_ts),h=await ma(e,t,f,g!==""&&g!==ce(f.ts),g?a?.get(g):void 0);if(o.cursor=ce(f.ts),h)vt(e.opts.statePath,e.state)}if(ge(o.cursor)<r)o.cursor=bt(r);for(let f of c){let p=ce(f.ts),g=ge(ce(f.latest_reply));if(!g||ce(f.thread_ts)!==p)continue;let h=ge(o.threads[p]??o.since);if(g<=h)continue;let m=e.opts.repliesTo,y=m!==void 0&&Jd(e,t,m,p,f)===void 0,w=y?Math.min(h,e.notJoined?.get(`${t.id}:${p}`)??0):h,x=(await zo((D)=>e.client.replies(t.id,p,bt(w),D))).sort((D,E)=>ge(ce(D.ts))-ge(ce(E.ts)));if(y)ya(e,t,m,p,x);for(let D of x){let E=ge(ce(D.ts));if(ce(D.ts)===p||E<=h||E>r)continue;let C=ce(D.subtype)!=="thread_broadcast"&&await ma(e,t,D,!0,f);if(o.threads[p]=ce(D.ts),C)vt(e.opts.statePath,e.state)}o.threads[p]=bt(Math.max(ge(o.threads[p]??"0"),Math.min(g,r)))}for(let f of Object.keys(o.threads))if(ge(f)<i)delete o.threads[f];vt(e.opts.statePath,e.state)}async function zb(e,t,n){let s,o,r,i=e.opts.repliesTo,l=`${t.id}:${n.thread_ts??""}`;if(i&&n.thread_ts&&e.state.joined?.[l]===void 0){let g=Math.min(e.notJoined?.get(l)??0,ge(n.ts)-1),h=await zo((m)=>e.client.replies(t.id,n.thread_ts,bt(g),m));if(s=h.find((m)=>ce(m.ts)===n.ts),o=h.find((m)=>ce(m.ts)===n.thread_ts),s)ya(e,t,i,n.thread_ts,h)}for(let g=0;g<5&&!s;g++){let h=await e.client.replies(t.id,n.thread_ts??n.ts,bt(ge(n.ts)-1),r);if(s=h.messages.find((m)=>ce(m.ts)===n.ts),o??=n.thread_ts?h.messages.find((m)=>ce(m.ts)===n.thread_ts):void 0,r=h.nextCursor,!r)break}if(!s)return!1;let u=ce(s.thread_ts),c=e.state.channels[t.id],d=u!==""&&u!==n.ts&&ce(s.subtype)!=="thread_broadcast"?c?.threads[u]:c?.cursor;if(d!==void 0&&ge(n.ts)<=ge(d))return!0;let f=Object.keys(e.state.joined??{}).length;if(await ma(e,t,s,u!==""&&u!==n.ts,o)||Object.keys(e.state.joined??{}).length!==f)vt(e.opts.statePath,e.state);return!0}var Yb=2592000;function Gb(e,t){if(!e.joined)return;for(let[n,s]of Object.entries(e.joined))if(s<t)delete e.joined[n];if(!Object.keys(e.joined).length)delete e.joined}function Xb(e,t){if(!e.seen)return;for(let[n,s]of Object.entries(e.seen))if(s<t)delete e.seen[n];if(!Object.keys(e.seen).length)delete e.seen}var Vb=10;function Zb(e,t,n){if(!(t>0))return e;let s=60000/t,o=-1/0,r=async()=>{let i=fe.now();o=Math.max(o,i);let l=o-i-(Vb-1)*s;if(o+=s,l>0)await fe.sleep(l,n)};return{listChannels:(i)=>e.listChannels(i),userName:(i)=>e.userName(i),history:async(i,l,u)=>(await r(),e.history(i,l,u)),replies:async(i,l,u,c)=>(await r(),e.replies(i,l,u,c))}}function Qb(e,t,n,s){let o=n-s.windowSec,r=(f)=>t.channels[f.id],i=(f)=>r(f)?.scanned!==void 0&&ge(r(f).latest??"0")<o,l=(f)=>s.once||r(f)?.scanned===void 0||n-ge(r(f).scanned)>=s.periodSec,u=new Map,c=e.filter((f)=>!i(f)),a=s.once||s.periodSec<=s.intervalSec?1/0:Math.max(1,Math.ceil(c.length*s.intervalSec/s.periodSec)),d=c.filter(l).sort((f,p)=>ge(r(f)?.scanned??"0")-ge(r(p)?.scanned??"0")).slice(0,a);for(let f of d)u.set(f.id,"full");for(let f of e){if(u.has(f.id))continue;u.set(f.id,i(f)&&(f.isIm||f.isMpim)&&!l(f)?"skip":"cursor")}return u}async function Ud(e,t){let n=t.maxFailures??(t.once?3:12),s=t.backoffBaseMs??2000,o=t.backoffCapMs??300000,r=t.refreshEvery??10,i=t.once?void 0:t.relay;if(!i&&!t.once)fe.err(`slack stream: WARNING: polling mode (${t.pollReason??"no relay configured"}) — this is the fallback, `+`not the intended setup: matches arrive up to ${Math.round(t.intervalMs/1000)}s late (replies under older parents up to ${Math.round(Math.max(t.threadScanSec??180,t.intervalMs/1000))}s) and every cycle spends Slack API calls. For real time, set up the relay (slack relay init) and set SLACK_RELAY_URL + SLACK_RELAY_TOKEN: ${Ib}`);e=Zb(e,t.callsPerMin??40,t.signal);let l,u=new AbortController,c=()=>u.abort();t.signal?.addEventListener("abort",c,{once:!0});try{l=Ub(t.statePath);let a=Jb(t.statePath,t.identity),d=t.repliesTo?[...t.repliesTo].sort().join(","):void 0;if(a.joinedBy!==d)delete a.joined;if(d)a.joinedBy=d;else delete a.joinedBy;let f={opts:t,client:e,state:a,names:new Map,matches:0},p=new Set,g=[],h=fe.now()/1000,m=h,y="",w=0,x=0,D=-1/0,E=0,C=(M)=>{fe.err(`slack stream: rate limited — waiting ${M.retryAfter}s`),E=Math.max(E,fe.now()+M.retryAfter*1000)},S=async(M)=>{if(g=(await e.listChannels(t.channels)).filter((de)=>!t.channels||t.channels.includes(de.id)),t.channels){for(let de of t.channels)if(!g.some((re)=>re.id===de))throw new tn(`--channel ${de}: the identity is not a member of it`)}let U=Object.keys(a.channels).length===0;for(let de of g){if(a.channels[de.id])continue;let K=Math.min(U||x===0?M:m,t.sinceSec!==void 0?h-t.sinceSec:1/0);a.channels[de.id]={since:bt(K),cursor:bt(K),threads:{}}}m=M,vt(t.statePath,a)};if(t.sinceSec!==void 0)a.channels={},delete a.seen,delete a.relay;let k={queue:[],retry:[],inflight:void 0,onDrain:void 0,handled:0,live:void 0,full:!1},O=new AbortController,P=()=>O.abort(),L=(M,oe="")=>{if(k.live===M)return;k.live=M,fe.err(M?`slack stream: relay connected${oe?` (${oe})`:""} — polling every ${Math.round(Math.max(t.intervalMs,i.reconcileMs)/1000)}s as a safety net`:`slack stream: relay unavailable${oe?` (${oe})`:""} — polling every ${Math.round(t.intervalMs/1000)}s`),P()},v=async(M)=>{let oe=t.sinceSec===void 0&&a.relay?.url===M.url?{seq:a.relay.seq,...a.relay.epoch?{epoch:a.relay.epoch}:{}}:{seq:0},U=0,de=()=>k.queue.length+k.retry.length+(k.inflight?1:0);while(!u.signal.aborted){while(de()>=qo/2&&!u.signal.aborted)await new Promise((W)=>{let he=()=>W();k.onDrain=()=>{u.signal.removeEventListener("abort",he),W()},u.signal.addEventListener("abort",he,{once:!0})});if(u.signal.aborted)return;let re=new AbortController,K=()=>re.abort();u.signal.addEventListener("abort",K,{once:!0});let ie=!1,G="stream closed";try{await M.subscribe(oe,re.signal,{hello:(W)=>{if(U=0,W.gap)k.full=!0;if(W.gap||a.relay?.url!==M.url||a.relay.epoch!==W.epoch){a.relay={url:M.url,seq:W.seq,...W.epoch?{epoch:W.epoch}:{}},k.handled=Math.min(k.handled,W.seq);for(let he of[...k.queue,...k.retry,...k.inflight?[k.inflight]:[]])he.seq=Math.min(he.seq,W.seq)}oe={seq:W.seq,...W.epoch?{epoch:W.epoch}:{}},L(!0,W.via)},bell:(W,he)=>{if(ie)return;if(de()>=qo){fe.err(`slack stream: relay backlog over ${qo} — pausing the relay until it drains`),ie=!0,re.abort(),L(!1,"paused while its backlog drains");return}oe={...oe,seq:W},k.queue.push({seq:W,bell:he,tries:0,dueMs:0}),P()}})}catch(W){if(W instanceof fa){if(k.live)L(!1,Ge(W));k.live=!1,fe.err(`slack stream: relay disabled for this run: ${Ge(W)} — check SLACK_RELAY_TOKEN`);return}G=Ge(W)}finally{u.signal.removeEventListener("abort",K)}if(u.signal.aborted)return;if(ie)continue;L(!1,G),U++,await fe.sleep(Ho(U,2000,60000),u.signal)}};if(i)v(i);let j=async(M)=>{if(t.channels&&!t.channels.includes(M.channel))return!0;if(M.kind==="reaction"){if(!t.reactions||M.self&&t.selfUsers.has(M.self))return!0;if(M.user&&t.selfUsers.has(M.user))return!0;let de={type:"reaction",channel:{id:M.channel},ts:M.ts,user:{id:M.user??""}};return fe.out(t.json?JSON.stringify(de):`reaction ${M.channel} ${M.ts} by ${M.user??"?"}`),!0}let oe=g.find((de)=>de.id===M.channel);if(!oe){if(fe.now()/1000-m<60)return!1;await S(fe.now()/1000),oe=g.find((de)=>de.id===M.channel)}let U=oe&&a.channels[oe.id];if(!oe||!U||p.has(oe.id))return!0;if(ge(M.ts)<ge(U.since))return!0;if(M.self&&t.selfUsers.has(M.self)){if(t.repliesTo?.has(M.self)&&M.thread_ts){let de=a.joined??={},re=`${oe.id}:${M.thread_ts}`;de[re]=Math.max(de[re]??0,ge(M.ts)),f.notJoined?.delete(re),vt(t.statePath,a)}return!0}return zb(f,oe,M)},H=()=>{if(!a.relay||a.relay.url!==i?.url)return;let M=[...k.queue,...k.retry,...k.inflight?[k.inflight]:[]].map((oe)=>oe.seq);a.relay.seq=Math.max(0,M.length?Math.min(...M)-1:Math.max(a.relay.seq,k.handled))},B=async()=>{let M=fe.now(),oe=k.retry.filter((re)=>re.dueMs<=M);if(oe.length)k.retry=k.retry.filter((re)=>re.dueMs>M),k.queue=[...oe,...k.queue].sort((re,K)=>re.seq-K.seq);let U=0;while(k.queue.length&&U<Pb&&!t.signal?.aborted&&fe.now()>=E){let re=k.queue.shift();k.inflight=re,U++;let K,ie;try{K=await j(re.bell)}catch(G){if(G instanceof qe){C(G),re.dueMs=E,k.retry.push(re),k.inflight=void 0;break}K=!1,ie=G}if(k.inflight=void 0,ie!==void 0&&/thread_not_found|message_not_found/.test(Ge(ie)))ie=void 0;if(ie!==void 0&&pa(ie)==="channel")fe.err(`slack stream: relay bell for ${re.bell.channel} dropped: ${Ge(ie)}`),K=!0;if(ie===void 0&&Q)fe.err("slack stream: relay bell reads recovered"),Q=!1;if(K)k.handled=Math.max(k.handled,re.seq);else if(ie!==void 0){if(re.fails=(re.fails??0)+1,!Q)fe.err(`slack stream: relay bell for ${re.bell.channel} failed (${Ge(ie)}) — retrying`);Q=!0,re.dueMs=fe.now()+Ho(re.fails,1500,60000),k.retry.push(re)}else if(++re.tries>=Lb)fe.err(`slack stream: relay bell for ${re.bell.channel} abandoned after ${re.tries} tries (not visible) — only the poll can find it now`),k.handled=Math.max(k.handled,re.seq);else re.dueMs=fe.now()+Ho(re.tries,1500,60000),k.retry.push(re)}if(k.onDrain&&k.queue.length+k.retry.length<qo/2)k.onDrain(),k.onDrain=void 0;let de=a.relay?.seq;if(H(),U||a.relay?.seq!==de)vt(t.statePath,a)},q=()=>k.live===!0&&i?Math.max(t.intervalMs,i.reconcileMs):t.intervalMs,z=()=>{let M=fe.now();return(M>=D+q()||k.full)&&M>=E},R=()=>k.queue.length>0||k.retry.some((M)=>M.dueMs<=fe.now()),te=!1,Q=!1;while(!t.signal?.aborted){if(z()&&!(te&&R())){k.full=!1;let U=fe.now()/1000;try{if(x%r===0)await S(U);let de=Math.max(0,t.threadScanSec??180),re=Qb(g.filter((K)=>!p.has(K.id)),a,U,{windowSec:t.threadWindowSec,periodSec:de,intervalSec:q()/1000,once:t.once});for(let K of g){if(t.signal?.aborted)break;if(p.has(K.id))continue;let ie=re.get(K.id)??"full";if(ie==="skip")continue;for(;;)try{let G=a.channels[K.id],W=ie==="cursor"&&G.scanned!==void 0&&ge(G.latest??"0")<U-t.threadWindowSec&&U-ge(G.scanned)>=de;if(await Hb(f,K,U,ie==="full"),W)G.scanned=bt(U),vt(t.statePath,a);break}catch(G){if(G instanceof qe){if(C(G),await fe.sleep(E-fe.now(),t.signal),t.signal?.aborted)break;continue}if(pa(G)==="channel"){p.add(K.id),y=Ge(G),fe.err(`slack stream: skipping ${K.isIm?K.id:"#"+K.name} (${K.id}): ${Ge(G)}`);break}throw G}}if(g.length>0&&g.every((K)=>p.has(K.id)))throw new tn(`every channel failed — nothing left to watch (last: ${y})`);if(w>0)fe.err(`slack stream: recovered after ${w} failed attempt(s)`);w=0}catch(de){if(de instanceof tn||pa(de)==="fatal")return fe.err(`slack stream: fatal: ${Ge(de)}`),3;if(w++,w>=n)return fe.err(`slack stream: giving up after ${w} consecutive failures: ${Ge(de)}`),3;let re=Ho(w,s,o);fe.err(`slack stream: ${Ge(de)} — reconnecting in ${(re/1000).toFixed(1)}s (attempt ${w}/${n})`),await fe.sleep(re,t.signal),k.full=!0;continue}if(x++,Xb(a,U-t.threadWindowSec-86400),Gb(a,U-Yb),t.once){if(vt(t.statePath,a),f.matches===0)fe.err(`slack stream: no matches in ${g.length-p.size} channel(s)`);return f.matches>0?0:2}D=U*1000,te=!0}if(t.signal?.aborted)break;let M=fe.now(),oe=Math.max(E,k.queue.length||k.full?M:Math.min(D+q(),...k.retry.map((U)=>U.dueMs)));if(oe>M){O=new AbortController;let U=O,de=()=>U.abort();t.signal?.addEventListener("abort",de,{once:!0}),await fe.sleep(oe-M,U.signal),t.signal?.removeEventListener("abort",de)}if(z()&&!(te&&R()))continue;await B(),te=!1}return 0}catch(a){return fe.err(`slack stream: fatal: ${Ge(a)}`),3}finally{u.abort(),t.signal?.removeEventListener("abort",c),l?.()}}class Kd extends Error{}function ew(e,t){let n;while((n=e.indexOf(`
250
250
 
251
251
  `))>=0){let s=e.slice(0,n);e=e.slice(n+2);let o="message",r,i=[];for(let l of s.split(`
252
252
  `)){if(!l||l.startsWith(":"))continue;let u=l.indexOf(":"),c=u<0?l:l.slice(0,u),a=u<0?"":l.slice(u+1).replace(/^ /,"");if(c==="event")o=a;else if(c==="data")i.push(a);else if(c==="id")r=a}if(i.length)t(o,i.join(`
253
- `),r)}return e}var Zb="slack-term-relay.v1";function Qb(e){return`bearer.${Buffer.from(e,"utf8").toString("base64url")}`}function Jd(e){return e==="websocket"||e==="sse"?e:"auto"}var ew=32;function Ud(e){return e===void 0?"":`?after=${e.seq}${e.epoch?`&epoch=${encodeURIComponent(e.epoch)}`:""}`}function Kd(e,t,n=70000,s={}){let o=e.replace(/\/+$/,""),r=s.transport??"auto",i=nw(o,t,n);return async(l,u,c)=>{let a=s.WebSocket===void 0?globalThis.WebSocket:s.WebSocket;if(r!=="sse")if(!a){if(r==="websocket")throw Error("relay: this runtime has no WebSocket")}else{if(await tw(a,o,t,n,s.pingMs??25000,s.ackDelayMs??100,l,u,c)||u.aborted)return;if(r==="websocket")throw Error("relay: WebSocket connection failed")}return i(l,u,c)}}function tw(e,t,n,s,o,r,i,l,u){return new Promise((c,a)=>{if(l.aborted)return c(!0);let d;try{d=new e(`${t.replace(/^http/i,"ws")}/ws${Ud(i)}`,[Zb,Qb(n)])}catch{return c(!1)}let f=!1,p=!1,g,h,m,y=0,w=0,x=(S)=>{if(p)return;p=!0,clearTimeout(g),clearTimeout(h),clearInterval(m),l.removeEventListener("abort",D),d.onopen=d.onmessage=d.onerror=d.onclose=null;try{d.close(1000)}catch{}if(S)a(S);else c(f||l.aborted)},D=()=>x();l.addEventListener("abort",D,{once:!0});let E=()=>{clearTimeout(g),g=setTimeout(()=>x(f?Error(`relay: no data for ${Math.round(s/1000)}s`):void 0),s)},C=()=>{if(clearTimeout(h),h=void 0,y<=w)return;w=y;try{d.send(JSON.stringify({type:"ack",seq:y}))}catch{}};E(),d.onopen=()=>{f=!0,E(),m=setInterval(()=>{try{d.send("ping")}catch{}},o)},d.onmessage=(S)=>{if(E(),typeof S.data!=="string"||S.data==="pong")return;let k;try{k=JSON.parse(S.data)}catch(O){return x(O)}if(k.type==="hello"){let{type:O,...P}=k;y=w=P.seq,u.hello({...P,via:"websocket"})}else if(k.type==="bell"&&typeof k.seq==="number"){if(u.bell(k.seq,k.bell),p)return;if(y=Math.max(y,k.seq),y-w>=ew)C();else h??=setTimeout(C,r)}},d.onerror=()=>{},d.onclose=(S)=>{if(!f||S.code===1000)return x();x(Error(`relay: WebSocket closed (${S.code}${S.reason?` ${S.reason}`:""})`))}})}function nw(e,t,n){return async(s,o,r)=>{let i=new AbortController,l=()=>i.abort();o.addEventListener("abort",l,{once:!0});let u,c=!1,a=()=>{clearTimeout(u),u=setTimeout(()=>{c=!0,i.abort()},n)};try{a();let d=await fetch(`${e}/stream${Ud(s)}`,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:i.signal});if(d.status===401)throw new Wd("relay rejected the token (401)");if(!d.ok||!d.body)throw Error(`relay: HTTP ${d.status}`);let f=d.body.getReader(),p=new TextDecoder,g="";for(;;){let{done:h,value:m}=await f.read();if(h)return;a(),g=Vb((g+p.decode(m,{stream:!0})).replace(/\r\n/g,`
254
- `),(y,w,x)=>{let D=JSON.parse(w);if(y==="hello")r.hello({...D,via:"sse"});else if(y==="bell"&&x!==void 0)r.bell(Number(x),D)})}}catch(d){if(o.aborted)return;if(c)throw Error(`relay: no data for ${Math.round(n/1000)}s`);throw d}finally{clearTimeout(u),o.removeEventListener("abort",l)}}}import{existsSync as ow,mkdirSync as rw,writeFileSync as iw}from"node:fs";import{basename as aw,join as ma,resolve as Hd}from"node:path";import{randomBytes as cw}from"node:crypto";var qd={name:"slack-term",version:"1.51.0",repository:{type:"git",url:"https://github.com/snomiao/slack-term.git"},bugs:{url:"https://github.com/snomiao/slack-term/issues"},devDependencies:{"@semantic-release/commit-analyzer":"^13","@semantic-release/github":"^12","@semantic-release/npm":"^13","@semantic-release/release-notes-generator":"^14","@types/bun":"latest","@types/node":"^22","@types/yargs":"^17.0.35","@typescript/native-preview":"^7.0.0-dev.20260707.2","@vitest/coverage-istanbul":"4.1.10","semantic-release":"^24",typescript:"^5.6",vitest:"4.1.10"},bin:{slack:"./ts/cli.ts"},exports:{"./worker":"./worker/src/index.ts","./package.json":"./package.json"},description:"Slack CLI — read activity/news/mentions, search, send messages with a confirm-hash safety gate.",engines:{node:">=18"},files:["ts/","locales/","dist/","worker/src/","README.md","SKILL.md","LICENSE"],homepage:"https://github.com/snomiao/slack-term",keywords:["slack","cli","messaging","agent","terminal"],license:"MIT",overrides:{"@semantic-release/npm":"^13","@semantic-release/github":"^12"},publishConfig:{access:"public",bin:{slack:"./dist/cli.js"}},scripts:{dev:"bun run ts/cli.ts",build:"bun build ts/cli.ts --target=node --outfile dist/cli.js --minify",typecheck:"tsgo --noEmit","typecheck:tsc":"tsc --noEmit","typecheck:worker":"bun install --cwd worker --frozen-lockfile && tsgo --noEmit -p worker",test:"bun test tests/ --timeout 90000 --parallel=2","test:watch":"bun test tests/ --timeout 90000 --isolate --watch","test:parity":"bash tests/parity.sh",record:"bun run tests/record.ts",anonymize:"bun run tests/anonymize.ts","scan-pii":"bash .githooks/pre-commit","scan-pii:all":"bash .githooks/pre-commit --all",prepare:"git config core.hooksPath .githooks 2>/dev/null || true",prepublishOnly:"bun run scan-pii:all && bun run typecheck && bun run build","test:coverage":"vitest run --coverage --exclude tests/parity.test.ts --no-file-parallelism"},type:"module",dependencies:{yargs:"^18.0.0"},peerDependencies:{"@cloudflare/workers-types":"^4"},peerDependenciesMeta:{"@cloudflare/workers-types":{optional:!0}}};var lw="4.105.0",uw="2026-07-01",ya="slack-term-relay",dw="https://github.com/snomiao/slack-term/blob/main/worker/README.md";function fw(e){return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(e)}function pw(e){return aw(Hd(e)).toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63).replace(/-+$/,"")||ya}function hw(e,t={}){let n={name:e,private:!0,type:"module",scripts:{deploy:"wrangler deploy",dev:"wrangler dev --local"},dependencies:{"slack-term":t.slackTerm??`^${qd.version}`},devDependencies:{wrangler:lw},engines:{node:">=22"}};return{"package.json":`${JSON.stringify(n,null,2)}
253
+ `),r)}return e}var tw="slack-term-relay.v1";function nw(e){return`bearer.${Buffer.from(e,"utf8").toString("base64url")}`}function qd(e){return e==="websocket"||e==="sse"?e:"auto"}var sw=32;function Hd(e){return e===void 0?"":`?after=${e.seq}${e.epoch?`&epoch=${encodeURIComponent(e.epoch)}`:""}`}function zd(e,t,n=70000,s={}){let o=e.replace(/\/+$/,""),r=s.transport??"auto",i=rw(o,t,n);return async(l,u,c)=>{let a=s.WebSocket===void 0?globalThis.WebSocket:s.WebSocket;if(r!=="sse")if(!a){if(r==="websocket")throw Error("relay: this runtime has no WebSocket")}else{if(await ow(a,o,t,n,s.pingMs??25000,s.ackDelayMs??100,l,u,c)||u.aborted)return;if(r==="websocket")throw Error("relay: WebSocket connection failed")}return i(l,u,c)}}function ow(e,t,n,s,o,r,i,l,u){return new Promise((c,a)=>{if(l.aborted)return c(!0);let d;try{d=new e(`${t.replace(/^http/i,"ws")}/ws${Hd(i)}`,[tw,nw(n)])}catch{return c(!1)}let f=!1,p=!1,g,h,m,y=0,w=0,x=(S)=>{if(p)return;p=!0,clearTimeout(g),clearTimeout(h),clearInterval(m),l.removeEventListener("abort",D),d.onopen=d.onmessage=d.onerror=d.onclose=null;try{d.close(1000)}catch{}if(S)a(S);else c(f||l.aborted)},D=()=>x();l.addEventListener("abort",D,{once:!0});let E=()=>{clearTimeout(g),g=setTimeout(()=>x(f?Error(`relay: no data for ${Math.round(s/1000)}s`):void 0),s)},C=()=>{if(clearTimeout(h),h=void 0,y<=w)return;w=y;try{d.send(JSON.stringify({type:"ack",seq:y}))}catch{}};E(),d.onopen=()=>{f=!0,E(),m=setInterval(()=>{try{d.send("ping")}catch{}},o)},d.onmessage=(S)=>{if(E(),typeof S.data!=="string"||S.data==="pong")return;let k;try{k=JSON.parse(S.data)}catch(O){return x(O)}if(k.type==="hello"){let{type:O,...P}=k;y=w=P.seq,u.hello({...P,via:"websocket"})}else if(k.type==="bell"&&typeof k.seq==="number"){if(u.bell(k.seq,k.bell),p)return;if(y=Math.max(y,k.seq),y-w>=sw)C();else h??=setTimeout(C,r)}},d.onerror=()=>{},d.onclose=(S)=>{if(!f||S.code===1000)return x();x(Error(`relay: WebSocket closed (${S.code}${S.reason?` ${S.reason}`:""})`))}})}function rw(e,t,n){return async(s,o,r)=>{let i=new AbortController,l=()=>i.abort();o.addEventListener("abort",l,{once:!0});let u,c=!1,a=()=>{clearTimeout(u),u=setTimeout(()=>{c=!0,i.abort()},n)};try{a();let d=await fetch(`${e}/stream${Hd(s)}`,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:i.signal});if(d.status===401)throw new Kd("relay rejected the token (401)");if(!d.ok||!d.body)throw Error(`relay: HTTP ${d.status}`);let f=d.body.getReader(),p=new TextDecoder,g="";for(;;){let{done:h,value:m}=await f.read();if(h)return;a(),g=ew((g+p.decode(m,{stream:!0})).replace(/\r\n/g,`
254
+ `),(y,w,x)=>{let D=JSON.parse(w);if(y==="hello")r.hello({...D,via:"sse"});else if(y==="bell"&&x!==void 0)r.bell(Number(x),D)})}}catch(d){if(o.aborted)return;if(c)throw Error(`relay: no data for ${Math.round(n/1000)}s`);throw d}finally{clearTimeout(u),o.removeEventListener("abort",l)}}}import{existsSync as aw,mkdirSync as cw,writeFileSync as lw}from"node:fs";import{basename as uw,join as ba,resolve as Gd}from"node:path";import{randomBytes as dw}from"node:crypto";var Yd={name:"slack-term",version:"1.51.2",repository:{type:"git",url:"https://github.com/snomiao/slack-term.git"},bugs:{url:"https://github.com/snomiao/slack-term/issues"},devDependencies:{"@semantic-release/commit-analyzer":"^13","@semantic-release/github":"^12","@semantic-release/npm":"^13","@semantic-release/release-notes-generator":"^14","@types/bun":"latest","@types/node":"^22","@types/yargs":"^17.0.35","@typescript/native-preview":"^7.0.0-dev.20260707.2","@vitest/coverage-istanbul":"4.1.10","semantic-release":"^24",typescript:"^5.6",vitest:"4.1.10"},bin:{slack:"./ts/cli.ts"},exports:{"./worker":"./worker/src/index.ts","./package.json":"./package.json"},description:"Slack CLI — read activity/news/mentions, search, send messages with a confirm-hash safety gate.",engines:{node:">=18"},files:["ts/","locales/","dist/","worker/src/","README.md","SKILL.md","LICENSE"],homepage:"https://github.com/snomiao/slack-term",keywords:["slack","cli","messaging","agent","terminal"],license:"MIT",overrides:{"@semantic-release/npm":"^13","@semantic-release/github":"^12"},publishConfig:{access:"public",bin:{slack:"./dist/cli.js"}},scripts:{dev:"bun run ts/cli.ts",build:"bun build ts/cli.ts --target=node --outfile dist/cli.js --minify",typecheck:"tsgo --noEmit","typecheck:tsc":"tsc --noEmit","typecheck:worker":"bun install --cwd worker --frozen-lockfile && tsgo --noEmit -p worker",test:"bun test tests/ --timeout 90000 --parallel=2","test:watch":"bun test tests/ --timeout 90000 --isolate --watch","test:parity":"bash tests/parity.sh",record:"bun run tests/record.ts",anonymize:"bun run tests/anonymize.ts","scan-pii":"bash .githooks/pre-commit","scan-pii:all":"bash .githooks/pre-commit --all",prepare:"git config core.hooksPath .githooks 2>/dev/null || true",prepublishOnly:"bun run scan-pii:all && bun run typecheck && bun run build","test:coverage":"vitest run --coverage --exclude tests/parity.test.ts --no-file-parallelism"},type:"module",dependencies:{yargs:"^18.0.0"},peerDependencies:{"@cloudflare/workers-types":"^4"},peerDependenciesMeta:{"@cloudflare/workers-types":{optional:!0}}};var fw="4.105.0",pw="2026-07-01",wa="slack-term-relay",hw="https://github.com/snomiao/slack-term/blob/main/worker/README.md";function gw(e){return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(e)}function mw(e){return uw(Gd(e)).toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63).replace(/-+$/,"")||wa}function yw(e,t={}){let n={name:e,private:!0,type:"module",scripts:{deploy:"wrangler deploy",dev:"wrangler dev --local"},dependencies:{"slack-term":t.slackTerm??`^${Yd.version}`},devDependencies:{wrangler:fw},engines:{node:">=22"}};return{"package.json":`${JSON.stringify(n,null,2)}
255
255
  `,"wrangler.jsonc":`// slack-term relay: Slack Events API -> doorbells for \`slack stream\`.
256
256
  // Secrets (not in this file): wrangler secret put SLACK_SIGNING_SECRET / RELAY_TOKEN / SLACK_TEAM_ID (optional)
257
257
  {
258
258
  "$schema": "node_modules/wrangler/config-schema.json",
259
259
  "name": ${JSON.stringify(e)},
260
260
  "main": "src/index.ts",
261
- "compatibility_date": "${uw}",
261
+ "compatibility_date": "${pw}",
262
262
  "durable_objects": {
263
263
  "bindings": [{ "name": "RELAY", "class_name": "Relay" }]
264
264
  },
@@ -274,7 +274,7 @@ export { default, Relay } from "slack-term/worker";
274
274
  .wrangler/
275
275
  .dev.vars*
276
276
  .env*
277
- `,"README.md":gw(e)}}function zd(e,t){let n=t??"<RELAY_TOKEN>";return`1. Node >= 22 (wrangler 4 needs it), then install:
277
+ `,"README.md":bw(e)}}function Xd(e,t){let n=t??"<RELAY_TOKEN>";return`1. Node >= 22 (wrangler 4 needs it), then install:
278
278
  npm install
279
279
  2. Log in to Cloudflare:
280
280
  npx wrangler login
@@ -295,7 +295,7 @@ export { default, Relay } from "slack-term/worker";
295
295
  6. Check it:
296
296
  slack relay health # or: curl -H "Authorization: Bearer $SLACK_RELAY_TOKEN" $SLACK_RELAY_URL/health
297
297
  slack stream -e . # stderr says: relay connected (websocket)
298
- `}function gw(e){return`# ${e}
298
+ `}function bw(e){return`# ${e}
299
299
 
300
300
  A [slack-term](https://github.com/snomiao/slack-term) relay: a Cloudflare Worker
301
301
  that turns Slack's Events API into a resumable doorbell stream for
@@ -304,7 +304,7 @@ configures and deploys it. Created by \`slack relay init\`.
304
304
 
305
305
  ## Set up
306
306
 
307
- ${zd(e)}
307
+ ${Xd(e)}
308
308
  \`RELAY_TOKEN\` is any long random string (\`openssl rand -hex 32\`); \`slack relay init\`
309
309
  printed one. Keep it out of this folder: anyone holding it can watch when and
310
310
  where messages are posted.
@@ -314,41 +314,41 @@ where messages are posted.
314
314
  Bump \`slack-term\` in package.json, \`npm install\`, \`npx wrangler deploy\`.
315
315
  Storage survives redeploys; clients reconnect and resume.
316
316
 
317
- Details (endpoints, privacy, protocol): ${dw}
318
- `}function Yd(e,t={},n=cw){let s=t.name??pw(e);if(!fw(s))return{ok:!1,error:`invalid worker name "${s}": use lowercase letters, digits and dashes (1-63 chars, no leading/trailing dash)`};let o=hw(s,t.slackTerm!==void 0?{slackTerm:t.slackTerm}:{}),r=Hd(e),i=Object.keys(o).filter((l)=>ow(ma(r,l)));if(i.length&&!t.force)return{ok:!1,error:`refusing to overwrite existing files in ${r} (pass --force to replace them)`,existing:i};for(let[l,u]of Object.entries(o)){let c=ma(r,l);rw(ma(c,".."),{recursive:!0}),iw(c,u)}return{ok:!0,dir:r,name:s,written:Object.keys(o),token:n(32).toString("hex")}}function Gd(e,t=process.cwd()){let n=e.dir.startsWith(`${t}/`)?e.dir.slice(t.length+1):e.dir;return[`Created ${e.dir} (worker "${e.name}"):`,...e.written.map((s)=>` ${s}`),"","RELAY_TOKEN (generated now, not saved anywhere — copy it):",` ${e.token}`,"","Next steps:",`0. cd ${n}`,zd(e.name,e.token)].join(`
319
- `)}async function Xd(e,t,n=fetch,s=1e4){if(!e||!t)return{code:2,out:"slack relay health: set SLACK_RELAY_URL and SLACK_RELAY_TOKEN (or pass --url / --token)"};let o=`${e.replace(/\/+$/,"")}/health`;try{let r=await n(o,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(s)}),i=await r.text();if(r.status===401)return{code:1,out:"slack relay health: 401 unauthorized — SLACK_RELAY_TOKEN does not match the relay's RELAY_TOKEN secret"};if(!r.ok)return{code:1,out:`slack relay health: HTTP ${r.status} from ${o}${i?`: ${i.slice(0,200)}`:""}`};let l;try{l=JSON.parse(i)}catch{return{code:1,out:`slack relay health: not a slack-term relay (non-JSON reply from ${o})`}}return{code:l.ok===!0?0:1,out:JSON.stringify(l,null,2)}}catch(r){return{code:1,out:`slack relay health: cannot reach ${o}: ${r instanceof Error?r.message:String(r)}`}}}import{spawn as mw}from"node:child_process";import{constants as Vd}from"node:os";var yw=["processing","active","suspended","closed"];function Zd(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?Co():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 Qd(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function ef(e,t,n){let{ref:s,threadTs:o}=n(t);if(!o||!/^\d{10}\.\d{6}$/.test(o))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Ro(e,s),thread_ts:o}}function ba(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function bw(e,t,n,s){let o,r,i,l,u,c=!1,a=!1,d=1,f=(h)=>{if(r)return;if(r=h,c=!0,o&&o.exitCode===null&&o.signalCode===null)o.kill(h),i=setTimeout(()=>o?.kill("SIGKILL"),5000)},p=()=>f("SIGINT"),g=()=>f("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",g);try{if(a=!0,await $s(e,t,"processing"),!c&&s.title!==void 0)await Ui(e,t,s.title);if(!c){o=mw(n[0],n.slice(1),{stdio:"inherit"});let h=new Promise((m)=>{o.once("error",()=>{console.error("agent: could not start command"),m(127)}),o.once("exit",(y,w)=>{m(y??(w?128+Vd.signals[w]:1))})});l=setInterval(()=>{if(c||u)return;u=$s(e,t,"processing").then(()=>{}).catch((m)=>ba("heartbeat failed; retrying on next tick",m)).finally(()=>{u=void 0})},s.every*1000),d=await h}}catch(h){ba("could not start agent session",h)}finally{if(c=!0,clearInterval(l),clearTimeout(i),await u,a)try{await $s(e,t,s.close?"closed":"active")}catch(h){if(ba("final status clear failed",h),d===0)d=1}process.removeListener("SIGINT",p),process.removeListener("SIGTERM",g)}return r?128+Vd.signals[r]:d}function tf(e,t){let n=(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"Thread root: raw channel ID:ts (avoids listing), #channel:ts, or permalink"}).option("title",{type:"string",describe:"Rename the session (1–200 characters)"}).option("bot-token-env",{type:"string",describe:"Environment variable holding an agent-enabled app's xoxb token (default SLACK_BOT_TOKEN); requires chat:write and channel membership"});return e.command("status <target> <status>","Set a bot agent session's status",(s)=>n(s).positional("status",{type:"string",choices:yw,demandOption:!0}),async(s)=>{Qd(s.title);let o=Zd(s["bot-token-env"]),r=await ef(o,s.target,t);if(await $s(o,r,s.status),s.title!==void 0)await Ui(o,r,s.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(s)=>n(s).parserConfiguration({"populate--":!0}).option("every",{type:"number",default:300,describe:"Heartbeat seconds (>0 and <3600); processing expires after one hour"}).option("close",{type:"boolean",default:!1,describe:"Finish with closed instead of active (also on failure or interrupt)"}),async(s)=>{if(Qd(s.title),!Number.isFinite(s.every)||s.every<=0||s.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let o=process.argv.indexOf("--"),r=o<0?[]:process.argv.slice(o+1);if(!r[0])throw Error("agent run requires -- <command...>");let i=Zd(s["bot-token-env"]),l=await ef(i,s.target,t);process.exitCode=await bw(i,l,r,{every:s.every,close:s.close,...s.title!==void 0?{title:s.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}import{readdirSync as vw,readFileSync as Pw,statSync as Lw}from"node:fs";import{join as $a}from"node:path";import{fileURLToPath as Nw}from"node:url";import{closeSync as ww,existsSync as nf,mkdirSync as of,openSync as Dw,readFileSync as zo,realpathSync as kw,renameSync as xw,statSync as ka,unlinkSync as sf,writeFileSync as Sw}from"node:fs";import{homedir as rf}from"node:os";import{dirname as xa,join as ut,resolve as wa}from"node:path";var _w=".slack-term";function vs(){return process.env.SLACK_TERM_HOME??ut(rf(),".config","slack-term")}function Yo(e=process.cwd()){let t=wa(e);for(;;){let n=ut(t,_w);try{if(ka(n).isDirectory())return{dir:n,global:!1}}catch{}let s=xa(t);if(s===t)break;t=s}return{dir:vs(),global:!0}}function Tn(e,t){of(xa(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;Sw(n,t,{mode:384}),xw(n,e)}function Ew(e,t,n=1e4,s=5000){let o=`${e}.lock`;of(xa(o),{recursive:!0});let r=Date.now()+s;for(;;)try{ww(Dw(o,"wx"));break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-ka(o).mtimeMs>n){sf(o);continue}}catch{continue}if(Date.now()>r)throw Error(`${o} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{sf(o)}catch{}}}function $w(e){if(!e||typeof e!=="object")return;let t=e;if(typeof t.channel!=="string"||!t.channel)return;let n={channel:t.channel};if(typeof t.thread_ts==="string"&&/^\d{10}\.\d{6}$/.test(t.thread_ts))n.thread_ts=t.thread_ts;if(typeof t.added==="string")n.added=t.added;if(typeof t.note==="string")n.note=t.note;return n}function tn(e){let t;try{t=Bun.YAML.parse(zo(e,"utf8"))}catch(o){if(o.code==="ENOENT")return{};throw Error(`${e}: ${o instanceof Error?o.message:String(o)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((o)=>typeof o==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let o={};for(let[r,i]of Object.entries(n.subscriptions)){let l=$w(i);if(l&&af(r))o[r]=l}s.subscriptions=o}return s}function Sa(e){let t=tn(ut(e.dir,"settings.yml")),n=tn(ut(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},o={...t,...n};if(Object.keys(s).length)o.subscriptions=s;else delete o.subscriptions;return o}var Cw=/^[a-z0-9][a-z0-9._-]{0,63}$/;function af(e){return Cw.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function cf(e){let t=tn(ut(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:tn(ut(e.dir,"settings.local.yml")).subscriptions??{},o=[];for(let[r,i]of Object.entries(n))if(!s[r])o.push({...i,name:r,scope:e,file:"settings.yml"});for(let[r,i]of Object.entries(s))o.push({...i,name:r,scope:e,file:"settings.local.yml"});return o.sort((r,i)=>r.name.localeCompare(i.name))}var Aw="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function Fw(e){try{let t=zo(e,"utf8").split(`
317
+ Details (endpoints, privacy, protocol): ${hw}
318
+ `}function Vd(e,t={},n=dw){let s=t.name??mw(e);if(!gw(s))return{ok:!1,error:`invalid worker name "${s}": use lowercase letters, digits and dashes (1-63 chars, no leading/trailing dash)`};let o=yw(s,t.slackTerm!==void 0?{slackTerm:t.slackTerm}:{}),r=Gd(e),i=Object.keys(o).filter((l)=>aw(ba(r,l)));if(i.length&&!t.force)return{ok:!1,error:`refusing to overwrite existing files in ${r} (pass --force to replace them)`,existing:i};for(let[l,u]of Object.entries(o)){let c=ba(r,l);cw(ba(c,".."),{recursive:!0}),lw(c,u)}return{ok:!0,dir:r,name:s,written:Object.keys(o),token:n(32).toString("hex")}}function Zd(e,t=process.cwd()){let n=e.dir.startsWith(`${t}/`)?e.dir.slice(t.length+1):e.dir;return[`Created ${e.dir} (worker "${e.name}"):`,...e.written.map((s)=>` ${s}`),"","RELAY_TOKEN (generated now, not saved anywhere — copy it):",` ${e.token}`,"","Next steps:",`0. cd ${n}`,Xd(e.name,e.token)].join(`
319
+ `)}async function Qd(e,t,n=fetch,s=1e4){if(!e||!t)return{code:2,out:"slack relay health: set SLACK_RELAY_URL and SLACK_RELAY_TOKEN (or pass --url / --token)"};let o=`${e.replace(/\/+$/,"")}/health`;try{let r=await n(o,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(s)}),i=await r.text();if(r.status===401)return{code:1,out:"slack relay health: 401 unauthorized — SLACK_RELAY_TOKEN does not match the relay's RELAY_TOKEN secret"};if(!r.ok)return{code:1,out:`slack relay health: HTTP ${r.status} from ${o}${i?`: ${i.slice(0,200)}`:""}`};let l;try{l=JSON.parse(i)}catch{return{code:1,out:`slack relay health: not a slack-term relay (non-JSON reply from ${o})`}}return{code:l.ok===!0?0:1,out:JSON.stringify(l,null,2)}}catch(r){return{code:1,out:`slack relay health: cannot reach ${o}: ${r instanceof Error?r.message:String(r)}`}}}import{spawn as ww}from"node:child_process";import{constants as ef}from"node:os";var Dw=["processing","active","suspended","closed"];function tf(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?Co():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 nf(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function sf(e,t,n){let{ref:s,threadTs:o}=n(t);if(!o||!/^\d{10}\.\d{6}$/.test(o))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Ro(e,s),thread_ts:o}}function Da(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function kw(e,t,n,s){let o,r,i,l,u,c=!1,a=!1,d=1,f=(h)=>{if(r)return;if(r=h,c=!0,o&&o.exitCode===null&&o.signalCode===null)o.kill(h),i=setTimeout(()=>o?.kill("SIGKILL"),5000)},p=()=>f("SIGINT"),g=()=>f("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",g);try{if(a=!0,await $s(e,t,"processing"),!c&&s.title!==void 0)await Ki(e,t,s.title);if(!c){o=ww(n[0],n.slice(1),{stdio:"inherit"});let h=new Promise((m)=>{o.once("error",()=>{console.error("agent: could not start command"),m(127)}),o.once("exit",(y,w)=>{m(y??(w?128+ef.signals[w]:1))})});l=setInterval(()=>{if(c||u)return;u=$s(e,t,"processing").then(()=>{}).catch((m)=>Da("heartbeat failed; retrying on next tick",m)).finally(()=>{u=void 0})},s.every*1000),d=await h}}catch(h){Da("could not start agent session",h)}finally{if(c=!0,clearInterval(l),clearTimeout(i),await u,a)try{await $s(e,t,s.close?"closed":"active")}catch(h){if(Da("final status clear failed",h),d===0)d=1}process.removeListener("SIGINT",p),process.removeListener("SIGTERM",g)}return r?128+ef.signals[r]:d}function of(e,t){let n=(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"Thread root: raw channel ID:ts (avoids listing), #channel:ts, or permalink"}).option("title",{type:"string",describe:"Rename the session (1–200 characters)"}).option("bot-token-env",{type:"string",describe:"Environment variable holding an agent-enabled app's xoxb token (default SLACK_BOT_TOKEN); requires chat:write and channel membership"});return e.command("status <target> <status>","Set a bot agent session's status",(s)=>n(s).positional("status",{type:"string",choices:Dw,demandOption:!0}),async(s)=>{nf(s.title);let o=tf(s["bot-token-env"]),r=await sf(o,s.target,t);if(await $s(o,r,s.status),s.title!==void 0)await Ki(o,r,s.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(s)=>n(s).parserConfiguration({"populate--":!0}).option("every",{type:"number",default:300,describe:"Heartbeat seconds (>0 and <3600); processing expires after one hour"}).option("close",{type:"boolean",default:!1,describe:"Finish with closed instead of active (also on failure or interrupt)"}),async(s)=>{if(nf(s.title),!Number.isFinite(s.every)||s.every<=0||s.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let o=process.argv.indexOf("--"),r=o<0?[]:process.argv.slice(o+1);if(!r[0])throw Error("agent run requires -- <command...>");let i=tf(s["bot-token-env"]),l=await sf(i,s.target,t);process.exitCode=await kw(i,l,r,{every:s.every,close:s.close,...s.title!==void 0?{title:s.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}import{readdirSync as Nw,readFileSync as Mw,statSync as Bw}from"node:fs";import{join as Aa}from"node:path";import{fileURLToPath as jw}from"node:url";import{closeSync as xw,existsSync as rf,mkdirSync as cf,openSync as Sw,readFileSync as Yo,realpathSync as _w,renameSync as Ew,statSync as Sa,unlinkSync as af,writeFileSync as $w}from"node:fs";import{homedir as lf}from"node:os";import{dirname as _a,join as ut,resolve as ka}from"node:path";var Cw=".slack-term";function vs(){return process.env.SLACK_TERM_HOME??ut(lf(),".config","slack-term")}function Go(e=process.cwd()){let t=ka(e);for(;;){let n=ut(t,Cw);try{if(Sa(n).isDirectory())return{dir:n,global:!1}}catch{}let s=_a(t);if(s===t)break;t=s}return{dir:vs(),global:!0}}function Tn(e,t){cf(_a(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;$w(n,t,{mode:384}),Ew(n,e)}function Aw(e,t,n=1e4,s=5000){let o=`${e}.lock`;cf(_a(o),{recursive:!0});let r=Date.now()+s;for(;;)try{xw(Sw(o,"wx"));break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-Sa(o).mtimeMs>n){af(o);continue}}catch{continue}if(Date.now()>r)throw Error(`${o} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{af(o)}catch{}}}function Fw(e){if(!e||typeof e!=="object")return;let t=e;if(typeof t.channel!=="string"||!t.channel)return;let n={channel:t.channel};if(typeof t.thread_ts==="string"&&/^\d{10}\.\d{6}$/.test(t.thread_ts))n.thread_ts=t.thread_ts;if(typeof t.added==="string")n.added=t.added;if(typeof t.note==="string")n.note=t.note;return n}function nn(e){let t;try{t=Bun.YAML.parse(Yo(e,"utf8"))}catch(o){if(o.code==="ENOENT")return{};throw Error(`${e}: ${o instanceof Error?o.message:String(o)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((o)=>typeof o==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let o={};for(let[r,i]of Object.entries(n.subscriptions)){let l=Fw(i);if(l&&uf(r))o[r]=l}s.subscriptions=o}return s}function Ea(e){let t=nn(ut(e.dir,"settings.yml")),n=nn(ut(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},o={...t,...n};if(Object.keys(s).length)o.subscriptions=s;else delete o.subscriptions;return o}var Tw=/^[a-z0-9][a-z0-9._-]{0,63}$/;function uf(e){return Tw.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function df(e){let t=nn(ut(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:nn(ut(e.dir,"settings.local.yml")).subscriptions??{},o=[];for(let[r,i]of Object.entries(n))if(!s[r])o.push({...i,name:r,scope:e,file:"settings.yml"});for(let[r,i]of Object.entries(s))o.push({...i,name:r,scope:e,file:"settings.local.yml"});return o.sort((r,i)=>r.name.localeCompare(i.name))}var Ow="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function Rw(e){try{let t=Yo(e,"utf8").split(`
320
320
  `),n=[];for(let s of t)if(s.startsWith("#")||!s.trim()&&n.length)n.push(s);else break;return n.length?n.join(`
321
321
  `).replace(/\n*$/,`
322
- `):""}catch{return""}}function Tw(e,t,n){let s=ut(e.dir,t?"settings.yml":"settings.local.yml");Ew(s,()=>{let o=t?Fw(s):Aw,r={};try{let i=Bun.YAML.parse(zo(s,"utf8"));if(i&&typeof i==="object"&&!Array.isArray(i))r=i}catch(i){if(i.code!=="ENOENT")throw Error(`${s}: ${i instanceof Error?i.message:String(i)}`)}n(r),Tn(s,o+Bun.YAML.stringify(r,null,2)+`
323
- `)})}function lf(e){return tn(ut(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function Ow(e,t=process.cwd()){if(!lf(e))return;let n=tn(ut(e.dir,"settings.yml")).owner;if(!n)return`${e.dir} is restricted and names no \`owner\` in settings.yml: nobody may write it with --shared (edit the file)`;let s=(i)=>{try{return kw(wa(i))}catch{return wa(i)}},o=s(n.replace(/^~(?=\/|$)/,rf())),r=s(t);if(r===o||r.startsWith(o.endsWith("/")?o:o+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function uf(e,t,n,s={}){let o=typeof s==="boolean"?{shared:s}:s,r=o.shared===!0;if(!af(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!r&&lf(e))throw new Da(e);if(r&&!o.asOwner){let l=Ow(e,o.cwd);if(l)throw new Da(e,l)}let i=cf(e).find((l)=>l.name===t);return Tw(e,r,(l)=>{let u=l.subscriptions&&typeof l.subscriptions==="object"?l.subscriptions:{};u[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},l.subscriptions=u}),i}class Da extends Error{constructor(e,t){super(t??`${e.dir} is restricted (restrict_to_subscriptions in settings.yml): only its owner adds subscriptions, with \`slack alias set --shared\` run from the owner's directory`)}}function Rw(){return ut(vs(),"scopes")}function Iw(){try{return zo(Rw(),"utf8").split(`
324
- `).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function _a(){let e=[];for(let s of Iw())try{if(ka(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=vs();if((nf(ut(t,"settings.yml"))||nf(ut(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function Ea(e,t,n=_a()){let s=[];for(let o of n)for(let r of cf(o))if(r.channel===e&&(r.thread_ts===void 0||r.thread_ts===t))s.push(r);return s}var pf=Nw(new URL("../locales/",import.meta.url)),df=new Map;function ff(e){let t;try{t=Lw(e).mtimeMs}catch{return}let n=df.get(e);if(n&&n.mtimeMs===t)return n.pack;let s;try{let o=JSON.parse(Pw(e,"utf8"));s=o&&typeof o.lang==="string"?o:void 0}catch{s=void 0}return df.set(e,{mtimeMs:t,pack:s}),s}function hf(){let e=Yo();return e.global?void 0:$a(e.dir,"locales")}function Mw(){let e=new Set;for(let t of[pf,hf()]){if(!t)continue;try{for(let n of vw(t))if(n.endsWith(".json"))e.add(n.slice(0,-5))}catch{}}return[...e].sort()}function Go(e){let t=ff($a(pf,`${e}.json`)),n=hf(),s=n?ff($a(n,`${e}.json`)):void 0;if(!s)return t;if(!t)return s;return{...t,...s,ask:{...t.ask,...s.ask},choice_patterns:s.choice_patterns??t.choice_patterns??[]}}function Xo(e,t,n={}){let s=Go(e)?.ask??{},o=s[t]??s[`${t} (WIRE)`]??Go("en")?.ask?.[t]??Go("en")?.ask?.[`${t} (WIRE)`];if(o===void 0)throw Error(`language pack ${e}: no ask.${t}`);return o.replace(/\{(\w+)\}/g,(r,i)=>(i in n)?String(n[i]):r)}function gf(){let e=[];for(let t of Mw())for(let n of Go(t)?.choice_patterns??[])try{e.push({lang:t,re:new RegExp(n,"iu")})}catch{}return e}var Te=[{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"}],vt=Te.length,st="question",nn=`:${st}: `,Pt="heavy_plus_sign",Vo=`:${Pt}: `,wf=[Pt,st],sn="information_source",Zo=`:${sn}: `,Et=["ja","en"];function Fa(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 l=r.trim().toLowerCase();return Et.includes(l)?{lang:l,source:i}:null}let n=(e.readerLocales??[]).map(mf);if(n.length&&n[0]&&n.every((r)=>r===n[0]))return{lang:n[0],source:"readers"};let s=Ta((e.content??[]).join(`
325
- `));if(s)return{lang:s,source:"content"};let o=mf(t.LC_ALL||t.LC_MESSAGES||t.LANG);if(o)return{lang:o,source:"system"};return{lang:"en",source:"default"}}function mf(e){let t=(e??"").toLowerCase();return Et.find((n)=>t===n||/^[_.\-@]/.test(t.slice(n.length))&&t.startsWith(n))??null}function Ta(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 Me={get ja(){return yf("ja")},get en(){return yf("en")}};function yf(e){let t=(n,s)=>Xo(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${Vo}${t("otherThread")}`,otherHere:`${Vo}${t("otherHere")}`,explainLine:`${Zo}${t("explainLine")}`,explainNote:`${Zo}${t("explainNote")}`,invalidPrefix:t("invalidPrefix"),answeredVia:(n,s)=>t("answeredVia",{how:n,who:s?` (${s})`:""}),howReaction:(n)=>t("howReaction",{glyph:n}),howReply:t("howReply"),howReplyN:(n)=>t("howReplyN",{n}),voidStamp:(n)=>t("voidStamp",{reason:n?`: ${n}`:""}),supersededBy:(n)=>t("supersededBy",{link:n})}}var Bw=Et.flatMap((e)=>[Me[e].otherThread,Me[e].otherHere].map((t)=>nn+t.slice(Vo.length)));function Df(e){if(e===void 0)return null;if(e.startsWith(Vo)||e.startsWith("➕ "))return Pt;if(e.startsWith(nn)||e.startsWith("❓ "))return st;return null}function jw(e){return e!==void 0&&(e.startsWith(Zo)||e.startsWith("ℹ️ "))}function Ww(e,t){if(e===void 0)return!1;return(e.startsWith("ℹ️ ")?Zo+e.slice(3):e)===t.explainLine}var Qo="_";function kf(e){if(e===void 0||!e.endsWith(Qo))return null;return Et.find((t)=>e.startsWith(Me[t].invalidPrefix))??null}function er(e){let t=e.split(`
326
- `),n=t[t.length-2];if(!kf(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function tr(e,t,n="ja"){let s=e.split(`
327
- `);if(s.length<2)return e;if(er(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${Me[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${Qo}`);let o=s.join(`
328
- `);return o===e?e:o}function nr(e){return typeof e==="string"&&Et.some((t)=>Me[t].explainNote===e.trim())}function bf(e){return kf(e)!==null}var Oa="white_check_mark",Ls=`:${Oa}: `,Ra="no_entry_sign",Aa=`:${Ra}: `,Jw=/^【[^】]*(?:作废|作廢|superseded|void)[^】]*】/i;function sr(e){return`:${Te[e].name}:`}function xf(e,t){let n=Te[t];for(let s of[sr(t),n.glyph]){if(e.startsWith(`${s} `))return e.slice(s.length+1);if(e===s)return""}return null}function Uw(e){return Te.some((t,n)=>xf(e,n)!==null)}function Le(e){return e.replace(/\s*\n\s*/g," ")}function Ia(e,t,n,s,o,r="ja",i=!1){let l=Me[r],u=[`${nn}*${e}*`];if(t)u.push("",t);if(n.length){if(u.push(""),u.push(...n.map((c,a)=>`${sr(a)} ${Le(c)}`)),u.push(o?l.otherThread:l.otherHere),i)u.push(l.explainLine);if(s.length)u.push(""),u.push(...s.map((c,a)=>`(${a+11}) ${Le(c)}`)),u.push(l.overflowNote);u.push(""),u.push(o?l.instructionReactionThread:l.instructionReactionHere)}else{if(u.push(""),i)u.push(l.explainLine,"");u.push(o?l.instructionTextThread:l.instructionTextHere)}return u.join(`
329
- `)}function Sf(e,t,n,s="ja",o){let r=t.answer.split(`
322
+ `):""}catch{return""}}function Iw(e,t,n){let s=ut(e.dir,t?"settings.yml":"settings.local.yml");Aw(s,()=>{let o=t?Rw(s):Ow,r={};try{let i=Bun.YAML.parse(Yo(s,"utf8"));if(i&&typeof i==="object"&&!Array.isArray(i))r=i}catch(i){if(i.code!=="ENOENT")throw Error(`${s}: ${i instanceof Error?i.message:String(i)}`)}n(r),Tn(s,o+Bun.YAML.stringify(r,null,2)+`
323
+ `)})}function ff(e){return nn(ut(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function vw(e,t=process.cwd()){if(!ff(e))return;let n=nn(ut(e.dir,"settings.yml")).owner;if(!n)return`${e.dir} is restricted and names no \`owner\` in settings.yml: nobody may write it with --shared (edit the file)`;let s=(i)=>{try{return _w(ka(i))}catch{return ka(i)}},o=s(n.replace(/^~(?=\/|$)/,lf())),r=s(t);if(r===o||r.startsWith(o.endsWith("/")?o:o+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function pf(e,t,n,s={}){let o=typeof s==="boolean"?{shared:s}:s,r=o.shared===!0;if(!uf(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!r&&ff(e))throw new xa(e);if(r&&!o.asOwner){let l=vw(e,o.cwd);if(l)throw new xa(e,l)}let i=df(e).find((l)=>l.name===t);return Iw(e,r,(l)=>{let u=l.subscriptions&&typeof l.subscriptions==="object"?l.subscriptions:{};u[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},l.subscriptions=u}),i}class xa extends Error{constructor(e,t){super(t??`${e.dir} is restricted (restrict_to_subscriptions in settings.yml): only its owner adds subscriptions, with \`slack alias set --shared\` run from the owner's directory`)}}function Pw(){return ut(vs(),"scopes")}function Lw(){try{return Yo(Pw(),"utf8").split(`
324
+ `).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function $a(){let e=[];for(let s of Lw())try{if(Sa(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=vs();if((rf(ut(t,"settings.yml"))||rf(ut(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function Ca(e,t,n=$a()){let s=[];for(let o of n)for(let r of df(o))if(r.channel===e&&(r.thread_ts===void 0||r.thread_ts===t))s.push(r);return s}var mf=jw(new URL("../locales/",import.meta.url)),hf=new Map;function gf(e){let t;try{t=Bw(e).mtimeMs}catch{return}let n=hf.get(e);if(n&&n.mtimeMs===t)return n.pack;let s;try{let o=JSON.parse(Mw(e,"utf8"));s=o&&typeof o.lang==="string"?o:void 0}catch{s=void 0}return hf.set(e,{mtimeMs:t,pack:s}),s}function yf(){let e=Go();return e.global?void 0:Aa(e.dir,"locales")}function Ww(){let e=new Set;for(let t of[mf,yf()]){if(!t)continue;try{for(let n of Nw(t))if(n.endsWith(".json"))e.add(n.slice(0,-5))}catch{}}return[...e].sort()}function Xo(e){let t=gf(Aa(mf,`${e}.json`)),n=yf(),s=n?gf(Aa(n,`${e}.json`)):void 0;if(!s)return t;if(!t)return s;return{...t,...s,ask:{...t.ask,...s.ask},choice_patterns:s.choice_patterns??t.choice_patterns??[]}}function Vo(e,t,n={}){let s=Xo(e)?.ask??{},o=s[t]??s[`${t} (WIRE)`]??Xo("en")?.ask?.[t]??Xo("en")?.ask?.[`${t} (WIRE)`];if(o===void 0)throw Error(`language pack ${e}: no ask.${t}`);return o.replace(/\{(\w+)\}/g,(r,i)=>(i in n)?String(n[i]):r)}function bf(){let e=[];for(let t of Ww())for(let n of Xo(t)?.choice_patterns??[])try{e.push({lang:t,re:new RegExp(n,"iu")})}catch{}return e}var Te=[{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"}],Pt=Te.length,st="question",sn=`:${st}: `,Lt="heavy_plus_sign",Zo=`:${Lt}: `,xf=[Lt,st],on="information_source",Qo=`:${on}: `,Et=["ja","en"];function Oa(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 l=r.trim().toLowerCase();return Et.includes(l)?{lang:l,source:i}:null}let n=(e.readerLocales??[]).map(wf);if(n.length&&n[0]&&n.every((r)=>r===n[0]))return{lang:n[0],source:"readers"};let s=Ra((e.content??[]).join(`
325
+ `));if(s)return{lang:s,source:"content"};let o=wf(t.LC_ALL||t.LC_MESSAGES||t.LANG);if(o)return{lang:o,source:"system"};return{lang:"en",source:"default"}}function wf(e){let t=(e??"").toLowerCase();return Et.find((n)=>t===n||/^[_.\-@]/.test(t.slice(n.length))&&t.startsWith(n))??null}function Ra(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 Be={get ja(){return Df("ja")},get en(){return Df("en")}};function Df(e){let t=(n,s)=>Vo(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${Zo}${t("otherThread")}`,otherHere:`${Zo}${t("otherHere")}`,explainLine:`${Qo}${t("explainLine")}`,explainNote:`${Qo}${t("explainNote")}`,invalidPrefix:t("invalidPrefix"),answeredVia:(n,s)=>t("answeredVia",{how:n,who:s?` (${s})`:""}),howReaction:(n)=>t("howReaction",{glyph:n}),howReply:t("howReply"),howReplyN:(n)=>t("howReplyN",{n}),voidStamp:(n)=>t("voidStamp",{reason:n?`: ${n}`:""}),supersededBy:(n)=>t("supersededBy",{link:n})}}var Jw=Et.flatMap((e)=>[Be[e].otherThread,Be[e].otherHere].map((t)=>sn+t.slice(Zo.length)));function Sf(e){if(e===void 0)return null;if(e.startsWith(Zo)||e.startsWith("➕ "))return Lt;if(e.startsWith(sn)||e.startsWith("❓ "))return st;return null}function Uw(e){return e!==void 0&&(e.startsWith(Qo)||e.startsWith("ℹ️ "))}function Kw(e,t){if(e===void 0)return!1;return(e.startsWith("ℹ️ ")?Qo+e.slice(3):e)===t.explainLine}var er="_";function _f(e){if(e===void 0||!e.endsWith(er))return null;return Et.find((t)=>e.startsWith(Be[t].invalidPrefix))??null}function tr(e){let t=e.split(`
326
+ `),n=t[t.length-2];if(!_f(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function nr(e,t,n="ja"){let s=e.split(`
327
+ `);if(s.length<2)return e;if(tr(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${Be[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${er}`);let o=s.join(`
328
+ `);return o===e?e:o}function sr(e){return typeof e==="string"&&Et.some((t)=>Be[t].explainNote===e.trim())}function kf(e){return _f(e)!==null}var Ia="white_check_mark",Ls=`:${Ia}: `,va="no_entry_sign",Ta=`:${va}: `,qw=/^【[^】]*(?:作废|作廢|superseded|void)[^】]*】/i;function or(e){return`:${Te[e].name}:`}function Ef(e,t){let n=Te[t];for(let s of[or(t),n.glyph]){if(e.startsWith(`${s} `))return e.slice(s.length+1);if(e===s)return""}return null}function Hw(e){return Te.some((t,n)=>Ef(e,n)!==null)}function Ne(e){return e.replace(/\s*\n\s*/g," ")}function Pa(e,t,n,s,o,r="ja",i=!1){let l=Be[r],u=[`${sn}*${e}*`];if(t)u.push("",t);if(n.length){if(u.push(""),u.push(...n.map((c,a)=>`${or(a)} ${Ne(c)}`)),u.push(o?l.otherThread:l.otherHere),i)u.push(l.explainLine);if(s.length)u.push(""),u.push(...s.map((c,a)=>`(${a+11}) ${Ne(c)}`)),u.push(l.overflowNote);u.push(""),u.push(o?l.instructionReactionThread:l.instructionReactionHere)}else{if(u.push(""),i)u.push(l.explainLine,"");u.push(o?l.instructionTextThread:l.instructionTextHere)}return u.join(`
329
+ `)}function $f(e,t,n,s="ja",o){let r=t.answer.split(`
330
330
  `).map((l)=>`> ${l}`).join(`
331
331
  `),i=`${Ls}*${e}*
332
- ${Me[s].answeredVia(t.how,n)}
332
+ ${Be[s].answeredVia(t.how,n)}
333
333
 
334
334
  ${r}`;if(o?.body)i+=`
335
335
 
336
336
  ${o.body}`;if(o?.chosenLine)i+=`
337
337
 
338
- ${o.chosenLine}`;return i}function _f(e,t){let n=$t(e);if(n.kind!=="open")return;let s={};if(n.body)s.body=n.body;if(t!==void 0&&t>=1){if(t<=n.reactable.length)s.chosenLine=`${sr(t-1)} ${Le(n.reactable[t-1])}`;else if(t-vt<=n.overflow.length&&t>vt)s.chosenLine=`(${t}) ${Le(n.overflow[t-vt-1])}`}return s.body||s.chosenLine?s:void 0}function Ef(e,t,n="ja",s,o){let r=Me[n],i=`${Aa}*${e}*
339
- ${r.voidStamp(Le(t.trim()))}`;if(o)i+=`
338
+ ${o.chosenLine}`;return i}function Cf(e,t){let n=$t(e);if(n.kind!=="open")return;let s={};if(n.body)s.body=n.body;if(t!==void 0&&t>=1){if(t<=n.reactable.length)s.chosenLine=`${or(t-1)} ${Ne(n.reactable[t-1])}`;else if(t-Pt<=n.overflow.length&&t>Pt)s.chosenLine=`(${t}) ${Ne(n.overflow[t-Pt-1])}`}return s.body||s.chosenLine?s:void 0}function Af(e,t,n="ja",s,o){let r=Be[n],i=`${Ta}*${e}*
339
+ ${r.voidStamp(Ne(t.trim()))}`;if(o)i+=`
340
340
  ${r.supersededBy(o)}`;if(s)i+=`
341
341
 
342
- ${s}`;return i}function $f(e){if(!e.startsWith(nn))return null;let t=e.slice(nn.length),n=t.match(/^\*([\s\S]+?)\*(?=\s|$)/);if(!n)return null;let s=t.slice(n[0].length),o=!1;for(let r of Et){let i=Me[r];for(let u of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere])if(s.includes(u))o=!0;for(let u of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere,i.overflowNote,i.otherThread,i.otherHere,...Bw,i.explainLine])s=s.split(u).join(" ");let l=s.indexOf(i.invalidPrefix);if(l>=0){let u=s.indexOf(Qo,l+i.invalidPrefix.length);s=s.slice(0,l)+" "+(u>=0?s.slice(u+Qo.length):"")}}if(!o)return null;return{question:n[1],body:s.replace(/[ \t]{3,}/g," ").trim()}}function Cf(e){if(!e[0]?.startsWith(Ls))return-1;let t=(n)=>!!n&&(n.startsWith("> ")||n.startsWith("&gt; "));for(let n=1;n+2<e.length;n++){let s=e[n];if(s.length>1&&s.startsWith("_")&&s.endsWith("_")&&e[n+1]===""&&t(e[n+2]))return n}return-1}function Af(e){let t=e.split(`
343
- `),n=Cf(t),o=((n>0?t[n]:t[1])??"").match(/^_(?:返信|Answered by reply)(?: \((\d+)\))?/);if(!o)return{byReply:!1};return o[1]?{byReply:!0,n:Number(o[1])}:{byReply:!0}}function Ps(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Ns(e){if(!e.trim())return"the message body is empty (it may be a bot post or an attachment-only message)";let t=e.split(`
344
- `),n=t[t.length-1]??"";if(e.startsWith(Ls))return"it is marked answered, but the quoted answer text is missing";if(!/_$/.test(n))return"it does not end with the `ask` instructions line — this message was not posted by `slack ask`, or its text has been edited";if(!t[0].startsWith(nn)&&!t[0].startsWith("*"))return"it does not start with the (bold) question — its text may have been edited";return"cannot read the list of choices — they are not numbered consecutively from 1, or the text has been edited"}function $t(e){let t=e.split(`
345
- `),n=(y)=>e.startsWith(`${y}*`)&&t.some((w,x)=>x>0&&w.length>1&&w.startsWith("_")&&w.endsWith("_"));if(n(Aa)){let y=t.findIndex((E,C)=>C>0&&E.startsWith("_")&&E.endsWith("_")),w=Ps(t.slice(0,y>0?y:1).join(`
346
- `).slice(Aa.length).replace(/^\*/,"").replace(/\*$/,"")),x=y>0?t[y].replace(/^_|_$/g,""):"",D=y>0?t[y+1]?.match(/^↪ [^::]*[::] (.+)$/)?.[1]:void 0;return D?{kind:"void",question:w,reason:x,supersededBy:D}:{kind:"void",question:w,reason:x}}let s=t[0].match(Jw)?e.match(/:question: \*([^\n]*?)\*/):null;if(s)return{kind:"void",question:Ps(s[1]),reason:Ps(t[0])};if(n(Ls)){let y=(C)=>C.startsWith("> ")?C.slice(2):C.startsWith("&gt; ")?C.slice(5):null,w=Cf(t),x;if(w>0){x=[];for(let C=w+2;C<t.length;C++){let S=y(t[C]);if(S===null)break;x.push(S)}}else x=t.map(y).filter((C)=>C!==null);let D=Ps(t.slice(0,w>0?w:1).join(`
342
+ ${s}`;return i}function Ff(e){if(!e.startsWith(sn))return null;let t=e.slice(sn.length),n=t.match(/^\*([\s\S]+?)\*(?=\s|$)/);if(!n)return null;let s=t.slice(n[0].length),o=!1;for(let r of Et){let i=Be[r];for(let u of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere])if(s.includes(u))o=!0;for(let u of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere,i.overflowNote,i.otherThread,i.otherHere,...Jw,i.explainLine])s=s.split(u).join(" ");let l=s.indexOf(i.invalidPrefix);if(l>=0){let u=s.indexOf(er,l+i.invalidPrefix.length);s=s.slice(0,l)+" "+(u>=0?s.slice(u+er.length):"")}}if(!o)return null;return{question:n[1],body:s.replace(/[ \t]{3,}/g," ").trim()}}function Tf(e){if(!e[0]?.startsWith(Ls))return-1;let t=(n)=>!!n&&(n.startsWith("> ")||n.startsWith("&gt; "));for(let n=1;n+2<e.length;n++){let s=e[n];if(s.length>1&&s.startsWith("_")&&s.endsWith("_")&&e[n+1]===""&&t(e[n+2]))return n}return-1}function Of(e){let t=e.split(`
343
+ `),n=Tf(t),o=((n>0?t[n]:t[1])??"").match(/^_(?:返信|Answered by reply)(?: \((\d+)\))?/);if(!o)return{byReply:!1};return o[1]?{byReply:!0,n:Number(o[1])}:{byReply:!0}}function Ps(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Ns(e){if(!e.trim())return"the message body is empty (it may be a bot post or an attachment-only message)";let t=e.split(`
344
+ `),n=t[t.length-1]??"";if(e.startsWith(Ls))return"it is marked answered, but the quoted answer text is missing";if(!/_$/.test(n))return"it does not end with the `ask` instructions line — this message was not posted by `slack ask`, or its text has been edited";if(!t[0].startsWith(sn)&&!t[0].startsWith("*"))return"it does not start with the (bold) question — its text may have been edited";return"cannot read the list of choices — they are not numbered consecutively from 1, or the text has been edited"}function $t(e){let t=e.split(`
345
+ `),n=(y)=>e.startsWith(`${y}*`)&&t.some((w,x)=>x>0&&w.length>1&&w.startsWith("_")&&w.endsWith("_"));if(n(Ta)){let y=t.findIndex((E,C)=>C>0&&E.startsWith("_")&&E.endsWith("_")),w=Ps(t.slice(0,y>0?y:1).join(`
346
+ `).slice(Ta.length).replace(/^\*/,"").replace(/\*$/,"")),x=y>0?t[y].replace(/^_|_$/g,""):"",D=y>0?t[y+1]?.match(/^↪ [^::]*[::] (.+)$/)?.[1]:void 0;return D?{kind:"void",question:w,reason:x,supersededBy:D}:{kind:"void",question:w,reason:x}}let s=t[0].match(qw)?e.match(/:question: \*([^\n]*?)\*/):null;if(s)return{kind:"void",question:Ps(s[1]),reason:Ps(t[0])};if(n(Ls)){let y=(C)=>C.startsWith("> ")?C.slice(2):C.startsWith("&gt; ")?C.slice(5):null,w=Tf(t),x;if(w>0){x=[];for(let C=w+2;C<t.length;C++){let S=y(t[C]);if(S===null)break;x.push(S)}}else x=t.map(y).filter((C)=>C!==null);let D=Ps(t.slice(0,w>0?w:1).join(`
347
347
  `).slice(Ls.length).replace(/^\*/,"").replace(/\*$/,"")),E=x.map(Ps).join(`
348
- `);if(!E)return{kind:"other"};return{kind:"resolved",question:D,answer:E}}let o=t[t.length-1]??"",r,i,l=Et.find((y)=>[Me[y].instructionReactionThread,Me[y].instructionReactionHere,Me[y].instructionTextThread,Me[y].instructionTextHere].includes(o));if(!l)return{kind:"other"};let u=Me[l];r=o===u.instructionReactionThread||o===u.instructionTextThread,i=o===u.instructionReactionThread||o===u.instructionReactionHere;let c=t[0].startsWith(nn)?t[0].slice(nn.length):t[0];if(t[0]=c,!t[0].startsWith("*"))return{kind:"other"};let a=0;while(a<t.length&&!(t[a].endsWith("*")&&(a>0||t[0].length>1)))a++;if(a>=t.length)return{kind:"other"};let d=t.slice(0,a+1).join(`
349
- `).replace(/^\*/,"").replace(/\*$/,""),f=[],p=[],g=t.length-1;if(bf(t[g-1]))g--;let h=!1;if(i){let y=t.length-2;if(bf(t[y]))y--;if(t[y]!=="")return{kind:"other"};if(y--,t[y]===u.overflowNote){y--;while(y>=0&&/^\(\d+\) /.test(t[y]))p.unshift(t[y].replace(/^\(\d+\) /,"")),y--;if(t[y]!=="")return{kind:"other"};y--}if(jw(t[y]))h=!0,y--;if(Df(t[y]))y--;let w=[];while(y>=0){let x=t[y];if(!Uw(x))break;w.unshift(x),y--}if(!w.length||w.length>vt)return{kind:"other"};for(let x=0;x<w.length;x++){let D=xf(w[x],x);if(D===null)return{kind:"other"};f.push(D)}if(t[y]!=="")return{kind:"other"};if(y<a+1)return{kind:"other"};g=y;for(let x=0;x<p.length;x++)if(!t.includes(`(${x+11}) ${p[x]}`))return{kind:"other"}}else if(t[g-1]===""&&Ww(t[g-2],u)&&t[g-3]===""&&g-3>=a)h=!0,g-=2;let m=t.slice(a+1,g).join(`
348
+ `);if(!E)return{kind:"other"};return{kind:"resolved",question:D,answer:E}}let o=t[t.length-1]??"",r,i,l=Et.find((y)=>[Be[y].instructionReactionThread,Be[y].instructionReactionHere,Be[y].instructionTextThread,Be[y].instructionTextHere].includes(o));if(!l)return{kind:"other"};let u=Be[l];r=o===u.instructionReactionThread||o===u.instructionTextThread,i=o===u.instructionReactionThread||o===u.instructionReactionHere;let c=t[0].startsWith(sn)?t[0].slice(sn.length):t[0];if(t[0]=c,!t[0].startsWith("*"))return{kind:"other"};let a=0;while(a<t.length&&!(t[a].endsWith("*")&&(a>0||t[0].length>1)))a++;if(a>=t.length)return{kind:"other"};let d=t.slice(0,a+1).join(`
349
+ `).replace(/^\*/,"").replace(/\*$/,""),f=[],p=[],g=t.length-1;if(kf(t[g-1]))g--;let h=!1;if(i){let y=t.length-2;if(kf(t[y]))y--;if(t[y]!=="")return{kind:"other"};if(y--,t[y]===u.overflowNote){y--;while(y>=0&&/^\(\d+\) /.test(t[y]))p.unshift(t[y].replace(/^\(\d+\) /,"")),y--;if(t[y]!=="")return{kind:"other"};y--}if(Uw(t[y]))h=!0,y--;if(Sf(t[y]))y--;let w=[];while(y>=0){let x=t[y];if(!Hw(x))break;w.unshift(x),y--}if(!w.length||w.length>Pt)return{kind:"other"};for(let x=0;x<w.length;x++){let D=Ef(w[x],x);if(D===null)return{kind:"other"};f.push(D)}if(t[y]!=="")return{kind:"other"};if(y<a+1)return{kind:"other"};g=y;for(let x=0;x<p.length;x++)if(!t.includes(`(${x+11}) ${p[x]}`))return{kind:"other"}}else if(t[g-1]===""&&Kw(t[g-2],u)&&t[g-3]===""&&g-3>=a)h=!0,g-=2;let m=t.slice(a+1,g).join(`
350
350
  `).replace(/^\n+|\n+$/g,"");return{kind:"open",question:d,body:m,reactable:f,overflow:p,threadOnly:r,lang:l,explain:h}}function Ms(e){let t=$t(e);if(t.kind!=="open")return null;if(!t.reactable.length)return st;let n=e.split(`
351
- `),s=sr(t.reactable.length-1),o=Te[t.reactable.length-1].glyph,r=-1;for(let i=n.length-1;i>=0;i--)if(n[i].startsWith(`${s} `)||n[i]===s||n[i].startsWith(`${o} `)||n[i]===o){r=i;break}return(r>=0?Df(n[r+1]):null)??st}function Ca(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Ff(e,t,n){let s=Array.from({length:n},(r,i)=>i===n-1?t:""),o=va(e,s);return o.kind==="chosen"&&o.index===n}function va(e,t){let n=Ca(e);if(!n)return{kind:"none"};let s=t.map(Ca),o=new Set;s.forEach((c,a)=>{if(c&&c===n)o.add(a+1)}),Te.forEach((c,a)=>{if(a<t.length&&e.trim()===c.glyph)o.add(a+1)});let r=0,i="",l=n.match(/^(\d{1,2})$/);if(l)r=Number(l[1]);else if(l=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(r=Number(l[1]),i=Ca(l[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(r>=1&&r<=t.length&&(i===""||i===s[r-1]))o.add(r);let u=[...o].sort((c,a)=>c-a);if(!u.length)return{kind:"none"};if(u.length>1)return{kind:"ambiguous",indexes:u};return{kind:"chosen",index:u[0]}}var On={phi:1.618033988749895,minMs:1000,fastMaxMs:5000,fastWindowMs:120000,slowMaxMs:20000};function Tf(e,t){let n=t<On.fastWindowMs?On.fastMaxMs:On.slowMaxMs;return Math.min(Math.max(e,On.minMs)*On.phi,n)}import{closeSync as Kw,existsSync as or,mkdirSync as rr,openSync as qw,readFileSync as ar,realpathSync as Hw,renameSync as zw,statSync as Pa,unlinkSync as Of,writeFileSync as Yw}from"node:fs";import{homedir as Rf}from"node:os";import{dirname as La,join as He,resolve as ir}from"node:path";var If=".slack-term",Gw=["inbox","archived","outbox","sent"];function Bs(){return process.env.SLACK_TERM_HOME??He(Rf(),".config","slack-term")}function Xe(e=process.cwd()){let t=ir(e);for(;;){let n=He(t,If);try{if(Pa(n).isDirectory())return{dir:n,global:!1}}catch{}let s=La(t);if(s===t)break;t=s}return{dir:Bs(),global:!0}}var Xw='# .slack-term/\n\nState for [slack-term](https://github.com/snomiao/slack-term) in this directory.\n`slack` uses the nearest `.slack-term/` walking up from where it runs (like\n`.git`), so everything below this directory shares it. Without one it uses\n~/.config/slack-term/.\n\nNothing here is committed: `.gitignore` holds `*`.\n\n| Path | What |\n|---|---|\n| `settings.yml` | yours to edit: `prefix` (put in front of every `slack reply`, e.g. `"[design]"`), `channel` (default), `as_bot`, `subscriptions` |\n| `settings.local.yml` | written by `slack alias set/unset`; same keys, wins over `settings.yml` |\n| `inbox/` → `archived/` | one file per incoming message (`slack stream --inbox`): who, where, the text with secrets redacted, a files count, the permalink. Handled = moved to `archived/`, by `slack done` or by a sent outbox reply with `in_reply_to` |\n| `outbox/` → `sent/` | one file per queued reply (`slack outbox add`, redacted); `slack outbox flush` sends them and moves each to `sent/` with its ts and permalink. A failure stays, with `error` and `attempts` |\n\n`restrict_to_subscriptions`, `auto_subscribe` and `nudge_after_min` count only in\n`settings.yml`. With `restrict_to_subscriptions: true`, only `settings.yml`\'s\nsubscriptions count, `slack alias set` refuses (the owner uses `--shared`), and\n`reply` / `outbox flush` refuse any other thread.\n\n`subscriptions` maps an alias to a place:\n\n subscriptions:\n board:\n channel: C00000001\n thread_ts: "1700000000.000100"\n\n## Commands\n\n slack alias ls # the aliases here\n slack alias set <name> <permalink> # name a thread (a reply\'s permalink names its root)\n slack alias unset <name>\n slack read <name> # read the thread\n slack reply <name> \'<text>\' # reply in it, with the prefix, behind the --code gate\n slack reply --to <permalink> \'<text>\' # reply in the thread where that message is\n slack reply <name> --to <permalink> … # refused when that message is in another thread\n slack inbox ls | listen | nudge # what was routed here\n slack done <file|ts> # handled without a reply\n slack outbox add <name> \'<text>\' --in-reply-to <ts>\n slack outbox flush # send the queue (one --code for the batch)\n slack alias who <channel> <ts> # which dirs subscribe a thread\n',Vw=`# slack-term settings for this directory. settings.local.yml (written by
351
+ `),s=or(t.reactable.length-1),o=Te[t.reactable.length-1].glyph,r=-1;for(let i=n.length-1;i>=0;i--)if(n[i].startsWith(`${s} `)||n[i]===s||n[i].startsWith(`${o} `)||n[i]===o){r=i;break}return(r>=0?Sf(n[r+1]):null)??st}function Fa(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Rf(e,t,n){let s=Array.from({length:n},(r,i)=>i===n-1?t:""),o=La(e,s);return o.kind==="chosen"&&o.index===n}function La(e,t){let n=Fa(e);if(!n)return{kind:"none"};let s=t.map(Fa),o=new Set;s.forEach((c,a)=>{if(c&&c===n)o.add(a+1)}),Te.forEach((c,a)=>{if(a<t.length&&e.trim()===c.glyph)o.add(a+1)});let r=0,i="",l=n.match(/^(\d{1,2})$/);if(l)r=Number(l[1]);else if(l=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(r=Number(l[1]),i=Fa(l[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(r>=1&&r<=t.length&&(i===""||i===s[r-1]))o.add(r);let u=[...o].sort((c,a)=>c-a);if(!u.length)return{kind:"none"};if(u.length>1)return{kind:"ambiguous",indexes:u};return{kind:"chosen",index:u[0]}}var On={phi:1.618033988749895,minMs:1000,fastMaxMs:5000,fastWindowMs:120000,slowMaxMs:20000};function If(e,t){let n=t<On.fastWindowMs?On.fastMaxMs:On.slowMaxMs;return Math.min(Math.max(e,On.minMs)*On.phi,n)}import{closeSync as zw,existsSync as rr,mkdirSync as ir,openSync as Yw,readFileSync as cr,realpathSync as Gw,renameSync as Xw,statSync as Na,unlinkSync as vf,writeFileSync as Vw}from"node:fs";import{homedir as Pf}from"node:os";import{dirname as Ma,join as He,resolve as ar}from"node:path";var Lf=".slack-term",Zw=["inbox","archived","outbox","sent"];function Bs(){return process.env.SLACK_TERM_HOME??He(Pf(),".config","slack-term")}function Xe(e=process.cwd()){let t=ar(e);for(;;){let n=He(t,Lf);try{if(Na(n).isDirectory())return{dir:n,global:!1}}catch{}let s=Ma(t);if(s===t)break;t=s}return{dir:Bs(),global:!0}}var Qw='# .slack-term/\n\nState for [slack-term](https://github.com/snomiao/slack-term) in this directory.\n`slack` uses the nearest `.slack-term/` walking up from where it runs (like\n`.git`), so everything below this directory shares it. Without one it uses\n~/.config/slack-term/.\n\nNothing here is committed: `.gitignore` holds `*`.\n\n| Path | What |\n|---|---|\n| `settings.yml` | yours to edit: `prefix` (put in front of every `slack reply`, e.g. `"[design]"`), `channel` (default), `as_bot`, `subscriptions` |\n| `settings.local.yml` | written by `slack alias set/unset`; same keys, wins over `settings.yml` |\n| `inbox/` → `archived/` | one file per incoming message (`slack stream --inbox`): who, where, the text with secrets redacted, a files count, the permalink. Handled = moved to `archived/`, by `slack done` or by a sent outbox reply with `in_reply_to` |\n| `outbox/` → `sent/` | one file per queued reply (`slack outbox add`, redacted); `slack outbox flush` sends them and moves each to `sent/` with its ts and permalink. A failure stays, with `error` and `attempts` |\n\n`restrict_to_subscriptions`, `auto_subscribe` and `nudge_after_min` count only in\n`settings.yml`. With `restrict_to_subscriptions: true`, only `settings.yml`\'s\nsubscriptions count, `slack alias set` refuses (the owner uses `--shared`), and\n`reply` / `outbox flush` refuse any other thread.\n\n`subscriptions` maps an alias to a place:\n\n subscriptions:\n board:\n channel: C00000001\n thread_ts: "1700000000.000100"\n\n## Commands\n\n slack alias ls # the aliases here\n slack alias set <name> <permalink> # name a thread (a reply\'s permalink names its root)\n slack alias unset <name>\n slack read <name> # read the thread\n slack reply <name> \'<text>\' # reply in it, with the prefix, behind the --code gate\n slack reply --to <permalink> \'<text>\' # reply in the thread where that message is\n slack reply <name> --to <permalink> … # refused when that message is in another thread\n slack inbox ls | listen | nudge # what was routed here\n slack done <file|ts> # handled without a reply\n slack outbox add <name> \'<text>\' --in-reply-to <ts>\n slack outbox flush # send the queue (one --code for the batch)\n slack alias who <channel> <ts> # which dirs subscribe a thread\n',eD=`# slack-term settings for this directory. settings.local.yml (written by
352
352
  # \`slack alias\`) has the same keys and wins over this file.
353
353
  #
354
354
  # prefix: "[lane]" # put in front of every \`slack reply\`; never doubled
@@ -365,33 +365,33 @@ ${s}`;return i}function $f(e){if(!e.startsWith(nn))return null;let t=e.slice(nn.
365
365
  # owner: ~/ws/x/tree/shr # with restrict: --shared writes run only from under it
366
366
  # auto_subscribe: [D00000001] # new top-level messages there are subscribed here
367
367
  # nudge_after_min: 30 # \`slack inbox nudge\` reports what waits longer
368
- `;function Na(e,t={}){let n=He(ir(e),If),s=[];rr(n,{recursive:!0});for(let i of Gw){let l=He(n,i);if(!or(l))rr(l,{recursive:!0}),s.push(`${i}/`)}let o=(i,l)=>{let u=He(n,i);if(or(u))return;Ma(u,l),s.push(i)};o(".gitignore",`*
369
- `),o("README.md",Xw);let r=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0));if(o("settings.yml",Vw+(Object.keys(r).length?`
368
+ `;function Ba(e,t={}){let n=He(ar(e),Lf),s=[];ir(n,{recursive:!0});for(let i of Zw){let l=He(n,i);if(!rr(l))ir(l,{recursive:!0}),s.push(`${i}/`)}let o=(i,l)=>{let u=He(n,i);if(rr(u))return;ja(u,l),s.push(i)};o(".gitignore",`*
369
+ `),o("README.md",Qw);let r=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0));if(o("settings.yml",eD+(Object.keys(r).length?`
370
370
  `+Bun.YAML.stringify(r,null,2)+`
371
- `:"")),n!==Bs())nD(n);return{dir:n,created:s}}function Ma(e,t){rr(La(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;Yw(n,t,{mode:384}),zw(n,e)}function vf(e,t,n=1e4,s=5000){let o=`${e}.lock`;rr(La(o),{recursive:!0});let r=Date.now()+s;for(;;)try{Kw(qw(o,"wx"));break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-Pa(o).mtimeMs>n){Of(o);continue}}catch{continue}if(Date.now()>r)throw Error(`${o} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{Of(o)}catch{}}}function Zw(e){if(!e||typeof e!=="object")return;let t=e;if(typeof t.channel!=="string"||!t.channel)return;let n={channel:t.channel};if(typeof t.thread_ts==="string"&&/^\d{10}\.\d{6}$/.test(t.thread_ts))n.thread_ts=t.thread_ts;if(typeof t.added==="string")n.added=t.added;if(typeof t.note==="string")n.note=t.note;return n}function es(e){let t;try{t=Bun.YAML.parse(ar(e,"utf8"))}catch(o){if(o.code==="ENOENT")return{};throw Error(`${e}: ${o instanceof Error?o.message:String(o)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((o)=>typeof o==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let o={};for(let[r,i]of Object.entries(n.subscriptions)){let l=Zw(i);if(l&&Ba(r))o[r]=l}s.subscriptions=o}return s}function ts(e){let t=es(He(e.dir,"settings.yml")),n=es(He(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},o={...t,...n};if(Object.keys(s).length)o.subscriptions=s;else delete o.subscriptions;return o}var Qw=/^[a-z0-9][a-z0-9._-]{0,63}$/;function Ba(e){return Qw.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function on(e){let t=es(He(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:es(He(e.dir,"settings.local.yml")).subscriptions??{},o=[];for(let[r,i]of Object.entries(n))if(!s[r])o.push({...i,name:r,scope:e,file:"settings.yml"});for(let[r,i]of Object.entries(s))o.push({...i,name:r,scope:e,file:"settings.local.yml"});return o.sort((r,i)=>r.name.localeCompare(i.name))}function ja(e,t=process.cwd()){if(!Ba(e))return;let n=Xe(t),s=n.global?[n]:[n,{dir:Bs(),global:!0}];for(let o of s){let r=on(o).find((i)=>i.name===e);if(r)return r}return}var eD="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function tD(e){try{let t=ar(e,"utf8").split(`
371
+ `:"")),n!==Bs())rD(n);return{dir:n,created:s}}function ja(e,t){ir(Ma(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;Vw(n,t,{mode:384}),Xw(n,e)}function Nf(e,t,n=1e4,s=5000){let o=`${e}.lock`;ir(Ma(o),{recursive:!0});let r=Date.now()+s;for(;;)try{zw(Yw(o,"wx"));break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-Na(o).mtimeMs>n){vf(o);continue}}catch{continue}if(Date.now()>r)throw Error(`${o} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{vf(o)}catch{}}}function tD(e){if(!e||typeof e!=="object")return;let t=e;if(typeof t.channel!=="string"||!t.channel)return;let n={channel:t.channel};if(typeof t.thread_ts==="string"&&/^\d{10}\.\d{6}$/.test(t.thread_ts))n.thread_ts=t.thread_ts;if(typeof t.added==="string")n.added=t.added;if(typeof t.note==="string")n.note=t.note;return n}function es(e){let t;try{t=Bun.YAML.parse(cr(e,"utf8"))}catch(o){if(o.code==="ENOENT")return{};throw Error(`${e}: ${o instanceof Error?o.message:String(o)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((o)=>typeof o==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let o={};for(let[r,i]of Object.entries(n.subscriptions)){let l=tD(i);if(l&&Wa(r))o[r]=l}s.subscriptions=o}return s}function ts(e){let t=es(He(e.dir,"settings.yml")),n=es(He(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},o={...t,...n};if(Object.keys(s).length)o.subscriptions=s;else delete o.subscriptions;return o}var nD=/^[a-z0-9][a-z0-9._-]{0,63}$/;function Wa(e){return nD.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function rn(e){let t=es(He(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:es(He(e.dir,"settings.local.yml")).subscriptions??{},o=[];for(let[r,i]of Object.entries(n))if(!s[r])o.push({...i,name:r,scope:e,file:"settings.yml"});for(let[r,i]of Object.entries(s))o.push({...i,name:r,scope:e,file:"settings.local.yml"});return o.sort((r,i)=>r.name.localeCompare(i.name))}function Ja(e,t=process.cwd()){if(!Wa(e))return;let n=Xe(t),s=n.global?[n]:[n,{dir:Bs(),global:!0}];for(let o of s){let r=rn(o).find((i)=>i.name===e);if(r)return r}return}var sD="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function oD(e){try{let t=cr(e,"utf8").split(`
372
372
  `),n=[];for(let s of t)if(s.startsWith("#")||!s.trim()&&n.length)n.push(s);else break;return n.length?n.join(`
373
373
  `).replace(/\n*$/,`
374
- `):""}catch{return""}}function Pf(e,t,n){let s=He(e.dir,t?"settings.yml":"settings.local.yml");vf(s,()=>{let o=t?tD(s):eD,r={};try{let i=Bun.YAML.parse(ar(s,"utf8"));if(i&&typeof i==="object"&&!Array.isArray(i))r=i}catch(i){if(i.code!=="ENOENT")throw Error(`${s}: ${i instanceof Error?i.message:String(i)}`)}n(r),Ma(s,o+Bun.YAML.stringify(r,null,2)+`
375
- `)})}function In(e){return es(He(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function Lf(e,t=process.cwd()){if(!In(e))return;let n=es(He(e.dir,"settings.yml")).owner;if(!n)return`${e.dir} is restricted and names no \`owner\` in settings.yml: nobody may write it with --shared (edit the file)`;let s=(i)=>{try{return Hw(ir(i))}catch{return ir(i)}},o=s(n.replace(/^~(?=\/|$)/,Rf())),r=s(t);if(r===o||r.startsWith(o.endsWith("/")?o:o+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function Wa(e,t,n,s={}){let o=typeof s==="boolean"?{shared:s}:s,r=o.shared===!0;if(!Ba(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!r&&In(e))throw new Rn(e);if(r&&!o.asOwner){let l=Lf(e,o.cwd);if(l)throw new Rn(e,l)}let i=on(e).find((l)=>l.name===t);return Pf(e,r,(l)=>{let u=l.subscriptions&&typeof l.subscriptions==="object"?l.subscriptions:{};u[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},l.subscriptions=u}),i}function Nf(e,t,n=!1,s){let o=on(e).find((r)=>r.name===t);if(!o)return"absent";if(o.file==="settings.yml"&&!n)return"in-settings.yml";if(o.file==="settings.yml"){let r=Lf(e,s);if(r)throw new Rn(e,r)}return Pf(e,o.file==="settings.yml",(r)=>{let i=r.subscriptions;if(i)delete i[t];if(i&&!Object.keys(i).length)delete r.subscriptions}),"removed"}class Rn extends Error{constructor(e,t){super(t??`${e.dir} is restricted (restrict_to_subscriptions in settings.yml): only its owner adds subscriptions, with \`slack alias set --shared\` run from the owner's directory`)}}function Mf(){return He(Bs(),"scopes")}function nD(e){let t=Mf();vf(t,()=>{let n=Bf();if(n.includes(e))return;Ma(t,[...n,e].join(`
374
+ `):""}catch{return""}}function Mf(e,t,n){let s=He(e.dir,t?"settings.yml":"settings.local.yml");Nf(s,()=>{let o=t?oD(s):sD,r={};try{let i=Bun.YAML.parse(cr(s,"utf8"));if(i&&typeof i==="object"&&!Array.isArray(i))r=i}catch(i){if(i.code!=="ENOENT")throw Error(`${s}: ${i instanceof Error?i.message:String(i)}`)}n(r),ja(s,o+Bun.YAML.stringify(r,null,2)+`
375
+ `)})}function In(e){return es(He(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function Bf(e,t=process.cwd()){if(!In(e))return;let n=es(He(e.dir,"settings.yml")).owner;if(!n)return`${e.dir} is restricted and names no \`owner\` in settings.yml: nobody may write it with --shared (edit the file)`;let s=(i)=>{try{return Gw(ar(i))}catch{return ar(i)}},o=s(n.replace(/^~(?=\/|$)/,Pf())),r=s(t);if(r===o||r.startsWith(o.endsWith("/")?o:o+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function Ua(e,t,n,s={}){let o=typeof s==="boolean"?{shared:s}:s,r=o.shared===!0;if(!Wa(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!r&&In(e))throw new Rn(e);if(r&&!o.asOwner){let l=Bf(e,o.cwd);if(l)throw new Rn(e,l)}let i=rn(e).find((l)=>l.name===t);return Mf(e,r,(l)=>{let u=l.subscriptions&&typeof l.subscriptions==="object"?l.subscriptions:{};u[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},l.subscriptions=u}),i}function jf(e,t,n=!1,s){let o=rn(e).find((r)=>r.name===t);if(!o)return"absent";if(o.file==="settings.yml"&&!n)return"in-settings.yml";if(o.file==="settings.yml"){let r=Bf(e,s);if(r)throw new Rn(e,r)}return Mf(e,o.file==="settings.yml",(r)=>{let i=r.subscriptions;if(i)delete i[t];if(i&&!Object.keys(i).length)delete r.subscriptions}),"removed"}class Rn extends Error{constructor(e,t){super(t??`${e.dir} is restricted (restrict_to_subscriptions in settings.yml): only its owner adds subscriptions, with \`slack alias set --shared\` run from the owner's directory`)}}function Wf(){return He(Bs(),"scopes")}function rD(e){let t=Wf();Nf(t,()=>{let n=Jf();if(n.includes(e))return;ja(t,[...n,e].join(`
376
376
  `)+`
377
- `)})}function Bf(){try{return ar(Mf(),"utf8").split(`
378
- `).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function sD(){let e=[];for(let s of Bf())try{if(Pa(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=Bs();if((or(He(t,"settings.yml"))||or(He(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function jf(e,t,n=sD()){let s=[];for(let o of n)for(let r of on(o))if(r.channel===e&&(r.thread_ts===void 0||r.thread_ts===t))s.push(r);return s}function Ja(e,t){let n=t?.trim();if(!n)return e;let s=/^\[([^\]@\s]+)\]$/.exec(n),o=e;if(s){let r=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=e.replace(new RegExp(`^\\s*\\[${r}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),"")}else if(e.trimStart().startsWith(n))o=e.trimStart().slice(n.length).replace(/^[ \t]+/,"");return o.trim()?`${n} ${o}`:""}function Ua(e,t){if(e.channel===t.channel&&e.threadTs===t.root)return;let n=(s,o)=>o?`${s} thread ${o}`:`${s} (top level)`;return`the message you are answering (${t.ts}) is in ${n(t.channel,t.root)}, but the destination is ${n(e.channel,e.threadTs)}.
377
+ `)})}function Jf(){try{return cr(Wf(),"utf8").split(`
378
+ `).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function iD(){let e=[];for(let s of Jf())try{if(Na(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=Bs();if((rr(He(t,"settings.yml"))||rr(He(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function Uf(e,t,n=iD()){let s=[];for(let o of n)for(let r of rn(o))if(r.channel===e&&(r.thread_ts===void 0||r.thread_ts===t))s.push(r);return s}function Ka(e,t){let n=t?.trim();if(!n)return e;let s=/^\[([^\]@\s]+)\]$/.exec(n),o=e;if(s){let r=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=e.replace(new RegExp(`^\\s*\\[${r}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),"")}else if(e.trimStart().startsWith(n))o=e.trimStart().slice(n.length).replace(/^[ \t]+/,"");return o.trim()?`${n} ${o}`:""}function qa(e,t){if(e.channel===t.channel&&e.threadTs===t.root)return;let n=(s,o)=>o?`${s} thread ${o}`:`${s} (top level)`;return`the message you are answering (${t.ts}) is in ${n(t.channel,t.root)}, but the destination is ${n(e.channel,e.threadTs)}.
379
379
  `+` Drop the destination to reply where the message is: slack reply --to <permalink> '…'
380
- `+" Or pass --any-thread if the other thread is really meant."}var Wf=/(⬜️?|:white_large_square:)(\s*)(\d+)\./g,oD=/(✅|:white_check_mark:)\s*(\d+)\./g;function Jf(e,t){let n=[...e.matchAll(Wf)].map((i)=>Number(i[3])),s=[...e.matchAll(oD)].map((i)=>Number(i[2]));if(t===void 0){if(n.length===0)return s.length?{kind:"already",n:s[0]}:{kind:"none"};if(n.length>1)return{kind:"ambiguous",open:n};t=n[0]}if(!n.includes(t))return s.includes(t)?{kind:"already",n:t}:{kind:"missing",n:t};let o=!1;return{kind:"ticked",text:e.replace(Wf,(i,l,u,c)=>{if(o||Number(c)!==t)return i;return o=!0,`${l.startsWith(":")?":white_check_mark:":"✅"}${u}${c}.`}),n:t}}function Uf(e,t,n){let s=/^\[([^\]@\s]+)\]$/.exec(n?.trim()??"");if(!s)return t;let o=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`^\\[${o}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),i=r.exec(e);if(!i)return t;return i[0]+t.replace(r,"")}import{readFileSync as qf}from"node:fs";import{homedir as rD}from"node:os";import{join as Kf}from"node:path";var Hf=/^@([a-z0-9][a-z0-9._-]{0,63})$/;function zf(e){let t=Hf.exec(e[0]??"");return t?{who:t[1],rest:e.slice(1)}:{rest:e}}function iD(e){let t=e;if(!t||typeof t!=="object"||t.kind!=="bot"&&t.kind!=="user")return;let n={kind:t.kind};if(typeof t.env==="string"&&/^[A-Z_][A-Z0-9_]*$/.test(t.env))n.env=t.env;if(typeof t.env_file==="string")n.env_file=t.env_file;if(typeof t.profile==="string")n.profile=t.profile;return n}function Ka(e=process.cwd()){let t=Yo(e),n=t.global?[t]:[{dir:vs(),global:!0},t],s=new Map;for(let o of n){let i=tn(Kf(o.dir,"settings.yml")).restrict_to_subscriptions?["settings.yml"]:["settings.yml","settings.local.yml"];for(let l of i){let u;try{u=Bun.YAML.parse(qf(Kf(o.dir,l),"utf8"))}catch{continue}let c=u?.identities;if(!c||typeof c!=="object")continue;for(let[a,d]of Object.entries(c)){let f=iD(d);if(f&&Hf.test(`@${a}`))s.set(a,f)}}}return s}function aD(e){let t={};for(let n of qf(e.replace(/^~(?=\/|$)/,rD()),"utf8").split(`
381
- `)){let s=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!s)continue;let o=s[2];if(/^(["']).*\1$/.test(o))o=o.slice(1,-1);t[s[1]]=o}return t}function Yf(e,t=process.env,n=Ka()){let s=n.get(e),o=[...n.keys()].sort().map((l)=>`@${l}`).join(", ")||"(none: add `identities:` to .slack-term/settings.yml)";if(!s)return{error:`unknown identity @${e}. Known: ${o}`};if(s.kind==="user"&&s.profile&&!s.env&&!s.env_file)return t.SLACK_WORKSPACE=s.profile,delete t.SLACK_TOKEN,delete t.SLACK_BOT_TOKEN,t.SLACK_TERM_IDENTITY=e,{kind:"user"};let r=s.env??(s.kind==="bot"?"SLACK_BOT_TOKEN":"SLACK_TOKEN"),i;try{i=s.env_file?aD(s.env_file)[r]:t[r]}catch{return{error:`@${e}: cannot read ${s.env_file}`}}if(!i)return{error:`@${e}: no ${r}${s.env_file?` in ${s.env_file}`:" in the environment"}`};if(s.kind==="bot"&&!i.startsWith("xoxb-"))return{error:`@${e} is a bot, but ${r} is not a bot token (xoxb-)`};if(s.kind==="user"&&i.startsWith("xoxb-"))return{error:`@${e} is a user, but ${r} holds a bot token`};if(s.kind==="bot")t.SLACK_BOT_TOKEN=i,t.SLACK_TOKEN=i;else t.SLACK_TOKEN=i,delete t.SLACK_BOT_TOKEN;return t.SLACK_TERM_IDENTITY=e,{kind:s.kind}}function Gf(e=process.env){return["AY_AGENT_ID","AGENT_YES_PID","CLAUDECODE"].find((t)=>e[t])}function Xf(e){if(!e.isWrite||e.who||e.asBot||e.asUser||e.activeIsBot)return null;let t=e.identities.map((s)=>`@${s}`).join(" | "),n=t?` Name who acts: slack ${e.identities[0]?`@${e.identities[0]}`:"@<who>"} ${e.cmd} … (${t})`:" Add identities to .slack-term/settings.yml, then: slack @<who> "+e.cmd+" …";if(e.agent)return[`Error: refusing to post as the user session from inside an agent (${e.agent} is set): \`${e.cmd}\` would go out as a PERSON.`,n," As the app: add --as-bot"," As the person, on purpose: add --as-user"].join(`
380
+ `+" Or pass --any-thread if the other thread is really meant."}var Kf=/(⬜️?|:white_large_square:)(\s*)(\d+)\./g,aD=/(✅|:white_check_mark:)\s*(\d+)\./g;function qf(e,t){let n=[...e.matchAll(Kf)].map((i)=>Number(i[3])),s=[...e.matchAll(aD)].map((i)=>Number(i[2]));if(t===void 0){if(n.length===0)return s.length?{kind:"already",n:s[0]}:{kind:"none"};if(n.length>1)return{kind:"ambiguous",open:n};t=n[0]}if(!n.includes(t))return s.includes(t)?{kind:"already",n:t}:{kind:"missing",n:t};let o=!1;return{kind:"ticked",text:e.replace(Kf,(i,l,u,c)=>{if(o||Number(c)!==t)return i;return o=!0,`${l.startsWith(":")?":white_check_mark:":"✅"}${u}${c}.`}),n:t}}function Hf(e,t,n){let s=/^\[([^\]@\s]+)\]$/.exec(n?.trim()??"");if(!s)return t;let o=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`^\\[${o}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),i=r.exec(e);if(!i)return t;return i[0]+t.replace(r,"")}import{readFileSync as Yf}from"node:fs";import{homedir as cD}from"node:os";import{join as zf}from"node:path";var Gf=/^@([a-z0-9][a-z0-9._-]{0,63})$/;function Xf(e){let t=Gf.exec(e[0]??"");return t?{who:t[1],rest:e.slice(1)}:{rest:e}}function lD(e){let t=e;if(!t||typeof t!=="object"||t.kind!=="bot"&&t.kind!=="user")return;let n={kind:t.kind};if(typeof t.env==="string"&&/^[A-Z_][A-Z0-9_]*$/.test(t.env))n.env=t.env;if(typeof t.env_file==="string")n.env_file=t.env_file;if(typeof t.profile==="string")n.profile=t.profile;return n}function Ha(e=process.cwd()){let t=Go(e),n=t.global?[t]:[{dir:vs(),global:!0},t],s=new Map;for(let o of n){let i=nn(zf(o.dir,"settings.yml")).restrict_to_subscriptions?["settings.yml"]:["settings.yml","settings.local.yml"];for(let l of i){let u;try{u=Bun.YAML.parse(Yf(zf(o.dir,l),"utf8"))}catch{continue}let c=u?.identities;if(!c||typeof c!=="object")continue;for(let[a,d]of Object.entries(c)){let f=lD(d);if(f&&Gf.test(`@${a}`))s.set(a,f)}}}return s}function uD(e){let t={};for(let n of Yf(e.replace(/^~(?=\/|$)/,cD()),"utf8").split(`
381
+ `)){let s=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!s)continue;let o=s[2];if(/^(["']).*\1$/.test(o))o=o.slice(1,-1);t[s[1]]=o}return t}function Vf(e,t=process.env,n=Ha()){let s=n.get(e),o=[...n.keys()].sort().map((l)=>`@${l}`).join(", ")||"(none: add `identities:` to .slack-term/settings.yml)";if(!s)return{error:`unknown identity @${e}. Known: ${o}`};if(s.kind==="user"&&s.profile&&!s.env&&!s.env_file)return t.SLACK_WORKSPACE=s.profile,delete t.SLACK_TOKEN,delete t.SLACK_BOT_TOKEN,t.SLACK_TERM_IDENTITY=e,{kind:"user"};let r=s.env??(s.kind==="bot"?"SLACK_BOT_TOKEN":"SLACK_TOKEN"),i;try{i=s.env_file?uD(s.env_file)[r]:t[r]}catch{return{error:`@${e}: cannot read ${s.env_file}`}}if(!i)return{error:`@${e}: no ${r}${s.env_file?` in ${s.env_file}`:" in the environment"}`};if(s.kind==="bot"&&!i.startsWith("xoxb-"))return{error:`@${e} is a bot, but ${r} is not a bot token (xoxb-)`};if(s.kind==="user"&&i.startsWith("xoxb-"))return{error:`@${e} is a user, but ${r} holds a bot token`};if(s.kind==="bot")t.SLACK_BOT_TOKEN=i,t.SLACK_TOKEN=i;else t.SLACK_TOKEN=i,delete t.SLACK_BOT_TOKEN;return t.SLACK_TERM_IDENTITY=e,{kind:s.kind}}function Zf(e=process.env){return["AY_AGENT_ID","AGENT_YES_PID","CLAUDECODE"].find((t)=>e[t])}function Qf(e){if(!e.isWrite||e.who||e.asBot||e.asUser||e.activeIsBot)return null;let t=e.identities.map((s)=>`@${s}`).join(" | "),n=t?` Name who acts: slack ${e.identities[0]?`@${e.identities[0]}`:"@<who>"} ${e.cmd} … (${t})`:" Add identities to .slack-term/settings.yml, then: slack @<who> "+e.cmd+" …";if(e.agent)return[`Error: refusing to post as the user session from inside an agent (${e.agent} is set): \`${e.cmd}\` would go out as a PERSON.`,n," As the app: add --as-bot"," As the person, on purpose: add --as-user"].join(`
382
382
  `);if(e.identities.length>=2)return[`Error: several identities are configured (${t}): name the one \`${e.cmd}\` acts as.`,n," Or: --as-bot / --as-user"].join(`
383
- `);return null}var qa=/:([a-z0-9_+'-]+):((?::skin-tone-[2-6]:)?)/g,cD=/<([A-Za-z][A-Za-z0-9+.-]*:[^|<>\s]*)(?:\|([^<>]*))?>/g,lD=/&(amp|lt|gt);/g,uD=/[︎️]/gu,dD=/[\u{1F3FB}-\u{1F3FF}]/gu,Vf=String.raw`:[a-z0-9_+'-]+:(?::skin-tone-[2-6]:)?`,fD=String.raw`©®‼⁉™ℹ←-⇿⌀-⏿Ⓜ■-➿⤀-⥿⬀-⯿〰〽㊗㊙\u{1F000}-\u{1FAFF}`,Zf=String.raw`[${fD}][\u{E0020}-\u{E007F}]*`,pD=new RegExp(String.raw`(?<sc>${Vf}(?:‍${Vf})*)|(?<emoji>[0-9#*]⃣|[\u{1F1E6}-\u{1F1FF}]{2}|${Zf}(?:‍${Zf})*)|(?<char>[\s\S])`,"gu");function Ha(e){let t=new Map,n=[e??null],s=0;while(n.length&&s++<1e5){let o=n.pop();if(Array.isArray(o))n.push(...o);else if(o&&typeof o==="object"){let{name:r,unicode:i}=o;if(o.type==="emoji"&&typeof r==="string"&&typeof i==="string")try{t.set(r.split("::")[0],i.split("-").filter(Boolean).map((l)=>String.fromCodePoint(parseInt(l,16))).join(""))}catch{}n.push(...Object.values(o))}}return t}function hD(e,t,n){if(n===void 0)return t;for(let s of["http://","mailto:"])if(t.slice(0,s.length).toLowerCase()===s&&n===t.slice(s.length))return n;return e}function js(e,t){let n=e.normalize("NFC");return n=n.replace(cD,(s,o,r)=>hD(s,o,r)),n=n.replace(lD,(s,o)=>({amp:"&",lt:"<",gt:">"})[o]),n=n.replace(qa,(s,o)=>t.get(o)??s),n=n.replace(uD,"").replace(dD,""),n.split(/\s+/).filter(Boolean).join(" ")}function Qf(e){return[...e.matchAll(pD)].map((t)=>{let n=t.groups;return n.sc!==void 0?["sc",n.sc]:n.emoji!==void 0?["emoji",n.emoji]:["char",n.char]})}function ep(e,t){let n=Ha(t.blocks),s=js(e,n),o=js(typeof t.text==="string"?t.text:"",n);if(s===o)return!0;if(qa.lastIndex=0,!qa.test(o))return!1;let r=Qf(s),i=Qf(o);return r.length===i.length&&r.every(([l,u],c)=>u===i[c][1]||i[c][0]==="sc"&&l==="emoji")}function tp(e,t){let n=0;while(n<e.length&&n<t.length&&e[n]===t[n])n++;let s=Math.max(0,n-10);return`char ${n}: sent ${JSON.stringify(e.slice(s,n+30))}, stored ${JSON.stringify(t.slice(s,n+30))}`}function gD(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`\n]*`/g," ").replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ")}function np(e){let t=gf();for(let n of gD(e).split(`
384
- `))for(let s of t)if(s.re.test(n))return s.lang;return}function sp(e){return`hint: this looks like a choice question — use slack ask '${e}' "<question>" <choice>… so the reader can tap an answer instead of typing it`}import{existsSync as ip,readdirSync as SD,readFileSync as _D,renameSync as ED,statSync as $D,unlinkSync as CD,utimesSync as AD}from"node:fs";import{join as Ct}from"node:path";import{readFileSync as mD}from"node:fs";function op(e){let t="";for(;;){let r=/^\(\?([is]+)\)/.exec(e);if(!r)break;t+=r[1],e=e.slice(r[0].length)}e=e.replaceAll("(?P<","(?<").replaceAll("\\z","$").replaceAll("[[:alnum:]]","[A-Za-z0-9]").replaceAll("[:alnum:]","A-Za-z0-9").replaceAll("[:alpha:]","A-Za-z").replaceAll("[:digit:]","0-9").replaceAll("[:space:]","\\s");let n="",s=[],o=0;for(let r=0;r<e.length;r++){let i=e[r];if(i==="\\"){n+=i+(e[r+1]??""),r++;continue}if(i==="["){let l=r+1;if(e[l]==="^")l++;if(e[l]==="]")l++;while(l<e.length&&e[l]!=="]"){if(e[l]==="\\")l++;l++}n+=e.slice(r,l+1),r=l;continue}if(e.startsWith("(?i)",r)){n+="(?i:",o++,r+=3;continue}if(i==="("){s.push(o),o=0,n+=i;continue}if(i===")"){n+=")".repeat(o),o=s.pop()??0,n+=i;continue}if(i==="|"&&o){n+=")".repeat(o)+"|"+"(?i:".repeat(o);continue}n+=i}return n+=")".repeat(o),{source:n,flags:[...new Set(t)].join("")}}function yD(e){let t=Bun.TOML.parse(e),n=(i)=>{let l=op(i);return new RegExp(l.source,l.flags)},s=(t.allowlist?.regexes??[]).map(n),o=(t.allowlist?.stopwords??[]).map((i)=>i.toLowerCase()),r=[];for(let i of t.rules){if(!i.regex)continue;let l=[...s],u=[],c=[],a=[...o];for(let f of[...i.allowlists??[],...i.allowlist?[i.allowlist]:[]]){let p=f.regexTarget==="match"?u:f.regexTarget==="line"?c:l;for(let g of f.regexes??[])p.push(n(g));for(let g of f.stopwords??[])a.push(String(g).toLowerCase())}let d=op(i.regex);r.push({id:i.id,re:new RegExp(d.source,d.flags+"gd"),keywords:(i.keywords??[]).map((f)=>f.toLowerCase()),...i.entropy?{entropy:i.entropy}:{},...i.secretGroup?{group:i.secretGroup}:{},allow:l,...u.length?{allowMatch:u}:{},...c.length?{allowLine:c}:{},stop:a})}return r}var bD=[{id:"url-secret-param",re:/[?&](?:access_token|token|key|api_key|apikey|secret|client_secret|password|passwd|pwd|sig|signature)=([^&\s#<>"'|]{6,})/gid,group:1,keywords:["="],allow:[/^(?:x+|\*+|\.\.\.|your[-_]?\w*|xxx\w*)$/i],stop:[]},{id:"sk-key",re:/\b(sk-(?:proj-|ant-|or-v1-|svcacct-)?[A-Za-z0-9_-]{20,})/gd,group:1,keywords:["sk-"],entropy:3.5,allow:[],stop:[]},{id:"otp-code",re:/(?:code|コード|otp|pin|passcode|認証|確認番号|ワンタイム)[^\d\n]{0,20}(?<![\d.])(\d{6})(?![\d.])/gid,group:1,keywords:[],allow:[],stop:[]}],rp;function wD(){return rp??=[...yD(mD(new URL("./vendor/gitleaks.toml",import.meta.url),"utf8")),...bD],rp}function DD(e){let t=new Map;for(let s of e)t.set(s,(t.get(s)??0)+1);let n=0;for(let s of t.values()){let o=s/e.length;n-=o*Math.log2(o)}return n}function kD(e,t){let n=new Set;for(let o of t){if(o.length<6)continue;n.add(o),n.add(JSON.stringify(o).slice(1,-1))}let s=[];for(let o of[...n].sort((r,i)=>i.length-r.length))for(let r=e.indexOf(o);r>=0;r=e.indexOf(o,r+o.length))s.push({id:"known-secret",start:r,end:r+o.length});return s}function xD(e,t={}){let n=t.rules??wD(),s=e.toLowerCase(),o=t.known?.length?kD(e,t.known):[];for(let r of n){if(r.keywords.length&&!r.keywords.some((i)=>s.includes(i)))continue;for(let i of e.matchAll(r.re)){let l=r.group??i.findIndex((d,f)=>f>0&&!!d),u=l>0?i[l]:i[0];if(!u)continue;if(r.entropy&&DD(u)<r.entropy)continue;if(r.allow.some((d)=>d.test(u)))continue;if(r.allowMatch?.some((d)=>d.test(i[0])))continue;if(r.allowLine){let d=e.lastIndexOf(`
383
+ `);return null}var za=/:([a-z0-9_+'-]+):((?::skin-tone-[2-6]:)?)/g,dD=/<([A-Za-z][A-Za-z0-9+.-]*:[^|<>\s]*)(?:\|([^<>]*))?>/g,fD=/&(amp|lt|gt);/g,pD=/[︎️]/gu,hD=/[\u{1F3FB}-\u{1F3FF}]/gu,ep=String.raw`:[a-z0-9_+'-]+:(?::skin-tone-[2-6]:)?`,gD=String.raw`©®‼⁉™ℹ←-⇿⌀-⏿Ⓜ■-➿⤀-⥿⬀-⯿〰〽㊗㊙\u{1F000}-\u{1FAFF}`,tp=String.raw`[${gD}][\u{E0020}-\u{E007F}]*`,mD=new RegExp(String.raw`(?<sc>${ep}(?:‍${ep})*)|(?<emoji>[0-9#*]⃣|[\u{1F1E6}-\u{1F1FF}]{2}|${tp}(?:‍${tp})*)|(?<char>[\s\S])`,"gu");function Ya(e){let t=new Map,n=[e??null],s=0;while(n.length&&s++<1e5){let o=n.pop();if(Array.isArray(o))n.push(...o);else if(o&&typeof o==="object"){let{name:r,unicode:i}=o;if(o.type==="emoji"&&typeof r==="string"&&typeof i==="string")try{t.set(r.split("::")[0],i.split("-").filter(Boolean).map((l)=>String.fromCodePoint(parseInt(l,16))).join(""))}catch{}n.push(...Object.values(o))}}return t}function yD(e,t,n){if(n===void 0)return t;for(let s of["http://","mailto:"])if(t.slice(0,s.length).toLowerCase()===s&&n===t.slice(s.length))return n;return e}function js(e,t){let n=e.normalize("NFC");return n=n.replace(dD,(s,o,r)=>yD(s,o,r)),n=n.replace(fD,(s,o)=>({amp:"&",lt:"<",gt:">"})[o]),n=n.replace(za,(s,o)=>t.get(o)??s),n=n.replace(pD,"").replace(hD,""),n.split(/\s+/).filter(Boolean).join(" ")}function np(e){return[...e.matchAll(mD)].map((t)=>{let n=t.groups;return n.sc!==void 0?["sc",n.sc]:n.emoji!==void 0?["emoji",n.emoji]:["char",n.char]})}function sp(e,t){let n=Ya(t.blocks),s=js(e,n),o=js(typeof t.text==="string"?t.text:"",n);if(s===o)return!0;if(za.lastIndex=0,!za.test(o))return!1;let r=np(s),i=np(o);return r.length===i.length&&r.every(([l,u],c)=>u===i[c][1]||i[c][0]==="sc"&&l==="emoji")}function op(e,t){let n=0;while(n<e.length&&n<t.length&&e[n]===t[n])n++;let s=Math.max(0,n-10);return`char ${n}: sent ${JSON.stringify(e.slice(s,n+30))}, stored ${JSON.stringify(t.slice(s,n+30))}`}function bD(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`\n]*`/g," ").replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ")}function rp(e){let t=bf();for(let n of bD(e).split(`
384
+ `))for(let s of t)if(s.re.test(n))return s.lang;return}function ip(e){return`hint: this looks like a choice question — use slack ask '${e}' "<question>" <choice>… so the reader can tap an answer instead of typing it`}import{existsSync as lp,readdirSync as $D,readFileSync as CD,renameSync as AD,statSync as FD,unlinkSync as TD,utimesSync as OD}from"node:fs";import{join as Ct}from"node:path";import{readFileSync as wD}from"node:fs";function ap(e){let t="";for(;;){let r=/^\(\?([is]+)\)/.exec(e);if(!r)break;t+=r[1],e=e.slice(r[0].length)}e=e.replaceAll("(?P<","(?<").replaceAll("\\z","$").replaceAll("[[:alnum:]]","[A-Za-z0-9]").replaceAll("[:alnum:]","A-Za-z0-9").replaceAll("[:alpha:]","A-Za-z").replaceAll("[:digit:]","0-9").replaceAll("[:space:]","\\s");let n="",s=[],o=0;for(let r=0;r<e.length;r++){let i=e[r];if(i==="\\"){n+=i+(e[r+1]??""),r++;continue}if(i==="["){let l=r+1;if(e[l]==="^")l++;if(e[l]==="]")l++;while(l<e.length&&e[l]!=="]"){if(e[l]==="\\")l++;l++}n+=e.slice(r,l+1),r=l;continue}if(e.startsWith("(?i)",r)){n+="(?i:",o++,r+=3;continue}if(i==="("){s.push(o),o=0,n+=i;continue}if(i===")"){n+=")".repeat(o),o=s.pop()??0,n+=i;continue}if(i==="|"&&o){n+=")".repeat(o)+"|"+"(?i:".repeat(o);continue}n+=i}return n+=")".repeat(o),{source:n,flags:[...new Set(t)].join("")}}function DD(e){let t=Bun.TOML.parse(e),n=(i)=>{let l=ap(i);return new RegExp(l.source,l.flags)},s=(t.allowlist?.regexes??[]).map(n),o=(t.allowlist?.stopwords??[]).map((i)=>i.toLowerCase()),r=[];for(let i of t.rules){if(!i.regex)continue;let l=[...s],u=[],c=[],a=[...o];for(let f of[...i.allowlists??[],...i.allowlist?[i.allowlist]:[]]){let p=f.regexTarget==="match"?u:f.regexTarget==="line"?c:l;for(let g of f.regexes??[])p.push(n(g));for(let g of f.stopwords??[])a.push(String(g).toLowerCase())}let d=ap(i.regex);r.push({id:i.id,re:new RegExp(d.source,d.flags+"gd"),keywords:(i.keywords??[]).map((f)=>f.toLowerCase()),...i.entropy?{entropy:i.entropy}:{},...i.secretGroup?{group:i.secretGroup}:{},allow:l,...u.length?{allowMatch:u}:{},...c.length?{allowLine:c}:{},stop:a})}return r}var kD=[{id:"url-secret-param",re:/[?&](?:access_token|token|key|api_key|apikey|secret|client_secret|password|passwd|pwd|sig|signature)=([^&\s#<>"'|]{6,})/gid,group:1,keywords:["="],allow:[/^(?:x+|\*+|\.\.\.|your[-_]?\w*|xxx\w*)$/i],stop:[]},{id:"sk-key",re:/\b(sk-(?:proj-|ant-|or-v1-|svcacct-)?[A-Za-z0-9_-]{20,})/gd,group:1,keywords:["sk-"],entropy:3.5,allow:[],stop:[]},{id:"otp-code",re:/(?:code|コード|otp|pin|passcode|認証|確認番号|ワンタイム)[^\d\n]{0,20}(?<![\d.])(\d{6})(?![\d.])/gid,group:1,keywords:[],allow:[],stop:[]}],cp;function xD(){return cp??=[...DD(wD(new URL("./vendor/gitleaks.toml",import.meta.url),"utf8")),...kD],cp}function SD(e){let t=new Map;for(let s of e)t.set(s,(t.get(s)??0)+1);let n=0;for(let s of t.values()){let o=s/e.length;n-=o*Math.log2(o)}return n}function _D(e,t){let n=new Set;for(let o of t){if(o.length<6)continue;n.add(o),n.add(JSON.stringify(o).slice(1,-1))}let s=[];for(let o of[...n].sort((r,i)=>i.length-r.length))for(let r=e.indexOf(o);r>=0;r=e.indexOf(o,r+o.length))s.push({id:"known-secret",start:r,end:r+o.length});return s}function ED(e,t={}){let n=t.rules??xD(),s=e.toLowerCase(),o=t.known?.length?_D(e,t.known):[];for(let r of n){if(r.keywords.length&&!r.keywords.some((i)=>s.includes(i)))continue;for(let i of e.matchAll(r.re)){let l=r.group??i.findIndex((d,f)=>f>0&&!!d),u=l>0?i[l]:i[0];if(!u)continue;if(r.entropy&&SD(u)<r.entropy)continue;if(r.allow.some((d)=>d.test(u)))continue;if(r.allowMatch?.some((d)=>d.test(i[0])))continue;if(r.allowLine){let d=e.lastIndexOf(`
385
385
  `,i.index)+1,f=e.indexOf(`
386
- `,i.index+i[0].length);if(r.allowLine.some((p)=>p.test(e.slice(d,f<0?void 0:f))))continue}let c=u.toLowerCase();if(r.stop.some((d)=>c.includes(d)))continue;let a=r.group?i.indices?.[r.group]:void 0;if(a)o.push({id:r.id,start:a[0],end:a[1]});else{let d=i.index,f=i.index+i[0].length,p=/[\s'"`;=:,]/;while(d<f&&p.test(e[d]))d++;for(;;)if(f>d&&p.test(e[f-1]))f--;else if(f-2>=d&&/\\[nr]/.test(e.slice(f-2,f)))f-=2;else break;o.push({id:r.id,start:d,end:f})}}}return o}function cr(e,t={}){let n=xD(e,t).sort((i,l)=>i.start-l.start||l.end-i.end);if(!n.length)return{text:e,kinds:[]};let s=[];for(let i of n){let l=s[s.length-1];if(l&&i.start<l.end){if(i.end-i.start>l.end-l.start)l.id=i.id;l.end=Math.max(l.end,i.end)}else s.push({...i})}let o="",r=0;for(let i of s)o+=e.slice(r,i.start)+`[redacted:${i.id}]`,r=i.end;return{text:o+e.slice(r),kinds:[...new Set(s.map((i)=>i.id))]}}var FD=/^\d{10}\.\d{6}$/;function TD(e,t){return`${e}-${t}.yml`}function Ws(e){return Bun.YAML.stringify(e,null,2)+`
387
- `}function OD(e,t,n=[]){let s=TD(t.channel,t.ts);if(ip(Ct(e.dir,"inbox",s))||ip(Ct(e.dir,"archived",s)))return!1;let o=cr(t.text,{known:n}),r={...t,text:o.text,...o.kinds.length?{redacted:o.kinds}:{}};return Tn(Ct(e.dir,"inbox",s),Ws(r)),!0}function ap(e,t=_a(),n=new Date,s=[]){let o=e.thread_ts??e.ts,r=Ea(e.channel.id,o,t);if(!r.length&&!e.thread_ts){for(let u of t){if(!Sa(u).auto_subscribe?.includes(e.channel.id))continue;uf(u,`t-${e.ts}`,{channel:e.channel.id,thread_ts:e.ts,note:"auto: new top-level message"},{shared:!0,asOwner:!0})}r=Ea(e.channel.id,o,t)}let i=[],l=new Set;for(let u of r){if(l.has(u.scope.dir))continue;if(l.add(u.scope.dir),OD(u.scope,{ts:e.ts,channel:e.channel.id,channel_name:e.channel.name,...e.thread_ts?{thread_ts:e.thread_ts}:{},user:e.user.id,user_name:e.user.name,text:e.text,...e.files?{files:e.files}:{},permalink:e.permalink,alias:u.name,received_at:n.toISOString()},s))i.push(u.scope.dir)}return i}function cp(e,t){let n;try{n=SD(e).filter((o)=>o.endsWith(".yml"))}catch{return[]}let s=[];for(let o of n.sort()){let r=Ct(e,o);try{let i=t(Bun.YAML.parse(_D(r,"utf8")));if(i)s.push({file:r,entry:i,mtimeMs:$D(r).mtimeMs})}catch{}}return s}function RD(e){let t=e;return t&&typeof t.ts==="string"&&typeof t.channel==="string"&&typeof t.text==="string"?t:void 0}function ns(e){return cp(Ct(e.dir,"inbox"),RD).sort((t,n)=>Number(t.entry.ts)-Number(n.entry.ts))}function za(e,t){let n=ns(e),s=FD.test(t)?n.find((r)=>r.entry.ts===t):n.find((r)=>r.file===t||r.file.endsWith(`/${t}`)||r.file.endsWith(`/${t}.yml`));if(!s)return;let o=Ct(e.dir,"archived",s.file.slice(s.file.lastIndexOf("/")+1));return ED(s.file,o),o}function ID(e){let t=e;return t&&typeof t.to==="string"&&typeof t.text==="string"?t:void 0}function Ya(e){return cp(Ct(e.dir,"outbox"),ID)}function lp(e,t,n=new Date){let s=Ct(e.dir,"outbox",`${n.toISOString().replace(/[:.]/g,"-")}-${process.pid}.yml`),o=cr(t.text);return Tn(s,Ws({...t,text:o.text})),{file:s,redacted:o.kinds}}function up(e,t,n,s=new Date){let o=t.file.slice(t.file.lastIndexOf("/")+1),r=cr(t.entry.text),{error:i,...l}=t.entry;if(Tn(Ct(e.dir,"sent",o),Ws({...l,text:r.text,...r.kinds.length?{redacted:r.kinds}:{},...n,sent_at:s.toISOString()})),CD(t.file),t.entry.in_reply_to)za(e,t.entry.in_reply_to);return Ct(e.dir,"sent",o)}function dp(e,t){Tn(e.file,Ws({...e.entry,attempts:(e.entry.attempts??0)+1,error:t}))}function fp(e,t=Date.now()){let n=Sa(e).nudge_after_min??30;return ns(e).filter((s)=>t-s.mtimeMs>=n*60000)}function pp(e,t=new Date){Tn(e.file,Ws({...e.entry,nudged_at:t.toISOString()}));let n=new Date(e.mtimeMs);AD(e.file,n,n)}var Xa=[{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"}],O$=Xa.length,vD="question",PD=`:${vD}: `,LD="heavy_plus_sign",Ga=`:${LD}: `;var ND="information_source",hp=`:${ND}: `,mp=["ja","en"];var lr={get ja(){return gp("ja")},get en(){return gp("en")}};function gp(e){let t=(n,s)=>Xo(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${Ga}${t("otherThread")}`,otherHere:`${Ga}${t("otherHere")}`,explainLine:`${hp}${t("explainLine")}`,explainNote:`${hp}${t("explainNote")}`,invalidPrefix:t("invalidPrefix"),answeredVia:(n,s)=>t("answeredVia",{how:n,who:s?` (${s})`:""}),howReaction:(n)=>t("howReaction",{glyph:n}),howReply:t("howReply"),howReplyN:(n)=>t("howReplyN",{n}),voidStamp:(n)=>t("voidStamp",{reason:n?`: ${n}`:""}),supersededBy:(n)=>t("supersededBy",{link:n})}}var R$=mp.flatMap((e)=>[lr[e].otherThread,lr[e].otherHere].map((t)=>PD+t.slice(Ga.length)));var yp="_";function bp(e){if(e===void 0||!e.endsWith(yp))return null;return mp.find((t)=>e.startsWith(lr[t].invalidPrefix))??null}function Va(e){let t=e.split(`
388
- `),n=t[t.length-2];if(!bp(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function wp(e,t,n="ja"){let s=e.split(`
389
- `);if(s.length<2)return e;if(Va(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${lr[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${yp}`);let o=s.join(`
390
- `);return o===e?e:o}function Dp(e){return bp(e)!==null}var MD="white_check_mark",I$=`:${MD}: `,BD="no_entry_sign",v$=`:${BD}: `;var wt=Xa,ss=wt.length,Us="ballot_box_with_ballot",Za=`:${Us}: `,xp="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",Sp="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",ur="_締切: ",dr="_",ec="bar_chart",Qa=`:${ec}: `;function fr(e){return`:${wt[e].name}:`}function kp(e,t){for(let n of[fr(t),wt[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function jD(e){return wt.some((t,n)=>e.startsWith(`${fr(n)} `)||e.startsWith(`${t.glyph} `))}function Js(e){return e.replace(/\s*\n\s*/g," ")}function _p(e,t,n,s={}){let o=!!s.multi,r=s.deadline??"",i=s.invalid??[];if(!n.length||n.length>ss)throw Error(`poll needs 1..${ss} choices, got ${n.length}`);let l=[`${Za}*${e}*`];if(t)l.push("",t);if(l.push(""),l.push(...n.map((u,c)=>`${fr(c)} ${Js(u)}`)),l.push(""),r)l.push(`${ur}${Js(r)}${dr}`);return l.push(o?Sp:xp),wp(l.join(`
391
- `),o?[]:i)}function Ep(e,t){let n=t.reduce((o,r)=>o+r.count,0),s=[`${Qa}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return s.push(...t.map((o,r)=>`${fr(r)} ×${o.count} ${Js(o.choice)}`)),s.join(`
386
+ `,i.index+i[0].length);if(r.allowLine.some((p)=>p.test(e.slice(d,f<0?void 0:f))))continue}let c=u.toLowerCase();if(r.stop.some((d)=>c.includes(d)))continue;let a=r.group?i.indices?.[r.group]:void 0;if(a)o.push({id:r.id,start:a[0],end:a[1]});else{let d=i.index,f=i.index+i[0].length,p=/[\s'"`;=:,]/;while(d<f&&p.test(e[d]))d++;for(;;)if(f>d&&p.test(e[f-1]))f--;else if(f-2>=d&&/\\[nr]/.test(e.slice(f-2,f)))f-=2;else break;o.push({id:r.id,start:d,end:f})}}}return o}function lr(e,t={}){let n=ED(e,t).sort((i,l)=>i.start-l.start||l.end-i.end);if(!n.length)return{text:e,kinds:[]};let s=[];for(let i of n){let l=s[s.length-1];if(l&&i.start<l.end){if(i.end-i.start>l.end-l.start)l.id=i.id;l.end=Math.max(l.end,i.end)}else s.push({...i})}let o="",r=0;for(let i of s)o+=e.slice(r,i.start)+`[redacted:${i.id}]`,r=i.end;return{text:o+e.slice(r),kinds:[...new Set(s.map((i)=>i.id))]}}var RD=/^\d{10}\.\d{6}$/;function ID(e,t){return`${e}-${t}.yml`}function Ws(e){return Bun.YAML.stringify(e,null,2)+`
387
+ `}function vD(e,t,n=[]){let s=ID(t.channel,t.ts);if(lp(Ct(e.dir,"inbox",s))||lp(Ct(e.dir,"archived",s)))return!1;let o=lr(t.text,{known:n}),r={...t,text:o.text,...o.kinds.length?{redacted:o.kinds}:{}};return Tn(Ct(e.dir,"inbox",s),Ws(r)),!0}function up(e,t=$a(),n=new Date,s=[]){let o=e.thread_ts??e.ts,r=Ca(e.channel.id,o,t);if(!r.length&&!e.thread_ts){for(let u of t){if(!Ea(u).auto_subscribe?.includes(e.channel.id))continue;pf(u,`t-${e.ts}`,{channel:e.channel.id,thread_ts:e.ts,note:"auto: new top-level message"},{shared:!0,asOwner:!0})}r=Ca(e.channel.id,o,t)}let i=[],l=new Set;for(let u of r){if(l.has(u.scope.dir))continue;if(l.add(u.scope.dir),vD(u.scope,{ts:e.ts,channel:e.channel.id,channel_name:e.channel.name,...e.thread_ts?{thread_ts:e.thread_ts}:{},user:e.user.id,user_name:e.user.name,text:e.text,...e.files?{files:e.files}:{},permalink:e.permalink,alias:u.name,received_at:n.toISOString()},s))i.push(u.scope.dir)}return i}function dp(e,t){let n;try{n=$D(e).filter((o)=>o.endsWith(".yml"))}catch{return[]}let s=[];for(let o of n.sort()){let r=Ct(e,o);try{let i=t(Bun.YAML.parse(CD(r,"utf8")));if(i)s.push({file:r,entry:i,mtimeMs:FD(r).mtimeMs})}catch{}}return s}function PD(e){let t=e;return t&&typeof t.ts==="string"&&typeof t.channel==="string"&&typeof t.text==="string"?t:void 0}function ns(e){return dp(Ct(e.dir,"inbox"),PD).sort((t,n)=>Number(t.entry.ts)-Number(n.entry.ts))}function Ga(e,t){let n=ns(e),s=RD.test(t)?n.find((r)=>r.entry.ts===t):n.find((r)=>r.file===t||r.file.endsWith(`/${t}`)||r.file.endsWith(`/${t}.yml`));if(!s)return;let o=Ct(e.dir,"archived",s.file.slice(s.file.lastIndexOf("/")+1));return AD(s.file,o),o}function LD(e){let t=e;return t&&typeof t.to==="string"&&typeof t.text==="string"?t:void 0}function Xa(e){return dp(Ct(e.dir,"outbox"),LD)}function fp(e,t,n=new Date){let s=Ct(e.dir,"outbox",`${n.toISOString().replace(/[:.]/g,"-")}-${process.pid}.yml`),o=lr(t.text);return Tn(s,Ws({...t,text:o.text})),{file:s,redacted:o.kinds}}function pp(e,t,n,s=new Date){let o=t.file.slice(t.file.lastIndexOf("/")+1),r=lr(t.entry.text),{error:i,...l}=t.entry;if(Tn(Ct(e.dir,"sent",o),Ws({...l,text:r.text,...r.kinds.length?{redacted:r.kinds}:{},...n,sent_at:s.toISOString()})),TD(t.file),t.entry.in_reply_to)Ga(e,t.entry.in_reply_to);return Ct(e.dir,"sent",o)}function hp(e,t){Tn(e.file,Ws({...e.entry,attempts:(e.entry.attempts??0)+1,error:t}))}function gp(e,t=Date.now()){let n=Ea(e).nudge_after_min??30;return ns(e).filter((s)=>t-s.mtimeMs>=n*60000)}function mp(e,t=new Date){Tn(e.file,Ws({...e.entry,nudged_at:t.toISOString()}));let n=new Date(e.mtimeMs);OD(e.file,n,n)}var Za=[{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"}],I$=Za.length,ND="question",MD=`:${ND}: `,BD="heavy_plus_sign",Va=`:${BD}: `;var jD="information_source",yp=`:${jD}: `,wp=["ja","en"];var ur={get ja(){return bp("ja")},get en(){return bp("en")}};function bp(e){let t=(n,s)=>Vo(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${Va}${t("otherThread")}`,otherHere:`${Va}${t("otherHere")}`,explainLine:`${yp}${t("explainLine")}`,explainNote:`${yp}${t("explainNote")}`,invalidPrefix:t("invalidPrefix"),answeredVia:(n,s)=>t("answeredVia",{how:n,who:s?` (${s})`:""}),howReaction:(n)=>t("howReaction",{glyph:n}),howReply:t("howReply"),howReplyN:(n)=>t("howReplyN",{n}),voidStamp:(n)=>t("voidStamp",{reason:n?`: ${n}`:""}),supersededBy:(n)=>t("supersededBy",{link:n})}}var v$=wp.flatMap((e)=>[ur[e].otherThread,ur[e].otherHere].map((t)=>MD+t.slice(Va.length)));var Dp="_";function kp(e){if(e===void 0||!e.endsWith(Dp))return null;return wp.find((t)=>e.startsWith(ur[t].invalidPrefix))??null}function Qa(e){let t=e.split(`
388
+ `),n=t[t.length-2];if(!kp(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function xp(e,t,n="ja"){let s=e.split(`
389
+ `);if(s.length<2)return e;if(Qa(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${ur[n].invalidPrefix}${t.map((r)=>`<@${r}>`).join(", ")}${Dp}`);let o=s.join(`
390
+ `);return o===e?e:o}function Sp(e){return kp(e)!==null}var WD="white_check_mark",P$=`:${WD}: `,JD="no_entry_sign",L$=`:${JD}: `;var wt=Za,ss=wt.length,Us="ballot_box_with_ballot",ec=`:${Us}: `,Ep="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",$p="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",dr="_締切: ",fr="_",nc="bar_chart",tc=`:${nc}: `;function pr(e){return`:${wt[e].name}:`}function _p(e,t){for(let n of[pr(t),wt[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function UD(e){return wt.some((t,n)=>e.startsWith(`${pr(n)} `)||e.startsWith(`${t.glyph} `))}function Js(e){return e.replace(/\s*\n\s*/g," ")}function Cp(e,t,n,s={}){let o=!!s.multi,r=s.deadline??"",i=s.invalid??[];if(!n.length||n.length>ss)throw Error(`poll needs 1..${ss} choices, got ${n.length}`);let l=[`${ec}*${e}*`];if(t)l.push("",t);if(l.push(""),l.push(...n.map((u,c)=>`${pr(c)} ${Js(u)}`)),l.push(""),r)l.push(`${dr}${Js(r)}${fr}`);return l.push(o?$p:Ep),xp(l.join(`
391
+ `),o?[]:i)}function Ap(e,t){let n=t.reduce((o,r)=>o+r.count,0),s=[`${tc}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return s.push(...t.map((o,r)=>`${pr(r)} ×${o.count} ${Js(o.choice)}`)),s.join(`
392
392
  `)}function Ks(e){let t=e.split(`
393
- `);if(e.startsWith(Qa)){let f=t[0].slice(Qa.length).replace(/^\*/,"").replace(/\*$/,""),p=[];for(let g=0;g<wt.length;g++){let h=t.map((y)=>kp(y,g)).find((y)=>y!==null&&y.startsWith("×"));if(h===void 0)break;let m=/^×(\d+) (.*)$/.exec(h);if(!m)return{kind:"other"};p.push({choice:m[2],count:Number(m[1])})}if(!p.length)return{kind:"other"};return{kind:"closed",question:f,tallies:p}}let n=t[t.length-1]??"",s;if(n===xp)s=!1;else if(n===Sp)s=!0;else return{kind:"other"};if(t[0].startsWith(Za))t[0]=t[0].slice(Za.length);if(!t[0].startsWith("*"))return{kind:"other"};let o=0;while(o<t.length&&!(t[o].endsWith("*")&&(o>0||t[0].length>1)))o++;if(o>=t.length)return{kind:"other"};let r=t.slice(0,o+1).join(`
394
- `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,l=Va(e);if(Dp(t[i]))i--;let u="",c=t[i];if(c!==void 0&&c.startsWith(ur)&&c.endsWith(dr)&&c.length>ur.length+dr.length)u=c.slice(ur.length,-dr.length),i--;if(t[i]!=="")return{kind:"other"};i--;let a=[];while(i>=0){let f=t[i];if(!jD(f))break;a.unshift(f),i--}if(!a.length||a.length>ss)return{kind:"other"};let d=[];for(let f=0;f<a.length;f++){let p=kp(a[f],f);if(p===null)return{kind:"other"};d.push(p)}if(t[i]!=="")return{kind:"other"};if(i<o+1)return{kind:"other"};return{kind:"open",question:r,choices:d,multi:s,deadline:u,invalid:l}}function $p(e,t,n,s){let o=new Map(t.map((c)=>[c.name,c.users])),r=e.map((c,a)=>(o.get(wt[a].name)??[]).filter((d)=>!n.has(d))),i=[];if(!s){let c=new Map;for(let a of r)for(let d of a)c.set(d,(c.get(d)??0)+1);for(let[a,d]of c)if(d>1)i.push(a)}let l=new Set(i),u=r.map((c)=>c.filter((a)=>!l.has(a)));return{tallies:e.map((c,a)=>({choice:c,count:u[a].length})),voters:u,ambiguous:i}}function WD(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var Cp={isTestEnv:()=>WD(),sleep:(e)=>Cp.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function JD(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 pr(e,t,n,s=JD()){for(let o=0;o<e.length;o++){let r=!0;try{await t(e[o])}catch(i){r=!1,n(e[o],i)}if(r&&s>0&&o<e.length-1)await Cp.sleep(s)}}var Ap=["text","select","user","link","date","number","checkbox"];function Tp(e){let t=e.split(":"),n=(t[0]??"").trim(),s=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!Ap.includes(s))throw Error(`--col ${e}: unknown type "${s}" (expected one of ${Ap.join(", ")})`);if(s==="select"){let o=(t.slice(2).join(":")||"").split(",").map((r)=>r.trim()).filter(Boolean);if(!o.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:s,choices:o}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:s}}var Fp=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function Op(e){if(!e.length)throw Error("at least one --col is required (the first one is the primary text column)");if(e[0].type!=="text")throw Error(`the first --col is the primary column and must be text, got ${e[0].type}`);return e.map((t,n)=>{let s={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)s.is_primary_column=!0;if(t.type==="select")s.options={format:"single_select",choices:t.choices.map((o,r)=>({value:o,label:o,color:Fp[r%Fp.length]}))};if(t.type==="user")s.options={format:"single_entity"};return s})}function Rp(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((s)=>{let o=s??{},i=((o.options??{}).choices??[]).map((l)=>{let u=l??{};return{value:String(u.value??""),label:String(u.label??u.value??"")}});return{id:String(o.id??""),key:String(o.key??""),name:String(o.name??""),type:String(o.type??""),choices:i}})}function tc(e,t){let n=e.find((s)=>s.name===t)??e.find((s)=>s.key===t)??e.find((s)=>s.id===t);if(!n)throw Error(`no column "${t}" in this list (columns: ${e.map((s)=>s.name||s.key).join(", ")})`);return n}function nc(e,t){switch(e.type){case"text":return{rich_text:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:t}]}]}]};case"select":{let n=e.choices.find((s)=>s.value===t||s.label===t);if(!n)throw Error(`"${t}" is not an option of ${e.name} (options: ${e.choices.map((s)=>s.label).join(", ")})`);return{select:[n.value]}}case"user":return{user:[t]};case"link":return{link:[{original_url:t,display_as_url:!0}]};case"date":return{date:[t]};case"number":{let n=Number(t);if(!Number.isFinite(n))throw Error(`${e.name}: "${t}" is not a number`);return{number:[n]}}case"checkbox":case"todo_completed":if(!["true","false"].includes(t))throw Error(`${e.name}: expected true or false, got "${t}"`);return{checkbox:t==="true"};default:throw Error(`writing a ${e.type} column (${e.name}) from the CLI is not supported`)}}function sc(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 Ip(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as rc}from"node:child_process";import{chmodSync as UD,existsSync as Pp,mkdirSync as KD}from"node:fs";import{homedir as qD,hostname as HD}from"node:os";import{basename as Lp,dirname as zD,join as YD}from"node:path";function gr(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var hr={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function GD(e){try{let n=(rc("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:Lp(n[2].trim())}}catch{return}}function XD(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=GD(e);if(!n)return;if(hr[n.comm])return n;e=n.ppid}return}function vp(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Np(e=process.env){let t={pid:process.pid,host:VD(),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 s=vp(e.SLACK_TERM_AGENT_PID)??vp(e.CLAUDE_PID);if(!s||!n){let i=XD();if(i)s??=i.pid,n??=hr[i.comm]}if(n)t.cli=n;if(s)t.agentPid=s;let o=e.SLACK_TERM_AGENT_SESSION||e.CLAUDE_CODE_SESSION_ID;if(o)t.sessionId=o;let r=ZD(t.cwd);if(r)t.gitBranch=r;return t}function VD(){try{return HD()}catch{return""}}function ZD(e){try{let t=rc("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var QD="slack_term_sent";function Mp(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:QD,event_payload:n}}function At(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return YD(process.env.HOME||qD(),".config","slack-cli","sent.sqlite")}function e0(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=ps("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 t0=`
393
+ `);if(e.startsWith(tc)){let f=t[0].slice(tc.length).replace(/^\*/,"").replace(/\*$/,""),p=[];for(let g=0;g<wt.length;g++){let h=t.map((y)=>_p(y,g)).find((y)=>y!==null&&y.startsWith("×"));if(h===void 0)break;let m=/^×(\d+) (.*)$/.exec(h);if(!m)return{kind:"other"};p.push({choice:m[2],count:Number(m[1])})}if(!p.length)return{kind:"other"};return{kind:"closed",question:f,tallies:p}}let n=t[t.length-1]??"",s;if(n===Ep)s=!1;else if(n===$p)s=!0;else return{kind:"other"};if(t[0].startsWith(ec))t[0]=t[0].slice(ec.length);if(!t[0].startsWith("*"))return{kind:"other"};let o=0;while(o<t.length&&!(t[o].endsWith("*")&&(o>0||t[0].length>1)))o++;if(o>=t.length)return{kind:"other"};let r=t.slice(0,o+1).join(`
394
+ `).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,l=Qa(e);if(Sp(t[i]))i--;let u="",c=t[i];if(c!==void 0&&c.startsWith(dr)&&c.endsWith(fr)&&c.length>dr.length+fr.length)u=c.slice(dr.length,-fr.length),i--;if(t[i]!=="")return{kind:"other"};i--;let a=[];while(i>=0){let f=t[i];if(!UD(f))break;a.unshift(f),i--}if(!a.length||a.length>ss)return{kind:"other"};let d=[];for(let f=0;f<a.length;f++){let p=_p(a[f],f);if(p===null)return{kind:"other"};d.push(p)}if(t[i]!=="")return{kind:"other"};if(i<o+1)return{kind:"other"};return{kind:"open",question:r,choices:d,multi:s,deadline:u,invalid:l}}function Fp(e,t,n,s){let o=new Map(t.map((c)=>[c.name,c.users])),r=e.map((c,a)=>(o.get(wt[a].name)??[]).filter((d)=>!n.has(d))),i=[];if(!s){let c=new Map;for(let a of r)for(let d of a)c.set(d,(c.get(d)??0)+1);for(let[a,d]of c)if(d>1)i.push(a)}let l=new Set(i),u=r.map((c)=>c.filter((a)=>!l.has(a)));return{tallies:e.map((c,a)=>({choice:c,count:u[a].length})),voters:u,ambiguous:i}}function KD(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var Tp={isTestEnv:()=>KD(),sleep:(e)=>Tp.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function qD(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 hr(e,t,n,s=qD()){for(let o=0;o<e.length;o++){let r=!0;try{await t(e[o])}catch(i){r=!1,n(e[o],i)}if(r&&s>0&&o<e.length-1)await Tp.sleep(s)}}var Op=["text","select","user","link","date","number","checkbox"];function Ip(e){let t=e.split(":"),n=(t[0]??"").trim(),s=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!Op.includes(s))throw Error(`--col ${e}: unknown type "${s}" (expected one of ${Op.join(", ")})`);if(s==="select"){let o=(t.slice(2).join(":")||"").split(",").map((r)=>r.trim()).filter(Boolean);if(!o.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:s,choices:o}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:s}}var Rp=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function vp(e){if(!e.length)throw Error("at least one --col is required (the first one is the primary text column)");if(e[0].type!=="text")throw Error(`the first --col is the primary column and must be text, got ${e[0].type}`);return e.map((t,n)=>{let s={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)s.is_primary_column=!0;if(t.type==="select")s.options={format:"single_select",choices:t.choices.map((o,r)=>({value:o,label:o,color:Rp[r%Rp.length]}))};if(t.type==="user")s.options={format:"single_entity"};return s})}function Pp(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((s)=>{let o=s??{},i=((o.options??{}).choices??[]).map((l)=>{let u=l??{};return{value:String(u.value??""),label:String(u.label??u.value??"")}});return{id:String(o.id??""),key:String(o.key??""),name:String(o.name??""),type:String(o.type??""),choices:i}})}function sc(e,t){let n=e.find((s)=>s.name===t)??e.find((s)=>s.key===t)??e.find((s)=>s.id===t);if(!n)throw Error(`no column "${t}" in this list (columns: ${e.map((s)=>s.name||s.key).join(", ")})`);return n}function oc(e,t){switch(e.type){case"text":return{rich_text:[{type:"rich_text",elements:[{type:"rich_text_section",elements:[{type:"text",text:t}]}]}]};case"select":{let n=e.choices.find((s)=>s.value===t||s.label===t);if(!n)throw Error(`"${t}" is not an option of ${e.name} (options: ${e.choices.map((s)=>s.label).join(", ")})`);return{select:[n.value]}}case"user":return{user:[t]};case"link":return{link:[{original_url:t,display_as_url:!0}]};case"date":return{date:[t]};case"number":{let n=Number(t);if(!Number.isFinite(n))throw Error(`${e.name}: "${t}" is not a number`);return{number:[n]}}case"checkbox":case"todo_completed":if(!["true","false"].includes(t))throw Error(`${e.name}: expected true or false, got "${t}"`);return{checkbox:t==="true"};default:throw Error(`writing a ${e.type} column (${e.name}) from the CLI is not supported`)}}function rc(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 Lp(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as ac}from"node:child_process";import{chmodSync as HD,existsSync as Mp,mkdirSync as zD}from"node:fs";import{homedir as YD,hostname as GD}from"node:os";import{basename as Bp,dirname as XD,join as VD}from"node:path";function mr(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var gr={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function ZD(e){try{let n=(ac("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:Bp(n[2].trim())}}catch{return}}function QD(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=ZD(e);if(!n)return;if(gr[n.comm])return n;e=n.ppid}return}function Np(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function jp(e=process.env){let t={pid:process.pid,host:e0(),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 s=Np(e.SLACK_TERM_AGENT_PID)??Np(e.CLAUDE_PID);if(!s||!n){let i=QD();if(i)s??=i.pid,n??=gr[i.comm]}if(n)t.cli=n;if(s)t.agentPid=s;let o=e.SLACK_TERM_AGENT_SESSION||e.CLAUDE_CODE_SESSION_ID;if(o)t.sessionId=o;let r=t0(t.cwd);if(r)t.gitBranch=r;return t}function e0(){try{return GD()}catch{return""}}function t0(e){try{let t=ac("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var n0="slack_term_sent";function Wp(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:n0,event_payload:n}}function At(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return VD(process.env.HOME||YD(),".config","slack-cli","sent.sqlite")}function s0(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=ps("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 o0=`
395
395
  CREATE TABLE IF NOT EXISTS sent (
396
396
  id INTEGER PRIMARY KEY AUTOINCREMENT,
397
397
  kind TEXT NOT NULL,
@@ -420,166 +420,167 @@ CREATE TABLE IF NOT EXISTS sent (
420
420
  );
421
421
  CREATE INDEX IF NOT EXISTS sent_msg ON sent(channel, ts);
422
422
  CREATE INDEX IF NOT EXISTS sent_at ON sent(sent_at);
423
- `;function mr(){let e=At();try{KD(zD(e),{recursive:!0})}catch{}let t=e0(e);if(!t)return;try{UD(e,384)}catch{}try{t.exec(t0);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 Bp(e){if(!gr())return!1;let t=mr();if(!t)return console.error(` (could not record to the sent log: ${qs} — ${At()})`),!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)
424
- 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(` (could not record to the sent log: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var qs="cannot open the sent log: this runtime has no SQLite (needs bun, or node >= 22.5 for node:sqlite)";function ic(e){let t=mr();if(!t)return;try{let n=[],s=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),s.push(`%${oc(e.text)}%`);if(e.channel)n.push("(channel = ? OR target = ?)"),s.push(e.channel,e.channel);if(e.sinceMs!==void 0)n.push("sent_at >= ?"),s.push(e.sinceMs);if(e.session)n.push("session_id LIKE ? ESCAPE '\\'"),s.push(`${oc(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),s.push(`${oc(e.cwd)}%`);if(e.kind)n.push("kind = ?"),s.push(e.kind);let o=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return s.push(e.limit??50),t.prepare(o).all(...s)}finally{try{t.close()}catch{}}}function oc(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function yr(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let o={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*o}let s=Date.parse(e);return Number.isNaN(s)?void 0:s}function jp(e,...t){if(!gr()||!Pp(At()))return;let n=mr();if(!n)return;try{n.prepare(e).run(...t)}catch{}finally{try{n.close()}catch{}}}function ac(e,t,n,s){let o=Date.now();jp(`UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer = ?, answer_exit = 0,
423
+ `;function yr(){let e=At();try{zD(XD(e),{recursive:!0})}catch{}let t=s0(e);if(!t)return;try{HD(e,384)}catch{}try{t.exec(o0);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 Jp(e){if(!mr())return!1;let t=yr();if(!t)return console.error(` (could not record to the sent log: ${qs} — ${At()})`),!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)
424
+ 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(` (could not record to the sent log: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var qs="cannot open the sent log: this runtime has no SQLite (needs bun, or node >= 22.5 for node:sqlite)";function cc(e){let t=yr();if(!t)return;try{let n=[],s=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),s.push(`%${ic(e.text)}%`);if(e.channel)n.push("(channel = ? OR target = ?)"),s.push(e.channel,e.channel);if(e.sinceMs!==void 0)n.push("sent_at >= ?"),s.push(e.sinceMs);if(e.session)n.push("session_id LIKE ? ESCAPE '\\'"),s.push(`${ic(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),s.push(`${ic(e.cwd)}%`);if(e.kind)n.push("kind = ?"),s.push(e.kind);let o=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return s.push(e.limit??50),t.prepare(o).all(...s)}finally{try{t.close()}catch{}}}function ic(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function br(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let o={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*o}let s=Date.parse(e);return Number.isNaN(s)?void 0:s}function Up(e,...t){if(!mr()||!Mp(At()))return;let n=yr();if(!n)return;try{n.prepare(e).run(...t)}catch{}finally{try{n.close()}catch{}}}function lc(e,t,n,s){let o=Date.now();Up(`UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer = ?, answer_exit = 0,
425
425
  delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
426
- WHERE kind = 'ask' AND channel = ? AND ts = ?`,o,n,o,n,s,e,t)}function Wp(e,t,n,s){jp(`UPDATE sent SET delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
427
- WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,s,e,t)}function Jp(e){if(!Pp(At()))return[];let t=mr();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 Up(e){let t=e.agent_pid??e.pid;if(!n0(t))return!1;try{let s=(rc("ps",["-o","lstart=,comm=","-p",String(t)],{encoding:"utf8",timeout:2000}).stdout??"").trim(),o=Date.parse(s.slice(0,24));if(!Number.isNaN(o)&&o>e.sent_at+1000)return!1;let r=Lp(s.slice(24).trim()),i=new Set(Object.values(hr));if(e.cli&&i.has(e.cli)&&r&&hr[r]!==e.cli)return!1}catch{}return!0}function n0(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}class Dt 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 uc(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}var Hp=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();function zp(e){Hp=e}async function Yp(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof Dt)||n+s.retryAfter>Hp)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function Gp(e,t,n,s){return Yp(()=>s0(e,t,n,s))}async function s0(e,t,n,s){s=e.startsWith("xoxc-")?s??Vt():void 0;let o={};if(s)o.Cookie=`d=${s}`;let r=await fetch(`${uc()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(r.status===429){let l=parseInt(r.headers.get("retry-after")??"60",10);throw new Dt(isNaN(l)?60:l,t)}let i=await r.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new Dt(60,t);if(l==="invalid_auth"&&e.startsWith("xoxc-")&&!s)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
426
+ WHERE kind = 'ask' AND channel = ? AND ts = ?`,o,n,o,n,s,e,t)}function Kp(e,t,n,s){Up(`UPDATE sent SET delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
427
+ WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,s,e,t)}function qp(e){if(!Mp(At()))return[];let t=yr();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 Hp(e){let t=e.agent_pid??e.pid;if(!r0(t))return!1;try{let s=(ac("ps",["-o","lstart=,comm=","-p",String(t)],{encoding:"utf8",timeout:2000}).stdout??"").trim(),o=Date.parse(s.slice(0,24));if(!Number.isNaN(o)&&o>e.sent_at+1000)return!1;let r=Bp(s.slice(24).trim()),i=new Set(Object.values(gr));if(e.cli&&i.has(e.cli)&&r&&gr[r]!==e.cli)return!1}catch{}return!0}function r0(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}class Dt 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 fc(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}var Gp=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();function Xp(e){Gp=e}async function Vp(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof Dt)||n+s.retryAfter>Gp)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function Zp(e,t,n,s){return Vp(()=>i0(e,t,n,s))}async function i0(e,t,n,s){s=e.startsWith("xoxc-")?s??Zt():void 0;let o={};if(s)o.Cookie=`d=${s}`;let r=await fetch(`${fc()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(r.status===429){let l=parseInt(r.headers.get("retry-after")??"60",10);throw new Dt(isNaN(l)?60:l,t)}let i=await r.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new Dt(60,t);if(l==="invalid_auth"&&e.startsWith("xoxc-")&&!s)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
428
428
  Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
429
429
  Or replace the token with an xoxp- user token:
430
430
  slack auth login`);if((l==="missing_scope"||l==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${l}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${l} — ${l==="cannot_dm_bot"?`you're authenticated as a bot, so "@you" is the bot itself and it can't DM itself`:"this bot token lacks the user scope this action needs"}.
431
431
  Tailing/DMing people and listing users need a user session, not a bot token.
432
432
  Switch workspace: slack auth ls then slack auth use <name>
433
- Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${l}`)}return i}function o0(e,t,n,s){return Yp(()=>r0(e,t,n,s))}async function r0(e,t,n,s){let o={};if(s)o.Cookie=`d=${s}`;let r=await fetch(`${uc()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(r.status===429){let l=parseInt(r.headers.get("retry-after")??"60",10);throw new Dt(isNaN(l)?60:l,t)}let i=await r.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new Dt(60,t);if((l==="invalid_auth"||l==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
433
+ Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${l}`)}return i}function a0(e,t,n,s){return Vp(()=>c0(e,t,n,s))}async function c0(e,t,n,s){let o={};if(s)o.Cookie=`d=${s}`;let r=await fetch(`${fc()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(r.status===429){let l=parseInt(r.headers.get("retry-after")??"60",10);throw new Dt(isNaN(l)?60:l,t)}let i=await r.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new Dt(60,t);if((l==="invalid_auth"||l==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
434
434
  Import from Slack desktop: slack auth login`);if((l==="invalid_auth"||l==="not_authed")&&!s)throw Error(`${t} also requires the xoxd session cookie.
435
- Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${l}`)}return i}function kt(e,t,n={},s){let o=new URLSearchParams({token:e,...n});return o0(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()},s)}function ye(e,t,n,s){let o=new URLSearchParams(n).toString();return Gp(e,`${t}?${o}`,{method:"GET"},s)}function Oe(e,t,n,s){return Gp(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function dc(e,t){let n=await ye(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Lt(e,t){t=e.startsWith("xoxc-")?t??Vt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let s=await fetch(`${uc()}/auth.test`,{method:"GET",headers:n});if(s.status===429){let i=parseInt(s.headers.get("retry-after")??"60",10);throw new Dt(isNaN(i)?60:i,"auth.test")}let o=s.headers.get("x-oauth-scopes")??"",r=await s.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:o.split(",").map((i)=>i.trim()).filter(Boolean)}}async function Xp(e,t,n){let s=await ye(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function ot(e,t,n=20,s,o,r,i){let l={channel:t,limit:String(n)};if(s!==void 0)l.oldest=s;if(o!==void 0)l.cursor=o;if(i)l.inclusive="true";return br(await ye(e,"conversations.history",l,r))}function br(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let s of n)Fo(s);return e}async function Pe(e,t,n,s=50,o){return br(await ye(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},o))}async function fc(e,t,n,s={},o){let r={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)r.oldest=s.oldest;if(s.cursor!==void 0)r.cursor=s.cursor;return br(await ye(e,"conversations.replies",r,o))}async function Vp(e,t,n){return ye(e,"files.info",{file:t},n)}async function Zp(e,t={},n){let s={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)s.types=t.types;if(t.channel)s.channel=t.channel;if(t.user)s.user=t.user;return ye(e,"files.list",s,n)}async function Qp(e,t,n,s){let o={name:t,schema:n};if(s)o.todo_mode=!0;return await Oe(e,"slackLists.create",o)}async function pc(e,t,n={}){let s={list_id:t};if(n.limit)s.limit=n.limit;if(n.cursor)s.cursor=n.cursor;if(n.includeList)s.include_list=!0;return await Oe(e,"slackLists.items.list",s)}async function eh(e,t,n){return await Oe(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function th(e,t,n,s){let o={list_id:t,access_level:n};if(s.userIds?.length)o.user_ids=s.userIds;if(s.channelIds?.length)o.channel_ids=s.channelIds;return await Oe(e,"slackLists.access.set",o)}async function nh(e,t,n){return await Oe(e,"slackLists.items.update",{list_id:t,cells:n})}async function sh(e,t,n={},s){let o={list_id:t};if(n.limit)o.limit=String(n.limit);if(n.cursor)o.cursor=n.cursor;return kt(e,"lists.records.list",o,s)}async function oh(e,t,n,s,o){return br(await ye(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(s,1))},o))}async function rh(e,t,n){return oh(e,t,100,1,n)}async function hc(e,t,n,s){let r=1,i=[],l={ok:!0,messages:{}};while(!0){let c=await oh(e,t,100,r,s),a=Hs(c,["messages","matches"]),d=Array.isArray(a)?a:[];i.push(...d);let f=Number(Hs(c,["messages","paging","pages"])??1);if(l=c,d.length===0||r>=f||i.length>=n)break;r+=1}let u=l;if(!u.messages)u.messages={};return u.messages.matches=i.slice(0,n),u}async function Nt(e,t,n,s,o,r,i,l){let u=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(s!==void 0)u.thread_ts=s;if(o&&s!==void 0)u.reply_broadcast=!0;return(await ih(e,"chat.postMessage",u,l,r)).ts??""}function i0(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function ih(e,t,n,s,o){if(!s)return Oe(e,t,n,o);try{return await Oe(e,t,{...n,metadata:s},o)}catch(r){if(!i0(r))throw r;return Oe(e,t,n,o)}}async function ah(e,t,n,s,o,r){let i={channel:t,text:n,post_at:s,blocks:[{type:"markdown",text:n}]};if(o!==void 0)i.thread_ts=o;return(await Oe(e,"chat.scheduleMessage",i,r)).scheduled_message_id??""}async function ch(e,t,n){let s={};if(t)s.channel=t;return ye(e,"chat.scheduledMessages.list",s,n)}async function lh(e,t,n,s){await Oe(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},s)}async function Pn(e,t,n,s){return(await ye(e,"chat.getPermalink",{channel:t,message_ts:n},s)).permalink??""}async function Mt(e,t,n,s,o,r,i){return(await ih(e,"chat.update",r?{channel:t,ts:n,text:s}:{channel:t,ts:n,text:s,blocks:[{type:"markdown",text:s}]},i,o)).ts??n}async function uh(e,t,n,s){await Oe(e,"chat.delete",{channel:t,ts:n},s)}async function dh(e,t,n,s,o=200,r){let i={channel:t,ts:n,limit:String(o)};if(s!==void 0)i.cursor=s;return ye(e,"conversations.replies",i,r)}async function gc(e,t,n,s){await Oe(e,"pins.add",{channel:t,timestamp:n},s)}async function Ft(e,t,n,s,o){await Oe(e,"reactions.add",{channel:t,timestamp:n,name:s},o)}async function fh(e,t,n,s){return((await ye(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function Bt(e,t,n,s,o){await Oe(e,"reactions.remove",{channel:t,timestamp:n,name:s},o)}async function ph(e,t,n=!1,s){let o=await Oe(e,"conversations.create",{name:t,is_private:n},s);return{id:o.channel?.id??"",name:o.channel?.name??t}}async function hh(e,t,n,s){let o=await Oe(e,"conversations.rename",{channel:t,name:n},s);return{id:o.channel?.id??t,name:o.channel?.name??n}}async function gh(e,t,n,s){await Oe(e,"conversations.invite",{channel:t,users:n.join(",")},s)}async function zs(e,t){let n=[],s="";while(!0){let o={limit:"200",types:"public_channel,private_channel,im,mpim"};if(s)o.cursor=s;let r=await ye(e,"conversations.list",o,t);if(n.push(...r.channels??[]),s=r.response_metadata?.next_cursor??"",!s)break}return{channels:n}}async function jt(e,t,n){let o=(await Oe(e,"conversations.open",{users:t},n)).channel?.id;if(!o)throw Error(`Failed to open DM with user ${t}`);return o}async function mh(e,t,n){let s="";while(!0){let o={types:"im",limit:"200"};if(s)o.cursor=s;let r=await ye(e,"conversations.list",o,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(s=r.response_metadata?.next_cursor??"",!s)break}return""}async function cc(e,t,n,s){let o=await mh(e,t,n);if(o)return o;let r=s?`${s} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function vn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Kp(e,t){let n=vn(e.name??""),s=vn(e.real_name??e.profile?.real_name??""),o=vn(e.profile?.display_name??"");return n===t||s===t||!!o&&o===t}var yh=200;async function bh(e,t,n){let s=0,o=new Set,r="";while(!0){let a={limit:"200"};if(r)a.cursor=r;let d=await ye(e,"users.list",a,n);for(let f of d.members??[]){if(s++,f.id)o.add(f.id);if(Kp(f,t))return{id:f.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,l=0,u=!1,c="";while(!0){let a={types:"im",limit:"200"};if(c)a.cursor=c;let d=await ye(e,"conversations.list",a,n);for(let f of d.channels??[]){let p=f.user;if(!p||o.has(p))continue;if(i>=yh){u=!0;break}o.add(p),i++;let g;try{g=(await ye(e,"users.info",{user:p},n)).user}catch(h){if(h instanceof Dt)throw h;l++;continue}if(g&&Kp(g,t))return{id:p,dm:String(f.id??""),workspaceCount:s,connectCount:i,skipped:l,capped:u}}if(u)break;if(c=d.response_metadata?.next_cursor??"",!c)break}return{id:"",workspaceCount:s,connectCount:i,skipped:l,capped:u}}function wh(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
435
+ Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${l}`)}return i}function kt(e,t,n={},s){let o=new URLSearchParams({token:e,...n});return a0(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()},s)}function be(e,t,n,s){let o=new URLSearchParams(n).toString();return Zp(e,`${t}?${o}`,{method:"GET"},s)}function Oe(e,t,n,s){return Zp(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function pc(e,t){let n=await be(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Nt(e,t){t=e.startsWith("xoxc-")?t??Zt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let s=await fetch(`${fc()}/auth.test`,{method:"GET",headers:n});if(s.status===429){let i=parseInt(s.headers.get("retry-after")??"60",10);throw new Dt(isNaN(i)?60:i,"auth.test")}let o=s.headers.get("x-oauth-scopes")??"",r=await s.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:o.split(",").map((i)=>i.trim()).filter(Boolean)}}async function Qp(e,t,n){let s=await be(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function ot(e,t,n=20,s,o,r,i){let l={channel:t,limit:String(n)};if(s!==void 0)l.oldest=s;if(o!==void 0)l.cursor=o;if(i)l.inclusive="true";return wr(await be(e,"conversations.history",l,r))}function wr(e){let t=e,n=Array.isArray(t.messages)?t.messages:t.messages&&typeof t.messages==="object"&&Array.isArray(t.messages.matches)?t.messages.matches:[];for(let s of n)Fo(s);return e}async function Pe(e,t,n,s=50,o){return wr(await be(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},o))}async function hc(e,t,n,s={},o){let r={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)r.oldest=s.oldest;if(s.cursor!==void 0)r.cursor=s.cursor;return wr(await be(e,"conversations.replies",r,o))}async function eh(e,t,n){return be(e,"files.info",{file:t},n)}async function th(e,t={},n){let s={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)s.types=t.types;if(t.channel)s.channel=t.channel;if(t.user)s.user=t.user;return be(e,"files.list",s,n)}async function nh(e,t,n,s){let o={name:t,schema:n};if(s)o.todo_mode=!0;return await Oe(e,"slackLists.create",o)}async function gc(e,t,n={}){let s={list_id:t};if(n.limit)s.limit=n.limit;if(n.cursor)s.cursor=n.cursor;if(n.includeList)s.include_list=!0;return await Oe(e,"slackLists.items.list",s)}async function sh(e,t,n){return await Oe(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function oh(e,t,n,s){let o={list_id:t,access_level:n};if(s.userIds?.length)o.user_ids=s.userIds;if(s.channelIds?.length)o.channel_ids=s.channelIds;return await Oe(e,"slackLists.access.set",o)}async function rh(e,t,n){return await Oe(e,"slackLists.items.update",{list_id:t,cells:n})}async function ih(e,t,n={},s){let o={list_id:t};if(n.limit)o.limit=String(n.limit);if(n.cursor)o.cursor=n.cursor;return kt(e,"lists.records.list",o,s)}async function ah(e,t,n,s,o){return wr(await be(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(s,1))},o))}async function ch(e,t,n){return ah(e,t,100,1,n)}async function mc(e,t,n,s){let r=1,i=[],l={ok:!0,messages:{}};while(!0){let c=await ah(e,t,100,r,s),a=Hs(c,["messages","matches"]),d=Array.isArray(a)?a:[];i.push(...d);let f=Number(Hs(c,["messages","paging","pages"])??1);if(l=c,d.length===0||r>=f||i.length>=n)break;r+=1}let u=l;if(!u.messages)u.messages={};return u.messages.matches=i.slice(0,n),u}async function Mt(e,t,n,s,o,r,i,l){let u=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(s!==void 0)u.thread_ts=s;if(o&&s!==void 0)u.reply_broadcast=!0;return(await lh(e,"chat.postMessage",u,l,r)).ts??""}function l0(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function lh(e,t,n,s,o){if(!s)return Oe(e,t,n,o);try{return await Oe(e,t,{...n,metadata:s},o)}catch(r){if(!l0(r))throw r;return Oe(e,t,n,o)}}async function uh(e,t,n,s,o,r){let i={channel:t,text:n,post_at:s,blocks:[{type:"markdown",text:n}]};if(o!==void 0)i.thread_ts=o;return(await Oe(e,"chat.scheduleMessage",i,r)).scheduled_message_id??""}async function dh(e,t,n){let s={};if(t)s.channel=t;return be(e,"chat.scheduledMessages.list",s,n)}async function fh(e,t,n,s){await Oe(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},s)}async function Pn(e,t,n,s){return(await be(e,"chat.getPermalink",{channel:t,message_ts:n},s)).permalink??""}async function Bt(e,t,n,s,o,r,i){return(await lh(e,"chat.update",r?{channel:t,ts:n,text:s}:{channel:t,ts:n,text:s,blocks:[{type:"markdown",text:s}]},i,o)).ts??n}async function ph(e,t,n,s){await Oe(e,"chat.delete",{channel:t,ts:n},s)}async function hh(e,t,n,s,o=200,r){let i={channel:t,ts:n,limit:String(o)};if(s!==void 0)i.cursor=s;return be(e,"conversations.replies",i,r)}async function yc(e,t,n,s){await Oe(e,"pins.add",{channel:t,timestamp:n},s)}async function Ft(e,t,n,s,o){await Oe(e,"reactions.add",{channel:t,timestamp:n,name:s},o)}async function gh(e,t,n,s){return((await be(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((r)=>({name:String(r.name??""),users:Array.isArray(r.users)?r.users.map(String):[]}))}async function jt(e,t,n,s,o){await Oe(e,"reactions.remove",{channel:t,timestamp:n,name:s},o)}async function mh(e,t,n=!1,s){let o=await Oe(e,"conversations.create",{name:t,is_private:n},s);return{id:o.channel?.id??"",name:o.channel?.name??t}}async function yh(e,t,n,s){let o=await Oe(e,"conversations.rename",{channel:t,name:n},s);return{id:o.channel?.id??t,name:o.channel?.name??n}}async function bc(e,t,n,s){await Oe(e,"conversations.invite",{channel:t,users:n.join(",")},s)}async function zs(e,t){let n=[],s="";while(!0){let o={limit:"200",types:"public_channel,private_channel,im,mpim"};if(s)o.cursor=s;let r=await be(e,"conversations.list",o,t);if(n.push(...r.channels??[]),s=r.response_metadata?.next_cursor??"",!s)break}return{channels:n}}async function Wt(e,t,n){let o=(await Oe(e,"conversations.open",{users:t},n)).channel?.id;if(!o)throw Error(`Failed to open DM with user ${t}`);return o}async function bh(e,t,n){let s="";while(!0){let o={types:"im",limit:"200"};if(s)o.cursor=s;let r=await be(e,"conversations.list",o,n);for(let i of r.channels??[])if(i.user===t)return String(i.id??"");if(s=r.response_metadata?.next_cursor??"",!s)break}return""}async function uc(e,t,n,s){let o=await bh(e,t,n);if(o)return o;let r=s?`${s} (${t})`:t;throw Error(`No existing DM with ${r}. Open it once in Slack first.`)}function vn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function zp(e,t){let n=vn(e.name??""),s=vn(e.real_name??e.profile?.real_name??""),o=vn(e.profile?.display_name??"");return n===t||s===t||!!o&&o===t}var wh=200;async function Dh(e,t,n){let s=0,o=new Set,r="";while(!0){let a={limit:"200"};if(r)a.cursor=r;let d=await be(e,"users.list",a,n);for(let f of d.members??[]){if(s++,f.id)o.add(f.id);if(zp(f,t))return{id:f.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(r=d.response_metadata?.next_cursor??"",!r)break}let i=0,l=0,u=!1,c="";while(!0){let a={types:"im",limit:"200"};if(c)a.cursor=c;let d=await be(e,"conversations.list",a,n);for(let f of d.channels??[]){let p=f.user;if(!p||o.has(p))continue;if(i>=wh){u=!0;break}o.add(p),i++;let g;try{g=(await be(e,"users.info",{user:p},n)).user}catch(h){if(h instanceof Dt)throw h;l++;continue}if(g&&zp(g,t))return{id:p,dm:String(f.id??""),workspaceCount:s,connectCount:i,skipped:l,capped:u}}if(u)break;if(c=d.response_metadata?.next_cursor??"",!c)break}return{id:"",workspaceCount:s,connectCount:i,skipped:l,capped:u}}function kh(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
436
436
  `+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
437
- Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,s=[];if(t.capped)s.push(`stopped after ${yh} Slack Connect DM partners, so there may be more`);if(t.skipped)s.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
437
+ Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,s=[];if(t.capped)s.push(`stopped after ${wh} Slack Connect DM partners, so there may be more`);if(t.skipped)s.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
438
438
  `+(s.length?`This search was incomplete: ${s.join("; ")}.
439
439
  `:"")+`Slack Connect people from another workspace are not in users.list, so if they never
440
440
  DMed you they cannot be found by name at all. Look them up and use their ID:
441
- slack user ls --external`)}async function Wt(e,t,n){let s=t.startsWith("@")?t.slice(1):t;if(lc(s))return s;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let o=vn(s),r=await ye(e,"auth.test",{},n);if(o==="you"||o==="me"||vn(r.user??"")===o){if(!r.user_id)throw Error("auth.test did not return user_id");return r.user_id}let i=await bh(e,o,n);if(i.id)return i.id;throw wh(t,i)}function dt(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,o=e.indexOf("?"),r=o>=0?new URLSearchParams(e.slice(o)):void 0,i=r?.get("thread_ts")??void 0,c={channel:r?.get("cid")??void 0??n};if(s)c.ts=s;if(i)c.threadTs=i;return c}function a0(e){return dt(e)?.channel}function qp(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function lc(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function be(e,t,n){let s=a0(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(qp(t))return t;if(lc(t))return cc(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&qp(t.slice(1)))return t.slice(1);let o=t.startsWith("@"),r=t.slice(1),i=vn(r);if(o){if(lc(r))return cc(e,r,n);let c=await ye(e,"auth.test",{},n);if(i==="you"||i==="me"||vn(c.user??"")===i){let f=c.user_id;if(!f)throw Error("auth.test did not return user_id");return await mh(e,f,n)||jt(e,f,n)}let d=await bh(e,i,n);if(!d.id)throw wh(t,d);if(d.dm)return d.dm;return cc(e,d.id,n,t)}let l=r.toLowerCase(),u="";while(!0){let c={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(u)c.cursor=u;let a=await ye(e,"conversations.list",c,n);for(let d of a.channels??[])if(String(d.name??"").toLowerCase()===l)return String(d.id??"");if(u=a.response_metadata?.next_cursor??"",!u)break}throw Error(`channel not found: ${t}`)}async function Ys(e,t,n){try{let s=await ye(e,"users.info",{user:t},n),o=s.user?.profile?.display_name,r=o&&o.length>0?o:s.user?.real_name??s.user?.name??t,i=s.user?.name??t;return[r,i]}catch{return[t,t]}}async function Re(e,t,n){try{let s=await ye(e,"users.info",{user:t},n),o=s.user?.profile?.display_name;if(o&&o.length>0)return o;return s.user?.real_name??s.user?.name??t}catch{return t}}async function Dh(e,t){let n=[],s="";while(!0){let o={limit:"200"};if(s)o.cursor=s;let r=await ye(e,"users.list",o,t);if(n.push(...r.members??[]),s=r.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function kh(e,t,n){let s=[],o="";while(!0){let r={channel:t,limit:"200"};if(o)r.cursor=o;let i=await ye(e,"conversations.members",r,n);if(s.push(...i.members??[]),o=i.response_metadata?.next_cursor??"",!o)break}return s}async function mc(e,t={},n){let s={limit:String(t.limit??50)};if(t.filter)s.filter=t.filter;if(t.cursor)s.cursor=t.cursor;return kt(e,"saved.list",s,n)}var yc=(e)=>({item_type:"message",item_id:e.channel,ts:e.ts});async function xh(e,t,n={},s){let o={...yc(t),todo_state:n.todo===!1?"saved":"to_do"};if(n.due)o.date_due=String(n.due);return kt(e,"saved.add",o,s)}async function bc(e,t,n,s){let o=yc(t);if(n.mark)o.mark=n.mark;if(n.todo!==void 0)o.todo_state=n.todo?"to_do":"saved";if(n.due!==void 0)o.date_due=String(n.due);return kt(e,"saved.update",o,s)}async function Sh(e,t,n){return kt(e,"saved.delete",yc(t),n)}async function Gs(e,t){return kt(e,"drafts.list",{},t)}async function _h(e,t,n,s){let{randomUUID:o}=await import("node:crypto"),r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Ao(n)}]}]);return kt(e,"drafts.create",{client_msg_id:o(),destinations:JSON.stringify([{channel_id:t}]),blocks:r,file_ids:JSON.stringify([]),is_from_composer:"true"},s)}async function Eh(e,t,n,s,o){let r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Ao(s)}]}]),i=(Date.now()/1000).toFixed(6);return kt(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:r,file_ids:JSON.stringify([])},o)}async function $h(e,t,n){return kt(e,"conversations.info",{channel:t},n)}async function os(e,t,n){return ye(e,"users.info",{user:t},n)}async function Ch(e,t,n){try{let s=await ye(e,"users.info",{user:t,include_locale:"true"},n);return typeof s.user?.locale==="string"?s.user.locale:void 0}catch{return}}async function Ln(e,t,n){return ye(e,"conversations.info",{channel:t},n)}async function Ah(e,t,n){let s=(Date.now()/1000).toFixed(6);return kt(e,"drafts.delete",{draft_id:t,client_last_updated_ts:s},n)}async function wc(e,t){let n=await kt(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function Fh(e,t,n,s={},o){let{statSync:r,readFileSync:i}=await import("node:fs"),{basename:l}=await import("node:path"),u=r(n),c=l(n),a=await ye(e,"files.getUploadURLExternal",{filename:c,length:String(u.size)},o),{upload_url:d,file_id:f}=a;if(!d||!f)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let p=i(n),g=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:p});if(!g.ok)throw Error(`Upload PUT failed: ${g.status} ${g.statusText}`);let h={files:[{id:f,title:s.title??c}],channel_id:t};if(s.threadTs)h.thread_ts=s.threadTs;if(s.initialComment)h.initial_comment=s.initialComment;let m=await Oe(e,"files.completeUploadExternal",h,o),y={fileId:f},w=m.files?.[0]?.permalink;if(w)y.permalink=w;return y}function Hs(e,t){let n=e;for(let s of t){if(n===void 0||n===null)return;if(typeof s==="number"){if(!Array.isArray(n))return;n=n[s]??void 0}else{if(typeof n!=="object"||Array.isArray(n))return;n=n[s]}}return n}var Oh=["todo","saved","completed","archived"],Xs=(e)=>typeof e==="string"?e:"",Th=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function Dc(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return(Array.isArray(t.saved_items)?t.saved_items:[]).filter((s)=>!!s&&typeof s==="object"&&!Array.isArray(s)).map((s)=>({channel:Xs(s.item_id),ts:Xs(s.ts),due:Th(s.date_due),completed:Th(s.date_completed),todoState:Xs(s.todo_state),state:Xs(s.state),archived:s.is_archived===!0,itemType:Xs(s.item_type)}))}function Rh(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 Vs(e){return e.completed>0||e.state==="completed"||e.todoState==="completed"}function kc(e,t,n){let s=Vs(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${s} no due date`;let o=!Vs(e)&&e.due<t?" OVERDUE":"";return`${s} due ${n(e.due)}${o}`}function xc(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as y0,readFileSync as b0}from"node:fs";import{homedir as w0}from"node:os";import{join as D0}from"node:path";import{existsSync as c0,mkdirSync as l0,readFileSync as u0,writeFileSync as d0}from"node:fs";import{homedir as f0}from"node:os";import{dirname as p0,join as h0}from"node:path";var g0=3600000,wr={now:()=>Date.now(),path:()=>h0(process.env.HOME||f0(),".config","slack-cli","cache.json")},Dr=!0,rn;function Ih(){return{channels:{},users:{}}}function Sc(){if(rn)return rn;if(rn=Ih(),!Dr)return rn;try{let e=wr.path();if(!c0(e))return rn;let t=JSON.parse(u0(e,"utf8"));for(let n of["channels","users"]){let s=t?.[n];if(!s||typeof s!=="object"||Array.isArray(s))continue;for(let[o,r]of Object.entries(s))if(r&&typeof r==="object"&&typeof r.value==="string"&&typeof r.expires==="number")rn[n][o]={value:r.value,expires:r.expires}}}catch{rn=Ih()}return rn}function m0(e){if(!Dr)return;try{let t=wr.path();l0(p0(t),{recursive:!0}),d0(t,JSON.stringify(e,null,2)+`
442
- `)}catch{}}function vh(e,t){return e?`${e} ${t}`:void 0}function kr(e,t,n){if(!Dr)return;let s=vh(t,n);if(!s)return;let o=Sc()[e][s];if(!o)return;if(o.expires<=wr.now()){delete Sc()[e][s];return}return o.value}function xr(e,t,n,s,o=g0){if(!Dr)return;let r=vh(t,n);if(!r)return;let i=Sc();i[e][r]={value:s,expires:wr.now()+o},m0(i)}var _c={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"}},rs=["done","dropped","doing","pending"],Mh=["alert","needs-discussion","waiting","blocked"];function k0(){return D0(process.env.HOME||w0(),".config","slack-cli","todo.json")}function Sr(e){return e.replace(/^:+|:+$/g,"")}function Zs(e=k0()){let t={marker:_c.marker,progress:{..._c.progress},flags:{..._c.flags}};try{if(!y0(e))return t;let n=JSON.parse(b0(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=Sr(n.marker.trim());for(let s of rs){let o=n.progress?.[s];if(typeof o==="string"&&o.trim())t.progress[s]=Sr(o.trim())}for(let s of Mh){let o=n.flags?.[s];if(typeof o==="string"&&o.trim())t.flags[s]=Sr(o.trim())}}catch{}return t}function Ph(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${Sr(e)}:`}function Bh(e,t,n={}){let s=n.shared===!0,o=(l)=>Ph(l,s),r=(l)=>Ph(l,s,!0),i=[];if(e==="untriaged")i.push(o(t.marker),...rs.map((l)=>r(t.progress[l])));else if(e==="stuck")i.push(o(t.marker),r(t.progress.done),r(t.progress.dropped),`(${Mh.map((l)=>o(t.flags[l])).join(" OR ")})`);else if(e==="open")i.push(o(t.marker),r(t.progress.done),r(t.progress.dropped));else{let l=rs.indexOf(e);i.push(o(t.progress[e]));for(let u of rs.slice(0,l))i.push(r(t.progress[u]))}if(n.in){let l=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${l}`)}if(n.from){let l=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${l}`)}return i.join(" ")}var x0=3,S0={sleep:(e)=>_0()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function _0(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Ve(e,t,n=x0){for(let s=0;;s++)try{return await t()}catch(o){if(!(o instanceof qe))throw o;if(s>=n)throw Error(`Slack rate limit hit on ${e} — gave up after ${n} retries. Try again in a minute.`);console.error(`Warning: Slack rate limit hit on ${e} — backing off for ${o.retryAfter}s`),await S0.sleep(o.retryAfter*1000)}}var Lh=new Map;async function jh(e,t){let n=Lh.get(e);if(n)return n;let s=await Ve("auth.test",()=>Vn(e,t)),o={userId:s.userId,teamId:s.teamId};return Lh.set(e,o),o}async function Wh(e,t){return(await jh(e,t)).userId}async function Ec(e,t){try{return(await jh(e,t)).teamId}catch{return""}}async function $c(e,t,n,s){if(!t.startsWith("#"))return n(e,t,s);let o=await Ec(e,s),r=kr("channels",o,t);if(r)return r;let i=await Ve("resolveChannel",()=>n(e,t,s));return xr("channels",o,t,i),i}async function Jh(e,t,n,s){let o=await Ec(e,s),r=kr("users",o,t);if(r)return r;let i=await Ve("users.info",()=>n(e,t,s));if(i&&i!==t)xr("users",o,t,i);return i}async function Uh(e,t,n,s){let o=await Ec(e,s),r=kr("users",o,`tz:${t}`);if(r)return r==="?"?null:r;let i=null;try{let l=await Ve("users.info",()=>n(e,t,s));if(l?.user?.is_bot===!0||t==="USLACKBOT")return Nh(o,t,null);let u=l?.user?.tz;i=typeof u==="string"&&u?u:null}catch{return null}return Nh(o,t,i)}function Nh(e,t,n){return xr("users",e,`tz:${t}`,n??"?"),n}async function Kh(e,t,n,s,o,r){let i=o.progress[s],l=await Wh(e,r),u=await Ve("reactions.get",()=>od(e,t,n,r)),c=new Set(u.filter((p)=>p.users.includes(l)).map((p)=>p.name)),a=rs.map((p)=>o.progress[p]).filter((p)=>c.has(p));if(a.length===1&&a[0]===i)return{noop:!0,removed:[],leftover:[]};if(!c.has(i))await Ve("reactions.add",()=>To(e,t,n,i,r));let d=[],f=[];for(let p of a){if(p===i)continue;try{await Ve("reactions.remove",()=>Oo(e,t,n,p,r)),d.push(p)}catch{f.push(p)}}return{noop:!1,added:s,removed:d,leftover:f}}async function qh(e,t,n,s,o,r,i){let l=o.flags[s];if(r)await Ve("reactions.remove",()=>Oo(e,t,n,l,i));else await Ve("reactions.add",()=>To(e,t,n,l,i));return l}var Cc=1000;async function Hh(e,t,n,s={}){let o=s.limit??Cc,r=s.cookie,i=await Wh(e,r),l=rs.map((f)=>n.progress[f]),u=[],c=0,a,d=!1;while(c<o){let f=Math.min(200,o-c),p=await Ve("conversations.history",()=>An(e,t,f,void 0,a,r)),g=p.messages??[];c+=g.length;for(let h of g){let m=String(h.ts??"");if(!m)continue;let y=new Set((h.reactions??[]).filter((x)=>(x.users??[]).map(String).includes(i)).map((x)=>String(x.name??""))),w=l.filter((x)=>y.has(x));if(w.length<2)continue;u.push({ts:m,text:String(h.text??"").split(`
443
- `)[0]??"",emoji:w,keep:w[0]})}if(a=p.response_metadata?.next_cursor||void 0,!a||g.length===0)break;if(c>=o){d=!0;break}}if(s.fix)for(let f of u)try{try{await Ve("reactions.add",()=>To(e,t,f.ts,f.keep,r))}catch(p){if(!(p instanceof Error)||!/already_reacted/.test(p.message))throw p}for(let p of f.emoji){if(p===f.keep)continue;await Ve("reactions.remove",()=>Oo(e,t,f.ts,p,r))}f.fixed=!0}catch(p){f.fixed=!1,f.error=p instanceof Error?p.message:String(p)}return{scanned:c,findings:u,truncated:d}}var E0=!0,$0;function Ac(e){if(E0=e,!e)$0=void 0}function Be(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
444
- `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function is(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var as=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},je=(e)=>typeof e==="string"?e:"";function C0(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>je(as(as(n).message).text)).filter(Boolean).join(`
445
- `)}function Fc(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(as).map((n)=>{let s=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),o=as(as((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:s,unfurl:!s&&!!je(n.original_url),author_id:je(n.author_id)||je(as(o.message).user)||null,author_name:je(n.author_name)||null,channel_id:je(n.channel_id)||je(o.channel)||null,ts:je(n.ts)||je(o.ts)||null,title:je(n.title)||null,text:je(n.text)||C0(n)||je(n.pretext)||je(n.fallback),permalink:je(n.from_url)||je(n.title_link)||je(n.original_url)||null}})}function zh(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let s=n.author_name??n.author_id,o=n.shared?`↪ shared message${s?` from @${s}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,r=n.text?n.text.replace(/\n+$/,"").split(`
441
+ slack user ls --external`)}async function Tt(e,t,n){let s=t.startsWith("@")?t.slice(1):t;if(dc(s))return s;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let o=vn(s),r=await be(e,"auth.test",{},n);if(o==="you"||o==="me"||vn(r.user??"")===o){if(!r.user_id)throw Error("auth.test did not return user_id");return r.user_id}let i=await Dh(e,o,n);if(i.id)return i.id;throw kh(t,i)}function dt(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,o=e.indexOf("?"),r=o>=0?new URLSearchParams(e.slice(o)):void 0,i=r?.get("thread_ts")??void 0,c={channel:r?.get("cid")??void 0??n};if(s)c.ts=s;if(i)c.threadTs=i;return c}function u0(e){return dt(e)?.channel}function Yp(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function dc(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function ye(e,t,n){let s=u0(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(Yp(t))return t;if(dc(t))return uc(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Yp(t.slice(1)))return t.slice(1);let o=t.startsWith("@"),r=t.slice(1),i=vn(r);if(o){if(dc(r))return uc(e,r,n);let c=await be(e,"auth.test",{},n);if(i==="you"||i==="me"||vn(c.user??"")===i){let f=c.user_id;if(!f)throw Error("auth.test did not return user_id");return await bh(e,f,n)||Wt(e,f,n)}let d=await Dh(e,i,n);if(!d.id)throw kh(t,d);if(d.dm)return d.dm;return uc(e,d.id,n,t)}let l=r.toLowerCase(),u="";while(!0){let c={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(u)c.cursor=u;let a=await be(e,"conversations.list",c,n);for(let d of a.channels??[])if(String(d.name??"").toLowerCase()===l)return String(d.id??"");if(u=a.response_metadata?.next_cursor??"",!u)break}throw Error(`channel not found: ${t}`)}async function Ys(e,t,n){try{let s=await be(e,"users.info",{user:t},n),o=s.user?.profile?.display_name,r=o&&o.length>0?o:s.user?.real_name??s.user?.name??t,i=s.user?.name??t;return[r,i]}catch{return[t,t]}}async function Re(e,t,n){try{let s=await be(e,"users.info",{user:t},n),o=s.user?.profile?.display_name;if(o&&o.length>0)return o;return s.user?.real_name??s.user?.name??t}catch{return t}}async function xh(e,t){let n=[],s="";while(!0){let o={limit:"200"};if(s)o.cursor=s;let r=await be(e,"users.list",o,t);if(n.push(...r.members??[]),s=r.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function Sh(e,t,n){let s=[],o="";while(!0){let r={channel:t,limit:"200"};if(o)r.cursor=o;let i=await be(e,"conversations.members",r,n);if(s.push(...i.members??[]),o=i.response_metadata?.next_cursor??"",!o)break}return s}async function wc(e,t={},n){let s={limit:String(t.limit??50)};if(t.filter)s.filter=t.filter;if(t.cursor)s.cursor=t.cursor;return kt(e,"saved.list",s,n)}var Dc=(e)=>({item_type:"message",item_id:e.channel,ts:e.ts});async function _h(e,t,n={},s){let o={...Dc(t),todo_state:n.todo===!1?"saved":"to_do"};if(n.due)o.date_due=String(n.due);return kt(e,"saved.add",o,s)}async function kc(e,t,n,s){let o=Dc(t);if(n.mark)o.mark=n.mark;if(n.todo!==void 0)o.todo_state=n.todo?"to_do":"saved";if(n.due!==void 0)o.date_due=String(n.due);return kt(e,"saved.update",o,s)}async function Eh(e,t,n){return kt(e,"saved.delete",Dc(t),n)}async function Gs(e,t){return kt(e,"drafts.list",{},t)}async function $h(e,t,n,s){let{randomUUID:o}=await import("node:crypto"),r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Ao(n)}]}]);return kt(e,"drafts.create",{client_msg_id:o(),destinations:JSON.stringify([{channel_id:t}]),blocks:r,file_ids:JSON.stringify([]),is_from_composer:"true"},s)}async function Ch(e,t,n,s,o){let r=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Ao(s)}]}]),i=(Date.now()/1000).toFixed(6);return kt(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:r,file_ids:JSON.stringify([])},o)}async function Ah(e,t,n){return kt(e,"conversations.info",{channel:t},n)}async function os(e,t,n){return be(e,"users.info",{user:t},n)}async function Fh(e,t,n){try{let s=await be(e,"users.info",{user:t,include_locale:"true"},n);return typeof s.user?.locale==="string"?s.user.locale:void 0}catch{return}}async function Ln(e,t,n){return be(e,"conversations.info",{channel:t},n)}async function Th(e,t,n){let s=(Date.now()/1000).toFixed(6);return kt(e,"drafts.delete",{draft_id:t,client_last_updated_ts:s},n)}async function xc(e,t){let n=await kt(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function Oh(e,t,n,s={},o){let{statSync:r,readFileSync:i}=await import("node:fs"),{basename:l}=await import("node:path"),u=r(n),c=l(n),a=await be(e,"files.getUploadURLExternal",{filename:c,length:String(u.size)},o),{upload_url:d,file_id:f}=a;if(!d||!f)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let p=i(n),g=await fetch(d,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:p});if(!g.ok)throw Error(`Upload PUT failed: ${g.status} ${g.statusText}`);let h={files:[{id:f,title:s.title??c}],channel_id:t};if(s.threadTs)h.thread_ts=s.threadTs;if(s.initialComment)h.initial_comment=s.initialComment;let m=await Oe(e,"files.completeUploadExternal",h,o),y={fileId:f},w=m.files?.[0]?.permalink;if(w)y.permalink=w;return y}function Hs(e,t){let n=e;for(let s of t){if(n===void 0||n===null)return;if(typeof s==="number"){if(!Array.isArray(n))return;n=n[s]??void 0}else{if(typeof n!=="object"||Array.isArray(n))return;n=n[s]}}return n}var Ih=["todo","saved","completed","archived"],Xs=(e)=>typeof e==="string"?e:"",Rh=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function Sc(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e:{};return(Array.isArray(t.saved_items)?t.saved_items:[]).filter((s)=>!!s&&typeof s==="object"&&!Array.isArray(s)).map((s)=>({channel:Xs(s.item_id),ts:Xs(s.ts),due:Rh(s.date_due),completed:Rh(s.date_completed),todoState:Xs(s.todo_state),state:Xs(s.state),archived:s.is_archived===!0,itemType:Xs(s.item_type)}))}function vh(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 Vs(e){return e.completed>0||e.state==="completed"||e.todoState==="completed"}function _c(e,t,n){let s=Vs(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${s} no due date`;let o=!Vs(e)&&e.due<t?" OVERDUE":"";return`${s} due ${n(e.due)}${o}`}function Ec(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as D0,readFileSync as k0}from"node:fs";import{homedir as x0}from"node:os";import{join as S0}from"node:path";import{existsSync as d0,mkdirSync as f0,readFileSync as p0,writeFileSync as h0}from"node:fs";import{homedir as g0}from"node:os";import{dirname as m0,join as y0}from"node:path";var b0=3600000,Dr={now:()=>Date.now(),path:()=>y0(process.env.HOME||g0(),".config","slack-cli","cache.json")},kr=!0,an;function Ph(){return{channels:{},users:{}}}function $c(){if(an)return an;if(an=Ph(),!kr)return an;try{let e=Dr.path();if(!d0(e))return an;let t=JSON.parse(p0(e,"utf8"));for(let n of["channels","users"]){let s=t?.[n];if(!s||typeof s!=="object"||Array.isArray(s))continue;for(let[o,r]of Object.entries(s))if(r&&typeof r==="object"&&typeof r.value==="string"&&typeof r.expires==="number")an[n][o]={value:r.value,expires:r.expires}}}catch{an=Ph()}return an}function w0(e){if(!kr)return;try{let t=Dr.path();f0(m0(t),{recursive:!0}),h0(t,JSON.stringify(e,null,2)+`
442
+ `)}catch{}}function Lh(e,t){return e?`${e} ${t}`:void 0}function xr(e,t,n){if(!kr)return;let s=Lh(t,n);if(!s)return;let o=$c()[e][s];if(!o)return;if(o.expires<=Dr.now()){delete $c()[e][s];return}return o.value}function Sr(e,t,n,s,o=b0){if(!kr)return;let r=Lh(t,n);if(!r)return;let i=$c();i[e][r]={value:s,expires:Dr.now()+o},w0(i)}var Cc={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"}},rs=["done","dropped","doing","pending"],jh=["alert","needs-discussion","waiting","blocked"];function _0(){return S0(process.env.HOME||x0(),".config","slack-cli","todo.json")}function _r(e){return e.replace(/^:+|:+$/g,"")}function Zs(e=_0()){let t={marker:Cc.marker,progress:{...Cc.progress},flags:{...Cc.flags}};try{if(!D0(e))return t;let n=JSON.parse(k0(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=_r(n.marker.trim());for(let s of rs){let o=n.progress?.[s];if(typeof o==="string"&&o.trim())t.progress[s]=_r(o.trim())}for(let s of jh){let o=n.flags?.[s];if(typeof o==="string"&&o.trim())t.flags[s]=_r(o.trim())}}catch{}return t}function Nh(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${_r(e)}:`}function Wh(e,t,n={}){let s=n.shared===!0,o=(l)=>Nh(l,s),r=(l)=>Nh(l,s,!0),i=[];if(e==="untriaged")i.push(o(t.marker),...rs.map((l)=>r(t.progress[l])));else if(e==="stuck")i.push(o(t.marker),r(t.progress.done),r(t.progress.dropped),`(${jh.map((l)=>o(t.flags[l])).join(" OR ")})`);else if(e==="open")i.push(o(t.marker),r(t.progress.done),r(t.progress.dropped));else{let l=rs.indexOf(e);i.push(o(t.progress[e]));for(let u of rs.slice(0,l))i.push(r(t.progress[u]))}if(n.in){let l=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${l}`)}if(n.from){let l=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${l}`)}return i.join(" ")}var E0=3,$0={sleep:(e)=>C0()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function C0(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Ve(e,t,n=E0){for(let s=0;;s++)try{return await t()}catch(o){if(!(o instanceof qe))throw o;if(s>=n)throw Error(`Slack rate limit hit on ${e} — gave up after ${n} retries. Try again in a minute.`);console.error(`Warning: Slack rate limit hit on ${e} — backing off for ${o.retryAfter}s`),await $0.sleep(o.retryAfter*1000)}}var Mh=new Map;async function Jh(e,t){let n=Mh.get(e);if(n)return n;let s=await Ve("auth.test",()=>Vn(e,t)),o={userId:s.userId,teamId:s.teamId};return Mh.set(e,o),o}async function Uh(e,t){return(await Jh(e,t)).userId}async function Ac(e,t){try{return(await Jh(e,t)).teamId}catch{return""}}async function Fc(e,t,n,s){if(!t.startsWith("#"))return n(e,t,s);let o=await Ac(e,s),r=xr("channels",o,t);if(r)return r;let i=await Ve("resolveChannel",()=>n(e,t,s));return Sr("channels",o,t,i),i}async function Kh(e,t,n,s){let o=await Ac(e,s),r=xr("users",o,t);if(r)return r;let i=await Ve("users.info",()=>n(e,t,s));if(i&&i!==t)Sr("users",o,t,i);return i}async function qh(e,t,n,s){let o=await Ac(e,s),r=xr("users",o,`tz:${t}`);if(r)return r==="?"?null:r;let i=null;try{let l=await Ve("users.info",()=>n(e,t,s));if(l?.user?.is_bot===!0||t==="USLACKBOT")return Bh(o,t,null);let u=l?.user?.tz;i=typeof u==="string"&&u?u:null}catch{return null}return Bh(o,t,i)}function Bh(e,t,n){return Sr("users",e,`tz:${t}`,n??"?"),n}async function Hh(e,t,n,s,o,r){let i=o.progress[s],l=await Uh(e,r),u=await Ve("reactions.get",()=>cd(e,t,n,r)),c=new Set(u.filter((p)=>p.users.includes(l)).map((p)=>p.name)),a=rs.map((p)=>o.progress[p]).filter((p)=>c.has(p));if(a.length===1&&a[0]===i)return{noop:!0,removed:[],leftover:[]};if(!c.has(i))await Ve("reactions.add",()=>To(e,t,n,i,r));let d=[],f=[];for(let p of a){if(p===i)continue;try{await Ve("reactions.remove",()=>Oo(e,t,n,p,r)),d.push(p)}catch{f.push(p)}}return{noop:!1,added:s,removed:d,leftover:f}}async function zh(e,t,n,s,o,r,i){let l=o.flags[s];if(r)await Ve("reactions.remove",()=>Oo(e,t,n,l,i));else await Ve("reactions.add",()=>To(e,t,n,l,i));return l}var Tc=1000;async function Yh(e,t,n,s={}){let o=s.limit??Tc,r=s.cookie,i=await Uh(e,r),l=rs.map((f)=>n.progress[f]),u=[],c=0,a,d=!1;while(c<o){let f=Math.min(200,o-c),p=await Ve("conversations.history",()=>An(e,t,f,void 0,a,r)),g=p.messages??[];c+=g.length;for(let h of g){let m=String(h.ts??"");if(!m)continue;let y=new Set((h.reactions??[]).filter((x)=>(x.users??[]).map(String).includes(i)).map((x)=>String(x.name??""))),w=l.filter((x)=>y.has(x));if(w.length<2)continue;u.push({ts:m,text:String(h.text??"").split(`
443
+ `)[0]??"",emoji:w,keep:w[0]})}if(a=p.response_metadata?.next_cursor||void 0,!a||g.length===0)break;if(c>=o){d=!0;break}}if(s.fix)for(let f of u)try{try{await Ve("reactions.add",()=>To(e,t,f.ts,f.keep,r))}catch(p){if(!(p instanceof Error)||!/already_reacted/.test(p.message))throw p}for(let p of f.emoji){if(p===f.keep)continue;await Ve("reactions.remove",()=>Oo(e,t,f.ts,p,r))}f.fixed=!0}catch(p){f.fixed=!1,f.error=p instanceof Error?p.message:String(p)}return{scanned:c,findings:u,truncated:d}}var A0=!0,F0;function Oc(e){if(A0=e,!e)F0=void 0}function je(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
444
+ `;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function is(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var as=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},We=(e)=>typeof e==="string"?e:"";function T0(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>We(as(as(n).message).text)).filter(Boolean).join(`
445
+ `)}function Rc(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(as).map((n)=>{let s=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),o=as(as((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:s,unfurl:!s&&!!We(n.original_url),author_id:We(n.author_id)||We(as(o.message).user)||null,author_name:We(n.author_name)||null,channel_id:We(n.channel_id)||We(o.channel)||null,ts:We(n.ts)||We(o.ts)||null,title:We(n.title)||null,text:We(n.text)||T0(n)||We(n.pretext)||We(n.fallback),permalink:We(n.from_url)||We(n.title_link)||We(n.original_url)||null}})}function Gh(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let s=n.author_name??n.author_id,o=n.shared?`↪ shared message${s?` from @${s}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,r=n.text?n.text.replace(/\n+$/,"").split(`
446
446
  `).map((l)=>`
447
447
  │ ${l}`).join(""):"",i=n.permalink?`
448
448
  ${n.permalink}`:"";return`
449
- ${o}${r}${i}`}).join("")}var Yh=new Set(["send","reply","outbox flush","inbox nudge","ask","poll","vote","edit","tick","delete","react","upload","schedule send","schedule rm","pinlog new","pinlog set","pinlog note","pinlog pin","todo set","todo flag","todos add","todos done","todos complete","todos edit","todos rm","todos remove","todos delete","lists create","lists add","lists set","lists share","drafts new","drafts save","drafts edit","drafts update","drafts delete","drafts rm","channel create","channel new","channel rename","channel mv"]),A0={channels:"channel",ch:"channel"};function Tc(e){let[t="",n=""]=e.map(String),s=A0[t]??t;return Yh.has(s)||Yh.has(`${s} ${n}`)}function Oc(e,t){return String(e[0]??"")==="ask"&&t.ls===!0}function Gh(e,t,n){let s=n.botTokenSource;if(!s||n.globalPaths.includes(s))return null;if(n.slackTokenSet||n.activeTokenIsBot)return null;if(!Tc(e)||Oc(e,t)||t["as-bot"]===!0)return null;let o=s==="shell"?"exported in the environment":`set in ${s}`,r="as-bot"in t;return[`Error: refusing to act as YOU — SLACK_BOT_TOKEN is ${o}, 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(`
450
- `)}function Nn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function an(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function F0(e,t){let n=Nn(t),s=an(e.profile);for(let r of[e.name,e.real_name,s.display_name,s.real_name])if(typeof r==="string"&&r&&Nn(r)===n)return!0;let o=typeof s.email==="string"?s.email.toLowerCase():"";return o!==""&&o===t.toLowerCase()}function T0(e){let t=an(e.profile),n=new Set;for(let s of[t.display_name,e.real_name,e.name,t.real_name])if(typeof s==="string"&&s){let o=Nn(s);if(o.length>=2)n.add(o)}return[...n]}function O0(e,t){let n=Nn(e),s,o=!1;for(let r of t){let i=typeof r.id==="string"?r.id:"";if(!i)continue;for(let l of T0(r)){let u=-1;if(n===l)u=e.length;else for(let c of Vh)if(e.length>c.length&&e.endsWith(c)&&Nn(e.slice(0,e.length-c.length))===l){u=e.length-c.length;break}if(u<0)continue;if(!s||l.length>s.formLen)s={userId:i,matchLen:u,formLen:l.length,display:vc(r)},o=!1;else if(l.length===s.formLen&&s.userId!==i)o=!0}}if(!s)return;return o?"ambiguous":{userId:s.userId,matchLen:s.matchLen,display:s.display}}async function cn(e,t,n,s){let o=`[${Zh}ー]+`,r=`${o}(?:[._-]+${o})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${r})`,"gu"),l=new Set;for(let w of t.matchAll(i))l.add(w[1]);if(l.size===0)return{text:t,resolved:[],unresolved:[]};let u=new Map;for(let w of l)u.set(w,{status:"pending"});let c=(w)=>{for(let x of l){if(u.get(x).status!=="pending")continue;if(Ic(x)){let D=O0(x,w);if(D==="ambiguous")u.set(x,{status:"ambiguous"});else if(D)u.set(x,{status:"resolved",userId:D.userId,matchLen:D.matchLen,display:D.display})}else{let D=w.filter((C)=>F0(C,x)),E=new Set(D.map((C)=>typeof C.id==="string"?C.id:"").filter(Boolean));if(E.size===1){let C=D.find((S)=>typeof S.id==="string");u.set(x,{status:"resolved",userId:C.id,matchLen:x.length,display:vc(C)})}else if(E.size>1)u.set(x,{status:"ambiguous"})}}},a=!1;try{let w=await vo(e,s);c((w.members??[]).map(an)),a=!0}catch{a=!1}let d=[...l].some((w)=>u.get(w).status==="pending"),f=!1,p=!0;if(d&&n){f=!0;try{let w=await Hi(e,n,s),x=[];for(let D of w){let E=an(await zi(e,D,s)),C=an(E.user);if(typeof C.id!=="string")C.id=D;x.push(C)}c(x)}catch{p=!1}}let g=a&&(n?f&&p:!0),h=[],m=[];for(let w of l){let x=u.get(w);if(x.status==="resolved")h.push({surface:`@${w.slice(0,x.matchLen)}`,display:x.display,userId:x.userId});else if(x.status==="ambiguous")m.push({surface:`@${w}`,reason:"ambiguous"});else m.push({surface:`@${w}`,reason:g?"no-match":"unavailable"})}return{text:t.replace(i,(w,x)=>{let D=u.get(x);if(D&&D.status==="resolved")return`<@${D.userId}>${x.slice(D.matchLen)}`;return w}),resolved:h,unresolved:m}}function _r(e){let t=[],n=!1;for(let s of e)if(s.reason==="ambiguous")t.push(`${s.surface} matches multiple people — not tagged, sent as plain text (use <@USERID> to tag)`);else if(s.reason==="unavailable"){if(n)continue;t.push("could not fetch the user list (users:read missing or an API/connection error) — @mentions not tagged, sent as plain text"),n=!0}else t.push(`${s.surface} matched no one — not tagged, sent as plain text`);return t}async function Xh(e,t,n,s={}){let o=s.warn??((i)=>process.stderr.write(`${i}
451
- `)),r=await cn(e,t,n,s.cookie);for(let i of _r(r.unresolved))o(`warn: ${i}`);return r.text}var Vh=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],Zh="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function Ic(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function R0(e){let t=[],n=new RegExp(`([${Zh}]{1,12})(${Vh.join("|")})`,"gu");for(let s of e.matchAll(n))t.push({ref:s[1],honorific:s[2]});for(let s of e.matchAll(/\b(?:dear|hi|hello|hey)\b[ \t]+([A-Z][A-Za-z'’-]{1,20})/gi))t.push({ref:s[1],honorific:""});for(let s of e.matchAll(/(?:^|\n)[ \t]*([A-Z][A-Za-z'’-]{1,20}),/g))t.push({ref:s[1],honorific:""});return t}function I0(e){let t=an(e.profile),n=new Set;for(let s of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof s!=="string"||!s)continue;for(let o of[s,...s.split(/\s+/)]){let r=Nn(o);if(r.length>=2)n.add(r)}}return[...n]}function v0(e,t){let n=Nn(e);if(n.length<2)return;for(let s of t)if(n===s)return s;if(Ic(e)){for(let s of t)if(n.includes(s)||s.includes(n))return s}return}function vc(e){return[an(e.profile).display_name,e.real_name,e.name].filter((s)=>typeof s==="string"&&s!=="")[0]??String(e.id??"?")}async function Qh(e,t,n){let s=R0(t);if(s.length===0)return[];let o=new Set;for(let c of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))o.add(c[1]);let i=((await vo(e,n)).members??[]).map(an).filter((c)=>c.deleted!==!0&&c.is_bot!==!0&&c.id!=="USLACKBOT").map((c)=>({id:typeof c.id==="string"?c.id:"",forms:I0(c),display:vc(c)})).filter((c)=>c.id!==""),l=[],u=new Set;for(let{ref:c,honorific:a}of s)for(let d of i){let f=v0(c,d.forms);if(!f)continue;if(o.has(d.id)||u.has(d.id))break;u.add(d.id),l.push({surface:Ic(c)?`${f}${a}`:c,display:d.display,userId:d.id});break}return l}async function Mn(e,t,n,s){let o=t,r=[],i=o,l=0;while(!0){let u=i.indexOf("<@U",l);if(u===-1)break;let c=i.slice(u+2),a=c.search(/[>|]/),d=a===-1?c:c.slice(0,a);if(d.length>=9)r.push(d);l=u+1}for(let u of r){if(!n.has(u))n.set(u,await Zn(e,u,s));let c=n.get(u)??u;o=o.replaceAll(`<@${u}>`,`@${c}`),o=o.replace(new RegExp(`<@${u}\\|[^>]*>`,"g"),`@${c}`)}return o}function cs(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let o=Number(n);if(!Number.isFinite(o))return s??"date";let r=new Date(o*1000);if(Number.isNaN(r.getTime()))return s??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=i[r.getUTCDay()]??"",c=l[r.getUTCMonth()]??"";return`${u}, ${c} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function eg(e,t=new Date){let n=new Date(e*1000),s=Rc(t),o=Rc(new Date(t.getTime()-86400000)),r=Rc(n);if(r===s)return"Today";if(r===o)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),l=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${l} ${String(n.getDate()).padStart(2,"0")}`}function Rc(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Bn(e){let t=new Date(e*1000),n=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${s}-${o} ${r}:${i}`}var P0=/[A-Za-z0-9_-]{32,}/g;function ls(e){return e.replace(P0,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function Pc(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",s=!!t&&L0(t),o=s?t:n,r=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),l,u;try{let p=new Intl.DateTimeFormat("en-GB",{timeZone:o,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});u=p.format(e),l=Number(p.formatToParts(e).find((g)=>g.type==="hour")?.value??"12")}catch{return null}let c=r>i?l>=r||l<i:l>=r&&l<i,a=s?`${o}, recipient`:`${o}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${u} (${a})`;if(!c)return d;return`${d}
452
- ⚠ QUIET HOURS (${r}:00-${i}:00) — this will buzz a phone.${s?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function L0(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as tg}from"node:fs";import{isatty as ng}from"node:tty";import{format as sg}from"node:util";var N0=new Int32Array(new SharedArrayBuffer(4)),M0=141;function og(e,t){let n=Buffer.from(t,"utf8"),s=0;while(s<n.length)try{s+=tg(e,n,s,n.length-s)}catch(o){let r=o.code;if(r==="EAGAIN"||r==="EWOULDBLOCK"){Atomics.wait(N0,0,0,2);continue}if(r==="EPIPE")process.exit(M0);if(e!==2)try{tg(2,`slack: cannot write output (${r??String(o)}); output is incomplete
453
- `)}catch{}process.exit(1)}}function rg(){if(!ng(1))console.log=(...e)=>og(1,sg(...e)+`
454
- `),console.info=console.log;if(!ng(2))console.error=(...e)=>og(2,sg(...e)+`
455
- `),console.warn=console.error}import{closeSync as ig,mkdirSync as B0,openSync as ag,readFileSync as us,statSync as cg,unlinkSync as Er,writeFileSync as lg}from"node:fs";import{homedir as j0}from"node:os";import{join as ug}from"node:path";var eo="Pinlog · 最終更新";function Lc(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=(o)=>t.find((r)=>r.type===o)?.value??"??",s=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${s}:${n("minute")} JST`}function W0(e){return`_${eo} ${Lc(e)} · 更新はスレッドに_`}var Nc=new RegExp(`(^|\\n+)_?${eo} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function ds(e){return Nc.test(e)}function to(e){return e.replace(Nc,"")}function Mc(e,t){return`${to(e).trimEnd()}
449
+ ${o}${r}${i}`}).join("")}var Xh=new Set(["send","reply","outbox flush","channel invite","channels invite","ch invite","inbox nudge","ask","poll","vote","edit","tick","delete","react","upload","schedule send","schedule rm","pinlog new","pinlog set","pinlog note","pinlog pin","todo set","todo flag","todos add","todos done","todos complete","todos edit","todos rm","todos remove","todos delete","lists create","lists add","lists set","lists share","drafts new","drafts save","drafts edit","drafts update","drafts delete","drafts rm","channel create","channel new","channel rename","channel mv"]),O0={channels:"channel",ch:"channel"};function Ic(e){let[t="",n=""]=e.map(String),s=O0[t]??t;return Xh.has(s)||Xh.has(`${s} ${n}`)}function vc(e,t){return String(e[0]??"")==="ask"&&t.ls===!0}function Vh(e,t,n){let s=n.botTokenSource;if(!s||n.globalPaths.includes(s))return null;if(n.slackTokenSet||n.activeTokenIsBot)return null;if(!Ic(e)||vc(e,t)||t["as-bot"]===!0)return null;let o=s==="shell"?"exported in the environment":`set in ${s}`,r="as-bot"in t;return[`Error: refusing to act as YOU — SLACK_BOT_TOKEN is ${o}, 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(`
450
+ `)}function Nn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function cn(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function R0(e,t){let n=Nn(t),s=cn(e.profile);for(let r of[e.name,e.real_name,s.display_name,s.real_name])if(typeof r==="string"&&r&&Nn(r)===n)return!0;let o=typeof s.email==="string"?s.email.toLowerCase():"";return o!==""&&o===t.toLowerCase()}function I0(e){let t=cn(e.profile),n=new Set;for(let s of[t.display_name,e.real_name,e.name,t.real_name])if(typeof s==="string"&&s){let o=Nn(s);if(o.length>=2)n.add(o)}return[...n]}function v0(e,t){let n=Nn(e),s,o=!1;for(let r of t){let i=typeof r.id==="string"?r.id:"";if(!i)continue;for(let l of I0(r)){let u=-1;if(n===l)u=e.length;else for(let c of Qh)if(e.length>c.length&&e.endsWith(c)&&Nn(e.slice(0,e.length-c.length))===l){u=e.length-c.length;break}if(u<0)continue;if(!s||l.length>s.formLen)s={userId:i,matchLen:u,formLen:l.length,display:Nc(r)},o=!1;else if(l.length===s.formLen&&s.userId!==i)o=!0}}if(!s)return;return o?"ambiguous":{userId:s.userId,matchLen:s.matchLen,display:s.display}}async function ln(e,t,n,s){let o=`[${eg}ー]+`,r=`${o}(?:[._-]+${o})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${r})`,"gu"),l=new Set;for(let w of t.matchAll(i))l.add(w[1]);if(l.size===0)return{text:t,resolved:[],unresolved:[]};let u=new Map;for(let w of l)u.set(w,{status:"pending"});let c=(w)=>{for(let x of l){if(u.get(x).status!=="pending")continue;if(Lc(x)){let D=v0(x,w);if(D==="ambiguous")u.set(x,{status:"ambiguous"});else if(D)u.set(x,{status:"resolved",userId:D.userId,matchLen:D.matchLen,display:D.display})}else{let D=w.filter((C)=>R0(C,x)),E=new Set(D.map((C)=>typeof C.id==="string"?C.id:"").filter(Boolean));if(E.size===1){let C=D.find((S)=>typeof S.id==="string");u.set(x,{status:"resolved",userId:C.id,matchLen:x.length,display:Nc(C)})}else if(E.size>1)u.set(x,{status:"ambiguous"})}}},a=!1;try{let w=await vo(e,s);c((w.members??[]).map(cn)),a=!0}catch{a=!1}let d=[...l].some((w)=>u.get(w).status==="pending"),f=!1,p=!0;if(d&&n){f=!0;try{let w=await Yi(e,n,s),x=[];for(let D of w){let E=cn(await Gi(e,D,s)),C=cn(E.user);if(typeof C.id!=="string")C.id=D;x.push(C)}c(x)}catch{p=!1}}let g=a&&(n?f&&p:!0),h=[],m=[];for(let w of l){let x=u.get(w);if(x.status==="resolved")h.push({surface:`@${w.slice(0,x.matchLen)}`,display:x.display,userId:x.userId});else if(x.status==="ambiguous")m.push({surface:`@${w}`,reason:"ambiguous"});else m.push({surface:`@${w}`,reason:g?"no-match":"unavailable"})}return{text:t.replace(i,(w,x)=>{let D=u.get(x);if(D&&D.status==="resolved")return`<@${D.userId}>${x.slice(D.matchLen)}`;return w}),resolved:h,unresolved:m}}function Er(e){let t=[],n=!1;for(let s of e)if(s.reason==="ambiguous")t.push(`${s.surface} matches multiple people — not tagged, sent as plain text (use <@USERID> to tag)`);else if(s.reason==="unavailable"){if(n)continue;t.push("could not fetch the user list (users:read missing or an API/connection error) — @mentions not tagged, sent as plain text"),n=!0}else t.push(`${s.surface} matched no one — not tagged, sent as plain text`);return t}async function Zh(e,t,n,s={}){let o=s.warn??((i)=>process.stderr.write(`${i}
451
+ `)),r=await ln(e,t,n,s.cookie);for(let i of Er(r.unresolved))o(`warn: ${i}`);return r.text}var Qh=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],eg="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function Lc(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function P0(e){let t=[],n=new RegExp(`([${eg}]{1,12})(${Qh.join("|")})`,"gu");for(let s of e.matchAll(n))t.push({ref:s[1],honorific:s[2]});for(let s of e.matchAll(/\b(?:dear|hi|hello|hey)\b[ \t]+([A-Z][A-Za-z'’-]{1,20})/gi))t.push({ref:s[1],honorific:""});for(let s of e.matchAll(/(?:^|\n)[ \t]*([A-Z][A-Za-z'’-]{1,20}),/g))t.push({ref:s[1],honorific:""});return t}function L0(e){let t=cn(e.profile),n=new Set;for(let s of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof s!=="string"||!s)continue;for(let o of[s,...s.split(/\s+/)]){let r=Nn(o);if(r.length>=2)n.add(r)}}return[...n]}function N0(e,t){let n=Nn(e);if(n.length<2)return;for(let s of t)if(n===s)return s;if(Lc(e)){for(let s of t)if(n.includes(s)||s.includes(n))return s}return}function Nc(e){return[cn(e.profile).display_name,e.real_name,e.name].filter((s)=>typeof s==="string"&&s!=="")[0]??String(e.id??"?")}async function tg(e,t,n){let s=P0(t);if(s.length===0)return[];let o=new Set;for(let c of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))o.add(c[1]);let i=((await vo(e,n)).members??[]).map(cn).filter((c)=>c.deleted!==!0&&c.is_bot!==!0&&c.id!=="USLACKBOT").map((c)=>({id:typeof c.id==="string"?c.id:"",forms:L0(c),display:Nc(c)})).filter((c)=>c.id!==""),l=[],u=new Set;for(let{ref:c,honorific:a}of s)for(let d of i){let f=N0(c,d.forms);if(!f)continue;if(o.has(d.id)||u.has(d.id))break;u.add(d.id),l.push({surface:Lc(c)?`${f}${a}`:c,display:d.display,userId:d.id});break}return l}async function Mn(e,t,n,s){let o=t,r=[],i=o,l=0;while(!0){let u=i.indexOf("<@U",l);if(u===-1)break;let c=i.slice(u+2),a=c.search(/[>|]/),d=a===-1?c:c.slice(0,a);if(d.length>=9)r.push(d);l=u+1}for(let u of r){if(!n.has(u))n.set(u,await Zn(e,u,s));let c=n.get(u)??u;o=o.replaceAll(`<@${u}>`,`@${c}`),o=o.replace(new RegExp(`<@${u}\\|[^>]*>`,"g"),`@${c}`)}return o}function cs(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let o=Number(n);if(!Number.isFinite(o))return s??"date";let r=new Date(o*1000);if(Number.isNaN(r.getTime()))return s??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=i[r.getUTCDay()]??"",c=l[r.getUTCMonth()]??"";return`${u}, ${c} ${String(r.getUTCDate()).padStart(2,"0")}, ${r.getUTCFullYear()}`})}function ng(e,t=new Date){let n=new Date(e*1000),s=Pc(t),o=Pc(new Date(t.getTime()-86400000)),r=Pc(n);if(r===s)return"Today";if(r===o)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),l=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${l} ${String(n.getDate()).padStart(2,"0")}`}function Pc(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Bn(e){let t=new Date(e*1000),n=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${s}-${o} ${r}:${i}`}var M0=/[A-Za-z0-9_-]{32,}/g;function ls(e){return e.replace(M0,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function Mc(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",s=!!t&&B0(t),o=s?t:n,r=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),l,u;try{let p=new Intl.DateTimeFormat("en-GB",{timeZone:o,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});u=p.format(e),l=Number(p.formatToParts(e).find((g)=>g.type==="hour")?.value??"12")}catch{return null}let c=r>i?l>=r||l<i:l>=r&&l<i,a=s?`${o}, recipient`:`${o}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${u} (${a})`;if(!c)return d;return`${d}
452
+ ⚠ QUIET HOURS (${r}:00-${i}:00) — this will buzz a phone.${s?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function B0(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as sg}from"node:fs";import{isatty as og}from"node:tty";import{format as rg}from"node:util";var j0=new Int32Array(new SharedArrayBuffer(4)),W0=141;function ig(e,t){let n=Buffer.from(t,"utf8"),s=0;while(s<n.length)try{s+=sg(e,n,s,n.length-s)}catch(o){let r=o.code;if(r==="EAGAIN"||r==="EWOULDBLOCK"){Atomics.wait(j0,0,0,2);continue}if(r==="EPIPE")process.exit(W0);if(e!==2)try{sg(2,`slack: cannot write output (${r??String(o)}); output is incomplete
453
+ `)}catch{}process.exit(1)}}function ag(){if(!og(1))console.log=(...e)=>ig(1,rg(...e)+`
454
+ `),console.info=console.log;if(!og(2))console.error=(...e)=>ig(2,rg(...e)+`
455
+ `),console.warn=console.error}import{closeSync as cg,mkdirSync as J0,openSync as lg,readFileSync as us,statSync as ug,unlinkSync as $r,writeFileSync as dg}from"node:fs";import{homedir as U0}from"node:os";import{join as fg}from"node:path";var eo="Pinlog · 最終更新";function Bc(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=(o)=>t.find((r)=>r.type===o)?.value??"??",s=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${s}:${n("minute")} JST`}function K0(e){return`_${eo} ${Bc(e)} · 更新はスレッドに_`}var jc=new RegExp(`(^|\\n+)_?${eo} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function ds(e){return jc.test(e)}function to(e){return e.replace(jc,"")}function Wc(e,t){return`${to(e).trimEnd()}
456
456
 
457
- ${W0(t)}`}function Bc(e){let n=e.match(Nc)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class Qs extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function J0(){return ug(process.env.HOME||j0(),".config","slack-cli","locks")}function dg(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 U0(e,t){let n=`${e}.break`,s=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
458
- `,o;try{o=ag(n,"wx"),lg(o,s)}catch(r){if(r.code!=="EEXIST")throw r;try{let i=us(n,"utf8");if((/^pid=\d+/.test(i)?!dg(i):Date.now()-cg(n).mtimeMs>1e4)&&us(n,"utf8")===i)Er(n)}catch{}return}try{if(us(e,"utf8")===t)Er(e)}catch{}finally{ig(o);try{if(us(n,"utf8")===s)Er(n)}catch{}}}function fg(e,t={}){let n=t.dir??J0(),s=t.staleMs??120000;B0(n,{recursive:!0});let o=ug(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()}
459
- `;for(let i=0;i<3;i++)try{let l=ag(o,"wx");lg(l,r),ig(l);let u=!0,c=()=>{if(!u)return;u=!1;try{if(us(o,"utf8")===r)Er(o)}catch{}};return process.once("exit",c),c}catch(l){if(l.code!=="EEXIST")throw l;let u,c;try{u=us(o,"utf8"),c=Date.now()-cg(o).mtimeMs}catch{continue}if(/^pid=\d+/.test(u)?!dg(u):c>s){U0(o,u);continue}throw new Qs(u.trim().replace(/ nonce=\S+/,"")||"another process")}throw new Qs("another process")}function ft(e,t){return`${e}:${t}`}function $r(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}var Og=new Map,Jc=new Map,zc=[Tt(Wc(),".slack-cli",".env.local"),Tt(Wc(),".config/slack-cli",".env")];function Cr(e){if(!Fg(e))return;let t=Hc(e,"utf8");for(let n of t.split(`
460
- `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),i=s.slice(o+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(zc.includes(e))Jc.set(r,[...Jc.get(r)??[],{path:e,val:i}]);if(!(r in process.env))process.env[r]=i,Og.set(r,e)}}function Y0(e){K0(e,{recursive:!0});let t=Tt(e,".gitignore");if(!Fg(t))Tg(t,`*
461
- `)}function G0(){for(let e of zc)Cr(e);Cr(Tt(process.cwd(),".slack-cli",".env.local")),Cr(Tt(process.cwd(),".env.local")),Cr(Tt(process.cwd(),".env"))}function X0(e){return Ag("sha256").update(e).digest("hex")}function T(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Y(e){return Array.isArray(e)?e:[]}function Or(e){return Number(e.ts??0)}async function Rg(e,t,n){let s=t.user;if(typeof s==="string"){if(!n.has(s))n.set(s,await Re(e,s));return n.get(s)??s}return typeof t.username==="string"?t.username:"bot"}function Uc(e){let t=new Date(e*1000),n=t.getUTCFullYear(),s=String(t.getUTCMonth()+1).padStart(2,"0"),o=String(t.getUTCDate()).padStart(2,"0"),r=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),l=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${s}-${o} ${r}:${i}:${l}`}function Rr(e){let[t,n="000000"]=e.split("."),s=Number(t),o=new Date(s*1000),r=o.getUTCFullYear(),i=String(o.getUTCMonth()+1).padStart(2,"0"),l=String(o.getUTCDate()).padStart(2,"0"),u=String(o.getUTCHours()).padStart(2,"0"),c=String(o.getUTCMinutes()).padStart(2,"0"),a=String(o.getUTCSeconds()).padStart(2,"0"),d=n.padEnd(6,"0").slice(0,6);return`${r}-${i}-${l}T${u}:${c}:${a}.${d}`}function Yc(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 jc(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Yc(e):e}async function Nr(e,t,n,s,o){let r=typeof t.ts==="string"?t.ts:`${Or(t)}.000000`,i=Rr(r),l="?";if(typeof t.user==="string"){let x=t.user,D="@"+x;if(!n.has(D)){let E=await Jh(e,x,async(C,S,k)=>(await Ys(C,S,k))[1],o);n.set(D,E)}l=n.get(D)??x}else if(typeof t.username==="string")l=t.username;let u=typeof t.text==="string"?t.text:"",a=cs(await Mn(e,u,n,o)).split(`
457
+ ${K0(t)}`}function Jc(e){let n=e.match(jc)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class Qs extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function q0(){return fg(process.env.HOME||U0(),".config","slack-cli","locks")}function pg(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 H0(e,t){let n=`${e}.break`,s=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
458
+ `,o;try{o=lg(n,"wx"),dg(o,s)}catch(r){if(r.code!=="EEXIST")throw r;try{let i=us(n,"utf8");if((/^pid=\d+/.test(i)?!pg(i):Date.now()-ug(n).mtimeMs>1e4)&&us(n,"utf8")===i)$r(n)}catch{}return}try{if(us(e,"utf8")===t)$r(e)}catch{}finally{cg(o);try{if(us(n,"utf8")===s)$r(n)}catch{}}}function hg(e,t={}){let n=t.dir??q0(),s=t.staleMs??120000;J0(n,{recursive:!0});let o=fg(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()}
459
+ `;for(let i=0;i<3;i++)try{let l=lg(o,"wx");dg(l,r),cg(l);let u=!0,c=()=>{if(!u)return;u=!1;try{if(us(o,"utf8")===r)$r(o)}catch{}};return process.once("exit",c),c}catch(l){if(l.code!=="EEXIST")throw l;let u,c;try{u=us(o,"utf8"),c=Date.now()-ug(o).mtimeMs}catch{continue}if(/^pid=\d+/.test(u)?!pg(u):c>s){H0(o,u);continue}throw new Qs(u.trim().replace(/ nonce=\S+/,"")||"another process")}throw new Qs("another process")}function ft(e,t){return`${e}:${t}`}function Cr(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}var vg=new Map,zc=new Map,Zc=[Ot(Hc(),".slack-cli",".env.local"),Ot(Hc(),".config/slack-cli",".env")];function Ar(e){if(!Rg(e))return;let t=Vc(e,"utf8");for(let n of t.split(`
460
+ `)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let r=s.slice(0,o).trim(),i=s.slice(o+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(Zc.includes(e))zc.set(r,[...zc.get(r)??[],{path:e,val:i}]);if(!(r in process.env))process.env[r]=i,vg.set(r,e)}}function V0(e){z0(e,{recursive:!0});let t=Ot(e,".gitignore");if(!Rg(t))Ig(t,`*
461
+ `)}function Z0(){for(let e of Zc)Ar(e);Ar(Ot(process.cwd(),".slack-cli",".env.local")),Ar(Ot(process.cwd(),".env.local")),Ar(Ot(process.cwd(),".env"))}function Q0(e){return Og("sha256").update(e).digest("hex")}function T(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Y(e){return Array.isArray(e)?e:[]}function Rr(e){return Number(e.ts??0)}async function Pg(e,t,n){let s=t.user;if(typeof s==="string"){if(!n.has(s))n.set(s,await Re(e,s));return n.get(s)??s}return typeof t.username==="string"?t.username:"bot"}function Yc(e){let t=new Date(e*1000),n=t.getUTCFullYear(),s=String(t.getUTCMonth()+1).padStart(2,"0"),o=String(t.getUTCDate()).padStart(2,"0"),r=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),l=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${s}-${o} ${r}:${i}:${l}`}function Ir(e){let[t,n="000000"]=e.split("."),s=Number(t),o=new Date(s*1000),r=o.getUTCFullYear(),i=String(o.getUTCMonth()+1).padStart(2,"0"),l=String(o.getUTCDate()).padStart(2,"0"),u=String(o.getUTCHours()).padStart(2,"0"),c=String(o.getUTCMinutes()).padStart(2,"0"),a=String(o.getUTCSeconds()).padStart(2,"0"),d=n.padEnd(6,"0").slice(0,6);return`${r}-${i}-${l}T${u}:${c}:${a}.${d}`}function Qc(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 Uc(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Qc(e):e}async function Mr(e,t,n,s,o){let r=typeof t.ts==="string"?t.ts:`${Rr(t)}.000000`,i=Ir(r),l="?";if(typeof t.user==="string"){let x=t.user,D="@"+x;if(!n.has(D)){let E=await Kh(e,x,async(C,S,k)=>(await Ys(C,S,k))[1],o);n.set(D,E)}l=n.get(D)??x}else if(typeof t.username==="string")l=t.username;let u=typeof t.text==="string"?t.text:"",a=cs(await Mn(e,u,n,o)).split(`
462
462
  `),d=a[0]+(a.length>1?`
463
463
  `+a.slice(1).map((x)=>` ${x}`).join(`
464
- `):""),f=s?`${s} @${l}`:`@${l}`,p=Y(t.reactions).map(T).map((x)=>{let D=typeof x.name==="string"?x.name:"",E=Number(x.count??Y(x.users).length??0);return D?`:${D}:\xD7${E}`:""}).filter(Boolean).join(" "),g=Y(t.files).map(T).map((x)=>{let D=typeof x.name==="string"?x.name:typeof x.title==="string"?x.title:"(file)",E=typeof x.size==="number"?` (${Mr(x.size)})`:"",C=typeof x.id==="string"?` [${x.id}]`:"";return`
465
- \uD83D\uDCCE ${D}${E}${C}`}).join(""),h=Number(t.reply_count??0),m=h>0?` [+${h} ${h===1?"reply":"replies"}]`:"",y=await Promise.all(Fc(t).map(async(x)=>({...x,text:x.text?cs(await Mn(e,x.text,n,o)):""}))),w=(p?`
466
- ${p}`:"")+g+zh(y,Rr);return`${i} ${f}: ${d}${m}${w}`}function Mr(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function V0(e){return Y(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 Ig(e){let t=V0(e),n=Fc(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:Y(e.reactions).map(T).map((s)=>({name:s.name??null,count:s.count??null,users:Array.isArray(s.users)?s.users:[]}))}:{},...e.reply_count!==void 0?{reply_count:e.reply_count}:{},...e.reply_users_count!==void 0?{reply_users_count:e.reply_users_count}:{},...e.latest_reply!==void 0?{latest_reply:e.latest_reply}:{},...t.length>0?{files:t}:{},...n.length>0?{attachments:n}:{}}}async function Z0(e,t,n,s,o){let r=[];for(let i of n){let l=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let u=await Pe(e,t,i.ts,200,o),c=Y(u.messages).map(T);l=c[c.length-1]??i}if(l.user!==s)r.push(i)}return r}async function pg(e,t,n,s="text",o=!1,r){let i=dt(t),l=await be(e,t,r),u=new Map,a=await(async()=>{if(i?.threadTs){let f=await Pe(e,l,i.threadTs,n,r);return Y(f.messages).map(T)}let d=await ot(e,l,n,void 0,void 0,r);return Y(d.messages).map(T).reverse()})();if(o){let{userId:d}=await dc(e,r);a=await Z0(e,l,a,d,r)}if(s==="jsonl"){for(let d of a)console.log(JSON.stringify(Ig(d)));return}for(let d of a)console.log(await Nr(e,d,u,void 0,r))}function Q0(e){let t=(o)=>o.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"),n=typeof e.user==="string"?e.user:typeof e.bot_id==="string"?e.bot_id:"",s=Array.isArray(e.files)&&e.files.length?` [files: ${e.files.length}]`:"";return`${String(e.ts)} ${n} ${t(typeof e.text==="string"?e.text:"")}${s}`}async function ek(e,t,n,s){let o=[],r;for(let i=0;i<200;i++){let l=T(await fc(e,t,n,r?{cursor:r}:{},s));for(let u of Y(l.messages).map(T))if(!o.some((c)=>c.ts===u.ts))o.push(u);if(r=String(T(l.response_metadata).next_cursor??"")||void 0,!r)return o}throw Error("thread has more than 200 pages: refusing to return it partially")}async function hg(e,t,n,s,o="text",r,i){let l=await be(e,t,r),c=i!==void 0||o==="tsv"?await ek(e,l,jc(n),r):Y((await Pe(e,l,jc(n),s,r)).messages).map(T);if(i!==void 0){let d=Number(jc(i));if(!Number.isFinite(d))throw Error(`--since needs a message ts (1700000000.000100) or ISO stamp (got ${N(i)})`);c=c.filter((f)=>Number(f.ts)>d)}if(o==="tsv"){for(let d of c)console.log(Q0(d));return}if(o==="jsonl"){for(let d of c)console.log(JSON.stringify(Ig(d)));return}let a=new Map;for(let d of c)console.log(await Nr(e,d,a,void 0,r))}async function tk(e){let t=await zs(e),n=Y(t.channels).map(T).filter((o)=>o.is_member===!0).sort((o,r)=>Number(r.updated??0)-Number(o.updated??0)).slice(0,10),s=new Map;for(let o of n){let r=String(o.id??""),i=typeof o.name==="string"?o.name:typeof o.user==="string"?o.user:r,l=await ot(e,r,5),u=Y(l.messages).map(T).filter((c)=>c.subtype===void 0||c.subtype===null).filter((c)=>{let a=typeof c.text==="string"?c.text:"";return a.length>0&&!a.startsWith("<@")}).slice(0,3).reverse();if(u.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let c of u){let a=await Rg(e,c,s),d=(typeof c.text==="string"?c.text:"").split(`
467
- `)[0]??"",f=await Mn(e,d,s);console.log(` ${a}: ${f}`)}}}async function nk(e,t){let n=await rh(e,"to:me"),s=Y(Hs(n,["messages","matches"])).map(T).slice(0,t),o=new Map,r=[];for(let i of s){let l=eg(Or(i)),u=r[r.length-1];if(u?.label===l)u.msgs.push(i);else r.push({label:l,msgs:[i]})}for(let i=0;i<r.length;i++){let{label:l,msgs:u}=r[i];if(i>0)console.log("");console.log(` ${l}`),console.log(" ----------------------------");for(let c of[...u].reverse()){let a=T(c.channel),d=a.is_im===!0,f=typeof a.name==="string"?a.name:"dm",p;if(d&&f.startsWith("U")){let g="@"+f;if(!o.has(g)){let[,h]=await Ys(e,f);o.set(g,h)}p=`@${o.get(g)??f}`}else if(d)p=`@${f}`;else p=`#${f}`;console.log(await Nr(e,c,o,p))}}}async function sk(e,t,n,s,o="text",r){let i=await zs(e,r),l=Y(i.channels).map(T).filter((u)=>s||u.is_member===!0).filter((u)=>{if(!n)return!0;return(typeof u.name==="string"?u.name:"").toLowerCase().includes(n.toLowerCase())}).sort((u,c)=>Number(c.updated??0)-Number(u.updated??0)).slice(0,t);if(o==="jsonl"){for(let u of l)console.log(JSON.stringify(u));return}for(let u of l){let c=String(u.id??""),a=typeof u.name==="string"?u.name:typeof u.user==="string"?u.user:c,d=u.is_im===!0,f=u.is_mpim===!0,p=d||f?"@":"#",g=u.is_member===!0?"":" (not joined)",h=typeof T(u.purpose).value==="string"?String(T(u.purpose).value):"",m=h?` ${h.split(`
468
- `)[0]?.slice(0,60)}`:"";console.log(`${p}${a} ${c}${g}${m}`)}}function ok(e){let t=(o)=>o.startsWith("xoxp-")||o.startsWith("xoxc-"),n=Fi(),s=n.find((o)=>o.profile.token===e);if(!s)return;return n.find((o)=>t(o.profile.token)&&o.profile.teamId===s.profile.teamId)}async function vg(e,t,n,s,o){let r=e,i=o,l;try{l=await hc(r,t,n,i)}catch(a){let d=a instanceof Error?a.message:String(a);if(e.startsWith("xoxb-")&&d.includes("not_allowed_token_type")){let f=ok(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,l=await hc(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.
464
+ `):""),f=s?`${s} @${l}`:`@${l}`,p=Y(t.reactions).map(T).map((x)=>{let D=typeof x.name==="string"?x.name:"",E=Number(x.count??Y(x.users).length??0);return D?`:${D}:\xD7${E}`:""}).filter(Boolean).join(" "),g=Y(t.files).map(T).map((x)=>{let D=typeof x.name==="string"?x.name:typeof x.title==="string"?x.title:"(file)",E=typeof x.size==="number"?` (${Br(x.size)})`:"",C=typeof x.id==="string"?` [${x.id}]`:"";return`
465
+ \uD83D\uDCCE ${D}${E}${C}`}).join(""),h=Number(t.reply_count??0),m=h>0?` [+${h} ${h===1?"reply":"replies"}]`:"",y=await Promise.all(Rc(t).map(async(x)=>({...x,text:x.text?cs(await Mn(e,x.text,n,o)):""}))),w=(p?`
466
+ ${p}`:"")+g+Gh(y,Ir);return`${i} ${f}: ${d}${m}${w}`}function Br(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ek(e){return Y(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 Lg(e){let t=ek(e),n=Rc(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:Y(e.reactions).map(T).map((s)=>({name:s.name??null,count:s.count??null,users:Array.isArray(s.users)?s.users:[]}))}:{},...e.reply_count!==void 0?{reply_count:e.reply_count}:{},...e.reply_users_count!==void 0?{reply_users_count:e.reply_users_count}:{},...e.latest_reply!==void 0?{latest_reply:e.latest_reply}:{},...t.length>0?{files:t}:{},...n.length>0?{attachments:n}:{}}}async function tk(e,t,n,s,o){let r=[];for(let i of n){let l=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let u=await Pe(e,t,i.ts,200,o),c=Y(u.messages).map(T);l=c[c.length-1]??i}if(l.user!==s)r.push(i)}return r}async function gg(e,t,n,s="text",o=!1,r){let i=dt(t),l=await ye(e,t,r),u=new Map,a=await(async()=>{if(i?.threadTs){let f=await Pe(e,l,i.threadTs,n,r);return Y(f.messages).map(T)}let d=await ot(e,l,n,void 0,void 0,r);return Y(d.messages).map(T).reverse()})();if(o){let{userId:d}=await pc(e,r);a=await tk(e,l,a,d,r)}if(s==="jsonl"){for(let d of a)console.log(JSON.stringify(Lg(d)));return}for(let d of a)console.log(await Mr(e,d,u,void 0,r))}function nk(e){let t=(o)=>o.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"),n=typeof e.user==="string"?e.user:typeof e.bot_id==="string"?e.bot_id:"",s=Array.isArray(e.files)&&e.files.length?` [files: ${e.files.length}]`:"";return`${String(e.ts)} ${n} ${t(typeof e.text==="string"?e.text:"")}${s}`}async function sk(e,t,n,s){let o=[],r;for(let i=0;i<200;i++){let l=T(await hc(e,t,n,r?{cursor:r}:{},s));for(let u of Y(l.messages).map(T))if(!o.some((c)=>c.ts===u.ts))o.push(u);if(r=String(T(l.response_metadata).next_cursor??"")||void 0,!r)return o}throw Error("thread has more than 200 pages: refusing to return it partially")}async function mg(e,t,n,s,o="text",r,i){let l=await ye(e,t,r),c=i!==void 0||o==="tsv"?await sk(e,l,Uc(n),r):Y((await Pe(e,l,Uc(n),s,r)).messages).map(T);if(i!==void 0){let d=Number(Uc(i));if(!Number.isFinite(d))throw Error(`--since needs a message ts (1700000000.000100) or ISO stamp (got ${N(i)})`);c=c.filter((f)=>Number(f.ts)>d)}if(o==="tsv"){for(let d of c)console.log(nk(d));return}if(o==="jsonl"){for(let d of c)console.log(JSON.stringify(Lg(d)));return}let a=new Map;for(let d of c)console.log(await Mr(e,d,a,void 0,r))}async function ok(e){let t=await zs(e),n=Y(t.channels).map(T).filter((o)=>o.is_member===!0).sort((o,r)=>Number(r.updated??0)-Number(o.updated??0)).slice(0,10),s=new Map;for(let o of n){let r=String(o.id??""),i=typeof o.name==="string"?o.name:typeof o.user==="string"?o.user:r,l=await ot(e,r,5),u=Y(l.messages).map(T).filter((c)=>c.subtype===void 0||c.subtype===null).filter((c)=>{let a=typeof c.text==="string"?c.text:"";return a.length>0&&!a.startsWith("<@")}).slice(0,3).reverse();if(u.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let c of u){let a=await Pg(e,c,s),d=(typeof c.text==="string"?c.text:"").split(`
467
+ `)[0]??"",f=await Mn(e,d,s);console.log(` ${a}: ${f}`)}}}async function rk(e,t){let n=await ch(e,"to:me"),s=Y(Hs(n,["messages","matches"])).map(T).slice(0,t),o=new Map,r=[];for(let i of s){let l=ng(Rr(i)),u=r[r.length-1];if(u?.label===l)u.msgs.push(i);else r.push({label:l,msgs:[i]})}for(let i=0;i<r.length;i++){let{label:l,msgs:u}=r[i];if(i>0)console.log("");console.log(` ${l}`),console.log(" ----------------------------");for(let c of[...u].reverse()){let a=T(c.channel),d=a.is_im===!0,f=typeof a.name==="string"?a.name:"dm",p;if(d&&f.startsWith("U")){let g="@"+f;if(!o.has(g)){let[,h]=await Ys(e,f);o.set(g,h)}p=`@${o.get(g)??f}`}else if(d)p=`@${f}`;else p=`#${f}`;console.log(await Mr(e,c,o,p))}}}async function ik(e,t,n,s,o="text",r){let i=await zs(e,r),l=Y(i.channels).map(T).filter((u)=>s||u.is_member===!0).filter((u)=>{if(!n)return!0;return(typeof u.name==="string"?u.name:"").toLowerCase().includes(n.toLowerCase())}).sort((u,c)=>Number(c.updated??0)-Number(u.updated??0)).slice(0,t);if(o==="jsonl"){for(let u of l)console.log(JSON.stringify(u));return}for(let u of l){let c=String(u.id??""),a=typeof u.name==="string"?u.name:typeof u.user==="string"?u.user:c,d=u.is_im===!0,f=u.is_mpim===!0,p=d||f?"@":"#",g=u.is_member===!0?"":" (not joined)",h=typeof T(u.purpose).value==="string"?String(T(u.purpose).value):"",m=h?` ${h.split(`
468
+ `)[0]?.slice(0,60)}`:"";console.log(`${p}${a} ${c}${g}${m}`)}}function ak(e){let t=(o)=>o.startsWith("xoxp-")||o.startsWith("xoxc-"),n=Ti(),s=n.find((o)=>o.profile.token===e);if(!s)return;return n.find((o)=>t(o.profile.token)&&o.profile.teamId===s.profile.teamId)}async function Ng(e,t,n,s,o){let r=e,i=o,l;try{l=await mc(r,t,n,i)}catch(a){let d=a instanceof Error?a.message:String(a);if(e.startsWith("xoxb-")&&d.includes("not_allowed_token_type")){let f=ak(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,l=await mc(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.
469
469
  `+` Add a user-token profile: slack auth login (or slack auth login --token <token>)
470
- Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw a}if(s){console.log(JSON.stringify(l,null,2));return}let u=Y(Hs(l,["messages","matches"])).map(T),c=new Map;for(let a of u){let d=T(a.channel),f=d.is_im===!0,p=typeof d.name==="string"?d.name:"dm",g;if(f&&p.startsWith("U")){let h="@"+p;if(!c.has(h)){let[,m]=await Ys(r,p,i);c.set(h,m)}g=`@${c.get(h)??p}`}else if(f)g=`@${p}`;else g=`#${p}`;console.log(await Nr(r,a,c,g,i))}}async function Pg(e,t,n,s){let{ref:o,ts:r}=Ut(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 $c(e,o,be,s),ts:r}}async function rk(e,t){let n=Zs(),s={};if(!t.mine)s.shared=!0;if(t.in)s.in=t.in;if(t.from)s.from=t.from;let o=Bh(t.state,n,s);if(!t.json){let r=await We(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${Wr(r)} \xB7 matching ${i})`),console.error(`(query: ${o})`)}await Ve("search.messages",()=>vg(e,o,t.count,t.json,t.cookie))}async function ik(e,t){let n=Zs(),{channelId:s,ts:o}=await Pg(e,t.target,t.channelId,t.cookie),r=await Kh(e,s,o,t.state,n,t.cookie);if(r.noop){console.log(`= Already ${t.state} (ts: ${o})`);return}let i=r.removed.length?`, removed ${r.removed.map((l)=>`:${l}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${o})${i}`),r.leftover.length)console.error(`\u26A0 ${r.leftover.map((l)=>`:${l}:`).join(" ")} could not be removed \u2014 this message now carries more than one `+"progress reaction. Readers collapse by priority so nothing is lost; repair with: slack todo doctor --in <#chan> --fix")}async function ak(e,t){let n=Zs(),{channelId:s,ts:o}=await Pg(e,t.target,t.channelId,t.cookie),r=await qh(e,s,o,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${r}: (ts: ${o})`)}async function ck(e,t){let n=Zs(),s=t.channelId??await $c(e,t.channel,be,t.cookie),o={limit:t.limit};if(t.fix)o.fix=!0;if(t.cookie)o.cookie=t.cookie;let r=await Hh(e,s,n,o);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 l=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((u)=>`:${u}:`).join(" ")} \u2192 keep :${i.keep}: [${l}] ${N(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 lk(e,t,n,s){let o=Math.floor(Date.now()/1000)-t*86400,r=await zs(e),i=Y(r.channels).map(T).filter((a)=>a.is_member===!0&&a.is_im!==!0&&a.is_mpim!==!0).filter((a)=>{if(!s)return!0;return(typeof a.name==="string"?a.name:"").toLowerCase().includes(s.toLowerCase())}).sort((a,d)=>Number(d.updated??0)-Number(a.updated??0)),l=new Map,u=0,c=0;for(let a of i){let d=String(a.id??""),f=typeof a.name==="string"?a.name:d,p;try{p=await ot(e,d,n)}catch(h){console.error(` SKIP #${f}: ${h.message}`);continue}let g=Y(p.messages).map(T).filter((h)=>(h.subtype===void 0||h.subtype===null)&&Or(h)>=o);if(g.length===0)continue;c+=1,u+=g.length,console.log(`## #${f} (${g.length} msgs)
471
- `);for(let h of[...g].reverse()){let m=await Rg(e,h,l),y=typeof h.text==="string"?h.text:"",x=cs(await Mn(e,y,l)).split(`
472
- `).join(" \u21B5 ");console.log(`[${Bn(Or(h))}] ${m}: ${x}`)}console.log("")}console.error(`Dumped ${u} messages across ${c} channels (cutoff: ${t}d)`)}function uk(e){let t=[];function n(s){if(typeof s==="string"){t.push(s);return}if(Array.isArray(s)){for(let o of s)n(o);return}if(s&&typeof s==="object"){let o=s;if(typeof o.text==="string"){t.push(o.text);return}if(o.type==="link"&&typeof o.url==="string"){t.push(o.url);return}if(Array.isArray(o.elements))n(o.elements);else if(Array.isArray(o.content))n(o.content)}}for(let s of e)n(s);return t.join("").trim()}async function Br(e,t,n){let s=new Map;return async(o)=>{if(!o)return"(unknown)";if(s.has(o))return s.get(o);try{let r=await $h(e,o,t),i=T(r.channel),l;if(i.is_im===!0){let u=typeof i.user==="string"?i.user:"";if(!u||u===n)l="@self";else{let[c]=await Ys(e,u);l=`@${c}`}}else l=`#${typeof i.name==="string"?i.name:o}`;return s.set(o,l),l}catch{return o}}}function Gc(e){let t=T(Y(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function Ir(e){return uk(Y(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function dk(e,t,n=!1){let s=await Gs(e,t),o=Y(s.drafts??s.messages??[]).map(T).filter((c)=>c.is_deleted!==!0),r=n?o:o.filter((c)=>c.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 wc(e,t))}catch{}let l=await Br(e,t,i),u=new Map;for(let c of r){let a=Gc(c),d=Ir(c),f=Number(c.date_created??c.date_create??0),p=f?Uc(f):"?",g=await l(a),h=typeof c.id==="string"?c.id:"",m=c.is_sent===!0?" [SENT]":"",y=cs(await Mn(e,d,u));console.log(`-- ${h} ${g} [${p}]${m}`);for(let w of y.split(`
473
- `))console.log(` ${w}`)}}var vr=50,no=20;async function fk(e,t,n){let s=[],o,r=0;do{let d=T(await mc(e,{filter:n.filter,limit:vr,cursor:o},t));s.push(...Dc(d));let f=T(d.response_metadata).next_cursor;o=typeof f==="string"&&f?f:void 0}while(o&&++r<no);if(o)console.error(`Note: read the first ${s.length} items only (${no} pages); the order covers those.`);let i=Rh(s).slice(0,n.limit);if(i.length===0){(n.json?console.error:console.log)(`No ${n.filter==="todo"?"to-dos":`${n.filter} items`}.`);return}let l="",u="";try{({url:l,userId:u}=await Lt(e,t))}catch{}let c=await Br(e,t,u),a=Date.now()/1000;for(let d of i){let f;if(d.channel&&d.ts)try{let w=T(await Pe(e,d.channel,d.ts,1,t));f=Y(w.messages).map(T).find((x)=>x.ts===d.ts)}catch{}let p=d.channel&&d.ts?l?xc(l,d.channel,d.ts):`${d.channel}:${d.ts}`:"";if(n.json){console.log(JSON.stringify({...d,done:Vs(d),permalink:p,user:f?.user??null,text:f?.text??null}));continue}let g=d.channel?await c(d.channel):`(${d.itemType||"item"})`,h=typeof f?.user==="string"?`@${await Re(e,f.user,t)}: `:"",m=typeof f?.text==="string"?f.text.split(`
474
- `)[0]??"":"(message not readable)",y=m.length>100?`${m.slice(0,100)}\u2026`:m;if(console.log(`${kc(d,a,Bn)} ${N(g)}`),console.log(` ${N(h+y)}`),p)console.log(` ${p}`)}}function pk(e){if(e.kind==="done")return e.undo?["completed","todo","saved","archived"]:["todo","saved","completed","archived"];return["todo","saved","completed","archived"]}async function hk(e,t,n,s,o){let r=0;for(let i of o){let l;do{if(r++>=no)return"unknown";let u=T(await mc(e,{filter:i,limit:vr,cursor:l},t)),c=Dc(u).find((d)=>d.channel===n&&d.ts===s);if(c)return c;let a=T(u.response_metadata).next_cursor;l=typeof a==="string"&&a?a:void 0}while(l)}return}function gk(e,t){let n=(s)=>s===void 0?[]:[` Due: ${s?t(s):"(clear the due date)"}`];switch(e.kind){case"add":return[` Action: add as ${e.saved?"a saved item (no checkbox)":"a to-do"}`,...n(e.due)];case"done":return[` Action: mark ${e.undo?"NOT done (reopen)":"done"}`];case"edit":return[" Action: edit",...e.todo===void 0?[]:[` Kind: ${e.todo?"to-do":"saved item (no checkbox)"}`],...n(e.due)];case"rm":return[" Action: REMOVE from your To-dos (the message itself is untouched)"]}}async function Ar(e,t,n,s,o){let{ref:r,ts:i}=Ut(n);if(!i)console.error("Error: a To-do points at a message \u2014 give its permalink or #chan:<ts> (see `slack todos ls`)."),process.exit(2);if(s.kind==="edit"&&s.due===void 0&&s.todo===void 0)console.error("Error: nothing to edit \u2014 pass --due <time|none>, --todo or --saved."),process.exit(2);let l=await be(e,r,t),u=await hk(e,t,l,i,pk(s));if(u==="unknown"&&s.kind!=="add")console.error(`Error: not found in the first ${no*vr} saved items \u2014 stopped there to stay under Slack's rate limits. Nothing was changed.`),process.exit(1);let c=u==="unknown"?void 0:u;if(s.kind==="add"&&c)console.error(`Error: that message is already in your To-dos (${Vs(c)?"done":c.todoState||"saved"}) \u2014 use \`slack todos edit\` or \`done\`.`),process.exit(1);if(s.kind!=="add"&&!c)console.error("Error: that message is not in your To-dos \u2014 nothing to change. `slack todos ls --filter saved` lists everything saved."),process.exit(1);let a="",d="";try{({url:a,userId:d}=await Lt(e,t))}catch{}let f=await(await Br(e,t,d))(l),p;try{let D=T(await Pe(e,l,i,1,t));p=Y(D.messages).map(T).find((E)=>E.ts===i)}catch{}let g=typeof p?.user==="string"?`@${await Re(e,p.user,t)}: `:"",h=typeof p?.text==="string"?p.text.split(`
475
- `)[0]??"":"(message not readable)",m=ls(h.length>100?`${h.slice(0,100)}\u2026`:h),y=Date.now()/1000,w=ke("todos",JSON.stringify(s),l,i,d);if(o!==w)Se(o,w,["--- To-do ------------------------------------",` For: ${d?`@${await Re(e,d,t)} (your own To-dos)`:"(your own To-dos)"}`,` Where: ${N(f)}`,` Msg: ${N(g+m)}`,...a?[` Link: ${xc(a,l,i)}`]:[],...c?[` Now: ${kc(c,y,Bn)}`]:[],...u==="unknown"?[` Note: not checked beyond the first ${no*vr} saved items \u2014 it may already be saved`]:[],...gk(s,Vg),"----------------------------------------------"]);let x={channel:l,ts:i};switch(s.kind){case"add":await xh(e,x,{todo:!s.saved,...s.due?{due:s.due}:{}},t),console.log(`\u2713 Added to your To-dos${s.due?` (due ${Bn(s.due)})`:""}`);break;case"done":await bc(e,x,{mark:s.undo?"uncompleted":"completed"},t),console.log(s.undo?"\u2713 Reopened":"\u2713 Marked done");break;case"edit":await bc(e,x,{...s.todo===void 0?{}:{todo:s.todo},...s.due===void 0?{}:{due:s.due}},t),console.log("\u2713 Updated");break;case"rm":await Sh(e,x,t),console.log("\u2713 Removed from your To-dos");break}}async function mk(e,t,n){let s=await Gs(e,t),o=Y(s.drafts).map(T).find((g)=>String(g.id)===n);if(!o)console.error(`Draft not found: ${n}`),process.exit(1);let r="";try{({userId:r}=await wc(e,t))}catch{}let i=await Br(e,t,r),l=Gc(o),u=Ir(o),c=Number(o.date_created??0),a=String(o.last_updated_ts??"?"),d=await i(l),p=cs(await Mn(e,u,new Map));console.log(`id: ${o.id}`),console.log(`channel: ${d} (${l})`),console.log(`created: ${c?Uc(c):"?"}`),console.log(`updated: ${Uc(Number(a.split(".")[0]))}`),console.log(`status: ${o.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(p)}function ke(...e){return X0(e.join(`
476
- `)).slice(0,4)}function N(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var yk={"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 pe(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,s,o]=n;switch(o){case"missing_scope":return`Error: token lacks the ${yk[s]??"the required"} scope (needed for ${s}). Add it to your Slack App's User Token Scopes (or Bot Token Scopes if you use a bot token / --as-bot) \u2014 it must be on the token type the CLI actually uses \u2014 then reinstall to the workspace.`;case"invalid_name":return"Error: not a valid emoji shortcode \u2014 use the name without colons (e.g. white_check_mark), and make sure it exists in the workspace.";case"already_reacted":return"Error: you've already added that reaction to the message.";case"no_reaction":return"Error: that reaction isn't on the message \u2014 nothing to remove.";case"message_not_found":return"Error: no message found at that timestamp in the channel \u2014 check the target ts/permalink.";case"channel_not_found":return"Error: channel not found \u2014 check the target.";default:return t}}async function jr(e,t,n){if(!t.startsWith("D"))return null;try{let s=await Jr(e,t,n);if(!s)return null;return await Uh(e,s,os,n)}catch{return null}}function Se(e,t,n,s,o=new Date){for(let i of n)console.log(i);let r=Pc(o,s);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 Ut(e){let t=dt(e);if(t)return t.ts?{ref:t.channel,ts:t.ts}:{ref:t.channel};if(e.startsWith("#")||e.startsWith("@")){let n=e.indexOf(":");if(n>0){let s=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,n),ts:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,n),ts:Yc(s)}}}return{ref:e}}function xt(e,t=!0){let n=dt(e);if(n){if(!t)return{ref:n.channel};let r=n.threadTs??n.ts;return r?{ref:n.channel,threadTs:r}:{ref:n.channel}}let s=e.indexOf(":");if(s>0){let r=e.slice(s+1);if(/^\d{10}\.\d{6}$/.test(r))return{ref:e.slice(0,s),threadTs:r};if(/^\d{4}-\d{2}-\d{2}T/.test(r))return{ref:e.slice(0,s),threadTs:Yc(r)}}let o=ja(e);if(o)return o.thread_ts?{ref:o.channel,threadTs:o.thread_ts}:{ref:o.channel};return{ref:e}}async function gg(e,t,n,s,o,r=!1){let i=ts(n),l,u;if(s)if(dt(s)){let c=await fs(e,s,t);l=c.channel,u=c.root}else{let c=xt(s);if(!c.threadTs&&/^\d{10}\.\d{6}$/.test(s)){if(!i.channel)return{error:`a bare ts needs a channel: set \`channel\` in .slack-term/settings.yml, or pass #chan:${s}`};c={ref:i.channel,threadTs:s}}if(!c.threadTs)return{error:`"${s}" is not a thread \u2014 reply only posts in threads. For a top-level post use \`slack send\`.`};l=await be(e,c.ref,t),u=c.threadTs}if(o){let c=await fs(e,o,t);if(l===void 0)l=c.channel,u=c.root;else if(!r){let a=Ua({channel:l,...u?{threadTs:u}:{}},c);if(a)return{error:a}}}if(!l||!u)return{error:"reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"};if(In(n)&&!on(n).some((c)=>c.channel===l&&(c.thread_ts===void 0||c.thread_ts===u)))return{error:`${l} thread ${u} is not one of ${n.dir}'s subscriptions (restrict_to_subscriptions)`};return{channel:l,threadTs:u}}async function fs(e,t,n){let s=dt(t),o,r,i;if(s)o=s.channel,r=s.ts,i=s.threadTs;else{let u=xt(t);o=u.ref,r=u.threadTs}if(!r)throw Error(`--to needs a message permalink (or #chan:<ts>), got "${t}"`);let l=await be(e,o,n);if(!i)try{let u=T(await Pe(e,l,r,1,n)).messages??[],c=u.map(T).find((a)=>a.ts===r)??T(u[0]);i=typeof c.thread_ts==="string"?c.thread_ts:r}catch(u){if(!/thread_not_found/.test(u instanceof Error?u.message:String(u)))throw u;i=r}return{channel:l,ts:r,root:i}}async function dn(e,t,n,s){let o=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=T(await Ln(e,t,s)),l=T(i.channel);if(l.is_im===!0){let u=typeof l.user==="string"?l.user:"";o=u?`@${await Re(e,u,s)}`:t}else o=typeof l.name==="string"?`#${l.name}`:t}catch{o=t}return o===t?t:`${o} (${t})`}async function We(e,t){try{return await Lt(e,t)}catch{return null}}function Kt(e,t){let n;return async()=>{if(n===void 0)n=await We(e,t);return n}}function Wn(e){if(!gr())return{record:()=>{}};let t=Np();return{metadata:Mp(e,t),record:(n)=>{Bp({...n,kind:e,attribution:t})}}}function bk(e){let t=N(e.text.split(`
470
+ Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw a}if(s){console.log(JSON.stringify(l,null,2));return}let u=Y(Hs(l,["messages","matches"])).map(T),c=new Map;for(let a of u){let d=T(a.channel),f=d.is_im===!0,p=typeof d.name==="string"?d.name:"dm",g;if(f&&p.startsWith("U")){let h="@"+p;if(!c.has(h)){let[,m]=await Ys(r,p,i);c.set(h,m)}g=`@${c.get(h)??p}`}else if(f)g=`@${p}`;else g=`#${p}`;console.log(await Mr(r,a,c,g,i))}}async function Mg(e,t,n,s){let{ref:o,ts:r}=Kt(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 Fc(e,o,ye,s),ts:r}}async function ck(e,t){let n=Zs(),s={};if(!t.mine)s.shared=!0;if(t.in)s.in=t.in;if(t.from)s.from=t.from;let o=Wh(t.state,n,s);if(!t.json){let r=await Me(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${Jr(r)} \xB7 matching ${i})`),console.error(`(query: ${o})`)}await Ve("search.messages",()=>Ng(e,o,t.count,t.json,t.cookie))}async function lk(e,t){let n=Zs(),{channelId:s,ts:o}=await Mg(e,t.target,t.channelId,t.cookie),r=await Hh(e,s,o,t.state,n,t.cookie);if(r.noop){console.log(`= Already ${t.state} (ts: ${o})`);return}let i=r.removed.length?`, removed ${r.removed.map((l)=>`:${l}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${o})${i}`),r.leftover.length)console.error(`\u26A0 ${r.leftover.map((l)=>`:${l}:`).join(" ")} could not be removed \u2014 this message now carries more than one `+"progress reaction. Readers collapse by priority so nothing is lost; repair with: slack todo doctor --in <#chan> --fix")}async function uk(e,t){let n=Zs(),{channelId:s,ts:o}=await Mg(e,t.target,t.channelId,t.cookie),r=await zh(e,s,o,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${r}: (ts: ${o})`)}async function dk(e,t){let n=Zs(),s=t.channelId??await Fc(e,t.channel,ye,t.cookie),o={limit:t.limit};if(t.fix)o.fix=!0;if(t.cookie)o.cookie=t.cookie;let r=await Yh(e,s,n,o);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 l=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((u)=>`:${u}:`).join(" ")} \u2192 keep :${i.keep}: [${l}] ${N(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 fk(e,t,n,s){let o=Math.floor(Date.now()/1000)-t*86400,r=await zs(e),i=Y(r.channels).map(T).filter((a)=>a.is_member===!0&&a.is_im!==!0&&a.is_mpim!==!0).filter((a)=>{if(!s)return!0;return(typeof a.name==="string"?a.name:"").toLowerCase().includes(s.toLowerCase())}).sort((a,d)=>Number(d.updated??0)-Number(a.updated??0)),l=new Map,u=0,c=0;for(let a of i){let d=String(a.id??""),f=typeof a.name==="string"?a.name:d,p;try{p=await ot(e,d,n)}catch(h){console.error(` SKIP #${f}: ${h.message}`);continue}let g=Y(p.messages).map(T).filter((h)=>(h.subtype===void 0||h.subtype===null)&&Rr(h)>=o);if(g.length===0)continue;c+=1,u+=g.length,console.log(`## #${f} (${g.length} msgs)
471
+ `);for(let h of[...g].reverse()){let m=await Pg(e,h,l),y=typeof h.text==="string"?h.text:"",x=cs(await Mn(e,y,l)).split(`
472
+ `).join(" \u21B5 ");console.log(`[${Bn(Rr(h))}] ${m}: ${x}`)}console.log("")}console.error(`Dumped ${u} messages across ${c} channels (cutoff: ${t}d)`)}function pk(e){let t=[];function n(s){if(typeof s==="string"){t.push(s);return}if(Array.isArray(s)){for(let o of s)n(o);return}if(s&&typeof s==="object"){let o=s;if(typeof o.text==="string"){t.push(o.text);return}if(o.type==="link"&&typeof o.url==="string"){t.push(o.url);return}if(Array.isArray(o.elements))n(o.elements);else if(Array.isArray(o.content))n(o.content)}}for(let s of e)n(s);return t.join("").trim()}async function jr(e,t,n){let s=new Map;return async(o)=>{if(!o)return"(unknown)";if(s.has(o))return s.get(o);try{let r=await Ah(e,o,t),i=T(r.channel),l;if(i.is_im===!0){let u=typeof i.user==="string"?i.user:"";if(!u||u===n)l="@self";else{let[c]=await Ys(e,u);l=`@${c}`}}else l=`#${typeof i.name==="string"?i.name:o}`;return s.set(o,l),l}catch{return o}}}function el(e){let t=T(Y(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function vr(e){return pk(Y(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function hk(e,t,n=!1){let s=await Gs(e,t),o=Y(s.drafts??s.messages??[]).map(T).filter((c)=>c.is_deleted!==!0),r=n?o:o.filter((c)=>c.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 xc(e,t))}catch{}let l=await jr(e,t,i),u=new Map;for(let c of r){let a=el(c),d=vr(c),f=Number(c.date_created??c.date_create??0),p=f?Yc(f):"?",g=await l(a),h=typeof c.id==="string"?c.id:"",m=c.is_sent===!0?" [SENT]":"",y=cs(await Mn(e,d,u));console.log(`-- ${h} ${g} [${p}]${m}`);for(let w of y.split(`
473
+ `))console.log(` ${w}`)}}var Pr=50,no=20;async function gk(e,t,n){let s=[],o,r=0;do{let d=T(await wc(e,{filter:n.filter,limit:Pr,cursor:o},t));s.push(...Sc(d));let f=T(d.response_metadata).next_cursor;o=typeof f==="string"&&f?f:void 0}while(o&&++r<no);if(o)console.error(`Note: read the first ${s.length} items only (${no} pages); the order covers those.`);let i=vh(s).slice(0,n.limit);if(i.length===0){(n.json?console.error:console.log)(`No ${n.filter==="todo"?"to-dos":`${n.filter} items`}.`);return}let l="",u="";try{({url:l,userId:u}=await Nt(e,t))}catch{}let c=await jr(e,t,u),a=Date.now()/1000;for(let d of i){let f;if(d.channel&&d.ts)try{let w=T(await Pe(e,d.channel,d.ts,1,t));f=Y(w.messages).map(T).find((x)=>x.ts===d.ts)}catch{}let p=d.channel&&d.ts?l?Ec(l,d.channel,d.ts):`${d.channel}:${d.ts}`:"";if(n.json){console.log(JSON.stringify({...d,done:Vs(d),permalink:p,user:f?.user??null,text:f?.text??null}));continue}let g=d.channel?await c(d.channel):`(${d.itemType||"item"})`,h=typeof f?.user==="string"?`@${await Re(e,f.user,t)}: `:"",m=typeof f?.text==="string"?f.text.split(`
474
+ `)[0]??"":"(message not readable)",y=m.length>100?`${m.slice(0,100)}\u2026`:m;if(console.log(`${_c(d,a,Bn)} ${N(g)}`),console.log(` ${N(h+y)}`),p)console.log(` ${p}`)}}function mk(e){if(e.kind==="done")return e.undo?["completed","todo","saved","archived"]:["todo","saved","completed","archived"];return["todo","saved","completed","archived"]}async function yk(e,t,n,s,o){let r=0;for(let i of o){let l;do{if(r++>=no)return"unknown";let u=T(await wc(e,{filter:i,limit:Pr,cursor:l},t)),c=Sc(u).find((d)=>d.channel===n&&d.ts===s);if(c)return c;let a=T(u.response_metadata).next_cursor;l=typeof a==="string"&&a?a:void 0}while(l)}return}function bk(e,t){let n=(s)=>s===void 0?[]:[` Due: ${s?t(s):"(clear the due date)"}`];switch(e.kind){case"add":return[` Action: add as ${e.saved?"a saved item (no checkbox)":"a to-do"}`,...n(e.due)];case"done":return[` Action: mark ${e.undo?"NOT done (reopen)":"done"}`];case"edit":return[" Action: edit",...e.todo===void 0?[]:[` Kind: ${e.todo?"to-do":"saved item (no checkbox)"}`],...n(e.due)];case"rm":return[" Action: REMOVE from your To-dos (the message itself is untouched)"]}}async function Fr(e,t,n,s,o){let{ref:r,ts:i}=Kt(n);if(!i)console.error("Error: a To-do points at a message \u2014 give its permalink or #chan:<ts> (see `slack todos ls`)."),process.exit(2);if(s.kind==="edit"&&s.due===void 0&&s.todo===void 0)console.error("Error: nothing to edit \u2014 pass --due <time|none>, --todo or --saved."),process.exit(2);let l=await ye(e,r,t),u=await yk(e,t,l,i,mk(s));if(u==="unknown"&&s.kind!=="add")console.error(`Error: not found in the first ${no*Pr} saved items \u2014 stopped there to stay under Slack's rate limits. Nothing was changed.`),process.exit(1);let c=u==="unknown"?void 0:u;if(s.kind==="add"&&c)console.error(`Error: that message is already in your To-dos (${Vs(c)?"done":c.todoState||"saved"}) \u2014 use \`slack todos edit\` or \`done\`.`),process.exit(1);if(s.kind!=="add"&&!c)console.error("Error: that message is not in your To-dos \u2014 nothing to change. `slack todos ls --filter saved` lists everything saved."),process.exit(1);let a="",d="";try{({url:a,userId:d}=await Nt(e,t))}catch{}let f=await(await jr(e,t,d))(l),p;try{let D=T(await Pe(e,l,i,1,t));p=Y(D.messages).map(T).find((E)=>E.ts===i)}catch{}let g=typeof p?.user==="string"?`@${await Re(e,p.user,t)}: `:"",h=typeof p?.text==="string"?p.text.split(`
475
+ `)[0]??"":"(message not readable)",m=ls(h.length>100?`${h.slice(0,100)}\u2026`:h),y=Date.now()/1000,w=we("todos",JSON.stringify(s),l,i,d);if(o!==w)xe(o,w,["--- To-do ------------------------------------",` For: ${d?`@${await Re(e,d,t)} (your own To-dos)`:"(your own To-dos)"}`,` Where: ${N(f)}`,` Msg: ${N(g+m)}`,...a?[` Link: ${Ec(a,l,i)}`]:[],...c?[` Now: ${_c(c,y,Bn)}`]:[],...u==="unknown"?[` Note: not checked beyond the first ${no*Pr} saved items \u2014 it may already be saved`]:[],...bk(s,em),"----------------------------------------------"]);let x={channel:l,ts:i};switch(s.kind){case"add":await _h(e,x,{todo:!s.saved,...s.due?{due:s.due}:{}},t),console.log(`\u2713 Added to your To-dos${s.due?` (due ${Bn(s.due)})`:""}`);break;case"done":await kc(e,x,{mark:s.undo?"uncompleted":"completed"},t),console.log(s.undo?"\u2713 Reopened":"\u2713 Marked done");break;case"edit":await kc(e,x,{...s.todo===void 0?{}:{todo:s.todo},...s.due===void 0?{}:{due:s.due}},t),console.log("\u2713 Updated");break;case"rm":await Eh(e,x,t),console.log("\u2713 Removed from your To-dos");break}}async function wk(e,t,n){let s=await Gs(e,t),o=Y(s.drafts).map(T).find((g)=>String(g.id)===n);if(!o)console.error(`Draft not found: ${n}`),process.exit(1);let r="";try{({userId:r}=await xc(e,t))}catch{}let i=await jr(e,t,r),l=el(o),u=vr(o),c=Number(o.date_created??0),a=String(o.last_updated_ts??"?"),d=await i(l),p=cs(await Mn(e,u,new Map));console.log(`id: ${o.id}`),console.log(`channel: ${d} (${l})`),console.log(`created: ${c?Yc(c):"?"}`),console.log(`updated: ${Yc(Number(a.split(".")[0]))}`),console.log(`status: ${o.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(p)}function we(...e){return Q0(e.join(`
476
+ `)).slice(0,4)}function N(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var Dk={"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 pe(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,s,o]=n;switch(o){case"missing_scope":return`Error: token lacks the ${Dk[s]??"the required"} scope (needed for ${s}). Add it to your Slack App's User Token Scopes (or Bot Token Scopes if you use a bot token / --as-bot) \u2014 it must be on the token type the CLI actually uses \u2014 then reinstall to the workspace.`;case"invalid_name":return"Error: not a valid emoji shortcode \u2014 use the name without colons (e.g. white_check_mark), and make sure it exists in the workspace.";case"already_reacted":return"Error: you've already added that reaction to the message.";case"no_reaction":return"Error: that reaction isn't on the message \u2014 nothing to remove.";case"message_not_found":return"Error: no message found at that timestamp in the channel \u2014 check the target ts/permalink.";case"channel_not_found":return"Error: channel not found \u2014 check the target.";default:return t}}async function Wr(e,t,n){if(!t.startsWith("D"))return null;try{let s=await Ur(e,t,n);if(!s)return null;return await qh(e,s,os,n)}catch{return null}}function xe(e,t,n,s,o=new Date){for(let i of n)console.log(i);let r=Mc(o,s);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 Kt(e){let t=dt(e);if(t)return t.ts?{ref:t.channel,ts:t.ts}:{ref:t.channel};if(e.startsWith("#")||e.startsWith("@")){let n=e.indexOf(":");if(n>0){let s=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,n),ts:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,n),ts:Qc(s)}}}return{ref:e}}function xt(e,t=!0){let n=dt(e);if(n){if(!t)return{ref:n.channel};let r=n.threadTs??n.ts;return r?{ref:n.channel,threadTs:r}:{ref:n.channel}}let s=e.indexOf(":");if(s>0){let r=e.slice(s+1);if(/^\d{10}\.\d{6}$/.test(r))return{ref:e.slice(0,s),threadTs:r};if(/^\d{4}-\d{2}-\d{2}T/.test(r))return{ref:e.slice(0,s),threadTs:Qc(r)}}let o=Ja(e);if(o)return o.thread_ts?{ref:o.channel,threadTs:o.thread_ts}:{ref:o.channel};return{ref:e}}async function yg(e,t,n,s,o,r=!1){let i=ts(n),l,u;if(s)if(dt(s)){let c=await fs(e,s,t);l=c.channel,u=c.root}else{let c=xt(s);if(!c.threadTs&&/^\d{10}\.\d{6}$/.test(s)){if(!i.channel)return{error:`a bare ts needs a channel: set \`channel\` in .slack-term/settings.yml, or pass #chan:${s}`};c={ref:i.channel,threadTs:s}}if(!c.threadTs)return{error:`"${s}" is not a thread \u2014 reply only posts in threads. For a top-level post use \`slack send\`.`};l=await ye(e,c.ref,t),u=c.threadTs}if(o){let c=await fs(e,o,t);if(l===void 0)l=c.channel,u=c.root;else if(!r){let a=qa({channel:l,...u?{threadTs:u}:{}},c);if(a)return{error:a}}}if(!l||!u)return{error:"reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"};if(In(n)&&!rn(n).some((c)=>c.channel===l&&(c.thread_ts===void 0||c.thread_ts===u)))return{error:`${l} thread ${u} is not one of ${n.dir}'s subscriptions (restrict_to_subscriptions)`};return{channel:l,threadTs:u}}async function fs(e,t,n){let s=dt(t),o,r,i;if(s)o=s.channel,r=s.ts,i=s.threadTs;else{let u=xt(t);o=u.ref,r=u.threadTs}if(!r)throw Error(`--to needs a message permalink (or #chan:<ts>), got "${t}"`);let l=await ye(e,o,n);if(!i)try{let u=T(await Pe(e,l,r,1,n)).messages??[],c=u.map(T).find((a)=>a.ts===r)??T(u[0]);i=typeof c.thread_ts==="string"?c.thread_ts:r}catch(u){if(!/thread_not_found/.test(u instanceof Error?u.message:String(u)))throw u;i=r}return{channel:l,ts:r,root:i}}async function Ut(e,t,n,s){let o=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=T(await Ln(e,t,s)),l=T(i.channel);if(l.is_im===!0){let u=typeof l.user==="string"?l.user:"";o=u?`@${await Re(e,u,s)}`:t}else o=typeof l.name==="string"?`#${l.name}`:t}catch{o=t}return o===t?t:`${o} (${t})`}async function Me(e,t){try{return await Nt(e,t)}catch{return null}}function qt(e,t){let n;return async()=>{if(n===void 0)n=await Me(e,t);return n}}function Wn(e){if(!mr())return{record:()=>{}};let t=jp();return{metadata:Wp(e,t),record:(n)=>{Jp({...n,kind:e,attribution:t})}}}function kk(e){let t=N(e.text.split(`
477
477
  `)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,s=[e.cli??"?",e.session_id?`session=${e.session_id}`:"",e.agent_pid?`pid=${e.agent_pid}`:`pid=${e.pid}`,e.git_branch?`branch=${e.git_branch}`:"",`cwd=${e.cwd}`].filter(Boolean).join(" ");return`${Bn(e.sent_at/1000)} ${e.kind.padEnd(4)} ${N(e.target??e.channel)} ${n}
478
478
  ${t}
479
- ${N(s)}`}function Wr(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let s=N(e.user||e.userId||"?"),o=e.userId?` (${e.userId})`:"",r=e.team?` \u2014 ${N(e.team)}`:"";return`@${s}${o}${r}${n}`}function Ee(e,t={}){return` ${"From:".padEnd(t.pad??6)}${Wr(e,t.asBot)}`}async function Kc(e,t,n=60,s){let o=typeof t.user==="string"?await Re(e,t.user,s):typeof t.username==="string"?t.username:"?",r=ls((typeof t.text==="string"?t.text:"").split(`
480
- `)[0]??""),i=r.length>n?`${r.slice(0,n)}\u2026`:r,l=typeof t.ts==="string"?t.ts:"";return`${l?Rr(l).slice(0,16).replace("T"," "):""} @${o}${i?`: ${i}`:""}`}async function wk(e,t,n,s){let o=n.find((r)=>String(r.ts)===t)??n[0];if(!o)return t;return Kc(e,o,40,s)}function mg(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Dk(e,t){let n=mg(e),s=mg(t);if(!n||!s)return 0;if(n===s)return 1;let o=(c)=>{let a=new Map;for(let d=0;d<c.length-1;d++){let f=c.slice(d,d+2);a.set(f,(a.get(f)??0)+1)}return a},r=o(n),i=o(s);if(r.size===0||i.size===0)return 0;let l=0;for(let[c,a]of r){let d=i.get(c);if(d)l+=Math.min(a,d)}let u=yg(r)+yg(i);return u===0?0:2*l/u}function yg(e){let t=0;for(let n of e.values())t+=n;return t}async function bg(e,t,n,s){let o=Ne();if(!o)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
481
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(s)return{botToken:o};let{ref:r}=Ut(e);if(!r.startsWith("@"))return{botToken:o};try{let i=await Wt(t,r,n);return{botToken:o,channelId:await jt(o,i)}}catch(i){console.error(`Error: could not resolve ${N(r)} to the bot's DM.
479
+ ${N(s)}`}function Jr(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let s=N(e.user||e.userId||"?"),o=e.userId?` (${e.userId})`:"",r=e.team?` \u2014 ${N(e.team)}`:"";return`@${s}${o}${r}${n}`}function _e(e,t={}){return` ${"From:".padEnd(t.pad??6)}${Jr(e,t.asBot)}`}async function Gc(e,t,n=60,s){let o=typeof t.user==="string"?await Re(e,t.user,s):typeof t.username==="string"?t.username:"?",r=ls((typeof t.text==="string"?t.text:"").split(`
480
+ `)[0]??""),i=r.length>n?`${r.slice(0,n)}\u2026`:r,l=typeof t.ts==="string"?t.ts:"";return`${l?Ir(l).slice(0,16).replace("T"," "):""} @${o}${i?`: ${i}`:""}`}async function xk(e,t,n,s){let o=n.find((r)=>String(r.ts)===t)??n[0];if(!o)return t;return Gc(e,o,40,s)}function bg(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function Sk(e,t){let n=bg(e),s=bg(t);if(!n||!s)return 0;if(n===s)return 1;let o=(c)=>{let a=new Map;for(let d=0;d<c.length-1;d++){let f=c.slice(d,d+2);a.set(f,(a.get(f)??0)+1)}return a},r=o(n),i=o(s);if(r.size===0||i.size===0)return 0;let l=0;for(let[c,a]of r){let d=i.get(c);if(d)l+=Math.min(a,d)}let u=wg(r)+wg(i);return u===0?0:2*l/u}function wg(e){let t=0;for(let n of e.values())t+=n;return t}async function Dg(e,t,n,s){let o=Le();if(!o)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
481
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(s)return{botToken:o};let{ref:r}=Kt(e);if(!r.startsWith("@"))return{botToken:o};try{let i=await Tt(t,r,n);return{botToken:o,channelId:await Wt(o,i)}}catch(i){console.error(`Error: could not resolve ${N(r)} to the bot's DM.
482
482
  ${i instanceof Error?i.message:String(i)}
483
- `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function kk(e,t){let n=Kt(e,t.cookie),{ref:s,ts:o}=Ut(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 r;if(t.channelId)r=t.channelId;else r=await be(e,s,t.cookie);let i=await Pe(e,r,o,1,t.cookie),u=Y(i.messages).map(T).find((S)=>String(S.ts)===o);if(!u)console.error(`Message not found at ts=${o} in channel ${r}`),process.exit(1);let c=typeof u.text==="string"?u.text:"",a=t.newText;if(t.tick){let S=Jf(c,t.tick.n);if(S.kind==="already")console.log(`already ticked (${S.n}.)`),process.exit(0);if(S.kind==="none")console.error("Error: the message has no \u2B1C <n>. item"),process.exit(2);if(S.kind==="missing")console.error(`Error: the message has no \u2B1C ${S.n}. item`),process.exit(2);if(S.kind==="ambiguous")console.error(`Error: several open items (${S.open.join(", ")}): name one, e.g. slack tick <target> ${S.open[0]}`),process.exit(2);a=S.text}else a=Uf(c,a,t.lanePrefix);let d=t.mentionCookie??t.cookie,f=t.mentions&&!t.tick?await Xh(t.mentionToken??e,a,r,d?{cookie:d}:{}):a;Ke(f,t.allowUrlAdjacent);let p=$t(c).kind,g=$t(f).kind,h=Ks(c).kind!=="other",m=h?Ks(f).kind==="other":p!=="other"&&(g==="other"||p!=="open"&&g==="open");if(m&&!t.force)console.error(`Error: this message is ${h?"a `slack poll`":`a \`slack ask\` question (${p==="open"?"open":p==="resolved"?"answered":"void"})`}, and ${h||g==="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"}.
483
+ `+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function _k(e,t){let n=qt(e,t.cookie),{ref:s,ts:o}=Kt(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 r;if(t.channelId)r=t.channelId;else r=await ye(e,s,t.cookie);let i=await Pe(e,r,o,1,t.cookie),u=Y(i.messages).map(T).find((S)=>String(S.ts)===o);if(!u)console.error(`Message not found at ts=${o} in channel ${r}`),process.exit(1);let c=typeof u.text==="string"?u.text:"",a=t.newText;if(t.tick){let S=qf(c,t.tick.n);if(S.kind==="already")console.log(`already ticked (${S.n}.)`),process.exit(0);if(S.kind==="none")console.error("Error: the message has no \u2B1C <n>. item"),process.exit(2);if(S.kind==="missing")console.error(`Error: the message has no \u2B1C ${S.n}. item`),process.exit(2);if(S.kind==="ambiguous")console.error(`Error: several open items (${S.open.join(", ")}): name one, e.g. slack tick <target> ${S.open[0]}`),process.exit(2);a=S.text}else a=Hf(c,a,t.lanePrefix);let d=t.mentionCookie??t.cookie,f=t.mentions&&!t.tick?await Zh(t.mentionToken??e,a,r,d?{cookie:d}:{}):a;Ke(f,t.allowUrlAdjacent);let p=$t(c).kind,g=$t(f).kind,h=Ks(c).kind!=="other",m=h?Ks(f).kind==="other":p!=="other"&&(g==="other"||p!=="open"&&g==="open");if(m&&!t.force)console.error(`Error: this message is ${h?"a `slack poll`":`a \`slack ask\` question (${p==="open"?"open":p==="resolved"?"answered":"void"})`}, and ${h||g==="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"}.
484
484
  `+(h?" Edit it anyway with --force.":` To retire it: slack ask --void='${t.target}' --reason '\u2026'
485
- Edit it anyway with --force.`)),process.exit(1);let y=m,w=await n(),x=y?ke("force-edit-ask-poll",c,f,w?.userId??""):ke(c,f,w?.userId??"");if(t.code!==x)Se(t.code,x,[...y?[`\u26A0 --force: rewriting a \`slack ${h?"poll":"ask"}\` message by hand \u2014 collect may no longer read it back`]:[],"--- Editing as -------------------------------",Ee(w,{asBot:t.asBot}),"--- Original message -------------------------",...c.split(`
485
+ Edit it anyway with --force.`)),process.exit(1);let y=m,w=await n(),x=y?we("force-edit-ask-poll",c,f,w?.userId??""):we(c,f,w?.userId??"");if(t.code!==x)xe(t.code,x,[...y?[`\u26A0 --force: rewriting a \`slack ${h?"poll":"ask"}\` message by hand \u2014 collect may no longer read it back`]:[],"--- Editing as -------------------------------",_e(w,{asBot:t.asBot}),"--- Original message -------------------------",...c.split(`
486
486
  `).map((S)=>` ${S}`),"--- Replacing with ---------------------------",...f.split(`
487
- `).map((S)=>` ${S}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let D=Wn("edit"),E=p!=="other"||g!=="other"||h||Ks(f).kind!=="other",C=await Mt(e,r,o,f,t.cookie,E?!0:void 0,D.metadata);console.log(`\u2713 Edited (ts: ${C})`),D.record({team:w?.team,channel:r,target:t.target,ts:o,text:f,asBot:t.asBot})}async function xk(e,t){let n=Kt(e,t.cookie),{ref:s,ts:o}=Ut(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 r;if(t.channelId)r=t.channelId;else r=await be(e,s,t.cookie);let i=await Pe(e,r,o,1,t.cookie),u=Y(i.messages).map(T).find((f)=>String(f.ts)===o);if(!u)console.error(`Message not found at ts=${o} in channel ${r}`),process.exit(1);let c=typeof u.text==="string"?u.text:"",a=await n(),d=ke(r,o,c,a?.userId??"");if(t.code!==d){let f=await dn(e,r,s,t.cookie);Se(t.code,d,["--- Deleting message -------------------------",Ee(a,{asBot:t.asBot}),` \u2192 ${f} at ${Rr(o)}`,...c.split(`
488
- `).map((p)=>` ${p}`),"---------------------------------------------"])}await uh(e,r,o,t.cookie),console.log(`\u2713 Deleted (ts: ${o})`)}function un(e){return`'${e.replace(/'/g,"'\\''")}'`}async function Xc(e,t,n){let s=$r(t);if(s)return{...s,ref:s.channel};let{ref:o,ts:r}=Ut(t);if(!r)console.error(`Error: ${N(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 ${un(t)}`),process.exit(2);return{channel:await be(e,o,n),ts:r,ref:o}}async function Sk(e,t,n,s){let o=T(await Pe(e,t,n,1,s)),r=Y(o.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 Fr(e,t){if(t!==void 0)try{return Hc(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:Be(e)}var wg=40000;function Pr(e,t){if(t.length>wg)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${wg}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function Lr(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof Dt)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function Lg(e,t){let n=Pc(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function _k(e,t){let{ref:n,ts:s}=Ut(t.target);if(s||$r(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 ${un(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(Ke(t.state,t.allowUrlAdjacent),t.log!==void 0)Ke(t.log,t.allowUrlAdjacent),Pr("reason",t.log);let o=`${t.workspace?` -w ${un(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,r=Kt(e,t.cookie),i=await be(e,n,t.cookie),l=await r(),u=ke("pinlog-create",i,t.state,t.log??"",l?.userId??""),c=new Date,a=Mc(t.state,c);if(Pr("HEAD (state + footer)",a),t.code!==u){let h=await dn(e,i,n,t.cookie),m=(await Ng(e,i,200,t.cookie)).found;Se(t.code,u,["--- New pinlog -------------------------------",Ee(l,{asBot:t.asBot}),` \u2192 ${h} \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((y)=>` ${ft(i,String(y.ts))} ${Mg(String(y.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...a.split(`
487
+ `).map((S)=>` ${S}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let D=Wn("edit"),E=p!=="other"||g!=="other"||h||Ks(f).kind!=="other",C=await Bt(e,r,o,f,t.cookie,E?!0:void 0,D.metadata);console.log(`\u2713 Edited (ts: ${C})`),D.record({team:w?.team,channel:r,target:t.target,ts:o,text:f,asBot:t.asBot})}async function Ek(e,t){let n=qt(e,t.cookie),{ref:s,ts:o}=Kt(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 r;if(t.channelId)r=t.channelId;else r=await ye(e,s,t.cookie);let i=await Pe(e,r,o,1,t.cookie),u=Y(i.messages).map(T).find((f)=>String(f.ts)===o);if(!u)console.error(`Message not found at ts=${o} in channel ${r}`),process.exit(1);let c=typeof u.text==="string"?u.text:"",a=await n(),d=we(r,o,c,a?.userId??"");if(t.code!==d){let f=await Ut(e,r,s,t.cookie);xe(t.code,d,["--- Deleting message -------------------------",_e(a,{asBot:t.asBot}),` \u2192 ${f} at ${Ir(o)}`,...c.split(`
488
+ `).map((p)=>` ${p}`),"---------------------------------------------"])}await ph(e,r,o,t.cookie),console.log(`\u2713 Deleted (ts: ${o})`)}function dn(e){return`'${e.replace(/'/g,"'\\''")}'`}async function tl(e,t,n){let s=Cr(t);if(s)return{...s,ref:s.channel};let{ref:o,ts:r}=Kt(t);if(!r)console.error(`Error: ${N(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 ${dn(t)}`),process.exit(2);return{channel:await ye(e,o,n),ts:r,ref:o}}async function $k(e,t,n,s){let o=T(await Pe(e,t,n,1,s)),r=Y(o.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 Tr(e,t){if(t!==void 0)try{return Vc(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:je(e)}var kg=40000;function Lr(e,t){if(t.length>kg)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${kg}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function Nr(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof Dt)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function Bg(e,t){let n=Mc(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function Ck(e,t){let{ref:n,ts:s}=Kt(t.target);if(s||Cr(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 ${dn(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(Ke(t.state,t.allowUrlAdjacent),t.log!==void 0)Ke(t.log,t.allowUrlAdjacent),Lr("reason",t.log);let o=`${t.workspace?` -w ${dn(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,r=qt(e,t.cookie),i=await ye(e,n,t.cookie),l=await r(),u=we("pinlog-create",i,t.state,t.log??"",l?.userId??""),c=new Date,a=Wc(t.state,c);if(Lr("HEAD (state + footer)",a),t.code!==u){let h=await Ut(e,i,n,t.cookie),m=(await jg(e,i,200,t.cookie)).found;xe(t.code,u,["--- New pinlog -------------------------------",_e(l,{asBot:t.asBot}),` \u2192 ${h} \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((y)=>` ${ft(i,String(y.ts))} ${Wg(String(y.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...a.split(`
489
489
  `).map((y)=>` ${N(y)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
490
- `).map((y)=>` ${N(y)}`)]:[],"---------------------------------------------"])}let d=Wn("send"),f;try{f=await Nt(e,i,a,void 0,!1,t.cookie,!0,d.metadata)}catch(h){if(Lr(h))console.error(`\u2717 HEAD was NOT posted: ${pe(h)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${pe(h)}
491
- Check before retrying, or you will have two boards: slack pinlog ls ${un(t.target)}${o}`);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:l?.team,channel:i,target:t.target,ts:f,text:a,asBot:t.asBot});let p=ft(i,f);console.log(`\u2713 Posted HEAD: ${p}`);let g=Lg(c,"this new top-level post notified everyone who follows the channel");if(g)console.error(g);try{await gc(e,i,f,t.cookie),console.log("\u2713 Pinned")}catch(h){let m=h instanceof Error?h.message:String(h),y=/missing_scope/.test(m)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:pe(h);console.error(`\u26A0 NOT pinned: ${y}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${p}${o}`)}if(t.log)try{let h=await Nt(e,i,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${h})`)}catch(h){let m=ke("pinlog-log",i,f,t.log,l?.userId??"");console.error(`${Lr(h)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${pe(h)}
490
+ `).map((y)=>` ${N(y)}`)]:[],"---------------------------------------------"])}let d=Wn("send"),f;try{f=await Mt(e,i,a,void 0,!1,t.cookie,!0,d.metadata)}catch(h){if(Nr(h))console.error(`\u2717 HEAD was NOT posted: ${pe(h)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${pe(h)}
491
+ Check before retrying, or you will have two boards: slack pinlog ls ${dn(t.target)}${o}`);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:l?.team,channel:i,target:t.target,ts:f,text:a,asBot:t.asBot});let p=ft(i,f);console.log(`\u2713 Posted HEAD: ${p}`);let g=Bg(c,"this new top-level post notified everyone who follows the channel");if(g)console.error(g);try{await yc(e,i,f,t.cookie),console.log("\u2713 Pinned")}catch(h){let m=h instanceof Error?h.message:String(h),y=/missing_scope/.test(m)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:pe(h);console.error(`\u26A0 NOT pinned: ${y}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${p}${o}`)}if(t.log)try{let h=await Mt(e,i,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${h})`)}catch(h){let m=we("pinlog-log",i,f,t.log,l?.userId??"");console.error(`${Nr(h)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${pe(h)}
492
492
  The board IS posted. Retry just the reason (check the thread first):
493
- slack pinlog note ${p} ${un(is(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${o} --code=${m}`),process.exit(1)}}async function Dg(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(Ke(t.log,t.allowUrlAdjacent),t.state!==void 0)Ke(t.state,t.allowUrlAdjacent);Pr("log line",t.log);let n=Kt(e,t.cookie),{channel:s,ts:o,ref:r}=await Xc(e,t.target,t.cookie);try{fg(`pinlog-${s}-${o}`)}catch(y){if(!(y instanceof Qs))throw y;console.error(`Error: another update of ${ft(s,o)} is running (${y.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await Sk(e,s,o,t.cookie),l=typeof i.text==="string"?i.text:"";if(t.adopt&&t.logOnly)console.error("Error: --adopt rewrites the state with a footer \u2014 it does not apply to note."),process.exit(2);if(!ds(l)&&!t.adopt)console.error(`Error: the message at ${ft(s,o)} is not a pinlog HEAD (no "${eo}" footer).
494
- `+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let u=await n(),c=ft(s,o),a=new Date,d=`${t.workspace?` -w ${un(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=ke("pinlog-log",s,o,t.log,u?.userId??""),p=`slack pinlog note ${c} ${un(is(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,g=Lg(a,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==f){let y=await dn(e,s,r,t.cookie);Se(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",Ee(u,{asBot:t.asBot}),` \u2192 ${y}, thread of ${c}`,...t.log.split(`
495
- `).map((w)=>` ${N(w)}`),"---------------------------------------------"])}}else{let y=Mc(t.state,a);Pr("new HEAD (state + footer)",y);let w=!ds(l),x=ke("pinlog-update",s,o,l,t.state,t.log,u?.userId??"");if(t.code!==x){let C=await dn(e,s,r,t.cookie),S=to(l).trim()===to(t.state).trim();Se(t.code,x,["--- Updating pinlog --------------------------",Ee(u,{asBot:t.asBot}),` \u2192 ${C}, ${c}`,"--- Current HEAD -----------------------------",...l.split(`
493
+ slack pinlog note ${p} ${dn(is(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${o} --code=${m}`),process.exit(1)}}async function xg(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(Ke(t.log,t.allowUrlAdjacent),t.state!==void 0)Ke(t.state,t.allowUrlAdjacent);Lr("log line",t.log);let n=qt(e,t.cookie),{channel:s,ts:o,ref:r}=await tl(e,t.target,t.cookie);try{hg(`pinlog-${s}-${o}`)}catch(y){if(!(y instanceof Qs))throw y;console.error(`Error: another update of ${ft(s,o)} is running (${y.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let i=await $k(e,s,o,t.cookie),l=typeof i.text==="string"?i.text:"";if(t.adopt&&t.logOnly)console.error("Error: --adopt rewrites the state with a footer \u2014 it does not apply to note."),process.exit(2);if(!ds(l)&&!t.adopt)console.error(`Error: the message at ${ft(s,o)} is not a pinlog HEAD (no "${eo}" footer).
494
+ `+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let u=await n(),c=ft(s,o),a=new Date,d=`${t.workspace?` -w ${dn(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=we("pinlog-log",s,o,t.log,u?.userId??""),p=`slack pinlog note ${c} ${dn(is(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,g=Bg(a,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==f){let y=await Ut(e,s,r,t.cookie);xe(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",_e(u,{asBot:t.asBot}),` \u2192 ${y}, thread of ${c}`,...t.log.split(`
495
+ `).map((w)=>` ${N(w)}`),"---------------------------------------------"])}}else{let y=Wc(t.state,a);Lr("new HEAD (state + footer)",y);let w=!ds(l),x=we("pinlog-update",s,o,l,t.state,t.log,u?.userId??"");if(t.code!==x){let C=await Ut(e,s,r,t.cookie),S=to(l).trim()===to(t.state).trim();xe(t.code,x,["--- Updating pinlog --------------------------",_e(u,{asBot:t.asBot}),` \u2192 ${C}, ${c}`,"--- Current HEAD -----------------------------",...l.split(`
496
496
  `).map((k)=>` ${N(k)}`),"--- New HEAD (edited in place \u2014 silent) ------",...y.split(`
497
497
  `).map((k)=>` ${N(k)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
498
- `).map((k)=>` ${N(k)}`),"---------------------------------------------",...S?["\u26A0 The state text is unchanged \u2014 only the footer time moves. Replies are for real changes."]:[],...w?["\u26A0 Adopting: this message has no pinlog footer yet \u2014 it becomes a board now."]:[]])}let D=Wn("edit");try{await Mt(e,s,o,y,t.cookie,!0,D.metadata)}catch(C){let S=C instanceof Error?C.message:String(C),k=/cant_update_message/.test(S)?`
499
- Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",O=Lr(C)?`\u2717 HEAD was NOT updated: ${pe(C)}${k}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${pe(C)}
498
+ `).map((k)=>` ${N(k)}`),"---------------------------------------------",...S?["\u26A0 The state text is unchanged \u2014 only the footer time moves. Replies are for real changes."]:[],...w?["\u26A0 Adopting: this message has no pinlog footer yet \u2014 it becomes a board now."]:[]])}let D=Wn("edit");try{await Bt(e,s,o,y,t.cookie,!0,D.metadata)}catch(C){let S=C instanceof Error?C.message:String(C),k=/cant_update_message/.test(S)?`
499
+ Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",O=Nr(C)?`\u2717 HEAD was NOT updated: ${pe(C)}${k}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${pe(C)}
500
500
  Check it first: slack pinlog get ${c}${d}`;console.error(`${O}
501
- The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}D.record({team:u?.team,channel:s,target:t.target,ts:o,text:y,asBot:t.asBot});let E;try{if(E=Y(T(await Pe(e,s,o,1,t.cookie)).messages).map(T).find((S)=>S.ts===o),!E)console.error("\u26A0 HEAD updated, but the read-back did not return it, so it was not checked")}catch(C){console.error(`\u26A0 HEAD updated, but it could not be read back to check: ${pe(C)}`)}if(E&&!ep(y,E)){let C=Ha(E.blocks);console.error(`\u2717 HEAD was edited, but Slack does not show what was sent (${tp(js(y,C),js(typeof E.text==="string"?E.text:"",C))}).
502
- The log reply was NOT posted. Check it: slack pinlog get ${c}${d}`),process.exit(3)}console.log(`\u2713 HEAD updated${E?" (read back: matches)":""}: ${c}`)}let h=Wn("send"),m;try{m=await Nt(e,s,t.log,o,!1,t.cookie,!0,h.metadata)}catch(y){let w=Lr(y);console.error((w?`\u2717 Log reply was NOT posted: ${pe(y)}
501
+ The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}D.record({team:u?.team,channel:s,target:t.target,ts:o,text:y,asBot:t.asBot});let E;try{if(E=Y(T(await Pe(e,s,o,1,t.cookie)).messages).map(T).find((S)=>S.ts===o),!E)console.error("\u26A0 HEAD updated, but the read-back did not return it, so it was not checked")}catch(C){console.error(`\u26A0 HEAD updated, but it could not be read back to check: ${pe(C)}`)}if(E&&!sp(y,E)){let C=Ya(E.blocks);console.error(`\u2717 HEAD was edited, but Slack does not show what was sent (${op(js(y,C),js(typeof E.text==="string"?E.text:"",C))}).
502
+ The log reply was NOT posted. Check it: slack pinlog get ${c}${d}`),process.exit(3)}console.log(`\u2713 HEAD updated${E?" (read back: matches)":""}: ${c}`)}let h=Wn("send"),m;try{m=await Mt(e,s,t.log,o,!1,t.cookie,!0,h.metadata)}catch(y){let w=Nr(y);console.error((w?`\u2717 Log reply was NOT posted: ${pe(y)}
503
503
  `:`\u26A0 UNKNOWN whether the log reply was posted: ${pe(y)}
504
504
  `)+(t.logOnly?"":` The HEAD IS updated \u2014 only the log line ${w?"is":"may be"} missing.
505
505
  `)+(w?"":` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${c}${d}
506
506
  `)+` Retry just the log line${w?"":" (only if it is not there)"}:
507
- ${p}`),process.exit(1)}if(h.record({team:u?.team,channel:s,target:t.target,ts:m,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${m})`),g)console.error(g)}function kg(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Ek(e){return Lc(new Date(Number(e.split(".")[0])*1000))}async function $k(e,t,n,s){if(typeof t.user==="string"){let r=n.get(t.user);if(r!==void 0)return r;let i;try{i=await Re(e,t.user,s)}catch{i=t.user}return n.set(t.user,i),i}let o=T(t.bot_profile);if(typeof o.name==="string")return o.name;return typeof t.username==="string"?t.username:"bot"}async function Ck(e,t,n,s){let{channel:o,ts:r}=await Xc(e,t,n),i=[],l,u=0;do{let h=T(await dh(e,o,r,l,200,n));for(let y of Y(h.messages).map(T)){if(String(y.ts)===r&&i.some((w)=>String(w.ts)===r))continue;i.push(y)}let m=T(h.response_metadata).next_cursor;l=typeof m==="string"&&m?m:void 0,u++}while(l&&u<50);let c=l===void 0,a=i.find((h)=>String(h.ts)===r);if(!a)console.error(`Error: no message at ts=${r} in ${o}.`),process.exit(1);let d=typeof a.text==="string"?a.text:"",f=i.filter((h)=>String(h.ts)!==r);if(s){console.log(JSON.stringify({id:ft(o,r),isPinlog:ds(d),updated:Bc(d),complete:c,head:d,log:f.map((h)=>({ts:String(h.ts),user:h.user??null,text:typeof h.text==="string"?h.text:""}))}));return}if(!ds(d))console.error(`\u26A0 ${ft(o,r)} has no "${eo}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${ft(o,r)} ===`);for(let h of kg(d).split(`
508
- `))console.log(N(h));let p=c?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${f.length}${p}) ===`);let g=new Map;for(let h of f){let m=typeof h.text==="string"?h.text:"",y=N(await $k(e,h,g,n)),w=kg(m).split(`
509
- `).map((x)=>N(x));console.log(`${Ek(String(h.ts))} @${y}: ${w[0]??""}`);for(let x of w.slice(1))console.log(` ${x}`)}}async function Ng(e,t,n,s){let o=0,r,i=[];do{let l=T(await ot(e,t,Math.min(200,n-o),void 0,r,s)),u=Y(l.messages).map(T);o+=u.length;for(let a of u)if(typeof a.text==="string"&&ds(a.text))i.push(a);let c=T(l.response_metadata).next_cursor;r=typeof c==="string"&&c?c:void 0}while(r&&o<n);return{found:i,scanned:o}}function Mg(e){return N(to(e).split(`
510
- `).find((t)=>t.trim())??"").slice(0,80)}async function Ak(e,t,n,s){let{ref:o,ts:r}=Ut(t);if(r||$r(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${un(t)}`),process.exit(2);let i=await be(e,o,s),{found:l,scanned:u}=await Ng(e,i,n,s),c=await dn(e,i,o,s);if(l.length===0){console.log(`No pinlogs in the last ${u} messages of ${c}.${u>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let a of l){let d=String(a.ts),f=ft(i,d),p=String(a.text),g=Y(a.pinned_to).some((y)=>y===i)?"\uD83D\uDCCC":" ",h=Mg(p),m=typeof a.reply_count==="number"?a.reply_count:0;console.log(`${g} ${f} updated ${Bc(p)??"?"} log ${m}`),console.log(` ${h}`)}}async function Fk(e,t,n){let{channel:s,ts:o}=await Xc(e,t,n);try{await gc(e,s,o,n),console.log(`\u2713 Pinned ${ft(s,o)}`)}catch(r){let i=r instanceof Error?r.message:String(r);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${ft(s,o)}`);return}console.error(`\u2717 NOT pinned: ${pe(r)}`),process.exit(1)}}async function Tk(e,t){let{ref:n,ts:s}=Ut(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 o=t.emoji.replace(/^:|:$/g,""),r;if(t.channelId)r=t.channelId;else r=await be(e,n,t.cookie);if(t.remove)await Bt(e,r,s,o,t.cookie),console.log(`\u2713 Removed :${o}: (ts: ${s})`);else await Ft(e,r,s,o,t.cookie),console.log(`\u2713 Reacted :${o}: (ts: ${s})`)}async function Vc(e,t,n,s){if(!n||!t.startsWith("D"))return!1;try{let o=T(await Ln(e,t,s)),r=T(o.channel);return r.is_im===!0&&r.user===n}catch{return!1}}function Ok(e){let t=new Set;for(let n of e){if(typeof n.user==="string")t.add(n.user);if(typeof n.parent_user_id==="string")t.add(n.parent_user_id);for(let s of Y(n.reply_users))if(typeof s==="string")t.add(s)}return t}async function Rk(e,t,n){if(!t.startsWith("D"))return;try{let s=T(T(await Ln(e,t,n)).channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function Ik(e,t){let{ref:n,threadTs:s}=xt(t.target),o=t.cookie;if(!t.code&&np(t.message))console.error(sp(t.target));let r=Kt(e,o),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await jt(e,t.userId,o);else i=await be(e,n,o);if(!t.asBot&&await Vc(e,i,(await r())?.userId,o))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
511
- `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let l=Be(t.message);Ke(l,t.allowUrlAdjacent);let u=l,c=null;if(t.mentions){c=await cn(t.mentionToken??e,l,i,t.mentionCookie),u=c.text;for(let S of _r(c.unresolved))console.error(`\u26A0 ${N(S)}`)}let a=[];if(c&&(c.resolved.length>0||c.unresolved.length>0)){a.push("--- Mentions ---------------------------------");for(let S of c.resolved)a.push(` \u2713 ${N(S.surface)} \u2192 @${N(S.display)} (${S.userId}) \u2014 will notify`);for(let S of c.unresolved){let k=S.reason==="ambiguous"?"ambiguous":S.reason==="unavailable"?"lookup unavailable":"no match";a.push(` \u26A0 ${N(S.surface)} \u2014 plain text, NOT notified (${k})`)}}let d="",f="?",p=[],g,h,m;if(s)try{let S=await Pe(e,i,s,100,o);p=Y(S.messages).map(T);let k=p[p.length-1];d=typeof k?.text==="string"?k.text:"",g=typeof k?.user==="string"?k.user:void 0,h=typeof k?.bot_id==="string"?k.bot_id:void 0,m=typeof k?.ts==="string"?k.ts:void 0}catch{}else try{let S=await ot(e,i,1,void 0,void 0,o),k=Y(S.messages).map(T),O=k.filter((L)=>L.subtype===void 0||L.subtype===null)[0];d=typeof O?.text==="string"?O.text:"",f=typeof O?.user==="string"?await Re(e,O.user,o):typeof O?.username==="string"?O.username:"?";let P=k[0];g=typeof P?.user==="string"?P.user:void 0,h=typeof P?.bot_id==="string"?P.bot_id:void 0,m=typeof P?.ts==="string"?P.ts:void 0}catch{}try{let S=s?Ok(p):new Set([await Rk(e,i,o)].filter((k)=>!!k));for(let k of await Qh(t.mentionToken??e,u,t.mentionCookie)){if(S.has(k.userId))continue;console.error(`\u26A0 possible untagged mention: ${N(k.surface)} \u2014 @${N(k.display)} won't be notified (did you mean <@${k.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&m&&(g||h))try{let S=await r();if(!!S&&(!!g&&!!S.userId&&S.userId===g||!!h&&!!S.botId&&S.botId===h)){let O=`slack edit "#${i}:${m}" "<new text>" --channel-id ${i}`;try{let P=await Pn(e,i,m,o);if(P)O=`slack edit "${P}" "<new text>"`}catch{}console.error("\u26A0 They haven't replied yet (the last message is yours)."),console.error(" To avoid a string of messages, consider editing your last message instead of sending a new one:"),console.error(` ${O}`),console.error(" To send anyway, confirm with --code=XXXX.")}}catch{}if(s&&p.length){let S={sim:0,msg:null};for(let k of p){let O=typeof k.text==="string"?k.text:"";if(!O)continue;let P=Dk(u,O);if(P>S.sim)S={sim:P,msg:k}}if(S.msg&&S.sim>=0.82){let k=Math.round(S.sim*100);console.error(`\u26A0 possible duplicate: ${k}% similar to an existing thread message \u2014 ${await Kc(e,S.msg,60,o)}`)}}let y=await r(),w=await jr(e,i,o),x=ke(i,s??"",d,u,y?.userId??"");if(t.code!==x){let S=await dn(e,i,n,o),k=Ee(y,{asBot:t.asBot});if(s){let O=await wk(e,s,p,o),P=p.slice(-3),L=P.length?await Promise.all(P.map(async(v)=>` ${await Kc(e,v,60,o)}`)):[" (thread context unavailable)"];Se(t.code,x,["--- Recent messages in thread ----------------",...L,...a,"--- Sending ----------------------------------",k,` \u2192 ${S} thread of ${O} \u2014 THREAD REPLY`,` Message: ${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}else Se(t.code,x,["--- Last message in channel ------------------",` ${f}: ${ls(d.split(`
512
- `)[0]??"").slice(0,100)}`,...a,"--- Sending ----------------------------------",k,` \u2192 ${S} \u2014 NEW top-level message`,` Message: ${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}let D=Wn("send"),E=await Nt(e,i,u,s,t.broadcast,o,void 0,D.metadata),C="";try{C=await Pn(e,i,E,o)}catch{}if(D.record({team:(await r())?.team,channel:i,target:t.target,ts:E,threadTs:s,permalink:C,text:u,asBot:t.asBot}),C)console.log(`\u2713 Sent: ${C}`);else console.log(`\u2713 Sent (ts: ${E})`);if(t.asBot&&i.startsWith("D"))try{let S=await Po(e);if(!S.ok)for(let k of Lo(S,!0))console.error(k);else{let k=S.appId?`https://api.slack.com/apps/${S.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${k} \u2192 App Home.`)}}catch{}}var vk=2,le=3,Pk=4,Lk=5,Bg=6,Nk=7,Mk=10;function Bk(){return/^(1|true|yes|on)$/i.test(process.env.SLACK_TERM_ASK_EXPLAIN??"")}var xg=8,jk=(e)=>new Promise((t)=>setTimeout(t,e)),jg=new Set(["thread_broadcast"]),Wk=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function Wg(e){if(!e.length)return;let t=e.map((n)=>{let s=N(n.surface);if(n.reason==="unavailable")return`${s}: could not fetch the user list or channel members (users:read missing or an API/connection error)`;if(n.reason==="ambiguous")return`${s}: matches multiple people \u2014 use an explicit <@USERID> tag`;return`${s}: matched no one`});console.error(`Error: \`ask\` will not post with unresolved answerer tags.
507
+ ${p}`),process.exit(1)}if(h.record({team:u?.team,channel:s,target:t.target,ts:m,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${m})`),g)console.error(g)}function Sg(e){return e.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&")}function Ak(e){return Bc(new Date(Number(e.split(".")[0])*1000))}async function Fk(e,t,n,s){if(typeof t.user==="string"){let r=n.get(t.user);if(r!==void 0)return r;let i;try{i=await Re(e,t.user,s)}catch{i=t.user}return n.set(t.user,i),i}let o=T(t.bot_profile);if(typeof o.name==="string")return o.name;return typeof t.username==="string"?t.username:"bot"}async function Tk(e,t,n,s){let{channel:o,ts:r}=await tl(e,t,n),i=[],l,u=0;do{let h=T(await hh(e,o,r,l,200,n));for(let y of Y(h.messages).map(T)){if(String(y.ts)===r&&i.some((w)=>String(w.ts)===r))continue;i.push(y)}let m=T(h.response_metadata).next_cursor;l=typeof m==="string"&&m?m:void 0,u++}while(l&&u<50);let c=l===void 0,a=i.find((h)=>String(h.ts)===r);if(!a)console.error(`Error: no message at ts=${r} in ${o}.`),process.exit(1);let d=typeof a.text==="string"?a.text:"",f=i.filter((h)=>String(h.ts)!==r);if(s){console.log(JSON.stringify({id:ft(o,r),isPinlog:ds(d),updated:Jc(d),complete:c,head:d,log:f.map((h)=>({ts:String(h.ts),user:h.user??null,text:typeof h.text==="string"?h.text:""}))}));return}if(!ds(d))console.error(`\u26A0 ${ft(o,r)} has no "${eo}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${ft(o,r)} ===`);for(let h of Sg(d).split(`
508
+ `))console.log(N(h));let p=c?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${f.length}${p}) ===`);let g=new Map;for(let h of f){let m=typeof h.text==="string"?h.text:"",y=N(await Fk(e,h,g,n)),w=Sg(m).split(`
509
+ `).map((x)=>N(x));console.log(`${Ak(String(h.ts))} @${y}: ${w[0]??""}`);for(let x of w.slice(1))console.log(` ${x}`)}}async function jg(e,t,n,s){let o=0,r,i=[];do{let l=T(await ot(e,t,Math.min(200,n-o),void 0,r,s)),u=Y(l.messages).map(T);o+=u.length;for(let a of u)if(typeof a.text==="string"&&ds(a.text))i.push(a);let c=T(l.response_metadata).next_cursor;r=typeof c==="string"&&c?c:void 0}while(r&&o<n);return{found:i,scanned:o}}function Wg(e){return N(to(e).split(`
510
+ `).find((t)=>t.trim())??"").slice(0,80)}async function Ok(e,t,n,s){let{ref:o,ts:r}=Kt(t);if(r||Cr(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${dn(t)}`),process.exit(2);let i=await ye(e,o,s),{found:l,scanned:u}=await jg(e,i,n,s),c=await Ut(e,i,o,s);if(l.length===0){console.log(`No pinlogs in the last ${u} messages of ${c}.${u>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let a of l){let d=String(a.ts),f=ft(i,d),p=String(a.text),g=Y(a.pinned_to).some((y)=>y===i)?"\uD83D\uDCCC":" ",h=Wg(p),m=typeof a.reply_count==="number"?a.reply_count:0;console.log(`${g} ${f} updated ${Jc(p)??"?"} log ${m}`),console.log(` ${h}`)}}async function Rk(e,t,n){let{channel:s,ts:o}=await tl(e,t,n);try{await yc(e,s,o,n),console.log(`\u2713 Pinned ${ft(s,o)}`)}catch(r){let i=r instanceof Error?r.message:String(r);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${ft(s,o)}`);return}console.error(`\u2717 NOT pinned: ${pe(r)}`),process.exit(1)}}async function Ik(e,t){let{ref:n,ts:s}=Kt(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 o=t.emoji.replace(/^:|:$/g,""),r;if(t.channelId)r=t.channelId;else r=await ye(e,n,t.cookie);if(t.remove)await jt(e,r,s,o,t.cookie),console.log(`\u2713 Removed :${o}: (ts: ${s})`);else await Ft(e,r,s,o,t.cookie),console.log(`\u2713 Reacted :${o}: (ts: ${s})`)}async function nl(e,t,n,s){if(!n||!t.startsWith("D"))return!1;try{let o=T(await Ln(e,t,s)),r=T(o.channel);return r.is_im===!0&&r.user===n}catch{return!1}}function vk(e){let t=new Set;for(let n of e){if(typeof n.user==="string")t.add(n.user);if(typeof n.parent_user_id==="string")t.add(n.parent_user_id);for(let s of Y(n.reply_users))if(typeof s==="string")t.add(s)}return t}async function Pk(e,t,n){if(!t.startsWith("D"))return;try{let s=T(T(await Ln(e,t,n)).channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function Lk(e,t){let{ref:n,threadTs:s}=xt(t.target),o=t.cookie;if(!t.code&&rp(t.message))console.error(ip(t.target));let r=qt(e,o),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Wt(e,t.userId,o);else i=await ye(e,n,o);if(!t.asBot&&await nl(e,i,(await r())?.userId,o))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
511
+ `+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let l=je(t.message);Ke(l,t.allowUrlAdjacent);let u=l,c=null;if(t.mentions){c=await ln(t.mentionToken??e,l,i,t.mentionCookie),u=c.text;for(let S of Er(c.unresolved))console.error(`\u26A0 ${N(S)}`)}let a=[];if(c&&(c.resolved.length>0||c.unresolved.length>0)){a.push("--- Mentions ---------------------------------");for(let S of c.resolved)a.push(` \u2713 ${N(S.surface)} \u2192 @${N(S.display)} (${S.userId}) \u2014 will notify`);for(let S of c.unresolved){let k=S.reason==="ambiguous"?"ambiguous":S.reason==="unavailable"?"lookup unavailable":"no match";a.push(` \u26A0 ${N(S.surface)} \u2014 plain text, NOT notified (${k})`)}}let d="",f="?",p=[],g,h,m;if(s)try{let S=await Pe(e,i,s,100,o);p=Y(S.messages).map(T);let k=p[p.length-1];d=typeof k?.text==="string"?k.text:"",g=typeof k?.user==="string"?k.user:void 0,h=typeof k?.bot_id==="string"?k.bot_id:void 0,m=typeof k?.ts==="string"?k.ts:void 0}catch{}else try{let S=await ot(e,i,1,void 0,void 0,o),k=Y(S.messages).map(T),O=k.filter((L)=>L.subtype===void 0||L.subtype===null)[0];d=typeof O?.text==="string"?O.text:"",f=typeof O?.user==="string"?await Re(e,O.user,o):typeof O?.username==="string"?O.username:"?";let P=k[0];g=typeof P?.user==="string"?P.user:void 0,h=typeof P?.bot_id==="string"?P.bot_id:void 0,m=typeof P?.ts==="string"?P.ts:void 0}catch{}try{let S=s?vk(p):new Set([await Pk(e,i,o)].filter((k)=>!!k));for(let k of await tg(t.mentionToken??e,u,t.mentionCookie)){if(S.has(k.userId))continue;console.error(`\u26A0 possible untagged mention: ${N(k.surface)} \u2014 @${N(k.display)} won't be notified (did you mean <@${k.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&m&&(g||h))try{let S=await r();if(!!S&&(!!g&&!!S.userId&&S.userId===g||!!h&&!!S.botId&&S.botId===h)){let O=`slack edit "#${i}:${m}" "<new text>" --channel-id ${i}`;try{let P=await Pn(e,i,m,o);if(P)O=`slack edit "${P}" "<new text>"`}catch{}console.error("\u26A0 They haven't replied yet (the last message is yours)."),console.error(" To avoid a string of messages, consider editing your last message instead of sending a new one:"),console.error(` ${O}`),console.error(" To send anyway, confirm with --code=XXXX.")}}catch{}if(s&&p.length){let S={sim:0,msg:null};for(let k of p){let O=typeof k.text==="string"?k.text:"";if(!O)continue;let P=Sk(u,O);if(P>S.sim)S={sim:P,msg:k}}if(S.msg&&S.sim>=0.82){let k=Math.round(S.sim*100);console.error(`\u26A0 possible duplicate: ${k}% similar to an existing thread message \u2014 ${await Gc(e,S.msg,60,o)}`)}}let y=await r(),w=await Wr(e,i,o),x=we(i,s??"",d,u,y?.userId??"");if(t.code!==x){let S=await Ut(e,i,n,o),k=_e(y,{asBot:t.asBot});if(s){let O=await xk(e,s,p,o),P=p.slice(-3),L=P.length?await Promise.all(P.map(async(v)=>` ${await Gc(e,v,60,o)}`)):[" (thread context unavailable)"];xe(t.code,x,["--- Recent messages in thread ----------------",...L,...a,"--- Sending ----------------------------------",k,` \u2192 ${S} thread of ${O} \u2014 THREAD REPLY`,` Message: ${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}else xe(t.code,x,["--- Last message in channel ------------------",` ${f}: ${ls(d.split(`
512
+ `)[0]??"").slice(0,100)}`,...a,"--- Sending ----------------------------------",k,` \u2192 ${S} \u2014 NEW top-level message`,` Message: ${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}let D=Wn("send"),E=await Mt(e,i,u,s,t.broadcast,o,void 0,D.metadata),C="";try{C=await Pn(e,i,E,o)}catch{}if(D.record({team:(await r())?.team,channel:i,target:t.target,ts:E,threadTs:s,permalink:C,text:u,asBot:t.asBot}),t.json)console.log(JSON.stringify({ok:!0,channel:i,ts:E,...s?{thread_ts:s}:{},...C?{permalink:C}:{}}));else if(C)console.log(`\u2713 Sent: ${C}`);else console.log(`\u2713 Sent (ts: ${E})`);if(t.asBot&&i.startsWith("D"))try{let S=await Lo(e);if(!S.ok)for(let k of No(S,!0))console.error(k);else{let k=S.appId?`https://api.slack.com/apps/${S.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${k} \u2192 App Home.`)}}catch{}}var Nk=2,le=3,Mk=4,Bk=5,Jg=6,jk=7,Wk=10;function Jk(){return/^(1|true|yes|on)$/i.test(process.env.SLACK_TERM_ASK_EXPLAIN??"")}var _g=8,Uk=(e)=>new Promise((t)=>setTimeout(t,e));function Kc(e){return e==="-"||e===""&&process.argv.slice(2).includes("-")}async function qc(){return(await Bun.stdin.text()).replace(/\s+$/,"")}var Ug=new Set(["thread_broadcast"]),Kk=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function Kg(e){if(!e.length)return;let t=e.map((n)=>{let s=N(n.surface);if(n.reason==="unavailable")return`${s}: could not fetch the user list or channel members (users:read missing or an API/connection error)`;if(n.reason==="ambiguous")return`${s}: matches multiple people \u2014 use an explicit <@USERID> tag`;return`${s}: matched no one`});console.error(`Error: \`ask\` will not post with unresolved answerer tags.
513
513
  ${t.join(`
514
- `)}`),process.exit(le)}function so(e){let t=new Set;return{text:e.replace(Wk,(s,o)=>{let r=o.toLowerCase();return t.add(r),`<!${r}>`}),kinds:t}}async function Jr(e,t,n){if(!t.startsWith("D"))return;try{let s=T(await Ln(e,t,n)),o=T(s.channel);return o.is_im===!0&&typeof o.user==="string"?o.user:void 0}catch{return}}async function Jg(e,t,n,s){let o=new Map;if(t.threadParentTs||t.replyCount!==0)try{let l=T(await Pe(e,t.channelId,t.threadParentTs??t.ts,100,t.cookie));for(let u of Y(l.messages).map(T))o.set(String(u.ts),u)}catch(l){console.error(` (could not read the thread's follow-up notes: ${l instanceof Error?l.message:String(l)})`)}if(!t.threadOnly&&!t.threadParentTs)try{let l=T(await ot(e,t.channelId,30,t.ts,void 0,t.cookie,!0)),u=Y(l.messages).map(T),c=u.filter((a)=>Number(a.ts)>Number(t.ts)&&(t.askerBotId&&a.bot_id===t.askerBotId||t.askerUserId&&a.user===t.askerUserId)).reduce((a,d)=>Math.min(a,Number(d.ts)),1/0);for(let a of u)if(Number(a.ts)<c&&!o.has(String(a.ts)))o.set(String(a.ts),a)}catch(l){console.error(` (could not read the DM's follow-up notes: ${l instanceof Error?l.message:String(l)})`)}let r=[...o.values()].filter((l)=>Number(l.ts)>Number(t.ts)).filter((l)=>!n||Number(l.ts)>Number(n)).filter((l)=>t.isAnswerer(l.user)&&!l.bot_id).filter((l)=>typeof l.subtype!=="string"||jg.has(l.subtype)).filter((l)=>typeof l.text==="string"&&l.text.trim()!==""&&!nr(l.text)).sort((l,u)=>Number(l.ts)-Number(u.ts)).filter((l)=>!s(l)),i=[];for(let l of r){let u="";try{u=await Pn(e,t.channelId,String(l.ts),t.cookie)}catch{}i.push({ts:String(l.ts),user:String(l.user),text:l.text.trim(),permalink:u})}return i}function Jt(...e){return e.filter((t)=>!!t).reduce((t,n)=>!t||Number(n)>Number(t)?n:t,"")}async function ln(e,t,n){if(t.json){console.log(JSON.stringify({status:n.status,answer:n.answer,how:n.how??null,who:n.who??null,...n.status==="void"?{reason:n.reason??"",supersededBy:n.supersededBy??null}:{},...n.explain?.length?{explain:n.explain}:{},notes:n.notes,cursor:n.cursor,permalink:t.shown}));return}if(n.notes.length){console.error(` ${n.notes.length} thread note(s) (separate from the answer):`);for(let s of n.notes){let o=s.user;try{o=await Re(e,s.user,t.cookie)}catch{}for(let[r,i]of s.text.split(`
515
- `).entries())console.error(` ${r?" ".repeat(N(o).length+2):`${N(o)}: `}${N(i)}`)}}if(n.status==="answered")console.error(` To pick up later notes: ${jn(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}function Ug(e,t,n=!1){let{channelId:s,ts:o,reactable:r,threadOnly:i,audience:l,broadcast:u,cookie:c}=t,a=Me[t.lang],d={explainNow:[],explainPosted:!1},{askerUserId:f,askerBotId:p}=t,g=(B)=>typeof B==="string"&&!!B&&B!==f&&(u||l.has(B)),h=(B)=>{if(d.replyCount=Number(B.reply_count)||0,typeof B.text==="string")d.ownText=B.text},m=(B)=>{let q=typeof B.text==="string"?$t(B.text):void 0;if(q?.kind==="void")d.voided=q;return!!d.voided};function y(B){let q=Y(B.reactions).map(T),z=[];for(let R=0;R<r.length;R++){let te=q.find((M)=>M.name===Te[R].name),Q=te?Y(te.users).filter(g):[];if(Q.length)z.push({index:R,users:Q})}return z}async function w(B,q){if(n)return;let z=typeof B.text==="string"?B.text:"";if(!z)return;let R=tr(z,q,t.lang);if(R===z)return;try{await Mt(e,s,o,R,c,!0)}catch(te){console.error(` (could not add the notice to the question text: ${te instanceof Error?te.message:String(te)})`)}}let x=new Set;function D(B){for(let q of Y(B.reactions).map(T)){if(typeof q.name!=="string"||!wf.includes(q.name))continue;let z=q.name===Pt?"\u2795":"\u2753";for(let R of Y(q.users).filter(g)){if(x.has(R))continue;if(x.add(R),!n)console.error(` (<@${R}> pressed ${z} other; waiting for their reply)`)}}}let E=new Set,C=new Map,S=!1;async function k(B){if(B==="USLACKBOT")return!0;let q=C.get(B);if(q!==void 0)return q;try{let z=T(T(await os(e,B,c)).user).is_bot;if(typeof z!=="boolean")return null;return C.set(B,z),z}catch{return null}}async function O(){let B=t.threadParentTs??o;try{let q,z=0;for(;;){let R=T(await fc(e,s,B,{oldest:o,...q?{cursor:q}:{}},c));if(Y(R.messages).map(T).some((te)=>Number(te.ts)>Number(o)&&nr(te.text)))return"exists";if(q=String(T(R.response_metadata).next_cursor??"")||void 0,!q)break;if(++z>=Mk)return"exists"}}catch(q){return console.error(` (could not read the thread, so the explain-request note has not been posted yet: ${q instanceof Error?q.message:String(q)})`),"unread"}try{await Nt(e,s,a.explainNote,B,!1,c,!0)}catch(q){return console.error(` (could not post the explain-request note to the thread: ${q instanceof Error?q.message:String(q)})`),"failed"}return"posted"}async function P(B){let q=Y(B.reactions).map(T).find((R)=>R.name===sn),z=[];for(let R of q?Y(q.users).filter(g):[]){if(await k(R)!==!1)continue;if(z.push(R),E.has(R))continue;if(E.add(R),!n)console.error(` (<@${R}> pressed \u2139\uFE0F explain \u2014 not an answer. Explain in the thread; still waiting for an answer)`)}if(d.explainNow=z,z.length&&!S&&!n){let R=await O();if(R!=="unread")S=!0,d.explainPosted=R==="posted"}}async function L(B){if(t.explain)await P(B);if(r.length)D(B);let q=y(B);if(q.length<=1&&er(typeof B.text==="string"?B.text:"").length)await w(B,[]);if(!q.length)return null;if(q.length===1){let{index:M,users:oe}=q[0];return{answer:r[M],how:a.howReaction(Te[M].glyph),who:oe[0],choice:M+1}}let z=q.map((M)=>Te[M.index].glyph).join(" / "),R=new Map;for(let M of q)for(let oe of M.users)R.set(oe,(R.get(oe)??0)+1);let te=[...R].filter(([,M])=>M>1).map(([M])=>M);if(!n)console.error(te.length?` (${z} are pressed at once; waiting until it is narrowed to one)`:` (answers are split: ${z}; waiting until they agree on one)`);let Q=te.sort();return await w(B,Q),null}let v=[...r,...t.overflow];function j(B,q=1/0){let z=[...B].sort((R,te)=>Number(R.ts)-Number(te.ts));for(let R of z){if(!(Number(R.ts)>Number(o)))continue;if(t.after&&!(Number(R.ts)>Number(t.after)))continue;if(!g(R.user))continue;if(typeof R.subtype==="string"&&!jg.has(R.subtype))continue;if(Number(R.ts)>=q)break;let te=typeof R.text==="string"?R.text.trim():"";if(!te||t.explain&&nr(te))continue;if(!v.length)return{answer:te,how:a.howReply,who:R.user,ts:String(R.ts)};let Q=va(te,v);if(Q.kind==="chosen")return{answer:v[Q.index-1],how:a.howReplyN(Q.index),who:R.user,ts:String(R.ts),choice:Q.index};let M=Q.kind==="ambiguous",oe=d.unchosen;if(!oe||oe.ambiguous&&!M||oe.ambiguous===M&&Number(R.ts)<Number(oe.ts))d.unchosen={text:te,who:typeof R.user==="string"?R.user:"",ts:String(R.ts),ambiguous:M}}return null}async function H(){if(delete d.unchosen,t.threadParentTs){let R=T(await Pe(e,s,t.threadParentTs,100,c)),te=Y(R.messages).map(T),Q=te.find((M)=>M.ts===o);if(Q){if(h(Q),m(Q))return null;let M=await L(Q);if(M)return M}return j(te)}let B=T(await ot(e,s,30,o,void 0,c,!0)),q=Y(B.messages).map(T),z=q.find((R)=>R.ts===o);if(z){if(h(z),m(z))return null}if(z){let R=await L(z);if(R)return R}if(!i){let R=q.filter((Q)=>Number(Q.ts)>Number(o)&&(p&&Q.bot_id===p||f&&Q.user===f)).reduce((Q,M)=>Math.min(Q,Number(M.ts)),1/0),te=j(q,R);if(te)return te}if(z&&Number(z.reply_count)>0){let R=T(await Pe(e,s,o,30,c)),te=j(Y(R.messages).map(T));if(te)return te}return null}return{poll:H,state:d,isAnswerer:g,candidates:v}}async function Kg(e,t){let{channelId:n,ts:s,question:o,reactable:r,threadOnly:i,cookie:l,timeout:u,shown:c}=t,{askerUserId:a,askerBotId:d}=t,{poll:f,state:p,isAnswerer:g,candidates:h}=Ug(e,t),m="";async function y(k){for(let P=0;P<r.length;P++)try{await Bt(e,n,s,Te[P].name,l)}catch{}let O="";if(k.who)try{O=await Re(e,k.who,l)}catch{O=k.who}if(O)console.error(` Answered by: ${N(O)}`);try{let P=p.ownText?_f(p.ownText,k.choice):void 0;await Mt(e,n,s,Sf(o,k,O,t.lang,P),l,!0);try{await Ft(e,n,s,Oa,l),await Bt(e,n,s,t.seedMarker,l)}catch{}try{if(t.explain)await Bt(e,n,s,sn,l)}catch{}}catch(P){console.error(` (failed to update the original message: ${P instanceof Error?P.message:String(P)})`)}}let w=Date.now()+u*1000,x=Date.now(),D=0,E=On.minMs,C=0,S;for(;;){let k=null;try{k=await f(),D=0}catch(P){if(P instanceof Dt)C=P.retryAfter*1000;else{if(D++,D>=xg)console.error(`Error: Slack requests failed ${D} times in a row: ${P instanceof Error?P.message:String(P)}`),process.exit(le);console.error(` (Slack error ${D}/${xg}, retrying: ${P instanceof Error?P.message:String(P)})`)}}S=p.unchosen;let O=p.voided;if(O){if(qg(O,c),t.json)await ln(e,t,{status:"void",answer:null,reason:O.reason,...O.supersededBy?{supersededBy:O.supersededBy}:{},notes:[],cursor:Jt(s,t.after)});process.exit(Bg)}if(k){let P=await Jg(e,{channelId:n,ts:s,threadOnly:i,replyCount:p.replyCount,isAnswerer:g,askerUserId:a,askerBotId:d,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...l?{cookie:l}:{}},t.after,(v)=>v.ts===k.ts);await y(k);let L={status:"answered",answer:k.answer,how:k.how,notes:P,cursor:Jt(s,t.after,k.ts,...P.map((v)=>v.ts))};if(ac(n,s,k.answer,L.cursor),k.who)L.who=k.who;await ln(e,t,L),process.exit(0)}if(p.explainPosted&&t.explainExit){if(console.error(` An explanation was requested (the question is still open). Explain in the thread, then collect with: ${jn(c,t.asBot,t.after)}`),t.json)await ln(e,t,{status:"explain",answer:null,notes:[],cursor:Jt(s,t.after),explain:p.explainNow});process.exit(Nk)}if(S&&!S.ambiguous){let P=S.who;try{if(P)P=await Re(e,P,l)}catch{}if(console.error(` (${N(P)} replied with something that is not a choice \u2014 not a decision. Printing the reply on stdout)`),console.error(` Choices: ${h.map((L,v)=>`${v+1}. ${N(Le(L))}`).join(" ")}`),console.error(` ${c}`),console.error(` To wait for what comes after this reply: ${jn(c,t.asBot,S.ts)}`),Wp(n,s,S.text,Jt(s,t.after,S.ts)),t.json)await ln(e,t,{status:"freetext",answer:S.text,who:S.who,notes:[],cursor:Jt(s,t.after,S.ts),explain:p.explainNow});else console.log(S.text);process.exit(Lk)}if(S&&S.ts!==m){m=S.ts;let P=S.who;try{if(P)P=await Re(e,P,l)}catch{}console.error(` (${N(P)}'s reply matches several choices; waiting until it is narrowed to one)`),console.error(` "${N(S.text)}"`)}if(Date.now()>=w)break;await jk(Math.min(Math.max(E,C),Math.max(0,w-Date.now()))),C=0,E=Tf(E,Date.now()-x)}if(S){if(console.error("Error: there was a reply, but it matches several choices so it cannot be settled (the message is left in place)"),console.error(` Reply: "${N(S.text)}"`),console.error(` Choices: ${h.map((k,O)=>`${O+1}. ${N(Le(k))}`).join(" ")}`),console.error(` ${c}`),console.error(` Reply in the thread, then collect with: ${jn(c,t.asBot,t.after)}`),t.json)await ln(e,t,{status:"ambiguous",answer:null,notes:[],cursor:Jt(s,t.after),explain:p.explainNow});process.exit(Pk)}if(u===0)console.error(`No answer yet: ${c}`);else console.error(`Error: no answer within ${u}s (the message is left in place)`),console.error(` ${c}`),console.error(` To collect later: ${jn(c,t.asBot,t.after)}`);if(t.json)await ln(e,t,{status:"timeout",answer:null,notes:[],cursor:Jt(s,t.after),explain:p.explainNow});process.exit(vk)}function jn(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function Jk(e,t){let{ref:n,threadTs:s}=xt(t.target,!1),o=t.cookie,r=Kt(e,o),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await jt(e,t.userId,o);else i=await be(e,n,o);let l=(await r())?.userId??"",u=await Jr(e,i,o);if(!t.asBot&&!!l&&u===l)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
516
- `+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let c=so(Be(t.question)),a=so(Be(t.body??"")),d=new Set([...c.kinds,...a.kinds]);for(let G of`${c.text}
517
- ${a.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))d.add(G[1]);let f=t.mentionToken??e,p=await cn(f,c.text,i,t.mentionCookie),g=a.text?await cn(f,a.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},h=p.text,m=g.text,y=[...p.resolved,...g.resolved],w=[...p.unresolved,...g.unresolved];Wg(w);let x=d.size>0,D=new Set(y.map((G)=>G.userId).filter((G)=>G!==l)),E=new Map(y.map((G)=>[G.userId,G.display]));for(let G of`${h}
514
+ `)}`),process.exit(le)}function so(e){let t=new Set;return{text:e.replace(Kk,(s,o)=>{let r=o.toLowerCase();return t.add(r),`<!${r}>`}),kinds:t}}async function Ur(e,t,n){if(!t.startsWith("D"))return;try{let s=T(await Ln(e,t,n)),o=T(s.channel);return o.is_im===!0&&typeof o.user==="string"?o.user:void 0}catch{return}}async function qg(e,t,n,s){let o=new Map;if(t.threadParentTs||t.replyCount!==0)try{let l=T(await Pe(e,t.channelId,t.threadParentTs??t.ts,100,t.cookie));for(let u of Y(l.messages).map(T))o.set(String(u.ts),u)}catch(l){console.error(` (could not read the thread's follow-up notes: ${l instanceof Error?l.message:String(l)})`)}if(!t.threadOnly&&!t.threadParentTs)try{let l=T(await ot(e,t.channelId,30,t.ts,void 0,t.cookie,!0)),u=Y(l.messages).map(T),c=u.filter((a)=>Number(a.ts)>Number(t.ts)&&(t.askerBotId&&a.bot_id===t.askerBotId||t.askerUserId&&a.user===t.askerUserId)).reduce((a,d)=>Math.min(a,Number(d.ts)),1/0);for(let a of u)if(Number(a.ts)<c&&!o.has(String(a.ts)))o.set(String(a.ts),a)}catch(l){console.error(` (could not read the DM's follow-up notes: ${l instanceof Error?l.message:String(l)})`)}let r=[...o.values()].filter((l)=>Number(l.ts)>Number(t.ts)).filter((l)=>!n||Number(l.ts)>Number(n)).filter((l)=>t.isAnswerer(l.user)&&!l.bot_id).filter((l)=>typeof l.subtype!=="string"||Ug.has(l.subtype)).filter((l)=>typeof l.text==="string"&&l.text.trim()!==""&&!sr(l.text)).sort((l,u)=>Number(l.ts)-Number(u.ts)).filter((l)=>!s(l)),i=[];for(let l of r){let u="";try{u=await Pn(e,t.channelId,String(l.ts),t.cookie)}catch{}i.push({ts:String(l.ts),user:String(l.user),text:l.text.trim(),permalink:u})}return i}function Jt(...e){return e.filter((t)=>!!t).reduce((t,n)=>!t||Number(n)>Number(t)?n:t,"")}async function un(e,t,n){if(t.json){console.log(JSON.stringify({status:n.status,answer:n.answer,how:n.how??null,who:n.who??null,...n.status==="void"?{reason:n.reason??"",supersededBy:n.supersededBy??null}:{},...n.explain?.length?{explain:n.explain}:{},notes:n.notes,cursor:n.cursor,permalink:t.shown}));return}if(n.notes.length){console.error(` ${n.notes.length} thread note(s) (separate from the answer):`);for(let s of n.notes){let o=s.user;try{o=await Re(e,s.user,t.cookie)}catch{}for(let[r,i]of s.text.split(`
515
+ `).entries())console.error(` ${r?" ".repeat(N(o).length+2):`${N(o)}: `}${N(i)}`)}}if(n.status==="answered")console.error(` To pick up later notes: ${jn(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}function Hg(e,t,n=!1){let{channelId:s,ts:o,reactable:r,threadOnly:i,audience:l,broadcast:u,cookie:c}=t,a=Be[t.lang],d={explainNow:[],explainPosted:!1},{askerUserId:f,askerBotId:p}=t,g=(B)=>typeof B==="string"&&!!B&&B!==f&&(u||l.has(B)),h=(B)=>{if(d.replyCount=Number(B.reply_count)||0,typeof B.text==="string")d.ownText=B.text},m=(B)=>{let q=typeof B.text==="string"?$t(B.text):void 0;if(q?.kind==="void")d.voided=q;return!!d.voided};function y(B){let q=Y(B.reactions).map(T),z=[];for(let R=0;R<r.length;R++){let te=q.find((M)=>M.name===Te[R].name),Q=te?Y(te.users).filter(g):[];if(Q.length)z.push({index:R,users:Q})}return z}async function w(B,q){if(n)return;let z=typeof B.text==="string"?B.text:"";if(!z)return;let R=nr(z,q,t.lang);if(R===z)return;try{await Bt(e,s,o,R,c,!0)}catch(te){console.error(` (could not add the notice to the question text: ${te instanceof Error?te.message:String(te)})`)}}let x=new Set;function D(B){for(let q of Y(B.reactions).map(T)){if(typeof q.name!=="string"||!xf.includes(q.name))continue;let z=q.name===Lt?"\u2795":"\u2753";for(let R of Y(q.users).filter(g)){if(x.has(R))continue;if(x.add(R),!n)console.error(` (<@${R}> pressed ${z} other; waiting for their reply)`)}}}let E=new Set,C=new Map,S=!1;async function k(B){if(B==="USLACKBOT")return!0;let q=C.get(B);if(q!==void 0)return q;try{let z=T(T(await os(e,B,c)).user).is_bot;if(typeof z!=="boolean")return null;return C.set(B,z),z}catch{return null}}async function O(){let B=t.threadParentTs??o;try{let q,z=0;for(;;){let R=T(await hc(e,s,B,{oldest:o,...q?{cursor:q}:{}},c));if(Y(R.messages).map(T).some((te)=>Number(te.ts)>Number(o)&&sr(te.text)))return"exists";if(q=String(T(R.response_metadata).next_cursor??"")||void 0,!q)break;if(++z>=Wk)return"exists"}}catch(q){return console.error(` (could not read the thread, so the explain-request note has not been posted yet: ${q instanceof Error?q.message:String(q)})`),"unread"}try{await Mt(e,s,a.explainNote,B,!1,c,!0)}catch(q){return console.error(` (could not post the explain-request note to the thread: ${q instanceof Error?q.message:String(q)})`),"failed"}return"posted"}async function P(B){let q=Y(B.reactions).map(T).find((R)=>R.name===on),z=[];for(let R of q?Y(q.users).filter(g):[]){if(await k(R)!==!1)continue;if(z.push(R),E.has(R))continue;if(E.add(R),!n)console.error(` (<@${R}> pressed \u2139\uFE0F explain \u2014 not an answer. Explain in the thread; still waiting for an answer)`)}if(d.explainNow=z,z.length&&!S&&!n){let R=await O();if(R!=="unread")S=!0,d.explainPosted=R==="posted"}}async function L(B){if(t.explain)await P(B);if(r.length)D(B);let q=y(B);if(q.length<=1&&tr(typeof B.text==="string"?B.text:"").length)await w(B,[]);if(!q.length)return null;if(q.length===1){let{index:M,users:oe}=q[0];return{answer:r[M],how:a.howReaction(Te[M].glyph),who:oe[0],choice:M+1}}let z=q.map((M)=>Te[M.index].glyph).join(" / "),R=new Map;for(let M of q)for(let oe of M.users)R.set(oe,(R.get(oe)??0)+1);let te=[...R].filter(([,M])=>M>1).map(([M])=>M);if(!n)console.error(te.length?` (${z} are pressed at once; waiting until it is narrowed to one)`:` (answers are split: ${z}; waiting until they agree on one)`);let Q=te.sort();return await w(B,Q),null}let v=[...r,...t.overflow];function j(B,q=1/0){let z=[...B].sort((R,te)=>Number(R.ts)-Number(te.ts));for(let R of z){if(!(Number(R.ts)>Number(o)))continue;if(t.after&&!(Number(R.ts)>Number(t.after)))continue;if(!g(R.user))continue;if(typeof R.subtype==="string"&&!Ug.has(R.subtype))continue;if(Number(R.ts)>=q)break;let te=typeof R.text==="string"?R.text.trim():"";if(!te||t.explain&&sr(te))continue;if(!v.length)return{answer:te,how:a.howReply,who:R.user,ts:String(R.ts)};let Q=La(te,v);if(Q.kind==="chosen")return{answer:v[Q.index-1],how:a.howReplyN(Q.index),who:R.user,ts:String(R.ts),choice:Q.index};let M=Q.kind==="ambiguous",oe=d.unchosen;if(!oe||oe.ambiguous&&!M||oe.ambiguous===M&&Number(R.ts)<Number(oe.ts))d.unchosen={text:te,who:typeof R.user==="string"?R.user:"",ts:String(R.ts),ambiguous:M}}return null}async function H(){if(delete d.unchosen,t.threadParentTs){let R=T(await Pe(e,s,t.threadParentTs,100,c)),te=Y(R.messages).map(T),Q=te.find((M)=>M.ts===o);if(Q){if(h(Q),m(Q))return null;let M=await L(Q);if(M)return M}return j(te)}let B=T(await ot(e,s,30,o,void 0,c,!0)),q=Y(B.messages).map(T),z=q.find((R)=>R.ts===o);if(z){if(h(z),m(z))return null}if(z){let R=await L(z);if(R)return R}if(!i){let R=q.filter((Q)=>Number(Q.ts)>Number(o)&&(p&&Q.bot_id===p||f&&Q.user===f)).reduce((Q,M)=>Math.min(Q,Number(M.ts)),1/0),te=j(q,R);if(te)return te}if(z&&Number(z.reply_count)>0){let R=T(await Pe(e,s,o,30,c)),te=j(Y(R.messages).map(T));if(te)return te}return null}return{poll:H,state:d,isAnswerer:g,candidates:v}}async function zg(e,t){let{channelId:n,ts:s,question:o,reactable:r,threadOnly:i,cookie:l,timeout:u,shown:c}=t,{askerUserId:a,askerBotId:d}=t,{poll:f,state:p,isAnswerer:g,candidates:h}=Hg(e,t),m="";async function y(k){for(let P=0;P<r.length;P++)try{await jt(e,n,s,Te[P].name,l)}catch{}let O="";if(k.who)try{O=await Re(e,k.who,l)}catch{O=k.who}if(O)console.error(` Answered by: ${N(O)}`);try{let P=p.ownText?Cf(p.ownText,k.choice):void 0;await Bt(e,n,s,$f(o,k,O,t.lang,P),l,!0);try{await Ft(e,n,s,Ia,l),await jt(e,n,s,t.seedMarker,l)}catch{}try{if(t.explain)await jt(e,n,s,on,l)}catch{}}catch(P){console.error(` (failed to update the original message: ${P instanceof Error?P.message:String(P)})`)}}let w=Date.now()+u*1000,x=Date.now(),D=0,E=On.minMs,C=0,S;for(;;){let k=null;try{k=await f(),D=0}catch(P){if(P instanceof Dt)C=P.retryAfter*1000;else{if(D++,D>=_g)console.error(`Error: Slack requests failed ${D} times in a row: ${P instanceof Error?P.message:String(P)}`),process.exit(le);console.error(` (Slack error ${D}/${_g}, retrying: ${P instanceof Error?P.message:String(P)})`)}}S=p.unchosen;let O=p.voided;if(O){if(Yg(O,c),t.json)await un(e,t,{status:"void",answer:null,reason:O.reason,...O.supersededBy?{supersededBy:O.supersededBy}:{},notes:[],cursor:Jt(s,t.after)});process.exit(Jg)}if(k){let P=await qg(e,{channelId:n,ts:s,threadOnly:i,replyCount:p.replyCount,isAnswerer:g,askerUserId:a,askerBotId:d,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...l?{cookie:l}:{}},t.after,(v)=>v.ts===k.ts);await y(k);let L={status:"answered",answer:k.answer,how:k.how,notes:P,cursor:Jt(s,t.after,k.ts,...P.map((v)=>v.ts))};if(lc(n,s,k.answer,L.cursor),k.who)L.who=k.who;await un(e,t,L),process.exit(0)}if(p.explainPosted&&t.explainExit){if(console.error(` An explanation was requested (the question is still open). Explain in the thread, then collect with: ${jn(c,t.asBot,t.after)}`),t.json)await un(e,t,{status:"explain",answer:null,notes:[],cursor:Jt(s,t.after),explain:p.explainNow});process.exit(jk)}if(S&&!S.ambiguous){let P=S.who;try{if(P)P=await Re(e,P,l)}catch{}if(console.error(` (${N(P)} replied with something that is not a choice \u2014 not a decision. Printing the reply on stdout)`),console.error(` Choices: ${h.map((L,v)=>`${v+1}. ${N(Ne(L))}`).join(" ")}`),console.error(` ${c}`),console.error(` To wait for what comes after this reply: ${jn(c,t.asBot,S.ts)}`),Kp(n,s,S.text,Jt(s,t.after,S.ts)),t.json)await un(e,t,{status:"freetext",answer:S.text,who:S.who,notes:[],cursor:Jt(s,t.after,S.ts),explain:p.explainNow});else console.log(S.text);process.exit(Bk)}if(S&&S.ts!==m){m=S.ts;let P=S.who;try{if(P)P=await Re(e,P,l)}catch{}console.error(` (${N(P)}'s reply matches several choices; waiting until it is narrowed to one)`),console.error(` "${N(S.text)}"`)}if(Date.now()>=w)break;await Uk(Math.min(Math.max(E,C),Math.max(0,w-Date.now()))),C=0,E=If(E,Date.now()-x)}if(S){if(console.error("Error: there was a reply, but it matches several choices so it cannot be settled (the message is left in place)"),console.error(` Reply: "${N(S.text)}"`),console.error(` Choices: ${h.map((k,O)=>`${O+1}. ${N(Ne(k))}`).join(" ")}`),console.error(` ${c}`),console.error(` Reply in the thread, then collect with: ${jn(c,t.asBot,t.after)}`),t.json)await un(e,t,{status:"ambiguous",answer:null,notes:[],cursor:Jt(s,t.after),explain:p.explainNow});process.exit(Mk)}if(u===0)console.error(`No answer yet: ${c}`);else console.error(`Error: no answer within ${u}s (the message is left in place)`),console.error(` ${c}`),console.error(` To collect later: ${jn(c,t.asBot,t.after)}`);if(t.json)await un(e,t,{status:"timeout",answer:null,notes:[],cursor:Jt(s,t.after),explain:p.explainNow});process.exit(Nk)}function jn(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function qk(e,t){let{ref:n,threadTs:s}=xt(t.target,!1),o=t.cookie,r=qt(e,o),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Wt(e,t.userId,o);else i=await ye(e,n,o);let l=(await r())?.userId??"",u=await Ur(e,i,o);if(!t.asBot&&!!l&&u===l)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
516
+ `+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let c=so(je(t.question)),a=so(je(t.body??"")),d=new Set([...c.kinds,...a.kinds]);for(let G of`${c.text}
517
+ ${a.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))d.add(G[1]);let f=t.mentionToken??e,p=await ln(f,c.text,i,t.mentionCookie),g=a.text?await ln(f,a.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},h=p.text,m=g.text,y=[...p.resolved,...g.resolved],w=[...p.unresolved,...g.unresolved];Kg(w);let x=d.size>0,D=new Set(y.map((G)=>G.userId).filter((G)=>G!==l)),E=new Map(y.map((G)=>[G.userId,G.display]));for(let G of`${h}
518
518
  ${m}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)){let W=G[1];if(W===l||D.has(W))continue;D.add(W),E.set(W,await Re(f,W,t.mentionCookie))}let C;if(x)C=`anyone in ${n} (${[...d].map((G)=>`@${G}`).join(", ")})`;else{if(!D.size&&u&&u!==l)D.add(u),E.set(u,await Re(e,u,o));if(!D.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}' ...
519
519
  Or open it to the whole channel: slack ask '${t.target}' '@here ${t.question}' ...
520
- (In a 1:1 DM the other person counts automatically.)`),process.exit(le);C=[...D].map((G)=>`@${N(E.get(G)??G)} (${G})`).join(", ")}let S=t.choices.map(Be),k=S.slice(0,vt),O=S.slice(vt),P=!i.startsWith("D")||!!s,L=x?[]:await Promise.all([...D].map((G)=>Ch(f,G,t.mentionCookie))),v=Fa({flag:t.lang,readerLocales:L,content:[h,m,...k,...O]});if(!v)console.error(`Error: unsupported language "${N(t.lang??process.env.SLACK_TERM_LANG??"")}" \u2014 use one of: ${Et.join(", ")}`),process.exit(le);let j=v.lang,H=t.explain??Bk(),B=Ia(h,m,k,O,P,j,H);Ke(B,t.allowUrlAdjacent);let q="",z="?";try{let G=await ot(e,i,1,void 0,void 0,o),W=Y(G.messages).map(T).filter((he)=>he.subtype===void 0||he.subtype===null)[0];q=typeof W?.text==="string"?W.text:"",z=typeof W?.user==="string"?await Re(e,W.user,o):typeof W?.username==="string"?W.username:"?"}catch{}let R=await r(),te=await jr(e,i,o),Q=ke(i,s??"",q,B,R?.userId??"",...t.voidAfter?["reask",`${t.voidAfter.channelId}:${t.voidAfter.ts}`,t.voidAfter.reason]:[]);if(t.code!==Q){let G=await dn(e,i,n,o),W=k.length?["--- Choices (seeded as reactions) ------------",...k.map((he,we)=>` ${Te[we].glyph} ${Le(he)}`),...O.map((he,we)=>` (${we+11}) ${Le(he)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];Se(t.code,Q,["--- Last message in channel ------------------",` ${z}: ${ls(q.split(`
521
- `)[0]??"").slice(0,100)}`,...W,"--- Asking -----------------------------------",Ee(R,{asBot:t.asBot}),` \u2192 ${G}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${h}`,` Answerable by: ${C}`,` Via: ${P?"reactions or thread replies":"reactions or replies in this DM"}`,...H?[" Explain: \u2139\uFE0F pill offered \u2014 pressing it asks you to explain; it is never an answer"]:[],...t.voidAfter?[` Then void: ${N(t.voidAfter.link)} (reason: ${N(t.voidAfter.reason||"none")}) \u2014 replaced by this question`]:[],` Language: ${j} (${{flag:"--lang",env:"SLACK_TERM_LANG",readers:"answerers' Slack locale",content:"the question's text",system:"system locale",default:"default"}[v.source]}; override with --lang)`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],te)}let M=Wn("ask"),oe=await Nt(e,i,B,s,!1,o,!0,M.metadata),U=k.length?Pt:st;await pr([...k.map((G,W)=>Te[W].name),U,...H?[sn]:[]],(G)=>Ft(e,i,oe,G,o),(G,W)=>{let he=W instanceof Error?W.message:String(W);if(G===U)console.error(` (could not add marker ${G}: ${he})`);else console.error(` (could not add reaction ${G}: ${he})`)});let de="";try{de=await Pn(e,i,oe,o)}catch{}let re=de||`${i}:${oe}`;if(console.error(`\u2713 Asked: ${re}`),M.record({team:R?.team,channel:i,target:t.target,ts:oe,threadTs:s,permalink:de,text:B,asBot:t.asBot}),t.voidAfter){if(!await zg(e,t.voidAfter,t.voidAfter.reason,re,o))console.error(` \u26A0 The new question is posted, but the old one could not be voided \u2014 do it by hand: slack ask --void='${N(t.voidAfter.link)}' --superseded-by='${re}'`)}if(!t.wait){console.log(jn(re,!!t.asBot));return}let K=t.timeout??3600;console.error(` Waiting for an answer (up to ${K}s)\u2026 Ctrl-C to stop`);let ie={channelId:i,ts:oe,question:h,reactable:k,overflow:O,threadOnly:P,seedMarker:U,lang:j,audience:D,broadcast:x,askerUserId:R?.userId??"",askerBotId:R?.botId??"",timeout:K,shown:re,asBot:!!t.asBot,json:!!t.json,explain:H,explainExit:!!t.explainExit};if(s)ie.threadParentTs=s;if(o)ie.cookie=o;await Kg(e,ie)}function qg(e,t){if(console.error(`This question is void \u2014 it will never be answered. Stop waiting on it: ${N(t)}`),e.reason)console.error(` ${N(e.reason)}`);if(e.supersededBy)console.error(` New question: ${N(e.supersededBy)}`)}async function qc(e,t,n){let s=dt(t),o,r,i;if(s?.ts)o=s.channel,r=s.ts,i=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let l=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!l)return null;o=l[1],r=l[2]}return Ur(e,{channelId:o,ts:r,threadTs:i},n)}async function Ur(e,t,n){let{channelId:s,ts:o}=t,r=t.threadTs&&t.threadTs!==t.ts?t.threadTs:void 0,i;if(r){let u=T(await Pe(e,s,r,100,n));i=Y(u.messages).map(T).find((c)=>c.ts===o)}else{let u=T(await ot(e,s,1,o,void 0,n,!0));i=Y(u.messages).map(T).find((c)=>c.ts===o)}let l={channelId:s,ts:o};if(r)l.threadTs=r;if(i)l.msg=i;return l}async function Hg(e,t,n,s,o){let r=N(t),i=await qc(e,t,o);if(!i)return console.error(`\u2717 ${r}: not a permalink (or 'C\u2026:1700000000.000100')`),null;if(!i.msg)return console.error(`\u2717 ${r}: message not found`),null;let l=i.msg;if(!(!!n?.userId&&l.user===n.userId||!!n?.botId&&l.bot_id===n.botId))return console.error(`\u2717 ${r}: not a question posted by you (${Wr(n,s)})${s?"":" \u2014 if the bot posted it, use --as-bot"}`),null;let c=typeof l.text==="string"?l.text:"",a=$t(c);if(a.kind==="void")return"void";if(a.kind==="resolved")return console.error(`\u2717 ${r}: already answered (answer: ${N(a.answer.split(`
522
- `)[0]??"")}) \u2014 cannot be changed`),null;if(a.kind!=="open")return console.error(`\u2717 ${r}: cannot be read as a \`slack ask\` question \u2014 ${Ns(c)}`),null;let d={link:t,channelId:i.channelId,ts:i.ts,parsed:a,seedMarker:Ms(c)??st,msg:l};if(i.threadTs)d.threadTs=i.threadTs;return d}async function Uk(e,t,n,s){let o=(i)=>typeof i==="string"&&i!==n?.userId;if(Y(t.msg.reactions).map(T).some((i)=>Te.some((l)=>l.name===i.name)&&Y(i.users).some(o)))return!0;if(Number(t.msg.reply_count)>0){let i=T(await Pe(e,t.channelId,t.ts,100,s));if(Y(i.messages).map(T).some((l)=>Number(l.ts)>Number(t.ts)&&o(l.user)&&!l.bot_id))return!0}if(t.channelId.startsWith("D")){let i=T(await ot(e,t.channelId,30,t.ts,void 0,s,!0));if(Y(i.messages).map(T).some((l)=>Number(l.ts)>Number(t.ts)&&o(l.user)&&!l.bot_id))return!0}return!1}async function Kk(e,t){let n=await We(e,t.cookie),s=await Hg(e,t.link,n,t.asBot,t.cookie);if(s==="void")console.error(`\u2717 ${N(t.link)}: a voided question cannot be edited`),process.exit(le);if(!s)process.exit(le);let o=s.parsed,r=async(C)=>{let S=so(Be(C)),k=await cn(t.mentionToken,S.text,s.channelId,t.mentionCookie);return Wg(k.unresolved),k.text},i=t.question!==void 0?await r(t.question):o.question,l=t.body!==void 0?await r(t.body):o.body,u=[...o.reactable,...o.overflow],c=t.choices?t.choices.map(Be):u,a=JSON.stringify(c.map(Le))!==JSON.stringify(u.map(Le));if(a&&await Uk(e,s,n,t.cookie))console.error(`\u2717 This question already has responses (reactions or replies) \u2014 changing the choices would change what the pressed reactions mean.
520
+ (In a 1:1 DM the other person counts automatically.)`),process.exit(le);C=[...D].map((G)=>`@${N(E.get(G)??G)} (${G})`).join(", ")}let S=t.choices.map(je),k=S.slice(0,Pt),O=S.slice(Pt),P=!i.startsWith("D")||!!s,L=x?[]:await Promise.all([...D].map((G)=>Fh(f,G,t.mentionCookie))),v=Oa({flag:t.lang,readerLocales:L,content:[h,m,...k,...O]});if(!v)console.error(`Error: unsupported language "${N(t.lang??process.env.SLACK_TERM_LANG??"")}" \u2014 use one of: ${Et.join(", ")}`),process.exit(le);let j=v.lang,H=t.explain??Jk(),B=Pa(h,m,k,O,P,j,H);Ke(B,t.allowUrlAdjacent);let q="",z="?";try{let G=await ot(e,i,1,void 0,void 0,o),W=Y(G.messages).map(T).filter((he)=>he.subtype===void 0||he.subtype===null)[0];q=typeof W?.text==="string"?W.text:"",z=typeof W?.user==="string"?await Re(e,W.user,o):typeof W?.username==="string"?W.username:"?"}catch{}let R=await r(),te=await Wr(e,i,o),Q=we(i,s??"",q,B,R?.userId??"",...t.voidAfter?["reask",`${t.voidAfter.channelId}:${t.voidAfter.ts}`,t.voidAfter.reason]:[]);if(t.code!==Q){let G=await Ut(e,i,n,o),W=k.length?["--- Choices (seeded as reactions) ------------",...k.map((he,De)=>` ${Te[De].glyph} ${Ne(he)}`),...O.map((he,De)=>` (${De+11}) ${Ne(he)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];xe(t.code,Q,["--- Last message in channel ------------------",` ${z}: ${ls(q.split(`
521
+ `)[0]??"").slice(0,100)}`,...W,"--- Asking -----------------------------------",_e(R,{asBot:t.asBot}),` \u2192 ${G}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${h}`,` Answerable by: ${C}`,` Via: ${P?"reactions or thread replies":"reactions or replies in this DM"}`,...H?[" Explain: \u2139\uFE0F pill offered \u2014 pressing it asks you to explain; it is never an answer"]:[],...t.voidAfter?[` Then void: ${N(t.voidAfter.link)} (reason: ${N(t.voidAfter.reason||"none")}) \u2014 replaced by this question`]:[],` Language: ${j} (${{flag:"--lang",env:"SLACK_TERM_LANG",readers:"answerers' Slack locale",content:"the question's text",system:"system locale",default:"default"}[v.source]}; override with --lang)`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],te)}let M=Wn("ask"),oe=await Mt(e,i,B,s,!1,o,!0,M.metadata),U=k.length?Lt:st;await hr([...k.map((G,W)=>Te[W].name),U,...H?[on]:[]],(G)=>Ft(e,i,oe,G,o),(G,W)=>{let he=W instanceof Error?W.message:String(W);if(G===U)console.error(` (could not add marker ${G}: ${he})`);else console.error(` (could not add reaction ${G}: ${he})`)});let de="";try{de=await Pn(e,i,oe,o)}catch{}let re=de||`${i}:${oe}`;if(console.error(`\u2713 Asked: ${re}`),M.record({team:R?.team,channel:i,target:t.target,ts:oe,threadTs:s,permalink:de,text:B,asBot:t.asBot}),t.voidAfter){if(!await Xg(e,t.voidAfter,t.voidAfter.reason,re,o))console.error(` \u26A0 The new question is posted, but the old one could not be voided \u2014 do it by hand: slack ask --void='${N(t.voidAfter.link)}' --superseded-by='${re}'`)}if(!t.wait){console.log(jn(re,!!t.asBot));return}let K=t.timeout??3600;console.error(` Waiting for an answer (up to ${K}s)\u2026 Ctrl-C to stop`);let ie={channelId:i,ts:oe,question:h,reactable:k,overflow:O,threadOnly:P,seedMarker:U,lang:j,audience:D,broadcast:x,askerUserId:R?.userId??"",askerBotId:R?.botId??"",timeout:K,shown:re,asBot:!!t.asBot,json:!!t.json,explain:H,explainExit:!!t.explainExit};if(s)ie.threadParentTs=s;if(o)ie.cookie=o;await zg(e,ie)}function Yg(e,t){if(console.error(`This question is void \u2014 it will never be answered. Stop waiting on it: ${N(t)}`),e.reason)console.error(` ${N(e.reason)}`);if(e.supersededBy)console.error(` New question: ${N(e.supersededBy)}`)}async function Xc(e,t,n){let s=dt(t),o,r,i;if(s?.ts)o=s.channel,r=s.ts,i=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let l=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!l)return null;o=l[1],r=l[2]}return Kr(e,{channelId:o,ts:r,threadTs:i},n)}async function Kr(e,t,n){let{channelId:s,ts:o}=t,r=t.threadTs&&t.threadTs!==t.ts?t.threadTs:void 0,i;if(r){let u=T(await Pe(e,s,r,100,n));i=Y(u.messages).map(T).find((c)=>c.ts===o)}else{let u=T(await ot(e,s,1,o,void 0,n,!0));i=Y(u.messages).map(T).find((c)=>c.ts===o)}let l={channelId:s,ts:o};if(r)l.threadTs=r;if(i)l.msg=i;return l}async function Gg(e,t,n,s,o){let r=N(t),i=await Xc(e,t,o);if(!i)return console.error(`\u2717 ${r}: not a permalink (or 'C\u2026:1700000000.000100')`),null;if(!i.msg)return console.error(`\u2717 ${r}: message not found`),null;let l=i.msg;if(!(!!n?.userId&&l.user===n.userId||!!n?.botId&&l.bot_id===n.botId))return console.error(`\u2717 ${r}: not a question posted by you (${Jr(n,s)})${s?"":" \u2014 if the bot posted it, use --as-bot"}`),null;let c=typeof l.text==="string"?l.text:"",a=$t(c);if(a.kind==="void")return"void";if(a.kind==="resolved")return console.error(`\u2717 ${r}: already answered (answer: ${N(a.answer.split(`
522
+ `)[0]??"")}) \u2014 cannot be changed`),null;if(a.kind!=="open")return console.error(`\u2717 ${r}: cannot be read as a \`slack ask\` question \u2014 ${Ns(c)}`),null;let d={link:t,channelId:i.channelId,ts:i.ts,parsed:a,seedMarker:Ms(c)??st,msg:l};if(i.threadTs)d.threadTs=i.threadTs;return d}async function Hk(e,t,n,s){let o=(i)=>typeof i==="string"&&i!==n?.userId;if(Y(t.msg.reactions).map(T).some((i)=>Te.some((l)=>l.name===i.name)&&Y(i.users).some(o)))return!0;if(Number(t.msg.reply_count)>0){let i=T(await Pe(e,t.channelId,t.ts,100,s));if(Y(i.messages).map(T).some((l)=>Number(l.ts)>Number(t.ts)&&o(l.user)&&!l.bot_id))return!0}if(t.channelId.startsWith("D")){let i=T(await ot(e,t.channelId,30,t.ts,void 0,s,!0));if(Y(i.messages).map(T).some((l)=>Number(l.ts)>Number(t.ts)&&o(l.user)&&!l.bot_id))return!0}return!1}async function zk(e,t){let n=await Me(e,t.cookie),s=await Gg(e,t.link,n,t.asBot,t.cookie);if(s==="void")console.error(`\u2717 ${N(t.link)}: a voided question cannot be edited`),process.exit(le);if(!s)process.exit(le);let o=s.parsed,r=async(C)=>{let S=so(je(C)),k=await ln(t.mentionToken,S.text,s.channelId,t.mentionCookie);return Kg(k.unresolved),k.text},i=t.question!==void 0?await r(t.question):o.question,l=t.body!==void 0?await r(t.body):o.body,u=[...o.reactable,...o.overflow],c=t.choices?t.choices.map(je):u,a=JSON.stringify(c.map(Ne))!==JSON.stringify(u.map(Ne));if(a&&await Hk(e,s,n,t.cookie))console.error(`\u2717 This question already has responses (reactions or replies) \u2014 changing the choices would change what the pressed reactions mean.
523
523
  `+` The question and body can still be changed. To change the choices, void it and ask again:
524
524
  slack ask --void='${N(t.link)}' --reask${t.asBot?" --as-bot":""} \u2026`),process.exit(le);if(!([...`${i}
525
525
  ${l}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].some((C)=>C[1]!==n?.userId)||/<!(?:here|channel|everyone)/.test(`${i}
526
- ${l}`)||s.channelId.startsWith("D")))console.error("\u2717 The question would be addressed to nobody \u2014 keep an @mention of who can answer"),process.exit(le);let p=t.lang?Fa({flag:t.lang})?.lang??o.lang:o.lang,g=c.slice(0,vt),h=c.slice(vt),m=typeof s.msg.text==="string"?s.msg.text:"",y=Ia(i,l,g,h,o.threadOnly,p,o.explain),w=er(m);if(w.length)y=tr(y,w,p);if(Ke(y,t.allowUrlAdjacent),y===m){console.error("No changes.");return}let x=ke("ask-edit",`${s.channelId}:${s.ts}`,y,n?.userId??"");if(t.code!==x){let C=(S,k,O)=>k===O?[` ${S}: (unchanged)`]:[` ${S}:`,...k.split(`
526
+ ${l}`)||s.channelId.startsWith("D")))console.error("\u2717 The question would be addressed to nobody \u2014 keep an @mention of who can answer"),process.exit(le);let p=t.lang?Oa({flag:t.lang})?.lang??o.lang:o.lang,g=c.slice(0,Pt),h=c.slice(Pt),m=typeof s.msg.text==="string"?s.msg.text:"",y=Pa(i,l,g,h,o.threadOnly,p,o.explain),w=tr(m);if(w.length)y=nr(y,w,p);if(Ke(y,t.allowUrlAdjacent),y===m){console.error("No changes.");return}let x=we("ask-edit",`${s.channelId}:${s.ts}`,y,n?.userId??"");if(t.code!==x){let C=(S,k,O)=>k===O?[` ${S}: (unchanged)`]:[` ${S}:`,...k.split(`
527
527
  `).map((P)=>` - ${P}`),...O.split(`
528
- `).map((P)=>` + ${P}`)];Se(t.code,x,["--- Editing question --------------------------",Ee(n,{asBot:t.asBot}),` ${N(t.link)}`,...C("Question",o.question,i),...C("Body",o.body,l),...a?[" Choices (nobody has answered yet \u2014 pills are re-seeded):",...u.map((S,k)=>` - ${k+1}. ${Le(S)}`),...c.map((S,k)=>` + ${k+1}. ${Le(S)}`)]:[" Choices: (unchanged)"],...p!==o.lang?[` Language: ${o.lang} \u2192 ${p} (the instructions are rewritten)`]:[],"----------------------------------------------"])}await Mt(e,s.channelId,s.ts,y,t.cookie,!0);let D=g.length?Pt:st,E=Ms(m)??st;if(a){let C=(S)=>o.explain?[S,sn]:[S];for(let S of[...o.reactable.map((k,O)=>Te[O].name),...C(E)])try{await Bt(e,s.channelId,s.ts,S,t.cookie)}catch{}await pr([...g.map((S,k)=>Te[k].name),...C(D)],(S)=>Ft(e,s.channelId,s.ts,S,t.cookie),(S,k)=>console.error(` (could not add reaction ${S}: ${k instanceof Error?k.message:String(k)})`))}else if(E!==D)try{await Ft(e,s.channelId,s.ts,D,t.cookie),await Bt(e,s.channelId,s.ts,E,t.cookie)}catch(C){console.error(` (could not swap the marker to ${D}: ${C instanceof Error?C.message:String(C)})`)}console.error(`\u2713 Edited: ${N(t.link)}`)}async function qk(e,t){let n={kind:"ask",limit:t.limit};if(t.channel)n.channel=t.channel;let s=ic(n);if(!s)console.error(`Error: ${qs}
529
- (${At()})`),process.exit(le);let o;if(t.stale){if(o=yr(t.stale),o===void 0)console.error(`Error: --stale needs a duration like 24h / 3d (got ${N(t.stale)})`),process.exit(le)}let r=[];for(let l of s){if(o!==void 0&&l.sent_at>o)continue;let u=l.as_bot?e.bot:e.user,c=l.permalink||`${l.channel}:${l.ts}`,a="unknown",d=(l.text.split(`
530
- `)[0]??"").replace(/^:question: /,""),f;if(u)try{let g=await Ur(u,{channelId:l.channel,ts:l.ts,threadTs:l.thread_ts??void 0},l.as_bot?void 0:e.cookie);if(!g.msg)a="gone";else{let h=$t(typeof g.msg.text==="string"?g.msg.text:"");if(a=h.kind==="resolved"?"answered":h.kind==="other"?"edited":h.kind,h.kind!=="other"&&h.question)d=h.question;if(h.kind==="resolved")f=h.answer}}catch{a="unknown"}if(t.state!=="all"&&a!==t.state)continue;let p={state:a,age_h:Math.round((Date.now()-l.sent_at)/3600000),asBot:!!l.as_bot,channel:l.channel,target:l.target??l.channel,link:c,question:Le(d)};if(f!==void 0)p.answer=f;r.push(p)}if(t.json)console.log(JSON.stringify(r));else{for(let l of r)console.log(`${l.state.padEnd(8)} ${String(l.age_h).padStart(4)}h ${l.asBot?"bot ":"user"} ${N(l.target)} ${l.link}
528
+ `).map((P)=>` + ${P}`)];xe(t.code,x,["--- Editing question --------------------------",_e(n,{asBot:t.asBot}),` ${N(t.link)}`,...C("Question",o.question,i),...C("Body",o.body,l),...a?[" Choices (nobody has answered yet \u2014 pills are re-seeded):",...u.map((S,k)=>` - ${k+1}. ${Ne(S)}`),...c.map((S,k)=>` + ${k+1}. ${Ne(S)}`)]:[" Choices: (unchanged)"],...p!==o.lang?[` Language: ${o.lang} \u2192 ${p} (the instructions are rewritten)`]:[],"----------------------------------------------"])}await Bt(e,s.channelId,s.ts,y,t.cookie,!0);let D=g.length?Lt:st,E=Ms(m)??st;if(a){let C=(S)=>o.explain?[S,on]:[S];for(let S of[...o.reactable.map((k,O)=>Te[O].name),...C(E)])try{await jt(e,s.channelId,s.ts,S,t.cookie)}catch{}await hr([...g.map((S,k)=>Te[k].name),...C(D)],(S)=>Ft(e,s.channelId,s.ts,S,t.cookie),(S,k)=>console.error(` (could not add reaction ${S}: ${k instanceof Error?k.message:String(k)})`))}else if(E!==D)try{await Ft(e,s.channelId,s.ts,D,t.cookie),await jt(e,s.channelId,s.ts,E,t.cookie)}catch(C){console.error(` (could not swap the marker to ${D}: ${C instanceof Error?C.message:String(C)})`)}console.error(`\u2713 Edited: ${N(t.link)}`)}async function Yk(e,t){let n={kind:"ask",limit:t.limit};if(t.channel)n.channel=t.channel;let s=cc(n);if(!s)console.error(`Error: ${qs}
529
+ (${At()})`),process.exit(le);let o;if(t.stale){if(o=br(t.stale),o===void 0)console.error(`Error: --stale needs a duration like 24h / 3d (got ${N(t.stale)})`),process.exit(le)}let r=[];for(let l of s){if(o!==void 0&&l.sent_at>o)continue;let u=l.as_bot?e.bot:e.user,c=l.permalink||`${l.channel}:${l.ts}`,a="unknown",d=(l.text.split(`
530
+ `)[0]??"").replace(/^:question: /,""),f;if(u)try{let g=await Kr(u,{channelId:l.channel,ts:l.ts,threadTs:l.thread_ts??void 0},l.as_bot?void 0:e.cookie);if(!g.msg)a="gone";else{let h=$t(typeof g.msg.text==="string"?g.msg.text:"");if(a=h.kind==="resolved"?"answered":h.kind==="other"?"edited":h.kind,h.kind!=="other"&&h.question)d=h.question;if(h.kind==="resolved")f=h.answer}}catch{a="unknown"}if(t.state!=="all"&&a!==t.state)continue;let p={state:a,age_h:Math.round((Date.now()-l.sent_at)/3600000),asBot:!!l.as_bot,channel:l.channel,target:l.target??l.channel,link:c,question:Ne(d)};if(f!==void 0)p.answer=f;r.push(p)}if(t.json)console.log(JSON.stringify(r));else{for(let l of r)console.log(`${l.state.padEnd(8)} ${String(l.age_h).padStart(4)}h ${l.asBot?"bot ":"user"} ${N(l.target)} ${l.link}
531
531
  ${N(l.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((l)=>l.state==="open");if(t.stale&&i.length)for(let l of[!1,!0]){let u=i.filter((c)=>c.asBot===l);if(!u.length)continue;console.error(`To void them (${u.length}, ${l?"bot":"user"}):
532
- slack ask ${u.map((c)=>`--void='${c.link}'`).join(" ")} --reason 'stale'${l?" --as-bot":""}`)}}async function Hk(e,t){let n=Jp(t.sinceMs);if(!n)console.error(`Error: ${qs}
533
- (${At()})`),process.exit(le);let s=t.channel?n.filter((a)=>a.channel===t.channel||a.target===t.channel):n,o=[],r={unanswered:0,ambiguous:0,resolved:0,void:0,explain:0},i=[],l=[],u=e.user?(await We(e.user,e.cookie))?.team??"":e.bot?(await We(e.bot))?.team??"":"",c=new Map;for(let a of s){if(a.team&&u&&a.team!==u){c.set(a.team,(c.get(a.team)??0)+1);continue}let d=a.permalink||`${a.channel}:${a.ts}`,f=!!a.as_bot,p=f?e.bot:e.user;if(!p){l.push(`${d}: ${f?"asked with --as-bot, but there is no bot token":"no user token"}`);continue}let g=f?void 0:e.cookie,h=a.delivered_cursor??void 0;try{let m={channelId:a.channel,ts:a.ts,threadTs:a.thread_ts??void 0},y=await Ur(p,m,g);if(!y.msg){l.push(`${d}: message not found (deleted?)`);continue}let w=await Yg(p,{channelId:a.channel,ts:a.ts,msg:y.msg},g),x=w.parsed;if(x.kind==="resolved"){r.resolved++;continue}if(x.kind==="void"){r.void++;continue}if(x.kind==="other"){l.push(`${d}: cannot be read as a \`slack ask\` question \u2014 ${Ns(w.text)}`);continue}if(!w.audience.size&&!w.broadcast){l.push(`${d}: the question is addressed to nobody`);continue}let D=Gg(w,x,m,{timeout:0,link:d,asBot:f,json:!1,cookie:g,after:h}),E=Ug(p,D,!0),C=await E.poll(),S=E.state.unchosen;if(E.state.voided){r.void++;continue}let k=jn(d,f,h);if(E.state.explainNow.length)r.explain++,i.push(`${d}: \u2139\uFE0F an explanation was requested (${E.state.explainNow.map((P)=>`<@${P}>`).join(" ")}) \u2014 explain in the thread`);let O={row:a,link:d,question:x.question,collect:k,alive:Up(a)};if(C)o.push({...O,answer:C.answer,how:C.how,freeText:!1});else if(S&&!S.ambiguous&&S.text!==a.delivered_answer)o.push({...O,answer:S.text,how:"reply (not a choice)",freeText:!0});else if(S?.ambiguous)r.ambiguous++;else r.unanswered++}catch(m){l.push(`${d}: ${m instanceof Error?m.message:String(m)}`)}}if(t.json)for(let a of o){let d=a.row;console.log(JSON.stringify({id:d.id,link:a.link,channel:d.channel,ts:d.ts,asked_at:d.sent_at,question:a.question,answer:a.answer,how:a.how,free_text:a.freeText,sender:{session_id:d.session_id??null,cli:d.cli??null,agent_pid:d.agent_pid??null,pid:d.pid,alive:a.alive,cwd:d.cwd,git_branch:d.git_branch??null,host:d.host??null},delivered_at:d.delivered_at??null,collect:a.collect}))}else{let a=new Map;for(let d of o){let f=d.row.session_id?`session ${d.row.session_id}`:`pid ${d.row.agent_pid??d.row.pid}`;a.set(f,[...a.get(f)??[],d])}for(let[d,f]of a){let p=f[0].row;console.log(`${N(d)} ${N(p.cli??"?")} pid ${p.agent_pid??p.pid} ${f[0].alive?"(alive)":"(gone)"}${p.git_branch?` branch=${N(p.git_branch)}`:""} cwd=${N(p.cwd)}`);for(let g of f)console.log(` ${N(g.link)} (${Bn(g.row.sent_at/1000)})`),console.log(` Q: ${N(Le(g.question))}`),console.log(` A: ${N(Le(g.answer))} \u2014 ${N(g.how)}${g.freeText?" \u2014 not a decision":""}`),console.log(` collect: ${N(g.collect)}`)}}for(let a of l)console.error(` (${N(a)})`);for(let a of i)console.error(` (${N(a)})`);for(let[a,d]of c)console.error(` (${d} question(s) belong to another workspace "${N(a)}" \u2014 check with slack -w <name> ask --pending)`);console.error(`${o.length} answered but not collected, ${r.unanswered} unanswered`+(r.ambiguous?`, ${r.ambiguous} with a reply matching several choices (unsettled)`:"")+(r.resolved?`, ${r.resolved} \u2705 already collected`:"")+(r.void?`, ${r.void} voided`:"")+(r.explain?`, ${r.explain} with an \u2139\uFE0F explain request`:"")+` \u2014 checked ${s.length} uncollected question(s) (log: ${At()})`)}async function zg(e,t,n,s,o){let r=N(t.link);try{let i=Ef(t.parsed.question,n,t.parsed.lang,t.parsed.body||void 0,s);await Mt(e,t.channelId,t.ts,i,o,!0)}catch(i){return console.error(`\u2717 ${r}: failed to rewrite: ${i instanceof Error?i.message:String(i)}`),!1}for(let i of[...t.parsed.reactable.map((l,u)=>Te[u].name),t.seedMarker,...t.parsed.explain?[sn]:[]])try{await Bt(e,t.channelId,t.ts,i,o)}catch{}try{await Ft(e,t.channelId,t.ts,Ra,o)}catch(i){console.error(` (${r}: could not add the \uD83D\uDEAB reaction: ${i instanceof Error?i.message:String(i)})`)}return console.error(`\u2713 Voided: ${r}`),!0}async function zk(e,t){let n=await We(e,t.cookie);if(t.supersededBy){let l=N(t.supersededBy),u=!1;try{let c=await qc(e,t.supersededBy,t.cookie);if(u=!!c?.msg,!c)console.error(`Error: --superseded-by must be a message permalink (or 'C\u2026:1700000000.000100'): ${l}`),process.exit(le)}catch(c){console.error(`Error: cannot check --superseded-by: ${l} (${c instanceof Error?c.message:String(c)})`),process.exit(le)}if(!u)console.error(`Error: --superseded-by message not found: ${l}`),process.exit(le)}let s=[],o=0;for(let l of t.links){let u=N(l),c=await qc(e,l,t.cookie);if(!c){console.error(`\u2717 ${u}: not a permalink (or 'C\u2026:1700000000.000100')`),o++;continue}if(!c.msg){console.error(`\u2717 ${u}: message not found`),o++;continue}let a=c.msg;if(!(!!n?.userId&&a.user===n.userId||!!n?.botId&&a.bot_id===n.botId)){console.error(`\u2717 ${u}: not a question posted by you (${Wr(n,t.asBot)}), so it cannot be voided${t.asBot?"":" \u2014 if the bot posted it, use --as-bot"}`),o++;continue}let f=typeof a.text==="string"?a.text:"",p=$t(f),g=!1;if(p.kind==="void"){console.error(`- ${u}: already voided (nothing to do)`);continue}if(p.kind==="resolved"){console.error(`\u2717 ${u}: an answered question cannot be voided (answer: ${N(p.answer.split(`
534
- `)[0]??"")})`),o++;continue}if(p.kind!=="open"){let y=$f(f);if(!y){console.error(`\u2717 ${u}: cannot be read as a \`slack ask\` question \u2014 ${Ns(f)}`),o++;continue}let w=Y(a.reactions).map(T).filter((x)=>Y(x.users).includes(n?.userId??"\x00")).map((x)=>Te.findIndex((D)=>D.name===x.name)).filter((x)=>x>=0);p={kind:"open",question:y.question,body:y.body,reactable:Array.from({length:w.length?Math.max(...w)+1:0},()=>""),overflow:[],threadOnly:!0,lang:Ta(f)??"ja",explain:Y(a.reactions).map(T).some((x)=>x.name===sn&&Y(x.users).includes(n?.userId??"\x00"))},g=!0}let h=g?Y(a.reactions).map(T).some((y)=>y.name===Pt&&Y(y.users).includes(n?.userId??"\x00"))?Pt:st:Ms(f)??st,m=Y(a.reactions).map(T).filter((y)=>typeof y.name==="string"&&Te.some((w)=>w.name===y.name)).filter((y)=>Y(y.users).some((w)=>w!==n?.userId)).map((y)=>`:${String(y.name)}:`);s.push({link:l,channelId:c.channelId,ts:c.ts,text:f,parsed:p,seedMarker:h,pressed:m,...g?{unreadable:g}:{}})}if(!s.length)console.error(o?"No questions can be voided.":"Nothing to do."),process.exit(o?le:0);let r=ke("ask-void",...s.map((l)=>`${l.channelId}:${l.ts}`),t.reason,t.supersededBy??"",n?.userId??"");if(t.code!==r)Se(t.code,r,["--- Void -----------------------------------------",Ee(n,{asBot:t.asBot}),` Reason: ${t.reason?N(t.reason):"(none)"}`,...t.supersededBy?[` Replaced: ${N(t.supersededBy)}`]:[],` ${s.length} question(s):`,...s.map((l)=>` \u2022 ${N(l.link)}
532
+ slack ask ${u.map((c)=>`--void='${c.link}'`).join(" ")} --reason 'stale'${l?" --as-bot":""}`)}}async function Gk(e,t){let n=qp(t.sinceMs);if(!n)console.error(`Error: ${qs}
533
+ (${At()})`),process.exit(le);let s=t.channel?n.filter((a)=>a.channel===t.channel||a.target===t.channel):n,o=[],r={unanswered:0,ambiguous:0,resolved:0,void:0,explain:0},i=[],l=[],u=e.user?(await Me(e.user,e.cookie))?.team??"":e.bot?(await Me(e.bot))?.team??"":"",c=new Map;for(let a of s){if(a.team&&u&&a.team!==u){c.set(a.team,(c.get(a.team)??0)+1);continue}let d=a.permalink||`${a.channel}:${a.ts}`,f=!!a.as_bot,p=f?e.bot:e.user;if(!p){l.push(`${d}: ${f?"asked with --as-bot, but there is no bot token":"no user token"}`);continue}let g=f?void 0:e.cookie,h=a.delivered_cursor??void 0;try{let m={channelId:a.channel,ts:a.ts,threadTs:a.thread_ts??void 0},y=await Kr(p,m,g);if(!y.msg){l.push(`${d}: message not found (deleted?)`);continue}let w=await Vg(p,{channelId:a.channel,ts:a.ts,msg:y.msg},g),x=w.parsed;if(x.kind==="resolved"){r.resolved++;continue}if(x.kind==="void"){r.void++;continue}if(x.kind==="other"){l.push(`${d}: cannot be read as a \`slack ask\` question \u2014 ${Ns(w.text)}`);continue}if(!w.audience.size&&!w.broadcast){l.push(`${d}: the question is addressed to nobody`);continue}let D=Zg(w,x,m,{timeout:0,link:d,asBot:f,json:!1,cookie:g,after:h}),E=Hg(p,D,!0),C=await E.poll(),S=E.state.unchosen;if(E.state.voided){r.void++;continue}let k=jn(d,f,h);if(E.state.explainNow.length)r.explain++,i.push(`${d}: \u2139\uFE0F an explanation was requested (${E.state.explainNow.map((P)=>`<@${P}>`).join(" ")}) \u2014 explain in the thread`);let O={row:a,link:d,question:x.question,collect:k,alive:Hp(a)};if(C)o.push({...O,answer:C.answer,how:C.how,freeText:!1});else if(S&&!S.ambiguous&&S.text!==a.delivered_answer)o.push({...O,answer:S.text,how:"reply (not a choice)",freeText:!0});else if(S?.ambiguous)r.ambiguous++;else r.unanswered++}catch(m){l.push(`${d}: ${m instanceof Error?m.message:String(m)}`)}}if(t.json)for(let a of o){let d=a.row;console.log(JSON.stringify({id:d.id,link:a.link,channel:d.channel,ts:d.ts,asked_at:d.sent_at,question:a.question,answer:a.answer,how:a.how,free_text:a.freeText,sender:{session_id:d.session_id??null,cli:d.cli??null,agent_pid:d.agent_pid??null,pid:d.pid,alive:a.alive,cwd:d.cwd,git_branch:d.git_branch??null,host:d.host??null},delivered_at:d.delivered_at??null,collect:a.collect}))}else{let a=new Map;for(let d of o){let f=d.row.session_id?`session ${d.row.session_id}`:`pid ${d.row.agent_pid??d.row.pid}`;a.set(f,[...a.get(f)??[],d])}for(let[d,f]of a){let p=f[0].row;console.log(`${N(d)} ${N(p.cli??"?")} pid ${p.agent_pid??p.pid} ${f[0].alive?"(alive)":"(gone)"}${p.git_branch?` branch=${N(p.git_branch)}`:""} cwd=${N(p.cwd)}`);for(let g of f)console.log(` ${N(g.link)} (${Bn(g.row.sent_at/1000)})`),console.log(` Q: ${N(Ne(g.question))}`),console.log(` A: ${N(Ne(g.answer))} \u2014 ${N(g.how)}${g.freeText?" \u2014 not a decision":""}`),console.log(` collect: ${N(g.collect)}`)}}for(let a of l)console.error(` (${N(a)})`);for(let a of i)console.error(` (${N(a)})`);for(let[a,d]of c)console.error(` (${d} question(s) belong to another workspace "${N(a)}" \u2014 check with slack -w <name> ask --pending)`);console.error(`${o.length} answered but not collected, ${r.unanswered} unanswered`+(r.ambiguous?`, ${r.ambiguous} with a reply matching several choices (unsettled)`:"")+(r.resolved?`, ${r.resolved} \u2705 already collected`:"")+(r.void?`, ${r.void} voided`:"")+(r.explain?`, ${r.explain} with an \u2139\uFE0F explain request`:"")+` \u2014 checked ${s.length} uncollected question(s) (log: ${At()})`)}async function Xg(e,t,n,s,o){let r=N(t.link);try{let i=Af(t.parsed.question,n,t.parsed.lang,t.parsed.body||void 0,s);await Bt(e,t.channelId,t.ts,i,o,!0)}catch(i){return console.error(`\u2717 ${r}: failed to rewrite: ${i instanceof Error?i.message:String(i)}`),!1}for(let i of[...t.parsed.reactable.map((l,u)=>Te[u].name),t.seedMarker,...t.parsed.explain?[on]:[]])try{await jt(e,t.channelId,t.ts,i,o)}catch{}try{await Ft(e,t.channelId,t.ts,va,o)}catch(i){console.error(` (${r}: could not add the \uD83D\uDEAB reaction: ${i instanceof Error?i.message:String(i)})`)}return console.error(`\u2713 Voided: ${r}`),!0}async function Xk(e,t){let n=await Me(e,t.cookie);if(t.supersededBy){let l=N(t.supersededBy),u=!1;try{let c=await Xc(e,t.supersededBy,t.cookie);if(u=!!c?.msg,!c)console.error(`Error: --superseded-by must be a message permalink (or 'C\u2026:1700000000.000100'): ${l}`),process.exit(le)}catch(c){console.error(`Error: cannot check --superseded-by: ${l} (${c instanceof Error?c.message:String(c)})`),process.exit(le)}if(!u)console.error(`Error: --superseded-by message not found: ${l}`),process.exit(le)}let s=[],o=0;for(let l of t.links){let u=N(l),c=await Xc(e,l,t.cookie);if(!c){console.error(`\u2717 ${u}: not a permalink (or 'C\u2026:1700000000.000100')`),o++;continue}if(!c.msg){console.error(`\u2717 ${u}: message not found`),o++;continue}let a=c.msg;if(!(!!n?.userId&&a.user===n.userId||!!n?.botId&&a.bot_id===n.botId)){console.error(`\u2717 ${u}: not a question posted by you (${Jr(n,t.asBot)}), so it cannot be voided${t.asBot?"":" \u2014 if the bot posted it, use --as-bot"}`),o++;continue}let f=typeof a.text==="string"?a.text:"",p=$t(f),g=!1;if(p.kind==="void"){console.error(`- ${u}: already voided (nothing to do)`);continue}if(p.kind==="resolved"){console.error(`\u2717 ${u}: an answered question cannot be voided (answer: ${N(p.answer.split(`
534
+ `)[0]??"")})`),o++;continue}if(p.kind!=="open"){let y=Ff(f);if(!y){console.error(`\u2717 ${u}: cannot be read as a \`slack ask\` question \u2014 ${Ns(f)}`),o++;continue}let w=Y(a.reactions).map(T).filter((x)=>Y(x.users).includes(n?.userId??"\x00")).map((x)=>Te.findIndex((D)=>D.name===x.name)).filter((x)=>x>=0);p={kind:"open",question:y.question,body:y.body,reactable:Array.from({length:w.length?Math.max(...w)+1:0},()=>""),overflow:[],threadOnly:!0,lang:Ra(f)??"ja",explain:Y(a.reactions).map(T).some((x)=>x.name===on&&Y(x.users).includes(n?.userId??"\x00"))},g=!0}let h=g?Y(a.reactions).map(T).some((y)=>y.name===Lt&&Y(y.users).includes(n?.userId??"\x00"))?Lt:st:Ms(f)??st,m=Y(a.reactions).map(T).filter((y)=>typeof y.name==="string"&&Te.some((w)=>w.name===y.name)).filter((y)=>Y(y.users).some((w)=>w!==n?.userId)).map((y)=>`:${String(y.name)}:`);s.push({link:l,channelId:c.channelId,ts:c.ts,text:f,parsed:p,seedMarker:h,pressed:m,...g?{unreadable:g}:{}})}if(!s.length)console.error(o?"No questions can be voided.":"Nothing to do."),process.exit(o?le:0);let r=we("ask-void",...s.map((l)=>`${l.channelId}:${l.ts}`),t.reason,t.supersededBy??"",n?.userId??"");if(t.code!==r)xe(t.code,r,["--- Void -----------------------------------------",_e(n,{asBot:t.asBot}),` Reason: ${t.reason?N(t.reason):"(none)"}`,...t.supersededBy?[` Replaced: ${N(t.supersededBy)}`]:[],` ${s.length} question(s):`,...s.map((l)=>` \u2022 ${N(l.link)}
535
535
  ${N(l.parsed.question.split(`
536
536
  `)[0]??"").slice(0,100)}`+(l.pressed.length?`
537
537
  (already pressed: ${l.pressed.join(" ")} \u2014 left in place, never collected)`:"")+(l.unreadable?`
538
- \u26A0 its layout no longer reads as an ask (edited by hand?) \u2014 voided from a best-effort read: question and the rest of the text kept as they are`:""))," Each becomes \uD83D\uDEAB (body kept, options and instructions removed); our pills and marker (\u2795, or \u2753) come off; a \uD83D\uDEAB reaction is added.",...o?[` (${o} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let i=0;for(let l of s)if(!await zg(e,l,t.reason,t.supersededBy,t.cookie))i++;process.exit(i||o?le:0)}async function Yk(e,t){let n=dt(t.link),s,o,r;if(n?.ts)s=n.channel,o=n.ts,r=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let h=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!h)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
539
- `+` Got: ${N(t.link)}`),process.exit(le);s=h[1],o=h[2]}let i=await Ur(e,{channelId:s,ts:o,threadTs:r},t.cookie);if(!i.msg)console.error(`Error: message not found: ${N(t.link)}`),process.exit(le);let l=i.msg,u=await Yg(e,{channelId:s,ts:o,msg:l},t.cookie),{text:c,parsed:a,audience:d,broadcast:f,askerUserId:p,askerBotId:g}=u;if(a.kind==="other")console.error(`Error: this cannot be read as a \`slack ask\` question.
538
+ \u26A0 its layout no longer reads as an ask (edited by hand?) \u2014 voided from a best-effort read: question and the rest of the text kept as they are`:""))," Each becomes \uD83D\uDEAB (body kept, options and instructions removed); our pills and marker (\u2795, or \u2753) come off; a \uD83D\uDEAB reaction is added.",...o?[` (${o} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let i=0;for(let l of s)if(!await Xg(e,l,t.reason,t.supersededBy,t.cookie))i++;process.exit(i||o?le:0)}async function Vk(e,t){let n=dt(t.link),s,o,r;if(n?.ts)s=n.channel,o=n.ts,r=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let h=t.link.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!h)console.error(`Error: --waitFor needs the permalink of a question (or 'C\u2026:1700000000.000100').
539
+ `+` Got: ${N(t.link)}`),process.exit(le);s=h[1],o=h[2]}let i=await Kr(e,{channelId:s,ts:o,threadTs:r},t.cookie);if(!i.msg)console.error(`Error: message not found: ${N(t.link)}`),process.exit(le);let l=i.msg,u=await Vg(e,{channelId:s,ts:o,msg:l},t.cookie),{text:c,parsed:a,audience:d,broadcast:f,askerUserId:p,askerBotId:g}=u;if(a.kind==="other")console.error(`Error: this cannot be read as a \`slack ask\` question.
540
540
  Reason: ${Ns(c)}
541
541
  ${N(t.link)}
542
- (the pressed reactions are still there: check with slack read '${N(t.link)}')`),process.exit(le);if(a.kind==="void"){if(qg(a,t.link),t.json)await ln(e,{json:!0,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"void",answer:null,reason:a.reason,...a.supersededBy?{supersededBy:a.supersededBy}:{},notes:[],cursor:Jt(o,t.after)});process.exit(Bg)}if(a.kind==="resolved"){console.error(`\u2713 Answered: ${N(a.question)}`);let h=typeof T(l.edited).ts==="string"?String(T(l.edited).ts):void 0,m=Af(c),y=!1,w=(C)=>{if(y||!m.byReply)return!1;if(h&&Number(C.ts)>Number(h))return!1;let S=typeof C.text==="string"?C.text.trim():"",k=S===a.answer||m.n!==void 0&&(new RegExp(`^[(\uFF08]?${m.n}(?![0-9])`).test(S)||Ff(S,a.answer,m.n));if(k)y=!0;return k},x=t.after,D=[];if(d.size||f){let C=(S)=>typeof S==="string"&&!!S&&S!==p&&(f||d.has(S));D=await Jg(e,{channelId:s,ts:o,threadOnly:!!r||!s.startsWith("D"),replyCount:Number(l.reply_count)||0,isAnswerer:C,askerUserId:p,askerBotId:g,...r?{threadParentTs:r}:{},...t.cookie?{cookie:t.cookie}:{}},x,w)}let E=Jt(o,x,...D.map((C)=>C.ts));await ln(e,{json:t.json,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"answered",answer:a.answer,notes:D,cursor:E}),ac(s,o,a.answer,E);return}if(!d.size&&!f)console.error(`Error: this question is addressed to nobody, so valid answerers cannot be determined: ${N(t.link)}`),process.exit(le);if(t.timeout>0)console.error(` Waiting for an answer (up to ${t.timeout}s)\u2026 Ctrl-C to stop`);await Kg(e,Gg(u,a,{channelId:s,ts:o,threadTs:r},t))}async function Yg(e,t,n){let{msg:s}=t,o=typeof s.text==="string"?s.text:"",r=$t(o),i=typeof s.user==="string"?s.user:"",l=typeof s.bot_id==="string"?s.bot_id:"",u=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(o),c=new Set;for(let a of o.matchAll(/<@([UW][A-Z0-9]+)>/g))if(a[1]!==i)c.add(a[1]);if(r.kind!=="other"&&!c.size&&!u){let a=await Jr(e,t.channelId,n);if(a&&a!==i)c.add(a)}return{text:o,parsed:r,audience:c,broadcast:u,askerUserId:i,askerBotId:l}}function Gg(e,t,n,s){let o={channelId:n.channelId,ts:n.ts,question:t.question,reactable:t.reactable,overflow:t.overflow,threadOnly:t.threadOnly,seedMarker:Ms(e.text)??st,lang:t.lang,audience:e.audience,broadcast:e.broadcast,askerUserId:e.askerUserId,askerBotId:e.askerBotId,timeout:s.timeout,shown:s.link,asBot:s.asBot,json:s.json,explain:t.explain,explainExit:!!s.explainExit};if(n.threadTs)o.threadParentTs=n.threadTs;if(s.cookie)o.cookie=s.cookie;if(s.after)o.after=s.after;return o}var pt=3;function Gk(e){return`slack poll --results='${e}'`}async function Xk(e,t){let{ref:n,threadTs:s}=xt(t.target,!1),o=t.cookie,r=Kt(e,o),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await jt(e,t.userId,o);else i=await be(e,n,o);let l=(await r())?.userId??"",u=await Jr(e,i,o);if(!t.asBot&&!!l&&u===l)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
543
- `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let c=so(Be(t.question)),a=so(Be(t.body??"")),d=t.mentionToken??e,f=await cn(d,c.text,i,t.mentionCookie),p=a.text?await cn(d,a.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},g=f.text,h=p.text;for(let j of _r([...f.unresolved,...p.unresolved]))console.error(`\u26A0 ${N(j)}`);let m=t.choices.map(Be),y=!!t.multi,w=t.until??"",x=_p(g,h,m,{multi:y,deadline:w});Ke(x,t.allowUrlAdjacent);let D="",E="?";try{let j=await ot(e,i,1,void 0,void 0,o),H=Y(j.messages).map(T).filter((B)=>B.subtype===void 0||B.subtype===null)[0];D=typeof H?.text==="string"?H.text:"",E=typeof H?.user==="string"?await Re(e,H.user,o):typeof H?.username==="string"?H.username:"?"}catch{}let C=await r(),S=await jr(e,i,o),k=ke(i,s??"",D,x,C?.userId??"");if(t.code!==k){let j=await dn(e,i,n,o);Se(t.code,k,["--- Last message in channel ------------------",` ${E}: ${ls(D.split(`
544
- `)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...m.map((H,B)=>` ${wt[B].glyph} ${Js(H)}`),"--- Posting ----------------------------------",Ee(C,{asBot:t.asBot}),` \u2192 ${j}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${g}`,` Rule: ${y?"any number of votes per person (--multi)":"one vote per person"}${w?` \u2014 closes ${w}`:""}`," Note: your own votes are not counted (the pills are seeds you added, so they can't be told apart)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],S)}let O=Wn("poll"),P=await Nt(e,i,x,s,!1,o,!0,O.metadata);await pr([Us,...m.map((j,H)=>wt[H].name)],(j)=>Ft(e,i,P,j,o),(j,H)=>{let B=H instanceof Error?H.message:String(H);if(j===Us)console.error(` (could not add marker ${j}: ${B})`);else console.error(` (could not add reaction ${j}: ${B})`)});let L="";try{L=await Pn(e,i,P,o)}catch{}let v=L||`${i}:${P}`;console.error(`\u2713 Posted: ${v}`),O.record({team:C?.team,channel:i,target:t.target,ts:P,threadTs:s,permalink:L,text:x,asBot:t.asBot}),console.log(Gk(v)),console.error(` To close: slack poll --close='${v}'${t.asBot?" --as-bot":""}`)}async function Vk(e,t,n){let s=dt(t),o,r,i;if(s?.ts)o=s.channel,r=s.ts,i=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let u=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!u)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
545
- `+` Got: ${N(t)}`),process.exit(pt);o=u[1],r=u[2]}let l;if(i){let u=T(await Pe(e,o,i,100,n));l=Y(u.messages).map(T).find((c)=>c.ts===r)}else{let u=T(await ot(e,o,1,r,void 0,n,!0));l=Y(u.messages).map(T).find((c)=>c.ts===r)}if(!l)console.error(`Error: message not found: ${N(t)}`),process.exit(pt);return{channelId:o,ts:r,msg:l}}function Sg(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,s)=>`${wt[s].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function Zk(e,t){let{channelId:n,ts:s,msg:o}=await Vk(e,t.link,t.cookie),r=typeof o.text==="string"?o.text:"",i=Ks(r);if(i.kind==="other")console.error(`Error: this is not a \`slack poll\` poll (don't know how to count its votes).
546
- ${N(t.link)}`),process.exit(pt);if(i.kind==="closed"){console.error(`\u2713 Poll closed: ${N(i.question)}`);for(let p of Sg(i.tallies))console.log(p);return}let l=new Set;if(typeof o.user==="string"&&o.user)l.add(o.user);let u=await fh(e,n,s,t.cookie),c=$p(i.choices,u,l,i.multi);console.error(`${N(i.question)}${i.deadline?` (closes ${i.deadline})`:""}`);for(let p of Sg(c.tallies))console.log(p);let a=c.tallies.reduce((p,g)=>p+g.count,0);if(console.error(` ${a} vote(s) total${i.multi?" (multiple choice)":""}`),t.names)for(let p=0;p<c.voters.length;p++){if(!c.voters[p].length)continue;let g=await Promise.all(c.voters[p].map((h)=>Re(e,h,t.cookie)));console.error(` ${wt[p].glyph} ${g.map((h)=>`@${N(h)}`).join(", ")}`)}let d=i.multi?[]:c.ambiguous,f=tr(r,d);if(f!==r&&!t.noNotify)try{await Mt(t.writeToken??e,n,s,f,t.writeToken?t.writeCookie:t.cookie,!0)}catch(p){console.error(` (could not add the notice to the poll text: ${p instanceof Error?p.message:String(p)})
547
- `+" Only the poster can rewrite a message \u2014 if the bot posted the poll, add --as-bot.")}if(c.ambiguous.length){let p=await Promise.all(c.ambiguous.map((g)=>Re(e,g,t.cookie)));console.error(`\u26A0 One vote per person, but some people pressed several (invalid votes): ${p.map((g)=>`@${N(g)}`).join(", ")}`)}if(!t.close)return;await Mt(t.writeToken??e,n,s,Ep(i.question,c.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await Ft(t.writeToken??e,n,s,ec,t.writeToken?t.writeCookie:t.cookie),await Bt(t.writeToken??e,n,s,Us,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 Closed the poll: ${N(t.link)}`)}async function Qk(e){let t=await Po(e);for(let n of Lo(t,!1))console.log(n);if(!t.ok)process.exit(1)}function Tr(){let e=Ne();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
548
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function _g(e,t,n,s){let o=await Wt(n,e,s);return jt(t,o)}function Eg(e){try{return Xg(e)}catch{console.error(`Error: cannot parse --due "${e}" \u2014 use an ISO datetime (2026-11-01T18:00) or a Unix ts.`),process.exit(2)}}function Xg(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 Vg(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 ex(e,t){Ke(t.message,t.allowUrlAdjacent);let n=Kt(e,t.cookie),{ref:s,threadTs:o}=xt(t.target),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await jt(e,t.userId,t.cookie);else r=await be(e,s,t.cookie);let i=Xg(t.at),l=new Date(i*1000).toISOString(),u=await n();if(!t.asBot&&await Vc(e,r,u?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
549
- `+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let c=ke(r,t.message,String(i),u?.userId??""),a=t.targetOverride?` [${t.targetOverride} \u2192 ${r}]`:"";if(t.code!==c){let f=await jr(e,r,t.cookie);Se(t.code,c,["--- Scheduling message -----------------------",Ee(u,{asBot:t.asBot,pad:9}),` To: ${s}${o?` (thread ${o})`:""}${a}`,` At: ${Vg(i)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(i*1000))}let d=await ah(e,r,t.message,i,o,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${l})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
542
+ (the pressed reactions are still there: check with slack read '${N(t.link)}')`),process.exit(le);if(a.kind==="void"){if(Yg(a,t.link),t.json)await un(e,{json:!0,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"void",answer:null,reason:a.reason,...a.supersededBy?{supersededBy:a.supersededBy}:{},notes:[],cursor:Jt(o,t.after)});process.exit(Jg)}if(a.kind==="resolved"){console.error(`\u2713 Answered: ${N(a.question)}`);let h=typeof T(l.edited).ts==="string"?String(T(l.edited).ts):void 0,m=Of(c),y=!1,w=(C)=>{if(y||!m.byReply)return!1;if(h&&Number(C.ts)>Number(h))return!1;let S=typeof C.text==="string"?C.text.trim():"",k=S===a.answer||m.n!==void 0&&(new RegExp(`^[(\uFF08]?${m.n}(?![0-9])`).test(S)||Rf(S,a.answer,m.n));if(k)y=!0;return k},x=t.after,D=[];if(d.size||f){let C=(S)=>typeof S==="string"&&!!S&&S!==p&&(f||d.has(S));D=await qg(e,{channelId:s,ts:o,threadOnly:!!r||!s.startsWith("D"),replyCount:Number(l.reply_count)||0,isAnswerer:C,askerUserId:p,askerBotId:g,...r?{threadParentTs:r}:{},...t.cookie?{cookie:t.cookie}:{}},x,w)}let E=Jt(o,x,...D.map((C)=>C.ts));await un(e,{json:t.json,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"answered",answer:a.answer,notes:D,cursor:E}),lc(s,o,a.answer,E);return}if(!d.size&&!f)console.error(`Error: this question is addressed to nobody, so valid answerers cannot be determined: ${N(t.link)}`),process.exit(le);if(t.timeout>0)console.error(` Waiting for an answer (up to ${t.timeout}s)\u2026 Ctrl-C to stop`);await zg(e,Zg(u,a,{channelId:s,ts:o,threadTs:r},t))}async function Vg(e,t,n){let{msg:s}=t,o=typeof s.text==="string"?s.text:"",r=$t(o),i=typeof s.user==="string"?s.user:"",l=typeof s.bot_id==="string"?s.bot_id:"",u=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(o),c=new Set;for(let a of o.matchAll(/<@([UW][A-Z0-9]+)>/g))if(a[1]!==i)c.add(a[1]);if(r.kind!=="other"&&!c.size&&!u){let a=await Ur(e,t.channelId,n);if(a&&a!==i)c.add(a)}return{text:o,parsed:r,audience:c,broadcast:u,askerUserId:i,askerBotId:l}}function Zg(e,t,n,s){let o={channelId:n.channelId,ts:n.ts,question:t.question,reactable:t.reactable,overflow:t.overflow,threadOnly:t.threadOnly,seedMarker:Ms(e.text)??st,lang:t.lang,audience:e.audience,broadcast:e.broadcast,askerUserId:e.askerUserId,askerBotId:e.askerBotId,timeout:s.timeout,shown:s.link,asBot:s.asBot,json:s.json,explain:t.explain,explainExit:!!s.explainExit};if(n.threadTs)o.threadParentTs=n.threadTs;if(s.cookie)o.cookie=s.cookie;if(s.after)o.after=s.after;return o}var pt=3;function Zk(e){return`slack poll --results='${e}'`}async function Qk(e,t){let{ref:n,threadTs:s}=xt(t.target,!1),o=t.cookie,r=qt(e,o),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Wt(e,t.userId,o);else i=await ye(e,n,o);let l=(await r())?.userId??"",u=await Ur(e,i,o);if(!t.asBot&&!!l&&u===l)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
543
+ `+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let c=so(je(t.question)),a=so(je(t.body??"")),d=t.mentionToken??e,f=await ln(d,c.text,i,t.mentionCookie),p=a.text?await ln(d,a.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},g=f.text,h=p.text;for(let j of Er([...f.unresolved,...p.unresolved]))console.error(`\u26A0 ${N(j)}`);let m=t.choices.map(je),y=!!t.multi,w=t.until??"",x=Cp(g,h,m,{multi:y,deadline:w});Ke(x,t.allowUrlAdjacent);let D="",E="?";try{let j=await ot(e,i,1,void 0,void 0,o),H=Y(j.messages).map(T).filter((B)=>B.subtype===void 0||B.subtype===null)[0];D=typeof H?.text==="string"?H.text:"",E=typeof H?.user==="string"?await Re(e,H.user,o):typeof H?.username==="string"?H.username:"?"}catch{}let C=await r(),S=await Wr(e,i,o),k=we(i,s??"",D,x,C?.userId??"");if(t.code!==k){let j=await Ut(e,i,n,o);xe(t.code,k,["--- Last message in channel ------------------",` ${E}: ${ls(D.split(`
544
+ `)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...m.map((H,B)=>` ${wt[B].glyph} ${Js(H)}`),"--- Posting ----------------------------------",_e(C,{asBot:t.asBot}),` \u2192 ${j}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${g}`,` Rule: ${y?"any number of votes per person (--multi)":"one vote per person"}${w?` \u2014 closes ${w}`:""}`," Note: your own votes are not counted (the pills are seeds you added, so they can't be told apart)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],S)}let O=Wn("poll"),P=await Mt(e,i,x,s,!1,o,!0,O.metadata);await hr([Us,...m.map((j,H)=>wt[H].name)],(j)=>Ft(e,i,P,j,o),(j,H)=>{let B=H instanceof Error?H.message:String(H);if(j===Us)console.error(` (could not add marker ${j}: ${B})`);else console.error(` (could not add reaction ${j}: ${B})`)});let L="";try{L=await Pn(e,i,P,o)}catch{}let v=L||`${i}:${P}`;console.error(`\u2713 Posted: ${v}`),O.record({team:C?.team,channel:i,target:t.target,ts:P,threadTs:s,permalink:L,text:x,asBot:t.asBot}),console.log(Zk(v)),console.error(` To close: slack poll --close='${v}'${t.asBot?" --as-bot":""}`)}async function ex(e,t,n){let s=dt(t),o,r,i;if(s?.ts)o=s.channel,r=s.ts,i=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let u=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!u)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
545
+ `+` Got: ${N(t)}`),process.exit(pt);o=u[1],r=u[2]}let l;if(i){let u=T(await Pe(e,o,i,100,n));l=Y(u.messages).map(T).find((c)=>c.ts===r)}else{let u=T(await ot(e,o,1,r,void 0,n,!0));l=Y(u.messages).map(T).find((c)=>c.ts===r)}if(!l)console.error(`Error: message not found: ${N(t)}`),process.exit(pt);return{channelId:o,ts:r,msg:l}}function Eg(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,s)=>`${wt[s].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function tx(e,t){let{channelId:n,ts:s,msg:o}=await ex(e,t.link,t.cookie),r=typeof o.text==="string"?o.text:"",i=Ks(r);if(i.kind==="other")console.error(`Error: this is not a \`slack poll\` poll (don't know how to count its votes).
546
+ ${N(t.link)}`),process.exit(pt);if(i.kind==="closed"){console.error(`\u2713 Poll closed: ${N(i.question)}`);for(let p of Eg(i.tallies))console.log(p);return}let l=new Set;if(typeof o.user==="string"&&o.user)l.add(o.user);let u=await gh(e,n,s,t.cookie),c=Fp(i.choices,u,l,i.multi);console.error(`${N(i.question)}${i.deadline?` (closes ${i.deadline})`:""}`);for(let p of Eg(c.tallies))console.log(p);let a=c.tallies.reduce((p,g)=>p+g.count,0);if(console.error(` ${a} vote(s) total${i.multi?" (multiple choice)":""}`),t.names)for(let p=0;p<c.voters.length;p++){if(!c.voters[p].length)continue;let g=await Promise.all(c.voters[p].map((h)=>Re(e,h,t.cookie)));console.error(` ${wt[p].glyph} ${g.map((h)=>`@${N(h)}`).join(", ")}`)}let d=i.multi?[]:c.ambiguous,f=nr(r,d);if(f!==r&&!t.noNotify)try{await Bt(t.writeToken??e,n,s,f,t.writeToken?t.writeCookie:t.cookie,!0)}catch(p){console.error(` (could not add the notice to the poll text: ${p instanceof Error?p.message:String(p)})
547
+ `+" Only the poster can rewrite a message \u2014 if the bot posted the poll, add --as-bot.")}if(c.ambiguous.length){let p=await Promise.all(c.ambiguous.map((g)=>Re(e,g,t.cookie)));console.error(`\u26A0 One vote per person, but some people pressed several (invalid votes): ${p.map((g)=>`@${N(g)}`).join(", ")}`)}if(!t.close)return;await Bt(t.writeToken??e,n,s,Ap(i.question,c.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await Ft(t.writeToken??e,n,s,nc,t.writeToken?t.writeCookie:t.cookie),await jt(t.writeToken??e,n,s,Us,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 Closed the poll: ${N(t.link)}`)}async function nx(e){let t=await Lo(e);for(let n of No(t,!1))console.log(n);if(!t.ok)process.exit(1)}function Or(){let e=Le();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
548
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function $g(e,t,n,s){let o=await Tt(n,e,s);return Wt(t,o)}function Cg(e){try{return Qg(e)}catch{console.error(`Error: cannot parse --due "${e}" \u2014 use an ISO datetime (2026-11-01T18:00) or a Unix ts.`),process.exit(2)}}function Qg(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 em(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 sx(e,t){Ke(t.message,t.allowUrlAdjacent);let n=qt(e,t.cookie),{ref:s,threadTs:o}=xt(t.target),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await Wt(e,t.userId,t.cookie);else r=await ye(e,s,t.cookie);let i=Qg(t.at),l=new Date(i*1000).toISOString(),u=await n();if(!t.asBot&&await nl(e,r,u?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
549
+ `+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let c=we(r,t.message,String(i),u?.userId??""),a=t.targetOverride?` [${t.targetOverride} \u2192 ${r}]`:"";if(t.code!==c){let f=await Wr(e,r,t.cookie);xe(t.code,c,["--- Scheduling message -----------------------",_e(u,{asBot:t.asBot,pad:9}),` To: ${s}${o?` (thread ${o})`:""}${a}`,` At: ${em(i)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(i*1000))}let d=await uh(e,r,t.message,i,o,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${l})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
550
550
  `+` slack schedule ls --as-bot
551
- slack schedule rm '${t.target}' ${d} --as-bot`),r.startsWith("D"))try{let f=await Po(e);if(!f.ok)for(let p of Lo(f,!0))console.error(p);else{let p=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: ${p} \u2192 App Home.`)}}catch{}}}async function $g(e,t,n,s){let o;if(n)o=n;else if(t)o=await be(e,t,s);let i=(await ch(e,o,s)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let l of i){let u=new Date(l.post_at*1000).toISOString();console.log(`${l.id} ${u} [${l.channel_id}] ${l.text.split(`
552
- `)[0]?.slice(0,80)??""}`)}}async function Cg(e,t){let n;if(t.channelId)n=t.channelId;else n=await be(e,t.target,t.cookie);let s=await We(e,t.cookie),o=ke(n,t.id,s?.userId??"");if(t.code!==o)Se(t.code,o,["--- Deleting scheduled message ---------------",Ee(s,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await lh(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function tx(e,t){if(t.comment!==void 0)Ke(t.comment,t.allowUrlAdjacent);let n=Kt(e,t.cookie),{statSync:s,existsSync:o}=await import("fs"),{basename:r}=await import("path");for(let g of t.filePaths)if(!o(g))console.error(`Error: file not found: ${g}`),process.exit(1);let{ref:i,threadTs:l}=xt(t.target),u;if(t.channelId)u=t.channelId;else if(t.userId)u=await jt(e,t.userId,t.cookie);else u=await be(e,i,t.cookie);if(await Vc(e,u,(await n())?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own upload.`);let c=t.filePaths.length>1,a=t.filePaths.map((g)=>{let h=r(g),m=c?h:t.title??h;return{fp:g,filename:h,title:m,sizeFmt:Mr(s(g).size)}}),d=await n(),f=ke(u,...a.flatMap((g)=>[g.fp,g.title]),d?.userId??"");if(t.code!==f){let g=` To: ${i}${l?` (thread ${l})`:""}`,h=c?[`--- Uploading ${a.length} files ------------------------`,Ee(d,{pad:7}),g,...a.map((m)=>` ${m.filename} (${m.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",Ee(d,{pad:7}),g,` File: ${a[0].fp}`,` Title: ${a[0].title}`,` Size: ${a[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];Se(t.code,f,h)}let p=a.length;for(let g=0;g<p;g++){let h=a[g],m={title:h.title};if(l!==void 0)m.threadTs=l;if(t.comment!==void 0&&g===0)m.initialComment=t.comment;let{fileId:y,permalink:w}=await Fh(e,u,h.fp,m,t.cookie),x=p>1?`[${g+1}/${p}] `:"";console.log(`${x}\u2713 Uploaded (file_id: ${y}${w?`, url: ${w}`:""})`)}}async function nx(e,t,n){let s=n.channel?await be(e,n.channel,t):void 0,o=[],r=1,i=1;do{let u={page:r,count:200};if(n.types)u.types=n.types;if(s)u.channel=s;if(n.user)u.user=n.user;let c=T(await Zp(e,u,t));for(let a of Y(c.files))o.push(T(a));i=Number(T(c.paging).pages??1),r++}while(o.length<n.limit&&r<=i);let l=o.slice(0,n.limit);if(n.format==="jsonl"){for(let u of l)console.log(JSON.stringify({id:u.id??null,name:u.name??u.title??null,filetype:u.filetype??null,size:u.size??null,user:u.user??null,created:u.created??null,permalink:u.permalink??null}));return}for(let u of l){let c=String(u.id??""),a=typeof u.name==="string"?u.name:typeof u.title==="string"?u.title:c,d=typeof u.filetype==="string"?u.filetype:"?",f=typeof u.size==="number"?Mr(u.size):"";console.log(`${c} ${d.padEnd(7)} ${f.padStart(9)} ${a}`)}}function Kr(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 sx(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 s=e[n];if(s!=null)return typeof s==="object"?JSON.stringify(s):String(s)}return""}async function ox(e,t,n,s){let o=Kr(n);if(!o)throw Error(`Not a list ID or list URL: ${n}
553
- `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let r=[],i;do{let u={limit:200};if(i)u.cursor=i;let c=s.asBot?await pc(oo(),o,u):T(await sh(e,o,u,t));for(let d of Y(c.items??c.records))r.push(T(d));let a=T(c.response_metadata).next_cursor;i=typeof a==="string"&&a?a:void 0}while(i&&r.length<s.limit);let l=r.slice(0,s.limit);if(s.format==="jsonl"){for(let u of l)console.log(JSON.stringify(u));return}for(let u of l){let c=String(u.id??""),a=Y(u.fields).map(T).map((d)=>{let f=String(d.key??d.column_id??"?"),p=sx(d);return p?`${f}=${p}`:""}).filter(Boolean);console.log(`${c} ${a.join(" | ")}`)}}function oo(){let e=Ne();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
554
- `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function qr(e){let t=[];try{t=(await Lt(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).
555
- `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function rx(e,t){try{let n=await dc(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function Zg(e,t){let n=await pc(e,t,{limit:1,includeList:!0}),s=Rp(T(n.list));if(!s.length)throw Error(`could not read the column schema of list ${t}`);return s}function Hr(e){console.error(pe(e)),process.exit(1)}async function ix(e){let t=e.cols.map(Tp),n=Op(t),s=oo();await qr(s);let o=await We(s),r=ke("lists-create",e.name,JSON.stringify(n),String(e.todo),o?.userId??"");if(e.code!==r)Se(e.code,r,["--- Creating Slack List ----------------------",Ee(o,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((u,c)=>` column: ${u.name} (${u.type}${u.choices?`: ${u.choices.join("/")}`:""})${c===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 Qp(s,e.name,n,e.todo)}catch(u){Hr(u)}let l=String(i.list_id??T(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${l})`),console.log(await rx(s,l))}async function ax(e){let t=Kr(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=oo();await qr(n);let s=await Zg(n,t),r=[{col:s.find((a)=>a.type==="text")??s[0],value:e.text},...sc(e.sets).map((a)=>({col:tc(s,a.col),value:a.value}))],i=r.map((a)=>({column_id:a.col.id,...nc(a.col,a.value)})),l=await We(n),u=ke("lists-add",t,JSON.stringify(i),l?.userId??"");if(e.code!==u)Se(e.code,u,["--- Adding a row to Slack List ---------------",Ee(l,{asBot:!0,pad:9}),` list: ${t}`,...r.map((a)=>` ${(a.col.name||a.col.key).padEnd(8)} ${a.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let c;try{c=await eh(n,t,i)}catch(a){Hr(a)}console.log(`\u2713 Added row ${String(T(c.item).id??"")} ${e.text}`)}async function cx(e){let t=Kr(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=oo();await qr(n);let s=await Zg(n,t),o=sc(e.sets).map((u)=>({col:tc(s,u.col),value:u.value}));if(e.done!==void 0){let u=Ip(s);if(!u)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);o.push({col:{...u,type:"checkbox"},value:String(e.done)})}if(!o.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let r=o.map((u)=>({row_id:e.row,column_id:u.col.id,...nc(u.col,u.value)})),i=await We(n),l=ke("lists-set",t,e.row,JSON.stringify(r),i?.userId??"");if(e.code!==l)Se(e.code,l,["--- Updating Slack List row -----------------",Ee(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...o.map((u)=>` ${(u.col.name||u.col.key).padEnd(8)} ${u.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await nh(n,t,r)}catch(u){Hr(u)}console.log(`\u2713 Updated row ${e.row}`)}async function lx(e){let t=Kr(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=oo();await qr(n);let s=e.users.length?e.users:e.channels,o=await We(n),r=ke("lists-share",t,e.level,s.join(","),o?.userId??"");if(e.code!==r)Se(e.code,r,["--- Sharing Slack List ----------------------",Ee(o,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${s.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await th(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){Hr(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${s.join(", ")}`)}function ux(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 dx(e,t,n,s){let o=ux(n);if(!o)throw Error(`Not a file ID or file permalink: ${n}
556
- `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let r=T(await Vp(e,o,t)),i=T(r.file),l=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:o,u=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!u)throw Error(`files.info returned no download URL for ${o}`);let c={Authorization:`Bearer ${e}`};if(t)c.Cookie=`d=${t}`;let a=await fetch(u,{headers:c});if(!a.ok)throw Error(`Download failed: HTTP ${a.status} ${a.statusText}`);let d=Buffer.from(await a.arrayBuffer()),{statSync:f,existsSync:p}=await import("fs"),{basename:g}=await import("path"),h=s??l;if(s&&p(s)&&f(s).isDirectory())h=Tt(s,g(l));Tg(h,d),console.log(`\u2713 Downloaded ${l} (${Mr(d.length)}) \u2192 ${h}`)}async function fx(){rg(),G0();let e=(c)=>xs(c.workspace),t=(c)=>Ti(c.workspace),n=async(c)=>{let a=Xe(),d=ts(a);if(In(a))try{let g=await fs(e(c),c.target,t(c));if(!on(a).some((h)=>h.channel===g.channel&&(h.thread_ts===void 0||h.thread_ts===g.root)))console.error(`Error: that message is not in one of ${a.dir}'s subscriptions (restrict_to_subscriptions)`),process.exit(2)}catch(g){console.error(pe(g)),process.exit(1)}let f={target:c.target,newText:c.newText??"",allowUrlAdjacent:c["allow-url-adjacent"]===!0};if(c.tick)f.tick=c.tick;if(d.prefix)f.lanePrefix=d.prefix;if(c.force)f.force=!0;if(c.code)f.code=c.code;if(c["channel-id"])f.channelId=c["channel-id"];if(c.mentions!==!1)f.mentions=!0;let p;if(c["as-bot"]){let g=await bg(f.target,e(c),t(c),f.channelId);if(p=g.botToken,g.channelId&&!f.channelId)f.channelId=g.channelId;f.asBot=!0,f.mentionToken=e(c);let h=t(c);if(h)f.mentionCookie=h}else{p=e(c);let g=t(c);if(g)f.cookie=g}await kk(p,f)},s=async(c)=>{if(!String(c.message??"").trim())console.error("Error: message is empty"),process.exit(1);let a={target:c.target,message:c.message,allowUrlAdjacent:c["allow-url-adjacent"]===!0};if(c.code)a.code=c.code;if(c["channel-id"])a.channelId=c["channel-id"];if(c["user-id"])a.userId=c["user-id"];if(c.broadcast)a.broadcast=!0;if(c.mentions!==!1){a.mentions=!0,a.mentionToken=e(c);let f=t(c);if(f)a.mentionCookie=f}let d;if(c["as-bot"]){let f=Ne();if(!f)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
557
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!a.channelId&&!a.userId&&a.target.startsWith("@"))try{a.userId=await Wt(e(c),a.target,t(c))}catch(p){console.error(`Error: could not resolve ${a.target} to a user for the bot DM.
551
+ slack schedule rm '${t.target}' ${d} --as-bot`),r.startsWith("D"))try{let f=await Lo(e);if(!f.ok)for(let p of No(f,!0))console.error(p);else{let p=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: ${p} \u2192 App Home.`)}}catch{}}}async function Ag(e,t,n,s){let o;if(n)o=n;else if(t)o=await ye(e,t,s);let i=(await dh(e,o,s)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let l of i){let u=new Date(l.post_at*1000).toISOString();console.log(`${l.id} ${u} [${l.channel_id}] ${l.text.split(`
552
+ `)[0]?.slice(0,80)??""}`)}}async function Fg(e,t){let n;if(t.channelId)n=t.channelId;else n=await ye(e,t.target,t.cookie);let s=await Me(e,t.cookie),o=we(n,t.id,s?.userId??"");if(t.code!==o)xe(t.code,o,["--- Deleting scheduled message ---------------",_e(s,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await fh(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function Tg(e,t){if(t.comment!==void 0)Ke(t.comment,t.allowUrlAdjacent);let n=qt(e,t.cookie),{statSync:s,existsSync:o}=await import("fs"),{basename:r}=await import("path");for(let g of t.filePaths)if(!o(g))console.error(`Error: file not found: ${g}`),process.exit(1);let{ref:i,threadTs:l}=xt(t.target),u;if(t.channelId)u=t.channelId;else if(t.userId)u=await Wt(e,t.userId,t.cookie);else u=await ye(e,i,t.cookie);if(await nl(e,u,(await n())?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own upload.`);let c=t.filePaths.length>1,a=t.filePaths.map((g)=>{let h=r(g),m=c?h:t.title??h;return{fp:g,filename:h,title:m,sizeFmt:Br(s(g).size)}}),d=await n(),f=we(u,...a.flatMap((g)=>[g.fp,g.title]),d?.userId??"");if(t.code!==f){let g=` To: ${i}${l?` (thread ${l})`:""}`,h=c?[`--- Uploading ${a.length} files ------------------------`,_e(d,{pad:7}),g,...a.map((m)=>` ${m.filename} (${m.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",_e(d,{pad:7}),g,` File: ${a[0].fp}`,` Title: ${a[0].title}`,` Size: ${a[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];xe(t.code,f,h)}let p=a.length;for(let g=0;g<p;g++){let h=a[g],m={title:h.title};if(l!==void 0)m.threadTs=l;if(t.comment!==void 0&&g===0)m.initialComment=t.comment;let{fileId:y,permalink:w}=await Oh(e,u,h.fp,m,t.cookie),x=p>1?`[${g+1}/${p}] `:"";console.log(`${x}\u2713 Uploaded (file_id: ${y}${w?`, url: ${w}`:""})`)}}async function ox(e,t,n){let s=n.channel?await ye(e,n.channel,t):void 0,o=[],r=1,i=1;do{let u={page:r,count:200};if(n.types)u.types=n.types;if(s)u.channel=s;if(n.user)u.user=n.user;let c=T(await th(e,u,t));for(let a of Y(c.files))o.push(T(a));i=Number(T(c.paging).pages??1),r++}while(o.length<n.limit&&r<=i);let l=o.slice(0,n.limit);if(n.format==="jsonl"){for(let u of l)console.log(JSON.stringify({id:u.id??null,name:u.name??u.title??null,filetype:u.filetype??null,size:u.size??null,user:u.user??null,created:u.created??null,permalink:u.permalink??null}));return}for(let u of l){let c=String(u.id??""),a=typeof u.name==="string"?u.name:typeof u.title==="string"?u.title:c,d=typeof u.filetype==="string"?u.filetype:"?",f=typeof u.size==="number"?Br(u.size):"";console.log(`${c} ${d.padEnd(7)} ${f.padStart(9)} ${a}`)}}function qr(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 rx(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 s=e[n];if(s!=null)return typeof s==="object"?JSON.stringify(s):String(s)}return""}async function ix(e,t,n,s){let o=qr(n);if(!o)throw Error(`Not a list ID or list URL: ${n}
553
+ `+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let r=[],i;do{let u={limit:200};if(i)u.cursor=i;let c=s.asBot?await gc(oo(),o,u):T(await ih(e,o,u,t));for(let d of Y(c.items??c.records))r.push(T(d));let a=T(c.response_metadata).next_cursor;i=typeof a==="string"&&a?a:void 0}while(i&&r.length<s.limit);let l=r.slice(0,s.limit);if(s.format==="jsonl"){for(let u of l)console.log(JSON.stringify(u));return}for(let u of l){let c=String(u.id??""),a=Y(u.fields).map(T).map((d)=>{let f=String(d.key??d.column_id??"?"),p=rx(d);return p?`${f}=${p}`:""}).filter(Boolean);console.log(`${c} ${a.join(" | ")}`)}}function oo(){let e=Le();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
554
+ `+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function Hr(e){let t=[];try{t=(await Nt(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).
555
+ `+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function ax(e,t){try{let n=await pc(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function tm(e,t){let n=await gc(e,t,{limit:1,includeList:!0}),s=Pp(T(n.list));if(!s.length)throw Error(`could not read the column schema of list ${t}`);return s}function zr(e){console.error(pe(e)),process.exit(1)}async function cx(e){let t=e.cols.map(Ip),n=vp(t),s=oo();await Hr(s);let o=await Me(s),r=we("lists-create",e.name,JSON.stringify(n),String(e.todo),o?.userId??"");if(e.code!==r)xe(e.code,r,["--- Creating Slack List ----------------------",_e(o,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((u,c)=>` column: ${u.name} (${u.type}${u.choices?`: ${u.choices.join("/")}`:""})${c===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 nh(s,e.name,n,e.todo)}catch(u){zr(u)}let l=String(i.list_id??T(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${l})`),console.log(await ax(s,l))}async function lx(e){let t=qr(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=oo();await Hr(n);let s=await tm(n,t),r=[{col:s.find((a)=>a.type==="text")??s[0],value:e.text},...rc(e.sets).map((a)=>({col:sc(s,a.col),value:a.value}))],i=r.map((a)=>({column_id:a.col.id,...oc(a.col,a.value)})),l=await Me(n),u=we("lists-add",t,JSON.stringify(i),l?.userId??"");if(e.code!==u)xe(e.code,u,["--- Adding a row to Slack List ---------------",_e(l,{asBot:!0,pad:9}),` list: ${t}`,...r.map((a)=>` ${(a.col.name||a.col.key).padEnd(8)} ${a.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let c;try{c=await sh(n,t,i)}catch(a){zr(a)}console.log(`\u2713 Added row ${String(T(c.item).id??"")} ${e.text}`)}async function ux(e){let t=qr(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=oo();await Hr(n);let s=await tm(n,t),o=rc(e.sets).map((u)=>({col:sc(s,u.col),value:u.value}));if(e.done!==void 0){let u=Lp(s);if(!u)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);o.push({col:{...u,type:"checkbox"},value:String(e.done)})}if(!o.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let r=o.map((u)=>({row_id:e.row,column_id:u.col.id,...oc(u.col,u.value)})),i=await Me(n),l=we("lists-set",t,e.row,JSON.stringify(r),i?.userId??"");if(e.code!==l)xe(e.code,l,["--- Updating Slack List row -----------------",_e(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...o.map((u)=>` ${(u.col.name||u.col.key).padEnd(8)} ${u.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await rh(n,t,r)}catch(u){zr(u)}console.log(`\u2713 Updated row ${e.row}`)}async function dx(e){let t=qr(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=oo();await Hr(n);let s=e.users.length?e.users:e.channels,o=await Me(n),r=we("lists-share",t,e.level,s.join(","),o?.userId??"");if(e.code!==r)xe(e.code,r,["--- Sharing Slack List ----------------------",_e(o,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${s.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await oh(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){zr(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${s.join(", ")}`)}function fx(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 px(e,t,n,s){let o=fx(n);if(!o)throw Error(`Not a file ID or file permalink: ${n}
556
+ `+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let r=T(await eh(e,o,t)),i=T(r.file),l=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:o,u=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!u)throw Error(`files.info returned no download URL for ${o}`);let c={Authorization:`Bearer ${e}`};if(t)c.Cookie=`d=${t}`;let a=await fetch(u,{headers:c});if(!a.ok)throw Error(`Download failed: HTTP ${a.status} ${a.statusText}`);let d=Buffer.from(await a.arrayBuffer()),{statSync:f,existsSync:p}=await import("fs"),{basename:g}=await import("path"),h=s??l;if(s&&p(s)&&f(s).isDirectory())h=Ot(s,g(l));Ig(h,d),console.log(`\u2713 Downloaded ${l} (${Br(d.length)}) \u2192 ${h}`)}async function hx(){ag(),Z0();let e=(c)=>xs(c.workspace),t=(c)=>Oi(c.workspace),n=async(c)=>{let a=Xe(),d=ts(a);if(In(a))try{let g=await fs(e(c),c.target,t(c));if(!rn(a).some((h)=>h.channel===g.channel&&(h.thread_ts===void 0||h.thread_ts===g.root)))console.error(`Error: that message is not in one of ${a.dir}'s subscriptions (restrict_to_subscriptions)`),process.exit(2)}catch(g){console.error(pe(g)),process.exit(1)}let f={target:c.target,newText:c.newText??"",allowUrlAdjacent:c["allow-url-adjacent"]===!0};if(c.tick)f.tick=c.tick;if(d.prefix)f.lanePrefix=d.prefix;if(c.force)f.force=!0;if(c.code)f.code=c.code;if(c["channel-id"])f.channelId=c["channel-id"];if(c.mentions!==!1)f.mentions=!0;let p;if(c["as-bot"]){let g=await Dg(f.target,e(c),t(c),f.channelId);if(p=g.botToken,g.channelId&&!f.channelId)f.channelId=g.channelId;f.asBot=!0,f.mentionToken=e(c);let h=t(c);if(h)f.mentionCookie=h}else{p=e(c);let g=t(c);if(g)f.cookie=g}await _k(p,f)},s=async(c)=>{if(Kc(c.message))c={...c,message:await qc()};if(!String(c.message??"").trim())console.error("Error: message is empty"),process.exit(1);let a={target:c.target,message:c.message,allowUrlAdjacent:c["allow-url-adjacent"]===!0};if(c.json)a.json=!0;if(c.code)a.code=c.code;if(c["channel-id"])a.channelId=c["channel-id"];if(c["user-id"])a.userId=c["user-id"];if(c.broadcast)a.broadcast=!0;if(c.mentions!==!1){a.mentions=!0,a.mentionToken=e(c);let f=t(c);if(f)a.mentionCookie=f}let d;if(c["as-bot"]){let f=Le();if(!f)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
557
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!a.channelId&&!a.userId&&a.target.startsWith("@"))try{a.userId=await Tt(e(c),a.target,t(c))}catch(p){console.error(`Error: could not resolve ${a.target} to a user for the bot DM.
558
558
  ${p instanceof Error?p.message:String(p)}
559
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}d=f,a.asBot=!0}else{d=e(c);let f=t(c);if(f)a.cookie=f}try{await Ik(d,a)}catch(f){console.error(pe(f)),process.exit(1)}},o={state:{type:"string",choices:["open","untriaged","pending","doing","done","dropped","stuck"],default:"open",describe:"open (default) = marked and not done/dropped; untriaged = marked with no progress; stuck = unfinished with a reason flag"},in:{type:"string",describe:"Limit to a channel (#chan)"},from:{type:"string",describe:"Limit to a sender (@user, or 'me') \u2014 usually the person a task is waiting on"},n:{alias:"count",type:"number",default:50,describe:"Max results"},json:{type:"boolean",default:!1}},r=async(c,a)=>{let d={state:c.state??"open",mine:a||c.mine===!0,count:c.n??50,json:c.json===!0};if(c.in)d.in=c.in;if(c.from)d.from=c.from;let f=t(c);if(f)d.cookie=f;await rk(e(c),d)},{who:i,rest:l}=zf(ai(process.argv)),u;if(i){let c=Yf(i);if("error"in c)console.error(`Error: ${c.error}`),process.exit(2);u=c.kind}await Iu(l).scriptName("slack").showHelpOnFail(!1).fail((c,a,d)=>{if(a)console.error(a.message),process.exit(1);console.error(c),console.error(""),d.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).option("as-user",{type:"boolean",describe:"Act as the user session on purpose (needed for writes from inside an agent, or when several identities exist)"}).middleware(async(c)=>{let a=String((c._??[])[0]??"");if(u==="bot"&&"as-bot"in c)c["as-bot"]=!0,c.asBot=!0;if(u==="user"&&c["as-bot"]===!0)console.error(`Error: @${i} is a user identity, but --as-bot was given`),process.exit(2);if(!a||a==="auth"||a==="login"||a==="agent"||a==="sent"||a==="relay")return;try{let d=xs(c.workspace),f=Ne(),p=Gh(c._??[],c,{botTokenSource:f?Og.get("SLACK_BOT_TOKEN")??Jc.get("SLACK_BOT_TOKEN")?.find((h)=>h.val===f)?.path??"shell":void 0,globalPaths:zc,slackTokenSet:!!process.env.SLACK_TOKEN,activeTokenIsBot:!!f&&d===f});if(p)console.error(p),process.exit(2);let g=Xf({isWrite:Tc(c._??[])&&!Oc(c._??[],c),who:i,asBot:c["as-bot"]===!0,asUser:c["as-user"]===!0,activeIsBot:d.startsWith("xoxb-"),agent:Gf(),identities:[...Ka().keys()].sort(),cmd:(c._??[]).slice(0,2).join(" ")});if(g)console.error(g),process.exit(2)}catch(d){if((d instanceof Error?d.message:String(d)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
560
- `),await Is(),process.exit(0);throw d}},!0).command("agent","Bot agent session status and command heartbeat",(c)=>tf(c,xt)).command(["read [target]","msgs [target]"],"Browse messages",(c)=>c.positional("target",{type:"string",describe:"#channel, @user, URL, or an alias (slack alias ls)"}).option("limit",{alias:"n",type:"number",default:20,describe:"Number of messages"}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("unreplied",{type:"boolean",default:!1,describe:"Only messages whose last word (incl. thread replies) is not yours \u2014 i.e. awaiting your answer"}),async(c)=>{let a=e(c),d=c.json?"jsonl":c.format,f=c.target?ja(c.target):void 0;if(f?.thread_ts)await hg(a,f.channel,f.thread_ts,Math.max(c.limit,100),d,t(c));else if(f)await pg(a,f.channel,c.limit,d,c.unreplied,t(c));else if(c.target)await pg(a,c.target,c.limit,d,c.unreplied,t(c));else await tk(a)}).command("thread <target> <ts>","Show thread messages",(c)=>c.positional("target",{type:"string",demandOption:!0}).positional("ts",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:100}).option("format",{type:"string",choices:["text","jsonl","tsv"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs); tsv: <ts> TAB <user|bot id> TAB <text, \\ \\n \\r \\t escaped> [files: N], every page"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("since",{type:"string",describe:"Only messages after this ts (reads every page)"}),async(c)=>{let a=c.json?"jsonl":c.format;await hg(e(c),c.target,c.ts,c.limit,a,t(c),c.since)}).command(["channel","channels","ch"],"Channel commands",(c)=>c.command(["ls","list"],"List channels",(a)=>a.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(a)=>{await sk(e(a),a.limit,a.filter,a.all,a.json?"jsonl":a.format,t(a))}).command("get <channel>","Show channel details",(a)=>a.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(a)=>{let d=e(a),f=t(a),p=a.channel,g=p.startsWith("#")||p.startsWith("@")||p.startsWith("C")||p.startsWith("G")||p.startsWith("D")?p:`#${p}`,h=await be(d,g,f),m=T(await Ln(d,h,f)),y=T(m.channel),w=typeof y.name==="string"?y.name:h,D=y.is_im===!0?"@":"#",E=String(T(y.purpose).value??""),C=String(T(y.topic).value??""),S=y.num_members??y.member_count??"";if(console.log(`${D}${w} ${h}`),C)console.log(`topic: ${C}`);if(E)console.log(`purpose: ${E}`);if(S)console.log(`members: ${S}`);console.log(`private: ${y.is_private===!0}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(a)=>a.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(a)=>{let d=e(a),f=t(a),p=a.name.replace(/^#/,"").toLowerCase(),g=a.private===!0,h=a.invite.filter(Boolean),m=await We(d,f),y=ke(p,String(g),h.join(","),m?.userId??"");if(a.code!==y)Se(a.code,y,["--- Creating channel -------------------------",Ee(m,{pad:9}),` name: ${g?"\uD83D\uDD12 ":"#"}${p}`,` private: ${g}`,...h.length?[` invite: ${h.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let w;try{w=await ph(d,p,g,f)}catch(x){console.error(x instanceof Error?x.message:String(x)),process.exit(1)}if(console.log(`\u2713 Created ${g?"\uD83D\uDD12 ":"#"}${w.name} (${w.id})`),h.length){let x=[];for(let D of h)try{x.push(D.startsWith("U")||D.startsWith("W")?D:await Wt(d,D,f))}catch(E){console.error(` ! could not resolve ${D}: ${E instanceof Error?E.message:String(E)}`)}for(let D of x)try{let E=T(await os(d,D,f)),C=T(E.user);if(C.is_ultra_restricted===!0)console.error(`\u26A0 ${D} is a single-channel guest \u2014 Slack restricts them to their one existing channel; this invite will likely report success but not actually add them.`);else if(C.is_restricted===!0)console.error(`\u26A0 ${D} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(x.length)try{await gh(d,w.id,x,f),console.log(`\u2713 Invited ${x.length} member${x.length===1?"":"s"}`)}catch(D){console.error(` ! invite failed: ${D instanceof Error?D.message:String(D)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(a)=>a.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(a)=>{let d=e(a),f=t(a),p=a.channel;if(p.startsWith("@"))console.error(`Error: ${p} is a DM \u2014 only channels can be renamed.`),process.exit(1);let g=p.startsWith("#")||/^[CG][A-Z0-9]{8,}$/.test(p)?p:`#${p}`,h=a.newName.replace(/^#/,"").toLowerCase(),m,y;try{m=await be(d,g,f)}catch(E){console.error(`Error: could not resolve channel ${p}: ${E instanceof Error?E.message:String(E)}`),process.exit(1)}try{let E=T(T(await Ln(d,m,f)).channel);if(E.is_im===!0||E.is_mpim===!0)console.error(`Error: ${m} is a DM \u2014 only channels can be renamed.`),process.exit(1);y=typeof E.name==="string"?E.name:g.replace(/^#/,"")}catch(E){let C=E instanceof Error?E.message:String(E);if(/channel_not_found/.test(C))console.error(`Error: could not resolve channel ${p}: channel not found (or not visible to this token).`),process.exit(1);y=g.replace(/^#/,"")}if(a.dryRun===!0){console.log(`#${y} -> #${h} (${m})`),console.log("(dry run \u2014 conversations.rename not called)");return}let w=await We(d,f),x=ke("rename",m,h,w?.userId??"");if(a.code!==x)Se(a.code,x,["--- Renaming channel -------------------------",Ee(w,{pad:9}),` channel: ${m}`,` from: #${y}`,` to: #${h}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let D;try{D=await hh(d,m,h,f)}catch(E){let S=(E instanceof Error?E.message:String(E)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],k={name_taken:`Error: a channel named #${h} already exists.`,invalid_name:`Error: "${h}" is not a valid channel name (lowercase letters, numbers, hyphens, underscores; max 80 chars).`,invalid_name_specials:`Error: "${h}" contains characters Slack doesn't allow in channel names.`,invalid_name_maxlength:`Error: "${h}" 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 #${y} (workspace settings may restrict renaming to admins or the channel creator).`,not_in_channel:`Error: this token isn't a member of #${y} \u2014 join it first.`,is_archived:`Error: #${y} is archived \u2014 unarchive it before renaming.`};console.error((S&&k[S])??pe(E)),process.exit(1)}console.log(`\u2713 Renamed #${y} -> #${D.name} (${D.id})`)}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(c)=>c.command(["ls","list"],"List workspace members",(a)=>a.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(a)=>{let d=a.json?"jsonl":a.format,f=e(a),p=t(a),g=await Dh(f,p),h=a.filter?.toLowerCase(),m=Y(g.members).map(T);if(a.external){let D=new Set(m.map((k)=>String(k.id))),E=T(await zs(f,p)),C=Y(E.channels).map(T).filter((k)=>k.is_ext_shared===!0&&!!k.name),S=new Set;for(let k of C)try{for(let O of await kh(f,String(k.id),p))if(!D.has(O))S.add(O)}catch{}for(let k of S)try{let O=T(await os(f,k,p)),P=T(O.user);if(P.id)m.push(P)}catch{}}let y=m.filter((D)=>D.deleted!==!0&&D.is_bot!==!0&&String(D.id)!=="USLACKBOT").filter((D)=>{if(!h)return!0;let E=String(D.name??"").toLowerCase(),C=String(T(D.profile).real_name??"").toLowerCase(),S=String(T(D.profile).email??"").toLowerCase();return E.includes(h)||C.includes(h)||S.includes(h)}).slice(0,a.limit);if(d==="jsonl"){for(let D of y)console.log(JSON.stringify(D));return}if(d==="yaml"){for(let D of y){let E=function(C,S=""){if(C===null)return"null";if(typeof C==="string")return C.includes(`
559
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}d=f,a.asBot=!0}else{d=e(c);let f=t(c);if(f)a.cookie=f}try{await Lk(d,a)}catch(f){console.error(pe(f)),process.exit(1)}},o={state:{type:"string",choices:["open","untriaged","pending","doing","done","dropped","stuck"],default:"open",describe:"open (default) = marked and not done/dropped; untriaged = marked with no progress; stuck = unfinished with a reason flag"},in:{type:"string",describe:"Limit to a channel (#chan)"},from:{type:"string",describe:"Limit to a sender (@user, or 'me') \u2014 usually the person a task is waiting on"},n:{alias:"count",type:"number",default:50,describe:"Max results"},json:{type:"boolean",default:!1}},r=async(c,a)=>{let d={state:c.state??"open",mine:a||c.mine===!0,count:c.n??50,json:c.json===!0};if(c.in)d.in=c.in;if(c.from)d.from=c.from;let f=t(c);if(f)d.cookie=f;await ck(e(c),d)},{who:i,rest:l}=Xf(ci(process.argv)),u;if(i){let c=Vf(i);if("error"in c)console.error(`Error: ${c.error}`),process.exit(2);u=c.kind}await Mu(l).scriptName("slack").showHelpOnFail(!1).fail((c,a,d)=>{if(a)console.error(a.message),process.exit(1);console.error(c),console.error(""),d.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).option("as-user",{type:"boolean",describe:"Act as the user session on purpose (needed for writes from inside an agent, or when several identities exist)"}).middleware(async(c)=>{let a=String((c._??[])[0]??"");if(u==="bot"&&"as-bot"in c)c["as-bot"]=!0,c.asBot=!0;if(u==="user"&&c["as-bot"]===!0)console.error(`Error: @${i} is a user identity, but --as-bot was given`),process.exit(2);if(!a||a==="auth"||a==="login"||a==="agent"||a==="sent"||a==="relay")return;try{let d=xs(c.workspace),f=Le(),p=Vh(c._??[],c,{botTokenSource:f?vg.get("SLACK_BOT_TOKEN")??zc.get("SLACK_BOT_TOKEN")?.find((h)=>h.val===f)?.path??"shell":void 0,globalPaths:Zc,slackTokenSet:!!process.env.SLACK_TOKEN,activeTokenIsBot:!!f&&d===f});if(p)console.error(p),process.exit(2);let g=Qf({isWrite:Ic(c._??[])&&!vc(c._??[],c),who:i,asBot:c["as-bot"]===!0,asUser:c["as-user"]===!0,activeIsBot:d.startsWith("xoxb-"),agent:Zf(),identities:[...Ha().keys()].sort(),cmd:(c._??[]).slice(0,2).join(" ")});if(g)console.error(g),process.exit(2)}catch(d){if((d instanceof Error?d.message:String(d)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
560
+ `),await Is(),process.exit(0);throw d}},!0).command("agent","Bot agent session status and command heartbeat",(c)=>of(c,xt)).command(["read [target]","msgs [target]"],"Browse messages",(c)=>c.positional("target",{type:"string",describe:"#channel, @user, URL, or an alias (slack alias ls)"}).option("limit",{alias:"n",type:"number",default:20,describe:"Number of messages"}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("unreplied",{type:"boolean",default:!1,describe:"Only messages whose last word (incl. thread replies) is not yours \u2014 i.e. awaiting your answer"}),async(c)=>{let a=e(c),d=c.json?"jsonl":c.format,f=c.target?Ja(c.target):void 0;if(f?.thread_ts)await mg(a,f.channel,f.thread_ts,Math.max(c.limit,100),d,t(c));else if(f)await gg(a,f.channel,c.limit,d,c.unreplied,t(c));else if(c.target)await gg(a,c.target,c.limit,d,c.unreplied,t(c));else await ok(a)}).command("thread <target> <ts>","Show thread messages",(c)=>c.positional("target",{type:"string",demandOption:!0}).positional("ts",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:100}).option("format",{type:"string",choices:["text","jsonl","tsv"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs); tsv: <ts> TAB <user|bot id> TAB <text, \\ \\n \\r \\t escaped> [files: N], every page"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("since",{type:"string",describe:"Only messages after this ts (reads every page)"}),async(c)=>{let a=c.json?"jsonl":c.format;await mg(e(c),c.target,c.ts,c.limit,a,t(c),c.since)}).command(["channel","channels","ch"],"Channel commands",(c)=>c.command(["ls","list"],"List channels",(a)=>a.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(a)=>{await ik(e(a),a.limit,a.filter,a.all,a.json?"jsonl":a.format,t(a))}).command("get <channel>","Show channel details",(a)=>a.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(a)=>{let d=e(a),f=t(a),p=a.channel,g=p.startsWith("#")||p.startsWith("@")||p.startsWith("C")||p.startsWith("G")||p.startsWith("D")?p:`#${p}`,h=await ye(d,g,f),m=T(await Ln(d,h,f)),y=T(m.channel),w=typeof y.name==="string"?y.name:h,D=y.is_im===!0?"@":"#",E=String(T(y.purpose).value??""),C=String(T(y.topic).value??""),S=y.num_members??y.member_count??"";if(console.log(`${D}${w} ${h}`),C)console.log(`topic: ${C}`);if(E)console.log(`purpose: ${E}`);if(S)console.log(`members: ${S}`);console.log(`private: ${y.is_private===!0}`)}).command("invite <channel> <users..>","Invite people to a channel (conversations.invite; confirm-hash gate). Acts as the current identity, e.g. slack @bot channel invite \u2026",(a)=>a.positional("channel",{type:"string",demandOption:!0,describe:"#name, channel id, or permalink"}).positional("users",{type:"string",array:!0,demandOption:!0,describe:"@handle or U\u2026 ids"}).option("code",{type:"string",describe:"Safety hash to confirm"}),async(a)=>{let d=e(a),f=t(a),p,g=[];try{p=await ye(d,String(a.channel),f);for(let w of a.users.map(String))g.push(/^[UW][A-Z0-9]{2,}$/.test(w)?w:await Tt(d,w,f))}catch(w){console.error(pe(w)),process.exit(1)}let h=await Me(d,f),m=await Ut(d,p,String(a.channel),f),y=we("channel-invite",p,g.join(","),h?.userId??"");if(a.code!==y)xe(a.code,y,["--- Inviting to a channel --------------------",_e(h,{pad:9}),` channel: ${m}`,` users: ${g.join(", ")}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await bc(d,p,g,f)}catch(w){let x=w instanceof Error?w.message:String(w);if(!/already_in_channel/.test(x))console.error(`\u2717 invite failed: ${pe(w)}${/not_in_channel/.test(x)?`
561
+ The inviter must be a member of the channel first.`:""}`),process.exit(1)}console.log(`\u2713 Invited ${g.length} to ${m}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(a)=>a.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(a)=>{let d=e(a),f=t(a),p=a.name.replace(/^#/,"").toLowerCase(),g=a.private===!0,h=a.invite.filter(Boolean),m=await Me(d,f),y=we(p,String(g),h.join(","),m?.userId??"");if(a.code!==y)xe(a.code,y,["--- Creating channel -------------------------",_e(m,{pad:9}),` name: ${g?"\uD83D\uDD12 ":"#"}${p}`,` private: ${g}`,...h.length?[` invite: ${h.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let w;try{w=await mh(d,p,g,f)}catch(x){console.error(x instanceof Error?x.message:String(x)),process.exit(1)}if(console.log(`\u2713 Created ${g?"\uD83D\uDD12 ":"#"}${w.name} (${w.id})`),h.length){let x=[];for(let D of h)try{x.push(D.startsWith("U")||D.startsWith("W")?D:await Tt(d,D,f))}catch(E){console.error(` ! could not resolve ${D}: ${E instanceof Error?E.message:String(E)}`)}for(let D of x)try{let E=T(await os(d,D,f)),C=T(E.user);if(C.is_ultra_restricted===!0)console.error(`\u26A0 ${D} is a single-channel guest \u2014 Slack restricts them to their one existing channel; this invite will likely report success but not actually add them.`);else if(C.is_restricted===!0)console.error(`\u26A0 ${D} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(x.length)try{await bc(d,w.id,x,f),console.log(`\u2713 Invited ${x.length} member${x.length===1?"":"s"}`)}catch(D){console.error(` ! invite failed: ${D instanceof Error?D.message:String(D)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(a)=>a.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(a)=>{let d=e(a),f=t(a),p=a.channel;if(p.startsWith("@"))console.error(`Error: ${p} is a DM \u2014 only channels can be renamed.`),process.exit(1);let g=p.startsWith("#")||/^[CG][A-Z0-9]{8,}$/.test(p)?p:`#${p}`,h=a.newName.replace(/^#/,"").toLowerCase(),m,y;try{m=await ye(d,g,f)}catch(E){console.error(`Error: could not resolve channel ${p}: ${E instanceof Error?E.message:String(E)}`),process.exit(1)}try{let E=T(T(await Ln(d,m,f)).channel);if(E.is_im===!0||E.is_mpim===!0)console.error(`Error: ${m} is a DM \u2014 only channels can be renamed.`),process.exit(1);y=typeof E.name==="string"?E.name:g.replace(/^#/,"")}catch(E){let C=E instanceof Error?E.message:String(E);if(/channel_not_found/.test(C))console.error(`Error: could not resolve channel ${p}: channel not found (or not visible to this token).`),process.exit(1);y=g.replace(/^#/,"")}if(a.dryRun===!0){console.log(`#${y} -> #${h} (${m})`),console.log("(dry run \u2014 conversations.rename not called)");return}let w=await Me(d,f),x=we("rename",m,h,w?.userId??"");if(a.code!==x)xe(a.code,x,["--- Renaming channel -------------------------",_e(w,{pad:9}),` channel: ${m}`,` from: #${y}`,` to: #${h}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let D;try{D=await yh(d,m,h,f)}catch(E){let S=(E instanceof Error?E.message:String(E)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],k={name_taken:`Error: a channel named #${h} already exists.`,invalid_name:`Error: "${h}" is not a valid channel name (lowercase letters, numbers, hyphens, underscores; max 80 chars).`,invalid_name_specials:`Error: "${h}" contains characters Slack doesn't allow in channel names.`,invalid_name_maxlength:`Error: "${h}" 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 #${y} (workspace settings may restrict renaming to admins or the channel creator).`,not_in_channel:`Error: this token isn't a member of #${y} \u2014 join it first.`,is_archived:`Error: #${y} is archived \u2014 unarchive it before renaming.`};console.error((S&&k[S])??pe(E)),process.exit(1)}console.log(`\u2713 Renamed #${y} -> #${D.name} (${D.id})`)}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(c)=>c.command(["ls","list"],"List workspace members",(a)=>a.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(a)=>{let d=a.json?"jsonl":a.format,f=e(a),p=t(a),g=await xh(f,p),h=a.filter?.toLowerCase(),m=Y(g.members).map(T);if(a.external){let D=new Set(m.map((k)=>String(k.id))),E=T(await zs(f,p)),C=Y(E.channels).map(T).filter((k)=>k.is_ext_shared===!0&&!!k.name),S=new Set;for(let k of C)try{for(let O of await Sh(f,String(k.id),p))if(!D.has(O))S.add(O)}catch{}for(let k of S)try{let O=T(await os(f,k,p)),P=T(O.user);if(P.id)m.push(P)}catch{}}let y=m.filter((D)=>D.deleted!==!0&&D.is_bot!==!0&&String(D.id)!=="USLACKBOT").filter((D)=>{if(!h)return!0;let E=String(D.name??"").toLowerCase(),C=String(T(D.profile).real_name??"").toLowerCase(),S=String(T(D.profile).email??"").toLowerCase();return E.includes(h)||C.includes(h)||S.includes(h)}).slice(0,a.limit);if(d==="jsonl"){for(let D of y)console.log(JSON.stringify(D));return}if(d==="yaml"){for(let D of y){let E=function(C,S=""){if(C===null)return"null";if(typeof C==="string")return C.includes(`
561
562
  `)?`|
562
563
  ${C.split(`
563
564
  `).join(`
564
565
  `)}`:C;if(typeof C!=="object")return String(C);if(Array.isArray(C))return C.map((k)=>`
565
566
  ${S} - ${E(k,S+" ")}`).join("");return Object.entries(C).map(([k,O])=>`
566
- ${S} ${k}: ${E(O,S+" ")}`).join("")};console.log("---");for(let[C,S]of Object.entries(D))console.log(`${C}: ${E(S)}`)}return}let w=Intl.DateTimeFormat().resolvedOptions().timeZone,x=y.length?String(T(Y(g.members).map(T)[0]??{}).team_id??""):"";for(let D of y){let E=T(D.profile),C=String(D.name??D.id),S=String(D.id??""),k=String(E.display_name||""),O=String(E.real_name||""),P=String(E.email||""),L=String(D.tz??""),j=[...new Set([k,O].filter((R)=>R&&R!==C))].join(" / "),H=L&&L!==w?L:"",B=String(D.team_id??""),q=D.is_stranger===!0||x&&B&&B!==x?`external:${B||"?"}`:D.is_ultra_restricted===!0?"single-channel guest":D.is_restricted===!0?"guest":"",z=[P,H].filter(Boolean).join(" ");console.log(`@${C} ${S} ${j}${z?" "+z:""}${q?` [${q}]`:""}`)}}).command("get <user>","Show user details",(a)=>a.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(a)=>{let d=e(a),f=t(a),p=a.user.startsWith("@")?a.user:`@${a.user}`,g="";try{g=await Wt(d,p,f)}catch(v){console.error(v instanceof Error?v.message:String(v)),process.exit(1)}let h=T(await os(d,g,f)),m=T(h.user),y=T(m.profile),w=Intl.DateTimeFormat().resolvedOptions().timeZone,x=String(m.name??g),D=String(m.id??g),E=String(y.display_name||""),C=String(y.real_name||""),S=String(y.email||""),k=String(m.tz??""),O=String(y.phone||""),P=String(y.title||"");console.log(`@${x} ${D}`);let L=[...new Set([E,C].filter((v)=>v&&v!==x))];if(L.length)console.log(`name: ${L.join(" / ")}`);if(S)console.log(`email: ${S}`);if(O)console.log(`phone: ${O}`);if(P)console.log(`title: ${P}`);if(k&&k!==w)console.log(`tz: ${k}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(c)=>c.option("limit",{alias:"l",type:"number",default:20}),async(c)=>{await nk(e(c),c.limit)}).command("search <query>","Full-text search",(c)=>c.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(c)=>{await vg(e(c),c.query,c.count,c.json,t(c))}).command("send <target> <message>","Send a message (confirm-hash safety gate)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("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."}).option("to",{type:"string",describe:"Permalink of the message you are answering: refuses when it is not in the target's thread (see also `slack reply --to`)"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to: send even when the message is in another thread"}),async(c)=>{if(c.to&&!c["any-thread"])try{let a=e(c),d=t(c),f=await fs(a,c.to,d),p=dt(c.target)?await fs(a,c.target,d):void 0,g=p?{channel:p.channel,threadTs:p.root}:(()=>{let y=xt(c.target);return{ref:y.ref,...y.threadTs?{threadTs:y.threadTs}:{}}})(),h="channel"in g?g.channel:await be(a,g.ref,d),m=Ua({channel:h,...g.threadTs?{threadTs:g.threadTs}:{}},f);if(m)console.error(`Error: ${m}`),process.exit(2)}catch(a){console.error(pe(a)),process.exit(1)}await s(c)}).command("init [dir]","Create .slack-term/ in a directory: aliases, settings, inbox/outbox (never committed)",(c)=>c.positional("dir",{type:"string",default:".",describe:"Directory to put .slack-term/ in"}).option("prefix",{type:"string",describe:'Put in front of every `slack reply`, e.g. "[design]"'}).option("channel",{type:"string",describe:"Default channel (id)"}).option("as-bot",{type:"boolean",describe:"Reply as the bot by default"}),(c)=>{let{dir:a,created:d}=Na(c.dir,{...c.prefix?{prefix:c.prefix}:{},...c.channel?{channel:c.channel}:{},...c["as-bot"]!==void 0?{as_bot:c["as-bot"]}:{}});console.log(d.length?`${a}: created ${d.join(", ")}`:`${a}: already set up`)}).command("alias","Name channels and threads for this directory (the nearest .slack-term/)",(c)=>c.command(["ls","list"],"List aliases: name, channel, thread, file",(a)=>a.option("json",{type:"boolean",default:!1}),(a)=>{let d=Xe(),f=on(d);if(a.json){console.log(JSON.stringify(f.map(({scope:p,...g})=>g)));return}for(let p of f)console.log(`${p.name} ${p.channel} ${p.thread_ts??"-"} ${p.file}${p.note?` ${p.note}`:""}`);if(!f.length)console.error(`no aliases in ${d.dir}${d.global?" (no .slack-term/ above here: `slack init` makes one)":""}`)}).command("set <name> <target>","Name a channel or thread: a permalink (a reply's names its thread root), #chan:<ts>, or #chan",(a)=>a.positional("name",{type:"string",demandOption:!0}).positional("target",{type:"string",demandOption:!0}).option("note",{type:"string",describe:"Free text shown by `alias ls`"}).option("shared",{type:"boolean",default:!1,describe:"Write settings.yml (the allowlist owner's file) instead of settings.local.yml"}).option("dir",{type:"string",describe:"Use the .slack-term/ above this directory instead of the cwd's (with --shared: a lane's dir)"}),async(a)=>{let d=e(a),f=t(a),p=Xe(a.dir),g=dt(a.target)?.ts!==void 0||xt(a.target).threadTs!==void 0,h,m,y="";if(g){let D=await fs(d,a.target,f);if(h=D.channel,m=D.root,D.root!==D.ts)y=` (${D.ts} is a reply: named its thread root)`}else h=await be(d,xt(a.target).ref,f);let w;try{w=Wa(p,a.name,{channel:h,...m?{thread_ts:m}:{},...a.note?{note:a.note}:{}},a.shared)}catch(D){if(D instanceof Rn)console.error(`Error: ${D.message}`),process.exit(2);throw D}let x=w&&(w.channel!==h||w.thread_ts!==m)?` (was ${w.channel} ${w.thread_ts??"-"})`:"";console.log(`${a.name} \u2192 ${h} ${m??"-"}${y}${x} [${p.dir}]`)}).command(["unset <name>","rm <name>"],"Remove an alias (from settings.local.yml; --shared: also from settings.yml)",(a)=>a.positional("name",{type:"string",demandOption:!0}).option("shared",{type:"boolean",default:!1,describe:"Allow removing one defined in settings.yml"}).option("dir",{type:"string",describe:"Use the .slack-term/ above this directory"}),(a)=>{let d=Xe(a.dir),f;try{f=Nf(d,a.name,a.shared)}catch(p){if(p instanceof Rn)console.error(`Error: ${p.message}`),process.exit(2);throw p}if(f==="removed")console.log(`${a.name} removed [${d.dir}]`);else if(f==="absent")console.error(`no alias "${a.name}" in ${d.dir}`),process.exit(2);else console.error(`"${a.name}" is defined in ${d.dir}/settings.yml: edit that file to remove it`),process.exit(2)}).command("who <channel> <ts>","Which registered .slack-term/ dirs subscribe this thread (or message): dir, alias",(a)=>a.positional("channel",{type:"string",demandOption:!0,describe:"Channel id"}).positional("ts",{type:"string",demandOption:!0,describe:"Thread root ts (a reply's own ts is not its thread)"}).option("json",{type:"boolean",default:!1}),(a)=>{let d=jf(a.channel,a.ts).map((f)=>({dir:H0(f.scope.dir),scope:f.scope.dir,alias:f.name,file:f.file}));if(a.json)console.log(JSON.stringify(d));else for(let f of d)console.log(`${f.dir} ${f.alias}`);if(!d.length)process.exitCode=2}).command("import <tsv>","One-shot: import a legacy allowlist.tsv (<thread_ts> TAB <lane>) into each lane's settings.yml",(a)=>a.positional("tsv",{type:"string",demandOption:!0}).option("channel",{type:"string",demandOption:!0,describe:"The channel every thread is in (for a DM: the DM id)"}).option("lane-dir",{type:"array",string:!0,demandOption:!0,describe:"<lane>=<dir> (a directory holding .slack-term/, made if missing); repeatable"}),(a)=>{let d=new Map;for(let g of a["lane-dir"]??[]){let h=String(g).indexOf("=");if(h<=0)console.error(`Error: --lane-dir ${g}: want <lane>=<dir>`),process.exit(2);d.set(String(g).slice(0,h),String(g).slice(h+1))}let f=0,p=new Map;for(let g of Hc(a.tsv,"utf8").split(`
567
- `)){let[h,m]=g.trim().split("\t");if(!h||g.startsWith("#")||!m)continue;let y=d.get(m);if(!y||!/^\d{10}\.\d{6}$/.test(h)){p.set(m,(p.get(m)??0)+1);continue}let w={dir:Na(y).dir,global:!1};Wa(w,`t-${h}`,{channel:a.channel,thread_ts:h,note:"imported from legacy allowlist"},!0),f++}console.log(`imported ${f} subscription(s)`);for(let[g,h]of p)console.error(`skipped ${h} line(s) for lane "${g}" (no --lane-dir, or not a ts)`)}).demandCommand(1,"alias needs a subcommand: ls, set, unset, who, import")).command("reply [dest] [message]","Reply in a thread \u2014 an alias, a permalink or #chan:<ts> \u2014 with the directory's prefix (confirm-hash gate, like send)",(c)=>c.positional("dest",{type:"string",describe:"alias | permalink | #chan:<ts> | <ts> (in settings' channel). Omit with --to"}).positional("message",{type:"string",describe:"Text, or - for stdin"}).option("to",{type:"string",describe:"Permalink of the message you are answering: replies in ITS thread; with a dest, refuses when they differ"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to and a dest: post to dest even when the message is in another thread"}).option("prefix",{type:"string",describe:`Override settings' prefix ("" for none)`}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("broadcast",{type:"boolean",default:!1,describe:"Also send to channel"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real mentions (--no-mentions for literal text)"}),async(c)=>{let{dest:a,message:d}=c;if(c.to&&d===void 0)d=a,a=void 0;if(d==="-")d=await Bun.stdin.text();if(d===void 0||!d.trim())console.error("Error: message is empty"),process.exit(1);if(!a&&!c.to)console.error("Error: reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"),process.exit(2);let f=e(c),p=t(c),g=Xe(),h=ts(g),m;try{let D=await gg(f,p,g,a,c.to,c["any-thread"]);if("error"in D)console.error(`Error: ${D.error}`),process.exit(2);m=D}catch(D){console.error(pe(D)),process.exit(1)}let{channel:y,threadTs:w}=m;if(In(g)&&(c.prefix!==void 0||c["as-bot"]!==void 0&&c["as-bot"]!==(h.as_bot??!1)))console.error(`Error: ${g.dir} is restricted: who it posts as (prefix, as_bot) comes from settings.yml; --prefix / --as-bot are refused`),process.exit(2);let x=Ja(d,c.prefix??h.prefix);if(!x.trim())console.error("Error: message is empty (only the prefix)"),process.exit(1);await s({workspace:c.workspace,target:`${y}:${w}`,message:x,code:c.code,"allow-url-adjacent":c["allow-url-adjacent"],"as-bot":c["as-bot"]??h.as_bot??!1,broadcast:c.broadcast,mentions:c.mentions})}).command("inbox","This directory's .slack-term/inbox/: messages routed here by `slack stream --inbox`",(c)=>c.command(["ls","list"],"Pending messages: ts, from, alias, text (redacted)",(a)=>a.option("json",{type:"boolean",default:!1}),(a)=>{let d=ns(Xe());if(a.json){console.log(JSON.stringify(d.map((f)=>({file:f.file,...f.entry}))));return}for(let f of d)console.log(`${f.entry.ts} ${f.entry.user_name??f.entry.user} ${f.entry.alias} ${f.entry.text.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\t/g,"\\t")}${f.entry.files?` [files: ${f.entry.files}]`:""}`)}).command("listen","Print each message as it arrives in inbox/ (one JSON line each); pending ones first. Exits 0 at --timeout",(a)=>a.option("timeout",{type:"number",default:3600,describe:"Seconds"}).option("new-only",{type:"boolean",default:!1,describe:"Skip what is already pending"}).option("thread",{type:"string",describe:"Only messages in this thread (its root ts)"}).option("alias",{type:"string",describe:"Only messages routed by this alias"}).option("from",{type:"array",string:!0,describe:"Only messages from these user ids; repeatable"}),async(a)=>{let d=Xe(),f=a.from?.length?new Set(a.from.map(String)):void 0,p=(m)=>(!a.thread||(m.thread_ts??m.ts)===a.thread)&&(!a.alias||m.alias===a.alias)&&(!f||f.has(m.user)),g=new Set;if(a["new-only"])for(let m of ns(d))g.add(m.file);let h=Date.now()+a.timeout*1000;for(;;){for(let m of ns(d)){if(g.has(m.file))continue;if(g.add(m.file),p(m.entry))console.log(JSON.stringify({file:m.file,...m.entry}))}if(Date.now()>=h)break;await new Promise((m)=>setTimeout(m,Math.min(500,Math.max(0,h-Date.now()))))}}).command("nudge","Pending messages older than settings' nudge_after_min (default 30): exit 1 when there are any; --eyes also puts \uD83D\uDC40 on each, once",(a)=>a.option("json",{type:"boolean",default:!1}).option("eyes",{type:"boolean",default:!1,describe:"React \uD83D\uDC40 on each overdue message (once per message: recorded as nudged_at)"}).option("as-bot",{type:"boolean",describe:"React via the bot token (default: settings' as_bot)"}),async(a)=>{let d=Xe(),f=fp(d);if(a.eyes){let p=a["as-bot"]??ts(d).as_bot??!1,g=p?Ne():e(a);if(!g)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);let h=p?void 0:t(a);for(let m of f){if(m.entry.nudged_at)continue;try{await Ft(g,m.entry.channel,m.entry.ts,"eyes",h)}catch(y){if(!/already_reacted/.test(y instanceof Error?y.message:String(y))){console.error(`\u26A0 ${m.entry.channel}:${m.entry.ts}: could not add \uD83D\uDC40: ${pe(y)}`);continue}}pp(m),m.entry.nudged_at=new Date().toISOString()}}if(a.json)console.log(JSON.stringify(f.map((p)=>({file:p.file,ts:p.entry.ts,channel:p.entry.channel,permalink:p.entry.permalink,waiting_min:Math.round((Date.now()-p.mtimeMs)/60000),...p.entry.nudged_at?{nudged_at:p.entry.nudged_at}:{}}))));else for(let p of f)console.log(`${p.entry.ts} ${Math.round((Date.now()-p.mtimeMs)/60000)} min ${p.entry.permalink}${p.entry.nudged_at?"\t\uD83D\uDC40":""}`);if(f.length)process.exitCode=1}).demandCommand(1,"inbox needs a subcommand: ls, listen, nudge")).command("done <ref..>","Mark inbox messages handled (moved to archived/) without replying: a file name, path or message ts",(c)=>c.positional("ref",{type:"string",array:!0,demandOption:!0}),(c)=>{let a=Xe(),d=0;for(let f of c.ref){let p=za(a,f);if(p)console.log(`archived ${p}`);else console.error(`not in ${a.dir}/inbox: ${f}`),d++}if(d)process.exit(2)}).command("outbox","This directory's .slack-term/outbox/: replies queued as files, sent by `outbox flush`",(c)=>c.command("add <dest> <message>","Queue a reply (text redacted before it is written; - reads stdin)",(a)=>a.positional("dest",{type:"string",demandOption:!0,describe:"alias | permalink | #chan:<ts>"}).positional("message",{type:"string",demandOption:!0}).option("in-reply-to",{type:"string",describe:"ts of the inbox message this answers: archived once sent"}),async(a)=>{let d=a.message==="-"?await Bun.stdin.text():a.message;if(!d.trim())console.error("Error: message is empty"),process.exit(1);let f=lp(Xe(),{to:a.dest,text:d,...a["in-reply-to"]?{in_reply_to:a["in-reply-to"]}:{}});if(f.redacted.length)console.error(`\u26A0 redacted before queueing: ${f.redacted.join(", ")}`);console.log(f.file)}).command(["ls","list"],"Queued replies: file, dest, attempts, error",(a)=>a,()=>{for(let a of Ya(Xe()))console.log(`${a.file} ${a.entry.to}${a.entry.attempts?` attempts=${a.entry.attempts} ${a.entry.error??""}`:""}`)}).command("flush","Send every queued reply (prefix, thread and restrict checks as `reply`); a --code covers the whole batch",(a)=>a.option("code",{type:"string",describe:"Safety hash to confirm the batch"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}),async(a)=>{let d=Xe(),f=ts(d),p=Ya(d);if(!p.length){console.error(`nothing in ${d.dir}/outbox`);return}if(In(d)&&a["as-bot"]!==void 0&&a["as-bot"]!==(f.as_bot??!1))console.error(`Error: ${d.dir} is restricted: as_bot comes from settings.yml; --as-bot is refused`),process.exit(2);let g=a["as-bot"]??f.as_bot??!1,h=e(a),m=t(a),y,w;if(g){let k=Ne();if(!k)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);y=k}else y=h,w=m;let x=[],D=[];for(let k of p)try{let O=await gg(h,m,d,k.entry.to,void 0);if("error"in O){D.push(`${k.file}: ${O.error}`);continue}let P=Ja(k.entry.text,f.prefix);if(!P.trim()){D.push(`${k.file}: empty`);continue}Ke(P),x.push({item:k,...O,text:P})}catch(O){D.push(`${k.file}: ${pe(O)}`)}for(let k of D)console.error(`refused (stays queued): ${k}`);if(!x.length)process.exit(2);let E=[`OUTBOX \u2014 ${x.length} repl${x.length===1?"y":"ies"}${g?" as the bot":""}:`];for(let k of x)E.push(` \u2192 ${k.channel} thread ${k.threadTs}: ${N(k.text).replace(/\n/g,"\u23CE").slice(0,120)}${k.text.includes("[redacted:")?" (secrets were masked when queued: this is what posts)":""}`);let C=ke("outbox",g?"bot":"user",...x.map((k)=>`${k.channel}:${k.threadTs}:${k.text}`));if(a.code!==C)Se(a.code,C,E);let S=0;for(let k of x)try{let O=await Nt(y,k.channel,k.text,k.threadTs,!1,w),P="";try{P=await Pn(y,k.channel,O,w)}catch{}let L=up(d,k.item,{ts:O,permalink:P,channel:k.channel,thread_ts:k.threadTs});console.log(`\u2713 ${P||O} (${L})`)}catch(O){dp(k.item,pe(O)),console.error(`\u2717 ${k.item.file}: ${pe(O)}`),S++}if(S)process.exit(1)}).demandCommand(1,"outbox needs a subcommand: add, ls, flush")).command("ask [target] [question] [choices..]","Ask a question with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions (confirm-hash safety gate). Lifecycle: --waitFor=<link> collect, --void=<link> void (verb aliases: `ask collect <link>`, `ask void <link\u2026>`)",(c)=>c.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:[...Et],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 (`slack ask void`) \u2014 stop waiting. 7 = only with --explain-exit: \u2139\uFE0F pressed, explain and collect again (the question stays open)."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted (except, on an --explain question someone pressed \u2139\uFE0F on, one thread note per question). Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: the cursor \u2014 everything at or before this ts was already delivered. Text replies there are neither answers nor notes again (pass the `cursor` a previous --json result gave you, or the reply ts an exit 5 printed). Reactions still count."}).option("void",{type:"string",array:!0,describe:"Void question(s) you posted that expired or stopped meaning anything \u2014 --void=<permalink>, repeatable. The text becomes \uD83D\uDEAB with --reason (body kept, options removed), our pills come off, and --wait/--waitFor on it exits 6. Same --code gate. Only your own questions (--as-bot for the bot's). Alias: `slack ask void <link\u2026>`."}).option("reask",{type:"boolean",default:!1,describe:"With ONE --void: post the question again (same channel/thread, same text and choices unless you give new ones as positionals / --body) and void the old one as replaced by it \u2014 one gate for both. The way to change the options of a question someone already answered."}).option("edit",{type:"string",describe:'Change an open question you posted: --edit=<permalink> ["new question" [choices\u2026]] [--body \u2026]. Rebuilt with the ask layout so collect still reads it. Options can change only while nobody has answered (then: --void=<link> --reask). Same --code gate.'}).option("ls",{type:"boolean",default:!1,describe:"List the questions you posted (local sent-log) with their LIVE state: --state open|answered|void|all (default open), --stale 24h, --channel, --json. With --stale it prints the --void command that would retire them."}).option("pending",{type:"boolean",default:!1,describe:"List questions THIS machine asked (local sent-log) that somebody answered but nobody collected, grouped by the asking session, with whether that agent is still alive and the --waitFor line that collects each. Read-only: --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("explain",{type:"boolean",describe:"Also offer an \u2139\uFE0F 'explain' pill (seeded after \u2795): pressing it asks YOU to explain the question in its thread and is never an answer \u2014 the question stays open. --wait/--waitFor report it on stderr (and as `explain` in --json), and post one thread note per question. Default: $SLACK_TERM_ASK_EXPLAIN=1 turns it on; --no-explain turns it off."}).option("explain-exit",{type:"boolean",default:!1,describe:'With --wait / --waitFor: exit 7 (stdout empty; --json status "explain") when someone presses \u2139\uFE0F \u2014 once per question, on the run that posts the thread note. The question stays open: explain, then collect again.'}).option("json",{type:"boolean",default:!1,describe:"With --pending: one JSON object per answered question (sender, answer, collect command). With --wait / --waitFor: print ONE JSON object on stdout \u2014 {status, answer, how, who, notes:[{ts,user,text,permalink}], cursor, permalink} \u2014 instead of the bare answer. `notes` are the audience's replies that are not the answer (thread replies; plain replies too in a 1:1 DM). Exit codes unchanged."}).option("timeout",{type:"number",default:3600,describe:"Overall limit for --wait / --waitFor, in seconds (0 with --waitFor = check once)"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Ask via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(c)=>{if(c.ls||c.pending){if(c.ls&&c.pending)console.error("Error: --ls and --pending are separate lists \u2014 pick one."),process.exit(le);let D=(()=>{try{return e(c)}catch{return}})(),E={};if(D)E.user=D;let C=Ne();if(C)E.bot=C;let S=t(c);if(S)E.cookie=S;if(c.pending){if(c.target||c.question||c.waitFor||c.wait||c.void||c.edit)console.error("Error: --pending reads the local log \u2014 do not also pass a target/question or another ask action."),process.exit(le);let O=yr(String(c.since));if(O===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${N(String(c.since))})`),process.exit(le);let P={sinceMs:O,json:!!c.json};if(c.channel)P.channel=String(c.channel);try{await Hk(E,P)}catch(L){console.error(pe(L)),process.exit(le)}return}let k={state:String(c.state??"open"),json:!!c.json,limit:Number(c.limit)||50};if(c.stale)k.stale=String(c.stale);if(c.channel)k.channel=String(c.channel);await qk(E,k);return}let a=(D)=>{if(!D){let C=t(c);return C?{token:e(c),cookie:C}:{token:e(c)}}let E=Ne();if(!E)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
568
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);return{token:E}},d=c.target!==void 0&&c.target!=="void"&&c.target!=="collect"?String(c.target):void 0,f=[c.question,...c.choices??[]].filter((D)=>D!==void 0).map(String);if(c.edit){if(c.void||c.wait||c.waitFor)console.error("Error: --edit changes one open question \u2014 do not combine it with --void/--wait/--waitFor."),process.exit(le);let{token:D,cookie:E}=a(!!c["as-bot"]),C={link:String(c.edit),asBot:!!c["as-bot"],mentionToken:D,allowUrlAdjacent:!!c["allow-url-adjacent"]};if(d!==void 0)C.question=d;if(f.length)C.choices=f.map((S)=>S.trim()).filter(Boolean);if(c.body!==void 0)C.body=String(c.body);if(c.lang)C.lang=String(c.lang);if(c.code)C.code=String(c.code);if(E)C.cookie=E,C.mentionCookie=E;try{await Kk(D,C)}catch(S){console.error(pe(S)),process.exit(le)}return}let p,g=(c.void??[]).map(String).filter(Boolean);if(c.reask){if(g.length!==1||c.target==="void")console.error("Error: --reask goes with exactly one --void=<permalink> (the question to replace)."),process.exit(le);if(c.waitFor)console.error("Error: --reask posts a new question \u2014 --wait works, --waitFor does not."),process.exit(le);let{token:D,cookie:E}=a(!!c["as-bot"]),C=await We(D,E),S=await Hg(D,g[0],C,!!c["as-bot"],E);if(S==="void")console.error(`\u2717 ${N(g[0])}: already voided \u2014 to ask again, just use slack ask`),process.exit(le);if(!S)process.exit(le);if(p={...S,reason:Be(String(c.reason??"")).trim()},c.target=S.threadTs?`${S.channelId}:${S.threadTs}`:S.channelId,c["channel-id"]=S.channelId,c.question=d??is(S.parsed.question),c.choices=f.length?f:[...S.parsed.reactable,...S.parsed.overflow].map(is),c.body===void 0&&S.parsed.body)c.body=is(S.parsed.body);if(!c.lang)c.lang=S.parsed.lang;if(c.explain===void 0&&S.parsed.explain)c.explain=!0;c.void=void 0}if(!p&&(c.target==="void"||g.length)){let D=c.target==="void"?[c.question,...c.choices??[]]:[];if(c.target!=="void"&&(c.target||c.question||c.choices?.length))console.error("Error: --void voids existing questions \u2014 do not also pass a target/question/choices."),process.exit(le);let E=[...g,...D.map((O)=>String(O??""))].filter(Boolean);if(!E.length)console.error("Error: --void=<permalink> \u2014 which question(s)?"),process.exit(le);if(c.wait||c.waitFor)console.error("Error: --void voids existing questions \u2014 do not also pass --wait/--waitFor."),process.exit(le);let C,S;if(c["as-bot"]){let O=Ne();if(!O)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
569
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);C=O}else C=e(c),S=t(c);let k={links:E,reason:Be(String(c.reason??"")).trim(),asBot:!!c["as-bot"]};if(c["superseded-by"])k.supersededBy=String(c["superseded-by"]);if(c.code)k.code=String(c.code);if(S)k.cookie=S;try{await zk(C,k)}catch(O){console.error(pe(O)),process.exit(le)}return}if(c.target==="collect"){if(!c.question||c.choices?.length)console.error("Error: slack ask collect <permalink> \u2014 exactly one question."),process.exit(le);c.waitFor=String(c.question),c.target=void 0,c.question=void 0}let h=c.waitFor?String(c.waitFor):"",m=Number(c.timeout);if(!Number.isFinite(m)||m<0||m===0&&!h)console.error("Error: --timeout must be a positive number of seconds"),process.exit(le);if(h){if(c.target||c.question||c.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(le);let D,E;if(c["as-bot"]){let C=Ne();if(!C)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
570
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);D=C}else D=e(c),E=t(c);try{let C={link:h,timeout:m,asBot:!!c["as-bot"],json:!!c.json};if(c["explain-exit"])C.explainExit=!0;if(E)C.cookie=E;if(c.after){let S=String(c.after);if(!/^\d{10}\.\d{6}$/.test(S))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${N(S)})`),process.exit(le);C.after=S}await Yk(D,C)}catch(C){console.error(pe(C)),process.exit(le)}return}if(!c.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(le);let y=String(c.question??"").trim();if(!y)console.error("Error: question is empty"),process.exit(le);let w={allowUrlAdjacent:c["allow-url-adjacent"],target:c.target,question:y,choices:(c.choices??[]).map((D)=>String(D).trim()).filter(Boolean),timeout:m};if(c.code)w.code=c.code;if(c.body)w.body=c.body;if(c.lang)w.lang=String(c.lang);if(c.wait)w.wait=!0;if(c.json)w.json=!0;if(typeof c.explain==="boolean")w.explain=c.explain;if(c["explain-exit"])w.explainExit=!0;if(p)w.voidAfter=p;if(c["channel-id"])w.channelId=c["channel-id"];if(c["user-id"])w.userId=c["user-id"];let x;if(c["as-bot"]){let D=Ne();if(!D)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
571
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);if(!w.channelId&&!w.userId&&w.target.startsWith("@"))try{w.userId=await Wt(D,w.target)}catch(E){console.error(`Error: could not resolve ${w.target} to a user for the bot DM.
567
+ ${S} ${k}: ${E(O,S+" ")}`).join("")};console.log("---");for(let[C,S]of Object.entries(D))console.log(`${C}: ${E(S)}`)}return}let w=Intl.DateTimeFormat().resolvedOptions().timeZone,x=y.length?String(T(Y(g.members).map(T)[0]??{}).team_id??""):"";for(let D of y){let E=T(D.profile),C=String(D.name??D.id),S=String(D.id??""),k=String(E.display_name||""),O=String(E.real_name||""),P=String(E.email||""),L=String(D.tz??""),j=[...new Set([k,O].filter((R)=>R&&R!==C))].join(" / "),H=L&&L!==w?L:"",B=String(D.team_id??""),q=D.is_stranger===!0||x&&B&&B!==x?`external:${B||"?"}`:D.is_ultra_restricted===!0?"single-channel guest":D.is_restricted===!0?"guest":"",z=[P,H].filter(Boolean).join(" ");console.log(`@${C} ${S} ${j}${z?" "+z:""}${q?` [${q}]`:""}`)}}).command("get <user>","Show user details",(a)=>a.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(a)=>{let d=e(a),f=t(a),p=a.user.startsWith("@")?a.user:`@${a.user}`,g="";try{g=await Tt(d,p,f)}catch(v){console.error(v instanceof Error?v.message:String(v)),process.exit(1)}let h=T(await os(d,g,f)),m=T(h.user),y=T(m.profile),w=Intl.DateTimeFormat().resolvedOptions().timeZone,x=String(m.name??g),D=String(m.id??g),E=String(y.display_name||""),C=String(y.real_name||""),S=String(y.email||""),k=String(m.tz??""),O=String(y.phone||""),P=String(y.title||"");console.log(`@${x} ${D}`);let L=[...new Set([E,C].filter((v)=>v&&v!==x))];if(L.length)console.log(`name: ${L.join(" / ")}`);if(S)console.log(`email: ${S}`);if(O)console.log(`phone: ${O}`);if(P)console.log(`title: ${P}`);if(k&&k!==w)console.log(`tz: ${k}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(c)=>c.option("limit",{alias:"l",type:"number",default:20}),async(c)=>{await rk(e(c),c.limit)}).command("search <query>","Full-text search",(c)=>c.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(c)=>{await Ng(e(c),c.query,c.count,c.json,t(c))}).command("send <target> <message>","Send a message (confirm-hash safety gate); - as the message reads stdin",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("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."}).option("to",{type:"string",describe:"Permalink of the message you are answering: refuses when it is not in the target's thread (see also `slack reply --to`)"}).option("json",{type:"boolean",default:!1,describe:"On success print one JSON line: {ok, channel, ts, thread_ts?, permalink?}"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to: send even when the message is in another thread"}),async(c)=>{if(c.to&&!c["any-thread"])try{let a=e(c),d=t(c),f=await fs(a,c.to,d),p=dt(c.target)?await fs(a,c.target,d):void 0,g=p?{channel:p.channel,threadTs:p.root}:(()=>{let y=xt(c.target);return{ref:y.ref,...y.threadTs?{threadTs:y.threadTs}:{}}})(),h="channel"in g?g.channel:await ye(a,g.ref,d),m=qa({channel:h,...g.threadTs?{threadTs:g.threadTs}:{}},f);if(m)console.error(`Error: ${m}`),process.exit(2)}catch(a){console.error(pe(a)),process.exit(1)}await s(c)}).command("init [dir]","Create .slack-term/ in a directory: aliases, settings, inbox/outbox (never committed)",(c)=>c.positional("dir",{type:"string",default:".",describe:"Directory to put .slack-term/ in"}).option("prefix",{type:"string",describe:'Put in front of every `slack reply`, e.g. "[design]"'}).option("channel",{type:"string",describe:"Default channel (id)"}).option("as-bot",{type:"boolean",describe:"Reply as the bot by default"}),(c)=>{let{dir:a,created:d}=Ba(c.dir,{...c.prefix?{prefix:c.prefix}:{},...c.channel?{channel:c.channel}:{},...c["as-bot"]!==void 0?{as_bot:c["as-bot"]}:{}});console.log(d.length?`${a}: created ${d.join(", ")}`:`${a}: already set up`)}).command("alias","Name channels and threads for this directory (the nearest .slack-term/)",(c)=>c.command(["ls","list"],"List aliases: name, channel, thread, file",(a)=>a.option("json",{type:"boolean",default:!1}),(a)=>{let d=Xe(),f=rn(d);if(a.json){console.log(JSON.stringify(f.map(({scope:p,...g})=>g)));return}for(let p of f)console.log(`${p.name} ${p.channel} ${p.thread_ts??"-"} ${p.file}${p.note?` ${p.note}`:""}`);if(!f.length)console.error(`no aliases in ${d.dir}${d.global?" (no .slack-term/ above here: `slack init` makes one)":""}`)}).command("set <name> <target>","Name a channel or thread: a permalink (a reply's names its thread root), #chan:<ts>, or #chan",(a)=>a.positional("name",{type:"string",demandOption:!0}).positional("target",{type:"string",demandOption:!0}).option("note",{type:"string",describe:"Free text shown by `alias ls`"}).option("shared",{type:"boolean",default:!1,describe:"Write settings.yml (the allowlist owner's file) instead of settings.local.yml"}).option("dir",{type:"string",describe:"Use the .slack-term/ above this directory instead of the cwd's (with --shared: a lane's dir)"}),async(a)=>{let d=e(a),f=t(a),p=Xe(a.dir),g=dt(a.target)?.ts!==void 0||xt(a.target).threadTs!==void 0,h,m,y="";if(g){let D=await fs(d,a.target,f);if(h=D.channel,m=D.root,D.root!==D.ts)y=` (${D.ts} is a reply: named its thread root)`}else h=await ye(d,xt(a.target).ref,f);let w;try{w=Ua(p,a.name,{channel:h,...m?{thread_ts:m}:{},...a.note?{note:a.note}:{}},a.shared)}catch(D){if(D instanceof Rn)console.error(`Error: ${D.message}`),process.exit(2);throw D}let x=w&&(w.channel!==h||w.thread_ts!==m)?` (was ${w.channel} ${w.thread_ts??"-"})`:"";console.log(`${a.name} \u2192 ${h} ${m??"-"}${y}${x} [${p.dir}]`)}).command(["unset <name>","rm <name>"],"Remove an alias (from settings.local.yml; --shared: also from settings.yml)",(a)=>a.positional("name",{type:"string",demandOption:!0}).option("shared",{type:"boolean",default:!1,describe:"Allow removing one defined in settings.yml"}).option("dir",{type:"string",describe:"Use the .slack-term/ above this directory"}),(a)=>{let d=Xe(a.dir),f;try{f=jf(d,a.name,a.shared)}catch(p){if(p instanceof Rn)console.error(`Error: ${p.message}`),process.exit(2);throw p}if(f==="removed")console.log(`${a.name} removed [${d.dir}]`);else if(f==="absent")console.error(`no alias "${a.name}" in ${d.dir}`),process.exit(2);else console.error(`"${a.name}" is defined in ${d.dir}/settings.yml: edit that file to remove it`),process.exit(2)}).command("who <channel> <ts>","Which registered .slack-term/ dirs subscribe this thread (or message): dir, alias",(a)=>a.positional("channel",{type:"string",demandOption:!0,describe:"Channel id"}).positional("ts",{type:"string",demandOption:!0,describe:"Thread root ts (a reply's own ts is not its thread)"}).option("json",{type:"boolean",default:!1}),(a)=>{let d=Uf(a.channel,a.ts).map((f)=>({dir:G0(f.scope.dir),scope:f.scope.dir,alias:f.name,file:f.file}));if(a.json)console.log(JSON.stringify(d));else for(let f of d)console.log(`${f.dir} ${f.alias}`);if(!d.length)process.exitCode=2}).command("import <tsv>","One-shot: import a legacy allowlist.tsv (<thread_ts> TAB <lane>) into each lane's settings.yml",(a)=>a.positional("tsv",{type:"string",demandOption:!0}).option("channel",{type:"string",demandOption:!0,describe:"The channel every thread is in (for a DM: the DM id)"}).option("lane-dir",{type:"array",string:!0,demandOption:!0,describe:"<lane>=<dir> (a directory holding .slack-term/, made if missing); repeatable"}),(a)=>{let d=new Map;for(let g of a["lane-dir"]??[]){let h=String(g).indexOf("=");if(h<=0)console.error(`Error: --lane-dir ${g}: want <lane>=<dir>`),process.exit(2);d.set(String(g).slice(0,h),String(g).slice(h+1))}let f=0,p=new Map;for(let g of Vc(a.tsv,"utf8").split(`
568
+ `)){let[h,m]=g.trim().split("\t");if(!h||g.startsWith("#")||!m)continue;let y=d.get(m);if(!y||!/^\d{10}\.\d{6}$/.test(h)){p.set(m,(p.get(m)??0)+1);continue}let w={dir:Ba(y).dir,global:!1};Ua(w,`t-${h}`,{channel:a.channel,thread_ts:h,note:"imported from legacy allowlist"},!0),f++}console.log(`imported ${f} subscription(s)`);for(let[g,h]of p)console.error(`skipped ${h} line(s) for lane "${g}" (no --lane-dir, or not a ts)`)}).demandCommand(1,"alias needs a subcommand: ls, set, unset, who, import")).command("reply [dest] [message]","Reply in a thread \u2014 an alias, a permalink or #chan:<ts> \u2014 with the directory's prefix (confirm-hash gate, like send)",(c)=>c.positional("dest",{type:"string",describe:"alias | permalink | #chan:<ts> | <ts> (in settings' channel). Omit with --to"}).positional("message",{type:"string",describe:"Text, or - for stdin"}).option("json",{type:"boolean",default:!1,describe:"On success print one JSON line: {ok, channel, ts, thread_ts, permalink?}"}).option("to",{type:"string",describe:"Permalink of the message you are answering: replies in ITS thread; with a dest, refuses when they differ"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to and a dest: post to dest even when the message is in another thread"}).option("prefix",{type:"string",describe:`Override settings' prefix ("" for none)`}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("broadcast",{type:"boolean",default:!1,describe:"Also send to channel"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real mentions (--no-mentions for literal text)"}),async(c)=>{let{dest:a,message:d}=c;if(c.to&&d===void 0)d=a,a=void 0;if(Kc(d))d=await qc();if(d===void 0||!d.trim())console.error("Error: message is empty"),process.exit(1);if(!a&&!c.to)console.error("Error: reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"),process.exit(2);let f=e(c),p=t(c),g=Xe(),h=ts(g),m;try{let D=await yg(f,p,g,a,c.to,c["any-thread"]);if("error"in D)console.error(`Error: ${D.error}`),process.exit(2);m=D}catch(D){console.error(pe(D)),process.exit(1)}let{channel:y,threadTs:w}=m;if(In(g)&&(c.prefix!==void 0||c["as-bot"]!==void 0&&c["as-bot"]!==(h.as_bot??!1)))console.error(`Error: ${g.dir} is restricted: who it posts as (prefix, as_bot) comes from settings.yml; --prefix / --as-bot are refused`),process.exit(2);let x=Ka(d,c.prefix??h.prefix);if(!x.trim())console.error("Error: message is empty (only the prefix)"),process.exit(1);await s({workspace:c.workspace,target:`${y}:${w}`,message:x,code:c.code,"allow-url-adjacent":c["allow-url-adjacent"],"as-bot":c["as-bot"]??h.as_bot??!1,broadcast:c.broadcast,mentions:c.mentions,json:c.json})}).command("inbox","This directory's .slack-term/inbox/: messages routed here by `slack stream --inbox`",(c)=>c.command(["ls","list"],"Pending messages: ts, from, alias, text (redacted)",(a)=>a.option("json",{type:"boolean",default:!1}),(a)=>{let d=ns(Xe());if(a.json){console.log(JSON.stringify(d.map((f)=>({file:f.file,...f.entry}))));return}for(let f of d)console.log(`${f.entry.ts} ${f.entry.user_name??f.entry.user} ${f.entry.alias} ${f.entry.text.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\t/g,"\\t")}${f.entry.files?` [files: ${f.entry.files}]`:""}`)}).command("listen","Print each message as it arrives in inbox/ (one JSON line each); pending ones first. Exits 0 at --timeout",(a)=>a.option("timeout",{type:"number",default:3600,describe:"Seconds"}).option("new-only",{type:"boolean",default:!1,describe:"Skip what is already pending"}).option("thread",{type:"string",describe:"Only messages in this thread (its root ts)"}).option("alias",{type:"string",describe:"Only messages routed by this alias"}).option("from",{type:"array",string:!0,describe:"Only messages from these user ids; repeatable"}),async(a)=>{let d=Xe(),f=a.from?.length?new Set(a.from.map(String)):void 0,p=(m)=>(!a.thread||(m.thread_ts??m.ts)===a.thread)&&(!a.alias||m.alias===a.alias)&&(!f||f.has(m.user)),g=new Set;if(a["new-only"])for(let m of ns(d))g.add(m.file);let h=Date.now()+a.timeout*1000;for(;;){for(let m of ns(d)){if(g.has(m.file))continue;if(g.add(m.file),p(m.entry))console.log(JSON.stringify({file:m.file,...m.entry}))}if(Date.now()>=h)break;await new Promise((m)=>setTimeout(m,Math.min(500,Math.max(0,h-Date.now()))))}}).command("nudge","Pending messages older than settings' nudge_after_min (default 30): exit 1 when there are any; --eyes also puts \uD83D\uDC40 on each, once",(a)=>a.option("json",{type:"boolean",default:!1}).option("eyes",{type:"boolean",default:!1,describe:"React \uD83D\uDC40 on each overdue message (once per message: recorded as nudged_at)"}).option("as-bot",{type:"boolean",describe:"React via the bot token (default: settings' as_bot)"}),async(a)=>{let d=Xe(),f=gp(d);if(a.eyes){let p=a["as-bot"]??ts(d).as_bot??!1,g=p?Le():e(a);if(!g)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);let h=p?void 0:t(a);for(let m of f){if(m.entry.nudged_at)continue;try{await Ft(g,m.entry.channel,m.entry.ts,"eyes",h)}catch(y){if(!/already_reacted/.test(y instanceof Error?y.message:String(y))){console.error(`\u26A0 ${m.entry.channel}:${m.entry.ts}: could not add \uD83D\uDC40: ${pe(y)}`);continue}}mp(m),m.entry.nudged_at=new Date().toISOString()}}if(a.json)console.log(JSON.stringify(f.map((p)=>({file:p.file,ts:p.entry.ts,channel:p.entry.channel,permalink:p.entry.permalink,waiting_min:Math.round((Date.now()-p.mtimeMs)/60000),...p.entry.nudged_at?{nudged_at:p.entry.nudged_at}:{}}))));else for(let p of f)console.log(`${p.entry.ts} ${Math.round((Date.now()-p.mtimeMs)/60000)} min ${p.entry.permalink}${p.entry.nudged_at?"\t\uD83D\uDC40":""}`);if(f.length)process.exitCode=1}).demandCommand(1,"inbox needs a subcommand: ls, listen, nudge")).command("done <ref..>","Mark inbox messages handled (moved to archived/) without replying: a file name, path or message ts",(c)=>c.positional("ref",{type:"string",array:!0,demandOption:!0}),(c)=>{let a=Xe(),d=0;for(let f of c.ref){let p=Ga(a,f);if(p)console.log(`archived ${p}`);else console.error(`not in ${a.dir}/inbox: ${f}`),d++}if(d)process.exit(2)}).command("outbox","This directory's .slack-term/outbox/: replies queued as files, sent by `outbox flush`",(c)=>c.command("add <dest> <message>","Queue a reply (text redacted before it is written; - reads stdin)",(a)=>a.positional("dest",{type:"string",demandOption:!0,describe:"alias | permalink | #chan:<ts>"}).positional("message",{type:"string",demandOption:!0}).option("in-reply-to",{type:"string",describe:"ts of the inbox message this answers: archived once sent"}),async(a)=>{let d=Kc(a.message)?await qc():a.message;if(!d.trim())console.error("Error: message is empty"),process.exit(1);let f=fp(Xe(),{to:a.dest,text:d,...a["in-reply-to"]?{in_reply_to:a["in-reply-to"]}:{}});if(f.redacted.length)console.error(`\u26A0 redacted before queueing: ${f.redacted.join(", ")}`);console.log(f.file)}).command(["ls","list"],"Queued replies: file, dest, attempts, error",(a)=>a,()=>{for(let a of Xa(Xe()))console.log(`${a.file} ${a.entry.to}${a.entry.attempts?` attempts=${a.entry.attempts} ${a.entry.error??""}`:""}`)}).command("flush","Send every queued reply (prefix, thread and restrict checks as `reply`); a --code covers the whole batch",(a)=>a.option("code",{type:"string",describe:"Safety hash to confirm the batch"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}),async(a)=>{let d=Xe(),f=ts(d),p=Xa(d);if(!p.length){console.error(`nothing in ${d.dir}/outbox`);return}if(In(d)&&a["as-bot"]!==void 0&&a["as-bot"]!==(f.as_bot??!1))console.error(`Error: ${d.dir} is restricted: as_bot comes from settings.yml; --as-bot is refused`),process.exit(2);let g=a["as-bot"]??f.as_bot??!1,h=e(a),m=t(a),y,w;if(g){let k=Le();if(!k)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);y=k}else y=h,w=m;let x=[],D=[];for(let k of p)try{let O=await yg(h,m,d,k.entry.to,void 0);if("error"in O){D.push(`${k.file}: ${O.error}`);continue}let P=Ka(k.entry.text,f.prefix);if(!P.trim()){D.push(`${k.file}: empty`);continue}Ke(P),x.push({item:k,...O,text:P})}catch(O){D.push(`${k.file}: ${pe(O)}`)}for(let k of D)console.error(`refused (stays queued): ${k}`);if(!x.length)process.exit(2);let E=[`OUTBOX \u2014 ${x.length} repl${x.length===1?"y":"ies"}${g?" as the bot":""}:`];for(let k of x)E.push(` \u2192 ${k.channel} thread ${k.threadTs}: ${N(k.text).replace(/\n/g,"\u23CE").slice(0,120)}${k.text.includes("[redacted:")?" (secrets were masked when queued: this is what posts)":""}`);let C=we("outbox",g?"bot":"user",...x.map((k)=>`${k.channel}:${k.threadTs}:${k.text}`));if(a.code!==C)xe(a.code,C,E);let S=0;for(let k of x)try{let O=await Mt(y,k.channel,k.text,k.threadTs,!1,w),P="";try{P=await Pn(y,k.channel,O,w)}catch{}let L=pp(d,k.item,{ts:O,permalink:P,channel:k.channel,thread_ts:k.threadTs});console.log(`\u2713 ${P||O} (${L})`)}catch(O){hp(k.item,pe(O)),console.error(`\u2717 ${k.item.file}: ${pe(O)}`),S++}if(S)process.exit(1)}).demandCommand(1,"outbox needs a subcommand: add, ls, flush")).command("ask [target] [question] [choices..]","Ask a question with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions (confirm-hash safety gate). Lifecycle: --waitFor=<link> collect, --void=<link> void (verb aliases: `ask collect <link>`, `ask void <link\u2026>`)",(c)=>c.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:[...Et],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 (`slack ask void`) \u2014 stop waiting. 7 = only with --explain-exit: \u2139\uFE0F pressed, explain and collect again (the question stays open)."}).option("waitFor",{type:"string",describe:"Collect the answer to a question already posted: pass its permalink. Nothing is posted (except, on an --explain question someone pressed \u2139\uFE0F on, one thread note per question). Same stdout/exit contract as --wait; --timeout 0 checks once and exits 2 if still open."}).option("after",{type:"string",describe:"With --waitFor: the cursor \u2014 everything at or before this ts was already delivered. Text replies there are neither answers nor notes again (pass the `cursor` a previous --json result gave you, or the reply ts an exit 5 printed). Reactions still count."}).option("void",{type:"string",array:!0,describe:"Void question(s) you posted that expired or stopped meaning anything \u2014 --void=<permalink>, repeatable. The text becomes \uD83D\uDEAB with --reason (body kept, options removed), our pills come off, and --wait/--waitFor on it exits 6. Same --code gate. Only your own questions (--as-bot for the bot's). Alias: `slack ask void <link\u2026>`."}).option("reask",{type:"boolean",default:!1,describe:"With ONE --void: post the question again (same channel/thread, same text and choices unless you give new ones as positionals / --body) and void the old one as replaced by it \u2014 one gate for both. The way to change the options of a question someone already answered."}).option("edit",{type:"string",describe:'Change an open question you posted: --edit=<permalink> ["new question" [choices\u2026]] [--body \u2026]. Rebuilt with the ask layout so collect still reads it. Options can change only while nobody has answered (then: --void=<link> --reask). Same --code gate.'}).option("ls",{type:"boolean",default:!1,describe:"List the questions you posted (local sent-log) with their LIVE state: --state open|answered|void|all (default open), --stale 24h, --channel, --json. With --stale it prints the --void command that would retire them."}).option("pending",{type:"boolean",default:!1,describe:"List questions THIS machine asked (local sent-log) that somebody answered but nobody collected, grouped by the asking session, with whether that agent is still alive and the --waitFor line that collects each. Read-only: --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("explain",{type:"boolean",describe:"Also offer an \u2139\uFE0F 'explain' pill (seeded after \u2795): pressing it asks YOU to explain the question in its thread and is never an answer \u2014 the question stays open. --wait/--waitFor report it on stderr (and as `explain` in --json), and post one thread note per question. Default: $SLACK_TERM_ASK_EXPLAIN=1 turns it on; --no-explain turns it off."}).option("explain-exit",{type:"boolean",default:!1,describe:'With --wait / --waitFor: exit 7 (stdout empty; --json status "explain") when someone presses \u2139\uFE0F \u2014 once per question, on the run that posts the thread note. The question stays open: explain, then collect again.'}).option("json",{type:"boolean",default:!1,describe:"With --pending: one JSON object per answered question (sender, answer, collect command). With --wait / --waitFor: print ONE JSON object on stdout \u2014 {status, answer, how, who, notes:[{ts,user,text,permalink}], cursor, permalink} \u2014 instead of the bare answer. `notes` are the audience's replies that are not the answer (thread replies; plain replies too in a 1:1 DM). Exit codes unchanged."}).option("timeout",{type:"number",default:3600,describe:"Overall limit for --wait / --waitFor, in seconds (0 with --waitFor = check once)"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Ask via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(c)=>{if(c.ls||c.pending){if(c.ls&&c.pending)console.error("Error: --ls and --pending are separate lists \u2014 pick one."),process.exit(le);let D=(()=>{try{return e(c)}catch{return}})(),E={};if(D)E.user=D;let C=Le();if(C)E.bot=C;let S=t(c);if(S)E.cookie=S;if(c.pending){if(c.target||c.question||c.waitFor||c.wait||c.void||c.edit)console.error("Error: --pending reads the local log \u2014 do not also pass a target/question or another ask action."),process.exit(le);let O=br(String(c.since));if(O===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${N(String(c.since))})`),process.exit(le);let P={sinceMs:O,json:!!c.json};if(c.channel)P.channel=String(c.channel);try{await Gk(E,P)}catch(L){console.error(pe(L)),process.exit(le)}return}let k={state:String(c.state??"open"),json:!!c.json,limit:Number(c.limit)||50};if(c.stale)k.stale=String(c.stale);if(c.channel)k.channel=String(c.channel);await Yk(E,k);return}let a=(D)=>{if(!D){let C=t(c);return C?{token:e(c),cookie:C}:{token:e(c)}}let E=Le();if(!E)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
569
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);return{token:E}},d=c.target!==void 0&&c.target!=="void"&&c.target!=="collect"?String(c.target):void 0,f=[c.question,...c.choices??[]].filter((D)=>D!==void 0).map(String);if(c.edit){if(c.void||c.wait||c.waitFor)console.error("Error: --edit changes one open question \u2014 do not combine it with --void/--wait/--waitFor."),process.exit(le);let{token:D,cookie:E}=a(!!c["as-bot"]),C={link:String(c.edit),asBot:!!c["as-bot"],mentionToken:D,allowUrlAdjacent:!!c["allow-url-adjacent"]};if(d!==void 0)C.question=d;if(f.length)C.choices=f.map((S)=>S.trim()).filter(Boolean);if(c.body!==void 0)C.body=String(c.body);if(c.lang)C.lang=String(c.lang);if(c.code)C.code=String(c.code);if(E)C.cookie=E,C.mentionCookie=E;try{await zk(D,C)}catch(S){console.error(pe(S)),process.exit(le)}return}let p,g=(c.void??[]).map(String).filter(Boolean);if(c.reask){if(g.length!==1||c.target==="void")console.error("Error: --reask goes with exactly one --void=<permalink> (the question to replace)."),process.exit(le);if(c.waitFor)console.error("Error: --reask posts a new question \u2014 --wait works, --waitFor does not."),process.exit(le);let{token:D,cookie:E}=a(!!c["as-bot"]),C=await Me(D,E),S=await Gg(D,g[0],C,!!c["as-bot"],E);if(S==="void")console.error(`\u2717 ${N(g[0])}: already voided \u2014 to ask again, just use slack ask`),process.exit(le);if(!S)process.exit(le);if(p={...S,reason:je(String(c.reason??"")).trim()},c.target=S.threadTs?`${S.channelId}:${S.threadTs}`:S.channelId,c["channel-id"]=S.channelId,c.question=d??is(S.parsed.question),c.choices=f.length?f:[...S.parsed.reactable,...S.parsed.overflow].map(is),c.body===void 0&&S.parsed.body)c.body=is(S.parsed.body);if(!c.lang)c.lang=S.parsed.lang;if(c.explain===void 0&&S.parsed.explain)c.explain=!0;c.void=void 0}if(!p&&(c.target==="void"||g.length)){let D=c.target==="void"?[c.question,...c.choices??[]]:[];if(c.target!=="void"&&(c.target||c.question||c.choices?.length))console.error("Error: --void voids existing questions \u2014 do not also pass a target/question/choices."),process.exit(le);let E=[...g,...D.map((O)=>String(O??""))].filter(Boolean);if(!E.length)console.error("Error: --void=<permalink> \u2014 which question(s)?"),process.exit(le);if(c.wait||c.waitFor)console.error("Error: --void voids existing questions \u2014 do not also pass --wait/--waitFor."),process.exit(le);let C,S;if(c["as-bot"]){let O=Le();if(!O)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
570
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);C=O}else C=e(c),S=t(c);let k={links:E,reason:je(String(c.reason??"")).trim(),asBot:!!c["as-bot"]};if(c["superseded-by"])k.supersededBy=String(c["superseded-by"]);if(c.code)k.code=String(c.code);if(S)k.cookie=S;try{await Xk(C,k)}catch(O){console.error(pe(O)),process.exit(le)}return}if(c.target==="collect"){if(!c.question||c.choices?.length)console.error("Error: slack ask collect <permalink> \u2014 exactly one question."),process.exit(le);c.waitFor=String(c.question),c.target=void 0,c.question=void 0}let h=c.waitFor?String(c.waitFor):"",m=Number(c.timeout);if(!Number.isFinite(m)||m<0||m===0&&!h)console.error("Error: --timeout must be a positive number of seconds"),process.exit(le);if(h){if(c.target||c.question||c.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(le);let D,E;if(c["as-bot"]){let C=Le();if(!C)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
571
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);D=C}else D=e(c),E=t(c);try{let C={link:h,timeout:m,asBot:!!c["as-bot"],json:!!c.json};if(c["explain-exit"])C.explainExit=!0;if(E)C.cookie=E;if(c.after){let S=String(c.after);if(!/^\d{10}\.\d{6}$/.test(S))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${N(S)})`),process.exit(le);C.after=S}await Vk(D,C)}catch(C){console.error(pe(C)),process.exit(le)}return}if(!c.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(le);let y=String(c.question??"").trim();if(!y)console.error("Error: question is empty"),process.exit(le);let w={allowUrlAdjacent:c["allow-url-adjacent"],target:c.target,question:y,choices:(c.choices??[]).map((D)=>String(D).trim()).filter(Boolean),timeout:m};if(c.code)w.code=c.code;if(c.body)w.body=c.body;if(c.lang)w.lang=String(c.lang);if(c.wait)w.wait=!0;if(c.json)w.json=!0;if(typeof c.explain==="boolean")w.explain=c.explain;if(c["explain-exit"])w.explainExit=!0;if(p)w.voidAfter=p;if(c["channel-id"])w.channelId=c["channel-id"];if(c["user-id"])w.userId=c["user-id"];let x;if(c["as-bot"]){let D=Le();if(!D)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
572
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);if(!w.channelId&&!w.userId&&w.target.startsWith("@"))try{w.userId=await Tt(D,w.target)}catch(E){console.error(`Error: could not resolve ${w.target} to a user for the bot DM.
572
573
  ${E instanceof Error?E.message:String(E)}
573
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(le)}x=D,w.mentionToken=D,w.asBot=!0}else{x=e(c),w.mentionToken=x;let D=t(c);if(D)w.cookie=D,w.mentionCookie=D}try{await Jk(x,w)}catch(D){console.error(pe(D)),process.exit(le)}}).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)",(c)=>c.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --results/--close)"}).positional("question",{type:"string",describe:"The question. @tags are optional here \u2014 unlike `ask`, a poll needs no addressee: anyone who can see it may vote."}).positional("choices",{type:"string",array:!0,describe:"2..10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions for voters to click"}).option("multi",{type:"boolean",default:!1,describe:"Let one person pick several choices (default: one vote per person)"}).option("until",{type:"string",describe:"Deadline shown in the message (display only \u2014 closing is still `--close`)"}).option("results",{type:"string",describe:"Count an existing poll: pass its permalink. Posts nothing; only edit is the invalid-ballot notice in the poll itself (--no-notify to suppress)."}).option("close",{type:"string",describe:"Count an existing poll AND freeze the tally into the message. Only the poster can do this."}).option("names",{type:"boolean",default:!1,describe:"Also list who voted for what (stderr)"}).option("no-notify",{type:"boolean",default:!1,describe:"With --results: do not write the invalid-ballot notice back into the message (keeps it strictly read-only)"}).option("code",{type:"string",describe:"Safety hash to confirm the post"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Post via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient \u2014 and so YOUR OWN vote counts, since the seeds are then the bot's. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(c)=>{let a=c.close?String(c.close):c.results?String(c.results):"";if(c.results&&c.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(pt);let d=()=>{let m=Ne();if(!m)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
574
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(pt);return m};if(a){if(c.target||c.question||c.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(pt);let m=e(c),y=t(c);try{let w={link:a};if(c.close)w.close=!0;if(c.names)w.names=!0;if(c["no-notify"])w.noNotify=!0;if(y)w.cookie=y;if(c["as-bot"])w.writeToken=d();await Zk(m,w)}catch(w){console.error(pe(w)),process.exit(pt)}return}if(!c.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(pt);let f=String(c.question??"").trim();if(!f)console.error("Error: question is empty"),process.exit(pt);let p=(c.choices??[]).map((m)=>String(m).trim()).filter(Boolean);if(p.length<2||p.length>ss)console.error(`Error: poll needs 2..${ss} choices (got ${p.length}). For a free-text question use \`slack ask\`.`),process.exit(pt);let g={target:c.target,question:f,choices:p};if(c.multi)g.multi=!0;if(c.until)g.until=String(c.until);if(c.code)g.code=c.code;if(c.body)g.body=c.body;if(c["allow-url-adjacent"])g.allowUrlAdjacent=!0;if(c["channel-id"])g.channelId=c["channel-id"];if(c["user-id"])g.userId=c["user-id"];let h;if(c["as-bot"]){let m=d();if(!g.channelId&&!g.userId&&g.target.startsWith("@"))try{g.userId=await Wt(m,g.target)}catch(y){console.error(`Error: could not resolve ${g.target} to a user for the bot DM.
574
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(le)}x=D,w.mentionToken=D,w.asBot=!0}else{x=e(c),w.mentionToken=x;let D=t(c);if(D)w.cookie=D,w.mentionCookie=D}try{await qk(x,w)}catch(D){console.error(pe(D)),process.exit(le)}}).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)",(c)=>c.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --results/--close)"}).positional("question",{type:"string",describe:"The question. @tags are optional here \u2014 unlike `ask`, a poll needs no addressee: anyone who can see it may vote."}).positional("choices",{type:"string",array:!0,describe:"2..10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions for voters to click"}).option("multi",{type:"boolean",default:!1,describe:"Let one person pick several choices (default: one vote per person)"}).option("until",{type:"string",describe:"Deadline shown in the message (display only \u2014 closing is still `--close`)"}).option("results",{type:"string",describe:"Count an existing poll: pass its permalink. Posts nothing; only edit is the invalid-ballot notice in the poll itself (--no-notify to suppress)."}).option("close",{type:"string",describe:"Count an existing poll AND freeze the tally into the message. Only the poster can do this."}).option("names",{type:"boolean",default:!1,describe:"Also list who voted for what (stderr)"}).option("no-notify",{type:"boolean",default:!1,describe:"With --results: do not write the invalid-ballot notice back into the message (keeps it strictly read-only)"}).option("code",{type:"string",describe:"Safety hash to confirm the post"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Post via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient \u2014 and so YOUR OWN vote counts, since the seeds are then the bot's. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(c)=>{let a=c.close?String(c.close):c.results?String(c.results):"";if(c.results&&c.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(pt);let d=()=>{let m=Le();if(!m)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
575
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(pt);return m};if(a){if(c.target||c.question||c.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(pt);let m=e(c),y=t(c);try{let w={link:a};if(c.close)w.close=!0;if(c.names)w.names=!0;if(c["no-notify"])w.noNotify=!0;if(y)w.cookie=y;if(c["as-bot"])w.writeToken=d();await tx(m,w)}catch(w){console.error(pe(w)),process.exit(pt)}return}if(!c.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(pt);let f=String(c.question??"").trim();if(!f)console.error("Error: question is empty"),process.exit(pt);let p=(c.choices??[]).map((m)=>String(m).trim()).filter(Boolean);if(p.length<2||p.length>ss)console.error(`Error: poll needs 2..${ss} choices (got ${p.length}). For a free-text question use \`slack ask\`.`),process.exit(pt);let g={target:c.target,question:f,choices:p};if(c.multi)g.multi=!0;if(c.until)g.until=String(c.until);if(c.code)g.code=c.code;if(c.body)g.body=c.body;if(c["allow-url-adjacent"])g.allowUrlAdjacent=!0;if(c["channel-id"])g.channelId=c["channel-id"];if(c["user-id"])g.userId=c["user-id"];let h;if(c["as-bot"]){let m=d();if(!g.channelId&&!g.userId&&g.target.startsWith("@"))try{g.userId=await Tt(m,g.target)}catch(y){console.error(`Error: could not resolve ${g.target} to a user for the bot DM.
575
576
  ${y instanceof Error?y.message:String(y)}
576
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(pt)}h=m,g.mentionToken=m,g.asBot=!0}else{h=e(c),g.mentionToken=h;let m=t(c);if(m)g.cookie=m,g.mentionCookie=m}try{await Xk(h,g)}catch(m){console.error(pe(m)),process.exit(pt)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(c)=>c.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)"}),(c)=>{let a;if(c.since!==void 0){if(a=yr(String(c.since)),a===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${N(String(c.since))})`),process.exit(1)}let d={limit:Number(c.count)||50};if(c.query)d.text=String(c.query);if(c.channel)d.channel=String(c.channel);if(a!==void 0)d.sinceMs=a;if(c.session)d.session=String(c.session);if(c.cwd){let p=z0(String(c.cwd));try{d.cwd=q0(p)}catch{d.cwd=p}}if(c.kind)d.kind=c.kind;let f=ic(d);if(!f)console.error(`Error: ${qs}
577
- (${At()})`),process.exit(1);if(c.json){for(let p of f)console.log(JSON.stringify(p));return}if(!f.length){console.error(`No sent messages match (log: ${At()}).`);return}for(let p of f)console.log(bk(p))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(c)=>c,async()=>{let c=Ne();if(!c)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
578
- Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await Qk(c)}).command("schedule","Manage scheduled messages",(c)=>c.command("send <target> <message>","Schedule a message for later delivery",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("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(a)=>{if(!String(a.message??"").trim())console.error("Error: message is empty"),process.exit(1);let d={target:a.target,message:a.message,at:a.at};if(a.code)d.code=a.code;if(a["allow-url-adjacent"])d.allowUrlAdjacent=!0;if(a["channel-id"])d.channelId=a["channel-id"],d.targetOverride=`--channel-id ${a["channel-id"]}`;if(a["user-id"])d.userId=a["user-id"],d.targetOverride=`--user-id ${a["user-id"]}`;let f;if(a["as-bot"]){let p=Tr();if(!d.channelId&&!d.userId&&d.target.startsWith("@"))try{d.userId=await Wt(e(a),d.target,t(a))}catch(g){console.error(`Error: could not resolve ${d.target} to a user for the bot DM.
577
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(pt)}h=m,g.mentionToken=m,g.asBot=!0}else{h=e(c),g.mentionToken=h;let m=t(c);if(m)g.cookie=m,g.mentionCookie=m}try{await Qk(h,g)}catch(m){console.error(pe(m)),process.exit(pt)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(c)=>c.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)"}),(c)=>{let a;if(c.since!==void 0){if(a=br(String(c.since)),a===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${N(String(c.since))})`),process.exit(1)}let d={limit:Number(c.count)||50};if(c.query)d.text=String(c.query);if(c.channel)d.channel=String(c.channel);if(a!==void 0)d.sinceMs=a;if(c.session)d.session=String(c.session);if(c.cwd){let p=X0(String(c.cwd));try{d.cwd=Y0(p)}catch{d.cwd=p}}if(c.kind)d.kind=c.kind;let f=cc(d);if(!f)console.error(`Error: ${qs}
578
+ (${At()})`),process.exit(1);if(c.json){for(let p of f)console.log(JSON.stringify(p));return}if(!f.length){console.error(`No sent messages match (log: ${At()}).`);return}for(let p of f)console.log(kk(p))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(c)=>c,async()=>{let c=Le();if(!c)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
579
+ Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await nx(c)}).command("schedule","Manage scheduled messages",(c)=>c.command("send <target> <message>","Schedule a message for later delivery",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("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(a)=>{if(!String(a.message??"").trim())console.error("Error: message is empty"),process.exit(1);let d={target:a.target,message:a.message,at:a.at};if(a.code)d.code=a.code;if(a["allow-url-adjacent"])d.allowUrlAdjacent=!0;if(a["channel-id"])d.channelId=a["channel-id"],d.targetOverride=`--channel-id ${a["channel-id"]}`;if(a["user-id"])d.userId=a["user-id"],d.targetOverride=`--user-id ${a["user-id"]}`;let f;if(a["as-bot"]){let p=Or();if(!d.channelId&&!d.userId&&d.target.startsWith("@"))try{d.userId=await Tt(e(a),d.target,t(a))}catch(g){console.error(`Error: could not resolve ${d.target} to a user for the bot DM.
579
580
  ${g instanceof Error?g.message:String(g)}
580
- Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}f=p,d.asBot=!0}else{f=e(a);let p=t(a);if(p)d.cookie=p}await ex(f,d)}).command(["ls","list"],"List pending scheduled messages",(a)=>a.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(a)=>{let d=a.target;if(a["as-bot"]){let f=Tr(),p=a["channel-id"];if(!p&&d?.startsWith("@"))p=await _g(d,f,e(a),t(a));await $g(f,d,p);return}await $g(e(a),d,a["channel-id"],t(a))}).command("rm <target> <id>","Delete a scheduled message",(a)=>a.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(a)=>{let d={target:a.target,id:a.id};if(a.code)d.code=a.code;if(a["channel-id"])d.channelId=a["channel-id"],d.targetOverride=`--channel-id ${a["channel-id"]}`;if(a["as-bot"]){let p=Tr();if(!d.channelId&&d.target.startsWith("@"))d.channelId=await _g(d.target,p,e(a),t(a));d.asBot=!0,await Cg(p,d);return}let f=t(a);if(f)d.cookie=f;await Cg(e(a),d)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(c)=>c.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(c)=>n(c)).command("tick <target> [n]","Tick item n of a posted checklist (\u2B1C n. \u2192 \u2705 n.), nothing else changed; without n, the one open item (confirm-hash gate, like edit)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("n",{type:"number",describe:"Item number"}).option("code",{type:"string",describe:"Safety hash to confirm the edit"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (needed for a message the bot posted)"}),async(c)=>n({...c,tick:c.n!==void 0?{n:c.n}:{},mentions:!1})).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(c)=>c.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(c)=>{let a={target:c.target};if(c.code)a.code=c.code;if(c["channel-id"])a.channelId=c["channel-id"];let d;if(c["as-bot"]){let f=await bg(a.target,e(c),t(c),a.channelId);if(d=f.botToken,f.channelId&&!a.channelId)a.channelId=f.channelId;a.asBot=!0}else{d=e(c);let f=t(c);if(f)a.cookie=f}await xk(d,a)}).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)",(c)=>{let a={type:"boolean",default:!1,describe:"Act via the bot token (xoxb / SLACK_BOT_TOKEN). A board the bot created can only be updated --as-bot: Slack lets a token edit only its own messages."},d=async(p)=>{if(p["as-bot"]){let h=Tr();if(typeof p.workspace==="string"){let m=t(p),[y,w]=await Promise.all([Lt(e(p),m),Lt(h)]);if(y.url!==w.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${w.url}, but -w ${p.workspace} is ${y.url}.
581
- Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:h,asBot:!0}}let g=t(p);return{token:e(p),...g?{cookie:g}:{},asBot:!1}},f=(p)=>{console.error(pe(p)),process.exit(1)};return c.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)",(p)=>p.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",a).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(p)=>{let g=p.file!==void 0;if(g&&p.state!==void 0&&p.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let h=g?Fr(void 0,p.file):Fr(p.state,void 0),m=g?p.state:p.reason;if(h===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let y=await d(p),w={target:p.channel,state:h,asBot:y.asBot,allowUrlAdjacent:p["allow-url-adjacent"]};if(m!==void 0)w.log=Be(m);if(y.cookie)w.cookie=y.cookie;if(typeof p.workspace==="string")w.workspace=p.workspace;if(p.code)w.code=p.code;await _k(y.token,w).catch(f)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(p)=>p.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",a).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(p)=>{let g=p.file!==void 0;if(g&&p.state!==void 0&&p.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let h=g?Fr(void 0,p.file):Fr(p.state,void 0),m=g?p.state:p.reason;if(h===void 0||m===void 0)console.error("Error: `pinlog set` needs the whole new state AND the reason: slack pinlog set <board> '<state>' '<reason>'\n Only a reason, state unchanged: slack pinlog note <board> '<reason>'"),process.exit(2);let y=await d(p),w={target:p.board,state:h,log:Be(m),adopt:p.adopt,asBot:y.asBot,allowUrlAdjacent:p["allow-url-adjacent"]};if(typeof p.workspace==="string")w.workspace=p.workspace;if(y.cookie)w.cookie=y.cookie;if(p.code)w.code=p.code;await Dg(y.token,w).catch(f)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(p)=>p.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",a),async(p)=>{let g=await d(p),h={target:p.board,log:Be(p.reason),logOnly:!0,asBot:g.asBot,allowUrlAdjacent:p["allow-url-adjacent"]};if(typeof p.workspace==="string")h.workspace=p.workspace;if(g.cookie)h.cookie=g.cookie;if(p.code)h.code=p.code;await Dg(g.token,h).catch(f)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(p)=>p.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",a),async(p)=>{let g=await d(p);await Ck(g.token,p.board,g.cookie,p.json).catch(f)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(p)=>p.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",a),async(p)=>{let g=await d(p);await Ak(g.token,p.channel,p.limit,g.cookie).catch(f)}).command("pin <board>",!1,(p)=>p.positional("board",{type:"string",demandOption:!0}).option("as-bot",a),async(p)=>{let g=await d(p);await Fk(g.token,p.board,g.cookie).catch(f)}).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",(c)=>c.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(c)=>{let a={target:c.target,emoji:c.emoji};if(c.remove)a.remove=!0;if(c["channel-id"])a.channelId=c["channel-id"];let d=t(c);if(d)a.cookie=d;try{await Tk(e(c),a)}catch(f){console.error(pe(f)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(c)=>c.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((a)=>{if(a.cache===!1)Ac(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(a)=>a.options(o).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(a)=>{await r(a,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(a)=>a.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(a)=>{let d={target:a.target,state:a.state};if(a["channel-id"])d.channelId=a["channel-id"];let f=t(a);if(f)d.cookie=f;try{await ik(e(a),d)}catch(p){console.error(pe(p)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(a)=>a.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(a)=>{let d={target:a.target,flag:a.flag};if(a.remove)d.remove=!0;if(a["channel-id"])d.channelId=a["channel-id"];let f=t(a);if(f)d.cookie=f;try{await ak(e(a),d)}catch(p){console.error(pe(p)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(a)=>a.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:Cc,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(a)=>{let d={channel:a.in,limit:a.limit};if(a.fix)d.fix=!0;if(a["channel-id"])d.channelId=a["channel-id"];let f=t(a);if(f)d.cookie=f;await ck(e(a),d)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(c)=>c.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((a)=>{if(a.cache===!1)Ac(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(a)=>a.options(o),async(a)=>{await r(a,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(c)=>c.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(c)=>{let a={target:c.target,filePaths:c.file};if(c.title)a.title=c.title;if(c.comment)a.comment=c.comment;if(c["allow-url-adjacent"])a.allowUrlAdjacent=!0;if(c.code)a.code=c.code;if(c["channel-id"])a.channelId=c["channel-id"];if(c["user-id"])a.userId=c["user-id"];let d=t(c);if(d)a.cookie=d;await tx(e(c),a)}).command("files","File commands",(c)=>c.command(["ls","list"],"List files visible to you (files.list)",(a)=>a.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(a)=>{let d={limit:a.limit,format:a.json?"jsonl":a.format};if(a.type)d.types=a.type;if(a.channel)d.channel=a.channel;if(a.user)d.user=a.user;await nx(e(a),t(a),d)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(c)=>c.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(a)=>a.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(a)=>{try{let d={name:a.name,cols:a.col,todo:a.todo===!0};if(a.code!==void 0)d.code=a.code;await ix(d)}catch(d){console.error(pe(d)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(a)=>a.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(a)=>{try{let d={list:a.list,text:a.text,sets:a.set};if(a.code!==void 0)d.code=a.code;await ax(d)}catch(d){console.error(pe(d)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(a)=>a.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(a)=>{try{let d={list:a.list,row:a.row,sets:a.set};if(a.done!==void 0)d.done=a.done;if(a.code!==void 0)d.code=a.code;await cx(d)}catch(d){console.error(pe(d)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(a)=>a.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(a)=>{try{let d={list:a.list,users:a.user,channels:a.channel,level:a.level};if(a.code!==void 0)d.code=a.code;await lx(d)}catch(d){console.error(pe(d)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(a)=>a.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(a)=>{let d=a.json?"jsonl":a.format;try{let f=a.asBot===!0;await ox(f?"":e(a),f?void 0:t(a),a.ref,{limit:a.limit,format:d,asBot:f})}catch(f){console.error(pe(f)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(c)=>c.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(c)=>{await dx(e(c),t(c),c.ref,c.dest)}).command("dump","Bulk export channel history as markdown",(c)=>c.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(c)=>{await lk(e(c),c.days,c.limit,c.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (requires xoxc desktop token). Not `slack todo` (reaction tasks)",(c)=>c.command(["$0","ls","list"],"List your To-dos, soonest due first",(a)=>a.option("filter",{type:"string",choices:[...Oh],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(a)=>{if(!Number.isInteger(a.limit)||a.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${a.limit}).`),process.exit(2);await fk(e(a),t(a),{filter:a.filter,limit:a.limit,json:a.json})}).command("add <target>","Add a message to your To-dos (two-step: preview, then --code)",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"Due time (ISO datetime or Unix ts)"}).option("saved",{type:"boolean",default:!1,describe:"Save it without a checkbox instead of as a to-do"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(a)=>{let d=a.due===void 0?void 0:Eg(a.due);await Ar(e(a),t(a),a.target,{kind:"add",...d?{due:d}:{},saved:a.saved},a.code)}).command(["done <target>","complete <target>"],"Check a to-do off (--undo reopens it)",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("undo",{type:"boolean",default:!1,describe:"Mark it not done again"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(a)=>{await Ar(e(a),t(a),a.target,{kind:"done",undo:a.undo},a.code)}).command("edit <target>","Change a to-do's due date, or switch it between to-do and saved item",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"New due time (ISO datetime or Unix ts), or `none` to clear it"}).option("todo",{type:"boolean",describe:"Make it a to-do (with a checkbox)"}).option("saved",{type:"boolean",describe:"Make it a plain saved item (no checkbox)"}).conflicts("todo","saved").option("code",{type:"string",describe:"Confirmation code from the preview"}),async(a)=>{let d=a.due===void 0?void 0:a.due==="none"?0:Eg(a.due),f=a.todo?!0:a.saved?!1:void 0;await Ar(e(a),t(a),a.target,{kind:"edit",...d===void 0?{}:{due:d},...f===void 0?{}:{todo:f}},a.code)}).command(["rm <target>","remove <target>","delete <target>"],"Remove a message from your To-dos (the message stays)",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(a)=>{await Ar(e(a),t(a),a.target,{kind:"rm"},a.code)})).command("drafts","Manage message drafts (requires xoxc desktop token)",(c)=>c.command(["$0","ls","list"],"List pending drafts",(a)=>a.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(a)=>{await dk(e(a),t(a),a.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(a)=>a.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(a)=>{let d=e(a),f=t(a),p=a.text.join(" ");if(!p)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);Ke(p,a["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let g=await be(d,a.channel,f),h=await _h(d,g,p,f);console.log(`\u2713 Draft created (id: ${T(h.draft).id??"?"})`)}).command("get <id>","Show a draft",(a)=>a.positional("id",{type:"string",demandOption:!0}),async(a)=>{await mk(e(a),t(a),a.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(a)=>a.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(a)=>{let d=e(a),f=t(a),p=a.text.join(" ");if(!p)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);Ke(p,a["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let g=await Gs(d,f),h=Y(g.drafts).map(T).find((D)=>String(D.id)===a.id);if(!h)console.error(`Draft not found: ${a.id}`),process.exit(1);let m=Ir(h),y=await We(d,f),w=ke(m,p,y?.userId??"");if(a.code!==w)Se(a.code,w,["--- Editing draft as -------------------------",Ee(y),"--- Current draft ----------------------------",...m.split(`
581
+ Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}f=p,d.asBot=!0}else{f=e(a);let p=t(a);if(p)d.cookie=p}await sx(f,d)}).command(["ls","list"],"List pending scheduled messages",(a)=>a.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(a)=>{let d=a.target;if(a["as-bot"]){let f=Or(),p=a["channel-id"];if(!p&&d?.startsWith("@"))p=await $g(d,f,e(a),t(a));await Ag(f,d,p);return}await Ag(e(a),d,a["channel-id"],t(a))}).command("rm <target> <id>","Delete a scheduled message",(a)=>a.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(a)=>{let d={target:a.target,id:a.id};if(a.code)d.code=a.code;if(a["channel-id"])d.channelId=a["channel-id"],d.targetOverride=`--channel-id ${a["channel-id"]}`;if(a["as-bot"]){let p=Or();if(!d.channelId&&d.target.startsWith("@"))d.channelId=await $g(d.target,p,e(a),t(a));d.asBot=!0,await Fg(p,d);return}let f=t(a);if(f)d.cookie=f;await Fg(e(a),d)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(c)=>c.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(c)=>n(c)).command("tick <target> [n]","Tick item n of a posted checklist (\u2B1C n. \u2192 \u2705 n.), nothing else changed; without n, the one open item (confirm-hash gate, like edit)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("n",{type:"number",describe:"Item number"}).option("code",{type:"string",describe:"Safety hash to confirm the edit"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (needed for a message the bot posted)"}),async(c)=>n({...c,tick:c.n!==void 0?{n:c.n}:{},mentions:!1})).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(c)=>c.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(c)=>{let a={target:c.target};if(c.code)a.code=c.code;if(c["channel-id"])a.channelId=c["channel-id"];let d;if(c["as-bot"]){let f=await Dg(a.target,e(c),t(c),a.channelId);if(d=f.botToken,f.channelId&&!a.channelId)a.channelId=f.channelId;a.asBot=!0}else{d=e(c);let f=t(c);if(f)a.cookie=f}await Ek(d,a)}).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)",(c)=>{let a={type:"boolean",default:!1,describe:"Act via the bot token (xoxb / SLACK_BOT_TOKEN). A board the bot created can only be updated --as-bot: Slack lets a token edit only its own messages."},d=async(p)=>{if(p["as-bot"]){let h=Or();if(typeof p.workspace==="string"){let m=t(p),[y,w]=await Promise.all([Nt(e(p),m),Nt(h)]);if(y.url!==w.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${w.url}, but -w ${p.workspace} is ${y.url}.
582
+ Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:h,asBot:!0}}let g=t(p);return{token:e(p),...g?{cookie:g}:{},asBot:!1}},f=(p)=>{console.error(pe(p)),process.exit(1)};return c.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)",(p)=>p.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",a).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(p)=>{let g=p.file!==void 0;if(g&&p.state!==void 0&&p.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let h=g?Tr(void 0,p.file):Tr(p.state,void 0),m=g?p.state:p.reason;if(h===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let y=await d(p),w={target:p.channel,state:h,asBot:y.asBot,allowUrlAdjacent:p["allow-url-adjacent"]};if(m!==void 0)w.log=je(m);if(y.cookie)w.cookie=y.cookie;if(typeof p.workspace==="string")w.workspace=p.workspace;if(p.code)w.code=p.code;await Ck(y.token,w).catch(f)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(p)=>p.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",a).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(p)=>{let g=p.file!==void 0;if(g&&p.state!==void 0&&p.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let h=g?Tr(void 0,p.file):Tr(p.state,void 0),m=g?p.state:p.reason;if(h===void 0||m===void 0)console.error("Error: `pinlog set` needs the whole new state AND the reason: slack pinlog set <board> '<state>' '<reason>'\n Only a reason, state unchanged: slack pinlog note <board> '<reason>'"),process.exit(2);let y=await d(p),w={target:p.board,state:h,log:je(m),adopt:p.adopt,asBot:y.asBot,allowUrlAdjacent:p["allow-url-adjacent"]};if(typeof p.workspace==="string")w.workspace=p.workspace;if(y.cookie)w.cookie=y.cookie;if(p.code)w.code=p.code;await xg(y.token,w).catch(f)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(p)=>p.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",a),async(p)=>{let g=await d(p),h={target:p.board,log:je(p.reason),logOnly:!0,asBot:g.asBot,allowUrlAdjacent:p["allow-url-adjacent"]};if(typeof p.workspace==="string")h.workspace=p.workspace;if(g.cookie)h.cookie=g.cookie;if(p.code)h.code=p.code;await xg(g.token,h).catch(f)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(p)=>p.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",a),async(p)=>{let g=await d(p);await Tk(g.token,p.board,g.cookie,p.json).catch(f)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(p)=>p.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",a),async(p)=>{let g=await d(p);await Ok(g.token,p.channel,p.limit,g.cookie).catch(f)}).command("pin <board>",!1,(p)=>p.positional("board",{type:"string",demandOption:!0}).option("as-bot",a),async(p)=>{let g=await d(p);await Rk(g.token,p.board,g.cookie).catch(f)}).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",(c)=>c.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(c)=>{let a={target:c.target,emoji:c.emoji};if(c.remove)a.remove=!0;if(c["channel-id"])a.channelId=c["channel-id"];let d=t(c);if(d)a.cookie=d;try{await Ik(e(c),a)}catch(f){console.error(pe(f)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(c)=>c.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((a)=>{if(a.cache===!1)Oc(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(a)=>a.options(o).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(a)=>{await r(a,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(a)=>a.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(a)=>{let d={target:a.target,state:a.state};if(a["channel-id"])d.channelId=a["channel-id"];let f=t(a);if(f)d.cookie=f;try{await lk(e(a),d)}catch(p){console.error(pe(p)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(a)=>a.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(a)=>{let d={target:a.target,flag:a.flag};if(a.remove)d.remove=!0;if(a["channel-id"])d.channelId=a["channel-id"];let f=t(a);if(f)d.cookie=f;try{await uk(e(a),d)}catch(p){console.error(pe(p)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(a)=>a.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:Tc,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(a)=>{let d={channel:a.in,limit:a.limit};if(a.fix)d.fix=!0;if(a["channel-id"])d.channelId=a["channel-id"];let f=t(a);if(f)d.cookie=f;await dk(e(a),d)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(c)=>c.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((a)=>{if(a.cache===!1)Oc(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(a)=>a.options(o),async(a)=>{await r(a,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}).option("as-bot",{type:"boolean",default:!1,describe:"Upload via the bot token (xoxb / SLACK_BOT_TOKEN); `slack @bot upload \u2026` does this too"}),async(c)=>{let a={target:c.target,filePaths:c.file};if(c.title)a.title=c.title;if(c.comment)a.comment=c.comment;if(c["allow-url-adjacent"])a.allowUrlAdjacent=!0;if(c.code)a.code=c.code;if(c["channel-id"])a.channelId=c["channel-id"];if(c["user-id"])a.userId=c["user-id"];if(c["as-bot"]){let f=Le();if(!f)console.error("Error: --as-bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);await Tg(f,a);return}let d=t(c);if(d)a.cookie=d;await Tg(e(c),a)}).command("files","File commands",(c)=>c.command(["ls","list"],"List files visible to you (files.list)",(a)=>a.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(a)=>{let d={limit:a.limit,format:a.json?"jsonl":a.format};if(a.type)d.types=a.type;if(a.channel)d.channel=a.channel;if(a.user)d.user=a.user;await ox(e(a),t(a),d)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(c)=>c.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(a)=>a.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(a)=>{try{let d={name:a.name,cols:a.col,todo:a.todo===!0};if(a.code!==void 0)d.code=a.code;await cx(d)}catch(d){console.error(pe(d)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(a)=>a.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(a)=>{try{let d={list:a.list,text:a.text,sets:a.set};if(a.code!==void 0)d.code=a.code;await lx(d)}catch(d){console.error(pe(d)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(a)=>a.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(a)=>{try{let d={list:a.list,row:a.row,sets:a.set};if(a.done!==void 0)d.done=a.done;if(a.code!==void 0)d.code=a.code;await ux(d)}catch(d){console.error(pe(d)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(a)=>a.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(a)=>{try{let d={list:a.list,users:a.user,channels:a.channel,level:a.level};if(a.code!==void 0)d.code=a.code;await dx(d)}catch(d){console.error(pe(d)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(a)=>a.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(a)=>{let d=a.json?"jsonl":a.format;try{let f=a.asBot===!0;await ix(f?"":e(a),f?void 0:t(a),a.ref,{limit:a.limit,format:d,asBot:f})}catch(f){console.error(pe(f)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(c)=>c.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(c)=>{await px(e(c),t(c),c.ref,c.dest)}).command("dump","Bulk export channel history as markdown",(c)=>c.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(c)=>{await fk(e(c),c.days,c.limit,c.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (requires xoxc desktop token). Not `slack todo` (reaction tasks)",(c)=>c.command(["$0","ls","list"],"List your To-dos, soonest due first",(a)=>a.option("filter",{type:"string",choices:[...Ih],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(a)=>{if(!Number.isInteger(a.limit)||a.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${a.limit}).`),process.exit(2);await gk(e(a),t(a),{filter:a.filter,limit:a.limit,json:a.json})}).command("add <target>","Add a message to your To-dos (two-step: preview, then --code)",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"Due time (ISO datetime or Unix ts)"}).option("saved",{type:"boolean",default:!1,describe:"Save it without a checkbox instead of as a to-do"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(a)=>{let d=a.due===void 0?void 0:Cg(a.due);await Fr(e(a),t(a),a.target,{kind:"add",...d?{due:d}:{},saved:a.saved},a.code)}).command(["done <target>","complete <target>"],"Check a to-do off (--undo reopens it)",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("undo",{type:"boolean",default:!1,describe:"Mark it not done again"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(a)=>{await Fr(e(a),t(a),a.target,{kind:"done",undo:a.undo},a.code)}).command("edit <target>","Change a to-do's due date, or switch it between to-do and saved item",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"New due time (ISO datetime or Unix ts), or `none` to clear it"}).option("todo",{type:"boolean",describe:"Make it a to-do (with a checkbox)"}).option("saved",{type:"boolean",describe:"Make it a plain saved item (no checkbox)"}).conflicts("todo","saved").option("code",{type:"string",describe:"Confirmation code from the preview"}),async(a)=>{let d=a.due===void 0?void 0:a.due==="none"?0:Cg(a.due),f=a.todo?!0:a.saved?!1:void 0;await Fr(e(a),t(a),a.target,{kind:"edit",...d===void 0?{}:{due:d},...f===void 0?{}:{todo:f}},a.code)}).command(["rm <target>","remove <target>","delete <target>"],"Remove a message from your To-dos (the message stays)",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(a)=>{await Fr(e(a),t(a),a.target,{kind:"rm"},a.code)})).command("drafts","Manage message drafts (requires xoxc desktop token)",(c)=>c.command(["$0","ls","list"],"List pending drafts",(a)=>a.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(a)=>{await hk(e(a),t(a),a.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(a)=>a.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(a)=>{let d=e(a),f=t(a),p=a.text.join(" ");if(!p)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);Ke(p,a["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let g=await ye(d,a.channel,f),h=await $h(d,g,p,f);console.log(`\u2713 Draft created (id: ${T(h.draft).id??"?"})`)}).command("get <id>","Show a draft",(a)=>a.positional("id",{type:"string",demandOption:!0}),async(a)=>{await wk(e(a),t(a),a.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(a)=>a.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(a)=>{let d=e(a),f=t(a),p=a.text.join(" ");if(!p)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);Ke(p,a["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let g=await Gs(d,f),h=Y(g.drafts).map(T).find((D)=>String(D.id)===a.id);if(!h)console.error(`Draft not found: ${a.id}`),process.exit(1);let m=vr(h),y=await Me(d,f),w=we(m,p,y?.userId??"");if(a.code!==w)xe(a.code,w,["--- Editing draft as -------------------------",_e(y),"--- Current draft ----------------------------",...m.split(`
582
583
  `).map((D)=>` ${D}`),"--- Replacing with ---------------------------",...p.split(`
583
- `).map((D)=>` ${D}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let x=await Eh(d,a.id,Gc(h),p,f);console.log(`\u2713 Draft updated (id: ${T(x.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(a)=>a.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(a)=>{let d=e(a),f=t(a),p=await Gs(d,f),g=Y(p.drafts).map(T).find((w)=>String(w.id)===a.id);if(!g)console.error(`Draft not found: ${a.id}`),process.exit(1);let h=Ir(g),m=await We(d,f),y=ke(a.id,h,m?.userId??"");if(a.code!==y)Se(a.code,y,["\u2500-- Deleting draft \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",Ee(m),` id: ${a.id}`,...h.split(`
584
- `).map((w)=>` ${w}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await Ah(d,a.id,f),console.log(`\u2713 Draft deleted (id: ${a.id})`)})).command("auth","Authentication and workspace management",(c)=>c.command("token","Print the active token (or save one with --token)",(a)=>a.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(a)=>{if(a.token===void 0){console.log(xs(a.workspace));return}await Sd({...a.token!==void 0?{token:a.token}:{},...a.name!==void 0?{name:a.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(a)=>{let d=xs(a.workspace),f=d.startsWith("xoxc-")?Ti(a.workspace):void 0,p=[["SLACK_TOKEN",d]];if(f)p.push(["SLACK_COOKIE",f]);let g=p.map(([h,m])=>{if(/[\r\n\0']/.test(m))throw Error(`Cannot export ${h}: unsupported characters in credential`);return`${h}='${m}'`});console.log(g.join(`
585
- `))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(a)=>a.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(a)=>{await _d({...a.bot!==void 0?{bot:a.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(a)=>a.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(d)=>d.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(d)=>{await ia({...d.profile!==void 0?{profile:d.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(d)=>d.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(d)=>{await aa({...d.workspace!==void 0?{workspace:d.workspace}:{}})}).option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}).option("from-desktop",{type:"boolean",default:!1,describe:"Import the Slack Desktop token without scanning a browser"}).option("from-chrome",{type:"boolean",default:!1,describe:"Import the desktop token and Chrome cookie"}).option("from-firefox",{type:"boolean",default:!1,describe:"Import the desktop token and Firefox cookie"}).option("from-all",{type:"boolean",default:!1,describe:"Import the desktop token and scan Chrome and Firefox"}).command("$0",!1,()=>{},async(d)=>{await Is({...d.token!==void 0?{token:d.token}:{},...d.name!==void 0?{name:d.name}:{},yes:d.yes,fromDesktop:d.fromDesktop,fromChrome:d.fromChrome,fromFirefox:d.fromFirefox,fromAll:d.fromAll})}),async(a)=>{await Is({...a.token!==void 0?{token:a.token}:{},...a.name!==void 0?{name:a.name}:{},yes:a.yes,fromDesktop:a.fromDesktop,fromChrome:a.fromChrome,fromFirefox:a.fromFirefox,fromAll:a.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(a)=>a.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(a)=>Ed({...a.workspace!==void 0?{workspace:a.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(a)=>a.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)"}),(a)=>$d({envfile:a.envfile,...a.workspace!==void 0?{workspace:a.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let a=Fi();if(a.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:d,profile:f,current:p}of a)console.log(`${p?"* ":" "}${d} ${f.team} (${f.user}) ${f.url??""}`)}).command("use <name>","Switch active workspace",(a)=>a.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(a)=>{if(!a.g)Y0(Tt(process.cwd(),".slack-cli"));ju(a.name,a.g),console.log(`Switched to workspace "${a.name}" ${a.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(a)=>a.positional("name",{type:"string",demandOption:!0}),(a)=>{Bu(a.name),console.log(`Removed workspace "${a.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(a)=>a.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(a)=>{await xd({...a.workspace!==void 0?{workspace:a.workspace}:{},...a.profile!==void 0?{profile:a.profile}:{},yes:a.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(a)=>a.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(a)=>{await aa({...a.workspace!==void 0?{workspace:a.workspace}:{},yes:a.yes})}).command("$0",!1,()=>{},()=>{c.showHelp(),process.exit(0)})).command("relay","Set up / check the real-time relay for `slack stream` (a Cloudflare Worker)",(c)=>c.command("init [dir]","Scaffold a deployable relay Worker folder (local files only; prints a fresh RELAY_TOKEN and the next steps)",(a)=>a.positional("dir",{type:"string",default:ya,describe:"Folder to create"}).option("name",{type:"string",describe:"Worker name (default: the folder's name)"}).option("force",{type:"boolean",default:!1,describe:"Overwrite files that already exist"}).option("slack-term",{type:"string",describe:"slack-term dependency spec (default: this CLI's version), e.g. latest or file:../slack-term"}),(a)=>{let d=Yd(a.dir,{force:a.force,...a.name!==void 0?{name:a.name}:{},...a["slack-term"]!==void 0?{slackTerm:a["slack-term"]}:{}});if(!d.ok){console.error(`slack relay init: ${d.error}`);for(let f of d.existing??[])console.error(` exists: ${f}`);process.exit(2)}console.log(Gd(d))}).command("health","GET /health on the relay (SLACK_RELAY_URL / SLACK_RELAY_TOKEN); exit 0 = ok",(a)=>a.option("url",{type:"string",describe:"Relay URL (default: $SLACK_RELAY_URL)"}).option("token",{type:"string",describe:"Relay token (default: $SLACK_RELAY_TOKEN)"}),async(a)=>{let d=await Xd(a.url??process.env.SLACK_RELAY_URL,a.token??process.env.SLACK_RELAY_TOKEN);(d.code===0?console.log:console.error)(d.out),process.exit(d.code)}).demandCommand(1,"Specify a relay subcommand (init, health)")).command("stream","Print every new message matching --grep, across all channels the identity is in (threads included); resumable",(c)=>c.option("grep",{alias:"e",type:"string",demandOption:!0,describe:"Regex matched against each message's text (raw, e.g. <@U00000001>). Non-matching messages are never printed or logged"}).option("ignore-case",{alias:"i",type:"boolean",default:!1,describe:"Case-insensitive --grep"}).option("channel",{type:"array",string:!0,describe:"Only these channels (#name, id or permalink); repeatable"}).option("replies-to",{type:"array",string:!0,describe:"Also print replies in threads this id started or replied in (user U\u2026/bot B\u2026; `self` = the streaming identity), --grep or not; repeatable"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per match: type, channel{id,name}, ts, thread_ts, user{id,name}, text, permalink, match (grep | replies-to)"}).option("once",{type:"boolean",default:!1,describe:"Scan once from the saved cursor (or --since) and exit: 0 = matches printed, 2 = none, 3 = failure"}).option("since",{type:"string",describe:"Replay from this long ago (e.g. 30m, 2h), ignoring the saved cursor"}).option("interval",{type:"string",default:"45s",describe:"Poll interval (e.g. 30s, 2m)"}).option("thread-window",{type:"string",default:"3d",describe:"Watch replies in threads whose parent is at most this old"}).option("thread-scan",{type:"string",default:"3m",describe:"Polling: re-read each channel's whole --thread-window this often (cycles in between read only what is new)"}).option("calls-per-min",{type:"number",default:40,describe:"Polling: pace conversations.history/replies to this many calls per minute (0 = unpaced)"}).option("state",{type:"string",describe:"Cursor file (default: one per identity+grep+channels under $XDG_STATE_HOME/slack-term/stream/)"}).option("as-user",{type:"boolean",default:!1,describe:"Stream as the user identity (sees the user's DMs) instead of the bot"}).option("relay",{type:"boolean",default:!0,describe:"Use the doorbell relay (`slack relay init`) when SLACK_RELAY_URL and SLACK_RELAY_TOKEN are set; --no-relay polls only"}).option("reconcile",{type:"string",default:"5m",describe:"While the relay is connected, poll this rarely as a safety net"}).option("inbox",{type:"boolean",default:!1,describe:"Also write each match into the inbox/ of every .slack-term/ that subscribes its thread (redacted, text-only)"}).option("reactions",{type:"boolean",default:!1,describe:'Relay only: also print reaction_added bells as {type: "reaction", channel, ts, user} (the emoji: reactions.get)'}),async(c)=>{let a,d,f,p,g,h;try{a=new RegExp(c.grep,c["ignore-case"]?"i":""),f=Qt(c.interval)*1000,p=Qt(c["thread-window"]),g=Qt(c["thread-scan"]),h=c.since!==void 0?Qt(c.since):void 0,d=Qt(c.reconcile)*1000}catch(R){console.error(`slack stream: ${R instanceof Error?R.message:String(R)}`),process.exit(1)}let m=Ne(),y=c["as-user"]===!0||!m,w=y?e(c):m,x=y?t(c):void 0;if(!m&&c["as-user"]!==!0)console.error("slack stream: no bot token (SLACK_BOT_TOKEN) \u2014 streaming as the USER identity, which includes its DMs.");let D;try{D=await Lt(w,x)}catch(R){console.error(`slack stream: fatal: ${R instanceof Error?R.message:String(R)}`),process.exit(3)}let E=new Set([D.userId].filter(Boolean)),C=new Set([D.botId].filter(Boolean));if(y&&m)try{let R=await Lt(m);if(R.userId)E.add(R.userId);if(R.botId)C.add(R.botId)}catch{}let S;if(c["replies-to"]?.length){S=new Set;for(let R of c["replies-to"].map(String)){if(R==="self"){for(let te of[D.userId,D.botId])if(te)S.add(te);continue}if(!/^[UWB][A-Z0-9]{2,}$/.test(R))console.error(`slack stream: --replies-to: "${R}" is not a user or bot id (U\u2026/W\u2026/B\u2026) or "self"`),process.exit(1);if(S.add(R),R.startsWith("B"))try{let{userId:te}=await Xp(w,R,x);if(te)S.add(te)}catch(te){console.error(`slack stream: --replies-to ${R}: cannot resolve its bot user id (${te instanceof Error?te.message:String(te)}); threads where it shows as a user id are missed`)}}}let k;if(c.channel?.length)try{k=[];for(let R of c.channel)k.push(await be(w,String(R),x))}catch(R){console.error(`slack stream: --channel: ${R instanceof Error?R.message:String(R)}`),process.exit(1)}let O=Ag("sha256").update(JSON.stringify([D.url,D.userId,a.source,a.flags,[...k??[]].sort(),...c["replies-to"]?.length?[[...c["replies-to"].map(String)].sort()]:[]])).digest("hex").slice(0,16),P=process.env.XDG_STATE_HOME||Tt(Wc(),".local","state"),L=c.state??Tt(P,"slack-term","stream",`${O}.json`);console.error(`slack stream: as ${y?"user":"bot"} @${D.user} (${D.userId}); state ${L}`);let v=process.env.SLACK_RELAY_URL,j=process.env.SLACK_RELAY_TOKEN,H=c.relay&&!y&&!c.once&&v&&j?{url:v,subscribe:Kd(v,j,void 0,{transport:Jd(process.env.SLACK_RELAY_TRANSPORT)}),reconcileMs:d}:void 0;if(c.relay&&y&&v)console.error("slack stream: relay not used with --as-user (it only sees the bot's channels)");let B=!c.relay?"--no-relay":y?v?"--as-user: the relay only rings for the bot's channels":"streaming as the user; the relay serves the bot identity":"SLACK_RELAY_URL / SLACK_RELAY_TOKEN not set",q=new AbortController;process.on("SIGINT",()=>q.abort()),process.on("SIGTERM",()=>q.abort()),zp(0);let z=await jd(Md(w,x),{grep:a,...S?{repliesTo:S}:{},...k?{channels:k}:{},selfUsers:E,selfBots:C,json:c.json,reactions:c.reactions,...c.inbox?{onMatch:(R,te)=>{try{let Q=[w,x,process.env.SLACK_RELAY_TOKEN].filter((oe)=>!!oe),M=ap({...R,...te?{files:te}:{}},void 0,new Date,Q);if(M.length)console.error(`slack stream: delivered ${R.channel.id}:${R.ts} to ${M.length} inbox(es)`)}catch(Q){console.error(`slack stream: inbox delivery failed: ${Q instanceof Error?Q.message:String(Q)}`)}}}:{},once:c.once,...h!==void 0?{sinceSec:h}:{},intervalMs:f,threadWindowSec:p,threadScanSec:g,callsPerMin:c["calls-per-min"],...H?{}:{pollReason:B},statePath:L,teamUrl:D.url,identity:D.userId,signal:q.signal,...H?{relay:H}:{}});process.exit(z)}).command("tail [target]","Stream new messages in real time (like tail -f)",(c)=>c.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(c)=>{let a=e(c),d=t(c),f=new AbortController;process.on("SIGINT",()=>{f.abort(),process.exit(0)}),await Rd(a,c.target,{...c.since!==void 0?{since:c.since}:{},...c.thread!==void 0?{thread:c.thread}:{},...c["watch-thread"]!==void 0?{watchThread:c["watch-thread"]}:{},me:c.me,interval:c.interval,...c.timeout!==void 0?{timeout:c.timeout}:{},...c["exit-on-message"]===!0?{exitOnMessage:!0}:{},...d!==void 0?{cookie:d}:{},...c.rtm===!1?{noRtm:!0}:{}},f.signal)}).command("login",!1,(c)=>c.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(c)=>{await Is({...c.token!==void 0?{token:c.token}:{},...c.name!==void 0?{name:c.name}:{},yes:c.yes,fromDesktop:c.fromDesktop,fromChrome:c.fromChrome,fromFirefox:c.fromFirefox,fromAll:c.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}fx().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
584
+ `).map((D)=>` ${D}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let x=await Ch(d,a.id,el(h),p,f);console.log(`\u2713 Draft updated (id: ${T(x.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(a)=>a.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(a)=>{let d=e(a),f=t(a),p=await Gs(d,f),g=Y(p.drafts).map(T).find((w)=>String(w.id)===a.id);if(!g)console.error(`Draft not found: ${a.id}`),process.exit(1);let h=vr(g),m=await Me(d,f),y=we(a.id,h,m?.userId??"");if(a.code!==y)xe(a.code,y,["\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",_e(m),` id: ${a.id}`,...h.split(`
585
+ `).map((w)=>` ${w}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await Th(d,a.id,f),console.log(`\u2713 Draft deleted (id: ${a.id})`)})).command("auth","Authentication and workspace management",(c)=>c.command("token","Print the active token (or save one with --token)",(a)=>a.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(a)=>{if(a.token===void 0){console.log(xs(a.workspace));return}await $d({...a.token!==void 0?{token:a.token}:{},...a.name!==void 0?{name:a.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(a)=>{let d=xs(a.workspace),f=d.startsWith("xoxc-")?Oi(a.workspace):void 0,p=[["SLACK_TOKEN",d]];if(f)p.push(["SLACK_COOKIE",f]);let g=p.map(([h,m])=>{if(/[\r\n\0']/.test(m))throw Error(`Cannot export ${h}: unsupported characters in credential`);return`${h}='${m}'`});console.log(g.join(`
586
+ `))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(a)=>a.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(a)=>{await Cd({...a.bot!==void 0?{bot:a.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(a)=>a.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(d)=>d.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(d)=>{await ca({...d.profile!==void 0?{profile:d.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(d)=>d.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(d)=>{await la({...d.workspace!==void 0?{workspace:d.workspace}:{}})}).option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}).option("from-desktop",{type:"boolean",default:!1,describe:"Import the Slack Desktop token without scanning a browser"}).option("from-chrome",{type:"boolean",default:!1,describe:"Import the desktop token and Chrome cookie"}).option("from-firefox",{type:"boolean",default:!1,describe:"Import the desktop token and Firefox cookie"}).option("from-all",{type:"boolean",default:!1,describe:"Import the desktop token and scan Chrome and Firefox"}).command("$0",!1,()=>{},async(d)=>{await Is({...d.token!==void 0?{token:d.token}:{},...d.name!==void 0?{name:d.name}:{},yes:d.yes,fromDesktop:d.fromDesktop,fromChrome:d.fromChrome,fromFirefox:d.fromFirefox,fromAll:d.fromAll})}),async(a)=>{await Is({...a.token!==void 0?{token:a.token}:{},...a.name!==void 0?{name:a.name}:{},yes:a.yes,fromDesktop:a.fromDesktop,fromChrome:a.fromChrome,fromFirefox:a.fromFirefox,fromAll:a.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(a)=>a.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(a)=>Ad({...a.workspace!==void 0?{workspace:a.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(a)=>a.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)"}),(a)=>Fd({envfile:a.envfile,...a.workspace!==void 0?{workspace:a.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let a=Ti();if(a.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:d,profile:f,current:p}of a)console.log(`${p?"* ":" "}${d} ${f.team} (${f.user}) ${f.url??""}`)}).command("use <name>","Switch active workspace",(a)=>a.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(a)=>{if(!a.g)V0(Ot(process.cwd(),".slack-cli"));qu(a.name,a.g),console.log(`Switched to workspace "${a.name}" ${a.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(a)=>a.positional("name",{type:"string",demandOption:!0}),(a)=>{Ku(a.name),console.log(`Removed workspace "${a.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(a)=>a.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(a)=>{await Ed({...a.workspace!==void 0?{workspace:a.workspace}:{},...a.profile!==void 0?{profile:a.profile}:{},yes:a.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(a)=>a.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(a)=>{await la({...a.workspace!==void 0?{workspace:a.workspace}:{},yes:a.yes})}).command("$0",!1,()=>{},()=>{c.showHelp(),process.exit(0)})).command("relay","Set up / check the real-time relay for `slack stream` (a Cloudflare Worker)",(c)=>c.command("init [dir]","Scaffold a deployable relay Worker folder (local files only; prints a fresh RELAY_TOKEN and the next steps)",(a)=>a.positional("dir",{type:"string",default:wa,describe:"Folder to create"}).option("name",{type:"string",describe:"Worker name (default: the folder's name)"}).option("force",{type:"boolean",default:!1,describe:"Overwrite files that already exist"}).option("slack-term",{type:"string",describe:"slack-term dependency spec (default: this CLI's version), e.g. latest or file:../slack-term"}),(a)=>{let d=Vd(a.dir,{force:a.force,...a.name!==void 0?{name:a.name}:{},...a["slack-term"]!==void 0?{slackTerm:a["slack-term"]}:{}});if(!d.ok){console.error(`slack relay init: ${d.error}`);for(let f of d.existing??[])console.error(` exists: ${f}`);process.exit(2)}console.log(Zd(d))}).command("health","GET /health on the relay (SLACK_RELAY_URL / SLACK_RELAY_TOKEN); exit 0 = ok",(a)=>a.option("url",{type:"string",describe:"Relay URL (default: $SLACK_RELAY_URL)"}).option("token",{type:"string",describe:"Relay token (default: $SLACK_RELAY_TOKEN)"}),async(a)=>{let d=await Qd(a.url??process.env.SLACK_RELAY_URL,a.token??process.env.SLACK_RELAY_TOKEN);(d.code===0?console.log:console.error)(d.out),process.exit(d.code)}).demandCommand(1,"Specify a relay subcommand (init, health)")).command("stream","Print every new message matching --grep, across all channels the identity is in (threads included); resumable",(c)=>c.option("grep",{alias:"e",type:"string",demandOption:!0,describe:"Regex matched against each message's text (raw, e.g. <@U00000001>). Non-matching messages are never printed or logged"}).option("ignore-case",{alias:"i",type:"boolean",default:!1,describe:"Case-insensitive --grep"}).option("channel",{type:"array",string:!0,describe:"Only these channels (#name, id or permalink); repeatable"}).option("replies-to",{type:"array",string:!0,describe:"Also print replies in threads this id started or replied in (user U\u2026/bot B\u2026; `self` = the streaming identity), --grep or not; repeatable"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per match: type, channel{id,name}, ts, thread_ts, user{id,name}, text, permalink, match (grep | replies-to)"}).option("once",{type:"boolean",default:!1,describe:"Scan once from the saved cursor (or --since) and exit: 0 = matches printed, 2 = none, 3 = failure"}).option("since",{type:"string",describe:"Replay from this long ago (e.g. 30m, 2h), ignoring the saved cursor"}).option("interval",{type:"string",default:"45s",describe:"Poll interval (e.g. 30s, 2m)"}).option("thread-window",{type:"string",default:"3d",describe:"Watch replies in threads whose parent is at most this old"}).option("thread-scan",{type:"string",default:"3m",describe:"Polling: re-read each channel's whole --thread-window this often (cycles in between read only what is new)"}).option("calls-per-min",{type:"number",default:40,describe:"Polling: pace conversations.history/replies to this many calls per minute (0 = unpaced)"}).option("state",{type:"string",describe:"Cursor file (default: one per identity+grep+channels under $XDG_STATE_HOME/slack-term/stream/)"}).option("as-user",{type:"boolean",default:!1,describe:"Stream as the user identity (sees the user's DMs) instead of the bot"}).option("relay",{type:"boolean",default:!0,describe:"Use the doorbell relay (`slack relay init`) when SLACK_RELAY_URL and SLACK_RELAY_TOKEN are set; --no-relay polls only"}).option("reconcile",{type:"string",default:"5m",describe:"While the relay is connected, poll this rarely as a safety net"}).option("inbox",{type:"boolean",default:!1,describe:"Also write each match into the inbox/ of every .slack-term/ that subscribes its thread (redacted, text-only)"}).option("reactions",{type:"boolean",default:!1,describe:'Relay only: also print reaction_added bells as {type: "reaction", channel, ts, user} (the emoji: reactions.get)'}),async(c)=>{let a,d,f,p,g,h;try{a=new RegExp(c.grep,c["ignore-case"]?"i":""),f=en(c.interval)*1000,p=en(c["thread-window"]),g=en(c["thread-scan"]),h=c.since!==void 0?en(c.since):void 0,d=en(c.reconcile)*1000}catch(R){console.error(`slack stream: ${R instanceof Error?R.message:String(R)}`),process.exit(1)}let m=Le(),y=c["as-user"]===!0||!m,w=y?e(c):m,x=y?t(c):void 0;if(!m&&c["as-user"]!==!0)console.error("slack stream: no bot token (SLACK_BOT_TOKEN) \u2014 streaming as the USER identity, which includes its DMs.");let D;try{D=await Nt(w,x)}catch(R){console.error(`slack stream: fatal: ${R instanceof Error?R.message:String(R)}`),process.exit(3)}let E=new Set([D.userId].filter(Boolean)),C=new Set([D.botId].filter(Boolean));if(y&&m)try{let R=await Nt(m);if(R.userId)E.add(R.userId);if(R.botId)C.add(R.botId)}catch{}let S;if(c["replies-to"]?.length){S=new Set;for(let R of c["replies-to"].map(String)){if(R==="self"){for(let te of[D.userId,D.botId])if(te)S.add(te);continue}if(!/^[UWB][A-Z0-9]{2,}$/.test(R))console.error(`slack stream: --replies-to: "${R}" is not a user or bot id (U\u2026/W\u2026/B\u2026) or "self"`),process.exit(1);if(S.add(R),R.startsWith("B"))try{let{userId:te}=await Qp(w,R,x);if(te)S.add(te)}catch(te){console.error(`slack stream: --replies-to ${R}: cannot resolve its bot user id (${te instanceof Error?te.message:String(te)}); threads where it shows as a user id are missed`)}}}let k;if(c.channel?.length)try{k=[];for(let R of c.channel)k.push(await ye(w,String(R),x))}catch(R){console.error(`slack stream: --channel: ${R instanceof Error?R.message:String(R)}`),process.exit(1)}let O=Og("sha256").update(JSON.stringify([D.url,D.userId,a.source,a.flags,[...k??[]].sort(),...c["replies-to"]?.length?[[...c["replies-to"].map(String)].sort()]:[]])).digest("hex").slice(0,16),P=process.env.XDG_STATE_HOME||Ot(Hc(),".local","state"),L=c.state??Ot(P,"slack-term","stream",`${O}.json`);console.error(`slack stream: as ${y?"user":"bot"} @${D.user} (${D.userId}); state ${L}`);let v=process.env.SLACK_RELAY_URL,j=process.env.SLACK_RELAY_TOKEN,H=c.relay&&!y&&!c.once&&v&&j?{url:v,subscribe:zd(v,j,void 0,{transport:qd(process.env.SLACK_RELAY_TRANSPORT)}),reconcileMs:d}:void 0;if(c.relay&&y&&v)console.error("slack stream: relay not used with --as-user (it only sees the bot's channels)");let B=!c.relay?"--no-relay":y?v?"--as-user: the relay only rings for the bot's channels":"streaming as the user; the relay serves the bot identity":"SLACK_RELAY_URL / SLACK_RELAY_TOKEN not set",q=new AbortController;process.on("SIGINT",()=>q.abort()),process.on("SIGTERM",()=>q.abort()),Xp(0);let z=await Ud(Wd(w,x),{grep:a,...S?{repliesTo:S}:{},...k?{channels:k}:{},selfUsers:E,selfBots:C,json:c.json,reactions:c.reactions,...c.inbox?{onMatch:(R,te)=>{try{let Q=[w,x,process.env.SLACK_RELAY_TOKEN].filter((oe)=>!!oe),M=up({...R,...te?{files:te}:{}},void 0,new Date,Q);if(M.length)console.error(`slack stream: delivered ${R.channel.id}:${R.ts} to ${M.length} inbox(es)`)}catch(Q){console.error(`slack stream: inbox delivery failed: ${Q instanceof Error?Q.message:String(Q)}`)}}}:{},once:c.once,...h!==void 0?{sinceSec:h}:{},intervalMs:f,threadWindowSec:p,threadScanSec:g,callsPerMin:c["calls-per-min"],...H?{}:{pollReason:B},statePath:L,teamUrl:D.url,identity:D.userId,signal:q.signal,...H?{relay:H}:{}});process.exit(z)}).command("tail [target]","Stream new messages in real time (like tail -f)",(c)=>c.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(c)=>{let a=e(c),d=t(c),f=new AbortController;process.on("SIGINT",()=>{f.abort(),process.exit(0)}),await Pd(a,c.target,{...c.since!==void 0?{since:c.since}:{},...c.thread!==void 0?{thread:c.thread}:{},...c["watch-thread"]!==void 0?{watchThread:c["watch-thread"]}:{},me:c.me,interval:c.interval,...c.timeout!==void 0?{timeout:c.timeout}:{},...c["exit-on-message"]===!0?{exitOnMessage:!0}:{},...d!==void 0?{cookie:d}:{},...c.rtm===!1?{noRtm:!0}:{}},f.signal)}).command("login",!1,(c)=>c.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(c)=>{await Is({...c.token!==void 0?{token:c.token}:{},...c.name!==void 0?{name:c.name}:{},yes:c.yes,fromDesktop:c.fromDesktop,fromChrome:c.fromChrome,fromFirefox:c.fromFirefox,fromAll:c.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}hx().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});