gemi 0.54.3 → 0.55.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 (211) hide show
  1. package/dist/app/index.js +2 -2
  2. package/dist/app/index.js.map +1 -1
  3. package/dist/broadcasting/index.js +1 -1
  4. package/dist/bun/plugin.js +2 -2
  5. package/dist/bun/plugin.js.map +1 -1
  6. package/dist/bun/preload.js +2 -2
  7. package/dist/bun/preload.js.map +2 -2
  8. package/dist/{chunk-0weeq0ke.js → chunk-01am9k5v.js} +2 -2
  9. package/dist/{chunk-0weeq0ke.js.map → chunk-01am9k5v.js.map} +1 -1
  10. package/dist/chunk-02gdzs5t.js +4 -0
  11. package/dist/{chunk-4qkzdyj7.js.map → chunk-02gdzs5t.js.map} +1 -1
  12. package/dist/{chunk-71m47kad.js → chunk-1pwwrpa3.js} +2 -2
  13. package/dist/{chunk-71m47kad.js.map → chunk-1pwwrpa3.js.map} +2 -2
  14. package/dist/{chunk-h7mcwfg5.js → chunk-1zfsgffv.js} +4 -4
  15. package/dist/{chunk-h7mcwfg5.js.map → chunk-1zfsgffv.js.map} +2 -2
  16. package/dist/{chunk-kz39hphm.js → chunk-31kcf7dq.js} +3 -3
  17. package/dist/{chunk-kz39hphm.js.map → chunk-31kcf7dq.js.map} +1 -1
  18. package/dist/chunk-33wjsw4r.js +66 -0
  19. package/dist/{chunk-tpyhhdq5.js.map → chunk-33wjsw4r.js.map} +4 -54
  20. package/dist/{chunk-50vm7x98.js → chunk-3e88tyee.js} +3 -3
  21. package/dist/{chunk-50vm7x98.js.map → chunk-3e88tyee.js.map} +1 -1
  22. package/dist/{chunk-xxw0gz4q.js → chunk-3y75q5a2.js} +2 -2
  23. package/dist/{chunk-xxw0gz4q.js.map → chunk-3y75q5a2.js.map} +1 -1
  24. package/dist/chunk-4qwwy968.js +4 -0
  25. package/dist/{chunk-1snh7yc4.js.map → chunk-4qwwy968.js.map} +2 -2
  26. package/dist/{chunk-1sh6kqjn.js → chunk-4t80js0n.js} +3 -3
  27. package/dist/{chunk-1sh6kqjn.js.map → chunk-4t80js0n.js.map} +1 -1
  28. package/dist/chunk-4xx78ba9.js +4 -0
  29. package/dist/{chunk-r9z5rrk0.js.map → chunk-4xx78ba9.js.map} +2 -2
  30. package/dist/{chunk-g5tj10p8.js → chunk-4yafsffx.js} +2 -2
  31. package/dist/{chunk-g5tj10p8.js.map → chunk-4yafsffx.js.map} +1 -1
  32. package/dist/{chunk-gn9zjgep.js → chunk-5ad8era8.js} +2 -2
  33. package/dist/{chunk-gn9zjgep.js.map → chunk-5ad8era8.js.map} +1 -1
  34. package/dist/{chunk-3bw1jk21.js → chunk-62723jyy.js} +1 -1
  35. package/dist/chunk-62ke19q4.js +13 -0
  36. package/dist/chunk-62ke19q4.js.map +222 -0
  37. package/dist/{chunk-004bcmsa.js → chunk-64s1pzz1.js} +2 -2
  38. package/dist/{chunk-004bcmsa.js.map → chunk-64s1pzz1.js.map} +1 -1
  39. package/dist/{chunk-dwx2y7br.js → chunk-699z6d8y.js} +4 -4
  40. package/dist/{chunk-dwx2y7br.js.map → chunk-699z6d8y.js.map} +2 -2
  41. package/dist/{chunk-4zmcbmf9.js → chunk-77xj0dgc.js} +2 -2
  42. package/dist/{chunk-4zmcbmf9.js.map → chunk-77xj0dgc.js.map} +1 -1
  43. package/dist/{chunk-bb3zvxsf.js → chunk-8k1zqrvh.js} +3 -3
  44. package/dist/{chunk-bb3zvxsf.js.map → chunk-8k1zqrvh.js.map} +1 -1
  45. package/dist/{chunk-9nskvzpv.js → chunk-98a576s9.js} +3 -3
  46. package/dist/{chunk-9nskvzpv.js.map → chunk-98a576s9.js.map} +1 -1
  47. package/dist/{chunk-cz3szqhq.js → chunk-9c89q2mz.js} +3 -3
  48. package/dist/{chunk-cz3szqhq.js.map → chunk-9c89q2mz.js.map} +1 -1
  49. package/dist/chunk-9r0sb4zn.js +5 -0
  50. package/dist/{chunk-efsk1wy0.js.map → chunk-9r0sb4zn.js.map} +2 -2
  51. package/dist/chunk-9r1atj8w.js +6 -0
  52. package/dist/{chunk-p8fm3tjy.js.map → chunk-9r1atj8w.js.map} +2 -2
  53. package/dist/chunk-b50zmz3t.js +5 -0
  54. package/dist/{chunk-113khwbw.js.map → chunk-b50zmz3t.js.map} +1 -1
  55. package/dist/chunk-cn2r5jfj.js +5 -0
  56. package/dist/{chunk-dxw8k6f1.js.map → chunk-cn2r5jfj.js.map} +2 -2
  57. package/dist/{chunk-nncwsdzz.js → chunk-ct274qts.js} +2 -2
  58. package/dist/{chunk-nncwsdzz.js.map → chunk-ct274qts.js.map} +1 -1
  59. package/dist/{chunk-jp4pf3yt.js → chunk-d36dfqxw.js} +4 -4
  60. package/dist/{chunk-jp4pf3yt.js.map → chunk-d36dfqxw.js.map} +2 -2
  61. package/dist/chunk-dzzmqv0j.js +5 -0
  62. package/dist/{chunk-f13f68c0.js.map → chunk-dzzmqv0j.js.map} +2 -2
  63. package/dist/{chunk-f418jh9k.js → chunk-ejrcyzx8.js} +2 -2
  64. package/dist/{chunk-f418jh9k.js.map → chunk-ejrcyzx8.js.map} +1 -1
  65. package/dist/chunk-enhkf60v.js +9 -0
  66. package/dist/chunk-enhkf60v.js.map +12 -0
  67. package/dist/{chunk-n1tkn8gv.js → chunk-eqrd31ye.js} +2 -2
  68. package/dist/{chunk-n1tkn8gv.js.map → chunk-eqrd31ye.js.map} +1 -1
  69. package/dist/{chunk-k14dmqwh.js → chunk-f9mfw82d.js} +3 -3
  70. package/dist/{chunk-k14dmqwh.js.map → chunk-f9mfw82d.js.map} +1 -1
  71. package/dist/{chunk-kv2ep453.js → chunk-g30q4n5y.js} +18 -19
  72. package/dist/{chunk-kv2ep453.js.map → chunk-g30q4n5y.js.map} +4 -8
  73. package/dist/chunk-gasdfwva.js +4 -0
  74. package/dist/{chunk-c0wcsmpj.js.map → chunk-gasdfwva.js.map} +2 -2
  75. package/dist/{chunk-c22vcxty.js → chunk-gzdf2025.js} +2 -2
  76. package/dist/{chunk-c22vcxty.js.map → chunk-gzdf2025.js.map} +2 -2
  77. package/dist/{chunk-ms8qd7da.js → chunk-h3mwgbg7.js} +3 -3
  78. package/dist/{chunk-ms8qd7da.js.map → chunk-h3mwgbg7.js.map} +1 -1
  79. package/dist/{chunk-6j1z2cqt.js → chunk-hs5v3eqj.js} +2 -2
  80. package/dist/{chunk-6j1z2cqt.js.map → chunk-hs5v3eqj.js.map} +1 -1
  81. package/dist/chunk-javjeayw.js +5 -0
  82. package/dist/{chunk-jdgvdddd.js.map → chunk-javjeayw.js.map} +2 -2
  83. package/dist/chunk-jdj7k3r9.js +4 -0
  84. package/dist/{chunk-hk067634.js.map → chunk-jdj7k3r9.js.map} +2 -2
  85. package/dist/chunk-kgg1eqne.js +4 -0
  86. package/dist/{chunk-hrrmxreg.js.map → chunk-kgg1eqne.js.map} +2 -2
  87. package/dist/{chunk-7f5ad759.js → chunk-kgmr9qxx.js} +2 -2
  88. package/dist/{chunk-7f5ad759.js.map → chunk-kgmr9qxx.js.map} +1 -1
  89. package/dist/{chunk-pgjk5ft3.js → chunk-kry5vwam.js} +3 -3
  90. package/dist/{chunk-pgjk5ft3.js.map → chunk-kry5vwam.js.map} +1 -1
  91. package/dist/{chunk-r06rxn19.js → chunk-m0ggfy1m.js} +3 -3
  92. package/dist/{chunk-r06rxn19.js.map → chunk-m0ggfy1m.js.map} +1 -1
  93. package/dist/{chunk-bzhtymvv.js → chunk-npg72mez.js} +2 -2
  94. package/dist/{chunk-bzhtymvv.js.map → chunk-npg72mez.js.map} +1 -1
  95. package/dist/chunk-pvdbrt4z.js +5 -0
  96. package/dist/chunk-pvdbrt4z.js.map +13 -0
  97. package/dist/{chunk-e3mggavt.js → chunk-q0waxxz5.js} +2 -2
  98. package/dist/{chunk-e3mggavt.js.map → chunk-q0waxxz5.js.map} +1 -1
  99. package/dist/chunk-rgb69nh1.js +4 -0
  100. package/dist/{chunk-s6e7cvek.js.map → chunk-rgb69nh1.js.map} +2 -2
  101. package/dist/{chunk-jjvnmyw4.js → chunk-rjxdc0xh.js} +2 -2
  102. package/dist/{chunk-jjvnmyw4.js.map → chunk-rjxdc0xh.js.map} +2 -2
  103. package/dist/{chunk-sqp7kn7h.js → chunk-rsdg619q.js} +3 -3
  104. package/dist/{chunk-sqp7kn7h.js.map → chunk-rsdg619q.js.map} +1 -1
  105. package/dist/chunk-tja0c815.js +5 -0
  106. package/dist/{chunk-2pt6kyn9.js.map → chunk-tja0c815.js.map} +2 -2
  107. package/dist/{chunk-agabw2w1.js → chunk-tkdxv6cq.js} +2 -2
  108. package/dist/{chunk-agabw2w1.js.map → chunk-tkdxv6cq.js.map} +1 -1
  109. package/dist/chunk-tmnhkphv.js +19 -0
  110. package/dist/chunk-tmnhkphv.js.map +60 -0
  111. package/dist/{chunk-w6gb9gc5.js → chunk-v06qcyj5.js} +3 -3
  112. package/dist/{chunk-w6gb9gc5.js.map → chunk-v06qcyj5.js.map} +1 -1
  113. package/dist/{chunk-9taz1h3t.js → chunk-v6v6sem5.js} +3 -3
  114. package/dist/{chunk-9taz1h3t.js.map → chunk-v6v6sem5.js.map} +1 -1
  115. package/dist/{chunk-f4e7fh95.js → chunk-v7y8zm61.js} +3 -3
  116. package/dist/{chunk-f4e7fh95.js.map → chunk-v7y8zm61.js.map} +2 -2
  117. package/dist/{chunk-85av4ncy.js → chunk-vkngcrzq.js} +2 -2
  118. package/dist/{chunk-85av4ncy.js.map → chunk-vkngcrzq.js.map} +1 -1
  119. package/dist/chunk-w9k9s4wh.js +4 -0
  120. package/dist/{chunk-jb2nst6v.js.map → chunk-w9k9s4wh.js.map} +2 -2
  121. package/dist/chunk-wgpa04jb.js +5 -0
  122. package/dist/{chunk-6rhebm18.js.map → chunk-wgpa04jb.js.map} +2 -2
  123. package/dist/chunk-x14sk95v.js +9 -0
  124. package/dist/{chunk-k8endm5j.js.map → chunk-x14sk95v.js.map} +6 -6
  125. package/dist/chunk-xjy5apyr.js +4 -0
  126. package/dist/{chunk-07t0dmdg.js.map → chunk-xjy5apyr.js.map} +2 -2
  127. package/dist/{chunk-fcqc3e3r.js → chunk-xnytbrda.js} +2 -2
  128. package/dist/{chunk-fcqc3e3r.js.map → chunk-xnytbrda.js.map} +1 -1
  129. package/dist/chunk-y9fp58bg.js +4 -0
  130. package/dist/{chunk-br8ten26.js.map → chunk-y9fp58bg.js.map} +2 -2
  131. package/dist/{chunk-jb022m7n.js → chunk-yf8kxjr2.js} +2 -2
  132. package/dist/{chunk-jb022m7n.js.map → chunk-yf8kxjr2.js.map} +1 -1
  133. package/dist/config/index.js +1 -1
  134. package/dist/console/run.js +2 -2
  135. package/dist/console/run.js.map +1 -1
  136. package/dist/container/index.js +2 -2
  137. package/dist/container/index.js.map +1 -1
  138. package/dist/database/DatabaseManager.d.ts.map +1 -1
  139. package/dist/database/index.js +2 -2
  140. package/dist/database/index.js.map +1 -1
  141. package/dist/email/index.js +2 -2
  142. package/dist/email/index.js.map +1 -1
  143. package/dist/facades/Storage.d.ts +1 -1
  144. package/dist/facades/Storage.d.ts.map +1 -1
  145. package/dist/facades/index.js +2 -2
  146. package/dist/facades/index.js.map +1 -1
  147. package/dist/foundation/index.js +2 -2
  148. package/dist/foundation/index.js.map +1 -1
  149. package/dist/http/index.js +2 -2
  150. package/dist/http/index.js.map +1 -1
  151. package/dist/i18n/dictionaryRuntime.js +2 -2
  152. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  153. package/dist/i18n/index.js +2 -2
  154. package/dist/i18n/index.js.map +2 -2
  155. package/dist/kernel/index.js +2 -2
  156. package/dist/kernel/index.js.map +2 -2
  157. package/dist/orm/compile/relation-count.d.ts.map +1 -1
  158. package/dist/orm/corpus.d.ts.map +1 -1
  159. package/dist/orm/dialect/index.d.ts +32 -1
  160. package/dist/orm/dialect/index.d.ts.map +1 -1
  161. package/dist/orm/dialect/postgres.d.ts +14 -0
  162. package/dist/orm/dialect/postgres.d.ts.map +1 -1
  163. package/dist/orm/dialect/sqlite.d.ts +31 -0
  164. package/dist/orm/dialect/sqlite.d.ts.map +1 -1
  165. package/dist/orm/index.js +3 -3
  166. package/dist/orm/index.js.map +5 -5
  167. package/dist/orm/policy.d.ts.map +1 -1
  168. package/dist/orm/relation-filters.d.ts +24 -0
  169. package/dist/orm/relation-filters.d.ts.map +1 -1
  170. package/dist/orm/types.d.ts +129 -40
  171. package/dist/orm/types.d.ts.map +1 -1
  172. package/dist/server/index.js +2 -2
  173. package/dist/server/index.js.map +2 -2
  174. package/dist/services/email/drivers/ResendDriver.d.ts.map +1 -1
  175. package/dist/services/file-storage/drivers/S3Driver.d.ts +24 -1
  176. package/dist/services/file-storage/drivers/S3Driver.d.ts.map +1 -1
  177. package/dist/services/image-optimization/drivers/SharpDriver.d.ts.map +1 -1
  178. package/dist/services/index.js +9 -18
  179. package/dist/services/index.js.map +5 -99
  180. package/dist/services/rate-limiter/drivers/RedisRateLimiterDriver.d.ts.map +1 -1
  181. package/dist/services/redis/RedisManager.d.ts +19 -2
  182. package/dist/services/redis/RedisManager.d.ts.map +1 -1
  183. package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
  184. package/dist/support/index.js +2 -2
  185. package/dist/support/index.js.map +1 -1
  186. package/dist/support/sharp.d.ts +21 -0
  187. package/dist/support/sharp.d.ts.map +1 -0
  188. package/package.json +1 -1
  189. package/dist/chunk-07t0dmdg.js +0 -4
  190. package/dist/chunk-113khwbw.js +0 -5
  191. package/dist/chunk-1snh7yc4.js +0 -4
  192. package/dist/chunk-2pt6kyn9.js +0 -5
  193. package/dist/chunk-4qkzdyj7.js +0 -4
  194. package/dist/chunk-6rhebm18.js +0 -5
  195. package/dist/chunk-br8ten26.js +0 -4
  196. package/dist/chunk-c0wcsmpj.js +0 -4
  197. package/dist/chunk-dxw8k6f1.js +0 -5
  198. package/dist/chunk-efsk1wy0.js +0 -5
  199. package/dist/chunk-f13f68c0.js +0 -5
  200. package/dist/chunk-hk067634.js +0 -4
  201. package/dist/chunk-hrrmxreg.js +0 -4
  202. package/dist/chunk-jb2nst6v.js +0 -4
  203. package/dist/chunk-jdgvdddd.js +0 -5
  204. package/dist/chunk-k8endm5j.js +0 -9
  205. package/dist/chunk-p8fm3tjy.js +0 -6
  206. package/dist/chunk-r9z5rrk0.js +0 -4
  207. package/dist/chunk-s6e7cvek.js +0 -4
  208. package/dist/chunk-tpyhhdq5.js +0 -81
  209. package/dist/chunk-zckj6bs6.js +0 -9
  210. package/dist/chunk-zckj6bs6.js.map +0 -12
  211. /package/dist/{chunk-3bw1jk21.js.map → chunk-62723jyy.js.map} +0 -0
@@ -1,14 +1,5 @@
1
1
  // @bun
2
- import{T as BS,U as $S,Z as GS}from"../chunk-br8ten26.js";import{$ as $v,_ as Rv,aa as sc,ba as d4,ca as i4,da as o4,ea as vv,fa as Lw,ga as sw,ha as T4,ia as e4,ja as sS,ka as a4,la as kc,ma as AS,na as q4,oa as p4,pa as V4,qa as l4,ra as P4,sa as E4}from"../chunk-dwx2y7br.js";import{ta as _4}from"../chunk-2pt6kyn9.js";import{Ba as d1,Fa as E,ua as Dt,va as g4,xa as m4,ya as WS,za as Vx}from"../chunk-jp4pf3yt.js";import{Ga as hc}from"../chunk-efsk1wy0.js";import{Ha as C4}from"../chunk-cz3szqhq.js";import{Ia as K4}from"../chunk-f13f68c0.js";import"../chunk-r06rxn19.js";import"../chunk-50vm7x98.js";import{La as SS}from"../chunk-ms8qd7da.js";import{Na as Iy}from"../chunk-jb022m7n.js";import{Oa as o0,Qa as Kt}from"../chunk-9taz1h3t.js";import{Ra as e0}from"../chunk-bb3zvxsf.js";import{$a as Oy,Sa as ob,Ta as cy,Ua as zy,Va as Ny,Wa as Zy,Xa as Wy,Ya as Ry,Za as jy,_a as Ky,ab as Dy,bb as Jy,cb as Qy,db as ky,eb as Yy,fb as y0,gb as B0,hb as Wn,ib as Xy,jb as Uy,kb as Hy,lb as Fy,mb as uy,nb as Ly,ob as sy,pb as Ay}from"../chunk-9nskvzpv.js";import{Ab as yy,Bb as By,Cb as $y,Db as Gy,Eb as My,qb as eb,rb as ab,sb as rb,tb as ty,ub as ny,vb as hy,wb as vy,xb as Sy,yb as wy,zb as by}from"../chunk-1sh6kqjn.js";import"../chunk-xxw0gz4q.js";import{Jb as xy,Kb as fy}from"../chunk-004bcmsa.js";import"../chunk-n1tkn8gv.js";import{$b as Ab,Nb as kb,Rb as kx,Sb as Yb,Tb as Xb,Ub,Vb as Hb,Xb as Fb,Yb as ub,Zb as Lb,_b as sb,ac as Ib,bc as gb,cc as Cb,dc as Pb,ec as mb,hc as Tb,jc as _b,kc as qb,pc as pb}from"../chunk-tpyhhdq5.js";import"../chunk-pgjk5ft3.js";import"../chunk-k8endm5j.js";import"../chunk-e3mggavt.js";import{$d as jb,Ed as Zn,Fd as zn,Gd as Qx,Rd as Ec,Sd as Mc,Wd as T0,ae as Kb,ce as Ob,de as Db,fe as Jb,je as Qb}from"../chunk-85av4ncy.js";import"../chunk-k14dmqwh.js";import"../chunk-0weeq0ke.js";import"../chunk-g5tj10p8.js";import{Te as Vb,Ue as lb,Ve as Eb,We as db,Xe as ib}from"../chunk-kv2ep453.js";import"../chunk-nncwsdzz.js";import{af as b0}from"../chunk-w6gb9gc5.js";import"../chunk-6j1z2cqt.js";import{df as y,hf as Yc}from"../chunk-7f5ad759.js";var Oh=y(hc(),1);function p0(c){return(x)=>async(f)=>{let{request:t}=f;if(c.expectContinueHeader!==!1&&Oh.HttpRequest.isInstance(t)&&t.body&&c.runtime==="node"&&c.requestHandler?.constructor?.name!=="FetchHttpHandler"){let n=!0;if(typeof c.expectContinueHeader==="number")try{n=(Number(t.headers?.["content-length"])??c.bodyLengthChecker?.(t.body)??1/0)>=c.expectContinueHeader}catch(h){}else n=!!c.expectContinueHeader;if(n)t.headers.Expect="100-continue"}return x({...f,request:t})}}var V0={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0},Dh=(c)=>({applyToStack:(x)=>{x.add(p0(c),V0)}});var l={WHEN_SUPPORTED:"WHEN_SUPPORTED",WHEN_REQUIRED:"WHEN_REQUIRED"},gx=l.WHEN_SUPPORTED,Oc={WHEN_SUPPORTED:"WHEN_SUPPORTED",WHEN_REQUIRED:"WHEN_REQUIRED"},Cx=l.WHEN_SUPPORTED,O;(function(c){c.MD5="MD5",c.CRC32="CRC32",c.CRC32C="CRC32C",c.CRC64NVME="CRC64NVME",c.SHA1="SHA1",c.SHA256="SHA256"})(O||(O={}));var Jh;(function(c){c.HEADER="header",c.TRAILER="trailer"})(Jh||(Jh={}));var wx=O.CRC32;var wc;(function(c){c.ENV="env",c.CONFIG="shared config entry"})(wc||(wc={}));var uc=(c,x,f,t)=>{if(!(x in c))return;let n=c[x].toUpperCase();if(!Object.values(f).includes(n))throw TypeError(`Cannot load ${t} '${x}'. Expected one of ${Object.values(f)}, got '${c[x]}'.`);return n};var l0="AWS_REQUEST_CHECKSUM_CALCULATION",E0="request_checksum_calculation",Qh={environmentVariableSelector:(c)=>uc(c,l0,l,wc.ENV),configFileSelector:(c)=>uc(c,E0,l,wc.CONFIG),default:gx};var d0="AWS_RESPONSE_CHECKSUM_VALIDATION",i0="response_checksum_validation",kh={environmentVariableSelector:(c)=>uc(c,d0,Oc,wc.ENV),configFileSelector:(c)=>uc(c,i0,Oc,wc.CONFIG),default:Cx};var Lc=y(sc(),1),Ch=y(hc(),1),Ph=y(Vx(),1);var Yh=(c,{requestChecksumRequired:x,requestAlgorithmMember:f,requestChecksumCalculation:t})=>{if(!f)return t===l.WHEN_SUPPORTED||x?wx:void 0;if(!c[f])return;return c[f]};var Dc=(c)=>c===O.MD5?"content-md5":`x-amz-checksum-${c.toLowerCase()}`;var Xh=(c,x)=>{let f=c.toLowerCase();for(let t of Object.keys(x))if(f===t.toLowerCase())return!0;return!1};var Uh=(c,x)=>{let f=c.toLowerCase();for(let t of Object.keys(x))if(t.toLowerCase().startsWith(f))return!0;return!1};var Hh=y(o0(),1),Px=(c)=>c!==void 0&&typeof c!=="string"&&!ArrayBuffer.isView(c)&&!Hh.isArrayBuffer(c);var Fh=y(e0(),1),{__extends:ry,__assign:c8,__rest:x8,__decorate:f8,__param:t8,__esDecorate:n8,__runInitializers:h8,__propKey:v8,__setFunctionName:S8,__metadata:w8,__awaiter:mx,__generator:Tx,__exportStar:b8,__createBinding:y8,__values:_x,__read:B8,__spread:$8,__spreadArrays:G8,__spreadArray:M8,__await:z8,__asyncGenerator:N8,__asyncDelegator:Z8,__asyncValues:W8,__makeTemplateObject:R8,__importStar:j8,__importDefault:K8,__classPrivateFieldGet:O8,__classPrivateFieldSet:D8,__classPrivateFieldIn:J8,__addDisposableResource:Q8,__disposeResources:k8,__rewriteRelativeImportExtension:Y8}=Fh.default;import{Buffer as uh}from"buffer";var Lh=(c,x)=>{if(typeof c!=="string")throw TypeError(`The "input" argument must be of type string. Received type ${typeof c} (${c})`);return x?uh.from(c,x):uh.from(c)};var ht=(c)=>{let x=Lh(c,"utf8");return new Uint8Array(x.buffer,x.byteOffset,x.byteLength/Uint8Array.BYTES_PER_ELEMENT)};var a0=typeof Buffer<"u"&&Buffer.from?function(c){return Buffer.from(c,"utf8")}:ht;function bx(c){if(c instanceof Uint8Array)return c;if(typeof c==="string")return a0(c);if(ArrayBuffer.isView(c))return new Uint8Array(c.buffer,c.byteOffset,c.byteLength/Uint8Array.BYTES_PER_ELEMENT);return new Uint8Array(c)}function yx(c){if(typeof c==="string")return c.length===0;return c.byteLength===0}function Jc(c){return new Uint8Array([(c&4278190080)>>24,(c&16711680)>>16,(c&65280)>>8,c&255])}function Bx(c){if(!Uint32Array.from){var x=new Uint32Array(c.length),f=0;while(f<c.length)x[f]=c[f],f+=1;return x}return Uint32Array.from(c)}var St=function(){function c(){this.crc32c=new vt}return c.prototype.update=function(x){if(yx(x))return;this.crc32c.update(bx(x))},c.prototype.digest=function(){return mx(this,void 0,void 0,function(){return Tx(this,function(x){return[2,Jc(this.crc32c.digest())]})})},c.prototype.reset=function(){this.crc32c=new vt},c}();var vt=function(){function c(){this.checksum=4294967295}return c.prototype.update=function(x){var f,t;try{for(var n=_x(x),h=n.next();!h.done;h=n.next()){var v=h.value;this.checksum=this.checksum>>>8^cw[(this.checksum^v)&255]}}catch(S){f={error:S}}finally{try{if(h&&!h.done&&(t=n.return))t.call(n)}finally{if(f)throw f.error}}return this},c.prototype.digest=function(){return(this.checksum^4294967295)>>>0},c}();var r0=[0,4067132163,3778769143,324072436,3348797215,904991772,648144872,3570033899,2329499855,2024987596,1809983544,2575936315,1296289744,3207089363,2893594407,1578318884,274646895,3795141740,4049975192,51262619,3619967088,632279923,922689671,3298075524,2592579488,1760304291,2075979607,2312596564,1562183871,2943781820,3156637768,1313733451,549293790,3537243613,3246849577,871202090,3878099393,357341890,102525238,4101499445,2858735121,1477399826,1264559846,3107202533,1845379342,2677391885,2361733625,2125378298,820201905,3263744690,3520608582,598981189,4151959214,85089709,373468761,3827903834,3124367742,1213305469,1526817161,2842354314,2107672161,2412447074,2627466902,1861252501,1098587580,3004210879,2688576843,1378610760,2262928035,1955203488,1742404180,2511436119,3416409459,969524848,714683780,3639785095,205050476,4266873199,3976438427,526918040,1361435347,2739821008,2954799652,1114974503,2529119692,1691668175,2005155131,2247081528,3690758684,697762079,986182379,3366744552,476452099,3993867776,4250756596,255256311,1640403810,2477592673,2164122517,1922457750,2791048317,1412925310,1197962378,3037525897,3944729517,427051182,170179418,4165941337,746937522,3740196785,3451792453,1070968646,1905808397,2213795598,2426610938,1657317369,3053634322,1147748369,1463399397,2773627110,4215344322,153784257,444234805,3893493558,1021025245,3467647198,3722505002,797665321,2197175160,1889384571,1674398607,2443626636,1164749927,3070701412,2757221520,1446797203,137323447,4198817972,3910406976,461344835,3484808360,1037989803,781091935,3705997148,2460548119,1623424788,1939049696,2180517859,1429367560,2807687179,3020495871,1180866812,410100952,3927582683,4182430767,186734380,3756733383,763408580,1053836080,3434856499,2722870694,1344288421,1131464017,2971354706,1708204729,2545590714,2229949006,1988219213,680717673,3673779818,3383336350,1002577565,4010310262,493091189,238226049,4233660802,2987750089,1082061258,1395524158,2705686845,1972364758,2279892693,2494862625,1725896226,952904198,3399985413,3656866545,731699698,4283874585,222117402,510512622,3959836397,3280807620,837199303,582374963,3504198960,68661723,4135334616,3844915500,390545967,1230274059,3141532936,2825850620,1510247935,2395924756,2091215383,1878366691,2644384480,3553878443,565732008,854102364,3229815391,340358836,3861050807,4117890627,119113024,1493875044,2875275879,3090270611,1247431312,2660249211,1828433272,2141937292,2378227087,3811616794,291187481,34330861,4032846830,615137029,3603020806,3314634738,939183345,1776939221,2609017814,2295496738,2058945313,2926798794,1545135305,1330124605,3173225534,4084100981,17165430,307568514,3762199681,888469610,3332340585,3587147933,665062302,2042050490,2346497209,2559330125,1793573966,3190661285,1279665062,1595330642,2910671697],cw=Bx(r0);var xw=()=>{let x=[,,,,,,,,];for(let f=0;f<8;f++){let t=Array(512);for(let n=0;n<256;n++){let h=BigInt(n);for(let v=0;v<8*(f+1);v++)if(h&1n)h=h>>1n^0x9a6c9329ac4bc9b5n;else h=h>>1n;t[n*2]=Number(h>>32n&0xffffffffn),t[n*2+1]=Number(h&0xffffffffn)}x[f]=new Uint32Array(t)}return x},wt,$x,bt,yt,Bt,$t,Gt,Mt,zt,fw=()=>{if(!wt)wt=xw(),[$x,bt,yt,Bt,$t,Gt,Mt,zt]=wt};class Nt{c1=0;c2=0;constructor(){fw(),this.reset()}update(c){let x=c.length,f=0,t=this.c1,n=this.c2;while(f+8<=x){let h=((n^c[f++])&255)<<1,v=((n>>>8^c[f++])&255)<<1,S=((n>>>16^c[f++])&255)<<1,w=((n>>>24^c[f++])&255)<<1,b=((t^c[f++])&255)<<1,B=((t>>>8^c[f++])&255)<<1,$=((t>>>16^c[f++])&255)<<1,N=((t>>>24^c[f++])&255)<<1;t=zt[h]^Mt[v]^Gt[S]^$t[w]^Bt[b]^yt[B]^bt[$]^$x[N],n=zt[h+1]^Mt[v+1]^Gt[S+1]^$t[w+1]^Bt[b+1]^yt[B+1]^bt[$+1]^$x[N+1]}while(f<x){let h=((n^c[f])&255)<<1;n=(n>>>8|(t&255)<<24)>>>0,t=t>>>8^$x[h],n^=$x[h+1],f++}this.c1=t,this.c2=n}async digest(){let c=this.c1^4294967295,x=this.c2^4294967295;return new Uint8Array([c>>>24,c>>>16&255,c>>>8&255,c&255,x>>>24,x>>>16&255,x>>>8&255,x&255])}reset(){this.c1=4294967295,this.c2=4294967295}}var Zt={CrtCrc64Nvme:null};var Wt=function(){function c(){this.crc32=new Qc}return c.prototype.update=function(x){if(yx(x))return;this.crc32.update(bx(x))},c.prototype.digest=function(){return mx(this,void 0,void 0,function(){return Tx(this,function(x){return[2,Jc(this.crc32.digest())]})})},c.prototype.reset=function(){this.crc32=new Qc},c}();var Qc=function(){function c(){this.checksum=4294967295}return c.prototype.update=function(x){var f,t;try{for(var n=_x(x),h=n.next();!h.done;h=n.next()){var v=h.value;this.checksum=this.checksum>>>8^nw[(this.checksum^v)&255]}}catch(S){f={error:S}}finally{try{if(h&&!h.done&&(t=n.return))t.call(n)}finally{if(f)throw f.error}}return this},c.prototype.digest=function(){return(this.checksum^4294967295)>>>0},c}();var tw=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918000,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117],nw=Bx(tw);import*as Rt from"zlib";class sh{checksum=0;update(c){this.checksum=Rt.crc32(c,this.checksum)}async digest(){return Jc(this.checksum)}reset(){this.checksum=0}}var Ah=()=>{if(typeof Rt.crc32>"u")return Wt;return sh};var Ih=[O.CRC32,O.CRC32C,O.CRC64NVME,O.SHA1,O.SHA256],jt=[O.SHA256,O.SHA1,O.CRC32,O.CRC32C,O.CRC64NVME];var qx=(c,x)=>{let{checksumAlgorithms:f={}}=x;switch(c){case O.MD5:return f?.MD5??x.md5;case O.CRC32:return f?.CRC32??Ah();case O.CRC32C:return f?.CRC32C??St;case O.CRC64NVME:if(typeof Zt.CrtCrc64Nvme!=="function")return f?.CRC64NVME??Nt;return f?.CRC64NVME??Zt.CrtCrc64Nvme;case O.SHA1:return f?.SHA1??x.sha1;case O.SHA256:return f?.SHA256??x.sha256;default:if(f?.[c])return f[c];throw Error(`The checksum algorithm "${c}" is not supported by the client. Select one of ${Ih}, or provide an implementation to the client constructor checksums field.`)}};var gh=y(Kt(),1),px=(c,x)=>{let f=new c;return f.update(gh.toUint8Array(x||"")),f.digest()};var mh={name:"flexibleChecksumsMiddleware",step:"build",tags:["BODY_CHECKSUM"],override:!0},Th=(c,x)=>(f,t)=>async(n)=>{if(!Ch.HttpRequest.isInstance(n.request))return f(n);if(Uh("x-amz-checksum-",n.request.headers))return f(n);let{request:h,input:v}=n,{body:S,headers:w}=h,{base64Encoder:b,streamHasher:B}=c,{requestChecksumRequired:$,requestAlgorithmMember:N}=x,j=await c.requestChecksumCalculation(),I=N?.name,T=N?.httpHeader;if(I&&!v[I]){if(j===l.WHEN_SUPPORTED||$){if(v[I]=wx,T)w[T]=wx}}let cc=Yh(v,{requestChecksumRequired:$,requestAlgorithmMember:N?.name,requestChecksumCalculation:j}),jc=S,Kc=w;if(cc){switch(cc){case O.CRC32:Lc.setFeature(t,"FLEXIBLE_CHECKSUMS_REQ_CRC32","U");break;case O.CRC32C:Lc.setFeature(t,"FLEXIBLE_CHECKSUMS_REQ_CRC32C","V");break;case O.CRC64NVME:Lc.setFeature(t,"FLEXIBLE_CHECKSUMS_REQ_CRC64","W");break;case O.SHA1:Lc.setFeature(t,"FLEXIBLE_CHECKSUMS_REQ_SHA1","X");break;case O.SHA256:Lc.setFeature(t,"FLEXIBLE_CHECKSUMS_REQ_SHA256","Y");break}let V=Dc(cc),tt=qx(cc,c);if(Px(S)){let{getAwsChunkedEncodingStream:nt,bodyLengthChecker:q0}=c;jc=nt(typeof c.requestStreamBufferSize==="number"&&c.requestStreamBufferSize>=8192?Ph.createBufferedReadable(S,c.requestStreamBufferSize,t.logger):S,{base64Encoder:b,bodyLengthChecker:q0,checksumLocationName:V,checksumAlgorithmFn:tt,streamHasher:B}),Kc={...w,"content-encoding":w["content-encoding"]?`${w["content-encoding"]},aws-chunked`:"aws-chunked","transfer-encoding":"chunked","x-amz-decoded-content-length":w["content-length"],"x-amz-content-sha256":"STREAMING-UNSIGNED-PAYLOAD-TRAILER","x-amz-trailer":V},delete Kc["content-length"]}else if(!Xh(V,w)){let nt=await px(tt,S);Kc={...w,[V]:b(nt)}}}try{return await f({...n,request:{...h,headers:Kc,body:jc}})}catch(V){if(V instanceof Error&&V.name==="InvalidChunkSizeError")try{if(!V.message.endsWith("."))V.message+=".";V.message+=" Set [requestStreamBufferSize=number e.g. 65_536] in client constructor to instruct AWS SDK to buffer your input stream."}catch(tt){}throw V}};var Gx=y(sc(),1);var _h={name:"flexibleChecksumsInputMiddleware",toMiddleware:"serializerMiddleware",relation:"before",tags:["BODY_CHECKSUM"],override:!0},qh=(c,x)=>(f,t)=>async(n)=>{let h=n.input,{requestValidationModeMember:v}=x,S=await c.requestChecksumCalculation(),w=await c.responseChecksumValidation();switch(S){case l.WHEN_REQUIRED:Gx.setFeature(t,"FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED","a");break;case l.WHEN_SUPPORTED:Gx.setFeature(t,"FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED","Z");break}switch(w){case Oc.WHEN_REQUIRED:Gx.setFeature(t,"FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED","c");break;case Oc.WHEN_SUPPORTED:Gx.setFeature(t,"FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED","b");break}if(v&&!h[v]){if(w===Oc.WHEN_SUPPORTED)h[v]="ENABLED"}return f(n)};var dh=y(hc(),1);var lx=(c=[])=>{let x=[],f=jt.length;for(let t of c){let n=jt.indexOf(t);if(n!==-1)x[n]=t;else x[f++]=t}return x.filter(Boolean)};var ph=(c)=>{let x=c.lastIndexOf("-");if(x!==-1){let f=c.slice(x+1);if(!f.startsWith("0")){let t=parseInt(f,10);if(!isNaN(t)&&t>=1&&t<=1e4)return!0}}return!1};var lh=y(Vx(),1);var Vh=async(c,{checksumAlgorithmFn:x,base64Encoder:f})=>f(await px(x,c));var Eh=async(c,{config:x,responseAlgorithms:f,logger:t})=>{let n=lx(f),{body:h,headers:v}=c;for(let S of n){let w=Dc(S),b=v[w];if(b){let B;try{B=qx(S,x)}catch(j){if(S===O.CRC64NVME){t?.warn(`Skipping ${O.CRC64NVME} checksum validation: ${j.message}`);continue}throw j}let{base64Encoder:$}=x;if(Px(h)){c.body=lh.createChecksumStream({expectedChecksum:b,checksumSourceLocation:w,checksum:new B,source:h,base64Encoder:$});return}let N=await Vh(h,{checksumAlgorithmFn:B,base64Encoder:$});if(N===b)break;throw Error(`Checksum mismatch: expected "${N}" but received "${b}" in response header "${w}".`)}}};var ih={name:"flexibleChecksumsResponseMiddleware",toMiddleware:"deserializerMiddleware",relation:"after",tags:["BODY_CHECKSUM"],override:!0},oh=(c,x)=>(f,t)=>async(n)=>{if(!dh.HttpRequest.isInstance(n.request))return f(n);let h=n.input,v=await f(n),S=v.response,{requestValidationModeMember:w,responseAlgorithms:b}=x;if(w&&h[w]==="ENABLED"){let{clientName:B,commandName:$}=t,N=Object.keys(c.checksumAlgorithms??{}).filter((T)=>{let cc=Dc(T);return S.headers[cc]!==void 0}),j=lx([...b??[],...N]);if(B==="S3Client"&&$==="GetObjectCommand"&&j.every((T)=>{let cc=Dc(T),jc=S.headers[cc];return!jc||ph(jc)}))return v;await Eh(S,{config:c,responseAlgorithms:j,logger:t.logger})}return v};var Ex=(c,x)=>({applyToStack:(f)=>{f.add(Th(c,x),mh),f.addRelativeTo(qh(c,x),_h),f.addRelativeTo(oh(c,x),ih)}});var Ot=y(Dt(),1);var eh=(c)=>{let{requestChecksumCalculation:x,responseChecksumValidation:f,requestStreamBufferSize:t}=c;return Object.assign(c,{requestChecksumCalculation:Ot.normalizeProvider(x??gx),responseChecksumValidation:Ot.normalizeProvider(f??Cx),requestStreamBufferSize:Number(t??0),checksumAlgorithms:c.checksumAlgorithms??{}})};var Af=y(d4(),1),qS=y(i4(),1),pS=y(o4(),1);var ah=y(hc(),1),rh=y(E(),1),hw="content-length",vw="x-amz-decoded-content-length";function Sw(){return(c,x)=>async(f)=>{let{request:t}=f;if(ah.HttpRequest.isInstance(t)){if(!(hw in t.headers)&&!(vw in t.headers))if(typeof x?.logger?.warn==="function"&&!(x.logger instanceof rh.NoOpLogger))x.logger.warn("Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.");else console.warn("Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.")}return c({...f})}}var ww={step:"finalizeRequest",tags:["CHECK_CONTENT_LENGTH_HEADER"],name:"getCheckContentLengthHeaderPlugin",override:!0},cv=(c)=>({applyToStack:(x)=>{x.add(Sw(),ww)}});var xv=(c)=>{return(x,f)=>async(t)=>{let n=await c.region(),h=c.region,v=()=>{};if(f.__s3RegionRedirect)Object.defineProperty(c,"region",{writable:!1,value:async()=>{return f.__s3RegionRedirect}}),v=()=>Object.defineProperty(c,"region",{writable:!0,value:h});try{let S=await x(t);if(f.__s3RegionRedirect){v();let w=await c.region();if(n!==w)throw Error("Region was not restored following S3 region redirect.")}return S}catch(S){throw v(),S}}},fv={tags:["REGION_REDIRECT","S3"],name:"regionRedirectEndpointMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};function bw(c){return(x,f)=>async(t)=>{try{return await x(t)}catch(n){if(c.followRegionRedirects){let h=n?.$metadata?.httpStatusCode,v=f.commandName==="HeadBucketCommand",S=n?.$response?.headers?.["x-amz-bucket-region"];if(S){if(h===301||h===400&&(n?.name==="IllegalLocationConstraintException"||v)){try{let w=S;f.logger?.debug(`Redirecting from ${await c.region()} to ${w}`),f.__s3RegionRedirect=w}catch(w){throw Error("Region redirect failed: "+w)}return x(t)}}}throw n}}}var yw={step:"initialize",tags:["REGION_REDIRECT","S3"],name:"regionRedirectMiddleware",override:!0},tv=(c)=>({applyToStack:(x)=>{x.add(bw(c),yw),x.addRelativeTo(xv(c),fv)}});var nv=y(hc(),1),hv=y(E(),1),Bw=(c)=>{return(x,f)=>async(t)=>{let n=await x(t),{response:h}=n;if(nv.HttpResponse.isInstance(h)){if(h.headers.expires){h.headers.expiresstring=h.headers.expires;try{hv.parseRfc7231DateTime(h.headers.expires)}catch(v){f.logger?.warn(`AWS SDK Warning for ${f.clientName}::${f.commandName} response parsing (${h.headers.expires}): ${v}`),delete h.headers.expires}}}return n}},$w={tags:["S3"],name:"s3ExpiresMiddleware",override:!0,relation:"after",toMiddleware:"deserializerMiddleware"},dx=(c)=>({applyToStack:(x)=>{x.addRelativeTo(Bw(c),$w)}});class ix{data;lastPurgeTime=Date.now();static EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS=30000;constructor(c={}){this.data=c}get(c){let x=this.data[c];if(!x)return;return x}set(c,x){return this.data[c]=x,x}delete(c){delete this.data[c]}async purgeExpired(){let c=Date.now();if(this.lastPurgeTime+ix.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS>c)return;for(let x in this.data){let f=this.data[x];if(!f.isRefreshing){let t=await f.identity;if(t.expiration){if(t.expiration.getTime()<c)delete this.data[x]}}}}}class Mx{_identity;isRefreshing;accessed;constructor(c,x=!1,f=Date.now()){this._identity=c,this.isRefreshing=x,this.accessed=f}get identity(){return this.accessed=Date.now(),this._identity}}class zx{createSessionFn;cache;static REFRESH_WINDOW_MS=60000;constructor(c,x=new ix){this.createSessionFn=c,this.cache=x}async getS3ExpressIdentity(c,x){let f=x.Bucket,{cache:t}=this,n=t.get(f);if(n)return n.identity.then((h)=>{if((h.expiration?.getTime()??0)<Date.now())return t.set(f,new Mx(this.getIdentity(f))).identity;if((h.expiration?.getTime()??0)<Date.now()+zx.REFRESH_WINDOW_MS&&!n.isRefreshing)n.isRefreshing=!0,this.getIdentity(f).then((w)=>{t.set(f,new Mx(Promise.resolve(w)))});return h});return t.set(f,new Mx(this.getIdentity(f))).identity}async getIdentity(c){await this.cache.purgeExpired().catch((t)=>{console.warn(`Error while clearing expired entries in S3ExpressIdentityCache:
3
- `+t)});let x=await this.createSessionFn(c);if(!x.Credentials?.AccessKeyId||!x.Credentials?.SecretAccessKey)throw Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey.");return{accessKeyId:x.Credentials.AccessKeyId,secretAccessKey:x.Credentials.SecretAccessKey,sessionToken:x.Credentials.SessionToken,expiration:x.Credentials.Expiration?new Date(x.Credentials.Expiration):void 0}}}var Gv=y($v(),1);var Ac=y(vv(),1),Sv="Directory",wv="S3Express",bv="sigv4-s3express",ox="X-Amz-S3session-Token",Nx=ox.toLowerCase(),Gw="AWS_S3_DISABLE_EXPRESS_SESSION_AUTH",Mw="s3_disable_express_session_auth",Jt={environmentVariableSelector:(c)=>Ac.booleanSelector(c,Gw,Ac.SelectorType.ENV),configFileSelector:(c)=>Ac.booleanSelector(c,Mw,Ac.SelectorType.CONFIG),default:!1};class ex extends Gv.SignatureV4{async signWithCredentials(c,x,f){let t=yv(x);c.headers[Nx]=x.sessionToken;let n=this;return Bv(n,t),n.signRequest(c,f??{})}async presignWithCredentials(c,x,f){let t=yv(x);return delete c.headers[Nx],c.headers[ox]=x.sessionToken,c.query=c.query??{},c.query[ox]=x.sessionToken,Bv(this,t),this.presign(c,f)}}function yv(c){return{accessKeyId:c.accessKeyId,secretAccessKey:c.secretAccessKey,expiration:c.expiration}}function Bv(c,x){let f=setTimeout(()=>{throw Error("SignatureV4S3Express credential override was created but not called.")},10),t=c.credentialProvider,n=()=>{return clearTimeout(f),c.credentialProvider=t,Promise.resolve(x)};c.credentialProvider=n}var Mv=y(sc(),1),zv=y(hc(),1);var Nv=(c)=>{return(x,f)=>async(t)=>{if(f.endpointV2){let n=f.endpointV2,h=n.properties?.authSchemes?.[0]?.name===bv;if(n.properties?.backend===wv||n.properties?.bucketType===Sv)Mv.setFeature(f,"S3_EXPRESS_BUCKET","J"),f.isS3ExpressBucket=!0;if(h){let S=t.input.Bucket;if(S){let w=await c.s3ExpressIdentityProvider.getS3ExpressIdentity(await c.credentials(),{Bucket:S});if(f.s3ExpressIdentity=w,zv.HttpRequest.isInstance(t.request)&&w.sessionToken)t.request.headers[Nx]=w.sessionToken}}}return x(t)}},Zv={name:"s3ExpressMiddleware",step:"build",tags:["S3","S3_EXPRESS"],override:!0},Qt=(c)=>({applyToStack:(x)=>{x.add(Nv(c),Zv)}});var jv=y(Rv(),1),Kv=y(hc(),1),Ov=y(Dt(),1);var Wv=async(c,x,f,t)=>{let n=await t.signWithCredentials(f,c,{});if(n.headers["X-Amz-Security-Token"]||n.headers["x-amz-security-token"])throw Error("X-Amz-Security-Token must not be set for s3-express requests.");return n};var zw=(c)=>(x)=>{throw x},Nw=(c,x)=>{};var Dv=(c)=>(x,f)=>async(t)=>{if(!Kv.HttpRequest.isInstance(t.request))return x(t);let h=Ov.getSmithyContext(f).selectedHttpAuthScheme;if(!h)throw Error("No HttpAuthScheme was selected: unable to sign request");let{httpAuthOption:{signingProperties:v={}},identity:S,signer:w}=h,b;if(f.s3ExpressIdentity)b=await Wv(f.s3ExpressIdentity,v,t.request,await c.signer());else b=await w.sign(t.request,S,v);let B=await x({...t,request:b}).catch((w.errorHandler||zw)(v));return(w.successHandler||Nw)(B.response,v),B},kt=(c)=>({applyToStack:(x)=>{x.addRelativeTo(Dv(c),jv.httpSigningMiddlewareOptions)}});var Jv=(c,{session:x})=>{let[f,t]=x,{forcePathStyle:n,useAccelerateEndpoint:h,disableMultiregionAccessPoints:v,followRegionRedirects:S,s3ExpressIdentityProvider:w,bucketEndpoint:b,expectContinueHeader:B}=c;return Object.assign(c,{forcePathStyle:n??!1,useAccelerateEndpoint:h??!1,disableMultiregionAccessPoints:v??!1,followRegionRedirects:S??!1,s3ExpressIdentityProvider:w??new zx(async($)=>f().send(new t({Bucket:$}))),bucketEndpoint:b??!1,expectContinueHeader:B??2097152})};var Qv=y(hc(),1),ax=y(Vx(),1),Zw={CopyObjectCommand:!0,UploadPartCopyCommand:!0,CompleteMultipartUploadCommand:!0},Ww=3000,Rw=(c)=>(x,f)=>async(t)=>{let n=await x(t),{response:h}=n;if(!Qv.HttpResponse.isInstance(h))return n;let{statusCode:v,body:S}=h;if(v<200||v>=300)return n;if(!(typeof S?.stream==="function"||typeof S?.pipe==="function"||typeof S?.tee==="function"))return n;let b=S,B=S;if(S&&typeof S==="object"&&!(S instanceof Uint8Array))[b,B]=await ax.splitStream(S);h.body=B;let $=await jw(b,{streamCollector:async(j)=>{return ax.headStream(j,Ww)}});if(typeof b?.destroy==="function")b.destroy();let N=c.utf8Encoder($.subarray($.length-16));if($.length===0&&Zw[f.commandName]){let j=Error("S3 aborted request");throw j.name="InternalError",j}if(N&&N.endsWith("</Error>"))h.statusCode=400;return n},jw=(c=new Uint8Array,x)=>{if(c instanceof Uint8Array)return Promise.resolve(c);return x.streamCollector(c)||Promise.resolve(new Uint8Array)},Kw={relation:"after",toMiddleware:"deserializerMiddleware",tags:["THROW_200_EXCEPTIONS","S3"],name:"throw200ExceptionsMiddleware",override:!0},bc=(c)=>({applyToStack:(x)=>{x.addRelativeTo(Rw(c),Kw)}});var kv=(c)=>typeof c==="string"&&c.indexOf("arn:")===0&&c.split(":").length>=6;function Yv(c){return(x,f)=>async(t)=>{if(c.bucketEndpoint){let n=f.endpointV2;if(n){let h=t.input.Bucket;if(typeof h==="string")try{let v=new URL(h);f.endpointV2={...n,url:v}}catch(v){let S=`@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${h} could not be parsed as URL.`;if(f.logger?.constructor?.name==="NoOpLogger")console.warn(S);else f.logger?.warn?.(S);throw v}}}return x(t)}}var Xv={name:"bucketEndpointMiddleware",override:!0,relation:"after",toMiddleware:"endpointV2Middleware"};function Ow({bucketEndpoint:c}){return(x)=>async(f)=>{let{input:{Bucket:t}}=f;if(!c&&typeof t==="string"&&!kv(t)&&t.indexOf("/")>=0){let n=Error(`Bucket name shouldn't contain '/', received '${t}'`);throw n.name="InvalidBucketName",n}return x({...f})}}var Dw={step:"initialize",tags:["VALIDATE_BUCKET_NAME"],name:"validateBucketNameMiddleware",override:!0},Uv=(c)=>({applyToStack:(x)=>{x.add(Ow(c),Dw),x.addRelativeTo(Yv(c),Xv)}});var If=y(e4(),1),VS=y(sS(),1),Vc=y(Rv(),1),lS=y(d1(),1);var Hv=(c)=>Object.assign(c,{eventStreamMarshaller:c.eventStreamSerdeProvider(c)});var ES=y(a4(),1),dS=y(kc(),1),gf=y(AS(),1),iS=y(E(),1);var nf=y(sc(),1);var Yt=y($v(),1);var Zx={CrtSignerV4:null};class Wx{sigv4aSigner;sigv4Signer;signerOptions;static sigv4aDependency(){if(typeof Zx.CrtSignerV4==="function")return"crt";else if(typeof Yt.signatureV4aContainer.SignatureV4a==="function")return"js";return"none"}constructor(c){this.sigv4Signer=new ex(c),this.signerOptions=c}async sign(c,x={}){if(x.signingRegion==="*")return this.getSigv4aSigner().sign(c,x);return this.sigv4Signer.sign(c,x)}async signWithCredentials(c,x,f={}){if(f.signingRegion==="*"){let t=this.getSigv4aSigner(),n=Zx.CrtSignerV4;if(n&&t instanceof n)return t.signWithCredentials(c,x,f);else throw Error(`signWithCredentials with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.signWithCredentials(c,x,f)}async presign(c,x={}){if(x.signingRegion==="*"){let f=this.getSigv4aSigner(),t=Zx.CrtSignerV4;if(t&&f instanceof t)return f.presign(c,x);else throw Error(`presign with signingRegion '*' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`)}return this.sigv4Signer.presign(c,x)}async presignWithCredentials(c,x,f={}){if(f.signingRegion==="*")throw Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(c,x,f)}getSigv4aSigner(){if(!this.sigv4aSigner){let c=Zx.CrtSignerV4,x=Yt.signatureV4aContainer.SignatureV4a;if(this.signerOptions.runtime==="node"){if(!c&&!x)throw Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");if(c&&typeof c==="function")this.sigv4aSigner=new c({...this.signerOptions,signingAlgorithm:1});else if(x&&typeof x==="function")this.sigv4aSigner=new x({...this.signerOptions});else throw Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt")}else{if(!x||typeof x!=="function")throw Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a");this.sigv4aSigner=new x({...this.signerOptions})}}return this.sigv4aSigner}}var P1=y(kc(),1),mc=y(Dt(),1);var C1=y(sw(),1),Pc=y(Lw(),1);var Ic={["required"]:!1,["type"]:"string"},gc={["required"]:!0,default:!1,["type"]:"boolean"},Rx={["required"]:!1,["type"]:"boolean"},i={["fn"]:"booleanEquals",["argv"]:[{["ref"]:"Accelerate"},!0]},J={["fn"]:"booleanEquals",["argv"]:[{["ref"]:"UseFIPS"},!0]},D={["fn"]:"booleanEquals",["argv"]:[{["ref"]:"UseDualStack"},!0]},Y={["fn"]:"isSet",["argv"]:[{["ref"]:"Endpoint"}]},H1={["fn"]:"aws.partition",["argv"]:[{["ref"]:"Region"}],["assign"]:"partitionResult"},Fv={["fn"]:"stringEquals",["argv"]:[{["fn"]:"getAttr",["argv"]:[{["ref"]:"partitionResult"},"name"]},"aws-cn"]},Kx={["fn"]:"isSet",["argv"]:[{["ref"]:"Bucket"}]},K={["ref"]:"Bucket"},uv={["conditions"]:[i],["error"]:"S3Express does not support S3 Accelerate.",["type"]:"error"},Lv={["conditions"]:[Y,{["fn"]:"parseURL",["argv"]:[{["ref"]:"Endpoint"}],["assign"]:"url"}],["rules"]:[{["conditions"]:[{["fn"]:"isSet",["argv"]:[{["ref"]:"DisableS3ExpressSessionAuth"}]},{["fn"]:"booleanEquals",["argv"]:[{["ref"]:"DisableS3ExpressSessionAuth"},!0]}],["rules"]:[{["conditions"]:[{["fn"]:"booleanEquals",["argv"]:[{["fn"]:"getAttr",["argv"]:[{["ref"]:"url"},"isIp"]},!0]}],["rules"]:[{["conditions"]:[{["fn"]:"uriEncode",["argv"]:[K],["assign"]:"uri_encoded_bucket"}],["rules"]:[{["endpoint"]:{["url"]:"{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",["properties"]:{["backend"]:"S3Express",["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3express",["signingRegion"]:"{Region}"}]},["headers"]:{}},["type"]:"endpoint"}],["type"]:"tree"}],["type"]:"tree"},{["conditions"]:[{["fn"]:"aws.isVirtualHostableS3Bucket",["argv"]:[K,!1]}],["rules"]:[{["endpoint"]:{["url"]:"{url#scheme}://{Bucket}.{url#authority}{url#path}",["properties"]:{["backend"]:"S3Express",["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3express",["signingRegion"]:"{Region}"}]},["headers"]:{}},["type"]:"endpoint"}],["type"]:"tree"},{["error"]:"S3Express bucket name is not a valid virtual hostable name.",["type"]:"error"}],["type"]:"tree"},{["conditions"]:[{["fn"]:"booleanEquals",["argv"]:[{["fn"]:"getAttr",["argv"]:[{["ref"]:"url"},"isIp"]},!0]}],["rules"]:[{["conditions"]:[{["fn"]:"uriEncode",["argv"]:[K],["assign"]:"uri_encoded_bucket"}],["rules"]:[{["endpoint"]:{["url"]:"{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",["properties"]:{["backend"]:"S3Express",["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4-s3express",["signingName"]:"s3express",["signingRegion"]:"{Region}"}]},["headers"]:{}},["type"]:"endpoint"}],["type"]:"tree"}],["type"]:"tree"},{["conditions"]:[{["fn"]:"aws.isVirtualHostableS3Bucket",["argv"]:[K,!1]}],["rules"]:[{["endpoint"]:{["url"]:"{url#scheme}://{Bucket}.{url#authority}{url#path}",["properties"]:{["backend"]:"S3Express",["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4-s3express",["signingName"]:"s3express",["signingRegion"]:"{Region}"}]},["headers"]:{}},["type"]:"endpoint"}],["type"]:"tree"},{["error"]:"S3Express bucket name is not a valid virtual hostable name.",["type"]:"error"}],["type"]:"tree"},P={["fn"]:"parseURL",["argv"]:[{["ref"]:"Endpoint"}],["assign"]:"url"},Xt={["fn"]:"booleanEquals",["argv"]:[{["fn"]:"getAttr",["argv"]:[{["ref"]:"url"},"isIp"]},!0]},F1={["ref"]:"url"},u1={["fn"]:"uriEncode",["argv"]:[K],["assign"]:"uri_encoded_bucket"},_={["backend"]:"S3Express",["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3express",["signingRegion"]:"{Region}"}]},G={},L1={["fn"]:"aws.isVirtualHostableS3Bucket",["argv"]:[K,!1]},sv={["error"]:"S3Express bucket name is not a valid virtual hostable name.",["type"]:"error"},Av={["fn"]:"isSet",["argv"]:[{["ref"]:"UseS3ExpressControlEndpoint"}]},Iv={["fn"]:"booleanEquals",["argv"]:[{["ref"]:"UseS3ExpressControlEndpoint"},!0]},M={["fn"]:"not",["argv"]:[Y]},Z={["fn"]:"booleanEquals",["argv"]:[{["ref"]:"UseDualStack"},!1]},z={["fn"]:"booleanEquals",["argv"]:[{["ref"]:"UseFIPS"},!1]},rx={["error"]:"Unrecognized S3Express bucket name format.",["type"]:"error"},gv={["fn"]:"not",["argv"]:[Kx]},Cv={["ref"]:"hardwareType"},Pv={["conditions"]:[M],["error"]:"Expected a endpoint to be specified but no endpoint was found",["type"]:"error"},cf={["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4a",["signingName"]:"s3-outposts",["signingRegionSet"]:["*"]},{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3-outposts",["signingRegion"]:"{Region}"}]},Ut={["fn"]:"booleanEquals",["argv"]:[{["ref"]:"ForcePathStyle"},!1]},Jw={["ref"]:"ForcePathStyle"},X={["fn"]:"booleanEquals",["argv"]:[{["ref"]:"Accelerate"},!1]},F={["fn"]:"stringEquals",["argv"]:[{["ref"]:"Region"},"aws-global"]},u={["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3",["signingRegion"]:"us-east-1"}]},R={["fn"]:"not",["argv"]:[F]},L={["fn"]:"booleanEquals",["argv"]:[{["ref"]:"UseGlobalEndpoint"},!0]},mv={["url"]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",["properties"]:{["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3",["signingRegion"]:"{Region}"}]},["headers"]:{}},U={["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3",["signingRegion"]:"{Region}"}]},s={["fn"]:"booleanEquals",["argv"]:[{["ref"]:"UseGlobalEndpoint"},!1]},Tv={["url"]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:{}},_v={["url"]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:{}},qv={["url"]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:{}},Ht={["fn"]:"booleanEquals",["argv"]:[{["fn"]:"getAttr",["argv"]:[F1,"isIp"]},!1]},Ft={["url"]:"{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",["properties"]:U,["headers"]:{}},et={["url"]:"{url#scheme}://{Bucket}.{url#authority}{url#path}",["properties"]:U,["headers"]:{}},pv={["endpoint"]:et,["type"]:"endpoint"},ut={["url"]:"https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:{}},Vv={["url"]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:{}},xf={["error"]:"Invalid region: region was not a valid DNS name.",["type"]:"error"},m={["ref"]:"bucketArn"},s1={["ref"]:"arnType"},Lt={["fn"]:"getAttr",["argv"]:[m,"service"]},at={["ref"]:"accessPointName"},lv={["conditions"]:[D],["error"]:"S3 Object Lambda does not support Dual-stack",["type"]:"error"},Ev={["conditions"]:[i],["error"]:"S3 Object Lambda does not support S3 Accelerate",["type"]:"error"},dv={["conditions"]:[{["fn"]:"isSet",["argv"]:[{["ref"]:"DisableAccessPoints"}]},{["fn"]:"booleanEquals",["argv"]:[{["ref"]:"DisableAccessPoints"},!0]}],["error"]:"Access points are not supported for this operation",["type"]:"error"},st={["conditions"]:[{["fn"]:"isSet",["argv"]:[{["ref"]:"UseArnRegion"}]},{["fn"]:"booleanEquals",["argv"]:[{["ref"]:"UseArnRegion"},!1]},{["fn"]:"not",["argv"]:[{["fn"]:"stringEquals",["argv"]:[{["fn"]:"getAttr",["argv"]:[m,"region"]},"{Region}"]}]}],["error"]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",["type"]:"error"},A1={["fn"]:"getAttr",["argv"]:[{["ref"]:"bucketPartition"},"name"]},I1={["fn"]:"getAttr",["argv"]:[m,"accountId"]},At={["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3-object-lambda",["signingRegion"]:"{bucketArn#region}"}]},iv={["error"]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",["type"]:"error"},It={["error"]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",["type"]:"error"},gt={["error"]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",["type"]:"error"},Ct={["error"]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",["type"]:"error"},ov={["error"]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",["type"]:"error"},ev={["error"]:"Invalid ARN: Expected a resource of the format `accesspoint:<accesspoint name>` but no name was provided",["type"]:"error"},jx={["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3",["signingRegion"]:"{bucketArn#region}"}]},av={["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4a",["signingName"]:"s3-outposts",["signingRegionSet"]:["*"]},{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3-outposts",["signingRegion"]:"{bucketArn#region}"}]},rv={["fn"]:"aws.parseArn",["argv"]:[K]},c1={["url"]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:U,["headers"]:{}},x1={["url"]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:U,["headers"]:{}},f1={["url"]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:U,["headers"]:{}},Pt={["url"]:"{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",["properties"]:U,["headers"]:{}},t1={["url"]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:U,["headers"]:{}},n1={["ref"]:"UseObjectLambdaEndpoint"},mt={["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4",["signingName"]:"s3-object-lambda",["signingRegion"]:"{Region}"}]},h1={["url"]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:{}},v1={["url"]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:{}},S1={["url"]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:{}},Tt={["url"]:"{url#scheme}://{url#authority}{url#path}",["properties"]:U,["headers"]:{}},w1={["url"]:"https://s3.{Region}.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:{}},_t=[{["ref"]:"Region"}],Qw=[{["ref"]:"Endpoint"}],kw=[K],qt=[i],Cc=[Y,P],b1=[{["fn"]:"isSet",["argv"]:[{["ref"]:"DisableS3ExpressSessionAuth"}]},{["fn"]:"booleanEquals",["argv"]:[{["ref"]:"DisableS3ExpressSessionAuth"},!0]}],Yw=[u1],pt=[L1],d=[H1],Vt=[J,D],Ox=[J,Z],Dx=[z,D],Jx=[z,Z],y1=[{["fn"]:"substring",["argv"]:[K,6,14,!0],["assign"]:"s3expressAvailabilityZoneId"},{["fn"]:"substring",["argv"]:[K,14,16,!0],["assign"]:"s3expressAvailabilityZoneDelim"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"s3expressAvailabilityZoneDelim"},"--"]}],xc=[{["conditions"]:[J,D],["endpoint"]:{["url"]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",["properties"]:_,["headers"]:{}},["type"]:"endpoint"},{["conditions"]:Ox,["endpoint"]:{["url"]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",["properties"]:_,["headers"]:{}},["type"]:"endpoint"},{["conditions"]:Dx,["endpoint"]:{["url"]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",["properties"]:_,["headers"]:{}},["type"]:"endpoint"},{["conditions"]:Jx,["endpoint"]:{["url"]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",["properties"]:_,["headers"]:{}},["type"]:"endpoint"}],B1=[{["fn"]:"substring",["argv"]:[K,6,15,!0],["assign"]:"s3expressAvailabilityZoneId"},{["fn"]:"substring",["argv"]:[K,15,17,!0],["assign"]:"s3expressAvailabilityZoneDelim"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"s3expressAvailabilityZoneDelim"},"--"]}],$1=[{["fn"]:"substring",["argv"]:[K,6,19,!0],["assign"]:"s3expressAvailabilityZoneId"},{["fn"]:"substring",["argv"]:[K,19,21,!0],["assign"]:"s3expressAvailabilityZoneDelim"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"s3expressAvailabilityZoneDelim"},"--"]}],G1=[{["fn"]:"substring",["argv"]:[K,6,20,!0],["assign"]:"s3expressAvailabilityZoneId"},{["fn"]:"substring",["argv"]:[K,20,22,!0],["assign"]:"s3expressAvailabilityZoneDelim"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"s3expressAvailabilityZoneDelim"},"--"]}],M1=[{["fn"]:"substring",["argv"]:[K,6,26,!0],["assign"]:"s3expressAvailabilityZoneId"},{["fn"]:"substring",["argv"]:[K,26,28,!0],["assign"]:"s3expressAvailabilityZoneDelim"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"s3expressAvailabilityZoneDelim"},"--"]}],fc=[{["conditions"]:[J,D],["endpoint"]:{["url"]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",["properties"]:{["backend"]:"S3Express",["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4-s3express",["signingName"]:"s3express",["signingRegion"]:"{Region}"}]},["headers"]:{}},["type"]:"endpoint"},{["conditions"]:Ox,["endpoint"]:{["url"]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",["properties"]:{["backend"]:"S3Express",["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4-s3express",["signingName"]:"s3express",["signingRegion"]:"{Region}"}]},["headers"]:{}},["type"]:"endpoint"},{["conditions"]:Dx,["endpoint"]:{["url"]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",["properties"]:{["backend"]:"S3Express",["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4-s3express",["signingName"]:"s3express",["signingRegion"]:"{Region}"}]},["headers"]:{}},["type"]:"endpoint"},{["conditions"]:Jx,["endpoint"]:{["url"]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",["properties"]:{["backend"]:"S3Express",["authSchemes"]:[{["disableDoubleEncoding"]:!0,["name"]:"sigv4-s3express",["signingName"]:"s3express",["signingRegion"]:"{Region}"}]},["headers"]:{}},["type"]:"endpoint"}],z1=[K,0,7,!0],N1=[{["fn"]:"substring",["argv"]:[K,7,15,!0],["assign"]:"s3expressAvailabilityZoneId"},{["fn"]:"substring",["argv"]:[K,15,17,!0],["assign"]:"s3expressAvailabilityZoneDelim"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"s3expressAvailabilityZoneDelim"},"--"]}],Z1=[{["fn"]:"substring",["argv"]:[K,7,16,!0],["assign"]:"s3expressAvailabilityZoneId"},{["fn"]:"substring",["argv"]:[K,16,18,!0],["assign"]:"s3expressAvailabilityZoneDelim"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"s3expressAvailabilityZoneDelim"},"--"]}],W1=[{["fn"]:"substring",["argv"]:[K,7,20,!0],["assign"]:"s3expressAvailabilityZoneId"},{["fn"]:"substring",["argv"]:[K,20,22,!0],["assign"]:"s3expressAvailabilityZoneDelim"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"s3expressAvailabilityZoneDelim"},"--"]}],R1=[{["fn"]:"substring",["argv"]:[K,7,21,!0],["assign"]:"s3expressAvailabilityZoneId"},{["fn"]:"substring",["argv"]:[K,21,23,!0],["assign"]:"s3expressAvailabilityZoneDelim"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"s3expressAvailabilityZoneDelim"},"--"]}],j1=[{["fn"]:"substring",["argv"]:[K,7,27,!0],["assign"]:"s3expressAvailabilityZoneId"},{["fn"]:"substring",["argv"]:[K,27,29,!0],["assign"]:"s3expressAvailabilityZoneDelim"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"s3expressAvailabilityZoneDelim"},"--"]}],Xw=[Kx],K1=[{["fn"]:"isValidHostLabel",["argv"]:[{["ref"]:"outpostId"},!1]}],O1=[{["fn"]:"stringEquals",["argv"]:[{["ref"]:"regionPrefix"},"beta"]}],Uw=["*"],D1=[{["fn"]:"isValidHostLabel",["argv"]:[{["ref"]:"Region"},!1]}],yc=[{["fn"]:"stringEquals",["argv"]:[{["ref"]:"Region"},"us-east-1"]}],lt=[{["fn"]:"stringEquals",["argv"]:[s1,"accesspoint"]}],J1=[{["fn"]:"getAttr",["argv"]:[m,"resourceId[1]"],["assign"]:"accessPointName"},{["fn"]:"not",["argv"]:[{["fn"]:"stringEquals",["argv"]:[at,""]}]}],Hw=[m,"resourceId[1]"],Q1=[D],Et=[{["fn"]:"not",["argv"]:[{["fn"]:"stringEquals",["argv"]:[{["fn"]:"getAttr",["argv"]:[m,"region"]},""]}]}],k1=[{["fn"]:"not",["argv"]:[{["fn"]:"isSet",["argv"]:[{["fn"]:"getAttr",["argv"]:[m,"resourceId[2]"]}]}]}],Fw=[m,"resourceId[2]"],dt=[{["fn"]:"aws.partition",["argv"]:[{["fn"]:"getAttr",["argv"]:[m,"region"]}],["assign"]:"bucketPartition"}],Y1=[{["fn"]:"stringEquals",["argv"]:[A1,{["fn"]:"getAttr",["argv"]:[{["ref"]:"partitionResult"},"name"]}]}],it=[{["fn"]:"isValidHostLabel",["argv"]:[{["fn"]:"getAttr",["argv"]:[m,"region"]},!0]}],ot=[{["fn"]:"isValidHostLabel",["argv"]:[I1,!1]}],X1=[{["fn"]:"isValidHostLabel",["argv"]:[at,!1]}],ff=[J],U1=[{["fn"]:"isValidHostLabel",["argv"]:[{["ref"]:"Region"},!0]}],uw={version:"1.0",parameters:{Bucket:Ic,Region:Ic,UseFIPS:gc,UseDualStack:gc,Endpoint:Ic,ForcePathStyle:gc,Accelerate:gc,UseGlobalEndpoint:gc,UseObjectLambdaEndpoint:Rx,Key:Ic,Prefix:Ic,CopySource:Ic,DisableAccessPoints:Rx,DisableMultiRegionAccessPoints:gc,UseArnRegion:Rx,UseS3ExpressControlEndpoint:Rx,DisableS3ExpressSessionAuth:Rx},["rules"]:[{["conditions"]:[{["fn"]:"isSet",["argv"]:_t}],["rules"]:[{["conditions"]:[i,J],error:"Accelerate cannot be used with FIPS",["type"]:"error"},{["conditions"]:[D,Y],error:"Cannot set dual-stack in combination with a custom endpoint.",["type"]:"error"},{["conditions"]:[Y,J],error:"A custom endpoint cannot be combined with FIPS",["type"]:"error"},{["conditions"]:[Y,i],error:"A custom endpoint cannot be combined with S3 Accelerate",["type"]:"error"},{["conditions"]:[J,H1,Fv],error:"Partition does not support FIPS",["type"]:"error"},{["conditions"]:[Kx,{["fn"]:"substring",["argv"]:[K,0,6,!0],["assign"]:"bucketSuffix"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"bucketSuffix"},"--x-s3"]}],["rules"]:[uv,Lv,{["conditions"]:[Av,Iv],["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:[u1,M],["rules"]:[{["conditions"]:Vt,endpoint:{["url"]:"https://s3express-control-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:_,["headers"]:G},["type"]:"endpoint"},{["conditions"]:Ox,endpoint:{["url"]:"https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:_,["headers"]:G},["type"]:"endpoint"},{["conditions"]:Dx,endpoint:{["url"]:"https://s3express-control.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:_,["headers"]:G},["type"]:"endpoint"},{["conditions"]:Jx,endpoint:{["url"]:"https://s3express-control.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:_,["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"}],["type"]:"tree"}],["type"]:"tree"},{["conditions"]:pt,["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:b1,["rules"]:[{["conditions"]:y1,["rules"]:xc,["type"]:"tree"},{["conditions"]:B1,["rules"]:xc,["type"]:"tree"},{["conditions"]:$1,["rules"]:xc,["type"]:"tree"},{["conditions"]:G1,["rules"]:xc,["type"]:"tree"},{["conditions"]:M1,["rules"]:xc,["type"]:"tree"},rx],["type"]:"tree"},{["conditions"]:y1,["rules"]:fc,["type"]:"tree"},{["conditions"]:B1,["rules"]:fc,["type"]:"tree"},{["conditions"]:$1,["rules"]:fc,["type"]:"tree"},{["conditions"]:G1,["rules"]:fc,["type"]:"tree"},{["conditions"]:M1,["rules"]:fc,["type"]:"tree"},rx],["type"]:"tree"}],["type"]:"tree"},sv],["type"]:"tree"},{["conditions"]:[Kx,{["fn"]:"substring",["argv"]:z1,["assign"]:"accessPointSuffix"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"accessPointSuffix"},"--xa-s3"]}],["rules"]:[uv,Lv,{["conditions"]:pt,["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:b1,["rules"]:[{["conditions"]:N1,["rules"]:xc,["type"]:"tree"},{["conditions"]:Z1,["rules"]:xc,["type"]:"tree"},{["conditions"]:W1,["rules"]:xc,["type"]:"tree"},{["conditions"]:R1,["rules"]:xc,["type"]:"tree"},{["conditions"]:j1,["rules"]:xc,["type"]:"tree"},rx],["type"]:"tree"},{["conditions"]:N1,["rules"]:fc,["type"]:"tree"},{["conditions"]:Z1,["rules"]:fc,["type"]:"tree"},{["conditions"]:W1,["rules"]:fc,["type"]:"tree"},{["conditions"]:R1,["rules"]:fc,["type"]:"tree"},{["conditions"]:j1,["rules"]:fc,["type"]:"tree"},rx],["type"]:"tree"}],["type"]:"tree"},sv],["type"]:"tree"},{["conditions"]:[gv,Av,Iv],["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:Cc,endpoint:{["url"]:"{url#scheme}://{url#authority}{url#path}",["properties"]:_,["headers"]:G},["type"]:"endpoint"},{["conditions"]:Vt,endpoint:{["url"]:"https://s3express-control-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",["properties"]:_,["headers"]:G},["type"]:"endpoint"},{["conditions"]:Ox,endpoint:{["url"]:"https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}",["properties"]:_,["headers"]:G},["type"]:"endpoint"},{["conditions"]:Dx,endpoint:{["url"]:"https://s3express-control.dualstack.{Region}.{partitionResult#dnsSuffix}",["properties"]:_,["headers"]:G},["type"]:"endpoint"},{["conditions"]:Jx,endpoint:{["url"]:"https://s3express-control.{Region}.{partitionResult#dnsSuffix}",["properties"]:_,["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"}],["type"]:"tree"},{["conditions"]:[Kx,{["fn"]:"substring",["argv"]:[K,49,50,!0],["assign"]:"hardwareType"},{["fn"]:"substring",["argv"]:[K,8,12,!0],["assign"]:"regionPrefix"},{["fn"]:"substring",["argv"]:z1,["assign"]:"bucketAliasSuffix"},{["fn"]:"substring",["argv"]:[K,32,49,!0],["assign"]:"outpostId"},{["fn"]:"aws.partition",["argv"]:_t,["assign"]:"regionPartition"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"bucketAliasSuffix"},"--op-s3"]}],["rules"]:[{["conditions"]:K1,["rules"]:[{["conditions"]:pt,["rules"]:[{["conditions"]:[{["fn"]:"stringEquals",["argv"]:[Cv,"e"]}],["rules"]:[{["conditions"]:O1,["rules"]:[Pv,{["conditions"]:Cc,endpoint:{["url"]:"https://{Bucket}.ec2.{url#authority}",["properties"]:cf,["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"},{endpoint:{["url"]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",["properties"]:cf,["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[{["fn"]:"stringEquals",["argv"]:[Cv,"o"]}],["rules"]:[{["conditions"]:O1,["rules"]:[Pv,{["conditions"]:Cc,endpoint:{["url"]:"https://{Bucket}.op-{outpostId}.{url#authority}",["properties"]:cf,["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"},{endpoint:{["url"]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",["properties"]:cf,["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',["type"]:"error"}],["type"]:"tree"},{error:"Invalid Outposts Bucket alias - it must be a valid bucket name.",["type"]:"error"}],["type"]:"tree"},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",["type"]:"error"}],["type"]:"tree"},{["conditions"]:Xw,["rules"]:[{["conditions"]:[Y,{["fn"]:"not",["argv"]:[{["fn"]:"isSet",["argv"]:[{["fn"]:"parseURL",["argv"]:Qw}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",["type"]:"error"},{["conditions"]:[Ut,L1],["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:D1,["rules"]:[{["conditions"]:[i,Fv],error:"S3 Accelerate cannot be used in this region",["type"]:"error"},{["conditions"]:[D,J,X,M,F],endpoint:{["url"]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[D,J,X,M,R,L],["rules"]:[{endpoint:mv,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[D,J,X,M,R,s],endpoint:mv,["type"]:"endpoint"},{["conditions"]:[Z,J,X,M,F],endpoint:{["url"]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[Z,J,X,M,R,L],["rules"]:[{endpoint:Tv,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[Z,J,X,M,R,s],endpoint:Tv,["type"]:"endpoint"},{["conditions"]:[D,z,i,M,F],endpoint:{["url"]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[D,z,i,M,R,L],["rules"]:[{endpoint:_v,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[D,z,i,M,R,s],endpoint:_v,["type"]:"endpoint"},{["conditions"]:[D,z,X,M,F],endpoint:{["url"]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[D,z,X,M,R,L],["rules"]:[{endpoint:qv,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[D,z,X,M,R,s],endpoint:qv,["type"]:"endpoint"},{["conditions"]:[Z,z,X,Y,P,Xt,F],endpoint:{["url"]:"{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[Z,z,X,Y,P,Ht,F],endpoint:{["url"]:"{url#scheme}://{Bucket}.{url#authority}{url#path}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[Z,z,X,Y,P,Xt,R,L],["rules"]:[{["conditions"]:yc,endpoint:Ft,["type"]:"endpoint"},{endpoint:Ft,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[Z,z,X,Y,P,Ht,R,L],["rules"]:[{["conditions"]:yc,endpoint:et,["type"]:"endpoint"},pv],["type"]:"tree"},{["conditions"]:[Z,z,X,Y,P,Xt,R,s],endpoint:Ft,["type"]:"endpoint"},{["conditions"]:[Z,z,X,Y,P,Ht,R,s],endpoint:et,["type"]:"endpoint"},{["conditions"]:[Z,z,i,M,F],endpoint:{["url"]:"https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[Z,z,i,M,R,L],["rules"]:[{["conditions"]:yc,endpoint:ut,["type"]:"endpoint"},{endpoint:ut,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[Z,z,i,M,R,s],endpoint:ut,["type"]:"endpoint"},{["conditions"]:[Z,z,X,M,F],endpoint:{["url"]:"https://{Bucket}.s3.{partitionResult#dnsSuffix}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[Z,z,X,M,R,L],["rules"]:[{["conditions"]:yc,endpoint:{["url"]:"https://{Bucket}.s3.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:G},["type"]:"endpoint"},{endpoint:Vv,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[Z,z,X,M,R,s],endpoint:Vv,["type"]:"endpoint"}],["type"]:"tree"},xf],["type"]:"tree"}],["type"]:"tree"},{["conditions"]:[Y,P,{["fn"]:"stringEquals",["argv"]:[{["fn"]:"getAttr",["argv"]:[F1,"scheme"]},"http"]},{["fn"]:"aws.isVirtualHostableS3Bucket",["argv"]:[K,!0]},Ut,z,Z,X],["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:D1,["rules"]:[pv],["type"]:"tree"},xf],["type"]:"tree"}],["type"]:"tree"},{["conditions"]:[Ut,{["fn"]:"aws.parseArn",["argv"]:kw,["assign"]:"bucketArn"}],["rules"]:[{["conditions"]:[{["fn"]:"getAttr",["argv"]:[m,"resourceId[0]"],["assign"]:"arnType"},{["fn"]:"not",["argv"]:[{["fn"]:"stringEquals",["argv"]:[s1,""]}]}],["rules"]:[{["conditions"]:[{["fn"]:"stringEquals",["argv"]:[Lt,"s3-object-lambda"]}],["rules"]:[{["conditions"]:lt,["rules"]:[{["conditions"]:J1,["rules"]:[lv,Ev,{["conditions"]:Et,["rules"]:[dv,{["conditions"]:k1,["rules"]:[st,{["conditions"]:dt,["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:Y1,["rules"]:[{["conditions"]:it,["rules"]:[{["conditions"]:[{["fn"]:"stringEquals",["argv"]:[I1,""]}],error:"Invalid ARN: Missing account id",["type"]:"error"},{["conditions"]:ot,["rules"]:[{["conditions"]:X1,["rules"]:[{["conditions"]:Cc,endpoint:{["url"]:"{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",["properties"]:At,["headers"]:G},["type"]:"endpoint"},{["conditions"]:ff,endpoint:{["url"]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",["properties"]:At,["headers"]:G},["type"]:"endpoint"},{endpoint:{["url"]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",["properties"]:At,["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"},iv],["type"]:"tree"},It],["type"]:"tree"},gt],["type"]:"tree"},Ct],["type"]:"tree"}],["type"]:"tree"}],["type"]:"tree"},ov],["type"]:"tree"},{error:"Invalid ARN: bucket ARN is missing a region",["type"]:"error"}],["type"]:"tree"},ev],["type"]:"tree"},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",["type"]:"error"}],["type"]:"tree"},{["conditions"]:lt,["rules"]:[{["conditions"]:J1,["rules"]:[{["conditions"]:Et,["rules"]:[{["conditions"]:lt,["rules"]:[{["conditions"]:Et,["rules"]:[dv,{["conditions"]:k1,["rules"]:[st,{["conditions"]:dt,["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:[{["fn"]:"stringEquals",["argv"]:[A1,"{partitionResult#name}"]}],["rules"]:[{["conditions"]:it,["rules"]:[{["conditions"]:[{["fn"]:"stringEquals",["argv"]:[Lt,"s3"]}],["rules"]:[{["conditions"]:ot,["rules"]:[{["conditions"]:X1,["rules"]:[{["conditions"]:qt,error:"Access Points do not support S3 Accelerate",["type"]:"error"},{["conditions"]:Vt,endpoint:{["url"]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",["properties"]:jx,["headers"]:G},["type"]:"endpoint"},{["conditions"]:Ox,endpoint:{["url"]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",["properties"]:jx,["headers"]:G},["type"]:"endpoint"},{["conditions"]:Dx,endpoint:{["url"]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",["properties"]:jx,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[z,Z,Y,P],endpoint:{["url"]:"{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",["properties"]:jx,["headers"]:G},["type"]:"endpoint"},{["conditions"]:Jx,endpoint:{["url"]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",["properties"]:jx,["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"},iv],["type"]:"tree"},It],["type"]:"tree"},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",["type"]:"error"}],["type"]:"tree"},gt],["type"]:"tree"},Ct],["type"]:"tree"}],["type"]:"tree"}],["type"]:"tree"},ov],["type"]:"tree"}],["type"]:"tree"}],["type"]:"tree"},{["conditions"]:[{["fn"]:"isValidHostLabel",["argv"]:[at,!0]}],["rules"]:[{["conditions"]:Q1,error:"S3 MRAP does not support dual-stack",["type"]:"error"},{["conditions"]:ff,error:"S3 MRAP does not support FIPS",["type"]:"error"},{["conditions"]:qt,error:"S3 MRAP does not support S3 Accelerate",["type"]:"error"},{["conditions"]:[{["fn"]:"booleanEquals",["argv"]:[{["ref"]:"DisableMultiRegionAccessPoints"},!0]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",["type"]:"error"},{["conditions"]:[{["fn"]:"aws.partition",["argv"]:_t,["assign"]:"mrapPartition"}],["rules"]:[{["conditions"]:[{["fn"]:"stringEquals",["argv"]:[{["fn"]:"getAttr",["argv"]:[{["ref"]:"mrapPartition"},"name"]},{["fn"]:"getAttr",["argv"]:[m,"partition"]}]}],["rules"]:[{endpoint:{["url"]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",["properties"]:{["authSchemes"]:[{["disableDoubleEncoding"]:!0,name:"sigv4a",["signingName"]:"s3",["signingRegionSet"]:Uw}]},["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",["type"]:"error"}],["type"]:"tree"}],["type"]:"tree"},{error:"Invalid Access Point Name",["type"]:"error"}],["type"]:"tree"},ev],["type"]:"tree"},{["conditions"]:[{["fn"]:"stringEquals",["argv"]:[Lt,"s3-outposts"]}],["rules"]:[{["conditions"]:Q1,error:"S3 Outposts does not support Dual-stack",["type"]:"error"},{["conditions"]:ff,error:"S3 Outposts does not support FIPS",["type"]:"error"},{["conditions"]:qt,error:"S3 Outposts does not support S3 Accelerate",["type"]:"error"},{["conditions"]:[{["fn"]:"isSet",["argv"]:[{["fn"]:"getAttr",["argv"]:[m,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",["type"]:"error"},{["conditions"]:[{["fn"]:"getAttr",["argv"]:Hw,["assign"]:"outpostId"}],["rules"]:[{["conditions"]:K1,["rules"]:[st,{["conditions"]:dt,["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:Y1,["rules"]:[{["conditions"]:it,["rules"]:[{["conditions"]:ot,["rules"]:[{["conditions"]:[{["fn"]:"getAttr",["argv"]:Fw,["assign"]:"outpostType"}],["rules"]:[{["conditions"]:[{["fn"]:"getAttr",["argv"]:[m,"resourceId[3]"],["assign"]:"accessPointName"}],["rules"]:[{["conditions"]:[{["fn"]:"stringEquals",["argv"]:[{["ref"]:"outpostType"},"accesspoint"]}],["rules"]:[{["conditions"]:Cc,endpoint:{["url"]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",["properties"]:av,["headers"]:G},["type"]:"endpoint"},{endpoint:{["url"]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",["properties"]:av,["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"},{error:"Expected an outpost type `accesspoint`, found {outpostType}",["type"]:"error"}],["type"]:"tree"},{error:"Invalid ARN: expected an access point name",["type"]:"error"}],["type"]:"tree"},{error:"Invalid ARN: Expected a 4-component resource",["type"]:"error"}],["type"]:"tree"},It],["type"]:"tree"},gt],["type"]:"tree"},Ct],["type"]:"tree"}],["type"]:"tree"}],["type"]:"tree"},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",["type"]:"error"}],["type"]:"tree"},{error:"Invalid ARN: The Outpost Id was not set",["type"]:"error"}],["type"]:"tree"},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",["type"]:"error"}],["type"]:"tree"},{error:"Invalid ARN: No ARN type specified",["type"]:"error"}],["type"]:"tree"},{["conditions"]:[{["fn"]:"substring",["argv"]:[K,0,4,!1],["assign"]:"arnPrefix"},{["fn"]:"stringEquals",["argv"]:[{["ref"]:"arnPrefix"},"arn:"]},{["fn"]:"not",["argv"]:[{["fn"]:"isSet",["argv"]:[rv]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",["type"]:"error"},{["conditions"]:[{["fn"]:"booleanEquals",["argv"]:[Jw,!0]},rv],error:"Path-style addressing cannot be used with ARN buckets",["type"]:"error"},{["conditions"]:Yw,["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:[X],["rules"]:[{["conditions"]:[D,M,J,F],endpoint:{["url"]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[D,M,J,R,L],["rules"]:[{endpoint:c1,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[D,M,J,R,s],endpoint:c1,["type"]:"endpoint"},{["conditions"]:[Z,M,J,F],endpoint:{["url"]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[Z,M,J,R,L],["rules"]:[{endpoint:x1,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[Z,M,J,R,s],endpoint:x1,["type"]:"endpoint"},{["conditions"]:[D,M,z,F],endpoint:{["url"]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[D,M,z,R,L],["rules"]:[{endpoint:f1,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[D,M,z,R,s],endpoint:f1,["type"]:"endpoint"},{["conditions"]:[Z,Y,P,z,F],endpoint:{["url"]:"{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[Z,Y,P,z,R,L],["rules"]:[{["conditions"]:yc,endpoint:Pt,["type"]:"endpoint"},{endpoint:Pt,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[Z,Y,P,z,R,s],endpoint:Pt,["type"]:"endpoint"},{["conditions"]:[Z,M,z,F],endpoint:{["url"]:"https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[Z,M,z,R,L],["rules"]:[{["conditions"]:yc,endpoint:{["url"]:"https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",["properties"]:U,["headers"]:G},["type"]:"endpoint"},{endpoint:t1,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[Z,M,z,R,s],endpoint:t1,["type"]:"endpoint"}],["type"]:"tree"},{error:"Path-style addressing cannot be used with S3 Accelerate",["type"]:"error"}],["type"]:"tree"}],["type"]:"tree"}],["type"]:"tree"},{["conditions"]:[{["fn"]:"isSet",["argv"]:[n1]},{["fn"]:"booleanEquals",["argv"]:[n1,!0]}],["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:U1,["rules"]:[lv,Ev,{["conditions"]:Cc,endpoint:{["url"]:"{url#scheme}://{url#authority}{url#path}",["properties"]:mt,["headers"]:G},["type"]:"endpoint"},{["conditions"]:ff,endpoint:{["url"]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",["properties"]:mt,["headers"]:G},["type"]:"endpoint"},{endpoint:{["url"]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",["properties"]:mt,["headers"]:G},["type"]:"endpoint"}],["type"]:"tree"},xf],["type"]:"tree"}],["type"]:"tree"},{["conditions"]:[gv],["rules"]:[{["conditions"]:d,["rules"]:[{["conditions"]:U1,["rules"]:[{["conditions"]:[J,D,M,F],endpoint:{["url"]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[J,D,M,R,L],["rules"]:[{endpoint:h1,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[J,D,M,R,s],endpoint:h1,["type"]:"endpoint"},{["conditions"]:[J,Z,M,F],endpoint:{["url"]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[J,Z,M,R,L],["rules"]:[{endpoint:v1,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[J,Z,M,R,s],endpoint:v1,["type"]:"endpoint"},{["conditions"]:[z,D,M,F],endpoint:{["url"]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[z,D,M,R,L],["rules"]:[{endpoint:S1,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[z,D,M,R,s],endpoint:S1,["type"]:"endpoint"},{["conditions"]:[z,Z,Y,P,F],endpoint:{["url"]:"{url#scheme}://{url#authority}{url#path}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[z,Z,Y,P,R,L],["rules"]:[{["conditions"]:yc,endpoint:Tt,["type"]:"endpoint"},{endpoint:Tt,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[z,Z,Y,P,R,s],endpoint:Tt,["type"]:"endpoint"},{["conditions"]:[z,Z,M,F],endpoint:{["url"]:"https://s3.{partitionResult#dnsSuffix}",["properties"]:u,["headers"]:G},["type"]:"endpoint"},{["conditions"]:[z,Z,M,R,L],["rules"]:[{["conditions"]:yc,endpoint:{["url"]:"https://s3.{partitionResult#dnsSuffix}",["properties"]:U,["headers"]:G},["type"]:"endpoint"},{endpoint:w1,["type"]:"endpoint"}],["type"]:"tree"},{["conditions"]:[z,Z,M,R,s],endpoint:w1,["type"]:"endpoint"}],["type"]:"tree"},xf],["type"]:"tree"}],["type"]:"tree"}],["type"]:"tree"},{error:"A region must be set when sending requests to S3.",["type"]:"error"}]},g1=uw;var Aw=new Pc.EndpointCache({size:50,params:["Accelerate","Bucket","DisableAccessPoints","DisableMultiRegionAccessPoints","DisableS3ExpressSessionAuth","Endpoint","ForcePathStyle","Region","UseArnRegion","UseDualStack","UseFIPS","UseGlobalEndpoint","UseObjectLambdaEndpoint","UseS3ExpressControlEndpoint"]}),tf=(c,x={})=>{return Aw.get(c,()=>Pc.resolveEndpoint(g1,{endpointParams:c,logger:x.logger}))};Pc.customEndpointFunctions.aws=C1.awsEndpointFunctions;var Iw=(c)=>async(x,f,t)=>{if(!t)throw Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`");let n=await c(x,f,t),h=mc.getSmithyContext(f)?.commandInstance?.constructor?.getEndpointParameterInstructions;if(!h)throw Error(`getEndpointParameterInstructions() is not defined on '${f.commandName}'`);let v=await P1.resolveParams(t,{getEndpointParameterInstructions:h},x);return Object.assign(n,v)},gw=async(c,x,f)=>{return{operation:mc.getSmithyContext(x).operation,region:await mc.normalizeProvider(c.region)()||(()=>{throw Error("expected `region` to be configured for `aws.auth#sigv4`")})()}},m1=Iw(gw);function T1(c){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"s3",region:c.region},propertiesExtractor:(x,f)=>({signingProperties:{config:x,context:f}})}}function _1(c){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"s3",region:c.region},propertiesExtractor:(x,f)=>({signingProperties:{config:x,context:f}})}}var Cw=(c,x,f)=>{return(n)=>{let v=c(n).properties?.authSchemes;if(!v)return x(n);let S=[];for(let w of v){let{name:b,properties:B={},...$}=w,N=b.toLowerCase();if(b!==N)console.warn(`HttpAuthScheme has been normalized with lowercasing: '${b}' to '${N}'`);let j;if(N==="sigv4a"){j="aws.auth#sigv4a";let cc=v.find((jc)=>{let Kc=jc.name.toLowerCase();return Kc!=="sigv4a"&&Kc.startsWith("sigv4")});if(Wx.sigv4aDependency()==="none"&&cc)continue}else if(N.startsWith("sigv4"))j="aws.auth#sigv4";else throw Error(`Unknown HttpAuthScheme found in '@smithy.rules#endpointRuleSet': '${N}'`);let I=f[j];if(!I)throw Error(`Could not find HttpAuthOption create function for '${j}'`);let T=I(n);T.schemeId=j,T.signingProperties={...T.signingProperties||{},...$,...B},S.push(T)}return S}},Pw=(c)=>{let x=[];switch(c.operation){default:x.push(T1(c)),x.push(_1(c))}return x},q1=Cw(tf,Pw,{"aws.auth#sigv4":T1,"aws.auth#sigv4a":_1}),p1=(c)=>{let x=nf.resolveAwsSdkSigV4Config(c),f=nf.resolveAwsSdkSigV4AConfig(x);return Object.assign(f,{authSchemePreference:mc.normalizeProvider(c.authSchemePreference??[])})};var tS=y(kc(),1),nS=y(E(),1);var V1=(c)=>{return Object.assign(c,{useFipsEndpoint:c.useFipsEndpoint??!1,useDualstackEndpoint:c.useDualstackEndpoint??!1,forcePathStyle:c.forcePathStyle??!1,useAccelerateEndpoint:c.useAccelerateEndpoint??!1,useGlobalEndpoint:c.useGlobalEndpoint??!1,disableMultiregionAccessPoints:c.disableMultiregionAccessPoints??!1,defaultSigningName:"s3",clientContextParams:c.clientContextParams??{}})},tc={ForcePathStyle:{type:"clientContextParams",name:"forcePathStyle"},UseArnRegion:{type:"clientContextParams",name:"useArnRegion"},DisableMultiRegionAccessPoints:{type:"clientContextParams",name:"disableMultiregionAccessPoints"},Accelerate:{type:"clientContextParams",name:"useAccelerateEndpoint"},DisableS3ExpressSessionAuth:{type:"clientContextParams",name:"disableS3ExpressSessionAuth"},UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};var rt=y(d1(),1);var l1=y(E(),1);class H extends l1.ServiceException{constructor(c){super(c);Object.setPrototypeOf(this,H.prototype)}}class hf extends H{name="NoSuchUpload";$fault="client";constructor(c){super({name:"NoSuchUpload",$fault:"client",...c});Object.setPrototypeOf(this,hf.prototype)}}class vf extends H{name="AccessDenied";$fault="client";constructor(c){super({name:"AccessDenied",$fault:"client",...c});Object.setPrototypeOf(this,vf.prototype)}}class Sf extends H{name="ObjectNotInActiveTierError";$fault="client";constructor(c){super({name:"ObjectNotInActiveTierError",$fault:"client",...c});Object.setPrototypeOf(this,Sf.prototype)}}class wf extends H{name="BucketAlreadyExists";$fault="client";constructor(c){super({name:"BucketAlreadyExists",$fault:"client",...c});Object.setPrototypeOf(this,wf.prototype)}}class bf extends H{name="BucketAlreadyOwnedByYou";$fault="client";constructor(c){super({name:"BucketAlreadyOwnedByYou",$fault:"client",...c});Object.setPrototypeOf(this,bf.prototype)}}class yf extends H{name="NoSuchBucket";$fault="client";constructor(c){super({name:"NoSuchBucket",$fault:"client",...c});Object.setPrototypeOf(this,yf.prototype)}}class Bf extends H{name="InvalidObjectState";$fault="client";StorageClass;AccessTier;constructor(c){super({name:"InvalidObjectState",$fault:"client",...c});Object.setPrototypeOf(this,Bf.prototype),this.StorageClass=c.StorageClass,this.AccessTier=c.AccessTier}}class $f extends H{name="NoSuchKey";$fault="client";constructor(c){super({name:"NoSuchKey",$fault:"client",...c});Object.setPrototypeOf(this,$f.prototype)}}class Gf extends H{name="NotFound";$fault="client";constructor(c){super({name:"NotFound",$fault:"client",...c});Object.setPrototypeOf(this,Gf.prototype)}}class Mf extends H{name="EncryptionTypeMismatch";$fault="client";constructor(c){super({name:"EncryptionTypeMismatch",$fault:"client",...c});Object.setPrototypeOf(this,Mf.prototype)}}class zf extends H{name="InvalidRequest";$fault="client";constructor(c){super({name:"InvalidRequest",$fault:"client",...c});Object.setPrototypeOf(this,zf.prototype)}}class Nf extends H{name="InvalidWriteOffset";$fault="client";constructor(c){super({name:"InvalidWriteOffset",$fault:"client",...c});Object.setPrototypeOf(this,Nf.prototype)}}class Zf extends H{name="TooManyParts";$fault="client";constructor(c){super({name:"TooManyParts",$fault:"client",...c});Object.setPrototypeOf(this,Zf.prototype)}}class Wf extends H{name="IdempotencyParameterMismatch";$fault="client";constructor(c){super({name:"IdempotencyParameterMismatch",$fault:"client",...c});Object.setPrototypeOf(this,Wf.prototype)}}class Rf extends H{name="ObjectAlreadyInActiveTierError";$fault="client";constructor(c){super({name:"ObjectAlreadyInActiveTierError",$fault:"client",...c});Object.setPrototypeOf(this,Rf.prototype)}}var i1=rt.TypeRegistry.for("smithy.ts.sdk.synthetic.com.amazonaws.s3"),mw=[-3,"smithy.ts.sdk.synthetic.com.amazonaws.s3","S3ServiceException",0,[],[]];i1.registerError(mw,H);var C=rt.TypeRegistry.for("com.amazonaws.s3"),Tw=[-3,"com.amazonaws.s3","AccessDenied",{["error"]:"client",["httpError"]:403},[],[]];C.registerError(Tw,vf);var _w=[-3,"com.amazonaws.s3","BucketAlreadyExists",{["error"]:"client",["httpError"]:409},[],[]];C.registerError(_w,wf);var qw=[-3,"com.amazonaws.s3","BucketAlreadyOwnedByYou",{["error"]:"client",["httpError"]:409},[],[]];C.registerError(qw,bf);var pw=[-3,"com.amazonaws.s3","EncryptionTypeMismatch",{["error"]:"client",["httpError"]:400},[],[]];C.registerError(pw,Mf);var Vw=[-3,"com.amazonaws.s3","IdempotencyParameterMismatch",{["error"]:"client",["httpError"]:400},[],[]];C.registerError(Vw,Wf);var lw=[-3,"com.amazonaws.s3","InvalidObjectState",{["error"]:"client",["httpError"]:403},["StorageClass","AccessTier"],[0,0]];C.registerError(lw,Bf);var Ew=[-3,"com.amazonaws.s3","InvalidRequest",{["error"]:"client",["httpError"]:400},[],[]];C.registerError(Ew,zf);var dw=[-3,"com.amazonaws.s3","InvalidWriteOffset",{["error"]:"client",["httpError"]:400},[],[]];C.registerError(dw,Nf);var iw=[-3,"com.amazonaws.s3","NoSuchBucket",{["error"]:"client",["httpError"]:404},[],[]];C.registerError(iw,yf);var ow=[-3,"com.amazonaws.s3","NoSuchKey",{["error"]:"client",["httpError"]:404},[],[]];C.registerError(ow,$f);var ew=[-3,"com.amazonaws.s3","NoSuchUpload",{["error"]:"client",["httpError"]:404},[],[]];C.registerError(ew,hf);var aw=[-3,"com.amazonaws.s3","NotFound",{["error"]:"client"},[],[]];C.registerError(aw,Gf);var rw=[-3,"com.amazonaws.s3","ObjectAlreadyInActiveTierError",{["error"]:"client",["httpError"]:403},[],[]];C.registerError(rw,Rf);var c4=[-3,"com.amazonaws.s3","ObjectNotInActiveTierError",{["error"]:"client",["httpError"]:403},[],[]];C.registerError(c4,Sf);var x4=[-3,"com.amazonaws.s3","TooManyParts",{["error"]:"client",["httpError"]:400},[],[]];C.registerError(x4,Zf);var o1=[i1,C];var E1=[0,"com.amazonaws.s3","SessionCredentialValue",8,0],cn=[0,"com.amazonaws.s3","SSECustomerKey",8,0],jf=[0,"com.amazonaws.s3","SSEKMSEncryptionContext",8,0],Tc=[0,"com.amazonaws.s3","SSEKMSKeyId",8,0],e1=[0,"com.amazonaws.s3","StreamingBlob",{["streaming"]:1},42];var f4=[3,"com.amazonaws.s3","CommonPrefix",0,["Prefix"],[0]];var t4=[3,"com.amazonaws.s3","CreateSessionOutput",{["xmlName"]:"CreateSessionResult"},["Credentials","ServerSideEncryption","SSEKMSKeyId","SSEKMSEncryptionContext","BucketKeyEnabled"],[[()=>N4,{["xmlName"]:"Credentials"}],[0,{["httpHeader"]:"x-amz-server-side-encryption"}],[()=>Tc,{["httpHeader"]:"x-amz-server-side-encryption-aws-kms-key-id"}],[()=>jf,{["httpHeader"]:"x-amz-server-side-encryption-context"}],[2,{["httpHeader"]:"x-amz-server-side-encryption-bucket-key-enabled"}]],1],n4=[3,"com.amazonaws.s3","CreateSessionRequest",0,["Bucket","SessionMode","ServerSideEncryption","SSEKMSKeyId","SSEKMSEncryptionContext","BucketKeyEnabled"],[[0,1],[0,{["httpHeader"]:"x-amz-create-session-mode"}],[0,{["httpHeader"]:"x-amz-server-side-encryption"}],[()=>Tc,{["httpHeader"]:"x-amz-server-side-encryption-aws-kms-key-id"}],[()=>jf,{["httpHeader"]:"x-amz-server-side-encryption-context"}],[2,{["httpHeader"]:"x-amz-server-side-encryption-bucket-key-enabled"}]],1];var h4=[3,"com.amazonaws.s3","GetObjectOutput",0,["Body","DeleteMarker","AcceptRanges","Expiration","Restore","LastModified","ContentLength","ETag","ChecksumCRC32","ChecksumCRC32C","ChecksumCRC64NVME","ChecksumSHA1","ChecksumSHA256","ChecksumType","MissingMeta","VersionId","CacheControl","ContentDisposition","ContentEncoding","ContentLanguage","ContentRange","ContentType","Expires","ExpiresString","WebsiteRedirectLocation","ServerSideEncryption","Metadata","SSECustomerAlgorithm","SSECustomerKeyMD5","SSEKMSKeyId","BucketKeyEnabled","StorageClass","RequestCharged","ReplicationStatus","PartsCount","TagCount","ObjectLockMode","ObjectLockRetainUntilDate","ObjectLockLegalHoldStatus"],[[()=>e1,16],[2,{["httpHeader"]:"x-amz-delete-marker"}],[0,{["httpHeader"]:"accept-ranges"}],[0,{["httpHeader"]:"x-amz-expiration"}],[0,{["httpHeader"]:"x-amz-restore"}],[4,{["httpHeader"]:"Last-Modified"}],[1,{["httpHeader"]:"Content-Length"}],[0,{["httpHeader"]:"ETag"}],[0,{["httpHeader"]:"x-amz-checksum-crc32"}],[0,{["httpHeader"]:"x-amz-checksum-crc32c"}],[0,{["httpHeader"]:"x-amz-checksum-crc64nvme"}],[0,{["httpHeader"]:"x-amz-checksum-sha1"}],[0,{["httpHeader"]:"x-amz-checksum-sha256"}],[0,{["httpHeader"]:"x-amz-checksum-type"}],[1,{["httpHeader"]:"x-amz-missing-meta"}],[0,{["httpHeader"]:"x-amz-version-id"}],[0,{["httpHeader"]:"Cache-Control"}],[0,{["httpHeader"]:"Content-Disposition"}],[0,{["httpHeader"]:"Content-Encoding"}],[0,{["httpHeader"]:"Content-Language"}],[0,{["httpHeader"]:"Content-Range"}],[0,{["httpHeader"]:"Content-Type"}],[4,{["httpHeader"]:"Expires"}],[0,{["httpHeader"]:"ExpiresString"}],[0,{["httpHeader"]:"x-amz-website-redirect-location"}],[0,{["httpHeader"]:"x-amz-server-side-encryption"}],[128,{["httpPrefixHeaders"]:"x-amz-meta-"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-algorithm"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-key-MD5"}],[()=>Tc,{["httpHeader"]:"x-amz-server-side-encryption-aws-kms-key-id"}],[2,{["httpHeader"]:"x-amz-server-side-encryption-bucket-key-enabled"}],[0,{["httpHeader"]:"x-amz-storage-class"}],[0,{["httpHeader"]:"x-amz-request-charged"}],[0,{["httpHeader"]:"x-amz-replication-status"}],[1,{["httpHeader"]:"x-amz-mp-parts-count"}],[1,{["httpHeader"]:"x-amz-tagging-count"}],[0,{["httpHeader"]:"x-amz-object-lock-mode"}],[5,{["httpHeader"]:"x-amz-object-lock-retain-until-date"}],[0,{["httpHeader"]:"x-amz-object-lock-legal-hold"}]]],v4=[3,"com.amazonaws.s3","GetObjectRequest",0,["Bucket","Key","IfMatch","IfModifiedSince","IfNoneMatch","IfUnmodifiedSince","Range","ResponseCacheControl","ResponseContentDisposition","ResponseContentEncoding","ResponseContentLanguage","ResponseContentType","ResponseExpires","VersionId","SSECustomerAlgorithm","SSECustomerKey","SSECustomerKeyMD5","RequestPayer","PartNumber","ExpectedBucketOwner","ChecksumMode"],[[0,1],[0,1],[0,{["httpHeader"]:"If-Match"}],[4,{["httpHeader"]:"If-Modified-Since"}],[0,{["httpHeader"]:"If-None-Match"}],[4,{["httpHeader"]:"If-Unmodified-Since"}],[0,{["httpHeader"]:"Range"}],[0,{["httpQuery"]:"response-cache-control"}],[0,{["httpQuery"]:"response-content-disposition"}],[0,{["httpQuery"]:"response-content-encoding"}],[0,{["httpQuery"]:"response-content-language"}],[0,{["httpQuery"]:"response-content-type"}],[6,{["httpQuery"]:"response-expires"}],[0,{["httpQuery"]:"versionId"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-algorithm"}],[()=>cn,{["httpHeader"]:"x-amz-server-side-encryption-customer-key"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-key-MD5"}],[0,{["httpHeader"]:"x-amz-request-payer"}],[1,{["httpQuery"]:"partNumber"}],[0,{["httpHeader"]:"x-amz-expected-bucket-owner"}],[0,{["httpHeader"]:"x-amz-checksum-mode"}]],2];var S4=[3,"com.amazonaws.s3","HeadObjectOutput",0,["DeleteMarker","AcceptRanges","Expiration","Restore","ArchiveStatus","LastModified","ContentLength","ChecksumCRC32","ChecksumCRC32C","ChecksumCRC64NVME","ChecksumSHA1","ChecksumSHA256","ChecksumType","ETag","MissingMeta","VersionId","CacheControl","ContentDisposition","ContentEncoding","ContentLanguage","ContentType","ContentRange","Expires","ExpiresString","WebsiteRedirectLocation","ServerSideEncryption","Metadata","SSECustomerAlgorithm","SSECustomerKeyMD5","SSEKMSKeyId","BucketKeyEnabled","StorageClass","RequestCharged","ReplicationStatus","PartsCount","TagCount","ObjectLockMode","ObjectLockRetainUntilDate","ObjectLockLegalHoldStatus"],[[2,{["httpHeader"]:"x-amz-delete-marker"}],[0,{["httpHeader"]:"accept-ranges"}],[0,{["httpHeader"]:"x-amz-expiration"}],[0,{["httpHeader"]:"x-amz-restore"}],[0,{["httpHeader"]:"x-amz-archive-status"}],[4,{["httpHeader"]:"Last-Modified"}],[1,{["httpHeader"]:"Content-Length"}],[0,{["httpHeader"]:"x-amz-checksum-crc32"}],[0,{["httpHeader"]:"x-amz-checksum-crc32c"}],[0,{["httpHeader"]:"x-amz-checksum-crc64nvme"}],[0,{["httpHeader"]:"x-amz-checksum-sha1"}],[0,{["httpHeader"]:"x-amz-checksum-sha256"}],[0,{["httpHeader"]:"x-amz-checksum-type"}],[0,{["httpHeader"]:"ETag"}],[1,{["httpHeader"]:"x-amz-missing-meta"}],[0,{["httpHeader"]:"x-amz-version-id"}],[0,{["httpHeader"]:"Cache-Control"}],[0,{["httpHeader"]:"Content-Disposition"}],[0,{["httpHeader"]:"Content-Encoding"}],[0,{["httpHeader"]:"Content-Language"}],[0,{["httpHeader"]:"Content-Type"}],[0,{["httpHeader"]:"Content-Range"}],[4,{["httpHeader"]:"Expires"}],[0,{["httpHeader"]:"ExpiresString"}],[0,{["httpHeader"]:"x-amz-website-redirect-location"}],[0,{["httpHeader"]:"x-amz-server-side-encryption"}],[128,{["httpPrefixHeaders"]:"x-amz-meta-"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-algorithm"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-key-MD5"}],[()=>Tc,{["httpHeader"]:"x-amz-server-side-encryption-aws-kms-key-id"}],[2,{["httpHeader"]:"x-amz-server-side-encryption-bucket-key-enabled"}],[0,{["httpHeader"]:"x-amz-storage-class"}],[0,{["httpHeader"]:"x-amz-request-charged"}],[0,{["httpHeader"]:"x-amz-replication-status"}],[1,{["httpHeader"]:"x-amz-mp-parts-count"}],[1,{["httpHeader"]:"x-amz-tagging-count"}],[0,{["httpHeader"]:"x-amz-object-lock-mode"}],[5,{["httpHeader"]:"x-amz-object-lock-retain-until-date"}],[0,{["httpHeader"]:"x-amz-object-lock-legal-hold"}]]],w4=[3,"com.amazonaws.s3","HeadObjectRequest",0,["Bucket","Key","IfMatch","IfModifiedSince","IfNoneMatch","IfUnmodifiedSince","Range","ResponseCacheControl","ResponseContentDisposition","ResponseContentEncoding","ResponseContentLanguage","ResponseContentType","ResponseExpires","VersionId","SSECustomerAlgorithm","SSECustomerKey","SSECustomerKeyMD5","RequestPayer","PartNumber","ExpectedBucketOwner","ChecksumMode"],[[0,1],[0,1],[0,{["httpHeader"]:"If-Match"}],[4,{["httpHeader"]:"If-Modified-Since"}],[0,{["httpHeader"]:"If-None-Match"}],[4,{["httpHeader"]:"If-Unmodified-Since"}],[0,{["httpHeader"]:"Range"}],[0,{["httpQuery"]:"response-cache-control"}],[0,{["httpQuery"]:"response-content-disposition"}],[0,{["httpQuery"]:"response-content-encoding"}],[0,{["httpQuery"]:"response-content-language"}],[0,{["httpQuery"]:"response-content-type"}],[6,{["httpQuery"]:"response-expires"}],[0,{["httpQuery"]:"versionId"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-algorithm"}],[()=>cn,{["httpHeader"]:"x-amz-server-side-encryption-customer-key"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-key-MD5"}],[0,{["httpHeader"]:"x-amz-request-payer"}],[1,{["httpQuery"]:"partNumber"}],[0,{["httpHeader"]:"x-amz-expected-bucket-owner"}],[0,{["httpHeader"]:"x-amz-checksum-mode"}]],2];var b4=[3,"com.amazonaws.s3","ListObjectsV2Output",{["xmlName"]:"ListBucketResult"},["IsTruncated","Contents","Name","Prefix","Delimiter","MaxKeys","CommonPrefixes","EncodingType","KeyCount","ContinuationToken","NextContinuationToken","StartAfter","RequestCharged"],[2,[()=>W4,{["xmlFlattened"]:1}],0,0,0,1,[()=>Z4,{["xmlFlattened"]:1}],0,1,0,0,0,[0,{["httpHeader"]:"x-amz-request-charged"}]]],y4=[3,"com.amazonaws.s3","ListObjectsV2Request",0,["Bucket","Delimiter","EncodingType","MaxKeys","Prefix","ContinuationToken","FetchOwner","StartAfter","RequestPayer","ExpectedBucketOwner","OptionalObjectAttributes"],[[0,1],[0,{["httpQuery"]:"delimiter"}],[0,{["httpQuery"]:"encoding-type"}],[1,{["httpQuery"]:"max-keys"}],[0,{["httpQuery"]:"prefix"}],[0,{["httpQuery"]:"continuation-token"}],[2,{["httpQuery"]:"fetch-owner"}],[0,{["httpQuery"]:"start-after"}],[0,{["httpHeader"]:"x-amz-request-payer"}],[0,{["httpHeader"]:"x-amz-expected-bucket-owner"}],[64,{["httpHeader"]:"x-amz-optional-object-attributes"}]],1];var B4=[3,"com.amazonaws.s3","Object",0,["Key","LastModified","ETag","ChecksumAlgorithm","ChecksumType","Size","StorageClass","Owner","RestoreStatus"],[0,4,0,[64,{["xmlFlattened"]:1}],0,1,0,()=>$4,()=>z4]];var $4=[3,"com.amazonaws.s3","Owner",0,["DisplayName","ID"],[0,0]];var G4=[3,"com.amazonaws.s3","PutObjectOutput",0,["Expiration","ETag","ChecksumCRC32","ChecksumCRC32C","ChecksumCRC64NVME","ChecksumSHA1","ChecksumSHA256","ChecksumType","ServerSideEncryption","VersionId","SSECustomerAlgorithm","SSECustomerKeyMD5","SSEKMSKeyId","SSEKMSEncryptionContext","BucketKeyEnabled","Size","RequestCharged"],[[0,{["httpHeader"]:"x-amz-expiration"}],[0,{["httpHeader"]:"ETag"}],[0,{["httpHeader"]:"x-amz-checksum-crc32"}],[0,{["httpHeader"]:"x-amz-checksum-crc32c"}],[0,{["httpHeader"]:"x-amz-checksum-crc64nvme"}],[0,{["httpHeader"]:"x-amz-checksum-sha1"}],[0,{["httpHeader"]:"x-amz-checksum-sha256"}],[0,{["httpHeader"]:"x-amz-checksum-type"}],[0,{["httpHeader"]:"x-amz-server-side-encryption"}],[0,{["httpHeader"]:"x-amz-version-id"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-algorithm"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-key-MD5"}],[()=>Tc,{["httpHeader"]:"x-amz-server-side-encryption-aws-kms-key-id"}],[()=>jf,{["httpHeader"]:"x-amz-server-side-encryption-context"}],[2,{["httpHeader"]:"x-amz-server-side-encryption-bucket-key-enabled"}],[1,{["httpHeader"]:"x-amz-object-size"}],[0,{["httpHeader"]:"x-amz-request-charged"}]]],M4=[3,"com.amazonaws.s3","PutObjectRequest",0,["Bucket","Key","ACL","Body","CacheControl","ContentDisposition","ContentEncoding","ContentLanguage","ContentLength","ContentMD5","ContentType","ChecksumAlgorithm","ChecksumCRC32","ChecksumCRC32C","ChecksumCRC64NVME","ChecksumSHA1","ChecksumSHA256","Expires","IfMatch","IfNoneMatch","GrantFullControl","GrantRead","GrantReadACP","GrantWriteACP","WriteOffsetBytes","Metadata","ServerSideEncryption","StorageClass","WebsiteRedirectLocation","SSECustomerAlgorithm","SSECustomerKey","SSECustomerKeyMD5","SSEKMSKeyId","SSEKMSEncryptionContext","BucketKeyEnabled","RequestPayer","Tagging","ObjectLockMode","ObjectLockRetainUntilDate","ObjectLockLegalHoldStatus","ExpectedBucketOwner"],[[0,1],[0,1],[0,{["httpHeader"]:"x-amz-acl"}],[()=>e1,16],[0,{["httpHeader"]:"Cache-Control"}],[0,{["httpHeader"]:"Content-Disposition"}],[0,{["httpHeader"]:"Content-Encoding"}],[0,{["httpHeader"]:"Content-Language"}],[1,{["httpHeader"]:"Content-Length"}],[0,{["httpHeader"]:"Content-MD5"}],[0,{["httpHeader"]:"Content-Type"}],[0,{["httpHeader"]:"x-amz-sdk-checksum-algorithm"}],[0,{["httpHeader"]:"x-amz-checksum-crc32"}],[0,{["httpHeader"]:"x-amz-checksum-crc32c"}],[0,{["httpHeader"]:"x-amz-checksum-crc64nvme"}],[0,{["httpHeader"]:"x-amz-checksum-sha1"}],[0,{["httpHeader"]:"x-amz-checksum-sha256"}],[4,{["httpHeader"]:"Expires"}],[0,{["httpHeader"]:"If-Match"}],[0,{["httpHeader"]:"If-None-Match"}],[0,{["httpHeader"]:"x-amz-grant-full-control"}],[0,{["httpHeader"]:"x-amz-grant-read"}],[0,{["httpHeader"]:"x-amz-grant-read-acp"}],[0,{["httpHeader"]:"x-amz-grant-write-acp"}],[1,{["httpHeader"]:"x-amz-write-offset-bytes"}],[128,{["httpPrefixHeaders"]:"x-amz-meta-"}],[0,{["httpHeader"]:"x-amz-server-side-encryption"}],[0,{["httpHeader"]:"x-amz-storage-class"}],[0,{["httpHeader"]:"x-amz-website-redirect-location"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-algorithm"}],[()=>cn,{["httpHeader"]:"x-amz-server-side-encryption-customer-key"}],[0,{["httpHeader"]:"x-amz-server-side-encryption-customer-key-MD5"}],[()=>Tc,{["httpHeader"]:"x-amz-server-side-encryption-aws-kms-key-id"}],[()=>jf,{["httpHeader"]:"x-amz-server-side-encryption-context"}],[2,{["httpHeader"]:"x-amz-server-side-encryption-bucket-key-enabled"}],[0,{["httpHeader"]:"x-amz-request-payer"}],[0,{["httpHeader"]:"x-amz-tagging"}],[0,{["httpHeader"]:"x-amz-object-lock-mode"}],[5,{["httpHeader"]:"x-amz-object-lock-retain-until-date"}],[0,{["httpHeader"]:"x-amz-object-lock-legal-hold"}],[0,{["httpHeader"]:"x-amz-expected-bucket-owner"}]],2];var z4=[3,"com.amazonaws.s3","RestoreStatus",0,["IsRestoreInProgress","RestoreExpiryDate"],[2,4]];var N4=[3,"com.amazonaws.s3","SessionCredentials",0,["AccessKeyId","SecretAccessKey","SessionToken","Expiration"],[[0,{["xmlName"]:"AccessKeyId"}],[()=>E1,{["xmlName"]:"SecretAccessKey"}],[()=>E1,{["xmlName"]:"SessionToken"}],[4,{["xmlName"]:"Expiration"}]],4];var Z4=[1,"com.amazonaws.s3","CommonPrefixList",0,()=>f4];var W4=[1,"com.amazonaws.s3","ObjectList",0,[()=>B4,0]];var a1=[9,"com.amazonaws.s3","CreateSession",{["http"]:["GET","/?session",200]},()=>n4,()=>t4];var r1=[9,"com.amazonaws.s3","GetObject",{["httpChecksum"]:"-",["http"]:["GET","/{Key+}?x-id=GetObject",200]},()=>v4,()=>h4];var cS=[9,"com.amazonaws.s3","HeadObject",{["http"]:["HEAD","/{Key+}",200]},()=>w4,()=>S4];var xS=[9,"com.amazonaws.s3","ListObjectsV2",{["http"]:["GET","/?list-type=2",200]},()=>y4,()=>b4];var fS=[9,"com.amazonaws.s3","PutObject",{["httpChecksum"]:"-",["http"]:["PUT","/{Key+}?x-id=PutObject",200]},()=>M4,()=>G4];class xn extends nS.Command.classBuilder().ep({...tc,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m(function(c,x,f,t){return[tS.getEndpointPlugin(f,c.getEndpointParameterInstructions()),bc(f)]}).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").sc(a1).build(){}var hS={name:"@aws-sdk/client-s3",description:"AWS SDK for JavaScript S3 Client for Node.js, Browser and React Native",version:"3.1015.0",scripts:{build:"concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs","build:cjs":"node ../../scripts/compilation/inline client-s3","build:es":"tsc -p tsconfig.es.json","build:include:deps":'yarn g:turbo run build -F="$npm_package_name"',"build:types":"tsc -p tsconfig.types.json","build:types:downlevel":"downlevel-dts dist-types dist-types/ts3.4",clean:"premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo","extract:docs":"api-extractor run --local","generate:client":"node ../../scripts/generate-clients/single-service --solo s3",test:"yarn g:vitest run","test:browser":"node ./test/browser-build/esbuild && yarn g:vitest run -c vitest.config.browser.mts","test:browser:watch":"node ./test/browser-build/esbuild && yarn g:vitest watch -c vitest.config.browser.mts","test:e2e":"yarn g:vitest run -c vitest.config.e2e.mts && yarn test:browser","test:e2e:watch":"yarn g:vitest watch -c vitest.config.e2e.mts","test:index":"tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs","test:integration":"yarn g:vitest run -c vitest.config.integ.mts","test:integration:watch":"yarn g:vitest watch -c vitest.config.integ.mts","test:watch":"yarn g:vitest watch"},main:"./dist-cjs/index.js",types:"./dist-types/index.d.ts",module:"./dist-es/index.js",sideEffects:!1,dependencies:{"@aws-crypto/sha1-browser":"5.2.0","@aws-crypto/sha256-browser":"5.2.0","@aws-crypto/sha256-js":"5.2.0","@aws-sdk/core":"^3.973.24","@aws-sdk/credential-provider-node":"^3.972.25","@aws-sdk/middleware-bucket-endpoint":"^3.972.8","@aws-sdk/middleware-expect-continue":"^3.972.8","@aws-sdk/middleware-flexible-checksums":"^3.974.4","@aws-sdk/middleware-host-header":"^3.972.8","@aws-sdk/middleware-location-constraint":"^3.972.8","@aws-sdk/middleware-logger":"^3.972.8","@aws-sdk/middleware-recursion-detection":"^3.972.8","@aws-sdk/middleware-sdk-s3":"^3.972.24","@aws-sdk/middleware-ssec":"^3.972.8","@aws-sdk/middleware-user-agent":"^3.972.25","@aws-sdk/region-config-resolver":"^3.972.9","@aws-sdk/signature-v4-multi-region":"^3.996.12","@aws-sdk/types":"^3.973.6","@aws-sdk/util-endpoints":"^3.996.5","@aws-sdk/util-user-agent-browser":"^3.972.8","@aws-sdk/util-user-agent-node":"^3.973.11","@smithy/config-resolver":"^4.4.13","@smithy/core":"^3.23.12","@smithy/eventstream-serde-browser":"^4.2.12","@smithy/eventstream-serde-config-resolver":"^4.3.12","@smithy/eventstream-serde-node":"^4.2.12","@smithy/fetch-http-handler":"^5.3.15","@smithy/hash-blob-browser":"^4.2.13","@smithy/hash-node":"^4.2.12","@smithy/hash-stream-node":"^4.2.12","@smithy/invalid-dependency":"^4.2.12","@smithy/md5-js":"^4.2.12","@smithy/middleware-content-length":"^4.2.12","@smithy/middleware-endpoint":"^4.4.27","@smithy/middleware-retry":"^4.4.44","@smithy/middleware-serde":"^4.2.15","@smithy/middleware-stack":"^4.2.12","@smithy/node-config-provider":"^4.3.12","@smithy/node-http-handler":"^4.5.0","@smithy/protocol-http":"^5.3.12","@smithy/smithy-client":"^4.12.7","@smithy/types":"^4.13.1","@smithy/url-parser":"^4.2.12","@smithy/util-base64":"^4.3.2","@smithy/util-body-length-browser":"^4.2.2","@smithy/util-body-length-node":"^4.2.3","@smithy/util-defaults-mode-browser":"^4.3.43","@smithy/util-defaults-mode-node":"^4.2.47","@smithy/util-endpoints":"^3.3.3","@smithy/util-middleware":"^4.2.12","@smithy/util-retry":"^4.2.12","@smithy/util-stream":"^4.5.20","@smithy/util-utf8":"^4.2.2","@smithy/util-waiter":"^4.2.13",tslib:"^2.6.2"},devDependencies:{"@aws-sdk/signature-v4-crt":"3.1015.0","@smithy/snapshot-testing":"^2.0.3","@tsconfig/node20":"20.1.8","@types/node":"^20.14.8",concurrently:"7.0.0","downlevel-dts":"0.10.1",premove:"4.0.0",typescript:"~5.8.3",vitest:"^4.0.17"},engines:{node:">=20.0.0"},typesVersions:{"<4.5":{"dist-types/*":["dist-types/ts3.4/*"]}},files:["dist-*/**"],author:{name:"AWS SDK for JavaScript Team",url:"https://aws.amazon.com/javascript/"},license:"Apache-2.0",browser:{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.browser"},"react-native":{"./dist-es/runtimeConfig":"./dist-es/runtimeConfig.native"},homepage:"https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-s3",repository:{type:"git",url:"https://github.com/aws/aws-sdk-js-v3.git",directory:"clients/client-s3"}};var pc=y(sc(),1);var Of=y(SS(),1),MS=y(K4(),1);var Kf=y(SS(),1),vS="AWS_EC2_METADATA_DISABLED",wS=async(c)=>{let{ENV_CMDS_FULL_URI:x,ENV_CMDS_RELATIVE_URI:f,fromContainerMetadata:t,fromInstanceMetadata:n}=await import("../chunk-jdgvdddd.js");if(process.env[f]||process.env[x]){c.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata");let{fromHttp:h}=await import("../chunk-c22vcxty.js");return Kf.chain(h(c),t(c))}if(process.env[vS]&&process.env[vS]!=="false")return async()=>{throw new Kf.CredentialsProviderError("EC2 Instance Metadata Service access disabled",{logger:c.logger})};return c.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"),n(c)};function bS(c,x){let f=j4(c),t,n,h,v=async(S)=>{if(S?.forceRefresh)return await f(S);if(h?.expiration){if(h?.expiration?.getTime()<Date.now())h=void 0}if(t)await t;else if(!h||x?.(h))if(h){if(!n)n=f(S).then((w)=>{h=w}).finally(()=>{n=void 0})}else return t=f(S).then((w)=>{h=w}).finally(()=>{t=void 0}),v(S);return h};return v}var j4=(c)=>async(x)=>{let f;for(let t of c)try{return await t(x)}catch(n){if(f=n,n?.tryNextLink)continue;throw n}throw f};var yS=!1,zS=(c={})=>bS([async()=>{if(c.profile??process.env[MS.ENV_PROFILE]){if(process.env[BS]&&process.env[$S]){if(!yS)(c.logger?.warn&&c.logger?.constructor?.name!=="NoOpLogger"?c.logger.warn.bind(c.logger):console.warn)(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING:
4
- Multiple credential sources detected:
5
- Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set.
6
- This SDK will proceed with the AWS_PROFILE value.
7
-
8
- However, a future version may change this behavior to prefer the ENV static credentials.
9
- Please ensure that your environment only sets either the AWS_PROFILE or the
10
- AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair.
11
- `),yS=!0}throw new Of.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.",{logger:c.logger,tryNextLink:!0})}return c.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"),GS(c)()},async(x)=>{c.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO");let{ssoStartUrl:f,ssoAccountId:t,ssoRegion:n,ssoRoleName:h,ssoSession:v}=c;if(!f&&!t&&!n&&!h&&!v)throw new Of.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).",{logger:c.logger});let{fromSSO:S}=await import("../chunk-dxw8k6f1.js");return S(c)(x)},async(x)=>{c.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni");let{fromIni:f}=await import("../chunk-s6e7cvek.js");return f(c)(x)},async(x)=>{c.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess");let{fromProcess:f}=await import("../chunk-hrrmxreg.js");return f(c)(x)},async(x)=>{c.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile");let{fromTokenFile:f}=await import("../chunk-c0wcsmpj.js");return f(c)(x)},async()=>{return c.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"),(await wS(c))()},async()=>{throw new Of.CredentialsProviderError("Could not load credentials from any providers",{tryNextLink:!1,logger:c.logger})}],O4);var O4=(c)=>c?.expiration!==void 0&&c.expiration.getTime()-Date.now()<300000;var _c=y(vv(),1),D4="AWS_S3_USE_ARN_REGION",J4="s3_use_arn_region",NS={environmentVariableSelector:(c)=>_c.booleanSelector(c,D4,_c.SelectorType.ENV),configFileSelector:(c)=>_c.booleanSelector(c,J4,_c.SelectorType.CONFIG),default:void 0};var Xf=y(q4(),1),Gc=y(sS(),1);var Bc=y(WS(),1);var RS=y(WS(),1);class qc{bytes;constructor(c){if(this.bytes=c,c.byteLength!==8)throw Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(c){if(c>9223372036854776000||c<-9223372036854776000)throw Error(`${c} is too large (or, if negative, too small) to represent as an Int64`);let x=new Uint8Array(8);for(let f=7,t=Math.abs(Math.round(c));f>-1&&t>0;f--,t/=256)x[f]=t;if(c<0)ZS(x);return new qc(x)}valueOf(){let c=this.bytes.slice(0),x=c[0]&128;if(x)ZS(c);return parseInt(RS.toHex(c),16)*(x?-1:1)}toString(){return String(this.valueOf())}}function ZS(c){for(let x=0;x<8;x++)c[x]^=255;for(let x=7;x>-1;x--)if(c[x]++,c[x]!==0)break}class fn{toUtf8;fromUtf8;constructor(c,x){this.toUtf8=c,this.fromUtf8=x}format(c){let x=[];for(let n of Object.keys(c)){let h=this.fromUtf8(n);x.push(Uint8Array.from([h.byteLength]),h,this.formatHeaderValue(c[n]))}let f=new Uint8Array(x.reduce((n,h)=>n+h.byteLength,0)),t=0;for(let n of x)f.set(n,t),t+=n.byteLength;return f}formatHeaderValue(c){switch(c.type){case"boolean":return Uint8Array.from([c.value?0:1]);case"byte":return Uint8Array.from([2,c.value]);case"short":let x=new DataView(new ArrayBuffer(3));return x.setUint8(0,3),x.setInt16(1,c.value,!1),new Uint8Array(x.buffer);case"integer":let f=new DataView(new ArrayBuffer(5));return f.setUint8(0,4),f.setInt32(1,c.value,!1),new Uint8Array(f.buffer);case"long":let t=new Uint8Array(9);return t[0]=5,t.set(c.value.bytes,1),t;case"binary":let n=new DataView(new ArrayBuffer(3+c.value.byteLength));n.setUint8(0,6),n.setUint16(1,c.value.byteLength,!1);let h=new Uint8Array(n.buffer);return h.set(c.value,3),h;case"string":let v=this.fromUtf8(c.value),S=new DataView(new ArrayBuffer(3+v.byteLength));S.setUint8(0,7),S.setUint16(1,v.byteLength,!1);let w=new Uint8Array(S.buffer);return w.set(v,3),w;case"timestamp":let b=new Uint8Array(9);return b[0]=8,b.set(qc.fromNumber(c.value.valueOf()).bytes,1),b;case"uuid":if(!L4.test(c.value))throw Error(`Invalid UUID received: ${c.value}`);let B=new Uint8Array(17);return B[0]=9,B.set(Bc.fromHex(c.value.replace(/\-/g,"")),1),B}}parse(c){let x={},f=0;while(f<c.byteLength){let t=c.getUint8(f++),n=this.toUtf8(new Uint8Array(c.buffer,c.byteOffset+f,t));switch(f+=t,c.getUint8(f++)){case 0:x[n]={type:KS,value:!0};break;case 1:x[n]={type:KS,value:!1};break;case 2:x[n]={type:Q4,value:c.getInt8(f++)};break;case 3:x[n]={type:k4,value:c.getInt16(f,!1)},f+=2;break;case 4:x[n]={type:Y4,value:c.getInt32(f,!1)},f+=4;break;case 5:x[n]={type:X4,value:new qc(new Uint8Array(c.buffer,c.byteOffset+f,8))},f+=8;break;case 6:let h=c.getUint16(f,!1);f+=2,x[n]={type:U4,value:new Uint8Array(c.buffer,c.byteOffset+f,h)},f+=h;break;case 7:let v=c.getUint16(f,!1);f+=2,x[n]={type:H4,value:this.toUtf8(new Uint8Array(c.buffer,c.byteOffset+f,v))},f+=v;break;case 8:x[n]={type:F4,value:new Date(new qc(new Uint8Array(c.buffer,c.byteOffset+f,8)).valueOf())},f+=8;break;case 9:let S=new Uint8Array(c.buffer,c.byteOffset+f,16);f+=16,x[n]={type:u4,value:`${Bc.toHex(S.subarray(0,4))}-${Bc.toHex(S.subarray(4,6))}-${Bc.toHex(S.subarray(6,8))}-${Bc.toHex(S.subarray(8,10))}-${Bc.toHex(S.subarray(10))}`};break;default:throw Error("Unrecognized header type tag")}}return x}}var jS;(function(c){c[c.boolTrue=0]="boolTrue",c[c.boolFalse=1]="boolFalse",c[c.byte=2]="byte",c[c.short=3]="short",c[c.integer=4]="integer",c[c.long=5]="long",c[c.byteArray=6]="byteArray",c[c.string=7]="string",c[c.timestamp=8]="timestamp",c[c.uuid=9]="uuid"})(jS||(jS={}));var KS="boolean",Q4="byte",k4="short",Y4="integer",X4="long",U4="binary",H4="string",F4="timestamp",u4="uuid",L4=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;var OS=4,$c=OS*2,Xc=4,s4=$c+Xc*2;function DS({byteLength:c,byteOffset:x,buffer:f}){if(c<s4)throw Error("Provided message too short to accommodate event stream message overhead");let t=new DataView(f,x,c),n=t.getUint32(0,!1);if(c!==n)throw Error("Reported message length does not match received message length");let h=t.getUint32(OS,!1),v=t.getUint32($c,!1),S=t.getUint32(c-Xc,!1),w=new Qc().update(new Uint8Array(f,x,$c));if(v!==w.digest())throw Error(`The prelude checksum specified in the message (${v}) does not match the calculated CRC32 checksum (${w.digest()})`);if(w.update(new Uint8Array(f,x+$c,c-($c+Xc))),S!==w.digest())throw Error(`The message checksum (${w.digest()}) did not match the expected value of ${S}`);return{headers:new DataView(f,x+$c+Xc,h),body:new Uint8Array(f,x+$c+Xc+h,n-h-($c+Xc+Xc))}}class tn{headerMarshaller;messageBuffer;isEndOfStream;constructor(c,x){this.headerMarshaller=new fn(c,x),this.messageBuffer=[],this.isEndOfStream=!1}feed(c){this.messageBuffer.push(this.decode(c))}endOfStream(){this.isEndOfStream=!0}getMessage(){let c=this.messageBuffer.pop(),x=this.isEndOfStream;return{getMessage(){return c},isEndOfStream(){return x}}}getAvailableMessages(){let c=this.messageBuffer;this.messageBuffer=[];let x=this.isEndOfStream;return{getMessages(){return c},isEndOfStream(){return x}}}encode({headers:c,body:x}){let f=this.headerMarshaller.format(c),t=f.byteLength+x.byteLength+16,n=new Uint8Array(t),h=new DataView(n.buffer,n.byteOffset,n.byteLength),v=new Qc;return h.setUint32(0,t,!1),h.setUint32(4,f.byteLength,!1),h.setUint32(8,v.update(n.subarray(0,8)).digest(),!1),n.set(f,12),n.set(x,f.byteLength+12),h.setUint32(t-4,v.update(n.subarray(8,t-4)).digest(),!1),n}decode(c){let{headers:x,body:f}=DS(c);return{headers:this.headerMarshaller.parse(x),body:f}}formatHeaders(c){return this.headerMarshaller.format(c)}}class nn{options;constructor(c){this.options=c}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let c of this.options.inputStream)yield this.options.decoder.decode(c)}}class hn{options;constructor(c){this.options=c}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let c of this.options.messageStream)yield this.options.encoder.encode(c);if(this.options.includeEndFrame)yield new Uint8Array(0)}}class vn{options;constructor(c){this.options=c}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let c of this.options.messageStream){let x=await this.options.deserializer(c);if(x===void 0)continue;yield x}}}class Sn{options;constructor(c){this.options=c}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let c of this.options.inputStream)yield this.options.serializer(c)}}function JS(c){let x=0,f=0,t=null,n=null,h=(S)=>{if(typeof S!=="number")throw Error("Attempted to allocate an event message where size was not a number: "+S);x=S,f=4,t=new Uint8Array(S),new DataView(t.buffer).setUint32(0,S,!1)},v=async function*(){let S=c[Symbol.asyncIterator]();while(!0){let{value:w,done:b}=await S.next();if(b){if(!x)return;else if(x===f)yield t;else throw Error("Truncated event message received.");return}let B=w.length,$=0;while($<B){if(!t){let j=B-$;if(!n)n=new Uint8Array(4);let I=Math.min(4-f,j);if(n.set(w.slice($,$+I),f),f+=I,$+=I,f<4)break;h(new DataView(n.buffer).getUint32(0,!1)),n=null}let N=Math.min(x-f,B-$);if(t.set(w.slice($,$+N),f),f+=N,$+=N,x&&x===f)yield t,t=null,x=0,f=0}}};return{[Symbol.asyncIterator]:v}}function QS(c,x){return async function(f){let{value:t}=f.headers[":message-type"];if(t==="error"){let n=Error(f.headers[":error-message"].value||"UnknownError");throw n.name=f.headers[":error-code"].value,n}else if(t==="exception"){let n=f.headers[":exception-type"].value,h={[n]:f},v=await c(h);if(v.$unknown){let S=Error(x(f.body));throw S.name=n,S}throw v[n]}else if(t==="event"){let n={[f.headers[":event-type"].value]:f},h=await c(n);if(h.$unknown)return;return h}else throw Error(`Unrecognizable event type: ${f.headers[":event-type"].value}`)}}class wn{eventStreamCodec;utfEncoder;constructor({utf8Encoder:c,utf8Decoder:x}){this.eventStreamCodec=new tn(c,x),this.utfEncoder=c}deserialize(c,x){let f=JS(c);return new vn({messageStream:new nn({inputStream:f,decoder:this.eventStreamCodec}),deserializer:QS(x,this.utfEncoder)})}serialize(c,x){return new hn({messageStream:new Sn({inputStream:c,serializer:x}),encoder:this.eventStreamCodec,includeEndFrame:!0})}}import{Readable as A4}from"stream";async function*kS(c){let x=!1,f=!1,t=[];c.on("error",(n)=>{if(!x)x=!0;if(n)throw n}),c.on("data",(n)=>{t.push(n)}),c.on("end",()=>{x=!0});while(!f){let n=await new Promise((h)=>setTimeout(()=>h(t.shift()),0));if(n)yield n;f=x&&t.length===0}}class bn{universalMarshaller;constructor({utf8Encoder:c,utf8Decoder:x}){this.universalMarshaller=new wn({utf8Decoder:x,utf8Encoder:c})}deserialize(c,x){let f=typeof c[Symbol.asyncIterator]==="function"?c:kS(c);return this.universalMarshaller.deserialize(f,x)}serialize(c,x){return A4.from(this.universalMarshaller.serialize(c,x))}}var YS=(c)=>new bn(c);var Yf=y(p4(),1);var XS=y(Kt(),1);import{Writable as I4}from"stream";class yn extends I4{hash;constructor(c,x){super(x);this.hash=c}_write(c,x,f){try{this.hash.update(XS.toUint8Array(c))}catch(t){return f(t)}f()}}var US=(c,x)=>{if(x.readableFlowing!==null)throw Error("Unable to calculate hash for flowing readable stream");let f=new c,t=new yn(f);return x.pipe(t),new Promise((n,h)=>{x.on("error",(v)=>{t.end(),h(v)}),t.on("error",h),t.on("finish",()=>{f.digest().then(n).catch(h)})})};var Uf=y(AS(),1),q=y(_4(),1),Hf=y(m4(),1),Ff=y(E(),1),IS=y(V4(),1),gS=y(l4(),1),CS=y(T4(),1);var Df=y(sc(),1),HS=y(P4(),1);var FS=y(E(),1),uS=y(C4(),1),Jf=y(g4(),1),Qf=y(Vx(),1),kf=y(Kt(),1);var LS=(c)=>{return{apiVersion:"2006-03-01",base64Decoder:c?.base64Decoder??Jf.fromBase64,base64Encoder:c?.base64Encoder??Jf.toBase64,disableHostPrefix:c?.disableHostPrefix??!1,endpointProvider:c?.endpointProvider??tf,extensions:c?.extensions??[],getAwsChunkedEncodingStream:c?.getAwsChunkedEncodingStream??Qf.getAwsChunkedEncodingStream,httpAuthSchemeProvider:c?.httpAuthSchemeProvider??q1,httpAuthSchemes:c?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:(x)=>x.getIdentityProvider("aws.auth#sigv4"),signer:new Df.AwsSdkSigV4Signer},{schemeId:"aws.auth#sigv4a",identityProvider:(x)=>x.getIdentityProvider("aws.auth#sigv4a"),signer:new Df.AwsSdkSigV4ASigner}],logger:c?.logger??new FS.NoOpLogger,protocol:c?.protocol??HS.AwsRestXmlProtocol,protocolSettings:c?.protocolSettings??{defaultNamespace:"com.amazonaws.s3",errorTypeRegistries:o1,xmlNamespace:"http://s3.amazonaws.com/doc/2006-03-01/",version:"2006-03-01",serviceTarget:"AmazonS3"},sdkStreamMixin:c?.sdkStreamMixin??Qf.sdkStreamMixin,serviceId:c?.serviceId??"S3",signerConstructor:c?.signerConstructor??Wx,signingEscapePath:c?.signingEscapePath??!1,urlParser:c?.urlParser??uS.parseUrl,useArnRegion:c?.useArnRegion??void 0,utf8Decoder:c?.utf8Decoder??kf.fromUtf8,utf8Encoder:c?.utf8Encoder??kf.toUtf8}};var PS=(c)=>{Ff.emitWarningIfUnsupportedVersion(process.version);let x=gS.resolveDefaultsModeConfig(c),f=()=>x().then(Ff.loadConfigsForDefaultMode),t=LS(c);pc.emitWarningIfUnsupportedVersion(process.version);let n={profile:c?.profile,logger:t.logger};return{...t,...c,runtime:"node",defaultsMode:x,authSchemePreference:c?.authSchemePreference??q.loadConfig(pc.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS,n),bodyLengthChecker:c?.bodyLengthChecker??IS.calculateBodyLength,credentialDefaultProvider:c?.credentialDefaultProvider??zS,defaultUserAgentProvider:c?.defaultUserAgentProvider??Xf.createDefaultUserAgentProvider({serviceId:t.serviceId,clientVersion:hS.version}),disableS3ExpressSessionAuth:c?.disableS3ExpressSessionAuth??q.loadConfig(Jt,n),eventStreamSerdeProvider:c?.eventStreamSerdeProvider??YS,maxAttempts:c?.maxAttempts??q.loadConfig(Uf.NODE_MAX_ATTEMPT_CONFIG_OPTIONS,c),md5:c?.md5??Yf.Hash.bind(null,"md5"),region:c?.region??q.loadConfig(Gc.NODE_REGION_CONFIG_OPTIONS,{...Gc.NODE_REGION_CONFIG_FILE_OPTIONS,...n}),requestChecksumCalculation:c?.requestChecksumCalculation??q.loadConfig(Qh,n),requestHandler:Hf.NodeHttpHandler.create(c?.requestHandler??f),responseChecksumValidation:c?.responseChecksumValidation??q.loadConfig(kh,n),retryMode:c?.retryMode??q.loadConfig({...Uf.NODE_RETRY_MODE_CONFIG_OPTIONS,default:async()=>(await f()).retryMode||CS.DEFAULT_RETRY_MODE},c),sha1:c?.sha1??Yf.Hash.bind(null,"sha1"),sha256:c?.sha256??Yf.Hash.bind(null,"sha256"),sigv4aSigningRegionSet:c?.sigv4aSigningRegionSet??q.loadConfig(pc.NODE_SIGV4A_CONFIG_OPTIONS,n),streamCollector:c?.streamCollector??Hf.streamCollector,streamHasher:c?.streamHasher??US,useArnRegion:c?.useArnRegion??q.loadConfig(NS,n),useDualstackEndpoint:c?.useDualstackEndpoint??q.loadConfig(Gc.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS,n),useFipsEndpoint:c?.useFipsEndpoint??q.loadConfig(Gc.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS,n),userAgentAppId:c?.userAgentAppId??q.loadConfig(Xf.NODE_APP_ID_CONFIG_OPTIONS,n)}};var uf=y(E4(),1),Lf=y(hc(),1),sf=y(E(),1);var mS=(c)=>{let{httpAuthSchemes:x,httpAuthSchemeProvider:f,credentials:t}=c;return{setHttpAuthScheme(n){let h=x.findIndex((v)=>v.schemeId===n.schemeId);if(h===-1)x.push(n);else x.splice(h,1,n)},httpAuthSchemes(){return x},setHttpAuthSchemeProvider(n){f=n},httpAuthSchemeProvider(){return f},setCredentials(n){t=n},credentials(){return t}}},TS=(c)=>{return{httpAuthSchemes:c.httpAuthSchemes(),httpAuthSchemeProvider:c.httpAuthSchemeProvider(),credentials:c.credentials()}};var _S=(c,x)=>{let f=Object.assign(uf.getAwsRegionExtensionConfiguration(c),sf.getDefaultExtensionConfiguration(c),Lf.getHttpHandlerExtensionConfiguration(c),mS(c));return x.forEach((t)=>t.configure(f)),Object.assign(c,uf.resolveAwsRegionExtensionConfiguration(f),sf.resolveDefaultRuntimeConfig(f),Lf.resolveHttpHandlerRuntimeConfig(f),TS(f))};class Bn extends iS.Client{config;constructor(...[c]){let x=PS(c||{});super(x);this.initConfig=x;let f=V1(x),t=If.resolveUserAgentConfig(f),n=eh(t),h=gf.resolveRetryConfig(n),v=VS.resolveRegionConfig(h),S=Af.resolveHostHeaderConfig(v),w=dS.resolveEndpointConfig(S),b=Hv(w),B=p1(b),$=Jv(B,{session:[()=>this,xn]}),N=_S($,c?.extensions||[]);this.config=N,this.middlewareStack.use(lS.getSchemaSerdePlugin(this.config)),this.middlewareStack.use(If.getUserAgentPlugin(this.config)),this.middlewareStack.use(gf.getRetryPlugin(this.config)),this.middlewareStack.use(ES.getContentLengthPlugin(this.config)),this.middlewareStack.use(Af.getHostHeaderPlugin(this.config)),this.middlewareStack.use(qS.getLoggerPlugin(this.config)),this.middlewareStack.use(pS.getRecursionDetectionPlugin(this.config)),this.middlewareStack.use(Vc.getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:m1,identityProviderConfigProvider:async(j)=>new Vc.DefaultIdentityProviderConfig({"aws.auth#sigv4":j.credentials,"aws.auth#sigv4a":j.credentials})})),this.middlewareStack.use(Vc.getHttpSigningPlugin(this.config)),this.middlewareStack.use(Uv(this.config)),this.middlewareStack.use(Dh(this.config)),this.middlewareStack.use(tv(this.config)),this.middlewareStack.use(Qt(this.config)),this.middlewareStack.use(kt(this.config))}destroy(){super.destroy()}}function r4(c){return(x)=>async(f)=>{let t={...f.input},n=[{target:"SSECustomerKey",hash:"SSECustomerKeyMD5"},{target:"CopySourceSSECustomerKey",hash:"CopySourceSSECustomerKeyMD5"}];for(let h of n){let v=t[h.target];if(v){let S;if(typeof v==="string")if(xb(v,c))S=c.base64Decoder(v);else S=c.utf8Decoder(v),t[h.target]=c.base64Encoder(S);else S=ArrayBuffer.isView(v)?new Uint8Array(v.buffer,v.byteOffset,v.byteLength):new Uint8Array(v),t[h.target]=c.base64Encoder(S);let w=new c.md5;w.update(S),t[h.hash]=c.base64Encoder(await w.digest())}}return x({...f,input:t})}}var cb={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0},lc=(c)=>({applyToStack:(x)=>{x.add(r4(c),cb)}});function xb(c,x){if(!/^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(c))return!1;try{return x.base64Decoder(c).length===32}catch{return!1}}var oS=y(kc(),1),eS=y(E(),1);class Cf extends eS.Command.classBuilder().ep({...tc,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(c,x,f,t){return[oS.getEndpointPlugin(f,c.getEndpointParameterInstructions()),Ex(f,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC64NVME","CRC32","CRC32C","SHA256","SHA1"]}),lc(f),dx(f)]}).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").sc(r1).build(){}var aS=y(kc(),1),rS=y(E(),1);class $n extends rS.Command.classBuilder().ep({...tc,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(c,x,f,t){return[aS.getEndpointPlugin(f,c.getEndpointParameterInstructions()),bc(f),lc(f),dx(f)]}).s("AmazonS3","HeadObject",{}).n("S3Client","HeadObjectCommand").sc(cS).build(){}var c0=y(kc(),1),x0=y(E(),1);class Gn extends x0.Command.classBuilder().ep({...tc,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m(function(c,x,f,t){return[c0.getEndpointPlugin(f,c.getEndpointParameterInstructions()),bc(f)]}).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").sc(xS).build(){}var f0=y(kc(),1),t0=y(E(),1);class Mn extends t0.Command.classBuilder().ep({...tc,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m(function(c,x,f,t){return[f0.getEndpointPlugin(f,c.getEndpointParameterInstructions()),Ex(f,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),cv(f),bc(f),lc(f)]}).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").sc(fS).build(){}import{Buffer as n0}from"buffer";class h0 extends kx{client;constructor(...c){super();this.client=new Bn(...c)}async put(c){let x,f,t,n=process.env.BUCKET_NAME;if(c instanceof Blob)x=c,t=`${Bun.randomUUIDv7()}.${c.type.split("/")[1].split(";")[0]}`,f=c.type;else x=c.body,t=c.name,n=c.bucket??n,f=c.contentType||(x instanceof Blob||x instanceof File?x.type:void 0);f=f||void 0;let h=x instanceof n0?x:x instanceof Blob||x instanceof File?n0.from(await x.arrayBuffer()):"";return await this.client.send(new Mn({Bucket:n,Key:t,Body:h,ContentType:f})),t}async list(c){return await this.client.send(new Gn({Bucket:process.env.BUCKET_NAME,Prefix:c}))}async fetch(c){let x=process.env.BUCKET_NAME,f;if(typeof c==="string")f=c;else x=c.bucket??x,f=c.name;if(!f)throw Error("Object name has to be specified");let t=await this.client.send(new Cf({Bucket:x,Key:f}));return new Response(t.Body.transformToWebStream(),{headers:{"Content-Type":t.ContentType,"Content-Length":t.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":t.LastModified?.toUTCString()||"",ETag:t.ETag||""}})}async read(c){let x=typeof c==="string"?{name:c}:c,f=x.bucket??process.env.BUCKET_NAME,{name:t,range:n=null}=x;if(!t)throw Error("Object name has to be specified");let h;try{h=await this.client.send(new Cf({Bucket:f,Key:t,Range:n?zn(n):void 0}))}catch(b){if(b?.name==="InvalidRange"||b?.$metadata?.httpStatusCode===416)throw new Ec(await this.size({name:t,bucket:f}));if(b?.name==="NoSuchKey"||b?.$metadata?.httpStatusCode===404)throw new Mc(t);throw b}let v=Qx(h.ContentRange),S=Boolean(v)&&h.$metadata?.httpStatusCode===206,w=v?.total??h.ContentLength??0;return{body:h.Body.transformToWebStream(),start:v?.start??0,end:v?.end??w-1,total:w,partial:S,type:h.ContentType??"application/octet-stream",etag:h.ETag||void 0,lastModified:h.LastModified,name:t}}async size(c){let x=typeof c==="string"?c:c.name,f=(typeof c==="string"?void 0:c.bucket)??process.env.BUCKET_NAME;try{return(await this.client.send(new $n({Bucket:f,Key:x}))).ContentLength??0}catch(t){if(t?.name==="NotFound"||t?.$metadata?.httpStatusCode===404)throw new Mc(x);throw t}}}import{Buffer as v0}from"buffer";import{Readable as fb}from"stream";function Nn(c){return c?.statusCode===404||c?.details?.errorCode==="BlobNotFound"||c?.code==="BlobNotFound"}function tb(c){return c?.statusCode===416||c?.details?.errorCode==="InvalidRange"||c?.code==="InvalidRange"}class S0 extends kx{config;serviceClientPromise=null;constructor(c={}){super();this.config=c}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let c;try{c=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 x=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new c.BlobServiceClient(this.config.url,this.config.credential);if(x)return c.BlobServiceClient.fromConnectionString(x);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(c,x){if(!c)throw Error("Object name has to be specified");let f=x??this.config.container??process.env.BUCKET_NAME;if(!f)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient(f).getBlockBlobClient(c)}async put(c){let x,f,t,n;if(c instanceof Blob)x=c,t=`${Bun.randomUUIDv7()}.${c.type.split("/")[1].split(";")[0]}`,f=c.type;else x=c.body,t=c.name,n=c.bucket,f=c.contentType??(x instanceof Blob||x instanceof File?x.type:void 0);let h=x instanceof v0?x:v0.from(await x.arrayBuffer());return await(await this.blob(t,n)).uploadData(h,{blobHTTPHeaders:f?{blobContentType:f}:void 0}),t}async list(c){let x=this.config.container??process.env.BUCKET_NAME,t=(await this.serviceClient()).getContainerClient(x),n=[];for await(let h of t.listBlobsFlat({prefix:c}))n.push(h.name);return n}async fetch(c){let x=await this.read(typeof c==="string"?{name:c}:{name:c.name,bucket:c.bucket});return new Response(x.body,{headers:{"Content-Type":x.type,"Content-Length":String(x.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":x.lastModified?.toUTCString()??"",ETag:x.etag??""}})}async read(c){let x=typeof c==="string"?{name:c}:c,{name:f,bucket:t,range:n=null}=x,h=await this.blob(f,t),v,S,w=n?.kind==="suffix"||n?.kind==="offset"&&n.end===null&&n.start===0;if(n&&w){let j=await this.size({name:f,bucket:t}),I=Zn(n,j);if(!I)throw new Ec(j);v=I.start,S=I.length}else if(n?.kind==="offset")v=n.start,S=n.end===null?void 0:n.end-n.start+1;let b;try{b=await h.download(v,S)}catch(j){if(tb(j))throw new Ec(await this.size({name:f,bucket:t}));if(Nn(j))throw new Mc(f);throw j}let B=Qx(b.contentRange),$=Boolean(B),N=B?.total??b.contentLength??0;return{body:await nb(b),start:B?.start??0,end:B?.end??N-1,total:N,partial:$,type:b.contentType??"application/octet-stream",etag:b.etag||void 0,lastModified:b.lastModified,name:f}}async size(c){let x=typeof c==="string"?c:c.name,f=typeof c==="string"?void 0:c.bucket,t=await this.blob(x,f);try{return(await t.getProperties()).contentLength??0}catch(n){if(Nn(n))throw new Mc(x);throw n}}async delete(c){let x=typeof c==="string"?c:c.name,f=typeof c==="string"?void 0:c.bucket,t=await this.blob(x,f);try{await t.delete()}catch(n){if(Nn(n))throw new Mc(x);throw n}}}async function nb(c){if(c.blobBody)return await c.blobBody;if(c.readableStreamBody)return fb.toWeb(c.readableStreamBody);return null}var w0={token:"redis"},hb=`
2
+ import{Sa as eG}from"../chunk-yf8kxjr2.js";import{$a as gG,Ta as NG,Ua as DG,Va as wG,Wa as qG,Xa as PG,Ya as yG,Za as AG,_a as VG,ab as cG,bb as mG,cb as EG,db as uG,eb as dG,fb as pG,gb as m4,hb as E4,ib as T1,jb as lG,kb as nG,lb as iG,mb as oG,nb as sG,ob as aG,pb as tG,qb as rG}from"../chunk-98a576s9.js";import{Ab as vG,Bb as _G,Cb as bG,Db as CG,Eb as IG,Fb as TG,rb as jG,sb as FG,tb as LG,ub as UG,vb as fG,wb as SG,xb as kG,yb as RG,zb as hG}from"../chunk-4t80js0n.js";import"../chunk-3y75q5a2.js";import{Kb as OG,Lb as HG}from"../chunk-64s1pzz1.js";import"../chunk-eqrd31ye.js";import{$b as r0,Ob as p0,Sb as e,Tb as l0,Ub as n0,Vb as i0,Wb as o0,Yb as s0,Zb as a0,_b as t0,ac as e0,bc as GG,cc as WG,dc as $G,ec as YG,fc as ZG,ic as JG,kc as QG,lc as KG,qc as x1}from"../chunk-tmnhkphv.js";import"../chunk-kry5vwam.js";import"../chunk-x14sk95v.js";import"../chunk-q0waxxz5.js";import{Fd as I1,Gd as b1,Hd as r,Sd as A,Td as _,Xd as D0,ae as g0,be as c0,de as m0,ee as E0,ge as u0,ke as d0}from"../chunk-vkngcrzq.js";import"../chunk-f9mfw82d.js";import"../chunk-01am9k5v.js";import"../chunk-4yafsffx.js";import{Ue as XG,Ve as zG,We as xG,Xe as MG,Ye as BG}from"../chunk-pvdbrt4z.js";import"../chunk-ct274qts.js";import{bf as c4}from"../chunk-v06qcyj5.js";import"../chunk-hs5v3eqj.js";import{if as y4}from"../chunk-kgmr9qxx.js";import{Buffer as P4}from"buffer";class A4 extends e{client;config;constructor(...G){super();this.config=G}async connect(){let G=await import("../chunk-62ke19q4.js");return this.client??=new G.S3Client(...this.config),{sdk:G,client:this.client}}async put(G){let W,$,Y,Z=process.env.BUCKET_NAME;if(G instanceof Blob)W=G,Y=`${Bun.randomUUIDv7()}.${G.type.split("/")[1].split(";")[0]}`,$=G.type;else W=G.body,Y=G.name,Z=G.bucket??Z,$=G.contentType||(W instanceof Blob||W instanceof File?W.type:void 0);$=$||void 0;let J=W instanceof P4?W:W instanceof Blob||W instanceof File?P4.from(await W.arrayBuffer()):"",{sdk:Q,client:K}=await this.connect();return await K.send(new Q.PutObjectCommand({Bucket:Z,Key:Y,Body:J,ContentType:$})),Y}async list(G){let{sdk:W,client:$}=await this.connect();return await $.send(new W.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:G}))}async fetch(G){let W=process.env.BUCKET_NAME,$;if(typeof G==="string")$=G;else W=G.bucket??W,$=G.name;if(!$)throw Error("Object name has to be specified");let{sdk:Y,client:Z}=await this.connect(),J=await Z.send(new Y.GetObjectCommand({Bucket:W,Key:$}));return new Response(J.Body.transformToWebStream(),{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(G){let W=typeof G==="string"?{name:G}:G,$=W.bucket??process.env.BUCKET_NAME,{name:Y,range:Z=null}=W;if(!Y)throw Error("Object name has to be specified");let{sdk:J,client:Q}=await this.connect(),K;try{K=await Q.send(new J.GetObjectCommand({Bucket:$,Key:Y,Range:Z?b1(Z):void 0}))}catch(B){if(B?.name==="InvalidRange"||B?.$metadata?.httpStatusCode===416)throw new A(await this.size({name:Y,bucket:$}));if(B?.name==="NoSuchKey"||B?.$metadata?.httpStatusCode===404)throw new _(Y);throw B}let z=r(K.ContentRange),X=Boolean(z)&&K.$metadata?.httpStatusCode===206,M=z?.total??K.ContentLength??0;return{body:K.Body.transformToWebStream(),start:z?.start??0,end:z?.end??M-1,total:M,partial:X,type:K.ContentType??"application/octet-stream",etag:K.ETag||void 0,lastModified:K.LastModified,name:Y}}async size(G){let W=typeof G==="string"?G:G.name,$=(typeof G==="string"?void 0:G.bucket)??process.env.BUCKET_NAME,{sdk:Y,client:Z}=await this.connect();try{return(await Z.send(new Y.HeadObjectCommand({Bucket:$,Key:W}))).ContentLength??0}catch(J){if(J?.name==="NotFound"||J?.$metadata?.httpStatusCode===404)throw new _(W);throw J}}}import{Buffer as V4}from"buffer";import{Readable as U0}from"stream";function C1(G){return G?.statusCode===404||G?.details?.errorCode==="BlobNotFound"||G?.code==="BlobNotFound"}function f0(G){return G?.statusCode===416||G?.details?.errorCode==="InvalidRange"||G?.code==="InvalidRange"}class g4 extends e{config;serviceClientPromise=null;constructor(G={}){super();this.config=G}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let G;try{G=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 W=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new G.BlobServiceClient(this.config.url,this.config.credential);if(W)return G.BlobServiceClient.fromConnectionString(W);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(G,W){if(!G)throw Error("Object name has to be specified");let $=W??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(G)}async put(G){let W,$,Y,Z;if(G instanceof Blob)W=G,Y=`${Bun.randomUUIDv7()}.${G.type.split("/")[1].split(";")[0]}`,$=G.type;else W=G.body,Y=G.name,Z=G.bucket,$=G.contentType??(W instanceof Blob||W instanceof File?W.type:void 0);let J=W instanceof V4?W:V4.from(await W.arrayBuffer());return await(await this.blob(Y,Z)).uploadData(J,{blobHTTPHeaders:$?{blobContentType:$}:void 0}),Y}async list(G){let W=this.config.container??process.env.BUCKET_NAME,Y=(await this.serviceClient()).getContainerClient(W),Z=[];for await(let J of Y.listBlobsFlat({prefix:G}))Z.push(J.name);return Z}async fetch(G){let W=await this.read(typeof G==="string"?{name:G}:{name:G.name,bucket:G.bucket});return new Response(W.body,{headers:{"Content-Type":W.type,"Content-Length":String(W.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":W.lastModified?.toUTCString()??"",ETag:W.etag??""}})}async read(G){let W=typeof G==="string"?{name:G}:G,{name:$,bucket:Y,range:Z=null}=W,J=await this.blob($,Y),Q,K,z=Z?.kind==="suffix"||Z?.kind==="offset"&&Z.end===null&&Z.start===0;if(Z&&z){let k=await this.size({name:$,bucket:Y}),t=I1(Z,k);if(!t)throw new A(k);Q=t.start,K=t.length}else if(Z?.kind==="offset")Q=Z.start,K=Z.end===null?void 0:Z.end-Z.start+1;let X;try{X=await J.download(Q,K)}catch(k){if(f0(k))throw new A(await this.size({name:$,bucket:Y}));if(C1(k))throw new _($);throw k}let M=r(X.contentRange),B=Boolean(M),S=M?.total??X.contentLength??0;return{body:await S0(X),start:M?.start??0,end:M?.end??S-1,total:S,partial:B,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(G){let W=typeof G==="string"?G:G.name,$=typeof G==="string"?void 0:G.bucket,Y=await this.blob(W,$);try{return(await Y.getProperties()).contentLength??0}catch(Z){if(C1(Z))throw new _(W);throw Z}}async delete(G){let W=typeof G==="string"?G:G.name,$=typeof G==="string"?void 0:G.bucket,Y=await this.blob(W,$);try{await Y.delete()}catch(Z){if(C1(Z))throw new _(W);throw Z}}}async function S0(G){if(G.blobBody)return await G.blobBody;if(G.readableStreamBody)return U0.toWeb(G.readableStreamBody);return null}var k0=`
12
3
  local currentKey = KEYS[1]
13
4
  local previousKey = KEYS[2]
14
5
  local limit = tonumber(ARGV[1])
@@ -35,12 +26,12 @@ current = redis.call("INCRBY", currentKey, cost)
35
26
  redis.call("PEXPIRE", currentKey, window * 2)
36
27
 
37
28
  return {1, current, previous}
38
- `;class $0 extends Wn{injectedClient;prefix;failOpen;onError;scriptSha=null;constructor(c={}){super();this.injectedClient=c.client,this.prefix=c.prefix??"gemi:rl",this.failOpen=c.failOpen??!0,this.onError=c.onError??((x)=>console.error(x))}async consume(c){let{key:x,limit:f,window:t}=c,n=c.cost??1,h=Date.now(),v=y0(h,t),S=h-v,w=v/t;try{let b=await this.run([`${this.prefix}:${x}:${w}`,`${this.prefix}:${x}:${w-1}`],[String(f),String(t),String(S),String(n)]),[B,$,N]=(Array.isArray(b)?b:[]).map(Number);return B0({allowed:B===1,current:Number.isFinite($)?$:0,previous:Number.isFinite(N)?N:0,now:h,elapsed:S,window:t,limit:f,cost:n})}catch(b){if(this.onError(b),!this.failOpen)return{allowed:!1,limit:f,remaining:0,resetAt:h+t,retryAfter:t};return{allowed:!0,limit:f,remaining:Math.max(0,Math.floor(f-n)),resetAt:v+t,retryAfter:0}}}get client(){if(this.injectedClient)return this.injectedClient;let c=b0(),x=c.bound(w0)?c.make(w0).client:void 0;if(!x)throw Error("RedisRateLimiter could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisRateLimiter({ client }).");return x}async run(c,x){let f=this.client,t=[String(c.length),...c,...x];try{return await f.send("EVALSHA",[await this.load(f),...t])}catch(n){if(!vb(n))throw n;return this.scriptSha=null,await f.send("EVALSHA",[await this.load(f),...t])}}load(c){if(!this.scriptSha)this.scriptSha=Promise.resolve(c.send("SCRIPT",["LOAD",hb])).then(String).catch((x)=>{throw this.scriptSha=null,x});return this.scriptSha}}function vb(c){return String(c?.message??c).includes("NOSCRIPT")}class dc{}var Sb={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"};class G0 extends dc{config;constructor(c={}){super();this.config={...Sb,...c}}getRedirectUrl(){let c=this.config.scope,x=this.config.clientId,f=new URL("https://accounts.google.com/o/oauth2/v2/auth"),t={scope:c,include_granted_scopes:"true",response_type:"code",state:"state_parameter_passthrough_value",redirect_uri:`${process.env.HOST_NAME}/auth/oauth/google/callback`,client_id:x};for(let[h,v]of Object.entries(t))f.searchParams.append(h,v);return f.toString()}async onCallback(c){let x=new URL("https://oauth2.googleapis.com/token");x.searchParams.append("code",c.search.get("code")),x.searchParams.append("client_id",this.config.clientId),x.searchParams.append("client_secret",this.config.clientSecret),x.searchParams.append("grant_type","authorization_code"),x.searchParams.append("redirect_uri",`${process.env.HOST_NAME}${this.config.redirectPath}`);let f=await fetch(x.toString(),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"}}),{access_token:t}=await f.json(),h=await(await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${t}`)).json();if(!h.email)console.error("Google OAuth error: email not found in user info response",h);return{name:h.name,email:h.email}}}var zc="https://api.x.com/2/",ic="https://api.x.com/labs/2/",Nc="https://api.x.com/1.1/",vc="https://upload.x.com/1.1/",M0="https://stream.x.com/1.1/",oc="https://ads-api.x.com/12/",ec="https://ads-api-sandbox.twitter.com/12/";class Rn{constructor({realData:c,rateLimit:x,instance:f,queryParams:t,sharedParams:n}){this._maxResultsWhenFetchLast=100,this._realData=c,this._rateLimit=x,this._instance=f,this._queryParams=t,this._sharedParams=n}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(c){return this._instance.get(this.getEndpoint(),c,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(c,x){return new this.constructor({realData:c.data,rateLimit:c.rateLimit,instance:this._instance,queryParams:x,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(c){return{...c?{max_results:c}:{},...this._queryParams}}async next(c){let x=this.getNextQueryParams(c),f=await this.makeRequest(x);return this.makeNewInstanceFromResult(f,x)}async fetchNext(c){let x=this.getNextQueryParams(c),f=await this.makeRequest(x);return await this.refreshInstanceFromResult(f,!0),this}async fetchLast(c=1/0){let x=this.getNextQueryParams(this._maxResultsWhenFetchLast),f=0;while(f<c&&this._isRateLimitOk){let t=await this.makeRequest(x);if(await this.refreshInstanceFromResult(t,!0),f+=this.getPageLengthFromRequest(t),this.isFetchLastOver(t))break;x=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var c;return{...(c=this._rateLimit)!==null&&c!==void 0?c:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let c=this,x=this.canFetchNextPage(this._realData);while(x&&this._isRateLimitOk&&c.getItemArray().length>0){let f=await c.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:f._realData,headers:{},rateLimit:f._rateLimit},!0),x=this.canFetchNextPage(f._realData),yield*f.getItemArray(),c=f}}async*fetchAndIterate(){for(let f of this.getItemArray())yield[f,this];let c=this,x=this.canFetchNextPage(this._realData);while(x&&this._isRateLimitOk&&c.getItemArray().length>0){let f=await c.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:f._realData,headers:{},rateLimit:f._rateLimit},!0),x=this.canFetchNextPage(f._realData);for(let t of f.getItemArray())yield[t,f];this._rateLimit=f._rateLimit,c=f}}}class jn extends Rn{async previous(c){let x=this.getPreviousQueryParams(c),f=await this.makeRequest(x);return this.makeNewInstanceFromResult(f,x)}async fetchPrevious(c){let x=this.getPreviousQueryParams(c),f=await this.makeRequest(x);return await this.refreshInstanceFromResult(f,!1),this}}var ac=Rn;class A extends ac{getNextQueryParams(c){var x;return{...this._queryParams,cursor:(x=this._realData.next_cursor_str)!==null&&x!==void 0?x:this._realData.next_cursor,...c?{count:c}:{}}}isFetchLastOver(c){return!this.canFetchNextPage(c.data)}canFetchNextPage(c){return!this.isNextCursorInvalid(c.next_cursor)||!this.isNextCursorInvalid(c.next_cursor_str)}isNextCursorInvalid(c){return c===void 0||c===0||c===-1||c==="0"||c==="-1"}}class Kn extends A{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.events.push(...f.events),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class On extends A{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.welcome_messages.push(...f.welcome_messages),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var k;(function(c){c.Jpeg="image/jpeg",c.Mp4="video/mp4",c.Mov="video/quicktime",c.Gif="image/gif",c.Png="image/png",c.Srt="text/plain",c.Webp="image/webp"})(k||(k={}));var Zc;(function(c){c.Create="message_create",c.WelcomeCreate="welcome_message"})(Zc||(Zc={}));var Yx;(function(c){c.Request="request",c.PartialResponse="partial-response",c.Response="response"})(Yx||(Yx={}));class Pf extends Error{constructor(){super(...arguments);this.error=!0}}class Xx extends Pf{constructor(c,x){super(c);this.type=Yx.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:x})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class Ux extends Pf{constructor(c,x){super(c);this.type=Yx.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:x})}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 Hx extends Pf{constructor(c,x){super(c);if(this.type=Yx.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:x}),this.code=x.code,this.headers=x.headers,this.rateLimit=x.rateLimit,x.data&&typeof x.data==="object"&&"error"in x.data&&!x.data.errors){let f={...x.data};f.errors=[{code:Uc.InternalError,message:f.error}],this.data=f}else this.data=x.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...c){let x=this.errors;if(!(x===null||x===void 0?void 0:x.length))return!1;if("code"in x[0])return x.some((n)=>c.includes(n.code));let f=this.data;return c.includes(f.type)}get errors(){var c;return(c=this.data)===null||c===void 0?void 0:c.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(Uc.AuthTimestampInvalid,Uc.AuthenticationFail,Uc.BadAuthenticationData,Uc.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var Uc;(function(c){c[c.InvalidCoordinates=3]="InvalidCoordinates",c[c.NoLocationFound=13]="NoLocationFound",c[c.AuthenticationFail=32]="AuthenticationFail",c[c.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",c[c.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",c[c.AuthTimestampInvalid=135]="AuthTimestampInvalid",c[c.BadAuthenticationData=215]="BadAuthenticationData",c[c.NoUserMatch=17]="NoUserMatch",c[c.UserNotFound=50]="UserNotFound",c[c.ResourceNotFound=34]="ResourceNotFound",c[c.TweetNotFound=144]="TweetNotFound",c[c.TweetNotVisible=179]="TweetNotVisible",c[c.NotAllowedResource=220]="NotAllowedResource",c[c.MediaIdNotFound=325]="MediaIdNotFound",c[c.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",c[c.TweetViolatedRules=422]="TweetViolatedRules",c[c.TargetUserSuspended=63]="TargetUserSuspended",c[c.YouAreSuspended=64]="YouAreSuspended",c[c.AccountUpdateFailed=120]="AccountUpdateFailed",c[c.NoSelfSpamReport=36]="NoSelfSpamReport",c[c.NoSelfMute=271]="NoSelfMute",c[c.AccountLocked=326]="AccountLocked",c[c.RateLimitExceeded=88]="RateLimitExceeded",c[c.NoDMRightForApp=93]="NoDMRightForApp",c[c.OverCapacity=130]="OverCapacity",c[c.InternalError=131]="InternalError",c[c.TooManyFollowings=161]="TooManyFollowings",c[c.TweetLimitExceeded=185]="TweetLimitExceeded",c[c.DuplicatedTweet=187]="DuplicatedTweet",c[c.TooManySpamReports=205]="TooManySpamReports",c[c.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",c[c.NoWriteRightForApp=261]="NoWriteRightForApp",c[c.TweetActionsDisabled=425]="TweetActionsDisabled",c[c.TweetRepliesRestricted=433]="TweetRepliesRestricted",c[c.NamedParameterMissing=38]="NamedParameterMissing",c[c.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",c[c.TweetTextTooLong=186]="TweetTextTooLong",c[c.MissingUrlParameter=195]="MissingUrlParameter",c[c.NoMultipleGifs=323]="NoMultipleGifs",c[c.InvalidMediaIds=324]="InvalidMediaIds",c[c.InvalidUrl=407]="InvalidUrl",c[c.TooManyTweetAttachments=386]="TooManyTweetAttachments",c[c.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",c[c.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",c[c.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",c[c.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",c[c.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",c[c.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",c[c.UnableToSendDM=151]="UnableToSendDM",c[c.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",c[c.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",c[c.DMTextTooLong=354]="DMTextTooLong",c[c.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",c[c.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",c[c.SuspendedApplication=416]="SuspendedApplication",c[c.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(Uc||(Uc={}));var z0;(function(c){c.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",c.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",c.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",c.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",c.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",c.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",c.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",c.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",c.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",c.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",c.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",c.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",c.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(z0||(z0={}));var W;(function(c){c.Connected="connected",c.ConnectError="connect error",c.ConnectionError="connection error",c.ConnectionClosed="connection closed",c.ConnectionLost="connection lost",c.ReconnectAttempt="reconnect attempt",c.Reconnected="reconnected",c.ReconnectError="reconnect error",c.ReconnectLimitExceeded="reconnect limit exceeded",c.DataKeepAlive="data keep-alive",c.Data="data event content",c.DataError="data twitter error",c.TweetParseError="data tweet parse error",c.Error="stream error"})(W||(W={}));class Fx{constructor(c){this.value=c}}import*as dn from"fs";var g={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function Dn(c){let x={value:void 0,promise:c().then((f)=>{return x.value=f,f})};return x}function mf(c){if(Array.isArray(c))return c;return[c]}function Z0(c){for(let x of Object.keys(c))if(c[x]===void 0)delete c[x]}function Tf(c){return typeof c==="object"&&"errors"in c&&!("data"in c)}function ux(c){if(Array.isArray(c)&&c.length>1)return!0;return c.toString().includes(",")}var N0=new Set;function Jn(c){if(typeof console>"u"||!console.warn||!g.deprecationWarnings)return;let x=`${c.instance}-${c.method}-${c.problem}`;if(N0.has(x))return;let f=`[twitter-api-v2] Deprecation warning: In ${c.instance}.${c.method}() call, ${c.problem}.
39
- ${c.resolution}.`;console.warn(f),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),N0.add(x)}import{EventEmitter as $b}from"events";import{request as wb}from"https";import*as p from"zlib";import{EventEmitter as bb}from"events";class W0{constructor(c){this.requestData=c,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let c=this.requestData.url;return c.hostname+c.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(c){if(g.debug)g.logger.log("Request error:",c);return new Xx("Request failed.",{request:this.req,error:c})}createPartialResponseError(c,x){let t=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(x)t+=" (connection abruptly closed)";else t+=" (parse error)";return new Ux(t,{request:this.req,response:this.res,responseError:c,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(c){return c.map(({code:x,message:f})=>`${f} (Twitter code ${x})`).join(", ")}formatV2Error(c){return`${c.title}: ${c.detail} (see ${c.type})`}createResponseError({res:c,data:x,rateLimit:f,code:t}){var n;if(g.debug)g.logger.log(`Request failed with code ${t}, data:`,x),g.logger.log("Response headers:",c.headers);let h=`Request failed with code ${t}`;if((n=x===null||x===void 0?void 0:x.errors)===null||n===void 0?void 0:n.length){let v=x.errors;if(typeof v[0]==="object"&&"code"in v[0])h+=" - "+this.formatV1Errors(v);else h+=" - "+this.formatV2Error(x)}return new Hx(h,{code:t,data:x,headers:c.headers,request:this.req,response:c,rateLimit:f})}getResponseDataStream(c){if(this.isCompressionDisabled())return c;let x=(c.headers["content-encoding"]||"identity").trim().toLowerCase();if(x==="br"){let f=p.createBrotliDecompress({flush:p.constants.BROTLI_OPERATION_FLUSH,finishFlush:p.constants.BROTLI_OPERATION_FLUSH});return c.pipe(f),f}if(x==="gzip"){let f=p.createGunzip({flush:p.constants.Z_SYNC_FLUSH,finishFlush:p.constants.Z_SYNC_FLUSH});return c.pipe(f),f}if(x==="deflate"){let f=p.createInflate({flush:p.constants.Z_SYNC_FLUSH,finishFlush:p.constants.Z_SYNC_FLUSH});return c.pipe(f),f}return c}detectResponseType(c){var x,f;if(((x=c.headers["content-type"])===null||x===void 0?void 0:x.includes("application/json"))||((f=c.headers["content-type"])===null||f===void 0?void 0:f.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(c){let x=this.responseData,f=this.requestData.forceParseMode||this.detectResponseType(c);if(f==="buffer")return Buffer.concat(x);else if(f==="text")return Buffer.concat(x).toString();else if(f==="json"){let t=Buffer.concat(x).toString();return t.length?JSON.parse(t):void 0}else if(f==="url"){let t=Buffer.concat(x).toString(),n={};for(let[h,v]of new URLSearchParams(t))n[h]=v;return n}else return}getRateLimitFromResponse(c){let x=void 0;if(c.headers["x-rate-limit-limit"]){if(x={limit:Number(c.headers["x-rate-limit-limit"]),remaining:Number(c.headers["x-rate-limit-remaining"]),reset:Number(c.headers["x-rate-limit-reset"])},c.headers["x-app-limit-24hour-limit"])x.day={limit:Number(c.headers["x-app-limit-24hour-limit"]),remaining:Number(c.headers["x-app-limit-24hour-remaining"]),reset:Number(c.headers["x-app-limit-24hour-reset"])};if(c.headers["x-user-limit-24hour-limit"])x.userDay={limit:Number(c.headers["x-user-limit-24hour-limit"]),remaining:Number(c.headers["x-user-limit-24hour-remaining"]),reset:Number(c.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(x)}return x}onSocketEventHandler(c,x,f){let t=this.onSocketCloseHandler.bind(this,c);f.on("close",t),x.on("complete",()=>f.off("close",t))}onSocketCloseHandler(c){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return c(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(c,x){var f,t;(t=(f=this.requestData).requestEventDebugHandler)===null||t===void 0||t.call(f,"request-error",{requestError:x}),this.requestErrorHandled=!0,c(this.createRequestError(x))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(c,x,f){this.res=f;let t=this.getResponseDataStream(f);if(t.on("data",(n)=>this.responseData.push(n)),t.on("end",this.onResponseEndHandler.bind(this,c,x)),t.on("close",this.onResponseCloseHandler.bind(this,c,x)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:f}),f.on("aborted",(n)=>this.requestData.requestEventDebugHandler("response-aborted",{error:n})),f.on("error",(n)=>this.requestData.requestEventDebugHandler("response-error",{error:n})),f.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),f.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(c,x){let f=this.getRateLimitFromResponse(this.res),t;try{t=this.getParsedResponse(this.res)}catch(h){x(this.createPartialResponseError(h,!1));return}let n=this.res.statusCode;if(n>=400){x(this.createResponseError({data:t,res:this.res,rateLimit:f,code:n}));return}if(g.debug)g.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),g.logger.log("Response body:",t);c({data:t,headers:this.res.headers,rateLimit:f})}onResponseCloseHandler(c,x){let f=this.res;if(f.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(c,x)}catch(t){return x(this.createPartialResponseError(t,!0))}if(!f.complete)return x(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(c,x,f){if(f.statusCode<400){if(g.debug)g.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${f.statusCode} (starting stream)`);let n=this.getResponseDataStream(f);c({req:this.req,res:n,originalResponse:f,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},x,f)}debugRequest(){let c=this.requestData.url;if(g.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),c.search)g.logger.log("Request parameters:",[...c.searchParams.entries()].map(([x,f])=>`${x}: ${f}`));if(this.requestData.body)g.logger.log("Request body:",this.requestData.body)}buildRequest(){var c;let x=this.requestData.url,f=x.username?`${x.username}:${x.password}`:void 0,t=(c=this.requestData.options.headers)!==null&&c!==void 0?c:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")t["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")t["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")t["accept-encoding"]="deflate;q=1, *;q=0.1";if(g.debug)this.debugRequest();this.req=wb({...this.requestData.options,host:x.hostname,port:x.port||void 0,path:x.pathname+x.search,protocol:x.protocol,auth:f,headers:t})}registerRequestEventDebugHandlers(c){c.on("close",()=>this.requestData.requestEventDebugHandler("close")),c.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),c.on("socket",(x)=>{this.requestData.requestEventDebugHandler("socket",{socket:x}),x.on("error",(f)=>this.requestData.requestEventDebugHandler("socket-error",{socket:x,error:f})),x.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:x})),x.on("close",(f)=>this.requestData.requestEventDebugHandler("socket-close",{socket:x,withError:f})),x.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:x})),x.on("lookup",(...f)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:x,data:f})),x.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:x}))})}makeRequest(){return this.buildRequest(),new Promise((c,x)=>{let f=(v)=>{n.emit("complete"),c(v)},t=(v)=>{n.emit("complete"),x(v)},n=new bb,h=this.req;if(h.on("error",this.requestErrorHandler.bind(this,t)),h.on("socket",this.onSocketEventHandler.bind(this,t,n)),h.on("response",this.classicResponseHandler.bind(this,f,t)),this.requestData.options.timeout)h.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(h);if(this.requestData.body)h.write(this.requestData.body);h.end()})}async makeRequestAsStream(){let{req:c,res:x,requestData:f,originalResponse:t}=await this.makeRequestAndResolveWhenReady();return new _f(f,{req:c,res:x,originalResponse:t})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((c,x)=>{let f=this.req;if(f.on("error",this.requestErrorHandler.bind(this,x)),f.on("response",this.streamResponseHandler.bind(this,c,x)),this.requestData.body)f.write(this.requestData.body);f.end()})}}var Lx=W0;import{EventEmitter as yb}from"events";class R0 extends yb{constructor(c){super();this.stream=c,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),c.on(W.Data,this.onStreamData),c.on(W.ConnectionError,this.onStreamError),c.on(W.TweetParseError,this.onStreamError),c.on(W.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let c=this.stack;return this.stack=[],c}destroy(){this.removeAllListeners(),this.stream.off(W.Data,this.onStreamData),this.stream.off(W.ConnectionError,this.onStreamError),this.stream.off(W.TweetParseError,this.onStreamError),this.stream.off(W.ConnectionClosed,this.onStreamError)}emitEvent(c,x){this.emit("event",{type:c,payload:x})}onStreamError(c){this.emitEvent("error",c)}onStreamData(c){this.stack.push(c),this.emitEvent("data",c)}}var j0=R0;import{EventEmitter as Bb}from"events";class qf extends Bb{constructor(){super(...arguments);this.currentMessage=""}push(c){this.currentMessage+=c,c=this.currentMessage;let x=c.length,f=0,t=0;while(t<x){if(c.slice(t,t+2)===`\r
40
- `){let n=c.slice(f,t);if(f=t+=2,!n.length)continue;try{let h=JSON.parse(n);if(h){this.emit(Hc.ParsedData,h);continue}}catch(h){this.emit(Hc.ParseError,h)}}t++}this.currentMessage=c.slice(f,x)}reset(){this.currentMessage=""}}var Hc;(function(c){c.ParsedData="parsed data",c.ParseError="parse error"})(Hc||(Hc={}));var K0=[5,15,30,60,90,120,180,300,600,900],Gb=(c)=>c>K0.length?901000:K0[c-1]*1000;class O0 extends $b{constructor(c,x){super();if(this.requestData=c,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=Gb,this.parser=new qf,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),x)this.req=x.req,this.res=x.res,this.originalResponse=x.originalResponse,this.initEventsFromRequest()}on(c,x){return super.on(c,x)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let c=(x)=>{this.emit(W.ConnectionError,x),this.emit(W.Error,{type:W.ConnectionError,error:x,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",c),this.res.on("error",c),this.res.on("close",()=>c(Error("Connection closed by Twitter."))),this.res.on("data",(x)=>{if(this.resetKeepAliveTimeout(),x.toString()===`\r
41
- `)return this.emit(W.DataKeepAlive);this.parser.push(x.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let c=this.requestData.payloadIsError;this.parser.on(Hc.ParsedData,(x)=>{if(c&&c(x))this.emit(W.DataError,x),this.emit(W.Error,{type:W.DataError,error:x,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(W.Data,x)}),this.parser.on(Hc.ParseError,(x)=>{this.emit(W.TweetParseError,x),this.emit(W.Error,{type:W.TweetParseError,error:x,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(W.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(W.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let x=await new Lx(this.requestData).makeRequestAsStream(),f=this.eventNames();for(let t of f){let n=this.listeners(t);for(let h of n)x.on(t,h)}return x}async connect(c={}){if(typeof c.autoReconnect<"u")this.autoReconnect=c.autoReconnect;if(typeof c.autoReconnectRetries<"u")this.autoReconnectRetries=c.autoReconnectRetries==="unlimited"?1/0:c.autoReconnectRetries;if(typeof c.keepAliveTimeout<"u")this.keepAliveTimeoutMs=c.keepAliveTimeout==="disable"?1/0:c.keepAliveTimeout;if(typeof c.nextRetryTimeout<"u")this.nextRetryTimeout=c.nextRetryTimeout;this.unbindTimeouts();try{await this.reconnect()}catch(x){if(this.emit(W.ConnectError,0),this.emit(W.Error,{type:W.ConnectError,error:x,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,x);else throw x}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let c=!0;if(this.req)c=!1,this.closeWithoutEmit();let{req:x,res:f,originalResponse:t}=await new Lx(this.requestData).makeRequestAndResolveWhenReady();this.req=x,this.res=f,this.originalResponse=t,this.emit(c?W.Connected:W.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(c=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(W.ConnectionClosed);return}if(c>=this.autoReconnectRetries){this.emit(W.ReconnectLimitExceeded),this.emit(W.ConnectionClosed);return}try{this.emit(W.ReconnectAttempt,c),await this.reconnect()}catch(x){this.emit(W.ReconnectError,c),this.emit(W.Error,{type:W.ReconnectError,error:x,message:`Reconnect error - ${c+1} attempts made yet.`}),this.makeAutoReconnectRetry(c,x)}}makeAutoReconnectRetry(c,x){let f=this.nextRetryTimeout(c+1,x);this.retryTimeout=setTimeout(()=>{this.onConnectionError(c+1)},f)}async*[Symbol.asyncIterator](){let c=new j0(this);try{while(!0){if(!this.req||this.req.aborted)throw Error("Connection closed");if(c.hasStack())yield*c.popStack();let{type:x,payload:f}=await c.nextEvent();if(x==="error")throw f}}finally{c.destroy()}}}var _f=O0;function D0(c){var x;if(!((x=c.clientSettings.plugins)===null||x===void 0?void 0:x.length))return!1;for(let f of c.clientSettings.plugins)if(f.onRequestError||f.onResponseError)return!0;return!1}async function J0(c,x,f,t){let n;if(t instanceof Xx||t instanceof Ux)n=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(c.url),params:c,computedParams:x,requestOptions:f,error:t});else if(t instanceof Hx)n=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(c.url),params:c,computedParams:x,requestOptions:f,error:t});if(n&&n instanceof Fx)return n.value;return Promise.reject(t)}import*as Y0 from"crypto";class a{constructor(c){this.nonceLength=32,this.consumerKeys=c.consumerKeys}static percentEncode(c){return encodeURIComponent(c).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(c,x){return Y0.createHmac("sha1",x).update(c).digest("base64")}authorize(c,x={}){let f={oauth_consumer_key:this.consumerKeys.key,oauth_nonce:this.getNonce(),oauth_signature_method:"HMAC-SHA1",oauth_timestamp:this.getTimestamp(),oauth_version:"1.0"};if(x.key!==void 0)f.oauth_token=x.key;if(!c.data)c.data={};return f.oauth_signature=this.getSignature(c,x.secret,f),f}toHeader(c){let x=k0(c),f="OAuth ";for(let t of x){if(t.key.indexOf("oauth_")!==0)continue;f+=a.percentEncode(t.key)+'="'+a.percentEncode(t.value)+'",'}return{Authorization:f.slice(0,f.length-1)}}getNonce(){let x="";for(let f=0;f<this.nonceLength;f++)x+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.trunc(Math.random()*62)];return x}getTimestamp(){return Math.trunc(new Date().getTime()/1000)}getSignature(c,x,f){return this.hash(this.getBaseString(c,f),this.getSigningKey(x))}getSigningKey(c){return a.percentEncode(this.consumerKeys.secret)+"&"+a.percentEncode(c||"")}getBaseString(c,x){return c.method.toUpperCase()+"&"+a.percentEncode(this.getBaseUrl(c.url))+"&"+a.percentEncode(this.getParameterString(c,x))}getParameterString(c,x){let f=k0(Nb(Q0(x,Q0(c.data,zb(c.url))))),t="";for(let{key:n,value:h}of f)if(h&&Array.isArray(h)){h.sort();let v="";h.forEach((S,w)=>{if(v+=n+"="+S,w<h.length)v+="&"}),t+=v}else t+=n+"="+h+"&";return t.slice(0,t.length-1)}getBaseUrl(c){return c.split("?")[0]}}var sx=a;function Q0(c,x){return{...c||{},...x||{}}}function k0(c){return Object.keys(c).sort().map((x)=>({key:x,value:c[x]}))}function Mb(c){let x=c.split("&"),f={};for(let t of x){let[n,h=""]=t.split("=");if(f[n]){if(!Array.isArray(f[n]))f[n]=[f[n]];f[n].push(decodeURIComponent(h))}else f[n]=decodeURIComponent(h)}return f}function zb(c){let x=c.split("?");if(x.length===1)return{};return Mb(x[1])}function Nb(c){let x={};for(let f in c){let t=c[f];if(t&&Array.isArray(t))t=t.map((n)=>a.percentEncode(n));else t=a.percentEncode(t);x[a.percentEncode(f)]=t}return x}class r{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...c){let x=c.map((f)=>f instanceof Buffer?f:Buffer.from(f));this._chunks.push(...x)}append(c,x,f){let t=x instanceof Buffer?x:x.toString(),n=this.getMultipartHeader(c,t,f);this.bodyAppend(n,t,r.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((c,x)=>c+x.length,this.getMultipartFooter().length)}getBuffer(){let c=[...this._chunks,this.getMultipartFooter()],x=Buffer.alloc(this.getLength()),f=0;for(let t of c)for(let n=0;n<t.length;f++,n++)x[f]=t[n];return x}getBoundary(){if(!this._boundary)this.generateBoundary();return this._boundary}generateBoundary(){let c="--------------------------";for(let x=0;x<24;x++)c+=Math.floor(Math.random()*10).toString(16);this._boundary=c}getMultipartHeader(c,x,f){if(!f)f=x instanceof Buffer?r.DEFAULT_CONTENT_TYPE:"";let t={"Content-Disposition":["form-data",`name="${c}"`],"Content-Type":f},n="";for(let[h,v]of Object.entries(t)){if(!v.length)continue;n+=h+": "+mf(v).join("; ")+r.LINE_BREAK}return"--"+this.getBoundary()+r.LINE_BREAK+n+r.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+r.LINE_BREAK)}}r.LINE_BREAK=`\r
42
- `;r.DEFAULT_CONTENT_TYPE="application/octet-stream";class Qn{static formatQueryToString(c){let x={};for(let f in c)if(typeof c[f]==="string")x[f]=c[f];else if(typeof c[f]<"u")x[f]=String(c[f]);return x}static autoDetectBodyType(c){if(c.pathname.startsWith("/2/")||c.pathname.startsWith("/labs/2/")){if(c.password.startsWith("/2/oauth2"))return"url";return"json"}if(c.hostname==="upload.x.com"){if(c.pathname==="/1.1/media/upload.json")return"form-data";return"json"}let x=c.pathname.split("/1.1/",2)[1];if(this.JSON_1_1_ENDPOINTS.has(x))return"json";return"url"}static addQueryParamsToUrl(c,x){let f=Object.entries(x);if(f.length){let t="";for(let[n,h]of f)t+=(t.length?"&":"?")+`${sx.percentEncode(n)}=${sx.percentEncode(h)}`;c.search=t}}static constructBodyParams(c,x,f){if(c instanceof Buffer)return c;if(f==="json"){if(!x["content-type"])x["content-type"]="application/json;charset=UTF-8";return JSON.stringify(c)}else if(f==="url"){if(!x["content-type"])x["content-type"]="application/x-www-form-urlencoded;charset=UTF-8";if(Object.keys(c).length)return new URLSearchParams(c).toString().replace(/\*/g,"%2A");return""}else if(f==="raw")throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");else{let t=new r;for(let n in c)t.append(n,c[n]);if(!x["content-type"]){let n=t.getHeaders();x["content-type"]=n["content-type"]}return t.getBuffer()}}static setBodyLengthHeader(c,x){var f;if(c.headers=(f=c.headers)!==null&&f!==void 0?f:{},typeof x==="string")c.headers["content-length"]=Buffer.byteLength(x);else c.headers["content-length"]=x.length}static isOAuthSerializable(c){return!(c instanceof Buffer)}static mergeQueryAndBodyForOAuth(c,x){let f={};for(let t in c)f[t]=c[t];if(this.isOAuthSerializable(x))for(let t in x){let n=x[t];if(this.isOAuthSerializable(n))f[t]=typeof n==="object"&&n!==null&&"toString"in n?n.toString():n}return f}static moveUrlQueryParamsIntoObject(c,x){for(let[f,t]of c.searchParams)x[f]=t;return c.search="",c}static applyRequestParametersToUrl(c,x){return c.pathname=c.pathname.replace(/:([A-Z_-]+)/ig,(f,t)=>{if(x[t]!==void 0)return String(x[t]);return f}),c}}Qn.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 o=Qn;import*as X0 from"crypto";class Fc{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(c){return this.escapeBase64Url(X0.createHash("sha256").update(c).digest("base64"))}static getAuthHeader(c,x){let f=encodeURIComponent(c)+":"+encodeURIComponent(x);return Buffer.from(f).toString("base64")}static generateRandomString(c){let x="",f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let t=0;t<c;t++)x+=f[Math.floor(Math.random()*f.length)];return x}static escapeBase64Url(c){return c.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class rc{constructor(c){if(this.rateLimits={},this.clientSettings={},c)this.clientSettings=c}getRateLimits(){return this.rateLimits}saveRateLimit(c,x){this.rateLimits[c]=x}async send(c){var x,f,t,n,h;if((x=this.clientSettings.plugins)===null||x===void 0?void 0:x.length){let $=await this.applyPreRequestConfigHooks(c);if($)return $}let v=this.getHttpRequestArgs(c),S={method:v.method,headers:v.headers,timeout:c.timeout,agent:this.clientSettings.httpAgent},w=c.enableRateLimitSave!==!1;if(v.body)o.setBodyLengthHeader(S,v.body);if((f=this.clientSettings.plugins)===null||f===void 0?void 0:f.length)await this.applyPreRequestHooks(c,v,S);let b=new Lx({url:v.url,options:S,body:v.body,rateLimitSaver:w?this.saveRateLimit.bind(this,v.rawUrl):void 0,requestEventDebugHandler:c.requestEventDebugHandler,compression:(n=(t=c.compression)!==null&&t!==void 0?t:this.clientSettings.compression)!==null&&n!==void 0?n:!0,forceParseMode:c.forceParseMode}).makeRequest();if(D0(this))b=this.applyResponseErrorHooks(c,v,S,b);let B=await b;if((h=this.clientSettings.plugins)===null||h===void 0?void 0:h.length){let $=await this.applyPostRequestHooks(c,v,S,B);if($)return $.value}return B}sendStream(c){var x,f;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(c);let t=this.getHttpRequestArgs(c),n={method:t.method,headers:t.headers,agent:this.clientSettings.httpAgent},h=c.enableRateLimitSave!==!1,v=c.autoConnect!==!1;if(t.body)o.setBodyLengthHeader(n,t.body);let S={url:t.url,options:n,body:t.body,rateLimitSaver:h?this.saveRateLimit.bind(this,t.rawUrl):void 0,payloadIsError:c.payloadIsError,compression:(f=(x=c.compression)!==null&&x!==void 0?x:this.clientSettings.compression)!==null&&f!==void 0?f:!0},w=new _f(S);if(!v)return w;return w.connect()}initializeToken(c){if(typeof c==="string")this.bearerToken=c;else if(typeof c==="object"&&"appKey"in c){if(this.consumerToken=c.appKey,this.consumerSecret=c.appSecret,c.accessToken&&c.accessSecret)this.accessToken=c.accessToken,this.accessSecret=c.accessSecret;this._oauth=this.buildOAuth()}else if(typeof c==="object"&&"username"in c){let x=encodeURIComponent(c.username)+":"+encodeURIComponent(c.password);this.basicToken=Buffer.from(x).toString("base64")}else if(typeof c==="object"&&"clientId"in c)this.clientId=c.clientId,this.clientSecret=c.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 sx({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(!this.accessSecret||!this.accessToken)return;return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var c;return(c=this.clientSettings.plugins)!==null&&c!==void 0?c:[]}hasPlugins(){var c;return!!((c=this.clientSettings.plugins)===null||c===void 0?void 0:c.length)}async applyPluginMethod(c,x){var f;let t;for(let n of this.getPlugins()){let h=await((f=n[c])===null||f===void 0?void 0:f.call(n,x));if(h&&h instanceof Fx)t=h}return t}writeAuthHeaders({headers:c,bodyInSignature:x,url:f,method:t,query:n,body:h}){if(c={...c},this.bearerToken)c.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)c.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)c.Authorization="Basic "+Fc.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let v=x?o.mergeQueryAndBodyForOAuth(n,h):n,S=this._oauth.authorize({url:f.toString(),method:t,data:v},this.getOAuthAccessTokens());c={...c,...this._oauth.toHeader(S)}}return c}getUrlObjectFromUrlString(c){if(!c.startsWith("http"))c="https://"+c;return new URL(c)}getHttpRequestArgs({url:c,method:x,query:f={},body:t={},headers:n,forceBodyMode:h,enableAuth:v,params:S}){let w=void 0;if(x=x.toUpperCase(),n=n!==null&&n!==void 0?n:{},!n["x-user-agent"])n["x-user-agent"]="Node.twitter-api-v2";let b=this.getUrlObjectFromUrlString(c),B=b.origin+b.pathname;if(S)o.applyRequestParametersToUrl(b,S);let $=o.formatQueryToString(f);if(o.moveUrlQueryParamsIntoObject(b,$),!(t instanceof Buffer))Z0(t);let N=h!==null&&h!==void 0?h:o.autoDetectBodyType(b);if(v!==!1){let j=rc.BODY_METHODS.has(x)&&N==="url";n=this.writeAuthHeaders({headers:n,bodyInSignature:j,method:x,query:$,url:b,body:t})}if(rc.BODY_METHODS.has(x))w=o.constructBodyParams(t,n,N)||void 0;return o.addQueryParamsToUrl(b,$),{rawUrl:B,url:b,method:x,headers:n,body:w}}async applyPreRequestConfigHooks(c){var x;let f=this.getUrlObjectFromUrlString(c.url);for(let t of this.getPlugins()){let n=await((x=t.onBeforeRequestConfig)===null||x===void 0?void 0:x.call(t,{client:this,url:f,params:c}));if(n)return n}}applyPreStreamRequestConfigHooks(c){var x;let f=this.getUrlObjectFromUrlString(c.url);for(let t of this.getPlugins())(x=t.onBeforeStreamRequestConfig)===null||x===void 0||x.call(t,{client:this,url:f,params:c})}async applyPreRequestHooks(c,x,f){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(c.url),params:c,computedParams:x,requestOptions:f})}async applyPostRequestHooks(c,x,f,t){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(c.url),params:c,computedParams:x,requestOptions:f,response:t})}applyResponseErrorHooks(c,x,f,t){return t.catch(J0.bind(this,c,x,f))}}rc.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class Wc{constructor(c,x={}){if(this._currentUser=null,this._currentUserV2=null,c instanceof Wc)this._requestMaker=c._requestMaker;else this._requestMaker=new rc(x),this._requestMaker.initializeToken(c)}setPrefix(c){this._prefix=c}cloneWithPrefix(c){let x=this.constructor(this);return x.setPrefix(c),x}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(c){return this.getPlugins().find((x)=>x instanceof c)}hasHitRateLimit(c){var x;if(this.isRateLimitStatusObsolete(c))return!1;return((x=this.getLastRateLimitStatus(c))===null||x===void 0?void 0:x.remaining)===0}isRateLimitStatusObsolete(c){let x=this.getLastRateLimitStatus(c);if(x===void 0)return!0;return x.reset*1000<Date.now()}getLastRateLimitStatus(c){let x=c.match(/^https?:\/\//)?c:this._prefix+c;return this._requestMaker.getRateLimits()[x]}getCurrentUserObject(c=!1){if(!c&&this._currentUser){if(this._currentUser.value)return Promise.resolve(this._currentUser.value);return this._currentUser.promise}return this._currentUser=Dn(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:Nc})),this._currentUser.promise}getCurrentUserV2Object(c=!1){if(!c&&this._currentUserV2){if(this._currentUserV2.value)return Promise.resolve(this._currentUserV2.value);return this._currentUserV2.promise}return this._currentUserV2=Dn(()=>this.get("users/me",void 0,{prefix:zc})),this._currentUserV2.promise}async get(c,x={},{fullResponse:f,prefix:t=this._prefix,...n}={}){if(t)c=t+c;let h=await this._requestMaker.send({url:c,method:"GET",query:x,...n});return f?h:h.data}async delete(c,x={},{fullResponse:f,prefix:t=this._prefix,...n}={}){if(t)c=t+c;let h=await this._requestMaker.send({url:c,method:"DELETE",query:x,...n});return f?h:h.data}async post(c,x,{fullResponse:f,prefix:t=this._prefix,...n}={}){if(t)c=t+c;let h=await this._requestMaker.send({url:c,method:"POST",body:x,...n});return f?h:h.data}async put(c,x,{fullResponse:f,prefix:t=this._prefix,...n}={}){if(t)c=t+c;let h=await this._requestMaker.send({url:c,method:"PUT",body:x,...n});return f?h:h.data}async patch(c,x,{fullResponse:f,prefix:t=this._prefix,...n}={}){if(t)c=t+c;let h=await this._requestMaker.send({url:c,method:"PATCH",body:x,...n});return f?h:h.data}getStream(c,x,{prefix:f=this._prefix,...t}={}){return this._requestMaker.sendStream({url:f?f+c:c,method:"GET",query:x,...t})}postStream(c,x,{prefix:f=this._prefix,...t}={}){return this._requestMaker.sendStream({url:f?f+c:c,method:"POST",body:x,...t})}}class e extends Wc{constructor(c){if(!(c instanceof Wc))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(c)}}class cx extends ac{constructor(){super(...arguments);this.hasFinishedFetch=!1}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.push(...f),this.hasFinishedFetch=f.length===0}getNextQueryParams(c){let x=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(c),max_id:(x-BigInt(1)).toString()}}getPageLengthFromRequest(c){return c.data.length}isFetchLastOver(c){return!c.data.length}canFetchNextPage(c){return c.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class kn extends cx{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class Yn extends cx{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class pf extends cx{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class Xn extends cx{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class Vf extends cx{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class Un extends A{constructor(){super(...arguments);this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.users.push(...f.users),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class Hn extends A{constructor(){super(...arguments);this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.ids.push(...f.ids),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class Fn extends A{constructor(){super(...arguments);this._endpoint="followers/list.json"}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.users.push(...f.users),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class un extends A{constructor(){super(...arguments);this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.ids.push(...f.ids),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class Ln extends A{constructor(){super(...arguments);this._endpoint="friends/list.json"}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.users.push(...f.users),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class sn extends A{constructor(){super(...arguments);this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.ids.push(...f.ids),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class An extends ac{constructor(){super(...arguments);this._endpoint="users/search.json"}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.push(...f)}getNextQueryParams(c){var x;let f=Number((x=this._queryParams.page)!==null&&x!==void 0?x:"1");return{...this._queryParams,page:f+1,...c?{count:c}:{}}}getPageLengthFromRequest(c){return c.data.length}isFetchLastOver(c){return!c.data.length}canFetchNextPage(c){return c.length>0}getItemArray(){return this.users}get users(){return this._realData}}class lf extends A{constructor(){super(...arguments);this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.ids.push(...f.ids),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class In extends lf{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class Ef extends A{refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.lists.push(...f.lists),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class gn extends Ef{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class Cn extends Ef{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class Pn extends Ef{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class mn extends A{refreshInstanceFromResult(c,x){let f=c.data;if(this._rateLimit=c.rateLimit,x)this._realData.users.push(...f.users),this._realData.next_cursor=f.next_cursor}getPageLengthFromRequest(c){return c.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class Tn extends mn{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class _n extends mn{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class xx extends e{constructor(){super(...arguments);this._prefix=Nc}singleTweet(c,x={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:c,...x})}tweets(c,x={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:c,...x})}oembedTweet(c,x={}){return this.get("oembed",{url:`https://x.com/i/statuses/${c}`,...x},{prefix:"https://publish.x.com/"})}async homeTimeline(c={}){let x={tweet_mode:"extended",...c},f=await this.get("statuses/home_timeline.json",x,{fullResponse:!0});return new kn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async mentionTimeline(c={}){let x={tweet_mode:"extended",...c},f=await this.get("statuses/mentions_timeline.json",x,{fullResponse:!0});return new Yn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async userTimeline(c,x={}){let f={tweet_mode:"extended",user_id:c,...x},t=await this.get("statuses/user_timeline.json",f,{fullResponse:!0});return new pf({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:f})}async userTimelineByUsername(c,x={}){let f={tweet_mode:"extended",screen_name:c,...x},t=await this.get("statuses/user_timeline.json",f,{fullResponse:!0});return new pf({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:f})}async favoriteTimeline(c,x={}){let f={tweet_mode:"extended",user_id:c,...x},t=await this.get("favorites/list.json",f,{fullResponse:!0});return new Vf({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:f})}async favoriteTimelineByUsername(c,x={}){let f={tweet_mode:"extended",screen_name:c,...x},t=await this.get("favorites/list.json",f,{fullResponse:!0});return new Vf({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:f})}user(c){return this.get("users/show.json",{tweet_mode:"extended",...c})}users(c){return this.get("users/lookup.json",{tweet_mode:"extended",...c})}verifyCredentials(c={}){return this.get("account/verify_credentials.json",c)}async listMutedUsers(c={}){let x={tweet_mode:"extended",...c},f=await this.get("mutes/users/list.json",x,{fullResponse:!0});return new Un({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async listMutedUserIds(c={}){let x={stringify_ids:!0,...c},f=await this.get("mutes/users/ids.json",x,{fullResponse:!0});return new Hn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async userFriendList(c={}){let x={...c},f=await this.get("friends/list.json",x,{fullResponse:!0});return new Ln({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async userFollowerList(c={}){let x={...c},f=await this.get("followers/list.json",x,{fullResponse:!0});return new Fn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async userFollowerIds(c={}){let x={stringify_ids:!0,...c},f=await this.get("followers/ids.json",x,{fullResponse:!0});return new un({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async userFollowingIds(c={}){let x={stringify_ids:!0,...c},f=await this.get("friends/ids.json",x,{fullResponse:!0});return new sn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async searchUsers(c,x={}){let f={q:c,tweet_mode:"extended",page:1,...x},t=await this.get("users/search.json",f,{fullResponse:!0});return new An({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:f})}friendship(c){return this.get("friendships/show.json",c)}friendships(c){return this.get("friendships/lookup.json",c)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(c={}){let x={stringify_ids:!0,...c},f=await this.get("friendships/incoming.json",x,{fullResponse:!0});return new lf({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async friendshipsOutgoing(c={}){let x={stringify_ids:!0,...c},f=await this.get("friendships/outgoing.json",x,{fullResponse:!0});return new In({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(c){return this.get("users/profile_banner.json",c)}list(c){return this.get("lists/show.json",{tweet_mode:"extended",...c})}lists(c={}){return this.get("lists/list.json",{tweet_mode:"extended",...c})}async listMembers(c={}){let x={tweet_mode:"extended",...c},f=await this.get("lists/members.json",x,{fullResponse:!0});return new Tn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}listGetMember(c){return this.get("lists/members/show.json",{tweet_mode:"extended",...c})}async listMemberships(c={}){let x={tweet_mode:"extended",...c},f=await this.get("lists/memberships.json",x,{fullResponse:!0});return new gn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async listOwnerships(c={}){let x={tweet_mode:"extended",...c},f=await this.get("lists/ownerships.json",x,{fullResponse:!0});return new Cn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async listStatuses(c){let x={tweet_mode:"extended",...c},f=await this.get("lists/statuses.json",x,{fullResponse:!0});return new Xn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}async listSubscribers(c={}){let x={tweet_mode:"extended",...c},f=await this.get("lists/subscribers.json",x,{fullResponse:!0});return new _n({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}listGetSubscriber(c){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...c})}async listSubscriptions(c={}){let x={tweet_mode:"extended",...c},f=await this.get("lists/subscriptions.json",x,{fullResponse:!0});return new Pn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}mediaInfo(c){return this.get("media/upload.json",{command:"STATUS",media_id:c},{prefix:vc})}filterStream({autoConnect:c,...x}={}){let f={};for(let[n,h]of Object.entries(x))if(n==="follow"||n==="track")f[n]=h.toString();else if(n==="locations"){let v=h;f.locations=mf(v).map((S)=>`${S.lng},${S.lat}`).join(",")}else f[n]=h;return this.stream.postStream("statuses/filter.json",f,{autoConnect:c})}sampleStream({autoConnect:c,...x}={}){return this.stream.getStream("statuses/sample.json",x,{autoConnect:c})}get stream(){let c=new df(this);return c.setPrefix(M0),c}trendsByPlace(c,x={}){return this.get("trends/place.json",{id:c,...x})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(c,x){return this.get("trends/closest.json",{lat:c,long:x})}geoPlace(c){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:c}})}geoSearch(c){return this.get("geo/search.json",c)}geoReverseGeoCode(c){return this.get("geo/reverse_geocode.json",c)}rateLimitStatuses(...c){return this.get("application/rate_limit_status.json",{resources:c})}supportedLanguages(){return this.get("help/languages.json")}}import*as Rc from"fs";async function qn(c){let x=await pn(c);if(typeof x==="number")return new Promise((f,t)=>{Rc.readFile(x,(n,h)=>{if(n)return t(n);f(h)})});else if(x instanceof Buffer)return x;else return x.readFile()}function pn(c){if(typeof c==="string")return Rc.promises.open(c,"r");else if(typeof c==="number")return c;else if(typeof c==="object"&&!(c instanceof Buffer))return c;else if(!(c instanceof Buffer))throw Error("Given file is not valid, please check its type.");else return c}async function U0(c){if(typeof c==="number")return(await new Promise((f,t)=>{Rc.fstat(c,(n,h)=>{if(n)t(n);f(h)})})).size;else if(c instanceof Buffer)return c.length;else return(await c.stat()).size}function H0(c,x,f){if(typeof f==="string")return f;else if(typeof c==="string"&&!x)return Zb(c);else if(typeof x==="string")return Wb(x);throw Error("You must specify type if file is a file handle or Buffer.")}function Zb(c){if(c.endsWith(".jpeg")||c.endsWith(".jpg"))return k.Jpeg;if(c.endsWith(".png"))return k.Png;if(c.endsWith(".webp"))return k.Webp;if(c.endsWith(".gif"))return k.Gif;if(c.endsWith(".mpeg4")||c.endsWith(".mp4"))return k.Mp4;if(c.endsWith(".mov")||c.endsWith(".mov"))return k.Mov;if(c.endsWith(".srt"))return k.Srt;return Jn({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"}),k.Jpeg}function Wb(c){if(Jn({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"}),c==="gif")return k.Gif;if(c==="jpg")return k.Jpeg;if(c==="png")return k.Png;if(c==="webp")return k.Webp;if(c==="srt")return k.Srt;if(c==="mp4"||c==="longmp4")return k.Mp4;if(c==="mov")return k.Mov;return c}function F0(c,x){if(c===k.Mp4||c===k.Mov)return x==="tweet"?"TweetVideo":"DmVideo";if(c===k.Gif)return x==="tweet"?"TweetGif":"DmGif";if(c===k.Srt)return"Subtitles";else return x==="tweet"?"TweetImage":"DmImage"}function Vn(c){return new Promise((x)=>setTimeout(x,c*1000))}async function ln(c,x,f=0,t){if(c instanceof Buffer){let h=c.slice(f,f+x);return[h,h.length]}if(!t)throw Error("Well, we will need a buffer to store file content.");let n;if(typeof c==="number")n=await new Promise((h,v)=>{Rc.read(c,t,0,x,f,(S,w)=>{if(S)v(S);h(w)})});else n=(await c.read(t,0,x,f)).bytesRead;return[t,n]}var En="media/upload.json";class fx extends xx{constructor(){super(...arguments);this._prefix=Nc}get readOnly(){return this}tweet(c,x={}){let f={status:c,tweet_mode:"extended",...x};return this.post("statuses/update.json",f)}async quote(c,x,f={}){let t="https://x.com/i/statuses/"+x;return this.tweet(c,{...f,attachment_url:t})}async tweetThread(c){let x=[];for(let f of c){let t=x.length?x[x.length-1]:null,n={...typeof f==="string"?{status:f}:f},h=t?t.id_str:n.in_reply_to_status_id,v=n.status;if(h)x.push(await this.reply(v,h,n));else x.push(await this.tweet(v,n))}return x}reply(c,x,f={}){return this.tweet(c,{auto_populate_reply_metadata:!0,in_reply_to_status_id:x,...f})}deleteTweet(c){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:c}})}reportUserAsSpam(c){return this.post("users/report_spam.json",{tweet_mode:"extended",...c})}updateFriendship(c){return this.post("friendships/update.json",c)}createFriendship(c){return this.post("friendships/create.json",c)}destroyFriendship(c){return this.post("friendships/destroy.json",c)}updateAccountSettings(c){return this.post("account/settings.json",c)}updateAccountProfile(c){return this.post("account/update_profile.json",c)}async updateAccountProfileBanner(c,x={}){let f={banner:await qn(c),...x};return this.post("account/update_profile_banner.json",f,{forceBodyMode:"form-data"})}async updateAccountProfileImage(c,x={}){let f={tweet_mode:"extended",image:await qn(c),...x};return this.post("account/update_profile_image.json",f,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(c){return this.post("lists/create.json",{tweet_mode:"extended",...c})}updateList(c){return this.post("lists/update.json",{tweet_mode:"extended",...c})}removeList(c){return this.post("lists/destroy.json",{tweet_mode:"extended",...c})}addListMembers(c){let f=c.user_id&&ux(c.user_id)||c.screen_name&&ux(c.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post(f,c)}removeListMembers(c){let f=c.user_id&&ux(c.user_id)||c.screen_name&&ux(c.screen_name)?"lists/members/destroy_all.json":"lists/members/destroy.json";return this.post(f,c)}subscribeToList(c){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...c})}unsubscribeOfList(c){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...c})}createMediaMetadata(c,x){return this.post("media/metadata/create.json",{media_id:c,...x},{prefix:vc,forceBodyMode:"json"})}createMediaSubtitles(c,x){return this.post("media/subtitles/create.json",{media_id:c,media_category:"TweetVideo",subtitle_info:{subtitles:x}},{prefix:vc,forceBodyMode:"json"})}deleteMediaSubtitles(c,...x){return this.post("media/subtitles/delete.json",{media_id:c,media_category:"TweetVideo",subtitle_info:{subtitles:x.map((f)=>({language_code:f}))}},{prefix:vc,forceBodyMode:"json"})}async uploadMedia(c,x={},f=!1){var t;let n=(t=x.chunkLength)!==null&&t!==void 0?t:1048576,{fileHandle:h,mediaCategory:v,fileSize:S,mimeType:w}=await this.getUploadMediaRequirements(c,x);try{let b=await this.post(En,{command:"INIT",total_bytes:S,media_type:w,media_category:v,additional_owners:x.additionalOwners,shared:x.shared?!0:void 0},{prefix:vc});await this.mediaChunkedUpload(h,n,b.media_id_string,x.maxConcurrentUploads);let B=await this.post(En,{command:"FINALIZE",media_id:b.media_id_string},{prefix:vc});if(B.processing_info&&B.processing_info.state!=="succeeded")await this.awaitForMediaProcessingCompletion(B);if(f)return B;else return B.media_id_string}finally{if(typeof c==="number")dn.close(c,()=>{});else if(typeof h==="object"&&!(h instanceof Buffer))h.close()}}async awaitForMediaProcessingCompletion(c){var x;while(!0){c=await this.mediaInfo(c.media_id_string);let{processing_info:f}=c;if(!f||f.state==="succeeded")return;if((x=f.error)===null||x===void 0?void 0:x.code){let{name:t,message:n}=f.error;throw Error(`Failed to process media: ${t} - ${n}.`)}if(f.state==="failed")throw Error("Failed to process the media.");if(f.check_after_secs)await Vn(f.check_after_secs);else await Vn(5)}}async getUploadMediaRequirements(c,{mimeType:x,type:f,target:t,longVideo:n}={}){let h;try{h=await pn(c);let v=H0(c,f,x),S;if(v===k.Mp4&&(!x&&!f&&t!=="dm"||n))S="amplify_video";else S=F0(v,t!==null&&t!==void 0?t:"tweet");return{fileHandle:h,mediaCategory:S,fileSize:await U0(h),mimeType:v}}catch(v){if(typeof c==="number")dn.close(c,()=>{});else if(typeof h==="object"&&!(h instanceof Buffer))h.close();throw v}}async mediaChunkedUpload(c,x,f,t=3){let n=0;if(t<1)throw RangeError("Bad maxConcurrentUploads parameter.");let h=c instanceof Buffer?void 0:Buffer.alloc(x),v,S,w=0;[v,S]=await ln(c,x,w,h),w+=S;let b=new Set;while(S){let B=v.slice(0,S);if(B.length){let $=this.post(En,{command:"APPEND",media_id:f,segment_index:n,media:B},{prefix:vc});b.add($),$.then(()=>{b.delete($)}),n++}if(b.size>=t)await Promise.race(b);[v,S]=await ln(c,x,w,h),w+=S}await Promise.all([...b])}}class u0 extends fx{constructor(){super(...arguments);this._prefix=Nc}get readWrite(){return this}sendDm({recipient_id:c,custom_profile_id:x,...f}){let t={event:{type:Zc.Create,[Zc.Create]:{target:{recipient_id:c},message_data:f}}};if(x)t.event[Zc.Create].custom_profile_id=x;return this.post("direct_messages/events/new.json",t,{forceBodyMode:"json"})}getDmEvent(c){return this.get("direct_messages/events/show.json",{id:c})}deleteDm(c){return this.delete("direct_messages/events/destroy.json",{id:c})}async listDmEvents(c={}){let x={...c},f=await this.get("direct_messages/events/list.json",x,{fullResponse:!0});return new Kn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}newWelcomeDm(c,x){let f={[Zc.WelcomeCreate]:{name:c,message_data:x}};return this.post("direct_messages/welcome_messages/new.json",f,{forceBodyMode:"json"})}getWelcomeDm(c){return this.get("direct_messages/welcome_messages/show.json",{id:c})}deleteWelcomeDm(c){return this.delete("direct_messages/welcome_messages/destroy.json",{id:c})}updateWelcomeDm(c,x){let f={message_data:x};return this.put("direct_messages/welcome_messages/update.json",f,{forceBodyMode:"json",query:{id:c}})}async listWelcomeDms(c={}){let x={...c},f=await this.get("direct_messages/welcome_messages/list.json",x,{fullResponse:!0});return new On({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x})}newWelcomeDmRule(c){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:c}},{forceBodyMode:"json"})}getWelcomeDmRule(c){return this.get("direct_messages/welcome_messages/rules/show.json",{id:c})}deleteWelcomeDmRule(c){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:c})}async listWelcomeDmRules(c={}){let x={...c};return this.get("direct_messages/welcome_messages/rules/list.json",x)}async setWelcomeDm(c,x=!0){var f;let t=await this.listWelcomeDmRules();if((f=t.welcome_message_rules)===null||f===void 0?void 0:f.length){for(let n of t.welcome_message_rules)if(await this.deleteWelcomeDmRule(n.id),x)await this.deleteWelcomeDm(n.welcome_message_id)}return this.newWelcomeDmRule(c)}markDmAsRead(c,x){return this.post("direct_messages/mark_read.json",{last_read_event_id:c,recipient_id:x},{forceBodyMode:"url"})}indicateDmTyping(c){return this.post("direct_messages/indicate_typing.json",{recipient_id:c},{forceBodyMode:"url"})}async downloadDmImage(c){if(typeof c!=="string"){let f=c[Zc.Create].message_data.attachment;if(!f)throw Error("The given direct message doesn't contain any attachment");c=f.media.media_url_https}let x=await this.get(c,void 0,{forceParseMode:"buffer",prefix:""});if(!x.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return x}}var df=u0;class Q{constructor(c){this.result=c}get tweets(){return Q.tweets(this.result)}static tweets(c){var x,f;return(f=(x=c.includes)===null||x===void 0?void 0:x.tweets)!==null&&f!==void 0?f:[]}tweetById(c){return Q.tweetById(this.result,c)}static tweetById(c,x){return this.tweets(c).find((f)=>f.id===x)}retweet(c){return Q.retweet(this.result,c)}static retweet(c,x){var f;let t=((f=x.referenced_tweets)!==null&&f!==void 0?f:[]).filter((n)=>n.type==="retweeted").map((n)=>n.id);return this.tweets(c).find((n)=>t.includes(n.id))}quote(c){return Q.quote(this.result,c)}static quote(c,x){var f;let t=((f=x.referenced_tweets)!==null&&f!==void 0?f:[]).filter((n)=>n.type==="quoted").map((n)=>n.id);return this.tweets(c).find((n)=>t.includes(n.id))}repliedTo(c){return Q.repliedTo(this.result,c)}static repliedTo(c,x){var f;let t=((f=x.referenced_tweets)!==null&&f!==void 0?f:[]).filter((n)=>n.type==="replied_to").map((n)=>n.id);return this.tweets(c).find((n)=>t.includes(n.id))}author(c){return Q.author(this.result,c)}static author(c,x){let f=x.author_id;return f?this.users(c).find((t)=>t.id===f):void 0}repliedToAuthor(c){return Q.repliedToAuthor(this.result,c)}static repliedToAuthor(c,x){let f=x.in_reply_to_user_id;return f?this.users(c).find((t)=>t.id===f):void 0}get users(){return Q.users(this.result)}static users(c){var x,f;return(f=(x=c.includes)===null||x===void 0?void 0:x.users)!==null&&f!==void 0?f:[]}userById(c){return Q.userById(this.result,c)}static userById(c,x){return this.users(c).find((f)=>f.id===x)}pinnedTweet(c){return Q.pinnedTweet(this.result,c)}static pinnedTweet(c,x){return x.pinned_tweet_id?this.tweets(c).find((f)=>f.id===x.pinned_tweet_id):void 0}get media(){return Q.media(this.result)}static media(c){var x,f;return(f=(x=c.includes)===null||x===void 0?void 0:x.media)!==null&&f!==void 0?f:[]}medias(c){return Q.medias(this.result,c)}static medias(c,x){var f,t;let n=(t=(f=x.attachments)===null||f===void 0?void 0:f.media_keys)!==null&&t!==void 0?t:[];return this.media(c).filter((h)=>n.includes(h.media_key))}get polls(){return Q.polls(this.result)}static polls(c){var x,f;return(f=(x=c.includes)===null||x===void 0?void 0:x.polls)!==null&&f!==void 0?f:[]}poll(c){return Q.poll(this.result,c)}static poll(c,x){var f,t;let n=(t=(f=x.attachments)===null||f===void 0?void 0:f.poll_ids)!==null&&t!==void 0?t:[];if(n.length){let h=n[0];return this.polls(c).find((v)=>v.id===h)}return}get places(){return Q.places(this.result)}static places(c){var x,f;return(f=(x=c.includes)===null||x===void 0?void 0:x.places)!==null&&f!==void 0?f:[]}place(c){return Q.place(this.result,c)}static place(c,x){var f;let t=(f=x.geo)===null||f===void 0?void 0:f.place_id;return t?this.places(c).find((n)=>n.id===t):void 0}listOwner(c){return Q.listOwner(this.result,c)}static listOwner(c,x){let f=x.owner_id;return f?this.users(c).find((t)=>t.id===f):void 0}spaceCreator(c){return Q.spaceCreator(this.result,c)}static spaceCreator(c,x){let f=x.creator_id;return f?this.users(c).find((t)=>t.id===f):void 0}spaceHosts(c){return Q.spaceHosts(this.result,c)}static spaceHosts(c,x){var f;let t=(f=x.host_ids)!==null&&f!==void 0?f:[];return this.users(c).filter((n)=>t.includes(n.id))}spaceSpeakers(c){return Q.spaceSpeakers(this.result,c)}static spaceSpeakers(c,x){var f;let t=(f=x.speaker_ids)!==null&&f!==void 0?f:[];return this.users(c).filter((n)=>t.includes(n.id))}spaceInvitedUsers(c){return Q.spaceInvitedUsers(this.result,c)}static spaceInvitedUsers(c,x){var f;let t=(f=x.invited_user_ids)!==null&&f!==void 0?f:[];return this.users(c).filter((n)=>t.includes(n.id))}}class of extends jn{updateIncludes(c){if(c.errors){if(!this._realData.errors)this._realData.errors=[];this._realData.errors=[...this._realData.errors,...c.errors]}if(!c.includes)return;if(!this._realData.includes)this._realData.includes={};let x=this._realData.includes;for(let[f,t]of Object.entries(c.includes)){if(!x[f])x[f]=[];x[f]=[...x[f],...t]}}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 c;if(!((c=this._realData)===null||c===void 0?void 0:c.includes))return new Q(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new Q(this._realData)}get errors(){var c;return(c=this._realData.errors)!==null&&c!==void 0?c:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class nc extends of{refreshInstanceFromResult(c,x){var f;let t=c.data,n=(f=t.data)!==null&&f!==void 0?f:[];if(this._rateLimit=c.rateLimit,!this._realData.data)this._realData.data=[];if(x)this._realData.meta.result_count+=t.meta.result_count,this._realData.meta.next_token=t.meta.next_token,this._realData.data.push(...n);else this._realData.meta.result_count+=t.meta.result_count,this._realData.meta.previous_token=t.meta.previous_token,this._realData.data.unshift(...n);this.updateIncludes(t)}getNextQueryParams(c){return this.assertUsable(),{...this.injectQueryParams(c),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(c){return this.assertUsable(),{...this.injectQueryParams(c),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(c){var x,f;return(f=(x=c.data.data)===null||x===void 0?void 0:x.length)!==null&&f!==void 0?f:0}isFetchLastOver(c){var x;return!((x=c.data.data)===null||x===void 0?void 0:x.length)||!this.canFetchNextPage(c.data)}canFetchNextPage(c){var x;return!!((x=c.meta)===null||x===void 0?void 0:x.next_token)}}class on extends of{refreshInstanceFromResult(c,x){var f;let t=c.data,n=(f=t.data)!==null&&f!==void 0?f:[];if(this._rateLimit=c.rateLimit,!this._realData.data)this._realData.data=[];if(x)this._realData.meta.oldest_id=t.meta.oldest_id,this._realData.meta.result_count+=t.meta.result_count,this._realData.meta.next_token=t.meta.next_token,this._realData.data.push(...n);else this._realData.meta.newest_id=t.meta.newest_id,this._realData.meta.result_count+=t.meta.result_count,this._realData.data.unshift(...n);this.updateIncludes(t)}getNextQueryParams(c){this.assertUsable();let x={...this.injectQueryParams(c)};if(this._realData.meta.next_token)x.next_token=this._realData.meta.next_token;else{if(x.start_time)x.since_id=this.dateStringToSnowflakeId(x.start_time),delete x.start_time;if(x.end_time)delete x.end_time;x.until_id=this._realData.meta.oldest_id}return x}getPreviousQueryParams(c){return this.assertUsable(),{...this.injectQueryParams(c),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(c){var x,f;return(f=(x=c.data.data)===null||x===void 0?void 0:x.length)!==null&&f!==void 0?f:0}isFetchLastOver(c){var x;return!((x=c.data.data)===null||x===void 0?void 0:x.length)||!this.canFetchNextPage(c.data)}canFetchNextPage(c){return!!c.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(c){let x=BigInt("1288834974657"),f=new Date(c);if(isNaN(f.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(f.valueOf())-x<<BigInt("22")).toString()}get tweets(){var c;return(c=this._realData.data)!==null&&c!==void 0?c:[]}get meta(){return super.meta}}class tx extends nc{refreshInstanceFromResult(c,x){super.refreshInstanceFromResult(c,x);let f=c.data;if(x)this._realData.meta.oldest_id=f.meta.oldest_id;else this._realData.meta.newest_id=f.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var c;return(c=this._realData.data)!==null&&c!==void 0?c:[]}get meta(){return super.meta}}class en extends on{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class an extends on{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class rn extends tx{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class ch extends tx{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class xh extends tx{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class fh extends tx{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class th extends tx{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class nh extends nc{get tweets(){var c;return(c=this._realData.data)!==null&&c!==void 0?c:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class hh extends nh{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class vh extends nh{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class Sc extends nc{getItemArray(){return this.users}get users(){var c;return(c=this._realData.data)!==null&&c!==void 0?c:[]}get meta(){return super.meta}}class Sh extends Sc{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class wh extends Sc{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class bh extends Sc{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class yh extends Sc{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class Bh extends Sc{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class $h extends Sc{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class Gh extends Sc{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class Mh extends Sc{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class ef extends nc{getItemArray(){return this.lists}get lists(){var c;return(c=this._realData.data)!==null&&c!==void 0?c:[]}get meta(){return super.meta}}class zh extends ef{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class Nh extends ef{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class Zh extends ef{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class nx extends e{constructor(){super(...arguments);this._prefix=ic}}class af extends nc{getItemArray(){return this.events}get events(){var c;return(c=this._realData.data)!==null&&c!==void 0?c:[]}get meta(){return super.meta}}class Wh extends af{constructor(){super(...arguments);this._endpoint="dm_events"}}class Rh extends af{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class jh extends af{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class hx extends e{constructor(){super(...arguments);this._prefix=zc}get labs(){if(this._labs)return this._labs;return this._labs=new nx(this)}async search(c,x={}){let f=typeof c==="string"?{...x,query:c}:{...c},t=await this.get("tweets/search/recent",f,{fullResponse:!0});return new en({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:f})}async searchAll(c,x={}){let f={...x,query:c},t=await this.get("tweets/search/all",f,{fullResponse:!0});return new an({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:f})}singleTweet(c,x={}){return this.get("tweets/:id",x,{params:{id:c}})}tweets(c,x={}){return this.get("tweets",{ids:c,...x})}tweetCountRecent(c,x={}){return this.get("tweets/counts/recent",{query:c,...x})}tweetCountAll(c,x={}){return this.get("tweets/counts/all",{query:c,...x})}async tweetRetweetedBy(c,x={}){let{asPaginator:f,...t}=x,n=await this.get("tweets/:id/retweeted_by",t,{fullResponse:!0,params:{id:c}});if(!f)return n.data;return new Mh({realData:n.data,rateLimit:n.rateLimit,instance:this,queryParams:t,sharedParams:{id:c}})}async tweetLikedBy(c,x={}){let{asPaginator:f,...t}=x,n=await this.get("tweets/:id/liking_users",t,{fullResponse:!0,params:{id:c}});if(!f)return n.data;return new Gh({realData:n.data,rateLimit:n.rateLimit,instance:this,queryParams:t,sharedParams:{id:c}})}async homeTimeline(c={}){let x=await this.getCurrentUserV2Object(),f=await this.get("users/:id/timelines/reverse_chronological",c,{fullResponse:!0,params:{id:x.data.id}});return new ch({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:c,sharedParams:{id:x.data.id}})}async userTimeline(c,x={}){let f=await this.get("users/:id/tweets",x,{fullResponse:!0,params:{id:c}});return new xh({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x,sharedParams:{id:c}})}async userMentionTimeline(c,x={}){let f=await this.get("users/:id/mentions",x,{fullResponse:!0,params:{id:c}});return new fh({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x,sharedParams:{id:c}})}async quotes(c,x={}){let f=await this.get("tweets/:id/quote_tweets",x,{fullResponse:!0,params:{id:c}});return new rn({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:x,sharedParams:{id:c}})}async bookmarks(c={}){let x=await this.getCurrentUserV2Object(),f=await this.get("users/:id/bookmarks",c,{fullResponse:!0,params:{id:x.data.id}});return new th({realData:f.data,rateLimit:f.rateLimit,instance:this,queryParams:c,sharedParams:{id:x.data.id}})}me(c={}){return this.get("users/me",c)}user(c,x={}){return this.get("users/:id",x,{params:{id:c}})}users(c,x={}){let f=Array.isArray(c)?c.join(","):c;return this.get("users",{...x,ids:f})}userByUsername(c,x={}){return this.get("users/by/username/:username",x,{params:{username:c}})}usersByUsernames(c,x={}){return c=Array.isArray(c)?c.join(","):c,this.get("users/by",{...x,usernames:c})}async followers(c,x={}){let{asPaginator:f,...t}=x,n={id:c};if(!f)return this.get("users/:id/followers",t,{params:n});let h=await this.get("users/:id/followers",t,{fullResponse:!0,params:n});return new bh({realData:h.data,rateLimit:h.rateLimit,instance:this,queryParams:t,sharedParams:n})}async following(c,x={}){let{asPaginator:f,...t}=x,n={id:c};if(!f)return this.get("users/:id/following",t,{params:n});let h=await this.get("users/:id/following",t,{fullResponse:!0,params:n});return new yh({realData:h.data,rateLimit:h.rateLimit,instance:this,queryParams:t,sharedParams:n})}async userLikedTweets(c,x={}){let f={id:c},t=await this.get("users/:id/liked_tweets",x,{fullResponse:!0,params:f});return new hh({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}async userBlockingUsers(c,x={}){let f={id:c},t=await this.get("users/:id/blocking",x,{fullResponse:!0,params:f});return new Sh({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}async userMutingUsers(c,x={}){let f={id:c},t=await this.get("users/:id/muting",x,{fullResponse:!0,params:f});return new wh({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}list(c,x={}){return this.get("lists/:id",x,{params:{id:c}})}async listsOwned(c,x={}){let f={id:c},t=await this.get("users/:id/owned_lists",x,{fullResponse:!0,params:f});return new zh({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}async listMemberships(c,x={}){let f={id:c},t=await this.get("users/:id/list_memberships",x,{fullResponse:!0,params:f});return new Nh({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}async listFollowed(c,x={}){let f={id:c},t=await this.get("users/:id/followed_lists",x,{fullResponse:!0,params:f});return new Zh({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}async listTweets(c,x={}){let f={id:c},t=await this.get("lists/:id/tweets",x,{fullResponse:!0,params:f});return new vh({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}async listMembers(c,x={}){let f={id:c},t=await this.get("lists/:id/members",x,{fullResponse:!0,params:f});return new Bh({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}async listFollowers(c,x={}){let f={id:c},t=await this.get("lists/:id/followers",x,{fullResponse:!0,params:f});return new $h({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}async listDmEvents(c={}){let x=await this.get("dm_events",c,{fullResponse:!0});return new Wh({realData:x.data,rateLimit:x.rateLimit,instance:this,queryParams:{...c}})}async listDmEventsWithParticipant(c,x={}){let f={participant_id:c},t=await this.get("dm_conversations/with/:participant_id/dm_events",x,{fullResponse:!0,params:f});return new Rh({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}async listDmEventsOfConversation(c,x={}){let f={dm_conversation_id:c},t=await this.get("dm_conversations/:dm_conversation_id/dm_events",x,{fullResponse:!0,params:f});return new jh({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...x},sharedParams:f})}space(c,x={}){return this.get("spaces/:id",x,{params:{id:c}})}spaces(c,x={}){return this.get("spaces",{ids:c,...x})}spacesByCreators(c,x={}){return this.get("spaces/by/creator_ids",{user_ids:c,...x})}searchSpaces(c){return this.get("spaces/search",c)}spaceBuyers(c,x={}){return this.get("spaces/:id/buyers",x,{params:{id:c}})}spaceTweets(c,x={}){return this.get("spaces/:id/tweets",x,{params:{id:c}})}searchStream({autoConnect:c,...x}={}){return this.getStream("tweets/search/stream",x,{payloadIsError:Tf,autoConnect:c})}streamRules(c={}){return this.get("tweets/search/stream/rules",c)}updateStreamRules(c,x={}){return this.post("tweets/search/stream/rules",c,{query:x})}sampleStream({autoConnect:c,...x}={}){return this.getStream("tweets/sample/stream",x,{payloadIsError:Tf,autoConnect:c})}sample10Stream({autoConnect:c,...x}={}){return this.getStream("tweets/sample10/stream",x,{payloadIsError:Tf,autoConnect:c})}complianceJobs(c){return this.get("compliance/jobs",c)}complianceJob(c){return this.get("compliance/jobs/:id",void 0,{params:{id:c}})}async sendComplianceJob(c){let x=await this.post("compliance/jobs",{type:c.type,name:c.name}),f=c.ids instanceof Buffer?c.ids:Buffer.from(c.ids.join(`
43
- `));return await this.put(x.data.upload_url,f,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),x}async complianceJobResult(c){let x=c;while(x.status!=="complete"){if(x.status==="expired"||x.status==="failed")throw Error("Job failed to be completed.");await new Promise((t)=>setTimeout(t,3500)),x=(await this.complianceJob(c.id)).data}return(await this.get(c.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split(`
44
- `).filter((t)=>t).map((t)=>JSON.parse(t))}async usage(c={}){return this.get("usage/tweets",c)}community(c,x={}){return this.get("communities/:id",x,{params:{id:c}})}searchCommunities(c,x={}){return this.get("communities/search",{query:c,...x})}}class vx extends nx{constructor(){super(...arguments);this._prefix=ic}get readOnly(){return this}}class Sx extends hx{constructor(){super(...arguments);this._prefix=zc}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new vx(this)}hideReply(c,x){return this.put("tweets/:id/hidden",{hidden:x},{params:{id:c}})}like(c,x){return this.post("users/:id/likes",{tweet_id:x},{params:{id:c}})}unlike(c,x){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:c,tweet_id:x}})}retweet(c,x){return this.post("users/:id/retweets",{tweet_id:x},{params:{id:c}})}unretweet(c,x){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:c,tweet_id:x}})}tweet(c,x={}){if(typeof c==="object")x=c;else x={text:c,...x};return this.post("tweets",x)}async uploadMedia(c,x,f=1048576){let t=x.media_category;if(!x.media_category){if(x.media_type.includes("gif"))t="tweet_gif";else if(x.media_type.includes("image"))t="tweet_image";else if(x.media_type.includes("video"))t="tweet_video"}let n={additional_owners:x.additional_owners,media_type:x.media_type,total_bytes:c.length,media_category:t},v=(await this.post("media/upload/initialize",n)).data.id,S=Math.ceil(c.length/f),w=new Uint8Array(c);for(let B=0;B<S;B++){let $=B*f,N=Math.min($+f,c.length),j=w.slice($,N),I=Buffer.from(j),T={segment_index:B,media:I};await this.post(`media/upload/${v}/append`,T,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${v}/finalize`)).data.processing_info)await this.waitForMediaProcessing(v);return v}async waitForMediaProcessing(c){var x;let t=(await this.get("media/upload",{command:"STATUS",media_id:c})).data.processing_info;if(!t)return;switch(t.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(x=t.error)===null||x===void 0?void 0:x.message}`);case"pending":case"in_progress":{let n=t===null||t===void 0?void 0:t.check_after_secs;if(n&&n>0)await new Promise((h)=>setTimeout(h,n*1000)),await this.waitForMediaProcessing(c)}}}createMediaMetadata(c,x){return this.post("media/metadata",{id:c,metadata:x})}reply(c,x,f={}){var t;let n={in_reply_to_tweet_id:x,...(t=f.reply)!==null&&t!==void 0?t:{}};return this.post("tweets",{text:c,...f,reply:n})}quote(c,x,f={}){return this.tweet(c,{...f,quote_tweet_id:x})}async tweetThread(c){var x,f;let t=[];for(let n of c){let h=t.length?t[t.length-1]:null,v={...typeof n==="string"?{text:n}:n},S=h?h.data.id:(x=v.reply)===null||x===void 0?void 0:x.in_reply_to_tweet_id,w=(f=v.text)!==null&&f!==void 0?f:"";if(S)t.push(await this.reply(w,S,v));else t.push(await this.tweet(w,v))}return t}deleteTweet(c){return this.delete("tweets/:id",void 0,{params:{id:c}})}async bookmark(c){let x=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:c},{params:{id:x.data.id}})}async deleteBookmark(c){let x=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:x.data.id,tweet_id:c}})}follow(c,x){return this.post("users/:id/following",{target_user_id:x},{params:{id:c}})}unfollow(c,x){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:c,target_user_id:x}})}block(c,x){return this.post("users/:id/blocking",{target_user_id:x},{params:{id:c}})}unblock(c,x){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:c,target_user_id:x}})}mute(c,x){return this.post("users/:id/muting",{target_user_id:x},{params:{id:c}})}unmute(c,x){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:c,target_user_id:x}})}createList(c){return this.post("lists",c)}updateList(c,x={}){return this.put("lists/:id",x,{params:{id:c}})}removeList(c){return this.delete("lists/:id",void 0,{params:{id:c}})}addListMember(c,x){return this.post("lists/:id/members",{user_id:x},{params:{id:c}})}removeListMember(c,x){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:c,user_id:x}})}subscribeToList(c,x){return this.post("users/:id/followed_lists",{list_id:x},{params:{id:c}})}unsubscribeOfList(c,x){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:c,list_id:x}})}pinList(c,x){return this.post("users/:id/pinned_lists",{list_id:x},{params:{id:c}})}unpinList(c,x){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:c,list_id:x}})}sendDmInConversation(c,x){return this.post("dm_conversations/:dm_conversation_id/messages",x,{params:{dm_conversation_id:c}})}sendDmToParticipant(c,x){return this.post("dm_conversations/with/:participant_id/messages",x,{params:{participant_id:c}})}createDmConversation(c){return this.post("dm_conversations",c)}}class L0 extends vx{constructor(){super(...arguments);this._prefix=ic}get readWrite(){return this}}var s0=L0;class A0 extends Sx{constructor(){super(...arguments);this._prefix=zc}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new s0(this)}}var I0=A0;class Ax extends Wc{get v1(){if(this._v1)return this._v1;return this._v1=new xx(this)}get v2(){if(this._v2)return this._v2;return this._v2=new hx(this)}async currentUser(c=!1){return await this.getCurrentUserObject(c)}async currentUserV2(c=!1){return await this.getCurrentUserV2Object(c)}search(c,x){return this.v2.search(c,x)}async generateAuthLink(c="oob",{authAccessType:x,linkMode:f="authenticate",forceLogin:t,screenName:n}={}){let h=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:c,x_auth_access_type:x}),v=`https://api.x.com/oauth/${f}?oauth_token=${encodeURIComponent(h.oauth_token)}`;if(t!==void 0)v+=`&force_login=${encodeURIComponent(t)}`;if(n!==void 0)v+=`&screen_name=${encodeURIComponent(n)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:v,oauthResult:h});return{url:v,...h}}async login(c){let x=this.getActiveTokens();if(x.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let f=await this.post("https://api.x.com/oauth/access_token",{oauth_token:x.accessToken,oauth_verifier:c}),t=new this.constructor({appKey:x.appKey,appSecret:x.appSecret,accessToken:f.oauth_token,accessSecret:f.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:f.oauth_token,accessSecret:f.oauth_token_secret,userId:f.user_id,screenName:f.screen_name,client:t}}async appLogin(){let c=this.getActiveTokens();if(c.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let f=await new this.constructor({username:c.appKey,password:c.appSecret},this._requestMaker.clientSettings).post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor(f.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(c,x={}){var f,t;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 n=(f=x.state)!==null&&f!==void 0?f:Fc.generateRandomString(32),h=Fc.getCodeVerifier(),v=Fc.getCodeChallengeFromVerifier(h),S=(t=x.scope)!==null&&t!==void 0?t:"",w=Array.isArray(S)?S.join(" "):S,b=new URL("https://x.com/i/oauth2/authorize"),B={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:c,state:n,code_challenge:v,code_challenge_method:"s256",scope:w};o.addQueryParamsToUrl(b,B);let $={url:b.toString(),state:n,codeVerifier:h,codeChallenge:v};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:$,redirectUri:c});return $}async loginWithOAuth2({code:c,codeVerifier:x,redirectUri:f}){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 t=await this.post("https://api.x.com/2/oauth2/token",{code:c,code_verifier:x,redirect_uri:f,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(t)}async refreshOAuth2Token(c){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 x=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:c,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(x)}async revokeOAuth2Token(c,x="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:c,token_type_hint:x})}parseOAuth2AccessTokenResult(c){let x=new this.constructor(c.access_token,this._requestMaker.clientSettings),f=c.scope.split(" ").filter((t)=>t);return{client:x,expiresIn:c.expires_in,accessToken:c.access_token,scope:f,refreshToken:c.refresh_token}}}class Ix extends Ax{get v1(){if(this._v1)return this._v1;return this._v1=new fx(this)}get v2(){if(this._v2)return this._v2;return this._v2=new Sx(this)}get readOnly(){return this}}class rf extends e{constructor(){super(...arguments);this._prefix=oc}}class ct extends rf{constructor(){super(...arguments);this._prefix=oc}get readOnly(){return this}}class xt extends e{constructor(){super(...arguments);this._prefix=ec}}class ft extends xt{constructor(){super(...arguments);this._prefix=ec}get readOnly(){return this}}class g0 extends ft{constructor(){super(...arguments);this._prefix=ec}get readWrite(){return this}}var C0=g0;class P0 extends ct{constructor(){super(...arguments);this._prefix=oc}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new C0(this)}}var m0=P0;class Kh extends Ix{get v1(){if(this._v1)return this._v1;return this._v1=new df(this)}get v2(){if(this._v2)return this._v2;return this._v2=new I0(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new m0(this)}static getErrors(c){var x;if(typeof c!=="object")return[];if(!("data"in c))return[];return(x=c.data.errors)!==null&&x!==void 0?x:[]}static getProfileImageInSize(c,x){let f=c.split("/").pop(),t=["normal","bigger","mini"],n=c;for(let v of t)if(f.includes(`_${v}`)){n=c.replace(`_${v}`,"");break}if(x==="original")return n;let h=n.lastIndexOf(".");if(h!==-1){let v=n.slice(h+1);return n.slice(0,h)+"_"+x+"."+v}else return n+"_"+x}}var Rb={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class _0 extends dc{config;client;oauthStates=new Map;constructor(c={}){super();this.config={...Rb,...c},this.client=new Kh({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}getRedirectUrl(){let{url:c,codeVerifier:x,state:f}=this.client.generateOAuth2AuthLink(`${process.env.HOST_NAME}${this.config.redirectPath}`,{scope:this.config.scope});return this.oauthStates.set(f,{state:f,codeVerifier:x}),T0.to(c),c}async onCallback(c){let x=c.search.get("code"),f=c.search.get("state"),t=this.oauthStates.get(f);if(!t)throw Error("Invalid or expired OAuth state");let n=await this.client.loginWithOAuth2({code:x,codeVerifier:t.codeVerifier,redirectUri:`${process.env.HOST_NAME}${this.config.redirectPath}`});this.oauthStates.delete(f);let{data:h}=await n.client.v2.me({"user.fields":["name","username","entities"]}),{name:v,email:S,id:w="",username:b}=h??{};return{name:v,email:S,username:b,providerId:w}}}export{mb as viewRouteConfigDefaults,fy as translationConfigDefaults,zn as toRangeHeaderValue,yy as scheduleConfigDefaults,Zn as resolveRange,Ly as redisConfigDefaults,Hy as rateLimiterConfigDefaults,ab as queueConfigDefaults,Qx as parseContentRange,Kb as middlewareConfigDefaults,db as mailConfigDefaults,Ky as logConfigDefaults,sb as imageConfigDefaults,Ub as filesystemConfigDefaults,$y as discoverJobs,Gy as discoverCronJobs,My as discoverCommands,xy as defineTranslationConfig,by as defineScheduleConfig,Cb as defineRouteConfig,uy as defineRedisConfig,Uy as defineRateLimiterConfig,eb as defineQueueConfig,jb as defineMiddlewareConfig,Eb as defineMailConfig,jy as defineLogConfig,Lb as defineImageConfig,Xb as defineFilesystemConfig,hy as defineCommandConfig,Sy as defineCommand,Jy as defineBroadcastConfig,Ob as defineAuthConfig,vy as commandConfigDefaults,Qy as broadcastConfigDefaults,Db as authConfigDefaults,Pb as apiRouteConfigDefaults,_0 as XOAuthProvider,_b as ViewRouteDispatcher,ub as Sharp,ob as Scheduler,zy as ScheduleServiceProvider,h0 as S3Driver,Ay as RouteServiceProvider,lb as ResendDriver,sy as RedisServiceProvider,$0 as RedisRateLimiter,pb as RedisManager,Fy as RateLimiterServiceProvider,Wn as RateLimiterDriver,Qb as RateLimiter,Ec as RangeNotSatisfiableError,Yy as QueueServiceProvider,rb as QueueManager,dc as OAuthProvider,Dy as MiddlewareServiceProvider,gb as MiddlewareRegistry,Ny as MailServiceProvider,ib as MailManager,Oy as LogServiceProvider,Ib as LogManager,Ry as KernelIdServiceProvider,Tb as KernelId,By as Job,Xy as InMemoryRateLimiter,Wy as ImageServiceProvider,Fb as ImageOptimizationDriver,Ab as ImageManager,G0 as GoogleOAuthProvider,Zy as FilesystemServiceProvider,Hb as FilesystemManager,Yb as FileSystemDriver,kx as FileStorageDriver,Mc as FileNotFoundError,Vb as EmailDriver,wy as CronJob,Iy as CommandRegistry,ty as CommandFailed,ny as Command,ky as BroadcastServiceProvider,kb as BroadcastManager,S0 as AzureBlobDriver,cy as AuthServiceProvider,Jb as AuthManager,qb as ApiRouteDispatcher};
29
+ `;class u4 extends T1{injectedClient;prefix;failOpen;onError;scriptSha=null;constructor(G={}){super();this.injectedClient=G.client,this.prefix=G.prefix??"gemi:rl",this.failOpen=G.failOpen??!0,this.onError=G.onError??((W)=>console.error(W))}async consume(G){let{key:W,limit:$,window:Y}=G,Z=G.cost??1,J=Date.now(),Q=m4(J,Y),K=J-Q,z=Q/Y;try{let X=await this.run([`${this.prefix}:${W}:${z}`,`${this.prefix}:${W}:${z-1}`],[String($),String(Y),String(K),String(Z)]),[M,B,S]=(Array.isArray(X)?X:[]).map(Number);return E4({allowed:M===1,current:Number.isFinite(B)?B:0,previous:Number.isFinite(S)?S:0,now:J,elapsed:K,window:Y,limit:$,cost:Z})}catch(X){if(this.onError(X),!this.failOpen)return{allowed:!1,limit:$,remaining:0,resetAt:J+Y,retryAfter:Y};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-Z)),resetAt:Q+Y,retryAfter:0}}}get client(){if(this.injectedClient)return this.injectedClient;let G=c4(),W=G.bound(x1)?G.make(x1).client:void 0;if(!W)throw Error("RedisRateLimiter could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisRateLimiter({ client }).");return W}async run(G,W){let $=this.client,Y=[String(G.length),...G,...W];try{return await $.send("EVALSHA",[await this.load($),...Y])}catch(Z){if(!R0(Z))throw Z;return this.scriptSha=null,await $.send("EVALSHA",[await this.load($),...Y])}}load(G){if(!this.scriptSha)this.scriptSha=Promise.resolve(G.send("SCRIPT",["LOAD",k0])).then(String).catch((W)=>{throw this.scriptSha=null,W});return this.scriptSha}}function R0(G){return String(G?.message??G).includes("NOSCRIPT")}class V{}var h0={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"};class d4 extends V{config;constructor(G={}){super();this.config={...h0,...G}}getRedirectUrl(){let G=this.config.scope,W=this.config.clientId,$=new URL("https://accounts.google.com/o/oauth2/v2/auth"),Y={scope:G,include_granted_scopes:"true",response_type:"code",state:"state_parameter_passthrough_value",redirect_uri:`${process.env.HOST_NAME}/auth/oauth/google/callback`,client_id:W};for(let[J,Q]of Object.entries(Y))$.searchParams.append(J,Q);return $.toString()}async onCallback(G){let W=new URL("https://oauth2.googleapis.com/token");W.searchParams.append("code",G.search.get("code")),W.searchParams.append("client_id",this.config.clientId),W.searchParams.append("client_secret",this.config.clientSecret),W.searchParams.append("grant_type","authorization_code"),W.searchParams.append("redirect_uri",`${process.env.HOST_NAME}${this.config.redirectPath}`);let $=await fetch(W.toString(),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"}}),{access_token:Y}=await $.json(),J=await(await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${Y}`)).json();if(!J.email)console.error("Google OAuth error: email not found in user info response",J);return{name:J.name,email:J.email}}}var b="https://api.x.com/2/",g="https://api.x.com/labs/2/",C="https://api.x.com/1.1/",h="https://upload.x.com/1.1/",p4="https://stream.x.com/1.1/",c="https://ads-api.x.com/12/",m="https://ads-api-sandbox.twitter.com/12/";class w1{constructor({realData:G,rateLimit:W,instance:$,queryParams:Y,sharedParams:Z}){this._maxResultsWhenFetchLast=100,this._realData=G,this._rateLimit=W,this._instance=$,this._queryParams=Y,this._sharedParams=Z}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(G){return this._instance.get(this.getEndpoint(),G,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(G,W){return new this.constructor({realData:G.data,rateLimit:G.rateLimit,instance:this._instance,queryParams:W,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(G){return{...G?{max_results:G}:{},...this._queryParams}}async next(G){let W=this.getNextQueryParams(G),$=await this.makeRequest(W);return this.makeNewInstanceFromResult($,W)}async fetchNext(G){let W=this.getNextQueryParams(G),$=await this.makeRequest(W);return await this.refreshInstanceFromResult($,!0),this}async fetchLast(G=1/0){let W=this.getNextQueryParams(this._maxResultsWhenFetchLast),$=0;while($<G&&this._isRateLimitOk){let Y=await this.makeRequest(W);if(await this.refreshInstanceFromResult(Y,!0),$+=this.getPageLengthFromRequest(Y),this.isFetchLastOver(Y))break;W=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var G;return{...(G=this._rateLimit)!==null&&G!==void 0?G:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let G=this,W=this.canFetchNextPage(this._realData);while(W&&this._isRateLimitOk&&G.getItemArray().length>0){let $=await G.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),W=this.canFetchNextPage($._realData),yield*$.getItemArray(),G=$}}async*fetchAndIterate(){for(let $ of this.getItemArray())yield[$,this];let G=this,W=this.canFetchNextPage(this._realData);while(W&&this._isRateLimitOk&&G.getItemArray().length>0){let $=await G.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),W=this.canFetchNextPage($._realData);for(let Y of $.getItemArray())yield[Y,$];this._rateLimit=$._rateLimit,G=$}}}class q1 extends w1{async previous(G){let W=this.getPreviousQueryParams(G),$=await this.makeRequest(W);return this.makeNewInstanceFromResult($,W)}async fetchPrevious(G){let W=this.getPreviousQueryParams(G),$=await this.makeRequest(W);return await this.refreshInstanceFromResult($,!1),this}}var E=w1;class F extends E{getNextQueryParams(G){var W;return{...this._queryParams,cursor:(W=this._realData.next_cursor_str)!==null&&W!==void 0?W:this._realData.next_cursor,...G?{count:G}:{}}}isFetchLastOver(G){return!this.canFetchNextPage(G.data)}canFetchNextPage(G){return!this.isNextCursorInvalid(G.next_cursor)||!this.isNextCursorInvalid(G.next_cursor_str)}isNextCursorInvalid(G){return G===void 0||G===0||G===-1||G==="0"||G==="-1"}}class P1 extends F{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.events.push(...$.events),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class y1 extends F{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.welcome_messages.push(...$.welcome_messages),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var j;(function(G){G.Jpeg="image/jpeg",G.Mp4="video/mp4",G.Mov="video/quicktime",G.Gif="image/gif",G.Png="image/png",G.Srt="text/plain",G.Webp="image/webp"})(j||(j={}));var I;(function(G){G.Create="message_create",G.WelcomeCreate="welcome_message"})(I||(I={}));var G1;(function(G){G.Request="request",G.PartialResponse="partial-response",G.Response="response"})(G1||(G1={}));class M1 extends Error{constructor(){super(...arguments);this.error=!0}}class W1 extends M1{constructor(G,W){super(G);this.type=G1.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:W})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class $1 extends M1{constructor(G,W){super(G);this.type=G1.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:W})}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 Y1 extends M1{constructor(G,W){super(G);if(this.type=G1.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:W}),this.code=W.code,this.headers=W.headers,this.rateLimit=W.rateLimit,W.data&&typeof W.data==="object"&&"error"in W.data&&!W.data.errors){let $={...W.data};$.errors=[{code:q.InternalError,message:$.error}],this.data=$}else this.data=W.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...G){let W=this.errors;if(!(W===null||W===void 0?void 0:W.length))return!1;if("code"in W[0])return W.some((Z)=>G.includes(Z.code));let $=this.data;return G.includes($.type)}get errors(){var G;return(G=this.data)===null||G===void 0?void 0:G.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(q.AuthTimestampInvalid,q.AuthenticationFail,q.BadAuthenticationData,q.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var q;(function(G){G[G.InvalidCoordinates=3]="InvalidCoordinates",G[G.NoLocationFound=13]="NoLocationFound",G[G.AuthenticationFail=32]="AuthenticationFail",G[G.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",G[G.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",G[G.AuthTimestampInvalid=135]="AuthTimestampInvalid",G[G.BadAuthenticationData=215]="BadAuthenticationData",G[G.NoUserMatch=17]="NoUserMatch",G[G.UserNotFound=50]="UserNotFound",G[G.ResourceNotFound=34]="ResourceNotFound",G[G.TweetNotFound=144]="TweetNotFound",G[G.TweetNotVisible=179]="TweetNotVisible",G[G.NotAllowedResource=220]="NotAllowedResource",G[G.MediaIdNotFound=325]="MediaIdNotFound",G[G.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",G[G.TweetViolatedRules=422]="TweetViolatedRules",G[G.TargetUserSuspended=63]="TargetUserSuspended",G[G.YouAreSuspended=64]="YouAreSuspended",G[G.AccountUpdateFailed=120]="AccountUpdateFailed",G[G.NoSelfSpamReport=36]="NoSelfSpamReport",G[G.NoSelfMute=271]="NoSelfMute",G[G.AccountLocked=326]="AccountLocked",G[G.RateLimitExceeded=88]="RateLimitExceeded",G[G.NoDMRightForApp=93]="NoDMRightForApp",G[G.OverCapacity=130]="OverCapacity",G[G.InternalError=131]="InternalError",G[G.TooManyFollowings=161]="TooManyFollowings",G[G.TweetLimitExceeded=185]="TweetLimitExceeded",G[G.DuplicatedTweet=187]="DuplicatedTweet",G[G.TooManySpamReports=205]="TooManySpamReports",G[G.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",G[G.NoWriteRightForApp=261]="NoWriteRightForApp",G[G.TweetActionsDisabled=425]="TweetActionsDisabled",G[G.TweetRepliesRestricted=433]="TweetRepliesRestricted",G[G.NamedParameterMissing=38]="NamedParameterMissing",G[G.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",G[G.TweetTextTooLong=186]="TweetTextTooLong",G[G.MissingUrlParameter=195]="MissingUrlParameter",G[G.NoMultipleGifs=323]="NoMultipleGifs",G[G.InvalidMediaIds=324]="InvalidMediaIds",G[G.InvalidUrl=407]="InvalidUrl",G[G.TooManyTweetAttachments=386]="TooManyTweetAttachments",G[G.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",G[G.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",G[G.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",G[G.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",G[G.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",G[G.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",G[G.UnableToSendDM=151]="UnableToSendDM",G[G.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",G[G.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",G[G.DMTextTooLong=354]="DMTextTooLong",G[G.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",G[G.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",G[G.SuspendedApplication=416]="SuspendedApplication",G[G.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(q||(q={}));var l4;(function(G){G.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",G.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",G.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",G.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",G.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",G.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",G.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",G.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",G.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",G.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",G.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",G.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",G.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(l4||(l4={}));var x;(function(G){G.Connected="connected",G.ConnectError="connect error",G.ConnectionError="connection error",G.ConnectionClosed="connection closed",G.ConnectionLost="connection lost",G.ReconnectAttempt="reconnect attempt",G.Reconnected="reconnected",G.ReconnectError="reconnect error",G.ReconnectLimitExceeded="reconnect limit exceeded",G.DataKeepAlive="data keep-alive",G.Data="data event content",G.DataError="data twitter error",G.TweetParseError="data tweet parse error",G.Error="stream error"})(x||(x={}));class Z1{constructor(G){this.value=G}}import*as K4 from"fs";var L={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function A1(G){let W={value:void 0,promise:G().then(($)=>{return W.value=$,$})};return W}function B1(G){if(Array.isArray(G))return G;return[G]}function i4(G){for(let W of Object.keys(G))if(G[W]===void 0)delete G[W]}function N1(G){return typeof G==="object"&&"errors"in G&&!("data"in G)}function J1(G){if(Array.isArray(G)&&G.length>1)return!0;return G.toString().includes(",")}var n4=new Set;function V1(G){if(typeof console>"u"||!console.warn||!L.deprecationWarnings)return;let W=`${G.instance}-${G.method}-${G.problem}`;if(n4.has(W))return;let $=`[twitter-api-v2] Deprecation warning: In ${G.instance}.${G.method}() call, ${G.problem}.
30
+ ${G.resolution}.`;console.warn($),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),n4.add(W)}import{EventEmitter as I0}from"events";import{request as v0}from"https";import*as D from"zlib";import{EventEmitter as _0}from"events";class o4{constructor(G){this.requestData=G,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let G=this.requestData.url;return G.hostname+G.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(G){if(L.debug)L.logger.log("Request error:",G);return new W1("Request failed.",{request:this.req,error:G})}createPartialResponseError(G,W){let Y=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(W)Y+=" (connection abruptly closed)";else Y+=" (parse error)";return new $1(Y,{request:this.req,response:this.res,responseError:G,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(G){return G.map(({code:W,message:$})=>`${$} (Twitter code ${W})`).join(", ")}formatV2Error(G){return`${G.title}: ${G.detail} (see ${G.type})`}createResponseError({res:G,data:W,rateLimit:$,code:Y}){var Z;if(L.debug)L.logger.log(`Request failed with code ${Y}, data:`,W),L.logger.log("Response headers:",G.headers);let J=`Request failed with code ${Y}`;if((Z=W===null||W===void 0?void 0:W.errors)===null||Z===void 0?void 0:Z.length){let Q=W.errors;if(typeof Q[0]==="object"&&"code"in Q[0])J+=" - "+this.formatV1Errors(Q);else J+=" - "+this.formatV2Error(W)}return new Y1(J,{code:Y,data:W,headers:G.headers,request:this.req,response:G,rateLimit:$})}getResponseDataStream(G){if(this.isCompressionDisabled())return G;let W=(G.headers["content-encoding"]||"identity").trim().toLowerCase();if(W==="br"){let $=D.createBrotliDecompress({flush:D.constants.BROTLI_OPERATION_FLUSH,finishFlush:D.constants.BROTLI_OPERATION_FLUSH});return G.pipe($),$}if(W==="gzip"){let $=D.createGunzip({flush:D.constants.Z_SYNC_FLUSH,finishFlush:D.constants.Z_SYNC_FLUSH});return G.pipe($),$}if(W==="deflate"){let $=D.createInflate({flush:D.constants.Z_SYNC_FLUSH,finishFlush:D.constants.Z_SYNC_FLUSH});return G.pipe($),$}return G}detectResponseType(G){var W,$;if(((W=G.headers["content-type"])===null||W===void 0?void 0:W.includes("application/json"))||(($=G.headers["content-type"])===null||$===void 0?void 0:$.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(G){let W=this.responseData,$=this.requestData.forceParseMode||this.detectResponseType(G);if($==="buffer")return Buffer.concat(W);else if($==="text")return Buffer.concat(W).toString();else if($==="json"){let Y=Buffer.concat(W).toString();return Y.length?JSON.parse(Y):void 0}else if($==="url"){let Y=Buffer.concat(W).toString(),Z={};for(let[J,Q]of new URLSearchParams(Y))Z[J]=Q;return Z}else return}getRateLimitFromResponse(G){let W=void 0;if(G.headers["x-rate-limit-limit"]){if(W={limit:Number(G.headers["x-rate-limit-limit"]),remaining:Number(G.headers["x-rate-limit-remaining"]),reset:Number(G.headers["x-rate-limit-reset"])},G.headers["x-app-limit-24hour-limit"])W.day={limit:Number(G.headers["x-app-limit-24hour-limit"]),remaining:Number(G.headers["x-app-limit-24hour-remaining"]),reset:Number(G.headers["x-app-limit-24hour-reset"])};if(G.headers["x-user-limit-24hour-limit"])W.userDay={limit:Number(G.headers["x-user-limit-24hour-limit"]),remaining:Number(G.headers["x-user-limit-24hour-remaining"]),reset:Number(G.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(W)}return W}onSocketEventHandler(G,W,$){let Y=this.onSocketCloseHandler.bind(this,G);$.on("close",Y),W.on("complete",()=>$.off("close",Y))}onSocketCloseHandler(G){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return G(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(G,W){var $,Y;(Y=($=this.requestData).requestEventDebugHandler)===null||Y===void 0||Y.call($,"request-error",{requestError:W}),this.requestErrorHandled=!0,G(this.createRequestError(W))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(G,W,$){this.res=$;let Y=this.getResponseDataStream($);if(Y.on("data",(Z)=>this.responseData.push(Z)),Y.on("end",this.onResponseEndHandler.bind(this,G,W)),Y.on("close",this.onResponseCloseHandler.bind(this,G,W)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:$}),$.on("aborted",(Z)=>this.requestData.requestEventDebugHandler("response-aborted",{error:Z})),$.on("error",(Z)=>this.requestData.requestEventDebugHandler("response-error",{error:Z})),$.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),$.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(G,W){let $=this.getRateLimitFromResponse(this.res),Y;try{Y=this.getParsedResponse(this.res)}catch(J){W(this.createPartialResponseError(J,!1));return}let Z=this.res.statusCode;if(Z>=400){W(this.createResponseError({data:Y,res:this.res,rateLimit:$,code:Z}));return}if(L.debug)L.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),L.logger.log("Response body:",Y);G({data:Y,headers:this.res.headers,rateLimit:$})}onResponseCloseHandler(G,W){let $=this.res;if($.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(G,W)}catch(Y){return W(this.createPartialResponseError(Y,!0))}if(!$.complete)return W(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(G,W,$){if($.statusCode<400){if(L.debug)L.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${$.statusCode} (starting stream)`);let Z=this.getResponseDataStream($);G({req:this.req,res:Z,originalResponse:$,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},W,$)}debugRequest(){let G=this.requestData.url;if(L.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),G.search)L.logger.log("Request parameters:",[...G.searchParams.entries()].map(([W,$])=>`${W}: ${$}`));if(this.requestData.body)L.logger.log("Request body:",this.requestData.body)}buildRequest(){var G;let W=this.requestData.url,$=W.username?`${W.username}:${W.password}`:void 0,Y=(G=this.requestData.options.headers)!==null&&G!==void 0?G:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")Y["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")Y["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")Y["accept-encoding"]="deflate;q=1, *;q=0.1";if(L.debug)this.debugRequest();this.req=v0({...this.requestData.options,host:W.hostname,port:W.port||void 0,path:W.pathname+W.search,protocol:W.protocol,auth:$,headers:Y})}registerRequestEventDebugHandlers(G){G.on("close",()=>this.requestData.requestEventDebugHandler("close")),G.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),G.on("socket",(W)=>{this.requestData.requestEventDebugHandler("socket",{socket:W}),W.on("error",($)=>this.requestData.requestEventDebugHandler("socket-error",{socket:W,error:$})),W.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:W})),W.on("close",($)=>this.requestData.requestEventDebugHandler("socket-close",{socket:W,withError:$})),W.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:W})),W.on("lookup",(...$)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:W,data:$})),W.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:W}))})}makeRequest(){return this.buildRequest(),new Promise((G,W)=>{let $=(Q)=>{Z.emit("complete"),G(Q)},Y=(Q)=>{Z.emit("complete"),W(Q)},Z=new _0,J=this.req;if(J.on("error",this.requestErrorHandler.bind(this,Y)),J.on("socket",this.onSocketEventHandler.bind(this,Y,Z)),J.on("response",this.classicResponseHandler.bind(this,$,Y)),this.requestData.options.timeout)J.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(J);if(this.requestData.body)J.write(this.requestData.body);J.end()})}async makeRequestAsStream(){let{req:G,res:W,requestData:$,originalResponse:Y}=await this.makeRequestAndResolveWhenReady();return new j1($,{req:G,res:W,originalResponse:Y})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((G,W)=>{let $=this.req;if($.on("error",this.requestErrorHandler.bind(this,W)),$.on("response",this.streamResponseHandler.bind(this,G,W)),this.requestData.body)$.write(this.requestData.body);$.end()})}}var Q1=o4;import{EventEmitter as b0}from"events";class s4 extends b0{constructor(G){super();this.stream=G,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),G.on(x.Data,this.onStreamData),G.on(x.ConnectionError,this.onStreamError),G.on(x.TweetParseError,this.onStreamError),G.on(x.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let G=this.stack;return this.stack=[],G}destroy(){this.removeAllListeners(),this.stream.off(x.Data,this.onStreamData),this.stream.off(x.ConnectionError,this.onStreamError),this.stream.off(x.TweetParseError,this.onStreamError),this.stream.off(x.ConnectionClosed,this.onStreamError)}emitEvent(G,W){this.emit("event",{type:G,payload:W})}onStreamError(G){this.emitEvent("error",G)}onStreamData(G){this.stack.push(G),this.emitEvent("data",G)}}var a4=s4;import{EventEmitter as C0}from"events";class F1 extends C0{constructor(){super(...arguments);this.currentMessage=""}push(G){this.currentMessage+=G,G=this.currentMessage;let W=G.length,$=0,Y=0;while(Y<W){if(G.slice(Y,Y+2)===`\r
31
+ `){let Z=G.slice($,Y);if($=Y+=2,!Z.length)continue;try{let J=JSON.parse(Z);if(J){this.emit(P.ParsedData,J);continue}}catch(J){this.emit(P.ParseError,J)}}Y++}this.currentMessage=G.slice($,W)}reset(){this.currentMessage=""}}var P;(function(G){G.ParsedData="parsed data",G.ParseError="parse error"})(P||(P={}));var t4=[5,15,30,60,90,120,180,300,600,900],T0=(G)=>G>t4.length?901000:t4[G-1]*1000;class r4 extends I0{constructor(G,W){super();if(this.requestData=G,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=T0,this.parser=new F1,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),W)this.req=W.req,this.res=W.res,this.originalResponse=W.originalResponse,this.initEventsFromRequest()}on(G,W){return super.on(G,W)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let G=(W)=>{this.emit(x.ConnectionError,W),this.emit(x.Error,{type:x.ConnectionError,error:W,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",G),this.res.on("error",G),this.res.on("close",()=>G(Error("Connection closed by Twitter."))),this.res.on("data",(W)=>{if(this.resetKeepAliveTimeout(),W.toString()===`\r
32
+ `)return this.emit(x.DataKeepAlive);this.parser.push(W.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let G=this.requestData.payloadIsError;this.parser.on(P.ParsedData,(W)=>{if(G&&G(W))this.emit(x.DataError,W),this.emit(x.Error,{type:x.DataError,error:W,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(x.Data,W)}),this.parser.on(P.ParseError,(W)=>{this.emit(x.TweetParseError,W),this.emit(x.Error,{type:x.TweetParseError,error:W,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(x.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(x.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let W=await new Q1(this.requestData).makeRequestAsStream(),$=this.eventNames();for(let Y of $){let Z=this.listeners(Y);for(let J of Z)W.on(Y,J)}return W}async connect(G={}){if(typeof G.autoReconnect<"u")this.autoReconnect=G.autoReconnect;if(typeof G.autoReconnectRetries<"u")this.autoReconnectRetries=G.autoReconnectRetries==="unlimited"?1/0:G.autoReconnectRetries;if(typeof G.keepAliveTimeout<"u")this.keepAliveTimeoutMs=G.keepAliveTimeout==="disable"?1/0:G.keepAliveTimeout;if(typeof G.nextRetryTimeout<"u")this.nextRetryTimeout=G.nextRetryTimeout;this.unbindTimeouts();try{await this.reconnect()}catch(W){if(this.emit(x.ConnectError,0),this.emit(x.Error,{type:x.ConnectError,error:W,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,W);else throw W}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let G=!0;if(this.req)G=!1,this.closeWithoutEmit();let{req:W,res:$,originalResponse:Y}=await new Q1(this.requestData).makeRequestAndResolveWhenReady();this.req=W,this.res=$,this.originalResponse=Y,this.emit(G?x.Connected:x.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(G=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(x.ConnectionClosed);return}if(G>=this.autoReconnectRetries){this.emit(x.ReconnectLimitExceeded),this.emit(x.ConnectionClosed);return}try{this.emit(x.ReconnectAttempt,G),await this.reconnect()}catch(W){this.emit(x.ReconnectError,G),this.emit(x.Error,{type:x.ReconnectError,error:W,message:`Reconnect error - ${G+1} attempts made yet.`}),this.makeAutoReconnectRetry(G,W)}}makeAutoReconnectRetry(G,W){let $=this.nextRetryTimeout(G+1,W);this.retryTimeout=setTimeout(()=>{this.onConnectionError(G+1)},$)}async*[Symbol.asyncIterator](){let G=new a4(this);try{while(!0){if(!this.req||this.req.aborted)throw Error("Connection closed");if(G.hasStack())yield*G.popStack();let{type:W,payload:$}=await G.nextEvent();if(W==="error")throw $}}finally{G.destroy()}}}var j1=r4;function e4(G){var W;if(!((W=G.clientSettings.plugins)===null||W===void 0?void 0:W.length))return!1;for(let $ of G.clientSettings.plugins)if($.onRequestError||$.onResponseError)return!0;return!1}async function G0(G,W,$,Y){let Z;if(Y instanceof W1||Y instanceof $1)Z=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(G.url),params:G,computedParams:W,requestOptions:$,error:Y});else if(Y instanceof Y1)Z=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(G.url),params:G,computedParams:W,requestOptions:$,error:Y});if(Z&&Z instanceof Z1)return Z.value;return Promise.reject(Y)}import*as Y0 from"crypto";class U{constructor(G){this.nonceLength=32,this.consumerKeys=G.consumerKeys}static percentEncode(G){return encodeURIComponent(G).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(G,W){return Y0.createHmac("sha1",W).update(G).digest("base64")}authorize(G,W={}){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(W.key!==void 0)$.oauth_token=W.key;if(!G.data)G.data={};return $.oauth_signature=this.getSignature(G,W.secret,$),$}toHeader(G){let W=$0(G),$="OAuth ";for(let Y of W){if(Y.key.indexOf("oauth_")!==0)continue;$+=U.percentEncode(Y.key)+'="'+U.percentEncode(Y.value)+'",'}return{Authorization:$.slice(0,$.length-1)}}getNonce(){let W="";for(let $=0;$<this.nonceLength;$++)W+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.trunc(Math.random()*62)];return W}getTimestamp(){return Math.trunc(new Date().getTime()/1000)}getSignature(G,W,$){return this.hash(this.getBaseString(G,$),this.getSigningKey(W))}getSigningKey(G){return U.percentEncode(this.consumerKeys.secret)+"&"+U.percentEncode(G||"")}getBaseString(G,W){return G.method.toUpperCase()+"&"+U.percentEncode(this.getBaseUrl(G.url))+"&"+U.percentEncode(this.getParameterString(G,W))}getParameterString(G,W){let $=$0(P0(W0(W,W0(G.data,q0(G.url))))),Y="";for(let{key:Z,value:J}of $)if(J&&Array.isArray(J)){J.sort();let Q="";J.forEach((K,z)=>{if(Q+=Z+"="+K,z<J.length)Q+="&"}),Y+=Q}else Y+=Z+"="+J+"&";return Y.slice(0,Y.length-1)}getBaseUrl(G){return G.split("?")[0]}}var K1=U;function W0(G,W){return{...G||{},...W||{}}}function $0(G){return Object.keys(G).sort().map((W)=>({key:W,value:G[W]}))}function w0(G){let W=G.split("&"),$={};for(let Y of W){let[Z,J=""]=Y.split("=");if($[Z]){if(!Array.isArray($[Z]))$[Z]=[$[Z]];$[Z].push(decodeURIComponent(J))}else $[Z]=decodeURIComponent(J)}return $}function q0(G){let W=G.split("?");if(W.length===1)return{};return w0(W[1])}function P0(G){let W={};for(let $ in G){let Y=G[$];if(Y&&Array.isArray(Y))Y=Y.map((Z)=>U.percentEncode(Z));else Y=U.percentEncode(Y);W[U.percentEncode($)]=Y}return W}class f{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...G){let W=G.map(($)=>$ instanceof Buffer?$:Buffer.from($));this._chunks.push(...W)}append(G,W,$){let Y=W instanceof Buffer?W:W.toString(),Z=this.getMultipartHeader(G,Y,$);this.bodyAppend(Z,Y,f.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((G,W)=>G+W.length,this.getMultipartFooter().length)}getBuffer(){let G=[...this._chunks,this.getMultipartFooter()],W=Buffer.alloc(this.getLength()),$=0;for(let Y of G)for(let Z=0;Z<Y.length;$++,Z++)W[$]=Y[Z];return W}getBoundary(){if(!this._boundary)this.generateBoundary();return this._boundary}generateBoundary(){let G="--------------------------";for(let W=0;W<24;W++)G+=Math.floor(Math.random()*10).toString(16);this._boundary=G}getMultipartHeader(G,W,$){if(!$)$=W instanceof Buffer?f.DEFAULT_CONTENT_TYPE:"";let Y={"Content-Disposition":["form-data",`name="${G}"`],"Content-Type":$},Z="";for(let[J,Q]of Object.entries(Y)){if(!Q.length)continue;Z+=J+": "+B1(Q).join("; ")+f.LINE_BREAK}return"--"+this.getBoundary()+f.LINE_BREAK+Z+f.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+f.LINE_BREAK)}}f.LINE_BREAK=`\r
33
+ `;f.DEFAULT_CONTENT_TYPE="application/octet-stream";class g1{static formatQueryToString(G){let W={};for(let $ in G)if(typeof G[$]==="string")W[$]=G[$];else if(typeof G[$]<"u")W[$]=String(G[$]);return W}static autoDetectBodyType(G){if(G.pathname.startsWith("/2/")||G.pathname.startsWith("/labs/2/")){if(G.password.startsWith("/2/oauth2"))return"url";return"json"}if(G.hostname==="upload.x.com"){if(G.pathname==="/1.1/media/upload.json")return"form-data";return"json"}let W=G.pathname.split("/1.1/",2)[1];if(this.JSON_1_1_ENDPOINTS.has(W))return"json";return"url"}static addQueryParamsToUrl(G,W){let $=Object.entries(W);if($.length){let Y="";for(let[Z,J]of $)Y+=(Y.length?"&":"?")+`${K1.percentEncode(Z)}=${K1.percentEncode(J)}`;G.search=Y}}static constructBodyParams(G,W,$){if(G instanceof Buffer)return G;if($==="json"){if(!W["content-type"])W["content-type"]="application/json;charset=UTF-8";return JSON.stringify(G)}else if($==="url"){if(!W["content-type"])W["content-type"]="application/x-www-form-urlencoded;charset=UTF-8";if(Object.keys(G).length)return new URLSearchParams(G).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 Y=new f;for(let Z in G)Y.append(Z,G[Z]);if(!W["content-type"]){let Z=Y.getHeaders();W["content-type"]=Z["content-type"]}return Y.getBuffer()}}static setBodyLengthHeader(G,W){var $;if(G.headers=($=G.headers)!==null&&$!==void 0?$:{},typeof W==="string")G.headers["content-length"]=Buffer.byteLength(W);else G.headers["content-length"]=W.length}static isOAuthSerializable(G){return!(G instanceof Buffer)}static mergeQueryAndBodyForOAuth(G,W){let $={};for(let Y in G)$[Y]=G[Y];if(this.isOAuthSerializable(W))for(let Y in W){let Z=W[Y];if(this.isOAuthSerializable(Z))$[Y]=typeof Z==="object"&&Z!==null&&"toString"in Z?Z.toString():Z}return $}static moveUrlQueryParamsIntoObject(G,W){for(let[$,Y]of G.searchParams)W[$]=Y;return G.search="",G}static applyRequestParametersToUrl(G,W){return G.pathname=G.pathname.replace(/:([A-Z_-]+)/ig,($,Y)=>{if(W[Y]!==void 0)return String(W[Y]);return $}),G}}g1.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 O=g1;import*as Z0 from"crypto";class y{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(G){return this.escapeBase64Url(Z0.createHash("sha256").update(G).digest("base64"))}static getAuthHeader(G,W){let $=encodeURIComponent(G)+":"+encodeURIComponent(W);return Buffer.from($).toString("base64")}static generateRandomString(G){let W="",$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let Y=0;Y<G;Y++)W+=$[Math.floor(Math.random()*$.length)];return W}static escapeBase64Url(G){return G.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class u{constructor(G){if(this.rateLimits={},this.clientSettings={},G)this.clientSettings=G}getRateLimits(){return this.rateLimits}saveRateLimit(G,W){this.rateLimits[G]=W}async send(G){var W,$,Y,Z,J;if((W=this.clientSettings.plugins)===null||W===void 0?void 0:W.length){let B=await this.applyPreRequestConfigHooks(G);if(B)return B}let Q=this.getHttpRequestArgs(G),K={method:Q.method,headers:Q.headers,timeout:G.timeout,agent:this.clientSettings.httpAgent},z=G.enableRateLimitSave!==!1;if(Q.body)O.setBodyLengthHeader(K,Q.body);if(($=this.clientSettings.plugins)===null||$===void 0?void 0:$.length)await this.applyPreRequestHooks(G,Q,K);let X=new Q1({url:Q.url,options:K,body:Q.body,rateLimitSaver:z?this.saveRateLimit.bind(this,Q.rawUrl):void 0,requestEventDebugHandler:G.requestEventDebugHandler,compression:(Z=(Y=G.compression)!==null&&Y!==void 0?Y:this.clientSettings.compression)!==null&&Z!==void 0?Z:!0,forceParseMode:G.forceParseMode}).makeRequest();if(e4(this))X=this.applyResponseErrorHooks(G,Q,K,X);let M=await X;if((J=this.clientSettings.plugins)===null||J===void 0?void 0:J.length){let B=await this.applyPostRequestHooks(G,Q,K,M);if(B)return B.value}return M}sendStream(G){var W,$;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(G);let Y=this.getHttpRequestArgs(G),Z={method:Y.method,headers:Y.headers,agent:this.clientSettings.httpAgent},J=G.enableRateLimitSave!==!1,Q=G.autoConnect!==!1;if(Y.body)O.setBodyLengthHeader(Z,Y.body);let K={url:Y.url,options:Z,body:Y.body,rateLimitSaver:J?this.saveRateLimit.bind(this,Y.rawUrl):void 0,payloadIsError:G.payloadIsError,compression:($=(W=G.compression)!==null&&W!==void 0?W:this.clientSettings.compression)!==null&&$!==void 0?$:!0},z=new j1(K);if(!Q)return z;return z.connect()}initializeToken(G){if(typeof G==="string")this.bearerToken=G;else if(typeof G==="object"&&"appKey"in G){if(this.consumerToken=G.appKey,this.consumerSecret=G.appSecret,G.accessToken&&G.accessSecret)this.accessToken=G.accessToken,this.accessSecret=G.accessSecret;this._oauth=this.buildOAuth()}else if(typeof G==="object"&&"username"in G){let W=encodeURIComponent(G.username)+":"+encodeURIComponent(G.password);this.basicToken=Buffer.from(W).toString("base64")}else if(typeof G==="object"&&"clientId"in G)this.clientId=G.clientId,this.clientSecret=G.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 K1({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(!this.accessSecret||!this.accessToken)return;return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var G;return(G=this.clientSettings.plugins)!==null&&G!==void 0?G:[]}hasPlugins(){var G;return!!((G=this.clientSettings.plugins)===null||G===void 0?void 0:G.length)}async applyPluginMethod(G,W){var $;let Y;for(let Z of this.getPlugins()){let J=await(($=Z[G])===null||$===void 0?void 0:$.call(Z,W));if(J&&J instanceof Z1)Y=J}return Y}writeAuthHeaders({headers:G,bodyInSignature:W,url:$,method:Y,query:Z,body:J}){if(G={...G},this.bearerToken)G.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)G.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)G.Authorization="Basic "+y.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let Q=W?O.mergeQueryAndBodyForOAuth(Z,J):Z,K=this._oauth.authorize({url:$.toString(),method:Y,data:Q},this.getOAuthAccessTokens());G={...G,...this._oauth.toHeader(K)}}return G}getUrlObjectFromUrlString(G){if(!G.startsWith("http"))G="https://"+G;return new URL(G)}getHttpRequestArgs({url:G,method:W,query:$={},body:Y={},headers:Z,forceBodyMode:J,enableAuth:Q,params:K}){let z=void 0;if(W=W.toUpperCase(),Z=Z!==null&&Z!==void 0?Z:{},!Z["x-user-agent"])Z["x-user-agent"]="Node.twitter-api-v2";let X=this.getUrlObjectFromUrlString(G),M=X.origin+X.pathname;if(K)O.applyRequestParametersToUrl(X,K);let B=O.formatQueryToString($);if(O.moveUrlQueryParamsIntoObject(X,B),!(Y instanceof Buffer))i4(Y);let S=J!==null&&J!==void 0?J:O.autoDetectBodyType(X);if(Q!==!1){let k=u.BODY_METHODS.has(W)&&S==="url";Z=this.writeAuthHeaders({headers:Z,bodyInSignature:k,method:W,query:B,url:X,body:Y})}if(u.BODY_METHODS.has(W))z=O.constructBodyParams(Y,Z,S)||void 0;return O.addQueryParamsToUrl(X,B),{rawUrl:M,url:X,method:W,headers:Z,body:z}}async applyPreRequestConfigHooks(G){var W;let $=this.getUrlObjectFromUrlString(G.url);for(let Y of this.getPlugins()){let Z=await((W=Y.onBeforeRequestConfig)===null||W===void 0?void 0:W.call(Y,{client:this,url:$,params:G}));if(Z)return Z}}applyPreStreamRequestConfigHooks(G){var W;let $=this.getUrlObjectFromUrlString(G.url);for(let Y of this.getPlugins())(W=Y.onBeforeStreamRequestConfig)===null||W===void 0||W.call(Y,{client:this,url:$,params:G})}async applyPreRequestHooks(G,W,$){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(G.url),params:G,computedParams:W,requestOptions:$})}async applyPostRequestHooks(G,W,$,Y){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(G.url),params:G,computedParams:W,requestOptions:$,response:Y})}applyResponseErrorHooks(G,W,$,Y){return Y.catch(G0.bind(this,G,W,$))}}u.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class T{constructor(G,W={}){if(this._currentUser=null,this._currentUserV2=null,G instanceof T)this._requestMaker=G._requestMaker;else this._requestMaker=new u(W),this._requestMaker.initializeToken(G)}setPrefix(G){this._prefix=G}cloneWithPrefix(G){let W=this.constructor(this);return W.setPrefix(G),W}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(G){return this.getPlugins().find((W)=>W instanceof G)}hasHitRateLimit(G){var W;if(this.isRateLimitStatusObsolete(G))return!1;return((W=this.getLastRateLimitStatus(G))===null||W===void 0?void 0:W.remaining)===0}isRateLimitStatusObsolete(G){let W=this.getLastRateLimitStatus(G);if(W===void 0)return!0;return W.reset*1000<Date.now()}getLastRateLimitStatus(G){let W=G.match(/^https?:\/\//)?G:this._prefix+G;return this._requestMaker.getRateLimits()[W]}getCurrentUserObject(G=!1){if(!G&&this._currentUser){if(this._currentUser.value)return Promise.resolve(this._currentUser.value);return this._currentUser.promise}return this._currentUser=A1(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:C})),this._currentUser.promise}getCurrentUserV2Object(G=!1){if(!G&&this._currentUserV2){if(this._currentUserV2.value)return Promise.resolve(this._currentUserV2.value);return this._currentUserV2.promise}return this._currentUserV2=A1(()=>this.get("users/me",void 0,{prefix:b})),this._currentUserV2.promise}async get(G,W={},{fullResponse:$,prefix:Y=this._prefix,...Z}={}){if(Y)G=Y+G;let J=await this._requestMaker.send({url:G,method:"GET",query:W,...Z});return $?J:J.data}async delete(G,W={},{fullResponse:$,prefix:Y=this._prefix,...Z}={}){if(Y)G=Y+G;let J=await this._requestMaker.send({url:G,method:"DELETE",query:W,...Z});return $?J:J.data}async post(G,W,{fullResponse:$,prefix:Y=this._prefix,...Z}={}){if(Y)G=Y+G;let J=await this._requestMaker.send({url:G,method:"POST",body:W,...Z});return $?J:J.data}async put(G,W,{fullResponse:$,prefix:Y=this._prefix,...Z}={}){if(Y)G=Y+G;let J=await this._requestMaker.send({url:G,method:"PUT",body:W,...Z});return $?J:J.data}async patch(G,W,{fullResponse:$,prefix:Y=this._prefix,...Z}={}){if(Y)G=Y+G;let J=await this._requestMaker.send({url:G,method:"PATCH",body:W,...Z});return $?J:J.data}getStream(G,W,{prefix:$=this._prefix,...Y}={}){return this._requestMaker.sendStream({url:$?$+G:G,method:"GET",query:W,...Y})}postStream(G,W,{prefix:$=this._prefix,...Y}={}){return this._requestMaker.sendStream({url:$?$+G:G,method:"POST",body:W,...Y})}}class H extends T{constructor(G){if(!(G instanceof T))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(G)}}class d extends E{constructor(){super(...arguments);this.hasFinishedFetch=!1}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.push(...$),this.hasFinishedFetch=$.length===0}getNextQueryParams(G){let W=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(G),max_id:(W-BigInt(1)).toString()}}getPageLengthFromRequest(G){return G.data.length}isFetchLastOver(G){return!G.data.length}canFetchNextPage(G){return G.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class c1 extends d{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class m1 extends d{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class L1 extends d{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class E1 extends d{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class D1 extends d{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class u1 extends F{constructor(){super(...arguments);this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class d1 extends F{constructor(){super(...arguments);this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class p1 extends F{constructor(){super(...arguments);this._endpoint="followers/list.json"}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class l1 extends F{constructor(){super(...arguments);this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class n1 extends F{constructor(){super(...arguments);this._endpoint="friends/list.json"}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class i1 extends F{constructor(){super(...arguments);this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class o1 extends E{constructor(){super(...arguments);this._endpoint="users/search.json"}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.push(...$)}getNextQueryParams(G){var W;let $=Number((W=this._queryParams.page)!==null&&W!==void 0?W:"1");return{...this._queryParams,page:$+1,...G?{count:G}:{}}}getPageLengthFromRequest(G){return G.data.length}isFetchLastOver(G){return!G.data.length}canFetchNextPage(G){return G.length>0}getItemArray(){return this.users}get users(){return this._realData}}class O1 extends F{constructor(){super(...arguments);this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class s1 extends O1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class H1 extends F{refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.lists.push(...$.lists),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class a1 extends H1{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class t1 extends H1{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class r1 extends H1{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class e1 extends F{refreshInstanceFromResult(G,W){let $=G.data;if(this._rateLimit=G.rateLimit,W)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(G){return G.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class G4 extends e1{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class W4 extends e1{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class p extends H{constructor(){super(...arguments);this._prefix=C}singleTweet(G,W={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:G,...W})}tweets(G,W={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:G,...W})}oembedTweet(G,W={}){return this.get("oembed",{url:`https://x.com/i/statuses/${G}`,...W},{prefix:"https://publish.x.com/"})}async homeTimeline(G={}){let W={tweet_mode:"extended",...G},$=await this.get("statuses/home_timeline.json",W,{fullResponse:!0});return new c1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async mentionTimeline(G={}){let W={tweet_mode:"extended",...G},$=await this.get("statuses/mentions_timeline.json",W,{fullResponse:!0});return new m1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async userTimeline(G,W={}){let $={tweet_mode:"extended",user_id:G,...W},Y=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new L1({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$})}async userTimelineByUsername(G,W={}){let $={tweet_mode:"extended",screen_name:G,...W},Y=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new L1({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$})}async favoriteTimeline(G,W={}){let $={tweet_mode:"extended",user_id:G,...W},Y=await this.get("favorites/list.json",$,{fullResponse:!0});return new D1({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$})}async favoriteTimelineByUsername(G,W={}){let $={tweet_mode:"extended",screen_name:G,...W},Y=await this.get("favorites/list.json",$,{fullResponse:!0});return new D1({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$})}user(G){return this.get("users/show.json",{tweet_mode:"extended",...G})}users(G){return this.get("users/lookup.json",{tweet_mode:"extended",...G})}verifyCredentials(G={}){return this.get("account/verify_credentials.json",G)}async listMutedUsers(G={}){let W={tweet_mode:"extended",...G},$=await this.get("mutes/users/list.json",W,{fullResponse:!0});return new u1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async listMutedUserIds(G={}){let W={stringify_ids:!0,...G},$=await this.get("mutes/users/ids.json",W,{fullResponse:!0});return new d1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async userFriendList(G={}){let W={...G},$=await this.get("friends/list.json",W,{fullResponse:!0});return new n1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async userFollowerList(G={}){let W={...G},$=await this.get("followers/list.json",W,{fullResponse:!0});return new p1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async userFollowerIds(G={}){let W={stringify_ids:!0,...G},$=await this.get("followers/ids.json",W,{fullResponse:!0});return new l1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async userFollowingIds(G={}){let W={stringify_ids:!0,...G},$=await this.get("friends/ids.json",W,{fullResponse:!0});return new i1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async searchUsers(G,W={}){let $={q:G,tweet_mode:"extended",page:1,...W},Y=await this.get("users/search.json",$,{fullResponse:!0});return new o1({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$})}friendship(G){return this.get("friendships/show.json",G)}friendships(G){return this.get("friendships/lookup.json",G)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(G={}){let W={stringify_ids:!0,...G},$=await this.get("friendships/incoming.json",W,{fullResponse:!0});return new O1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async friendshipsOutgoing(G={}){let W={stringify_ids:!0,...G},$=await this.get("friendships/outgoing.json",W,{fullResponse:!0});return new s1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(G){return this.get("users/profile_banner.json",G)}list(G){return this.get("lists/show.json",{tweet_mode:"extended",...G})}lists(G={}){return this.get("lists/list.json",{tweet_mode:"extended",...G})}async listMembers(G={}){let W={tweet_mode:"extended",...G},$=await this.get("lists/members.json",W,{fullResponse:!0});return new G4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}listGetMember(G){return this.get("lists/members/show.json",{tweet_mode:"extended",...G})}async listMemberships(G={}){let W={tweet_mode:"extended",...G},$=await this.get("lists/memberships.json",W,{fullResponse:!0});return new a1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async listOwnerships(G={}){let W={tweet_mode:"extended",...G},$=await this.get("lists/ownerships.json",W,{fullResponse:!0});return new t1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async listStatuses(G){let W={tweet_mode:"extended",...G},$=await this.get("lists/statuses.json",W,{fullResponse:!0});return new E1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}async listSubscribers(G={}){let W={tweet_mode:"extended",...G},$=await this.get("lists/subscribers.json",W,{fullResponse:!0});return new W4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}listGetSubscriber(G){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...G})}async listSubscriptions(G={}){let W={tweet_mode:"extended",...G},$=await this.get("lists/subscriptions.json",W,{fullResponse:!0});return new r1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}mediaInfo(G){return this.get("media/upload.json",{command:"STATUS",media_id:G},{prefix:h})}filterStream({autoConnect:G,...W}={}){let $={};for(let[Z,J]of Object.entries(W))if(Z==="follow"||Z==="track")$[Z]=J.toString();else if(Z==="locations"){let Q=J;$.locations=B1(Q).map((K)=>`${K.lng},${K.lat}`).join(",")}else $[Z]=J;return this.stream.postStream("statuses/filter.json",$,{autoConnect:G})}sampleStream({autoConnect:G,...W}={}){return this.stream.getStream("statuses/sample.json",W,{autoConnect:G})}get stream(){let G=new U1(this);return G.setPrefix(p4),G}trendsByPlace(G,W={}){return this.get("trends/place.json",{id:G,...W})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(G,W){return this.get("trends/closest.json",{lat:G,long:W})}geoPlace(G){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:G}})}geoSearch(G){return this.get("geo/search.json",G)}geoReverseGeoCode(G){return this.get("geo/reverse_geocode.json",G)}rateLimitStatuses(...G){return this.get("application/rate_limit_status.json",{resources:G})}supportedLanguages(){return this.get("help/languages.json")}}import*as w from"fs";async function $4(G){let W=await Y4(G);if(typeof W==="number")return new Promise(($,Y)=>{w.readFile(W,(Z,J)=>{if(Z)return Y(Z);$(J)})});else if(W instanceof Buffer)return W;else return W.readFile()}function Y4(G){if(typeof G==="string")return w.promises.open(G,"r");else if(typeof G==="number")return G;else if(typeof G==="object"&&!(G instanceof Buffer))return G;else if(!(G instanceof Buffer))throw Error("Given file is not valid, please check its type.");else return G}async function J0(G){if(typeof G==="number")return(await new Promise(($,Y)=>{w.fstat(G,(Z,J)=>{if(Z)Y(Z);$(J)})})).size;else if(G instanceof Buffer)return G.length;else return(await G.stat()).size}function Q0(G,W,$){if(typeof $==="string")return $;else if(typeof G==="string"&&!W)return y0(G);else if(typeof W==="string")return A0(W);throw Error("You must specify type if file is a file handle or Buffer.")}function y0(G){if(G.endsWith(".jpeg")||G.endsWith(".jpg"))return j.Jpeg;if(G.endsWith(".png"))return j.Png;if(G.endsWith(".webp"))return j.Webp;if(G.endsWith(".gif"))return j.Gif;if(G.endsWith(".mpeg4")||G.endsWith(".mp4"))return j.Mp4;if(G.endsWith(".mov")||G.endsWith(".mov"))return j.Mov;if(G.endsWith(".srt"))return j.Srt;return V1({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"}),j.Jpeg}function A0(G){if(V1({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"}),G==="gif")return j.Gif;if(G==="jpg")return j.Jpeg;if(G==="png")return j.Png;if(G==="webp")return j.Webp;if(G==="srt")return j.Srt;if(G==="mp4"||G==="longmp4")return j.Mp4;if(G==="mov")return j.Mov;return G}function K0(G,W){if(G===j.Mp4||G===j.Mov)return W==="tweet"?"TweetVideo":"DmVideo";if(G===j.Gif)return W==="tweet"?"TweetGif":"DmGif";if(G===j.Srt)return"Subtitles";else return W==="tweet"?"TweetImage":"DmImage"}function Z4(G){return new Promise((W)=>setTimeout(W,G*1000))}async function J4(G,W,$=0,Y){if(G instanceof Buffer){let J=G.slice($,$+W);return[J,J.length]}if(!Y)throw Error("Well, we will need a buffer to store file content.");let Z;if(typeof G==="number")Z=await new Promise((J,Q)=>{w.read(G,Y,0,W,$,(K,z)=>{if(K)Q(K);J(z)})});else Z=(await G.read(Y,0,W,$)).bytesRead;return[Y,Z]}var Q4="media/upload.json";class l extends p{constructor(){super(...arguments);this._prefix=C}get readOnly(){return this}tweet(G,W={}){let $={status:G,tweet_mode:"extended",...W};return this.post("statuses/update.json",$)}async quote(G,W,$={}){let Y="https://x.com/i/statuses/"+W;return this.tweet(G,{...$,attachment_url:Y})}async tweetThread(G){let W=[];for(let $ of G){let Y=W.length?W[W.length-1]:null,Z={...typeof $==="string"?{status:$}:$},J=Y?Y.id_str:Z.in_reply_to_status_id,Q=Z.status;if(J)W.push(await this.reply(Q,J,Z));else W.push(await this.tweet(Q,Z))}return W}reply(G,W,$={}){return this.tweet(G,{auto_populate_reply_metadata:!0,in_reply_to_status_id:W,...$})}deleteTweet(G){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:G}})}reportUserAsSpam(G){return this.post("users/report_spam.json",{tweet_mode:"extended",...G})}updateFriendship(G){return this.post("friendships/update.json",G)}createFriendship(G){return this.post("friendships/create.json",G)}destroyFriendship(G){return this.post("friendships/destroy.json",G)}updateAccountSettings(G){return this.post("account/settings.json",G)}updateAccountProfile(G){return this.post("account/update_profile.json",G)}async updateAccountProfileBanner(G,W={}){let $={banner:await $4(G),...W};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(G,W={}){let $={tweet_mode:"extended",image:await $4(G),...W};return this.post("account/update_profile_image.json",$,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(G){return this.post("lists/create.json",{tweet_mode:"extended",...G})}updateList(G){return this.post("lists/update.json",{tweet_mode:"extended",...G})}removeList(G){return this.post("lists/destroy.json",{tweet_mode:"extended",...G})}addListMembers(G){let $=G.user_id&&J1(G.user_id)||G.screen_name&&J1(G.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,G)}removeListMembers(G){let $=G.user_id&&J1(G.user_id)||G.screen_name&&J1(G.screen_name)?"lists/members/destroy_all.json":"lists/members/destroy.json";return this.post($,G)}subscribeToList(G){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...G})}unsubscribeOfList(G){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...G})}createMediaMetadata(G,W){return this.post("media/metadata/create.json",{media_id:G,...W},{prefix:h,forceBodyMode:"json"})}createMediaSubtitles(G,W){return this.post("media/subtitles/create.json",{media_id:G,media_category:"TweetVideo",subtitle_info:{subtitles:W}},{prefix:h,forceBodyMode:"json"})}deleteMediaSubtitles(G,...W){return this.post("media/subtitles/delete.json",{media_id:G,media_category:"TweetVideo",subtitle_info:{subtitles:W.map(($)=>({language_code:$}))}},{prefix:h,forceBodyMode:"json"})}async uploadMedia(G,W={},$=!1){var Y;let Z=(Y=W.chunkLength)!==null&&Y!==void 0?Y:1048576,{fileHandle:J,mediaCategory:Q,fileSize:K,mimeType:z}=await this.getUploadMediaRequirements(G,W);try{let X=await this.post(Q4,{command:"INIT",total_bytes:K,media_type:z,media_category:Q,additional_owners:W.additionalOwners,shared:W.shared?!0:void 0},{prefix:h});await this.mediaChunkedUpload(J,Z,X.media_id_string,W.maxConcurrentUploads);let M=await this.post(Q4,{command:"FINALIZE",media_id:X.media_id_string},{prefix:h});if(M.processing_info&&M.processing_info.state!=="succeeded")await this.awaitForMediaProcessingCompletion(M);if($)return M;else return M.media_id_string}finally{if(typeof G==="number")K4.close(G,()=>{});else if(typeof J==="object"&&!(J instanceof Buffer))J.close()}}async awaitForMediaProcessingCompletion(G){var W;while(!0){G=await this.mediaInfo(G.media_id_string);let{processing_info:$}=G;if(!$||$.state==="succeeded")return;if((W=$.error)===null||W===void 0?void 0:W.code){let{name:Y,message:Z}=$.error;throw Error(`Failed to process media: ${Y} - ${Z}.`)}if($.state==="failed")throw Error("Failed to process the media.");if($.check_after_secs)await Z4($.check_after_secs);else await Z4(5)}}async getUploadMediaRequirements(G,{mimeType:W,type:$,target:Y,longVideo:Z}={}){let J;try{J=await Y4(G);let Q=Q0(G,$,W),K;if(Q===j.Mp4&&(!W&&!$&&Y!=="dm"||Z))K="amplify_video";else K=K0(Q,Y!==null&&Y!==void 0?Y:"tweet");return{fileHandle:J,mediaCategory:K,fileSize:await J0(J),mimeType:Q}}catch(Q){if(typeof G==="number")K4.close(G,()=>{});else if(typeof J==="object"&&!(J instanceof Buffer))J.close();throw Q}}async mediaChunkedUpload(G,W,$,Y=3){let Z=0;if(Y<1)throw RangeError("Bad maxConcurrentUploads parameter.");let J=G instanceof Buffer?void 0:Buffer.alloc(W),Q,K,z=0;[Q,K]=await J4(G,W,z,J),z+=K;let X=new Set;while(K){let M=Q.slice(0,K);if(M.length){let B=this.post(Q4,{command:"APPEND",media_id:$,segment_index:Z,media:M},{prefix:h});X.add(B),B.then(()=>{X.delete(B)}),Z++}if(X.size>=Y)await Promise.race(X);[Q,K]=await J4(G,W,z,J),z+=K}await Promise.all([...X])}}class X0 extends l{constructor(){super(...arguments);this._prefix=C}get readWrite(){return this}sendDm({recipient_id:G,custom_profile_id:W,...$}){let Y={event:{type:I.Create,[I.Create]:{target:{recipient_id:G},message_data:$}}};if(W)Y.event[I.Create].custom_profile_id=W;return this.post("direct_messages/events/new.json",Y,{forceBodyMode:"json"})}getDmEvent(G){return this.get("direct_messages/events/show.json",{id:G})}deleteDm(G){return this.delete("direct_messages/events/destroy.json",{id:G})}async listDmEvents(G={}){let W={...G},$=await this.get("direct_messages/events/list.json",W,{fullResponse:!0});return new P1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}newWelcomeDm(G,W){let $={[I.WelcomeCreate]:{name:G,message_data:W}};return this.post("direct_messages/welcome_messages/new.json",$,{forceBodyMode:"json"})}getWelcomeDm(G){return this.get("direct_messages/welcome_messages/show.json",{id:G})}deleteWelcomeDm(G){return this.delete("direct_messages/welcome_messages/destroy.json",{id:G})}updateWelcomeDm(G,W){let $={message_data:W};return this.put("direct_messages/welcome_messages/update.json",$,{forceBodyMode:"json",query:{id:G}})}async listWelcomeDms(G={}){let W={...G},$=await this.get("direct_messages/welcome_messages/list.json",W,{fullResponse:!0});return new y1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}newWelcomeDmRule(G){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:G}},{forceBodyMode:"json"})}getWelcomeDmRule(G){return this.get("direct_messages/welcome_messages/rules/show.json",{id:G})}deleteWelcomeDmRule(G){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:G})}async listWelcomeDmRules(G={}){let W={...G};return this.get("direct_messages/welcome_messages/rules/list.json",W)}async setWelcomeDm(G,W=!0){var $;let Y=await this.listWelcomeDmRules();if(($=Y.welcome_message_rules)===null||$===void 0?void 0:$.length){for(let Z of Y.welcome_message_rules)if(await this.deleteWelcomeDmRule(Z.id),W)await this.deleteWelcomeDm(Z.welcome_message_id)}return this.newWelcomeDmRule(G)}markDmAsRead(G,W){return this.post("direct_messages/mark_read.json",{last_read_event_id:G,recipient_id:W},{forceBodyMode:"url"})}indicateDmTyping(G){return this.post("direct_messages/indicate_typing.json",{recipient_id:G},{forceBodyMode:"url"})}async downloadDmImage(G){if(typeof G!=="string"){let $=G[I.Create].message_data.attachment;if(!$)throw Error("The given direct message doesn't contain any attachment");G=$.media.media_url_https}let W=await this.get(G,void 0,{forceParseMode:"buffer",prefix:""});if(!W.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return W}}var U1=X0;class N{constructor(G){this.result=G}get tweets(){return N.tweets(this.result)}static tweets(G){var W,$;return($=(W=G.includes)===null||W===void 0?void 0:W.tweets)!==null&&$!==void 0?$:[]}tweetById(G){return N.tweetById(this.result,G)}static tweetById(G,W){return this.tweets(G).find(($)=>$.id===W)}retweet(G){return N.retweet(this.result,G)}static retweet(G,W){var $;let Y=(($=W.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Z)=>Z.type==="retweeted").map((Z)=>Z.id);return this.tweets(G).find((Z)=>Y.includes(Z.id))}quote(G){return N.quote(this.result,G)}static quote(G,W){var $;let Y=(($=W.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Z)=>Z.type==="quoted").map((Z)=>Z.id);return this.tweets(G).find((Z)=>Y.includes(Z.id))}repliedTo(G){return N.repliedTo(this.result,G)}static repliedTo(G,W){var $;let Y=(($=W.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Z)=>Z.type==="replied_to").map((Z)=>Z.id);return this.tweets(G).find((Z)=>Y.includes(Z.id))}author(G){return N.author(this.result,G)}static author(G,W){let $=W.author_id;return $?this.users(G).find((Y)=>Y.id===$):void 0}repliedToAuthor(G){return N.repliedToAuthor(this.result,G)}static repliedToAuthor(G,W){let $=W.in_reply_to_user_id;return $?this.users(G).find((Y)=>Y.id===$):void 0}get users(){return N.users(this.result)}static users(G){var W,$;return($=(W=G.includes)===null||W===void 0?void 0:W.users)!==null&&$!==void 0?$:[]}userById(G){return N.userById(this.result,G)}static userById(G,W){return this.users(G).find(($)=>$.id===W)}pinnedTweet(G){return N.pinnedTweet(this.result,G)}static pinnedTweet(G,W){return W.pinned_tweet_id?this.tweets(G).find(($)=>$.id===W.pinned_tweet_id):void 0}get media(){return N.media(this.result)}static media(G){var W,$;return($=(W=G.includes)===null||W===void 0?void 0:W.media)!==null&&$!==void 0?$:[]}medias(G){return N.medias(this.result,G)}static medias(G,W){var $,Y;let Z=(Y=($=W.attachments)===null||$===void 0?void 0:$.media_keys)!==null&&Y!==void 0?Y:[];return this.media(G).filter((J)=>Z.includes(J.media_key))}get polls(){return N.polls(this.result)}static polls(G){var W,$;return($=(W=G.includes)===null||W===void 0?void 0:W.polls)!==null&&$!==void 0?$:[]}poll(G){return N.poll(this.result,G)}static poll(G,W){var $,Y;let Z=(Y=($=W.attachments)===null||$===void 0?void 0:$.poll_ids)!==null&&Y!==void 0?Y:[];if(Z.length){let J=Z[0];return this.polls(G).find((Q)=>Q.id===J)}return}get places(){return N.places(this.result)}static places(G){var W,$;return($=(W=G.includes)===null||W===void 0?void 0:W.places)!==null&&$!==void 0?$:[]}place(G){return N.place(this.result,G)}static place(G,W){var $;let Y=($=W.geo)===null||$===void 0?void 0:$.place_id;return Y?this.places(G).find((Z)=>Z.id===Y):void 0}listOwner(G){return N.listOwner(this.result,G)}static listOwner(G,W){let $=W.owner_id;return $?this.users(G).find((Y)=>Y.id===$):void 0}spaceCreator(G){return N.spaceCreator(this.result,G)}static spaceCreator(G,W){let $=W.creator_id;return $?this.users(G).find((Y)=>Y.id===$):void 0}spaceHosts(G){return N.spaceHosts(this.result,G)}static spaceHosts(G,W){var $;let Y=($=W.host_ids)!==null&&$!==void 0?$:[];return this.users(G).filter((Z)=>Y.includes(Z.id))}spaceSpeakers(G){return N.spaceSpeakers(this.result,G)}static spaceSpeakers(G,W){var $;let Y=($=W.speaker_ids)!==null&&$!==void 0?$:[];return this.users(G).filter((Z)=>Y.includes(Z.id))}spaceInvitedUsers(G){return N.spaceInvitedUsers(this.result,G)}static spaceInvitedUsers(G,W){var $;let Y=($=W.invited_user_ids)!==null&&$!==void 0?$:[];return this.users(G).filter((Z)=>Y.includes(Z.id))}}class f1 extends q1{updateIncludes(G){if(G.errors){if(!this._realData.errors)this._realData.errors=[];this._realData.errors=[...this._realData.errors,...G.errors]}if(!G.includes)return;if(!this._realData.includes)this._realData.includes={};let W=this._realData.includes;for(let[$,Y]of Object.entries(G.includes)){if(!W[$])W[$]=[];W[$]=[...W[$],...Y]}}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 G;if(!((G=this._realData)===null||G===void 0?void 0:G.includes))return new N(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new N(this._realData)}get errors(){var G;return(G=this._realData.errors)!==null&&G!==void 0?G:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class R extends f1{refreshInstanceFromResult(G,W){var $;let Y=G.data,Z=($=Y.data)!==null&&$!==void 0?$:[];if(this._rateLimit=G.rateLimit,!this._realData.data)this._realData.data=[];if(W)this._realData.meta.result_count+=Y.meta.result_count,this._realData.meta.next_token=Y.meta.next_token,this._realData.data.push(...Z);else this._realData.meta.result_count+=Y.meta.result_count,this._realData.meta.previous_token=Y.meta.previous_token,this._realData.data.unshift(...Z);this.updateIncludes(Y)}getNextQueryParams(G){return this.assertUsable(),{...this.injectQueryParams(G),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(G){return this.assertUsable(),{...this.injectQueryParams(G),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(G){var W,$;return($=(W=G.data.data)===null||W===void 0?void 0:W.length)!==null&&$!==void 0?$:0}isFetchLastOver(G){var W;return!((W=G.data.data)===null||W===void 0?void 0:W.length)||!this.canFetchNextPage(G.data)}canFetchNextPage(G){var W;return!!((W=G.meta)===null||W===void 0?void 0:W.next_token)}}class X4 extends f1{refreshInstanceFromResult(G,W){var $;let Y=G.data,Z=($=Y.data)!==null&&$!==void 0?$:[];if(this._rateLimit=G.rateLimit,!this._realData.data)this._realData.data=[];if(W)this._realData.meta.oldest_id=Y.meta.oldest_id,this._realData.meta.result_count+=Y.meta.result_count,this._realData.meta.next_token=Y.meta.next_token,this._realData.data.push(...Z);else this._realData.meta.newest_id=Y.meta.newest_id,this._realData.meta.result_count+=Y.meta.result_count,this._realData.data.unshift(...Z);this.updateIncludes(Y)}getNextQueryParams(G){this.assertUsable();let W={...this.injectQueryParams(G)};if(this._realData.meta.next_token)W.next_token=this._realData.meta.next_token;else{if(W.start_time)W.since_id=this.dateStringToSnowflakeId(W.start_time),delete W.start_time;if(W.end_time)delete W.end_time;W.until_id=this._realData.meta.oldest_id}return W}getPreviousQueryParams(G){return this.assertUsable(),{...this.injectQueryParams(G),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(G){var W,$;return($=(W=G.data.data)===null||W===void 0?void 0:W.length)!==null&&$!==void 0?$:0}isFetchLastOver(G){var W;return!((W=G.data.data)===null||W===void 0?void 0:W.length)||!this.canFetchNextPage(G.data)}canFetchNextPage(G){return!!G.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(G){let W=BigInt("1288834974657"),$=new Date(G);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())-W<<BigInt("22")).toString()}get tweets(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class n extends R{refreshInstanceFromResult(G,W){super.refreshInstanceFromResult(G,W);let $=G.data;if(W)this._realData.meta.oldest_id=$.meta.oldest_id;else this._realData.meta.newest_id=$.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class z4 extends X4{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class x4 extends X4{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class M4 extends n{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class B4 extends n{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class N4 extends n{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class j4 extends n{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class F4 extends n{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class L4 extends R{get tweets(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class D4 extends L4{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class O4 extends L4{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class v extends R{getItemArray(){return this.users}get users(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class H4 extends v{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class U4 extends v{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class f4 extends v{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class S4 extends v{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class k4 extends v{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class R4 extends v{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class h4 extends v{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class v4 extends v{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class S1 extends R{getItemArray(){return this.lists}get lists(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class _4 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class b4 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class C4 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class i extends H{constructor(){super(...arguments);this._prefix=g}}class k1 extends R{getItemArray(){return this.events}get events(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class I4 extends k1{constructor(){super(...arguments);this._endpoint="dm_events"}}class T4 extends k1{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class w4 extends k1{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class o extends H{constructor(){super(...arguments);this._prefix=b}get labs(){if(this._labs)return this._labs;return this._labs=new i(this)}async search(G,W={}){let $=typeof G==="string"?{...W,query:G}:{...G},Y=await this.get("tweets/search/recent",$,{fullResponse:!0});return new z4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$})}async searchAll(G,W={}){let $={...W,query:G},Y=await this.get("tweets/search/all",$,{fullResponse:!0});return new x4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$})}singleTweet(G,W={}){return this.get("tweets/:id",W,{params:{id:G}})}tweets(G,W={}){return this.get("tweets",{ids:G,...W})}tweetCountRecent(G,W={}){return this.get("tweets/counts/recent",{query:G,...W})}tweetCountAll(G,W={}){return this.get("tweets/counts/all",{query:G,...W})}async tweetRetweetedBy(G,W={}){let{asPaginator:$,...Y}=W,Z=await this.get("tweets/:id/retweeted_by",Y,{fullResponse:!0,params:{id:G}});if(!$)return Z.data;return new v4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:Y,sharedParams:{id:G}})}async tweetLikedBy(G,W={}){let{asPaginator:$,...Y}=W,Z=await this.get("tweets/:id/liking_users",Y,{fullResponse:!0,params:{id:G}});if(!$)return Z.data;return new h4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:Y,sharedParams:{id:G}})}async homeTimeline(G={}){let W=await this.getCurrentUserV2Object(),$=await this.get("users/:id/timelines/reverse_chronological",G,{fullResponse:!0,params:{id:W.data.id}});return new B4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:G,sharedParams:{id:W.data.id}})}async userTimeline(G,W={}){let $=await this.get("users/:id/tweets",W,{fullResponse:!0,params:{id:G}});return new N4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:G}})}async userMentionTimeline(G,W={}){let $=await this.get("users/:id/mentions",W,{fullResponse:!0,params:{id:G}});return new j4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:G}})}async quotes(G,W={}){let $=await this.get("tweets/:id/quote_tweets",W,{fullResponse:!0,params:{id:G}});return new M4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:G}})}async bookmarks(G={}){let W=await this.getCurrentUserV2Object(),$=await this.get("users/:id/bookmarks",G,{fullResponse:!0,params:{id:W.data.id}});return new F4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:G,sharedParams:{id:W.data.id}})}me(G={}){return this.get("users/me",G)}user(G,W={}){return this.get("users/:id",W,{params:{id:G}})}users(G,W={}){let $=Array.isArray(G)?G.join(","):G;return this.get("users",{...W,ids:$})}userByUsername(G,W={}){return this.get("users/by/username/:username",W,{params:{username:G}})}usersByUsernames(G,W={}){return G=Array.isArray(G)?G.join(","):G,this.get("users/by",{...W,usernames:G})}async followers(G,W={}){let{asPaginator:$,...Y}=W,Z={id:G};if(!$)return this.get("users/:id/followers",Y,{params:Z});let J=await this.get("users/:id/followers",Y,{fullResponse:!0,params:Z});return new f4({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:Y,sharedParams:Z})}async following(G,W={}){let{asPaginator:$,...Y}=W,Z={id:G};if(!$)return this.get("users/:id/following",Y,{params:Z});let J=await this.get("users/:id/following",Y,{fullResponse:!0,params:Z});return new S4({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:Y,sharedParams:Z})}async userLikedTweets(G,W={}){let $={id:G},Y=await this.get("users/:id/liked_tweets",W,{fullResponse:!0,params:$});return new D4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}async userBlockingUsers(G,W={}){let $={id:G},Y=await this.get("users/:id/blocking",W,{fullResponse:!0,params:$});return new H4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}async userMutingUsers(G,W={}){let $={id:G},Y=await this.get("users/:id/muting",W,{fullResponse:!0,params:$});return new U4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}list(G,W={}){return this.get("lists/:id",W,{params:{id:G}})}async listsOwned(G,W={}){let $={id:G},Y=await this.get("users/:id/owned_lists",W,{fullResponse:!0,params:$});return new _4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}async listMemberships(G,W={}){let $={id:G},Y=await this.get("users/:id/list_memberships",W,{fullResponse:!0,params:$});return new b4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}async listFollowed(G,W={}){let $={id:G},Y=await this.get("users/:id/followed_lists",W,{fullResponse:!0,params:$});return new C4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}async listTweets(G,W={}){let $={id:G},Y=await this.get("lists/:id/tweets",W,{fullResponse:!0,params:$});return new O4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}async listMembers(G,W={}){let $={id:G},Y=await this.get("lists/:id/members",W,{fullResponse:!0,params:$});return new k4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}async listFollowers(G,W={}){let $={id:G},Y=await this.get("lists/:id/followers",W,{fullResponse:!0,params:$});return new R4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}async listDmEvents(G={}){let W=await this.get("dm_events",G,{fullResponse:!0});return new I4({realData:W.data,rateLimit:W.rateLimit,instance:this,queryParams:{...G}})}async listDmEventsWithParticipant(G,W={}){let $={participant_id:G},Y=await this.get("dm_conversations/with/:participant_id/dm_events",W,{fullResponse:!0,params:$});return new T4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}async listDmEventsOfConversation(G,W={}){let $={dm_conversation_id:G},Y=await this.get("dm_conversations/:dm_conversation_id/dm_events",W,{fullResponse:!0,params:$});return new w4({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:{...W},sharedParams:$})}space(G,W={}){return this.get("spaces/:id",W,{params:{id:G}})}spaces(G,W={}){return this.get("spaces",{ids:G,...W})}spacesByCreators(G,W={}){return this.get("spaces/by/creator_ids",{user_ids:G,...W})}searchSpaces(G){return this.get("spaces/search",G)}spaceBuyers(G,W={}){return this.get("spaces/:id/buyers",W,{params:{id:G}})}spaceTweets(G,W={}){return this.get("spaces/:id/tweets",W,{params:{id:G}})}searchStream({autoConnect:G,...W}={}){return this.getStream("tweets/search/stream",W,{payloadIsError:N1,autoConnect:G})}streamRules(G={}){return this.get("tweets/search/stream/rules",G)}updateStreamRules(G,W={}){return this.post("tweets/search/stream/rules",G,{query:W})}sampleStream({autoConnect:G,...W}={}){return this.getStream("tweets/sample/stream",W,{payloadIsError:N1,autoConnect:G})}sample10Stream({autoConnect:G,...W}={}){return this.getStream("tweets/sample10/stream",W,{payloadIsError:N1,autoConnect:G})}complianceJobs(G){return this.get("compliance/jobs",G)}complianceJob(G){return this.get("compliance/jobs/:id",void 0,{params:{id:G}})}async sendComplianceJob(G){let W=await this.post("compliance/jobs",{type:G.type,name:G.name}),$=G.ids instanceof Buffer?G.ids:Buffer.from(G.ids.join(`
34
+ `));return await this.put(W.data.upload_url,$,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),W}async complianceJobResult(G){let W=G;while(W.status!=="complete"){if(W.status==="expired"||W.status==="failed")throw Error("Job failed to be completed.");await new Promise((Y)=>setTimeout(Y,3500)),W=(await this.complianceJob(G.id)).data}return(await this.get(G.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split(`
35
+ `).filter((Y)=>Y).map((Y)=>JSON.parse(Y))}async usage(G={}){return this.get("usage/tweets",G)}community(G,W={}){return this.get("communities/:id",W,{params:{id:G}})}searchCommunities(G,W={}){return this.get("communities/search",{query:G,...W})}}class s extends i{constructor(){super(...arguments);this._prefix=g}get readOnly(){return this}}class a extends o{constructor(){super(...arguments);this._prefix=b}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new s(this)}hideReply(G,W){return this.put("tweets/:id/hidden",{hidden:W},{params:{id:G}})}like(G,W){return this.post("users/:id/likes",{tweet_id:W},{params:{id:G}})}unlike(G,W){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:G,tweet_id:W}})}retweet(G,W){return this.post("users/:id/retweets",{tweet_id:W},{params:{id:G}})}unretweet(G,W){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:G,tweet_id:W}})}tweet(G,W={}){if(typeof G==="object")W=G;else W={text:G,...W};return this.post("tweets",W)}async uploadMedia(G,W,$=1048576){let Y=W.media_category;if(!W.media_category){if(W.media_type.includes("gif"))Y="tweet_gif";else if(W.media_type.includes("image"))Y="tweet_image";else if(W.media_type.includes("video"))Y="tweet_video"}let Z={additional_owners:W.additional_owners,media_type:W.media_type,total_bytes:G.length,media_category:Y},Q=(await this.post("media/upload/initialize",Z)).data.id,K=Math.ceil(G.length/$),z=new Uint8Array(G);for(let M=0;M<K;M++){let B=M*$,S=Math.min(B+$,G.length),k=z.slice(B,S),t=Buffer.from(k),H0={segment_index:M,media:t};await this.post(`media/upload/${Q}/append`,H0,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${Q}/finalize`)).data.processing_info)await this.waitForMediaProcessing(Q);return Q}async waitForMediaProcessing(G){var W;let Y=(await this.get("media/upload",{command:"STATUS",media_id:G})).data.processing_info;if(!Y)return;switch(Y.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(W=Y.error)===null||W===void 0?void 0:W.message}`);case"pending":case"in_progress":{let Z=Y===null||Y===void 0?void 0:Y.check_after_secs;if(Z&&Z>0)await new Promise((J)=>setTimeout(J,Z*1000)),await this.waitForMediaProcessing(G)}}}createMediaMetadata(G,W){return this.post("media/metadata",{id:G,metadata:W})}reply(G,W,$={}){var Y;let Z={in_reply_to_tweet_id:W,...(Y=$.reply)!==null&&Y!==void 0?Y:{}};return this.post("tweets",{text:G,...$,reply:Z})}quote(G,W,$={}){return this.tweet(G,{...$,quote_tweet_id:W})}async tweetThread(G){var W,$;let Y=[];for(let Z of G){let J=Y.length?Y[Y.length-1]:null,Q={...typeof Z==="string"?{text:Z}:Z},K=J?J.data.id:(W=Q.reply)===null||W===void 0?void 0:W.in_reply_to_tweet_id,z=($=Q.text)!==null&&$!==void 0?$:"";if(K)Y.push(await this.reply(z,K,Q));else Y.push(await this.tweet(z,Q))}return Y}deleteTweet(G){return this.delete("tweets/:id",void 0,{params:{id:G}})}async bookmark(G){let W=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:G},{params:{id:W.data.id}})}async deleteBookmark(G){let W=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:W.data.id,tweet_id:G}})}follow(G,W){return this.post("users/:id/following",{target_user_id:W},{params:{id:G}})}unfollow(G,W){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:G,target_user_id:W}})}block(G,W){return this.post("users/:id/blocking",{target_user_id:W},{params:{id:G}})}unblock(G,W){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:G,target_user_id:W}})}mute(G,W){return this.post("users/:id/muting",{target_user_id:W},{params:{id:G}})}unmute(G,W){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:G,target_user_id:W}})}createList(G){return this.post("lists",G)}updateList(G,W={}){return this.put("lists/:id",W,{params:{id:G}})}removeList(G){return this.delete("lists/:id",void 0,{params:{id:G}})}addListMember(G,W){return this.post("lists/:id/members",{user_id:W},{params:{id:G}})}removeListMember(G,W){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:G,user_id:W}})}subscribeToList(G,W){return this.post("users/:id/followed_lists",{list_id:W},{params:{id:G}})}unsubscribeOfList(G,W){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:G,list_id:W}})}pinList(G,W){return this.post("users/:id/pinned_lists",{list_id:W},{params:{id:G}})}unpinList(G,W){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:G,list_id:W}})}sendDmInConversation(G,W){return this.post("dm_conversations/:dm_conversation_id/messages",W,{params:{dm_conversation_id:G}})}sendDmToParticipant(G,W){return this.post("dm_conversations/with/:participant_id/messages",W,{params:{participant_id:G}})}createDmConversation(G){return this.post("dm_conversations",G)}}class z0 extends s{constructor(){super(...arguments);this._prefix=g}get readWrite(){return this}}var x0=z0;class M0 extends a{constructor(){super(...arguments);this._prefix=b}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new x0(this)}}var B0=M0;class X1 extends T{get v1(){if(this._v1)return this._v1;return this._v1=new p(this)}get v2(){if(this._v2)return this._v2;return this._v2=new o(this)}async currentUser(G=!1){return await this.getCurrentUserObject(G)}async currentUserV2(G=!1){return await this.getCurrentUserV2Object(G)}search(G,W){return this.v2.search(G,W)}async generateAuthLink(G="oob",{authAccessType:W,linkMode:$="authenticate",forceLogin:Y,screenName:Z}={}){let J=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:G,x_auth_access_type:W}),Q=`https://api.x.com/oauth/${$}?oauth_token=${encodeURIComponent(J.oauth_token)}`;if(Y!==void 0)Q+=`&force_login=${encodeURIComponent(Y)}`;if(Z!==void 0)Q+=`&screen_name=${encodeURIComponent(Z)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:Q,oauthResult:J});return{url:Q,...J}}async login(G){let W=this.getActiveTokens();if(W.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:W.accessToken,oauth_verifier:G}),Y=new this.constructor({appKey:W.appKey,appSecret:W.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:Y}}async appLogin(){let G=this.getActiveTokens();if(G.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:G.appKey,password:G.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(G,W={}){var $,Y;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 Z=($=W.state)!==null&&$!==void 0?$:y.generateRandomString(32),J=y.getCodeVerifier(),Q=y.getCodeChallengeFromVerifier(J),K=(Y=W.scope)!==null&&Y!==void 0?Y:"",z=Array.isArray(K)?K.join(" "):K,X=new URL("https://x.com/i/oauth2/authorize"),M={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:G,state:Z,code_challenge:Q,code_challenge_method:"s256",scope:z};O.addQueryParamsToUrl(X,M);let B={url:X.toString(),state:Z,codeVerifier:J,codeChallenge:Q};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:B,redirectUri:G});return B}async loginWithOAuth2({code:G,codeVerifier:W,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 Y=await this.post("https://api.x.com/2/oauth2/token",{code:G,code_verifier:W,redirect_uri:$,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(Y)}async refreshOAuth2Token(G){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 W=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:G,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(W)}async revokeOAuth2Token(G,W="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:G,token_type_hint:W})}parseOAuth2AccessTokenResult(G){let W=new this.constructor(G.access_token,this._requestMaker.clientSettings),$=G.scope.split(" ").filter((Y)=>Y);return{client:W,expiresIn:G.expires_in,accessToken:G.access_token,scope:$,refreshToken:G.refresh_token}}}class z1 extends X1{get v1(){if(this._v1)return this._v1;return this._v1=new l(this)}get v2(){if(this._v2)return this._v2;return this._v2=new a(this)}get readOnly(){return this}}class R1 extends H{constructor(){super(...arguments);this._prefix=c}}class h1 extends R1{constructor(){super(...arguments);this._prefix=c}get readOnly(){return this}}class v1 extends H{constructor(){super(...arguments);this._prefix=m}}class _1 extends v1{constructor(){super(...arguments);this._prefix=m}get readOnly(){return this}}class N0 extends _1{constructor(){super(...arguments);this._prefix=m}get readWrite(){return this}}var j0=N0;class F0 extends h1{constructor(){super(...arguments);this._prefix=c}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new j0(this)}}var L0=F0;class q4 extends z1{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 B0(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new L0(this)}static getErrors(G){var W;if(typeof G!=="object")return[];if(!("data"in G))return[];return(W=G.data.errors)!==null&&W!==void 0?W:[]}static getProfileImageInSize(G,W){let $=G.split("/").pop(),Y=["normal","bigger","mini"],Z=G;for(let Q of Y)if($.includes(`_${Q}`)){Z=G.replace(`_${Q}`,"");break}if(W==="original")return Z;let J=Z.lastIndexOf(".");if(J!==-1){let Q=Z.slice(J+1);return Z.slice(0,J)+"_"+W+"."+Q}else return Z+"_"+W}}var V0={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class O0 extends V{config;client;oauthStates=new Map;constructor(G={}){super();this.config={...V0,...G},this.client=new q4({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}getRedirectUrl(){let{url:G,codeVerifier:W,state:$}=this.client.generateOAuth2AuthLink(`${process.env.HOST_NAME}${this.config.redirectPath}`,{scope:this.config.scope});return this.oauthStates.set($,{state:$,codeVerifier:W}),D0.to(G),G}async onCallback(G){let W=G.search.get("code"),$=G.search.get("state"),Y=this.oauthStates.get($);if(!Y)throw Error("Invalid or expired OAuth state");let Z=await this.client.loginWithOAuth2({code:W,codeVerifier:Y.codeVerifier,redirectUri:`${process.env.HOST_NAME}${this.config.redirectPath}`});this.oauthStates.delete($);let{data:J}=await Z.client.v2.me({"user.fields":["name","username","entities"]}),{name:Q,email:K,id:z="",username:X}=J??{};return{name:Q,email:K,username:X,providerId:z}}}export{ZG as viewRouteConfigDefaults,HG as translationConfigDefaults,b1 as toRangeHeaderValue,_G as scheduleConfigDefaults,I1 as resolveRange,aG as redisConfigDefaults,iG as rateLimiterConfigDefaults,FG as queueConfigDefaults,r as parseContentRange,c0 as middlewareConfigDefaults,MG as mailConfigDefaults,gG as logConfigDefaults,r0 as imageConfigDefaults,i0 as filesystemConfigDefaults,CG as discoverJobs,IG as discoverCronJobs,TG as discoverCommands,OG as defineTranslationConfig,vG as defineScheduleConfig,$G as defineRouteConfig,sG as defineRedisConfig,nG as defineRateLimiterConfig,jG as defineQueueConfig,g0 as defineMiddlewareConfig,xG as defineMailConfig,VG as defineLogConfig,t0 as defineImageConfig,n0 as defineFilesystemConfig,SG as defineCommandConfig,RG as defineCommand,EG as defineBroadcastConfig,m0 as defineAuthConfig,kG as commandConfigDefaults,uG as broadcastConfigDefaults,E0 as authConfigDefaults,YG as apiRouteConfigDefaults,O0 as XOAuthProvider,QG as ViewRouteDispatcher,a0 as Sharp,NG as Scheduler,wG as ScheduleServiceProvider,A4 as S3Driver,rG as RouteServiceProvider,zG as ResendDriver,tG as RedisServiceProvider,u4 as RedisRateLimiter,x1 as RedisManager,oG as RateLimiterServiceProvider,T1 as RateLimiterDriver,d0 as RateLimiter,A as RangeNotSatisfiableError,pG as QueueServiceProvider,LG as QueueManager,V as OAuthProvider,mG as MiddlewareServiceProvider,WG as MiddlewareRegistry,qG as MailServiceProvider,BG as MailManager,cG as LogServiceProvider,GG as LogManager,AG as KernelIdServiceProvider,JG as KernelId,bG as Job,lG as InMemoryRateLimiter,yG as ImageServiceProvider,s0 as ImageOptimizationDriver,e0 as ImageManager,d4 as GoogleOAuthProvider,PG as FilesystemServiceProvider,o0 as FilesystemManager,l0 as FileSystemDriver,e as FileStorageDriver,_ as FileNotFoundError,XG as EmailDriver,hG as CronJob,eG as CommandRegistry,UG as CommandFailed,fG as Command,dG as BroadcastServiceProvider,p0 as BroadcastManager,g4 as AzureBlobDriver,DG as AuthServiceProvider,u0 as AuthManager,KG as ApiRouteDispatcher};
45
36
 
46
- //# debugId=8D970C77E5AD7BA064756E2164756E21
37
+ //# debugId=2CD236F96FE8CD9564756E2164756E21