slack-term 1.47.0 → 1.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +86 -2
- package/SKILL.md +3 -2
- package/dist/cli.js +346 -242
- package/locales/en.json +32 -0
- package/locales/ja.json +31 -0
- package/package.json +15 -1
- package/ts/ask.ts +47 -46
- package/ts/botIntent.ts +1 -1
- package/ts/choiceHint.ts +30 -0
- package/ts/cli.ts +774 -126
- package/ts/inbox.ts +191 -0
- package/ts/locales.ts +113 -0
- package/ts/readback.ts +102 -0
- package/ts/redact.ts +225 -0
- package/ts/relayInit.ts +209 -0
- package/ts/scope.ts +472 -0
- package/ts/slack.ts +40 -2
- package/ts/stream.ts +4 -1
- package/ts/tick.ts +47 -0
- package/ts/vendor/gitleaks.LICENSE +21 -0
- package/ts/vendor/gitleaks.toml +3209 -0
- package/worker/README.md +216 -0
- package/worker/src/hub.ts +203 -0
- package/worker/src/index.ts +308 -0
- package/worker/src/slack.ts +127 -0
package/dist/cli.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{createRequire as Up}from"node:module";var Lp=Object.create;var{getPrototypeOf:Mp,defineProperty:Ha,getOwnPropertyNames:Np}=Object;var za=Object.prototype.hasOwnProperty;function Bp(e){return this[e]}var jp,Wp,Xa=(e,t,n)=>{var o=e!=null&&typeof e==="object";if(o){var s=t?jp??=new WeakMap:Wp??=new WeakMap,r=s.get(e);if(r)return r}n=e!=null?Lp(Mp(e)):{};let i=t||!e||!e.__esModule||!za.call(e,"default")?Ha(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Np(e))if(!za.call(i,a))Ha(i,a,{get:Bp.bind(e,a),enumerable:!0})}if(o)s.set(e,i);return i};var Ga=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Zn=Up(import.meta.url);var pc=Ga(function(Jb,fc){fc.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 Bc=Ga(function(RD,Nc){Nc.exports=function(t){if(t===void 0)t=2;if(t>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+t+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var n=Error.prepareStackTrace;Error.prepareStackTrace=function(s,r){return r};var o=Error().stack;if(Error.prepareStackTrace=n,o!==null&&typeof o==="object")return o[t]?o[t].getFileName():void 0}});import{createHash as up}from"crypto";import{existsSync as dp,readFileSync as fp,mkdirSync as Vy,realpathSync as Zy,writeFileSync as pp}from"fs";import{homedir as La}from"os";import{join as kt,resolve as Qy}from"path";import{notStrictEqual as Ch,strictEqual as Ah}from"assert";var Jp={right:Hp,center:zp};class Va{constructor(e){var t;this.width=e.width,this.wrap=(t=e.wrap)!==null&&t!==void 0?t:!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==="string")return this.applyLayoutDSL(e[0]);let t=e.map((n)=>{if(typeof n==="string")return this.colFromString(n);return n});return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==="string"&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
|
|
4
|
-
`).map((
|
|
5
|
-
`)}rowToString(e,t){return this.rasterize(e).forEach((n,
|
|
6
|
-
`);else o
|
|
7
|
-
`);if(s.border)o.unshift("."+"-".repeat(this.negatePadding(s)+2)+"."),o.push("'"+"-".repeat(this.negatePadding(s)+2)+"'");if(s.padding)o.unshift(...Array(s.padding[0]||0).fill("")),o.push(...Array(s.padding[2]||0).fill(""));o.forEach((i,a)=>{if(!t[a])t.push([]);let c=t[a];for(let l=0;l<r;l++)if(c[l]===void 0)c.push("");c.push(i)})}),t}negatePadding(e){let t=e.width||0;if(e.padding)t-=(e.padding[3]||0)+(e.padding[1]||0);if(e.border)t-=4;return t}columnWidths(e){if(!this.wrap)return e.map((r)=>r.width||Ye.stringWidth(r.text));let t=e.length,n=this.width,o=e.map((r)=>{if(r.width)return t--,n-=r.width,r.width;return}),s=t?Math.floor(n/t):0;return o.map((r,i)=>{if(r===void 0)return Math.max(s,Kp(e[i]));return r})}}function Ya(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function Kp(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function qp(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Hp(e,t){e=e.trim();let n=Ye.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function zp(e,t){e=e.trim();let n=Ye.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Ye;function Za(e,t){return Ye=t,new Va({width:(e===null||e===void 0?void 0:e.width)||qp(),wrap:e===null||e===void 0?void 0:e.wrap})}function wr({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 Xp=wr();function tn(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes(""))return e;return e.replace(Xp,"")}var Qa=161,ec=1114109,tc=[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],nc=12288,sc=65510,oc=[12288,12288,65281,65376,65504,65510];var rc=4352,ic=262141,br=[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 js=(e,t)=>{let n=0,o=Math.floor(e.length/2)-1;while(n<=o){let s=Math.floor((n+o)/2),r=s*2;if(t<e[r])o=s-1;else if(t>e[r+1])n=s+1;else return!0}return!1};var ac=19968,[Gp,Yp]=Vp(br);function Vp(e){let t=e[0],n=e[1];for(let o=0;o<e.length;o+=2){let s=e[o],r=e[o+1];if(ac>=s&&ac<=r)return[s,r];if(r-s>n-t)t=s,n=r}return[t,n]}var cc=(e)=>{if(e<Qa||e>ec)return!1;return js(tc,e)},lc=(e)=>{if(e<nc||e>sc)return!1;return js(oc,e)};var uc=(e)=>{if(e>=Gp&&e<=Yp)return!0;if(e<rc||e>ic)return!1;return js(br,e)};function Zp(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function dc(e,{ambiguousAsWide:t=!1}={}){if(Zp(e),lc(e)||uc(e)||t&&cc(e))return 2;return 1}var hc=Xa(pc(),1),Qp=new Intl.Segmenter,eh=/^\p{Default_Ignorable_Code_Point}$/u;function lt(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(!o)e=tn(e);if(e.length===0)return 0;let s=0,r={ambiguousAsWide:!n};for(let{segment:i}of Qp.segment(e)){let a=i.codePointAt(0);if(a<=31||a>=127&&a<=159)continue;if(a>=8203&&a<=8207||a===65279)continue;if(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)continue;if(a>=55296&&a<=57343)continue;if(a>=65024&&a<=65039)continue;if(eh.test(i))continue;if(hc.default().test(i)){s+=2;continue}s+=dc(a,r)}return s}var gc=(e=0)=>(t)=>`\x1B[${t+e}m`,mc=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,yc=(e=0)=>(t,n,o)=>`\x1B[${38+e};2;${t};${n};${o}m`,De={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]}},zb=Object.keys(De.modifier),th=Object.keys(De.color),nh=Object.keys(De.bgColor),Xb=[...th,...nh];function sh(){let e=new Map;for(let[t,n]of Object.entries(De)){for(let[o,s]of Object.entries(n))De[o]={open:`\x1B[${s[0]}m`,close:`\x1B[${s[1]}m`},n[o]=De[o],e.set(s[0],s[1]);Object.defineProperty(De,t,{value:n,enumerable:!1})}return Object.defineProperty(De,"codes",{value:e,enumerable:!1}),De.color.close="\x1B[39m",De.bgColor.close="\x1B[49m",De.color.ansi=gc(),De.color.ansi256=mc(),De.color.ansi16m=yc(),De.bgColor.ansi=gc(10),De.bgColor.ansi256=mc(10),De.bgColor.ansi16m=yc(10),Object.defineProperties(De,{rgbToAnsi256:{value(t,n,o){if(t===n&&n===o){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(o/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[o]=n;if(o.length===3)o=[...o].map((r)=>r+r).join("");let s=Number.parseInt(o,16);return[s>>16&255,s>>8&255,s&255]},enumerable:!1},hexToAnsi256:{value:(t)=>De.rgbToAnsi256(...De.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,o,s;if(t>=232)n=((t-232)*10+8)/255,o=n,s=n;else{t-=16;let a=t%36;n=Math.floor(t/36)/5,o=Math.floor(a/6)/5,s=a%6/5}let r=Math.max(n,o,s)*2;if(r===0)return 30;let i=30+(Math.round(s)<<2|Math.round(o)<<1|Math.round(n));if(r===2)i+=60;return i},enumerable:!1},rgbToAnsi:{value:(t,n,o)=>De.ansi256ToAnsi(De.rgbToAnsi256(t,n,o)),enumerable:!1},hexToAnsi:{value:(t)=>De.ansi256ToAnsi(De.hexToAnsi256(t)),enumerable:!1}}),De}var oh=sh(),wc=oh;var Us=new Set(["\x1B",""]),rh=39,kr="\x07",kc="[",ih="]",xc="m",Ws=`${ih}8;;`,bc=(e)=>`${Us.values().next().value}${kc}${e}${xc}`,Dc=(e)=>`${Us.values().next().value}${Ws}${e}${kr}`,ah=(e)=>e.split(" ").map((t)=>lt(t)),Dr=(e,t,n)=>{let o=[...t],s=!1,r=!1,i=lt(tn(e.at(-1)));for(let[a,c]of o.entries()){let l=lt(c);if(i+l<=n)e[e.length-1]+=c;else e.push(c),i=0;if(Us.has(c))s=!0,r=o.slice(a+1,a+1+Ws.length).join("")===Ws;if(s){if(r){if(c===kr)s=!1,r=!1}else if(c===xc)s=!1;continue}if(i+=l,i===n&&a<o.length-1)e.push(""),i=0}if(!i&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},ch=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(lt(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},lh=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let o="",s,r,i=ah(e),a=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)a[a.length-1]=a.at(-1).trimStart();let h=lt(a.at(-1));if(d!==0){if(h>=t&&(n.wordWrap===!1||n.trim===!1))a.push(""),h=0;if(h>0||n.trim===!1)a[a.length-1]+=" ",h++}if(n.hard&&i[d]>t){let g=t-h,p=1+Math.floor((i[d]-g-1)/t);if(Math.floor((i[d]-1)/t)<p)a.push("");Dr(a,f,t);continue}if(h+i[d]>t&&h>0&&i[d]>0){if(n.wordWrap===!1&&h<t){Dr(a,f,t);continue}a.push("")}if(h+i[d]>t&&n.wordWrap===!1){Dr(a,f,t);continue}a[a.length-1]+=f}if(n.trim!==!1)a=a.map((d)=>ch(d));let c=a.join(`
|
|
8
|
-
`),l=[...c],u=0;for(let[d,f]of l.entries()){if(
|
|
9
|
-
`){if(
|
|
10
|
-
`){if(
|
|
3
|
+
import{createRequire as Yg}from"node:module";var Jg=Object.create;var{getPrototypeOf:Ug,defineProperty:zc,getOwnPropertyNames:Kg}=Object;var Yc=Object.prototype.hasOwnProperty;function qg(e){return this[e]}var Hg,zg,Gc=(e,t,n)=>{var s=e!=null&&typeof e==="object";if(s){var o=t?Hg??=new WeakMap:zg??=new WeakMap,a=o.get(e);if(a)return a}n=e!=null?Jg(Ug(e)):{};let r=t||!e||!e.__esModule||!Yc.call(e,"default")?zc(n,"default",{value:e,enumerable:!0}):n;if(e&&typeof e==="object"||typeof e==="function"){for(let i of Kg(e))if(!Yc.call(r,i))zc(r,i,{get:qg.bind(e,i),enumerable:!0})}if(s)o.set(e,r);return r};var Xc=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var fs=Yg(import.meta.url);var hl=Xc(function(Dx,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 jl=Xc(function(cS,Bl){Bl.exports=function(t){if(t===void 0)t=2;if(t>=Error.stackTraceLimit)throw TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+t+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var n=Error.prepareStackTrace;Error.prepareStackTrace=function(o,a){return a};var s=Error().stack;if(Error.prepareStackTrace=n,s!==null&&typeof s==="object")return s[t]?s[t].getFileName():void 0}});import{createHash as yg}from"crypto";import{existsSync as bg,readFileSync as Wc,mkdirSync as O0,realpathSync as R0,writeFileSync as wg}from"fs";import{homedir as Lc}from"os";import{dirname as I0,join as Ft,resolve as v0}from"path";import{notStrictEqual as Im,strictEqual as vm}from"assert";var Gg={right:Zg,center:Qg};class Zc{constructor(e){var t;this.width=e.width,this.wrap=(t=e.wrap)!==null&&t!==void 0?t:!0,this.rows=[]}span(...e){let t=this.div(...e);t.span=!0}resetOutput(){this.rows=[]}div(...e){if(e.length===0)this.div("");if(this.wrap&&this.shouldApplyLayoutDSL(...e)&&typeof e[0]==="string")return this.applyLayoutDSL(e[0]);let t=e.map((n)=>{if(typeof n==="string")return this.colFromString(n);return n});return this.rows.push(t),t}shouldApplyLayoutDSL(...e){return e.length===1&&typeof e[0]==="string"&&/[\t\n]/.test(e[0])}applyLayoutDSL(e){let t=e.split(`
|
|
4
|
+
`).map((s)=>s.split("\t")),n=0;return t.forEach((s)=>{if(s.length>1&&Ze.stringWidth(s[0])>n)n=Math.min(Math.floor(this.width*0.5),Ze.stringWidth(s[0]))}),t.forEach((s)=>{this.div(...s.map((o,a)=>({text:o.trim(),padding:this.measurePadding(o),width:a===0&&s.length>1?n:void 0})))}),this.rows[this.rows.length-1]}colFromString(e){return{text:e,padding:this.measurePadding(e)}}measurePadding(e){let t=Ze.stripAnsi(e);return[0,t.match(/\s*$/)[0].length,0,t.match(/^\s*/)[0].length]}toString(){let e=[];return this.rows.forEach((t)=>{this.rowToString(t,e)}),e.filter((t)=>!t.hidden).map((t)=>t.text).join(`
|
|
5
|
+
`)}rowToString(e,t){return this.rasterize(e).forEach((n,s)=>{let o="";n.forEach((a,r)=>{let{width:i}=e[r],c=this.negatePadding(e[r]),l=a;if(c>Ze.stringWidth(a))l+=" ".repeat(c-Ze.stringWidth(a));if(e[r].align&&e[r].align!=="left"&&this.wrap){let d=Gg[e[r].align];if(l=d(l,c),Ze.stringWidth(l)<c)l+=" ".repeat((i||0)-Ze.stringWidth(l)-1)}let u=e[r].padding||[0,0,0,0];if(u[3])o+=" ".repeat(u[3]);if(o+=Vc(e[r],l,"| "),o+=l,o+=Vc(e[r],l," |"),u[1])o+=" ".repeat(u[1]);if(s===0&&t.length>0)o=this.renderInline(o,t[t.length-1])}),t.push({text:o.replace(/ +$/,""),span:e.span})}),t}renderInline(e,t){let n=e.match(/^ */),s=n?n[0].length:0,o=t.text,a=Ze.stringWidth(o.trimRight());if(!t.span)return e;if(!this.wrap)return t.hidden=!0,o+e;if(s<a)return e;return t.hidden=!0,o.trimRight()+" ".repeat(s-a)+e.trimLeft()}rasterize(e){let t=[],n=this.columnWidths(e),s;return e.forEach((o,a)=>{if(o.width=n[a],this.wrap)s=Ze.wrap(o.text,this.negatePadding(o),{hard:!0}).split(`
|
|
6
|
+
`);else s=o.text.split(`
|
|
7
|
+
`);if(o.border)s.unshift("."+"-".repeat(this.negatePadding(o)+2)+"."),s.push("'"+"-".repeat(this.negatePadding(o)+2)+"'");if(o.padding)s.unshift(...Array(o.padding[0]||0).fill("")),s.push(...Array(o.padding[2]||0).fill(""));s.forEach((r,i)=>{if(!t[i])t.push([]);let c=t[i];for(let l=0;l<a;l++)if(c[l]===void 0)c.push("");c.push(r)})}),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((a)=>a.width||Ze.stringWidth(a.text));let t=e.length,n=this.width,s=e.map((a)=>{if(a.width)return t--,n-=a.width,a.width;return}),o=t?Math.floor(n/t):0;return s.map((a,r)=>{if(a===void 0)return Math.max(o,Xg(e[r]));return a})}}function Vc(e,t,n){if(e.border){if(/[.']-+[.']/.test(t))return"";if(t.trim().length!==0)return n;return" "}return""}function Xg(e){let t=e.padding||[],n=1+(t[3]||0)+(t[1]||0);if(e.border)return n+4;return n}function Vg(){if(typeof process==="object"&&process.stdout&&process.stdout.columns)return process.stdout.columns;return 80}function Zg(e,t){e=e.trim();let n=Ze.stringWidth(e);if(n<t)return" ".repeat(t-n)+e;return e}function Qg(e,t){e=e.trim();let n=Ze.stringWidth(e);if(n>=t)return e;return" ".repeat(t-n>>1)+e}var Ze;function Qc(e,t){return Ze=t,new Zc({width:(e===null||e===void 0?void 0:e.width)||Vg(),wrap:e===null||e===void 0?void 0:e.wrap})}function Ho({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 em=Ho();function dn(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);if(!e.includes("\x1B")&&!e.includes(""))return e;return e.replace(em,"")}var el=161,tl=1114109,nl=[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],sl=12288,rl=65510,ol=[12288,12288,65281,65376,65504,65510];var il=4352,al=262141,zo=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141];var sr=(e,t)=>{let n=0,s=Math.floor(e.length/2)-1;while(n<=s){let o=Math.floor((n+s)/2),a=o*2;if(t<e[a])s=o-1;else if(t>e[a+1])n=o+1;else return!0}return!1};var cl=19968,[tm,nm]=sm(zo);function sm(e){let t=e[0],n=e[1];for(let s=0;s<e.length;s+=2){let o=e[s],a=e[s+1];if(cl>=o&&cl<=a)return[o,a];if(a-o>n-t)t=o,n=a}return[t,n]}var ll=(e)=>{if(e<el||e>tl)return!1;return sr(nl,e)},ul=(e)=>{if(e<sl||e>rl)return!1;return sr(ol,e)};var dl=(e)=>{if(e>=tm&&e<=nm)return!0;if(e<il||e>al)return!1;return sr(zo,e)};function rm(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function fl(e,{ambiguousAsWide:t=!1}={}){if(rm(e),ul(e)||dl(e)||t&&ll(e))return 2;return 1}var gl=Gc(hl(),1),om=new Intl.Segmenter,im=/^\p{Default_Ignorable_Code_Point}$/u;function ht(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:s=!1}=t;if(!s)e=dn(e);if(e.length===0)return 0;let o=0,a={ambiguousAsWide:!n};for(let{segment:r}of om.segment(e)){let i=r.codePointAt(0);if(i<=31||i>=127&&i<=159)continue;if(i>=8203&&i<=8207||i===65279)continue;if(i>=768&&i<=879||i>=6832&&i<=6911||i>=7616&&i<=7679||i>=8400&&i<=8447||i>=65056&&i<=65071)continue;if(i>=55296&&i<=57343)continue;if(i>=65024&&i<=65039)continue;if(im.test(r))continue;if(gl.default().test(r)){o+=2;continue}o+=fl(i,a)}return o}var ml=(e=0)=>(t)=>`\x1B[${t+e}m`,yl=(e=0)=>(t)=>`\x1B[${38+e};5;${t}m`,bl=(e=0)=>(t,n,s)=>`\x1B[${38+e};2;${t};${n};${s}m`,xe={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}},_x=Object.keys(xe.modifier),am=Object.keys(xe.color),cm=Object.keys(xe.bgColor),Ex=[...am,...cm];function lm(){let e=new Map;for(let[t,n]of Object.entries(xe)){for(let[s,o]of Object.entries(n))xe[s]={open:`\x1B[${o[0]}m`,close:`\x1B[${o[1]}m`},n[s]=xe[s],e.set(o[0],o[1]);Object.defineProperty(xe,t,{value:n,enumerable:!1})}return Object.defineProperty(xe,"codes",{value:e,enumerable:!1}),xe.color.close="\x1B[39m",xe.bgColor.close="\x1B[49m",xe.color.ansi=ml(),xe.color.ansi256=yl(),xe.color.ansi16m=bl(),xe.bgColor.ansi=ml(10),xe.bgColor.ansi256=yl(10),xe.bgColor.ansi16m=bl(10),Object.defineProperties(xe,{rgbToAnsi256:{value(t,n,s){if(t===n&&n===s){if(t<8)return 16;if(t>248)return 231;return Math.round((t-8)/247*24)+232}return 16+36*Math.round(t/255*5)+6*Math.round(n/255*5)+Math.round(s/255*5)},enumerable:!1},hexToRgb:{value(t){let n=/[a-f\d]{6}|[a-f\d]{3}/i.exec(t.toString(16));if(!n)return[0,0,0];let[s]=n;if(s.length===3)s=[...s].map((a)=>a+a).join("");let o=Number.parseInt(s,16);return[o>>16&255,o>>8&255,o&255]},enumerable:!1},hexToAnsi256:{value:(t)=>xe.rgbToAnsi256(...xe.hexToRgb(t)),enumerable:!1},ansi256ToAnsi:{value(t){if(t<8)return 30+t;if(t<16)return 90+(t-8);let n,s,o;if(t>=232)n=((t-232)*10+8)/255,s=n,o=n;else{t-=16;let i=t%36;n=Math.floor(t/36)/5,s=Math.floor(i/6)/5,o=i%6/5}let a=Math.max(n,s,o)*2;if(a===0)return 30;let r=30+(Math.round(o)<<2|Math.round(s)<<1|Math.round(n));if(a===2)r+=60;return r},enumerable:!1},rgbToAnsi:{value:(t,n,s)=>xe.ansi256ToAnsi(xe.rgbToAnsi256(t,n,s)),enumerable:!1},hexToAnsi:{value:(t)=>xe.ansi256ToAnsi(xe.hexToAnsi256(t)),enumerable:!1}}),xe}var um=lm(),wl=um;var or=new Set(["\x1B",""]),dm=39,Go="\x07",xl="[",fm="]",Sl="m",rr=`${fm}8;;`,Dl=(e)=>`${or.values().next().value}${xl}${e}${Sl}`,kl=(e)=>`${or.values().next().value}${rr}${e}${Go}`,pm=(e)=>e.split(" ").map((t)=>ht(t)),Yo=(e,t,n)=>{let s=[...t],o=!1,a=!1,r=ht(dn(e.at(-1)));for(let[i,c]of s.entries()){let l=ht(c);if(r+l<=n)e[e.length-1]+=c;else e.push(c),r=0;if(or.has(c))o=!0,a=s.slice(i+1,i+1+rr.length).join("")===rr;if(o){if(a){if(c===Go)o=!1,a=!1}else if(c===Sl)o=!1;continue}if(r+=l,r===n&&i<s.length-1)e.push(""),r=0}if(!r&&e.at(-1).length>0&&e.length>1)e[e.length-2]+=e.pop()},hm=(e)=>{let t=e.split(" "),n=t.length;while(n>0){if(ht(t[n-1])>0)break;n--}if(n===t.length)return e;return t.slice(0,n).join(" ")+t.slice(n).join("")},gm=(e,t,n={})=>{if(n.trim!==!1&&e.trim()==="")return"";let s="",o,a,r=pm(e),i=[""];for(let[d,f]of e.split(" ").entries()){if(n.trim!==!1)i[i.length-1]=i.at(-1).trimStart();let p=ht(i.at(-1));if(d!==0){if(p>=t&&(n.wordWrap===!1||n.trim===!1))i.push(""),p=0;if(p>0||n.trim===!1)i[i.length-1]+=" ",p++}if(n.hard&&r[d]>t){let g=t-p,h=1+Math.floor((r[d]-g-1)/t);if(Math.floor((r[d]-1)/t)<h)i.push("");Yo(i,f,t);continue}if(p+r[d]>t&&p>0&&r[d]>0){if(n.wordWrap===!1&&p<t){Yo(i,f,t);continue}i.push("")}if(p+r[d]>t&&n.wordWrap===!1){Yo(i,f,t);continue}i[i.length-1]+=f}if(n.trim!==!1)i=i.map((d)=>hm(d));let c=i.join(`
|
|
8
|
+
`),l=[...c],u=0;for(let[d,f]of l.entries()){if(s+=f,or.has(f)){let{groups:g}=new RegExp(`(?:\\${xl}(?<code>\\d+)m|\\${rr}(?<uri>.*)${Go})`).exec(c.slice(u))||{groups:{}};if(g.code!==void 0){let h=Number.parseFloat(g.code);o=h===dm?void 0:h}else if(g.uri!==void 0)a=g.uri.length===0?void 0:g.uri}let p=wl.codes.get(Number(o));if(l[d+1]===`
|
|
9
|
+
`){if(a)s+=kl("");if(o&&p)s+=Dl(p)}else if(f===`
|
|
10
|
+
`){if(o&&p)s+=Dl(o);if(a)s+=kl(a)}u+=f.length}return s};function Xo(e,t,n){return String(e).normalize().replaceAll(`\r
|
|
11
11
|
`,`
|
|
12
12
|
`).split(`
|
|
13
|
-
`).map((
|
|
14
|
-
`)}function Sr(e){return Za(e,{stringWidth:lt,stripAnsi:tn,wrap:xr})}import{dirname as Sc,resolve as Ec}from"path";import{readdirSync as uh,statSync as dh}from"fs";function Er(e,t){let n=Ec(".",e),o;if(!dh(n).isDirectory())n=Sc(n);while(!0){if(o=t(n,uh(n)),o)return Ec(n,o);if(n=Sc(o=n),o===n)break}}import{inspect as Fh}from"util";import{fileURLToPath as Wc}from"url";import{format as hh}from"util";import{normalize as gh,resolve as mh}from"path";function nn(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",o=!1,s=e.match(/^-+/);for(let r=s?s[0].length:0;r<e.length;r++){let i=e.charAt(r);if(o)o=!1,i=i.toUpperCase();if(r!==0&&(i==="-"||i==="_"))o=!0;else if(i!=="-"&&i!=="_")n+=i}return n}}function Js(e,t){let n=e.toLowerCase();t=t||"-";let o="";for(let s=0;s<e.length;s++){let r=n.charAt(s),i=e.charAt(s);if(r!==i&&s>0)o+=`${t}${n.charAt(s)}`;else o+=i}return o}function Ks(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 _c(e){if(Array.isArray(e))return e.map((i)=>typeof i!=="string"?i+"":i);e=e.trim();let t=0,n=null,o=null,s=null,r=[];for(let i=0;i<e.length;i++){if(n=o,o=e.charAt(i),o===" "&&!s){if(n!==" ")t++;continue}if(o===s)s=null;else if((o==="'"||o==='"')&&!s)s=o;if(!r[t])r[t]="";r[t]+=o}return r}var nt;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(nt||(nt={}));var xt;class $r{constructor(e){xt=e}parse(e,t){let n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),o=_c(e),s=typeof e==="string",r=fh(Object.assign(Object.create(null),n.alias)),i=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),a=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,u=i["populate--"],d=u?"--":"_",f=Object.create(null),h=Object.create(null),g=n.__||xt.format,p={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},m=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,w=new RegExp("^--"+i["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(k){let C=typeof k==="object"?k.key:k,B=Object.keys(k).map(function(R){return{boolean:"bools",string:"strings",number:"numbers"}[R]}).filter(Boolean).pop();if(B)p[B][C]=!0;p.arrays[C]=!0,p.keys.push(C)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(k){p.bools[k]=!0,p.keys.push(k)}),[].concat(n.string||[]).filter(Boolean).forEach(function(k){p.strings[k]=!0,p.keys.push(k)}),[].concat(n.number||[]).filter(Boolean).forEach(function(k){p.numbers[k]=!0,p.keys.push(k)}),[].concat(n.count||[]).filter(Boolean).forEach(function(k){p.counts[k]=!0,p.keys.push(k)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(k){p.normalize[k]=!0,p.keys.push(k)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([k,C])=>{if(typeof C==="number")p.nargs[k]=C,p.keys.push(k)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([k,C])=>{if(typeof C==="function")p.coercions[k]=C,p.keys.push(k)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(k){p.configs[k]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([k,C])=>{if(typeof C==="boolean"||typeof C==="function")p.configs[k]=C})}re(n.key,r,n.default,p.arrays),Object.keys(a).forEach(function(k){(p.aliases[k]||[]).forEach(function(C){a[C]=a[k]})});let b=null;yr();let D=[],S=Object.assign(Object.create(null),{_:[]}),A={};for(let k=0;k<o.length;k++){let C=o[k],B=C.replace(/^-{3,}/,"---"),R,_,Z,X,ne,Oe;if(C!=="--"&&/^-/.test(C)&&oe(C))F(C);else if(B.match(/^---+(=|$)/)){F(C);continue}else if(C.match(/^--.+=/)||!i["short-option-groups"]&&C.match(/^-.+=/)){if(X=C.match(/^--?([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)if(j(X[1],p.arrays))k=x(k,X[1],o,X[2]);else if(j(X[1],p.nargs)!==!1)k=E(k,X[1],o,X[2]);else W(X[1],X[2],!0)}else if(C.match(w)&&i["boolean-negation"]){if(X=C.match(w),X!==null&&Array.isArray(X)&&X.length>=2)_=X[1],W(_,j(_,p.arrays)?[!1]:!1)}else if(C.match(/^--.+/)||!i["short-option-groups"]&&C.match(/^-[^-]+/)){if(X=C.match(/^--?(.+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(_=X[1],j(_,p.arrays))k=x(k,_,o);else if(j(_,p.nargs)!==!1)k=E(k,_,o);else if(ne=o[k+1],ne!==void 0&&(!ne.match(/^-/)||ne.match(m))&&!j(_,p.bools)&&!j(_,p.counts))W(_,ne),k++;else if(/^(true|false)$/.test(ne))W(_,ne),k++;else W(_,L(_))}else if(C.match(/^-.\..+=/)){if(X=C.match(/^-([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)W(X[1],X[2])}else if(C.match(/^-.\..+/)&&!C.match(m)){if(ne=o[k+1],X=C.match(/^-(.\..+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(_=X[1],ne!==void 0&&!ne.match(/^-/)&&!j(_,p.bools)&&!j(_,p.counts))W(_,ne),k++;else W(_,L(_))}else if(C.match(/^-[^-]+/)&&!C.match(m)){Z=C.slice(1,-1).split(""),R=!1;for(let We=0;We<Z.length;We++){if(ne=C.slice(We+2),Z[We+1]&&Z[We+1]==="="){if(Oe=C.slice(We+3),_=Z[We],j(_,p.arrays))k=x(k,_,o,Oe);else if(j(_,p.nargs)!==!1)k=E(k,_,o,Oe);else W(_,Oe);R=!0;break}if(ne==="-"){W(Z[We],ne);continue}if(/[A-Za-z]/.test(Z[We])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(ne)&&j(ne,p.bools)===!1){W(Z[We],ne),R=!0;break}if(Z[We+1]&&Z[We+1].match(/\W/)){W(Z[We],ne),R=!0;break}else W(Z[We],L(Z[We]))}if(_=C.slice(-1)[0],!R&&_!=="-")if(j(_,p.arrays))k=x(k,_,o);else if(j(_,p.nargs)!==!1)k=E(k,_,o);else if(ne=o[k+1],ne!==void 0&&(!/^(-|--)[^-]/.test(ne)||ne.match(m))&&!j(_,p.bools)&&!j(_,p.counts))W(_,ne),k++;else if(/^(true|false)$/.test(ne))W(_,ne),k++;else W(_,L(_))}else if(C.match(/^-[0-9]$/)&&C.match(m)&&j(C.slice(1),p.bools))_=C.slice(1),W(_,L(_));else if(C==="--"){D=o.slice(k+1);break}else if(i["halt-at-non-option"]){D=o.slice(k);break}else F(C)}if(q(S,!0),q(S,!1),I(S),N(),le(S,p.aliases,a,!0),H(S),i["set-placeholder-key"])v(S);if(Object.keys(p.counts).forEach(function(k){if(!te(S,k.split(".")))W(k,0)}),u&&D.length)S[d]=[];if(D.forEach(function(k){S[d].push(k)}),i["camel-case-expansion"]&&i["strip-dashed"])Object.keys(S).filter((k)=>k!=="--"&&k.includes("-")).forEach((k)=>{delete S[k]});if(i["strip-aliased"])[].concat(...Object.keys(r).map((k)=>r[k])).forEach((k)=>{if(i["camel-case-expansion"]&&k.includes("-"))delete S[k.split(".").map((C)=>nn(C)).join(".")];delete S[k]});function F(k){let C=P("_",k);if(typeof C==="string"||typeof C==="number")S._.push(C)}function E(k,C,B,R){let _,Z=j(C,p.nargs);if(Z=typeof Z!=="number"||isNaN(Z)?1:Z,Z===0){if(!Ae(R))b=Error(g("Argument unexpected for: %s",C));return W(C,L(C)),k}let X=Ae(R)?0:1;if(i["nargs-eats-options"]){if(B.length-(k+1)+X<Z)b=Error(g("Not enough arguments following: %s",C));X=Z}else{for(_=k+1;_<B.length;_++)if(!B[_].match(/^-[^0-9]/)||B[_].match(m)||oe(B[_]))X++;else break;if(X<Z)b=Error(g("Not enough arguments following: %s",C))}let ne=Math.min(X,Z);if(!Ae(R)&&ne>0)W(C,R),ne--;for(_=k+1;_<ne+k+1;_++)W(C,B[_]);return k+ne}function x(k,C,B,R){let _=[],Z=R||B[k+1],X=j(C,p.nargs);if(j(C,p.bools)&&!/^(true|false)$/.test(Z))_.push(!0);else if(Ae(Z)||Ae(R)&&/^-/.test(Z)&&!m.test(Z)&&!oe(Z)){if(a[C]!==void 0){let ne=a[C];_=Array.isArray(ne)?ne:[ne]}}else{if(!Ae(R))_.push(M(C,R,!0));for(let ne=k+1;ne<B.length;ne++){if(!i["greedy-arrays"]&&_.length>0||X&&typeof X==="number"&&_.length>=X)break;if(Z=B[ne],/^-/.test(Z)&&!m.test(Z)&&!oe(Z))break;k=ne,_.push(M(C,Z,s))}}if(typeof X==="number"&&(X&&_.length<X||isNaN(X)&&_.length===0))b=Error(g("Not enough arguments following: %s",C));return W(C,_),k}function W(k,C,B=s){if(/-/.test(k)&&i["camel-case-expansion"]){let Z=k.split(".").map(function(X){return nn(X)}).join(".");Q(k,Z)}let R=M(k,C,B),_=k.split(".");if(K(S,_,R),p.aliases[k])p.aliases[k].forEach(function(Z){let X=Z.split(".");K(S,X,R)});if(_.length>1&&i["dot-notation"])(p.aliases[_[0]]||[]).forEach(function(Z){let X=Z.split("."),ne=[].concat(_);if(ne.shift(),X=X.concat(ne),!(p.aliases[k]||[]).includes(X.join(".")))K(S,X,R)});if(j(k,p.normalize)&&!j(k,p.arrays))[k].concat(p.aliases[k]||[]).forEach(function(X){Object.defineProperty(A,X,{enumerable:!0,get(){return C},set(ne){C=typeof ne==="string"?xt.normalize(ne):ne}})})}function Q(k,C){if(!(p.aliases[k]&&p.aliases[k].length))p.aliases[k]=[C],f[C]=!0;if(!(p.aliases[C]&&p.aliases[C].length))Q(C,k)}function M(k,C,B){if(B)C=ph(C);if(j(k,p.bools)||j(k,p.counts)){if(typeof C==="string")C=C==="true"}let R=Array.isArray(C)?C.map(function(_){return P(k,_)}):P(k,C);if(j(k,p.counts)&&(Ae(R)||typeof R==="boolean"))R=_r();if(j(k,p.normalize)&&j(k,p.arrays))if(Array.isArray(C))R=C.map((_)=>xt.normalize(_));else R=xt.normalize(C);return R}function P(k,C){if(!i["parse-positional-numbers"]&&k==="_")return C;if(!j(k,p.strings)&&!j(k,p.bools)&&!Array.isArray(C)){if(Ks(C)&&i["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${C}`)))||!Ae(C)&&j(k,p.numbers))C=Number(C)}return C}function I(k){let C=Object.create(null);le(C,p.aliases,a),Object.keys(p.configs).forEach(function(B){let R=k[B]||C[B];if(R)try{let _=null,Z=xt.resolve(xt.cwd(),R),X=p.configs[B];if(typeof X==="function"){try{_=X(Z)}catch(ne){_=ne}if(_ instanceof Error){b=_;return}}else _=xt.require(Z);U(_)}catch(_){if(_.name==="PermissionDenied")b=_;else if(k[B])b=Error(g("Invalid JSON config file: %s",R))}})}function U(k,C){Object.keys(k).forEach(function(B){let R=k[B],_=C?C+"."+B:B;if(typeof R==="object"&&R!==null&&!Array.isArray(R)&&i["dot-notation"])U(R,_);else if(!te(S,_.split("."))||j(_,p.arrays)&&i["combine-arrays"])W(_,R)})}function N(){if(typeof c<"u")c.forEach(function(k){U(k)})}function q(k,C){if(typeof l>"u")return;let B=typeof l==="string"?l:"",R=xt.env();Object.keys(R).forEach(function(_){if(B===""||_.lastIndexOf(B,0)===0){let Z=_.split("__").map(function(X,ne){if(ne===0)X=X.substring(B.length);return nn(X)});if((C&&p.configs[Z.join(".")]||!C)&&!te(k,Z))W(Z.join("."),R[_])}})}function H(k){let C,B=new Set;Object.keys(k).forEach(function(R){if(!B.has(R)){if(C=j(R,p.coercions),typeof C==="function")try{let _=P(R,C(k[R]));[].concat(p.aliases[R]||[],R).forEach((Z)=>{B.add(Z),k[Z]=_})}catch(_){b=_}}})}function v(k){return p.keys.forEach((C)=>{if(~C.indexOf("."))return;if(typeof k[C]>"u")k[C]=void 0}),k}function le(k,C,B,R=!1){Object.keys(B).forEach(function(_){if(!te(k,_.split("."))){if(K(k,_.split("."),B[_]),R)h[_]=!0;(C[_]||[]).forEach(function(Z){if(te(k,Z.split(".")))return;K(k,Z.split("."),B[_])})}})}function te(k,C){let B=k;if(!i["dot-notation"])C=[C.join(".")];C.slice(0,-1).forEach(function(_){B=B[_]||{}});let R=C[C.length-1];if(typeof B!=="object")return!1;else return R in B}function K(k,C,B){let R=k;if(!i["dot-notation"])C=[C.join(".")];C.slice(0,-1).forEach(function(Oe){if(Oe=$c(Oe),typeof R==="object"&&R[Oe]===void 0)R[Oe]={};if(typeof R[Oe]!=="object"||Array.isArray(R[Oe])){if(Array.isArray(R[Oe]))R[Oe].push({});else R[Oe]=[R[Oe],{}];R=R[Oe][R[Oe].length-1]}else R=R[Oe]});let _=$c(C[C.length-1]),Z=j(C.join("."),p.arrays),X=Array.isArray(B),ne=i["duplicate-arguments-array"];if(!ne&&j(_,p.nargs)){if(ne=!0,!Ae(R[_])&&p.nargs[_]===1||Array.isArray(R[_])&&R[_].length===p.nargs[_])R[_]=void 0}if(B===_r())R[_]=_r(R[_]);else if(Array.isArray(R[_]))if(ne&&Z&&X)R[_]=i["flatten-duplicate-arrays"]?R[_].concat(B):(Array.isArray(R[_][0])?R[_]:[R[_]]).concat([B]);else if(!ne&&Boolean(Z)===Boolean(X))R[_]=B;else R[_]=R[_].concat([B]);else if(R[_]===void 0&&Z)R[_]=X?B:[B];else if(ne&&!(R[_]===void 0||j(_,p.counts)||j(_,p.bools)))R[_]=[R[_],B];else R[_]=B}function re(...k){k.forEach(function(C){Object.keys(C||{}).forEach(function(B){if(p.aliases[B])return;p.aliases[B]=[].concat(r[B]||[]),p.aliases[B].concat(B).forEach(function(R){if(/-/.test(R)&&i["camel-case-expansion"]){let _=nn(R);if(_!==B&&p.aliases[B].indexOf(_)===-1)p.aliases[B].push(_),f[_]=!0}}),p.aliases[B].concat(B).forEach(function(R){if(R.length>1&&/[A-Z]/.test(R)&&i["camel-case-expansion"]){let _=Js(R,"-");if(_!==B&&p.aliases[B].indexOf(_)===-1)p.aliases[B].push(_),f[_]=!0}}),p.aliases[B].forEach(function(R){p.aliases[R]=[B].concat(p.aliases[B].filter(function(_){return R!==_}))})})})}function j(k,C){let B=[].concat(p.aliases[k]||[],k),R=Object.keys(C),_=B.find((Z)=>R.includes(Z));return _?C[_]:!1}function de(k){let C=Object.keys(p);return[].concat(C.map((R)=>p[R])).some(function(R){return Array.isArray(R)?R.includes(k):R[k]})}function se(k,...C){return[].concat(...C).some(function(R){let _=k.match(R);return _&&de(_[1])})}function J(k){if(k.match(m)||!k.match(/^-[^-]+/))return!1;let C=!0,B,R=k.slice(1).split("");for(let _=0;_<R.length;_++){if(B=k.slice(_+2),!de(R[_])){C=!1;break}if(R[_+1]&&R[_+1]==="="||B==="-"||/[A-Za-z]/.test(R[_])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(B)||R[_+1]&&R[_+1].match(/\W/))break}return C}function oe(k){return i["unknown-options-as-args"]&&z(k)}function z(k){if(k=k.replace(/^-{3,}/,"--"),k.match(m))return!1;if(J(k))return!1;return!se(k,/^-+([^=]+?)=[\s\S]*$/,w,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function L(k){if(!j(k,p.bools)&&!j(k,p.counts)&&`${k}`in a)return a[k];else return pe(we(k))}function pe(k){return{[nt.BOOLEAN]:!0,[nt.STRING]:"",[nt.NUMBER]:void 0,[nt.ARRAY]:[]}[k]}function we(k){let C=nt.BOOLEAN;if(j(k,p.strings))C=nt.STRING;else if(j(k,p.numbers))C=nt.NUMBER;else if(j(k,p.bools))C=nt.BOOLEAN;else if(j(k,p.arrays))C=nt.ARRAY;return C}function Ae(k){return k===void 0}function yr(){Object.keys(p.counts).find((k)=>{if(j(k,p.arrays))return b=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",k)),!0;else if(j(k,p.nargs))return b=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",k)),!0;return!1})}return{aliases:Object.assign({},p.aliases),argv:Object.assign(A,S),configuration:i,defaulted:Object.assign({},h),error:b,newAliases:Object.assign({},f)}}}function fh(e){let t=[],n=Object.create(null),o=!0;Object.keys(e).forEach(function(s){t.push([].concat(e[s],s))});while(o){o=!1;for(let s=0;s<t.length;s++)for(let r=s+1;r<t.length;r++)if(t[s].filter(function(a){return t[r].indexOf(a)!==-1}).length){t[s]=t[s].concat(t[r]),t.splice(r,1),o=!0;break}}return t.forEach(function(s){s=s.filter(function(i,a,c){return c.indexOf(i)===a});let r=s.pop();if(r!==void 0&&typeof r==="string")n[r]=s}),n}function _r(e){return e!==void 0?e+1:1}function $c(e){if(e==="__proto__")return"___proto___";return e}function ph(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 yh}from"fs";import{createRequire as Cc}from"node:module";var Cr,Ar,Fr,Ac=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Fc=(Ar=(Cr=process===null||process===void 0?void 0:process.versions)===null||Cr===void 0?void 0:Cr.node)!==null&&Ar!==void 0?Ar:(Fr=process===null||process===void 0?void 0:process.version)===null||Fr===void 0?void 0:Fr.slice(1);if(Fc){if(Number(Fc.match(/^([^.]+)/)[1])<Ac)throw Error(`yargs parser supports a minimum Node.js version of ${Ac}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var wh=process?process.env:{},Tc=Cc?Cc(import.meta.url):void 0,Rc=new $r({cwd:process.cwd,env:()=>wh,format:hh,normalize:gh,resolve:mh,require:(e)=>{if(typeof Tc<"u")return Tc(e);else if(e.match(/\.json$/))return JSON.parse(yh(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),Qn=function(t,n){return Rc.parse(t.slice(),n).argv};Qn.detailed=function(e,t){return Rc.parse(e.slice(),t)};Qn.camelCase=nn;Qn.decamelize=Js;Qn.looksLikeNumber=Ks;var Tr=Qn;import{basename as Th,dirname as Rh,extname as Ih,relative as Oh,resolve as jc,join as Ph}from"path";function Ic(){if(bh())return 0;return 1}function bh(){return Dh()&&!process.defaultApp}function Dh(){return!!process.versions.electron}function Rr(e){return e.slice(Ic()+1)}function Oc(){return process.argv[Ic()]}import{readFileSync as kh,statSync as xh,writeFile as Sh}from"fs";import{format as Eh}from"util";import{resolve as _h}from"path";var Pc={fs:{readFileSync:kh,writeFile:Sh},format:Eh,resolve:_h,exists:(e)=>{try{return xh(e).isFile()}catch(t){return!1}}};var ut;class vc{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 ut.format.apply(ut.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),o=e.shift(),s=function(){};if(typeof e[e.length-1]==="function")s=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let r=o===1?t:n;if(this.cache[this.locale][t])r=this.cache[this.locale][t][o===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:s});else s();let i=[r];if(~r.indexOf("%d"))i.push(o);return ut.format.apply(ut.format,i.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(o,s){let r=t[s+1];if(n+=o,typeof r<"u")n+="%s"}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){if(this.writeQueue.push(e),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],{directory:n,locale:o,cb:s}=t,r=this._resolveLocaleFile(n,o),i=JSON.stringify(this.cache[o],null,2);ut.fs.writeFile(r,i,"utf-8",function(a){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();s(a)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(ut.fs.readFileSync)e=JSON.parse(ut.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=ut.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let o=ut.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(o))n=o}return n}_fileExistsSync(e){return ut.exists(e)}}function Lc(e,t){ut=t;let n=new vc(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 $h=(e)=>Lc(e,Pc),Mc=$h;var Uc=Xa(Bc(),1);import{createRequire as vh}from"node:module";import{readFileSync as Lh,readdirSync as Mh}from"node:fs";var Ir=Wc(import.meta.url),Nh=Ir.substring(0,Ir.lastIndexOf("node_modules")),Bh=vh(import.meta.url),Or={assert:{notStrictEqual:Ch,strictEqual:Ah},cliui:Sr,findUp:Er,getEnv:(e)=>process.env[e],inspect:Fh,getProcessArgvBin:Oc,mainFilename:Nh||process.cwd(),Parser:Tr,path:{basename:Th,dirname:Rh,extname:Ih,relative:Oh,resolve:jc,join:Ph},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:Lh,readdirSync:Mh,require:Bh,getCallerFile:()=>{let e=Uc.default(3);return e.match(/^file:\/\//)?Wc(e):e},stringWidth:lt,y18n:Mc({directory:jc(Ir,"../../../locales"),updateFiles:!1})};function Ue(e,t,n,o){n.assert.notStrictEqual(e,t,o)}function Pr(e,t){t.assert.strictEqual(typeof e,"string")}function An(e){return Object.keys(e)}function be(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 Lt(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),o=/\.*[\][<>]/g,s=n.shift();if(!s)throw Error(`No command found in: ${e}`);let r={cmd:s.replace(o,""),demanded:[],optional:[]};return n.forEach((i,a)=>{let c=!1;if(i=i.replace(/\s/g,""),/\.+[\]>]/.test(i)&&a===n.length-1)c=!0;if(/^\[/.test(i))r.optional.push({cmd:i.replace(o,"").split("|"),variadic:c});else r.demanded.push({cmd:i.replace(o,"").split("|"),variadic:c})}),r}var jh=["first","second","third","fourth","fifth","sixth"];function Y(e,t,n){function o(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[Lt(`cmd ${e}`),t,n]}try{let s=0,[r,i,a]=o(),c=[].slice.call(i);while(c.length&&c[c.length-1]===void 0)c.pop();let l=a||c.length;if(l<r.demanded.length)throw new $e(`Not enough arguments provided. Expected ${r.demanded.length} but received ${c.length}.`);let u=r.demanded.length+r.optional.length;if(l>u)throw new $e(`Too many arguments provided. Expected max ${u} but received ${l}.`);r.demanded.forEach((d)=>{let f=c.shift(),h=Jc(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)Kc(h,d.cmd,s);s+=1}),r.optional.forEach((d)=>{if(c.length===0)return;let f=c.shift(),h=Jc(f);if(d.cmd.filter((p)=>p===h||p==="*").length===0)Kc(h,d.cmd,s);s+=1})}catch(s){console.warn(s.stack)}}function Jc(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function Kc(e,t,n){throw new $e(`Invalid ${jh[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class vr{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,o=!1){if(Y("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let s=0;s<e.length;s++){if(typeof e[s]!=="function")throw Error("middleware must be a function");let r=e[s];r.applyBeforeValidation=t,r.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let s=e;s.applyBeforeValidation=t,s.global=n,s.mutates=o,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((o)=>{let s=[...n[t]||[],t];if(!o.option)return!0;else return!s.includes(o.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function qc(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function sn(e,t,n,o){return n.reduce((s,r)=>{if(r.applyBeforeValidation!==o)return s;if(r.mutates){if(r.applied)return s;r.applied=!0}if(be(s))return s.then((i)=>Promise.all([i,r(i,t)])).then(([i,a])=>Object.assign(i,a));else{let i=r(s,t);return be(i)?i.then((a)=>Object.assign(s,a)):Object.assign(s,i)}},e)}function on(e,t,n=(o)=>{throw o}){try{let o=Wh(e)?e():e;return be(o)?o.then((s)=>t(s)):t(o)}catch(o){return n(o)}}function Wh(e){return typeof e==="function"}var Fn=/(^\*)|(^\$0)/;class zc{constructor(e,t,n,o){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=o,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,o){o=o||{},this.requireCache.add(n);let s=this.shim.path.resolve(this.shim.path.dirname(n),e),r=this.shim.readdirSync(s,{recursive:o.recurse?!0:!1});if(!Array.isArray(o.extensions))o.extensions=["js"];let i=typeof o.visit==="function"?o.visit:(a)=>a;for(let a of r){let c=a.toString();if(o.exclude){let u=!1;if(typeof o.exclude==="function")u=o.exclude(c);else u=o.exclude.test(c);if(u)continue}if(o.include){let u=!1;if(typeof o.include==="function")u=o.include(c);else u=o.include.test(c);if(!u)continue}let l=!1;for(let u of o.extensions)if(c.endsWith(u))l=!0;if(l){let u=this.shim.path.join(s,c),d=t(u),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(i(f,u,c)){if(this.requireCache.has(u))continue;else this.requireCache.add(u);if(!f.command)f.command=this.shim.path.basename(u,this.shim.path.extname(u));this.addHandler(f)}}}}addHandler(e,t,n,o,s,r){let i=[],a=qc(s);if(o=o||(()=>{}),Array.isArray(e))if(Uh(e))[e,...i]=e;else for(let c of e)this.addHandler(c);else if(Kh(e)){let c=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(c===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)c=[].concat(c).concat(e.aliases);this.addHandler(c,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(Hc(n)){this.addHandler([e].concat(i),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let c=Lt(e);i=i.map((d)=>Lt(d).cmd);let l=!1,u=[c.cmd].concat(i).filter((d)=>{if(Fn.test(d))return l=!0,!1;return!0});if(u.length===0&&l)u.push("$0");if(l)c.cmd=u[0],i=u.slice(1),e=e.replace(Fn,c.cmd);if(i.forEach((d)=>{this.aliasMap[d]=c.cmd}),t!==!1)this.usage.command(e,t,l,i,r);if(this.handlers[c.cmd]={original:e,description:t,handler:o,builder:n||{},middlewares:a,deprecated:r,demanded:c.demanded,optional:c.optional},l)this.defaultCommand=this.handlers[c.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,o,s,r){let i=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,a=t.getInternalMethods().getContext(),c=a.commands.slice(),l=!e;if(e)a.commands.push(e),a.fullCommands.push(i.original);let u=this.applyBuilderUpdateUsageAndParse(l,i,t,n.aliases,c,o,s,r);return be(u)?u.then((d)=>this.applyMiddlewareAndGetResult(l,i,d.innerArgv,a,s,d.aliases,t)):this.applyMiddlewareAndGetResult(l,i,u.innerArgv,a,s,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,o,s,r,i,a){let c=t.builder,l=n;if(qs(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(o),a);if(be(u))return u.then((d)=>(l=Gc(d)?d:n,this.parseAndUpdateUsage(e,t,l,s,r,i)))}else if(Jh(c))n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(o),Object.keys(t.builder).forEach((u)=>{l.option(u,c[u])});return this.parseAndUpdateUsage(e,t,l,s,r,i)}parseAndUpdateUsage(e,t,n,o,s,r){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(o,t),t.description);let i=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,s,r);return be(i)?i.then((a)=>({aliases:n.parsed.aliases,innerArgv:a})):{aliases:n.parsed.aliases,innerArgv:i}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=Fn.test(t.original)?t.original.replace(Fn,"").trim():t.original,o=e.filter((s)=>!Fn.test(s));return o.push(n),`$0 ${o.join(" ")}`}handleValidationAndGetResult(e,t,n,o,s,r,i,a){if(!r.getInternalMethods().getHasOutput()){let c=r.getInternalMethods().runValidation(s,a,r.parsed.error,e);n=on(n,(l)=>(c(l),l))}if(t.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();let c=!!r.getOptions().configuration["populate--"];if(r.getInternalMethods().postProcess(n,c,!1,!1),n=sn(n,r,i,!1),n=on(n,(l)=>{let u=t.handler(l);return be(u)?u.then(()=>l):l}),!e)r.getInternalMethods().getUsageInstance().cacheHelpMessage();if(be(n)&&!r.getInternalMethods().hasParseCallback())n.catch((l)=>{try{r.getInternalMethods().getUsageInstance().fail(null,l)}catch(u){}})}if(!e)o.commands.pop(),o.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,o,s,r,i){let a={};if(s)return n;if(!i.getInternalMethods().getHasOutput())a=this.populatePositionals(t,n,o,i);let c=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=sn(n,i,c,!0);return be(l)?l.then((u)=>this.handleValidationAndGetResult(e,t,u,o,r,i,c,a)):this.handleValidationAndGetResult(e,t,l,o,r,i,c,a)}populatePositionals(e,t,n,o){t._=t._.slice(n.commands.length);let s=e.demanded.slice(0),r=e.optional.slice(0),i={};this.validation.positionalCount(s.length,t._.length);while(s.length){let a=s.shift();this.populatePositional(a,t,i)}while(r.length){let a=r.shift();this.populatePositional(a,t,i)}return t._=n.commands.concat(t._.map((a)=>""+a)),this.postProcessPositionals(t,i,this.cmdToParseOptions(e.original),o),i}populatePositional(e,t,n){let o=e.cmd[0];if(e.variadic)n[o]=t._.splice(0).map(String);else if(t._.length)n[o]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=Lt(e);return n.demanded.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r,t.demand[s]=!0}),n.optional.forEach((o)=>{let[s,...r]=o.cmd;if(o.variadic)t.array.push(s),t.default[s]=[];t.alias[s]=r}),t}postProcessPositionals(e,t,n,o){let s=Object.assign({},o.getOptions());s.default=Object.assign(n.default,s.default);for(let c of Object.keys(n.alias))s.alias[c]=(s.alias[c]||[]).concat(n.alias[c]);s.array=s.array.concat(n.array),s.config={};let r=[];if(Object.keys(t).forEach((c)=>{t[c].map((l)=>{if(s.configuration["unknown-options-as-args"])s.key[c]=!0;r.push(`--${c}`),r.push(l)})}),!r.length)return;let i=Object.assign({},s.configuration,{"populate--":!1}),a=this.shim.Parser.detailed(r,Object.assign({},s,{configuration:i}));if(a.error)o.getInternalMethods().getUsageInstance().fail(a.error.message,a.error);else{let c=Object.keys(t);Object.keys(t).forEach((l)=>{c.push(...a.aliases[l])}),Object.keys(a.argv).forEach((l)=>{if(c.includes(l)){if(!t[l])t[l]=a.argv[l];if(!this.isInConfigs(o,l)&&!this.isDefaulted(o,l)&&Object.prototype.hasOwnProperty.call(e,l)&&Object.prototype.hasOwnProperty.call(a.argv,l)&&(Array.isArray(e[l])||Array.isArray(a.argv[l])))e[l]=[].concat(e[l],a.argv[l]);else e[l]=a.argv[l]}})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some((o)=>Object.prototype.hasOwnProperty.call(o,t))||n.some((o)=>Object.prototype.hasOwnProperty.call(o,this.shim.Parser.camelCase(t)))}runDefaultBuilderOn(e){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(e)){let n=Fn.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(qs(t))return t(e,!0);else if(!Hc(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let o of[e,t,n]){if(typeof o==="string"||o===!1)return o;Ue(o,!0,this.shim)}return!1}freeze(){this.frozens.push({handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand})}unfreeze(){let e=this.frozens.pop();Ue(e,void 0,this.shim),{handlers:this.handlers,aliasMap:this.aliasMap,defaultCommand:this.defaultCommand}=e}reset(){return this.handlers={},this.aliasMap={},this.defaultCommand=void 0,this.requireCache=new Set,this}}function Xc(e,t,n,o){return new zc(e,t,n,o)}function Hc(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function Uh(e){return e.every((t)=>typeof t==="string")}function qs(e){return typeof e==="function"}function Jh(e){return typeof e==="object"}function Kh(e){return typeof e==="object"&&!Array.isArray(e)}function Mt(e={},t=()=>!0){let n={};return An(e).forEach((o)=>{if(t(o,e[o]))n[o]=e[o]}),n}function Nt(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 qh(e){return typeof e==="boolean"}function Vc(e,t){let n=t.y18n.__,o={},s=[];o.failFn=function(P){s.push(P)};let r=null,i=null,a=!0;o.showHelpOnFail=function(P=!0,I){let[U,N]=typeof P==="string"?[!0,P]:[P,I];if(e.getInternalMethods().isGlobalContext())i=N;return r=N,a=U,o};let c=!1;o.fail=function(P,I){let U=e.getInternalMethods().getLoggerInstance();if(s.length)for(let N=s.length-1;N>=0;--N){let q=s[N];if(qh(q)){if(I)throw I;else if(P)throw Error(P)}else q(P,I,o)}else{if(e.getExitProcess())Nt(!0);if(!c){if(c=!0,a)e.showHelp("error"),U.error();if(P||I)U.error(P||I);let N=r||i;if(N){if(P||I)U.error("");U.error(N)}}if(I=I||new $e(P),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,I);else throw I}};let l=[],u=!1;o.usage=(M,P)=>{if(M===null)return u=!0,l=[],o;return u=!1,l.push([M,P||""]),o},o.getUsage=()=>l,o.getUsageDisabled=()=>u,o.getPositionalGroupName=()=>n("Positionals:");let d=[];o.example=(M,P)=>{d.push([M,P||""])};let f=[];o.command=function(P,I,U,N,q=!1){if(U)f=f.map((H)=>(H[2]=!1,H));f.push([P,I||"",U,N,q])},o.getCommands=()=>f;let h={};o.describe=function(P,I){if(Array.isArray(P))P.forEach((U)=>{o.describe(U,I)});else if(typeof P==="object")Object.keys(P).forEach((U)=>{o.describe(U,P[U])});else h[P]=I},o.getDescriptions=()=>h;let g=[];o.epilog=(M)=>{g.push(M)};let p=!1,m;o.wrap=(M)=>{p=!0,m=M},o.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!p)m=x(),p=!0;return m};let w="__yargsString__:";o.deferY18nLookup=(M)=>w+M,o.help=function(){if(S)return S;D();let P=e.customScriptName?e.$0:t.path.basename(e.$0),I=e.getDemandedOptions(),U=e.getDemandedCommands(),N=e.getDeprecatedOptions(),q=e.getGroups(),H=e.getOptions(),v=[];v=v.concat(Object.keys(h)),v=v.concat(Object.keys(I)),v=v.concat(Object.keys(U)),v=v.concat(Object.keys(H.default)),v=v.filter(F),v=Object.keys(v.reduce((J,oe)=>{if(oe!=="_")J[oe]=!0;return J},{}));let le=o.getWrap(),te=t.cliui({width:le,wrap:!!le});if(!u){if(l.length)l.forEach((J)=>{if(te.div({text:`${J[0].replace(/\$0/g,P)}`}),J[1])te.div({text:`${J[1]}`,padding:[1,0,0,0]})}),te.div();else if(f.length){let J=null;if(U._)J=`${P} <${n("command")}>
|
|
15
|
-
`;else
|
|
16
|
-
`;te.div(`${
|
|
17
|
-
`);te.div(`${
|
|
18
|
-
`)}return te.toString().replace(/\s*$/,"")};function
|
|
13
|
+
`).map((s)=>gm(s,t,n)).join(`
|
|
14
|
+
`)}function Vo(e){return Qc(e,{stringWidth:ht,stripAnsi:dn,wrap:Xo})}import{dirname as _l,resolve as El}from"path";import{readdirSync as mm,statSync as ym}from"fs";function Zo(e,t){let n=El(".",e),s;if(!ym(n).isDirectory())n=_l(n);while(!0){if(s=t(n,mm(n)),s)return El(n,s);if(n=_l(s=n),s===n)break}}import{inspect as Pm}from"util";import{fileURLToPath as Jl}from"url";import{format as Dm}from"util";import{normalize as km,resolve as xm}from"path";function fn(e){if(!(e!==e.toLowerCase()&&e!==e.toUpperCase()))e=e.toLowerCase();if(e.indexOf("-")===-1&&e.indexOf("_")===-1)return e;else{let n="",s=!1,o=e.match(/^-+/);for(let a=o?o[0].length:0;a<e.length;a++){let r=e.charAt(a);if(s)s=!1,r=r.toUpperCase();if(a!==0&&(r==="-"||r==="_"))s=!0;else if(r!=="-"&&r!=="_")n+=r}return n}}function ir(e,t){let n=e.toLowerCase();t=t||"-";let s="";for(let o=0;o<e.length;o++){let a=n.charAt(o),r=e.charAt(o);if(a!==r&&o>0)s+=`${t}${n.charAt(o)}`;else s+=r}return s}function ar(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 $l(e){if(Array.isArray(e))return e.map((r)=>typeof r!=="string"?r+"":r);e=e.trim();let t=0,n=null,s=null,o=null,a=[];for(let r=0;r<e.length;r++){if(n=s,s=e.charAt(r),s===" "&&!o){if(n!==" ")t++;continue}if(s===o)o=null;else if((s==="'"||s==='"')&&!o)o=s;if(!a[t])a[t]="";a[t]+=s}return a}var ot;(function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"})(ot||(ot={}));var Tt;class ei{constructor(e){Tt=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=$l(e),o=typeof e==="string",a=bm(Object.assign(Object.create(null),n.alias)),r=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),i=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,u=r["populate--"],d=u?"--":"_",f=Object.create(null),p=Object.create(null),g=n.__||Tt.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:[]},b=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,m=new RegExp("^--"+r["negation-prefix"]+"(.+)");if([].concat(n.array||[]).filter(Boolean).forEach(function(x){let F=typeof x==="object"?x.key:x,W=Object.keys(x).map(function(R){return{boolean:"bools",string:"strings",number:"numbers"}[R]}).filter(Boolean).pop();if(W)h[W][F]=!0;h.arrays[F]=!0,h.keys.push(F)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(x){h.bools[x]=!0,h.keys.push(x)}),[].concat(n.string||[]).filter(Boolean).forEach(function(x){h.strings[x]=!0,h.keys.push(x)}),[].concat(n.number||[]).filter(Boolean).forEach(function(x){h.numbers[x]=!0,h.keys.push(x)}),[].concat(n.count||[]).filter(Boolean).forEach(function(x){h.counts[x]=!0,h.keys.push(x)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(x){h.normalize[x]=!0,h.keys.push(x)}),typeof n.narg==="object")Object.entries(n.narg).forEach(([x,F])=>{if(typeof F==="number")h.nargs[x]=F,h.keys.push(x)});if(typeof n.coerce==="object")Object.entries(n.coerce).forEach(([x,F])=>{if(typeof F==="function")h.coercions[x]=F,h.keys.push(x)});if(typeof n.config<"u"){if(Array.isArray(n.config)||typeof n.config==="string")[].concat(n.config).filter(Boolean).forEach(function(x){h.configs[x]=!0});else if(typeof n.config==="object")Object.entries(n.config).forEach(([x,F])=>{if(typeof F==="boolean"||typeof F==="function")h.configs[x]=F})}oe(n.key,a,n.default,h.arrays),Object.keys(i).forEach(function(x){(h.aliases[x]||[]).forEach(function(F){i[F]=i[x]})});let w=null;qo();let D=[],k=Object.assign(Object.create(null),{_:[]}),E={};for(let x=0;x<s.length;x++){let F=s[x],W=F.replace(/^-{3,}/,"---"),R,C,Q,X,ne,Ie;if(F!=="--"&&/^-/.test(F)&&re(F))A(F);else if(W.match(/^---+(=|$)/)){A(F);continue}else if(F.match(/^--.+=/)||!r["short-option-groups"]&&F.match(/^-.+=/)){if(X=F.match(/^--?([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)if(U(X[1],h.arrays))x=S(x,X[1],s,X[2]);else if(U(X[1],h.nargs)!==!1)x=_(x,X[1],s,X[2]);else I(X[1],X[2],!0)}else if(F.match(m)&&r["boolean-negation"]){if(X=F.match(m),X!==null&&Array.isArray(X)&&X.length>=2)C=X[1],I(C,U(C,h.arrays)?[!1]:!1)}else if(F.match(/^--.+/)||!r["short-option-groups"]&&F.match(/^-[^-]+/)){if(X=F.match(/^--?(.+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(C=X[1],U(C,h.arrays))x=S(x,C,s);else if(U(C,h.nargs)!==!1)x=_(x,C,s);else if(ne=s[x+1],ne!==void 0&&(!ne.match(/^-/)||ne.match(b))&&!U(C,h.bools)&&!U(C,h.counts))I(C,ne),x++;else if(/^(true|false)$/.test(ne))I(C,ne),x++;else I(C,B(C))}else if(F.match(/^-.\..+=/)){if(X=F.match(/^-([^=]+)=([\s\S]*)$/),X!==null&&Array.isArray(X)&&X.length>=3)I(X[1],X[2])}else if(F.match(/^-.\..+/)&&!F.match(b)){if(ne=s[x+1],X=F.match(/^-(.\..+)/),X!==null&&Array.isArray(X)&&X.length>=2)if(C=X[1],ne!==void 0&&!ne.match(/^-/)&&!U(C,h.bools)&&!U(C,h.counts))I(C,ne),x++;else I(C,B(C))}else if(F.match(/^-[^-]+/)&&!F.match(b)){Q=F.slice(1,-1).split(""),R=!1;for(let We=0;We<Q.length;We++){if(ne=F.slice(We+2),Q[We+1]&&Q[We+1]==="="){if(Ie=F.slice(We+3),C=Q[We],U(C,h.arrays))x=S(x,C,s,Ie);else if(U(C,h.nargs)!==!1)x=_(x,C,s,Ie);else I(C,Ie);R=!0;break}if(ne==="-"){I(Q[We],ne);continue}if(/[A-Za-z]/.test(Q[We])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(ne)&&U(ne,h.bools)===!1){I(Q[We],ne),R=!0;break}if(Q[We+1]&&Q[We+1].match(/\W/)){I(Q[We],ne),R=!0;break}else I(Q[We],B(Q[We]))}if(C=F.slice(-1)[0],!R&&C!=="-")if(U(C,h.arrays))x=S(x,C,s);else if(U(C,h.nargs)!==!1)x=_(x,C,s);else if(ne=s[x+1],ne!==void 0&&(!/^(-|--)[^-]/.test(ne)||ne.match(b))&&!U(C,h.bools)&&!U(C,h.counts))I(C,ne),x++;else if(/^(true|false)$/.test(ne))I(C,ne),x++;else I(C,B(C))}else if(F.match(/^-[0-9]$/)&&F.match(b)&&U(F.slice(1),h.bools))C=F.slice(1),I(C,B(C));else if(F==="--"){D=s.slice(x+1);break}else if(r["halt-at-non-option"]){D=s.slice(x);break}else A(F)}if(j(k,!0),j(k,!1),N(k),O(),ce(k,h.aliases,i,!0),z(k),r["set-placeholder-key"])M(k);if(Object.keys(h.counts).forEach(function(x){if(!te(k,x.split(".")))I(x,0)}),u&&D.length)k[d]=[];if(D.forEach(function(x){k[d].push(x)}),r["camel-case-expansion"]&&r["strip-dashed"])Object.keys(k).filter((x)=>x!=="--"&&x.includes("-")).forEach((x)=>{delete k[x]});if(r["strip-aliased"])[].concat(...Object.keys(a).map((x)=>a[x])).forEach((x)=>{if(r["camel-case-expansion"]&&x.includes("-"))delete k[x.split(".").map((F)=>fn(F)).join(".")];delete k[x]});function A(x){let F=v("_",x);if(typeof F==="string"||typeof F==="number")k._.push(F)}function _(x,F,W,R){let C,Q=U(F,h.nargs);if(Q=typeof Q!=="number"||isNaN(Q)?1:Q,Q===0){if(!Ae(R))w=Error(g("Argument unexpected for: %s",F));return I(F,B(F)),x}let X=Ae(R)?0:1;if(r["nargs-eats-options"]){if(W.length-(x+1)+X<Q)w=Error(g("Not enough arguments following: %s",F));X=Q}else{for(C=x+1;C<W.length;C++)if(!W[C].match(/^-[^0-9]/)||W[C].match(b)||re(W[C]))X++;else break;if(X<Q)w=Error(g("Not enough arguments following: %s",F))}let ne=Math.min(X,Q);if(!Ae(R)&&ne>0)I(F,R),ne--;for(C=x+1;C<ne+x+1;C++)I(F,W[C]);return x+ne}function S(x,F,W,R){let C=[],Q=R||W[x+1],X=U(F,h.nargs);if(U(F,h.bools)&&!/^(true|false)$/.test(Q))C.push(!0);else if(Ae(Q)||Ae(R)&&/^-/.test(Q)&&!b.test(Q)&&!re(Q)){if(i[F]!==void 0){let ne=i[F];C=Array.isArray(ne)?ne:[ne]}}else{if(!Ae(R))C.push(L(F,R,!0));for(let ne=x+1;ne<W.length;ne++){if(!r["greedy-arrays"]&&C.length>0||X&&typeof X==="number"&&C.length>=X)break;if(Q=W[ne],/^-/.test(Q)&&!b.test(Q)&&!re(Q))break;x=ne,C.push(L(F,Q,o))}}if(typeof X==="number"&&(X&&C.length<X||isNaN(X)&&C.length===0))w=Error(g("Not enough arguments following: %s",F));return I(F,C),x}function I(x,F,W=o){if(/-/.test(x)&&r["camel-case-expansion"]){let Q=x.split(".").map(function(X){return fn(X)}).join(".");J(x,Q)}let R=L(x,F,W),C=x.split(".");if(q(k,C,R),h.aliases[x])h.aliases[x].forEach(function(Q){let X=Q.split(".");q(k,X,R)});if(C.length>1&&r["dot-notation"])(h.aliases[C[0]]||[]).forEach(function(Q){let X=Q.split("."),ne=[].concat(C);if(ne.shift(),X=X.concat(ne),!(h.aliases[x]||[]).includes(X.join(".")))q(k,X,R)});if(U(x,h.normalize)&&!U(x,h.arrays))[x].concat(h.aliases[x]||[]).forEach(function(X){Object.defineProperty(E,X,{enumerable:!0,get(){return F},set(ne){F=typeof ne==="string"?Tt.normalize(ne):ne}})})}function J(x,F){if(!(h.aliases[x]&&h.aliases[x].length))h.aliases[x]=[F],f[F]=!0;if(!(h.aliases[F]&&h.aliases[F].length))J(F,x)}function L(x,F,W){if(W)F=wm(F);if(U(x,h.bools)||U(x,h.counts)){if(typeof F==="string")F=F==="true"}let R=Array.isArray(F)?F.map(function(C){return v(x,C)}):v(x,F);if(U(x,h.counts)&&(Ae(R)||typeof R==="boolean"))R=Qo();if(U(x,h.normalize)&&U(x,h.arrays))if(Array.isArray(F))R=F.map((C)=>Tt.normalize(C));else R=Tt.normalize(F);return R}function v(x,F){if(!r["parse-positional-numbers"]&&x==="_")return F;if(!U(x,h.strings)&&!U(x,h.bools)&&!Array.isArray(F)){if(ar(F)&&r["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${F}`)))||!Ae(F)&&U(x,h.numbers))F=Number(F)}return F}function N(x){let F=Object.create(null);ce(F,h.aliases,i),Object.keys(h.configs).forEach(function(W){let R=x[W]||F[W];if(R)try{let C=null,Q=Tt.resolve(Tt.cwd(),R),X=h.configs[W];if(typeof X==="function"){try{C=X(Q)}catch(ne){C=ne}if(C instanceof Error){w=C;return}}else C=Tt.require(Q);H(C)}catch(C){if(C.name==="PermissionDenied")w=C;else if(x[W])w=Error(g("Invalid JSON config file: %s",R))}})}function H(x,F){Object.keys(x).forEach(function(W){let R=x[W],C=F?F+"."+W:W;if(typeof R==="object"&&R!==null&&!Array.isArray(R)&&r["dot-notation"])H(R,C);else if(!te(k,C.split("."))||U(C,h.arrays)&&r["combine-arrays"])I(C,R)})}function O(){if(typeof c<"u")c.forEach(function(x){H(x)})}function j(x,F){if(typeof l>"u")return;let W=typeof l==="string"?l:"",R=Tt.env();Object.keys(R).forEach(function(C){if(W===""||C.lastIndexOf(W,0)===0){let Q=C.split("__").map(function(X,ne){if(ne===0)X=X.substring(W.length);return fn(X)});if((F&&h.configs[Q.join(".")]||!F)&&!te(x,Q))I(Q.join("."),R[C])}})}function z(x){let F,W=new Set;Object.keys(x).forEach(function(R){if(!W.has(R)){if(F=U(R,h.coercions),typeof F==="function")try{let C=v(R,F(x[R]));[].concat(h.aliases[R]||[],R).forEach((Q)=>{W.add(Q),x[Q]=C})}catch(C){w=C}}})}function M(x){return h.keys.forEach((F)=>{if(~F.indexOf("."))return;if(typeof x[F]>"u")x[F]=void 0}),x}function ce(x,F,W,R=!1){Object.keys(W).forEach(function(C){if(!te(x,C.split("."))){if(q(x,C.split("."),W[C]),R)p[C]=!0;(F[C]||[]).forEach(function(Q){if(te(x,Q.split(".")))return;q(x,Q.split("."),W[C])})}})}function te(x,F){let W=x;if(!r["dot-notation"])F=[F.join(".")];F.slice(0,-1).forEach(function(C){W=W[C]||{}});let R=F[F.length-1];if(typeof W!=="object")return!1;else return R in W}function q(x,F,W){let R=x;if(!r["dot-notation"])F=[F.join(".")];F.slice(0,-1).forEach(function(Ie){if(Ie=Cl(Ie),typeof R==="object"&&R[Ie]===void 0)R[Ie]={};if(typeof R[Ie]!=="object"||Array.isArray(R[Ie])){if(Array.isArray(R[Ie]))R[Ie].push({});else R[Ie]=[R[Ie],{}];R=R[Ie][R[Ie].length-1]}else R=R[Ie]});let C=Cl(F[F.length-1]),Q=U(F.join("."),h.arrays),X=Array.isArray(W),ne=r["duplicate-arguments-array"];if(!ne&&U(C,h.nargs)){if(ne=!0,!Ae(R[C])&&h.nargs[C]===1||Array.isArray(R[C])&&R[C].length===h.nargs[C])R[C]=void 0}if(W===Qo())R[C]=Qo(R[C]);else if(Array.isArray(R[C]))if(ne&&Q&&X)R[C]=r["flatten-duplicate-arrays"]?R[C].concat(W):(Array.isArray(R[C][0])?R[C]:[R[C]]).concat([W]);else if(!ne&&Boolean(Q)===Boolean(X))R[C]=W;else R[C]=R[C].concat([W]);else if(R[C]===void 0&&Q)R[C]=X?W:[W];else if(ne&&!(R[C]===void 0||U(C,h.counts)||U(C,h.bools)))R[C]=[R[C],W];else R[C]=W}function oe(...x){x.forEach(function(F){Object.keys(F||{}).forEach(function(W){if(h.aliases[W])return;h.aliases[W]=[].concat(a[W]||[]),h.aliases[W].concat(W).forEach(function(R){if(/-/.test(R)&&r["camel-case-expansion"]){let C=fn(R);if(C!==W&&h.aliases[W].indexOf(C)===-1)h.aliases[W].push(C),f[C]=!0}}),h.aliases[W].concat(W).forEach(function(R){if(R.length>1&&/[A-Z]/.test(R)&&r["camel-case-expansion"]){let C=ir(R,"-");if(C!==W&&h.aliases[W].indexOf(C)===-1)h.aliases[W].push(C),f[C]=!0}}),h.aliases[W].forEach(function(R){h.aliases[R]=[W].concat(h.aliases[W].filter(function(C){return R!==C}))})})})}function U(x,F){let W=[].concat(h.aliases[x]||[],x),R=Object.keys(F),C=W.find((Q)=>R.includes(Q));return C?F[C]:!1}function de(x){let F=Object.keys(h);return[].concat(F.map((R)=>h[R])).some(function(R){return Array.isArray(R)?R.includes(x):R[x]})}function se(x,...F){return[].concat(...F).some(function(R){let C=x.match(R);return C&&de(C[1])})}function K(x){if(x.match(b)||!x.match(/^-[^-]+/))return!1;let F=!0,W,R=x.slice(1).split("");for(let C=0;C<R.length;C++){if(W=x.slice(C+2),!de(R[C])){F=!1;break}if(R[C+1]&&R[C+1]==="="||W==="-"||/[A-Za-z]/.test(R[C])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(W)||R[C+1]&&R[C+1].match(/\W/))break}return F}function re(x){return r["unknown-options-as-args"]&&G(x)}function G(x){if(x=x.replace(/^-{3,}/,"--"),x.match(b))return!1;if(K(x))return!1;return!se(x,/^-+([^=]+?)=[\s\S]*$/,m,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}function B(x){if(!U(x,h.bools)&&!U(x,h.counts)&&`${x}`in i)return i[x];else return pe(we(x))}function pe(x){return{[ot.BOOLEAN]:!0,[ot.STRING]:"",[ot.NUMBER]:void 0,[ot.ARRAY]:[]}[x]}function we(x){let F=ot.BOOLEAN;if(U(x,h.strings))F=ot.STRING;else if(U(x,h.numbers))F=ot.NUMBER;else if(U(x,h.bools))F=ot.BOOLEAN;else if(U(x,h.arrays))F=ot.ARRAY;return F}function Ae(x){return x===void 0}function qo(){Object.keys(h.counts).find((x)=>{if(U(x,h.arrays))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",x)),!0;else if(U(x,h.nargs))return w=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",x)),!0;return!1})}return{aliases:Object.assign({},h.aliases),argv:Object.assign(E,k),configuration:r,defaulted:Object.assign({},p),error:w,newAliases:Object.assign({},f)}}}function bm(e){let t=[],n=Object.create(null),s=!0;Object.keys(e).forEach(function(o){t.push([].concat(e[o],o))});while(s){s=!1;for(let o=0;o<t.length;o++)for(let a=o+1;a<t.length;a++)if(t[o].filter(function(i){return t[a].indexOf(i)!==-1}).length){t[o]=t[o].concat(t[a]),t.splice(a,1),s=!0;break}}return t.forEach(function(o){o=o.filter(function(r,i,c){return c.indexOf(r)===i});let a=o.pop();if(a!==void 0&&typeof a==="string")n[a]=o}),n}function Qo(e){return e!==void 0?e+1:1}function Cl(e){if(e==="__proto__")return"___proto___";return e}function wm(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 Sm}from"fs";import{createRequire as Al}from"node:module";var ti,ni,si,Fl=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):20,Tl=(ni=(ti=process===null||process===void 0?void 0:process.versions)===null||ti===void 0?void 0:ti.node)!==null&&ni!==void 0?ni:(si=process===null||process===void 0?void 0:process.version)===null||si===void 0?void 0:si.slice(1);if(Tl){if(Number(Tl.match(/^([^.]+)/)[1])<Fl)throw Error(`yargs parser supports a minimum Node.js version of ${Fl}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}var _m=process?process.env:{},Ol=Al?Al(import.meta.url):void 0,Rl=new ei({cwd:process.cwd,env:()=>_m,format:Dm,normalize:km,resolve:xm,require:(e)=>{if(typeof Ol<"u")return Ol(e);else if(e.match(/\.json$/))return JSON.parse(Sm(e,"utf8"));else throw Error("only .json config files are supported in ESM")}}),ps=function(t,n){return Rl.parse(t.slice(),n).argv};ps.detailed=function(e,t){return Rl.parse(e.slice(),t)};ps.camelCase=fn;ps.decamelize=ir;ps.looksLikeNumber=ar;var ri=ps;import{basename as Lm,dirname as Mm,extname as Nm,relative as Bm,resolve as Wl,join as jm}from"path";function Il(){if(Em())return 0;return 1}function Em(){return $m()&&!process.defaultApp}function $m(){return!!process.versions.electron}function oi(e){return e.slice(Il()+1)}function vl(){return process.argv[Il()]}import{readFileSync as Cm,statSync as Am,writeFile as Fm}from"fs";import{format as Tm}from"util";import{resolve as Om}from"path";var Pl={fs:{readFileSync:Cm,writeFile:Fm},format:Tm,resolve:Om,exists:(e)=>{try{return Am(e).isFile()}catch(t){return!1}}};var gt;class Ll{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles=typeof e.updateFiles==="boolean"?e.updateFiles:!0,this.locale=e.locale||"en",this.fallbackToLanguage=typeof e.fallbackToLanguage==="boolean"?e.fallbackToLanguage:!0,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if(typeof arguments[0]!=="string")return this._taggedLiteral(arguments[0],...arguments);let t=e.shift(),n=function(){};if(typeof e[e.length-1]==="function")n=e.pop();if(n=n||function(){},!this.cache[this.locale])this._readLocaleFile();if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n});else n();return gt.format.apply(gt.format,[this.cache[this.locale][t]||t].concat(e))}__n(){let e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),s=e.shift(),o=function(){};if(typeof e[e.length-1]==="function")o=e.pop();if(!this.cache[this.locale])this._readLocaleFile();let a=s===1?t:n;if(this.cache[this.locale][t])a=this.cache[this.locale][t][s===1?"one":"other"];if(!this.cache[this.locale][t]&&this.updateFiles)this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:o});else o();let r=[a];if(~a.indexOf("%d"))r.push(s);return gt.format.apply(gt.format,r.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){if(!this.cache[this.locale])this._readLocaleFile();for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))this.cache[this.locale][t]=e[t]}_taggedLiteral(e,...t){let n="";return e.forEach(function(s,o){let a=t[o+1];if(n+=s,typeof a<"u")n+="%s"}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){if(this.writeQueue.push(e),this.writeQueue.length===1)this._processWriteQueue()}_processWriteQueue(){let e=this,t=this.writeQueue[0],{directory:n,locale:s,cb:o}=t,a=this._resolveLocaleFile(n,s),r=JSON.stringify(this.cache[s],null,2);gt.fs.writeFile(a,r,"utf-8",function(i){if(e.writeQueue.shift(),e.writeQueue.length>0)e._processWriteQueue();o(i)})}_readLocaleFile(){let e={},t=this._resolveLocaleFile(this.directory,this.locale);try{if(gt.fs.readFileSync)e=JSON.parse(gt.fs.readFileSync(t,"utf-8"))}catch(n){if(n instanceof SyntaxError)n.message="syntax error in "+t;if(n.code==="ENOENT")e={};else throw n}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=gt.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){let s=gt.resolve(e,"./",t.split("_")[0]+".json");if(this._fileExistsSync(s))n=s}return n}_fileExistsSync(e){return gt.exists(e)}}function Ml(e,t){gt=t;let n=new Ll(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 Rm=(e)=>Ml(e,Pl),Nl=Rm;var Ul=Gc(jl(),1);import{createRequire as Wm}from"node:module";import{readFileSync as Jm,readdirSync as Um}from"node:fs";var ii=Jl(import.meta.url),Km=ii.substring(0,ii.lastIndexOf("node_modules")),qm=Wm(import.meta.url),ai={assert:{notStrictEqual:Im,strictEqual:vm},cliui:Vo,findUp:Zo,getEnv:(e)=>process.env[e],inspect:Pm,getProcessArgvBin:vl,mainFilename:Km||process.cwd(),Parser:ri,path:{basename:Lm,dirname:Mm,extname:Nm,relative:Bm,resolve:Wl,join:jm},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:Jm,readdirSync:Um,require:qm,getCallerFile:()=>{let e=Ul.default(3);return e.match(/^file:\/\//)?Jl(e):e},stringWidth:ht,y18n:Nl({directory:Wl(ii,"../../../locales"),updateFiles:!1})};function Je(e,t,n,s){n.assert.notStrictEqual(e,t,s)}function ci(e,t){t.assert.strictEqual(typeof e,"string")}function jn(e){return Object.keys(e)}function De(e){return!!e&&!!e.then&&typeof e.then==="function"}class $e extends Error{constructor(e){super(e||"yargs error");if(this.name="YError",Error.captureStackTrace)Error.captureStackTrace(this,$e)}}function qt(e){let n=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),s=/\.*[\][<>]/g,o=n.shift();if(!o)throw Error(`No command found in: ${e}`);let a={cmd:o.replace(s,""),demanded:[],optional:[]};return n.forEach((r,i)=>{let c=!1;if(r=r.replace(/\s/g,""),/\.+[\]>]/.test(r)&&i===n.length-1)c=!0;if(/^\[/.test(r))a.optional.push({cmd:r.replace(s,"").split("|"),variadic:c});else a.demanded.push({cmd:r.replace(s,"").split("|"),variadic:c})}),a}var Hm=["first","second","third","fourth","fifth","sixth"];function V(e,t,n){function s(){return typeof e==="object"?[{demanded:[],optional:[]},e,t]:[qt(`cmd ${e}`),t,n]}try{let o=0,[a,r,i]=s(),c=[].slice.call(r);while(c.length&&c[c.length-1]===void 0)c.pop();let l=i||c.length;if(l<a.demanded.length)throw new $e(`Not enough arguments provided. Expected ${a.demanded.length} but received ${c.length}.`);let u=a.demanded.length+a.optional.length;if(l>u)throw new $e(`Too many arguments provided. Expected max ${u} but received ${l}.`);a.demanded.forEach((d)=>{let f=c.shift(),p=Kl(f);if(d.cmd.filter((h)=>h===p||h==="*").length===0)ql(p,d.cmd,o);o+=1}),a.optional.forEach((d)=>{if(c.length===0)return;let f=c.shift(),p=Kl(f);if(d.cmd.filter((h)=>h===p||h==="*").length===0)ql(p,d.cmd,o);o+=1})}catch(o){console.warn(o.stack)}}function Kl(e){if(Array.isArray(e))return"array";else if(e===null)return"null";return typeof e}function ql(e,t,n){throw new $e(`Invalid ${Hm[n]||"manyith"} argument. Expected ${t.join(" or ")} but received ${e}.`)}class li{constructor(e){this.globalMiddleware=[],this.frozens=[],this.yargs=e}addMiddleware(e,t,n=!0,s=!1){if(V("<array|function> [boolean] [boolean] [boolean]",[e,t,n],arguments.length),Array.isArray(e)){for(let o=0;o<e.length;o++){if(typeof e[o]!=="function")throw Error("middleware must be a function");let a=e[o];a.applyBeforeValidation=t,a.global=n}Array.prototype.push.apply(this.globalMiddleware,e)}else if(typeof e==="function"){let o=e;o.applyBeforeValidation=t,o.global=n,o.mutates=s,this.globalMiddleware.push(e)}return this.yargs}addCoerceMiddleware(e,t){let n=this.yargs.getAliases();return this.globalMiddleware=this.globalMiddleware.filter((s)=>{let o=[...n[t]||[],t];if(!s.option)return!0;else return!o.includes(s.option)}),e.option=t,this.addMiddleware(e,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){let e=this.frozens.pop();if(e!==void 0)this.globalMiddleware=e}reset(){this.globalMiddleware=this.globalMiddleware.filter((e)=>e.global)}}function Hl(e){if(!e)return[];return e.map((t)=>(t.applyBeforeValidation=!1,t))}function pn(e,t,n,s){return n.reduce((o,a)=>{if(a.applyBeforeValidation!==s)return o;if(a.mutates){if(a.applied)return o;a.applied=!0}if(De(o))return o.then((r)=>Promise.all([r,a(r,t)])).then(([r,i])=>Object.assign(r,i));else{let r=a(o,t);return De(r)?r.then((i)=>Object.assign(o,i)):Object.assign(o,r)}},e)}function hn(e,t,n=(s)=>{throw s}){try{let s=zm(e)?e():e;return De(s)?s.then((o)=>t(o)):t(s)}catch(s){return n(s)}}function zm(e){return typeof e==="function"}var Wn=/(^\*)|(^\$0)/;class Yl{constructor(e,t,n,s){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=s,this.usage=e,this.globalMiddleware=n,this.validation=t}addDirectory(e,t,n,s){s=s||{},this.requireCache.add(n);let o=this.shim.path.resolve(this.shim.path.dirname(n),e),a=this.shim.readdirSync(o,{recursive:s.recurse?!0:!1});if(!Array.isArray(s.extensions))s.extensions=["js"];let r=typeof s.visit==="function"?s.visit:(i)=>i;for(let i of a){let c=i.toString();if(s.exclude){let u=!1;if(typeof s.exclude==="function")u=s.exclude(c);else u=s.exclude.test(c);if(u)continue}if(s.include){let u=!1;if(typeof s.include==="function")u=s.include(c);else u=s.include.test(c);if(!u)continue}let l=!1;for(let u of s.extensions)if(c.endsWith(u))l=!0;if(l){let u=this.shim.path.join(o,c),d=t(u),f=Object.create(null,Object.getOwnPropertyDescriptors({...d}));if(r(f,u,c)){if(this.requireCache.has(u))continue;else this.requireCache.add(u);if(!f.command)f.command=this.shim.path.basename(u,this.shim.path.extname(u));this.addHandler(f)}}}}addHandler(e,t,n,s,o,a){let r=[],i=Hl(o);if(s=s||(()=>{}),Array.isArray(e))if(Ym(e))[e,...r]=e;else for(let c of e)this.addHandler(c);else if(Xm(e)){let c=Array.isArray(e.command)||typeof e.command==="string"?e.command:null;if(c===null)throw Error(`No command name given for module: ${this.shim.inspect(e)}`);if(e.aliases)c=[].concat(c).concat(e.aliases);this.addHandler(c,this.extractDesc(e),e.builder,e.handler,e.middlewares,e.deprecated);return}else if(zl(n)){this.addHandler([e].concat(r),t,n.builder,n.handler,n.middlewares,n.deprecated);return}if(typeof e==="string"){let c=qt(e);r=r.map((d)=>qt(d).cmd);let l=!1,u=[c.cmd].concat(r).filter((d)=>{if(Wn.test(d))return l=!0,!1;return!0});if(u.length===0&&l)u.push("$0");if(l)c.cmd=u[0],r=u.slice(1),e=e.replace(Wn,c.cmd);if(r.forEach((d)=>{this.aliasMap[d]=c.cmd}),t!==!1)this.usage.command(e,t,l,r,a);if(this.handlers[c.cmd]={original:e,description:t,handler:s,builder:n||{},middlewares:i,deprecated:a,demanded:c.demanded,optional:c.optional},l)this.defaultCommand=this.handlers[c.cmd]}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(e,t,n,s,o,a){let r=this.handlers[e]||this.handlers[this.aliasMap[e]]||this.defaultCommand,i=t.getInternalMethods().getContext(),c=i.commands.slice(),l=!e;if(e)i.commands.push(e),i.fullCommands.push(r.original);let u=this.applyBuilderUpdateUsageAndParse(l,r,t,n.aliases,c,s,o,a);return De(u)?u.then((d)=>this.applyMiddlewareAndGetResult(l,r,d.innerArgv,i,o,d.aliases,t)):this.applyMiddlewareAndGetResult(l,r,u.innerArgv,i,o,u.aliases,t)}applyBuilderUpdateUsageAndParse(e,t,n,s,o,a,r,i){let c=t.builder,l=n;if(cr(c)){n.getInternalMethods().getUsageInstance().freeze();let u=c(n.getInternalMethods().reset(s),i);if(De(u))return u.then((d)=>(l=Xl(d)?d:n,this.parseAndUpdateUsage(e,t,l,o,a,r)))}else if(Gm(c))n.getInternalMethods().getUsageInstance().freeze(),l=n.getInternalMethods().reset(s),Object.keys(t.builder).forEach((u)=>{l.option(u,c[u])});return this.parseAndUpdateUsage(e,t,l,o,a,r)}parseAndUpdateUsage(e,t,n,s,o,a){if(e)n.getInternalMethods().getUsageInstance().unfreeze(!0);if(this.shouldUpdateUsage(n))n.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(s,t),t.description);let r=n.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,o,a);return De(r)?r.then((i)=>({aliases:n.parsed.aliases,innerArgv:i})):{aliases:n.parsed.aliases,innerArgv:r}}shouldUpdateUsage(e){return!e.getInternalMethods().getUsageInstance().getUsageDisabled()&&e.getInternalMethods().getUsageInstance().getUsage().length===0}usageFromParentCommandsCommandHandler(e,t){let n=Wn.test(t.original)?t.original.replace(Wn,"").trim():t.original,s=e.filter((o)=>!Wn.test(o));return s.push(n),`$0 ${s.join(" ")}`}handleValidationAndGetResult(e,t,n,s,o,a,r,i){if(!a.getInternalMethods().getHasOutput()){let c=a.getInternalMethods().runValidation(o,i,a.parsed.error,e);n=hn(n,(l)=>(c(l),l))}if(t.handler&&!a.getInternalMethods().getHasOutput()){a.getInternalMethods().setHasOutput();let c=!!a.getOptions().configuration["populate--"];if(a.getInternalMethods().postProcess(n,c,!1,!1),n=pn(n,a,r,!1),n=hn(n,(l)=>{let u=t.handler(l);return De(u)?u.then(()=>l):l}),!e)a.getInternalMethods().getUsageInstance().cacheHelpMessage();if(De(n)&&!a.getInternalMethods().hasParseCallback())n.catch((l)=>{try{a.getInternalMethods().getUsageInstance().fail(null,l)}catch(u){}})}if(!e)s.commands.pop(),s.fullCommands.pop();return n}applyMiddlewareAndGetResult(e,t,n,s,o,a,r){let i={};if(o)return n;if(!r.getInternalMethods().getHasOutput())i=this.populatePositionals(t,n,s,r);let c=this.globalMiddleware.getMiddleware().slice(0).concat(t.middlewares),l=pn(n,r,c,!0);return De(l)?l.then((u)=>this.handleValidationAndGetResult(e,t,u,s,a,r,c,i)):this.handleValidationAndGetResult(e,t,l,s,a,r,c,i)}populatePositionals(e,t,n,s){t._=t._.slice(n.commands.length);let o=e.demanded.slice(0),a=e.optional.slice(0),r={};this.validation.positionalCount(o.length,t._.length);while(o.length){let i=o.shift();this.populatePositional(i,t,r)}while(a.length){let i=a.shift();this.populatePositional(i,t,r)}return t._=n.commands.concat(t._.map((i)=>""+i)),this.postProcessPositionals(t,r,this.cmdToParseOptions(e.original),s),r}populatePositional(e,t,n){let s=e.cmd[0];if(e.variadic)n[s]=t._.splice(0).map(String);else if(t._.length)n[s]=[String(t._.shift())]}cmdToParseOptions(e){let t={array:[],default:{},alias:{},demand:{}},n=qt(e);return n.demanded.forEach((s)=>{let[o,...a]=s.cmd;if(s.variadic)t.array.push(o),t.default[o]=[];t.alias[o]=a,t.demand[o]=!0}),n.optional.forEach((s)=>{let[o,...a]=s.cmd;if(s.variadic)t.array.push(o),t.default[o]=[];t.alias[o]=a}),t}postProcessPositionals(e,t,n,s){let o=Object.assign({},s.getOptions());o.default=Object.assign(n.default,o.default);for(let c of Object.keys(n.alias))o.alias[c]=(o.alias[c]||[]).concat(n.alias[c]);o.array=o.array.concat(n.array),o.config={};let a=[];if(Object.keys(t).forEach((c)=>{t[c].map((l)=>{if(o.configuration["unknown-options-as-args"])o.key[c]=!0;a.push(`--${c}`),a.push(l)})}),!a.length)return;let r=Object.assign({},o.configuration,{"populate--":!1}),i=this.shim.Parser.detailed(a,Object.assign({},o,{configuration:r}));if(i.error)s.getInternalMethods().getUsageInstance().fail(i.error.message,i.error);else{let c=Object.keys(t);Object.keys(t).forEach((l)=>{c.push(...i.aliases[l])}),Object.keys(i.argv).forEach((l)=>{if(c.includes(l)){if(!t[l])t[l]=i.argv[l];if(!this.isInConfigs(s,l)&&!this.isDefaulted(s,l)&&Object.prototype.hasOwnProperty.call(e,l)&&Object.prototype.hasOwnProperty.call(i.argv,l)&&(Array.isArray(e[l])||Array.isArray(i.argv[l])))e[l]=[].concat(e[l],i.argv[l]);else e[l]=i.argv[l]}})}}isDefaulted(e,t){let{default:n}=e.getOptions();return Object.prototype.hasOwnProperty.call(n,t)||Object.prototype.hasOwnProperty.call(n,this.shim.Parser.camelCase(t))}isInConfigs(e,t){let{configObjects:n}=e.getOptions();return n.some((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=Wn.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(cr(t))return t(e,!0);else if(!zl(t))Object.keys(t).forEach((n)=>{e.option(n,t[n])});return}extractDesc({describe:e,description:t,desc:n}){for(let s of[e,t,n]){if(typeof s==="string"||s===!1)return s;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 Gl(e,t,n,s){return new Yl(e,t,n,s)}function zl(e){return typeof e==="object"&&!!e.builder&&typeof e.handler==="function"}function Ym(e){return e.every((t)=>typeof t==="string")}function cr(e){return typeof e==="function"}function Gm(e){return typeof e==="object"}function Xm(e){return typeof e==="object"&&!Array.isArray(e)}function Ht(e={},t=()=>!0){let n={};return jn(e).forEach((s)=>{if(t(s,e[s]))n[s]=e[s]}),n}function zt(e){if(typeof process>"u")return;[process.stdout,process.stderr].forEach((t)=>{let n=t;if(n._handle&&n.isTTY&&typeof n._handle.setBlocking==="function")n._handle.setBlocking(e)})}function Vm(e){return typeof e==="boolean"}function Zl(e,t){let n=t.y18n.__,s={},o=[];s.failFn=function(v){o.push(v)};let a=null,r=null,i=!0;s.showHelpOnFail=function(v=!0,N){let[H,O]=typeof v==="string"?[!0,v]:[v,N];if(e.getInternalMethods().isGlobalContext())r=O;return a=O,i=H,s};let c=!1;s.fail=function(v,N){let H=e.getInternalMethods().getLoggerInstance();if(o.length)for(let O=o.length-1;O>=0;--O){let j=o[O];if(Vm(j)){if(N)throw N;else if(v)throw Error(v)}else j(v,N,s)}else{if(e.getExitProcess())zt(!0);if(!c){if(c=!0,i)e.showHelp("error"),H.error();if(v||N)H.error(v||N);let O=a||r;if(O){if(v||N)H.error("");H.error(O)}}if(N=N||new $e(v),e.getExitProcess())return e.exit(1);else if(e.getInternalMethods().hasParseCallback())return e.exit(1,N);else throw N}};let l=[],u=!1;s.usage=(L,v)=>{if(L===null)return u=!0,l=[],s;return u=!1,l.push([L,v||""]),s},s.getUsage=()=>l,s.getUsageDisabled=()=>u,s.getPositionalGroupName=()=>n("Positionals:");let d=[];s.example=(L,v)=>{d.push([L,v||""])};let f=[];s.command=function(v,N,H,O,j=!1){if(H)f=f.map((z)=>(z[2]=!1,z));f.push([v,N||"",H,O,j])},s.getCommands=()=>f;let p={};s.describe=function(v,N){if(Array.isArray(v))v.forEach((H)=>{s.describe(H,N)});else if(typeof v==="object")Object.keys(v).forEach((H)=>{s.describe(H,v[H])});else p[v]=N},s.getDescriptions=()=>p;let g=[];s.epilog=(L)=>{g.push(L)};let h=!1,b;s.wrap=(L)=>{h=!0,b=L},s.getWrap=()=>{if(t.getEnv("YARGS_DISABLE_WRAP"))return null;if(!h)b=S(),h=!0;return b};let m="__yargsString__:";s.deferY18nLookup=(L)=>m+L,s.help=function(){if(k)return k;D();let v=e.customScriptName?e.$0:t.path.basename(e.$0),N=e.getDemandedOptions(),H=e.getDemandedCommands(),O=e.getDeprecatedOptions(),j=e.getGroups(),z=e.getOptions(),M=[];M=M.concat(Object.keys(p)),M=M.concat(Object.keys(N)),M=M.concat(Object.keys(H)),M=M.concat(Object.keys(z.default)),M=M.filter(A),M=Object.keys(M.reduce((K,re)=>{if(re!=="_")K[re]=!0;return K},{}));let ce=s.getWrap(),te=t.cliui({width:ce,wrap:!!ce});if(!u){if(l.length)l.forEach((K)=>{if(te.div({text:`${K[0].replace(/\$0/g,v)}`}),K[1])te.div({text:`${K[1]}`,padding:[1,0,0,0]})}),te.div();else if(f.length){let K=null;if(H._)K=`${v} <${n("command")}>
|
|
15
|
+
`;else K=`${v} [${n("command")}]
|
|
16
|
+
`;te.div(`${K}`)}}if(f.length>1||f.length===1&&!f[0][2]){te.div(n("Commands:"));let K=e.getInternalMethods().getContext(),re=K.commands.length?`${K.commands.join(" ")} `:"";if(e.getInternalMethods().getParserConfiguration()["sort-commands"]===!0)f=f.sort((B,pe)=>B[0].localeCompare(pe[0]));let G=v?`${v} `:"";f.forEach((B)=>{let pe=`${G}${re}${B[0].replace(/^\$0 ?/,"")}`;te.span({text:pe,padding:[0,2,0,2],width:w(f,ce,`${v}${re}`)+4},{text:B[1]});let we=[];if(B[2])we.push(`[${n("default")}]`);if(B[3]&&B[3].length)we.push(`[${n("aliases:")} ${B[3].join(", ")}]`);if(B[4])if(typeof B[4]==="string")we.push(`[${n("deprecated: %s",B[4])}]`);else we.push(`[${n("deprecated")}]`);if(we.length)te.div({text:we.join(" "),padding:[0,0,0,2],align:"right"});else te.div()}),te.div()}let q=(Object.keys(z.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);M=M.filter((K)=>!e.parsed.newAliases[K]&&q.every((re)=>(z.alias[re]||[]).indexOf(K)===-1));let oe=n("Options:");if(!j[oe])j[oe]=[];E(M,z.alias,j,oe);let U=(K)=>/^--/.test(lr(K)),de=Object.keys(j).filter((K)=>j[K].length>0).map((K)=>{let re=j[K].filter(A).map((G)=>{if(q.includes(G))return G;for(let B=0,pe;(pe=q[B])!==void 0;B++)if((z.alias[pe]||[]).includes(G))return pe;return G});return{groupName:K,normalizedKeys:re}}).filter(({normalizedKeys:K})=>K.length>0).map(({groupName:K,normalizedKeys:re})=>{let G=re.reduce((B,pe)=>(B[pe]=[pe].concat(z.alias[pe]||[]).map((we)=>{if(K===s.getPositionalGroupName())return we;else return(/^[0-9]$/.test(we)?z.boolean.includes(pe)?"-":"--":we.length>1?"--":"-")+we}).sort((we,Ae)=>U(we)===U(Ae)?0:U(we)?1:-1).join(", "),B),{});return{groupName:K,normalizedKeys:re,switches:G}});if(de.filter(({groupName:K})=>K!==s.getPositionalGroupName()).some(({normalizedKeys:K,switches:re})=>!K.every((G)=>U(re[G]))))de.filter(({groupName:K})=>K!==s.getPositionalGroupName()).forEach(({normalizedKeys:K,switches:re})=>{K.forEach((G)=>{if(U(re[G]))re[G]=Zm(re[G],4)})});if(de.forEach(({groupName:K,normalizedKeys:re,switches:G})=>{te.div(K),re.forEach((B)=>{let pe=G[B],we=p[B]||"",Ae=null;if(we.includes(m))we=n(we.substring(m.length));if(z.boolean.includes(B))Ae=`[${n("boolean")}]`;if(z.count.includes(B))Ae=`[${n("count")}]`;if(z.string.includes(B))Ae=`[${n("string")}]`;if(z.normalize.includes(B))Ae=`[${n("string")}]`;if(z.array.includes(B))Ae=`[${n("array")}]`;if(z.number.includes(B))Ae=`[${n("number")}]`;let qo=(W)=>typeof W==="string"?`[${n("deprecated: %s",W)}]`:`[${n("deprecated")}]`,x=[B in O?qo(O[B]):null,Ae,B in N?`[${n("required")}]`:null,z.choices&&z.choices[B]?`[${n("choices:")} ${s.stringifiedValues(z.choices[B])}]`:null,_(z.default[B],z.defaultDescription[B])].filter(Boolean).join(" ");te.span({text:lr(pe),padding:[0,2,0,2+Vl(pe)],width:w(G,ce)+4},we);let F=e.getInternalMethods().getUsageConfiguration()["hide-types"]===!0;if(x&&!F)te.div({text:x,padding:[0,0,0,2],align:"right"});else te.div()}),te.div()}),d.length)te.div(n("Examples:")),d.forEach((K)=>{K[0]=K[0].replace(/\$0/g,v)}),d.forEach((K)=>{if(K[1]==="")te.div({text:K[0],padding:[0,2,0,2]});else te.div({text:K[0],padding:[0,2,0,2],width:w(d,ce)+4},{text:K[1]})}),te.div();if(g.length>0){let K=g.map((re)=>re.replace(/\$0/g,v)).join(`
|
|
17
|
+
`);te.div(`${K}
|
|
18
|
+
`)}return te.toString().replace(/\s*$/,"")};function w(L,v,N){let H=0;if(!Array.isArray(L))L=Object.values(L).map((O)=>[O]);if(L.forEach((O)=>{H=Math.max(t.stringWidth(N?`${N} ${lr(O[0])}`:lr(O[0]))+Vl(O[0]),H)}),v)H=Math.min(H,parseInt((v*0.5).toString(),10));return H}function D(){let L=e.getDemandedOptions(),v=e.getOptions();(Object.keys(v.alias)||[]).forEach((N)=>{v.alias[N].forEach((H)=>{if(p[H])s.describe(N,p[H]);if(H in L)e.demandOption(N,L[H]);if(v.boolean.includes(H))e.boolean(N);if(v.count.includes(H))e.count(N);if(v.string.includes(H))e.string(N);if(v.normalize.includes(H))e.normalize(N);if(v.array.includes(H))e.array(N);if(v.number.includes(H))e.number(N)})})}let k;s.cacheHelpMessage=function(){k=this.help()},s.clearCachedHelpMessage=function(){k=void 0},s.hasCachedHelpMessage=function(){return!!k};function E(L,v,N,H){let O=[],j=null;return Object.keys(N).forEach((z)=>{O=O.concat(N[z])}),L.forEach((z)=>{if(j=[z].concat(v[z]),!j.some((M)=>O.indexOf(M)!==-1))N[H].push(z)}),O}function A(L){return e.getOptions().hiddenOptions.indexOf(L)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}s.showHelp=(L)=>{let v=e.getInternalMethods().getLoggerInstance();if(!L)L="error";(typeof L==="function"?L:v[L])(s.help())},s.functionDescription=(L)=>["(",L.name?t.Parser.decamelize(L.name,"-"):n("generated-value"),")"].join(""),s.stringifiedValues=function(v,N){let H="",O=N||", ",j=[].concat(v);if(!v||!j.length)return H;return j.forEach((z)=>{if(H.length)H+=O;H+=JSON.stringify(z)}),H};function _(L,v){let N=`[${n("default:")} `;if(L===void 0&&!v)return null;if(v)N+=v;else switch(typeof L){case"string":N+=`"${L}"`;break;case"object":N+=JSON.stringify(L);break;default:N+=L}return`${N}]`}function S(){if(t.process.stdColumns)return Math.min(80,t.process.stdColumns);else return 80}let I=null;s.version=(L)=>{I=L},s.showVersion=(L)=>{let v=e.getInternalMethods().getLoggerInstance();if(!L)L="error";(typeof L==="function"?L:v[L])(I)},s.reset=function(v){return a=null,c=!1,l=[],u=!1,g=[],d=[],f=[],p=Ht(p,(N)=>!v[N]),s};let J=[];return s.freeze=function(){J.push({failMessage:a,failureOutput:c,usages:l,usageDisabled:u,epilogs:g,examples:d,commands:f,descriptions:p})},s.unfreeze=function(v=!1){let N=J.pop();if(!N)return;if(v)p={...N.descriptions,...p},f=[...N.commands,...f],l=[...N.usages,...l],d=[...N.examples,...d],g=[...N.epilogs,...g];else({failMessage:a,failureOutput:c,usages:l,usageDisabled:u,epilogs:g,examples:d,commands:f,descriptions:p}=N)},s}function ui(e){return typeof e==="object"}function Zm(e,t){return ui(e)?{text:e.text,indentation:e.indentation+t}:{text:e,indentation:t}}function Vl(e){return ui(e)?e.indentation:0}function lr(e){return ui(e)?e.text:e}var Ql=`###-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
|
+
`,eu=`#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 tu{constructor(e,t,n,s){var o,a,r;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=(r=((o=this.shim.getEnv("SHELL"))===null||o===void 0?void 0:o.includes("zsh"))||((a=this.shim.getEnv("ZSH_NAME"))===null||a===void 0?void 0:a.includes("zsh")))!==null&&r!==void 0?r:!1}defaultCompletion(e,t,n,s){let o=this.command.getCommandHandlers();for(let r=0,i=e.length;r<i;++r)if(o[e[r]]&&o[e[r]].builder){let c=o[e[r]].builder;if(cr(c)){this.indexAfterLastReset=r+1;let l=this.yargs.getInternalMethods().reset();return c(l,!0),l.argv}}let a=[];this.commandCompletions(a,e,n),this.optionCompletions(a,e,t,n),this.choicesFromOptionsCompletions(a,e,t,n),this.choicesFromPositionalsCompletions(a,e,t,n),s(null,a)}commandCompletions(e,t,n){let s=this.yargs.getInternalMethods().getContext().commands;if(!n.match(/^-/)&&s[s.length-1]!==n&&!this.previousArgHasChoices(t))this.usage.getCommands().forEach((o)=>{let a=qt(o[0]).cmd;if(t.indexOf(a)===-1)if(!this.zshShell)e.push(a);else{let r=o[1]||"";e.push(a.replace(/:/g,"\\:")+":"+r)}})}optionCompletions(e,t,n,s){if((s.match(/^-/)||s===""&&e.length===0)&&!this.previousArgHasChoices(t)){let o=this.yargs.getOptions(),a=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(o.key).forEach((r)=>{let i=!!o.configuration["boolean-negation"]&&o.boolean.includes(r);if(!a.includes(r)&&!o.hiddenOptions.includes(r)&&!this.argsContainKey(t,r,i))this.completeOptionKey(r,e,s,i&&!!o.default[r])})}}choicesFromOptionsCompletions(e,t,n,s){if(this.previousArgHasChoices(t)){let o=this.getPreviousArgChoices(t);if(o&&o.length>0)e.push(...o.map((a)=>a.replace(/:/g,"\\:")))}}choicesFromPositionalsCompletions(e,t,n,s){if(s===""&&e.length>0&&this.previousArgHasChoices(t))return;let o=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],a=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),r=o[n._.length-a-1];if(!r)return;let i=this.yargs.getOptions().choices[r]||[];for(let c of i)if(c.startsWith(s))e.push(c.replace(/:/g,"\\:"))}getPreviousArgChoices(e){if(e.length<1)return;let t=e[e.length-1],n="";if(!t.startsWith("-")&&e.length>1)n=t,t=e[e.length-2];if(!t.startsWith("-"))return;let s=t.replace(/^-+/,""),o=this.yargs.getOptions(),a=[s,...this.yargs.getAliases()[s]||[]],r;for(let i of a)if(Object.prototype.hasOwnProperty.call(o.key,i)&&Array.isArray(o.choices[i])){r=o.choices[i];break}if(r)return r.filter((i)=>!n||i.startsWith(n))}previousArgHasChoices(e){let t=this.getPreviousArgChoices(e);return t!==void 0&&t.length>0}argsContainKey(e,t,n){let s=(o)=>e.indexOf((/^[^0-9]$/.test(o)?"-":"--")+o)!==-1;if(s(t))return!0;if(n&&s(`no-${t}`))return!0;if(this.aliases){for(let o of this.aliases[t])if(s(o))return!0}return!1}completeOptionKey(e,t,n,s){var o,a,r,i;let c=e;if(this.zshShell){let f=this.usage.getDescriptions(),p=(a=(o=this===null||this===void 0?void 0:this.aliases)===null||o===void 0?void 0:o[e])===null||a===void 0?void 0:a.find((b)=>{let m=f[b];return typeof m==="string"&&m.length>0}),g=p?f[p]:void 0,h=(i=(r=f[e])!==null&&r!==void 0?r:g)!==null&&i!==void 0?i:"";c=`${e.replace(/:/g,"\\:")}:${h.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}let l=(f)=>/^--/.test(f),u=(f)=>/^[^0-9]$/.test(f),d=!l(n)&&u(e)?"-":"--";if(t.push(d+c),s)t.push(d+"no-"+c)}customCompletion(e,t,n,s){if(Je(this.customCompletionFunction,null,this.shim),ey(this.customCompletionFunction)){let o=this.customCompletionFunction(n,t);if(De(o))return o.then((a)=>{this.shim.process.nextTick(()=>{s(null,a)})}).catch((a)=>{this.shim.process.nextTick(()=>{s(a,void 0)})});return s(null,o)}else if(ty(this.customCompletionFunction))return this.customCompletionFunction(n,t,(o=s)=>this.defaultCompletion(e,t,n,o),(o)=>{s(null,o)});else return this.customCompletionFunction(n,t,(o)=>{s(null,o)})}getCompletion(e,t){let n=e.length?e[e.length-1]:"",s=this.yargs.parse(e,!0),o=this.customCompletionFunction?(a)=>this.customCompletion(e,a,n,t):(a)=>this.defaultCompletion(e,a,n,t);return De(s)?s.then(o):o(s)}generateCompletionScript(e,t){let n=this.zshShell?eu:Ql,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 nu(e,t,n,s){return new tu(e,t,n,s)}function ey(e){return e.length<3}function ty(e){return e.length>3}function su(e,t){if(e.length===0)return t.length;if(t.length===0)return e.length;let n=[],s;for(s=0;s<=t.length;s++)n[s]=[s];let o;for(o=0;o<=e.length;o++)n[0][o]=o;for(s=1;s<=t.length;s++)for(o=1;o<=e.length;o++)if(t.charAt(s-1)===e.charAt(o-1))n[s][o]=n[s-1][o-1];else if(s>1&&o>1&&t.charAt(s-2)===e.charAt(o-1)&&t.charAt(s-1)===e.charAt(o-2))n[s][o]=n[s-2][o-2]+1;else n[s][o]=Math.min(n[s-1][o-1]+1,Math.min(n[s][o-1]+1,n[s-1][o]+1));return n[t.length][e.length]}var ru=["$0","--","_"];function ou(e,t,n){let s=n.y18n.__,o=n.y18n.__n,a={};a.nonOptionCount=function(d){let f=e.getDemandedCommands(),g=d._.length+(d["--"]?d["--"].length:0)-e.getInternalMethods().getContext().commands.length;if(f._&&(g<f._.min||g>f._.max)){if(g<f._.min)if(f._.minMsg!==void 0)t.fail(f._.minMsg?f._.minMsg.replace(/\$0/g,g.toString()).replace(/\$1/,f._.min.toString()):null);else t.fail(o("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",g,g.toString(),f._.min.toString()));else if(g>f._.max)if(f._.maxMsg!==void 0)t.fail(f._.maxMsg?f._.maxMsg.replace(/\$0/g,g.toString()).replace(/\$1/,f._.max.toString()):null);else t.fail(o("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",g,g.toString(),f._.max.toString()))}},a.positionalCount=function(d,f){if(f<d)t.fail(o("Not enough non-option arguments: got %s, need at least %s","Not enough non-option arguments: got %s, need at least %s",f,f+"",d+""))},a.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 b of Object.keys(p)){let m=p[b];if(m&&g.indexOf(m)<0)g.push(m)}let h=g.length?`
|
|
75
75
|
${g.join(`
|
|
76
|
-
`)}`:"";t.fail(
|
|
77
|
-
${
|
|
78
|
-
`;f.forEach((g)=>{h+=g}),t.fail(h)}};let c={};r.conflicts=function(d,f){if(Y("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((h)=>{r.conflicts(h,d[h])});else{if(e.global(d),!c[d])c[d]=[];if(Array.isArray(f))f.forEach((h)=>r.conflicts(d,h));else c[d].push(f)}},r.getConflicting=()=>c,r.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(c[f])c[f].forEach((h)=>{if(h&&d[f]!==void 0&&d[h]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})}),e.getInternalMethods().getParserConfiguration()["strip-dashed"])Object.keys(c).forEach((f)=>{c[f].forEach((h)=>{if(h&&d[n.Parser.camelCase(f)]!==void 0&&d[n.Parser.camelCase(h)]!==void 0)t.fail(o("Arguments %s and %s are mutually exclusive",f,h))})})},r.recommendCommands=function(d,f){f=f.sort((m,w)=>w.length-m.length);let g=null,p=1/0;for(let m=0,w;(w=f[m])!==void 0;m++){let b=nl(d,w);if(b<=3&&b<p)p=b,g=w}if(g)t.fail(o("Did you mean %s?",g))},r.reset=function(d){return i=Mt(i,(f)=>!d[f]),c=Mt(c,(f)=>!d[f]),r};let l=[];return r.freeze=function(){l.push({implied:i,conflicting:c})},r.unfreeze=function(){let d=l.pop();Ue(d,void 0,n),{implied:i,conflicting:c}=d},r}var Mr=[],es;function ts(e,t,n,o){es=o;let s={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return s;let r=/\.json|\..*rc$/.test(e.extends),i=null;if(!r)try{i=import.meta.resolve(e.extends)}catch(a){return e}else i=Vh(t,e.extends);Yh(i),Mr.push(i),s=r?JSON.parse(es.readFileSync(i,"utf8")):o.require(e.extends),delete e.extends,s=ts(s,es.path.dirname(i),n,es)}return Mr=[],n?rl(s,e):Object.assign({},s,e)}function Yh(e){if(Mr.indexOf(e)>-1)throw new $e(`Circular extended configurations: '${e}'.`)}function Vh(e,t){return es.path.resolve(e,t)}function rl(e,t){let n={};function o(s){return s&&typeof s==="object"&&!Array.isArray(s)}Object.assign(n,e);for(let s of Object.keys(t))if(o(t[s])&&o(n[s]))n[s]=rl(e[s],t[s]);else n[s]=t[s];return n}var V=function(e,t,n,o,s){if(o==="m")throw TypeError("Private method is not writable");if(o==="a"&&!s)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return o==="a"?s.call(e,n):s?s.value=n:t.set(e,n),n},y=function(e,t,n,o){if(n==="a"&&!o)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?o:n==="a"?o.call(e):o?o.value:t.get(e)},Ce,rn,ns,Je,Ve,zs,Bt,an,Xs,st,Gs,ot,mt,Ze,rt,Ys,cn,Pe,ee,Vs,Zs,Qe,ln,Tn,un,jt,Qs,ie,dn,fn,pn,ue,eo,yt,Ee;function _l(e){return(t=[],n=e.process.cwd(),o)=>{let s=new $l(t,n,o,e);return Object.defineProperty(s,"argv",{get:()=>s.parse(),enumerable:!0}),s.help(),s.version(),s}}var il=Symbol("copyDoubleDash"),al=Symbol("copyDoubleDash"),Nr=Symbol("deleteFromParserHintObject"),cl=Symbol("emitWarning"),ll=Symbol("freeze"),ul=Symbol("getDollarZero"),hn=Symbol("getParserConfiguration"),dl=Symbol("getUsageConfiguration"),Br=Symbol("guessLocale"),fl=Symbol("guessVersion"),pl=Symbol("parsePositionalNumbers"),jr=Symbol("pkgUp"),Wt=Symbol("populateParserHintArray"),Rn=Symbol("populateParserHintSingleValueDictionary"),Wr=Symbol("populateParserHintArrayDictionary"),Ur=Symbol("populateParserHintDictionary"),Jr=Symbol("sanitizeKey"),Kr=Symbol("setKey"),qr=Symbol("unfreeze"),hl=Symbol("validateAsync"),gl=Symbol("getCommandInstance"),ml=Symbol("getContext"),yl=Symbol("getHasOutput"),wl=Symbol("getLoggerInstance"),bl=Symbol("getParseContext"),Dl=Symbol("getUsageInstance"),kl=Symbol("getValidationInstance"),to=Symbol("hasParseCallback"),xl=Symbol("isGlobalContext"),gn=Symbol("postProcess"),Sl=Symbol("rebase"),Hr=Symbol("reset"),ss=Symbol("runYargsParserAndExecuteCommands"),zr=Symbol("runValidation"),El=Symbol("setHasOutput"),mn=Symbol("kTrackManuallySetKeys"),Zh="en_US";class $l{constructor(e=[],t,n,o){this.customScriptName=!1,this.parsed=!1,Ce.set(this,void 0),rn.set(this,void 0),ns.set(this,{commands:[],fullCommands:[]}),Je.set(this,null),Ve.set(this,null),zs.set(this,"show-hidden"),Bt.set(this,null),an.set(this,!0),Xs.set(this,{}),st.set(this,!0),Gs.set(this,[]),ot.set(this,void 0),mt.set(this,{}),Ze.set(this,!1),rt.set(this,null),Ys.set(this,!0),cn.set(this,void 0),Pe.set(this,""),ee.set(this,void 0),Vs.set(this,void 0),Zs.set(this,{}),Qe.set(this,null),ln.set(this,null),Tn.set(this,{}),un.set(this,{}),jt.set(this,void 0),Qs.set(this,!1),ie.set(this,void 0),dn.set(this,!1),fn.set(this,!1),pn.set(this,!1),ue.set(this,void 0),eo.set(this,{}),yt.set(this,null),Ee.set(this,void 0),V(this,ie,o,"f"),V(this,jt,e,"f"),V(this,rn,t,"f"),V(this,Vs,n,"f"),V(this,ot,new vr(this),"f"),this.$0=this[ul](),this[Hr](),V(this,Ce,y(this,Ce,"f"),"f"),V(this,ue,y(this,ue,"f"),"f"),V(this,Ee,y(this,Ee,"f"),"f"),V(this,ee,y(this,ee,"f"),"f"),y(this,ee,"f").showHiddenOpt=y(this,zs,"f"),V(this,cn,this[al](),"f"),y(this,ie,"f").y18n.setLocale(Zh)}addHelpOpt(e,t){if(Y("[string|boolean] [string]",[e,t],arguments.length),y(this,rt,"f"))this[Nr](y(this,rt,"f")),V(this,rt,null,"f");if(e===!1&&t===void 0)return this;return V(this,rt,typeof e==="string"?e:"help","f"),this.boolean(y(this,rt,"f")),this.describe(y(this,rt,"f"),t||y(this,ue,"f").deferY18nLookup("Show help")),this}help(e,t){return this.addHelpOpt(e,t)}addShowHiddenOpt(e,t){if(Y("[string|boolean] [string]",[e,t],arguments.length),e===!1&&t===void 0)return this;let n=typeof e==="string"?e:y(this,zs,"f");return this.boolean(n),this.describe(n,t||y(this,ue,"f").deferY18nLookup("Show hidden options")),y(this,ee,"f").showHiddenOpt=n,this}showHidden(e,t){return this.addShowHiddenOpt(e,t)}alias(e,t){return Y("<object|string|array> [string|array]",[e,t],arguments.length),this[Wr](this.alias.bind(this),"alias",e,t),this}array(e){return Y("<array|string>",[e],arguments.length),this[Wt]("array",e),this[mn](e),this}boolean(e){return Y("<array|string>",[e],arguments.length),this[Wt]("boolean",e),this[mn](e),this}check(e,t){return Y("<function> [boolean]",[e,t],arguments.length),this.middleware((n,o)=>on(()=>e(n,o.getOptions()),(s)=>{if(!s)y(this,ue,"f").fail(y(this,ie,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof s==="string"||s instanceof Error)y(this,ue,"f").fail(s.toString(),s);return n},(s)=>(y(this,ue,"f").fail(s.message?s.message:s.toString(),s),n)),!1,t),this}choices(e,t){return Y("<object|string|array> [string|array]",[e,t],arguments.length),this[Wr](this.choices.bind(this),"choices",e,t),this}coerce(e,t){if(Y("<object|string|array> [function]",[e,t],arguments.length),Array.isArray(e)){if(!t)throw new $e("coerce callback must be provided");for(let o of e)this.coerce(o,t);return this}else if(typeof e==="object"){for(let o of Object.keys(e))this.coerce(o,e[o]);return this}if(!t)throw new $e("coerce callback must be provided");let n=e;return y(this,ee,"f").key[n]=!0,y(this,ot,"f").addCoerceMiddleware((o,s)=>{var r;let i=(r=s.getAliases()[n])!==null&&r!==void 0?r:[],a=[n,...i].filter((c)=>Object.prototype.hasOwnProperty.call(o,c));if(a.length===0)return o;return on(()=>t(o[a[0]]),(c)=>(a.forEach((l)=>{o[l]=c}),o),(c)=>{throw new $e(c.message)})},n),this}conflicts(e,t){return Y("<string|object> [string|array]",[e,t],arguments.length),y(this,Ee,"f").conflicts(e,t),this}config(e="config",t,n){if(Y("[object|string] [string|function] [function]",[e,t,n],arguments.length),typeof e==="object"&&!Array.isArray(e))return e=ts(e,y(this,rn,"f"),this[hn]()["deep-merge-config"]||!1,y(this,ie,"f")),y(this,ee,"f").configObjects=(y(this,ee,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||y(this,ue,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((o)=>{y(this,ee,"f").config[o]=n||!0}),this}completion(e,t,n){if(Y("[string] [string|boolean|function] [function]",[e,t,n],arguments.length),typeof t==="function")n=t,t=void 0;if(V(this,Ve,e||y(this,Ve,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(y(this,Ve,"f"),t),n)y(this,Je,"f").registerFunction(n);return this}command(e,t,n,o,s,r){return Y("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,o,s,r],arguments.length),y(this,Ce,"f").addHandler(e,t,n,o,s,r),this}commands(e,t,n,o,s,r){return this.command(e,t,n,o,s,r)}commandDir(e,t){Y("<string> [object]",[e,t],arguments.length);let n=y(this,Vs,"f")||y(this,ie,"f").require;return y(this,Ce,"f").addDirectory(e,n,y(this,ie,"f").getCallerFile(),t),this}count(e){return Y("<array|string>",[e],arguments.length),this[Wt]("count",e),this[mn](e),this}default(e,t,n){if(Y("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)Pr(e,y(this,ie,"f")),y(this,ee,"f").defaultDescription[e]=n;if(typeof t==="function"){if(Pr(e,y(this,ie,"f")),!y(this,ee,"f").defaultDescription[e])y(this,ee,"f").defaultDescription[e]=y(this,ue,"f").functionDescription(t);t=t.call()}return this[Rn](this.default.bind(this),"default",e,t),this}defaults(e,t,n){return this.default(e,t,n)}demandCommand(e=1,t,n,o){if(Y("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,t,n,o],arguments.length),typeof t!=="number")n=t,t=1/0;return this.global("_",!1),y(this,ee,"f").demandedCommands._={min:e,max:t,minMsg:n,maxMsg:o},this}demand(e,t,n){if(Array.isArray(t))t.forEach((o)=>{Ue(n,!0,y(this,ie,"f")),this.demandOption(o,n)}),t=1/0;else if(typeof t!=="number")n=t,t=1/0;if(typeof e==="number")Ue(n,!0,y(this,ie,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((o)=>{Ue(n,!0,y(this,ie,"f")),this.demandOption(o,n)});else if(typeof n==="string")this.demandOption(e,n);else if(n===!0||typeof n>"u")this.demandOption(e);return this}demandOption(e,t){return Y("<object|string|array> [string]",[e,t],arguments.length),this[Rn](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return Y("<string> [string|boolean]",[e,t],arguments.length),y(this,ee,"f").deprecatedOptions[e]=t,this}describe(e,t){return Y("<object|string|array> [string]",[e,t],arguments.length),this[Kr](e,!0),y(this,ue,"f").describe(e,t),this}detectLocale(e){return Y("<boolean>",[e],arguments.length),V(this,an,e,"f"),this}env(e){if(Y("[string|boolean]",[e],arguments.length),e===!1)delete y(this,ee,"f").envPrefix;else y(this,ee,"f").envPrefix=e||"";return this}epilogue(e){return Y("<string>",[e],arguments.length),y(this,ue,"f").epilog(e),this}epilog(e){return this.epilogue(e)}example(e,t){if(Y("<string|array> [string]",[e,t],arguments.length),Array.isArray(e))e.forEach((n)=>this.example(...n));else y(this,ue,"f").example(e,t);return this}exit(e,t){if(V(this,Ze,!0,"f"),V(this,Bt,t,"f"),y(this,st,"f"))y(this,ie,"f").process.exit(e)}exitProcess(e=!0){return Y("[boolean]",[e],arguments.length),V(this,st,e,"f"),this}fail(e){if(Y("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new $e("Invalid first argument. Expected function or boolean 'false'");return y(this,ue,"f").failFn(e),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(e,t){if(Y("<array> [function]",[e,t],arguments.length),!t)return new Promise((n,o)=>{y(this,Je,"f").getCompletion(e,(s,r)=>{if(s)o(s);else n(r)})});else return y(this,Je,"f").getCompletion(e,t)}getDemandedOptions(){return Y([],0),y(this,ee,"f").demandedOptions}getDemandedCommands(){return Y([],0),y(this,ee,"f").demandedCommands}getDeprecatedOptions(){return Y([],0),y(this,ee,"f").deprecatedOptions}getDetectLocale(){return y(this,an,"f")}getExitProcess(){return y(this,st,"f")}getGroups(){return Object.assign({},y(this,mt,"f"),y(this,un,"f"))}getHelp(){if(V(this,Ze,!0,"f"),!y(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[ss](y(this,jt,"f"),void 0,void 0,0,!0);if(be(t))return t.then(()=>y(this,ue,"f").help())}let e=y(this,Ce,"f").runDefaultBuilderOn(this);if(be(e))return e.then(()=>y(this,ue,"f").help())}return Promise.resolve(y(this,ue,"f").help())}getOptions(){return y(this,ee,"f")}getStrict(){return y(this,dn,"f")}getStrictCommands(){return y(this,fn,"f")}getStrictOptions(){return y(this,pn,"f")}global(e,t){if(Y("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)y(this,ee,"f").local=y(this,ee,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!y(this,ee,"f").local.includes(n))y(this,ee,"f").local.push(n)});return this}group(e,t){Y("<string|array> <string>",[e,t],arguments.length);let n=y(this,un,"f")[t]||y(this,mt,"f")[t];if(y(this,un,"f")[t])delete y(this,un,"f")[t];let o={};return y(this,mt,"f")[t]=(n||[]).concat(e).filter((s)=>{if(o[s])return!1;return o[s]=!0}),this}hide(e){return Y("<string>",[e],arguments.length),y(this,ee,"f").hiddenOptions.push(e),this}implies(e,t){return Y("<string|object> [number|string|array]",[e,t],arguments.length),y(this,Ee,"f").implies(e,t),this}locale(e){if(Y("[string]",[e],arguments.length),e===void 0)return this[Br](),y(this,ie,"f").y18n.getLocale();return V(this,an,!1,"f"),y(this,ie,"f").y18n.setLocale(e),this}middleware(e,t,n){return y(this,ot,"f").addMiddleware(e,!!t,n)}nargs(e,t){return Y("<string|object|array> [number]",[e,t],arguments.length),this[Rn](this.nargs.bind(this),"narg",e,t),this}normalize(e){return Y("<array|string>",[e],arguments.length),this[Wt]("normalize",e),this}number(e){return Y("<array|string>",[e],arguments.length),this[Wt]("number",e),this[mn](e),this}option(e,t){if(Y("<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[mn](e),y(this,yt,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[cl](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
|
|
79
|
-
`),void 0,"versionWarning");if(y(this,ee,"f").key[e]=!0,t.alias)this.alias(e,t.alias);let n=t.deprecate||t.deprecated;if(n)this.deprecateOption(e,n);let
|
|
80
|
-
`,"f");
|
|
81
|
-
`,"f");
|
|
82
|
-
`)t[
|
|
83
|
-
`?/^ {0,3}(?:(`{3,})[^`\n]*|(~{3,})[^\n]*)(?=\n|$)/.exec(e.slice(
|
|
84
|
-
{0,3}${
|
|
85
|
-
|$)`,"g");c.lastIndex=
|
|
86
|
-
`&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(c)))break;if(e[c]!=="`"){c++;continue}let u=0;while(e[c+u]==="`")u++;if(u===
|
|
87
|
-
`,{mode:384}),process.platform!=="win32")
|
|
88
|
-
`);
|
|
89
|
-
`)}function
|
|
90
|
-
`)){let
|
|
91
|
-
`+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let
|
|
76
|
+
`)}`:"";t.fail(o("Missing required argument: %s","Missing required arguments: %s",Object.keys(p).length,Object.keys(p).join(", ")+h))}},a.unknownArguments=function(d,f,p,g,h=!0){var b;let m=e.getInternalMethods().getCommandInstance().getCommands(),w=[],D=e.getInternalMethods().getContext();if(Object.keys(d).forEach((k)=>{if(!ru.includes(k)&&!Object.prototype.hasOwnProperty.call(p,k)&&!Object.prototype.hasOwnProperty.call(e.getInternalMethods().getParseContext(),k)&&!a.isValidAndSomeAliasIsNotNew(k,f))w.push(k)}),h&&(D.commands.length>0||m.length>0||g))d._.slice(D.commands.length).forEach((k)=>{if(!m.includes(""+k))w.push(""+k)});if(h){let E=((b=e.getDemandedCommands()._)===null||b===void 0?void 0:b.max)||0,A=D.commands.length+E;if(A<d._.length)d._.slice(A).forEach((_)=>{if(_=String(_),!D.commands.includes(_)&&!w.includes(_))w.push(_)})}if(w.length)t.fail(o("Unknown argument: %s","Unknown arguments: %s",w.length,w.map((k)=>k.trim()?k:`"${k}"`).join(", ")))},a.unknownCommands=function(d){let f=e.getInternalMethods().getCommandInstance().getCommands(),p=[],g=e.getInternalMethods().getContext();if(g.commands.length>0||f.length>0)d._.slice(g.commands.length).forEach((h)=>{if(!f.includes(""+h))p.push(""+h)});if(p.length>0)return t.fail(o("Unknown command: %s","Unknown commands: %s",p.length,p.join(", "))),!0;else return!1},a.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])},a.limitedChoices=function(d){let f=e.getOptions(),p={};if(!Object.keys(f.choices).length)return;Object.keys(d).forEach((b)=>{if(ru.indexOf(b)===-1&&Object.prototype.hasOwnProperty.call(f.choices,b))[].concat(d[b]).forEach((m)=>{if(f.choices[b].indexOf(m)===-1&&m!==void 0)p[b]=(p[b]||[]).concat(m)})});let g=Object.keys(p);if(!g.length)return;let h=s("Invalid values:");g.forEach((b)=>{h+=`
|
|
77
|
+
${s("Argument: %s, Given: %s, Choices: %s",b,t.stringifiedValues(p[b]),t.stringifiedValues(f.choices[b]))}`}),t.fail(h)};let r={};a.implies=function(d,f){if(V("<string|object> [array|number|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((p)=>{a.implies(p,d[p])});else{if(e.global(d),!r[d])r[d]=[];if(Array.isArray(f))f.forEach((p)=>a.implies(d,p));else Je(f,void 0,n),r[d].push(f)}},a.getImplied=function(){return r};function i(u,d){let f=Number(d);if(d=isNaN(f)?d:f,typeof d==="number")d=u._.length>=d;else if(d.match(/^--no-.+/))d=d.match(/^--no-(.+)/)[1],d=!Object.prototype.hasOwnProperty.call(u,d);else d=Object.prototype.hasOwnProperty.call(u,d);return d}a.implications=function(d){let f=[];if(Object.keys(r).forEach((p)=>{let g=p;(r[p]||[]).forEach((h)=>{let b=g,m=h;if(b=i(d,b),h=i(d,h),b&&!h)f.push(` ${g} -> ${m}`)})}),f.length){let p=`${s("Implications failed:")}
|
|
78
|
+
`;f.forEach((g)=>{p+=g}),t.fail(p)}};let c={};a.conflicts=function(d,f){if(V("<string|object> [array|string]",[d,f],arguments.length),typeof d==="object")Object.keys(d).forEach((p)=>{a.conflicts(p,d[p])});else{if(e.global(d),!c[d])c[d]=[];if(Array.isArray(f))f.forEach((p)=>a.conflicts(d,p));else c[d].push(f)}},a.getConflicting=()=>c,a.conflicting=function(d){if(Object.keys(d).forEach((f)=>{if(c[f])c[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(c).forEach((f)=>{c[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))})})},a.recommendCommands=function(d,f){f=f.sort((b,m)=>m.length-b.length);let g=null,h=1/0;for(let b=0,m;(m=f[b])!==void 0;b++){let w=su(d,m);if(w<=3&&w<h)h=w,g=m}if(g)t.fail(s("Did you mean %s?",g))},a.reset=function(d){return r=Ht(r,(f)=>!d[f]),c=Ht(c,(f)=>!d[f]),a};let l=[];return a.freeze=function(){l.push({implied:r,conflicting:c})},a.unfreeze=function(){let d=l.pop();Je(d,void 0,n),{implied:r,conflicting:c}=d},a}var di=[],hs;function gs(e,t,n,s){hs=s;let o={};if(Object.prototype.hasOwnProperty.call(e,"extends")){if(typeof e.extends!=="string")return o;let a=/\.json|\..*rc$/.test(e.extends),r=null;if(!a)try{r=import.meta.resolve(e.extends)}catch(i){return e}else r=sy(t,e.extends);ny(r),di.push(r),o=a?JSON.parse(hs.readFileSync(r,"utf8")):s.require(e.extends),delete e.extends,o=gs(o,hs.path.dirname(r),n,hs)}return di=[],n?iu(o,e):Object.assign({},o,e)}function ny(e){if(di.indexOf(e)>-1)throw new $e(`Circular extended configurations: '${e}'.`)}function sy(e,t){return hs.path.resolve(e,t)}function iu(e,t){let n={};function s(o){return o&&typeof o==="object"&&!Array.isArray(o)}Object.assign(n,e);for(let o of Object.keys(t))if(s(t[o])&&s(n[o]))n[o]=iu(e[o],t[o]);else n[o]=t[o];return n}var Z=function(e,t,n,s,o){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!o)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!o:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?o.call(e,n):o?o.value=n:t.set(e,n),n},y=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,gn,ms,He,Qe,ur,Yt,mn,dr,it,fr,at,St,et,ct,pr,yn,ve,ee,hr,gr,tt,bn,Jn,wn,Gt,mr,ie,Dn,kn,xn,ue,yr,_t,_e;function $u(e){return(t=[],n=e.process.cwd(),s)=>{let o=new Cu(t,n,s,e);return Object.defineProperty(o,"argv",{get:()=>o.parse(),enumerable:!0}),o.help(),o.version(),o}}var au=Symbol("copyDoubleDash"),cu=Symbol("copyDoubleDash"),fi=Symbol("deleteFromParserHintObject"),lu=Symbol("emitWarning"),uu=Symbol("freeze"),du=Symbol("getDollarZero"),Sn=Symbol("getParserConfiguration"),fu=Symbol("getUsageConfiguration"),pi=Symbol("guessLocale"),pu=Symbol("guessVersion"),hu=Symbol("parsePositionalNumbers"),hi=Symbol("pkgUp"),Xt=Symbol("populateParserHintArray"),Un=Symbol("populateParserHintSingleValueDictionary"),gi=Symbol("populateParserHintArrayDictionary"),mi=Symbol("populateParserHintDictionary"),yi=Symbol("sanitizeKey"),bi=Symbol("setKey"),wi=Symbol("unfreeze"),gu=Symbol("validateAsync"),mu=Symbol("getCommandInstance"),yu=Symbol("getContext"),bu=Symbol("getHasOutput"),wu=Symbol("getLoggerInstance"),Du=Symbol("getParseContext"),ku=Symbol("getUsageInstance"),xu=Symbol("getValidationInstance"),br=Symbol("hasParseCallback"),Su=Symbol("isGlobalContext"),_n=Symbol("postProcess"),_u=Symbol("rebase"),Di=Symbol("reset"),ys=Symbol("runYargsParserAndExecuteCommands"),ki=Symbol("runValidation"),Eu=Symbol("setHasOutput"),En=Symbol("kTrackManuallySetKeys"),ry="en_US";class Cu{constructor(e=[],t,n,s){this.customScriptName=!1,this.parsed=!1,Ce.set(this,void 0),gn.set(this,void 0),ms.set(this,{commands:[],fullCommands:[]}),He.set(this,null),Qe.set(this,null),ur.set(this,"show-hidden"),Yt.set(this,null),mn.set(this,!0),dr.set(this,{}),it.set(this,!0),fr.set(this,[]),at.set(this,void 0),St.set(this,{}),et.set(this,!1),ct.set(this,null),pr.set(this,!0),yn.set(this,void 0),ve.set(this,""),ee.set(this,void 0),hr.set(this,void 0),gr.set(this,{}),tt.set(this,null),bn.set(this,null),Jn.set(this,{}),wn.set(this,{}),Gt.set(this,void 0),mr.set(this,!1),ie.set(this,void 0),Dn.set(this,!1),kn.set(this,!1),xn.set(this,!1),ue.set(this,void 0),yr.set(this,{}),_t.set(this,null),_e.set(this,void 0),Z(this,ie,s,"f"),Z(this,Gt,e,"f"),Z(this,gn,t,"f"),Z(this,hr,n,"f"),Z(this,at,new li(this),"f"),this.$0=this[du](),this[Di](),Z(this,Ce,y(this,Ce,"f"),"f"),Z(this,ue,y(this,ue,"f"),"f"),Z(this,_e,y(this,_e,"f"),"f"),Z(this,ee,y(this,ee,"f"),"f"),y(this,ee,"f").showHiddenOpt=y(this,ur,"f"),Z(this,yn,this[cu](),"f"),y(this,ie,"f").y18n.setLocale(ry)}addHelpOpt(e,t){if(V("[string|boolean] [string]",[e,t],arguments.length),y(this,ct,"f"))this[fi](y(this,ct,"f")),Z(this,ct,null,"f");if(e===!1&&t===void 0)return this;return Z(this,ct,typeof e==="string"?e:"help","f"),this.boolean(y(this,ct,"f")),this.describe(y(this,ct,"f"),t||y(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:y(this,ur,"f");return this.boolean(n),this.describe(n,t||y(this,ue,"f").deferY18nLookup("Show hidden options")),y(this,ee,"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[gi](this.alias.bind(this),"alias",e,t),this}array(e){return V("<array|string>",[e],arguments.length),this[Xt]("array",e),this[En](e),this}boolean(e){return V("<array|string>",[e],arguments.length),this[Xt]("boolean",e),this[En](e),this}check(e,t){return V("<function> [boolean]",[e,t],arguments.length),this.middleware((n,s)=>hn(()=>e(n,s.getOptions()),(o)=>{if(!o)y(this,ue,"f").fail(y(this,ie,"f").y18n.__("Argument check failed: %s",e.toString()));else if(typeof o==="string"||o instanceof Error)y(this,ue,"f").fail(o.toString(),o);return n},(o)=>(y(this,ue,"f").fail(o.message?o.message:o.toString(),o),n)),!1,t),this}choices(e,t){return V("<object|string|array> [string|array]",[e,t],arguments.length),this[gi](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 y(this,ee,"f").key[n]=!0,y(this,at,"f").addCoerceMiddleware((s,o)=>{var a;let r=(a=o.getAliases()[n])!==null&&a!==void 0?a:[],i=[n,...r].filter((c)=>Object.prototype.hasOwnProperty.call(s,c));if(i.length===0)return s;return hn(()=>t(s[i[0]]),(c)=>(i.forEach((l)=>{s[l]=c}),s),(c)=>{throw new $e(c.message)})},n),this}conflicts(e,t){return V("<string|object> [string|array]",[e,t],arguments.length),y(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=gs(e,y(this,gn,"f"),this[Sn]()["deep-merge-config"]||!1,y(this,ie,"f")),y(this,ee,"f").configObjects=(y(this,ee,"f").configObjects||[]).concat(e),this;if(typeof t==="function")n=t,t=void 0;return this.describe(e,t||y(this,ue,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((s)=>{y(this,ee,"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||y(this,Qe,"f")||"completion","f"),!t&&t!==!1)t="generate completion script";if(this.command(y(this,Qe,"f"),t),n)y(this,He,"f").registerFunction(n);return this}command(e,t,n,s,o,a){return V("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]",[e,t,n,s,o,a],arguments.length),y(this,Ce,"f").addHandler(e,t,n,s,o,a),this}commands(e,t,n,s,o,a){return this.command(e,t,n,s,o,a)}commandDir(e,t){V("<string> [object]",[e,t],arguments.length);let n=y(this,hr,"f")||y(this,ie,"f").require;return y(this,Ce,"f").addDirectory(e,n,y(this,ie,"f").getCallerFile(),t),this}count(e){return V("<array|string>",[e],arguments.length),this[Xt]("count",e),this[En](e),this}default(e,t,n){if(V("<object|string|array> [*] [string]",[e,t,n],arguments.length),n)ci(e,y(this,ie,"f")),y(this,ee,"f").defaultDescription[e]=n;if(typeof t==="function"){if(ci(e,y(this,ie,"f")),!y(this,ee,"f").defaultDescription[e])y(this,ee,"f").defaultDescription[e]=y(this,ue,"f").functionDescription(t);t=t.call()}return this[Un](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),y(this,ee,"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,y(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,y(this,ie,"f")),this.demandCommand(e,t,n,n);else if(Array.isArray(e))e.forEach((s)=>{Je(n,!0,y(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[Un](this.demandOption.bind(this),"demandedOptions",e,t),this}deprecateOption(e,t){return V("<string> [string|boolean]",[e,t],arguments.length),y(this,ee,"f").deprecatedOptions[e]=t,this}describe(e,t){return V("<object|string|array> [string]",[e,t],arguments.length),this[bi](e,!0),y(this,ue,"f").describe(e,t),this}detectLocale(e){return V("<boolean>",[e],arguments.length),Z(this,mn,e,"f"),this}env(e){if(V("[string|boolean]",[e],arguments.length),e===!1)delete y(this,ee,"f").envPrefix;else y(this,ee,"f").envPrefix=e||"";return this}epilogue(e){return V("<string>",[e],arguments.length),y(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 y(this,ue,"f").example(e,t);return this}exit(e,t){if(Z(this,et,!0,"f"),Z(this,Yt,t,"f"),y(this,it,"f"))y(this,ie,"f").process.exit(e)}exitProcess(e=!0){return V("[boolean]",[e],arguments.length),Z(this,it,e,"f"),this}fail(e){if(V("<function|boolean>",[e],arguments.length),typeof e==="boolean"&&e!==!1)throw new $e("Invalid first argument. Expected function or boolean 'false'");return y(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)=>{y(this,He,"f").getCompletion(e,(o,a)=>{if(o)s(o);else n(a)})});else return y(this,He,"f").getCompletion(e,t)}getDemandedOptions(){return V([],0),y(this,ee,"f").demandedOptions}getDemandedCommands(){return V([],0),y(this,ee,"f").demandedCommands}getDeprecatedOptions(){return V([],0),y(this,ee,"f").deprecatedOptions}getDetectLocale(){return y(this,mn,"f")}getExitProcess(){return y(this,it,"f")}getGroups(){return Object.assign({},y(this,St,"f"),y(this,wn,"f"))}getHelp(){if(Z(this,et,!0,"f"),!y(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let t=this[ys](y(this,Gt,"f"),void 0,void 0,0,!0);if(De(t))return t.then(()=>y(this,ue,"f").help())}let e=y(this,Ce,"f").runDefaultBuilderOn(this);if(De(e))return e.then(()=>y(this,ue,"f").help())}return Promise.resolve(y(this,ue,"f").help())}getOptions(){return y(this,ee,"f")}getStrict(){return y(this,Dn,"f")}getStrictCommands(){return y(this,kn,"f")}getStrictOptions(){return y(this,xn,"f")}global(e,t){if(V("<string|array> [boolean]",[e,t],arguments.length),e=[].concat(e),t!==!1)y(this,ee,"f").local=y(this,ee,"f").local.filter((n)=>e.indexOf(n)===-1);else e.forEach((n)=>{if(!y(this,ee,"f").local.includes(n))y(this,ee,"f").local.push(n)});return this}group(e,t){V("<string|array> <string>",[e,t],arguments.length);let n=y(this,wn,"f")[t]||y(this,St,"f")[t];if(y(this,wn,"f")[t])delete y(this,wn,"f")[t];let s={};return y(this,St,"f")[t]=(n||[]).concat(e).filter((o)=>{if(s[o])return!1;return s[o]=!0}),this}hide(e){return V("<string>",[e],arguments.length),y(this,ee,"f").hiddenOptions.push(e),this}implies(e,t){return V("<string|object> [number|string|array]",[e,t],arguments.length),y(this,_e,"f").implies(e,t),this}locale(e){if(V("[string]",[e],arguments.length),e===void 0)return this[pi](),y(this,ie,"f").y18n.getLocale();return Z(this,mn,!1,"f"),y(this,ie,"f").y18n.setLocale(e),this}middleware(e,t,n){return y(this,at,"f").addMiddleware(e,!!t,n)}nargs(e,t){return V("<string|object|array> [number]",[e,t],arguments.length),this[Un](this.nargs.bind(this),"narg",e,t),this}normalize(e){return V("<array|string>",[e],arguments.length),this[Xt]("normalize",e),this}number(e){return V("<array|string>",[e],arguments.length),this[Xt]("number",e),this[En](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[En](e),y(this,_t,"f")&&(e==="version"||(t===null||t===void 0?void 0:t.alias)==="version"))this[lu](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join(`
|
|
79
|
+
`),void 0,"versionWarning");if(y(this,ee,"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)y(this,ee,"f").defaultDescription[e]=t.defaultDescription;if(t.skipValidation)this.skipValidation(e);let o=t.describe||t.description||t.desc,a=y(this,ue,"f").getDescriptions();if(!Object.prototype.hasOwnProperty.call(a,e)||typeof o==="string")this.describe(e,o);if(t.hidden)this.hide(e);if(t.requiresArg)this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){if(V("[string|array] [function|boolean|object] [function]",[e,t,n],arguments.length),this[uu](),typeof e>"u")e=y(this,Gt,"f");if(typeof t==="object")Z(this,bn,t,"f"),t=n;if(typeof t==="function")Z(this,tt,t,"f"),t=!1;if(!t)Z(this,Gt,e,"f");if(y(this,tt,"f"))Z(this,it,!1,"f");let s=this[ys](e,!!t),o=this.parsed;if(y(this,He,"f").setParsed(this.parsed),De(s))return s.then((a)=>{if(y(this,tt,"f"))y(this,tt,"f").call(this,y(this,Yt,"f"),a,y(this,ve,"f"));return a}).catch((a)=>{if(y(this,tt,"f"))y(this,tt,"f")(a,this.parsed.argv,y(this,ve,"f"));throw a}).finally(()=>{this[wi](),this.parsed=o});else{if(y(this,tt,"f"))y(this,tt,"f").call(this,y(this,Yt,"f"),s,y(this,ve,"f"));this[wi](),this.parsed=o}return s}parseAsync(e,t,n){let s=this.parse(e,t,n);return!De(s)?Promise.resolve(s):s}parseSync(e,t,n){let s=this.parse(e,t,n);if(De(s))throw new $e(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return s}parserConfiguration(e){return V("<object>",[e],arguments.length),Z(this,gr,e,"f"),this}pkgConf(e,t){V("<string> [string]",[e,t],arguments.length);let n=null,s=this[hi](t||y(this,gn,"f"));if(s[e]&&typeof s[e]==="object")n=gs(s[e],t||y(this,gn,"f"),this[Sn]()["deep-merge-config"]||!1,y(this,ie,"f")),y(this,ee,"f").configObjects=(y(this,ee,"f").configObjects||[]).concat(n);return this}positional(e,t){V("<string> <object>",[e,t],arguments.length);let n=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];t=Ht(t,(a,r)=>{if(a==="type"&&!["string","number","boolean"].includes(r))return!1;return n.includes(a)});let s=y(this,ms,"f").fullCommands[y(this,ms,"f").fullCommands.length-1],o=s?y(this,Ce,"f").cmdToParseOptions(s):{array:[],alias:{},default:{},demand:{}};return jn(o).forEach((a)=>{let r=o[a];if(Array.isArray(r)){if(r.indexOf(e)!==-1)t[a]=!0}else if(r[e]&&!(a in t))t[a]=r[e]}),this.group(e,y(this,ue,"f").getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return V("[boolean]",[e],arguments.length),Z(this,mr,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"&&y(this,ee,"f").narg[e])return this;else this[Un](this.requiresArg.bind(this),"narg",e,NaN);return this}showCompletionScript(e,t){return V("[string] [string]",[e,t],arguments.length),e=e||this.$0,y(this,yn,"f").log(y(this,He,"f").generateCompletionScript(e,t||y(this,Qe,"f")||"completion")),this}showHelp(e){if(V("[string|function]",[e],arguments.length),Z(this,et,!0,"f"),!y(this,ue,"f").hasCachedHelpMessage()){if(!this.parsed){let n=this[ys](y(this,Gt,"f"),void 0,void 0,0,!0);if(De(n))return n.then(()=>{y(this,ue,"f").showHelp(e)}),this}let t=y(this,Ce,"f").runDefaultBuilderOn(this);if(De(t))return t.then(()=>{y(this,ue,"f").showHelp(e)}),this}return y(this,ue,"f").showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return V("[boolean|string] [string]",[e,t],arguments.length),y(this,ue,"f").showHelpOnFail(e,t),this}showVersion(e){return V("[string|function]",[e],arguments.length),y(this,ue,"f").showVersion(e),this}skipValidation(e){return V("<array|string>",[e],arguments.length),this[Xt]("skipValidation",e),this}strict(e){return V("[boolean]",[e],arguments.length),Z(this,Dn,e!==!1,"f"),this}strictCommands(e){return V("[boolean]",[e],arguments.length),Z(this,kn,e!==!1,"f"),this}strictOptions(e){return V("[boolean]",[e],arguments.length),Z(this,xn,e!==!1,"f"),this}string(e){return V("<array|string>",[e],arguments.length),this[Xt]("string",e),this[En](e),this}terminalWidth(){return V([],0),y(this,ie,"f").process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return V("<object>",[e],arguments.length),Z(this,mn,!1,"f"),y(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,y(this,ie,"f")),(e||"").match(/^\$0( |$)/))return this.command(e,t,n,s);else throw new $e(".usage() description must start with $0 if being used as alias for .command()");else return y(this,ue,"f").usage(e),this}usageConfiguration(e){return V("<object>",[e],arguments.length),Z(this,yr,e,"f"),this}version(e,t,n){if(V("[boolean|string] [string] [string]",[e,t,n],arguments.length),y(this,_t,"f"))this[fi](y(this,_t,"f")),y(this,ue,"f").version(void 0),Z(this,_t,null,"f");if(arguments.length===0)n=this[pu](),e="version";else if(arguments.length===1){if(e===!1)return this;n=e,e="version"}else if(arguments.length===2)n=t,t=void 0;return Z(this,_t,typeof e==="string"?e:"version","f"),t=t||y(this,ue,"f").deferY18nLookup("Show version number"),y(this,ue,"f").version(n||void 0),this.boolean(y(this,_t,"f")),this.describe(y(this,_t,"f"),t),this}wrap(e){return V("<number|null|undefined>",[e],arguments.length),y(this,ue,"f").wrap(e),this}[(Ce=new WeakMap,gn=new WeakMap,ms=new WeakMap,He=new WeakMap,Qe=new WeakMap,ur=new WeakMap,Yt=new WeakMap,mn=new WeakMap,dr=new WeakMap,it=new WeakMap,fr=new WeakMap,at=new WeakMap,St=new WeakMap,et=new WeakMap,ct=new WeakMap,pr=new WeakMap,yn=new WeakMap,ve=new WeakMap,ee=new WeakMap,hr=new WeakMap,gr=new WeakMap,tt=new WeakMap,bn=new WeakMap,Jn=new WeakMap,wn=new WeakMap,Gt=new WeakMap,mr=new WeakMap,ie=new WeakMap,Dn=new WeakMap,kn=new WeakMap,xn=new WeakMap,ue=new WeakMap,yr=new WeakMap,_t=new WeakMap,_e=new WeakMap,au)](e){if(!e._||!e["--"])return e;e._.push.apply(e._,e["--"]);try{delete e["--"]}catch(t){}return e}[cu](){return{log:(...e)=>{if(!this[br]())console.log(...e);if(Z(this,et,!0,"f"),y(this,ve,"f").length)Z(this,ve,y(this,ve,"f")+`
|
|
80
|
+
`,"f");Z(this,ve,y(this,ve,"f")+e.join(" "),"f")},error:(...e)=>{if(!this[br]())console.error(...e);if(Z(this,et,!0,"f"),y(this,ve,"f").length)Z(this,ve,y(this,ve,"f")+`
|
|
81
|
+
`,"f");Z(this,ve,y(this,ve,"f")+e.join(" "),"f")}}}[fi](e){jn(y(this,ee,"f")).forEach((t)=>{if(((s)=>s==="configObjects")(t))return;let n=y(this,ee,"f")[t];if(Array.isArray(n)){if(n.includes(e))n.splice(n.indexOf(e),1)}else if(typeof n==="object")delete n[e]}),delete y(this,ue,"f").getDescriptions()[e]}[lu](e,t,n){if(!y(this,dr,"f")[n])y(this,ie,"f").process.emitWarning(e,t),y(this,dr,"f")[n]=!0}[uu](){y(this,fr,"f").push({options:y(this,ee,"f"),configObjects:y(this,ee,"f").configObjects.slice(0),exitProcess:y(this,it,"f"),groups:y(this,St,"f"),strict:y(this,Dn,"f"),strictCommands:y(this,kn,"f"),strictOptions:y(this,xn,"f"),completionCommand:y(this,Qe,"f"),output:y(this,ve,"f"),exitError:y(this,Yt,"f"),hasOutput:y(this,et,"f"),parsed:this.parsed,parseFn:y(this,tt,"f"),parseContext:y(this,bn,"f")}),y(this,ue,"f").freeze(),y(this,_e,"f").freeze(),y(this,Ce,"f").freeze(),y(this,at,"f").freeze()}[du](){let e="",t;if(/\b(node|iojs|electron)(\.exe)?$/.test(y(this,ie,"f").process.argv()[0]))t=y(this,ie,"f").process.argv().slice(1,2);else t=y(this,ie,"f").process.argv().slice(0,1);if(e=t.map((n)=>{let s=this[_u](y(this,gn,"f"),n);return n.match(/^(\/|([a-zA-Z]:)?\\)/)&&s.length<n.length?s:n}).join(" ").trim(),y(this,ie,"f").getEnv("_")&&y(this,ie,"f").getProcessArgvBin()===y(this,ie,"f").getEnv("_"))e=y(this,ie,"f").getEnv("_").replace(`${y(this,ie,"f").path.dirname(y(this,ie,"f").process.execPath())}/`,"");return e}[Sn](){return y(this,gr,"f")}[fu](){return y(this,yr,"f")}[pi](){if(!y(this,mn,"f"))return;let e=y(this,ie,"f").getEnv("LC_ALL")||y(this,ie,"f").getEnv("LC_MESSAGES")||y(this,ie,"f").getEnv("LANG")||y(this,ie,"f").getEnv("LANGUAGE")||"en_US";this.locale(e.replace(/[.:].*/,""))}[pu](){return this[hi]().version||"unknown"}[hu](e){let t=e["--"]?e["--"]:e._;for(let n=0,s;(s=t[n])!==void 0;n++)if(y(this,ie,"f").Parser.looksLikeNumber(s)&&Number.isSafeInteger(Math.floor(parseFloat(`${s}`))))t[n]=Number(s);return e}[hi](e){let t=e||"*";if(y(this,Jn,"f")[t])return y(this,Jn,"f")[t];let n={};try{let s=e||y(this,ie,"f").mainFilename;if(y(this,ie,"f").path.extname(s))s=y(this,ie,"f").path.dirname(s);let o=y(this,ie,"f").findUp(s,(a,r)=>{if(r.includes("package.json"))return"package.json";else return});Je(o,void 0,y(this,ie,"f")),n=JSON.parse(y(this,ie,"f").readFileSync(o,"utf8"))}catch(s){}return y(this,Jn,"f")[t]=n||{},y(this,Jn,"f")[t]}[Xt](e,t){t=[].concat(t),t.forEach((n)=>{n=this[yi](n),y(this,ee,"f")[e].push(n)})}[Un](e,t,n,s){this[mi](e,t,n,s,(o,a,r)=>{y(this,ee,"f")[o][a]=r})}[gi](e,t,n,s){this[mi](e,t,n,s,(o,a,r)=>{y(this,ee,"f")[o][a]=(y(this,ee,"f")[o][a]||[]).concat(r)})}[mi](e,t,n,s,o){if(Array.isArray(n))n.forEach((a)=>{e(a,s)});else if(((a)=>typeof a==="object")(n))for(let a of jn(n))e(a,n[a]);else o(t,this[yi](n),s)}[yi](e){if(e==="__proto__")return"___proto___";return e}[bi](e,t){return this[Un](this[bi].bind(this),"key",e,t),this}[wi](){var e,t,n,s,o,a,r,i,c,l,u,d;let f=y(this,fr,"f").pop();Je(f,void 0,y(this,ie,"f"));let p;e=this,t=this,n=this,s=this,o=this,a=this,r=this,i=this,c=this,l=this,u=this,d=this,{options:{set value(g){Z(e,ee,g,"f")}}.value,configObjects:p,exitProcess:{set value(g){Z(t,it,g,"f")}}.value,groups:{set value(g){Z(n,St,g,"f")}}.value,output:{set value(g){Z(s,ve,g,"f")}}.value,exitError:{set value(g){Z(o,Yt,g,"f")}}.value,hasOutput:{set value(g){Z(a,et,g,"f")}}.value,parsed:this.parsed,strict:{set value(g){Z(r,Dn,g,"f")}}.value,strictCommands:{set value(g){Z(i,kn,g,"f")}}.value,strictOptions:{set value(g){Z(c,xn,g,"f")}}.value,completionCommand:{set value(g){Z(l,Qe,g,"f")}}.value,parseFn:{set value(g){Z(u,tt,g,"f")}}.value,parseContext:{set value(g){Z(d,bn,g,"f")}}.value}=f,y(this,ee,"f").configObjects=p,y(this,ue,"f").unfreeze(),y(this,_e,"f").unfreeze(),y(this,Ce,"f").unfreeze(),y(this,at,"f").unfreeze()}[gu](e,t){return hn(t,(n)=>(e(n),n))}getInternalMethods(){return{getCommandInstance:this[mu].bind(this),getContext:this[yu].bind(this),getHasOutput:this[bu].bind(this),getLoggerInstance:this[wu].bind(this),getParseContext:this[Du].bind(this),getParserConfiguration:this[Sn].bind(this),getUsageConfiguration:this[fu].bind(this),getUsageInstance:this[ku].bind(this),getValidationInstance:this[xu].bind(this),hasParseCallback:this[br].bind(this),isGlobalContext:this[Su].bind(this),postProcess:this[_n].bind(this),reset:this[Di].bind(this),runValidation:this[ki].bind(this),runYargsParserAndExecuteCommands:this[ys].bind(this),setHasOutput:this[Eu].bind(this)}}[mu](){return y(this,Ce,"f")}[yu](){return y(this,ms,"f")}[bu](){return y(this,et,"f")}[wu](){return y(this,yn,"f")}[Du](){return y(this,bn,"f")||{}}[ku](){return y(this,ue,"f")}[xu](){return y(this,_e,"f")}[br](){return!!y(this,tt,"f")}[Su](){return y(this,pr,"f")}[_n](e,t,n,s){if(n)return e;if(De(e))return e;if(!t)e=this[au](e);if(this[Sn]()["parse-positional-numbers"]||this[Sn]()["parse-positional-numbers"]===void 0)e=this[hu](e);if(s)e=pn(e,this,y(this,at,"f").getMiddleware(),!1);return e}[Di](e={}){Z(this,ee,y(this,ee,"f")||{},"f");let t={};t.local=y(this,ee,"f").local||[],t.configObjects=y(this,ee,"f").configObjects||[];let n={};t.local.forEach((a)=>{n[a]=!0,(e[a]||[]).forEach((r)=>{n[r]=!0})}),Object.assign(y(this,wn,"f"),Object.keys(y(this,St,"f")).reduce((a,r)=>{let i=y(this,St,"f")[r].filter((c)=>!(c in n));if(i.length>0)a[r]=i;return a},{})),Z(this,St,{},"f");let s=["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"],o=["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"];if(s.forEach((a)=>{t[a]=(y(this,ee,"f")[a]||[]).filter((r)=>!n[r])}),o.forEach((a)=>{t[a]=Ht(y(this,ee,"f")[a],(r)=>!n[r])}),t.envPrefix=y(this,ee,"f").envPrefix,Z(this,ee,t,"f"),Z(this,ue,y(this,ue,"f")?y(this,ue,"f").reset(n):Zl(this,y(this,ie,"f")),"f"),Z(this,_e,y(this,_e,"f")?y(this,_e,"f").reset(n):ou(this,y(this,ue,"f"),y(this,ie,"f")),"f"),Z(this,Ce,y(this,Ce,"f")?y(this,Ce,"f").reset():Gl(y(this,ue,"f"),y(this,_e,"f"),y(this,at,"f"),y(this,ie,"f")),"f"),!y(this,He,"f"))Z(this,He,nu(this,y(this,ue,"f"),y(this,Ce,"f"),y(this,ie,"f")),"f");return y(this,at,"f").reset(),Z(this,Qe,null,"f"),Z(this,ve,"","f"),Z(this,Yt,null,"f"),Z(this,et,!1,"f"),this.parsed=!1,this}[_u](e,t){return y(this,ie,"f").path.relative(e,t)}[ys](e,t,n,s=0,o=!1){var a,r,i,c;let l=!!n||o;e=e||y(this,Gt,"f"),y(this,ee,"f").__=y(this,ie,"f").y18n.__,y(this,ee,"f").configuration=this[Sn]();let u=!!y(this,ee,"f").configuration["populate--"],d=Object.assign({},y(this,ee,"f").configuration,{"populate--":!0}),f=y(this,ie,"f").Parser.detailed(e,Object.assign({},y(this,ee,"f"),{configuration:{"parse-positional-numbers":!1,...d}})),p=Object.assign(f.argv,y(this,bn,"f")),g=void 0,h=f.aliases,b=!1,m=!1;if(Object.keys(p).forEach((w)=>{if(w===y(this,ct,"f")&&p[w])b=!0;else if(w===y(this,_t,"f")&&p[w])m=!0}),p.$0=this.$0,this.parsed=f,s===0)y(this,ue,"f").clearCachedHelpMessage();try{if(this[pi](),t)return this[_n](p,u,!!n,!1);if(y(this,ct,"f")){if([y(this,ct,"f")].concat(h[y(this,ct,"f")]||[]).filter((A)=>A.length>1).includes(""+p._[p._.length-1]))p._.pop(),b=!0}Z(this,pr,!1,"f");let w=y(this,Ce,"f").getCommands(),D=((a=y(this,He,"f"))===null||a===void 0?void 0:a.completionKey)?[(r=y(this,He,"f"))===null||r===void 0?void 0:r.completionKey,...(c=this.getAliases()[(i=y(this,He,"f"))===null||i===void 0?void 0:i.completionKey])!==null&&c!==void 0?c:[]].some((E)=>Object.prototype.hasOwnProperty.call(p,E)):!1,k=b||D||o;if(p._.length){if(w.length){let E;for(let A=s||0,_;p._[A]!==void 0;A++)if(_=String(p._[A]),w.includes(_)&&_!==y(this,Qe,"f")){let S=y(this,Ce,"f").runCommand(_,this,f,A+1,o,b||m||o);return this[_n](S,u,!!n,!1)}else if(!E&&_!==y(this,Qe,"f")){E=_;break}if(!y(this,Ce,"f").hasDefaultCommand()&&y(this,mr,"f")&&E&&!k)y(this,_e,"f").recommendCommands(E,w)}if(y(this,Qe,"f")&&p._.includes(y(this,Qe,"f"))&&!D){if(y(this,it,"f"))zt(!0);this.showCompletionScript(),this.exit(0)}}if(y(this,Ce,"f").hasDefaultCommand()&&!k){let E=y(this,Ce,"f").runCommand(null,this,f,0,o,b||m||o);return this[_n](E,u,!!n,!1)}if(D){if(y(this,it,"f"))zt(!0);e=[].concat(e);let E=e.slice(e.indexOf(`--${y(this,He,"f").completionKey}`)+1);return y(this,He,"f").getCompletion(E,(A,_)=>{if(A)throw new $e(A.message);(_||[]).forEach((S)=>{y(this,yn,"f").log(S)}),this.exit(0)}),this[_n](p,!u,!!n,!1)}if(!y(this,et,"f")){if(b){if(y(this,it,"f"))zt(!0);l=!0,this.showHelp((E)=>{y(this,yn,"f").log(E),this.exit(0)})}else if(m){if(y(this,it,"f"))zt(!0);l=!0,y(this,ue,"f").showVersion("log"),this.exit(0)}}if(!l&&y(this,ee,"f").skipValidation.length>0)l=Object.keys(p).some((E)=>y(this,ee,"f").skipValidation.indexOf(E)>=0&&p[E]===!0);if(!l){if(f.error)throw new $e(f.error.message);if(!D){let E=this[ki](h,{},f.error);if(!n)g=pn(p,this,y(this,at,"f").getMiddleware(),!0);if(g=this[gu](E,g!==null&&g!==void 0?g:p),De(g)&&!n)g=g.then(()=>pn(p,this,y(this,at,"f").getMiddleware(),!1))}}}catch(w){if(w instanceof $e)y(this,ue,"f").fail(w.message,w);else throw w}return this[_n](g!==null&&g!==void 0?g:p,u,!!n,!0)}[ki](e,t,n,s){let o={...this.getDemandedOptions()};return(a)=>{if(n)throw new $e(n.message);y(this,_e,"f").nonOptionCount(a),y(this,_e,"f").requiredArguments(a,o);let r=!1;if(y(this,kn,"f"))r=y(this,_e,"f").unknownCommands(a);if(y(this,Dn,"f")&&!r)y(this,_e,"f").unknownArguments(a,e,t,!!s);else if(y(this,xn,"f"))y(this,_e,"f").unknownArguments(a,e,{},!1,!1);y(this,_e,"f").limitedChoices(a),y(this,_e,"f").implications(a),y(this,_e,"f").conflicting(a)}}[Eu](){Z(this,et,!0,"f")}[En](e){if(typeof e==="string")y(this,ee,"f").key[e]=!0;else for(let t of e)y(this,ee,"f").key[t]=!0}}function Xl(e){return!!e&&typeof e.getInternalMethods==="function"}var oy=$u(ai),Au=oy;var iy=/<https?:\/\/[^\s<>|]+(?:\|[^<>\r\n]*)?>|https?:\/\/[^\t\n\v\f\r <\x00]+/gi,ay=/[\t\n\v\f\r (*_~]/;function cy(e){let t=e.split(""),n=(o,a)=>{for(let r=o;r<a;r++)if(t[r]!==`
|
|
82
|
+
`)t[r]="\x00"},s=0;while(s<e.length){let a=s===0||e[s-1]===`
|
|
83
|
+
`?/^ {0,3}(?:(`{3,})[^`\n]*|(~{3,})[^\n]*)(?=\n|$)/.exec(e.slice(s)):null;if(a){let i=a[1]??a[2],c=new RegExp(`
|
|
84
|
+
{0,3}${i[0]==="`"?"`":"~"}{${i.length},}[ ]*\r?(?=
|
|
85
|
+
|$)`,"g");c.lastIndex=s+a[0].length;let l=c.exec(e),u=l?l.index+l[0].length:e.length;n(s,u),s=u;continue}let r=e[s];if(r==="\\"){s+=2;continue}if(r==="`"){let i=0;while(e[s+i]==="`")i++;let c=s+i,l=-1;while(c<e.length){if(e[c]===`
|
|
86
|
+
`&&/^\n[ \t\r]*(?:\n|$)/.test(e.slice(c)))break;if(e[c]!=="`"){c++;continue}let u=0;while(e[c+u]==="`")u++;if(u===i){l=c+u;break}c+=u}if(l<0){s+=i;continue}n(s,l),s=l;continue}if(r==="["){let i=/^\[(?:\\.|[^\]\\\n])*\]\([^()\s]*\)/.exec(e.slice(s));if(i){n(s,s+i[0].length),s+=i[0].length;continue}}s++}return t.join("")}function ly(e,{markdown:t=!0}={}){let n=t?cy(e):e,s=[];for(let o of n.matchAll(iy)){let a=o[0];if(a.startsWith("<"))continue;let r=o.index??0,i=r>0?n[r-1]:"";if(i&&!ay.test(i))s.push({url:a,side:"before",char:e[r-1]});let c=a.match(/[^\x00-\x7f]|>/);if(c)s.push({url:a,side:"after",char:c[0]})}return s}function ze(e,t=!1,n=console.error,{sides:s=["before","after"],markdown:o=!0}={}){let a=ly(e,{markdown:o}).filter((l)=>s.includes(l.side));if(!a.length)return;let r=a.map((l)=>l.side==="before"?`${JSON.stringify(l.url)} (glued to ${JSON.stringify(l.char)} before it — Slack will NOT make it a link)`:`${JSON.stringify(l.url)} (runs into ${JSON.stringify(l.char)} after it)`),i=a.some((l)=>l.side==="before")?"Put an ASCII space (or a newline) before the URL, ":"",c=`Ambiguous URL boundary: ${r.join(", ")}. ${i}Put the URL on its own line, or wrap it as <url> / <url|label>. Use --allow-url-adjacent to warn only.`;if(!t)throw Error(c);n(`Warning: ${c}`)}import{existsSync as ws,readFileSync as _i,writeFileSync as xi,mkdirSync as Ru,chmodSync as Fu}from"node:fs";import{homedir as uy}from"node:os";import{join as $n,dirname as Ei}from"node:path";function $i(){return process.env.HOME||uy()}function Iu(){return $n($i(),".config","slack-cli","profiles.json")}function wr(){return $n(process.cwd(),".slack-cli","workspace")}function Dr(){return $n($i(),".slack-cli","workspace")}function Ds(){let e=Iu();if(!ws(e))return{profiles:{}};return JSON.parse(_i(e,"utf8"))}function dy(e){let t=Iu();if(Ru(Ei(t),{recursive:!0}),process.platform!=="win32"&&ws(t))Fu(t,384);if(xi(t,JSON.stringify(e,null,2)+`
|
|
87
|
+
`,{mode:384}),process.platform!=="win32")Fu(t,384)}function Kn(e){if(!ws(e))return;return _i(e,"utf8").trim()||void 0}function Tu(e,t){let n=Ei(e);Ru(n,{recursive:!0});let s=$n(n,".gitignore");if(!ws(s))xi(s,`*
|
|
88
|
+
`);xi(e,t+`
|
|
89
|
+
`)}function fy(e){let t={};for(let n of e.split(`
|
|
90
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let a=s.slice(0,o).trim(),r=s.slice(o+1).trim();if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))r=r.slice(1,-1);t[a]=r}return t}function Ou(e){if(!ws(e))return{};try{return fy(_i(e,"utf8"))}catch{return{}}}function Si(e,t){let n=$i(),s=e;while(!0){for(let r of[$n(s,".slack-term",".env.local"),$n(s,".env.local")]){let i=Ou(r);for(let c of t)if(i[c])return i[c]}if(s===n)break;let a=Ei(s);if(a===s)break;s=a}let o=Ou($n(n,".slack-term",".env.local"));for(let a of t)if(o[a])return o[a];return}function Ci(){let e=Ds(),t=Kn(wr()),n=Kn(Dr()),s=t??n;return Object.entries(e.profiles).map(([o,a])=>{let r=bs(e,o);return{name:o,profile:{...a,...r?{cookie:r}:{}},current:o===s}})}function bs(e,t){if(!t)return;let n=e.profiles[t];if(!n)return;if(n.cookie)return n.cookie;if(n.identity)return e.users?.[n.identity]?.cookie;return}function vu(e){let t=Ds();if(!(e in t.profiles))throw Error(`Profile not found: ${e}`);delete t.profiles[e],dy(t)}function Pu(e,t=!1){let n=Ds();if(!(e in n.profiles))throw Error(`Profile not found: ${e}`);if(t)Tu(Dr(),e);else Tu(wr(),e)}function ks(e){let n=Ds().profiles,s=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let o=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(o&&s.length===0)return o;let a=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(a&&s.length>0){let u=Si(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(a!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
|
|
91
|
+
`+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let r=Si(process.cwd(),["SLACK_TOKEN"]);if(r)return r;let i=process.env.SLACK_WORKSPACE;if(i){let u=n[i];if(!u)throw Error(`Workspace "${i}" not found. Available: ${s.join(", ")||"(none)"}`);return u.token}let c=Kn(wr());if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=Kn(Dr());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.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
|
|
101
|
-
`,{mode:384}),process.platform!=="win32")
|
|
102
|
-
`)){let
|
|
103
|
-
`):[];for(let[
|
|
100
|
+
`+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function Ue(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Ai(e){let t=Ds(),n=t.profiles;if(e)return bs(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let o=Si(process.cwd(),["SLACK_COOKIE"]);if(o)return o;let a=process.env.SLACK_WORKSPACE;if(a)return bs(t,a);let r=Kn(wr());if(r)return bs(t,r);let i=Kn(Dr());if(i)return bs(t,i);return}import{existsSync as Hn,readFileSync as xr,writeFileSync as Mu,mkdirSync as Nu,chmodSync as kr}from"node:fs";import{homedir as py}from"node:os";import{join as qn,dirname as Ti}from"node:path";function Oi(){return process.env.HOME||py()}function Bu(){return qn(Oi(),".config","slack-cli","profiles.json")}function Ri(){return qn(process.cwd(),".slack-cli","workspace")}function Ii(){return qn(Oi(),".slack-cli","workspace")}function Yn(){let e=Bu();if(!Hn(e))return{profiles:{}};return JSON.parse(xr(e,"utf8"))}function vi(e){let t=Bu();if(Nu(Ti(t),{recursive:!0}),process.platform!=="win32"&&Hn(t))kr(t,384);if(Mu(t,JSON.stringify(e,null,2)+`
|
|
101
|
+
`,{mode:384}),process.platform!=="win32")kr(t,384)}function zn(e){if(!Hn(e))return;return xr(e,"utf8").trim()||void 0}function hy(e){let t={};for(let n of e.split(`
|
|
102
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let a=s.slice(0,o).trim(),r=s.slice(o+1).trim();if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))r=r.slice(1,-1);t[a]=r}return t}function Lu(e){if(!Hn(e))return{};try{return hy(xr(e,"utf8"))}catch{return{}}}function Fi(e,t){let n=Oi(),s=e;while(!0){for(let r of[qn(s,".slack-term",".env.local"),qn(s,".env.local")]){let i=Lu(r);for(let c of t)if(i[c])return i[c]}if(s===n)break;let a=Ti(s);if(a===s)break;s=a}let o=Lu(qn(n,".slack-term",".env.local"));for(let a of t)if(o[a])return o[a];return}function Pi(e,t){Nu(Ti(e),{recursive:!0});let n=Hn(e)?xr(e,"utf8"):"",s=n?n.split(`
|
|
103
|
+
`):[];for(let[o,a]of Object.entries(t)){let r=s.findIndex((c)=>{let l=c.trim();return l.startsWith(o+"=")||l.startsWith(o+" =")}),i=`${o}=${a}`;if(r!==-1)s[r]=i;else s.push(i)}if(process.platform!=="win32"&&Hn(e))kr(e,384);if(Mu(e,s.join(`
|
|
104
104
|
`).trimEnd()+`
|
|
105
|
-
`,{mode:384}),process.platform!=="win32")
|
|
106
|
-
`+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let
|
|
105
|
+
`,{mode:384}),process.platform!=="win32")kr(e,384)}function Ss(){let e=Yn(),t=zn(Ri()),n=zn(Ii()),s=t??n;return Object.entries(e.profiles).map(([o,a])=>{let r=xs(e,o);return{name:o,profile:{...a,...r?{cookie:r}:{}},current:o===s}})}function Sr(e,t){let n=Yn();if(t.identity&&t.cookie){n.users??={};let s=n.users[t.identity]??{};n.users[t.identity]={...s,cookie:t.cookie};let{cookie:o,...a}=t;n.profiles[e]=a}else n.profiles[e]=t;vi(n)}function Li(e,t){let n=Yn(),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;vi(n)}function ju(e,t,n){let s=Yn();s.users??={},s.users[e]={...s.users[e]??{},cookie:t,...n?{source:n}:{}},vi(s)}function xs(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 Wu(e){let n=Yn().profiles,s=Object.keys(n);if(e){let u=n[e];if(!u)throw Error(`Workspace "${e}" not found. Available: ${s.join(", ")||"(none)"}`);return u.token}if(process.env.SLACK_TOKEN)return process.env.SLACK_TOKEN;let o=process.env.SLACK_BOT_TOKEN??process.env.SLACK_MCP_XOXP_TOKEN;if(o&&s.length===0)return o;let a=[process.env.SLACK_BOT_TOKEN,process.env.SLACK_MCP_XOXP_TOKEN].find((u)=>u&&!u.startsWith("xoxb-"));if(a&&s.length>0){let u=Fi(process.cwd(),["SLACK_BOT_TOKEN","SLACK_MCP_XOXP_TOKEN"]);if(a!==u){if(!globalThis.__slackEnvWarnShown)globalThis.__slackEnvWarnShown=!0,console.error(`Warning: SLACK_MCP_XOXP_TOKEN / SLACK_BOT_TOKEN is set but workspace profiles exist — using profiles.
|
|
106
|
+
`+" Migrate to SLACK_TOKEN=... or remove from your shell config.")}}let r=Fi(process.cwd(),["SLACK_TOKEN"]);if(r)return r;let i=process.env.SLACK_WORKSPACE;if(i){let u=n[i];if(!u)throw Error(`Workspace "${i}" not found. Available: ${s.join(", ")||"(none)"}`);return u.token}let c=zn(Ri());if(c){let u=n[c];if(!u)throw Error(`Workspace "${c}" (from .slack-cli/workspace) not found in profiles.`);return u.token}let l=zn(Ii());if(l){let u=n[l];if(!u)throw Error(`Workspace "${l}" (from ~/.slack-cli/workspace) not found in profiles.`);return u.token}if(s.length>0)throw Error(`Workspace not selected (${s.join(", ")} available).
|
|
107
107
|
Select locally: slack auth use <name> (writes .slack-cli/workspace)
|
|
108
108
|
Select globally: slack auth use -g <name> (writes ~/.slack-cli/workspace)`);throw Error(`No Slack token found.
|
|
109
109
|
Run one of:
|
|
@@ -112,34 +112,34 @@ ${g.join(`
|
|
|
112
112
|
`+` slack auth cookie — attach the xoxd cookie from Chrome (macOS/Windows)
|
|
113
113
|
`+` slack auth firefox — attach the xoxd cookie from Firefox (all platforms)
|
|
114
114
|
`+` slack auth token --token xoxp-... — paste an existing token
|
|
115
|
-
`+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function
|
|
116
|
-
`)t.push(null);else if(!/\s/u.test(
|
|
117
|
-
`)||!Array.isArray(t)||!t.some((g)=>g?.type==="rich_text"))return e;let n=
|
|
118
|
-
`;
|
|
115
|
+
`+" Or set SLACK_TOKEN=xoxp-... in .slack-term/.env.local")}function _r(){let e=process.env.SLACK_BOT_TOKEN;return e&&e.startsWith("xoxb-")?e:void 0}function Vt(e){let t=Yn(),n=t.profiles;if(e)return xs(t,e);if(process.env.SLACK_COOKIE)return process.env.SLACK_COOKIE;if(process.env.SLACK_MCP_XOXD_COOKIE)return process.env.SLACK_MCP_XOXD_COOKIE;if(process.env.SLACK_MCP_XOXP_TOKEN&&Object.keys(n).length===0)return process.env.SLACK_MCP_XOXD_COOKIE;let o=Fi(process.cwd(),["SLACK_COOKIE"]);if(o)return o;let a=process.env.SLACK_WORKSPACE;if(a)return xs(t,a);let r=zn(Ri());if(r)return xs(t,r);let i=zn(Ii());if(i)return xs(t,i);return}function Er(e){let t=[],n=(a)=>{if(!a)return;let r=t[t.length-1];if(r?.type==="text")r.text+=a;else t.push({type:"text",text:a})},s=/<(https?:\/\/[^\s<>|]+)(?:\|([^<>\r\n]*))?>|https?:\/\/[\x21-\x3b\x3d\x3f-\x7e]+/gi,o=0;for(let a of e.matchAll(s)){let r=a.index??0;if(n(e.slice(o,r)),a[1]){t.push(a[2]?{type:"link",url:a[1],text:a[2]}:{type:"link",url:a[1]}),o=r+a[0].length;continue}let i=a[0];while(/[.,:;!?'"*_~]$/.test(i)||i.endsWith(")")&&Ju(i,"(")<Ju(i,")"))i=i.slice(0,-1);t.push({type:"link",url:i}),o=r+i.length}return n(e.slice(o)),t}function Ju(e,t){return e.split(t).length-1}var gy={"&":"&","<":"<",">":">"};function my(e){if(typeof e!=="string"||!/^[0-9a-f]+(-[0-9a-f]+)*$/i.test(e))return[];let t=e.split("-").map((o)=>parseInt(o,16)),n=String.fromCodePoint(...t),s=String.fromCodePoint(...t.filter((o)=>o!==65039));return n===s?[n]:[n,s]}function yy(e){let t=[],n=(a)=>{for(let r of a)if(r===`
|
|
116
|
+
`)t.push(null);else if(!/\s/u.test(r))t.push(...gy[r]??r)},s=(a)=>{switch(a.type){case"text":n(String(a.text??""));break;case"link":case"message_mention":n(String(a.url??""));break;case"user":n(String(a.user_id??""));break;case"channel":n(String(a.channel_id??""));break;case"usergroup":n(String(a.usergroup_id??""));break;case"broadcast":n(String(a.range??""));break;case"emoji":t.push([`:${String(a.name??"")}:`,...my(a.unicode)].filter((r)=>r!=="::"));break;default:break}},o=(a)=>{let r=Array.isArray(a.elements)?a.elements:[];if(a.type==="rich_text_list"||a.type==="rich_text")r.forEach((i,c)=>{if(c>0)t.push(null);o(i)});else r.forEach(s)};return e.forEach((a,r)=>{if(r>0)t.push(null);let i=a;if(i.type==="rich_text")o(i)}),t}function by(e,t,n){if(typeof t==="string"){let o=n;while(o<e.length&&e[o]!==t)o++;return o<e.length?[o,1]:[-1,0]}let s=[-1,0];for(let o of t){let a=[...o];for(let r=n;r+a.length<=e.length&&(s[0]<0||r<s[0]);r++)if(a.every((i,c)=>e[r+c]===i)){s=[r,a.length];break}}return s}function wy(e,t){if(e.includes(`
|
|
117
|
+
`)||!Array.isArray(t)||!t.some((g)=>g?.type==="rich_text"))return e;let n=yy(t);if(!n.includes(null))return e;let s=[...e],o=t[0].elements,r=t[t.length-1].elements,i=Array.isArray(o)&&o[0]?.type==="rich_text_preformatted",c=Array.isArray(r)&&r[r.length-1]?.type==="rich_text_preformatted",l=0,u=-1,d=i,f=[];for(let g of n){if(g===null){d=!0;continue}let[h,b]=by(s,g,l);if(h<0)return e;if(d)f.push([u+1,h]),d=!1;u=h+b-1,l=h+b}if((d||c)&&u>=0)f.push([u+1,s.length]);let p=/^(?:[-*+•]|\d{1,9}[.)]|>|>)$/;for(let[g,h]of f){let b=g;if(s.lastIndexOf("<",g-1)>s.lastIndexOf(">",g-1)){let D=s.indexOf(">",g);if(D!==-1&&D<h)b=D+1}let m="",w=g===0;while(b<h)if(s[b]===" "){let D=b;while(D<h&&s[D]===" ")D++;if(w&&p.test(m))w=!1;else{let k=D-b<=2?D-b:1;for(let E=b;E<b+k;E++)s[E]=`
|
|
118
|
+
`;w=!0}m="",b=D}else m+=s[b],b++}return s.join("")}function $r(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;if(typeof t.text==="string")t.text=wy(t.text,t.blocks)}class Ke 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 Ni(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}var Dy=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();async function Hu(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof Ke)||n+s.retryAfter>Dy)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function Bi(e,t,n,s){return Hu(()=>ky(e,t,n,s))}async function ky(e,t,n,s){s=e.startsWith("xoxc-")?s??Vt():void 0;let o={};if(s)o.Cookie=`d=${s}`;let a=await fetch(`${Ni()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(a.status===429){let i=parseInt(a.headers.get("retry-after")??"60",10);throw new Ke(isNaN(i)?60:i,t)}let r=await a.json();if(r.ok!==!0){let i=r.error??"unknown";if(i==="ratelimited")throw new Ke(60,t);if(i==="invalid_auth"&&e.startsWith("xoxc-")&&!s)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
|
|
119
119
|
Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
|
|
120
120
|
Or replace the token with an xoxp- user token:
|
|
121
|
-
slack auth login`);if((
|
|
121
|
+
slack auth login`);if((i==="missing_scope"||i==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${i}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${i} — ${i==="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}: ${
|
|
125
|
-
Import from Slack desktop: slack auth login`);if((
|
|
126
|
-
Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${
|
|
124
|
+
Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${i}`)}return r}function xy(e,t,n,s){return Hu(()=>Sy(e,t,n,s))}async function Sy(e,t,n,s){let o={};if(s)o.Cookie=`d=${s}`;let a=await fetch(`${Ni()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(a.status===429){let i=parseInt(a.headers.get("retry-after")??"60",10);throw new Ke(isNaN(i)?60:i,t)}let r=await a.json();if(r.ok!==!0){let i=r.error??"unknown";if(i==="ratelimited")throw new Ke(60,t);if((i==="invalid_auth"||i==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
|
|
125
|
+
Import from Slack desktop: slack auth login`);if((i==="invalid_auth"||i==="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}: ${i}`)}return r}function _y(e,t,n={},s){let o=new URLSearchParams({token:e,...n});return xy(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()},s)}function Fe(e,t,n,s){let o=new URLSearchParams(n).toString();return Bi(e,`${t}?${o}`,{method:"GET"},s)}function ji(e,t,n,s){return Bi(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function zu(e,t,n){if(!e.startsWith("xoxb-"))throw Error("Agent sessions require a bot token (xoxb); user tokens are refused.");return Bi(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(1e4)})}function Es(e,t,n){return zu(e,"agents.sessions.setStatus",{...t,status:n})}function Wi(e,t,n){return zu(e,"agents.sessions.rename",{...t,title:n})}async function Gn(e,t){let n=await Fe(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Yu(e,t){t=e.startsWith("xoxc-")?t??Vt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let s=await fetch(`${Ni()}/auth.test`,{method:"GET",headers:n});if(s.status===429){let r=parseInt(s.headers.get("retry-after")??"60",10);throw new Ke(isNaN(r)?60:r,"auth.test")}let o=s.headers.get("x-oauth-scopes")??"",a=await s.json();if(a.ok!==!0)throw Error(`Slack error on auth.test: ${a.error??"unknown"}`);return{userId:a.user_id??"",user:a.user??"",botId:a.bot_id??"",team:a.team??"",url:a.url??"",scopes:o.split(",").map((r)=>r.trim()).filter(Boolean)}}async function Gu(e,t,n){let s=await Fe(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function Cn(e,t,n=20,s,o,a,r){let i={channel:t,limit:String(n)};if(s!==void 0)i.oldest=s;if(o!==void 0)i.cursor=o;if(r)i.inclusive="true";return Ji(await Fe(e,"conversations.history",i,a))}function Ji(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)$r(s);return e}async function Xu(e,t,n,s=50,o){return Ji(await Fe(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},o))}async function Vu(e,t,n,s={},o){let a={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)a.oldest=s.oldest;if(s.cursor!==void 0)a.cursor=s.cursor;return Ji(await Fe(e,"conversations.replies",a,o))}async function Zu(e,t,n){let s=[],o="";do{let a={limit:"200",types:t,exclude_archived:"true"};if(o)a.cursor=o;let r=await Fe(e,"users.conversations",a,n);s.push(...r.channels??[]),o=r.response_metadata?.next_cursor??""}while(o);return s}async function Cr(e,t,n,s,o){await ji(e,"reactions.add",{channel:t,timestamp:n,name:s},o)}async function Qu(e,t,n,s){return((await Fe(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((a)=>({name:String(a.name??""),users:Array.isArray(a.users)?a.users.map(String):[]}))}async function Ar(e,t,n,s,o){await ji(e,"reactions.remove",{channel:t,timestamp:n,name:s},o)}async function Ey(e,t,n){let o=(await ji(e,"conversations.open",{users:t},n)).channel?.id;if(!o)throw Error(`Failed to open DM with user ${t}`);return o}async function ed(e,t,n){let s="";while(!0){let o={types:"im",limit:"200"};if(s)o.cursor=s;let a=await Fe(e,"conversations.list",o,n);for(let r of a.channels??[])if(r.user===t)return String(r.id??"");if(s=a.response_metadata?.next_cursor??"",!s)break}return""}async function Mi(e,t,n,s){let o=await ed(e,t,n);if(o)return o;let a=s?`${s} (${t})`:t;throw Error(`No existing DM with ${a}. Open it once in Slack first.`)}function _s(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Uu(e,t){let n=_s(e.name??""),s=_s(e.real_name??e.profile?.real_name??""),o=_s(e.profile?.display_name??"");return n===t||s===t||!!o&&o===t}var td=200;async function $y(e,t,n){let s=0,o=new Set,a="";while(!0){let u={limit:"200"};if(a)u.cursor=a;let d=await Fe(e,"users.list",u,n);for(let f of d.members??[]){if(s++,f.id)o.add(f.id);if(Uu(f,t))return{id:f.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(a=d.response_metadata?.next_cursor??"",!a)break}let r=0,i=0,c=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await Fe(e,"conversations.list",u,n);for(let f of d.channels??[]){let p=f.user;if(!p||o.has(p))continue;if(r>=td){c=!0;break}o.add(p),r++;let g;try{g=(await Fe(e,"users.info",{user:p},n)).user}catch(h){if(h instanceof Ke)throw h;i++;continue}if(g&&Uu(g,t))return{id:p,dm:String(f.id??""),workspaceCount:s,connectCount:r,skipped:i,capped:c}}if(c)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:s,connectCount:r,skipped:i,capped:c}}function Cy(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)`,
|
|
129
|
-
`+(
|
|
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 ${td} 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
|
+
`+(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
|
|
133
|
-
${
|
|
132
|
+
slack user ls --external`)}function Ui(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,o=e.indexOf("?"),a=o>=0?new URLSearchParams(e.slice(o)):void 0,r=a?.get("thread_ts")??void 0,l={channel:a?.get("cid")??void 0??n};if(s)l.ts=s;if(r)l.threadTs=r;return l}function Ay(e){return Ui(e)?.channel}function Ku(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function qu(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function Fr(e,t,n){let s=Ay(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(Ku(t))return t;if(qu(t))return Mi(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Ku(t.slice(1)))return t.slice(1);let o=t.startsWith("@"),a=t.slice(1),r=_s(a);if(o){if(qu(a))return Mi(e,a,n);let l=await Fe(e,"auth.test",{},n);if(r==="you"||r==="me"||_s(l.user??"")===r){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await ed(e,f,n)||Ey(e,f,n)}let d=await $y(e,r,n);if(!d.id)throw Cy(t,d);if(d.dm)return d.dm;return Mi(e,d.id,n,t)}let i=a.toLowerCase(),c="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)l.cursor=c;let u=await Fe(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===i)return String(d.id??"");if(c=u.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function Tr(e,t,n){try{let s=await Fe(e,"users.info",{user:t},n),o=s.user?.profile?.display_name,a=o&&o.length>0?o:s.user?.real_name??s.user?.name??t,r=s.user?.name??t;return[a,r]}catch{return[t,t]}}async function Xn(e,t,n){try{let s=await Fe(e,"users.info",{user:t},n),o=s.user?.profile?.display_name;if(o&&o.length>0)return o;return s.user?.real_name??s.user?.name??t}catch{return t}}async function Or(e,t){let n=[],s="";while(!0){let o={limit:"200"};if(s)o.cursor=s;let a=await Fe(e,"users.list",o,t);if(n.push(...a.members??[]),s=a.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function Ki(e,t,n){let s=[],o="";while(!0){let a={channel:t,limit:"200"};if(o)a.cursor=o;let r=await Fe(e,"conversations.members",a,n);if(s.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return s}async function qi(e,t,n){return Fe(e,"users.info",{user:t},n)}async function nd(e,t,n){return Fe(e,"conversations.info",{channel:t},n)}async function sd(e,t){let n=await _y(e,"client.boot",{},t),s=typeof n.url==="string"?n.url:void 0;if(!s){let a=Object.keys(n).join(", ");throw Error(`client.boot did not return a WebSocket URL. Keys: ${a}`)}let o=n.self&&typeof n.self==="object"&&!Array.isArray(n.self)?n.self:{};return{wsUrl:s,selfId:typeof o.id==="string"?o.id:""}}var Fy=["chat:write","im:write"],Ty=["im:history","im:read"];async function Rr(e){let{userId:t,botId:n,team:s,scopes:o}=await Yu(e),a="";if(n)try{a=(await Gu(e,n)).appId}catch{a=""}let r=(l)=>o.includes(l),i=Fy.filter((l)=>!r(l)),c=Ty.filter((l)=>!r(l));return{canSend:i.length===0,canReceiveReplies:c.length===0,ok:i.length===0&&c.length===0,botUserId:t,appId:a,team:s,grantedScopes:o,missingSendScopes:i,missingReplyScopes:c}}function rd(e){return["",` Bot user: ${e.botUserId||"(unknown)"}`,` App ID: ${e.appId||"(unknown — bots.info unavailable)"}`,` Granted scopes: ${e.grantedScopes.join(", ")||"(none reported)"}`]}function Ir(e,t=!1){let n=e.appId?`https://api.slack.com/apps/${e.appId}`:"https://api.slack.com/apps";if(e.ok){let o=["✓ Bot DM scopes are complete (send + read replies)."," Two-way replies also require the Messages Tab, which is not API-detectable.",' If recipients see "Sending messages to this app is turned off", enable it:',` ${n} → App Home → "Messages Tab" ON + "Allow users to send messages".`];return t?o:[...o,...rd(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,...rd(e)]}import{createInterface as Ye}from"node:readline/promises";import{join as ta,resolve as nb}from"node:path";import{homedir as sb}from"node:os";import{readdirSync as As,readFileSync as Cs,existsSync as nt,copyFileSync as Yi,mkdtempSync as cd,rmSync as ld}from"node:fs";import{homedir as Pr,tmpdir as ud}from"node:os";import{join as me,dirname as Iy}from"node:path";import{pbkdf2Sync as vr,createDecipheriv as dd,createHash as vy,timingSafeEqual as Py}from"node:crypto";import{execSync as fd,execFileSync as Ly}from"node:child_process";function $s(e,t){let n=0,s=0,o=t;while(o<e.length){let a=e[o++];if(n+=(a&127)*2**s,(a&128)===0)break;s+=7}return{value:n,pos:o}}function Oy(e){let t=0,n=0,s=0;while(t<e.length){let r=e[t++];if(n+=(r&127)*2**s,(r&128)===0)break;s+=7}let o=Buffer.allocUnsafe(n),a=0;while(t<e.length&&a<n){let r=e[t++],i=r&3;if(i===0){let c=r>>2;if(c>=60){let l=c-59;c=0;for(let u=0;u<l;u++)c+=e[t++]*2**(8*u)}c+=1,e.copy(o,a,t,t+c),t+=c,a+=c}else{let c,l;if(i===1)c=4+(r>>2&7),l=(r>>5&7)*256+e[t++];else if(i===2)c=1+(r>>2),l=e[t]+e[t+1]*256,t+=2;else c=1+(r>>2),l=e[t]+e[t+1]*256+e[t+2]*65536+e[t+3]*16777216,t+=4;let u=a-l;for(let d=0;d<c&&a<n;d++)o[a++]=o[u++]}}return a===n?o:o.subarray(0,a)}function Hi(e,t){let n=$s(e,t),s=$s(e,n.pos);return{handle:{offset:n.value,size:s.value},pos:s.pos}}function od(e,t){let{offset:n,size:s}=t,o=e.subarray(n,n+s);return e[n+s]===1?Oy(o):Buffer.from(o)}function Ry(e){if(e.length<4)return[];let t=e.readUInt32LE(e.length-4),n=e.length-(t+1)*4,s=[],o=0,a=Buffer.alloc(0);while(o<n){let r=$s(e,o),i=$s(e,r.pos),c=$s(e,i.pos);o=c.pos;let l=r.value,u=i.value,d=c.value,f=e.subarray(o,o+u);o+=u;let p=e.subarray(o,o+d);o+=d,a=Buffer.concat([a.subarray(0,l),f]),s.push(p)}return s}function id(e){if(e.length<48)return Buffer.alloc(0);try{let t=e.length-48,n=Hi(e,t),s=Hi(e,n.pos),o=od(e,s.handle),a=[];for(let r of Ry(o))try{let{handle:i}=Hi(r,0);a.push(od(e,i))}catch{}return Buffer.concat(a)}catch{return Buffer.alloc(0)}}function ad(){let e=process.env.HOME??Pr();if(process.platform==="darwin")return[me(e,"Library","Application Support","Slack","Local Storage","leveldb")];if(process.platform==="linux")return[me(e,".config","Slack","Local Storage","leveldb"),me(e,"snap","slack","current",".config","Slack","Local Storage","leveldb"),me(e,".var","app","com.slack.Slack","config","Slack","Local Storage","leveldb")];if(process.platform==="win32"){let t=process.env.APPDATA??me(e,"AppData","Roaming");return[me(t,"Slack","Local Storage","leveldb")]}throw Error(`Unsupported platform: ${process.platform}`)}function My(){let e=process.env.HOME??Pr();if(process.platform==="darwin")return me(e,"Library","Application Support","Slack","Cookies");return""}function Ny(e,t){if(e.length<35||e.slice(0,3).toString()!=="v10")throw Error("Not a v10 encrypted cookie");let n=e.slice(19,35),s=e.slice(35),o=dd("aes-128-cbc",t,n);return o.setAutoPadding(!0),Buffer.concat([o.update(s),o.final()]).toString("utf8")}function By(){if(process.platform!=="darwin")return;let e=My();if(!nt(e))return;let t;try{t=fd('security find-generic-password -w -s "Slack Safe Storage" -a "Slack Key"',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return}let n=vr(t,"saltysalt",1003,16,"sha1");try{let{default:s}=fs("bun:sqlite"),o=new s(e,{readonly:!0}),a=o.prepare("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack%'").get();if(o.close(),!a)return;return Ny(Buffer.from(a.encrypted_value),n)}catch{return}}function pd(e){if(!nt(e))return[];let t=As(e).filter((r)=>r.endsWith(".ldb")||r.endsWith(".log"));if(t.length===0)return[];let n=new Map,s=(r)=>{let i=n.get(r);if(i!==void 0)return i;let c="";try{let l=Cs(me(e,r));c=r.endsWith(".ldb")?id(l).toString("latin1")||l.toString("latin1"):l.toString("latin1")}catch{c=""}return n.set(r,c),c},o=new Map;for(let r of t){let i=s(r);for(let c of i.matchAll(/"token":"(xoxc-[^"]+)"/g)){let l=c[1],u=l.split("-")[1]??"";if(!u||l.length<40)continue;let d=Math.max(0,c.index-2000),f=Math.min(i.length,c.index+2000),p=i.slice(d,f),g=p.match(/"url":"(https:\/\/[a-z0-9-]+\.slack\.com\/)"/),h=p.match(/"(?:team_name|name)":"([^"]{2,60})"/),b=o.get(u);if(!b||l.length>b.token.length){let m={token:l,teamId:u},w=g?.[1]??b?.url,D=h?.[1]??b?.teamName;if(w)m.url=w;if(D)m.teamName=D;o.set(u,m)}}}let a=t.map((r)=>s(r).replace(/[^\x20-\x7e]/g," ")).join(" ");for(let r of o.values()){if(r.teamName)continue;let i=a.indexOf(r.teamId);if(i!==-1){let c=Math.max(0,i-500),l=Math.min(a.length,i+500),d=a.slice(c,l).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(d?.[1]){r.teamName=d[1];continue}}if(!r.teamName&&r.url){let c=r.url.match(/https:\/\/([a-z0-9-]+)\.slack\.com\//)?.[1];if(c){let l=a.indexOf(c);if(l!==-1){let u=Math.max(0,l-500),d=Math.min(a.length,l+500),p=a.slice(u,d).match(/"(?:team_name|name)":"([^"]{2,60})"/);if(p?.[1]){r.teamName=p[1];continue}}r.teamName=c.split("-").map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}}}return[...o.values()]}async function Gi(e){let t=e??ad().find(nt);if(!t)throw Error(`Slack desktop app LevelDB not found at:
|
|
133
|
+
${ad().join(`
|
|
134
134
|
`)}
|
|
135
|
-
Is Slack installed and opened at least once?`);let n=
|
|
136
|
-
`)){let c=
|
|
135
|
+
Is Slack installed and opened at least once?`);let n=pd(t),s=e?void 0:By();if(s)for(let o of n)o.cookie=s;return n}function jy(e,t){try{return JSON.parse(Cs(me(e,"Local State"),"utf8")).profile?.info_cache?.[t]?.user_name||void 0}catch{return}}function Xi(){let e=Vi();if(!e||!nt(e))return[];let t=["Default",...As(e).filter((s)=>s.startsWith("Profile "))],n=[];for(let s of t){let o=me(e,s,"Local Storage","leveldb"),a=pd(o);if(a.length===0)continue;let r=jy(e,s);n.push({profileDir:s,...r?{email:r}:{},label:hd(e,s),sessions:a})}return n}function zi(e,t,n,s=!1){let o=(a,r)=>{try{let i=dd("aes-128-cbc",t,a);i.setAutoPadding(!0);let c=Buffer.concat([i.update(r),i.final()]);if(c.subarray(0,5).toString()==="xoxd-")return c.toString("utf8");if(c.length>=37){let l=vy("sha256").update(n).digest();if(Py(c.subarray(0,32),l)){let u=c.subarray(32).toString("utf8");if(u.startsWith("xoxd-"))return u}}return}catch{return}};return o(Buffer.alloc(16,32),e.slice(3))??(s&&e.length>=35?o(e.slice(19,35),e.slice(35)):void 0)}function hd(e,t){let n=(s,o)=>{if(s&&o)return`${s} (${o})`;return s||o||t};try{let o=JSON.parse(Cs(me(e,"Local State"),"utf8")).profile?.info_cache?.[t];if(o&&(o.name||o.user_name))return n(o.name??"",o.user_name??"")}catch{}try{let o=JSON.parse(Cs(me(e,t,"Preferences"),"utf8")).profile;return n(o?.name??"",o?.user_name??"")}catch{return t}}function Vi(){let e=process.env.HOME??Pr();if(process.platform==="darwin")return me(e,"Library","Application Support","Google","Chrome");if(process.platform==="linux")return me(process.env.XDG_CONFIG_HOME??me(e,".config"),"google-chrome");return""}function Wy(){try{return Ly("secret-tool",["lookup","application","chrome"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()||void 0}catch{return}}function Fs(){if(process.platform!=="darwin"&&process.platform!=="linux")return{candidates:[],totalProfiles:0};let e=Vi();if(!nt(e))return{candidates:[],totalProfiles:0};let t;if(process.platform==="darwin"){let r;try{r=fd('security find-generic-password -a Chrome -s "Chrome Safe Storage" -w',{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trimEnd()}catch{return{candidates:[],totalProfiles:0}}if(!r)return{candidates:[],totalProfiles:0};t=vr(r,"saltysalt",1003,16,"sha1")}let n=["Default",...As(e).filter((r)=>r.startsWith("Profile "))],s=[],o,a=!1;for(let r of n){let i=[me(e,r,"Network","Cookies"),me(e,r,"Cookies")].find(nt);if(!i)continue;let c=cd(me(ud(),"slack-chrome-cookies-")),l=me(c,"Cookies");try{if(Yi(i,l),nt(`${i}-wal`))Yi(`${i}-wal`,`${l}-wal`);let{default:u}=fs("bun:sqlite"),d=new u(l,{readonly:!0}),f;try{f=d.prepare("SELECT encrypted_value, value, host_key FROM cookies WHERE name='d' AND (host_key='slack.com' OR host_key LIKE '%.slack.com') LIMIT 1").get()}finally{d.close()}if(!f)continue;let 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=zi(p,vr("peanuts","saltysalt",1,16,"sha1"),f.host_key);else if(g==="v11"){if(!o){let b=Wy();if(b)o=vr(b,"saltysalt",1,16,"sha1")}if(o)h=zi(p,o,f.host_key);else a=!0}}else if(g==="v10"&&t)h=zi(p,t,f.host_key,!0);else if(g!=="v10")throw Error("Unknown cookie encryption prefix.");if(h)s.push({profileDir:r,profileName:hd(e,r),cookie:h})}catch(u){if(u instanceof Error&&(u.message.includes("unsupported v20")||u.message.includes("Unknown cookie")))throw u}finally{ld(c,{recursive:!0,force:!0})}}if(a&&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 Zi(){if(process.platform!=="linux")throw Error("Chrome session import is currently supported on Linux only.");let e=Vi();if(!nt(e))throw Error("Chrome profile directory was not found.");let t=new Map(Fs().candidates.map((o)=>[o.profileDir,o.cookie])),n=new Map,s=["Default",...As(e).filter((o)=>o.startsWith("Profile "))];for(let o of s){let a=me(e,o,"Local Storage","leveldb");if(!nt(a))continue;let r;try{r=await Gi(a)}catch{continue}for(let i of r){if(n.has(i.teamId))throw Error("More than one Chrome profile has a token for the same workspace. Select one browser profile first.");let c=t.get(o);if(c)i.cookie=c;n.set(i.teamId,i)}}return[...n.values()]}function Jy(){let e=process.env.HOME??Pr();if(process.platform==="darwin")return[me(e,"Library","Application Support","Firefox","Profiles")];if(process.platform==="linux")return[me(e,".mozilla","firefox"),me(e,"snap","firefox","common",".mozilla","firefox"),me(e,".var","app","org.mozilla.firefox",".mozilla","firefox")];if(process.platform==="win32")return[me(process.env.APPDATA??me(e,"AppData","Roaming"),"Mozilla","Firefox","Profiles")];return[]}function Uy(e){let t=me(e,"profiles.ini"),n=nt(t)?t:me(Iy(e),"profiles.ini"),s={};if(!nt(n))return s;try{let o=Cs(n,"utf8"),a="",r="";for(let i of o.split(`
|
|
136
|
+
`)){let c=i.trim();if(c.startsWith("[")){a="",r="";continue}let l=c.indexOf("=");if(l===-1)continue;let u=c.slice(0,l).trim().toLowerCase(),d=c.slice(l+1).trim();if(u==="name")a=d;if(u==="path")r=d.split(/[\\/]/).pop()??d;if(a&&r)s[r]=a,a="",r=""}}catch{}return s}function Lr(){let e=[];for(let t of Jy().filter(nt)){let n=Uy(t),s;try{s=As(t)}catch{continue}for(let o of s){let a=me(t,o,"cookies.sqlite");if(!nt(a))continue;let r=cd(me(ud(),"slack-firefox-cookies-")),i=me(r,"cookies.sqlite");try{Yi(a,i);let{default:c}=fs("bun:sqlite"),l=new c(i,{readonly:!0}),u=l.prepare("SELECT value FROM moz_cookies WHERE name='d' AND (host='slack.com' OR host LIKE '%.slack.com') LIMIT 1").get();if(l.close(),!u?.value||!u.value.startsWith("xoxd-"))continue;let d=n[o]??o;e.push({profileDir:o,profileName:d,cookie:u.value})}catch{}finally{ld(r,{recursive:!0,force:!0})}}}return e}import{readFileSync as Qi,writeFileSync as ea,mkdirSync as Ky,existsSync as Ts,rmSync as qy}from"node:fs";import{join as lt}from"node:path";import{createDecipheriv as Mr}from"node:crypto";import{spawnSync as Hy}from"node:child_process";var zy=Buffer.from("b31c6e241ac846728da9c1fac4936651cffb944d143ab816276bcc6da0284787","hex"),Yy=Buffer.from("e98f37d7f4e1fa433d19304dc2258042090e2d1d7eea7670d41f738d08729660","hex"),Gy=Buffer.from("ccf8a1cec56605b8517552ba1a2d061c03a29e90274fb2fcf59ba4b75c392390","hex"),mt="C:\\ProgramData\\slack-term-abe";function Xy(){let e=process.env.LOCALAPPDATA??lt(process.env.USERPROFILE??"","AppData","Local");return lt(e,"Google","Chrome","User Data")}var Vy=String.raw`try {
|
|
137
137
|
Add-Type -AssemblyName System.Security
|
|
138
138
|
$d = [IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\in.bin')
|
|
139
139
|
$o = [Security.Cryptography.ProtectedData]::Unprotect($d, $null, 'CurrentUser')
|
|
140
140
|
[IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\sys.bin', $o)
|
|
141
141
|
} catch { Set-Content 'C:\ProgramData\slack-term-abe\dpapi.err' ($_.Exception.Message) }
|
|
142
|
-
`,
|
|
142
|
+
`,Zy=String.raw`try {
|
|
143
143
|
Add-Type -TypeDefinition @'
|
|
144
144
|
using System; using System.Runtime.InteropServices;
|
|
145
145
|
public static class NC {
|
|
@@ -155,7 +155,7 @@ public static class NC {
|
|
|
155
155
|
'@
|
|
156
156
|
[IO.File]::WriteAllBytes('C:\ProgramData\slack-term-abe\cng.bin', [NC]::Dec([IO.File]::ReadAllBytes('C:\ProgramData\slack-term-abe\eak.bin')))
|
|
157
157
|
} catch { Set-Content 'C:\ProgramData\slack-term-abe\cng.err' ($_.Exception.Message) }
|
|
158
|
-
`;function
|
|
158
|
+
`;function Qy(e,t){let n=(s)=>`'${s.replace(/'/g,"''")}'`;return String.raw`
|
|
159
159
|
$ErrorActionPreference = 'Stop'
|
|
160
160
|
Add-Type -AssemblyName System.Security
|
|
161
161
|
$work = 'C:\ProgramData\slack-term-abe'
|
|
@@ -221,71 +221,173 @@ 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
|
|
225
|
-
`).filter((c)=>c.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${
|
|
226
|
-
Could not extract the cookie automatically: ${
|
|
224
|
+
`}function eb(e,t){let s=4+e.readUInt32LE(0)+4,o=e[s];if(o===1||o===2){let a=e.subarray(s+1,s+13),r=e.subarray(s+13,s+45),i=e.subarray(s+45,s+61),c=o===1?Mr("aes-256-gcm",zy,a):Mr("chacha20-poly1305",Yy,a,{authTagLength:16});return c.setAuthTag(i),Buffer.concat([c.update(r),c.final()])}if(o===3){if(!t)throw Error("flag 3 requires the CNG-decrypted key (cng.bin missing)");let a=e.subarray(s+33,s+45),r=e.subarray(s+45,s+77),i=e.subarray(s+77,s+93),c=Buffer.from(t.map((u,d)=>u^Gy[d])),l=Mr("aes-256-gcm",c,a);return l.setAuthTag(i),Buffer.concat([l.update(r),l.final()])}throw Error(`Unsupported app-bound key flag: ${o}`)}function tb(e,t){let n=t.subarray(3,15),s=t.subarray(15,t.length-16),o=t.subarray(t.length-16),a=Mr("aes-256-gcm",e,n);return a.setAuthTag(o),Buffer.concat([a.update(s),a.final()]).subarray(32).toString("utf8")}async function gd(e){if(process.platform!=="win32")throw Error("Windows-only");let t=Xy();if(!Ts(lt(t,"Local State")))throw Error(`Chrome Local State not found at ${t}`);Ky(mt,{recursive:!0});let n=lt(mt,"extract.ps1");ea(n,Qy(t,e)),ea(lt(mt,"inner_dpapi.ps1"),Vy),ea(lt(mt,"inner_cng.ps1"),Zy);let s=`Start-Process powershell -Verb RunAs -Wait -ArgumentList @('-NoProfile','-ExecutionPolicy','Bypass','-WindowStyle','Hidden','-File','${n.replace(/'/g,"''")}')`,o=Hy("powershell",["-NoProfile","-Command",s],{encoding:"utf8",windowsHide:!0});if(o.status!==0&&o.error)throw Error(`Failed to launch elevated helper: ${o.error.message}`);let a=lt(mt,"out.bin"),r=lt(mt,"Cookies");if(!Ts(a)||!Ts(r)){let i=Ts(lt(mt,"log.txt"))?Qi(lt(mt,"log.txt"),"utf8").split(`
|
|
225
|
+
`).filter((c)=>c.startsWith("ERROR")).join(" "):"";throw Error(`Elevated extraction did not complete${i?` (${i.trim()})`:" (UAC declined or Chrome build unsupported)"}`)}try{let i=Qi(a),c=Ts(lt(mt,"cng.bin"))?Qi(lt(mt,"cng.bin")):void 0,l=eb(i,c),{Database:u}=fs("bun:sqlite"),d=new u(r,{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=tb(l,p);if(!g.startsWith("xoxd-"))throw Error("decrypted value is not an xoxd- cookie");return g}finally{if(!process.env.SLACK_KEEP_ABE)qy(mt,{recursive:!0,force:!0})}}var rb=["search:read","channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"],ob=["channels:history","groups:history","im:history","mpim:history","channels:read","groups:read","im:read","mpim:read","users:read","chat:write","files:write"];function Vn(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function ib(){return JSON.stringify({display_information:{name:"slack-term"},oauth_config:{scopes:{user:rb}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}function ab(){return JSON.stringify({display_information:{name:"slack-term"},features:{bot_user:{display_name:"slack-term",always_online:!1}},oauth_config:{scopes:{bot:ob}},settings:{org_deploy_enabled:!1,socket_mode_enabled:!1,token_rotation_enabled:!1}},null,2)}async function Zt(e,t){return(await e.question(t)).trim()}async function Os(e,t){if(t)return!0;if(!e)return!1;let n=await Zt(e,"Read local browser profiles and Slack session cookies? [y/N]: ");return n.toLowerCase()==="y"||n.toLowerCase()==="yes"}async function An(e,t,n,s){console.error("Verifying token...");let o=await Gn(t,s),a=Vn(o.team),r;if(n)r=n;else if(e)r=await Zt(e,`Workspace name [${a}]: `)||a;else r=a;let i=null;if(e){console.log(""),console.log("Where to save the token?"),console.log(" 1) ./.env.local (current directory) [default]"),console.log(" 2) ./.slack-term/.env.local (current directory, slack-specific)"),console.log(" 3) ~/.slack-term/.env.local (global, available everywhere)"),console.log(" 4) profiles.json (multi-workspace: slack auth use)"),console.log("");let c=await Zt(e,"Choice [1/2/3/4, Enter=1]: ");if(c==="2")i=ta(process.cwd(),".slack-term",".env.local");else if(c==="3")i=ta(sb(),".slack-term",".env.local");else if(c==="4")i=null;else i=ta(process.cwd(),".env.local")}if(i===null)if(Sr(r,{token:t,...o,...s?{cookie:s}:{}}),console.log(`Saved workspace "${r}" to profiles.json: ${o.team} (${o.user})`),process.env.SLACK_MCP_XOXP_TOKEN)console.log(""),console.log("Warning: SLACK_MCP_XOXP_TOKEN is set — it conflicts with profiles."),console.log(" Unset it: unset SLACK_MCP_XOXP_TOKEN (and remove from ~/.zshrc / ~/.bashrc)");else console.log(` Run: slack auth use -g ${r}`);else{let c={SLACK_TOKEN:t};if(s)c.SLACK_COOKIE=s;Pi(i,c),console.log(`Saved token to ${i}`),console.log(" SLACK_TOKEN will be picked up automatically in this directory tree.")}return r}async function na(e,t=!1,n="auto",s=!1){console.error("Scanning Slack desktop app...");let o=await Gi();if(o.length===0)console.error("No sessions found. Make sure Slack is installed and you have signed in at least once."),process.exit(1);if(process.platform==="linux"&&n!=="none"&&o.some((a)=>!a.cookie)&&await Os(e,t)){let a=[];if(n!=="chrome")for(let r of Lr())a.push({source:"Firefox",profileName:r.profileName,cookie:r.cookie});if(n==="chrome"||n==="all"||n==="auto"&&a.length===0)try{for(let r of Fs().candidates)a.push({source:"Chrome",profileName:r.profileName,cookie:r.cookie})}catch(r){console.error(r instanceof Error?r.message:String(r))}if(a.length===1){for(let r of o)r.cookie??=a[0].cookie;console.log(`Found Slack session cookie in ${a[0].source} profile: ${a[0].profileName}`)}else if(a.length>1)console.log("Multiple browser sessions found. Choose one later with slack auth chrome or slack auth firefox.");if(o.some((r)=>!r.cookie))console.log("Desktop session needs an xoxd cookie on Linux. Run: slack auth chrome or slack auth firefox")}await sa(o,e,s)}async function sa(e,t,n=!1){if(e.length===1&&t&&e[0]?.cookie&&!n){let s=e[0],o=s.teamName??s.teamId;console.log(`Found workspace: ${o}${s.cookie?" (+ xoxd cookie)":""}`),await An(t,s.token,Vn(o),s.cookie),console.log(""),console.log("Note: desktop app tokens (xoxc-) are internal Slack tokens."),console.log("If API calls fail, replace with an xoxp- token: slack auth login");return}for(let s of e){let o=s.teamName??s.teamId,a=Vn(o);Sr(a,{token:s.token,team:o,teamId:s.teamId,url:s.url??"",user:"",...s.cookie?{cookie:s.cookie}:{}}),console.log(`Added workspace "${a}": ${o}${s.cookie?" + xoxd cookie":""}`)}if(console.log(""),e.length===1){let s=Vn(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 md(e){console.log("Which token type does your app use?"),console.log(""),console.log(" 1) User token (xoxp-) -full access including search [recommended]"),console.log(" 2) Bot token (xoxb-) -search and news unavailable"),console.log("");let n=await Zt(e,"Choice [1/2]: ")==="2"?"bot":"user",s=n==="user"?"xoxp-":"xoxb-",o=n==="user"?"User OAuth Token":"Bot User OAuth Token";console.log(""),console.log("Find your token here:"),console.log(" https://api.slack.com/apps"),console.log(" -> Select your app -> OAuth & Permissions"),console.log(` -> Copy the "${o}" (starts with ${s})`),console.log("");let a=await Zt(e,"Paste your token: ");if(!a)console.error("No token provided."),process.exit(1);if(!a.startsWith(s))console.error(`Expected a ${s} token, got: ${a.slice(0,10)}...`),process.exit(1);await An(e,a)}async function Nr(e,t){let n=t==="user"?ib():ab(),s=t==="user"?"User OAuth Token (xoxp-...)":"Bot User OAuth Token (xoxb-...)",o=t==="user"?"xoxp-":"xoxb-";if(t==="bot")console.log("Note: bot tokens cannot use search:read (user-only scope)."),console.log(" The news and search commands will not work with a bot token."),console.log("");console.log("Step 1 -Create your Slack app:"),console.log(" Open: https://api.slack.com/apps"),console.log(' Click "Create New App" -> "From a manifest" -> select your workspace'),console.log(" Paste this manifest (JSON tab):"),console.log(""),console.log("-------------------------------------------------------------"),console.log(n),console.log("-------------------------------------------------------------"),console.log(""),console.log('Step 2 -Install: "Install App" -> "Install to Workspace" -> Authorize'),console.log(""),console.log("Step 3 -Copy your token:"),console.log(` OAuth & Permissions -> ${s}`),console.log("");let a=await Zt(e,"Paste your token: ");if(!a)console.error("No token provided."),process.exit(1);if(!a.startsWith(o))console.error(`Expected a ${o} token, got: ${a.slice(0,10)}...`),process.exit(1);await An(e,a)}async function cb(e,t){let n=Xi();if(n.length===0)console.error("No Slack session found in Chrome. Sign in to Slack in Chrome (app.slack.com) and retry."),process.exit(1);let s=e.profile.token.split("-")[1],o=n.find((a)=>a.sessions.some((r)=>r.teamId===s));if(!o&&t){if(o=n.find((a)=>a.email===t||a.profileDir===t||a.profileDir===`Profile ${t}`),!o)console.error(`Chrome profile "${t}" has no Slack session. Available: ${n.map((a)=>a.email??a.profileDir).join(", ")}`),process.exit(1)}if(!o)if(n.length===1)o=n[0];else if(process.stdin.isTTY){console.log("Multiple Chrome profiles have a Slack session:"),n.forEach((c,l)=>console.log(` ${l+1}) ${c.email??c.label} [${c.profileDir}]`));let a=Ye({input:process.stdin,output:process.stdout}),r=(await a.question(`Choice [1-${n.length}]: `)).trim();a.close();let i=parseInt(r,10)-1;if(isNaN(i)||i<0||i>=n.length)console.error("Invalid choice."),process.exit(1);o=n[i]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),n.forEach((a)=>console.error(` slack auth cookie -w ${e.name} --profile "${a.email??a.profileDir}"`)),process.exit(1);console.log(`Using Chrome profile: ${o.email??o.label} [${o.profileDir}]`),console.log("Chrome's cookie is app-bound encrypted; a Windows elevation (UAC) prompt will appear — approve it.");try{return await gd(o.profileDir)}catch(a){console.error(`
|
|
226
|
+
Could not extract the cookie automatically: ${a instanceof Error?a.message:String(a)}`),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 yd(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=Ss();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((r)=>r.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((r)=>r.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let a=t.find((r)=>r.current);if(a)n=a.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((l,u)=>console.log(` ${u+1}) ${l.name} (${l.profile.team})`));let r=Ye({input:process.stdin,output:process.stdout}),i=(await r.question("Choice: ")).trim();r.close();let c=parseInt(i,10)-1;if(isNaN(c)||c<0||c>=t.length)console.error("Invalid choice."),process.exit(1);n=t[c].name}}let s=t.find((a)=>a.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
|
|
230
|
-
`))}function
|
|
229
|
+
`+"actions (tail @user, DMs, listing users) would still fail.");let a=t.filter((r)=>r.profile.token.startsWith("xoxc-")||r.profile.token.startsWith("xoxp-"));if(a.length>0)console.error(` Target a user-token workspace instead: ${a.map((r)=>r.name).join(", ")}`),console.error(` slack auth chrome -w ${a[0].name}`);else console.error(" Import your Slack desktop user session instead: slack auth login");process.exit(1)}let o;if(process.platform==="win32")o=await cb(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 a=e.yes?void 0:Ye({input:process.stdin,output:process.stdout});try{if(!await Os(a,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{a?.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 r,i;try{({candidates:r,totalProfiles:i}=Fs())}catch(c){console.error(`Failed: ${c instanceof Error?c.message:String(c)}`),process.exit(1)}if(r.length===0)console.error(`No Slack session found in Chrome (scanned ${i} profile${i!==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(r.length===1&&i<=1)o=r[0].cookie,console.log(`Found session in Chrome profile: ${r[0].profileName}`);else{let c=r.length===1?`Found 1 Slack session across ${i} Chrome profiles:`:`Found ${r.length} Slack sessions across ${i} Chrome profiles:`;console.log(c),r.forEach((p,g)=>console.log(` ${g+1}) ${p.profileName} [${p.profileDir}]`)),console.log("");let l=Ye({input:process.stdin,output:process.stdout}),u=r.length===1?" [Enter=1]":"",d=(await l.question(`Choice [1-${r.length}]${u}: `)).trim();l.close();let f=d===""&&r.length===1?0:parseInt(d,10)-1;if(isNaN(f)||f<0||f>=r.length)console.error("Invalid choice."),process.exit(1);o=r[f].cookie}}Li(n,o),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function ra(e={}){console.error("Scanning Chrome profiles for Slack sessions...");let t=Xi();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 a=e.profile,r=t.find((i)=>i.email===a||i.profileDir===a||i.profileDir===`Profile ${a}`);if(!r)console.error(`Chrome profile "${a}" has no Slack session. Available:`),t.forEach((i)=>console.error(` - ${i.email??i.label} [${i.profileDir}] (${i.sessions.length} workspace${i.sessions.length!==1?"s":""})`)),process.exit(1);n=r}else if(t.length===1)n=t[0];else if(process.stdin.isTTY){console.log("Found Slack sessions in multiple Chrome profiles:"),t.forEach((c,l)=>console.log(` ${l+1}) ${c.email??c.label} [${c.profileDir}] (${c.sessions.length} workspace${c.sessions.length!==1?"s":""})`));let a=Ye({input:process.stdin,output:process.stdout}),r=(await a.question(`Choice [1-${t.length}]: `)).trim();a.close();let i=parseInt(r,10)-1;if(isNaN(i)||i<0||i>=t.length)console.error("Invalid choice."),process.exit(1);n=t[i]}else console.error("Multiple Chrome profiles have a Slack session — choose one with --profile:"),t.forEach((a)=>console.error(` slack auth login chrome --profile "${a.email??a.profileDir}"`)),process.exit(1);let s=n.email??n.label??n.profileDir,o;if(process.platform==="darwin")try{let{candidates:a}=Fs();o=a.find((r)=>r.profileDir===n.profileDir)?.cookie??a[0]?.cookie}catch{}if(o)ju(s,o,`chrome:${n.profileDir}`);for(let a of n.sessions){let r=a.teamName??a.teamId,i=Vn(r);Sr(i,{token:a.token,team:r,teamId:a.teamId,url:a.url??"",user:"",identity:s}),console.log(`Added workspace "${i}": ${r} (identity: ${s})`)}if(console.log(""),o)console.log(`Captured xoxd cookie for ${s} — shared across its ${n.sessions.length} workspace(s).`),console.log("RTM WebSocket mode is now available: slack tail @you");else console.log("Note: no xoxd cookie captured (LocalStorage yields the token only; the cookie is"),console.log("encrypted at rest on this platform). Some features (RTM, drafts, search fallback) need it."),console.log(" Attach it from your live browser — e.g. a CDP read via rech — or paste it:"),console.log(` slack auth cookie --workspace ${Vn(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 oa(e={}){let t=Ss();if(t.length===0)console.error("No workspaces configured. Run: slack auth login"),process.exit(1);let n;if(e.workspace){if(!t.find((i)=>i.name===e.workspace))console.error(`Workspace "${e.workspace}" not found. Available: ${t.map((i)=>i.name).join(", ")}`),process.exit(1);n=e.workspace}else if(t.length===1)n=t[0].name;else{let r=t.find((i)=>i.current);if(r)n=r.name,console.log(`Using active workspace: ${n}`);else{console.log("Multiple workspaces found. Choose one:"),t.forEach((u,d)=>console.log(` ${d+1}) ${u.name} (${u.profile.team})`));let i=Ye({input:process.stdin,output:process.stdout}),c=(await i.question("Choice: ")).trim();i.close();let l=parseInt(c,10)-1;if(isNaN(l)||l<0||l>=t.length)console.error("Invalid choice."),process.exit(1);n=t[l].name}}if(!e.yes&&!process.stdin.isTTY)console.error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes."),process.exit(1);let s=e.yes?void 0:Ye({input:process.stdin,output:process.stdout});try{if(!await Os(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}}finally{s?.close()}console.log("Scanning Firefox profiles for Slack session...");let o=Lr();if(o.length===0)console.error("No Slack session found in Firefox. Possible reasons:"),console.error(" - Firefox is not installed"),console.error(" - You are not logged in to Slack in Firefox"),process.exit(1);let a;if(o.length===1)a=o[0].cookie,console.log(`Found session in Firefox profile: ${o[0].profileName}`);else{console.log("Multiple Firefox profiles have a Slack session. Choose one:"),o.forEach((l,u)=>console.log(` ${u+1}) ${l.profileName} [${l.profileDir}]`));let r=Ye({input:process.stdin,output:process.stdout}),i=(await r.question("Choice: ")).trim();r.close();let c=parseInt(i,10)-1;if(isNaN(c)||c<0||c>=o.length)console.error("Invalid choice."),process.exit(1);a=o[c].cookie}Li(n,a),console.log(`Saved xoxd cookie to workspace "${n}".`),console.log("RTM WebSocket mode is now available: slack tail @you")}async function bd(e={}){if(e.token){await An(null,e.token,e.name);return}if(!process.stdin.isTTY){let n=[];for await(let o of process.stdin)n.push(o);let s=Buffer.concat(n).toString("utf8").trim();if(!s)console.error("No token provided on stdin."),process.exit(1);await An(null,s,e.name);return}let t=Ye({input:process.stdin,output:process.stdout});try{await md(t)}finally{t.close()}}async function wd(e={}){let t=Ye({input:process.stdin,output:process.stdout});try{if(e.bot!==void 0){await Nr(t,e.bot?"bot":"user");return}console.log("Which token type?"),console.log(" 1) User token (xoxp-) -full access including search [default]"),console.log(" 2) Bot token (xoxb-) -search and news unavailable"),console.log("");let n=await Zt(t,"Choice [1/2, Enter=1]: ");await Nr(t,n==="2"?"bot":"user")}finally{t.close()}}function Dd(e={}){let t=(o,a)=>{if(/[\r\n]/.test(a))throw Error(`Invalid newline in ${o}.`);return`${o}=${/^[A-Za-z0-9._=-]+$/.test(a)?a:JSON.stringify(a)}`},n=[t("SLACK_TOKEN",Wu(e.workspace))],s=Vt(e.workspace);if(s)n.push(t("SLACK_COOKIE",s));if(!e.workspace){let o=_r();if(o)n.push(t("SLACK_BOT_TOKEN",o))}console.log(n.join(`
|
|
230
|
+
`))}function kd(e){let t=Ss(),n=e.workspace?t.find((o)=>o.name===e.workspace):t.find((o)=>o.current)??(t.length===1?t[0]:void 0);if(!n)throw Error(e.workspace?`Workspace "${e.workspace}" not found. Run: slack auth ls`:"Select a workspace with slack auth use <name>, or pass --workspace <name>.");if(!n.profile.cookie)throw Error(`Workspace "${n.name}" has no session cookie. Run: slack auth chrome -w ${n.name} or slack auth firefox -w ${n.name}`);let s=nb(e.envfile);Pi(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 Rs(e={}){let t=Ss();if(t.length>0){console.log("Currently logged in:");for(let{name:s,profile:o,current:a}of t)console.log(` ${a?"*":" "} ${s} ${o.team} (${o.user||"unknown"})`);console.log(""),console.log("Adding another workspace:"),console.log("")}if([e.fromChrome,e.fromFirefox,e.fromAll].filter(Boolean).length>1)throw Error("Choose only one browser source: --from-chrome, --from-firefox, or --from-all.");if(e.fromChrome&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{if(!await Os(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let o=await Zi();if(o.length===0)throw Error("No Slack session token found in Chrome profiles.");await sa(o,s,!0)}finally{s?.close()}return}if(e.fromAll&&!e.fromDesktop){if(!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let s=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{try{await na(s,e.yes??!1,"all",!0)}catch(o){if(!(o instanceof Error)||!o.message.startsWith("Slack desktop app LevelDB not found"))throw o;if(!await Os(s,e.yes??!1)){console.log("Browser profile scan cancelled.");return}let a=await Zi();if(a.length===0)throw Error("No Slack session token found in Chrome profiles.");if(a.every((r)=>!r.cookie)){let r=Lr();if(r.length===1)for(let i of a)i.cookie=r[0].cookie}await sa(a,s,!0)}}finally{s?.close()}return}if(e.fromDesktop||e.fromChrome||e.fromFirefox||e.fromAll){let s=e.fromChrome?"chrome":e.fromFirefox?"firefox":e.fromAll?"all":"none";if(s!=="none"&&!e.yes&&!process.stdin.isTTY)throw Error("Reading browser profiles requires confirmation. Re-run interactively or pass --yes.");let o=process.stdin.isTTY?Ye({input:process.stdin,output:process.stdout}):void 0;try{await na(o,e.yes??!1,s,!0)}finally{o?.close()}return}if(e.token){await An(null,e.token,e.name);return}if(!process.stdin.isTTY){let s=[];for await(let a of process.stdin)s.push(a);let o=Buffer.concat(s).toString("utf8").trim();if(!o)console.error("No token provided on stdin."),process.exit(1);await An(null,o,e.name);return}console.log("How would you like to authenticate with Slack?"),console.log(""),console.log(" 1) Slack desktop app - import session token"),console.log(" Reads the xoxc- token directly from the installed app."),console.log(" Token: all platforms | xoxd cookie: macOS, or Chrome/Firefox on Linux"),console.log(""),console.log(" 2) Chrome browser - import workspaces"),console.log(" Reads xoxc- tokens from Chrome, grouped by account."),console.log(" Token: all platforms | xoxd cookie: macOS only"),console.log(""),console.log(" 3) Connect existing Slack app [recommended if you have one]"),console.log(" Paste a token from an app you already created."),console.log(""),console.log(" 4) Create new Slack app - user token (xoxp-)"),console.log(" Guided setup with manifest. Full access including search."),console.log(""),console.log(" 5) Create new Slack app - bot token (xoxb-)"),console.log(" Bot is invited to channels. Search and news unavailable."),console.log("");let n=Ye({input:process.stdin,output:process.stdout});try{let s=await Zt(n,"Choice [1/2/3/4/5]: ");if(console.log(""),s==="1")await na(n,e.yes??!1);else if(s==="2"){n.close(),await ra();return}else if(s==="3")await md(n);else if(s==="4")await Nr(n,"user");else if(s==="5")await Nr(n,"bot");else console.error(`Invalid choice: "${s}". Enter 1, 2, 3, 4, or 5.`),process.exit(1)}finally{n.close()}}async function Br(e,t,n,s){let o=t,a=[],r=o,i=0;while(!0){let c=r.indexOf("<@U",i);if(c===-1)break;let l=r.slice(c+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)a.push(d);i=c+1}for(let c of a){if(!n.has(c))n.set(c,await Xn(e,c,s));let l=n.get(c)??c;o=o.replaceAll(`<@${c}>`,`@${l}`),o=o.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${l}`)}return o}function jr(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let o=Number(n);if(!Number.isFinite(o))return s??"date";let a=new Date(o*1000);if(Number.isNaN(a.getTime()))return s??"date";let r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],i=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=r[a.getUTCDay()]??"",l=i[a.getUTCMonth()]??"";return`${c}, ${l} ${String(a.getUTCDate()).padStart(2,"0")}, ${a.getUTCFullYear()}`})}function Sd(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function lb(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),o=s.getUTCFullYear(),a=String(s.getUTCMonth()+1).padStart(2,"0"),r=String(s.getUTCDate()).padStart(2,"0"),i=String(s.getUTCHours()).padStart(2,"0"),c=String(s.getUTCMinutes()).padStart(2,"0"),l=String(s.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${o}-${a}-${r}T${i}:${c}:${l}.${u}`}async function ub(e,t,n){let s=typeof t.ts==="string"?t.ts:"0.000000",o=lb(s),a="?";if(typeof t.user==="string"){let d=t.user,f="@"+d;if(!n.has(f)){let[,p]=await Tr(e,d);n.set(f,p)}a=n.get(f)??d}else if(typeof t.username==="string")a=t.username;let r=typeof t.text==="string"?t.text:"",c=jr(await Br(e,r,n)).split(`
|
|
231
231
|
`),l=c[0]+(c.length>1?`
|
|
232
232
|
`+c.slice(1).map((d)=>` ${d}`).join(`
|
|
233
|
-
`):""),u=
|
|
234
|
-
`)}),l.addEventListener("close",()=>c()),l.addEventListener("error",()=>c()),l.addEventListener("message",(u)=>{(async()=>{try{let d;try{d=JSON.parse(String(u.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){l.send(JSON.stringify({type:"pong",reply_to:d.id??0}));return}if(f!=="message")return;if((typeof d.channel==="string"?d.channel:"")!==
|
|
233
|
+
`):""),u=Sd(t)?"↳ ":"";return`${o} ${u}@${a}: ${l}`}async function db(e,t,n,s,o,a,r,i){if(i?.aborted)return;return new Promise((c)=>{let l=new e(n);i?.addEventListener("abort",()=>{l.close(),c()},{once:!0}),l.addEventListener("open",()=>{process.stderr.write(`Connected via RTM (experimental).
|
|
234
|
+
`)}),l.addEventListener("close",()=>c()),l.addEventListener("error",()=>c()),l.addEventListener("message",(u)=>{(async()=>{try{let d;try{d=JSON.parse(String(u.data))}catch{return}let f=typeof d.type==="string"?d.type:"";if(f==="ping"){l.send(JSON.stringify({type:"pong",reply_to:d.id??0}));return}if(f!=="message")return;if((typeof d.channel==="string"?d.channel:"")!==s)return;let g=typeof d.ts==="string"?d.ts:"";if(!g||a.has(g))return;let h=typeof d.subtype==="string"?d.subtype:"";if(h==="message_changed"||h==="message_deleted")return;if(o.thread){if((typeof d.thread_ts==="string"?d.thread_ts:g)!==o.thread&&g!==o.thread)return}if(o.watchThread&&Sd(d)){if((typeof d.thread_ts==="string"?d.thread_ts:"")!==o.watchThread)return}if(o.me&&o.myUserId){if(!(typeof d.text==="string"?d.text:"").includes(`<@${o.myUserId}>`))return}if(a.add(g),a.size>1000){let m=a.values().next().value;if(m!==void 0)a.delete(m)}let b=await ub(t,d,r);process.stdout.write(b+`
|
|
235
235
|
`)}catch(d){process.stderr.write(`RTM message error: ${d instanceof Error?d.message:String(d)}
|
|
236
|
-
`)}})()})})}var
|
|
236
|
+
`)}})()})})}var xd=3,fb=2000,ia={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),clientBoot:sd,getWebSocket:()=>{let e=globalThis.WebSocket;return typeof e==="function"?e:void 0}};async function _d(e,t,n,s,o,a,r){let i=ia.getWebSocket();if(!i)return;for(let c=0;c<xd;c++){if(r?.aborted)return;try{let{wsUrl:l}=await ia.clientBoot(e,t);await db(i,e,l,n,s,o,a,r)}catch{}if(r?.aborted)return;if(c<xd-1)await ia.sleep(fb)}}function Qt(e){let t=e.match(/^(\d+(?:\.\d+)?)(s|m|h|d)$/);if(!t)throw Error(`Invalid --since format: "${e}" (expected e.g. 10m, 2h, 1d)`);let n=parseFloat(t[1]);switch(t[2]){case"s":return n;case"m":return n*60;case"h":return n*3600;case"d":return n*86400}}var yt={sleep:(e)=>new Promise((t)=>setTimeout(t,e)),now:()=>Date.now(),tailRTM:_d};function Ot(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function aa(e){return Array.isArray(e)?e:[]}function Ed(e){return Number(e)||0}function $d(e){let t=typeof e.ts==="string"?e.ts:"",n=typeof e.thread_ts==="string"?e.thread_ts:"";return n!==""&&n!==t}function pb(e){let[t,n="000000"]=e.split("."),s=new Date(Number(t)*1000),o=s.getUTCFullYear(),a=String(s.getUTCMonth()+1).padStart(2,"0"),r=String(s.getUTCDate()).padStart(2,"0"),i=String(s.getUTCHours()).padStart(2,"0"),c=String(s.getUTCMinutes()).padStart(2,"0"),l=String(s.getUTCSeconds()).padStart(2,"0"),u=n.padEnd(6,"0").slice(0,6);return`${o}-${a}-${r}T${i}:${c}:${l}.${u}`}async function hb(e,t,n,s,o){let a=typeof t.ts==="string"?t.ts:"0.000000",r=pb(a),i="?";if(typeof t.user==="string"){let g=t.user,h="@"+g;if(!n.has(h)){let[,b]=await Tr(e,g,o);n.set(h,b)}i=n.get(h)??g}else if(typeof t.username==="string")i=t.username;let c=typeof t.text==="string"?t.text:"",u=jr(await Br(e,c,n,o)).split(`
|
|
237
237
|
`),d=u[0]+(u.length>1?`
|
|
238
238
|
`+u.slice(1).map((g)=>` ${g}`).join(`
|
|
239
|
-
`):""),f
|
|
239
|
+
`):""),f=$d(t)?"↳ ":"",p=s?`${s} @${i}`:`@${i}`;return`${r} ${f}${p}: ${d}`}async function gb(e,t,n,s,o,a,r){let i=Ot(await Cn(e,t,20,r?void 0:n||void 0,r,s.cookie)),c=aa(i.messages).map(Ot).reverse(),l=Ot(i.response_metadata),u=i.has_more===!0&&typeof l.next_cursor==="string"?l.next_cursor:void 0,d=[];if(s.watchThread&&!r){let b=Ot(await Xu(e,t,s.watchThread,50,s.cookie));d=aa(b.messages).map(Ot).filter((m)=>(typeof m.ts==="string"?m.ts:"")!==s.watchThread)}let f=[...c.map((b)=>({m:b,fromHistory:!0})),...d.map((b)=>({m:b,fromHistory:!1}))].sort((b,m)=>Ed(typeof b.m.ts==="string"?b.m.ts:"")-Ed(typeof m.m.ts==="string"?m.m.ts:"")),p=[],g=n,h=!1;for(let{m:b,fromHistory:m}of f){let w=typeof b.ts==="string"?b.ts:"";if(!w||o.has(w))continue;let D=typeof b.subtype==="string"?b.subtype:"";if(D==="message_changed"||D==="message_deleted")continue;if(s.thread){if((typeof b.thread_ts==="string"?b.thread_ts:w)!==s.thread&&w!==s.thread)continue}if(s.watchThread&&$d(b)){if((typeof b.thread_ts==="string"?b.thread_ts:"")!==s.watchThread)continue}if(s.me&&s.myUserId){if(!(typeof b.text==="string"?b.text:"").includes(`<@${s.myUserId}>`))continue}if(o.add(w),o.size>1000){let E=o.values().next().value;if(E!==void 0)o.delete(E)}if(p.push(await hb(e,b,a,void 0,s.cookie)),m)g=w;let k=typeof b.user==="string"?b.user:"";if(!s.myUserId||k!==s.myUserId)h=!0}return{newCursor:g,lines:p,hasMore:i.has_more===!0,nextPageCursor:u,emittedOther:h}}function mb(e){if(e.includes("slack.com")){let t=Ui(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 Cd(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
|
|
242
|
-
`);
|
|
243
|
-
`);if(
|
|
241
|
+
Use: slack tail "#channel" --me`),process.exit(1);if(!t)console.error("Usage: slack tail <#channel|@user>\n Run `slack tail --help` for details."),process.exit(1);let o=await Fr(e,t,n.cookie),a=n.interval??60000,r=n.timeout?yt.now()+Qt(n.timeout)*1000:1/0,i=new Map,c=new Set;try{let h=Ot(await nd(e,o,n.cookie));if(Ot(h.channel).is_archived===!0)console.error("Warning: this channel is archived — no new messages will arrive.")}catch(h){let b=h instanceof Error?h.message:String(h);if(b.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(b.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(b.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: ${b}`)}let l="";if(n.since){let h=Qt(n.since);l=(yt.now()/1000-h).toFixed(6)}else{let h=Ot(await Cn(e,o,1,void 0,void 0,n.cookie)),b=aa(h.messages).map(Ot);if(b.length>0&&typeof b[0]?.ts==="string")l=b[0].ts,c.add(l);else l=(yt.now()/1000).toFixed(6)}let u;if(n.me||n.exitOnMessage)u=(await Gn(e,n.cookie)).userId||void 0;let d;if(n.watchThread!==void 0)try{d=mb(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}:{},...u!==void 0?{myUserId:u}:{},...n.cookie!==void 0?{cookie:n.cookie}:{}};if(e.startsWith("xoxc-")&&n.cookie!==void 0&&n.noRtm!==!0&&n.since===void 0&&n.timeout===void 0&&n.exitOnMessage!==!0){if(await yt.tailRTM(e,n.cookie,o,f,c,i,s),s?.aborted)return;console.error("RTM unavailable — switching to polling.")}let p=!0,g=yt.now();while(!s?.aborted){if(yt.now()>=r)return;let h=!1;try{let w=yt.now()-g,D=a>0&&w>a*5,k,E=!0;do{let{newCursor:A,lines:_,nextPageCursor:S,emittedOther:I}=await gb(e,o,l,f,c,i,k);if(l=A,p&&E&&n.since&&_.length===0)process.stdout.write(`(no messages in the last ${n.since} — watching for new)
|
|
242
|
+
`);E=!1;for(let J of _)process.stdout.write(J+`
|
|
243
|
+
`);if(I)h=!0;k=D?S:void 0}while(k);p=!1}catch(m){if(m instanceof Ke){console.error(`Warning: Slack rate limit hit — backing off for ${m.retryAfter}s`),await yt.sleep(m.retryAfter*1000);continue}throw m}if(n.exitOnMessage&&h)return;g=yt.now();let b=r-yt.now();if(b<=0)return;await yt.sleep(Math.min(a,b))}}import{existsSync as yb,mkdirSync as Od,readFileSync as ua,renameSync as bb,unlinkSync as Ad,writeFileSync as da}from"node:fs";import{dirname as Rd}from"node:path";class ca extends Error{}function Fd(e){let t=e,n=(Array.isArray(t.messages)?t.messages:[]).filter((o)=>!!o&&typeof o==="object"&&!Array.isArray(o)),s=t.has_more===!0?t.response_metadata?.next_cursor:void 0;return typeof s==="string"&&s?{messages:n,nextCursor:s}:{messages:n}}function Id(e,t){return{async listChannels(){return(await Zu(e,"public_channel,private_channel,im,mpim",t)).flatMap((s)=>{if(!s||typeof s!=="object"||Array.isArray(s)||typeof s.id!=="string")return[];let o=s.is_im===!0;return[{id:s.id,name:ae(s.name)||s.id,isIm:o,...s.is_mpim===!0?{isMpim:!0}:{},...o&&typeof s.user==="string"?{user:s.user}:{}}]})},history:async(n,s,o)=>Fd(await Cn(e,n,200,s,o,t)),replies:async(n,s,o,a)=>Fd(await Vu(e,n,s,{oldest:o,...a?{cursor:a}:{}},t)),userName:(n)=>Xn(e,n,t)}}var wb="https://github.com/snomiao/slack-term/blob/main/worker/README.md",Db=1.618,kb=25,Wr=2000,xb=8,fe={now:()=>Date.now(),sleep:(e,t)=>new Promise((n)=>{if(t?.aborted)return n();let s=()=>{clearTimeout(o),n()},o=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})}),out:(e)=>{process.stdout.write(e+`
|
|
244
244
|
`)},err:(e)=>{process.stderr.write(e+`
|
|
245
|
-
`)},pidAlive:(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}};function
|
|
246
|
-
`)}function
|
|
245
|
+
`)},pidAlive:(e)=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}};function Jr(e,t,n){return Math.min(n,Math.round(t*Math.pow(Db,Math.max(0,e-1))))}var Sb=["invalid_auth","not_authed","token_revoked","token_expired","account_inactive","no_permission"],_b=["channel_not_found","not_in_channel","missing_scope","is_archived"];class en extends Error{}function Ge(e){return e instanceof Error?e.message:String(e)}function la(e){let t=Ge(e);if(Sb.some((n)=>t.includes(n)))return"fatal";if(_b.some((n)=>t.includes(n)))return"channel";return"transient"}var ae=(e)=>typeof e==="string"?e:"",ge=(e)=>Number(e)||0,bt=(e)=>e.toFixed(6),Eb=new Set(["message_changed","message_deleted","channel_join","channel_leave","group_join","group_leave"]);function $b(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 Cb(e,t,n,s){let a=`${e.endsWith("/")?e:e+"/"}archives/${t}/p${n.replace(".","")}`;return s&&s!==n?`${a}?thread_ts=${s}&cid=${t}`:a}function Ab(e,t){if(!yb(e))return{version:1,identity:t,channels:{}};let n;try{n=JSON.parse(ua(e,"utf8"))}catch(o){throw new en(`state file ${e} is unreadable (${Ge(o)}); move it aside to start fresh`)}if(!(n&&typeof n==="object"&&n.version===1&&n.channels&&typeof n.channels==="object"&&Object.values(n.channels).every((o)=>o&&typeof o.since==="string"&&typeof o.cursor==="string"&&o.threads&&typeof o.threads==="object")))throw new en(`state file ${e} is not a slack stream state; move it aside to start fresh`);if(n.identity!==t)throw new en(`state file ${e} belongs to identity ${n.identity}, not ${t}; pass a different --state`);return n}function Rt(e,t){Od(Rd(e),{recursive:!0});let n=`${e}.tmp-${process.pid}`;da(n,JSON.stringify(t)),bb(n,e)}function Fb(e){let t=`${e}.lock`;Od(Rd(t),{recursive:!0});let n=()=>{try{if(ua(t,"utf8").trim()===String(process.pid))Ad(t)}catch{}};try{da(t,String(process.pid),{flag:"wx"})}catch{let s=Number(ua(t,"utf8").trim());if(s&&fe.pidAlive(s))throw new en(`another slack stream (pid ${s}) already uses ${e}`);Ad(t),da(t,String(process.pid),{flag:"wx"})}return n}async function Td(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 fa(e,t,n,s,o){if(Eb.has(ae(n.subtype)))return!1;let a=ae(n.user),r=ae(n.bot_id),i=e.opts.repliesTo,c=ae(n.thread_ts);if(s&&i&&c&&(i.has(a)||i.has(r))){let m=e.state.joined??={};m[`${t.id}:${c}`]=Math.max(m[`${t.id}:${c}`]??0,ge(ae(n.ts)))}if(a&&e.opts.selfUsers.has(a)||r&&e.opts.selfBots.has(r))return!1;e.opts.grep.lastIndex=0;let l=e.opts.grep.test($b(n))?"grep":s&&i&&await Tb(e,t,i,n,o)?"replies-to":void 0;if(!l)return!1;let u=ae(n.ts),d=`${t.id}:${u}`;if(e.state.seen?.[d]!==void 0)return!1;if(e.opts.relay&&!e.opts.once)(e.state.seen??={})[d]=ge(u);let f=ae(n.thread_ts)||null,p=a||r,g=a?await Td(e,a):ae(n.username)||ae(n.bot_profile?.name)||r,h=t.isIm?`@${t.user?await Td(e,t.user):t.id}`:t.isMpim?t.name:`#${t.name}`,b={type:s?"reply":"message",channel:{id:t.id,name:h},ts:u,thread_ts:f,user:{id:p,name:g},text:ae(n.text).replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&"),permalink:Cb(e.opts.teamUrl,t.id,u,f??void 0),match:l};return e.opts.json?fe.out(JSON.stringify(b)):fe.out(Ob(b)),e.opts.onMatch?.(b,Array.isArray(n.files)?n.files.length:0),e.matches++,!0}async function Tb(e,t,n,s,o){if(n.has(ae(s.parent_user_id)))return!0;let a=ae(s.thread_ts),r=vd(e,t,n,a,o);if(r!==void 0)return r;let i=`${t.id}:${a}`,c=e.notJoined?.get(i);if(c!==void 0&&c>=ge(ae(s.ts)))return!1;let l=c!==void 0?bt(c):"0";return pa(e,t,n,a,await Ur((u)=>e.client.replies(t.id,a,l,u))),e.state.joined?.[i]!==void 0}function vd(e,t,n,s,o){if(e.state.joined?.[`${t.id}:${s}`]!==void 0)return!0;if(!o)return;if(n.has(ae(o.user))||n.has(ae(o.bot_id)))return!0;let a=Array.isArray(o.reply_users)?o.reply_users.map((i)=>ae(i)):void 0;if(a?.some((i)=>n.has(i)))return!0;let r=typeof o.reply_users_count==="number"?o.reply_users_count:void 0;if(a&&(r!==void 0?r<=a.length:a.length<5))return!1;return}function pa(e,t,n,s,o){let a=`${t.id}:${s}`,r=o.filter((c)=>n.has(ae(c.user))||n.has(ae(c.bot_id))).map((c)=>ge(ae(c.ts)));if(r.length){let c=e.state.joined??={};c[a]=Math.max(c[a]??0,...r),e.notJoined?.delete(a);return}let i=Math.max(e.notJoined?.get(a)??0,...o.map((c)=>ge(ae(c.ts))));(e.notJoined??=new Map).set(a,i)}function Ob(e){let t=new Date(ge(e.ts)*1000).toISOString().replace(/\.\d+Z$/,"Z"),n=e.type==="reply"?"↳ ":"",s=e.text.split(`
|
|
247
247
|
`).join(`
|
|
248
|
-
`);return`${t} ${e.channel.name} ${n}@${e.user.name}: ${
|
|
249
|
-
${e.permalink}`}async function Co(e){let t=[],n;do{let o=await e(n);t.push(...o.messages),n=o.nextCursor}while(n);return t}async function Sm(e,t,n,o=!0){let s=e.state.channels[t.id],r=n-(e.opts.settleSec??5),i=n-e.opts.threadWindowSec,a=he(s.cursor),c=o?Math.min(a,i):a,l=(await Co((f)=>e.client.history(t.id,pt(c),f))).sort((f,h)=>he(ae(f.ts))-he(ae(h.ts))),u=e.opts.repliesTo?new Map(l.map((f)=>[ae(f.ts),f])):void 0,d=l.at(-1);if(d&&he(ae(d.ts))>he(s.latest??"0"))s.latest=ae(d.ts);if(o)s.scanned=pt(n);for(let f of l){let h=he(ae(f.ts));if(h<=a||h>r)continue;let g=ae(f.thread_ts),p=await Ni(e,t,f,g!==""&&g!==ae(f.ts),g?u?.get(g):void 0);if(s.cursor=ae(f.ts),p)Et(e.opts.statePath,e.state)}if(he(s.cursor)<r)s.cursor=pt(r);for(let f of l){let h=ae(f.ts),g=he(ae(f.latest_reply));if(!g||ae(f.thread_ts)!==h)continue;let p=he(s.threads[h]??s.since);if(g<=p)continue;let m=e.opts.repliesTo,w=m!==void 0&&Iu(e,t,m,h,f)===void 0,b=w?Math.min(p,e.notJoined?.get(`${t.id}:${h}`)??0):p,D=(await Co((S)=>e.client.replies(t.id,h,pt(b),S))).sort((S,A)=>he(ae(S.ts))-he(ae(A.ts)));if(w)Bi(e,t,m,h,D);for(let S of D){let A=he(ae(S.ts));if(ae(S.ts)===h||A<=p||A>r)continue;let F=ae(S.subtype)!=="thread_broadcast"&&await Ni(e,t,S,!0,f);if(s.threads[h]=ae(S.ts),F)Et(e.opts.statePath,e.state)}s.threads[h]=pt(Math.max(he(s.threads[h]??"0"),Math.min(g,r)))}for(let f of Object.keys(s.threads))if(he(f)<i)delete s.threads[f];Et(e.opts.statePath,e.state)}async function Em(e,t,n){let o,s,r,i=e.opts.repliesTo,a=`${t.id}:${n.thread_ts??""}`;if(i&&n.thread_ts&&e.state.joined?.[a]===void 0){let g=Math.min(e.notJoined?.get(a)??0,he(n.ts)-1),p=await Co((m)=>e.client.replies(t.id,n.thread_ts,pt(g),m));if(o=p.find((m)=>ae(m.ts)===n.ts),s=p.find((m)=>ae(m.ts)===n.thread_ts),o)Bi(e,t,i,n.thread_ts,p)}for(let g=0;g<5&&!o;g++){let p=await e.client.replies(t.id,n.thread_ts??n.ts,pt(he(n.ts)-1),r);if(o=p.messages.find((m)=>ae(m.ts)===n.ts),s??=n.thread_ts?p.messages.find((m)=>ae(m.ts)===n.thread_ts):void 0,r=p.nextCursor,!r)break}if(!o)return!1;let c=ae(o.thread_ts),l=e.state.channels[t.id],d=c!==""&&c!==n.ts&&ae(o.subtype)!=="thread_broadcast"?l?.threads[c]:l?.cursor;if(d!==void 0&&he(n.ts)<=he(d))return!0;let f=Object.keys(e.state.joined??{}).length;if(await Ni(e,t,o,c!==""&&c!==n.ts,s)||Object.keys(e.state.joined??{}).length!==f)Et(e.opts.statePath,e.state);return!0}var _m=2592000;function $m(e,t){if(!e.joined)return;for(let[n,o]of Object.entries(e.joined))if(o<t)delete e.joined[n];if(!Object.keys(e.joined).length)delete e.joined}function Cm(e,t){if(!e.seen)return;for(let[n,o]of Object.entries(e.seen))if(o<t)delete e.seen[n];if(!Object.keys(e.seen).length)delete e.seen}var Am=10;function Fm(e,t,n){if(!(t>0))return e;let o=60000/t,s=-1/0,r=async()=>{let i=fe.now();s=Math.max(s,i);let a=s-i-(Am-1)*o;if(s+=o,a>0)await fe.sleep(a,n)};return{listChannels:()=>e.listChannels(),userName:(i)=>e.userName(i),history:async(i,a,c)=>(await r(),e.history(i,a,c)),replies:async(i,a,c,l)=>(await r(),e.replies(i,a,c,l))}}function Tm(e,t,n,o){let s=n-o.windowSec,r=(f)=>t.channels[f.id],i=(f)=>r(f)?.scanned!==void 0&&he(r(f).latest??"0")<s,a=(f)=>o.once||r(f)?.scanned===void 0||n-he(r(f).scanned)>=o.periodSec,c=new Map,l=e.filter((f)=>!i(f)),u=o.once||o.periodSec<=o.intervalSec?1/0:Math.max(1,Math.ceil(l.length*o.intervalSec/o.periodSec)),d=l.filter(a).sort((f,h)=>he(r(f)?.scanned??"0")-he(r(h)?.scanned??"0")).slice(0,u);for(let f of d)c.set(f.id,"full");for(let f of e){if(c.has(f.id))continue;c.set(f.id,i(f)&&(f.isIm||f.isMpim)&&!a(f)?"skip":"cursor")}return c}async function Ou(e,t){let n=t.maxFailures??(t.once?3:12),o=t.backoffBaseMs??2000,s=t.backoffCapMs??300000,r=t.refreshEvery??10,i=t.once?void 0:t.relay;if(!i&&!t.once)fe.err(`slack stream: WARNING: polling mode (${t.pollReason??"no relay configured"}) — this is the fallback, `+`not the intended setup: matches arrive up to ${Math.round(t.intervalMs/1000)}s late (replies under older parents up to ${Math.round(Math.max(t.threadScanSec??180,t.intervalMs/1000))}s) and every cycle spends Slack API calls. For real time, deploy the relay and set SLACK_RELAY_URL + SLACK_RELAY_TOKEN: ${um}`);e=Fm(e,t.callsPerMin??40,t.signal);let a,c=new AbortController,l=()=>c.abort();t.signal?.addEventListener("abort",l,{once:!0});try{a=Dm(t.statePath);let u=bm(t.statePath,t.identity),d=t.repliesTo?[...t.repliesTo].sort().join(","):void 0;if(u.joinedBy!==d)delete u.joined;if(d)u.joinedBy=d;else delete u.joinedBy;let f={opts:t,client:e,state:u,names:new Map,matches:0},h=new Set,g=[],p=fe.now()/1000,m=p,w="",b=0,D=0,S=-1/0,A=0,F=(K)=>{fe.err(`slack stream: rate limited — waiting ${K.retryAfter}s`),A=Math.max(A,fe.now()+K.retryAfter*1000)},E=async(K)=>{if(g=(await e.listChannels()).filter((de)=>!t.channels||t.channels.includes(de.id)),t.channels){for(let de of t.channels)if(!g.some((se)=>se.id===de))throw new qt(`--channel ${de}: the identity is not a member of it`)}let j=Object.keys(u.channels).length===0;for(let de of g){if(u.channels[de.id])continue;let J=Math.min(j||D===0?K:m,t.sinceSec!==void 0?p-t.sinceSec:1/0);u.channels[de.id]={since:pt(J),cursor:pt(J),threads:{}}}m=K,Et(t.statePath,u)};if(t.sinceSec!==void 0)u.channels={},delete u.seen,delete u.relay;let x={queue:[],retry:[],inflight:void 0,onDrain:void 0,handled:0,live:void 0,full:!1},W=new AbortController,Q=()=>W.abort(),M=(K,re="")=>{if(x.live===K)return;x.live=K,fe.err(K?`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`),Q()},P=async(K)=>{let re=t.sinceSec===void 0&&u.relay?.url===K.url?{seq:u.relay.seq,...u.relay.epoch?{epoch:u.relay.epoch}:{}}:{seq:0},j=0,de=()=>x.queue.length+x.retry.length+(x.inflight?1:0);while(!c.signal.aborted){while(de()>=_o/2&&!c.signal.aborted)await new Promise((L)=>{let pe=()=>L();x.onDrain=()=>{c.signal.removeEventListener("abort",pe),L()},c.signal.addEventListener("abort",pe,{once:!0})});if(c.signal.aborted)return;let se=new AbortController,J=()=>se.abort();c.signal.addEventListener("abort",J,{once:!0});let oe=!1,z="stream closed";try{await K.subscribe(re,se.signal,{hello:(L)=>{if(j=0,L.gap)x.full=!0;if(L.gap||u.relay?.url!==K.url||u.relay.epoch!==L.epoch){u.relay={url:K.url,seq:L.seq,...L.epoch?{epoch:L.epoch}:{}},x.handled=Math.min(x.handled,L.seq);for(let pe of[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]])pe.seq=Math.min(pe.seq,L.seq)}re={seq:L.seq,...L.epoch?{epoch:L.epoch}:{}},M(!0,L.via)},bell:(L,pe)=>{if(oe)return;if(de()>=_o){fe.err(`slack stream: relay backlog over ${_o} — pausing the relay until it drains`),oe=!0,se.abort(),M(!1,"paused while its backlog drains");return}re={...re,seq:L},x.queue.push({seq:L,bell:pe,tries:0,dueMs:0}),Q()}})}catch(L){if(L instanceof Pi){if(x.live)M(!1,Xe(L));x.live=!1,fe.err(`slack stream: relay disabled for this run: ${Xe(L)} — check SLACK_RELAY_TOKEN`);return}z=Xe(L)}finally{c.signal.removeEventListener("abort",J)}if(c.signal.aborted)return;if(oe)continue;M(!1,z),j++,await fe.sleep($o(j,2000,60000),c.signal)}};if(i)P(i);let I=async(K)=>{if(t.channels&&!t.channels.includes(K.channel))return!0;let re=g.find((de)=>de.id===K.channel);if(!re){if(fe.now()/1000-m<60)return!1;await E(fe.now()/1000),re=g.find((de)=>de.id===K.channel)}let j=re&&u.channels[re.id];if(!re||!j||h.has(re.id))return!0;if(he(K.ts)<he(j.since))return!0;if(K.self&&t.selfUsers.has(K.self)){if(t.repliesTo?.has(K.self)&&K.thread_ts){let de=u.joined??={},se=`${re.id}:${K.thread_ts}`;de[se]=Math.max(de[se]??0,he(K.ts)),f.notJoined?.delete(se),Et(t.statePath,u)}return!0}return Em(f,re,K)},U=()=>{if(!u.relay||u.relay.url!==i?.url)return;let K=[...x.queue,...x.retry,...x.inflight?[x.inflight]:[]].map((re)=>re.seq);u.relay.seq=Math.max(0,K.length?Math.min(...K)-1:Math.max(u.relay.seq,x.handled))},N=async()=>{let K=fe.now(),re=x.retry.filter((se)=>se.dueMs<=K);if(re.length)x.retry=x.retry.filter((se)=>se.dueMs>K),x.queue=[...re,...x.queue].sort((se,J)=>se.seq-J.seq);let j=0;while(x.queue.length&&j<fm&&!t.signal?.aborted&&fe.now()>=A){let se=x.queue.shift();x.inflight=se,j++;let J,oe;try{J=await I(se.bell)}catch(z){if(z instanceof He){F(z),se.dueMs=A,x.retry.push(se),x.inflight=void 0;break}J=!1,oe=z}if(x.inflight=void 0,oe!==void 0&&/thread_not_found|message_not_found/.test(Xe(oe)))oe=void 0;if(oe!==void 0&&vi(oe)==="channel")fe.err(`slack stream: relay bell for ${se.bell.channel} dropped: ${Xe(oe)}`),J=!0;if(oe===void 0&&te)fe.err("slack stream: relay bell reads recovered"),te=!1;if(J)x.handled=Math.max(x.handled,se.seq);else if(oe!==void 0){if(se.fails=(se.fails??0)+1,!te)fe.err(`slack stream: relay bell for ${se.bell.channel} failed (${Xe(oe)}) — retrying`);te=!0,se.dueMs=fe.now()+$o(se.fails,1500,60000),x.retry.push(se)}else if(++se.tries>=pm)fe.err(`slack stream: relay bell for ${se.bell.channel} abandoned after ${se.tries} tries (not visible) — only the poll can find it now`),x.handled=Math.max(x.handled,se.seq);else se.dueMs=fe.now()+$o(se.tries,1500,60000),x.retry.push(se)}if(x.onDrain&&x.queue.length+x.retry.length<_o/2)x.onDrain(),x.onDrain=void 0;let de=u.relay?.seq;if(U(),j||u.relay?.seq!==de)Et(t.statePath,u)},q=()=>x.live===!0&&i?Math.max(t.intervalMs,i.reconcileMs):t.intervalMs,H=()=>{let K=fe.now();return(K>=S+q()||x.full)&&K>=A},v=()=>x.queue.length>0||x.retry.some((K)=>K.dueMs<=fe.now()),le=!1,te=!1;while(!t.signal?.aborted){if(H()&&!(le&&v())){x.full=!1;let j=fe.now()/1000;try{if(D%r===0)await E(j);let de=Math.max(0,t.threadScanSec??180),se=Tm(g.filter((J)=>!h.has(J.id)),u,j,{windowSec:t.threadWindowSec,periodSec:de,intervalSec:q()/1000,once:t.once});for(let J of g){if(t.signal?.aborted)break;if(h.has(J.id))continue;let oe=se.get(J.id)??"full";if(oe==="skip")continue;for(;;)try{let z=u.channels[J.id],L=oe==="cursor"&&z.scanned!==void 0&&he(z.latest??"0")<j-t.threadWindowSec&&j-he(z.scanned)>=de;if(await Sm(f,J,j,oe==="full"),L)z.scanned=pt(j),Et(t.statePath,u);break}catch(z){if(z instanceof He){if(F(z),await fe.sleep(A-fe.now(),t.signal),t.signal?.aborted)break;continue}if(vi(z)==="channel"){h.add(J.id),w=Xe(z),fe.err(`slack stream: skipping ${J.isIm?J.id:"#"+J.name} (${J.id}): ${Xe(z)}`);break}throw z}}if(g.length>0&&g.every((J)=>h.has(J.id)))throw new qt(`every channel failed — nothing left to watch (last: ${w})`);if(b>0)fe.err(`slack stream: recovered after ${b} failed attempt(s)`);b=0}catch(de){if(de instanceof qt||vi(de)==="fatal")return fe.err(`slack stream: fatal: ${Xe(de)}`),3;if(b++,b>=n)return fe.err(`slack stream: giving up after ${b} consecutive failures: ${Xe(de)}`),3;let se=$o(b,o,s);fe.err(`slack stream: ${Xe(de)} — reconnecting in ${(se/1000).toFixed(1)}s (attempt ${b}/${n})`),await fe.sleep(se,t.signal),x.full=!0;continue}if(D++,Cm(u,j-t.threadWindowSec-86400),$m(u,j-_m),t.once){if(Et(t.statePath,u),f.matches===0)fe.err(`slack stream: no matches in ${g.length-h.size} channel(s)`);return f.matches>0?0:2}S=j*1000,le=!0}if(t.signal?.aborted)break;let K=fe.now(),re=Math.max(A,x.queue.length||x.full?K:Math.min(S+q(),...x.retry.map((j)=>j.dueMs)));if(re>K){W=new AbortController;let j=W,de=()=>j.abort();t.signal?.addEventListener("abort",de,{once:!0}),await fe.sleep(re-K,j.signal),t.signal?.removeEventListener("abort",de)}if(H()&&!(le&&v()))continue;await N(),le=!1}return 0}catch(u){return fe.err(`slack stream: fatal: ${Xe(u)}`),3}finally{c.abort(),t.signal?.removeEventListener("abort",l),a?.()}}class Pu extends Error{}function Rm(e,t){let n;while((n=e.indexOf(`
|
|
248
|
+
`);return`${t} ${e.channel.name} ${n}@${e.user.name}: ${s}
|
|
249
|
+
${e.permalink}`}async function Ur(e){let t=[],n;do{let s=await e(n);t.push(...s.messages),n=s.nextCursor}while(n);return t}async function Rb(e,t,n,s=!0){let o=e.state.channels[t.id],a=n-(e.opts.settleSec??5),r=n-e.opts.threadWindowSec,i=ge(o.cursor),c=s?Math.min(i,r):i,l=(await Ur((f)=>e.client.history(t.id,bt(c),f))).sort((f,p)=>ge(ae(f.ts))-ge(ae(p.ts))),u=e.opts.repliesTo?new Map(l.map((f)=>[ae(f.ts),f])):void 0,d=l.at(-1);if(d&&ge(ae(d.ts))>ge(o.latest??"0"))o.latest=ae(d.ts);if(s)o.scanned=bt(n);for(let f of l){let p=ge(ae(f.ts));if(p<=i||p>a)continue;let g=ae(f.thread_ts),h=await fa(e,t,f,g!==""&&g!==ae(f.ts),g?u?.get(g):void 0);if(o.cursor=ae(f.ts),h)Rt(e.opts.statePath,e.state)}if(ge(o.cursor)<a)o.cursor=bt(a);for(let f of l){let p=ae(f.ts),g=ge(ae(f.latest_reply));if(!g||ae(f.thread_ts)!==p)continue;let h=ge(o.threads[p]??o.since);if(g<=h)continue;let b=e.opts.repliesTo,m=b!==void 0&&vd(e,t,b,p,f)===void 0,w=m?Math.min(h,e.notJoined?.get(`${t.id}:${p}`)??0):h,D=(await Ur((k)=>e.client.replies(t.id,p,bt(w),k))).sort((k,E)=>ge(ae(k.ts))-ge(ae(E.ts)));if(m)pa(e,t,b,p,D);for(let k of D){let E=ge(ae(k.ts));if(ae(k.ts)===p||E<=h||E>a)continue;let A=ae(k.subtype)!=="thread_broadcast"&&await fa(e,t,k,!0,f);if(o.threads[p]=ae(k.ts),A)Rt(e.opts.statePath,e.state)}o.threads[p]=bt(Math.max(ge(o.threads[p]??"0"),Math.min(g,a)))}for(let f of Object.keys(o.threads))if(ge(f)<r)delete o.threads[f];Rt(e.opts.statePath,e.state)}async function Ib(e,t,n){let s,o,a,r=e.opts.repliesTo,i=`${t.id}:${n.thread_ts??""}`;if(r&&n.thread_ts&&e.state.joined?.[i]===void 0){let g=Math.min(e.notJoined?.get(i)??0,ge(n.ts)-1),h=await Ur((b)=>e.client.replies(t.id,n.thread_ts,bt(g),b));if(s=h.find((b)=>ae(b.ts)===n.ts),o=h.find((b)=>ae(b.ts)===n.thread_ts),s)pa(e,t,r,n.thread_ts,h)}for(let g=0;g<5&&!s;g++){let h=await e.client.replies(t.id,n.thread_ts??n.ts,bt(ge(n.ts)-1),a);if(s=h.messages.find((b)=>ae(b.ts)===n.ts),o??=n.thread_ts?h.messages.find((b)=>ae(b.ts)===n.thread_ts):void 0,a=h.nextCursor,!a)break}if(!s)return!1;let c=ae(s.thread_ts),l=e.state.channels[t.id],d=c!==""&&c!==n.ts&&ae(s.subtype)!=="thread_broadcast"?l?.threads[c]:l?.cursor;if(d!==void 0&&ge(n.ts)<=ge(d))return!0;let f=Object.keys(e.state.joined??{}).length;if(await fa(e,t,s,c!==""&&c!==n.ts,o)||Object.keys(e.state.joined??{}).length!==f)Rt(e.opts.statePath,e.state);return!0}var vb=2592000;function Pb(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 Lb(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 Mb=10;function Nb(e,t,n){if(!(t>0))return e;let s=60000/t,o=-1/0,a=async()=>{let r=fe.now();o=Math.max(o,r);let i=o-r-(Mb-1)*s;if(o+=s,i>0)await fe.sleep(i,n)};return{listChannels:()=>e.listChannels(),userName:(r)=>e.userName(r),history:async(r,i,c)=>(await a(),e.history(r,i,c)),replies:async(r,i,c,l)=>(await a(),e.replies(r,i,c,l))}}function Bb(e,t,n,s){let o=n-s.windowSec,a=(f)=>t.channels[f.id],r=(f)=>a(f)?.scanned!==void 0&&ge(a(f).latest??"0")<o,i=(f)=>s.once||a(f)?.scanned===void 0||n-ge(a(f).scanned)>=s.periodSec,c=new Map,l=e.filter((f)=>!r(f)),u=s.once||s.periodSec<=s.intervalSec?1/0:Math.max(1,Math.ceil(l.length*s.intervalSec/s.periodSec)),d=l.filter(i).sort((f,p)=>ge(a(f)?.scanned??"0")-ge(a(p)?.scanned??"0")).slice(0,u);for(let f of d)c.set(f.id,"full");for(let f of e){if(c.has(f.id))continue;c.set(f.id,r(f)&&(f.isIm||f.isMpim)&&!i(f)?"skip":"cursor")}return c}async function Pd(e,t){let n=t.maxFailures??(t.once?3:12),s=t.backoffBaseMs??2000,o=t.backoffCapMs??300000,a=t.refreshEvery??10,r=t.once?void 0:t.relay;if(!r&&!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: ${wb}`);e=Nb(e,t.callsPerMin??40,t.signal);let i,c=new AbortController,l=()=>c.abort();t.signal?.addEventListener("abort",l,{once:!0});try{i=Fb(t.statePath);let u=Ab(t.statePath,t.identity),d=t.repliesTo?[...t.repliesTo].sort().join(","):void 0;if(u.joinedBy!==d)delete u.joined;if(d)u.joinedBy=d;else delete u.joinedBy;let f={opts:t,client:e,state:u,names:new Map,matches:0},p=new Set,g=[],h=fe.now()/1000,b=h,m="",w=0,D=0,k=-1/0,E=0,A=(q)=>{fe.err(`slack stream: rate limited — waiting ${q.retryAfter}s`),E=Math.max(E,fe.now()+q.retryAfter*1000)},_=async(q)=>{if(g=(await e.listChannels()).filter((de)=>!t.channels||t.channels.includes(de.id)),t.channels){for(let de of t.channels)if(!g.some((se)=>se.id===de))throw new en(`--channel ${de}: the identity is not a member of it`)}let U=Object.keys(u.channels).length===0;for(let de of g){if(u.channels[de.id])continue;let K=Math.min(U||D===0?q:b,t.sinceSec!==void 0?h-t.sinceSec:1/0);u.channels[de.id]={since:bt(K),cursor:bt(K),threads:{}}}b=q,Rt(t.statePath,u)};if(t.sinceSec!==void 0)u.channels={},delete u.seen,delete u.relay;let S={queue:[],retry:[],inflight:void 0,onDrain:void 0,handled:0,live:void 0,full:!1},I=new AbortController,J=()=>I.abort(),L=(q,oe="")=>{if(S.live===q)return;S.live=q,fe.err(q?`slack stream: relay connected${oe?` (${oe})`:""} — polling every ${Math.round(Math.max(t.intervalMs,r.reconcileMs)/1000)}s as a safety net`:`slack stream: relay unavailable${oe?` (${oe})`:""} — polling every ${Math.round(t.intervalMs/1000)}s`),J()},v=async(q)=>{let oe=t.sinceSec===void 0&&u.relay?.url===q.url?{seq:u.relay.seq,...u.relay.epoch?{epoch:u.relay.epoch}:{}}:{seq:0},U=0,de=()=>S.queue.length+S.retry.length+(S.inflight?1:0);while(!c.signal.aborted){while(de()>=Wr/2&&!c.signal.aborted)await new Promise((B)=>{let pe=()=>B();S.onDrain=()=>{c.signal.removeEventListener("abort",pe),B()},c.signal.addEventListener("abort",pe,{once:!0})});if(c.signal.aborted)return;let se=new AbortController,K=()=>se.abort();c.signal.addEventListener("abort",K,{once:!0});let re=!1,G="stream closed";try{await q.subscribe(oe,se.signal,{hello:(B)=>{if(U=0,B.gap)S.full=!0;if(B.gap||u.relay?.url!==q.url||u.relay.epoch!==B.epoch){u.relay={url:q.url,seq:B.seq,...B.epoch?{epoch:B.epoch}:{}},S.handled=Math.min(S.handled,B.seq);for(let pe of[...S.queue,...S.retry,...S.inflight?[S.inflight]:[]])pe.seq=Math.min(pe.seq,B.seq)}oe={seq:B.seq,...B.epoch?{epoch:B.epoch}:{}},L(!0,B.via)},bell:(B,pe)=>{if(re)return;if(de()>=Wr){fe.err(`slack stream: relay backlog over ${Wr} — pausing the relay until it drains`),re=!0,se.abort(),L(!1,"paused while its backlog drains");return}oe={...oe,seq:B},S.queue.push({seq:B,bell:pe,tries:0,dueMs:0}),J()}})}catch(B){if(B instanceof ca){if(S.live)L(!1,Ge(B));S.live=!1,fe.err(`slack stream: relay disabled for this run: ${Ge(B)} — check SLACK_RELAY_TOKEN`);return}G=Ge(B)}finally{c.signal.removeEventListener("abort",K)}if(c.signal.aborted)return;if(re)continue;L(!1,G),U++,await fe.sleep(Jr(U,2000,60000),c.signal)}};if(r)v(r);let N=async(q)=>{if(t.channels&&!t.channels.includes(q.channel))return!0;let oe=g.find((de)=>de.id===q.channel);if(!oe){if(fe.now()/1000-b<60)return!1;await _(fe.now()/1000),oe=g.find((de)=>de.id===q.channel)}let U=oe&&u.channels[oe.id];if(!oe||!U||p.has(oe.id))return!0;if(ge(q.ts)<ge(U.since))return!0;if(q.self&&t.selfUsers.has(q.self)){if(t.repliesTo?.has(q.self)&&q.thread_ts){let de=u.joined??={},se=`${oe.id}:${q.thread_ts}`;de[se]=Math.max(de[se]??0,ge(q.ts)),f.notJoined?.delete(se),Rt(t.statePath,u)}return!0}return Ib(f,oe,q)},H=()=>{if(!u.relay||u.relay.url!==r?.url)return;let q=[...S.queue,...S.retry,...S.inflight?[S.inflight]:[]].map((oe)=>oe.seq);u.relay.seq=Math.max(0,q.length?Math.min(...q)-1:Math.max(u.relay.seq,S.handled))},O=async()=>{let q=fe.now(),oe=S.retry.filter((se)=>se.dueMs<=q);if(oe.length)S.retry=S.retry.filter((se)=>se.dueMs>q),S.queue=[...oe,...S.queue].sort((se,K)=>se.seq-K.seq);let U=0;while(S.queue.length&&U<kb&&!t.signal?.aborted&&fe.now()>=E){let se=S.queue.shift();S.inflight=se,U++;let K,re;try{K=await N(se.bell)}catch(G){if(G instanceof Ke){A(G),se.dueMs=E,S.retry.push(se),S.inflight=void 0;break}K=!1,re=G}if(S.inflight=void 0,re!==void 0&&/thread_not_found|message_not_found/.test(Ge(re)))re=void 0;if(re!==void 0&&la(re)==="channel")fe.err(`slack stream: relay bell for ${se.bell.channel} dropped: ${Ge(re)}`),K=!0;if(re===void 0&&te)fe.err("slack stream: relay bell reads recovered"),te=!1;if(K)S.handled=Math.max(S.handled,se.seq);else if(re!==void 0){if(se.fails=(se.fails??0)+1,!te)fe.err(`slack stream: relay bell for ${se.bell.channel} failed (${Ge(re)}) — retrying`);te=!0,se.dueMs=fe.now()+Jr(se.fails,1500,60000),S.retry.push(se)}else if(++se.tries>=xb)fe.err(`slack stream: relay bell for ${se.bell.channel} abandoned after ${se.tries} tries (not visible) — only the poll can find it now`),S.handled=Math.max(S.handled,se.seq);else se.dueMs=fe.now()+Jr(se.tries,1500,60000),S.retry.push(se)}if(S.onDrain&&S.queue.length+S.retry.length<Wr/2)S.onDrain(),S.onDrain=void 0;let de=u.relay?.seq;if(H(),U||u.relay?.seq!==de)Rt(t.statePath,u)},j=()=>S.live===!0&&r?Math.max(t.intervalMs,r.reconcileMs):t.intervalMs,z=()=>{let q=fe.now();return(q>=k+j()||S.full)&&q>=E},M=()=>S.queue.length>0||S.retry.some((q)=>q.dueMs<=fe.now()),ce=!1,te=!1;while(!t.signal?.aborted){if(z()&&!(ce&&M())){S.full=!1;let U=fe.now()/1000;try{if(D%a===0)await _(U);let de=Math.max(0,t.threadScanSec??180),se=Bb(g.filter((K)=>!p.has(K.id)),u,U,{windowSec:t.threadWindowSec,periodSec:de,intervalSec:j()/1000,once:t.once});for(let K of g){if(t.signal?.aborted)break;if(p.has(K.id))continue;let re=se.get(K.id)??"full";if(re==="skip")continue;for(;;)try{let G=u.channels[K.id],B=re==="cursor"&&G.scanned!==void 0&&ge(G.latest??"0")<U-t.threadWindowSec&&U-ge(G.scanned)>=de;if(await Rb(f,K,U,re==="full"),B)G.scanned=bt(U),Rt(t.statePath,u);break}catch(G){if(G instanceof Ke){if(A(G),await fe.sleep(E-fe.now(),t.signal),t.signal?.aborted)break;continue}if(la(G)==="channel"){p.add(K.id),m=Ge(G),fe.err(`slack stream: skipping ${K.isIm?K.id:"#"+K.name} (${K.id}): ${Ge(G)}`);break}throw G}}if(g.length>0&&g.every((K)=>p.has(K.id)))throw new en(`every channel failed — nothing left to watch (last: ${m})`);if(w>0)fe.err(`slack stream: recovered after ${w} failed attempt(s)`);w=0}catch(de){if(de instanceof en||la(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 se=Jr(w,s,o);fe.err(`slack stream: ${Ge(de)} — reconnecting in ${(se/1000).toFixed(1)}s (attempt ${w}/${n})`),await fe.sleep(se,t.signal),S.full=!0;continue}if(D++,Lb(u,U-t.threadWindowSec-86400),Pb(u,U-vb),t.once){if(Rt(t.statePath,u),f.matches===0)fe.err(`slack stream: no matches in ${g.length-p.size} channel(s)`);return f.matches>0?0:2}k=U*1000,ce=!0}if(t.signal?.aborted)break;let q=fe.now(),oe=Math.max(E,S.queue.length||S.full?q:Math.min(k+j(),...S.retry.map((U)=>U.dueMs)));if(oe>q){I=new AbortController;let U=I,de=()=>U.abort();t.signal?.addEventListener("abort",de,{once:!0}),await fe.sleep(oe-q,U.signal),t.signal?.removeEventListener("abort",de)}if(z()&&!(ce&&M()))continue;await O(),ce=!1}return 0}catch(u){return fe.err(`slack stream: fatal: ${Ge(u)}`),3}finally{c.abort(),t.signal?.removeEventListener("abort",l),i?.()}}class Ld extends Error{}function jb(e,t){let n;while((n=e.indexOf(`
|
|
250
250
|
|
|
251
|
-
`))>=0){let
|
|
252
|
-
`)){if(!
|
|
253
|
-
`),
|
|
254
|
-
`),(w,
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
251
|
+
`))>=0){let s=e.slice(0,n);e=e.slice(n+2);let o="message",a,r=[];for(let i of s.split(`
|
|
252
|
+
`)){if(!i||i.startsWith(":"))continue;let c=i.indexOf(":"),l=c<0?i:i.slice(0,c),u=c<0?"":i.slice(c+1).replace(/^ /,"");if(l==="event")o=u;else if(l==="data")r.push(u);else if(l==="id")a=u}if(r.length)t(o,r.join(`
|
|
253
|
+
`),a)}return e}var Wb="slack-term-relay.v1";function Jb(e){return`bearer.${Buffer.from(e,"utf8").toString("base64url")}`}function Md(e){return e==="websocket"||e==="sse"?e:"auto"}var Ub=32;function Nd(e){return e===void 0?"":`?after=${e.seq}${e.epoch?`&epoch=${encodeURIComponent(e.epoch)}`:""}`}function Bd(e,t,n=70000,s={}){let o=e.replace(/\/+$/,""),a=s.transport??"auto",r=qb(o,t,n);return async(i,c,l)=>{let u=s.WebSocket===void 0?globalThis.WebSocket:s.WebSocket;if(a!=="sse")if(!u){if(a==="websocket")throw Error("relay: this runtime has no WebSocket")}else{if(await Kb(u,o,t,n,s.pingMs??25000,s.ackDelayMs??100,i,c,l)||c.aborted)return;if(a==="websocket")throw Error("relay: WebSocket connection failed")}return r(i,c,l)}}function Kb(e,t,n,s,o,a,r,i,c){return new Promise((l,u)=>{if(i.aborted)return l(!0);let d;try{d=new e(`${t.replace(/^http/i,"ws")}/ws${Nd(r)}`,[Wb,Jb(n)])}catch{return l(!1)}let f=!1,p=!1,g,h,b,m=0,w=0,D=(_)=>{if(p)return;p=!0,clearTimeout(g),clearTimeout(h),clearInterval(b),i.removeEventListener("abort",k),d.onopen=d.onmessage=d.onerror=d.onclose=null;try{d.close(1000)}catch{}if(_)u(_);else l(f||i.aborted)},k=()=>D();i.addEventListener("abort",k,{once:!0});let E=()=>{clearTimeout(g),g=setTimeout(()=>D(f?Error(`relay: no data for ${Math.round(s/1000)}s`):void 0),s)},A=()=>{if(clearTimeout(h),h=void 0,m<=w)return;w=m;try{d.send(JSON.stringify({type:"ack",seq:m}))}catch{}};E(),d.onopen=()=>{f=!0,E(),b=setInterval(()=>{try{d.send("ping")}catch{}},o)},d.onmessage=(_)=>{if(E(),typeof _.data!=="string"||_.data==="pong")return;let S;try{S=JSON.parse(_.data)}catch(I){return D(I)}if(S.type==="hello"){let{type:I,...J}=S;m=w=J.seq,c.hello({...J,via:"websocket"})}else if(S.type==="bell"&&typeof S.seq==="number"){if(c.bell(S.seq,S.bell),p)return;if(m=Math.max(m,S.seq),m-w>=Ub)A();else h??=setTimeout(A,a)}},d.onerror=()=>{},d.onclose=(_)=>{if(!f||_.code===1000)return D();D(Error(`relay: WebSocket closed (${_.code}${_.reason?` ${_.reason}`:""})`))}})}function qb(e,t,n){return async(s,o,a)=>{let r=new AbortController,i=()=>r.abort();o.addEventListener("abort",i,{once:!0});let c,l=!1,u=()=>{clearTimeout(c),c=setTimeout(()=>{l=!0,r.abort()},n)};try{u();let d=await fetch(`${e}/stream${Nd(s)}`,{headers:{authorization:`Bearer ${t}`,accept:"text/event-stream"},signal:r.signal});if(d.status===401)throw new Ld("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:b}=await f.read();if(h)return;u(),g=jb((g+p.decode(b,{stream:!0})).replace(/\r\n/g,`
|
|
254
|
+
`),(m,w,D)=>{let k=JSON.parse(w);if(m==="hello")a.hello({...k,via:"sse"});else if(m==="bell"&&D!==void 0)a.bell(Number(D),k)})}}catch(d){if(o.aborted)return;if(l)throw Error(`relay: no data for ${Math.round(n/1000)}s`);throw d}finally{clearTimeout(c),o.removeEventListener("abort",i)}}}import{existsSync as zb,mkdirSync as Yb,writeFileSync as Gb}from"node:fs";import{basename as Xb,join as ha,resolve as Wd}from"node:path";import{randomBytes as Vb}from"node:crypto";var jd={name:"slack-term",version:"1.49.0",repository:{type:"git",url:"https://github.com/snomiao/slack-term.git"},bugs:{url:"https://github.com/snomiao/slack-term/issues"},devDependencies:{"@semantic-release/commit-analyzer":"^13","@semantic-release/github":"^12","@semantic-release/npm":"^13","@semantic-release/release-notes-generator":"^14","@types/bun":"latest","@types/node":"^22","@types/yargs":"^17.0.35","@typescript/native-preview":"^7.0.0-dev.20260707.2","@vitest/coverage-istanbul":"4.1.10","semantic-release":"^24",typescript:"^5.6",vitest:"4.1.10"},bin:{slack:"./ts/cli.ts"},exports:{"./worker":"./worker/src/index.ts","./package.json":"./package.json"},description:"Slack CLI — read activity/news/mentions, search, send messages with a confirm-hash safety gate.",engines:{node:">=18"},files:["ts/","locales/","dist/","worker/src/","README.md","SKILL.md","LICENSE"],homepage:"https://github.com/snomiao/slack-term",keywords:["slack","cli","messaging","agent","terminal"],license:"MIT",overrides:{"@semantic-release/npm":"^13","@semantic-release/github":"^12"},publishConfig:{access:"public",bin:{slack:"./dist/cli.js"}},scripts:{dev:"bun run ts/cli.ts",build:"bun build ts/cli.ts --target=node --outfile dist/cli.js --minify",typecheck:"tsgo --noEmit","typecheck:tsc":"tsc --noEmit","typecheck:worker":"bun install --cwd worker --frozen-lockfile && tsgo --noEmit -p worker",test:"bun test tests/ --timeout 90000 --parallel=2","test:watch":"bun test tests/ --timeout 90000 --isolate --watch","test:parity":"bash tests/parity.sh",record:"bun run tests/record.ts",anonymize:"bun run tests/anonymize.ts","scan-pii":"bash .githooks/pre-commit","scan-pii:all":"bash .githooks/pre-commit --all",prepare:"git config core.hooksPath .githooks 2>/dev/null || true",prepublishOnly:"bun run scan-pii:all && bun run typecheck && bun run build","test:coverage":"vitest run --coverage --exclude tests/parity.test.ts --no-file-parallelism"},type:"module",dependencies:{yargs:"^18.0.0"},peerDependencies:{"@cloudflare/workers-types":"^4"},peerDependenciesMeta:{"@cloudflare/workers-types":{optional:!0}}};var Zb="4.105.0",Qb="2026-07-01",ga="slack-term-relay",ew="https://github.com/snomiao/slack-term/blob/main/worker/README.md";function tw(e){return/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(e)}function nw(e){return Xb(Wd(e)).toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,63).replace(/-+$/,"")||ga}function sw(e,t={}){let n={name:e,private:!0,type:"module",scripts:{deploy:"wrangler deploy",dev:"wrangler dev --local"},dependencies:{"slack-term":t.slackTerm??`^${jd.version}`},devDependencies:{wrangler:Zb},engines:{node:">=22"}};return{"package.json":`${JSON.stringify(n,null,2)}
|
|
255
|
+
`,"wrangler.jsonc":`// slack-term relay: Slack Events API -> doorbells for \`slack stream\`.
|
|
256
|
+
// Secrets (not in this file): wrangler secret put SLACK_SIGNING_SECRET / RELAY_TOKEN / SLACK_TEAM_ID (optional)
|
|
257
|
+
{
|
|
258
|
+
"$schema": "node_modules/wrangler/config-schema.json",
|
|
259
|
+
"name": ${JSON.stringify(e)},
|
|
260
|
+
"main": "src/index.ts",
|
|
261
|
+
"compatibility_date": "${Qb}",
|
|
262
|
+
"durable_objects": {
|
|
263
|
+
"bindings": [{ "name": "RELAY", "class_name": "Relay" }]
|
|
264
|
+
},
|
|
265
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["Relay"] }],
|
|
266
|
+
// Request bodies are message events from possibly customer-facing channels:
|
|
267
|
+
// keep Workers Logs off so nothing about them is persisted by the platform.
|
|
268
|
+
"observability": { "enabled": false }
|
|
269
|
+
}
|
|
270
|
+
`,"src/index.ts":`// The relay lives in the slack-term package. Relay (the Durable Object class)
|
|
271
|
+
// must be exported from this main module for the RELAY binding to find it.
|
|
272
|
+
export { default, Relay } from "slack-term/worker";
|
|
273
|
+
`,".gitignore":`node_modules/
|
|
274
|
+
.wrangler/
|
|
275
|
+
.dev.vars*
|
|
276
|
+
.env*
|
|
277
|
+
`,"README.md":rw(e)}}function Jd(e,t){let n=t??"<RELAY_TOKEN>";return`1. Node >= 22 (wrangler 4 needs it), then install:
|
|
278
|
+
npm install
|
|
279
|
+
2. Log in to Cloudflare:
|
|
280
|
+
npx wrangler login
|
|
281
|
+
or set CLOUDFLARE_API_TOKEN (Workers Scripts: Edit) and CLOUDFLARE_ACCOUNT_ID.
|
|
282
|
+
3. Deploy, then set the secrets:
|
|
283
|
+
npx wrangler deploy
|
|
284
|
+
npx wrangler secret put SLACK_SIGNING_SECRET # Slack app -> Basic Information -> Signing Secret
|
|
285
|
+
npx wrangler secret put RELAY_TOKEN # paste: ${n}
|
|
286
|
+
npx wrangler secret put SLACK_TEAM_ID # optional: accept one workspace only (T...)
|
|
287
|
+
4. In the Slack app -> Event Subscriptions: Enable Events, Request URL
|
|
288
|
+
https://${e}.<your-subdomain>.workers.dev/slack/events
|
|
289
|
+
and subscribe to bot events: message.channels, message.groups, message.im,
|
|
290
|
+
app_mention (and message.mpim if the bot has mpim:history). Save; reinstall if asked.
|
|
291
|
+
5. Where \`slack stream\` runs:
|
|
292
|
+
export SLACK_RELAY_URL=https://${e}.<your-subdomain>.workers.dev
|
|
293
|
+
export SLACK_RELAY_TOKEN=${n}
|
|
294
|
+
6. Check it:
|
|
295
|
+
slack relay health # or: curl -H "Authorization: Bearer $SLACK_RELAY_TOKEN" $SLACK_RELAY_URL/health
|
|
296
|
+
slack stream -e . # stderr says: relay connected (websocket)
|
|
297
|
+
`}function rw(e){return`# ${e}
|
|
298
|
+
|
|
299
|
+
A [slack-term](https://github.com/snomiao/slack-term) relay: a Cloudflare Worker
|
|
300
|
+
that turns Slack's Events API into a resumable doorbell stream for
|
|
301
|
+
\`slack stream\`. The code is the \`slack-term/worker\` export; this folder only
|
|
302
|
+
configures and deploys it. Created by \`slack relay init\`.
|
|
303
|
+
|
|
304
|
+
## Set up
|
|
305
|
+
|
|
306
|
+
${Jd(e)}
|
|
307
|
+
\`RELAY_TOKEN\` is any long random string (\`openssl rand -hex 32\`); \`slack relay init\`
|
|
308
|
+
printed one. Keep it out of this folder: anyone holding it can watch when and
|
|
309
|
+
where messages are posted.
|
|
263
310
|
|
|
264
|
-
|
|
311
|
+
## Update
|
|
265
312
|
|
|
266
|
-
|
|
313
|
+
Bump \`slack-term\` in package.json, \`npm install\`, \`npx wrangler deploy\`.
|
|
314
|
+
Storage survives redeploys; clients reconnect and resume.
|
|
267
315
|
|
|
268
|
-
|
|
269
|
-
${r.
|
|
270
|
-
${r.
|
|
316
|
+
Details (endpoints, privacy, protocol): ${ew}
|
|
317
|
+
`}function Ud(e,t={},n=Vb){let s=t.name??nw(e);if(!tw(s))return{ok:!1,error:`invalid worker name "${s}": use lowercase letters, digits and dashes (1-63 chars, no leading/trailing dash)`};let o=sw(s,t.slackTerm!==void 0?{slackTerm:t.slackTerm}:{}),a=Wd(e),r=Object.keys(o).filter((i)=>zb(ha(a,i)));if(r.length&&!t.force)return{ok:!1,error:`refusing to overwrite existing files in ${a} (pass --force to replace them)`,existing:r};for(let[i,c]of Object.entries(o)){let l=ha(a,i);Yb(ha(l,".."),{recursive:!0}),Gb(l,c)}return{ok:!0,dir:a,name:s,written:Object.keys(o),token:n(32).toString("hex")}}function Kd(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}`,Jd(e.name,e.token)].join(`
|
|
318
|
+
`)}async function qd(e,t,n=fetch,s=1e4){if(!e||!t)return{code:2,out:"slack relay health: set SLACK_RELAY_URL and SLACK_RELAY_TOKEN (or pass --url / --token)"};let o=`${e.replace(/\/+$/,"")}/health`;try{let a=await n(o,{headers:{authorization:`Bearer ${t}`},signal:AbortSignal.timeout(s)}),r=await a.text();if(a.status===401)return{code:1,out:"slack relay health: 401 unauthorized — SLACK_RELAY_TOKEN does not match the relay's RELAY_TOKEN secret"};if(!a.ok)return{code:1,out:`slack relay health: HTTP ${a.status} from ${o}${r?`: ${r.slice(0,200)}`:""}`};let i;try{i=JSON.parse(r)}catch{return{code:1,out:`slack relay health: not a slack-term relay (non-JSON reply from ${o})`}}return{code:i.ok===!0?0:1,out:JSON.stringify(i,null,2)}}catch(a){return{code:1,out:`slack relay health: cannot reach ${o}: ${a instanceof Error?a.message:String(a)}`}}}import{spawn as ow}from"node:child_process";import{constants as Hd}from"node:os";var iw=["processing","active","suspended","closed"];function zd(e){if(e!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw Error("--bot-token-env must name an environment variable, not contain a token.");let t=e===void 0?_r():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 Yd(e){if(e!==void 0&&(!e.trim()||[...e].length>200))throw Error("--title must contain 1–200 characters.")}async function Gd(e,t,n){let{ref:s,threadTs:o}=n(t);if(!o||!/^\d{10}\.\d{6}$/.test(o))throw Error("Target must include a thread root: C00000001:1700000000.000100, #channel:ts, or a message permalink.");return{channel_id:await Fr(e,s),thread_ts:o}}function ma(e,t){console.error(`agent: ${e}: ${t instanceof Error?t.message:"request failed"}`)}async function aw(e,t,n,s){let o,a,r,i,c,l=!1,u=!1,d=1,f=(h)=>{if(a)return;if(a=h,l=!0,o&&o.exitCode===null&&o.signalCode===null)o.kill(h),r=setTimeout(()=>o?.kill("SIGKILL"),5000)},p=()=>f("SIGINT"),g=()=>f("SIGTERM");process.on("SIGINT",p),process.on("SIGTERM",g);try{if(u=!0,await Es(e,t,"processing"),!l&&s.title!==void 0)await Wi(e,t,s.title);if(!l){o=ow(n[0],n.slice(1),{stdio:"inherit"});let h=new Promise((b)=>{o.once("error",()=>{console.error("agent: could not start command"),b(127)}),o.once("exit",(m,w)=>{b(m??(w?128+Hd.signals[w]:1))})});i=setInterval(()=>{if(l||c)return;c=Es(e,t,"processing").then(()=>{}).catch((b)=>ma("heartbeat failed; retrying on next tick",b)).finally(()=>{c=void 0})},s.every*1000),d=await h}}catch(h){ma("could not start agent session",h)}finally{if(l=!0,clearInterval(i),clearTimeout(r),await c,u)try{await Es(e,t,s.close?"closed":"active")}catch(h){if(ma("final status clear failed",h),d===0)d=1}process.removeListener("SIGINT",p),process.removeListener("SIGTERM",g)}return a?128+Hd.signals[a]:d}function Xd(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:iw,demandOption:!0}),async(s)=>{Yd(s.title);let o=zd(s["bot-token-env"]),a=await Gd(o,s.target,t);if(await Es(o,a,s.status),s.title!==void 0)await Wi(o,a,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(Yd(s.title),!Number.isFinite(s.every)||s.every<=0||s.every>=3600)throw Error("--every must be greater than 0 and less than 3600 seconds.");let o=process.argv.indexOf("--"),a=o<0?[]:process.argv.slice(o+1);if(!a[0])throw Error("agent run requires -- <command...>");let r=zd(s["bot-token-env"]),i=await Gd(r,s.target,t);process.exitCode=await aw(r,i,a,{every:s.every,close:s.close,...s.title!==void 0?{title:s.title}:{}})}).demandCommand(1,"Choose agent status or agent run.")}import{readdirSync as Sw,readFileSync as _w,statSync as Ew}from"node:fs";import{join as Ea}from"node:path";import{fileURLToPath as $w}from"node:url";import{closeSync as cw,existsSync as Vd,mkdirSync as Qd,openSync as lw,readFileSync as Kr,realpathSync as uw,renameSync as dw,statSync as wa,unlinkSync as Zd,writeFileSync as fw}from"node:fs";import{homedir as ef}from"node:os";import{dirname as Da,join as ut,resolve as ya}from"node:path";var pw=".slack-term";function ka(){return process.env.SLACK_TERM_HOME??ut(ef(),".config","slack-term")}function tf(e=process.cwd()){let t=ya(e);for(;;){let n=ut(t,pw);try{if(wa(n).isDirectory())return{dir:n,global:!1}}catch{}let s=Da(t);if(s===t)break;t=s}return{dir:ka(),global:!0}}function Qn(e,t){Qd(Da(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;fw(n,t,{mode:384}),dw(n,e)}function hw(e,t,n=1e4,s=5000){let o=`${e}.lock`;Qd(Da(o),{recursive:!0});let a=Date.now()+s;for(;;)try{cw(lw(o,"wx"));break}catch(r){if(r.code!=="EEXIST")throw r;try{if(Date.now()-wa(o).mtimeMs>n){Zd(o);continue}}catch{continue}if(Date.now()>a)throw Error(`${o} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{Zd(o)}catch{}}}function gw(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 Zn(e){let t;try{t=Bun.YAML.parse(Kr(e,"utf8"))}catch(o){if(o.code==="ENOENT")return{};throw Error(`${e}: ${o instanceof Error?o.message:String(o)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((o)=>typeof o==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let o={};for(let[a,r]of Object.entries(n.subscriptions)){let i=gw(r);if(i&&nf(a))o[a]=i}s.subscriptions=o}return s}function xa(e){let t=Zn(ut(e.dir,"settings.yml")),n=Zn(ut(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},o={...t,...n};if(Object.keys(s).length)o.subscriptions=s;else delete o.subscriptions;return o}var mw=/^[a-z0-9][a-z0-9._-]{0,63}$/;function nf(e){return mw.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function sf(e){let t=Zn(ut(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:Zn(ut(e.dir,"settings.local.yml")).subscriptions??{},o=[];for(let[a,r]of Object.entries(n))if(!s[a])o.push({...r,name:a,scope:e,file:"settings.yml"});for(let[a,r]of Object.entries(s))o.push({...r,name:a,scope:e,file:"settings.local.yml"});return o.sort((a,r)=>a.name.localeCompare(r.name))}var yw="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function bw(e){try{let t=Kr(e,"utf8").split(`
|
|
319
|
+
`),n=[];for(let s of t)if(s.startsWith("#")||!s.trim()&&n.length)n.push(s);else break;return n.length?n.join(`
|
|
320
|
+
`).replace(/\n*$/,`
|
|
321
|
+
`):""}catch{return""}}function ww(e,t,n){let s=ut(e.dir,t?"settings.yml":"settings.local.yml");hw(s,()=>{let o=t?bw(s):yw,a={};try{let r=Bun.YAML.parse(Kr(s,"utf8"));if(r&&typeof r==="object"&&!Array.isArray(r))a=r}catch(r){if(r.code!=="ENOENT")throw Error(`${s}: ${r instanceof Error?r.message:String(r)}`)}n(a),Qn(s,o+Bun.YAML.stringify(a,null,2)+`
|
|
322
|
+
`)})}function rf(e){return Zn(ut(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function Dw(e,t=process.cwd()){if(!rf(e))return;let n=Zn(ut(e.dir,"settings.yml")).owner;if(!n)return`${e.dir} is restricted and names no \`owner\` in settings.yml: nobody may write it with --shared (edit the file)`;let s=(r)=>{try{return uw(ya(r))}catch{return ya(r)}},o=s(n.replace(/^~(?=\/|$)/,ef())),a=s(t);if(a===o||a.startsWith(o.endsWith("/")?o:o+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function of(e,t,n,s={}){let o=typeof s==="boolean"?{shared:s}:s,a=o.shared===!0;if(!nf(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!a&&rf(e))throw new ba(e);if(a&&!o.asOwner){let i=Dw(e,o.cwd);if(i)throw new ba(e,i)}let r=sf(e).find((i)=>i.name===t);return ww(e,a,(i)=>{let c=i.subscriptions&&typeof i.subscriptions==="object"?i.subscriptions:{};c[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},i.subscriptions=c}),r}class ba 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 kw(){return ut(ka(),"scopes")}function xw(){try{return Kr(kw(),"utf8").split(`
|
|
323
|
+
`).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function Sa(){let e=[];for(let s of xw())try{if(wa(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=ka();if((Vd(ut(t,"settings.yml"))||Vd(ut(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function _a(e,t,n=Sa()){let s=[];for(let o of n)for(let a of sf(o))if(a.channel===e&&(a.thread_ts===void 0||a.thread_ts===t))s.push(a);return s}var lf=$w(new URL("../locales/",import.meta.url)),af=new Map;function cf(e){let t;try{t=Ew(e).mtimeMs}catch{return}let n=af.get(e);if(n&&n.mtimeMs===t)return n.pack;let s;try{let o=JSON.parse(_w(e,"utf8"));s=o&&typeof o.lang==="string"?o:void 0}catch{s=void 0}return af.set(e,{mtimeMs:t,pack:s}),s}function uf(){let e=tf();return e.global?void 0:Ea(e.dir,"locales")}function Cw(){let e=new Set;for(let t of[lf,uf()]){if(!t)continue;try{for(let n of Sw(t))if(n.endsWith(".json"))e.add(n.slice(0,-5))}catch{}}return[...e].sort()}function qr(e){let t=cf(Ea(lf,`${e}.json`)),n=uf(),s=n?cf(Ea(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 Hr(e,t,n={}){let s=qr(e)?.ask??{},o=s[t]??s[`${t} (WIRE)`]??qr("en")?.ask?.[t]??qr("en")?.ask?.[`${t} (WIRE)`];if(o===void 0)throw Error(`language pack ${e}: no ask.${t}`);return o.replace(/\{(\w+)\}/g,(a,r)=>(r in n)?String(n[r]):a)}function df(){let e=[];for(let t of Cw())for(let n of qr(t)?.choice_patterns??[])try{e.push({lang:t,re:new RegExp(n,"iu")})}catch{}return e}var Te=[{name:"one",glyph:"1️⃣"},{name:"two",glyph:"2️⃣"},{name:"three",glyph:"3️⃣"},{name:"four",glyph:"4️⃣"},{name:"five",glyph:"5️⃣"},{name:"six",glyph:"6️⃣"},{name:"seven",glyph:"7️⃣"},{name:"eight",glyph:"8️⃣"},{name:"nine",glyph:"9️⃣"},{name:"keycap_ten",glyph:"\uD83D\uDD1F"}],It=Te.length,st="question",tn=`:${st}: `,vt="heavy_plus_sign",zr=`:${vt}: `,gf=[vt,st],nn="information_source",Yr=`:${nn}: `,Et=["ja","en"];function Aa(e,t=process.env){for(let[a,r]of[[e.flag,"flag"],[t.SLACK_TERM_LANG,"env"]]){if(a===void 0||a.trim()==="")continue;let i=a.trim().toLowerCase();return Et.includes(i)?{lang:i,source:r}:null}let n=(e.readerLocales??[]).map(ff);if(n.length&&n[0]&&n.every((a)=>a===n[0]))return{lang:n[0],source:"readers"};let s=Fa((e.content??[]).join(`
|
|
324
|
+
`));if(s)return{lang:s,source:"content"};let o=ff(t.LC_ALL||t.LC_MESSAGES||t.LANG);if(o)return{lang:o,source:"system"};return{lang:"en",source:"default"}}function ff(e){let t=(e??"").toLowerCase();return Et.find((n)=>t===n||/^[_.\-@]/.test(t.slice(n.length))&&t.startsWith(n))??null}function Fa(e){let t=e.replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ").replace(/:[a-z0-9_+-]+:/g," ");if(/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u.test(t))return"ja";if(/\p{Script=Latin}/u.test(t))return"en";return null}var Me={get ja(){return pf("ja")},get en(){return pf("en")}};function pf(e){let t=(n,s)=>Hr(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${zr}${t("otherThread")}`,otherHere:`${zr}${t("otherHere")}`,explainLine:`${Yr}${t("explainLine")}`,explainNote:`${Yr}${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 Aw=Et.flatMap((e)=>[Me[e].otherThread,Me[e].otherHere].map((t)=>tn+t.slice(zr.length)));function mf(e){if(e===void 0)return null;if(e.startsWith(zr)||e.startsWith("➕ "))return vt;if(e.startsWith(tn)||e.startsWith("❓ "))return st;return null}function Fw(e){return e!==void 0&&(e.startsWith(Yr)||e.startsWith("ℹ️ "))}function Tw(e,t){if(e===void 0)return!1;return(e.startsWith("ℹ️ ")?Yr+e.slice(3):e)===t.explainLine}var Gr="_";function yf(e){if(e===void 0||!e.endsWith(Gr))return null;return Et.find((t)=>e.startsWith(Me[t].invalidPrefix))??null}function Xr(e){let t=e.split(`
|
|
325
|
+
`),n=t[t.length-2];if(!yf(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function Vr(e,t,n="ja"){let s=e.split(`
|
|
326
|
+
`);if(s.length<2)return e;if(Xr(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${Me[n].invalidPrefix}${t.map((a)=>`<@${a}>`).join(", ")}${Gr}`);let o=s.join(`
|
|
327
|
+
`);return o===e?e:o}function Zr(e){return typeof e==="string"&&Et.some((t)=>Me[t].explainNote===e.trim())}function hf(e){return yf(e)!==null}var Ta="white_check_mark",vs=`:${Ta}: `,Oa="no_entry_sign",Ca=`:${Oa}: `,Ow=/^【[^】]*(?:作废|作廢|superseded|void)[^】]*】/i;function Qr(e){return`:${Te[e].name}:`}function bf(e,t){let n=Te[t];for(let s of[Qr(t),n.glyph]){if(e.startsWith(`${s} `))return e.slice(s.length+1);if(e===s)return""}return null}function Rw(e){return Te.some((t,n)=>bf(e,n)!==null)}function Le(e){return e.replace(/\s*\n\s*/g," ")}function Ra(e,t,n,s,o,a="ja",r=!1){let i=Me[a],c=[`${tn}*${e}*`];if(t)c.push("",t);if(n.length){if(c.push(""),c.push(...n.map((l,u)=>`${Qr(u)} ${Le(l)}`)),c.push(o?i.otherThread:i.otherHere),r)c.push(i.explainLine);if(s.length)c.push(""),c.push(...s.map((l,u)=>`(${u+11}) ${Le(l)}`)),c.push(i.overflowNote);c.push(""),c.push(o?i.instructionReactionThread:i.instructionReactionHere)}else{if(c.push(""),r)c.push(i.explainLine,"");c.push(o?i.instructionTextThread:i.instructionTextHere)}return c.join(`
|
|
328
|
+
`)}function wf(e,t,n,s="ja",o){let a=t.answer.split(`
|
|
329
|
+
`).map((i)=>`> ${i}`).join(`
|
|
330
|
+
`),r=`${vs}*${e}*
|
|
331
|
+
${Me[s].answeredVia(t.how,n)}
|
|
271
332
|
|
|
272
|
-
${
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
`),
|
|
282
|
-
`),n=t[t.length-
|
|
283
|
-
`)
|
|
284
|
-
`)
|
|
285
|
-
`)
|
|
286
|
-
`)}
|
|
287
|
-
`)
|
|
288
|
-
`).replace(
|
|
333
|
+
${a}`;if(o?.body)r+=`
|
|
334
|
+
|
|
335
|
+
${o.body}`;if(o?.chosenLine)r+=`
|
|
336
|
+
|
|
337
|
+
${o.chosenLine}`;return r}function Df(e,t){let n=$t(e);if(n.kind!=="open")return;let s={};if(n.body)s.body=n.body;if(t!==void 0&&t>=1){if(t<=n.reactable.length)s.chosenLine=`${Qr(t-1)} ${Le(n.reactable[t-1])}`;else if(t-It<=n.overflow.length&&t>It)s.chosenLine=`(${t}) ${Le(n.overflow[t-It-1])}`}return s.body||s.chosenLine?s:void 0}function kf(e,t,n="ja",s,o){let a=Me[n],r=`${Ca}*${e}*
|
|
338
|
+
${a.voidStamp(Le(t.trim()))}`;if(o)r+=`
|
|
339
|
+
${a.supersededBy(o)}`;if(s)r+=`
|
|
340
|
+
|
|
341
|
+
${s}`;return r}function xf(e){if(!e.startsWith(tn))return null;let t=e.slice(tn.length),n=t.match(/^\*([\s\S]+?)\*(?=\s|$)/);if(!n)return null;let s=t.slice(n[0].length),o=!1;for(let a of Et){let r=Me[a];for(let c of[r.instructionReactionThread,r.instructionReactionHere,r.instructionTextThread,r.instructionTextHere])if(s.includes(c))o=!0;for(let c of[r.instructionReactionThread,r.instructionReactionHere,r.instructionTextThread,r.instructionTextHere,r.overflowNote,r.otherThread,r.otherHere,...Aw,r.explainLine])s=s.split(c).join(" ");let i=s.indexOf(r.invalidPrefix);if(i>=0){let c=s.indexOf(Gr,i+r.invalidPrefix.length);s=s.slice(0,i)+" "+(c>=0?s.slice(c+Gr.length):"")}}if(!o)return null;return{question:n[1],body:s.replace(/[ \t]{3,}/g," ").trim()}}function Sf(e){if(!e[0]?.startsWith(vs))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 _f(e){let t=e.split(`
|
|
342
|
+
`),n=Sf(t),o=((n>0?t[n]:t[1])??"").match(/^_(?:返信|Answered by reply)(?: \((\d+)\))?/);if(!o)return{byReply:!1};return o[1]?{byReply:!0,n:Number(o[1])}:{byReply:!0}}function Is(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function Ps(e){if(!e.trim())return"本文が空です (bot 投稿や添付のみのメッセージかもしれません)";let t=e.split(`
|
|
343
|
+
`),n=t[t.length-1]??"";if(e.startsWith(vs))return"回答済みマーク付きですが、引用された回答本文が見つかりません";if(!/_$/.test(n))return"末尾が `ask` の案内文ではありません — このメッセージは `slack ask` で投稿されたものではないか、本文が編集されています";if(!t[0].startsWith(tn)&&!t[0].startsWith("*"))return"先頭が質問文 (太字) ではありません — 本文が編集されている可能性があります";return"選択肢の並びを読み取れません — 番号が 1 から連番になっていないか、本文が編集されています"}function $t(e){let t=e.split(`
|
|
344
|
+
`),n=(m)=>e.startsWith(`${m}*`)&&t.some((w,D)=>D>0&&w.length>1&&w.startsWith("_")&&w.endsWith("_"));if(n(Ca)){let m=t.findIndex((E,A)=>A>0&&E.startsWith("_")&&E.endsWith("_")),w=Is(t.slice(0,m>0?m:1).join(`
|
|
345
|
+
`).slice(Ca.length).replace(/^\*/,"").replace(/\*$/,"")),D=m>0?t[m].replace(/^_|_$/g,""):"",k=m>0?t[m+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(Ow)?e.match(/:question: \*([^\n]*?)\*/):null;if(s)return{kind:"void",question:Is(s[1]),reason:Is(t[0])};if(n(vs)){let m=(A)=>A.startsWith("> ")?A.slice(2):A.startsWith("> ")?A.slice(5):null,w=Sf(t),D;if(w>0){D=[];for(let A=w+2;A<t.length;A++){let _=m(t[A]);if(_===null)break;D.push(_)}}else D=t.map(m).filter((A)=>A!==null);let k=Is(t.slice(0,w>0?w:1).join(`
|
|
346
|
+
`).slice(vs.length).replace(/^\*/,"").replace(/\*$/,"")),E=D.map(Is).join(`
|
|
347
|
+
`);if(!E)return{kind:"other"};return{kind:"resolved",question:k,answer:E}}let o=t[t.length-1]??"",a,r,i=Et.find((m)=>[Me[m].instructionReactionThread,Me[m].instructionReactionHere,Me[m].instructionTextThread,Me[m].instructionTextHere].includes(o));if(!i)return{kind:"other"};let c=Me[i];a=o===c.instructionReactionThread||o===c.instructionTextThread,r=o===c.instructionReactionThread||o===c.instructionReactionHere;let l=t[0].startsWith(tn)?t[0].slice(tn.length):t[0];if(t[0]=l,!t[0].startsWith("*"))return{kind:"other"};let u=0;while(u<t.length&&!(t[u].endsWith("*")&&(u>0||t[0].length>1)))u++;if(u>=t.length)return{kind:"other"};let d=t.slice(0,u+1).join(`
|
|
348
|
+
`).replace(/^\*/,"").replace(/\*$/,""),f=[],p=[],g=t.length-1;if(hf(t[g-1]))g--;let h=!1;if(r){let m=t.length-2;if(hf(t[m]))m--;if(t[m]!=="")return{kind:"other"};if(m--,t[m]===c.overflowNote){m--;while(m>=0&&/^\(\d+\) /.test(t[m]))p.unshift(t[m].replace(/^\(\d+\) /,"")),m--;if(t[m]!=="")return{kind:"other"};m--}if(Fw(t[m]))h=!0,m--;if(mf(t[m]))m--;let w=[];while(m>=0){let D=t[m];if(!Rw(D))break;w.unshift(D),m--}if(!w.length||w.length>It)return{kind:"other"};for(let D=0;D<w.length;D++){let k=bf(w[D],D);if(k===null)return{kind:"other"};f.push(k)}if(t[m]!=="")return{kind:"other"};if(m<u+1)return{kind:"other"};g=m;for(let D=0;D<p.length;D++)if(!t.includes(`(${D+11}) ${p[D]}`))return{kind:"other"}}else if(t[g-1]===""&&Tw(t[g-2],c)&&t[g-3]===""&&g-3>=u)h=!0,g-=2;let b=t.slice(u+1,g).join(`
|
|
349
|
+
`).replace(/^\n+|\n+$/g,"");return{kind:"open",question:d,body:b,reactable:f,overflow:p,threadOnly:a,lang:i,explain:h}}function Ls(e){let t=$t(e);if(t.kind!=="open")return null;if(!t.reactable.length)return st;let n=e.split(`
|
|
350
|
+
`),s=Qr(t.reactable.length-1),o=Te[t.reactable.length-1].glyph,a=-1;for(let r=n.length-1;r>=0;r--)if(n[r].startsWith(`${s} `)||n[r]===s||n[r].startsWith(`${o} `)||n[r]===o){a=r;break}return(a>=0?mf(n[a+1]):null)??st}function $a(e){return e.normalize("NFKC").replace(/[*_`~]/g,"").trim().replace(/^[\s"'`「『((\[]+/,"").replace(/[\s"'`」』))\]。..!!??、,]+$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Ef(e,t,n){let s=Array.from({length:n},(a,r)=>r===n-1?t:""),o=Ia(e,s);return o.kind==="chosen"&&o.index===n}function Ia(e,t){let n=$a(e);if(!n)return{kind:"none"};let s=t.map($a),o=new Set;s.forEach((l,u)=>{if(l&&l===n)o.add(u+1)}),Te.forEach((l,u)=>{if(u<t.length&&e.trim()===l.glyph)o.add(u+1)});let a=0,r="",i=n.match(/^(\d{1,2})$/);if(i)a=Number(i[1]);else if(i=n.match(/^(\d{1,2})(?:\s*[.)::、。\-\]]\s*|\s+)(.*)$/)){if(a=Number(i[1]),r=$a(i[2]),!r)return{kind:"none"};if(/^\d+$/.test(r))return{kind:"none"}}if(a>=1&&a<=t.length&&(r===""||r===s[a-1]))o.add(a);let c=[...o].sort((l,u)=>l-u);if(!c.length)return{kind:"none"};if(c.length>1)return{kind:"ambiguous",indexes:c};return{kind:"chosen",index:c[0]}}var Fn={phi:1.618033988749895,minMs:1000,fastMaxMs:5000,fastWindowMs:120000,slowMaxMs:20000};function $f(e,t){let n=t<Fn.fastWindowMs?Fn.fastMaxMs:Fn.slowMaxMs;return Math.min(Math.max(e,Fn.minMs)*Fn.phi,n)}import{closeSync as Iw,existsSync as eo,mkdirSync as to,openSync as vw,readFileSync as so,realpathSync as Pw,renameSync as Lw,statSync as va,unlinkSync as Cf,writeFileSync as Mw}from"node:fs";import{homedir as Af}from"node:os";import{dirname as Pa,join as qe,resolve as no}from"node:path";var Ff=".slack-term",Nw=["inbox","archived","outbox","sent"];function Ms(){return process.env.SLACK_TERM_HOME??qe(Af(),".config","slack-term")}function Xe(e=process.cwd()){let t=no(e);for(;;){let n=qe(t,Ff);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}}var Bw='# .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',jw=`# slack-term settings for this directory. settings.local.yml (written by
|
|
351
|
+
# \`slack alias\`) has the same keys and wins over this file.
|
|
352
|
+
#
|
|
353
|
+
# prefix: "[lane]" # put in front of every \`slack reply\`; never doubled
|
|
354
|
+
# channel: C00000001 # default channel
|
|
355
|
+
# as_bot: false # reply as the bot (SLACK_BOT_TOKEN)
|
|
356
|
+
# subscriptions: # alias -> place (\`slack alias set\` writes settings.local.yml)
|
|
357
|
+
# board:
|
|
358
|
+
# channel: C00000001
|
|
359
|
+
# thread_ts: "1700000000.000100"
|
|
360
|
+
#
|
|
361
|
+
# Only here, never in settings.local.yml:
|
|
362
|
+
# restrict_to_subscriptions: true # the subscriptions above are the whole allowlist,
|
|
363
|
+
# # and prefix / as_bot / channel come from here only
|
|
364
|
+
# owner: ~/ws/x/tree/shr # with restrict: --shared writes run only from under it
|
|
365
|
+
# auto_subscribe: [D00000001] # new top-level messages there are subscribed here
|
|
366
|
+
# nudge_after_min: 30 # \`slack inbox nudge\` reports what waits longer
|
|
367
|
+
`;function La(e,t={}){let n=qe(no(e),Ff),s=[];to(n,{recursive:!0});for(let r of Nw){let i=qe(n,r);if(!eo(i))to(i,{recursive:!0}),s.push(`${r}/`)}let o=(r,i)=>{let c=qe(n,r);if(eo(c))return;Ma(c,i),s.push(r)};o(".gitignore",`*
|
|
368
|
+
`),o("README.md",Bw);let a=Object.fromEntries(Object.entries(t).filter(([,r])=>r!==void 0));if(o("settings.yml",jw+(Object.keys(a).length?`
|
|
369
|
+
`+Bun.YAML.stringify(a,null,2)+`
|
|
370
|
+
`:"")),n!==Ms())qw(n);return{dir:n,created:s}}function Ma(e,t){to(Pa(e),{recursive:!0});let n=`${e}.tmp-${process.pid}-${Date.now()}`;Mw(n,t,{mode:384}),Lw(n,e)}function Tf(e,t,n=1e4,s=5000){let o=`${e}.lock`;to(Pa(o),{recursive:!0});let a=Date.now()+s;for(;;)try{Iw(vw(o,"wx"));break}catch(r){if(r.code!=="EEXIST")throw r;try{if(Date.now()-va(o).mtimeMs>n){Cf(o);continue}}catch{continue}if(Date.now()>a)throw Error(`${o} is held by another writer`);Bun.sleepSync(25)}try{return t()}finally{try{Cf(o)}catch{}}}function Ww(e){if(!e||typeof e!=="object")return;let t=e;if(typeof t.channel!=="string"||!t.channel)return;let n={channel:t.channel};if(typeof t.thread_ts==="string"&&/^\d{10}\.\d{6}$/.test(t.thread_ts))n.thread_ts=t.thread_ts;if(typeof t.added==="string")n.added=t.added;if(typeof t.note==="string")n.note=t.note;return n}function es(e){let t;try{t=Bun.YAML.parse(so(e,"utf8"))}catch(o){if(o.code==="ENOENT")return{};throw Error(`${e}: ${o instanceof Error?o.message:String(o)}`)}if(!t||typeof t!=="object")return{};let n=t,s={};if(typeof n.prefix==="string"&&n.prefix.trim())s.prefix=n.prefix.trim();else if(Array.isArray(n.prefix)&&n.prefix.length===1&&typeof n.prefix[0]==="string")s.prefix=`[${n.prefix[0]}]`;if(typeof n.channel==="string"&&n.channel)s.channel=n.channel;if(typeof n.as_bot==="boolean")s.as_bot=n.as_bot;if(n.restrict_to_subscriptions===!0)s.restrict_to_subscriptions=!0;if(Array.isArray(n.auto_subscribe))s.auto_subscribe=n.auto_subscribe.filter((o)=>typeof o==="string");if(typeof n.nudge_after_min==="number"&&n.nudge_after_min>0)s.nudge_after_min=n.nudge_after_min;if(typeof n.owner==="string"&&n.owner)s.owner=n.owner;if(n.subscriptions&&typeof n.subscriptions==="object"){let o={};for(let[a,r]of Object.entries(n.subscriptions)){let i=Ww(r);if(i&&Na(a))o[a]=i}s.subscriptions=o}return s}function Ns(e){let t=es(qe(e.dir,"settings.yml")),n=es(qe(e.dir,"settings.local.yml"));if(delete n.restrict_to_subscriptions,delete n.auto_subscribe,delete n.owner,t.restrict_to_subscriptions)delete n.subscriptions,delete n.prefix,delete n.as_bot,delete n.channel;let s={...t.subscriptions,...n.subscriptions},o={...t,...n};if(Object.keys(s).length)o.subscriptions=s;else delete o.subscriptions;return o}var Jw=/^[a-z0-9][a-z0-9._-]{0,63}$/;function Na(e){return Jw.test(e)&&!/^\d{10}\.\d{6}$/.test(e)}function sn(e){let t=es(qe(e.dir,"settings.yml")),n=t.subscriptions??{},s=t.restrict_to_subscriptions?{}:es(qe(e.dir,"settings.local.yml")).subscriptions??{},o=[];for(let[a,r]of Object.entries(n))if(!s[a])o.push({...r,name:a,scope:e,file:"settings.yml"});for(let[a,r]of Object.entries(s))o.push({...r,name:a,scope:e,file:"settings.local.yml"});return o.sort((a,r)=>a.name.localeCompare(r.name))}function Ba(e,t=process.cwd()){if(!Na(e))return;let n=Xe(t),s=n.global?[n]:[n,{dir:Ms(),global:!0}];for(let o of s){let a=sn(o).find((r)=>r.name===e);if(a)return a}return}var Uw="# Written by `slack alias set/unset`; wins over settings.yml. Safe to edit by hand.\n";function Kw(e){try{let t=so(e,"utf8").split(`
|
|
371
|
+
`),n=[];for(let s of t)if(s.startsWith("#")||!s.trim()&&n.length)n.push(s);else break;return n.length?n.join(`
|
|
372
|
+
`).replace(/\n*$/,`
|
|
373
|
+
`):""}catch{return""}}function Of(e,t,n){let s=qe(e.dir,t?"settings.yml":"settings.local.yml");Tf(s,()=>{let o=t?Kw(s):Uw,a={};try{let r=Bun.YAML.parse(so(s,"utf8"));if(r&&typeof r==="object"&&!Array.isArray(r))a=r}catch(r){if(r.code!=="ENOENT")throw Error(`${s}: ${r instanceof Error?r.message:String(r)}`)}n(a),Ma(s,o+Bun.YAML.stringify(a,null,2)+`
|
|
374
|
+
`)})}function On(e){return es(qe(e.dir,"settings.yml")).restrict_to_subscriptions===!0}function Rf(e,t=process.cwd()){if(!On(e))return;let n=es(qe(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=(r)=>{try{return Pw(no(r))}catch{return no(r)}},o=s(n.replace(/^~(?=\/|$)/,Af())),a=s(t);if(a===o||a.startsWith(o.endsWith("/")?o:o+"/"))return;return`${e.dir} is owned by ${n}: --shared writes run only from under that directory`}function ja(e,t,n,s={}){let o=typeof s==="boolean"?{shared:s}:s,a=o.shared===!0;if(!Na(t))throw Error(`invalid alias name "${t}" (a-z 0-9 . _ -, at most 64, not a bare ts)`);if(!a&&On(e))throw new Tn(e);if(a&&!o.asOwner){let i=Rf(e,o.cwd);if(i)throw new Tn(e,i)}let r=sn(e).find((i)=>i.name===t);return Of(e,a,(i)=>{let c=i.subscriptions&&typeof i.subscriptions==="object"?i.subscriptions:{};c[t]={channel:n.channel,...n.thread_ts?{thread_ts:n.thread_ts}:{},added:n.added??new Date().toISOString(),...n.note?{note:n.note}:{}},i.subscriptions=c}),r}function If(e,t,n=!1,s){let o=sn(e).find((a)=>a.name===t);if(!o)return"absent";if(o.file==="settings.yml"&&!n)return"in-settings.yml";if(o.file==="settings.yml"){let a=Rf(e,s);if(a)throw new Tn(e,a)}return Of(e,o.file==="settings.yml",(a)=>{let r=a.subscriptions;if(r)delete r[t];if(r&&!Object.keys(r).length)delete a.subscriptions}),"removed"}class Tn 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 vf(){return qe(Ms(),"scopes")}function qw(e){let t=vf();Tf(t,()=>{let n=Pf();if(n.includes(e))return;Ma(t,[...n,e].join(`
|
|
375
|
+
`)+`
|
|
376
|
+
`)})}function Pf(){try{return so(vf(),"utf8").split(`
|
|
377
|
+
`).map((e)=>e.trim()).filter((e)=>e&&!e.startsWith("#"))}catch{return[]}}function Hw(){let e=[];for(let s of Pf())try{if(va(s).isDirectory())e.push({dir:s,global:!1})}catch{}let t=Ms();if((eo(qe(t,"settings.yml"))||eo(qe(t,"settings.local.yml")))&&!e.some((s)=>s.dir===t))e.push({dir:t,global:!0});return e}function Lf(e,t,n=Hw()){let s=[];for(let o of n)for(let a of sn(o))if(a.channel===e&&(a.thread_ts===void 0||a.thread_ts===t))s.push(a);return s}function Wa(e,t){let n=t?.trim();if(!n)return e;let s=/^\[([^\]@\s]+)\]$/.exec(n),o=e;if(s){let a=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=e.replace(new RegExp(`^\\s*\\[${a}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),"")}else if(e.trimStart().startsWith(n))o=e.trimStart().slice(n.length).replace(/^[ \t]+/,"");return o.trim()?`${n} ${o}`:""}function Ja(e,t){if(e.channel===t.channel&&e.threadTs===t.root)return;let n=(s,o)=>o?`${s} thread ${o}`:`${s} (top level)`;return`the message you are answering (${t.ts}) is in ${n(t.channel,t.root)}, but the destination is ${n(e.channel,e.threadTs)}.
|
|
378
|
+
`+` Drop the destination to reply where the message is: slack reply --to <permalink> '…'
|
|
379
|
+
`+" Or pass --any-thread if the other thread is really meant."}var Mf=/(⬜️?|:white_large_square:)(\s*)(\d+)\./g,zw=/(✅|:white_check_mark:)\s*(\d+)\./g;function Nf(e,t){let n=[...e.matchAll(Mf)].map((r)=>Number(r[3])),s=[...e.matchAll(zw)].map((r)=>Number(r[2]));if(t===void 0){if(n.length===0)return s.length?{kind:"already",n:s[0]}:{kind:"none"};if(n.length>1)return{kind:"ambiguous",open:n};t=n[0]}if(!n.includes(t))return s.includes(t)?{kind:"already",n:t}:{kind:"missing",n:t};let o=!1;return{kind:"ticked",text:e.replace(Mf,(r,i,c,l)=>{if(o||Number(l)!==t)return r;return o=!0,`${i.startsWith(":")?":white_check_mark:":"✅"}${c}${l}.`}),n:t}}function Bf(e,t,n){let s=/^\[([^\]@\s]+)\]$/.exec(n?.trim()??"");if(!s)return t;let o=s[1].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a=new RegExp(`^\\[${o}(?:@[a-z0-9-]{1,16})?\\][ \\t]*`),r=a.exec(e);if(!r)return t;return r[0]+t.replace(a,"")}var Ua=/:([a-z0-9_+'-]+):((?::skin-tone-[2-6]:)?)/g,Yw=/<([A-Za-z][A-Za-z0-9+.-]*:[^|<>\s]*)(?:\|([^<>]*))?>/g,Gw=/&(amp|lt|gt);/g,Xw=/[︎️]/gu,Vw=/[\u{1F3FB}-\u{1F3FF}]/gu,jf=String.raw`:[a-z0-9_+'-]+:(?::skin-tone-[2-6]:)?`,Zw=String.raw`©®‼⁉™ℹ←-⇿⌀-⏿Ⓜ■-➿⤀-⥿⬀-⯿〰〽㊗㊙\u{1F000}-\u{1FAFF}`,Wf=String.raw`[${Zw}][\u{E0020}-\u{E007F}]*`,Qw=new RegExp(String.raw`(?<sc>${jf}(?:${jf})*)|(?<emoji>[0-9#*]⃣|[\u{1F1E6}-\u{1F1FF}]{2}|${Wf}(?:${Wf})*)|(?<char>[\s\S])`,"gu");function Ka(e){let t=new Map,n=[e??null],s=0;while(n.length&&s++<1e5){let o=n.pop();if(Array.isArray(o))n.push(...o);else if(o&&typeof o==="object"){let{name:a,unicode:r}=o;if(o.type==="emoji"&&typeof a==="string"&&typeof r==="string")try{t.set(a.split("::")[0],r.split("-").filter(Boolean).map((i)=>String.fromCodePoint(parseInt(i,16))).join(""))}catch{}n.push(...Object.values(o))}}return t}function eD(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 Bs(e,t){let n=e.normalize("NFC");return n=n.replace(Yw,(s,o,a)=>eD(s,o,a)),n=n.replace(Gw,(s,o)=>({amp:"&",lt:"<",gt:">"})[o]),n=n.replace(Ua,(s,o)=>t.get(o)??s),n=n.replace(Xw,"").replace(Vw,""),n.split(/\s+/).filter(Boolean).join(" ")}function Jf(e){return[...e.matchAll(Qw)].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 Uf(e,t){let n=Ka(t.blocks),s=Bs(e,n),o=Bs(typeof t.text==="string"?t.text:"",n);if(s===o)return!0;if(Ua.lastIndex=0,!Ua.test(o))return!1;let a=Jf(s),r=Jf(o);return a.length===r.length&&a.every(([i,c],l)=>c===r[l][1]||r[l][0]==="sc"&&i==="emoji")}function Kf(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 tD(e){return e.replace(/```[\s\S]*?```/g," ").replace(/`[^`\n]*`/g," ").replace(/<[^>\s]*>/g," ").replace(/https?:\/\/\S+/g," ")}function qf(e){let t=df();for(let n of tD(e).split(`
|
|
380
|
+
`))for(let s of t)if(s.re.test(n))return s.lang;return}function Hf(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 Gf,readdirSync as lD,readFileSync as uD,renameSync as dD,statSync as fD,unlinkSync as pD}from"node:fs";import{join as Ct}from"node:path";import{readFileSync as nD}from"node:fs";function zf(e){let t="";for(;;){let a=/^\(\?([is]+)\)/.exec(e);if(!a)break;t+=a[1],e=e.slice(a[0].length)}e=e.replaceAll("(?P<","(?<").replaceAll("\\z","$").replaceAll("[[:alnum:]]","[A-Za-z0-9]").replaceAll("[:alnum:]","A-Za-z0-9").replaceAll("[:alpha:]","A-Za-z").replaceAll("[:digit:]","0-9").replaceAll("[:space:]","\\s");let n="",s=[],o=0;for(let a=0;a<e.length;a++){let r=e[a];if(r==="\\"){n+=r+(e[a+1]??""),a++;continue}if(r==="["){let i=a+1;if(e[i]==="^")i++;if(e[i]==="]")i++;while(i<e.length&&e[i]!=="]"){if(e[i]==="\\")i++;i++}n+=e.slice(a,i+1),a=i;continue}if(e.startsWith("(?i)",a)){n+="(?i:",o++,a+=3;continue}if(r==="("){s.push(o),o=0,n+=r;continue}if(r===")"){n+=")".repeat(o),o=s.pop()??0,n+=r;continue}if(r==="|"&&o){n+=")".repeat(o)+"|"+"(?i:".repeat(o);continue}n+=r}return n+=")".repeat(o),{source:n,flags:[...new Set(t)].join("")}}function sD(e){let t=Bun.TOML.parse(e),n=(r)=>{let i=zf(r);return new RegExp(i.source,i.flags)},s=(t.allowlist?.regexes??[]).map(n),o=(t.allowlist?.stopwords??[]).map((r)=>r.toLowerCase()),a=[];for(let r of t.rules){if(!r.regex)continue;let i=[...s],c=[],l=[],u=[...o];for(let f of[...r.allowlists??[],...r.allowlist?[r.allowlist]:[]]){let p=f.regexTarget==="match"?c:f.regexTarget==="line"?l:i;for(let g of f.regexes??[])p.push(n(g));for(let g of f.stopwords??[])u.push(String(g).toLowerCase())}let d=zf(r.regex);a.push({id:r.id,re:new RegExp(d.source,d.flags+"gd"),keywords:(r.keywords??[]).map((f)=>f.toLowerCase()),...r.entropy?{entropy:r.entropy}:{},...r.secretGroup?{group:r.secretGroup}:{},allow:i,...c.length?{allowMatch:c}:{},...l.length?{allowLine:l}:{},stop:u})}return a}var rD=[{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:[]}],Yf;function oD(){return Yf??=[...sD(nD(new URL("./vendor/gitleaks.toml",import.meta.url),"utf8")),...rD],Yf}function iD(e){let t=new Map;for(let s of e)t.set(s,(t.get(s)??0)+1);let n=0;for(let s of t.values()){let o=s/e.length;n-=o*Math.log2(o)}return n}function aD(e,t){let n=new Set;for(let o of t){if(o.length<6)continue;n.add(o),n.add(JSON.stringify(o).slice(1,-1))}let s=[];for(let o of[...n].sort((a,r)=>r.length-a.length))for(let a=e.indexOf(o);a>=0;a=e.indexOf(o,a+o.length))s.push({id:"known-secret",start:a,end:a+o.length});return s}function cD(e,t={}){let n=t.rules??oD(),s=e.toLowerCase(),o=t.known?.length?aD(e,t.known):[];for(let a of n){if(a.keywords.length&&!a.keywords.some((r)=>s.includes(r)))continue;for(let r of e.matchAll(a.re)){let i=a.group??r.findIndex((d,f)=>f>0&&!!d),c=i>0?r[i]:r[0];if(!c)continue;if(a.entropy&&iD(c)<a.entropy)continue;if(a.allow.some((d)=>d.test(c)))continue;if(a.allowMatch?.some((d)=>d.test(r[0])))continue;if(a.allowLine){let d=e.lastIndexOf(`
|
|
381
|
+
`,r.index)+1,f=e.indexOf(`
|
|
382
|
+
`,r.index+r[0].length);if(a.allowLine.some((p)=>p.test(e.slice(d,f<0?void 0:f))))continue}let l=c.toLowerCase();if(a.stop.some((d)=>l.includes(d)))continue;let u=a.group?r.indices?.[a.group]:void 0;if(u)o.push({id:a.id,start:u[0],end:u[1]});else{let d=r.index,f=r.index+r[0].length,p=/[\s'"`;=:,]/;while(d<f&&p.test(e[d]))d++;for(;;)if(f>d&&p.test(e[f-1]))f--;else if(f-2>=d&&/\\[nr]/.test(e.slice(f-2,f)))f-=2;else break;o.push({id:a.id,start:d,end:f})}}}return o}function ro(e,t={}){let n=cD(e,t).sort((r,i)=>r.start-i.start||i.end-r.end);if(!n.length)return{text:e,kinds:[]};let s=[];for(let r of n){let i=s[s.length-1];if(i&&r.start<i.end){if(r.end-r.start>i.end-i.start)i.id=r.id;i.end=Math.max(i.end,r.end)}else s.push({...r})}let o="",a=0;for(let r of s)o+=e.slice(a,r.start)+`[redacted:${r.id}]`,a=r.end;return{text:o+e.slice(a),kinds:[...new Set(s.map((r)=>r.id))]}}var hD=/^\d{10}\.\d{6}$/;function gD(e,t){return`${e}-${t}.yml`}function oo(e){return Bun.YAML.stringify(e,null,2)+`
|
|
383
|
+
`}function mD(e,t,n=[]){let s=gD(t.channel,t.ts);if(Gf(Ct(e.dir,"inbox",s))||Gf(Ct(e.dir,"archived",s)))return!1;let o=ro(t.text,{known:n}),a={...t,text:o.text,...o.kinds.length?{redacted:o.kinds}:{}};return Qn(Ct(e.dir,"inbox",s),oo(a)),!0}function Xf(e,t=Sa(),n=new Date,s=[]){let o=e.thread_ts??e.ts,a=_a(e.channel.id,o,t);if(!a.length&&!e.thread_ts){for(let c of t){if(!xa(c).auto_subscribe?.includes(e.channel.id))continue;of(c,`t-${e.ts}`,{channel:e.channel.id,thread_ts:e.ts,note:"auto: new top-level message"},{shared:!0,asOwner:!0})}a=_a(e.channel.id,o,t)}let r=[],i=new Set;for(let c of a){if(i.has(c.scope.dir))continue;if(i.add(c.scope.dir),mD(c.scope,{ts:e.ts,channel:e.channel.id,channel_name:e.channel.name,...e.thread_ts?{thread_ts:e.thread_ts}:{},user:e.user.id,user_name:e.user.name,text:e.text,...e.files?{files:e.files}:{},permalink:e.permalink,alias:c.name,received_at:n.toISOString()},s))r.push(c.scope.dir)}return r}function Vf(e,t){let n;try{n=lD(e).filter((o)=>o.endsWith(".yml"))}catch{return[]}let s=[];for(let o of n.sort()){let a=Ct(e,o);try{let r=t(Bun.YAML.parse(uD(a,"utf8")));if(r)s.push({file:a,entry:r,mtimeMs:fD(a).mtimeMs})}catch{}}return s}function yD(e){let t=e;return t&&typeof t.ts==="string"&&typeof t.channel==="string"&&typeof t.text==="string"?t:void 0}function ts(e){return Vf(Ct(e.dir,"inbox"),yD).sort((t,n)=>Number(t.entry.ts)-Number(n.entry.ts))}function qa(e,t){let n=ts(e),s=hD.test(t)?n.find((a)=>a.entry.ts===t):n.find((a)=>a.file===t||a.file.endsWith(`/${t}`)||a.file.endsWith(`/${t}.yml`));if(!s)return;let o=Ct(e.dir,"archived",s.file.slice(s.file.lastIndexOf("/")+1));return dD(s.file,o),o}function bD(e){let t=e;return t&&typeof t.to==="string"&&typeof t.text==="string"?t:void 0}function Ha(e){return Vf(Ct(e.dir,"outbox"),bD)}function Zf(e,t,n=new Date){let s=Ct(e.dir,"outbox",`${n.toISOString().replace(/[:.]/g,"-")}-${process.pid}.yml`),o=ro(t.text);return Qn(s,oo({...t,text:o.text})),{file:s,redacted:o.kinds}}function Qf(e,t,n,s=new Date){let o=t.file.slice(t.file.lastIndexOf("/")+1),a=ro(t.entry.text),{error:r,...i}=t.entry;if(Qn(Ct(e.dir,"sent",o),oo({...i,text:a.text,...a.kinds.length?{redacted:a.kinds}:{},...n,sent_at:s.toISOString()})),pD(t.file),t.entry.in_reply_to)qa(e,t.entry.in_reply_to);return Ct(e.dir,"sent",o)}function ep(e,t){Qn(e.file,oo({...e.entry,attempts:(e.entry.attempts??0)+1,error:t}))}function tp(e,t=Date.now()){let n=xa(e).nudge_after_min??30;return ts(e).filter((s)=>t-s.mtimeMs>=n*60000)}var Ya=[{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"}],p$=Ya.length,wD="question",DD=`:${wD}: `,kD="heavy_plus_sign",za=`:${kD}: `;var xD="information_source",np=`:${xD}: `,rp=["ja","en"];var io={get ja(){return sp("ja")},get en(){return sp("en")}};function sp(e){let t=(n,s)=>Hr(e,n,s);return{instructionReactionThread:t("instructionReactionThread"),instructionReactionHere:t("instructionReactionHere"),instructionTextThread:t("instructionTextThread"),instructionTextHere:t("instructionTextHere"),overflowNote:t("overflowNote"),otherThread:`${za}${t("otherThread")}`,otherHere:`${za}${t("otherHere")}`,explainLine:`${np}${t("explainLine")}`,explainNote:`${np}${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 h$=rp.flatMap((e)=>[io[e].otherThread,io[e].otherHere].map((t)=>DD+t.slice(za.length)));var op="_";function ip(e){if(e===void 0||!e.endsWith(op))return null;return rp.find((t)=>e.startsWith(io[t].invalidPrefix))??null}function Ga(e){let t=e.split(`
|
|
384
|
+
`),n=t[t.length-2];if(!ip(n))return[];return[...n.matchAll(/<@([UW][A-Z0-9]+)>/g)].map((s)=>s[1])}function ap(e,t,n="ja"){let s=e.split(`
|
|
385
|
+
`);if(s.length<2)return e;if(Ga(e).length)s.splice(s.length-2,1);if(t.length)s.splice(s.length-1,0,`${io[n].invalidPrefix}${t.map((a)=>`<@${a}>`).join(", ")}${op}`);let o=s.join(`
|
|
386
|
+
`);return o===e?e:o}function cp(e){return ip(e)!==null}var SD="white_check_mark",g$=`:${SD}: `,_D="no_entry_sign",m$=`:${_D}: `;var wt=Ya,ns=wt.length,Ws="ballot_box_with_ballot",Xa=`:${Ws}: `,up="_下のリアクションで投票してください (1 人 1 票、押し直しで変更できます)。_",dp="_下のリアクションで投票してください (当てはまるものを *いくつでも* 押せます)。_",ao="_締切: ",co="_",Za="bar_chart",Va=`:${Za}: `;function lo(e){return`:${wt[e].name}:`}function lp(e,t){for(let n of[lo(t),wt[t].glyph])if(e.startsWith(`${n} `))return e.slice(n.length+1);return null}function ED(e){return wt.some((t,n)=>e.startsWith(`${lo(n)} `)||e.startsWith(`${t.glyph} `))}function js(e){return e.replace(/\s*\n\s*/g," ")}function fp(e,t,n,s={}){let o=!!s.multi,a=s.deadline??"",r=s.invalid??[];if(!n.length||n.length>ns)throw Error(`poll needs 1..${ns} choices, got ${n.length}`);let i=[`${Xa}*${e}*`];if(t)i.push("",t);if(i.push(""),i.push(...n.map((c,l)=>`${lo(l)} ${js(c)}`)),i.push(""),a)i.push(`${ao}${js(a)}${co}`);return i.push(o?dp:up),ap(i.join(`
|
|
387
|
+
`),o?[]:r)}function pp(e,t){let n=t.reduce((o,a)=>o+a.count,0),s=[`${Va}*${e}*`,`_投票終了 (計 ${n} 票)_`,""];return s.push(...t.map((o,a)=>`${lo(a)} ×${o.count} ${js(o.choice)}`)),s.join(`
|
|
388
|
+
`)}function Js(e){let t=e.split(`
|
|
389
|
+
`);if(e.startsWith(Va)){let f=t[0].slice(Va.length).replace(/^\*/,"").replace(/\*$/,""),p=[];for(let g=0;g<wt.length;g++){let h=t.map((m)=>lp(m,g)).find((m)=>m!==null&&m.startsWith("×"));if(h===void 0)break;let b=/^×(\d+) (.*)$/.exec(h);if(!b)return{kind:"other"};p.push({choice:b[2],count:Number(b[1])})}if(!p.length)return{kind:"other"};return{kind:"closed",question:f,tallies:p}}let n=t[t.length-1]??"",s;if(n===up)s=!1;else if(n===dp)s=!0;else return{kind:"other"};if(t[0].startsWith(Xa))t[0]=t[0].slice(Xa.length);if(!t[0].startsWith("*"))return{kind:"other"};let o=0;while(o<t.length&&!(t[o].endsWith("*")&&(o>0||t[0].length>1)))o++;if(o>=t.length)return{kind:"other"};let a=t.slice(0,o+1).join(`
|
|
390
|
+
`).replace(/^\*/,"").replace(/\*$/,""),r=t.length-2,i=Ga(e);if(cp(t[r]))r--;let c="",l=t[r];if(l!==void 0&&l.startsWith(ao)&&l.endsWith(co)&&l.length>ao.length+co.length)c=l.slice(ao.length,-co.length),r--;if(t[r]!=="")return{kind:"other"};r--;let u=[];while(r>=0){let f=t[r];if(!ED(f))break;u.unshift(f),r--}if(!u.length||u.length>ns)return{kind:"other"};let d=[];for(let f=0;f<u.length;f++){let p=lp(u[f],f);if(p===null)return{kind:"other"};d.push(p)}if(t[r]!=="")return{kind:"other"};if(r<o+1)return{kind:"other"};return{kind:"open",question:a,choices:d,multi:s,deadline:c,invalid:i}}function hp(e,t,n,s){let o=new Map(t.map((l)=>[l.name,l.users])),a=e.map((l,u)=>(o.get(wt[u].name)??[]).filter((d)=>!n.has(d))),r=[];if(!s){let l=new Map;for(let u of a)for(let d of u)l.set(d,(l.get(d)??0)+1);for(let[u,d]of l)if(d>1)r.push(u)}let i=new Set(r),c=a.map((l)=>l.filter((u)=>!i.has(u)));return{tallies:e.map((l,u)=>({choice:l,count:c[u].length})),voters:c,ambiguous:r}}function $D(e=process.env){return!!e.VITEST||e.NODE_ENV==="test"||!!e.BUN_TEST}var gp={isTestEnv:()=>$D(),sleep:(e)=>gp.isTestEnv()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function CD(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 uo(e,t,n,s=CD()){for(let o=0;o<e.length;o++){let a=!0;try{await t(e[o])}catch(r){a=!1,n(e[o],r)}if(a&&s>0&&o<e.length-1)await gp.sleep(s)}}var mp=["text","select","user","link","date","number","checkbox"];function bp(e){let t=e.split(":"),n=(t[0]??"").trim(),s=(t[1]??"text").trim();if(!n)throw Error(`--col needs a name: ${e}`);if(!mp.includes(s))throw Error(`--col ${e}: unknown type "${s}" (expected one of ${mp.join(", ")})`);if(s==="select"){let o=(t.slice(2).join(":")||"").split(",").map((a)=>a.trim()).filter(Boolean);if(!o.length)throw Error(`--col ${e}: a select column needs choices, e.g. ${n}:select:todo,doing,done`);return{name:n,type:s,choices:o}}if(t.length>2)throw Error(`--col ${e}: only select columns take a third part`);return{name:n,type:s}}var yp=["gray","blue","green","yellow","red","purple","orange","pink","cyan","indigo","brown"];function wp(e){if(!e.length)throw Error("at least one --col is required (the first one is the primary text column)");if(e[0].type!=="text")throw Error(`the first --col is the primary column and must be text, got ${e[0].type}`);return e.map((t,n)=>{let s={key:`col${n+1}`,name:t.name,type:t.type};if(n===0)s.is_primary_column=!0;if(t.type==="select")s.options={format:"single_select",choices:t.choices.map((o,a)=>({value:o,label:o,color:yp[a%yp.length]}))};if(t.type==="user")s.options={format:"single_entity"};return s})}function Dp(e){return((e.list_metadata??e.metadata??{}).schema??e.schema??[]).map((s)=>{let o=s??{},r=((o.options??{}).choices??[]).map((i)=>{let c=i??{};return{value:String(c.value??""),label:String(c.label??c.value??"")}});return{id:String(o.id??""),key:String(o.key??""),name:String(o.name??""),type:String(o.type??""),choices:r}})}function Qa(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 ec(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 tc(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 kp(e){return e.find((t)=>t.key==="todo_completed"||t.type==="todo_completed")}import{spawnSync as sc}from"node:child_process";import{chmodSync as AD,existsSync as Sp,mkdirSync as FD}from"node:fs";import{homedir as TD,hostname as OD}from"node:os";import{basename as _p,dirname as RD,join as ID}from"node:path";function po(){return!/^(0|off|false|no)$/i.test(process.env.SLACK_TERM_ATTRIBUTION??"")}var fo={claude:"claude-code",codex:"codex",gemini:"gemini",opencode:"opencode","cursor-agent":"cursor-agent",aider:"aider",amp:"amp"};function vD(e){try{let n=(sc("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:_p(n[2].trim())}}catch{return}}function PD(){let e=process.ppid;for(let t=0;t<12&&e>1;t++){let n=vD(e);if(!n)return;if(fo[n.comm])return n;e=n.ppid}return}function xp(e){let t=Number(e);return Number.isInteger(t)&&t>0?t:void 0}function Ep(e=process.env){let t={pid:process.pid,host:LD(),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=xp(e.SLACK_TERM_AGENT_PID)??xp(e.CLAUDE_PID);if(!s||!n){let r=PD();if(r)s??=r.pid,n??=fo[r.comm]}if(n)t.cli=n;if(s)t.agentPid=s;let o=e.SLACK_TERM_AGENT_SESSION||e.CLAUDE_CODE_SESSION_ID;if(o)t.sessionId=o;let a=MD(t.cwd);if(a)t.gitBranch=a;return t}function LD(){try{return OD()}catch{return""}}function MD(e){try{let t=sc("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:e,encoding:"utf8",timeout:2000});return(t.status===0?(t.stdout??"").trim():"")||void 0}catch{return}}var ND="slack_term_sent";function $p(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:ND,event_payload:n}}function At(){if(process.env.SLACK_TERM_SENT_DB)return process.env.SLACK_TERM_SENT_DB;return ID(process.env.HOME||TD(),".config","slack-cli","sent.sqlite")}function BD(e){try{if(typeof globalThis.Bun<"u"){let{Database:n}=fs("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 jD=`
|
|
289
391
|
CREATE TABLE IF NOT EXISTS sent (
|
|
290
392
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
291
393
|
kind TEXT NOT NULL,
|
|
@@ -314,162 +416,164 @@ CREATE TABLE IF NOT EXISTS sent (
|
|
|
314
416
|
);
|
|
315
417
|
CREATE INDEX IF NOT EXISTS sent_msg ON sent(channel, ts);
|
|
316
418
|
CREATE INDEX IF NOT EXISTS sent_at ON sent(sent_at);
|
|
317
|
-
`;function
|
|
318
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.kind,e.team??null,e.channel,e.target??null,e.ts,e.threadTs??null,e.permalink??null,e.text,Date.now(),n.pid,n.agentPid??null,n.host||null,n.cwd,n.gitBranch??null,n.cli??null,n.sessionId??null,e.asBot?1:0),!0}catch(n){return console.error(` (送信ログに記録できませんでした: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var
|
|
419
|
+
`;function ho(){let e=At();try{FD(RD(e),{recursive:!0})}catch{}let t=BD(e);if(!t)return;try{AD(e,384)}catch{}try{t.exec(jD);for(let n of["delivered_answer TEXT","delivered_cursor TEXT"])try{t.exec(`ALTER TABLE sent ADD COLUMN ${n}`)}catch{}return t}catch{try{t.close()}catch{}return}}function Cp(e){if(!po())return!1;let t=ho();if(!t)return console.error(` (送信ログに記録できませんでした: ${Us} — ${At()})`),!1;try{let n=e.attribution;return t.prepare(`INSERT INTO sent (kind, team, channel, target, ts, thread_ts, permalink, text, sent_at, pid, agent_pid, host, cwd, git_branch, cli, session_id, as_bot)
|
|
420
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(e.kind,e.team??null,e.channel,e.target??null,e.ts,e.threadTs??null,e.permalink??null,e.text,Date.now(),n.pid,n.agentPid??null,n.host||null,n.cwd,n.gitBranch??null,n.cli??null,n.sessionId??null,e.asBot?1:0),!0}catch(n){return console.error(` (送信ログに記録できませんでした: ${n instanceof Error?n.message:String(n)})`),!1}finally{try{t.close()}catch{}}}var Us="送信ログを開けません: SQLite が使えないランタイムです (bun、または node >= 22.5 の node:sqlite が必要)";function rc(e){let t=ho();if(!t)return;try{let n=[],s=[];if(e.text)n.push("text LIKE ? ESCAPE '\\'"),s.push(`%${nc(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(`${nc(e.session)}%`);if(e.cwd)n.push("cwd LIKE ? ESCAPE '\\'"),s.push(`${nc(e.cwd)}%`);if(e.kind)n.push("kind = ?"),s.push(e.kind);let o=`SELECT * FROM sent${n.length?` WHERE ${n.join(" AND ")}`:""} ORDER BY sent_at DESC, id DESC LIMIT ?`;return s.push(e.limit??50),t.prepare(o).all(...s)}finally{try{t.close()}catch{}}}function nc(e){return e.replace(/[\\%_]/g,(t)=>`\\${t}`)}function go(e,t=Date.now()){let n=e.trim().match(/^(\d+(?:\.\d+)?)\s*(s|m|h|d|w)$/i);if(n){let o={s:1000,m:60000,h:3600000,d:86400000,w:604800000}[n[2].toLowerCase()];return t-Number(n[1])*o}let s=Date.parse(e);return Number.isNaN(s)?void 0:s}function Ap(e,...t){if(!po()||!Sp(At()))return;let n=ho();if(!n)return;try{n.prepare(e).run(...t)}catch{}finally{try{n.close()}catch{}}}function oc(e,t,n,s){let o=Date.now();Ap(`UPDATE sent SET collected_at = COALESCE(collected_at, ?), answer = ?, answer_exit = 0,
|
|
319
421
|
delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
|
|
320
|
-
WHERE kind = 'ask' AND channel = ? AND ts = ?`,
|
|
321
|
-
WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,
|
|
422
|
+
WHERE kind = 'ask' AND channel = ? AND ts = ?`,o,n,o,n,s,e,t)}function Fp(e,t,n,s){Ap(`UPDATE sent SET delivered_at = ?, delivered_answer = ?, delivered_cursor = ?
|
|
423
|
+
WHERE kind = 'ask' AND channel = ? AND ts = ? AND collected_at IS NULL`,Date.now(),n,s,e,t)}function Tp(e){if(!Sp(At()))return[];let t=ho();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 Op(e){let t=e.agent_pid??e.pid;if(!WD(t))return!1;try{let s=(sc("ps",["-o","lstart=,comm=","-p",String(t)],{encoding:"utf8",timeout:2000}).stdout??"").trim(),o=Date.parse(s.slice(0,24));if(!Number.isNaN(o)&&o>e.sent_at+1000)return!1;let a=_p(s.slice(24).trim()),r=new Set(Object.values(fo));if(e.cli&&r.has(e.cli)&&a&&fo[a]!==e.cli)return!1}catch{}return!0}function WD(e){if(!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}class Dt extends Error{retryAfter;method;constructor(e,t){super(t?`Slack rate limited on ${t} — retry after ${e}s`:`Slack rate limited — retry after ${e}s`);if(this.name="RateLimitError",this.retryAfter=e,t)this.method=t}}function cc(){return(process.env.SLACK_API_BASE??"https://slack.com/api").replace(/\/$/,"")}var vp=(()=>{let e=Number(process.env.SLACK_RATELIMIT_WAIT_SEC);return Number.isFinite(e)&&e>=0?e:120})();function Pp(e){vp=e}async function Lp(e,t=(n)=>new Promise((s)=>setTimeout(s,n))){let n=0;for(;;)try{return await e()}catch(s){if(!(s instanceof Dt)||n+s.retryAfter>vp)throw s;n+=s.retryAfter,console.error(`slack: ${s.message} — waiting`),await t(s.retryAfter*1000)}}function Mp(e,t,n,s){return Lp(()=>JD(e,t,n,s))}async function JD(e,t,n,s){s=e.startsWith("xoxc-")?s??Vt():void 0;let o={};if(s)o.Cookie=`d=${s}`;let a=await fetch(`${cc()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(a.status===429){let i=parseInt(a.headers.get("retry-after")??"60",10);throw new Dt(isNaN(i)?60:i,t)}let r=await a.json();if(r.ok!==!0){let i=r.error??"unknown";if(i==="ratelimited")throw new Dt(60,t);if(i==="invalid_auth"&&e.startsWith("xoxc-")&&!s)throw Error(`Desktop app token (xoxc-) needs its session cookie to be accepted by the public Slack API.
|
|
322
424
|
Attach it: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)
|
|
323
425
|
Or replace the token with an xoxp- user token:
|
|
324
|
-
slack auth login`);if((
|
|
426
|
+
slack auth login`);if((i==="missing_scope"||i==="cannot_dm_bot")&&e.startsWith("xoxb-")){if(t.startsWith("agents.sessions."))throw Error(`Slack error on ${t}: ${i}. Agent sessions need a granular bot token with chat:write and app membership in the channel.`);throw Error(`Slack error on ${t}: ${i} — ${i==="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"}.
|
|
325
427
|
Tailing/DMing people and listing users need a user session, not a bot token.
|
|
326
428
|
Switch workspace: slack auth ls then slack auth use <name>
|
|
327
|
-
Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${
|
|
328
|
-
Import from Slack desktop: slack auth login`);if((
|
|
329
|
-
Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${
|
|
429
|
+
Or import your Slack desktop session: slack auth login`)}throw Error(`Slack error on ${t}: ${i}`)}return r}function UD(e,t,n,s){return Lp(()=>KD(e,t,n,s))}async function KD(e,t,n,s){let o={};if(s)o.Cookie=`d=${s}`;let a=await fetch(`${cc()}/${t}`,{...n,headers:{...n.headers??{},Authorization:`Bearer ${e}`,...o}});if(a.status===429){let i=parseInt(a.headers.get("retry-after")??"60",10);throw new Dt(isNaN(i)?60:i,t)}let r=await a.json();if(r.ok!==!0){let i=r.error??"unknown";if(i==="ratelimited")throw new Dt(60,t);if((i==="invalid_auth"||i==="not_authed")&&!e.startsWith("xoxc-"))throw Error(`${t} requires a desktop app session token (xoxc-).
|
|
430
|
+
Import from Slack desktop: slack auth login`);if((i==="invalid_auth"||i==="not_authed")&&!s)throw Error(`${t} also requires the xoxd session cookie.
|
|
431
|
+
Attach it with: slack auth firefox (Linux/macOS/Windows) or slack auth chrome (macOS/Linux)`);throw Error(`Slack error on ${t}: ${i}`)}return r}function kt(e,t,n={},s){let o=new URLSearchParams({token:e,...n});return UD(e,t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()},s)}function ye(e,t,n,s){let o=new URLSearchParams(n).toString();return Mp(e,`${t}?${o}`,{method:"GET"},s)}function Oe(e,t,n,s){return Mp(e,t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},s)}async function lc(e,t){let n=await ye(e,"auth.test",{},t);return{team:n.team??"",teamId:n.team_id??"",url:n.url??"",user:n.user??"",userId:n.user_id??""}}async function Pt(e,t){t=e.startsWith("xoxc-")?t??Vt():void 0;let n={Authorization:`Bearer ${e}`};if(t)n.Cookie=`d=${t}`;let s=await fetch(`${cc()}/auth.test`,{method:"GET",headers:n});if(s.status===429){let r=parseInt(s.headers.get("retry-after")??"60",10);throw new Dt(isNaN(r)?60:r,"auth.test")}let o=s.headers.get("x-oauth-scopes")??"",a=await s.json();if(a.ok!==!0)throw Error(`Slack error on auth.test: ${a.error??"unknown"}`);return{userId:a.user_id??"",user:a.user??"",botId:a.bot_id??"",team:a.team??"",url:a.url??"",scopes:o.split(",").map((r)=>r.trim()).filter(Boolean)}}async function Np(e,t,n){let s=await ye(e,"bots.info",{bot:t},n);return{appId:s.bot?.app_id??"",userId:s.bot?.user_id??""}}async function rt(e,t,n=20,s,o,a,r){let i={channel:t,limit:String(n)};if(s!==void 0)i.oldest=s;if(o!==void 0)i.cursor=o;if(r)i.inclusive="true";return mo(await ye(e,"conversations.history",i,a))}function mo(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)$r(s);return e}async function Pe(e,t,n,s=50,o){return mo(await ye(e,"conversations.replies",{channel:t,ts:n,limit:String(s)},o))}async function uc(e,t,n,s={},o){let a={channel:t,ts:n,limit:String(s.limit??200)};if(s.oldest!==void 0)a.oldest=s.oldest;if(s.cursor!==void 0)a.cursor=s.cursor;return mo(await ye(e,"conversations.replies",a,o))}async function Bp(e,t,n){return ye(e,"files.info",{file:t},n)}async function jp(e,t={},n){let s={count:String(Math.min(Math.max(t.count??100,1),200)),page:String(Math.max(t.page??1,1))};if(t.types)s.types=t.types;if(t.channel)s.channel=t.channel;if(t.user)s.user=t.user;return ye(e,"files.list",s,n)}async function Wp(e,t,n,s){let o={name:t,schema:n};if(s)o.todo_mode=!0;return await Oe(e,"slackLists.create",o)}async function dc(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 Jp(e,t,n){return await Oe(e,"slackLists.items.create",{list_id:t,initial_fields:n})}async function Up(e,t,n,s){let o={list_id:t,access_level:n};if(s.userIds?.length)o.user_ids=s.userIds;if(s.channelIds?.length)o.channel_ids=s.channelIds;return await Oe(e,"slackLists.access.set",o)}async function Kp(e,t,n){return await Oe(e,"slackLists.items.update",{list_id:t,cells:n})}async function qp(e,t,n={},s){let o={list_id:t};if(n.limit)o.limit=String(n.limit);if(n.cursor)o.cursor=n.cursor;return kt(e,"lists.records.list",o,s)}async function Hp(e,t,n,s,o){return mo(await ye(e,"search.messages",{query:t,sort:"timestamp",sort_dir:"desc",count:String(Math.min(Math.max(n,1),100)),page:String(Math.max(s,1))},o))}async function zp(e,t,n){return Hp(e,t,100,1,n)}async function fc(e,t,n,s){let a=1,r=[],i={ok:!0,messages:{}};while(!0){let l=await Hp(e,t,100,a,s),u=Ks(l,["messages","matches"]),d=Array.isArray(u)?u:[];r.push(...d);let f=Number(Ks(l,["messages","paging","pages"])??1);if(i=l,d.length===0||a>=f||r.length>=n)break;a+=1}let c=i;if(!c.messages)c.messages={};return c.messages.matches=r.slice(0,n),c}async function Lt(e,t,n,s,o,a,r,i){let c=r?{channel:t,text:n}:{channel:t,text:n,blocks:[{type:"markdown",text:n}]};if(s!==void 0)c.thread_ts=s;if(o&&s!==void 0)c.reply_broadcast=!0;return(await Yp(e,"chat.postMessage",c,i,a)).ts??""}function qD(e){return e instanceof Error&&/: (invalid_metadata\w*|metadata_\w+)$/.test(e.message)}async function Yp(e,t,n,s,o){if(!s)return Oe(e,t,n,o);try{return await Oe(e,t,{...n,metadata:s},o)}catch(a){if(!qD(a))throw a;return Oe(e,t,n,o)}}async function Gp(e,t,n,s,o,a){let r={channel:t,text:n,post_at:s,blocks:[{type:"markdown",text:n}]};if(o!==void 0)r.thread_ts=o;return(await Oe(e,"chat.scheduleMessage",r,a)).scheduled_message_id??""}async function Xp(e,t,n){let s={};if(t)s.channel=t;return ye(e,"chat.scheduledMessages.list",s,n)}async function Vp(e,t,n,s){await Oe(e,"chat.deleteScheduledMessage",{channel:t,scheduled_message_id:n},s)}async function In(e,t,n,s){return(await ye(e,"chat.getPermalink",{channel:t,message_ts:n},s)).permalink??""}async function Mt(e,t,n,s,o,a,r){return(await Yp(e,"chat.update",a?{channel:t,ts:n,text:s}:{channel:t,ts:n,text:s,blocks:[{type:"markdown",text:s}]},r,o)).ts??n}async function Zp(e,t,n,s){await Oe(e,"chat.delete",{channel:t,ts:n},s)}async function Qp(e,t,n,s,o=200,a){let r={channel:t,ts:n,limit:String(o)};if(s!==void 0)r.cursor=s;return ye(e,"conversations.replies",r,a)}async function pc(e,t,n,s){await Oe(e,"pins.add",{channel:t,timestamp:n},s)}async function Nt(e,t,n,s,o){await Oe(e,"reactions.add",{channel:t,timestamp:n,name:s},o)}async function eh(e,t,n,s){return((await ye(e,"reactions.get",{channel:t,timestamp:n,full:"true"},s)).message?.reactions??[]).map((a)=>({name:String(a.name??""),users:Array.isArray(a.users)?a.users.map(String):[]}))}async function Bt(e,t,n,s,o){await Oe(e,"reactions.remove",{channel:t,timestamp:n,name:s},o)}async function th(e,t,n=!1,s){let o=await Oe(e,"conversations.create",{name:t,is_private:n},s);return{id:o.channel?.id??"",name:o.channel?.name??t}}async function nh(e,t,n,s){let o=await Oe(e,"conversations.rename",{channel:t,name:n},s);return{id:o.channel?.id??t,name:o.channel?.name??n}}async function sh(e,t,n,s){await Oe(e,"conversations.invite",{channel:t,users:n.join(",")},s)}async function qs(e,t){let n=[],s="";while(!0){let o={limit:"200",types:"public_channel,private_channel,im,mpim"};if(s)o.cursor=s;let a=await ye(e,"conversations.list",o,t);if(n.push(...a.channels??[]),s=a.response_metadata?.next_cursor??"",!s)break}return{channels:n}}async function jt(e,t,n){let o=(await Oe(e,"conversations.open",{users:t},n)).channel?.id;if(!o)throw Error(`Failed to open DM with user ${t}`);return o}async function rh(e,t,n){let s="";while(!0){let o={types:"im",limit:"200"};if(s)o.cursor=s;let a=await ye(e,"conversations.list",o,n);for(let r of a.channels??[])if(r.user===t)return String(r.id??"");if(s=a.response_metadata?.next_cursor??"",!s)break}return""}async function ic(e,t,n,s){let o=await rh(e,t,n);if(o)return o;let a=s?`${s} (${t})`:t;throw Error(`No existing DM with ${a}. Open it once in Slack first.`)}function Rn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function Rp(e,t){let n=Rn(e.name??""),s=Rn(e.real_name??e.profile?.real_name??""),o=Rn(e.profile?.display_name??"");return n===t||s===t||!!o&&o===t}var oh=200;async function ih(e,t,n){let s=0,o=new Set,a="";while(!0){let u={limit:"200"};if(a)u.cursor=a;let d=await ye(e,"users.list",u,n);for(let f of d.members??[]){if(s++,f.id)o.add(f.id);if(Rp(f,t))return{id:f.id??"",workspaceCount:s,connectCount:0,skipped:0,capped:!1}}if(a=d.response_metadata?.next_cursor??"",!a)break}let r=0,i=0,c=!1,l="";while(!0){let u={types:"im",limit:"200"};if(l)u.cursor=l;let d=await ye(e,"conversations.list",u,n);for(let f of d.channels??[]){let p=f.user;if(!p||o.has(p))continue;if(r>=oh){c=!0;break}o.add(p),r++;let g;try{g=(await ye(e,"users.info",{user:p},n)).user}catch(h){if(h instanceof Dt)throw h;i++;continue}if(g&&Rp(g,t))return{id:p,dm:String(f.id??""),workspaceCount:s,connectCount:r,skipped:i,capped:c}}if(c)break;if(l=d.response_metadata?.next_cursor??"",!l)break}return{id:"",workspaceCount:s,connectCount:r,skipped:i,capped:c}}function ah(e,t){if(t.workspaceCount===0)return Error(`Cannot resolve ${e}: users.list returned no members at all, so nothing could have matched.
|
|
330
432
|
`+`That is a token or scope fault, not a wrong handle — this says nothing about whether ${e} exists.
|
|
331
|
-
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)`,
|
|
332
|
-
`+(
|
|
433
|
+
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 ${oh} 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.
|
|
434
|
+
`+(s.length?`This search was incomplete: ${s.join("; ")}.
|
|
333
435
|
`:"")+`Slack Connect people from another workspace are not in users.list, so if they never
|
|
334
436
|
DMed you they cannot be found by name at all. Look them up and use their ID:
|
|
335
|
-
slack user ls --external`)}async function
|
|
336
|
-
`)}catch{}}function
|
|
337
|
-
`)[0]??"",emoji:
|
|
338
|
-
`;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function
|
|
339
|
-
`)}function
|
|
340
|
-
`).map((
|
|
341
|
-
│ ${
|
|
437
|
+
slack user ls --external`)}async function Wt(e,t,n){let s=t.startsWith("@")?t.slice(1):t;if(ac(s))return s;if(!t.startsWith("@"))throw Error(`Expected @user or a user ID, got: ${t}`);let o=Rn(s),a=await ye(e,"auth.test",{},n);if(o==="you"||o==="me"||Rn(a.user??"")===o){if(!a.user_id)throw Error("auth.test did not return user_id");return a.user_id}let r=await ih(e,o,n);if(r.id)return r.id;throw ah(t,r)}function dt(e){let t=e.match(/(?:app\.slack\.com\/client\/T[A-Za-z0-9]+|[A-Za-z0-9-]+\.slack\.com\/archives)\/([A-Za-z0-9]+)(?:\/p(\d{10})(\d{6}))?/);if(!t)return;let n=t[1],s=t[2]&&t[3]?`${t[2]}.${t[3]}`:void 0,o=e.indexOf("?"),a=o>=0?new URLSearchParams(e.slice(o)):void 0,r=a?.get("thread_ts")??void 0,l={channel:a?.get("cid")??void 0??n};if(s)l.ts=s;if(r)l.threadTs=r;return l}function HD(e){return dt(e)?.channel}function Ip(e){return/^[CDG][A-Z0-9]{8,}$/.test(e)}function ac(e){return/^[UW][A-Z0-9]{6,}$/.test(e)}async function be(e,t,n){let s=HD(t);if(s)return s;if(!t.startsWith("@")&&!t.startsWith("#")){if(Ip(t))return t;if(ac(t))return ic(e,t,n);throw Error(`Target must start with # or @ (or be a Slack URL/ID), got: ${t}`)}if(t.startsWith("#")&&Ip(t.slice(1)))return t.slice(1);let o=t.startsWith("@"),a=t.slice(1),r=Rn(a);if(o){if(ac(a))return ic(e,a,n);let l=await ye(e,"auth.test",{},n);if(r==="you"||r==="me"||Rn(l.user??"")===r){let f=l.user_id;if(!f)throw Error("auth.test did not return user_id");return await rh(e,f,n)||jt(e,f,n)}let d=await ih(e,r,n);if(!d.id)throw ah(t,d);if(d.dm)return d.dm;return ic(e,d.id,n,t)}let i=a.toLowerCase(),c="";while(!0){let l={limit:"200",types:"public_channel,private_channel",exclude_archived:"true"};if(c)l.cursor=c;let u=await ye(e,"conversations.list",l,n);for(let d of u.channels??[])if(String(d.name??"").toLowerCase()===i)return String(d.id??"");if(c=u.response_metadata?.next_cursor??"",!c)break}throw Error(`channel not found: ${t}`)}async function Hs(e,t,n){try{let s=await ye(e,"users.info",{user:t},n),o=s.user?.profile?.display_name,a=o&&o.length>0?o:s.user?.real_name??s.user?.name??t,r=s.user?.name??t;return[a,r]}catch{return[t,t]}}async function Re(e,t,n){try{let s=await ye(e,"users.info",{user:t},n),o=s.user?.profile?.display_name;if(o&&o.length>0)return o;return s.user?.real_name??s.user?.name??t}catch{return t}}async function ch(e,t){let n=[],s="";while(!0){let o={limit:"200"};if(s)o.cursor=s;let a=await ye(e,"users.list",o,t);if(n.push(...a.members??[]),s=a.response_metadata?.next_cursor??"",!s)break}return{members:n}}async function lh(e,t,n){let s=[],o="";while(!0){let a={channel:t,limit:"200"};if(o)a.cursor=o;let r=await ye(e,"conversations.members",a,n);if(s.push(...r.members??[]),o=r.response_metadata?.next_cursor??"",!o)break}return s}async function hc(e,t={},n){let s={limit:String(t.limit??50)};if(t.filter)s.filter=t.filter;if(t.cursor)s.cursor=t.cursor;return kt(e,"saved.list",s,n)}var gc=(e)=>({item_type:"message",item_id:e.channel,ts:e.ts});async function uh(e,t,n={},s){let o={...gc(t),todo_state:n.todo===!1?"saved":"to_do"};if(n.due)o.date_due=String(n.due);return kt(e,"saved.add",o,s)}async function mc(e,t,n,s){let o=gc(t);if(n.mark)o.mark=n.mark;if(n.todo!==void 0)o.todo_state=n.todo?"to_do":"saved";if(n.due!==void 0)o.date_due=String(n.due);return kt(e,"saved.update",o,s)}async function dh(e,t,n){return kt(e,"saved.delete",gc(t),n)}async function zs(e,t){return kt(e,"drafts.list",{},t)}async function fh(e,t,n,s){let{randomUUID:o}=await import("node:crypto"),a=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Er(n)}]}]);return kt(e,"drafts.create",{client_msg_id:o(),destinations:JSON.stringify([{channel_id:t}]),blocks:a,file_ids:JSON.stringify([]),is_from_composer:"true"},s)}async function ph(e,t,n,s,o){let a=JSON.stringify([{type:"rich_text",elements:[{type:"rich_text_section",elements:Er(s)}]}]),r=(Date.now()/1000).toFixed(6);return kt(e,"drafts.update",{draft_id:t,client_last_updated_ts:r,destinations:JSON.stringify([{channel_id:n}]),blocks:a,file_ids:JSON.stringify([])},o)}async function hh(e,t,n){return kt(e,"conversations.info",{channel:t},n)}async function ss(e,t,n){return ye(e,"users.info",{user:t},n)}async function gh(e,t,n){try{let s=await ye(e,"users.info",{user:t,include_locale:"true"},n);return typeof s.user?.locale==="string"?s.user.locale:void 0}catch{return}}async function vn(e,t,n){return ye(e,"conversations.info",{channel:t},n)}async function mh(e,t,n){let s=(Date.now()/1000).toFixed(6);return kt(e,"drafts.delete",{draft_id:t,client_last_updated_ts:s},n)}async function yc(e,t){let n=await kt(e,"auth.test",{},t);return{userId:String(n.user_id??""),teamId:String(n.team_id??"")}}async function yh(e,t,n,s={},o){let{statSync:a,readFileSync:r}=await import("node:fs"),{basename:i}=await import("node:path"),c=a(n),l=i(n),u=await ye(e,"files.getUploadURLExternal",{filename:l,length:String(c.size)},o),{upload_url:d,file_id:f}=u;if(!d||!f)throw Error("files.getUploadURLExternal returned no upload_url/file_id");let p=r(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??l}],channel_id:t};if(s.threadTs)h.thread_ts=s.threadTs;if(s.initialComment)h.initial_comment=s.initialComment;let b=await Oe(e,"files.completeUploadExternal",h,o),m={fileId:f},w=b.files?.[0]?.permalink;if(w)m.permalink=w;return m}function Ks(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 wh=["todo","saved","completed","archived"],Ys=(e)=>typeof e==="string"?e:"",bh=(e)=>{let t=typeof e==="number"||typeof e==="string"?Number(e):0;return Number.isFinite(t)?t:0};function bc(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:Ys(s.item_id),ts:Ys(s.ts),due:bh(s.date_due),completed:bh(s.date_completed),todoState:Ys(s.todo_state),state:Ys(s.state),archived:s.is_archived===!0,itemType:Ys(s.item_type)}))}function Dh(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 Gs(e){return e.completed>0||e.state==="completed"||e.todoState==="completed"}function wc(e,t,n){let s=Gs(e)?"☑":e.todoState==="to_do"?"☐":"·";if(!e.due)return`${s} no due date`;let o=!Gs(e)&&e.due<t?" OVERDUE":"";return`${s} due ${n(e.due)}${o}`}function Dc(e,t,n){return`${e.replace(/\/+$/,"")}/archives/${t}/p${n.replace(".","")}`}import{existsSync as n0,readFileSync as s0}from"node:fs";import{homedir as r0}from"node:os";import{join as o0}from"node:path";import{existsSync as zD,mkdirSync as YD,readFileSync as GD,writeFileSync as XD}from"node:fs";import{homedir as VD}from"node:os";import{dirname as ZD,join as QD}from"node:path";var e0=3600000,yo={now:()=>Date.now(),path:()=>QD(process.env.HOME||VD(),".config","slack-cli","cache.json")},bo=!0,rn;function kh(){return{channels:{},users:{}}}function kc(){if(rn)return rn;if(rn=kh(),!bo)return rn;try{let e=yo.path();if(!zD(e))return rn;let t=JSON.parse(GD(e,"utf8"));for(let n of["channels","users"]){let s=t?.[n];if(!s||typeof s!=="object"||Array.isArray(s))continue;for(let[o,a]of Object.entries(s))if(a&&typeof a==="object"&&typeof a.value==="string"&&typeof a.expires==="number")rn[n][o]={value:a.value,expires:a.expires}}}catch{rn=kh()}return rn}function t0(e){if(!bo)return;try{let t=yo.path();YD(ZD(t),{recursive:!0}),XD(t,JSON.stringify(e,null,2)+`
|
|
438
|
+
`)}catch{}}function xh(e,t){return e?`${e} ${t}`:void 0}function wo(e,t,n){if(!bo)return;let s=xh(t,n);if(!s)return;let o=kc()[e][s];if(!o)return;if(o.expires<=yo.now()){delete kc()[e][s];return}return o.value}function Do(e,t,n,s,o=e0){if(!bo)return;let a=xh(t,n);if(!a)return;let r=kc();r[e][a]={value:s,expires:yo.now()+o},t0(r)}var xc={marker:"pushpin",progress:{done:"white_check_mark",dropped:"no_entry_sign",doing:"eyes",pending:"hourglass_flowing_sand"},flags:{alert:"exclamation","needs-discussion":"thinking_face",waiting:"speech_balloon",blocked:"lock"}},rs=["done","dropped","doing","pending"],$h=["alert","needs-discussion","waiting","blocked"];function i0(){return o0(process.env.HOME||r0(),".config","slack-cli","todo.json")}function ko(e){return e.replace(/^:+|:+$/g,"")}function Xs(e=i0()){let t={marker:xc.marker,progress:{...xc.progress},flags:{...xc.flags}};try{if(!n0(e))return t;let n=JSON.parse(s0(e,"utf8"));if(typeof n.marker==="string"&&n.marker.trim())t.marker=ko(n.marker.trim());for(let s of rs){let o=n.progress?.[s];if(typeof o==="string"&&o.trim())t.progress[s]=ko(o.trim())}for(let s of $h){let o=n.flags?.[s];if(typeof o==="string"&&o.trim())t.flags[s]=ko(o.trim())}}catch{}return t}function Sh(e,t,n=!1){return`${n?"-":""}${t?"has":"hasmy"}::${ko(e)}:`}function Ch(e,t,n={}){let s=n.shared===!0,o=(i)=>Sh(i,s),a=(i)=>Sh(i,s,!0),r=[];if(e==="untriaged")r.push(o(t.marker),...rs.map((i)=>a(t.progress[i])));else if(e==="stuck")r.push(o(t.marker),a(t.progress.done),a(t.progress.dropped),`(${$h.map((i)=>o(t.flags[i])).join(" OR ")})`);else if(e==="open")r.push(o(t.marker),a(t.progress.done),a(t.progress.dropped));else{let i=rs.indexOf(e);r.push(o(t.progress[e]));for(let c of rs.slice(0,i))r.push(a(t.progress[c]))}if(n.in){let i=n.in.startsWith("#")||n.in.startsWith("@")?n.in:`#${n.in}`;r.push(`in:${i}`)}if(n.from){let i=n.from==="me"||n.from.startsWith("@")?n.from:`@${n.from}`;r.push(`from:${i}`)}return r.join(" ")}var a0=3,c0={sleep:(e)=>l0()?Promise.resolve():new Promise((t)=>setTimeout(t,e))};function l0(){return!!process.env.VITEST||!1||!!process.env.BUN_TEST}async function Ve(e,t,n=a0){for(let s=0;;s++)try{return await t()}catch(o){if(!(o instanceof Ke))throw o;if(s>=n)throw Error(`Slack rate limit hit on ${e} — gave up after ${n} retries. Try again in a minute.`);console.error(`Warning: Slack rate limit hit on ${e} — backing off for ${o.retryAfter}s`),await c0.sleep(o.retryAfter*1000)}}var _h=new Map;async function Ah(e,t){let n=_h.get(e);if(n)return n;let s=await Ve("auth.test",()=>Gn(e,t)),o={userId:s.userId,teamId:s.teamId};return _h.set(e,o),o}async function Fh(e,t){return(await Ah(e,t)).userId}async function Sc(e,t){try{return(await Ah(e,t)).teamId}catch{return""}}async function _c(e,t,n,s){if(!t.startsWith("#"))return n(e,t,s);let o=await Sc(e,s),a=wo("channels",o,t);if(a)return a;let r=await Ve("resolveChannel",()=>n(e,t,s));return Do("channels",o,t,r),r}async function Th(e,t,n,s){let o=await Sc(e,s),a=wo("users",o,t);if(a)return a;let r=await Ve("users.info",()=>n(e,t,s));if(r&&r!==t)Do("users",o,t,r);return r}async function Oh(e,t,n,s){let o=await Sc(e,s),a=wo("users",o,`tz:${t}`);if(a)return a==="?"?null:a;let r=null;try{let i=await Ve("users.info",()=>n(e,t,s));if(i?.user?.is_bot===!0||t==="USLACKBOT")return Eh(o,t,null);let c=i?.user?.tz;r=typeof c==="string"&&c?c:null}catch{return null}return Eh(o,t,r)}function Eh(e,t,n){return Do("users",e,`tz:${t}`,n??"?"),n}async function Rh(e,t,n,s,o,a){let r=o.progress[s],i=await Fh(e,a),c=await Ve("reactions.get",()=>Qu(e,t,n,a)),l=new Set(c.filter((p)=>p.users.includes(i)).map((p)=>p.name)),u=rs.map((p)=>o.progress[p]).filter((p)=>l.has(p));if(u.length===1&&u[0]===r)return{noop:!0,removed:[],leftover:[]};if(!l.has(r))await Ve("reactions.add",()=>Cr(e,t,n,r,a));let d=[],f=[];for(let p of u){if(p===r)continue;try{await Ve("reactions.remove",()=>Ar(e,t,n,p,a)),d.push(p)}catch{f.push(p)}}return{noop:!1,added:s,removed:d,leftover:f}}async function Ih(e,t,n,s,o,a,r){let i=o.flags[s];if(a)await Ve("reactions.remove",()=>Ar(e,t,n,i,r));else await Ve("reactions.add",()=>Cr(e,t,n,i,r));return i}var Ec=1000;async function vh(e,t,n,s={}){let o=s.limit??Ec,a=s.cookie,r=await Fh(e,a),i=rs.map((f)=>n.progress[f]),c=[],l=0,u,d=!1;while(l<o){let f=Math.min(200,o-l),p=await Ve("conversations.history",()=>Cn(e,t,f,void 0,u,a)),g=p.messages??[];l+=g.length;for(let h of g){let b=String(h.ts??"");if(!b)continue;let m=new Set((h.reactions??[]).filter((D)=>(D.users??[]).map(String).includes(r)).map((D)=>String(D.name??""))),w=i.filter((D)=>m.has(D));if(w.length<2)continue;c.push({ts:b,text:String(h.text??"").split(`
|
|
439
|
+
`)[0]??"",emoji:w,keep:w[0]})}if(u=p.response_metadata?.next_cursor||void 0,!u||g.length===0)break;if(l>=o){d=!0;break}}if(s.fix)for(let f of c)try{try{await Ve("reactions.add",()=>Cr(e,t,f.ts,f.keep,a))}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",()=>Ar(e,t,f.ts,p,a))}f.fixed=!0}catch(p){f.fixed=!1,f.error=p instanceof Error?p.message:String(p)}return{scanned:l,findings:c,truncated:d}}var u0=!0,d0;function $c(e){if(u0=e,!e)d0=void 0}function Ne(e){return e.replace(new RegExp(`[${"\\\\¥"}](.)`,"gs"),(t,n)=>{switch(n){case"n":return`
|
|
440
|
+
`;case"t":return"\t";case"\\":case"¥":return n==="¥"?"¥":"\\";default:return t}})}function os(e){return e.replace(new RegExp(`[${"\\\\¥"}]`,"g"),(t)=>`\\${t}`).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}var is=(e)=>e&&typeof e==="object"&&!Array.isArray(e)?e:{},Be=(e)=>typeof e==="string"?e:"";function f0(e){return(Array.isArray(e.message_blocks)?e.message_blocks:[]).map((n)=>Be(is(is(n).message).text)).filter(Boolean).join(`
|
|
441
|
+
`)}function Cc(e){return(Array.isArray(e.attachments)?e.attachments:[]).map(is).map((n)=>{let s=n.is_share===!0||n.is_msg_unfurl===!0||Array.isArray(n.message_blocks),o=is(is((Array.isArray(n.message_blocks)?n.message_blocks:[])[0]));return{shared:s,unfurl:!s&&!!Be(n.original_url),author_id:Be(n.author_id)||Be(is(o.message).user)||null,author_name:Be(n.author_name)||null,channel_id:Be(n.channel_id)||Be(o.channel)||null,ts:Be(n.ts)||Be(o.ts)||null,title:Be(n.title)||null,text:Be(n.text)||f0(n)||Be(n.pretext)||Be(n.fallback),permalink:Be(n.from_url)||Be(n.title_link)||Be(n.original_url)||null}})}function Ph(e,t){return e.filter((n)=>!n.unfurl&&(n.text||n.title)).map((n)=>{let s=n.author_name??n.author_id,o=n.shared?`↪ shared message${s?` from @${s}`:""}${n.channel_id?` in <#${n.channel_id}>`:""}${n.ts?` · ${t(n.ts)}`:""}`:`▸ ${n.title??"attachment"}`,a=n.text?n.text.replace(/\n+$/,"").split(`
|
|
442
|
+
`).map((i)=>`
|
|
443
|
+
│ ${i}`).join(""):"",r=n.permalink?`
|
|
342
444
|
${n.permalink}`:"";return`
|
|
343
|
-
${
|
|
344
|
-
`)}function
|
|
345
|
-
`)),
|
|
346
|
-
⚠ QUIET HOURS (${
|
|
347
|
-
`)}catch{}process.exit(1)}}function
|
|
348
|
-
`),console.info=console.log;if(!
|
|
349
|
-
`),console.warn=console.error}import{closeSync as
|
|
445
|
+
${o}${a}${r}`}).join("")}var Lh=new Set(["send","reply","outbox flush","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"]),p0={channels:"channel",ch:"channel"};function h0(e){let[t="",n=""]=e.map(String),s=p0[t]??t;return Lh.has(s)||Lh.has(`${s} ${n}`)}function g0(e,t){return String(e[0]??"")==="ask"&&t.ls===!0}function Mh(e,t,n){let s=n.botTokenSource;if(!s||n.globalPaths.includes(s))return null;if(n.slackTokenSet||n.activeTokenIsBot)return null;if(!h0(e)||g0(e,t)||t["as-bot"]===!0)return null;let o=s==="shell"?"exported in the environment":`set in ${s}`,a="as-bot"in t;return[`Error: refusing to act as YOU — SLACK_BOT_TOKEN is ${o}, but \`${e.slice(0,2).join(" ")}\` would use your user session, not the bot.`,a?" 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(`
|
|
446
|
+
`)}function Pn(e){return e.toLowerCase().replace(/[-_\s]/g,"")}function on(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function m0(e,t){let n=Pn(t),s=on(e.profile);for(let a of[e.name,e.real_name,s.display_name,s.real_name])if(typeof a==="string"&&a&&Pn(a)===n)return!0;let o=typeof s.email==="string"?s.email.toLowerCase():"";return o!==""&&o===t.toLowerCase()}function y0(e){let t=on(e.profile),n=new Set;for(let s of[t.display_name,e.real_name,e.name,t.real_name])if(typeof s==="string"&&s){let o=Pn(s);if(o.length>=2)n.add(o)}return[...n]}function b0(e,t){let n=Pn(e),s,o=!1;for(let a of t){let r=typeof a.id==="string"?a.id:"";if(!r)continue;for(let i of y0(a)){let c=-1;if(n===i)c=e.length;else for(let l of Bh)if(e.length>l.length&&e.endsWith(l)&&Pn(e.slice(0,e.length-l.length))===i){c=e.length-l.length;break}if(c<0)continue;if(!s||i.length>s.formLen)s={userId:r,matchLen:c,formLen:i.length,display:Tc(a)},o=!1;else if(i.length===s.formLen&&s.userId!==r)o=!0}}if(!s)return;return o?"ambiguous":{userId:s.userId,matchLen:s.matchLen,display:s.display}}async function an(e,t,n,s){let o=`[${jh}ー]+`,a=`${o}(?:[._-]+${o})*`,r=new RegExp(`(?<![A-Za-z0-9._@<-])@(${a})`,"gu"),i=new Set;for(let w of t.matchAll(r))i.add(w[1]);if(i.size===0)return{text:t,resolved:[],unresolved:[]};let c=new Map;for(let w of i)c.set(w,{status:"pending"});let l=(w)=>{for(let D of i){if(c.get(D).status!=="pending")continue;if(Fc(D)){let k=b0(D,w);if(k==="ambiguous")c.set(D,{status:"ambiguous"});else if(k)c.set(D,{status:"resolved",userId:k.userId,matchLen:k.matchLen,display:k.display})}else{let k=w.filter((A)=>m0(A,D)),E=new Set(k.map((A)=>typeof A.id==="string"?A.id:"").filter(Boolean));if(E.size===1){let A=k.find((_)=>typeof _.id==="string");c.set(D,{status:"resolved",userId:A.id,matchLen:D.length,display:Tc(A)})}else if(E.size>1)c.set(D,{status:"ambiguous"})}}},u=!1;try{let w=await Or(e,s);l((w.members??[]).map(on)),u=!0}catch{u=!1}let d=[...i].some((w)=>c.get(w).status==="pending"),f=!1,p=!0;if(d&&n){f=!0;try{let w=await Ki(e,n,s),D=[];for(let k of w){let E=on(await qi(e,k,s)),A=on(E.user);if(typeof A.id!=="string")A.id=k;D.push(A)}l(D)}catch{p=!1}}let g=u&&(n?f&&p:!0),h=[],b=[];for(let w of i){let D=c.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")b.push({surface:`@${w}`,reason:"ambiguous"});else b.push({surface:`@${w}`,reason:g?"no-match":"unavailable"})}return{text:t.replace(r,(w,D)=>{let k=c.get(D);if(k&&k.status==="resolved")return`<@${k.userId}>${D.slice(k.matchLen)}`;return w}),resolved:h,unresolved:b}}function xo(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 Nh(e,t,n,s={}){let o=s.warn??((r)=>process.stderr.write(`${r}
|
|
447
|
+
`)),a=await an(e,t,n,s.cookie);for(let r of xo(a.unresolved))o(`warn: ${r}`);return a.text}var Bh=["さん","さま","様","君","くん","ちゃん","氏","先生","先輩","殿","老师","老師","兄","姐","哥","姐妹"],jh="\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}A-Za-z0-9";function Fc(e){return/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(e)}function w0(e){let t=[],n=new RegExp(`([${jh}]{1,12})(${Bh.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 D0(e){let t=on(e.profile),n=new Set;for(let s of[e.name,e.real_name,t.display_name,t.real_name]){if(typeof s!=="string"||!s)continue;for(let o of[s,...s.split(/\s+/)]){let a=Pn(o);if(a.length>=2)n.add(a)}}return[...n]}function k0(e,t){let n=Pn(e);if(n.length<2)return;for(let s of t)if(n===s)return s;if(Fc(e)){for(let s of t)if(n.includes(s)||s.includes(n))return s}return}function Tc(e){return[on(e.profile).display_name,e.real_name,e.name].filter((s)=>typeof s==="string"&&s!=="")[0]??String(e.id??"?")}async function Wh(e,t,n){let s=w0(t);if(s.length===0)return[];let o=new Set;for(let l of t.matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g))o.add(l[1]);let r=((await Or(e,n)).members??[]).map(on).filter((l)=>l.deleted!==!0&&l.is_bot!==!0&&l.id!=="USLACKBOT").map((l)=>({id:typeof l.id==="string"?l.id:"",forms:D0(l),display:Tc(l)})).filter((l)=>l.id!==""),i=[],c=new Set;for(let{ref:l,honorific:u}of s)for(let d of r){let f=k0(l,d.forms);if(!f)continue;if(o.has(d.id)||c.has(d.id))break;c.add(d.id),i.push({surface:Fc(l)?`${f}${u}`:l,display:d.display,userId:d.id});break}return i}async function Ln(e,t,n,s){let o=t,a=[],r=o,i=0;while(!0){let c=r.indexOf("<@U",i);if(c===-1)break;let l=r.slice(c+2),u=l.search(/[>|]/),d=u===-1?l:l.slice(0,u);if(d.length>=9)a.push(d);i=c+1}for(let c of a){if(!n.has(c))n.set(c,await Xn(e,c,s));let l=n.get(c)??c;o=o.replaceAll(`<@${c}>`,`@${l}`),o=o.replace(new RegExp(`<@${c}\\|[^>]*>`,"g"),`@${l}`)}return o}function as(e){return e.replace(/<!date\^(\d+)\^[^|>]*(?:\|([^>]*))?>/g,(t,n,s)=>{let o=Number(n);if(!Number.isFinite(o))return s??"date";let a=new Date(o*1000);if(Number.isNaN(a.getTime()))return s??"date";let r=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],i=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],c=r[a.getUTCDay()]??"",l=i[a.getUTCMonth()]??"";return`${c}, ${l} ${String(a.getUTCDate()).padStart(2,"0")}, ${a.getUTCFullYear()}`})}function Jh(e,t=new Date){let n=new Date(e*1000),s=Ac(t),o=Ac(new Date(t.getTime()-86400000)),a=Ac(n);if(a===s)return"Today";if(a===o)return"Yesterday";let r=n.toLocaleDateString("en-US",{weekday:"long"}),i=n.toLocaleDateString("en-US",{month:"short"});return`${r}, ${i} ${String(n.getDate()).padStart(2,"0")}`}function Ac(e){return`${e.getFullYear()}-${e.getMonth()}-${e.getDate()}`}function Mn(e){let t=new Date(e*1000),n=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),o=String(t.getDate()).padStart(2,"0"),a=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${n}-${s}-${o} ${a}:${r}`}var x0=/[A-Za-z0-9_-]{32,}/g;function cs(e){return e.replace(x0,(t)=>`${t.slice(0,4)}…(${t.length-4} masked)`)}function Oc(e=new Date,t){let n=process.env.SLACK_QUIET_TZ??"Asia/Tokyo",s=!!t&&S0(t),o=s?t:n,a=Number(process.env.SLACK_QUIET_START??23),r=Number(process.env.SLACK_QUIET_END??8),i,c;try{let p=new Intl.DateTimeFormat("en-GB",{timeZone:o,hour12:!1,weekday:"short",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});c=p.format(e),i=Number(p.formatToParts(e).find((g)=>g.type==="hour")?.value??"12")}catch{return null}let l=a>r?i>=a||i<r:i>=a&&i<r,u=s?`${o}, recipient`:`${o}, sender — recipient's timezone unknown`,d=`\uD83D\uDD50 ${c} (${u})`;if(!l)return d;return`${d}
|
|
448
|
+
⚠ QUIET HOURS (${a}:00-${r}:00) — this will buzz a phone.${s?"":" Their local time may differ."} Send only for a production incident; otherwise hold it until morning.`}function S0(e){try{return new Intl.DateTimeFormat("en-GB",{timeZone:e}),!0}catch{return!1}}import{writeSync as Uh}from"node:fs";import{isatty as Kh}from"node:tty";import{format as qh}from"node:util";var _0=new Int32Array(new SharedArrayBuffer(4)),E0=141;function Hh(e,t){let n=Buffer.from(t,"utf8"),s=0;while(s<n.length)try{s+=Uh(e,n,s,n.length-s)}catch(o){let a=o.code;if(a==="EAGAIN"||a==="EWOULDBLOCK"){Atomics.wait(_0,0,0,2);continue}if(a==="EPIPE")process.exit(E0);if(e!==2)try{Uh(2,`slack: cannot write output (${a??String(o)}); output is incomplete
|
|
449
|
+
`)}catch{}process.exit(1)}}function zh(){if(!Kh(1))console.log=(...e)=>Hh(1,qh(...e)+`
|
|
450
|
+
`),console.info=console.log;if(!Kh(2))console.error=(...e)=>Hh(2,qh(...e)+`
|
|
451
|
+
`),console.warn=console.error}import{closeSync as Yh,mkdirSync as $0,openSync as Gh,readFileSync as ls,statSync as Xh,unlinkSync as So,writeFileSync as Vh}from"node:fs";import{homedir as C0}from"node:os";import{join as Zh}from"node:path";var Zs="Pinlog · 最終更新";function Rc(e){let t=new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Tokyo",hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).formatToParts(e),n=(o)=>t.find((a)=>a.type===o)?.value??"??",s=n("hour")==="24"?"00":n("hour");return`${n("year")}-${n("month")}-${n("day")} ${s}:${n("minute")} JST`}function A0(e){return`_${Zs} ${Rc(e)} · 更新はスレッドに_`}var Ic=new RegExp(`(^|\\n+)_?${Zs} \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2} JST · 更新はスレッドに_?[ \\t]*\\n*$`);function us(e){return Ic.test(e)}function Qs(e){return e.replace(Ic,"")}function vc(e,t){return`${Qs(e).trimEnd()}
|
|
350
452
|
|
|
351
|
-
${
|
|
352
|
-
`,
|
|
353
|
-
`;for(let
|
|
354
|
-
`)){let
|
|
355
|
-
`)}function
|
|
453
|
+
${A0(t)}`}function Pc(e){let n=e.match(Ic)?.[0]?.match(/(\d{4}-\d{2}-\d{2} \d{2}:\d{2} JST)/);return n?n[1]:null}class Vs extends Error{holder;constructor(e){super(`locked by ${e}`);this.holder=e;this.name="LockBusyError"}}function F0(){return Zh(process.env.HOME||C0(),".config","slack-cli","locks")}function Qh(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 T0(e,t){let n=`${e}.break`,s=`pid=${process.pid} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
|
|
454
|
+
`,o;try{o=Gh(n,"wx"),Vh(o,s)}catch(a){if(a.code!=="EEXIST")throw a;try{let r=ls(n,"utf8");if((/^pid=\d+/.test(r)?!Qh(r):Date.now()-Xh(n).mtimeMs>1e4)&&ls(n,"utf8")===r)So(n)}catch{}return}try{if(ls(e,"utf8")===t)So(e)}catch{}finally{Yh(o);try{if(ls(n,"utf8")===s)So(n)}catch{}}}function eg(e,t={}){let n=t.dir??F0(),s=t.staleMs??120000;$0(n,{recursive:!0});let o=Zh(n,`${e.replace(/[^A-Za-z0-9._-]/g,"_")}.lock`),a=`pid=${process.pid} since=${new Date().toISOString()} nonce=${Math.random().toString(36).slice(2)}${Date.now()}
|
|
455
|
+
`;for(let r=0;r<3;r++)try{let i=Gh(o,"wx");Vh(i,a),Yh(i);let c=!0,l=()=>{if(!c)return;c=!1;try{if(ls(o,"utf8")===a)So(o)}catch{}};return process.once("exit",l),l}catch(i){if(i.code!=="EEXIST")throw i;let c,l;try{c=ls(o,"utf8"),l=Date.now()-Xh(o).mtimeMs}catch{continue}if(/^pid=\d+/.test(c)?!Qh(c):l>s){T0(o,c);continue}throw new Vs(c.trim().replace(/ nonce=\S+/,"")||"another process")}throw new Vs("another process")}function ft(e,t){return`${e}:${t}`}function _o(e){let t=e.match(/^([CDG][A-Z0-9]{8,}):(\d{10}\.\d{6})$/);return t?{channel:t[1],ts:t[2]}:null}var Dg=new Map,Mc=new Map,Jc=[Ft(Lc(),".slack-cli",".env.local"),Ft(Lc(),".config/slack-cli",".env")];function Eo(e){if(!bg(e))return;let t=Wc(e,"utf8");for(let n of t.split(`
|
|
456
|
+
`)){let s=n.trim();if(!s||s.startsWith("#"))continue;let o=s.indexOf("=");if(o===-1)continue;let a=s.slice(0,o).trim(),r=s.slice(o+1).trim();if(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'"))r=r.slice(1,-1);if(Jc.includes(e))Mc.set(a,[...Mc.get(a)??[],{path:e,val:r}]);if(!(a in process.env))process.env[a]=r,Dg.set(a,e)}}function P0(e){O0(e,{recursive:!0});let t=Ft(e,".gitignore");if(!bg(t))wg(t,`*
|
|
457
|
+
`)}function L0(){for(let e of Jc)Eo(e);Eo(Ft(process.cwd(),".slack-cli",".env.local")),Eo(Ft(process.cwd(),".env.local")),Eo(Ft(process.cwd(),".env"))}function M0(e){return yg("sha256").update(e).digest("hex")}function T(e){return e&&typeof e==="object"&&!Array.isArray(e)?e:{}}function Y(e){return Array.isArray(e)?e:[]}function Fo(e){return Number(e.ts??0)}async function kg(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 Nc(e){let t=new Date(e*1000),n=t.getUTCFullYear(),s=String(t.getUTCMonth()+1).padStart(2,"0"),o=String(t.getUTCDate()).padStart(2,"0"),a=String(t.getUTCHours()).padStart(2,"0"),r=String(t.getUTCMinutes()).padStart(2,"0"),i=String(t.getUTCSeconds()).padStart(2,"0");return`${n}-${s}-${o} ${a}:${r}:${i}`}function To(e){let[t,n="000000"]=e.split("."),s=Number(t),o=new Date(s*1000),a=o.getUTCFullYear(),r=String(o.getUTCMonth()+1).padStart(2,"0"),i=String(o.getUTCDate()).padStart(2,"0"),c=String(o.getUTCHours()).padStart(2,"0"),l=String(o.getUTCMinutes()).padStart(2,"0"),u=String(o.getUTCSeconds()).padStart(2,"0"),d=n.padEnd(6,"0").slice(0,6);return`${a}-${r}-${i}T${c}:${l}:${u}.${d}`}function Uc(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 tg(e){return/^\d{4}-\d{2}-\d{2}T/.test(e)?Uc(e):e}async function Po(e,t,n,s,o){let a=typeof t.ts==="string"?t.ts:`${Fo(t)}.000000`,r=To(a),i="?";if(typeof t.user==="string"){let D=t.user,k="@"+D;if(!n.has(k)){let E=await Th(e,D,async(A,_,S)=>(await Hs(A,_,S))[1],o);n.set(k,E)}i=n.get(k)??D}else if(typeof t.username==="string")i=t.username;let c=typeof t.text==="string"?t.text:"",u=as(await Ln(e,c,n,o)).split(`
|
|
356
458
|
`),d=u[0]+(u.length>1?`
|
|
357
459
|
`+u.slice(1).map((D)=>` ${D}`).join(`
|
|
358
|
-
`):""),f=
|
|
359
|
-
\uD83D\uDCCE ${
|
|
360
|
-
${
|
|
361
|
-
`)[0]??"",f=await
|
|
362
|
-
`)[0]?.slice(0,60)}`:"";console.log(`${
|
|
460
|
+
`):""),f=s?`${s} @${i}`:`@${i}`,p=Y(t.reactions).map(T).map((D)=>{let k=typeof D.name==="string"?D.name:"",E=Number(D.count??Y(D.users).length??0);return k?`:${k}:\xD7${E}`:""}).filter(Boolean).join(" "),g=Y(t.files).map(T).map((D)=>{let k=typeof D.name==="string"?D.name:typeof D.title==="string"?D.title:"(file)",E=typeof D.size==="number"?` (${Lo(D.size)})`:"",A=typeof D.id==="string"?` [${D.id}]`:"";return`
|
|
461
|
+
\uD83D\uDCCE ${k}${E}${A}`}).join(""),h=Number(t.reply_count??0),b=h>0?` [+${h} ${h===1?"reply":"replies"}]`:"",m=await Promise.all(Cc(t).map(async(D)=>({...D,text:D.text?as(await Ln(e,D.text,n,o)):""}))),w=(p?`
|
|
462
|
+
${p}`:"")+g+Ph(m,To);return`${r} ${f}: ${d}${b}${w}`}function Lo(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function N0(e){return Y(e.files).map(T).map((t)=>({id:t.id??null,name:t.name??t.title??null,mimetype:t.mimetype??null,size:t.size??null,url_private_download:t.url_private_download??t.url_private??null,permalink:t.permalink??null}))}function xg(e){let t=N0(e),n=Cc(e);return{ts:e.ts??null,user:e.user??null,username:e.username??null,bot_id:e.bot_id??null,thread_ts:e.thread_ts??null,text:typeof e.text==="string"?e.text:"",...Array.isArray(e.reactions)&&e.reactions.length?{reactions:Y(e.reactions).map(T).map((s)=>({name:s.name??null,count:s.count??null,users:Array.isArray(s.users)?s.users:[]}))}:{},...e.reply_count!==void 0?{reply_count:e.reply_count}:{},...e.reply_users_count!==void 0?{reply_users_count:e.reply_users_count}:{},...e.latest_reply!==void 0?{latest_reply:e.latest_reply}:{},...t.length>0?{files:t}:{},...n.length>0?{attachments:n}:{}}}async function B0(e,t,n,s,o){let a=[];for(let r of n){let i=r;if(Number(r.reply_count??0)>0&&typeof r.ts==="string"){let c=await Pe(e,t,r.ts,200,o),l=Y(c.messages).map(T);i=l[l.length-1]??r}if(i.user!==s)a.push(r)}return a}async function ng(e,t,n,s="text",o=!1,a){let r=dt(t),i=await be(e,t,a),c=new Map,u=await(async()=>{if(r?.threadTs){let f=await Pe(e,i,r.threadTs,n,a);return Y(f.messages).map(T)}let d=await rt(e,i,n,void 0,void 0,a);return Y(d.messages).map(T).reverse()})();if(o){let{userId:d}=await lc(e,a);u=await B0(e,i,u,d,a)}if(s==="jsonl"){for(let d of u)console.log(JSON.stringify(xg(d)));return}for(let d of u)console.log(await Po(e,d,c,void 0,a))}function j0(e){let t=(o)=>o.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t"),n=typeof e.user==="string"?e.user:typeof e.bot_id==="string"?e.bot_id:"",s=Array.isArray(e.files)&&e.files.length?` [files: ${e.files.length}]`:"";return`${String(e.ts)} ${n} ${t(typeof e.text==="string"?e.text:"")}${s}`}async function W0(e,t,n,s){let o=[],a;for(let r=0;r<200;r++){let i=T(await uc(e,t,n,a?{cursor:a}:{},s));for(let c of Y(i.messages).map(T))if(!o.some((l)=>l.ts===c.ts))o.push(c);if(a=String(T(i.response_metadata).next_cursor??"")||void 0,!a)return o}throw Error("thread has more than 200 pages: refusing to return it partially")}async function sg(e,t,n,s,o="text",a,r){let i=await be(e,t,a),l=r!==void 0||o==="tsv"?await W0(e,i,tg(n),a):Y((await Pe(e,i,tg(n),s,a)).messages).map(T);if(r!==void 0)l=l.filter((d)=>Number(d.ts)>Number(r));if(o==="tsv"){for(let d of l)console.log(j0(d));return}if(o==="jsonl"){for(let d of l)console.log(JSON.stringify(xg(d)));return}let u=new Map;for(let d of l)console.log(await Po(e,d,u,void 0,a))}async function J0(e){let t=await qs(e),n=Y(t.channels).map(T).filter((o)=>o.is_member===!0).sort((o,a)=>Number(a.updated??0)-Number(o.updated??0)).slice(0,10),s=new Map;for(let o of n){let a=String(o.id??""),r=typeof o.name==="string"?o.name:typeof o.user==="string"?o.user:a,i=await rt(e,a,5),c=Y(i.messages).map(T).filter((l)=>l.subtype===void 0||l.subtype===null).filter((l)=>{let u=typeof l.text==="string"?l.text:"";return u.length>0&&!u.startsWith("<@")}).slice(0,3).reverse();if(c.length===0)continue;console.log(`-- #${r} --------------------------------`);for(let l of c){let u=await kg(e,l,s),d=(typeof l.text==="string"?l.text:"").split(`
|
|
463
|
+
`)[0]??"",f=await Ln(e,d,s);console.log(` ${u}: ${f}`)}}}async function U0(e,t){let n=await zp(e,"to:me"),s=Y(Ks(n,["messages","matches"])).map(T).slice(0,t),o=new Map,a=[];for(let r of s){let i=Jh(Fo(r)),c=a[a.length-1];if(c?.label===i)c.msgs.push(r);else a.push({label:i,msgs:[r]})}for(let r=0;r<a.length;r++){let{label:i,msgs:c}=a[r];if(r>0)console.log("");console.log(` ${i}`),console.log(" ----------------------------");for(let l of[...c].reverse()){let u=T(l.channel),d=u.is_im===!0,f=typeof u.name==="string"?u.name:"dm",p;if(d&&f.startsWith("U")){let g="@"+f;if(!o.has(g)){let[,h]=await Hs(e,f);o.set(g,h)}p=`@${o.get(g)??f}`}else if(d)p=`@${f}`;else p=`#${f}`;console.log(await Po(e,l,o,p))}}}async function K0(e,t,n,s,o="text",a){let r=await qs(e,a),i=Y(r.channels).map(T).filter((c)=>s||c.is_member===!0).filter((c)=>{if(!n)return!0;return(typeof c.name==="string"?c.name:"").toLowerCase().includes(n.toLowerCase())}).sort((c,l)=>Number(l.updated??0)-Number(c.updated??0)).slice(0,t);if(o==="jsonl"){for(let c of i)console.log(JSON.stringify(c));return}for(let c of i){let l=String(c.id??""),u=typeof c.name==="string"?c.name:typeof c.user==="string"?c.user:l,d=c.is_im===!0,f=c.is_mpim===!0,p=d||f?"@":"#",g=c.is_member===!0?"":" (not joined)",h=typeof T(c.purpose).value==="string"?String(T(c.purpose).value):"",b=h?` ${h.split(`
|
|
464
|
+
`)[0]?.slice(0,60)}`:"";console.log(`${p}${u} ${l}${g}${b}`)}}function q0(e){let t=(o)=>o.startsWith("xoxp-")||o.startsWith("xoxc-"),n=Ci(),s=n.find((o)=>o.profile.token===e);if(!s)return;return n.find((o)=>t(o.profile.token)&&o.profile.teamId===s.profile.teamId)}async function Sg(e,t,n,s,o){let a=e,r=o,i;try{i=await fc(a,t,n,r)}catch(u){let d=u instanceof Error?u.message:String(u);if(e.startsWith("xoxb-")&&d.includes("not_allowed_token_type")){let f=q0(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}".`),a=f.profile.token,r=f.profile.cookie,i=await fc(a,t,n,r);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.
|
|
363
465
|
`+` Add a user-token profile: slack auth login (or slack auth login --token <token>)
|
|
364
|
-
Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw u}if(
|
|
365
|
-
`);for(let
|
|
366
|
-
`).join(" \u21B5 ");console.log(`[${
|
|
367
|
-
`))console.log(` ${
|
|
368
|
-
`)[0]??"":"(message not readable)",
|
|
369
|
-
`)[0]??"":"(message not readable)",
|
|
370
|
-
`)).slice(0,4)}function
|
|
371
|
-
`)[0]??"").slice(0,100),n=e.permalink||`${e.channel}:${e.ts}`,
|
|
466
|
+
Then select it: slack auth use <name> (or pass --workspace <name>)`),process.exit(1)}else throw u}if(s){console.log(JSON.stringify(i,null,2));return}let c=Y(Ks(i,["messages","matches"])).map(T),l=new Map;for(let u of c){let d=T(u.channel),f=d.is_im===!0,p=typeof d.name==="string"?d.name:"dm",g;if(f&&p.startsWith("U")){let h="@"+p;if(!l.has(h)){let[,b]=await Hs(a,p,r);l.set(h,b)}g=`@${l.get(h)??p}`}else if(f)g=`@${p}`;else g=`#${p}`;console.log(await Po(a,u,l,g,r))}}async function _g(e,t,n,s){let{ref:o,ts:a}=Ut(t);if(!a)console.error("Error: target must embed a message ts (e.g. #chan:1700000000.000100 or a Slack permalink URL)"),process.exit(2);return{channelId:n??await _c(e,o,be,s),ts:a}}async function H0(e,t){let n=Xs(),s={};if(!t.mine)s.shared=!0;if(t.in)s.in=t.in;if(t.from)s.from=t.from;let o=Ch(t.state,n,s);if(!t.json){let a=await je(e,t.cookie),r=t.mine?"your reactions only [hasmy:]":"anyone's reactions [has:]";console.error(`(From: ${Bo(a)} \xB7 matching ${r})`),console.error(`(query: ${o})`)}await Ve("search.messages",()=>Sg(e,o,t.count,t.json,t.cookie))}async function z0(e,t){let n=Xs(),{channelId:s,ts:o}=await _g(e,t.target,t.channelId,t.cookie),a=await Rh(e,s,o,t.state,n,t.cookie);if(a.noop){console.log(`= Already ${t.state} (ts: ${o})`);return}let r=a.removed.length?`, removed ${a.removed.map((i)=>`:${i}:`).join(" ")}`:"";if(console.log(`\u2713 ${t.state} :${n.progress[t.state]}: (ts: ${o})${r}`),a.leftover.length)console.error(`\u26A0 ${a.leftover.map((i)=>`:${i}:`).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 Y0(e,t){let n=Xs(),{channelId:s,ts:o}=await _g(e,t.target,t.channelId,t.cookie),a=await Ih(e,s,o,t.flag,n,t.remove===!0,t.cookie);console.log(`\u2713 ${t.remove?"Cleared":"Flagged"} ${t.flag} :${a}: (ts: ${o})`)}async function G0(e,t){let n=Xs(),s=t.channelId??await _c(e,t.channel,be,t.cookie),o={limit:t.limit};if(t.fix)o.fix=!0;if(t.cookie)o.cookie=t.cookie;let a=await vh(e,s,n,o);if(a.findings.length===0)console.log(`\u2713 No multi-state tasks in ${a.scanned} message(s).`);else{for(let r of a.findings){let i=r.fixed===!0?"fixed":r.fixed===!1?`FAILED: ${r.error??"?"}`:"needs --fix";console.log(`${r.ts} ${r.emoji.map((c)=>`:${c}:`).join(" ")} \u2192 keep :${r.keep}: [${i}] ${P(r.text).slice(0,60)}`)}console.log(`${a.findings.length} multi-state task(s) in ${a.scanned} message(s).`)}if(a.truncated)console.error(`\u26A0 Scan limit reached (${t.limit} messages) \u2014 older history was NOT checked. Raise it with --limit N.`)}async function X0(e,t,n,s){let o=Math.floor(Date.now()/1000)-t*86400,a=await qs(e),r=Y(a.channels).map(T).filter((u)=>u.is_member===!0&&u.is_im!==!0&&u.is_mpim!==!0).filter((u)=>{if(!s)return!0;return(typeof u.name==="string"?u.name:"").toLowerCase().includes(s.toLowerCase())}).sort((u,d)=>Number(d.updated??0)-Number(u.updated??0)),i=new Map,c=0,l=0;for(let u of r){let d=String(u.id??""),f=typeof u.name==="string"?u.name:d,p;try{p=await rt(e,d,n)}catch(h){console.error(` SKIP #${f}: ${h.message}`);continue}let g=Y(p.messages).map(T).filter((h)=>(h.subtype===void 0||h.subtype===null)&&Fo(h)>=o);if(g.length===0)continue;l+=1,c+=g.length,console.log(`## #${f} (${g.length} msgs)
|
|
467
|
+
`);for(let h of[...g].reverse()){let b=await kg(e,h,i),m=typeof h.text==="string"?h.text:"",D=as(await Ln(e,m,i)).split(`
|
|
468
|
+
`).join(" \u21B5 ");console.log(`[${Mn(Fo(h))}] ${b}: ${D}`)}console.log("")}console.error(`Dumped ${c} messages across ${l} channels (cutoff: ${t}d)`)}function V0(e){let t=[];function n(s){if(typeof s==="string"){t.push(s);return}if(Array.isArray(s)){for(let o of s)n(o);return}if(s&&typeof s==="object"){let o=s;if(typeof o.text==="string"){t.push(o.text);return}if(o.type==="link"&&typeof o.url==="string"){t.push(o.url);return}if(Array.isArray(o.elements))n(o.elements);else if(Array.isArray(o.content))n(o.content)}}for(let s of e)n(s);return t.join("").trim()}async function Mo(e,t,n){let s=new Map;return async(o)=>{if(!o)return"(unknown)";if(s.has(o))return s.get(o);try{let a=await hh(e,o,t),r=T(a.channel),i;if(r.is_im===!0){let c=typeof r.user==="string"?r.user:"";if(!c||c===n)i="@self";else{let[l]=await Hs(e,c);i=`@${l}`}}else i=`#${typeof r.name==="string"?r.name:o}`;return s.set(o,i),i}catch{return o}}}function Kc(e){let t=T(Y(e.destinations)[0]);return String(t.channel_id??e.channel_id??e.channel??"")}function Oo(e){return V0(Y(e.blocks))||(typeof e.text==="string"?e.text:"(no text)")}async function Z0(e,t,n=!1){let s=await zs(e,t),o=Y(s.drafts??s.messages??[]).map(T).filter((l)=>l.is_deleted!==!0),a=n?o:o.filter((l)=>l.is_sent!==!0);if(a.length===0){console.log(n?"No drafts.":"No pending drafts. Run with --all to include sent.");return}let r="";try{({userId:r}=await yc(e,t))}catch{}let i=await Mo(e,t,r),c=new Map;for(let l of a){let u=Kc(l),d=Oo(l),f=Number(l.date_created??l.date_create??0),p=f?Nc(f):"?",g=await i(u),h=typeof l.id==="string"?l.id:"",b=l.is_sent===!0?" [SENT]":"",m=as(await Ln(e,d,c));console.log(`-- ${h} ${g} [${p}]${b}`);for(let w of m.split(`
|
|
469
|
+
`))console.log(` ${w}`)}}var Ro=50,er=20;async function Q0(e,t,n){let s=[],o,a=0;do{let d=T(await hc(e,{filter:n.filter,limit:Ro,cursor:o},t));s.push(...bc(d));let f=T(d.response_metadata).next_cursor;o=typeof f==="string"&&f?f:void 0}while(o&&++a<er);if(o)console.error(`Note: read the first ${s.length} items only (${er} pages); the order covers those.`);let r=Dh(s).slice(0,n.limit);if(r.length===0){(n.json?console.error:console.log)(`No ${n.filter==="todo"?"to-dos":`${n.filter} items`}.`);return}let i="",c="";try{({url:i,userId:c}=await Pt(e,t))}catch{}let l=await Mo(e,t,c),u=Date.now()/1000;for(let d of r){let f;if(d.channel&&d.ts)try{let w=T(await Pe(e,d.channel,d.ts,1,t));f=Y(w.messages).map(T).find((D)=>D.ts===d.ts)}catch{}let p=d.channel&&d.ts?i?Dc(i,d.channel,d.ts):`${d.channel}:${d.ts}`:"";if(n.json){console.log(JSON.stringify({...d,done:Gs(d),permalink:p,user:f?.user??null,text:f?.text??null}));continue}let g=d.channel?await l(d.channel):`(${d.itemType||"item"})`,h=typeof f?.user==="string"?`@${await Re(e,f.user,t)}: `:"",b=typeof f?.text==="string"?f.text.split(`
|
|
470
|
+
`)[0]??"":"(message not readable)",m=b.length>100?`${b.slice(0,100)}\u2026`:b;if(console.log(`${wc(d,u,Mn)} ${P(g)}`),console.log(` ${P(h+m)}`),p)console.log(` ${p}`)}}function ek(e){if(e.kind==="done")return e.undo?["completed","todo","saved","archived"]:["todo","saved","completed","archived"];return["todo","saved","completed","archived"]}async function tk(e,t,n,s,o){let a=0;for(let r of o){let i;do{if(a++>=er)return"unknown";let c=T(await hc(e,{filter:r,limit:Ro,cursor:i},t)),l=bc(c).find((d)=>d.channel===n&&d.ts===s);if(l)return l;let u=T(c.response_metadata).next_cursor;i=typeof u==="string"&&u?u:void 0}while(i)}return}function nk(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 $o(e,t,n,s,o){let{ref:a,ts:r}=Ut(n);if(!r)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 i=await be(e,a,t),c=await tk(e,t,i,r,ek(s));if(c==="unknown"&&s.kind!=="add")console.error(`Error: not found in the first ${er*Ro} saved items \u2014 stopped there to stay under Slack's rate limits. Nothing was changed.`),process.exit(1);let l=c==="unknown"?void 0:c;if(s.kind==="add"&&l)console.error(`Error: that message is already in your To-dos (${Gs(l)?"done":l.todoState||"saved"}) \u2014 use \`slack todos edit\` or \`done\`.`),process.exit(1);if(s.kind!=="add"&&!l)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 u="",d="";try{({url:u,userId:d}=await Pt(e,t))}catch{}let f=await(await Mo(e,t,d))(i),p;try{let k=T(await Pe(e,i,r,1,t));p=Y(k.messages).map(T).find((E)=>E.ts===r)}catch{}let g=typeof p?.user==="string"?`@${await Re(e,p.user,t)}: `:"",h=typeof p?.text==="string"?p.text.split(`
|
|
471
|
+
`)[0]??"":"(message not readable)",b=cs(h.length>100?`${h.slice(0,100)}\u2026`:h),m=Date.now()/1000,w=ke("todos",JSON.stringify(s),i,r,d);if(o!==w)Se(o,w,["--- To-do ------------------------------------",` For: ${d?`@${await Re(e,d,t)} (your own To-dos)`:"(your own To-dos)"}`,` Where: ${P(f)}`,` Msg: ${P(g+b)}`,...u?[` Link: ${Dc(u,i,r)}`]:[],...l?[` Now: ${wc(l,m,Mn)}`]:[],...c==="unknown"?[` Note: not checked beyond the first ${er*Ro} saved items \u2014 it may already be saved`]:[],...nk(s,jg),"----------------------------------------------"]);let D={channel:i,ts:r};switch(s.kind){case"add":await uh(e,D,{todo:!s.saved,...s.due?{due:s.due}:{}},t),console.log(`\u2713 Added to your To-dos${s.due?` (due ${Mn(s.due)})`:""}`);break;case"done":await mc(e,D,{mark:s.undo?"uncompleted":"completed"},t),console.log(s.undo?"\u2713 Reopened":"\u2713 Marked done");break;case"edit":await mc(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 dh(e,D,t),console.log("\u2713 Removed from your To-dos");break}}async function sk(e,t,n){let s=await zs(e,t),o=Y(s.drafts).map(T).find((g)=>String(g.id)===n);if(!o)console.error(`Draft not found: ${n}`),process.exit(1);let a="";try{({userId:a}=await yc(e,t))}catch{}let r=await Mo(e,t,a),i=Kc(o),c=Oo(o),l=Number(o.date_created??0),u=String(o.last_updated_ts??"?"),d=await r(i),p=as(await Ln(e,c,new Map));console.log(`id: ${o.id}`),console.log(`channel: ${d} (${i})`),console.log(`created: ${l?Nc(l):"?"}`),console.log(`updated: ${Nc(Number(u.split(".")[0]))}`),console.log(`status: ${o.is_sent===!0?"sent":"pending"}`),console.log("---"),console.log(p)}function ke(...e){return M0(e.join(`
|
|
472
|
+
`)).slice(0,4)}function P(e){return e.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x1f\x7f-\x9f]/g,"").replace(/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g,"")}var rk={"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 he(e){let t=e instanceof Error?e.message:String(e),n=t.match(/Slack error on (\S+): (\w+)/);if(!n)return t;let[,s,o]=n;switch(o){case"missing_scope":return`Error: token lacks the ${rk[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 No(e,t,n){if(!t.startsWith("D"))return null;try{let s=await jo(e,t,n);if(!s)return null;return await Oh(e,s,ss,n)}catch{return null}}function Se(e,t,n,s,o=new Date){for(let r of n)console.log(r);let a=Oc(o,s);if(a)console.log(a);if(e!==void 0)console.error(`Code mismatch (got ${e}, expected ${t})`);console.error(`Rerun with --code=${t}`),process.exit(1)}function Ut(e){let t=dt(e);if(t)return t.ts?{ref:t.channel,ts:t.ts}:{ref:t.channel};if(e.startsWith("#")||e.startsWith("@")){let n=e.indexOf(":");if(n>0){let s=e.slice(n+1);if(/^\d{10}\.\d{6}$/.test(s))return{ref:e.slice(0,n),ts:s};if(/^\d{4}-\d{2}-\d{2}T/.test(s))return{ref:e.slice(0,n),ts:Uc(s)}}}return{ref:e}}function xt(e,t=!0){let n=dt(e);if(n){if(!t)return{ref:n.channel};let a=n.threadTs??n.ts;return a?{ref:n.channel,threadTs:a}:{ref:n.channel}}let s=e.indexOf(":");if(s>0){let a=e.slice(s+1);if(/^\d{10}\.\d{6}$/.test(a))return{ref:e.slice(0,s),threadTs:a};if(/^\d{4}-\d{2}-\d{2}T/.test(a))return{ref:e.slice(0,s),threadTs:Uc(a)}}let o=Ba(e);if(o)return o.thread_ts?{ref:o.channel,threadTs:o.thread_ts}:{ref:o.channel};return{ref:e}}async function rg(e,t,n,s,o,a=!1){let r=Ns(n),i,c;if(s)if(dt(s)){let l=await ds(e,s,t);i=l.channel,c=l.root}else{let l=xt(s);if(!l.threadTs&&/^\d{10}\.\d{6}$/.test(s)){if(!r.channel)return{error:`a bare ts needs a channel: set \`channel\` in .slack-term/settings.yml, or pass #chan:${s}`};l={ref:r.channel,threadTs:s}}if(!l.threadTs)return{error:`"${s}" is not a thread \u2014 reply only posts in threads. For a top-level post use \`slack send\`.`};i=await be(e,l.ref,t),c=l.threadTs}if(o){let l=await ds(e,o,t);if(i===void 0)i=l.channel,c=l.root;else if(!a){let u=Ja({channel:i,...c?{threadTs:c}:{}},l);if(u)return{error:u}}}if(!i||!c)return{error:"reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"};if(On(n)&&!sn(n).some((l)=>l.channel===i&&(l.thread_ts===void 0||l.thread_ts===c)))return{error:`${i} thread ${c} is not one of ${n.dir}'s subscriptions (restrict_to_subscriptions)`};return{channel:i,threadTs:c}}async function ds(e,t,n){let s=dt(t),o,a,r;if(s)o=s.channel,a=s.ts,r=s.threadTs;else{let c=xt(t);o=c.ref,a=c.threadTs}if(!a)throw Error(`--to needs a message permalink (or #chan:<ts>), got "${t}"`);let i=await be(e,o,n);if(!r)try{let c=T(await Pe(e,i,a,1,n)).messages??[],l=c.map(T).find((u)=>u.ts===a)??T(c[0]);r=typeof l.thread_ts==="string"?l.thread_ts:a}catch(c){if(!/thread_not_found/.test(c instanceof Error?c.message:String(c)))throw c;r=a}return{channel:i,ts:a,root:r}}async function un(e,t,n,s){let o=n;if(/^#?[CDG][A-Z0-9]{8,}$/.test(n)||!n.startsWith("#")&&!n.startsWith("@"))try{let r=T(await vn(e,t,s)),i=T(r.channel);if(i.is_im===!0){let c=typeof i.user==="string"?i.user:"";o=c?`@${await Re(e,c,s)}`:t}else o=typeof i.name==="string"?`#${i.name}`:t}catch{o=t}return o===t?t:`${o} (${t})`}async function je(e,t){try{return await Pt(e,t)}catch{return null}}function Kt(e,t){let n;return async()=>{if(n===void 0)n=await je(e,t);return n}}function Bn(e){if(!po())return{record:()=>{}};let t=Ep();return{metadata:$p(e,t),record:(n)=>{Cp({...n,kind:e,attribution:t})}}}function ok(e){let t=P(e.text.split(`
|
|
473
|
+
`)[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`${Mn(e.sent_at/1000)} ${e.kind.padEnd(4)} ${P(e.target??e.channel)} ${n}
|
|
372
474
|
${t}
|
|
373
|
-
${
|
|
374
|
-
`)[0]??""),
|
|
375
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(
|
|
376
|
-
${
|
|
377
|
-
`+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function
|
|
378
|
-
`+(
|
|
379
|
-
Edit it anyway with --force.`)),process.exit(1);let m=
|
|
380
|
-
`).map((
|
|
381
|
-
`).map((
|
|
382
|
-
`).map((
|
|
383
|
-
`).map((
|
|
384
|
-
`).map((
|
|
385
|
-
Check before retrying, or you will have two boards: slack pinlog ls ${
|
|
475
|
+
${P(s)}`}function Bo(e,t){let n=t?" [as bot]":"";if(!e)return`(unknown \u2014 auth.test failed)${n}`;let s=P(e.user||e.userId||"?"),o=e.userId?` (${e.userId})`:"",a=e.team?` \u2014 ${P(e.team)}`:"";return`@${s}${o}${a}${n}`}function Ee(e,t={}){return` ${"From:".padEnd(t.pad??6)}${Bo(e,t.asBot)}`}async function Bc(e,t,n=60,s){let o=typeof t.user==="string"?await Re(e,t.user,s):typeof t.username==="string"?t.username:"?",a=cs((typeof t.text==="string"?t.text:"").split(`
|
|
476
|
+
`)[0]??""),r=a.length>n?`${a.slice(0,n)}\u2026`:a,i=typeof t.ts==="string"?t.ts:"";return`${i?To(i).slice(0,16).replace("T"," "):""} @${o}${r?`: ${r}`:""}`}async function ik(e,t,n,s){let o=n.find((a)=>String(a.ts)===t)??n[0];if(!o)return t;return Bc(e,o,40,s)}function og(e){return e.toLowerCase().replace(/<[@#!][^>]+>/g," ").replace(/[^\p{L}\p{N}\s]/gu," ").replace(/\s+/g," ").trim()}function ak(e,t){let n=og(e),s=og(t);if(!n||!s)return 0;if(n===s)return 1;let o=(l)=>{let u=new Map;for(let d=0;d<l.length-1;d++){let f=l.slice(d,d+2);u.set(f,(u.get(f)??0)+1)}return u},a=o(n),r=o(s);if(a.size===0||r.size===0)return 0;let i=0;for(let[l,u]of a){let d=r.get(l);if(d)i+=Math.min(u,d)}let c=ig(a)+ig(r);return c===0?0:2*i/c}function ig(e){let t=0;for(let n of e.values())t+=n;return t}async function ag(e,t,n,s){let o=Ue();if(!o)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
477
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(s)return{botToken:o};let{ref:a}=Ut(e);if(!a.startsWith("@"))return{botToken:o};try{let r=await Wt(t,a,n);return{botToken:o,channelId:await jt(o,r)}}catch(r){console.error(`Error: could not resolve ${P(a)} to the bot's DM.
|
|
478
|
+
${r instanceof Error?r.message:String(r)}
|
|
479
|
+
`+" Tip: pass the message permalink, or --channel-id <D\u2026>, to skip the lookup."),process.exit(1)}}async function ck(e,t){let n=Kt(e,t.cookie),{ref:s,ts:o}=Ut(t.target);if(!o)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let a;if(t.channelId)a=t.channelId;else a=await be(e,s,t.cookie);let r=await Pe(e,a,o,1,t.cookie),c=Y(r.messages).map(T).find((_)=>String(_.ts)===o);if(!c)console.error(`Message not found at ts=${o} in channel ${a}`),process.exit(1);let l=typeof c.text==="string"?c.text:"",u=t.newText;if(t.tick){let _=Nf(l,t.tick.n);if(_.kind==="already")console.log(`already ticked (${_.n}.)`),process.exit(0);if(_.kind==="none")console.error("Error: the message has no \u2B1C <n>. item"),process.exit(2);if(_.kind==="missing")console.error(`Error: the message has no \u2B1C ${_.n}. item`),process.exit(2);if(_.kind==="ambiguous")console.error(`Error: several open items (${_.open.join(", ")}): name one, e.g. slack tick <target> ${_.open[0]}`),process.exit(2);u=_.text}else u=Bf(l,u,t.lanePrefix);let d=t.mentionCookie??t.cookie,f=t.mentions&&!t.tick?await Nh(t.mentionToken??e,u,a,d?{cookie:d}:{}):u;ze(f,t.allowUrlAdjacent);let p=$t(l).kind,g=$t(f).kind,h=Js(l).kind!=="other",b=h?Js(f).kind==="other":p!=="other"&&(g==="other"||p!=="open"&&g==="open");if(b&&!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"}.
|
|
480
|
+
`+(h?" Edit it anyway with --force.":` To retire it: slack ask --void='${t.target}' --reason '\u2026'
|
|
481
|
+
Edit it anyway with --force.`)),process.exit(1);let m=b,w=await n(),D=m?ke("force-edit-ask-poll",l,f,w?.userId??""):ke(l,f,w?.userId??"");if(t.code!==D)Se(t.code,D,[...m?[`\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 -------------------------",...l.split(`
|
|
482
|
+
`).map((_)=>` ${_}`),"--- Replacing with ---------------------------",...f.split(`
|
|
483
|
+
`).map((_)=>` ${_}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let k=Bn("edit"),E=p!=="other"||g!=="other"||h||Js(f).kind!=="other",A=await Mt(e,a,o,f,t.cookie,E?!0:void 0,k.metadata);console.log(`\u2713 Edited (ts: ${A})`),k.record({team:w?.team,channel:a,target:t.target,ts:o,text:f,asBot:t.asBot})}async function lk(e,t){let n=Kt(e,t.cookie),{ref:s,ts:o}=Ut(t.target);if(!o)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let a;if(t.channelId)a=t.channelId;else a=await be(e,s,t.cookie);let r=await Pe(e,a,o,1,t.cookie),c=Y(r.messages).map(T).find((f)=>String(f.ts)===o);if(!c)console.error(`Message not found at ts=${o} in channel ${a}`),process.exit(1);let l=typeof c.text==="string"?c.text:"",u=await n(),d=ke(a,o,l,u?.userId??"");if(t.code!==d){let f=await un(e,a,s,t.cookie);Se(t.code,d,["--- Deleting message -------------------------",Ee(u,{asBot:t.asBot}),` \u2192 ${f} at ${To(o)}`,...l.split(`
|
|
484
|
+
`).map((p)=>` ${p}`),"---------------------------------------------"])}await Zp(e,a,o,t.cookie),console.log(`\u2713 Deleted (ts: ${o})`)}function ln(e){return`'${e.replace(/'/g,"'\\''")}'`}async function qc(e,t,n){let s=_o(t);if(s)return{...s,ref:s.channel};let{ref:o,ts:a}=Ut(t);if(!a)console.error(`Error: ${P(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 ${ln(t)}`),process.exit(2);return{channel:await be(e,o,n),ts:a,ref:o}}async function uk(e,t,n,s){let o=T(await Pe(e,t,n,1,s)),a=Y(o.messages).map(T).find((r)=>String(r.ts)===n);if(!a)console.error(`Error: no message at ts=${n} in ${t}.`),process.exit(1);return a}function Co(e,t){if(t!==void 0)try{return Wc(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:Ne(e)}var cg=40000;function Io(e,t){if(t.length>cg)console.error(`Error: the ${e} is ${t.length} characters; Slack truncates past ${cg}. Shorten it \u2014 move detail to a linked page.`),process.exit(2)}function vo(e){let n=(e instanceof Error?e.message:String(e)).match(/Slack error on \S+: (\w+)/);if(e instanceof Dt)return!0;return!!n&&!["internal_error","fatal_error","request_timeout","service_unavailable"].includes(n[1])}function Eg(e,t){let n=Oc(e);return n&&n.includes("QUIET HOURS")?`\u26A0 Quiet hours (JST): ${t}.`:null}async function dk(e,t){let{ref:n,ts:s}=Ut(t.target);if(s||_o(t.target))console.error("Error: `pinlog new` posts a NEW board \u2014 pass a channel (#chan or C\u2026), not a message.\n"+` To change an existing board: slack pinlog set ${ln(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(ze(t.state,t.allowUrlAdjacent),t.log!==void 0)ze(t.log,t.allowUrlAdjacent),Io("reason",t.log);let o=`${t.workspace?` -w ${ln(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,a=Kt(e,t.cookie),r=await be(e,n,t.cookie),i=await a(),c=ke("pinlog-create",r,t.state,t.log??"",i?.userId??""),l=new Date,u=vc(t.state,l);if(Io("HEAD (state + footer)",u),t.code!==c){let h=await un(e,r,n,t.cookie),b=(await $g(e,r,200,t.cookie)).found;Se(t.code,c,["--- New pinlog -------------------------------",Ee(i,{asBot:t.asBot}),` \u2192 ${h} \u2014 NEW top-level message, then pinned`,...b.length?[`\u26A0 ${b.length} board(s) already in this channel \u2014 to change one, use \`slack pinlog set <board> \u2026\` instead:`,...b.slice(0,5).map((m)=>` ${ft(r,String(m.ts))} ${Cg(String(m.text))}`)]:[" (no other boards in the last 200 messages of this channel)"],"--- State (the top-level message) ------------",...u.split(`
|
|
485
|
+
`).map((m)=>` ${P(m)}`),...t.log?["--- Reason (first thread reply \u2014 notifies) ---",...t.log.split(`
|
|
486
|
+
`).map((m)=>` ${P(m)}`)]:[],"---------------------------------------------"])}let d=Bn("send"),f;try{f=await Lt(e,r,u,void 0,!1,t.cookie,!0,d.metadata)}catch(h){if(vo(h))console.error(`\u2717 HEAD was NOT posted: ${he(h)}`);else console.error(`\u26A0 UNKNOWN whether the HEAD was posted: ${he(h)}
|
|
487
|
+
Check before retrying, or you will have two boards: slack pinlog ls ${ln(t.target)}${o}`);process.exit(1)}if(!f)console.error("\u2717 Slack accepted the post but returned no ts \u2014 check the channel before retrying, it may have landed."),process.exit(1);d.record({team:i?.team,channel:r,target:t.target,ts:f,text:u,asBot:t.asBot});let p=ft(r,f);console.log(`\u2713 Posted HEAD: ${p}`);let g=Eg(l,"this new top-level post notified everyone who follows the channel");if(g)console.error(g);try{await pc(e,r,f,t.cookie),console.log("\u2713 Pinned")}catch(h){let b=h instanceof Error?h.message:String(h),m=/missing_scope/.test(b)?`the ${t.asBot?"bot":"user"} token lacks the pins:write scope`:he(h);console.error(`\u26A0 NOT pinned: ${m}.`),console.error(` The board works unpinned; pin it later with: slack pinlog pin ${p}${o}`)}if(t.log)try{let h=await Lt(e,r,t.log,f,!1,t.cookie,!0);console.log(`\u2713 Reason posted in the thread (ts: ${h})`)}catch(h){let b=ke("pinlog-log",r,f,t.log,i?.userId??"");console.error(`${vo(h)?"\u2717 The reason was NOT posted":"\u26A0 UNKNOWN whether the reason was posted"}: ${he(h)}
|
|
386
488
|
The board IS posted. Retry just the reason (check the thread first):
|
|
387
|
-
slack pinlog note ${
|
|
388
|
-
`+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let c=await n(),l=
|
|
389
|
-
`).map((
|
|
390
|
-
`).map((
|
|
391
|
-
`).map((
|
|
392
|
-
`).map((
|
|
393
|
-
Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",
|
|
394
|
-
Check it first: slack pinlog get ${l}${d}`;console.error(`${
|
|
395
|
-
The log reply was NOT posted (a log line for a change the board may not show would be a lie).`),process.exit(1)}
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
`)+(
|
|
399
|
-
`)
|
|
400
|
-
|
|
401
|
-
`))console.log(
|
|
402
|
-
`)
|
|
403
|
-
`).
|
|
404
|
-
|
|
405
|
-
`)
|
|
489
|
+
slack pinlog note ${p} ${ln(os(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${o} --code=${b}`),process.exit(1)}}async function lg(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(ze(t.log,t.allowUrlAdjacent),t.state!==void 0)ze(t.state,t.allowUrlAdjacent);Io("log line",t.log);let n=Kt(e,t.cookie),{channel:s,ts:o,ref:a}=await qc(e,t.target,t.cookie);try{eg(`pinlog-${s}-${o}`)}catch(m){if(!(m instanceof Vs))throw m;console.error(`Error: another update of ${ft(s,o)} is running (${m.holder}). Re-run when it has finished \u2014 then re-read the board, it has changed.`),process.exit(1)}let r=await uk(e,s,o,t.cookie),i=typeof r.text==="string"?r.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(!us(i)&&!t.adopt)console.error(`Error: the message at ${ft(s,o)} is not a pinlog HEAD (no "${Zs}" footer).
|
|
490
|
+
`+" Refusing to overwrite it \u2014 check the id. To turn this message into a board on purpose, add --adopt."),process.exit(1);let c=await n(),l=ft(s,o),u=new Date,d=`${t.workspace?` -w ${ln(t.workspace)}`:""}${t.asBot?" --as-bot":""}`,f=ke("pinlog-log",s,o,t.log,c?.userId??""),p=`slack pinlog note ${l} ${ln(os(t.log))}${t.allowUrlAdjacent?" --allow-url-adjacent":""}${d} --code=${f}`,g=Eg(u,"the log reply notified everyone following this thread \u2014 hold non-urgent updates until 08:00");if(t.logOnly){if(t.code!==f){let m=await un(e,s,a,t.cookie);Se(t.code,f,["--- Pinlog log reply (HEAD unchanged) --------",Ee(c,{asBot:t.asBot}),` \u2192 ${m}, thread of ${l}`,...t.log.split(`
|
|
491
|
+
`).map((w)=>` ${P(w)}`),"---------------------------------------------"])}}else{let m=vc(t.state,u);Io("new HEAD (state + footer)",m);let w=!us(i),D=ke("pinlog-update",s,o,i,t.state,t.log,c?.userId??"");if(t.code!==D){let A=await un(e,s,a,t.cookie),_=Qs(i).trim()===Qs(t.state).trim();Se(t.code,D,["--- Updating pinlog --------------------------",Ee(c,{asBot:t.asBot}),` \u2192 ${A}, ${l}`,"--- Current HEAD -----------------------------",...i.split(`
|
|
492
|
+
`).map((S)=>` ${P(S)}`),"--- New HEAD (edited in place \u2014 silent) ------",...m.split(`
|
|
493
|
+
`).map((S)=>` ${P(S)}`),"--- Log reply (in the thread \u2014 notifies) -----",...t.log.split(`
|
|
494
|
+
`).map((S)=>` ${P(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=Bn("edit");try{await Mt(e,s,o,m,t.cookie,!0,k.metadata)}catch(A){let _=A instanceof Error?A.message:String(A),S=/cant_update_message/.test(_)?`
|
|
495
|
+
Only the HEAD's author can edit it${t.asBot?"":" \u2014 if the bot created this board, add --as-bot"}.`:"",I=vo(A)?`\u2717 HEAD was NOT updated: ${he(A)}${S}`:`\u26A0 UNKNOWN whether the HEAD was updated: ${he(A)}
|
|
496
|
+
Check it first: slack pinlog get ${l}${d}`;console.error(`${I}
|
|
497
|
+
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:c?.team,channel:s,target:t.target,ts:o,text:m,asBot:t.asBot});let E;try{E=Y(T(await Pe(e,s,o,1,t.cookie)).messages).map(T).find((_)=>_.ts===o)}catch(A){console.error(`\u26A0 HEAD updated, but it could not be read back to check: ${he(A)}`)}if(E&&!Uf(m,E)){let A=Ka(E.blocks);console.error(`\u2717 HEAD was edited, but Slack does not show what was sent (${Kf(Bs(m,A),Bs(typeof E.text==="string"?E.text:"",A))}).
|
|
498
|
+
The log reply was NOT posted. Check it: slack pinlog get ${l}${d}`),process.exit(3)}console.log(`\u2713 HEAD updated${E?" (read back: matches)":""}: ${l}`)}let h=Bn("send"),b;try{b=await Lt(e,s,t.log,o,!1,t.cookie,!0,h.metadata)}catch(m){let w=vo(m);console.error((w?`\u2717 Log reply was NOT posted: ${he(m)}
|
|
499
|
+
`:`\u26A0 UNKNOWN whether the log reply was posted: ${he(m)}
|
|
500
|
+
`)+(t.logOnly?"":` The HEAD IS updated \u2014 only the log line ${w?"is":"may be"} missing.
|
|
501
|
+
`)+(w?"":` Check the thread first (retrying a reply that landed notifies everyone twice): slack pinlog get ${l}${d}
|
|
502
|
+
`)+` Retry just the log line${w?"":" (only if it is not there)"}:
|
|
503
|
+
${p}`),process.exit(1)}if(h.record({team:c?.team,channel:s,target:t.target,ts:b,text:t.log,asBot:t.asBot}),console.log(`\u2713 Logged (ts: ${b})`),g)console.error(g)}function ug(e){return e.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}function fk(e){return Rc(new Date(Number(e.split(".")[0])*1000))}async function pk(e,t,n,s){if(typeof t.user==="string"){let a=n.get(t.user);if(a!==void 0)return a;let r;try{r=await Re(e,t.user,s)}catch{r=t.user}return n.set(t.user,r),r}let o=T(t.bot_profile);if(typeof o.name==="string")return o.name;return typeof t.username==="string"?t.username:"bot"}async function hk(e,t,n,s){let{channel:o,ts:a}=await qc(e,t,n),r=[],i,c=0;do{let h=T(await Qp(e,o,a,i,200,n));for(let m of Y(h.messages).map(T)){if(String(m.ts)===a&&r.some((w)=>String(w.ts)===a))continue;r.push(m)}let b=T(h.response_metadata).next_cursor;i=typeof b==="string"&&b?b:void 0,c++}while(i&&c<50);let l=i===void 0,u=r.find((h)=>String(h.ts)===a);if(!u)console.error(`Error: no message at ts=${a} in ${o}.`),process.exit(1);let d=typeof u.text==="string"?u.text:"",f=r.filter((h)=>String(h.ts)!==a);if(s){console.log(JSON.stringify({id:ft(o,a),isPinlog:us(d),updated:Pc(d),complete:l,head:d,log:f.map((h)=>({ts:String(h.ts),user:h.user??null,text:typeof h.text==="string"?h.text:""}))}));return}if(!us(d))console.error(`\u26A0 ${ft(o,a)} has no "${Zs}" footer \u2014 showing it anyway, but it is not a pinlog HEAD.`);console.log(`=== HEAD ${ft(o,a)} ===`);for(let h of ug(d).split(`
|
|
504
|
+
`))console.log(P(h));let p=l?"":" \u2014 INCOMPLETE: the newest entries are not shown";console.log(`=== log (${f.length}${p}) ===`);let g=new Map;for(let h of f){let b=typeof h.text==="string"?h.text:"",m=P(await pk(e,h,g,n)),w=ug(b).split(`
|
|
505
|
+
`).map((D)=>P(D));console.log(`${fk(String(h.ts))} @${m}: ${w[0]??""}`);for(let D of w.slice(1))console.log(` ${D}`)}}async function $g(e,t,n,s){let o=0,a,r=[];do{let i=T(await rt(e,t,Math.min(200,n-o),void 0,a,s)),c=Y(i.messages).map(T);o+=c.length;for(let u of c)if(typeof u.text==="string"&&us(u.text))r.push(u);let l=T(i.response_metadata).next_cursor;a=typeof l==="string"&&l?l:void 0}while(a&&o<n);return{found:r,scanned:o}}function Cg(e){return P(Qs(e).split(`
|
|
506
|
+
`).find((t)=>t.trim())??"").slice(0,80)}async function gk(e,t,n,s){let{ref:o,ts:a}=Ut(t);if(a||_o(t))console.error(`Error: \`pinlog ls\` takes a channel. For one board: slack pinlog get ${ln(t)}`),process.exit(2);let r=await be(e,o,s),{found:i,scanned:c}=await $g(e,r,n,s),l=await un(e,r,o,s);if(i.length===0){console.log(`No pinlogs in the last ${c} messages of ${l}.${c>=n?` (Older ones: --limit ${n*2})`:""}`);return}for(let u of i){let d=String(u.ts),f=ft(r,d),p=String(u.text),g=Y(u.pinned_to).some((m)=>m===r)?"\uD83D\uDCCC":" ",h=Cg(p),b=typeof u.reply_count==="number"?u.reply_count:0;console.log(`${g} ${f} updated ${Pc(p)??"?"} log ${b}`),console.log(` ${h}`)}}async function mk(e,t,n){let{channel:s,ts:o}=await qc(e,t,n);try{await pc(e,s,o,n),console.log(`\u2713 Pinned ${ft(s,o)}`)}catch(a){let r=a instanceof Error?a.message:String(a);if(/already_pinned/.test(r)){console.log(`\u2713 Already pinned: ${ft(s,o)}`);return}console.error(`\u2717 NOT pinned: ${he(a)}`),process.exit(1)}}async function yk(e,t){let{ref:n,ts:s}=Ut(t.target);if(!s)console.error("Error: target must embed a message ts (e.g. #chan:2026-05-11T06:01:04.000100 or a Slack permalink URL)"),process.exit(2);let o=t.emoji.replace(/^:|:$/g,""),a;if(t.channelId)a=t.channelId;else a=await be(e,n,t.cookie);if(t.remove)await Bt(e,a,s,o,t.cookie),console.log(`\u2713 Removed :${o}: (ts: ${s})`);else await Nt(e,a,s,o,t.cookie),console.log(`\u2713 Reacted :${o}: (ts: ${s})`)}async function Hc(e,t,n,s){if(!n||!t.startsWith("D"))return!1;try{let o=T(await vn(e,t,s)),a=T(o.channel);return a.is_im===!0&&a.user===n}catch{return!1}}function bk(e){let t=new Set;for(let n of e){if(typeof n.user==="string")t.add(n.user);if(typeof n.parent_user_id==="string")t.add(n.parent_user_id);for(let s of Y(n.reply_users))if(typeof s==="string")t.add(s)}return t}async function wk(e,t,n){if(!t.startsWith("D"))return;try{let s=T(T(await vn(e,t,n)).channel);return s.is_im===!0&&typeof s.user==="string"?s.user:void 0}catch{return}}async function Dk(e,t){let{ref:n,threadTs:s}=xt(t.target),o=t.cookie;if(!t.code&&qf(t.message))console.error(Hf(t.target));let a=Kt(e,o),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await jt(e,t.userId,o);else r=await be(e,n,o);if(!t.asBot&&await Hc(e,r,(await a())?.userId,o))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
|
|
507
|
+
`+` To reach yourself with a notification, send as the bot: slack send '${t.target}' '...' --as-bot`);let i=Ne(t.message);ze(i,t.allowUrlAdjacent);let c=i,l=null;if(t.mentions){l=await an(t.mentionToken??e,i,r,t.mentionCookie),c=l.text;for(let _ of xo(l.unresolved))console.error(`\u26A0 ${P(_)}`)}let u=[];if(l&&(l.resolved.length>0||l.unresolved.length>0)){u.push("--- Mentions ---------------------------------");for(let _ of l.resolved)u.push(` \u2713 ${P(_.surface)} \u2192 @${P(_.display)} (${_.userId}) \u2014 will notify`);for(let _ of l.unresolved){let S=_.reason==="ambiguous"?"ambiguous":_.reason==="unavailable"?"lookup unavailable":"no match";u.push(` \u26A0 ${P(_.surface)} \u2014 plain text, NOT notified (${S})`)}}let d="",f="?",p=[],g,h,b;if(s)try{let _=await Pe(e,r,s,100,o);p=Y(_.messages).map(T);let S=p[p.length-1];d=typeof S?.text==="string"?S.text:"",g=typeof S?.user==="string"?S.user:void 0,h=typeof S?.bot_id==="string"?S.bot_id:void 0,b=typeof S?.ts==="string"?S.ts:void 0}catch{}else try{let _=await rt(e,r,1,void 0,void 0,o),S=Y(_.messages).map(T),I=S.filter((L)=>L.subtype===void 0||L.subtype===null)[0];d=typeof I?.text==="string"?I.text:"",f=typeof I?.user==="string"?await Re(e,I.user,o):typeof I?.username==="string"?I.username:"?";let J=S[0];g=typeof J?.user==="string"?J.user:void 0,h=typeof J?.bot_id==="string"?J.bot_id:void 0,b=typeof J?.ts==="string"?J.ts:void 0}catch{}try{let _=s?bk(p):new Set([await wk(e,r,o)].filter((S)=>!!S));for(let S of await Wh(t.mentionToken??e,c,t.mentionCookie)){if(_.has(S.userId))continue;console.error(`\u26A0 possible untagged mention: ${P(S.surface)} \u2014 @${P(S.display)} won't be notified (did you mean <@${S.userId}>?)`)}}catch{}if(process.env.SLACK_UNREPLIED_WARN!=="0"&&b&&(g||h))try{let _=await a();if(!!_&&(!!g&&!!_.userId&&_.userId===g||!!h&&!!_.botId&&_.botId===h)){let I=`slack edit "#${r}:${b}" "<\u65B0\u3057\u3044\u672C\u6587>" --channel-id ${r}`;try{let J=await In(e,r,b,o);if(J)I=`slack edit "${J}" "<\u65B0\u3057\u3044\u672C\u6587>"`}catch{}console.error("\u26A0 \u76F8\u624B\u306F\u307E\u3060\u8FD4\u4FE1\u3057\u3066\u3044\u307E\u305B\u3093(\u6700\u5F8C\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u3042\u306A\u305F\u306E\u3082\u306E\u3067\u3059)\u3002"),console.error(" \u9023\u6295\u3092\u907F\u3051\u308B\u305F\u3081\u3001\u65B0\u898F\u9001\u4FE1\u3067\u306A\u304F\u76F4\u524D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u306E edit \u3092\u691C\u8A0E\u3057\u3066\u304F\u3060\u3055\u3044:"),console.error(` ${I}`),console.error(" \u3053\u306E\u307E\u307E\u9001\u4FE1\u3059\u308B\u5834\u5408\u306F --code=XXXX \u3067\u78BA\u5B9A\u3002")}}catch{}if(s&&p.length){let _={sim:0,msg:null};for(let S of p){let I=typeof S.text==="string"?S.text:"";if(!I)continue;let J=ak(c,I);if(J>_.sim)_={sim:J,msg:S}}if(_.msg&&_.sim>=0.82){let S=Math.round(_.sim*100);console.error(`\u26A0 possible duplicate: ${S}% similar to an existing thread message \u2014 ${await Bc(e,_.msg,60,o)}`)}}let m=await a(),w=await No(e,r,o),D=ke(r,s??"",d,c,m?.userId??"");if(t.code!==D){let _=await un(e,r,n,o),S=Ee(m,{asBot:t.asBot});if(s){let I=await ik(e,s,p,o),J=p.slice(-3),L=J.length?await Promise.all(J.map(async(v)=>` ${await Bc(e,v,60,o)}`)):[" (thread context unavailable)"];Se(t.code,D,["--- Recent messages in thread ----------------",...L,...u,"--- Sending ----------------------------------",S,` \u2192 ${_} thread of ${I} \u2014 THREAD REPLY`,` Message: ${c}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}else Se(t.code,D,["--- Last message in channel ------------------",` ${f}: ${cs(d.split(`
|
|
508
|
+
`)[0]??"").slice(0,100)}`,...u,"--- Sending ----------------------------------",S,` \u2192 ${_} \u2014 NEW top-level message`,` Message: ${c}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],w)}let k=Bn("send"),E=await Lt(e,r,c,s,t.broadcast,o,void 0,k.metadata),A="";try{A=await In(e,r,E,o)}catch{}if(k.record({team:(await a())?.team,channel:r,target:t.target,ts:E,threadTs:s,permalink:A,text:c,asBot:t.asBot}),A)console.log(`\u2713 Sent: ${A}`);else console.log(`\u2713 Sent (ts: ${E})`);if(t.asBot&&r.startsWith("D"))try{let _=await Rr(e);if(!_.ok)for(let S of Ir(_,!0))console.error(S);else{let S=_.appId?`https://api.slack.com/apps/${_.appId}`:"https://api.slack.com/apps";console.error(`Note: if ${t.target} can't reply (app messaging may be off), enable Messages Tab: ${S} \u2192 App Home.`)}}catch{}}var kk=2,le=3,xk=4,Sk=5,Ag=6,_k=7,Ek=10;function $k(){return/^(1|true|yes|on)$/i.test(process.env.SLACK_TERM_ASK_EXPLAIN??"")}var dg=8,Ck=(e)=>new Promise((t)=>setTimeout(t,e)),Fg=new Set(["thread_broadcast"]),Ak=/(?<![A-Za-z0-9._@<-])@(here|channel|everyone)(?![A-Za-z0-9._-])/giu;function Tg(e){if(!e.length)return;let t=e.map((n)=>{let s=P(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.
|
|
406
509
|
${t.join(`
|
|
407
|
-
`)}`),process.exit(
|
|
408
|
-
`).entries())console.error(` ${r?" ".repeat(O(s).length+2):`${O(s)}: `}${O(i)}`)}}if(n.status==="answered")console.error(` \u3053\u306E\u5F8C\u306E\u8FFD\u8A18\u3092\u62FE\u3046: ${$n(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}function $p(e,t,n=!1){let{channelId:o,ts:s,reactable:r,threadOnly:i,audience:a,broadcast:c,cookie:l}=t,u=Le[t.lang],d={explainNow:[],explainPosted:!1},{askerUserId:f,askerBotId:h}=t,g=(N)=>typeof N==="string"&&!!N&&N!==f&&(c||a.has(N)),p=(N)=>{if(d.replyCount=Number(N.reply_count)||0,typeof N.text==="string")d.ownText=N.text},m=(N)=>{let q=typeof N.text==="string"?bt(N.text):void 0;if(q?.kind==="void")d.voided=q;return!!d.voided};function w(N){let q=G(N.reactions).map(T),H=[];for(let v=0;v<r.length;v++){let le=q.find((K)=>K.name===Te[v].name),te=le?G(le.users).filter(g):[];if(te.length)H.push({index:v,users:te})}return H}async function b(N,q){if(n)return;let H=typeof N.text==="string"?N.text:"";if(!H)return;let v=To(H,q,t.lang);if(v===H)return;try{await At(e,o,s,v,l,!0)}catch(le){console.error(` (\u8CEA\u554F\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${le instanceof Error?le.message:String(le)})`)}}let D=new Set;function S(N){for(let q of G(N.reactions).map(T)){if(typeof q.name!=="string"||!qu.includes(q.name))continue;let H=q.name===jn?"\u2795":"\u2753";for(let v of G(q.users).filter(g)){if(D.has(v))continue;if(D.add(v),!n)console.error(` (<@${v}> \u304C ${H} \u305D\u306E\u4ED6 \u3092\u62BC\u3057\u307E\u3057\u305F\u3002\u8FD4\u4FE1\u3092\u5F85\u3061\u307E\u3059)`)}}}let A=new Set,F=new Map,E=!1;async function x(N){if(N==="USLACKBOT")return!0;let q=F.get(N);if(q!==void 0)return q;try{let H=T(T(await Jn(e,N,l)).user).is_bot;if(typeof H!=="boolean")return null;return F.set(N,H),H}catch{return null}}async function W(){let N=t.threadParentTs??s;try{let q,H=0;for(;;){let v=T(await Pd(e,o,N,{oldest:s,...q?{cursor:q}:{}},l));if(G(v.messages).map(T).some((le)=>Number(le.ts)>Number(s)&&Ro(le.text)))return"exists";if(q=String(T(v.response_metadata).next_cursor??"")||void 0,!q)break;if(++H>=qw)return"exists"}}catch(q){return console.error(` (\u30B9\u30EC\u30C3\u30C9\u3092\u8AAD\u3081\u306A\u3044\u305F\u3081\u3001\u8AAC\u660E\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u6848\u5185\u306F\u307E\u3060\u51FA\u3057\u3066\u3044\u307E\u305B\u3093: ${q instanceof Error?q.message:String(q)})`),"unread"}try{await zt(e,o,u.explainNote,N,!1,l,!0)}catch(q){return console.error(` (\u8AAC\u660E\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u6848\u5185\u3092\u30B9\u30EC\u30C3\u30C9\u306B\u51FA\u305B\u307E\u305B\u3093\u3067\u3057\u305F: ${q instanceof Error?q.message:String(q)})`),"failed"}return"posted"}async function Q(N){let q=G(N.reactions).map(T).find((v)=>v.name===Dn),H=[];for(let v of q?G(q.users).filter(g):[]){if(await x(v)!==!1)continue;if(H.push(v),A.has(v))continue;if(A.add(v),!n)console.error(` (<@${v}> \u304C \u2139\uFE0F \u8AAC\u660E\u3057\u3066 \u3092\u62BC\u3057\u307E\u3057\u305F \u2014 \u56DE\u7B54\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u56DE\u7B54\u306F\u5F85\u3061\u7D9A\u3051\u307E\u3059)`)}if(d.explainNow=H,H.length&&!E&&!n){let v=await W();if(v!=="unread")E=!0,d.explainPosted=v==="posted"}}async function M(N){if(t.explain)await Q(N);if(r.length)S(N);let q=w(N);if(q.length<=1&&Fo(typeof N.text==="string"?N.text:"").length)await b(N,[]);if(!q.length)return null;if(q.length===1){let{index:K,users:re}=q[0];return{answer:r[K],how:u.howReaction(Te[K].glyph),who:re[0],choice:K+1}}let H=q.map((K)=>Te[K.index].glyph).join(" / "),v=new Map;for(let K of q)for(let re of K.users)v.set(re,(v.get(re)??0)+1);let le=[...v].filter(([,K])=>K>1).map(([K])=>K);if(!n)console.error(le.length?` (${H} \u304C\u540C\u6642\u306B\u9078\u3070\u308C\u3066\u3044\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`:` (\u56DE\u7B54\u304C\u5206\u304B\u308C\u3066\u3044\u307E\u3059: ${H}\u3002\u3069\u3061\u3089\u304B\u4E00\u65B9\u306B\u305D\u308D\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`);let te=le.sort();return await b(N,te),null}let P=[...r,...t.overflow];function I(N,q=1/0){let H=[...N].sort((v,le)=>Number(v.ts)-Number(le.ts));for(let v of H){if(!(Number(v.ts)>Number(s)))continue;if(t.after&&!(Number(v.ts)>Number(t.after)))continue;if(!g(v.user))continue;if(typeof v.subtype==="string"&&!Sp.has(v.subtype))continue;if(Number(v.ts)>=q)break;let le=typeof v.text==="string"?v.text.trim():"";if(!le||t.explain&&Ro(le))continue;if(!P.length)return{answer:le,how:u.howReply,who:v.user,ts:String(v.ts)};let te=Xi(le,P);if(te.kind==="chosen")return{answer:P[te.index-1],how:u.howReplyN(te.index),who:v.user,ts:String(v.ts),choice:te.index};let K=te.kind==="ambiguous",re=d.unchosen;if(!re||re.ambiguous&&!K||re.ambiguous===K&&Number(v.ts)<Number(re.ts))d.unchosen={text:le,who:typeof v.user==="string"?v.user:"",ts:String(v.ts),ambiguous:K}}return null}async function U(){if(delete d.unchosen,t.threadParentTs){let v=T(await Me(e,o,t.threadParentTs,100,l)),le=G(v.messages).map(T),te=le.find((K)=>K.ts===s);if(te){if(p(te),m(te))return null;let K=await M(te);if(K)return K}return I(le)}let N=T(await tt(e,o,30,s,void 0,l,!0)),q=G(N.messages).map(T),H=q.find((v)=>v.ts===s);if(H){if(p(H),m(H))return null}if(H){let v=await M(H);if(v)return v}if(!i){let v=q.filter((te)=>Number(te.ts)>Number(s)&&(h&&te.bot_id===h||f&&te.user===f)).reduce((te,K)=>Math.min(te,Number(K.ts)),1/0),le=I(q,v);if(le)return le}if(H&&Number(H.reply_count)>0){let v=T(await Me(e,o,s,30,l)),le=I(G(v.messages).map(T));if(le)return le}return null}return{poll:U,state:d,isAnswerer:g,candidates:P}}async function Cp(e,t){let{channelId:n,ts:o,question:s,reactable:r,threadOnly:i,cookie:a,timeout:c,shown:l}=t,{askerUserId:u,askerBotId:d}=t,{poll:f,state:h,isAnswerer:g,candidates:p}=$p(e,t),m="";async function w(F){for(let x=0;x<r.length;x++)try{await Tt(e,n,o,Te[x].name,a)}catch{}let E="";if(F.who)try{E=await Ie(e,F.who,a)}catch{E=F.who}if(E)console.error(` \u56DE\u7B54\u8005: ${O(E)}`);try{let x=h.ownText?Yu(h.ownText,F.choice):void 0;await At(e,n,o,Gu(s,F,E,t.lang,x),a,!0);try{await Ft(e,n,o,qi,a),await Tt(e,n,o,t.seedMarker,a)}catch{}try{if(t.explain)await Tt(e,n,o,Dn,a)}catch{}}catch(x){console.error(` (\u5143\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u66F4\u65B0\u306B\u5931\u6557: ${x instanceof Error?x.message:String(x)})`)}}let b=Date.now()+c*1000,D=0,S=Xw,A;for(;;){let F=null;try{F=await f(),D=0}catch(x){if(D++,D>=op)console.error(`Error: Slack \u3078\u306E\u554F\u3044\u5408\u308F\u305B\u306B ${D} \u56DE\u9023\u7D9A\u3067\u5931\u6557\u3057\u307E\u3057\u305F: ${x instanceof Error?x.message:String(x)}`),process.exit(ce);console.error(` (Slack \u30A8\u30E9\u30FC ${D}/${op}, \u518D\u8A66\u884C\u3057\u307E\u3059: ${x instanceof Error?x.message:String(x)})`)}A=h.unchosen;let E=h.voided;if(E){if(Ap(E,l),t.json)await Zt(e,t,{status:"void",answer:null,reason:E.reason,...E.supersededBy?{supersededBy:E.supersededBy}:{},notes:[],cursor:Ot(o,t.after)});process.exit(xp)}if(F){let x=await _p(e,{channelId:n,ts:o,threadOnly:i,replyCount:h.replyCount,isAnswerer:g,askerUserId:u,askerBotId:d,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...a?{cookie:a}:{}},t.after,(Q)=>Q.ts===F.ts);await w(F);let W={status:"answered",answer:F.answer,how:F.how,notes:x,cursor:Ot(o,t.after,F.ts,...x.map((Q)=>Q.ts))};if(ia(n,o,F.answer,W.cursor),F.who)W.who=F.who;await Zt(e,t,W),process.exit(0)}if(h.explainPosted&&t.explainExit){if(console.error(` \u8AAC\u660E\u3092\u6C42\u3081\u3089\u308C\u3066\u3044\u307E\u3059 (\u8CEA\u554F\u306F\u307E\u3060\u958B\u3044\u3066\u3044\u307E\u3059)\u3002\u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${$n(l,t.asBot,t.after)}`),t.json)await Zt(e,t,{status:"explain",answer:null,notes:[],cursor:Ot(o,t.after),explain:h.explainNow});process.exit(Kw)}if(A&&!A.ambiguous){let x=A.who;try{if(x)x=await Ie(e,x,a)}catch{}if(console.error(` (${O(x)} \u304C\u9078\u629E\u80A2\u5916\u306E\u8FD4\u4FE1\u3092\u3057\u307E\u3057\u305F \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u672C\u6587\u3092 stdout \u306B\u51FA\u3057\u307E\u3059)`),console.error(` \u9078\u629E\u80A2: ${p.map((W,Q)=>`${Q+1}. ${O(ve(W))}`).join(" ")}`),console.error(` ${l}`),console.error(` \u3053\u306E\u8FD4\u4FE1\u306E\u5F8C\u3092\u5F85\u3064: ${$n(l,t.asBot,A.ts)}`),Cd(n,o,A.text,Ot(o,t.after,A.ts)),t.json)await Zt(e,t,{status:"freetext",answer:A.text,who:A.who,notes:[],cursor:Ot(o,t.after,A.ts),explain:h.explainNow});else console.log(A.text);process.exit(Jw)}if(A&&A.ts!==m){m=A.ts;let x=A.who;try{if(x)x=await Ie(e,x,a)}catch{}console.error(` (${O(x)} \u306E\u8FD4\u4FE1\u306F\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3057\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`),console.error(` \u300C${O(A.text)}\u300D`)}if(Date.now()>=b)break;await Yw(Math.min(S,Math.max(0,b-Date.now()))),S=Math.min(S*zw,Gw)}if(A){if(console.error("Error: \u8FD4\u4FE1\u306F\u3042\u308A\u307E\u3057\u305F\u304C\u3001\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3059\u308B\u305F\u3081\u78BA\u5B9A\u3067\u304D\u307E\u305B\u3093 (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)"),console.error(` \u8FD4\u4FE1: \u300C${O(A.text)}\u300D`),console.error(` \u9078\u629E\u80A2: ${p.map((F,E)=>`${E+1}. ${O(ve(F))}`).join(" ")}`),console.error(` ${l}`),console.error(` \u8FD4\u7B54\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${$n(l,t.asBot,t.after)}`),t.json)await Zt(e,t,{status:"ambiguous",answer:null,notes:[],cursor:Ot(o,t.after),explain:h.explainNow});process.exit(Uw)}if(c===0)console.error(`\u307E\u3060\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093: ${l}`);else console.error(`Error: ${c}s \u4EE5\u5185\u306B\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)`),console.error(` ${l}`),console.error(` \u3042\u3068\u3067\u56DE\u53CE\u3059\u308B: ${$n(l,t.asBot,t.after)}`);if(t.json)await Zt(e,t,{status:"timeout",answer:null,notes:[],cursor:Ot(o,t.after),explain:h.explainNow});process.exit(Ww)}function $n(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function Zw(e,t){let{ref:n,threadTs:o}=Vn(t.target,!1),s=t.cookie,r=vt(e,s),i;if(t.channelId)i=t.channelId;else if(t.userId)i=await Rt(e,t.userId,s);else i=await ke(e,n,s);let a=(await r())?.userId??"",c=await fr(e,i,s);if(!t.asBot&&!!a&&c===a)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
|
|
409
|
-
`+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let l=
|
|
410
|
-
${u.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))d.add(
|
|
411
|
-
${
|
|
510
|
+
`)}`),process.exit(le)}function tr(e){let t=new Set;return{text:e.replace(Ak,(s,o)=>{let a=o.toLowerCase();return t.add(a),`<!${a}>`}),kinds:t}}async function jo(e,t,n){if(!t.startsWith("D"))return;try{let s=T(await vn(e,t,n)),o=T(s.channel);return o.is_im===!0&&typeof o.user==="string"?o.user:void 0}catch{return}}async function Og(e,t,n,s){let o=new Map;if(t.threadParentTs||t.replyCount!==0)try{let i=T(await Pe(e,t.channelId,t.threadParentTs??t.ts,100,t.cookie));for(let c of Y(i.messages).map(T))o.set(String(c.ts),c)}catch(i){console.error(` (\u30B9\u30EC\u30C3\u30C9\u306E\u8FFD\u8A18\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${i instanceof Error?i.message:String(i)})`)}if(!t.threadOnly&&!t.threadParentTs)try{let i=T(await rt(e,t.channelId,30,t.ts,void 0,t.cookie,!0)),c=Y(i.messages).map(T),l=c.filter((u)=>Number(u.ts)>Number(t.ts)&&(t.askerBotId&&u.bot_id===t.askerBotId||t.askerUserId&&u.user===t.askerUserId)).reduce((u,d)=>Math.min(u,Number(d.ts)),1/0);for(let u of c)if(Number(u.ts)<l&&!o.has(String(u.ts)))o.set(String(u.ts),u)}catch(i){console.error(` (DM \u306E\u8FFD\u8A18\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${i instanceof Error?i.message:String(i)})`)}let a=[...o.values()].filter((i)=>Number(i.ts)>Number(t.ts)).filter((i)=>!n||Number(i.ts)>Number(n)).filter((i)=>t.isAnswerer(i.user)&&!i.bot_id).filter((i)=>typeof i.subtype!=="string"||Fg.has(i.subtype)).filter((i)=>typeof i.text==="string"&&i.text.trim()!==""&&!Zr(i.text)).sort((i,c)=>Number(i.ts)-Number(c.ts)).filter((i)=>!s(i)),r=[];for(let i of a){let c="";try{c=await In(e,t.channelId,String(i.ts),t.cookie)}catch{}r.push({ts:String(i.ts),user:String(i.user),text:i.text.trim(),permalink:c})}return r}function Jt(...e){return e.filter((t)=>!!t).reduce((t,n)=>!t||Number(n)>Number(t)?n:t,"")}async function cn(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(` \u30B9\u30EC\u30C3\u30C9\u306E\u8FFD\u8A18 ${n.notes.length} \u4EF6 (\u56DE\u7B54\u3068\u306F\u5225):`);for(let s of n.notes){let o=s.user;try{o=await Re(e,s.user,t.cookie)}catch{}for(let[a,r]of s.text.split(`
|
|
511
|
+
`).entries())console.error(` ${a?" ".repeat(P(o).length+2):`${P(o)}: `}${P(r)}`)}}if(n.status==="answered")console.error(` \u3053\u306E\u5F8C\u306E\u8FFD\u8A18\u3092\u62FE\u3046: ${Nn(t.shown,t.asBot,n.cursor)}`);if(n.answer!==null)console.log(n.answer)}function Rg(e,t,n=!1){let{channelId:s,ts:o,reactable:a,threadOnly:r,audience:i,broadcast:c,cookie:l}=t,u=Me[t.lang],d={explainNow:[],explainPosted:!1},{askerUserId:f,askerBotId:p}=t,g=(O)=>typeof O==="string"&&!!O&&O!==f&&(c||i.has(O)),h=(O)=>{if(d.replyCount=Number(O.reply_count)||0,typeof O.text==="string")d.ownText=O.text},b=(O)=>{let j=typeof O.text==="string"?$t(O.text):void 0;if(j?.kind==="void")d.voided=j;return!!d.voided};function m(O){let j=Y(O.reactions).map(T),z=[];for(let M=0;M<a.length;M++){let ce=j.find((q)=>q.name===Te[M].name),te=ce?Y(ce.users).filter(g):[];if(te.length)z.push({index:M,users:te})}return z}async function w(O,j){if(n)return;let z=typeof O.text==="string"?O.text:"";if(!z)return;let M=Vr(z,j,t.lang);if(M===z)return;try{await Mt(e,s,o,M,l,!0)}catch(ce){console.error(` (\u8CEA\u554F\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${ce instanceof Error?ce.message:String(ce)})`)}}let D=new Set;function k(O){for(let j of Y(O.reactions).map(T)){if(typeof j.name!=="string"||!gf.includes(j.name))continue;let z=j.name===vt?"\u2795":"\u2753";for(let M of Y(j.users).filter(g)){if(D.has(M))continue;if(D.add(M),!n)console.error(` (<@${M}> \u304C ${z} \u305D\u306E\u4ED6 \u3092\u62BC\u3057\u307E\u3057\u305F\u3002\u8FD4\u4FE1\u3092\u5F85\u3061\u307E\u3059)`)}}}let E=new Set,A=new Map,_=!1;async function S(O){if(O==="USLACKBOT")return!0;let j=A.get(O);if(j!==void 0)return j;try{let z=T(T(await ss(e,O,l)).user).is_bot;if(typeof z!=="boolean")return null;return A.set(O,z),z}catch{return null}}async function I(){let O=t.threadParentTs??o;try{let j,z=0;for(;;){let M=T(await uc(e,s,O,{oldest:o,...j?{cursor:j}:{}},l));if(Y(M.messages).map(T).some((ce)=>Number(ce.ts)>Number(o)&&Zr(ce.text)))return"exists";if(j=String(T(M.response_metadata).next_cursor??"")||void 0,!j)break;if(++z>=Ek)return"exists"}}catch(j){return console.error(` (\u30B9\u30EC\u30C3\u30C9\u3092\u8AAD\u3081\u306A\u3044\u305F\u3081\u3001\u8AAC\u660E\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u6848\u5185\u306F\u307E\u3060\u51FA\u3057\u3066\u3044\u307E\u305B\u3093: ${j instanceof Error?j.message:String(j)})`),"unread"}try{await Lt(e,s,u.explainNote,O,!1,l,!0)}catch(j){return console.error(` (\u8AAC\u660E\u30EA\u30AF\u30A8\u30B9\u30C8\u306E\u6848\u5185\u3092\u30B9\u30EC\u30C3\u30C9\u306B\u51FA\u305B\u307E\u305B\u3093\u3067\u3057\u305F: ${j instanceof Error?j.message:String(j)})`),"failed"}return"posted"}async function J(O){let j=Y(O.reactions).map(T).find((M)=>M.name===nn),z=[];for(let M of j?Y(j.users).filter(g):[]){if(await S(M)!==!1)continue;if(z.push(M),E.has(M))continue;if(E.add(M),!n)console.error(` (<@${M}> \u304C \u2139\uFE0F \u8AAC\u660E\u3057\u3066 \u3092\u62BC\u3057\u307E\u3057\u305F \u2014 \u56DE\u7B54\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304F\u3060\u3055\u3044\u3002\u56DE\u7B54\u306F\u5F85\u3061\u7D9A\u3051\u307E\u3059)`)}if(d.explainNow=z,z.length&&!_&&!n){let M=await I();if(M!=="unread")_=!0,d.explainPosted=M==="posted"}}async function L(O){if(t.explain)await J(O);if(a.length)k(O);let j=m(O);if(j.length<=1&&Xr(typeof O.text==="string"?O.text:"").length)await w(O,[]);if(!j.length)return null;if(j.length===1){let{index:q,users:oe}=j[0];return{answer:a[q],how:u.howReaction(Te[q].glyph),who:oe[0],choice:q+1}}let z=j.map((q)=>Te[q.index].glyph).join(" / "),M=new Map;for(let q of j)for(let oe of q.users)M.set(oe,(M.get(oe)??0)+1);let ce=[...M].filter(([,q])=>q>1).map(([q])=>q);if(!n)console.error(ce.length?` (${z} \u304C\u540C\u6642\u306B\u9078\u3070\u308C\u3066\u3044\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`:` (\u56DE\u7B54\u304C\u5206\u304B\u308C\u3066\u3044\u307E\u3059: ${z}\u3002\u3069\u3061\u3089\u304B\u4E00\u65B9\u306B\u305D\u308D\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`);let te=ce.sort();return await w(O,te),null}let v=[...a,...t.overflow];function N(O,j=1/0){let z=[...O].sort((M,ce)=>Number(M.ts)-Number(ce.ts));for(let M of z){if(!(Number(M.ts)>Number(o)))continue;if(t.after&&!(Number(M.ts)>Number(t.after)))continue;if(!g(M.user))continue;if(typeof M.subtype==="string"&&!Fg.has(M.subtype))continue;if(Number(M.ts)>=j)break;let ce=typeof M.text==="string"?M.text.trim():"";if(!ce||t.explain&&Zr(ce))continue;if(!v.length)return{answer:ce,how:u.howReply,who:M.user,ts:String(M.ts)};let te=Ia(ce,v);if(te.kind==="chosen")return{answer:v[te.index-1],how:u.howReplyN(te.index),who:M.user,ts:String(M.ts),choice:te.index};let q=te.kind==="ambiguous",oe=d.unchosen;if(!oe||oe.ambiguous&&!q||oe.ambiguous===q&&Number(M.ts)<Number(oe.ts))d.unchosen={text:ce,who:typeof M.user==="string"?M.user:"",ts:String(M.ts),ambiguous:q}}return null}async function H(){if(delete d.unchosen,t.threadParentTs){let M=T(await Pe(e,s,t.threadParentTs,100,l)),ce=Y(M.messages).map(T),te=ce.find((q)=>q.ts===o);if(te){if(h(te),b(te))return null;let q=await L(te);if(q)return q}return N(ce)}let O=T(await rt(e,s,30,o,void 0,l,!0)),j=Y(O.messages).map(T),z=j.find((M)=>M.ts===o);if(z){if(h(z),b(z))return null}if(z){let M=await L(z);if(M)return M}if(!r){let M=j.filter((te)=>Number(te.ts)>Number(o)&&(p&&te.bot_id===p||f&&te.user===f)).reduce((te,q)=>Math.min(te,Number(q.ts)),1/0),ce=N(j,M);if(ce)return ce}if(z&&Number(z.reply_count)>0){let M=T(await Pe(e,s,o,30,l)),ce=N(Y(M.messages).map(T));if(ce)return ce}return null}return{poll:H,state:d,isAnswerer:g,candidates:v}}async function Ig(e,t){let{channelId:n,ts:s,question:o,reactable:a,threadOnly:r,cookie:i,timeout:c,shown:l}=t,{askerUserId:u,askerBotId:d}=t,{poll:f,state:p,isAnswerer:g,candidates:h}=Rg(e,t),b="";async function m(S){for(let J=0;J<a.length;J++)try{await Bt(e,n,s,Te[J].name,i)}catch{}let I="";if(S.who)try{I=await Re(e,S.who,i)}catch{I=S.who}if(I)console.error(` \u56DE\u7B54\u8005: ${P(I)}`);try{let J=p.ownText?Df(p.ownText,S.choice):void 0;await Mt(e,n,s,wf(o,S,I,t.lang,J),i,!0);try{await Nt(e,n,s,Ta,i),await Bt(e,n,s,t.seedMarker,i)}catch{}try{if(t.explain)await Bt(e,n,s,nn,i)}catch{}}catch(J){console.error(` (\u5143\u30E1\u30C3\u30BB\u30FC\u30B8\u306E\u66F4\u65B0\u306B\u5931\u6557: ${J instanceof Error?J.message:String(J)})`)}}let w=Date.now()+c*1000,D=Date.now(),k=0,E=Fn.minMs,A=0,_;for(;;){let S=null;try{S=await f(),k=0}catch(J){if(J instanceof Dt)A=J.retryAfter*1000;else{if(k++,k>=dg)console.error(`Error: Slack \u3078\u306E\u554F\u3044\u5408\u308F\u305B\u306B ${k} \u56DE\u9023\u7D9A\u3067\u5931\u6557\u3057\u307E\u3057\u305F: ${J instanceof Error?J.message:String(J)}`),process.exit(le);console.error(` (Slack \u30A8\u30E9\u30FC ${k}/${dg}, \u518D\u8A66\u884C\u3057\u307E\u3059: ${J instanceof Error?J.message:String(J)})`)}}_=p.unchosen;let I=p.voided;if(I){if(vg(I,l),t.json)await cn(e,t,{status:"void",answer:null,reason:I.reason,...I.supersededBy?{supersededBy:I.supersededBy}:{},notes:[],cursor:Jt(s,t.after)});process.exit(Ag)}if(S){let J=await Og(e,{channelId:n,ts:s,threadOnly:r,replyCount:p.replyCount,isAnswerer:g,askerUserId:u,askerBotId:d,...t.threadParentTs?{threadParentTs:t.threadParentTs}:{},...i?{cookie:i}:{}},t.after,(v)=>v.ts===S.ts);await m(S);let L={status:"answered",answer:S.answer,how:S.how,notes:J,cursor:Jt(s,t.after,S.ts,...J.map((v)=>v.ts))};if(oc(n,s,S.answer,L.cursor),S.who)L.who=S.who;await cn(e,t,L),process.exit(0)}if(p.explainPosted&&t.explainExit){if(console.error(` \u8AAC\u660E\u3092\u6C42\u3081\u3089\u308C\u3066\u3044\u307E\u3059 (\u8CEA\u554F\u306F\u307E\u3060\u958B\u3044\u3066\u3044\u307E\u3059)\u3002\u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${Nn(l,t.asBot,t.after)}`),t.json)await cn(e,t,{status:"explain",answer:null,notes:[],cursor:Jt(s,t.after),explain:p.explainNow});process.exit(_k)}if(_&&!_.ambiguous){let J=_.who;try{if(J)J=await Re(e,J,i)}catch{}if(console.error(` (${P(J)} \u304C\u9078\u629E\u80A2\u5916\u306E\u8FD4\u4FE1\u3092\u3057\u307E\u3057\u305F \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u672C\u6587\u3092 stdout \u306B\u51FA\u3057\u307E\u3059)`),console.error(` \u9078\u629E\u80A2: ${h.map((L,v)=>`${v+1}. ${P(Le(L))}`).join(" ")}`),console.error(` ${l}`),console.error(` \u3053\u306E\u8FD4\u4FE1\u306E\u5F8C\u3092\u5F85\u3064: ${Nn(l,t.asBot,_.ts)}`),Fp(n,s,_.text,Jt(s,t.after,_.ts)),t.json)await cn(e,t,{status:"freetext",answer:_.text,who:_.who,notes:[],cursor:Jt(s,t.after,_.ts),explain:p.explainNow});else console.log(_.text);process.exit(Sk)}if(_&&_.ts!==b){b=_.ts;let J=_.who;try{if(J)J=await Re(e,J,i)}catch{}console.error(` (${P(J)} \u306E\u8FD4\u4FE1\u306F\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3057\u307E\u3059\u30021 \u3064\u306B\u7D5E\u3063\u3066\u3082\u3089\u3046\u307E\u3067\u5F85\u3061\u307E\u3059)`),console.error(` \u300C${P(_.text)}\u300D`)}if(Date.now()>=w)break;await Ck(Math.min(Math.max(E,A),Math.max(0,w-Date.now()))),A=0,E=$f(E,Date.now()-D)}if(_){if(console.error("Error: \u8FD4\u4FE1\u306F\u3042\u308A\u307E\u3057\u305F\u304C\u3001\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4\u3059\u308B\u305F\u3081\u78BA\u5B9A\u3067\u304D\u307E\u305B\u3093 (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)"),console.error(` \u8FD4\u4FE1: \u300C${P(_.text)}\u300D`),console.error(` \u9078\u629E\u80A2: ${h.map((S,I)=>`${I+1}. ${P(Le(S))}`).join(" ")}`),console.error(` ${l}`),console.error(` \u8FD4\u7B54\u3057\u3066\u304B\u3089\u56DE\u53CE\u3059\u308B: ${Nn(l,t.asBot,t.after)}`),t.json)await cn(e,t,{status:"ambiguous",answer:null,notes:[],cursor:Jt(s,t.after),explain:p.explainNow});process.exit(xk)}if(c===0)console.error(`\u307E\u3060\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093: ${l}`);else console.error(`Error: ${c}s \u4EE5\u5185\u306B\u56DE\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F (\u30E1\u30C3\u30BB\u30FC\u30B8\u306F\u305D\u306E\u307E\u307E\u6B8B\u3063\u3066\u3044\u307E\u3059)`),console.error(` ${l}`),console.error(` \u3042\u3068\u3067\u56DE\u53CE\u3059\u308B: ${Nn(l,t.asBot,t.after)}`);if(t.json)await cn(e,t,{status:"timeout",answer:null,notes:[],cursor:Jt(s,t.after),explain:p.explainNow});process.exit(kk)}function Nn(e,t,n){return`slack ask --waitFor='${e}'${t?" --as-bot":""}${n?` --after=${n}`:""}`}async function Fk(e,t){let{ref:n,threadTs:s}=xt(t.target,!1),o=t.cookie,a=Kt(e,o),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await jt(e,t.userId,o);else r=await be(e,n,o);let i=(await a())?.userId??"",c=await jo(e,r,o);if(!t.asBot&&!!i&&c===i)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
|
|
512
|
+
`+` To reach yourself with a notification, ask as the bot: slack ask '${t.target}' '...' --as-bot`);let l=tr(Ne(t.question)),u=tr(Ne(t.body??"")),d=new Set([...l.kinds,...u.kinds]);for(let G of`${l.text}
|
|
513
|
+
${u.text}`.matchAll(/<!(here|channel|everyone)(?:\|[^>]*)?>/g))d.add(G[1]);let f=t.mentionToken??e,p=await an(f,l.text,r,t.mentionCookie),g=u.text?await an(f,u.text,r,t.mentionCookie):{text:"",resolved:[],unresolved:[]},h=p.text,b=g.text,m=[...p.resolved,...g.resolved],w=[...p.unresolved,...g.unresolved];Tg(w);let D=d.size>0,k=new Set(m.map((G)=>G.userId).filter((G)=>G!==i)),E=new Map(m.map((G)=>[G.userId,G.display]));for(let G of`${h}
|
|
514
|
+
${b}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)){let B=G[1];if(B===i||k.has(B))continue;k.add(B),E.set(B,await Re(f,B,t.mentionCookie))}let A;if(D)A=`anyone in ${n} (${[...d].map((G)=>`@${G}`).join(", ")})`;else{if(!k.size&&c&&c!==i)k.add(c),E.set(c,await Re(e,c,o));if(!k.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}' ...
|
|
412
515
|
Or open it to the whole channel: slack ask '${t.target}' '@here ${t.question}' ...
|
|
413
|
-
(In a 1:1 DM the other person counts automatically.)`),process.exit(
|
|
414
|
-
`)[0]??"").slice(0,100)}`,...
|
|
415
|
-
`)[0]??"")}\uFF09\u2014 \u5909\u66F4\u3067\u304D\u307E\u305B\u3093`),null;if(u.kind!=="open")return console.error(`\u2717 ${
|
|
516
|
+
(In a 1:1 DM the other person counts automatically.)`),process.exit(le);A=[...k].map((G)=>`@${P(E.get(G)??G)} (${G})`).join(", ")}let _=t.choices.map(Ne),S=_.slice(0,It),I=_.slice(It),J=!r.startsWith("D")||!!s,L=D?[]:await Promise.all([...k].map((G)=>gh(f,G,t.mentionCookie))),v=Aa({flag:t.lang,readerLocales:L,content:[h,b,...S,...I]});if(!v)console.error(`Error: unsupported language "${P(t.lang??process.env.SLACK_TERM_LANG??"")}" \u2014 use one of: ${Et.join(", ")}`),process.exit(le);let N=v.lang,H=t.explain??$k(),O=Ra(h,b,S,I,J,N,H);ze(O,t.allowUrlAdjacent);let j="",z="?";try{let G=await rt(e,r,1,void 0,void 0,o),B=Y(G.messages).map(T).filter((pe)=>pe.subtype===void 0||pe.subtype===null)[0];j=typeof B?.text==="string"?B.text:"",z=typeof B?.user==="string"?await Re(e,B.user,o):typeof B?.username==="string"?B.username:"?"}catch{}let M=await a(),ce=await No(e,r,o),te=ke(r,s??"",j,O,M?.userId??"",...t.voidAfter?["reask",`${t.voidAfter.channelId}:${t.voidAfter.ts}`,t.voidAfter.reason]:[]);if(t.code!==te){let G=await un(e,r,n,o),B=S.length?["--- Choices (seeded as reactions) ------------",...S.map((pe,we)=>` ${Te[we].glyph} ${Le(pe)}`),...I.map((pe,we)=>` (${we+11}) ${Le(pe)} \u2014 text answer only`)]:["--- Choices ----------------------------------"," (none \u2014 free-text reply)"];Se(t.code,te,["--- Last message in channel ------------------",` ${z}: ${cs(j.split(`
|
|
517
|
+
`)[0]??"").slice(0,100)}`,...B,"--- Asking -----------------------------------",Ee(M,{asBot:t.asBot}),` \u2192 ${G}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${h}`,` Answerable by: ${A}`,` Via: ${J?"reactions or thread replies":"reactions or replies in this DM"}`,...H?[" Explain: \u2139\uFE0F pill offered \u2014 pressing it asks you to explain; it is never an answer"]:[],...t.voidAfter?[` Then \u7121\u52B9\u5316: ${P(t.voidAfter.link)} (reason: ${P(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"}[v.source]}; override with --lang)`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],ce)}let q=Bn("ask"),oe=await Lt(e,r,O,s,!1,o,!0,q.metadata),U=S.length?vt:st;await uo([...S.map((G,B)=>Te[B].name),U,...H?[nn]:[]],(G)=>Nt(e,r,oe,G,o),(G,B)=>{let pe=B instanceof Error?B.message:String(B);if(G===U)console.error(` (marker ${G} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${pe})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${G} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${pe})`)});let de="";try{de=await In(e,r,oe,o)}catch{}let se=de||`${r}:${oe}`;if(console.error(`\u2713 Asked: ${se}`),q.record({team:M?.team,channel:r,target:t.target,ts:oe,threadTs:s,permalink:de,text:O,asBot:t.asBot}),t.voidAfter){if(!await Lg(e,t.voidAfter,t.voidAfter.reason,se,o))console.error(` \u26A0 \u65B0\u3057\u3044\u8CEA\u554F\u306F\u51FA\u307E\u3057\u305F\u304C\u3001\u53E4\u3044\u8CEA\u554F\u3092\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F \u2014 \u624B\u3067: slack ask --void='${P(t.voidAfter.link)}' --superseded-by='${se}'`)}if(!t.wait){console.log(Nn(se,!!t.asBot));return}let K=t.timeout??3600;console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${K}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);let re={channelId:r,ts:oe,question:h,reactable:S,overflow:I,threadOnly:J,seedMarker:U,lang:N,audience:k,broadcast:D,askerUserId:M?.userId??"",askerBotId:M?.botId??"",timeout:K,shown:se,asBot:!!t.asBot,json:!!t.json,explain:H,explainExit:!!t.explainExit};if(s)re.threadParentTs=s;if(o)re.cookie=o;await Ig(e,re)}function vg(e,t){if(console.error(`\u3053\u306E\u8CEA\u554F\u306F\u7121\u52B9\u3067\u3059 \u2014 \u56DE\u7B54\u3055\u308C\u308B\u3053\u3068\u306F\u3042\u308A\u307E\u305B\u3093\u3002\u5F85\u3064\u306E\u3092\u3084\u3081\u3066\u304F\u3060\u3055\u3044: ${P(t)}`),e.reason)console.error(` ${P(e.reason)}`);if(e.supersededBy)console.error(` \u65B0\u3057\u3044\u8CEA\u554F: ${P(e.supersededBy)}`)}async function jc(e,t,n){let s=dt(t),o,a,r;if(s?.ts)o=s.channel,a=s.ts,r=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let i=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!i)return null;o=i[1],a=i[2]}return Wo(e,{channelId:o,ts:a,threadTs:r},n)}async function Wo(e,t,n){let{channelId:s,ts:o}=t,a=t.threadTs&&t.threadTs!==t.ts?t.threadTs:void 0,r;if(a){let c=T(await Pe(e,s,a,100,n));r=Y(c.messages).map(T).find((l)=>l.ts===o)}else{let c=T(await rt(e,s,1,o,void 0,n,!0));r=Y(c.messages).map(T).find((l)=>l.ts===o)}let i={channelId:s,ts:o};if(a)i.threadTs=a;if(r)i.msg=r;return i}async function Pg(e,t,n,s,o){let a=P(t),r=await jc(e,t,o);if(!r)return console.error(`\u2717 ${a}: permalink (\u307E\u305F\u306F 'C\u2026:1700000000.000100') \u3067\u306F\u3042\u308A\u307E\u305B\u3093`),null;if(!r.msg)return console.error(`\u2717 ${a}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`),null;let i=r.msg;if(!(!!n?.userId&&i.user===n.userId||!!n?.botId&&i.bot_id===n.botId))return console.error(`\u2717 ${a}: \u81EA\u5206\uFF08${Bo(n,s)}\uFF09\u304C\u6295\u7A3F\u3057\u305F\u8CEA\u554F\u3067\u306F\u3042\u308A\u307E\u305B\u3093`+`${s?"":" \u2014 bot \u304C\u51FA\u3057\u305F\u8CEA\u554F\u306A\u3089 --as-bot \u3067"}`),null;let l=typeof i.text==="string"?i.text:"",u=$t(l);if(u.kind==="void")return"void";if(u.kind==="resolved")return console.error(`\u2717 ${a}: \u56DE\u7B54\u6E08\u307F\u306E\u8CEA\u554F\u3067\u3059\uFF08\u56DE\u7B54: ${P(u.answer.split(`
|
|
518
|
+
`)[0]??"")}\uFF09\u2014 \u5909\u66F4\u3067\u304D\u307E\u305B\u3093`),null;if(u.kind!=="open")return console.error(`\u2717 ${a}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093 \u2014 ${Ps(l)}`),null;let d={link:t,channelId:r.channelId,ts:r.ts,parsed:u,seedMarker:Ls(l)??st,msg:i};if(r.threadTs)d.threadTs=r.threadTs;return d}async function Tk(e,t,n,s){let o=(r)=>typeof r==="string"&&r!==n?.userId;if(Y(t.msg.reactions).map(T).some((r)=>Te.some((i)=>i.name===r.name)&&Y(r.users).some(o)))return!0;if(Number(t.msg.reply_count)>0){let r=T(await Pe(e,t.channelId,t.ts,100,s));if(Y(r.messages).map(T).some((i)=>Number(i.ts)>Number(t.ts)&&o(i.user)&&!i.bot_id))return!0}if(t.channelId.startsWith("D")){let r=T(await rt(e,t.channelId,30,t.ts,void 0,s,!0));if(Y(r.messages).map(T).some((i)=>Number(i.ts)>Number(t.ts)&&o(i.user)&&!i.bot_id))return!0}return!1}async function Ok(e,t){let n=await je(e,t.cookie),s=await Pg(e,t.link,n,t.asBot,t.cookie);if(s==="void")console.error(`\u2717 ${P(t.link)}: \u7121\u52B9\u5316\u6E08\u307F\u306E\u8CEA\u554F\u306F\u7DE8\u96C6\u3067\u304D\u307E\u305B\u3093`),process.exit(le);if(!s)process.exit(le);let o=s.parsed,a=async(A)=>{let _=tr(Ne(A)),S=await an(t.mentionToken,_.text,s.channelId,t.mentionCookie);return Tg(S.unresolved),S.text},r=t.question!==void 0?await a(t.question):o.question,i=t.body!==void 0?await a(t.body):o.body,c=[...o.reactable,...o.overflow],l=t.choices?t.choices.map(Ne):c,u=JSON.stringify(l.map(Le))!==JSON.stringify(c.map(Le));if(u&&await Tk(e,s,n,t.cookie))console.error(`\u2717 \u3053\u306E\u8CEA\u554F\u306B\u306F\u3082\u3046\u56DE\u7B54\uFF08\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u304B\u8FD4\u4FE1\uFF09\u304C\u3042\u308A\u307E\u3059 \u2014 \u9078\u629E\u80A2\u3092\u5909\u3048\u308B\u3068\u3001\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306E\u610F\u5473\u304C\u5909\u308F\u3063\u3066\u3057\u307E\u3044\u307E\u3059\u3002
|
|
416
519
|
`+` \u8CEA\u554F\u6587\u3068\u672C\u6587\u306F\u5909\u3048\u3089\u308C\u307E\u3059\u3002\u9078\u629E\u80A2\u3092\u5909\u3048\u308B\u306A\u3089\u7121\u52B9\u5316\u3057\u3066\u51FA\u3057\u76F4\u3057\u3066\u304F\u3060\u3055\u3044:
|
|
417
|
-
`+` slack ask --void='${
|
|
418
|
-
${
|
|
419
|
-
${
|
|
420
|
-
`).map((
|
|
421
|
-
`).map((
|
|
422
|
-
(${
|
|
423
|
-
`)[0]??"").replace(/^:question: /,""),f;if(c)try{let g=await
|
|
424
|
-
${
|
|
425
|
-
slack ask ${c.map((l)=>`--void='${l.link}'`).join(" ")} --reason 'stale'${
|
|
426
|
-
(${
|
|
427
|
-
`)[0]??"")}\uFF09`),
|
|
428
|
-
${
|
|
429
|
-
`)[0]??"").slice(0,100)}`+(
|
|
430
|
-
(already pressed: ${
|
|
431
|
-
\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.",...
|
|
432
|
-
`+` Got: ${
|
|
433
|
-
${
|
|
434
|
-
`+` (\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306F\u6B8B\u3063\u3066\u3044\u307E\u3059: slack read '${
|
|
435
|
-
`+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let l=
|
|
436
|
-
`)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...
|
|
437
|
-
`+` Got: ${
|
|
438
|
-
`+" \u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u66F8\u304D\u63DB\u3048\u3089\u308C\u308B\u306E\u306F\u6295\u7A3F\u8005\u3060\u3051\u3067\u3059 \u2014 bot \u304C\u6295\u7A3F\u3057\u305F\u6295\u7968\u306A\u3089 --as-bot \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002")}if(l.ambiguous.length){let
|
|
439
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function
|
|
440
|
-
`+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let l=
|
|
520
|
+
`+` slack ask --void='${P(t.link)}' --reask${t.asBot?" --as-bot":""} \u2026`),process.exit(le);if(!([...`${r}
|
|
521
|
+
${i}`.matchAll(/<@([UW][A-Z0-9]+)(?:\|[^>]*)?>/g)].some((A)=>A[1]!==n?.userId)||/<!(?:here|channel|everyone)/.test(`${r}
|
|
522
|
+
${i}`)||s.channelId.startsWith("D")))console.error("\u2717 \u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u8CEA\u554F\u306B\u306A\u308A\u307E\u3059 \u2014 \u56DE\u7B54\u3067\u304D\u308B\u4EBA\u3092 @ \u3067\u6B8B\u3057\u3066\u304F\u3060\u3055\u3044"),process.exit(le);let p=t.lang?Aa({flag:t.lang})?.lang??o.lang:o.lang,g=l.slice(0,It),h=l.slice(It),b=typeof s.msg.text==="string"?s.msg.text:"",m=Ra(r,i,g,h,o.threadOnly,p,o.explain),w=Xr(b);if(w.length)m=Vr(m,w,p);if(ze(m,t.allowUrlAdjacent),m===b){console.error("\u5909\u66F4\u306F\u3042\u308A\u307E\u305B\u3093\u3002");return}let D=ke("ask-edit",`${s.channelId}:${s.ts}`,m,n?.userId??"");if(t.code!==D){let A=(_,S,I)=>S===I?[` ${_}: (unchanged)`]:[` ${_}:`,...S.split(`
|
|
523
|
+
`).map((J)=>` - ${J}`),...I.split(`
|
|
524
|
+
`).map((J)=>` + ${J}`)];Se(t.code,D,["--- Editing question --------------------------",Ee(n,{asBot:t.asBot}),` ${P(t.link)}`,...A("Question",o.question,r),...A("Body",o.body,i),...u?[" Choices (nobody has answered yet \u2014 pills are re-seeded):",...c.map((_,S)=>` - ${S+1}. ${Le(_)}`),...l.map((_,S)=>` + ${S+1}. ${Le(_)}`)]:[" Choices: (unchanged)"],...p!==o.lang?[` Language: ${o.lang} \u2192 ${p} (the instructions are rewritten)`]:[],"----------------------------------------------"])}await Mt(e,s.channelId,s.ts,m,t.cookie,!0);let k=g.length?vt:st,E=Ls(b)??st;if(u){let A=(_)=>o.explain?[_,nn]:[_];for(let _ of[...o.reactable.map((S,I)=>Te[I].name),...A(E)])try{await Bt(e,s.channelId,s.ts,_,t.cookie)}catch{}await uo([...g.map((_,S)=>Te[S].name),...A(k)],(_)=>Nt(e,s.channelId,s.ts,_,t.cookie),(_,S)=>console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${_} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${S instanceof Error?S.message:String(S)})`))}else if(E!==k)try{await Nt(e,s.channelId,s.ts,k,t.cookie),await Bt(e,s.channelId,s.ts,E,t.cookie)}catch(A){console.error(` (marker \u3092 ${k} \u306B\u66FF\u3048\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${A instanceof Error?A.message:String(A)})`)}console.error(`\u2713 \u7DE8\u96C6\u3057\u307E\u3057\u305F: ${P(t.link)}`)}async function Rk(e,t){let n={kind:"ask",limit:t.limit};if(t.channel)n.channel=t.channel;let s=rc(n);if(!s)console.error(`Error: ${Us}
|
|
525
|
+
(${At()})`),process.exit(le);let o;if(t.stale){if(o=go(t.stale),o===void 0)console.error(`Error: --stale needs a duration like 24h / 3d (got ${P(t.stale)})`),process.exit(le)}let a=[];for(let i of s){if(o!==void 0&&i.sent_at>o)continue;let c=i.as_bot?e.bot:e.user,l=i.permalink||`${i.channel}:${i.ts}`,u="unknown",d=(i.text.split(`
|
|
526
|
+
`)[0]??"").replace(/^:question: /,""),f;if(c)try{let g=await Wo(c,{channelId:i.channel,ts:i.ts,threadTs:i.thread_ts??void 0},i.as_bot?void 0:e.cookie);if(!g.msg)u="gone";else{let h=$t(typeof g.msg.text==="string"?g.msg.text:"");if(u=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{u="unknown"}if(t.state!=="all"&&u!==t.state)continue;let p={state:u,age_h:Math.round((Date.now()-i.sent_at)/3600000),asBot:!!i.as_bot,channel:i.channel,target:i.target??i.channel,link:l,question:Le(d)};if(f!==void 0)p.answer=f;a.push(p)}if(t.json)console.log(JSON.stringify(a));else{for(let i of a)console.log(`${i.state.padEnd(8)} ${String(i.age_h).padStart(4)}h ${i.asBot?"bot ":"user"} ${P(i.target)} ${i.link}
|
|
527
|
+
${P(i.question).slice(0,100)}`);console.error(`${a.length} question(s)${t.state==="all"?"":` in state "${t.state}"`}${t.stale?`, older than ${t.stale}`:""}.`)}let r=a.filter((i)=>i.state==="open");if(t.stale&&r.length)for(let i of[!1,!0]){let c=r.filter((l)=>l.asBot===i);if(!c.length)continue;console.error(`\u7121\u52B9\u5316\u3059\u308B\u306A\u3089 (${c.length} \u4EF6, ${i?"bot":"user"}):
|
|
528
|
+
slack ask ${c.map((l)=>`--void='${l.link}'`).join(" ")} --reason 'stale'${i?" --as-bot":""}`)}}async function Ik(e,t){let n=Tp(t.sinceMs);if(!n)console.error(`Error: ${Us}
|
|
529
|
+
(${At()})`),process.exit(le);let s=t.channel?n.filter((u)=>u.channel===t.channel||u.target===t.channel):n,o=[],a={unanswered:0,ambiguous:0,resolved:0,void:0,explain:0},r=[],i=[],c=e.user?(await je(e.user,e.cookie))?.team??"":e.bot?(await je(e.bot))?.team??"":"",l=new Map;for(let u of s){if(u.team&&c&&u.team!==c){l.set(u.team,(l.get(u.team)??0)+1);continue}let d=u.permalink||`${u.channel}:${u.ts}`,f=!!u.as_bot,p=f?e.bot:e.user;if(!p){i.push(`${d}: ${f?"--as-bot \u3067\u805E\u3044\u305F\u8CEA\u554F\u3067\u3059\u304C bot token \u304C\u3042\u308A\u307E\u305B\u3093":"user token \u304C\u3042\u308A\u307E\u305B\u3093"}`);continue}let g=f?void 0:e.cookie,h=u.delivered_cursor??void 0;try{let b={channelId:u.channel,ts:u.ts,threadTs:u.thread_ts??void 0},m=await Wo(p,b,g);if(!m.msg){i.push(`${d}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093 (\u524A\u9664?)`);continue}let w=await Mg(p,{channelId:u.channel,ts:u.ts,msg:m.msg},g),D=w.parsed;if(D.kind==="resolved"){a.resolved++;continue}if(D.kind==="void"){a.void++;continue}if(D.kind==="other"){i.push(`${d}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u3081\u307E\u305B\u3093 \u2014 ${Ps(w.text)}`);continue}if(!w.audience.size&&!w.broadcast){i.push(`${d}: \u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u8CEA\u554F\u3067\u3059`);continue}let k=Ng(w,D,b,{timeout:0,link:d,asBot:f,json:!1,cookie:g,after:h}),E=Rg(p,k,!0),A=await E.poll(),_=E.state.unchosen;if(E.state.voided){a.void++;continue}let S=Nn(d,f,h);if(E.state.explainNow.length)a.explain++,r.push(`${d}: \u2139\uFE0F \u8AAC\u660E\u3092\u6C42\u3081\u3089\u308C\u3066\u3044\u307E\u3059 (${E.state.explainNow.map((J)=>`<@${J}>`).join(" ")}) \u2014 \u30B9\u30EC\u30C3\u30C9\u3067\u8AAC\u660E\u3057\u3066\u304F\u3060\u3055\u3044`);let I={row:u,link:d,question:D.question,collect:S,alive:Op(u)};if(A)o.push({...I,answer:A.answer,how:A.how,freeText:!1});else if(_&&!_.ambiguous&&_.text!==u.delivered_answer)o.push({...I,answer:_.text,how:"\u8FD4\u4FE1 (\u9078\u629E\u80A2\u5916)",freeText:!0});else if(_?.ambiguous)a.ambiguous++;else a.unanswered++}catch(b){i.push(`${d}: ${b instanceof Error?b.message:String(b)}`)}}if(t.json)for(let u of o){let d=u.row;console.log(JSON.stringify({id:d.id,link:u.link,channel:d.channel,ts:d.ts,asked_at:d.sent_at,question:u.question,answer:u.answer,how:u.how,free_text:u.freeText,sender:{session_id:d.session_id??null,cli:d.cli??null,agent_pid:d.agent_pid??null,pid:d.pid,alive:u.alive,cwd:d.cwd,git_branch:d.git_branch??null,host:d.host??null},delivered_at:d.delivered_at??null,collect:u.collect}))}else{let u=new Map;for(let d of o){let f=d.row.session_id?`session ${d.row.session_id}`:`pid ${d.row.agent_pid??d.row.pid}`;u.set(f,[...u.get(f)??[],d])}for(let[d,f]of u){let p=f[0].row;console.log(`${P(d)} ${P(p.cli??"?")} pid ${p.agent_pid??p.pid} ${f[0].alive?"(alive)":"(gone)"}${p.git_branch?` branch=${P(p.git_branch)}`:""} cwd=${P(p.cwd)}`);for(let g of f)console.log(` ${P(g.link)} (${Mn(g.row.sent_at/1000)})`),console.log(` Q: ${P(Le(g.question))}`),console.log(` A: ${P(Le(g.answer))} \u2014 ${P(g.how)}${g.freeText?" \u2014 \u6C7A\u5B9A\u3067\u306F\u3042\u308A\u307E\u305B\u3093":""}`),console.log(` collect: ${P(g.collect)}`)}}for(let u of i)console.error(` (${P(u)})`);for(let u of r)console.error(` (${P(u)})`);for(let[u,d]of l)console.error(` (${d} \u4EF6\u306F\u5225\u306E\u30EF\u30FC\u30AF\u30B9\u30DA\u30FC\u30B9\u300C${P(u)}\u300D\u306E\u8CEA\u554F\u3067\u3059 \u2014 slack -w <name> ask --pending \u3067\u78BA\u8A8D)`);console.error(`${o.length} \u4EF6\u304C\u56DE\u7B54\u6E08\u307F\u30FB\u672A\u56DE\u53CE, ${a.unanswered} \u4EF6\u304C\u672A\u56DE\u7B54`+(a.ambiguous?`, ${a.ambiguous} \u4EF6\u306F\u8FD4\u4FE1\u304C\u8907\u6570\u306E\u9078\u629E\u80A2\u306B\u4E00\u81F4 (\u672A\u78BA\u5B9A)`:"")+(a.resolved?`, ${a.resolved} \u4EF6\u306F \u2705 \u56DE\u53CE\u6E08\u307F`:"")+(a.void?`, ${a.void} \u4EF6\u306F\u7121\u52B9\u5316\u6E08\u307F`:"")+(a.explain?`, ${a.explain} \u4EF6\u306F \u2139\uFE0F \u8AAC\u660E\u306E\u30EA\u30AF\u30A8\u30B9\u30C8\u3042\u308A`:"")+` \u2014 ${s.length} \u4EF6\u306E\u672A\u56DE\u53CE\u306E\u8CEA\u554F\u3092\u78BA\u8A8D (log: ${At()})`)}async function Lg(e,t,n,s,o){let a=P(t.link);try{let r=kf(t.parsed.question,n,t.parsed.lang,t.parsed.body||void 0,s);await Mt(e,t.channelId,t.ts,r,o,!0)}catch(r){return console.error(`\u2717 ${a}: \u66F8\u304D\u63DB\u3048\u306B\u5931\u6557\u3057\u307E\u3057\u305F: ${r instanceof Error?r.message:String(r)}`),!1}for(let r of[...t.parsed.reactable.map((i,c)=>Te[c].name),t.seedMarker,...t.parsed.explain?[nn]:[]])try{await Bt(e,t.channelId,t.ts,r,o)}catch{}try{await Nt(e,t.channelId,t.ts,Oa,o)}catch(r){console.error(` (${a}: \uD83D\uDEAB \u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${r instanceof Error?r.message:String(r)})`)}return console.error(`\u2713 \u7121\u52B9\u5316: ${a}`),!0}async function vk(e,t){let n=await je(e,t.cookie);if(t.supersededBy){let i=P(t.supersededBy),c=!1;try{let l=await jc(e,t.supersededBy,t.cookie);if(c=!!l?.msg,!l)console.error(`Error: --superseded-by must be a message permalink (or 'C\u2026:1700000000.000100'): ${i}`),process.exit(le)}catch(l){console.error(`Error: --superseded-by \u3092\u78BA\u8A8D\u3067\u304D\u307E\u305B\u3093: ${i} (${l instanceof Error?l.message:String(l)})`),process.exit(le)}if(!c)console.error(`Error: --superseded-by \u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${i}`),process.exit(le)}let s=[],o=0;for(let i of t.links){let c=P(i),l=await jc(e,i,t.cookie);if(!l){console.error(`\u2717 ${c}: permalink (\u307E\u305F\u306F 'C\u2026:1700000000.000100') \u3067\u306F\u3042\u308A\u307E\u305B\u3093`),o++;continue}if(!l.msg){console.error(`\u2717 ${c}: \u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`),o++;continue}let u=l.msg;if(!(!!n?.userId&&u.user===n.userId||!!n?.botId&&u.bot_id===n.botId)){console.error(`\u2717 ${c}: \u81EA\u5206\uFF08${Bo(n,t.asBot)}\uFF09\u304C\u6295\u7A3F\u3057\u305F\u8CEA\u554F\u3067\u306F\u306A\u3044\u306E\u3067\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093`+`${t.asBot?"":" \u2014 bot \u304C\u51FA\u3057\u305F\u8CEA\u554F\u306A\u3089 --as-bot \u3067"}`),o++;continue}let f=typeof u.text==="string"?u.text:"",p=$t(f),g=!1;if(p.kind==="void"){console.error(`- ${c}: \u3059\u3067\u306B\u7121\u52B9\u5316\u6E08\u307F\u3067\u3059\uFF08\u4F55\u3082\u3057\u307E\u305B\u3093\uFF09`);continue}if(p.kind==="resolved"){console.error(`\u2717 ${c}: \u56DE\u7B54\u6E08\u307F\u306E\u8CEA\u554F\u306F\u7121\u52B9\u5316\u3067\u304D\u307E\u305B\u3093\uFF08\u56DE\u7B54: ${P(p.answer.split(`
|
|
530
|
+
`)[0]??"")}\uFF09`),o++;continue}if(p.kind!=="open"){let m=xf(f);if(!m){console.error(`\u2717 ${c}: \`slack ask\` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093 \u2014 ${Ps(f)}`),o++;continue}let w=Y(u.reactions).map(T).filter((D)=>Y(D.users).includes(n?.userId??"\x00")).map((D)=>Te.findIndex((k)=>k.name===D.name)).filter((D)=>D>=0);p={kind:"open",question:m.question,body:m.body,reactable:Array.from({length:w.length?Math.max(...w)+1:0},()=>""),overflow:[],threadOnly:!0,lang:Fa(f)??"ja",explain:Y(u.reactions).map(T).some((D)=>D.name===nn&&Y(D.users).includes(n?.userId??"\x00"))},g=!0}let h=g?Y(u.reactions).map(T).some((m)=>m.name===vt&&Y(m.users).includes(n?.userId??"\x00"))?vt:st:Ls(f)??st,b=Y(u.reactions).map(T).filter((m)=>typeof m.name==="string"&&Te.some((w)=>w.name===m.name)).filter((m)=>Y(m.users).some((w)=>w!==n?.userId)).map((m)=>`:${String(m.name)}:`);s.push({link:i,channelId:l.channelId,ts:l.ts,text:f,parsed:p,seedMarker:h,pressed:b,...g?{unreadable:g}:{}})}if(!s.length)console.error(o?"\u7121\u52B9\u5316\u3067\u304D\u308B\u8CEA\u554F\u304C\u3042\u308A\u307E\u305B\u3093\u3002":"\u4F55\u3082\u3059\u308B\u3053\u3068\u304C\u3042\u308A\u307E\u305B\u3093\u3002"),process.exit(o?le:0);let a=ke("ask-void",...s.map((i)=>`${i.channelId}:${i.ts}`),t.reason,t.supersededBy??"",n?.userId??"");if(t.code!==a)Se(t.code,a,["--- \u7121\u52B9\u5316 (void) -------------------------------",Ee(n,{asBot:t.asBot}),` Reason: ${t.reason?P(t.reason):"(none)"}`,...t.supersededBy?[` Replaced: ${P(t.supersededBy)}`]:[],` ${s.length} question(s):`,...s.map((i)=>` \u2022 ${P(i.link)}
|
|
531
|
+
${P(i.parsed.question.split(`
|
|
532
|
+
`)[0]??"").slice(0,100)}`+(i.pressed.length?`
|
|
533
|
+
(already pressed: ${i.pressed.join(" ")} \u2014 left in place, never collected)`:"")+(i.unreadable?`
|
|
534
|
+
\u26A0 its layout no longer reads as an ask (edited by hand?) \u2014 voided from a best-effort read: question and the rest of the text kept as they are`:""))," Each becomes \uD83D\uDEAB (body kept, options and instructions removed); our pills and marker (\u2795, or \u2753) come off; a \uD83D\uDEAB reaction is added.",...o?[` (${o} link(s) above were refused and will be skipped)`]:[],"----------------------------------------------"]);let r=0;for(let i of s)if(!await Lg(e,i,t.reason,t.supersededBy,t.cookie))r++;process.exit(r||o?le:0)}async function Pk(e,t){let n=dt(t.link),s,o,a;if(n?.ts)s=n.channel,o=n.ts,a=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').
|
|
535
|
+
`+` Got: ${P(t.link)}`),process.exit(le);s=h[1],o=h[2]}let r=await Wo(e,{channelId:s,ts:o,threadTs:a},t.cookie);if(!r.msg)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${P(t.link)}`),process.exit(le);let i=r.msg,c=await Mg(e,{channelId:s,ts:o,msg:i},t.cookie),{text:l,parsed:u,audience:d,broadcast:f,askerUserId:p,askerBotId:g}=c;if(u.kind==="other")console.error("Error: \u3053\u308C\u306F `slack ask` \u306E\u8CEA\u554F\u3068\u3057\u3066\u8AAD\u307F\u53D6\u308C\u307E\u305B\u3093\u3002\n"+` \u7406\u7531: ${Ps(l)}
|
|
536
|
+
${P(t.link)}
|
|
537
|
+
`+` (\u62BC\u3055\u308C\u305F\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3\u306F\u6B8B\u3063\u3066\u3044\u307E\u3059: slack read '${P(t.link)}' \u3067\u78BA\u8A8D\u3067\u304D\u307E\u3059)`),process.exit(le);if(u.kind==="void"){if(vg(u,t.link),t.json)await cn(e,{json:!0,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"void",answer:null,reason:u.reason,...u.supersededBy?{supersededBy:u.supersededBy}:{},notes:[],cursor:Jt(o,t.after)});process.exit(Ag)}if(u.kind==="resolved"){console.error(`\u2713 \u56DE\u7B54\u6E08\u307F: ${P(u.question)}`);let h=typeof T(i.edited).ts==="string"?String(T(i.edited).ts):void 0,b=_f(l),m=!1,w=(A)=>{if(m||!b.byReply)return!1;if(h&&Number(A.ts)>Number(h))return!1;let _=typeof A.text==="string"?A.text.trim():"",S=_===u.answer||b.n!==void 0&&(new RegExp(`^[(\uFF08]?${b.n}(?![0-9])`).test(_)||Ef(_,u.answer,b.n));if(S)m=!0;return S},D=t.after,k=[];if(d.size||f){let A=(_)=>typeof _==="string"&&!!_&&_!==p&&(f||d.has(_));k=await Og(e,{channelId:s,ts:o,threadOnly:!!a||!s.startsWith("D"),replyCount:Number(i.reply_count)||0,isAnswerer:A,askerUserId:p,askerBotId:g,...a?{threadParentTs:a}:{},...t.cookie?{cookie:t.cookie}:{}},D,w)}let E=Jt(o,D,...k.map((A)=>A.ts));await cn(e,{json:t.json,shown:t.link,asBot:t.asBot,cookie:t.cookie},{status:"answered",answer:u.answer,notes:k,cursor:E}),oc(s,o,u.answer,E);return}if(!d.size&&!f)console.error(`Error: \u3053\u306E\u8CEA\u554F\u306F\u8AB0\u306B\u3082\u5B9B\u3066\u3089\u308C\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u6709\u52B9\u306A\u56DE\u7B54\u8005\u3092\u5224\u5B9A\u3067\u304D\u307E\u305B\u3093: ${P(t.link)}`),process.exit(le);if(t.timeout>0)console.error(` \u56DE\u7B54\u3092\u5F85\u3063\u3066\u3044\u307E\u3059 (\u6700\u5927 ${t.timeout}s)\u2026 Ctrl-C \u3067\u4E2D\u65AD`);await Ig(e,Ng(c,u,{channelId:s,ts:o,threadTs:a},t))}async function Mg(e,t,n){let{msg:s}=t,o=typeof s.text==="string"?s.text:"",a=$t(o),r=typeof s.user==="string"?s.user:"",i=typeof s.bot_id==="string"?s.bot_id:"",c=/<!(here|channel|everyone)(\^[^>]*)?(\|[^>]*)?>/.test(o),l=new Set;for(let u of o.matchAll(/<@([UW][A-Z0-9]+)>/g))if(u[1]!==r)l.add(u[1]);if(a.kind!=="other"&&!l.size&&!c){let u=await jo(e,t.channelId,n);if(u&&u!==r)l.add(u)}return{text:o,parsed:a,audience:l,broadcast:c,askerUserId:r,askerBotId:i}}function Ng(e,t,n,s){let o={channelId:n.channelId,ts:n.ts,question:t.question,reactable:t.reactable,overflow:t.overflow,threadOnly:t.threadOnly,seedMarker:Ls(e.text)??st,lang:t.lang,audience:e.audience,broadcast:e.broadcast,askerUserId:e.askerUserId,askerBotId:e.askerBotId,timeout:s.timeout,shown:s.link,asBot:s.asBot,json:s.json,explain:t.explain,explainExit:!!s.explainExit};if(n.threadTs)o.threadParentTs=n.threadTs;if(s.cookie)o.cookie=s.cookie;if(s.after)o.after=s.after;return o}var pt=3;function Lk(e){return`slack poll --results='${e}'`}async function Mk(e,t){let{ref:n,threadTs:s}=xt(t.target,!1),o=t.cookie,a=Kt(e,o),r;if(t.channelId)r=t.channelId;else if(t.userId)r=await jt(e,t.userId,o);else r=await be(e,n,o);let i=(await a())?.userId??"",c=await jo(e,r,o);if(!t.asBot&&!!i&&c===i)console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own message.
|
|
538
|
+
`+` To reach yourself with a notification, post as the bot: slack poll '${t.target}' '...' --as-bot`);let l=tr(Ne(t.question)),u=tr(Ne(t.body??"")),d=t.mentionToken??e,f=await an(d,l.text,r,t.mentionCookie),p=u.text?await an(d,u.text,r,t.mentionCookie):{text:"",resolved:[],unresolved:[]},g=f.text,h=p.text;for(let N of xo([...f.unresolved,...p.unresolved]))console.error(`\u26A0 ${P(N)}`);let b=t.choices.map(Ne),m=!!t.multi,w=t.until??"",D=fp(g,h,b,{multi:m,deadline:w});ze(D,t.allowUrlAdjacent);let k="",E="?";try{let N=await rt(e,r,1,void 0,void 0,o),H=Y(N.messages).map(T).filter((O)=>O.subtype===void 0||O.subtype===null)[0];k=typeof H?.text==="string"?H.text:"",E=typeof H?.user==="string"?await Re(e,H.user,o):typeof H?.username==="string"?H.username:"?"}catch{}let A=await a(),_=await No(e,r,o),S=ke(r,s??"",k,D,A?.userId??"");if(t.code!==S){let N=await un(e,r,n,o);Se(t.code,S,["--- Last message in channel ------------------",` ${E}: ${cs(k.split(`
|
|
539
|
+
`)[0]??"").slice(0,100)}`,"--- Ballot (seeded as reactions) -------------",...b.map((H,O)=>` ${wt[O].glyph} ${js(H)}`),"--- Posting ----------------------------------",Ee(A,{asBot:t.asBot}),` \u2192 ${N}${s?" \u2014 THREAD REPLY":" \u2014 NEW top-level message"}`,` Question: ${g}`,` Rule: ${m?"1 \u4EBA \u4F55\u7968\u3067\u3082 (--multi)":"1 \u4EBA 1 \u7968"}${w?` \u2014 \u7DE0\u5207 ${w}`:""}`," Note: \u3042\u306A\u305F\u81EA\u8EAB\u306E\u7968\u306F\u6570\u3048\u307E\u305B\u3093 (\u30D4\u30EB\u306F\u3042\u306A\u305F\u304C\u4ED8\u3051\u305F\u7A2E\u306A\u306E\u3067\u533A\u5225\u3067\u304D\u307E\u305B\u3093)","--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"],_)}let I=Bn("poll"),J=await Lt(e,r,D,s,!1,o,!0,I.metadata);await uo([Ws,...b.map((N,H)=>wt[H].name)],(N)=>Nt(e,r,J,N,o),(N,H)=>{let O=H instanceof Error?H.message:String(H);if(N===Ws)console.error(` (marker ${N} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${O})`);else console.error(` (\u30EA\u30A2\u30AF\u30B7\u30E7\u30F3 ${N} \u3092\u4ED8\u3051\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${O})`)});let L="";try{L=await In(e,r,J,o)}catch{}let v=L||`${r}:${J}`;console.error(`\u2713 Posted: ${v}`),I.record({team:A?.team,channel:r,target:t.target,ts:J,threadTs:s,permalink:L,text:D,asBot:t.asBot}),console.log(Lk(v)),console.error(` \u7DE0\u3081\u5207\u308B: slack poll --close='${v}'${t.asBot?" --as-bot":""}`)}async function Nk(e,t,n){let s=dt(t),o,a,r;if(s?.ts)o=s.channel,a=s.ts,r=s.threadTs&&s.threadTs!==s.ts?s.threadTs:void 0;else{let c=t.match(/^([A-Za-z0-9]+):(\d{10}\.\d{6})$/);if(!c)console.error(`Error: --results/--close needs the permalink of a poll (or 'C\u2026:1700000000.000100').
|
|
540
|
+
`+` Got: ${P(t)}`),process.exit(pt);o=c[1],a=c[2]}let i;if(r){let c=T(await Pe(e,o,r,100,n));i=Y(c.messages).map(T).find((l)=>l.ts===a)}else{let c=T(await rt(e,o,1,a,void 0,n,!0));i=Y(c.messages).map(T).find((l)=>l.ts===a)}if(!i)console.error(`Error: \u305D\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: ${P(t)}`),process.exit(pt);return{channelId:o,ts:a,msg:i}}function fg(e){let t=Math.max(1,...e.map((n)=>n.count));return e.map((n,s)=>`${wt[s].glyph} ${String(n.count).padStart(3)} ${"\u2588".repeat(Math.round(n.count/t*20))}${n.count?" ":""}${n.choice}`)}async function Bk(e,t){let{channelId:n,ts:s,msg:o}=await Nk(e,t.link,t.cookie),a=typeof o.text==="string"?o.text:"",r=Js(a);if(r.kind==="other")console.error("Error: \u3053\u308C\u306F `slack poll` \u306E\u6295\u7968\u3067\u306F\u3042\u308A\u307E\u305B\u3093 (\u7968\u306E\u6570\u3048\u65B9\u304C\u5206\u304B\u308A\u307E\u305B\u3093)\u3002\n"+` ${P(t.link)}`),process.exit(pt);if(r.kind==="closed"){console.error(`\u2713 \u6295\u7968\u7D42\u4E86: ${P(r.question)}`);for(let p of fg(r.tallies))console.log(p);return}let i=new Set;if(typeof o.user==="string"&&o.user)i.add(o.user);let c=await eh(e,n,s,t.cookie),l=hp(r.choices,c,i,r.multi);console.error(`${P(r.question)}${r.deadline?` (\u7DE0\u5207 ${r.deadline})`:""}`);for(let p of fg(l.tallies))console.log(p);let u=l.tallies.reduce((p,g)=>p+g.count,0);if(console.error(` \u8A08 ${u} \u7968${r.multi?" (\u8907\u6570\u9078\u629E\u53EF)":""}`),t.names)for(let p=0;p<l.voters.length;p++){if(!l.voters[p].length)continue;let g=await Promise.all(l.voters[p].map((h)=>Re(e,h,t.cookie)));console.error(` ${wt[p].glyph} ${g.map((h)=>`@${P(h)}`).join(", ")}`)}let d=r.multi?[]:l.ambiguous,f=Vr(a,d);if(f!==a&&!t.noNotify)try{await Mt(t.writeToken??e,n,s,f,t.writeToken?t.writeCookie:t.cookie,!0)}catch(p){console.error(` (\u6295\u7968\u6587\u306B\u6CE8\u610F\u66F8\u304D\u3092\u5165\u308C\u3089\u308C\u307E\u305B\u3093\u3067\u3057\u305F: ${p instanceof Error?p.message:String(p)})
|
|
541
|
+
`+" \u30E1\u30C3\u30BB\u30FC\u30B8\u3092\u66F8\u304D\u63DB\u3048\u3089\u308C\u308B\u306E\u306F\u6295\u7A3F\u8005\u3060\u3051\u3067\u3059 \u2014 bot \u304C\u6295\u7A3F\u3057\u305F\u6295\u7968\u306A\u3089 --as-bot \u3092\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044\u3002")}if(l.ambiguous.length){let p=await Promise.all(l.ambiguous.map((g)=>Re(e,g,t.cookie)));console.error(`\u26A0 1 \u4EBA 1 \u7968\u306A\u306E\u306B\u8907\u6570\u62BC\u3057\u3066\u3044\u308B\u4EBA\u304C\u3044\u307E\u3059 (\u7121\u52B9\u7968): ${p.map((g)=>`@${P(g)}`).join(", ")}`)}if(!t.close)return;await Mt(t.writeToken??e,n,s,pp(r.question,l.tallies),t.writeToken?t.writeCookie:t.cookie,!0);try{await Nt(t.writeToken??e,n,s,Za,t.writeToken?t.writeCookie:t.cookie),await Bt(t.writeToken??e,n,s,Ws,t.writeToken?t.writeCookie:t.cookie)}catch{}console.error(`\u2713 \u6295\u7968\u3092\u7DE0\u3081\u5207\u308A\u307E\u3057\u305F: ${P(t.link)}`)}async function jk(e){let t=await Rr(e);for(let n of Ir(t,!1))console.log(n);if(!t.ok)process.exit(1)}function Ao(){let e=Ue();if(!e)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
542
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);return e}async function pg(e,t,n,s){let o=await Wt(n,e,s);return jt(t,o)}function hg(e){try{return Bg(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 Bg(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 jg(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 Wk(e,t){ze(t.message,t.allowUrlAdjacent);let n=Kt(e,t.cookie),{ref:s,threadTs:o}=xt(t.target),a;if(t.channelId)a=t.channelId;else if(t.userId)a=await jt(e,t.userId,t.cookie);else a=await be(e,s,t.cookie);let r=Bg(t.at),i=new Date(r*1000).toISOString(),c=await n();if(!t.asBot&&await Hc(e,a,c?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you when this fires.
|
|
543
|
+
`+` To be notified, schedule it as the bot: slack schedule send '${t.target}' '...' --at '${t.at}' --as-bot`);let l=ke(a,t.message,String(r),c?.userId??""),u=t.targetOverride?` [${t.targetOverride} \u2192 ${a}]`:"";if(t.code!==l){let f=await No(e,a,t.cookie);Se(t.code,l,["--- Scheduling message -----------------------",Ee(c,{asBot:t.asBot,pad:9}),` To: ${s}${o?` (thread ${o})`:""}${u}`,` At: ${jg(r)}`,` Message: ${t.message}`,"---------------------------------------------"],f,new Date(r*1000))}let d=await Gp(e,a,t.message,r,o,t.cookie);if(console.log(`\u2713 Scheduled (id: ${d}, at: ${i})`),t.asBot){if(console.error(` Scheduled as the bot \u2014 the user token cannot see or cancel it. Use the same flag:
|
|
441
544
|
`+` slack schedule ls --as-bot
|
|
442
|
-
slack schedule rm '${t.target}' ${d} --as-bot`),
|
|
443
|
-
`)[0]?.slice(0,80)??""}`)}}async function
|
|
444
|
-
`+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let
|
|
445
|
-
`+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function
|
|
446
|
-
`+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function
|
|
447
|
-
`+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let
|
|
448
|
-
|
|
545
|
+
slack schedule rm '${t.target}' ${d} --as-bot`),a.startsWith("D"))try{let f=await Rr(e);if(!f.ok)for(let p of Ir(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 gg(e,t,n,s){let o;if(n)o=n;else if(t)o=await be(e,t,s);let r=(await Xp(e,o,s)).scheduled_messages??[];if(r.length===0){console.log("(no scheduled messages)");return}for(let i of r){let c=new Date(i.post_at*1000).toISOString();console.log(`${i.id} ${c} [${i.channel_id}] ${i.text.split(`
|
|
546
|
+
`)[0]?.slice(0,80)??""}`)}}async function mg(e,t){let n;if(t.channelId)n=t.channelId;else n=await be(e,t.target,t.cookie);let s=await je(e,t.cookie),o=ke(n,t.id,s?.userId??"");if(t.code!==o)Se(t.code,o,["--- Deleting scheduled message ---------------",Ee(s,{asBot:t.asBot,pad:9}),` Channel: ${t.target}${t.targetOverride?` [${t.targetOverride} \u2192 ${n}]`:""}`,` ID: ${t.id}`,"---------------------------------------------"]);await Vp(e,n,t.id,t.cookie),console.log(`\u2713 Deleted scheduled message ${t.id}`)}async function Jk(e,t){if(t.comment!==void 0)ze(t.comment,t.allowUrlAdjacent);let n=Kt(e,t.cookie),{statSync:s,existsSync:o}=await import("fs"),{basename:a}=await import("path");for(let g of t.filePaths)if(!o(g))console.error(`Error: file not found: ${g}`),process.exit(1);let{ref:r,threadTs:i}=xt(t.target),c;if(t.channelId)c=t.channelId;else if(t.userId)c=await jt(e,t.userId,t.cookie);else c=await be(e,r,t.cookie);if(await Hc(e,c,(await n())?.userId,t.cookie))console.error(`Warning: "${t.target}" is a DM to yourself \u2014 Slack will NOT notify you of your own upload.`);let l=t.filePaths.length>1,u=t.filePaths.map((g)=>{let h=a(g),b=l?h:t.title??h;return{fp:g,filename:h,title:b,sizeFmt:Lo(s(g).size)}}),d=await n(),f=ke(c,...u.flatMap((g)=>[g.fp,g.title]),d?.userId??"");if(t.code!==f){let g=` To: ${r}${i?` (thread ${i})`:""}`,h=l?[`--- Uploading ${u.length} files ------------------------`,Ee(d,{pad:7}),g,...u.map((b)=>` ${b.filename} (${b.sizeFmt})`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]:["--- Uploading file ---------------------------",Ee(d,{pad:7}),g,` File: ${u[0].fp}`,` Title: ${u[0].title}`,` Size: ${u[0].sizeFmt}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"];Se(t.code,f,h)}let p=u.length;for(let g=0;g<p;g++){let h=u[g],b={title:h.title};if(i!==void 0)b.threadTs=i;if(t.comment!==void 0&&g===0)b.initialComment=t.comment;let{fileId:m,permalink:w}=await yh(e,c,h.fp,b,t.cookie),D=p>1?`[${g+1}/${p}] `:"";console.log(`${D}\u2713 Uploaded (file_id: ${m}${w?`, url: ${w}`:""})`)}}async function Uk(e,t,n){let s=n.channel?await be(e,n.channel,t):void 0,o=[],a=1,r=1;do{let c={page:a,count:200};if(n.types)c.types=n.types;if(s)c.channel=s;if(n.user)c.user=n.user;let l=T(await jp(e,c,t));for(let u of Y(l.files))o.push(T(u));r=Number(T(l.paging).pages??1),a++}while(o.length<n.limit&&a<=r);let i=o.slice(0,n.limit);if(n.format==="jsonl"){for(let c of i)console.log(JSON.stringify({id:c.id??null,name:c.name??c.title??null,filetype:c.filetype??null,size:c.size??null,user:c.user??null,created:c.created??null,permalink:c.permalink??null}));return}for(let c of i){let l=String(c.id??""),u=typeof c.name==="string"?c.name:typeof c.title==="string"?c.title:l,d=typeof c.filetype==="string"?c.filetype:"?",f=typeof c.size==="number"?Lo(c.size):"";console.log(`${l} ${d.padEnd(7)} ${f.padStart(9)} ${u}`)}}function Jo(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 Kk(e){if(typeof e.text==="string"&&e.text)return e.text;let t=e.value;if(typeof t==="string"||typeof t==="number"||typeof t==="boolean")return String(t);if(Array.isArray(t))return t.map((n)=>typeof n==="string"?n:String(T(n).text??T(n).name??T(n).value??"")).filter(Boolean).join(", ");for(let n of["rich_text","select","user","date","number","checkbox","email","phone"]){let s=e[n];if(s!=null)return typeof s==="object"?JSON.stringify(s):String(s)}return""}async function qk(e,t,n,s){let o=Jo(n);if(!o)throw Error(`Not a list ID or list URL: ${n}
|
|
547
|
+
`+"Expected F\u2026 or https://<ws>.slack.com/lists/<TEAM>/<F-id>");let a=[],r;do{let c={limit:200};if(r)c.cursor=r;let l=s.asBot?await dc(nr(),o,c):T(await qp(e,o,c,t));for(let d of Y(l.items??l.records))a.push(T(d));let u=T(l.response_metadata).next_cursor;r=typeof u==="string"&&u?u:void 0}while(r&&a.length<s.limit);let i=a.slice(0,s.limit);if(s.format==="jsonl"){for(let c of i)console.log(JSON.stringify(c));return}for(let c of i){let l=String(c.id??""),u=Y(c.fields).map(T).map((d)=>{let f=String(d.key??d.column_id??"?"),p=Kk(d);return p?`${f}=${p}`:""}).filter(Boolean);console.log(`${l} ${u.join(" | ")}`)}}function nr(){let e=Ue();if(!e)console.error(`Error: Slack List writes go through the public slackLists.* API, which needs a bot token (xoxb-) \u2014 none was found.
|
|
548
|
+
`+" Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell)."),process.exit(1);return e}async function Uo(e){let t=[];try{t=(await Pt(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).
|
|
549
|
+
`+" Add it under OAuth & Permissions \u2192 Bot Token Scopes in the Slack app config, then reinstall the app."),process.exit(1)}async function Hk(e,t){try{let n=await lc(e);if(n.url&&n.teamId)return`${n.url.replace(/\/$/,"")}/lists/${n.teamId}/${t}`}catch{}return t}async function Wg(e,t){let n=await dc(e,t,{limit:1,includeList:!0}),s=Dp(T(n.list));if(!s.length)throw Error(`could not read the column schema of list ${t}`);return s}function Ko(e){console.error(he(e)),process.exit(1)}async function zk(e){let t=e.cols.map(bp),n=wp(t),s=nr();await Uo(s);let o=await je(s),a=ke("lists-create",e.name,JSON.stringify(n),String(e.todo),o?.userId??"");if(e.code!==a)Se(e.code,a,["--- Creating Slack List ----------------------",Ee(o,{asBot:!0,pad:9}),` name: ${e.name}`,...t.map((c,l)=>` column: ${c.name} (${c.type}${c.choices?`: ${c.choices.join("/")}`:""})${l===0?" [primary]":""}`),` todo: ${e.todo?"on (adds Completed / Assignee / Due date)":"off"}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let r;try{r=await Wp(s,e.name,n,e.todo)}catch(c){Ko(c)}let i=String(r.list_id??T(r.list).id??"");console.log(`\u2713 Created list ${e.name} (${i})`),console.log(await Hk(s,i))}async function Yk(e){let t=Jo(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=nr();await Uo(n);let s=await Wg(n,t),a=[{col:s.find((u)=>u.type==="text")??s[0],value:e.text},...tc(e.sets).map((u)=>({col:Qa(s,u.col),value:u.value}))],r=a.map((u)=>({column_id:u.col.id,...ec(u.col,u.value)})),i=await je(n),c=ke("lists-add",t,JSON.stringify(r),i?.userId??"");if(e.code!==c)Se(e.code,c,["--- Adding a row to Slack List ---------------",Ee(i,{asBot:!0,pad:9}),` list: ${t}`,...a.map((u)=>` ${(u.col.name||u.col.key).padEnd(8)} ${u.value}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let l;try{l=await Jp(n,t,r)}catch(u){Ko(u)}console.log(`\u2713 Added row ${String(T(l.item).id??"")} ${e.text}`)}async function Gk(e){let t=Jo(e.list);if(!t)throw Error(`Not a list ID or list URL: ${e.list}`);let n=nr();await Uo(n);let s=await Wg(n,t),o=tc(e.sets).map((c)=>({col:Qa(s,c.col),value:c.value}));if(e.done!==void 0){let c=kp(s);if(!c)throw Error(`list ${t} has no Completed column \u2014 it was not created with todo mode`);o.push({col:{...c,type:"checkbox"},value:String(e.done)})}if(!o.length)throw Error("nothing to set \u2014 pass --set name=value and/or --done / --no-done");let a=o.map((c)=>({row_id:e.row,column_id:c.col.id,...ec(c.col,c.value)})),r=await je(n),i=ke("lists-set",t,e.row,JSON.stringify(a),r?.userId??"");if(e.code!==i)Se(e.code,i,["--- Updating Slack List row -----------------",Ee(r,{asBot:!0,pad:9}),` list: ${t}`,` row: ${e.row}`,...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"]);try{await Kp(n,t,a)}catch(c){Ko(c)}console.log(`\u2713 Updated row ${e.row}`)}async function Xk(e){let t=Jo(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=nr();await Uo(n);let s=e.users.length?e.users:e.channels,o=await je(n),a=ke("lists-share",t,e.level,s.join(","),o?.userId??"");if(e.code!==a)Se(e.code,a,["--- Sharing Slack List ----------------------",Ee(o,{asBot:!0,pad:9}),` list: ${t}`,` ${e.users.length?"users: ":"channels:"} ${s.join(", ")}`,` access: ${e.level}${e.level==="owner"?" \u26A0 transfers ownership":""}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);try{await Up(n,t,e.level,e.users.length?{userIds:e.users}:{channelIds:e.channels})}catch(r){Ko(r)}console.log(`\u2713 Granted ${e.level} on ${t} to ${s.join(", ")}`)}function Vk(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 Zk(e,t,n,s){let o=Vk(n);if(!o)throw Error(`Not a file ID or file permalink: ${n}
|
|
550
|
+
`+"Expected F\u2026 or https://<ws>.slack.com/files/<UID>/<FID>/<name>");let a=T(await Bp(e,o,t)),r=T(a.file),i=typeof r.name==="string"?r.name:typeof r.title==="string"?r.title:o,c=typeof r.url_private_download==="string"?r.url_private_download:typeof r.url_private==="string"?r.url_private:"";if(!c)throw Error(`files.info returned no download URL for ${o}`);let l={Authorization:`Bearer ${e}`};if(t)l.Cookie=`d=${t}`;let u=await fetch(c,{headers:l});if(!u.ok)throw Error(`Download failed: HTTP ${u.status} ${u.statusText}`);let d=Buffer.from(await u.arrayBuffer()),{statSync:f,existsSync:p}=await import("fs"),{basename:g}=await import("path"),h=s??i;if(s&&p(s)&&f(s).isDirectory())h=Ft(s,g(i));wg(h,d),console.log(`\u2713 Downloaded ${i} (${Lo(d.length)}) \u2192 ${h}`)}async function Qk(){zh(),L0();let e=(r)=>ks(r.workspace),t=(r)=>Ai(r.workspace),n=async(r)=>{let i=Xe(),c=Ns(i);if(On(i))try{let d=await ds(e(r),r.target,t(r));if(!sn(i).some((f)=>f.channel===d.channel&&(f.thread_ts===void 0||f.thread_ts===d.root)))console.error(`Error: that message is not in one of ${i.dir}'s subscriptions (restrict_to_subscriptions)`),process.exit(2)}catch(d){console.error(he(d)),process.exit(1)}let l={target:r.target,newText:r.newText??"",allowUrlAdjacent:r["allow-url-adjacent"]===!0};if(r.tick)l.tick=r.tick;if(c.prefix)l.lanePrefix=c.prefix;if(r.force)l.force=!0;if(r.code)l.code=r.code;if(r["channel-id"])l.channelId=r["channel-id"];if(r.mentions!==!1)l.mentions=!0;let u;if(r["as-bot"]){let d=await ag(l.target,e(r),t(r),l.channelId);if(u=d.botToken,d.channelId&&!l.channelId)l.channelId=d.channelId;l.asBot=!0,l.mentionToken=e(r);let f=t(r);if(f)l.mentionCookie=f}else{u=e(r);let d=t(r);if(d)l.cookie=d}await ck(u,l)},s=async(r)=>{if(!String(r.message??"").trim())console.error("Error: message is empty"),process.exit(1);let i={target:r.target,message:r.message,allowUrlAdjacent:r["allow-url-adjacent"]===!0};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"];if(r["user-id"])i.userId=r["user-id"];if(r.broadcast)i.broadcast=!0;if(r.mentions!==!1){i.mentions=!0,i.mentionToken=e(r);let l=t(r);if(l)i.mentionCookie=l}let c;if(r["as-bot"]){let l=Ue();if(!l)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
551
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!i.channelId&&!i.userId&&i.target.startsWith("@"))try{i.userId=await Wt(e(r),i.target,t(r))}catch(u){console.error(`Error: could not resolve ${i.target} to a user for the bot DM.
|
|
552
|
+
${u instanceof Error?u.message:String(u)}
|
|
553
|
+
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}c=l,i.asBot=!0}else{c=e(r);let l=t(r);if(l)i.cookie=l}try{await Dk(c,i)}catch(l){console.error(he(l)),process.exit(1)}},o={state:{type:"string",choices:["open","untriaged","pending","doing","done","dropped","stuck"],default:"open",describe:"open (default) = marked and not done/dropped; untriaged = marked with no progress; stuck = unfinished with a reason flag"},in:{type:"string",describe:"Limit to a channel (#chan)"},from:{type:"string",describe:"Limit to a sender (@user, or 'me') \u2014 usually the person a task is waiting on"},n:{alias:"count",type:"number",default:50,describe:"Max results"},json:{type:"boolean",default:!1}},a=async(r,i)=>{let c={state:r.state??"open",mine:i||r.mine===!0,count:r.n??50,json:r.json===!0};if(r.in)c.in=r.in;if(r.from)c.from=r.from;let l=t(r);if(l)c.cookie=l;await H0(e(r),c)};await Au(oi(process.argv)).scriptName("slack").showHelpOnFail(!1).fail((r,i,c)=>{if(i)console.error(i.message),process.exit(1);console.error(r),console.error(""),c.showHelp(),process.exit(1)}).option("workspace",{alias:"w",type:"string",describe:"Workspace name"}).middleware(async(r)=>{let i=String((r._??[])[0]??"");if(!i||i==="auth"||i==="login"||i==="agent"||i==="sent"||i==="relay")return;try{let c=ks(r.workspace),l=Ue(),u=Mh(r._??[],r,{botTokenSource:l?Dg.get("SLACK_BOT_TOKEN")??Mc.get("SLACK_BOT_TOKEN")?.find((d)=>d.val===l)?.path??"shell":void 0,globalPaths:Jc,slackTokenSet:!!process.env.SLACK_TOKEN,activeTokenIsBot:!!l&&c===l});if(u)console.error(u),process.exit(2)}catch(c){if((c instanceof Error?c.message:String(c)).startsWith("No profiles configured"))console.log(`No workspace configured. Let's set that up:
|
|
554
|
+
`),await Rs(),process.exit(0);throw c}},!0).command("agent","Bot agent session status and command heartbeat",(r)=>Xd(r,xt)).command(["read [target]","msgs [target]"],"Browse messages",(r)=>r.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(r)=>{let i=e(r),c=r.json?"jsonl":r.format,l=r.target?Ba(r.target):void 0;if(l?.thread_ts)await sg(i,l.channel,l.thread_ts,Math.max(r.limit,100),c,t(r));else if(l)await ng(i,l.channel,r.limit,c,r.unreplied,t(r));else if(r.target)await ng(i,r.target,r.limit,c,r.unreplied,t(r));else await J0(i)}).command("thread <target> <ts>","Show thread messages",(r)=>r.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(r)=>{let i=r.json?"jsonl":r.format;await sg(e(r),r.target,r.ts,r.limit,i,t(r),r.since)}).command(["channel","channels","ch"],"Channel commands",(r)=>r.command(["ls","list"],"List channels",(i)=>i.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(i)=>{await K0(e(i),i.limit,i.filter,i.all,i.json?"jsonl":i.format,t(i))}).command("get <channel>","Show channel details",(i)=>i.positional("channel",{type:"string",demandOption:!0,describe:"#name or channel ID"}),async(i)=>{let c=e(i),l=t(i),u=i.channel,d=u.startsWith("#")||u.startsWith("@")||u.startsWith("C")||u.startsWith("G")||u.startsWith("D")?u:`#${u}`,f=await be(c,d,l),p=T(await vn(c,f,l)),g=T(p.channel),h=typeof g.name==="string"?g.name:f,m=g.is_im===!0?"@":"#",w=String(T(g.purpose).value??""),D=String(T(g.topic).value??""),k=g.num_members??g.member_count??"";if(console.log(`${m}${h} ${f}`),D)console.log(`topic: ${D}`);if(w)console.log(`purpose: ${w}`);if(k)console.log(`members: ${k}`);console.log(`private: ${g.is_private===!0}`)}).command(["create <name>","new <name>"],"Create a channel (confirm-hash safety gate)",(i)=>i.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(i)=>{let c=e(i),l=t(i),u=i.name.replace(/^#/,"").toLowerCase(),d=i.private===!0,f=i.invite.filter(Boolean),p=await je(c,l),g=ke(u,String(d),f.join(","),p?.userId??"");if(i.code!==g)Se(i.code,g,["--- Creating channel -------------------------",Ee(p,{pad:9}),` name: ${d?"\uD83D\uDD12 ":"#"}${u}`,` private: ${d}`,...f.length?[` invite: ${f.join(", ")}`]:[],"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let h;try{h=await th(c,u,d,l)}catch(b){console.error(b instanceof Error?b.message:String(b)),process.exit(1)}if(console.log(`\u2713 Created ${d?"\uD83D\uDD12 ":"#"}${h.name} (${h.id})`),f.length){let b=[];for(let m of f)try{b.push(m.startsWith("U")||m.startsWith("W")?m:await Wt(c,m,l))}catch(w){console.error(` ! could not resolve ${m}: ${w instanceof Error?w.message:String(w)}`)}for(let m of b)try{let w=T(await ss(c,m,l)),D=T(w.user);if(D.is_ultra_restricted===!0)console.error(`\u26A0 ${m} is a single-channel guest \u2014 Slack restricts them to their one existing channel; this invite will likely report success but not actually add them.`);else if(D.is_restricted===!0)console.error(`\u26A0 ${m} is a multi-channel guest \u2014 double-check they were actually added (guest invites can silently no-op depending on workspace restrictions).`)}catch{}if(b.length)try{await sh(c,h.id,b,l),console.log(`\u2713 Invited ${b.length} member${b.length===1?"":"s"}`)}catch(m){console.error(` ! invite failed: ${m instanceof Error?m.message:String(m)}`)}}}).command(["rename <channel> <new-name>","mv <channel> <new-name>"],"Rename a channel (confirm-hash safety gate)",(i)=>i.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(i)=>{let c=e(i),l=t(i),u=i.channel;if(u.startsWith("@"))console.error(`Error: ${u} is a DM \u2014 only channels can be renamed.`),process.exit(1);let d=u.startsWith("#")||/^[CG][A-Z0-9]{8,}$/.test(u)?u:`#${u}`,f=i.newName.replace(/^#/,"").toLowerCase(),p,g;try{p=await be(c,d,l)}catch(w){console.error(`Error: could not resolve channel ${u}: ${w instanceof Error?w.message:String(w)}`),process.exit(1)}try{let w=T(T(await vn(c,p,l)).channel);if(w.is_im===!0||w.is_mpim===!0)console.error(`Error: ${p} is a DM \u2014 only channels can be renamed.`),process.exit(1);g=typeof w.name==="string"?w.name:d.replace(/^#/,"")}catch(w){let D=w instanceof Error?w.message:String(w);if(/channel_not_found/.test(D))console.error(`Error: could not resolve channel ${u}: channel not found (or not visible to this token).`),process.exit(1);g=d.replace(/^#/,"")}if(i.dryRun===!0){console.log(`#${g} -> #${f} (${p})`),console.log("(dry run \u2014 conversations.rename not called)");return}let h=await je(c,l),b=ke("rename",p,f,h?.userId??"");if(i.code!==b)Se(i.code,b,["--- Renaming channel -------------------------",Ee(h,{pad:9}),` channel: ${p}`,` from: #${g}`,` to: #${f}`,"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let m;try{m=await nh(c,p,f,l)}catch(w){let k=(w instanceof Error?w.message:String(w)).match(/Slack error on conversations\.rename: (\w+)/)?.[1],E={name_taken:`Error: a channel named #${f} already exists.`,invalid_name:`Error: "${f}" is not a valid channel name (lowercase letters, numbers, hyphens, underscores; max 80 chars).`,invalid_name_specials:`Error: "${f}" contains characters Slack doesn't allow in channel names.`,invalid_name_maxlength:`Error: "${f}" 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 #${g} (workspace settings may restrict renaming to admins or the channel creator).`,not_in_channel:`Error: this token isn't a member of #${g} \u2014 join it first.`,is_archived:`Error: #${g} is archived \u2014 unarchive it before renaming.`};console.error((k&&E[k])??he(w)),process.exit(1)}console.log(`\u2713 Renamed #${g} -> #${m.name} (${m.id})`)}).demandCommand(1,"").showHelpOnFail(!0)).command(["user","usr"],"User commands",(r)=>r.command(["ls","list"],"List workspace members",(i)=>i.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(i)=>{let c=i.json?"jsonl":i.format,l=e(i),u=t(i),d=await ch(l,u),f=i.filter?.toLowerCase(),p=Y(d.members).map(T);if(i.external){let m=new Set(p.map((E)=>String(E.id))),w=T(await qs(l,u)),D=Y(w.channels).map(T).filter((E)=>E.is_ext_shared===!0&&!!E.name),k=new Set;for(let E of D)try{for(let A of await lh(l,String(E.id),u))if(!m.has(A))k.add(A)}catch{}for(let E of k)try{let A=T(await ss(l,E,u)),_=T(A.user);if(_.id)p.push(_)}catch{}}let g=p.filter((m)=>m.deleted!==!0&&m.is_bot!==!0&&String(m.id)!=="USLACKBOT").filter((m)=>{if(!f)return!0;let w=String(m.name??"").toLowerCase(),D=String(T(m.profile).real_name??"").toLowerCase(),k=String(T(m.profile).email??"").toLowerCase();return w.includes(f)||D.includes(f)||k.includes(f)}).slice(0,i.limit);if(c==="jsonl"){for(let m of g)console.log(JSON.stringify(m));return}if(c==="yaml"){for(let m of g){let w=function(D,k=""){if(D===null)return"null";if(typeof D==="string")return D.includes(`
|
|
449
555
|
`)?`|
|
|
450
|
-
${
|
|
556
|
+
${D.split(`
|
|
451
557
|
`).join(`
|
|
452
|
-
`)}`:
|
|
453
|
-
${
|
|
454
|
-
${
|
|
455
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);if(!r.channelId&&!r.userId&&r.target.startsWith("@"))try{r.userId=await It(e(s),r.target,t(s))}catch(c){console.error(`Error: could not resolve ${r.target} to a user for the bot DM.
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(
|
|
459
|
-
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
${
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
${l instanceof Error?l.message:String(l)}
|
|
470
|
-
|
|
471
|
-
Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:u,asBot:!0}}let l=t(c);return{token:e(c),...l?{cookie:l}:{},asBot:!1}},a=(c)=>{console.error(ye(c)),process.exit(1)};return s.command("new <channel> [state] [reason]","Post a NEW board in a channel and pin it \u2014 the state is the top-level message; prints the board's id (C\u2026:ts)",(c)=>c.positional("channel",{type:"string",demandOption:!0,describe:"#chan or channel ID"}).positional("state",{type:"string",describe:"The whole state (\\n for newlines), or use --file"}).positional("reason",{type:"string",describe:"Optional: why the board exists \u2014 its first thread reply"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <channel> is the reason"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog new "#gtm" "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u672A"',"preview, then rerun with --code"),async(c)=>{let l=c.file!==void 0;if(l&&c.state!==void 0&&c.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let u=l?Qo(void 0,c.file):Qo(c.state,void 0),d=l?c.state:c.reason;if(u===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let f=await i(c),h={target:c.channel,state:u,asBot:f.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(d!==void 0)h.log=Ne(d);if(f.cookie)h.cookie=f.cookie;if(typeof c.workspace==="string")h.workspace=c.workspace;if(c.code)h.code=c.code;await Rw(f.token,h).catch(a)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(c)=>c.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("state",{type:"string",describe:"The WHOLE new state, not a diff (or --file)"}).positional("reason",{type:"string",describe:"One short line: what changed and why (required)"}).option("file",{type:"string",describe:"Read the state from a file (- = stdin); then the only positional after <board> is the reason"}).option("adopt",{type:"boolean",default:!1,describe:"Allow a message WITHOUT the pinlog footer: turn a hand-run board into one"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r).example('slack pinlog set <board-link> "\u8CA9\u58F2\u30D6\u30ED\u30C3\u30AB\u30FC\\n1. \u898B\u7A4D\u30C6\u30F3\u30D7\u30EC \u2014 \u6E08" "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"").example('slack pinlog set <board-link> --file board.md "\u898B\u7A4D\u30C6\u30F3\u30D7\u30EC: \u672A \u2192 \u6E08"',"state from a file"),async(c)=>{let l=c.file!==void 0;if(l&&c.state!==void 0&&c.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let u=l?Qo(void 0,c.file):Qo(c.state,void 0),d=l?c.state:c.reason;if(u===void 0||d===void 0)console.error("Error: `pinlog set` needs the whole new state AND the reason: slack pinlog set <board> '<state>' '<reason>'\n Only a reason, state unchanged: slack pinlog note <board> '<reason>'"),process.exit(2);let f=await i(c),h={target:c.board,state:u,log:Ne(d),adopt:c.adopt,asBot:f.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(typeof c.workspace==="string")h.workspace=c.workspace;if(f.cookie)h.cookie=f.cookie;if(c.code)h.code=c.code;await np(f.token,h).catch(a)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(c)=>c.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or the id `new` printed"}).positional("reason",{type:"string",demandOption:!0,describe:"One short line, e.g. still blocked \u2014 chased X"}).option("code",{type:"string",describe:"Safety hash to confirm (printed by the preview)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("as-bot",r),async(c)=>{let l=await i(c),u={target:c.board,log:Ne(c.reason),logOnly:!0,asBot:l.asBot,allowUrlAdjacent:c["allow-url-adjacent"]};if(typeof c.workspace==="string")u.workspace=c.workspace;if(l.cookie)u.cookie=l.cookie;if(c.code)u.code=c.code;await np(l.token,u).catch(a)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(c)=>c.positional("board",{type:"string",demandOption:!0,describe:"The board: permalink, #chan:ts, or C\u2026:ts"}).option("json",{type:"boolean",default:!1,describe:"One JSON object: {id, isPinlog, updated, head, log[]}"}).option("as-bot",r),async(c)=>{let l=await i(c);await Pw(l.token,c.board,l.cookie,c.json).catch(a)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(c)=>c.positional("channel",{type:"string",demandOption:!0}).option("limit",{alias:"n",type:"number",default:500,describe:"How many recent channel messages to scan"}).option("as-bot",r),async(c)=>{let l=await i(c);await vw(l.token,c.channel,c.limit,l.cookie).catch(a)}).command("pin <board>",!1,(c)=>c.positional("board",{type:"string",demandOption:!0}).option("as-bot",r),async(c)=>{let l=await i(c);await Lw(l.token,c.board,l.cookie).catch(a)}).demandCommand(1,"Pick one: ls | get | new | set | note")},()=>{}).command("react <target> <emoji>","Add (or --remove) an emoji reaction \u2014 a lightweight ack that doesn't grow the thread",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("emoji",{type:"string",demandOption:!0,describe:"Emoji shortcode without colons (e.g. eyes, white_check_mark, hourglass)"}).option("remove",{type:"boolean",default:!1,describe:"Remove the reaction instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(s)=>{let r={target:s.target,emoji:s.emoji};if(s.remove)r.remove=!0;if(s["channel-id"])r.channelId=s["channel-id"];let i=t(s);if(i)r.cookie=i;try{await Mw(e(s),r)}catch(a){console.error(ye(a)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)$a(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(r)=>r.options(n).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(r)=>{await o(r,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("state",{type:"string",demandOption:!0,choices:["pending","doing","done","dropped"]}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,state:r.state};if(r["channel-id"])i.channelId=r["channel-id"];let a=t(r);if(a)i.cookie=a;try{await pw(e(r),i)}catch(c){console.error(ye(c)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts or permalink"}).positional("flag",{type:"string",demandOption:!0,choices:["alert","needs-discussion","waiting","blocked"],describe:"waiting = the other party in this conversation owes a reply; blocked = stuck on something outside it"}).option("remove",{type:"boolean",default:!1,describe:"Remove the flag instead of adding it"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={target:r.target,flag:r.flag};if(r.remove)i.remove=!0;if(r["channel-id"])i.channelId=r["channel-id"];let a=t(r);if(a)i.cookie=a;try{await hw(e(r),i)}catch(c){console.error(ye(c)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(r)=>r.option("in",{type:"string",demandOption:!0,describe:"Channel to scan (#chan)"}).option("fix",{type:"boolean",default:!1,describe:"Repair findings (keeps the highest-priority state)"}).option("limit",{type:"number",default:_a,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(r)=>{let i={channel:r.in,limit:r.limit};if(r.fix)i.fix=!0;if(r["channel-id"])i.channelId=r["channel-id"];let a=t(r);if(a)i.cookie=a;await gw(e(r),i)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(s)=>s.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((r)=>{if(r.cache===!1)$a(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(r)=>r.options(n),async(r)=>{await o(r,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(s)=>s.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}),async(s)=>{let r={target:s.target,filePaths:s.file};if(s.title)r.title=s.title;if(s.comment)r.comment=s.comment;if(s["allow-url-adjacent"])r.allowUrlAdjacent=!0;if(s.code)r.code=s.code;if(s["channel-id"])r.channelId=s["channel-id"];if(s["user-id"])r.userId=s["user-id"];let i=t(s);if(i)r.cookie=i;await db(e(s),r)}).command("files","File commands",(s)=>s.command(["ls","list"],"List files visible to you (files.list)",(r)=>r.option("limit",{alias:"l",type:"number",default:100,describe:"Max files to list"}).option("type",{alias:"t",type:"string",describe:"Slack type filter: images, pdfs, gdocs, snippets, zips, spaces, all"}).option("channel",{alias:"c",type:"string",describe:"Only files in this channel (#name, @user, ID, or permalink)"}).option("user",{alias:"u",type:"string",describe:"Only files from this raw user ID"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl"}),async(r)=>{let i={limit:r.limit,format:r.json?"jsonl":r.format};if(r.type)i.types=r.type;if(r.channel)i.channel=r.channel;if(r.user)i.user=r.user;await fb(e(r),t(r),i)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(s)=>s.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(r)=>r.positional("name",{type:"string",demandOption:!0,describe:"List name"}).option("col",{type:"string",array:!0,default:[],describe:"Column name:type (text|select|user|link|date|number|checkbox); select takes name:select:a,b,c. First is the primary text column. Repeatable"}).option("todo",{type:"boolean",default:!1,describe:"Todo mode: adds Completed / Assignee / Due date columns"}).option("code",{type:"string",describe:"Safety hash to confirm create"}),async(r)=>{try{let i={name:r.name,cols:r.col,todo:r.todo===!0};if(r.code!==void 0)i.code=r.code;await mb(i)}catch(i){console.error(ye(i)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("text",{type:"string",demandOption:!0,describe:"Primary (first text) column value"}).option("set",{type:"string",array:!0,default:[],describe:"Other cells: column=value (repeatable)"}).option("code",{type:"string",describe:"Safety hash to confirm add"}),async(r)=>{try{let i={list:r.list,text:r.text,sets:r.set};if(r.code!==void 0)i.code=r.code;await yb(i)}catch(i){console.error(ye(i)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).positional("row",{type:"string",demandOption:!0,describe:"Row id (Rec\u2026), as printed by lists add / lists <ref>"}).option("set",{type:"string",array:!0,default:[],describe:"column=value (repeatable)"}).option("done",{type:"boolean",describe:"Check the row off (--no-done to uncheck); needs a todo-mode list"}).option("code",{type:"string",describe:"Safety hash to confirm update"}),async(r)=>{try{let i={list:r.list,row:r.row,sets:r.set};if(r.done!==void 0)i.done=r.done;if(r.code!==void 0)i.code=r.code;await wb(i)}catch(i){console.error(ye(i)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(r)=>r.positional("list",{type:"string",demandOption:!0,describe:"List URL or F-id"}).option("user",{type:"string",array:!0,default:[],describe:"User ID (U\u2026), repeatable"}).option("channel",{type:"string",array:!0,default:[],describe:"Channel ID (C\u2026), repeatable"}).option("level",{type:"string",choices:["read","write","owner"],default:"write"}).option("code",{type:"string",describe:"Safety hash to confirm share"}),async(r)=>{try{let i={list:r.list,users:r.user,channels:r.channel,level:r.level};if(r.code!==void 0)i.code=r.code;await bb(i)}catch(i){console.error(ye(i)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(r)=>r.positional("ref",{type:"string",demandOption:!0,describe:"List URL (\u2026/lists/<TEAM>/<F-id>) or bare F-id"}).option("limit",{alias:"l",type:"number",default:100,describe:"Max rows to show"}).option("format",{type:"string",choices:["text","jsonl"],default:"text"}).option("json",{type:"boolean",default:!1,describe:"Alias for --format=jsonl (raw records)"}).option("as-bot",{type:"boolean",default:!1,describe:"Read with the bot token (SLACK_BOT_TOKEN, lists:read) via the public API instead of the user session"}),async(r)=>{let i=r.json?"jsonl":r.format;try{let a=r.asBot===!0;await hb(a?"":e(r),a?void 0:t(r),r.ref,{limit:r.limit,format:i,asBot:a})}catch(a){console.error(ye(a)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(s)=>s.positional("ref",{type:"string",demandOption:!0,describe:"File ID (F\u2026) or Slack file permalink"}).positional("dest",{type:"string",describe:"Output path or directory (default: ./<filename>)"}),async(s)=>{await kb(e(s),t(s),s.ref,s.dest)}).command("dump","Bulk export channel history as markdown",(s)=>s.option("days",{alias:"d",type:"number",default:7,describe:"Days of history"}).option("limit",{alias:"l",type:"number",default:200}).option("filter",{alias:"f",type:"string",describe:"Filter channel names"}),async(s)=>{await mw(e(s),s.days,s.limit,s.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (requires xoxc desktop token). Not `slack todo` (reaction tasks)",(s)=>s.command(["$0","ls","list"],"List your To-dos, soonest due first",(r)=>r.option("filter",{type:"string",choices:[...mf],default:"todo",describe:"todo = open to-dos; saved = everything saved; completed; archived"}).option("limit",{alias:"n",type:"number",default:50,describe:"At most this many items"}).option("json",{type:"boolean",default:!1,describe:"One JSON object per item (raw fields + permalink + message text)"}),async(r)=>{if(!Number.isInteger(r.limit)||r.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${r.limit}).`),process.exit(2);await bw(e(r),t(r),{filter:r.filter,limit:r.limit,json:r.json})}).command("add <target>","Add a message to your To-dos (two-step: preview, then --code)",(r)=>r.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(r)=>{let i=r.due===void 0?void 0:ap(r.due);await Zo(e(r),t(r),r.target,{kind:"add",...i?{due:i}:{},saved:r.saved},r.code)}).command(["done <target>","complete <target>"],"Check a to-do off (--undo reopens it)",(r)=>r.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(r)=>{await Zo(e(r),t(r),r.target,{kind:"done",undo:r.undo},r.code)}).command("edit <target>","Change a to-do's due date, or switch it between to-do and saved item",(r)=>r.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(r)=>{let i=r.due===void 0?void 0:r.due==="none"?0:ap(r.due),a=r.todo?!0:r.saved?!1:void 0;await Zo(e(r),t(r),r.target,{kind:"edit",...i===void 0?{}:{due:i},...a===void 0?{}:{todo:a}},r.code)}).command(["rm <target>","remove <target>","delete <target>"],"Remove a message from your To-dos (the message stays)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(r)=>{await Zo(e(r),t(r),r.target,{kind:"rm"},r.code)})).command("drafts","Manage message drafts (requires xoxc desktop token)",(s)=>s.command(["$0","ls","list"],"List pending drafts",(r)=>r.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(r)=>{await ww(e(r),t(r),r.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(r)=>r.positional("channel",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),a=t(r),c=r.text.join(" ");if(!c)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);Ke(c,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await ke(i,r.channel,a),u=await lf(i,l,c,a);console.log(`\u2713 Draft created (id: ${T(u.draft).id??"?"})`)}).command("get <id>","Show a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}),async(r)=>{await Sw(e(r),t(r),r.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).positional("text",{type:"string",array:!0,default:[]}).option("code",{type:"string"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing a bare URL that runs into non-ASCII text (it would link only up to that point)"}),async(r)=>{let i=e(r),a=t(r),c=r.text.join(" ");if(!c)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);Ke(c,r["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let l=await Ts(i,a),u=G(l.drafts).map(T).find((p)=>String(p.id)===r.id);if(!u)console.error(`Draft not found: ${r.id}`),process.exit(1);let d=sr(u),f=await je(i,a),h=xe(d,c,f?.userId??"");if(r.code!==h)Se(r.code,h,["--- Editing draft as -------------------------",_e(f),"--- Current draft ----------------------------",...d.split(`
|
|
472
|
-
`).map((
|
|
473
|
-
`).map((p)=>` ${p}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let g=await uf(i,r.id,Ja(u),c,a);console.log(`\u2713 Draft updated (id: ${T(g.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(r)=>r.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(r)=>{let i=e(r),a=t(r),c=await Ts(i,a),l=G(c.drafts).map(T).find((h)=>String(h.id)===r.id);if(!l)console.error(`Draft not found: ${r.id}`),process.exit(1);let u=sr(l),d=await je(i,a),f=xe(r.id,u,d?.userId??"");if(r.code!==f)Se(r.code,f,["\u2500-- Deleting draft \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",_e(d),` id: ${r.id}`,...u.split(`
|
|
474
|
-
`).map((h)=>` ${h}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await pf(i,r.id,a),console.log(`\u2713 Draft deleted (id: ${r.id})`)})).command("auth","Authentication and workspace management",(s)=>s.command("token","Print the active token (or save one with --token)",(r)=>r.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(r)=>{if(r.token===void 0){console.log(as(r.workspace));return}await mu({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(r)=>{let i=as(r.workspace),a=i.startsWith("xoxc-")?ei(r.workspace):void 0,c=[["SLACK_TOKEN",i]];if(a)c.push(["SLACK_COOKIE",a]);let l=c.map(([u,d])=>{if(/[\r\n\0']/.test(d))throw Error(`Cannot export ${u}: unsupported characters in credential`);return`${u}='${d}'`});console.log(l.join(`
|
|
475
|
-
`))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(r)=>r.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(r)=>{await yu({...r.bot!==void 0?{bot:r.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(r)=>r.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(i)=>i.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(i)=>{await Ti({...i.profile!==void 0?{profile:i.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(i)=>i.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(i)=>{await Ri({...i.workspace!==void 0?{workspace:i.workspace}:{}})}).option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}).option("from-desktop",{type:"boolean",default:!1,describe:"Import the Slack Desktop token without scanning a browser"}).option("from-chrome",{type:"boolean",default:!1,describe:"Import the desktop token and Chrome cookie"}).option("from-firefox",{type:"boolean",default:!1,describe:"Import the desktop token and Firefox cookie"}).option("from-all",{type:"boolean",default:!1,describe:"Import the desktop token and scan Chrome and Firefox"}).command("$0",!1,()=>{},async(i)=>{await ws({...i.token!==void 0?{token:i.token}:{},...i.name!==void 0?{name:i.name}:{},yes:i.yes,fromDesktop:i.fromDesktop,fromChrome:i.fromChrome,fromFirefox:i.fromFirefox,fromAll:i.fromAll})}),async(r)=>{await ws({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{},yes:r.yes,fromDesktop:r.fromDesktop,fromChrome:r.fromChrome,fromFirefox:r.fromFirefox,fromAll:r.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>wu({...r.workspace!==void 0?{workspace:r.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(r)=>r.option("envfile",{type:"string",demandOption:!0,describe:"Destination env file (e.g. ./.env.local)"}).option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(r)=>bu({envfile:r.envfile,...r.workspace!==void 0?{workspace:r.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let r=Qr();if(r.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:i,profile:a,current:c}of r)console.log(`${c?"* ":" "}${i} ${a.team} (${a.user}) ${a.url??""}`)}).command("use <name>","Switch active workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(r)=>{if(!r.g)ew(kt(process.cwd(),".slack-cli"));Pl(r.name,r.g),console.log(`Switched to workspace "${r.name}" ${r.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(r)=>r.positional("name",{type:"string",demandOption:!0}),(r)=>{Ol(r.name),console.log(`Removed workspace "${r.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("profile",{type:"string",alias:"p",describe:"Chrome profile email or dir (Windows, when several have a session)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await gu({...r.workspace!==void 0?{workspace:r.workspace}:{},...r.profile!==void 0?{profile:r.profile}:{},yes:r.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(r)=>r.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}).option("yes",{type:"boolean",default:!1,describe:"Allow reading browser profiles without a confirmation prompt"}),async(r)=>{await Ri({...r.workspace!==void 0?{workspace:r.workspace}:{},yes:r.yes})}).command("$0",!1,()=>{},()=>{s.showHelp(),process.exit(0)})).command("stream","Print every new message matching --grep, across all channels the identity is in (threads included); resumable",(s)=>s.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 (worker/) 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"}),async(s)=>{let r,i,a,c,l,u;try{r=new RegExp(s.grep,s["ignore-case"]?"i":""),a=Kt(s.interval)*1000,c=Kt(s["thread-window"]),l=Kt(s["thread-scan"]),u=s.since!==void 0?Kt(s.since):void 0,i=Kt(s.reconcile)*1000}catch(I){console.error(`slack stream: ${I instanceof Error?I.message:String(I)}`),process.exit(1)}let d=qe(),f=s["as-user"]===!0||!d,h=f?e(s):d,g=f?t(s):void 0;if(!d&&s["as-user"]!==!0)console.error("slack stream: no bot token (SLACK_BOT_TOKEN) \u2014 streaming as the USER identity, which includes its DMs.");let p;try{p=await Ct(h,g)}catch(I){console.error(`slack stream: fatal: ${I instanceof Error?I.message:String(I)}`),process.exit(3)}let m=new Set([p.userId].filter(Boolean)),w=new Set([p.botId].filter(Boolean));if(f&&d)try{let I=await Ct(d);if(I.userId)m.add(I.userId);if(I.botId)w.add(I.botId)}catch{}let b;if(s["replies-to"]?.length){b=new Set;for(let I of s["replies-to"].map(String)){if(I==="self"){for(let U of[p.userId,p.botId])if(U)b.add(U);continue}if(!/^[UWB][A-Z0-9]{2,}$/.test(I))console.error(`slack stream: --replies-to: "${I}" is not a user or bot id (U\u2026/W\u2026/B\u2026) or "self"`),process.exit(1);if(b.add(I),I.startsWith("B"))try{let{userId:U}=await Od(h,I,g);if(U)b.add(U)}catch(U){console.error(`slack stream: --replies-to ${I}: cannot resolve its bot user id (${U instanceof Error?U.message:String(U)}); threads where it shows as a user id are missed`)}}}let D;if(s.channel?.length)try{D=[];for(let I of s.channel)D.push(await ke(h,String(I),g))}catch(I){console.error(`slack stream: --channel: ${I instanceof Error?I.message:String(I)}`),process.exit(1)}let S=up("sha256").update(JSON.stringify([p.url,p.userId,r.source,r.flags,[...D??[]].sort(),...s["replies-to"]?.length?[[...s["replies-to"].map(String)].sort()]:[]])).digest("hex").slice(0,16),A=process.env.XDG_STATE_HOME||kt(La(),".local","state"),F=s.state??kt(A,"slack-term","stream",`${S}.json`);console.error(`slack stream: as ${f?"user":"bot"} @${p.user} (${p.userId}); state ${F}`);let E=process.env.SLACK_RELAY_URL,x=process.env.SLACK_RELAY_TOKEN,W=s.relay&&!f&&!s.once&&E&&x?{url:E,subscribe:Mu(E,x,void 0,{transport:vu(process.env.SLACK_RELAY_TRANSPORT)}),reconcileMs:i}:void 0;if(s.relay&&f&&E)console.error("slack stream: relay not used with --as-user (it only sees the bot's channels)");let Q=!s.relay?"--no-relay":f?E?"--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",M=new AbortController;process.on("SIGINT",()=>M.abort()),process.on("SIGTERM",()=>M.abort());let P=await Ou(Ru(h,g),{grep:r,...b?{repliesTo:b}:{},...D?{channels:D}:{},selfUsers:m,selfBots:w,json:s.json,once:s.once,...u!==void 0?{sinceSec:u}:{},intervalMs:a,threadWindowSec:c,threadScanSec:l,callsPerMin:s["calls-per-min"],...W?{}:{pollReason:Q},statePath:F,teamUrl:p.url,identity:p.userId,signal:M.signal,...W?{relay:W}:{}});process.exit(P)}).command("tail [target]","Stream new messages in real time (like tail -f)",(s)=>s.positional("target",{type:"string",describe:"#channel or @user to follow"}).option("since",{type:"string",describe:"Backfill from N ago (e.g. 10m, 2h, 1d)"}).option("thread",{type:"string",describe:"Follow a single thread by timestamp"}).option("watch-thread",{type:"string",describe:"Watch the channel's top-level timeline AND one thread's replies together (ts or permalink)"}).option("me",{type:"boolean",default:!1,describe:"Filter to messages that mention you"}).option("interval",{type:"number",default:60000,describe:"Poll interval in ms (default 60s; use --interval=3000 for near-real-time)"}).option("timeout",{type:"string",describe:"Auto-stop after this long (e.g. 30m, 2h). Exit code 0 even if nothing arrived."}).option("exit-on-message",{type:"boolean",default:!1,describe:"Stop as soon as the first new message from someone else arrives (wait-for-reply)"}).option("rtm",{type:"boolean",default:!0,describe:"Use RTM WebSocket when available (xoxc + cookie); pass --no-rtm to force polling"}),async(s)=>{let r=e(s),i=t(s),a=new AbortController;process.on("SIGINT",()=>{a.abort(),process.exit(0)}),await _u(r,s.target,{...s.since!==void 0?{since:s.since}:{},...s.thread!==void 0?{thread:s.thread}:{},...s["watch-thread"]!==void 0?{watchThread:s["watch-thread"]}:{},me:s.me,interval:s.interval,...s.timeout!==void 0?{timeout:s.timeout}:{},...s["exit-on-message"]===!0?{exitOnMessage:!0}:{},...i!==void 0?{cookie:i}:{},...s.rtm===!1?{noRtm:!0}:{}},a.signal)}).command("login",!1,(s)=>s.option("token",{type:"string"}).option("name",{type:"string"}).option("yes",{type:"boolean",default:!1}).option("from-desktop",{type:"boolean",default:!1}).option("from-chrome",{type:"boolean",default:!1}).option("from-firefox",{type:"boolean",default:!1}).option("from-all",{type:"boolean",default:!1}),async(s)=>{await ws({...s.token!==void 0?{token:s.token}:{},...s.name!==void 0?{name:s.name}:{},yes:s.yes,fromDesktop:s.fromDesktop,fromChrome:s.fromChrome,fromFirefox:s.fromFirefox,fromAll:s.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}xb().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
|
|
558
|
+
`)}`:D;if(typeof D!=="object")return String(D);if(Array.isArray(D))return D.map((E)=>`
|
|
559
|
+
${k} - ${w(E,k+" ")}`).join("");return Object.entries(D).map(([E,A])=>`
|
|
560
|
+
${k} ${E}: ${w(A,k+" ")}`).join("")};console.log("---");for(let[D,k]of Object.entries(m))console.log(`${D}: ${w(k)}`)}return}let h=Intl.DateTimeFormat().resolvedOptions().timeZone,b=g.length?String(T(Y(d.members).map(T)[0]??{}).team_id??""):"";for(let m of g){let w=T(m.profile),D=String(m.name??m.id),k=String(m.id??""),E=String(w.display_name||""),A=String(w.real_name||""),_=String(w.email||""),S=String(m.tz??""),J=[...new Set([E,A].filter((O)=>O&&O!==D))].join(" / "),L=S&&S!==h?S:"",v=String(m.team_id??""),N=m.is_stranger===!0||b&&v&&v!==b?`external:${v||"?"}`:m.is_ultra_restricted===!0?"single-channel guest":m.is_restricted===!0?"guest":"",H=[_,L].filter(Boolean).join(" ");console.log(`@${D} ${k} ${J}${H?" "+H:""}${N?` [${N}]`:""}`)}}).command("get <user>","Show user details",(i)=>i.positional("user",{type:"string",demandOption:!0,describe:"@handle or user ID"}),async(i)=>{let c=e(i),l=t(i),u=i.user.startsWith("@")?i.user:`@${i.user}`,d="";try{d=await Wt(c,u,l)}catch(I){console.error(I instanceof Error?I.message:String(I)),process.exit(1)}let f=T(await ss(c,d,l)),p=T(f.user),g=T(p.profile),h=Intl.DateTimeFormat().resolvedOptions().timeZone,b=String(p.name??d),m=String(p.id??d),w=String(g.display_name||""),D=String(g.real_name||""),k=String(g.email||""),E=String(p.tz??""),A=String(g.phone||""),_=String(g.title||"");console.log(`@${b} ${m}`);let S=[...new Set([w,D].filter((I)=>I&&I!==b))];if(S.length)console.log(`name: ${S.join(" / ")}`);if(k)console.log(`email: ${k}`);if(A)console.log(`phone: ${A}`);if(_)console.log(`title: ${_}`);if(E&&E!==h)console.log(`tz: ${E}`)}).demandCommand(1,"").showHelpOnFail(!0)).command("news","Activity feed (mentions to you)",(r)=>r.option("limit",{alias:"l",type:"number",default:20}),async(r)=>{await U0(e(r),r.limit)}).command("search <query>","Full-text search",(r)=>r.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(r)=>{await Sg(e(r),r.query,r.count,r.json,t(r))}).command("send <target> <message>","Send a message (confirm-hash safety gate)",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("message",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Send via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient and can be two-way"}).option("broadcast",{type:"boolean",default:!1,describe:`Also send to channel: broadcast a threaded reply back to the channel (Slack's "Also send to #channel" checkbox). Only effective with a thread target.`}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real <@USERID> mentions (on by default; resolves via users.list, then channel members for Slack Connect guests). Unresolved handles stay as plain text. The confirm preview shows the converted message before sending. Disable with --no-mentions for literal @text."}).option("to",{type:"string",describe:"Permalink of the message you are answering: refuses when it is not in the target's thread (see also `slack reply --to`)"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to: send even when the message is in another thread"}),async(r)=>{if(r.to&&!r["any-thread"])try{let i=e(r),c=t(r),l=await ds(i,r.to,c),u=dt(r.target)?await ds(i,r.target,c):void 0,d=u?{channel:u.channel,threadTs:u.root}:(()=>{let g=xt(r.target);return{ref:g.ref,...g.threadTs?{threadTs:g.threadTs}:{}}})(),f="channel"in d?d.channel:await be(i,d.ref,c),p=Ja({channel:f,...d.threadTs?{threadTs:d.threadTs}:{}},l);if(p)console.error(`Error: ${p}`),process.exit(2)}catch(i){console.error(he(i)),process.exit(1)}await s(r)}).command("init [dir]","Create .slack-term/ in a directory: aliases, settings, inbox/outbox (never committed)",(r)=>r.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"}),(r)=>{let{dir:i,created:c}=La(r.dir,{...r.prefix?{prefix:r.prefix}:{},...r.channel?{channel:r.channel}:{},...r["as-bot"]!==void 0?{as_bot:r["as-bot"]}:{}});console.log(c.length?`${i}: created ${c.join(", ")}`:`${i}: already set up`)}).command("alias","Name channels and threads for this directory (the nearest .slack-term/)",(r)=>r.command(["ls","list"],"List aliases: name, channel, thread, file",(i)=>i.option("json",{type:"boolean",default:!1}),(i)=>{let c=Xe(),l=sn(c);if(i.json){console.log(JSON.stringify(l.map(({scope:u,...d})=>d)));return}for(let u of l)console.log(`${u.name} ${u.channel} ${u.thread_ts??"-"} ${u.file}${u.note?` ${u.note}`:""}`);if(!l.length)console.error(`no aliases in ${c.dir}${c.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",(i)=>i.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(i)=>{let c=e(i),l=t(i),u=Xe(i.dir),d=dt(i.target)?.ts!==void 0||xt(i.target).threadTs!==void 0,f,p,g="";if(d){let m=await ds(c,i.target,l);if(f=m.channel,p=m.root,m.root!==m.ts)g=` (${m.ts} is a reply: named its thread root)`}else f=await be(c,xt(i.target).ref,l);let h;try{h=ja(u,i.name,{channel:f,...p?{thread_ts:p}:{},...i.note?{note:i.note}:{}},i.shared)}catch(m){if(m instanceof Tn)console.error(`Error: ${m.message}`),process.exit(2);throw m}let b=h&&(h.channel!==f||h.thread_ts!==p)?` (was ${h.channel} ${h.thread_ts??"-"})`:"";console.log(`${i.name} \u2192 ${f} ${p??"-"}${g}${b} [${u.dir}]`)}).command(["unset <name>","rm <name>"],"Remove an alias (from settings.local.yml; --shared: also from settings.yml)",(i)=>i.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"}),(i)=>{let c=Xe(i.dir),l;try{l=If(c,i.name,i.shared)}catch(u){if(u instanceof Tn)console.error(`Error: ${u.message}`),process.exit(2);throw u}if(l==="removed")console.log(`${i.name} removed [${c.dir}]`);else if(l==="absent")console.error(`no alias "${i.name}" in ${c.dir}`),process.exit(2);else console.error(`"${i.name}" is defined in ${c.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",(i)=>i.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}),(i)=>{let c=Lf(i.channel,i.ts).map((l)=>({dir:I0(l.scope.dir),scope:l.scope.dir,alias:l.name,file:l.file}));if(i.json)console.log(JSON.stringify(c));else for(let l of c)console.log(`${l.dir} ${l.alias}`);if(!c.length)process.exitCode=2}).command("import <tsv>","One-shot: import a legacy allowlist.tsv (<thread_ts> TAB <lane>) into each lane's settings.yml",(i)=>i.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"}),(i)=>{let c=new Map;for(let d of i["lane-dir"]??[]){let f=String(d).indexOf("=");if(f<=0)console.error(`Error: --lane-dir ${d}: want <lane>=<dir>`),process.exit(2);c.set(String(d).slice(0,f),String(d).slice(f+1))}let l=0,u=new Map;for(let d of Wc(i.tsv,"utf8").split(`
|
|
561
|
+
`)){let[f,p]=d.trim().split("\t");if(!f||d.startsWith("#")||!p)continue;let g=c.get(p);if(!g||!/^\d{10}\.\d{6}$/.test(f)){u.set(p,(u.get(p)??0)+1);continue}let h={dir:La(g).dir,global:!1};ja(h,`t-${f}`,{channel:i.channel,thread_ts:f,note:"imported from legacy allowlist"},!0),l++}console.log(`imported ${l} subscription(s)`);for(let[d,f]of u)console.error(`skipped ${f} line(s) for lane "${d}" (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)",(r)=>r.positional("dest",{type:"string",describe:"alias | permalink | #chan:<ts> | <ts> (in settings' channel). Omit with --to"}).positional("message",{type:"string",describe:"Text, or - for stdin"}).option("to",{type:"string",describe:"Permalink of the message you are answering: replies in ITS thread; with a dest, refuses when they differ"}).option("any-thread",{type:"boolean",default:!1,describe:"With --to and a dest: post to dest even when the message is in another thread"}).option("prefix",{type:"string",describe:`Override settings' prefix ("" for none)`}).option("code",{type:"string",describe:"Safety hash to confirm send"}).option("as-bot",{type:"boolean",describe:"Send via the bot token (default: settings' as_bot)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("broadcast",{type:"boolean",default:!1,describe:"Also send to channel"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens to real mentions (--no-mentions for literal text)"}),async(r)=>{let{dest:i,message:c}=r;if(r.to&&c===void 0)c=i,i=void 0;if(c==="-")c=await Bun.stdin.text();if(c===void 0||!c.trim())console.error("Error: message is empty"),process.exit(1);if(!i&&!r.to)console.error("Error: reply needs a destination (alias, permalink, #chan:<ts>) or --to <permalink>"),process.exit(2);let l=e(r),u=t(r),d=Xe(),f=Ns(d),p;try{let m=await rg(l,u,d,i,r.to,r["any-thread"]);if("error"in m)console.error(`Error: ${m.error}`),process.exit(2);p=m}catch(m){console.error(he(m)),process.exit(1)}let{channel:g,threadTs:h}=p;if(On(d)&&(r.prefix!==void 0||r["as-bot"]!==void 0&&r["as-bot"]!==(f.as_bot??!1)))console.error(`Error: ${d.dir} is restricted: who it posts as (prefix, as_bot) comes from settings.yml; --prefix / --as-bot are refused`),process.exit(2);let b=Wa(c,r.prefix??f.prefix);if(!b.trim())console.error("Error: message is empty (only the prefix)"),process.exit(1);await s({workspace:r.workspace,target:`${g}:${h}`,message:b,code:r.code,"allow-url-adjacent":r["allow-url-adjacent"],"as-bot":r["as-bot"]??f.as_bot??!1,broadcast:r.broadcast,mentions:r.mentions})}).command("inbox","This directory's .slack-term/inbox/: messages routed here by `slack stream --inbox`",(r)=>r.command(["ls","list"],"Pending messages: ts, from, alias, text (redacted)",(i)=>i.option("json",{type:"boolean",default:!1}),(i)=>{let c=ts(Xe());if(i.json){console.log(JSON.stringify(c.map((l)=>({file:l.file,...l.entry}))));return}for(let l of c)console.log(`${l.entry.ts} ${l.entry.user_name??l.entry.user} ${l.entry.alias} ${l.entry.text.replace(/\\/g,"\\\\").replace(/\n/g,"\\n").replace(/\t/g,"\\t")}${l.entry.files?` [files: ${l.entry.files}]`:""}`)}).command("listen","Print each message as it arrives in inbox/ (one JSON line each); pending ones first. Exits 0 at --timeout",(i)=>i.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(i)=>{let c=Xe(),l=i.from?.length?new Set(i.from.map(String)):void 0,u=(p)=>(!i.thread||(p.thread_ts??p.ts)===i.thread)&&(!i.alias||p.alias===i.alias)&&(!l||l.has(p.user)),d=new Set;if(i["new-only"])for(let p of ts(c))d.add(p.file);let f=Date.now()+i.timeout*1000;for(;;){for(let p of ts(c)){if(d.has(p.file))continue;if(d.add(p.file),u(p.entry))console.log(JSON.stringify({file:p.file,...p.entry}))}if(Date.now()>=f)break;await new Promise((p)=>setTimeout(p,Math.min(500,Math.max(0,f-Date.now()))))}}).command("nudge","Pending messages older than settings' nudge_after_min (default 30): exit 1 when there are any",(i)=>i.option("json",{type:"boolean",default:!1}),(i)=>{let c=tp(Xe());if(i.json)console.log(JSON.stringify(c.map((l)=>({file:l.file,ts:l.entry.ts,channel:l.entry.channel,permalink:l.entry.permalink,waiting_min:Math.round((Date.now()-l.mtimeMs)/60000)}))));else for(let l of c)console.log(`${l.entry.ts} ${Math.round((Date.now()-l.mtimeMs)/60000)} min ${l.entry.permalink}`);if(c.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",(r)=>r.positional("ref",{type:"string",array:!0,demandOption:!0}),(r)=>{let i=Xe(),c=0;for(let l of r.ref){let u=qa(i,l);if(u)console.log(`archived ${u}`);else console.error(`not in ${i.dir}/inbox: ${l}`),c++}if(c)process.exit(2)}).command("outbox","This directory's .slack-term/outbox/: replies queued as files, sent by `outbox flush`",(r)=>r.command("add <dest> <message>","Queue a reply (text redacted before it is written; - reads stdin)",(i)=>i.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(i)=>{let c=i.message==="-"?await Bun.stdin.text():i.message;if(!c.trim())console.error("Error: message is empty"),process.exit(1);let l=Zf(Xe(),{to:i.dest,text:c,...i["in-reply-to"]?{in_reply_to:i["in-reply-to"]}:{}});if(l.redacted.length)console.error(`\u26A0 redacted before queueing: ${l.redacted.join(", ")}`);console.log(l.file)}).command(["ls","list"],"Queued replies: file, dest, attempts, error",(i)=>i,()=>{for(let i of Ha(Xe()))console.log(`${i.file} ${i.entry.to}${i.entry.attempts?` attempts=${i.entry.attempts} ${i.entry.error??""}`:""}`)}).command("flush","Send every queued reply (prefix, thread and restrict checks as `reply`); a --code covers the whole batch",(i)=>i.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(i)=>{let c=Xe(),l=Ns(c),u=Ha(c);if(!u.length){console.error(`nothing in ${c.dir}/outbox`);return}if(On(c)&&i["as-bot"]!==void 0&&i["as-bot"]!==(l.as_bot??!1))console.error(`Error: ${c.dir} is restricted: as_bot comes from settings.yml; --as-bot is refused`),process.exit(2);let d=i["as-bot"]??l.as_bot??!1,f=e(i),p=t(i),g,h;if(d){let E=Ue();if(!E)console.error("Error: as_bot needs a bot token (SLACK_BOT_TOKEN)"),process.exit(1);g=E}else g=f,h=p;let b=[],m=[];for(let E of u)try{let A=await rg(f,p,c,E.entry.to,void 0);if("error"in A){m.push(`${E.file}: ${A.error}`);continue}let _=Wa(E.entry.text,l.prefix);if(!_.trim()){m.push(`${E.file}: empty`);continue}b.push({item:E,...A,text:_})}catch(A){m.push(`${E.file}: ${he(A)}`)}for(let E of m)console.error(`refused (stays queued): ${E}`);if(!b.length)process.exit(2);let w=[`OUTBOX \u2014 ${b.length} repl${b.length===1?"y":"ies"}${d?" as the bot":""}:`];for(let E of b)w.push(` \u2192 ${E.channel} thread ${E.threadTs}: ${P(E.text).replace(/\n/g,"\u23CE").slice(0,120)}`);let D=ke("outbox",d?"bot":"user",...b.map((E)=>`${E.channel}:${E.threadTs}:${E.text}`));if(i.code!==D)Se(i.code,D,w);let k=0;for(let E of b)try{let A=await Lt(g,E.channel,E.text,E.threadTs,!1,h),_="";try{_=await In(g,E.channel,A,h)}catch{}let S=Qf(c,E.item,{ts:A,permalink:_,channel:E.channel,thread_ts:E.threadTs});console.log(`\u2713 ${_||A} (${S})`)}catch(A){ep(E.item,he(A)),console.error(`\u2717 ${E.item.file}: ${he(A)}`),k++}if(k)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> \u7121\u52B9\u5316 (verb aliases: `ask collect <link>`, `ask void <link\u2026>`)",(r)=>r.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --waitFor)"}).positional("question",{type:"string",describe:"The question. Must @tag whoever may answer (@alice), or the whole channel (@here / @channel / @everyone) \u2014 only their answer counts. In a 1:1 DM the other party counts automatically."}).positional("choices",{type:"string",array:!0,describe:"Up to 10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions. Beyond 10 they are listed but answerable only by text. With none, the question asks for a free-text reply."}).option("code",{type:"string",describe:"Safety hash to confirm the ask"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("lang",{type:"string",choices:[...Et],describe:"Language of the instructions in the posted body. Default: $SLACK_TERM_LANG, else the answerers' Slack locale, else the question's own language, else the system locale, else ja"}).option("wait",{type:"boolean",default:!1,describe:"Block until answered; print ONLY the answer on stdout. Exit 0 = answered, 2 = nobody replied, 3 = transport failure, 4 = a reply matched several choices (stdout empty), 5 = a free-text reply that picked none of the choices (the reply is on stdout; NOT a decision \u2014 the question stays open), 6 = the question was voided (\u7121\u52B9\u5316, `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:"\u7121\u52B9\u5316: void question(s) you posted that expired or stopped meaning anything \u2014 --void=<permalink>, repeatable. The text becomes \uD83D\uDEAB with --reason (body kept, options removed), our pills come off, and --wait/--waitFor on it exits 6. Same --code gate. Only your own questions (--as-bot for the bot's). Alias: `slack ask void <link\u2026>`."}).option("reask",{type:"boolean",default:!1,describe:"With ONE --void: post the question again (same channel/thread, same text and choices unless you give new ones as positionals / --body) and void the old one as replaced by it \u2014 one gate for both. The way to change the options of a question someone already answered."}).option("edit",{type:"string",describe:'Change an open question you posted: --edit=<permalink> ["new question" [choices\u2026]] [--body \u2026]. Rebuilt with the ask layout so collect still reads it. Options can change only while nobody has answered (then: --void=<link> --reask). Same --code gate.'}).option("ls",{type:"boolean",default:!1,describe:"List the questions you posted (local sent-log) with their LIVE state: --state open|answered|void|all (default open), --stale 24h, --channel, --json. With --stale it prints the --void command that would retire them."}).option("pending",{type:"boolean",default:!1,describe:"List questions THIS machine asked (local sent-log) that somebody answered but nobody collected, grouped by the asking session, with whether that agent is still alive and the --waitFor line that collects each. Read-only: --since 7d, --channel, --json."}).option("since",{type:"string",default:"7d",describe:"With --pending: how far back to look (30m, 2h, 7d, or an ISO date)"}).option("stale",{type:"string",describe:"With --ls: only open questions older than this (24h, 3d)"}).option("state",{type:"string",default:"open",choices:["open","answered","void","edited","gone","unknown","all"],describe:"With --ls: which state to list"}).option("channel",{type:"string",describe:"With --ls / --pending: only this channel (id, or the target as typed)"}).option("limit",{type:"number",default:50,describe:"With --ls: how many recent asks to check"}).option("reason",{type:"string",describe:"With --void: why it is void (written into the message)"}).option("superseded-by",{type:"string",describe:"With --void: permalink of the question that replaces it"}).option("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(r)=>{if(r.ls||r.pending){if(r.ls&&r.pending)console.error("Error: --ls and --pending are separate lists \u2014 pick one."),process.exit(le);let m=(()=>{try{return e(r)}catch{return}})(),w={};if(m)w.user=m;let D=Ue();if(D)w.bot=D;let k=t(r);if(k)w.cookie=k;if(r.pending){if(r.target||r.question||r.waitFor||r.wait||r.void||r.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 A=go(String(r.since));if(A===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${P(String(r.since))})`),process.exit(le);let _={sinceMs:A,json:!!r.json};if(r.channel)_.channel=String(r.channel);try{await Ik(w,_)}catch(S){console.error(he(S)),process.exit(le)}return}let E={state:String(r.state??"open"),json:!!r.json,limit:Number(r.limit)||50};if(r.stale)E.stale=String(r.stale);if(r.channel)E.channel=String(r.channel);await Rk(w,E);return}let i=(m)=>{if(!m){let D=t(r);return D?{token:e(r),cookie:D}:{token:e(r)}}let w=Ue();if(!w)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
562
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);return{token:w}},c=r.target!==void 0&&r.target!=="void"&&r.target!=="collect"?String(r.target):void 0,l=[r.question,...r.choices??[]].filter((m)=>m!==void 0).map(String);if(r.edit){if(r.void||r.wait||r.waitFor)console.error("Error: --edit changes one open question \u2014 do not combine it with --void/--wait/--waitFor."),process.exit(le);let{token:m,cookie:w}=i(!!r["as-bot"]),D={link:String(r.edit),asBot:!!r["as-bot"],mentionToken:m,allowUrlAdjacent:!!r["allow-url-adjacent"]};if(c!==void 0)D.question=c;if(l.length)D.choices=l.map((k)=>k.trim()).filter(Boolean);if(r.body!==void 0)D.body=String(r.body);if(r.lang)D.lang=String(r.lang);if(r.code)D.code=String(r.code);if(w)D.cookie=w,D.mentionCookie=w;try{await Ok(m,D)}catch(k){console.error(he(k)),process.exit(le)}return}let u,d=(r.void??[]).map(String).filter(Boolean);if(r.reask){if(d.length!==1||r.target==="void")console.error("Error: --reask goes with exactly one --void=<permalink> (the question to replace)."),process.exit(le);if(r.waitFor)console.error("Error: --reask posts a new question \u2014 --wait works, --waitFor does not."),process.exit(le);let{token:m,cookie:w}=i(!!r["as-bot"]),D=await je(m,w),k=await Pg(m,d[0],D,!!r["as-bot"],w);if(k==="void")console.error(`\u2717 ${P(d[0])}: \u3059\u3067\u306B\u7121\u52B9\u5316\u6E08\u307F\u3067\u3059 \u2014 \u65B0\u3057\u304F\u805E\u304F\u306A\u3089\u666E\u901A\u306B slack ask \u3067`),process.exit(le);if(!k)process.exit(le);if(u={...k,reason:Ne(String(r.reason??"")).trim()},r.target=k.threadTs?`${k.channelId}:${k.threadTs}`:k.channelId,r["channel-id"]=k.channelId,r.question=c??os(k.parsed.question),r.choices=l.length?l:[...k.parsed.reactable,...k.parsed.overflow].map(os),r.body===void 0&&k.parsed.body)r.body=os(k.parsed.body);if(!r.lang)r.lang=k.parsed.lang;if(r.explain===void 0&&k.parsed.explain)r.explain=!0;r.void=void 0}if(!u&&(r.target==="void"||d.length)){let m=r.target==="void"?[r.question,...r.choices??[]]:[];if(r.target!=="void"&&(r.target||r.question||r.choices?.length))console.error("Error: --void voids existing questions \u2014 do not also pass a target/question/choices."),process.exit(le);let w=[...d,...m.map((A)=>String(A??""))].filter(Boolean);if(!w.length)console.error("Error: --void=<permalink> \u2014 which question(s)?"),process.exit(le);if(r.wait||r.waitFor)console.error("Error: --void voids existing questions \u2014 do not also pass --wait/--waitFor."),process.exit(le);let D,k;if(r["as-bot"]){let A=Ue();if(!A)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
563
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);D=A}else D=e(r),k=t(r);let E={links:w,reason:Ne(String(r.reason??"")).trim(),asBot:!!r["as-bot"]};if(r["superseded-by"])E.supersededBy=String(r["superseded-by"]);if(r.code)E.code=String(r.code);if(k)E.cookie=k;try{await vk(D,E)}catch(A){console.error(he(A)),process.exit(le)}return}if(r.target==="collect"){if(!r.question||r.choices?.length)console.error("Error: slack ask collect <permalink> \u2014 exactly one question."),process.exit(le);r.waitFor=String(r.question),r.target=void 0,r.question=void 0}let f=r.waitFor?String(r.waitFor):"",p=Number(r.timeout);if(!Number.isFinite(p)||p<0||p===0&&!f)console.error("Error: --timeout must be a positive number of seconds"),process.exit(le);if(f){if(r.target||r.question||r.choices?.length)console.error("Error: --waitFor collects an existing question \u2014 do not also pass a target/question/choices."),process.exit(le);let m,w;if(r["as-bot"]){let D=Ue();if(!D)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
564
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);m=D}else m=e(r),w=t(r);try{let D={link:f,timeout:p,asBot:!!r["as-bot"],json:!!r.json};if(r["explain-exit"])D.explainExit=!0;if(w)D.cookie=w;if(r.after){let k=String(r.after);if(!/^\d{10}\.\d{6}$/.test(k))console.error(`Error: --after needs a message ts like 1700000000.000100 (got ${P(k)})`),process.exit(le);D.after=k}await Pk(m,D)}catch(D){console.error(he(D)),process.exit(le)}return}if(!r.target)console.error("Error: target is required (or use --waitFor <permalink> to collect an answer)"),process.exit(le);let g=String(r.question??"").trim();if(!g)console.error("Error: question is empty"),process.exit(le);let h={allowUrlAdjacent:r["allow-url-adjacent"],target:r.target,question:g,choices:(r.choices??[]).map((m)=>String(m).trim()).filter(Boolean),timeout:p};if(r.code)h.code=r.code;if(r.body)h.body=r.body;if(r.lang)h.lang=String(r.lang);if(r.wait)h.wait=!0;if(r.json)h.json=!0;if(typeof r.explain==="boolean")h.explain=r.explain;if(r["explain-exit"])h.explainExit=!0;if(u)h.voidAfter=u;if(r["channel-id"])h.channelId=r["channel-id"];if(r["user-id"])h.userId=r["user-id"];let b;if(r["as-bot"]){let m=Ue();if(!m)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
565
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(le);if(!h.channelId&&!h.userId&&h.target.startsWith("@"))try{h.userId=await Wt(m,h.target)}catch(w){console.error(`Error: could not resolve ${h.target} to a user for the bot DM.
|
|
566
|
+
${w instanceof Error?w.message:String(w)}
|
|
567
|
+
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(le)}b=m,h.mentionToken=m,h.asBot=!0}else{b=e(r),h.mentionToken=b;let m=t(r);if(m)h.cookie=m,h.mentionCookie=m}try{await Fk(b,h)}catch(m){console.error(he(m)),process.exit(le)}}).command(["poll [target] [question] [choices..]","vote [target] [question] [choices..]"],"Post a poll with its choices pre-seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions, then count them (confirm-hash safety gate)",(r)=>r.positional("target",{type:"string",describe:"#chan, @user, #chan:thread_ts, or permalink (omit with --results/--close)"}).positional("question",{type:"string",describe:"The question. @tags are optional here \u2014 unlike `ask`, a poll needs no addressee: anyone who can see it may vote."}).positional("choices",{type:"string",array:!0,describe:"2..10 choices, seeded as 1\uFE0F\u20E3..\uD83D\uDD1F reactions for voters to click"}).option("multi",{type:"boolean",default:!1,describe:"Let one person pick several choices (default: 1 \u4EBA 1 \u7968)"}).option("until",{type:"string",describe:"Deadline shown in the message (display only \u2014 closing is still `--close`)"}).option("results",{type:"string",describe:"Count an existing poll: pass its permalink. Posts nothing; only edit is the invalid-ballot notice in the poll itself (--no-notify to suppress)."}).option("close",{type:"string",describe:"Count an existing poll AND freeze the tally into the message. Only the poster can do this."}).option("names",{type:"boolean",default:!1,describe:"Also list who voted for what (stderr)"}).option("no-notify",{type:"boolean",default:!1,describe:"With --results: do not write the invalid-ballot notice back into the message (keeps it strictly read-only)"}).option("code",{type:"string",describe:"Safety hash to confirm the post"}).option("body",{type:"string",describe:"Extra context shown under the question"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("user-id",{type:"string",describe:"Raw user ID (opens DM)"}).option("as-bot",{type:"boolean",default:!1,describe:"Post via the bot token (xoxb / SLACK_BOT_TOKEN) so a DM notifies the recipient \u2014 and so YOUR OWN vote counts, since the seeds are then the bot's. @tags and an @user target then resolve with the bot token too (needs users:read)."}),async(r)=>{let i=r.close?String(r.close):r.results?String(r.results):"";if(r.results&&r.close)console.error("Error: pass --results or --close, not both (--close counts as well)."),process.exit(pt);let c=()=>{let p=Ue();if(!p)console.error(`Error: --as-bot needs a bot token, but no xoxb- token was found.
|
|
568
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(pt);return p};if(i){if(r.target||r.question||r.choices?.length)console.error("Error: --results/--close reads an existing poll \u2014 do not also pass a target/question/choices."),process.exit(pt);let p=e(r),g=t(r);try{let h={link:i};if(r.close)h.close=!0;if(r.names)h.names=!0;if(r["no-notify"])h.noNotify=!0;if(g)h.cookie=g;if(r["as-bot"])h.writeToken=c();await Bk(p,h)}catch(h){console.error(he(h)),process.exit(pt)}return}if(!r.target)console.error("Error: target is required (or use --results <permalink> to count a poll)"),process.exit(pt);let l=String(r.question??"").trim();if(!l)console.error("Error: question is empty"),process.exit(pt);let u=(r.choices??[]).map((p)=>String(p).trim()).filter(Boolean);if(u.length<2||u.length>ns)console.error(`Error: poll needs 2..${ns} choices (got ${u.length}). For a free-text question use \`slack ask\`.`),process.exit(pt);let d={target:r.target,question:l,choices:u};if(r.multi)d.multi=!0;if(r.until)d.until=String(r.until);if(r.code)d.code=r.code;if(r.body)d.body=r.body;if(r["allow-url-adjacent"])d.allowUrlAdjacent=!0;if(r["channel-id"])d.channelId=r["channel-id"];if(r["user-id"])d.userId=r["user-id"];let f;if(r["as-bot"]){let p=c();if(!d.channelId&&!d.userId&&d.target.startsWith("@"))try{d.userId=await Wt(p,d.target)}catch(g){console.error(`Error: could not resolve ${d.target} to a user for the bot DM.
|
|
569
|
+
${g instanceof Error?g.message:String(g)}
|
|
570
|
+
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(pt)}f=p,d.mentionToken=p,d.asBot=!0}else{f=e(r),d.mentionToken=f;let p=t(r);if(p)d.cookie=p,d.mentionCookie=p}try{await Mk(f,d)}catch(p){console.error(he(p)),process.exit(pt)}}).command("sent [query]","Search what THIS machine posted/edited (send, ask, poll, edit) and who sent it \u2014 read-only, local log",(r)=>r.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)"}),(r)=>{let i;if(r.since!==void 0){if(i=go(String(r.since)),i===void 0)console.error(`Error: --since needs 30m / 2h / 7d / 1w or an ISO date (got ${P(String(r.since))})`),process.exit(1)}let c={limit:Number(r.count)||50};if(r.query)c.text=String(r.query);if(r.channel)c.channel=String(r.channel);if(i!==void 0)c.sinceMs=i;if(r.session)c.session=String(r.session);if(r.cwd){let u=v0(String(r.cwd));try{c.cwd=R0(u)}catch{c.cwd=u}}if(r.kind)c.kind=r.kind;let l=rc(c);if(!l)console.error(`Error: ${Us}
|
|
571
|
+
(${At()})`),process.exit(1);if(r.json){for(let u of l)console.log(JSON.stringify(u));return}if(!l.length){console.error(`No sent messages match (log: ${At()}).`);return}for(let u of l)console.log(ok(u))}).command("doctor","Check the bot token (xoxb) can carry a two-way DM (scopes + Messages Tab)",(r)=>r,async()=>{let r=Ue();if(!r)console.error(`Error: slack doctor checks the bot token, but no xoxb- token was found.
|
|
572
|
+
Set SLACK_BOT_TOKEN=xoxb-... in ~/.config/slack-cli/.env (or your shell).`),process.exit(1);await jk(r)}).command("schedule","Manage scheduled messages",(r)=>r.command("send <target> <message>","Schedule a message for later delivery",(i)=>i.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(i)=>{if(!String(i.message??"").trim())console.error("Error: message is empty"),process.exit(1);let c={target:i.target,message:i.message,at:i.at};if(i.code)c.code=i.code;if(i["allow-url-adjacent"])c.allowUrlAdjacent=!0;if(i["channel-id"])c.channelId=i["channel-id"],c.targetOverride=`--channel-id ${i["channel-id"]}`;if(i["user-id"])c.userId=i["user-id"],c.targetOverride=`--user-id ${i["user-id"]}`;let l;if(i["as-bot"]){let u=Ao();if(!c.channelId&&!c.userId&&c.target.startsWith("@"))try{c.userId=await Wt(e(i),c.target,t(i))}catch(d){console.error(`Error: could not resolve ${c.target} to a user for the bot DM.
|
|
573
|
+
${d instanceof Error?d.message:String(d)}
|
|
574
|
+
Tip: pass --user-id <Uxxxx> to skip the lookup.`),process.exit(1)}l=u,c.asBot=!0}else{l=e(i);let u=t(i);if(u)c.cookie=u}await Wk(l,c)}).command(["ls","list"],"List pending scheduled messages",(i)=>i.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(i)=>{let c=i.target;if(i["as-bot"]){let l=Ao(),u=i["channel-id"];if(!u&&c?.startsWith("@"))u=await pg(c,l,e(i),t(i));await gg(l,c,u);return}await gg(e(i),c,i["channel-id"],t(i))}).command("rm <target> <id>","Delete a scheduled message",(i)=>i.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(i)=>{let c={target:i.target,id:i.id};if(i.code)c.code=i.code;if(i["channel-id"])c.channelId=i["channel-id"],c.targetOverride=`--channel-id ${i["channel-id"]}`;if(i["as-bot"]){let u=Ao();if(!c.channelId&&c.target.startsWith("@"))c.channelId=await pg(c.target,u,e(i),t(i));c.asBot=!0,await mg(u,c);return}let l=t(i);if(l)c.cookie=l;await mg(e(i),c)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("edit <target> <newText>","Edit a sent message",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan:ts, @user:ts, or permalink"}).positional("newText",{type:"string",demandOption:!0}).option("code",{type:"string",describe:"Safety hash to confirm edit"}).option("force",{type:"boolean",default:!1,describe:"Apply an edit that BREAKS a `slack ask` / `slack poll` message (new text no longer reads as one, or an answered/void question made open again). Refused by default because collect reads that body back; edits that keep it readable (e.g. writing the \u2705 form) need no flag. Prefer `slack ask --edit=` / `--void=`."}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("channel-id",{type:"string",describe:"Raw channel ID"}).option("mentions",{type:"boolean",default:!0,describe:"Convert @handle tokens in the new text to real <@USERID> mentions (on by default). Unresolved handles stay as plain text. Disable with --no-mentions for literal @text."}).option("as-bot",{type:"boolean",default:!1,describe:"Edit as the bot (xoxb / SLACK_BOT_TOKEN). REQUIRED to correct a message the bot posted: Slack only lets a token edit its OWN messages, so a bot-authored message is uneditable by the user token and chat.update returns cant_update_message. Address it by permalink or --channel-id; an @user target resolves against the BOT's DM list, which is where a bot-authored DM actually lives."}),async(r)=>n(r)).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)",(r)=>r.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(r)=>n({...r,tick:r.n!==void 0?{n:r.n}:{},mentions:!1})).command("delete <target>","Delete a sent message (confirm-hash safety gate)",(r)=>r.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(r)=>{let i={target:r.target};if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"];let c;if(r["as-bot"]){let l=await ag(i.target,e(r),t(r),i.channelId);if(c=l.botToken,l.channelId&&!i.channelId)i.channelId=l.channelId;i.asBot=!0}else{c=e(r);let l=t(r);if(l)i.cookie=l}await lk(c,i)}).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)",(r)=>{let i={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."},c=async(u)=>{if(u["as-bot"]){let f=Ao();if(typeof u.workspace==="string"){let p=t(u),[g,h]=await Promise.all([Pt(e(u),p),Pt(f)]);if(g.url!==h.url)console.error(`Error: --as-bot acts with SLACK_BOT_TOKEN, which belongs to ${h.url}, but -w ${u.workspace} is ${g.url}.
|
|
575
|
+
Drop -w, or set SLACK_BOT_TOKEN to that workspace's bot token.`),process.exit(2)}return{token:f,asBot:!0}}let d=t(u);return{token:e(u),...d?{cookie:d}:{},asBot:!1}},l=(u)=>{console.error(he(u)),process.exit(1)};return r.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)",(u)=>u.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",i).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(u)=>{let d=u.file!==void 0;if(d&&u.state!==void 0&&u.reason!==void 0)console.error("Error: with --file, pass only the reason after <channel> (the state comes from the file)."),process.exit(2);let f=d?Co(void 0,u.file):Co(u.state,void 0),p=d?u.state:u.reason;if(f===void 0)console.error("Error: the state is required (positional or --file)."),process.exit(2);let g=await c(u),h={target:u.channel,state:f,asBot:g.asBot,allowUrlAdjacent:u["allow-url-adjacent"]};if(p!==void 0)h.log=Ne(p);if(g.cookie)h.cookie=g.cookie;if(typeof u.workspace==="string")h.workspace=u.workspace;if(u.code)h.code=u.code;await dk(g.token,h).catch(l)}).command("set <board> [state] [reason]","Change a board: replace its state (silent edit) AND post the reason in its thread (notifies)",(u)=>u.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",i).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(u)=>{let d=u.file!==void 0;if(d&&u.state!==void 0&&u.reason!==void 0)console.error("Error: with --file, pass only the reason after <board> (the state comes from the file)."),process.exit(2);let f=d?Co(void 0,u.file):Co(u.state,void 0),p=d?u.state:u.reason;if(f===void 0||p===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 g=await c(u),h={target:u.board,state:f,log:Ne(p),adopt:u.adopt,asBot:g.asBot,allowUrlAdjacent:u["allow-url-adjacent"]};if(typeof u.workspace==="string")h.workspace=u.workspace;if(g.cookie)h.cookie=g.cookie;if(u.code)h.code=u.code;await lg(g.token,h).catch(l)}).command("note <board> <reason>","Post only a reason in a board's thread (notifies); the state stays as is",(u)=>u.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",i),async(u)=>{let d=await c(u),f={target:u.board,log:Ne(u.reason),logOnly:!0,asBot:d.asBot,allowUrlAdjacent:u["allow-url-adjacent"]};if(typeof u.workspace==="string")f.workspace=u.workspace;if(d.cookie)f.cookie=d.cookie;if(u.code)f.code=u.code;await lg(d.token,f).catch(l)}).command(["get <board>","show <board>"],"Show a board's state and its log (read-only)",(u)=>u.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",i),async(u)=>{let d=await c(u);await hk(d.token,u.board,d.cookie,u.json).catch(l)}).command(["ls <channel>","list <channel>"],"List the boards in a channel, found by their footer (read-only)",(u)=>u.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",i),async(u)=>{let d=await c(u);await gk(d.token,u.channel,u.limit,d.cookie).catch(l)}).command("pin <board>",!1,(u)=>u.positional("board",{type:"string",demandOption:!0}).option("as-bot",i),async(u)=>{let d=await c(u);await mk(d.token,u.board,d.cookie).catch(l)}).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",(r)=>r.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(r)=>{let i={target:r.target,emoji:r.emoji};if(r.remove)i.remove=!0;if(r["channel-id"])i.channelId=r["channel-id"];let c=t(r);if(c)i.cookie=c;try{await yk(e(r),i)}catch(l){console.error(he(l)),process.exit(1)}}).command("todo","Reaction-backed task tracking (:pushpin: marks a task, progress lives in a second reaction)",(r)=>r.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((i)=>{if(i.cache===!1)$c(!1)}).command(["ls","list"],"List everyone's tasks (has: \u2014 read-only, one search per run)",(i)=>i.options(o).option("mine",{type:"boolean",default:!1,describe:"Only your own reactions (hasmy:) \u2014 same as `slack mytodo ls`"}).option("shared",{type:"boolean",default:!1,hidden:!0,describe:"Deprecated \u2014 anyone's reactions is the default for `todo ls`"}),async(i)=>{await a(i,!1)}).command("set <target> <state>","Move a task to a progress state (adds the new reaction before removing the old one)",(i)=>i.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(i)=>{let c={target:i.target,state:i.state};if(i["channel-id"])c.channelId=i["channel-id"];let l=t(i);if(l)c.cookie=l;try{await z0(e(i),c)}catch(u){console.error(he(u)),process.exit(1)}}).command("flag <target> <flag>","Add (or --remove) a reason flag (alert | needs-discussion | waiting | blocked) \u2014 flags stack, independent of progress",(i)=>i.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(i)=>{let c={target:i.target,flag:i.flag};if(i.remove)c.remove=!0;if(i["channel-id"])c.channelId=i["channel-id"];let l=t(i);if(l)c.cookie=l;try{await Y0(e(i),c)}catch(u){console.error(he(u)),process.exit(1)}}).command("doctor","Find messages carrying two or more progress reactions (--fix repairs them)",(i)=>i.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:Ec,describe:"Max messages to scan"}).option("channel-id",{type:"string",describe:"Raw channel ID"}),async(i)=>{let c={channel:i.in,limit:i.limit};if(i.fix)c.fix=!0;if(i["channel-id"])c.channelId=i["channel-id"];let l=t(i);if(l)c.cookie=l;await G0(e(i),c)}).demandCommand(1,"Specify a todo subcommand (ls, set, flag, doctor)"),()=>{}).command("mytodo","Tasks carrying YOUR reactions (hasmy:) \u2014 the my-only half of `todo`",(r)=>r.option("cache",{type:"boolean",default:!0,describe:"Use ~/.config/slack-cli/cache.json for channel/user lookups (--no-cache to bypass)"}).middleware((i)=>{if(i.cache===!1)$c(!1)}).command(["ls","list"],"List tasks you have reacted to (hasmy: \u2014 read-only, one search per run)",(i)=>i.options(o),async(i)=>{await a(i,!0)}).demandCommand(1,"Specify a mytodo subcommand (ls)"),()=>{}).command("upload <target> <file..>","Upload one or more files to a channel or DM",(r)=>r.positional("target",{type:"string",demandOption:!0,describe:"#chan, @user, #chan:thread_ts, or permalink (a message permalink replies in its thread)"}).positional("file",{type:"string",array:!0,demandOption:!0,describe:"Path(s) to file(s)"}).option("title",{type:"string",describe:"Title (single file only)"}).option("comment",{type:"string",describe:"Initial comment (first file)"}).option("allow-url-adjacent",{type:"boolean",default:!1,describe:"Warn instead of refusing ambiguous bare URL boundaries"}).option("code",{type:"string",describe:"4-hex safety code to confirm upload"}).option("channel-id",{type:"string"}).option("user-id",{type:"string"}),async(r)=>{let i={target:r.target,filePaths:r.file};if(r.title)i.title=r.title;if(r.comment)i.comment=r.comment;if(r["allow-url-adjacent"])i.allowUrlAdjacent=!0;if(r.code)i.code=r.code;if(r["channel-id"])i.channelId=r["channel-id"];if(r["user-id"])i.userId=r["user-id"];let c=t(r);if(c)i.cookie=c;await Jk(e(r),i)}).command("files","File commands",(r)=>r.command(["ls","list"],"List files visible to you (files.list)",(i)=>i.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(i)=>{let c={limit:i.limit,format:i.json?"jsonl":i.format};if(i.type)c.types=i.type;if(i.channel)c.channel=i.channel;if(i.user)c.user=i.user;await Uk(e(i),t(i),c)}).demandCommand(1,"").showHelpOnFail(!0),()=>{}).command("lists","Slack Lists \u2014 read rows (lists <ref>), or create / add / set (gated, as the bot)",(r)=>r.command("create <name>","Create a Slack List (confirm-hash safety gate; bot token, lists:write)",(i)=>i.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(i)=>{try{let c={name:i.name,cols:i.col,todo:i.todo===!0};if(i.code!==void 0)c.code=i.code;await zk(c)}catch(c){console.error(he(c)),process.exit(1)}}).command("add <list> <text>","Add a row to a Slack List (confirm-hash safety gate; bot token)",(i)=>i.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(i)=>{try{let c={list:i.list,text:i.text,sets:i.set};if(i.code!==void 0)c.code=i.code;await Yk(c)}catch(c){console.error(he(c)),process.exit(1)}}).command("set <list> <row>","Update cells of a Slack List row; --done checks it off (confirm-hash safety gate; bot token)",(i)=>i.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(i)=>{try{let c={list:i.list,row:i.row,sets:i.set};if(i.done!==void 0)c.done=i.done;if(i.code!==void 0)c.code=i.code;await Gk(c)}catch(c){console.error(he(c)),process.exit(1)}}).command("share <list>","Grant users or channels access to a Slack List (confirm-hash safety gate; bot token)",(i)=>i.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(i)=>{try{let c={list:i.list,users:i.user,channels:i.channel,level:i.level};if(i.code!==void 0)c.code=i.code;await Xk(c)}catch(c){console.error(he(c)),process.exit(1)}}).command("$0 <ref>","Read a Slack List's rows (by list URL or F-id) \u2014 read-only",(i)=>i.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(i)=>{let c=i.json?"jsonl":i.format;try{let l=i.asBot===!0;await qk(l?"":e(i),l?void 0:t(i),i.ref,{limit:i.limit,format:c,asBot:l})}catch(l){console.error(he(l)),process.exit(1)}})).command("download <ref> [dest]","Download a file attachment (by file ID or file permalink) to disk",(r)=>r.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(r)=>{await Zk(e(r),t(r),r.ref,r.dest)}).command("dump","Bulk export channel history as markdown",(r)=>r.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(r)=>{await X0(e(r),r.days,r.limit,r.filter)}).command("todos","Slack's To-dos tab \u2014 your personal to-dos (requires xoxc desktop token). Not `slack todo` (reaction tasks)",(r)=>r.command(["$0","ls","list"],"List your To-dos, soonest due first",(i)=>i.option("filter",{type:"string",choices:[...wh],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(i)=>{if(!Number.isInteger(i.limit)||i.limit<1)console.error(`Error: --limit must be a whole number of at least 1 (got ${i.limit}).`),process.exit(2);await Q0(e(i),t(i),{filter:i.filter,limit:i.limit,json:i.json})}).command("add <target>","Add a message to your To-dos (two-step: preview, then --code)",(i)=>i.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(i)=>{let c=i.due===void 0?void 0:hg(i.due);await $o(e(i),t(i),i.target,{kind:"add",...c?{due:c}:{},saved:i.saved},i.code)}).command(["done <target>","complete <target>"],"Check a to-do off (--undo reopens it)",(i)=>i.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(i)=>{await $o(e(i),t(i),i.target,{kind:"done",undo:i.undo},i.code)}).command("edit <target>","Change a to-do's due date, or switch it between to-do and saved item",(i)=>i.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(i)=>{let c=i.due===void 0?void 0:i.due==="none"?0:hg(i.due),l=i.todo?!0:i.saved?!1:void 0;await $o(e(i),t(i),i.target,{kind:"edit",...c===void 0?{}:{due:c},...l===void 0?{}:{todo:l}},i.code)}).command(["rm <target>","remove <target>","delete <target>"],"Remove a message from your To-dos (the message stays)",(i)=>i.positional("target",{type:"string",demandOption:!0,describe:"Message permalink or #chan:<ts>"}).option("code",{type:"string",describe:"Confirmation code from the preview"}),async(i)=>{await $o(e(i),t(i),i.target,{kind:"rm"},i.code)})).command("drafts","Manage message drafts (requires xoxc desktop token)",(r)=>r.command(["$0","ls","list"],"List pending drafts",(i)=>i.option("all",{alias:"a",type:"boolean",default:!1,describe:"Include sent drafts"}),async(i)=>{await Z0(e(i),t(i),i.all)}).command(["new <channel> [text..]","save <channel> [text..]"],"Create a draft",(i)=>i.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(i)=>{let c=e(i),l=t(i),u=i.text.join(" ");if(!u)console.error("Usage: slack drafts new <#channel|@user> <text>"),process.exit(2);ze(u,i["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let d=await be(c,i.channel,l),f=await fh(c,d,u,l);console.log(`\u2713 Draft created (id: ${T(f.draft).id??"?"})`)}).command("get <id>","Show a draft",(i)=>i.positional("id",{type:"string",demandOption:!0}),async(i)=>{await sk(e(i),t(i),i.id)}).command(["edit <id> [text..]","update <id> [text..]"],"Edit a draft",(i)=>i.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(i)=>{let c=e(i),l=t(i),u=i.text.join(" ");if(!u)console.error("Usage: slack drafts edit <id> <new-text>"),process.exit(2);ze(u,i["allow-url-adjacent"],void 0,{sides:["after"],markdown:!1});let d=await zs(c,l),f=Y(d.drafts).map(T).find((m)=>String(m.id)===i.id);if(!f)console.error(`Draft not found: ${i.id}`),process.exit(1);let p=Oo(f),g=await je(c,l),h=ke(p,u,g?.userId??"");if(i.code!==h)Se(i.code,h,["--- Editing draft as -------------------------",Ee(g),"--- Current draft ----------------------------",...p.split(`
|
|
576
|
+
`).map((m)=>` ${m}`),"--- Replacing with ---------------------------",...u.split(`
|
|
577
|
+
`).map((m)=>` ${m}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);let b=await ph(c,i.id,Kc(f),u,l);console.log(`\u2713 Draft updated (id: ${T(b.draft).id??"?"})`)}).command(["delete <id>","rm <id>"],"Delete a draft",(i)=>i.positional("id",{type:"string",demandOption:!0}).option("code",{type:"string"}),async(i)=>{let c=e(i),l=t(i),u=await zs(c,l),d=Y(u.drafts).map(T).find((h)=>String(h.id)===i.id);if(!d)console.error(`Draft not found: ${i.id}`),process.exit(1);let f=Oo(d),p=await je(c,l),g=ke(i.id,f,p?.userId??"");if(i.code!==g)Se(i.code,g,["\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(p),` id: ${i.id}`,...f.split(`
|
|
578
|
+
`).map((h)=>` ${h}`),"--------------------------------\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"]);await mh(c,i.id,l),console.log(`\u2713 Draft deleted (id: ${i.id})`)})).command("auth","Authentication and workspace management",(r)=>r.command("token","Print the active token (or save one with --token)",(i)=>i.option("token",{type:"string",describe:"Token to save directly (non-interactive)"}).option("name",{type:"string",describe:"Workspace name (used with --token)"}),async(i)=>{if(i.token===void 0){console.log(ks(i.workspace));return}await bd({...i.token!==void 0?{token:i.token}:{},...i.name!==void 0?{name:i.name}:{}})}).command("env","Print active workspace credentials in dotenv format",()=>{},(i)=>{let c=ks(i.workspace),l=c.startsWith("xoxc-")?Ai(i.workspace):void 0,u=[["SLACK_TOKEN",c]];if(l)u.push(["SLACK_COOKIE",l]);let d=u.map(([f,p])=>{if(/[\r\n\0']/.test(p))throw Error(`Cannot export ${f}: unsupported characters in credential`);return`${f}='${p}'`});console.log(d.join(`
|
|
579
|
+
`))}).command("app","Create a new Slack app and obtain a token (guided wizard)",(i)=>i.option("bot",{type:"boolean",describe:"Create a bot token (xoxb-) instead of user (xoxp-)"}),async(i)=>{await wd({...i.bot!==void 0?{bot:i.bot}:{}})}).command("login","Log in: interactive wizard, or a source (chrome, firefox)",(i)=>i.command("chrome","Import workspaces from Chrome, grouped by account (all platforms)",(c)=>c.option("profile",{type:"string",alias:"p",describe:'Chrome profile email or dir (e.g. "you@example.com" or "Profile 3")'}),async(c)=>{await ra({...c.profile!==void 0?{profile:c.profile}:{}})}).command("firefox","Import the xoxd cookie from Firefox into a workspace",(c)=>c.option("workspace",{type:"string",alias:"w",describe:"Workspace name to update (default: active)"}),async(c)=>{await oa({...c.workspace!==void 0?{workspace:c.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(c)=>{await Rs({...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})}),async(i)=>{await Rs({...i.token!==void 0?{token:i.token}:{},...i.name!==void 0?{name:i.name}:{},yes:i.yes,fromDesktop:i.fromDesktop,fromChrome:i.fromChrome,fromFirefox:i.fromFirefox,fromAll:i.fromAll})}).command("tokens","Print the selected credentials as dotenv assignments",(i)=>i.option("workspace",{type:"string",alias:"w",describe:"Workspace name (default: active)"}),(i)=>Dd({...i.workspace!==void 0?{workspace:i.workspace}:{}})).command("save","Save the active profile token and cookie to an env file",(i)=>i.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)"}),(i)=>kd({envfile:i.envfile,...i.workspace!==void 0?{workspace:i.workspace}:{}})).command(["ls","status"],"Show auth status",()=>{},()=>{let i=Ci();if(i.length===0){console.log("No workspaces configured. Run: slack auth login");return}for(let{name:c,profile:l,current:u}of i)console.log(`${u?"* ":" "}${c} ${l.team} (${l.user}) ${l.url??""}`)}).command("use <name>","Switch active workspace",(i)=>i.positional("name",{type:"string",demandOption:!0}).option("g",{type:"boolean",default:!1,describe:"Write global lockfile (~/.slack-cli/workspace)"}),(i)=>{if(!i.g)P0(Ft(process.cwd(),".slack-cli"));Pu(i.name,i.g),console.log(`Switched to workspace "${i.name}" ${i.g?"globally":"locally"}`)}).command(["logout <name>","rm <name>","remove <name>"],"Remove a workspace",(i)=>i.positional("name",{type:"string",demandOption:!0}),(i)=>{vu(i.name),console.log(`Removed workspace "${i.name}"`)}).command(["cookie","chrome"],"Attach a Chrome xoxd cookie to a workspace (macOS/Linux/Windows). To import workspaces, use: slack auth login chrome",(i)=>i.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(i)=>{await yd({...i.workspace!==void 0?{workspace:i.workspace}:{},...i.profile!==void 0?{profile:i.profile}:{},yes:i.yes})}).command("firefox","Attach Firefox browser xoxd cookie to a workspace (all platforms)",(i)=>i.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(i)=>{await oa({...i.workspace!==void 0?{workspace:i.workspace}:{},yes:i.yes})}).command("$0",!1,()=>{},()=>{r.showHelp(),process.exit(0)})).command("relay","Set up / check the real-time relay for `slack stream` (a Cloudflare Worker)",(r)=>r.command("init [dir]","Scaffold a deployable relay Worker folder (local files only; prints a fresh RELAY_TOKEN and the next steps)",(i)=>i.positional("dir",{type:"string",default:ga,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"}),(i)=>{let c=Ud(i.dir,{force:i.force,...i.name!==void 0?{name:i.name}:{},...i["slack-term"]!==void 0?{slackTerm:i["slack-term"]}:{}});if(!c.ok){console.error(`slack relay init: ${c.error}`);for(let l of c.existing??[])console.error(` exists: ${l}`);process.exit(2)}console.log(Kd(c))}).command("health","GET /health on the relay (SLACK_RELAY_URL / SLACK_RELAY_TOKEN); exit 0 = ok",(i)=>i.option("url",{type:"string",describe:"Relay URL (default: $SLACK_RELAY_URL)"}).option("token",{type:"string",describe:"Relay token (default: $SLACK_RELAY_TOKEN)"}),async(i)=>{let c=await qd(i.url??process.env.SLACK_RELAY_URL,i.token??process.env.SLACK_RELAY_TOKEN);(c.code===0?console.log:console.error)(c.out),process.exit(c.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",(r)=>r.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)"}),async(r)=>{let i,c,l,u,d,f;try{i=new RegExp(r.grep,r["ignore-case"]?"i":""),l=Qt(r.interval)*1000,u=Qt(r["thread-window"]),d=Qt(r["thread-scan"]),f=r.since!==void 0?Qt(r.since):void 0,c=Qt(r.reconcile)*1000}catch(O){console.error(`slack stream: ${O instanceof Error?O.message:String(O)}`),process.exit(1)}let p=Ue(),g=r["as-user"]===!0||!p,h=g?e(r):p,b=g?t(r):void 0;if(!p&&r["as-user"]!==!0)console.error("slack stream: no bot token (SLACK_BOT_TOKEN) \u2014 streaming as the USER identity, which includes its DMs.");let m;try{m=await Pt(h,b)}catch(O){console.error(`slack stream: fatal: ${O instanceof Error?O.message:String(O)}`),process.exit(3)}let w=new Set([m.userId].filter(Boolean)),D=new Set([m.botId].filter(Boolean));if(g&&p)try{let O=await Pt(p);if(O.userId)w.add(O.userId);if(O.botId)D.add(O.botId)}catch{}let k;if(r["replies-to"]?.length){k=new Set;for(let O of r["replies-to"].map(String)){if(O==="self"){for(let j of[m.userId,m.botId])if(j)k.add(j);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(k.add(O),O.startsWith("B"))try{let{userId:j}=await Np(h,O,b);if(j)k.add(j)}catch(j){console.error(`slack stream: --replies-to ${O}: cannot resolve its bot user id (${j instanceof Error?j.message:String(j)}); threads where it shows as a user id are missed`)}}}let E;if(r.channel?.length)try{E=[];for(let O of r.channel)E.push(await be(h,String(O),b))}catch(O){console.error(`slack stream: --channel: ${O instanceof Error?O.message:String(O)}`),process.exit(1)}let A=yg("sha256").update(JSON.stringify([m.url,m.userId,i.source,i.flags,[...E??[]].sort(),...r["replies-to"]?.length?[[...r["replies-to"].map(String)].sort()]:[]])).digest("hex").slice(0,16),_=process.env.XDG_STATE_HOME||Ft(Lc(),".local","state"),S=r.state??Ft(_,"slack-term","stream",`${A}.json`);console.error(`slack stream: as ${g?"user":"bot"} @${m.user} (${m.userId}); state ${S}`);let I=process.env.SLACK_RELAY_URL,J=process.env.SLACK_RELAY_TOKEN,L=r.relay&&!g&&!r.once&&I&&J?{url:I,subscribe:Bd(I,J,void 0,{transport:Md(process.env.SLACK_RELAY_TRANSPORT)}),reconcileMs:c}:void 0;if(r.relay&&g&&I)console.error("slack stream: relay not used with --as-user (it only sees the bot's channels)");let v=!r.relay?"--no-relay":g?I?"--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",N=new AbortController;process.on("SIGINT",()=>N.abort()),process.on("SIGTERM",()=>N.abort()),Pp(0);let H=await Pd(Id(h,b),{grep:i,...k?{repliesTo:k}:{},...E?{channels:E}:{},selfUsers:w,selfBots:D,json:r.json,...r.inbox?{onMatch:(O,j)=>{try{let z=[h,b,process.env.SLACK_RELAY_TOKEN].filter((ce)=>!!ce),M=Xf({...O,...j?{files:j}:{}},void 0,new Date,z);if(M.length)console.error(`slack stream: delivered ${O.channel.id}:${O.ts} to ${M.length} inbox(es)`)}catch(z){console.error(`slack stream: inbox delivery failed: ${z instanceof Error?z.message:String(z)}`)}}}:{},once:r.once,...f!==void 0?{sinceSec:f}:{},intervalMs:l,threadWindowSec:u,threadScanSec:d,callsPerMin:r["calls-per-min"],...L?{}:{pollReason:v},statePath:S,teamUrl:m.url,identity:m.userId,signal:N.signal,...L?{relay:L}:{}});process.exit(H)}).command("tail [target]","Stream new messages in real time (like tail -f)",(r)=>r.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(r)=>{let i=e(r),c=t(r),l=new AbortController;process.on("SIGINT",()=>{l.abort(),process.exit(0)}),await Cd(i,r.target,{...r.since!==void 0?{since:r.since}:{},...r.thread!==void 0?{thread:r.thread}:{},...r["watch-thread"]!==void 0?{watchThread:r["watch-thread"]}:{},me:r.me,interval:r.interval,...r.timeout!==void 0?{timeout:r.timeout}:{},...r["exit-on-message"]===!0?{exitOnMessage:!0}:{},...c!==void 0?{cookie:c}:{},...r.rtm===!1?{noRtm:!0}:{}},l.signal)}).command("login",!1,(r)=>r.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(r)=>{await Rs({...r.token!==void 0?{token:r.token}:{},...r.name!==void 0?{name:r.name}:{},yes:r.yes,fromDesktop:r.fromDesktop,fromChrome:r.fromChrome,fromFirefox:r.fromFirefox,fromAll:r.fromAll})}).demandCommand(1,"Specify a command. Run with --help for usage.").strict().help().alias("help","h").parseAsync()}Qk().catch((e)=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});
|