gemi 0.214.0 → 0.216.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 (264) hide show
  1. package/dist/ai/Agent.d.ts +9 -7
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/AgentController.d.ts +6 -5
  4. package/dist/ai/AgentController.d.ts.map +1 -1
  5. package/dist/ai/AgentProvider.d.ts +12 -15
  6. package/dist/ai/AgentProvider.d.ts.map +1 -1
  7. package/dist/ai/FallbackProvider.d.ts +6 -6
  8. package/dist/ai/FallbackProvider.d.ts.map +1 -1
  9. package/dist/ai/generate.d.ts.map +1 -1
  10. package/dist/ai/index.d.ts +1 -1
  11. package/dist/ai/index.d.ts.map +1 -1
  12. package/dist/ai/index.js +21 -21
  13. package/dist/ai/index.js.map +4 -4
  14. package/dist/ai/providers/anthropicStream.d.ts.map +1 -1
  15. package/dist/ai/providers/errors.d.ts +15 -7
  16. package/dist/ai/providers/errors.d.ts.map +1 -1
  17. package/dist/ai/providers/stream.d.ts.map +1 -1
  18. package/dist/ai/redact.d.ts +4 -6
  19. package/dist/ai/redact.d.ts.map +1 -1
  20. package/dist/ai/testing/index.js +2 -2
  21. package/dist/ai/testing/index.js.map +1 -1
  22. package/dist/ai/types.d.ts +23 -0
  23. package/dist/ai/types.d.ts.map +1 -1
  24. package/dist/app/index.js +1 -1
  25. package/dist/auth/config.d.ts +4 -1
  26. package/dist/auth/config.d.ts.map +1 -1
  27. package/dist/auth/connections/ConnectionManager.d.ts +9 -0
  28. package/dist/auth/connections/ConnectionManager.d.ts.map +1 -1
  29. package/dist/auth/connections/FacebookConnectionProvider.d.ts +126 -0
  30. package/dist/auth/connections/FacebookConnectionProvider.d.ts.map +1 -0
  31. package/dist/auth/connections/LinkedInConnectionProvider.d.ts +84 -0
  32. package/dist/auth/connections/LinkedInConnectionProvider.d.ts.map +1 -0
  33. package/dist/auth/connections/OAuthConnectionProvider.d.ts +14 -0
  34. package/dist/auth/connections/OAuthConnectionProvider.d.ts.map +1 -1
  35. package/dist/auth/connections/TikTokConnectionProvider.d.ts +52 -0
  36. package/dist/auth/connections/TikTokConnectionProvider.d.ts.map +1 -0
  37. package/dist/auth/connections/XConnectionProvider.d.ts +39 -0
  38. package/dist/auth/connections/XConnectionProvider.d.ts.map +1 -0
  39. package/dist/auth/connections/YouTubeConnectionProvider.d.ts +48 -0
  40. package/dist/auth/connections/YouTubeConnectionProvider.d.ts.map +1 -0
  41. package/dist/auth/connections/errors.d.ts +1 -1
  42. package/dist/auth/connections/errors.d.ts.map +1 -1
  43. package/dist/auth/connections/social.d.ts +63 -0
  44. package/dist/auth/connections/social.d.ts.map +1 -0
  45. package/dist/bin/ai-client/extract.d.ts +39 -1
  46. package/dist/bin/ai-client/extract.d.ts.map +1 -1
  47. package/dist/bin/ai-client/model.d.ts +7 -3
  48. package/dist/bin/ai-client/model.d.ts.map +1 -1
  49. package/dist/bin/gemi.js +12 -8
  50. package/dist/bin/gemi.js.map +4 -4
  51. package/dist/bin/http-client/extract.d.ts +11 -0
  52. package/dist/bin/http-client/extract.d.ts.map +1 -0
  53. package/dist/bin/http-client/model.d.ts +39 -0
  54. package/dist/bin/http-client/model.d.ts.map +1 -0
  55. package/dist/bun/plugin.js +1 -1
  56. package/dist/bun/preload.js +1 -1
  57. package/dist/{chunk-rdzdbd52.js → chunk-01r2cx3k.js} +4 -4
  58. package/dist/{chunk-rdzdbd52.js.map → chunk-01r2cx3k.js.map} +1 -1
  59. package/dist/{chunk-nc5p41g9.js → chunk-0a796avj.js} +2 -2
  60. package/dist/{chunk-nc5p41g9.js.map → chunk-0a796avj.js.map} +1 -1
  61. package/dist/{chunk-y0b22kf8.js → chunk-0ah98rf4.js} +2 -2
  62. package/dist/{chunk-y0b22kf8.js.map → chunk-0ah98rf4.js.map} +1 -1
  63. package/dist/{chunk-c80xrwep.js → chunk-0z8h6t7k.js} +2 -2
  64. package/dist/{chunk-c80xrwep.js.map → chunk-0z8h6t7k.js.map} +1 -1
  65. package/dist/{chunk-c8sqvhxp.js → chunk-1hs2fxxx.js} +2 -2
  66. package/dist/{chunk-c8sqvhxp.js.map → chunk-1hs2fxxx.js.map} +1 -1
  67. package/dist/{chunk-ge201pk4.js → chunk-1k6dn4ba.js} +1 -1
  68. package/dist/{chunk-gk2k76tn.js → chunk-2crfg0m7.js} +3 -3
  69. package/dist/{chunk-gk2k76tn.js.map → chunk-2crfg0m7.js.map} +1 -1
  70. package/dist/{chunk-153m8mfe.js → chunk-362a52jj.js} +2 -2
  71. package/dist/{chunk-153m8mfe.js.map → chunk-362a52jj.js.map} +1 -1
  72. package/dist/{chunk-gg97wgy0.js → chunk-3pfrqzw8.js} +2 -2
  73. package/dist/{chunk-gg97wgy0.js.map → chunk-3pfrqzw8.js.map} +1 -1
  74. package/dist/{chunk-5w0kzk4m.js → chunk-4zw9gaey.js} +2 -2
  75. package/dist/{chunk-5w0kzk4m.js.map → chunk-4zw9gaey.js.map} +1 -1
  76. package/dist/{chunk-m4nn6ne9.js → chunk-5294qsfq.js} +2 -2
  77. package/dist/{chunk-m4nn6ne9.js.map → chunk-5294qsfq.js.map} +1 -1
  78. package/dist/{chunk-5399t8zm.js → chunk-5cf59esb.js} +2 -2
  79. package/dist/{chunk-5399t8zm.js.map → chunk-5cf59esb.js.map} +1 -1
  80. package/dist/{chunk-768yza4f.js → chunk-5m0vh0rg.js} +2 -2
  81. package/dist/{chunk-768yza4f.js.map → chunk-5m0vh0rg.js.map} +1 -1
  82. package/dist/{chunk-d8nxkc90.js → chunk-5ya7fbfg.js} +2 -2
  83. package/dist/{chunk-d8nxkc90.js.map → chunk-5ya7fbfg.js.map} +1 -1
  84. package/dist/{chunk-tvd39jya.js → chunk-62b7paq5.js} +2 -2
  85. package/dist/{chunk-tvd39jya.js.map → chunk-62b7paq5.js.map} +1 -1
  86. package/dist/{chunk-bvm2w6ha.js → chunk-6669vjve.js} +2 -2
  87. package/dist/{chunk-bvm2w6ha.js.map → chunk-6669vjve.js.map} +1 -1
  88. package/dist/{chunk-fw7sxgse.js → chunk-6cge785m.js} +1 -1
  89. package/dist/{chunk-3egn4pfk.js → chunk-6s48nq83.js} +2 -2
  90. package/dist/{chunk-3egn4pfk.js.map → chunk-6s48nq83.js.map} +1 -1
  91. package/dist/{chunk-9xa5kzaq.js → chunk-7bywa721.js} +2 -2
  92. package/dist/{chunk-9xa5kzaq.js.map → chunk-7bywa721.js.map} +1 -1
  93. package/dist/{chunk-18aw52vs.js → chunk-7mg2ash8.js} +2 -2
  94. package/dist/{chunk-18aw52vs.js.map → chunk-7mg2ash8.js.map} +1 -1
  95. package/dist/{chunk-zsk4wvrs.js → chunk-8q3pnwtj.js} +2 -2
  96. package/dist/{chunk-zsk4wvrs.js.map → chunk-8q3pnwtj.js.map} +1 -1
  97. package/dist/{chunk-xdrnzs3t.js → chunk-95yr9y9v.js} +2 -2
  98. package/dist/{chunk-xdrnzs3t.js.map → chunk-95yr9y9v.js.map} +1 -1
  99. package/dist/{chunk-t8ghxzva.js → chunk-9k6swvf1.js} +3 -3
  100. package/dist/{chunk-t8ghxzva.js.map → chunk-9k6swvf1.js.map} +1 -1
  101. package/dist/{chunk-6n54q6wj.js → chunk-9pjvetym.js} +4 -4
  102. package/dist/{chunk-6n54q6wj.js.map → chunk-9pjvetym.js.map} +4 -4
  103. package/dist/{chunk-mcqzgyvf.js → chunk-a6yge4kh.js} +2 -2
  104. package/dist/{chunk-mcqzgyvf.js.map → chunk-a6yge4kh.js.map} +1 -1
  105. package/dist/{chunk-at5ce580.js → chunk-aqjjknyk.js} +3 -3
  106. package/dist/chunk-aqjjknyk.js.map +27 -0
  107. package/dist/{chunk-2v7stsgt.js → chunk-b02yzfpk.js} +2 -2
  108. package/dist/{chunk-2v7stsgt.js.map → chunk-b02yzfpk.js.map} +1 -1
  109. package/dist/{chunk-hcysexst.js → chunk-bk1e8sah.js} +2 -2
  110. package/dist/{chunk-hcysexst.js.map → chunk-bk1e8sah.js.map} +1 -1
  111. package/dist/{chunk-c8sq880v.js → chunk-btf3t4qa.js} +2 -2
  112. package/dist/{chunk-c8sq880v.js.map → chunk-btf3t4qa.js.map} +1 -1
  113. package/dist/{chunk-jgb3je66.js → chunk-bw1mvk6n.js} +2 -2
  114. package/dist/{chunk-jgb3je66.js.map → chunk-bw1mvk6n.js.map} +1 -1
  115. package/dist/{chunk-7czjphwg.js → chunk-c231j2e7.js} +2 -2
  116. package/dist/{chunk-7czjphwg.js.map → chunk-c231j2e7.js.map} +1 -1
  117. package/dist/{chunk-k6532519.js → chunk-c2c21b6g.js} +2 -2
  118. package/dist/{chunk-k6532519.js.map → chunk-c2c21b6g.js.map} +1 -1
  119. package/dist/{chunk-bjh3ms04.js → chunk-cgkp0ypn.js} +2 -2
  120. package/dist/{chunk-bjh3ms04.js.map → chunk-cgkp0ypn.js.map} +1 -1
  121. package/dist/{chunk-61sevt6g.js → chunk-cws2tsxg.js} +2 -2
  122. package/dist/{chunk-61sevt6g.js.map → chunk-cws2tsxg.js.map} +1 -1
  123. package/dist/{chunk-1a0ehbkm.js → chunk-djpqt7kh.js} +1 -1
  124. package/dist/{chunk-ha3d6zhv.js → chunk-djwmrvsq.js} +2 -2
  125. package/dist/{chunk-ha3d6zhv.js.map → chunk-djwmrvsq.js.map} +1 -1
  126. package/dist/chunk-dpm875be.js +71 -0
  127. package/dist/{chunk-2mwkjfnd.js.map → chunk-dpm875be.js.map} +5 -5
  128. package/dist/{chunk-2ek8wpe8.js → chunk-dqw432zh.js} +3 -3
  129. package/dist/{chunk-2ek8wpe8.js.map → chunk-dqw432zh.js.map} +1 -1
  130. package/dist/chunk-g1b6zetz.js +5 -0
  131. package/dist/{chunk-y10tys3s.js.map → chunk-g1b6zetz.js.map} +4 -4
  132. package/dist/{chunk-2hcwvkfx.js → chunk-g1th1dfa.js} +3 -3
  133. package/dist/{chunk-2hcwvkfx.js.map → chunk-g1th1dfa.js.map} +1 -1
  134. package/dist/{chunk-xbxdhmh4.js → chunk-g7vyn179.js} +3 -3
  135. package/dist/{chunk-xbxdhmh4.js.map → chunk-g7vyn179.js.map} +1 -1
  136. package/dist/{chunk-3vnb6xhz.js → chunk-gkjsanjh.js} +1 -1
  137. package/dist/{chunk-2x4x2qnk.js → chunk-gwe9hbds.js} +2 -2
  138. package/dist/{chunk-2x4x2qnk.js.map → chunk-gwe9hbds.js.map} +1 -1
  139. package/dist/{chunk-zzrmsvqc.js → chunk-hea3rwj3.js} +2 -2
  140. package/dist/{chunk-zzrmsvqc.js.map → chunk-hea3rwj3.js.map} +1 -1
  141. package/dist/{chunk-y54kz6h6.js → chunk-hknnxxg6.js} +3 -3
  142. package/dist/{chunk-y54kz6h6.js.map → chunk-hknnxxg6.js.map} +1 -1
  143. package/dist/{chunk-sqzm1k9q.js → chunk-htkw9qbv.js} +2 -2
  144. package/dist/{chunk-sqzm1k9q.js.map → chunk-htkw9qbv.js.map} +1 -1
  145. package/dist/{chunk-9ph676kt.js → chunk-j6j0qxam.js} +2 -2
  146. package/dist/{chunk-9ph676kt.js.map → chunk-j6j0qxam.js.map} +1 -1
  147. package/dist/{chunk-hka2sgqz.js → chunk-jr9f5r65.js} +3 -3
  148. package/dist/{chunk-hka2sgqz.js.map → chunk-jr9f5r65.js.map} +1 -1
  149. package/dist/{chunk-11wy7gm1.js → chunk-k9pch3e6.js} +2 -2
  150. package/dist/{chunk-11wy7gm1.js.map → chunk-k9pch3e6.js.map} +1 -1
  151. package/dist/{chunk-er6rhs42.js → chunk-kc1y747c.js} +3 -3
  152. package/dist/{chunk-er6rhs42.js.map → chunk-kc1y747c.js.map} +1 -1
  153. package/dist/{chunk-mj857ksa.js → chunk-kd6z1t9z.js} +3 -3
  154. package/dist/{chunk-mj857ksa.js.map → chunk-kd6z1t9z.js.map} +1 -1
  155. package/dist/{chunk-4q0pxgv6.js → chunk-knmh8ynk.js} +2 -2
  156. package/dist/{chunk-4q0pxgv6.js.map → chunk-knmh8ynk.js.map} +1 -1
  157. package/dist/{chunk-0njs5zqz.js → chunk-mjyr8at2.js} +3 -3
  158. package/dist/{chunk-0njs5zqz.js.map → chunk-mjyr8at2.js.map} +1 -1
  159. package/dist/{chunk-9a3wbbr6.js → chunk-mnfk2r8z.js} +2 -2
  160. package/dist/{chunk-9a3wbbr6.js.map → chunk-mnfk2r8z.js.map} +1 -1
  161. package/dist/{chunk-chy85f3v.js → chunk-mv2d2njy.js} +2 -2
  162. package/dist/{chunk-chy85f3v.js.map → chunk-mv2d2njy.js.map} +1 -1
  163. package/dist/{chunk-78gy3agg.js → chunk-mw4c05vw.js} +2 -2
  164. package/dist/{chunk-78gy3agg.js.map → chunk-mw4c05vw.js.map} +1 -1
  165. package/dist/{chunk-m4wagwhr.js → chunk-naj8bmj5.js} +2 -2
  166. package/dist/{chunk-m4wagwhr.js.map → chunk-naj8bmj5.js.map} +1 -1
  167. package/dist/{chunk-6cdykmvn.js → chunk-p5n1tqqg.js} +2 -2
  168. package/dist/{chunk-6cdykmvn.js.map → chunk-p5n1tqqg.js.map} +1 -1
  169. package/dist/{chunk-dghymwgp.js → chunk-py69zwwv.js} +2 -2
  170. package/dist/{chunk-dghymwgp.js.map → chunk-py69zwwv.js.map} +1 -1
  171. package/dist/{chunk-9yh4sfac.js → chunk-q677pnq5.js} +3 -3
  172. package/dist/{chunk-9yh4sfac.js.map → chunk-q677pnq5.js.map} +1 -1
  173. package/dist/chunk-rqa04dtq.js +11 -0
  174. package/dist/{chunk-3ejv7fs4.js.map → chunk-rqa04dtq.js.map} +6 -6
  175. package/dist/{chunk-vz2dt9f3.js → chunk-rzhgcajs.js} +1 -1
  176. package/dist/{chunk-5yfdrbwv.js → chunk-shn9t4vg.js} +2 -2
  177. package/dist/{chunk-5yfdrbwv.js.map → chunk-shn9t4vg.js.map} +1 -1
  178. package/dist/{chunk-2e278yhf.js → chunk-t0519abr.js} +2 -2
  179. package/dist/{chunk-2e278yhf.js.map → chunk-t0519abr.js.map} +1 -1
  180. package/dist/{chunk-c46y8hs0.js → chunk-t5af0fjq.js} +2 -2
  181. package/dist/{chunk-c46y8hs0.js.map → chunk-t5af0fjq.js.map} +1 -1
  182. package/dist/chunk-texzdarz.js +5 -0
  183. package/dist/{chunk-g4esp7z5.js.map → chunk-texzdarz.js.map} +1 -1
  184. package/dist/{chunk-wsp30cr6.js → chunk-ttz05z12.js} +2 -2
  185. package/dist/{chunk-wsp30cr6.js.map → chunk-ttz05z12.js.map} +1 -1
  186. package/dist/{chunk-sw8012bt.js → chunk-twb7x8j8.js} +2 -2
  187. package/dist/{chunk-sw8012bt.js.map → chunk-twb7x8j8.js.map} +1 -1
  188. package/dist/{chunk-2w8j265x.js → chunk-v7bbn1m0.js} +3 -3
  189. package/dist/{chunk-2w8j265x.js.map → chunk-v7bbn1m0.js.map} +1 -1
  190. package/dist/{chunk-qt80d3fw.js → chunk-w1my1q4q.js} +2 -2
  191. package/dist/{chunk-qt80d3fw.js.map → chunk-w1my1q4q.js.map} +1 -1
  192. package/dist/{chunk-ktxf56dm.js → chunk-wcj083k2.js} +3 -3
  193. package/dist/{chunk-ktxf56dm.js.map → chunk-wcj083k2.js.map} +1 -1
  194. package/dist/{chunk-fdbh87nv.js → chunk-xg5r0383.js} +3 -3
  195. package/dist/{chunk-fdbh87nv.js.map → chunk-xg5r0383.js.map} +1 -1
  196. package/dist/{chunk-wee3yrdn.js → chunk-xw241q0q.js} +1 -1
  197. package/dist/{chunk-nx86gzt1.js → chunk-y9fye7az.js} +2 -2
  198. package/dist/{chunk-nx86gzt1.js.map → chunk-y9fye7az.js.map} +1 -1
  199. package/dist/{chunk-ntwmz16f.js → chunk-yak9kt1x.js} +2 -2
  200. package/dist/{chunk-ntwmz16f.js.map → chunk-yak9kt1x.js.map} +1 -1
  201. package/dist/{chunk-frtx87yh.js → chunk-ybmy1rts.js} +2 -2
  202. package/dist/{chunk-frtx87yh.js.map → chunk-ybmy1rts.js.map} +1 -1
  203. package/dist/{chunk-s7p6w1p2.js → chunk-yjshg4e5.js} +2 -2
  204. package/dist/{chunk-s7p6w1p2.js.map → chunk-yjshg4e5.js.map} +1 -1
  205. package/dist/{chunk-tejgrqh7.js → chunk-z03ds1qe.js} +2 -2
  206. package/dist/{chunk-tejgrqh7.js.map → chunk-z03ds1qe.js.map} +1 -1
  207. package/dist/{chunk-3xrmx5c7.js → chunk-z54zefss.js} +2 -2
  208. package/dist/{chunk-3xrmx5c7.js.map → chunk-z54zefss.js.map} +1 -1
  209. package/dist/{chunk-cgjdxxwy.js → chunk-zbxvyanj.js} +2 -2
  210. package/dist/{chunk-cgjdxxwy.js.map → chunk-zbxvyanj.js.map} +1 -1
  211. package/dist/client/index.js +3 -2
  212. package/dist/client/index.js.map +1 -1
  213. package/dist/client/queryEffects.d.ts.map +1 -1
  214. package/dist/config/index.js +1 -1
  215. package/dist/console/run.js +2 -2
  216. package/dist/console/run.js.map +1 -1
  217. package/dist/container/index.js +2 -2
  218. package/dist/container/index.js.map +1 -1
  219. package/dist/database/index.js +2 -2
  220. package/dist/database/index.js.map +1 -1
  221. package/dist/email/index.js +2 -2
  222. package/dist/email/index.js.map +1 -1
  223. package/dist/facades/index.js +2 -2
  224. package/dist/facades/index.js.map +1 -1
  225. package/dist/foundation/index.js +2 -2
  226. package/dist/foundation/index.js.map +1 -1
  227. package/dist/http/ApiRouter.d.ts +6 -1
  228. package/dist/http/ApiRouter.d.ts.map +1 -1
  229. package/dist/http/index.js +2 -2
  230. package/dist/http/index.js.map +1 -1
  231. package/dist/i18n/dictionaryRuntime.js +2 -2
  232. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  233. package/dist/i18n/index.js +2 -2
  234. package/dist/i18n/index.js.map +1 -1
  235. package/dist/kernel/index.js +2 -2
  236. package/dist/kernel/index.js.map +1 -1
  237. package/dist/orm/index.js +2 -2
  238. package/dist/orm/index.js.map +1 -1
  239. package/dist/probe/index.js +2 -2
  240. package/dist/probe/index.js.map +1 -1
  241. package/dist/server/index.js +2 -2
  242. package/dist/server/index.js.map +1 -1
  243. package/dist/services/index.d.ts +11 -0
  244. package/dist/services/index.d.ts.map +1 -1
  245. package/dist/services/index.js +16 -16
  246. package/dist/services/index.js.map +9 -3
  247. package/dist/services/queue/work.js +2 -2
  248. package/dist/services/queue/work.js.map +1 -1
  249. package/dist/stats/route-table.js +1 -1
  250. package/dist/support/index.js +2 -2
  251. package/dist/support/index.js.map +1 -1
  252. package/dist/vitest/index.js +1 -1
  253. package/package.json +1 -1
  254. package/dist/chunk-2mwkjfnd.js +0 -71
  255. package/dist/chunk-3ejv7fs4.js +0 -11
  256. package/dist/chunk-at5ce580.js.map +0 -27
  257. package/dist/chunk-g4esp7z5.js +0 -5
  258. package/dist/chunk-y10tys3s.js +0 -5
  259. /package/dist/{chunk-ge201pk4.js.map → chunk-1k6dn4ba.js.map} +0 -0
  260. /package/dist/{chunk-fw7sxgse.js.map → chunk-6cge785m.js.map} +0 -0
  261. /package/dist/{chunk-1a0ehbkm.js.map → chunk-djpqt7kh.js.map} +0 -0
  262. /package/dist/{chunk-3vnb6xhz.js.map → chunk-gkjsanjh.js.map} +0 -0
  263. /package/dist/{chunk-vz2dt9f3.js.map → chunk-rzhgcajs.js.map} +0 -0
  264. /package/dist/{chunk-wee3yrdn.js.map → chunk-xw241q0q.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{rb as v9}from"../chunk-g6tqje74.js";import{$b as k9,Ab as q4,Bb as c1,Cb as mZ,Db as cZ,Eb as Y9,Ib as K9,Jb as G9,Kb as z9,Lb as X9,Mb as F9,Nb as M9,Ob as L9,Pb as N9,Qb as D9,Rb as H9,Sb as U9,Tb as g4,Ub as _6,Vb as w,Wb as x9,Xb as O9,Yb as S9,Zb as R9,_b as _9,ac as f9,bc as C9,cc as V9,dc as T9,ec as P9,fc as b9,gc as w9,hc as q9,sb as IZ,tb as yZ,ub as AZ,vb as hZ,wb as EZ,xb as y4,yb as gZ,zb as w4}from"../chunk-6cdykmvn.js";import{kc as h4}from"../chunk-at5ce580.js";import"../chunk-y10tys3s.js";import{$d as pZ,_d as uZ,ae as dZ,be as lZ,ce as nZ,de as sZ,ee as oZ,fe as aZ,ge as tZ,he as rZ,ie as eZ,je as W9,ke as Z9,le as $9,me as J9,ne as Q9}from"../chunk-2w8j265x.js";import{oe as iZ}from"../chunk-hcysexst.js";import{Ae as TZ,Be as PZ,Ce as bZ,De as wZ,Ee as qZ,Je as vZ,pe as HZ,qe as UZ,re as xZ,se as OZ,te as SZ,ue as RZ,ve as _Z,we as kZ,xe as fZ,ye as CZ,ze as VZ}from"../chunk-9yh4sfac.js";import{Ke as B9,Le as j9}from"../chunk-ktxf56dm.js";import"../chunk-5399t8zm.js";import{$f as R8,$g as YZ,Ag as u8,Bg as p8,Cg as d8,Dg as l8,Dh as jZ,Eg as n8,Eh as FZ,Fg as i8,Gg as s8,Lg as U,Mg as m,Ng as o8,Of as J8,Og as a8,Pf as Q8,Pg as t8,Qf as Y8,Qg as r8,Rf as K8,Rg as e8,Sf as G8,Te as N6,Tf as z8,Tg as WZ,Ue as P5,Ug as ZZ,Ve as b5,Vg as $Z,We as w5,Wg as JZ,Ye as q5,Yg as QZ,Zf as O8,_f as S8,af as D6,ag as _8,ah as KZ,bf as x4,bg as k8,bh as GZ,cf as Z6,cg as f8,df as O4,dg as C8,ef as S4,eg as V8,eh as zZ,fg as T8,hg as P8,if as f6,ig as R6,jf as C6,jg as b8,jh as XZ,lf as v5,mf as I5,nf as y5,ng as w8,nh as BZ,of as A5,og as q8,pf as h5,pg as I8,qf as E5,rf as g5,rh as m4,sf as m5,sg as y8,sh as e,tf as c5,tg as A8,uf as o0,ug as h8,vf as u5,vg as E8,wf as p5,xf as d5,xg as g8,yf as l5,yg as m8,zf as n5,zg as c8}from"../chunk-6n54q6wj.js";import"../chunk-t8ghxzva.js";import"../chunk-gk2k76tn.js";import{$i as U1,Aj as $8,Cj as h1,Qi as b4,Ui as J1,Wi as a,_i as D4,aj as A1,bj as i5,cj as s5,dj as o5,ej as a5,fj as t5,rj as HW,sj as UW,vj as r5,wi as U4,wj as e5,xi as N4,yi as H1,yj as W8,zj as Z8}from"../chunk-2hcwvkfx.js";import"../chunk-d8nxkc90.js";import{Nj as V}from"../chunk-m4wagwhr.js";import"../chunk-xdrnzs3t.js";import{$j as v1,Zj as N8,_j as D8,ak as H8,bk as d0,ck as U8,dk as x8}from"../chunk-2mwkjfnd.js";import{jk as F8,kk as M8,lk as L8}from"../chunk-y54kz6h6.js";import"../chunk-768yza4f.js";import{Uk as v8}from"../chunk-9a3wbbr6.js";import{Wk as X8,Xk as B8,Yk as j8}from"../chunk-mcqzgyvf.js";import"../chunk-cgjdxxwy.js";import"../chunk-er6rhs42.js";import"../chunk-bvm2w6ha.js";import"../chunk-3egn4pfk.js";import{Tl as _4,Ul as MZ,Vl as LZ,Wl as NZ,Yl as DZ}from"../chunk-fdbh87nv.js";import"../chunk-5w0kzk4m.js";import{gm as _}from"../chunk-mj857ksa.js";import"../chunk-gg97wgy0.js";import"../chunk-nx86gzt1.js";import"../chunk-zzrmsvqc.js";import"../chunk-5yfdrbwv.js";import"../chunk-jgb3je66.js";import{Lm as y1}from"../chunk-c80xrwep.js";import{Buffer as a0}from"buffer";class t0 extends U1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-rdzdbd52.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 a0?$:$ instanceof Blob||$ instanceof File?a0.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={}){D4(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=A1(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?N4(Q):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new J1(await this.size({name:J,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new a(J);throw j}let z=H1(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 a(Z);throw Y}}}import{Buffer as r0}from"buffer";import{Readable as SW}from"stream";function H4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function RW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class e0 extends U1{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 r0?$:r0.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 S=await this.size({name:$,bucket:J}),o=U4(Q,S);if(!o)throw new J1(S);K=o.start,G=o.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(S){if(RW(S))throw new J1(await this.size({name:$,bucket:J}));if(H4(S))throw new a($);throw S}let B=H1(X.contentRange),j=Boolean(B),L=B?.total??X.contentLength??0,H=await _W(X);if(H instanceof ReadableStream)H=A1(H,Z);return Z?.throwIfAborted(),{body:H,start:B?.start??0,end:B?.end??L-1,total:L,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(H4(Q))throw new a(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(H4(Q))return;throw Q}}}async function _W(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return SW.toWeb(W.readableStreamBody);return null}function kW(W){return W}class R4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class E1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var W6=1000,fW=60000,CW=`
2
+ import{rb as Q$}from"../chunk-g6tqje74.js";import{$b as s9,Ab as g4,Bb as s1,Cb as B9,Db as j9,Eb as b9,Ib as w9,Jb as q9,Kb as v9,Lb as I9,Mb as A9,Nb as h9,Ob as E9,Pb as g9,Qb as m9,Rb as c9,Sb as u9,Tb as n4,Ub as v6,Vb as h,Wb as p9,Xb as d9,Yb as l9,Zb as n9,_b as i9,ac as o9,bc as a9,cc as t9,dc as r9,ec as e9,fc as W$,gc as Z$,hc as $$,sb as Y9,tb as K9,ub as J9,vb as z9,wb as G9,xb as u4,yb as X9,zb as E4}from"../chunk-p5n1tqqg.js";import{kc as d4}from"../chunk-aqjjknyk.js";import"../chunk-g1b6zetz.js";import{$d as M9,ae as F9,be as L9,ce as D9,de as H9,ee as U9,fe as x9,ge as S9,he as R9,ie as O9,je as _9,ke as V9,le as k9,me as C9,ne as T9,oe as P9}from"../chunk-v7bbn1m0.js";import{pe as N9}from"../chunk-bk1e8sah.js";import{Ae as tZ,Be as rZ,Ce as eZ,De as W9,Ee as Z9,Fe as $9,Ke as Q9,qe as cZ,re as uZ,se as pZ,te as dZ,ue as lZ,ve as nZ,we as iZ,xe as sZ,ye as oZ,ze as aZ}from"../chunk-q677pnq5.js";import{Le as f9,Me as y9}from"../chunk-wcj083k2.js";import"../chunk-5cf59esb.js";import{$f as l8,Af as H8,Ag as jZ,Bg as MZ,Cg as FZ,Dg as LZ,Eg as DZ,Eh as yZ,Fg as HZ,Fh as AZ,Gg as NZ,Hg as UZ,Mg as R,Ng as i,Og as xZ,Pf as T8,Pg as SZ,Qf as P8,Qg as RZ,Rf as b8,Rg as OZ,Sf as w8,Sg as _Z,Tf as q8,Ue as V6,Uf as v8,Ug as VZ,Ve as e5,Vg as kZ,We as W8,Wg as CZ,Xe as Z8,Xg as TZ,Ze as $8,Zg as PZ,_f as d8,ag as n8,ah as bZ,bf as k6,bg as i8,bh as wZ,cf as C4,cg as s8,ch as qZ,df as B6,dg as o8,ef as T4,eg as a8,ff as P4,fg as t8,fh as vZ,gg as r8,ig as e8,jf as f6,jg as q6,kf as y6,kg as WZ,kh as IZ,mf as Q8,nf as Y8,of as K8,og as ZZ,oh as fZ,pf as J8,pg as $Z,qf as z8,qg as YZ,rf as G8,sf as X8,sh as i4,tf as B8,tg as KZ,th as z1,uf as j8,ug as JZ,vf as Y6,vg as zZ,wf as M8,wg as GZ,xf as F8,yf as L8,yg as XZ,zf as D8,zg as BZ}from"../chunk-9pjvetym.js";import"../chunk-9k6swvf1.js";import"../chunk-2crfg0m7.js";import{$i as _4,Aj as k8,Bj as C8,Dj as d1,Ri as h4,Vi as j1,Xi as Y1,aj as C1,bj as p1,cj as N8,dj as U8,ej as x8,fj as S8,gj as R8,sj as mW,tj as cW,wj as O8,xi as k4,xj as _8,yi as O4,zi as k1,zj as V8}from"../chunk-g1th1dfa.js";import"../chunk-5ya7fbfg.js";import{Oj as q}from"../chunk-naj8bmj5.js";import"../chunk-95yr9y9v.js";import{$j as m8,_j as g8,ak as U,bk as c8,ck as b,dk as u8,ek as p8}from"../chunk-dpm875be.js";import{kk as A8,lk as h8,mk as E8}from"../chunk-hknnxxg6.js";import"../chunk-5m0vh0rg.js";import{Vk as QZ}from"../chunk-mnfk2r8z.js";import{Xk as I8,Yk as f8,Zk as y8}from"../chunk-a6yge4kh.js";import"../chunk-zbxvyanj.js";import"../chunk-kc1y747c.js";import"../chunk-6669vjve.js";import"../chunk-6s48nq83.js";import{Ul as w4,Vl as hZ,Wl as EZ,Xl as gZ,Zl as mZ}from"../chunk-xg5r0383.js";import"../chunk-4zw9gaey.js";import{hm as C}from"../chunk-kd6z1t9z.js";import"../chunk-3pfrqzw8.js";import"../chunk-y9fye7az.js";import"../chunk-hea3rwj3.js";import"../chunk-shn9t4vg.js";import"../chunk-bw1mvk6n.js";import{Mm as u1}from"../chunk-0z8h6t7k.js";import{Buffer as K6}from"buffer";class J6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-01r2cx3k.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof K6?$:$ instanceof Blob||$ instanceof File?K6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}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:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){_4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}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,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=p1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?O4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as z6}from"buffer";import{Readable as dW}from"stream";function V4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function lW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class G6 extends C1{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 $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof z6?$:z6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}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:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=k4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(lW(V))throw new j1(await this.size({name:$,bucket:Q}));if(V4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await nW(X);if(x instanceof ReadableStream)x=p1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,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,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(V4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(V4(Y))return;throw Y}}}async function nW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return dW.toWeb(W.readableStreamBody);return null}function iW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class l1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var X6=1000,sW=60000,oW=`
3
3
  local currentKey = KEYS[1]
4
4
  local previousKey = KEYS[2]
5
5
  local limit = tonumber(ARGV[1])
@@ -26,12 +26,12 @@ current = redis.call("INCRBY", currentKey, cost)
26
26
  redis.call("PEXPIRE", currentKey, window * 2)
27
27
 
28
28
  return {1, current, previous}
29
- `;class $6 extends O4{injectedClient;prefix;mode;fallback;timeout;onError;scriptSha=null;down=!1;probing=!1;lastProbeAt=0;seenConnected=new WeakSet;loggedAt=-1/0;failuresSinceLog=0;fallbacksSinceLog=0;constructor(W={}){super();this.injectedClient=W.client,this.prefix=W.prefix??"gemi:rl",this.mode=W.onRedisError??(W.failOpen===void 0?"memory":W.failOpen?"open":"closed"),this.fallback=W.fallback??new S4,this.timeout=W.timeout??250,this.onError=W.onError}async consume(W){let{key:Z,limit:$,window:J}=W,Q=W.cost??1,Y=Date.now(),K=x4(Y,J),G=Y-K,z=K/J;if(this.down)return this.probe(),this.degrade(W,Y);try{let X=this.client;if(X.connected===!1&&this.seenConnected.has(X))throw new E1;let B=await this.withTimeout(this.run(X,[`${this.prefix}:${Z}:${z}`,`${this.prefix}:${Z}:${z-1}`],[String($),String(J),String(G),String(Q)]),()=>{this.scriptSha=null});if(X.connected===!0)this.seenConnected.add(X);let[j,L,H]=(Array.isArray(B)?B:[]).map(Number);return Z6({allowed:j===1,current:Number.isFinite(L)?L:0,previous:Number.isFinite(H)?H:0,now:Y,elapsed:G,window:J,limit:$,cost:Q})}catch(X){if(!this.down)this.down=!0,this.lastProbeAt=Date.now();return this.report(X),this.degrade(W,Y)}}async degrade(W,Z){let{limit:$,window:J}=W,Q=W.cost??1;if(this.fallbacksSinceLog+=1,this.mode==="memory")return await this.fallback.consume(W);if(this.mode==="closed")return{allowed:!1,limit:$,remaining:0,resetAt:Z+J,retryAfter:J};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-Q)),resetAt:x4(Z,J)+J,retryAfter:0}}probe(){let W=Date.now();if(this.probing||W-this.lastProbeAt<W6)return;this.probing=!0,this.lastProbeAt=W,(async()=>{let $=this.client;if($.connected===!1&&this.seenConnected.has($))throw new E1;if(await this.withTimeout($.send("PING",[]),void 0,this.timeout>0?this.timeout:W6),$.connected===!0)this.seenConnected.add($)})().then(()=>{if(this.probing=!1,this.down=!1,!this.onError)this.logRecovery()},($)=>{this.probing=!1;try{this.report($)}catch{}})}report(W){if(this.onError){this.onError(W);return}this.failuresSinceLog+=1;let Z=Date.now();if(Z-this.loggedAt<fW)return;let $=this.mode==="memory"?"counting in memory":this.mode==="open"?"admitting every request":"refusing every request",J=this.loggedAt===-1/0?"":` Since the last report: ${this.failuresSinceLog} failures, ${this.fallbacksSinceLog} calls answered without Redis.`;console.error(`[gemi] RedisRateLimiter: Redis failed, ${$} until it answers again.${J}`,W),this.loggedAt=Z,this.failuresSinceLog=0,this.fallbacksSinceLog=0}logRecovery(){console.info(`[gemi] RedisRateLimiter: Redis answers again; counting in Redis (${this.fallbacksSinceLog} calls answered without it since the last report).`),this.loggedAt=-1/0,this.failuresSinceLog=0,this.fallbacksSinceLog=0}withTimeout(W,Z,$=this.timeout){if(!($>0)||!Number.isFinite($))return W;let J,Q=new Promise((Y,K)=>{J=setTimeout(()=>{Z?.(),K(new R4($))},$)});return W.catch(()=>{}),Promise.race([W,Q]).finally(()=>clearTimeout(J))}get client(){if(this.injectedClient)return this.injectedClient;let W=_(),Z=W.bound(h1)?W.make(h1).client:void 0;if(!Z)throw Error("RedisRateLimiter could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisRateLimiter({ client }).");return Z}async run(W,Z,$){let J=[String(Z.length),...Z,...$];try{return await W.send("EVALSHA",[await this.load(W),...J])}catch(Q){if(!VW(Q))throw Q;return this.scriptSha=null,await W.send("EVALSHA",[await this.load(W),...J])}}load(W){if(!this.scriptSha)this.scriptSha=Promise.resolve(W.send("SCRIPT",["LOAD",CW])).then(String).catch((Z)=>{throw this.scriptSha=null,Z});return this.scriptSha}}function VW(W){return String(W?.message??W).includes("NOSCRIPT")}function x1(W){let Z=/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/.exec(W);if(!Z)return{address:W.trim()};let[,$,J]=Z;return $?{address:J.trim(),displayName:$}:{address:J.trim()}}function TW(W){if(W.contentType)return W.contentType;return Bun.file(W.filename).type.split(";")[0]||"application/octet-stream"}class k4 extends _4{config;provider="acs";supportsIdempotencyKey=!1;clientPromise=null;constructor(W={}){super();this.config=W}async client(){if(this.config.client)return this.config.client;return this.clientPromise??=(async()=>{let W;try{W=await import("@azure/communication-email")}catch{throw Error("AcsDriver requires the '@azure/communication-email' package. Install it with `bun add @azure/communication-email`, or pass a pre-built `client`.")}let Z=this.config.endpoint??process.env.AZURE_COMMUNICATION_ENDPOINT,$=this.config.connectionString??process.env.AZURE_COMMUNICATION_CONNECTION_STRING;if(Z){let J=this.config.credential;if(!J){let Q;try{Q=await import("@azure/identity")}catch{throw Error("AcsDriver with an `endpoint` and no `credential` requires the '@azure/identity' package (for DefaultAzureCredential). Install it with `bun add @azure/identity`.")}J=new Q.DefaultAzureCredential}return new W.EmailClient(Z,J)}if($)return new W.EmailClient($);throw Error("AcsDriver needs an endpoint (AZURE_COMMUNICATION_ENDPOINT, authenticated with managed identity), a connection string (AZURE_COMMUNICATION_CONNECTION_STRING), or a `client`.")})(),this.clientPromise.catch(()=>{this.clientPromise=null}),this.clientPromise}static toMessage(W){let Z={senderAddress:x1(W.from).address,content:{subject:W.subject,html:W.html,...W.text?{plainText:W.text}:{}},recipients:{to:W.to.map(x1),...W.cc?.length?{cc:W.cc.map(x1)}:{},...W.bcc?.length?{bcc:W.bcc.map(x1)}:{}}};if(W.replyTo?.length)Z.replyTo=W.replyTo.map(x1);if(W.headers&&Object.keys(W.headers).length)Z.headers=W.headers;if(W.attachments?.length)Z.attachments=W.attachments.map(($)=>({name:$.filename,contentType:TW($),contentInBase64:Buffer.from($.content).toString("base64")}));return Z}async send(W){return(await this.deliver(W)).ok}async deliver(W){if(W.scheduledAt)throw Error(`AcsDriver can't schedule a send (scheduledAt: "${W.scheduledAt}"): Azure Communication Services has no scheduled delivery. Send from a delayed job instead.`);let Z=k4.toMessage(W),$=await this.client(),J=crypto.randomUUID();try{let Q=await $.beginSend(Z,{operationId:J}),Y=Q.getOperationState?.();if(Y?.status==="failed"||Y?.status==="canceled")return console.error(Y.error),{ok:!1,id:J,error:Y.error};return{ok:!0,id:Q.getResult?.()?.id??J}}catch(Q){return console.error(Q),{ok:!1,id:null,error:Q}}}}import{createHash as A4,randomBytes as t,timingSafeEqual as PW}from"crypto";var g1=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 J6(W,Z){let $=W.client.name?b(W.client.name):"An application",J=W.scopes.map((Y)=>`<li><strong>${b(Y.name)}</strong><br><span>${b(Y.description)}</span></li>`).join(""),Q=Object.entries(W.form.fields).map(([Y,K])=>`<input type="hidden" name="${b(Y)}" value="${b(K)}">`).join("");return`<!doctype html>
29
+ `;class j6 extends T4{injectedClient;prefix;mode;fallback;timeout;onError;scriptSha=null;down=!1;probing=!1;lastProbeAt=0;seenConnected=new WeakSet;loggedAt=-1/0;failuresSinceLog=0;fallbacksSinceLog=0;constructor(W={}){super();this.injectedClient=W.client,this.prefix=W.prefix??"gemi:rl",this.mode=W.onRedisError??(W.failOpen===void 0?"memory":W.failOpen?"open":"closed"),this.fallback=W.fallback??new P4,this.timeout=W.timeout??250,this.onError=W.onError}async consume(W){let{key:Z,limit:$,window:Q}=W,Y=W.cost??1,K=Date.now(),J=C4(K,Q),z=K-J,G=J/Q;if(this.down)return this.probe(),this.degrade(W,K);try{let X=this.client;if(X.connected===!1&&this.seenConnected.has(X))throw new l1;let B=await this.withTimeout(this.run(X,[`${this.prefix}:${Z}:${G}`,`${this.prefix}:${Z}:${G-1}`],[String($),String(Q),String(z),String(Y)]),()=>{this.scriptSha=null});if(X.connected===!0)this.seenConnected.add(X);let[j,D,x]=(Array.isArray(B)?B:[]).map(Number);return B6({allowed:j===1,current:Number.isFinite(D)?D:0,previous:Number.isFinite(x)?x:0,now:K,elapsed:z,window:Q,limit:$,cost:Y})}catch(X){if(!this.down)this.down=!0,this.lastProbeAt=Date.now();return this.report(X),this.degrade(W,K)}}async degrade(W,Z){let{limit:$,window:Q}=W,Y=W.cost??1;if(this.fallbacksSinceLog+=1,this.mode==="memory")return await this.fallback.consume(W);if(this.mode==="closed")return{allowed:!1,limit:$,remaining:0,resetAt:Z+Q,retryAfter:Q};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-Y)),resetAt:C4(Z,Q)+Q,retryAfter:0}}probe(){let W=Date.now();if(this.probing||W-this.lastProbeAt<X6)return;this.probing=!0,this.lastProbeAt=W,(async()=>{let $=this.client;if($.connected===!1&&this.seenConnected.has($))throw new l1;if(await this.withTimeout($.send("PING",[]),void 0,this.timeout>0?this.timeout:X6),$.connected===!0)this.seenConnected.add($)})().then(()=>{if(this.probing=!1,this.down=!1,!this.onError)this.logRecovery()},($)=>{this.probing=!1;try{this.report($)}catch{}})}report(W){if(this.onError){this.onError(W);return}this.failuresSinceLog+=1;let Z=Date.now();if(Z-this.loggedAt<sW)return;let $=this.mode==="memory"?"counting in memory":this.mode==="open"?"admitting every request":"refusing every request",Q=this.loggedAt===-1/0?"":` Since the last report: ${this.failuresSinceLog} failures, ${this.fallbacksSinceLog} calls answered without Redis.`;console.error(`[gemi] RedisRateLimiter: Redis failed, ${$} until it answers again.${Q}`,W),this.loggedAt=Z,this.failuresSinceLog=0,this.fallbacksSinceLog=0}logRecovery(){console.info(`[gemi] RedisRateLimiter: Redis answers again; counting in Redis (${this.fallbacksSinceLog} calls answered without it since the last report).`),this.loggedAt=-1/0,this.failuresSinceLog=0,this.fallbacksSinceLog=0}withTimeout(W,Z,$=this.timeout){if(!($>0)||!Number.isFinite($))return W;let Q,Y=new Promise((K,J)=>{Q=setTimeout(()=>{Z?.(),J(new b4($))},$)});return W.catch(()=>{}),Promise.race([W,Y]).finally(()=>clearTimeout(Q))}get client(){if(this.injectedClient)return this.injectedClient;let W=C(),Z=W.bound(d1)?W.make(d1).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 Q=[String(Z.length),...Z,...$];try{return await W.send("EVALSHA",[await this.load(W),...Q])}catch(Y){if(!aW(Y))throw Y;return this.scriptSha=null,await W.send("EVALSHA",[await this.load(W),...Q])}}load(W){if(!this.scriptSha)this.scriptSha=Promise.resolve(W.send("SCRIPT",["LOAD",oW])).then(String).catch((Z)=>{throw this.scriptSha=null,Z});return this.scriptSha}}function aW(W){return String(W?.message??W).includes("NOSCRIPT")}function T1(W){let Z=/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/.exec(W);if(!Z)return{address:W.trim()};let[,$,Q]=Z;return $?{address:Q.trim(),displayName:$}:{address:Q.trim()}}function tW(W){if(W.contentType)return W.contentType;return Bun.file(W.filename).type.split(";")[0]||"application/octet-stream"}class q4 extends w4{config;provider="acs";supportsIdempotencyKey=!1;clientPromise=null;constructor(W={}){super();this.config=W}async client(){if(this.config.client)return this.config.client;return this.clientPromise??=(async()=>{let W;try{W=await import("@azure/communication-email")}catch{throw Error("AcsDriver requires the '@azure/communication-email' package. Install it with `bun add @azure/communication-email`, or pass a pre-built `client`.")}let Z=this.config.endpoint??process.env.AZURE_COMMUNICATION_ENDPOINT,$=this.config.connectionString??process.env.AZURE_COMMUNICATION_CONNECTION_STRING;if(Z){let Q=this.config.credential;if(!Q){let Y;try{Y=await import("@azure/identity")}catch{throw Error("AcsDriver with an `endpoint` and no `credential` requires the '@azure/identity' package (for DefaultAzureCredential). Install it with `bun add @azure/identity`.")}Q=new Y.DefaultAzureCredential}return new W.EmailClient(Z,Q)}if($)return new W.EmailClient($);throw Error("AcsDriver needs an endpoint (AZURE_COMMUNICATION_ENDPOINT, authenticated with managed identity), a connection string (AZURE_COMMUNICATION_CONNECTION_STRING), or a `client`.")})(),this.clientPromise.catch(()=>{this.clientPromise=null}),this.clientPromise}static toMessage(W){let Z={senderAddress:T1(W.from).address,content:{subject:W.subject,html:W.html,...W.text?{plainText:W.text}:{}},recipients:{to:W.to.map(T1),...W.cc?.length?{cc:W.cc.map(T1)}:{},...W.bcc?.length?{bcc:W.bcc.map(T1)}:{}}};if(W.replyTo?.length)Z.replyTo=W.replyTo.map(T1);if(W.headers&&Object.keys(W.headers).length)Z.headers=W.headers;if(W.attachments?.length)Z.attachments=W.attachments.map(($)=>({name:$.filename,contentType:tW($),contentInBase64:Buffer.from($.content).toString("base64")}));return Z}async send(W){return(await this.deliver(W)).ok}async deliver(W){if(W.scheduledAt)throw Error(`AcsDriver can't schedule a send (scheduledAt: "${W.scheduledAt}"): Azure Communication Services has no scheduled delivery. Send from a delayed job instead.`);let Z=q4.toMessage(W),$=await this.client(),Q=crypto.randomUUID();try{let Y=await $.beginSend(Z,{operationId:Q}),K=Y.getOperationState?.();if(K?.status==="failed"||K?.status==="canceled")return console.error(K.error),{ok:!1,id:Q,error:K.error};return{ok:!0,id:Y.getResult?.()?.id??Q}}catch(Y){return console.error(Y),{ok:!1,id:null,error:Y}}}}import{createHash as p4,randomBytes as K1,timingSafeEqual as rW}from"crypto";var n1=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 M6(W,Z){let $=W.client.name?A(W.client.name):"An application",Q=W.scopes.map((K)=>`<li><strong>${A(K.name)}</strong><br><span>${A(K.description)}</span></li>`).join(""),Y=Object.entries(W.form.fields).map(([K,J])=>`<input type="hidden" name="${A(K)}" value="${A(J)}">`).join("");return`<!doctype html>
30
30
  <html lang="en">
31
31
  <head>
32
32
  <meta charset="utf-8">
33
33
  <meta name="viewport" content="width=device-width, initial-scale=1">
34
- <title>Connect to ${b(Z.name)}</title>
34
+ <title>Connect to ${A(Z.name)}</title>
35
35
  <style>
36
36
  :root { color-scheme: light dark; font-family: system-ui, sans-serif; }
37
37
  body { margin: 0; display: grid; place-items: center; min-height: 100vh; padding: 16px; box-sizing: border-box; }
@@ -48,12 +48,12 @@ return {1, current, previous}
48
48
  </head>
49
49
  <body>
50
50
  <main>
51
- <h1>${$} wants to access your ${b(Z.name)} account</h1>
52
- <p class="warn">Signed in as ${b(W.user.label)}. After you allow it, you will be sent to <strong>${b(W.client.redirectHost)}</strong>. The name above was given by the application and is not verified. Only continue if you started this connection yourself.</p>
51
+ <h1>${$} wants to access your ${A(Z.name)} account</h1>
52
+ <p class="warn">Signed in as ${A(W.user.label)}. After you allow it, you will be sent to <strong>${A(W.client.redirectHost)}</strong>. The name above was given by the application and is not verified. Only continue if you started this connection yourself.</p>
53
53
  <p>It will be able to:</p>
54
- <ul>${J}</ul>
55
- <form method="post" action="${b(W.form.action)}">
56
- ${Q}
54
+ <ul>${Q}</ul>
55
+ <form method="post" action="${A(W.form.action)}">
56
+ ${Y}
57
57
  <div class="actions">
58
58
  <button type="submit" name="decision" value="deny">Deny</button>
59
59
  <button type="submit" name="decision" value="allow">Allow</button>
@@ -61,12 +61,12 @@ return {1, current, previous}
61
61
  </form>
62
62
  </main>
63
63
  </body>
64
- </html>`}function Q6(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>${b(W)}</p></body></html>`}function b(W){return W.replace(/[&<>"']/g,(Z)=>`&#${Z.charCodeAt(0)};`)}var f4="gmcp_at_",C4="gmcp_rt_",Y6="gmcp_ac_",bW="gmcp_c_",wW="gmcp_cs_",V4="gemi.mcp.oauth.ticket.v1",K6="gemi.mcp.oauth.consent.v1",qW=600000,G6=120000,v4=16384,vW={limit:20,window:3600},IW={limit:60,window:60},m1=["none","client_secret_post","client_secret_basic"];class M extends Error{error;description;status;headers;constructor(W,Z,$=400,J={}){super(Z);this.error=W;this.description=Z;this.status=$;this.headers=J}}class H6{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=z6("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=z6("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=y4(W);if(!Z?.startsWith(f4))return null;let $=await this.store.findToken(g(Z)),J=(Y)=>({ok:!1,error:"invalid_token",description:Y});if(!$||$.kind!=="access")return J("The access token is not valid.");if($.expiresAt<=Date.now())return J("The access token expired.");if($.resource!==this.context.resource)return J("The access token was not issued for this server.");let Q=await this.options.findUser($.userId);if(!Q)return J("The access token is not valid.");return{ok:!0,principal:{user:Q,via:this.name,id:$.familyId,scopes:$.scopes,clientId:$.clientId}}}challenge(){let W=this.scopeNames().join(" ");return`Bearer resource_metadata="${this.resourceMetadataUrl()}", scope="${W}"`}async handle(W){let Z=new URL(W.url).pathname,Q={[`/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-protected-resource"]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-authorization-server"]:{methods:["GET"],cors:!0,run:()=>this.serverMetadata()},[`${this.base}/register`]:{methods:["POST"],cors:!0,run:()=>this.register(W)},[`${this.base}/authorize`]:{methods:["GET"],cors:!1,run:()=>this.authorize(W)},[`${this.base}/consent`]:{methods:["GET","POST"],cors:!1,run:()=>W.method==="POST"?this.decide(W):this.consentScreen(W)},[`${this.base}/token`]:{methods:["POST"],cors:!0,run:()=>this.token(W)},[`${this.base}/revoke`]:{methods:["POST"],cors:!0,run:()=>this.revoke(W)}}[Z];if(!Q)return null;if(Z===`${this.base}/register`&&this.options.registration===!1)return null;let Y=Q.cors?yW:{};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 M))throw G;K=O1({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 $=c1(V4,"gat1",W);if(!$)return null;let J=await this.store.findClient($.c);if(!J||!J.redirectUris.some((G)=>P4(G,$.r)))return null;let Q=String(Z.id),Y=q4(K6,"gcs1",{t:X6(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 O1({resource:this.context.resource,authorization_servers:[this.issuer],scopes_supported:this.scopeNames(),bearer_methods_supported:["header"]})}serverMetadata(){return O1({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:m1,revocation_endpoint_auth_methods_supported:m1,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 w4(`mcp-oauth-register:${D6(new b4(W,{},"api",`${this.base}/register`))}`,Z.rateLimit??vW);if($!==null)throw new M("slow_down","Too many registrations from this address.",429,{"Retry-After":String($)});if(!/^application\/json\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new M("invalid_client_metadata","Send the client metadata as application/json.");let J;try{J=JSON.parse(await I4(W,v4))}catch{throw new M("invalid_client_metadata","The client metadata is not JSON, or is too large.")}if(typeof J!=="object"||J===null||Array.isArray(J))throw new M("invalid_client_metadata","The client metadata must be a JSON object.");let Q=J.redirect_uris;if(!Array.isArray(Q)||Q.length===0||Q.length>10)throw new M("invalid_redirect_uri","redirect_uris must list one to ten URIs.");for(let L of Q){let H=EW(L);if(H)throw new M("invalid_redirect_uri",`${String(L).slice(0,200)}: ${H}`);if(Z.allowRedirectUri&&Z.allowRedirectUri(new URL(L))!==!0)throw new M("invalid_redirect_uri",`${L}: this server does not accept it.`)}let Y=J.token_endpoint_auth_method??"client_secret_basic";if(!m1.includes(Y))throw new M("invalid_client_metadata",`token_endpoint_auth_method must be one of ${m1.join(", ")}.`);let K=J.grant_types??["authorization_code"];if(!Array.isArray(K)||K.some((L)=>L!=="authorization_code"&&L!=="refresh_token"))throw new M("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((L)=>L!=="code"))throw new M("invalid_client_metadata","response_types may only be code.");let z=F6(J.client_name,100,"client_name"),X=F6(J.client_uri,512,"client_uri");if(X!==null&&!hW(X))throw new M("invalid_client_metadata","client_uri must be an https URL.");let B=Y==="none"?null:`${wW}${t(32).toString("base64url")}`,j={clientId:`${bW}${t(16).toString("base64url")}`,clientSecretHash:B?g(B):null,tokenEndpointAuthMethod:Y,redirectUris:[...Q],clientName:z,clientUri:X,createdAt:Date.now()};return await this.store.createClient(j),O1({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 S of new Set(Z.keys()))if(Z.getAll(S).length>1)return A(`The parameter ${S} was sent more than once.`);let $=Z.get("client_id"),J=$?await this.store.findClient($):null;if(!J)return A("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((S)=>P4(S,Q)))return A("The redirect URI is not one the application registered.");let Y=Z.get("state"),K=(S,o)=>this.redirectBack(Q,Y,{error:S,error_description:o});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&&!M6(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((S)=>X.includes(S)))],j.length===0)return K("invalid_scope","None of the requested scopes exist here.")}let L=q4(V4,"gat1",{c:J.clientId,r:Q,s:j,cc:G,st:Y,n:t(16).toString("base64url"),exp:Date.now()+qW}),H=this.options.consentPath??`${this.base}/consent`;return T4(`${this.issuer}${H}?request=${encodeURIComponent(L)}`,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??_(e).config.signInPath;return T4(`${Y}${Y.includes("?")?"&":"?"}redirect=${encodeURIComponent(Q)}`,302)}let J=await this.consent(Z,$);if(!J)return A("This authorization request has expired or is not valid. Start again from the application.");return new Response(J6(J,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:g1})}async decide(W){let Z=W.headers.get("origin");if(!(Z!==null&&Z!=="null"?Z===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return A("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 A("The decision must be a form post.");let J;try{J=new URLSearchParams(await I4(W,v4))}catch{return A("The decision is too large.")}let Q=J.get("request"),Y=c1(V4,"gat1",Q),K=c1(K6,"gcs1",J.get("csrf")),G=await this.sessionUser(W);if(!Y||!K||!G||K.t!==X6(Q)||K.u!==String(G.id))return A("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)=>P4(B,Y.r)))return A("The application is not registered with this server.");if(!await this.store.use(`ticket:${Y.n}`,Y.exp))return A("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=`${Y6}${t(32).toString("base64url")}`;return await this.store.saveCode({hash:g(X),clientId:z.clientId,userId:String(G.id),redirectUri:Y.r,codeChallenge:Y.cc,scopes:Y.s,resource:this.context.resource,familyId:t(16).toString("base64url"),expiresAt:Date.now()+G6}),this.redirectBack(Y.r,Y.st,{code:X},303)}async token(W){let Z=await j6(W),$=await this.authenticateClient(W,Z),J=await w4(`mcp-oauth-token:${$.clientId}`,IW);if(J!==null)throw new M("slow_down","Too many token requests.",429,{"Retry-After":String(J)});let Q=Z.get("resource");if(Q!==null&&!M6(Q,this.context.resource))throw new M("invalid_target","The resource is not this server's.");switch(Z.get("grant_type")){case"authorization_code":{let Y=Z.get("code")??"",K=Y.startsWith(Y6)?await this.store.findCode(g(Y)):null;if(!K||K.clientId!==$.clientId)throw new M("invalid_grant","The authorization code is not valid.");if(!await this.store.use(K.hash,K.expiresAt+G6))throw await this.store.revokeFamily(K.familyId),new M("invalid_grant","The authorization code was already used.");if(K.expiresAt<=Date.now())throw new M("invalid_grant","The authorization code expired.");if(Z.get("redirect_uri")!==null&&Z.get("redirect_uri")!==K.redirectUri)throw new M("invalid_grant","redirect_uri is not the one the code was issued to.");let G=Z.get("code_verifier");if(!G||!/^[A-Za-z0-9._~-]{43,128}$/.test(G)||!B6(AW(G),K.codeChallenge))throw new M("invalid_grant","The PKCE code_verifier does not match.");if(!await this.options.findUser(K.userId))throw new M("invalid_grant","The authorization code is not valid.");return await this.issue(K)}case"refresh_token":{let Y=Z.get("refresh_token")??"",K=Y.startsWith(C4)?await this.store.findToken(g(Y)):null;if(!K||K.kind!=="refresh"||K.clientId!==$.clientId)throw new M("invalid_grant","The refresh token is not valid.");if(K.expiresAt<=Date.now())throw new M("invalid_grant","The refresh token expired.");if(!await this.store.use(K.hash,K.expiresAt))throw await this.store.revokeFamily(K.familyId),new M("invalid_grant","The refresh token was already used.");if(K.resource!==this.context.resource)throw new M("invalid_grant","The refresh token was not issued for this server.");let 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 M("invalid_scope","A refresh can only narrow the scopes that were granted.");G=X}if(!await this.options.findUser(K.userId))throw new M("invalid_grant","The refresh token is not valid.");return await this.issue({...K,scopes:G})}default:throw new M("unsupported_grant_type","grant_type must be authorization_code or refresh_token.")}}async issue(W){let Z=Date.now(),$=this.scopeNames(),J=W.scopes.filter((G)=>$.includes(G)),Q=`${f4}${t(32).toString("base64url")}`,Y=`${C4}${t(32).toString("base64url")}`,K={clientId:W.clientId,userId:W.userId,scopes:J,resource:W.resource,familyId:W.familyId};return await this.store.saveToken({...K,hash:g(Q),kind:"access",expiresAt:Z+this.accessTtl*1000}),await this.store.saveToken({...K,hash:g(Y),kind:"refresh",expiresAt:Z+this.refreshTtl*1000}),O1({access_token:Q,token_type:"Bearer",expires_in:this.accessTtl,refresh_token:Y,scope:J.join(" ")})}async revoke(W){let Z=await j6(W),$=await this.authenticateClient(W,Z),J=Z.get("token")??"";if(J.startsWith(f4)||J.startsWith(C4)){let Q=await this.store.findToken(g(J));if(Q&&Q.clientId===$.clientId)await this.store.revokeFamily(Q.familyId)}return new Response(null,{status:200,headers:{"Cache-Control":"no-store"}})}async authenticateClient(W,Z){let $=/^Basic\s+([A-Za-z0-9+/=]+)$/i.exec(W.headers.get("authorization")??""),J=Z.get("client_id"),Q=Z.get("client_secret");if($){let K=Buffer.from($[1],"base64").toString("utf8"),G=K.indexOf(":");if(G<0)throw r(!0);let z=L6(K.slice(0,G));if(z===null)throw r(!0);if(J!==null&&J!==z)throw r(!0);if(J=z,Q=L6(K.slice(G+1)),Q===null)throw r(!0)}let Y=J?await this.store.findClient(J):null;if(!Y)throw r(Boolean($));if(Y.tokenEndpointAuthMethod==="none"){if(Q)throw r(Boolean($));return Y}if(!Q||!Y.clientSecretHash||!B6(g(Q),Y.clientSecretHash))throw r(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),T4(Q.href,J)}async sessionUser(W){let Z=new b4(W,{},"api",this.base).cookies;return await N6(_(e),{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 yW={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function z6(W,Z,$){if(Z===void 0)return $;if(!Number.isInteger(Z)||Z<60)throw Error(`McpOAuthServer: ${W} must be a whole number of seconds, at least 60.`);return Z}function g(W){return A4("sha256").update(W).digest("hex")}function X6(W){return A4("sha256").update(W).digest("base64url")}function AW(W){return A4("sha256").update(W).digest("base64url")}function B6(W,Z){let $=Buffer.from(W),J=Buffer.from(Z);return $.length===J.length&&PW($,J)}function O1(W,Z=200,$={}){return new Response(JSON.stringify(W),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache",...$}})}function T4(W,Z){return new Response(null,{status:Z,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function A(W,Z=400){return new Response(Q6(W),{status:Z,headers:g1})}function r(W){return new M("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function I4(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 j6(W){if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new M("invalid_request","Send the request as application/x-www-form-urlencoded.");let Z;try{Z=new URLSearchParams(await I4(W,v4))}catch{throw new M("invalid_request","The request is too large.")}for(let $ of new Set(Z.keys()))if(Z.getAll($).length>1)throw new M("invalid_request",`${$} was sent more than once.`);return Z}function F6(W,Z,$){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>Z||gW(W))throw new M("invalid_client_metadata",`${$} must be text of at most ${Z} characters.`);return W}function hW(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function U6(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function EW(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:"&&U6(Z))return null;return"must be https, or http on a loopback address"}function P4(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:"&&U6($)&&$.hostname===J.hostname&&$.pathname===J.pathname&&$.search===J.search&&!J.hash&&!J.username&&!J.password}function M6(W,Z){return W===Z||W===`${Z}/`}function gW(W){for(let Z=0;Z<W.length;Z++){let $=W.charCodeAt(Z);if($<32||$===127)return!0}return!1}function L6(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class x6{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 O6{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 h4(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:u1(Z.redirectUris),clientName:Z.clientName??null,clientUri:Z.clientUri??null,createdAt:p1(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:u1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:p1(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:u1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:p1(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 h4(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 X of J){if(Q.has(X.familyId))continue;if(!Y.has(X.familyId))Y.set(X.familyId,X)}if(Y.size===0)return[];let K=[...new Set([...Y.values()].map((X)=>X.clientId))],G=await this.clients.findMany({where:{clientId:{in:K}}}),z=new Map(G.map((X)=>[X.clientId,X]));return[...Y.values()].map((X)=>({familyId:X.familyId,clientId:X.clientId,clientName:z.get(X.clientId)?.clientName??null,clientUri:z.get(X.clientId)?.clientUri??null,scopes:u1(X.scopes),connectedAt:new Date(p1(X.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 u1(W){return Array.isArray(W)?W.map(String):[]}function p1(W){return W instanceof Date?W.getTime():new Date(W).getTime()}class R1 extends w{application;previous;dispatched=[];static install(W){let Z=W.resolved(w)?W.make(w):void 0;if(Z instanceof R1)return Z;let $=new R1(W,Z);return W.instance(w,$),$}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(w,this.previous);return}this.application.forget(w)}assertDispatched(W,Z){let $=S1(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 $=S1(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 ${E4(J.length)}: ${d1(J)}.`)}assertDispatchedTimes(W,Z,$){let J=S1(W),Q=this.matching(J,$);if(Q.length===Z)return;throw Error(`Expected ${J}${$?" matching the predicate":""} to have been dispatched ${E4(Z)}, but it was dispatched ${E4(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"}: ${d1(this.dispatched)}.`)}matching(W,Z){return this.dispatched.filter(($)=>S1($.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}: ${d1($)}.`;return`Dispatched: ${d1(this.dispatched)}.`}}function S1(W){return W.name}function E4(W){return`${W} ${W===1?"time":"times"}`}function d1(W){return W.map(mW).join(", ")}function mW(W){let Z=S1(W.event.constructor),$=W.args??Object.values({...W.event});return`${Z}(${$.map(cW).join(", ")})`}function cW(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class l1{static name="unset";static afterCommit=!1;static dispatch(...W){S6(this),_(w).dispatch(new this(...W),W)}static dispatchAndWait(...W){return S6(this),_(w).dispatchAndWait(new this(...W),W)}static fake(){return R1.install(uW())}}function uW(){try{return _()}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 S6(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 l1{constructor(){super();Object.defineProperty(this,g4,{value:!0,enumerable:!1})}broadcastAs(){return this.constructor.name}broadcastWith(){return}channel(W,...Z){return{topic:R6(W,Z[0]??{}),pattern:W}}}function V6(){try{let W=_();if(typeof W?.bound==="function"&&W.bound(e))return W.make(e).config.emailCode}catch{}return}function pW(){return f6(V6())}function dW(W){return C6(W,V6())}function lW(W){let Z=null;try{let Y=_();if(typeof Y?.bound==="function"&&Y.bound(m4))Z=_(m4).resolver??null}catch{Z=null}if(Z)return Z.publicOrigin(W);let $=new URL(W.url),J=W.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return`${J==="http"||J==="https"?J:$.protocol.slice(0,-1)}://${$.host}`}function nW(W,Z){let $=typeof W==="string"?W.trim().replace(/\/+$/,""):"",J=URL.canParse($)?new URL($):null;if(!J||J.protocol!=="http:"&&J.protocol!=="https:"||J.origin!==$)throw Error(`${Z}: resolve() returned origin ${JSON.stringify(W)}, which is not an http(s) origin such as https://example.com.`);return $}var T6=new WeakMap;function p(W,Z,$){if(!$.resolve)return Promise.resolve({clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.staticRedirectUri()});let J=Z?.rawRequest;if(!Z||!J)return Promise.resolve(null);let Q=T6.get(W);if(!Q)Q=new WeakMap,T6.set(W,Q);let Y=Q.get(J);if(Y)return Y;let K=$.resolve,G=(async()=>{let z=await K({req:Z,origin:lW(J)});if(z===null||z===void 0)return null;let X=z.origin!==void 0?nW(z.origin,$.name):$.staticOrigin();return{clientId:z.clientId??$.clientId,clientSecret:z.clientSecret??$.clientSecret,redirectUri:`${X}${$.redirectPath}`}})();return Q.set(J,G),G.catch(()=>Q.delete(J)),G}var iW={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 sW(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class P6 extends m{config;constructor(W={}){super();this.config={...iW,...W}}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"GoogleOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GoogleOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}authorizationUrl(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:W.redirectUri,client_id:W.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 U("missing_code");let J=this.config.resolve?await this.clientFor(W):this.staticClient();if(!J)throw new U("unknown_provider");let Q=new URLSearchParams({code:$,client_id:J.clientId,client_secret:J.clientSecret,grant_type:"authorization_code",redirect_uri:J.redirectUri});if(Z?.codeVerifier)Q.set("code_verifier",Z.codeVerifier);let Y=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Q.toString()}),K=await Y.json().catch(()=>({}));if(!Y.ok||typeof K?.access_token!=="string"||K.access_token==="")throw console.error("Google OAuth error: token exchange failed",K?.error??Y.status),new U(sW(K?.error,"exchange_failed"));let z=await(await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${K.access_token}`}})).json().catch(()=>({}));if(typeof z.sub!=="string"||z.sub==="")return console.error("Google OAuth error: sub not found in user info response",z),{};if(!z.email)console.error("Google OAuth error: email not found in user info response",z);return{providerId:z.sub,name:z.name,email:z.email,emailVerified:z.email_verified===!0||z.email_verified==="true"}}}var oW="https://github.com/login/oauth/authorize",aW="https://github.com/login/oauth/access_token",b6="https://api.github.com";function tW(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class w6 extends m{config;constructor(W={}){super();this.config={clientId:process.env.GITHUB_CLIENT_ID??"",clientSecret:process.env.GITHUB_CLIENT_SECRET??"",redirectPath:"/auth/oauth/github/callback",scope:"read:user user:email",authorizationParams:{},...W}}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"GitHubOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GitHubOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(oW),J={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,scope:this.config.scope,response_type:"code"};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 U("missing_code");let J=this.config.resolve?await this.clientFor(W):this.staticClient();if(!J)throw new U("unknown_provider");let Q=new URLSearchParams({client_id:J.clientId,client_secret:J.clientSecret,code:$,redirect_uri:J.redirectUri});if(Z?.codeVerifier)Q.set("code_verifier",Z.codeVerifier);let Y=await fetch(aW,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:Q.toString()}),K=await Y.json().catch(()=>({}));if(!Y.ok||typeof K?.access_token!=="string"||K.access_token==="")throw console.error("GitHub OAuth error: token exchange failed",K?.error??Y.status),new U(tW(K?.error,"exchange_failed"));let G={Accept:"application/vnd.github+json",Authorization:`Bearer ${K.access_token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"gemi"},z=await fetch(`${b6}/user`,{headers:G}),X=await z.json().catch(()=>({}));if(!z.ok||typeof X?.id!=="number"||!Number.isSafeInteger(X.id))return console.error("GitHub OAuth error: no user id in the /user response",z.status),{};let B=typeof X.login==="string"&&X.login!==""?X.login:void 0,j=typeof X.name==="string"&&X.name!==""?X.name:B,L=await this.primaryVerifiedEmail(G),H=typeof X.email==="string"&&X.email!==""?X.email:void 0;return{providerId:String(X.id),username:B,name:j,...L?{email:L,emailVerified:!0}:H?{email:H,emailVerified:!1}:{}}}async primaryVerifiedEmail(W){let Z=await fetch(`${b6}/user/emails`,{headers:W}).catch(()=>null);if(!Z?.ok){console.error("GitHub OAuth error: could not read /user/emails",Z?.status);return}let $=await Z.json().catch(()=>null);if(!Array.isArray($))return;let J=$.find((Q)=>Q?.primary===!0&&Q.verified===!0);return typeof J?.email==="string"&&J.email!==""?J.email:void 0}}var d="https://api.x.com/2/",Q1="https://api.x.com/labs/2/",l="https://api.x.com/1.1/",c="https://upload.x.com/1.1/",q6="https://stream.x.com/1.1/",Y1="https://ads-api.x.com/12/",K1="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 u4 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 G1=c4;class x extends G1{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 p4 extends x{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 d4 extends x{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 n;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(n||(n={}));var _1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(_1||(_1={}));class n1 extends Error{constructor(){super(...arguments);this.error=!0}}class k1 extends n1{constructor(W,Z){super(W);this.type=_1.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 f1 extends n1{constructor(W,Z){super(W);this.type=_1.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 C1 extends n1{constructor(W,Z){super(W);if(this.type=_1.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:W1.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(W1.AuthTimestampInvalid,W1.AuthenticationFail,W1.BadAuthenticationData,W1.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var W1;(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"})(W1||(W1={}));var v6;(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"})(v6||(v6={}));var F;(function(W){W.Connected="connected",W.ConnectError="connect error",W.ConnectionError="connection error",W.ConnectionClosed="connection closed",W.ConnectionLost="connection lost",W.ReconnectAttempt="reconnect attempt",W.Reconnected="reconnected",W.ReconnectError="reconnect error",W.ReconnectLimitExceeded="reconnect limit exceeded",W.DataKeepAlive="data keep-alive",W.Data="data event content",W.DataError="data twitter error",W.TweetParseError="data tweet parse error",W.Error="stream error"})(F||(F={}));class V1{constructor(W){this.value=W}}import*as D0 from"fs";var R={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function l4(W){let Z={value:void 0,promise:W().then(($)=>{return Z.value=$,$})};return Z}function i1(W){if(Array.isArray(W))return W;return[W]}function y6(W){for(let Z of Object.keys(W))if(W[Z]===void 0)delete W[Z]}function s1(W){return typeof W==="object"&&"errors"in W&&!("data"in W)}function T1(W){if(Array.isArray(W)&&W.length>1)return!0;return W.toString().includes(",")}var I6=new Set;function n4(W){if(typeof console>"u"||!console.warn||!R.deprecationWarnings)return;let Z=`${W.instance}-${W.method}-${W.problem}`;if(I6.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."),I6.add(Z)}import{EventEmitter as $5}from"events";import{request as rW}from"https";import*as f from"zlib";import{EventEmitter as eW}from"events";class A6{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(R.debug)R.logger.log("Request error:",W);return new k1("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 f1(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(R.debug)R.logger.log(`Request failed with code ${J}, data:`,Z),R.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 C1(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 $=f.createBrotliDecompress({flush:f.constants.BROTLI_OPERATION_FLUSH,finishFlush:f.constants.BROTLI_OPERATION_FLUSH});return W.pipe($),$}if(Z==="gzip"){let $=f.createGunzip({flush:f.constants.Z_SYNC_FLUSH,finishFlush:f.constants.Z_SYNC_FLUSH});return W.pipe($),$}if(Z==="deflate"){let $=f.createInflate({flush:f.constants.Z_SYNC_FLUSH,finishFlush:f.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(R.debug)R.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),R.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(R.debug)R.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(R.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),W.search)R.logger.log("Request parameters:",[...W.searchParams.entries()].map(([Z,$])=>`${Z}: ${$}`));if(this.requestData.body)R.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(R.debug)this.debugRequest();this.req=rW({...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 eW,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 o1($,{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 P1=A6;import{EventEmitter as W5}from"events";class h6 extends W5{constructor(W){super();this.stream=W,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),W.on(F.Data,this.onStreamData),W.on(F.ConnectionError,this.onStreamError),W.on(F.TweetParseError,this.onStreamError),W.on(F.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let W=this.stack;return this.stack=[],W}destroy(){this.removeAllListeners(),this.stream.off(F.Data,this.onStreamData),this.stream.off(F.ConnectionError,this.onStreamError),this.stream.off(F.TweetParseError,this.onStreamError),this.stream.off(F.ConnectionClosed,this.onStreamError)}emitEvent(W,Z){this.emit("event",{type:W,payload:Z})}onStreamError(W){this.emitEvent("error",W)}onStreamData(W){this.stack.push(W),this.emitEvent("data",W)}}var E6=h6;import{EventEmitter as Z5}from"events";class a1 extends Z5{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(Z1.ParsedData,Y);continue}}catch(Y){this.emit(Z1.ParseError,Y)}}J++}this.currentMessage=W.slice($,Z)}reset(){this.currentMessage=""}}var Z1;(function(W){W.ParsedData="parsed data",W.ParseError="parse error"})(Z1||(Z1={}));var g6=[5,15,30,60,90,120,180,300,600,900],J5=(W)=>W>g6.length?901000:g6[W-1]*1000;class m6 extends $5{constructor(W,Z){super();if(this.requestData=W,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=J5,this.parser=new a1,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),Z)this.req=Z.req,this.res=Z.res,this.originalResponse=Z.originalResponse,this.initEventsFromRequest()}on(W,Z){return super.on(W,Z)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let W=(Z)=>{this.emit(F.ConnectionError,Z),this.emit(F.Error,{type:F.ConnectionError,error:Z,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",W),this.res.on("error",W),this.res.on("close",()=>W(Error("Connection closed by Twitter."))),this.res.on("data",(Z)=>{if(this.resetKeepAliveTimeout(),Z.toString()===`\r
67
- `)return this.emit(F.DataKeepAlive);this.parser.push(Z.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let W=this.requestData.payloadIsError;this.parser.on(Z1.ParsedData,(Z)=>{if(W&&W(Z))this.emit(F.DataError,Z),this.emit(F.Error,{type:F.DataError,error:Z,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(F.Data,Z)}),this.parser.on(Z1.ParseError,(Z)=>{this.emit(F.TweetParseError,Z),this.emit(F.Error,{type:F.TweetParseError,error:Z,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(F.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){if(this.keepAliveTimeout)clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0}unbindRetryTimeout(){if(this.retryTimeout)clearTimeout(this.retryTimeout),this.retryTimeout=void 0}closeWithoutEmit(){if(this.unbindTimeouts(),this.res)this.res.removeAllListeners(),this.res.destroy();if(this.req)this.req.removeAllListeners(),this.req.destroy()}close(){this.emit(F.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let Z=await new P1(this.requestData).makeRequestAsStream(),$=this.eventNames();for(let J of $){let Q=this.listeners(J);for(let Y of Q)Z.on(J,Y)}return Z}async connect(W={}){if(typeof W.autoReconnect<"u")this.autoReconnect=W.autoReconnect;if(typeof W.autoReconnectRetries<"u")this.autoReconnectRetries=W.autoReconnectRetries==="unlimited"?1/0:W.autoReconnectRetries;if(typeof W.keepAliveTimeout<"u")this.keepAliveTimeoutMs=W.keepAliveTimeout==="disable"?1/0:W.keepAliveTimeout;if(typeof W.nextRetryTimeout<"u")this.nextRetryTimeout=W.nextRetryTimeout;this.unbindTimeouts();try{await this.reconnect()}catch(Z){if(this.emit(F.ConnectError,0),this.emit(F.Error,{type:F.ConnectError,error:Z,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,Z);else throw Z}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let W=!0;if(this.req)W=!1,this.closeWithoutEmit();let{req:Z,res:$,originalResponse:J}=await new P1(this.requestData).makeRequestAndResolveWhenReady();this.req=Z,this.res=$,this.originalResponse=J,this.emit(W?F.Connected:F.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(W=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(F.ConnectionClosed);return}if(W>=this.autoReconnectRetries){this.emit(F.ReconnectLimitExceeded),this.emit(F.ConnectionClosed);return}try{this.emit(F.ReconnectAttempt,W),await this.reconnect()}catch(Z){this.emit(F.ReconnectError,W),this.emit(F.Error,{type:F.ReconnectError,error:Z,message:`Reconnect error - ${W+1} attempts made yet.`}),this.makeAutoReconnectRetry(W,Z)}}makeAutoReconnectRetry(W,Z){let $=this.nextRetryTimeout(W+1,Z);this.retryTimeout=setTimeout(()=>{this.onConnectionError(W+1)},$)}async*[Symbol.asyncIterator](){let W=new E6(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 o1=m6;function c6(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 u6(W,Z,$,J){let Q;if(J instanceof k1||J instanceof f1)Q=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:J});else if(J instanceof C1)Q=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:J});if(Q&&Q instanceof V1)return Q.value;return Promise.reject(J)}import*as l6 from"crypto";class q{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 l6.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;$+=q.percentEncode(J.key)+'="'+q.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 q.percentEncode(this.consumerKeys.secret)+"&"+q.percentEncode(W||"")}getBaseString(W,Z){return W.method.toUpperCase()+"&"+q.percentEncode(this.getBaseUrl(W.url))+"&"+q.percentEncode(this.getParameterString(W,Z))}getParameterString(W,Z){let $=d6(K5(p6(Z,p6(W.data,Y5(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 b1=q;function p6(W,Z){return{...W||{},...Z||{}}}function d6(W){return Object.keys(W).sort().map((Z)=>({key:Z,value:W[Z]}))}function Q5(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 Y5(W){let Z=W.split("?");if(Z.length===1)return{};return Q5(Z[1])}function K5(W){let Z={};for(let $ in W){let J=W[$];if(J&&Array.isArray(J))J=J.map((Q)=>q.percentEncode(Q));else J=q.percentEncode(J);Z[q.percentEncode($)]=J}return Z}class v{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,v.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?v.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+": "+i1(K).join("; ")+v.LINE_BREAK}return"--"+this.getBoundary()+v.LINE_BREAK+Q+v.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+v.LINE_BREAK)}}v.LINE_BREAK=`\r
68
- `;v.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?"&":"?")+`${b1.percentEncode(Q)}=${b1.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 v;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 T=i4;import*as n6 from"crypto";class $1{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url(n6.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 z1{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)T.setBodyLengthHeader(G,K.body);if(($=this.clientSettings.plugins)===null||$===void 0?void 0:$.length)await this.applyPreRequestHooks(W,K,G);let X=new P1({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(c6(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)T.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 o1(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 b1({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 V1)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 "+$1.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let K=Z?T.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)T.applyRequestParametersToUrl(X,G);let j=T.formatQueryToString($);if(T.moveUrlQueryParamsIntoObject(X,j),!(J instanceof Buffer))y6(J);let L=Y!==null&&Y!==void 0?Y:T.autoDetectBodyType(X);if(K!==!1){let H=z1.BODY_METHODS.has(Z)&&L==="url";Q=this.writeAuthHeaders({headers:Q,bodyInSignature:H,method:Z,query:j,url:X,body:J})}if(z1.BODY_METHODS.has(Z))z=T.constructBodyParams(J,Q,L)||void 0;return T.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(u6.bind(this,W,Z,$))}}z1.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class i{constructor(W,Z={}){if(this._currentUser=null,this._currentUserV2=null,W instanceof i)this._requestMaker=W._requestMaker;else this._requestMaker=new z1(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=l4(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:l})),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=l4(()=>this.get("users/me",void 0,{prefix:d})),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 P extends i{constructor(W){if(!(W instanceof i))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(W)}}class X1 extends G1{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 s4 extends X1{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class o4 extends X1{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class t1 extends X1{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class a4 extends X1{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class r1 extends X1{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class t4 extends x{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 r4 extends x{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 e4 extends x{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 W0 extends x{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 Z0 extends x{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 $0 extends x{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 J0 extends G1{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 e1 extends x{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 Q0 extends e1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class W4 extends x{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 Y0 extends W4{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class K0 extends W4{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class G0 extends W4{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class z0 extends x{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 X0 extends z0{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class B0 extends z0{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class B1 extends P{constructor(){super(...arguments);this._prefix=l}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 s4({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 o4({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 t1({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 t1({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 r1({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 r1({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 t4({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 r4({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 Z0({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 e4({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 W0({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 $0({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 J0({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 e1({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 Q0({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 X0({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 Y0({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 K0({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 a4({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 B0({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 G0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}mediaInfo(W){return this.get("media/upload.json",{command:"STATUS",media_id:W},{prefix:c})}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=i1(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 Z4(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 s from"fs";async function j0(W){let Z=await F0(W);if(typeof Z==="number")return new Promise(($,J)=>{s.readFile(Z,(Q,Y)=>{if(Q)return J(Q);$(Y)})});else if(Z instanceof Buffer)return Z;else return Z.readFile()}function F0(W){if(typeof W==="string")return s.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 i6(W){if(typeof W==="number")return(await new Promise(($,J)=>{s.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 s6(W,Z,$){if(typeof $==="string")return $;else if(typeof W==="string"&&!Z)return G5(W);else if(typeof Z==="string")return z5(Z);throw Error("You must specify type if file is a file handle or Buffer.")}function G5(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 n4({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 z5(W){if(n4({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 o6(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 M0(W){return new Promise((Z)=>setTimeout(Z,W*1000))}async function L0(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)=>{s.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 N0="media/upload.json";class j1 extends B1{constructor(){super(...arguments);this._prefix=l}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 j0(W),...Z};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,Z={}){let $={tweet_mode:"extended",image:await j0(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&&T1(W.user_id)||W.screen_name&&T1(W.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,W)}removeListMembers(W){let $=W.user_id&&T1(W.user_id)||W.screen_name&&T1(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:c,forceBodyMode:"json"})}createMediaSubtitles(W,Z){return this.post("media/subtitles/create.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z}},{prefix:c,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:c,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(N0,{command:"INIT",total_bytes:G,media_type:z,media_category:K,additional_owners:Z.additionalOwners,shared:Z.shared?!0:void 0},{prefix:c});await this.mediaChunkedUpload(Y,Q,X.media_id_string,Z.maxConcurrentUploads);let B=await this.post(N0,{command:"FINALIZE",media_id:X.media_id_string},{prefix:c});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")D0.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 M0($.check_after_secs);else await M0(5)}}async getUploadMediaRequirements(W,{mimeType:Z,type:$,target:J,longVideo:Q}={}){let Y;try{Y=await F0(W);let K=s6(W,$,Z),G;if(K===D.Mp4&&(!Z&&!$&&J!=="dm"||Q))G="amplify_video";else G=o6(K,J!==null&&J!==void 0?J:"tweet");return{fileHandle:Y,mediaCategory:G,fileSize:await i6(Y),mimeType:K}}catch(K){if(typeof W==="number")D0.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 L0(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(N0,{command:"APPEND",media_id:$,segment_index:Q,media:B},{prefix:c});X.add(j),j.then(()=>{X.delete(j)}),Q++}if(X.size>=J)await Promise.race(X);[K,G]=await L0(W,Z,z,Y),z+=G}await Promise.all([...X])}}class a6 extends j1{constructor(){super(...arguments);this._prefix=l}get readWrite(){return this}sendDm({recipient_id:W,custom_profile_id:Z,...$}){let J={event:{type:n.Create,[n.Create]:{target:{recipient_id:W},message_data:$}}};if(Z)J.event[n.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 p4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDm(W,Z){let $={[n.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 d4({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[n.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 Z4=a6;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 $4 extends u4{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 h extends $4{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 H0 extends $4{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 F1 extends h{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 U0 extends H0{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class x0 extends H0{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class O0 extends F1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class S0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class R0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class _0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class k0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class f0 extends h{get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class C0 extends f0{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class V0 extends f0{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class u extends h{getItemArray(){return this.users}get users(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class T0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class P0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class b0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class w0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class q0 extends u{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class v0 extends u{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class I0 extends u{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class y0 extends u{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class J4 extends h{getItemArray(){return this.lists}get lists(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class A0 extends J4{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class h0 extends J4{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class E0 extends J4{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class M1 extends P{constructor(){super(...arguments);this._prefix=Q1}}class Q4 extends h{getItemArray(){return this.events}get events(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class g0 extends Q4{constructor(){super(...arguments);this._endpoint="dm_events"}}class m0 extends Q4{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class c0 extends Q4{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class L1 extends P{constructor(){super(...arguments);this._prefix=d}get labs(){if(this._labs)return this._labs;return this._labs=new M1(this)}async search(W,Z={}){let $=typeof W==="string"?{...Z,query:W}:{...W},J=await this.get("tweets/search/recent",$,{fullResponse:!0});return new U0({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 x0({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 y0({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 I0({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 S0({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 R0({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 _0({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 O0({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 k0({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 b0({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 w0({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 C0({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 T0({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 P0({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 A0({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 E0({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 V0({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 q0({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 v0({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 g0({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 m0({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:s1,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:s1,autoConnect:W})}sample10Stream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample10/stream",Z,{payloadIsError:s1,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
- `));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 N1 extends M1{constructor(){super(...arguments);this._prefix=Q1}get readOnly(){return this}}class D1 extends L1{constructor(){super(...arguments);this._prefix=d}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new N1(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*$,L=Math.min(j+$,W.length),H=z.slice(j,L),S=Buffer.from(H),o={segment_index:B,media:S};await this.post(`media/upload/${K}/append`,o,{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 t6 extends N1{constructor(){super(...arguments);this._prefix=Q1}get readWrite(){return this}}var r6=t6;class e6 extends D1{constructor(){super(...arguments);this._prefix=d}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new r6(this)}}var WW=e6;class w1 extends i{get v1(){if(this._v1)return this._v1;return this._v1=new B1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new L1(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?$:$1.generateRandomString(32),Y=$1.getCodeVerifier(),K=$1.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};T.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 q1 extends w1{get v1(){if(this._v1)return this._v1;return this._v1=new j1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new D1(this)}get readOnly(){return this}}class Y4 extends P{constructor(){super(...arguments);this._prefix=Y1}}class K4 extends Y4{constructor(){super(...arguments);this._prefix=Y1}get readOnly(){return this}}class G4 extends P{constructor(){super(...arguments);this._prefix=K1}}class z4 extends G4{constructor(){super(...arguments);this._prefix=K1}get readOnly(){return this}}class ZW extends z4{constructor(){super(...arguments);this._prefix=K1}get readWrite(){return this}}var $W=ZW;class JW extends K4{constructor(){super(...arguments);this._prefix=Y1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new $W(this)}}var QW=JW;class X4 extends q1{get v1(){if(this._v1)return this._v1;return this._v1=new Z4(this)}get v2(){if(this._v2)return this._v2;return this._v2=new WW(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new QW(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 X5={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class YW extends m{config;client;constructor(W={}){super();this.config={...X5,...W},this.client=new X4({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"XOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!Z)throw Error("XOAuthProvider needs the state and PKCE challenge gemi passes.");if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("XOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL("https://x.com/i/oauth2/authorize"),J={response_type:"code",client_id:W.clientId,redirect_uri:W.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 U("missing_code");if(!Z?.codeVerifier)throw new U("invalid_state");let J=this.config.resolve?await this.clientFor(W):this.staticClient();if(!J)throw new U("unknown_provider");let Q=this.config.resolve?new X4({clientId:J.clientId,clientSecret:J.clientSecret}):this.client,Y;try{Y=await Q.loginWithOAuth2({code:$,codeVerifier:Z.codeVerifier,redirectUri:J.redirectUri})}catch(j){throw console.error("X OAuth error: token exchange failed",j),new U("exchange_failed")}let{data:K}=await Y.client.v2.me({"user.fields":["name","username","entities"]}),{name:G,email:z,id:X="",username:B}=K??{};return{name:G,email:z,username:B,providerId:X}}}var GW=["instagram_business_basic"],E={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 B4(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 F4(W.tokenUrl??E.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:u0(J?.user_id),permissions:Array.isArray(Y)?Y.map(String):typeof Y==="string"?Y.split(/[\s,]+/).filter(Boolean):null}}async function zW(W){let Z=new URL("/access_token",W.graphUrl??E.graphUrl);return Z.searchParams.set("grant_type","ig_exchange_token"),Z.searchParams.set("client_secret",W.clientSecret),Z.searchParams.set("access_token",W.accessToken),BW(await F4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function XW(W){let Z=new URL("/refresh_access_token",W.graphUrl??E.graphUrl);return Z.searchParams.set("grant_type","ig_refresh_token"),Z.searchParams.set("access_token",W.accessToken),BW(await F4(Z.toString(),"token refresh",{method:"GET"}))}async function j4(W){let Z=W.graphApiVersion?`/${W.graphApiVersion.replace(/^\/+|\/+$/g,"")}`:"",$=new URL(`${Z}/me`,W.graphUrl??E.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 F4($.toString(),"profile request",{method:"GET"}),Q=Array.isArray(J.data)?J.data[0]:J,Y=u0(Q?.user_id);if(!Y)throw new I("Instagram's /me answered without a user_id.",200);let K={user_id:Y},G=u0(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 BW(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 F4(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=p0(await J.text().catch(()=>""));if(!J.ok){let Y=Q.error??{},K=KW(Q.error_type)??KW(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 p0(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 u0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function KW(W){return typeof W==="string"&&W!==""?W:void 0}class jW extends m{createUsersWithoutEmail=!0;linkByEmail=!1;config;constructor(W={}){super();this.config={clientId:process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:GW,redirectPath:"/auth/oauth/instagram/callback",authorizationParams:{},...W}}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"InstagramOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("InstagramOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(this.config.authorizeUrl??E.authorizeUrl),J={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.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 U("missing_code");let $=this.config.resolve?await this.clientFor(W):this.staticClient();if(!$)throw new U("unknown_provider");let J;try{let Q=await B4({code:Z,clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.redirectUri,tokenUrl:this.config.tokenUrl});J=await j4({accessToken:Q.accessToken,graphUrl:this.config.graphUrl,graphApiVersion:this.config.graphApiVersion,fields:["user_id","username","name"]})}catch(Q){if(Q instanceof I)throw console.error(`Instagram OAuth error: ${Q.message}`),new U("exchange_failed");throw Q}return{providerId:J.user_id,username:J.username,name:J.name||J.username}}}import{createHmac as B5,timingSafeEqual as j5}from"crypto";class y extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function F5(W,Z,$={}){if(!Z)throw Error("parseMetaSignedRequest needs the app secret.");if(typeof W!=="string")throw new y("malformed","No signed_request was given.");let J=W.indexOf(".");if(J<=0||J===W.length-1||W.indexOf(".",J+1)!==-1)throw new y("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 y("malformed","A signed_request is base64url.");let K=B5("sha256",Z).update(Y).digest(),G=Buffer.from(Q,"base64url");if(G.length!==K.length||!j5(G,K))throw new y("bad_signature","The signed_request's signature does not match the app secret.");let z;try{let L=Buffer.from(Y,"base64url").toString("utf8").replace(/("user_id"\s*:\s*)(-?\d+)(?=\s*[,}])/g,'$1"$2"');z=JSON.parse(L)}catch{throw new y("malformed","The signed_request's payload is not JSON.")}if(!z||typeof z!=="object")throw new y("malformed","The signed_request's payload is not an object.");if(String(z.algorithm??"").toUpperCase()!=="HMAC-SHA256")throw new y("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 y("expired","The signed_request has expired.");let j=z.user_id;if((typeof j!=="string"||j==="")&&typeof j!=="number")throw new y("missing_user","The signed_request names no user.");return{...z,algorithm:String(z.algorithm),user_id:String(j)}}var M5=86400000;class L4 extends d0{instagram;constructor(W={}){let Z={authorizeUrl:W.authorizeUrl??E.authorizeUrl,tokenUrl:W.tokenUrl??E.tokenUrl,graphUrl:W.graphUrl??E.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:L5,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<M5){if($.reason==="rejected")throw new v1("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let J=await M4("refresh_failed",()=>XW({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 M4("exchange_failed",()=>B4({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await M4("exchange_failed",()=>zW({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),J=await M4("exchange_failed",()=>j4({accessToken:$.accessToken,graphUrl:this.instagram.graphUrl,graphApiVersion:this.instagram.graphApiVersion}));return{accessToken:$.accessToken,refreshToken:null,tokenType:$.tokenType,expiresAt:$.expiresIn===null?null:new Date(Date.now()+$.expiresIn*1000),scopes:Z.permissions??this.config.scopes,providerAccountId:J.user_id,profile:{...J}}}refresh(){return Promise.reject(new v1("refresh_failed","Instagram connections renew the access token itself; call connection.refresh()."))}}async function L5(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 M4(W,Z){try{return await Z()}catch($){if($ instanceof I)throw new v1(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}class O extends Error{code;status;graphCode;graphSubcode;containerId;constructor(W,Z,$={}){super(Z);this.code=W;this.name="InstagramPublishError",this.status=$.status,this.graphCode=$.graphCode,this.graphSubcode=$.graphSubcode,this.containerId=$.containerId}}var C={captionLength:2200,hashtags:30,mentions:20,userTags:20,carouselMin:2,carouselMax:10},FW="instagram_business_content_publish",N5={for(W,Z={}){return new i0(W,Z)}};class i0{connection;version;pollIntervalMs;maxPollIntervalMs;timeoutMs;constructor(W,Z={}){this.connection=W;let $=W.connectionProvider();if(!($ instanceof L4))throw TypeError(`Instagram.for() takes an Instagram connection; "${W.provider}" is not an InstagramConnectionProvider.`);let J=Z.graphApiVersion??$.instagram.graphApiVersion;this.version=J?`/${J.replace(/^\/+|\/+$/g,"")}`:"",this.pollIntervalMs=Z.pollIntervalMs??2000,this.maxPollIntervalMs=Z.maxPollIntervalMs??1e4,this.timeoutMs=Z.timeoutMs??300000}async publishImage(W,Z={}){if(I1("imageUrl",W.imageUrl),n0(W.caption),W.altText!==void 0&&typeof W.altText!=="string")k("altText must be a string.");if(W.userTags!==void 0)V5(W.userTags);let $=this.start(Z),J=await this.createContainer({image_url:W.imageUrl,caption:W.caption,alt_text:W.altText,user_tags:W.userTags?JSON.stringify(W.userTags):void 0,location_id:W.locationId},$);return this.publishContainer(J,!1,$)}async publishCarousel(W,Z={}){let $=W.items;if(!Array.isArray($)||$.length<C.carouselMin||$.length>C.carouselMax)k(`A carousel takes ${C.carouselMin} to ${C.carouselMax} items.`);$.forEach((G,z)=>DW(`items[${z}]`,G)),n0(W.caption);let J=this.start(Z),Q=[];for(let G of $)Q.push(await this.createContainer(G.videoUrl!==void 0?{media_type:"VIDEO",video_url:G.videoUrl,is_carousel_item:"true"}:{image_url:G.imageUrl,is_carousel_item:"true"},J));for(let[G,z]of $.entries())if(z.videoUrl!==void 0)await this.waitUntilFinished(Q[G],J);let Y=$.some((G)=>G.videoUrl!==void 0),K=await this.createContainer({media_type:"CAROUSEL",children:Q.join(","),caption:W.caption},J);return this.publishContainer(K,Y,J)}async publishReel(W,Z={}){if(I1("videoUrl",W.videoUrl),W.coverUrl!==void 0)I1("coverUrl",W.coverUrl);if(n0(W.caption),W.thumbOffset!==void 0&&!(Number.isInteger(W.thumbOffset)&&W.thumbOffset>=0))k("thumbOffset must be a whole number of milliseconds, 0 or more.");let $=this.start(Z),J=await this.createContainer({media_type:"REELS",video_url:W.videoUrl,caption:W.caption,cover_url:W.coverUrl,share_to_feed:W.shareToFeed===void 0?void 0:String(W.shareToFeed),thumb_offset:W.thumbOffset===void 0?void 0:String(W.thumbOffset)},$);return this.publishContainer(J,!0,$)}async publishStory(W,Z={}){DW("story",W);let $=this.start(Z),J=W.videoUrl!==void 0,Q=await this.createContainer(J?{media_type:"STORIES",video_url:W.videoUrl}:{media_type:"STORIES",image_url:W.imageUrl},$);return this.publishContainer(Q,J,$)}async publishingLimit(W={}){let Z=this.start(W),$=await this.call("publishing limit request",`/${this.accountId()}/content_publishing_limit?fields=quota_usage,config`,void 0,Z),J=Array.isArray($.data)?$.data[0]:$,Q=J?.config??{},Y=l0(J?.quota_usage,0),K=l0(Q.quota_total,100);return{quotaUsage:Y,quotaTotal:K,quotaDurationSeconds:l0(Q.quota_duration,86400),remaining:Math.max(0,K-Y)}}async containerStatus(W,Z={}){return this.readStatus(W,this.start(Z))}start(W){if(W.signal?.throwIfAborted(),!this.connection.hasScopes(FW))throw new O("permission_denied",`The Instagram connection was not granted ${FW}; connect it again with that scope.`);return{signal:W.signal,deadline:Date.now()+(W.timeoutMs??this.timeoutMs)}}accountId(){let W=this.connection.providerAccountId;if(!W)throw new O("invalid_input","The Instagram connection has no account id (providerAccountId).");return W}async createContainer(W,Z){let $=await this.call("media container request",`/${this.accountId()}/media`,W,Z);return LW($,"media container request")}async publishContainer(W,Z,$){try{if(Z)await this.waitUntilFinished(W,$);let J=await this.publishOnce(W,Z,$);return{mediaId:J,permalink:await this.permalink(J,$)}}catch(J){throw J instanceof O?f5(J,W):J}}async publishOnce(W,Z,$){try{return await this.mediaPublish(W,$)}catch(J){if(!(J instanceof O))throw J;if(J.code==="transient"){let{statusCode:Q}=await this.readStatus(W,$);if(Q==="PUBLISHED")throw new O("unconfirmed","Instagram's media_publish failed, but the container reads PUBLISHED: the post is probably live. Do not publish it again.",{status:J.status,graphCode:J.graphCode,graphSubcode:J.graphSubcode});if(Q!=="FINISHED")throw J;return this.mediaPublish(W,$)}if(k5(J)&&!Z)return await this.waitUntilFinished(W,$),this.mediaPublish(W,$);throw J}}async mediaPublish(W,Z){let $=await this.call("media_publish request",`/${this.accountId()}/media_publish`,{creation_id:W},Z,{retry:!1});return LW($,"media_publish request")}async permalink(W,Z){try{let $=await this.call("permalink request",`/${W}?fields=permalink`,void 0,Z,{retry:!1});return typeof $.permalink==="string"?$.permalink:void 0}catch{return}}async readStatus(W,Z){if(!/^\d+$/.test(W))k("A container id is a string of digits.");let $=await this.call("container status request",`/${W}?fields=status_code,status`,void 0,Z),J=$.status_code;if(typeof J!=="string"||!D5.has(J))throw new O("graph_error","Instagram's container status answered without a known status_code.",{status:200,containerId:W});let Q={id:W,statusCode:J};if(typeof $.status==="string"&&$.status!=="")Q.status=xW($.status);return Q}async waitUntilFinished(W,Z){let $=this.pollIntervalMs;for(;;){let{statusCode:J,status:Q}=await this.readStatus(W,Z);if(J==="FINISHED")return;if(J==="PUBLISHED")throw new O("invalid_input","That media container has been published already.",{containerId:W});if(J==="ERROR")throw new O("invalid_media",`Instagram could not process the media${Q?` (${Q})`:""}.`,{containerId:W});if(J==="EXPIRED")throw new O("expired","The media container expired before it was published.",{containerId:W});let Y=Z.deadline-Date.now();if(Y<=0)throw new O("timeout","Instagram had not finished processing the media in time; the container is still processing.",{containerId:W});await C5(Math.min($,Y),Z.signal),$=Math.min($*1.5,this.maxPollIntervalMs)}}async call(W,Z,$,J,{retry:Q=!0}={}){try{return await this.callOnce(W,Z,$,J)}catch(Y){if(!Q||!(Y instanceof O)||Y.code!=="transient")throw Y;return this.callOnce(W,Z,$,J)}}async callOnce(W,Z,$,J){J.signal?.throwIfAborted();let Q={method:$?"POST":"GET",signal:J.signal};if($){let G=new URLSearchParams;for(let[z,X]of Object.entries($))if(X!==void 0)G.set(z,X);Q.body=G}let Y;try{Y=await this.connection.fetch(`${this.version}${Z}`,Q)}catch(G){if(J.signal?.aborted)throw J.signal.reason;if(G instanceof TypeError)throw new O("transient",`Instagram's ${W} failed to reach Instagram.`);throw G}let K=p0(await Y.text().catch(()=>""));if(Y.ok)return K;throw _5(W,Y.status,K)}}var D5=new Set(["EXPIRED","ERROR","FINISHED","IN_PROGRESS","PUBLISHED"]),H5=new Set([4,17,32,613,80002]),U5=new Set([3,10]),x5=new Set([9004,352,36000,36001,36002,36003,36004]),O5=new Set([2207004,2207005,2207006,2207009,2207023,2207026,2207028,2207052]),S5=new Set([102,190,463,467]),R5=new Set([2207001,2207003,2207053]),MW={code:9007,subcode:2207027};function _5(W,Z,$){let J=$.error??{},Q=NW(J.code),Y=NW(J.error_subcode),K=typeof J.type==="string"&&J.type!==""?J.type:void 0,G=typeof J.message==="string"&&J.message!==""?`: ${xW(J.message)}`:"",z=[Q,Y].filter((j)=>j!==void 0).join("/"),X=`Instagram refused the ${W} (HTTP ${Z}${K?`, ${K}`:""}${z?` ${z}`:""})${G}`,B="graph_error";if(Y===2207042)B="quota_exceeded";else if(Y===2207010)B="invalid_input";else if(Q!==void 0&&H5.has(Q))B="rate_limited";else if(Q!==void 0&&S5.has(Q))B="reconnect_required";else if(Q!==void 0&&(U5.has(Q)||Q>=200&&Q<=299))B="permission_denied";else if(Q!==void 0&&x5.has(Q)||Y!==void 0&&O5.has(Y))B="invalid_media";else if(J.is_transient===!0||Q===1||Q===2||Y!==void 0&&R5.has(Y)||Z>=500||Z===429)B=Z===429?"rate_limited":"transient";return new O(B,X,{status:Z,graphCode:Q,graphSubcode:Y})}function k5(W){return W.graphCode===MW.code||W.graphSubcode===MW.subcode}function f5(W,Z){if(W.containerId)return W;return new O(W.code,W.message,{status:W.status,graphCode:W.graphCode,graphSubcode:W.graphSubcode,containerId:Z})}function xW(W){return W.replace(/access_token=[^&\s"']*/gi,"access_token=[redacted]").replace(/\b(?:IG|EAA)[A-Za-z0-9_-]{20,}/g,"[redacted]").slice(0,500)}function LW(W,Z){let $=W.id;if(typeof $==="string"&&$!=="")return $;if(typeof $==="number"&&Number.isSafeInteger($))return String($);throw new O("graph_error",`Instagram's ${Z} answered without an id.`,{status:200})}function NW(W){let Z=Number(W);return W!==void 0&&W!==null&&Number.isFinite(Z)?Z:void 0}function l0(W,Z){let $=Number(W);return W!==void 0&&W!==null&&Number.isFinite($)?$:Z}function C5(W,Z){return new Promise(($,J)=>{if(Z?.aborted)return J(Z.reason);let Q=()=>{clearTimeout(Y),J(Z?.reason)},Y=setTimeout(()=>{Z?.removeEventListener("abort",Q),$()},W);Z?.addEventListener("abort",Q,{once:!0})})}function k(W){throw new O("invalid_input",W)}function n0(W){if(W===void 0)return;if(typeof W!=="string")k("caption must be a string.");if([...W].length>C.captionLength)k(`A caption takes at most ${C.captionLength} characters.`);if((W.match(/#[\p{L}\p{N}_]+/gu)??[]).length>C.hashtags)k(`A caption takes at most ${C.hashtags} hashtags.`);if((W.match(/(?<![\p{L}\p{N}_.@])@[\p{L}\p{N}_.]+/gu)??[]).length>C.mentions)k(`A caption takes at most ${C.mentions} @mentions.`)}function V5(W){if(!Array.isArray(W)||W.length>C.userTags)k(`userTags takes at most ${C.userTags} tags.`);for(let Z of W){let $=(J)=>typeof J==="number"&&J>=0&&J<=1;if(typeof Z?.username!=="string"||Z.username===""||!$(Z.x)||!$(Z.y))k("Each user tag needs a username, and x and y between 0 and 1.")}}function DW(W,Z){let $=Z?.imageUrl!==void 0,J=Z?.videoUrl!==void 0;if($===J)k(`${W} takes exactly one of imageUrl and videoUrl.`);if($)I1(`${W}.imageUrl`,Z.imageUrl);else I1(`${W}.videoUrl`,Z.videoUrl)}function I1(W,Z){let $;try{$=new URL(Z)}catch{k(`${W} is not an absolute URL.`)}if($.protocol!=="https:")k(`${W} must be an https URL: Instagram fetches the media from it.`);let J=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Q=HW(J);if(Q?UW(Q)!==null:!J.includes(".")||/(^|\.)(localhost|local|internal)$/.test(J))k(`${W} must be a public URL: Instagram fetches the media from it.`)}class s0{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 T5(W={}){return new s0(W)}class OW extends o0{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,j9 as translationConfigDefaults,N4 as toRangeHeaderValue,g5 as subjectFor,zZ as strictCspPolicy,r5 as sniffContentType,oZ as scheduleConfigDefaults,U4 as resolveRange,P9 as redisConfigDefaults,C9 as rateLimiterConfigDefaults,_Z as queueConfigDefaults,F5 as parseMetaSignedRequest,H1 as parseContentRange,w5 as mintSessionToken,FZ as middlewareConfigDefaults,hZ as mcpCallOf,NZ as mailConfigDefaults,Z8 as logConfigDefaults,b5 as isSessionToken,dW as isFixedSignInCode,u8 as isFinalRunStatus,_6 as isBroadcastEvent,e5 as isActiveContentType,h5 as inRollout,r8 as imageConfigDefaults,pW as fixedSignInCode,o5 as filesystemConfigDefaults,N9 as featuresConfigDefaults,tZ as eventConfigDefaults,E5 as evaluateFeature,R8 as encodeCursor,YZ as documentScriptCspHash,Z9 as discoverWorkflows,Q9 as discoverListeners,W9 as discoverJobs,$9 as discoverCronJobs,J9 as discoverCommands,B9 as defineTranslationConfig,sZ as defineScheduleConfig,g8 as defineRunsConfig,ZZ as defineRouteConfig,T9 as defineRedisConfig,f9 as defineRateLimiterConfig,RZ as defineQueueConfig,jZ as defineMiddlewareConfig,LZ as defineMailConfig,W8 as defineLogConfig,t8 as defineImageConfig,s5 as defineFilesystemConfig,L9 as defineFeaturesConfig,T5 as defineFeature,aZ as defineEventConfig,kW as defineEncryptionConfig,dZ as defineCommandConfig,nZ as defineCommand,O8 as defineChangeFeedConfig,J8 as defineCacheConfig,w8 as defineBroadcastConfig,v5 as defineAuthConfig,_8 as decodeCursor,OZ as createWorkflowTableStatements,l8 as createRunsTableStatements,lZ as commandConfigDefaults,S8 as changeFeedConfigDefaults,Q8 as cacheConfigDefaults,A5 as bucketOf,y5 as bucketKey,q8 as broadcastConfigDefaults,y4 as bearerToken,I5 as authConfigDefaults,D4 as assertDeletablePrefix,$Z as apiRouteConfigDefaults,YW as XOAuthProvider,wZ as WorkflowRuntime,PZ as WorkflowCancelledError,eZ as Workflow,VZ as WaitTimeoutError,XZ as ViewRouteDispatcher,d5 as UndeclaredFeatureError,z8 as TaggedCache,t5 as StorageFetchTimeoutError,TZ as StepTimeoutError,CZ as StepFailedError,bZ as Step,OW as StaticFeatureFlagSource,a8 as Sharp,cZ as Scheduler,F9 as ScheduleServiceProvider,GZ as STATIC_NAVIGATION_CSP_HASH,b8 as SOCKET_ID_HEADER,P5 as SESSION_TOKEN_PREFIX,t0 as S3Driver,q9 as RunsServiceProvider,n8 as RunNotFoundError,s8 as RunManager,i8 as RunFailure,w9 as RouteServiceProvider,MZ as ResendDriver,b9 as RedisServiceProvider,R4 as RedisRateLimiterTimeoutError,E1 as RedisRateLimiterDisconnectedError,$6 as RedisRateLimiter,h1 as RedisManager,K8 as RedisCacheStore,I8 as RedisBroadcastDriver,V9 as RateLimiterServiceProvider,O4 as RateLimiterDriver,q5 as RateLimiter,J1 as RangeNotSatisfiableError,Y9 as QueueServiceProvider,qZ as QueueManager,x8 as ProviderConnection,O6 as PrismaMcpOAuthStore,h8 as PendingBroadcast,c8 as OPEN_RUN_STATUSES,H8 as OAuthReconnectRequiredError,m as OAuthProvider,d0 as OAuthConnectionProvider,v1 as OAuthConnectionError,U as OAuthCallbackError,k9 as MiddlewareServiceProvider,WZ as MiddlewareRegistry,y as MetaSignedRequestError,kZ as MemoryWorkflowStore,p8 as MemoryRunStore,fZ as MemoryQueueDriver,x6 as MemoryMcpOAuthStore,UZ as MemoryLockStore,N8 as MemoryConnectionStore,f8 as MemoryChangeFeedDriver,Y8 as MemoryCacheStore,v8 as MemoryBroadcastDriver,yZ as McpToolError,EZ as McpRegistry,H6 as McpOAuthServer,mZ as McpHttpServer,AZ as McpCallRefusedError,gZ as McpApiKeyResolver,H9 as MailServiceProvider,DZ as MailManager,_9 as LogServiceProvider,$8 as LogManager,j8 as LockManager,X8 as LockLostError,rZ as Listener,R9 as KernelIdServiceProvider,QZ as KernelId,vZ as Job,P8 as InvalidChannelError,i0 as InstagramPublisher,O as InstagramPublishError,jW as InstagramOAuthProvider,L4 as InstagramConnectionProvider,I as InstagramApiError,N5 as Instagram,S4 as InMemoryRateLimiter,S9 as ImageServiceProvider,o8 as ImageOptimizationDriver,e8 as ImageManager,KZ as ISLAND_LOADER_CSP_HASH,C as INSTAGRAM_LIMITS,B8 as HeldLock,P6 as GoogleOAuthProvider,w6 as GitHubOAuthProvider,O9 as FilesystemServiceProvider,a5 as FilesystemManager,i5 as FileSystemDriver,U1 as FileStorageDriver,a as FileNotFoundError,D9 as FeaturesServiceProvider,p5 as FeatureSourceReadOnlyError,l5 as FeatureScope,m5 as FeatureReloadError,u5 as FeatureModelMissingError,n5 as FeatureManager,c5 as FeatureFlagStore,o0 as FeatureFlagSource,s0 as Feature,m8 as FINAL_RUN_STATUSES,x9 as EventServiceProvider,w as EventManager,l1 as Event,U9 as EncryptionServiceProvider,M8 as EncryptionKeyError,F8 as Encrypter,_4 as EmailDriver,L8 as DecryptionError,xZ as DatabaseWorkflowStore,d8 as DatabaseRunStore,SZ as DatabaseQueueDriver,HZ as DatabaseLockStore,M9 as DatabaseFeatureFlagSource,D8 as DatabaseConnectionStore,k8 as DatabaseChangeFeedDriver,IZ as DEFAULT_MCP_SCOPE,iZ as CronJob,U8 as ConnectionManager,v9 as CommandRegistry,uZ as CommandFailed,pZ as Command,T8 as ChangeFeedSubscription,z9 as ChangeFeedServiceProvider,V8 as ChangeFeedManager,C8 as ChangeFeedFullError,G9 as CacheServiceProvider,G8 as CacheManager,g1 as CONSENT_PAGE_HEADERS,K9 as BroadcastServiceProvider,E8 as BroadcastScope,y8 as BroadcastPayloadTooLargeError,A8 as BroadcastManager,k6 as BroadcastEvent,e0 as AzureBlobDriver,X9 as AuthServiceProvider,e as AuthManager,BZ as ApiRouteDispatcher,k4 as AcsDriver};
64
+ </html>`}function F6(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>${A(W)}</p></body></html>`}function A(W){return W.replace(/[&<>"']/g,(Z)=>`&#${Z.charCodeAt(0)};`)}var v4="gmcp_at_",I4="gmcp_rt_",L6="gmcp_ac_",eW="gmcp_c_",W5="gmcp_cs_",f4="gemi.mcp.oauth.ticket.v1",D6="gemi.mcp.oauth.consent.v1",Z5=600000,H6=120000,m4=16384,$5={limit:20,window:3600},Q5={limit:60,window:60},i1=["none","client_secret_post","client_secret_basic"];class L extends Error{error;description;status;headers;constructor(W,Z,$=400,Q={}){super(Z);this.error=W;this.description=Z;this.status=$;this.headers=Q}}class C6{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=N6("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=N6("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=u4(W);if(!Z?.startsWith(v4))return null;let $=await this.store.findToken(n(Z)),Q=(K)=>({ok:!1,error:"invalid_token",description:K});if(!$||$.kind!=="access")return Q("The access token is not valid.");if($.expiresAt<=Date.now())return Q("The access token expired.");if($.resource!==this.context.resource)return Q("The access token was not issued for this server.");let Y=await this.options.findUser($.userId);if(!Y)return Q("The access token is not valid.");return{ok:!0,principal:{user:Y,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,Y={[`/.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(!Y)return null;if(Z===`${this.base}/register`&&this.options.registration===!1)return null;let K=Y.cors?Y5:{};if(W.method==="OPTIONS"&&Y.cors)return new Response(null,{status:204,headers:{...K,"Access-Control-Allow-Methods":Y.methods.join(", "),"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}});if(!Y.methods.includes(W.method))return new Response(null,{status:405,headers:{...K,Allow:Y.methods.join(", ")}});let J;try{J=await Y.run()}catch(z){if(!(z instanceof L))throw z;J=P1({error:z.error,error_description:z.description},z.status,z.headers)}for(let[z,G]of Object.entries(K))J.headers.set(z,G);return J}async consent(W,Z){if(!Z)return null;let $=s1(f4,"gat1",W);if(!$)return null;let Q=await this.store.findClient($.c);if(!Q||!Q.redirectUris.some((z)=>A4(z,$.r)))return null;let Y=String(Z.id),K=g4(D6,"gcs1",{t:U6(W),u:Y,exp:$.exp}),J=new Map(this.context.registry.scopes().map((z)=>[z.name,z.description]));return{client:{id:Q.clientId,name:Q.clientName,redirectHost:new URL($.r).host},scopes:$.s.map((z)=>({name:z,description:J.get(z)??z})),user:{id:Y,label:this.userLabel(Z)},form:{action:`${this.issuer}${this.base}/consent`,method:"POST",fields:{request:W,csrf:K}}}}resourceMetadata(){return P1({resource:this.context.resource,authorization_servers:[this.issuer],scopes_supported:this.scopeNames(),bearer_methods_supported:["header"]})}serverMetadata(){return P1({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 E4(`mcp-oauth-register:${k6(new h4(W,{},"api",`${this.base}/register`))}`,Z.rateLimit??$5);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 Q;try{Q=JSON.parse(await c4(W,m4))}catch{throw new L("invalid_client_metadata","The client metadata is not JSON, or is too large.")}if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new L("invalid_client_metadata","The client metadata must be a JSON object.");let Y=Q.redirect_uris;if(!Array.isArray(Y)||Y.length===0||Y.length>10)throw new L("invalid_redirect_uri","redirect_uris must list one to ten URIs.");for(let D of Y){let x=z5(D);if(x)throw new L("invalid_redirect_uri",`${String(D).slice(0,200)}: ${x}`);if(Z.allowRedirectUri&&Z.allowRedirectUri(new URL(D))!==!0)throw new L("invalid_redirect_uri",`${D}: this server does not accept it.`)}let K=Q.token_endpoint_auth_method??"client_secret_basic";if(!i1.includes(K))throw new L("invalid_client_metadata",`token_endpoint_auth_method must be one of ${i1.join(", ")}.`);let J=Q.grant_types??["authorization_code"];if(!Array.isArray(J)||J.some((D)=>D!=="authorization_code"&&D!=="refresh_token"))throw new L("invalid_client_metadata","grant_types may only be authorization_code and refresh_token.");let z=Q.response_types??["code"];if(!Array.isArray(z)||z.some((D)=>D!=="code"))throw new L("invalid_client_metadata","response_types may only be code.");let G=R6(Q.client_name,100,"client_name"),X=R6(Q.client_uri,512,"client_uri");if(X!==null&&!J5(X))throw new L("invalid_client_metadata","client_uri must be an https URL.");let B=K==="none"?null:`${W5}${K1(32).toString("base64url")}`,j={clientId:`${eW}${K1(16).toString("base64url")}`,clientSecretHash:B?n(B):null,tokenEndpointAuthMethod:K,redirectUris:[...Y],clientName:G,clientUri:X,createdAt:Date.now()};return await this.store.createClient(j),P1({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:K,grant_types:J,response_types:z,...G?{client_name:G}:{},...X?{client_uri:X}:{}},201)}async authorize(W){let Z=new URL(W.url).searchParams;for(let V of new Set(Z.keys()))if(Z.getAll(V).length>1)return p(`The parameter ${V} was sent more than once.`);let $=Z.get("client_id"),Q=$?await this.store.findClient($):null;if(!Q)return p("The application is not registered with this server.");let Y=Z.get("redirect_uri")??(Q.redirectUris.length===1?Q.redirectUris[0]:null);if(!Y||!Q.redirectUris.some((V)=>A4(V,Y)))return p("The redirect URI is not one the application registered.");let K=Z.get("state"),J=(V,Q1)=>this.redirectBack(Y,K,{error:V,error_description:Q1});if(Z.get("response_type")!=="code")return J("unsupported_response_type","Only response_type=code is supported.");let z=Z.get("code_challenge");if(Z.get("code_challenge_method")!=="S256"||!z||!/^[A-Za-z0-9_-]{43}$/.test(z))return J("invalid_request","PKCE is required: code_challenge with code_challenge_method=S256.");let G=Z.get("resource");if(G!==null&&!O6(G,this.context.resource))return J("invalid_target","The resource is not this server's.");if(K!==null&&K.length>2048)return J("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((V)=>X.includes(V)))],j.length===0)return J("invalid_scope","None of the requested scopes exist here.")}let D=g4(f4,"gat1",{c:Q.clientId,r:Y,s:j,cc:z,st:K,n:K1(16).toString("base64url"),exp:Date.now()+Z5}),x=this.options.consentPath??`${this.base}/consent`;return y4(`${this.issuer}${x}?request=${encodeURIComponent(D)}`,302)}async consentScreen(W){let Z=new URL(W.url).searchParams.get("request"),$=await this.sessionUser(W);if(!$){let Y=`${this.base}/consent?request=${encodeURIComponent(Z??"")}`,K=this.options.signInPath??C(z1).config.signInPath;return y4(`${K}${K.includes("?")?"&":"?"}redirect=${encodeURIComponent(Y)}`,302)}let Q=await this.consent(Z,$);if(!Q)return p("This authorization request has expired or is not valid. Start again from the application.");return new Response(M6(Q,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:n1})}async decide(W){let Z=W.headers.get("origin");if(!(Z!==null&&Z!=="null"?Z===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return p("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 p("The decision must be a form post.");let Q;try{Q=new URLSearchParams(await c4(W,m4))}catch{return p("The decision is too large.")}let Y=Q.get("request"),K=s1(f4,"gat1",Y),J=s1(D6,"gcs1",Q.get("csrf")),z=await this.sessionUser(W);if(!K||!J||!z||J.t!==U6(Y)||J.u!==String(z.id))return p("This authorization request has expired or is not valid. Start again from the application.",403);let G=await this.store.findClient(K.c);if(!G||!G.redirectUris.some((B)=>A4(B,K.r)))return p("The application is not registered with this server.");if(!await this.store.use(`ticket:${K.n}`,K.exp))return p("This request was already answered. Start again from the application.");if(Q.get("decision")!=="allow")return this.redirectBack(K.r,K.st,{error:"access_denied",error_description:"The user denied the request."},303);let X=`${L6}${K1(32).toString("base64url")}`;return await this.store.saveCode({hash:n(X),clientId:G.clientId,userId:String(z.id),redirectUri:K.r,codeChallenge:K.cc,scopes:K.s,resource:this.context.resource,familyId:K1(16).toString("base64url"),expiresAt:Date.now()+H6}),this.redirectBack(K.r,K.st,{code:X},303)}async token(W){let Z=await S6(W),$=await this.authenticateClient(W,Z),Q=await E4(`mcp-oauth-token:${$.clientId}`,Q5);if(Q!==null)throw new L("slow_down","Too many token requests.",429,{"Retry-After":String(Q)});let Y=Z.get("resource");if(Y!==null&&!O6(Y,this.context.resource))throw new L("invalid_target","The resource is not this server's.");switch(Z.get("grant_type")){case"authorization_code":{let K=Z.get("code")??"",J=K.startsWith(L6)?await this.store.findCode(n(K)):null;if(!J||J.clientId!==$.clientId)throw new L("invalid_grant","The authorization code is not valid.");if(!await this.store.use(J.hash,J.expiresAt+H6))throw await this.store.revokeFamily(J.familyId),new L("invalid_grant","The authorization code was already used.");if(J.expiresAt<=Date.now())throw new L("invalid_grant","The authorization code expired.");if(Z.get("redirect_uri")!==null&&Z.get("redirect_uri")!==J.redirectUri)throw new L("invalid_grant","redirect_uri is not the one the code was issued to.");let z=Z.get("code_verifier");if(!z||!/^[A-Za-z0-9._~-]{43,128}$/.test(z)||!x6(K5(z),J.codeChallenge))throw new L("invalid_grant","The PKCE code_verifier does not match.");if(!await this.options.findUser(J.userId))throw new L("invalid_grant","The authorization code is not valid.");return await this.issue(J)}case"refresh_token":{let K=Z.get("refresh_token")??"",J=K.startsWith(I4)?await this.store.findToken(n(K)):null;if(!J||J.kind!=="refresh"||J.clientId!==$.clientId)throw new L("invalid_grant","The refresh token is not valid.");if(J.expiresAt<=Date.now())throw new L("invalid_grant","The refresh token expired.");if(!await this.store.use(J.hash,J.expiresAt))throw await this.store.revokeFamily(J.familyId),new L("invalid_grant","The refresh token was already used.");if(J.resource!==this.context.resource)throw new L("invalid_grant","The refresh token was not issued for this server.");let z=J.scopes,G=Z.get("scope");if(G!==null&&G.trim()!==""){let X=[...new Set(G.split(" ").filter(Boolean))];if(X.some((B)=>!J.scopes.includes(B)))throw new L("invalid_scope","A refresh can only narrow the scopes that were granted.");z=X}if(!await this.options.findUser(J.userId))throw new L("invalid_grant","The refresh token is not valid.");return await this.issue({...J,scopes:z})}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(),Q=W.scopes.filter((z)=>$.includes(z)),Y=`${v4}${K1(32).toString("base64url")}`,K=`${I4}${K1(32).toString("base64url")}`,J={clientId:W.clientId,userId:W.userId,scopes:Q,resource:W.resource,familyId:W.familyId};return await this.store.saveToken({...J,hash:n(Y),kind:"access",expiresAt:Z+this.accessTtl*1000}),await this.store.saveToken({...J,hash:n(K),kind:"refresh",expiresAt:Z+this.refreshTtl*1000}),P1({access_token:Y,token_type:"Bearer",expires_in:this.accessTtl,refresh_token:K,scope:Q.join(" ")})}async revoke(W){let Z=await S6(W),$=await this.authenticateClient(W,Z),Q=Z.get("token")??"";if(Q.startsWith(v4)||Q.startsWith(I4)){let Y=await this.store.findToken(n(Q));if(Y&&Y.clientId===$.clientId)await this.store.revokeFamily(Y.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")??""),Q=Z.get("client_id"),Y=Z.get("client_secret");if($){let J=Buffer.from($[1],"base64").toString("utf8"),z=J.indexOf(":");if(z<0)throw J1(!0);let G=_6(J.slice(0,z));if(G===null)throw J1(!0);if(Q!==null&&Q!==G)throw J1(!0);if(Q=G,Y=_6(J.slice(z+1)),Y===null)throw J1(!0)}let K=Q?await this.store.findClient(Q):null;if(!K)throw J1(Boolean($));if(K.tokenEndpointAuthMethod==="none"){if(Y)throw J1(Boolean($));return K}if(!Y||!K.clientSecretHash||!x6(n(Y),K.clientSecretHash))throw J1(Boolean($));return K}redirectBack(W,Z,$,Q=302){let Y=new URL(W);for(let[K,J]of Object.entries($))Y.searchParams.set(K,J);if(Z!==null)Y.searchParams.set("state",Z);return Y.searchParams.set("iss",this.issuer),y4(Y.href,Q)}async sessionUser(W){let Z=new h4(W,{},"api",this.base).cookies;return await V6(C(z1),{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 Y5={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function N6(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 n(W){return p4("sha256").update(W).digest("hex")}function U6(W){return p4("sha256").update(W).digest("base64url")}function K5(W){return p4("sha256").update(W).digest("base64url")}function x6(W,Z){let $=Buffer.from(W),Q=Buffer.from(Z);return $.length===Q.length&&rW($,Q)}function P1(W,Z=200,$={}){return new Response(JSON.stringify(W),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache",...$}})}function y4(W,Z){return new Response(null,{status:Z,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function p(W,Z=400){return new Response(F6(W),{status:Z,headers:n1})}function J1(W){return new L("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function c4(W,Z){let $=Number(W.headers.get("content-length"));if(Number.isFinite($)&&$>Z)throw Error("too large");if(!W.body)return"";let Q=W.body.getReader(),Y=[],K=0;for(;;){let{done:J,value:z}=await Q.read();if(J)break;if(K+=z.byteLength,K>Z)throw await Q.cancel(),Error("too large");Y.push(z)}return Buffer.concat(Y).toString("utf8")}async function S6(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 c4(W,m4))}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 R6(W,Z,$){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>Z||G5(W))throw new L("invalid_client_metadata",`${$} must be text of at most ${Z} characters.`);return W}function J5(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function T6(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function z5(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:"&&T6(Z))return null;return"must be https, or http on a loopback address"}function A4(W,Z){if(W===Z)return!0;let $,Q;try{$=new URL(W),Q=new URL(Z)}catch{return!1}return $.protocol==="http:"&&Q.protocol==="http:"&&T6($)&&$.hostname===Q.hostname&&$.pathname===Q.pathname&&$.search===Q.search&&!Q.hash&&!Q.username&&!Q.password}function O6(W,Z){return W===Z||W===`${Z}/`}function G5(W){for(let Z=0;Z<W.length;Z++){let $=W.charCodeAt(Z);if($<32||$===127)return!0}return!1}function _6(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class P6{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 b6{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 Q=W?.[Z],Y=$.filter((K)=>typeof Q?.[K]!=="function");if(Y.length>0)throw Error(`PrismaMcpOAuthStore: models.${Z} must be a gemi ORM model or a Prisma delegate (it has no ${Y.join(", ")}()).`)}this.clients=W.clients,this.credentials=W.credentials,this.usesModel=W.uses,this.uses=new d4(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:o1(Z.redirectUris),clientName:Z.clientName??null,clientUri:Z.clientUri??null,createdAt:a1(Z.createdAt)}}async saveCode(W){await this.credentials.create({data:{hash:W.hash,kind:"code",clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,redirectUri:W.redirectUri,codeChallenge:W.codeChallenge,expiresAt:new Date(W.expiresAt)}})}async findCode(W){let Z=await this.findLive(W,["code"]);if(!Z||Z.redirectUri==null||Z.codeChallenge==null)return null;return{hash:Z.hash,clientId:Z.clientId,userId:Z.userId,redirectUri:Z.redirectUri,codeChallenge:Z.codeChallenge,scopes:o1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:a1(Z.expiresAt)}}async saveToken(W){await this.credentials.create({data:{hash:W.hash,kind:W.kind,clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,expiresAt:new Date(W.expiresAt)}})}async findToken(W){let Z=await this.findLive(W,["access","refresh"]);if(!Z)return null;return{hash:Z.hash,kind:Z.kind,clientId:Z.clientId,userId:Z.userId,scopes:o1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:a1(Z.expiresAt)}}use(W,Z){return this.uses.consume(W,Z)}async revokeFamily(W){await this.credentials.updateMany({where:{familyId:W,revokedAt:null},data:{revokedAt:new Date}})}nonces(W={}){return new d4(this.usesModel,{prefix:W.prefix??"nonce:"})}async connectedApps(W,Z=new Date){let $=String(W),Q=await this.credentials.findMany({where:{userId:$,kind:"refresh",expiresAt:{gt:Z}},orderBy:{createdAt:"asc"}}),Y=await this.revokedFamilies({userId:$}),K=new Map;for(let X of Q){if(Y.has(X.familyId))continue;if(!K.has(X.familyId))K.set(X.familyId,X)}if(K.size===0)return[];let J=[...new Set([...K.values()].map((X)=>X.clientId))],z=await this.clients.findMany({where:{clientId:{in:J}}}),G=new Map(z.map((X)=>[X.clientId,X]));return[...K.values()].map((X)=>({familyId:X.familyId,clientId:X.clientId,clientName:G.get(X.clientId)?.clientName??null,clientUri:G.get(X.clientId)?.clientUri??null,scopes:o1(X.scopes),connectedAt:new Date(a1(X.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}})],Q=$.length===0?[]:await this.credentials.findMany({where:{familyId:{in:$},expiresAt:{gte:Z}},select:{familyId:!0}}),Y=[...new Set(Q.map((K)=>K.familyId))];await this.credentials.deleteMany({where:{expiresAt:{lt:Z},...Y.length>0?{OR:[{revokedAt:null},{familyId:{notIn:Y}}]}:{}}}),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 o1(W){return Array.isArray(W)?W.map(String):[]}function a1(W){return W instanceof Date?W.getTime():new Date(W).getTime()}class w1 extends h{application;previous;dispatched=[];static install(W){let Z=W.resolved(h)?W.make(h):void 0;if(Z instanceof w1)return Z;let $=new w1(W,Z);return W.instance(h,$),$}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(h,this.previous);return}this.application.forget(h)}assertDispatched(W,Z){let $=b1(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 $=b1(W),Q=this.matching($,Z);if(Q.length===0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} not to have been dispatched, but it was dispatched ${l4(Q.length)}: ${t1(Q)}.`)}assertDispatchedTimes(W,Z,$){let Q=b1(W),Y=this.matching(Q,$);if(Y.length===Z)return;throw Error(`Expected ${Q}${$?" matching the predicate":""} to have been dispatched ${l4(Z)}, but it was dispatched ${l4(Y.length)}. ${this.summary(Q,$!==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"}: ${t1(this.dispatched)}.`)}matching(W,Z){return this.dispatched.filter(($)=>b1($.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}: ${t1($)}.`;return`Dispatched: ${t1(this.dispatched)}.`}}function b1(W){return W.name}function l4(W){return`${W} ${W===1?"time":"times"}`}function t1(W){return W.map(X5).join(", ")}function X5(W){let Z=b1(W.event.constructor),$=W.args??Object.values({...W.event});return`${Z}(${$.map(B5).join(", ")})`}function B5(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class r1{static name="unset";static afterCommit=!1;static dispatch(...W){w6(this),C(h).dispatch(new this(...W),W)}static dispatchAndWait(...W){return w6(this),C(h).dispatchAndWait(new this(...W),W)}static fake(){return w1.install(j5())}}function j5(){try{return C()}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 w6(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 I6 extends r1{constructor(){super();Object.defineProperty(this,n4,{value:!0,enumerable:!1})}broadcastAs(){return this.constructor.name}broadcastWith(){return}channel(W,...Z){return{topic:q6(W,Z[0]??{}),pattern:W}}}function A6(){try{let W=C();if(typeof W?.bound==="function"&&W.bound(z1))return W.make(z1).config.emailCode}catch{}return}function M5(){return f6(A6())}function F5(W){return y6(W,A6())}function L5(W){let Z=null;try{let K=C();if(typeof K?.bound==="function"&&K.bound(i4))Z=C(i4).resolver??null}catch{Z=null}if(Z)return Z.publicOrigin(W);let $=new URL(W.url),Q=W.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return`${Q==="http"||Q==="https"?Q:$.protocol.slice(0,-1)}://${$.host}`}function D5(W,Z){let $=typeof W==="string"?W.trim().replace(/\/+$/,""):"",Q=URL.canParse($)?new URL($):null;if(!Q||Q.protocol!=="http:"&&Q.protocol!=="https:"||Q.origin!==$)throw Error(`${Z}: resolve() returned origin ${JSON.stringify(W)}, which is not an http(s) origin such as https://example.com.`);return $}var h6=new WeakMap;function a(W,Z,$){if(!$.resolve)return Promise.resolve({clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.staticRedirectUri()});let Q=Z?.rawRequest;if(!Z||!Q)return Promise.resolve(null);let Y=h6.get(W);if(!Y)Y=new WeakMap,h6.set(W,Y);let K=Y.get(Q);if(K)return K;let J=$.resolve,z=(async()=>{let G=await J({req:Z,origin:L5(Q)});if(G===null||G===void 0)return null;let X=G.origin!==void 0?D5(G.origin,$.name):$.staticOrigin();return{clientId:G.clientId??$.clientId,clientSecret:G.clientSecret??$.clientSecret,redirectUri:`${X}${$.redirectPath}`}})();return Y.set(Q,z),z.catch(()=>Y.delete(Q)),z}var H5={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 N5(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class E6 extends i{config;constructor(W={}){super();this.config={...H5,...W}}redirectUri(){return`${q()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"GoogleOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>q()??""})}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GoogleOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}authorizationUrl(W,Z){let $=new URL("https://accounts.google.com/o/oauth2/v2/auth"),Q={include_granted_scopes:"true",...this.config.authorizationParams,scope:this.config.scope,response_type:"code",redirect_uri:W.redirectUri,client_id:W.clientId};if(Z)Q.state=Z.state,Q.code_challenge=Z.codeChallenge,Q.code_challenge_method=Z.codeChallengeMethod;for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new R("missing_code");let Q=this.config.resolve?await this.clientFor(W):this.staticClient();if(!Q)throw new R("unknown_provider");let Y=new URLSearchParams({code:$,client_id:Q.clientId,client_secret:Q.clientSecret,grant_type:"authorization_code",redirect_uri:Q.redirectUri});if(Z?.codeVerifier)Y.set("code_verifier",Z.codeVerifier);let K=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y.toString()}),J=await K.json().catch(()=>({}));if(!K.ok||typeof J?.access_token!=="string"||J.access_token==="")throw console.error("Google OAuth error: token exchange failed",J?.error??K.status),new R(N5(J?.error,"exchange_failed"));let G=await(await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${J.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 U5="https://github.com/login/oauth/authorize",x5="https://github.com/login/oauth/access_token",g6="https://api.github.com";function S5(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class m6 extends i{config;constructor(W={}){super();this.config={clientId:process.env.GITHUB_CLIENT_ID??"",clientSecret:process.env.GITHUB_CLIENT_SECRET??"",redirectPath:"/auth/oauth/github/callback",scope:"read:user user:email",authorizationParams:{},...W}}redirectUri(){return`${q()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"GitHubOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>q()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GitHubOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(U5),Q={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,scope:this.config.scope,response_type:"code"};if(Z)Q.state=Z.state,Q.code_challenge=Z.codeChallenge,Q.code_challenge_method=Z.codeChallengeMethod;for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new R("missing_code");let Q=this.config.resolve?await this.clientFor(W):this.staticClient();if(!Q)throw new R("unknown_provider");let Y=new URLSearchParams({client_id:Q.clientId,client_secret:Q.clientSecret,code:$,redirect_uri:Q.redirectUri});if(Z?.codeVerifier)Y.set("code_verifier",Z.codeVerifier);let K=await fetch(x5,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:Y.toString()}),J=await K.json().catch(()=>({}));if(!K.ok||typeof J?.access_token!=="string"||J.access_token==="")throw console.error("GitHub OAuth error: token exchange failed",J?.error??K.status),new R(S5(J?.error,"exchange_failed"));let z={Accept:"application/vnd.github+json",Authorization:`Bearer ${J.access_token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"gemi"},G=await fetch(`${g6}/user`,{headers:z}),X=await G.json().catch(()=>({}));if(!G.ok||typeof X?.id!=="number"||!Number.isSafeInteger(X.id))return console.error("GitHub OAuth error: no user id in the /user response",G.status),{};let B=typeof X.login==="string"&&X.login!==""?X.login:void 0,j=typeof X.name==="string"&&X.name!==""?X.name:B,D=await this.primaryVerifiedEmail(z),x=typeof X.email==="string"&&X.email!==""?X.email:void 0;return{providerId:String(X.id),username:B,name:j,...D?{email:D,emailVerified:!0}:x?{email:x,emailVerified:!1}:{}}}async primaryVerifiedEmail(W){let Z=await fetch(`${g6}/user/emails`,{headers:W}).catch(()=>null);if(!Z?.ok){console.error("GitHub OAuth error: could not read /user/emails",Z?.status);return}let $=await Z.json().catch(()=>null);if(!Array.isArray($))return;let Q=$.find((Y)=>Y?.primary===!0&&Y.verified===!0);return typeof Q?.email==="string"&&Q.email!==""?Q.email:void 0}}var t="https://api.x.com/2/",M1="https://api.x.com/labs/2/",r="https://api.x.com/1.1/",s="https://upload.x.com/1.1/",c6="https://stream.x.com/1.1/",F1="https://ads-api.x.com/12/",L1="https://ads-api-sandbox.twitter.com/12/";class s4{constructor({realData:W,rateLimit:Z,instance:$,queryParams:Q,sharedParams:Y}){this._maxResultsWhenFetchLast=100,this._realData=W,this._rateLimit=Z,this._instance=$,this._queryParams=Q,this._sharedParams=Y}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 Q=await this.makeRequest(Z);if(await this.refreshInstanceFromResult(Q,!0),$+=this.getPageLengthFromRequest(Q),this.isFetchLastOver(Q))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 Q of $.getItemArray())yield[Q,$];this._rateLimit=$._rateLimit,W=$}}}class o4 extends s4{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 D1=s4;class O extends D1{getNextQueryParams(W){var Z;return{...this._queryParams,cursor:(Z=this._realData.next_cursor_str)!==null&&Z!==void 0?Z:this._realData.next_cursor,...W?{count:W}:{}}}isFetchLastOver(W){return!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!this.isNextCursorInvalid(W.next_cursor)||!this.isNextCursorInvalid(W.next_cursor_str)}isNextCursorInvalid(W){return W===void 0||W===0||W===-1||W==="0"||W==="-1"}}class a4 extends O{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 O{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 N;(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"})(N||(N={}));var e;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(e||(e={}));var q1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(q1||(q1={}));class e1 extends Error{constructor(){super(...arguments);this.error=!0}}class v1 extends e1{constructor(W,Z){super(W);this.type=q1.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 I1 extends e1{constructor(W,Z){super(W);this.type=q1.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 f1 extends e1{constructor(W,Z){super(W);if(this.type=q1.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:G1.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((Y)=>W.includes(Y.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(G1.AuthTimestampInvalid,G1.AuthenticationFail,G1.BadAuthenticationData,G1.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var G1;(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"})(G1||(G1={}));var u6;(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"})(u6||(u6={}));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 y1{constructor(W){this.value=W}}import*as _0 from"fs";var k={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function r4(W){let Z={value:void 0,promise:W().then(($)=>{return Z.value=$,$})};return Z}function W4(W){if(Array.isArray(W))return W;return[W]}function d6(W){for(let Z of Object.keys(W))if(W[Z]===void 0)delete W[Z]}function Z4(W){return typeof W==="object"&&"errors"in W&&!("data"in W)}function A1(W){if(Array.isArray(W)&&W.length>1)return!0;return W.toString().includes(",")}var p6=new Set;function e4(W){if(typeof console>"u"||!console.warn||!k.deprecationWarnings)return;let Z=`${W.instance}-${W.method}-${W.problem}`;if(p6.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."),p6.add(Z)}import{EventEmitter as k5}from"events";import{request as R5}from"https";import*as P from"zlib";import{EventEmitter as O5}from"events";class l6{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(k.debug)k.logger.log("Request error:",W);return new v1("Request failed.",{request:this.req,error:W})}createPartialResponseError(W,Z){let Q=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(Z)Q+=" (connection abruptly closed)";else Q+=" (parse error)";return new I1(Q,{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:Q}){var Y;if(k.debug)k.logger.log(`Request failed with code ${Q}, data:`,Z),k.logger.log("Response headers:",W.headers);let K=`Request failed with code ${Q}`;if((Y=Z===null||Z===void 0?void 0:Z.errors)===null||Y===void 0?void 0:Y.length){let J=Z.errors;if(typeof J[0]==="object"&&"code"in J[0])K+=" - "+this.formatV1Errors(J);else K+=" - "+this.formatV2Error(Z)}return new f1(K,{code:Q,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 $=P.createBrotliDecompress({flush:P.constants.BROTLI_OPERATION_FLUSH,finishFlush:P.constants.BROTLI_OPERATION_FLUSH});return W.pipe($),$}if(Z==="gzip"){let $=P.createGunzip({flush:P.constants.Z_SYNC_FLUSH,finishFlush:P.constants.Z_SYNC_FLUSH});return W.pipe($),$}if(Z==="deflate"){let $=P.createInflate({flush:P.constants.Z_SYNC_FLUSH,finishFlush:P.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 Q=Buffer.concat(Z).toString();return Q.length?JSON.parse(Q):void 0}else if($==="url"){let Q=Buffer.concat(Z).toString(),Y={};for(let[K,J]of new URLSearchParams(Q))Y[K]=J;return Y}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 Q=this.onSocketCloseHandler.bind(this,W);$.on("close",Q),Z.on("complete",()=>$.off("close",Q))}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 $,Q;(Q=($=this.requestData).requestEventDebugHandler)===null||Q===void 0||Q.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 Q=this.getResponseDataStream($);if(Q.on("data",(Y)=>this.responseData.push(Y)),Q.on("end",this.onResponseEndHandler.bind(this,W,Z)),Q.on("close",this.onResponseCloseHandler.bind(this,W,Z)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:$}),$.on("aborted",(Y)=>this.requestData.requestEventDebugHandler("response-aborted",{error:Y})),$.on("error",(Y)=>this.requestData.requestEventDebugHandler("response-error",{error:Y})),$.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),Q;try{Q=this.getParsedResponse(this.res)}catch(K){Z(this.createPartialResponseError(K,!1));return}let Y=this.res.statusCode;if(Y>=400){Z(this.createResponseError({data:Q,res:this.res,rateLimit:$,code:Y}));return}if(k.debug)k.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),k.logger.log("Response body:",Q);W({data:Q,headers:this.res.headers,rateLimit:$})}onResponseCloseHandler(W,Z){let $=this.res;if($.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(W,Z)}catch(Q){return Z(this.createPartialResponseError(Q,!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(k.debug)k.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${$.statusCode} (starting stream)`);let Y=this.getResponseDataStream($);W({req:this.req,res:Y,originalResponse:$,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},Z,$)}debugRequest(){let W=this.requestData.url;if(k.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),W.search)k.logger.log("Request parameters:",[...W.searchParams.entries()].map(([Z,$])=>`${Z}: ${$}`));if(this.requestData.body)k.logger.log("Request body:",this.requestData.body)}buildRequest(){var W;let Z=this.requestData.url,$=Z.username?`${Z.username}:${Z.password}`:void 0,Q=(W=this.requestData.options.headers)!==null&&W!==void 0?W:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")Q["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")Q["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")Q["accept-encoding"]="deflate;q=1, *;q=0.1";if(k.debug)this.debugRequest();this.req=R5({...this.requestData.options,host:Z.hostname,port:Z.port||void 0,path:Z.pathname+Z.search,protocol:Z.protocol,auth:$,headers:Q})}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 $=(J)=>{Y.emit("complete"),W(J)},Q=(J)=>{Y.emit("complete"),Z(J)},Y=new O5,K=this.req;if(K.on("error",this.requestErrorHandler.bind(this,Q)),K.on("socket",this.onSocketEventHandler.bind(this,Q,Y)),K.on("response",this.classicResponseHandler.bind(this,$,Q)),this.requestData.options.timeout)K.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(K);if(this.requestData.body)K.write(this.requestData.body);K.end()})}async makeRequestAsStream(){let{req:W,res:Z,requestData:$,originalResponse:Q}=await this.makeRequestAndResolveWhenReady();return new $4($,{req:W,res:Z,originalResponse:Q})}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 h1=l6;import{EventEmitter as _5}from"events";class n6 extends _5{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 i6=n6;import{EventEmitter as V5}from"events";class Q4 extends V5{constructor(){super(...arguments);this.currentMessage=""}push(W){this.currentMessage+=W,W=this.currentMessage;let Z=W.length,$=0,Q=0;while(Q<Z){if(W.slice(Q,Q+2)===`\r
66
+ `){let Y=W.slice($,Q);if($=Q+=2,!Y.length)continue;try{let K=JSON.parse(Y);if(K){this.emit(X1.ParsedData,K);continue}}catch(K){this.emit(X1.ParseError,K)}}Q++}this.currentMessage=W.slice($,Z)}reset(){this.currentMessage=""}}var X1;(function(W){W.ParsedData="parsed data",W.ParseError="parse error"})(X1||(X1={}));var s6=[5,15,30,60,90,120,180,300,600,900],C5=(W)=>W>s6.length?901000:s6[W-1]*1000;class o6 extends k5{constructor(W,Z){super();if(this.requestData=W,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=C5,this.parser=new Q4,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(X1.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(X1.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 h1(this.requestData).makeRequestAsStream(),$=this.eventNames();for(let Q of $){let Y=this.listeners(Q);for(let K of Y)Z.on(Q,K)}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:Q}=await new h1(this.requestData).makeRequestAndResolveWhenReady();this.req=Z,this.res=$,this.originalResponse=Q,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 i6(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 $4=o6;function a6(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 t6(W,Z,$,Q){let Y;if(Q instanceof v1||Q instanceof I1)Y=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:Q});else if(Q instanceof f1)Y=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:Q});if(Y&&Y instanceof y1)return Y.value;return Promise.reject(Q)}import*as WW from"crypto";class E{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 WW.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=e6(W),$="OAuth ";for(let Q of Z){if(Q.key.indexOf("oauth_")!==0)continue;$+=E.percentEncode(Q.key)+'="'+E.percentEncode(Q.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 E.percentEncode(this.consumerKeys.secret)+"&"+E.percentEncode(W||"")}getBaseString(W,Z){return W.method.toUpperCase()+"&"+E.percentEncode(this.getBaseUrl(W.url))+"&"+E.percentEncode(this.getParameterString(W,Z))}getParameterString(W,Z){let $=e6(b5(r6(Z,r6(W.data,P5(W.url))))),Q="";for(let{key:Y,value:K}of $)if(K&&Array.isArray(K)){K.sort();let J="";K.forEach((z,G)=>{if(J+=Y+"="+z,G<K.length)J+="&"}),Q+=J}else Q+=Y+"="+K+"&";return Q.slice(0,Q.length-1)}getBaseUrl(W){return W.split("?")[0]}}var E1=E;function r6(W,Z){return{...W||{},...Z||{}}}function e6(W){return Object.keys(W).sort().map((Z)=>({key:Z,value:W[Z]}))}function T5(W){let Z=W.split("&"),$={};for(let Q of Z){let[Y,K=""]=Q.split("=");if($[Y]){if(!Array.isArray($[Y]))$[Y]=[$[Y]];$[Y].push(decodeURIComponent(K))}else $[Y]=decodeURIComponent(K)}return $}function P5(W){let Z=W.split("?");if(Z.length===1)return{};return T5(Z[1])}function b5(W){let Z={};for(let $ in W){let Q=W[$];if(Q&&Array.isArray(Q))Q=Q.map((Y)=>E.percentEncode(Y));else Q=E.percentEncode(Q);Z[E.percentEncode($)]=Q}return Z}class g{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...W){let Z=W.map(($)=>$ instanceof Buffer?$:Buffer.from($));this._chunks.push(...Z)}append(W,Z,$){let Q=Z instanceof Buffer?Z:Z.toString(),Y=this.getMultipartHeader(W,Q,$);this.bodyAppend(Y,Q,g.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 Q of W)for(let Y=0;Y<Q.length;$++,Y++)Z[$]=Q[Y];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?g.DEFAULT_CONTENT_TYPE:"";let Q={"Content-Disposition":["form-data",`name="${W}"`],"Content-Type":$},Y="";for(let[K,J]of Object.entries(Q)){if(!J.length)continue;Y+=K+": "+W4(J).join("; ")+g.LINE_BREAK}return"--"+this.getBoundary()+g.LINE_BREAK+Y+g.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+g.LINE_BREAK)}}g.LINE_BREAK=`\r
68
+ `;g.DEFAULT_CONTENT_TYPE="application/octet-stream";class W0{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 Q="";for(let[Y,K]of $)Q+=(Q.length?"&":"?")+`${E1.percentEncode(Y)}=${E1.percentEncode(K)}`;W.search=Q}}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 Q=new g;for(let Y in W)Q.append(Y,W[Y]);if(!Z["content-type"]){let Y=Q.getHeaders();Z["content-type"]=Y["content-type"]}return Q.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 Q in W)$[Q]=W[Q];if(this.isOAuthSerializable(Z))for(let Q in Z){let Y=Z[Q];if(this.isOAuthSerializable(Y))$[Q]=typeof Y==="object"&&Y!==null&&"toString"in Y?Y.toString():Y}return $}static moveUrlQueryParamsIntoObject(W,Z){for(let[$,Q]of W.searchParams)Z[$]=Q;return W.search="",W}static applyRequestParametersToUrl(W,Z){return W.pathname=W.pathname.replace(/:([A-Z_-]+)/ig,($,Q)=>{if(Z[Q]!==void 0)return String(Z[Q]);return $}),W}}W0.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 v=W0;import*as ZW from"crypto";class B1{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url(ZW.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 Q=0;Q<W;Q++)Z+=$[Math.floor(Math.random()*$.length)];return Z}static escapeBase64Url(W){return W.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class H1{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,$,Q,Y,K;if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length){let j=await this.applyPreRequestConfigHooks(W);if(j)return j}let J=this.getHttpRequestArgs(W),z={method:J.method,headers:J.headers,timeout:W.timeout,agent:this.clientSettings.httpAgent},G=W.enableRateLimitSave!==!1;if(J.body)v.setBodyLengthHeader(z,J.body);if(($=this.clientSettings.plugins)===null||$===void 0?void 0:$.length)await this.applyPreRequestHooks(W,J,z);let X=new h1({url:J.url,options:z,body:J.body,rateLimitSaver:G?this.saveRateLimit.bind(this,J.rawUrl):void 0,requestEventDebugHandler:W.requestEventDebugHandler,compression:(Y=(Q=W.compression)!==null&&Q!==void 0?Q:this.clientSettings.compression)!==null&&Y!==void 0?Y:!0,forceParseMode:W.forceParseMode}).makeRequest();if(a6(this))X=this.applyResponseErrorHooks(W,J,z,X);let B=await X;if((K=this.clientSettings.plugins)===null||K===void 0?void 0:K.length){let j=await this.applyPostRequestHooks(W,J,z,B);if(j)return j.value}return B}sendStream(W){var Z,$;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(W);let Q=this.getHttpRequestArgs(W),Y={method:Q.method,headers:Q.headers,agent:this.clientSettings.httpAgent},K=W.enableRateLimitSave!==!1,J=W.autoConnect!==!1;if(Q.body)v.setBodyLengthHeader(Y,Q.body);let z={url:Q.url,options:Y,body:Q.body,rateLimitSaver:K?this.saveRateLimit.bind(this,Q.rawUrl):void 0,payloadIsError:W.payloadIsError,compression:($=(Z=W.compression)!==null&&Z!==void 0?Z:this.clientSettings.compression)!==null&&$!==void 0?$:!0},G=new $4(z);if(!J)return G;return G.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 E1({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 Q;for(let Y of this.getPlugins()){let K=await(($=Y[W])===null||$===void 0?void 0:$.call(Y,Z));if(K&&K instanceof y1)Q=K}return Q}writeAuthHeaders({headers:W,bodyInSignature:Z,url:$,method:Q,query:Y,body:K}){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 "+B1.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let J=Z?v.mergeQueryAndBodyForOAuth(Y,K):Y,z=this._oauth.authorize({url:$.toString(),method:Q,data:J},this.getOAuthAccessTokens());W={...W,...this._oauth.toHeader(z)}}return W}getUrlObjectFromUrlString(W){if(!W.startsWith("http"))W="https://"+W;return new URL(W)}getHttpRequestArgs({url:W,method:Z,query:$={},body:Q={},headers:Y,forceBodyMode:K,enableAuth:J,params:z}){let G=void 0;if(Z=Z.toUpperCase(),Y=Y!==null&&Y!==void 0?Y:{},!Y["x-user-agent"])Y["x-user-agent"]="Node.twitter-api-v2";let X=this.getUrlObjectFromUrlString(W),B=X.origin+X.pathname;if(z)v.applyRequestParametersToUrl(X,z);let j=v.formatQueryToString($);if(v.moveUrlQueryParamsIntoObject(X,j),!(Q instanceof Buffer))d6(Q);let D=K!==null&&K!==void 0?K:v.autoDetectBodyType(X);if(J!==!1){let x=H1.BODY_METHODS.has(Z)&&D==="url";Y=this.writeAuthHeaders({headers:Y,bodyInSignature:x,method:Z,query:j,url:X,body:Q})}if(H1.BODY_METHODS.has(Z))G=v.constructBodyParams(Q,Y,D)||void 0;return v.addQueryParamsToUrl(X,j),{rawUrl:B,url:X,method:Z,headers:Y,body:G}}async applyPreRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let Q of this.getPlugins()){let Y=await((Z=Q.onBeforeRequestConfig)===null||Z===void 0?void 0:Z.call(Q,{client:this,url:$,params:W}));if(Y)return Y}}applyPreStreamRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let Q of this.getPlugins())(Z=Q.onBeforeStreamRequestConfig)===null||Z===void 0||Z.call(Q,{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,$,Q){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,response:Q})}applyResponseErrorHooks(W,Z,$,Q){return Q.catch(t6.bind(this,W,Z,$))}}H1.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class W1{constructor(W,Z={}){if(this._currentUser=null,this._currentUserV2=null,W instanceof W1)this._requestMaker=W._requestMaker;else this._requestMaker=new H1(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=r4(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:r})),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=r4(()=>this.get("users/me",void 0,{prefix:t})),this._currentUserV2.promise}async get(W,Z={},{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"GET",query:Z,...Y});return $?K:K.data}async delete(W,Z={},{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"DELETE",query:Z,...Y});return $?K:K.data}async post(W,Z,{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"POST",body:Z,...Y});return $?K:K.data}async put(W,Z,{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"PUT",body:Z,...Y});return $?K:K.data}async patch(W,Z,{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"PATCH",body:Z,...Y});return $?K:K.data}getStream(W,Z,{prefix:$=this._prefix,...Q}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"GET",query:Z,...Q})}postStream(W,Z,{prefix:$=this._prefix,...Q}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"POST",body:Z,...Q})}}class I extends W1{constructor(W){if(!(W instanceof W1))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(W)}}class N1 extends D1{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 Z0 extends N1{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class $0 extends N1{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class Y4 extends N1{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class Q0 extends N1{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class K4 extends N1{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class Y0 extends O{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 K0 extends O{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 J0 extends O{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 z0 extends O{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 G0 extends O{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 X0 extends O{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 B0 extends D1{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 J4 extends O{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 j0 extends J4{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class z4 extends O{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 M0 extends z4{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class F0 extends z4{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class L0 extends z4{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class D0 extends O{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 H0 extends D0{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class N0 extends D0{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class U1 extends I{constructor(){super(...arguments);this._prefix=r}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 Z0({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 $0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},Q=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new Y4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async userTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},Q=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new Y4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async favoriteTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},Q=await this.get("favorites/list.json",$,{fullResponse:!0});return new K4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async favoriteTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},Q=await this.get("favorites/list.json",$,{fullResponse:!0});return new K4({realData:Q.data,rateLimit:Q.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 Y0({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 K0({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 G0({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 J0({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 z0({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 X0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async searchUsers(W,Z={}){let $={q:W,tweet_mode:"extended",page:1,...Z},Q=await this.get("users/search.json",$,{fullResponse:!0});return new B0({realData:Q.data,rateLimit:Q.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 J4({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 j0({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 H0({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 M0({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 F0({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 Q0({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 N0({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 L0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}mediaInfo(W){return this.get("media/upload.json",{command:"STATUS",media_id:W},{prefix:s})}filterStream({autoConnect:W,...Z}={}){let $={};for(let[Y,K]of Object.entries(Z))if(Y==="follow"||Y==="track")$[Y]=K.toString();else if(Y==="locations"){let J=K;$.locations=W4(J).map((z)=>`${z.lng},${z.lat}`).join(",")}else $[Y]=K;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 G4(this);return W.setPrefix(c6),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 Z1 from"fs";async function U0(W){let Z=await x0(W);if(typeof Z==="number")return new Promise(($,Q)=>{Z1.readFile(Z,(Y,K)=>{if(Y)return Q(Y);$(K)})});else if(Z instanceof Buffer)return Z;else return Z.readFile()}function x0(W){if(typeof W==="string")return Z1.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 $W(W){if(typeof W==="number")return(await new Promise(($,Q)=>{Z1.fstat(W,(Y,K)=>{if(Y)Q(Y);$(K)})})).size;else if(W instanceof Buffer)return W.length;else return(await W.stat()).size}function QW(W,Z,$){if(typeof $==="string")return $;else if(typeof W==="string"&&!Z)return w5(W);else if(typeof Z==="string")return q5(Z);throw Error("You must specify type if file is a file handle or Buffer.")}function w5(W){if(W.endsWith(".jpeg")||W.endsWith(".jpg"))return N.Jpeg;if(W.endsWith(".png"))return N.Png;if(W.endsWith(".webp"))return N.Webp;if(W.endsWith(".gif"))return N.Gif;if(W.endsWith(".mpeg4")||W.endsWith(".mp4"))return N.Mp4;if(W.endsWith(".mov")||W.endsWith(".mov"))return N.Mov;if(W.endsWith(".srt"))return N.Srt;return e4({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"options.mimeType is missing and filename couldn't help to resolve MIME type, so it will fallback to image/jpeg",resolution:"If you except to give filenames without extensions, please specify explicitlty the MIME type using options.mimeType"}),N.Jpeg}function q5(W){if(e4({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"you're using options.type",resolution:"Remove options.type argument and migrate to options.mimeType which takes the real MIME type. If you're using type=longmp4, add options.longVideo alongside of mimeType=EUploadMimeType.Mp4"}),W==="gif")return N.Gif;if(W==="jpg")return N.Jpeg;if(W==="png")return N.Png;if(W==="webp")return N.Webp;if(W==="srt")return N.Srt;if(W==="mp4"||W==="longmp4")return N.Mp4;if(W==="mov")return N.Mov;return W}function YW(W,Z){if(W===N.Mp4||W===N.Mov)return Z==="tweet"?"TweetVideo":"DmVideo";if(W===N.Gif)return Z==="tweet"?"TweetGif":"DmGif";if(W===N.Srt)return"Subtitles";else return Z==="tweet"?"TweetImage":"DmImage"}function S0(W){return new Promise((Z)=>setTimeout(Z,W*1000))}async function R0(W,Z,$=0,Q){if(W instanceof Buffer){let K=W.slice($,$+Z);return[K,K.length]}if(!Q)throw Error("Well, we will need a buffer to store file content.");let Y;if(typeof W==="number")Y=await new Promise((K,J)=>{Z1.read(W,Q,0,Z,$,(z,G)=>{if(z)J(z);K(G)})});else Y=(await W.read(Q,0,Z,$)).bytesRead;return[Q,Y]}var O0="media/upload.json";class x1 extends U1{constructor(){super(...arguments);this._prefix=r}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 Q="https://x.com/i/statuses/"+Z;return this.tweet(W,{...$,attachment_url:Q})}async tweetThread(W){let Z=[];for(let $ of W){let Q=Z.length?Z[Z.length-1]:null,Y={...typeof $==="string"?{status:$}:$},K=Q?Q.id_str:Y.in_reply_to_status_id,J=Y.status;if(K)Z.push(await this.reply(J,K,Y));else Z.push(await this.tweet(J,Y))}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 U0(W),...Z};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,Z={}){let $={tweet_mode:"extended",image:await U0(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&&A1(W.user_id)||W.screen_name&&A1(W.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,W)}removeListMembers(W){let $=W.user_id&&A1(W.user_id)||W.screen_name&&A1(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:s,forceBodyMode:"json"})}createMediaSubtitles(W,Z){return this.post("media/subtitles/create.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z}},{prefix:s,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:s,forceBodyMode:"json"})}async uploadMedia(W,Z={},$=!1){var Q;let Y=(Q=Z.chunkLength)!==null&&Q!==void 0?Q:1048576,{fileHandle:K,mediaCategory:J,fileSize:z,mimeType:G}=await this.getUploadMediaRequirements(W,Z);try{let X=await this.post(O0,{command:"INIT",total_bytes:z,media_type:G,media_category:J,additional_owners:Z.additionalOwners,shared:Z.shared?!0:void 0},{prefix:s});await this.mediaChunkedUpload(K,Y,X.media_id_string,Z.maxConcurrentUploads);let B=await this.post(O0,{command:"FINALIZE",media_id:X.media_id_string},{prefix:s});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")_0.close(W,()=>{});else if(typeof K==="object"&&!(K instanceof Buffer))K.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:Q,message:Y}=$.error;throw Error(`Failed to process media: ${Q} - ${Y}.`)}if($.state==="failed")throw Error("Failed to process the media.");if($.check_after_secs)await S0($.check_after_secs);else await S0(5)}}async getUploadMediaRequirements(W,{mimeType:Z,type:$,target:Q,longVideo:Y}={}){let K;try{K=await x0(W);let J=QW(W,$,Z),z;if(J===N.Mp4&&(!Z&&!$&&Q!=="dm"||Y))z="amplify_video";else z=YW(J,Q!==null&&Q!==void 0?Q:"tweet");return{fileHandle:K,mediaCategory:z,fileSize:await $W(K),mimeType:J}}catch(J){if(typeof W==="number")_0.close(W,()=>{});else if(typeof K==="object"&&!(K instanceof Buffer))K.close();throw J}}async mediaChunkedUpload(W,Z,$,Q=3){let Y=0;if(Q<1)throw RangeError("Bad maxConcurrentUploads parameter.");let K=W instanceof Buffer?void 0:Buffer.alloc(Z),J,z,G=0;[J,z]=await R0(W,Z,G,K),G+=z;let X=new Set;while(z){let B=J.slice(0,z);if(B.length){let j=this.post(O0,{command:"APPEND",media_id:$,segment_index:Y,media:B},{prefix:s});X.add(j),j.then(()=>{X.delete(j)}),Y++}if(X.size>=Q)await Promise.race(X);[J,z]=await R0(W,Z,G,K),G+=z}await Promise.all([...X])}}class KW extends x1{constructor(){super(...arguments);this._prefix=r}get readWrite(){return this}sendDm({recipient_id:W,custom_profile_id:Z,...$}){let Q={event:{type:e.Create,[e.Create]:{target:{recipient_id:W},message_data:$}}};if(Z)Q.event[e.Create].custom_profile_id=Z;return this.post("direct_messages/events/new.json",Q,{forceBodyMode:"json"})}getDmEvent(W){return this.get("direct_messages/events/show.json",{id:W})}deleteDm(W){return this.delete("direct_messages/events/destroy.json",{id:W})}async listDmEvents(W={}){let Z={...W},$=await this.get("direct_messages/events/list.json",Z,{fullResponse:!0});return new a4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDm(W,Z){let $={[e.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 Q=await this.listWelcomeDmRules();if(($=Q.welcome_message_rules)===null||$===void 0?void 0:$.length){for(let Y of Q.welcome_message_rules)if(await this.deleteWelcomeDmRule(Y.id),Z)await this.deleteWelcomeDm(Y.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[e.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 G4=KW;class H{constructor(W){this.result=W}get tweets(){return H.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 H.tweetById(this.result,W)}static tweetById(W,Z){return this.tweets(W).find(($)=>$.id===Z)}retweet(W){return H.retweet(this.result,W)}static retweet(W,Z){var $;let Q=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Y)=>Y.type==="retweeted").map((Y)=>Y.id);return this.tweets(W).find((Y)=>Q.includes(Y.id))}quote(W){return H.quote(this.result,W)}static quote(W,Z){var $;let Q=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Y)=>Y.type==="quoted").map((Y)=>Y.id);return this.tweets(W).find((Y)=>Q.includes(Y.id))}repliedTo(W){return H.repliedTo(this.result,W)}static repliedTo(W,Z){var $;let Q=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Y)=>Y.type==="replied_to").map((Y)=>Y.id);return this.tweets(W).find((Y)=>Q.includes(Y.id))}author(W){return H.author(this.result,W)}static author(W,Z){let $=Z.author_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}repliedToAuthor(W){return H.repliedToAuthor(this.result,W)}static repliedToAuthor(W,Z){let $=Z.in_reply_to_user_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}get users(){return H.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 H.userById(this.result,W)}static userById(W,Z){return this.users(W).find(($)=>$.id===Z)}pinnedTweet(W){return H.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 H.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 H.medias(this.result,W)}static medias(W,Z){var $,Q;let Y=(Q=($=Z.attachments)===null||$===void 0?void 0:$.media_keys)!==null&&Q!==void 0?Q:[];return this.media(W).filter((K)=>Y.includes(K.media_key))}get polls(){return H.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 H.poll(this.result,W)}static poll(W,Z){var $,Q;let Y=(Q=($=Z.attachments)===null||$===void 0?void 0:$.poll_ids)!==null&&Q!==void 0?Q:[];if(Y.length){let K=Y[0];return this.polls(W).find((J)=>J.id===K)}return}get places(){return H.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 H.place(this.result,W)}static place(W,Z){var $;let Q=($=Z.geo)===null||$===void 0?void 0:$.place_id;return Q?this.places(W).find((Y)=>Y.id===Q):void 0}listOwner(W){return H.listOwner(this.result,W)}static listOwner(W,Z){let $=Z.owner_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}spaceCreator(W){return H.spaceCreator(this.result,W)}static spaceCreator(W,Z){let $=Z.creator_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}spaceHosts(W){return H.spaceHosts(this.result,W)}static spaceHosts(W,Z){var $;let Q=($=Z.host_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Y)=>Q.includes(Y.id))}spaceSpeakers(W){return H.spaceSpeakers(this.result,W)}static spaceSpeakers(W,Z){var $;let Q=($=Z.speaker_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Y)=>Q.includes(Y.id))}spaceInvitedUsers(W){return H.spaceInvitedUsers(this.result,W)}static spaceInvitedUsers(W,Z){var $;let Q=($=Z.invited_user_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Y)=>Q.includes(Y.id))}}class X4 extends o4{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[$,Q]of Object.entries(W.includes)){if(!Z[$])Z[$]=[];Z[$]=[...Z[$],...Q]}}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 H(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new H(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 d extends X4{refreshInstanceFromResult(W,Z){var $;let Q=W.data,Y=($=Q.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.result_count+=Q.meta.result_count,this._realData.meta.next_token=Q.meta.next_token,this._realData.data.push(...Y);else this._realData.meta.result_count+=Q.meta.result_count,this._realData.meta.previous_token=Q.meta.previous_token,this._realData.data.unshift(...Y);this.updateIncludes(Q)}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 V0 extends X4{refreshInstanceFromResult(W,Z){var $;let Q=W.data,Y=($=Q.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.oldest_id=Q.meta.oldest_id,this._realData.meta.result_count+=Q.meta.result_count,this._realData.meta.next_token=Q.meta.next_token,this._realData.data.push(...Y);else this._realData.meta.newest_id=Q.meta.newest_id,this._realData.meta.result_count+=Q.meta.result_count,this._realData.data.unshift(...Y);this.updateIncludes(Q)}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 S1 extends d{refreshInstanceFromResult(W,Z){super.refreshInstanceFromResult(W,Z);let $=W.data;if(Z)this._realData.meta.oldest_id=$.meta.oldest_id;else this._realData.meta.newest_id=$.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class k0 extends V0{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class C0 extends V0{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class T0 extends S1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class P0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class b0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class w0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class q0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class v0 extends d{get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class I0 extends v0{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class f0 extends v0{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class o extends d{getItemArray(){return this.users}get users(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class y0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class A0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class h0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class E0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class g0 extends o{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class m0 extends o{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class c0 extends o{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class u0 extends o{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class B4 extends d{getItemArray(){return this.lists}get lists(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class p0 extends B4{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class d0 extends B4{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class l0 extends B4{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class R1 extends I{constructor(){super(...arguments);this._prefix=M1}}class j4 extends d{getItemArray(){return this.events}get events(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class n0 extends j4{constructor(){super(...arguments);this._endpoint="dm_events"}}class i0 extends j4{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class s0 extends j4{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class O1 extends I{constructor(){super(...arguments);this._prefix=t}get labs(){if(this._labs)return this._labs;return this._labs=new R1(this)}async search(W,Z={}){let $=typeof W==="string"?{...Z,query:W}:{...W},Q=await this.get("tweets/search/recent",$,{fullResponse:!0});return new k0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async searchAll(W,Z={}){let $={...Z,query:W},Q=await this.get("tweets/search/all",$,{fullResponse:!0});return new C0({realData:Q.data,rateLimit:Q.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:$,...Q}=Z,Y=await this.get("tweets/:id/retweeted_by",Q,{fullResponse:!0,params:{id:W}});if(!$)return Y.data;return new u0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:Q,sharedParams:{id:W}})}async tweetLikedBy(W,Z={}){let{asPaginator:$,...Q}=Z,Y=await this.get("tweets/:id/liking_users",Q,{fullResponse:!0,params:{id:W}});if(!$)return Y.data;return new c0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:Q,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 P0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:Z.data.id}})}async userTimeline(W,Z={}){let $=await this.get("users/:id/tweets",Z,{fullResponse:!0,params:{id:W}});return new b0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async userMentionTimeline(W,Z={}){let $=await this.get("users/:id/mentions",Z,{fullResponse:!0,params:{id:W}});return new w0({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 T0({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 q0({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:$,...Q}=Z,Y={id:W};if(!$)return this.get("users/:id/followers",Q,{params:Y});let K=await this.get("users/:id/followers",Q,{fullResponse:!0,params:Y});return new h0({realData:K.data,rateLimit:K.rateLimit,instance:this,queryParams:Q,sharedParams:Y})}async following(W,Z={}){let{asPaginator:$,...Q}=Z,Y={id:W};if(!$)return this.get("users/:id/following",Q,{params:Y});let K=await this.get("users/:id/following",Q,{fullResponse:!0,params:Y});return new E0({realData:K.data,rateLimit:K.rateLimit,instance:this,queryParams:Q,sharedParams:Y})}async userLikedTweets(W,Z={}){let $={id:W},Q=await this.get("users/:id/liked_tweets",Z,{fullResponse:!0,params:$});return new I0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userBlockingUsers(W,Z={}){let $={id:W},Q=await this.get("users/:id/blocking",Z,{fullResponse:!0,params:$});return new y0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userMutingUsers(W,Z={}){let $={id:W},Q=await this.get("users/:id/muting",Z,{fullResponse:!0,params:$});return new A0({realData:Q.data,rateLimit:Q.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},Q=await this.get("users/:id/owned_lists",Z,{fullResponse:!0,params:$});return new p0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMemberships(W,Z={}){let $={id:W},Q=await this.get("users/:id/list_memberships",Z,{fullResponse:!0,params:$});return new d0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowed(W,Z={}){let $={id:W},Q=await this.get("users/:id/followed_lists",Z,{fullResponse:!0,params:$});return new l0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listTweets(W,Z={}){let $={id:W},Q=await this.get("lists/:id/tweets",Z,{fullResponse:!0,params:$});return new f0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMembers(W,Z={}){let $={id:W},Q=await this.get("lists/:id/members",Z,{fullResponse:!0,params:$});return new g0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowers(W,Z={}){let $={id:W},Q=await this.get("lists/:id/followers",Z,{fullResponse:!0,params:$});return new m0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEvents(W={}){let Z=await this.get("dm_events",W,{fullResponse:!0});return new n0({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:{...W}})}async listDmEventsWithParticipant(W,Z={}){let $={participant_id:W},Q=await this.get("dm_conversations/with/:participant_id/dm_events",Z,{fullResponse:!0,params:$});return new i0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEventsOfConversation(W,Z={}){let $={dm_conversation_id:W},Q=await this.get("dm_conversations/:dm_conversation_id/dm_events",Z,{fullResponse:!0,params:$});return new s0({realData:Q.data,rateLimit:Q.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:Z4,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:Z4,autoConnect:W})}sample10Stream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample10/stream",Z,{payloadIsError:Z4,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
+ `));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((Q)=>setTimeout(Q,3500)),Z=(await this.complianceJob(W.id)).data}return(await this.get(W.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split(`
70
+ `).filter((Q)=>Q).map((Q)=>JSON.parse(Q))}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 _1 extends R1{constructor(){super(...arguments);this._prefix=M1}get readOnly(){return this}}class V1 extends O1{constructor(){super(...arguments);this._prefix=t}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new _1(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 Q=Z.media_category;if(!Z.media_category){if(Z.media_type.includes("gif"))Q="tweet_gif";else if(Z.media_type.includes("image"))Q="tweet_image";else if(Z.media_type.includes("video"))Q="tweet_video"}let Y={additional_owners:Z.additional_owners,media_type:Z.media_type,total_bytes:W.length,media_category:Q},J=(await this.post("media/upload/initialize",Y)).data.id,z=Math.ceil(W.length/$),G=new Uint8Array(W);for(let B=0;B<z;B++){let j=B*$,D=Math.min(j+$,W.length),x=G.slice(j,D),V=Buffer.from(x),Q1={segment_index:B,media:V};await this.post(`media/upload/${J}/append`,Q1,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${J}/finalize`)).data.processing_info)await this.waitForMediaProcessing(J);return J}async waitForMediaProcessing(W){var Z;let Q=(await this.get("media/upload",{command:"STATUS",media_id:W})).data.processing_info;if(!Q)return;switch(Q.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(Z=Q.error)===null||Z===void 0?void 0:Z.message}`);case"pending":case"in_progress":{let Y=Q===null||Q===void 0?void 0:Q.check_after_secs;if(Y&&Y>0)await new Promise((K)=>setTimeout(K,Y*1000)),await this.waitForMediaProcessing(W)}}}createMediaMetadata(W,Z){return this.post("media/metadata",{id:W,metadata:Z})}reply(W,Z,$={}){var Q;let Y={in_reply_to_tweet_id:Z,...(Q=$.reply)!==null&&Q!==void 0?Q:{}};return this.post("tweets",{text:W,...$,reply:Y})}quote(W,Z,$={}){return this.tweet(W,{...$,quote_tweet_id:Z})}async tweetThread(W){var Z,$;let Q=[];for(let Y of W){let K=Q.length?Q[Q.length-1]:null,J={...typeof Y==="string"?{text:Y}:Y},z=K?K.data.id:(Z=J.reply)===null||Z===void 0?void 0:Z.in_reply_to_tweet_id,G=($=J.text)!==null&&$!==void 0?$:"";if(z)Q.push(await this.reply(G,z,J));else Q.push(await this.tweet(G,J))}return Q}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 JW extends _1{constructor(){super(...arguments);this._prefix=M1}get readWrite(){return this}}var zW=JW;class GW extends V1{constructor(){super(...arguments);this._prefix=t}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new zW(this)}}var XW=GW;class g1 extends W1{get v1(){if(this._v1)return this._v1;return this._v1=new U1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new O1(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:Q,screenName:Y}={}){let K=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:W,x_auth_access_type:Z}),J=`https://api.x.com/oauth/${$}?oauth_token=${encodeURIComponent(K.oauth_token)}`;if(Q!==void 0)J+=`&force_login=${encodeURIComponent(Q)}`;if(Y!==void 0)J+=`&screen_name=${encodeURIComponent(Y)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:J,oauthResult:K});return{url:J,...K}}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}),Q=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:Q}}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 $,Q;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 Y=($=Z.state)!==null&&$!==void 0?$:B1.generateRandomString(32),K=B1.getCodeVerifier(),J=B1.getCodeChallengeFromVerifier(K),z=(Q=Z.scope)!==null&&Q!==void 0?Q:"",G=Array.isArray(z)?z.join(" "):z,X=new URL("https://x.com/i/oauth2/authorize"),B={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:W,state:Y,code_challenge:J,code_challenge_method:"s256",scope:G};v.addQueryParamsToUrl(X,B);let j={url:X.toString(),state:Y,codeVerifier:K,codeChallenge:J};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 Q=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(Q)}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((Q)=>Q);return{client:Z,expiresIn:W.expires_in,accessToken:W.access_token,scope:$,refreshToken:W.refresh_token}}}class m1 extends g1{get v1(){if(this._v1)return this._v1;return this._v1=new x1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new V1(this)}get readOnly(){return this}}class M4 extends I{constructor(){super(...arguments);this._prefix=F1}}class F4 extends M4{constructor(){super(...arguments);this._prefix=F1}get readOnly(){return this}}class L4 extends I{constructor(){super(...arguments);this._prefix=L1}}class D4 extends L4{constructor(){super(...arguments);this._prefix=L1}get readOnly(){return this}}class BW extends D4{constructor(){super(...arguments);this._prefix=L1}get readWrite(){return this}}var jW=BW;class MW extends F4{constructor(){super(...arguments);this._prefix=F1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new jW(this)}}var FW=MW;class H4 extends m1{get v1(){if(this._v1)return this._v1;return this._v1=new G4(this)}get v2(){if(this._v2)return this._v2;return this._v2=new XW(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new FW(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(),Q=["normal","bigger","mini"],Y=W;for(let J of Q)if($.includes(`_${J}`)){Y=W.replace(`_${J}`,"");break}if(Z==="original")return Y;let K=Y.lastIndexOf(".");if(K!==-1){let J=Y.slice(K+1);return Y.slice(0,K)+"_"+Z+"."+J}else return Y+"_"+Z}}var v5={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class LW extends i{config;client;constructor(W={}){super();this.config={...v5,...W},this.client=new H4({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${q()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"XOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>q()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!Z)throw Error("XOAuthProvider needs the state and PKCE challenge gemi passes.");if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("XOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL("https://x.com/i/oauth2/authorize"),Q={response_type:"code",client_id:W.clientId,redirect_uri:W.redirectUri,state:Z.state,code_challenge:Z.codeChallenge,code_challenge_method:Z.codeChallengeMethod,scope:this.config.scope.join(" ")};for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new R("missing_code");if(!Z?.codeVerifier)throw new R("invalid_state");let Q=this.config.resolve?await this.clientFor(W):this.staticClient();if(!Q)throw new R("unknown_provider");let Y=this.config.resolve?new H4({clientId:Q.clientId,clientSecret:Q.clientSecret}):this.client,K;try{K=await Y.loginWithOAuth2({code:$,codeVerifier:Z.codeVerifier,redirectUri:Q.redirectUri})}catch(j){throw console.error("X OAuth error: token exchange failed",j),new R("exchange_failed")}let{data:J}=await K.client.v2.me({"user.fields":["name","username","entities"]}),{name:z,email:G,id:X="",username:B}=J??{};return{name:z,email:G,username:B,providerId:X}}}var HW=["instagram_business_basic"],l={authorizeUrl:"https://www.instagram.com/oauth/authorize",tokenUrl:"https://api.instagram.com/oauth/access_token",graphUrl:"https://graph.instagram.com"};class m extends Error{status;type;code;constructor(W,Z,$,Q,Y){super(W,Y);this.status=Z;this.type=$;this.code=Q;this.name="InstagramApiError"}}async function N4(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 x4(W.tokenUrl??l.tokenUrl,"code exchange",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Z.toString()}),Q=Array.isArray($.data)?$.data[0]:$,Y=Q?.access_token;if(typeof Y!=="string"||Y==="")throw new m("Instagram's code exchange answered without an access token.",200);let K=Q?.permissions;return{accessToken:Y,userId:o0(Q?.user_id),permissions:Array.isArray(K)?K.map(String):typeof K==="string"?K.split(/[\s,]+/).filter(Boolean):null}}async function NW(W){let Z=new URL("/access_token",W.graphUrl??l.graphUrl);return Z.searchParams.set("grant_type","ig_exchange_token"),Z.searchParams.set("client_secret",W.clientSecret),Z.searchParams.set("access_token",W.accessToken),xW(await x4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function UW(W){let Z=new URL("/refresh_access_token",W.graphUrl??l.graphUrl);return Z.searchParams.set("grant_type","ig_refresh_token"),Z.searchParams.set("access_token",W.accessToken),xW(await x4(Z.toString(),"token refresh",{method:"GET"}))}async function U4(W){let Z=W.graphApiVersion?`/${W.graphApiVersion.replace(/^\/+|\/+$/g,"")}`:"",$=new URL(`${Z}/me`,W.graphUrl??l.graphUrl);$.searchParams.set("fields",(W.fields??["user_id","username","name","account_type","profile_picture_url"]).join(",")),$.searchParams.set("access_token",W.accessToken);let Q=await x4($.toString(),"profile request",{method:"GET"}),Y=Array.isArray(Q.data)?Q.data[0]:Q,K=o0(Y?.user_id);if(!K)throw new m("Instagram's /me answered without a user_id.",200);let J={user_id:K},z=o0(Y?.id);if(z)J.id=z;for(let G of["username","name","account_type","profile_picture_url"]){let X=Y?.[G];if(typeof X==="string"&&X!=="")J[G]=X}return J}function xW(W){if(typeof W.access_token!=="string"||W.access_token==="")throw new m("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 x4(W,Z,$){let Q;try{Q=await fetch(W,{...$,redirect:"error"})}catch(K){throw new m(`Instagram's ${Z} failed to reach Instagram.`,void 0,void 0,void 0,{cause:K})}let Y=a0(await Q.text().catch(()=>""));if(!Q.ok){let K=Y.error??{},J=DW(Y.error_type)??DW(K.type),z=Number(Y.code??K.code);throw new m(`Instagram refused the ${Z} (HTTP ${Q.status}${J?`, ${J}`:""}${Number.isFinite(z)?` ${z}`:""}).`,Q.status,J,Number.isFinite(z)?z:void 0)}return Y}function a0(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 o0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function DW(W){return typeof W==="string"&&W!==""?W:void 0}class SW 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:HW,redirectPath:"/auth/oauth/instagram/callback",authorizationParams:{},...W}}redirectUri(){return`${q()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"InstagramOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>q()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("InstagramOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(this.config.authorizeUrl??l.authorizeUrl),Q={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,response_type:"code",scope:this.config.scopes.join(",")};if(Z)Q.state=Z.state;for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W){let Z=W.search.get("code");if(!Z)throw new R("missing_code");let $=this.config.resolve?await this.clientFor(W):this.staticClient();if(!$)throw new R("unknown_provider");let Q;try{let Y=await N4({code:Z,clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.redirectUri,tokenUrl:this.config.tokenUrl});Q=await U4({accessToken:Y.accessToken,graphUrl:this.config.graphUrl,graphApiVersion:this.config.graphApiVersion,fields:["user_id","username","name"]})}catch(Y){if(Y instanceof m)throw console.error(`Instagram OAuth error: ${Y.message}`),new R("exchange_failed");throw Y}return{providerId:Q.user_id,username:Q.username,name:Q.name||Q.username}}}import{createHmac as I5,timingSafeEqual as f5}from"crypto";class c extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function y5(W,Z,$={}){if(!Z)throw Error("parseMetaSignedRequest needs the app secret.");if(typeof W!=="string")throw new c("malformed","No signed_request was given.");let Q=W.indexOf(".");if(Q<=0||Q===W.length-1||W.indexOf(".",Q+1)!==-1)throw new c("malformed","A signed_request is <signature>.<payload>.");let Y=W.slice(0,Q),K=W.slice(Q+1);if(!/^[A-Za-z0-9_-]+={0,2}$/.test(Y)||!/^[A-Za-z0-9_-]+={0,2}$/.test(K))throw new c("malformed","A signed_request is base64url.");let J=I5("sha256",Z).update(K).digest(),z=Buffer.from(Y,"base64url");if(z.length!==J.length||!f5(z,J))throw new c("bad_signature","The signed_request's signature does not match the app secret.");let G;try{let D=Buffer.from(K,"base64url").toString("utf8").replace(/("user_id"\s*:\s*)(-?\d+)(?=\s*[,}])/g,'$1"$2"');G=JSON.parse(D)}catch{throw new c("malformed","The signed_request's payload is not JSON.")}if(!G||typeof G!=="object")throw new c("malformed","The signed_request's payload is not an object.");if(String(G.algorithm??"").toUpperCase()!=="HMAC-SHA256")throw new c("unsupported_algorithm","Only HMAC-SHA256 signed_requests are accepted.");let X=Math.floor(($.now??Date.now())/1000),B=Number(G.expires);if(Number.isFinite(B)&&B>0&&B<X)throw new c("expired","The signed_request has expired.");let j=G.user_id;if((typeof j!=="string"||j==="")&&typeof j!=="number")throw new c("missing_user","The signed_request names no user.");return{...G,algorithm:String(G.algorithm),user_id:String(j)}}var A5=86400000;class R4 extends b{instagram;constructor(W={}){let Z={authorizeUrl:W.authorizeUrl??l.authorizeUrl,tokenUrl:W.tokenUrl??l.tokenUrl,graphUrl:W.graphUrl??l.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:t0,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<A5){if($.reason==="rejected")throw new U("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let Q=await S4("refresh_failed",()=>UW({accessToken:$.accessToken,graphUrl:Z.graphUrl}));return{accessToken:Q.accessToken,refreshToken:null,tokenType:Q.tokenType,expiresAt:Q.expiresIn===null?null:new Date(Date.now()+Q.expiresIn*1000),scopes:$.scopes,providerAccountId:$.providerAccountId}}});this.instagram=Z}async exchangeCode(W){let Z=await S4("exchange_failed",()=>N4({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await S4("exchange_failed",()=>NW({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),Q=await S4("exchange_failed",()=>U4({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:Q.user_id,profile:{...Q}}}refresh(){return Promise.reject(new U("refresh_failed","Instagram connections renew the access token itself; call connection.refresh()."))}}async function t0(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 S4(W,Z){try{return await Z()}catch($){if($ instanceof m)throw new U(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}async function S(W,Z,$){let Q;try{Q=await $()}catch(K){if(K instanceof U)throw K;throw new U(Z,`The ${W} request failed.`,{cause:K})}let Y=await Q.json().catch(()=>null);if(!Q.ok||Y===null||typeof Y!=="object")throw new U(Z,`The ${W} request was refused (HTTP ${Q.status}).`,{status:Q.ok?502:Q.status});return Y}function $1(W,Z,$={}){return fetch(W,{headers:{...$,Authorization:`Bearer ${Z}`,Accept:"application/json"},redirect:"error"})}function f(W,Z,$){if(W.connectionProvider()!==Z)throw TypeError(`${$} takes a connection to this provider; "${W.provider}" is configured with another one.`)}function F(W){return typeof W==="string"&&W!==""?W:null}var y=F;function u(W){return new U("exchange_failed",`${W} did not say which account was connected.`,{status:502})}var RW=["pages_show_list","pages_read_engagement","pages_manage_posts"];class OW extends b{configId;graphApiVersion;constructor(W={}){let Z=W.graphApiVersion?.replace(/^\/+|\/+$/g,""),$=Z?`/${Z}`:"",Q=W.apiBaseUrl??"https://graph.facebook.com";super({authorizeUrl:W.authorizeUrl??`${W.dialogUrl??"https://www.facebook.com"}${$}/dialog/oauth`,tokenUrl:W.tokenUrl??`${Q}${$}/oauth/access_token`,revokeUrl:W.revokeUrl??`${Q}${$}/me/permissions`,apiBaseUrl:Q,clientId:W.clientId??process.env.FACEBOOK_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.FACEBOOK_CLIENT_SECRET??"",scopes:W.scopes??RW,scopeSeparator:",",pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??60,multiple:W.multiple??!1,tokenPlacement:"query",revokeTokenHint:"access_token",isTokenRejected:t0,refreshStrategy:async(Y)=>{if(Y.reason==="rejected")throw new U("refresh_failed","Facebook refused the access token (OAuthException 190).",{status:401});return null}});this.configId=W.configId??(process.env.FACEBOOK_CONFIG_ID||void 0),this.graphApiVersion=Z||void 0}authorizationUrl(W){let Z=new URL(super.authorizationUrl(W));if(this.configId)Z.searchParams.delete("scope"),Z.searchParams.set("config_id",this.configId);return Z.toString()}async exchangeCode(W){let Z=await this.tokenCall({client_id:this.config.clientId,client_secret:this.config.clientSecret,redirect_uri:W.redirectUri,code:W.code}),$=await this.tokenCall({grant_type:"fb_exchange_token",client_id:this.config.clientId,client_secret:this.config.clientSecret,fb_exchange_token:Z.accessToken}),Q=$.accessToken,Y=await S("Facebook /me","exchange_failed",()=>fetch(this.graphUrl(this.path("/me",{fields:"id,name,picture{url}"}),Q),{redirect:"error"})),K=y(Y.id);if(!K)throw u("Facebook");let J=await S("Facebook /me/permissions","exchange_failed",()=>fetch(this.graphUrl(this.path("/me/permissions"),Q),{redirect:"error"})),z=(Array.isArray(J.data)?J.data:[]).filter((B)=>B.status==="granted"&&typeof B.permission==="string").map((B)=>B.permission),G=await this.listPages((B)=>fetch(this.graphUrl(B,Q),{redirect:"error"}),"exchange_failed"),X={id:K,name:F(Y.name),username:null,avatarUrl:r0(Y.picture),pages:G.map(({accessToken:B,...j})=>j)};return{accessToken:Q,refreshToken:null,tokenType:$.tokenType,expiresAt:$.expiresIn===null?null:new Date(Date.now()+$.expiresIn*1000),scopes:z.length>0?z:this.config.scopes,providerAccountId:K,profile:{...X}}}refresh(){return Promise.reject(new U("refresh_failed","Facebook issues no refresh token; reconnect the account."))}async revoke(W){let Z=new URL(this.config.revokeUrl);Z.searchParams.set("access_token",W);let $;try{$=await fetch(Z,{method:"DELETE",redirect:"error"})}catch(Q){throw new U("revoke_failed","The revocation request failed.",{cause:Q})}if(await $.body?.cancel().catch(()=>{}),!$.ok)throw new U("revoke_failed",`Facebook refused the revocation (HTTP ${$.status}).`,{status:$.status})}async profile(W){f(W,this,"FacebookConnectionProvider.profile()");let Z=await S("Facebook /me","request_failed",()=>W.fetch(this.path("/me",{fields:"id,name,picture{url}"}))),$=y(Z.id);if(!$)throw u("Facebook");let Q=await this.pages(W);return{id:$,name:F(Z.name),username:null,avatarUrl:r0(Z.picture),pages:Q.map((Y)=>Y.toJSON())}}async pages(W){return f(W,this,"FacebookConnectionProvider.pages()"),(await this.listPages(($)=>W.fetch($),"request_failed")).map(($)=>new e0(W,$))}path(W,Z={}){let $=this.graphApiVersion?`/${this.graphApiVersion}`:"",Q=new URL(`${$}${W}`,this.config.apiBaseUrl);for(let[Y,K]of Object.entries(Z))Q.searchParams.set(Y,K);return`${Q.pathname}${Q.search}`}graphUrl(W,Z){let $=new URL(W,this.config.apiBaseUrl);if($.origin!==new URL(this.config.apiBaseUrl).origin)throw new U("forbidden_url","Facebook paged to another origin.");return $.searchParams.set("access_token",Z),$}async listPages(W,Z){let $=[],Q=this.path("/me/accounts",{fields:"id,name,category,tasks,access_token,picture{url}",limit:"100"});for(let Y=0;Q!==null&&Y<20;Y++){let K=Q,J=await S("Facebook /me/accounts",Z,()=>W(K));for(let G of Array.isArray(J.data)?J.data:[]){let X=y(G.id);if(!X)continue;$.push({id:X,name:F(G.name),category:F(G.category),tasks:Array.isArray(G.tasks)?G.tasks.filter((B)=>typeof B==="string"):[],avatarUrl:r0(G.picture),accessToken:F(G.access_token)})}let z=J.paging??{};Q=typeof z.next==="string"?z.next:null}return $}async tokenCall(W){let Z=new URL(this.config.tokenUrl);for(let[K,J]of Object.entries(W))Z.searchParams.set(K,J);let $=await S("Facebook token","exchange_failed",()=>fetch(Z,{headers:{Accept:"application/json"},redirect:"error"})),Q=F($.access_token);if(!Q)throw new U("exchange_failed","Facebook answered the code exchange without a token.",{status:502});let Y=Number($.expires_in);return{accessToken:Q,tokenType:F($.token_type),expiresIn:Number.isFinite(Y)&&Y>0?Y:null}}}class e0{connection;id;name;category;tasks;avatarUrl;#W;constructor(W,Z){this.connection=W;this.id=Z.id,this.name=Z.name,this.category=Z.category,this.tasks=Z.tasks,this.avatarUrl=Z.avatarUrl,this.#W=Z.accessToken}get canPost(){return this.tasks.includes("CREATE_CONTENT")}accessToken(){if(this.#W===null)throw new U("request_failed",`Facebook gave no Page token for Page ${this.id}.`);return this.#W}fetch(W,Z={}){return this.connection.fetchWithToken(this.accessToken(),W,Z)}toJSON(){return{id:this.id,name:this.name,category:this.category,tasks:[...this.tasks],avatarUrl:this.avatarUrl}}[Symbol.for("nodejs.util.inspect.custom")](){return{FacebookPage:this.toJSON()}}}function r0(W){let Z=W?.data;return F(Z?.url)}var VW=["openid","profile","w_member_social"],h5=["w_organization_social","r_organization_social"];class kW extends b{apiVersion;constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:W.tokenUrl??"https://www.linkedin.com/oauth/v2/accessToken",revokeUrl:W.revokeUrl,apiBaseUrl:W.apiBaseUrl??"https://api.linkedin.com",clientId:W.clientId??process.env.LINKEDIN_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.LINKEDIN_CLIENT_SECRET??"",scopes:W.scopes??VW,pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??86400,multiple:W.multiple??!1});this.apiVersion=W.apiVersion??"202610"}async exchangeCode(W){let Z=await super.exchangeCode(W),$=_W(await S("LinkedIn userinfo","exchange_failed",()=>$1(this.userInfoUrl(),Z.accessToken)));return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"LinkedInConnectionProvider.profile()"),_W(await S("LinkedIn userinfo","request_failed",()=>W.fetch(this.userInfoUrl())))}async organizations(W){f(W,this,"LinkedInConnectionProvider.organizations()");let Z=new URL("/rest/organizationAcls",this.config.apiBaseUrl);Z.searchParams.set("q","roleAssignee"),Z.searchParams.set("state","APPROVED");let $=await S("LinkedIn organizationAcls","request_failed",()=>W.fetch(Z,{headers:this.restHeaders()})),Q=new Map;for(let J of Array.isArray($.elements)?$.elements:[]){let z=F(J.organization)??F(J.organizationTarget),G=z?.match(/^urn:li:organization:(\d+)$/)?.[1];if(!z||!G||Q.has(G))continue;Q.set(G,{id:G,urn:z,role:F(J.role)??"UNKNOWN",name:null,vanityName:null})}if(Q.size===0)return[];let Y=`/rest/organizations?ids=List(${[...Q.keys()].join(",")})`,K=await W.fetch(Y,{headers:this.restHeaders()});if(K.ok){let J=await K.json().catch(()=>({}));for(let[z,G]of Object.entries(J.results??{})){let X=Q.get(z);if(!X)continue;X.name=F(G.localizedName),X.vanityName=F(G.vanityName)}}else await K.body?.cancel().catch(()=>{});return[...Q.values()]}restHeaders(){return{"LinkedIn-Version":this.apiVersion,"X-Restli-Protocol-Version":"2.0.0"}}userInfoUrl(){return new URL("/v2/userinfo",this.config.apiBaseUrl)}}function _W(W){let Z=y(W.sub);if(!Z)throw u("LinkedIn");let $=F(W.given_name),Q=F(W.family_name);return{id:Z,name:F(W.name)??([$,Q].filter(Boolean).join(" ")||null),username:null,avatarUrl:F(W.picture),authorUrn:`urn:li:person:${Z}`,email:F(W.email)}}var TW=["user.info.basic","video.publish","video.upload"];class PW extends b{constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://www.tiktok.com/v2/auth/authorize/",tokenUrl:W.tokenUrl??"https://open.tiktokapis.com/v2/oauth/token/",revokeUrl:W.revokeUrl??"https://open.tiktokapis.com/v2/oauth/revoke/",apiBaseUrl:W.apiBaseUrl??"https://open.tiktokapis.com",clientId:W.clientKey??W.clientId??process.env.TIKTOK_CLIENT_KEY??"",clientSecret:W.clientSecret??process.env.TIKTOK_CLIENT_SECRET??"",clientIdParam:"client_key",scopes:W.scopes??TW,scopeSeparator:",",pkce:!1,revokeTokenHint:"access_token",authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??300,multiple:W.multiple??!1})}async exchangeCode(W){let Z=await super.exchangeCode(W),$=CW(await S("TikTok user info","exchange_failed",()=>$1(this.userInfoUrl(Z.scopes),Z.accessToken)),"exchange_failed");return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"TikTokConnectionProvider.profile()"),CW(await S("TikTok user info","request_failed",()=>W.fetch(this.userInfoUrl([...W.scopes]))),"request_failed")}userInfoUrl(W){let Z=new URL("/v2/user/info/",this.config.apiBaseUrl),$=["open_id","union_id","avatar_url","display_name"];if(W.includes("user.info.profile"))$.push("username");return Z.searchParams.set("fields",$.join(",")),Z}}function CW(W,Z){let $=W.error??{};if(typeof $.code==="string"&&$.code!=="ok")throw new U(Z,`TikTok refused the user info request (${E5($.code)}).`,{status:400});let Q=(W.data??{}).user,Y=y(Q?.open_id);if(!Q||!Y)throw u("TikTok");return{id:Y,name:F(Q.display_name),username:F(Q.username),avatarUrl:F(Q.avatar_url),unionId:F(Q.union_id)}}function E5(W){return/^[a-z0-9_]{1,64}$/.test(W)?W:"error"}var wW=["https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.readonly"];class qW extends b{constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:W.tokenUrl??"https://oauth2.googleapis.com/token",revokeUrl:W.revokeUrl??"https://oauth2.googleapis.com/revoke",apiBaseUrl:W.apiBaseUrl??"https://www.googleapis.com",clientId:W.clientId??process.env.GOOGLE_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.GOOGLE_CLIENT_SECRET??"",scopes:W.scopes??wW,pkce:!0,authorizationParams:{access_type:"offline",prompt:"consent",include_granted_scopes:"true",...W.authorizationParams},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??300,multiple:W.multiple??!1})}async exchangeCode(W){let Z=await super.exchangeCode(W),$=bW(await S("YouTube channel","exchange_failed",()=>$1(this.channelUrl(),Z.accessToken)));return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"YouTubeConnectionProvider.profile()"),bW(await S("YouTube channel","request_failed",()=>W.fetch(this.channelUrl())))}channelUrl(){let W=new URL("/youtube/v3/channels",this.config.apiBaseUrl);return W.searchParams.set("part","snippet"),W.searchParams.set("mine","true"),W}}function bW(W){let[Z]=Array.isArray(W.items)?W.items:[],$=y(Z?.id);if(!$)throw u("YouTube (the Google account has no channel)");let Q=Z.snippet??{},Y=Q.thumbnails??{},K=Y.high?.url??Y.medium?.url??Y.default?.url;return{id:$,name:F(Q.title),username:F(Q.customUrl),avatarUrl:F(K)}}var IW=["tweet.read","tweet.write","users.read","media.write","offline.access"];class fW extends b{constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://x.com/i/oauth2/authorize",tokenUrl:W.tokenUrl??"https://api.x.com/2/oauth2/token",revokeUrl:W.revokeUrl??"https://api.x.com/2/oauth2/revoke",apiBaseUrl:W.apiBaseUrl??"https://api.x.com",clientId:W.clientId??process.env.X_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.X_CLIENT_SECRET??process.env.X_SECRET??"",scopes:W.scopes??IW,clientAuth:"basic",pkce:!0,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??300,multiple:W.multiple??!1})}async exchangeCode(W){let Z=await super.exchangeCode(W),$=vW(await S("X profile","exchange_failed",()=>$1(this.profileUrl(),Z.accessToken)));return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"XConnectionProvider.profile()"),vW(await S("X profile","request_failed",()=>W.fetch(this.profileUrl())))}profileUrl(){let W=new URL("/2/users/me",this.config.apiBaseUrl);return W.searchParams.set("user.fields","profile_image_url"),W}}function vW(W){let Z=W.data??{},$=y(Z.id);if(!$)throw u("X");return{id:$,name:F(Z.name),username:F(Z.username),avatarUrl:F(Z.profile_image_url)}}class _ extends Error{code;status;graphCode;graphSubcode;containerId;constructor(W,Z,$={}){super(Z);this.code=W;this.name="InstagramPublishError",this.status=$.status,this.graphCode=$.graphCode,this.graphSubcode=$.graphSubcode,this.containerId=$.containerId}}var w={captionLength:2200,hashtags:30,mentions:20,userTags:20,carouselMin:2,carouselMax:10},yW="instagram_business_content_publish",g5={for(W,Z={}){return new $6(W,Z)}};class $6{connection;version;pollIntervalMs;maxPollIntervalMs;timeoutMs;constructor(W,Z={}){this.connection=W;let $=W.connectionProvider();if(!($ instanceof R4))throw TypeError(`Instagram.for() takes an Instagram connection; "${W.provider}" is not an InstagramConnectionProvider.`);let Q=Z.graphApiVersion??$.instagram.graphApiVersion;this.version=Q?`/${Q.replace(/^\/+|\/+$/g,"")}`:"",this.pollIntervalMs=Z.pollIntervalMs??2000,this.maxPollIntervalMs=Z.maxPollIntervalMs??1e4,this.timeoutMs=Z.timeoutMs??300000}async publishImage(W,Z={}){if(c1("imageUrl",W.imageUrl),Z6(W.caption),W.altText!==void 0&&typeof W.altText!=="string")T("altText must be a string.");if(W.userTags!==void 0)t5(W.userTags);let $=this.start(Z),Q=await this.createContainer({image_url:W.imageUrl,caption:W.caption,alt_text:W.altText,user_tags:W.userTags?JSON.stringify(W.userTags):void 0,location_id:W.locationId},$);return this.publishContainer(Q,!1,$)}async publishCarousel(W,Z={}){let $=W.items;if(!Array.isArray($)||$.length<w.carouselMin||$.length>w.carouselMax)T(`A carousel takes ${w.carouselMin} to ${w.carouselMax} items.`);$.forEach((z,G)=>gW(`items[${G}]`,z)),Z6(W.caption);let Q=this.start(Z),Y=[];for(let z of $)Y.push(await this.createContainer(z.videoUrl!==void 0?{media_type:"VIDEO",video_url:z.videoUrl,is_carousel_item:"true"}:{image_url:z.imageUrl,is_carousel_item:"true"},Q));for(let[z,G]of $.entries())if(G.videoUrl!==void 0)await this.waitUntilFinished(Y[z],Q);let K=$.some((z)=>z.videoUrl!==void 0),J=await this.createContainer({media_type:"CAROUSEL",children:Y.join(","),caption:W.caption},Q);return this.publishContainer(J,K,Q)}async publishReel(W,Z={}){if(c1("videoUrl",W.videoUrl),W.coverUrl!==void 0)c1("coverUrl",W.coverUrl);if(Z6(W.caption),W.thumbOffset!==void 0&&!(Number.isInteger(W.thumbOffset)&&W.thumbOffset>=0))T("thumbOffset must be a whole number of milliseconds, 0 or more.");let $=this.start(Z),Q=await this.createContainer({media_type:"REELS",video_url:W.videoUrl,caption:W.caption,cover_url:W.coverUrl,share_to_feed:W.shareToFeed===void 0?void 0:String(W.shareToFeed),thumb_offset:W.thumbOffset===void 0?void 0:String(W.thumbOffset)},$);return this.publishContainer(Q,!0,$)}async publishStory(W,Z={}){gW("story",W);let $=this.start(Z),Q=W.videoUrl!==void 0,Y=await this.createContainer(Q?{media_type:"STORIES",video_url:W.videoUrl}:{media_type:"STORIES",image_url:W.imageUrl},$);return this.publishContainer(Y,Q,$)}async publishingLimit(W={}){let Z=this.start(W),$=await this.call("publishing limit request",`/${this.accountId()}/content_publishing_limit?fields=quota_usage,config`,void 0,Z),Q=Array.isArray($.data)?$.data[0]:$,Y=Q?.config??{},K=W6(Q?.quota_usage,0),J=W6(Y.quota_total,100);return{quotaUsage:K,quotaTotal:J,quotaDurationSeconds:W6(Y.quota_duration,86400),remaining:Math.max(0,J-K)}}async containerStatus(W,Z={}){return this.readStatus(W,this.start(Z))}start(W){if(W.signal?.throwIfAborted(),!this.connection.hasScopes(yW))throw new _("permission_denied",`The Instagram connection was not granted ${yW}; connect it again with that scope.`);return{signal:W.signal,deadline:Date.now()+(W.timeoutMs??this.timeoutMs)}}accountId(){let W=this.connection.providerAccountId;if(!W)throw new _("invalid_input","The Instagram connection has no account id (providerAccountId).");return W}async createContainer(W,Z){let $=await this.call("media container request",`/${this.accountId()}/media`,W,Z);return hW($,"media container request")}async publishContainer(W,Z,$){try{if(Z)await this.waitUntilFinished(W,$);let Q=await this.publishOnce(W,Z,$);return{mediaId:Q,permalink:await this.permalink(Q,$)}}catch(Q){throw Q instanceof _?o5(Q,W):Q}}async publishOnce(W,Z,$){try{return await this.mediaPublish(W,$)}catch(Q){if(!(Q instanceof _))throw Q;if(Q.code==="transient"){let{statusCode:Y}=await this.readStatus(W,$);if(Y==="PUBLISHED")throw new _("unconfirmed","Instagram's media_publish failed, but the container reads PUBLISHED: the post is probably live. Do not publish it again.",{status:Q.status,graphCode:Q.graphCode,graphSubcode:Q.graphSubcode});if(Y!=="FINISHED")throw Q;return this.mediaPublish(W,$)}if(s5(Q)&&!Z)return await this.waitUntilFinished(W,$),this.mediaPublish(W,$);throw Q}}async mediaPublish(W,Z){let $=await this.call("media_publish request",`/${this.accountId()}/media_publish`,{creation_id:W},Z,{retry:!1});return hW($,"media_publish request")}async permalink(W,Z){try{let $=await this.call("permalink request",`/${W}?fields=permalink`,void 0,Z,{retry:!1});return typeof $.permalink==="string"?$.permalink:void 0}catch{return}}async readStatus(W,Z){if(!/^\d+$/.test(W))T("A container id is a string of digits.");let $=await this.call("container status request",`/${W}?fields=status_code,status`,void 0,Z),Q=$.status_code;if(typeof Q!=="string"||!m5.has(Q))throw new _("graph_error","Instagram's container status answered without a known status_code.",{status:200,containerId:W});let Y={id:W,statusCode:Q};if(typeof $.status==="string"&&$.status!=="")Y.status=uW($.status);return Y}async waitUntilFinished(W,Z){let $=this.pollIntervalMs;for(;;){let{statusCode:Q,status:Y}=await this.readStatus(W,Z);if(Q==="FINISHED")return;if(Q==="PUBLISHED")throw new _("invalid_input","That media container has been published already.",{containerId:W});if(Q==="ERROR")throw new _("invalid_media",`Instagram could not process the media${Y?` (${Y})`:""}.`,{containerId:W});if(Q==="EXPIRED")throw new _("expired","The media container expired before it was published.",{containerId:W});let K=Z.deadline-Date.now();if(K<=0)throw new _("timeout","Instagram had not finished processing the media in time; the container is still processing.",{containerId:W});await a5(Math.min($,K),Z.signal),$=Math.min($*1.5,this.maxPollIntervalMs)}}async call(W,Z,$,Q,{retry:Y=!0}={}){try{return await this.callOnce(W,Z,$,Q)}catch(K){if(!Y||!(K instanceof _)||K.code!=="transient")throw K;return this.callOnce(W,Z,$,Q)}}async callOnce(W,Z,$,Q){Q.signal?.throwIfAborted();let Y={method:$?"POST":"GET",signal:Q.signal};if($){let z=new URLSearchParams;for(let[G,X]of Object.entries($))if(X!==void 0)z.set(G,X);Y.body=z}let K;try{K=await this.connection.fetch(`${this.version}${Z}`,Y)}catch(z){if(Q.signal?.aborted)throw Q.signal.reason;if(z instanceof TypeError)throw new _("transient",`Instagram's ${W} failed to reach Instagram.`);throw z}let J=a0(await K.text().catch(()=>""));if(K.ok)return J;throw i5(W,K.status,J)}}var m5=new Set(["EXPIRED","ERROR","FINISHED","IN_PROGRESS","PUBLISHED"]),c5=new Set([4,17,32,613,80002]),u5=new Set([3,10]),p5=new Set([9004,352,36000,36001,36002,36003,36004]),d5=new Set([2207004,2207005,2207006,2207009,2207023,2207026,2207028,2207052]),l5=new Set([102,190,463,467]),n5=new Set([2207001,2207003,2207053]),AW={code:9007,subcode:2207027};function i5(W,Z,$){let Q=$.error??{},Y=EW(Q.code),K=EW(Q.error_subcode),J=typeof Q.type==="string"&&Q.type!==""?Q.type:void 0,z=typeof Q.message==="string"&&Q.message!==""?`: ${uW(Q.message)}`:"",G=[Y,K].filter((j)=>j!==void 0).join("/"),X=`Instagram refused the ${W} (HTTP ${Z}${J?`, ${J}`:""}${G?` ${G}`:""})${z}`,B="graph_error";if(K===2207042)B="quota_exceeded";else if(K===2207010)B="invalid_input";else if(Y!==void 0&&c5.has(Y))B="rate_limited";else if(Y!==void 0&&l5.has(Y))B="reconnect_required";else if(Y!==void 0&&(u5.has(Y)||Y>=200&&Y<=299))B="permission_denied";else if(Y!==void 0&&p5.has(Y)||K!==void 0&&d5.has(K))B="invalid_media";else if(Q.is_transient===!0||Y===1||Y===2||K!==void 0&&n5.has(K)||Z>=500||Z===429)B=Z===429?"rate_limited":"transient";return new _(B,X,{status:Z,graphCode:Y,graphSubcode:K})}function s5(W){return W.graphCode===AW.code||W.graphSubcode===AW.subcode}function o5(W,Z){if(W.containerId)return W;return new _(W.code,W.message,{status:W.status,graphCode:W.graphCode,graphSubcode:W.graphSubcode,containerId:Z})}function uW(W){return W.replace(/access_token=[^&\s"']*/gi,"access_token=[redacted]").replace(/\b(?:IG|EAA)[A-Za-z0-9_-]{20,}/g,"[redacted]").slice(0,500)}function hW(W,Z){let $=W.id;if(typeof $==="string"&&$!=="")return $;if(typeof $==="number"&&Number.isSafeInteger($))return String($);throw new _("graph_error",`Instagram's ${Z} answered without an id.`,{status:200})}function EW(W){let Z=Number(W);return W!==void 0&&W!==null&&Number.isFinite(Z)?Z:void 0}function W6(W,Z){let $=Number(W);return W!==void 0&&W!==null&&Number.isFinite($)?$:Z}function a5(W,Z){return new Promise(($,Q)=>{if(Z?.aborted)return Q(Z.reason);let Y=()=>{clearTimeout(K),Q(Z?.reason)},K=setTimeout(()=>{Z?.removeEventListener("abort",Y),$()},W);Z?.addEventListener("abort",Y,{once:!0})})}function T(W){throw new _("invalid_input",W)}function Z6(W){if(W===void 0)return;if(typeof W!=="string")T("caption must be a string.");if([...W].length>w.captionLength)T(`A caption takes at most ${w.captionLength} characters.`);if((W.match(/#[\p{L}\p{N}_]+/gu)??[]).length>w.hashtags)T(`A caption takes at most ${w.hashtags} hashtags.`);if((W.match(/(?<![\p{L}\p{N}_.@])@[\p{L}\p{N}_.]+/gu)??[]).length>w.mentions)T(`A caption takes at most ${w.mentions} @mentions.`)}function t5(W){if(!Array.isArray(W)||W.length>w.userTags)T(`userTags takes at most ${w.userTags} tags.`);for(let Z of W){let $=(Q)=>typeof Q==="number"&&Q>=0&&Q<=1;if(typeof Z?.username!=="string"||Z.username===""||!$(Z.x)||!$(Z.y))T("Each user tag needs a username, and x and y between 0 and 1.")}}function gW(W,Z){let $=Z?.imageUrl!==void 0,Q=Z?.videoUrl!==void 0;if($===Q)T(`${W} takes exactly one of imageUrl and videoUrl.`);if($)c1(`${W}.imageUrl`,Z.imageUrl);else c1(`${W}.videoUrl`,Z.videoUrl)}function c1(W,Z){let $;try{$=new URL(Z)}catch{T(`${W} is not an absolute URL.`)}if($.protocol!=="https:")T(`${W} must be an https URL: Instagram fetches the media from it.`);let Q=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Y=mW(Q);if(Y?cW(Y)!==null:!Q.includes(".")||/(^|\.)(localhost|local|internal)$/.test(Q))T(`${W} must be a public URL: Instagram fetches the media from it.`)}class Q6{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 r5(W={}){return new Q6(W)}class pW extends Y6{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{TZ as viewRouteConfigDefaults,y9 as translationConfigDefaults,O4 as toRangeHeaderValue,X8 as subjectFor,vZ as strictCspPolicy,O8 as sniffContentType,x9 as scheduleConfigDefaults,k4 as resolveRange,e9 as redisConfigDefaults,a9 as rateLimiterConfigDefaults,iZ as queueConfigDefaults,y5 as parseMetaSignedRequest,k1 as parseContentRange,Z8 as mintSessionToken,AZ as middlewareConfigDefaults,z9 as mcpCallOf,gZ as mailConfigDefaults,k8 as logConfigDefaults,W8 as isSessionToken,F5 as isFixedSignInCode,MZ as isFinalRunStatus,v6 as isBroadcastEvent,_8 as isActiveContentType,z8 as inRollout,OZ as imageConfigDefaults,M5 as fixedSignInCode,x8 as filesystemConfigDefaults,g9 as featuresConfigDefaults,R9 as eventConfigDefaults,G8 as evaluateFeature,n8 as encodeCursor,bZ as documentScriptCspHash,k9 as discoverWorkflows,P9 as discoverListeners,V9 as discoverJobs,C9 as discoverCronJobs,T9 as discoverCommands,f9 as defineTranslationConfig,U9 as defineScheduleConfig,XZ as defineRunsConfig,kZ as defineRouteConfig,r9 as defineRedisConfig,o9 as defineRateLimiterConfig,nZ as defineQueueConfig,yZ as defineMiddlewareConfig,EZ as defineMailConfig,V8 as defineLogConfig,RZ as defineImageConfig,U8 as defineFilesystemConfig,E9 as defineFeaturesConfig,r5 as defineFeature,S9 as defineEventConfig,iW as defineEncryptionConfig,L9 as defineCommandConfig,H9 as defineCommand,d8 as defineChangeFeedConfig,T8 as defineCacheConfig,ZZ as defineBroadcastConfig,Q8 as defineAuthConfig,i8 as decodeCursor,dZ as createWorkflowTableStatements,DZ as createRunsTableStatements,D9 as commandConfigDefaults,l8 as changeFeedConfigDefaults,P8 as cacheConfigDefaults,J8 as bucketOf,K8 as bucketKey,$Z as broadcastConfigDefaults,u4 as bearerToken,Y8 as authConfigDefaults,_4 as assertDeletablePrefix,CZ as apiRouteConfigDefaults,qW as YouTubeConnectionProvider,wW as YOUTUBE_DEFAULT_SCOPES,IW as X_DEFAULT_SCOPES,LW as XOAuthProvider,fW as XConnectionProvider,Z9 as WorkflowRuntime,eZ as WorkflowCancelledError,_9 as Workflow,tZ as WaitTimeoutError,IZ as ViewRouteDispatcher,L8 as UndeclaredFeatureError,PW as TikTokConnectionProvider,v8 as TaggedCache,TW as TIKTOK_DEFAULT_SCOPES,R8 as StorageFetchTimeoutError,rZ as StepTimeoutError,aZ as StepFailedError,W9 as Step,pW as StaticFeatureFlagSource,SZ as Sharp,j9 as Scheduler,A9 as ScheduleServiceProvider,qZ as STATIC_NAVIGATION_CSP_HASH,WZ as SOCKET_ID_HEADER,e5 as SESSION_TOKEN_PREFIX,J6 as S3Driver,$$ as RunsServiceProvider,HZ as RunNotFoundError,UZ as RunManager,NZ as RunFailure,Z$ as RouteServiceProvider,hZ as ResendDriver,W$ as RedisServiceProvider,b4 as RedisRateLimiterTimeoutError,l1 as RedisRateLimiterDisconnectedError,j6 as RedisRateLimiter,d1 as RedisManager,w8 as RedisCacheStore,YZ as RedisBroadcastDriver,t9 as RateLimiterServiceProvider,T4 as RateLimiterDriver,$8 as RateLimiter,j1 as RangeNotSatisfiableError,b9 as QueueServiceProvider,$9 as QueueManager,p8 as ProviderConnection,b6 as PrismaMcpOAuthStore,zZ as PendingBroadcast,jZ as OPEN_RUN_STATUSES,c8 as OAuthReconnectRequiredError,i as OAuthProvider,b as OAuthConnectionProvider,U as OAuthConnectionError,R as OAuthCallbackError,s9 as MiddlewareServiceProvider,VZ as MiddlewareRegistry,c as MetaSignedRequestError,sZ as MemoryWorkflowStore,FZ as MemoryRunStore,oZ as MemoryQueueDriver,P6 as MemoryMcpOAuthStore,uZ as MemoryLockStore,g8 as MemoryConnectionStore,o8 as MemoryChangeFeedDriver,b8 as MemoryCacheStore,QZ as MemoryBroadcastDriver,K9 as McpToolError,G9 as McpRegistry,C6 as McpOAuthServer,B9 as McpHttpServer,J9 as McpCallRefusedError,X9 as McpApiKeyResolver,c9 as MailServiceProvider,mZ as MailManager,i9 as LogServiceProvider,C8 as LogManager,y8 as LockManager,I8 as LockLostError,O9 as Listener,kW as LinkedInConnectionProvider,h5 as LINKEDIN_ORGANIZATION_SCOPES,VW as LINKEDIN_DEFAULT_SCOPES,n9 as KernelIdServiceProvider,PZ as KernelId,Q9 as Job,e8 as InvalidChannelError,$6 as InstagramPublisher,_ as InstagramPublishError,SW as InstagramOAuthProvider,R4 as InstagramConnectionProvider,m as InstagramApiError,g5 as Instagram,P4 as InMemoryRateLimiter,l9 as ImageServiceProvider,xZ as ImageOptimizationDriver,_Z as ImageManager,wZ as ISLAND_LOADER_CSP_HASH,w as INSTAGRAM_LIMITS,f8 as HeldLock,E6 as GoogleOAuthProvider,m6 as GitHubOAuthProvider,d9 as FilesystemServiceProvider,S8 as FilesystemManager,N8 as FileSystemDriver,C1 as FileStorageDriver,Y1 as FileNotFoundError,m9 as FeaturesServiceProvider,F8 as FeatureSourceReadOnlyError,D8 as FeatureScope,B8 as FeatureReloadError,M8 as FeatureModelMissingError,H8 as FeatureManager,j8 as FeatureFlagStore,Y6 as FeatureFlagSource,Q6 as Feature,e0 as FacebookPage,OW as FacebookConnectionProvider,BZ as FINAL_RUN_STATUSES,RW as FACEBOOK_DEFAULT_SCOPES,p9 as EventServiceProvider,h as EventManager,r1 as Event,u9 as EncryptionServiceProvider,h8 as EncryptionKeyError,A8 as Encrypter,w4 as EmailDriver,E8 as DecryptionError,pZ as DatabaseWorkflowStore,LZ as DatabaseRunStore,lZ as DatabaseQueueDriver,cZ as DatabaseLockStore,h9 as DatabaseFeatureFlagSource,m8 as DatabaseConnectionStore,s8 as DatabaseChangeFeedDriver,Y9 as DEFAULT_MCP_SCOPE,N9 as CronJob,u8 as ConnectionManager,Q$ as CommandRegistry,M9 as CommandFailed,F9 as Command,r8 as ChangeFeedSubscription,v9 as ChangeFeedServiceProvider,t8 as ChangeFeedManager,a8 as ChangeFeedFullError,q9 as CacheServiceProvider,q8 as CacheManager,n1 as CONSENT_PAGE_HEADERS,w9 as BroadcastServiceProvider,GZ as BroadcastScope,KZ as BroadcastPayloadTooLargeError,JZ as BroadcastManager,I6 as BroadcastEvent,G6 as AzureBlobDriver,I9 as AuthServiceProvider,z1 as AuthManager,fZ as ApiRouteDispatcher,q4 as AcsDriver};
71
71
 
72
- //# debugId=5E51DBD2ABE6BE7364756E2164756E21
72
+ //# debugId=C28014A2581132CF64756E2164756E21