slack-term 1.55.2 → 1.55.3
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/README.md +6 -4
- package/dist/cli.js +220 -217
- package/package.json +1 -1
- package/ts/cli.ts +22 -4
- package/ts/identity.ts +16 -5
package/dist/cli.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{createRequire as vm}from"node:module";var Am=Object.create;var{getPrototypeOf:Tm,defineProperty:gl,getOwnPropertyNames:Fm}=Object;var ml=Object.prototype.hasOwnProperty;function Om(e){return this[e]}var Rm,Im,yl=(e,t,n)=>{var s=e!=null&&typeof e==="object";if(s){var r=t?Rm??=new WeakMap:Im??=new WeakMap,o=r.get(e);if(o)return o}n=e!=null?Am(Tm(e)):{};let i=t||!e||!e.__esModule||!ml.call(e,"default")?gl(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let l of Fm(e))if(!ml.call(i,l))gl(i,l,{get:Om.bind(e,l),enumerable:!0})}if(s)r.set(e,i);return i};var bl=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var gs=vm(import.meta.url);var Ll=bl(function(yS,Pl){Pl.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 cu=bl(function(o_,au){au.exports=function(t){if(t===void 0)t=2;if(t>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+t+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var n=Error.prepareStackTrace;Error.prepareStackTrace=function(r,o){return o};var s=Error().stack;if(Error.prepareStackTrace=n,s!==null&&typeof s==="object")return s[t]?s[t].getFileName():void 0}});import{createHash as rm}from"crypto";import{existsSync as om,readFileSync as ll,mkdirSync as Ek,realpathSync as $k,writeFileSync as im}from"fs";import{spawnSync as Ck}from"child_process";import{homedir as Bo}from"os";import{dirname as Ak,join as gt,resolve as Tk}from"path";import{notStrictEqual as wy,strictEqual as Dy}from"assert";var Pm={right:Mm,center:Bm};class Dl{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 vm}from"node:module";var Am=Object.create;var{getPrototypeOf:Tm,defineProperty:ml,getOwnPropertyNames:Fm}=Object;var yl=Object.prototype.hasOwnProperty;function Om(e){return this[e]}var Rm,Im,bl=(e,t,n)=>{var s=e!=null&&typeof e==="object";if(s){var r=t?Rm??=new WeakMap:Im??=new WeakMap,o=r.get(e);if(o)return o}n=e!=null?Am(Tm(e)):{};let i=t||!e||!e.__esModule||!yl.call(e,"default")?ml(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let l of Fm(e))if(!yl.call(i,l))ml(i,l,{get:Om.bind(e,l),enumerable:!0})}if(s)r.set(e,i);return i};var wl=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ms=vm(import.meta.url);var Nl=wl(function(yS,Ll){Ll.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 lu=wl(function(o_,cu){cu.exports=function(t){if(t===void 0)t=2;if(t>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+t+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var n=Error.prepareStackTrace;Error.prepareStackTrace=function(r,o){return o};var s=Error().stack;if(Error.prepareStackTrace=n,s!==null&&typeof s==="object")return s[t]?s[t].getFileName():void 0}});import{createHash as rm}from"crypto";import{existsSync as om,readFileSync as ul,mkdirSync as ED,realpathSync as $D,writeFileSync as im}from"fs";import{spawnSync as CD}from"child_process";import{homedir as jo}from"os";import{dirname as AD,join as gt,resolve as TD}from"path";import{notStrictEqual as wy,strictEqual as ky}from"assert";var Pm={right:Mm,center:Bm};class Dl{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((r,o)=>({text:r.trim(),padding:this.measurePadding(r),width:o===0&&s.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=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 r="";n.forEach((o,i)=>{let{width:l}=e[i],u=this.negatePadding(e[i]),a=o;if(u>Ze.stringWidth(o))a+=" ".repeat(u-Ze.stringWidth(o));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=Pm[e[i].align];if(a=d(a,u),Ze.stringWidth(a)<u)a+=" ".repeat((l||0)-Ze.stringWidth(a)-1)}let c=e[i].padding||[0,0,0,0];if(c[3])r+=" ".repeat(c[3]);if(r+=
|
|
5
|
+
`)}rowToString(e,t){return this.rasterize(e).forEach((n,s)=>{let r="";n.forEach((o,i)=>{let{width:l}=e[i],u=this.negatePadding(e[i]),a=o;if(u>Ze.stringWidth(o))a+=" ".repeat(u-Ze.stringWidth(o));if(e[i].align&&e[i].align!=="left"&&this.wrap){let d=Pm[e[i].align];if(a=d(a,u),Ze.stringWidth(a)<u)a+=" ".repeat((l||0)-Ze.stringWidth(a)-1)}let c=e[i].padding||[0,0,0,0];if(c[3])r+=" ".repeat(c[3]);if(r+=kl(e[i],a,"| "),r+=a,r+=kl(e[i],a," |"),c[1])r+=" ".repeat(c[1]);if(s===0&&t.length>0)r=this.renderInline(r,t[t.length-1])}),t.push({text:r.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),s=n?n[0].length:0,r=t.text,o=Ze.stringWidth(r.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,r+e;if(s<o)return e;return t.hidden=!0,r.trimRight()+" ".repeat(s-o)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),s;return e.forEach((r,o)=>{if(r.width=n[o],this.wrap)s=Ze.wrap(r.text,this.negatePadding(r),{hard:!0}).split(`
|
|
6
6
|
`);else s=r.text.split(`
|
|
7
|
-
`);if(r.border)s.unshift("."+"-".repeat(this.negatePadding(r)+2)+"."),s.push("'"+"-".repeat(this.negatePadding(r)+2)+"'");if(r.padding)s.unshift(...Array(r.padding[0]||0).fill("")),s.push(...Array(r.padding[2]||0).fill(""));s.forEach((i,l)=>{if(!t[l])t.push([]);let u=t[l];for(let a=0;a<o;a++)if(u[a]===void 0)u.push("");u.push(i)})}),t}negatePadding(e){let t=e.width||0;if(e.padding)t-=(e.padding[3]||0)+(e.padding[1]||0);if(e.border)t-=4;return t}columnWidths(e){if(!this.wrap)return e.map((o)=>o.width||Ze.stringWidth(o.text));let t=e.length,n=this.width,s=e.map((o)=>{if(o.width)return t--,n-=o.width,o.width;return}),r=t?Math.floor(n/t):0;return s.map((o,i)=>{if(o===void 0)return Math.max(r,Lm(e[i]));return o})}}function wl(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function Lm(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Nm(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Mm(e,t){e=e.trim();let n=Ze.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function Bm(e,t){e=e.trim();let n=Ze.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Ze;function kl(e,t){return Ze=t,new Dl({width:(e===null||e===void 0?void 0:e.width)||Nm(),wrap:e===null||e===void 0?void 0:e.wrap})}function si({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 jm=si();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(jm,"")}var xl=161,Sl=1114109,_l=[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],El=12288,$l=65510,Cl=[12288,12288,65281,65376,65504,65510];var Al=4352,Tl=262141,ri=[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 ur=(e,t)=>{let n=0,s=Math.floor(e.length/2)-1;while(n<=s){let r=Math.floor((n+s)/2),o=r*2;if(t<e[o])s=r-1;else if(t>e[o+1])n=r+1;else return!0}return!1};var Fl=19968,[Wm,Um]=Jm(ri);function Jm(e){let t=e[0],n=e[1];for(let s=0;s<e.length;s+=2){let r=e[s],o=e[s+1];if(Fl>=r&&Fl<=o)return[r,o];if(o-r>n-t)t=r,n=o}return[t,n]}var Ol=(e)=>{if(e<xl||e>Sl)return!1;return ur(_l,e)},Rl=(e)=>{if(e<El||e>$l)return!1;return ur(Cl,e)};var Il=(e)=>{if(e>=Wm&&e<=Um)return!0;if(e<Al||e>Tl)return!1;return ur(ri,e)};function Km(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function vl(e,{ambiguousAsWide:t=!1}={}){if(Km(e),Rl(e)||Il(e)||t&&Ol(e))return 2;return 1}var Nl=yl(Ll(),1),qm=new Intl.Segmenter,Hm=/^\p{Default_Ignorable_Code_Point}$/u;function mt(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 r=0,o={ambiguousAsWide:!n};for(let{segment:i}of qm.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(Hm.test(i))continue;if(Nl.default().test(i)){r+=2;continue}r+=vl(l,o)}return r}var Ml=(e=0)=>(t)=>`\x1B[${t+e}m`,Bl=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,jl=(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]}},kS=Object.keys(Se.modifier),zm=Object.keys(Se.color),Ym=Object.keys(Se.bgColor),xS=[...zm,...Ym];function Gm(){let e=new Map;for(let[t,n]of Object.entries(Se)){for(let[s,r]of Object.entries(n))Se[s]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[s]=Se[s],e.set(r[0],r[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=Ml(),Se.color.ansi256=Bl(),Se.color.ansi16m=jl(),Se.bgColor.ansi=Ml(10),Se.bgColor.ansi256=Bl(10),Se.bgColor.ansi16m=jl(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((o)=>o+o).join("");let r=Number.parseInt(s,16);return[r>>16&255,r>>8&255,r&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,r;if(t>=232)n=((t-232)*10+8)/255,s=n,r=n;else{t-=16;let l=t%36;n=Math.floor(t/36)/5,s=Math.floor(l/6)/5,r=l%6/5}let o=Math.max(n,s,r)*2;if(o===0)return 30;let i=30+(Math.round(r)<<2|Math.round(s)<<1|Math.round(n));if(o===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,s)=>Se.ansi256ToAnsi(Se.rgbToAnsi256(t,n,s)),enumerable:!1},hexToAnsi:{value:(t)=>Se.ansi256ToAnsi(Se.hexToAnsi256(t)),enumerable:!1}}),Se}var Xm=Gm(),Wl=Xm;var fr=new Set(["\x1B",""]),Vm=39,ii="\x07",Kl="[",Zm="]",ql="m",dr=`${Zm}8;;`,Ul=(e)=>`${fr.values().next().value}${Kl}${e}${ql}`,Jl=(e)=>`${fr.values().next().value}${dr}${e}${ii}`,Qm=(e)=>e.split(" ").map((t)=>mt(t)),oi=(e,t,n)=>{let s=[...t],r=!1,o=!1,i=mt(fn(e.at(-1)));for(let[l,u]of s.entries()){let a=mt(u);if(i+a<=n)e[e.length-1]+=u;else e.push(u),i=0;if(fr.has(u))r=!0,o=s.slice(l+1,l+1+dr.length).join("")===dr;if(r){if(o){if(u===ii)r=!1,o=!1}else if(u===ql)r=!1;continue}if(i+=a,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()},ey=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(mt(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},ty=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let s="",r,o,i=Qm(e),l=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)l[l.length-1]=l.at(-1).trimStart();let p=mt(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("");oi(l,f,t);continue}if(p+i[d]>t&&p>0&&i[d]>0){if(n.wordWrap===!1&&p<t){oi(l,f,t);continue}l.push("")}if(p+i[d]>t&&n.wordWrap===!1){oi(l,f,t);continue}l[l.length-1]+=f}if(n.trim!==!1)l=l.map((d)=>ey(d));let u=l.join(`
|
|
8
|
-
`),a=[...u],c=0;for(let[d,f]of a.entries()){if(s+=f,
|
|
9
|
-
`){if(o)s+=
|
|
10
|
-
`){if(r&&p)s+=
|
|
7
|
+
`);if(r.border)s.unshift("."+"-".repeat(this.negatePadding(r)+2)+"."),s.push("'"+"-".repeat(this.negatePadding(r)+2)+"'");if(r.padding)s.unshift(...Array(r.padding[0]||0).fill("")),s.push(...Array(r.padding[2]||0).fill(""));s.forEach((i,l)=>{if(!t[l])t.push([]);let u=t[l];for(let a=0;a<o;a++)if(u[a]===void 0)u.push("");u.push(i)})}),t}negatePadding(e){let t=e.width||0;if(e.padding)t-=(e.padding[3]||0)+(e.padding[1]||0);if(e.border)t-=4;return t}columnWidths(e){if(!this.wrap)return e.map((o)=>o.width||Ze.stringWidth(o.text));let t=e.length,n=this.width,s=e.map((o)=>{if(o.width)return t--,n-=o.width,o.width;return}),r=t?Math.floor(n/t):0;return s.map((o,i)=>{if(o===void 0)return Math.max(r,Lm(e[i]));return o})}}function kl(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function Lm(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Nm(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Mm(e,t){e=e.trim();let n=Ze.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function Bm(e,t){e=e.trim();let n=Ze.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Ze;function xl(e,t){return Ze=t,new Dl({width:(e===null||e===void 0?void 0:e.width)||Nm(),wrap:e===null||e===void 0?void 0:e.wrap})}function si({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 jm=si();function pn(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes(""))return e;return e.replace(jm,"")}var Sl=161,_l=1114109,El=[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],$l=12288,Cl=65510,Al=[12288,12288,65281,65376,65504,65510];var Tl=4352,Fl=262141,ri=[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 dr=(e,t)=>{let n=0,s=Math.floor(e.length/2)-1;while(n<=s){let r=Math.floor((n+s)/2),o=r*2;if(t<e[o])s=r-1;else if(t>e[o+1])n=r+1;else return!0}return!1};var Ol=19968,[Wm,Um]=Jm(ri);function Jm(e){let t=e[0],n=e[1];for(let s=0;s<e.length;s+=2){let r=e[s],o=e[s+1];if(Ol>=r&&Ol<=o)return[r,o];if(o-r>n-t)t=r,n=o}return[t,n]}var Rl=(e)=>{if(e<Sl||e>_l)return!1;return dr(El,e)},Il=(e)=>{if(e<$l||e>Cl)return!1;return dr(Al,e)};var vl=(e)=>{if(e>=Wm&&e<=Um)return!0;if(e<Tl||e>Fl)return!1;return dr(ri,e)};function Km(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function Pl(e,{ambiguousAsWide:t=!1}={}){if(Km(e),Il(e)||vl(e)||t&&Rl(e))return 2;return 1}var Ml=bl(Nl(),1),qm=new Intl.Segmenter,Hm=/^\p{Default_Ignorable_Code_Point}$/u;function mt(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:s=!1}=t;if(!s)e=pn(e);if(e.length===0)return 0;let r=0,o={ambiguousAsWide:!n};for(let{segment:i}of qm.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(Hm.test(i))continue;if(Ml.default().test(i)){r+=2;continue}r+=Pl(l,o)}return r}var Bl=(e=0)=>(t)=>`\x1B[${t+e}m`,jl=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,Wl=(e=0)=>(t,n,s)=>`\x1B[${38+e};2;${t};${n};${s}m`,_e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},DS=Object.keys(_e.modifier),zm=Object.keys(_e.color),Ym=Object.keys(_e.bgColor),xS=[...zm,...Ym];function Gm(){let e=new Map;for(let[t,n]of Object.entries(_e)){for(let[s,r]of Object.entries(n))_e[s]={open:`\x1B[${r[0]}m`,close:`\x1B[${r[1]}m`},n[s]=_e[s],e.set(r[0],r[1]);Object.defineProperty(_e,t,{value:n,enumerable:!1})}return Object.defineProperty(_e,"codes",{value:e,enumerable:!1}),_e.color.close="\x1B[39m",_e.bgColor.close="\x1B[49m",_e.color.ansi=Bl(),_e.color.ansi256=jl(),_e.color.ansi16m=Wl(),_e.bgColor.ansi=Bl(10),_e.bgColor.ansi256=jl(10),_e.bgColor.ansi16m=Wl(10),Object.defineProperties(_e,{rgbToAnsi256:{value(t,n,s){if(t===n&&n===s){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(s/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[s]=n;if(s.length===3)s=[...s].map((o)=>o+o).join("");let r=Number.parseInt(s,16);return[r>>16&255,r>>8&255,r&255]},enumerable:!1},hexToAnsi256:{value:(t)=>_e.rgbToAnsi256(..._e.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,s,r;if(t>=232)n=((t-232)*10+8)/255,s=n,r=n;else{t-=16;let l=t%36;n=Math.floor(t/36)/5,s=Math.floor(l/6)/5,r=l%6/5}let o=Math.max(n,s,r)*2;if(o===0)return 30;let i=30+(Math.round(r)<<2|Math.round(s)<<1|Math.round(n));if(o===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,s)=>_e.ansi256ToAnsi(_e.rgbToAnsi256(t,n,s)),enumerable:!1},hexToAnsi:{value:(t)=>_e.ansi256ToAnsi(_e.hexToAnsi256(t)),enumerable:!1}}),_e}var Xm=Gm(),Ul=Xm;var pr=new Set(["\x1B",""]),Vm=39,ii="\x07",ql="[",Zm="]",Hl="m",fr=`${Zm}8;;`,Jl=(e)=>`${pr.values().next().value}${ql}${e}${Hl}`,Kl=(e)=>`${pr.values().next().value}${fr}${e}${ii}`,Qm=(e)=>e.split(" ").map((t)=>mt(t)),oi=(e,t,n)=>{let s=[...t],r=!1,o=!1,i=mt(pn(e.at(-1)));for(let[l,u]of s.entries()){let a=mt(u);if(i+a<=n)e[e.length-1]+=u;else e.push(u),i=0;if(pr.has(u))r=!0,o=s.slice(l+1,l+1+fr.length).join("")===fr;if(r){if(o){if(u===ii)r=!1,o=!1}else if(u===Hl)r=!1;continue}if(i+=a,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()},ey=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(mt(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},ty=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let s="",r,o,i=Qm(e),l=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)l[l.length-1]=l.at(-1).trimStart();let p=mt(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("");oi(l,f,t);continue}if(p+i[d]>t&&p>0&&i[d]>0){if(n.wordWrap===!1&&p<t){oi(l,f,t);continue}l.push("")}if(p+i[d]>t&&n.wordWrap===!1){oi(l,f,t);continue}l[l.length-1]+=f}if(n.trim!==!1)l=l.map((d)=>ey(d));let u=l.join(`
|
|
8
|
+
`),a=[...u],c=0;for(let[d,f]of a.entries()){if(s+=f,pr.has(f)){let{groups:g}=new RegExp(`(?:\\${ql}(?<code>\\d+)m|\\${fr}(?<uri>.*)${ii})`).exec(u.slice(c))||{groups:{}};if(g.code!==void 0){let h=Number.parseFloat(g.code);r=h===Vm?void 0:h}else if(g.uri!==void 0)o=g.uri.length===0?void 0:g.uri}let p=Ul.codes.get(Number(r));if(a[d+1]===`
|
|
9
|
+
`){if(o)s+=Kl("");if(r&&p)s+=Jl(p)}else if(f===`
|
|
10
|
+
`){if(r&&p)s+=Jl(r);if(o)s+=Kl(o)}c+=f.length}return s};function ai(e,t,n){return String(e).normalize().replaceAll(`\r
|
|
11
11
|
`,`
|
|
12
12
|
`).split(`
|
|
13
13
|
`).map((s)=>ty(s,t,n)).join(`
|
|
14
|
-
`)}function ci(e){return kl(e,{stringWidth:mt,stripAnsi:fn,wrap:ai})}import{dirname as Hl,resolve as zl}from"path";import{readdirSync as ny,statSync as sy}from"fs";function li(e,t){let n=zl(".",e),s;if(!sy(n).isDirectory())n=Hl(n);while(!0){if(s=t(n,ny(n)),s)return zl(n,s);if(n=Hl(s=n),s===n)break}}import{inspect as ky}from"util";import{fileURLToPath as uu}from"url";import{format as iy}from"util";import{normalize as ay,resolve as cy}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,r=e.match(/^-+/);for(let o=r?r[0].length:0;o<e.length;o++){let i=e.charAt(o);if(s)s=!1,i=i.toUpperCase();if(o!==0&&(i==="-"||i==="_"))s=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function pr(e,t){let n=e.toLowerCase();t=t||"-";let s="";for(let r=0;r<e.length;r++){let o=n.charAt(r),i=e.charAt(r);if(o!==i&&r>0)s+=`${t}${n.charAt(r)}`;else s+=i}return s}function hr(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 Yl(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,s=null,r=null,o=[];for(let i=0;i<e.length;i++){if(n=s,s=e.charAt(i),s===" "&&!r){if(n!==" ")t++;continue}if(s===r)r=null;else if((s==="'"||s==='"')&&!r)r=s;if(!o[t])o[t]="";o[t]+=s}return o}var it;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(it||(it={}));var It;class di{constructor(e){It=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=Yl(e),r=typeof e==="string",o=ry(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||[],a=n.envPrefix,c=i["populate--"],d=c?"--":"_",f=Object.create(null),p=Object.create(null),g=n.__||It.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(E){let T=typeof E==="object"?E.key:E,J=Object.keys(E).map(function(I){return{boolean:"bools",string:"strings",number:"numbers"}[I]}).filter(Boolean).pop();if(J)h[J][T]=!0;h.arrays[T]=!0,h.keys.push(T)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(E){h.bools[E]=!0,h.keys.push(E)}),[].concat(n.string||[]).filter(Boolean).forEach(function(E){h.strings[E]=!0,h.keys.push(E)}),[].concat(n.number||[]).filter(Boolean).forEach(function(E){h.numbers[E]=!0,h.keys.push(E)}),[].concat(n.count||[]).filter(Boolean).forEach(function(E){h.counts[E]=!0,h.keys.push(E)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(E){h.normalize[E]=!0,h.keys.push(E)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([E,T])=>{if(typeof T==="number")h.nargs[E]=T,h.keys.push(E)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([E,T])=>{if(typeof T==="function")h.coercions[E]=T,h.keys.push(E)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(E){h.configs[E]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([E,T])=>{if(typeof T==="boolean"||typeof T==="function")h.configs[E]=T})}re(n.key,o,n.default,h.arrays),Object.keys(l).forEach(function(E){(h.aliases[E]||[]).forEach(function(T){l[T]=l[E]})});let w=null;ni();let k=[],D=Object.assign(Object.create(null),{_:[]}),_={};for(let E=0;E<s.length;E++){let T=s[E],J=T.replace(/^-{3,}/,"---"),I,A,ee,X,se,Ie;if(T!=="--"&&/^-/.test(T)&&ie(T))C(T);else if(J.match(/^---+(=|$)/)){C(T);continue}else if(T.match(/^--.+=/)||!i["short-option-groups"]&&T.match(/^-.+=/)){if(X=T.match(/^--?([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)if(q(X[1],h.arrays))E=x(E,X[1],s,X[2]);else if(q(X[1],h.nargs)!==!1)E=S(E,X[1],s,X[2]);else R(X[1],X[2],!0)}else if(T.match(y)&&i["boolean-negation"]){if(X=T.match(y),X!==null&&Array.isArray(X)&&X.length>=2)A=X[1],R(A,q(A,h.arrays)?[!1]:!1)}else if(T.match(/^--.+/)||!i["short-option-groups"]&&T.match(/^-[^-]+/)){if(X=T.match(/^--?(.+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(A=X[1],q(A,h.arrays))E=x(E,A,s);else if(q(A,h.nargs)!==!1)E=S(E,A,s);else if(se=s[E+1],se!==void 0&&(!se.match(/^-/)||se.match(m))&&!q(A,h.bools)&&!q(A,h.counts))R(A,se),E++;else if(/^(true|false)$/.test(se))R(A,se),E++;else R(A,W(A))}else if(T.match(/^-.\..+=/)){if(X=T.match(/^-([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)R(X[1],X[2])}else if(T.match(/^-.\..+/)&&!T.match(m)){if(se=s[E+1],X=T.match(/^-(.\..+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(A=X[1],se!==void 0&&!se.match(/^-/)&&!q(A,h.bools)&&!q(A,h.counts))R(A,se),E++;else R(A,W(A))}else if(T.match(/^-[^-]+/)&&!T.match(m)){ee=T.slice(1,-1).split(""),I=!1;for(let Ue=0;Ue<ee.length;Ue++){if(se=T.slice(Ue+2),ee[Ue+1]&&ee[Ue+1]==="="){if(Ie=T.slice(Ue+3),A=ee[Ue],q(A,h.arrays))E=x(E,A,s,Ie);else if(q(A,h.nargs)!==!1)E=S(E,A,s,Ie);else R(A,Ie);I=!0;break}if(se==="-"){R(ee[Ue],se);continue}if(/[A-Za-z]/.test(ee[Ue])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(se)&&q(se,h.bools)===!1){R(ee[Ue],se),I=!0;break}if(ee[Ue+1]&&ee[Ue+1].match(/\W/)){R(ee[Ue],se),I=!0;break}else R(ee[Ue],W(ee[Ue]))}if(A=T.slice(-1)[0],!I&&A!=="-")if(q(A,h.arrays))E=x(E,A,s);else if(q(A,h.nargs)!==!1)E=S(E,A,s);else if(se=s[E+1],se!==void 0&&(!/^(-|--)[^-]/.test(se)||se.match(m))&&!q(A,h.bools)&&!q(A,h.counts))R(A,se),E++;else if(/^(true|false)$/.test(se))R(A,se),E++;else R(A,W(A))}else if(T.match(/^-[0-9]$/)&&T.match(m)&&q(T.slice(1),h.bools))A=T.slice(1),R(A,W(A));else if(T==="--"){k=s.slice(E+1);break}else if(i["halt-at-non-option"]){k=s.slice(E);break}else C(T)}if(K(D,!0),K(D,!1),M(D),N(),te(D,h.aliases,l,!0),z(D),i["set-placeholder-key"])O(D);if(Object.keys(h.counts).forEach(function(E){if(!Q(D,E.split(".")))R(E,0)}),c&&k.length)D[d]=[];if(k.forEach(function(E){D[d].push(E)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(D).filter((E)=>E!=="--"&&E.includes("-")).forEach((E)=>{delete D[E]});if(i["strip-aliased"])[].concat(...Object.keys(o).map((E)=>o[E])).forEach((E)=>{if(i["camel-case-expansion"]&&E.includes("-"))delete D[E.split(".").map((T)=>pn(T)).join(".")];delete D[E]});function C(E){let T=v("_",E);if(typeof T==="string"||typeof T==="number")D._.push(T)}function S(E,T,J,I){let A,ee=q(T,h.nargs);if(ee=typeof ee!=="number"||isNaN(ee)?1:ee,ee===0){if(!Ae(I))w=Error(g("Argument unexpected for: %s",T));return R(T,W(T)),E}let X=Ae(I)?0:1;if(i["nargs-eats-options"]){if(J.length-(E+1)+X<ee)w=Error(g("Not enough arguments following: %s",T));X=ee}else{for(A=E+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",T))}let se=Math.min(X,ee);if(!Ae(I)&&se>0)R(T,I),se--;for(A=E+1;A<se+E+1;A++)R(T,J[A]);return E+se}function x(E,T,J,I){let A=[],ee=I||J[E+1],X=q(T,h.nargs);if(q(T,h.bools)&&!/^(true|false)$/.test(ee))A.push(!0);else if(Ae(ee)||Ae(I)&&/^-/.test(ee)&&!m.test(ee)&&!ie(ee)){if(l[T]!==void 0){let se=l[T];A=Array.isArray(se)?se:[se]}}else{if(!Ae(I))A.push(P(T,I,!0));for(let se=E+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;E=se,A.push(P(T,ee,r))}}if(typeof X==="number"&&(X&&A.length<X||isNaN(X)&&A.length===0))w=Error(g("Not enough arguments following: %s",T));return R(T,A),E}function R(E,T,J=r){if(/-/.test(E)&&i["camel-case-expansion"]){let ee=E.split(".").map(function(X){return pn(X)}).join(".");L(E,ee)}let I=P(E,T,J),A=E.split(".");if(j(D,A,I),h.aliases[E])h.aliases[E].forEach(function(ee){let X=ee.split(".");j(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[E]||[]).includes(X.join(".")))j(D,X,I)});if(q(E,h.normalize)&&!q(E,h.arrays))[E].concat(h.aliases[E]||[]).forEach(function(X){Object.defineProperty(_,X,{enumerable:!0,get(){return T},set(se){T=typeof se==="string"?It.normalize(se):se}})})}function L(E,T){if(!(h.aliases[E]&&h.aliases[E].length))h.aliases[E]=[T],f[T]=!0;if(!(h.aliases[T]&&h.aliases[T].length))L(T,E)}function P(E,T,J){if(J)T=oy(T);if(q(E,h.bools)||q(E,h.counts)){if(typeof T==="string")T=T==="true"}let I=Array.isArray(T)?T.map(function(A){return v(E,A)}):v(E,T);if(q(E,h.counts)&&(Ae(I)||typeof I==="boolean"))I=ui();if(q(E,h.normalize)&&q(E,h.arrays))if(Array.isArray(T))I=T.map((A)=>It.normalize(A));else I=It.normalize(T);return I}function v(E,T){if(!i["parse-positional-numbers"]&&E==="_")return T;if(!q(E,h.strings)&&!q(E,h.bools)&&!Array.isArray(T)){if(hr(T)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${T}`)))||!Ae(T)&&q(E,h.numbers))T=Number(T)}return T}function M(E){let T=Object.create(null);te(T,h.aliases,l),Object.keys(h.configs).forEach(function(J){let I=E[J]||T[J];if(I)try{let A=null,ee=It.resolve(It.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=It.require(ee);U(A)}catch(A){if(A.name==="PermissionDenied")w=A;else if(E[J])w=Error(g("Invalid JSON config file: %s",I))}})}function U(E,T){Object.keys(E).forEach(function(J){let I=E[J],A=T?T+"."+J:J;if(typeof I==="object"&&I!==null&&!Array.isArray(I)&&i["dot-notation"])U(I,A);else if(!Q(D,A.split("."))||q(A,h.arrays)&&i["combine-arrays"])R(A,I)})}function N(){if(typeof u<"u")u.forEach(function(E){U(E)})}function K(E,T){if(typeof a>"u")return;let J=typeof a==="string"?a:"",I=It.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((T&&h.configs[ee.join(".")]||!T)&&!Q(E,ee))R(ee.join("."),I[A])}})}function z(E){let T,J=new Set;Object.keys(E).forEach(function(I){if(!J.has(I)){if(T=q(I,h.coercions),typeof T==="function")try{let A=v(I,T(E[I]));[].concat(h.aliases[I]||[],I).forEach((ee)=>{J.add(ee),E[ee]=A})}catch(A){w=A}}})}function O(E){return h.keys.forEach((T)=>{if(~T.indexOf("."))return;if(typeof E[T]>"u")E[T]=void 0}),E}function te(E,T,J,I=!1){Object.keys(J).forEach(function(A){if(!Q(E,A.split("."))){if(j(E,A.split("."),J[A]),I)p[A]=!0;(T[A]||[]).forEach(function(ee){if(Q(E,ee.split(".")))return;j(E,ee.split("."),J[A])})}})}function Q(E,T){let J=E;if(!i["dot-notation"])T=[T.join(".")];T.slice(0,-1).forEach(function(A){J=J[A]||{}});let I=T[T.length-1];if(typeof J!=="object")return!1;else return I in J}function j(E,T,J){let I=E;if(!i["dot-notation"])T=[T.join(".")];T.slice(0,-1).forEach(function(Ie){if(Ie=Gl(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=Gl(T[T.length-1]),ee=q(T.join("."),h.arrays),X=Array.isArray(J),se=i["duplicate-arguments-array"];if(!se&&q(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===ui())I[A]=ui(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||q(A,h.counts)||q(A,h.bools)))I[A]=[I[A],J];else I[A]=J}function re(...E){E.forEach(function(T){Object.keys(T||{}).forEach(function(J){if(h.aliases[J])return;h.aliases[J]=[].concat(o[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=pr(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 q(E,T){let J=[].concat(h.aliases[E]||[],E),I=Object.keys(T),A=J.find((ee)=>I.includes(ee));return A?T[A]:!1}function de(E){let T=Object.keys(h);return[].concat(T.map((I)=>h[I])).some(function(I){return Array.isArray(I)?I.includes(E):I[E]})}function oe(E,...T){return[].concat(...T).some(function(I){let A=E.match(I);return A&&de(A[1])})}function H(E){if(E.match(m)||!E.match(/^-[^-]+/))return!1;let T=!0,J,I=E.slice(1).split("");for(let A=0;A<I.length;A++){if(J=E.slice(A+2),!de(I[A])){T=!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 T}function ie(E){return i["unknown-options-as-args"]&&G(E)}function G(E){if(E=E.replace(/^-{3,}/,"--"),E.match(m))return!1;if(H(E))return!1;return!oe(E,/^-+([^=]+?)=[\s\S]*$/,y,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function W(E){if(!q(E,h.bools)&&!q(E,h.counts)&&`${E}`in l)return l[E];else return he(De(E))}function he(E){return{[it.BOOLEAN]:!0,[it.STRING]:"",[it.NUMBER]:void 0,[it.ARRAY]:[]}[E]}function De(E){let T=it.BOOLEAN;if(q(E,h.strings))T=it.STRING;else if(q(E,h.numbers))T=it.NUMBER;else if(q(E,h.bools))T=it.BOOLEAN;else if(q(E,h.arrays))T=it.ARRAY;return T}function Ae(E){return E===void 0}function ni(){Object.keys(h.counts).find((E)=>{if(q(E,h.arrays))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",E)),!0;else if(q(E,h.nargs))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",E)),!0;return!1})}return{aliases:Object.assign({},h.aliases),argv:Object.assign(_,D),configuration:i,defaulted:Object.assign({},p),error:w,newAliases:Object.assign({},f)}}}function ry(e){let t=[],n=Object.create(null),s=!0;Object.keys(e).forEach(function(r){t.push([].concat(e[r],r))});while(s){s=!1;for(let r=0;r<t.length;r++)for(let o=r+1;o<t.length;o++)if(t[r].filter(function(l){return t[o].indexOf(l)!==-1}).length){t[r]=t[r].concat(t[o]),t.splice(o,1),s=!0;break}}return t.forEach(function(r){r=r.filter(function(i,l,u){return u.indexOf(i)===l});let o=r.pop();if(o!==void 0&&typeof o==="string")n[o]=r}),n}function ui(e){return e!==void 0?e+1:1}function Gl(e){if(e==="__proto__")return"___proto___";return e}function oy(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 ly}from"fs";import{createRequire as Xl}from"node:module";var fi,pi,hi,Vl=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Zl=(pi=(fi=process===null||process===void 0?void 0:process.versions)===null||fi===void 0?void 0:fi.node)!==null&&pi!==void 0?pi:(hi=process===null||process===void 0?void 0:process.version)===null||hi===void 0?void 0:hi.slice(1);if(Zl){if(Number(Zl.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 uy=process?process.env:{},Ql=Xl?Xl(import.meta.url):void 0,eu=new di({cwd:process.cwd,env:()=>uy,format:iy,normalize:ay,resolve:cy,require:(e)=>{if(typeof Ql<"u")return Ql(e);else if(e.match(/\.json$/))return JSON.parse(ly(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),ms=function(t,n){return eu.parse(t.slice(),n).argv};ms.detailed=function(e,t){return eu.parse(e.slice(),t)};ms.camelCase=pn;ms.decamelize=pr;ms.looksLikeNumber=hr;var gi=ms;import{basename as xy,dirname as Sy,extname as _y,relative as Ey,resolve as lu,join as $y}from"path";function tu(){if(dy())return 0;return 1}function dy(){return fy()&&!process.defaultApp}function fy(){return!!process.versions.electron}function mi(e){return e.slice(tu()+1)}function nu(){return process.argv[tu()]}import{readFileSync as py,statSync as hy,writeFile as gy}from"fs";import{format as my}from"util";import{resolve as yy}from"path";var su={fs:{readFileSync:py,writeFile:gy},format:my,resolve:yy,exists:(e)=>{try{return hy(e).isFile()}catch(t){return!1}}};var yt;class ru{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 yt.format.apply(yt.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),s=e.shift(),r=function(){};if(typeof e[e.length-1]==="function")r=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let o=s===1?t:n;if(this.cache[this.locale][t])o=this.cache[this.locale][t][s===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:r});else r();let i=[o];if(~o.indexOf("%d"))i.push(s);return yt.format.apply(yt.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(s,r){let o=t[r+1];if(n+=s,typeof o<"u")n+="%s"}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){if(this.writeQueue.push(e),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],{directory:n,locale:s,cb:r}=t,o=this._resolveLocaleFile(n,s),i=JSON.stringify(this.cache[s],null,2);yt.fs.writeFile(o,i,"utf-8",function(l){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();r(l)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(yt.fs.readFileSync)e=JSON.parse(yt.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=yt.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let s=yt.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(s))n=s}return n}_fileExistsSync(e){return yt.exists(e)}}function ou(e,t){yt=t;let n=new ru(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 by=(e)=>ou(e,su),iu=by;var du=yl(cu(),1);import{createRequire as Cy}from"node:module";import{readFileSync as Ay,readdirSync as Ty}from"node:fs";var yi=uu(import.meta.url),Fy=yi.substring(0,yi.lastIndexOf("node_modules")),Oy=Cy(import.meta.url),bi={assert:{notStrictEqual:wy,strictEqual:Dy},cliui:ci,findUp:li,getEnv:(e)=>process.env[e],inspect:ky,getProcessArgvBin:nu,mainFilename:Fy||process.cwd(),Parser:gi,path:{basename:xy,dirname:Sy,extname:_y,relative:Ey,resolve:lu,join:$y},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:Ay,readdirSync:Ty,require:Oy,getCallerFile:()=>{let e=du.default(3);return e.match(/^file:\/\//)?uu(e):e},stringWidth:mt,y18n:iu({directory:lu(yi,"../../../locales"),updateFiles:!1})};function Je(e,t,n,s){n.assert.notStrictEqual(e,t,s)}function wi(e,t){t.assert.strictEqual(typeof e,"string")}function Un(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,r=n.shift();if(!r)throw Error(`No command found in: ${e}`);let o={cmd:r.replace(s,""),demanded:[],optional:[]};return n.forEach((i,l)=>{let u=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&l===n.length-1)u=!0;if(/^\[/.test(i))o.optional.push({cmd:i.replace(s,"").split("|"),variadic:u});else o.demanded.push({cmd:i.replace(s,"").split("|"),variadic:u})}),o}var Ry=["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 r=0,[o,i,l]=s(),u=[].slice.call(i);while(u.length&&u[u.length-1]===void 0)u.pop();let a=l||u.length;if(a<o.demanded.length)throw new $e(`Not enough arguments provided. Expected ${o.demanded.length} but received ${u.length}.`);let c=o.demanded.length+o.optional.length;if(a>c)throw new $e(`Too many arguments provided. Expected max ${c} but received ${a}.`);o.demanded.forEach((d)=>{let f=u.shift(),p=fu(f);if(d.cmd.filter((h)=>h===p||h==="*").length===0)pu(p,d.cmd,r);r+=1}),o.optional.forEach((d)=>{if(u.length===0)return;let f=u.shift(),p=fu(f);if(d.cmd.filter((h)=>h===p||h==="*").length===0)pu(p,d.cmd,r);r+=1})}catch(r){console.warn(r.stack)}}function fu(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function pu(e,t,n){throw new $e(`Invalid ${Ry[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 r=0;r<e.length;r++){if(typeof e[r]!=="function")throw Error("middleware must be a function");let o=e[r];o.applyBeforeValidation=t,o.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let r=e;r.applyBeforeValidation=t,r.global=n,r.mutates=s,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((s)=>{let r=[...n[t]||[],t];if(!s.option)return!0;else return!r.includes(s.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function hu(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function hn(e,t,n,s){return n.reduce((r,o)=>{if(o.applyBeforeValidation!==s)return r;if(o.mutates){if(o.applied)return r;o.applied=!0}if(ke(r))return r.then((i)=>Promise.all([i,o(i,t)])).then(([i,l])=>Object.assign(i,l));else{let i=o(r,t);return ke(i)?i.then((l)=>Object.assign(r,l)):Object.assign(r,i)}},e)}function gn(e,t,n=(s)=>{throw s}){try{let s=Iy(e)?e():e;return ke(s)?s.then((r)=>t(r)):t(s)}catch(s){return n(s)}}function Iy(e){return typeof e==="function"}var Jn=/(^\*)|(^\$0)/;class mu{constructor(e,t,n,s){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=s,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,s){s=s||{},this.requireCache.add(n);let r=this.shim.path.resolve(this.shim.path.dirname(n),e),o=this.shim.readdirSync(r,{recursive:s.recurse?!0:!1});if(!Array.isArray(s.extensions))s.extensions=["js"];let i=typeof s.visit==="function"?s.visit:(l)=>l;for(let l of o){let u=l.toString();if(s.exclude){let c=!1;if(typeof s.exclude==="function")c=s.exclude(u);else c=s.exclude.test(u);if(c)continue}if(s.include){let c=!1;if(typeof s.include==="function")c=s.include(u);else c=s.include.test(u);if(!c)continue}let a=!1;for(let c of s.extensions)if(u.endsWith(c))a=!0;if(a){let c=this.shim.path.join(r,u),d=t(c),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,c,u)){if(this.requireCache.has(c))continue;else this.requireCache.add(c);if(!f.command)f.command=this.shim.path.basename(c,this.shim.path.extname(c));this.addHandler(f)}}}}addHandler(e,t,n,s,r,o){let i=[],l=hu(r);if(s=s||(()=>{}),Array.isArray(e))if(vy(e))[e,...i]=e;else for(let u of e)this.addHandler(u);else if(Ly(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(gu(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 a=!1,c=[u.cmd].concat(i).filter((d)=>{if(Jn.test(d))return a=!0,!1;return!0});if(c.length===0&&a)c.push("$0");if(a)u.cmd=c[0],i=c.slice(1),e=e.replace(Jn,u.cmd);if(i.forEach((d)=>{this.aliasMap[d]=u.cmd}),t!==!1)this.usage.command(e,t,a,i,o);if(this.handlers[u.cmd]={original:e,description:t,handler:s,builder:n||{},middlewares:l,deprecated:o,demanded:u.demanded,optional:u.optional},a)this.defaultCommand=this.handlers[u.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,s,r,o){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,l=t.getInternalMethods().getContext(),u=l.commands.slice(),a=!e;if(e)l.commands.push(e),l.fullCommands.push(i.original);let c=this.applyBuilderUpdateUsageAndParse(a,i,t,n.aliases,u,s,r,o);return ke(c)?c.then((d)=>this.applyMiddlewareAndGetResult(a,i,d.innerArgv,l,r,d.aliases,t)):this.applyMiddlewareAndGetResult(a,i,c.innerArgv,l,r,c.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,s,r,o,i,l){let u=t.builder,a=n;if(gr(u)){n.getInternalMethods().getUsageInstance().freeze();let c=u(n.getInternalMethods().reset(s),l);if(ke(c))return c.then((d)=>(a=bu(d)?d:n,this.parseAndUpdateUsage(e,t,a,r,o,i)))}else if(Py(u))n.getInternalMethods().getUsageInstance().freeze(),a=n.getInternalMethods().reset(s),Object.keys(t.builder).forEach((c)=>{a.option(c,u[c])});return this.parseAndUpdateUsage(e,t,a,r,o,i)}parseAndUpdateUsage(e,t,n,s,r,o){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(s,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,r,o);return 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=Jn.test(t.original)?t.original.replace(Jn,"").trim():t.original,s=e.filter((r)=>!Jn.test(r));return s.push(n),`$0 ${s.join(" ")}`}handleValidationAndGetResult(e,t,n,s,r,o,i,l){if(!o.getInternalMethods().getHasOutput()){let u=o.getInternalMethods().runValidation(r,l,o.parsed.error,e);n=gn(n,(a)=>(u(a),a))}if(t.handler&&!o.getInternalMethods().getHasOutput()){o.getInternalMethods().setHasOutput();let u=!!o.getOptions().configuration["populate--"];if(o.getInternalMethods().postProcess(n,u,!1,!1),n=hn(n,o,i,!1),n=gn(n,(a)=>{let c=t.handler(a);return ke(c)?c.then(()=>a):a}),!e)o.getInternalMethods().getUsageInstance().cacheHelpMessage();if(ke(n)&&!o.getInternalMethods().hasParseCallback())n.catch((a)=>{try{o.getInternalMethods().getUsageInstance().fail(null,a)}catch(c){}})}if(!e)s.commands.pop(),s.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,s,r,o,i){let l={};if(r)return n;if(!i.getInternalMethods().getHasOutput())l=this.populatePositionals(t,n,s,i);let u=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),a=hn(n,i,u,!0);return ke(a)?a.then((c)=>this.handleValidationAndGetResult(e,t,c,s,o,i,u,l)):this.handleValidationAndGetResult(e,t,a,s,o,i,u,l)}populatePositionals(e,t,n,s){t._=t._.slice(n.commands.length);let r=e.demanded.slice(0),o=e.optional.slice(0),i={};this.validation.positionalCount(r.length,t._.length);while(r.length){let l=r.shift();this.populatePositional(l,t,i)}while(o.length){let l=o.shift();this.populatePositional(l,t,i)}return t._=n.commands.concat(t._.map((l)=>""+l)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),s),i}populatePositional(e,t,n){let s=e.cmd[0];if(e.variadic)n[s]=t._.splice(0).map(String);else if(t._.length)n[s]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=Ht(e);return n.demanded.forEach((s)=>{let[r,...o]=s.cmd;if(s.variadic)t.array.push(r),t.default[r]=[];t.alias[r]=o,t.demand[r]=!0}),n.optional.forEach((s)=>{let[r,...o]=s.cmd;if(s.variadic)t.array.push(r),t.default[r]=[];t.alias[r]=o}),t}postProcessPositionals(e,t,n,s){let r=Object.assign({},s.getOptions());r.default=Object.assign(n.default,r.default);for(let u of Object.keys(n.alias))r.alias[u]=(r.alias[u]||[]).concat(n.alias[u]);r.array=r.array.concat(n.array),r.config={};let o=[];if(Object.keys(t).forEach((u)=>{t[u].map((a)=>{if(r.configuration["unknown-options-as-args"])r.key[u]=!0;o.push(`--${u}`),o.push(a)})}),!o.length)return;let i=Object.assign({},r.configuration,{"populate--":!1}),l=this.shim.Parser.detailed(o,Object.assign({},r,{configuration:i}));if(l.error)s.getInternalMethods().getUsageInstance().fail(l.error.message,l.error);else{let u=Object.keys(t);Object.keys(t).forEach((a)=>{u.push(...l.aliases[a])}),Object.keys(l.argv).forEach((a)=>{if(u.includes(a)){if(!t[a])t[a]=l.argv[a];if(!this.isInConfigs(s,a)&&!this.isDefaulted(s,a)&&Object.prototype.hasOwnProperty.call(e,a)&&Object.prototype.hasOwnProperty.call(l.argv,a)&&(Array.isArray(e[a])||Array.isArray(l.argv[a])))e[a]=[].concat(e[a],l.argv[a]);else e[a]=l.argv[a]}})}}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=Jn.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(gr(t))return t(e,!0);else if(!gu(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;Je(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();Je(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 yu(e,t,n,s){return new mu(e,t,n,s)}function gu(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function vy(e){return e.every((t)=>typeof t==="string")}function gr(e){return typeof e==="function"}function Py(e){return typeof e==="object"}function Ly(e){return typeof e==="object"&&!Array.isArray(e)}function zt(e={},t=()=>!0){let n={};return Un(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 Ny(e){return typeof e==="boolean"}function Du(e,t){let n=t.y18n.__,s={},r=[];s.failFn=function(v){r.push(v)};let o=null,i=null,l=!0;s.showHelpOnFail=function(v=!0,M){let[U,N]=typeof v==="string"?[!0,v]:[v,M];if(e.getInternalMethods().isGlobalContext())i=N;return o=N,l=U,s};let u=!1;s.fail=function(v,M){let U=e.getInternalMethods().getLoggerInstance();if(r.length)for(let N=r.length-1;N>=0;--N){let K=r[N];if(Ny(K)){if(M)throw M;else if(v)throw Error(v)}else K(v,M,s)}else{if(e.getExitProcess())Yt(!0);if(!u){if(u=!0,l)e.showHelp("error"),U.error();if(v||M)U.error(v||M);let N=o||i;if(N){if(v||M)U.error("");U.error(N)}}if(M=M||new $e(v),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,M);else throw M}};let a=[],c=!1;s.usage=(P,v)=>{if(P===null)return c=!0,a=[],s;return c=!1,a.push([P,v||""]),s},s.getUsage=()=>a,s.getUsageDisabled=()=>c,s.getPositionalGroupName=()=>n("Positionals:");let d=[];s.example=(P,v)=>{d.push([P,v||""])};let f=[];s.command=function(v,M,U,N,K=!1){if(U)f=f.map((z)=>(z[2]=!1,z));f.push([v,M||"",U,N,K])},s.getCommands=()=>f;let p={};s.describe=function(v,M){if(Array.isArray(v))v.forEach((U)=>{s.describe(U,M)});else if(typeof v==="object")Object.keys(v).forEach((U)=>{s.describe(U,v[U])});else p[v]=M},s.getDescriptions=()=>p;let g=[];s.epilog=(P)=>{g.push(P)};let h=!1,m;s.wrap=(P)=>{h=!0,m=P},s.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!h)m=x(),h=!0;return m};let y="__yargsString__:";s.deferY18nLookup=(P)=>y+P,s.help=function(){if(D)return D;k();let v=e.customScriptName?e.$0:t.path.basename(e.$0),M=e.getDemandedOptions(),U=e.getDemandedCommands(),N=e.getDeprecatedOptions(),K=e.getGroups(),z=e.getOptions(),O=[];O=O.concat(Object.keys(p)),O=O.concat(Object.keys(M)),O=O.concat(Object.keys(U)),O=O.concat(Object.keys(z.default)),O=O.filter(C),O=Object.keys(O.reduce((H,ie)=>{if(ie!=="_")H[ie]=!0;return H},{}));let te=s.getWrap(),Q=t.cliui({width:te,wrap:!!te});if(!c){if(a.length)a.forEach((H)=>{if(Q.div({text:`${H[0].replace(/\$0/g,v)}`}),H[1])Q.div({text:`${H[1]}`,padding:[1,0,0,0]})}),Q.div();else if(f.length){let H=null;if(U._)H=`${v} <${n("command")}>
|
|
15
|
-
`;else
|
|
16
|
-
`;
|
|
17
|
-
`);
|
|
18
|
-
`)}return
|
|
14
|
+
`)}function ci(e){return xl(e,{stringWidth:mt,stripAnsi:pn,wrap:ai})}import{dirname as zl,resolve as Yl}from"path";import{readdirSync as ny,statSync as sy}from"fs";function li(e,t){let n=Yl(".",e),s;if(!sy(n).isDirectory())n=zl(n);while(!0){if(s=t(n,ny(n)),s)return Yl(n,s);if(n=zl(s=n),s===n)break}}import{inspect as Dy}from"util";import{fileURLToPath as du}from"url";import{format as iy}from"util";import{normalize as ay,resolve as cy}from"path";function hn(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",s=!1,r=e.match(/^-+/);for(let o=r?r[0].length:0;o<e.length;o++){let i=e.charAt(o);if(s)s=!1,i=i.toUpperCase();if(o!==0&&(i==="-"||i==="_"))s=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function hr(e,t){let n=e.toLowerCase();t=t||"-";let s="";for(let r=0;r<e.length;r++){let o=n.charAt(r),i=e.charAt(r);if(o!==i&&r>0)s+=`${t}${n.charAt(r)}`;else s+=i}return s}function gr(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 Gl(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,s=null,r=null,o=[];for(let i=0;i<e.length;i++){if(n=s,s=e.charAt(i),s===" "&&!r){if(n!==" ")t++;continue}if(s===r)r=null;else if((s==="'"||s==='"')&&!r)r=s;if(!o[t])o[t]="";o[t]+=s}return o}var it;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(it||(it={}));var It;class di{constructor(e){It=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=Gl(e),r=typeof e==="string",o=ry(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||[],a=n.envPrefix,c=i["populate--"],d=c?"--":"_",f=Object.create(null),p=Object.create(null),g=n.__||It.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(C){let T=typeof C==="object"?C.key:C,U=Object.keys(C).map(function(I){return{boolean:"bools",string:"strings",number:"numbers"}[I]}).filter(Boolean).pop();if(U)h[U][T]=!0;h.arrays[T]=!0,h.keys.push(T)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(C){h.bools[C]=!0,h.keys.push(C)}),[].concat(n.string||[]).filter(Boolean).forEach(function(C){h.strings[C]=!0,h.keys.push(C)}),[].concat(n.number||[]).filter(Boolean).forEach(function(C){h.numbers[C]=!0,h.keys.push(C)}),[].concat(n.count||[]).filter(Boolean).forEach(function(C){h.counts[C]=!0,h.keys.push(C)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(C){h.normalize[C]=!0,h.keys.push(C)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([C,T])=>{if(typeof T==="number")h.nargs[C]=T,h.keys.push(C)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([C,T])=>{if(typeof T==="function")h.coercions[C]=T,h.keys.push(C)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(C){h.configs[C]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([C,T])=>{if(typeof T==="boolean"||typeof T==="function")h.configs[C]=T})}ce(n.key,o,n.default,h.arrays),Object.keys(l).forEach(function(C){(h.aliases[C]||[]).forEach(function(T){l[T]=l[C]})});let w=null;fn();let D=[],k=Object.assign(Object.create(null),{_:[]}),_={};for(let C=0;C<s.length;C++){let T=s[C],U=T.replace(/^-{3,}/,"---"),I,A,Q,G,se,Ie;if(T!=="--"&&/^-/.test(T)&&re(T))E(T);else if(U.match(/^---+(=|$)/)){E(T);continue}else if(T.match(/^--.+=/)||!i["short-option-groups"]&&T.match(/^-.+=/)){if(G=T.match(/^--?([^=]+)=([\s\S]*)$/),G!==null&&Array.isArray(G)&&G.length>=3)if(K(G[1],h.arrays))C=x(C,G[1],s,G[2]);else if(K(G[1],h.nargs)!==!1)C=S(C,G[1],s,G[2]);else R(G[1],G[2],!0)}else if(T.match(y)&&i["boolean-negation"]){if(G=T.match(y),G!==null&&Array.isArray(G)&&G.length>=2)A=G[1],R(A,K(A,h.arrays)?[!1]:!1)}else if(T.match(/^--.+/)||!i["short-option-groups"]&&T.match(/^-[^-]+/)){if(G=T.match(/^--?(.+)/),G!==null&&Array.isArray(G)&&G.length>=2)if(A=G[1],K(A,h.arrays))C=x(C,A,s);else if(K(A,h.nargs)!==!1)C=S(C,A,s);else if(se=s[C+1],se!==void 0&&(!se.match(/^-/)||se.match(m))&&!K(A,h.bools)&&!K(A,h.counts))R(A,se),C++;else if(/^(true|false)$/.test(se))R(A,se),C++;else R(A,Y(A))}else if(T.match(/^-.\..+=/)){if(G=T.match(/^-([^=]+)=([\s\S]*)$/),G!==null&&Array.isArray(G)&&G.length>=3)R(G[1],G[2])}else if(T.match(/^-.\..+/)&&!T.match(m)){if(se=s[C+1],G=T.match(/^-(.\..+)/),G!==null&&Array.isArray(G)&&G.length>=2)if(A=G[1],se!==void 0&&!se.match(/^-/)&&!K(A,h.bools)&&!K(A,h.counts))R(A,se),C++;else R(A,Y(A))}else if(T.match(/^-[^-]+/)&&!T.match(m)){Q=T.slice(1,-1).split(""),I=!1;for(let Ue=0;Ue<Q.length;Ue++){if(se=T.slice(Ue+2),Q[Ue+1]&&Q[Ue+1]==="="){if(Ie=T.slice(Ue+3),A=Q[Ue],K(A,h.arrays))C=x(C,A,s,Ie);else if(K(A,h.nargs)!==!1)C=S(C,A,s,Ie);else R(A,Ie);I=!0;break}if(se==="-"){R(Q[Ue],se);continue}if(/[A-Za-z]/.test(Q[Ue])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(se)&&K(se,h.bools)===!1){R(Q[Ue],se),I=!0;break}if(Q[Ue+1]&&Q[Ue+1].match(/\W/)){R(Q[Ue],se),I=!0;break}else R(Q[Ue],Y(Q[Ue]))}if(A=T.slice(-1)[0],!I&&A!=="-")if(K(A,h.arrays))C=x(C,A,s);else if(K(A,h.nargs)!==!1)C=S(C,A,s);else if(se=s[C+1],se!==void 0&&(!/^(-|--)[^-]/.test(se)||se.match(m))&&!K(A,h.bools)&&!K(A,h.counts))R(A,se),C++;else if(/^(true|false)$/.test(se))R(A,se),C++;else R(A,Y(A))}else if(T.match(/^-[0-9]$/)&&T.match(m)&&K(T.slice(1),h.bools))A=T.slice(1),R(A,Y(A));else if(T==="--"){D=s.slice(C+1);break}else if(i["halt-at-non-option"]){D=s.slice(C);break}else E(T)}if(J(k,!0),J(k,!1),B(k),N(),ee(k,h.aliases,l,!0),H(k),i["set-placeholder-key"])O(k);if(Object.keys(h.counts).forEach(function(C){if(!X(k,C.split(".")))R(C,0)}),c&&D.length)k[d]=[];if(D.forEach(function(C){k[d].push(C)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(k).filter((C)=>C!=="--"&&C.includes("-")).forEach((C)=>{delete k[C]});if(i["strip-aliased"])[].concat(...Object.keys(o).map((C)=>o[C])).forEach((C)=>{if(i["camel-case-expansion"]&&C.includes("-"))delete k[C.split(".").map((T)=>hn(T)).join(".")];delete k[C]});function E(C){let T=P("_",C);if(typeof T==="string"||typeof T==="number")k._.push(T)}function S(C,T,U,I){let A,Q=K(T,h.nargs);if(Q=typeof Q!=="number"||isNaN(Q)?1:Q,Q===0){if(!be(I))w=Error(g("Argument unexpected for: %s",T));return R(T,Y(T)),C}let G=be(I)?0:1;if(i["nargs-eats-options"]){if(U.length-(C+1)+G<Q)w=Error(g("Not enough arguments following: %s",T));G=Q}else{for(A=C+1;A<U.length;A++)if(!U[A].match(/^-[^0-9]/)||U[A].match(m)||re(U[A]))G++;else break;if(G<Q)w=Error(g("Not enough arguments following: %s",T))}let se=Math.min(G,Q);if(!be(I)&&se>0)R(T,I),se--;for(A=C+1;A<se+C+1;A++)R(T,U[A]);return C+se}function x(C,T,U,I){let A=[],Q=I||U[C+1],G=K(T,h.nargs);if(K(T,h.bools)&&!/^(true|false)$/.test(Q))A.push(!0);else if(be(Q)||be(I)&&/^-/.test(Q)&&!m.test(Q)&&!re(Q)){if(l[T]!==void 0){let se=l[T];A=Array.isArray(se)?se:[se]}}else{if(!be(I))A.push(v(T,I,!0));for(let se=C+1;se<U.length;se++){if(!i["greedy-arrays"]&&A.length>0||G&&typeof G==="number"&&A.length>=G)break;if(Q=U[se],/^-/.test(Q)&&!m.test(Q)&&!re(Q))break;C=se,A.push(v(T,Q,r))}}if(typeof G==="number"&&(G&&A.length<G||isNaN(G)&&A.length===0))w=Error(g("Not enough arguments following: %s",T));return R(T,A),C}function R(C,T,U=r){if(/-/.test(C)&&i["camel-case-expansion"]){let Q=C.split(".").map(function(G){return hn(G)}).join(".");L(C,Q)}let I=v(C,T,U),A=C.split(".");if(j(k,A,I),h.aliases[C])h.aliases[C].forEach(function(Q){let G=Q.split(".");j(k,G,I)});if(A.length>1&&i["dot-notation"])(h.aliases[A[0]]||[]).forEach(function(Q){let G=Q.split("."),se=[].concat(A);if(se.shift(),G=G.concat(se),!(h.aliases[C]||[]).includes(G.join(".")))j(k,G,I)});if(K(C,h.normalize)&&!K(C,h.arrays))[C].concat(h.aliases[C]||[]).forEach(function(G){Object.defineProperty(_,G,{enumerable:!0,get(){return T},set(se){T=typeof se==="string"?It.normalize(se):se}})})}function L(C,T){if(!(h.aliases[C]&&h.aliases[C].length))h.aliases[C]=[T],f[T]=!0;if(!(h.aliases[T]&&h.aliases[T].length))L(T,C)}function v(C,T,U){if(U)T=oy(T);if(K(C,h.bools)||K(C,h.counts)){if(typeof T==="string")T=T==="true"}let I=Array.isArray(T)?T.map(function(A){return P(C,A)}):P(C,T);if(K(C,h.counts)&&(be(I)||typeof I==="boolean"))I=ui();if(K(C,h.normalize)&&K(C,h.arrays))if(Array.isArray(T))I=T.map((A)=>It.normalize(A));else I=It.normalize(T);return I}function P(C,T){if(!i["parse-positional-numbers"]&&C==="_")return T;if(!K(C,h.strings)&&!K(C,h.bools)&&!Array.isArray(T)){if(gr(T)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${T}`)))||!be(T)&&K(C,h.numbers))T=Number(T)}return T}function B(C){let T=Object.create(null);ee(T,h.aliases,l),Object.keys(h.configs).forEach(function(U){let I=C[U]||T[U];if(I)try{let A=null,Q=It.resolve(It.cwd(),I),G=h.configs[U];if(typeof G==="function"){try{A=G(Q)}catch(se){A=se}if(A instanceof Error){w=A;return}}else A=It.require(Q);W(A)}catch(A){if(A.name==="PermissionDenied")w=A;else if(C[U])w=Error(g("Invalid JSON config file: %s",I))}})}function W(C,T){Object.keys(C).forEach(function(U){let I=C[U],A=T?T+"."+U:U;if(typeof I==="object"&&I!==null&&!Array.isArray(I)&&i["dot-notation"])W(I,A);else if(!X(k,A.split("."))||K(A,h.arrays)&&i["combine-arrays"])R(A,I)})}function N(){if(typeof u<"u")u.forEach(function(C){W(C)})}function J(C,T){if(typeof a>"u")return;let U=typeof a==="string"?a:"",I=It.env();Object.keys(I).forEach(function(A){if(U===""||A.lastIndexOf(U,0)===0){let Q=A.split("__").map(function(G,se){if(se===0)G=G.substring(U.length);return hn(G)});if((T&&h.configs[Q.join(".")]||!T)&&!X(C,Q))R(Q.join("."),I[A])}})}function H(C){let T,U=new Set;Object.keys(C).forEach(function(I){if(!U.has(I)){if(T=K(I,h.coercions),typeof T==="function")try{let A=P(I,T(C[I]));[].concat(h.aliases[I]||[],I).forEach((Q)=>{U.add(Q),C[Q]=A})}catch(A){w=A}}})}function O(C){return h.keys.forEach((T)=>{if(~T.indexOf("."))return;if(typeof C[T]>"u")C[T]=void 0}),C}function ee(C,T,U,I=!1){Object.keys(U).forEach(function(A){if(!X(C,A.split("."))){if(j(C,A.split("."),U[A]),I)p[A]=!0;(T[A]||[]).forEach(function(Q){if(X(C,Q.split(".")))return;j(C,Q.split("."),U[A])})}})}function X(C,T){let U=C;if(!i["dot-notation"])T=[T.join(".")];T.slice(0,-1).forEach(function(A){U=U[A]||{}});let I=T[T.length-1];if(typeof U!=="object")return!1;else return I in U}function j(C,T,U){let I=C;if(!i["dot-notation"])T=[T.join(".")];T.slice(0,-1).forEach(function(Ie){if(Ie=Xl(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=Xl(T[T.length-1]),Q=K(T.join("."),h.arrays),G=Array.isArray(U),se=i["duplicate-arguments-array"];if(!se&&K(A,h.nargs)){if(se=!0,!be(I[A])&&h.nargs[A]===1||Array.isArray(I[A])&&I[A].length===h.nargs[A])I[A]=void 0}if(U===ui())I[A]=ui(I[A]);else if(Array.isArray(I[A]))if(se&&Q&&G)I[A]=i["flatten-duplicate-arrays"]?I[A].concat(U):(Array.isArray(I[A][0])?I[A]:[I[A]]).concat([U]);else if(!se&&Boolean(Q)===Boolean(G))I[A]=U;else I[A]=I[A].concat([U]);else if(I[A]===void 0&&Q)I[A]=G?U:[U];else if(se&&!(I[A]===void 0||K(A,h.counts)||K(A,h.bools)))I[A]=[I[A],U];else I[A]=U}function ce(...C){C.forEach(function(T){Object.keys(T||{}).forEach(function(U){if(h.aliases[U])return;h.aliases[U]=[].concat(o[U]||[]),h.aliases[U].concat(U).forEach(function(I){if(/-/.test(I)&&i["camel-case-expansion"]){let A=hn(I);if(A!==U&&h.aliases[U].indexOf(A)===-1)h.aliases[U].push(A),f[A]=!0}}),h.aliases[U].concat(U).forEach(function(I){if(I.length>1&&/[A-Z]/.test(I)&&i["camel-case-expansion"]){let A=hr(I,"-");if(A!==U&&h.aliases[U].indexOf(A)===-1)h.aliases[U].push(A),f[A]=!0}}),h.aliases[U].forEach(function(I){h.aliases[I]=[U].concat(h.aliases[U].filter(function(A){return I!==A}))})})})}function K(C,T){let U=[].concat(h.aliases[C]||[],C),I=Object.keys(T),A=U.find((Q)=>I.includes(Q));return A?T[A]:!1}function ue(C){let T=Object.keys(h);return[].concat(T.map((I)=>h[I])).some(function(I){return Array.isArray(I)?I.includes(C):I[C]})}function le(C,...T){return[].concat(...T).some(function(I){let A=C.match(I);return A&&ue(A[1])})}function q(C){if(C.match(m)||!C.match(/^-[^-]+/))return!1;let T=!0,U,I=C.slice(1).split("");for(let A=0;A<I.length;A++){if(U=C.slice(A+2),!ue(I[A])){T=!1;break}if(I[A+1]&&I[A+1]==="="||U==="-"||/[A-Za-z]/.test(I[A])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(U)||I[A+1]&&I[A+1].match(/\W/))break}return T}function re(C){return i["unknown-options-as-args"]&&pe(C)}function pe(C){if(C=C.replace(/^-{3,}/,"--"),C.match(m))return!1;if(q(C))return!1;return!le(C,/^-+([^=]+?)=[\s\S]*$/,y,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function Y(C){if(!K(C,h.bools)&&!K(C,h.counts)&&`${C}`in l)return l[C];else return te(fe(C))}function te(C){return{[it.BOOLEAN]:!0,[it.STRING]:"",[it.NUMBER]:void 0,[it.ARRAY]:[]}[C]}function fe(C){let T=it.BOOLEAN;if(K(C,h.strings))T=it.STRING;else if(K(C,h.numbers))T=it.NUMBER;else if(K(C,h.bools))T=it.BOOLEAN;else if(K(C,h.arrays))T=it.ARRAY;return T}function be(C){return C===void 0}function fn(){Object.keys(h.counts).find((C)=>{if(K(C,h.arrays))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",C)),!0;else if(K(C,h.nargs))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",C)),!0;return!1})}return{aliases:Object.assign({},h.aliases),argv:Object.assign(_,k),configuration:i,defaulted:Object.assign({},p),error:w,newAliases:Object.assign({},f)}}}function ry(e){let t=[],n=Object.create(null),s=!0;Object.keys(e).forEach(function(r){t.push([].concat(e[r],r))});while(s){s=!1;for(let r=0;r<t.length;r++)for(let o=r+1;o<t.length;o++)if(t[r].filter(function(l){return t[o].indexOf(l)!==-1}).length){t[r]=t[r].concat(t[o]),t.splice(o,1),s=!0;break}}return t.forEach(function(r){r=r.filter(function(i,l,u){return u.indexOf(i)===l});let o=r.pop();if(o!==void 0&&typeof o==="string")n[o]=r}),n}function ui(e){return e!==void 0?e+1:1}function Xl(e){if(e==="__proto__")return"___proto___";return e}function oy(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 ly}from"fs";import{createRequire as Vl}from"node:module";var fi,pi,hi,Zl=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Ql=(pi=(fi=process===null||process===void 0?void 0:process.versions)===null||fi===void 0?void 0:fi.node)!==null&&pi!==void 0?pi:(hi=process===null||process===void 0?void 0:process.version)===null||hi===void 0?void 0:hi.slice(1);if(Ql){if(Number(Ql.match(/^([^.]+)/)[1])<Zl)throw Error(`yargs parser supports a minimum Node.js version of ${Zl}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var uy=process?process.env:{},eu=Vl?Vl(import.meta.url):void 0,tu=new di({cwd:process.cwd,env:()=>uy,format:iy,normalize:ay,resolve:cy,require:(e)=>{if(typeof eu<"u")return eu(e);else if(e.match(/\.json$/))return JSON.parse(ly(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),ys=function(t,n){return tu.parse(t.slice(),n).argv};ys.detailed=function(e,t){return tu.parse(e.slice(),t)};ys.camelCase=hn;ys.decamelize=hr;ys.looksLikeNumber=gr;var gi=ys;import{basename as xy,dirname as Sy,extname as _y,relative as Ey,resolve as uu,join as $y}from"path";function nu(){if(dy())return 0;return 1}function dy(){return fy()&&!process.defaultApp}function fy(){return!!process.versions.electron}function mi(e){return e.slice(nu()+1)}function su(){return process.argv[nu()]}import{readFileSync as py,statSync as hy,writeFile as gy}from"fs";import{format as my}from"util";import{resolve as yy}from"path";var ru={fs:{readFileSync:py,writeFile:gy},format:my,resolve:yy,exists:(e)=>{try{return hy(e).isFile()}catch(t){return!1}}};var yt;class ou{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles=typeof e.updateFiles==="boolean"?e.updateFiles:!0,this.locale=e.locale||"en",this.fallbackToLanguage=typeof e.fallbackToLanguage==="boolean"?e.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let t=e.shift(),n=function(){};if(typeof e[e.length-1]==="function")n=e.pop();if(n=n||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n});else n();return yt.format.apply(yt.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),s=e.shift(),r=function(){};if(typeof e[e.length-1]==="function")r=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let o=s===1?t:n;if(this.cache[this.locale][t])o=this.cache[this.locale][t][s===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:r});else r();let i=[o];if(~o.indexOf("%d"))i.push(s);return yt.format.apply(yt.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(s,r){let o=t[r+1];if(n+=s,typeof o<"u")n+="%s"}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){if(this.writeQueue.push(e),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],{directory:n,locale:s,cb:r}=t,o=this._resolveLocaleFile(n,s),i=JSON.stringify(this.cache[s],null,2);yt.fs.writeFile(o,i,"utf-8",function(l){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();r(l)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(yt.fs.readFileSync)e=JSON.parse(yt.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=yt.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let s=yt.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(s))n=s}return n}_fileExistsSync(e){return yt.exists(e)}}function iu(e,t){yt=t;let n=new ou(e);return{__:n.__.bind(n),__n:n.__n.bind(n),setLocale:n.setLocale.bind(n),getLocale:n.getLocale.bind(n),updateLocale:n.updateLocale.bind(n),locale:n.locale}}var by=(e)=>iu(e,ru),au=by;var fu=bl(lu(),1);import{createRequire as Cy}from"node:module";import{readFileSync as Ay,readdirSync as Ty}from"node:fs";var yi=du(import.meta.url),Fy=yi.substring(0,yi.lastIndexOf("node_modules")),Oy=Cy(import.meta.url),bi={assert:{notStrictEqual:wy,strictEqual:ky},cliui:ci,findUp:li,getEnv:(e)=>process.env[e],inspect:Dy,getProcessArgvBin:su,mainFilename:Fy||process.cwd(),Parser:gi,path:{basename:xy,dirname:Sy,extname:_y,relative:Ey,resolve:uu,join:$y},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:Ay,readdirSync:Ty,require:Oy,getCallerFile:()=>{let e=fu.default(3);return e.match(/^file:\/\//)?du(e):e},stringWidth:mt,y18n:au({directory:uu(yi,"../../../locales"),updateFiles:!1})};function Je(e,t,n,s){n.assert.notStrictEqual(e,t,s)}function wi(e,t){t.assert.strictEqual(typeof e,"string")}function Jn(e){return Object.keys(e)}function xe(e){return!!e&&!!e.then&&typeof e.then==="function"}class Ce extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,Ce)}}function Ht(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),s=/\.*[\][<>]/g,r=n.shift();if(!r)throw Error(`No command found in: ${e}`);let o={cmd:r.replace(s,""),demanded:[],optional:[]};return n.forEach((i,l)=>{let u=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&l===n.length-1)u=!0;if(/^\[/.test(i))o.optional.push({cmd:i.replace(s,"").split("|"),variadic:u});else o.demanded.push({cmd:i.replace(s,"").split("|"),variadic:u})}),o}var Ry=["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 r=0,[o,i,l]=s(),u=[].slice.call(i);while(u.length&&u[u.length-1]===void 0)u.pop();let a=l||u.length;if(a<o.demanded.length)throw new Ce(`Not enough arguments provided. Expected ${o.demanded.length} but received ${u.length}.`);let c=o.demanded.length+o.optional.length;if(a>c)throw new Ce(`Too many arguments provided. Expected max ${c} but received ${a}.`);o.demanded.forEach((d)=>{let f=u.shift(),p=pu(f);if(d.cmd.filter((h)=>h===p||h==="*").length===0)hu(p,d.cmd,r);r+=1}),o.optional.forEach((d)=>{if(u.length===0)return;let f=u.shift(),p=pu(f);if(d.cmd.filter((h)=>h===p||h==="*").length===0)hu(p,d.cmd,r);r+=1})}catch(r){console.warn(r.stack)}}function pu(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function hu(e,t,n){throw new Ce(`Invalid ${Ry[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class ki{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 r=0;r<e.length;r++){if(typeof e[r]!=="function")throw Error("middleware must be a function");let o=e[r];o.applyBeforeValidation=t,o.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let r=e;r.applyBeforeValidation=t,r.global=n,r.mutates=s,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((s)=>{let r=[...n[t]||[],t];if(!s.option)return!0;else return!r.includes(s.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function gu(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function gn(e,t,n,s){return n.reduce((r,o)=>{if(o.applyBeforeValidation!==s)return r;if(o.mutates){if(o.applied)return r;o.applied=!0}if(xe(r))return r.then((i)=>Promise.all([i,o(i,t)])).then(([i,l])=>Object.assign(i,l));else{let i=o(r,t);return xe(i)?i.then((l)=>Object.assign(r,l)):Object.assign(r,i)}},e)}function mn(e,t,n=(s)=>{throw s}){try{let s=Iy(e)?e():e;return xe(s)?s.then((r)=>t(r)):t(s)}catch(s){return n(s)}}function Iy(e){return typeof e==="function"}var Kn=/(^\*)|(^\$0)/;class yu{constructor(e,t,n,s){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=s,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,s){s=s||{},this.requireCache.add(n);let r=this.shim.path.resolve(this.shim.path.dirname(n),e),o=this.shim.readdirSync(r,{recursive:s.recurse?!0:!1});if(!Array.isArray(s.extensions))s.extensions=["js"];let i=typeof s.visit==="function"?s.visit:(l)=>l;for(let l of o){let u=l.toString();if(s.exclude){let c=!1;if(typeof s.exclude==="function")c=s.exclude(u);else c=s.exclude.test(u);if(c)continue}if(s.include){let c=!1;if(typeof s.include==="function")c=s.include(u);else c=s.include.test(u);if(!c)continue}let a=!1;for(let c of s.extensions)if(u.endsWith(c))a=!0;if(a){let c=this.shim.path.join(r,u),d=t(c),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,c,u)){if(this.requireCache.has(c))continue;else this.requireCache.add(c);if(!f.command)f.command=this.shim.path.basename(c,this.shim.path.extname(c));this.addHandler(f)}}}}addHandler(e,t,n,s,r,o){let i=[],l=gu(r);if(s=s||(()=>{}),Array.isArray(e))if(vy(e))[e,...i]=e;else for(let u of e)this.addHandler(u);else if(Ly(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(mu(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 a=!1,c=[u.cmd].concat(i).filter((d)=>{if(Kn.test(d))return a=!0,!1;return!0});if(c.length===0&&a)c.push("$0");if(a)u.cmd=c[0],i=c.slice(1),e=e.replace(Kn,u.cmd);if(i.forEach((d)=>{this.aliasMap[d]=u.cmd}),t!==!1)this.usage.command(e,t,a,i,o);if(this.handlers[u.cmd]={original:e,description:t,handler:s,builder:n||{},middlewares:l,deprecated:o,demanded:u.demanded,optional:u.optional},a)this.defaultCommand=this.handlers[u.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,s,r,o){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,l=t.getInternalMethods().getContext(),u=l.commands.slice(),a=!e;if(e)l.commands.push(e),l.fullCommands.push(i.original);let c=this.applyBuilderUpdateUsageAndParse(a,i,t,n.aliases,u,s,r,o);return xe(c)?c.then((d)=>this.applyMiddlewareAndGetResult(a,i,d.innerArgv,l,r,d.aliases,t)):this.applyMiddlewareAndGetResult(a,i,c.innerArgv,l,r,c.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,s,r,o,i,l){let u=t.builder,a=n;if(mr(u)){n.getInternalMethods().getUsageInstance().freeze();let c=u(n.getInternalMethods().reset(s),l);if(xe(c))return c.then((d)=>(a=wu(d)?d:n,this.parseAndUpdateUsage(e,t,a,r,o,i)))}else if(Py(u))n.getInternalMethods().getUsageInstance().freeze(),a=n.getInternalMethods().reset(s),Object.keys(t.builder).forEach((c)=>{a.option(c,u[c])});return this.parseAndUpdateUsage(e,t,a,r,o,i)}parseAndUpdateUsage(e,t,n,s,r,o){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(s,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,r,o);return xe(i)?i.then((l)=>({aliases:n.parsed.aliases,innerArgv:l})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=Kn.test(t.original)?t.original.replace(Kn,"").trim():t.original,s=e.filter((r)=>!Kn.test(r));return s.push(n),`$0 ${s.join(" ")}`}handleValidationAndGetResult(e,t,n,s,r,o,i,l){if(!o.getInternalMethods().getHasOutput()){let u=o.getInternalMethods().runValidation(r,l,o.parsed.error,e);n=mn(n,(a)=>(u(a),a))}if(t.handler&&!o.getInternalMethods().getHasOutput()){o.getInternalMethods().setHasOutput();let u=!!o.getOptions().configuration["populate--"];if(o.getInternalMethods().postProcess(n,u,!1,!1),n=gn(n,o,i,!1),n=mn(n,(a)=>{let c=t.handler(a);return xe(c)?c.then(()=>a):a}),!e)o.getInternalMethods().getUsageInstance().cacheHelpMessage();if(xe(n)&&!o.getInternalMethods().hasParseCallback())n.catch((a)=>{try{o.getInternalMethods().getUsageInstance().fail(null,a)}catch(c){}})}if(!e)s.commands.pop(),s.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,s,r,o,i){let l={};if(r)return n;if(!i.getInternalMethods().getHasOutput())l=this.populatePositionals(t,n,s,i);let u=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),a=gn(n,i,u,!0);return xe(a)?a.then((c)=>this.handleValidationAndGetResult(e,t,c,s,o,i,u,l)):this.handleValidationAndGetResult(e,t,a,s,o,i,u,l)}populatePositionals(e,t,n,s){t._=t._.slice(n.commands.length);let r=e.demanded.slice(0),o=e.optional.slice(0),i={};this.validation.positionalCount(r.length,t._.length);while(r.length){let l=r.shift();this.populatePositional(l,t,i)}while(o.length){let l=o.shift();this.populatePositional(l,t,i)}return t._=n.commands.concat(t._.map((l)=>""+l)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),s),i}populatePositional(e,t,n){let s=e.cmd[0];if(e.variadic)n[s]=t._.splice(0).map(String);else if(t._.length)n[s]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=Ht(e);return n.demanded.forEach((s)=>{let[r,...o]=s.cmd;if(s.variadic)t.array.push(r),t.default[r]=[];t.alias[r]=o,t.demand[r]=!0}),n.optional.forEach((s)=>{let[r,...o]=s.cmd;if(s.variadic)t.array.push(r),t.default[r]=[];t.alias[r]=o}),t}postProcessPositionals(e,t,n,s){let r=Object.assign({},s.getOptions());r.default=Object.assign(n.default,r.default);for(let u of Object.keys(n.alias))r.alias[u]=(r.alias[u]||[]).concat(n.alias[u]);r.array=r.array.concat(n.array),r.config={};let o=[];if(Object.keys(t).forEach((u)=>{t[u].map((a)=>{if(r.configuration["unknown-options-as-args"])r.key[u]=!0;o.push(`--${u}`),o.push(a)})}),!o.length)return;let i=Object.assign({},r.configuration,{"populate--":!1}),l=this.shim.Parser.detailed(o,Object.assign({},r,{configuration:i}));if(l.error)s.getInternalMethods().getUsageInstance().fail(l.error.message,l.error);else{let u=Object.keys(t);Object.keys(t).forEach((a)=>{u.push(...l.aliases[a])}),Object.keys(l.argv).forEach((a)=>{if(u.includes(a)){if(!t[a])t[a]=l.argv[a];if(!this.isInConfigs(s,a)&&!this.isDefaulted(s,a)&&Object.prototype.hasOwnProperty.call(e,a)&&Object.prototype.hasOwnProperty.call(l.argv,a)&&(Array.isArray(e[a])||Array.isArray(l.argv[a])))e[a]=[].concat(e[a],l.argv[a]);else e[a]=l.argv[a]}})}}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=Kn.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(mr(t))return t(e,!0);else if(!mu(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;Je(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();Je(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 bu(e,t,n,s){return new yu(e,t,n,s)}function mu(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function vy(e){return e.every((t)=>typeof t==="string")}function mr(e){return typeof e==="function"}function Py(e){return typeof e==="object"}function Ly(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 Ny(e){return typeof e==="boolean"}function Du(e,t){let n=t.y18n.__,s={},r=[];s.failFn=function(P){r.push(P)};let o=null,i=null,l=!0;s.showHelpOnFail=function(P=!0,B){let[W,N]=typeof P==="string"?[!0,P]:[P,B];if(e.getInternalMethods().isGlobalContext())i=N;return o=N,l=W,s};let u=!1;s.fail=function(P,B){let W=e.getInternalMethods().getLoggerInstance();if(r.length)for(let N=r.length-1;N>=0;--N){let J=r[N];if(Ny(J)){if(B)throw B;else if(P)throw Error(P)}else J(P,B,s)}else{if(e.getExitProcess())Yt(!0);if(!u){if(u=!0,l)e.showHelp("error"),W.error();if(P||B)W.error(P||B);let N=o||i;if(N){if(P||B)W.error("");W.error(N)}}if(B=B||new Ce(P),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,B);else throw B}};let a=[],c=!1;s.usage=(v,P)=>{if(v===null)return c=!0,a=[],s;return c=!1,a.push([v,P||""]),s},s.getUsage=()=>a,s.getUsageDisabled=()=>c,s.getPositionalGroupName=()=>n("Positionals:");let d=[];s.example=(v,P)=>{d.push([v,P||""])};let f=[];s.command=function(P,B,W,N,J=!1){if(W)f=f.map((H)=>(H[2]=!1,H));f.push([P,B||"",W,N,J])},s.getCommands=()=>f;let p={};s.describe=function(P,B){if(Array.isArray(P))P.forEach((W)=>{s.describe(W,B)});else if(typeof P==="object")Object.keys(P).forEach((W)=>{s.describe(W,P[W])});else p[P]=B},s.getDescriptions=()=>p;let g=[];s.epilog=(v)=>{g.push(v)};let h=!1,m;s.wrap=(v)=>{h=!0,m=v},s.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!h)m=x(),h=!0;return m};let y="__yargsString__:";s.deferY18nLookup=(v)=>y+v,s.help=function(){if(k)return k;D();let P=e.customScriptName?e.$0:t.path.basename(e.$0),B=e.getDemandedOptions(),W=e.getDemandedCommands(),N=e.getDeprecatedOptions(),J=e.getGroups(),H=e.getOptions(),O=[];O=O.concat(Object.keys(p)),O=O.concat(Object.keys(B)),O=O.concat(Object.keys(W)),O=O.concat(Object.keys(H.default)),O=O.filter(E),O=Object.keys(O.reduce((q,re)=>{if(re!=="_")q[re]=!0;return q},{}));let ee=s.getWrap(),X=t.cliui({width:ee,wrap:!!ee});if(!c){if(a.length)a.forEach((q)=>{if(X.div({text:`${q[0].replace(/\$0/g,P)}`}),q[1])X.div({text:`${q[1]}`,padding:[1,0,0,0]})}),X.div();else if(f.length){let q=null;if(W._)q=`${P} <${n("command")}>
|
|
15
|
+
`;else q=`${P} [${n("command")}]
|
|
16
|
+
`;X.div(`${q}`)}}if(f.length>1||f.length===1&&!f[0][2]){X.div(n("Commands:"));let q=e.getInternalMethods().getContext(),re=q.commands.length?`${q.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((Y,te)=>Y[0].localeCompare(te[0]));let pe=P?`${P} `:"";f.forEach((Y)=>{let te=`${pe}${re}${Y[0].replace(/^\$0 ?/,"")}`;X.span({text:te,padding:[0,2,0,2],width:w(f,ee,`${P}${re}`)+4},{text:Y[1]});let fe=[];if(Y[2])fe.push(`[${n("default")}]`);if(Y[3]&&Y[3].length)fe.push(`[${n("aliases:")} ${Y[3].join(", ")}]`);if(Y[4])if(typeof Y[4]==="string")fe.push(`[${n("deprecated: %s",Y[4])}]`);else fe.push(`[${n("deprecated")}]`);if(fe.length)X.div({text:fe.join(" "),padding:[0,0,0,2],align:"right"});else X.div()}),X.div()}let j=(Object.keys(H.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);O=O.filter((q)=>!e.parsed.newAliases[q]&&j.every((re)=>(H.alias[re]||[]).indexOf(q)===-1));let ce=n("Options:");if(!J[ce])J[ce]=[];_(O,H.alias,J,ce);let K=(q)=>/^--/.test(yr(q)),ue=Object.keys(J).filter((q)=>J[q].length>0).map((q)=>{let re=J[q].filter(E).map((pe)=>{if(j.includes(pe))return pe;for(let Y=0,te;(te=j[Y])!==void 0;Y++)if((H.alias[te]||[]).includes(pe))return te;return pe});return{groupName:q,normalizedKeys:re}}).filter(({normalizedKeys:q})=>q.length>0).map(({groupName:q,normalizedKeys:re})=>{let pe=re.reduce((Y,te)=>(Y[te]=[te].concat(H.alias[te]||[]).map((fe)=>{if(q===s.getPositionalGroupName())return fe;else return(/^[0-9]$/.test(fe)?H.boolean.includes(te)?"-":"--":fe.length>1?"--":"-")+fe}).sort((fe,be)=>K(fe)===K(be)?0:K(fe)?1:-1).join(", "),Y),{});return{groupName:q,normalizedKeys:re,switches:pe}});if(ue.filter(({groupName:q})=>q!==s.getPositionalGroupName()).some(({normalizedKeys:q,switches:re})=>!q.every((pe)=>K(re[pe]))))ue.filter(({groupName:q})=>q!==s.getPositionalGroupName()).forEach(({normalizedKeys:q,switches:re})=>{q.forEach((pe)=>{if(K(re[pe]))re[pe]=My(re[pe],4)})});if(ue.forEach(({groupName:q,normalizedKeys:re,switches:pe})=>{X.div(q),re.forEach((Y)=>{let te=pe[Y],fe=p[Y]||"",be=null;if(fe.includes(y))fe=n(fe.substring(y.length));if(H.boolean.includes(Y))be=`[${n("boolean")}]`;if(H.count.includes(Y))be=`[${n("count")}]`;if(H.string.includes(Y))be=`[${n("string")}]`;if(H.normalize.includes(Y))be=`[${n("string")}]`;if(H.array.includes(Y))be=`[${n("array")}]`;if(H.number.includes(Y))be=`[${n("number")}]`;let fn=(U)=>typeof U==="string"?`[${n("deprecated: %s",U)}]`:`[${n("deprecated")}]`,C=[Y in N?fn(N[Y]):null,be,Y in B?`[${n("required")}]`:null,H.choices&&H.choices[Y]?`[${n("choices:")} ${s.stringifiedValues(H.choices[Y])}]`:null,S(H.default[Y],H.defaultDescription[Y])].filter(Boolean).join(" ");X.span({text:yr(te),padding:[0,2,0,2+ku(te)],width:w(pe,ee)+4},fe);let T=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(C&&!T)X.div({text:C,padding:[0,0,0,2],align:"right"});else X.div()}),X.div()}),d.length)X.div(n("Examples:")),d.forEach((q)=>{q[0]=q[0].replace(/\$0/g,P)}),d.forEach((q)=>{if(q[1]==="")X.div({text:q[0],padding:[0,2,0,2]});else X.div({text:q[0],padding:[0,2,0,2],width:w(d,ee)+4},{text:q[1]})}),X.div();if(g.length>0){let q=g.map((re)=>re.replace(/\$0/g,P)).join(`
|
|
17
|
+
`);X.div(`${q}
|
|
18
|
+
`)}return X.toString().replace(/\s*$/,"")};function w(v,P,B){let W=0;if(!Array.isArray(v))v=Object.values(v).map((N)=>[N]);if(v.forEach((N)=>{W=Math.max(t.stringWidth(B?`${B} ${yr(N[0])}`:yr(N[0]))+ku(N[0]),W)}),P)W=Math.min(W,parseInt((P*0.5).toString(),10));return W}function D(){let v=e.getDemandedOptions(),P=e.getOptions();(Object.keys(P.alias)||[]).forEach((B)=>{P.alias[B].forEach((W)=>{if(p[W])s.describe(B,p[W]);if(W in v)e.demandOption(B,v[W]);if(P.boolean.includes(W))e.boolean(B);if(P.count.includes(W))e.count(B);if(P.string.includes(W))e.string(B);if(P.normalize.includes(W))e.normalize(B);if(P.array.includes(W))e.array(B);if(P.number.includes(W))e.number(B)})})}let k;s.cacheHelpMessage=function(){k=this.help()},s.clearCachedHelpMessage=function(){k=void 0},s.hasCachedHelpMessage=function(){return!!k};function _(v,P,B,W){let N=[],J=null;return Object.keys(B).forEach((H)=>{N=N.concat(B[H])}),v.forEach((H)=>{if(J=[H].concat(P[H]),!J.some((O)=>N.indexOf(O)!==-1))B[W].push(H)}),N}function E(v){return e.getOptions().hiddenOptions.indexOf(v)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}s.showHelp=(v)=>{let P=e.getInternalMethods().getLoggerInstance();if(!v)v="error";(typeof v==="function"?v:P[v])(s.help())},s.functionDescription=(v)=>["(",v.name?t.Parser.decamelize(v.name,"-"):n("generated-value"),")"].join(""),s.stringifiedValues=function(P,B){let W="",N=B||", ",J=[].concat(P);if(!P||!J.length)return W;return J.forEach((H)=>{if(W.length)W+=N;W+=JSON.stringify(H)}),W};function S(v,P){let B=`[${n("default:")} `;if(v===void 0&&!P)return null;if(P)B+=P;else switch(typeof v){case"string":B+=`"${v}"`;break;case"object":B+=JSON.stringify(v);break;default:B+=v}return`${B}]`}function x(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let R=null;s.version=(v)=>{R=v},s.showVersion=(v)=>{let P=e.getInternalMethods().getLoggerInstance();if(!v)v="error";(typeof v==="function"?v:P[v])(R)},s.reset=function(P){return o=null,u=!1,a=[],c=!1,g=[],d=[],f=[],p=zt(p,(B)=>!P[B]),s};let L=[];return s.freeze=function(){L.push({failMessage:o,failureOutput:u,usages:a,usageDisabled:c,epilogs:g,examples:d,commands:f,descriptions:p})},s.unfreeze=function(P=!1){let B=L.pop();if(!B)return;if(P)p={...B.descriptions,...p},f=[...B.commands,...f],a=[...B.usages,...a],d=[...B.examples,...d],g=[...B.epilogs,...g];else({failMessage:o,failureOutput:u,usages:a,usageDisabled:c,epilogs:g,examples:d,commands:f,descriptions:p}=B)},s}function Di(e){return typeof e==="object"}function My(e,t){return Di(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function ku(e){return Di(e)?e.indentation:0}function yr(e){return Di(e)?e.text:e}var xu=`###-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
|
-
`,
|
|
47
|
+
`,Su=`#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
|
|
74
|
+
`;class _u{constructor(e,t,n,s){var r,o,i;this.yargs=e,this.usage=t,this.command=n,this.shim=s,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=(i=((r=this.shim.getEnv("SHELL"))===null||r===void 0?void 0:r.includes("zsh"))||((o=this.shim.getEnv("ZSH_NAME"))===null||o===void 0?void 0:o.includes("zsh")))!==null&&i!==void 0?i:!1}defaultCompletion(e,t,n,s){let r=this.command.getCommandHandlers();for(let i=0,l=e.length;i<l;++i)if(r[e[i]]&&r[e[i]].builder){let u=r[e[i]].builder;if(mr(u)){this.indexAfterLastReset=i+1;let a=this.yargs.getInternalMethods().reset();return u(a,!0),a.argv}}let o=[];this.commandCompletions(o,e,n),this.optionCompletions(o,e,t,n),this.choicesFromOptionsCompletions(o,e,t,n),this.choicesFromPositionalsCompletions(o,e,t,n),s(null,o)}commandCompletions(e,t,n){let s=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&s[s.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((r)=>{let o=Ht(r[0]).cmd;if(t.indexOf(o)===-1)if(!this.zshShell)e.push(o);else{let i=r[1]||"";e.push(o.replace(/:/g,"\\:")+":"+i)}})}optionCompletions(e,t,n,s){if((s.match(/^-/)||s===""&&e.length===0)&&!this.previousArgHasChoices(t)){let r=this.yargs.getOptions(),o=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(r.key).forEach((i)=>{let l=!!r.configuration["boolean-negation"]&&r.boolean.includes(i);if(!o.includes(i)&&!r.hiddenOptions.includes(i)&&!this.argsContainKey(t,i,l))this.completeOptionKey(i,e,s,l&&!!r.default[i])})}}choicesFromOptionsCompletions(e,t,n,s){if(this.previousArgHasChoices(t)){let r=this.getPreviousArgChoices(t);if(r&&r.length>0)e.push(...r.map((o)=>o.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,s){if(s===""&&e.length>0&&this.previousArgHasChoices(t))return;let r=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],o=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),i=r[n._.length-o-1];if(!i)return;let l=this.yargs.getOptions().choices[i]||[];for(let u of l)if(u.startsWith(s))e.push(u.replace(/:/g,"\\:"))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],n="";if(!t.startsWith("-")&&e.length>1)n=t,t=e[e.length-2];if(!t.startsWith("-"))return;let s=t.replace(/^-+/,""),r=this.yargs.getOptions(),o=[s,...this.yargs.getAliases()[s]||[]],i;for(let l of o)if(Object.prototype.hasOwnProperty.call(r.key,l)&&Array.isArray(r.choices[l])){i=r.choices[l];break}if(i)return i.filter((l)=>!n||l.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let s=(r)=>e.indexOf((/^[^0-9]$/.test(r)?"-":"--")+r)!==-1;if(s(t))return!0;if(n&&s(`no-${t}`))return!0;if(this.aliases){for(let r of this.aliases[t])if(s(r))return!0}return!1}completeOptionKey(e,t,n,s){var r,o,i,l;let u=e;if(this.zshShell){let f=this.usage.getDescriptions(),p=(o=(r=this===null||this===void 0?void 0:this.aliases)===null||r===void 0?void 0:r[e])===null||o===void 0?void 0:o.find((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 a=(f)=>/^--/.test(f),c=(f)=>/^[^0-9]$/.test(f),d=!a(n)&&c(e)?"-":"--";if(t.push(d+u),s)t.push(d+"no-"+u)}customCompletion(e,t,n,s){if(Je(this.customCompletionFunction,null,this.shim),jy(this.customCompletionFunction)){let r=this.customCompletionFunction(n,t);if(xe(r))return r.then((o)=>{this.shim.process.nextTick(()=>{s(null,o)})}).catch((o)=>{this.shim.process.nextTick(()=>{s(o,void 0)})});return s(null,r)}else if(Wy(this.customCompletionFunction))return this.customCompletionFunction(n,t,(r=s)=>this.defaultCompletion(e,t,n,r),(r)=>{s(null,r)});else return this.customCompletionFunction(n,t,(r)=>{s(null,r)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",s=this.yargs.parse(e,!0),r=this.customCompletionFunction?(o)=>this.customCompletion(e,o,n,t):(o)=>this.defaultCompletion(e,o,n,t);return xe(s)?s.then(r):r(s)}generateCompletionScript(e,t){let n=this.zshShell?Su:xu,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 Eu(e,t,n,s){return new _u(e,t,n,s)}function jy(e){return e.length<3}function Wy(e){return e.length>3}function $u(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],s;for(s=0;s<=t.length;s++)n[s]=[s];let r;for(r=0;r<=e.length;r++)n[0][r]=r;for(s=1;s<=t.length;s++)for(r=1;r<=e.length;r++)if(t.charAt(s-1)===e.charAt(r-1))n[s][r]=n[s-1][r-1];else if(s>1&&r>1&&t.charAt(s-2)===e.charAt(r-1)&&t.charAt(s-1)===e.charAt(r-2))n[s][r]=n[s-2][r-2]+1;else n[s][r]=Math.min(n[s-1][r-1]+1,Math.min(n[s][r-1]+1,n[s-1][r]+1));return n[t.length][e.length]}var Cu=["$0","--","_"];function Au(e,t,n){let s=n.y18n.__,r=n.y18n.__n,o={};o.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(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",g,g.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(r("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()))}},o.positionalCount=function(d,f){if(f<d)t.fail(r("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",f,f+"",d+""))},o.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(r("Missing required argument: %s","Missing required arguments: %s",Object.keys(p).length,Object.keys(p).join(", ")+h))}},o.unknownArguments=function(d,f,p,g,h=!0){var m;let y=e.getInternalMethods().getCommandInstance().getCommands(),w=[],
|
|
76
|
+
`)}`:"";t.fail(r("Missing required argument: %s","Missing required arguments: %s",Object.keys(p).length,Object.keys(p).join(", ")+h))}},o.unknownArguments=function(d,f,p,g,h=!0){var m;let y=e.getInternalMethods().getCommandInstance().getCommands(),w=[],D=e.getInternalMethods().getContext();if(Object.keys(d).forEach((k)=>{if(!Cu.includes(k)&&!Object.prototype.hasOwnProperty.call(p,k)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),k)&&!o.isValidAndSomeAliasIsNotNew(k,f))w.push(k)}),h&&(D.commands.length>0||y.length>0||g))d._.slice(D.commands.length).forEach((k)=>{if(!y.includes(""+k))w.push(""+k)});if(h){let _=((m=e.getDemandedCommands()._)===null||m===void 0?void 0:m.max)||0,E=D.commands.length+_;if(E<d._.length)d._.slice(E).forEach((S)=>{if(S=String(S),!D.commands.includes(S)&&!w.includes(S))w.push(S)})}if(w.length)t.fail(r("Unknown argument: %s","Unknown arguments: %s",w.length,w.map((k)=>k.trim()?k:`"${k}"`).join(", ")))},o.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(r("Unknown command: %s","Unknown commands: %s",p.length,p.join(", "))),!0;else return!1},o.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])},o.limitedChoices=function(d){let f=e.getOptions(),p={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((m)=>{if(Cu.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={};o.implies=function(d,f){if(V("<string|object> [array|number|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((p)=>{o.implies(p,d[p])});else{if(e.global(d),!i[d])i[d]=[];if(Array.isArray(f))f.forEach((p)=>o.implies(d,p));else Je(f,void 0,n),i[d].push(f)}},o.getImplied=function(){return i};function l(c,d){let f=Number(d);if(d=isNaN(f)?d:f,typeof d==="number")d=c._.length>=d;else if(d.match(/^--no-.+/))d=d.match(/^--no-(.+)/)[1],d=!Object.prototype.hasOwnProperty.call(c,d);else d=Object.prototype.hasOwnProperty.call(c,d);return d}o.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={};o.conflicts=function(d,f){if(V("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((p)=>{o.conflicts(p,d[p])});else{if(e.global(d),!u[d])u[d]=[];if(Array.isArray(f))f.forEach((p)=>o.conflicts(d,p));else u[d].push(f)}},o.getConflicting=()=>u,o.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))})})},o.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=Eu(d,y);if(w<=3&&w<h)h=w,g=y}if(g)t.fail(s("Did you mean %s?",g))},o.reset=function(d){return i=zt(i,(f)=>!d[f]),u=zt(u,(f)=>!d[f]),o};let a=[];return o.freeze=function(){a.push({implied:i,conflicting:u})},o.unfreeze=function(){let d=a.pop();Je(d,void 0,n),{implied:i,conflicting:u}=d},o}var xi=[],ys;function bs(e,t,n,s){ys=s;let r={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return r;let o=/\.json|\..*rc$/.test(e.extends),i=null;if(!o)try{i=import.meta.resolve(e.extends)}catch(l){return e}else i=Jy(t,e.extends);Uy(i),xi.push(i),r=o?JSON.parse(ys.readFileSync(i,"utf8")):s.require(e.extends),delete e.extends,r=bs(r,ys.path.dirname(i),n,ys)}return xi=[],n?Au(r,e):Object.assign({},r,e)}function Uy(e){if(xi.indexOf(e)>-1)throw new $e(`Circular extended configurations: '${e}'.`)}function Jy(e,t){return ys.path.resolve(e,t)}function Au(e,t){let n={};function s(r){return r&&typeof r==="object"&&!Array.isArray(r)}Object.assign(n,e);for(let r of Object.keys(t))if(s(t[r])&&s(n[r]))n[r]=Au(e[r],t[r]);else n[r]=t[r];return n}var Z=function(e,t,n,s,r){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!r)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!r:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(e,n):r?r.value=n:t.set(e,n),n},b=function(e,t,n,s){if(n==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(e):s?s.value:t.get(e)},Ce,mn,ws,ze,Qe,yr,Gt,yn,br,at,wr,ct,_t,et,lt,Dr,bn,ve,ne,kr,xr,tt,wn,Kn,Dn,Xt,Sr,ae,kn,xn,Sn,ue,_r,Et,Ee;function Yu(e){return(t=[],n=e.process.cwd(),s)=>{let r=new Gu(t,n,s,e);return Object.defineProperty(r,"argv",{get:()=>r.parse(),enumerable:!0}),r.help(),r.version(),r}}var Tu=Symbol("copyDoubleDash"),Fu=Symbol("copyDoubleDash"),Si=Symbol("deleteFromParserHintObject"),Ou=Symbol("emitWarning"),Ru=Symbol("freeze"),Iu=Symbol("getDollarZero"),_n=Symbol("getParserConfiguration"),vu=Symbol("getUsageConfiguration"),_i=Symbol("guessLocale"),Pu=Symbol("guessVersion"),Lu=Symbol("parsePositionalNumbers"),Ei=Symbol("pkgUp"),Vt=Symbol("populateParserHintArray"),qn=Symbol("populateParserHintSingleValueDictionary"),$i=Symbol("populateParserHintArrayDictionary"),Ci=Symbol("populateParserHintDictionary"),Ai=Symbol("sanitizeKey"),Ti=Symbol("setKey"),Fi=Symbol("unfreeze"),Nu=Symbol("validateAsync"),Mu=Symbol("getCommandInstance"),Bu=Symbol("getContext"),ju=Symbol("getHasOutput"),Wu=Symbol("getLoggerInstance"),Uu=Symbol("getParseContext"),Ju=Symbol("getUsageInstance"),Ku=Symbol("getValidationInstance"),Er=Symbol("hasParseCallback"),qu=Symbol("isGlobalContext"),En=Symbol("postProcess"),Hu=Symbol("rebase"),Oi=Symbol("reset"),Ds=Symbol("runYargsParserAndExecuteCommands"),Ri=Symbol("runValidation"),zu=Symbol("setHasOutput"),$n=Symbol("kTrackManuallySetKeys"),Ky="en_US";class Gu{constructor(e=[],t,n,s){this.customScriptName=!1,this.parsed=!1,Ce.set(this,void 0),mn.set(this,void 0),ws.set(this,{commands:[],fullCommands:[]}),ze.set(this,null),Qe.set(this,null),yr.set(this,"show-hidden"),Gt.set(this,null),yn.set(this,!0),br.set(this,{}),at.set(this,!0),wr.set(this,[]),ct.set(this,void 0),_t.set(this,{}),et.set(this,!1),lt.set(this,null),Dr.set(this,!0),bn.set(this,void 0),ve.set(this,""),ne.set(this,void 0),kr.set(this,void 0),xr.set(this,{}),tt.set(this,null),wn.set(this,null),Kn.set(this,{}),Dn.set(this,{}),Xt.set(this,void 0),Sr.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),_r.set(this,{}),Et.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,kr,n,"f"),Z(this,ct,new Di(this),"f"),this.$0=this[Iu](),this[Oi](),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,yr,"f"),Z(this,bn,this[Fu](),"f"),b(this,ae,"f").y18n.setLocale(Ky)}addHelpOpt(e,t){if(V("[string|boolean] [string]",[e,t],arguments.length),b(this,lt,"f"))this[Si](b(this,lt,"f")),Z(this,lt,null,"f");if(e===!1&&t===void 0)return this;return Z(this,lt,typeof e==="string"?e:"help","f"),this.boolean(b(this,lt,"f")),this.describe(b(this,lt,"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,yr,"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[$i](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()),(r)=>{if(!r)b(this,ue,"f").fail(b(this,ae,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof r==="string"||r instanceof Error)b(this,ue,"f").fail(r.toString(),r);return n},(r)=>(b(this,ue,"f").fail(r.message?r.message:r.toString(),r),n)),!1,t),this}choices(e,t){return V("<object|string|array> [string|array]",[e,t],arguments.length),this[$i](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,ct,"f").addCoerceMiddleware((s,r)=>{var o;let i=(o=r.getAliases()[n])!==null&&o!==void 0?o:[],l=[n,...i].filter((u)=>Object.prototype.hasOwnProperty.call(s,u));if(l.length===0)return s;return gn(()=>t(s[l[0]]),(u)=>(l.forEach((a)=>{s[a]=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=bs(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,r,o){return V("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,s,r,o],arguments.length),b(this,Ce,"f").addHandler(e,t,n,s,r,o),this}commands(e,t,n,s,r,o){return this.command(e,t,n,s,r,o)}commandDir(e,t){V("<string> [object]",[e,t],arguments.length);let n=b(this,kr,"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)wi(e,b(this,ae,"f")),b(this,ne,"f").defaultDescription[e]=n;if(typeof t==="function"){if(wi(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)=>{Je(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")Je(n,!0,b(this,ae,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((s)=>{Je(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[Ti](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,at,"f"))b(this,ae,"f").process.exit(e)}exitProcess(e=!0){return V("[boolean]",[e],arguments.length),Z(this,at,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,(r,o)=>{if(r)s(r);else n(o)})});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,at,"f")}getGroups(){return Object.assign({},b(this,_t,"f"),b(this,Dn,"f"))}getHelp(){if(Z(this,et,!0,"f"),!b(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[Ds](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,_t,"f")[t];if(b(this,Dn,"f")[t])delete b(this,Dn,"f")[t];let s={};return b(this,_t,"f")[t]=(n||[]).concat(e).filter((r)=>{if(s[r])return!1;return s[r]=!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[_i](),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,ct,"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,Et,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[Ou](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
|
|
79
|
-
`),void 0,"versionWarning");if(b(this,ne,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let s=t.demand||t.required||t.require;if(s)this.demand(e,s);if(t.demandOption)this.demandOption(e,typeof t.demandOption==="string"?t.demandOption:void 0);if(t.conflicts)this.conflicts(e,t.conflicts);if("default"in t)this.default(e,t.default);if(t.implies!==void 0)this.implies(e,t.implies);if(t.nargs!==void 0)this.nargs(e,t.nargs);if(t.config)this.config(e,t.configParser);if(t.normalize)this.normalize(e);if(t.choices)this.choices(e,t.choices);if(t.coerce)this.coerce(e,t.coerce);if(t.group)this.group(e,t.group);if(t.boolean||t.type==="boolean"){if(this.boolean(e),t.alias)this.boolean(t.alias)}if(t.array||t.type==="array"){if(this.array(e),t.alias)this.array(t.alias)}if(t.number||t.type==="number"){if(this.number(e),t.alias)this.number(t.alias)}if(t.string||t.type==="string"){if(this.string(e),t.alias)this.string(t.alias)}if(t.count||t.type==="count")this.count(e);if(typeof t.global==="boolean")this.global(e,t.global);if(t.defaultDescription)b(this,ne,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let r=t.describe||t.description||t.desc,o=b(this,
|
|
80
|
-
`,"f");Z(this,ve,b(this,ve,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[
|
|
81
|
-
`,"f");Z(this,ve,b(this,ve,"f")+e.join(" "),"f")}}}[Si](e){Un(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]}[Ou](e,t,n){if(!b(this,br,"f")[n])b(this,ae,"f").process.emitWarning(e,t),b(this,br,"f")[n]=!0}[Ru](){b(this,wr,"f").push({options:b(this,ne,"f"),configObjects:b(this,ne,"f").configObjects.slice(0),exitProcess:b(this,at,"f"),groups:b(this,_t,"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,ct,"f").freeze()}[Iu](){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[Hu](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,xr,"f")}[vu](){return b(this,_r,"f")}[_i](){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(/[.:].*/,""))}[Pu](){return this[Ei]().version||"unknown"}[Lu](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}[Ei](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 r=b(this,ae,"f").findUp(s,(o,i)=>{if(i.includes("package.json"))return"package.json";else return});Je(r,void 0,b(this,ae,"f")),n=JSON.parse(b(this,ae,"f").readFileSync(r,"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[Ai](n),b(this,ne,"f")[e].push(n)})}[qn](e,t,n,s){this[Ci](e,t,n,s,(r,o,i)=>{b(this,ne,"f")[r][o]=i})}[$i](e,t,n,s){this[Ci](e,t,n,s,(r,o,i)=>{b(this,ne,"f")[r][o]=(b(this,ne,"f")[r][o]||[]).concat(i)})}[Ci](e,t,n,s,r){if(Array.isArray(n))n.forEach((o)=>{e(o,s)});else if(((o)=>typeof o==="object")(n))for(let o of Un(n))e(o,n[o]);else r(t,this[Ai](n),s)}[Ai](e){if(e==="__proto__")return"___proto___";return e}[Ti](e,t){return this[qn](this[Ti].bind(this),"key",e,t),this}[Fi](){var e,t,n,s,r,o,i,l,u,a,c,d;let f=b(this,wr,"f").pop();Je(f,void 0,b(this,ae,"f"));let p;e=this,t=this,n=this,s=this,r=this,o=this,i=this,l=this,u=this,a=this,c=this,d=this,{options:{set value(g){Z(e,ne,g,"f")}}.value,configObjects:p,exitProcess:{set value(g){Z(t,at,g,"f")}}.value,groups:{set value(g){Z(n,_t,g,"f")}}.value,output:{set value(g){Z(s,ve,g,"f")}}.value,exitError:{set value(g){Z(r,Gt,g,"f")}}.value,hasOutput:{set value(g){Z(o,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(a,Qe,g,"f")}}.value,parseFn:{set value(g){Z(c,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,ct,"f").unfreeze()}[Nu](e,t){return gn(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[Mu].bind(this),getContext:this[Bu].bind(this),getHasOutput:this[ju].bind(this),getLoggerInstance:this[Wu].bind(this),getParseContext:this[Uu].bind(this),getParserConfiguration:this[_n].bind(this),getUsageConfiguration:this[vu].bind(this),getUsageInstance:this[Ju].bind(this),getValidationInstance:this[Ku].bind(this),hasParseCallback:this[Er].bind(this),isGlobalContext:this[qu].bind(this),postProcess:this[En].bind(this),reset:this[Oi].bind(this),runValidation:this[Ri].bind(this),runYargsParserAndExecuteCommands:this[Ds].bind(this),setHasOutput:this[zu].bind(this)}}[Mu](){return b(this,Ce,"f")}[Bu](){return b(this,ws,"f")}[ju](){return b(this,et,"f")}[Wu](){return b(this,bn,"f")}[Uu](){return b(this,wn,"f")||{}}[Ju](){return b(this,ue,"f")}[Ku](){return b(this,Ee,"f")}[Er](){return!!b(this,tt,"f")}[qu](){return b(this,Dr,"f")}[En](e,t,n,s){if(n)return e;if(ke(e))return e;if(!t)e=this[Tu](e);if(this[_n]()["parse-positional-numbers"]||this[_n]()["parse-positional-numbers"]===void 0)e=this[Lu](e);if(s)e=hn(e,this,b(this,ct,"f").getMiddleware(),!1);return e}[Oi](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((o)=>{n[o]=!0,(e[o]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(b(this,Dn,"f"),Object.keys(b(this,_t,"f")).reduce((o,i)=>{let l=b(this,_t,"f")[i].filter((u)=>!(u in n));if(l.length>0)o[i]=l;return o},{})),Z(this,_t,{},"f");let s=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],r=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(s.forEach((o)=>{t[o]=(b(this,ne,"f")[o]||[]).filter((i)=>!n[i])}),r.forEach((o)=>{t[o]=zt(b(this,ne,"f")[o],(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):Du(this,b(this,ae,"f")),"f"),Z(this,Ee,b(this,Ee,"f")?b(this,Ee,"f").reset(n):Cu(this,b(this,ue,"f"),b(this,ae,"f")),"f"),Z(this,Ce,b(this,Ce,"f")?b(this,Ce,"f").reset():yu(b(this,ue,"f"),b(this,Ee,"f"),b(this,ct,"f"),b(this,ae,"f")),"f"),!b(this,ze,"f"))Z(this,ze,_u(this,b(this,ue,"f"),b(this,Ce,"f"),b(this,ae,"f")),"f");return b(this,ct,"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}[Hu](e,t){return b(this,ae,"f").path.relative(e,t)}[Ds](e,t,n,s=0,r=!1){var o,i,l,u;let a=!!n||r;e=e||b(this,Xt,"f"),b(this,ne,"f").__=b(this,ae,"f").y18n.__,b(this,ne,"f").configuration=this[_n]();let c=!!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,lt,"f")&&p[w])m=!0;else if(w===b(this,Et,"f")&&p[w])y=!0}),p.$0=this.$0,this.parsed=f,s===0)b(this,ue,"f").clearCachedHelpMessage();try{if(this[_i](),t)return this[En](p,c,!!n,!1);if(b(this,lt,"f")){if([b(this,lt,"f")].concat(h[b(this,lt,"f")]||[]).filter((C)=>C.length>1).includes(""+p._[p._.length-1]))p._.pop(),m=!0}Z(this,Dr,!1,"f");let w=b(this,Ce,"f").getCommands(),k=((o=b(this,ze,"f"))===null||o===void 0?void 0:o.completionKey)?[(i=b(this,ze,"f"))===null||i===void 0?void 0:i.completionKey,...(u=this.getAliases()[(l=b(this,ze,"f"))===null||l===void 0?void 0:l.completionKey])!==null&&u!==void 0?u:[]].some((_)=>Object.prototype.hasOwnProperty.call(p,_)):!1,D=m||k||r;if(p._.length){if(w.length){let _;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 x=b(this,Ce,"f").runCommand(S,this,f,C+1,r,m||y||r);return this[En](x,c,!!n,!1)}else if(!_&&S!==b(this,Qe,"f")){_=S;break}if(!b(this,Ce,"f").hasDefaultCommand()&&b(this,Sr,"f")&&_&&!D)b(this,Ee,"f").recommendCommands(_,w)}if(b(this,Qe,"f")&&p._.includes(b(this,Qe,"f"))&&!k){if(b(this,at,"f"))Yt(!0);this.showCompletionScript(),this.exit(0)}}if(b(this,Ce,"f").hasDefaultCommand()&&!D){let _=b(this,Ce,"f").runCommand(null,this,f,0,r,m||y||r);return this[En](_,c,!!n,!1)}if(k){if(b(this,at,"f"))Yt(!0);e=[].concat(e);let _=e.slice(e.indexOf(`--${b(this,ze,"f").completionKey}`)+1);return b(this,ze,"f").getCompletion(_,(C,S)=>{if(C)throw new $e(C.message);(S||[]).forEach((x)=>{b(this,bn,"f").log(x)}),this.exit(0)}),this[En](p,!c,!!n,!1)}if(!b(this,et,"f")){if(m){if(b(this,at,"f"))Yt(!0);a=!0,this.showHelp((_)=>{b(this,bn,"f").log(_),this.exit(0)})}else if(y){if(b(this,at,"f"))Yt(!0);a=!0,b(this,ue,"f").showVersion("log"),this.exit(0)}}if(!a&&b(this,ne,"f").skipValidation.length>0)a=Object.keys(p).some((_)=>b(this,ne,"f").skipValidation.indexOf(_)>=0&&p[_]===!0);if(!a){if(f.error)throw new $e(f.error.message);if(!k){let _=this[Ri](h,{},f.error);if(!n)g=hn(p,this,b(this,ct,"f").getMiddleware(),!0);if(g=this[Nu](_,g!==null&&g!==void 0?g:p),ke(g)&&!n)g=g.then(()=>hn(p,this,b(this,ct,"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,c,!!n,!0)}[Ri](e,t,n,s){let r={...this.getDemandedOptions()};return(o)=>{if(n)throw new $e(n.message);b(this,Ee,"f").nonOptionCount(o),b(this,Ee,"f").requiredArguments(o,r);let i=!1;if(b(this,xn,"f"))i=b(this,Ee,"f").unknownCommands(o);if(b(this,kn,"f")&&!i)b(this,Ee,"f").unknownArguments(o,e,t,!!s);else if(b(this,Sn,"f"))b(this,Ee,"f").unknownArguments(o,e,{},!1,!1);b(this,Ee,"f").limitedChoices(o),b(this,Ee,"f").implications(o),b(this,Ee,"f").conflicting(o)}}[zu](){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 bu(e){return!!e&&typeof e.getInternalMethods==="function"}var qy=Yu(bi),Xu=qy;var Zu=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,Qu=/[\t\n\v\f\r (*_~]/,Hy=/[.,:;!?]$/;function ed(e){if(Hy.test(e))return e.slice(-1);if(e.endsWith(")")&&Vu(e,"(")<Vu(e,")"))return")";return}function td(e){let t=e.split(""),n=(r,o)=>{for(let i=r;i<o;i++)if(t[i]!==`
|
|
78
|
+
`;f.forEach((g)=>{p+=g}),t.fail(p)}};let u={};o.conflicts=function(d,f){if(V("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((p)=>{o.conflicts(p,d[p])});else{if(e.global(d),!u[d])u[d]=[];if(Array.isArray(f))f.forEach((p)=>o.conflicts(d,p));else u[d].push(f)}},o.getConflicting=()=>u,o.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))})})},o.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=$u(d,y);if(w<=3&&w<h)h=w,g=y}if(g)t.fail(s("Did you mean %s?",g))},o.reset=function(d){return i=zt(i,(f)=>!d[f]),u=zt(u,(f)=>!d[f]),o};let a=[];return o.freeze=function(){a.push({implied:i,conflicting:u})},o.unfreeze=function(){let d=a.pop();Je(d,void 0,n),{implied:i,conflicting:u}=d},o}var xi=[],bs;function ws(e,t,n,s){bs=s;let r={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return r;let o=/\.json|\..*rc$/.test(e.extends),i=null;if(!o)try{i=import.meta.resolve(e.extends)}catch(l){return e}else i=Jy(t,e.extends);Uy(i),xi.push(i),r=o?JSON.parse(bs.readFileSync(i,"utf8")):s.require(e.extends),delete e.extends,r=ws(r,bs.path.dirname(i),n,bs)}return xi=[],n?Tu(r,e):Object.assign({},r,e)}function Uy(e){if(xi.indexOf(e)>-1)throw new Ce(`Circular extended configurations: '${e}'.`)}function Jy(e,t){return bs.path.resolve(e,t)}function Tu(e,t){let n={};function s(r){return r&&typeof r==="object"&&!Array.isArray(r)}Object.assign(n,e);for(let r of Object.keys(t))if(s(t[r])&&s(n[r]))n[r]=Tu(e[r],t[r]);else n[r]=t[r];return n}var Z=function(e,t,n,s,r){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!r)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!r:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?r.call(e,n):r?r.value=n:t.set(e,n),n},b=function(e,t,n,s){if(n==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(e):s?s.value:t.get(e)},Ae,yn,ks,ze,Qe,br,Gt,bn,wr,at,kr,ct,_t,et,lt,Dr,wn,ve,ne,xr,Sr,tt,kn,qn,Dn,Xt,_r,ie,xn,Sn,_n,de,Er,Et,$e;function Gu(e){return(t=[],n=e.process.cwd(),s)=>{let r=new Xu(t,n,s,e);return Object.defineProperty(r,"argv",{get:()=>r.parse(),enumerable:!0}),r.help(),r.version(),r}}var Fu=Symbol("copyDoubleDash"),Ou=Symbol("copyDoubleDash"),Si=Symbol("deleteFromParserHintObject"),Ru=Symbol("emitWarning"),Iu=Symbol("freeze"),vu=Symbol("getDollarZero"),En=Symbol("getParserConfiguration"),Pu=Symbol("getUsageConfiguration"),_i=Symbol("guessLocale"),Lu=Symbol("guessVersion"),Nu=Symbol("parsePositionalNumbers"),Ei=Symbol("pkgUp"),Vt=Symbol("populateParserHintArray"),Hn=Symbol("populateParserHintSingleValueDictionary"),$i=Symbol("populateParserHintArrayDictionary"),Ci=Symbol("populateParserHintDictionary"),Ai=Symbol("sanitizeKey"),Ti=Symbol("setKey"),Fi=Symbol("unfreeze"),Mu=Symbol("validateAsync"),Bu=Symbol("getCommandInstance"),ju=Symbol("getContext"),Wu=Symbol("getHasOutput"),Uu=Symbol("getLoggerInstance"),Ju=Symbol("getParseContext"),Ku=Symbol("getUsageInstance"),qu=Symbol("getValidationInstance"),$r=Symbol("hasParseCallback"),Hu=Symbol("isGlobalContext"),$n=Symbol("postProcess"),zu=Symbol("rebase"),Oi=Symbol("reset"),Ds=Symbol("runYargsParserAndExecuteCommands"),Ri=Symbol("runValidation"),Yu=Symbol("setHasOutput"),Cn=Symbol("kTrackManuallySetKeys"),Ky="en_US";class Xu{constructor(e=[],t,n,s){this.customScriptName=!1,this.parsed=!1,Ae.set(this,void 0),yn.set(this,void 0),ks.set(this,{commands:[],fullCommands:[]}),ze.set(this,null),Qe.set(this,null),br.set(this,"show-hidden"),Gt.set(this,null),bn.set(this,!0),wr.set(this,{}),at.set(this,!0),kr.set(this,[]),ct.set(this,void 0),_t.set(this,{}),et.set(this,!1),lt.set(this,null),Dr.set(this,!0),wn.set(this,void 0),ve.set(this,""),ne.set(this,void 0),xr.set(this,void 0),Sr.set(this,{}),tt.set(this,null),kn.set(this,null),qn.set(this,{}),Dn.set(this,{}),Xt.set(this,void 0),_r.set(this,!1),ie.set(this,void 0),xn.set(this,!1),Sn.set(this,!1),_n.set(this,!1),de.set(this,void 0),Er.set(this,{}),Et.set(this,null),$e.set(this,void 0),Z(this,ie,s,"f"),Z(this,Xt,e,"f"),Z(this,yn,t,"f"),Z(this,xr,n,"f"),Z(this,ct,new ki(this),"f"),this.$0=this[vu](),this[Oi](),Z(this,Ae,b(this,Ae,"f"),"f"),Z(this,de,b(this,de,"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,br,"f"),Z(this,wn,this[Ou](),"f"),b(this,ie,"f").y18n.setLocale(Ky)}addHelpOpt(e,t){if(V("[string|boolean] [string]",[e,t],arguments.length),b(this,lt,"f"))this[Si](b(this,lt,"f")),Z(this,lt,null,"f");if(e===!1&&t===void 0)return this;return Z(this,lt,typeof e==="string"?e:"help","f"),this.boolean(b(this,lt,"f")),this.describe(b(this,lt,"f"),t||b(this,de,"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,br,"f");return this.boolean(n),this.describe(n,t||b(this,de,"f").deferY18nLookup("Show hidden options")),b(this,ne,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return V("<object|string|array> [string|array]",[e,t],arguments.length),this[$i](this.alias.bind(this),"alias",e,t),this}array(e){return V("<array|string>",[e],arguments.length),this[Vt]("array",e),this[Cn](e),this}boolean(e){return V("<array|string>",[e],arguments.length),this[Vt]("boolean",e),this[Cn](e),this}check(e,t){return V("<function> [boolean]",[e,t],arguments.length),this.middleware((n,s)=>mn(()=>e(n,s.getOptions()),(r)=>{if(!r)b(this,de,"f").fail(b(this,ie,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof r==="string"||r instanceof Error)b(this,de,"f").fail(r.toString(),r);return n},(r)=>(b(this,de,"f").fail(r.message?r.message:r.toString(),r),n)),!1,t),this}choices(e,t){return V("<object|string|array> [string|array]",[e,t],arguments.length),this[$i](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 Ce("coerce callback must be provided");for(let s of e)this.coerce(s,t);return this}else if(typeof e==="object"){for(let s of Object.keys(e))this.coerce(s,e[s]);return this}if(!t)throw new Ce("coerce callback must be provided");let n=e;return b(this,ne,"f").key[n]=!0,b(this,ct,"f").addCoerceMiddleware((s,r)=>{var o;let i=(o=r.getAliases()[n])!==null&&o!==void 0?o:[],l=[n,...i].filter((u)=>Object.prototype.hasOwnProperty.call(s,u));if(l.length===0)return s;return mn(()=>t(s[l[0]]),(u)=>(l.forEach((a)=>{s[a]=u}),s),(u)=>{throw new Ce(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=ws(e,b(this,yn,"f"),this[En]()["deep-merge-config"]||!1,b(this,ie,"f")),b(this,ne,"f").configObjects=(b(this,ne,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||b(this,de,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((s)=>{b(this,ne,"f").config[s]=n||!0}),this}completion(e,t,n){if(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,r,o){return V("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,s,r,o],arguments.length),b(this,Ae,"f").addHandler(e,t,n,s,r,o),this}commands(e,t,n,s,r,o){return this.command(e,t,n,s,r,o)}commandDir(e,t){V("<string> [object]",[e,t],arguments.length);let n=b(this,xr,"f")||b(this,ie,"f").require;return b(this,Ae,"f").addDirectory(e,n,b(this,ie,"f").getCallerFile(),t),this}count(e){return V("<array|string>",[e],arguments.length),this[Vt]("count",e),this[Cn](e),this}default(e,t,n){if(V("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)wi(e,b(this,ie,"f")),b(this,ne,"f").defaultDescription[e]=n;if(typeof t==="function"){if(wi(e,b(this,ie,"f")),!b(this,ne,"f").defaultDescription[e])b(this,ne,"f").defaultDescription[e]=b(this,de,"f").functionDescription(t);t=t.call()}return this[Hn](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)=>{Je(n,!0,b(this,ie,"f")),this.demandOption(s,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")Je(n,!0,b(this,ie,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((s)=>{Je(n,!0,b(this,ie,"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[Hn](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[Ti](e,!0),b(this,de,"f").describe(e,t),this}detectLocale(e){return V("<boolean>",[e],arguments.length),Z(this,bn,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,de,"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,de,"f").example(e,t);return this}exit(e,t){if(Z(this,et,!0,"f"),Z(this,Gt,t,"f"),b(this,at,"f"))b(this,ie,"f").process.exit(e)}exitProcess(e=!0){return V("[boolean]",[e],arguments.length),Z(this,at,e,"f"),this}fail(e){if(V("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new Ce("Invalid first argument. Expected function or boolean 'false'");return b(this,de,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(V("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,s)=>{b(this,ze,"f").getCompletion(e,(r,o)=>{if(r)s(r);else n(o)})});else return b(this,ze,"f").getCompletion(e,t)}getDemandedOptions(){return 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,bn,"f")}getExitProcess(){return b(this,at,"f")}getGroups(){return Object.assign({},b(this,_t,"f"),b(this,Dn,"f"))}getHelp(){if(Z(this,et,!0,"f"),!b(this,de,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[Ds](b(this,Xt,"f"),void 0,void 0,0,!0);if(xe(t))return t.then(()=>b(this,de,"f").help())}let e=b(this,Ae,"f").runDefaultBuilderOn(this);if(xe(e))return e.then(()=>b(this,de,"f").help())}return Promise.resolve(b(this,de,"f").help())}getOptions(){return b(this,ne,"f")}getStrict(){return b(this,xn,"f")}getStrictCommands(){return b(this,Sn,"f")}getStrictOptions(){return b(this,_n,"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,_t,"f")[t];if(b(this,Dn,"f")[t])delete b(this,Dn,"f")[t];let s={};return b(this,_t,"f")[t]=(n||[]).concat(e).filter((r)=>{if(s[r])return!1;return s[r]=!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[_i](),b(this,ie,"f").y18n.getLocale();return Z(this,bn,!1,"f"),b(this,ie,"f").y18n.setLocale(e),this}middleware(e,t,n){return b(this,ct,"f").addMiddleware(e,!!t,n)}nargs(e,t){return V("<string|object|array> [number]",[e,t],arguments.length),this[Hn](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[Cn](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[Cn](e),b(this,Et,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[Ru](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
|
|
79
|
+
`),void 0,"versionWarning");if(b(this,ne,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let s=t.demand||t.required||t.require;if(s)this.demand(e,s);if(t.demandOption)this.demandOption(e,typeof t.demandOption==="string"?t.demandOption:void 0);if(t.conflicts)this.conflicts(e,t.conflicts);if("default"in t)this.default(e,t.default);if(t.implies!==void 0)this.implies(e,t.implies);if(t.nargs!==void 0)this.nargs(e,t.nargs);if(t.config)this.config(e,t.configParser);if(t.normalize)this.normalize(e);if(t.choices)this.choices(e,t.choices);if(t.coerce)this.coerce(e,t.coerce);if(t.group)this.group(e,t.group);if(t.boolean||t.type==="boolean"){if(this.boolean(e),t.alias)this.boolean(t.alias)}if(t.array||t.type==="array"){if(this.array(e),t.alias)this.array(t.alias)}if(t.number||t.type==="number"){if(this.number(e),t.alias)this.number(t.alias)}if(t.string||t.type==="string"){if(this.string(e),t.alias)this.string(t.alias)}if(t.count||t.type==="count")this.count(e);if(typeof t.global==="boolean")this.global(e,t.global);if(t.defaultDescription)b(this,ne,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let r=t.describe||t.description||t.desc,o=b(this,de,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(o,e)||typeof r==="string")this.describe(e,r);if(t.hidden)this.hide(e);if(t.requiresArg)this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){if(V("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[Iu](),typeof e>"u")e=b(this,Xt,"f");if(typeof t==="object")Z(this,kn,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,at,!1,"f");let s=this[Ds](e,!!t),r=this.parsed;if(b(this,ze,"f").setParsed(this.parsed),xe(s))return s.then((o)=>{if(b(this,tt,"f"))b(this,tt,"f").call(this,b(this,Gt,"f"),o,b(this,ve,"f"));return o}).catch((o)=>{if(b(this,tt,"f"))b(this,tt,"f")(o,this.parsed.argv,b(this,ve,"f"));throw o}).finally(()=>{this[Fi](),this.parsed=r});else{if(b(this,tt,"f"))b(this,tt,"f").call(this,b(this,Gt,"f"),s,b(this,ve,"f"));this[Fi](),this.parsed=r}return s}parseAsync(e,t,n){let s=this.parse(e,t,n);return!xe(s)?Promise.resolve(s):s}parseSync(e,t,n){let s=this.parse(e,t,n);if(xe(s))throw new Ce(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return s}parserConfiguration(e){return V("<object>",[e],arguments.length),Z(this,Sr,e,"f"),this}pkgConf(e,t){V("<string> [string]",[e,t],arguments.length);let n=null,s=this[Ei](t||b(this,yn,"f"));if(s[e]&&typeof s[e]==="object")n=ws(s[e],t||b(this,yn,"f"),this[En]()["deep-merge-config"]||!1,b(this,ie,"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,(o,i)=>{if(o==="type"&&!["string","number","boolean"].includes(i))return!1;return n.includes(o)});let s=b(this,ks,"f").fullCommands[b(this,ks,"f").fullCommands.length-1],r=s?b(this,Ae,"f").cmdToParseOptions(s):{array:[],alias:{},default:{},demand:{}};return Jn(r).forEach((o)=>{let i=r[o];if(Array.isArray(i)){if(i.indexOf(e)!==-1)t[o]=!0}else if(i[e]&&!(o in t))t[o]=i[e]}),this.group(e,b(this,de,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return V("[boolean]",[e],arguments.length),Z(this,_r,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[Hn](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,wn,"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,de,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[Ds](b(this,Xt,"f"),void 0,void 0,0,!0);if(xe(n))return n.then(()=>{b(this,de,"f").showHelp(e)}),this}let t=b(this,Ae,"f").runDefaultBuilderOn(this);if(xe(t))return t.then(()=>{b(this,de,"f").showHelp(e)}),this}return b(this,de,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return V("[boolean|string] [string]",[e,t],arguments.length),b(this,de,"f").showHelpOnFail(e,t),this}showVersion(e){return V("[string|function]",[e],arguments.length),b(this,de,"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,xn,e!==!1,"f"),this}strictCommands(e){return V("[boolean]",[e],arguments.length),Z(this,Sn,e!==!1,"f"),this}strictOptions(e){return V("[boolean]",[e],arguments.length),Z(this,_n,e!==!1,"f"),this}string(e){return V("<array|string>",[e],arguments.length),this[Vt]("string",e),this[Cn](e),this}terminalWidth(){return V([],0),b(this,ie,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return V("<object>",[e],arguments.length),Z(this,bn,!1,"f"),b(this,ie,"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(Je(e,null,b(this,ie,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,s);else throw new Ce(".usage() description must start with $0 if being used as alias for .command()");else return b(this,de,"f").usage(e),this}usageConfiguration(e){return V("<object>",[e],arguments.length),Z(this,Er,e,"f"),this}version(e,t,n){if(V("[boolean|string] [string] [string]",[e,t,n],arguments.length),b(this,Et,"f"))this[Si](b(this,Et,"f")),b(this,de,"f").version(void 0),Z(this,Et,null,"f");if(arguments.length===0)n=this[Lu](),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,Et,typeof e==="string"?e:"version","f"),t=t||b(this,de,"f").deferY18nLookup("Show version number"),b(this,de,"f").version(n||void 0),this.boolean(b(this,Et,"f")),this.describe(b(this,Et,"f"),t),this}wrap(e){return V("<number|null|undefined>",[e],arguments.length),b(this,de,"f").wrap(e),this}[(Ae=new WeakMap,yn=new WeakMap,ks=new WeakMap,ze=new WeakMap,Qe=new WeakMap,br=new WeakMap,Gt=new WeakMap,bn=new WeakMap,wr=new WeakMap,at=new WeakMap,kr=new WeakMap,ct=new WeakMap,_t=new WeakMap,et=new WeakMap,lt=new WeakMap,Dr=new WeakMap,wn=new WeakMap,ve=new WeakMap,ne=new WeakMap,xr=new WeakMap,Sr=new WeakMap,tt=new WeakMap,kn=new WeakMap,qn=new WeakMap,Dn=new WeakMap,Xt=new WeakMap,_r=new WeakMap,ie=new WeakMap,xn=new WeakMap,Sn=new WeakMap,_n=new WeakMap,de=new WeakMap,Er=new WeakMap,Et=new WeakMap,$e=new WeakMap,Fu)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[Ou](){return{log:(...e)=>{if(!this[$r]())console.log(...e);if(Z(this,et,!0,"f"),b(this,ve,"f").length)Z(this,ve,b(this,ve,"f")+`
|
|
80
|
+
`,"f");Z(this,ve,b(this,ve,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[$r]())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")}}}[Si](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,de,"f").getDescriptions()[e]}[Ru](e,t,n){if(!b(this,wr,"f")[n])b(this,ie,"f").process.emitWarning(e,t),b(this,wr,"f")[n]=!0}[Iu](){b(this,kr,"f").push({options:b(this,ne,"f"),configObjects:b(this,ne,"f").configObjects.slice(0),exitProcess:b(this,at,"f"),groups:b(this,_t,"f"),strict:b(this,xn,"f"),strictCommands:b(this,Sn,"f"),strictOptions:b(this,_n,"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,kn,"f")}),b(this,de,"f").freeze(),b(this,$e,"f").freeze(),b(this,Ae,"f").freeze(),b(this,ct,"f").freeze()}[vu](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(b(this,ie,"f").process.argv()[0]))t=b(this,ie,"f").process.argv().slice(1,2);else t=b(this,ie,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let s=this[zu](b(this,yn,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&s.length<n.length?s:n}).join(" ").trim(),b(this,ie,"f").getEnv("_")&&b(this,ie,"f").getProcessArgvBin()===b(this,ie,"f").getEnv("_"))e=b(this,ie,"f").getEnv("_").replace(`${b(this,ie,"f").path.dirname(b(this,ie,"f").process.execPath())}/`,"");return e}[En](){return b(this,Sr,"f")}[Pu](){return b(this,Er,"f")}[_i](){if(!b(this,bn,"f"))return;let e=b(this,ie,"f").getEnv("LC_ALL")||b(this,ie,"f").getEnv("LC_MESSAGES")||b(this,ie,"f").getEnv("LANG")||b(this,ie,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[Lu](){return this[Ei]().version||"unknown"}[Nu](e){let t=e["--"]?e["--"]:e._;for(let n=0,s;(s=t[n])!==void 0;n++)if(b(this,ie,"f").Parser.looksLikeNumber(s)&&Number.isSafeInteger(Math.floor(parseFloat(`${s}`))))t[n]=Number(s);return e}[Ei](e){let t=e||"*";if(b(this,qn,"f")[t])return b(this,qn,"f")[t];let n={};try{let s=e||b(this,ie,"f").mainFilename;if(b(this,ie,"f").path.extname(s))s=b(this,ie,"f").path.dirname(s);let r=b(this,ie,"f").findUp(s,(o,i)=>{if(i.includes("package.json"))return"package.json";else return});Je(r,void 0,b(this,ie,"f")),n=JSON.parse(b(this,ie,"f").readFileSync(r,"utf8"))}catch(s){}return b(this,qn,"f")[t]=n||{},b(this,qn,"f")[t]}[Vt](e,t){t=[].concat(t),t.forEach((n)=>{n=this[Ai](n),b(this,ne,"f")[e].push(n)})}[Hn](e,t,n,s){this[Ci](e,t,n,s,(r,o,i)=>{b(this,ne,"f")[r][o]=i})}[$i](e,t,n,s){this[Ci](e,t,n,s,(r,o,i)=>{b(this,ne,"f")[r][o]=(b(this,ne,"f")[r][o]||[]).concat(i)})}[Ci](e,t,n,s,r){if(Array.isArray(n))n.forEach((o)=>{e(o,s)});else if(((o)=>typeof o==="object")(n))for(let o of Jn(n))e(o,n[o]);else r(t,this[Ai](n),s)}[Ai](e){if(e==="__proto__")return"___proto___";return e}[Ti](e,t){return this[Hn](this[Ti].bind(this),"key",e,t),this}[Fi](){var e,t,n,s,r,o,i,l,u,a,c,d;let f=b(this,kr,"f").pop();Je(f,void 0,b(this,ie,"f"));let p;e=this,t=this,n=this,s=this,r=this,o=this,i=this,l=this,u=this,a=this,c=this,d=this,{options:{set value(g){Z(e,ne,g,"f")}}.value,configObjects:p,exitProcess:{set value(g){Z(t,at,g,"f")}}.value,groups:{set value(g){Z(n,_t,g,"f")}}.value,output:{set value(g){Z(s,ve,g,"f")}}.value,exitError:{set value(g){Z(r,Gt,g,"f")}}.value,hasOutput:{set value(g){Z(o,et,g,"f")}}.value,parsed:this.parsed,strict:{set value(g){Z(i,xn,g,"f")}}.value,strictCommands:{set value(g){Z(l,Sn,g,"f")}}.value,strictOptions:{set value(g){Z(u,_n,g,"f")}}.value,completionCommand:{set value(g){Z(a,Qe,g,"f")}}.value,parseFn:{set value(g){Z(c,tt,g,"f")}}.value,parseContext:{set value(g){Z(d,kn,g,"f")}}.value}=f,b(this,ne,"f").configObjects=p,b(this,de,"f").unfreeze(),b(this,$e,"f").unfreeze(),b(this,Ae,"f").unfreeze(),b(this,ct,"f").unfreeze()}[Mu](e,t){return mn(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[Bu].bind(this),getContext:this[ju].bind(this),getHasOutput:this[Wu].bind(this),getLoggerInstance:this[Uu].bind(this),getParseContext:this[Ju].bind(this),getParserConfiguration:this[En].bind(this),getUsageConfiguration:this[Pu].bind(this),getUsageInstance:this[Ku].bind(this),getValidationInstance:this[qu].bind(this),hasParseCallback:this[$r].bind(this),isGlobalContext:this[Hu].bind(this),postProcess:this[$n].bind(this),reset:this[Oi].bind(this),runValidation:this[Ri].bind(this),runYargsParserAndExecuteCommands:this[Ds].bind(this),setHasOutput:this[Yu].bind(this)}}[Bu](){return b(this,Ae,"f")}[ju](){return b(this,ks,"f")}[Wu](){return b(this,et,"f")}[Uu](){return b(this,wn,"f")}[Ju](){return b(this,kn,"f")||{}}[Ku](){return b(this,de,"f")}[qu](){return b(this,$e,"f")}[$r](){return!!b(this,tt,"f")}[Hu](){return b(this,Dr,"f")}[$n](e,t,n,s){if(n)return e;if(xe(e))return e;if(!t)e=this[Fu](e);if(this[En]()["parse-positional-numbers"]||this[En]()["parse-positional-numbers"]===void 0)e=this[Nu](e);if(s)e=gn(e,this,b(this,ct,"f").getMiddleware(),!1);return e}[Oi](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((o)=>{n[o]=!0,(e[o]||[]).forEach((i)=>{n[i]=!0})}),Object.assign(b(this,Dn,"f"),Object.keys(b(this,_t,"f")).reduce((o,i)=>{let l=b(this,_t,"f")[i].filter((u)=>!(u in n));if(l.length>0)o[i]=l;return o},{})),Z(this,_t,{},"f");let s=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],r=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(s.forEach((o)=>{t[o]=(b(this,ne,"f")[o]||[]).filter((i)=>!n[i])}),r.forEach((o)=>{t[o]=zt(b(this,ne,"f")[o],(i)=>!n[i])}),t.envPrefix=b(this,ne,"f").envPrefix,Z(this,ne,t,"f"),Z(this,de,b(this,de,"f")?b(this,de,"f").reset(n):Du(this,b(this,ie,"f")),"f"),Z(this,$e,b(this,$e,"f")?b(this,$e,"f").reset(n):Au(this,b(this,de,"f"),b(this,ie,"f")),"f"),Z(this,Ae,b(this,Ae,"f")?b(this,Ae,"f").reset():bu(b(this,de,"f"),b(this,$e,"f"),b(this,ct,"f"),b(this,ie,"f")),"f"),!b(this,ze,"f"))Z(this,ze,Eu(this,b(this,de,"f"),b(this,Ae,"f"),b(this,ie,"f")),"f");return b(this,ct,"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}[zu](e,t){return b(this,ie,"f").path.relative(e,t)}[Ds](e,t,n,s=0,r=!1){var o,i,l,u;let a=!!n||r;e=e||b(this,Xt,"f"),b(this,ne,"f").__=b(this,ie,"f").y18n.__,b(this,ne,"f").configuration=this[En]();let c=!!b(this,ne,"f").configuration["populate--"],d=Object.assign({},b(this,ne,"f").configuration,{"populate--":!0}),f=b(this,ie,"f").Parser.detailed(e,Object.assign({},b(this,ne,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),p=Object.assign(f.argv,b(this,kn,"f")),g=void 0,h=f.aliases,m=!1,y=!1;if(Object.keys(p).forEach((w)=>{if(w===b(this,lt,"f")&&p[w])m=!0;else if(w===b(this,Et,"f")&&p[w])y=!0}),p.$0=this.$0,this.parsed=f,s===0)b(this,de,"f").clearCachedHelpMessage();try{if(this[_i](),t)return this[$n](p,c,!!n,!1);if(b(this,lt,"f")){if([b(this,lt,"f")].concat(h[b(this,lt,"f")]||[]).filter((E)=>E.length>1).includes(""+p._[p._.length-1]))p._.pop(),m=!0}Z(this,Dr,!1,"f");let w=b(this,Ae,"f").getCommands(),D=((o=b(this,ze,"f"))===null||o===void 0?void 0:o.completionKey)?[(i=b(this,ze,"f"))===null||i===void 0?void 0:i.completionKey,...(u=this.getAliases()[(l=b(this,ze,"f"))===null||l===void 0?void 0:l.completionKey])!==null&&u!==void 0?u:[]].some((_)=>Object.prototype.hasOwnProperty.call(p,_)):!1,k=m||D||r;if(p._.length){if(w.length){let _;for(let E=s||0,S;p._[E]!==void 0;E++)if(S=String(p._[E]),w.includes(S)&&S!==b(this,Qe,"f")){let x=b(this,Ae,"f").runCommand(S,this,f,E+1,r,m||y||r);return this[$n](x,c,!!n,!1)}else if(!_&&S!==b(this,Qe,"f")){_=S;break}if(!b(this,Ae,"f").hasDefaultCommand()&&b(this,_r,"f")&&_&&!k)b(this,$e,"f").recommendCommands(_,w)}if(b(this,Qe,"f")&&p._.includes(b(this,Qe,"f"))&&!D){if(b(this,at,"f"))Yt(!0);this.showCompletionScript(),this.exit(0)}}if(b(this,Ae,"f").hasDefaultCommand()&&!k){let _=b(this,Ae,"f").runCommand(null,this,f,0,r,m||y||r);return this[$n](_,c,!!n,!1)}if(D){if(b(this,at,"f"))Yt(!0);e=[].concat(e);let _=e.slice(e.indexOf(`--${b(this,ze,"f").completionKey}`)+1);return b(this,ze,"f").getCompletion(_,(E,S)=>{if(E)throw new Ce(E.message);(S||[]).forEach((x)=>{b(this,wn,"f").log(x)}),this.exit(0)}),this[$n](p,!c,!!n,!1)}if(!b(this,et,"f")){if(m){if(b(this,at,"f"))Yt(!0);a=!0,this.showHelp((_)=>{b(this,wn,"f").log(_),this.exit(0)})}else if(y){if(b(this,at,"f"))Yt(!0);a=!0,b(this,de,"f").showVersion("log"),this.exit(0)}}if(!a&&b(this,ne,"f").skipValidation.length>0)a=Object.keys(p).some((_)=>b(this,ne,"f").skipValidation.indexOf(_)>=0&&p[_]===!0);if(!a){if(f.error)throw new Ce(f.error.message);if(!D){let _=this[Ri](h,{},f.error);if(!n)g=gn(p,this,b(this,ct,"f").getMiddleware(),!0);if(g=this[Mu](_,g!==null&&g!==void 0?g:p),xe(g)&&!n)g=g.then(()=>gn(p,this,b(this,ct,"f").getMiddleware(),!1))}}}catch(w){if(w instanceof Ce)b(this,de,"f").fail(w.message,w);else throw w}return this[$n](g!==null&&g!==void 0?g:p,c,!!n,!0)}[Ri](e,t,n,s){let r={...this.getDemandedOptions()};return(o)=>{if(n)throw new Ce(n.message);b(this,$e,"f").nonOptionCount(o),b(this,$e,"f").requiredArguments(o,r);let i=!1;if(b(this,Sn,"f"))i=b(this,$e,"f").unknownCommands(o);if(b(this,xn,"f")&&!i)b(this,$e,"f").unknownArguments(o,e,t,!!s);else if(b(this,_n,"f"))b(this,$e,"f").unknownArguments(o,e,{},!1,!1);b(this,$e,"f").limitedChoices(o),b(this,$e,"f").implications(o),b(this,$e,"f").conflicting(o)}}[Yu](){Z(this,et,!0,"f")}[Cn](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 wu(e){return!!e&&typeof e.getInternalMethods==="function"}var qy=Gu(bi),Vu=qy;var Qu=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,ed=/[\t\n\v\f\r (*_~]/,Hy=/[.,:;!?]$/;function td(e){if(Hy.test(e))return e.slice(-1);if(e.endsWith(")")&&Zu(e,"(")<Zu(e,")"))return")";return}function nd(e){let t=e.split(""),n=(r,o)=>{for(let i=r;i<o;i++)if(t[i]!==`
|
|
82
82
|
`)t[i]="\x00"},s=0;while(s<e.length){let o=s===0||e[s-1]===`
|
|
83
83
|
`?/^ {0,3}(?:(`{3,})[^`\n]*|(~{3,})[^\n]*)(?=\n|$)/.exec(e.slice(s)):null;if(o){let l=o[1]??o[2],u=new RegExp(`
|
|
84
84
|
{0,3}${l[0]==="`"?"`":"~"}{${l.length},}[ ]*\r?(?=
|
|
85
85
|
|$)`,"g");u.lastIndex=s+o[0].length;let a=u.exec(e),c=a?a.index+a[0].length:e.length;n(s,c),s=c;continue}let i=e[s];if(i==="\\"){s+=2;continue}if(i==="`"){let l=0;while(e[s+l]==="`")l++;let u=s+l,a=-1;while(u<e.length){if(e[u]===`
|
|
86
|
-
`&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(u)))break;if(e[u]!=="`"){u++;continue}let c=0;while(e[u+c]==="`")c++;if(c===l){a=u+c;break}u+=c}if(a<0){s+=l;continue}n(s,a),s=a;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 zy(e,{markdown:t=!0}={}){let n=t?
|
|
87
|
-
`,{mode:384}),process.platform!=="win32")
|
|
86
|
+
`&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(u)))break;if(e[u]!=="`"){u++;continue}let c=0;while(e[u+c]==="`")c++;if(c===l){a=u+c;break}u+=c}if(a<0){s+=l;continue}n(s,a),s=a;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 zy(e,{markdown:t=!0}={}){let n=t?nd(e):e,s=[];for(let r of n.matchAll(Qu)){let o=r[0];if(o.startsWith("<"))continue;let i=r.index??0,l=i>0?n[i-1]:"";if(l&&!ed.test(l))s.push({url:o,side:"before",char:e[i-1]});let u=o.match(/[^\x00-\x7f]|>/);if(u)s.push({url:o,side:"after",char:u[0]});else{let a=td(o);if(a&&!(a===")"&&l==="("))s.push({url:o,side:"trailing",char:a})}}return s}function Ke(e,t=!1,n=console.error,{sides:s=["before","after","trailing"],markdown:r=!0}={}){let o=zy(e,{markdown:r}),i=o.filter((d)=>d.side==="trailing"&&s.includes("trailing"));if(i.length)n(`⚠ URL ends in punctuation Slack may take into the link: ${i.map((d)=>`${JSON.stringify(d.url)} → ${JSON.stringify(xs(`x ${d.url}`).slice(2))}`).join(", ")}. If the ${JSON.stringify(i[0].char)} is not part of the URL, send the suggested form (or --fix-urls).`);let l=o.filter((d)=>d.side!=="trailing"&&s.includes(d.side));if(!l.length)return;let u=l.map((d)=>d.side==="before"?`${JSON.stringify(d.url)} (glued to ${JSON.stringify(d.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(d.url)} (runs into ${JSON.stringify(d.char)} after it; non-ASCII in a URL is OK only if intended, otherwise send ${JSON.stringify(xs(`x ${d.url}`).slice(2))} or put an ASCII space after the URL)`),a=l.some((d)=>d.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",c=`Ambiguous URL boundary: ${u.join(", ")}. ${a}Put the URL on its own line, or wrap it as <url> / <url|label>. Use --fix-urls to wrap them, or --allow-url-adjacent to warn only.`;if(!t)throw Error(c);n(`⚠ Warning: ${c}`)}function xs(e){let t=nd(e),n="",s=0;for(let r of t.matchAll(Qu)){let o=r.index??0;if(r[0].startsWith("<"))continue;let i=e.slice(o,o+r[0].length),l=i.search(/[^\x00-\x7f]|>/);if(l>=0)i=i.slice(0,l);while(td(i))i=i.slice(0,-1);let u=o>0?t[o-1]:"";if(!(i.length<r[0].length||u&&!ed.test(u))||!/^https?:\/\/./i.test(i))continue;n+=e.slice(s,o)+`<${i}>`,s=o+i.length}return n+e.slice(s)}function Zu(e,t){return e.split(t).length-1}import{existsSync as _s,readFileSync as Pi,writeFileSync as Ii,mkdirSync as id,chmodSync as sd}from"node:fs";import{homedir as Yy}from"node:os";import{join as An,dirname as Li}from"node:path";function Ni(){return process.env.HOME||Yy()}function ad(){return An(Ni(),".config","slack-cli","profiles.json")}function Cr(){return An(process.cwd(),".slack-cli","workspace")}function Ar(){return An(Ni(),".slack-cli","workspace")}function Es(){let e=ad();if(!_s(e))return{profiles:{}};return JSON.parse(Pi(e,"utf8"))}function Gy(e){let t=ad();if(id(Li(t),{recursive:!0}),process.platform!=="win32"&&_s(t))sd(t,384);if(Ii(t,JSON.stringify(e,null,2)+`
|
|
87
|
+
`,{mode:384}),process.platform!=="win32")sd(t,384)}function zn(e){if(!_s(e))return;return Pi(e,"utf8").trim()||void 0}function rd(e,t){let n=Li(e);id(n,{recursive:!0});let s=An(n,".gitignore");if(!_s(s))Ii(s,`*
|
|
88
88
|
`);Ii(e,t+`
|
|
89
89
|
`)}function Xy(e){let t={};for(let n of e.split(`
|
|
90
|
-
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[o]=i}return t}function
|
|
91
|
-
`+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=vi(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let l=process.env.SLACK_WORKSPACE;if(l){let c=n[l];if(!c)throw Error(`Workspace "${l}" not found. Available: ${s.join(", ")||"(none)"}`);return c.token}let u=
|
|
90
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[o]=i}return t}function od(e){if(!_s(e))return{};try{return Xy(Pi(e,"utf8"))}catch{return{}}}function vi(e,t){let n=Ni(),s=e;while(!0){for(let i of[An(s,".slack-term",".env.local"),An(s,".env.local")]){let l=od(i);for(let u of t)if(l[u])return l[u]}if(s===n)break;let o=Li(s);if(o===s)break;s=o}let r=od(An(n,".slack-term",".env.local"));for(let o of t)if(r[o])return r[o];return}function Mi(){let e=Es(),t=zn(Cr()),n=zn(Ar()),s=t??n;return Object.entries(e.profiles).map(([r,o])=>{let i=Ss(e,r);return{name:r,profile:{...o,...i?{cookie:i}:{}},current:r===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 cd(e){let t=Es();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],Gy(t)}function ld(e,t=!1){let n=Es();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)rd(Ar(),e);else rd(Cr(),e)}function $s(e){let n=Es().profiles,s=Object.keys(n);if(e){let c=n[e];if(!c)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return c.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let r=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(r&&s.length===0)return r;let o=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((c)=>c&&!c.startsWith("xoxb-"));if(o&&s.length>0){let c=vi(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(o!==c){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=vi(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let l=process.env.SLACK_WORKSPACE;if(l){let c=n[l];if(!c)throw Error(`Workspace "${l}" not found. Available: ${s.join(", ")||"(none)"}`);return c.token}let u=zn(Cr());if(u){let c=n[u];if(!c)throw Error(`Workspace "${u}" (from .slack-cli/workspace) not found in profiles.`);return c.token}let a=zn(Ar());if(a){let c=n[a];if(!c)throw Error(`Workspace "${a}" (from ~/.slack-cli/workspace) not found in profiles.`);return c.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 Le(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Bi(e){let t=
|
|
101
|
-
`,{mode:384}),process.platform!=="win32")
|
|
102
|
-
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[o]=i}return t}function
|
|
103
|
-
`):[];for(let[r,o]of Object.entries(t)){let i=s.findIndex((u)=>{let a=u.trim();return a.startsWith(r+"=")||a.startsWith(r+" =")}),l=`${r}=${o}`;if(i!==-1)s[i]=l;else s.push(l)}if(process.platform!=="win32"&&
|
|
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 Bi(e){let t=Es(),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 r=vi(process.cwd(),["SLACK_COOKIE"]);if(r)return r;let o=process.env.SLACK_WORKSPACE;if(o)return Ss(t,o);let i=zn(Cr());if(i)return Ss(t,i);let l=zn(Ar());if(l)return Ss(t,l);return}import{existsSync as Gn,readFileSync as Fr,writeFileSync as dd,mkdirSync as fd,chmodSync as Tr}from"node:fs";import{homedir as Vy}from"node:os";import{join as Yn,dirname as Wi}from"node:path";function Ui(){return process.env.HOME||Vy()}function pd(){return Yn(Ui(),".config","slack-cli","profiles.json")}function Ji(){return Yn(process.cwd(),".slack-cli","workspace")}function Ki(){return Yn(Ui(),".slack-cli","workspace")}function Vn(){let e=pd();if(!Gn(e))return{profiles:{}};return JSON.parse(Fr(e,"utf8"))}function qi(e){let t=pd();if(fd(Wi(t),{recursive:!0}),process.platform!=="win32"&&Gn(t))Tr(t,384);if(dd(t,JSON.stringify(e,null,2)+`
|
|
101
|
+
`,{mode:384}),process.platform!=="win32")Tr(t,384)}function Xn(e){if(!Gn(e))return;return Fr(e,"utf8").trim()||void 0}function Zy(e){let t={};for(let n of e.split(`
|
|
102
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);t[o]=i}return t}function ud(e){if(!Gn(e))return{};try{return Zy(Fr(e,"utf8"))}catch{return{}}}function ji(e,t){let n=Ui(),s=e;while(!0){for(let i of[Yn(s,".slack-term",".env.local"),Yn(s,".env.local")]){let l=ud(i);for(let u of t)if(l[u])return l[u]}if(s===n)break;let o=Wi(s);if(o===s)break;s=o}let r=ud(Yn(n,".slack-term",".env.local"));for(let o of t)if(r[o])return r[o];return}function Hi(e,t){fd(Wi(e),{recursive:!0});let n=Gn(e)?Fr(e,"utf8"):"",s=n?n.split(`
|
|
103
|
+
`):[];for(let[r,o]of Object.entries(t)){let i=s.findIndex((u)=>{let a=u.trim();return a.startsWith(r+"=")||a.startsWith(r+" =")}),l=`${r}=${o}`;if(i!==-1)s[i]=l;else s.push(l)}if(process.platform!=="win32"&&Gn(e))Tr(e,384);if(dd(e,s.join(`
|
|
104
104
|
`).trimEnd()+`
|
|
105
|
-
`,{mode:384}),process.platform!=="win32")
|
|
106
|
-
`+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let i=ji(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let l=process.env.SLACK_WORKSPACE;if(l){let c=n[l];if(!c)throw Error(`Workspace "${l}" not found. Available: ${s.join(", ")||"(none)"}`);return c.token}let u=
|
|
105
|
+
`,{mode:384}),process.platform!=="win32")Tr(e,384)}function As(){let e=Vn(),t=Xn(Ji()),n=Xn(Ki()),s=t??n;return Object.entries(e.profiles).map(([r,o])=>{let i=Cs(e,r);return{name:r,profile:{...o,...i?{cookie:i}:{}},current:r===s}})}function Or(e,t){let n=Vn();if(t.identity&&t.cookie){n.users??={};let s=n.users[t.identity]??{};n.users[t.identity]={...s,cookie:t.cookie};let{cookie:r,...o}=t;n.profiles[e]=o}else n.profiles[e]=t;qi(n)}function zi(e,t){let n=Vn(),s=n.profiles[e];if(!s)throw Error(`Profile not found: ${e}`);if(s.identity)n.users??={},n.users[s.identity]={...n.users[s.identity]??{},cookie:t};else s.cookie=t;qi(n)}function hd(e,t,n){let s=Vn();s.users??={},s.users[e]={...s.users[e]??{},cookie:t,...n?{source:n}:{}},qi(s)}function Cs(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 gd(e){let n=Vn().profiles,s=Object.keys(n);if(e){let c=n[e];if(!c)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return c.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let r=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(r&&s.length===0)return r;let o=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((c)=>c&&!c.startsWith("xoxb-"));if(o&&s.length>0){let c=ji(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(o!==c){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=ji(process.cwd(),["SLACK_TOKEN"]);if(i)return i;let l=process.env.SLACK_WORKSPACE;if(l){let c=n[l];if(!c)throw Error(`Workspace "${l}" not found. Available: ${s.join(", ")||"(none)"}`);return c.token}let u=Xn(Ji());if(u){let c=n[u];if(!c)throw Error(`Workspace "${u}" (from .slack-cli/workspace) not found in profiles.`);return c.token}let a=Xn(Ki());if(a){let c=n[a];if(!c)throw Error(`Workspace "${a}" (from ~/.slack-cli/workspace) not found in profiles.`);return c.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,28 +112,28 @@ ${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
|
|
115
|
+
`+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function Rr(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Zt(e){let t=Vn(),n=t.profiles;if(e)return Cs(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let r=ji(process.cwd(),["SLACK_COOKIE"]);if(r)return r;let o=process.env.SLACK_WORKSPACE;if(o)return Cs(t,o);let i=Xn(Ji());if(i)return Cs(t,i);let l=Xn(Ki());if(l)return Cs(t,l);return}function Ir(e){let t=[],n=(o)=>{if(!o)return;let i=t[t.length-1];if(i?.type==="text")i.text+=o;else t.push({type:"text",text:o})},s=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,r=0;for(let o of e.matchAll(s)){let i=o.index??0;if(n(e.slice(r,i)),o[1]){t.push(o[2]?{type:"link",url:o[1],text:o[2]}:{type:"link",url:o[1]}),r=i+o[0].length;continue}let l=o[0];while(/[.,:;!?'"*_~]$/.test(l)||l.endsWith(")")&&md(l,"(")<md(l,")"))l=l.slice(0,-1);t.push({type:"link",url:l}),r=i+l.length}return n(e.slice(r)),t}function md(e,t){return e.split(t).length-1}var Qy={"&":"&","<":"<",">":">"};function eb(e){if(typeof e!=="string"||!/^[0-9a-f]+(-[0-9a-f]+)*$/i.test(e))return[];let t=e.split("-").map((r)=>parseInt(r,16)),n=String.fromCodePoint(...t),s=String.fromCodePoint(...t.filter((r)=>r!==65039));return n===s?[n]:[n,s]}function tb(e){let t=[],n=(o)=>{for(let i of o)if(i===`
|
|
116
116
|
`)t.push(null);else if(!/\s/u.test(i))t.push(...Qy[i]??i)},s=(o)=>{switch(o.type){case"text":n(String(o.text??""));break;case"link":case"message_mention":n(String(o.url??""));break;case"user":n(String(o.user_id??""));break;case"channel":n(String(o.channel_id??""));break;case"usergroup":n(String(o.usergroup_id??""));break;case"broadcast":n(String(o.range??""));break;case"emoji":t.push([`:${String(o.name??"")}:`,...eb(o.unicode)].filter((i)=>i!=="::"));break;default:break}},r=(o)=>{let i=Array.isArray(o.elements)?o.elements:[];if(o.type==="rich_text_list"||o.type==="rich_text")i.forEach((l,u)=>{if(u>0)t.push(null);r(l)});else i.forEach(s)};return e.forEach((o,i)=>{if(i>0)t.push(null);let l=o;if(l.type==="rich_text")r(l)}),t}function nb(e,t,n){if(typeof t==="string"){let r=n;while(r<e.length&&e[r]!==t)r++;return r<e.length?[r,1]:[-1,0]}let s=[-1,0];for(let r of t){let o=[...r];for(let i=n;i+o.length<=e.length&&(s[0]<0||i<s[0]);i++)if(o.every((l,u)=>e[i+u]===l)){s=[i,o.length];break}}return s}function sb(e,t){if(e.includes(`
|
|
117
|
-
`)||!Array.isArray(t)||!t.some((g)=>g?.type==="rich_text"))return e;let n=tb(t);if(!n.includes(null))return e;let s=[...e],r=t[0].elements,i=t[t.length-1].elements,l=Array.isArray(r)&&r[0]?.type==="rich_text_preformatted",u=Array.isArray(i)&&i[i.length-1]?.type==="rich_text_preformatted",a=0,c=-1,d=l,f=[];for(let g of n){if(g===null){d=!0;continue}let[h,m]=nb(s,g,a);if(h<0)return e;if(d)f.push([c+1,h]),d=!1;c=h+m-1,a=h+m}if((d||u)&&c>=0)f.push([c+1,s.length]);let p=/^(?:[-*+•]|\d{1,9}[.)]|>|>)$/;for(let[g,h]of f){let m=g;if(s.lastIndexOf("<",g-1)>s.lastIndexOf(">",g-1)){let
|
|
118
|
-
`;w=!0}y="",m=
|
|
117
|
+
`)||!Array.isArray(t)||!t.some((g)=>g?.type==="rich_text"))return e;let n=tb(t);if(!n.includes(null))return e;let s=[...e],r=t[0].elements,i=t[t.length-1].elements,l=Array.isArray(r)&&r[0]?.type==="rich_text_preformatted",u=Array.isArray(i)&&i[i.length-1]?.type==="rich_text_preformatted",a=0,c=-1,d=l,f=[];for(let g of n){if(g===null){d=!0;continue}let[h,m]=nb(s,g,a);if(h<0)return e;if(d)f.push([c+1,h]),d=!1;c=h+m-1,a=h+m}if((d||u)&&c>=0)f.push([c+1,s.length]);let p=/^(?:[-*+•]|\d{1,9}[.)]|>|>)$/;for(let[g,h]of f){let m=g;if(s.lastIndexOf("<",g-1)>s.lastIndexOf(">",g-1)){let D=s.indexOf(">",g);if(D!==-1&&D<h)m=D+1}let y="",w=g===0;while(m<h)if(s[m]===" "){let D=m;while(D<h&&s[D]===" ")D++;if(w&&p.test(y))w=!1;else{let k=D-m<=2?D-m:1;for(let _=m;_<m+k;_++)s[_]=`
|
|
118
|
+
`;w=!0}y="",m=D}else y+=s[m],m++}return s.join("")}function vr(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.text==="string")t.text=sb(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 Gi(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}var rb=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();async function kd(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>rb)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function Xi(e,t,n,s){return kd(()=>ob(e,t,n,s))}async function ob(e,t,n,s){s=e.startsWith("xoxc-")?s??Zt():void 0;let r={};if(s)r.Cookie=`d=${s}`;let o=await fetch(`${Gi()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(o.status===429){let l=parseInt(o.headers.get("retry-after")??"60",10);throw new qe(isNaN(l)?60:l,t)}let i=await o.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 ib(e,t,n,s){return
|
|
124
|
+
Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${l}`)}return i}function ib(e,t,n,s){return kd(()=>ab(e,t,n,s))}async function ab(e,t,n,s){let r={};if(s)r.Cookie=`d=${s}`;let o=await fetch(`${Gi()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(o.status===429){let l=parseInt(o.headers.get("retry-after")??"60",10);throw new qe(isNaN(l)?60:l,t)}let i=await o.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 cb(e,t,n={},s){let r=new URLSearchParams({token:e,...n});return ib(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()},s)}function Te(e,t,n,s){let r=new URLSearchParams(n).toString();return Xi(e,`${t}?${r}`,{method:"GET"},s)}function Vi(e,t,n,s){return Xi(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function Dd(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return Xi(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function
|
|
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 cb(e,t,n={},s){let r=new URLSearchParams({token:e,...n});return ib(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()},s)}function Te(e,t,n,s){let r=new URLSearchParams(n).toString();return Xi(e,`${t}?${r}`,{method:"GET"},s)}function Vi(e,t,n,s){return Xi(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function Dd(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return Xi(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function Fs(e,t,n){return Dd(e,"agents.sessions.setStatus",{...t,status:n})}function Zi(e,t,n){return Dd(e,"agents.sessions.rename",{...t,title:n})}async function Zn(e,t){let n=await Te(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function xd(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(`${Gi()}/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 r=s.headers.get("x-oauth-scopes")??"",o=await s.json();if(o.ok!==!0)throw Error(`Slack error on auth.test: ${o.error??"unknown"}`);return{userId:o.user_id??"",user:o.user??"",botId:o.bot_id??"",team:o.team??"",url:o.url??"",scopes:r.split(",").map((i)=>i.trim()).filter(Boolean)}}async function Sd(e,t,n){let s=await Te(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function Tn(e,t,n=20,s,r,o,i){let l={channel:t,limit:String(n)};if(s!==void 0)l.oldest=s;if(r!==void 0)l.cursor=r;if(i)l.inclusive="true";return Qi(await Te(e,"conversations.history",l,o))}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)vr(s);return e}async function _d(e,t,n,s=50,r){return Qi(await Te(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},r))}async function Ed(e,t,n,s={},r){let o={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)o.oldest=s.oldest;if(s.cursor!==void 0)o.cursor=s.cursor;return Qi(await Te(e,"conversations.replies",o,r))}async function ea(e,t,n){let s=[],r="";do{let o={limit:"200",types:t,exclude_archived:"true"};if(r)o.cursor=r;let i=await Te(e,"users.conversations",o,n);s.push(...i.channels??[]),r=i.response_metadata?.next_cursor??""}while(r);return s}async function Pr(e,t,n,s,r){await Vi(e,"reactions.add",{channel:t,timestamp:n,name:s},r)}async function $d(e,t,n,s){return((await Te(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((o)=>({name:String(o.name??""),users:Array.isArray(o.users)?o.users.map(String):[]}))}async function Lr(e,t,n,s,r){await Vi(e,"reactions.remove",{channel:t,timestamp:n,name:s},r)}async function lb(e,t,n){let r=(await Vi(e,"conversations.open",{users:t},n)).channel?.id;if(!r)throw Error(`Failed to open DM with user ${t}`);return r}async function Cd(e,t,n){let s="";while(!0){let r={types:"im",limit:"200"};if(s)r.cursor=s;let o=await Te(e,"conversations.list",r,n);for(let i of o.channels??[])if(i.user===t)return String(i.id??"");if(s=o.response_metadata?.next_cursor??"",!s)break}return""}async function Yi(e,t,n,s){let r=await Cd(e,t,n);if(r)return r;let o=s?`${s} (${t})`:t;throw Error(`No existing DM with ${o}. Open it once in Slack first.`)}function Ts(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function yd(e,t){let n=Ts(e.name??""),s=Ts(e.real_name??e.profile?.real_name??""),r=Ts(e.profile?.display_name??"");return n===t||s===t||!!r&&r===t}var Ad=200;async function ub(e,t,n){let s=0,r=new Set,o="";while(!0){let c={limit:"200"};if(o)c.cursor=o;let d=await Te(e,"users.list",c,n);for(let f of d.members??[]){if(s++,f.id)r.add(f.id);if(yd(f,t))return{id:f.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(o=d.response_metadata?.next_cursor??"",!o)break}let i=0,l=0,u=!1,a="";while(!0){let c={types:"im",limit:"200"};if(a)c.cursor=a;let d=await Te(e,"conversations.list",c,n);for(let f of d.channels??[]){let p=f.user;if(!p||r.has(p))continue;if(i>=Ad){u=!0;break}r.add(p),i++;let g;try{g=(await Te(e,"users.info",{user:p},n)).user}catch(h){if(h instanceof qe)throw h;l++;continue}if(g&&yd(g,t))return{id:p,dm:String(f.id??""),workspaceCount:s,connectCount:i,skipped:l,capped:u}}if(u)break;if(a=d.response_metadata?.next_cursor??"",!a)break}return{id:"",workspaceCount:s,connectCount:i,skipped:l,capped:u}}function db(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 ${
|
|
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 ${Ad} 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 ta(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,r=e.indexOf("?"),o=r>=0?new URLSearchParams(e.slice(r)):void 0,i=o?.get("thread_ts")??void 0,a={channel:o?.get("cid")??void 0??n};if(s)a.ts=s;if(i)a.threadTs=i;return a}function fb(e){return ta(e)?.channel}function
|
|
133
|
-
${
|
|
132
|
+
slack user ls --external`)}function ta(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,r=e.indexOf("?"),o=r>=0?new URLSearchParams(e.slice(r)):void 0,i=o?.get("thread_ts")??void 0,a={channel:o?.get("cid")??void 0??n};if(s)a.ts=s;if(i)a.threadTs=i;return a}function fb(e){return ta(e)?.channel}function bd(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function wd(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Nr(e,t,n){let s=fb(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(bd(t))return t;if(wd(t))return Yi(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&bd(t.slice(1)))return t.slice(1);let r=t.startsWith("@"),o=t.slice(1),i=Ts(o);if(r){if(wd(o))return Yi(e,o,n);let a=await Te(e,"auth.test",{},n);if(i==="you"||i==="me"||Ts(a.user??"")===i){let f=a.user_id;if(!f)throw Error("auth.test did not return user_id");return await Cd(e,f,n)||lb(e,f,n)}let d=await ub(e,i,n);if(!d.id)throw db(t,d);if(d.dm)return d.dm;return Yi(e,d.id,n,t)}let l=o.toLowerCase(),u="";while(!0){let a={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(u)a.cursor=u;let c=await Te(e,"conversations.list",a,n);for(let d of c.channels??[])if(String(d.name??"").toLowerCase()===l)return String(d.id??"");if(u=c.response_metadata?.next_cursor??"",!u)break}throw Error(`channel not found: ${t}`)}async function Mr(e,t,n){try{let s=await Te(e,"users.info",{user:t},n),r=s.user?.profile?.display_name,o=r&&r.length>0?r:s.user?.real_name??s.user?.name??t,i=s.user?.name??t;return[o,i]}catch{return[t,t]}}async function Qn(e,t,n){try{let s=await Te(e,"users.info",{user:t},n),r=s.user?.profile?.display_name;if(r&&r.length>0)return r;return s.user?.real_name??s.user?.name??t}catch{return t}}async function Br(e,t){let n=[],s="";while(!0){let r={limit:"200"};if(s)r.cursor=s;let o=await Te(e,"users.list",r,t);if(n.push(...o.members??[]),s=o.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function na(e,t,n){let s=[],r="";while(!0){let o={channel:t,limit:"200"};if(r)o.cursor=r;let i=await Te(e,"conversations.members",o,n);if(s.push(...i.members??[]),r=i.response_metadata?.next_cursor??"",!r)break}return s}async function sa(e,t,n){return Te(e,"users.info",{user:t},n)}async function jr(e,t,n){return Te(e,"conversations.info",{channel:t},n)}async function Td(e,t){let n=await cb(e,"client.boot",{},t),s=typeof n.url==="string"?n.url:void 0;if(!s){let o=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${o}`)}let r=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:s,selfId:typeof r.id==="string"?r.id:""}}var pb=["chat:write","im:write"],hb=["im:history","im:read"];async function Wr(e){let{userId:t,botId:n,team:s,scopes:r}=await xd(e),o="";if(n)try{o=(await Sd(e,n)).appId}catch{o=""}let i=(a)=>r.includes(a),l=pb.filter((a)=>!i(a)),u=hb.filter((a)=>!i(a));return{canSend:l.length===0,canReceiveReplies:u.length===0,ok:l.length===0&&u.length===0,botUserId:t,appId:o,team:s,grantedScopes:r,missingSendScopes:l,missingReplyScopes:u}}function Fd(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function Ur(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let r=["✓ Bot DM scopes are complete (send + read replies)."," Two-way replies also require the Messages Tab, which is not API-detectable.",' If recipients see "Sending messages to this app is turned off", enable it:',` ${n} → App Home → "Messages Tab" ON + "Allow users to send messages".`];return t?r:[...r,...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 pa,resolve as jb}from"node:path";import{homedir as Wb}from"node:os";import{readdirSync as Is,readFileSync as Rs,existsSync as nt,copyFileSync as ia,mkdtempSync as vd,rmSync as Pd}from"node:fs";import{homedir as Kr,tmpdir as Ld}from"node:os";import{join as ye,dirname as yb}from"node:path";import{pbkdf2Sync as Jr,createDecipheriv as Nd,createHash as bb,timingSafeEqual as wb}from"node:crypto";import{execSync as Md,execFileSync as kb}from"node:child_process";function Os(e,t){let n=0,s=0,r=t;while(r<e.length){let o=e[r++];if(n+=(o&127)*2**s,(o&128)===0)break;s+=7}return{value:n,pos:r}}function gb(e){let t=0,n=0,s=0;while(t<e.length){let i=e[t++];if(n+=(i&127)*2**s,(i&128)===0)break;s+=7}let r=Buffer.allocUnsafe(n),o=0;while(t<e.length&&o<n){let i=e[t++],l=i&3;if(l===0){let u=i>>2;if(u>=60){let a=u-59;u=0;for(let c=0;c<a;c++)u+=e[t++]*2**(8*c)}u+=1,e.copy(r,o,t,t+u),t+=u,o+=u}else{let u,a;if(l===1)u=4+(i>>2&7),a=(i>>5&7)*256+e[t++];else if(l===2)u=1+(i>>2),a=e[t]+e[t+1]*256,t+=2;else u=1+(i>>2),a=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let c=o-a;for(let d=0;d<u&&o<n;d++)r[o++]=r[c++]}}return o===n?r:r.subarray(0,o)}function ra(e,t){let n=Os(e,t),s=Os(e,n.pos);return{handle:{offset:n.value,size:s.value},pos:s.pos}}function Od(e,t){let{offset:n,size:s}=t,r=e.subarray(n,n+s);return e[n+s]===1?gb(r):Buffer.from(r)}function mb(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,s=[],r=0,o=Buffer.alloc(0);while(r<n){let i=Os(e,r),l=Os(e,i.pos),u=Os(e,l.pos);r=u.pos;let a=i.value,c=l.value,d=u.value,f=e.subarray(r,r+c);r+=c;let p=e.subarray(r,r+d);r+=d,o=Buffer.concat([o.subarray(0,a),f]),s.push(p)}return s}function Rd(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=ra(e,t),s=ra(e,n.pos),r=Od(e,s.handle),o=[];for(let i of mb(r))try{let{handle:l}=ra(i,0);o.push(Od(e,l))}catch{}return Buffer.concat(o)}catch{return Buffer.alloc(0)}}function Id(){let e=process.env.HOME??Kr();if(process.platform==="darwin")return[ye(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[ye(e,".config","Slack","Local Storage","leveldb"),ye(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),ye(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??ye(e,"AppData","Roaming");return[ye(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function Db(){let e=process.env.HOME??Kr();if(process.platform==="darwin")return ye(e,"Library","Application Support","Slack","Cookies");return""}function xb(e,t){if(e.length<35||e.slice(0,3).toString()!=="v10")throw Error("Not a v10 encrypted cookie");let n=e.slice(19,35),s=e.slice(35),r=Nd("aes-128-cbc",t,n);return r.setAutoPadding(!0),Buffer.concat([r.update(s),r.final()]).toString("utf8")}function Sb(){if(process.platform!=="darwin")return;let e=Db();if(!nt(e))return;let t;try{t=Md('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=Jr(t,"saltysalt",1003,16,"sha1");try{let{default:s}=ms("bun:sqlite"),r=new s(e,{readonly:!0}),o=r.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(r.close(),!o)return;return xb(Buffer.from(o.encrypted_value),n)}catch{return}}function Bd(e){if(!nt(e))return[];let t=Is(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 a=Rs(ye(e,i));u=i.endsWith(".ldb")?Rd(a).toString("latin1")||a.toString("latin1"):a.toString("latin1")}catch{u=""}return n.set(i,u),u},r=new Map;for(let i of t){let l=s(i);for(let u of l.matchAll(/"token":"(xoxc-[^"]+)"/g)){let a=u[1],c=a.split("-")[1]??"";if(!c||a.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=r.get(c);if(!m||a.length>m.token.length){let y={token:a,teamId:c},w=g?.[1]??m?.url,D=h?.[1]??m?.teamName;if(w)y.url=w;if(D)y.teamName=D;r.set(c,y)}}}let o=t.map((i)=>s(i).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let i of r.values()){if(i.teamName)continue;let l=o.indexOf(i.teamId);if(l!==-1){let u=Math.max(0,l-500),a=Math.min(o.length,l+500),d=o.slice(u,a).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 a=o.indexOf(u);if(a!==-1){let c=Math.max(0,a-500),d=Math.min(o.length,a+500),p=o.slice(c,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(p?.[1]){i.teamName=p[1];continue}}i.teamName=u.split("-").map((c)=>c.charAt(0).toUpperCase()+c.slice(1)).join(" ")}}}return[...r.values()]}async function aa(e){let t=e??Id().find(nt);if(!t)throw Error(`Slack desktop app LevelDB not found at:
|
|
133
|
+
${Id().join(`
|
|
134
134
|
`)}
|
|
135
|
-
Is Slack installed and opened at least once?`);let n=
|
|
136
|
-
`)){let u=l.trim();if(u.startsWith("[")){o="",i="";continue}let a=u.indexOf("=");if(a===-1)continue;let c=u.slice(0,a).trim().toLowerCase(),d=u.slice(a+1).trim();if(c==="name")o=d;if(c==="path")i=d.split(/[\\/]/).pop()??d;if(o&&i)s[i]=o,o="",i=""}}catch{}return s}function
|
|
135
|
+
Is Slack installed and opened at least once?`);let n=Bd(t),s=e?void 0:Sb();if(s)for(let r of n)r.cookie=s;return n}function _b(e,t){try{return JSON.parse(Rs(ye(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function ca(){let e=la();if(!e||!nt(e))return[];let t=["Default",...Is(e).filter((s)=>s.startsWith("Profile "))],n=[];for(let s of t){let r=ye(e,s,"Local Storage","leveldb"),o=Bd(r);if(o.length===0)continue;let i=_b(e,s);n.push({profileDir:s,...i?{email:i}:{},label:jd(e,s),sessions:o})}return n}function oa(e,t,n,s=!1){let r=(o,i)=>{try{let l=Nd("aes-128-cbc",t,o);l.setAutoPadding(!0);let u=Buffer.concat([l.update(i),l.final()]);if(u.subarray(0,5).toString()==="xoxd-")return u.toString("utf8");if(u.length>=37){let a=bb("sha256").update(n).digest();if(wb(u.subarray(0,32),a)){let c=u.subarray(32).toString("utf8");if(c.startsWith("xoxd-"))return c}}return}catch{return}};return r(Buffer.alloc(16,32),e.slice(3))??(s&&e.length>=35?r(e.slice(19,35),e.slice(35)):void 0)}function jd(e,t){let n=(s,r)=>{if(s&&r)return`${s} (${r})`;return s||r||t};try{let r=JSON.parse(Rs(ye(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(r&&(r.name||r.user_name))return n(r.name??"",r.user_name??"")}catch{}try{let r=JSON.parse(Rs(ye(e,t,"Preferences"),"utf8")).profile;return n(r?.name??"",r?.user_name??"")}catch{return t}}function la(){let e=process.env.HOME??Kr();if(process.platform==="darwin")return ye(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return ye(process.env.XDG_CONFIG_HOME??ye(e,".config"),"google-chrome");return""}function Eb(){try{return kb("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function vs(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=la();if(!nt(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let i;try{i=Md('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=Jr(i,"saltysalt",1003,16,"sha1")}let n=["Default",...Is(e).filter((i)=>i.startsWith("Profile "))],s=[],r,o=!1;for(let i of n){let l=[ye(e,i,"Network","Cookies"),ye(e,i,"Cookies")].find(nt);if(!l)continue;let u=vd(ye(Ld(),"slack-chrome-cookies-")),a=ye(u,"Cookies");try{if(ia(l,a),nt(`${l}-wal`))ia(`${l}-wal`,`${a}-wal`);let{default:c}=ms("bun:sqlite"),d=new c(a,{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=oa(p,Jr("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(g==="v11"){if(!r){let m=Eb();if(m)r=Jr(m,"saltysalt",1,16,"sha1")}if(r)h=oa(p,r,f.host_key);else o=!0}}else if(g==="v10"&&t)h=oa(p,t,f.host_key,!0);else if(g!=="v10")throw Error("Unknown cookie encryption prefix.");if(h)s.push({profileDir:i,profileName:jd(e,i),cookie:h})}catch(c){if(c instanceof Error&&(c.message.includes("unsupported v20")||c.message.includes("Unknown cookie")))throw c}finally{Pd(u,{recursive:!0,force:!0})}}if(o&&s.length===0)throw Error("Chrome v11 cookie key is unavailable. Install secret-tool and unlock the GNOME keyring, or use slack auth firefox.");return{candidates:s,totalProfiles:n.length}}async function ua(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=la();if(!nt(e))throw Error("Chrome profile directory was not found.");let t=new Map(vs().candidates.map((r)=>[r.profileDir,r.cookie])),n=new Map,s=["Default",...Is(e).filter((r)=>r.startsWith("Profile "))];for(let r of s){let o=ye(e,r,"Local Storage","leveldb");if(!nt(o))continue;let i;try{i=await aa(o)}catch{continue}for(let l of i){if(n.has(l.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let u=t.get(r);if(u)l.cookie=u;n.set(l.teamId,l)}}return[...n.values()]}function $b(){let e=process.env.HOME??Kr();if(process.platform==="darwin")return[ye(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[ye(e,".mozilla","firefox"),ye(e,"snap","firefox","common",".mozilla","firefox"),ye(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[ye(process.env.APPDATA??ye(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function Cb(e){let t=ye(e,"profiles.ini"),n=nt(t)?t:ye(yb(e),"profiles.ini"),s={};if(!nt(n))return s;try{let r=Rs(n,"utf8"),o="",i="";for(let l of r.split(`
|
|
136
|
+
`)){let u=l.trim();if(u.startsWith("[")){o="",i="";continue}let a=u.indexOf("=");if(a===-1)continue;let c=u.slice(0,a).trim().toLowerCase(),d=u.slice(a+1).trim();if(c==="name")o=d;if(c==="path")i=d.split(/[\\/]/).pop()??d;if(o&&i)s[i]=o,o="",i=""}}catch{}return s}function qr(){let e=[];for(let t of $b().filter(nt)){let n=Cb(t),s;try{s=Is(t)}catch{continue}for(let r of s){let o=ye(t,r,"cookies.sqlite");if(!nt(o))continue;let i=vd(ye(Ld(),"slack-firefox-cookies-")),l=ye(i,"cookies.sqlite");try{ia(o,l);let{default:u}=ms("bun:sqlite"),a=new u(l,{readonly:!0}),c=a.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(a.close(),!c?.value||!c.value.startsWith("xoxd-"))continue;let d=n[r]??r;e.push({profileDir:r,profileName:d,cookie:c.value})}catch{}finally{Pd(i,{recursive:!0,force:!0})}}}return e}import{readFileSync as da,writeFileSync as fa,mkdirSync as Ab,existsSync as Ps,rmSync as Tb}from"node:fs";import{join as ut}from"node:path";import{createDecipheriv as Hr}from"node:crypto";import{spawnSync as Fb}from"node:child_process";var Ob=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),Rb=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),Ib=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),bt="C:\\ProgramData\\slack-term-abe";function vb(){let e=process.env.LOCALAPPDATA??ut(process.env.USERPROFILE??"","AppData","Local");return ut(e,"Google","Chrome","User Data")}var Pb=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')
|
|
@@ -221,37 +221,37 @@ 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 Mb(e,t){let s=4+e.readUInt32LE(0)+4,r=e[s];if(r===1||r===2){let o=e.subarray(s+1,s+13),i=e.subarray(s+13,s+45),l=e.subarray(s+45,s+61),u=r===1?
|
|
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=da(o),u=
|
|
226
|
-
Could not extract the cookie automatically: ${o instanceof Error?o.message:String(o)}`),console.error("Fallback (manual): Chrome > DevTools (F12) > Application > Cookies > https://app.slack.com > copy the `d` value,"),console.error("then set it via an env file: SLACK_COOKIE=xoxd-... (in .slack-term/.env.local)"),process.exit(1)}}async function
|
|
224
|
+
`}function Mb(e,t){let s=4+e.readUInt32LE(0)+4,r=e[s];if(r===1||r===2){let o=e.subarray(s+1,s+13),i=e.subarray(s+13,s+45),l=e.subarray(s+45,s+61),u=r===1?Hr("aes-256-gcm",Ob,o):Hr("chacha20-poly1305",Rb,o,{authTagLength:16});return u.setAuthTag(l),Buffer.concat([u.update(i),u.final()])}if(r===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let o=e.subarray(s+33,s+45),i=e.subarray(s+45,s+77),l=e.subarray(s+77,s+93),u=Buffer.from(t.map((c,d)=>c^Ib[d])),a=Hr("aes-256-gcm",u,o);return a.setAuthTag(l),Buffer.concat([a.update(i),a.final()])}throw Error(`Unsupported app-bound key flag: ${r}`)}function Bb(e,t){let n=t.subarray(3,15),s=t.subarray(15,t.length-16),r=t.subarray(t.length-16),o=Hr("aes-256-gcm",e,n);return o.setAuthTag(r),Buffer.concat([o.update(s),o.final()]).subarray(32).toString("utf8")}async function Wd(e){if(process.platform!=="win32")throw Error("Windows-only");let t=vb();if(!Ps(ut(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);Ab(bt,{recursive:!0});let n=ut(bt,"extract.ps1");fa(n,Nb(t,e)),fa(ut(bt,"inner_dpapi.ps1"),Pb),fa(ut(bt,"inner_cng.ps1"),Lb);let s=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,r=Fb("powershell",["-NoProfile","-Command",s],{encoding:"utf8",windowsHide:!0});if(r.status!==0&&r.error)throw Error(`Failed to launch elevated helper: ${r.error.message}`);let o=ut(bt,"out.bin"),i=ut(bt,"Cookies");if(!Ps(o)||!Ps(i)){let l=Ps(ut(bt,"log.txt"))?da(ut(bt,"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=da(o),u=Ps(ut(bt,"cng.bin"))?da(ut(bt,"cng.bin")):void 0,a=Mb(l,u),{Database:c}=ms("bun:sqlite"),d=new c(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=Bb(a,p);if(!g.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return g}finally{if(!process.env.SLACK_KEEP_ABE)Tb(bt,{recursive:!0,force:!0})}}var Ub=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],Jb=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function es(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Kb(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:Ub}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function qb(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:Jb}},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 Ls(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 r=await Zn(t,s),o=es(r.team),i;if(n)i=n;else if(e)i=await Qt(e,`Workspace name [${o}]: `)||o;else i=o;let l=null;if(e){console.log(""),console.log("Where to save the token?"),console.log(" 1) ./.env.local (current directory) [default]"),console.log(" 2) ./.slack-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=pa(process.cwd(),".slack-term",".env.local");else if(u==="3")l=pa(Wb(),".slack-term",".env.local");else if(u==="4")l=null;else l=pa(process.cwd(),".env.local")}if(l===null)if(Or(i,{token:t,...r,...s?{cookie:s}:{}}),console.log(`Saved workspace "${i}" to profiles.json: ${r.team} (${r.user})`),process.env.SLACK_MCP_XOXP_TOKEN)console.log(""),console.log("Warning: SLACK_MCP_XOXP_TOKEN is set — it conflicts with profiles."),console.log(" Unset it: unset SLACK_MCP_XOXP_TOKEN (and remove from ~/.zshrc / ~/.bashrc)");else console.log(` Run: slack auth use -g ${i}`);else{let u={SLACK_TOKEN:t};if(s)u.SLACK_COOKIE=s;Hi(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 ha(e,t=!1,n="auto",s=!1){console.error("Scanning Slack desktop app...");let r=await aa();if(r.length===0)console.error("No sessions found. Make sure Slack is installed and you have signed in at least once."),process.exit(1);if(process.platform==="linux"&&n!=="none"&&r.some((o)=>!o.cookie)&&await Ls(e,t)){let o=[];if(n!=="chrome")for(let i of qr())o.push({source:"Firefox",profileName:i.profileName,cookie:i.cookie});if(n==="chrome"||n==="all"||n==="auto"&&o.length===0)try{for(let i of vs().candidates)o.push({source:"Chrome",profileName:i.profileName,cookie:i.cookie})}catch(i){console.error(i instanceof Error?i.message:String(i))}if(o.length===1){for(let i of r)i.cookie??=o[0].cookie;console.log(`Found Slack session cookie in ${o[0].source} profile: ${o[0].profileName}`)}else if(o.length>1)console.log("Multiple browser sessions found. Choose one later with slack auth chrome or slack auth firefox.");if(r.some((i)=>!i.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await ga(r,e,s)}async function ga(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let s=e[0],r=s.teamName??s.teamId;console.log(`Found workspace: ${r}${s.cookie?" (+ xoxd cookie)":""}`),await Fn(t,s.token,es(r),s.cookie),console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- token: slack auth login");return}for(let s of e){let r=s.teamName??s.teamId,o=es(r);Or(o,{token:s.token,team:r,teamId:s.teamId,url:s.url??"",user:"",...s.cookie?{cookie:s.cookie}:{}}),console.log(`Added workspace "${o}": ${r}${s.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let s=es(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 Ud(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-",r=n==="user"?"User OAuth Token":"Bot User OAuth Token";console.log(""),console.log("Find your token here:"),console.log(" https://api.slack.com/apps"),console.log(" -> Select your app -> OAuth & Permissions"),console.log(` -> Copy the "${r}" (starts with ${s})`),console.log("");let o=await Qt(e,"Paste your token: ");if(!o)console.error("No token provided."),process.exit(1);if(!o.startsWith(s))console.error(`Expected a ${s} token, got: ${o.slice(0,10)}...`),process.exit(1);await Fn(e,o)}async function zr(e,t){let n=t==="user"?Kb():qb(),s=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",r=t==="user"?"xoxp-":"xoxb-";if(t==="bot")console.log("Note: bot tokens cannot use search:read (user-only scope)."),console.log(" The news and search commands will not work with a bot token."),console.log("");console.log("Step 1 -Create your Slack app:"),console.log(" Open: https://api.slack.com/apps"),console.log(' Click "Create New App" -> "From a manifest" -> select your workspace'),console.log(" Paste this manifest (JSON tab):"),console.log(""),console.log("-------------------------------------------------------------"),console.log(n),console.log("-------------------------------------------------------------"),console.log(""),console.log('Step 2 -Install: "Install App" -> "Install to Workspace" -> Authorize'),console.log(""),console.log("Step 3 -Copy your token:"),console.log(` OAuth & Permissions -> ${s}`),console.log("");let o=await Qt(e,"Paste your token: ");if(!o)console.error("No token provided."),process.exit(1);if(!o.startsWith(r))console.error(`Expected a ${r} token, got: ${o.slice(0,10)}...`),process.exit(1);await Fn(e,o)}async function Hb(e,t){let n=ca();if(n.length===0)console.error("No Slack session found in Chrome. Sign in to Slack in Chrome (app.slack.com) and retry."),process.exit(1);let s=e.profile.token.split("-")[1],r=n.find((o)=>o.sessions.some((i)=>i.teamId===s));if(!r&&t){if(r=n.find((o)=>o.email===t||o.profileDir===t||o.profileDir===`Profile ${t}`),!r)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((o)=>o.email??o.profileDir).join(", ")}`),process.exit(1)}if(!r)if(n.length===1)r=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((u,a)=>console.log(` ${a+1}) ${u.email??u.label} [${u.profileDir}]`));let o=Ye({input:process.stdin,output:process.stdout}),i=(await o.question(`Choice [1-${n.length}]: `)).trim();o.close();let l=parseInt(i,10)-1;if(isNaN(l)||l<0||l>=n.length)console.error("Invalid choice."),process.exit(1);r=n[l]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),n.forEach((o)=>console.error(` slack auth cookie -w ${e.name} --profile "${o.email??o.profileDir}"`)),process.exit(1);console.log(`Using Chrome profile: ${r.email??r.label} [${r.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await Wd(r.profileDir)}catch(o){console.error(`
|
|
226
|
+
Could not extract the cookie automatically: ${o instanceof Error?o.message:String(o)}`),console.error("Fallback (manual): Chrome > DevTools (F12) > Application > Cookies > https://app.slack.com > copy the `d` value,"),console.error("then set it via an env file: SLACK_COOKIE=xoxd-... (in .slack-term/.env.local)"),process.exit(1)}}async function Jd(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=As();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((i)=>i.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((i)=>i.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let o=t.find((i)=>i.current);if(o)n=o.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((a,c)=>console.log(` ${c+1}) ${a.name} (${a.profile.team})`));let i=Ye({input:process.stdin,output:process.stdout}),l=(await i.question("Choice: ")).trim();i.close();let u=parseInt(l,10)-1;if(isNaN(u)||u<0||u>=t.length)console.error("Invalid choice."),process.exit(1);n=t[u].name}}let s=t.find((o)=>o.name===n);if(s.profile.token.startsWith("xoxb-")){console.error(`
|
|
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 o=t.filter((i)=>i.profile.token.startsWith("xoxc-")||i.profile.token.startsWith("xoxp-"));if(o.length>0)console.error(` Target a user-token workspace instead: ${o.map((i)=>i.name).join(", ")}`),console.error(` slack auth chrome -w ${o[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let r;if(process.platform==="win32")r=await Hb(s,e.profile);else{if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let o=e.yes?void 0:Ye({input:process.stdin,output:process.stdout});try{if(!await
|
|
230
|
-
`))}function
|
|
229
|
+
`+"actions (tail @user, DMs, listing users) would still fail.");let o=t.filter((i)=>i.profile.token.startsWith("xoxc-")||i.profile.token.startsWith("xoxp-"));if(o.length>0)console.error(` Target a user-token workspace instead: ${o.map((i)=>i.name).join(", ")}`),console.error(` slack auth chrome -w ${o[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let r;if(process.platform==="win32")r=await Hb(s,e.profile);else{if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let o=e.yes?void 0:Ye({input:process.stdin,output:process.stdout});try{if(!await Ls(o,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{o?.close()}if(console.log("Scanning Chrome profiles for Slack session..."),process.platform==="darwin")console.log("macOS may show a dialog asking for your login password — click Allow.");let i,l;try{({candidates:i,totalProfiles:l}=vs())}catch(u){console.error(`Failed: ${u instanceof Error?u.message:String(u)}`),process.exit(1)}if(i.length===0)console.error(`No Slack session found in Chrome (scanned ${l} profile${l!==1?"s":""}). Possible reasons:`),console.error(" - You denied the keychain dialog (try running again and click Allow)"),console.error(" - Chrome is not installed or has no Slack session"),console.error(" - You're not logged in to Slack in Chrome"),process.exit(1);if(i.length===1&&l<=1)r=i[0].cookie,console.log(`Found session in Chrome profile: ${i[0].profileName}`);else{let u=i.length===1?`Found 1 Slack session across ${l} Chrome profiles:`:`Found ${i.length} Slack sessions across ${l} Chrome profiles:`;console.log(u),i.forEach((p,g)=>console.log(` ${g+1}) ${p.profileName} [${p.profileDir}]`)),console.log("");let a=Ye({input:process.stdin,output:process.stdout}),c=i.length===1?" [Enter=1]":"",d=(await a.question(`Choice [1-${i.length}]${c}: `)).trim();a.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);r=i[f].cookie}}zi(n,r),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function ma(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=ca();if(t.length===0)console.error("No Slack session found in Chrome."),console.error(" Open Slack in Chrome (https://app.slack.com) and sign in, then retry."),process.exit(1);let n;if(e.profile){let o=e.profile,i=t.find((l)=>l.email===o||l.profileDir===o||l.profileDir===`Profile ${o}`);if(!i)console.error(`Chrome profile "${o}" has no Slack session. Available:`),t.forEach((l)=>console.error(` - ${l.email??l.label} [${l.profileDir}] (${l.sessions.length} workspace${l.sessions.length!==1?"s":""})`)),process.exit(1);n=i}else if(t.length===1)n=t[0];else if(process.stdin.isTTY){console.log("Found Slack sessions in multiple Chrome profiles:"),t.forEach((u,a)=>console.log(` ${a+1}) ${u.email??u.label} [${u.profileDir}] (${u.sessions.length} workspace${u.sessions.length!==1?"s":""})`));let o=Ye({input:process.stdin,output:process.stdout}),i=(await o.question(`Choice [1-${t.length}]: `)).trim();o.close();let l=parseInt(i,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),t.forEach((o)=>console.error(` slack auth login chrome --profile "${o.email??o.profileDir}"`)),process.exit(1);let s=n.email??n.label??n.profileDir,r;if(process.platform==="darwin")try{let{candidates:o}=vs();r=o.find((i)=>i.profileDir===n.profileDir)?.cookie??o[0]?.cookie}catch{}if(r)hd(s,r,`chrome:${n.profileDir}`);for(let o of n.sessions){let i=o.teamName??o.teamId,l=es(i);Or(l,{token:o.token,team:i,teamId:o.teamId,url:o.url??"",user:"",identity:s}),console.log(`Added workspace "${l}": ${i} (identity: ${s})`)}if(console.log(""),r)console.log(`Captured xoxd cookie for ${s} — shared across its ${n.sessions.length} workspace(s).`),console.log("RTM WebSocket mode is now available: slack tail @you");else console.log("Note: no xoxd cookie captured (LocalStorage yields the token only; the cookie is"),console.log("encrypted at rest on this platform). Some features (RTM, drafts, search fallback) need it."),console.log(" Attach it from your live browser — e.g. a CDP read via rech — or paste it:"),console.log(` slack auth cookie --workspace ${es(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 ya(e={}){let t=As();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((c,d)=>console.log(` ${d+1}) ${c.name} (${c.profile.team})`));let l=Ye({input:process.stdin,output:process.stdout}),u=(await l.question("Choice: ")).trim();l.close();let a=parseInt(u,10)-1;if(isNaN(a)||a<0||a>=t.length)console.error("Invalid choice."),process.exit(1);n=t[a].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 Ls(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{s?.close()}console.log("Scanning Firefox profiles for Slack session...");let r=qr();if(r.length===0)console.error("No Slack session found in Firefox. Possible reasons:"),console.error(" - Firefox is not installed"),console.error(" - You are not logged in to Slack in Firefox"),process.exit(1);let o;if(r.length===1)o=r[0].cookie,console.log(`Found session in Firefox profile: ${r[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),r.forEach((a,c)=>console.log(` ${c+1}) ${a.profileName} [${a.profileDir}]`));let i=Ye({input:process.stdin,output:process.stdout}),l=(await i.question("Choice: ")).trim();i.close();let u=parseInt(l,10)-1;if(isNaN(u)||u<0||u>=r.length)console.error("Invalid choice."),process.exit(1);o=r[u].cookie}zi(n,o),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function Kd(e={}){if(e.token){await Fn(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let r of process.stdin)n.push(r);let s=Buffer.concat(n).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await Fn(null,s,e.name);return}let t=Ye({input:process.stdin,output:process.stdout});try{await Ud(t)}finally{t.close()}}async function qd(e={}){let t=Ye({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await zr(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 zr(t,n==="2"?"bot":"user")}finally{t.close()}}function Hd(e={}){let t=(r,o)=>{if(/[\r\n]/.test(o))throw Error(`Invalid newline in ${r}.`);return`${r}=${/^[A-Za-z0-9._=-]+$/.test(o)?o:JSON.stringify(o)}`},n=[t("SLACK_TOKEN",gd(e.workspace))],s=Zt(e.workspace);if(s)n.push(t("SLACK_COOKIE",s));if(!e.workspace){let r=Rr();if(r)n.push(t("SLACK_BOT_TOKEN",r))}console.log(n.join(`
|
|
230
|
+
`))}function zd(e){let t=As(),n=e.workspace?t.find((r)=>r.name===e.workspace):t.find((r)=>r.current)??(t.length===1?t[0]:void 0);if(!n)throw Error(e.workspace?`Workspace "${e.workspace}" not found. Run: slack auth ls`:"Select a workspace with slack auth use <name>, or pass --workspace <name>.");if(!n.profile.cookie)throw Error(`Workspace "${n.name}" has no session cookie. Run: slack auth chrome -w ${n.name} or slack auth firefox -w ${n.name}`);let s=jb(e.envfile);Hi(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 Ns(e={}){let t=As();if(t.length>0){console.log("Currently logged in:");for(let{name:s,profile:r,current:o}of t)console.log(` ${o?"*":" "} ${s} ${r.team} (${r.user||"unknown"})`);console.log(""),console.log("Adding another workspace:"),console.log("")}if([e.fromChrome,e.fromFirefox,e.fromAll].filter(Boolean).length>1)throw Error("Choose only one browser source: --from-chrome, --from-firefox, or --from-all.");if(e.fromChrome&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{if(!await Ls(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let r=await ua();if(r.length===0)throw Error("No Slack session token found in Chrome profiles.");await ga(r,s,!0)}finally{s?.close()}return}if(e.fromAll&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{try{await ha(s,e.yes??!1,"all",!0)}catch(r){if(!(r instanceof Error)||!r.message.startsWith("Slack desktop app LevelDB not found"))throw r;if(!await Ls(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let o=await ua();if(o.length===0)throw Error("No Slack session token found in Chrome profiles.");if(o.every((i)=>!i.cookie)){let i=qr();if(i.length===1)for(let l of o)l.cookie=i[0].cookie}await ga(o,s,!0)}}finally{s?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let s=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(s!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let r=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{await ha(r,e.yes??!1,s,!0)}finally{r?.close()}return}if(e.token){await Fn(null,e.token,e.name);return}if(!process.stdin.isTTY){let s=[];for await(let o of process.stdin)s.push(o);let r=Buffer.concat(s).toString("utf8").trim();if(!r)console.error("No token provided on stdin."),process.exit(1);await Fn(null,r,e.name);return}console.log("How would you like to authenticate with Slack?"),console.log(""),console.log(" 1) Slack desktop app - import session token"),console.log(" Reads the xoxc- token directly from the installed app."),console.log(" Token: all platforms | xoxd cookie: macOS, or Chrome/Firefox on Linux"),console.log(""),console.log(" 2) Chrome browser - import workspaces"),console.log(" Reads xoxc- tokens from Chrome, grouped by account."),console.log(" Token: all platforms | xoxd cookie: macOS only"),console.log(""),console.log(" 3) Connect existing Slack app [recommended if you have one]"),console.log(" Paste a token from an app you already created."),console.log(""),console.log(" 4) Create new Slack app - user token (xoxp-)"),console.log(" Guided setup with manifest. Full access including search."),console.log(""),console.log(" 5) Create new Slack app - bot token (xoxb-)"),console.log(" Bot is invited to channels. Search and news unavailable."),console.log("");let n=Ye({input:process.stdin,output:process.stdout});try{let s=await Qt(n,"Choice [1/2/3/4/5]: ");if(console.log(""),s==="1")await ha(n,e.yes??!1);else if(s==="2"){n.close(),await ma();return}else if(s==="3")await Ud(n);else if(s==="4")await zr(n,"user");else if(s==="5")await zr(n,"bot");else console.error(`Invalid choice: "${s}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function Yr(e,t,n,s){let r=t,o=[],i=r,l=0;while(!0){let u=i.indexOf("<@U",l);if(u===-1)break;let a=i.slice(u+2),c=a.search(/[>|]/),d=c===-1?a:a.slice(0,c);if(d.length>=9)o.push(d);l=u+1}for(let u of o){if(!n.has(u))n.set(u,await Qn(e,u,s));let a=n.get(u)??u;r=r.replaceAll(`<@${u}>`,`@${a}`),r=r.replace(new RegExp(`<@${u}\\|[^>]*>`,"g"),`@${a}`)}return r}function Gr(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let r=Number(n);if(!Number.isFinite(r))return s??"date";let o=new Date(r*1000);if(Number.isNaN(o.getTime()))return s??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=i[o.getUTCDay()]??"",a=l[o.getUTCMonth()]??"";return`${u}, ${a} ${String(o.getUTCDate()).padStart(2,"0")}, ${o.getUTCFullYear()}`})}function Gd(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function zb(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),r=s.getUTCFullYear(),o=String(s.getUTCMonth()+1).padStart(2,"0"),i=String(s.getUTCDate()).padStart(2,"0"),l=String(s.getUTCHours()).padStart(2,"0"),u=String(s.getUTCMinutes()).padStart(2,"0"),a=String(s.getUTCSeconds()).padStart(2,"0"),c=n.padEnd(6,"0").slice(0,6);return`${r}-${o}-${i}T${l}:${u}:${a}.${c}`}async function Yb(e,t,n){let s=typeof t.ts==="string"?t.ts:"0.000000",r=zb(s),o="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,p]=await Mr(e,d);n.set(f,p)}o=n.get(f)??d}else if(typeof t.username==="string")o=t.username;let i=typeof t.text==="string"?t.text:"",u=Gr(await Yr(e,i,n)).split(`
|
|
231
231
|
`),a=u[0]+(u.length>1?`
|
|
232
232
|
`+u.slice(1).map((d)=>` ${d}`).join(`
|
|
233
|
-
`):""),c=
|
|
234
|
-
`)}),a.addEventListener("close",()=>u()),a.addEventListener("error",()=>u()),a.addEventListener("message",(c)=>{(async()=>{try{let d;try{d=JSON.parse(String(c.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){a.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||o.has(g))return;let h=typeof d.subtype==="string"?d.subtype:"";if(h==="message_changed"||h==="message_deleted")return;if(r.thread){if((typeof d.thread_ts==="string"?d.thread_ts:g)!==r.thread&&g!==r.thread)return}if(r.watchThread&&
|
|
233
|
+
`):""),c=Gd(t)?"↳ ":"";return`${r} ${c}@${o}: ${a}`}async function Gb(e,t,n,s,r,o,i,l){if(l?.aborted)return;return new Promise((u)=>{let a=new e(n);l?.addEventListener("abort",()=>{a.close(),u()},{once:!0}),a.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
|
|
234
|
+
`)}),a.addEventListener("close",()=>u()),a.addEventListener("error",()=>u()),a.addEventListener("message",(c)=>{(async()=>{try{let d;try{d=JSON.parse(String(c.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){a.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||o.has(g))return;let h=typeof d.subtype==="string"?d.subtype:"";if(h==="message_changed"||h==="message_deleted")return;if(r.thread){if((typeof d.thread_ts==="string"?d.thread_ts:g)!==r.thread&&g!==r.thread)return}if(r.watchThread&&Gd(d)){if((typeof d.thread_ts==="string"?d.thread_ts:"")!==r.watchThread)return}if(r.me&&r.myUserId){if(!(typeof d.text==="string"?d.text:"").includes(`<@${r.myUserId}>`))return}if(o.add(g),o.size>1000){let y=o.values().next().value;if(y!==void 0)o.delete(y)}let m=await Yb(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
|
|
236
|
+
`)}})()})})}var Yd=3,Xb=2000,ba={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:Td,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function Xd(e,t,n,s,r,o,i){let l=ba.getWebSocket();if(!l)return;for(let u=0;u<Yd;u++){if(i?.aborted)return;try{let{wsUrl:a}=await ba.clientBoot(e,t);await Gb(l,e,a,n,s,r,o,i)}catch{}if(i?.aborted)return;if(u<Yd-1)await ba.sleep(Xb)}}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 wt={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:Xd};function vt(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function wa(e){return Array.isArray(e)?e:[]}function Vd(e){return Number(e)||0}function Zd(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function Vb(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),r=s.getUTCFullYear(),o=String(s.getUTCMonth()+1).padStart(2,"0"),i=String(s.getUTCDate()).padStart(2,"0"),l=String(s.getUTCHours()).padStart(2,"0"),u=String(s.getUTCMinutes()).padStart(2,"0"),a=String(s.getUTCSeconds()).padStart(2,"0"),c=n.padEnd(6,"0").slice(0,6);return`${r}-${o}-${i}T${l}:${u}:${a}.${c}`}async function Zb(e,t,n,s,r){let o=typeof t.ts==="string"?t.ts:"0.000000",i=Vb(o),l="?";if(typeof t.user==="string"){let g=t.user,h="@"+g;if(!n.has(h)){let[,m]=await Mr(e,g,r);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:"",c=Gr(await Yr(e,u,n,r)).split(`
|
|
237
237
|
`),d=c[0]+(c.length>1?`
|
|
238
238
|
`+c.slice(1).map((g)=>` ${g}`).join(`
|
|
239
|
-
`):""),f=
|
|
239
|
+
`):""),f=Zd(t)?"↳ ":"",p=s?`${s} @${l}`:`@${l}`;return`${i} ${f}${p}: ${d}`}async function Qb(e,t,n,s,r,o,i){let l=vt(await Tn(e,t,20,i?void 0:n||void 0,i,s.cookie)),u=wa(l.messages).map(vt).reverse(),a=vt(l.response_metadata),c=l.has_more===!0&&typeof a.next_cursor==="string"?a.next_cursor:void 0,d=[];if(s.watchThread&&!i){let m=vt(await _d(e,t,s.watchThread,50,s.cookie));d=wa(m.messages).map(vt).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)=>Vd(typeof m.m.ts==="string"?m.m.ts:"")-Vd(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||r.has(w))continue;let D=typeof m.subtype==="string"?m.subtype:"";if(D==="message_changed"||D==="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&&Zd(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(r.add(w),r.size>1000){let _=r.values().next().value;if(_!==void 0)r.delete(_)}if(p.push(await Zb(e,m,o,void 0,s.cookie)),y)g=w;let k=typeof m.user==="string"?m.user:"";if(!s.myUserId||k!==s.myUserId)h=!0}return{newCursor:g,lines:p,hasMore:l.has_more===!0,nextPageCursor:c,emittedOther:h}}function ew(e){if(e.includes("slack.com")){let t=ta(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 Qd(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 r=await
|
|
241
|
+
Use: slack tail "#channel" --me`),process.exit(1);if(!t)console.error("Usage: slack tail <#channel|@user>\n Run `slack tail --help` for details."),process.exit(1);let r=await Nr(e,t,n.cookie),o=n.interval??60000,i=n.timeout?wt.now()+en(n.timeout)*1000:1/0,l=new Map,u=new Set;try{let h=vt(await jr(e,r,n.cookie));if(vt(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 a="";if(n.since){let h=en(n.since);a=(wt.now()/1000-h).toFixed(6)}else{let h=vt(await Tn(e,r,1,void 0,void 0,n.cookie)),m=wa(h.messages).map(vt);if(m.length>0&&typeof m[0]?.ts==="string")a=m[0].ts,u.add(a);else a=(wt.now()/1000).toFixed(6)}let c;if(n.me||n.exitOnMessage)c=(await Zn(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=ew(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}:{},...c!==void 0?{myUserId:c}:{},...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 wt.tailRTM(e,n.cookie,r,f,u,l,s),s?.aborted)return;console.error("RTM unavailable — switching to polling.")}let p=!0,g=wt.now();while(!s?.aborted){if(wt.now()>=i)return;let h=!1;try{let w=wt.now()-g,D=o>0&&w>o*5,k,_=!0;do{let{newCursor:E,lines:S,nextPageCursor:x,emittedOther:R}=await Qb(e,r,a,f,u,l,k);if(a=E,p&&_&&n.since&&S.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
|
|
242
242
|
`);_=!1;for(let L of S)process.stdout.write(L+`
|
|
243
|
-
`);if(R)h=!0;D
|
|
243
|
+
`);if(R)h=!0;k=D?x:void 0}while(k);p=!1}catch(y){if(y instanceof qe){console.error(`Warning: Slack rate limit hit — backing off for ${y.retryAfter}s`),await wt.sleep(y.retryAfter*1000);continue}throw y}if(n.exitOnMessage&&h)return;g=wt.now();let m=i-wt.now();if(m<=0)return;await wt.sleep(Math.min(o,m))}}import{existsSync as tw,mkdirSync as sf,readFileSync as xa,renameSync as nw,unlinkSync as ef,writeFileSync as Sa}from"node:fs";import{dirname as rf}from"node:path";class ka extends Error{}function tf(e){let t=e,n=(Array.isArray(t.messages)?t.messages:[]).filter((r)=>!!r&&typeof r==="object"&&!Array.isArray(r)),s=t.has_more===!0?t.response_metadata?.next_cursor:void 0;return typeof s==="string"&&s?{messages:n,nextCursor:s}:{messages:n}}function of(e,t){return{async listChannels(n){let s;if(n){s=[];for(let r of n){let o=await jr(e,r,t),i=o.channel;if(i&&i.is_member!==!1)s.push(o.channel)}}else try{s=await ea(e,"public_channel,private_channel,im,mpim",t)}catch(r){if(!/missing_scope/.test(r instanceof Error?r.message:String(r)))throw r;s=[];let o=[];for(let i of["public_channel","private_channel","im","mpim"])try{s.push(...await ea(e,i,t))}catch(l){if(!/missing_scope/.test(l instanceof Error?l.message:String(l)))throw l;o.push(i)}he.err(`slack stream: no scope to list ${o.join(", ")} — watching the rest`)}return s.flatMap((r)=>{if(!r||typeof r!=="object"||Array.isArray(r)||typeof r.id!=="string")return[];let o=r.is_im===!0;return[{id:r.id,name:ae(r.name)||r.id,isIm:o,...r.is_mpim===!0?{isMpim:!0}:{},...o&&typeof r.user==="string"?{user:r.user}:{}}]})},history:async(n,s,r)=>tf(await Tn(e,n,200,s,r,t)),replies:async(n,s,r,o)=>tf(await Ed(e,n,s,{oldest:r,...o?{cursor:o}:{}},t)),userName:(n)=>Qn(e,n,t)}}var sw="https://github.com/snomiao/slack-term/blob/main/worker/README.md",rw=1.618,ow=25,Xr=2000,iw=8,he={now:()=>Date.now(),sleep:(e,t)=>new Promise((n)=>{if(t?.aborted)return n();let s=()=>{clearTimeout(r),n()},r=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})}),out:(e)=>{process.stdout.write(e+`
|
|
244
244
|
`)},err:(e)=>{process.stderr.write(e+`
|
|
245
|
-
`)},pidAlive:(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}};function
|
|
246
|
-
`)}function dw(e,t,n,s){let o=`${e.endsWith("/")?e:e+"/"}archives/${t}/p${n.replace(".","")}`;return s&&s!==n?`${o}?thread_ts=${s}&cid=${t}`:o}function fw(e,t){if(!tw(e))return{version:1,identity:t,channels:{}};let n;try{n=JSON.parse(xa(e,"utf8"))}catch(r){throw new tn(`state file ${e} is unreadable (${Ge(r)}); move it aside to start fresh`)}if(!(n&&typeof n==="object"&&n.version===1&&n.channels&&typeof n.channels==="object"&&Object.values(n.channels).every((r)=>r&&typeof r.since==="string"&&typeof r.cursor==="string"&&r.threads&&typeof r.threads==="object")))throw new 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 Pt(e,t){
|
|
245
|
+
`)},pidAlive:(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}};function ts(e,t,n){return Math.min(n,Math.round(t*Math.pow(rw,Math.max(0,e-1))))}var aw=["invalid_auth","not_authed","token_revoked","token_expired","account_inactive","no_permission"],cw=["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 Da(e){let t=Ge(e);if(aw.some((n)=>t.includes(n)))return"fatal";if(cw.some((n)=>t.includes(n)))return"channel";return"transient"}var ae=(e)=>typeof e==="string"?e:"",me=(e)=>Number(e)||0,kt=(e)=>e.toFixed(6),lw=new Set(["message_changed","message_deleted","channel_join","channel_leave","group_join","group_leave"]);function uw(e){let t=[ae(e.text)];if(Array.isArray(e.attachments)){for(let n of e.attachments)if(n&&typeof n==="object"&&!Array.isArray(n))t.push(ae(n.pretext),ae(n.text),ae(n.fallback))}return t.filter(Boolean).join(`
|
|
246
|
+
`)}function dw(e,t,n,s){let o=`${e.endsWith("/")?e:e+"/"}archives/${t}/p${n.replace(".","")}`;return s&&s!==n?`${o}?thread_ts=${s}&cid=${t}`:o}function fw(e,t){if(!tw(e))return{version:1,identity:t,channels:{}};let n;try{n=JSON.parse(xa(e,"utf8"))}catch(r){throw new tn(`state file ${e} is unreadable (${Ge(r)}); move it aside to start fresh`)}if(!(n&&typeof n==="object"&&n.version===1&&n.channels&&typeof n.channels==="object"&&Object.values(n.channels).every((r)=>r&&typeof r.since==="string"&&typeof r.cursor==="string"&&r.threads&&typeof r.threads==="object")))throw new 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 Pt(e,t){sf(rf(e),{recursive:!0});let n=`${e}.tmp-${process.pid}`;Sa(n,JSON.stringify(t)),nw(n,e)}function pw(e){let t=`${e}.lock`;sf(rf(t),{recursive:!0});let n=()=>{try{if(xa(t,"utf8").trim()===String(process.pid))ef(t)}catch{}};try{Sa(t,String(process.pid),{flag:"wx"})}catch{let s=Number(xa(t,"utf8").trim());if(s&&he.pidAlive(s))throw new tn(`another slack stream (pid ${s}) already uses ${e}`);ef(t),Sa(t,String(process.pid),{flag:"wx"})}return n}async function nf(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 _a(e,t,n,s,r){if(lw.has(ae(n.subtype)))return!1;let o=ae(n.user),i=ae(n.bot_id),l=e.opts.repliesTo,u=ae(n.thread_ts);if(s&&l&&u&&(l.has(o)||l.has(i))){let y=e.state.joined??={};y[`${t.id}:${u}`]=Math.max(y[`${t.id}:${u}`]??0,me(ae(n.ts)))}if(o&&e.opts.selfUsers.has(o)||i&&e.opts.selfBots.has(i))return!1;e.opts.grep.lastIndex=0;let a=e.opts.grep.test(uw(n))?"grep":s&&l&&await hw(e,t,l,n,r)?"replies-to":void 0;if(!a)return!1;let c=ae(n.ts),d=`${t.id}:${c}`;if(e.state.seen?.[d]!==void 0)return!1;if(e.opts.relay&&!e.opts.once)(e.state.seen??={})[d]=me(c);let f=ae(n.thread_ts)||null,p=o||i,g=o?await nf(e,o):ae(n.username)||ae(n.bot_profile?.name)||i,h=t.isIm?`@${t.user?await nf(e,t.user):t.id}`:t.isMpim?t.name:`#${t.name}`,m={type:s?"reply":"message",channel:{id:t.id,name:h},ts:c,thread_ts:f,user:{id:p,name:g},text:ae(n.text).replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"),permalink:dw(e.opts.teamUrl,t.id,c,f??void 0),match:a};return e.opts.json?he.out(JSON.stringify(m)):he.out(gw(m)),e.opts.onMatch?.(m,Array.isArray(n.files)?n.files.length:0),e.matches++,!0}async function hw(e,t,n,s,r){if(n.has(ae(s.parent_user_id)))return!0;let o=ae(s.thread_ts),i=af(e,t,n,o,r);if(i!==void 0)return i;let l=`${t.id}:${o}`,u=e.notJoined?.get(l);if(u!==void 0&&u>=me(ae(s.ts)))return!1;let a=u!==void 0?kt(u):"0";return Ea(e,t,n,o,await Vr((c)=>e.client.replies(t.id,o,a,c))),e.state.joined?.[l]!==void 0}function af(e,t,n,s,r){if(e.state.joined?.[`${t.id}:${s}`]!==void 0)return!0;if(!r)return;if(n.has(ae(r.user))||n.has(ae(r.bot_id)))return!0;let o=Array.isArray(r.reply_users)?r.reply_users.map((l)=>ae(l)):void 0;if(o?.some((l)=>n.has(l)))return!0;let i=typeof r.reply_users_count==="number"?r.reply_users_count:void 0;if(o&&(i!==void 0?i<=o.length:o.length<5))return!1;return}function Ea(e,t,n,s,r){let o=`${t.id}:${s}`,i=r.filter((u)=>n.has(ae(u.user))||n.has(ae(u.bot_id))).map((u)=>me(ae(u.ts)));if(i.length){let u=e.state.joined??={};u[o]=Math.max(u[o]??0,...i),e.notJoined?.delete(o);return}let l=Math.max(e.notJoined?.get(o)??0,...r.map((u)=>me(ae(u.ts))));(e.notJoined??=new Map).set(o,l)}function gw(e){let t=new Date(me(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 Xr(e){let t=[],n;do{let s=await e(n);t.push(...s.messages),n=s.nextCursor}while(n);return t}async function mw(e,t,n,s=!0){let r=e.state.channels[t.id],o=n-(e.opts.settleSec??5),i=n-e.opts.threadWindowSec,l=ge(r.cursor),u=s?Math.min(l,i):l,a=(await Xr((f)=>e.client.history(t.id,Dt(u),f))).sort((f,p)=>ge(ce(f.ts))-ge(ce(p.ts))),c=e.opts.repliesTo?new Map(a.map((f)=>[ce(f.ts),f])):void 0,d=a.at(-1);if(d&&ge(ce(d.ts))>ge(r.latest??"0"))r.latest=ce(d.ts);if(s)r.scanned=Dt(n);for(let f of a){let p=ge(ce(f.ts));if(p<=l||p>o)continue;let g=ce(f.thread_ts),h=await _a(e,t,f,g!==""&&g!==ce(f.ts),g?c?.get(g):void 0);if(r.cursor=ce(f.ts),h)Pt(e.opts.statePath,e.state)}if(ge(r.cursor)<o)r.cursor=Dt(o);for(let f of a){let p=ce(f.ts),g=ge(ce(f.latest_reply));if(!g||ce(f.thread_ts)!==p)continue;let h=ge(r.threads[p]??r.since);if(g<=h)continue;let m=e.opts.repliesTo,y=m!==void 0&&of(e,t,m,p,f)===void 0,w=y?Math.min(h,e.notJoined?.get(`${t.id}:${p}`)??0):h,k=(await Xr((D)=>e.client.replies(t.id,p,Dt(w),D))).sort((D,_)=>ge(ce(D.ts))-ge(ce(_.ts)));if(y)Ea(e,t,m,p,k);for(let D of k){let _=ge(ce(D.ts));if(ce(D.ts)===p||_<=h||_>o)continue;let C=ce(D.subtype)!=="thread_broadcast"&&await _a(e,t,D,!0,f);if(r.threads[p]=ce(D.ts),C)Pt(e.opts.statePath,e.state)}r.threads[p]=Dt(Math.max(ge(r.threads[p]??"0"),Math.min(g,o)))}for(let f of Object.keys(r.threads))if(ge(f)<i)delete r.threads[f];Pt(e.opts.statePath,e.state)}async function yw(e,t,n){let s,r,o,i=e.opts.repliesTo,l=`${t.id}:${n.thread_ts??""}`;if(i&&n.thread_ts&&e.state.joined?.[l]===void 0){let g=Math.min(e.notJoined?.get(l)??0,ge(n.ts)-1),h=await Xr((m)=>e.client.replies(t.id,n.thread_ts,Dt(g),m));if(s=h.find((m)=>ce(m.ts)===n.ts),r=h.find((m)=>ce(m.ts)===n.thread_ts),s)Ea(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,Dt(ge(n.ts)-1),o);if(s=h.messages.find((m)=>ce(m.ts)===n.ts),r??=n.thread_ts?h.messages.find((m)=>ce(m.ts)===n.thread_ts):void 0,o=h.nextCursor,!o)break}if(!s)return!1;let u=ce(s.thread_ts),a=e.state.channels[t.id],d=u!==""&&u!==n.ts&&ce(s.subtype)!=="thread_broadcast"?a?.threads[u]:a?.cursor;if(d!==void 0&&ge(n.ts)<=ge(d))return!0;let f=Object.keys(e.state.joined??{}).length;if(await _a(e,t,s,u!==""&&u!==n.ts,r)||Object.keys(e.state.joined??{}).length!==f)Pt(e.opts.statePath,e.state);return!0}var bw=2592000;function ww(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 Dw(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 kw=10;function xw(e,t,n){if(!(t>0))return e;let s=60000/t,r=-1/0,o=async()=>{let i=fe.now();r=Math.max(r,i);let l=r-i-(kw-1)*s;if(r+=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 o(),e.history(i,l,u)),replies:async(i,l,u,a)=>(await o(),e.replies(i,l,u,a))}}function Sw(e,t,n,s){let r=n-s.windowSec,o=(f)=>t.channels[f.id],i=(f)=>o(f)?.scanned!==void 0&&ge(o(f).latest??"0")<r,l=(f)=>s.once||o(f)?.scanned===void 0||n-ge(o(f).scanned)>=s.periodSec,u=new Map,a=e.filter((f)=>!i(f)),c=s.once||s.periodSec<=s.intervalSec?1/0:Math.max(1,Math.ceil(a.length*s.intervalSec/s.periodSec)),d=a.filter(l).sort((f,p)=>ge(o(f)?.scanned??"0")-ge(o(p)?.scanned??"0")).slice(0,c);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 af(e,t){let n=t.maxFailures??(t.once?3:12),s=t.backoffBaseMs??2000,r=t.backoffCapMs??300000,o=t.refreshEvery??10,i=t.once?void 0:t.relay;if(!i&&!t.once)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: ${sw}`);e=xw(e,t.callsPerMin??40,t.signal);let l,u=new AbortController,a=()=>u.abort();t.signal?.addEventListener("abort",a,{once:!0});try{l=pw(t.statePath);let c=fw(t.statePath,t.identity),d=t.repliesTo?[...t.repliesTo].sort().join(","):void 0;if(c.joinedBy!==d)delete c.joined;if(d)c.joinedBy=d;else delete c.joinedBy;let f={opts:t,client:e,state:c,names:new Map,matches:0},p=new Set,g=[],h=fe.now()/1000,m=h,y="",w=0,k=0,D=-1/0,_=0,C=(j)=>{fe.err(`slack stream: rate limited — waiting ${j.retryAfter}s`),_=Math.max(_,fe.now()+j.retryAfter*1000)},S=async(j)=>{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((oe)=>oe.id===de))throw new tn(`--channel ${de}: the identity is not a member of it`)}let q=Object.keys(c.channels).length===0;for(let de of g){if(c.channels[de.id])continue;let H=Math.min(q||k===0?j:m,t.sinceSec!==void 0?h-t.sinceSec:1/0);c.channels[de.id]={since:Dt(H),cursor:Dt(H),threads:{}}}m=j,Pt(t.statePath,c)};if(t.sinceSec!==void 0)c.channels={},delete c.seen,delete c.relay;let x={queue:[],retry:[],inflight:void 0,onDrain:void 0,handled:0,live:void 0,full:!1},R=new AbortController,L=()=>R.abort(),P=(j,re="")=>{if(x.live===j)return;x.live=j,fe.err(j?`slack stream: relay connected${re?` (${re})`:""} — polling every ${Math.round(Math.max(t.intervalMs,i.reconcileMs)/1000)}s as a safety net`:`slack stream: relay unavailable${re?` (${re})`:""} — polling every ${Math.round(t.intervalMs/1000)}s`),L()},v=async(j)=>{let re=t.sinceSec===void 0&&c.relay?.url===j.url?{seq:c.relay.seq,...c.relay.epoch?{epoch:c.relay.epoch}:{}}:{seq:0},q=0,de=()=>x.queue.length+x.retry.length+(x.inflight?1:0);while(!u.signal.aborted){while(de()>=Gr/2&&!u.signal.aborted)await new Promise((W)=>{let he=()=>W();x.onDrain=()=>{u.signal.removeEventListener("abort",he),W()},u.signal.addEventListener("abort",he,{once:!0})});if(u.signal.aborted)return;let oe=new AbortController,H=()=>oe.abort();u.signal.addEventListener("abort",H,{once:!0});let ie=!1,G="stream closed";try{await j.subscribe(re,oe.signal,{hello:(W)=>{if(q=0,W.gap)x.full=!0;if(W.gap||c.relay?.url!==j.url||c.relay.epoch!==W.epoch){c.relay={url:j.url,seq:W.seq,...W.epoch?{epoch:W.epoch}:{}},x.handled=Math.min(x.handled,W.seq);for(let he of[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]])he.seq=Math.min(he.seq,W.seq)}re={seq:W.seq,...W.epoch?{epoch:W.epoch}:{}},P(!0,W.via)},bell:(W,he)=>{if(ie)return;if(de()>=Gr){fe.err(`slack stream: relay backlog over ${Gr} — pausing the relay until it drains`),ie=!0,oe.abort(),P(!1,"paused while its backlog drains");return}re={...re,seq:W},x.queue.push({seq:W,bell:he,tries:0,dueMs:0}),L()}})}catch(W){if(W instanceof Da){if(x.live)P(!1,Ge(W));x.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",H)}if(u.signal.aborted)return;if(ie)continue;P(!1,G),q++,await fe.sleep(es(q,2000,60000),u.signal)}};if(i)v(i);let M=async(j)=>{if(t.channels&&!t.channels.includes(j.channel))return!0;if(j.kind==="reaction"){if(!t.reactions||j.self&&t.selfUsers.has(j.self))return!0;if(j.user&&t.selfUsers.has(j.user))return!0;let de={type:"reaction",channel:{id:j.channel},ts:j.ts,user:{id:j.user??""}};return fe.out(t.json?JSON.stringify(de):`reaction ${j.channel} ${j.ts} by ${j.user??"?"}`),!0}let re=g.find((de)=>de.id===j.channel);if(!re){if(fe.now()/1000-m<60)return!1;await S(fe.now()/1000),re=g.find((de)=>de.id===j.channel)}let q=re&&c.channels[re.id];if(!re||!q||p.has(re.id))return!0;if(ge(j.ts)<ge(q.since))return!0;if(j.self&&t.selfUsers.has(j.self)){if(t.repliesTo?.has(j.self)&&j.thread_ts){let de=c.joined??={},oe=`${re.id}:${j.thread_ts}`;de[oe]=Math.max(de[oe]??0,ge(j.ts)),f.notJoined?.delete(oe),Pt(t.statePath,c)}return!0}return yw(f,re,j)},U=()=>{if(!c.relay||c.relay.url!==i?.url)return;let j=[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]].map((re)=>re.seq);c.relay.seq=Math.max(0,j.length?Math.min(...j)-1:Math.max(c.relay.seq,x.handled))},N=async()=>{let j=fe.now(),re=x.retry.filter((oe)=>oe.dueMs<=j);if(re.length)x.retry=x.retry.filter((oe)=>oe.dueMs>j),x.queue=[...re,...x.queue].sort((oe,H)=>oe.seq-H.seq);let q=0;while(x.queue.length&&q<ow&&!t.signal?.aborted&&fe.now()>=_){let oe=x.queue.shift();x.inflight=oe,q++;let H,ie;try{H=await M(oe.bell)}catch(G){if(G instanceof qe){C(G),oe.dueMs=_,x.retry.push(oe),x.inflight=void 0;break}H=!1,ie=G}if(x.inflight=void 0,ie!==void 0&&/thread_not_found|message_not_found/.test(Ge(ie)))ie=void 0;if(ie!==void 0&&ka(ie)==="channel")fe.err(`slack stream: relay bell for ${oe.bell.channel} dropped: ${Ge(ie)}`),H=!0;if(ie===void 0&&Q)fe.err("slack stream: relay bell reads recovered"),Q=!1;if(H)x.handled=Math.max(x.handled,oe.seq);else if(ie!==void 0){if(oe.fails=(oe.fails??0)+1,!Q)fe.err(`slack stream: relay bell for ${oe.bell.channel} failed (${Ge(ie)}) — retrying`);Q=!0,oe.dueMs=fe.now()+es(oe.fails,1500,60000),x.retry.push(oe)}else if(++oe.tries>=iw)fe.err(`slack stream: relay bell for ${oe.bell.channel} abandoned after ${oe.tries} tries (not visible) — only the poll can find it now`),x.handled=Math.max(x.handled,oe.seq);else oe.dueMs=fe.now()+es(oe.tries,1500,60000),x.retry.push(oe)}if(x.onDrain&&x.queue.length+x.retry.length<Gr/2)x.onDrain(),x.onDrain=void 0;let de=c.relay?.seq;if(U(),q||c.relay?.seq!==de)Pt(t.statePath,c)},K=()=>x.live===!0&&i?Math.max(t.intervalMs,i.reconcileMs):t.intervalMs,z=()=>{let j=fe.now();return(j>=D+K()||x.full)&&j>=_},O=()=>x.queue.length>0||x.retry.some((j)=>j.dueMs<=fe.now()),te=!1,Q=!1;while(!t.signal?.aborted){if(z()&&!(te&&O())){x.full=!1;let q=fe.now()/1000;try{if(k%o===0)await S(q);let de=Math.max(0,t.threadScanSec??180),oe=Sw(g.filter((H)=>!p.has(H.id)),c,q,{windowSec:t.threadWindowSec,periodSec:de,intervalSec:K()/1000,once:t.once});for(let H of g){if(t.signal?.aborted)break;if(p.has(H.id))continue;let ie=oe.get(H.id)??"full";if(ie==="skip")continue;for(;;)try{let G=c.channels[H.id],W=ie==="cursor"&&G.scanned!==void 0&&ge(G.latest??"0")<q-t.threadWindowSec&&q-ge(G.scanned)>=de;if(await mw(f,H,q,ie==="full"),W)G.scanned=Dt(q),Pt(t.statePath,c);break}catch(G){if(G instanceof qe){if(C(G),await fe.sleep(_-fe.now(),t.signal),t.signal?.aborted)break;continue}if(ka(G)==="channel"){p.add(H.id),y=Ge(G),fe.err(`slack stream: skipping ${H.isIm?H.id:"#"+H.name} (${H.id}): ${Ge(G)}`);break}throw G}}if(g.length>0&&g.every((H)=>p.has(H.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||ka(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 oe=es(w,s,r);fe.err(`slack stream: ${Ge(de)} — reconnecting in ${(oe/1000).toFixed(1)}s (attempt ${w}/${n})`),await fe.sleep(oe,t.signal),x.full=!0;continue}if(k++,Dw(c,q-t.threadWindowSec-86400),ww(c,q-bw),t.once){if(Pt(t.statePath,c),f.matches===0)fe.err(`slack stream: no matches in ${g.length-p.size} channel(s)`);return f.matches>0?0:2}D=q*1000,te=!0}if(t.signal?.aborted)break;let j=fe.now(),re=Math.max(_,x.queue.length||x.full?j:Math.min(D+K(),...x.retry.map((q)=>q.dueMs)));if(re>j){R=new AbortController;let q=R,de=()=>q.abort();t.signal?.addEventListener("abort",de,{once:!0}),await fe.sleep(re-j,q.signal),t.signal?.removeEventListener("abort",de)}if(z()&&!(te&&O()))continue;await N(),te=!1}return 0}catch(c){return fe.err(`slack stream: fatal: ${Ge(c)}`),3}finally{u.abort(),t.signal?.removeEventListener("abort",a),l?.()}}class cf extends Error{}function _w(e,t){let n;while((n=e.indexOf(`
|
|
249
|
+
${e.permalink}`}async function Vr(e){let t=[],n;do{let s=await e(n);t.push(...s.messages),n=s.nextCursor}while(n);return t}async function mw(e,t,n,s=!0){let r=e.state.channels[t.id],o=n-(e.opts.settleSec??5),i=n-e.opts.threadWindowSec,l=me(r.cursor),u=s?Math.min(l,i):l,a=(await Vr((f)=>e.client.history(t.id,kt(u),f))).sort((f,p)=>me(ae(f.ts))-me(ae(p.ts))),c=e.opts.repliesTo?new Map(a.map((f)=>[ae(f.ts),f])):void 0,d=a.at(-1);if(d&&me(ae(d.ts))>me(r.latest??"0"))r.latest=ae(d.ts);if(s)r.scanned=kt(n);for(let f of a){let p=me(ae(f.ts));if(p<=l||p>o)continue;let g=ae(f.thread_ts),h=await _a(e,t,f,g!==""&&g!==ae(f.ts),g?c?.get(g):void 0);if(r.cursor=ae(f.ts),h)Pt(e.opts.statePath,e.state)}if(me(r.cursor)<o)r.cursor=kt(o);for(let f of a){let p=ae(f.ts),g=me(ae(f.latest_reply));if(!g||ae(f.thread_ts)!==p)continue;let h=me(r.threads[p]??r.since);if(g<=h)continue;let m=e.opts.repliesTo,y=m!==void 0&&af(e,t,m,p,f)===void 0,w=y?Math.min(h,e.notJoined?.get(`${t.id}:${p}`)??0):h,D=(await Vr((k)=>e.client.replies(t.id,p,kt(w),k))).sort((k,_)=>me(ae(k.ts))-me(ae(_.ts)));if(y)Ea(e,t,m,p,D);for(let k of D){let _=me(ae(k.ts));if(ae(k.ts)===p||_<=h||_>o)continue;let E=ae(k.subtype)!=="thread_broadcast"&&await _a(e,t,k,!0,f);if(r.threads[p]=ae(k.ts),E)Pt(e.opts.statePath,e.state)}r.threads[p]=kt(Math.max(me(r.threads[p]??"0"),Math.min(g,o)))}for(let f of Object.keys(r.threads))if(me(f)<i)delete r.threads[f];Pt(e.opts.statePath,e.state)}async function yw(e,t,n){let s,r,o,i=e.opts.repliesTo,l=`${t.id}:${n.thread_ts??""}`;if(i&&n.thread_ts&&e.state.joined?.[l]===void 0){let g=Math.min(e.notJoined?.get(l)??0,me(n.ts)-1),h=await Vr((m)=>e.client.replies(t.id,n.thread_ts,kt(g),m));if(s=h.find((m)=>ae(m.ts)===n.ts),r=h.find((m)=>ae(m.ts)===n.thread_ts),s)Ea(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,kt(me(n.ts)-1),o);if(s=h.messages.find((m)=>ae(m.ts)===n.ts),r??=n.thread_ts?h.messages.find((m)=>ae(m.ts)===n.thread_ts):void 0,o=h.nextCursor,!o)break}if(!s)return!1;let u=ae(s.thread_ts),a=e.state.channels[t.id],d=u!==""&&u!==n.ts&&ae(s.subtype)!=="thread_broadcast"?a?.threads[u]:a?.cursor;if(d!==void 0&&me(n.ts)<=me(d))return!0;let f=Object.keys(e.state.joined??{}).length;if(await _a(e,t,s,u!==""&&u!==n.ts,r)||Object.keys(e.state.joined??{}).length!==f)Pt(e.opts.statePath,e.state);return!0}var bw=2592000;function ww(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 kw(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 Dw=10;function xw(e,t,n){if(!(t>0))return e;let s=60000/t,r=-1/0,o=async()=>{let i=he.now();r=Math.max(r,i);let l=r-i-(Dw-1)*s;if(r+=s,l>0)await he.sleep(l,n)};return{listChannels:(i)=>e.listChannels(i),userName:(i)=>e.userName(i),history:async(i,l,u)=>(await o(),e.history(i,l,u)),replies:async(i,l,u,a)=>(await o(),e.replies(i,l,u,a))}}function Sw(e,t,n,s){let r=n-s.windowSec,o=(f)=>t.channels[f.id],i=(f)=>o(f)?.scanned!==void 0&&me(o(f).latest??"0")<r,l=(f)=>s.once||o(f)?.scanned===void 0||n-me(o(f).scanned)>=s.periodSec,u=new Map,a=e.filter((f)=>!i(f)),c=s.once||s.periodSec<=s.intervalSec?1/0:Math.max(1,Math.ceil(a.length*s.intervalSec/s.periodSec)),d=a.filter(l).sort((f,p)=>me(o(f)?.scanned??"0")-me(o(p)?.scanned??"0")).slice(0,c);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 cf(e,t){let n=t.maxFailures??(t.once?3:12),s=t.backoffBaseMs??2000,r=t.backoffCapMs??300000,o=t.refreshEvery??10,i=t.once?void 0:t.relay;if(!i&&!t.once)he.err(`slack stream: WARNING: polling mode (${t.pollReason??"no relay configured"}) — this is the fallback, `+`not the intended setup: matches arrive up to ${Math.round(t.intervalMs/1000)}s late (replies under older parents up to ${Math.round(Math.max(t.threadScanSec??180,t.intervalMs/1000))}s) and every cycle spends Slack API calls. For real time, set up the relay (slack relay init) and set SLACK_RELAY_URL + SLACK_RELAY_TOKEN: ${sw}`);e=xw(e,t.callsPerMin??40,t.signal);let l,u=new AbortController,a=()=>u.abort();t.signal?.addEventListener("abort",a,{once:!0});try{l=pw(t.statePath);let c=fw(t.statePath,t.identity),d=t.repliesTo?[...t.repliesTo].sort().join(","):void 0;if(c.joinedBy!==d)delete c.joined;if(d)c.joinedBy=d;else delete c.joinedBy;let f={opts:t,client:e,state:c,names:new Map,matches:0},p=new Set,g=[],h=he.now()/1000,m=h,y="",w=0,D=0,k=-1/0,_=0,E=(j)=>{he.err(`slack stream: rate limited — waiting ${j.retryAfter}s`),_=Math.max(_,he.now()+j.retryAfter*1000)},S=async(j)=>{if(g=(await e.listChannels(t.channels)).filter((ue)=>!t.channels||t.channels.includes(ue.id)),t.channels){for(let ue of t.channels)if(!g.some((le)=>le.id===ue))throw new tn(`--channel ${ue}: the identity is not a member of it`)}let K=Object.keys(c.channels).length===0;for(let ue of g){if(c.channels[ue.id])continue;let q=Math.min(K||D===0?j:m,t.sinceSec!==void 0?h-t.sinceSec:1/0);c.channels[ue.id]={since:kt(q),cursor:kt(q),threads:{}}}m=j,Pt(t.statePath,c)};if(t.sinceSec!==void 0)c.channels={},delete c.seen,delete c.relay;let x={queue:[],retry:[],inflight:void 0,onDrain:void 0,handled:0,live:void 0,full:!1},R=new AbortController,L=()=>R.abort(),v=(j,ce="")=>{if(x.live===j)return;x.live=j,he.err(j?`slack stream: relay connected${ce?` (${ce})`:""} — polling every ${Math.round(Math.max(t.intervalMs,i.reconcileMs)/1000)}s as a safety net`:`slack stream: relay unavailable${ce?` (${ce})`:""} — polling every ${Math.round(t.intervalMs/1000)}s`),L()},P=async(j)=>{let ce=t.sinceSec===void 0&&c.relay?.url===j.url?{seq:c.relay.seq,...c.relay.epoch?{epoch:c.relay.epoch}:{}}:{seq:0},K=0,ue=()=>x.queue.length+x.retry.length+(x.inflight?1:0);while(!u.signal.aborted){while(ue()>=Xr/2&&!u.signal.aborted)await new Promise((Y)=>{let te=()=>Y();x.onDrain=()=>{u.signal.removeEventListener("abort",te),Y()},u.signal.addEventListener("abort",te,{once:!0})});if(u.signal.aborted)return;let le=new AbortController,q=()=>le.abort();u.signal.addEventListener("abort",q,{once:!0});let re=!1,pe="stream closed";try{await j.subscribe(ce,le.signal,{hello:(Y)=>{if(K=0,Y.gap)x.full=!0;if(Y.gap||c.relay?.url!==j.url||c.relay.epoch!==Y.epoch){c.relay={url:j.url,seq:Y.seq,...Y.epoch?{epoch:Y.epoch}:{}},x.handled=Math.min(x.handled,Y.seq);for(let te of[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]])te.seq=Math.min(te.seq,Y.seq)}ce={seq:Y.seq,...Y.epoch?{epoch:Y.epoch}:{}},v(!0,Y.via)},bell:(Y,te)=>{if(re)return;if(ue()>=Xr){he.err(`slack stream: relay backlog over ${Xr} — pausing the relay until it drains`),re=!0,le.abort(),v(!1,"paused while its backlog drains");return}ce={...ce,seq:Y},x.queue.push({seq:Y,bell:te,tries:0,dueMs:0}),L()}})}catch(Y){if(Y instanceof ka){if(x.live)v(!1,Ge(Y));x.live=!1,he.err(`slack stream: relay disabled for this run: ${Ge(Y)} — check SLACK_RELAY_TOKEN`);return}pe=Ge(Y)}finally{u.signal.removeEventListener("abort",q)}if(u.signal.aborted)return;if(re)continue;v(!1,pe),K++,await he.sleep(ts(K,2000,60000),u.signal)}};if(i)P(i);let B=async(j)=>{if(t.channels&&!t.channels.includes(j.channel))return!0;if(j.kind==="reaction"){if(!t.reactions||j.self&&t.selfUsers.has(j.self))return!0;if(j.user&&t.selfUsers.has(j.user))return!0;let ue={type:"reaction",channel:{id:j.channel},ts:j.ts,user:{id:j.user??""}};return he.out(t.json?JSON.stringify(ue):`reaction ${j.channel} ${j.ts} by ${j.user??"?"}`),!0}let ce=g.find((ue)=>ue.id===j.channel);if(!ce){if(he.now()/1000-m<60)return!1;await S(he.now()/1000),ce=g.find((ue)=>ue.id===j.channel)}let K=ce&&c.channels[ce.id];if(!ce||!K||p.has(ce.id))return!0;if(me(j.ts)<me(K.since))return!0;if(j.self&&t.selfUsers.has(j.self)){if(t.repliesTo?.has(j.self)&&j.thread_ts){let ue=c.joined??={},le=`${ce.id}:${j.thread_ts}`;ue[le]=Math.max(ue[le]??0,me(j.ts)),f.notJoined?.delete(le),Pt(t.statePath,c)}return!0}return yw(f,ce,j)},W=()=>{if(!c.relay||c.relay.url!==i?.url)return;let j=[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]].map((ce)=>ce.seq);c.relay.seq=Math.max(0,j.length?Math.min(...j)-1:Math.max(c.relay.seq,x.handled))},N=async()=>{let j=he.now(),ce=x.retry.filter((le)=>le.dueMs<=j);if(ce.length)x.retry=x.retry.filter((le)=>le.dueMs>j),x.queue=[...ce,...x.queue].sort((le,q)=>le.seq-q.seq);let K=0;while(x.queue.length&&K<ow&&!t.signal?.aborted&&he.now()>=_){let le=x.queue.shift();x.inflight=le,K++;let q,re;try{q=await B(le.bell)}catch(pe){if(pe instanceof qe){E(pe),le.dueMs=_,x.retry.push(le),x.inflight=void 0;break}q=!1,re=pe}if(x.inflight=void 0,re!==void 0&&/thread_not_found|message_not_found/.test(Ge(re)))re=void 0;if(re!==void 0&&Da(re)==="channel")he.err(`slack stream: relay bell for ${le.bell.channel} dropped: ${Ge(re)}`),q=!0;if(re===void 0&&X)he.err("slack stream: relay bell reads recovered"),X=!1;if(q)x.handled=Math.max(x.handled,le.seq);else if(re!==void 0){if(le.fails=(le.fails??0)+1,!X)he.err(`slack stream: relay bell for ${le.bell.channel} failed (${Ge(re)}) — retrying`);X=!0,le.dueMs=he.now()+ts(le.fails,1500,60000),x.retry.push(le)}else if(++le.tries>=iw)he.err(`slack stream: relay bell for ${le.bell.channel} abandoned after ${le.tries} tries (not visible) — only the poll can find it now`),x.handled=Math.max(x.handled,le.seq);else le.dueMs=he.now()+ts(le.tries,1500,60000),x.retry.push(le)}if(x.onDrain&&x.queue.length+x.retry.length<Xr/2)x.onDrain(),x.onDrain=void 0;let ue=c.relay?.seq;if(W(),K||c.relay?.seq!==ue)Pt(t.statePath,c)},J=()=>x.live===!0&&i?Math.max(t.intervalMs,i.reconcileMs):t.intervalMs,H=()=>{let j=he.now();return(j>=k+J()||x.full)&&j>=_},O=()=>x.queue.length>0||x.retry.some((j)=>j.dueMs<=he.now()),ee=!1,X=!1;while(!t.signal?.aborted){if(H()&&!(ee&&O())){x.full=!1;let K=he.now()/1000;try{if(D%o===0)await S(K);let ue=Math.max(0,t.threadScanSec??180),le=Sw(g.filter((q)=>!p.has(q.id)),c,K,{windowSec:t.threadWindowSec,periodSec:ue,intervalSec:J()/1000,once:t.once});for(let q of g){if(t.signal?.aborted)break;if(p.has(q.id))continue;let re=le.get(q.id)??"full";if(re==="skip")continue;for(;;)try{let pe=c.channels[q.id],Y=re==="cursor"&&pe.scanned!==void 0&&me(pe.latest??"0")<K-t.threadWindowSec&&K-me(pe.scanned)>=ue;if(await mw(f,q,K,re==="full"),Y)pe.scanned=kt(K),Pt(t.statePath,c);break}catch(pe){if(pe instanceof qe){if(E(pe),await he.sleep(_-he.now(),t.signal),t.signal?.aborted)break;continue}if(Da(pe)==="channel"){p.add(q.id),y=Ge(pe),he.err(`slack stream: skipping ${q.isIm?q.id:"#"+q.name} (${q.id}): ${Ge(pe)}`);break}throw pe}}if(g.length>0&&g.every((q)=>p.has(q.id)))throw new tn(`every channel failed — nothing left to watch (last: ${y})`);if(w>0)he.err(`slack stream: recovered after ${w} failed attempt(s)`);w=0}catch(ue){if(ue instanceof tn||Da(ue)==="fatal")return he.err(`slack stream: fatal: ${Ge(ue)}`),3;if(w++,w>=n)return he.err(`slack stream: giving up after ${w} consecutive failures: ${Ge(ue)}`),3;let le=ts(w,s,r);he.err(`slack stream: ${Ge(ue)} — reconnecting in ${(le/1000).toFixed(1)}s (attempt ${w}/${n})`),await he.sleep(le,t.signal),x.full=!0;continue}if(D++,kw(c,K-t.threadWindowSec-86400),ww(c,K-bw),t.once){if(Pt(t.statePath,c),f.matches===0)he.err(`slack stream: no matches in ${g.length-p.size} channel(s)`);return f.matches>0?0:2}k=K*1000,ee=!0}if(t.signal?.aborted)break;let j=he.now(),ce=Math.max(_,x.queue.length||x.full?j:Math.min(k+J(),...x.retry.map((K)=>K.dueMs)));if(ce>j){R=new AbortController;let K=R,ue=()=>K.abort();t.signal?.addEventListener("abort",ue,{once:!0}),await he.sleep(ce-j,K.signal),t.signal?.removeEventListener("abort",ue)}if(H()&&!(ee&&O()))continue;await N(),ee=!1}return 0}catch(c){return he.err(`slack stream: fatal: ${Ge(c)}`),3}finally{u.abort(),t.signal?.removeEventListener("abort",a),l?.()}}class lf extends Error{}function _w(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 r="message",o,i=[];for(let l of s.split(`
|
|
252
252
|
`)){if(!l||l.startsWith(":"))continue;let u=l.indexOf(":"),a=u<0?l:l.slice(0,u),c=u<0?"":l.slice(u+1).replace(/^ /,"");if(a==="event")r=c;else if(a==="data")i.push(c);else if(a==="id")o=c}if(i.length)t(r,i.join(`
|
|
253
|
-
`),o)}return e}var Ew="slack-term-relay.v1";function $w(e){return`bearer.${Buffer.from(e,"utf8").toString("base64url")}`}function $a(e){return e==="websocket"||e==="sse"?e:"auto"}var Cw=32;function
|
|
254
|
-
`),(y,w,
|
|
253
|
+
`),o)}return e}var Ew="slack-term-relay.v1";function $w(e){return`bearer.${Buffer.from(e,"utf8").toString("base64url")}`}function $a(e){return e==="websocket"||e==="sse"?e:"auto"}var Cw=32;function uf(e){return e===void 0?"":`?after=${e.seq}${e.epoch?`&epoch=${encodeURIComponent(e.epoch)}`:""}`}function Ca(e,t,n=70000,s={}){let r=e.replace(/\/+$/,""),o=s.transport??"auto",i=Tw(r,t,n);return async(l,u,a)=>{let c=s.WebSocket===void 0?globalThis.WebSocket:s.WebSocket;if(o!=="sse")if(!c){if(o==="websocket")throw Error("relay: this runtime has no WebSocket")}else{if(await Aw(c,r,t,n,s.pingMs??25000,s.ackDelayMs??100,l,u,a)||u.aborted)return;if(o==="websocket")throw Error("relay: WebSocket connection failed")}return i(l,u,a)}}function Aw(e,t,n,s,r,o,i,l,u){return new Promise((a,c)=>{if(l.aborted)return a(!0);let d;try{d=new e(`${t.replace(/^http/i,"ws")}/ws${uf(i)}`,[Ew,$w(n)])}catch{return a(!1)}let f=!1,p=!1,g,h,m,y=0,w=0,D=(S)=>{if(p)return;p=!0,clearTimeout(g),clearTimeout(h),clearInterval(m),l.removeEventListener("abort",k),d.onopen=d.onmessage=d.onerror=d.onclose=null;try{d.close(1000)}catch{}if(S)c(S);else a(f||l.aborted)},k=()=>D();l.addEventListener("abort",k,{once:!0});let _=()=>{clearTimeout(g),g=setTimeout(()=>D(f?Error(`relay: no data for ${Math.round(s/1000)}s`):void 0),s)},E=()=>{if(clearTimeout(h),h=void 0,y<=w)return;w=y;try{d.send(JSON.stringify({type:"ack",seq:y}))}catch{}};_(),d.onopen=()=>{f=!0,_(),m=setInterval(()=>{try{d.send("ping")}catch{}},r)},d.onmessage=(S)=>{if(_(),typeof S.data!=="string"||S.data==="pong")return;let x;try{x=JSON.parse(S.data)}catch(R){return D(R)}if(x.type==="hello"){let{type:R,...L}=x;y=w=L.seq,u.hello({...L,via:"websocket"})}else if(x.type==="bell"&&typeof x.seq==="number"){if(u.bell(x.seq,x.bell),p)return;if(y=Math.max(y,x.seq),y-w>=Cw)E();else h??=setTimeout(E,o)}},d.onerror=()=>{},d.onclose=(S)=>{if(!f||S.code===1000)return D();D(Error(`relay: WebSocket closed (${S.code}${S.reason?` ${S.reason}`:""})`))}})}function Tw(e,t,n){return async(s,r,o)=>{let i=new AbortController,l=()=>i.abort();r.addEventListener("abort",l,{once:!0});let u,a=!1,c=()=>{clearTimeout(u),u=setTimeout(()=>{a=!0,i.abort()},n)};try{c();let d=await fetch(`${e}/stream${uf(s)}`,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:i.signal});if(d.status===401)throw new lf("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;c(),g=_w((g+p.decode(m,{stream:!0})).replace(/\r\n/g,`
|
|
254
|
+
`),(y,w,D)=>{let k=JSON.parse(w);if(y==="hello")o.hello({...k,via:"sse"});else if(y==="bell"&&D!==void 0)o.bell(Number(D),k)})}}catch(d){if(r.aborted)return;if(a)throw Error(`relay: no data for ${Math.round(n/1000)}s`);throw d}finally{clearTimeout(u),r.removeEventListener("abort",l)}}}import{spawnSync as mf}from"node:child_process";import{closeSync as Fw,mkdirSync as Ow,openSync as Rw,readFileSync as yf,unlinkSync as df,writeFileSync as Iw}from"node:fs";import{homedir as ff,tmpdir as vw}from"node:os";import{dirname as Pw,resolve as Zr}from"node:path";function Aa(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}var pf=1000;function hf(e,t){let n=e.split(/\s+/).filter(Boolean).join(" ");if(t<=1)return"";return n.length<=t?n:`${n.slice(0,t-1)}…`}var Lw=3600000;function gf(e){return`${new Date(e).toISOString().slice(0,16).replace("T"," ")} UTC`}function bf(e,t,n=Date.now()){if(n-(t??e)<Lw)return"[ask-answer]";return t!==void 0?`[ask-answer, late: answered ${gf(t)}]`:`[ask-answer, late: asked ${gf(e)}, pressed since]`}function wf(e){let t=`${e.tag??"[ask-answer]"} ${e.link} →`,n=hf(e.answer,300),s=e.how?` (${e.how})`:"";if(e.freeText)s+=" — a free-text reply, not a choice: the question stays open";else if(e.collected)s+=" — collected ✅";if(e.goneAsker)s+=` — asked by pid ${e.goneAsker}, now gone: sent to this lane by its directory`;let r=hf(e.question,pf-t.length-n.length-s.length-8);return`${t} ${n}${s}. Q: ${r}`.slice(0,pf)}var kf=(e,t)=>mf(e,t,{encoding:"utf8",timeout:60000});function Nw(e){try{let t=yf(`/proc/${e}/stat`,"utf8");return Number(t.slice(t.lastIndexOf(")")+2).split(" ")[1])||0}catch{let t=mf("ps",["-o","ppid=","-p",String(e)],{encoding:"utf8",timeout:2000});return Number((t.stdout??"").trim())||0}}function Df(e,t,n=kf,s=Nw){for(let r=0;r<4&&e>1;r++,e=s(e)){let o=n(process.env.SLACK_TERM_AY||"ay",["send",String(e),"--force",t]);if(o.error)return;let i=`${o.stdout??""}${o.stderr??""}`;if(/no agent matched/i.test(i))continue;if(o.status===0||/QUEUED|sent to pid|NOT SUBMITTED/.test(i))return e}return}function xf(e=kf){let t=e(process.env.SLACK_TERM_AY||"ay",["ls","--json"]);try{let n=JSON.parse(t.stdout??"");return Array.isArray(n)?n.flatMap((s)=>typeof s.pid==="number"&&typeof s.cwd==="string"?[{pid:s.pid,cwd:s.cwd,...typeof s.started_at==="number"?{started_at:s.started_at}:{}}]:[]):[]}catch{return[]}}function Sf(e,t,n=Aa){let s=Zr(e),r=Zr(vw());if(s===Zr(ff())||s===r||s.startsWith(`${r}/`))return;return t.filter((i)=>Zr(i.cwd.replace(/^~(?=\/|$)/,ff()))===s&&n(i.pid)).sort((i,l)=>(l.started_at??0)-(i.started_at??0))[0]?.pid}function _f(e){Ow(Pw(e),{recursive:!0});for(let t=0;t<2;t++)try{let n=Rw(e,"wx");return Iw(n,String(process.pid)),Fw(n),()=>{try{df(e)}catch{}}}catch{let n=0;try{n=Number(yf(e,"utf8").trim())}catch{}if(n&&n!==process.pid&&Aa(n))return;try{df(e)}catch{}}return}import{existsSync as Bw,mkdirSync as jw,writeFileSync as Ww}from"node:fs";import{basename as Uw,join as Ta,resolve as $f}from"node:path";import{randomBytes as Jw}from"node:crypto";var Ef={name:"slack-term",version:"1.55.3",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 Kw="4.105.0",qw="2026-07-01",Fa="slack-term-relay",Hw="https://github.com/snomiao/slack-term/blob/main/worker/README.md";function zw(e){return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(e)}function Yw(e){return Uw($f(e)).toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63).replace(/-+$/,"")||Fa}function Gw(e,t={}){let n={name:e,private:!0,type:"module",scripts:{deploy:"wrangler deploy",dev:"wrangler dev --local"},dependencies:{"slack-term":t.slackTerm??`^${Ef.version}`},devDependencies:{wrangler:Kw},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
|
{
|
|
@@ -274,7 +274,7 @@ export { default, Relay } from "slack-term/worker";
|
|
|
274
274
|
.wrangler/
|
|
275
275
|
.dev.vars*
|
|
276
276
|
.env*
|
|
277
|
-
`,"README.md":Xw(e)}}function
|
|
277
|
+
`,"README.md":Xw(e)}}function Cf(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
|
|
@@ -304,7 +304,7 @@ configures and deploys it. Created by \`slack relay init\`.
|
|
|
304
304
|
|
|
305
305
|
## Set up
|
|
306
306
|
|
|
307
|
-
${
|
|
307
|
+
${Cf(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.
|
|
@@ -315,40 +315,40 @@ Bump \`slack-term\` in package.json, \`npm install\`, \`npx wrangler deploy\`.
|
|
|
315
315
|
Storage survives redeploys; clients reconnect and resume.
|
|
316
316
|
|
|
317
317
|
Details (endpoints, privacy, protocol): ${Hw}
|
|
318
|
-
`}function
|
|
319
|
-
`)}async function
|
|
318
|
+
`}function Af(e,t={},n=Jw){let s=t.name??Yw(e);if(!zw(s))return{ok:!1,error:`invalid worker name "${s}": use lowercase letters, digits and dashes (1-63 chars, no leading/trailing dash)`};let r=Gw(s,t.slackTerm!==void 0?{slackTerm:t.slackTerm}:{}),o=$f(e),i=Object.keys(r).filter((l)=>Bw(Ta(o,l)));if(i.length&&!t.force)return{ok:!1,error:`refusing to overwrite existing files in ${o} (pass --force to replace them)`,existing:i};for(let[l,u]of Object.entries(r)){let a=Ta(o,l);jw(Ta(a,".."),{recursive:!0}),Ww(a,u)}return{ok:!0,dir:o,name:s,written:Object.keys(r),token:n(32).toString("hex")}}function Tf(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}`,Cf(e.name,e.token)].join(`
|
|
319
|
+
`)}async function Ff(e,t,n=fetch,s=1e4){if(!e||!t)return{code:2,out:"slack relay health: set SLACK_RELAY_URL and SLACK_RELAY_TOKEN (or pass --url / --token)"};let r=`${e.replace(/\/+$/,"")}/health`;try{let o=await n(r,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(s)}),i=await o.text();if(o.status===401)return{code:1,out:"slack relay health: 401 unauthorized — SLACK_RELAY_TOKEN does not match the relay's RELAY_TOKEN secret"};if(!o.ok)return{code:1,out:`slack relay health: HTTP ${o.status} from ${r}${i?`: ${i.slice(0,200)}`:""}`};let l;try{l=JSON.parse(i)}catch{return{code:1,out:`slack relay health: not a slack-term relay (non-JSON reply from ${r})`}}return{code:l.ok===!0?0:1,out:JSON.stringify(l,null,2)}}catch(o){return{code:1,out:`slack relay health: cannot reach ${r}: ${o instanceof Error?o.message:String(o)}`}}}import{spawn as Vw}from"node:child_process";import{constants as Of}from"node:os";var Zw=["processing","active","suspended","closed"];function Rf(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?Rr():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 If(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function vf(e,t,n){let{ref:s,threadTs:r}=n(t);if(!r||!/^\d{10}\.\d{6}$/.test(r))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Nr(e,s),thread_ts:r}}function Oa(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function Qw(e,t,n,s){let r,o,i,l,u,a=!1,c=!1,d=1,f=(h)=>{if(o)return;if(o=h,a=!0,r&&r.exitCode===null&&r.signalCode===null)r.kill(h),i=setTimeout(()=>r?.kill("SIGKILL"),5000)},p=()=>f("SIGINT"),g=()=>f("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",g);try{if(c=!0,await Fs(e,t,"processing"),!a&&s.title!==void 0)await Zi(e,t,s.title);if(!a){r=Vw(n[0],n.slice(1),{stdio:"inherit"});let h=new Promise((m)=>{r.once("error",()=>{console.error("agent: could not start command"),m(127)}),r.once("exit",(y,w)=>{m(y??(w?128+Of.signals[w]:1))})});l=setInterval(()=>{if(a||u)return;u=Fs(e,t,"processing").then(()=>{}).catch((m)=>Oa("heartbeat failed; retrying on next tick",m)).finally(()=>{u=void 0})},s.every*1000),d=await h}}catch(h){Oa("could not start agent session",h)}finally{if(a=!0,clearInterval(l),clearTimeout(i),await u,c)try{await Fs(e,t,s.close?"closed":"active")}catch(h){if(Oa("final status clear failed",h),d===0)d=1}process.removeListener("SIGINT",p),process.removeListener("SIGTERM",g)}return o?128+Of.signals[o]:d}function Pf(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:Zw,demandOption:!0}),async(s)=>{If(s.title);let r=Rf(s["bot-token-env"]),o=await vf(r,s.target,t);if(await Fs(r,o,s.status),s.title!==void 0)await Zi(r,o,s.title)}).command("run <target>","Keep a thread working while a command runs: run <target> -- <command...>",(s)=>n(s).parserConfiguration({"populate--":!0}).option("every",{type:"number",default:300,describe:"Heartbeat seconds (>0 and <3600); processing expires after one hour"}).option("close",{type:"boolean",default:!1,describe:"Finish with closed instead of active (also on failure or interrupt)"}),async(s)=>{if(If(s.title),!Number.isFinite(s.every)||s.every<=0||s.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let r=process.argv.indexOf("--"),o=r<0?[]:process.argv.slice(r+1);if(!o[0])throw Error("agent run requires -- <command...>");let i=Rf(s["bot-token-env"]),l=await vf(i,s.target,t);process.exitCode=await Qw(i,l,o,{every:s.every,close:s.close,...s.title!==void 0?{title:s.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}import{readdirSync as g0,readFileSync as m0,statSync as y0}from"node:fs";import{join as Ba}from"node:path";import{fileURLToPath as b0}from"node:url";import{closeSync as e0,existsSync as Lf,mkdirSync as Mf,openSync as t0,readFileSync as Qr,realpathSync as n0,renameSync as s0,statSync as va,unlinkSync as Nf,writeFileSync as r0}from"node:fs";import{homedir as Bf}from"node:os";import{dirname as Pa,join as dt,resolve as Ra}from"node:path";var o0=".slack-term";function Ms(){return process.env.SLACK_TERM_HOME??dt(Bf(),".config","slack-term")}function eo(e=process.cwd()){let t=Ra(e);for(;;){let n=dt(t,o0);try{if(va(n).isDirectory())return{dir:n,global:!1}}catch{}let s=Pa(t);if(s===t)break;t=s}return{dir:Ms(),global:!0}}function On(e,t){Mf(Pa(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;r0(n,t,{mode:384}),s0(n,e)}function i0(e,t,n=1e4,s=5000){let r=`${e}.lock`;Mf(Pa(r),{recursive:!0});let o=Date.now()+s;for(;;)try{e0(t0(r,"wx"));break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-va(r).mtimeMs>n){Nf(r);continue}}catch{continue}if(Date.now()>o)throw Error(`${r} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{Nf(r)}catch{}}}function a0(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(Qr(e,"utf8"))}catch(r){if(r.code==="ENOENT")return{};throw Error(`${e}: ${r instanceof Error?r.message:String(r)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((r)=>typeof r==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let r={};for(let[o,i]of Object.entries(n.subscriptions)){let l=a0(i);if(l&&jf(o))r[o]=l}s.subscriptions=r}return s}function La(e){let t=nn(dt(e.dir,"settings.yml")),n=nn(dt(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},r={...t,...n};if(Object.keys(s).length)r.subscriptions=s;else delete r.subscriptions;return r}var c0=/^[a-z0-9][a-z0-9._-]{0,63}$/;function jf(e){return c0.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function Wf(e){let t=nn(dt(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:nn(dt(e.dir,"settings.local.yml")).subscriptions??{},r=[];for(let[o,i]of Object.entries(n))if(!s[o])r.push({...i,name:o,scope:e,file:"settings.yml"});for(let[o,i]of Object.entries(s))r.push({...i,name:o,scope:e,file:"settings.local.yml"});return r.sort((o,i)=>o.name.localeCompare(i.name))}var l0="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function u0(e){try{let t=Qr(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 d0(e,t,n){let s=dt(e.dir,t?"settings.yml":"settings.local.yml");i0(s,()=>{let r=t?u0(s):l0,o={};try{let i=Bun.YAML.parse(
|
|
323
|
-
`)})}function
|
|
324
|
-
`).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function Na(){let e=[];for(let s of h0())try{if(va(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=
|
|
325
|
-
`));if(s)return{lang:s,source:"content"};let r=
|
|
326
|
-
`),n=t[t.length-2];if(!
|
|
327
|
-
`);if(s.length<2)return e;if(
|
|
328
|
-
`);return r===e?e:r}function
|
|
329
|
-
`)}function
|
|
322
|
+
`):""}catch{return""}}function d0(e,t,n){let s=dt(e.dir,t?"settings.yml":"settings.local.yml");i0(s,()=>{let r=t?u0(s):l0,o={};try{let i=Bun.YAML.parse(Qr(s,"utf8"));if(i&&typeof i==="object"&&!Array.isArray(i))o=i}catch(i){if(i.code!=="ENOENT")throw Error(`${s}: ${i instanceof Error?i.message:String(i)}`)}n(o),On(s,r+Bun.YAML.stringify(o,null,2)+`
|
|
323
|
+
`)})}function Uf(e){return nn(dt(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function f0(e,t=process.cwd()){if(!Uf(e))return;let n=nn(dt(e.dir,"settings.yml")).owner;if(!n)return`${e.dir} is restricted and names no \`owner\` in settings.yml: nobody may write it with --shared (edit the file)`;let s=(i)=>{try{return n0(Ra(i))}catch{return Ra(i)}},r=s(n.replace(/^~(?=\/|$)/,Bf())),o=s(t);if(o===r||o.startsWith(r.endsWith("/")?r:r+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function Jf(e,t,n,s={}){let r=typeof s==="boolean"?{shared:s}:s,o=r.shared===!0;if(!jf(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!o&&Uf(e))throw new Ia(e);if(o&&!r.asOwner){let l=f0(e,r.cwd);if(l)throw new Ia(e,l)}let i=Wf(e).find((l)=>l.name===t);return d0(e,o,(l)=>{let u=l.subscriptions&&typeof l.subscriptions==="object"?l.subscriptions:{};u[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},l.subscriptions=u}),i}class Ia 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 p0(){return dt(Ms(),"scopes")}function h0(){try{return Qr(p0(),"utf8").split(`
|
|
324
|
+
`).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function Na(){let e=[];for(let s of h0())try{if(va(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=Ms();if((Lf(dt(t,"settings.yml"))||Lf(dt(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function Ma(e,t,n=Na()){let s=[];for(let r of n)for(let o of Wf(r))if(o.channel===e&&(o.thread_ts===void 0||o.thread_ts===t))s.push(o);return s}var Hf=b0(new URL("../locales/",import.meta.url)),Kf=new Map;function qf(e){let t;try{t=y0(e).mtimeMs}catch{return}let n=Kf.get(e);if(n&&n.mtimeMs===t)return n.pack;let s;try{let r=JSON.parse(m0(e,"utf8"));s=r&&typeof r.lang==="string"?r:void 0}catch{s=void 0}return Kf.set(e,{mtimeMs:t,pack:s}),s}function zf(){let e=eo();return e.global?void 0:Ba(e.dir,"locales")}function w0(){let e=new Set;for(let t of[Hf,zf()]){if(!t)continue;try{for(let n of g0(t))if(n.endsWith(".json"))e.add(n.slice(0,-5))}catch{}}return[...e].sort()}function to(e){let t=qf(Ba(Hf,`${e}.json`)),n=zf(),s=n?qf(Ba(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 no(e,t,n={}){let s=to(e)?.ask??{},r=s[t]??s[`${t} (WIRE)`]??to("en")?.ask?.[t]??to("en")?.ask?.[`${t} (WIRE)`];if(r===void 0)throw Error(`language pack ${e}: no ask.${t}`);return r.replace(/\{(\w+)\}/g,(o,i)=>(i in n)?String(n[i]):o)}function Yf(){let e=[];for(let t of w0())for(let n of to(t)?.choice_patterns??[])try{e.push({lang:t,re:new RegExp(n,"iu")})}catch{}return e}var Fe=[{name:"one",glyph:"1️⃣"},{name:"two",glyph:"2️⃣"},{name:"three",glyph:"3️⃣"},{name:"four",glyph:"4️⃣"},{name:"five",glyph:"5️⃣"},{name:"six",glyph:"6️⃣"},{name:"seven",glyph:"7️⃣"},{name:"eight",glyph:"8️⃣"},{name:"nine",glyph:"9️⃣"},{name:"keycap_ten",glyph:"\uD83D\uDD1F"}],Lt=Fe.length,st="question",sn=`:${st}: `,Nt="heavy_plus_sign",so=`:${Nt}: `,Zf=[Nt,st],rn="information_source",ro=`:${rn}: `,$t=["ja","en"];function Ua(e,t=process.env){for(let[o,i]of[[e.flag,"flag"],[t.SLACK_TERM_LANG,"env"]]){if(o===void 0||o.trim()==="")continue;let l=o.trim().toLowerCase();return $t.includes(l)?{lang:l,source:i}:null}let n=(e.readerLocales??[]).map(Gf);if(n.length&&n[0]&&n.every((o)=>o===n[0]))return{lang:n[0],source:"readers"};let s=Ja((e.content??[]).join(`
|
|
325
|
+
`));if(s)return{lang:s,source:"content"};let r=Gf(t.LC_ALL||t.LC_MESSAGES||t.LANG);if(r)return{lang:r,source:"system"};return{lang:"en",source:"default"}}function Gf(e){let t=(e??"").toLowerCase();return $t.find((n)=>t===n||/^[_.\-@]/.test(t.slice(n.length))&&t.startsWith(n))??null}function Ja(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 Xf("ja")},get en(){return Xf("en")}};function Xf(e){let t=(n,s)=>no(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${so}${t("otherThread")}`,otherHere:`${so}${t("otherHere")}`,explainLine:`${ro}${t("explainLine")}`,explainNote:`${ro}${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 k0=$t.flatMap((e)=>[Be[e].otherThread,Be[e].otherHere].map((t)=>sn+t.slice(so.length)));function Qf(e){if(e===void 0)return null;if(e.startsWith(so)||e.startsWith("➕ "))return Nt;if(e.startsWith(sn)||e.startsWith("❓ "))return st;return null}function D0(e){return e!==void 0&&(e.startsWith(ro)||e.startsWith("ℹ️ "))}function x0(e,t){if(e===void 0)return!1;return(e.startsWith("ℹ️ ")?ro+e.slice(3):e)===t.explainLine}var oo="_";function ep(e){if(e===void 0||!e.endsWith(oo))return null;return $t.find((t)=>e.startsWith(Be[t].invalidPrefix))??null}function io(e){let t=e.split(`
|
|
326
|
+
`),n=t[t.length-2];if(!ep(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function ao(e,t,n="ja"){let s=e.split(`
|
|
327
|
+
`);if(s.length<2)return e;if(io(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${Be[n].invalidPrefix}${t.map((o)=>`<@${o}>`).join(", ")}${oo}`);let r=s.join(`
|
|
328
|
+
`);return r===e?e:r}function co(e){return typeof e==="string"&&$t.some((t)=>Be[t].explainNote===e.trim())}function Vf(e){return ep(e)!==null}var Ka="white_check_mark",js=`:${Ka}: `,qa="no_entry_sign",Wa=`:${qa}: `,S0=/^【[^】]*(?:作废|作廢|superseded|void)[^】]*】/i;function lo(e){return`:${Fe[e].name}:`}function tp(e,t){let n=Fe[t];for(let s of[lo(t),n.glyph]){if(e.startsWith(`${s} `))return e.slice(s.length+1);if(e===s)return""}return null}function _0(e){return Fe.some((t,n)=>tp(e,n)!==null)}function Ne(e){return e.replace(/\s*\n\s*/g," ")}function Ha(e,t,n,s,r,o="ja",i=!1){let l=Be[o],u=[`${sn}*${e}*`];if(t)u.push("",t);if(n.length){if(u.push(""),u.push(...n.map((a,c)=>`${lo(c)} ${Ne(a)}`)),u.push(r?l.otherThread:l.otherHere),i)u.push(l.explainLine);if(s.length)u.push(""),u.push(...s.map((a,c)=>`(${c+11}) ${Ne(a)}`)),u.push(l.overflowNote);u.push(""),u.push(r?l.instructionReactionThread:l.instructionReactionHere)}else{if(u.push(""),i)u.push(l.explainLine,"");u.push(r?l.instructionTextThread:l.instructionTextHere)}return u.join(`
|
|
329
|
+
`)}function np(e,t,n,s="ja",r){let o=t.answer.split(`
|
|
330
330
|
`).map((l)=>`> ${l}`).join(`
|
|
331
|
-
`),i=`${
|
|
331
|
+
`),i=`${js}*${e}*
|
|
332
332
|
${Be[s].answeredVia(t.how,n)}
|
|
333
333
|
|
|
334
334
|
${o}`;if(r?.body)i+=`
|
|
335
335
|
|
|
336
336
|
${r.body}`;if(r?.chosenLine)i+=`
|
|
337
337
|
|
|
338
|
-
${r.chosenLine}`;return i}function
|
|
338
|
+
${r.chosenLine}`;return i}function sp(e,t){let n=Ct(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=`${lo(t-1)} ${Ne(n.reactable[t-1])}`;else if(t-Lt<=n.overflow.length&&t>Lt)s.chosenLine=`(${t}) ${Ne(n.overflow[t-Lt-1])}`}return s.body||s.chosenLine?s:void 0}function rp(e,t,n="ja",s,r){let o=Be[n],i=`${Wa}*${e}*
|
|
339
339
|
${o.voidStamp(Ne(t.trim()))}`;if(r)i+=`
|
|
340
340
|
${o.supersededBy(r)}`;if(s)i+=`
|
|
341
341
|
|
|
342
|
-
${s}`;return i}function
|
|
343
|
-
`),n=
|
|
344
|
-
`),n=t[t.length-1]??"";if(e.startsWith(
|
|
345
|
-
`),n=(y)=>e.startsWith(`${y}*`)&&t.some((w,
|
|
346
|
-
`).slice(Wa.length).replace(/^\*/,"").replace(/\*$/,"")),
|
|
347
|
-
`).slice(
|
|
348
|
-
`);if(!_)return{kind:"other"};return{kind:"resolved",question:
|
|
349
|
-
`).replace(/^\*/,"").replace(/\*$/,""),f=[],p=[],g=t.length-1;if(
|
|
350
|
-
`).replace(/^\n+|\n+$/g,"");return{kind:"open",question:d,body:m,reactable:f,overflow:p,threadOnly:o,lang:l,explain:h}}function
|
|
351
|
-
`),s=
|
|
342
|
+
${s}`;return i}function op(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),r=!1;for(let o of $t){let i=Be[o];for(let u of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere])if(s.includes(u))r=!0;for(let u of[i.instructionReactionThread,i.instructionReactionHere,i.instructionTextThread,i.instructionTextHere,i.overflowNote,i.otherThread,i.otherHere,...k0,i.explainLine])s=s.split(u).join(" ");let l=s.indexOf(i.invalidPrefix);if(l>=0){let u=s.indexOf(oo,l+i.invalidPrefix.length);s=s.slice(0,l)+" "+(u>=0?s.slice(u+oo.length):"")}}if(!r)return null;return{question:n[1],body:s.replace(/[ \t]{3,}/g," ").trim()}}function ip(e){if(!e[0]?.startsWith(js))return-1;let t=(n)=>!!n&&(n.startsWith("> ")||n.startsWith("> "));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 ap(e){let t=e.split(`
|
|
343
|
+
`),n=ip(t),r=((n>0?t[n]:t[1])??"").match(/^_(?:返信|Answered by reply)(?: \((\d+)\))?/);if(!r)return{byReply:!1};return r[1]?{byReply:!0,n:Number(r[1])}:{byReply:!0}}function Bs(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function Ws(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(js))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 Ct(e){let t=e.split(`
|
|
345
|
+
`),n=(y)=>e.startsWith(`${y}*`)&&t.some((w,D)=>D>0&&w.length>1&&w.startsWith("_")&&w.endsWith("_"));if(n(Wa)){let y=t.findIndex((_,E)=>E>0&&_.startsWith("_")&&_.endsWith("_")),w=Bs(t.slice(0,y>0?y:1).join(`
|
|
346
|
+
`).slice(Wa.length).replace(/^\*/,"").replace(/\*$/,"")),D=y>0?t[y].replace(/^_|_$/g,""):"",k=y>0?t[y+1]?.match(/^↪ [^::]*[::] (.+)$/)?.[1]:void 0;return k?{kind:"void",question:w,reason:D,supersededBy:k}:{kind:"void",question:w,reason:D}}let s=t[0].match(S0)?e.match(/:question: \*([^\n]*?)\*/):null;if(s)return{kind:"void",question:Bs(s[1]),reason:Bs(t[0])};if(n(js)){let y=(E)=>E.startsWith("> ")?E.slice(2):E.startsWith("> ")?E.slice(5):null,w=ip(t),D;if(w>0){D=[];for(let E=w+2;E<t.length;E++){let S=y(t[E]);if(S===null)break;D.push(S)}}else D=t.map(y).filter((E)=>E!==null);let k=Bs(t.slice(0,w>0?w:1).join(`
|
|
347
|
+
`).slice(js.length).replace(/^\*/,"").replace(/\*$/,"")),_=D.map(Bs).join(`
|
|
348
|
+
`);if(!_)return{kind:"other"};return{kind:"resolved",question:k,answer:_}}let r=t[t.length-1]??"",o,i,l=$t.find((y)=>[Be[y].instructionReactionThread,Be[y].instructionReactionHere,Be[y].instructionTextThread,Be[y].instructionTextHere].includes(r));if(!l)return{kind:"other"};let u=Be[l];o=r===u.instructionReactionThread||r===u.instructionTextThread,i=r===u.instructionReactionThread||r===u.instructionReactionHere;let a=t[0].startsWith(sn)?t[0].slice(sn.length):t[0];if(t[0]=a,!t[0].startsWith("*"))return{kind:"other"};let c=0;while(c<t.length&&!(t[c].endsWith("*")&&(c>0||t[0].length>1)))c++;if(c>=t.length)return{kind:"other"};let d=t.slice(0,c+1).join(`
|
|
349
|
+
`).replace(/^\*/,"").replace(/\*$/,""),f=[],p=[],g=t.length-1;if(Vf(t[g-1]))g--;let h=!1;if(i){let y=t.length-2;if(Vf(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(D0(t[y]))h=!0,y--;if(Qf(t[y]))y--;let w=[];while(y>=0){let D=t[y];if(!_0(D))break;w.unshift(D),y--}if(!w.length||w.length>Lt)return{kind:"other"};for(let D=0;D<w.length;D++){let k=tp(w[D],D);if(k===null)return{kind:"other"};f.push(k)}if(t[y]!=="")return{kind:"other"};if(y<c+1)return{kind:"other"};g=y;for(let D=0;D<p.length;D++)if(!t.includes(`(${D+11}) ${p[D]}`))return{kind:"other"}}else if(t[g-1]===""&&x0(t[g-2],u)&&t[g-3]===""&&g-3>=c)h=!0,g-=2;let m=t.slice(c+1,g).join(`
|
|
350
|
+
`).replace(/^\n+|\n+$/g,"");return{kind:"open",question:d,body:m,reactable:f,overflow:p,threadOnly:o,lang:l,explain:h}}function Us(e){let t=Ct(e);if(t.kind!=="open")return null;if(!t.reactable.length)return st;let n=e.split(`
|
|
351
|
+
`),s=lo(t.reactable.length-1),r=Fe[t.reactable.length-1].glyph,o=-1;for(let i=n.length-1;i>=0;i--)if(n[i].startsWith(`${s} `)||n[i]===s||n[i].startsWith(`${r} `)||n[i]===r){o=i;break}return(o>=0?Qf(n[o+1]):null)??st}function ja(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function cp(e,t,n){let s=Array.from({length:n},(o,i)=>i===n-1?t:""),r=za(e,s);return r.kind==="chosen"&&r.index===n}function za(e,t){let n=ja(e);if(!n)return{kind:"none"};let s=t.map(ja),r=new Set;s.forEach((a,c)=>{if(a&&a===n)r.add(c+1)}),Fe.forEach((a,c)=>{if(c<t.length&&e.trim()===a.glyph)r.add(c+1)});let o=0,i="",l=n.match(/^(\d{1,2})$/);if(l)o=Number(l[1]);else if(l=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(o=Number(l[1]),i=ja(l[2]),!i)return{kind:"none"};if(/^\d+$/.test(i))return{kind:"none"}}if(o>=1&&o<=t.length&&(i===""||i===s[o-1]))r.add(o);let u=[...r].sort((a,c)=>a-c);if(!u.length)return{kind:"none"};if(u.length>1)return{kind:"ambiguous",indexes:u};return{kind:"chosen",index:u[0]}}var Rn={phi:1.618033988749895,minMs:1000,fastMaxMs:5000,fastWindowMs:120000,slowMaxMs:20000};function lp(e,t){let n=t<Rn.fastWindowMs?Rn.fastMaxMs:Rn.slowMaxMs;return Math.min(Math.max(e,Rn.minMs)*Rn.phi,n)}import{closeSync as E0,existsSync as uo,mkdirSync as fo,openSync as $0,readFileSync as ho,realpathSync as C0,renameSync as A0,statSync as Ya,unlinkSync as up,writeFileSync as T0}from"node:fs";import{homedir as dp}from"node:os";import{dirname as Ga,join as He,resolve as po}from"node:path";var fp=".slack-term",F0=["inbox","archived","outbox","sent"];function Js(){return process.env.SLACK_TERM_HOME??He(dp(),".config","slack-term")}function Xe(e=process.cwd()){let t=po(e);for(;;){let n=He(t,fp);try{if(Ya(n).isDirectory())return{dir:n,global:!1}}catch{}let s=Ga(t);if(s===t)break;t=s}return{dir:Js(),global:!0}}var O0='# .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',R0=`# 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 rp(e){if(!e.startsWith(sn))return null;let t=e.slice(sn.
|
|
|
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 Xa(e,t={}){let n=He(
|
|
368
|
+
`;function Xa(e,t={}){let n=He(po(e),fp),s=[];fo(n,{recursive:!0});for(let i of F0){let l=He(n,i);if(!uo(l))fo(l,{recursive:!0}),s.push(`${i}/`)}let r=(i,l)=>{let u=He(n,i);if(uo(u))return;Va(u,l),s.push(i)};r(".gitignore",`*
|
|
369
369
|
`),r("README.md",O0);let o=Object.fromEntries(Object.entries(t).filter(([,i])=>i!==void 0));if(r("settings.yml",R0+(Object.keys(o).length?`
|
|
370
370
|
`+Bun.YAML.stringify(o,null,2)+`
|
|
371
|
-
`:"")),n!==
|
|
371
|
+
`:"")),n!==Js())N0(n);return{dir:n,created:s}}function Va(e,t){fo(Ga(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;T0(n,t,{mode:384}),A0(n,e)}function pp(e,t,n=1e4,s=5000){let r=`${e}.lock`;fo(Ga(r),{recursive:!0});let o=Date.now()+s;for(;;)try{E0($0(r,"wx"));break}catch(i){if(i.code!=="EEXIST")throw i;try{if(Date.now()-Ya(r).mtimeMs>n){up(r);continue}}catch{continue}if(Date.now()>o)throw Error(`${r} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{up(r)}catch{}}}function I0(e){if(!e||typeof e!=="object")return;let t=e;if(typeof t.channel!=="string"||!t.channel)return;let n={channel:t.channel};if(typeof t.thread_ts==="string"&&/^\d{10}\.\d{6}$/.test(t.thread_ts))n.thread_ts=t.thread_ts;if(typeof t.added==="string")n.added=t.added;if(typeof t.note==="string")n.note=t.note;return n}function ns(e){let t;try{t=Bun.YAML.parse(ho(e,"utf8"))}catch(r){if(r.code==="ENOENT")return{};throw Error(`${e}: ${r instanceof Error?r.message:String(r)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((r)=>typeof r==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let r={};for(let[o,i]of Object.entries(n.subscriptions)){let l=I0(i);if(l&&Za(o))r[o]=l}s.subscriptions=r}return s}function ss(e){let t=ns(He(e.dir,"settings.yml")),n=ns(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},r={...t,...n};if(Object.keys(s).length)r.subscriptions=s;else delete r.subscriptions;return r}var v0=/^[a-z0-9][a-z0-9._-]{0,63}$/;function Za(e){return v0.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function on(e){let t=ns(He(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:ns(He(e.dir,"settings.local.yml")).subscriptions??{},r=[];for(let[o,i]of Object.entries(n))if(!s[o])r.push({...i,name:o,scope:e,file:"settings.yml"});for(let[o,i]of Object.entries(s))r.push({...i,name:o,scope:e,file:"settings.local.yml"});return r.sort((o,i)=>o.name.localeCompare(i.name))}function Qa(e,t=process.cwd()){if(!Za(e))return;let n=Xe(t),s=n.global?[n]:[n,{dir:Js(),global:!0}];for(let r of s){let o=on(r).find((i)=>i.name===e);if(o)return o}return}var P0="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function L0(e){try{let t=ho(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
|
|
375
|
-
`)})}function
|
|
374
|
+
`):""}catch{return""}}function hp(e,t,n){let s=He(e.dir,t?"settings.yml":"settings.local.yml");pp(s,()=>{let r=t?L0(s):P0,o={};try{let i=Bun.YAML.parse(ho(s,"utf8"));if(i&&typeof i==="object"&&!Array.isArray(i))o=i}catch(i){if(i.code!=="ENOENT")throw Error(`${s}: ${i instanceof Error?i.message:String(i)}`)}n(o),Va(s,r+Bun.YAML.stringify(o,null,2)+`
|
|
375
|
+
`)})}function vn(e){return ns(He(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function gp(e,t=process.cwd()){if(!vn(e))return;let n=ns(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 C0(po(i))}catch{return po(i)}},r=s(n.replace(/^~(?=\/|$)/,dp())),o=s(t);if(o===r||o.startsWith(r.endsWith("/")?r:r+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function ec(e,t,n,s={}){let r=typeof s==="boolean"?{shared:s}:s,o=r.shared===!0;if(!Za(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!o&&vn(e))throw new In(e);if(o&&!r.asOwner){let l=gp(e,r.cwd);if(l)throw new In(e,l)}let i=on(e).find((l)=>l.name===t);return hp(e,o,(l)=>{let u=l.subscriptions&&typeof l.subscriptions==="object"?l.subscriptions:{};u[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},l.subscriptions=u}),i}function mp(e,t,n=!1,s){let r=on(e).find((o)=>o.name===t);if(!r)return"absent";if(r.file==="settings.yml"&&!n)return"in-settings.yml";if(r.file==="settings.yml"){let o=gp(e,s);if(o)throw new In(e,o)}return hp(e,r.file==="settings.yml",(o)=>{let i=o.subscriptions;if(i)delete i[t];if(i&&!Object.keys(i).length)delete o.subscriptions}),"removed"}class In 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 yp(){return He(Js(),"scopes")}function N0(e){let t=yp();pp(t,()=>{let n=bp();if(n.includes(e))return;Va(t,[...n,e].join(`
|
|
376
376
|
`)+`
|
|
377
|
-
`)})}function
|
|
378
|
-
`).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function M0(){let e=[];for(let s of
|
|
377
|
+
`)})}function bp(){try{return ho(yp(),"utf8").split(`
|
|
378
|
+
`).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function M0(){let e=[];for(let s of bp())try{if(Ya(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=Js();if((uo(He(t,"settings.yml"))||uo(He(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function wp(e,t,n=M0()){let s=[];for(let r of n)for(let o of on(r))if(o.channel===e&&(o.thread_ts===void 0||o.thread_ts===t))s.push(o);return s}function tc(e,t){let n=t?.trim();if(!n)return e;let s=/^\[([^\]@\s]+)\]$/.exec(n),r=e;if(s){let o=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=e.replace(new RegExp(`^\\s*\\[${o}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),"")}else if(e.trimStart().startsWith(n))r=e.trimStart().slice(n.length).replace(/^[ \t]+/,"");return r.trim()?`${n} ${r}`:""}function nc(e,t){if(e.channel===t.channel&&e.threadTs===t.root)return;let n=(s,r)=>r?`${s} thread ${r}`:`${s} (top level)`;return`the message you are answering (${t.ts}) is in ${n(t.channel,t.root)}, but the destination is ${n(e.channel,e.threadTs)}.
|
|
379
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
|
|
381
|
-
`)){let s=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!s)continue;let r=s[2];if(/^(["']).*\1$/.test(r))r=r.slice(1,-1);t[s[1]]=r}return t}function
|
|
382
|
-
`)
|
|
383
|
-
`);return null}var
|
|
384
|
-
`))for(let s of t)if(s.re.test(n))return s.lang;return}function vp(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 Np,readdirSync as
|
|
380
|
+
`+" Or pass --any-thread if the other thread is really meant."}var kp=/(⬜️?|:white_large_square:)(\s*)(\d+)\./g,B0=/(✅|:white_check_mark:)\s*(\d+)\./g;function Dp(e,t){let n=[...e.matchAll(kp)].map((i)=>Number(i[3])),s=[...e.matchAll(B0)].map((i)=>Number(i[2]));if(t===void 0){if(n.length===0)return s.length?{kind:"already",n:s[0]}:{kind:"none"};if(n.length>1)return{kind:"ambiguous",open:n};t=n[0]}if(!n.includes(t))return s.includes(t)?{kind:"already",n:t}:{kind:"missing",n:t};let r=!1;return{kind:"ticked",text:e.replace(kp,(i,l,u,a)=>{if(r||Number(a)!==t)return i;return r=!0,`${l.startsWith(":")?":white_check_mark:":"✅"}${u}${a}.`}),n:t}}function xp(e,t,n){let s=/^\[([^\]@\s]+)\]$/.exec(n?.trim()??"");if(!s)return t;let r=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`^\\[${r}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),i=o.exec(e);if(!i)return t;return i[0]+t.replace(o,"")}import{readFileSync as _p}from"node:fs";import{homedir as j0}from"node:os";import{join as Sp}from"node:path";var Ep=/^@([a-z0-9][a-z0-9._-]{0,63})$/;function $p(e){let t=Ep.exec(e[0]??"");return t?{who:t[1],rest:e.slice(1)}:{rest:e}}function W0(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 go(e=process.cwd()){let t=eo(e),n=t.global?[t]:[{dir:Ms(),global:!0},t],s=new Map;for(let r of n){let i=nn(Sp(r.dir,"settings.yml")).restrict_to_subscriptions?["settings.yml"]:["settings.yml","settings.local.yml"];for(let l of i){let u;try{u=Bun.YAML.parse(_p(Sp(r.dir,l),"utf8"))}catch{continue}let a=u?.identities;if(!a||typeof a!=="object")continue;for(let[c,d]of Object.entries(a)){let f=W0(d);if(f&&Ep.test(`@${c}`))s.set(c,f)}}}return s}function U0(e){let t={};for(let n of _p(e.replace(/^~(?=\/|$)/,j0()),"utf8").split(`
|
|
381
|
+
`)){let s=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/.exec(n);if(!s)continue;let r=s[2];if(/^(["']).*\1$/.test(r))r=r.slice(1,-1);t[s[1]]=r}return t}function mo(e,t=process.env,n=go()){let s=n.get(e),r=[...n.keys()].sort().map((l)=>`@${l}`).join(", ")||"(none: add `identities:` to .slack-term/settings.yml)";if(!s)return{error:`unknown identity @${e}. Known: ${r}`};if(s.kind==="user"&&s.profile&&!s.env&&!s.env_file)return t.SLACK_WORKSPACE=s.profile,delete t.SLACK_TOKEN,delete t.SLACK_BOT_TOKEN,t.SLACK_TERM_IDENTITY=e,{kind:"user"};let o=s.env??(s.kind==="bot"?"SLACK_BOT_TOKEN":"SLACK_TOKEN"),i;try{i=s.env_file?U0(s.env_file)[o]:t[o]}catch{return{error:`@${e}: cannot read ${s.env_file}`}}if(!i)return{error:`@${e}: no ${o}${s.env_file?` in ${s.env_file}`:" in the environment"}`};if(s.kind==="bot"&&!i.startsWith("xoxb-"))return{error:`@${e} is a bot, but ${o} is not a bot token (xoxb-)`};if(s.kind==="user"&&i.startsWith("xoxb-"))return{error:`@${e} is a user, but ${o} holds a bot token`};if(s.kind==="bot")t.SLACK_BOT_TOKEN=i,t.SLACK_TOKEN=i;else t.SLACK_TOKEN=i,delete t.SLACK_BOT_TOKEN;return t.SLACK_TERM_IDENTITY=e,{kind:s.kind}}function sc(e=process.env){return["AY_AGENT_ID","AGENT_YES_PID","CLAUDECODE"].find((t)=>e[t])}function Cp(e){if(!e.isWrite||e.who||e.asBot||e.activeIsBot)return null;let t=e.userIdentities??[];if(e.asUser&&!e.agent)return null;let n=e.identities.map((r)=>`@${r}`).join(" | "),s=n?` Name who acts: slack ${e.identities[0]?`@${e.identities[0]}`:"@<who>"} ${e.cmd} … (${n})`:" Add identities to .slack-term/settings.yml, then: slack @<who> "+e.cmd+" …";if(e.agent){let r=t.length?` As a person, on purpose: slack @${t[0]} ${e.cmd} … (${t.map((o)=>`@${o}`).join(" | ")})`:" As a person, on purpose: add them to `identities:` (kind: user), then slack @<name> "+e.cmd+" …";return[`Error: refusing to post as the user session from inside an agent (${e.agent} is set): \`${e.cmd}\` would go out as a PERSON.`,...e.asUser?[" --as-user is not accepted from an agent: it hides whose name the post goes out under."]:[],s," As the app: add --as-bot",r].join(`
|
|
382
|
+
`)}if(e.identities.length>=2)return[`Error: several identities are configured (${n}): name the one \`${e.cmd}\` acts as.`,s," Or: --as-bot / --as-user"].join(`
|
|
383
|
+
`);return null}var rc=/:([a-z0-9_+'-]+):((?::skin-tone-[2-6]:)?)/g,J0=/<([A-Za-z][A-Za-z0-9+.-]*:[^|<>\s]*)(?:\|([^<>]*))?>/g,K0=/&(amp|lt|gt);/g,q0=/[︎️]/gu,H0=/[\u{1F3FB}-\u{1F3FF}]/gu,Ap=String.raw`:[a-z0-9_+'-]+:(?::skin-tone-[2-6]:)?`,z0=String.raw`©®‼⁉™ℹ←-⇿⌀-⏿Ⓜ■-➿⤀-⥿⬀-⯿〰〽㊗㊙\u{1F000}-\u{1FAFF}`,Tp=String.raw`[${z0}][\u{E0020}-\u{E007F}]*`,Y0=new RegExp(String.raw`(?<sc>${Ap}(?:${Ap})*)|(?<emoji>[0-9#*]⃣|[\u{1F1E6}-\u{1F1FF}]{2}|${Tp}(?:${Tp})*)|(?<char>[\s\S])`,"gu");function oc(e){let t=new Map,n=[e??null],s=0;while(n.length&&s++<1e5){let r=n.pop();if(Array.isArray(r))n.push(...r);else if(r&&typeof r==="object"){let{name:o,unicode:i}=r;if(r.type==="emoji"&&typeof o==="string"&&typeof i==="string")try{t.set(o.split("::")[0],i.split("-").filter(Boolean).map((l)=>String.fromCodePoint(parseInt(l,16))).join(""))}catch{}n.push(...Object.values(r))}}return t}function G0(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 Ks(e,t){let n=e.normalize("NFC");return n=n.replace(J0,(s,r,o)=>G0(s,r,o)),n=n.replace(K0,(s,r)=>({amp:"&",lt:"<",gt:">"})[r]),n=n.replace(rc,(s,r)=>t.get(r)??s),n=n.replace(q0,"").replace(H0,""),n.split(/\s+/).filter(Boolean).join(" ")}function Fp(e){return[...e.matchAll(Y0)].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 Op(e,t){let n=oc(t.blocks),s=Ks(e,n),r=Ks(typeof t.text==="string"?t.text:"",n);if(s===r)return!0;if(rc.lastIndex=0,!rc.test(r))return!1;let o=Fp(s),i=Fp(r);return o.length===i.length&&o.every(([l,u],a)=>u===i[a][1]||i[a][0]==="sc"&&l==="emoji")}function Rp(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 X0(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`\n]*`/g," ").replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ")}function Ip(e){let t=Yf();for(let n of X0(e).split(`
|
|
384
|
+
`))for(let s of t)if(s.re.test(n))return s.lang;return}function vp(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 Np,readdirSync as rk,readFileSync as ok,renameSync as ik,statSync as ak,unlinkSync as ck,utimesSync as lk}from"node:fs";import{join as At}from"node:path";import{readFileSync as V0}from"node:fs";function Pp(e){let t="";for(;;){let o=/^\(\?([is]+)\)/.exec(e);if(!o)break;t+=o[1],e=e.slice(o[0].length)}e=e.replaceAll("(?P<","(?<").replaceAll("\\z","$").replaceAll("[[:alnum:]]","[A-Za-z0-9]").replaceAll("[:alnum:]","A-Za-z0-9").replaceAll("[:alpha:]","A-Za-z").replaceAll("[:digit:]","0-9").replaceAll("[:space:]","\\s");let n="",s=[],r=0;for(let o=0;o<e.length;o++){let i=e[o];if(i==="\\"){n+=i+(e[o+1]??""),o++;continue}if(i==="["){let l=o+1;if(e[l]==="^")l++;if(e[l]==="]")l++;while(l<e.length&&e[l]!=="]"){if(e[l]==="\\")l++;l++}n+=e.slice(o,l+1),o=l;continue}if(e.startsWith("(?i)",o)){n+="(?i:",r++,o+=3;continue}if(i==="("){s.push(r),r=0,n+=i;continue}if(i===")"){n+=")".repeat(r),r=s.pop()??0,n+=i;continue}if(i==="|"&&r){n+=")".repeat(r)+"|"+"(?i:".repeat(r);continue}n+=i}return n+=")".repeat(r),{source:n,flags:[...new Set(t)].join("")}}function Z0(e){let t=Bun.TOML.parse(e),n=(i)=>{let l=Pp(i);return new RegExp(l.source,l.flags)},s=(t.allowlist?.regexes??[]).map(n),r=(t.allowlist?.stopwords??[]).map((i)=>i.toLowerCase()),o=[];for(let i of t.rules){if(!i.regex)continue;let l=[...s],u=[],a=[],c=[...r];for(let f of[...i.allowlists??[],...i.allowlist?[i.allowlist]:[]]){let p=f.regexTarget==="match"?u:f.regexTarget==="line"?a:l;for(let g of f.regexes??[])p.push(n(g));for(let g of f.stopwords??[])c.push(String(g).toLowerCase())}let d=Pp(i.regex);o.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}:{},...a.length?{allowLine:a}:{},stop:c})}return o}var Q0=[{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:[]}],Lp;function ek(){return Lp??=[...Z0(V0(new URL("./vendor/gitleaks.toml",import.meta.url),"utf8")),...Q0],Lp}function tk(e){let t=new Map;for(let s of e)t.set(s,(t.get(s)??0)+1);let n=0;for(let s of t.values()){let r=s/e.length;n-=r*Math.log2(r)}return n}function nk(e,t){let n=new Set;for(let r of t){if(r.length<6)continue;n.add(r),n.add(JSON.stringify(r).slice(1,-1))}let s=[];for(let r of[...n].sort((o,i)=>i.length-o.length))for(let o=e.indexOf(r);o>=0;o=e.indexOf(r,o+r.length))s.push({id:"known-secret",start:o,end:o+r.length});return s}function sk(e,t={}){let n=t.rules??ek(),s=e.toLowerCase(),r=t.known?.length?nk(e,t.known):[];for(let o of n){if(o.keywords.length&&!o.keywords.some((i)=>s.includes(i)))continue;for(let i of e.matchAll(o.re)){let l=o.group??i.findIndex((d,f)=>f>0&&!!d),u=l>0?i[l]:i[0];if(!u)continue;if(o.entropy&&tk(u)<o.entropy)continue;if(o.allow.some((d)=>d.test(u)))continue;if(o.allowMatch?.some((d)=>d.test(i[0])))continue;if(o.allowLine){let d=e.lastIndexOf(`
|
|
385
385
|
`,i.index)+1,f=e.indexOf(`
|
|
386
|
-
`,i.index+i[0].length);if(o.allowLine.some((p)=>p.test(e.slice(d,f<0?void 0:f))))continue}let a=u.toLowerCase();if(o.stop.some((d)=>a.includes(d)))continue;let c=o.group?i.indices?.[o.group]:void 0;if(c)r.push({id:o.id,start:c[0],end:c[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;r.push({id:o.id,start:d,end:f})}}}return r}function
|
|
387
|
-
`}function
|
|
386
|
+
`,i.index+i[0].length);if(o.allowLine.some((p)=>p.test(e.slice(d,f<0?void 0:f))))continue}let a=u.toLowerCase();if(o.stop.some((d)=>a.includes(d)))continue;let c=o.group?i.indices?.[o.group]:void 0;if(c)r.push({id:o.id,start:c[0],end:c[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;r.push({id:o.id,start:d,end:f})}}}return r}function yo(e,t={}){let n=sk(e,t).sort((i,l)=>i.start-l.start||l.end-i.end);if(!n.length)return{text:e,kinds:[]};let s=[];for(let i of n){let l=s[s.length-1];if(l&&i.start<l.end){if(i.end-i.start>l.end-l.start)l.id=i.id;l.end=Math.max(l.end,i.end)}else s.push({...i})}let r="",o=0;for(let i of s)r+=e.slice(o,i.start)+`[redacted:${i.id}]`,o=i.end;return{text:r+e.slice(o),kinds:[...new Set(s.map((i)=>i.id))]}}var uk=/^\d{10}\.\d{6}$/;function dk(e,t){return`${e}-${t}.yml`}function qs(e){return Bun.YAML.stringify(e,null,2)+`
|
|
387
|
+
`}function fk(e,t,n=[]){let s=dk(t.channel,t.ts);if(Np(At(e.dir,"inbox",s))||Np(At(e.dir,"archived",s)))return!1;let r=yo(t.text,{known:n}),o={...t,text:r.text,...r.kinds.length?{redacted:r.kinds}:{}};return On(At(e.dir,"inbox",s),qs(o)),!0}function Mp(e,t=Na(),n=new Date,s=[]){let r=e.thread_ts??e.ts,o=Ma(e.channel.id,r,t);if(!o.length&&!e.thread_ts){for(let u of t){if(!La(u).auto_subscribe?.includes(e.channel.id))continue;Jf(u,`t-${e.ts}`,{channel:e.channel.id,thread_ts:e.ts,note:"auto: new top-level message"},{shared:!0,asOwner:!0})}o=Ma(e.channel.id,r,t)}let i=[],l=new Set;for(let u of o){if(l.has(u.scope.dir))continue;if(l.add(u.scope.dir),fk(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 Bp(e,t){let n;try{n=rk(e).filter((r)=>r.endsWith(".yml"))}catch{return[]}let s=[];for(let r of n.sort()){let o=At(e,r);try{let i=t(Bun.YAML.parse(ok(o,"utf8")));if(i)s.push({file:o,entry:i,mtimeMs:ak(o).mtimeMs})}catch{}}return s}function pk(e){let t=e;return t&&typeof t.ts==="string"&&typeof t.channel==="string"&&typeof t.text==="string"?t:void 0}function rs(e){return Bp(At(e.dir,"inbox"),pk).sort((t,n)=>Number(t.entry.ts)-Number(n.entry.ts))}function ic(e,t){let n=rs(e),s=uk.test(t)?n.find((o)=>o.entry.ts===t):n.find((o)=>o.file===t||o.file.endsWith(`/${t}`)||o.file.endsWith(`/${t}.yml`));if(!s)return;let r=At(e.dir,"archived",s.file.slice(s.file.lastIndexOf("/")+1));return ik(s.file,r),r}function hk(e){let t=e;return t&&typeof t.to==="string"&&typeof t.text==="string"?t:void 0}function ac(e){return Bp(At(e.dir,"outbox"),hk)}function jp(e,t,n=new Date){let s=At(e.dir,"outbox",`${n.toISOString().replace(/[:.]/g,"-")}-${process.pid}.yml`),r=yo(t.text);return On(s,qs({...t,text:r.text})),{file:s,redacted:r.kinds}}function Wp(e,t,n,s=new Date){let r=t.file.slice(t.file.lastIndexOf("/")+1),o=yo(t.entry.text),{error:i,...l}=t.entry;if(On(At(e.dir,"sent",r),qs({...l,text:o.text,...o.kinds.length?{redacted:o.kinds}:{},...n,sent_at:s.toISOString()})),ck(t.file),t.entry.in_reply_to)ic(e,t.entry.in_reply_to);return At(e.dir,"sent",r)}function Up(e,t){On(e.file,qs({...e.entry,attempts:(e.entry.attempts??0)+1,error:t}))}function Jp(e,t=Date.now()){let n=La(e).nudge_after_min??30;return rs(e).filter((s)=>t-s.mtimeMs>=n*60000)}function Kp(e,t=new Date){On(e.file,qs({...e.entry,nudged_at:t.toISOString()}));let n=new Date(e.mtimeMs);lk(e.file,n,n)}var lc=[{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"}],xC=lc.length,gk="question",mk=`:${gk}: `,yk="heavy_plus_sign",cc=`:${yk}: `;var bk="information_source",qp=`:${bk}: `,zp=["ja","en"];var bo={get ja(){return Hp("ja")},get en(){return Hp("en")}};function Hp(e){let t=(n,s)=>no(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${cc}${t("otherThread")}`,otherHere:`${cc}${t("otherHere")}`,explainLine:`${qp}${t("explainLine")}`,explainNote:`${qp}${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 SC=zp.flatMap((e)=>[bo[e].otherThread,bo[e].otherHere].map((t)=>mk+t.slice(cc.length)));var Yp="_";function Gp(e){if(e===void 0||!e.endsWith(Yp))return null;return zp.find((t)=>e.startsWith(bo[t].invalidPrefix))??null}function uc(e){let t=e.split(`
|
|
388
388
|
`),n=t[t.length-2];if(!Gp(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(
|
|
390
|
-
`);return r===e?e:r}function Vp(e){return Gp(e)!==null}var
|
|
391
|
-
`),r?[]:i)}function nh(e,t){let n=t.reduce((r,o)=>r+o.count,0),s=[`${
|
|
392
|
-
`)}function
|
|
393
|
-
`);if(e.startsWith(
|
|
394
|
-
`).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,l=
|
|
389
|
+
`);if(s.length<2)return e;if(uc(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${bo[n].invalidPrefix}${t.map((o)=>`<@${o}>`).join(", ")}${Yp}`);let r=s.join(`
|
|
390
|
+
`);return r===e?e:r}function Vp(e){return Gp(e)!==null}var wk="white_check_mark",_C=`:${wk}: `,kk="no_entry_sign",EC=`:${kk}: `;var Dt=lc,os=Dt.length,zs="ballot_box_with_ballot",dc=`:${zs}: `,Qp="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",eh="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",wo="_締切: ",ko="_",pc="bar_chart",fc=`:${pc}: `;function Do(e){return`:${Dt[e].name}:`}function Zp(e,t){for(let n of[Do(t),Dt[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function Dk(e){return Dt.some((t,n)=>e.startsWith(`${Do(n)} `)||e.startsWith(`${t.glyph} `))}function Hs(e){return e.replace(/\s*\n\s*/g," ")}function th(e,t,n,s={}){let r=!!s.multi,o=s.deadline??"",i=s.invalid??[];if(!n.length||n.length>os)throw Error(`poll needs 1..${os} choices, got ${n.length}`);let l=[`${dc}*${e}*`];if(t)l.push("",t);if(l.push(""),l.push(...n.map((u,a)=>`${Do(a)} ${Hs(u)}`)),l.push(""),o)l.push(`${wo}${Hs(o)}${ko}`);return l.push(r?eh:Qp),Xp(l.join(`
|
|
391
|
+
`),r?[]:i)}function nh(e,t){let n=t.reduce((r,o)=>r+o.count,0),s=[`${fc}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return s.push(...t.map((r,o)=>`${Do(o)} ×${r.count} ${Hs(r.choice)}`)),s.join(`
|
|
392
|
+
`)}function Ys(e){let t=e.split(`
|
|
393
|
+
`);if(e.startsWith(fc)){let f=t[0].slice(fc.length).replace(/^\*/,"").replace(/\*$/,""),p=[];for(let g=0;g<Dt.length;g++){let h=t.map((y)=>Zp(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===Qp)s=!1;else if(n===eh)s=!0;else return{kind:"other"};if(t[0].startsWith(dc))t[0]=t[0].slice(dc.length);if(!t[0].startsWith("*"))return{kind:"other"};let r=0;while(r<t.length&&!(t[r].endsWith("*")&&(r>0||t[0].length>1)))r++;if(r>=t.length)return{kind:"other"};let o=t.slice(0,r+1).join(`
|
|
394
|
+
`).replace(/^\*/,"").replace(/\*$/,""),i=t.length-2,l=uc(e);if(Vp(t[i]))i--;let u="",a=t[i];if(a!==void 0&&a.startsWith(wo)&&a.endsWith(ko)&&a.length>wo.length+ko.length)u=a.slice(wo.length,-ko.length),i--;if(t[i]!=="")return{kind:"other"};i--;let c=[];while(i>=0){let f=t[i];if(!Dk(f))break;c.unshift(f),i--}if(!c.length||c.length>os)return{kind:"other"};let d=[];for(let f=0;f<c.length;f++){let p=Zp(c[f],f);if(p===null)return{kind:"other"};d.push(p)}if(t[i]!=="")return{kind:"other"};if(i<r+1)return{kind:"other"};return{kind:"open",question:o,choices:d,multi:s,deadline:u,invalid:l}}function sh(e,t,n,s){let r=new Map(t.map((a)=>[a.name,a.users])),o=e.map((a,c)=>(r.get(Dt[c].name)??[]).filter((d)=>!n.has(d))),i=[];if(!s){let a=new Map;for(let c of o)for(let d of c)a.set(d,(a.get(d)??0)+1);for(let[c,d]of a)if(d>1)i.push(c)}let l=new Set(i),u=o.map((a)=>a.filter((c)=>!l.has(c)));return{tallies:e.map((a,c)=>({choice:a,count:u[c].length})),voters:u,ambiguous:i}}function xk(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var rh={isTestEnv:()=>xk(),sleep:(e)=>rh.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function Sk(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 xo(e,t,n,s=Sk()){for(let r=0;r<e.length;r++){let o=!0;try{await t(e[r])}catch(i){o=!1,n(e[r],i)}if(o&&s>0&&r<e.length-1)await rh.sleep(s)}}var oh=["text","select","user","link","date","number","checkbox"];function ah(e){let t=e.split(":"),n=(t[0]??"").trim(),s=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!oh.includes(s))throw Error(`--col ${e}: unknown type "${s}" (expected one of ${oh.join(", ")})`);if(s==="select"){let r=(t.slice(2).join(":")||"").split(",").map((o)=>o.trim()).filter(Boolean);if(!r.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:s,choices:r}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:s}}var ih=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function ch(e){if(!e.length)throw Error("at least one --col is required (the first one is the primary text column)");if(e[0].type!=="text")throw Error(`the first --col is the primary column and must be text, got ${e[0].type}`);return e.map((t,n)=>{let s={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)s.is_primary_column=!0;if(t.type==="select")s.options={format:"single_select",choices:t.choices.map((r,o)=>({value:r,label:r,color:ih[o%ih.length]}))};if(t.type==="user")s.options={format:"single_entity"};return s})}function lh(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((s)=>{let r=s??{},i=((r.options??{}).choices??[]).map((l)=>{let u=l??{};return{value:String(u.value??""),label:String(u.label??u.value??"")}});return{id:String(r.id??""),key:String(r.key??""),name:String(r.name??""),type:String(r.type??""),choices:i}})}function hc(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 gc(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 mc(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 uh(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as bc}from"node:child_process";import{chmodSync as _k,existsSync as fh,mkdirSync as Ek}from"node:fs";import{homedir as $k,hostname as Ck}from"node:os";import{basename as ph,dirname as Ak,join as Tk}from"node:path";function _o(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var So={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function Fk(e){try{let n=(bc("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:ph(n[2].trim())}}catch{return}}function Ok(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=Fk(e);if(!n)return;if(So[n.comm])return n;e=n.ppid}return}function dh(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function hh(e=process.env){let t={pid:process.pid,host:Rk(),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=dh(e.SLACK_TERM_AGENT_PID)??dh(e.CLAUDE_PID);if(!s||!n){let i=Ok();if(i)s??=i.pid,n??=So[i.comm]}if(n)t.cli=n;if(s)t.agentPid=s;let r=e.SLACK_TERM_AGENT_SESSION||e.CLAUDE_CODE_SESSION_ID;if(r)t.sessionId=r;let o=Ik(t.cwd);if(o)t.gitBranch=o;return t}function Rk(){try{return Ck()}catch{return""}}function Ik(e){try{let t=bc("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var vk="slack_term_sent";function gh(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:vk,event_payload:n}}function Tt(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return Tk(process.env.HOME||$k(),".config","slack-cli","sent.sqlite")}function Pk(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=ms("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 Lk=`
|
|
395
395
|
CREATE TABLE IF NOT EXISTS sent (
|
|
396
396
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
397
397
|
kind TEXT NOT NULL,
|
|
@@ -423,167 +423,170 @@ CREATE TABLE IF NOT EXISTS sent (
|
|
|
423
423
|
);
|
|
424
424
|
CREATE INDEX IF NOT EXISTS sent_msg ON sent(channel, ts);
|
|
425
425
|
CREATE INDEX IF NOT EXISTS sent_at ON sent(sent_at);
|
|
426
|
-
`;function
|
|
427
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.kind,e.team??null,e.channel,e.target??null,e.ts,e.threadTs??null,e.permalink??null,e.text,Date.now(),n.pid,n.agentPid??null,n.host||null,n.cwd,n.gitBranch??null,n.cli??null,n.sessionId??null,e.asBot?1:0,process.env.SLACK_TERM_IDENTITY||null),!0}catch(n){return console.error(` (could not record to the sent log: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var
|
|
426
|
+
`;function Eo(){let e=Tt();try{Ek(Ak(e),{recursive:!0})}catch{}let t=Pk(e);if(!t)return;try{_k(e,384)}catch{}try{t.exec(Lk);for(let n of["delivered_answer TEXT","delivered_cursor TEXT","pushed_at INTEGER","pushed_answer TEXT","identity TEXT"])try{t.exec(`ALTER TABLE sent ADD COLUMN ${n}`)}catch{}return t}catch{try{t.close()}catch{}return}}function mh(e){if(!_o())return!1;let t=Eo();if(!t)return console.error(` (could not record to the sent log: ${Gs} — ${Tt()})`),!1;try{let n=e.attribution;return t.prepare(`INSERT INTO sent (kind, team, channel, target, ts, thread_ts, permalink, text, sent_at, pid, agent_pid, host, cwd, git_branch, cli, session_id, as_bot, identity)
|
|
427
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.kind,e.team??null,e.channel,e.target??null,e.ts,e.threadTs??null,e.permalink??null,e.text,Date.now(),n.pid,n.agentPid??null,n.host||null,n.cwd,n.gitBranch??null,n.cli??null,n.sessionId??null,e.asBot?1:0,process.env.SLACK_TERM_IDENTITY||null),!0}catch(n){return console.error(` (could not record to the sent log: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var Gs="cannot open the sent log: this runtime has no SQLite (needs bun, or node >= 22.5 for node:sqlite)";function wc(e){let t=Eo();if(!t)return;try{let n=[],s=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),s.push(`%${yc(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(`${yc(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),s.push(`${yc(e.cwd)}%`);if(e.kind)n.push("kind = ?"),s.push(e.kind);let r=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return s.push(e.limit??50),t.prepare(r).all(...s)}finally{try{t.close()}catch{}}}function yc(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function is(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let r={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*r}let s=Date.parse(e);return Number.isNaN(s)?void 0:s}function Xs(e,...t){if(!_o()||!fh(Tt()))return;let n=Eo();if(!n)return;try{n.prepare(e).run(...t)}catch{}finally{try{n.close()}catch{}}}function kc(e,t,n,s){let r=Date.now();Xs(`UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer = ?, answer_exit = 0,
|
|
428
428
|
delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
|
|
429
|
-
WHERE kind = 'ask' AND channel = ? AND ts = ?`,r,n,r,n,s,e,t)}function Dc(e,t,n,s){
|
|
430
|
-
WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,s,e,t)}function yh(e,t,n){
|
|
429
|
+
WHERE kind = 'ask' AND channel = ? AND ts = ?`,r,n,r,n,s,e,t)}function Dc(e,t,n,s){Xs(`UPDATE sent SET delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
|
|
430
|
+
WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,s,e,t)}function yh(e,t,n){Xs("UPDATE sent SET pushed_at = ?, pushed_answer = ? WHERE kind = 'ask' AND channel = ? AND ts = ?",Date.now(),n,e,t)}function bh(e,t,n){Xs("UPDATE sent SET identity = ? WHERE kind = 'ask' AND channel = ? AND ts = ?",n,e,t)}function $o(e,t,n){Xs("UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer_exit = ? WHERE kind = 'ask' AND channel = ? AND ts = ?",Date.now(),n,e,t)}function xc(e){if(!fh(Tt()))return[];let t=Eo();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 wh(e){let t=e.agent_pid??e.pid;if(!Nk(t))return!1;try{let s=(bc("ps",["-o","lstart=,comm=","-p",String(t)],{encoding:"utf8",timeout:2000}).stdout??"").trim(),r=Date.parse(s.slice(0,24));if(!Number.isNaN(r)&&r>e.sent_at+1000)return!1;let o=ph(s.slice(24).trim()),i=new Set(Object.values(So));if(e.cli&&i.has(e.cli)&&o&&So[o]!==e.cli)return!1}catch{}return!0}function Nk(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}class rt 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 Ec(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}var xh=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();function $c(e){xh=e}async function Sh(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof rt)||n+s.retryAfter>xh)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function _h(e,t,n,s){return Sh(()=>Mk(e,t,n,s))}async function Mk(e,t,n,s){s=e.startsWith("xoxc-")?s??Zt():void 0;let r={};if(s)r.Cookie=`d=${s}`;let o=await fetch(`${Ec()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(o.status===429){let l=parseInt(o.headers.get("retry-after")??"60",10);throw new rt(isNaN(l)?60:l,t)}let i=await o.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new rt(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.
|
|
431
431
|
Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
|
|
432
432
|
Or replace the token with an xoxp- user token:
|
|
433
433
|
slack auth login`);if((l==="missing_scope"||l==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${l}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${l} — ${l==="cannot_dm_bot"?`you're authenticated as a bot, so "@you" is the bot itself and it can't DM itself`:"this bot token lacks the user scope this action needs"}.
|
|
434
434
|
Tailing/DMing people and listing users need a user session, not a bot token.
|
|
435
435
|
Switch workspace: slack auth ls then slack auth use <name>
|
|
436
|
-
Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${l}`)}return i}function
|
|
436
|
+
Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${l}`)}return i}function Bk(e,t,n,s){return Sh(()=>jk(e,t,n,s))}async function jk(e,t,n,s){let r={};if(s)r.Cookie=`d=${s}`;let o=await fetch(`${Ec()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...r}});if(o.status===429){let l=parseInt(o.headers.get("retry-after")??"60",10);throw new rt(isNaN(l)?60:l,t)}let i=await o.json();if(i.ok!==!0){let l=i.error??"unknown";if(l==="ratelimited")throw new rt(60,t);if((l==="invalid_auth"||l==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
|
|
437
437
|
Import from Slack desktop: slack auth login`);if((l==="invalid_auth"||l==="not_authed")&&!s)throw Error(`${t} also requires the xoxd session cookie.
|
|
438
|
-
Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${l}`)}return i}function xt(e,t,n={},s){let r=new URLSearchParams({token:e,...n});return
|
|
438
|
+
Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${l}`)}return i}function xt(e,t,n={},s){let r=new URLSearchParams({token:e,...n});return Bk(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString()},s)}function ke(e,t,n,s){let r=new URLSearchParams(n).toString();return _h(e,`${t}?${r}`,{method:"GET"},s)}function Oe(e,t,n,s){return _h(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function Cc(e,t){let n=await ke(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Mt(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(`${Ec()}/auth.test`,{method:"GET",headers:n});if(s.status===429){let i=parseInt(s.headers.get("retry-after")??"60",10);throw new rt(isNaN(i)?60:i,"auth.test")}let r=s.headers.get("x-oauth-scopes")??"",o=await s.json();if(o.ok!==!0)throw Error(`Slack error on auth.test: ${o.error??"unknown"}`);return{userId:o.user_id??"",user:o.user??"",botId:o.bot_id??"",team:o.team??"",url:o.url??"",scopes:r.split(",").map((i)=>i.trim()).filter(Boolean)}}async function Eh(e,t,n){let s=await ke(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function ot(e,t,n=20,s,r,o,i){let l={channel:t,limit:String(n)};if(s!==void 0)l.oldest=s;if(r!==void 0)l.cursor=r;if(i)l.inclusive="true";return Co(await ke(e,"conversations.history",l,o))}function Co(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)vr(s);return e}async function Pe(e,t,n,s=50,r){return Co(await ke(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},r))}async function Ac(e,t,n,s={},r){let o={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)o.oldest=s.oldest;if(s.cursor!==void 0)o.cursor=s.cursor;return Co(await ke(e,"conversations.replies",o,r))}async function $h(e,t,n){return ke(e,"files.info",{file:t},n)}async function Ch(e,t={},n){let s={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)s.types=t.types;if(t.channel)s.channel=t.channel;if(t.user)s.user=t.user;return ke(e,"files.list",s,n)}async function Ah(e,t,n,s){let r={name:t,schema:n};if(s)r.todo_mode=!0;return await Oe(e,"slackLists.create",r)}async function Tc(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 Th(e,t,n){return await Oe(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function Fh(e,t,n,s){let r={list_id:t,access_level:n};if(s.userIds?.length)r.user_ids=s.userIds;if(s.channelIds?.length)r.channel_ids=s.channelIds;return await Oe(e,"slackLists.access.set",r)}async function Oh(e,t,n){return await Oe(e,"slackLists.items.update",{list_id:t,cells:n})}async function Rh(e,t,n={},s){let r={list_id:t};if(n.limit)r.limit=String(n.limit);if(n.cursor)r.cursor=n.cursor;return xt(e,"lists.records.list",r,s)}async function Ih(e,t,n,s,r){return Co(await ke(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(s,1))},r))}async function vh(e,t,n){return Ih(e,t,100,1,n)}async function Fc(e,t,n,s){let o=1,i=[],l={ok:!0,messages:{}};while(!0){let a=await Ih(e,t,100,o,s),c=Vs(a,["messages","matches"]),d=Array.isArray(c)?c:[];i.push(...d);let f=Number(Vs(a,["messages","paging","pages"])??1);if(l=a,d.length===0||o>=f||i.length>=n)break;o+=1}let u=l;if(!u.messages)u.messages={};return u.messages.matches=i.slice(0,n),u}async function Bt(e,t,n,s,r,o,i,l){let u=i?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(s!==void 0)u.thread_ts=s;if(r&&s!==void 0)u.reply_broadcast=!0;return(await Ph(e,"chat.postMessage",u,l,o)).ts??""}function Wk(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function Ph(e,t,n,s,r){if(!s)return Oe(e,t,n,r);try{return await Oe(e,t,{...n,metadata:s},r)}catch(o){if(!Wk(o))throw o;return Oe(e,t,n,r)}}async function Lh(e,t,n,s,r,o){let i={channel:t,text:n,post_at:s,blocks:[{type:"markdown",text:n}]};if(r!==void 0)i.thread_ts=r;return(await Oe(e,"chat.scheduleMessage",i,o)).scheduled_message_id??""}async function Nh(e,t,n){let s={};if(t)s.channel=t;return ke(e,"chat.scheduledMessages.list",s,n)}async function Mh(e,t,n,s){await Oe(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},s)}async function Ln(e,t,n,s){return(await ke(e,"chat.getPermalink",{channel:t,message_ts:n},s)).permalink??""}async function jt(e,t,n,s,r,o,i){return(await Ph(e,"chat.update",o?{channel:t,ts:n,text:s}:{channel:t,ts:n,text:s,blocks:[{type:"markdown",text:s}]},i,r)).ts??n}async function Bh(e,t,n,s){await Oe(e,"chat.delete",{channel:t,ts:n},s)}async function jh(e,t,n,s,r=200,o){let i={channel:t,ts:n,limit:String(r)};if(s!==void 0)i.cursor=s;return ke(e,"conversations.replies",i,o)}async function Oc(e,t,n,s){await Oe(e,"pins.add",{channel:t,timestamp:n},s)}async function Ft(e,t,n,s,r){await Oe(e,"reactions.add",{channel:t,timestamp:n,name:s},r)}async function Wh(e,t,n,s){return((await ke(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((o)=>({name:String(o.name??""),users:Array.isArray(o.users)?o.users.map(String):[]}))}async function Wt(e,t,n,s,r){await Oe(e,"reactions.remove",{channel:t,timestamp:n,name:s},r)}async function Uh(e,t,n=!1,s){let r=await Oe(e,"conversations.create",{name:t,is_private:n},s);return{id:r.channel?.id??"",name:r.channel?.name??t}}async function Jh(e,t,n,s){let r=await Oe(e,"conversations.rename",{channel:t,name:n},s);return{id:r.channel?.id??t,name:r.channel?.name??n}}async function Rc(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 r={limit:"200",types:"public_channel,private_channel,im,mpim"};if(s)r.cursor=s;let o=await ke(e,"conversations.list",r,t);if(n.push(...o.channels??[]),s=o.response_metadata?.next_cursor??"",!s)break}return{channels:n}}async function Ut(e,t,n){let r=(await Oe(e,"conversations.open",{users:t},n)).channel?.id;if(!r)throw Error(`Failed to open DM with user ${t}`);return r}async function Kh(e,t,n){let s="";while(!0){let r={types:"im",limit:"200"};if(s)r.cursor=s;let o=await ke(e,"conversations.list",r,n);for(let i of o.channels??[])if(i.user===t)return String(i.id??"");if(s=o.response_metadata?.next_cursor??"",!s)break}return""}async function Sc(e,t,n,s){let r=await Kh(e,t,n);if(r)return r;let o=s?`${s} (${t})`:t;throw Error(`No existing DM with ${o}. Open it once in Slack first.`)}function Pn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function kh(e,t){let n=Pn(e.name??""),s=Pn(e.real_name??e.profile?.real_name??""),r=Pn(e.profile?.display_name??"");return n===t||s===t||!!r&&r===t}var qh=200;async function Hh(e,t,n){let s=0,r=new Set,o="";while(!0){let c={limit:"200"};if(o)c.cursor=o;let d=await ke(e,"users.list",c,n);for(let f of d.members??[]){if(s++,f.id)r.add(f.id);if(kh(f,t))return{id:f.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(o=d.response_metadata?.next_cursor??"",!o)break}let i=0,l=0,u=!1,a="";while(!0){let c={types:"im",limit:"200"};if(a)c.cursor=a;let d=await ke(e,"conversations.list",c,n);for(let f of d.channels??[]){let p=f.user;if(!p||r.has(p))continue;if(i>=qh){u=!0;break}r.add(p),i++;let g;try{g=(await ke(e,"users.info",{user:p},n)).user}catch(h){if(h instanceof rt)throw h;l++;continue}if(g&&kh(g,t))return{id:p,dm:String(f.id??""),workspaceCount:s,connectCount:i,skipped:l,capped:u}}if(u)break;if(a=d.response_metadata?.next_cursor??"",!a)break}return{id:"",workspaceCount:s,connectCount:i,skipped:l,capped:u}}function zh(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
|
|
439
439
|
`+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
|
|
440
440
|
Check who you are: slack auth ls`);let n=t.connectCount?`${t.workspaceCount} workspace account(s) and ${t.connectCount} Slack Connect DM partner(s)`:`${t.workspaceCount} workspace account(s)`,s=[];if(t.capped)s.push(`stopped after ${qh} Slack Connect DM partners, so there may be more`);if(t.skipped)s.push(`${t.skipped} DM partner profile(s) could not be read and were never compared`);return Error(`User not found: ${e} — searched ${n}, none matched.
|
|
441
441
|
`+(s.length?`This search was incomplete: ${s.join("; ")}.
|
|
442
442
|
`:"")+`Slack Connect people from another workspace are not in users.list, so if they never
|
|
443
443
|
DMed you they cannot be found by name at all. Look them up and use their ID:
|
|
444
|
-
slack user ls --external`)}async function Ot(e,t,n){let s=t.startsWith("@")?t.slice(1):t;if(
|
|
445
|
-
`)}catch{}}function cg(e,t){return e?`${e} ${t}`:void 0}function
|
|
446
|
-
`)[0]??"",emoji:w,keep:w[0]})}if(c=p.response_metadata?.next_cursor||void 0,!c||g.length===0)break;if(a>=r){d=!0;break}}if(s.fix)for(let f of u)try{try{await Ve("reactions.add",()=>
|
|
447
|
-
`;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function
|
|
448
|
-
`)}function
|
|
444
|
+
slack user ls --external`)}async function Ot(e,t,n){let s=t.startsWith("@")?t.slice(1):t;if(_c(s))return s;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let r=Pn(s),o=await ke(e,"auth.test",{},n);if(r==="you"||r==="me"||Pn(o.user??"")===r){if(!o.user_id)throw Error("auth.test did not return user_id");return o.user_id}let i=await Hh(e,r,n);if(i.id)return i.id;throw zh(t,i)}function ft(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,r=e.indexOf("?"),o=r>=0?new URLSearchParams(e.slice(r)):void 0,i=o?.get("thread_ts")??void 0,a={channel:o?.get("cid")??void 0??n};if(s)a.ts=s;if(i)a.threadTs=i;return a}function Uk(e){return ft(e)?.channel}function Dh(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function _c(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function we(e,t,n){let s=Uk(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(Dh(t))return t;if(_c(t))return Sc(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Dh(t.slice(1)))return t.slice(1);let r=t.startsWith("@"),o=t.slice(1),i=Pn(o);if(r){if(_c(o))return Sc(e,o,n);let a=await ke(e,"auth.test",{},n);if(i==="you"||i==="me"||Pn(a.user??"")===i){let f=a.user_id;if(!f)throw Error("auth.test did not return user_id");return await Kh(e,f,n)||Ut(e,f,n)}let d=await Hh(e,i,n);if(!d.id)throw zh(t,d);if(d.dm)return d.dm;return Sc(e,d.id,n,t)}let l=o.toLowerCase(),u="";while(!0){let a={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(u)a.cursor=u;let c=await ke(e,"conversations.list",a,n);for(let d of c.channels??[])if(String(d.name??"").toLowerCase()===l)return String(d.id??"");if(u=c.response_metadata?.next_cursor??"",!u)break}throw Error(`channel not found: ${t}`)}async function Qs(e,t,n){try{let s=await ke(e,"users.info",{user:t},n),r=s.user?.profile?.display_name,o=r&&r.length>0?r:s.user?.real_name??s.user?.name??t,i=s.user?.name??t;return[o,i]}catch{return[t,t]}}async function Re(e,t,n){try{let s=await ke(e,"users.info",{user:t},n),r=s.user?.profile?.display_name;if(r&&r.length>0)return r;return s.user?.real_name??s.user?.name??t}catch{return t}}async function Yh(e,t){let n=[],s="";while(!0){let r={limit:"200"};if(s)r.cursor=s;let o=await ke(e,"users.list",r,t);if(n.push(...o.members??[]),s=o.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function Gh(e,t,n){let s=[],r="";while(!0){let o={channel:t,limit:"200"};if(r)o.cursor=r;let i=await ke(e,"conversations.members",o,n);if(s.push(...i.members??[]),r=i.response_metadata?.next_cursor??"",!r)break}return s}async function Ic(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 xt(e,"saved.list",s,n)}var vc=(e)=>({item_type:"message",item_id:e.channel,ts:e.ts});async function Xh(e,t,n={},s){let r={...vc(t),todo_state:n.todo===!1?"saved":"to_do"};if(n.due)r.date_due=String(n.due);return xt(e,"saved.add",r,s)}async function Pc(e,t,n,s){let r=vc(t);if(n.mark)r.mark=n.mark;if(n.todo!==void 0)r.todo_state=n.todo?"to_do":"saved";if(n.due!==void 0)r.date_due=String(n.due);return xt(e,"saved.update",r,s)}async function Vh(e,t,n){return xt(e,"saved.delete",vc(t),n)}async function er(e,t){return xt(e,"drafts.list",{},t)}async function Zh(e,t,n,s){let{randomUUID:r}=await import("node:crypto"),o=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Ir(n)}]}]);return xt(e,"drafts.create",{client_msg_id:r(),destinations:JSON.stringify([{channel_id:t}]),blocks:o,file_ids:JSON.stringify([]),is_from_composer:"true"},s)}async function Qh(e,t,n,s,r){let o=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Ir(s)}]}]),i=(Date.now()/1000).toFixed(6);return xt(e,"drafts.update",{draft_id:t,client_last_updated_ts:i,destinations:JSON.stringify([{channel_id:n}]),blocks:o,file_ids:JSON.stringify([])},r)}async function eg(e,t,n){return xt(e,"conversations.info",{channel:t},n)}async function as(e,t,n){return ke(e,"users.info",{user:t},n)}async function tg(e,t,n){try{let s=await ke(e,"users.info",{user:t,include_locale:"true"},n);return typeof s.user?.locale==="string"?s.user.locale:void 0}catch{return}}async function Nn(e,t,n){return ke(e,"conversations.info",{channel:t},n)}async function ng(e,t,n){let s=(Date.now()/1000).toFixed(6);return xt(e,"drafts.delete",{draft_id:t,client_last_updated_ts:s},n)}async function Lc(e,t){let n=await xt(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function sg(e,t,n,s={},r){let{statSync:o,readFileSync:i}=await import("node:fs"),{basename:l}=await import("node:path"),u=o(n),a=l(n),c=await ke(e,"files.getUploadURLExternal",{filename:a,length:String(u.size)},r),{upload_url:d,file_id:f}=c;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??a}],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,r),y={fileId:f},w=m.files?.[0]?.permalink;if(w)y.permalink=w;return y}function Vs(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 og=["todo","saved","completed","archived"],tr=(e)=>typeof e==="string"?e:"",rg=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function Nc(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:tr(s.item_id),ts:tr(s.ts),due:rg(s.date_due),completed:rg(s.date_completed),todoState:tr(s.todo_state),state:tr(s.state),archived:s.is_archived===!0,itemType:tr(s.item_type)}))}function ig(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 nr(e){return e.completed>0||e.state==="completed"||e.todoState==="completed"}function Mc(e,t,n){let s=nr(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${s} no due date`;let r=!nr(e)&&e.due<t?" OVERDUE":"";return`${s} due ${n(e.due)}${r}`}function Bc(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as Zk,readFileSync as Qk}from"node:fs";import{homedir as eD}from"node:os";import{join as tD}from"node:path";import{existsSync as Jk,mkdirSync as Kk,readFileSync as qk,writeFileSync as Hk}from"node:fs";import{homedir as zk}from"node:os";import{dirname as Yk,join as Gk}from"node:path";var Xk=3600000,Ao={now:()=>Date.now(),path:()=>Gk(process.env.HOME||zk(),".config","slack-cli","cache.json")},To=!0,an;function ag(){return{channels:{},users:{}}}function jc(){if(an)return an;if(an=ag(),!To)return an;try{let e=Ao.path();if(!Jk(e))return an;let t=JSON.parse(qk(e,"utf8"));for(let n of["channels","users"]){let s=t?.[n];if(!s||typeof s!=="object"||Array.isArray(s))continue;for(let[r,o]of Object.entries(s))if(o&&typeof o==="object"&&typeof o.value==="string"&&typeof o.expires==="number")an[n][r]={value:o.value,expires:o.expires}}}catch{an=ag()}return an}function Vk(e){if(!To)return;try{let t=Ao.path();Kk(Yk(t),{recursive:!0}),Hk(t,JSON.stringify(e,null,2)+`
|
|
445
|
+
`)}catch{}}function cg(e,t){return e?`${e} ${t}`:void 0}function Fo(e,t,n){if(!To)return;let s=cg(t,n);if(!s)return;let r=jc()[e][s];if(!r)return;if(r.expires<=Ao.now()){delete jc()[e][s];return}return r.value}function Oo(e,t,n,s,r=Xk){if(!To)return;let o=cg(t,n);if(!o)return;let i=jc();i[e][o]={value:s,expires:Ao.now()+r},Vk(i)}var Wc={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"}},cs=["done","dropped","doing","pending"],fg=["alert","needs-discussion","waiting","blocked"];function nD(){return tD(process.env.HOME||eD(),".config","slack-cli","todo.json")}function Ro(e){return e.replace(/^:+|:+$/g,"")}function sr(e=nD()){let t={marker:Wc.marker,progress:{...Wc.progress},flags:{...Wc.flags}};try{if(!Zk(e))return t;let n=JSON.parse(Qk(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=Ro(n.marker.trim());for(let s of cs){let r=n.progress?.[s];if(typeof r==="string"&&r.trim())t.progress[s]=Ro(r.trim())}for(let s of fg){let r=n.flags?.[s];if(typeof r==="string"&&r.trim())t.flags[s]=Ro(r.trim())}}catch{}return t}function lg(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${Ro(e)}:`}function pg(e,t,n={}){let s=n.shared===!0,r=(l)=>lg(l,s),o=(l)=>lg(l,s,!0),i=[];if(e==="untriaged")i.push(r(t.marker),...cs.map((l)=>o(t.progress[l])));else if(e==="stuck")i.push(r(t.marker),o(t.progress.done),o(t.progress.dropped),`(${fg.map((l)=>r(t.flags[l])).join(" OR ")})`);else if(e==="open")i.push(r(t.marker),o(t.progress.done),o(t.progress.dropped));else{let l=cs.indexOf(e);i.push(r(t.progress[e]));for(let u of cs.slice(0,l))i.push(o(t.progress[u]))}if(n.in){let l=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;i.push(`in:${l}`)}if(n.from){let l=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;i.push(`from:${l}`)}return i.join(" ")}var sD=3,rD={sleep:(e)=>oD()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function oD(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Ve(e,t,n=sD){for(let s=0;;s++)try{return await t()}catch(r){if(!(r instanceof qe))throw r;if(s>=n)throw Error(`Slack rate limit hit on ${e} — gave up after ${n} retries. Try again in a minute.`);console.error(`Warning: Slack rate limit hit on ${e} — backing off for ${r.retryAfter}s`),await rD.sleep(r.retryAfter*1000)}}var ug=new Map;async function hg(e,t){let n=ug.get(e);if(n)return n;let s=await Ve("auth.test",()=>Zn(e,t)),r={userId:s.userId,teamId:s.teamId};return ug.set(e,r),r}async function gg(e,t){return(await hg(e,t)).userId}async function Uc(e,t){try{return(await hg(e,t)).teamId}catch{return""}}async function Jc(e,t,n,s){if(!t.startsWith("#"))return n(e,t,s);let r=await Uc(e,s),o=Fo("channels",r,t);if(o)return o;let i=await Ve("resolveChannel",()=>n(e,t,s));return Oo("channels",r,t,i),i}async function mg(e,t,n,s){let r=await Uc(e,s),o=Fo("users",r,t);if(o)return o;let i=await Ve("users.info",()=>n(e,t,s));if(i&&i!==t)Oo("users",r,t,i);return i}async function yg(e,t,n,s){let r=await Uc(e,s),o=Fo("users",r,`tz:${t}`);if(o)return o==="?"?null:o;let i=null;try{let l=await Ve("users.info",()=>n(e,t,s));if(l?.user?.is_bot===!0||t==="USLACKBOT")return dg(r,t,null);let u=l?.user?.tz;i=typeof u==="string"&&u?u:null}catch{return null}return dg(r,t,i)}function dg(e,t,n){return Oo("users",e,`tz:${t}`,n??"?"),n}async function bg(e,t,n,s,r,o){let i=r.progress[s],l=await gg(e,o),u=await Ve("reactions.get",()=>$d(e,t,n,o)),a=new Set(u.filter((p)=>p.users.includes(l)).map((p)=>p.name)),c=cs.map((p)=>r.progress[p]).filter((p)=>a.has(p));if(c.length===1&&c[0]===i)return{noop:!0,removed:[],leftover:[]};if(!a.has(i))await Ve("reactions.add",()=>Pr(e,t,n,i,o));let d=[],f=[];for(let p of c){if(p===i)continue;try{await Ve("reactions.remove",()=>Lr(e,t,n,p,o)),d.push(p)}catch{f.push(p)}}return{noop:!1,added:s,removed:d,leftover:f}}async function wg(e,t,n,s,r,o,i){let l=r.flags[s];if(o)await Ve("reactions.remove",()=>Lr(e,t,n,l,i));else await Ve("reactions.add",()=>Pr(e,t,n,l,i));return l}var Kc=1000;async function kg(e,t,n,s={}){let r=s.limit??Kc,o=s.cookie,i=await gg(e,o),l=cs.map((f)=>n.progress[f]),u=[],a=0,c,d=!1;while(a<r){let f=Math.min(200,r-a),p=await Ve("conversations.history",()=>Tn(e,t,f,void 0,c,o)),g=p.messages??[];a+=g.length;for(let h of g){let m=String(h.ts??"");if(!m)continue;let y=new Set((h.reactions??[]).filter((D)=>(D.users??[]).map(String).includes(i)).map((D)=>String(D.name??""))),w=l.filter((D)=>y.has(D));if(w.length<2)continue;u.push({ts:m,text:String(h.text??"").split(`
|
|
446
|
+
`)[0]??"",emoji:w,keep:w[0]})}if(c=p.response_metadata?.next_cursor||void 0,!c||g.length===0)break;if(a>=r){d=!0;break}}if(s.fix)for(let f of u)try{try{await Ve("reactions.add",()=>Pr(e,t,f.ts,f.keep,o))}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",()=>Lr(e,t,f.ts,p,o))}f.fixed=!0}catch(p){f.fixed=!1,f.error=p instanceof Error?p.message:String(p)}return{scanned:a,findings:u,truncated:d}}var iD=!0,aD;function qc(e){if(iD=e,!e)aD=void 0}function je(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
|
|
447
|
+
`;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function ls(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var us=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},We=(e)=>typeof e==="string"?e:"";function cD(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>We(us(us(n).message).text)).filter(Boolean).join(`
|
|
448
|
+
`)}function Hc(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(us).map((n)=>{let s=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),r=us(us((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(us(r.message).user)||null,author_name:We(n.author_name)||null,channel_id:We(n.channel_id)||We(r.channel)||null,ts:We(n.ts)||We(r.ts)||null,title:We(n.title)||null,text:We(n.text)||cD(n)||We(n.pretext)||We(n.fallback),permalink:We(n.from_url)||We(n.title_link)||We(n.original_url)||null}})}function Dg(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let s=n.author_name??n.author_id,r=n.shared?`↪ shared message${s?` from @${s}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,o=n.text?n.text.replace(/\n+$/,"").split(`
|
|
449
449
|
`).map((l)=>`
|
|
450
450
|
│ ${l}`).join(""):"",i=n.permalink?`
|
|
451
451
|
${n.permalink}`:"";return`
|
|
452
|
-
${r}${o}${i}`}).join("")}var xg=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"]),
|
|
453
|
-
`)}function
|
|
454
|
-
`)),o=await ln(e,t,n,s.cookie);for(let i of
|
|
455
|
-
⚠ QUIET HOURS (${o}:00-${i}:00) — this will buzz a phone.${s?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function
|
|
452
|
+
${r}${o}${i}`}).join("")}var xg=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"]),lD={channels:"channel",ch:"channel"};function zc(e){let[t="",n=""]=e.map(String),s=lD[t]??t;return xg.has(s)||xg.has(`${s} ${n}`)}function Yc(e,t){return String(e[0]??"")==="ask"&&(t.ls===!0||t.pending===!0&&t.push!==!0)}function Sg(e,t,n){let s=n.botTokenSource;if(!s||n.globalPaths.includes(s))return null;if(n.slackTokenSet||n.activeTokenIsBot)return null;if(!zc(e)||Yc(e,t)||t["as-bot"]===!0)return null;let r=s==="shell"?"exported in the environment":`set in ${s}`,o="as-bot"in t;return[`Error: refusing to act as YOU — SLACK_BOT_TOKEN is ${r}, but \`${e.slice(0,2).join(" ")}\` would use your user session, not the bot.`,o?" As the app: add --as-bot":" This command has no --as-bot: it can only act as a user."," As yourself: set SLACK_TOKEN, or clear the bot token for this run (SLACK_BOT_TOKEN= slack ...)"].join(`
|
|
453
|
+
`)}function Mn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function cn(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function uD(e,t){let n=Mn(t),s=cn(e.profile);for(let o of[e.name,e.real_name,s.display_name,s.real_name])if(typeof o==="string"&&o&&Mn(o)===n)return!0;let r=typeof s.email==="string"?s.email.toLowerCase():"";return r!==""&&r===t.toLowerCase()}function dD(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 r=Mn(s);if(r.length>=2)n.add(r)}return[...n]}function fD(e,t){let n=Mn(e),s,r=!1;for(let o of t){let i=typeof o.id==="string"?o.id:"";if(!i)continue;for(let l of dD(o)){let u=-1;if(n===l)u=e.length;else for(let a of Eg)if(e.length>a.length&&e.endsWith(a)&&Mn(e.slice(0,e.length-a.length))===l){u=e.length-a.length;break}if(u<0)continue;if(!s||l.length>s.formLen)s={userId:i,matchLen:u,formLen:l.length,display:Vc(o)},r=!1;else if(l.length===s.formLen&&s.userId!==i)r=!0}}if(!s)return;return r?"ambiguous":{userId:s.userId,matchLen:s.matchLen,display:s.display}}async function ln(e,t,n,s){let r=`[${$g}ー]+`,o=`${r}(?:[._-]+${r})*`,i=new RegExp(`(?<![A-Za-z0-9._@<-])@(${o})`,"gu"),l=new Set;for(let w of t.matchAll(i))l.add(w[1]);if(l.size===0)return{text:t,resolved:[],unresolved:[]};let u=new Map;for(let w of l)u.set(w,{status:"pending"});let a=(w)=>{for(let D of l){if(u.get(D).status!=="pending")continue;if(Xc(D)){let k=fD(D,w);if(k==="ambiguous")u.set(D,{status:"ambiguous"});else if(k)u.set(D,{status:"resolved",userId:k.userId,matchLen:k.matchLen,display:k.display})}else{let k=w.filter((E)=>uD(E,D)),_=new Set(k.map((E)=>typeof E.id==="string"?E.id:"").filter(Boolean));if(_.size===1){let E=k.find((S)=>typeof S.id==="string");u.set(D,{status:"resolved",userId:E.id,matchLen:D.length,display:Vc(E)})}else if(_.size>1)u.set(D,{status:"ambiguous"})}}},c=!1;try{let w=await Br(e,s);a((w.members??[]).map(cn)),c=!0}catch{c=!1}let d=[...l].some((w)=>u.get(w).status==="pending"),f=!1,p=!0;if(d&&n){f=!0;try{let w=await na(e,n,s),D=[];for(let k of w){let _=cn(await sa(e,k,s)),E=cn(_.user);if(typeof E.id!=="string")E.id=k;D.push(E)}a(D)}catch{p=!1}}let g=c&&(n?f&&p:!0),h=[],m=[];for(let w of l){let D=u.get(w);if(D.status==="resolved")h.push({surface:`@${w.slice(0,D.matchLen)}`,display:D.display,userId:D.userId});else if(D.status==="ambiguous")m.push({surface:`@${w}`,reason:"ambiguous"});else m.push({surface:`@${w}`,reason:g?"no-match":"unavailable"})}return{text:t.replace(i,(w,D)=>{let k=u.get(D);if(k&&k.status==="resolved")return`<@${k.userId}>${D.slice(k.matchLen)}`;return w}),resolved:h,unresolved:m}}function Io(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 _g(e,t,n,s={}){let r=s.warn??((i)=>process.stderr.write(`${i}
|
|
454
|
+
`)),o=await ln(e,t,n,s.cookie);for(let i of Io(o.unresolved))r(`warn: ${i}`);return o.text}var Eg=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],$g="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function Xc(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function pD(e){let t=[],n=new RegExp(`([${$g}]{1,12})(${Eg.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 hD(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 r of[s,...s.split(/\s+/)]){let o=Mn(r);if(o.length>=2)n.add(o)}}return[...n]}function gD(e,t){let n=Mn(e);if(n.length<2)return;for(let s of t)if(n===s)return s;if(Xc(e)){for(let s of t)if(n.includes(s)||s.includes(n))return s}return}function Vc(e){return[cn(e.profile).display_name,e.real_name,e.name].filter((s)=>typeof s==="string"&&s!=="")[0]??String(e.id??"?")}async function Cg(e,t,n){let s=pD(t);if(s.length===0)return[];let r=new Set;for(let a of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))r.add(a[1]);let i=((await Br(e,n)).members??[]).map(cn).filter((a)=>a.deleted!==!0&&a.is_bot!==!0&&a.id!=="USLACKBOT").map((a)=>({id:typeof a.id==="string"?a.id:"",forms:hD(a),display:Vc(a)})).filter((a)=>a.id!==""),l=[],u=new Set;for(let{ref:a,honorific:c}of s)for(let d of i){let f=gD(a,d.forms);if(!f)continue;if(r.has(d.id)||u.has(d.id))break;u.add(d.id),l.push({surface:Xc(a)?`${f}${c}`:a,display:d.display,userId:d.id});break}return l}async function Bn(e,t,n,s){let r=t,o=[],i=r,l=0;while(!0){let u=i.indexOf("<@U",l);if(u===-1)break;let a=i.slice(u+2),c=a.search(/[>|]/),d=c===-1?a:a.slice(0,c);if(d.length>=9)o.push(d);l=u+1}for(let u of o){if(!n.has(u))n.set(u,await Qn(e,u,s));let a=n.get(u)??u;r=r.replaceAll(`<@${u}>`,`@${a}`),r=r.replace(new RegExp(`<@${u}\\|[^>]*>`,"g"),`@${a}`)}return r}function ds(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let r=Number(n);if(!Number.isFinite(r))return s??"date";let o=new Date(r*1000);if(Number.isNaN(o.getTime()))return s??"date";let i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],l=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],u=i[o.getUTCDay()]??"",a=l[o.getUTCMonth()]??"";return`${u}, ${a} ${String(o.getUTCDate()).padStart(2,"0")}, ${o.getUTCFullYear()}`})}function Ag(e,t=new Date){let n=new Date(e*1000),s=Gc(t),r=Gc(new Date(t.getTime()-86400000)),o=Gc(n);if(o===s)return"Today";if(o===r)return"Yesterday";let i=n.toLocaleDateString("en-US",{weekday:"long"}),l=n.toLocaleDateString("en-US",{month:"short"});return`${i}, ${l} ${String(n.getDate()).padStart(2,"0")}`}function Gc(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function jn(e){let t=new Date(e*1000),n=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),r=String(t.getDate()).padStart(2,"0"),o=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${n}-${s}-${r} ${o}:${i}`}var mD=/[A-Za-z0-9_-]{32,}/g;function fs(e){return e.replace(mD,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function Zc(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",s=!!t&&yD(t),r=s?t:n,o=Number(process.env.SLACK_QUIET_START??23),i=Number(process.env.SLACK_QUIET_END??8),l,u;try{let p=new Intl.DateTimeFormat("en-GB",{timeZone:r,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});u=p.format(e),l=Number(p.formatToParts(e).find((g)=>g.type==="hour")?.value??"12")}catch{return null}let a=o>i?l>=o||l<i:l>=o&&l<i,c=s?`${r}, recipient`:`${r}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${u} (${c})`;if(!a)return d;return`${d}
|
|
455
|
+
⚠ QUIET HOURS (${o}:00-${i}:00) — this will buzz a phone.${s?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function yD(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as Tg}from"node:fs";import{isatty as Fg}from"node:tty";import{format as Og}from"node:util";var bD=new Int32Array(new SharedArrayBuffer(4)),wD=141;function Rg(e,t){let n=Buffer.from(t,"utf8"),s=0;while(s<n.length)try{s+=Tg(e,n,s,n.length-s)}catch(r){let o=r.code;if(o==="EAGAIN"||o==="EWOULDBLOCK"){Atomics.wait(bD,0,0,2);continue}if(o==="EPIPE")process.exit(wD);if(e!==2)try{Tg(2,`slack: cannot write output (${o??String(r)}); output is incomplete
|
|
456
456
|
`)}catch{}process.exit(1)}}function Ig(){if(!Fg(1))console.log=(...e)=>Rg(1,Og(...e)+`
|
|
457
457
|
`),console.info=console.log;if(!Fg(2))console.error=(...e)=>Rg(2,Og(...e)+`
|
|
458
|
-
`),console.warn=console.error}import{closeSync as vg,mkdirSync as
|
|
458
|
+
`),console.warn=console.error}import{closeSync as vg,mkdirSync as kD,openSync as Pg,readFileSync as ps,statSync as Lg,unlinkSync as vo,writeFileSync as Ng}from"node:fs";import{homedir as DD}from"node:os";import{join as Mg}from"node:path";var or="Pinlog · 最終更新";function Qc(e){let t=new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Tokyo",hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).formatToParts(e),n=(r)=>t.find((o)=>o.type===r)?.value??"??",s=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${s}:${n("minute")} JST`}function xD(e){return`_${or} ${Qc(e)} · 更新はスレッドに_`}var el=new RegExp(`(^|\\n+)_?${or} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function hs(e){return el.test(e)}function ir(e){return e.replace(el,"")}function tl(e,t){return`${ir(e).trimEnd()}
|
|
459
459
|
|
|
460
|
-
${
|
|
461
|
-
`,r;try{r=Pg(n,"wx"),Ng(r,s)}catch(o){if(o.code!=="EEXIST")throw o;try{let i=
|
|
462
|
-
`;for(let i=0;i<3;i++)try{let l=Pg(r,"wx");Ng(l,o),vg(l);let u=!0,a=()=>{if(!u)return;u=!1;try{if(
|
|
463
|
-
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(
|
|
464
|
-
`)}function
|
|
460
|
+
${xD(t)}`}function nl(e){let n=e.match(el)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class rr extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function SD(){return Mg(process.env.HOME||DD(),".config","slack-cli","locks")}function Bg(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 _D(e,t){let n=`${e}.break`,s=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
|
|
461
|
+
`,r;try{r=Pg(n,"wx"),Ng(r,s)}catch(o){if(o.code!=="EEXIST")throw o;try{let i=ps(n,"utf8");if((/^pid=\d+/.test(i)?!Bg(i):Date.now()-Lg(n).mtimeMs>1e4)&&ps(n,"utf8")===i)vo(n)}catch{}return}try{if(ps(e,"utf8")===t)vo(e)}catch{}finally{vg(r);try{if(ps(n,"utf8")===s)vo(n)}catch{}}}function jg(e,t={}){let n=t.dir??SD(),s=t.staleMs??120000;kD(n,{recursive:!0});let r=Mg(n,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.lock`),o=`pid=${process.pid} since=${new Date().toISOString()} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
|
|
462
|
+
`;for(let i=0;i<3;i++)try{let l=Pg(r,"wx");Ng(l,o),vg(l);let u=!0,a=()=>{if(!u)return;u=!1;try{if(ps(r,"utf8")===o)vo(r)}catch{}};return process.once("exit",a),a}catch(l){if(l.code!=="EEXIST")throw l;let u,a;try{u=ps(r,"utf8"),a=Date.now()-Lg(r).mtimeMs}catch{continue}if(/^pid=\d+/.test(u)?!Bg(u):a>s){_D(r,u);continue}throw new rr(u.trim().replace(/ nonce=\S+/,"")||"another process")}throw new rr("another process")}function pt(e,t){return`${e}:${t}`}function Po(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}var am=new Map,il=new Map,dl=[gt(jo(),".slack-cli",".env.local"),gt(jo(),".config/slack-cli",".env")];function Lo(e){if(!om(e))return;let t=ul(e,"utf8");for(let n of t.split(`
|
|
463
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let r=s.indexOf("=");if(r===-1)continue;let o=s.slice(0,r).trim(),i=s.slice(r+1).trim();if(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))i=i.slice(1,-1);if(dl.includes(e))il.set(o,[...il.get(o)??[],{path:e,val:i}]);if(!(o in process.env))process.env[o]=i,am.set(o,e)}}function FD(e){ED(e,{recursive:!0});let t=gt(e,".gitignore");if(!om(t))im(t,`*
|
|
464
|
+
`)}function OD(){for(let e of dl)Lo(e);Lo(gt(process.cwd(),".slack-cli",".env.local")),Lo(gt(process.cwd(),".env.local")),Lo(gt(process.cwd(),".env"))}function RD(e){return rm("sha256").update(e).digest("hex")}function F(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function z(e){return Array.isArray(e)?e:[]}function Wo(e){return Number(e.ts??0)}async function cm(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 al(e){let t=new Date(e*1000),n=t.getUTCFullYear(),s=String(t.getUTCMonth()+1).padStart(2,"0"),r=String(t.getUTCDate()).padStart(2,"0"),o=String(t.getUTCHours()).padStart(2,"0"),i=String(t.getUTCMinutes()).padStart(2,"0"),l=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${s}-${r} ${o}:${i}:${l}`}function Uo(e){let[t,n="000000"]=e.split("."),s=Number(t),r=new Date(s*1000),o=r.getUTCFullYear(),i=String(r.getUTCMonth()+1).padStart(2,"0"),l=String(r.getUTCDate()).padStart(2,"0"),u=String(r.getUTCHours()).padStart(2,"0"),a=String(r.getUTCMinutes()).padStart(2,"0"),c=String(r.getUTCSeconds()).padStart(2,"0"),d=n.padEnd(6,"0").slice(0,6);return`${o}-${i}-${l}T${u}:${a}:${c}.${d}`}function fl(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 sl(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?fl(e):e}async function Yo(e,t,n,s,r){let o=typeof t.ts==="string"?t.ts:`${Wo(t)}.000000`,i=Uo(o),l="?";if(typeof t.user==="string"){let D=t.user,k="@"+D;if(!n.has(k)){let _=await mg(e,D,async(E,S,x)=>(await Qs(E,S,x))[1],r);n.set(k,_)}l=n.get(k)??D}else if(typeof t.username==="string")l=t.username;let u=typeof t.text==="string"?t.text:"",c=ds(await Bn(e,u,n,r)).split(`
|
|
465
465
|
`),d=c[0]+(c.length>1?`
|
|
466
|
-
`+c.slice(1).map((
|
|
467
|
-
`):""),f=s?`${s} @${l}`:`@${l}`,p=
|
|
468
|
-
\uD83D\uDCCE ${
|
|
469
|
-
${p}`:"")+g+
|
|
470
|
-
`)[0]??"",f=await
|
|
471
|
-
`)[0]?.slice(0,60)}`:"";console.log(`${p}${c} ${a}${g}${m}`)}}function
|
|
466
|
+
`+c.slice(1).map((D)=>` ${D}`).join(`
|
|
467
|
+
`):""),f=s?`${s} @${l}`:`@${l}`,p=z(t.reactions).map(F).map((D)=>{let k=typeof D.name==="string"?D.name:"",_=Number(D.count??z(D.users).length??0);return k?`:${k}:\xD7${_}`:""}).filter(Boolean).join(" "),g=z(t.files).map(F).map((D)=>{let k=typeof D.name==="string"?D.name:typeof D.title==="string"?D.title:"(file)",_=typeof D.size==="number"?` (${Go(D.size)})`:"",E=typeof D.id==="string"?` [${D.id}]`:"";return`
|
|
468
|
+
\uD83D\uDCCE ${k}${_}${E}`}).join(""),h=Number(t.reply_count??0),m=h>0?` [+${h} ${h===1?"reply":"replies"}]`:"",y=await Promise.all(Hc(t).map(async(D)=>({...D,text:D.text?ds(await Bn(e,D.text,n,r)):""}))),w=(p?`
|
|
469
|
+
${p}`:"")+g+Dg(y,Uo);return`${i} ${f}: ${d}${m}${w}`}function Go(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function ID(e){return z(e.files).map(F).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 lm(e){let t=ID(e),n=Hc(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:z(e.reactions).map(F).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 vD(e,t,n,s,r){let o=[];for(let i of n){let l=i;if(Number(i.reply_count??0)>0&&typeof i.ts==="string"){let u=await Pe(e,t,i.ts,200,r),a=z(u.messages).map(F);l=a[a.length-1]??i}if(l.user!==s)o.push(i)}return o}async function Wg(e,t,n,s="text",r=!1,o){let i=ft(t),l=await we(e,t,o),u=new Map,c=await(async()=>{if(i?.threadTs){let f=await Pe(e,l,i.threadTs,n,o);return z(f.messages).map(F)}let d=await ot(e,l,n,void 0,void 0,o);return z(d.messages).map(F).reverse()})();if(r){let{userId:d}=await Cc(e,o);c=await vD(e,l,c,d,o)}if(s==="jsonl"){for(let d of c)console.log(JSON.stringify(lm(d)));return}for(let d of c)console.log(await Yo(e,d,u,void 0,o))}function PD(e){let t=(r)=>r.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"),n=typeof e.user==="string"?e.user:typeof e.bot_id==="string"?e.bot_id:"",s=Array.isArray(e.files)&&e.files.length?` [files: ${e.files.length}]`:"";return`${String(e.ts)} ${n} ${t(typeof e.text==="string"?e.text:"")}${s}`}async function LD(e,t,n,s){let r=[],o;for(let i=0;i<200;i++){let l=F(await Ac(e,t,n,o?{cursor:o}:{},s));for(let u of z(l.messages).map(F))if(!r.some((a)=>a.ts===u.ts))r.push(u);if(o=String(F(l.response_metadata).next_cursor??"")||void 0,!o)return r}throw Error("thread has more than 200 pages: refusing to return it partially")}async function Ug(e,t,n,s,r="text",o,i){let l=await we(e,t,o),a=i!==void 0||r==="tsv"?await LD(e,l,sl(n),o):z((await Pe(e,l,sl(n),s,o)).messages).map(F);if(i!==void 0){let d=Number(sl(i));if(!Number.isFinite(d))throw Error(`--since needs a message ts (1700000000.000100) or ISO stamp (got ${M(i)})`);a=a.filter((f)=>Number(f.ts)>d)}if(r==="tsv"){for(let d of a)console.log(PD(d));return}if(r==="jsonl"){for(let d of a)console.log(JSON.stringify(lm(d)));return}let c=new Map;for(let d of a)console.log(await Yo(e,d,c,void 0,o))}async function ND(e){let t=await Zs(e),n=z(t.channels).map(F).filter((r)=>r.is_member===!0).sort((r,o)=>Number(o.updated??0)-Number(r.updated??0)).slice(0,10),s=new Map;for(let r of n){let o=String(r.id??""),i=typeof r.name==="string"?r.name:typeof r.user==="string"?r.user:o,l=await ot(e,o,5),u=z(l.messages).map(F).filter((a)=>a.subtype===void 0||a.subtype===null).filter((a)=>{let c=typeof a.text==="string"?a.text:"";return c.length>0&&!c.startsWith("<@")}).slice(0,3).reverse();if(u.length===0)continue;console.log(`-- #${i} --------------------------------`);for(let a of u){let c=await cm(e,a,s),d=(typeof a.text==="string"?a.text:"").split(`
|
|
470
|
+
`)[0]??"",f=await Bn(e,d,s);console.log(` ${c}: ${f}`)}}}async function MD(e,t){let n=await vh(e,"to:me"),s=z(Vs(n,["messages","matches"])).map(F).slice(0,t),r=new Map,o=[];for(let i of s){let l=Ag(Wo(i)),u=o[o.length-1];if(u?.label===l)u.msgs.push(i);else o.push({label:l,msgs:[i]})}for(let i=0;i<o.length;i++){let{label:l,msgs:u}=o[i];if(i>0)console.log("");console.log(` ${l}`),console.log(" ----------------------------");for(let a of[...u].reverse()){let c=F(a.channel),d=c.is_im===!0,f=typeof c.name==="string"?c.name:"dm",p;if(d&&f.startsWith("U")){let g="@"+f;if(!r.has(g)){let[,h]=await Qs(e,f);r.set(g,h)}p=`@${r.get(g)??f}`}else if(d)p=`@${f}`;else p=`#${f}`;console.log(await Yo(e,a,r,p))}}}async function BD(e,t,n,s,r="text",o){let i=await Zs(e,o),l=z(i.channels).map(F).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,a)=>Number(a.updated??0)-Number(u.updated??0)).slice(0,t);if(r==="jsonl"){for(let u of l)console.log(JSON.stringify(u));return}for(let u of l){let a=String(u.id??""),c=typeof u.name==="string"?u.name:typeof u.user==="string"?u.user:a,d=u.is_im===!0,f=u.is_mpim===!0,p=d||f?"@":"#",g=u.is_member===!0?"":" (not joined)",h=typeof F(u.purpose).value==="string"?String(F(u.purpose).value):"",m=h?` ${h.split(`
|
|
471
|
+
`)[0]?.slice(0,60)}`:"";console.log(`${p}${c} ${a}${g}${m}`)}}function jD(e){let t=(r)=>r.startsWith("xoxp-")||r.startsWith("xoxc-"),n=Mi(),s=n.find((r)=>r.profile.token===e);if(!s)return;return n.find((r)=>t(r.profile.token)&&r.profile.teamId===s.profile.teamId)}async function um(e,t,n,s,r){let o=e,i=r,l;try{l=await Fc(o,t,n,i)}catch(c){let d=c instanceof Error?c.message:String(c);if(e.startsWith("xoxb-")&&d.includes("not_allowed_token_type")){let f=jD(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}".`),o=f.profile.token,i=f.profile.cookie,l=await Fc(o,t,n,i);else console.error(`Error: search requires a user token (xoxp-/xoxc-) \u2014 the active profile is a bot token (xoxb-), which Slack rejects for search.messages.
|
|
472
472
|
`+` Add a user-token profile: slack auth login (or slack auth login --token <token>)
|
|
473
|
-
Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw c}if(s){console.log(JSON.stringify(l,null,2));return}let u=
|
|
474
|
-
`);for(let h of[...g].reverse()){let m=await cm(e,h,l),y=typeof h.text==="string"?h.text:"",
|
|
475
|
-
`).join(" \u21B5 ");console.log(`[${
|
|
476
|
-
`))console.log(` ${w}`)}}var
|
|
477
|
-
`)[0]??"":"(message not readable)",y=m.length>100?`${m.slice(0,100)}\u2026`:m;if(console.log(`${
|
|
478
|
-
`)[0]??"":"(message not readable)",m=
|
|
479
|
-
`)).slice(0,4)}function
|
|
480
|
-
`)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,s=[e.cli??"?",e.session_id?`session=${e.session_id}`:"",e.agent_pid?`pid=${e.agent_pid}`:`pid=${e.pid}`,e.git_branch?`branch=${e.git_branch}`:"",`cwd=${e.cwd}`].filter(Boolean).join(" ");return`${
|
|
473
|
+
Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw c}if(s){console.log(JSON.stringify(l,null,2));return}let u=z(Vs(l,["messages","matches"])).map(F),a=new Map;for(let c of u){let d=F(c.channel),f=d.is_im===!0,p=typeof d.name==="string"?d.name:"dm",g;if(f&&p.startsWith("U")){let h="@"+p;if(!a.has(h)){let[,m]=await Qs(o,p,i);a.set(h,m)}g=`@${a.get(h)??p}`}else if(f)g=`@${p}`;else g=`#${p}`;console.log(await Yo(o,c,a,g,i))}}async function dm(e,t,n,s){let{ref:r,ts:o}=Kt(t);if(!o)console.error("Error: target must embed a message ts (e.g. #chan:1700000000.000100 or a Slack permalink URL)"),process.exit(2);return{channelId:n??await Jc(e,r,we,s),ts:o}}async function WD(e,t){let n=sr(),s={};if(!t.mine)s.shared=!0;if(t.in)s.in=t.in;if(t.from)s.from=t.from;let r=pg(t.state,n,s);if(!t.json){let o=await Me(e,t.cookie),i=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${Zo(o)} \xB7 matching ${i})`),console.error(`(query: ${r})`)}await Ve("search.messages",()=>um(e,r,t.count,t.json,t.cookie))}async function UD(e,t){let n=sr(),{channelId:s,ts:r}=await dm(e,t.target,t.channelId,t.cookie),o=await bg(e,s,r,t.state,n,t.cookie);if(o.noop){console.log(`= Already ${t.state} (ts: ${r})`);return}let i=o.removed.length?`, removed ${o.removed.map((l)=>`:${l}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${r})${i}`),o.leftover.length)console.error(`\u26A0 ${o.leftover.map((l)=>`:${l}:`).join(" ")} could not be removed \u2014 this message now carries more than one `+"progress reaction. Readers collapse by priority so nothing is lost; repair with: slack todo doctor --in <#chan> --fix")}async function JD(e,t){let n=sr(),{channelId:s,ts:r}=await dm(e,t.target,t.channelId,t.cookie),o=await wg(e,s,r,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${o}: (ts: ${r})`)}async function KD(e,t){let n=sr(),s=t.channelId??await Jc(e,t.channel,we,t.cookie),r={limit:t.limit};if(t.fix)r.fix=!0;if(t.cookie)r.cookie=t.cookie;let o=await kg(e,s,n,r);if(o.findings.length===0)console.log(`\u2713 No multi-state tasks in ${o.scanned} message(s).`);else{for(let i of o.findings){let l=i.fixed===!0?"fixed":i.fixed===!1?`FAILED: ${i.error??"?"}`:"needs --fix";console.log(`${i.ts} ${i.emoji.map((u)=>`:${u}:`).join(" ")} \u2192 keep :${i.keep}: [${l}] ${M(i.text).slice(0,60)}`)}console.log(`${o.findings.length} multi-state task(s) in ${o.scanned} message(s).`)}if(o.truncated)console.error(`\u26A0 Scan limit reached (${t.limit} messages) \u2014 older history was NOT checked. Raise it with --limit N.`)}async function qD(e,t,n,s){let r=Math.floor(Date.now()/1000)-t*86400,o=await Zs(e),i=z(o.channels).map(F).filter((c)=>c.is_member===!0&&c.is_im!==!0&&c.is_mpim!==!0).filter((c)=>{if(!s)return!0;return(typeof c.name==="string"?c.name:"").toLowerCase().includes(s.toLowerCase())}).sort((c,d)=>Number(d.updated??0)-Number(c.updated??0)),l=new Map,u=0,a=0;for(let c of i){let d=String(c.id??""),f=typeof c.name==="string"?c.name:d,p;try{p=await ot(e,d,n)}catch(h){console.error(` SKIP #${f}: ${h.message}`);continue}let g=z(p.messages).map(F).filter((h)=>(h.subtype===void 0||h.subtype===null)&&Wo(h)>=r);if(g.length===0)continue;a+=1,u+=g.length,console.log(`## #${f} (${g.length} msgs)
|
|
474
|
+
`);for(let h of[...g].reverse()){let m=await cm(e,h,l),y=typeof h.text==="string"?h.text:"",D=ds(await Bn(e,y,l)).split(`
|
|
475
|
+
`).join(" \u21B5 ");console.log(`[${jn(Wo(h))}] ${m}: ${D}`)}console.log("")}console.error(`Dumped ${u} messages across ${a} channels (cutoff: ${t}d)`)}function HD(e){let t=[];function n(s){if(typeof s==="string"){t.push(s);return}if(Array.isArray(s)){for(let r of s)n(r);return}if(s&&typeof s==="object"){let r=s;if(typeof r.text==="string"){t.push(r.text);return}if(r.type==="link"&&typeof r.url==="string"){t.push(r.url);return}if(Array.isArray(r.elements))n(r.elements);else if(Array.isArray(r.content))n(r.content)}}for(let s of e)n(s);return t.join("").trim()}async function Xo(e,t,n){let s=new Map;return async(r)=>{if(!r)return"(unknown)";if(s.has(r))return s.get(r);try{let o=await eg(e,r,t),i=F(o.channel),l;if(i.is_im===!0){let u=typeof i.user==="string"?i.user:"";if(!u||u===n)l="@self";else{let[a]=await Qs(e,u);l=`@${a}`}}else l=`#${typeof i.name==="string"?i.name:r}`;return s.set(r,l),l}catch{return r}}}function pl(e){let t=F(z(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function Jo(e){return HD(z(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function zD(e,t,n=!1){let s=await er(e,t),r=z(s.drafts??s.messages??[]).map(F).filter((a)=>a.is_deleted!==!0),o=n?r:r.filter((a)=>a.is_sent!==!0);if(o.length===0){console.log(n?"No drafts.":"No pending drafts. Run with --all to include sent.");return}let i="";try{({userId:i}=await Lc(e,t))}catch{}let l=await Xo(e,t,i),u=new Map;for(let a of o){let c=pl(a),d=Jo(a),f=Number(a.date_created??a.date_create??0),p=f?al(f):"?",g=await l(c),h=typeof a.id==="string"?a.id:"",m=a.is_sent===!0?" [SENT]":"",y=ds(await Bn(e,d,u));console.log(`-- ${h} ${g} [${p}]${m}`);for(let w of y.split(`
|
|
476
|
+
`))console.log(` ${w}`)}}var Ko=50,ar=20;async function YD(e,t,n){let s=[],r,o=0;do{let d=F(await Ic(e,{filter:n.filter,limit:Ko,cursor:r},t));s.push(...Nc(d));let f=F(d.response_metadata).next_cursor;r=typeof f==="string"&&f?f:void 0}while(r&&++o<ar);if(r)console.error(`Note: read the first ${s.length} items only (${ar} pages); the order covers those.`);let i=ig(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 Mt(e,t))}catch{}let a=await Xo(e,t,u),c=Date.now()/1000;for(let d of i){let f;if(d.channel&&d.ts)try{let w=F(await Pe(e,d.channel,d.ts,1,t));f=z(w.messages).map(F).find((D)=>D.ts===d.ts)}catch{}let p=d.channel&&d.ts?l?Bc(l,d.channel,d.ts):`${d.channel}:${d.ts}`:"";if(n.json){console.log(JSON.stringify({...d,done:nr(d),permalink:p,user:f?.user??null,text:f?.text??null}));continue}let g=d.channel?await a(d.channel):`(${d.itemType||"item"})`,h=typeof f?.user==="string"?`@${await Re(e,f.user,t)}: `:"",m=typeof f?.text==="string"?f.text.split(`
|
|
477
|
+
`)[0]??"":"(message not readable)",y=m.length>100?`${m.slice(0,100)}\u2026`:m;if(console.log(`${Mc(d,c,jn)} ${M(g)}`),console.log(` ${M(h+y)}`),p)console.log(` ${p}`)}}function GD(e){if(e.kind==="done")return e.undo?["completed","todo","saved","archived"]:["todo","saved","completed","archived"];return["todo","saved","completed","archived"]}async function XD(e,t,n,s,r){let o=0;for(let i of r){let l;do{if(o++>=ar)return"unknown";let u=F(await Ic(e,{filter:i,limit:Ko,cursor:l},t)),a=Nc(u).find((d)=>d.channel===n&&d.ts===s);if(a)return a;let c=F(u.response_metadata).next_cursor;l=typeof c==="string"&&c?c:void 0}while(l)}return}function VD(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 No(e,t,n,s,r){let{ref:o,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 we(e,o,t),u=await XD(e,t,l,i,GD(s));if(u==="unknown"&&s.kind!=="add")console.error(`Error: not found in the first ${ar*Ko} saved items \u2014 stopped there to stay under Slack's rate limits. Nothing was changed.`),process.exit(1);let a=u==="unknown"?void 0:u;if(s.kind==="add"&&a)console.error(`Error: that message is already in your To-dos (${nr(a)?"done":a.todoState||"saved"}) \u2014 use \`slack todos edit\` or \`done\`.`),process.exit(1);if(s.kind!=="add"&&!a)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 c="",d="";try{({url:c,userId:d}=await Mt(e,t))}catch{}let f=await(await Xo(e,t,d))(l),p;try{let k=F(await Pe(e,l,i,1,t));p=z(k.messages).map(F).find((_)=>_.ts===i)}catch{}let g=typeof p?.user==="string"?`@${await Re(e,p.user,t)}: `:"",h=typeof p?.text==="string"?p.text.split(`
|
|
478
|
+
`)[0]??"":"(message not readable)",m=fs(h.length>100?`${h.slice(0,100)}\u2026`:h),y=Date.now()/1000,w=De("todos",JSON.stringify(s),l,i,d);if(r!==w)Se(r,w,["--- To-do ------------------------------------",` For: ${d?`@${await Re(e,d,t)} (your own To-dos)`:"(your own To-dos)"}`,` Where: ${M(f)}`,` Msg: ${M(g+m)}`,...c?[` Link: ${Bc(c,l,i)}`]:[],...a?[` Now: ${Mc(a,y,jn)}`]:[],...u==="unknown"?[` Note: not checked beyond the first ${ar*Ko} saved items \u2014 it may already be saved`]:[],...VD(s,$m),"----------------------------------------------"]);let D={channel:l,ts:i};switch(s.kind){case"add":await Xh(e,D,{todo:!s.saved,...s.due?{due:s.due}:{}},t),console.log(`\u2713 Added to your To-dos${s.due?` (due ${jn(s.due)})`:""}`);break;case"done":await Pc(e,D,{mark:s.undo?"uncompleted":"completed"},t),console.log(s.undo?"\u2713 Reopened":"\u2713 Marked done");break;case"edit":await Pc(e,D,{...s.todo===void 0?{}:{todo:s.todo},...s.due===void 0?{}:{due:s.due}},t),console.log("\u2713 Updated");break;case"rm":await Vh(e,D,t),console.log("\u2713 Removed from your To-dos");break}}async function ZD(e,t,n){let s=await er(e,t),r=z(s.drafts).map(F).find((g)=>String(g.id)===n);if(!r)console.error(`Draft not found: ${n}`),process.exit(1);let o="";try{({userId:o}=await Lc(e,t))}catch{}let i=await Xo(e,t,o),l=pl(r),u=Jo(r),a=Number(r.date_created??0),c=String(r.last_updated_ts??"?"),d=await i(l),p=ds(await Bn(e,u,new Map));console.log(`id: ${r.id}`),console.log(`channel: ${d} (${l})`),console.log(`created: ${a?al(a):"?"}`),console.log(`updated: ${al(Number(c.split(".")[0]))}`),console.log(`status: ${r.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(p)}function De(...e){return RD(e.join(`
|
|
479
|
+
`)).slice(0,4)}function M(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var QD={"reactions.add":"reactions:write","reactions.remove":"reactions:write","chat.postMessage":"chat:write","chat.update":"chat:write","chat.delete":"chat:write","pins.add":"pins:write","slackLists.create":"lists:write","slackLists.items.create":"lists:write","slackLists.items.update":"lists:write","slackLists.items.list":"lists:read","slackLists.access.set":"lists:write","conversations.rename":"channels:manage (or groups:write for a private channel)","conversations.replies":"channels:history (or groups:history)","conversations.history":"channels:history (or groups:history)"};function ge(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,s,r]=n;switch(r){case"missing_scope":return`Error: token lacks the ${QD[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 Vo(e,t,n){if(!t.startsWith("D"))return null;try{let s=await Qo(e,t,n);if(!s)return null;return await yg(e,s,as,n)}catch{return null}}function Se(e,t,n,s,r=new Date){for(let i of n)console.log(i);let o=Zc(r,s);if(o)console.log(o);if(e!==void 0)console.error(`Code mismatch (got ${e}, expected ${t})`);console.error(`Rerun with --code=${t}`),process.exit(1)}function Kt(e){let t=ft(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:fl(s)}}}return{ref:e}}function St(e,t=!0){let n=ft(e);if(n){if(!t)return{ref:n.channel};let o=n.threadTs??n.ts;return o?{ref:n.channel,threadTs:o}:{ref:n.channel}}let s=e.indexOf(":");if(s>0){let o=e.slice(s+1);if(/^\d{10}\.\d{6}$/.test(o))return{ref:e.slice(0,s),threadTs:o};if(/^\d{4}-\d{2}-\d{2}T/.test(o))return{ref:e.slice(0,s),threadTs:fl(o)}}let r=Qa(e);if(r)return r.thread_ts?{ref:r.channel,threadTs:r.thread_ts}:{ref:r.channel};return{ref:e}}async function Jg(e,t,n,s,r,o=!1){let i=ss(n),l,u;if(s)if(ft(s)){let a=await gs(e,s,t);l=a.channel,u=a.root}else{let a=St(s);if(!a.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}`};a={ref:i.channel,threadTs:s}}if(!a.threadTs)return{error:`"${s}" is not a thread \u2014 reply only posts in threads. For a top-level post use \`slack send\`.`};l=await we(e,a.ref,t),u=a.threadTs}if(r){let a=await gs(e,r,t);if(l===void 0)l=a.channel,u=a.root;else if(!o){let c=nc({channel:l,...u?{threadTs:u}:{}},a);if(c)return{error:c}}}if(!l||!u)return{error:"reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"};if(vn(n)&&!on(n).some((a)=>a.channel===l&&(a.thread_ts===void 0||a.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 gs(e,t,n){let s=ft(t),r,o,i;if(s)r=s.channel,o=s.ts,i=s.threadTs;else{let u=St(t);r=u.ref,o=u.threadTs}if(!o)throw Error(`--to needs a message permalink (or #chan:<ts>), got "${t}"`);let l=await we(e,r,n);if(!i)try{let u=F(await Pe(e,l,o,1,n)).messages??[],a=u.map(F).find((c)=>c.ts===o)??F(u[0]);i=typeof a.thread_ts==="string"?a.thread_ts:o}catch(u){if(!/thread_not_found/.test(u instanceof Error?u.message:String(u)))throw u;i=o}return{channel:l,ts:o,root:i}}async function Jt(e,t,n,s){let r=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let i=F(await Nn(e,t,s)),l=F(i.channel);if(l.is_im===!0){let u=typeof l.user==="string"?l.user:"";r=u?`@${await Re(e,u,s)}`:t}else r=typeof l.name==="string"?`#${l.name}`:t}catch{r=t}return r===t?t:`${r} (${t})`}async function Me(e,t){try{return await Mt(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 Un(e){if(!_o())return{record:()=>{}};let t=hh();return{metadata:gh(e,t),record:(n)=>{mh({...n,kind:e,attribution:t})}}}function ex(e){let t=M(e.text.split(`
|
|
480
|
+
`)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,s=[e.cli??"?",e.session_id?`session=${e.session_id}`:"",e.agent_pid?`pid=${e.agent_pid}`:`pid=${e.pid}`,e.git_branch?`branch=${e.git_branch}`:"",`cwd=${e.cwd}`].filter(Boolean).join(" ");return`${jn(e.sent_at/1000)} ${e.kind.padEnd(4)} ${M(e.target??e.channel)} ${n}
|
|
481
481
|
${t}
|
|
482
|
-
${
|
|
483
|
-
`)[0]??""),i=o.length>n?`${o.slice(0,n)}\u2026`:o,l=typeof t.ts==="string"?t.ts:"";return`${l?
|
|
484
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(s)return{botToken:r};let{ref:o}=Kt(e);if(!o.startsWith("@"))return{botToken:r};try{let i=await Ot(t,o,n);return{botToken:r,channelId:await Ut(r,i)}}catch(i){console.error(`Error: could not resolve ${
|
|
482
|
+
${M(s)}`}function Zo(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let s=M(e.user||e.userId||"?"),r=e.userId?` (${e.userId})`:"",o=e.team?` \u2014 ${M(e.team)}`:"";return`@${s}${r}${o}${n}`}function Ee(e,t={}){return` ${"From:".padEnd(t.pad??6)}${Zo(e,t.asBot)}`}async function cl(e,t,n=60,s){let r=typeof t.user==="string"?await Re(e,t.user,s):typeof t.username==="string"?t.username:"?",o=fs((typeof t.text==="string"?t.text:"").split(`
|
|
483
|
+
`)[0]??""),i=o.length>n?`${o.slice(0,n)}\u2026`:o,l=typeof t.ts==="string"?t.ts:"";return`${l?Uo(l).slice(0,16).replace("T"," "):""} @${r}${i?`: ${i}`:""}`}async function tx(e,t,n,s){let r=n.find((o)=>String(o.ts)===t)??n[0];if(!r)return t;return cl(e,r,40,s)}function Kg(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function nx(e,t){let n=Kg(e),s=Kg(t);if(!n||!s)return 0;if(n===s)return 1;let r=(a)=>{let c=new Map;for(let d=0;d<a.length-1;d++){let f=a.slice(d,d+2);c.set(f,(c.get(f)??0)+1)}return c},o=r(n),i=r(s);if(o.size===0||i.size===0)return 0;let l=0;for(let[a,c]of o){let d=i.get(a);if(d)l+=Math.min(c,d)}let u=qg(o)+qg(i);return u===0?0:2*l/u}function qg(e){let t=0;for(let n of e.values())t+=n;return t}async function Hg(e,t,n,s){let r=Le();if(!r)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
484
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(s)return{botToken:r};let{ref:o}=Kt(e);if(!o.startsWith("@"))return{botToken:r};try{let i=await Ot(t,o,n);return{botToken:r,channelId:await Ut(r,i)}}catch(i){console.error(`Error: could not resolve ${M(o)} to the bot's DM.
|
|
485
485
|
${i instanceof Error?i.message:String(i)}
|
|
486
|
-
`+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function sx(e,t){let n=qt(e,t.cookie),{ref:s,ts:r}=Kt(t.target);if(!r)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let o;if(t.channelId)o=t.channelId;else o=await
|
|
486
|
+
`+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function sx(e,t){let n=qt(e,t.cookie),{ref:s,ts:r}=Kt(t.target);if(!r)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let o;if(t.channelId)o=t.channelId;else o=await we(e,s,t.cookie);let i=await Pe(e,o,r,1,t.cookie),u=z(i.messages).map(F).find((S)=>String(S.ts)===r);if(!u)console.error(`Message not found at ts=${r} in channel ${o}`),process.exit(1);let a=typeof u.text==="string"?u.text:"",c=t.newText;if(t.tick){let S=Dp(a,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);c=S.text}else c=xp(a,c,t.lanePrefix);let d=t.mentionCookie??t.cookie,f=t.mentions&&!t.tick?await _g(t.mentionToken??e,c,o,d?{cookie:d}:{}):c;Ke(f,t.allowUrlAdjacent);let p=Ct(a).kind,g=Ct(f).kind,h=Ys(a).kind!=="other",m=h?Ys(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"}.
|
|
487
487
|
`+(h?" Edit it anyway with --force.":` To retire it: slack ask --void='${t.target}' --reason '\u2026'
|
|
488
|
-
Edit it anyway with --force.`)),process.exit(1);let y=m,w=await n(),
|
|
488
|
+
Edit it anyway with --force.`)),process.exit(1);let y=m,w=await n(),D=y?De("force-edit-ask-poll",a,f,w?.userId??""):De(a,f,w?.userId??"");if(t.code!==D)Se(t.code,D,[...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 -------------------------",...a.split(`
|
|
489
489
|
`).map((S)=>` ${S}`),"--- Replacing with ---------------------------",...f.split(`
|
|
490
|
-
`).map((S)=>` ${S}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let
|
|
491
|
-
`).map((p)=>` ${p}`),"---------------------------------------------"])}await Bh(e,o,r,t.cookie),console.log(`\u2713 Deleted (ts: ${r})`)}function dn(e){return`'${e.replace(/'/g,"'\\''")}'`}async function
|
|
492
|
-
`).map((y)=>` ${
|
|
493
|
-
`).map((y)=>` ${
|
|
494
|
-
Check before retrying, or you will have two boards: slack pinlog ls ${dn(t.target)}${r}`);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:c,asBot:t.asBot});let p=pt(i,f);console.log(`\u2713 Posted HEAD: ${p}`);let g=fm(a,"this new top-level post notified everyone who follows the channel");if(g)console.error(g);try{await
|
|
490
|
+
`).map((S)=>` ${S}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let k=Un("edit"),_=p!=="other"||g!=="other"||h||Ys(f).kind!=="other",E=await jt(e,o,r,f,t.cookie,_?!0:void 0,k.metadata);console.log(`\u2713 Edited (ts: ${E})`),k.record({team:w?.team,channel:o,target:t.target,ts:r,text:f,asBot:t.asBot})}async function rx(e,t){let n=qt(e,t.cookie),{ref:s,ts:r}=Kt(t.target);if(!r)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let o;if(t.channelId)o=t.channelId;else o=await we(e,s,t.cookie);let i=await Pe(e,o,r,1,t.cookie),u=z(i.messages).map(F).find((f)=>String(f.ts)===r);if(!u)console.error(`Message not found at ts=${r} in channel ${o}`),process.exit(1);let a=typeof u.text==="string"?u.text:"",c=await n(),d=De(o,r,a,c?.userId??"");if(t.code!==d){let f=await Jt(e,o,s,t.cookie);Se(t.code,d,["--- Deleting message -------------------------",Ee(c,{asBot:t.asBot}),` \u2192 ${f} at ${Uo(r)}`,...a.split(`
|
|
491
|
+
`).map((p)=>` ${p}`),"---------------------------------------------"])}await Bh(e,o,r,t.cookie),console.log(`\u2713 Deleted (ts: ${r})`)}function dn(e){return`'${e.replace(/'/g,"'\\''")}'`}async function hl(e,t,n){let s=Po(t);if(s)return{...s,ref:s.channel};let{ref:r,ts:o}=Kt(t);if(!o)console.error(`Error: ${M(t)} is a channel, not a board \u2014 pass the board's permalink, `+`#chan:ts, or the id \`new\` printed (C\u2026:ts). Boards in a channel: slack pinlog ls ${dn(t)}`),process.exit(2);return{channel:await we(e,r,n),ts:o,ref:r}}async function ox(e,t,n,s){let r=F(await Pe(e,t,n,1,s)),o=z(r.messages).map(F).find((i)=>String(i.ts)===n);if(!o)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return o}function Mo(e,t){if(t!==void 0)try{return ul(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 zg=40000;function qo(e,t){if(t.length>zg)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${zg}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function Ho(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof rt)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function fm(e,t){let n=Zc(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function ix(e,t){let{ref:n,ts:s}=Kt(t.target);if(s||Po(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),qo("reason",t.log);let r=`${t.workspace?` -w ${dn(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,o=qt(e,t.cookie),i=await we(e,n,t.cookie),l=await o(),u=De("pinlog-create",i,t.state,t.log??"",l?.userId??""),a=new Date,c=tl(t.state,a);if(qo("HEAD (state + footer)",c),t.code!==u){let h=await Jt(e,i,n,t.cookie),m=(await pm(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)=>` ${pt(i,String(y.ts))} ${hm(String(y.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...c.split(`
|
|
492
|
+
`).map((y)=>` ${M(y)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
|
|
493
|
+
`).map((y)=>` ${M(y)}`)]:[],"---------------------------------------------"])}let d=Un("send"),f;try{f=await Bt(e,i,c,void 0,!1,t.cookie,!0,d.metadata)}catch(h){if(Ho(h))console.error(`\u2717 HEAD was NOT posted: ${ge(h)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${ge(h)}
|
|
494
|
+
Check before retrying, or you will have two boards: slack pinlog ls ${dn(t.target)}${r}`);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:c,asBot:t.asBot});let p=pt(i,f);console.log(`\u2713 Posted HEAD: ${p}`);let g=fm(a,"this new top-level post notified everyone who follows the channel");if(g)console.error(g);try{await Oc(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`:ge(h);console.error(`\u26A0 NOT pinned: ${y}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${p}${r}`)}if(t.log)try{let h=await Bt(e,i,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${h})`)}catch(h){let m=De("pinlog-log",i,f,t.log,l?.userId??"");console.error(`${Ho(h)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${ge(h)}
|
|
495
495
|
The board IS posted. Retry just the reason (check the thread first):
|
|
496
|
-
slack pinlog note ${p} ${dn(
|
|
497
|
-
`+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let u=await n(),a=pt(s,r),c=new Date,d=`${t.workspace?` -w ${dn(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=
|
|
498
|
-
`).map((w)=>` ${
|
|
499
|
-
`).map((x)=>` ${
|
|
500
|
-
`).map((x)=>` ${
|
|
501
|
-
`).map((x)=>` ${
|
|
502
|
-
Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",R=
|
|
496
|
+
slack pinlog note ${p} ${dn(ls(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${r} --code=${m}`),process.exit(1)}}async function Yg(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);qo("log line",t.log);let n=qt(e,t.cookie),{channel:s,ts:r,ref:o}=await hl(e,t.target,t.cookie);try{jg(`pinlog-${s}-${r}`)}catch(y){if(!(y instanceof rr))throw y;console.error(`Error: another update of ${pt(s,r)} 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 ox(e,s,r,t.cookie),l=typeof i.text==="string"?i.text:"";if(t.adopt&&t.logOnly)console.error("Error: --adopt rewrites the state with a footer \u2014 it does not apply to note."),process.exit(2);if(!hs(l)&&!t.adopt)console.error(`Error: the message at ${pt(s,r)} is not a pinlog HEAD (no "${or}" footer).
|
|
497
|
+
`+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let u=await n(),a=pt(s,r),c=new Date,d=`${t.workspace?` -w ${dn(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=De("pinlog-log",s,r,t.log,u?.userId??""),p=`slack pinlog note ${a} ${dn(ls(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,g=fm(c,"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 Jt(e,s,o,t.cookie);Se(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",Ee(u,{asBot:t.asBot}),` \u2192 ${y}, thread of ${a}`,...t.log.split(`
|
|
498
|
+
`).map((w)=>` ${M(w)}`),"---------------------------------------------"])}}else{let y=tl(t.state,c);qo("new HEAD (state + footer)",y);let w=!hs(l),D=De("pinlog-update",s,r,l,t.state,t.log,u?.userId??"");if(t.code!==D){let E=await Jt(e,s,o,t.cookie),S=ir(l).trim()===ir(t.state).trim();Se(t.code,D,["--- Updating pinlog --------------------------",Ee(u,{asBot:t.asBot}),` \u2192 ${E}, ${a}`,"--- Current HEAD -----------------------------",...l.split(`
|
|
499
|
+
`).map((x)=>` ${M(x)}`),"--- New HEAD (edited in place \u2014 silent) ------",...y.split(`
|
|
500
|
+
`).map((x)=>` ${M(x)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
|
|
501
|
+
`).map((x)=>` ${M(x)}`),"---------------------------------------------",...S?["\u26A0 The state text is unchanged \u2014 only the footer time moves. Replies are for real changes."]:[],...w?["\u26A0 Adopting: this message has no pinlog footer yet \u2014 it becomes a board now."]:[]])}let k=Un("edit");try{await jt(e,s,r,y,t.cookie,!0,k.metadata)}catch(E){let S=E instanceof Error?E.message:String(E),x=/cant_update_message/.test(S)?`
|
|
502
|
+
Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",R=Ho(E)?`\u2717 HEAD was NOT updated: ${ge(E)}${x}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${ge(E)}
|
|
503
503
|
Check it first: slack pinlog get ${a}${d}`;console.error(`${R}
|
|
504
|
-
The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}
|
|
505
|
-
The log reply was NOT posted. Check it: slack pinlog get ${a}${d}`),process.exit(3)}console.log(`\u2713 HEAD updated${_?" (read back: matches)":""}: ${a}`)}let h=
|
|
506
|
-
`:`\u26A0 UNKNOWN whether the log reply was posted: ${
|
|
504
|
+
The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}k.record({team:u?.team,channel:s,target:t.target,ts:r,text:y,asBot:t.asBot});let _;try{if(_=z(F(await Pe(e,s,r,1,t.cookie)).messages).map(F).find((S)=>S.ts===r),!_)console.error("\u26A0 HEAD updated, but the read-back did not return it, so it was not checked")}catch(E){console.error(`\u26A0 HEAD updated, but it could not be read back to check: ${ge(E)}`)}if(_&&!Op(y,_)){let E=oc(_.blocks);console.error(`\u2717 HEAD was edited, but Slack does not show what was sent (${Rp(Ks(y,E),Ks(typeof _.text==="string"?_.text:"",E))}).
|
|
505
|
+
The log reply was NOT posted. Check it: slack pinlog get ${a}${d}`),process.exit(3)}console.log(`\u2713 HEAD updated${_?" (read back: matches)":""}: ${a}`)}let h=Un("send"),m;try{m=await Bt(e,s,t.log,r,!1,t.cookie,!0,h.metadata)}catch(y){let w=Ho(y);console.error((w?`\u2717 Log reply was NOT posted: ${ge(y)}
|
|
506
|
+
`:`\u26A0 UNKNOWN whether the log reply was posted: ${ge(y)}
|
|
507
507
|
`)+(t.logOnly?"":` The HEAD IS updated \u2014 only the log line ${w?"is":"may be"} missing.
|
|
508
508
|
`)+(w?"":` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${a}${d}
|
|
509
509
|
`)+` Retry just the log line${w?"":" (only if it is not there)"}:
|
|
510
|
-
${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 Gg(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function ax(e){return
|
|
511
|
-
`))console.log(
|
|
512
|
-
`).map((
|
|
513
|
-
`).find((t)=>t.trim())??"").slice(0,80)}async function ux(e,t,n,s){let{ref:r,ts:o}=Kt(t);if(o||
|
|
514
|
-
`+` 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,a=null;if(t.mentions){a=await ln(t.mentionToken??e,l,i,t.mentionCookie),u=a.text;for(let S of
|
|
515
|
-
`)[0]??"").slice(0,100)}`,...c,"--- Sending ----------------------------------",x,` \u2192 ${S} \u2014 NEW top-level message`,` Message: ${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}let
|
|
510
|
+
${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 Gg(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function ax(e){return Qc(new Date(Number(e.split(".")[0])*1000))}async function cx(e,t,n,s){if(typeof t.user==="string"){let o=n.get(t.user);if(o!==void 0)return o;let i;try{i=await Re(e,t.user,s)}catch{i=t.user}return n.set(t.user,i),i}let r=F(t.bot_profile);if(typeof r.name==="string")return r.name;return typeof t.username==="string"?t.username:"bot"}async function lx(e,t,n,s){let{channel:r,ts:o}=await hl(e,t,n),i=[],l,u=0;do{let h=F(await jh(e,r,o,l,200,n));for(let y of z(h.messages).map(F)){if(String(y.ts)===o&&i.some((w)=>String(w.ts)===o))continue;i.push(y)}let m=F(h.response_metadata).next_cursor;l=typeof m==="string"&&m?m:void 0,u++}while(l&&u<50);let a=l===void 0,c=i.find((h)=>String(h.ts)===o);if(!c)console.error(`Error: no message at ts=${o} in ${r}.`),process.exit(1);let d=typeof c.text==="string"?c.text:"",f=i.filter((h)=>String(h.ts)!==o);if(s){console.log(JSON.stringify({id:pt(r,o),isPinlog:hs(d),updated:nl(d),complete:a,head:d,log:f.map((h)=>({ts:String(h.ts),user:h.user??null,text:typeof h.text==="string"?h.text:""}))}));return}if(!hs(d))console.error(`\u26A0 ${pt(r,o)} has no "${or}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${pt(r,o)} ===`);for(let h of Gg(d).split(`
|
|
511
|
+
`))console.log(M(h));let p=a?"":" \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=M(await cx(e,h,g,n)),w=Gg(m).split(`
|
|
512
|
+
`).map((D)=>M(D));console.log(`${ax(String(h.ts))} @${y}: ${w[0]??""}`);for(let D of w.slice(1))console.log(` ${D}`)}}async function pm(e,t,n,s){let r=0,o,i=[];do{let l=F(await ot(e,t,Math.min(200,n-r),void 0,o,s)),u=z(l.messages).map(F);r+=u.length;for(let c of u)if(typeof c.text==="string"&&hs(c.text))i.push(c);let a=F(l.response_metadata).next_cursor;o=typeof a==="string"&&a?a:void 0}while(o&&r<n);return{found:i,scanned:r}}function hm(e){return M(ir(e).split(`
|
|
513
|
+
`).find((t)=>t.trim())??"").slice(0,80)}async function ux(e,t,n,s){let{ref:r,ts:o}=Kt(t);if(o||Po(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${dn(t)}`),process.exit(2);let i=await we(e,r,s),{found:l,scanned:u}=await pm(e,i,n,s),a=await Jt(e,i,r,s);if(l.length===0){console.log(`No pinlogs in the last ${u} messages of ${a}.${u>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let c of l){let d=String(c.ts),f=pt(i,d),p=String(c.text),g=z(c.pinned_to).some((y)=>y===i)?"\uD83D\uDCCC":" ",h=hm(p),m=typeof c.reply_count==="number"?c.reply_count:0;console.log(`${g} ${f} updated ${nl(p)??"?"} log ${m}`),console.log(` ${h}`)}}async function dx(e,t,n){let{channel:s,ts:r}=await hl(e,t,n);try{await Oc(e,s,r,n),console.log(`\u2713 Pinned ${pt(s,r)}`)}catch(o){let i=o instanceof Error?o.message:String(o);if(/already_pinned/.test(i)){console.log(`\u2713 Already pinned: ${pt(s,r)}`);return}console.error(`\u2717 NOT pinned: ${ge(o)}`),process.exit(1)}}async function fx(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 r=t.emoji.replace(/^:|:$/g,""),o;if(t.channelId)o=t.channelId;else o=await we(e,n,t.cookie);if(t.remove)await Wt(e,o,s,r,t.cookie),console.log(`\u2713 Removed :${r}: (ts: ${s})`);else await Ft(e,o,s,r,t.cookie),console.log(`\u2713 Reacted :${r}: (ts: ${s})`)}async function gl(e,t,n,s){if(!n||!t.startsWith("D"))return!1;try{let r=F(await Nn(e,t,s)),o=F(r.channel);return o.is_im===!0&&o.user===n}catch{return!1}}function px(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 z(n.reply_users))if(typeof s==="string")t.add(s)}return t}async function hx(e,t,n){if(!t.startsWith("D"))return;try{let s=F(F(await Nn(e,t,n)).channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function gx(e,t){let{ref:n,threadTs:s}=St(t.target),r=t.cookie;if(!t.code&&Ip(t.message))console.error(vp(t.target));let o=qt(e,r),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Ut(e,t.userId,r);else i=await we(e,n,r);if(!t.asBot&&await gl(e,i,(await o())?.userId,r))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
|
|
514
|
+
`+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let l=je(t.message);Ke(l,t.allowUrlAdjacent);let u=l,a=null;if(t.mentions){a=await ln(t.mentionToken??e,l,i,t.mentionCookie),u=a.text;for(let S of Io(a.unresolved))console.error(`\u26A0 ${M(S)}`)}let c=[];if(a&&(a.resolved.length>0||a.unresolved.length>0)){c.push("--- Mentions ---------------------------------");for(let S of a.resolved)c.push(` \u2713 ${M(S.surface)} \u2192 @${M(S.display)} (${S.userId}) \u2014 will notify`);for(let S of a.unresolved){let x=S.reason==="ambiguous"?"ambiguous":S.reason==="unavailable"?"lookup unavailable":"no match";c.push(` \u26A0 ${M(S.surface)} \u2014 plain text, NOT notified (${x})`)}}let d="",f="?",p=[],g,h,m;if(s)try{let S=await Pe(e,i,s,100,r);p=z(S.messages).map(F);let x=p[p.length-1];d=typeof x?.text==="string"?x.text:"",g=typeof x?.user==="string"?x.user:void 0,h=typeof x?.bot_id==="string"?x.bot_id:void 0,m=typeof x?.ts==="string"?x.ts:void 0}catch{}else try{let S=await ot(e,i,1,void 0,void 0,r),x=z(S.messages).map(F),R=x.filter((v)=>v.subtype===void 0||v.subtype===null)[0];d=typeof R?.text==="string"?R.text:"",f=typeof R?.user==="string"?await Re(e,R.user,r):typeof R?.username==="string"?R.username:"?";let L=x[0];g=typeof L?.user==="string"?L.user:void 0,h=typeof L?.bot_id==="string"?L.bot_id:void 0,m=typeof L?.ts==="string"?L.ts:void 0}catch{}try{let S=s?px(p):new Set([await hx(e,i,r)].filter((x)=>!!x));for(let x of await Cg(t.mentionToken??e,u,t.mentionCookie)){if(S.has(x.userId))continue;console.error(`\u26A0 possible untagged mention: ${M(x.surface)} \u2014 @${M(x.display)} won't be notified (did you mean <@${x.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&m&&(g||h))try{let S=await o();if(!!S&&(!!g&&!!S.userId&&S.userId===g||!!h&&!!S.botId&&S.botId===h)){let R=`slack edit "#${i}:${m}" "<new text>" --channel-id ${i}`;try{let L=await Ln(e,i,m,r);if(L)R=`slack edit "${L}" "<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(` ${R}`),console.error(" To send anyway, confirm with --code=XXXX.")}}catch{}if(s&&p.length){let S={sim:0,msg:null};for(let x of p){let R=typeof x.text==="string"?x.text:"";if(!R)continue;let L=nx(u,R);if(L>S.sim)S={sim:L,msg:x}}if(S.msg&&S.sim>=0.82){let x=Math.round(S.sim*100);console.error(`\u26A0 possible duplicate: ${x}% similar to an existing thread message \u2014 ${await cl(e,S.msg,60,r)}`)}}let y=await o(),w=await Vo(e,i,r),D=De(i,s??"",d,u,y?.userId??"");if(t.code!==D){let S=await Jt(e,i,n,r),x=Ee(y,{asBot:t.asBot});if(s){let R=await tx(e,s,p,r),L=p.slice(-3),v=L.length?await Promise.all(L.map(async(P)=>` ${await cl(e,P,60,r)}`)):[" (thread context unavailable)"];Se(t.code,D,["--- Recent messages in thread ----------------",...v,...c,"--- Sending ----------------------------------",x,` \u2192 ${S} thread of ${R} \u2014 THREAD REPLY`,` Message: ${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}else Se(t.code,D,["--- Last message in channel ------------------",` ${f}: ${fs(d.split(`
|
|
515
|
+
`)[0]??"").slice(0,100)}`,...c,"--- Sending ----------------------------------",x,` \u2192 ${S} \u2014 NEW top-level message`,` Message: ${u}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}let k=Un("send"),_=await Bt(e,i,u,s,t.broadcast,r,void 0,k.metadata),E="";try{E=await Ln(e,i,_,r)}catch{}if(k.record({team:(await o())?.team,channel:i,target:t.target,ts:_,threadTs:s,permalink:E,text:u,asBot:t.asBot}),t.json)console.log(JSON.stringify({ok:!0,channel:i,ts:_,...s?{thread_ts:s}:{},...E?{permalink:E}:{}}));else if(E)console.log(`\u2713 Sent: ${E}`);else console.log(`\u2713 Sent (ts: ${_})`);if(t.asBot&&i.startsWith("D"))try{let S=await Wr(e);if(!S.ok)for(let x of Ur(S,!0))console.error(x);else{let x=S.appId?`https://api.slack.com/apps/${S.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${x} \u2192 App Home.`)}}catch{}}var mx=2,oe=3,yx=4,bx=5,zo=6,wx=7,kx=10;function Dx(){return/^(1|true|yes|on)$/i.test(process.env.SLACK_TERM_ASK_EXPLAIN??"")}var Xg=8,xx=(e)=>new Promise((t)=>setTimeout(t,e));function rl(e){return e==="-"||e===""&&process.argv.slice(2).includes("-")}async function ol(){return(await Bun.stdin.text()).replace(/\s+$/,"")}var gm=new Set(["thread_broadcast"]),Sx=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function mm(e){if(!e.length)return;let t=e.map((n)=>{let s=M(n.surface);if(n.reason==="unavailable")return`${s}: could not fetch the user list or channel members (users:read missing or an API/connection error)`;if(n.reason==="ambiguous")return`${s}: matches multiple people \u2014 use an explicit <@USERID> tag`;return`${s}: matched no one`});console.error(`Error: \`ask\` will not post with unresolved answerer tags.
|
|
516
516
|
${t.join(`
|
|
517
|
-
`)}`),process.exit(
|
|
518
|
-
`).entries())console.error(` ${o?" ".repeat(
|
|
519
|
-
`+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`)
|
|
520
|
-
${
|
|
521
|
-
${
|
|
517
|
+
`)}`),process.exit(oe)}function cr(e){let t=new Set;return{text:e.replace(Sx,(s,r)=>{let o=r.toLowerCase();return t.add(o),`<!${o}>`}),kinds:t}}async function Qo(e,t,n){if(!t.startsWith("D"))return;try{let s=F(await Nn(e,t,n)),r=F(s.channel);return r.is_im===!0&&typeof r.user==="string"?r.user:void 0}catch{return}}async function ym(e,t,n,s){let r=new Map;if(t.threadParentTs||t.replyCount!==0)try{let l=F(await Pe(e,t.channelId,t.threadParentTs??t.ts,100,t.cookie));for(let u of z(l.messages).map(F))r.set(String(u.ts),u)}catch(l){console.error(` (could not read the thread's follow-up notes: ${l instanceof Error?l.message:String(l)})`)}if(!t.threadOnly&&!t.threadParentTs)try{let l=F(await ot(e,t.channelId,30,t.ts,void 0,t.cookie,!0)),u=z(l.messages).map(F),a=u.filter((c)=>Number(c.ts)>Number(t.ts)&&(t.askerBotId&&c.bot_id===t.askerBotId||t.askerUserId&&c.user===t.askerUserId)).reduce((c,d)=>Math.min(c,Number(d.ts)),1/0);for(let c of u)if(Number(c.ts)<a&&!r.has(String(c.ts)))r.set(String(c.ts),c)}catch(l){console.error(` (could not read the DM's follow-up notes: ${l instanceof Error?l.message:String(l)})`)}let o=[...r.values()].filter((l)=>Number(l.ts)>Number(t.ts)).filter((l)=>!n||Number(l.ts)>Number(n)).filter((l)=>t.isAnswerer(l.user)&&!l.bot_id).filter((l)=>typeof l.subtype!=="string"||gm.has(l.subtype)).filter((l)=>typeof l.text==="string"&&l.text.trim()!==""&&!co(l.text)).sort((l,u)=>Number(l.ts)-Number(u.ts)).filter((l)=>!s(l)),i=[];for(let l of o){let u="";try{u=await Ln(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 Rt(...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 r=s.user;try{r=await Re(e,s.user,t.cookie)}catch{}for(let[o,i]of s.text.split(`
|
|
518
|
+
`).entries())console.error(` ${o?" ".repeat(M(r).length+2):`${M(r)}: `}${M(i)}`)}}if(n.status==="answered")console.error(` To pick up later notes: ${Wn(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}function bm(e,t,n=!1){let{channelId:s,ts:r,reactable:o,threadOnly:i,audience:l,broadcast:u,cookie:a}=t,c=Be[t.lang],d={explainNow:[],explainPosted:!1},{askerUserId:f,askerBotId:p}=t,g=(N)=>typeof N==="string"&&!!N&&N!==f&&(u||l.has(N)),h=(N)=>{if(d.replyCount=Number(N.reply_count)||0,typeof N.text==="string")d.ownText=N.text},m=(N)=>{let J=typeof N.text==="string"?Ct(N.text):void 0;if(J?.kind==="void")d.voided=J;return!!d.voided};function y(N){let J=z(N.reactions).map(F),H=[];for(let O=0;O<o.length;O++){let ee=J.find((j)=>j.name===Fe[O].name),X=ee?z(ee.users).filter(g):[];if(X.length)H.push({index:O,users:X})}return H}async function w(N,J){if(n)return;let H=typeof N.text==="string"?N.text:"";if(!H)return;let O=ao(H,J,t.lang);if(O===H)return;try{await jt(e,s,r,O,a,!0)}catch(ee){console.error(` (could not add the notice to the question text: ${ee instanceof Error?ee.message:String(ee)})`)}}let D=new Set;function k(N){for(let J of z(N.reactions).map(F)){if(typeof J.name!=="string"||!Zf.includes(J.name))continue;let H=J.name===Nt?"\u2795":"\u2753";for(let O of z(J.users).filter(g)){if(D.has(O))continue;if(D.add(O),!n)console.error(` (<@${O}> pressed ${H} other; waiting for their reply)`)}}}let _=new Set,E=new Map,S=!1;async function x(N){if(N==="USLACKBOT")return!0;let J=E.get(N);if(J!==void 0)return J;try{let H=F(F(await as(e,N,a)).user).is_bot;if(typeof H!=="boolean")return null;return E.set(N,H),H}catch{return null}}async function R(){let N=t.threadParentTs??r;try{let J,H=0;for(;;){let O=F(await Ac(e,s,N,{oldest:r,...J?{cursor:J}:{}},a));if(z(O.messages).map(F).some((ee)=>Number(ee.ts)>Number(r)&&co(ee.text)))return"exists";if(J=String(F(O.response_metadata).next_cursor??"")||void 0,!J)break;if(++H>=kx)return"exists"}}catch(J){return console.error(` (could not read the thread, so the explain-request note has not been posted yet: ${J instanceof Error?J.message:String(J)})`),"unread"}try{await Bt(e,s,c.explainNote,N,!1,a,!0)}catch(J){return console.error(` (could not post the explain-request note to the thread: ${J instanceof Error?J.message:String(J)})`),"failed"}return"posted"}async function L(N){let J=z(N.reactions).map(F).find((O)=>O.name===rn),H=[];for(let O of J?z(J.users).filter(g):[]){if(await x(O)!==!1)continue;if(H.push(O),_.has(O))continue;if(_.add(O),!n)console.error(` (<@${O}> pressed \u2139\uFE0F explain \u2014 not an answer. Explain in the thread; still waiting for an answer)`)}if(d.explainNow=H,H.length&&!S&&!n){let O=await R();if(O!=="unread")S=!0,d.explainPosted=O==="posted"}}async function v(N){if(t.explain)await L(N);if(o.length)k(N);let J=y(N);if(J.length<=1&&io(typeof N.text==="string"?N.text:"").length)await w(N,[]);if(!J.length)return null;if(J.length===1){let{index:j,users:ce}=J[0];return{answer:o[j],how:c.howReaction(Fe[j].glyph),who:ce[0],choice:j+1}}let H=J.map((j)=>Fe[j.index].glyph).join(" / "),O=new Map;for(let j of J)for(let ce of j.users)O.set(ce,(O.get(ce)??0)+1);let ee=[...O].filter(([,j])=>j>1).map(([j])=>j);if(!n)console.error(ee.length?` (${H} are pressed at once; waiting until it is narrowed to one)`:` (answers are split: ${H}; waiting until they agree on one)`);let X=ee.sort();return await w(N,X),null}let P=[...o,...t.overflow];function B(N,J=1/0){let H=[...N].sort((O,ee)=>Number(O.ts)-Number(ee.ts));for(let O of H){if(!(Number(O.ts)>Number(r)))continue;if(t.after&&!(Number(O.ts)>Number(t.after)))continue;if(!g(O.user))continue;if(typeof O.subtype==="string"&&!gm.has(O.subtype))continue;if(Number(O.ts)>=J)break;let ee=typeof O.text==="string"?O.text.trim():"";if(!ee||t.explain&&co(ee))continue;if(!P.length)return{answer:ee,how:c.howReply,who:O.user,ts:String(O.ts)};let X=za(ee,P);if(X.kind==="chosen")return{answer:P[X.index-1],how:c.howReplyN(X.index),who:O.user,ts:String(O.ts),choice:X.index};let j=X.kind==="ambiguous",ce=d.unchosen;if(!ce||ce.ambiguous&&!j||ce.ambiguous===j&&Number(O.ts)<Number(ce.ts))d.unchosen={text:ee,who:typeof O.user==="string"?O.user:"",ts:String(O.ts),ambiguous:j}}return null}async function W(){if(delete d.unchosen,t.threadParentTs){let O=F(await Pe(e,s,t.threadParentTs,100,a)),ee=z(O.messages).map(F),X=ee.find((j)=>j.ts===r);if(X){if(h(X),m(X))return null;let j=await v(X);if(j)return j}return B(ee)}let N=F(await ot(e,s,30,r,void 0,a,!0)),J=z(N.messages).map(F),H=J.find((O)=>O.ts===r);if(H){if(h(H),m(H))return null}if(H){let O=await v(H);if(O)return O}if(!i){let O=J.filter((X)=>Number(X.ts)>Number(r)&&(p&&X.bot_id===p||f&&X.user===f)).reduce((X,j)=>Math.min(X,Number(j.ts)),1/0),ee=B(J,O);if(ee)return ee}if(H&&Number(H.reply_count)>0){let O=F(await Pe(e,s,r,30,a)),ee=B(z(O.messages).map(F));if(ee)return ee}return null}return{poll:W,state:d,isAnswerer:g,candidates:P}}async function wm(e,t){let{channelId:n,ts:s,question:r,reactable:o,threadOnly:i,cookie:l,timeout:u,shown:a}=t,{askerUserId:c,askerBotId:d}=t,{poll:f,state:p,isAnswerer:g,candidates:h}=bm(e,t),m="";async function y(x){for(let L=0;L<o.length;L++)try{await Wt(e,n,s,Fe[L].name,l)}catch{}let R="";if(x.who)try{R=await Re(e,x.who,l)}catch{R=x.who}if(R)console.error(` Answered by: ${M(R)}`);try{let L=p.ownText?sp(p.ownText,x.choice):void 0;await jt(e,n,s,np(r,x,R,t.lang,L),l,!0);try{await Ft(e,n,s,Ka,l),await Wt(e,n,s,t.seedMarker,l)}catch{}try{if(t.explain)await Wt(e,n,s,rn,l)}catch{}}catch(L){console.error(` (failed to update the original message: ${L instanceof Error?L.message:String(L)})`)}}let w=Date.now()+u*1000,D=Date.now(),k=0,_=Rn.minMs,E=0,S;for(;;){let x=null;try{x=await f(),k=0}catch(L){if(L instanceof rt)E=L.retryAfter*1000;else{if(k++,k>=Xg)console.error(`Error: Slack requests failed ${k} times in a row: ${L instanceof Error?L.message:String(L)}`),process.exit(oe);console.error(` (Slack error ${k}/${Xg}, retrying: ${L instanceof Error?L.message:String(L)})`)}}S=p.unchosen;let R=p.voided;if(R){if(km(R,a),t.json)await un(e,t,{status:"void",answer:null,reason:R.reason,...R.supersededBy?{supersededBy:R.supersededBy}:{},notes:[],cursor:Rt(s,t.after)});process.exit(zo)}if(x){let L=await ym(e,{channelId:n,ts:s,threadOnly:i,replyCount:p.replyCount,isAnswerer:g,askerUserId:c,askerBotId:d,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...l?{cookie:l}:{}},t.after,(P)=>P.ts===x.ts);await y(x);let v={status:"answered",answer:x.answer,how:x.how,notes:L,cursor:Rt(s,t.after,x.ts,...L.map((P)=>P.ts))};if(kc(n,s,x.answer,v.cursor),x.who)v.who=x.who;await un(e,t,v),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: ${Wn(a,t.asBot,t.after)}`),t.json)await un(e,t,{status:"explain",answer:null,notes:[],cursor:Rt(s,t.after),explain:p.explainNow});process.exit(wx)}if(S&&!S.ambiguous){let L=S.who;try{if(L)L=await Re(e,L,l)}catch{}if(console.error(` (${M(L)} replied with something that is not a choice \u2014 not a decision. Printing the reply on stdout)`),console.error(` Choices: ${h.map((v,P)=>`${P+1}. ${M(Ne(v))}`).join(" ")}`),console.error(` ${a}`),console.error(` To wait for what comes after this reply: ${Wn(a,t.asBot,S.ts)}`),Dc(n,s,S.text,Rt(s,t.after,S.ts)),t.json)await un(e,t,{status:"freetext",answer:S.text,who:S.who,notes:[],cursor:Rt(s,t.after,S.ts),explain:p.explainNow});else console.log(S.text);process.exit(bx)}if(S&&S.ts!==m){m=S.ts;let L=S.who;try{if(L)L=await Re(e,L,l)}catch{}console.error(` (${M(L)}'s reply matches several choices; waiting until it is narrowed to one)`),console.error(` "${M(S.text)}"`)}if(Date.now()>=w)break;await xx(Math.min(Math.max(_,E),Math.max(0,w-Date.now()))),E=0,_=lp(_,Date.now()-D)}if(S){if(console.error("Error: there was a reply, but it matches several choices so it cannot be settled (the message is left in place)"),console.error(` Reply: "${M(S.text)}"`),console.error(` Choices: ${h.map((x,R)=>`${R+1}. ${M(Ne(x))}`).join(" ")}`),console.error(` ${a}`),console.error(` Reply in the thread, then collect with: ${Wn(a,t.asBot,t.after)}`),t.json)await un(e,t,{status:"ambiguous",answer:null,notes:[],cursor:Rt(s,t.after),explain:p.explainNow});process.exit(yx)}if(u===0)console.error(`No answer yet: ${a}`);else console.error(`Error: no answer within ${u}s (the message is left in place)`),console.error(` ${a}`),console.error(` To collect later: ${Wn(a,t.asBot,t.after)}`);if(t.json)await un(e,t,{status:"timeout",answer:null,notes:[],cursor:Rt(s,t.after),explain:p.explainNow});process.exit(mx)}function Wn(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function _x(e,t){let{ref:n,threadTs:s}=St(t.target,!1),r=t.cookie,o=qt(e,r),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Ut(e,t.userId,r);else i=await we(e,n,r);let l=(await o())?.userId??"",u=await Qo(e,i,r),a=sc();if(!t.asBot&&!!l&&u===l){if(console.error(`${a?"Error":"Warning"}: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
|
|
519
|
+
`+` To reach yourself with a notification, ask as the bot: slack @<bot> ask '${t.target}' '...' (or --as-bot)`),a)process.exit(oe)}let c=cr(je(t.question)),d=cr(je(t.body??"")),f=new Set([...c.kinds,...d.kinds]);for(let te of`${c.text}
|
|
520
|
+
${d.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))f.add(te[1]);let p=t.mentionToken??e,g=await ln(p,c.text,i,t.mentionCookie),h=d.text?await ln(p,d.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},m=g.text,y=h.text,w=[...g.resolved,...h.resolved],D=[...g.unresolved,...h.unresolved];mm(D);let k=!!l&&(w.some((te)=>te.userId===l)||new RegExp(`<@${l}(?:\\|[^>]*)?>`).test(`${m}
|
|
521
|
+
${y}`));if(a&&!t.asBot&&k)console.error(`Error: \`ask\` would post as you (${l}) a question addressed to you \u2014 the asker and the one asked are the same person.
|
|
522
|
+
`+` To ask yourself, ask as the bot: slack @<bot> ask '${t.target}' '${t.question}' (or --as-bot)
|
|
523
|
+
To ask someone else as yourself, tag them, not you.`),process.exit(oe);let _=f.size>0,E=new Set(w.map((te)=>te.userId).filter((te)=>te!==l)),S=new Map(w.map((te)=>[te.userId,te.display]));for(let te of`${m}
|
|
524
|
+
${y}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)){let fe=te[1];if(fe===l||E.has(fe))continue;E.add(fe),S.set(fe,await Re(p,fe,t.mentionCookie))}let x;if(_)x=`anyone in ${n} (${[...f].map((te)=>`@${te}`).join(", ")})`;else{if(!E.size&&u&&u!==l)E.add(u),S.set(u,await Re(e,u,r));if(!E.size)console.error("Error: `ask` will not post a question nobody is addressed to \u2014 no one is tagged.\n"+` Tag the person who should answer: slack ask '${t.target}' '@alice ${t.question}' ...
|
|
522
525
|
Or open it to the whole channel: slack ask '${t.target}' '@here ${t.question}' ...
|
|
523
|
-
(In a 1:1 DM the other person counts automatically.)`),process.exit(
|
|
524
|
-
`)[0]??"").slice(0,100)}`,...
|
|
525
|
-
`)[0]??"")}) \u2014 cannot be changed`),null;if(c.kind!=="open")return console.error(`\u2717 ${o}: cannot be read as a \`slack ask\` question \u2014 ${
|
|
526
|
+
(In a 1:1 DM the other person counts automatically.)`),process.exit(oe);x=[...E].map((te)=>`@${M(S.get(te)??te)} (${te})`).join(", ")}let R=t.choices.map(je),L=R.slice(0,Lt),v=R.slice(Lt),P=!i.startsWith("D")||!!s,B=_?[]:await Promise.all([...E].map((te)=>tg(p,te,t.mentionCookie))),W=Ua({flag:t.lang,readerLocales:B,content:[m,y,...L,...v]});if(!W)console.error(`Error: unsupported language "${M(t.lang??process.env.SLACK_TERM_LANG??"")}" \u2014 use one of: ${$t.join(", ")}`),process.exit(oe);let N=W.lang,J=t.explain??Dx(),H=Ha(m,y,L,v,P,N,J);Ke(H,t.allowUrlAdjacent);let O="",ee="?";try{let te=await ot(e,i,1,void 0,void 0,r),fe=z(te.messages).map(F).filter((be)=>be.subtype===void 0||be.subtype===null)[0];O=typeof fe?.text==="string"?fe.text:"",ee=typeof fe?.user==="string"?await Re(e,fe.user,r):typeof fe?.username==="string"?fe.username:"?"}catch{}let X=await o(),j=await Vo(e,i,r),ce=De(i,s??"",O,H,X?.userId??"",...t.voidAfter?["reask",`${t.voidAfter.channelId}:${t.voidAfter.ts}`,t.voidAfter.reason]:[]);if(t.code!==ce){let te=await Jt(e,i,n,r),fe=L.length?["--- Choices (seeded as reactions) ------------",...L.map((be,fn)=>` ${Fe[fn].glyph} ${Ne(be)}`),...v.map((be,fn)=>` (${fn+11}) ${Ne(be)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];Se(t.code,ce,["--- Last message in channel ------------------",` ${ee}: ${fs(O.split(`
|
|
527
|
+
`)[0]??"").slice(0,100)}`,...fe,"--- Asking -----------------------------------",Ee(X,{asBot:t.asBot}),` \u2192 ${te}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${m}`,` Answerable by: ${x}`,` Via: ${P?"reactions or thread replies":"reactions or replies in this DM"}`,...J?[" Explain: \u2139\uFE0F pill offered \u2014 pressing it asks you to explain; it is never an answer"]:[],...t.voidAfter?[` Then void: ${M(t.voidAfter.link)} (reason: ${M(t.voidAfter.reason||"none")}) \u2014 replaced by this question`]:[],` Language: ${N} (${{flag:"--lang",env:"SLACK_TERM_LANG",readers:"answerers' Slack locale",content:"the question's text",system:"system locale",default:"default"}[W.source]}; override with --lang)`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],j)}let K=Un("ask"),ue=await Bt(e,i,H,s,!1,r,!0,K.metadata),le=L.length?Nt:st;await xo([...L.map((te,fe)=>Fe[fe].name),le,...J?[rn]:[]],(te)=>Ft(e,i,ue,te,r),(te,fe)=>{let be=fe instanceof Error?fe.message:String(fe);if(te===le)console.error(` (could not add marker ${te}: ${be})`);else console.error(` (could not add reaction ${te}: ${be})`)});let q="";try{q=await Ln(e,i,ue,r)}catch{}let re=q||`${i}:${ue}`;if(console.error(`\u2713 Asked: ${re}`),K.record({team:X?.team,channel:i,target:t.target,ts:ue,threadTs:s,permalink:q,text:H,asBot:t.asBot}),t.voidAfter){if(!await xm(e,t.voidAfter,t.voidAfter.reason,re,r))console.error(` \u26A0 The new question is posted, but the old one could not be voided \u2014 do it by hand: slack ask --void='${M(t.voidAfter.link)}' --superseded-by='${re}'`)}if(!t.wait){console.log(Wn(re,!!t.asBot));return}let pe=t.timeout??3600;console.error(` Waiting for an answer (up to ${pe}s)\u2026 Ctrl-C to stop`);let Y={channelId:i,ts:ue,question:m,reactable:L,overflow:v,threadOnly:P,seedMarker:le,lang:N,audience:E,broadcast:_,askerUserId:X?.userId??"",askerBotId:X?.botId??"",timeout:pe,shown:re,asBot:!!t.asBot,json:!!t.json,explain:J,explainExit:!!t.explainExit};if(s)Y.threadParentTs=s;if(r)Y.cookie=r;await wm(e,Y)}function km(e,t){if(console.error(`This question is void \u2014 it will never be answered. Stop waiting on it: ${M(t)}`),e.reason)console.error(` ${M(e.reason)}`);if(e.supersededBy)console.error(` New question: ${M(e.supersededBy)}`)}async function ll(e,t,n){let s=ft(t),r,o,i;if(s?.ts)r=s.channel,o=s.ts,i=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let l=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!l)return null;r=l[1],o=l[2]}return lr(e,{channelId:r,ts:o,threadTs:i},n)}async function lr(e,t,n){let{channelId:s,ts:r}=t,o=t.threadTs&&t.threadTs!==t.ts?t.threadTs:void 0,i;if(o){let u=F(await Pe(e,s,o,100,n));i=z(u.messages).map(F).find((a)=>a.ts===r)}else{let u=F(await ot(e,s,1,r,void 0,n,!0));i=z(u.messages).map(F).find((a)=>a.ts===r)}let l={channelId:s,ts:r};if(o)l.threadTs=o;if(i)l.msg=i;return l}async function Dm(e,t,n,s,r){let o=M(t),i=await ll(e,t,r);if(!i)return console.error(`\u2717 ${o}: not a permalink (or 'C\u2026:1700000000.000100')`),null;if(!i.msg)return console.error(`\u2717 ${o}: message not found`),null;let l=i.msg;if(!(!!n?.userId&&l.user===n.userId||!!n?.botId&&l.bot_id===n.botId))return console.error(`\u2717 ${o}: not a question posted by you (${Zo(n,s)})${s?"":" \u2014 if the bot posted it, use --as-bot"}`),null;let a=typeof l.text==="string"?l.text:"",c=Ct(a);if(c.kind==="void")return"void";if(c.kind==="resolved")return console.error(`\u2717 ${o}: already answered (answer: ${M(c.answer.split(`
|
|
528
|
+
`)[0]??"")}) \u2014 cannot be changed`),null;if(c.kind!=="open")return console.error(`\u2717 ${o}: cannot be read as a \`slack ask\` question \u2014 ${Ws(a)}`),null;let d={link:t,channelId:i.channelId,ts:i.ts,parsed:c,seedMarker:Us(a)??st,msg:l};if(i.threadTs)d.threadTs=i.threadTs;return d}async function Ex(e,t,n,s){let r=(i)=>typeof i==="string"&&i!==n?.userId;if(z(t.msg.reactions).map(F).some((i)=>Fe.some((l)=>l.name===i.name)&&z(i.users).some(r)))return!0;if(Number(t.msg.reply_count)>0){let i=F(await Pe(e,t.channelId,t.ts,100,s));if(z(i.messages).map(F).some((l)=>Number(l.ts)>Number(t.ts)&&r(l.user)&&!l.bot_id))return!0}if(t.channelId.startsWith("D")){let i=F(await ot(e,t.channelId,30,t.ts,void 0,s,!0));if(z(i.messages).map(F).some((l)=>Number(l.ts)>Number(t.ts)&&r(l.user)&&!l.bot_id))return!0}return!1}async function $x(e,t){let n=await Me(e,t.cookie),s=await Dm(e,t.link,n,t.asBot,t.cookie);if(s==="void")console.error(`\u2717 ${M(t.link)}: a voided question cannot be edited`),process.exit(oe);if(!s)process.exit(oe);let r=s.parsed,o=async(E)=>{let S=cr(je(E)),x=await ln(t.mentionToken,S.text,s.channelId,t.mentionCookie);return mm(x.unresolved),x.text},i=t.question!==void 0?await o(t.question):r.question,l=t.body!==void 0?await o(t.body):r.body,u=[...r.reactable,...r.overflow],a=t.choices?t.choices.map(je):u,c=JSON.stringify(a.map(Ne))!==JSON.stringify(u.map(Ne));if(c&&await Ex(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.
|
|
526
529
|
`+` The question and body can still be changed. To change the choices, void it and ask again:
|
|
527
|
-
slack ask --void='${
|
|
528
|
-
${l}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].some((
|
|
529
|
-
${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(
|
|
530
|
+
slack ask --void='${M(t.link)}' --reask${t.asBot?" --as-bot":""} \u2026`),process.exit(oe);if(!([...`${i}
|
|
531
|
+
${l}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].some((E)=>E[1]!==n?.userId)||/<!(?:here|channel|everyone)/.test(`${i}
|
|
532
|
+
${l}`)||s.channelId.startsWith("D")))console.error("\u2717 The question would be addressed to nobody \u2014 keep an @mention of who can answer"),process.exit(oe);let p=t.lang?Ua({flag:t.lang})?.lang??r.lang:r.lang,g=a.slice(0,Lt),h=a.slice(Lt),m=typeof s.msg.text==="string"?s.msg.text:"",y=Ha(i,l,g,h,r.threadOnly,p,r.explain),w=io(m);if(w.length)y=ao(y,w,p);if(Ke(y,t.allowUrlAdjacent),y===m){console.error("No changes.");return}let D=De("ask-edit",`${s.channelId}:${s.ts}`,y,n?.userId??"");if(t.code!==D){let E=(S,x,R)=>x===R?[` ${S}: (unchanged)`]:[` ${S}:`,...x.split(`
|
|
530
533
|
`).map((L)=>` - ${L}`),...R.split(`
|
|
531
|
-
`).map((L)=>` + ${L}`)];
|
|
532
|
-
(${Tt()})`),process.exit(
|
|
533
|
-
`)[0]??"").replace(/^:question: /,""),f;if(u)try{let g=await
|
|
534
|
-
${
|
|
535
|
-
slack ask ${u.map((a)=>`--void='${a.link}'`).join(" ")} --reason 'stale'${l?" --as-bot":""}`)}}async function Ax(e,t,n){if(n.has(e.channel))return n.get(e.channel);let s={channelId:e.channel,ts:e.ts,threadTs:e.thread_ts??void 0},r=async(i)=>{if(!i)return!1;try{return await
|
|
536
|
-
(${Tt()})`),process.exit(
|
|
537
|
-
`)[0]??"")})`),r++;continue}if(p.kind!=="open"){let y=
|
|
538
|
-
${
|
|
534
|
+
`).map((L)=>` + ${L}`)];Se(t.code,D,["--- Editing question --------------------------",Ee(n,{asBot:t.asBot}),` ${M(t.link)}`,...E("Question",r.question,i),...E("Body",r.body,l),...c?[" Choices (nobody has answered yet \u2014 pills are re-seeded):",...u.map((S,x)=>` - ${x+1}. ${Ne(S)}`),...a.map((S,x)=>` + ${x+1}. ${Ne(S)}`)]:[" Choices: (unchanged)"],...p!==r.lang?[` Language: ${r.lang} \u2192 ${p} (the instructions are rewritten)`]:[],"----------------------------------------------"])}await jt(e,s.channelId,s.ts,y,t.cookie,!0);let k=g.length?Nt:st,_=Us(m)??st;if(c){let E=(S)=>r.explain?[S,rn]:[S];for(let S of[...r.reactable.map((x,R)=>Fe[R].name),...E(_)])try{await Wt(e,s.channelId,s.ts,S,t.cookie)}catch{}await xo([...g.map((S,x)=>Fe[x].name),...E(k)],(S)=>Ft(e,s.channelId,s.ts,S,t.cookie),(S,x)=>console.error(` (could not add reaction ${S}: ${x instanceof Error?x.message:String(x)})`))}else if(_!==k)try{await Ft(e,s.channelId,s.ts,k,t.cookie),await Wt(e,s.channelId,s.ts,_,t.cookie)}catch(E){console.error(` (could not swap the marker to ${k}: ${E instanceof Error?E.message:String(E)})`)}console.error(`\u2713 Edited: ${M(t.link)}`)}async function Cx(e,t){let n={kind:"ask",limit:t.limit};if(t.channel)n.channel=t.channel;let s=wc(n);if(!s)console.error(`Error: ${Gs}
|
|
535
|
+
(${Tt()})`),process.exit(oe);let r;if(t.stale){if(r=is(t.stale),r===void 0)console.error(`Error: --stale needs a duration like 24h / 3d (got ${M(t.stale)})`),process.exit(oe)}let o=[];for(let l of s){if(r!==void 0&&l.sent_at>r)continue;let u=l.as_bot?e.bot:e.user,a=l.permalink||`${l.channel}:${l.ts}`,c="unknown",d=(l.text.split(`
|
|
536
|
+
`)[0]??"").replace(/^:question: /,""),f;if(u)try{let g=await lr(u,{channelId:l.channel,ts:l.ts,threadTs:l.thread_ts??void 0},l.as_bot?void 0:e.cookie);if(!g.msg)c="gone";else{let h=Ct(typeof g.msg.text==="string"?g.msg.text:"");if(c=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{c="unknown"}if(t.state!=="all"&&c!==t.state)continue;let p={state:c,age_h:Math.round((Date.now()-l.sent_at)/3600000),asBot:!!l.as_bot,channel:l.channel,target:l.target??l.channel,link:a,question:Ne(d)};if(f!==void 0)p.answer=f;o.push(p)}if(t.json)console.log(JSON.stringify(o));else{for(let l of o)console.log(`${l.state.padEnd(8)} ${String(l.age_h).padStart(4)}h ${l.asBot?"bot ":"user"} ${M(l.target)} ${l.link}
|
|
537
|
+
${M(l.question).slice(0,100)}`);console.error(`${o.length} question(s)${t.state==="all"?"":` in state "${t.state}"`}${t.stale?`, older than ${t.stale}`:""}.`)}let i=o.filter((l)=>l.state==="open");if(t.stale&&i.length)for(let l of[!1,!0]){let u=i.filter((a)=>a.asBot===l);if(!u.length)continue;console.error(`To void them (${u.length}, ${l?"bot":"user"}):
|
|
538
|
+
slack ask ${u.map((a)=>`--void='${a.link}'`).join(" ")} --reason 'stale'${l?" --as-bot":""}`)}}async function Ax(e,t,n){if(n.has(e.channel))return n.get(e.channel);let s={channelId:e.channel,ts:e.ts,threadTs:e.thread_ts??void 0},r=async(i)=>{if(!i)return!1;try{return await lr(i,s),!0}catch(l){if(l instanceof rt)throw l;return/channel_not_found|not_in_channel/.test(l instanceof Error?l.message:String(l))?!1:void 0}},o;if(await r(t)===!1)for(let[i,l]of go()){if(l.kind!=="bot"||i===process.env.SLACK_TERM_IDENTITY)continue;let u={...process.env};if("error"in mo(i,u))continue;if(await r(u.SLACK_BOT_TOKEN)){o=i;break}}return n.set(e.channel,o),o}function Tx(e,t){if(!e.identity||e.identity===process.env.SLACK_TERM_IDENTITY)return t;let n={...process.env},s=mo(e.identity,n);if("error"in s)return s.error;if(s.kind==="bot")return{bot:n.SLACK_BOT_TOKEN,user:n.SLACK_TOKEN};if(!n.SLACK_TOKEN)return`asked as @${e.identity}, a profile identity: run the pass as that identity`;return{user:n.SLACK_TOKEN}}async function Vg(e,t){let n=[];$c(0);let s=xc(t.sinceMs);if(!s)console.error(`Error: ${Gs}
|
|
539
|
+
(${Tt()})`),process.exit(oe);let r=Date.now()-86400000,o=s.filter((m)=>(!t.channel||m.channel===t.channel||m.target===t.channel)&&(!t.only||t.only.has(`${m.channel}:${m.ts}`))&&(!t.skip||m.sent_at>=r||!t.skip.has(`${m.channel}:${m.ts}`))),i=[],l={unanswered:0,ambiguous:0,resolved:0,void:0,explain:0,throttled:0},u=[],a=[],c=e.user?(await Me(e.user,e.cookie))?.team??"":e.bot?(await Me(e.bot))?.team??"":"",d=new Map,f=new Map;o.reverse();for(let[m,y]of o.entries()){if(y.team&&c&&y.team!==c){d.set(y.team,(d.get(y.team)??0)+1);continue}let w=y.permalink||`${y.channel}:${y.ts}`,D=!!y.as_bot;n.push(`${y.channel}:${y.ts}`);let k=y.delivered_cursor??void 0;try{if(!y.identity&&D){let O=await Ax(y,e.bot,f);if(O){if(y.identity=O,t.push)bh(y.channel,y.ts,O)}}let _=Tx(y,e);if(typeof _==="string"){a.push(`${w}: ${_}`);continue}let E=D?_.bot:_.user;if(!E){a.push(`${w}: ${D?"asked with --as-bot, but there is no bot token":"no user token"}`);continue}let S=D?void 0:_.cookie,x={channelId:y.channel,ts:y.ts,threadTs:y.thread_ts??void 0},R=await lr(E,x,S);if(!R.msg){a.push(`${w}: message not found (deleted?)`);continue}let L=await Sm(E,{channelId:y.channel,ts:y.ts,msg:R.msg},S),v=L.parsed;if(v.kind==="resolved"){if(l.resolved++,t.push)$o(y.channel,y.ts,0);continue}if(v.kind==="void"){if(l.void++,t.push)$o(y.channel,y.ts,zo);continue}if(v.kind==="other"){a.push(`${w}: cannot be read as a \`slack ask\` question \u2014 ${Ws(L.text)}`);continue}if(!L.audience.size&&!L.broadcast){a.push(`${w}: the question is addressed to nobody`);continue}let P=_m(L,v,x,{timeout:0,link:w,asBot:D,json:!1,cookie:S,after:k}),B=bm(E,P,!0),W=await B.poll(),N=B.state.unchosen;if(B.state.voided){if(l.void++,t.push)$o(y.channel,y.ts,zo);continue}let J=Wn(w,D,k);if(B.state.explainNow.length)l.explain++,u.push(`${w}: \u2139\uFE0F an explanation was requested (${B.state.explainNow.map((O)=>`<@${O}>`).join(" ")}) \u2014 explain in the thread`);let H={row:y,link:w,question:v.question,collect:J,alive:wh(y)};if(W)i.push({...H,answer:W.answer,how:W.how,freeText:!1,...W.ts?{answeredTs:W.ts}:{}});else if(N&&!N.ambiguous&&N.text!==y.delivered_answer)i.push({...H,answer:N.text,how:"reply (not a choice)",freeText:!0,cursor:Rt(y.ts,k,N.ts),answeredTs:N.ts});else if(N?.ambiguous)l.ambiguous++;else l.unanswered++}catch(_){if(_ instanceof rt){n.pop(),l.throttled=o.length-m,a.push(`rate-limited by Slack (${_.message}): ${l.throttled} question(s) not checked this pass`);break}a.push(`${w}: ${_ instanceof Error?_.message:String(_)}`)}}if(t.push)Ox(i,t.selfArgs??[],a);let p=(m)=>!m.pushed&&m.row.pushed_answer!==m.answer,g=t.watch?i.filter((m)=>m.pushed):t.undelivered?i.filter(p):i,h={checked:n,throttled:l.throttled>0};if(t.watch&&!g.length&&!a.length)return h;if(t.json)for(let m of g){let y=m.row;console.log(JSON.stringify({id:y.id,link:m.link,channel:y.channel,ts:y.ts,asked_at:y.sent_at,question:m.question,answer:m.answer,how:m.how,free_text:m.freeText,sender:{session_id:y.session_id??null,cli:y.cli??null,agent_pid:y.agent_pid??null,pid:y.pid,alive:m.alive,cwd:y.cwd,git_branch:y.git_branch??null,host:y.host??null},delivered_at:y.delivered_at??null,collect:m.collect,...t.push?{pushed:m.pushed??null}:{},...m.undelivered?{undelivered:m.undelivered}:{}}))}else{let m=new Map;for(let y of g){let w=y.row.session_id?`session ${y.row.session_id}`:`pid ${y.row.agent_pid??y.row.pid}`;m.set(w,[...m.get(w)??[],y])}for(let[y,w]of m){let D=w[0].row;console.log(`${M(y)} ${M(D.cli??"?")} pid ${D.agent_pid??D.pid} ${w[0].alive?"(alive)":"(gone)"}${D.git_branch?` branch=${M(D.git_branch)}`:""} cwd=${M(D.cwd)}`);for(let k of w){if(console.log(` ${M(k.link)} (${jn(k.row.sent_at/1000)})`),console.log(` Q: ${M(Ne(k.question))}`),console.log(` A: ${M(Ne(k.answer))} \u2014 ${M(k.how)}${k.freeText?" \u2014 not a decision":""}`),console.log(` collect: ${M(k.collect)}`),k.undelivered)console.log(` undelivered: ${M(k.undelivered)}`);if(k.pushed)console.log(` pushed to pid ${k.pushed.pid}${k.pushed.collected?", collected \u2705":""}`)}}}for(let m of a)console.error(` (${M(m)})`);for(let m of u)console.error(` (${M(m)})`);for(let[m,y]of d)console.error(` (${y} question(s) belong to another workspace "${M(m)}" \u2014 check with slack -w <name> ask --pending)`);return console.error(`${i.length} answered but not collected, ${l.unanswered} unanswered`+(l.ambiguous?`, ${l.ambiguous} with a reply matching several choices (unsettled)`:"")+(l.resolved?`, ${l.resolved} \u2705 already collected`:"")+(l.void?`, ${l.void} voided`:"")+(l.explain?`, ${l.explain} with an \u2139\uFE0F explain request`:"")+(l.throttled?`, ${l.throttled} not checked (rate-limited)`:"")+(t.push?`, ${i.filter((m)=>m.pushed).length} pushed to the asker`:"")+(t.undelivered?`, ${i.filter(p).length} undelivered`:"")+` \u2014 checked ${o.length} uncollected question(s) (log: ${Tt()})`),h}async function Fx(e,t,n){let s=!1,r=new Set,o=!0,i=async()=>{if(s)return;s=!0;try{while(o||r.size){let a=o?void 0:new Set(r);o=!1,r.clear();try{await e(a)}catch(c){console.error(`slack ask --watch: pass failed: ${ge(c)}`)}}}finally{s=!1}},l=process.env.SLACK_RELAY_URL,u=process.env.SLACK_RELAY_TOKEN;if(l&&u){let a=Ca(l,u,void 0,{transport:$a(process.env.SLACK_RELAY_TRANSPORT)});(async()=>{for(let c=0;;c++){try{await a(void 0,new AbortController().signal,{hello:()=>{c=0},bell:(d,f)=>{let p=`${f.channel}:${f.thread_ts??f.ts}`;if(!(xc(t())??[]).some((h)=>`${h.channel}:${h.ts}`===p))return;r.add(p),setTimeout(()=>{i()},3000)}})}catch(d){console.error(`slack ask --watch: relay: ${d instanceof Error?d.message:String(d)} \u2014 reconnecting`)}await new Promise((d)=>setTimeout(d,ts(c,2000,300000)))}})()}else console.error("slack ask --watch: no SLACK_RELAY_URL / SLACK_RELAY_TOKEN \u2014 checking every interval only");for(;;)o=!0,await i(),await new Promise((a)=>setTimeout(a,typeof n==="number"?n:n()))}function Ox(e,t,n){let s=_f(gt(process.env.XDG_STATE_HOME||gt(jo(),".local","state"),"slack-term","ask-push.lock"));if(!s){n.push("another `ask --pending --push` pass is running: nothing pushed by this one");return}try{let r;for(let o of e){let i=o.row,l=i.pushed_answer===o.answer,u=i.agent_pid??i.pid;if(!l){let c=u,d=o.alive?c:Sf(i.cwd,r??=xf());if(d===void 0){o.undelivered=`the asker (pid ${c}) is gone and no live agent runs in ${i.cwd}`;continue}let f=wf({link:o.link,answer:o.answer,how:o.how,question:o.question,freeText:o.freeText,collected:!o.freeText,...o.alive?{}:{goneAsker:c},tag:bf(i.sent_at,o.answeredTs?Number(o.answeredTs)*1000:void 0)}),p=Df(d,f);if(p===void 0){o.undelivered=`pid ${d} did not take the push over ay \u2014 tried again next pass`,n.push(`${o.link}: ${o.undelivered}`);continue}u=p,yh(i.channel,i.ts,o.answer)}else if(o.freeText)continue;let a=!1;if(o.freeText)Dc(i.channel,i.ts,o.answer,o.cursor??"");else{let c=i.delivered_cursor?[`--after=${i.delivered_cursor}`]:[],d=i.identity&&i.identity!==process.env.SLACK_TERM_IDENTITY?[`@${i.identity}`]:[],f=CD(process.execPath,[...process.argv.slice(1,2),...d,...t,"ask",`--waitFor=${o.link}`,"--timeout","0",...i.as_bot?["--as-bot"]:[],...c],{encoding:"utf8",timeout:120000,stdio:["ignore","pipe","pipe"]});if(a=f.status===0,!a)n.push(`${o.link}: pushed, but collecting it exited ${f.status??"on a signal"} \u2014 collect by hand: ${o.collect}`)}o.pushed={pid:u,collected:a}}}finally{s()}}async function xm(e,t,n,s,r){let o=M(t.link);try{let i=rp(t.parsed.question,n,t.parsed.lang,t.parsed.body||void 0,s);await jt(e,t.channelId,t.ts,i,r,!0)}catch(i){return console.error(`\u2717 ${o}: failed to rewrite: ${i instanceof Error?i.message:String(i)}`),!1}for(let i of[...t.parsed.reactable.map((l,u)=>Fe[u].name),t.seedMarker,...t.parsed.explain?[rn]:[]])try{await Wt(e,t.channelId,t.ts,i,r)}catch{}try{await Ft(e,t.channelId,t.ts,qa,r)}catch(i){console.error(` (${o}: could not add the \uD83D\uDEAB reaction: ${i instanceof Error?i.message:String(i)})`)}return console.error(`\u2713 Voided: ${o}`),!0}async function Rx(e,t){let n=await Me(e,t.cookie);if(t.supersededBy){let l=M(t.supersededBy),u=!1;try{let a=await ll(e,t.supersededBy,t.cookie);if(u=!!a?.msg,!a)console.error(`Error: --superseded-by must be a message permalink (or 'C\u2026:1700000000.000100'): ${l}`),process.exit(oe)}catch(a){console.error(`Error: cannot check --superseded-by: ${l} (${a instanceof Error?a.message:String(a)})`),process.exit(oe)}if(!u)console.error(`Error: --superseded-by message not found: ${l}`),process.exit(oe)}let s=[],r=0;for(let l of t.links){let u=M(l),a=await ll(e,l,t.cookie);if(!a){console.error(`\u2717 ${u}: not a permalink (or 'C\u2026:1700000000.000100')`),r++;continue}if(!a.msg){console.error(`\u2717 ${u}: message not found`),r++;continue}let c=a.msg;if(!(!!n?.userId&&c.user===n.userId||!!n?.botId&&c.bot_id===n.botId)){console.error(`\u2717 ${u}: not a question posted by you (${Zo(n,t.asBot)}), so it cannot be voided${t.asBot?"":" \u2014 if the bot posted it, use --as-bot"}`),r++;continue}let f=typeof c.text==="string"?c.text:"",p=Ct(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: ${M(p.answer.split(`
|
|
540
|
+
`)[0]??"")})`),r++;continue}if(p.kind!=="open"){let y=op(f);if(!y){console.error(`\u2717 ${u}: cannot be read as a \`slack ask\` question \u2014 ${Ws(f)}`),r++;continue}let w=z(c.reactions).map(F).filter((D)=>z(D.users).includes(n?.userId??"\x00")).map((D)=>Fe.findIndex((k)=>k.name===D.name)).filter((D)=>D>=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:Ja(f)??"ja",explain:z(c.reactions).map(F).some((D)=>D.name===rn&&z(D.users).includes(n?.userId??"\x00"))},g=!0}let h=g?z(c.reactions).map(F).some((y)=>y.name===Nt&&z(y.users).includes(n?.userId??"\x00"))?Nt:st:Us(f)??st,m=z(c.reactions).map(F).filter((y)=>typeof y.name==="string"&&Fe.some((w)=>w.name===y.name)).filter((y)=>z(y.users).some((w)=>w!==n?.userId)).map((y)=>`:${String(y.name)}:`);s.push({link:l,channelId:a.channelId,ts:a.ts,text:f,parsed:p,seedMarker:h,pressed:m,...g?{unreadable:g}:{}})}if(!s.length)console.error(r?"No questions can be voided.":"Nothing to do."),process.exit(r?oe:0);let o=De("ask-void",...s.map((l)=>`${l.channelId}:${l.ts}`),t.reason,t.supersededBy??"",n?.userId??"");if(t.code!==o)Se(t.code,o,["--- Void -----------------------------------------",Ee(n,{asBot:t.asBot}),` Reason: ${t.reason?M(t.reason):"(none)"}`,...t.supersededBy?[` Replaced: ${M(t.supersededBy)}`]:[],` ${s.length} question(s):`,...s.map((l)=>` \u2022 ${M(l.link)}
|
|
541
|
+
${M(l.parsed.question.split(`
|
|
539
542
|
`)[0]??"").slice(0,100)}`+(l.pressed.length?`
|
|
540
543
|
(already pressed: ${l.pressed.join(" ")} \u2014 left in place, never collected)`:"")+(l.unreadable?`
|
|
541
|
-
\u26A0 its layout no longer reads as an ask (edited by hand?) \u2014 voided from a best-effort read: question and the rest of the text kept as they are`:""))," Each becomes \uD83D\uDEAB (body kept, options and instructions removed); our pills and marker (\u2795, or \u2753) come off; a \uD83D\uDEAB reaction is added.",...r?[` (${r} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let i=0;for(let l of s)if(!await xm(e,l,t.reason,t.supersededBy,t.cookie))i++;process.exit(i||r?
|
|
542
|
-
`+` Got: ${
|
|
543
|
-
Reason: ${
|
|
544
|
-
${
|
|
545
|
-
(the pressed reactions are still there: check with slack read '${
|
|
546
|
-
`+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let a=
|
|
547
|
-
`)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...m.map((
|
|
548
|
-
`+` Got: ${
|
|
549
|
-
${
|
|
550
|
-
`+" Only the poster can rewrite a message \u2014 if the bot posted the poll, add --as-bot.")}if(a.ambiguous.length){let p=await Promise.all(a.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)=>`@${
|
|
551
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function Qg(e,t,n,s){let r=await Ot(n,e,s);return Ut(t,r)}function em(e){try{return Em(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 Em(e){if(/^\d{10,}$/.test(e))return parseInt(e,10);let t=new Date(e.replace(" ","T"));if(isNaN(t.getTime()))throw Error(`Cannot parse time: ${e}`);return Math.floor(t.getTime()/1000)}function $m(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 Bx(e,t){Ke(t.message,t.allowUrlAdjacent);let n=qt(e,t.cookie),{ref:s,threadTs:r}=St(t.target),o;if(t.channelId)o=t.channelId;else if(t.userId)o=await Ut(e,t.userId,t.cookie);else o=await
|
|
552
|
-
`+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let a=
|
|
544
|
+
\u26A0 its layout no longer reads as an ask (edited by hand?) \u2014 voided from a best-effort read: question and the rest of the text kept as they are`:""))," Each becomes \uD83D\uDEAB (body kept, options and instructions removed); our pills and marker (\u2795, or \u2753) come off; a \uD83D\uDEAB reaction is added.",...r?[` (${r} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let i=0;for(let l of s)if(!await xm(e,l,t.reason,t.supersededBy,t.cookie))i++;process.exit(i||r?oe:0)}async function Ix(e,t){let n=ft(t.link),s,r,o;if(n?.ts)s=n.channel,r=n.ts,o=n.threadTs&&n.threadTs!==n.ts?n.threadTs:void 0;else{let 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').
|
|
545
|
+
`+` Got: ${M(t.link)}`),process.exit(oe);s=h[1],r=h[2]}let i=await lr(e,{channelId:s,ts:r,threadTs:o},t.cookie);if(!i.msg)console.error(`Error: message not found: ${M(t.link)}`),process.exit(oe);let l=i.msg,u=await Sm(e,{channelId:s,ts:r,msg:l},t.cookie),{text:a,parsed:c,audience:d,broadcast:f,askerUserId:p,askerBotId:g}=u;if(c.kind==="other")console.error(`Error: this cannot be read as a \`slack ask\` question.
|
|
546
|
+
Reason: ${Ws(a)}
|
|
547
|
+
${M(t.link)}
|
|
548
|
+
(the pressed reactions are still there: check with slack read '${M(t.link)}')`),process.exit(oe);if(c.kind==="void"){if(km(c,t.link),t.json)await un(e,{json:!0,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"void",answer:null,reason:c.reason,...c.supersededBy?{supersededBy:c.supersededBy}:{},notes:[],cursor:Rt(r,t.after)});process.exit(zo)}if(c.kind==="resolved"){console.error(`\u2713 Answered: ${M(c.question)}`);let h=typeof F(l.edited).ts==="string"?String(F(l.edited).ts):void 0,m=ap(a),y=!1,w=(E)=>{if(y||!m.byReply)return!1;if(h&&Number(E.ts)>Number(h))return!1;let S=typeof E.text==="string"?E.text.trim():"",x=S===c.answer||m.n!==void 0&&(new RegExp(`^[(\uFF08]?${m.n}(?![0-9])`).test(S)||cp(S,c.answer,m.n));if(x)y=!0;return x},D=t.after,k=[];if(d.size||f){let E=(S)=>typeof S==="string"&&!!S&&S!==p&&(f||d.has(S));k=await ym(e,{channelId:s,ts:r,threadOnly:!!o||!s.startsWith("D"),replyCount:Number(l.reply_count)||0,isAnswerer:E,askerUserId:p,askerBotId:g,...o?{threadParentTs:o}:{},...t.cookie?{cookie:t.cookie}:{}},D,w)}let _=Rt(r,D,...k.map((E)=>E.ts));await un(e,{json:t.json,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"answered",answer:c.answer,notes:k,cursor:_}),kc(s,r,c.answer,_);return}if(!d.size&&!f)console.error(`Error: this question is addressed to nobody, so valid answerers cannot be determined: ${M(t.link)}`),process.exit(oe);if(t.timeout>0)console.error(` Waiting for an answer (up to ${t.timeout}s)\u2026 Ctrl-C to stop`);await wm(e,_m(u,c,{channelId:s,ts:r,threadTs:o},t))}async function Sm(e,t,n){let{msg:s}=t,r=typeof s.text==="string"?s.text:"",o=Ct(r),i=typeof s.user==="string"?s.user:"",l=typeof s.bot_id==="string"?s.bot_id:"",u=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(r),a=new Set;for(let c of r.matchAll(/<@([UW][A-Z0-9]+)>/g))if(c[1]!==i)a.add(c[1]);if(o.kind!=="other"&&!a.size&&!u){let c=await Qo(e,t.channelId,n);if(c&&c!==i)a.add(c)}return{text:r,parsed:o,audience:a,broadcast:u,askerUserId:i,askerBotId:l}}function _m(e,t,n,s){let r={channelId:n.channelId,ts:n.ts,question:t.question,reactable:t.reactable,overflow:t.overflow,threadOnly:t.threadOnly,seedMarker:Us(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)r.threadParentTs=n.threadTs;if(s.cookie)r.cookie=s.cookie;if(s.after)r.after=s.after;return r}var ht=3;function vx(e){return`slack poll --results='${e}'`}async function Px(e,t){let{ref:n,threadTs:s}=St(t.target,!1),r=t.cookie,o=qt(e,r),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Ut(e,t.userId,r);else i=await we(e,n,r);let l=(await o())?.userId??"",u=await Qo(e,i,r);if(!t.asBot&&!!l&&u===l)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
|
|
549
|
+
`+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let a=cr(je(t.question)),c=cr(je(t.body??"")),d=t.mentionToken??e,f=await ln(d,a.text,i,t.mentionCookie),p=c.text?await ln(d,c.text,i,t.mentionCookie):{text:"",resolved:[],unresolved:[]},g=f.text,h=p.text;for(let B of Io([...f.unresolved,...p.unresolved]))console.error(`\u26A0 ${M(B)}`);let m=t.choices.map(je),y=!!t.multi,w=t.until??"",D=th(g,h,m,{multi:y,deadline:w});Ke(D,t.allowUrlAdjacent);let k="",_="?";try{let B=await ot(e,i,1,void 0,void 0,r),W=z(B.messages).map(F).filter((N)=>N.subtype===void 0||N.subtype===null)[0];k=typeof W?.text==="string"?W.text:"",_=typeof W?.user==="string"?await Re(e,W.user,r):typeof W?.username==="string"?W.username:"?"}catch{}let E=await o(),S=await Vo(e,i,r),x=De(i,s??"",k,D,E?.userId??"");if(t.code!==x){let B=await Jt(e,i,n,r);Se(t.code,x,["--- Last message in channel ------------------",` ${_}: ${fs(k.split(`
|
|
550
|
+
`)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...m.map((W,N)=>` ${Dt[N].glyph} ${Hs(W)}`),"--- Posting ----------------------------------",Ee(E,{asBot:t.asBot}),` \u2192 ${B}${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 R=Un("poll"),L=await Bt(e,i,D,s,!1,r,!0,R.metadata);await xo([zs,...m.map((B,W)=>Dt[W].name)],(B)=>Ft(e,i,L,B,r),(B,W)=>{let N=W instanceof Error?W.message:String(W);if(B===zs)console.error(` (could not add marker ${B}: ${N})`);else console.error(` (could not add reaction ${B}: ${N})`)});let v="";try{v=await Ln(e,i,L,r)}catch{}let P=v||`${i}:${L}`;console.error(`\u2713 Posted: ${P}`),R.record({team:E?.team,channel:i,target:t.target,ts:L,threadTs:s,permalink:v,text:D,asBot:t.asBot}),console.log(vx(P)),console.error(` To close: slack poll --close='${P}'${t.asBot?" --as-bot":""}`)}async function Lx(e,t,n){let s=ft(t),r,o,i;if(s?.ts)r=s.channel,o=s.ts,i=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let u=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!u)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
|
|
551
|
+
`+` Got: ${M(t)}`),process.exit(ht);r=u[1],o=u[2]}let l;if(i){let u=F(await Pe(e,r,i,100,n));l=z(u.messages).map(F).find((a)=>a.ts===o)}else{let u=F(await ot(e,r,1,o,void 0,n,!0));l=z(u.messages).map(F).find((a)=>a.ts===o)}if(!l)console.error(`Error: message not found: ${M(t)}`),process.exit(ht);return{channelId:r,ts:o,msg:l}}function Zg(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,s)=>`${Dt[s].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function Nx(e,t){let{channelId:n,ts:s,msg:r}=await Lx(e,t.link,t.cookie),o=typeof r.text==="string"?r.text:"",i=Ys(o);if(i.kind==="other")console.error(`Error: this is not a \`slack poll\` poll (don't know how to count its votes).
|
|
552
|
+
${M(t.link)}`),process.exit(ht);if(i.kind==="closed"){console.error(`\u2713 Poll closed: ${M(i.question)}`);for(let p of Zg(i.tallies))console.log(p);return}let l=new Set;if(typeof r.user==="string"&&r.user)l.add(r.user);let u=await Wh(e,n,s,t.cookie),a=sh(i.choices,u,l,i.multi);console.error(`${M(i.question)}${i.deadline?` (closes ${i.deadline})`:""}`);for(let p of Zg(a.tallies))console.log(p);let c=a.tallies.reduce((p,g)=>p+g.count,0);if(console.error(` ${c} vote(s) total${i.multi?" (multiple choice)":""}`),t.names)for(let p=0;p<a.voters.length;p++){if(!a.voters[p].length)continue;let g=await Promise.all(a.voters[p].map((h)=>Re(e,h,t.cookie)));console.error(` ${Dt[p].glyph} ${g.map((h)=>`@${M(h)}`).join(", ")}`)}let d=i.multi?[]:a.ambiguous,f=ao(o,d);if(f!==o&&!t.noNotify)try{await jt(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)})
|
|
553
|
+
`+" Only the poster can rewrite a message \u2014 if the bot posted the poll, add --as-bot.")}if(a.ambiguous.length){let p=await Promise.all(a.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)=>`@${M(g)}`).join(", ")}`)}if(!t.close)return;await jt(t.writeToken??e,n,s,nh(i.question,a.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await Ft(t.writeToken??e,n,s,pc,t.writeToken?t.writeCookie:t.cookie),await Wt(t.writeToken??e,n,s,zs,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 Closed the poll: ${M(t.link)}`)}async function Mx(e){let t=await Wr(e);for(let n of Ur(t,!1))console.log(n);if(!t.ok)process.exit(1)}function Bo(){let e=Le();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
554
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function Qg(e,t,n,s){let r=await Ot(n,e,s);return Ut(t,r)}function em(e){try{return Em(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 Em(e){if(/^\d{10,}$/.test(e))return parseInt(e,10);let t=new Date(e.replace(" ","T"));if(isNaN(t.getTime()))throw Error(`Cannot parse time: ${e}`);return Math.floor(t.getTime()/1000)}function $m(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 Bx(e,t){Ke(t.message,t.allowUrlAdjacent);let n=qt(e,t.cookie),{ref:s,threadTs:r}=St(t.target),o;if(t.channelId)o=t.channelId;else if(t.userId)o=await Ut(e,t.userId,t.cookie);else o=await we(e,s,t.cookie);let i=Em(t.at),l=new Date(i*1000).toISOString(),u=await n();if(!t.asBot&&await gl(e,o,u?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
|
|
555
|
+
`+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let a=De(o,t.message,String(i),u?.userId??""),c=t.targetOverride?` [${t.targetOverride} \u2192 ${o}]`:"";if(t.code!==a){let f=await Vo(e,o,t.cookie);Se(t.code,a,["--- Scheduling message -----------------------",Ee(u,{asBot:t.asBot,pad:9}),` To: ${s}${r?` (thread ${r})`:""}${c}`,` At: ${$m(i)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(i*1000))}let d=await Lh(e,o,t.message,i,r,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:
|
|
553
556
|
`+` slack schedule ls --as-bot
|
|
554
|
-
slack schedule rm '${t.target}' ${d} --as-bot`),o.startsWith("D"))try{let f=await
|
|
555
|
-
`)[0]?.slice(0,80)??""}`)}}async function nm(e,t){let n;if(t.channelId)n=t.channelId;else n=await
|
|
556
|
-
`+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let o=[],i;do{let u={limit:200};if(i)u.cursor=i;let a=s.asBot?await
|
|
557
|
-
`+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function
|
|
558
|
-
`+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function Jx(e,t){try{let n=await
|
|
559
|
-
`+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let o=F(await $h(e,r,t)),i=F(o.file),l=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:r,u=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!u)throw Error(`files.info returned no download URL for ${r}`);let a={Authorization:`Bearer ${e}`};if(t)a.Cookie=`d=${t}`;let c=await fetch(u,{headers:a});if(!c.ok)throw Error(`Download failed: HTTP ${c.status} ${c.statusText}`);let d=Buffer.from(await c.arrayBuffer()),{statSync:f,existsSync:p}=await import("fs"),{basename:g}=await import("path"),h=s??l;if(s&&p(s)&&f(s).isDirectory())h=gt(s,g(l));im(h,d),console.log(`\u2713 Downloaded ${l} (${
|
|
557
|
+
slack schedule rm '${t.target}' ${d} --as-bot`),o.startsWith("D"))try{let f=await Wr(e);if(!f.ok)for(let p of Ur(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 tm(e,t,n,s){let r;if(n)r=n;else if(t)r=await we(e,t,s);let i=(await Nh(e,r,s)).scheduled_messages??[];if(i.length===0){console.log("(no scheduled messages)");return}for(let l of i){let u=new Date(l.post_at*1000).toISOString();console.log(`${l.id} ${u} [${l.channel_id}] ${l.text.split(`
|
|
558
|
+
`)[0]?.slice(0,80)??""}`)}}async function nm(e,t){let n;if(t.channelId)n=t.channelId;else n=await we(e,t.target,t.cookie);let s=await Me(e,t.cookie),r=De(n,t.id,s?.userId??"");if(t.code!==r)Se(t.code,r,["--- Deleting scheduled message ---------------",Ee(s,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await Mh(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function sm(e,t){if(t.comment!==void 0)Ke(t.comment,t.allowUrlAdjacent);let n=qt(e,t.cookie),{statSync:s,existsSync:r}=await import("fs"),{basename:o}=await import("path");for(let g of t.filePaths)if(!r(g))console.error(`Error: file not found: ${g}`),process.exit(1);let{ref:i,threadTs:l}=St(t.target),u;if(t.channelId)u=t.channelId;else if(t.userId)u=await Ut(e,t.userId,t.cookie);else u=await we(e,i,t.cookie);if(await gl(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 a=t.filePaths.length>1,c=t.filePaths.map((g)=>{let h=o(g),m=a?h:t.title??h;return{fp:g,filename:h,title:m,sizeFmt:Go(s(g).size)}}),d=await n(),f=De(u,...c.flatMap((g)=>[g.fp,g.title]),d?.userId??"");if(t.code!==f){let g=` To: ${i}${l?` (thread ${l})`:""}`,h=a?[`--- Uploading ${c.length} files ------------------------`,Ee(d,{pad:7}),g,...c.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: ${c[0].fp}`,` Title: ${c[0].title}`,` Size: ${c[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];Se(t.code,f,h)}let p=c.length;for(let g=0;g<p;g++){let h=c[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 sg(e,u,h.fp,m,t.cookie),D=p>1?`[${g+1}/${p}] `:"";console.log(`${D}\u2713 Uploaded (file_id: ${y}${w?`, url: ${w}`:""})`)}}async function jx(e,t,n){let s=n.channel?await we(e,n.channel,t):void 0,r=[],o=1,i=1;do{let u={page:o,count:200};if(n.types)u.types=n.types;if(s)u.channel=s;if(n.user)u.user=n.user;let a=F(await Ch(e,u,t));for(let c of z(a.files))r.push(F(c));i=Number(F(a.paging).pages??1),o++}while(r.length<n.limit&&o<=i);let l=r.slice(0,n.limit);if(n.format==="jsonl"){for(let u of l)console.log(JSON.stringify({id:u.id??null,name:u.name??u.title??null,filetype:u.filetype??null,size:u.size??null,user:u.user??null,created:u.created??null,permalink:u.permalink??null}));return}for(let u of l){let a=String(u.id??""),c=typeof u.name==="string"?u.name:typeof u.title==="string"?u.title:a,d=typeof u.filetype==="string"?u.filetype:"?",f=typeof u.size==="number"?Go(u.size):"";console.log(`${a} ${d.padEnd(7)} ${f.padStart(9)} ${c}`)}}function ei(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 Wx(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(F(n).text??F(n).name??F(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 Ux(e,t,n,s){let r=ei(n);if(!r)throw Error(`Not a list ID or list URL: ${n}
|
|
559
|
+
`+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let o=[],i;do{let u={limit:200};if(i)u.cursor=i;let a=s.asBot?await Tc(ur(),r,u):F(await Rh(e,r,u,t));for(let d of z(a.items??a.records))o.push(F(d));let c=F(a.response_metadata).next_cursor;i=typeof c==="string"&&c?c:void 0}while(i&&o.length<s.limit);let l=o.slice(0,s.limit);if(s.format==="jsonl"){for(let u of l)console.log(JSON.stringify(u));return}for(let u of l){let a=String(u.id??""),c=z(u.fields).map(F).map((d)=>{let f=String(d.key??d.column_id??"?"),p=Wx(d);return p?`${f}=${p}`:""}).filter(Boolean);console.log(`${a} ${c.join(" | ")}`)}}function ur(){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.
|
|
560
|
+
`+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function ti(e){let t=[];try{t=(await Mt(e)).scopes}catch{return}if(t.length&&!t.includes("lists:write"))console.error(`Error: the bot token lacks the lists:write scope (needed for slackLists.* writes).
|
|
561
|
+
`+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function Jx(e,t){try{let n=await Cc(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function Cm(e,t){let n=await Tc(e,t,{limit:1,includeList:!0}),s=lh(F(n.list));if(!s.length)throw Error(`could not read the column schema of list ${t}`);return s}function ni(e){console.error(ge(e)),process.exit(1)}async function Kx(e){let t=e.cols.map(ah),n=ch(t),s=ur();await ti(s);let r=await Me(s),o=De("lists-create",e.name,JSON.stringify(n),String(e.todo),r?.userId??"");if(e.code!==o)Se(e.code,o,["--- Creating Slack List ----------------------",Ee(r,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((u,a)=>` column: ${u.name} (${u.type}${u.choices?`: ${u.choices.join("/")}`:""})${a===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 Ah(s,e.name,n,e.todo)}catch(u){ni(u)}let l=String(i.list_id??F(i.list).id??"");console.log(`\u2713 Created list ${e.name} (${l})`),console.log(await Jx(s,l))}async function qx(e){let t=ei(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=ur();await ti(n);let s=await Cm(n,t),o=[{col:s.find((c)=>c.type==="text")??s[0],value:e.text},...mc(e.sets).map((c)=>({col:hc(s,c.col),value:c.value}))],i=o.map((c)=>({column_id:c.col.id,...gc(c.col,c.value)})),l=await Me(n),u=De("lists-add",t,JSON.stringify(i),l?.userId??"");if(e.code!==u)Se(e.code,u,["--- Adding a row to Slack List ---------------",Ee(l,{asBot:!0,pad:9}),` list: ${t}`,...o.map((c)=>` ${(c.col.name||c.col.key).padEnd(8)} ${c.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let a;try{a=await Th(n,t,i)}catch(c){ni(c)}console.log(`\u2713 Added row ${String(F(a.item).id??"")} ${e.text}`)}async function Hx(e){let t=ei(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=ur();await ti(n);let s=await Cm(n,t),r=mc(e.sets).map((u)=>({col:hc(s,u.col),value:u.value}));if(e.done!==void 0){let u=uh(s);if(!u)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);r.push({col:{...u,type:"checkbox"},value:String(e.done)})}if(!r.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let o=r.map((u)=>({row_id:e.row,column_id:u.col.id,...gc(u.col,u.value)})),i=await Me(n),l=De("lists-set",t,e.row,JSON.stringify(o),i?.userId??"");if(e.code!==l)Se(e.code,l,["--- Updating Slack List row -----------------",Ee(i,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...r.map((u)=>` ${(u.col.name||u.col.key).padEnd(8)} ${u.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await Oh(n,t,o)}catch(u){ni(u)}console.log(`\u2713 Updated row ${e.row}`)}async function zx(e){let t=ei(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=ur();await ti(n);let s=e.users.length?e.users:e.channels,r=await Me(n),o=De("lists-share",t,e.level,s.join(","),r?.userId??"");if(e.code!==o)Se(e.code,o,["--- Sharing Slack List ----------------------",Ee(r,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${s.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await Fh(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(i){ni(i)}console.log(`\u2713 Granted ${e.level} on ${t} to ${s.join(", ")}`)}function Yx(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 Gx(e,t,n,s){let r=Yx(n);if(!r)throw Error(`Not a file ID or file permalink: ${n}
|
|
562
|
+
`+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let o=F(await $h(e,r,t)),i=F(o.file),l=typeof i.name==="string"?i.name:typeof i.title==="string"?i.title:r,u=typeof i.url_private_download==="string"?i.url_private_download:typeof i.url_private==="string"?i.url_private:"";if(!u)throw Error(`files.info returned no download URL for ${r}`);let a={Authorization:`Bearer ${e}`};if(t)a.Cookie=`d=${t}`;let c=await fetch(u,{headers:a});if(!c.ok)throw Error(`Download failed: HTTP ${c.status} ${c.statusText}`);let d=Buffer.from(await c.arrayBuffer()),{statSync:f,existsSync:p}=await import("fs"),{basename:g}=await import("path"),h=s??l;if(s&&p(s)&&f(s).isDirectory())h=gt(s,g(l));im(h,d),console.log(`\u2713 Downloaded ${l} (${Go(d.length)}) \u2192 ${h}`)}async function Xx(){Ig(),OD();let e=(a)=>$s(a.workspace),t=(a)=>Bi(a.workspace),n=async(a)=>{let c=Xe(),d=ss(c);if(vn(c))try{let g=await gs(e(a),a.target,t(a));if(!on(c).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 ${c.dir}'s subscriptions (restrict_to_subscriptions)`),process.exit(2)}catch(g){console.error(ge(g)),process.exit(1)}if(a["fix-urls"]&&a.newText)a={...a,newText:xs(a.newText)};let f={target:a.target,newText:a.newText??"",allowUrlAdjacent:a["allow-url-adjacent"]===!0};if(a.tick)f.tick=a.tick;if(d.prefix)f.lanePrefix=d.prefix;if(a.force)f.force=!0;if(a.code)f.code=a.code;if(a["channel-id"])f.channelId=a["channel-id"];if(a.mentions!==!1)f.mentions=!0;let p;if(a["as-bot"]){let g=await Hg(f.target,e(a),t(a),f.channelId);if(p=g.botToken,g.channelId&&!f.channelId)f.channelId=g.channelId;f.asBot=!0,f.mentionToken=e(a);let h=t(a);if(h)f.mentionCookie=h}else{p=e(a);let g=t(a);if(g)f.cookie=g}await sx(p,f)},s=async(a)=>{if(rl(a.message))a={...a,message:await ol()};if(!String(a.message??"").trim())console.error("Error: message is empty"),process.exit(1);if(a["fix-urls"])a={...a,message:xs(a.message)};let c={target:a.target,message:a.message,allowUrlAdjacent:a["allow-url-adjacent"]===!0};if(a.json)c.json=!0;if(a.code)c.code=a.code;if(a["channel-id"])c.channelId=a["channel-id"];if(a["user-id"])c.userId=a["user-id"];if(a.broadcast)c.broadcast=!0;if(a.mentions!==!1){c.mentions=!0,c.mentionToken=e(a);let f=t(a);if(f)c.mentionCookie=f}let d;if(a["as-bot"]){let f=Le();if(!f)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
560
563
|
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!c.channelId&&!c.userId&&c.target.startsWith("@"))try{c.userId=await Ot(e(a),c.target,t(a))}catch(p){console.error(`Error: could not resolve ${c.target} to a user for the bot DM.
|
|
561
564
|
${p instanceof Error?p.message:String(p)}
|
|
562
|
-
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}d=f,c.asBot=!0}else{d=e(a);let f=t(a);if(f)c.cookie=f}try{await gx(d,c)}catch(f){console.error(
|
|
563
|
-
`),await
|
|
564
|
-
The inviter must be a member of the channel first.`:""}`),process.exit(1)}console.log(`\u2713 Invited ${g.length} to ${m}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(c)=>c.positional("name",{type:"string",demandOption:!0,describe:"Channel name (Slack lowercases it; no spaces)"}).option("private",{type:"boolean",default:!1,describe:"Create a private channel"}).option("invite",{type:"string",array:!0,default:[],describe:"Users to invite after creating (@handle or Uxxxx, repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(c)=>{let d=e(c),f=t(c),p=c.name.replace(/^#/,"").toLowerCase(),g=c.private===!0,h=c.invite.filter(Boolean),m=await Me(d,f),y=
|
|
565
|
+
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}d=f,c.asBot=!0}else{d=e(a);let f=t(a);if(f)c.cookie=f}try{await gx(d,c)}catch(f){console.error(ge(f)),process.exit(1)}},r={state:{type:"string",choices:["open","untriaged","pending","doing","done","dropped","stuck"],default:"open",describe:"open (default) = marked and not done/dropped; untriaged = marked with no progress; stuck = unfinished with a reason flag"},in:{type:"string",describe:"Limit to a channel (#chan)"},from:{type:"string",describe:"Limit to a sender (@user, or 'me') \u2014 usually the person a task is waiting on"},n:{alias:"count",type:"number",default:50,describe:"Max results"},json:{type:"boolean",default:!1}},o=async(a,c)=>{let d={state:a.state??"open",mine:c||a.mine===!0,count:a.n??50,json:a.json===!0};if(a.in)d.in=a.in;if(a.from)d.from=a.from;let f=t(a);if(f)d.cookie=f;await WD(e(a),d)},{who:i,rest:l}=$p(mi(process.argv)),u;if(i){let a=mo(i);if("error"in a)console.error(`Error: ${a.error}`),process.exit(2);u=a.kind}await Vu(l).scriptName("slack").showHelpOnFail(!1).fail((a,c,d)=>{if(c)console.error(c.message),process.exit(1);console.error(a),console.error(""),d.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).option("as-user",{type:"boolean",describe:"Act as the user session on purpose (not accepted for writes from inside an agent: name the person with slack @<who>)"}).middleware(async(a)=>{let c=String((a._??[])[0]??"");if(u==="bot"&&"as-bot"in a)a["as-bot"]=!0,a.asBot=!0;if(u==="user"&&a["as-bot"]===!0)console.error(`Error: @${i} is a user identity, but --as-bot was given`),process.exit(2);if(!c||c==="auth"||c==="login"||c==="agent"||c==="sent"||c==="relay")return;try{let d=$s(a.workspace),f=Le(),p=Sg(a._??[],a,{botTokenSource:f?am.get("SLACK_BOT_TOKEN")??il.get("SLACK_BOT_TOKEN")?.find((m)=>m.val===f)?.path??"shell":void 0,globalPaths:dl,slackTokenSet:!!process.env.SLACK_TOKEN,activeTokenIsBot:!!f&&d===f});if(p)console.error(p),process.exit(2);let g=go(),h=Cp({isWrite:zc(a._??[])&&!Yc(a._??[],a),who:i,asBot:a["as-bot"]===!0,asUser:a["as-user"]===!0,activeIsBot:d.startsWith("xoxb-"),agent:sc(),identities:[...g.keys()].sort(),userIdentities:[...g].filter(([,m])=>m.kind==="user").map(([m])=>m).sort(),cmd:(a._??[]).slice(0,2).join(" ")});if(h)console.error(h),process.exit(2)}catch(d){if((d instanceof Error?d.message:String(d)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
|
|
566
|
+
`),await Ns(),process.exit(0);throw d}},!0).command("agent","Bot agent session status and command heartbeat",(a)=>Pf(a,St)).command(["read [target]","msgs [target]"],"Browse messages",(a)=>a.positional("target",{type:"string",describe:"#channel, @user, URL, or an alias (slack alias ls)"}).option("limit",{alias:"n",type:"number",default:20,describe:"Number of messages"}).option("format",{type:"string",choices:["text","jsonl"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs)"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("unreplied",{type:"boolean",default:!1,describe:"Only messages whose last word (incl. thread replies) is not yours \u2014 i.e. awaiting your answer"}),async(a)=>{let c=e(a),d=a.json?"jsonl":a.format,f=a.target?Qa(a.target):void 0;if(f?.thread_ts)await Ug(c,f.channel,f.thread_ts,Math.max(a.limit,100),d,t(a));else if(f)await Wg(c,f.channel,a.limit,d,a.unreplied,t(a));else if(a.target)await Wg(c,a.target,a.limit,d,a.unreplied,t(a));else await ND(c)}).command("thread <target> <ts>","Show thread messages",(a)=>a.positional("target",{type:"string",demandOption:!0}).positional("ts",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:100}).option("format",{type:"string",choices:["text","jsonl","tsv"],default:"text",describe:"jsonl exposes raw ts/user/text (incl. external-guest user IDs); tsv: <ts> TAB <user|bot id> TAB <text, \\ \\n \\r \\t escaped> [files: N], every page"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("since",{type:"string",describe:"Only messages after this ts (reads every page)"}),async(a)=>{let c=a.json?"jsonl":a.format;await Ug(e(a),a.target,a.ts,a.limit,c,t(a),a.since)}).command(["channel","channels","ch"],"Channel commands",(a)=>a.command(["ls","list"],"List channels",(c)=>c.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("all",{type:"boolean",default:!1}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(c)=>{await BD(e(c),c.limit,c.filter,c.all,c.json?"jsonl":c.format,t(c))}).command("get <channel>","Show channel details",(c)=>c.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(c)=>{let d=e(c),f=t(c),p=c.channel,g=p.startsWith("#")||p.startsWith("@")||p.startsWith("C")||p.startsWith("G")||p.startsWith("D")?p:`#${p}`,h=await we(d,g,f),m=F(await Nn(d,h,f)),y=F(m.channel),w=typeof y.name==="string"?y.name:h,k=y.is_im===!0?"@":"#",_=String(F(y.purpose).value??""),E=String(F(y.topic).value??""),S=y.num_members??y.member_count??"";if(console.log(`${k}${w} ${h}`),E)console.log(`topic: ${E}`);if(_)console.log(`purpose: ${_}`);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",(c)=>c.positional("channel",{type:"string",demandOption:!0,describe:"#name, channel id, or permalink"}).positional("users",{type:"string",array:!0,demandOption:!0,describe:"@handle or U\u2026 ids"}).option("code",{type:"string",describe:"Safety hash to confirm"}),async(c)=>{let d=e(c),f=t(c),p,g=[];try{p=await we(d,String(c.channel),f);for(let w of c.users.map(String))g.push(/^[UW][A-Z0-9]{2,}$/.test(w)?w:await Ot(d,w,f))}catch(w){console.error(ge(w)),process.exit(1)}let h=await Me(d,f),m=await Jt(d,p,String(c.channel),f),y=De("channel-invite",p,g.join(","),h?.userId??"");if(c.code!==y)Se(c.code,y,["--- Inviting to a channel --------------------",Ee(h,{pad:9}),` channel: ${m}`,` users: ${g.join(", ")}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await Rc(d,p,g,f)}catch(w){let D=w instanceof Error?w.message:String(w);if(!/already_in_channel/.test(D))console.error(`\u2717 invite failed: ${ge(w)}${/not_in_channel/.test(D)?`
|
|
567
|
+
The inviter must be a member of the channel first.`:""}`),process.exit(1)}console.log(`\u2713 Invited ${g.length} to ${m}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(c)=>c.positional("name",{type:"string",demandOption:!0,describe:"Channel name (Slack lowercases it; no spaces)"}).option("private",{type:"boolean",default:!1,describe:"Create a private channel"}).option("invite",{type:"string",array:!0,default:[],describe:"Users to invite after creating (@handle or Uxxxx, repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(c)=>{let d=e(c),f=t(c),p=c.name.replace(/^#/,"").toLowerCase(),g=c.private===!0,h=c.invite.filter(Boolean),m=await Me(d,f),y=De(p,String(g),h.join(","),m?.userId??"");if(c.code!==y)Se(c.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 Uh(d,p,g,f)}catch(D){console.error(D instanceof Error?D.message:String(D)),process.exit(1)}if(console.log(`\u2713 Created ${g?"\uD83D\uDD12 ":"#"}${w.name} (${w.id})`),h.length){let D=[];for(let k of h)try{D.push(k.startsWith("U")||k.startsWith("W")?k:await Ot(d,k,f))}catch(_){console.error(` ! could not resolve ${k}: ${_ instanceof Error?_.message:String(_)}`)}for(let k of D)try{let _=F(await as(d,k,f)),E=F(_.user);if(E.is_ultra_restricted===!0)console.error(`\u26A0 ${k} 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(E.is_restricted===!0)console.error(`\u26A0 ${k} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(D.length)try{await Rc(d,w.id,D,f),console.log(`\u2713 Invited ${D.length} member${D.length===1?"":"s"}`)}catch(k){console.error(` ! invite failed: ${k instanceof Error?k.message:String(k)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(c)=>c.positional("channel",{type:"string",demandOption:!0,describe:"#name, name, or channel ID (C\u2026/G\u2026)"}).positional("new-name",{type:"string",demandOption:!0,describe:"New channel name (Slack lowercases it; no spaces)"}).option("dry-run",{type:"boolean",default:!1,describe:"Resolve the channel and print old -> new without renaming"}).option("code",{type:"string",describe:"Safety hash to confirm rename"}),async(c)=>{let d=e(c),f=t(c),p=c.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=c.newName.replace(/^#/,"").toLowerCase(),m,y;try{m=await we(d,g,f)}catch(_){console.error(`Error: could not resolve channel ${p}: ${_ instanceof Error?_.message:String(_)}`),process.exit(1)}try{let _=F(F(await Nn(d,m,f)).channel);if(_.is_im===!0||_.is_mpim===!0)console.error(`Error: ${m} is a DM \u2014 only channels can be renamed.`),process.exit(1);y=typeof _.name==="string"?_.name:g.replace(/^#/,"")}catch(_){let E=_ instanceof Error?_.message:String(_);if(/channel_not_found/.test(E))console.error(`Error: could not resolve channel ${p}: channel not found (or not visible to this token).`),process.exit(1);y=g.replace(/^#/,"")}if(c.dryRun===!0){console.log(`#${y} -> #${h} (${m})`),console.log("(dry run \u2014 conversations.rename not called)");return}let w=await Me(d,f),D=De("rename",m,h,w?.userId??"");if(c.code!==D)Se(c.code,D,["--- 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 k;try{k=await Jh(d,m,h,f)}catch(_){let S=(_ instanceof Error?_.message:String(_)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],x={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&&x[S])??ge(_)),process.exit(1)}console.log(`\u2713 Renamed #${y} -> #${k.name} (${k.id})`)}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(a)=>a.command(["ls","list"],"List workspace members",(c)=>c.option("limit",{alias:"n",type:"number",default:200}).option("filter",{alias:"f",type:"string"}).option("format",{type:"string",choices:["text","jsonl","yaml"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}).option("external",{type:"boolean",default:!1,describe:"Also include people reachable only through Slack Connect shared channels \u2014 they are in ANOTHER workspace, so users.list never returns them (costs one API call per shared channel)"}),async(c)=>{let d=c.json?"jsonl":c.format,f=e(c),p=t(c),g=await Yh(f,p),h=c.filter?.toLowerCase(),m=z(g.members).map(F);if(c.external){let k=new Set(m.map((x)=>String(x.id))),_=F(await Zs(f,p)),E=z(_.channels).map(F).filter((x)=>x.is_ext_shared===!0&&!!x.name),S=new Set;for(let x of E)try{for(let R of await Gh(f,String(x.id),p))if(!k.has(R))S.add(R)}catch{}for(let x of S)try{let R=F(await as(f,x,p)),L=F(R.user);if(L.id)m.push(L)}catch{}}let y=m.filter((k)=>k.deleted!==!0&&k.is_bot!==!0&&String(k.id)!=="USLACKBOT").filter((k)=>{if(!h)return!0;let _=String(k.name??"").toLowerCase(),E=String(F(k.profile).real_name??"").toLowerCase(),S=String(F(k.profile).email??"").toLowerCase();return _.includes(h)||E.includes(h)||S.includes(h)}).slice(0,c.limit);if(d==="jsonl"){for(let k of y)console.log(JSON.stringify(k));return}if(d==="yaml"){for(let k of y){let _=function(E,S=""){if(E===null)return"null";if(typeof E==="string")return E.includes(`
|
|
565
568
|
`)?`|
|
|
566
|
-
${
|
|
569
|
+
${E.split(`
|
|
567
570
|
`).join(`
|
|
568
|
-
`)}`:
|
|
569
|
-
${S} - ${_(x,S+" ")}`).join("");return Object.entries(
|
|
570
|
-
${S} ${x}: ${_(R,S+" ")}`).join("")};console.log("---");for(let[
|
|
571
|
-
`)){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:Xa(y).dir,global:!1};ec(w,`t-${h}`,{channel:c.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)",(a)=>a.positional("dest",{type:"string",describe:"alias | permalink | #chan:<ts> | <ts> (in settings' channel). Omit with --to"}).positional("message",{type:"string",describe:"Text, or - for stdin"}).option("json",{type:"boolean",default:!1,describe:"On success print one JSON line: {ok, channel, ts, thread_ts, permalink?}"}).option("to",{type:"string",describe:"Permalink of the message you are answering: replies in ITS thread; with a dest, refuses when they differ"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to and a dest: post to dest even when the message is in another thread"}).option("prefix",{type:"string",describe:`Override settings' prefix ("" for none)`}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("fix-urls",{type:"boolean",default:!1,describe:"Wrap ambiguous bare URLs as <url> (cut at the first non-ASCII character / trailing punctuation) before sending"}).option("broadcast",{type:"boolean",default:!1,describe:"Also send to channel"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real mentions (--no-mentions for literal text)"}),async(a)=>{let{dest:c,message:d}=a;if(a.to&&d===void 0)d=c,c=void 0;if(sl(d))d=await rl();if(d===void 0||!d.trim())console.error("Error: message is empty"),process.exit(1);if(!c&&!a.to)console.error("Error: reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"),process.exit(2);let f=e(a),p=t(a),g=Xe(),h=ns(g),m;try{let D=await Jg(f,p,g,c,a.to,a["any-thread"]);if("error"in D)console.error(`Error: ${D.error}`),process.exit(2);m=D}catch(D){console.error(pe(D)),process.exit(1)}let{channel:y,threadTs:w}=m;if(In(g)&&(a.prefix!==void 0||a["as-bot"]!==void 0&&a["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 k=tc(d,a.prefix??h.prefix);if(!k.trim())console.error("Error: message is empty (only the prefix)"),process.exit(1);await s({workspace:a.workspace,target:`${y}:${w}`,message:k,code:a.code,"allow-url-adjacent":a["allow-url-adjacent"],"fix-urls":a["fix-urls"],"as-bot":a["as-bot"]??h.as_bot??!1,broadcast:a.broadcast,mentions:a.mentions,json:a.json})}).command("inbox","This directory's .slack-term/inbox/: messages routed here by `slack stream --inbox`",(a)=>a.command(["ls","list"],"Pending messages: ts, from, alias, text (redacted)",(c)=>c.option("json",{type:"boolean",default:!1}),(c)=>{let d=ss(Xe());if(c.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",(c)=>c.option("timeout",{type:"number",default:3600,describe:"Seconds"}).option("new-only",{type:"boolean",default:!1,describe:"Skip what is already pending"}).option("thread",{type:"string",describe:"Only messages in this thread (its root ts)"}).option("alias",{type:"string",describe:"Only messages routed by this alias"}).option("from",{type:"array",string:!0,describe:"Only messages from these user ids; repeatable"}),async(c)=>{let d=Xe(),f=c.from?.length?new Set(c.from.map(String)):void 0,p=(m)=>(!c.thread||(m.thread_ts??m.ts)===c.thread)&&(!c.alias||m.alias===c.alias)&&(!f||f.has(m.user)),g=new Set;if(c["new-only"])for(let m of ss(d))g.add(m.file);let h=Date.now()+c.timeout*1000;for(;;){for(let m of ss(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",(c)=>c.option("json",{type:"boolean",default:!1}).option("eyes",{type:"boolean",default:!1,describe:"React \uD83D\uDC40 on each overdue message (once per message: recorded as nudged_at)"}).option("as-bot",{type:"boolean",describe:"React via the bot token (default: settings' as_bot)"}),async(c)=>{let d=Xe(),f=Jp(d);if(c.eyes){let p=c["as-bot"]??ns(d).as_bot??!1,g=p?Le():e(c);if(!g)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);let h=p?void 0:t(c);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}}Kp(m),m.entry.nudged_at=new Date().toISOString()}}if(c.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",(a)=>a.positional("ref",{type:"string",array:!0,demandOption:!0}),(a)=>{let c=Xe(),d=0;for(let f of a.ref){let p=oc(c,f);if(p)console.log(`archived ${p}`);else console.error(`not in ${c.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`",(a)=>a.command("add <dest> <message>","Queue a reply (text redacted before it is written; - reads stdin)",(c)=>c.positional("dest",{type:"string",demandOption:!0,describe:"alias | permalink | #chan:<ts>"}).positional("message",{type:"string",demandOption:!0}).option("in-reply-to",{type:"string",describe:"ts of the inbox message this answers: archived once sent"}),async(c)=>{let d=sl(c.message)?await rl():c.message;if(!d.trim())console.error("Error: message is empty"),process.exit(1);let f=jp(Xe(),{to:c.dest,text:d,...c["in-reply-to"]?{in_reply_to:c["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",(c)=>c,()=>{for(let c of ic(Xe()))console.log(`${c.file} ${c.entry.to}${c.entry.attempts?` attempts=${c.entry.attempts} ${c.entry.error??""}`:""}`)}).command("flush","Send every queued reply (prefix, thread and restrict checks as `reply`); a --code covers the whole batch",(c)=>c.option("code",{type:"string",describe:"Safety hash to confirm the batch"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}),async(c)=>{let d=Xe(),f=ns(d),p=ic(d);if(!p.length){console.error(`nothing in ${d.dir}/outbox`);return}if(In(d)&&c["as-bot"]!==void 0&&c["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=c["as-bot"]??f.as_bot??!1,h=e(c),m=t(c),y,w;if(g){let x=Le();if(!x)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);y=x}else y=h,w=m;let k=[],D=[];for(let x of p)try{let R=await Jg(h,m,d,x.entry.to,void 0);if("error"in R){D.push(`${x.file}: ${R.error}`);continue}let L=tc(x.entry.text,f.prefix);if(!L.trim()){D.push(`${x.file}: empty`);continue}Ke(L),k.push({item:x,...R,text:L})}catch(R){D.push(`${x.file}: ${pe(R)}`)}for(let x of D)console.error(`refused (stays queued): ${x}`);if(!k.length)process.exit(2);let _=[`OUTBOX \u2014 ${k.length} repl${k.length===1?"y":"ies"}${g?" as the bot":""}:`];for(let x of k)_.push(` \u2192 ${x.channel} thread ${x.threadTs}: ${B(x.text).replace(/\n/g,"\u23CE").slice(0,120)}${x.text.includes("[redacted:")?" (secrets were masked when queued: this is what posts)":""}`);let C=we("outbox",g?"bot":"user",...k.map((x)=>`${x.channel}:${x.threadTs}:${x.text}`));if(c.code!==C)xe(c.code,C,_);let S=0;for(let x of k)try{let R=await Bt(y,x.channel,x.text,x.threadTs,!1,w),L="";try{L=await Pn(y,x.channel,R,w)}catch{}let P=Wp(d,x.item,{ts:R,permalink:L,channel:x.channel,thread_ts:x.threadTs});console.log(`\u2713 ${L||R} (${P})`)}catch(R){Up(x.item,pe(R)),console.error(`\u2717 ${x.item.file}: ${pe(R)}`),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>`)",(a)=>a.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --waitFor)"}).positional("question",{type:"string",describe:"The question. Must @tag whoever may answer (@alice), or the whole channel (@here / @channel / @everyone) \u2014 only their answer counts. In a 1:1 DM the other party counts automatically."}).positional("choices",{type:"string",array:!0,describe:"Up to 10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply."}).option("code",{type:"string",describe:"Safety hash to confirm the ask"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("lang",{type:"string",choices:[...$t],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 unless --push: --since 7d, --channel, --json. Never waits out a rate limit: a throttled pass says how many it skipped."}).option("push",{type:"boolean",default:!1,describe:"With --pending: send each answer to the agent that asked (ay send to the pid in the sent-log, or up to 3 of its parents), then collect a decision (\u2705, off this list); a free-text reply is marked delivered, the question stays open. A gone asker's answer goes to the newest live agent in the same directory (a restarted lane), else it stays listed. Each answer is pushed once."}).option("undelivered",{type:"boolean",default:!1,describe:"With --pending: the sweep \u2014 only answers that have reached nobody yet. With --push, also why (asker gone and no live agent in its directory, or ay refused)."}).option("watch",{type:"boolean",default:!1,describe:"With --pending --push: keep running \u2014 a pass every --interval, and one for a question as soon as the relay rings for it (SLACK_RELAY_URL / SLACK_RELAY_TOKEN). Prints only what it pushed."}).option("interval",{type:"number",default:10,describe:"With --watch: minutes between full passes"}).option("since",{type:"string",default:"7d",describe:"With --pending: how far back to look (30m, 2h, 7d, or an ISO date)"}).option("stale",{type:"string",describe:"With --ls: only open questions older than this (24h, 3d)"}).option("state",{type:"string",default:"open",choices:["open","answered","void","edited","gone","unknown","all"],describe:"With --ls: which state to list"}).option("channel",{type:"string",describe:"With --ls / --pending: only this channel (id, or the target as typed)"}).option("limit",{type:"number",default:50,describe:"With --ls: how many recent asks to check"}).option("reason",{type:"string",describe:"With --void: why it is void (written into the message)"}).option("superseded-by",{type:"string",describe:"With --void: permalink of the question that replaces it"}).option("explain",{type:"boolean",describe:"Also offer an \u2139\uFE0F 'explain' pill (seeded after \u2795): pressing it asks YOU to explain the question in its thread and is never an answer \u2014 the question stays open. --wait/--waitFor report it on stderr (and as `explain` in --json), and post one thread note per question. Default: $SLACK_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(a)=>{if(a.ls||a.pending){if(a.ls&&a.pending)console.error("Error: --ls and --pending are separate lists \u2014 pick one."),process.exit(le);let D=(()=>{try{return e(a)}catch{return}})(),_={};if(D)_.user=D;let C=Le();if(C)_.bot=C;let S=t(a);if(S)_.cookie=S;if(a.pending){if(a.target||a.question||a.waitFor||a.wait||a.void||a.edit)console.error("Error: --pending reads the local log \u2014 do not also pass a target/question or another ask action."),process.exit(le);let R=os(String(a.since));if(R===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${B(String(a.since))})`),process.exit(le);if(a.watch&&!a.push)console.error("Error: --watch keeps pushing answers \u2014 use it with --push."),process.exit(le);let L={sinceMs:R,json:!!a.json,push:!!a.push,undelivered:!!a.undelivered};if(a.channel)L.channel=String(a.channel);if(a.workspace)L.selfArgs=["-w",String(a.workspace)];if(a.watch){let P=Number(a.interval);if(!(P>0))console.error("Error: --interval needs a number of minutes above 0."),process.exit(le);let v=String(a.since),M=new Set;await Fx(async(U)=>{let N=await Vg(_,{...L,sinceMs:os(v)??R,watch:!0,...U?{only:U}:{skip:M}});if(U)return;if(N.throttled)for(let K of N.checked)M.add(K);else M.clear()},()=>os(v)??R,()=>(M.size?Math.min(2,P):P)*60000)}try{await Vg(_,L)}catch(P){console.error(pe(P)),process.exit(le)}return}let x={state:String(a.state??"open"),json:!!a.json,limit:Number(a.limit)||50};if(a.stale)x.stale=String(a.stale);if(a.channel)x.channel=String(a.channel);await Cx(_,x);return}let c=(D)=>{if(!D){let C=t(a);return C?{token:e(a),cookie:C}:{token:e(a)}}let _=Le();if(!_)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(
|
|
573
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(
|
|
574
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(
|
|
575
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(
|
|
571
|
+
`)}`:E;if(typeof E!=="object")return String(E);if(Array.isArray(E))return E.map((x)=>`
|
|
572
|
+
${S} - ${_(x,S+" ")}`).join("");return Object.entries(E).map(([x,R])=>`
|
|
573
|
+
${S} ${x}: ${_(R,S+" ")}`).join("")};console.log("---");for(let[E,S]of Object.entries(k))console.log(`${E}: ${_(S)}`)}return}let w=Intl.DateTimeFormat().resolvedOptions().timeZone,D=y.length?String(F(z(g.members).map(F)[0]??{}).team_id??""):"";for(let k of y){let _=F(k.profile),E=String(k.name??k.id),S=String(k.id??""),x=String(_.display_name||""),R=String(_.real_name||""),L=String(_.email||""),v=String(k.tz??""),B=[...new Set([x,R].filter((O)=>O&&O!==E))].join(" / "),W=v&&v!==w?v:"",N=String(k.team_id??""),J=k.is_stranger===!0||D&&N&&N!==D?`external:${N||"?"}`:k.is_ultra_restricted===!0?"single-channel guest":k.is_restricted===!0?"guest":"",H=[L,W].filter(Boolean).join(" ");console.log(`@${E} ${S} ${B}${H?" "+H:""}${J?` [${J}]`:""}`)}}).command("get <user>","Show user details",(c)=>c.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(c)=>{let d=e(c),f=t(c),p=c.user.startsWith("@")?c.user:`@${c.user}`,g="";try{g=await Ot(d,p,f)}catch(P){console.error(P instanceof Error?P.message:String(P)),process.exit(1)}let h=F(await as(d,g,f)),m=F(h.user),y=F(m.profile),w=Intl.DateTimeFormat().resolvedOptions().timeZone,D=String(m.name??g),k=String(m.id??g),_=String(y.display_name||""),E=String(y.real_name||""),S=String(y.email||""),x=String(m.tz??""),R=String(y.phone||""),L=String(y.title||"");console.log(`@${D} ${k}`);let v=[...new Set([_,E].filter((P)=>P&&P!==D))];if(v.length)console.log(`name: ${v.join(" / ")}`);if(S)console.log(`email: ${S}`);if(R)console.log(`phone: ${R}`);if(L)console.log(`title: ${L}`);if(x&&x!==w)console.log(`tz: ${x}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(a)=>a.option("limit",{alias:"l",type:"number",default:20}),async(a)=>{await MD(e(a),a.limit)}).command("search <query>","Full-text search",(a)=>a.positional("query",{type:"string",demandOption:!0}).option("count",{alias:"n",type:"number",default:100}).option("json",{type:"boolean",default:!1,describe:"Output raw JSON"}),async(a)=>{await um(e(a),a.query,a.count,a.json,t(a))}).command("send <target> <message>","Send a message (confirm-hash safety gate); - as the message reads stdin",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("fix-urls",{type:"boolean",default:!1,describe:"Wrap ambiguous bare URLs as <url> (cut at the first non-ASCII character / trailing punctuation) before sending"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Send via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient and can be two-way"}).option("broadcast",{type:"boolean",default:!1,describe:`Also send to channel: broadcast a threaded reply back to the channel (Slack's "Also send to #channel" checkbox). Only effective with a thread target.`}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real <@USERID> mentions (on by default; resolves via users.list, then channel members for Slack Connect guests). Unresolved handles stay as plain text. The confirm preview shows the converted message before sending. Disable with --no-mentions for literal @text."}).option("to",{type:"string",describe:"Permalink of the message you are answering: refuses when it is not in the target's thread (see also `slack reply --to`)"}).option("json",{type:"boolean",default:!1,describe:"On success print one JSON line: {ok, channel, ts, thread_ts?, permalink?}"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to: send even when the message is in another thread"}),async(a)=>{if(a.to&&!a["any-thread"])try{let c=e(a),d=t(a),f=await gs(c,a.to,d),p=ft(a.target)?await gs(c,a.target,d):void 0,g=p?{channel:p.channel,threadTs:p.root}:(()=>{let y=St(a.target);return{ref:y.ref,...y.threadTs?{threadTs:y.threadTs}:{}}})(),h="channel"in g?g.channel:await we(c,g.ref,d),m=nc({channel:h,...g.threadTs?{threadTs:g.threadTs}:{}},f);if(m)console.error(`Error: ${m}`),process.exit(2)}catch(c){console.error(ge(c)),process.exit(1)}await s(a)}).command("init [dir]","Create .slack-term/ in a directory: aliases, settings, inbox/outbox (never committed)",(a)=>a.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"}),(a)=>{let{dir:c,created:d}=Xa(a.dir,{...a.prefix?{prefix:a.prefix}:{},...a.channel?{channel:a.channel}:{},...a["as-bot"]!==void 0?{as_bot:a["as-bot"]}:{}});console.log(d.length?`${c}: created ${d.join(", ")}`:`${c}: already set up`)}).command("alias","Name channels and threads for this directory (the nearest .slack-term/)",(a)=>a.command(["ls","list"],"List aliases: name, channel, thread, file",(c)=>c.option("json",{type:"boolean",default:!1}),(c)=>{let d=Xe(),f=on(d);if(c.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",(c)=>c.positional("name",{type:"string",demandOption:!0}).positional("target",{type:"string",demandOption:!0}).option("note",{type:"string",describe:"Free text shown by `alias ls`"}).option("shared",{type:"boolean",default:!1,describe:"Write settings.yml (the allowlist owner's file) instead of settings.local.yml"}).option("dir",{type:"string",describe:"Use the .slack-term/ above this directory instead of the cwd's (with --shared: a lane's dir)"}),async(c)=>{let d=e(c),f=t(c),p=Xe(c.dir),g=ft(c.target)?.ts!==void 0||St(c.target).threadTs!==void 0,h,m,y="";if(g){let k=await gs(d,c.target,f);if(h=k.channel,m=k.root,k.root!==k.ts)y=` (${k.ts} is a reply: named its thread root)`}else h=await we(d,St(c.target).ref,f);let w;try{w=ec(p,c.name,{channel:h,...m?{thread_ts:m}:{},...c.note?{note:c.note}:{}},c.shared)}catch(k){if(k instanceof In)console.error(`Error: ${k.message}`),process.exit(2);throw k}let D=w&&(w.channel!==h||w.thread_ts!==m)?` (was ${w.channel} ${w.thread_ts??"-"})`:"";console.log(`${c.name} \u2192 ${h} ${m??"-"}${y}${D} [${p.dir}]`)}).command(["unset <name>","rm <name>"],"Remove an alias (from settings.local.yml; --shared: also from settings.yml)",(c)=>c.positional("name",{type:"string",demandOption:!0}).option("shared",{type:"boolean",default:!1,describe:"Allow removing one defined in settings.yml"}).option("dir",{type:"string",describe:"Use the .slack-term/ above this directory"}),(c)=>{let d=Xe(c.dir),f;try{f=mp(d,c.name,c.shared)}catch(p){if(p instanceof In)console.error(`Error: ${p.message}`),process.exit(2);throw p}if(f==="removed")console.log(`${c.name} removed [${d.dir}]`);else if(f==="absent")console.error(`no alias "${c.name}" in ${d.dir}`),process.exit(2);else console.error(`"${c.name}" is defined in ${d.dir}/settings.yml: edit that file to remove it`),process.exit(2)}).command("who <channel> <ts>","Which registered .slack-term/ dirs subscribe this thread (or message): dir, alias",(c)=>c.positional("channel",{type:"string",demandOption:!0,describe:"Channel id"}).positional("ts",{type:"string",demandOption:!0,describe:"Thread root ts (a reply's own ts is not its thread)"}).option("json",{type:"boolean",default:!1}),(c)=>{let d=wp(c.channel,c.ts).map((f)=>({dir:AD(f.scope.dir),scope:f.scope.dir,alias:f.name,file:f.file}));if(c.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",(c)=>c.positional("tsv",{type:"string",demandOption:!0}).option("channel",{type:"string",demandOption:!0,describe:"The channel every thread is in (for a DM: the DM id)"}).option("lane-dir",{type:"array",string:!0,demandOption:!0,describe:"<lane>=<dir> (a directory holding .slack-term/, made if missing); repeatable"}),(c)=>{let d=new Map;for(let g of c["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 ul(c.tsv,"utf8").split(`
|
|
574
|
+
`)){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:Xa(y).dir,global:!1};ec(w,`t-${h}`,{channel:c.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)",(a)=>a.positional("dest",{type:"string",describe:"alias | permalink | #chan:<ts> | <ts> (in settings' channel). Omit with --to"}).positional("message",{type:"string",describe:"Text, or - for stdin"}).option("json",{type:"boolean",default:!1,describe:"On success print one JSON line: {ok, channel, ts, thread_ts, permalink?}"}).option("to",{type:"string",describe:"Permalink of the message you are answering: replies in ITS thread; with a dest, refuses when they differ"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to and a dest: post to dest even when the message is in another thread"}).option("prefix",{type:"string",describe:`Override settings' prefix ("" for none)`}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("fix-urls",{type:"boolean",default:!1,describe:"Wrap ambiguous bare URLs as <url> (cut at the first non-ASCII character / trailing punctuation) before sending"}).option("broadcast",{type:"boolean",default:!1,describe:"Also send to channel"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real mentions (--no-mentions for literal text)"}),async(a)=>{let{dest:c,message:d}=a;if(a.to&&d===void 0)d=c,c=void 0;if(rl(d))d=await ol();if(d===void 0||!d.trim())console.error("Error: message is empty"),process.exit(1);if(!c&&!a.to)console.error("Error: reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"),process.exit(2);let f=e(a),p=t(a),g=Xe(),h=ss(g),m;try{let k=await Jg(f,p,g,c,a.to,a["any-thread"]);if("error"in k)console.error(`Error: ${k.error}`),process.exit(2);m=k}catch(k){console.error(ge(k)),process.exit(1)}let{channel:y,threadTs:w}=m;if(vn(g)&&(a.prefix!==void 0||a["as-bot"]!==void 0&&a["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 D=tc(d,a.prefix??h.prefix);if(!D.trim())console.error("Error: message is empty (only the prefix)"),process.exit(1);await s({workspace:a.workspace,target:`${y}:${w}`,message:D,code:a.code,"allow-url-adjacent":a["allow-url-adjacent"],"fix-urls":a["fix-urls"],"as-bot":a["as-bot"]??h.as_bot??!1,broadcast:a.broadcast,mentions:a.mentions,json:a.json})}).command("inbox","This directory's .slack-term/inbox/: messages routed here by `slack stream --inbox`",(a)=>a.command(["ls","list"],"Pending messages: ts, from, alias, text (redacted)",(c)=>c.option("json",{type:"boolean",default:!1}),(c)=>{let d=rs(Xe());if(c.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",(c)=>c.option("timeout",{type:"number",default:3600,describe:"Seconds"}).option("new-only",{type:"boolean",default:!1,describe:"Skip what is already pending"}).option("thread",{type:"string",describe:"Only messages in this thread (its root ts)"}).option("alias",{type:"string",describe:"Only messages routed by this alias"}).option("from",{type:"array",string:!0,describe:"Only messages from these user ids; repeatable"}),async(c)=>{let d=Xe(),f=c.from?.length?new Set(c.from.map(String)):void 0,p=(m)=>(!c.thread||(m.thread_ts??m.ts)===c.thread)&&(!c.alias||m.alias===c.alias)&&(!f||f.has(m.user)),g=new Set;if(c["new-only"])for(let m of rs(d))g.add(m.file);let h=Date.now()+c.timeout*1000;for(;;){for(let m of rs(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",(c)=>c.option("json",{type:"boolean",default:!1}).option("eyes",{type:"boolean",default:!1,describe:"React \uD83D\uDC40 on each overdue message (once per message: recorded as nudged_at)"}).option("as-bot",{type:"boolean",describe:"React via the bot token (default: settings' as_bot)"}),async(c)=>{let d=Xe(),f=Jp(d);if(c.eyes){let p=c["as-bot"]??ss(d).as_bot??!1,g=p?Le():e(c);if(!g)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);let h=p?void 0:t(c);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: ${ge(y)}`);continue}}Kp(m),m.entry.nudged_at=new Date().toISOString()}}if(c.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",(a)=>a.positional("ref",{type:"string",array:!0,demandOption:!0}),(a)=>{let c=Xe(),d=0;for(let f of a.ref){let p=ic(c,f);if(p)console.log(`archived ${p}`);else console.error(`not in ${c.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`",(a)=>a.command("add <dest> <message>","Queue a reply (text redacted before it is written; - reads stdin)",(c)=>c.positional("dest",{type:"string",demandOption:!0,describe:"alias | permalink | #chan:<ts>"}).positional("message",{type:"string",demandOption:!0}).option("in-reply-to",{type:"string",describe:"ts of the inbox message this answers: archived once sent"}),async(c)=>{let d=rl(c.message)?await ol():c.message;if(!d.trim())console.error("Error: message is empty"),process.exit(1);let f=jp(Xe(),{to:c.dest,text:d,...c["in-reply-to"]?{in_reply_to:c["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",(c)=>c,()=>{for(let c of ac(Xe()))console.log(`${c.file} ${c.entry.to}${c.entry.attempts?` attempts=${c.entry.attempts} ${c.entry.error??""}`:""}`)}).command("flush","Send every queued reply (prefix, thread and restrict checks as `reply`); a --code covers the whole batch",(c)=>c.option("code",{type:"string",describe:"Safety hash to confirm the batch"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}),async(c)=>{let d=Xe(),f=ss(d),p=ac(d);if(!p.length){console.error(`nothing in ${d.dir}/outbox`);return}if(vn(d)&&c["as-bot"]!==void 0&&c["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=c["as-bot"]??f.as_bot??!1,h=e(c),m=t(c),y,w;if(g){let x=Le();if(!x)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);y=x}else y=h,w=m;let D=[],k=[];for(let x of p)try{let R=await Jg(h,m,d,x.entry.to,void 0);if("error"in R){k.push(`${x.file}: ${R.error}`);continue}let L=tc(x.entry.text,f.prefix);if(!L.trim()){k.push(`${x.file}: empty`);continue}Ke(L),D.push({item:x,...R,text:L})}catch(R){k.push(`${x.file}: ${ge(R)}`)}for(let x of k)console.error(`refused (stays queued): ${x}`);if(!D.length)process.exit(2);let _=[`OUTBOX \u2014 ${D.length} repl${D.length===1?"y":"ies"}${g?" as the bot":""}:`];for(let x of D)_.push(` \u2192 ${x.channel} thread ${x.threadTs}: ${M(x.text).replace(/\n/g,"\u23CE").slice(0,120)}${x.text.includes("[redacted:")?" (secrets were masked when queued: this is what posts)":""}`);let E=De("outbox",g?"bot":"user",...D.map((x)=>`${x.channel}:${x.threadTs}:${x.text}`));if(c.code!==E)Se(c.code,E,_);let S=0;for(let x of D)try{let R=await Bt(y,x.channel,x.text,x.threadTs,!1,w),L="";try{L=await Ln(y,x.channel,R,w)}catch{}let v=Wp(d,x.item,{ts:R,permalink:L,channel:x.channel,thread_ts:x.threadTs});console.log(`\u2713 ${L||R} (${v})`)}catch(R){Up(x.item,ge(R)),console.error(`\u2717 ${x.item.file}: ${ge(R)}`),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>`)",(a)=>a.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --waitFor)"}).positional("question",{type:"string",describe:"The question. Must @tag whoever may answer (@alice), or the whole channel (@here / @channel / @everyone) \u2014 only their answer counts. In a 1:1 DM the other party counts automatically."}).positional("choices",{type:"string",array:!0,describe:"Up to 10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply."}).option("code",{type:"string",describe:"Safety hash to confirm the ask"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("lang",{type:"string",choices:[...$t],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 unless --push: --since 7d, --channel, --json. Never waits out a rate limit: a throttled pass says how many it skipped."}).option("push",{type:"boolean",default:!1,describe:"With --pending: send each answer to the agent that asked (ay send to the pid in the sent-log, or up to 3 of its parents), then collect a decision (\u2705, off this list); a free-text reply is marked delivered, the question stays open. A gone asker's answer goes to the newest live agent in the same directory (a restarted lane), else it stays listed. Each answer is pushed once."}).option("undelivered",{type:"boolean",default:!1,describe:"With --pending: the sweep \u2014 only answers that have reached nobody yet. With --push, also why (asker gone and no live agent in its directory, or ay refused)."}).option("watch",{type:"boolean",default:!1,describe:"With --pending --push: keep running \u2014 a pass every --interval, and one for a question as soon as the relay rings for it (SLACK_RELAY_URL / SLACK_RELAY_TOKEN). Prints only what it pushed."}).option("interval",{type:"number",default:10,describe:"With --watch: minutes between full passes"}).option("since",{type:"string",default:"7d",describe:"With --pending: how far back to look (30m, 2h, 7d, or an ISO date)"}).option("stale",{type:"string",describe:"With --ls: only open questions older than this (24h, 3d)"}).option("state",{type:"string",default:"open",choices:["open","answered","void","edited","gone","unknown","all"],describe:"With --ls: which state to list"}).option("channel",{type:"string",describe:"With --ls / --pending: only this channel (id, or the target as typed)"}).option("limit",{type:"number",default:50,describe:"With --ls: how many recent asks to check"}).option("reason",{type:"string",describe:"With --void: why it is void (written into the message)"}).option("superseded-by",{type:"string",describe:"With --void: permalink of the question that replaces it"}).option("explain",{type:"boolean",describe:"Also offer an \u2139\uFE0F 'explain' pill (seeded after \u2795): pressing it asks YOU to explain the question in its thread and is never an answer \u2014 the question stays open. --wait/--waitFor report it on stderr (and as `explain` in --json), and post one thread note per question. Default: $SLACK_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(a)=>{if(a.ls||a.pending){if(a.ls&&a.pending)console.error("Error: --ls and --pending are separate lists \u2014 pick one."),process.exit(oe);let k=(()=>{try{return e(a)}catch{return}})(),_={};if(k)_.user=k;let E=Le();if(E)_.bot=E;let S=t(a);if(S)_.cookie=S;if(a.pending){if(a.target||a.question||a.waitFor||a.wait||a.void||a.edit)console.error("Error: --pending reads the local log \u2014 do not also pass a target/question or another ask action."),process.exit(oe);let R=is(String(a.since));if(R===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${M(String(a.since))})`),process.exit(oe);if(a.watch&&!a.push)console.error("Error: --watch keeps pushing answers \u2014 use it with --push."),process.exit(oe);let L={sinceMs:R,json:!!a.json,push:!!a.push,undelivered:!!a.undelivered};if(a.channel)L.channel=String(a.channel);if(a.workspace)L.selfArgs=["-w",String(a.workspace)];if(a.watch){let v=Number(a.interval);if(!(v>0))console.error("Error: --interval needs a number of minutes above 0."),process.exit(oe);let P=String(a.since),B=new Set;await Fx(async(W)=>{let N=await Vg(_,{...L,sinceMs:is(P)??R,watch:!0,...W?{only:W}:{skip:B}});if(W)return;if(N.throttled)for(let J of N.checked)B.add(J);else B.clear()},()=>is(P)??R,()=>(B.size?Math.min(2,v):v)*60000)}try{await Vg(_,L)}catch(v){console.error(ge(v)),process.exit(oe)}return}let x={state:String(a.state??"open"),json:!!a.json,limit:Number(a.limit)||50};if(a.stale)x.stale=String(a.stale);if(a.channel)x.channel=String(a.channel);await Cx(_,x);return}let c=(k)=>{if(!k){let E=t(a);return E?{token:e(a),cookie:E}:{token:e(a)}}let _=Le();if(!_)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
575
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);return{token:_}},d=a.target!==void 0&&a.target!=="void"&&a.target!=="collect"?String(a.target):void 0,f=[a.question,...a.choices??[]].filter((k)=>k!==void 0).map(String);if(a.edit){if(a.void||a.wait||a.waitFor)console.error("Error: --edit changes one open question \u2014 do not combine it with --void/--wait/--waitFor."),process.exit(oe);let{token:k,cookie:_}=c(!!a["as-bot"]),E={link:String(a.edit),asBot:!!a["as-bot"],mentionToken:k,allowUrlAdjacent:!!a["allow-url-adjacent"]};if(d!==void 0)E.question=d;if(f.length)E.choices=f.map((S)=>S.trim()).filter(Boolean);if(a.body!==void 0)E.body=String(a.body);if(a.lang)E.lang=String(a.lang);if(a.code)E.code=String(a.code);if(_)E.cookie=_,E.mentionCookie=_;try{await $x(k,E)}catch(S){console.error(ge(S)),process.exit(oe)}return}let p,g=(a.void??[]).map(String).filter(Boolean);if(a.reask){if(g.length!==1||a.target==="void")console.error("Error: --reask goes with exactly one --void=<permalink> (the question to replace)."),process.exit(oe);if(a.waitFor)console.error("Error: --reask posts a new question \u2014 --wait works, --waitFor does not."),process.exit(oe);let{token:k,cookie:_}=c(!!a["as-bot"]),E=await Me(k,_),S=await Dm(k,g[0],E,!!a["as-bot"],_);if(S==="void")console.error(`\u2717 ${M(g[0])}: already voided \u2014 to ask again, just use slack ask`),process.exit(oe);if(!S)process.exit(oe);if(p={...S,reason:je(String(a.reason??"")).trim()},a.target=S.threadTs?`${S.channelId}:${S.threadTs}`:S.channelId,a["channel-id"]=S.channelId,a.question=d??ls(S.parsed.question),a.choices=f.length?f:[...S.parsed.reactable,...S.parsed.overflow].map(ls),a.body===void 0&&S.parsed.body)a.body=ls(S.parsed.body);if(!a.lang)a.lang=S.parsed.lang;if(a.explain===void 0&&S.parsed.explain)a.explain=!0;a.void=void 0}if(!p&&(a.target==="void"||g.length)){let k=a.target==="void"?[a.question,...a.choices??[]]:[];if(a.target!=="void"&&(a.target||a.question||a.choices?.length))console.error("Error: --void voids existing questions \u2014 do not also pass a target/question/choices."),process.exit(oe);let _=[...g,...k.map((R)=>String(R??""))].filter(Boolean);if(!_.length)console.error("Error: --void=<permalink> \u2014 which question(s)?"),process.exit(oe);if(a.wait||a.waitFor)console.error("Error: --void voids existing questions \u2014 do not also pass --wait/--waitFor."),process.exit(oe);let E,S;if(a["as-bot"]){let R=Le();if(!R)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
576
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);E=R}else E=e(a),S=t(a);let x={links:_,reason:je(String(a.reason??"")).trim(),asBot:!!a["as-bot"]};if(a["superseded-by"])x.supersededBy=String(a["superseded-by"]);if(a.code)x.code=String(a.code);if(S)x.cookie=S;try{await Rx(E,x)}catch(R){console.error(ge(R)),process.exit(oe)}return}if(a.target==="collect"){if(!a.question||a.choices?.length)console.error("Error: slack ask collect <permalink> \u2014 exactly one question."),process.exit(oe);a.waitFor=String(a.question),a.target=void 0,a.question=void 0}let h=a.waitFor?String(a.waitFor):"",m=Number(a.timeout);if(!Number.isFinite(m)||m<0||m===0&&!h)console.error("Error: --timeout must be a positive number of seconds"),process.exit(oe);if(h){if(a.target||a.question||a.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(oe);let k,_;if(a["as-bot"]){let E=Le();if(!E)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
577
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);k=E}else k=e(a),_=t(a);try{let E={link:h,timeout:m,asBot:!!a["as-bot"],json:!!a.json};if(a["explain-exit"])E.explainExit=!0;if(_)E.cookie=_;if(a.after){let S=String(a.after);if(!/^\d{10}\.\d{6}$/.test(S))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${M(S)})`),process.exit(oe);E.after=S}await Ix(k,E)}catch(E){console.error(ge(E)),process.exit(oe)}return}if(!a.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(oe);let y=String(a.question??"").trim();if(!y)console.error("Error: question is empty"),process.exit(oe);let w={allowUrlAdjacent:a["allow-url-adjacent"],target:a.target,question:y,choices:(a.choices??[]).map((k)=>String(k).trim()).filter(Boolean),timeout:m};if(a.code)w.code=a.code;if(a.body)w.body=a.body;if(a.lang)w.lang=String(a.lang);if(a.wait)w.wait=!0;if(a.json)w.json=!0;if(typeof a.explain==="boolean")w.explain=a.explain;if(a["explain-exit"])w.explainExit=!0;if(p)w.voidAfter=p;if(a["channel-id"])w.channelId=a["channel-id"];if(a["user-id"])w.userId=a["user-id"];let D;if(a["as-bot"]){let k=Le();if(!k)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
578
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(oe);if(!w.channelId&&!w.userId&&w.target.startsWith("@"))try{w.userId=await Ot(k,w.target)}catch(_){console.error(`Error: could not resolve ${w.target} to a user for the bot DM.
|
|
576
579
|
${_ instanceof Error?_.message:String(_)}
|
|
577
|
-
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(
|
|
578
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ht);return m};if(c){if(a.target||a.question||a.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(ht);let m=e(a),y=t(a);try{let w={link:c};if(a.close)w.close=!0;if(a.names)w.names=!0;if(a["no-notify"])w.noNotify=!0;if(y)w.cookie=y;if(a["as-bot"])w.writeToken=d();await Nx(m,w)}catch(w){console.error(
|
|
580
|
+
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(oe)}D=k,w.mentionToken=k,w.asBot=!0}else{D=e(a),w.mentionToken=D;let k=t(a);if(k)w.cookie=k,w.mentionCookie=k}try{await _x(D,w)}catch(k){console.error(ge(k)),process.exit(oe)}}).command(["poll [target] [question] [choices..]","vote [target] [question] [choices..]"],"Post a poll with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions, then count them (confirm-hash safety gate)",(a)=>a.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --results/--close)"}).positional("question",{type:"string",describe:"The question. @tags are optional here \u2014 unlike `ask`, a poll needs no addressee: anyone who can see it may vote."}).positional("choices",{type:"string",array:!0,describe:"2..10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions for voters to click"}).option("multi",{type:"boolean",default:!1,describe:"Let one person pick several choices (default: one vote per person)"}).option("until",{type:"string",describe:"Deadline shown in the message (display only \u2014 closing is still `--close`)"}).option("results",{type:"string",describe:"Count an existing poll: pass its permalink. Posts nothing; only edit is the invalid-ballot notice in the poll itself (--no-notify to suppress)."}).option("close",{type:"string",describe:"Count an existing poll AND freeze the tally into the message. Only the poster can do this."}).option("names",{type:"boolean",default:!1,describe:"Also list who voted for what (stderr)"}).option("no-notify",{type:"boolean",default:!1,describe:"With --results: do not write the invalid-ballot notice back into the message (keeps it strictly read-only)"}).option("code",{type:"string",describe:"Safety hash to confirm the post"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Post via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient \u2014 and so YOUR OWN vote counts, since the seeds are then the bot's. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(a)=>{let c=a.close?String(a.close):a.results?String(a.results):"";if(a.results&&a.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(ht);let d=()=>{let m=Le();if(!m)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
581
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(ht);return m};if(c){if(a.target||a.question||a.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(ht);let m=e(a),y=t(a);try{let w={link:c};if(a.close)w.close=!0;if(a.names)w.names=!0;if(a["no-notify"])w.noNotify=!0;if(y)w.cookie=y;if(a["as-bot"])w.writeToken=d();await Nx(m,w)}catch(w){console.error(ge(w)),process.exit(ht)}return}if(!a.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(ht);let f=String(a.question??"").trim();if(!f)console.error("Error: question is empty"),process.exit(ht);let p=(a.choices??[]).map((m)=>String(m).trim()).filter(Boolean);if(p.length<2||p.length>os)console.error(`Error: poll needs 2..${os} choices (got ${p.length}). For a free-text question use \`slack ask\`.`),process.exit(ht);let g={target:a.target,question:f,choices:p};if(a.multi)g.multi=!0;if(a.until)g.until=String(a.until);if(a.code)g.code=a.code;if(a.body)g.body=a.body;if(a["allow-url-adjacent"])g.allowUrlAdjacent=!0;if(a["channel-id"])g.channelId=a["channel-id"];if(a["user-id"])g.userId=a["user-id"];let h;if(a["as-bot"]){let m=d();if(!g.channelId&&!g.userId&&g.target.startsWith("@"))try{g.userId=await Ot(m,g.target)}catch(y){console.error(`Error: could not resolve ${g.target} to a user for the bot DM.
|
|
579
582
|
${y instanceof Error?y.message:String(y)}
|
|
580
|
-
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(ht)}h=m,g.mentionToken=m,g.asBot=!0}else{h=e(a),g.mentionToken=h;let m=t(a);if(m)g.cookie=m,g.mentionCookie=m}try{await Px(h,g)}catch(m){console.error(
|
|
583
|
+
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(ht)}h=m,g.mentionToken=m,g.asBot=!0}else{h=e(a),g.mentionToken=h;let m=t(a);if(m)g.cookie=m,g.mentionCookie=m}try{await Px(h,g)}catch(m){console.error(ge(m)),process.exit(ht)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(a)=>a.positional("query",{type:"string",describe:"Substring of the message text (case-insensitive)"}).option("channel",{type:"string",describe:"Channel/DM id (C\u2026/D\u2026) or the target as typed (#eng, @bob)"}).option("since",{type:"string",describe:"Only newer than this: 30m, 2h, 7d, 1w, or an ISO date"}).option("session",{type:"string",describe:"Agent session id (prefix match)"}).option("cwd",{type:"string",describe:"Working directory the sender ran in (prefix match)"}).option("kind",{type:"string",choices:["send","ask","poll","edit"],describe:"Only this kind of write"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per line (every recorded field)"}).option("count",{alias:"n",type:"number",default:50,describe:"Max rows (newest first)"}),(a)=>{let c;if(a.since!==void 0){if(c=is(String(a.since)),c===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${M(String(a.since))})`),process.exit(1)}let d={limit:Number(a.count)||50};if(a.query)d.text=String(a.query);if(a.channel)d.channel=String(a.channel);if(c!==void 0)d.sinceMs=c;if(a.session)d.session=String(a.session);if(a.cwd){let p=TD(String(a.cwd));try{d.cwd=$D(p)}catch{d.cwd=p}}if(a.kind)d.kind=a.kind;let f=wc(d);if(!f)console.error(`Error: ${Gs}
|
|
581
584
|
(${Tt()})`),process.exit(1);if(a.json){for(let p of f)console.log(JSON.stringify(p));return}if(!f.length){console.error(`No sent messages match (log: ${Tt()}).`);return}for(let p of f)console.log(ex(p))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(a)=>a,async()=>{let a=Le();if(!a)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
|
|
582
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await Mx(a)}).command("schedule","Manage scheduled messages",(a)=>a.command("send <target> <message>","Schedule a message for later delivery",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("at",{type:"string",demandOption:!0,describe:"Delivery time (ISO datetime or Unix ts)"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Schedule via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. Without it a scheduled DM to yourself is posted by you, and Slack never notifies you of your own message \u2014 it fires into silence."}),async(c)=>{if(!String(c.message??"").trim())console.error("Error: message is empty"),process.exit(1);let d={target:c.target,message:c.message,at:c.at};if(c.code)d.code=c.code;if(c["allow-url-adjacent"])d.allowUrlAdjacent=!0;if(c["channel-id"])d.channelId=c["channel-id"],d.targetOverride=`--channel-id ${c["channel-id"]}`;if(c["user-id"])d.userId=c["user-id"],d.targetOverride=`--user-id ${c["user-id"]}`;let f;if(c["as-bot"]){let p=
|
|
585
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await Mx(a)}).command("schedule","Manage scheduled messages",(a)=>a.command("send <target> <message>","Schedule a message for later delivery",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("at",{type:"string",demandOption:!0,describe:"Delivery time (ISO datetime or Unix ts)"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Schedule via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient. Without it a scheduled DM to yourself is posted by you, and Slack never notifies you of your own message \u2014 it fires into silence."}),async(c)=>{if(!String(c.message??"").trim())console.error("Error: message is empty"),process.exit(1);let d={target:c.target,message:c.message,at:c.at};if(c.code)d.code=c.code;if(c["allow-url-adjacent"])d.allowUrlAdjacent=!0;if(c["channel-id"])d.channelId=c["channel-id"],d.targetOverride=`--channel-id ${c["channel-id"]}`;if(c["user-id"])d.userId=c["user-id"],d.targetOverride=`--user-id ${c["user-id"]}`;let f;if(c["as-bot"]){let p=Bo();if(!d.channelId&&!d.userId&&d.target.startsWith("@"))try{d.userId=await Ot(e(c),d.target,t(c))}catch(g){console.error(`Error: could not resolve ${d.target} to a user for the bot DM.
|
|
583
586
|
${g instanceof Error?g.message:String(g)}
|
|
584
|
-
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}f=p,d.asBot=!0}else{f=e(c);let p=t(c);if(p)d.cookie=p}await Bx(f,d)}).command(["ls","list"],"List pending scheduled messages",(c)=>c.positional("target",{type:"string",describe:"#channel to filter by"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"List what the BOT token scheduled. A message from `schedule send --as-bot` belongs to the app, so the user token's listing does not contain it \u2014 and an invisible pending message cannot be cancelled."}),async(c)=>{let d=c.target;if(c["as-bot"]){let f=
|
|
585
|
-
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 a.command("new <channel> [state] [reason]","Post a NEW board in a channel and pin it \u2014 the state is the top-level message; prints the board's id (C\u2026:ts)",(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",c).example('slack pinlog new "#gtm" "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u672A"',"preview, then rerun with --code"),async(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?No(void 0,p.file):No(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 ix(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",c).example('slack pinlog set <board-link> "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u6E08" "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"").example('slack pinlog set <board-link> --file board.md "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"state from a file"),async(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?No(void 0,p.file):No(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 Yg(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",c),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 Yg(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",c),async(p)=>{let g=await d(p);await lx(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",c),async(p)=>{let g=await d(p);await ux(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",c),async(p)=>{let g=await d(p);await dx(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",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("emoji",{type:"string",demandOption:!0,describe:"Emoji shortcode without colons (e.g. eyes, white_check_mark, hourglass)"}).option("remove",{type:"boolean",default:!1,describe:"Remove the reaction instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(a)=>{let c={target:a.target,emoji:a.emoji};if(a.remove)c.remove=!0;if(a["channel-id"])c.channelId=a["channel-id"];let d=t(a);if(d)c.cookie=d;try{await fx(e(a),c)}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)",(a)=>a.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((c)=>{if(c.cache===!1)Kc(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(c)=>c.options(r).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(c)=>{await o(c,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("state",{type:"string",demandOption:!0,choices:["pending","doing","done","dropped"]}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(c)=>{let d={target:c.target,state:c.state};if(c["channel-id"])d.channelId=c["channel-id"];let f=t(c);if(f)d.cookie=f;try{await Uk(e(c),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",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("flag",{type:"string",demandOption:!0,choices:["alert","needs-discussion","waiting","blocked"],describe:"waiting = the other party in this conversation owes a reply; blocked = stuck on something outside it"}).option("remove",{type:"boolean",default:!1,describe:"Remove the flag instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(c)=>{let d={target:c.target,flag:c.flag};if(c.remove)d.remove=!0;if(c["channel-id"])d.channelId=c["channel-id"];let f=t(c);if(f)d.cookie=f;try{await Jk(e(c),d)}catch(p){console.error(pe(p)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(c)=>c.option("in",{type:"string",demandOption:!0,describe:"Channel to scan (#chan)"}).option("fix",{type:"boolean",default:!1,describe:"Repair findings (keeps the highest-priority state)"}).option("limit",{type:"number",default:Jc,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(c)=>{let d={channel:c.in,limit:c.limit};if(c.fix)d.fix=!0;if(c["channel-id"])d.channelId=c["channel-id"];let f=t(c);if(f)d.cookie=f;await Kk(e(c),d)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(a)=>a.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((c)=>{if(c.cache===!1)Kc(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(c)=>c.options(r),async(c)=>{await o(c,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}).option("as-bot",{type:"boolean",default:!1,describe:"Upload via the bot token (xoxb / SLACK_BOT_TOKEN); `slack @bot upload \u2026` does this too"}),async(a)=>{let c={target:a.target,filePaths:a.file};if(a.title)c.title=a.title;if(a.comment)c.comment=a.comment;if(a["allow-url-adjacent"])c.allowUrlAdjacent=!0;if(a.code)c.code=a.code;if(a["channel-id"])c.channelId=a["channel-id"];if(a["user-id"])c.userId=a["user-id"];if(a["as-bot"]){let f=Le();if(!f)console.error("Error: --as-bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);await sm(f,c);return}let d=t(a);if(d)c.cookie=d;await sm(e(a),c)}).command("files","File commands",(a)=>a.command(["ls","list"],"List files visible to you (files.list)",(c)=>c.option("limit",{alias:"l",type:"number",default:100,describe:"Max files to list"}).option("type",{alias:"t",type:"string",describe:"Slack type filter: images, pdfs, gdocs, snippets, zips, spaces, all"}).option("channel",{alias:"c",type:"string",describe:"Only files in this channel (#name, @user, ID, or permalink)"}).option("user",{alias:"u",type:"string",describe:"Only files from this raw user ID"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(c)=>{let d={limit:c.limit,format:c.json?"jsonl":c.format};if(c.type)d.types=c.type;if(c.channel)d.channel=c.channel;if(c.user)d.user=c.user;await jx(e(c),t(c),d)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(a)=>a.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(c)=>c.positional("name",{type:"string",demandOption:!0,describe:"List name"}).option("col",{type:"string",array:!0,default:[],describe:"Column name:type (text|select|user|link|date|number|checkbox); select takes name:select:a,b,c. First is the primary text column. Repeatable"}).option("todo",{type:"boolean",default:!1,describe:"Todo mode: adds Completed / Assignee / Due date columns"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(c)=>{try{let d={name:c.name,cols:c.col,todo:c.todo===!0};if(c.code!==void 0)d.code=c.code;await Kx(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)",(c)=>c.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("text",{type:"string",demandOption:!0,describe:"Primary (first text) column value"}).option("set",{type:"string",array:!0,default:[],describe:"Other cells: column=value (repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm add"}),async(c)=>{try{let d={list:c.list,text:c.text,sets:c.set};if(c.code!==void 0)d.code=c.code;await qx(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)",(c)=>c.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("row",{type:"string",demandOption:!0,describe:"Row id (Rec\u2026), as printed by lists add / lists <ref>"}).option("set",{type:"string",array:!0,default:[],describe:"column=value (repeatable)"}).option("done",{type:"boolean",describe:"Check the row off (--no-done to uncheck); needs a todo-mode list"}).option("code",{type:"string",describe:"Safety hash to confirm update"}),async(c)=>{try{let d={list:c.list,row:c.row,sets:c.set};if(c.done!==void 0)d.done=c.done;if(c.code!==void 0)d.code=c.code;await Hx(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)",(c)=>c.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).option("user",{type:"string",array:!0,default:[],describe:"User ID (U\u2026), repeatable"}).option("channel",{type:"string",array:!0,default:[],describe:"Channel ID (C\u2026), repeatable"}).option("level",{type:"string",choices:["read","write","owner"],default:"write"}).option("code",{type:"string",describe:"Safety hash to confirm share"}),async(c)=>{try{let d={list:c.list,users:c.user,channels:c.channel,level:c.level};if(c.code!==void 0)d.code=c.code;await zx(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",(c)=>c.positional("ref",{type:"string",demandOption:!0,describe:"List URL (\u2026/lists/<TEAM>/<F-id>) or bare F-id"}).option("limit",{alias:"l",type:"number",default:100,describe:"Max rows to show"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl (raw records)"}).option("as-bot",{type:"boolean",default:!1,describe:"Read with the bot token (SLACK_BOT_TOKEN, lists:read) via the public API instead of the user session"}),async(c)=>{let d=c.json?"jsonl":c.format;try{let f=c.asBot===!0;await Ux(f?"":e(c),f?void 0:t(c),c.ref,{limit:c.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",(a)=>a.positional("ref",{type:"string",demandOption:!0,describe:"File ID (F\u2026) or Slack file permalink"}).positional("dest",{type:"string",describe:"Output path or directory (default: ./<filename>)"}),async(a)=>{await Gx(e(a),t(a),a.ref,a.dest)}).command("dump","Bulk export channel history as markdown",(a)=>a.option("days",{alias:"d",type:"number",default:7,describe:"Days of history"}).option("limit",{alias:"l",type:"number",default:200}).option("filter",{alias:"f",type:"string",describe:"Filter channel names"}),async(a)=>{await qk(e(a),a.days,a.limit,a.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (requires xoxc desktop token). Not `slack todo` (reaction tasks)",(a)=>a.command(["$0","ls","list"],"List your To-dos, soonest due first",(c)=>c.option("filter",{type:"string",choices:[...og],default:"todo",describe:"todo = open to-dos; saved = everything saved; completed; archived"}).option("limit",{alias:"n",type:"number",default:50,describe:"At most this many items"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per item (raw fields + permalink + message text)"}),async(c)=>{if(!Number.isInteger(c.limit)||c.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${c.limit}).`),process.exit(2);await Yk(e(c),t(c),{filter:c.filter,limit:c.limit,json:c.json})}).command("add <target>","Add a message to your To-dos (two-step: preview, then --code)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"Due time (ISO datetime or Unix ts)"}).option("saved",{type:"boolean",default:!1,describe:"Save it without a checkbox instead of as a to-do"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{let d=c.due===void 0?void 0:em(c.due);await Lo(e(c),t(c),c.target,{kind:"add",...d?{due:d}:{},saved:c.saved},c.code)}).command(["done <target>","complete <target>"],"Check a to-do off (--undo reopens it)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("undo",{type:"boolean",default:!1,describe:"Mark it not done again"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{await Lo(e(c),t(c),c.target,{kind:"done",undo:c.undo},c.code)}).command("edit <target>","Change a to-do's due date, or switch it between to-do and saved item",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"New due time (ISO datetime or Unix ts), or `none` to clear it"}).option("todo",{type:"boolean",describe:"Make it a to-do (with a checkbox)"}).option("saved",{type:"boolean",describe:"Make it a plain saved item (no checkbox)"}).conflicts("todo","saved").option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{let d=c.due===void 0?void 0:c.due==="none"?0:em(c.due),f=c.todo?!0:c.saved?!1:void 0;await Lo(e(c),t(c),c.target,{kind:"edit",...d===void 0?{}:{due:d},...f===void 0?{}:{todo:f}},c.code)}).command(["rm <target>","remove <target>","delete <target>"],"Remove a message from your To-dos (the message stays)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{await Lo(e(c),t(c),c.target,{kind:"rm"},c.code)})).command("drafts","Manage message drafts (requires xoxc desktop token)",(a)=>a.command(["$0","ls","list"],"List pending drafts",(c)=>c.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(c)=>{await zk(e(c),t(c),c.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(c)=>c.positional("channel",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(c)=>{let d=e(c),f=t(c),p=c.text.join(" ");if(!p)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);Ke(p,c["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let g=await ye(d,c.channel,f),h=await Zh(d,g,p,f);console.log(`\u2713 Draft created (id: ${F(h.draft).id??"?"})`)}).command("get <id>","Show a draft",(c)=>c.positional("id",{type:"string",demandOption:!0}),async(c)=>{await Zk(e(c),t(c),c.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(c)=>c.positional("id",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("code",{type:"string"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(c)=>{let d=e(c),f=t(c),p=c.text.join(" ");if(!p)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);Ke(p,c["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let g=await Qs(d,f),h=Y(g.drafts).map(F).find((D)=>String(D.id)===c.id);if(!h)console.error(`Draft not found: ${c.id}`),process.exit(1);let m=Uo(h),y=await Me(d,f),w=we(m,p,y?.userId??"");if(c.code!==w)xe(c.code,w,["--- Editing draft as -------------------------",_e(y),"--- Current draft ----------------------------",...m.split(`
|
|
586
|
-
`).map((
|
|
587
|
-
`).map((
|
|
588
|
-
`).map((w)=>` ${w}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await ng(d,c.id,f),console.log(`\u2713 Draft deleted (id: ${c.id})`)})).command("auth","Authentication and workspace management",(a)=>a.command("token","Print the active token (or save one with --token)",(c)=>c.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(c)=>{if(c.token===void 0){console.log(
|
|
589
|
-
`))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(c)=>c.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(c)=>{await Kd({...c.bot!==void 0?{bot:c.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(c)=>c.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(d)=>d.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(d)=>{await ma({...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 ya({...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 Ls({...d.token!==void 0?{token:d.token}:{},...d.name!==void 0?{name:d.name}:{},yes:d.yes,fromDesktop:d.fromDesktop,fromChrome:d.fromChrome,fromFirefox:d.fromFirefox,fromAll:d.fromAll})}),async(c)=>{await Ls({...c.token!==void 0?{token:c.token}:{},...c.name!==void 0?{name:c.name}:{},yes:c.yes,fromDesktop:c.fromDesktop,fromChrome:c.fromChrome,fromFirefox:c.fromFirefox,fromAll:c.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(c)=>c.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(c)=>qd({...c.workspace!==void 0?{workspace:c.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(c)=>c.option("envfile",{type:"string",demandOption:!0,describe:"Destination env file (e.g. ./.env.local)"}).option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(c)=>Hd({envfile:c.envfile,...c.workspace!==void 0?{workspace:c.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let c=Mi();if(c.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:d,profile:f,current:p}of c)console.log(`${p?"* ":" "}${d} ${f.team} (${f.user}) ${f.url??""}`)}).command("use <name>","Switch active workspace",(c)=>c.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(c)=>{if(!c.g)Fk(gt(process.cwd(),".slack-cli"));cd(c.name,c.g),console.log(`Switched to workspace "${c.name}" ${c.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(c)=>c.positional("name",{type:"string",demandOption:!0}),(c)=>{ad(c.name),console.log(`Removed workspace "${c.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(c)=>c.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("profile",{type:"string",alias:"p",describe:"Chrome profile email or dir (Windows, when several have a session)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(c)=>{await Ud({...c.workspace!==void 0?{workspace:c.workspace}:{},...c.profile!==void 0?{profile:c.profile}:{},yes:c.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(c)=>c.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(c)=>{await ya({...c.workspace!==void 0?{workspace:c.workspace}:{},yes:c.yes})}).command("$0",!1,()=>{},()=>{a.showHelp(),process.exit(0)})).command("relay","Set up / check the real-time relay for `slack stream` (a Cloudflare Worker)",(a)=>a.command("init [dir]","Scaffold a deployable relay Worker folder (local files only; prints a fresh RELAY_TOKEN and the next steps)",(c)=>c.positional("dir",{type:"string",default:Fa,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"}),(c)=>{let d=Cf(c.dir,{force:c.force,...c.name!==void 0?{name:c.name}:{},...c["slack-term"]!==void 0?{slackTerm:c["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(Af(d))}).command("health","GET /health on the relay (SLACK_RELAY_URL / SLACK_RELAY_TOKEN); exit 0 = ok",(c)=>c.option("url",{type:"string",describe:"Relay URL (default: $SLACK_RELAY_URL)"}).option("token",{type:"string",describe:"Relay token (default: $SLACK_RELAY_TOKEN)"}),async(c)=>{let d=await Tf(c.url??process.env.SLACK_RELAY_URL,c.token??process.env.SLACK_RELAY_TOKEN);(d.code===0?console.log:console.error)(d.out),process.exit(d.code)}).demandCommand(1,"Specify a relay subcommand (init, health)")).command("stream","Print every new message matching --grep, across all channels the identity is in (threads included); resumable",(a)=>a.option("grep",{alias:"e",type:"string",demandOption:!0,describe:"Regex matched against each message's text (raw, e.g. <@U00000001>). Non-matching messages are never printed or logged"}).option("ignore-case",{alias:"i",type:"boolean",default:!1,describe:"Case-insensitive --grep"}).option("channel",{type:"array",string:!0,describe:"Only these channels (#name, id or permalink); repeatable"}).option("replies-to",{type:"array",string:!0,describe:"Also print replies in threads this id started or replied in (user U\u2026/bot B\u2026; `self` = the streaming identity), --grep or not; repeatable"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per match: type, channel{id,name}, ts, thread_ts, user{id,name}, text, permalink, match (grep | replies-to)"}).option("once",{type:"boolean",default:!1,describe:"Scan once from the saved cursor (or --since) and exit: 0 = matches printed, 2 = none, 3 = failure"}).option("since",{type:"string",describe:"Replay from this long ago (e.g. 30m, 2h), ignoring the saved cursor"}).option("interval",{type:"string",default:"45s",describe:"Poll interval (e.g. 30s, 2m)"}).option("thread-window",{type:"string",default:"3d",describe:"Watch replies in threads whose parent is at most this old"}).option("thread-scan",{type:"string",default:"3m",describe:"Polling: re-read each channel's whole --thread-window this often (cycles in between read only what is new)"}).option("calls-per-min",{type:"number",default:40,describe:"Polling: pace conversations.history/replies to this many calls per minute (0 = unpaced)"}).option("state",{type:"string",describe:"Cursor file (default: one per identity+grep+channels under $XDG_STATE_HOME/slack-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(a)=>{let c,d,f,p,g,h;try{c=new RegExp(a.grep,a["ignore-case"]?"i":""),f=en(a.interval)*1000,p=en(a["thread-window"]),g=en(a["thread-scan"]),h=a.since!==void 0?en(a.since):void 0,d=en(a.reconcile)*1000}catch(O){console.error(`slack stream: ${O instanceof Error?O.message:String(O)}`),process.exit(1)}let m=Le(),y=a["as-user"]===!0||!m,w=y?e(a):m,k=y?t(a):void 0;if(!m&&a["as-user"]!==!0)console.error("slack stream: no bot token (SLACK_BOT_TOKEN) \u2014 streaming as the USER identity, which includes its DMs.");let D;try{D=await Mt(w,k)}catch(O){console.error(`slack stream: fatal: ${O instanceof Error?O.message:String(O)}`),process.exit(3)}let _=new Set([D.userId].filter(Boolean)),C=new Set([D.botId].filter(Boolean));if(y&&m)try{let O=await Mt(m);if(O.userId)_.add(O.userId);if(O.botId)C.add(O.botId)}catch{}let S;if(a["replies-to"]?.length){S=new Set;for(let O of a["replies-to"].map(String)){if(O==="self"){for(let te of[D.userId,D.botId])if(te)S.add(te);continue}if(!/^[UWB][A-Z0-9]{2,}$/.test(O))console.error(`slack stream: --replies-to: "${O}" is not a user or bot id (U\u2026/W\u2026/B\u2026) or "self"`),process.exit(1);if(S.add(O),O.startsWith("B"))try{let{userId:te}=await Eh(w,O,k);if(te)S.add(te)}catch(te){console.error(`slack stream: --replies-to ${O}: cannot resolve its bot user id (${te instanceof Error?te.message:String(te)}); threads where it shows as a user id are missed`)}}}let x;if(a.channel?.length)try{x=[];for(let O of a.channel)x.push(await ye(w,String(O),k))}catch(O){console.error(`slack stream: --channel: ${O instanceof Error?O.message:String(O)}`),process.exit(1)}let R=rm("sha256").update(JSON.stringify([D.url,D.userId,c.source,c.flags,[...x??[]].sort(),...a["replies-to"]?.length?[[...a["replies-to"].map(String)].sort()]:[]])).digest("hex").slice(0,16),L=process.env.XDG_STATE_HOME||gt(Bo(),".local","state"),P=a.state??gt(L,"slack-term","stream",`${R}.json`);console.error(`slack stream: as ${y?"user":"bot"} @${D.user} (${D.userId}); state ${P}`);let v=process.env.SLACK_RELAY_URL,M=process.env.SLACK_RELAY_TOKEN,U=a.relay&&!y&&!a.once&&v&&M?{url:v,subscribe:Ca(v,M,void 0,{transport:$a(process.env.SLACK_RELAY_TRANSPORT)}),reconcileMs:d}:void 0;if(a.relay&&y&&v)console.error("slack stream: relay not used with --as-user (it only sees the bot's channels)");let N=!a.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",K=new AbortController;process.on("SIGINT",()=>K.abort()),process.on("SIGTERM",()=>K.abort()),Ec(0);let z=await af(rf(w,k),{grep:c,...S?{repliesTo:S}:{},...x?{channels:x}:{},selfUsers:_,selfBots:C,json:a.json,reactions:a.reactions,...a.inbox?{onMatch:(O,te)=>{try{let Q=[w,k,process.env.SLACK_RELAY_TOKEN].filter((re)=>!!re),j=Mp({...O,...te?{files:te}:{}},void 0,new Date,Q);if(j.length)console.error(`slack stream: delivered ${O.channel.id}:${O.ts} to ${j.length} inbox(es)`)}catch(Q){console.error(`slack stream: inbox delivery failed: ${Q instanceof Error?Q.message:String(Q)}`)}}}:{},once:a.once,...h!==void 0?{sinceSec:h}:{},intervalMs:f,threadWindowSec:p,threadScanSec:g,callsPerMin:a["calls-per-min"],...U?{}:{pollReason:N},statePath:P,teamUrl:D.url,identity:D.userId,signal:K.signal,...U?{relay:U}:{}});process.exit(z)}).command("tail [target]","Stream new messages in real time (like tail -f)",(a)=>a.positional("target",{type:"string",describe:"#channel or @user to follow"}).option("since",{type:"string",describe:"Backfill from N ago (e.g. 10m, 2h, 1d)"}).option("thread",{type:"string",describe:"Follow a single thread by timestamp"}).option("watch-thread",{type:"string",describe:"Watch the channel's top-level timeline AND one thread's replies together (ts or permalink)"}).option("me",{type:"boolean",default:!1,describe:"Filter to messages that mention you"}).option("interval",{type:"number",default:60000,describe:"Poll interval in ms (default 60s; use --interval=3000 for near-real-time)"}).option("timeout",{type:"string",describe:"Auto-stop after this long (e.g. 30m, 2h). Exit code 0 even if nothing arrived."}).option("exit-on-message",{type:"boolean",default:!1,describe:"Stop as soon as the first new message from someone else arrives (wait-for-reply)"}).option("rtm",{type:"boolean",default:!0,describe:"Use RTM WebSocket when available (xoxc + cookie); pass --no-rtm to force polling"}),async(a)=>{let c=e(a),d=t(a),f=new AbortController;process.on("SIGINT",()=>{f.abort(),process.exit(0)}),await Zd(c,a.target,{...a.since!==void 0?{since:a.since}:{},...a.thread!==void 0?{thread:a.thread}:{},...a["watch-thread"]!==void 0?{watchThread:a["watch-thread"]}:{},me:a.me,interval:a.interval,...a.timeout!==void 0?{timeout:a.timeout}:{},...a["exit-on-message"]===!0?{exitOnMessage:!0}:{},...d!==void 0?{cookie:d}:{},...a.rtm===!1?{noRtm:!0}:{}},f.signal)}).command("login",!1,(a)=>a.option("token",{type:"string"}).option("name",{type:"string"}).option("yes",{type:"boolean",default:!1}).option("from-desktop",{type:"boolean",default:!1}).option("from-chrome",{type:"boolean",default:!1}).option("from-firefox",{type:"boolean",default:!1}).option("from-all",{type:"boolean",default:!1}),async(a)=>{await Ls({...a.token!==void 0?{token:a.token}:{},...a.name!==void 0?{name:a.name}:{},yes:a.yes,fromDesktop:a.fromDesktop,fromChrome:a.fromChrome,fromFirefox:a.fromFirefox,fromAll:a.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}Xx().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
|
|
587
|
+
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}f=p,d.asBot=!0}else{f=e(c);let p=t(c);if(p)d.cookie=p}await Bx(f,d)}).command(["ls","list"],"List pending scheduled messages",(c)=>c.positional("target",{type:"string",describe:"#channel to filter by"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"List what the BOT token scheduled. A message from `schedule send --as-bot` belongs to the app, so the user token's listing does not contain it \u2014 and an invisible pending message cannot be cancelled."}),async(c)=>{let d=c.target;if(c["as-bot"]){let f=Bo(),p=c["channel-id"];if(!p&&d?.startsWith("@"))p=await Qg(d,f,e(c),t(c));await tm(f,d,p);return}await tm(e(c),d,c["channel-id"],t(c))}).command("rm <target> <id>","Delete a scheduled message",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#channel or @user"}).positional("id",{type:"string",demandOption:!0,describe:"Scheduled message ID"}).option("code",{type:"string",describe:"Safety hash to confirm"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Cancel a message scheduled with `schedule send --as-bot`. It belongs to the bot token, so the user token cannot delete it."}),async(c)=>{let d={target:c.target,id:c.id};if(c.code)d.code=c.code;if(c["channel-id"])d.channelId=c["channel-id"],d.targetOverride=`--channel-id ${c["channel-id"]}`;if(c["as-bot"]){let p=Bo();if(!d.channelId&&d.target.startsWith("@"))d.channelId=await Qg(d.target,p,e(c),t(c));d.asBot=!0,await nm(p,d);return}let f=t(c);if(f)d.cookie=f;await nm(e(c),d)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("newText",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm edit"}).option("force",{type:"boolean",default:!1,describe:"Apply an edit that BREAKS a `slack ask` / `slack poll` message (new text no longer reads as one, or an answered/void question made open again). Refused by default because collect reads that body back; edits that keep it readable (e.g. writing the \u2705 form) need no flag. Prefer `slack ask --edit=` / `--void=`."}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("fix-urls",{type:"boolean",default:!1,describe:"Wrap ambiguous bare URLs as <url> (cut at the first non-ASCII character / trailing punctuation) before sending"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens in the new text to real <@USERID> mentions (on by default). Unresolved handles stay as plain text. Disable with --no-mentions for literal @text."}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED to correct a message the bot posted: Slack only lets a token edit its OWN messages, so a bot-authored message is uneditable by the user token and chat.update returns cant_update_message. Address it by permalink or --channel-id; an @user target resolves against the BOT's DM list, which is where a bot-authored DM actually lives."}),async(a)=>n(a)).command("tick <target> [n]","Tick item n of a posted checklist (\u2B1C n. \u2192 \u2705 n.), nothing else changed; without n, the one open item (confirm-hash gate, like edit)",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("n",{type:"number",describe:"Item number"}).option("code",{type:"string",describe:"Safety hash to confirm the edit"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (needed for a message the bot posted)"}),async(a)=>n({...a,tick:a.n!==void 0?{n:a.n}:{},mentions:!1})).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).option("code",{type:"string",describe:"Safety hash to confirm delete"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("as-bot",{type:"boolean",default:!1,describe:"Delete as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED for a message the bot posted: chat.delete refuses another token's message exactly as chat.update does."}),async(a)=>{let c={target:a.target};if(a.code)c.code=a.code;if(a["channel-id"])c.channelId=a["channel-id"];let d;if(a["as-bot"]){let f=await Hg(c.target,e(a),t(a),c.channelId);if(d=f.botToken,f.channelId&&!c.channelId)c.channelId=f.channelId;c.asBot=!0}else{d=e(a);let f=t(a);if(f)c.cookie=f}await rx(d,c)}).command("pinlog","Pinned status board: the pinned top-level message is the current state (edited in place, silent); each change is one thread reply (the log, notifies)",(a)=>{let c={type:"boolean",default:!1,describe:"Act via the bot token (xoxb / SLACK_BOT_TOKEN). A board the bot created can only be updated --as-bot: Slack lets a token edit only its own messages."},d=async(p)=>{if(p["as-bot"]){let h=Bo();if(typeof p.workspace==="string"){let m=t(p),[y,w]=await Promise.all([Mt(e(p),m),Mt(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}.
|
|
588
|
+
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(ge(p)),process.exit(1)};return a.command("new <channel> [state] [reason]","Post a NEW board in a channel and pin it \u2014 the state is the top-level message; prints the board's id (C\u2026:ts)",(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",c).example('slack pinlog new "#gtm" "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u672A"',"preview, then rerun with --code"),async(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?Mo(void 0,p.file):Mo(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 ix(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",c).example('slack pinlog set <board-link> "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u6E08" "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"").example('slack pinlog set <board-link> --file board.md "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"state from a file"),async(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?Mo(void 0,p.file):Mo(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 Yg(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",c),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 Yg(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",c),async(p)=>{let g=await d(p);await lx(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",c),async(p)=>{let g=await d(p);await ux(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",c),async(p)=>{let g=await d(p);await dx(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",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("emoji",{type:"string",demandOption:!0,describe:"Emoji shortcode without colons (e.g. eyes, white_check_mark, hourglass)"}).option("remove",{type:"boolean",default:!1,describe:"Remove the reaction instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(a)=>{let c={target:a.target,emoji:a.emoji};if(a.remove)c.remove=!0;if(a["channel-id"])c.channelId=a["channel-id"];let d=t(a);if(d)c.cookie=d;try{await fx(e(a),c)}catch(f){console.error(ge(f)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(a)=>a.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((c)=>{if(c.cache===!1)qc(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(c)=>c.options(r).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(c)=>{await o(c,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("state",{type:"string",demandOption:!0,choices:["pending","doing","done","dropped"]}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(c)=>{let d={target:c.target,state:c.state};if(c["channel-id"])d.channelId=c["channel-id"];let f=t(c);if(f)d.cookie=f;try{await UD(e(c),d)}catch(p){console.error(ge(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",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("flag",{type:"string",demandOption:!0,choices:["alert","needs-discussion","waiting","blocked"],describe:"waiting = the other party in this conversation owes a reply; blocked = stuck on something outside it"}).option("remove",{type:"boolean",default:!1,describe:"Remove the flag instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(c)=>{let d={target:c.target,flag:c.flag};if(c.remove)d.remove=!0;if(c["channel-id"])d.channelId=c["channel-id"];let f=t(c);if(f)d.cookie=f;try{await JD(e(c),d)}catch(p){console.error(ge(p)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(c)=>c.option("in",{type:"string",demandOption:!0,describe:"Channel to scan (#chan)"}).option("fix",{type:"boolean",default:!1,describe:"Repair findings (keeps the highest-priority state)"}).option("limit",{type:"number",default:Kc,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(c)=>{let d={channel:c.in,limit:c.limit};if(c.fix)d.fix=!0;if(c["channel-id"])d.channelId=c["channel-id"];let f=t(c);if(f)d.cookie=f;await KD(e(c),d)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(a)=>a.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((c)=>{if(c.cache===!1)qc(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(c)=>c.options(r),async(c)=>{await o(c,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(a)=>a.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}).option("as-bot",{type:"boolean",default:!1,describe:"Upload via the bot token (xoxb / SLACK_BOT_TOKEN); `slack @bot upload \u2026` does this too"}),async(a)=>{let c={target:a.target,filePaths:a.file};if(a.title)c.title=a.title;if(a.comment)c.comment=a.comment;if(a["allow-url-adjacent"])c.allowUrlAdjacent=!0;if(a.code)c.code=a.code;if(a["channel-id"])c.channelId=a["channel-id"];if(a["user-id"])c.userId=a["user-id"];if(a["as-bot"]){let f=Le();if(!f)console.error("Error: --as-bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);await sm(f,c);return}let d=t(a);if(d)c.cookie=d;await sm(e(a),c)}).command("files","File commands",(a)=>a.command(["ls","list"],"List files visible to you (files.list)",(c)=>c.option("limit",{alias:"l",type:"number",default:100,describe:"Max files to list"}).option("type",{alias:"t",type:"string",describe:"Slack type filter: images, pdfs, gdocs, snippets, zips, spaces, all"}).option("channel",{alias:"c",type:"string",describe:"Only files in this channel (#name, @user, ID, or permalink)"}).option("user",{alias:"u",type:"string",describe:"Only files from this raw user ID"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(c)=>{let d={limit:c.limit,format:c.json?"jsonl":c.format};if(c.type)d.types=c.type;if(c.channel)d.channel=c.channel;if(c.user)d.user=c.user;await jx(e(c),t(c),d)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(a)=>a.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(c)=>c.positional("name",{type:"string",demandOption:!0,describe:"List name"}).option("col",{type:"string",array:!0,default:[],describe:"Column name:type (text|select|user|link|date|number|checkbox); select takes name:select:a,b,c. First is the primary text column. Repeatable"}).option("todo",{type:"boolean",default:!1,describe:"Todo mode: adds Completed / Assignee / Due date columns"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(c)=>{try{let d={name:c.name,cols:c.col,todo:c.todo===!0};if(c.code!==void 0)d.code=c.code;await Kx(d)}catch(d){console.error(ge(d)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(c)=>c.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("text",{type:"string",demandOption:!0,describe:"Primary (first text) column value"}).option("set",{type:"string",array:!0,default:[],describe:"Other cells: column=value (repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm add"}),async(c)=>{try{let d={list:c.list,text:c.text,sets:c.set};if(c.code!==void 0)d.code=c.code;await qx(d)}catch(d){console.error(ge(d)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(c)=>c.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("row",{type:"string",demandOption:!0,describe:"Row id (Rec\u2026), as printed by lists add / lists <ref>"}).option("set",{type:"string",array:!0,default:[],describe:"column=value (repeatable)"}).option("done",{type:"boolean",describe:"Check the row off (--no-done to uncheck); needs a todo-mode list"}).option("code",{type:"string",describe:"Safety hash to confirm update"}),async(c)=>{try{let d={list:c.list,row:c.row,sets:c.set};if(c.done!==void 0)d.done=c.done;if(c.code!==void 0)d.code=c.code;await Hx(d)}catch(d){console.error(ge(d)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(c)=>c.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).option("user",{type:"string",array:!0,default:[],describe:"User ID (U\u2026), repeatable"}).option("channel",{type:"string",array:!0,default:[],describe:"Channel ID (C\u2026), repeatable"}).option("level",{type:"string",choices:["read","write","owner"],default:"write"}).option("code",{type:"string",describe:"Safety hash to confirm share"}),async(c)=>{try{let d={list:c.list,users:c.user,channels:c.channel,level:c.level};if(c.code!==void 0)d.code=c.code;await zx(d)}catch(d){console.error(ge(d)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(c)=>c.positional("ref",{type:"string",demandOption:!0,describe:"List URL (\u2026/lists/<TEAM>/<F-id>) or bare F-id"}).option("limit",{alias:"l",type:"number",default:100,describe:"Max rows to show"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl (raw records)"}).option("as-bot",{type:"boolean",default:!1,describe:"Read with the bot token (SLACK_BOT_TOKEN, lists:read) via the public API instead of the user session"}),async(c)=>{let d=c.json?"jsonl":c.format;try{let f=c.asBot===!0;await Ux(f?"":e(c),f?void 0:t(c),c.ref,{limit:c.limit,format:d,asBot:f})}catch(f){console.error(ge(f)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(a)=>a.positional("ref",{type:"string",demandOption:!0,describe:"File ID (F\u2026) or Slack file permalink"}).positional("dest",{type:"string",describe:"Output path or directory (default: ./<filename>)"}),async(a)=>{await Gx(e(a),t(a),a.ref,a.dest)}).command("dump","Bulk export channel history as markdown",(a)=>a.option("days",{alias:"d",type:"number",default:7,describe:"Days of history"}).option("limit",{alias:"l",type:"number",default:200}).option("filter",{alias:"f",type:"string",describe:"Filter channel names"}),async(a)=>{await qD(e(a),a.days,a.limit,a.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (requires xoxc desktop token). Not `slack todo` (reaction tasks)",(a)=>a.command(["$0","ls","list"],"List your To-dos, soonest due first",(c)=>c.option("filter",{type:"string",choices:[...og],default:"todo",describe:"todo = open to-dos; saved = everything saved; completed; archived"}).option("limit",{alias:"n",type:"number",default:50,describe:"At most this many items"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per item (raw fields + permalink + message text)"}),async(c)=>{if(!Number.isInteger(c.limit)||c.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${c.limit}).`),process.exit(2);await YD(e(c),t(c),{filter:c.filter,limit:c.limit,json:c.json})}).command("add <target>","Add a message to your To-dos (two-step: preview, then --code)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"Due time (ISO datetime or Unix ts)"}).option("saved",{type:"boolean",default:!1,describe:"Save it without a checkbox instead of as a to-do"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{let d=c.due===void 0?void 0:em(c.due);await No(e(c),t(c),c.target,{kind:"add",...d?{due:d}:{},saved:c.saved},c.code)}).command(["done <target>","complete <target>"],"Check a to-do off (--undo reopens it)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("undo",{type:"boolean",default:!1,describe:"Mark it not done again"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{await No(e(c),t(c),c.target,{kind:"done",undo:c.undo},c.code)}).command("edit <target>","Change a to-do's due date, or switch it between to-do and saved item",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("due",{type:"string",describe:"New due time (ISO datetime or Unix ts), or `none` to clear it"}).option("todo",{type:"boolean",describe:"Make it a to-do (with a checkbox)"}).option("saved",{type:"boolean",describe:"Make it a plain saved item (no checkbox)"}).conflicts("todo","saved").option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{let d=c.due===void 0?void 0:c.due==="none"?0:em(c.due),f=c.todo?!0:c.saved?!1:void 0;await No(e(c),t(c),c.target,{kind:"edit",...d===void 0?{}:{due:d},...f===void 0?{}:{todo:f}},c.code)}).command(["rm <target>","remove <target>","delete <target>"],"Remove a message from your To-dos (the message stays)",(c)=>c.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(c)=>{await No(e(c),t(c),c.target,{kind:"rm"},c.code)})).command("drafts","Manage message drafts (requires xoxc desktop token)",(a)=>a.command(["$0","ls","list"],"List pending drafts",(c)=>c.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(c)=>{await zD(e(c),t(c),c.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(c)=>c.positional("channel",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(c)=>{let d=e(c),f=t(c),p=c.text.join(" ");if(!p)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);Ke(p,c["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let g=await we(d,c.channel,f),h=await Zh(d,g,p,f);console.log(`\u2713 Draft created (id: ${F(h.draft).id??"?"})`)}).command("get <id>","Show a draft",(c)=>c.positional("id",{type:"string",demandOption:!0}),async(c)=>{await ZD(e(c),t(c),c.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(c)=>c.positional("id",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("code",{type:"string"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(c)=>{let d=e(c),f=t(c),p=c.text.join(" ");if(!p)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);Ke(p,c["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let g=await er(d,f),h=z(g.drafts).map(F).find((k)=>String(k.id)===c.id);if(!h)console.error(`Draft not found: ${c.id}`),process.exit(1);let m=Jo(h),y=await Me(d,f),w=De(m,p,y?.userId??"");if(c.code!==w)Se(c.code,w,["--- Editing draft as -------------------------",Ee(y),"--- Current draft ----------------------------",...m.split(`
|
|
589
|
+
`).map((k)=>` ${k}`),"--- Replacing with ---------------------------",...p.split(`
|
|
590
|
+
`).map((k)=>` ${k}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let D=await Qh(d,c.id,pl(h),p,f);console.log(`\u2713 Draft updated (id: ${F(D.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(c)=>c.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(c)=>{let d=e(c),f=t(c),p=await er(d,f),g=z(p.drafts).map(F).find((w)=>String(w.id)===c.id);if(!g)console.error(`Draft not found: ${c.id}`),process.exit(1);let h=Jo(g),m=await Me(d,f),y=De(c.id,h,m?.userId??"");if(c.code!==y)Se(c.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: ${c.id}`,...h.split(`
|
|
591
|
+
`).map((w)=>` ${w}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await ng(d,c.id,f),console.log(`\u2713 Draft deleted (id: ${c.id})`)})).command("auth","Authentication and workspace management",(a)=>a.command("token","Print the active token (or save one with --token)",(c)=>c.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(c)=>{if(c.token===void 0){console.log($s(c.workspace));return}await Kd({...c.token!==void 0?{token:c.token}:{},...c.name!==void 0?{name:c.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(c)=>{let d=$s(c.workspace),f=d.startsWith("xoxc-")?Bi(c.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(`
|
|
592
|
+
`))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(c)=>c.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(c)=>{await qd({...c.bot!==void 0?{bot:c.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(c)=>c.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(d)=>d.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(d)=>{await ma({...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 ya({...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 Ns({...d.token!==void 0?{token:d.token}:{},...d.name!==void 0?{name:d.name}:{},yes:d.yes,fromDesktop:d.fromDesktop,fromChrome:d.fromChrome,fromFirefox:d.fromFirefox,fromAll:d.fromAll})}),async(c)=>{await Ns({...c.token!==void 0?{token:c.token}:{},...c.name!==void 0?{name:c.name}:{},yes:c.yes,fromDesktop:c.fromDesktop,fromChrome:c.fromChrome,fromFirefox:c.fromFirefox,fromAll:c.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(c)=>c.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(c)=>Hd({...c.workspace!==void 0?{workspace:c.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(c)=>c.option("envfile",{type:"string",demandOption:!0,describe:"Destination env file (e.g. ./.env.local)"}).option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(c)=>zd({envfile:c.envfile,...c.workspace!==void 0?{workspace:c.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let c=Mi();if(c.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:d,profile:f,current:p}of c)console.log(`${p?"* ":" "}${d} ${f.team} (${f.user}) ${f.url??""}`)}).command("use <name>","Switch active workspace",(c)=>c.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(c)=>{if(!c.g)FD(gt(process.cwd(),".slack-cli"));ld(c.name,c.g),console.log(`Switched to workspace "${c.name}" ${c.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(c)=>c.positional("name",{type:"string",demandOption:!0}),(c)=>{cd(c.name),console.log(`Removed workspace "${c.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(c)=>c.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("profile",{type:"string",alias:"p",describe:"Chrome profile email or dir (Windows, when several have a session)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(c)=>{await Jd({...c.workspace!==void 0?{workspace:c.workspace}:{},...c.profile!==void 0?{profile:c.profile}:{},yes:c.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(c)=>c.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(c)=>{await ya({...c.workspace!==void 0?{workspace:c.workspace}:{},yes:c.yes})}).command("$0",!1,()=>{},()=>{a.showHelp(),process.exit(0)})).command("relay","Set up / check the real-time relay for `slack stream` (a Cloudflare Worker)",(a)=>a.command("init [dir]","Scaffold a deployable relay Worker folder (local files only; prints a fresh RELAY_TOKEN and the next steps)",(c)=>c.positional("dir",{type:"string",default:Fa,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"}),(c)=>{let d=Af(c.dir,{force:c.force,...c.name!==void 0?{name:c.name}:{},...c["slack-term"]!==void 0?{slackTerm:c["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(Tf(d))}).command("health","GET /health on the relay (SLACK_RELAY_URL / SLACK_RELAY_TOKEN); exit 0 = ok",(c)=>c.option("url",{type:"string",describe:"Relay URL (default: $SLACK_RELAY_URL)"}).option("token",{type:"string",describe:"Relay token (default: $SLACK_RELAY_TOKEN)"}),async(c)=>{let d=await Ff(c.url??process.env.SLACK_RELAY_URL,c.token??process.env.SLACK_RELAY_TOKEN);(d.code===0?console.log:console.error)(d.out),process.exit(d.code)}).demandCommand(1,"Specify a relay subcommand (init, health)")).command("stream","Print every new message matching --grep, across all channels the identity is in (threads included); resumable",(a)=>a.option("grep",{alias:"e",type:"string",demandOption:!0,describe:"Regex matched against each message's text (raw, e.g. <@U00000001>). Non-matching messages are never printed or logged"}).option("ignore-case",{alias:"i",type:"boolean",default:!1,describe:"Case-insensitive --grep"}).option("channel",{type:"array",string:!0,describe:"Only these channels (#name, id or permalink); repeatable"}).option("replies-to",{type:"array",string:!0,describe:"Also print replies in threads this id started or replied in (user U\u2026/bot B\u2026; `self` = the streaming identity), --grep or not; repeatable"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per match: type, channel{id,name}, ts, thread_ts, user{id,name}, text, permalink, match (grep | replies-to)"}).option("once",{type:"boolean",default:!1,describe:"Scan once from the saved cursor (or --since) and exit: 0 = matches printed, 2 = none, 3 = failure"}).option("since",{type:"string",describe:"Replay from this long ago (e.g. 30m, 2h), ignoring the saved cursor"}).option("interval",{type:"string",default:"45s",describe:"Poll interval (e.g. 30s, 2m)"}).option("thread-window",{type:"string",default:"3d",describe:"Watch replies in threads whose parent is at most this old"}).option("thread-scan",{type:"string",default:"3m",describe:"Polling: re-read each channel's whole --thread-window this often (cycles in between read only what is new)"}).option("calls-per-min",{type:"number",default:40,describe:"Polling: pace conversations.history/replies to this many calls per minute (0 = unpaced)"}).option("state",{type:"string",describe:"Cursor file (default: one per identity+grep+channels under $XDG_STATE_HOME/slack-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(a)=>{let c,d,f,p,g,h;try{c=new RegExp(a.grep,a["ignore-case"]?"i":""),f=en(a.interval)*1000,p=en(a["thread-window"]),g=en(a["thread-scan"]),h=a.since!==void 0?en(a.since):void 0,d=en(a.reconcile)*1000}catch(O){console.error(`slack stream: ${O instanceof Error?O.message:String(O)}`),process.exit(1)}let m=Le(),y=a["as-user"]===!0||!m,w=y?e(a):m,D=y?t(a):void 0;if(!m&&a["as-user"]!==!0)console.error("slack stream: no bot token (SLACK_BOT_TOKEN) \u2014 streaming as the USER identity, which includes its DMs.");let k;try{k=await Mt(w,D)}catch(O){console.error(`slack stream: fatal: ${O instanceof Error?O.message:String(O)}`),process.exit(3)}let _=new Set([k.userId].filter(Boolean)),E=new Set([k.botId].filter(Boolean));if(y&&m)try{let O=await Mt(m);if(O.userId)_.add(O.userId);if(O.botId)E.add(O.botId)}catch{}let S;if(a["replies-to"]?.length){S=new Set;for(let O of a["replies-to"].map(String)){if(O==="self"){for(let ee of[k.userId,k.botId])if(ee)S.add(ee);continue}if(!/^[UWB][A-Z0-9]{2,}$/.test(O))console.error(`slack stream: --replies-to: "${O}" is not a user or bot id (U\u2026/W\u2026/B\u2026) or "self"`),process.exit(1);if(S.add(O),O.startsWith("B"))try{let{userId:ee}=await Eh(w,O,D);if(ee)S.add(ee)}catch(ee){console.error(`slack stream: --replies-to ${O}: cannot resolve its bot user id (${ee instanceof Error?ee.message:String(ee)}); threads where it shows as a user id are missed`)}}}let x;if(a.channel?.length)try{x=[];for(let O of a.channel)x.push(await we(w,String(O),D))}catch(O){console.error(`slack stream: --channel: ${O instanceof Error?O.message:String(O)}`),process.exit(1)}let R=rm("sha256").update(JSON.stringify([k.url,k.userId,c.source,c.flags,[...x??[]].sort(),...a["replies-to"]?.length?[[...a["replies-to"].map(String)].sort()]:[]])).digest("hex").slice(0,16),L=process.env.XDG_STATE_HOME||gt(jo(),".local","state"),v=a.state??gt(L,"slack-term","stream",`${R}.json`);console.error(`slack stream: as ${y?"user":"bot"} @${k.user} (${k.userId}); state ${v}`);let P=process.env.SLACK_RELAY_URL,B=process.env.SLACK_RELAY_TOKEN,W=a.relay&&!y&&!a.once&&P&&B?{url:P,subscribe:Ca(P,B,void 0,{transport:$a(process.env.SLACK_RELAY_TRANSPORT)}),reconcileMs:d}:void 0;if(a.relay&&y&&P)console.error("slack stream: relay not used with --as-user (it only sees the bot's channels)");let N=!a.relay?"--no-relay":y?P?"--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",J=new AbortController;process.on("SIGINT",()=>J.abort()),process.on("SIGTERM",()=>J.abort()),$c(0);let H=await cf(of(w,D),{grep:c,...S?{repliesTo:S}:{},...x?{channels:x}:{},selfUsers:_,selfBots:E,json:a.json,reactions:a.reactions,...a.inbox?{onMatch:(O,ee)=>{try{let X=[w,D,process.env.SLACK_RELAY_TOKEN].filter((ce)=>!!ce),j=Mp({...O,...ee?{files:ee}:{}},void 0,new Date,X);if(j.length)console.error(`slack stream: delivered ${O.channel.id}:${O.ts} to ${j.length} inbox(es)`)}catch(X){console.error(`slack stream: inbox delivery failed: ${X instanceof Error?X.message:String(X)}`)}}}:{},once:a.once,...h!==void 0?{sinceSec:h}:{},intervalMs:f,threadWindowSec:p,threadScanSec:g,callsPerMin:a["calls-per-min"],...W?{}:{pollReason:N},statePath:v,teamUrl:k.url,identity:k.userId,signal:J.signal,...W?{relay:W}:{}});process.exit(H)}).command("tail [target]","Stream new messages in real time (like tail -f)",(a)=>a.positional("target",{type:"string",describe:"#channel or @user to follow"}).option("since",{type:"string",describe:"Backfill from N ago (e.g. 10m, 2h, 1d)"}).option("thread",{type:"string",describe:"Follow a single thread by timestamp"}).option("watch-thread",{type:"string",describe:"Watch the channel's top-level timeline AND one thread's replies together (ts or permalink)"}).option("me",{type:"boolean",default:!1,describe:"Filter to messages that mention you"}).option("interval",{type:"number",default:60000,describe:"Poll interval in ms (default 60s; use --interval=3000 for near-real-time)"}).option("timeout",{type:"string",describe:"Auto-stop after this long (e.g. 30m, 2h). Exit code 0 even if nothing arrived."}).option("exit-on-message",{type:"boolean",default:!1,describe:"Stop as soon as the first new message from someone else arrives (wait-for-reply)"}).option("rtm",{type:"boolean",default:!0,describe:"Use RTM WebSocket when available (xoxc + cookie); pass --no-rtm to force polling"}),async(a)=>{let c=e(a),d=t(a),f=new AbortController;process.on("SIGINT",()=>{f.abort(),process.exit(0)}),await Qd(c,a.target,{...a.since!==void 0?{since:a.since}:{},...a.thread!==void 0?{thread:a.thread}:{},...a["watch-thread"]!==void 0?{watchThread:a["watch-thread"]}:{},me:a.me,interval:a.interval,...a.timeout!==void 0?{timeout:a.timeout}:{},...a["exit-on-message"]===!0?{exitOnMessage:!0}:{},...d!==void 0?{cookie:d}:{},...a.rtm===!1?{noRtm:!0}:{}},f.signal)}).command("login",!1,(a)=>a.option("token",{type:"string"}).option("name",{type:"string"}).option("yes",{type:"boolean",default:!1}).option("from-desktop",{type:"boolean",default:!1}).option("from-chrome",{type:"boolean",default:!1}).option("from-firefox",{type:"boolean",default:!1}).option("from-all",{type:"boolean",default:!1}),async(a)=>{await Ns({...a.token!==void 0?{token:a.token}:{},...a.name!==void 0?{name:a.name}:{},yes:a.yes,fromDesktop:a.fromDesktop,fromChrome:a.fromChrome,fromFirefox:a.fromFirefox,fromAll:a.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}Xx().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
|