gemi 0.144.0 → 0.145.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.
Files changed (208) hide show
  1. package/dist/ai/AgentController.d.ts +2 -2
  2. package/dist/ai/AgentController.d.ts.map +1 -1
  3. package/dist/ai/index.d.ts +2 -2
  4. package/dist/ai/index.d.ts.map +1 -1
  5. package/dist/ai/index.js +11 -11
  6. package/dist/ai/index.js.map +3 -3
  7. package/dist/ai/store/Nonces.d.ts +68 -0
  8. package/dist/ai/store/Nonces.d.ts.map +1 -1
  9. package/dist/ai/store/index.d.ts +1 -1
  10. package/dist/ai/store/index.d.ts.map +1 -1
  11. package/dist/app/index.js +1 -1
  12. package/dist/bun/plugin.js +1 -1
  13. package/dist/bun/preload.js +1 -1
  14. package/dist/{chunk-fg2k18d2.js → chunk-0k8fk96c.js} +2 -2
  15. package/dist/{chunk-fg2k18d2.js.map → chunk-0k8fk96c.js.map} +1 -1
  16. package/dist/{chunk-y5yac6n1.js → chunk-0mt7kqwx.js} +2 -2
  17. package/dist/{chunk-y5yac6n1.js.map → chunk-0mt7kqwx.js.map} +1 -1
  18. package/dist/{chunk-1ed75a7b.js → chunk-1fyn63ka.js} +3 -3
  19. package/dist/{chunk-1ed75a7b.js.map → chunk-1fyn63ka.js.map} +1 -1
  20. package/dist/{chunk-tkvamktq.js → chunk-1ttd4rn9.js} +2 -2
  21. package/dist/{chunk-tkvamktq.js.map → chunk-1ttd4rn9.js.map} +1 -1
  22. package/dist/{chunk-m70hn4eg.js → chunk-1wz6kwjc.js} +2 -2
  23. package/dist/{chunk-m70hn4eg.js.map → chunk-1wz6kwjc.js.map} +1 -1
  24. package/dist/{chunk-fsem81ec.js → chunk-29jmaj16.js} +1 -1
  25. package/dist/{chunk-fpz9e3xx.js → chunk-2b3hh9xw.js} +3 -3
  26. package/dist/{chunk-fpz9e3xx.js.map → chunk-2b3hh9xw.js.map} +1 -1
  27. package/dist/{chunk-n9zycjm1.js → chunk-2djjs8f1.js} +3 -3
  28. package/dist/{chunk-n9zycjm1.js.map → chunk-2djjs8f1.js.map} +1 -1
  29. package/dist/{chunk-p81qeav5.js → chunk-2ery6a75.js} +3 -3
  30. package/dist/{chunk-p81qeav5.js.map → chunk-2ery6a75.js.map} +1 -1
  31. package/dist/{chunk-hyhbk12v.js → chunk-2k3935ke.js} +2 -2
  32. package/dist/{chunk-hyhbk12v.js.map → chunk-2k3935ke.js.map} +1 -1
  33. package/dist/{chunk-qt6x2r6a.js → chunk-2x6cv37t.js} +2 -2
  34. package/dist/{chunk-qt6x2r6a.js.map → chunk-2x6cv37t.js.map} +1 -1
  35. package/dist/{chunk-68f0jpje.js → chunk-313593t3.js} +2 -2
  36. package/dist/{chunk-68f0jpje.js.map → chunk-313593t3.js.map} +1 -1
  37. package/dist/{chunk-5qfzvnyp.js → chunk-3csz8pfk.js} +3 -3
  38. package/dist/{chunk-5qfzvnyp.js.map → chunk-3csz8pfk.js.map} +1 -1
  39. package/dist/{chunk-rezmtdyt.js → chunk-3x8zrsby.js} +2 -2
  40. package/dist/{chunk-rezmtdyt.js.map → chunk-3x8zrsby.js.map} +1 -1
  41. package/dist/{chunk-6d3m2w2p.js → chunk-43ws58db.js} +2 -2
  42. package/dist/{chunk-6d3m2w2p.js.map → chunk-43ws58db.js.map} +1 -1
  43. package/dist/chunk-49s8wwp2.js +5 -0
  44. package/dist/{chunk-b6mgrrk6.js.map → chunk-49s8wwp2.js.map} +1 -1
  45. package/dist/{chunk-ncb1qtae.js → chunk-4d4td4k9.js} +2 -2
  46. package/dist/{chunk-ncb1qtae.js.map → chunk-4d4td4k9.js.map} +1 -1
  47. package/dist/{chunk-v57ndv0h.js → chunk-4jd25v6d.js} +2 -2
  48. package/dist/{chunk-v57ndv0h.js.map → chunk-4jd25v6d.js.map} +1 -1
  49. package/dist/{chunk-78bfmwp0.js → chunk-4m0eqq80.js} +2 -2
  50. package/dist/{chunk-78bfmwp0.js.map → chunk-4m0eqq80.js.map} +1 -1
  51. package/dist/{chunk-ktrm6y5j.js → chunk-563ksar3.js} +3 -3
  52. package/dist/{chunk-ktrm6y5j.js.map → chunk-563ksar3.js.map} +1 -1
  53. package/dist/{chunk-z80v4z8y.js → chunk-5q2pmve9.js} +2 -2
  54. package/dist/{chunk-z80v4z8y.js.map → chunk-5q2pmve9.js.map} +1 -1
  55. package/dist/{chunk-20d0n391.js → chunk-5yz684rw.js} +2 -2
  56. package/dist/{chunk-20d0n391.js.map → chunk-5yz684rw.js.map} +1 -1
  57. package/dist/{chunk-236be97q.js → chunk-63xwah5k.js} +1 -1
  58. package/dist/{chunk-b4jx4fzq.js → chunk-65wy1r1a.js} +1 -1
  59. package/dist/{chunk-9tgcmx4h.js → chunk-70yz9e7f.js} +2 -2
  60. package/dist/{chunk-9tgcmx4h.js.map → chunk-70yz9e7f.js.map} +1 -1
  61. package/dist/{chunk-t03nda3s.js → chunk-73rzf7ys.js} +2 -2
  62. package/dist/{chunk-t03nda3s.js.map → chunk-73rzf7ys.js.map} +1 -1
  63. package/dist/{chunk-1cn7ets3.js → chunk-7txqv2qq.js} +3 -3
  64. package/dist/{chunk-1cn7ets3.js.map → chunk-7txqv2qq.js.map} +1 -1
  65. package/dist/{chunk-1skdsmjx.js → chunk-86zhngpg.js} +2 -2
  66. package/dist/{chunk-1skdsmjx.js.map → chunk-86zhngpg.js.map} +1 -1
  67. package/dist/{chunk-ce9wm3r9.js → chunk-877yc341.js} +3 -3
  68. package/dist/{chunk-ce9wm3r9.js.map → chunk-877yc341.js.map} +1 -1
  69. package/dist/{chunk-wffc5k3m.js → chunk-87y2nrjy.js} +2 -2
  70. package/dist/{chunk-wffc5k3m.js.map → chunk-87y2nrjy.js.map} +1 -1
  71. package/dist/{chunk-9zd7c4wq.js → chunk-8k346pjw.js} +14 -14
  72. package/dist/{chunk-9zd7c4wq.js.map → chunk-8k346pjw.js.map} +3 -3
  73. package/dist/{chunk-27xsjq8a.js → chunk-8km4drvv.js} +3 -3
  74. package/dist/{chunk-27xsjq8a.js.map → chunk-8km4drvv.js.map} +1 -1
  75. package/dist/{chunk-sa6a0wy1.js → chunk-94hcjdbe.js} +2 -2
  76. package/dist/{chunk-sa6a0wy1.js.map → chunk-94hcjdbe.js.map} +1 -1
  77. package/dist/{chunk-kaphqnpp.js → chunk-9z8zq4rx.js} +3 -3
  78. package/dist/{chunk-kaphqnpp.js.map → chunk-9z8zq4rx.js.map} +1 -1
  79. package/dist/{chunk-8ex0y47w.js → chunk-apga49vp.js} +2 -2
  80. package/dist/{chunk-8ex0y47w.js.map → chunk-apga49vp.js.map} +1 -1
  81. package/dist/{chunk-yjszzjyj.js → chunk-attr793y.js} +2 -2
  82. package/dist/{chunk-yjszzjyj.js.map → chunk-attr793y.js.map} +1 -1
  83. package/dist/{chunk-1x9ghjpt.js → chunk-bsa6b82q.js} +1 -1
  84. package/dist/{chunk-ceb4jcrm.js → chunk-bstn00nx.js} +2 -2
  85. package/dist/{chunk-ceb4jcrm.js.map → chunk-bstn00nx.js.map} +1 -1
  86. package/dist/{chunk-azd6da5h.js → chunk-bykkqvd8.js} +2 -2
  87. package/dist/{chunk-azd6da5h.js.map → chunk-bykkqvd8.js.map} +1 -1
  88. package/dist/{chunk-9k46m1vf.js → chunk-cee5gq7t.js} +2 -2
  89. package/dist/{chunk-9k46m1vf.js.map → chunk-cee5gq7t.js.map} +1 -1
  90. package/dist/{chunk-9dkpv8ev.js → chunk-dxh8njb4.js} +2 -2
  91. package/dist/{chunk-9dkpv8ev.js.map → chunk-dxh8njb4.js.map} +1 -1
  92. package/dist/{chunk-maqkrbsb.js → chunk-e06t0625.js} +2 -2
  93. package/dist/{chunk-maqkrbsb.js.map → chunk-e06t0625.js.map} +1 -1
  94. package/dist/{chunk-0839f72f.js → chunk-e9z8p2fy.js} +2 -2
  95. package/dist/{chunk-0839f72f.js.map → chunk-e9z8p2fy.js.map} +1 -1
  96. package/dist/{chunk-6hs102jh.js → chunk-eqv7yxk7.js} +2 -2
  97. package/dist/{chunk-6hs102jh.js.map → chunk-eqv7yxk7.js.map} +1 -1
  98. package/dist/{chunk-m6t5a0me.js → chunk-fqqbnp0z.js} +2 -2
  99. package/dist/{chunk-m6t5a0me.js.map → chunk-fqqbnp0z.js.map} +1 -1
  100. package/dist/{chunk-1w5dnkd1.js → chunk-g22kph4n.js} +2 -2
  101. package/dist/{chunk-1w5dnkd1.js.map → chunk-g22kph4n.js.map} +1 -1
  102. package/dist/{chunk-rvm5mkwm.js → chunk-g8sh9btf.js} +2 -2
  103. package/dist/{chunk-rvm5mkwm.js.map → chunk-g8sh9btf.js.map} +1 -1
  104. package/dist/{chunk-a78b9v7h.js → chunk-gvdg52ew.js} +4 -4
  105. package/dist/{chunk-a78b9v7h.js.map → chunk-gvdg52ew.js.map} +1 -1
  106. package/dist/{chunk-8ky8cmde.js → chunk-h8eawyhx.js} +2 -2
  107. package/dist/{chunk-8ky8cmde.js.map → chunk-h8eawyhx.js.map} +1 -1
  108. package/dist/{chunk-r567t83k.js → chunk-hcw671mg.js} +4 -4
  109. package/dist/{chunk-r567t83k.js.map → chunk-hcw671mg.js.map} +1 -1
  110. package/dist/{chunk-ej4kf7m5.js → chunk-hh5bs656.js} +3 -3
  111. package/dist/{chunk-ej4kf7m5.js.map → chunk-hh5bs656.js.map} +1 -1
  112. package/dist/{chunk-3q7sc68p.js → chunk-j6ygdvj8.js} +2 -2
  113. package/dist/{chunk-3q7sc68p.js.map → chunk-j6ygdvj8.js.map} +1 -1
  114. package/dist/{chunk-t2nsn0r2.js → chunk-jzpbwvbt.js} +2 -2
  115. package/dist/{chunk-t2nsn0r2.js.map → chunk-jzpbwvbt.js.map} +1 -1
  116. package/dist/{chunk-en33hg1c.js → chunk-k79ajvtc.js} +2 -2
  117. package/dist/{chunk-en33hg1c.js.map → chunk-k79ajvtc.js.map} +1 -1
  118. package/dist/{chunk-t0wfj6hy.js → chunk-k8pn2qvf.js} +2 -2
  119. package/dist/{chunk-t0wfj6hy.js.map → chunk-k8pn2qvf.js.map} +1 -1
  120. package/dist/{chunk-83cvkhzn.js → chunk-kmh402m4.js} +2 -2
  121. package/dist/{chunk-83cvkhzn.js.map → chunk-kmh402m4.js.map} +1 -1
  122. package/dist/{chunk-b4mg6v4g.js → chunk-m9am5fqq.js} +5 -5
  123. package/dist/{chunk-b4mg6v4g.js.map → chunk-m9am5fqq.js.map} +3 -3
  124. package/dist/{chunk-m8yd59gg.js → chunk-mr3szvr3.js} +2 -2
  125. package/dist/{chunk-m8yd59gg.js.map → chunk-mr3szvr3.js.map} +1 -1
  126. package/dist/{chunk-mkw35cz7.js → chunk-mtamgvf4.js} +2 -2
  127. package/dist/{chunk-mkw35cz7.js.map → chunk-mtamgvf4.js.map} +1 -1
  128. package/dist/{chunk-5xfpqda5.js → chunk-mv1rs9he.js} +1 -1
  129. package/dist/{chunk-s29tgy4y.js → chunk-mzkzgp2j.js} +2 -2
  130. package/dist/{chunk-s29tgy4y.js.map → chunk-mzkzgp2j.js.map} +1 -1
  131. package/dist/{chunk-9xzg05xg.js → chunk-n9n4qt20.js} +3 -3
  132. package/dist/{chunk-9xzg05xg.js.map → chunk-n9n4qt20.js.map} +1 -1
  133. package/dist/{chunk-2ra5skyk.js → chunk-p27y4xrw.js} +2 -2
  134. package/dist/{chunk-2ra5skyk.js.map → chunk-p27y4xrw.js.map} +1 -1
  135. package/dist/{chunk-sgwgj2q0.js → chunk-pq657qcp.js} +1 -1
  136. package/dist/{chunk-63q7ycwt.js → chunk-pwbm3x1y.js} +2 -2
  137. package/dist/{chunk-63q7ycwt.js.map → chunk-pwbm3x1y.js.map} +1 -1
  138. package/dist/{chunk-w4ma7978.js → chunk-q4qw629n.js} +2 -2
  139. package/dist/{chunk-w4ma7978.js.map → chunk-q4qw629n.js.map} +1 -1
  140. package/dist/{chunk-f2e7n064.js → chunk-q9na1syb.js} +2 -2
  141. package/dist/{chunk-f2e7n064.js.map → chunk-q9na1syb.js.map} +1 -1
  142. package/dist/{chunk-x0t3t7g3.js → chunk-rkbwb3v5.js} +2 -2
  143. package/dist/{chunk-x0t3t7g3.js.map → chunk-rkbwb3v5.js.map} +1 -1
  144. package/dist/{chunk-0t2ym9ap.js → chunk-rma7afjd.js} +3 -3
  145. package/dist/{chunk-0t2ym9ap.js.map → chunk-rma7afjd.js.map} +1 -1
  146. package/dist/{chunk-f5qdyw45.js → chunk-tr9ynv3w.js} +2 -2
  147. package/dist/{chunk-f5qdyw45.js.map → chunk-tr9ynv3w.js.map} +1 -1
  148. package/dist/{chunk-kzc6bn8n.js → chunk-twrf6d08.js} +2 -2
  149. package/dist/{chunk-kzc6bn8n.js.map → chunk-twrf6d08.js.map} +1 -1
  150. package/dist/{chunk-6jd0e1dz.js → chunk-v9z4x5j2.js} +2 -2
  151. package/dist/{chunk-6jd0e1dz.js.map → chunk-v9z4x5j2.js.map} +1 -1
  152. package/dist/{chunk-jmhrpfqn.js → chunk-vm5t0j24.js} +2 -2
  153. package/dist/{chunk-jmhrpfqn.js.map → chunk-vm5t0j24.js.map} +1 -1
  154. package/dist/{chunk-a37shxb1.js → chunk-xv58jnpb.js} +2 -2
  155. package/dist/{chunk-a37shxb1.js.map → chunk-xv58jnpb.js.map} +1 -1
  156. package/dist/{chunk-p57nt0pm.js → chunk-ydkv9e8w.js} +3 -3
  157. package/dist/{chunk-p57nt0pm.js.map → chunk-ydkv9e8w.js.map} +1 -1
  158. package/dist/{chunk-aw8gj99f.js → chunk-ymdpt00k.js} +2 -2
  159. package/dist/{chunk-aw8gj99f.js.map → chunk-ymdpt00k.js.map} +1 -1
  160. package/dist/{chunk-5g7m7g4a.js → chunk-z7tsh9qr.js} +3 -3
  161. package/dist/{chunk-5g7m7g4a.js.map → chunk-z7tsh9qr.js.map} +1 -1
  162. package/dist/config/index.js +1 -1
  163. package/dist/console/run.js +2 -2
  164. package/dist/console/run.js.map +1 -1
  165. package/dist/container/index.js +2 -2
  166. package/dist/container/index.js.map +1 -1
  167. package/dist/database/index.js +2 -2
  168. package/dist/database/index.js.map +1 -1
  169. package/dist/email/index.js +2 -2
  170. package/dist/email/index.js.map +1 -1
  171. package/dist/facades/index.js +2 -2
  172. package/dist/facades/index.js.map +1 -1
  173. package/dist/foundation/index.js +2 -2
  174. package/dist/foundation/index.js.map +1 -1
  175. package/dist/http/index.js +2 -2
  176. package/dist/http/index.js.map +1 -1
  177. package/dist/i18n/dictionaryRuntime.js +2 -2
  178. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  179. package/dist/i18n/index.js +2 -2
  180. package/dist/i18n/index.js.map +1 -1
  181. package/dist/kernel/index.js +2 -2
  182. package/dist/kernel/index.js.map +1 -1
  183. package/dist/orm/index.js +2 -2
  184. package/dist/orm/index.js.map +1 -1
  185. package/dist/server/index.js +2 -2
  186. package/dist/server/index.js.map +1 -1
  187. package/dist/services/index.d.ts +2 -1
  188. package/dist/services/index.d.ts.map +1 -1
  189. package/dist/services/index.js +9 -9
  190. package/dist/services/index.js.map +4 -3
  191. package/dist/services/mcp/http/McpHttpServer.d.ts +81 -1
  192. package/dist/services/mcp/http/McpHttpServer.d.ts.map +1 -1
  193. package/dist/services/mcp/http/oauth/prismaStore.d.ts +112 -0
  194. package/dist/services/mcp/http/oauth/prismaStore.d.ts.map +1 -0
  195. package/dist/services/queue/work.js +2 -2
  196. package/dist/services/queue/work.js.map +1 -1
  197. package/dist/stats/route-table.js +1 -1
  198. package/dist/support/index.js +2 -2
  199. package/dist/support/index.js.map +1 -1
  200. package/dist/vitest/index.js +1 -1
  201. package/package.json +1 -1
  202. package/dist/chunk-b6mgrrk6.js +0 -5
  203. /package/dist/{chunk-fsem81ec.js.map → chunk-29jmaj16.js.map} +0 -0
  204. /package/dist/{chunk-236be97q.js.map → chunk-63xwah5k.js.map} +0 -0
  205. /package/dist/{chunk-b4jx4fzq.js.map → chunk-65wy1r1a.js.map} +0 -0
  206. /package/dist/{chunk-1x9ghjpt.js.map → chunk-bsa6b82q.js.map} +0 -0
  207. /package/dist/{chunk-5xfpqda5.js.map → chunk-mv1rs9he.js.map} +0 -0
  208. /package/dist/{chunk-sgwgj2q0.js.map → chunk-pq657qcp.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{cb as w8}from"../chunk-fcqx2t0p.js";import{Ab as j8,Bb as M8,Cb as L8,Db as N8,Eb as S4,Fb as Z6,Gb as k,Hb as x8,Ib as D8,Jb as F8,Kb as H8,Lb as U8,Mb as O8,Nb as S8,Ob as R8,Pb as _8,Qb as f8,Rb as k8,Sb as C8,Tb as b8,Ub as T8,Vb as I8,Wb as P8,db as PZ,eb as wZ,fb as VZ,gb as vZ,hb as qZ,ib as H4,jb as yZ,kb as N4,lb as x4,mb as V1,nb as AZ,ob as hZ,pb as Z8,tb as $8,ub as J8,vb as Q8,wb as Y8,xb as z8,yb as X8,zb as B8}from"../chunk-b4mg6v4g.js";import"../chunk-9zd7c4wq.js";import{Ad as eZ,Bd as W8,md as gZ,nd as EZ,od as mZ,pd as cZ,qd as uZ,rd as dZ,sd as lZ,td as nZ,ud as iZ,vd as oZ,wd as sZ,xd as aZ,yd as tZ,zd as rZ}from"../chunk-fpz9e3xx.js";import{Cd as pZ}from"../chunk-6jd0e1dz.js";import{Dd as LZ,Ed as NZ,Fd as xZ,Gd as DZ,Hd as FZ,Id as HZ,Jd as UZ,Kd as OZ,Ld as SZ,Md as RZ,Nd as _Z,Od as fZ,Pd as kZ,Qd as CZ,Rd as bZ,Sd as TZ,Xd as IZ}from"../chunk-ce9wm3r9.js";import{Yd as K8,Zd as G8}from"../chunk-p57nt0pm.js";import"../chunk-6hs102jh.js";import{$e as eW,$f as n5,Ae as AW,Af as b5,Be as hW,Bf as T5,Bg as v1,Ce as gW,Cf as P5,De as EW,Ee as mW,Fe as b0,Ff as w5,Ge as cW,Gf as V5,He as uW,Hf as v5,Ie as pW,If as q5,Je as dW,Ke as lW,Kf as y5,Lf as A5,Mf as h5,Mg as KZ,Nf as g5,Ng as GZ,Of as E5,Pf as m5,Qf as c5,Rf as u5,Sf as p5,Tf as d5,Yf as C,Zf as i,_f as l5,af as W5,ag as i5,bf as Z5,bg as o5,cf as $5,cg as s5,df as J5,ef as Q5,eg as a5,fe as o0,fg as t5,ge as bW,gg as r5,he as TW,hg as e5,ie as IW,ig as WZ,ke as PW,kf as D5,lf as F5,lg as ZZ,mf as H5,mg as $Z,nf as U5,ng as JZ,oe as s0,of as O5,pe as v0,pf as S5,qe as q0,qf as R5,re as G4,rf as _5,se as wW,sf as f5,sg as QZ,uf as k5,vf as W6,we as VW,wf as C5,wg as YZ,xe as vW,ye as qW,ze as yW}from"../chunk-a78b9v7h.js";import"../chunk-ej4kf7m5.js";import"../chunk-5qfzvnyp.js";import{Bi as I1,Fh as K4,Gh as J4,Hh as M1,Uh as L4,Xh as t,Zh as d,bi as Q4,ci as L1,di as T1,ei as nW,fi as iW,gi as oW,hi as sW,wi as aW,xi as tW,zi as rW}from"../chunk-27xsjq8a.js";import"../chunk-9k46m1vf.js";import{Li as r}from"../chunk-fg2k18d2.js";import{Ti as j5,Ui as M5,Vi as b1,Wi as L5,Xi as k0,Yi as N5,Zi as x5}from"../chunk-ktrm6y5j.js";import{dj as z5,ej as X5,fj as B5}from"../chunk-9xzg05xg.js";import"../chunk-a37shxb1.js";import{Oj as I5}from"../chunk-68f0jpje.js";import{Qj as Y5,Rj as K5,Sj as G5}from"../chunk-1skdsmjx.js";import"../chunk-yjszzjyj.js";import"../chunk-p81qeav5.js";import"../chunk-t03nda3s.js";import"../chunk-qt6x2r6a.js";import{Ik as zZ,Jk as XZ,Kk as BZ,Lk as jZ,Nk as MZ}from"../chunk-5g7m7g4a.js";import"../chunk-m8yd59gg.js";import{Xk as q}from"../chunk-1ed75a7b.js";import"../chunk-0839f72f.js";import"../chunk-rvm5mkwm.js";import"../chunk-s29tgy4y.js";import"../chunk-8ex0y47w.js";import"../chunk-m6t5a0me.js";import{vl as I0}from"../chunk-t2nsn0r2.js";import{Buffer as T0}from"buffer";class P0 extends L1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-r567t83k.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 T0?$:$ instanceof Blob||$ instanceof File?T0.from(await $.arrayBuffer()):"",{sdk:G,client:z}=await this.connect();return Z?.throwIfAborted(),await z.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={}){Q4(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 z=(await Q.send(new J.DeleteObjectsCommand({Bucket:$,Delete:{Objects:K.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(z.length>0){let X=z[0];throw Error(`S3 could not delete ${z.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.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?J4(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 z=M1(G.ContentRange),X=Boolean(z)&&G.$metadata?.httpStatusCode===206,B=z?.total??G.ContentLength??0;return{body:G.Body.transformToWebStream(),start:z?.start??0,end:z?.end??B-1,total:B,partial:X,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 w0}from"buffer";import{Readable as m6}from"stream";function Y4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function c6(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class V0 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 w0?$:w0.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,z=Q?.kind==="suffix"||Q?.kind==="offset"&&Q.end===null&&Q.start===0;if(Q&&z){let H=await this.size({name:$,bucket:J}),p=K4(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 X;try{X=await Y.download(K,G,Z?{abortSignal:Z}:void 0)}catch(H){if(c6(H))throw new t(await this.size({name:$,bucket:J}));if(Y4(H))throw new d($);throw H}let B=M1(X.contentRange),j=Boolean(B),x=B?.total??X.contentLength??0,O=await u6(X);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:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.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(Y4(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(Y4(Q))return;throw Q}}}async function u6(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return m6.toWeb(W.readableStreamBody);return null}function p6(W){return W}var d6=`
2
+ import{cb as y8}from"../chunk-fcqx2t0p.js";import{Ab as x8,Bb as D8,Cb as F8,Db as H8,Eb as f4,Fb as Y6,Gb as C,Hb as U8,Ib as O8,Jb as S8,Kb as R8,Lb as _8,Mb as f8,Nb as C8,Ob as k8,Pb as b8,Qb as T8,Rb as P8,Sb as V8,Tb as I8,Ub as v8,Vb as q8,Wb as w8,db as wZ,eb as yZ,fb as AZ,gb as hZ,hb as gZ,ib as O4,jb as EZ,kb as D4,lb as F4,mb as v1,nb as mZ,ob as cZ,pb as Y8,tb as K8,ub as G8,vb as z8,wb as X8,xb as M8,yb as L8,zb as N8}from"../chunk-m9am5fqq.js";import{Zb as R4}from"../chunk-8k346pjw.js";import{Ad as $8,Bd as J8,Cd as Q8,nd as uZ,od as pZ,pd as dZ,qd as lZ,rd as nZ,sd as sZ,td as oZ,ud as aZ,vd as tZ,wd as rZ,xd as eZ,yd as W8,zd as Z8}from"../chunk-2b3hh9xw.js";import{Dd as iZ}from"../chunk-v9z4x5j2.js";import{Ed as FZ,Fd as HZ,Gd as UZ,Hd as OZ,Id as SZ,Jd as RZ,Kd as _Z,Ld as fZ,Md as CZ,Nd as kZ,Od as bZ,Pd as TZ,Qd as PZ,Rd as VZ,Sd as IZ,Td as vZ,Yd as qZ}from"../chunk-877yc341.js";import{Zd as B8,_d as j8}from"../chunk-ydkv9e8w.js";import"../chunk-eqv7yxk7.js";import{$f as o5,Ae as EW,Be as mW,Bf as I5,Ce as cW,Cf as v5,Cg as q1,De as uW,Df as w5,Ee as pW,Fe as dW,Ge as V0,Gf as y5,He as lW,Hf as A5,Ie as nW,If as h5,Je as iW,Jf as g5,Ke as sW,Le as oW,Lf as E5,Mf as m5,Nf as c5,Ng as BZ,Of as u5,Og as jZ,Pf as p5,Qf as d5,Rf as l5,Sf as n5,Tf as i5,Uf as s5,Zf as k,_f as i,af as J5,ag as a5,bf as Q5,bg as t5,cf as Y5,cg as r5,df as K5,dg as e5,ef as G5,ff as z5,fg as WZ,ge as t0,gg as ZZ,he as IW,hg as $Z,ie as vW,ig as JZ,je as qW,jg as QZ,le as wW,lf as O5,mf as S5,mg as YZ,nf as R5,ng as KZ,of as _5,og as GZ,pe as r0,pf as f5,qe as A0,qf as C5,re as h0,rf as k5,se as X4,sf as b5,te as yW,tf as T5,tg as zZ,vf as P5,wf as Q6,xe as AW,xf as V5,xg as XZ,ye as hW,ze as gW}from"../chunk-gvdg52ew.js";import"../chunk-hh5bs656.js";import"../chunk-3csz8pfk.js";import{Ai as $5,Ci as P1,Gh as z4,Hh as Y4,Ih as M1,Vh as x4,Yh as t,_h as d,ci as K4,di as L1,ei as T1,fi as aW,gi as tW,hi as rW,ii as eW,xi as W5,yi as Z5}from"../chunk-8km4drvv.js";import"../chunk-cee5gq7t.js";import{Mi as r}from"../chunk-0k8fk96c.js";import{Ui as x5,Vi as D5,Wi as b1,Xi as F5,Yi as T0,Zi as H5,_i as U5}from"../chunk-563ksar3.js";import{ej as M5,fj as L5,gj as N5}from"../chunk-n9n4qt20.js";import"../chunk-xv58jnpb.js";import{Pj as q5}from"../chunk-313593t3.js";import{Rj as X5,Sj as B5,Tj as j5}from"../chunk-86zhngpg.js";import"../chunk-attr793y.js";import"../chunk-2ery6a75.js";import"../chunk-73rzf7ys.js";import"../chunk-2x6cv37t.js";import{Jk as MZ,Kk as LZ,Lk as NZ,Mk as xZ,Ok as DZ}from"../chunk-z7tsh9qr.js";import"../chunk-mr3szvr3.js";import{Yk as w}from"../chunk-1fyn63ka.js";import"../chunk-e9z8p2fy.js";import"../chunk-g8sh9btf.js";import"../chunk-mzkzgp2j.js";import"../chunk-apga49vp.js";import"../chunk-fqqbnp0z.js";import{wl as v0}from"../chunk-jzpbwvbt.js";import{Buffer as I0}from"buffer";class q0 extends L1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-hcw671mg.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 I0?$:$ instanceof Blob||$ instanceof File?I0.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={}){K4(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?Y4(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 w0}from"buffer";import{Readable as d6}from"stream";function G4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function l6(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class y0 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 w0?$:w0.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=z4(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(l6(H))throw new t(await this.size({name:$,bucket:J}));if(G4(H))throw new d($);throw H}let B=M1(z.contentRange),j=Boolean(B),x=B?.total??z.contentLength??0,O=await n6(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(G4(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(G4(Q))return;throw Q}}}async function n6(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return d6.toWeb(W.readableStreamBody);return null}function i6(W){return W}var s6=`
3
3
  local currentKey = KEYS[1]
4
4
  local previousKey = KEYS[2]
5
5
  local limit = tonumber(ARGV[1])
@@ -26,7 +26,7 @@ current = redis.call("INCRBY", currentKey, cost)
26
26
  redis.call("PEXPIRE", currentKey, window * 2)
27
27
 
28
28
  return {1, current, previous}
29
- `;class y0 extends G4{injectedClient;prefix;failOpen;onError;scriptSha=null;constructor(W={}){super();this.injectedClient=W.client,this.prefix=W.prefix??"gemi:rl",this.failOpen=W.failOpen??!0,this.onError=W.onError??((Z)=>console.error(Z))}async consume(W){let{key:Z,limit:$,window:J}=W,Q=W.cost??1,Y=Date.now(),K=v0(Y,J),G=Y-K,z=K/J;try{let X=await this.run([`${this.prefix}:${Z}:${z}`,`${this.prefix}:${Z}:${z-1}`],[String($),String(J),String(G),String(Q)]),[B,j,x]=(Array.isArray(X)?X:[]).map(Number);return q0({allowed:B===1,current:Number.isFinite(j)?j:0,previous:Number.isFinite(x)?x:0,now:Y,elapsed:G,window:J,limit:$,cost:Q})}catch(X){if(this.onError(X),!this.failOpen)return{allowed:!1,limit:$,remaining:0,resetAt:Y+J,retryAfter:J};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-Q)),resetAt:K+J,retryAfter:0}}}get client(){if(this.injectedClient)return this.injectedClient;let W=q(),Z=W.bound(I1)?W.make(I1).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 $=this.client,J=[String(W.length),...W,...Z];try{return await $.send("EVALSHA",[await this.load($),...J])}catch(Q){if(!l6(Q))throw Q;return this.scriptSha=null,await $.send("EVALSHA",[await this.load($),...J])}}load(W){if(!this.scriptSha)this.scriptSha=Promise.resolve(W.send("SCRIPT",["LOAD",d6])).then(String).catch((Z)=>{throw this.scriptSha=null,Z});return this.scriptSha}}function l6(W){return String(W?.message??W).includes("NOSCRIPT")}import{createHash as U4,randomBytes as l,timingSafeEqual as n6}from"crypto";var P1=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 A0(W,Z){let $=W.client.name?f(W.client.name):"An application",J=W.scopes.map((Y)=>`<li><strong>${f(Y.name)}</strong><br><span>${f(Y.description)}</span></li>`).join(""),Q=Object.entries(W.form.fields).map(([Y,K])=>`<input type="hidden" name="${f(Y)}" value="${f(K)}">`).join("");return`<!doctype html>
29
+ `;class g0 extends X4{injectedClient;prefix;failOpen;onError;scriptSha=null;constructor(W={}){super();this.injectedClient=W.client,this.prefix=W.prefix??"gemi:rl",this.failOpen=W.failOpen??!0,this.onError=W.onError??((Z)=>console.error(Z))}async consume(W){let{key:Z,limit:$,window:J}=W,Q=W.cost??1,Y=Date.now(),K=A0(Y,J),G=Y-K,X=K/J;try{let z=await this.run([`${this.prefix}:${Z}:${X}`,`${this.prefix}:${Z}:${X-1}`],[String($),String(J),String(G),String(Q)]),[B,j,x]=(Array.isArray(z)?z:[]).map(Number);return h0({allowed:B===1,current:Number.isFinite(j)?j:0,previous:Number.isFinite(x)?x:0,now:Y,elapsed:G,window:J,limit:$,cost:Q})}catch(z){if(this.onError(z),!this.failOpen)return{allowed:!1,limit:$,remaining:0,resetAt:Y+J,retryAfter:J};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-Q)),resetAt:K+J,retryAfter:0}}}get client(){if(this.injectedClient)return this.injectedClient;let W=w(),Z=W.bound(P1)?W.make(P1).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 $=this.client,J=[String(W.length),...W,...Z];try{return await $.send("EVALSHA",[await this.load($),...J])}catch(Q){if(!o6(Q))throw Q;return this.scriptSha=null,await $.send("EVALSHA",[await this.load($),...J])}}load(W){if(!this.scriptSha)this.scriptSha=Promise.resolve(W.send("SCRIPT",["LOAD",s6])).then(String).catch((Z)=>{throw this.scriptSha=null,Z});return this.scriptSha}}function o6(W){return String(W?.message??W).includes("NOSCRIPT")}import{createHash as S4,randomBytes as l,timingSafeEqual as a6}from"crypto";var V1=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 E0(W,Z){let $=W.client.name?f(W.client.name):"An application",J=W.scopes.map((Y)=>`<li><strong>${f(Y.name)}</strong><br><span>${f(Y.description)}</span></li>`).join(""),Q=Object.entries(W.form.fields).map(([Y,K])=>`<input type="hidden" name="${f(Y)}" value="${f(K)}">`).join("");return`<!doctype html>
30
30
  <html lang="en">
31
31
  <head>
32
32
  <meta charset="utf-8">
@@ -61,12 +61,12 @@ return {1, current, previous}
61
61
  </form>
62
62
  </main>
63
63
  </body>
64
- </html>`}function h0(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 z4="gmcp_at_",X4="gmcp_rt_",g0="gmcp_ac_",i6="gmcp_c_",o6="gmcp_cs_",B4="gemi.mcp.oauth.ticket.v1",E0="gemi.mcp.oauth.consent.v1",s6=600000,m0=120000,D4=16384,a6={limit:20,window:3600},t6={limit:60,window:60},w1=["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 a0{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=c0("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=c0("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=H4(W);if(!Z?.startsWith(z4))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?r6:{};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,z]of Object.entries(Y))K.headers.set(G,z);return K}async consent(W,Z){if(!Z)return null;let $=V1(B4,"gat1",W);if(!$)return null;let J=await this.store.findClient($.c);if(!J||!J.redirectUris.some((G)=>M4(G,$.r)))return null;let Q=String(Z.id),Y=x4(E0,"gcs1",{t:u0(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:w1,revocation_endpoint_auth_methods_supported:w1,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 N4(`mcp-oauth-register:${s0(new L4(W,{},"api",`${this.base}/register`))}`,Z.rateLimit??a6);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 F4(W,D4))}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=ZW(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(!w1.includes(Y))throw new L("invalid_client_metadata",`token_endpoint_auth_method must be one of ${w1.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 z=l0(J.client_name,100,"client_name"),X=l0(J.client_uri,512,"client_uri");if(X!==null&&!WW(X))throw new L("invalid_client_metadata","client_uri must be an https URL.");let B=Y==="none"?null:`${o6}${l(32).toString("base64url")}`,j={clientId:`${i6}${l(16).toString("base64url")}`,clientSecretHash:B?y(B):null,tokenEndpointAuthMethod:Y,redirectUris:[...Q],clientName:z,clientUri:X,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,...z?{client_name:z}:{},...X?{client_uri:X}:{}},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 w(`The parameter ${H} was sent more than once.`);let $=Z.get("client_id"),J=$?await this.store.findClient($):null;if(!J)return w("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)=>M4(H,Q)))return w("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 z=Z.get("resource");if(z!==null&&!n0(z,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 X=this.scopeNames(),B=Z.get("scope"),j=X;if(B!==null&&B.trim()!==""){if(j=[...new Set(B.split(" ").filter((H)=>X.includes(H)))],j.length===0)return K("invalid_scope","None of the requested scopes exist here.")}let x=x4(B4,"gat1",{c:J.clientId,r:Q,s:j,cc:G,st:Y,n:l(16).toString("base64url"),exp:Date.now()+s6}),O=this.options.consentPath??`${this.base}/consent`;return j4(`${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??q(v1).config.signInPath;return j4(`${Y}${Y.includes("?")?"&":"?"}redirect=${encodeURIComponent(Q)}`,302)}let J=await this.consent(Z,$);if(!J)return w("This authorization request has expired or is not valid. Start again from the application.");return new Response(A0(J,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:P1})}async decide(W){let Z=W.headers.get("origin");if(!(Z!==null?Z===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return w("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 w("The decision must be a form post.");let J;try{J=new URLSearchParams(await F4(W,D4))}catch{return w("The decision is too large.")}let Q=J.get("request"),Y=V1(B4,"gat1",Q),K=V1(E0,"gcs1",J.get("csrf")),G=await this.sessionUser(W);if(!Y||!K||!G||K.t!==u0(Q)||K.u!==String(G.id))return w("This authorization request has expired or is not valid. Start again from the application.",403);let z=await this.store.findClient(Y.c);if(!z||!z.redirectUris.some((B)=>M4(B,Y.r)))return w("The application is not registered with this server.");if(!await this.store.use(`ticket:${Y.n}`,Y.exp))return w("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 X=`${g0}${l(32).toString("base64url")}`;return await this.store.saveCode({hash:y(X),clientId:z.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()+m0}),this.redirectBack(Y.r,Y.st,{code:X},303)}async token(W){let Z=await d0(W),$=await this.authenticateClient(W,Z),J=await N4(`mcp-oauth-token:${$.clientId}`,t6);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&&!n0(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(g0)?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+m0))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)||!p0(e6(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,z=Z.get("scope");if(z!==null&&z.trim()!==""){let X=[...new Set(z.split(" ").filter(Boolean))];if(X.some((B)=>!K.scopes.includes(B)))throw new L("invalid_scope","A refresh can only narrow the scopes that were granted.");G=X}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=`${z4}${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 d0(W),$=await this.authenticateClient(W,Z),J=Z.get("token")??"";if(J.startsWith(z4)||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 z=i0(K.slice(0,G));if(z===null)throw n(!0);if(J!==null&&J!==z)throw n(!0);if(J=z,Q=i0(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||!p0(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),j4(Q.href,J)}async sessionUser(W){let Z=new L4(W,{},"api",this.base).cookies;return await o0(q(v1),{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 r6={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function c0(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 U4("sha256").update(W).digest("hex")}function u0(W){return U4("sha256").update(W).digest("base64url")}function e6(W){return U4("sha256").update(W).digest("base64url")}function p0(W,Z){let $=Buffer.from(W),J=Buffer.from(Z);return $.length===J.length&&n6($,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 j4(W,Z){return new Response(null,{status:Z,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function w(W,Z=400){return new Response(h0(W),{status:Z,headers:P1})}function n(W){return new L("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function F4(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 d0(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 F4(W,D4))}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 l0(W,Z,$){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>Z||$W(W))throw new L("invalid_client_metadata",`${$} must be text of at most ${Z} characters.`);return W}function WW(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function t0(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function ZW(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:"&&t0(Z))return null;return"must be https, or http on a loopback address"}function M4(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:"&&t0($)&&$.hostname===J.hostname&&$.pathname===J.pathname&&$.search===J.search&&!J.hash&&!J.username&&!J.password}function n0(W,Z){return W===Z||W===`${Z}/`}function $W(W){for(let Z=0;Z<W.length;Z++){let $=W.charCodeAt(Z);if($<32||$===127)return!0}return!1}function i0(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class r0{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 D1 extends k{application;previous;dispatched=[];static install(W){let Z=W.resolved(k)?W.make(k):void 0;if(Z instanceof D1)return Z;let $=new D1(W,Z);return W.instance(k,$),$}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(k,this.previous);return}this.application.forget(k)}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 ${O4(J.length)}: ${q1(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 ${O4(Z)}, but it was dispatched ${O4(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"}: ${q1(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}: ${q1($)}.`;return`Dispatched: ${q1(this.dispatched)}.`}}function x1(W){return W.name}function O4(W){return`${W} ${W===1?"time":"times"}`}function q1(W){return W.map(JW).join(", ")}function JW(W){let Z=x1(W.event.constructor),$=W.args??Object.values({...W.event});return`${Z}(${$.map(QW).join(", ")})`}function QW(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class y1{static name="unset";static afterCommit=!1;static dispatch(...W){e0(this),q(k).dispatch(new this(...W),W)}static dispatchAndWait(...W){return e0(this),q(k).dispatchAndWait(new this(...W),W)}static fake(){return D1.install(YW())}}function YW(){try{return q()}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 e0(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 $6 extends y1{constructor(){super();Object.defineProperty(this,S4,{value:!0,enumerable:!1})}broadcastAs(){return this.constructor.name}broadcastWith(){return}channel(W,...Z){return{topic:W6(W,Z[0]??{}),pattern:W}}}var KW={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 GW(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={...KW,...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 C("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 C(GW(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/",Q6="https://stream.x.com/1.1/",W1="https://ads-api.x.com/12/",Z1="https://ads-api-sandbox.twitter.com/12/";class R4{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 _4 extends R4{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=R4;class F 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 f4 extends F{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 k4 extends F{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 m;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(m||(m={}));var F1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(F1||(F1={}));class A1 extends Error{constructor(){super(...arguments);this.error=!0}}class H1 extends A1{constructor(W,Z){super(W);this.type=F1.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 A1{constructor(W,Z){super(W);this.type=F1.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 A1{constructor(W,Z){super(W);if(this.type=F1.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:o.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(o.AuthTimestampInvalid,o.AuthenticationFail,o.BadAuthenticationData,o.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var o;(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"})(o||(o={}));var Y6;(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"})(Y6||(Y6={}));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 t4 from"fs";var U={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function C4(W){let Z={value:void 0,promise:W().then(($)=>{return Z.value=$,$})};return Z}function h1(W){if(Array.isArray(W))return W;return[W]}function G6(W){for(let Z of Object.keys(W))if(W[Z]===void 0)delete W[Z]}function g1(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 K6=new Set;function b4(W){if(typeof console>"u"||!console.warn||!U.deprecationWarnings)return;let Z=`${W.instance}-${W.method}-${W.problem}`;if(K6.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."),K6.add(Z)}import{EventEmitter as MW}from"events";import{request as zW}from"https";import*as S from"zlib";import{EventEmitter as XW}from"events";class z6{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=zW({...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 XW,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 E1($,{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=z6;import{EventEmitter as BW}from"events";class X6 extends BW{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 B6=X6;import{EventEmitter as jW}from"events";class m1 extends jW{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(s.ParsedData,Y);continue}}catch(Y){this.emit(s.ParseError,Y)}}J++}this.currentMessage=W.slice($,Z)}reset(){this.currentMessage=""}}var s;(function(W){W.ParsedData="parsed data",W.ParseError="parse error"})(s||(s={}));var j6=[5,15,30,60,90,120,180,300,600,900],LW=(W)=>W>j6.length?901000:j6[W-1]*1000;class M6 extends MW{constructor(W,Z){super();if(this.requestData=W,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=LW,this.parser=new m1,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(M.ConnectionError,Z),this.emit(M.Error,{type:M.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(M.DataKeepAlive);this.parser.push(Z.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let W=this.requestData.payloadIsError;this.parser.on(s.ParsedData,(Z)=>{if(W&&W(Z))this.emit(M.DataError,Z),this.emit(M.Error,{type:M.DataError,error:Z,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(M.Data,Z)}),this.parser.on(s.ParseError,(Z)=>{this.emit(M.TweetParseError,Z),this.emit(M.Error,{type:M.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(M.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(M.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let Z=await new _1(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(M.ConnectError,0),this.emit(M.Error,{type:M.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 _1(this.requestData).makeRequestAndResolveWhenReady();this.req=Z,this.res=$,this.originalResponse=J,this.emit(W?M.Connected:M.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(W=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(M.ConnectionClosed);return}if(W>=this.autoReconnectRetries){this.emit(M.ReconnectLimitExceeded),this.emit(M.ConnectionClosed);return}try{this.emit(M.ReconnectAttempt,W),await this.reconnect()}catch(Z){this.emit(M.ReconnectError,W),this.emit(M.Error,{type:M.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 B6(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 E1=M6;function L6(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 N6(W,Z,$,J){let Q;if(J instanceof H1||J instanceof U1)Q=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:J});else if(J instanceof O1)Q=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:J});if(Q&&Q instanceof S1)return Q.value;return Promise.reject(J)}import*as F6 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 F6.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=D6(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 $=D6(DW(x6(Z,x6(W.data,xW(W.url))))),J="";for(let{key:Q,value:Y}of $)if(Y&&Array.isArray(Y)){Y.sort();let K="";Y.forEach((G,z)=>{if(K+=Q+"="+G,z<Y.length)K+="&"}),J+=K}else J+=Q+"="+Y+"&";return J.slice(0,J.length-1)}getBaseUrl(W){return W.split("?")[0]}}var f1=b;function x6(W,Z){return{...W||{},...Z||{}}}function D6(W){return Object.keys(W).sort().map((Z)=>({key:Z,value:W[Z]}))}function NW(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 xW(W){let Z=W.split("?");if(Z.length===1)return{};return NW(Z[1])}function DW(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 T{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,T.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?T.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+": "+h1(K).join("; ")+T.LINE_BREAK}return"--"+this.getBoundary()+T.LINE_BREAK+Q+T.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+T.LINE_BREAK)}}T.LINE_BREAK=`\r
68
- `;T.DEFAULT_CONTENT_TYPE="application/octet-stream";class T4{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}}T4.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=T4;import*as H6 from"crypto";class a{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url(H6.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},z=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 X=new _1({url:K.url,options:G,body:K.body,rateLimitSaver:z?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(L6(this))X=this.applyResponseErrorHooks(W,K,G,X);let B=await X;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},z=new E1(G);if(!K)return z;return z.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 z=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 X=this.getUrlObjectFromUrlString(W),B=X.origin+X.pathname;if(G)R.applyRequestParametersToUrl(X,G);let j=R.formatQueryToString($);if(R.moveUrlQueryParamsIntoObject(X,j),!(J instanceof Buffer))G6(J);let x=Y!==null&&Y!==void 0?Y:R.autoDetectBodyType(X);if(K!==!1){let O=J1.BODY_METHODS.has(Z)&&x==="url";Q=this.writeAuthHeaders({headers:Q,bodyInSignature:O,method:Z,query:j,url:X,body:J})}if(J1.BODY_METHODS.has(Z))z=R.constructBodyParams(J,Q,x)||void 0;return R.addQueryParamsToUrl(X,j),{rawUrl:B,url:X,method:Z,headers:Q,body:z}}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(N6.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=C4(()=>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=C4(()=>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 I4 extends Q1{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class P4 extends Q1{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class c1 extends Q1{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class w4 extends Q1{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class u1 extends Q1{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class V4 extends F{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 v4 extends F{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 q4 extends F{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 y4 extends F{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 A4 extends F{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 h4 extends F{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 g4 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 p1 extends F{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 E4 extends p1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class d1 extends F{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 m4 extends d1{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class c4 extends d1{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class u4 extends d1{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class p4 extends F{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 p4{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class l4 extends p4{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 I4({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 P4({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 c1({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 c1({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 u1({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 u1({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 V4({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 v4({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 A4({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 q4({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 y4({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 h4({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 g4({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 p1({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 E4({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 d4({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 m4({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 c4({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 w4({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 l4({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 u4({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=h1(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 l1(this);return W.setPrefix(Q6),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 n4(W){let Z=await i4(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 i4(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 U6(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 O6(W,Z,$){if(typeof $==="string")return $;else if(typeof W==="string"&&!Z)return FW(W);else if(typeof Z==="string")return HW(Z);throw Error("You must specify type if file is a file handle or Buffer.")}function FW(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 b4({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 HW(W){if(b4({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 S6(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 o4(W){return new Promise((Z)=>setTimeout(Z,W*1000))}async function s4(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,z)=>{if(G)K(G);Y(z)})});else Q=(await W.read(J,0,Z,$)).bytesRead;return[J,Q]}var a4="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 n4(W),...Z};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,Z={}){let $={tweet_mode:"extended",image:await n4(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:z}=await this.getUploadMediaRequirements(W,Z);try{let X=await this.post(a4,{command:"INIT",total_bytes:G,media_type:z,media_category:K,additional_owners:Z.additionalOwners,shared:Z.shared?!0:void 0},{prefix:A});await this.mediaChunkedUpload(Y,Q,X.media_id_string,Z.maxConcurrentUploads);let B=await this.post(a4,{command:"FINALIZE",media_id:X.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")t4.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 o4($.check_after_secs);else await o4(5)}}async getUploadMediaRequirements(W,{mimeType:Z,type:$,target:J,longVideo:Q}={}){let Y;try{Y=await i4(W);let K=O6(W,$,Z),G;if(K===D.Mp4&&(!Z&&!$&&J!=="dm"||Q))G="amplify_video";else G=S6(K,J!==null&&J!==void 0?J:"tweet");return{fileHandle:Y,mediaCategory:G,fileSize:await U6(Y),mimeType:K}}catch(K){if(typeof W==="number")t4.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,z=0;[K,G]=await s4(W,Z,z,Y),z+=G;let X=new Set;while(G){let B=K.slice(0,G);if(B.length){let j=this.post(a4,{command:"APPEND",media_id:$,segment_index:Q,media:B},{prefix:A});X.add(j),j.then(()=>{X.delete(j)}),Q++}if(X.size>=J)await Promise.race(X);[K,G]=await s4(W,Z,z,Y),z+=G}await Promise.all([...X])}}class R6 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 f4({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 k4({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 l1=R6;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 n1 extends _4{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 n1{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 r4 extends n1{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 e4 extends r4{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class W0 extends r4{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class Z0 extends G1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class $0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class J0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class Q0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class Y0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class K0 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 G0 extends K0{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class z0 extends K0{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 X0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class B0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class j0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class M0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class L0 extends h{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class N0 extends h{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class x0 extends h{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class D0 extends h{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class i1 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 i1{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class H0 extends i1{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class U0 extends i1{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class z1 extends _{constructor(){super(...arguments);this._prefix=e}}class o1 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 O0 extends o1{constructor(){super(...arguments);this._endpoint="dm_events"}}class S0 extends o1{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class R0 extends o1{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 e4({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 W0({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 D0({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 x0({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 $0({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 J0({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 Q0({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 Y0({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 j0({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 M0({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 G0({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 X0({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 B0({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 H0({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 U0({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 z0({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 L0({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 N0({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 O0({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 S0({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 R0({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:g1,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:g1,autoConnect:W})}sample10Stream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample10/stream",Z,{payloadIsError:g1,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 m0(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 B4="gmcp_at_",j4="gmcp_rt_",c0="gmcp_ac_",t6="gmcp_c_",r6="gmcp_cs_",M4="gemi.mcp.oauth.ticket.v1",u0="gemi.mcp.oauth.consent.v1",e6=600000,p0=120000,H4=16384,WW={limit:20,window:3600},ZW={limit:60,window:60},I1=["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 e0{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=d0("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=d0("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=O4(W);if(!Z?.startsWith(B4))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?$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(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 $=v1(M4,"gat1",W);if(!$)return null;let J=await this.store.findClient($.c);if(!J||!J.redirectUris.some((G)=>N4(G,$.r)))return null;let Q=String(Z.id),Y=F4(u0,"gcs1",{t:l0(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:I1,revocation_endpoint_auth_methods_supported:I1,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 D4(`mcp-oauth-register:${r0(new x4(W,{},"api",`${this.base}/register`))}`,Z.rateLimit??WW);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 U4(W,H4))}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=YW(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(!I1.includes(Y))throw new L("invalid_client_metadata",`token_endpoint_auth_method must be one of ${I1.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=s0(J.client_name,100,"client_name"),z=s0(J.client_uri,512,"client_uri");if(z!==null&&!QW(z))throw new L("invalid_client_metadata","client_uri must be an https URL.");let B=Y==="none"?null:`${r6}${l(32).toString("base64url")}`,j={clientId:`${t6}${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)=>N4(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&&!o0(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=F4(M4,"gat1",{c:J.clientId,r:Q,s:j,cc:G,st:Y,n:l(16).toString("base64url"),exp:Date.now()+e6}),O=this.options.consentPath??`${this.base}/consent`;return L4(`${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(q1).config.signInPath;return L4(`${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(E0(J,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:V1})}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 U4(W,H4))}catch{return I("The decision is too large.")}let Q=J.get("request"),Y=v1(M4,"gat1",Q),K=v1(u0,"gcs1",J.get("csrf")),G=await this.sessionUser(W);if(!Y||!K||!G||K.t!==l0(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)=>N4(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=`${c0}${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()+p0}),this.redirectBack(Y.r,Y.st,{code:z},303)}async token(W){let Z=await i0(W),$=await this.authenticateClient(W,Z),J=await D4(`mcp-oauth-token:${$.clientId}`,ZW);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&&!o0(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(c0)?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+p0))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)||!n0(JW(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(j4)?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=`${B4}${l(32).toString("base64url")}`,Y=`${j4}${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 i0(W),$=await this.authenticateClient(W,Z),J=Z.get("token")??"";if(J.startsWith(B4)||J.startsWith(j4)){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=a0(K.slice(0,G));if(X===null)throw n(!0);if(J!==null&&J!==X)throw n(!0);if(J=X,Q=a0(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||!n0(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),L4(Q.href,J)}async sessionUser(W){let Z=new x4(W,{},"api",this.base).cookies;return await t0(w(q1),{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 d0(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 S4("sha256").update(W).digest("hex")}function l0(W){return S4("sha256").update(W).digest("base64url")}function JW(W){return S4("sha256").update(W).digest("base64url")}function n0(W,Z){let $=Buffer.from(W),J=Buffer.from(Z);return $.length===J.length&&a6($,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 L4(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(m0(W),{status:Z,headers:V1})}function n(W){return new L("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function U4(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 i0(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 U4(W,H4))}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 s0(W,Z,$){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>Z||KW(W))throw new L("invalid_client_metadata",`${$} must be text of at most ${Z} characters.`);return W}function QW(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function W6(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function YW(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:"&&W6(Z))return null;return"must be https, or http on a loopback address"}function N4(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:"&&W6($)&&$.hostname===J.hostname&&$.pathname===J.pathname&&$.search===J.search&&!J.hash&&!J.username&&!J.password}function o0(W,Z){return W===Z||W===`${Z}/`}function KW(W){for(let Z=0;Z<W.length;Z++){let $=W.charCodeAt(Z);if($<32||$===127)return!0}return!1}function a0(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class Z6{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 $6{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 R4(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:w1(Z.redirectUris),clientName:Z.clientName??null,clientUri:Z.clientUri??null,createdAt:y1(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:w1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:y1(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:w1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:y1(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 R4(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:w1(z.scopes),connectedAt:new Date(y1(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 w1(W){return Array.isArray(W)?W.map(String):[]}function y1(W){return W instanceof Date?W.getTime():new Date(W).getTime()}class D1 extends C{application;previous;dispatched=[];static install(W){let Z=W.resolved(C)?W.make(C):void 0;if(Z instanceof D1)return Z;let $=new D1(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 ${_4(J.length)}: ${A1(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 ${_4(Z)}, but it was dispatched ${_4(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"}: ${A1(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}: ${A1($)}.`;return`Dispatched: ${A1(this.dispatched)}.`}}function x1(W){return W.name}function _4(W){return`${W} ${W===1?"time":"times"}`}function A1(W){return W.map(GW).join(", ")}function GW(W){let Z=x1(W.event.constructor),$=W.args??Object.values({...W.event});return`${Z}(${$.map(zW).join(", ")})`}function zW(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class h1{static name="unset";static afterCommit=!1;static dispatch(...W){J6(this),w(C).dispatch(new this(...W),W)}static dispatchAndWait(...W){return J6(this),w(C).dispatchAndWait(new this(...W),W)}static fake(){return D1.install(XW())}}function XW(){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 J6(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 K6 extends h1{constructor(){super();Object.defineProperty(this,f4,{value:!0,enumerable:!1})}broadcastAs(){return this.constructor.name}broadcastWith(){return}channel(W,...Z){return{topic:Q6(W,Z[0]??{}),pattern:W}}}var BW={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 jW(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class G6 extends i{config;constructor(W={}){super();this.config={...BW,...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(jW(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/",z6="https://stream.x.com/1.1/",W1="https://ads-api.x.com/12/",Z1="https://ads-api-sandbox.twitter.com/12/";class C4{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 k4 extends C4{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=C4;class F 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 b4 extends F{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 T4 extends F{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 m;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(m||(m={}));var F1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(F1||(F1={}));class g1 extends Error{constructor(){super(...arguments);this.error=!0}}class H1 extends g1{constructor(W,Z){super(W);this.type=F1.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 g1{constructor(W,Z){super(W);this.type=F1.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 g1{constructor(W,Z){super(W);if(this.type=F1.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 X6;(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"})(X6||(X6={}));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 W0 from"fs";var U={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function P4(W){let Z={value:void 0,promise:W().then(($)=>{return Z.value=$,$})};return Z}function E1(W){if(Array.isArray(W))return W;return[W]}function j6(W){for(let Z of Object.keys(W))if(W[Z]===void 0)delete W[Z]}function m1(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 B6=new Set;function V4(W){if(typeof console>"u"||!console.warn||!U.deprecationWarnings)return;let Z=`${W.instance}-${W.method}-${W.problem}`;if(B6.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."),B6.add(Z)}import{EventEmitter as DW}from"events";import{request as MW}from"https";import*as S from"zlib";import{EventEmitter as LW}from"events";class M6{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=MW({...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 LW,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 c1($,{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=M6;import{EventEmitter as NW}from"events";class L6 extends NW{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 N6=L6;import{EventEmitter as xW}from"events";class u1 extends xW{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(o.ParsedData,Y);continue}}catch(Y){this.emit(o.ParseError,Y)}}J++}this.currentMessage=W.slice($,Z)}reset(){this.currentMessage=""}}var o;(function(W){W.ParsedData="parsed data",W.ParseError="parse error"})(o||(o={}));var x6=[5,15,30,60,90,120,180,300,600,900],FW=(W)=>W>x6.length?901000:x6[W-1]*1000;class D6 extends DW{constructor(W,Z){super();if(this.requestData=W,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=FW,this.parser=new u1,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(M.ConnectionError,Z),this.emit(M.Error,{type:M.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(M.DataKeepAlive);this.parser.push(Z.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let W=this.requestData.payloadIsError;this.parser.on(o.ParsedData,(Z)=>{if(W&&W(Z))this.emit(M.DataError,Z),this.emit(M.Error,{type:M.DataError,error:Z,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(M.Data,Z)}),this.parser.on(o.ParseError,(Z)=>{this.emit(M.TweetParseError,Z),this.emit(M.Error,{type:M.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(M.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(M.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let Z=await new _1(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(M.ConnectError,0),this.emit(M.Error,{type:M.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 _1(this.requestData).makeRequestAndResolveWhenReady();this.req=Z,this.res=$,this.originalResponse=J,this.emit(W?M.Connected:M.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(W=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(M.ConnectionClosed);return}if(W>=this.autoReconnectRetries){this.emit(M.ReconnectLimitExceeded),this.emit(M.ConnectionClosed);return}try{this.emit(M.ReconnectAttempt,W),await this.reconnect()}catch(Z){this.emit(M.ReconnectError,W),this.emit(M.Error,{type:M.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 N6(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 c1=D6;function F6(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 H6(W,Z,$,J){let Q;if(J instanceof H1||J instanceof U1)Q=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:J});else if(J instanceof O1)Q=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:J});if(Q&&Q instanceof S1)return Q.value;return Promise.reject(J)}import*as S6 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 S6.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=O6(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 $=O6(OW(U6(Z,U6(W.data,UW(W.url))))),J="";for(let{key:Q,value:Y}of $)if(Y&&Array.isArray(Y)){Y.sort();let K="";Y.forEach((G,X)=>{if(K+=Q+"="+G,X<Y.length)K+="&"}),J+=K}else J+=Q+"="+Y+"&";return J.slice(0,J.length-1)}getBaseUrl(W){return W.split("?")[0]}}var f1=b;function U6(W,Z){return{...W||{},...Z||{}}}function O6(W){return Object.keys(W).sort().map((Z)=>({key:Z,value:W[Z]}))}function HW(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 UW(W){let Z=W.split("?");if(Z.length===1)return{};return HW(Z[1])}function OW(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 T{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,T.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?T.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+": "+E1(K).join("; ")+T.LINE_BREAK}return"--"+this.getBoundary()+T.LINE_BREAK+Q+T.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+T.LINE_BREAK)}}T.LINE_BREAK=`\r
68
+ `;T.DEFAULT_CONTENT_TYPE="application/octet-stream";class I4{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}}I4.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=I4;import*as R6 from"crypto";class a{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url(R6.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(F6(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 c1(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))j6(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(H6.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=P4(()=>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=P4(()=>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 v4 extends Q1{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class q4 extends Q1{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class p1 extends Q1{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class w4 extends Q1{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class d1 extends Q1{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class y4 extends F{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 A4 extends F{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 h4 extends F{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 g4 extends F{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 E4 extends F{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 m4 extends F{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 c4 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 l1 extends F{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 u4 extends l1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class n1 extends F{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 p4 extends n1{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class d4 extends n1{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class l4 extends n1{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class n4 extends F{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 n4{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class s4 extends n4{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 v4({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 q4({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 p1({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 p1({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 d1({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 d1({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 y4({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 A4({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 E4({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 h4({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 g4({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 m4({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 c4({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 l1({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 u4({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 i4({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 p4({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 d4({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 w4({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 s4({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 l4({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=E1(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 i1(this);return W.setPrefix(z6),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 o4(W){let Z=await a4(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 a4(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 _6(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 f6(W,Z,$){if(typeof $==="string")return $;else if(typeof W==="string"&&!Z)return SW(W);else if(typeof Z==="string")return RW(Z);throw Error("You must specify type if file is a file handle or Buffer.")}function SW(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 V4({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 RW(W){if(V4({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 C6(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 t4(W){return new Promise((Z)=>setTimeout(Z,W*1000))}async function r4(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 e4="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 o4(W),...Z};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,Z={}){let $={tweet_mode:"extended",image:await o4(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(e4,{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(e4,{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")W0.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 t4($.check_after_secs);else await t4(5)}}async getUploadMediaRequirements(W,{mimeType:Z,type:$,target:J,longVideo:Q}={}){let Y;try{Y=await a4(W);let K=f6(W,$,Z),G;if(K===D.Mp4&&(!Z&&!$&&J!=="dm"||Q))G="amplify_video";else G=C6(K,J!==null&&J!==void 0?J:"tweet");return{fileHandle:Y,mediaCategory:G,fileSize:await _6(Y),mimeType:K}}catch(K){if(typeof W==="number")W0.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 r4(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(e4,{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 r4(W,Z,X,Y),X+=G}await Promise.all([...z])}}class k6 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 b4({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 T4({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 i1=k6;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 s1 extends k4{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 s1{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 Z0 extends s1{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 $0 extends Z0{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class J0 extends Z0{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class Q0 extends G1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class Y0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class K0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class G0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class z0 extends G1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class X0 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 B0 extends X0{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class j0 extends X0{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 M0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class L0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class N0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class x0 extends h{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class D0 extends h{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class F0 extends h{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class H0 extends h{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class U0 extends h{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class o1 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 O0 extends o1{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class S0 extends o1{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class R0 extends o1{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class z1 extends _{constructor(){super(...arguments);this._prefix=e}}class a1 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 _0 extends a1{constructor(){super(...arguments);this._endpoint="dm_events"}}class f0 extends a1{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class C0 extends a1{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 $0({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 J0({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 U0({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 H0({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 Y0({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 K0({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 G0({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 Q0({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 z0({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 N0({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 x0({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 B0({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 M0({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 L0({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 O0({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 S0({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 R0({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 j0({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 D0({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 F0({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 _0({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 f0({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 C0({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:m1,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:m1,autoConnect:W})}sample10Stream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample10/stream",Z,{payloadIsError:m1,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/$),z=new Uint8Array(W);for(let B=0;B<G;B++){let j=B*$,x=Math.min(j+$,W.length),O=z.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,z=($=K.text)!==null&&$!==void 0?$:"";if(G)J.push(await this.reply(z,G,K));else J.push(await this.tweet(z,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 _6 extends B1{constructor(){super(...arguments);this._prefix=e}get readWrite(){return this}}var f6=_6;class k6 extends j1{constructor(){super(...arguments);this._prefix=g}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new f6(this)}}var C6=k6;class k1 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:"",z=Array.isArray(G)?G.join(" "):G,X=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:z};R.addQueryParamsToUrl(X,B);let j={url:X.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 C1 extends k1{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 s1 extends _{constructor(){super(...arguments);this._prefix=W1}}class a1 extends s1{constructor(){super(...arguments);this._prefix=W1}get readOnly(){return this}}class t1 extends _{constructor(){super(...arguments);this._prefix=Z1}}class r1 extends t1{constructor(){super(...arguments);this._prefix=Z1}get readOnly(){return this}}class b6 extends r1{constructor(){super(...arguments);this._prefix=Z1}get readWrite(){return this}}var T6=b6;class I6 extends a1{constructor(){super(...arguments);this._prefix=W1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new T6(this)}}var P6=I6;class _0 extends C1{get v1(){if(this._v1)return this._v1;return this._v1=new l1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new C6(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new P6(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 UW={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class w6 extends i{config;client;constructor(W={}){super();this.config={...UW,...W},this.client=new _0({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 C("missing_code");if(!Z?.codeVerifier)throw new C("invalid_state");let J;try{J=await this.client.loginWithOAuth2({code:$,codeVerifier:Z.codeVerifier,redirectUri:this.redirectUri()})}catch(X){throw console.error("X OAuth error: token exchange failed",X),new C("exchange_failed")}let{data:Q}=await J.client.v2.me({"user.fields":["name","username","entities"]}),{name:Y,email:K,id:G="",username:z}=Q??{};return{name:Y,email:K,username:z,providerId:G}}}var v6=["instagram_business_basic"],v={authorizeUrl:"https://www.instagram.com/oauth/authorize",tokenUrl:"https://api.instagram.com/oauth/access_token",graphUrl:"https://graph.instagram.com"};class I 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 e1(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 Z4(W.tokenUrl??v.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 I("Instagram's code exchange answered without an access token.",200);let Y=J?.permissions;return{accessToken:Q,userId:f0(J?.user_id),permissions:Array.isArray(Y)?Y.map(String):typeof Y==="string"?Y.split(/[\s,]+/).filter(Boolean):null}}async function q6(W){let Z=new URL("/access_token",W.graphUrl??v.graphUrl);return Z.searchParams.set("grant_type","ig_exchange_token"),Z.searchParams.set("client_secret",W.clientSecret),Z.searchParams.set("access_token",W.accessToken),A6(await Z4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function y6(W){let Z=new URL("/refresh_access_token",W.graphUrl??v.graphUrl);return Z.searchParams.set("grant_type","ig_refresh_token"),Z.searchParams.set("access_token",W.accessToken),A6(await Z4(Z.toString(),"token refresh",{method:"GET"}))}async function W4(W){let Z=W.graphApiVersion?`/${W.graphApiVersion.replace(/^\/+|\/+$/g,"")}`:"",$=new URL(`${Z}/me`,W.graphUrl??v.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 Z4($.toString(),"profile request",{method:"GET"}),Q=Array.isArray(J.data)?J.data[0]:J,Y=f0(Q?.user_id);if(!Y)throw new I("Instagram's /me answered without a user_id.",200);let K={user_id:Y},G=f0(Q?.id);if(G)K.id=G;for(let z of["username","name","account_type","profile_picture_url"]){let X=Q?.[z];if(typeof X==="string"&&X!=="")K[z]=X}return K}function A6(W){if(typeof W.access_token!=="string"||W.access_token==="")throw new I("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 Z4(W,Z,$){let J;try{J=await fetch(W,{...$,redirect:"error"})}catch(Y){throw new I(`Instagram's ${Z} failed to reach Instagram.`,void 0,void 0,void 0,{cause:Y})}let Q=OW(await J.text().catch(()=>""));if(!J.ok){let Y=Q.error??{},K=V6(Q.error_type)??V6(Y.type),G=Number(Q.code??Y.code);throw new I(`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 OW(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 f0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function V6(W){return typeof W==="string"&&W!==""?W:void 0}class h6 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:v6,redirectPath:"/auth/oauth/instagram/callback",authorizationParams:{},...W}}redirectUri(){return`${r()??""}${this.config.redirectPath}`}getRedirectUrl(W,Z){let $=new URL(this.config.authorizeUrl??v.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 C("missing_code");let $;try{let J=await e1({code:Z,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri(),tokenUrl:this.config.tokenUrl});$=await W4({accessToken:J.accessToken,graphUrl:this.config.graphUrl,graphApiVersion:this.config.graphApiVersion,fields:["user_id","username","name"]})}catch(J){if(J instanceof I)throw console.error(`Instagram OAuth error: ${J.message}`),new C("exchange_failed");throw J}return{providerId:$.user_id,username:$.username,name:$.name||$.username}}}import{createHmac as SW,timingSafeEqual as RW}from"crypto";class P extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function _W(W,Z,$={}){if(!Z)throw Error("parseMetaSignedRequest needs the app secret.");if(typeof W!=="string")throw new P("malformed","No signed_request was given.");let J=W.indexOf(".");if(J<=0||J===W.length-1||W.indexOf(".",J+1)!==-1)throw new P("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 P("malformed","A signed_request is base64url.");let K=SW("sha256",Z).update(Y).digest(),G=Buffer.from(Q,"base64url");if(G.length!==K.length||!RW(G,K))throw new P("bad_signature","The signed_request's signature does not match the app secret.");let z;try{let x=Buffer.from(Y,"base64url").toString("utf8").replace(/("user_id"\s*:\s*)(-?\d+)(?=\s*[,}])/g,'$1"$2"');z=JSON.parse(x)}catch{throw new P("malformed","The signed_request's payload is not JSON.")}if(!z||typeof z!=="object")throw new P("malformed","The signed_request's payload is not an object.");if(String(z.algorithm??"").toUpperCase()!=="HMAC-SHA256")throw new P("unsupported_algorithm","Only HMAC-SHA256 signed_requests are accepted.");let X=Math.floor(($.now??Date.now())/1000),B=Number(z.expires);if(Number.isFinite(B)&&B>0&&B<X)throw new P("expired","The signed_request has expired.");let j=z.user_id;if((typeof j!=="string"||j==="")&&typeof j!=="number")throw new P("missing_user","The signed_request names no user.");return{...z,algorithm:String(z.algorithm),user_id:String(j)}}var fW=86400000;class g6 extends k0{instagram;constructor(W={}){let Z={authorizeUrl:W.authorizeUrl??v.authorizeUrl,tokenUrl:W.tokenUrl??v.tokenUrl,graphUrl:W.graphUrl??v.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:kW,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<fW){if($.reason==="rejected")throw new b1("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let J=await $4("refresh_failed",()=>y6({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 $4("exchange_failed",()=>e1({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await $4("exchange_failed",()=>q6({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),J=await $4("exchange_failed",()=>W4({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 kW(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 $4(W,Z){try{return await Z()}catch($){if($ instanceof I)throw new b1(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}class C0{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 CW(W={}){return new C0(W)}class E6 extends b0{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{e5 as viewRouteConfigDefaults,G8 as translationConfigDefaults,J4 as toRangeHeaderValue,gW as subjectFor,aW as sniffContentType,lZ as scheduleConfigDefaults,K4 as resolveRange,b8 as redisConfigDefaults,f8 as rateLimiterConfigDefaults,UZ as queueConfigDefaults,_W as parseMetaSignedRequest,M1 as parseContentRange,IW as mintSessionToken,GZ as middlewareConfigDefaults,vZ as mcpCallOf,jZ as mailConfigDefaults,O8 as logConfigDefaults,TW as isSessionToken,g5 as isFinalRunStatus,Z6 as isBroadcastEvent,tW as isActiveContentType,AW as inRollout,o5 as imageConfigDefaults,oW as filesystemConfigDefaults,j8 as featuresConfigDefaults,iZ as eventConfigDefaults,hW as evaluateFeature,H5 as encodeCursor,ZZ as documentScriptCspHash,tZ as discoverWorkflows,W8 as discoverListeners,aZ as discoverJobs,rZ as discoverCronJobs,eZ as discoverCommands,K8 as defineTranslationConfig,dZ as defineScheduleConfig,y5 as defineRunsConfig,t5 as defineRouteConfig,C8 as defineRedisConfig,_8 as defineRateLimiterConfig,HZ as defineQueueConfig,KZ as defineMiddlewareConfig,BZ as defineMailConfig,U8 as defineLogConfig,i5 as defineImageConfig,iW as defineFilesystemConfig,B8 as defineFeaturesConfig,CW as defineFeature,nZ as defineEventConfig,p6 as defineEncryptionConfig,mZ as defineCommandConfig,uZ as defineCommand,D5 as defineChangeFeedConfig,eW as defineCacheConfig,b5 as defineBroadcastConfig,VW as defineAuthConfig,U5 as decodeCursor,DZ as createWorkflowTableStatements,c5 as createRunsTableStatements,cZ as commandConfigDefaults,F5 as changeFeedConfigDefaults,W5 as cacheConfigDefaults,yW as bucketOf,qW as bucketKey,T5 as broadcastConfigDefaults,H4 as bearerToken,vW as authConfigDefaults,Q4 as assertDeletablePrefix,r5 as apiRouteConfigDefaults,w6 as XOAuthProvider,bZ as WorkflowRuntime,kZ as WorkflowCancelledError,sZ as Workflow,_Z as WaitTimeoutError,QZ as ViewRouteDispatcher,pW as UndeclaredFeatureError,Q5 as TaggedCache,fZ as StepTimeoutError,RZ as StepFailedError,CZ as Step,E6 as StaticFeatureFlagSource,n5 as Sharp,hZ as Scheduler,z8 as ScheduleServiceProvider,JZ as STATIC_NAVIGATION_CSP_HASH,C5 as SOCKET_ID_HEADER,bW as SESSION_TOKEN_PREFIX,P0 as S3Driver,P8 as RunsServiceProvider,u5 as RunNotFoundError,d5 as RunManager,p5 as RunFailure,I8 as RouteServiceProvider,XZ as ResendDriver,T8 as RedisServiceProvider,y0 as RedisRateLimiter,I1 as RedisManager,$5 as RedisCacheStore,P5 as RedisBroadcastDriver,k8 as RateLimiterServiceProvider,G4 as RateLimiterDriver,PW as RateLimiter,t as RangeNotSatisfiableError,Z8 as QueueServiceProvider,TZ as QueueManager,x5 as ProviderConnection,v5 as PendingBroadcast,h5 as OPEN_RUN_STATUSES,L5 as OAuthReconnectRequiredError,i as OAuthProvider,k0 as OAuthConnectionProvider,b1 as OAuthConnectionError,C as OAuthCallbackError,R8 as MiddlewareServiceProvider,a5 as MiddlewareRegistry,P as MetaSignedRequestError,OZ as MemoryWorkflowStore,E5 as MemoryRunStore,SZ as MemoryQueueDriver,r0 as MemoryMcpOAuthStore,NZ as MemoryLockStore,j5 as MemoryConnectionStore,S5 as MemoryChangeFeedDriver,Z5 as MemoryCacheStore,I5 as MemoryBroadcastDriver,wZ as McpToolError,qZ as McpRegistry,a0 as McpOAuthServer,AZ as McpHttpServer,VZ as McpCallRefusedError,yZ as McpApiKeyResolver,L8 as MailServiceProvider,MZ as MailManager,S8 as LogServiceProvider,rW as LogManager,G5 as LockManager,Y5 as LockLostError,oZ as Listener,H8 as KernelIdServiceProvider,WZ as KernelId,IZ as Job,k5 as InvalidChannelError,h6 as InstagramOAuthProvider,g6 as InstagramConnectionProvider,I as InstagramApiError,wW as InMemoryRateLimiter,F8 as ImageServiceProvider,l5 as ImageOptimizationDriver,s5 as ImageManager,$Z as ISLAND_LOADER_CSP_HASH,K5 as HeldLock,J6 as GoogleOAuthProvider,D8 as FilesystemServiceProvider,sW as FilesystemManager,nW as FileSystemDriver,L1 as FileStorageDriver,d as FileNotFoundError,M8 as FeaturesServiceProvider,uW as FeatureSourceReadOnlyError,dW as FeatureScope,EW as FeatureReloadError,cW as FeatureModelMissingError,lW as FeatureManager,mW as FeatureFlagStore,b0 as FeatureFlagSource,C0 as Feature,A5 as FINAL_RUN_STATUSES,x8 as EventServiceProvider,k as EventManager,y1 as Event,N8 as EncryptionServiceProvider,X5 as EncryptionKeyError,z5 as Encrypter,zZ as EmailDriver,B5 as DecryptionError,xZ as DatabaseWorkflowStore,m5 as DatabaseRunStore,FZ as DatabaseQueueDriver,LZ as DatabaseLockStore,X8 as DatabaseFeatureFlagSource,M5 as DatabaseConnectionStore,O5 as DatabaseChangeFeedDriver,PZ as DEFAULT_MCP_SCOPE,pZ as CronJob,N5 as ConnectionManager,w8 as CommandRegistry,gZ as CommandFailed,EZ as Command,f5 as ChangeFeedSubscription,Q8 as ChangeFeedServiceProvider,_5 as ChangeFeedManager,R5 as ChangeFeedFullError,J8 as CacheServiceProvider,J5 as CacheManager,P1 as CONSENT_PAGE_HEADERS,$8 as BroadcastServiceProvider,q5 as BroadcastScope,w5 as BroadcastPayloadTooLargeError,V5 as BroadcastManager,$6 as BroadcastEvent,V0 as AzureBlobDriver,Y8 as AuthServiceProvider,v1 as AuthManager,YZ 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 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 b6 extends B1{constructor(){super(...arguments);this._prefix=e}get readWrite(){return this}}var T6=b6;class P6 extends j1{constructor(){super(...arguments);this._prefix=g}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new T6(this)}}var V6=P6;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 t1 extends _{constructor(){super(...arguments);this._prefix=W1}}class r1 extends t1{constructor(){super(...arguments);this._prefix=W1}get readOnly(){return this}}class e1 extends _{constructor(){super(...arguments);this._prefix=Z1}}class W4 extends e1{constructor(){super(...arguments);this._prefix=Z1}get readOnly(){return this}}class I6 extends W4{constructor(){super(...arguments);this._prefix=Z1}get readWrite(){return this}}var v6=I6;class q6 extends r1{constructor(){super(...arguments);this._prefix=W1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new v6(this)}}var w6=q6;class k0 extends k1{get v1(){if(this._v1)return this._v1;return this._v1=new i1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new V6(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new w6(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 _W={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class y6 extends i{config;client;constructor(W={}){super();this.config={..._W,...W},this.client=new k0({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 h6=["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 Z4(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 J4(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:b0(J?.user_id),permissions:Array.isArray(Y)?Y.map(String):typeof Y==="string"?Y.split(/[\s,]+/).filter(Boolean):null}}async function g6(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),m6(await J4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function E6(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),m6(await J4(Z.toString(),"token refresh",{method:"GET"}))}async function $4(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 J4($.toString(),"profile request",{method:"GET"}),Q=Array.isArray(J.data)?J.data[0]:J,Y=b0(Q?.user_id);if(!Y)throw new P("Instagram's /me answered without a user_id.",200);let K={user_id:Y},G=b0(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 m6(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 J4(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=fW(await J.text().catch(()=>""));if(!J.ok){let Y=Q.error??{},K=A6(Q.error_type)??A6(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 fW(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 b0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function A6(W){return typeof W==="string"&&W!==""?W:void 0}class c6 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:h6,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 Z4({code:Z,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri(),tokenUrl:this.config.tokenUrl});$=await $4({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 CW,timingSafeEqual as kW}from"crypto";class V extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function bW(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=CW("sha256",Z).update(Y).digest(),G=Buffer.from(Q,"base64url");if(G.length!==K.length||!kW(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 TW=86400000;class u6 extends T0{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:PW,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<TW){if($.reason==="rejected")throw new b1("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let J=await Q4("refresh_failed",()=>E6({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 Q4("exchange_failed",()=>Z4({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await Q4("exchange_failed",()=>g6({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),J=await Q4("exchange_failed",()=>$4({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 PW(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 Q4(W,Z){try{return await Z()}catch($){if($ instanceof P)throw new b1(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}class P0{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 VW(W={}){return new P0(W)}class p6 extends V0{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{JZ as viewRouteConfigDefaults,j8 as translationConfigDefaults,Y4 as toRangeHeaderValue,uW as subjectFor,W5 as sniffContentType,oZ as scheduleConfigDefaults,z4 as resolveRange,I8 as redisConfigDefaults,T8 as rateLimiterConfigDefaults,_Z as queueConfigDefaults,bW as parseMetaSignedRequest,M1 as parseContentRange,qW as mintSessionToken,jZ as middlewareConfigDefaults,hZ as mcpCallOf,xZ as mailConfigDefaults,f8 as logConfigDefaults,vW as isSessionToken,u5 as isFinalRunStatus,Y6 as isBroadcastEvent,Z5 as isActiveContentType,mW as inRollout,r5 as imageConfigDefaults,rW as filesystemConfigDefaults,x8 as featuresConfigDefaults,tZ as eventConfigDefaults,cW as evaluateFeature,R5 as encodeCursor,YZ as documentScriptCspHash,Z8 as discoverWorkflows,Q8 as discoverListeners,W8 as discoverJobs,$8 as discoverCronJobs,J8 as discoverCommands,B8 as defineTranslationConfig,sZ as defineScheduleConfig,E5 as defineRunsConfig,ZZ as defineRouteConfig,V8 as defineRedisConfig,b8 as defineRateLimiterConfig,RZ as defineQueueConfig,BZ as defineMiddlewareConfig,NZ as defineMailConfig,_8 as defineLogConfig,t5 as defineImageConfig,tW as defineFilesystemConfig,N8 as defineFeaturesConfig,VW as defineFeature,aZ as defineEventConfig,i6 as defineEncryptionConfig,dZ as defineCommandConfig,nZ as defineCommand,O5 as defineChangeFeedConfig,J5 as defineCacheConfig,I5 as defineBroadcastConfig,AW as defineAuthConfig,_5 as decodeCursor,OZ as createWorkflowTableStatements,l5 as createRunsTableStatements,lZ as commandConfigDefaults,S5 as changeFeedConfigDefaults,Q5 as cacheConfigDefaults,EW as bucketOf,gW as bucketKey,v5 as broadcastConfigDefaults,O4 as bearerToken,hW as authConfigDefaults,K4 as assertDeletablePrefix,$Z as apiRouteConfigDefaults,y6 as XOAuthProvider,IZ as WorkflowRuntime,PZ as WorkflowCancelledError,eZ as Workflow,bZ as WaitTimeoutError,zZ as ViewRouteDispatcher,iW as UndeclaredFeatureError,z5 as TaggedCache,TZ as StepTimeoutError,kZ as StepFailedError,VZ as Step,p6 as StaticFeatureFlagSource,a5 as Sharp,cZ as Scheduler,M8 as ScheduleServiceProvider,GZ as STATIC_NAVIGATION_CSP_HASH,V5 as SOCKET_ID_HEADER,IW as SESSION_TOKEN_PREFIX,q0 as S3Driver,w8 as RunsServiceProvider,n5 as RunNotFoundError,s5 as RunManager,i5 as RunFailure,q8 as RouteServiceProvider,LZ as ResendDriver,v8 as RedisServiceProvider,g0 as RedisRateLimiter,P1 as RedisManager,K5 as RedisCacheStore,w5 as RedisBroadcastDriver,P8 as RateLimiterServiceProvider,X4 as RateLimiterDriver,wW as RateLimiter,t as RangeNotSatisfiableError,Y8 as QueueServiceProvider,vZ as QueueManager,U5 as ProviderConnection,$6 as PrismaMcpOAuthStore,h5 as PendingBroadcast,c5 as OPEN_RUN_STATUSES,F5 as OAuthReconnectRequiredError,i as OAuthProvider,T0 as OAuthConnectionProvider,b1 as OAuthConnectionError,k as OAuthCallbackError,k8 as MiddlewareServiceProvider,WZ as MiddlewareRegistry,V as MetaSignedRequestError,fZ as MemoryWorkflowStore,p5 as MemoryRunStore,CZ as MemoryQueueDriver,Z6 as MemoryMcpOAuthStore,HZ as MemoryLockStore,x5 as MemoryConnectionStore,C5 as MemoryChangeFeedDriver,Y5 as MemoryCacheStore,q5 as MemoryBroadcastDriver,yZ as McpToolError,gZ as McpRegistry,e0 as McpOAuthServer,mZ as McpHttpServer,AZ as McpCallRefusedError,EZ as McpApiKeyResolver,F8 as MailServiceProvider,DZ as MailManager,C8 as LogServiceProvider,$5 as LogManager,j5 as LockManager,X5 as LockLostError,rZ as Listener,R8 as KernelIdServiceProvider,QZ as KernelId,qZ as Job,P5 as InvalidChannelError,c6 as InstagramOAuthProvider,u6 as InstagramConnectionProvider,P as InstagramApiError,yW as InMemoryRateLimiter,S8 as ImageServiceProvider,o5 as ImageOptimizationDriver,e5 as ImageManager,KZ as ISLAND_LOADER_CSP_HASH,B5 as HeldLock,G6 as GoogleOAuthProvider,O8 as FilesystemServiceProvider,eW as FilesystemManager,aW as FileSystemDriver,L1 as FileStorageDriver,d as FileNotFoundError,D8 as FeaturesServiceProvider,nW as FeatureSourceReadOnlyError,sW as FeatureScope,pW as FeatureReloadError,lW as FeatureModelMissingError,oW as FeatureManager,dW as FeatureFlagStore,V0 as FeatureFlagSource,P0 as Feature,m5 as FINAL_RUN_STATUSES,U8 as EventServiceProvider,C as EventManager,h1 as Event,H8 as EncryptionServiceProvider,L5 as EncryptionKeyError,M5 as Encrypter,MZ as EmailDriver,N5 as DecryptionError,UZ as DatabaseWorkflowStore,d5 as DatabaseRunStore,SZ as DatabaseQueueDriver,FZ as DatabaseLockStore,L8 as DatabaseFeatureFlagSource,D5 as DatabaseConnectionStore,f5 as DatabaseChangeFeedDriver,wZ as DEFAULT_MCP_SCOPE,iZ as CronJob,H5 as ConnectionManager,y8 as CommandRegistry,uZ as CommandFailed,pZ as Command,T5 as ChangeFeedSubscription,z8 as ChangeFeedServiceProvider,b5 as ChangeFeedManager,k5 as ChangeFeedFullError,G8 as CacheServiceProvider,G5 as CacheManager,V1 as CONSENT_PAGE_HEADERS,K8 as BroadcastServiceProvider,g5 as BroadcastScope,y5 as BroadcastPayloadTooLargeError,A5 as BroadcastManager,K6 as BroadcastEvent,y0 as AzureBlobDriver,X8 as AuthServiceProvider,q1 as AuthManager,XZ as ApiRouteDispatcher};
71
71
 
72
- //# debugId=FD92CEB9EF5C905A64756E2164756E21
72
+ //# debugId=256877A64130C21764756E2164756E21