gemi 0.58.0 → 0.59.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/Agent.d.ts +33 -0
- package/dist/ai/Agent.d.ts.map +1 -0
- package/dist/ai/AgentController.d.ts +8 -0
- package/dist/ai/AgentController.d.ts.map +1 -0
- package/dist/ai/useChat.d.ts +12 -0
- package/dist/ai/useChat.d.ts.map +1 -0
- package/dist/app/index.js +1 -1
- package/dist/broadcasting/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-szss069z.js → chunk-06j6rsew.js} +2 -2
- package/dist/{chunk-szss069z.js.map → chunk-06j6rsew.js.map} +1 -1
- package/dist/{chunk-yjzs247s.js → chunk-0fm6jh9b.js} +2 -2
- package/dist/{chunk-yjzs247s.js.map → chunk-0fm6jh9b.js.map} +1 -1
- package/dist/chunk-23h0dmx2.js +5 -0
- package/dist/{chunk-87qab82w.js.map → chunk-23h0dmx2.js.map} +3 -3
- package/dist/{chunk-m3xy5xyf.js → chunk-2cwcfwg3.js} +2 -2
- package/dist/{chunk-m3xy5xyf.js.map → chunk-2cwcfwg3.js.map} +1 -1
- package/dist/{chunk-xzk827r3.js → chunk-2khdxyjb.js} +2 -2
- package/dist/{chunk-xzk827r3.js.map → chunk-2khdxyjb.js.map} +1 -1
- package/dist/{chunk-sy7jbdeb.js → chunk-3296fwss.js} +2 -2
- package/dist/{chunk-sy7jbdeb.js.map → chunk-3296fwss.js.map} +1 -1
- package/dist/{chunk-xdv1b8mr.js → chunk-3gvjn3q4.js} +2 -2
- package/dist/{chunk-xdv1b8mr.js.map → chunk-3gvjn3q4.js.map} +1 -1
- package/dist/{chunk-jhkjz9jr.js → chunk-4dan69s4.js} +2 -2
- package/dist/{chunk-3zxwscmf.js.map → chunk-4dan69s4.js.map} +1 -1
- package/dist/{chunk-hxf1re93.js → chunk-4mcyyh1v.js} +2 -2
- package/dist/{chunk-hxf1re93.js.map → chunk-4mcyyh1v.js.map} +1 -1
- package/dist/{chunk-w62m5f0n.js → chunk-5gdv4n4a.js} +3 -3
- package/dist/{chunk-w62m5f0n.js.map → chunk-5gdv4n4a.js.map} +1 -1
- package/dist/{chunk-j0c6ytkj.js → chunk-8kj3zrm9.js} +3 -3
- package/dist/{chunk-j0c6ytkj.js.map → chunk-8kj3zrm9.js.map} +1 -1
- package/dist/{chunk-0a2xgcj3.js → chunk-98a3k7bp.js} +2 -2
- package/dist/{chunk-0a2xgcj3.js.map → chunk-98a3k7bp.js.map} +1 -1
- package/dist/{chunk-5athahgr.js → chunk-9gsdcjt7.js} +2 -2
- package/dist/{chunk-5athahgr.js.map → chunk-9gsdcjt7.js.map} +1 -1
- package/dist/{chunk-pmhd6zfc.js → chunk-b0t4zp6b.js} +2 -2
- package/dist/{chunk-pmhd6zfc.js.map → chunk-b0t4zp6b.js.map} +1 -1
- package/dist/{chunk-3xadx444.js → chunk-bn1v4sfs.js} +2 -2
- package/dist/{chunk-3xadx444.js.map → chunk-bn1v4sfs.js.map} +1 -1
- package/dist/{chunk-9m2tbf3n.js → chunk-c40n5r4v.js} +2 -2
- package/dist/{chunk-9m2tbf3n.js.map → chunk-c40n5r4v.js.map} +1 -1
- package/dist/{chunk-a2sgjpvq.js → chunk-cejf873g.js} +2 -2
- package/dist/{chunk-a2sgjpvq.js.map → chunk-cejf873g.js.map} +1 -1
- package/dist/{chunk-tss5svjr.js → chunk-cw9y6k15.js} +2 -2
- package/dist/{chunk-tss5svjr.js.map → chunk-cw9y6k15.js.map} +1 -1
- package/dist/{chunk-5n2rvfh3.js → chunk-cyrxdj6a.js} +2 -2
- package/dist/{chunk-5n2rvfh3.js.map → chunk-cyrxdj6a.js.map} +1 -1
- package/dist/chunk-dgasxgsm.js +19 -0
- package/dist/{chunk-hwa5sqw5.js.map → chunk-dgasxgsm.js.map} +6 -6
- package/dist/{chunk-3g5bjvdf.js → chunk-f6dd4gd8.js} +2 -2
- package/dist/{chunk-3g5bjvdf.js.map → chunk-f6dd4gd8.js.map} +1 -1
- package/dist/{chunk-qgxr0g36.js → chunk-fb4cy6sq.js} +2 -2
- package/dist/{chunk-qgxr0g36.js.map → chunk-fb4cy6sq.js.map} +1 -1
- package/dist/{chunk-7ef5n8k2.js → chunk-fbvvqf9b.js} +2 -2
- package/dist/{chunk-7ef5n8k2.js.map → chunk-fbvvqf9b.js.map} +1 -1
- package/dist/{chunk-zbxgbr12.js → chunk-fxy42w6n.js} +2 -2
- package/dist/{chunk-zbxgbr12.js.map → chunk-fxy42w6n.js.map} +1 -1
- package/dist/{chunk-xey9cbap.js → chunk-get4mkx8.js} +2 -2
- package/dist/{chunk-xey9cbap.js.map → chunk-get4mkx8.js.map} +1 -1
- package/dist/chunk-gfma8e03.js +55 -0
- package/dist/chunk-gfma8e03.js.map +11 -0
- package/dist/{chunk-3zxwscmf.js → chunk-gwchvzdp.js} +2 -2
- package/dist/{chunk-jhkjz9jr.js.map → chunk-gwchvzdp.js.map} +1 -1
- package/dist/{chunk-k0fvsyeh.js → chunk-hsfjt13m.js} +1 -1
- package/dist/{chunk-yf7vz71n.js → chunk-hwhw98hc.js} +1 -1
- package/dist/{chunk-fjm4y8bn.js → chunk-hxb1eg2z.js} +2 -2
- package/dist/{chunk-fjm4y8bn.js.map → chunk-hxb1eg2z.js.map} +1 -1
- package/dist/{chunk-7b0x860b.js → chunk-j06g4sqc.js} +2 -2
- package/dist/{chunk-7b0x860b.js.map → chunk-j06g4sqc.js.map} +1 -1
- package/dist/{chunk-dgsgjg53.js → chunk-j23cengk.js} +2 -2
- package/dist/{chunk-dgsgjg53.js.map → chunk-j23cengk.js.map} +1 -1
- package/dist/{chunk-8gew8b9a.js → chunk-n412aa9s.js} +3 -3
- package/dist/{chunk-8gew8b9a.js.map → chunk-n412aa9s.js.map} +1 -1
- package/dist/{chunk-437085pe.js → chunk-p3qd0gqa.js} +2 -2
- package/dist/{chunk-437085pe.js.map → chunk-p3qd0gqa.js.map} +1 -1
- package/dist/{chunk-gw6agevz.js → chunk-pkjq9833.js} +3 -3
- package/dist/{chunk-gw6agevz.js.map → chunk-pkjq9833.js.map} +1 -1
- package/dist/{chunk-7j6wbv12.js → chunk-q0y0j3ne.js} +2 -2
- package/dist/{chunk-7j6wbv12.js.map → chunk-q0y0j3ne.js.map} +1 -1
- package/dist/chunk-q6qghsy7.js +5 -0
- package/dist/{chunk-b35e128b.js.map → chunk-q6qghsy7.js.map} +1 -1
- package/dist/{chunk-wbrj0gya.js → chunk-qva4841r.js} +2 -2
- package/dist/{chunk-wbrj0gya.js.map → chunk-qva4841r.js.map} +1 -1
- package/dist/{chunk-86jebsm4.js → chunk-rkbv3df7.js} +3 -3
- package/dist/{chunk-86jebsm4.js.map → chunk-rkbv3df7.js.map} +1 -1
- package/dist/{chunk-keehyx51.js → chunk-rpjsmr41.js} +2 -2
- package/dist/{chunk-keehyx51.js.map → chunk-rpjsmr41.js.map} +1 -1
- package/dist/{chunk-mwpdp09e.js → chunk-spbgpndn.js} +2 -2
- package/dist/{chunk-mwpdp09e.js.map → chunk-spbgpndn.js.map} +1 -1
- package/dist/{chunk-yy0eb9wn.js → chunk-stq96kya.js} +2 -2
- package/dist/{chunk-yy0eb9wn.js.map → chunk-stq96kya.js.map} +1 -1
- package/dist/{chunk-d125j8t0.js → chunk-tds3xq6b.js} +3 -3
- package/dist/{chunk-d125j8t0.js.map → chunk-tds3xq6b.js.map} +1 -1
- package/dist/{chunk-3337e5g0.js → chunk-tey1xayb.js} +2 -2
- package/dist/{chunk-3337e5g0.js.map → chunk-tey1xayb.js.map} +1 -1
- package/dist/{chunk-3aa287k7.js → chunk-txhcx69q.js} +2 -2
- package/dist/{chunk-3aa287k7.js.map → chunk-txhcx69q.js.map} +1 -1
- package/dist/{chunk-w7rf99w6.js → chunk-vj9538yn.js} +2 -2
- package/dist/{chunk-w7rf99w6.js.map → chunk-vj9538yn.js.map} +1 -1
- package/dist/{chunk-yed5whgs.js → chunk-wcv6qtpq.js} +3 -3
- package/dist/{chunk-yed5whgs.js.map → chunk-wcv6qtpq.js.map} +1 -1
- package/dist/{chunk-vr90r27j.js → chunk-wzvs3sym.js} +2 -2
- package/dist/{chunk-vr90r27j.js.map → chunk-wzvs3sym.js.map} +1 -1
- package/dist/{chunk-cyaz97p5.js → chunk-x6y1z4cq.js} +2 -2
- package/dist/{chunk-cyaz97p5.js.map → chunk-x6y1z4cq.js.map} +1 -1
- package/dist/{chunk-6235kb30.js → chunk-xecj8025.js} +3 -3
- package/dist/{chunk-6235kb30.js.map → chunk-xecj8025.js.map} +1 -1
- package/dist/{chunk-eejmhtnc.js → chunk-y64j80v9.js} +2 -2
- package/dist/{chunk-eejmhtnc.js.map → chunk-y64j80v9.js.map} +1 -1
- package/dist/{chunk-zh2egcyb.js → chunk-ygfwtgvm.js} +2 -2
- package/dist/{chunk-zh2egcyb.js.map → chunk-ygfwtgvm.js.map} +1 -1
- package/dist/{chunk-4yt5x8s2.js → chunk-ys904esh.js} +2 -2
- package/dist/{chunk-4yt5x8s2.js.map → chunk-ys904esh.js.map} +1 -1
- package/dist/{chunk-y6a8r2bn.js → chunk-z1e55w67.js} +3 -3
- package/dist/{chunk-y6a8r2bn.js.map → chunk-z1e55w67.js.map} +1 -1
- package/dist/{chunk-qb5mv6pj.js → chunk-z2tcxwyr.js} +3 -3
- package/dist/{chunk-qb5mv6pj.js.map → chunk-z2tcxwyr.js.map} +1 -1
- package/dist/{chunk-hppagzz4.js → chunk-zhbrkpb3.js} +4 -4
- package/dist/{chunk-hppagzz4.js.map → chunk-zhbrkpb3.js.map} +1 -1
- package/dist/{chunk-grdahng8.js → chunk-zqsfanvk.js} +2 -2
- package/dist/{chunk-grdahng8.js.map → chunk-zqsfanvk.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-li1J_igh.js → ThemeProvider-ByU4BQdL.js} +68 -2
- package/dist/chunks/{ThemeProvider-li1J_igh.js.map → ThemeProvider-ByU4BQdL.js.map} +1 -1
- package/dist/client/ComponentContext.d.ts +46 -0
- package/dist/client/ComponentContext.d.ts.map +1 -1
- package/dist/client/index.js +9 -2
- package/dist/client/index.js.map +1 -1
- package/dist/client/init.d.ts.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/Features.d.ts +67 -1
- package/dist/facades/Features.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +2 -2
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/Server.d.ts.map +1 -1
- package/dist/server/httpDev.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +3 -3
- package/dist/services/events/Event.d.ts +6 -0
- package/dist/services/events/Event.d.ts.map +1 -1
- package/dist/services/features/FeatureFlagStore.d.ts +56 -0
- package/dist/services/features/FeatureFlagStore.d.ts.map +1 -1
- package/dist/services/features/FeatureManager.d.ts +35 -1
- package/dist/services/features/FeatureManager.d.ts.map +1 -1
- package/dist/services/features/types.d.ts +62 -0
- package/dist/services/features/types.d.ts.map +1 -1
- package/dist/services/index.d.ts +2 -2
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +8 -8
- package/dist/services/index.js.map +3 -3
- package/dist/services/logging/LogManager.d.ts +10 -1
- package/dist/services/logging/LogManager.d.ts.map +1 -1
- package/dist/services/logging/LogServiceProvider.d.ts +10 -0
- package/dist/services/logging/LogServiceProvider.d.ts.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/testing/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-87qab82w.js +0 -5
- package/dist/chunk-b35e128b.js +0 -5
- package/dist/chunk-hwa5sqw5.js +0 -19
- package/dist/chunk-mkfpnymy.js +0 -55
- package/dist/chunk-mkfpnymy.js.map +0 -11
- /package/dist/{chunk-k0fvsyeh.js.map → chunk-hsfjt13m.js.map} +0 -0
- /package/dist/{chunk-yf7vz71n.js.map → chunk-hwhw98hc.js.map} +0 -0
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Sa as
|
|
2
|
+
import{Sa as q6}from"../chunk-yf8kxjr2.js";import{$a as B6,Ta as AG,Ua as EG,Va as Z6,Wa as m4,Xa as Q6,Ya as K6,Za as X6,_a as z6,ab as x6,bb as U,cb as M6,db as j6,eb as N6,fb as L6,gb as D6,hb as F6,ib as O6,jb as H6,kb as U6,lb as S6,mb as f6,nb as R6,ob as i4,pb as o4,qb as A1,rb as k6,sb as _6,tb as v6,ub as b6,vb as h6,wb as C6,xb as I6,yb as T6}from"../chunk-23h0dmx2.js";import{Ab as gG,Bb as cG,Cb as dG,Db as lG,Eb as pG,Fb as nG,Gb as iG,Hb as oG,Ib as sG,Jb as aG,Kb as tG,Lb as rG,Mb as eG,Nb as G6,Ob as W6,Pb as $6,Qb as Y6,Rb as J6,zb as VG}from"../chunk-b0t4zp6b.js";import{Sb as mG,Tb as uG}from"../chunk-p3qd0gqa.js";import"../chunk-ys904esh.js";import{$b as ZG,Bc as CG,Cc as IG,Hc as N1,Wb as JG,_b as W1,ac as QG,bc as KG,cc as XG,ec as zG,fc as BG,gc as xG,hc as MG,ic as jG,jc as NG,kc as LG,lc as DG,mc as FG,nc as OG,qc as HG,rc as UG,sc as SG,tc as fG,uc as RG,vc as kG,wc as _G,xc as vG,yc as bG,zc as hG}from"../chunk-dgasxgsm.js";import"../chunk-rkbv3df7.js";import"../chunk-z1e55w67.js";import"../chunk-q0y0j3ne.js";import{Ae as $G,Ee as YG,Yd as y1,Zd as P1,_d as G1,ke as V,le as h,pe as v0,ue as r0,ve as e0,xe as GG,ye as WG}from"../chunk-4mcyyh1v.js";import"../chunk-z2tcxwyr.js";import"../chunk-f6dd4gd8.js";import"../chunk-3296fwss.js";import{of as TG,pf as qG,qf as PG,rf as wG,sf as yG}from"../chunk-5gdv4n4a.js";import"../chunk-x6y1z4cq.js";import{xf as g}from"../chunk-tds3xq6b.js";import"../chunk-j23cengk.js";import"../chunk-hxb1eg2z.js";import{If as d4}from"../chunk-4dan69s4.js";import{Buffer as u4}from"buffer";class l4 extends W1{client;config;constructor(...G){super();this.config=G}async connect(){let G=await import("../chunk-zhbrkpb3.js");return this.client??=new G.S3Client(...this.config),{sdk:G,client:this.client}}async put(G){let W,$,Y,J=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,J=G.bucket??J,$=G.contentType||(W instanceof Blob||W instanceof File?W.type:void 0);$=$||void 0;let Z=W instanceof u4?W:W instanceof Blob||W instanceof File?u4.from(await W.arrayBuffer()):"",{sdk:Q,client:K}=await this.connect();return await K.send(new Q.PutObjectCommand({Bucket:J,Key:Y,Body:Z,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:J}=await this.connect(),Z=await J.send(new Y.GetObjectCommand({Bucket:W,Key:$}));return new Response(Z.Body.transformToWebStream(),{headers:{"Content-Type":Z.ContentType,"Content-Length":Z.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":Z.LastModified?.toUTCString()||"",ETag:Z.ETag||""}})}async read(G){let W=typeof G==="string"?{name:G}:G,$=W.bucket??process.env.BUCKET_NAME,{name:Y,range:J=null}=W;if(!Y)throw Error("Object name has to be specified");let{sdk:Z,client:Q}=await this.connect(),K;try{K=await Q.send(new Z.GetObjectCommand({Bucket:$,Key:Y,Range:J?P1(J):void 0}))}catch(M){if(M?.name==="InvalidRange"||M?.$metadata?.httpStatusCode===416)throw new V(await this.size({name:Y,bucket:$}));if(M?.name==="NoSuchKey"||M?.$metadata?.httpStatusCode===404)throw new h(Y);throw M}let z=G1(K.ContentRange),X=Boolean(z)&&K.$metadata?.httpStatusCode===206,x=z?.total??K.ContentLength??0;return{body:K.Body.transformToWebStream(),start:z?.start??0,end:z?.end??x-1,total:x,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:J}=await this.connect();try{return(await J.send(new Y.HeadObjectCommand({Bucket:$,Key:W}))).ContentLength??0}catch(Z){if(Z?.name==="NotFound"||Z?.$metadata?.httpStatusCode===404)throw new h(W);throw Z}}}import{Buffer as p4}from"buffer";import{Readable as I0}from"stream";function w1(G){return G?.statusCode===404||G?.details?.errorCode==="BlobNotFound"||G?.code==="BlobNotFound"}function T0(G){return G?.statusCode===416||G?.details?.errorCode==="InvalidRange"||G?.code==="InvalidRange"}class n4 extends W1{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,J;if(G instanceof Blob)W=G,Y=`${Bun.randomUUIDv7()}.${G.type.split("/")[1].split(";")[0]}`,$=G.type;else W=G.body,Y=G.name,J=G.bucket,$=G.contentType??(W instanceof Blob||W instanceof File?W.type:void 0);let Z=W instanceof p4?W:p4.from(await W.arrayBuffer());return await(await this.blob(Y,J)).uploadData(Z,{blobHTTPHeaders:$?{blobContentType:$}:void 0}),Y}async list(G){let W=this.config.container??process.env.BUCKET_NAME,Y=(await this.serviceClient()).getContainerClient(W),J=[];for await(let Z of Y.listBlobsFlat({prefix:G}))J.push(Z.name);return J}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:J=null}=W,Z=await this.blob($,Y),Q,K,z=J?.kind==="suffix"||J?.kind==="offset"&&J.end===null&&J.start===0;if(J&&z){let k=await this.size({name:$,bucket:Y}),e=y1(J,k);if(!e)throw new V(k);Q=e.start,K=e.length}else if(J?.kind==="offset")Q=J.start,K=J.end===null?void 0:J.end-J.start+1;let X;try{X=await Z.download(Q,K)}catch(k){if(T0(k))throw new V(await this.size({name:$,bucket:Y}));if(w1(k))throw new h($);throw k}let x=G1(X.contentRange),M=Boolean(x),R=x?.total??X.contentLength??0;return{body:await q0(X),start:x?.start??0,end:x?.end??R-1,total:R,partial:M,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(J){if(w1(J))throw new h(W);throw J}}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(J){if(w1(J))throw new h(W);throw J}}}async function q0(G){if(G.blobBody)return await G.blobBody;if(G.readableStreamBody)return I0.toWeb(G.readableStreamBody);return null}var P0=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
|
@@ -26,12 +26,12 @@ current = redis.call("INCRBY", currentKey, cost)
|
|
|
26
26
|
redis.call("PEXPIRE", currentKey, window * 2)
|
|
27
27
|
|
|
28
28
|
return {1, current, previous}
|
|
29
|
-
`;class s4 extends A1{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,J=G.cost??1,Z=Date.now(),Q=i4(Z,Y),K=Z-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(J)]),[x,M,R]=(Array.isArray(X)?X:[]).map(Number);return o4({allowed:x===1,current:Number.isFinite(M)?M:0,previous:Number.isFinite(R)?R:0,now:Z,elapsed:K,window:Y,limit:$,cost:J})}catch(X){if(this.onError(X),!this.failOpen)return{allowed:!1,limit:$,remaining:0,resetAt:Z+Y,retryAfter:Y};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-J)),resetAt:Q+Y,retryAfter:0}}}get client(){if(this.injectedClient)return this.injectedClient;let G=g(),W=G.bound(N1)?G.make(N1).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(J){if(!w0(J))throw J;return this.scriptSha=null,await $.send("EVALSHA",[await this.load($),...Y])}}load(G){if(!this.scriptSha)this.scriptSha=Promise.resolve(G.send("SCRIPT",["LOAD",P0])).then(String).catch((W)=>{throw this.scriptSha=null,W});return this.scriptSha}}function w0(G){return String(G?.message??G).includes("NOSCRIPT")}class Y1 extends U{application;previous;dispatched=[];static install(G){let W=G.resolved(U)?G.make(U):void 0;if(W instanceof Y1)return W;let $=new Y1(G,W);return G.instance(U,$),$}constructor(G,W){super({listeners:[]});this.application=G;this.previous=W}dispatch(G,W){this.dispatched.push({event:G,args:W})}async dispatchAndWait(G,W){this.dispatched.push({event:G,args:W})}restore(){if(this.previous){this.application.instance(U,this.previous);return}this.application.forget(U)}assertDispatched(G,W){let $=$1(G);if(this.matching($,W).length>0)return;throw Error(`Expected ${$}${W?" matching the predicate":""} to have been dispatched. ${this.summary($,W!==void 0)}`)}assertNotDispatched(G,W){let $=$1(G),Y=this.matching($,W);if(Y.length===0)return;throw Error(`Expected ${$}${W?" matching the predicate":""} not to have been dispatched, but it was dispatched ${V1(Y.length)}: ${L1(Y)}.`)}assertDispatchedTimes(G,W,$){let Y=$1(G),J=this.matching(Y,$);if(J.length===W)return;throw Error(`Expected ${Y}${$?" matching the predicate":""} to have been dispatched ${V1(W)}, but it was dispatched ${V1(J.length)}. ${this.summary(Y,$!==void 0)}`)}assertNothingDispatched(){if(this.dispatched.length===0)return;let G=this.dispatched.length;throw Error(`Expected nothing to have been dispatched, but ${G} ${G===1?"event was":"events were"}: ${L1(this.dispatched)}.`)}matching(G,W){return this.dispatched.filter(($)=>$1($.event.constructor)===G&&(W===void 0||W($.event)))}summary(G,W){if(this.dispatched.length===0)return"Nothing was dispatched.";let $=this.matching(G);if(W&&$.length>0)return`Dispatched ${G}: ${L1($)}.`;return`Dispatched: ${L1(this.dispatched)}.`}}function $1(G){return G.name}function V1(G){return`${G} ${G===1?"time":"times"}`}function L1(G){return G.map(y0).join(", ")}function y0(G){let W=$1(G.event.constructor),$=G.args??Object.values({...G.event});return`${W}(${$.map(A0).join(", ")})`}function A0(G){try{return JSON.stringify(G)??String(G)}catch{return String(G)}}class t4{static name="unset";static afterCommit=!1;static dispatch(...G){a4(this),g(U).dispatch(new this(...G),G)}static dispatchAndWait(...G){return a4(this),g(U).dispatchAndWait(new this(...G),G)}static fake(){return Y1.install(g())}}function a4(G){if(G.name!=="unset"&&G.name!=="")return;throw Error("Cannot dispatch an event with no name. Add `static name` to this Event "+"subclass \u2014 the listener registry is keyed by that string, and by that "+"string alone, so an event without one cannot reach a listener.")}class c{}var V0={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 r4 extends c{config;constructor(G={}){super();this.config={...V0,...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[Z,Q]of Object.entries(Y))$.searchParams.append(Z,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(),Z=await(await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${Y}`)).json();if(!Z.email)console.error("Google OAuth error: email not found in user info response",Z);return{name:Z.name,email:Z.email}}}var C="https://api.x.com/2/",E="https://api.x.com/labs/2/",I="https://api.x.com/1.1/",v="https://upload.x.com/1.1/",e4="https://stream.x.com/1.1/",m="https://ads-api.x.com/12/",u="https://ads-api-sandbox.twitter.com/12/";class g1{constructor({realData:G,rateLimit:W,instance:$,queryParams:Y,sharedParams:J}){this._maxResultsWhenFetchLast=100,this._realData=G,this._rateLimit=W,this._instance=$,this._queryParams=Y,this._sharedParams=J}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 c1 extends g1{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 d=g1;class L extends d{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 E1 extends L{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 m1 extends L{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 N;(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"})(N||(N={}));var T;(function(G){G.Create="message_create",G.WelcomeCreate="welcome_message"})(T||(T={}));var J1;(function(G){G.Request="request",G.PartialResponse="partial-response",G.Response="response"})(J1||(J1={}));class D1 extends Error{constructor(){super(...arguments);this.error=!0}}class Z1 extends D1{constructor(G,W){super(G);this.type=J1.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 Q1 extends D1{constructor(G,W){super(G);this.type=J1.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 K1 extends D1{constructor(G,W){super(G);if(this.type=J1.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:w.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((J)=>G.includes(J.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(w.AuthTimestampInvalid,w.AuthenticationFail,w.BadAuthenticationData,w.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var w;(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"})(w||(w={}));var G0;(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"})(G0||(G0={}));var B;(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"})(B||(B={}));class X1{constructor(G){this.value=G}}import*as j4 from"fs";var D={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function u1(G){let W={value:void 0,promise:G().then(($)=>{return W.value=$,$})};return W}function F1(G){if(Array.isArray(G))return G;return[G]}function $0(G){for(let W of Object.keys(G))if(G[W]===void 0)delete G[W]}function O1(G){return typeof G==="object"&&"errors"in G&&!("data"in G)}function z1(G){if(Array.isArray(G)&&G.length>1)return!0;return G.toString().includes(",")}var W0=new Set;function d1(G){if(typeof console>"u"||!console.warn||!D.deprecationWarnings)return;let W=`${G.instance}-${G.method}-${G.problem}`;if(W0.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."),W0.add(W)}import{EventEmitter as u0}from"events";import{request as g0}from"https";import*as F from"zlib";import{EventEmitter as c0}from"events";class Y0{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(D.debug)D.logger.log("Request error:",G);return new Z1("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 Q1(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 J;if(D.debug)D.logger.log(`Request failed with code ${Y}, data:`,W),D.logger.log("Response headers:",G.headers);let Z=`Request failed with code ${Y}`;if((J=W===null||W===void 0?void 0:W.errors)===null||J===void 0?void 0:J.length){let Q=W.errors;if(typeof Q[0]==="object"&&"code"in Q[0])Z+=" - "+this.formatV1Errors(Q);else Z+=" - "+this.formatV2Error(W)}return new K1(Z,{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 $=F.createBrotliDecompress({flush:F.constants.BROTLI_OPERATION_FLUSH,finishFlush:F.constants.BROTLI_OPERATION_FLUSH});return G.pipe($),$}if(W==="gzip"){let $=F.createGunzip({flush:F.constants.Z_SYNC_FLUSH,finishFlush:F.constants.Z_SYNC_FLUSH});return G.pipe($),$}if(W==="deflate"){let $=F.createInflate({flush:F.constants.Z_SYNC_FLUSH,finishFlush:F.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(),J={};for(let[Z,Q]of new URLSearchParams(Y))J[Z]=Q;return J}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",(J)=>this.responseData.push(J)),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",(J)=>this.requestData.requestEventDebugHandler("response-aborted",{error:J})),$.on("error",(J)=>this.requestData.requestEventDebugHandler("response-error",{error:J})),$.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(Z){W(this.createPartialResponseError(Z,!1));return}let J=this.res.statusCode;if(J>=400){W(this.createResponseError({data:Y,res:this.res,rateLimit:$,code:J}));return}if(D.debug)D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),D.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(D.debug)D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${$.statusCode} (starting stream)`);let J=this.getResponseDataStream($);G({req:this.req,res:J,originalResponse:$,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},W,$)}debugRequest(){let G=this.requestData.url;if(D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),G.search)D.logger.log("Request parameters:",[...G.searchParams.entries()].map(([W,$])=>`${W}: ${$}`));if(this.requestData.body)D.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(D.debug)this.debugRequest();this.req=g0({...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)=>{J.emit("complete"),G(Q)},Y=(Q)=>{J.emit("complete"),W(Q)},J=new c0,Z=this.req;if(Z.on("error",this.requestErrorHandler.bind(this,Y)),Z.on("socket",this.onSocketEventHandler.bind(this,Y,J)),Z.on("response",this.classicResponseHandler.bind(this,$,Y)),this.requestData.options.timeout)Z.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(Z);if(this.requestData.body)Z.write(this.requestData.body);Z.end()})}async makeRequestAsStream(){let{req:G,res:W,requestData:$,originalResponse:Y}=await this.makeRequestAndResolveWhenReady();return new H1($,{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 B1=Y0;import{EventEmitter as E0}from"events";class J0 extends E0{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(B.Data,this.onStreamData),G.on(B.ConnectionError,this.onStreamError),G.on(B.TweetParseError,this.onStreamError),G.on(B.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(B.Data,this.onStreamData),this.stream.off(B.ConnectionError,this.onStreamError),this.stream.off(B.TweetParseError,this.onStreamError),this.stream.off(B.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 Z0=J0;import{EventEmitter as m0}from"events";class U1 extends m0{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 J=G.slice($,Y);if($=Y+=2,!J.length)continue;try{let Z=JSON.parse(J);if(Z){this.emit(y.ParsedData,Z);continue}}catch(Z){this.emit(y.ParseError,Z)}}Y++}this.currentMessage=G.slice($,W)}reset(){this.currentMessage=""}}var y;(function(G){G.ParsedData="parsed data",G.ParseError="parse error"})(y||(y={}));var Q0=[5,15,30,60,90,120,180,300,600,900],
|
|
32
|
-
`)return this.emit(B.DataKeepAlive);this.parser.push(W.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let G=this.requestData.payloadIsError;this.parser.on(y.ParsedData,(W)=>{if(G&&G(W))this.emit(B.DataError,W),this.emit(B.Error,{type:B.DataError,error:W,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(B.Data,W)}),this.parser.on(y.ParseError,(W)=>{this.emit(B.TweetParseError,W),this.emit(B.Error,{type:B.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(B.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(B.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let W=await new B1(this.requestData).makeRequestAsStream(),$=this.eventNames();for(let Y of $){let J=this.listeners(Y);for(let Z of J)W.on(Y,Z)}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(B.ConnectError,0),this.emit(B.Error,{type:B.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 B1(this.requestData).makeRequestAndResolveWhenReady();this.req=W,this.res=$,this.originalResponse=Y,this.emit(G?B.Connected:B.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(G=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(B.ConnectionClosed);return}if(G>=this.autoReconnectRetries){this.emit(B.ReconnectLimitExceeded),this.emit(B.ConnectionClosed);return}try{this.emit(B.ReconnectAttempt,G),await this.reconnect()}catch(W){this.emit(B.ReconnectError,G),this.emit(B.Error,{type:B.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 Z0(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 H1=K0;function X0(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 z0(G,W,$,Y){let J;if(Y instanceof Z1||Y instanceof Q1)J=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(G.url),params:G,computedParams:W,requestOptions:$,error:Y});else if(Y instanceof K1)J=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(G.url),params:G,computedParams:W,requestOptions:$,error:Y});if(J&&J instanceof X1)return J.value;return Promise.reject(Y)}import*as M0 from"crypto";class S{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 M0.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=x0(G),$="OAuth ";for(let Y of W){if(Y.key.indexOf("oauth_")!==0)continue;$+=S.percentEncode(Y.key)+'="'+S.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 S.percentEncode(this.consumerKeys.secret)+"&"+S.percentEncode(G||"")}getBaseString(G,W){return G.method.toUpperCase()+"&"+S.percentEncode(this.getBaseUrl(G.url))+"&"+S.percentEncode(this.getParameterString(G,W))}getParameterString(G,W){let $=x0(
|
|
33
|
-
`;f.DEFAULT_CONTENT_TYPE="application/octet-stream";class l1{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[J,Z]of $)Y+=(Y.length?"&":"?")+`${x1.percentEncode(J)}=${x1.percentEncode(Z)}`;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 J in G)Y.append(J,G[J]);if(!W["content-type"]){let J=Y.getHeaders();W["content-type"]=J["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 J=W[Y];if(this.isOAuthSerializable(J))$[Y]=typeof J==="object"&&J!==null&&"toString"in J?J.toString():J}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}}l1.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=l1;import*as j0 from"crypto";class A{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(G){return this.escapeBase64Url(j0.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 l{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,J,Z;if((W=this.clientSettings.plugins)===null||W===void 0?void 0:W.length){let M=await this.applyPreRequestConfigHooks(G);if(M)return M}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 B1({url:Q.url,options:K,body:Q.body,rateLimitSaver:z?this.saveRateLimit.bind(this,Q.rawUrl):void 0,requestEventDebugHandler:G.requestEventDebugHandler,compression:(J=(Y=G.compression)!==null&&Y!==void 0?Y:this.clientSettings.compression)!==null&&J!==void 0?J:!0,forceParseMode:G.forceParseMode}).makeRequest();if(X0(this))X=this.applyResponseErrorHooks(G,Q,K,X);let x=await X;if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length){let M=await this.applyPostRequestHooks(G,Q,K,x);if(M)return M.value}return x}sendStream(G){var W,$;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(G);let Y=this.getHttpRequestArgs(G),J={method:Y.method,headers:Y.headers,agent:this.clientSettings.httpAgent},Z=G.enableRateLimitSave!==!1,Q=G.autoConnect!==!1;if(Y.body)O.setBodyLengthHeader(J,Y.body);let K={url:Y.url,options:J,body:Y.body,rateLimitSaver:Z?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 H1(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 x1({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 J of this.getPlugins()){let Z=await(($=J[G])===null||$===void 0?void 0:$.call(J,W));if(Z&&Z instanceof X1)Y=Z}return Y}writeAuthHeaders({headers:G,bodyInSignature:W,url:$,method:Y,query:J,body:Z}){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 "+A.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let Q=W?O.mergeQueryAndBodyForOAuth(J,Z):J,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:J,forceBodyMode:Z,enableAuth:Q,params:K}){let z=void 0;if(W=W.toUpperCase(),J=J!==null&&J!==void 0?J:{},!J["x-user-agent"])J["x-user-agent"]="Node.twitter-api-v2";let X=this.getUrlObjectFromUrlString(G),x=X.origin+X.pathname;if(K)O.applyRequestParametersToUrl(X,K);let M=O.formatQueryToString($);if(O.moveUrlQueryParamsIntoObject(X,M),!(Y instanceof Buffer))$0(Y);let R=Z!==null&&Z!==void 0?Z:O.autoDetectBodyType(X);if(Q!==!1){let k=l.BODY_METHODS.has(W)&&R==="url";J=this.writeAuthHeaders({headers:J,bodyInSignature:k,method:W,query:M,url:X,body:Y})}if(l.BODY_METHODS.has(W))z=O.constructBodyParams(Y,J,R)||void 0;return O.addQueryParamsToUrl(X,M),{rawUrl:x,url:X,method:W,headers:J,body:z}}async applyPreRequestConfigHooks(G){var W;let $=this.getUrlObjectFromUrlString(G.url);for(let Y of this.getPlugins()){let J=await((W=Y.onBeforeRequestConfig)===null||W===void 0?void 0:W.call(Y,{client:this,url:$,params:G}));if(J)return J}}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(z0.bind(this,G,W,$))}}l.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class q{constructor(G,W={}){if(this._currentUser=null,this._currentUserV2=null,G instanceof q)this._requestMaker=G._requestMaker;else this._requestMaker=new l(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=u1(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:I})),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=u1(()=>this.get("users/me",void 0,{prefix:C})),this._currentUserV2.promise}async get(G,W={},{fullResponse:$,prefix:Y=this._prefix,...J}={}){if(Y)G=Y+G;let Z=await this._requestMaker.send({url:G,method:"GET",query:W,...J});return $?Z:Z.data}async delete(G,W={},{fullResponse:$,prefix:Y=this._prefix,...J}={}){if(Y)G=Y+G;let Z=await this._requestMaker.send({url:G,method:"DELETE",query:W,...J});return $?Z:Z.data}async post(G,W,{fullResponse:$,prefix:Y=this._prefix,...J}={}){if(Y)G=Y+G;let Z=await this._requestMaker.send({url:G,method:"POST",body:W,...J});return $?Z:Z.data}async put(G,W,{fullResponse:$,prefix:Y=this._prefix,...J}={}){if(Y)G=Y+G;let Z=await this._requestMaker.send({url:G,method:"PUT",body:W,...J});return $?Z:Z.data}async patch(G,W,{fullResponse:$,prefix:Y=this._prefix,...J}={}){if(Y)G=Y+G;let Z=await this._requestMaker.send({url:G,method:"PATCH",body:W,...J});return $?Z:Z.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 q{constructor(G){if(!(G instanceof q))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(G)}}class p extends d{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 p1 extends p{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class n1 extends p{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class S1 extends p{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class i1 extends p{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class f1 extends p{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class o1 extends L{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 s1 extends L{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 a1 extends L{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 t1 extends L{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 r1 extends L{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 e1 extends L{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 G4 extends d{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 R1 extends L{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 W4 extends R1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class k1 extends L{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 $4 extends k1{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class Y4 extends k1{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class J4 extends k1{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class Z4 extends L{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 Q4 extends Z4{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class K4 extends Z4{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class n extends H{constructor(){super(...arguments);this._prefix=I}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 p1({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 n1({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 S1({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 S1({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 f1({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 f1({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 o1({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 s1({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 r1({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 a1({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 t1({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 e1({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 G4({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 R1({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 W4({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 Q4({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 $4({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 Y4({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 i1({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 K4({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 J4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}mediaInfo(G){return this.get("media/upload.json",{command:"STATUS",media_id:G},{prefix:v})}filterStream({autoConnect:G,...W}={}){let $={};for(let[J,Z]of Object.entries(W))if(J==="follow"||J==="track")$[J]=Z.toString();else if(J==="locations"){let Q=Z;$.locations=F1(Q).map((K)=>`${K.lng},${K.lat}`).join(",")}else $[J]=Z;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 _1(this);return G.setPrefix(e4),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 P from"fs";async function X4(G){let W=await z4(G);if(typeof W==="number")return new Promise(($,Y)=>{P.readFile(W,(J,Z)=>{if(J)return Y(J);$(Z)})});else if(W instanceof Buffer)return W;else return W.readFile()}function z4(G){if(typeof G==="string")return P.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 N0(G){if(typeof G==="number")return(await new Promise(($,Y)=>{P.fstat(G,(J,Z)=>{if(J)Y(J);$(Z)})})).size;else if(G instanceof Buffer)return G.length;else return(await G.stat()).size}function L0(G,W,$){if(typeof $==="string")return $;else if(typeof G==="string"&&!W)return i0(G);else if(typeof W==="string")return o0(W);throw Error("You must specify type if file is a file handle or Buffer.")}function i0(G){if(G.endsWith(".jpeg")||G.endsWith(".jpg"))return N.Jpeg;if(G.endsWith(".png"))return N.Png;if(G.endsWith(".webp"))return N.Webp;if(G.endsWith(".gif"))return N.Gif;if(G.endsWith(".mpeg4")||G.endsWith(".mp4"))return N.Mp4;if(G.endsWith(".mov")||G.endsWith(".mov"))return N.Mov;if(G.endsWith(".srt"))return N.Srt;return d1({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"options.mimeType is missing and filename couldn't help to resolve MIME type, so it will fallback to image/jpeg",resolution:"If you except to give filenames without extensions, please specify explicitlty the MIME type using options.mimeType"}),N.Jpeg}function o0(G){if(d1({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 N.Gif;if(G==="jpg")return N.Jpeg;if(G==="png")return N.Png;if(G==="webp")return N.Webp;if(G==="srt")return N.Srt;if(G==="mp4"||G==="longmp4")return N.Mp4;if(G==="mov")return N.Mov;return G}function D0(G,W){if(G===N.Mp4||G===N.Mov)return W==="tweet"?"TweetVideo":"DmVideo";if(G===N.Gif)return W==="tweet"?"TweetGif":"DmGif";if(G===N.Srt)return"Subtitles";else return W==="tweet"?"TweetImage":"DmImage"}function B4(G){return new Promise((W)=>setTimeout(W,G*1000))}async function x4(G,W,$=0,Y){if(G instanceof Buffer){let Z=G.slice($,$+W);return[Z,Z.length]}if(!Y)throw Error("Well, we will need a buffer to store file content.");let J;if(typeof G==="number")J=await new Promise((Z,Q)=>{P.read(G,Y,0,W,$,(K,z)=>{if(K)Q(K);Z(z)})});else J=(await G.read(Y,0,W,$)).bytesRead;return[Y,J]}var M4="media/upload.json";class i extends n{constructor(){super(...arguments);this._prefix=I}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,J={...typeof $==="string"?{status:$}:$},Z=Y?Y.id_str:J.in_reply_to_status_id,Q=J.status;if(Z)W.push(await this.reply(Q,Z,J));else W.push(await this.tweet(Q,J))}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 X4(G),...W};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(G,W={}){let $={tweet_mode:"extended",image:await X4(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&&z1(G.user_id)||G.screen_name&&z1(G.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,G)}removeListMembers(G){let $=G.user_id&&z1(G.user_id)||G.screen_name&&z1(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:v,forceBodyMode:"json"})}createMediaSubtitles(G,W){return this.post("media/subtitles/create.json",{media_id:G,media_category:"TweetVideo",subtitle_info:{subtitles:W}},{prefix:v,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:v,forceBodyMode:"json"})}async uploadMedia(G,W={},$=!1){var Y;let J=(Y=W.chunkLength)!==null&&Y!==void 0?Y:1048576,{fileHandle:Z,mediaCategory:Q,fileSize:K,mimeType:z}=await this.getUploadMediaRequirements(G,W);try{let X=await this.post(M4,{command:"INIT",total_bytes:K,media_type:z,media_category:Q,additional_owners:W.additionalOwners,shared:W.shared?!0:void 0},{prefix:v});await this.mediaChunkedUpload(Z,J,X.media_id_string,W.maxConcurrentUploads);let x=await this.post(M4,{command:"FINALIZE",media_id:X.media_id_string},{prefix:v});if(x.processing_info&&x.processing_info.state!=="succeeded")await this.awaitForMediaProcessingCompletion(x);if($)return x;else return x.media_id_string}finally{if(typeof G==="number")j4.close(G,()=>{});else if(typeof Z==="object"&&!(Z instanceof Buffer))Z.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:J}=$.error;throw Error(`Failed to process media: ${Y} - ${J}.`)}if($.state==="failed")throw Error("Failed to process the media.");if($.check_after_secs)await B4($.check_after_secs);else await B4(5)}}async getUploadMediaRequirements(G,{mimeType:W,type:$,target:Y,longVideo:J}={}){let Z;try{Z=await z4(G);let Q=L0(G,$,W),K;if(Q===N.Mp4&&(!W&&!$&&Y!=="dm"||J))K="amplify_video";else K=D0(Q,Y!==null&&Y!==void 0?Y:"tweet");return{fileHandle:Z,mediaCategory:K,fileSize:await N0(Z),mimeType:Q}}catch(Q){if(typeof G==="number")j4.close(G,()=>{});else if(typeof Z==="object"&&!(Z instanceof Buffer))Z.close();throw Q}}async mediaChunkedUpload(G,W,$,Y=3){let J=0;if(Y<1)throw RangeError("Bad maxConcurrentUploads parameter.");let Z=G instanceof Buffer?void 0:Buffer.alloc(W),Q,K,z=0;[Q,K]=await x4(G,W,z,Z),z+=K;let X=new Set;while(K){let x=Q.slice(0,K);if(x.length){let M=this.post(M4,{command:"APPEND",media_id:$,segment_index:J,media:x},{prefix:v});X.add(M),M.then(()=>{X.delete(M)}),J++}if(X.size>=Y)await Promise.race(X);[Q,K]=await x4(G,W,z,Z),z+=K}await Promise.all([...X])}}class F0 extends i{constructor(){super(...arguments);this._prefix=I}get readWrite(){return this}sendDm({recipient_id:G,custom_profile_id:W,...$}){let Y={event:{type:T.Create,[T.Create]:{target:{recipient_id:G},message_data:$}}};if(W)Y.event[T.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 E1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}newWelcomeDm(G,W){let $={[T.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 m1({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 J of Y.welcome_message_rules)if(await this.deleteWelcomeDmRule(J.id),W)await this.deleteWelcomeDm(J.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[T.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 _1=F0;class j{constructor(G){this.result=G}get tweets(){return j.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 j.tweetById(this.result,G)}static tweetById(G,W){return this.tweets(G).find(($)=>$.id===W)}retweet(G){return j.retweet(this.result,G)}static retweet(G,W){var $;let Y=(($=W.referenced_tweets)!==null&&$!==void 0?$:[]).filter((J)=>J.type==="retweeted").map((J)=>J.id);return this.tweets(G).find((J)=>Y.includes(J.id))}quote(G){return j.quote(this.result,G)}static quote(G,W){var $;let Y=(($=W.referenced_tweets)!==null&&$!==void 0?$:[]).filter((J)=>J.type==="quoted").map((J)=>J.id);return this.tweets(G).find((J)=>Y.includes(J.id))}repliedTo(G){return j.repliedTo(this.result,G)}static repliedTo(G,W){var $;let Y=(($=W.referenced_tweets)!==null&&$!==void 0?$:[]).filter((J)=>J.type==="replied_to").map((J)=>J.id);return this.tweets(G).find((J)=>Y.includes(J.id))}author(G){return j.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 j.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 j.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 j.userById(this.result,G)}static userById(G,W){return this.users(G).find(($)=>$.id===W)}pinnedTweet(G){return j.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 j.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 j.medias(this.result,G)}static medias(G,W){var $,Y;let J=(Y=($=W.attachments)===null||$===void 0?void 0:$.media_keys)!==null&&Y!==void 0?Y:[];return this.media(G).filter((Z)=>J.includes(Z.media_key))}get polls(){return j.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 j.poll(this.result,G)}static poll(G,W){var $,Y;let J=(Y=($=W.attachments)===null||$===void 0?void 0:$.poll_ids)!==null&&Y!==void 0?Y:[];if(J.length){let Z=J[0];return this.polls(G).find((Q)=>Q.id===Z)}return}get places(){return j.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 j.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((J)=>J.id===Y):void 0}listOwner(G){return j.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 j.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 j.spaceHosts(this.result,G)}static spaceHosts(G,W){var $;let Y=($=W.host_ids)!==null&&$!==void 0?$:[];return this.users(G).filter((J)=>Y.includes(J.id))}spaceSpeakers(G){return j.spaceSpeakers(this.result,G)}static spaceSpeakers(G,W){var $;let Y=($=W.speaker_ids)!==null&&$!==void 0?$:[];return this.users(G).filter((J)=>Y.includes(J.id))}spaceInvitedUsers(G){return j.spaceInvitedUsers(this.result,G)}static spaceInvitedUsers(G,W){var $;let Y=($=W.invited_user_ids)!==null&&$!==void 0?$:[];return this.users(G).filter((J)=>Y.includes(J.id))}}class v1 extends c1{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 j(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new j(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 _ extends v1{refreshInstanceFromResult(G,W){var $;let Y=G.data,J=($=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(...J);else this._realData.meta.result_count+=Y.meta.result_count,this._realData.meta.previous_token=Y.meta.previous_token,this._realData.data.unshift(...J);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 N4 extends v1{refreshInstanceFromResult(G,W){var $;let Y=G.data,J=($=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(...J);else this._realData.meta.newest_id=Y.meta.newest_id,this._realData.meta.result_count+=Y.meta.result_count,this._realData.data.unshift(...J);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 o extends _{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 L4 extends N4{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class D4 extends N4{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class F4 extends o{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class O4 extends o{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class H4 extends o{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class U4 extends o{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class S4 extends o{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class f4 extends _{get tweets(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class R4 extends f4{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class k4 extends f4{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class b extends _{getItemArray(){return this.users}get users(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class _4 extends b{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class v4 extends b{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class b4 extends b{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class h4 extends b{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class C4 extends b{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class I4 extends b{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class T4 extends b{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class q4 extends b{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class b1 extends _{getItemArray(){return this.lists}get lists(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class P4 extends b1{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class w4 extends b1{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class y4 extends b1{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class s extends H{constructor(){super(...arguments);this._prefix=E}}class h1 extends _{getItemArray(){return this.events}get events(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class A4 extends h1{constructor(){super(...arguments);this._endpoint="dm_events"}}class V4 extends h1{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class g4 extends h1{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class a extends H{constructor(){super(...arguments);this._prefix=C}get labs(){if(this._labs)return this._labs;return this._labs=new s(this)}async search(G,W={}){let $=typeof G==="string"?{...W,query:G}:{...G},Y=await this.get("tweets/search/recent",$,{fullResponse:!0});return new L4({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 D4({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,J=await this.get("tweets/:id/retweeted_by",Y,{fullResponse:!0,params:{id:G}});if(!$)return J.data;return new q4({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:Y,sharedParams:{id:G}})}async tweetLikedBy(G,W={}){let{asPaginator:$,...Y}=W,J=await this.get("tweets/:id/liking_users",Y,{fullResponse:!0,params:{id:G}});if(!$)return J.data;return new T4({realData:J.data,rateLimit:J.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 O4({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 H4({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 U4({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 F4({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 S4({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,J={id:G};if(!$)return this.get("users/:id/followers",Y,{params:J});let Z=await this.get("users/:id/followers",Y,{fullResponse:!0,params:J});return new b4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:Y,sharedParams:J})}async following(G,W={}){let{asPaginator:$,...Y}=W,J={id:G};if(!$)return this.get("users/:id/following",Y,{params:J});let Z=await this.get("users/:id/following",Y,{fullResponse:!0,params:J});return new h4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:Y,sharedParams:J})}async userLikedTweets(G,W={}){let $={id:G},Y=await this.get("users/:id/liked_tweets",W,{fullResponse:!0,params:$});return new R4({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 _4({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 v4({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 P4({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 w4({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 y4({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 k4({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 C4({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 I4({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 A4({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 V4({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 g4({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:O1,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:O1,autoConnect:G})}sample10Stream({autoConnect:G,...W}={}){return this.getStream("tweets/sample10/stream",W,{payloadIsError:O1,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(`
|
|
29
|
+
`;class s4 extends A1{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,J=G.cost??1,Z=Date.now(),Q=i4(Z,Y),K=Z-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(J)]),[x,M,R]=(Array.isArray(X)?X:[]).map(Number);return o4({allowed:x===1,current:Number.isFinite(M)?M:0,previous:Number.isFinite(R)?R:0,now:Z,elapsed:K,window:Y,limit:$,cost:J})}catch(X){if(this.onError(X),!this.failOpen)return{allowed:!1,limit:$,remaining:0,resetAt:Z+Y,retryAfter:Y};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-J)),resetAt:Q+Y,retryAfter:0}}}get client(){if(this.injectedClient)return this.injectedClient;let G=g(),W=G.bound(N1)?G.make(N1).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(J){if(!w0(J))throw J;return this.scriptSha=null,await $.send("EVALSHA",[await this.load($),...Y])}}load(G){if(!this.scriptSha)this.scriptSha=Promise.resolve(G.send("SCRIPT",["LOAD",P0])).then(String).catch((W)=>{throw this.scriptSha=null,W});return this.scriptSha}}function w0(G){return String(G?.message??G).includes("NOSCRIPT")}class Y1 extends U{application;previous;dispatched=[];static install(G){let W=G.resolved(U)?G.make(U):void 0;if(W instanceof Y1)return W;let $=new Y1(G,W);return G.instance(U,$),$}constructor(G,W){super({listeners:[]});this.application=G;this.previous=W}dispatch(G,W){this.dispatched.push({event:G,args:W})}async dispatchAndWait(G,W){this.dispatched.push({event:G,args:W})}restore(){if(this.previous){this.application.instance(U,this.previous);return}this.application.forget(U)}assertDispatched(G,W){let $=$1(G);if(this.matching($,W).length>0)return;throw Error(`Expected ${$}${W?" matching the predicate":""} to have been dispatched. ${this.summary($,W!==void 0)}`)}assertNotDispatched(G,W){let $=$1(G),Y=this.matching($,W);if(Y.length===0)return;throw Error(`Expected ${$}${W?" matching the predicate":""} not to have been dispatched, but it was dispatched ${V1(Y.length)}: ${L1(Y)}.`)}assertDispatchedTimes(G,W,$){let Y=$1(G),J=this.matching(Y,$);if(J.length===W)return;throw Error(`Expected ${Y}${$?" matching the predicate":""} to have been dispatched ${V1(W)}, but it was dispatched ${V1(J.length)}. ${this.summary(Y,$!==void 0)}`)}assertNothingDispatched(){if(this.dispatched.length===0)return;let G=this.dispatched.length;throw Error(`Expected nothing to have been dispatched, but ${G} ${G===1?"event was":"events were"}: ${L1(this.dispatched)}.`)}matching(G,W){return this.dispatched.filter(($)=>$1($.event.constructor)===G&&(W===void 0||W($.event)))}summary(G,W){if(this.dispatched.length===0)return"Nothing was dispatched.";let $=this.matching(G);if(W&&$.length>0)return`Dispatched ${G}: ${L1($)}.`;return`Dispatched: ${L1(this.dispatched)}.`}}function $1(G){return G.name}function V1(G){return`${G} ${G===1?"time":"times"}`}function L1(G){return G.map(y0).join(", ")}function y0(G){let W=$1(G.event.constructor),$=G.args??Object.values({...G.event});return`${W}(${$.map(A0).join(", ")})`}function A0(G){try{return JSON.stringify(G)??String(G)}catch{return String(G)}}class t4{static name="unset";static afterCommit=!1;static dispatch(...G){a4(this),g(U).dispatch(new this(...G),G)}static dispatchAndWait(...G){return a4(this),g(U).dispatchAndWait(new this(...G),G)}static fake(){return Y1.install(V0())}}function V0(){try{return g()}catch(G){throw Error("Event.fake() needs a booted application. The fake works by replacing the container's EventManager with a recorder, so there has to be a "+"container to replace it in \u2014 and a dispatch finds the recorder the "+"same way, by resolving from that container. Boot the app's kernel in the test's setup: `const kernel = new Kernel(); kernel.boot()` is enough on its own, since that is the phase that publishes the application every dispatch outside a request resolves through.",{cause:G})}}function a4(G){if(G.name!=="unset"&&G.name!=="")return;throw Error("Cannot dispatch an event with no name. Add `static name` to this Event "+"subclass \u2014 the listener registry is keyed by that string, and by that "+"string alone, so an event without one cannot reach a listener.")}class c{}var g0={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 r4 extends c{config;constructor(G={}){super();this.config={...g0,...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[Z,Q]of Object.entries(Y))$.searchParams.append(Z,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(),Z=await(await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${Y}`)).json();if(!Z.email)console.error("Google OAuth error: email not found in user info response",Z);return{name:Z.name,email:Z.email}}}var C="https://api.x.com/2/",E="https://api.x.com/labs/2/",I="https://api.x.com/1.1/",v="https://upload.x.com/1.1/",e4="https://stream.x.com/1.1/",m="https://ads-api.x.com/12/",u="https://ads-api-sandbox.twitter.com/12/";class g1{constructor({realData:G,rateLimit:W,instance:$,queryParams:Y,sharedParams:J}){this._maxResultsWhenFetchLast=100,this._realData=G,this._rateLimit=W,this._instance=$,this._queryParams=Y,this._sharedParams=J}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 c1 extends g1{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 d=g1;class L extends d{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 E1 extends L{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 m1 extends L{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 N;(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"})(N||(N={}));var T;(function(G){G.Create="message_create",G.WelcomeCreate="welcome_message"})(T||(T={}));var J1;(function(G){G.Request="request",G.PartialResponse="partial-response",G.Response="response"})(J1||(J1={}));class D1 extends Error{constructor(){super(...arguments);this.error=!0}}class Z1 extends D1{constructor(G,W){super(G);this.type=J1.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 Q1 extends D1{constructor(G,W){super(G);this.type=J1.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 K1 extends D1{constructor(G,W){super(G);if(this.type=J1.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:w.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((J)=>G.includes(J.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(w.AuthTimestampInvalid,w.AuthenticationFail,w.BadAuthenticationData,w.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var w;(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"})(w||(w={}));var G0;(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"})(G0||(G0={}));var B;(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"})(B||(B={}));class X1{constructor(G){this.value=G}}import*as j4 from"fs";var D={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function u1(G){let W={value:void 0,promise:G().then(($)=>{return W.value=$,$})};return W}function F1(G){if(Array.isArray(G))return G;return[G]}function $0(G){for(let W of Object.keys(G))if(G[W]===void 0)delete G[W]}function O1(G){return typeof G==="object"&&"errors"in G&&!("data"in G)}function z1(G){if(Array.isArray(G)&&G.length>1)return!0;return G.toString().includes(",")}var W0=new Set;function d1(G){if(typeof console>"u"||!console.warn||!D.deprecationWarnings)return;let W=`${G.instance}-${G.method}-${G.problem}`;if(W0.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."),W0.add(W)}import{EventEmitter as d0}from"events";import{request as c0}from"https";import*as F from"zlib";import{EventEmitter as E0}from"events";class Y0{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(D.debug)D.logger.log("Request error:",G);return new Z1("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 Q1(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 J;if(D.debug)D.logger.log(`Request failed with code ${Y}, data:`,W),D.logger.log("Response headers:",G.headers);let Z=`Request failed with code ${Y}`;if((J=W===null||W===void 0?void 0:W.errors)===null||J===void 0?void 0:J.length){let Q=W.errors;if(typeof Q[0]==="object"&&"code"in Q[0])Z+=" - "+this.formatV1Errors(Q);else Z+=" - "+this.formatV2Error(W)}return new K1(Z,{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 $=F.createBrotliDecompress({flush:F.constants.BROTLI_OPERATION_FLUSH,finishFlush:F.constants.BROTLI_OPERATION_FLUSH});return G.pipe($),$}if(W==="gzip"){let $=F.createGunzip({flush:F.constants.Z_SYNC_FLUSH,finishFlush:F.constants.Z_SYNC_FLUSH});return G.pipe($),$}if(W==="deflate"){let $=F.createInflate({flush:F.constants.Z_SYNC_FLUSH,finishFlush:F.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(),J={};for(let[Z,Q]of new URLSearchParams(Y))J[Z]=Q;return J}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",(J)=>this.responseData.push(J)),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",(J)=>this.requestData.requestEventDebugHandler("response-aborted",{error:J})),$.on("error",(J)=>this.requestData.requestEventDebugHandler("response-error",{error:J})),$.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(Z){W(this.createPartialResponseError(Z,!1));return}let J=this.res.statusCode;if(J>=400){W(this.createResponseError({data:Y,res:this.res,rateLimit:$,code:J}));return}if(D.debug)D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),D.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(D.debug)D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${$.statusCode} (starting stream)`);let J=this.getResponseDataStream($);G({req:this.req,res:J,originalResponse:$,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},W,$)}debugRequest(){let G=this.requestData.url;if(D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),G.search)D.logger.log("Request parameters:",[...G.searchParams.entries()].map(([W,$])=>`${W}: ${$}`));if(this.requestData.body)D.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(D.debug)this.debugRequest();this.req=c0({...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)=>{J.emit("complete"),G(Q)},Y=(Q)=>{J.emit("complete"),W(Q)},J=new E0,Z=this.req;if(Z.on("error",this.requestErrorHandler.bind(this,Y)),Z.on("socket",this.onSocketEventHandler.bind(this,Y,J)),Z.on("response",this.classicResponseHandler.bind(this,$,Y)),this.requestData.options.timeout)Z.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(Z);if(this.requestData.body)Z.write(this.requestData.body);Z.end()})}async makeRequestAsStream(){let{req:G,res:W,requestData:$,originalResponse:Y}=await this.makeRequestAndResolveWhenReady();return new H1($,{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 B1=Y0;import{EventEmitter as m0}from"events";class J0 extends m0{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(B.Data,this.onStreamData),G.on(B.ConnectionError,this.onStreamError),G.on(B.TweetParseError,this.onStreamError),G.on(B.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(B.Data,this.onStreamData),this.stream.off(B.ConnectionError,this.onStreamError),this.stream.off(B.TweetParseError,this.onStreamError),this.stream.off(B.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 Z0=J0;import{EventEmitter as u0}from"events";class U1 extends u0{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 J=G.slice($,Y);if($=Y+=2,!J.length)continue;try{let Z=JSON.parse(J);if(Z){this.emit(y.ParsedData,Z);continue}}catch(Z){this.emit(y.ParseError,Z)}}Y++}this.currentMessage=G.slice($,W)}reset(){this.currentMessage=""}}var y;(function(G){G.ParsedData="parsed data",G.ParseError="parse error"})(y||(y={}));var Q0=[5,15,30,60,90,120,180,300,600,900],l0=(G)=>G>Q0.length?901000:Q0[G-1]*1000;class K0 extends d0{constructor(G,W){super();if(this.requestData=G,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=l0,this.parser=new U1,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(B.ConnectionError,W),this.emit(B.Error,{type:B.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(B.DataKeepAlive);this.parser.push(W.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let G=this.requestData.payloadIsError;this.parser.on(y.ParsedData,(W)=>{if(G&&G(W))this.emit(B.DataError,W),this.emit(B.Error,{type:B.DataError,error:W,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(B.Data,W)}),this.parser.on(y.ParseError,(W)=>{this.emit(B.TweetParseError,W),this.emit(B.Error,{type:B.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(B.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(B.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let W=await new B1(this.requestData).makeRequestAsStream(),$=this.eventNames();for(let Y of $){let J=this.listeners(Y);for(let Z of J)W.on(Y,Z)}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(B.ConnectError,0),this.emit(B.Error,{type:B.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 B1(this.requestData).makeRequestAndResolveWhenReady();this.req=W,this.res=$,this.originalResponse=Y,this.emit(G?B.Connected:B.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(G=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(B.ConnectionClosed);return}if(G>=this.autoReconnectRetries){this.emit(B.ReconnectLimitExceeded),this.emit(B.ConnectionClosed);return}try{this.emit(B.ReconnectAttempt,G),await this.reconnect()}catch(W){this.emit(B.ReconnectError,G),this.emit(B.Error,{type:B.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 Z0(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 H1=K0;function X0(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 z0(G,W,$,Y){let J;if(Y instanceof Z1||Y instanceof Q1)J=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(G.url),params:G,computedParams:W,requestOptions:$,error:Y});else if(Y instanceof K1)J=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(G.url),params:G,computedParams:W,requestOptions:$,error:Y});if(J&&J instanceof X1)return J.value;return Promise.reject(Y)}import*as M0 from"crypto";class S{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 M0.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=x0(G),$="OAuth ";for(let Y of W){if(Y.key.indexOf("oauth_")!==0)continue;$+=S.percentEncode(Y.key)+'="'+S.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 S.percentEncode(this.consumerKeys.secret)+"&"+S.percentEncode(G||"")}getBaseString(G,W){return G.method.toUpperCase()+"&"+S.percentEncode(this.getBaseUrl(G.url))+"&"+S.percentEncode(this.getParameterString(G,W))}getParameterString(G,W){let $=x0(i0(B0(W,B0(G.data,n0(G.url))))),Y="";for(let{key:J,value:Z}of $)if(Z&&Array.isArray(Z)){Z.sort();let Q="";Z.forEach((K,z)=>{if(Q+=J+"="+K,z<Z.length)Q+="&"}),Y+=Q}else Y+=J+"="+Z+"&";return Y.slice(0,Y.length-1)}getBaseUrl(G){return G.split("?")[0]}}var x1=S;function B0(G,W){return{...G||{},...W||{}}}function x0(G){return Object.keys(G).sort().map((W)=>({key:W,value:G[W]}))}function p0(G){let W=G.split("&"),$={};for(let Y of W){let[J,Z=""]=Y.split("=");if($[J]){if(!Array.isArray($[J]))$[J]=[$[J]];$[J].push(decodeURIComponent(Z))}else $[J]=decodeURIComponent(Z)}return $}function n0(G){let W=G.split("?");if(W.length===1)return{};return p0(W[1])}function i0(G){let W={};for(let $ in G){let Y=G[$];if(Y&&Array.isArray(Y))Y=Y.map((J)=>S.percentEncode(J));else Y=S.percentEncode(Y);W[S.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(),J=this.getMultipartHeader(G,Y,$);this.bodyAppend(J,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 J=0;J<Y.length;$++,J++)W[$]=Y[J];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":$},J="";for(let[Z,Q]of Object.entries(Y)){if(!Q.length)continue;J+=Z+": "+F1(Q).join("; ")+f.LINE_BREAK}return"--"+this.getBoundary()+f.LINE_BREAK+J+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 l1{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[J,Z]of $)Y+=(Y.length?"&":"?")+`${x1.percentEncode(J)}=${x1.percentEncode(Z)}`;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 J in G)Y.append(J,G[J]);if(!W["content-type"]){let J=Y.getHeaders();W["content-type"]=J["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 J=W[Y];if(this.isOAuthSerializable(J))$[Y]=typeof J==="object"&&J!==null&&"toString"in J?J.toString():J}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}}l1.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=l1;import*as j0 from"crypto";class A{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(G){return this.escapeBase64Url(j0.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 l{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,J,Z;if((W=this.clientSettings.plugins)===null||W===void 0?void 0:W.length){let M=await this.applyPreRequestConfigHooks(G);if(M)return M}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 B1({url:Q.url,options:K,body:Q.body,rateLimitSaver:z?this.saveRateLimit.bind(this,Q.rawUrl):void 0,requestEventDebugHandler:G.requestEventDebugHandler,compression:(J=(Y=G.compression)!==null&&Y!==void 0?Y:this.clientSettings.compression)!==null&&J!==void 0?J:!0,forceParseMode:G.forceParseMode}).makeRequest();if(X0(this))X=this.applyResponseErrorHooks(G,Q,K,X);let x=await X;if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length){let M=await this.applyPostRequestHooks(G,Q,K,x);if(M)return M.value}return x}sendStream(G){var W,$;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(G);let Y=this.getHttpRequestArgs(G),J={method:Y.method,headers:Y.headers,agent:this.clientSettings.httpAgent},Z=G.enableRateLimitSave!==!1,Q=G.autoConnect!==!1;if(Y.body)O.setBodyLengthHeader(J,Y.body);let K={url:Y.url,options:J,body:Y.body,rateLimitSaver:Z?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 H1(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 x1({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 J of this.getPlugins()){let Z=await(($=J[G])===null||$===void 0?void 0:$.call(J,W));if(Z&&Z instanceof X1)Y=Z}return Y}writeAuthHeaders({headers:G,bodyInSignature:W,url:$,method:Y,query:J,body:Z}){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 "+A.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let Q=W?O.mergeQueryAndBodyForOAuth(J,Z):J,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:J,forceBodyMode:Z,enableAuth:Q,params:K}){let z=void 0;if(W=W.toUpperCase(),J=J!==null&&J!==void 0?J:{},!J["x-user-agent"])J["x-user-agent"]="Node.twitter-api-v2";let X=this.getUrlObjectFromUrlString(G),x=X.origin+X.pathname;if(K)O.applyRequestParametersToUrl(X,K);let M=O.formatQueryToString($);if(O.moveUrlQueryParamsIntoObject(X,M),!(Y instanceof Buffer))$0(Y);let R=Z!==null&&Z!==void 0?Z:O.autoDetectBodyType(X);if(Q!==!1){let k=l.BODY_METHODS.has(W)&&R==="url";J=this.writeAuthHeaders({headers:J,bodyInSignature:k,method:W,query:M,url:X,body:Y})}if(l.BODY_METHODS.has(W))z=O.constructBodyParams(Y,J,R)||void 0;return O.addQueryParamsToUrl(X,M),{rawUrl:x,url:X,method:W,headers:J,body:z}}async applyPreRequestConfigHooks(G){var W;let $=this.getUrlObjectFromUrlString(G.url);for(let Y of this.getPlugins()){let J=await((W=Y.onBeforeRequestConfig)===null||W===void 0?void 0:W.call(Y,{client:this,url:$,params:G}));if(J)return J}}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(z0.bind(this,G,W,$))}}l.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class q{constructor(G,W={}){if(this._currentUser=null,this._currentUserV2=null,G instanceof q)this._requestMaker=G._requestMaker;else this._requestMaker=new l(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=u1(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:I})),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=u1(()=>this.get("users/me",void 0,{prefix:C})),this._currentUserV2.promise}async get(G,W={},{fullResponse:$,prefix:Y=this._prefix,...J}={}){if(Y)G=Y+G;let Z=await this._requestMaker.send({url:G,method:"GET",query:W,...J});return $?Z:Z.data}async delete(G,W={},{fullResponse:$,prefix:Y=this._prefix,...J}={}){if(Y)G=Y+G;let Z=await this._requestMaker.send({url:G,method:"DELETE",query:W,...J});return $?Z:Z.data}async post(G,W,{fullResponse:$,prefix:Y=this._prefix,...J}={}){if(Y)G=Y+G;let Z=await this._requestMaker.send({url:G,method:"POST",body:W,...J});return $?Z:Z.data}async put(G,W,{fullResponse:$,prefix:Y=this._prefix,...J}={}){if(Y)G=Y+G;let Z=await this._requestMaker.send({url:G,method:"PUT",body:W,...J});return $?Z:Z.data}async patch(G,W,{fullResponse:$,prefix:Y=this._prefix,...J}={}){if(Y)G=Y+G;let Z=await this._requestMaker.send({url:G,method:"PATCH",body:W,...J});return $?Z:Z.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 q{constructor(G){if(!(G instanceof q))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(G)}}class p extends d{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 p1 extends p{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class n1 extends p{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class S1 extends p{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class i1 extends p{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class f1 extends p{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class o1 extends L{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 s1 extends L{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 a1 extends L{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 t1 extends L{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 r1 extends L{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 e1 extends L{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 G4 extends d{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 R1 extends L{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 W4 extends R1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class k1 extends L{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 $4 extends k1{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class Y4 extends k1{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class J4 extends k1{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class Z4 extends L{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 Q4 extends Z4{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class K4 extends Z4{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class n extends H{constructor(){super(...arguments);this._prefix=I}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 p1({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 n1({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 S1({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 S1({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 f1({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 f1({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 o1({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 s1({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 r1({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 a1({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 t1({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 e1({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 G4({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 R1({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 W4({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 Q4({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 $4({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 Y4({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 i1({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 K4({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 J4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}mediaInfo(G){return this.get("media/upload.json",{command:"STATUS",media_id:G},{prefix:v})}filterStream({autoConnect:G,...W}={}){let $={};for(let[J,Z]of Object.entries(W))if(J==="follow"||J==="track")$[J]=Z.toString();else if(J==="locations"){let Q=Z;$.locations=F1(Q).map((K)=>`${K.lng},${K.lat}`).join(",")}else $[J]=Z;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 _1(this);return G.setPrefix(e4),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 P from"fs";async function X4(G){let W=await z4(G);if(typeof W==="number")return new Promise(($,Y)=>{P.readFile(W,(J,Z)=>{if(J)return Y(J);$(Z)})});else if(W instanceof Buffer)return W;else return W.readFile()}function z4(G){if(typeof G==="string")return P.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 N0(G){if(typeof G==="number")return(await new Promise(($,Y)=>{P.fstat(G,(J,Z)=>{if(J)Y(J);$(Z)})})).size;else if(G instanceof Buffer)return G.length;else return(await G.stat()).size}function L0(G,W,$){if(typeof $==="string")return $;else if(typeof G==="string"&&!W)return o0(G);else if(typeof W==="string")return s0(W);throw Error("You must specify type if file is a file handle or Buffer.")}function o0(G){if(G.endsWith(".jpeg")||G.endsWith(".jpg"))return N.Jpeg;if(G.endsWith(".png"))return N.Png;if(G.endsWith(".webp"))return N.Webp;if(G.endsWith(".gif"))return N.Gif;if(G.endsWith(".mpeg4")||G.endsWith(".mp4"))return N.Mp4;if(G.endsWith(".mov")||G.endsWith(".mov"))return N.Mov;if(G.endsWith(".srt"))return N.Srt;return d1({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"options.mimeType is missing and filename couldn't help to resolve MIME type, so it will fallback to image/jpeg",resolution:"If you except to give filenames without extensions, please specify explicitlty the MIME type using options.mimeType"}),N.Jpeg}function s0(G){if(d1({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 N.Gif;if(G==="jpg")return N.Jpeg;if(G==="png")return N.Png;if(G==="webp")return N.Webp;if(G==="srt")return N.Srt;if(G==="mp4"||G==="longmp4")return N.Mp4;if(G==="mov")return N.Mov;return G}function D0(G,W){if(G===N.Mp4||G===N.Mov)return W==="tweet"?"TweetVideo":"DmVideo";if(G===N.Gif)return W==="tweet"?"TweetGif":"DmGif";if(G===N.Srt)return"Subtitles";else return W==="tweet"?"TweetImage":"DmImage"}function B4(G){return new Promise((W)=>setTimeout(W,G*1000))}async function x4(G,W,$=0,Y){if(G instanceof Buffer){let Z=G.slice($,$+W);return[Z,Z.length]}if(!Y)throw Error("Well, we will need a buffer to store file content.");let J;if(typeof G==="number")J=await new Promise((Z,Q)=>{P.read(G,Y,0,W,$,(K,z)=>{if(K)Q(K);Z(z)})});else J=(await G.read(Y,0,W,$)).bytesRead;return[Y,J]}var M4="media/upload.json";class i extends n{constructor(){super(...arguments);this._prefix=I}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,J={...typeof $==="string"?{status:$}:$},Z=Y?Y.id_str:J.in_reply_to_status_id,Q=J.status;if(Z)W.push(await this.reply(Q,Z,J));else W.push(await this.tweet(Q,J))}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 X4(G),...W};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(G,W={}){let $={tweet_mode:"extended",image:await X4(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&&z1(G.user_id)||G.screen_name&&z1(G.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,G)}removeListMembers(G){let $=G.user_id&&z1(G.user_id)||G.screen_name&&z1(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:v,forceBodyMode:"json"})}createMediaSubtitles(G,W){return this.post("media/subtitles/create.json",{media_id:G,media_category:"TweetVideo",subtitle_info:{subtitles:W}},{prefix:v,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:v,forceBodyMode:"json"})}async uploadMedia(G,W={},$=!1){var Y;let J=(Y=W.chunkLength)!==null&&Y!==void 0?Y:1048576,{fileHandle:Z,mediaCategory:Q,fileSize:K,mimeType:z}=await this.getUploadMediaRequirements(G,W);try{let X=await this.post(M4,{command:"INIT",total_bytes:K,media_type:z,media_category:Q,additional_owners:W.additionalOwners,shared:W.shared?!0:void 0},{prefix:v});await this.mediaChunkedUpload(Z,J,X.media_id_string,W.maxConcurrentUploads);let x=await this.post(M4,{command:"FINALIZE",media_id:X.media_id_string},{prefix:v});if(x.processing_info&&x.processing_info.state!=="succeeded")await this.awaitForMediaProcessingCompletion(x);if($)return x;else return x.media_id_string}finally{if(typeof G==="number")j4.close(G,()=>{});else if(typeof Z==="object"&&!(Z instanceof Buffer))Z.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:J}=$.error;throw Error(`Failed to process media: ${Y} - ${J}.`)}if($.state==="failed")throw Error("Failed to process the media.");if($.check_after_secs)await B4($.check_after_secs);else await B4(5)}}async getUploadMediaRequirements(G,{mimeType:W,type:$,target:Y,longVideo:J}={}){let Z;try{Z=await z4(G);let Q=L0(G,$,W),K;if(Q===N.Mp4&&(!W&&!$&&Y!=="dm"||J))K="amplify_video";else K=D0(Q,Y!==null&&Y!==void 0?Y:"tweet");return{fileHandle:Z,mediaCategory:K,fileSize:await N0(Z),mimeType:Q}}catch(Q){if(typeof G==="number")j4.close(G,()=>{});else if(typeof Z==="object"&&!(Z instanceof Buffer))Z.close();throw Q}}async mediaChunkedUpload(G,W,$,Y=3){let J=0;if(Y<1)throw RangeError("Bad maxConcurrentUploads parameter.");let Z=G instanceof Buffer?void 0:Buffer.alloc(W),Q,K,z=0;[Q,K]=await x4(G,W,z,Z),z+=K;let X=new Set;while(K){let x=Q.slice(0,K);if(x.length){let M=this.post(M4,{command:"APPEND",media_id:$,segment_index:J,media:x},{prefix:v});X.add(M),M.then(()=>{X.delete(M)}),J++}if(X.size>=Y)await Promise.race(X);[Q,K]=await x4(G,W,z,Z),z+=K}await Promise.all([...X])}}class F0 extends i{constructor(){super(...arguments);this._prefix=I}get readWrite(){return this}sendDm({recipient_id:G,custom_profile_id:W,...$}){let Y={event:{type:T.Create,[T.Create]:{target:{recipient_id:G},message_data:$}}};if(W)Y.event[T.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 E1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W})}newWelcomeDm(G,W){let $={[T.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 m1({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 J of Y.welcome_message_rules)if(await this.deleteWelcomeDmRule(J.id),W)await this.deleteWelcomeDm(J.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[T.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 _1=F0;class j{constructor(G){this.result=G}get tweets(){return j.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 j.tweetById(this.result,G)}static tweetById(G,W){return this.tweets(G).find(($)=>$.id===W)}retweet(G){return j.retweet(this.result,G)}static retweet(G,W){var $;let Y=(($=W.referenced_tweets)!==null&&$!==void 0?$:[]).filter((J)=>J.type==="retweeted").map((J)=>J.id);return this.tweets(G).find((J)=>Y.includes(J.id))}quote(G){return j.quote(this.result,G)}static quote(G,W){var $;let Y=(($=W.referenced_tweets)!==null&&$!==void 0?$:[]).filter((J)=>J.type==="quoted").map((J)=>J.id);return this.tweets(G).find((J)=>Y.includes(J.id))}repliedTo(G){return j.repliedTo(this.result,G)}static repliedTo(G,W){var $;let Y=(($=W.referenced_tweets)!==null&&$!==void 0?$:[]).filter((J)=>J.type==="replied_to").map((J)=>J.id);return this.tweets(G).find((J)=>Y.includes(J.id))}author(G){return j.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 j.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 j.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 j.userById(this.result,G)}static userById(G,W){return this.users(G).find(($)=>$.id===W)}pinnedTweet(G){return j.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 j.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 j.medias(this.result,G)}static medias(G,W){var $,Y;let J=(Y=($=W.attachments)===null||$===void 0?void 0:$.media_keys)!==null&&Y!==void 0?Y:[];return this.media(G).filter((Z)=>J.includes(Z.media_key))}get polls(){return j.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 j.poll(this.result,G)}static poll(G,W){var $,Y;let J=(Y=($=W.attachments)===null||$===void 0?void 0:$.poll_ids)!==null&&Y!==void 0?Y:[];if(J.length){let Z=J[0];return this.polls(G).find((Q)=>Q.id===Z)}return}get places(){return j.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 j.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((J)=>J.id===Y):void 0}listOwner(G){return j.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 j.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 j.spaceHosts(this.result,G)}static spaceHosts(G,W){var $;let Y=($=W.host_ids)!==null&&$!==void 0?$:[];return this.users(G).filter((J)=>Y.includes(J.id))}spaceSpeakers(G){return j.spaceSpeakers(this.result,G)}static spaceSpeakers(G,W){var $;let Y=($=W.speaker_ids)!==null&&$!==void 0?$:[];return this.users(G).filter((J)=>Y.includes(J.id))}spaceInvitedUsers(G){return j.spaceInvitedUsers(this.result,G)}static spaceInvitedUsers(G,W){var $;let Y=($=W.invited_user_ids)!==null&&$!==void 0?$:[];return this.users(G).filter((J)=>Y.includes(J.id))}}class v1 extends c1{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 j(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new j(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 _ extends v1{refreshInstanceFromResult(G,W){var $;let Y=G.data,J=($=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(...J);else this._realData.meta.result_count+=Y.meta.result_count,this._realData.meta.previous_token=Y.meta.previous_token,this._realData.data.unshift(...J);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 N4 extends v1{refreshInstanceFromResult(G,W){var $;let Y=G.data,J=($=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(...J);else this._realData.meta.newest_id=Y.meta.newest_id,this._realData.meta.result_count+=Y.meta.result_count,this._realData.data.unshift(...J);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 o extends _{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 L4 extends N4{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class D4 extends N4{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class F4 extends o{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class O4 extends o{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class H4 extends o{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class U4 extends o{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class S4 extends o{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class f4 extends _{get tweets(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class R4 extends f4{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class k4 extends f4{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class b extends _{getItemArray(){return this.users}get users(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class _4 extends b{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class v4 extends b{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class b4 extends b{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class h4 extends b{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class C4 extends b{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class I4 extends b{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class T4 extends b{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class q4 extends b{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class b1 extends _{getItemArray(){return this.lists}get lists(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class P4 extends b1{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class w4 extends b1{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class y4 extends b1{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class s extends H{constructor(){super(...arguments);this._prefix=E}}class h1 extends _{getItemArray(){return this.events}get events(){var G;return(G=this._realData.data)!==null&&G!==void 0?G:[]}get meta(){return super.meta}}class A4 extends h1{constructor(){super(...arguments);this._endpoint="dm_events"}}class V4 extends h1{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class g4 extends h1{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class a extends H{constructor(){super(...arguments);this._prefix=C}get labs(){if(this._labs)return this._labs;return this._labs=new s(this)}async search(G,W={}){let $=typeof G==="string"?{...W,query:G}:{...G},Y=await this.get("tweets/search/recent",$,{fullResponse:!0});return new L4({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 D4({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,J=await this.get("tweets/:id/retweeted_by",Y,{fullResponse:!0,params:{id:G}});if(!$)return J.data;return new q4({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:Y,sharedParams:{id:G}})}async tweetLikedBy(G,W={}){let{asPaginator:$,...Y}=W,J=await this.get("tweets/:id/liking_users",Y,{fullResponse:!0,params:{id:G}});if(!$)return J.data;return new T4({realData:J.data,rateLimit:J.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 O4({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 H4({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 U4({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 F4({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 S4({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,J={id:G};if(!$)return this.get("users/:id/followers",Y,{params:J});let Z=await this.get("users/:id/followers",Y,{fullResponse:!0,params:J});return new b4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:Y,sharedParams:J})}async following(G,W={}){let{asPaginator:$,...Y}=W,J={id:G};if(!$)return this.get("users/:id/following",Y,{params:J});let Z=await this.get("users/:id/following",Y,{fullResponse:!0,params:J});return new h4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:Y,sharedParams:J})}async userLikedTweets(G,W={}){let $={id:G},Y=await this.get("users/:id/liked_tweets",W,{fullResponse:!0,params:$});return new R4({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 _4({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 v4({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 P4({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 w4({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 y4({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 k4({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 C4({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 I4({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 A4({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 V4({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 g4({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:O1,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:O1,autoConnect:G})}sample10Stream({autoConnect:G,...W}={}){return this.getStream("tweets/sample10/stream",W,{payloadIsError:O1,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
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 t extends s{constructor(){super(...arguments);this._prefix=E}get readOnly(){return this}}class r extends a{constructor(){super(...arguments);this._prefix=C}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new t(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 J={additional_owners:W.additional_owners,media_type:W.media_type,total_bytes:G.length,media_category:Y},Q=(await this.post("media/upload/initialize",J)).data.id,K=Math.ceil(G.length/$),z=new Uint8Array(G);for(let x=0;x<K;x++){let M=x*$,R=Math.min(M+$,G.length),k=z.slice(M,R),e=Buffer.from(k),C0={segment_index:x,media:e};await this.post(`media/upload/${Q}/append`,C0,{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 J=Y===null||Y===void 0?void 0:Y.check_after_secs;if(J&&J>0)await new Promise((Z)=>setTimeout(Z,J*1000)),await this.waitForMediaProcessing(G)}}}createMediaMetadata(G,W){return this.post("media/metadata",{id:G,metadata:W})}reply(G,W,$={}){var Y;let J={in_reply_to_tweet_id:W,...(Y=$.reply)!==null&&Y!==void 0?Y:{}};return this.post("tweets",{text:G,...$,reply:J})}quote(G,W,$={}){return this.tweet(G,{...$,quote_tweet_id:W})}async tweetThread(G){var W,$;let Y=[];for(let J of G){let Z=Y.length?Y[Y.length-1]:null,Q={...typeof J==="string"?{text:J}:J},K=Z?Z.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 O0 extends t{constructor(){super(...arguments);this._prefix=E}get readWrite(){return this}}var H0=O0;class U0 extends r{constructor(){super(...arguments);this._prefix=C}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new H0(this)}}var S0=U0;class M1 extends q{get v1(){if(this._v1)return this._v1;return this._v1=new n(this)}get v2(){if(this._v2)return this._v2;return this._v2=new a(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:J}={}){let Z=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(Z.oauth_token)}`;if(Y!==void 0)Q+=`&force_login=${encodeURIComponent(Y)}`;if(J!==void 0)Q+=`&screen_name=${encodeURIComponent(J)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:Q,oauthResult:Z});return{url:Q,...Z}}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 J=($=W.state)!==null&&$!==void 0?$:A.generateRandomString(32),Z=A.getCodeVerifier(),Q=A.getCodeChallengeFromVerifier(Z),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"),x={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:G,state:J,code_challenge:Q,code_challenge_method:"s256",scope:z};O.addQueryParamsToUrl(X,x);let M={url:X.toString(),state:J,codeVerifier:Z,codeChallenge:Q};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:M,redirectUri:G});return M}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 j1 extends M1{get v1(){if(this._v1)return this._v1;return this._v1=new i(this)}get v2(){if(this._v2)return this._v2;return this._v2=new r(this)}get readOnly(){return this}}class C1 extends H{constructor(){super(...arguments);this._prefix=m}}class I1 extends C1{constructor(){super(...arguments);this._prefix=m}get readOnly(){return this}}class T1 extends H{constructor(){super(...arguments);this._prefix=u}}class q1 extends T1{constructor(){super(...arguments);this._prefix=u}get readOnly(){return this}}class f0 extends q1{constructor(){super(...arguments);this._prefix=u}get readWrite(){return this}}var R0=f0;class k0 extends I1{constructor(){super(...arguments);this._prefix=m}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new R0(this)}}var _0=k0;class c4 extends j1{get v1(){if(this._v1)return this._v1;return this._v1=new _1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new S0(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new _0(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"],J=G;for(let Q of Y)if($.includes(`_${Q}`)){J=G.replace(`_${Q}`,"");break}if(W==="original")return J;let Z=J.lastIndexOf(".");if(Z!==-1){let Q=J.slice(Z+1);return J.slice(0,Z)+"_"+W+"."+Q}else return J+"_"+W}}var s0={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class b0 extends c{config;client;oauthStates=new Map;constructor(G={}){super();this.config={...s0,...G},this.client=new c4({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}),v0.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 J=await this.client.loginWithOAuth2({code:W,codeVerifier:Y.codeVerifier,redirectUri:`${process.env.HOST_NAME}${this.config.redirectPath}`});this.oauthStates.delete($);let{data:Z}=await J.client.v2.me({"user.fields":["name","username","entities"]}),{name:Q,email:K,id:z="",username:X}=Z??{};return{name:Q,email:K,username:X,providerId:z}}}class E4{describe;rollout;when;serverOnly;salt;constructor(G={}){if(G.rollout!==void 0){let{rollout:W}=G;if(!Number.isFinite(W)||W<0||W>100)throw Error(`A feature's \`rollout\` must be a number between 0 and 100, received ${String(W)}.`)}this.describe=G.describe,this.rollout=G.rollout,this.when=G.when,this.serverOnly=G.serverOnly??!1,this.salt=G.salt}}function a0(G={}){return new E4(G)}class h0 extends m4{active;constructor(G={}){super();this.active=G}async load(){return Object.entries(this.active).map(([G,W])=>({key:G,active:W}))}}export{FG as viewRouteConfigDefaults,EG as translationConfigDefaults,P1 as toRangeHeaderValue,RG as subjectFor,oG as scheduleConfigDefaults,y1 as resolveRange,b6 as redisConfigDefaults,k6 as rateLimiterConfigDefaults,AG as queueConfigDefaults,G1 as parseContentRange,r0 as middlewareConfigDefaults,qG as mailConfigDefaults,L6 as logConfigDefaults,SG as inRollout,xG as imageConfigDefaults,QG as filesystemConfigDefaults,K6 as featuresConfigDefaults,aG as eventConfigDefaults,fG as evaluateFeature,$6 as discoverListeners,eG as discoverJobs,G6 as discoverCronJobs,W6 as discoverCommands,cG as defineTranslationConfig,iG as defineScheduleConfig,LG as defineRouteConfig,v6 as defineRedisConfig,R6 as defineRateLimiterConfig,yG as defineQueueConfig,t0 as defineMiddlewareConfig,TG as defineMailConfig,N6 as defineLogConfig,BG as defineImageConfig,ZG as defineFilesystemConfig,Q6 as defineFeaturesConfig,a0 as defineFeature,sG as defineEventConfig,dG as defineCommandConfig,pG as defineCommand,O6 as defineBroadcastConfig,e0 as defineAuthConfig,lG as commandConfigDefaults,UG as bucketOf,HG as bucketKey,H6 as broadcastConfigDefaults,GG as authConfigDefaults,DG as apiRouteConfigDefaults,b0 as XOAuthProvider,bG as ViewRouteDispatcher,h0 as StaticFeatureFlagSource,zG as Sharp,wG as Scheduler,Y6 as ScheduleServiceProvider,l4 as S3Driver,C6 as RouteServiceProvider,IG as ResendDriver,h6 as RedisServiceProvider,s4 as RedisRateLimiter,N1 as RedisManager,_6 as RateLimiterServiceProvider,A1 as RateLimiterDriver,$G as RateLimiter,V as RangeNotSatisfiableError,S6 as QueueServiceProvider,VG as QueueManager,c as OAuthProvider,F6 as MiddlewareServiceProvider,NG as MiddlewareRegistry,z6 as MailServiceProvider,PG as MailManager,D6 as LogServiceProvider,jG as LogManager,tG as Listener,j6 as KernelIdServiceProvider,OG as KernelId,rG as Job,f6 as InMemoryRateLimiter,M6 as ImageServiceProvider,XG as ImageOptimizationDriver,MG as ImageManager,r4 as GoogleOAuthProvider,x6 as FilesystemServiceProvider,KG as FilesystemManager,JG as FileSystemDriver,W1 as FileStorageDriver,h as FileNotFoundError,X6 as FeaturesServiceProvider,_G as FeatureScope,J6 as FeatureModelMissingError,vG as FeatureManager,kG as FeatureFlagStore,m4 as FeatureFlagSource,E4 as Feature,B6 as EventServiceProvider,U as EventManager,t4 as Event,CG as EmailDriver,Z6 as DatabaseFeatureFlagSource,nG as CronJob,I6 as CommandRegistry,mG as CommandFailed,uG as Command,U6 as BroadcastServiceProvider,YG as BroadcastManager,n4 as AzureBlobDriver,gG as AuthServiceProvider,WG as AuthManager,hG as ApiRouteDispatcher};
|
|
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 t extends s{constructor(){super(...arguments);this._prefix=E}get readOnly(){return this}}class r extends a{constructor(){super(...arguments);this._prefix=C}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new t(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 J={additional_owners:W.additional_owners,media_type:W.media_type,total_bytes:G.length,media_category:Y},Q=(await this.post("media/upload/initialize",J)).data.id,K=Math.ceil(G.length/$),z=new Uint8Array(G);for(let x=0;x<K;x++){let M=x*$,R=Math.min(M+$,G.length),k=z.slice(M,R),e=Buffer.from(k),C0={segment_index:x,media:e};await this.post(`media/upload/${Q}/append`,C0,{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 J=Y===null||Y===void 0?void 0:Y.check_after_secs;if(J&&J>0)await new Promise((Z)=>setTimeout(Z,J*1000)),await this.waitForMediaProcessing(G)}}}createMediaMetadata(G,W){return this.post("media/metadata",{id:G,metadata:W})}reply(G,W,$={}){var Y;let J={in_reply_to_tweet_id:W,...(Y=$.reply)!==null&&Y!==void 0?Y:{}};return this.post("tweets",{text:G,...$,reply:J})}quote(G,W,$={}){return this.tweet(G,{...$,quote_tweet_id:W})}async tweetThread(G){var W,$;let Y=[];for(let J of G){let Z=Y.length?Y[Y.length-1]:null,Q={...typeof J==="string"?{text:J}:J},K=Z?Z.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 O0 extends t{constructor(){super(...arguments);this._prefix=E}get readWrite(){return this}}var H0=O0;class U0 extends r{constructor(){super(...arguments);this._prefix=C}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new H0(this)}}var S0=U0;class M1 extends q{get v1(){if(this._v1)return this._v1;return this._v1=new n(this)}get v2(){if(this._v2)return this._v2;return this._v2=new a(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:J}={}){let Z=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(Z.oauth_token)}`;if(Y!==void 0)Q+=`&force_login=${encodeURIComponent(Y)}`;if(J!==void 0)Q+=`&screen_name=${encodeURIComponent(J)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:Q,oauthResult:Z});return{url:Q,...Z}}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 J=($=W.state)!==null&&$!==void 0?$:A.generateRandomString(32),Z=A.getCodeVerifier(),Q=A.getCodeChallengeFromVerifier(Z),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"),x={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:G,state:J,code_challenge:Q,code_challenge_method:"s256",scope:z};O.addQueryParamsToUrl(X,x);let M={url:X.toString(),state:J,codeVerifier:Z,codeChallenge:Q};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:M,redirectUri:G});return M}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 j1 extends M1{get v1(){if(this._v1)return this._v1;return this._v1=new i(this)}get v2(){if(this._v2)return this._v2;return this._v2=new r(this)}get readOnly(){return this}}class C1 extends H{constructor(){super(...arguments);this._prefix=m}}class I1 extends C1{constructor(){super(...arguments);this._prefix=m}get readOnly(){return this}}class T1 extends H{constructor(){super(...arguments);this._prefix=u}}class q1 extends T1{constructor(){super(...arguments);this._prefix=u}get readOnly(){return this}}class f0 extends q1{constructor(){super(...arguments);this._prefix=u}get readWrite(){return this}}var R0=f0;class k0 extends I1{constructor(){super(...arguments);this._prefix=m}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new R0(this)}}var _0=k0;class c4 extends j1{get v1(){if(this._v1)return this._v1;return this._v1=new _1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new S0(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new _0(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"],J=G;for(let Q of Y)if($.includes(`_${Q}`)){J=G.replace(`_${Q}`,"");break}if(W==="original")return J;let Z=J.lastIndexOf(".");if(Z!==-1){let Q=J.slice(Z+1);return J.slice(0,Z)+"_"+W+"."+Q}else return J+"_"+W}}var a0={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class b0 extends c{config;client;oauthStates=new Map;constructor(G={}){super();this.config={...a0,...G},this.client=new c4({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}),v0.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 J=await this.client.loginWithOAuth2({code:W,codeVerifier:Y.codeVerifier,redirectUri:`${process.env.HOST_NAME}${this.config.redirectPath}`});this.oauthStates.delete($);let{data:Z}=await J.client.v2.me({"user.fields":["name","username","entities"]}),{name:Q,email:K,id:z="",username:X}=Z??{};return{name:Q,email:K,username:X,providerId:z}}}class E4{describe;rollout;when;serverOnly;salt;constructor(G={}){if(G.rollout!==void 0){let{rollout:W}=G;if(!Number.isFinite(W)||W<0||W>100)throw Error(`A feature's \`rollout\` must be a number between 0 and 100, received ${String(W)}.`)}this.describe=G.describe,this.rollout=G.rollout,this.when=G.when,this.serverOnly=G.serverOnly??!1,this.salt=G.salt}}function t0(G={}){return new E4(G)}class h0 extends m4{active;constructor(G={}){super();this.active=G}async load(){return Object.entries(this.active).map(([G,W])=>({key:G,active:W}))}}export{OG as viewRouteConfigDefaults,uG as translationConfigDefaults,P1 as toRangeHeaderValue,kG as subjectFor,aG as scheduleConfigDefaults,y1 as resolveRange,C6 as redisConfigDefaults,v6 as rateLimiterConfigDefaults,gG as queueConfigDefaults,G1 as parseContentRange,e0 as middlewareConfigDefaults,wG as mailConfigDefaults,F6 as logConfigDefaults,fG as inRollout,MG as imageConfigDefaults,KG as filesystemConfigDefaults,z6 as featuresConfigDefaults,rG as eventConfigDefaults,RG as evaluateFeature,J6 as discoverListeners,W6 as discoverJobs,$6 as discoverCronJobs,Y6 as discoverCommands,mG as defineTranslationConfig,sG as defineScheduleConfig,DG as defineRouteConfig,h6 as defineRedisConfig,_6 as defineRateLimiterConfig,VG as defineQueueConfig,r0 as defineMiddlewareConfig,PG as defineMailConfig,D6 as defineLogConfig,xG as defineImageConfig,QG as defineFilesystemConfig,X6 as defineFeaturesConfig,t0 as defineFeature,tG as defineEventConfig,pG as defineCommandConfig,iG as defineCommand,U6 as defineBroadcastConfig,GG as defineAuthConfig,nG as commandConfigDefaults,SG as bucketOf,UG as bucketKey,S6 as broadcastConfigDefaults,WG as authConfigDefaults,FG as apiRouteConfigDefaults,b0 as XOAuthProvider,CG as ViewRouteDispatcher,h0 as StaticFeatureFlagSource,BG as Sharp,AG as Scheduler,Z6 as ScheduleServiceProvider,l4 as S3Driver,T6 as RouteServiceProvider,qG as ResendDriver,I6 as RedisServiceProvider,s4 as RedisRateLimiter,N1 as RedisManager,b6 as RateLimiterServiceProvider,A1 as RateLimiterDriver,YG as RateLimiter,V as RangeNotSatisfiableError,R6 as QueueServiceProvider,cG as QueueManager,c as OAuthProvider,H6 as MiddlewareServiceProvider,LG as MiddlewareRegistry,x6 as MailServiceProvider,yG as MailManager,O6 as LogServiceProvider,NG as LogManager,eG as Listener,L6 as KernelIdServiceProvider,HG as KernelId,G6 as Job,k6 as InMemoryRateLimiter,N6 as ImageServiceProvider,zG as ImageOptimizationDriver,jG as ImageManager,r4 as GoogleOAuthProvider,j6 as FilesystemServiceProvider,XG as FilesystemManager,ZG as FileSystemDriver,W1 as FileStorageDriver,h as FileNotFoundError,B6 as FeaturesServiceProvider,bG as FeatureScope,_G as FeatureReloadError,Q6 as FeatureModelMissingError,hG as FeatureManager,vG as FeatureFlagStore,m4 as FeatureFlagSource,E4 as Feature,M6 as EventServiceProvider,U as EventManager,t4 as Event,TG as EmailDriver,K6 as DatabaseFeatureFlagSource,oG as CronJob,q6 as CommandRegistry,dG as CommandFailed,lG as Command,f6 as BroadcastServiceProvider,JG as BroadcastManager,n4 as AzureBlobDriver,EG as AuthServiceProvider,$G as AuthManager,IG as ApiRouteDispatcher};
|
|
36
36
|
|
|
37
|
-
//# debugId=
|
|
37
|
+
//# debugId=C5D90C2DC10CE48664756E2164756E21
|