gemi 0.178.0 → 0.179.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/auth/connections/ConnectionManager.d.ts +7 -0
- package/dist/auth/connections/ConnectionManager.d.ts.map +1 -1
- package/dist/auth/connections/InstagramPublisher.d.ts +186 -0
- package/dist/auth/connections/InstagramPublisher.d.ts.map +1 -0
- package/dist/auth/oauth/instagram.d.ts +6 -0
- package/dist/auth/oauth/instagram.d.ts.map +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-bhaae60h.js → chunk-47cjayhh.js} +4 -4
- package/dist/{chunk-bhaae60h.js.map → chunk-47cjayhh.js.map} +3 -3
- package/dist/{chunk-a2r94jbz.js → chunk-4hj0q8fs.js} +2 -2
- package/dist/{chunk-a2r94jbz.js.map → chunk-4hj0q8fs.js.map} +1 -1
- package/dist/{chunk-s1x12f0b.js → chunk-51yv7x03.js} +2 -2
- package/dist/{chunk-s1x12f0b.js.map → chunk-51yv7x03.js.map} +1 -1
- package/dist/{chunk-ygdmm1h4.js → chunk-520hnb9j.js} +2 -2
- package/dist/{chunk-ygdmm1h4.js.map → chunk-520hnb9j.js.map} +1 -1
- package/dist/{chunk-hthdwnfr.js → chunk-5cf61bb5.js} +2 -2
- package/dist/{chunk-hthdwnfr.js.map → chunk-5cf61bb5.js.map} +1 -1
- package/dist/{chunk-pv3152gj.js → chunk-5db4v8gv.js} +1 -1
- package/dist/{chunk-10ap3vpj.js → chunk-5v07y14d.js} +2 -2
- package/dist/{chunk-10ap3vpj.js.map → chunk-5v07y14d.js.map} +1 -1
- package/dist/{chunk-wap1efbn.js → chunk-66xyz4m3.js} +4 -4
- package/dist/{chunk-wap1efbn.js.map → chunk-66xyz4m3.js.map} +1 -1
- package/dist/{chunk-yhdwr77h.js → chunk-6nrd3djs.js} +2 -2
- package/dist/{chunk-yhdwr77h.js.map → chunk-6nrd3djs.js.map} +1 -1
- package/dist/{chunk-x9h1hchj.js → chunk-6t9zjhm6.js} +2 -2
- package/dist/{chunk-x9h1hchj.js.map → chunk-6t9zjhm6.js.map} +1 -1
- package/dist/{chunk-mg9m53kk.js → chunk-6vdvhj14.js} +2 -2
- package/dist/{chunk-mg9m53kk.js.map → chunk-6vdvhj14.js.map} +1 -1
- package/dist/{chunk-p779zv1n.js → chunk-6wwk0psy.js} +2 -2
- package/dist/{chunk-p779zv1n.js.map → chunk-6wwk0psy.js.map} +1 -1
- package/dist/{chunk-n8egkp1k.js → chunk-7jxf0kys.js} +2 -2
- package/dist/{chunk-n8egkp1k.js.map → chunk-7jxf0kys.js.map} +1 -1
- package/dist/{chunk-c6ms23fk.js → chunk-8v95cjc5.js} +2 -2
- package/dist/{chunk-c6ms23fk.js.map → chunk-8v95cjc5.js.map} +1 -1
- package/dist/{chunk-hmvbj1rq.js → chunk-8zwm5n7d.js} +2 -2
- package/dist/{chunk-hmvbj1rq.js.map → chunk-8zwm5n7d.js.map} +1 -1
- package/dist/{chunk-gr4vynwd.js → chunk-93s13x3v.js} +2 -2
- package/dist/{chunk-gr4vynwd.js.map → chunk-93s13x3v.js.map} +1 -1
- package/dist/{chunk-nwdtdq2k.js → chunk-9522w4e4.js} +2 -2
- package/dist/{chunk-nwdtdq2k.js.map → chunk-9522w4e4.js.map} +1 -1
- package/dist/{chunk-5yjseh8g.js → chunk-9mcweetq.js} +2 -2
- package/dist/{chunk-5yjseh8g.js.map → chunk-9mcweetq.js.map} +1 -1
- package/dist/{chunk-3szc00gq.js → chunk-b53n5696.js} +2 -2
- package/dist/{chunk-3szc00gq.js.map → chunk-b53n5696.js.map} +1 -1
- package/dist/{chunk-eq252sbg.js → chunk-bm2zz2j1.js} +2 -2
- package/dist/{chunk-eq252sbg.js.map → chunk-bm2zz2j1.js.map} +1 -1
- package/dist/{chunk-gr625kyj.js → chunk-bptarxbq.js} +2 -2
- package/dist/{chunk-gr625kyj.js.map → chunk-bptarxbq.js.map} +1 -1
- package/dist/{chunk-5d7qhnt9.js → chunk-c0qq5t8a.js} +3 -3
- package/dist/{chunk-5d7qhnt9.js.map → chunk-c0qq5t8a.js.map} +1 -1
- package/dist/{chunk-7e1fgzcv.js → chunk-cv496s8h.js} +2 -2
- package/dist/{chunk-7e1fgzcv.js.map → chunk-cv496s8h.js.map} +1 -1
- package/dist/{chunk-jj4w6ce5.js → chunk-czzyrw7d.js} +2 -2
- package/dist/{chunk-jj4w6ce5.js.map → chunk-czzyrw7d.js.map} +1 -1
- package/dist/{chunk-a2br22hp.js → chunk-dp5ha6qy.js} +2 -2
- package/dist/{chunk-a2br22hp.js.map → chunk-dp5ha6qy.js.map} +1 -1
- package/dist/{chunk-8bnmvhrv.js → chunk-e14fgtk1.js} +2 -2
- package/dist/{chunk-8bnmvhrv.js.map → chunk-e14fgtk1.js.map} +1 -1
- package/dist/{chunk-tpx30rbj.js → chunk-e7hb47yy.js} +2 -2
- package/dist/{chunk-tpx30rbj.js.map → chunk-e7hb47yy.js.map} +1 -1
- package/dist/{chunk-9tt0bb0p.js → chunk-f5mhc5eh.js} +2 -2
- package/dist/{chunk-9tt0bb0p.js.map → chunk-f5mhc5eh.js.map} +1 -1
- package/dist/{chunk-5zfwvabd.js → chunk-gjb7cfr4.js} +2 -2
- package/dist/{chunk-5zfwvabd.js.map → chunk-gjb7cfr4.js.map} +1 -1
- package/dist/{chunk-rhqcv3te.js → chunk-hbjatkm9.js} +2 -2
- package/dist/{chunk-rhqcv3te.js.map → chunk-hbjatkm9.js.map} +1 -1
- package/dist/{chunk-bmzznzhz.js → chunk-hm1xy515.js} +3 -3
- package/dist/{chunk-bmzznzhz.js.map → chunk-hm1xy515.js.map} +1 -1
- package/dist/{chunk-y13dsype.js → chunk-ht0atvyc.js} +3 -3
- package/dist/{chunk-y13dsype.js.map → chunk-ht0atvyc.js.map} +1 -1
- package/dist/{chunk-q21wxx5y.js → chunk-jpq74abh.js} +1 -1
- package/dist/{chunk-96gnm8zb.js → chunk-jwvwve00.js} +2 -2
- package/dist/{chunk-96gnm8zb.js.map → chunk-jwvwve00.js.map} +1 -1
- package/dist/{chunk-hkjfyhv4.js → chunk-ks99tx7f.js} +2 -2
- package/dist/{chunk-hkjfyhv4.js.map → chunk-ks99tx7f.js.map} +1 -1
- package/dist/{chunk-344f6c5q.js → chunk-mby1wdny.js} +2 -2
- package/dist/{chunk-344f6c5q.js.map → chunk-mby1wdny.js.map} +1 -1
- package/dist/{chunk-tdbm67bb.js → chunk-me14hs9k.js} +2 -2
- package/dist/{chunk-tdbm67bb.js.map → chunk-me14hs9k.js.map} +1 -1
- package/dist/{chunk-cmjmy3gt.js → chunk-mpv431ga.js} +1 -1
- package/dist/{chunk-yszn7ses.js → chunk-nv2ecda9.js} +2 -2
- package/dist/{chunk-yszn7ses.js.map → chunk-nv2ecda9.js.map} +1 -1
- package/dist/{chunk-sq2ccgxy.js → chunk-nwg70wza.js} +3 -3
- package/dist/{chunk-sq2ccgxy.js.map → chunk-nwg70wza.js.map} +1 -1
- package/dist/{chunk-0mye000w.js → chunk-pw6ssy3a.js} +2 -2
- package/dist/{chunk-64m4fmf0.js.map → chunk-pw6ssy3a.js.map} +1 -1
- package/dist/{chunk-e4f6xw7b.js → chunk-q30ryk1a.js} +2 -2
- package/dist/{chunk-e4f6xw7b.js.map → chunk-q30ryk1a.js.map} +1 -1
- package/dist/{chunk-cnnmb8p3.js → chunk-q3g4xs1z.js} +2 -2
- package/dist/{chunk-cnnmb8p3.js.map → chunk-q3g4xs1z.js.map} +1 -1
- package/dist/{chunk-h2yyyzsv.js → chunk-r36kq8x1.js} +3 -3
- package/dist/{chunk-h2yyyzsv.js.map → chunk-r36kq8x1.js.map} +1 -1
- package/dist/{chunk-h3xpvksc.js → chunk-r7j4c5t2.js} +2 -2
- package/dist/{chunk-h3xpvksc.js.map → chunk-r7j4c5t2.js.map} +1 -1
- package/dist/{chunk-w1y6x2rm.js → chunk-rv0r5fde.js} +2 -2
- package/dist/{chunk-w1y6x2rm.js.map → chunk-rv0r5fde.js.map} +1 -1
- package/dist/{chunk-8ym912fj.js → chunk-s0m717j8.js} +3 -3
- package/dist/{chunk-8ym912fj.js.map → chunk-s0m717j8.js.map} +1 -1
- package/dist/{chunk-9nks1y2h.js → chunk-s208599z.js} +2 -2
- package/dist/{chunk-9nks1y2h.js.map → chunk-s208599z.js.map} +1 -1
- package/dist/{chunk-brcn3h9b.js → chunk-sen7c0e6.js} +3 -3
- package/dist/{chunk-brcn3h9b.js.map → chunk-sen7c0e6.js.map} +1 -1
- package/dist/{chunk-fbbqy4af.js → chunk-sr1gv50s.js} +2 -2
- package/dist/{chunk-fbbqy4af.js.map → chunk-sr1gv50s.js.map} +1 -1
- package/dist/{chunk-640mjh9h.js → chunk-ssmq5r41.js} +2 -2
- package/dist/{chunk-640mjh9h.js.map → chunk-ssmq5r41.js.map} +1 -1
- package/dist/{chunk-q5j1bwny.js → chunk-sx6jmyaf.js} +1 -1
- package/dist/{chunk-mkb9nt5n.js → chunk-tefb1nz7.js} +2 -2
- package/dist/{chunk-mkb9nt5n.js.map → chunk-tefb1nz7.js.map} +1 -1
- package/dist/{chunk-j6sbfa2q.js → chunk-tjmw2z5z.js} +2 -2
- package/dist/{chunk-j6sbfa2q.js.map → chunk-tjmw2z5z.js.map} +1 -1
- package/dist/{chunk-r4ewwmcr.js → chunk-tv13vbcm.js} +2 -2
- package/dist/{chunk-r4ewwmcr.js.map → chunk-tv13vbcm.js.map} +1 -1
- package/dist/{chunk-2cw1et3n.js → chunk-v8qzdvpj.js} +2 -2
- package/dist/{chunk-2cw1et3n.js.map → chunk-v8qzdvpj.js.map} +1 -1
- package/dist/{chunk-bcdst4fd.js → chunk-vhk6735r.js} +2 -2
- package/dist/{chunk-bcdst4fd.js.map → chunk-vhk6735r.js.map} +1 -1
- package/dist/chunk-vq2a7qd8.js +5 -0
- package/dist/{chunk-sz8w3kwt.js.map → chunk-vq2a7qd8.js.map} +1 -1
- package/dist/{chunk-q21p7bq9.js → chunk-vv1na1vj.js} +1 -1
- package/dist/{chunk-xvaan2fe.js → chunk-w6br58a9.js} +4 -4
- package/dist/{chunk-xvaan2fe.js.map → chunk-w6br58a9.js.map} +1 -1
- package/dist/{chunk-zn6j65pg.js → chunk-wjkcqe8w.js} +2 -2
- package/dist/{chunk-zn6j65pg.js.map → chunk-wjkcqe8w.js.map} +1 -1
- package/dist/{chunk-z0q126b1.js → chunk-wtjfjh0x.js} +2 -2
- package/dist/{chunk-z0q126b1.js.map → chunk-wtjfjh0x.js.map} +1 -1
- package/dist/{chunk-fsesx3mr.js → chunk-xf8f9tbf.js} +2 -2
- package/dist/{chunk-fsesx3mr.js.map → chunk-xf8f9tbf.js.map} +1 -1
- package/dist/{chunk-a4s0kf20.js → chunk-xgmc7cp5.js} +2 -2
- package/dist/{chunk-a4s0kf20.js.map → chunk-xgmc7cp5.js.map} +1 -1
- package/dist/{chunk-nbmzs80j.js → chunk-xvaryyd0.js} +2 -2
- package/dist/{chunk-nbmzs80j.js.map → chunk-xvaryyd0.js.map} +1 -1
- package/dist/{chunk-64m4fmf0.js → chunk-xzzdywf6.js} +2 -2
- package/dist/{chunk-0mye000w.js.map → chunk-xzzdywf6.js.map} +1 -1
- package/dist/{chunk-aat9zhrj.js → chunk-y3pnwpvp.js} +3 -3
- package/dist/{chunk-aat9zhrj.js.map → chunk-y3pnwpvp.js.map} +1 -1
- package/dist/{chunk-h9kgvg25.js → chunk-yef8dvmg.js} +2 -2
- package/dist/{chunk-h9kgvg25.js.map → chunk-yef8dvmg.js.map} +1 -1
- package/dist/{chunk-kx3etqsr.js → chunk-yx26j5vk.js} +2 -2
- package/dist/{chunk-kx3etqsr.js.map → chunk-yx26j5vk.js.map} +1 -1
- package/dist/{chunk-v9g2np6k.js → chunk-z8mq4g46.js} +2 -2
- package/dist/{chunk-v9g2np6k.js.map → chunk-z8mq4g46.js.map} +1 -1
- package/dist/{chunk-zczvbygf.js → chunk-zm4fdsq5.js} +2 -2
- package/dist/{chunk-zczvbygf.js.map → chunk-zm4fdsq5.js.map} +1 -1
- package/dist/{chunk-ay60f8dy.js → chunk-znrk326r.js} +1 -1
- package/dist/{chunk-574s5sgz.js → chunk-zpshgset.js} +2 -2
- package/dist/{chunk-574s5sgz.js.map → chunk-zpshgset.js.map} +1 -1
- package/dist/{chunk-nfx1p5z2.js → chunk-zrrpab1x.js} +3 -3
- package/dist/{chunk-nfx1p5z2.js.map → chunk-zrrpab1x.js.map} +1 -1
- package/dist/{chunk-8tyxtp36.js → chunk-zx5tp1c6.js} +2 -2
- package/dist/{chunk-8tyxtp36.js.map → chunk-zx5tp1c6.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.d.ts +2 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +13 -13
- package/dist/services/index.js.map +5 -4
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-sz8w3kwt.js +0 -5
- /package/dist/{chunk-pv3152gj.js.map → chunk-5db4v8gv.js.map} +0 -0
- /package/dist/{chunk-q21wxx5y.js.map → chunk-jpq74abh.js.map} +0 -0
- /package/dist/{chunk-cmjmy3gt.js.map → chunk-mpv431ga.js.map} +0 -0
- /package/dist/{chunk-q5j1bwny.js.map → chunk-sx6jmyaf.js.map} +0 -0
- /package/dist/{chunk-q21p7bq9.js.map → chunk-vv1na1vj.js.map} +0 -0
- /package/dist/{chunk-ay60f8dy.js.map → chunk-znrk326r.js.map} +0 -0
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{db as E8}from"../chunk-8m9kgynj.js";import{Ab as H8,Bb as U8,Cb as O8,Db as S8,Eb as R8,Fb as T4,Gb as X6,Hb as C,Ib as _8,Jb as f8,Kb as C8,Lb as k8,Mb as b8,Nb as T8,Ob as P8,Pb as V8,Qb as I8,Rb as v8,Sb as q8,Tb as w8,Ub as y8,Vb as A8,Wb as h8,Xb as g8,eb as gZ,fb as EZ,gb as mZ,hb as cZ,ib as uZ,jb as f4,kb as pZ,lb as O4,mb as S4,nb as q1,ob as dZ,pb as lZ,qb as X8,ub as B8,vb as j8,wb as M8,xb as L8,yb as F8,zb as D8}from"../chunk-e4f6xw7b.js";import{_b as k4}from"../chunk-s1x12f0b.js";import{Ad as rZ,Bd as eZ,Cd as W8,Dd as Z8,Ed as $8,Fd as J8,Gd as Q8,Hd as Y8,Id as K8,Jd as G8,Kd as z8,vd as nZ,wd as iZ,xd as sZ,yd as oZ,zd as aZ}from"../chunk-w1y6x2rm.js";import{Ld as tZ}from"../chunk-9aj6eavs.js";import{$d as AZ,Md as SZ,Nd as RZ,Od as _Z,Pd as fZ,Qd as CZ,Rd as kZ,Sd as bZ,Td as TZ,Ud as PZ,Vd as VZ,Wd as IZ,Xd as vZ,Yd as qZ,Zd as wZ,_d as yZ,ee as hZ}from"../chunk-h3xpvksc.js";import{fe as N8,ge as x8}from"../chunk-n8egkp1k.js";import"../chunk-zqptpk90.js";import{$f as t5,Ae as B4,Af as I5,Be as c0,Bf as v5,Ce as j4,De as M4,Df as q5,Dg as MZ,Ef as z6,Ff as w5,He as mW,Hg as LZ,Ie as cW,Je as uW,Jf as y5,Ke as pW,Kf as A5,Le as dW,Lf as g5,Me as lW,Mg as w1,Ne as nW,Oe as iW,Of as E5,Pe as sW,Pf as m5,Qe as w0,Qf as c5,Re as oW,Rf as u5,Se as aW,Te as tW,Tf as p5,Ue as rW,Uf as d5,Ve as eW,Vf as l5,Wf as n5,Xf as i5,Xg as NZ,Yf as s5,Yg as xZ,Zf as o5,_f as a5,ag as r5,fg as k,gg as i,hg as e5,if as G5,ig as WZ,jf as z5,jg as ZZ,kf as X5,kg as $Z,lf as B5,lg as JZ,mf as j5,nf as M5,ng as QZ,og as YZ,pg as KZ,qe as Z6,qg as GZ,re as AW,rg as zZ,se as hW,te as gW,tf as f5,uf as C5,ug as XZ,ve as EW,vf as k5,vg as BZ,wf as b5,wg as jZ,xf as T5,yf as P5,ze as $6,zf as V5}from"../chunk-wap1efbn.js";import"../chunk-nwdtdq2k.js";import"../chunk-v9g2np6k.js";import{Hi as Q5,Ii as Y5,Ki as K5,Mi as P1,Qh as X4,Rh as K4,Sh as M1,di as U4,gi as t,ii as d,mi as G4,ni as L1,oi as T1,pi as W5,qi as Z5,ri as $5,si as J5}from"../chunk-5d7qhnt9.js";import"../chunk-96gnm8zb.js";import{Wi as r}from"../chunk-hmvbj1rq.js";import{cj as U5,dj as O5,ej as b1,fj as S5,gj as v0,hj as R5,ij as _5}from"../chunk-bhaae60h.js";import{oj as F5,pj as D5,qj as H5}from"../chunk-8ym912fj.js";import"../chunk-344f6c5q.js";import{Zj as h5}from"../chunk-9nks1y2h.js";import{$j as L5,ak as N5,bk as x5}from"../chunk-c6ms23fk.js";import"../chunk-cnnmb8p3.js";import"../chunk-sq2ccgxy.js";import"../chunk-x9h1hchj.js";import"../chunk-a2br22hp.js";import{Tk as FZ,Uk as DZ,Vk as HZ,Wk as UZ,Yk as OZ}from"../chunk-aat9zhrj.js";import"../chunk-gr4vynwd.js";import{gl as w}from"../chunk-h2yyyzsv.js";import"../chunk-5yjseh8g.js";import"../chunk-574s5sgz.js";import"../chunk-zczvbygf.js";import"../chunk-a2r94jbz.js";import"../chunk-tpx30rbj.js";import{Hl as A0}from"../chunk-0mye000w.js";import{Buffer as y0}from"buffer";class h0 extends L1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-xvaan2fe.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket??Y,J=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);J=J||void 0;let K=$ instanceof y0?$:$ instanceof Blob||$ instanceof File?y0.from(await $.arrayBuffer()):"",{sdk:G,client:X}=await this.connect();return Z?.throwIfAborted(),await X.send(new G.PutObjectCommand({Bucket:Y,Key:Q,Body:K,ContentType:J}),{abortSignal:Z}),Q}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:J,client:Q}=await this.connect();try{await Q.send(new J.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(Y){if(Y?.name==="NoSuchKey"||Y?.$metadata?.httpStatusCode===404)return;throw Y}}async*pages(W,{bucket:Z,signal:$}){let{sdk:J,client:Q}=await this.connect(),Y;do{$?.throwIfAborted();let K=await Q.send(new J.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:Y}),{abortSignal:$});yield(K.Contents??[]).map((G)=>({name:G.Key,size:G.Size??0,lastModified:G.LastModified??new Date(0)})),Y=K.IsTruncated?K.NextContinuationToken:void 0}while(Y)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){G4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect(),Y=0;for await(let K of this.pages(W,{...Z,bucket:$})){if(K.length===0)continue;Z.signal?.throwIfAborted();let X=(await Q.send(new J.DeleteObjectsCommand({Bucket:$,Delete:{Objects:K.map((z)=>({Key:z.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(X.length>0){let z=X[0];throw Error(`S3 could not delete ${X.length} object(s) under "${W}", e.g. "${z.Key}": ${z.Code??"unknown"} ${z.Message??""}`.trim())}Y+=K.length}return Y}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,J;if(typeof W==="string")J=W;else $=W.bucket??$,J=W.name;if(!J)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();Z?.throwIfAborted();let K=await Y.send(new Q.GetObjectCommand({Bucket:$,Key:J}),{abortSignal:Z}),G=T1(K.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(G,{headers:{"Content-Type":K.ContentType,"Content-Length":K.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":K.LastModified?.toUTCString()||"",ETag:K.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:J,range:Q=null}=Z;if(!J)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect(),G;try{G=await K.send(new Y.GetObjectCommand({Bucket:$,Key:J,Range:Q?K4(Q):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new t(await this.size({name:J,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new d(J);throw j}let X=M1(G.ContentRange),z=Boolean(X)&&G.$metadata?.httpStatusCode===206,B=X?.total??G.ContentLength??0;return{body:G.Body.transformToWebStream(),start:X?.start??0,end:X?.end??B-1,total:B,partial:z,type:G.ContentType??"application/octet-stream",etag:G.ETag||void 0,lastModified:G.LastModified,name:J}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect();try{return(await Q.send(new J.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(Y){if(Y?.name==="NotFound"||Y?.$metadata?.httpStatusCode===404)throw new d(Z);throw Y}}}import{Buffer as g0}from"buffer";import{Readable as s6}from"stream";function z4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function o6(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class E0 extends L1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket,J=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let K=$ instanceof g0?$:g0.from(await $.arrayBuffer()),G=await this.blob(Q,Y);return Z?.throwIfAborted(),await G.uploadData(K,{blobHTTPHeaders:J?{blobContentType:J}:void 0,abortSignal:Z}),Q}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let J=Z??this.config.container??process.env.BUCKET_NAME;if(!J)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let Y=(await this.serviceClient()).getContainerClient(J);for await(let K of Y.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:K.name,size:K.properties?.contentLength??0,lastModified:K.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,J=(await this.serviceClient()).getContainerClient(Z),Q=[];for await(let Y of J.listBlobsFlat({prefix:W}))Q.push(Y.name);return Q}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:J,range:Q=null}=W,Y=await this.blob($,J);Z?.throwIfAborted();let K,G,X=Q?.kind==="suffix"||Q?.kind==="offset"&&Q.end===null&&Q.start===0;if(Q&&X){let H=await this.size({name:$,bucket:J}),p=X4(Q,H);if(!p)throw new t(H);K=p.start,G=p.length}else if(Q?.kind==="offset")K=Q.start,G=Q.end===null?void 0:Q.end-Q.start+1;let z;try{z=await Y.download(K,G,Z?{abortSignal:Z}:void 0)}catch(H){if(o6(H))throw new t(await this.size({name:$,bucket:J}));if(z4(H))throw new d($);throw H}let B=M1(z.contentRange),j=Boolean(B),x=B?.total??z.contentLength??0,O=await a6(z);if(O instanceof ReadableStream)O=T1(O,Z);return Z?.throwIfAborted(),{body:O,start:B?.start??0,end:B?.end??x-1,total:x,partial:j,type:z.contentType??"application/octet-stream",etag:z.etag||void 0,lastModified:z.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{return(await J.getProperties()).contentLength??0}catch(Q){if(z4(Q))throw new d(Z);throw Q}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{await J.delete()}catch(Q){if(z4(Q))return;throw Q}}}async function a6(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return s6.toWeb(W.readableStreamBody);return null}function t6(W){return W}class L4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class V1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var m0=1000,r6=60000,e6=`
|
|
2
|
+
import{db as M9}from"../chunk-8m9kgynj.js";import{Ab as n8,Bb as i8,Cb as s8,Db as o8,Eb as a8,Fb as w4,Gb as x6,Hb as T,Ib as t8,Jb as r8,Kb as e8,Lb as W9,Mb as Z9,Nb as $9,Ob as J9,Pb as Q9,Qb as Y9,Rb as K9,Sb as z9,Tb as G9,Ub as X9,Vb as B9,Wb as j9,Xb as F9,eb as F8,fb as M8,gb as L8,hb as N8,ib as D8,jb as P4,kb as H8,lb as f4,mb as C4,nb as h1,ob as x8,pb as U8,qb as h8,ub as g8,vb as E8,wb as m8,xb as c8,yb as d8,zb as l8}from"../chunk-q30ryk1a.js";import{_b as q4}from"../chunk-51yv7x03.js";import{Ad as C8,Bd as V8,Cd as T8,Dd as P8,Ed as b8,Fd as q8,Gd as v8,Hd as w8,Id as I8,Jd as y8,Kd as A8,vd as O8,wd as S8,xd as R8,yd as _8,zd as k8}from"../chunk-rv0r5fde.js";import{Ld as f8}from"../chunk-9aj6eavs.js";import{$d as B8,Md as oZ,Nd as aZ,Od as tZ,Pd as rZ,Qd as eZ,Rd as W8,Sd as Z8,Td as $8,Ud as J8,Vd as Q8,Wd as Y8,Xd as K8,Yd as z8,Zd as G8,_d as X8,ee as j8}from"../chunk-r7j4c5t2.js";import{fe as u8,ge as p8}from"../chunk-7jxf0kys.js";import"../chunk-zqptpk90.js";import{$f as fZ,Ae as N4,Af as YZ,Be as a0,Bf as KZ,Ce as D4,De as H4,Df as zZ,Dg as mZ,Ef as H6,Ff as GZ,He as L5,Hg as cZ,Ie as N5,Je as D5,Jf as XZ,Ke as H5,Kf as BZ,Le as x5,Lf as FZ,Me as U5,Mg as g1,Ne as O5,Oe as S5,Of as MZ,Pe as R5,Pf as LZ,Qe as p0,Qf as NZ,Re as _5,Rf as DZ,Se as k5,Te as f5,Tf as HZ,Ue as C5,Uf as xZ,Ve as V5,Vf as UZ,Wf as OZ,Xf as SZ,Xg as uZ,Yf as RZ,Yg as pZ,Zf as _Z,_f as kZ,ag as CZ,fg as P,gg as a,hg as VZ,if as y5,ig as TZ,jf as A5,jg as PZ,kf as h5,kg as bZ,lf as g5,lg as qZ,mf as E5,nf as m5,ng as vZ,og as wZ,pg as IZ,qe as B6,qg as yZ,re as B5,rg as AZ,se as j5,te as F5,tf as r5,uf as e5,ug as hZ,ve as M5,vf as WZ,vg as gZ,wf as ZZ,wg as EZ,xf as $Z,yf as JZ,ze as j6,zf as QZ}from"../chunk-66xyz4m3.js";import"../chunk-9522w4e4.js";import"../chunk-z8mq4g46.js";import{Ei as KW,Fi as zW,Ii as v5,Ji as w5,Li as I5,Ni as w1,Qh as L4,Rh as j4,Sh as N1,di as k4,gi as W1,ii as i,mi as F4,ni as D1,oi as v1,pi as T5,qi as P5,ri as b5,si as q5}from"../chunk-c0qq5t8a.js";import"../chunk-jwvwve00.js";import{Xi as Z1}from"../chunk-8zwm5n7d.js";import{dj as i5,ej as s5,fj as b1,gj as o5,hj as g0,ij as a5,jj as t5}from"../chunk-47cjayhh.js";import{pj as d5,qj as l5,rj as n5}from"../chunk-s0m717j8.js";import"../chunk-mby1wdny.js";import{_j as jZ}from"../chunk-s208599z.js";import{ak as c5,bk as u5,ck as p5}from"../chunk-8v95cjc5.js";import"../chunk-q3g4xs1z.js";import"../chunk-nwg70wza.js";import"../chunk-6t9zjhm6.js";import"../chunk-dp5ha6qy.js";import{Uk as dZ,Vk as lZ,Wk as nZ,Xk as iZ,Zk as sZ}from"../chunk-y3pnwpvp.js";import"../chunk-93s13x3v.js";import{hl as h}from"../chunk-r36kq8x1.js";import"../chunk-9mcweetq.js";import"../chunk-zpshgset.js";import"../chunk-zm4fdsq5.js";import"../chunk-4hj0q8fs.js";import"../chunk-e7hb47yy.js";import{Il as l0}from"../chunk-pw6ssy3a.js";import{Buffer as d0}from"buffer";class n0 extends D1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-w6br58a9.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket??Y,J=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);J=J||void 0;let K=$ instanceof d0?$:$ instanceof Blob||$ instanceof File?d0.from(await $.arrayBuffer()):"",{sdk:z,client:X}=await this.connect();return Z?.throwIfAborted(),await X.send(new z.PutObjectCommand({Bucket:Y,Key:Q,Body:K,ContentType:J}),{abortSignal:Z}),Q}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:J,client:Q}=await this.connect();try{await Q.send(new J.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(Y){if(Y?.name==="NoSuchKey"||Y?.$metadata?.httpStatusCode===404)return;throw Y}}async*pages(W,{bucket:Z,signal:$}){let{sdk:J,client:Q}=await this.connect(),Y;do{$?.throwIfAborted();let K=await Q.send(new J.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:Y}),{abortSignal:$});yield(K.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),Y=K.IsTruncated?K.NextContinuationToken:void 0}while(Y)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){F4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect(),Y=0;for await(let K of this.pages(W,{...Z,bucket:$})){if(K.length===0)continue;Z.signal?.throwIfAborted();let X=(await Q.send(new J.DeleteObjectsCommand({Bucket:$,Delete:{Objects:K.map((G)=>({Key:G.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(X.length>0){let G=X[0];throw Error(`S3 could not delete ${X.length} object(s) under "${W}", e.g. "${G.Key}": ${G.Code??"unknown"} ${G.Message??""}`.trim())}Y+=K.length}return Y}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,J;if(typeof W==="string")J=W;else $=W.bucket??$,J=W.name;if(!J)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();Z?.throwIfAborted();let K=await Y.send(new Q.GetObjectCommand({Bucket:$,Key:J}),{abortSignal:Z}),z=v1(K.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":K.ContentType,"Content-Length":K.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":K.LastModified?.toUTCString()||"",ETag:K.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:J,range:Q=null}=Z;if(!J)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect(),z;try{z=await K.send(new Y.GetObjectCommand({Bucket:$,Key:J,Range:Q?j4(Q):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new W1(await this.size({name:J,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new i(J);throw j}let X=N1(z.ContentRange),G=Boolean(X)&&z.$metadata?.httpStatusCode===206,B=X?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:X?.start??0,end:X?.end??B-1,total:B,partial:G,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:J}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect();try{return(await Q.send(new J.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(Y){if(Y?.name==="NotFound"||Y?.$metadata?.httpStatusCode===404)throw new i(Z);throw Y}}}import{Buffer as i0}from"buffer";import{Readable as BW}from"stream";function M4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function jW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class s0 extends D1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket,J=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let K=$ instanceof i0?$:i0.from(await $.arrayBuffer()),z=await this.blob(Q,Y);return Z?.throwIfAborted(),await z.uploadData(K,{blobHTTPHeaders:J?{blobContentType:J}:void 0,abortSignal:Z}),Q}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let J=Z??this.config.container??process.env.BUCKET_NAME;if(!J)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let Y=(await this.serviceClient()).getContainerClient(J);for await(let K of Y.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:K.name,size:K.properties?.contentLength??0,lastModified:K.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,J=(await this.serviceClient()).getContainerClient(Z),Q=[];for await(let Y of J.listBlobsFlat({prefix:W}))Q.push(Y.name);return Q}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:J,range:Q=null}=W,Y=await this.blob($,J);Z?.throwIfAborted();let K,z,X=Q?.kind==="suffix"||Q?.kind==="offset"&&Q.end===null&&Q.start===0;if(Q&&X){let U=await this.size({name:$,bucket:J}),n=L4(Q,U);if(!n)throw new W1(U);K=n.start,z=n.length}else if(Q?.kind==="offset")K=Q.start,z=Q.end===null?void 0:Q.end-Q.start+1;let G;try{G=await Y.download(K,z,Z?{abortSignal:Z}:void 0)}catch(U){if(jW(U))throw new W1(await this.size({name:$,bucket:J}));if(M4(U))throw new i($);throw U}let B=N1(G.contentRange),j=Boolean(B),N=B?.total??G.contentLength??0,S=await FW(G);if(S instanceof ReadableStream)S=v1(S,Z);return Z?.throwIfAborted(),{body:S,start:B?.start??0,end:B?.end??N-1,total:N,partial:j,type:G.contentType??"application/octet-stream",etag:G.etag||void 0,lastModified:G.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{return(await J.getProperties()).contentLength??0}catch(Q){if(M4(Q))throw new i(Z);throw Q}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{await J.delete()}catch(Q){if(M4(Q))return;throw Q}}}async function FW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return BW.toWeb(W.readableStreamBody);return null}function MW(W){return W}class x4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class I1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var o0=1000,LW=60000,NW=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
|
@@ -26,12 +26,12 @@ current = redis.call("INCRBY", currentKey, cost)
|
|
|
26
26
|
redis.call("PEXPIRE", currentKey, window * 2)
|
|
27
27
|
|
|
28
28
|
return {1, current, previous}
|
|
29
|
-
`;class
|
|
29
|
+
`;class t0 extends D4{injectedClient;prefix;mode;fallback;timeout;onError;scriptSha=null;down=!1;probing=!1;lastProbeAt=0;seenConnected=new WeakSet;loggedAt=-1/0;failuresSinceLog=0;fallbacksSinceLog=0;constructor(W={}){super();this.injectedClient=W.client,this.prefix=W.prefix??"gemi:rl",this.mode=W.onRedisError??(W.failOpen===void 0?"memory":W.failOpen?"open":"closed"),this.fallback=W.fallback??new H4,this.timeout=W.timeout??250,this.onError=W.onError}async consume(W){let{key:Z,limit:$,window:J}=W,Q=W.cost??1,Y=Date.now(),K=N4(Y,J),z=Y-K,X=K/J;if(this.down)return this.probe(),this.degrade(W,Y);try{let G=this.client;if(G.connected===!1&&this.seenConnected.has(G))throw new I1;let B=await this.withTimeout(this.run(G,[`${this.prefix}:${Z}:${X}`,`${this.prefix}:${Z}:${X-1}`],[String($),String(J),String(z),String(Q)]),()=>{this.scriptSha=null});if(G.connected===!0)this.seenConnected.add(G);let[j,N,S]=(Array.isArray(B)?B:[]).map(Number);return a0({allowed:j===1,current:Number.isFinite(N)?N:0,previous:Number.isFinite(S)?S:0,now:Y,elapsed:z,window:J,limit:$,cost:Q})}catch(G){if(!this.down)this.down=!0,this.lastProbeAt=Date.now();return this.report(G),this.degrade(W,Y)}}async degrade(W,Z){let{limit:$,window:J}=W,Q=W.cost??1;if(this.fallbacksSinceLog+=1,this.mode==="memory")return await this.fallback.consume(W);if(this.mode==="closed")return{allowed:!1,limit:$,remaining:0,resetAt:Z+J,retryAfter:J};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-Q)),resetAt:N4(Z,J)+J,retryAfter:0}}probe(){let W=Date.now();if(this.probing||W-this.lastProbeAt<o0)return;this.probing=!0,this.lastProbeAt=W,(async()=>{let $=this.client;if($.connected===!1&&this.seenConnected.has($))throw new I1;if(await this.withTimeout($.send("PING",[]),void 0,this.timeout>0?this.timeout:o0),$.connected===!0)this.seenConnected.add($)})().then(()=>{if(this.probing=!1,this.down=!1,!this.onError)this.logRecovery()},($)=>{this.probing=!1;try{this.report($)}catch{}})}report(W){if(this.onError){this.onError(W);return}this.failuresSinceLog+=1;let Z=Date.now();if(Z-this.loggedAt<LW)return;let $=this.mode==="memory"?"counting in memory":this.mode==="open"?"admitting every request":"refusing every request",J=this.loggedAt===-1/0?"":` Since the last report: ${this.failuresSinceLog} failures, ${this.fallbacksSinceLog} calls answered without Redis.`;console.error(`[gemi] RedisRateLimiter: Redis failed, ${$} until it answers again.${J}`,W),this.loggedAt=Z,this.failuresSinceLog=0,this.fallbacksSinceLog=0}logRecovery(){console.info(`[gemi] RedisRateLimiter: Redis answers again; counting in Redis (${this.fallbacksSinceLog} calls answered without it since the last report).`),this.loggedAt=-1/0,this.failuresSinceLog=0,this.fallbacksSinceLog=0}withTimeout(W,Z,$=this.timeout){if(!($>0)||!Number.isFinite($))return W;let J,Q=new Promise((Y,K)=>{J=setTimeout(()=>{Z?.(),K(new x4($))},$)});return W.catch(()=>{}),Promise.race([W,Q]).finally(()=>clearTimeout(J))}get client(){if(this.injectedClient)return this.injectedClient;let W=h(),Z=W.bound(w1)?W.make(w1).client:void 0;if(!Z)throw Error("RedisRateLimiter could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisRateLimiter({ client }).");return Z}async run(W,Z,$){let J=[String(Z.length),...Z,...$];try{return await W.send("EVALSHA",[await this.load(W),...J])}catch(Q){if(!DW(Q))throw Q;return this.scriptSha=null,await W.send("EVALSHA",[await this.load(W),...J])}}load(W){if(!this.scriptSha)this.scriptSha=Promise.resolve(W.send("SCRIPT",["LOAD",NW])).then(String).catch((Z)=>{throw this.scriptSha=null,Z});return this.scriptSha}}function DW(W){return String(W?.message??W).includes("NOSCRIPT")}import{createHash as b4,randomBytes as s,timingSafeEqual as HW}from"crypto";var y1=Object.freeze({"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"});function r0(W,Z){let $=W.client.name?V(W.client.name):"An application",J=W.scopes.map((Y)=>`<li><strong>${V(Y.name)}</strong><br><span>${V(Y.description)}</span></li>`).join(""),Q=Object.entries(W.form.fields).map(([Y,K])=>`<input type="hidden" name="${V(Y)}" value="${V(K)}">`).join("");return`<!doctype html>
|
|
30
30
|
<html lang="en">
|
|
31
31
|
<head>
|
|
32
32
|
<meta charset="utf-8">
|
|
33
33
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
34
|
-
<title>Connect to ${
|
|
34
|
+
<title>Connect to ${V(Z.name)}</title>
|
|
35
35
|
<style>
|
|
36
36
|
:root { color-scheme: light dark; font-family: system-ui, sans-serif; }
|
|
37
37
|
body { margin: 0; display: grid; place-items: center; min-height: 100vh; padding: 16px; box-sizing: border-box; }
|
|
@@ -48,11 +48,11 @@ return {1, current, previous}
|
|
|
48
48
|
</head>
|
|
49
49
|
<body>
|
|
50
50
|
<main>
|
|
51
|
-
<h1>${$} wants to access your ${
|
|
52
|
-
<p class="warn">Signed in as ${
|
|
51
|
+
<h1>${$} wants to access your ${V(Z.name)} account</h1>
|
|
52
|
+
<p class="warn">Signed in as ${V(W.user.label)}. After you allow it, you will be sent to <strong>${V(W.client.redirectHost)}</strong>. The name above was given by the application and is not verified. Only continue if you started this connection yourself.</p>
|
|
53
53
|
<p>It will be able to:</p>
|
|
54
54
|
<ul>${J}</ul>
|
|
55
|
-
<form method="post" action="${
|
|
55
|
+
<form method="post" action="${V(W.form.action)}">
|
|
56
56
|
${Q}
|
|
57
57
|
<div class="actions">
|
|
58
58
|
<button type="submit" name="decision" value="deny">Deny</button>
|
|
@@ -61,12 +61,12 @@ return {1, current, previous}
|
|
|
61
61
|
</form>
|
|
62
62
|
</main>
|
|
63
63
|
</body>
|
|
64
|
-
</html>`}function d0(W){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Authorization failed</title></head><body style="font-family: system-ui, sans-serif; padding: 24px"><h1 style="font-size: 1.2rem">This connection could not be authorized</h1><p>${f(W)}</p></body></html>`}function f(W){return W.replace(/[&<>"']/g,(Z)=>`&#${Z.charCodeAt(0)};`)}var N4="gmcp_at_",x4="gmcp_rt_",l0="gmcp_ac_",$W="gmcp_c_",JW="gmcp_cs_",F4="gemi.mcp.oauth.ticket.v1",n0="gemi.mcp.oauth.consent.v1",QW=600000,i0=120000,R4=16384,YW={limit:20,window:3600},KW={limit:60,window:60},v1=["none","client_secret_post","client_secret_basic"];class L extends Error{error;description;status;headers;constructor(W,Z,$=400,J={}){super(Z);this.error=W;this.description=Z;this.status=$;this.headers=J}}class J6{options;name="oauth";context;issuer;base;accessTtl;refreshTtl;constructor(W){this.options=W;let Z=W?.store;for(let $ of["createClient","findClient","saveCode","findCode","saveToken","findToken","use","revokeFamily"])if(typeof Z?.[$]!=="function")throw Error(`McpOAuthServer: store.${$} is missing. Use MemoryMcpOAuthStore, or implement McpOAuthStore.`);if(typeof W.findUser!=="function")throw Error("McpOAuthServer: findUser(id) is required: it loads the user a token was issued to.");if(W.consentPath!==void 0&&!/^\/[^/\\]/.test(W.consentPath))throw Error('McpOAuthServer: consentPath must be a path on this app, like "/oauth/consent".');this.accessTtl=s0("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=s0("refreshTokenTtl",W.refreshTokenTtl,2592000)}get store(){return this.options.store}boot(W){this.context=W;let Z=new URL(W.resource);this.issuer=Z.origin,this.base=`${Z.pathname}/oauth`}async resolve(W){let Z=f4(W);if(!Z?.startsWith(N4))return null;let $=await this.store.findToken(y(Z)),J=(Y)=>({ok:!1,error:"invalid_token",description:Y});if(!$||$.kind!=="access")return J("The access token is not valid.");if($.expiresAt<=Date.now())return J("The access token expired.");if($.resource!==this.context.resource)return J("The access token was not issued for this server.");let Q=await this.options.findUser($.userId);if(!Q)return J("The access token is not valid.");return{ok:!0,principal:{user:Q,via:this.name,id:$.familyId,scopes:$.scopes,clientId:$.clientId}}}challenge(){let W=this.scopeNames().join(" ");return`Bearer resource_metadata="${this.resourceMetadataUrl()}", scope="${W}"`}async handle(W){let Z=new URL(W.url).pathname,Q={[`/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-protected-resource"]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-authorization-server"]:{methods:["GET"],cors:!0,run:()=>this.serverMetadata()},[`${this.base}/register`]:{methods:["POST"],cors:!0,run:()=>this.register(W)},[`${this.base}/authorize`]:{methods:["GET"],cors:!1,run:()=>this.authorize(W)},[`${this.base}/consent`]:{methods:["GET","POST"],cors:!1,run:()=>W.method==="POST"?this.decide(W):this.consentScreen(W)},[`${this.base}/token`]:{methods:["POST"],cors:!0,run:()=>this.token(W)},[`${this.base}/revoke`]:{methods:["POST"],cors:!0,run:()=>this.revoke(W)}}[Z];if(!Q)return null;if(Z===`${this.base}/register`&&this.options.registration===!1)return null;let Y=Q.cors?GW:{};if(W.method==="OPTIONS"&&Q.cors)return new Response(null,{status:204,headers:{...Y,"Access-Control-Allow-Methods":Q.methods.join(", "),"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}});if(!Q.methods.includes(W.method))return new Response(null,{status:405,headers:{...Y,Allow:Q.methods.join(", ")}});let K;try{K=await Q.run()}catch(G){if(!(G instanceof L))throw G;K=N1({error:G.error,error_description:G.description},G.status,G.headers)}for(let[G,X]of Object.entries(Y))K.headers.set(G,X);return K}async consent(W,Z){if(!Z)return null;let $=q1(F4,"gat1",W);if(!$)return null;let J=await this.store.findClient($.c);if(!J||!J.redirectUris.some((G)=>H4(G,$.r)))return null;let Q=String(Z.id),Y=S4(n0,"gcs1",{t:o0(W),u:Q,exp:$.exp}),K=new Map(this.context.registry.scopes().map((G)=>[G.name,G.description]));return{client:{id:J.clientId,name:J.clientName,redirectHost:new URL($.r).host},scopes:$.s.map((G)=>({name:G,description:K.get(G)??G})),user:{id:Q,label:this.userLabel(Z)},form:{action:`${this.issuer}${this.base}/consent`,method:"POST",fields:{request:W,csrf:Y}}}}resourceMetadata(){return N1({resource:this.context.resource,authorization_servers:[this.issuer],scopes_supported:this.scopeNames(),bearer_methods_supported:["header"]})}serverMetadata(){return N1({issuer:this.issuer,authorization_endpoint:`${this.issuer}${this.base}/authorize`,token_endpoint:`${this.issuer}${this.base}/token`,...this.options.registration===!1?{}:{registration_endpoint:`${this.issuer}${this.base}/register`},revocation_endpoint:`${this.issuer}${this.base}/revoke`,scopes_supported:this.scopeNames(),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],token_endpoint_auth_methods_supported:v1,revocation_endpoint_auth_methods_supported:v1,code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,client_id_metadata_document_supported:!1})}async register(W){let Z=this.options.registration||{},$=await O4(`mcp-oauth-register:${$6(new U4(W,{},"api",`${this.base}/register`))}`,Z.rateLimit??YW);if($!==null)throw new L("slow_down","Too many registrations from this address.",429,{"Retry-After":String($)});if(!/^application\/json\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new L("invalid_client_metadata","Send the client metadata as application/json.");let J;try{J=JSON.parse(await _4(W,R4))}catch{throw new L("invalid_client_metadata","The client metadata is not JSON, or is too large.")}if(typeof J!=="object"||J===null||Array.isArray(J))throw new L("invalid_client_metadata","The client metadata must be a JSON object.");let Q=J.redirect_uris;if(!Array.isArray(Q)||Q.length===0||Q.length>10)throw new L("invalid_redirect_uri","redirect_uris must list one to ten URIs.");for(let x of Q){let O=BW(x);if(O)throw new L("invalid_redirect_uri",`${String(x).slice(0,200)}: ${O}`);if(Z.allowRedirectUri&&Z.allowRedirectUri(new URL(x))!==!0)throw new L("invalid_redirect_uri",`${x}: this server does not accept it.`)}let Y=J.token_endpoint_auth_method??"client_secret_basic";if(!v1.includes(Y))throw new L("invalid_client_metadata",`token_endpoint_auth_method must be one of ${v1.join(", ")}.`);let K=J.grant_types??["authorization_code"];if(!Array.isArray(K)||K.some((x)=>x!=="authorization_code"&&x!=="refresh_token"))throw new L("invalid_client_metadata","grant_types may only be authorization_code and refresh_token.");let G=J.response_types??["code"];if(!Array.isArray(G)||G.some((x)=>x!=="code"))throw new L("invalid_client_metadata","response_types may only be code.");let X=r0(J.client_name,100,"client_name"),z=r0(J.client_uri,512,"client_uri");if(z!==null&&!XW(z))throw new L("invalid_client_metadata","client_uri must be an https URL.");let B=Y==="none"?null:`${JW}${l(32).toString("base64url")}`,j={clientId:`${$W}${l(16).toString("base64url")}`,clientSecretHash:B?y(B):null,tokenEndpointAuthMethod:Y,redirectUris:[...Q],clientName:X,clientUri:z,createdAt:Date.now()};return await this.store.createClient(j),N1({client_id:j.clientId,client_id_issued_at:Math.floor(j.createdAt/1000),...B?{client_secret:B,client_secret_expires_at:0}:{},redirect_uris:j.redirectUris,token_endpoint_auth_method:Y,grant_types:K,response_types:G,...X?{client_name:X}:{},...z?{client_uri:z}:{}},201)}async authorize(W){let Z=new URL(W.url).searchParams;for(let H of new Set(Z.keys()))if(Z.getAll(H).length>1)return I(`The parameter ${H} was sent more than once.`);let $=Z.get("client_id"),J=$?await this.store.findClient($):null;if(!J)return I("The application is not registered with this server.");let Q=Z.get("redirect_uri")??(J.redirectUris.length===1?J.redirectUris[0]:null);if(!Q||!J.redirectUris.some((H)=>H4(H,Q)))return I("The redirect URI is not one the application registered.");let Y=Z.get("state"),K=(H,p)=>this.redirectBack(Q,Y,{error:H,error_description:p});if(Z.get("response_type")!=="code")return K("unsupported_response_type","Only response_type=code is supported.");let G=Z.get("code_challenge");if(Z.get("code_challenge_method")!=="S256"||!G||!/^[A-Za-z0-9_-]{43}$/.test(G))return K("invalid_request","PKCE is required: code_challenge with code_challenge_method=S256.");let X=Z.get("resource");if(X!==null&&!e0(X,this.context.resource))return K("invalid_target","The resource is not this server's.");if(Y!==null&&Y.length>2048)return K("invalid_request","state is too long.");let z=this.scopeNames(),B=Z.get("scope"),j=z;if(B!==null&&B.trim()!==""){if(j=[...new Set(B.split(" ").filter((H)=>z.includes(H)))],j.length===0)return K("invalid_scope","None of the requested scopes exist here.")}let x=S4(F4,"gat1",{c:J.clientId,r:Q,s:j,cc:G,st:Y,n:l(16).toString("base64url"),exp:Date.now()+QW}),O=this.options.consentPath??`${this.base}/consent`;return D4(`${this.issuer}${O}?request=${encodeURIComponent(x)}`,302)}async consentScreen(W){let Z=new URL(W.url).searchParams.get("request"),$=await this.sessionUser(W);if(!$){let Q=`${this.base}/consent?request=${encodeURIComponent(Z??"")}`,Y=this.options.signInPath??w(w1).config.signInPath;return D4(`${Y}${Y.includes("?")?"&":"?"}redirect=${encodeURIComponent(Q)}`,302)}let J=await this.consent(Z,$);if(!J)return I("This authorization request has expired or is not valid. Start again from the application.");return new Response(p0(J,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:I1})}async decide(W){let Z=W.headers.get("origin");if(!(Z!==null?Z===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return I("This decision did not come from this site's consent page.",403);if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))return I("The decision must be a form post.");let J;try{J=new URLSearchParams(await _4(W,R4))}catch{return I("The decision is too large.")}let Q=J.get("request"),Y=q1(F4,"gat1",Q),K=q1(n0,"gcs1",J.get("csrf")),G=await this.sessionUser(W);if(!Y||!K||!G||K.t!==o0(Q)||K.u!==String(G.id))return I("This authorization request has expired or is not valid. Start again from the application.",403);let X=await this.store.findClient(Y.c);if(!X||!X.redirectUris.some((B)=>H4(B,Y.r)))return I("The application is not registered with this server.");if(!await this.store.use(`ticket:${Y.n}`,Y.exp))return I("This request was already answered. Start again from the application.");if(J.get("decision")!=="allow")return this.redirectBack(Y.r,Y.st,{error:"access_denied",error_description:"The user denied the request."},303);let z=`${l0}${l(32).toString("base64url")}`;return await this.store.saveCode({hash:y(z),clientId:X.clientId,userId:String(G.id),redirectUri:Y.r,codeChallenge:Y.cc,scopes:Y.s,resource:this.context.resource,familyId:l(16).toString("base64url"),expiresAt:Date.now()+i0}),this.redirectBack(Y.r,Y.st,{code:z},303)}async token(W){let Z=await t0(W),$=await this.authenticateClient(W,Z),J=await O4(`mcp-oauth-token:${$.clientId}`,KW);if(J!==null)throw new L("slow_down","Too many token requests.",429,{"Retry-After":String(J)});let Q=Z.get("resource");if(Q!==null&&!e0(Q,this.context.resource))throw new L("invalid_target","The resource is not this server's.");switch(Z.get("grant_type")){case"authorization_code":{let Y=Z.get("code")??"",K=Y.startsWith(l0)?await this.store.findCode(y(Y)):null;if(!K||K.clientId!==$.clientId)throw new L("invalid_grant","The authorization code is not valid.");if(!await this.store.use(K.hash,K.expiresAt+i0))throw await this.store.revokeFamily(K.familyId),new L("invalid_grant","The authorization code was already used.");if(K.expiresAt<=Date.now())throw new L("invalid_grant","The authorization code expired.");if(Z.get("redirect_uri")!==null&&Z.get("redirect_uri")!==K.redirectUri)throw new L("invalid_grant","redirect_uri is not the one the code was issued to.");let G=Z.get("code_verifier");if(!G||!/^[A-Za-z0-9._~-]{43,128}$/.test(G)||!a0(zW(G),K.codeChallenge))throw new L("invalid_grant","The PKCE code_verifier does not match.");if(!await this.options.findUser(K.userId))throw new L("invalid_grant","The authorization code is not valid.");return await this.issue(K)}case"refresh_token":{let Y=Z.get("refresh_token")??"",K=Y.startsWith(x4)?await this.store.findToken(y(Y)):null;if(!K||K.kind!=="refresh"||K.clientId!==$.clientId)throw new L("invalid_grant","The refresh token is not valid.");if(K.expiresAt<=Date.now())throw new L("invalid_grant","The refresh token expired.");if(!await this.store.use(K.hash,K.expiresAt))throw await this.store.revokeFamily(K.familyId),new L("invalid_grant","The refresh token was already used.");if(K.resource!==this.context.resource)throw new L("invalid_grant","The refresh token was not issued for this server.");let G=K.scopes,X=Z.get("scope");if(X!==null&&X.trim()!==""){let z=[...new Set(X.split(" ").filter(Boolean))];if(z.some((B)=>!K.scopes.includes(B)))throw new L("invalid_scope","A refresh can only narrow the scopes that were granted.");G=z}if(!await this.options.findUser(K.userId))throw new L("invalid_grant","The refresh token is not valid.");return await this.issue({...K,scopes:G})}default:throw new L("unsupported_grant_type","grant_type must be authorization_code or refresh_token.")}}async issue(W){let Z=Date.now(),$=this.scopeNames(),J=W.scopes.filter((G)=>$.includes(G)),Q=`${N4}${l(32).toString("base64url")}`,Y=`${x4}${l(32).toString("base64url")}`,K={clientId:W.clientId,userId:W.userId,scopes:J,resource:W.resource,familyId:W.familyId};return await this.store.saveToken({...K,hash:y(Q),kind:"access",expiresAt:Z+this.accessTtl*1000}),await this.store.saveToken({...K,hash:y(Y),kind:"refresh",expiresAt:Z+this.refreshTtl*1000}),N1({access_token:Q,token_type:"Bearer",expires_in:this.accessTtl,refresh_token:Y,scope:J.join(" ")})}async revoke(W){let Z=await t0(W),$=await this.authenticateClient(W,Z),J=Z.get("token")??"";if(J.startsWith(N4)||J.startsWith(x4)){let Q=await this.store.findToken(y(J));if(Q&&Q.clientId===$.clientId)await this.store.revokeFamily(Q.familyId)}return new Response(null,{status:200,headers:{"Cache-Control":"no-store"}})}async authenticateClient(W,Z){let $=/^Basic\s+([A-Za-z0-9+/=]+)$/i.exec(W.headers.get("authorization")??""),J=Z.get("client_id"),Q=Z.get("client_secret");if($){let K=Buffer.from($[1],"base64").toString("utf8"),G=K.indexOf(":");if(G<0)throw n(!0);let X=W6(K.slice(0,G));if(X===null)throw n(!0);if(J!==null&&J!==X)throw n(!0);if(J=X,Q=W6(K.slice(G+1)),Q===null)throw n(!0)}let Y=J?await this.store.findClient(J):null;if(!Y)throw n(Boolean($));if(Y.tokenEndpointAuthMethod==="none"){if(Q)throw n(Boolean($));return Y}if(!Q||!Y.clientSecretHash||!a0(y(Q),Y.clientSecretHash))throw n(Boolean($));return Y}redirectBack(W,Z,$,J=302){let Q=new URL(W);for(let[Y,K]of Object.entries($))Q.searchParams.set(Y,K);if(Z!==null)Q.searchParams.set("state",Z);return Q.searchParams.set("iss",this.issuer),D4(Q.href,J)}async sessionUser(W){let Z=new U4(W,{},"api",this.base).cookies;return await Z6(w(w1),{cookies:Z,headers:{get:($)=>$.toLowerCase()==="user-agent"?W.headers.get("user-agent"):null}})}userLabel(W){if(this.options.userLabel)return this.options.userLabel(W);let Z=W;return String(Z.email??Z.name??Z.id)}scopeNames(){return this.context.registry.scopes().map((W)=>W.name)}resourceMetadataUrl(){return`${this.issuer}/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`}}var GW={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function s0(W,Z,$){if(Z===void 0)return $;if(!Number.isInteger(Z)||Z<60)throw Error(`McpOAuthServer: ${W} must be a whole number of seconds, at least 60.`);return Z}function y(W){return C4("sha256").update(W).digest("hex")}function o0(W){return C4("sha256").update(W).digest("base64url")}function zW(W){return C4("sha256").update(W).digest("base64url")}function a0(W,Z){let $=Buffer.from(W),J=Buffer.from(Z);return $.length===J.length&&ZW($,J)}function N1(W,Z=200,$={}){return new Response(JSON.stringify(W),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache",...$}})}function D4(W,Z){return new Response(null,{status:Z,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function I(W,Z=400){return new Response(d0(W),{status:Z,headers:I1})}function n(W){return new L("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function _4(W,Z){let $=Number(W.headers.get("content-length"));if(Number.isFinite($)&&$>Z)throw Error("too large");if(!W.body)return"";let J=W.body.getReader(),Q=[],Y=0;for(;;){let{done:K,value:G}=await J.read();if(K)break;if(Y+=G.byteLength,Y>Z)throw await J.cancel(),Error("too large");Q.push(G)}return Buffer.concat(Q).toString("utf8")}async function t0(W){if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new L("invalid_request","Send the request as application/x-www-form-urlencoded.");let Z;try{Z=new URLSearchParams(await _4(W,R4))}catch{throw new L("invalid_request","The request is too large.")}for(let $ of new Set(Z.keys()))if(Z.getAll($).length>1)throw new L("invalid_request",`${$} was sent more than once.`);return Z}function r0(W,Z,$){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>Z||jW(W))throw new L("invalid_client_metadata",`${$} must be text of at most ${Z} characters.`);return W}function XW(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function Q6(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function BW(W){if(typeof W!=="string"||W.length>2048)return"not a URI";let Z;try{Z=new URL(W)}catch{return"not an absolute URI"}if(Z.hash||W.includes("#"))return"must not have a fragment";if(Z.username||Z.password)return"must not carry credentials";if(Z.protocol==="https:")return null;if(Z.protocol==="http:"&&Q6(Z))return null;return"must be https, or http on a loopback address"}function H4(W,Z){if(W===Z)return!0;let $,J;try{$=new URL(W),J=new URL(Z)}catch{return!1}return $.protocol==="http:"&&J.protocol==="http:"&&Q6($)&&$.hostname===J.hostname&&$.pathname===J.pathname&&$.search===J.search&&!J.hash&&!J.username&&!J.password}function e0(W,Z){return W===Z||W===`${Z}/`}function jW(W){for(let Z=0;Z<W.length;Z++){let $=W.charCodeAt(Z);if($<32||$===127)return!0}return!1}function W6(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class Y6{clients=new Map;codes=new Map;tokens=new Map;used=new Map;revoked=new Set;async createClient(W){this.clients.set(W.clientId,structuredClone(W))}async findClient(W){let Z=this.clients.get(W);return Z?structuredClone(Z):null}async saveCode(W){this.sweep(),this.codes.set(W.hash,structuredClone(W))}async findCode(W){let Z=this.codes.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async saveToken(W){this.sweep(),this.tokens.set(W.hash,structuredClone(W))}async findToken(W){let Z=this.tokens.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async use(W,Z){if(this.used.has(W))return!1;return this.used.set(W,Z),!0}async revokeFamily(W){this.revoked.add(W);for(let[Z,$]of this.tokens)if($.familyId===W)this.tokens.delete(Z);for(let[Z,$]of this.codes)if($.familyId===W)this.codes.delete(Z)}async families(W){let Z=new Map;for(let $ of this.tokens.values())if($.userId===W&&!this.revoked.has($.familyId)&&$.expiresAt>Date.now())Z.set($.familyId,{familyId:$.familyId,clientId:$.clientId,scopes:[...$.scopes]});return[...Z.values()]}sweep(W=Date.now()){for(let[Z,$]of this.codes)if($.expiresAt<=W)this.codes.delete(Z);for(let[Z,$]of this.tokens)if($.expiresAt<=W)this.tokens.delete(Z);for(let[Z,$]of this.used)if($<=W)this.used.delete(Z)}}class K6{clients;credentials;uses;usesModel;constructor(W){for(let[Z,$]of[["clients",["create","findUnique","findMany"]],["credentials",["create","findFirst","findMany","count","updateMany","deleteMany"]],["uses",["create","deleteMany"]]]){let J=W?.[Z],Q=$.filter((Y)=>typeof J?.[Y]!=="function");if(Q.length>0)throw Error(`PrismaMcpOAuthStore: models.${Z} must be a gemi ORM model or a Prisma delegate (it has no ${Q.join(", ")}()).`)}this.clients=W.clients,this.credentials=W.credentials,this.usesModel=W.uses,this.uses=new k4(W.uses)}async createClient(W){await this.clients.create({data:{clientId:W.clientId,clientSecretHash:W.clientSecretHash,tokenEndpointAuthMethod:W.tokenEndpointAuthMethod,redirectUris:[...W.redirectUris],clientName:W.clientName,clientUri:W.clientUri,createdAt:new Date(W.createdAt)}})}async findClient(W){let Z=await this.clients.findUnique({where:{clientId:W}});if(!Z)return null;return{clientId:Z.clientId,clientSecretHash:Z.clientSecretHash??null,tokenEndpointAuthMethod:Z.tokenEndpointAuthMethod,redirectUris:y1(Z.redirectUris),clientName:Z.clientName??null,clientUri:Z.clientUri??null,createdAt:A1(Z.createdAt)}}async saveCode(W){await this.credentials.create({data:{hash:W.hash,kind:"code",clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,redirectUri:W.redirectUri,codeChallenge:W.codeChallenge,expiresAt:new Date(W.expiresAt)}})}async findCode(W){let Z=await this.findLive(W,["code"]);if(!Z||Z.redirectUri==null||Z.codeChallenge==null)return null;return{hash:Z.hash,clientId:Z.clientId,userId:Z.userId,redirectUri:Z.redirectUri,codeChallenge:Z.codeChallenge,scopes:y1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:A1(Z.expiresAt)}}async saveToken(W){await this.credentials.create({data:{hash:W.hash,kind:W.kind,clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,expiresAt:new Date(W.expiresAt)}})}async findToken(W){let Z=await this.findLive(W,["access","refresh"]);if(!Z)return null;return{hash:Z.hash,kind:Z.kind,clientId:Z.clientId,userId:Z.userId,scopes:y1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:A1(Z.expiresAt)}}use(W,Z){return this.uses.consume(W,Z)}async revokeFamily(W){await this.credentials.updateMany({where:{familyId:W,revokedAt:null},data:{revokedAt:new Date}})}nonces(W={}){return new k4(this.usesModel,{prefix:W.prefix??"nonce:"})}async connectedApps(W,Z=new Date){let $=String(W),J=await this.credentials.findMany({where:{userId:$,kind:"refresh",expiresAt:{gt:Z}},orderBy:{createdAt:"asc"}}),Q=await this.revokedFamilies({userId:$}),Y=new Map;for(let z of J){if(Q.has(z.familyId))continue;if(!Y.has(z.familyId))Y.set(z.familyId,z)}if(Y.size===0)return[];let K=[...new Set([...Y.values()].map((z)=>z.clientId))],G=await this.clients.findMany({where:{clientId:{in:K}}}),X=new Map(G.map((z)=>[z.clientId,z]));return[...Y.values()].map((z)=>({familyId:z.familyId,clientId:z.clientId,clientName:X.get(z.clientId)?.clientName??null,clientUri:X.get(z.clientId)?.clientUri??null,scopes:y1(z.scopes),connectedAt:new Date(A1(z.createdAt))})).reverse()}async disconnect(W,Z){if(await this.credentials.count({where:{familyId:Z,userId:String(W)}})===0)return!1;return await this.revokeFamily(Z),!0}async revokeUser(W){await this.credentials.updateMany({where:{userId:String(W),revokedAt:null},data:{revokedAt:new Date}})}async prune(W=Date.now()){let Z=new Date(W-86400000),$=[...await this.revokedFamilies({expiresAt:{lt:Z}})],J=$.length===0?[]:await this.credentials.findMany({where:{familyId:{in:$},expiresAt:{gte:Z}},select:{familyId:!0}}),Q=[...new Set(J.map((Y)=>Y.familyId))];await this.credentials.deleteMany({where:{expiresAt:{lt:Z},...Q.length>0?{OR:[{revokedAt:null},{familyId:{notIn:Q}}]}:{}}}),await this.usesModel.deleteMany({where:{expiresAt:{lt:new Date(W)}}})}async findLive(W,Z){let $=await this.credentials.findFirst({where:{hash:W,kind:{in:Z},revokedAt:null}});if(!$)return null;return await this.credentials.count({where:{familyId:$.familyId,revokedAt:{not:null}}})>0?null:$}async revokedFamilies(W){let Z=await this.credentials.findMany({where:{...W,revokedAt:{not:null}},select:{familyId:!0}});return new Set(Z.map(($)=>$.familyId))}}function y1(W){return Array.isArray(W)?W.map(String):[]}function A1(W){return W instanceof Date?W.getTime():new Date(W).getTime()}class F1 extends C{application;previous;dispatched=[];static install(W){let Z=W.resolved(C)?W.make(C):void 0;if(Z instanceof F1)return Z;let $=new F1(W,Z);return W.instance(C,$),$}constructor(W,Z){super({listeners:[]});this.application=W;this.previous=Z}dispatch(W,Z){this.dispatched.push({event:W,args:Z})}async dispatchAndWait(W,Z){this.dispatched.push({event:W,args:Z})}restore(){if(this.previous){this.application.instance(C,this.previous);return}this.application.forget(C)}assertDispatched(W,Z){let $=x1(W);if(this.matching($,Z).length>0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} to have been dispatched. ${this.summary($,Z!==void 0)}`)}assertNotDispatched(W,Z){let $=x1(W),J=this.matching($,Z);if(J.length===0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} not to have been dispatched, but it was dispatched ${b4(J.length)}: ${h1(J)}.`)}assertDispatchedTimes(W,Z,$){let J=x1(W),Q=this.matching(J,$);if(Q.length===Z)return;throw Error(`Expected ${J}${$?" matching the predicate":""} to have been dispatched ${b4(Z)}, but it was dispatched ${b4(Q.length)}. ${this.summary(J,$!==void 0)}`)}assertNothingDispatched(){if(this.dispatched.length===0)return;let W=this.dispatched.length;throw Error(`Expected nothing to have been dispatched, but ${W} ${W===1?"event was":"events were"}: ${h1(this.dispatched)}.`)}matching(W,Z){return this.dispatched.filter(($)=>x1($.event.constructor)===W&&(Z===void 0||Z($.event)))}summary(W,Z){if(this.dispatched.length===0)return"Nothing was dispatched.";let $=this.matching(W);if(Z&&$.length>0)return`Dispatched ${W}: ${h1($)}.`;return`Dispatched: ${h1(this.dispatched)}.`}}function x1(W){return W.name}function b4(W){return`${W} ${W===1?"time":"times"}`}function h1(W){return W.map(MW).join(", ")}function MW(W){let Z=x1(W.event.constructor),$=W.args??Object.values({...W.event});return`${Z}(${$.map(LW).join(", ")})`}function LW(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class g1{static name="unset";static afterCommit=!1;static dispatch(...W){G6(this),w(C).dispatch(new this(...W),W)}static dispatchAndWait(...W){return G6(this),w(C).dispatchAndWait(new this(...W),W)}static fake(){return F1.install(NW())}}function NW(){try{return w()}catch(W){throw Error("Event.fake() needs a booted application. The fake works by replacing the container's EventManager with a recorder, so there has to be a "+"container to replace it in \u2014 and a dispatch finds the recorder the "+"same way, by resolving from that container. Boot the app's kernel in the test's setup: `const kernel = new Kernel(); kernel.boot()` is enough on its own, since that is the phase that publishes the application every dispatch outside a request resolves through.",{cause:W})}}function G6(W){if(W.name!=="unset"&&W.name!=="")return;throw Error("Cannot dispatch an event with no name. Add `static name` to this Event "+"subclass \u2014 the listener registry is keyed by that string, and by that "+"string alone, so an event without one cannot reach a listener.")}class B6 extends g1{constructor(){super();Object.defineProperty(this,T4,{value:!0,enumerable:!1})}broadcastAs(){return this.constructor.name}broadcastWith(){return}channel(W,...Z){return{topic:z6(W,Z[0]??{}),pattern:W}}}var xW={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET,redirectPath:"/auth/oauth/google/callback",scope:"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",authorizationParams:{}};function FW(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class j6 extends i{config;constructor(W={}){super();this.config={...xW,...W}}redirectUri(){return`${r()??""}${this.config.redirectPath}`}getRedirectUrl(W,Z){let $=new URL("https://accounts.google.com/o/oauth2/v2/auth"),J={include_granted_scopes:"true",...this.config.authorizationParams,scope:this.config.scope,response_type:"code",redirect_uri:this.redirectUri(),client_id:this.config.clientId};if(Z)J.state=Z.state,J.code_challenge=Z.codeChallenge,J.code_challenge_method=Z.codeChallengeMethod;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new k("missing_code");let J=new URLSearchParams({code:$,client_id:this.config.clientId,client_secret:this.config.clientSecret,grant_type:"authorization_code",redirect_uri:this.redirectUri()});if(Z?.codeVerifier)J.set("code_verifier",Z.codeVerifier);let Q=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J.toString()}),Y=await Q.json().catch(()=>({}));if(!Q.ok||typeof Y?.access_token!=="string"||Y.access_token==="")throw console.error("Google OAuth error: token exchange failed",Y?.error??Q.status),new k(FW(Y?.error,"exchange_failed"));let G=await(await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${Y.access_token}`}})).json().catch(()=>({}));if(typeof G.sub!=="string"||G.sub==="")return console.error("Google OAuth error: sub not found in user info response",G),{};if(!G.email)console.error("Google OAuth error: email not found in user info response",G);return{providerId:G.sub,name:G.name,email:G.email,emailVerified:G.email_verified===!0||G.email_verified==="true"}}}var g="https://api.x.com/2/",e="https://api.x.com/labs/2/",E="https://api.x.com/1.1/",A="https://upload.x.com/1.1/",M6="https://stream.x.com/1.1/",W1="https://ads-api.x.com/12/",Z1="https://ads-api-sandbox.twitter.com/12/";class P4{constructor({realData:W,rateLimit:Z,instance:$,queryParams:J,sharedParams:Q}){this._maxResultsWhenFetchLast=100,this._realData=W,this._rateLimit=Z,this._instance=$,this._queryParams=J,this._sharedParams=Q}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(W){return this._instance.get(this.getEndpoint(),W,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(W,Z){return new this.constructor({realData:W.data,rateLimit:W.rateLimit,instance:this._instance,queryParams:Z,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(W){return{...W?{max_results:W}:{},...this._queryParams}}async next(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchNext(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!0),this}async fetchLast(W=1/0){let Z=this.getNextQueryParams(this._maxResultsWhenFetchLast),$=0;while($<W&&this._isRateLimitOk){let J=await this.makeRequest(Z);if(await this.refreshInstanceFromResult(J,!0),$+=this.getPageLengthFromRequest(J),this.isFetchLastOver(J))break;Z=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var W;return{...(W=this._rateLimit)!==null&&W!==void 0?W:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData),yield*$.getItemArray(),W=$}}async*fetchAndIterate(){for(let $ of this.getItemArray())yield[$,this];let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData);for(let J of $.getItemArray())yield[J,$];this._rateLimit=$._rateLimit,W=$}}}class V4 extends P4{async previous(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchPrevious(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!1),this}}var $1=P4;class D extends $1{getNextQueryParams(W){var Z;return{...this._queryParams,cursor:(Z=this._realData.next_cursor_str)!==null&&Z!==void 0?Z:this._realData.next_cursor,...W?{count:W}:{}}}isFetchLastOver(W){return!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!this.isNextCursorInvalid(W.next_cursor)||!this.isNextCursorInvalid(W.next_cursor_str)}isNextCursorInvalid(W){return W===void 0||W===0||W===-1||W==="0"||W==="-1"}}class I4 extends D{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.events.push(...$.events),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class v4 extends D{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.welcome_messages.push(...$.welcome_messages),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var F;(function(W){W.Jpeg="image/jpeg",W.Mp4="video/mp4",W.Mov="video/quicktime",W.Gif="image/gif",W.Png="image/png",W.Srt="text/plain",W.Webp="image/webp"})(F||(F={}));var m;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(m||(m={}));var D1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(D1||(D1={}));class E1 extends Error{constructor(){super(...arguments);this.error=!0}}class H1 extends E1{constructor(W,Z){super(W);this.type=D1.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class U1 extends E1{constructor(W,Z){super(W);this.type=D1.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}get request(){return this._options.request}get response(){return this._options.response}get responseError(){return this._options.responseError}get rawContent(){return this._options.rawContent}toJSON(){return{type:this.type,error:this.responseError}}}class O1 extends E1{constructor(W,Z){super(W);if(this.type=D1.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z}),this.code=Z.code,this.headers=Z.headers,this.rateLimit=Z.rateLimit,Z.data&&typeof Z.data==="object"&&"error"in Z.data&&!Z.data.errors){let $={...Z.data};$.errors=[{code:s.InternalError,message:$.error}],this.data=$}else this.data=Z.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...W){let Z=this.errors;if(!(Z===null||Z===void 0?void 0:Z.length))return!1;if("code"in Z[0])return Z.some((Q)=>W.includes(Q.code));let $=this.data;return W.includes($.type)}get errors(){var W;return(W=this.data)===null||W===void 0?void 0:W.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(s.AuthTimestampInvalid,s.AuthenticationFail,s.BadAuthenticationData,s.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var s;(function(W){W[W.InvalidCoordinates=3]="InvalidCoordinates",W[W.NoLocationFound=13]="NoLocationFound",W[W.AuthenticationFail=32]="AuthenticationFail",W[W.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",W[W.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",W[W.AuthTimestampInvalid=135]="AuthTimestampInvalid",W[W.BadAuthenticationData=215]="BadAuthenticationData",W[W.NoUserMatch=17]="NoUserMatch",W[W.UserNotFound=50]="UserNotFound",W[W.ResourceNotFound=34]="ResourceNotFound",W[W.TweetNotFound=144]="TweetNotFound",W[W.TweetNotVisible=179]="TweetNotVisible",W[W.NotAllowedResource=220]="NotAllowedResource",W[W.MediaIdNotFound=325]="MediaIdNotFound",W[W.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",W[W.TweetViolatedRules=422]="TweetViolatedRules",W[W.TargetUserSuspended=63]="TargetUserSuspended",W[W.YouAreSuspended=64]="YouAreSuspended",W[W.AccountUpdateFailed=120]="AccountUpdateFailed",W[W.NoSelfSpamReport=36]="NoSelfSpamReport",W[W.NoSelfMute=271]="NoSelfMute",W[W.AccountLocked=326]="AccountLocked",W[W.RateLimitExceeded=88]="RateLimitExceeded",W[W.NoDMRightForApp=93]="NoDMRightForApp",W[W.OverCapacity=130]="OverCapacity",W[W.InternalError=131]="InternalError",W[W.TooManyFollowings=161]="TooManyFollowings",W[W.TweetLimitExceeded=185]="TweetLimitExceeded",W[W.DuplicatedTweet=187]="DuplicatedTweet",W[W.TooManySpamReports=205]="TooManySpamReports",W[W.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",W[W.NoWriteRightForApp=261]="NoWriteRightForApp",W[W.TweetActionsDisabled=425]="TweetActionsDisabled",W[W.TweetRepliesRestricted=433]="TweetRepliesRestricted",W[W.NamedParameterMissing=38]="NamedParameterMissing",W[W.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",W[W.TweetTextTooLong=186]="TweetTextTooLong",W[W.MissingUrlParameter=195]="MissingUrlParameter",W[W.NoMultipleGifs=323]="NoMultipleGifs",W[W.InvalidMediaIds=324]="InvalidMediaIds",W[W.InvalidUrl=407]="InvalidUrl",W[W.TooManyTweetAttachments=386]="TooManyTweetAttachments",W[W.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",W[W.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",W[W.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",W[W.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",W[W.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",W[W.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",W[W.UnableToSendDM=151]="UnableToSendDM",W[W.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",W[W.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",W[W.DMTextTooLong=354]="DMTextTooLong",W[W.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",W[W.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",W[W.SuspendedApplication=416]="SuspendedApplication",W[W.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(s||(s={}));var L6;(function(W){W.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",W.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",W.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",W.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",W.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",W.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",W.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",W.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",W.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",W.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",W.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",W.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",W.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(L6||(L6={}));var M;(function(W){W.Connected="connected",W.ConnectError="connect error",W.ConnectionError="connection error",W.ConnectionClosed="connection closed",W.ConnectionLost="connection lost",W.ReconnectAttempt="reconnect attempt",W.Reconnected="reconnected",W.ReconnectError="reconnect error",W.ReconnectLimitExceeded="reconnect limit exceeded",W.DataKeepAlive="data keep-alive",W.Data="data event content",W.DataError="data twitter error",W.TweetParseError="data tweet parse error",W.Error="stream error"})(M||(M={}));class S1{constructor(W){this.value=W}}import*as Q0 from"fs";var U={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function q4(W){let Z={value:void 0,promise:W().then(($)=>{return Z.value=$,$})};return Z}function m1(W){if(Array.isArray(W))return W;return[W]}function x6(W){for(let Z of Object.keys(W))if(W[Z]===void 0)delete W[Z]}function c1(W){return typeof W==="object"&&"errors"in W&&!("data"in W)}function R1(W){if(Array.isArray(W)&&W.length>1)return!0;return W.toString().includes(",")}var N6=new Set;function w4(W){if(typeof console>"u"||!console.warn||!U.deprecationWarnings)return;let Z=`${W.instance}-${W.method}-${W.problem}`;if(N6.has(Z))return;let $=`[twitter-api-v2] Deprecation warning: In ${W.instance}.${W.method}() call, ${W.problem}.
|
|
65
|
-
${W.resolution}.`;console.warn($),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),N6.add(Z)}import{EventEmitter as SW}from"events";import{request as DW}from"https";import*as S from"zlib";import{EventEmitter as HW}from"events";class F6{constructor(W){this.requestData=W,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let W=this.requestData.url;return W.hostname+W.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(W){if(U.debug)U.logger.log("Request error:",W);return new H1("Request failed.",{request:this.req,error:W})}createPartialResponseError(W,Z){let J=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(Z)J+=" (connection abruptly closed)";else J+=" (parse error)";return new U1(J,{request:this.req,response:this.res,responseError:W,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(W){return W.map(({code:Z,message:$})=>`${$} (Twitter code ${Z})`).join(", ")}formatV2Error(W){return`${W.title}: ${W.detail} (see ${W.type})`}createResponseError({res:W,data:Z,rateLimit:$,code:J}){var Q;if(U.debug)U.logger.log(`Request failed with code ${J}, data:`,Z),U.logger.log("Response headers:",W.headers);let Y=`Request failed with code ${J}`;if((Q=Z===null||Z===void 0?void 0:Z.errors)===null||Q===void 0?void 0:Q.length){let K=Z.errors;if(typeof K[0]==="object"&&"code"in K[0])Y+=" - "+this.formatV1Errors(K);else Y+=" - "+this.formatV2Error(Z)}return new O1(Y,{code:J,data:Z,headers:W.headers,request:this.req,response:W,rateLimit:$})}getResponseDataStream(W){if(this.isCompressionDisabled())return W;let Z=(W.headers["content-encoding"]||"identity").trim().toLowerCase();if(Z==="br"){let $=S.createBrotliDecompress({flush:S.constants.BROTLI_OPERATION_FLUSH,finishFlush:S.constants.BROTLI_OPERATION_FLUSH});return W.pipe($),$}if(Z==="gzip"){let $=S.createGunzip({flush:S.constants.Z_SYNC_FLUSH,finishFlush:S.constants.Z_SYNC_FLUSH});return W.pipe($),$}if(Z==="deflate"){let $=S.createInflate({flush:S.constants.Z_SYNC_FLUSH,finishFlush:S.constants.Z_SYNC_FLUSH});return W.pipe($),$}return W}detectResponseType(W){var Z,$;if(((Z=W.headers["content-type"])===null||Z===void 0?void 0:Z.includes("application/json"))||(($=W.headers["content-type"])===null||$===void 0?void 0:$.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(W){let Z=this.responseData,$=this.requestData.forceParseMode||this.detectResponseType(W);if($==="buffer")return Buffer.concat(Z);else if($==="text")return Buffer.concat(Z).toString();else if($==="json"){let J=Buffer.concat(Z).toString();return J.length?JSON.parse(J):void 0}else if($==="url"){let J=Buffer.concat(Z).toString(),Q={};for(let[Y,K]of new URLSearchParams(J))Q[Y]=K;return Q}else return}getRateLimitFromResponse(W){let Z=void 0;if(W.headers["x-rate-limit-limit"]){if(Z={limit:Number(W.headers["x-rate-limit-limit"]),remaining:Number(W.headers["x-rate-limit-remaining"]),reset:Number(W.headers["x-rate-limit-reset"])},W.headers["x-app-limit-24hour-limit"])Z.day={limit:Number(W.headers["x-app-limit-24hour-limit"]),remaining:Number(W.headers["x-app-limit-24hour-remaining"]),reset:Number(W.headers["x-app-limit-24hour-reset"])};if(W.headers["x-user-limit-24hour-limit"])Z.userDay={limit:Number(W.headers["x-user-limit-24hour-limit"]),remaining:Number(W.headers["x-user-limit-24hour-remaining"]),reset:Number(W.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(Z)}return Z}onSocketEventHandler(W,Z,$){let J=this.onSocketCloseHandler.bind(this,W);$.on("close",J),Z.on("complete",()=>$.off("close",J))}onSocketCloseHandler(W){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return W(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(W,Z){var $,J;(J=($=this.requestData).requestEventDebugHandler)===null||J===void 0||J.call($,"request-error",{requestError:Z}),this.requestErrorHandled=!0,W(this.createRequestError(Z))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(W,Z,$){this.res=$;let J=this.getResponseDataStream($);if(J.on("data",(Q)=>this.responseData.push(Q)),J.on("end",this.onResponseEndHandler.bind(this,W,Z)),J.on("close",this.onResponseCloseHandler.bind(this,W,Z)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:$}),$.on("aborted",(Q)=>this.requestData.requestEventDebugHandler("response-aborted",{error:Q})),$.on("error",(Q)=>this.requestData.requestEventDebugHandler("response-error",{error:Q})),$.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),$.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(W,Z){let $=this.getRateLimitFromResponse(this.res),J;try{J=this.getParsedResponse(this.res)}catch(Y){Z(this.createPartialResponseError(Y,!1));return}let Q=this.res.statusCode;if(Q>=400){Z(this.createResponseError({data:J,res:this.res,rateLimit:$,code:Q}));return}if(U.debug)U.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),U.logger.log("Response body:",J);W({data:J,headers:this.res.headers,rateLimit:$})}onResponseCloseHandler(W,Z){let $=this.res;if($.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(W,Z)}catch(J){return Z(this.createPartialResponseError(J,!0))}if(!$.complete)return Z(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(W,Z,$){if($.statusCode<400){if(U.debug)U.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${$.statusCode} (starting stream)`);let Q=this.getResponseDataStream($);W({req:this.req,res:Q,originalResponse:$,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},Z,$)}debugRequest(){let W=this.requestData.url;if(U.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),W.search)U.logger.log("Request parameters:",[...W.searchParams.entries()].map(([Z,$])=>`${Z}: ${$}`));if(this.requestData.body)U.logger.log("Request body:",this.requestData.body)}buildRequest(){var W;let Z=this.requestData.url,$=Z.username?`${Z.username}:${Z.password}`:void 0,J=(W=this.requestData.options.headers)!==null&&W!==void 0?W:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")J["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")J["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")J["accept-encoding"]="deflate;q=1, *;q=0.1";if(U.debug)this.debugRequest();this.req=DW({...this.requestData.options,host:Z.hostname,port:Z.port||void 0,path:Z.pathname+Z.search,protocol:Z.protocol,auth:$,headers:J})}registerRequestEventDebugHandlers(W){W.on("close",()=>this.requestData.requestEventDebugHandler("close")),W.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),W.on("socket",(Z)=>{this.requestData.requestEventDebugHandler("socket",{socket:Z}),Z.on("error",($)=>this.requestData.requestEventDebugHandler("socket-error",{socket:Z,error:$})),Z.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:Z})),Z.on("close",($)=>this.requestData.requestEventDebugHandler("socket-close",{socket:Z,withError:$})),Z.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:Z})),Z.on("lookup",(...$)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:Z,data:$})),Z.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:Z}))})}makeRequest(){return this.buildRequest(),new Promise((W,Z)=>{let $=(K)=>{Q.emit("complete"),W(K)},J=(K)=>{Q.emit("complete"),Z(K)},Q=new HW,Y=this.req;if(Y.on("error",this.requestErrorHandler.bind(this,J)),Y.on("socket",this.onSocketEventHandler.bind(this,J,Q)),Y.on("response",this.classicResponseHandler.bind(this,$,J)),this.requestData.options.timeout)Y.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(Y);if(this.requestData.body)Y.write(this.requestData.body);Y.end()})}async makeRequestAsStream(){let{req:W,res:Z,requestData:$,originalResponse:J}=await this.makeRequestAndResolveWhenReady();return new u1($,{req:W,res:Z,originalResponse:J})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((W,Z)=>{let $=this.req;if($.on("error",this.requestErrorHandler.bind(this,Z)),$.on("response",this.streamResponseHandler.bind(this,W,Z)),this.requestData.body)$.write(this.requestData.body);$.end()})}}var _1=F6;import{EventEmitter as UW}from"events";class D6 extends UW{constructor(W){super();this.stream=W,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),W.on(M.Data,this.onStreamData),W.on(M.ConnectionError,this.onStreamError),W.on(M.TweetParseError,this.onStreamError),W.on(M.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let W=this.stack;return this.stack=[],W}destroy(){this.removeAllListeners(),this.stream.off(M.Data,this.onStreamData),this.stream.off(M.ConnectionError,this.onStreamError),this.stream.off(M.TweetParseError,this.onStreamError),this.stream.off(M.ConnectionClosed,this.onStreamError)}emitEvent(W,Z){this.emit("event",{type:W,payload:Z})}onStreamError(W){this.emitEvent("error",W)}onStreamData(W){this.stack.push(W),this.emitEvent("data",W)}}var H6=D6;import{EventEmitter as OW}from"events";class p1 extends OW{constructor(){super(...arguments);this.currentMessage=""}push(W){this.currentMessage+=W,W=this.currentMessage;let Z=W.length,$=0,J=0;while(J<Z){if(W.slice(J,J+2)===`\r
|
|
66
|
-
`){let Q=W.slice($,J);if($=J+=2,!Q.length)continue;try{let Y=JSON.parse(Q);if(Y){this.emit(
|
|
67
|
-
`)return this.emit(
|
|
68
|
-
`;T.DEFAULT_CONTENT_TYPE="application/octet-stream";class y4{static formatQueryToString(W){let Z={};for(let $ in W)if(typeof W[$]==="string")Z[$]=W[$];else if(typeof W[$]<"u")Z[$]=String(W[$]);return Z}static autoDetectBodyType(W){if(W.pathname.startsWith("/2/")||W.pathname.startsWith("/labs/2/")){if(W.password.startsWith("/2/oauth2"))return"url";return"json"}if(W.hostname==="upload.x.com"){if(W.pathname==="/1.1/media/upload.json")return"form-data";return"json"}let Z=W.pathname.split("/1.1/",2)[1];if(this.JSON_1_1_ENDPOINTS.has(Z))return"json";return"url"}static addQueryParamsToUrl(W,Z){let $=Object.entries(Z);if($.length){let J="";for(let[Q,Y]of $)J+=(J.length?"&":"?")+`${f1.percentEncode(Q)}=${f1.percentEncode(Y)}`;W.search=J}}static constructBodyParams(W,Z,$){if(W instanceof Buffer)return W;if($==="json"){if(!Z["content-type"])Z["content-type"]="application/json;charset=UTF-8";return JSON.stringify(W)}else if($==="url"){if(!Z["content-type"])Z["content-type"]="application/x-www-form-urlencoded;charset=UTF-8";if(Object.keys(W).length)return new URLSearchParams(W).toString().replace(/\*/g,"%2A");return""}else if($==="raw")throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");else{let J=new T;for(let Q in W)J.append(Q,W[Q]);if(!Z["content-type"]){let Q=J.getHeaders();Z["content-type"]=Q["content-type"]}return J.getBuffer()}}static setBodyLengthHeader(W,Z){var $;if(W.headers=($=W.headers)!==null&&$!==void 0?$:{},typeof Z==="string")W.headers["content-length"]=Buffer.byteLength(Z);else W.headers["content-length"]=Z.length}static isOAuthSerializable(W){return!(W instanceof Buffer)}static mergeQueryAndBodyForOAuth(W,Z){let $={};for(let J in W)$[J]=W[J];if(this.isOAuthSerializable(Z))for(let J in Z){let Q=Z[J];if(this.isOAuthSerializable(Q))$[J]=typeof Q==="object"&&Q!==null&&"toString"in Q?Q.toString():Q}return $}static moveUrlQueryParamsIntoObject(W,Z){for(let[$,J]of W.searchParams)Z[$]=J;return W.search="",W}static applyRequestParametersToUrl(W,Z){return W.pathname=W.pathname.replace(/:([A-Z_-]+)/ig,($,J)=>{if(Z[J]!==void 0)return String(Z[J]);return $}),W}}y4.JSON_1_1_ENDPOINTS=new Set(["direct_messages/events/new.json","direct_messages/welcome_messages/new.json","direct_messages/welcome_messages/rules/new.json","media/metadata/create.json","collections/entries/curate.json"]);var R=y4;import*as k6 from"crypto";class a{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url(k6.createHash("sha256").update(W).digest("base64"))}static getAuthHeader(W,Z){let $=encodeURIComponent(W)+":"+encodeURIComponent(Z);return Buffer.from($).toString("base64")}static generateRandomString(W){let Z="",$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let J=0;J<W;J++)Z+=$[Math.floor(Math.random()*$.length)];return Z}static escapeBase64Url(W){return W.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class J1{constructor(W){if(this.rateLimits={},this.clientSettings={},W)this.clientSettings=W}getRateLimits(){return this.rateLimits}saveRateLimit(W,Z){this.rateLimits[W]=Z}async send(W){var Z,$,J,Q,Y;if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length){let j=await this.applyPreRequestConfigHooks(W);if(j)return j}let K=this.getHttpRequestArgs(W),G={method:K.method,headers:K.headers,timeout:W.timeout,agent:this.clientSettings.httpAgent},X=W.enableRateLimitSave!==!1;if(K.body)R.setBodyLengthHeader(G,K.body);if(($=this.clientSettings.plugins)===null||$===void 0?void 0:$.length)await this.applyPreRequestHooks(W,K,G);let z=new _1({url:K.url,options:G,body:K.body,rateLimitSaver:X?this.saveRateLimit.bind(this,K.rawUrl):void 0,requestEventDebugHandler:W.requestEventDebugHandler,compression:(Q=(J=W.compression)!==null&&J!==void 0?J:this.clientSettings.compression)!==null&&Q!==void 0?Q:!0,forceParseMode:W.forceParseMode}).makeRequest();if(S6(this))z=this.applyResponseErrorHooks(W,K,G,z);let B=await z;if((Y=this.clientSettings.plugins)===null||Y===void 0?void 0:Y.length){let j=await this.applyPostRequestHooks(W,K,G,B);if(j)return j.value}return B}sendStream(W){var Z,$;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(W);let J=this.getHttpRequestArgs(W),Q={method:J.method,headers:J.headers,agent:this.clientSettings.httpAgent},Y=W.enableRateLimitSave!==!1,K=W.autoConnect!==!1;if(J.body)R.setBodyLengthHeader(Q,J.body);let G={url:J.url,options:Q,body:J.body,rateLimitSaver:Y?this.saveRateLimit.bind(this,J.rawUrl):void 0,payloadIsError:W.payloadIsError,compression:($=(Z=W.compression)!==null&&Z!==void 0?Z:this.clientSettings.compression)!==null&&$!==void 0?$:!0},X=new u1(G);if(!K)return X;return X.connect()}initializeToken(W){if(typeof W==="string")this.bearerToken=W;else if(typeof W==="object"&&"appKey"in W){if(this.consumerToken=W.appKey,this.consumerSecret=W.appSecret,W.accessToken&&W.accessSecret)this.accessToken=W.accessToken,this.accessSecret=W.accessSecret;this._oauth=this.buildOAuth()}else if(typeof W==="object"&&"username"in W){let Z=encodeURIComponent(W.username)+":"+encodeURIComponent(W.password);this.basicToken=Buffer.from(Z).toString("base64")}else if(typeof W==="object"&&"clientId"in W)this.clientId=W.clientId,this.clientSecret=W.clientSecret}getActiveTokens(){if(this.bearerToken)return{type:"oauth2",bearerToken:this.bearerToken};else if(this.basicToken)return{type:"basic",token:this.basicToken};else if(this.consumerSecret&&this._oauth)return{type:"oauth-1.0a",appKey:this.consumerToken,appSecret:this.consumerSecret,accessToken:this.accessToken,accessSecret:this.accessSecret};else if(this.clientId)return{type:"oauth2-user",clientId:this.clientId};return{type:"none"}}buildOAuth(){if(!this.consumerSecret||!this.consumerToken)throw Error("Invalid consumer tokens");return new f1({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(!this.accessSecret||!this.accessToken)return;return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var W;return(W=this.clientSettings.plugins)!==null&&W!==void 0?W:[]}hasPlugins(){var W;return!!((W=this.clientSettings.plugins)===null||W===void 0?void 0:W.length)}async applyPluginMethod(W,Z){var $;let J;for(let Q of this.getPlugins()){let Y=await(($=Q[W])===null||$===void 0?void 0:$.call(Q,Z));if(Y&&Y instanceof S1)J=Y}return J}writeAuthHeaders({headers:W,bodyInSignature:Z,url:$,method:J,query:Q,body:Y}){if(W={...W},this.bearerToken)W.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)W.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)W.Authorization="Basic "+a.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let K=Z?R.mergeQueryAndBodyForOAuth(Q,Y):Q,G=this._oauth.authorize({url:$.toString(),method:J,data:K},this.getOAuthAccessTokens());W={...W,...this._oauth.toHeader(G)}}return W}getUrlObjectFromUrlString(W){if(!W.startsWith("http"))W="https://"+W;return new URL(W)}getHttpRequestArgs({url:W,method:Z,query:$={},body:J={},headers:Q,forceBodyMode:Y,enableAuth:K,params:G}){let X=void 0;if(Z=Z.toUpperCase(),Q=Q!==null&&Q!==void 0?Q:{},!Q["x-user-agent"])Q["x-user-agent"]="Node.twitter-api-v2";let z=this.getUrlObjectFromUrlString(W),B=z.origin+z.pathname;if(G)R.applyRequestParametersToUrl(z,G);let j=R.formatQueryToString($);if(R.moveUrlQueryParamsIntoObject(z,j),!(J instanceof Buffer))x6(J);let x=Y!==null&&Y!==void 0?Y:R.autoDetectBodyType(z);if(K!==!1){let O=J1.BODY_METHODS.has(Z)&&x==="url";Q=this.writeAuthHeaders({headers:Q,bodyInSignature:O,method:Z,query:j,url:z,body:J})}if(J1.BODY_METHODS.has(Z))X=R.constructBodyParams(J,Q,x)||void 0;return R.addQueryParamsToUrl(z,j),{rawUrl:B,url:z,method:Z,headers:Q,body:X}}async applyPreRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let J of this.getPlugins()){let Q=await((Z=J.onBeforeRequestConfig)===null||Z===void 0?void 0:Z.call(J,{client:this,url:$,params:W}));if(Q)return Q}}applyPreStreamRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let J of this.getPlugins())(Z=J.onBeforeStreamRequestConfig)===null||Z===void 0||Z.call(J,{client:this,url:$,params:W})}async applyPreRequestHooks(W,Z,$){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$})}async applyPostRequestHooks(W,Z,$,J){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,response:J})}applyResponseErrorHooks(W,Z,$,J){return J.catch(R6.bind(this,W,Z,$))}}J1.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class c{constructor(W,Z={}){if(this._currentUser=null,this._currentUserV2=null,W instanceof c)this._requestMaker=W._requestMaker;else this._requestMaker=new J1(Z),this._requestMaker.initializeToken(W)}setPrefix(W){this._prefix=W}cloneWithPrefix(W){let Z=this.constructor(this);return Z.setPrefix(W),Z}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(W){return this.getPlugins().find((Z)=>Z instanceof W)}hasHitRateLimit(W){var Z;if(this.isRateLimitStatusObsolete(W))return!1;return((Z=this.getLastRateLimitStatus(W))===null||Z===void 0?void 0:Z.remaining)===0}isRateLimitStatusObsolete(W){let Z=this.getLastRateLimitStatus(W);if(Z===void 0)return!0;return Z.reset*1000<Date.now()}getLastRateLimitStatus(W){let Z=W.match(/^https?:\/\//)?W:this._prefix+W;return this._requestMaker.getRateLimits()[Z]}getCurrentUserObject(W=!1){if(!W&&this._currentUser){if(this._currentUser.value)return Promise.resolve(this._currentUser.value);return this._currentUser.promise}return this._currentUser=q4(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:E})),this._currentUser.promise}getCurrentUserV2Object(W=!1){if(!W&&this._currentUserV2){if(this._currentUserV2.value)return Promise.resolve(this._currentUserV2.value);return this._currentUserV2.promise}return this._currentUserV2=q4(()=>this.get("users/me",void 0,{prefix:g})),this._currentUserV2.promise}async get(W,Z={},{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"GET",query:Z,...Q});return $?Y:Y.data}async delete(W,Z={},{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"DELETE",query:Z,...Q});return $?Y:Y.data}async post(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"POST",body:Z,...Q});return $?Y:Y.data}async put(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"PUT",body:Z,...Q});return $?Y:Y.data}async patch(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"PATCH",body:Z,...Q});return $?Y:Y.data}getStream(W,Z,{prefix:$=this._prefix,...J}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"GET",query:Z,...J})}postStream(W,Z,{prefix:$=this._prefix,...J}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"POST",body:Z,...J})}}class _ extends c{constructor(W){if(!(W instanceof c))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(W)}}class Q1 extends $1{constructor(){super(...arguments);this.hasFinishedFetch=!1}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.push(...$),this.hasFinishedFetch=$.length===0}getNextQueryParams(W){let Z=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(W),max_id:(Z-BigInt(1)).toString()}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class A4 extends Q1{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class h4 extends Q1{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class d1 extends Q1{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class g4 extends Q1{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class l1 extends Q1{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class E4 extends D{constructor(){super(...arguments);this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class m4 extends D{constructor(){super(...arguments);this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class c4 extends D{constructor(){super(...arguments);this._endpoint="followers/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class u4 extends D{constructor(){super(...arguments);this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class p4 extends D{constructor(){super(...arguments);this._endpoint="friends/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class d4 extends D{constructor(){super(...arguments);this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class l4 extends $1{constructor(){super(...arguments);this._endpoint="users/search.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.push(...$)}getNextQueryParams(W){var Z;let $=Number((Z=this._queryParams.page)!==null&&Z!==void 0?Z:"1");return{...this._queryParams,page:$+1,...W?{count:W}:{}}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.users}get users(){return this._realData}}class n1 extends D{constructor(){super(...arguments);this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class n4 extends n1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class i1 extends D{refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.lists.push(...$.lists),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class i4 extends i1{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class s4 extends i1{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class o4 extends i1{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class a4 extends D{refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class t4 extends a4{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class r4 extends a4{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class Y1 extends _{constructor(){super(...arguments);this._prefix=E}singleTweet(W,Z={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:W,...Z})}tweets(W,Z={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:W,...Z})}oembedTweet(W,Z={}){return this.get("oembed",{url:`https://x.com/i/statuses/${W}`,...Z},{prefix:"https://publish.x.com/"})}async homeTimeline(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("statuses/home_timeline.json",Z,{fullResponse:!0});return new A4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async mentionTimeline(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("statuses/mentions_timeline.json",Z,{fullResponse:!0});return new h4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},J=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new d1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async userTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},J=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new d1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async favoriteTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},J=await this.get("favorites/list.json",$,{fullResponse:!0});return new l1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async favoriteTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},J=await this.get("favorites/list.json",$,{fullResponse:!0});return new l1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}user(W){return this.get("users/show.json",{tweet_mode:"extended",...W})}users(W){return this.get("users/lookup.json",{tweet_mode:"extended",...W})}verifyCredentials(W={}){return this.get("account/verify_credentials.json",W)}async listMutedUsers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("mutes/users/list.json",Z,{fullResponse:!0});return new E4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listMutedUserIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("mutes/users/ids.json",Z,{fullResponse:!0});return new m4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFriendList(W={}){let Z={...W},$=await this.get("friends/list.json",Z,{fullResponse:!0});return new p4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowerList(W={}){let Z={...W},$=await this.get("followers/list.json",Z,{fullResponse:!0});return new c4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowerIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("followers/ids.json",Z,{fullResponse:!0});return new u4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowingIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friends/ids.json",Z,{fullResponse:!0});return new d4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async searchUsers(W,Z={}){let $={q:W,tweet_mode:"extended",page:1,...Z},J=await this.get("users/search.json",$,{fullResponse:!0});return new l4({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}friendship(W){return this.get("friendships/show.json",W)}friendships(W){return this.get("friendships/lookup.json",W)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friendships/incoming.json",Z,{fullResponse:!0});return new n1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async friendshipsOutgoing(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friendships/outgoing.json",Z,{fullResponse:!0});return new n4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(W){return this.get("users/profile_banner.json",W)}list(W){return this.get("lists/show.json",{tweet_mode:"extended",...W})}lists(W={}){return this.get("lists/list.json",{tweet_mode:"extended",...W})}async listMembers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/members.json",Z,{fullResponse:!0});return new t4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}listGetMember(W){return this.get("lists/members/show.json",{tweet_mode:"extended",...W})}async listMemberships(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/memberships.json",Z,{fullResponse:!0});return new i4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listOwnerships(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/ownerships.json",Z,{fullResponse:!0});return new s4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listStatuses(W){let Z={tweet_mode:"extended",...W},$=await this.get("lists/statuses.json",Z,{fullResponse:!0});return new g4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listSubscribers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/subscribers.json",Z,{fullResponse:!0});return new r4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}listGetSubscriber(W){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...W})}async listSubscriptions(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/subscriptions.json",Z,{fullResponse:!0});return new o4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}mediaInfo(W){return this.get("media/upload.json",{command:"STATUS",media_id:W},{prefix:A})}filterStream({autoConnect:W,...Z}={}){let $={};for(let[Q,Y]of Object.entries(Z))if(Q==="follow"||Q==="track")$[Q]=Y.toString();else if(Q==="locations"){let K=Y;$.locations=m1(K).map((G)=>`${G.lng},${G.lat}`).join(",")}else $[Q]=Y;return this.stream.postStream("statuses/filter.json",$,{autoConnect:W})}sampleStream({autoConnect:W,...Z}={}){return this.stream.getStream("statuses/sample.json",Z,{autoConnect:W})}get stream(){let W=new s1(this);return W.setPrefix(M6),W}trendsByPlace(W,Z={}){return this.get("trends/place.json",{id:W,...Z})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(W,Z){return this.get("trends/closest.json",{lat:W,long:Z})}geoPlace(W){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:W}})}geoSearch(W){return this.get("geo/search.json",W)}geoReverseGeoCode(W){return this.get("geo/reverse_geocode.json",W)}rateLimitStatuses(...W){return this.get("application/rate_limit_status.json",{resources:W})}supportedLanguages(){return this.get("help/languages.json")}}import*as u from"fs";async function e4(W){let Z=await W0(W);if(typeof Z==="number")return new Promise(($,J)=>{u.readFile(Z,(Q,Y)=>{if(Q)return J(Q);$(Y)})});else if(Z instanceof Buffer)return Z;else return Z.readFile()}function W0(W){if(typeof W==="string")return u.promises.open(W,"r");else if(typeof W==="number")return W;else if(typeof W==="object"&&!(W instanceof Buffer))return W;else if(!(W instanceof Buffer))throw Error("Given file is not valid, please check its type.");else return W}async function b6(W){if(typeof W==="number")return(await new Promise(($,J)=>{u.fstat(W,(Q,Y)=>{if(Q)J(Q);$(Y)})})).size;else if(W instanceof Buffer)return W.length;else return(await W.stat()).size}function T6(W,Z,$){if(typeof $==="string")return $;else if(typeof W==="string"&&!Z)return kW(W);else if(typeof Z==="string")return bW(Z);throw Error("You must specify type if file is a file handle or Buffer.")}function kW(W){if(W.endsWith(".jpeg")||W.endsWith(".jpg"))return F.Jpeg;if(W.endsWith(".png"))return F.Png;if(W.endsWith(".webp"))return F.Webp;if(W.endsWith(".gif"))return F.Gif;if(W.endsWith(".mpeg4")||W.endsWith(".mp4"))return F.Mp4;if(W.endsWith(".mov")||W.endsWith(".mov"))return F.Mov;if(W.endsWith(".srt"))return F.Srt;return w4({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"options.mimeType is missing and filename couldn't help to resolve MIME type, so it will fallback to image/jpeg",resolution:"If you except to give filenames without extensions, please specify explicitlty the MIME type using options.mimeType"}),F.Jpeg}function bW(W){if(w4({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"you're using options.type",resolution:"Remove options.type argument and migrate to options.mimeType which takes the real MIME type. If you're using type=longmp4, add options.longVideo alongside of mimeType=EUploadMimeType.Mp4"}),W==="gif")return F.Gif;if(W==="jpg")return F.Jpeg;if(W==="png")return F.Png;if(W==="webp")return F.Webp;if(W==="srt")return F.Srt;if(W==="mp4"||W==="longmp4")return F.Mp4;if(W==="mov")return F.Mov;return W}function P6(W,Z){if(W===F.Mp4||W===F.Mov)return Z==="tweet"?"TweetVideo":"DmVideo";if(W===F.Gif)return Z==="tweet"?"TweetGif":"DmGif";if(W===F.Srt)return"Subtitles";else return Z==="tweet"?"TweetImage":"DmImage"}function Z0(W){return new Promise((Z)=>setTimeout(Z,W*1000))}async function $0(W,Z,$=0,J){if(W instanceof Buffer){let Y=W.slice($,$+Z);return[Y,Y.length]}if(!J)throw Error("Well, we will need a buffer to store file content.");let Q;if(typeof W==="number")Q=await new Promise((Y,K)=>{u.read(W,J,0,Z,$,(G,X)=>{if(G)K(G);Y(X)})});else Q=(await W.read(J,0,Z,$)).bytesRead;return[J,Q]}var J0="media/upload.json";class K1 extends Y1{constructor(){super(...arguments);this._prefix=E}get readOnly(){return this}tweet(W,Z={}){let $={status:W,tweet_mode:"extended",...Z};return this.post("statuses/update.json",$)}async quote(W,Z,$={}){let J="https://x.com/i/statuses/"+Z;return this.tweet(W,{...$,attachment_url:J})}async tweetThread(W){let Z=[];for(let $ of W){let J=Z.length?Z[Z.length-1]:null,Q={...typeof $==="string"?{status:$}:$},Y=J?J.id_str:Q.in_reply_to_status_id,K=Q.status;if(Y)Z.push(await this.reply(K,Y,Q));else Z.push(await this.tweet(K,Q))}return Z}reply(W,Z,$={}){return this.tweet(W,{auto_populate_reply_metadata:!0,in_reply_to_status_id:Z,...$})}deleteTweet(W){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:W}})}reportUserAsSpam(W){return this.post("users/report_spam.json",{tweet_mode:"extended",...W})}updateFriendship(W){return this.post("friendships/update.json",W)}createFriendship(W){return this.post("friendships/create.json",W)}destroyFriendship(W){return this.post("friendships/destroy.json",W)}updateAccountSettings(W){return this.post("account/settings.json",W)}updateAccountProfile(W){return this.post("account/update_profile.json",W)}async updateAccountProfileBanner(W,Z={}){let $={banner:await e4(W),...Z};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,Z={}){let $={tweet_mode:"extended",image:await e4(W),...Z};return this.post("account/update_profile_image.json",$,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(W){return this.post("lists/create.json",{tweet_mode:"extended",...W})}updateList(W){return this.post("lists/update.json",{tweet_mode:"extended",...W})}removeList(W){return this.post("lists/destroy.json",{tweet_mode:"extended",...W})}addListMembers(W){let $=W.user_id&&R1(W.user_id)||W.screen_name&&R1(W.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,W)}removeListMembers(W){let $=W.user_id&&R1(W.user_id)||W.screen_name&&R1(W.screen_name)?"lists/members/destroy_all.json":"lists/members/destroy.json";return this.post($,W)}subscribeToList(W){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...W})}unsubscribeOfList(W){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...W})}createMediaMetadata(W,Z){return this.post("media/metadata/create.json",{media_id:W,...Z},{prefix:A,forceBodyMode:"json"})}createMediaSubtitles(W,Z){return this.post("media/subtitles/create.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z}},{prefix:A,forceBodyMode:"json"})}deleteMediaSubtitles(W,...Z){return this.post("media/subtitles/delete.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z.map(($)=>({language_code:$}))}},{prefix:A,forceBodyMode:"json"})}async uploadMedia(W,Z={},$=!1){var J;let Q=(J=Z.chunkLength)!==null&&J!==void 0?J:1048576,{fileHandle:Y,mediaCategory:K,fileSize:G,mimeType:X}=await this.getUploadMediaRequirements(W,Z);try{let z=await this.post(J0,{command:"INIT",total_bytes:G,media_type:X,media_category:K,additional_owners:Z.additionalOwners,shared:Z.shared?!0:void 0},{prefix:A});await this.mediaChunkedUpload(Y,Q,z.media_id_string,Z.maxConcurrentUploads);let B=await this.post(J0,{command:"FINALIZE",media_id:z.media_id_string},{prefix:A});if(B.processing_info&&B.processing_info.state!=="succeeded")await this.awaitForMediaProcessingCompletion(B);if($)return B;else return B.media_id_string}finally{if(typeof W==="number")Q0.close(W,()=>{});else if(typeof Y==="object"&&!(Y instanceof Buffer))Y.close()}}async awaitForMediaProcessingCompletion(W){var Z;while(!0){W=await this.mediaInfo(W.media_id_string);let{processing_info:$}=W;if(!$||$.state==="succeeded")return;if((Z=$.error)===null||Z===void 0?void 0:Z.code){let{name:J,message:Q}=$.error;throw Error(`Failed to process media: ${J} - ${Q}.`)}if($.state==="failed")throw Error("Failed to process the media.");if($.check_after_secs)await Z0($.check_after_secs);else await Z0(5)}}async getUploadMediaRequirements(W,{mimeType:Z,type:$,target:J,longVideo:Q}={}){let Y;try{Y=await W0(W);let K=T6(W,$,Z),G;if(K===F.Mp4&&(!Z&&!$&&J!=="dm"||Q))G="amplify_video";else G=P6(K,J!==null&&J!==void 0?J:"tweet");return{fileHandle:Y,mediaCategory:G,fileSize:await b6(Y),mimeType:K}}catch(K){if(typeof W==="number")Q0.close(W,()=>{});else if(typeof Y==="object"&&!(Y instanceof Buffer))Y.close();throw K}}async mediaChunkedUpload(W,Z,$,J=3){let Q=0;if(J<1)throw RangeError("Bad maxConcurrentUploads parameter.");let Y=W instanceof Buffer?void 0:Buffer.alloc(Z),K,G,X=0;[K,G]=await $0(W,Z,X,Y),X+=G;let z=new Set;while(G){let B=K.slice(0,G);if(B.length){let j=this.post(J0,{command:"APPEND",media_id:$,segment_index:Q,media:B},{prefix:A});z.add(j),j.then(()=>{z.delete(j)}),Q++}if(z.size>=J)await Promise.race(z);[K,G]=await $0(W,Z,X,Y),X+=G}await Promise.all([...z])}}class V6 extends K1{constructor(){super(...arguments);this._prefix=E}get readWrite(){return this}sendDm({recipient_id:W,custom_profile_id:Z,...$}){let J={event:{type:m.Create,[m.Create]:{target:{recipient_id:W},message_data:$}}};if(Z)J.event[m.Create].custom_profile_id=Z;return this.post("direct_messages/events/new.json",J,{forceBodyMode:"json"})}getDmEvent(W){return this.get("direct_messages/events/show.json",{id:W})}deleteDm(W){return this.delete("direct_messages/events/destroy.json",{id:W})}async listDmEvents(W={}){let Z={...W},$=await this.get("direct_messages/events/list.json",Z,{fullResponse:!0});return new I4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDm(W,Z){let $={[m.WelcomeCreate]:{name:W,message_data:Z}};return this.post("direct_messages/welcome_messages/new.json",$,{forceBodyMode:"json"})}getWelcomeDm(W){return this.get("direct_messages/welcome_messages/show.json",{id:W})}deleteWelcomeDm(W){return this.delete("direct_messages/welcome_messages/destroy.json",{id:W})}updateWelcomeDm(W,Z){let $={message_data:Z};return this.put("direct_messages/welcome_messages/update.json",$,{forceBodyMode:"json",query:{id:W}})}async listWelcomeDms(W={}){let Z={...W},$=await this.get("direct_messages/welcome_messages/list.json",Z,{fullResponse:!0});return new v4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDmRule(W){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:W}},{forceBodyMode:"json"})}getWelcomeDmRule(W){return this.get("direct_messages/welcome_messages/rules/show.json",{id:W})}deleteWelcomeDmRule(W){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:W})}async listWelcomeDmRules(W={}){let Z={...W};return this.get("direct_messages/welcome_messages/rules/list.json",Z)}async setWelcomeDm(W,Z=!0){var $;let J=await this.listWelcomeDmRules();if(($=J.welcome_message_rules)===null||$===void 0?void 0:$.length){for(let Q of J.welcome_message_rules)if(await this.deleteWelcomeDmRule(Q.id),Z)await this.deleteWelcomeDm(Q.welcome_message_id)}return this.newWelcomeDmRule(W)}markDmAsRead(W,Z){return this.post("direct_messages/mark_read.json",{last_read_event_id:W,recipient_id:Z},{forceBodyMode:"url"})}indicateDmTyping(W){return this.post("direct_messages/indicate_typing.json",{recipient_id:W},{forceBodyMode:"url"})}async downloadDmImage(W){if(typeof W!=="string"){let $=W[m.Create].message_data.attachment;if(!$)throw Error("The given direct message doesn't contain any attachment");W=$.media.media_url_https}let Z=await this.get(W,void 0,{forceParseMode:"buffer",prefix:""});if(!Z.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return Z}}var s1=V6;class N{constructor(W){this.result=W}get tweets(){return N.tweets(this.result)}static tweets(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.tweets)!==null&&$!==void 0?$:[]}tweetById(W){return N.tweetById(this.result,W)}static tweetById(W,Z){return this.tweets(W).find(($)=>$.id===Z)}retweet(W){return N.retweet(this.result,W)}static retweet(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="retweeted").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}quote(W){return N.quote(this.result,W)}static quote(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="quoted").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}repliedTo(W){return N.repliedTo(this.result,W)}static repliedTo(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="replied_to").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}author(W){return N.author(this.result,W)}static author(W,Z){let $=Z.author_id;return $?this.users(W).find((J)=>J.id===$):void 0}repliedToAuthor(W){return N.repliedToAuthor(this.result,W)}static repliedToAuthor(W,Z){let $=Z.in_reply_to_user_id;return $?this.users(W).find((J)=>J.id===$):void 0}get users(){return N.users(this.result)}static users(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.users)!==null&&$!==void 0?$:[]}userById(W){return N.userById(this.result,W)}static userById(W,Z){return this.users(W).find(($)=>$.id===Z)}pinnedTweet(W){return N.pinnedTweet(this.result,W)}static pinnedTweet(W,Z){return Z.pinned_tweet_id?this.tweets(W).find(($)=>$.id===Z.pinned_tweet_id):void 0}get media(){return N.media(this.result)}static media(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.media)!==null&&$!==void 0?$:[]}medias(W){return N.medias(this.result,W)}static medias(W,Z){var $,J;let Q=(J=($=Z.attachments)===null||$===void 0?void 0:$.media_keys)!==null&&J!==void 0?J:[];return this.media(W).filter((Y)=>Q.includes(Y.media_key))}get polls(){return N.polls(this.result)}static polls(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.polls)!==null&&$!==void 0?$:[]}poll(W){return N.poll(this.result,W)}static poll(W,Z){var $,J;let Q=(J=($=Z.attachments)===null||$===void 0?void 0:$.poll_ids)!==null&&J!==void 0?J:[];if(Q.length){let Y=Q[0];return this.polls(W).find((K)=>K.id===Y)}return}get places(){return N.places(this.result)}static places(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.places)!==null&&$!==void 0?$:[]}place(W){return N.place(this.result,W)}static place(W,Z){var $;let J=($=Z.geo)===null||$===void 0?void 0:$.place_id;return J?this.places(W).find((Q)=>Q.id===J):void 0}listOwner(W){return N.listOwner(this.result,W)}static listOwner(W,Z){let $=Z.owner_id;return $?this.users(W).find((J)=>J.id===$):void 0}spaceCreator(W){return N.spaceCreator(this.result,W)}static spaceCreator(W,Z){let $=Z.creator_id;return $?this.users(W).find((J)=>J.id===$):void 0}spaceHosts(W){return N.spaceHosts(this.result,W)}static spaceHosts(W,Z){var $;let J=($=Z.host_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}spaceSpeakers(W){return N.spaceSpeakers(this.result,W)}static spaceSpeakers(W,Z){var $;let J=($=Z.speaker_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}spaceInvitedUsers(W){return N.spaceInvitedUsers(this.result,W)}static spaceInvitedUsers(W,Z){var $;let J=($=Z.invited_user_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}}class o1 extends V4{updateIncludes(W){if(W.errors){if(!this._realData.errors)this._realData.errors=[];this._realData.errors=[...this._realData.errors,...W.errors]}if(!W.includes)return;if(!this._realData.includes)this._realData.includes={};let Z=this._realData.includes;for(let[$,J]of Object.entries(W.includes)){if(!Z[$])Z[$]=[];Z[$]=[...Z[$],...J]}}assertUsable(){if(this.unusable)throw Error("Unable to use this paginator to fetch more data, as it does not contain any metadata. Check .errors property for more details.")}get meta(){return this._realData.meta}get includes(){var W;if(!((W=this._realData)===null||W===void 0?void 0:W.includes))return new N(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new N(this._realData)}get errors(){var W;return(W=this._realData.errors)!==null&&W!==void 0?W:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class v extends o1{refreshInstanceFromResult(W,Z){var $;let J=W.data,Q=($=J.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.next_token=J.meta.next_token,this._realData.data.push(...Q);else this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.previous_token=J.meta.previous_token,this._realData.data.unshift(...Q);this.updateIncludes(J)}getNextQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(W){var Z,$;return($=(Z=W.data.data)===null||Z===void 0?void 0:Z.length)!==null&&$!==void 0?$:0}isFetchLastOver(W){var Z;return!((Z=W.data.data)===null||Z===void 0?void 0:Z.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){var Z;return!!((Z=W.meta)===null||Z===void 0?void 0:Z.next_token)}}class Y0 extends o1{refreshInstanceFromResult(W,Z){var $;let J=W.data,Q=($=J.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.oldest_id=J.meta.oldest_id,this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.next_token=J.meta.next_token,this._realData.data.push(...Q);else this._realData.meta.newest_id=J.meta.newest_id,this._realData.meta.result_count+=J.meta.result_count,this._realData.data.unshift(...Q);this.updateIncludes(J)}getNextQueryParams(W){this.assertUsable();let Z={...this.injectQueryParams(W)};if(this._realData.meta.next_token)Z.next_token=this._realData.meta.next_token;else{if(Z.start_time)Z.since_id=this.dateStringToSnowflakeId(Z.start_time),delete Z.start_time;if(Z.end_time)delete Z.end_time;Z.until_id=this._realData.meta.oldest_id}return Z}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(W){var Z,$;return($=(Z=W.data.data)===null||Z===void 0?void 0:Z.length)!==null&&$!==void 0?$:0}isFetchLastOver(W){var Z;return!((Z=W.data.data)===null||Z===void 0?void 0:Z.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!!W.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(W){let Z=BigInt("1288834974657"),$=new Date(W);if(isNaN($.valueOf()))throw Error("Unable to convert start_time/end_time to a valid date. A ISO 8601 DateTime is excepted, please check your input.");return(BigInt($.valueOf())-Z<<BigInt("22")).toString()}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class G1 extends v{refreshInstanceFromResult(W,Z){super.refreshInstanceFromResult(W,Z);let $=W.data;if(Z)this._realData.meta.oldest_id=$.meta.oldest_id;else this._realData.meta.newest_id=$.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class K0 extends Y0{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class G0 extends Y0{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class z0 extends G1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class X0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class B0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class j0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class M0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class L0 extends v{get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class N0 extends L0{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class x0 extends L0{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class h extends v{getItemArray(){return this.users}get users(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class F0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class D0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class H0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class U0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class O0 extends h{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class S0 extends h{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class R0 extends h{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class _0 extends h{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class a1 extends v{getItemArray(){return this.lists}get lists(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class f0 extends a1{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class C0 extends a1{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class k0 extends a1{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class z1 extends _{constructor(){super(...arguments);this._prefix=e}}class t1 extends v{getItemArray(){return this.events}get events(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class b0 extends t1{constructor(){super(...arguments);this._endpoint="dm_events"}}class T0 extends t1{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class P0 extends t1{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class X1 extends _{constructor(){super(...arguments);this._prefix=g}get labs(){if(this._labs)return this._labs;return this._labs=new z1(this)}async search(W,Z={}){let $=typeof W==="string"?{...Z,query:W}:{...W},J=await this.get("tweets/search/recent",$,{fullResponse:!0});return new K0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async searchAll(W,Z={}){let $={...Z,query:W},J=await this.get("tweets/search/all",$,{fullResponse:!0});return new G0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}singleTweet(W,Z={}){return this.get("tweets/:id",Z,{params:{id:W}})}tweets(W,Z={}){return this.get("tweets",{ids:W,...Z})}tweetCountRecent(W,Z={}){return this.get("tweets/counts/recent",{query:W,...Z})}tweetCountAll(W,Z={}){return this.get("tweets/counts/all",{query:W,...Z})}async tweetRetweetedBy(W,Z={}){let{asPaginator:$,...J}=Z,Q=await this.get("tweets/:id/retweeted_by",J,{fullResponse:!0,params:{id:W}});if(!$)return Q.data;return new _0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async tweetLikedBy(W,Z={}){let{asPaginator:$,...J}=Z,Q=await this.get("tweets/:id/liking_users",J,{fullResponse:!0,params:{id:W}});if(!$)return Q.data;return new R0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async homeTimeline(W={}){let Z=await this.getCurrentUserV2Object(),$=await this.get("users/:id/timelines/reverse_chronological",W,{fullResponse:!0,params:{id:Z.data.id}});return new X0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:Z.data.id}})}async userTimeline(W,Z={}){let $=await this.get("users/:id/tweets",Z,{fullResponse:!0,params:{id:W}});return new B0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async userMentionTimeline(W,Z={}){let $=await this.get("users/:id/mentions",Z,{fullResponse:!0,params:{id:W}});return new j0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async quotes(W,Z={}){let $=await this.get("tweets/:id/quote_tweets",Z,{fullResponse:!0,params:{id:W}});return new z0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async bookmarks(W={}){let Z=await this.getCurrentUserV2Object(),$=await this.get("users/:id/bookmarks",W,{fullResponse:!0,params:{id:Z.data.id}});return new M0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:Z.data.id}})}me(W={}){return this.get("users/me",W)}user(W,Z={}){return this.get("users/:id",Z,{params:{id:W}})}users(W,Z={}){let $=Array.isArray(W)?W.join(","):W;return this.get("users",{...Z,ids:$})}userByUsername(W,Z={}){return this.get("users/by/username/:username",Z,{params:{username:W}})}usersByUsernames(W,Z={}){return W=Array.isArray(W)?W.join(","):W,this.get("users/by",{...Z,usernames:W})}async followers(W,Z={}){let{asPaginator:$,...J}=Z,Q={id:W};if(!$)return this.get("users/:id/followers",J,{params:Q});let Y=await this.get("users/:id/followers",J,{fullResponse:!0,params:Q});return new H0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:J,sharedParams:Q})}async following(W,Z={}){let{asPaginator:$,...J}=Z,Q={id:W};if(!$)return this.get("users/:id/following",J,{params:Q});let Y=await this.get("users/:id/following",J,{fullResponse:!0,params:Q});return new U0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:J,sharedParams:Q})}async userLikedTweets(W,Z={}){let $={id:W},J=await this.get("users/:id/liked_tweets",Z,{fullResponse:!0,params:$});return new N0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userBlockingUsers(W,Z={}){let $={id:W},J=await this.get("users/:id/blocking",Z,{fullResponse:!0,params:$});return new F0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userMutingUsers(W,Z={}){let $={id:W},J=await this.get("users/:id/muting",Z,{fullResponse:!0,params:$});return new D0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}list(W,Z={}){return this.get("lists/:id",Z,{params:{id:W}})}async listsOwned(W,Z={}){let $={id:W},J=await this.get("users/:id/owned_lists",Z,{fullResponse:!0,params:$});return new f0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMemberships(W,Z={}){let $={id:W},J=await this.get("users/:id/list_memberships",Z,{fullResponse:!0,params:$});return new C0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowed(W,Z={}){let $={id:W},J=await this.get("users/:id/followed_lists",Z,{fullResponse:!0,params:$});return new k0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listTweets(W,Z={}){let $={id:W},J=await this.get("lists/:id/tweets",Z,{fullResponse:!0,params:$});return new x0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMembers(W,Z={}){let $={id:W},J=await this.get("lists/:id/members",Z,{fullResponse:!0,params:$});return new O0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowers(W,Z={}){let $={id:W},J=await this.get("lists/:id/followers",Z,{fullResponse:!0,params:$});return new S0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEvents(W={}){let Z=await this.get("dm_events",W,{fullResponse:!0});return new b0({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:{...W}})}async listDmEventsWithParticipant(W,Z={}){let $={participant_id:W},J=await this.get("dm_conversations/with/:participant_id/dm_events",Z,{fullResponse:!0,params:$});return new T0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEventsOfConversation(W,Z={}){let $={dm_conversation_id:W},J=await this.get("dm_conversations/:dm_conversation_id/dm_events",Z,{fullResponse:!0,params:$});return new P0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}space(W,Z={}){return this.get("spaces/:id",Z,{params:{id:W}})}spaces(W,Z={}){return this.get("spaces",{ids:W,...Z})}spacesByCreators(W,Z={}){return this.get("spaces/by/creator_ids",{user_ids:W,...Z})}searchSpaces(W){return this.get("spaces/search",W)}spaceBuyers(W,Z={}){return this.get("spaces/:id/buyers",Z,{params:{id:W}})}spaceTweets(W,Z={}){return this.get("spaces/:id/tweets",Z,{params:{id:W}})}searchStream({autoConnect:W,...Z}={}){return this.getStream("tweets/search/stream",Z,{payloadIsError:c1,autoConnect:W})}streamRules(W={}){return this.get("tweets/search/stream/rules",W)}updateStreamRules(W,Z={}){return this.post("tweets/search/stream/rules",W,{query:Z})}sampleStream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample/stream",Z,{payloadIsError:c1,autoConnect:W})}sample10Stream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample10/stream",Z,{payloadIsError:c1,autoConnect:W})}complianceJobs(W){return this.get("compliance/jobs",W)}complianceJob(W){return this.get("compliance/jobs/:id",void 0,{params:{id:W}})}async sendComplianceJob(W){let Z=await this.post("compliance/jobs",{type:W.type,name:W.name}),$=W.ids instanceof Buffer?W.ids:Buffer.from(W.ids.join(`
|
|
64
|
+
</html>`}function e0(W){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Authorization failed</title></head><body style="font-family: system-ui, sans-serif; padding: 24px"><h1 style="font-size: 1.2rem">This connection could not be authorized</h1><p>${V(W)}</p></body></html>`}function V(W){return W.replace(/[&<>"']/g,(Z)=>`&#${Z.charCodeAt(0)};`)}var U4="gmcp_at_",O4="gmcp_rt_",W6="gmcp_ac_",xW="gmcp_c_",UW="gmcp_cs_",S4="gemi.mcp.oauth.ticket.v1",Z6="gemi.mcp.oauth.consent.v1",OW=600000,$6=120000,V4=16384,SW={limit:20,window:3600},RW={limit:60,window:60},A1=["none","client_secret_post","client_secret_basic"];class M extends Error{error;description;status;headers;constructor(W,Z,$=400,J={}){super(Z);this.error=W;this.description=Z;this.status=$;this.headers=J}}class F6{options;name="oauth";context;issuer;base;accessTtl;refreshTtl;constructor(W){this.options=W;let Z=W?.store;for(let $ of["createClient","findClient","saveCode","findCode","saveToken","findToken","use","revokeFamily"])if(typeof Z?.[$]!=="function")throw Error(`McpOAuthServer: store.${$} is missing. Use MemoryMcpOAuthStore, or implement McpOAuthStore.`);if(typeof W.findUser!=="function")throw Error("McpOAuthServer: findUser(id) is required: it loads the user a token was issued to.");if(W.consentPath!==void 0&&!/^\/[^/\\]/.test(W.consentPath))throw Error('McpOAuthServer: consentPath must be a path on this app, like "/oauth/consent".');this.accessTtl=J6("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=J6("refreshTokenTtl",W.refreshTokenTtl,2592000)}get store(){return this.options.store}boot(W){this.context=W;let Z=new URL(W.resource);this.issuer=Z.origin,this.base=`${Z.pathname}/oauth`}async resolve(W){let Z=P4(W);if(!Z?.startsWith(U4))return null;let $=await this.store.findToken(g(Z)),J=(Y)=>({ok:!1,error:"invalid_token",description:Y});if(!$||$.kind!=="access")return J("The access token is not valid.");if($.expiresAt<=Date.now())return J("The access token expired.");if($.resource!==this.context.resource)return J("The access token was not issued for this server.");let Q=await this.options.findUser($.userId);if(!Q)return J("The access token is not valid.");return{ok:!0,principal:{user:Q,via:this.name,id:$.familyId,scopes:$.scopes,clientId:$.clientId}}}challenge(){let W=this.scopeNames().join(" ");return`Bearer resource_metadata="${this.resourceMetadataUrl()}", scope="${W}"`}async handle(W){let Z=new URL(W.url).pathname,Q={[`/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-protected-resource"]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-authorization-server"]:{methods:["GET"],cors:!0,run:()=>this.serverMetadata()},[`${this.base}/register`]:{methods:["POST"],cors:!0,run:()=>this.register(W)},[`${this.base}/authorize`]:{methods:["GET"],cors:!1,run:()=>this.authorize(W)},[`${this.base}/consent`]:{methods:["GET","POST"],cors:!1,run:()=>W.method==="POST"?this.decide(W):this.consentScreen(W)},[`${this.base}/token`]:{methods:["POST"],cors:!0,run:()=>this.token(W)},[`${this.base}/revoke`]:{methods:["POST"],cors:!0,run:()=>this.revoke(W)}}[Z];if(!Q)return null;if(Z===`${this.base}/register`&&this.options.registration===!1)return null;let Y=Q.cors?_W:{};if(W.method==="OPTIONS"&&Q.cors)return new Response(null,{status:204,headers:{...Y,"Access-Control-Allow-Methods":Q.methods.join(", "),"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}});if(!Q.methods.includes(W.method))return new Response(null,{status:405,headers:{...Y,Allow:Q.methods.join(", ")}});let K;try{K=await Q.run()}catch(z){if(!(z instanceof M))throw z;K=H1({error:z.error,error_description:z.description},z.status,z.headers)}for(let[z,X]of Object.entries(Y))K.headers.set(z,X);return K}async consent(W,Z){if(!Z)return null;let $=h1(S4,"gat1",W);if(!$)return null;let J=await this.store.findClient($.c);if(!J||!J.redirectUris.some((z)=>_4(z,$.r)))return null;let Q=String(Z.id),Y=C4(Z6,"gcs1",{t:Q6(W),u:Q,exp:$.exp}),K=new Map(this.context.registry.scopes().map((z)=>[z.name,z.description]));return{client:{id:J.clientId,name:J.clientName,redirectHost:new URL($.r).host},scopes:$.s.map((z)=>({name:z,description:K.get(z)??z})),user:{id:Q,label:this.userLabel(Z)},form:{action:`${this.issuer}${this.base}/consent`,method:"POST",fields:{request:W,csrf:Y}}}}resourceMetadata(){return H1({resource:this.context.resource,authorization_servers:[this.issuer],scopes_supported:this.scopeNames(),bearer_methods_supported:["header"]})}serverMetadata(){return H1({issuer:this.issuer,authorization_endpoint:`${this.issuer}${this.base}/authorize`,token_endpoint:`${this.issuer}${this.base}/token`,...this.options.registration===!1?{}:{registration_endpoint:`${this.issuer}${this.base}/register`},revocation_endpoint:`${this.issuer}${this.base}/revoke`,scopes_supported:this.scopeNames(),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],token_endpoint_auth_methods_supported:A1,revocation_endpoint_auth_methods_supported:A1,code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,client_id_metadata_document_supported:!1})}async register(W){let Z=this.options.registration||{},$=await f4(`mcp-oauth-register:${j6(new k4(W,{},"api",`${this.base}/register`))}`,Z.rateLimit??SW);if($!==null)throw new M("slow_down","Too many registrations from this address.",429,{"Retry-After":String($)});if(!/^application\/json\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new M("invalid_client_metadata","Send the client metadata as application/json.");let J;try{J=JSON.parse(await T4(W,V4))}catch{throw new M("invalid_client_metadata","The client metadata is not JSON, or is too large.")}if(typeof J!=="object"||J===null||Array.isArray(J))throw new M("invalid_client_metadata","The client metadata must be a JSON object.");let Q=J.redirect_uris;if(!Array.isArray(Q)||Q.length===0||Q.length>10)throw new M("invalid_redirect_uri","redirect_uris must list one to ten URIs.");for(let N of Q){let S=CW(N);if(S)throw new M("invalid_redirect_uri",`${String(N).slice(0,200)}: ${S}`);if(Z.allowRedirectUri&&Z.allowRedirectUri(new URL(N))!==!0)throw new M("invalid_redirect_uri",`${N}: this server does not accept it.`)}let Y=J.token_endpoint_auth_method??"client_secret_basic";if(!A1.includes(Y))throw new M("invalid_client_metadata",`token_endpoint_auth_method must be one of ${A1.join(", ")}.`);let K=J.grant_types??["authorization_code"];if(!Array.isArray(K)||K.some((N)=>N!=="authorization_code"&&N!=="refresh_token"))throw new M("invalid_client_metadata","grant_types may only be authorization_code and refresh_token.");let z=J.response_types??["code"];if(!Array.isArray(z)||z.some((N)=>N!=="code"))throw new M("invalid_client_metadata","response_types may only be code.");let X=z6(J.client_name,100,"client_name"),G=z6(J.client_uri,512,"client_uri");if(G!==null&&!fW(G))throw new M("invalid_client_metadata","client_uri must be an https URL.");let B=Y==="none"?null:`${UW}${s(32).toString("base64url")}`,j={clientId:`${xW}${s(16).toString("base64url")}`,clientSecretHash:B?g(B):null,tokenEndpointAuthMethod:Y,redirectUris:[...Q],clientName:X,clientUri:G,createdAt:Date.now()};return await this.store.createClient(j),H1({client_id:j.clientId,client_id_issued_at:Math.floor(j.createdAt/1000),...B?{client_secret:B,client_secret_expires_at:0}:{},redirect_uris:j.redirectUris,token_endpoint_auth_method:Y,grant_types:K,response_types:z,...X?{client_name:X}:{},...G?{client_uri:G}:{}},201)}async authorize(W){let Z=new URL(W.url).searchParams;for(let U of new Set(Z.keys()))if(Z.getAll(U).length>1)return I(`The parameter ${U} was sent more than once.`);let $=Z.get("client_id"),J=$?await this.store.findClient($):null;if(!J)return I("The application is not registered with this server.");let Q=Z.get("redirect_uri")??(J.redirectUris.length===1?J.redirectUris[0]:null);if(!Q||!J.redirectUris.some((U)=>_4(U,Q)))return I("The redirect URI is not one the application registered.");let Y=Z.get("state"),K=(U,n)=>this.redirectBack(Q,Y,{error:U,error_description:n});if(Z.get("response_type")!=="code")return K("unsupported_response_type","Only response_type=code is supported.");let z=Z.get("code_challenge");if(Z.get("code_challenge_method")!=="S256"||!z||!/^[A-Za-z0-9_-]{43}$/.test(z))return K("invalid_request","PKCE is required: code_challenge with code_challenge_method=S256.");let X=Z.get("resource");if(X!==null&&!G6(X,this.context.resource))return K("invalid_target","The resource is not this server's.");if(Y!==null&&Y.length>2048)return K("invalid_request","state is too long.");let G=this.scopeNames(),B=Z.get("scope"),j=G;if(B!==null&&B.trim()!==""){if(j=[...new Set(B.split(" ").filter((U)=>G.includes(U)))],j.length===0)return K("invalid_scope","None of the requested scopes exist here.")}let N=C4(S4,"gat1",{c:J.clientId,r:Q,s:j,cc:z,st:Y,n:s(16).toString("base64url"),exp:Date.now()+OW}),S=this.options.consentPath??`${this.base}/consent`;return R4(`${this.issuer}${S}?request=${encodeURIComponent(N)}`,302)}async consentScreen(W){let Z=new URL(W.url).searchParams.get("request"),$=await this.sessionUser(W);if(!$){let Q=`${this.base}/consent?request=${encodeURIComponent(Z??"")}`,Y=this.options.signInPath??h(g1).config.signInPath;return R4(`${Y}${Y.includes("?")?"&":"?"}redirect=${encodeURIComponent(Q)}`,302)}let J=await this.consent(Z,$);if(!J)return I("This authorization request has expired or is not valid. Start again from the application.");return new Response(r0(J,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:y1})}async decide(W){let Z=W.headers.get("origin");if(!(Z!==null?Z===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return I("This decision did not come from this site's consent page.",403);if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))return I("The decision must be a form post.");let J;try{J=new URLSearchParams(await T4(W,V4))}catch{return I("The decision is too large.")}let Q=J.get("request"),Y=h1(S4,"gat1",Q),K=h1(Z6,"gcs1",J.get("csrf")),z=await this.sessionUser(W);if(!Y||!K||!z||K.t!==Q6(Q)||K.u!==String(z.id))return I("This authorization request has expired or is not valid. Start again from the application.",403);let X=await this.store.findClient(Y.c);if(!X||!X.redirectUris.some((B)=>_4(B,Y.r)))return I("The application is not registered with this server.");if(!await this.store.use(`ticket:${Y.n}`,Y.exp))return I("This request was already answered. Start again from the application.");if(J.get("decision")!=="allow")return this.redirectBack(Y.r,Y.st,{error:"access_denied",error_description:"The user denied the request."},303);let G=`${W6}${s(32).toString("base64url")}`;return await this.store.saveCode({hash:g(G),clientId:X.clientId,userId:String(z.id),redirectUri:Y.r,codeChallenge:Y.cc,scopes:Y.s,resource:this.context.resource,familyId:s(16).toString("base64url"),expiresAt:Date.now()+$6}),this.redirectBack(Y.r,Y.st,{code:G},303)}async token(W){let Z=await K6(W),$=await this.authenticateClient(W,Z),J=await f4(`mcp-oauth-token:${$.clientId}`,RW);if(J!==null)throw new M("slow_down","Too many token requests.",429,{"Retry-After":String(J)});let Q=Z.get("resource");if(Q!==null&&!G6(Q,this.context.resource))throw new M("invalid_target","The resource is not this server's.");switch(Z.get("grant_type")){case"authorization_code":{let Y=Z.get("code")??"",K=Y.startsWith(W6)?await this.store.findCode(g(Y)):null;if(!K||K.clientId!==$.clientId)throw new M("invalid_grant","The authorization code is not valid.");if(!await this.store.use(K.hash,K.expiresAt+$6))throw await this.store.revokeFamily(K.familyId),new M("invalid_grant","The authorization code was already used.");if(K.expiresAt<=Date.now())throw new M("invalid_grant","The authorization code expired.");if(Z.get("redirect_uri")!==null&&Z.get("redirect_uri")!==K.redirectUri)throw new M("invalid_grant","redirect_uri is not the one the code was issued to.");let z=Z.get("code_verifier");if(!z||!/^[A-Za-z0-9._~-]{43,128}$/.test(z)||!Y6(kW(z),K.codeChallenge))throw new M("invalid_grant","The PKCE code_verifier does not match.");if(!await this.options.findUser(K.userId))throw new M("invalid_grant","The authorization code is not valid.");return await this.issue(K)}case"refresh_token":{let Y=Z.get("refresh_token")??"",K=Y.startsWith(O4)?await this.store.findToken(g(Y)):null;if(!K||K.kind!=="refresh"||K.clientId!==$.clientId)throw new M("invalid_grant","The refresh token is not valid.");if(K.expiresAt<=Date.now())throw new M("invalid_grant","The refresh token expired.");if(!await this.store.use(K.hash,K.expiresAt))throw await this.store.revokeFamily(K.familyId),new M("invalid_grant","The refresh token was already used.");if(K.resource!==this.context.resource)throw new M("invalid_grant","The refresh token was not issued for this server.");let z=K.scopes,X=Z.get("scope");if(X!==null&&X.trim()!==""){let G=[...new Set(X.split(" ").filter(Boolean))];if(G.some((B)=>!K.scopes.includes(B)))throw new M("invalid_scope","A refresh can only narrow the scopes that were granted.");z=G}if(!await this.options.findUser(K.userId))throw new M("invalid_grant","The refresh token is not valid.");return await this.issue({...K,scopes:z})}default:throw new M("unsupported_grant_type","grant_type must be authorization_code or refresh_token.")}}async issue(W){let Z=Date.now(),$=this.scopeNames(),J=W.scopes.filter((z)=>$.includes(z)),Q=`${U4}${s(32).toString("base64url")}`,Y=`${O4}${s(32).toString("base64url")}`,K={clientId:W.clientId,userId:W.userId,scopes:J,resource:W.resource,familyId:W.familyId};return await this.store.saveToken({...K,hash:g(Q),kind:"access",expiresAt:Z+this.accessTtl*1000}),await this.store.saveToken({...K,hash:g(Y),kind:"refresh",expiresAt:Z+this.refreshTtl*1000}),H1({access_token:Q,token_type:"Bearer",expires_in:this.accessTtl,refresh_token:Y,scope:J.join(" ")})}async revoke(W){let Z=await K6(W),$=await this.authenticateClient(W,Z),J=Z.get("token")??"";if(J.startsWith(U4)||J.startsWith(O4)){let Q=await this.store.findToken(g(J));if(Q&&Q.clientId===$.clientId)await this.store.revokeFamily(Q.familyId)}return new Response(null,{status:200,headers:{"Cache-Control":"no-store"}})}async authenticateClient(W,Z){let $=/^Basic\s+([A-Za-z0-9+/=]+)$/i.exec(W.headers.get("authorization")??""),J=Z.get("client_id"),Q=Z.get("client_secret");if($){let K=Buffer.from($[1],"base64").toString("utf8"),z=K.indexOf(":");if(z<0)throw o(!0);let X=X6(K.slice(0,z));if(X===null)throw o(!0);if(J!==null&&J!==X)throw o(!0);if(J=X,Q=X6(K.slice(z+1)),Q===null)throw o(!0)}let Y=J?await this.store.findClient(J):null;if(!Y)throw o(Boolean($));if(Y.tokenEndpointAuthMethod==="none"){if(Q)throw o(Boolean($));return Y}if(!Q||!Y.clientSecretHash||!Y6(g(Q),Y.clientSecretHash))throw o(Boolean($));return Y}redirectBack(W,Z,$,J=302){let Q=new URL(W);for(let[Y,K]of Object.entries($))Q.searchParams.set(Y,K);if(Z!==null)Q.searchParams.set("state",Z);return Q.searchParams.set("iss",this.issuer),R4(Q.href,J)}async sessionUser(W){let Z=new k4(W,{},"api",this.base).cookies;return await B6(h(g1),{cookies:Z,headers:{get:($)=>$.toLowerCase()==="user-agent"?W.headers.get("user-agent"):null}})}userLabel(W){if(this.options.userLabel)return this.options.userLabel(W);let Z=W;return String(Z.email??Z.name??Z.id)}scopeNames(){return this.context.registry.scopes().map((W)=>W.name)}resourceMetadataUrl(){return`${this.issuer}/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`}}var _W={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function J6(W,Z,$){if(Z===void 0)return $;if(!Number.isInteger(Z)||Z<60)throw Error(`McpOAuthServer: ${W} must be a whole number of seconds, at least 60.`);return Z}function g(W){return b4("sha256").update(W).digest("hex")}function Q6(W){return b4("sha256").update(W).digest("base64url")}function kW(W){return b4("sha256").update(W).digest("base64url")}function Y6(W,Z){let $=Buffer.from(W),J=Buffer.from(Z);return $.length===J.length&&HW($,J)}function H1(W,Z=200,$={}){return new Response(JSON.stringify(W),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache",...$}})}function R4(W,Z){return new Response(null,{status:Z,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function I(W,Z=400){return new Response(e0(W),{status:Z,headers:y1})}function o(W){return new M("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function T4(W,Z){let $=Number(W.headers.get("content-length"));if(Number.isFinite($)&&$>Z)throw Error("too large");if(!W.body)return"";let J=W.body.getReader(),Q=[],Y=0;for(;;){let{done:K,value:z}=await J.read();if(K)break;if(Y+=z.byteLength,Y>Z)throw await J.cancel(),Error("too large");Q.push(z)}return Buffer.concat(Q).toString("utf8")}async function K6(W){if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new M("invalid_request","Send the request as application/x-www-form-urlencoded.");let Z;try{Z=new URLSearchParams(await T4(W,V4))}catch{throw new M("invalid_request","The request is too large.")}for(let $ of new Set(Z.keys()))if(Z.getAll($).length>1)throw new M("invalid_request",`${$} was sent more than once.`);return Z}function z6(W,Z,$){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>Z||VW(W))throw new M("invalid_client_metadata",`${$} must be text of at most ${Z} characters.`);return W}function fW(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function M6(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function CW(W){if(typeof W!=="string"||W.length>2048)return"not a URI";let Z;try{Z=new URL(W)}catch{return"not an absolute URI"}if(Z.hash||W.includes("#"))return"must not have a fragment";if(Z.username||Z.password)return"must not carry credentials";if(Z.protocol==="https:")return null;if(Z.protocol==="http:"&&M6(Z))return null;return"must be https, or http on a loopback address"}function _4(W,Z){if(W===Z)return!0;let $,J;try{$=new URL(W),J=new URL(Z)}catch{return!1}return $.protocol==="http:"&&J.protocol==="http:"&&M6($)&&$.hostname===J.hostname&&$.pathname===J.pathname&&$.search===J.search&&!J.hash&&!J.username&&!J.password}function G6(W,Z){return W===Z||W===`${Z}/`}function VW(W){for(let Z=0;Z<W.length;Z++){let $=W.charCodeAt(Z);if($<32||$===127)return!0}return!1}function X6(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class L6{clients=new Map;codes=new Map;tokens=new Map;used=new Map;revoked=new Set;async createClient(W){this.clients.set(W.clientId,structuredClone(W))}async findClient(W){let Z=this.clients.get(W);return Z?structuredClone(Z):null}async saveCode(W){this.sweep(),this.codes.set(W.hash,structuredClone(W))}async findCode(W){let Z=this.codes.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async saveToken(W){this.sweep(),this.tokens.set(W.hash,structuredClone(W))}async findToken(W){let Z=this.tokens.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async use(W,Z){if(this.used.has(W))return!1;return this.used.set(W,Z),!0}async revokeFamily(W){this.revoked.add(W);for(let[Z,$]of this.tokens)if($.familyId===W)this.tokens.delete(Z);for(let[Z,$]of this.codes)if($.familyId===W)this.codes.delete(Z)}async families(W){let Z=new Map;for(let $ of this.tokens.values())if($.userId===W&&!this.revoked.has($.familyId)&&$.expiresAt>Date.now())Z.set($.familyId,{familyId:$.familyId,clientId:$.clientId,scopes:[...$.scopes]});return[...Z.values()]}sweep(W=Date.now()){for(let[Z,$]of this.codes)if($.expiresAt<=W)this.codes.delete(Z);for(let[Z,$]of this.tokens)if($.expiresAt<=W)this.tokens.delete(Z);for(let[Z,$]of this.used)if($<=W)this.used.delete(Z)}}class N6{clients;credentials;uses;usesModel;constructor(W){for(let[Z,$]of[["clients",["create","findUnique","findMany"]],["credentials",["create","findFirst","findMany","count","updateMany","deleteMany"]],["uses",["create","deleteMany"]]]){let J=W?.[Z],Q=$.filter((Y)=>typeof J?.[Y]!=="function");if(Q.length>0)throw Error(`PrismaMcpOAuthStore: models.${Z} must be a gemi ORM model or a Prisma delegate (it has no ${Q.join(", ")}()).`)}this.clients=W.clients,this.credentials=W.credentials,this.usesModel=W.uses,this.uses=new q4(W.uses)}async createClient(W){await this.clients.create({data:{clientId:W.clientId,clientSecretHash:W.clientSecretHash,tokenEndpointAuthMethod:W.tokenEndpointAuthMethod,redirectUris:[...W.redirectUris],clientName:W.clientName,clientUri:W.clientUri,createdAt:new Date(W.createdAt)}})}async findClient(W){let Z=await this.clients.findUnique({where:{clientId:W}});if(!Z)return null;return{clientId:Z.clientId,clientSecretHash:Z.clientSecretHash??null,tokenEndpointAuthMethod:Z.tokenEndpointAuthMethod,redirectUris:E1(Z.redirectUris),clientName:Z.clientName??null,clientUri:Z.clientUri??null,createdAt:m1(Z.createdAt)}}async saveCode(W){await this.credentials.create({data:{hash:W.hash,kind:"code",clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,redirectUri:W.redirectUri,codeChallenge:W.codeChallenge,expiresAt:new Date(W.expiresAt)}})}async findCode(W){let Z=await this.findLive(W,["code"]);if(!Z||Z.redirectUri==null||Z.codeChallenge==null)return null;return{hash:Z.hash,clientId:Z.clientId,userId:Z.userId,redirectUri:Z.redirectUri,codeChallenge:Z.codeChallenge,scopes:E1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:m1(Z.expiresAt)}}async saveToken(W){await this.credentials.create({data:{hash:W.hash,kind:W.kind,clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,expiresAt:new Date(W.expiresAt)}})}async findToken(W){let Z=await this.findLive(W,["access","refresh"]);if(!Z)return null;return{hash:Z.hash,kind:Z.kind,clientId:Z.clientId,userId:Z.userId,scopes:E1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:m1(Z.expiresAt)}}use(W,Z){return this.uses.consume(W,Z)}async revokeFamily(W){await this.credentials.updateMany({where:{familyId:W,revokedAt:null},data:{revokedAt:new Date}})}nonces(W={}){return new q4(this.usesModel,{prefix:W.prefix??"nonce:"})}async connectedApps(W,Z=new Date){let $=String(W),J=await this.credentials.findMany({where:{userId:$,kind:"refresh",expiresAt:{gt:Z}},orderBy:{createdAt:"asc"}}),Q=await this.revokedFamilies({userId:$}),Y=new Map;for(let G of J){if(Q.has(G.familyId))continue;if(!Y.has(G.familyId))Y.set(G.familyId,G)}if(Y.size===0)return[];let K=[...new Set([...Y.values()].map((G)=>G.clientId))],z=await this.clients.findMany({where:{clientId:{in:K}}}),X=new Map(z.map((G)=>[G.clientId,G]));return[...Y.values()].map((G)=>({familyId:G.familyId,clientId:G.clientId,clientName:X.get(G.clientId)?.clientName??null,clientUri:X.get(G.clientId)?.clientUri??null,scopes:E1(G.scopes),connectedAt:new Date(m1(G.createdAt))})).reverse()}async disconnect(W,Z){if(await this.credentials.count({where:{familyId:Z,userId:String(W)}})===0)return!1;return await this.revokeFamily(Z),!0}async revokeUser(W){await this.credentials.updateMany({where:{userId:String(W),revokedAt:null},data:{revokedAt:new Date}})}async prune(W=Date.now()){let Z=new Date(W-86400000),$=[...await this.revokedFamilies({expiresAt:{lt:Z}})],J=$.length===0?[]:await this.credentials.findMany({where:{familyId:{in:$},expiresAt:{gte:Z}},select:{familyId:!0}}),Q=[...new Set(J.map((Y)=>Y.familyId))];await this.credentials.deleteMany({where:{expiresAt:{lt:Z},...Q.length>0?{OR:[{revokedAt:null},{familyId:{notIn:Q}}]}:{}}}),await this.usesModel.deleteMany({where:{expiresAt:{lt:new Date(W)}}})}async findLive(W,Z){let $=await this.credentials.findFirst({where:{hash:W,kind:{in:Z},revokedAt:null}});if(!$)return null;return await this.credentials.count({where:{familyId:$.familyId,revokedAt:{not:null}}})>0?null:$}async revokedFamilies(W){let Z=await this.credentials.findMany({where:{...W,revokedAt:{not:null}},select:{familyId:!0}});return new Set(Z.map(($)=>$.familyId))}}function E1(W){return Array.isArray(W)?W.map(String):[]}function m1(W){return W instanceof Date?W.getTime():new Date(W).getTime()}class U1 extends T{application;previous;dispatched=[];static install(W){let Z=W.resolved(T)?W.make(T):void 0;if(Z instanceof U1)return Z;let $=new U1(W,Z);return W.instance(T,$),$}constructor(W,Z){super({listeners:[]});this.application=W;this.previous=Z}dispatch(W,Z){this.dispatched.push({event:W,args:Z})}async dispatchAndWait(W,Z){this.dispatched.push({event:W,args:Z})}restore(){if(this.previous){this.application.instance(T,this.previous);return}this.application.forget(T)}assertDispatched(W,Z){let $=x1(W);if(this.matching($,Z).length>0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} to have been dispatched. ${this.summary($,Z!==void 0)}`)}assertNotDispatched(W,Z){let $=x1(W),J=this.matching($,Z);if(J.length===0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} not to have been dispatched, but it was dispatched ${v4(J.length)}: ${c1(J)}.`)}assertDispatchedTimes(W,Z,$){let J=x1(W),Q=this.matching(J,$);if(Q.length===Z)return;throw Error(`Expected ${J}${$?" matching the predicate":""} to have been dispatched ${v4(Z)}, but it was dispatched ${v4(Q.length)}. ${this.summary(J,$!==void 0)}`)}assertNothingDispatched(){if(this.dispatched.length===0)return;let W=this.dispatched.length;throw Error(`Expected nothing to have been dispatched, but ${W} ${W===1?"event was":"events were"}: ${c1(this.dispatched)}.`)}matching(W,Z){return this.dispatched.filter(($)=>x1($.event.constructor)===W&&(Z===void 0||Z($.event)))}summary(W,Z){if(this.dispatched.length===0)return"Nothing was dispatched.";let $=this.matching(W);if(Z&&$.length>0)return`Dispatched ${W}: ${c1($)}.`;return`Dispatched: ${c1(this.dispatched)}.`}}function x1(W){return W.name}function v4(W){return`${W} ${W===1?"time":"times"}`}function c1(W){return W.map(TW).join(", ")}function TW(W){let Z=x1(W.event.constructor),$=W.args??Object.values({...W.event});return`${Z}(${$.map(PW).join(", ")})`}function PW(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class u1{static name="unset";static afterCommit=!1;static dispatch(...W){D6(this),h(T).dispatch(new this(...W),W)}static dispatchAndWait(...W){return D6(this),h(T).dispatchAndWait(new this(...W),W)}static fake(){return U1.install(bW())}}function bW(){try{return h()}catch(W){throw Error("Event.fake() needs a booted application. The fake works by replacing the container's EventManager with a recorder, so there has to be a "+"container to replace it in \u2014 and a dispatch finds the recorder the "+"same way, by resolving from that container. Boot the app's kernel in the test's setup: `const kernel = new Kernel(); kernel.boot()` is enough on its own, since that is the phase that publishes the application every dispatch outside a request resolves through.",{cause:W})}}function D6(W){if(W.name!=="unset"&&W.name!=="")return;throw Error("Cannot dispatch an event with no name. Add `static name` to this Event "+"subclass \u2014 the listener registry is keyed by that string, and by that "+"string alone, so an event without one cannot reach a listener.")}class U6 extends u1{constructor(){super();Object.defineProperty(this,w4,{value:!0,enumerable:!1})}broadcastAs(){return this.constructor.name}broadcastWith(){return}channel(W,...Z){return{topic:H6(W,Z[0]??{}),pattern:W}}}var qW={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET,redirectPath:"/auth/oauth/google/callback",scope:"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",authorizationParams:{}};function vW(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class O6 extends a{config;constructor(W={}){super();this.config={...qW,...W}}redirectUri(){return`${Z1()??""}${this.config.redirectPath}`}getRedirectUrl(W,Z){let $=new URL("https://accounts.google.com/o/oauth2/v2/auth"),J={include_granted_scopes:"true",...this.config.authorizationParams,scope:this.config.scope,response_type:"code",redirect_uri:this.redirectUri(),client_id:this.config.clientId};if(Z)J.state=Z.state,J.code_challenge=Z.codeChallenge,J.code_challenge_method=Z.codeChallengeMethod;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new P("missing_code");let J=new URLSearchParams({code:$,client_id:this.config.clientId,client_secret:this.config.clientSecret,grant_type:"authorization_code",redirect_uri:this.redirectUri()});if(Z?.codeVerifier)J.set("code_verifier",Z.codeVerifier);let Q=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J.toString()}),Y=await Q.json().catch(()=>({}));if(!Q.ok||typeof Y?.access_token!=="string"||Y.access_token==="")throw console.error("Google OAuth error: token exchange failed",Y?.error??Q.status),new P(vW(Y?.error,"exchange_failed"));let z=await(await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${Y.access_token}`}})).json().catch(()=>({}));if(typeof z.sub!=="string"||z.sub==="")return console.error("Google OAuth error: sub not found in user info response",z),{};if(!z.email)console.error("Google OAuth error: email not found in user info response",z);return{providerId:z.sub,name:z.name,email:z.email,emailVerified:z.email_verified===!0||z.email_verified==="true"}}}var c="https://api.x.com/2/",$1="https://api.x.com/labs/2/",u="https://api.x.com/1.1/",E="https://upload.x.com/1.1/",S6="https://stream.x.com/1.1/",J1="https://ads-api.x.com/12/",Q1="https://ads-api-sandbox.twitter.com/12/";class I4{constructor({realData:W,rateLimit:Z,instance:$,queryParams:J,sharedParams:Q}){this._maxResultsWhenFetchLast=100,this._realData=W,this._rateLimit=Z,this._instance=$,this._queryParams=J,this._sharedParams=Q}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(W){return this._instance.get(this.getEndpoint(),W,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(W,Z){return new this.constructor({realData:W.data,rateLimit:W.rateLimit,instance:this._instance,queryParams:Z,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(W){return{...W?{max_results:W}:{},...this._queryParams}}async next(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchNext(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!0),this}async fetchLast(W=1/0){let Z=this.getNextQueryParams(this._maxResultsWhenFetchLast),$=0;while($<W&&this._isRateLimitOk){let J=await this.makeRequest(Z);if(await this.refreshInstanceFromResult(J,!0),$+=this.getPageLengthFromRequest(J),this.isFetchLastOver(J))break;Z=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var W;return{...(W=this._rateLimit)!==null&&W!==void 0?W:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData),yield*$.getItemArray(),W=$}}async*fetchAndIterate(){for(let $ of this.getItemArray())yield[$,this];let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData);for(let J of $.getItemArray())yield[J,$];this._rateLimit=$._rateLimit,W=$}}}class y4 extends I4{async previous(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchPrevious(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!1),this}}var Y1=I4;class H extends Y1{getNextQueryParams(W){var Z;return{...this._queryParams,cursor:(Z=this._realData.next_cursor_str)!==null&&Z!==void 0?Z:this._realData.next_cursor,...W?{count:W}:{}}}isFetchLastOver(W){return!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!this.isNextCursorInvalid(W.next_cursor)||!this.isNextCursorInvalid(W.next_cursor_str)}isNextCursorInvalid(W){return W===void 0||W===0||W===-1||W==="0"||W==="-1"}}class A4 extends H{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.events.push(...$.events),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class h4 extends H{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.welcome_messages.push(...$.welcome_messages),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var D;(function(W){W.Jpeg="image/jpeg",W.Mp4="video/mp4",W.Mov="video/quicktime",W.Gif="image/gif",W.Png="image/png",W.Srt="text/plain",W.Webp="image/webp"})(D||(D={}));var p;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(p||(p={}));var O1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(O1||(O1={}));class p1 extends Error{constructor(){super(...arguments);this.error=!0}}class S1 extends p1{constructor(W,Z){super(W);this.type=O1.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class R1 extends p1{constructor(W,Z){super(W);this.type=O1.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}get request(){return this._options.request}get response(){return this._options.response}get responseError(){return this._options.responseError}get rawContent(){return this._options.rawContent}toJSON(){return{type:this.type,error:this.responseError}}}class _1 extends p1{constructor(W,Z){super(W);if(this.type=O1.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z}),this.code=Z.code,this.headers=Z.headers,this.rateLimit=Z.rateLimit,Z.data&&typeof Z.data==="object"&&"error"in Z.data&&!Z.data.errors){let $={...Z.data};$.errors=[{code:t.InternalError,message:$.error}],this.data=$}else this.data=Z.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...W){let Z=this.errors;if(!(Z===null||Z===void 0?void 0:Z.length))return!1;if("code"in Z[0])return Z.some((Q)=>W.includes(Q.code));let $=this.data;return W.includes($.type)}get errors(){var W;return(W=this.data)===null||W===void 0?void 0:W.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(t.AuthTimestampInvalid,t.AuthenticationFail,t.BadAuthenticationData,t.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var t;(function(W){W[W.InvalidCoordinates=3]="InvalidCoordinates",W[W.NoLocationFound=13]="NoLocationFound",W[W.AuthenticationFail=32]="AuthenticationFail",W[W.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",W[W.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",W[W.AuthTimestampInvalid=135]="AuthTimestampInvalid",W[W.BadAuthenticationData=215]="BadAuthenticationData",W[W.NoUserMatch=17]="NoUserMatch",W[W.UserNotFound=50]="UserNotFound",W[W.ResourceNotFound=34]="ResourceNotFound",W[W.TweetNotFound=144]="TweetNotFound",W[W.TweetNotVisible=179]="TweetNotVisible",W[W.NotAllowedResource=220]="NotAllowedResource",W[W.MediaIdNotFound=325]="MediaIdNotFound",W[W.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",W[W.TweetViolatedRules=422]="TweetViolatedRules",W[W.TargetUserSuspended=63]="TargetUserSuspended",W[W.YouAreSuspended=64]="YouAreSuspended",W[W.AccountUpdateFailed=120]="AccountUpdateFailed",W[W.NoSelfSpamReport=36]="NoSelfSpamReport",W[W.NoSelfMute=271]="NoSelfMute",W[W.AccountLocked=326]="AccountLocked",W[W.RateLimitExceeded=88]="RateLimitExceeded",W[W.NoDMRightForApp=93]="NoDMRightForApp",W[W.OverCapacity=130]="OverCapacity",W[W.InternalError=131]="InternalError",W[W.TooManyFollowings=161]="TooManyFollowings",W[W.TweetLimitExceeded=185]="TweetLimitExceeded",W[W.DuplicatedTweet=187]="DuplicatedTweet",W[W.TooManySpamReports=205]="TooManySpamReports",W[W.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",W[W.NoWriteRightForApp=261]="NoWriteRightForApp",W[W.TweetActionsDisabled=425]="TweetActionsDisabled",W[W.TweetRepliesRestricted=433]="TweetRepliesRestricted",W[W.NamedParameterMissing=38]="NamedParameterMissing",W[W.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",W[W.TweetTextTooLong=186]="TweetTextTooLong",W[W.MissingUrlParameter=195]="MissingUrlParameter",W[W.NoMultipleGifs=323]="NoMultipleGifs",W[W.InvalidMediaIds=324]="InvalidMediaIds",W[W.InvalidUrl=407]="InvalidUrl",W[W.TooManyTweetAttachments=386]="TooManyTweetAttachments",W[W.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",W[W.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",W[W.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",W[W.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",W[W.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",W[W.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",W[W.UnableToSendDM=151]="UnableToSendDM",W[W.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",W[W.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",W[W.DMTextTooLong=354]="DMTextTooLong",W[W.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",W[W.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",W[W.SuspendedApplication=416]="SuspendedApplication",W[W.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(t||(t={}));var R6;(function(W){W.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",W.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",W.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",W.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",W.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",W.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",W.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",W.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",W.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",W.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",W.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",W.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",W.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(R6||(R6={}));var F;(function(W){W.Connected="connected",W.ConnectError="connect error",W.ConnectionError="connection error",W.ConnectionClosed="connection closed",W.ConnectionLost="connection lost",W.ReconnectAttempt="reconnect attempt",W.Reconnected="reconnected",W.ReconnectError="reconnect error",W.ReconnectLimitExceeded="reconnect limit exceeded",W.DataKeepAlive="data keep-alive",W.Data="data event content",W.DataError="data twitter error",W.TweetParseError="data tweet parse error",W.Error="stream error"})(F||(F={}));class k1{constructor(W){this.value=W}}import*as X0 from"fs";var O={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function g4(W){let Z={value:void 0,promise:W().then(($)=>{return Z.value=$,$})};return Z}function d1(W){if(Array.isArray(W))return W;return[W]}function k6(W){for(let Z of Object.keys(W))if(W[Z]===void 0)delete W[Z]}function l1(W){return typeof W==="object"&&"errors"in W&&!("data"in W)}function f1(W){if(Array.isArray(W)&&W.length>1)return!0;return W.toString().includes(",")}var _6=new Set;function E4(W){if(typeof console>"u"||!console.warn||!O.deprecationWarnings)return;let Z=`${W.instance}-${W.method}-${W.problem}`;if(_6.has(Z))return;let $=`[twitter-api-v2] Deprecation warning: In ${W.instance}.${W.method}() call, ${W.problem}.
|
|
65
|
+
${W.resolution}.`;console.warn($),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),_6.add(Z)}import{EventEmitter as hW}from"events";import{request as wW}from"https";import*as _ from"zlib";import{EventEmitter as IW}from"events";class f6{constructor(W){this.requestData=W,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let W=this.requestData.url;return W.hostname+W.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(W){if(O.debug)O.logger.log("Request error:",W);return new S1("Request failed.",{request:this.req,error:W})}createPartialResponseError(W,Z){let J=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(Z)J+=" (connection abruptly closed)";else J+=" (parse error)";return new R1(J,{request:this.req,response:this.res,responseError:W,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(W){return W.map(({code:Z,message:$})=>`${$} (Twitter code ${Z})`).join(", ")}formatV2Error(W){return`${W.title}: ${W.detail} (see ${W.type})`}createResponseError({res:W,data:Z,rateLimit:$,code:J}){var Q;if(O.debug)O.logger.log(`Request failed with code ${J}, data:`,Z),O.logger.log("Response headers:",W.headers);let Y=`Request failed with code ${J}`;if((Q=Z===null||Z===void 0?void 0:Z.errors)===null||Q===void 0?void 0:Q.length){let K=Z.errors;if(typeof K[0]==="object"&&"code"in K[0])Y+=" - "+this.formatV1Errors(K);else Y+=" - "+this.formatV2Error(Z)}return new _1(Y,{code:J,data:Z,headers:W.headers,request:this.req,response:W,rateLimit:$})}getResponseDataStream(W){if(this.isCompressionDisabled())return W;let Z=(W.headers["content-encoding"]||"identity").trim().toLowerCase();if(Z==="br"){let $=_.createBrotliDecompress({flush:_.constants.BROTLI_OPERATION_FLUSH,finishFlush:_.constants.BROTLI_OPERATION_FLUSH});return W.pipe($),$}if(Z==="gzip"){let $=_.createGunzip({flush:_.constants.Z_SYNC_FLUSH,finishFlush:_.constants.Z_SYNC_FLUSH});return W.pipe($),$}if(Z==="deflate"){let $=_.createInflate({flush:_.constants.Z_SYNC_FLUSH,finishFlush:_.constants.Z_SYNC_FLUSH});return W.pipe($),$}return W}detectResponseType(W){var Z,$;if(((Z=W.headers["content-type"])===null||Z===void 0?void 0:Z.includes("application/json"))||(($=W.headers["content-type"])===null||$===void 0?void 0:$.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(W){let Z=this.responseData,$=this.requestData.forceParseMode||this.detectResponseType(W);if($==="buffer")return Buffer.concat(Z);else if($==="text")return Buffer.concat(Z).toString();else if($==="json"){let J=Buffer.concat(Z).toString();return J.length?JSON.parse(J):void 0}else if($==="url"){let J=Buffer.concat(Z).toString(),Q={};for(let[Y,K]of new URLSearchParams(J))Q[Y]=K;return Q}else return}getRateLimitFromResponse(W){let Z=void 0;if(W.headers["x-rate-limit-limit"]){if(Z={limit:Number(W.headers["x-rate-limit-limit"]),remaining:Number(W.headers["x-rate-limit-remaining"]),reset:Number(W.headers["x-rate-limit-reset"])},W.headers["x-app-limit-24hour-limit"])Z.day={limit:Number(W.headers["x-app-limit-24hour-limit"]),remaining:Number(W.headers["x-app-limit-24hour-remaining"]),reset:Number(W.headers["x-app-limit-24hour-reset"])};if(W.headers["x-user-limit-24hour-limit"])Z.userDay={limit:Number(W.headers["x-user-limit-24hour-limit"]),remaining:Number(W.headers["x-user-limit-24hour-remaining"]),reset:Number(W.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(Z)}return Z}onSocketEventHandler(W,Z,$){let J=this.onSocketCloseHandler.bind(this,W);$.on("close",J),Z.on("complete",()=>$.off("close",J))}onSocketCloseHandler(W){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return W(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(W,Z){var $,J;(J=($=this.requestData).requestEventDebugHandler)===null||J===void 0||J.call($,"request-error",{requestError:Z}),this.requestErrorHandled=!0,W(this.createRequestError(Z))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(W,Z,$){this.res=$;let J=this.getResponseDataStream($);if(J.on("data",(Q)=>this.responseData.push(Q)),J.on("end",this.onResponseEndHandler.bind(this,W,Z)),J.on("close",this.onResponseCloseHandler.bind(this,W,Z)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:$}),$.on("aborted",(Q)=>this.requestData.requestEventDebugHandler("response-aborted",{error:Q})),$.on("error",(Q)=>this.requestData.requestEventDebugHandler("response-error",{error:Q})),$.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),$.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(W,Z){let $=this.getRateLimitFromResponse(this.res),J;try{J=this.getParsedResponse(this.res)}catch(Y){Z(this.createPartialResponseError(Y,!1));return}let Q=this.res.statusCode;if(Q>=400){Z(this.createResponseError({data:J,res:this.res,rateLimit:$,code:Q}));return}if(O.debug)O.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),O.logger.log("Response body:",J);W({data:J,headers:this.res.headers,rateLimit:$})}onResponseCloseHandler(W,Z){let $=this.res;if($.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(W,Z)}catch(J){return Z(this.createPartialResponseError(J,!0))}if(!$.complete)return Z(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(W,Z,$){if($.statusCode<400){if(O.debug)O.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${$.statusCode} (starting stream)`);let Q=this.getResponseDataStream($);W({req:this.req,res:Q,originalResponse:$,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},Z,$)}debugRequest(){let W=this.requestData.url;if(O.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),W.search)O.logger.log("Request parameters:",[...W.searchParams.entries()].map(([Z,$])=>`${Z}: ${$}`));if(this.requestData.body)O.logger.log("Request body:",this.requestData.body)}buildRequest(){var W;let Z=this.requestData.url,$=Z.username?`${Z.username}:${Z.password}`:void 0,J=(W=this.requestData.options.headers)!==null&&W!==void 0?W:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")J["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")J["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")J["accept-encoding"]="deflate;q=1, *;q=0.1";if(O.debug)this.debugRequest();this.req=wW({...this.requestData.options,host:Z.hostname,port:Z.port||void 0,path:Z.pathname+Z.search,protocol:Z.protocol,auth:$,headers:J})}registerRequestEventDebugHandlers(W){W.on("close",()=>this.requestData.requestEventDebugHandler("close")),W.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),W.on("socket",(Z)=>{this.requestData.requestEventDebugHandler("socket",{socket:Z}),Z.on("error",($)=>this.requestData.requestEventDebugHandler("socket-error",{socket:Z,error:$})),Z.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:Z})),Z.on("close",($)=>this.requestData.requestEventDebugHandler("socket-close",{socket:Z,withError:$})),Z.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:Z})),Z.on("lookup",(...$)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:Z,data:$})),Z.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:Z}))})}makeRequest(){return this.buildRequest(),new Promise((W,Z)=>{let $=(K)=>{Q.emit("complete"),W(K)},J=(K)=>{Q.emit("complete"),Z(K)},Q=new IW,Y=this.req;if(Y.on("error",this.requestErrorHandler.bind(this,J)),Y.on("socket",this.onSocketEventHandler.bind(this,J,Q)),Y.on("response",this.classicResponseHandler.bind(this,$,J)),this.requestData.options.timeout)Y.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(Y);if(this.requestData.body)Y.write(this.requestData.body);Y.end()})}async makeRequestAsStream(){let{req:W,res:Z,requestData:$,originalResponse:J}=await this.makeRequestAndResolveWhenReady();return new n1($,{req:W,res:Z,originalResponse:J})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((W,Z)=>{let $=this.req;if($.on("error",this.requestErrorHandler.bind(this,Z)),$.on("response",this.streamResponseHandler.bind(this,W,Z)),this.requestData.body)$.write(this.requestData.body);$.end()})}}var C1=f6;import{EventEmitter as yW}from"events";class C6 extends yW{constructor(W){super();this.stream=W,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),W.on(F.Data,this.onStreamData),W.on(F.ConnectionError,this.onStreamError),W.on(F.TweetParseError,this.onStreamError),W.on(F.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let W=this.stack;return this.stack=[],W}destroy(){this.removeAllListeners(),this.stream.off(F.Data,this.onStreamData),this.stream.off(F.ConnectionError,this.onStreamError),this.stream.off(F.TweetParseError,this.onStreamError),this.stream.off(F.ConnectionClosed,this.onStreamError)}emitEvent(W,Z){this.emit("event",{type:W,payload:Z})}onStreamError(W){this.emitEvent("error",W)}onStreamData(W){this.stack.push(W),this.emitEvent("data",W)}}var V6=C6;import{EventEmitter as AW}from"events";class i1 extends AW{constructor(){super(...arguments);this.currentMessage=""}push(W){this.currentMessage+=W,W=this.currentMessage;let Z=W.length,$=0,J=0;while(J<Z){if(W.slice(J,J+2)===`\r
|
|
66
|
+
`){let Q=W.slice($,J);if($=J+=2,!Q.length)continue;try{let Y=JSON.parse(Q);if(Y){this.emit(r.ParsedData,Y);continue}}catch(Y){this.emit(r.ParseError,Y)}}J++}this.currentMessage=W.slice($,Z)}reset(){this.currentMessage=""}}var r;(function(W){W.ParsedData="parsed data",W.ParseError="parse error"})(r||(r={}));var T6=[5,15,30,60,90,120,180,300,600,900],gW=(W)=>W>T6.length?901000:T6[W-1]*1000;class P6 extends hW{constructor(W,Z){super();if(this.requestData=W,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=gW,this.parser=new i1,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),Z)this.req=Z.req,this.res=Z.res,this.originalResponse=Z.originalResponse,this.initEventsFromRequest()}on(W,Z){return super.on(W,Z)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let W=(Z)=>{this.emit(F.ConnectionError,Z),this.emit(F.Error,{type:F.ConnectionError,error:Z,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",W),this.res.on("error",W),this.res.on("close",()=>W(Error("Connection closed by Twitter."))),this.res.on("data",(Z)=>{if(this.resetKeepAliveTimeout(),Z.toString()===`\r
|
|
67
|
+
`)return this.emit(F.DataKeepAlive);this.parser.push(Z.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let W=this.requestData.payloadIsError;this.parser.on(r.ParsedData,(Z)=>{if(W&&W(Z))this.emit(F.DataError,Z),this.emit(F.Error,{type:F.DataError,error:Z,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(F.Data,Z)}),this.parser.on(r.ParseError,(Z)=>{this.emit(F.TweetParseError,Z),this.emit(F.Error,{type:F.TweetParseError,error:Z,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(F.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){if(this.keepAliveTimeout)clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0}unbindRetryTimeout(){if(this.retryTimeout)clearTimeout(this.retryTimeout),this.retryTimeout=void 0}closeWithoutEmit(){if(this.unbindTimeouts(),this.res)this.res.removeAllListeners(),this.res.destroy();if(this.req)this.req.removeAllListeners(),this.req.destroy()}close(){this.emit(F.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let Z=await new C1(this.requestData).makeRequestAsStream(),$=this.eventNames();for(let J of $){let Q=this.listeners(J);for(let Y of Q)Z.on(J,Y)}return Z}async connect(W={}){if(typeof W.autoReconnect<"u")this.autoReconnect=W.autoReconnect;if(typeof W.autoReconnectRetries<"u")this.autoReconnectRetries=W.autoReconnectRetries==="unlimited"?1/0:W.autoReconnectRetries;if(typeof W.keepAliveTimeout<"u")this.keepAliveTimeoutMs=W.keepAliveTimeout==="disable"?1/0:W.keepAliveTimeout;if(typeof W.nextRetryTimeout<"u")this.nextRetryTimeout=W.nextRetryTimeout;this.unbindTimeouts();try{await this.reconnect()}catch(Z){if(this.emit(F.ConnectError,0),this.emit(F.Error,{type:F.ConnectError,error:Z,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,Z);else throw Z}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let W=!0;if(this.req)W=!1,this.closeWithoutEmit();let{req:Z,res:$,originalResponse:J}=await new C1(this.requestData).makeRequestAndResolveWhenReady();this.req=Z,this.res=$,this.originalResponse=J,this.emit(W?F.Connected:F.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(W=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(F.ConnectionClosed);return}if(W>=this.autoReconnectRetries){this.emit(F.ReconnectLimitExceeded),this.emit(F.ConnectionClosed);return}try{this.emit(F.ReconnectAttempt,W),await this.reconnect()}catch(Z){this.emit(F.ReconnectError,W),this.emit(F.Error,{type:F.ReconnectError,error:Z,message:`Reconnect error - ${W+1} attempts made yet.`}),this.makeAutoReconnectRetry(W,Z)}}makeAutoReconnectRetry(W,Z){let $=this.nextRetryTimeout(W+1,Z);this.retryTimeout=setTimeout(()=>{this.onConnectionError(W+1)},$)}async*[Symbol.asyncIterator](){let W=new V6(this);try{while(!0){if(!this.req||this.req.aborted)throw Error("Connection closed");if(W.hasStack())yield*W.popStack();let{type:Z,payload:$}=await W.nextEvent();if(Z==="error")throw $}}finally{W.destroy()}}}var n1=P6;function b6(W){var Z;if(!((Z=W.clientSettings.plugins)===null||Z===void 0?void 0:Z.length))return!1;for(let $ of W.clientSettings.plugins)if($.onRequestError||$.onResponseError)return!0;return!1}async function q6(W,Z,$,J){let Q;if(J instanceof S1||J instanceof R1)Q=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:J});else if(J instanceof _1)Q=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:J});if(Q&&Q instanceof k1)return Q.value;return Promise.reject(J)}import*as I6 from"crypto";class b{constructor(W){this.nonceLength=32,this.consumerKeys=W.consumerKeys}static percentEncode(W){return encodeURIComponent(W).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(W,Z){return I6.createHmac("sha1",Z).update(W).digest("base64")}authorize(W,Z={}){let $={oauth_consumer_key:this.consumerKeys.key,oauth_nonce:this.getNonce(),oauth_signature_method:"HMAC-SHA1",oauth_timestamp:this.getTimestamp(),oauth_version:"1.0"};if(Z.key!==void 0)$.oauth_token=Z.key;if(!W.data)W.data={};return $.oauth_signature=this.getSignature(W,Z.secret,$),$}toHeader(W){let Z=w6(W),$="OAuth ";for(let J of Z){if(J.key.indexOf("oauth_")!==0)continue;$+=b.percentEncode(J.key)+'="'+b.percentEncode(J.value)+'",'}return{Authorization:$.slice(0,$.length-1)}}getNonce(){let Z="";for(let $=0;$<this.nonceLength;$++)Z+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.trunc(Math.random()*62)];return Z}getTimestamp(){return Math.trunc(new Date().getTime()/1000)}getSignature(W,Z,$){return this.hash(this.getBaseString(W,$),this.getSigningKey(Z))}getSigningKey(W){return b.percentEncode(this.consumerKeys.secret)+"&"+b.percentEncode(W||"")}getBaseString(W,Z){return W.method.toUpperCase()+"&"+b.percentEncode(this.getBaseUrl(W.url))+"&"+b.percentEncode(this.getParameterString(W,Z))}getParameterString(W,Z){let $=w6(cW(v6(Z,v6(W.data,mW(W.url))))),J="";for(let{key:Q,value:Y}of $)if(Y&&Array.isArray(Y)){Y.sort();let K="";Y.forEach((z,X)=>{if(K+=Q+"="+z,X<Y.length)K+="&"}),J+=K}else J+=Q+"="+Y+"&";return J.slice(0,J.length-1)}getBaseUrl(W){return W.split("?")[0]}}var V1=b;function v6(W,Z){return{...W||{},...Z||{}}}function w6(W){return Object.keys(W).sort().map((Z)=>({key:Z,value:W[Z]}))}function EW(W){let Z=W.split("&"),$={};for(let J of Z){let[Q,Y=""]=J.split("=");if($[Q]){if(!Array.isArray($[Q]))$[Q]=[$[Q]];$[Q].push(decodeURIComponent(Y))}else $[Q]=decodeURIComponent(Y)}return $}function mW(W){let Z=W.split("?");if(Z.length===1)return{};return EW(Z[1])}function cW(W){let Z={};for(let $ in W){let J=W[$];if(J&&Array.isArray(J))J=J.map((Q)=>b.percentEncode(Q));else J=b.percentEncode(J);Z[b.percentEncode($)]=J}return Z}class q{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...W){let Z=W.map(($)=>$ instanceof Buffer?$:Buffer.from($));this._chunks.push(...Z)}append(W,Z,$){let J=Z instanceof Buffer?Z:Z.toString(),Q=this.getMultipartHeader(W,J,$);this.bodyAppend(Q,J,q.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((W,Z)=>W+Z.length,this.getMultipartFooter().length)}getBuffer(){let W=[...this._chunks,this.getMultipartFooter()],Z=Buffer.alloc(this.getLength()),$=0;for(let J of W)for(let Q=0;Q<J.length;$++,Q++)Z[$]=J[Q];return Z}getBoundary(){if(!this._boundary)this.generateBoundary();return this._boundary}generateBoundary(){let W="--------------------------";for(let Z=0;Z<24;Z++)W+=Math.floor(Math.random()*10).toString(16);this._boundary=W}getMultipartHeader(W,Z,$){if(!$)$=Z instanceof Buffer?q.DEFAULT_CONTENT_TYPE:"";let J={"Content-Disposition":["form-data",`name="${W}"`],"Content-Type":$},Q="";for(let[Y,K]of Object.entries(J)){if(!K.length)continue;Q+=Y+": "+d1(K).join("; ")+q.LINE_BREAK}return"--"+this.getBoundary()+q.LINE_BREAK+Q+q.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+q.LINE_BREAK)}}q.LINE_BREAK=`\r
|
|
68
|
+
`;q.DEFAULT_CONTENT_TYPE="application/octet-stream";class m4{static formatQueryToString(W){let Z={};for(let $ in W)if(typeof W[$]==="string")Z[$]=W[$];else if(typeof W[$]<"u")Z[$]=String(W[$]);return Z}static autoDetectBodyType(W){if(W.pathname.startsWith("/2/")||W.pathname.startsWith("/labs/2/")){if(W.password.startsWith("/2/oauth2"))return"url";return"json"}if(W.hostname==="upload.x.com"){if(W.pathname==="/1.1/media/upload.json")return"form-data";return"json"}let Z=W.pathname.split("/1.1/",2)[1];if(this.JSON_1_1_ENDPOINTS.has(Z))return"json";return"url"}static addQueryParamsToUrl(W,Z){let $=Object.entries(Z);if($.length){let J="";for(let[Q,Y]of $)J+=(J.length?"&":"?")+`${V1.percentEncode(Q)}=${V1.percentEncode(Y)}`;W.search=J}}static constructBodyParams(W,Z,$){if(W instanceof Buffer)return W;if($==="json"){if(!Z["content-type"])Z["content-type"]="application/json;charset=UTF-8";return JSON.stringify(W)}else if($==="url"){if(!Z["content-type"])Z["content-type"]="application/x-www-form-urlencoded;charset=UTF-8";if(Object.keys(W).length)return new URLSearchParams(W).toString().replace(/\*/g,"%2A");return""}else if($==="raw")throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");else{let J=new q;for(let Q in W)J.append(Q,W[Q]);if(!Z["content-type"]){let Q=J.getHeaders();Z["content-type"]=Q["content-type"]}return J.getBuffer()}}static setBodyLengthHeader(W,Z){var $;if(W.headers=($=W.headers)!==null&&$!==void 0?$:{},typeof Z==="string")W.headers["content-length"]=Buffer.byteLength(Z);else W.headers["content-length"]=Z.length}static isOAuthSerializable(W){return!(W instanceof Buffer)}static mergeQueryAndBodyForOAuth(W,Z){let $={};for(let J in W)$[J]=W[J];if(this.isOAuthSerializable(Z))for(let J in Z){let Q=Z[J];if(this.isOAuthSerializable(Q))$[J]=typeof Q==="object"&&Q!==null&&"toString"in Q?Q.toString():Q}return $}static moveUrlQueryParamsIntoObject(W,Z){for(let[$,J]of W.searchParams)Z[$]=J;return W.search="",W}static applyRequestParametersToUrl(W,Z){return W.pathname=W.pathname.replace(/:([A-Z_-]+)/ig,($,J)=>{if(Z[J]!==void 0)return String(Z[J]);return $}),W}}m4.JSON_1_1_ENDPOINTS=new Set(["direct_messages/events/new.json","direct_messages/welcome_messages/new.json","direct_messages/welcome_messages/rules/new.json","media/metadata/create.json","collections/entries/curate.json"]);var f=m4;import*as y6 from"crypto";class e{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url(y6.createHash("sha256").update(W).digest("base64"))}static getAuthHeader(W,Z){let $=encodeURIComponent(W)+":"+encodeURIComponent(Z);return Buffer.from($).toString("base64")}static generateRandomString(W){let Z="",$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let J=0;J<W;J++)Z+=$[Math.floor(Math.random()*$.length)];return Z}static escapeBase64Url(W){return W.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class K1{constructor(W){if(this.rateLimits={},this.clientSettings={},W)this.clientSettings=W}getRateLimits(){return this.rateLimits}saveRateLimit(W,Z){this.rateLimits[W]=Z}async send(W){var Z,$,J,Q,Y;if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length){let j=await this.applyPreRequestConfigHooks(W);if(j)return j}let K=this.getHttpRequestArgs(W),z={method:K.method,headers:K.headers,timeout:W.timeout,agent:this.clientSettings.httpAgent},X=W.enableRateLimitSave!==!1;if(K.body)f.setBodyLengthHeader(z,K.body);if(($=this.clientSettings.plugins)===null||$===void 0?void 0:$.length)await this.applyPreRequestHooks(W,K,z);let G=new C1({url:K.url,options:z,body:K.body,rateLimitSaver:X?this.saveRateLimit.bind(this,K.rawUrl):void 0,requestEventDebugHandler:W.requestEventDebugHandler,compression:(Q=(J=W.compression)!==null&&J!==void 0?J:this.clientSettings.compression)!==null&&Q!==void 0?Q:!0,forceParseMode:W.forceParseMode}).makeRequest();if(b6(this))G=this.applyResponseErrorHooks(W,K,z,G);let B=await G;if((Y=this.clientSettings.plugins)===null||Y===void 0?void 0:Y.length){let j=await this.applyPostRequestHooks(W,K,z,B);if(j)return j.value}return B}sendStream(W){var Z,$;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(W);let J=this.getHttpRequestArgs(W),Q={method:J.method,headers:J.headers,agent:this.clientSettings.httpAgent},Y=W.enableRateLimitSave!==!1,K=W.autoConnect!==!1;if(J.body)f.setBodyLengthHeader(Q,J.body);let z={url:J.url,options:Q,body:J.body,rateLimitSaver:Y?this.saveRateLimit.bind(this,J.rawUrl):void 0,payloadIsError:W.payloadIsError,compression:($=(Z=W.compression)!==null&&Z!==void 0?Z:this.clientSettings.compression)!==null&&$!==void 0?$:!0},X=new n1(z);if(!K)return X;return X.connect()}initializeToken(W){if(typeof W==="string")this.bearerToken=W;else if(typeof W==="object"&&"appKey"in W){if(this.consumerToken=W.appKey,this.consumerSecret=W.appSecret,W.accessToken&&W.accessSecret)this.accessToken=W.accessToken,this.accessSecret=W.accessSecret;this._oauth=this.buildOAuth()}else if(typeof W==="object"&&"username"in W){let Z=encodeURIComponent(W.username)+":"+encodeURIComponent(W.password);this.basicToken=Buffer.from(Z).toString("base64")}else if(typeof W==="object"&&"clientId"in W)this.clientId=W.clientId,this.clientSecret=W.clientSecret}getActiveTokens(){if(this.bearerToken)return{type:"oauth2",bearerToken:this.bearerToken};else if(this.basicToken)return{type:"basic",token:this.basicToken};else if(this.consumerSecret&&this._oauth)return{type:"oauth-1.0a",appKey:this.consumerToken,appSecret:this.consumerSecret,accessToken:this.accessToken,accessSecret:this.accessSecret};else if(this.clientId)return{type:"oauth2-user",clientId:this.clientId};return{type:"none"}}buildOAuth(){if(!this.consumerSecret||!this.consumerToken)throw Error("Invalid consumer tokens");return new V1({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(!this.accessSecret||!this.accessToken)return;return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var W;return(W=this.clientSettings.plugins)!==null&&W!==void 0?W:[]}hasPlugins(){var W;return!!((W=this.clientSettings.plugins)===null||W===void 0?void 0:W.length)}async applyPluginMethod(W,Z){var $;let J;for(let Q of this.getPlugins()){let Y=await(($=Q[W])===null||$===void 0?void 0:$.call(Q,Z));if(Y&&Y instanceof k1)J=Y}return J}writeAuthHeaders({headers:W,bodyInSignature:Z,url:$,method:J,query:Q,body:Y}){if(W={...W},this.bearerToken)W.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)W.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)W.Authorization="Basic "+e.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let K=Z?f.mergeQueryAndBodyForOAuth(Q,Y):Q,z=this._oauth.authorize({url:$.toString(),method:J,data:K},this.getOAuthAccessTokens());W={...W,...this._oauth.toHeader(z)}}return W}getUrlObjectFromUrlString(W){if(!W.startsWith("http"))W="https://"+W;return new URL(W)}getHttpRequestArgs({url:W,method:Z,query:$={},body:J={},headers:Q,forceBodyMode:Y,enableAuth:K,params:z}){let X=void 0;if(Z=Z.toUpperCase(),Q=Q!==null&&Q!==void 0?Q:{},!Q["x-user-agent"])Q["x-user-agent"]="Node.twitter-api-v2";let G=this.getUrlObjectFromUrlString(W),B=G.origin+G.pathname;if(z)f.applyRequestParametersToUrl(G,z);let j=f.formatQueryToString($);if(f.moveUrlQueryParamsIntoObject(G,j),!(J instanceof Buffer))k6(J);let N=Y!==null&&Y!==void 0?Y:f.autoDetectBodyType(G);if(K!==!1){let S=K1.BODY_METHODS.has(Z)&&N==="url";Q=this.writeAuthHeaders({headers:Q,bodyInSignature:S,method:Z,query:j,url:G,body:J})}if(K1.BODY_METHODS.has(Z))X=f.constructBodyParams(J,Q,N)||void 0;return f.addQueryParamsToUrl(G,j),{rawUrl:B,url:G,method:Z,headers:Q,body:X}}async applyPreRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let J of this.getPlugins()){let Q=await((Z=J.onBeforeRequestConfig)===null||Z===void 0?void 0:Z.call(J,{client:this,url:$,params:W}));if(Q)return Q}}applyPreStreamRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let J of this.getPlugins())(Z=J.onBeforeStreamRequestConfig)===null||Z===void 0||Z.call(J,{client:this,url:$,params:W})}async applyPreRequestHooks(W,Z,$){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$})}async applyPostRequestHooks(W,Z,$,J){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,response:J})}applyResponseErrorHooks(W,Z,$,J){return J.catch(q6.bind(this,W,Z,$))}}K1.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class d{constructor(W,Z={}){if(this._currentUser=null,this._currentUserV2=null,W instanceof d)this._requestMaker=W._requestMaker;else this._requestMaker=new K1(Z),this._requestMaker.initializeToken(W)}setPrefix(W){this._prefix=W}cloneWithPrefix(W){let Z=this.constructor(this);return Z.setPrefix(W),Z}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(W){return this.getPlugins().find((Z)=>Z instanceof W)}hasHitRateLimit(W){var Z;if(this.isRateLimitStatusObsolete(W))return!1;return((Z=this.getLastRateLimitStatus(W))===null||Z===void 0?void 0:Z.remaining)===0}isRateLimitStatusObsolete(W){let Z=this.getLastRateLimitStatus(W);if(Z===void 0)return!0;return Z.reset*1000<Date.now()}getLastRateLimitStatus(W){let Z=W.match(/^https?:\/\//)?W:this._prefix+W;return this._requestMaker.getRateLimits()[Z]}getCurrentUserObject(W=!1){if(!W&&this._currentUser){if(this._currentUser.value)return Promise.resolve(this._currentUser.value);return this._currentUser.promise}return this._currentUser=g4(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:u})),this._currentUser.promise}getCurrentUserV2Object(W=!1){if(!W&&this._currentUserV2){if(this._currentUserV2.value)return Promise.resolve(this._currentUserV2.value);return this._currentUserV2.promise}return this._currentUserV2=g4(()=>this.get("users/me",void 0,{prefix:c})),this._currentUserV2.promise}async get(W,Z={},{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"GET",query:Z,...Q});return $?Y:Y.data}async delete(W,Z={},{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"DELETE",query:Z,...Q});return $?Y:Y.data}async post(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"POST",body:Z,...Q});return $?Y:Y.data}async put(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"PUT",body:Z,...Q});return $?Y:Y.data}async patch(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"PATCH",body:Z,...Q});return $?Y:Y.data}getStream(W,Z,{prefix:$=this._prefix,...J}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"GET",query:Z,...J})}postStream(W,Z,{prefix:$=this._prefix,...J}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"POST",body:Z,...J})}}class C extends d{constructor(W){if(!(W instanceof d))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(W)}}class z1 extends Y1{constructor(){super(...arguments);this.hasFinishedFetch=!1}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.push(...$),this.hasFinishedFetch=$.length===0}getNextQueryParams(W){let Z=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(W),max_id:(Z-BigInt(1)).toString()}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class c4 extends z1{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class u4 extends z1{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class s1 extends z1{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class p4 extends z1{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class o1 extends z1{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class d4 extends H{constructor(){super(...arguments);this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class l4 extends H{constructor(){super(...arguments);this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class n4 extends H{constructor(){super(...arguments);this._endpoint="followers/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class i4 extends H{constructor(){super(...arguments);this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class s4 extends H{constructor(){super(...arguments);this._endpoint="friends/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class o4 extends H{constructor(){super(...arguments);this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class a4 extends Y1{constructor(){super(...arguments);this._endpoint="users/search.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.push(...$)}getNextQueryParams(W){var Z;let $=Number((Z=this._queryParams.page)!==null&&Z!==void 0?Z:"1");return{...this._queryParams,page:$+1,...W?{count:W}:{}}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.users}get users(){return this._realData}}class a1 extends H{constructor(){super(...arguments);this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class t4 extends a1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class t1 extends H{refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.lists.push(...$.lists),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class r4 extends t1{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class e4 extends t1{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class W0 extends t1{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class Z0 extends H{refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class $0 extends Z0{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class J0 extends Z0{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class G1 extends C{constructor(){super(...arguments);this._prefix=u}singleTweet(W,Z={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:W,...Z})}tweets(W,Z={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:W,...Z})}oembedTweet(W,Z={}){return this.get("oembed",{url:`https://x.com/i/statuses/${W}`,...Z},{prefix:"https://publish.x.com/"})}async homeTimeline(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("statuses/home_timeline.json",Z,{fullResponse:!0});return new c4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async mentionTimeline(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("statuses/mentions_timeline.json",Z,{fullResponse:!0});return new u4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},J=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new s1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async userTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},J=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new s1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async favoriteTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},J=await this.get("favorites/list.json",$,{fullResponse:!0});return new o1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async favoriteTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},J=await this.get("favorites/list.json",$,{fullResponse:!0});return new o1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}user(W){return this.get("users/show.json",{tweet_mode:"extended",...W})}users(W){return this.get("users/lookup.json",{tweet_mode:"extended",...W})}verifyCredentials(W={}){return this.get("account/verify_credentials.json",W)}async listMutedUsers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("mutes/users/list.json",Z,{fullResponse:!0});return new d4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listMutedUserIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("mutes/users/ids.json",Z,{fullResponse:!0});return new l4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFriendList(W={}){let Z={...W},$=await this.get("friends/list.json",Z,{fullResponse:!0});return new s4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowerList(W={}){let Z={...W},$=await this.get("followers/list.json",Z,{fullResponse:!0});return new n4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowerIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("followers/ids.json",Z,{fullResponse:!0});return new i4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowingIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friends/ids.json",Z,{fullResponse:!0});return new o4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async searchUsers(W,Z={}){let $={q:W,tweet_mode:"extended",page:1,...Z},J=await this.get("users/search.json",$,{fullResponse:!0});return new a4({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}friendship(W){return this.get("friendships/show.json",W)}friendships(W){return this.get("friendships/lookup.json",W)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friendships/incoming.json",Z,{fullResponse:!0});return new a1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async friendshipsOutgoing(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friendships/outgoing.json",Z,{fullResponse:!0});return new t4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(W){return this.get("users/profile_banner.json",W)}list(W){return this.get("lists/show.json",{tweet_mode:"extended",...W})}lists(W={}){return this.get("lists/list.json",{tweet_mode:"extended",...W})}async listMembers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/members.json",Z,{fullResponse:!0});return new $0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}listGetMember(W){return this.get("lists/members/show.json",{tweet_mode:"extended",...W})}async listMemberships(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/memberships.json",Z,{fullResponse:!0});return new r4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listOwnerships(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/ownerships.json",Z,{fullResponse:!0});return new e4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listStatuses(W){let Z={tweet_mode:"extended",...W},$=await this.get("lists/statuses.json",Z,{fullResponse:!0});return new p4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listSubscribers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/subscribers.json",Z,{fullResponse:!0});return new J0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}listGetSubscriber(W){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...W})}async listSubscriptions(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/subscriptions.json",Z,{fullResponse:!0});return new W0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}mediaInfo(W){return this.get("media/upload.json",{command:"STATUS",media_id:W},{prefix:E})}filterStream({autoConnect:W,...Z}={}){let $={};for(let[Q,Y]of Object.entries(Z))if(Q==="follow"||Q==="track")$[Q]=Y.toString();else if(Q==="locations"){let K=Y;$.locations=d1(K).map((z)=>`${z.lng},${z.lat}`).join(",")}else $[Q]=Y;return this.stream.postStream("statuses/filter.json",$,{autoConnect:W})}sampleStream({autoConnect:W,...Z}={}){return this.stream.getStream("statuses/sample.json",Z,{autoConnect:W})}get stream(){let W=new r1(this);return W.setPrefix(S6),W}trendsByPlace(W,Z={}){return this.get("trends/place.json",{id:W,...Z})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(W,Z){return this.get("trends/closest.json",{lat:W,long:Z})}geoPlace(W){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:W}})}geoSearch(W){return this.get("geo/search.json",W)}geoReverseGeoCode(W){return this.get("geo/reverse_geocode.json",W)}rateLimitStatuses(...W){return this.get("application/rate_limit_status.json",{resources:W})}supportedLanguages(){return this.get("help/languages.json")}}import*as l from"fs";async function Q0(W){let Z=await Y0(W);if(typeof Z==="number")return new Promise(($,J)=>{l.readFile(Z,(Q,Y)=>{if(Q)return J(Q);$(Y)})});else if(Z instanceof Buffer)return Z;else return Z.readFile()}function Y0(W){if(typeof W==="string")return l.promises.open(W,"r");else if(typeof W==="number")return W;else if(typeof W==="object"&&!(W instanceof Buffer))return W;else if(!(W instanceof Buffer))throw Error("Given file is not valid, please check its type.");else return W}async function A6(W){if(typeof W==="number")return(await new Promise(($,J)=>{l.fstat(W,(Q,Y)=>{if(Q)J(Q);$(Y)})})).size;else if(W instanceof Buffer)return W.length;else return(await W.stat()).size}function h6(W,Z,$){if(typeof $==="string")return $;else if(typeof W==="string"&&!Z)return uW(W);else if(typeof Z==="string")return pW(Z);throw Error("You must specify type if file is a file handle or Buffer.")}function uW(W){if(W.endsWith(".jpeg")||W.endsWith(".jpg"))return D.Jpeg;if(W.endsWith(".png"))return D.Png;if(W.endsWith(".webp"))return D.Webp;if(W.endsWith(".gif"))return D.Gif;if(W.endsWith(".mpeg4")||W.endsWith(".mp4"))return D.Mp4;if(W.endsWith(".mov")||W.endsWith(".mov"))return D.Mov;if(W.endsWith(".srt"))return D.Srt;return E4({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"options.mimeType is missing and filename couldn't help to resolve MIME type, so it will fallback to image/jpeg",resolution:"If you except to give filenames without extensions, please specify explicitlty the MIME type using options.mimeType"}),D.Jpeg}function pW(W){if(E4({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"you're using options.type",resolution:"Remove options.type argument and migrate to options.mimeType which takes the real MIME type. If you're using type=longmp4, add options.longVideo alongside of mimeType=EUploadMimeType.Mp4"}),W==="gif")return D.Gif;if(W==="jpg")return D.Jpeg;if(W==="png")return D.Png;if(W==="webp")return D.Webp;if(W==="srt")return D.Srt;if(W==="mp4"||W==="longmp4")return D.Mp4;if(W==="mov")return D.Mov;return W}function g6(W,Z){if(W===D.Mp4||W===D.Mov)return Z==="tweet"?"TweetVideo":"DmVideo";if(W===D.Gif)return Z==="tweet"?"TweetGif":"DmGif";if(W===D.Srt)return"Subtitles";else return Z==="tweet"?"TweetImage":"DmImage"}function K0(W){return new Promise((Z)=>setTimeout(Z,W*1000))}async function z0(W,Z,$=0,J){if(W instanceof Buffer){let Y=W.slice($,$+Z);return[Y,Y.length]}if(!J)throw Error("Well, we will need a buffer to store file content.");let Q;if(typeof W==="number")Q=await new Promise((Y,K)=>{l.read(W,J,0,Z,$,(z,X)=>{if(z)K(z);Y(X)})});else Q=(await W.read(J,0,Z,$)).bytesRead;return[J,Q]}var G0="media/upload.json";class X1 extends G1{constructor(){super(...arguments);this._prefix=u}get readOnly(){return this}tweet(W,Z={}){let $={status:W,tweet_mode:"extended",...Z};return this.post("statuses/update.json",$)}async quote(W,Z,$={}){let J="https://x.com/i/statuses/"+Z;return this.tweet(W,{...$,attachment_url:J})}async tweetThread(W){let Z=[];for(let $ of W){let J=Z.length?Z[Z.length-1]:null,Q={...typeof $==="string"?{status:$}:$},Y=J?J.id_str:Q.in_reply_to_status_id,K=Q.status;if(Y)Z.push(await this.reply(K,Y,Q));else Z.push(await this.tweet(K,Q))}return Z}reply(W,Z,$={}){return this.tweet(W,{auto_populate_reply_metadata:!0,in_reply_to_status_id:Z,...$})}deleteTweet(W){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:W}})}reportUserAsSpam(W){return this.post("users/report_spam.json",{tweet_mode:"extended",...W})}updateFriendship(W){return this.post("friendships/update.json",W)}createFriendship(W){return this.post("friendships/create.json",W)}destroyFriendship(W){return this.post("friendships/destroy.json",W)}updateAccountSettings(W){return this.post("account/settings.json",W)}updateAccountProfile(W){return this.post("account/update_profile.json",W)}async updateAccountProfileBanner(W,Z={}){let $={banner:await Q0(W),...Z};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,Z={}){let $={tweet_mode:"extended",image:await Q0(W),...Z};return this.post("account/update_profile_image.json",$,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(W){return this.post("lists/create.json",{tweet_mode:"extended",...W})}updateList(W){return this.post("lists/update.json",{tweet_mode:"extended",...W})}removeList(W){return this.post("lists/destroy.json",{tweet_mode:"extended",...W})}addListMembers(W){let $=W.user_id&&f1(W.user_id)||W.screen_name&&f1(W.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,W)}removeListMembers(W){let $=W.user_id&&f1(W.user_id)||W.screen_name&&f1(W.screen_name)?"lists/members/destroy_all.json":"lists/members/destroy.json";return this.post($,W)}subscribeToList(W){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...W})}unsubscribeOfList(W){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...W})}createMediaMetadata(W,Z){return this.post("media/metadata/create.json",{media_id:W,...Z},{prefix:E,forceBodyMode:"json"})}createMediaSubtitles(W,Z){return this.post("media/subtitles/create.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z}},{prefix:E,forceBodyMode:"json"})}deleteMediaSubtitles(W,...Z){return this.post("media/subtitles/delete.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z.map(($)=>({language_code:$}))}},{prefix:E,forceBodyMode:"json"})}async uploadMedia(W,Z={},$=!1){var J;let Q=(J=Z.chunkLength)!==null&&J!==void 0?J:1048576,{fileHandle:Y,mediaCategory:K,fileSize:z,mimeType:X}=await this.getUploadMediaRequirements(W,Z);try{let G=await this.post(G0,{command:"INIT",total_bytes:z,media_type:X,media_category:K,additional_owners:Z.additionalOwners,shared:Z.shared?!0:void 0},{prefix:E});await this.mediaChunkedUpload(Y,Q,G.media_id_string,Z.maxConcurrentUploads);let B=await this.post(G0,{command:"FINALIZE",media_id:G.media_id_string},{prefix:E});if(B.processing_info&&B.processing_info.state!=="succeeded")await this.awaitForMediaProcessingCompletion(B);if($)return B;else return B.media_id_string}finally{if(typeof W==="number")X0.close(W,()=>{});else if(typeof Y==="object"&&!(Y instanceof Buffer))Y.close()}}async awaitForMediaProcessingCompletion(W){var Z;while(!0){W=await this.mediaInfo(W.media_id_string);let{processing_info:$}=W;if(!$||$.state==="succeeded")return;if((Z=$.error)===null||Z===void 0?void 0:Z.code){let{name:J,message:Q}=$.error;throw Error(`Failed to process media: ${J} - ${Q}.`)}if($.state==="failed")throw Error("Failed to process the media.");if($.check_after_secs)await K0($.check_after_secs);else await K0(5)}}async getUploadMediaRequirements(W,{mimeType:Z,type:$,target:J,longVideo:Q}={}){let Y;try{Y=await Y0(W);let K=h6(W,$,Z),z;if(K===D.Mp4&&(!Z&&!$&&J!=="dm"||Q))z="amplify_video";else z=g6(K,J!==null&&J!==void 0?J:"tweet");return{fileHandle:Y,mediaCategory:z,fileSize:await A6(Y),mimeType:K}}catch(K){if(typeof W==="number")X0.close(W,()=>{});else if(typeof Y==="object"&&!(Y instanceof Buffer))Y.close();throw K}}async mediaChunkedUpload(W,Z,$,J=3){let Q=0;if(J<1)throw RangeError("Bad maxConcurrentUploads parameter.");let Y=W instanceof Buffer?void 0:Buffer.alloc(Z),K,z,X=0;[K,z]=await z0(W,Z,X,Y),X+=z;let G=new Set;while(z){let B=K.slice(0,z);if(B.length){let j=this.post(G0,{command:"APPEND",media_id:$,segment_index:Q,media:B},{prefix:E});G.add(j),j.then(()=>{G.delete(j)}),Q++}if(G.size>=J)await Promise.race(G);[K,z]=await z0(W,Z,X,Y),X+=z}await Promise.all([...G])}}class E6 extends X1{constructor(){super(...arguments);this._prefix=u}get readWrite(){return this}sendDm({recipient_id:W,custom_profile_id:Z,...$}){let J={event:{type:p.Create,[p.Create]:{target:{recipient_id:W},message_data:$}}};if(Z)J.event[p.Create].custom_profile_id=Z;return this.post("direct_messages/events/new.json",J,{forceBodyMode:"json"})}getDmEvent(W){return this.get("direct_messages/events/show.json",{id:W})}deleteDm(W){return this.delete("direct_messages/events/destroy.json",{id:W})}async listDmEvents(W={}){let Z={...W},$=await this.get("direct_messages/events/list.json",Z,{fullResponse:!0});return new A4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDm(W,Z){let $={[p.WelcomeCreate]:{name:W,message_data:Z}};return this.post("direct_messages/welcome_messages/new.json",$,{forceBodyMode:"json"})}getWelcomeDm(W){return this.get("direct_messages/welcome_messages/show.json",{id:W})}deleteWelcomeDm(W){return this.delete("direct_messages/welcome_messages/destroy.json",{id:W})}updateWelcomeDm(W,Z){let $={message_data:Z};return this.put("direct_messages/welcome_messages/update.json",$,{forceBodyMode:"json",query:{id:W}})}async listWelcomeDms(W={}){let Z={...W},$=await this.get("direct_messages/welcome_messages/list.json",Z,{fullResponse:!0});return new h4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDmRule(W){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:W}},{forceBodyMode:"json"})}getWelcomeDmRule(W){return this.get("direct_messages/welcome_messages/rules/show.json",{id:W})}deleteWelcomeDmRule(W){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:W})}async listWelcomeDmRules(W={}){let Z={...W};return this.get("direct_messages/welcome_messages/rules/list.json",Z)}async setWelcomeDm(W,Z=!0){var $;let J=await this.listWelcomeDmRules();if(($=J.welcome_message_rules)===null||$===void 0?void 0:$.length){for(let Q of J.welcome_message_rules)if(await this.deleteWelcomeDmRule(Q.id),Z)await this.deleteWelcomeDm(Q.welcome_message_id)}return this.newWelcomeDmRule(W)}markDmAsRead(W,Z){return this.post("direct_messages/mark_read.json",{last_read_event_id:W,recipient_id:Z},{forceBodyMode:"url"})}indicateDmTyping(W){return this.post("direct_messages/indicate_typing.json",{recipient_id:W},{forceBodyMode:"url"})}async downloadDmImage(W){if(typeof W!=="string"){let $=W[p.Create].message_data.attachment;if(!$)throw Error("The given direct message doesn't contain any attachment");W=$.media.media_url_https}let Z=await this.get(W,void 0,{forceParseMode:"buffer",prefix:""});if(!Z.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return Z}}var r1=E6;class L{constructor(W){this.result=W}get tweets(){return L.tweets(this.result)}static tweets(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.tweets)!==null&&$!==void 0?$:[]}tweetById(W){return L.tweetById(this.result,W)}static tweetById(W,Z){return this.tweets(W).find(($)=>$.id===Z)}retweet(W){return L.retweet(this.result,W)}static retweet(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="retweeted").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}quote(W){return L.quote(this.result,W)}static quote(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="quoted").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}repliedTo(W){return L.repliedTo(this.result,W)}static repliedTo(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="replied_to").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}author(W){return L.author(this.result,W)}static author(W,Z){let $=Z.author_id;return $?this.users(W).find((J)=>J.id===$):void 0}repliedToAuthor(W){return L.repliedToAuthor(this.result,W)}static repliedToAuthor(W,Z){let $=Z.in_reply_to_user_id;return $?this.users(W).find((J)=>J.id===$):void 0}get users(){return L.users(this.result)}static users(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.users)!==null&&$!==void 0?$:[]}userById(W){return L.userById(this.result,W)}static userById(W,Z){return this.users(W).find(($)=>$.id===Z)}pinnedTweet(W){return L.pinnedTweet(this.result,W)}static pinnedTweet(W,Z){return Z.pinned_tweet_id?this.tweets(W).find(($)=>$.id===Z.pinned_tweet_id):void 0}get media(){return L.media(this.result)}static media(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.media)!==null&&$!==void 0?$:[]}medias(W){return L.medias(this.result,W)}static medias(W,Z){var $,J;let Q=(J=($=Z.attachments)===null||$===void 0?void 0:$.media_keys)!==null&&J!==void 0?J:[];return this.media(W).filter((Y)=>Q.includes(Y.media_key))}get polls(){return L.polls(this.result)}static polls(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.polls)!==null&&$!==void 0?$:[]}poll(W){return L.poll(this.result,W)}static poll(W,Z){var $,J;let Q=(J=($=Z.attachments)===null||$===void 0?void 0:$.poll_ids)!==null&&J!==void 0?J:[];if(Q.length){let Y=Q[0];return this.polls(W).find((K)=>K.id===Y)}return}get places(){return L.places(this.result)}static places(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.places)!==null&&$!==void 0?$:[]}place(W){return L.place(this.result,W)}static place(W,Z){var $;let J=($=Z.geo)===null||$===void 0?void 0:$.place_id;return J?this.places(W).find((Q)=>Q.id===J):void 0}listOwner(W){return L.listOwner(this.result,W)}static listOwner(W,Z){let $=Z.owner_id;return $?this.users(W).find((J)=>J.id===$):void 0}spaceCreator(W){return L.spaceCreator(this.result,W)}static spaceCreator(W,Z){let $=Z.creator_id;return $?this.users(W).find((J)=>J.id===$):void 0}spaceHosts(W){return L.spaceHosts(this.result,W)}static spaceHosts(W,Z){var $;let J=($=Z.host_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}spaceSpeakers(W){return L.spaceSpeakers(this.result,W)}static spaceSpeakers(W,Z){var $;let J=($=Z.speaker_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}spaceInvitedUsers(W){return L.spaceInvitedUsers(this.result,W)}static spaceInvitedUsers(W,Z){var $;let J=($=Z.invited_user_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}}class e1 extends y4{updateIncludes(W){if(W.errors){if(!this._realData.errors)this._realData.errors=[];this._realData.errors=[...this._realData.errors,...W.errors]}if(!W.includes)return;if(!this._realData.includes)this._realData.includes={};let Z=this._realData.includes;for(let[$,J]of Object.entries(W.includes)){if(!Z[$])Z[$]=[];Z[$]=[...Z[$],...J]}}assertUsable(){if(this.unusable)throw Error("Unable to use this paginator to fetch more data, as it does not contain any metadata. Check .errors property for more details.")}get meta(){return this._realData.meta}get includes(){var W;if(!((W=this._realData)===null||W===void 0?void 0:W.includes))return new L(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new L(this._realData)}get errors(){var W;return(W=this._realData.errors)!==null&&W!==void 0?W:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class y extends e1{refreshInstanceFromResult(W,Z){var $;let J=W.data,Q=($=J.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.next_token=J.meta.next_token,this._realData.data.push(...Q);else this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.previous_token=J.meta.previous_token,this._realData.data.unshift(...Q);this.updateIncludes(J)}getNextQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(W){var Z,$;return($=(Z=W.data.data)===null||Z===void 0?void 0:Z.length)!==null&&$!==void 0?$:0}isFetchLastOver(W){var Z;return!((Z=W.data.data)===null||Z===void 0?void 0:Z.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){var Z;return!!((Z=W.meta)===null||Z===void 0?void 0:Z.next_token)}}class B0 extends e1{refreshInstanceFromResult(W,Z){var $;let J=W.data,Q=($=J.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.oldest_id=J.meta.oldest_id,this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.next_token=J.meta.next_token,this._realData.data.push(...Q);else this._realData.meta.newest_id=J.meta.newest_id,this._realData.meta.result_count+=J.meta.result_count,this._realData.data.unshift(...Q);this.updateIncludes(J)}getNextQueryParams(W){this.assertUsable();let Z={...this.injectQueryParams(W)};if(this._realData.meta.next_token)Z.next_token=this._realData.meta.next_token;else{if(Z.start_time)Z.since_id=this.dateStringToSnowflakeId(Z.start_time),delete Z.start_time;if(Z.end_time)delete Z.end_time;Z.until_id=this._realData.meta.oldest_id}return Z}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(W){var Z,$;return($=(Z=W.data.data)===null||Z===void 0?void 0:Z.length)!==null&&$!==void 0?$:0}isFetchLastOver(W){var Z;return!((Z=W.data.data)===null||Z===void 0?void 0:Z.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!!W.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(W){let Z=BigInt("1288834974657"),$=new Date(W);if(isNaN($.valueOf()))throw Error("Unable to convert start_time/end_time to a valid date. A ISO 8601 DateTime is excepted, please check your input.");return(BigInt($.valueOf())-Z<<BigInt("22")).toString()}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class B1 extends y{refreshInstanceFromResult(W,Z){super.refreshInstanceFromResult(W,Z);let $=W.data;if(Z)this._realData.meta.oldest_id=$.meta.oldest_id;else this._realData.meta.newest_id=$.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class j0 extends B0{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class F0 extends B0{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class M0 extends B1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class L0 extends B1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class N0 extends B1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class D0 extends B1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class H0 extends B1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class x0 extends y{get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class U0 extends x0{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class O0 extends x0{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class m extends y{getItemArray(){return this.users}get users(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class S0 extends m{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class R0 extends m{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class _0 extends m{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class k0 extends m{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class f0 extends m{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class C0 extends m{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class V0 extends m{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class T0 extends m{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class W4 extends y{getItemArray(){return this.lists}get lists(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class P0 extends W4{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class b0 extends W4{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class q0 extends W4{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class j1 extends C{constructor(){super(...arguments);this._prefix=$1}}class Z4 extends y{getItemArray(){return this.events}get events(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class v0 extends Z4{constructor(){super(...arguments);this._endpoint="dm_events"}}class w0 extends Z4{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class I0 extends Z4{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class F1 extends C{constructor(){super(...arguments);this._prefix=c}get labs(){if(this._labs)return this._labs;return this._labs=new j1(this)}async search(W,Z={}){let $=typeof W==="string"?{...Z,query:W}:{...W},J=await this.get("tweets/search/recent",$,{fullResponse:!0});return new j0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async searchAll(W,Z={}){let $={...Z,query:W},J=await this.get("tweets/search/all",$,{fullResponse:!0});return new F0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}singleTweet(W,Z={}){return this.get("tweets/:id",Z,{params:{id:W}})}tweets(W,Z={}){return this.get("tweets",{ids:W,...Z})}tweetCountRecent(W,Z={}){return this.get("tweets/counts/recent",{query:W,...Z})}tweetCountAll(W,Z={}){return this.get("tweets/counts/all",{query:W,...Z})}async tweetRetweetedBy(W,Z={}){let{asPaginator:$,...J}=Z,Q=await this.get("tweets/:id/retweeted_by",J,{fullResponse:!0,params:{id:W}});if(!$)return Q.data;return new T0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async tweetLikedBy(W,Z={}){let{asPaginator:$,...J}=Z,Q=await this.get("tweets/:id/liking_users",J,{fullResponse:!0,params:{id:W}});if(!$)return Q.data;return new V0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async homeTimeline(W={}){let Z=await this.getCurrentUserV2Object(),$=await this.get("users/:id/timelines/reverse_chronological",W,{fullResponse:!0,params:{id:Z.data.id}});return new L0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:Z.data.id}})}async userTimeline(W,Z={}){let $=await this.get("users/:id/tweets",Z,{fullResponse:!0,params:{id:W}});return new N0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async userMentionTimeline(W,Z={}){let $=await this.get("users/:id/mentions",Z,{fullResponse:!0,params:{id:W}});return new D0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async quotes(W,Z={}){let $=await this.get("tweets/:id/quote_tweets",Z,{fullResponse:!0,params:{id:W}});return new M0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async bookmarks(W={}){let Z=await this.getCurrentUserV2Object(),$=await this.get("users/:id/bookmarks",W,{fullResponse:!0,params:{id:Z.data.id}});return new H0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:Z.data.id}})}me(W={}){return this.get("users/me",W)}user(W,Z={}){return this.get("users/:id",Z,{params:{id:W}})}users(W,Z={}){let $=Array.isArray(W)?W.join(","):W;return this.get("users",{...Z,ids:$})}userByUsername(W,Z={}){return this.get("users/by/username/:username",Z,{params:{username:W}})}usersByUsernames(W,Z={}){return W=Array.isArray(W)?W.join(","):W,this.get("users/by",{...Z,usernames:W})}async followers(W,Z={}){let{asPaginator:$,...J}=Z,Q={id:W};if(!$)return this.get("users/:id/followers",J,{params:Q});let Y=await this.get("users/:id/followers",J,{fullResponse:!0,params:Q});return new _0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:J,sharedParams:Q})}async following(W,Z={}){let{asPaginator:$,...J}=Z,Q={id:W};if(!$)return this.get("users/:id/following",J,{params:Q});let Y=await this.get("users/:id/following",J,{fullResponse:!0,params:Q});return new k0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:J,sharedParams:Q})}async userLikedTweets(W,Z={}){let $={id:W},J=await this.get("users/:id/liked_tweets",Z,{fullResponse:!0,params:$});return new U0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userBlockingUsers(W,Z={}){let $={id:W},J=await this.get("users/:id/blocking",Z,{fullResponse:!0,params:$});return new S0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userMutingUsers(W,Z={}){let $={id:W},J=await this.get("users/:id/muting",Z,{fullResponse:!0,params:$});return new R0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}list(W,Z={}){return this.get("lists/:id",Z,{params:{id:W}})}async listsOwned(W,Z={}){let $={id:W},J=await this.get("users/:id/owned_lists",Z,{fullResponse:!0,params:$});return new P0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMemberships(W,Z={}){let $={id:W},J=await this.get("users/:id/list_memberships",Z,{fullResponse:!0,params:$});return new b0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowed(W,Z={}){let $={id:W},J=await this.get("users/:id/followed_lists",Z,{fullResponse:!0,params:$});return new q0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listTweets(W,Z={}){let $={id:W},J=await this.get("lists/:id/tweets",Z,{fullResponse:!0,params:$});return new O0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMembers(W,Z={}){let $={id:W},J=await this.get("lists/:id/members",Z,{fullResponse:!0,params:$});return new f0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowers(W,Z={}){let $={id:W},J=await this.get("lists/:id/followers",Z,{fullResponse:!0,params:$});return new C0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEvents(W={}){let Z=await this.get("dm_events",W,{fullResponse:!0});return new v0({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:{...W}})}async listDmEventsWithParticipant(W,Z={}){let $={participant_id:W},J=await this.get("dm_conversations/with/:participant_id/dm_events",Z,{fullResponse:!0,params:$});return new w0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEventsOfConversation(W,Z={}){let $={dm_conversation_id:W},J=await this.get("dm_conversations/:dm_conversation_id/dm_events",Z,{fullResponse:!0,params:$});return new I0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}space(W,Z={}){return this.get("spaces/:id",Z,{params:{id:W}})}spaces(W,Z={}){return this.get("spaces",{ids:W,...Z})}spacesByCreators(W,Z={}){return this.get("spaces/by/creator_ids",{user_ids:W,...Z})}searchSpaces(W){return this.get("spaces/search",W)}spaceBuyers(W,Z={}){return this.get("spaces/:id/buyers",Z,{params:{id:W}})}spaceTweets(W,Z={}){return this.get("spaces/:id/tweets",Z,{params:{id:W}})}searchStream({autoConnect:W,...Z}={}){return this.getStream("tweets/search/stream",Z,{payloadIsError:l1,autoConnect:W})}streamRules(W={}){return this.get("tweets/search/stream/rules",W)}updateStreamRules(W,Z={}){return this.post("tweets/search/stream/rules",W,{query:Z})}sampleStream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample/stream",Z,{payloadIsError:l1,autoConnect:W})}sample10Stream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample10/stream",Z,{payloadIsError:l1,autoConnect:W})}complianceJobs(W){return this.get("compliance/jobs",W)}complianceJob(W){return this.get("compliance/jobs/:id",void 0,{params:{id:W}})}async sendComplianceJob(W){let Z=await this.post("compliance/jobs",{type:W.type,name:W.name}),$=W.ids instanceof Buffer?W.ids:Buffer.from(W.ids.join(`
|
|
69
69
|
`));return await this.put(Z.data.upload_url,$,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),Z}async complianceJobResult(W){let Z=W;while(Z.status!=="complete"){if(Z.status==="expired"||Z.status==="failed")throw Error("Job failed to be completed.");await new Promise((J)=>setTimeout(J,3500)),Z=(await this.complianceJob(W.id)).data}return(await this.get(W.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split(`
|
|
70
|
-
`).filter((J)=>J).map((J)=>JSON.parse(J))}async usage(W={}){return this.get("usage/tweets",W)}community(W,Z={}){return this.get("communities/:id",Z,{params:{id:W}})}searchCommunities(W,Z={}){return this.get("communities/search",{query:W,...Z})}}class B1 extends z1{constructor(){super(...arguments);this._prefix=e}get readOnly(){return this}}class j1 extends X1{constructor(){super(...arguments);this._prefix=g}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new B1(this)}hideReply(W,Z){return this.put("tweets/:id/hidden",{hidden:Z},{params:{id:W}})}like(W,Z){return this.post("users/:id/likes",{tweet_id:Z},{params:{id:W}})}unlike(W,Z){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:W,tweet_id:Z}})}retweet(W,Z){return this.post("users/:id/retweets",{tweet_id:Z},{params:{id:W}})}unretweet(W,Z){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:W,tweet_id:Z}})}tweet(W,Z={}){if(typeof W==="object")Z=W;else Z={text:W,...Z};return this.post("tweets",Z)}async uploadMedia(W,Z,$=1048576){let J=Z.media_category;if(!Z.media_category){if(Z.media_type.includes("gif"))J="tweet_gif";else if(Z.media_type.includes("image"))J="tweet_image";else if(Z.media_type.includes("video"))J="tweet_video"}let Q={additional_owners:Z.additional_owners,media_type:Z.media_type,total_bytes:W.length,media_category:J},K=(await this.post("media/upload/initialize",Q)).data.id,G=Math.ceil(W.length/$),X=new Uint8Array(W);for(let B=0;B<G;B++){let j=B*$,x=Math.min(j+$,W.length),O=X.slice(j,x),H=Buffer.from(O),p={segment_index:B,media:H};await this.post(`media/upload/${K}/append`,p,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${K}/finalize`)).data.processing_info)await this.waitForMediaProcessing(K);return K}async waitForMediaProcessing(W){var Z;let J=(await this.get("media/upload",{command:"STATUS",media_id:W})).data.processing_info;if(!J)return;switch(J.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(Z=J.error)===null||Z===void 0?void 0:Z.message}`);case"pending":case"in_progress":{let Q=J===null||J===void 0?void 0:J.check_after_secs;if(Q&&Q>0)await new Promise((Y)=>setTimeout(Y,Q*1000)),await this.waitForMediaProcessing(W)}}}createMediaMetadata(W,Z){return this.post("media/metadata",{id:W,metadata:Z})}reply(W,Z,$={}){var J;let Q={in_reply_to_tweet_id:Z,...(J=$.reply)!==null&&J!==void 0?J:{}};return this.post("tweets",{text:W,...$,reply:Q})}quote(W,Z,$={}){return this.tweet(W,{...$,quote_tweet_id:Z})}async tweetThread(W){var Z,$;let J=[];for(let Q of W){let Y=J.length?J[J.length-1]:null,K={...typeof Q==="string"?{text:Q}:Q},G=Y?Y.data.id:(Z=K.reply)===null||Z===void 0?void 0:Z.in_reply_to_tweet_id,X=($=K.text)!==null&&$!==void 0?$:"";if(G)J.push(await this.reply(X,G,K));else J.push(await this.tweet(X,K))}return J}deleteTweet(W){return this.delete("tweets/:id",void 0,{params:{id:W}})}async bookmark(W){let Z=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:W},{params:{id:Z.data.id}})}async deleteBookmark(W){let Z=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:Z.data.id,tweet_id:W}})}follow(W,Z){return this.post("users/:id/following",{target_user_id:Z},{params:{id:W}})}unfollow(W,Z){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}block(W,Z){return this.post("users/:id/blocking",{target_user_id:Z},{params:{id:W}})}unblock(W,Z){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}mute(W,Z){return this.post("users/:id/muting",{target_user_id:Z},{params:{id:W}})}unmute(W,Z){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}createList(W){return this.post("lists",W)}updateList(W,Z={}){return this.put("lists/:id",Z,{params:{id:W}})}removeList(W){return this.delete("lists/:id",void 0,{params:{id:W}})}addListMember(W,Z){return this.post("lists/:id/members",{user_id:Z},{params:{id:W}})}removeListMember(W,Z){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:W,user_id:Z}})}subscribeToList(W,Z){return this.post("users/:id/followed_lists",{list_id:Z},{params:{id:W}})}unsubscribeOfList(W,Z){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:W,list_id:Z}})}pinList(W,Z){return this.post("users/:id/pinned_lists",{list_id:Z},{params:{id:W}})}unpinList(W,Z){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:W,list_id:Z}})}sendDmInConversation(W,Z){return this.post("dm_conversations/:dm_conversation_id/messages",Z,{params:{dm_conversation_id:W}})}sendDmToParticipant(W,Z){return this.post("dm_conversations/with/:participant_id/messages",Z,{params:{participant_id:W}})}createDmConversation(W){return this.post("dm_conversations",W)}}class I6 extends B1{constructor(){super(...arguments);this._prefix=e}get readWrite(){return this}}var v6=I6;class q6 extends j1{constructor(){super(...arguments);this._prefix=g}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new v6(this)}}var w6=q6;class C1 extends c{get v1(){if(this._v1)return this._v1;return this._v1=new Y1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new X1(this)}async currentUser(W=!1){return await this.getCurrentUserObject(W)}async currentUserV2(W=!1){return await this.getCurrentUserV2Object(W)}search(W,Z){return this.v2.search(W,Z)}async generateAuthLink(W="oob",{authAccessType:Z,linkMode:$="authenticate",forceLogin:J,screenName:Q}={}){let Y=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:W,x_auth_access_type:Z}),K=`https://api.x.com/oauth/${$}?oauth_token=${encodeURIComponent(Y.oauth_token)}`;if(J!==void 0)K+=`&force_login=${encodeURIComponent(J)}`;if(Q!==void 0)K+=`&screen_name=${encodeURIComponent(Q)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:K,oauthResult:Y});return{url:K,...Y}}async login(W){let Z=this.getActiveTokens();if(Z.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let $=await this.post("https://api.x.com/oauth/access_token",{oauth_token:Z.accessToken,oauth_verifier:W}),J=new this.constructor({appKey:Z.appKey,appSecret:Z.appSecret,accessToken:$.oauth_token,accessSecret:$.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:$.oauth_token,accessSecret:$.oauth_token_secret,userId:$.user_id,screenName:$.screen_name,client:J}}async appLogin(){let W=this.getActiveTokens();if(W.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let $=await new this.constructor({username:W.appKey,password:W.appSecret},this._requestMaker.clientSettings).post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor($.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(W,Z={}){var $,J;if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. You can find your client ID in Twitter Developer Portal. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let Q=($=Z.state)!==null&&$!==void 0?$:a.generateRandomString(32),Y=a.getCodeVerifier(),K=a.getCodeChallengeFromVerifier(Y),G=(J=Z.scope)!==null&&J!==void 0?J:"",X=Array.isArray(G)?G.join(" "):G,z=new URL("https://x.com/i/oauth2/authorize"),B={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:W,state:Q,code_challenge:K,code_challenge_method:"s256",scope:X};R.addQueryParamsToUrl(z,B);let j={url:z.toString(),state:Q,codeVerifier:Y,codeChallenge:K};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:j,redirectUri:W});return j}async loginWithOAuth2({code:W,codeVerifier:Z,redirectUri:$}){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let J=await this.post("https://api.x.com/2/oauth2/token",{code:W,code_verifier:Z,redirect_uri:$,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(J)}async refreshOAuth2Token(W){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let Z=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:W,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(Z)}async revokeOAuth2Token(W,Z="access_token"){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");return await this.post("https://api.x.com/2/oauth2/revoke",{client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret,token:W,token_type_hint:Z})}parseOAuth2AccessTokenResult(W){let Z=new this.constructor(W.access_token,this._requestMaker.clientSettings),$=W.scope.split(" ").filter((J)=>J);return{client:Z,expiresIn:W.expires_in,accessToken:W.access_token,scope:$,refreshToken:W.refresh_token}}}class k1 extends C1{get v1(){if(this._v1)return this._v1;return this._v1=new K1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new j1(this)}get readOnly(){return this}}class r1 extends _{constructor(){super(...arguments);this._prefix=W1}}class e1 extends r1{constructor(){super(...arguments);this._prefix=W1}get readOnly(){return this}}class W4 extends _{constructor(){super(...arguments);this._prefix=Z1}}class Z4 extends W4{constructor(){super(...arguments);this._prefix=Z1}get readOnly(){return this}}class y6 extends Z4{constructor(){super(...arguments);this._prefix=Z1}get readWrite(){return this}}var A6=y6;class h6 extends e1{constructor(){super(...arguments);this._prefix=W1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new A6(this)}}var g6=h6;class V0 extends k1{get v1(){if(this._v1)return this._v1;return this._v1=new s1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new w6(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new g6(this)}static getErrors(W){var Z;if(typeof W!=="object")return[];if(!("data"in W))return[];return(Z=W.data.errors)!==null&&Z!==void 0?Z:[]}static getProfileImageInSize(W,Z){let $=W.split("/").pop(),J=["normal","bigger","mini"],Q=W;for(let K of J)if($.includes(`_${K}`)){Q=W.replace(`_${K}`,"");break}if(Z==="original")return Q;let Y=Q.lastIndexOf(".");if(Y!==-1){let K=Q.slice(Y+1);return Q.slice(0,Y)+"_"+Z+"."+K}else return Q+"_"+Z}}var TW={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class E6 extends i{config;client;constructor(W={}){super();this.config={...TW,...W},this.client=new V0({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${r()??""}${this.config.redirectPath}`}getRedirectUrl(W,Z){if(!Z)throw Error("XOAuthProvider needs the state and PKCE challenge gemi passes.");let $=new URL("https://x.com/i/oauth2/authorize"),J={response_type:"code",client_id:this.config.clientId,redirect_uri:this.redirectUri(),state:Z.state,code_challenge:Z.codeChallenge,code_challenge_method:Z.codeChallengeMethod,scope:this.config.scope.join(" ")};for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new k("missing_code");if(!Z?.codeVerifier)throw new k("invalid_state");let J;try{J=await this.client.loginWithOAuth2({code:$,codeVerifier:Z.codeVerifier,redirectUri:this.redirectUri()})}catch(z){throw console.error("X OAuth error: token exchange failed",z),new k("exchange_failed")}let{data:Q}=await J.client.v2.me({"user.fields":["name","username","entities"]}),{name:Y,email:K,id:G="",username:X}=Q??{};return{name:Y,email:K,username:X,providerId:G}}}var c6=["instagram_business_basic"],q={authorizeUrl:"https://www.instagram.com/oauth/authorize",tokenUrl:"https://api.instagram.com/oauth/access_token",graphUrl:"https://graph.instagram.com"};class P extends Error{status;type;code;constructor(W,Z,$,J,Q){super(W,Q);this.status=Z;this.type=$;this.code=J;this.name="InstagramApiError"}}async function $4(W){let Z=new URLSearchParams({client_id:W.clientId,client_secret:W.clientSecret,grant_type:"authorization_code",redirect_uri:W.redirectUri,code:W.code.replace(/#_$/,"")}),$=await Q4(W.tokenUrl??q.tokenUrl,"code exchange",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Z.toString()}),J=Array.isArray($.data)?$.data[0]:$,Q=J?.access_token;if(typeof Q!=="string"||Q==="")throw new P("Instagram's code exchange answered without an access token.",200);let Y=J?.permissions;return{accessToken:Q,userId:I0(J?.user_id),permissions:Array.isArray(Y)?Y.map(String):typeof Y==="string"?Y.split(/[\s,]+/).filter(Boolean):null}}async function u6(W){let Z=new URL("/access_token",W.graphUrl??q.graphUrl);return Z.searchParams.set("grant_type","ig_exchange_token"),Z.searchParams.set("client_secret",W.clientSecret),Z.searchParams.set("access_token",W.accessToken),d6(await Q4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function p6(W){let Z=new URL("/refresh_access_token",W.graphUrl??q.graphUrl);return Z.searchParams.set("grant_type","ig_refresh_token"),Z.searchParams.set("access_token",W.accessToken),d6(await Q4(Z.toString(),"token refresh",{method:"GET"}))}async function J4(W){let Z=W.graphApiVersion?`/${W.graphApiVersion.replace(/^\/+|\/+$/g,"")}`:"",$=new URL(`${Z}/me`,W.graphUrl??q.graphUrl);$.searchParams.set("fields",(W.fields??["user_id","username","name","account_type","profile_picture_url"]).join(",")),$.searchParams.set("access_token",W.accessToken);let J=await Q4($.toString(),"profile request",{method:"GET"}),Q=Array.isArray(J.data)?J.data[0]:J,Y=I0(Q?.user_id);if(!Y)throw new P("Instagram's /me answered without a user_id.",200);let K={user_id:Y},G=I0(Q?.id);if(G)K.id=G;for(let X of["username","name","account_type","profile_picture_url"]){let z=Q?.[X];if(typeof z==="string"&&z!=="")K[X]=z}return K}function d6(W){if(typeof W.access_token!=="string"||W.access_token==="")throw new P("Instagram answered without an access token.",200);let Z=Number(W.expires_in);return{accessToken:W.access_token,tokenType:typeof W.token_type==="string"?W.token_type:null,expiresIn:Number.isFinite(Z)&&Z>0?Z:null}}async function Q4(W,Z,$){let J;try{J=await fetch(W,{...$,redirect:"error"})}catch(Y){throw new P(`Instagram's ${Z} failed to reach Instagram.`,void 0,void 0,void 0,{cause:Y})}let Q=PW(await J.text().catch(()=>""));if(!J.ok){let Y=Q.error??{},K=m6(Q.error_type)??m6(Y.type),G=Number(Q.code??Y.code);throw new P(`Instagram refused the ${Z} (HTTP ${J.status}${K?`, ${K}`:""}${Number.isFinite(G)?` ${G}`:""}).`,J.status,K,Number.isFinite(G)?G:void 0)}return Q}function PW(W){try{let Z=JSON.parse(W.replace(/("(?:user_id|id)"\s*:\s*)(-?\d+)(?=\s*[,}\]])/g,'$1"$2"'));return Z&&typeof Z==="object"?Z:{}}catch{return{}}}function I0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function m6(W){return typeof W==="string"&&W!==""?W:void 0}class l6 extends i{createUsersWithoutEmail=!0;linkByEmail=!1;config;constructor(W={}){super();this.config={clientId:process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:c6,redirectPath:"/auth/oauth/instagram/callback",authorizationParams:{},...W}}redirectUri(){return`${r()??""}${this.config.redirectPath}`}getRedirectUrl(W,Z){let $=new URL(this.config.authorizeUrl??q.authorizeUrl),J={...this.config.authorizationParams,client_id:this.config.clientId,redirect_uri:this.redirectUri(),response_type:"code",scope:this.config.scopes.join(",")};if(Z)J.state=Z.state;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W){let Z=W.search.get("code");if(!Z)throw new k("missing_code");let $;try{let J=await $4({code:Z,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri(),tokenUrl:this.config.tokenUrl});$=await J4({accessToken:J.accessToken,graphUrl:this.config.graphUrl,graphApiVersion:this.config.graphApiVersion,fields:["user_id","username","name"]})}catch(J){if(J instanceof P)throw console.error(`Instagram OAuth error: ${J.message}`),new k("exchange_failed");throw J}return{providerId:$.user_id,username:$.username,name:$.name||$.username}}}import{createHmac as VW,timingSafeEqual as IW}from"crypto";class V extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function vW(W,Z,$={}){if(!Z)throw Error("parseMetaSignedRequest needs the app secret.");if(typeof W!=="string")throw new V("malformed","No signed_request was given.");let J=W.indexOf(".");if(J<=0||J===W.length-1||W.indexOf(".",J+1)!==-1)throw new V("malformed","A signed_request is <signature>.<payload>.");let Q=W.slice(0,J),Y=W.slice(J+1);if(!/^[A-Za-z0-9_-]+={0,2}$/.test(Q)||!/^[A-Za-z0-9_-]+={0,2}$/.test(Y))throw new V("malformed","A signed_request is base64url.");let K=VW("sha256",Z).update(Y).digest(),G=Buffer.from(Q,"base64url");if(G.length!==K.length||!IW(G,K))throw new V("bad_signature","The signed_request's signature does not match the app secret.");let X;try{let x=Buffer.from(Y,"base64url").toString("utf8").replace(/("user_id"\s*:\s*)(-?\d+)(?=\s*[,}])/g,'$1"$2"');X=JSON.parse(x)}catch{throw new V("malformed","The signed_request's payload is not JSON.")}if(!X||typeof X!=="object")throw new V("malformed","The signed_request's payload is not an object.");if(String(X.algorithm??"").toUpperCase()!=="HMAC-SHA256")throw new V("unsupported_algorithm","Only HMAC-SHA256 signed_requests are accepted.");let z=Math.floor(($.now??Date.now())/1000),B=Number(X.expires);if(Number.isFinite(B)&&B>0&&B<z)throw new V("expired","The signed_request has expired.");let j=X.user_id;if((typeof j!=="string"||j==="")&&typeof j!=="number")throw new V("missing_user","The signed_request names no user.");return{...X,algorithm:String(X.algorithm),user_id:String(j)}}var qW=86400000;class n6 extends v0{instagram;constructor(W={}){let Z={authorizeUrl:W.authorizeUrl??q.authorizeUrl,tokenUrl:W.tokenUrl??q.tokenUrl,graphUrl:W.graphUrl??q.graphUrl,graphApiVersion:W.graphApiVersion};super({authorizeUrl:Z.authorizeUrl,tokenUrl:Z.tokenUrl,clientId:W.clientId??process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:W.scopes??["instagram_business_basic","instagram_business_content_publish"],scopeSeparator:",",pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,apiBaseUrl:Z.graphUrl,refreshLeewaySeconds:W.refreshLeewaySeconds??864000,multiple:W.multiple??!1,tokenPlacement:"query",isTokenRejected:wW,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<qW){if($.reason==="rejected")throw new b1("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let J=await Y4("refresh_failed",()=>p6({accessToken:$.accessToken,graphUrl:Z.graphUrl}));return{accessToken:J.accessToken,refreshToken:null,tokenType:J.tokenType,expiresAt:J.expiresIn===null?null:new Date(Date.now()+J.expiresIn*1000),scopes:$.scopes,providerAccountId:$.providerAccountId}}});this.instagram=Z}async exchangeCode(W){let Z=await Y4("exchange_failed",()=>$4({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await Y4("exchange_failed",()=>u6({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),J=await Y4("exchange_failed",()=>J4({accessToken:$.accessToken,graphUrl:this.instagram.graphUrl,graphApiVersion:this.instagram.graphApiVersion}));return{accessToken:$.accessToken,refreshToken:null,tokenType:$.tokenType,expiresAt:$.expiresIn===null?null:new Date(Date.now()+$.expiresIn*1000),scopes:Z.permissions??this.config.scopes,providerAccountId:J.user_id,profile:{...J}}}refresh(){return Promise.reject(new b1("refresh_failed","Instagram connections renew the access token itself; call connection.refresh()."))}}async function wW(W){if(W.status===401)return!0;if(W.status!==400)return!1;let Z=await W.clone().json().catch(()=>null);return Number(Z?.error?.code)===190}async function Y4(W,Z){try{return await Z()}catch($){if($ instanceof P)throw new b1(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}class q0{describe;rollout;when;serverOnly;salt;constructor(W={}){if(W.rollout!==void 0){let{rollout:Z}=W;if(!Number.isFinite(Z)||Z<0||Z>100)throw Error(`A feature's \`rollout\` must be a number between 0 and 100, received ${String(Z)}.`)}this.describe=W.describe,this.rollout=W.rollout,this.when=W.when,this.serverOnly=W.serverOnly??!1,this.salt=W.salt}}function yW(W={}){return new q0(W)}class i6 extends w0{rows=new Map;constructor(W={}){super();for(let[Z,$]of Object.entries(W))this.rows.set(Z,{key:Z,active:$})}async load(){return[...this.rows.values()].map((W)=>({...W}))}async write(W,Z,$){return this.rows.set(W,{key:W,active:Z,updatedBy:$.actor,updatedAt:new Date}),{actorRecorded:!0}}}export{GZ as viewRouteConfigDefaults,x8 as translationConfigDefaults,K4 as toRangeHeaderValue,nW as subjectFor,Q5 as sniffContentType,eZ as scheduleConfigDefaults,X4 as resolveRange,y8 as redisConfigDefaults,v8 as rateLimiterConfigDefaults,bZ as queueConfigDefaults,vW as parseMetaSignedRequest,M1 as parseContentRange,gW as mintSessionToken,xZ as middlewareConfigDefaults,cZ as mcpCallOf,UZ as mailConfigDefaults,T8 as logConfigDefaults,hW as isSessionToken,n5 as isFinalRunStatus,X6 as isBroadcastEvent,Y5 as isActiveContentType,dW as inRollout,$Z as imageConfigDefaults,$5 as filesystemConfigDefaults,U8 as featuresConfigDefaults,Z8 as eventConfigDefaults,lW as evaluateFeature,k5 as encodeCursor,XZ as documentScriptCspHash,Y8 as discoverWorkflows,z8 as discoverListeners,Q8 as discoverJobs,K8 as discoverCronJobs,G8 as discoverCommands,N8 as defineTranslationConfig,rZ as defineScheduleConfig,p5 as defineRunsConfig,YZ as defineRouteConfig,w8 as defineRedisConfig,I8 as defineRateLimiterConfig,kZ as defineQueueConfig,NZ as defineMiddlewareConfig,HZ as defineMailConfig,b8 as defineLogConfig,ZZ as defineImageConfig,Z5 as defineFilesystemConfig,H8 as defineFeaturesConfig,yW as defineFeature,W8 as defineEventConfig,t6 as defineEncryptionConfig,sZ as defineCommandConfig,aZ as defineCommand,f5 as defineChangeFeedConfig,G5 as defineCacheConfig,y5 as defineBroadcastConfig,mW as defineAuthConfig,b5 as decodeCursor,fZ as createWorkflowTableStatements,o5 as createRunsTableStatements,oZ as commandConfigDefaults,C5 as changeFeedConfigDefaults,z5 as cacheConfigDefaults,pW as bucketOf,uW as bucketKey,A5 as broadcastConfigDefaults,f4 as bearerToken,cW as authConfigDefaults,G4 as assertDeletablePrefix,KZ as apiRouteConfigDefaults,E6 as XOAuthProvider,yZ as WorkflowRuntime,qZ as WorkflowCancelledError,J8 as Workflow,IZ as WaitTimeoutError,MZ as ViewRouteDispatcher,tW as UndeclaredFeatureError,M5 as TaggedCache,vZ as StepTimeoutError,VZ as StepFailedError,wZ as Step,i6 as StaticFeatureFlagSource,WZ as Sharp,lZ as Scheduler,F8 as ScheduleServiceProvider,jZ as STATIC_NAVIGATION_CSP_HASH,w5 as SOCKET_ID_HEADER,AW as SESSION_TOKEN_PREFIX,h0 as S3Driver,g8 as RunsServiceProvider,a5 as RunNotFoundError,r5 as RunManager,t5 as RunFailure,h8 as RouteServiceProvider,DZ as ResendDriver,A8 as RedisServiceProvider,L4 as RedisRateLimiterTimeoutError,V1 as RedisRateLimiterDisconnectedError,u0 as RedisRateLimiter,P1 as RedisManager,B5 as RedisCacheStore,g5 as RedisBroadcastDriver,q8 as RateLimiterServiceProvider,j4 as RateLimiterDriver,EW as RateLimiter,t as RangeNotSatisfiableError,X8 as QueueServiceProvider,AZ as QueueManager,_5 as ProviderConnection,K6 as PrismaMcpOAuthStore,c5 as PendingBroadcast,l5 as OPEN_RUN_STATUSES,S5 as OAuthReconnectRequiredError,i as OAuthProvider,v0 as OAuthConnectionProvider,b1 as OAuthConnectionError,k as OAuthCallbackError,V8 as MiddlewareServiceProvider,QZ as MiddlewareRegistry,V as MetaSignedRequestError,TZ as MemoryWorkflowStore,i5 as MemoryRunStore,PZ as MemoryQueueDriver,Y6 as MemoryMcpOAuthStore,RZ as MemoryLockStore,U5 as MemoryConnectionStore,P5 as MemoryChangeFeedDriver,X5 as MemoryCacheStore,h5 as MemoryBroadcastDriver,EZ as McpToolError,uZ as McpRegistry,J6 as McpOAuthServer,dZ as McpHttpServer,mZ as McpCallRefusedError,pZ as McpApiKeyResolver,S8 as MailServiceProvider,OZ as MailManager,P8 as LogServiceProvider,K5 as LogManager,x5 as LockManager,L5 as LockLostError,$8 as Listener,k8 as KernelIdServiceProvider,zZ as KernelId,hZ as Job,q5 as InvalidChannelError,l6 as InstagramOAuthProvider,n6 as InstagramConnectionProvider,P as InstagramApiError,M4 as InMemoryRateLimiter,C8 as ImageServiceProvider,e5 as ImageOptimizationDriver,JZ as ImageManager,BZ as ISLAND_LOADER_CSP_HASH,N5 as HeldLock,j6 as GoogleOAuthProvider,f8 as FilesystemServiceProvider,J5 as FilesystemManager,W5 as FileSystemDriver,L1 as FileStorageDriver,d as FileNotFoundError,O8 as FeaturesServiceProvider,aW as FeatureSourceReadOnlyError,rW as FeatureScope,iW as FeatureReloadError,oW as FeatureModelMissingError,eW as FeatureManager,sW as FeatureFlagStore,w0 as FeatureFlagSource,q0 as Feature,d5 as FINAL_RUN_STATUSES,_8 as EventServiceProvider,C as EventManager,g1 as Event,R8 as EncryptionServiceProvider,D5 as EncryptionKeyError,F5 as Encrypter,FZ as EmailDriver,H5 as DecryptionError,_Z as DatabaseWorkflowStore,s5 as DatabaseRunStore,CZ as DatabaseQueueDriver,SZ as DatabaseLockStore,D8 as DatabaseFeatureFlagSource,O5 as DatabaseConnectionStore,T5 as DatabaseChangeFeedDriver,gZ as DEFAULT_MCP_SCOPE,tZ as CronJob,R5 as ConnectionManager,E8 as CommandRegistry,nZ as CommandFailed,iZ as Command,v5 as ChangeFeedSubscription,M8 as ChangeFeedServiceProvider,I5 as ChangeFeedManager,V5 as ChangeFeedFullError,j8 as CacheServiceProvider,j5 as CacheManager,I1 as CONSENT_PAGE_HEADERS,B8 as BroadcastServiceProvider,u5 as BroadcastScope,E5 as BroadcastPayloadTooLargeError,m5 as BroadcastManager,B6 as BroadcastEvent,E0 as AzureBlobDriver,L8 as AuthServiceProvider,w1 as AuthManager,LZ as ApiRouteDispatcher};
|
|
70
|
+
`).filter((J)=>J).map((J)=>JSON.parse(J))}async usage(W={}){return this.get("usage/tweets",W)}community(W,Z={}){return this.get("communities/:id",Z,{params:{id:W}})}searchCommunities(W,Z={}){return this.get("communities/search",{query:W,...Z})}}class M1 extends j1{constructor(){super(...arguments);this._prefix=$1}get readOnly(){return this}}class L1 extends F1{constructor(){super(...arguments);this._prefix=c}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new M1(this)}hideReply(W,Z){return this.put("tweets/:id/hidden",{hidden:Z},{params:{id:W}})}like(W,Z){return this.post("users/:id/likes",{tweet_id:Z},{params:{id:W}})}unlike(W,Z){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:W,tweet_id:Z}})}retweet(W,Z){return this.post("users/:id/retweets",{tweet_id:Z},{params:{id:W}})}unretweet(W,Z){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:W,tweet_id:Z}})}tweet(W,Z={}){if(typeof W==="object")Z=W;else Z={text:W,...Z};return this.post("tweets",Z)}async uploadMedia(W,Z,$=1048576){let J=Z.media_category;if(!Z.media_category){if(Z.media_type.includes("gif"))J="tweet_gif";else if(Z.media_type.includes("image"))J="tweet_image";else if(Z.media_type.includes("video"))J="tweet_video"}let Q={additional_owners:Z.additional_owners,media_type:Z.media_type,total_bytes:W.length,media_category:J},K=(await this.post("media/upload/initialize",Q)).data.id,z=Math.ceil(W.length/$),X=new Uint8Array(W);for(let B=0;B<z;B++){let j=B*$,N=Math.min(j+$,W.length),S=X.slice(j,N),U=Buffer.from(S),n={segment_index:B,media:U};await this.post(`media/upload/${K}/append`,n,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${K}/finalize`)).data.processing_info)await this.waitForMediaProcessing(K);return K}async waitForMediaProcessing(W){var Z;let J=(await this.get("media/upload",{command:"STATUS",media_id:W})).data.processing_info;if(!J)return;switch(J.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(Z=J.error)===null||Z===void 0?void 0:Z.message}`);case"pending":case"in_progress":{let Q=J===null||J===void 0?void 0:J.check_after_secs;if(Q&&Q>0)await new Promise((Y)=>setTimeout(Y,Q*1000)),await this.waitForMediaProcessing(W)}}}createMediaMetadata(W,Z){return this.post("media/metadata",{id:W,metadata:Z})}reply(W,Z,$={}){var J;let Q={in_reply_to_tweet_id:Z,...(J=$.reply)!==null&&J!==void 0?J:{}};return this.post("tweets",{text:W,...$,reply:Q})}quote(W,Z,$={}){return this.tweet(W,{...$,quote_tweet_id:Z})}async tweetThread(W){var Z,$;let J=[];for(let Q of W){let Y=J.length?J[J.length-1]:null,K={...typeof Q==="string"?{text:Q}:Q},z=Y?Y.data.id:(Z=K.reply)===null||Z===void 0?void 0:Z.in_reply_to_tweet_id,X=($=K.text)!==null&&$!==void 0?$:"";if(z)J.push(await this.reply(X,z,K));else J.push(await this.tweet(X,K))}return J}deleteTweet(W){return this.delete("tweets/:id",void 0,{params:{id:W}})}async bookmark(W){let Z=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:W},{params:{id:Z.data.id}})}async deleteBookmark(W){let Z=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:Z.data.id,tweet_id:W}})}follow(W,Z){return this.post("users/:id/following",{target_user_id:Z},{params:{id:W}})}unfollow(W,Z){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}block(W,Z){return this.post("users/:id/blocking",{target_user_id:Z},{params:{id:W}})}unblock(W,Z){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}mute(W,Z){return this.post("users/:id/muting",{target_user_id:Z},{params:{id:W}})}unmute(W,Z){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}createList(W){return this.post("lists",W)}updateList(W,Z={}){return this.put("lists/:id",Z,{params:{id:W}})}removeList(W){return this.delete("lists/:id",void 0,{params:{id:W}})}addListMember(W,Z){return this.post("lists/:id/members",{user_id:Z},{params:{id:W}})}removeListMember(W,Z){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:W,user_id:Z}})}subscribeToList(W,Z){return this.post("users/:id/followed_lists",{list_id:Z},{params:{id:W}})}unsubscribeOfList(W,Z){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:W,list_id:Z}})}pinList(W,Z){return this.post("users/:id/pinned_lists",{list_id:Z},{params:{id:W}})}unpinList(W,Z){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:W,list_id:Z}})}sendDmInConversation(W,Z){return this.post("dm_conversations/:dm_conversation_id/messages",Z,{params:{dm_conversation_id:W}})}sendDmToParticipant(W,Z){return this.post("dm_conversations/with/:participant_id/messages",Z,{params:{participant_id:W}})}createDmConversation(W){return this.post("dm_conversations",W)}}class m6 extends M1{constructor(){super(...arguments);this._prefix=$1}get readWrite(){return this}}var c6=m6;class u6 extends L1{constructor(){super(...arguments);this._prefix=c}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new c6(this)}}var p6=u6;class T1 extends d{get v1(){if(this._v1)return this._v1;return this._v1=new G1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new F1(this)}async currentUser(W=!1){return await this.getCurrentUserObject(W)}async currentUserV2(W=!1){return await this.getCurrentUserV2Object(W)}search(W,Z){return this.v2.search(W,Z)}async generateAuthLink(W="oob",{authAccessType:Z,linkMode:$="authenticate",forceLogin:J,screenName:Q}={}){let Y=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:W,x_auth_access_type:Z}),K=`https://api.x.com/oauth/${$}?oauth_token=${encodeURIComponent(Y.oauth_token)}`;if(J!==void 0)K+=`&force_login=${encodeURIComponent(J)}`;if(Q!==void 0)K+=`&screen_name=${encodeURIComponent(Q)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:K,oauthResult:Y});return{url:K,...Y}}async login(W){let Z=this.getActiveTokens();if(Z.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let $=await this.post("https://api.x.com/oauth/access_token",{oauth_token:Z.accessToken,oauth_verifier:W}),J=new this.constructor({appKey:Z.appKey,appSecret:Z.appSecret,accessToken:$.oauth_token,accessSecret:$.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:$.oauth_token,accessSecret:$.oauth_token_secret,userId:$.user_id,screenName:$.screen_name,client:J}}async appLogin(){let W=this.getActiveTokens();if(W.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let $=await new this.constructor({username:W.appKey,password:W.appSecret},this._requestMaker.clientSettings).post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor($.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(W,Z={}){var $,J;if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. You can find your client ID in Twitter Developer Portal. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let Q=($=Z.state)!==null&&$!==void 0?$:e.generateRandomString(32),Y=e.getCodeVerifier(),K=e.getCodeChallengeFromVerifier(Y),z=(J=Z.scope)!==null&&J!==void 0?J:"",X=Array.isArray(z)?z.join(" "):z,G=new URL("https://x.com/i/oauth2/authorize"),B={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:W,state:Q,code_challenge:K,code_challenge_method:"s256",scope:X};f.addQueryParamsToUrl(G,B);let j={url:G.toString(),state:Q,codeVerifier:Y,codeChallenge:K};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:j,redirectUri:W});return j}async loginWithOAuth2({code:W,codeVerifier:Z,redirectUri:$}){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let J=await this.post("https://api.x.com/2/oauth2/token",{code:W,code_verifier:Z,redirect_uri:$,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(J)}async refreshOAuth2Token(W){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let Z=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:W,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(Z)}async revokeOAuth2Token(W,Z="access_token"){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");return await this.post("https://api.x.com/2/oauth2/revoke",{client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret,token:W,token_type_hint:Z})}parseOAuth2AccessTokenResult(W){let Z=new this.constructor(W.access_token,this._requestMaker.clientSettings),$=W.scope.split(" ").filter((J)=>J);return{client:Z,expiresIn:W.expires_in,accessToken:W.access_token,scope:$,refreshToken:W.refresh_token}}}class P1 extends T1{get v1(){if(this._v1)return this._v1;return this._v1=new X1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new L1(this)}get readOnly(){return this}}class $4 extends C{constructor(){super(...arguments);this._prefix=J1}}class J4 extends $4{constructor(){super(...arguments);this._prefix=J1}get readOnly(){return this}}class Q4 extends C{constructor(){super(...arguments);this._prefix=Q1}}class Y4 extends Q4{constructor(){super(...arguments);this._prefix=Q1}get readOnly(){return this}}class d6 extends Y4{constructor(){super(...arguments);this._prefix=Q1}get readWrite(){return this}}var l6=d6;class n6 extends J4{constructor(){super(...arguments);this._prefix=J1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new l6(this)}}var i6=n6;class y0 extends P1{get v1(){if(this._v1)return this._v1;return this._v1=new r1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new p6(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new i6(this)}static getErrors(W){var Z;if(typeof W!=="object")return[];if(!("data"in W))return[];return(Z=W.data.errors)!==null&&Z!==void 0?Z:[]}static getProfileImageInSize(W,Z){let $=W.split("/").pop(),J=["normal","bigger","mini"],Q=W;for(let K of J)if($.includes(`_${K}`)){Q=W.replace(`_${K}`,"");break}if(Z==="original")return Q;let Y=Q.lastIndexOf(".");if(Y!==-1){let K=Q.slice(Y+1);return Q.slice(0,Y)+"_"+Z+"."+K}else return Q+"_"+Z}}var dW={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class s6 extends a{config;client;constructor(W={}){super();this.config={...dW,...W},this.client=new y0({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${Z1()??""}${this.config.redirectPath}`}getRedirectUrl(W,Z){if(!Z)throw Error("XOAuthProvider needs the state and PKCE challenge gemi passes.");let $=new URL("https://x.com/i/oauth2/authorize"),J={response_type:"code",client_id:this.config.clientId,redirect_uri:this.redirectUri(),state:Z.state,code_challenge:Z.codeChallenge,code_challenge_method:Z.codeChallengeMethod,scope:this.config.scope.join(" ")};for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new P("missing_code");if(!Z?.codeVerifier)throw new P("invalid_state");let J;try{J=await this.client.loginWithOAuth2({code:$,codeVerifier:Z.codeVerifier,redirectUri:this.redirectUri()})}catch(G){throw console.error("X OAuth error: token exchange failed",G),new P("exchange_failed")}let{data:Q}=await J.client.v2.me({"user.fields":["name","username","entities"]}),{name:Y,email:K,id:z="",username:X}=Q??{};return{name:Y,email:K,username:X,providerId:z}}}var a6=["instagram_business_basic"],A={authorizeUrl:"https://www.instagram.com/oauth/authorize",tokenUrl:"https://api.instagram.com/oauth/access_token",graphUrl:"https://graph.instagram.com"};class v extends Error{status;type;code;constructor(W,Z,$,J,Q){super(W,Q);this.status=Z;this.type=$;this.code=J;this.name="InstagramApiError"}}async function K4(W){let Z=new URLSearchParams({client_id:W.clientId,client_secret:W.clientSecret,grant_type:"authorization_code",redirect_uri:W.redirectUri,code:W.code.replace(/#_$/,"")}),$=await G4(W.tokenUrl??A.tokenUrl,"code exchange",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Z.toString()}),J=Array.isArray($.data)?$.data[0]:$,Q=J?.access_token;if(typeof Q!=="string"||Q==="")throw new v("Instagram's code exchange answered without an access token.",200);let Y=J?.permissions;return{accessToken:Q,userId:A0(J?.user_id),permissions:Array.isArray(Y)?Y.map(String):typeof Y==="string"?Y.split(/[\s,]+/).filter(Boolean):null}}async function t6(W){let Z=new URL("/access_token",W.graphUrl??A.graphUrl);return Z.searchParams.set("grant_type","ig_exchange_token"),Z.searchParams.set("client_secret",W.clientSecret),Z.searchParams.set("access_token",W.accessToken),e6(await G4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function r6(W){let Z=new URL("/refresh_access_token",W.graphUrl??A.graphUrl);return Z.searchParams.set("grant_type","ig_refresh_token"),Z.searchParams.set("access_token",W.accessToken),e6(await G4(Z.toString(),"token refresh",{method:"GET"}))}async function z4(W){let Z=W.graphApiVersion?`/${W.graphApiVersion.replace(/^\/+|\/+$/g,"")}`:"",$=new URL(`${Z}/me`,W.graphUrl??A.graphUrl);$.searchParams.set("fields",(W.fields??["user_id","username","name","account_type","profile_picture_url"]).join(",")),$.searchParams.set("access_token",W.accessToken);let J=await G4($.toString(),"profile request",{method:"GET"}),Q=Array.isArray(J.data)?J.data[0]:J,Y=A0(Q?.user_id);if(!Y)throw new v("Instagram's /me answered without a user_id.",200);let K={user_id:Y},z=A0(Q?.id);if(z)K.id=z;for(let X of["username","name","account_type","profile_picture_url"]){let G=Q?.[X];if(typeof G==="string"&&G!=="")K[X]=G}return K}function e6(W){if(typeof W.access_token!=="string"||W.access_token==="")throw new v("Instagram answered without an access token.",200);let Z=Number(W.expires_in);return{accessToken:W.access_token,tokenType:typeof W.token_type==="string"?W.token_type:null,expiresIn:Number.isFinite(Z)&&Z>0?Z:null}}async function G4(W,Z,$){let J;try{J=await fetch(W,{...$,redirect:"error"})}catch(Y){throw new v(`Instagram's ${Z} failed to reach Instagram.`,void 0,void 0,void 0,{cause:Y})}let Q=h0(await J.text().catch(()=>""));if(!J.ok){let Y=Q.error??{},K=o6(Q.error_type)??o6(Y.type),z=Number(Q.code??Y.code);throw new v(`Instagram refused the ${Z} (HTTP ${J.status}${K?`, ${K}`:""}${Number.isFinite(z)?` ${z}`:""}).`,J.status,K,Number.isFinite(z)?z:void 0)}return Q}function h0(W){try{let Z=JSON.parse(W.replace(/("(?:user_id|id)"\s*:\s*)(-?\d+)(?=\s*[,}\]])/g,'$1"$2"'));return Z&&typeof Z==="object"?Z:{}}catch{return{}}}function A0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function o6(W){return typeof W==="string"&&W!==""?W:void 0}class WW extends a{createUsersWithoutEmail=!0;linkByEmail=!1;config;constructor(W={}){super();this.config={clientId:process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:a6,redirectPath:"/auth/oauth/instagram/callback",authorizationParams:{},...W}}redirectUri(){return`${Z1()??""}${this.config.redirectPath}`}getRedirectUrl(W,Z){let $=new URL(this.config.authorizeUrl??A.authorizeUrl),J={...this.config.authorizationParams,client_id:this.config.clientId,redirect_uri:this.redirectUri(),response_type:"code",scope:this.config.scopes.join(",")};if(Z)J.state=Z.state;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W){let Z=W.search.get("code");if(!Z)throw new P("missing_code");let $;try{let J=await K4({code:Z,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri(),tokenUrl:this.config.tokenUrl});$=await z4({accessToken:J.accessToken,graphUrl:this.config.graphUrl,graphApiVersion:this.config.graphApiVersion,fields:["user_id","username","name"]})}catch(J){if(J instanceof v)throw console.error(`Instagram OAuth error: ${J.message}`),new P("exchange_failed");throw J}return{providerId:$.user_id,username:$.username,name:$.name||$.username}}}import{createHmac as lW,timingSafeEqual as nW}from"crypto";class w extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function iW(W,Z,$={}){if(!Z)throw Error("parseMetaSignedRequest needs the app secret.");if(typeof W!=="string")throw new w("malformed","No signed_request was given.");let J=W.indexOf(".");if(J<=0||J===W.length-1||W.indexOf(".",J+1)!==-1)throw new w("malformed","A signed_request is <signature>.<payload>.");let Q=W.slice(0,J),Y=W.slice(J+1);if(!/^[A-Za-z0-9_-]+={0,2}$/.test(Q)||!/^[A-Za-z0-9_-]+={0,2}$/.test(Y))throw new w("malformed","A signed_request is base64url.");let K=lW("sha256",Z).update(Y).digest(),z=Buffer.from(Q,"base64url");if(z.length!==K.length||!nW(z,K))throw new w("bad_signature","The signed_request's signature does not match the app secret.");let X;try{let N=Buffer.from(Y,"base64url").toString("utf8").replace(/("user_id"\s*:\s*)(-?\d+)(?=\s*[,}])/g,'$1"$2"');X=JSON.parse(N)}catch{throw new w("malformed","The signed_request's payload is not JSON.")}if(!X||typeof X!=="object")throw new w("malformed","The signed_request's payload is not an object.");if(String(X.algorithm??"").toUpperCase()!=="HMAC-SHA256")throw new w("unsupported_algorithm","Only HMAC-SHA256 signed_requests are accepted.");let G=Math.floor(($.now??Date.now())/1000),B=Number(X.expires);if(Number.isFinite(B)&&B>0&&B<G)throw new w("expired","The signed_request has expired.");let j=X.user_id;if((typeof j!=="string"||j==="")&&typeof j!=="number")throw new w("missing_user","The signed_request names no user.");return{...X,algorithm:String(X.algorithm),user_id:String(j)}}var sW=86400000;class B4 extends g0{instagram;constructor(W={}){let Z={authorizeUrl:W.authorizeUrl??A.authorizeUrl,tokenUrl:W.tokenUrl??A.tokenUrl,graphUrl:W.graphUrl??A.graphUrl,graphApiVersion:W.graphApiVersion};super({authorizeUrl:Z.authorizeUrl,tokenUrl:Z.tokenUrl,clientId:W.clientId??process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:W.scopes??["instagram_business_basic","instagram_business_content_publish"],scopeSeparator:",",pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,apiBaseUrl:Z.graphUrl,refreshLeewaySeconds:W.refreshLeewaySeconds??864000,multiple:W.multiple??!1,tokenPlacement:"query",isTokenRejected:oW,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<sW){if($.reason==="rejected")throw new b1("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let J=await X4("refresh_failed",()=>r6({accessToken:$.accessToken,graphUrl:Z.graphUrl}));return{accessToken:J.accessToken,refreshToken:null,tokenType:J.tokenType,expiresAt:J.expiresIn===null?null:new Date(Date.now()+J.expiresIn*1000),scopes:$.scopes,providerAccountId:$.providerAccountId}}});this.instagram=Z}async exchangeCode(W){let Z=await X4("exchange_failed",()=>K4({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await X4("exchange_failed",()=>t6({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),J=await X4("exchange_failed",()=>z4({accessToken:$.accessToken,graphUrl:this.instagram.graphUrl,graphApiVersion:this.instagram.graphApiVersion}));return{accessToken:$.accessToken,refreshToken:null,tokenType:$.tokenType,expiresAt:$.expiresIn===null?null:new Date(Date.now()+$.expiresIn*1000),scopes:Z.permissions??this.config.scopes,providerAccountId:J.user_id,profile:{...J}}}refresh(){return Promise.reject(new b1("refresh_failed","Instagram connections renew the access token itself; call connection.refresh()."))}}async function oW(W){if(W.status===401)return!0;if(W.status!==400)return!1;let Z=await W.clone().json().catch(()=>null);return Number(Z?.error?.code)===190}async function X4(W,Z){try{return await Z()}catch($){if($ instanceof v)throw new b1(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}class x extends Error{code;status;graphCode;graphSubcode;containerId;constructor(W,Z,$={}){super(Z);this.code=W;this.name="InstagramPublishError",this.status=$.status,this.graphCode=$.graphCode,this.graphSubcode=$.graphSubcode,this.containerId=$.containerId}}var k={captionLength:2200,hashtags:30,mentions:20,userTags:20,carouselMin:2,carouselMax:10},ZW="instagram_business_content_publish",aW={for(W,Z={}){return new c0(W,Z)}};class c0{connection;version;pollIntervalMs;maxPollIntervalMs;timeoutMs;constructor(W,Z={}){this.connection=W;let $=W.connectionProvider();if(!($ instanceof B4))throw TypeError(`Instagram.for() takes an Instagram connection; "${W.provider}" is not an InstagramConnectionProvider.`);let J=Z.graphApiVersion??$.instagram.graphApiVersion;this.version=J?`/${J.replace(/^\/+|\/+$/g,"")}`:"",this.pollIntervalMs=Z.pollIntervalMs??2000,this.maxPollIntervalMs=Z.maxPollIntervalMs??1e4,this.timeoutMs=Z.timeoutMs??300000}async publishImage(W,Z={}){if(q1("imageUrl",W.imageUrl),m0(W.caption),W.altText!==void 0&&typeof W.altText!=="string")R("altText must be a string.");if(W.userTags!==void 0)G5(W.userTags);let $=this.start(Z),J=await this.createContainer({image_url:W.imageUrl,caption:W.caption,alt_text:W.altText,user_tags:W.userTags?JSON.stringify(W.userTags):void 0,location_id:W.locationId},$);return this.publishContainer(J,!1,$)}async publishCarousel(W,Z={}){let $=W.items;if(!Array.isArray($)||$.length<k.carouselMin||$.length>k.carouselMax)R(`A carousel takes ${k.carouselMin} to ${k.carouselMax} items.`);$.forEach((z,X)=>YW(`items[${X}]`,z)),m0(W.caption);let J=this.start(Z),Q=[];for(let z of $)Q.push(await this.createContainer(z.videoUrl!==void 0?{media_type:"VIDEO",video_url:z.videoUrl,is_carousel_item:"true"}:{image_url:z.imageUrl,is_carousel_item:"true"},J));for(let[z,X]of $.entries())if(X.videoUrl!==void 0)await this.waitUntilFinished(Q[z],J);let Y=$.some((z)=>z.videoUrl!==void 0),K=await this.createContainer({media_type:"CAROUSEL",children:Q.join(","),caption:W.caption},J);return this.publishContainer(K,Y,J)}async publishReel(W,Z={}){if(q1("videoUrl",W.videoUrl),W.coverUrl!==void 0)q1("coverUrl",W.coverUrl);if(m0(W.caption),W.thumbOffset!==void 0&&!(Number.isInteger(W.thumbOffset)&&W.thumbOffset>=0))R("thumbOffset must be a whole number of milliseconds, 0 or more.");let $=this.start(Z),J=await this.createContainer({media_type:"REELS",video_url:W.videoUrl,caption:W.caption,cover_url:W.coverUrl,share_to_feed:W.shareToFeed===void 0?void 0:String(W.shareToFeed),thumb_offset:W.thumbOffset===void 0?void 0:String(W.thumbOffset)},$);return this.publishContainer(J,!0,$)}async publishStory(W,Z={}){YW("story",W);let $=this.start(Z),J=W.videoUrl!==void 0,Q=await this.createContainer(J?{media_type:"STORIES",video_url:W.videoUrl}:{media_type:"STORIES",image_url:W.imageUrl},$);return this.publishContainer(Q,J,$)}async publishingLimit(W={}){let Z=this.start(W),$=await this.call("publishing limit request",`/${this.accountId()}/content_publishing_limit?fields=quota_usage,config`,void 0,Z),J=Array.isArray($.data)?$.data[0]:$,Q=J?.config??{},Y=E0(J?.quota_usage,0),K=E0(Q.quota_total,100);return{quotaUsage:Y,quotaTotal:K,quotaDurationSeconds:E0(Q.quota_duration,86400),remaining:Math.max(0,K-Y)}}async containerStatus(W,Z={}){return this.readStatus(W,this.start(Z))}start(W){if(W.signal?.throwIfAborted(),!this.connection.hasScopes(ZW))throw new x("permission_denied",`The Instagram connection was not granted ${ZW}; connect it again with that scope.`);return{signal:W.signal,deadline:Date.now()+(W.timeoutMs??this.timeoutMs)}}accountId(){let W=this.connection.providerAccountId;if(!W)throw new x("invalid_input","The Instagram connection has no account id (providerAccountId).");return W}async createContainer(W,Z){let $=await this.call("media container request",`/${this.accountId()}/media`,W,Z);return JW($,"media container request")}async publishContainer(W,Z,$){try{if(Z)await this.waitUntilFinished(W,$);let J=await this.publishOnce(W,Z,$);return{mediaId:J,permalink:await this.permalink(J,$)}}catch(J){throw J instanceof x?K5(J,W):J}}async publishOnce(W,Z,$){try{return await this.mediaPublish(W,$)}catch(J){if(!(J instanceof x))throw J;if(J.code==="transient"){let{statusCode:Q}=await this.readStatus(W,$);if(Q==="PUBLISHED")throw new x("unconfirmed","Instagram's media_publish failed, but the container reads PUBLISHED: the post is probably live. Do not publish it again.",{status:J.status,graphCode:J.graphCode,graphSubcode:J.graphSubcode});if(Q!=="FINISHED")throw J;return this.mediaPublish(W,$)}if(Y5(J)&&!Z)return await this.waitUntilFinished(W,$),this.mediaPublish(W,$);throw J}}async mediaPublish(W,Z){let $=await this.call("media_publish request",`/${this.accountId()}/media_publish`,{creation_id:W},Z,{retry:!1});return JW($,"media_publish request")}async permalink(W,Z){try{let $=await this.call("permalink request",`/${W}?fields=permalink`,void 0,Z,{retry:!1});return typeof $.permalink==="string"?$.permalink:void 0}catch{return}}async readStatus(W,Z){if(!/^\d+$/.test(W))R("A container id is a string of digits.");let $=await this.call("container status request",`/${W}?fields=status_code,status`,void 0,Z),J=$.status_code;if(typeof J!=="string"||!tW.has(J))throw new x("graph_error","Instagram's container status answered without a known status_code.",{status:200,containerId:W});let Q={id:W,statusCode:J};if(typeof $.status==="string"&&$.status!=="")Q.status=GW($.status);return Q}async waitUntilFinished(W,Z){let $=this.pollIntervalMs;for(;;){let{statusCode:J,status:Q}=await this.readStatus(W,Z);if(J==="FINISHED")return;if(J==="PUBLISHED")throw new x("invalid_input","That media container has been published already.",{containerId:W});if(J==="ERROR")throw new x("invalid_media",`Instagram could not process the media${Q?` (${Q})`:""}.`,{containerId:W});if(J==="EXPIRED")throw new x("expired","The media container expired before it was published.",{containerId:W});let Y=Z.deadline-Date.now();if(Y<=0)throw new x("timeout","Instagram had not finished processing the media in time; the container is still processing.",{containerId:W});await z5(Math.min($,Y),Z.signal),$=Math.min($*1.5,this.maxPollIntervalMs)}}async call(W,Z,$,J,{retry:Q=!0}={}){try{return await this.callOnce(W,Z,$,J)}catch(Y){if(!Q||!(Y instanceof x)||Y.code!=="transient")throw Y;return this.callOnce(W,Z,$,J)}}async callOnce(W,Z,$,J){J.signal?.throwIfAborted();let Q={method:$?"POST":"GET",signal:J.signal};if($){let z=new URLSearchParams;for(let[X,G]of Object.entries($))if(G!==void 0)z.set(X,G);Q.body=z}let Y;try{Y=await this.connection.fetch(`${this.version}${Z}`,Q)}catch(z){if(J.signal?.aborted)throw J.signal.reason;if(z instanceof TypeError)throw new x("transient",`Instagram's ${W} failed to reach Instagram.`);throw z}let K=h0(await Y.text().catch(()=>""));if(Y.ok)return K;throw Q5(W,Y.status,K)}}var tW=new Set(["EXPIRED","ERROR","FINISHED","IN_PROGRESS","PUBLISHED"]),rW=new Set([4,17,32,613,80002]),eW=new Set([3,10]),W5=new Set([9004,352,36000,36001,36002,36003,36004]),Z5=new Set([2207004,2207005,2207006,2207009,2207023,2207026,2207028,2207052]),$5=new Set([102,190,463,467]),J5=new Set([2207001,2207003,2207053]),$W={code:9007,subcode:2207027};function Q5(W,Z,$){let J=$.error??{},Q=QW(J.code),Y=QW(J.error_subcode),K=typeof J.type==="string"&&J.type!==""?J.type:void 0,z=typeof J.message==="string"&&J.message!==""?`: ${GW(J.message)}`:"",X=[Q,Y].filter((j)=>j!==void 0).join("/"),G=`Instagram refused the ${W} (HTTP ${Z}${K?`, ${K}`:""}${X?` ${X}`:""})${z}`,B="graph_error";if(Y===2207042)B="quota_exceeded";else if(Y===2207010)B="invalid_input";else if(Q!==void 0&&rW.has(Q))B="rate_limited";else if(Q!==void 0&&$5.has(Q))B="reconnect_required";else if(Q!==void 0&&(eW.has(Q)||Q>=200&&Q<=299))B="permission_denied";else if(Q!==void 0&&W5.has(Q)||Y!==void 0&&Z5.has(Y))B="invalid_media";else if(J.is_transient===!0||Q===1||Q===2||Y!==void 0&&J5.has(Y)||Z>=500||Z===429)B=Z===429?"rate_limited":"transient";return new x(B,G,{status:Z,graphCode:Q,graphSubcode:Y})}function Y5(W){return W.graphCode===$W.code||W.graphSubcode===$W.subcode}function K5(W,Z){if(W.containerId)return W;return new x(W.code,W.message,{status:W.status,graphCode:W.graphCode,graphSubcode:W.graphSubcode,containerId:Z})}function GW(W){return W.replace(/access_token=[^&\s"']*/gi,"access_token=[redacted]").replace(/\b(?:IG|EAA)[A-Za-z0-9_-]{20,}/g,"[redacted]").slice(0,500)}function JW(W,Z){let $=W.id;if(typeof $==="string"&&$!=="")return $;if(typeof $==="number"&&Number.isSafeInteger($))return String($);throw new x("graph_error",`Instagram's ${Z} answered without an id.`,{status:200})}function QW(W){let Z=Number(W);return W!==void 0&&W!==null&&Number.isFinite(Z)?Z:void 0}function E0(W,Z){let $=Number(W);return W!==void 0&&W!==null&&Number.isFinite($)?$:Z}function z5(W,Z){return new Promise(($,J)=>{if(Z?.aborted)return J(Z.reason);let Q=()=>{clearTimeout(Y),J(Z?.reason)},Y=setTimeout(()=>{Z?.removeEventListener("abort",Q),$()},W);Z?.addEventListener("abort",Q,{once:!0})})}function R(W){throw new x("invalid_input",W)}function m0(W){if(W===void 0)return;if(typeof W!=="string")R("caption must be a string.");if([...W].length>k.captionLength)R(`A caption takes at most ${k.captionLength} characters.`);if((W.match(/#[\p{L}\p{N}_]+/gu)??[]).length>k.hashtags)R(`A caption takes at most ${k.hashtags} hashtags.`);if((W.match(/(?<![\p{L}\p{N}_.@])@[\p{L}\p{N}_.]+/gu)??[]).length>k.mentions)R(`A caption takes at most ${k.mentions} @mentions.`)}function G5(W){if(!Array.isArray(W)||W.length>k.userTags)R(`userTags takes at most ${k.userTags} tags.`);for(let Z of W){let $=(J)=>typeof J==="number"&&J>=0&&J<=1;if(typeof Z?.username!=="string"||Z.username===""||!$(Z.x)||!$(Z.y))R("Each user tag needs a username, and x and y between 0 and 1.")}}function YW(W,Z){let $=Z?.imageUrl!==void 0,J=Z?.videoUrl!==void 0;if($===J)R(`${W} takes exactly one of imageUrl and videoUrl.`);if($)q1(`${W}.imageUrl`,Z.imageUrl);else q1(`${W}.videoUrl`,Z.videoUrl)}function q1(W,Z){let $;try{$=new URL(Z)}catch{R(`${W} is not an absolute URL.`)}if($.protocol!=="https:")R(`${W} must be an https URL: Instagram fetches the media from it.`);let J=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Q=KW(J);if(Q?zW(Q)!==null:!J.includes(".")||/(^|\.)(localhost|local|internal)$/.test(J))R(`${W} must be a public URL: Instagram fetches the media from it.`)}class u0{describe;rollout;when;serverOnly;salt;constructor(W={}){if(W.rollout!==void 0){let{rollout:Z}=W;if(!Number.isFinite(Z)||Z<0||Z>100)throw Error(`A feature's \`rollout\` must be a number between 0 and 100, received ${String(Z)}.`)}this.describe=W.describe,this.rollout=W.rollout,this.when=W.when,this.serverOnly=W.serverOnly??!1,this.salt=W.salt}}function X5(W={}){return new u0(W)}class XW extends p0{rows=new Map;constructor(W={}){super();for(let[Z,$]of Object.entries(W))this.rows.set(Z,{key:Z,active:$})}async load(){return[...this.rows.values()].map((W)=>({...W}))}async write(W,Z,$){return this.rows.set(W,{key:W,active:Z,updatedBy:$.actor,updatedAt:new Date}),{actorRecorded:!0}}}export{yZ as viewRouteConfigDefaults,p8 as translationConfigDefaults,j4 as toRangeHeaderValue,O5 as subjectFor,v5 as sniffContentType,V8 as scheduleConfigDefaults,L4 as resolveRange,X9 as redisConfigDefaults,K9 as rateLimiterConfigDefaults,Z8 as queueConfigDefaults,iW as parseMetaSignedRequest,N1 as parseContentRange,F5 as mintSessionToken,pZ as middlewareConfigDefaults,N8 as mcpCallOf,iZ as mailConfigDefaults,$9 as logConfigDefaults,j5 as isSessionToken,OZ as isFinalRunStatus,x6 as isBroadcastEvent,w5 as isActiveContentType,x5 as inRollout,bZ as imageConfigDefaults,b5 as filesystemConfigDefaults,i8 as featuresConfigDefaults,P8 as eventConfigDefaults,U5 as evaluateFeature,WZ as encodeCursor,hZ as documentScriptCspHash,w8 as discoverWorkflows,A8 as discoverListeners,v8 as discoverJobs,I8 as discoverCronJobs,y8 as discoverCommands,u8 as defineTranslationConfig,C8 as defineScheduleConfig,HZ as defineRunsConfig,wZ as defineRouteConfig,G9 as defineRedisConfig,Y9 as defineRateLimiterConfig,W8 as defineQueueConfig,uZ as defineMiddlewareConfig,nZ as defineMailConfig,Z9 as defineLogConfig,PZ as defineImageConfig,P5 as defineFilesystemConfig,n8 as defineFeaturesConfig,X5 as defineFeature,T8 as defineEventConfig,MW as defineEncryptionConfig,R8 as defineCommandConfig,k8 as defineCommand,r5 as defineChangeFeedConfig,y5 as defineCacheConfig,XZ as defineBroadcastConfig,L5 as defineAuthConfig,ZZ as decodeCursor,rZ as createWorkflowTableStatements,_Z as createRunsTableStatements,_8 as commandConfigDefaults,e5 as changeFeedConfigDefaults,A5 as cacheConfigDefaults,H5 as bucketOf,D5 as bucketKey,BZ as broadcastConfigDefaults,P4 as bearerToken,N5 as authConfigDefaults,F4 as assertDeletablePrefix,IZ as apiRouteConfigDefaults,s6 as XOAuthProvider,X8 as WorkflowRuntime,z8 as WorkflowCancelledError,q8 as Workflow,Y8 as WaitTimeoutError,mZ as ViewRouteDispatcher,f5 as UndeclaredFeatureError,m5 as TaggedCache,K8 as StepTimeoutError,Q8 as StepFailedError,G8 as Step,XW as StaticFeatureFlagSource,TZ as Sharp,U8 as Scheduler,d8 as ScheduleServiceProvider,EZ as STATIC_NAVIGATION_CSP_HASH,GZ as SOCKET_ID_HEADER,B5 as SESSION_TOKEN_PREFIX,n0 as S3Driver,F9 as RunsServiceProvider,kZ as RunNotFoundError,CZ as RunManager,fZ as RunFailure,j9 as RouteServiceProvider,lZ as ResendDriver,B9 as RedisServiceProvider,x4 as RedisRateLimiterTimeoutError,I1 as RedisRateLimiterDisconnectedError,t0 as RedisRateLimiter,w1 as RedisManager,g5 as RedisCacheStore,FZ as RedisBroadcastDriver,z9 as RateLimiterServiceProvider,D4 as RateLimiterDriver,M5 as RateLimiter,W1 as RangeNotSatisfiableError,h8 as QueueServiceProvider,B8 as QueueManager,t5 as ProviderConnection,N6 as PrismaMcpOAuthStore,NZ as PendingBroadcast,UZ as OPEN_RUN_STATUSES,o5 as OAuthReconnectRequiredError,a as OAuthProvider,g0 as OAuthConnectionProvider,b1 as OAuthConnectionError,P as OAuthCallbackError,Q9 as MiddlewareServiceProvider,vZ as MiddlewareRegistry,w as MetaSignedRequestError,$8 as MemoryWorkflowStore,SZ as MemoryRunStore,J8 as MemoryQueueDriver,L6 as MemoryMcpOAuthStore,aZ as MemoryLockStore,i5 as MemoryConnectionStore,JZ as MemoryChangeFeedDriver,h5 as MemoryCacheStore,jZ as MemoryBroadcastDriver,M8 as McpToolError,D8 as McpRegistry,F6 as McpOAuthServer,x8 as McpHttpServer,L8 as McpCallRefusedError,H8 as McpApiKeyResolver,o8 as MailServiceProvider,sZ as MailManager,J9 as LogServiceProvider,I5 as LogManager,p5 as LockManager,c5 as LockLostError,b8 as Listener,W9 as KernelIdServiceProvider,AZ as KernelId,j8 as Job,zZ as InvalidChannelError,c0 as InstagramPublisher,x as InstagramPublishError,WW as InstagramOAuthProvider,B4 as InstagramConnectionProvider,v as InstagramApiError,aW as Instagram,H4 as InMemoryRateLimiter,e8 as ImageServiceProvider,VZ as ImageOptimizationDriver,qZ as ImageManager,gZ as ISLAND_LOADER_CSP_HASH,k as INSTAGRAM_LIMITS,u5 as HeldLock,O6 as GoogleOAuthProvider,r8 as FilesystemServiceProvider,q5 as FilesystemManager,T5 as FileSystemDriver,D1 as FileStorageDriver,i as FileNotFoundError,s8 as FeaturesServiceProvider,k5 as FeatureSourceReadOnlyError,C5 as FeatureScope,S5 as FeatureReloadError,_5 as FeatureModelMissingError,V5 as FeatureManager,R5 as FeatureFlagStore,p0 as FeatureFlagSource,u0 as Feature,xZ as FINAL_RUN_STATUSES,t8 as EventServiceProvider,T as EventManager,u1 as Event,a8 as EncryptionServiceProvider,l5 as EncryptionKeyError,d5 as Encrypter,dZ as EmailDriver,n5 as DecryptionError,tZ as DatabaseWorkflowStore,RZ as DatabaseRunStore,eZ as DatabaseQueueDriver,oZ as DatabaseLockStore,l8 as DatabaseFeatureFlagSource,s5 as DatabaseConnectionStore,$Z as DatabaseChangeFeedDriver,F8 as DEFAULT_MCP_SCOPE,f8 as CronJob,a5 as ConnectionManager,M9 as CommandRegistry,O8 as CommandFailed,S8 as Command,KZ as ChangeFeedSubscription,m8 as ChangeFeedServiceProvider,YZ as ChangeFeedManager,QZ as ChangeFeedFullError,E8 as CacheServiceProvider,E5 as CacheManager,y1 as CONSENT_PAGE_HEADERS,g8 as BroadcastServiceProvider,DZ as BroadcastScope,MZ as BroadcastPayloadTooLargeError,LZ as BroadcastManager,U6 as BroadcastEvent,s0 as AzureBlobDriver,c8 as AuthServiceProvider,g1 as AuthManager,cZ as ApiRouteDispatcher};
|
|
71
71
|
|
|
72
|
-
//# debugId=
|
|
72
|
+
//# debugId=9C8060F18EBEB0F664756E2164756E21
|