vibebusiness 1.2.49 → 1.2.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/app-build-manifest.json +17 -17
  3. package/.next/standalone/.next/app-path-routes-manifest.json +1 -1
  4. package/.next/standalone/.next/build-manifest.json +2 -2
  5. package/.next/standalone/.next/prerender-manifest.json +1 -1
  6. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  7. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  8. package/.next/standalone/.next/server/app/_not-found.rsc +1 -1
  9. package/.next/standalone/.next/server/app/api/analyze/route.js.nft.json +1 -1
  10. package/.next/standalone/.next/server/app/api/config/route.js.nft.json +1 -1
  11. package/.next/standalone/.next/server/app/api/epics/[id]/ideas/route.js.nft.json +1 -1
  12. package/.next/standalone/.next/server/app/api/epics/[id]/route.js.nft.json +1 -1
  13. package/.next/standalone/.next/server/app/api/epics/route.js.nft.json +1 -1
  14. package/.next/standalone/.next/server/app/api/goals/[id]/kpis/route.js.nft.json +1 -1
  15. package/.next/standalone/.next/server/app/api/goals/[id]/route.js.nft.json +1 -1
  16. package/.next/standalone/.next/server/app/api/goals/route.js.nft.json +1 -1
  17. package/.next/standalone/.next/server/app/api/hypotheses/[id]/route.js.nft.json +1 -1
  18. package/.next/standalone/.next/server/app/api/hypotheses/route.js.nft.json +1 -1
  19. package/.next/standalone/.next/server/app/api/ideas/[id]/comments/route.js.nft.json +1 -1
  20. package/.next/standalone/.next/server/app/api/ideas/[id]/implement/route.js.nft.json +1 -1
  21. package/.next/standalone/.next/server/app/api/ideas/[id]/route.js.nft.json +1 -1
  22. package/.next/standalone/.next/server/app/api/ideas/[id]/transition/route.js.nft.json +1 -1
  23. package/.next/standalone/.next/server/app/api/ideas/route.js.nft.json +1 -1
  24. package/.next/standalone/.next/server/app/api/implementations/route.js.nft.json +1 -1
  25. package/.next/standalone/.next/server/app/api/kpis/refresh/route.js +1 -1
  26. package/.next/standalone/.next/server/app/api/kpis/refresh/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/social/[id]/publish/route.js.nft.json +1 -1
  28. package/.next/standalone/.next/server/app/api/social/[id]/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/social/route.js.nft.json +1 -1
  30. package/.next/standalone/.next/server/app/goals/[id]/page_client-reference-manifest.js +1 -1
  31. package/.next/standalone/.next/server/app/goals/page.js.nft.json +1 -1
  32. package/.next/standalone/.next/server/app/goals/page_client-reference-manifest.js +1 -1
  33. package/.next/standalone/.next/server/app/hypotheses/[id]/page_client-reference-manifest.js +1 -1
  34. package/.next/standalone/.next/server/app/hypotheses/page.js +1 -1
  35. package/.next/standalone/.next/server/app/hypotheses/page.js.nft.json +1 -1
  36. package/.next/standalone/.next/server/app/hypotheses/page_client-reference-manifest.js +1 -1
  37. package/.next/standalone/.next/server/app/ideas/[id]/page.js.nft.json +1 -1
  38. package/.next/standalone/.next/server/app/ideas/[id]/page_client-reference-manifest.js +1 -1
  39. package/.next/standalone/.next/server/app/page.js +1 -1
  40. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  41. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  42. package/.next/standalone/.next/server/app/roadmap/[id]/page_client-reference-manifest.js +1 -1
  43. package/.next/standalone/.next/server/app/roadmap/page.js.nft.json +1 -1
  44. package/.next/standalone/.next/server/app/roadmap/page_client-reference-manifest.js +1 -1
  45. package/.next/standalone/.next/server/app/sessions/page.js.nft.json +1 -1
  46. package/.next/standalone/.next/server/app/sessions/page_client-reference-manifest.js +1 -1
  47. package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  48. package/.next/standalone/.next/server/app/settings.html +1 -1
  49. package/.next/standalone/.next/server/app/settings.rsc +1 -1
  50. package/.next/standalone/.next/server/app/social/page_client-reference-manifest.js +1 -1
  51. package/.next/standalone/.next/server/app/social.html +1 -1
  52. package/.next/standalone/.next/server/app/social.rsc +1 -1
  53. package/.next/standalone/.next/server/app-paths-manifest.json +13 -13
  54. package/.next/standalone/.next/server/chunks/3794.js +64 -4
  55. package/.next/standalone/.next/server/pages/404.html +1 -1
  56. package/.next/standalone/.next/server/pages/500.html +1 -1
  57. package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  58. package/.next/standalone/data/business-context.json +45 -6
  59. package/.next/standalone/data/goals.json +50 -10
  60. package/.next/standalone/data/ideas.json +1278 -597
  61. package/.next/standalone/data/implementations.json +101 -0
  62. package/.next/standalone/data/posthog.json +68 -0
  63. package/.next/standalone/data/sessions.json +5 -4
  64. package/.next/standalone/data/social.json +2 -2
  65. package/.next/standalone/package.json +1 -1
  66. package/.next/standalone/scripts/skills/social-media.ts +172 -2
  67. package/dist/scripts/heartbeat.js +286 -26
  68. package/package.json +1 -1
  69. /package/.next/static/{zIIaTqrawBK1MmHg37JOr → pCt9lOHHLoEA8SuY832zV}/_buildManifest.js +0 -0
  70. /package/.next/static/{zIIaTqrawBK1MmHg37JOr → pCt9lOHHLoEA8SuY832zV}/_ssgManifest.js +0 -0
@@ -1,5 +1,5 @@
1
- exports.id=3794,exports.ids=[3794],exports.modules={1401:e=>{function t(e){var t=Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=1401,e.exports=t},5883:(e,t,s)=>{"use strict";s.r(t),s.d(t,{ApiPartialResponseError:()=>f,ApiRequestError:()=>_,ApiResponseError:()=>w,DmEventsV1Paginator:()=>p,EApiV1ErrorCode:()=>k,EApiV2ErrorCode:()=>R,EDirectMessageEventTypeV1:()=>b,ETwitterApiError:()=>x,ETwitterStreamEvent:()=>T,EUploadMimeType:()=>v,FriendshipsIncomingV1Paginator:()=>eg,FriendshipsOutgoingV1Paginator:()=>e_,HomeTimelineV1Paginator:()=>er,ListMembersV1Paginator:()=>ex,ListMembershipsV1Paginator:()=>ew,ListOwnershipsV1Paginator:()=>ey,ListSubscribersV1Paginator:()=>ek,ListSubscriptionsV1Paginator:()=>ev,ListTimelineV1Paginator:()=>en,MentionTimelineV1Paginator:()=>ei,MuteUserIdsV1Paginator:()=>eu,MuteUserListV1Paginator:()=>el,PreviousableTwitterPaginator:()=>d,QuotedTweetsTimelineV2Paginator:()=>eN,TweetBookmarksTimelineV2Paginator:()=>eW,TweetHomeTimelineV2Paginator:()=>eB,TweetLikingUsersV2Paginator:()=>e2,TweetRetweetersUsersV2Paginator:()=>e4,TweetSearchAllV2Paginator:()=>e$,TweetSearchRecentV2Paginator:()=>eU,TweetStream:()=>H,TweetUserMentionTimelineV2Paginator:()=>eV,TweetUserTimelineV2Paginator:()=>eH,TweetV2ListTweetsPaginator:()=>eY,TweetV2UserLikedTweetsPaginator:()=>ez,TwitterApi:()=>t_,TwitterApiPluginResponseOverride:()=>y,TwitterApiReadOnly:()=>tl,TwitterApiReadWrite:()=>tu,TwitterApiV2Settings:()=>P,TwitterApiv1:()=>eI,TwitterApiv2:()=>to,TwitterApiv2Labs:()=>tn,TwitterPaginator:()=>u,TwitterV2IncludesHelper:()=>ej,UserBlockingUsersV2Paginator:()=>eQ,UserFavoritesV1Paginator:()=>eo,UserFollowerIdsV1Paginator:()=>ec,UserFollowerListV1Paginator:()=>ed,UserFollowersIdsV1Paginator:()=>ep,UserFollowersV2Paginator:()=>eX,UserFollowingV2Paginator:()=>eZ,UserFriendListV1Paginator:()=>eh,UserListFollowedV2Paginator:()=>e6,UserListFollowersV2Paginator:()=>e1,UserListMembersV2Paginator:()=>e0,UserListMembershipsV2Paginator:()=>e3,UserMutingUsersV2Paginator:()=>eG,UserOwnedListsV2Paginator:()=>e5,UserSearchV1Paginator:()=>em,UserTimelineV1Paginator:()=>ea,WelcomeDmV1Paginator:()=>m,default:()=>tf});let r="https://api.x.com/2/",i="https://api.x.com/labs/2/",a="https://api.x.com/1.1/",n="https://upload.x.com/1.1/",o="https://ads-api.x.com/12/",l="https://ads-api-sandbox.twitter.com/12/";class u{constructor({realData:e,rateLimit:t,instance:s,queryParams:r,sharedParams:i}){this._maxResultsWhenFetchLast=100,this._realData=e,this._rateLimit=t,this._instance=s,this._queryParams=r,this._sharedParams=i}get _isRateLimitOk(){return!!(!this._rateLimit||1e3*this._rateLimit.reset<Date.now())||this._rateLimit.remaining>0}makeRequest(e){return this._instance.get(this.getEndpoint(),e,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(e,t){return new this.constructor({realData:e.data,rateLimit:e.rateLimit,instance:this._instance,queryParams:t,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(e){return{...e?{max_results:e}:{},...this._queryParams}}async next(e){let t=this.getNextQueryParams(e),s=await this.makeRequest(t);return this.makeNewInstanceFromResult(s,t)}async fetchNext(e){let t=this.getNextQueryParams(e),s=await this.makeRequest(t);return await this.refreshInstanceFromResult(s,!0),this}async fetchLast(e=1/0){let t=this.getNextQueryParams(this._maxResultsWhenFetchLast),s=0;for(;s<e&&this._isRateLimitOk;){let e=await this.makeRequest(t);if(await this.refreshInstanceFromResult(e,!0),s+=this.getPageLengthFromRequest(e),this.isFetchLastOver(e))break;t=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var e;return{...null!==(e=this._rateLimit)&&void 0!==e?e:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async *[Symbol.asyncIterator](){yield*this.getItemArray();let e=this,t=this.canFetchNextPage(this._realData);for(;t&&this._isRateLimitOk&&e.getItemArray().length>0;){let s=await e.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:s._realData,headers:{},rateLimit:s._rateLimit},!0),t=this.canFetchNextPage(s._realData);let r=s.getItemArray();yield*r,e=s}}async *fetchAndIterate(){for(let e of this.getItemArray())yield[e,this];let e=this,t=this.canFetchNextPage(this._realData);for(;t&&this._isRateLimitOk&&e.getItemArray().length>0;){let s=await e.next(this._maxResultsWhenFetchLast);for(let e of(this.refreshInstanceFromResult({data:s._realData,headers:{},rateLimit:s._rateLimit},!0),t=this.canFetchNextPage(s._realData),s.getItemArray()))yield[e,s];this._rateLimit=s._rateLimit,e=s}}}class d extends u{async previous(e){let t=this.getPreviousQueryParams(e),s=await this.makeRequest(t);return this.makeNewInstanceFromResult(s,t)}async fetchPrevious(e){let t=this.getPreviousQueryParams(e),s=await this.makeRequest(t);return await this.refreshInstanceFromResult(s,!1),this}}let c=u;class h extends c{getNextQueryParams(e){var t;return{...this._queryParams,cursor:null!==(t=this._realData.next_cursor_str)&&void 0!==t?t:this._realData.next_cursor,...e?{count:e}:{}}}isFetchLastOver(e){return!this.canFetchNextPage(e.data)}canFetchNextPage(e){return!this.isNextCursorInvalid(e.next_cursor)||!this.isNextCursorInvalid(e.next_cursor_str)}isNextCursorInvalid(e){return void 0===e||0===e||-1===e||"0"===e||"-1"===e}}class p extends h{constructor(){super(...arguments),this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.events.push(...s.events),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class m extends h{constructor(){super(...arguments),this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.welcome_messages.push(...s.welcome_messages),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}(function(e){e.Jpeg="image/jpeg",e.Mp4="video/mp4",e.Mov="video/quicktime",e.Gif="image/gif",e.Png="image/png",e.Srt="text/plain",e.Webp="image/webp"})(v||(v={})),function(e){e.Create="message_create",e.WelcomeCreate="welcome_message"}(b||(b={})),function(e){e.Request="request",e.PartialResponse="partial-response",e.Response="response"}(x||(x={}));class g extends Error{constructor(){super(...arguments),this.error=!0}}class _ extends g{constructor(e,t){super(e),this.type=x.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class f extends g{constructor(e,t){super(e),this.type=x.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t})}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 w extends g{constructor(e,t){if(super(e),this.type=x.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t}),this.code=t.code,this.headers=t.headers,this.rateLimit=t.rateLimit,t.data&&"object"==typeof t.data&&"error"in t.data&&!t.data.errors){let e={...t.data};e.errors=[{code:k.InternalError,message:e.error}],this.data=e}else this.data=t.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...e){let t=this.errors;if(!(null==t?void 0:t.length))return!1;if("code"in t[0])return t.some(t=>e.includes(t.code));let s=this.data;return e.includes(s.type)}get errors(){var e;return null===(e=this.data)||void 0===e?void 0:e.errors}get rateLimitError(){return 420===this.code||429===this.code}get isAuthError(){return 401===this.code||this.hasErrorCode(k.AuthTimestampInvalid,k.AuthenticationFail,k.BadAuthenticationData,k.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}(function(e){e[e.InvalidCoordinates=3]="InvalidCoordinates",e[e.NoLocationFound=13]="NoLocationFound",e[e.AuthenticationFail=32]="AuthenticationFail",e[e.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",e[e.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",e[e.AuthTimestampInvalid=135]="AuthTimestampInvalid",e[e.BadAuthenticationData=215]="BadAuthenticationData",e[e.NoUserMatch=17]="NoUserMatch",e[e.UserNotFound=50]="UserNotFound",e[e.ResourceNotFound=34]="ResourceNotFound",e[e.TweetNotFound=144]="TweetNotFound",e[e.TweetNotVisible=179]="TweetNotVisible",e[e.NotAllowedResource=220]="NotAllowedResource",e[e.MediaIdNotFound=325]="MediaIdNotFound",e[e.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",e[e.TweetViolatedRules=422]="TweetViolatedRules",e[e.TargetUserSuspended=63]="TargetUserSuspended",e[e.YouAreSuspended=64]="YouAreSuspended",e[e.AccountUpdateFailed=120]="AccountUpdateFailed",e[e.NoSelfSpamReport=36]="NoSelfSpamReport",e[e.NoSelfMute=271]="NoSelfMute",e[e.AccountLocked=326]="AccountLocked",e[e.RateLimitExceeded=88]="RateLimitExceeded",e[e.NoDMRightForApp=93]="NoDMRightForApp",e[e.OverCapacity=130]="OverCapacity",e[e.InternalError=131]="InternalError",e[e.TooManyFollowings=161]="TooManyFollowings",e[e.TweetLimitExceeded=185]="TweetLimitExceeded",e[e.DuplicatedTweet=187]="DuplicatedTweet",e[e.TooManySpamReports=205]="TooManySpamReports",e[e.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",e[e.NoWriteRightForApp=261]="NoWriteRightForApp",e[e.TweetActionsDisabled=425]="TweetActionsDisabled",e[e.TweetRepliesRestricted=433]="TweetRepliesRestricted",e[e.NamedParameterMissing=38]="NamedParameterMissing",e[e.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",e[e.TweetTextTooLong=186]="TweetTextTooLong",e[e.MissingUrlParameter=195]="MissingUrlParameter",e[e.NoMultipleGifs=323]="NoMultipleGifs",e[e.InvalidMediaIds=324]="InvalidMediaIds",e[e.InvalidUrl=407]="InvalidUrl",e[e.TooManyTweetAttachments=386]="TooManyTweetAttachments",e[e.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",e[e.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",e[e.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",e[e.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",e[e.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",e[e.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",e[e.UnableToSendDM=151]="UnableToSendDM",e[e.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",e[e.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",e[e.DMTextTooLong=354]="DMTextTooLong",e[e.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",e[e.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",e[e.SuspendedApplication=416]="SuspendedApplication",e[e.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(k||(k={})),function(e){e.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",e.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",e.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",e.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",e.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",e.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",e.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",e.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",e.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",e.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",e.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",e.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",e.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"}(R||(R={})),function(e){e.Connected="connected",e.ConnectError="connect error",e.ConnectionError="connection error",e.ConnectionClosed="connection closed",e.ConnectionLost="connection lost",e.ReconnectAttempt="reconnect attempt",e.Reconnected="reconnected",e.ReconnectError="reconnect error",e.ReconnectLimitExceeded="reconnect limit exceeded",e.DataKeepAlive="data keep-alive",e.Data="data event content",e.DataError="data twitter error",e.TweetParseError="data tweet parse error",e.Error="stream error"}(T||(T={}));class y{constructor(e){this.value=e}}var v,b,x,k,R,T,S,D=s(2048);let P={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function E(e){let t={value:void 0,promise:e().then(e=>(t.value=e,e))};return t}function A(e){return Array.isArray(e)?e:[e]}function L(e){return"object"==typeof e&&"errors"in e&&!("data"in e)}function I(e){return!!Array.isArray(e)&&e.length>1||e.toString().includes(",")}let q=new Set;function j(e){if("undefined"==typeof console||!console.warn||!P.deprecationWarnings)return;let t=`${e.instance}-${e.method}-${e.problem}`;q.has(t)||(console.warn(`[twitter-api-v2] Deprecation warning: In ${e.instance}.${e.method}() call, ${e.problem}.
2
- ${e.resolution}.`),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),q.add(t))}var C=s(7702),M=s(8791),O=s(1568);class F{constructor(e){this.requestData=e,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let e=this.requestData.url;return e.hostname+e.pathname}isCompressionDisabled(){return!this.requestData.compression||"identity"===this.requestData.compression}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(e){return P.debug&&P.logger.log("Request error:",e),new _("Request failed.",{request:this.req,error:e})}createPartialResponseError(e,t){let s=this.res,r=`Request failed with partial response with HTTP code ${s.statusCode}`;return t?r+=" (connection abruptly closed)":r+=" (parse error)",new f(r,{request:this.req,response:this.res,responseError:e,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(e){return e.map(({code:e,message:t})=>`${t} (Twitter code ${e})`).join(", ")}formatV2Error(e){return`${e.title}: ${e.detail} (see ${e.type})`}createResponseError({res:e,data:t,rateLimit:s,code:r}){var i;P.debug&&(P.logger.log(`Request failed with code ${r}, data:`,t),P.logger.log("Response headers:",e.headers));let a=`Request failed with code ${r}`;if(null===(i=null==t?void 0:t.errors)||void 0===i?void 0:i.length){let e=t.errors;"object"==typeof e[0]&&"code"in e[0]?a+=" - "+this.formatV1Errors(e):a+=" - "+this.formatV2Error(t)}return new w(a,{code:r,data:t,headers:e.headers,request:this.req,response:e,rateLimit:s})}getResponseDataStream(e){if(this.isCompressionDisabled())return e;let t=(e.headers["content-encoding"]||"identity").trim().toLowerCase();if("br"===t){let t=O.createBrotliDecompress({flush:O.constants.BROTLI_OPERATION_FLUSH,finishFlush:O.constants.BROTLI_OPERATION_FLUSH});return e.pipe(t),t}if("gzip"===t){let t=O.createGunzip({flush:O.constants.Z_SYNC_FLUSH,finishFlush:O.constants.Z_SYNC_FLUSH});return e.pipe(t),t}if("deflate"===t){let t=O.createInflate({flush:O.constants.Z_SYNC_FLUSH,finishFlush:O.constants.Z_SYNC_FLUSH});return e.pipe(t),t}return e}detectResponseType(e){var t,s;return(null===(t=e.headers["content-type"])||void 0===t?void 0:t.includes("application/json"))||(null===(s=e.headers["content-type"])||void 0===s?void 0:s.includes("application/problem+json"))?"json":this.isFormEncodedEndpoint()?"url":"text"}getParsedResponse(e){let t=this.responseData,s=this.requestData.forceParseMode||this.detectResponseType(e);if("buffer"===s)return Buffer.concat(t);if("text"===s)return Buffer.concat(t).toString();if("json"===s){let e=Buffer.concat(t).toString();return e.length?JSON.parse(e):void 0}{if("url"!==s)return;let e=Buffer.concat(t).toString(),r={};for(let[t,s]of new URLSearchParams(e))r[t]=s;return r}}getRateLimitFromResponse(e){let t;return e.headers["x-rate-limit-limit"]&&(t={limit:Number(e.headers["x-rate-limit-limit"]),remaining:Number(e.headers["x-rate-limit-remaining"]),reset:Number(e.headers["x-rate-limit-reset"])},e.headers["x-app-limit-24hour-limit"]&&(t.day={limit:Number(e.headers["x-app-limit-24hour-limit"]),remaining:Number(e.headers["x-app-limit-24hour-remaining"]),reset:Number(e.headers["x-app-limit-24hour-reset"])}),e.headers["x-user-limit-24hour-limit"]&&(t.userDay={limit:Number(e.headers["x-user-limit-24hour-limit"]),remaining:Number(e.headers["x-user-limit-24hour-remaining"]),reset:Number(e.headers["x-user-limit-24hour-reset"])}),this.requestData.rateLimitSaver&&this.requestData.rateLimitSaver(t)),t}onSocketEventHandler(e,t,s){let r=this.onSocketCloseHandler.bind(this,e);s.on("close",r),t.on("complete",()=>s.off("close",r))}onSocketCloseHandler(e){if(this.req.removeAllListeners("timeout"),!this.res&&!this.requestErrorHandled)return e(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(e,t){var s,r;null===(r=(s=this.requestData).requestEventDebugHandler)||void 0===r||r.call(s,"request-error",{requestError:t}),this.requestErrorHandled=!0,e(this.createRequestError(t))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(e,t,s){this.res=s;let r=this.getResponseDataStream(s);r.on("data",e=>this.responseData.push(e)),r.on("end",this.onResponseEndHandler.bind(this,e,t)),r.on("close",this.onResponseCloseHandler.bind(this,e,t)),this.requestData.requestEventDebugHandler&&(this.requestData.requestEventDebugHandler("response",{res:s}),s.on("aborted",e=>this.requestData.requestEventDebugHandler("response-aborted",{error:e})),s.on("error",e=>this.requestData.requestEventDebugHandler("response-error",{error:e})),s.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),s.on("end",()=>this.requestData.requestEventDebugHandler("response-end")))}onResponseEndHandler(e,t){let s;let r=this.getRateLimitFromResponse(this.res);try{s=this.getParsedResponse(this.res)}catch(e){t(this.createPartialResponseError(e,!1));return}let i=this.res.statusCode;if(i>=400){t(this.createResponseError({data:s,res:this.res,rateLimit:r,code:i}));return}P.debug&&(P.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),P.logger.log("Response body:",s)),e({data:s,headers:this.res.headers,rateLimit:r})}onResponseCloseHandler(e,t){let s=this.res;if(s.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(e,t)}catch(e){return t(this.createPartialResponseError(e,!0))}if(!s.complete)return t(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(e,t,s){if(s.statusCode<400){P.debug&&P.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${s.statusCode} (starting stream)`);let t=this.getResponseDataStream(s);e({req:this.req,res:t,originalResponse:s,requestData:this.requestData})}else this.classicResponseHandler(()=>void 0,t,s)}debugRequest(){let e=this.requestData.url;P.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),e.search&&P.logger.log("Request parameters:",[...e.searchParams.entries()].map(([e,t])=>`${e}: ${t}`)),this.requestData.body&&P.logger.log("Request body:",this.requestData.body)}buildRequest(){var e;let t=this.requestData.url,s=t.username?`${t.username}:${t.password}`:void 0,r=null!==(e=this.requestData.options.headers)&&void 0!==e?e:{};!0===this.requestData.compression||"brotli"===this.requestData.compression?r["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1":"gzip"===this.requestData.compression?r["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1":"deflate"===this.requestData.compression&&(r["accept-encoding"]="deflate;q=1, *;q=0.1"),P.debug&&this.debugRequest(),this.req=(0,M.request)({...this.requestData.options,host:t.hostname,port:t.port||void 0,path:t.pathname+t.search,protocol:t.protocol,auth:s,headers:r})}registerRequestEventDebugHandlers(e){e.on("close",()=>this.requestData.requestEventDebugHandler("close")),e.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),e.on("socket",e=>{this.requestData.requestEventDebugHandler("socket",{socket:e}),e.on("error",t=>this.requestData.requestEventDebugHandler("socket-error",{socket:e,error:t})),e.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:e})),e.on("close",t=>this.requestData.requestEventDebugHandler("socket-close",{socket:e,withError:t})),e.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:e})),e.on("lookup",(...t)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:e,data:t})),e.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:e}))})}makeRequest(){return this.buildRequest(),new Promise((e,t)=>{let s=e=>{r.emit("complete"),t(e)},r=new C.EventEmitter,i=this.req;i.on("error",this.requestErrorHandler.bind(this,s)),i.on("socket",this.onSocketEventHandler.bind(this,s,r)),i.on("response",this.classicResponseHandler.bind(this,t=>{r.emit("complete"),e(t)},s)),this.requestData.options.timeout&&i.on("timeout",this.timeoutErrorHandler.bind(this)),this.requestData.requestEventDebugHandler&&this.registerRequestEventDebugHandlers(i),this.requestData.body&&i.write(this.requestData.body),i.end()})}async makeRequestAsStream(){let{req:e,res:t,requestData:s,originalResponse:r}=await this.makeRequestAndResolveWhenReady();return new V(s,{req:e,res:t,originalResponse:r})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((e,t)=>{let s=this.req;s.on("error",this.requestErrorHandler.bind(this,t)),s.on("response",this.streamResponseHandler.bind(this,e,t)),this.requestData.body&&s.write(this.requestData.body),s.end()})}}class U extends C.EventEmitter{constructor(e){super(),this.stream=e,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),e.on(T.Data,this.onStreamData),e.on(T.ConnectionError,this.onStreamError),e.on(T.TweetParseError,this.onStreamError),e.on(T.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let e=this.stack;return this.stack=[],e}destroy(){this.removeAllListeners(),this.stream.off(T.Data,this.onStreamData),this.stream.off(T.ConnectionError,this.onStreamError),this.stream.off(T.TweetParseError,this.onStreamError),this.stream.off(T.ConnectionClosed,this.onStreamError)}emitEvent(e,t){this.emit("event",{type:e,payload:t})}onStreamError(e){this.emitEvent("error",e)}onStreamData(e){this.stack.push(e),this.emitEvent("data",e)}}class $ extends C.EventEmitter{constructor(){super(...arguments),this.currentMessage=""}push(e){this.currentMessage+=e;let t=(e=this.currentMessage).length,s=0,r=0;for(;r<t;){if("\r\n"===e.slice(r,r+2)){let t=e.slice(s,r);if(s=r+=2,!t.length)continue;try{let e=JSON.parse(t);if(e){this.emit(S.ParsedData,e);continue}}catch(e){this.emit(S.ParseError,e)}}r++}this.currentMessage=e.slice(s,t)}reset(){this.currentMessage=""}}!function(e){e.ParsedData="parsed data",e.ParseError="parse error"}(S||(S={}));let N=[5,15,30,60,90,120,180,300,600,900],B=e=>e>N.length?901e3:1e3*N[e-1];class H extends C.EventEmitter{constructor(e,t){super(),this.requestData=e,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=12e4,this.nextRetryTimeout=B,this.parser=new $,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),t&&(this.req=t.req,this.res=t.res,this.originalResponse=t.originalResponse,this.initEventsFromRequest())}on(e,t){return super.on(e,t)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let e=e=>{this.emit(T.ConnectionError,e),this.emit(T.Error,{type:T.ConnectionError,error:e,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",e),this.res.on("error",e),this.res.on("close",()=>e(Error("Connection closed by Twitter."))),this.res.on("data",e=>{if(this.resetKeepAliveTimeout(),"\r\n"===e.toString())return this.emit(T.DataKeepAlive);this.parser.push(e.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let e=this.requestData.payloadIsError;this.parser.on(S.ParsedData,t=>{e&&e(t)?(this.emit(T.DataError,t),this.emit(T.Error,{type:T.DataError,error:t,message:"Twitter sent a payload that is detected as an error payload."})):this.emit(T.Data,t)}),this.parser.on(S.ParseError,e=>{this.emit(T.TweetParseError,e),this.emit(T.Error,{type:T.TweetParseError,error:e,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0&&(this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs))}onKeepAliveTimeout(){this.emit(T.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){this.keepAliveTimeout&&(clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0)}unbindRetryTimeout(){this.retryTimeout&&(clearTimeout(this.retryTimeout),this.retryTimeout=void 0)}closeWithoutEmit(){this.unbindTimeouts(),this.res&&(this.res.removeAllListeners(),this.res.destroy()),this.req&&(this.req.removeAllListeners(),this.req.destroy())}close(){this.emit(T.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let e=new F(this.requestData),t=await e.makeRequestAsStream();for(let e of this.eventNames())for(let s of this.listeners(e))t.on(e,s);return t}async connect(e={}){void 0!==e.autoReconnect&&(this.autoReconnect=e.autoReconnect),void 0!==e.autoReconnectRetries&&(this.autoReconnectRetries="unlimited"===e.autoReconnectRetries?1/0:e.autoReconnectRetries),void 0!==e.keepAliveTimeout&&(this.keepAliveTimeoutMs="disable"===e.keepAliveTimeout?1/0:e.keepAliveTimeout),void 0!==e.nextRetryTimeout&&(this.nextRetryTimeout=e.nextRetryTimeout),this.unbindTimeouts();try{await this.reconnect()}catch(e){if(this.emit(T.ConnectError,0),this.emit(T.Error,{type:T.ConnectError,error:e,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,e);else throw e}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let e=!0;this.req&&(e=!1,this.closeWithoutEmit());let{req:t,res:s,originalResponse:r}=await new F(this.requestData).makeRequestAndResolveWhenReady();this.req=t,this.res=s,this.originalResponse=r,this.emit(e?T.Connected:T.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(e=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(T.ConnectionClosed);return}if(e>=this.autoReconnectRetries){this.emit(T.ReconnectLimitExceeded),this.emit(T.ConnectionClosed);return}try{this.emit(T.ReconnectAttempt,e),await this.reconnect()}catch(t){this.emit(T.ReconnectError,e),this.emit(T.Error,{type:T.ReconnectError,error:t,message:`Reconnect error - ${e+1} attempts made yet.`}),this.makeAutoReconnectRetry(e,t)}}makeAutoReconnectRetry(e,t){let s=this.nextRetryTimeout(e+1,t);this.retryTimeout=setTimeout(()=>{this.onConnectionError(e+1)},s)}async *[Symbol.asyncIterator](){let e=new U(this);try{for(;;){if(!this.req||this.req.aborted)throw Error("Connection closed");e.hasStack()&&(yield*e.popStack());let{type:t,payload:s}=await e.nextEvent();if("error"===t)throw s}}finally{e.destroy()}}}let V=H;async function W(e,t,s,r){let i;return(r instanceof _||r instanceof f?i=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,error:r}):r instanceof w&&(i=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,error:r})),i&&i instanceof y)?i.value:Promise.reject(r)}var K=s(4770);class z{constructor(e){this.nonceLength=32,this.consumerKeys=e.consumerKeys}static percentEncode(e){return encodeURIComponent(e).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(e,t){return K.createHmac("sha1",t).update(e).digest("base64")}authorize(e,t={}){let s={oauth_consumer_key:this.consumerKeys.key,oauth_nonce:this.getNonce(),oauth_signature_method:"HMAC-SHA1",oauth_timestamp:this.getTimestamp(),oauth_version:"1.0"};return void 0!==t.key&&(s.oauth_token=t.key),e.data||(e.data={}),s.oauth_signature=this.getSignature(e,t.secret,s),s}toHeader(e){let t=J(e),s="OAuth ";for(let e of t)0===e.key.indexOf("oauth_")&&(s+=z.percentEncode(e.key)+'="'+z.percentEncode(e.value)+'",');return{Authorization:s.slice(0,s.length-1)}}getNonce(){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let s=0;s<this.nonceLength;s++)t+=e[Math.trunc(Math.random()*e.length)];return t}getTimestamp(){return Math.trunc(new Date().getTime()/1e3)}getSignature(e,t,s){return this.hash(this.getBaseString(e,s),this.getSigningKey(t))}getSigningKey(e){return z.percentEncode(this.consumerKeys.secret)+"&"+z.percentEncode(e||"")}getBaseString(e,t){return e.method.toUpperCase()+"&"+z.percentEncode(this.getBaseUrl(e.url))+"&"+z.percentEncode(this.getParameterString(e,t))}getParameterString(e,t){let s=J(function(e){let t={};for(let s in e){let r=e[s];r=r&&Array.isArray(r)?r.map(e=>z.percentEncode(e)):z.percentEncode(r),t[z.percentEncode(s)]=r}return t}(Y(t,Y(e.data,function(e){let t=e.split("?");return 1===t.length?{}:function(e){let t=e.split("&"),s={};for(let e of t){let[t,r=""]=e.split("=");s[t]?(Array.isArray(s[t])||(s[t]=[s[t]]),s[t].push(decodeURIComponent(r))):s[t]=decodeURIComponent(r)}return s}(t[1])}(e.url))))),r="";for(let{key:e,value:t}of s)if(t&&Array.isArray(t)){t.sort();let s="";t.forEach((r,i)=>{s+=e+"="+r,i<t.length&&(s+="&")}),r+=s}else r+=e+"="+t+"&";return r.slice(0,r.length-1)}getBaseUrl(e){return e.split("?")[0]}}function Y(e,t){return{...e||{},...t||{}}}function J(e){return Object.keys(e).sort().map(t=>({key:t,value:e[t]}))}class Q{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...e){let t=e.map(e=>e instanceof Buffer?e:Buffer.from(e));this._chunks.push(...t)}append(e,t,s){let r=t instanceof Buffer?t:t.toString(),i=this.getMultipartHeader(e,r,s);this.bodyAppend(i,r,Q.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((e,t)=>e+t.length,this.getMultipartFooter().length)}getBuffer(){let e=[...this._chunks,this.getMultipartFooter()],t=Buffer.alloc(this.getLength()),s=0;for(let r of e)for(let e=0;e<r.length;s++,e++)t[s]=r[e];return t}getBoundary(){return this._boundary||this.generateBoundary(),this._boundary}generateBoundary(){let e="--------------------------";for(let t=0;t<24;t++)e+=Math.floor(10*Math.random()).toString(16);this._boundary=e}getMultipartHeader(e,t,s){s||(s=t instanceof Buffer?Q.DEFAULT_CONTENT_TYPE:"");let r="";for(let[t,i]of Object.entries({"Content-Disposition":["form-data",`name="${e}"`],"Content-Type":s}))i.length&&(r+=t+": "+A(i).join("; ")+Q.LINE_BREAK);return"--"+this.getBoundary()+Q.LINE_BREAK+r+Q.LINE_BREAK}getMultipartFooter(){return this._footerChunk?this._footerChunk:this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+Q.LINE_BREAK)}}Q.LINE_BREAK="\r\n",Q.DEFAULT_CONTENT_TYPE="application/octet-stream";class G{static formatQueryToString(e){let t={};for(let s in e)"string"==typeof e[s]?t[s]=e[s]:void 0!==e[s]&&(t[s]=String(e[s]));return t}static autoDetectBodyType(e){if(e.pathname.startsWith("/2/")||e.pathname.startsWith("/labs/2/"))return e.password.startsWith("/2/oauth2")?"url":"json";if("upload.x.com"===e.hostname)return"/1.1/media/upload.json"===e.pathname?"form-data":"json";let t=e.pathname.split("/1.1/",2)[1];return this.JSON_1_1_ENDPOINTS.has(t)?"json":"url"}static addQueryParamsToUrl(e,t){let s=Object.entries(t);if(s.length){let t="";for(let[e,r]of s)t+=(t.length?"&":"?")+`${z.percentEncode(e)}=${z.percentEncode(r)}`;e.search=t}}static constructBodyParams(e,t,s){if(e instanceof Buffer)return e;if("json"===s)return t["content-type"]||(t["content-type"]="application/json;charset=UTF-8"),JSON.stringify(e);if("url"===s)return(t["content-type"]||(t["content-type"]="application/x-www-form-urlencoded;charset=UTF-8"),Object.keys(e).length)?new URLSearchParams(e).toString().replace(/\*/g,"%2A"):"";if("raw"===s)throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");{let s=new Q;for(let t in e)s.append(t,e[t]);if(!t["content-type"]){let e=s.getHeaders();t["content-type"]=e["content-type"]}return s.getBuffer()}}static setBodyLengthHeader(e,t){var s;e.headers=null!==(s=e.headers)&&void 0!==s?s:{},"string"==typeof t?e.headers["content-length"]=Buffer.byteLength(t):e.headers["content-length"]=t.length}static isOAuthSerializable(e){return!(e instanceof Buffer)}static mergeQueryAndBodyForOAuth(e,t){let s={};for(let t in e)s[t]=e[t];if(this.isOAuthSerializable(t))for(let e in t){let r=t[e];this.isOAuthSerializable(r)&&(s[e]="object"==typeof r&&null!==r&&"toString"in r?r.toString():r)}return s}static moveUrlQueryParamsIntoObject(e,t){for(let[s,r]of e.searchParams)t[s]=r;return e.search="",e}static applyRequestParametersToUrl(e,t){return e.pathname=e.pathname.replace(/:([A-Z_-]+)/ig,(e,s)=>void 0!==t[s]?String(t[s]):e),e}}G.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"]);class X{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(e){return this.escapeBase64Url(K.createHash("sha256").update(e).digest("base64"))}static getAuthHeader(e,t){let s=encodeURIComponent(e)+":"+encodeURIComponent(t);return Buffer.from(s).toString("base64")}static generateRandomString(e){let t="",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let r=0;r<e;r++)t+=s[Math.floor(Math.random()*s.length)];return t}static escapeBase64Url(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class Z{constructor(e){this.rateLimits={},this.clientSettings={},e&&(this.clientSettings=e)}getRateLimits(){return this.rateLimits}saveRateLimit(e,t){this.rateLimits[e]=t}async send(e){var t,s,r,i,a;if(null===(t=this.clientSettings.plugins)||void 0===t?void 0:t.length){let t=await this.applyPreRequestConfigHooks(e);if(t)return t}let n=this.getHttpRequestArgs(e),o={method:n.method,headers:n.headers,timeout:e.timeout,agent:this.clientSettings.httpAgent},l=!1!==e.enableRateLimitSave;n.body&&G.setBodyLengthHeader(o,n.body),(null===(s=this.clientSettings.plugins)||void 0===s?void 0:s.length)&&await this.applyPreRequestHooks(e,n,o);let u=new F({url:n.url,options:o,body:n.body,rateLimitSaver:l?this.saveRateLimit.bind(this,n.rawUrl):void 0,requestEventDebugHandler:e.requestEventDebugHandler,compression:null===(i=null!==(r=e.compression)&&void 0!==r?r:this.clientSettings.compression)||void 0===i||i,forceParseMode:e.forceParseMode}).makeRequest();(function(e){var t;if(!(null===(t=e.clientSettings.plugins)||void 0===t?void 0:t.length))return!1;for(let t of e.clientSettings.plugins)if(t.onRequestError||t.onResponseError)return!0;return!1})(this)&&(u=this.applyResponseErrorHooks(e,n,o,u));let d=await u;if(null===(a=this.clientSettings.plugins)||void 0===a?void 0:a.length){let t=await this.applyPostRequestHooks(e,n,o,d);if(t)return t.value}return d}sendStream(e){var t,s;this.clientSettings.plugins&&this.applyPreStreamRequestConfigHooks(e);let r=this.getHttpRequestArgs(e),i={method:r.method,headers:r.headers,agent:this.clientSettings.httpAgent},a=!1!==e.enableRateLimitSave,n=!1!==e.autoConnect;r.body&&G.setBodyLengthHeader(i,r.body);let o=new V({url:r.url,options:i,body:r.body,rateLimitSaver:a?this.saveRateLimit.bind(this,r.rawUrl):void 0,payloadIsError:e.payloadIsError,compression:null===(s=null!==(t=e.compression)&&void 0!==t?t:this.clientSettings.compression)||void 0===s||s});return n?o.connect():o}initializeToken(e){if("string"==typeof e)this.bearerToken=e;else if("object"==typeof e&&"appKey"in e)this.consumerToken=e.appKey,this.consumerSecret=e.appSecret,e.accessToken&&e.accessSecret&&(this.accessToken=e.accessToken,this.accessSecret=e.accessSecret),this._oauth=this.buildOAuth();else if("object"==typeof e&&"username"in e){let t=encodeURIComponent(e.username)+":"+encodeURIComponent(e.password);this.basicToken=Buffer.from(t).toString("base64")}else"object"==typeof e&&"clientId"in e&&(this.clientId=e.clientId,this.clientSecret=e.clientSecret)}getActiveTokens(){return this.bearerToken?{type:"oauth2",bearerToken:this.bearerToken}:this.basicToken?{type:"basic",token:this.basicToken}:this.consumerSecret&&this._oauth?{type:"oauth-1.0a",appKey:this.consumerToken,appSecret:this.consumerSecret,accessToken:this.accessToken,accessSecret:this.accessSecret}:this.clientId?{type:"oauth2-user",clientId:this.clientId}:{type:"none"}}buildOAuth(){if(!this.consumerSecret||!this.consumerToken)throw Error("Invalid consumer tokens");return new z({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(this.accessSecret&&this.accessToken)return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var e;return null!==(e=this.clientSettings.plugins)&&void 0!==e?e:[]}hasPlugins(){var e;return!!(null===(e=this.clientSettings.plugins)||void 0===e?void 0:e.length)}async applyPluginMethod(e,t){var s;let r;for(let i of this.getPlugins()){let a=await (null===(s=i[e])||void 0===s?void 0:s.call(i,t));a&&a instanceof y&&(r=a)}return r}writeAuthHeaders({headers:e,bodyInSignature:t,url:s,method:r,query:i,body:a}){if(e={...e},this.bearerToken)e.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)e.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)e.Authorization="Basic "+X.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let n=t?G.mergeQueryAndBodyForOAuth(i,a):i,o=this._oauth.authorize({url:s.toString(),method:r,data:n},this.getOAuthAccessTokens());e={...e,...this._oauth.toHeader(o)}}return e}getUrlObjectFromUrlString(e){return e.startsWith("http")||(e="https://"+e),new URL(e)}getHttpRequestArgs({url:e,method:t,query:s={},body:r={},headers:i,forceBodyMode:a,enableAuth:n,params:o}){let l;t=t.toUpperCase(),(i=null!=i?i:{})["x-user-agent"]||(i["x-user-agent"]="Node.twitter-api-v2");let u=this.getUrlObjectFromUrlString(e),d=u.origin+u.pathname;o&&G.applyRequestParametersToUrl(u,o);let c=G.formatQueryToString(s);G.moveUrlQueryParamsIntoObject(u,c),r instanceof Buffer||function(e){for(let t of Object.keys(e))void 0===e[t]&&delete e[t]}(r);let h=null!=a?a:G.autoDetectBodyType(u);if(!1!==n){let e=Z.BODY_METHODS.has(t)&&"url"===h;i=this.writeAuthHeaders({headers:i,bodyInSignature:e,method:t,query:c,url:u,body:r})}return Z.BODY_METHODS.has(t)&&(l=G.constructBodyParams(r,i,h)||void 0),G.addQueryParamsToUrl(u,c),{rawUrl:d,url:u,method:t,headers:i,body:l}}async applyPreRequestConfigHooks(e){var t;let s=this.getUrlObjectFromUrlString(e.url);for(let r of this.getPlugins()){let i=await (null===(t=r.onBeforeRequestConfig)||void 0===t?void 0:t.call(r,{client:this,url:s,params:e}));if(i)return i}}applyPreStreamRequestConfigHooks(e){var t;let s=this.getUrlObjectFromUrlString(e.url);for(let r of this.getPlugins())null===(t=r.onBeforeStreamRequestConfig)||void 0===t||t.call(r,{client:this,url:s,params:e})}async applyPreRequestHooks(e,t,s){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s})}async applyPostRequestHooks(e,t,s,r){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,response:r})}applyResponseErrorHooks(e,t,s,r){return r.catch(W.bind(this,e,t,s))}}Z.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class ee{constructor(e,t={}){this._currentUser=null,this._currentUserV2=null,e instanceof ee?this._requestMaker=e._requestMaker:(this._requestMaker=new Z(t),this._requestMaker.initializeToken(e))}setPrefix(e){this._prefix=e}cloneWithPrefix(e){let t=this.constructor(this);return t.setPrefix(e),t}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(e){return this.getPlugins().find(t=>t instanceof e)}hasHitRateLimit(e){var t;return!this.isRateLimitStatusObsolete(e)&&(null===(t=this.getLastRateLimitStatus(e))||void 0===t?void 0:t.remaining)===0}isRateLimitStatusObsolete(e){let t=this.getLastRateLimitStatus(e);return void 0===t||1e3*t.reset<Date.now()}getLastRateLimitStatus(e){let t=e.match(/^https?:\/\//)?e:this._prefix+e;return this._requestMaker.getRateLimits()[t]}getCurrentUserObject(e=!1){return!e&&this._currentUser?this._currentUser.value?Promise.resolve(this._currentUser.value):this._currentUser.promise:(this._currentUser=E(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:a})),this._currentUser.promise)}getCurrentUserV2Object(e=!1){return!e&&this._currentUserV2?this._currentUserV2.value?Promise.resolve(this._currentUserV2.value):this._currentUserV2.promise:(this._currentUserV2=E(()=>this.get("users/me",void 0,{prefix:r})),this._currentUserV2.promise)}async get(e,t={},{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"GET",query:t,...i});return s?a:a.data}async delete(e,t={},{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"DELETE",query:t,...i});return s?a:a.data}async post(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"POST",body:t,...i});return s?a:a.data}async put(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"PUT",body:t,...i});return s?a:a.data}async patch(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"PATCH",body:t,...i});return s?a:a.data}getStream(e,t,{prefix:s=this._prefix,...r}={}){return this._requestMaker.sendStream({url:s?s+e:e,method:"GET",query:t,...r})}postStream(e,t,{prefix:s=this._prefix,...r}={}){return this._requestMaker.sendStream({url:s?s+e:e,method:"POST",body:t,...r})}}class et extends ee{constructor(e){if(!(e instanceof ee))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(e)}}class es extends c{constructor(){super(...arguments),this.hasFinishedFetch=!1}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.push(...s),this.hasFinishedFetch=0===s.length)}getNextQueryParams(e){let t=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(e),max_id:(t-BigInt(1)).toString()}}getPageLengthFromRequest(e){return e.data.length}isFetchLastOver(e){return!e.data.length}canFetchNextPage(e){return e.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class er extends es{constructor(){super(...arguments),this._endpoint="statuses/home_timeline.json"}}class ei extends es{constructor(){super(...arguments),this._endpoint="statuses/mentions_timeline.json"}}class ea extends es{constructor(){super(...arguments),this._endpoint="statuses/user_timeline.json"}}class en extends es{constructor(){super(...arguments),this._endpoint="lists/statuses.json"}}class eo extends es{constructor(){super(...arguments),this._endpoint="favorites/list.json"}}class el extends h{constructor(){super(...arguments),this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class eu extends h{constructor(){super(...arguments),this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class ed extends h{constructor(){super(...arguments),this._endpoint="followers/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ec extends h{constructor(){super(...arguments),this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class eh extends h{constructor(){super(...arguments),this._endpoint="friends/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ep extends h{constructor(){super(...arguments),this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class em extends c{constructor(){super(...arguments),this._endpoint="users/search.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&this._realData.push(...s)}getNextQueryParams(e){var t;let s=Number(null!==(t=this._queryParams.page)&&void 0!==t?t:"1");return{...this._queryParams,page:s+1,...e?{count:e}:{}}}getPageLengthFromRequest(e){return e.data.length}isFetchLastOver(e){return!e.data.length}canFetchNextPage(e){return e.length>0}getItemArray(){return this.users}get users(){return this._realData}}class eg extends h{constructor(){super(...arguments),this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class e_ extends eg{constructor(){super(...arguments),this._endpoint="friendships/outgoing.json"}}class ef extends h{refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.lists.push(...s.lists),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class ew extends ef{constructor(){super(...arguments),this._endpoint="lists/memberships.json"}}class ey extends ef{constructor(){super(...arguments),this._endpoint="lists/ownerships.json"}}class ev extends ef{constructor(){super(...arguments),this._endpoint="lists/subscriptions.json"}}class eb extends h{refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ex extends eb{constructor(){super(...arguments),this._endpoint="lists/members.json"}}class ek extends eb{constructor(){super(...arguments),this._endpoint="lists/subscribers.json"}}class eR extends et{constructor(){super(...arguments),this._prefix=a}singleTweet(e,t={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:e,...t})}tweets(e,t={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:e,...t})}oembedTweet(e,t={}){return this.get("oembed",{url:`https://x.com/i/statuses/${e}`,...t},{prefix:"https://publish.x.com/"})}async homeTimeline(e={}){let t={tweet_mode:"extended",...e},s=await this.get("statuses/home_timeline.json",t,{fullResponse:!0});return new er({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async mentionTimeline(e={}){let t={tweet_mode:"extended",...e},s=await this.get("statuses/mentions_timeline.json",t,{fullResponse:!0});return new ei({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userTimeline(e,t={}){let s={tweet_mode:"extended",user_id:e,...t},r=await this.get("statuses/user_timeline.json",s,{fullResponse:!0});return new ea({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async userTimelineByUsername(e,t={}){let s={tweet_mode:"extended",screen_name:e,...t},r=await this.get("statuses/user_timeline.json",s,{fullResponse:!0});return new ea({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async favoriteTimeline(e,t={}){let s={tweet_mode:"extended",user_id:e,...t},r=await this.get("favorites/list.json",s,{fullResponse:!0});return new eo({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async favoriteTimelineByUsername(e,t={}){let s={tweet_mode:"extended",screen_name:e,...t},r=await this.get("favorites/list.json",s,{fullResponse:!0});return new eo({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}user(e){return this.get("users/show.json",{tweet_mode:"extended",...e})}users(e){return this.get("users/lookup.json",{tweet_mode:"extended",...e})}verifyCredentials(e={}){return this.get("account/verify_credentials.json",e)}async listMutedUsers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("mutes/users/list.json",t,{fullResponse:!0});return new el({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listMutedUserIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("mutes/users/ids.json",t,{fullResponse:!0});return new eu({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFriendList(e={}){let t={...e},s=await this.get("friends/list.json",t,{fullResponse:!0});return new eh({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowerList(e={}){let t={...e},s=await this.get("followers/list.json",t,{fullResponse:!0});return new ed({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowerIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("followers/ids.json",t,{fullResponse:!0});return new ec({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowingIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("friends/ids.json",t,{fullResponse:!0});return new ep({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async searchUsers(e,t={}){let s={q:e,tweet_mode:"extended",page:1,...t},r=await this.get("users/search.json",s,{fullResponse:!0});return new em({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}friendship(e){return this.get("friendships/show.json",e)}friendships(e){return this.get("friendships/lookup.json",e)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(e={}){let t={stringify_ids:!0,...e},s=await this.get("friendships/incoming.json",t,{fullResponse:!0});return new eg({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async friendshipsOutgoing(e={}){let t={stringify_ids:!0,...e},s=await this.get("friendships/outgoing.json",t,{fullResponse:!0});return new e_({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(e){return this.get("users/profile_banner.json",e)}list(e){return this.get("lists/show.json",{tweet_mode:"extended",...e})}lists(e={}){return this.get("lists/list.json",{tweet_mode:"extended",...e})}async listMembers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/members.json",t,{fullResponse:!0});return new ex({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}listGetMember(e){return this.get("lists/members/show.json",{tweet_mode:"extended",...e})}async listMemberships(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/memberships.json",t,{fullResponse:!0});return new ew({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listOwnerships(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/ownerships.json",t,{fullResponse:!0});return new ey({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listStatuses(e){let t={tweet_mode:"extended",...e},s=await this.get("lists/statuses.json",t,{fullResponse:!0});return new en({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listSubscribers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/subscribers.json",t,{fullResponse:!0});return new ek({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}listGetSubscriber(e){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...e})}async listSubscriptions(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/subscriptions.json",t,{fullResponse:!0});return new ev({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}mediaInfo(e){return this.get("media/upload.json",{command:"STATUS",media_id:e},{prefix:n})}filterStream({autoConnect:e,...t}={}){let s={};for(let[e,r]of Object.entries(t))"follow"===e||"track"===e?s[e]=r.toString():"locations"===e?s.locations=A(r).map(e=>`${e.lng},${e.lat}`).join(","):s[e]=r;return this.stream.postStream("statuses/filter.json",s,{autoConnect:e})}sampleStream({autoConnect:e,...t}={}){return this.stream.getStream("statuses/sample.json",t,{autoConnect:e})}get stream(){let e=new eq(this);return e.setPrefix("https://stream.x.com/1.1/"),e}trendsByPlace(e,t={}){return this.get("trends/place.json",{id:e,...t})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(e,t){return this.get("trends/closest.json",{lat:e,long:t})}geoPlace(e){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:e}})}geoSearch(e){return this.get("geo/search.json",e)}geoReverseGeoCode(e){return this.get("geo/reverse_geocode.json",e)}rateLimitStatuses(...e){return this.get("application/rate_limit_status.json",{resources:e})}supportedLanguages(){return this.get("help/languages.json")}}async function eT(e){let t=await eS(e);return"number"==typeof t?new Promise((e,s)=>{D.readFile(t,(t,r)=>{if(t)return s(t);e(r)})}):t instanceof Buffer?t:t.readFile()}function eS(e){if("string"==typeof e)return D.promises.open(e,"r");if("number"==typeof e||"object"==typeof e&&!(e instanceof Buffer)||e instanceof Buffer)return e;throw Error("Given file is not valid, please check its type.")}async function eD(e){return"number"==typeof e?(await new Promise((t,s)=>{D.fstat(e,(e,r)=>{e&&s(e),t(r)})})).size:e instanceof Buffer?e.length:(await e.stat()).size}function eP(e){return new Promise(t=>setTimeout(t,1e3*e))}async function eE(e,t,s=0,r){let i;if(e instanceof Buffer){let r=e.slice(s,s+t);return[r,r.length]}if(!r)throw Error("Well, we will need a buffer to store file content.");return i="number"==typeof e?await new Promise((i,a)=>{D.read(e,r,0,t,s,(e,t)=>{e&&a(e),i(t)})}):(await e.read(r,0,t,s)).bytesRead,[r,i]}let eA="media/upload.json";class eL extends eR{constructor(){super(...arguments),this._prefix=a}get readOnly(){return this}tweet(e,t={}){let s={status:e,tweet_mode:"extended",...t};return this.post("statuses/update.json",s)}async quote(e,t,s={}){return this.tweet(e,{...s,attachment_url:"https://x.com/i/statuses/"+t})}async tweetThread(e){let t=[];for(let s of e){let e=t.length?t[t.length-1]:null,r={..."string"==typeof s?{status:s}:s},i=e?e.id_str:r.in_reply_to_status_id,a=r.status;i?t.push(await this.reply(a,i,r)):t.push(await this.tweet(a,r))}return t}reply(e,t,s={}){return this.tweet(e,{auto_populate_reply_metadata:!0,in_reply_to_status_id:t,...s})}deleteTweet(e){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:e}})}reportUserAsSpam(e){return this.post("users/report_spam.json",{tweet_mode:"extended",...e})}updateFriendship(e){return this.post("friendships/update.json",e)}createFriendship(e){return this.post("friendships/create.json",e)}destroyFriendship(e){return this.post("friendships/destroy.json",e)}updateAccountSettings(e){return this.post("account/settings.json",e)}updateAccountProfile(e){return this.post("account/update_profile.json",e)}async updateAccountProfileBanner(e,t={}){let s={banner:await eT(e),...t};return this.post("account/update_profile_banner.json",s,{forceBodyMode:"form-data"})}async updateAccountProfileImage(e,t={}){let s={tweet_mode:"extended",image:await eT(e),...t};return this.post("account/update_profile_image.json",s,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(e){return this.post("lists/create.json",{tweet_mode:"extended",...e})}updateList(e){return this.post("lists/update.json",{tweet_mode:"extended",...e})}removeList(e){return this.post("lists/destroy.json",{tweet_mode:"extended",...e})}addListMembers(e){let t=e.user_id&&I(e.user_id)||e.screen_name&&I(e.screen_name);return this.post(t?"lists/members/create_all.json":"lists/members/create.json",e)}removeListMembers(e){let t=e.user_id&&I(e.user_id)||e.screen_name&&I(e.screen_name);return this.post(t?"lists/members/destroy_all.json":"lists/members/destroy.json",e)}subscribeToList(e){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...e})}unsubscribeOfList(e){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...e})}createMediaMetadata(e,t){return this.post("media/metadata/create.json",{media_id:e,...t},{prefix:n,forceBodyMode:"json"})}createMediaSubtitles(e,t){return this.post("media/subtitles/create.json",{media_id:e,media_category:"TweetVideo",subtitle_info:{subtitles:t}},{prefix:n,forceBodyMode:"json"})}deleteMediaSubtitles(e,...t){return this.post("media/subtitles/delete.json",{media_id:e,media_category:"TweetVideo",subtitle_info:{subtitles:t.map(e=>({language_code:e}))}},{prefix:n,forceBodyMode:"json"})}async uploadMedia(e,t={},s=!1){var r;let i=null!==(r=t.chunkLength)&&void 0!==r?r:1048576,{fileHandle:a,mediaCategory:o,fileSize:l,mimeType:u}=await this.getUploadMediaRequirements(e,t);try{let e=await this.post(eA,{command:"INIT",total_bytes:l,media_type:u,media_category:o,additional_owners:t.additionalOwners,shared:!!t.shared||void 0},{prefix:n});await this.mediaChunkedUpload(a,i,e.media_id_string,t.maxConcurrentUploads);let r=await this.post(eA,{command:"FINALIZE",media_id:e.media_id_string},{prefix:n});if(r.processing_info&&"succeeded"!==r.processing_info.state&&await this.awaitForMediaProcessingCompletion(r),s)return r;return r.media_id_string}finally{"number"==typeof e?D.close(e,()=>{}):"object"!=typeof a||a instanceof Buffer||a.close()}}async awaitForMediaProcessingCompletion(e){for(var t;;){let{processing_info:s}=e=await this.mediaInfo(e.media_id_string);if(!s||"succeeded"===s.state)return;if(null===(t=s.error)||void 0===t?void 0:t.code){let{name:e,message:t}=s.error;throw Error(`Failed to process media: ${e} - ${t}.`)}if("failed"===s.state)throw Error("Failed to process the media.");s.check_after_secs?await eP(s.check_after_secs):await eP(5)}}async getUploadMediaRequirements(e,{mimeType:t,type:s,target:r,longVideo:i}={}){let a;try{let o;a=await eS(e);let l=function(e,t,s){if("string"==typeof s)return s;if("string"==typeof e&&!t)return e.endsWith(".jpeg")||e.endsWith(".jpg")?v.Jpeg:e.endsWith(".png")?v.Png:e.endsWith(".webp")?v.Webp:e.endsWith(".gif")?v.Gif:e.endsWith(".mpeg4")||e.endsWith(".mp4")?v.Mp4:e.endsWith(".mov")||e.endsWith(".mov")?v.Mov:e.endsWith(".srt")?v.Srt:(j({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"}),v.Jpeg);if("string"==typeof t)return(j({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"}),"gif"===t)?v.Gif:"jpg"===t?v.Jpeg:"png"===t?v.Png:"webp"===t?v.Webp:"srt"===t?v.Srt:"mp4"===t||"longmp4"===t?v.Mp4:"mov"===t?v.Mov:t;throw Error("You must specify type if file is a file handle or Buffer.")}(e,s,t);if(l!==v.Mp4||(t||s||"dm"===r)&&!i){var n;n=null!=r?r:"tweet",o=l===v.Mp4||l===v.Mov?"tweet"===n?"TweetVideo":"DmVideo":l===v.Gif?"tweet"===n?"TweetGif":"DmGif":l===v.Srt?"Subtitles":"tweet"===n?"TweetImage":"DmImage"}else o="amplify_video";return{fileHandle:a,mediaCategory:o,fileSize:await eD(a),mimeType:l}}catch(t){throw"number"==typeof e?D.close(e,()=>{}):"object"!=typeof a||a instanceof Buffer||a.close(),t}}async mediaChunkedUpload(e,t,s,r=3){let i,a,o=0;if(r<1)throw RangeError("Bad maxConcurrentUploads parameter.");let l=e instanceof Buffer?void 0:Buffer.alloc(t),u=0;[i,a]=await eE(e,t,u,l),u+=a;let d=new Set;for(;a;){let c=i.slice(0,a);if(c.length){let e=this.post(eA,{command:"APPEND",media_id:s,segment_index:o,media:c},{prefix:n});d.add(e),e.then(()=>{d.delete(e)}),o++}d.size>=r&&await Promise.race(d),[i,a]=await eE(e,t,u,l),u+=a}await Promise.all([...d])}}class eI extends eL{constructor(){super(...arguments),this._prefix=a}get readWrite(){return this}sendDm({recipient_id:e,custom_profile_id:t,...s}){let r={event:{type:b.Create,[b.Create]:{target:{recipient_id:e},message_data:s}}};return t&&(r.event[b.Create].custom_profile_id=t),this.post("direct_messages/events/new.json",r,{forceBodyMode:"json"})}getDmEvent(e){return this.get("direct_messages/events/show.json",{id:e})}deleteDm(e){return this.delete("direct_messages/events/destroy.json",{id:e})}async listDmEvents(e={}){let t={...e},s=await this.get("direct_messages/events/list.json",t,{fullResponse:!0});return new p({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}newWelcomeDm(e,t){let s={[b.WelcomeCreate]:{name:e,message_data:t}};return this.post("direct_messages/welcome_messages/new.json",s,{forceBodyMode:"json"})}getWelcomeDm(e){return this.get("direct_messages/welcome_messages/show.json",{id:e})}deleteWelcomeDm(e){return this.delete("direct_messages/welcome_messages/destroy.json",{id:e})}updateWelcomeDm(e,t){return this.put("direct_messages/welcome_messages/update.json",{message_data:t},{forceBodyMode:"json",query:{id:e}})}async listWelcomeDms(e={}){let t={...e},s=await this.get("direct_messages/welcome_messages/list.json",t,{fullResponse:!0});return new m({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}newWelcomeDmRule(e){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:e}},{forceBodyMode:"json"})}getWelcomeDmRule(e){return this.get("direct_messages/welcome_messages/rules/show.json",{id:e})}deleteWelcomeDmRule(e){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:e})}async listWelcomeDmRules(e={}){let t={...e};return this.get("direct_messages/welcome_messages/rules/list.json",t)}async setWelcomeDm(e,t=!0){var s;let r=await this.listWelcomeDmRules();if(null===(s=r.welcome_message_rules)||void 0===s?void 0:s.length)for(let e of r.welcome_message_rules)await this.deleteWelcomeDmRule(e.id),t&&await this.deleteWelcomeDm(e.welcome_message_id);return this.newWelcomeDmRule(e)}markDmAsRead(e,t){return this.post("direct_messages/mark_read.json",{last_read_event_id:e,recipient_id:t},{forceBodyMode:"url"})}indicateDmTyping(e){return this.post("direct_messages/indicate_typing.json",{recipient_id:e},{forceBodyMode:"url"})}async downloadDmImage(e){if("string"!=typeof e){let t=e[b.Create].message_data.attachment;if(!t)throw Error("The given direct message doesn't contain any attachment");e=t.media.media_url_https}let t=await this.get(e,void 0,{forceParseMode:"buffer",prefix:""});if(!t.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return t}}let eq=eI;class ej{constructor(e){this.result=e}get tweets(){return ej.tweets(this.result)}static tweets(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.tweets)&&void 0!==s?s:[]}tweetById(e){return ej.tweetById(this.result,e)}static tweetById(e,t){return this.tweets(e).find(e=>e.id===t)}retweet(e){return ej.retweet(this.result,e)}static retweet(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"retweeted"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}quote(e){return ej.quote(this.result,e)}static quote(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"quoted"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}repliedTo(e){return ej.repliedTo(this.result,e)}static repliedTo(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"replied_to"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}author(e){return ej.author(this.result,e)}static author(e,t){let s=t.author_id;return s?this.users(e).find(e=>e.id===s):void 0}repliedToAuthor(e){return ej.repliedToAuthor(this.result,e)}static repliedToAuthor(e,t){let s=t.in_reply_to_user_id;return s?this.users(e).find(e=>e.id===s):void 0}get users(){return ej.users(this.result)}static users(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.users)&&void 0!==s?s:[]}userById(e){return ej.userById(this.result,e)}static userById(e,t){return this.users(e).find(e=>e.id===t)}pinnedTweet(e){return ej.pinnedTweet(this.result,e)}static pinnedTweet(e,t){return t.pinned_tweet_id?this.tweets(e).find(e=>e.id===t.pinned_tweet_id):void 0}get media(){return ej.media(this.result)}static media(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.media)&&void 0!==s?s:[]}medias(e){return ej.medias(this.result,e)}static medias(e,t){var s,r;let i=null!==(r=null===(s=t.attachments)||void 0===s?void 0:s.media_keys)&&void 0!==r?r:[];return this.media(e).filter(e=>i.includes(e.media_key))}get polls(){return ej.polls(this.result)}static polls(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.polls)&&void 0!==s?s:[]}poll(e){return ej.poll(this.result,e)}static poll(e,t){var s,r;let i=null!==(r=null===(s=t.attachments)||void 0===s?void 0:s.poll_ids)&&void 0!==r?r:[];if(i.length){let t=i[0];return this.polls(e).find(e=>e.id===t)}}get places(){return ej.places(this.result)}static places(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.places)&&void 0!==s?s:[]}place(e){return ej.place(this.result,e)}static place(e,t){var s;let r=null===(s=t.geo)||void 0===s?void 0:s.place_id;return r?this.places(e).find(e=>e.id===r):void 0}listOwner(e){return ej.listOwner(this.result,e)}static listOwner(e,t){let s=t.owner_id;return s?this.users(e).find(e=>e.id===s):void 0}spaceCreator(e){return ej.spaceCreator(this.result,e)}static spaceCreator(e,t){let s=t.creator_id;return s?this.users(e).find(e=>e.id===s):void 0}spaceHosts(e){return ej.spaceHosts(this.result,e)}static spaceHosts(e,t){var s;let r=null!==(s=t.host_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}spaceSpeakers(e){return ej.spaceSpeakers(this.result,e)}static spaceSpeakers(e,t){var s;let r=null!==(s=t.speaker_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}spaceInvitedUsers(e){return ej.spaceInvitedUsers(this.result,e)}static spaceInvitedUsers(e,t){var s;let r=null!==(s=t.invited_user_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}}class eC extends d{updateIncludes(e){if(e.errors&&(this._realData.errors||(this._realData.errors=[]),this._realData.errors=[...this._realData.errors,...e.errors]),!e.includes)return;this._realData.includes||(this._realData.includes={});let t=this._realData.includes;for(let[s,r]of Object.entries(e.includes))t[s]||(t[s]=[]),t[s]=[...t[s],...r]}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 e;return(null===(e=this._realData)||void 0===e?void 0:e.includes)?this._includesInstance?this._includesInstance:this._includesInstance=new ej(this._realData):new ej(this._realData)}get errors(){var e;return null!==(e=this._realData.errors)&&void 0!==e?e:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class eM extends eC{refreshInstanceFromResult(e,t){var s;let r=e.data,i=null!==(s=r.data)&&void 0!==s?s:[];this._rateLimit=e.rateLimit,this._realData.data||(this._realData.data=[]),t?(this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.next_token=r.meta.next_token,this._realData.data.push(...i)):(this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.previous_token=r.meta.previous_token,this._realData.data.unshift(...i)),this.updateIncludes(r)}getNextQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(e){var t,s;return null!==(s=null===(t=e.data.data)||void 0===t?void 0:t.length)&&void 0!==s?s:0}isFetchLastOver(e){var t;return!(null===(t=e.data.data)||void 0===t?void 0:t.length)||!this.canFetchNextPage(e.data)}canFetchNextPage(e){var t;return!!(null===(t=e.meta)||void 0===t?void 0:t.next_token)}}class eO extends eC{refreshInstanceFromResult(e,t){var s;let r=e.data,i=null!==(s=r.data)&&void 0!==s?s:[];this._rateLimit=e.rateLimit,this._realData.data||(this._realData.data=[]),t?(this._realData.meta.oldest_id=r.meta.oldest_id,this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.next_token=r.meta.next_token,this._realData.data.push(...i)):(this._realData.meta.newest_id=r.meta.newest_id,this._realData.meta.result_count+=r.meta.result_count,this._realData.data.unshift(...i)),this.updateIncludes(r)}getNextQueryParams(e){this.assertUsable();let t={...this.injectQueryParams(e)};return this._realData.meta.next_token?t.next_token=this._realData.meta.next_token:(t.start_time&&(t.since_id=this.dateStringToSnowflakeId(t.start_time),delete t.start_time),t.end_time&&delete t.end_time,t.until_id=this._realData.meta.oldest_id),t}getPreviousQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(e){var t,s;return null!==(s=null===(t=e.data.data)||void 0===t?void 0:t.length)&&void 0!==s?s:0}isFetchLastOver(e){var t;return!(null===(t=e.data.data)||void 0===t?void 0:t.length)||!this.canFetchNextPage(e.data)}canFetchNextPage(e){return!!e.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(e){let t=BigInt("1288834974657"),s=new Date(e);if(isNaN(s.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(s.valueOf())-t<<BigInt("22")).toString()}get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eF extends eM{refreshInstanceFromResult(e,t){super.refreshInstanceFromResult(e,t);let s=e.data;t?this._realData.meta.oldest_id=s.meta.oldest_id:this._realData.meta.newest_id=s.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eU extends eO{constructor(){super(...arguments),this._endpoint="tweets/search/recent"}}class e$ extends eO{constructor(){super(...arguments),this._endpoint="tweets/search/all"}}class eN extends eF{constructor(){super(...arguments),this._endpoint="tweets/:id/quote_tweets"}}class eB extends eF{constructor(){super(...arguments),this._endpoint="users/:id/timelines/reverse_chronological"}}class eH extends eF{constructor(){super(...arguments),this._endpoint="users/:id/tweets"}}class eV extends eF{constructor(){super(...arguments),this._endpoint="users/:id/mentions"}}class eW extends eF{constructor(){super(...arguments),this._endpoint="users/:id/bookmarks"}}class eK extends eM{get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class ez extends eK{constructor(){super(...arguments),this._endpoint="users/:id/liked_tweets"}}class eY extends eK{constructor(){super(...arguments),this._endpoint="lists/:id/tweets"}}class eJ extends eM{getItemArray(){return this.users}get users(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eQ extends eJ{constructor(){super(...arguments),this._endpoint="users/:id/blocking"}}class eG extends eJ{constructor(){super(...arguments),this._endpoint="users/:id/muting"}}class eX extends eJ{constructor(){super(...arguments),this._endpoint="users/:id/followers"}}class eZ extends eJ{constructor(){super(...arguments),this._endpoint="users/:id/following"}}class e0 extends eJ{constructor(){super(...arguments),this._endpoint="lists/:id/members"}}class e1 extends eJ{constructor(){super(...arguments),this._endpoint="lists/:id/followers"}}class e2 extends eJ{constructor(){super(...arguments),this._endpoint="tweets/:id/liking_users"}}class e4 extends eJ{constructor(){super(...arguments),this._endpoint="tweets/:id/retweeted_by"}}class e8 extends eM{getItemArray(){return this.lists}get lists(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class e5 extends e8{constructor(){super(...arguments),this._endpoint="users/:id/owned_lists"}}class e3 extends e8{constructor(){super(...arguments),this._endpoint="users/:id/list_memberships"}}class e6 extends e8{constructor(){super(...arguments),this._endpoint="users/:id/followed_lists"}}class e7 extends et{constructor(){super(...arguments),this._prefix=i}}class e9 extends eM{getItemArray(){return this.events}get events(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class te extends e9{constructor(){super(...arguments),this._endpoint="dm_events"}}class tt extends e9{constructor(){super(...arguments),this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class ts extends e9{constructor(){super(...arguments),this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class tr extends et{constructor(){super(...arguments),this._prefix=r}get labs(){return this._labs?this._labs:this._labs=new e7(this)}async search(e,t={}){let s="string"==typeof e?{...t,query:e}:{...e},r=await this.get("tweets/search/recent",s,{fullResponse:!0});return new eU({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async searchAll(e,t={}){let s={...t,query:e},r=await this.get("tweets/search/all",s,{fullResponse:!0});return new e$({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}singleTweet(e,t={}){return this.get("tweets/:id",t,{params:{id:e}})}tweets(e,t={}){return this.get("tweets",{ids:e,...t})}tweetCountRecent(e,t={}){return this.get("tweets/counts/recent",{query:e,...t})}tweetCountAll(e,t={}){return this.get("tweets/counts/all",{query:e,...t})}async tweetRetweetedBy(e,t={}){let{asPaginator:s,...r}=t,i=await this.get("tweets/:id/retweeted_by",r,{fullResponse:!0,params:{id:e}});return s?new e4({realData:i.data,rateLimit:i.rateLimit,instance:this,queryParams:r,sharedParams:{id:e}}):i.data}async tweetLikedBy(e,t={}){let{asPaginator:s,...r}=t,i=await this.get("tweets/:id/liking_users",r,{fullResponse:!0,params:{id:e}});return s?new e2({realData:i.data,rateLimit:i.rateLimit,instance:this,queryParams:r,sharedParams:{id:e}}):i.data}async homeTimeline(e={}){let t=await this.getCurrentUserV2Object(),s=await this.get("users/:id/timelines/reverse_chronological",e,{fullResponse:!0,params:{id:t.data.id}});return new eB({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:e,sharedParams:{id:t.data.id}})}async userTimeline(e,t={}){let s=await this.get("users/:id/tweets",t,{fullResponse:!0,params:{id:e}});return new eH({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async userMentionTimeline(e,t={}){let s=await this.get("users/:id/mentions",t,{fullResponse:!0,params:{id:e}});return new eV({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async quotes(e,t={}){let s=await this.get("tweets/:id/quote_tweets",t,{fullResponse:!0,params:{id:e}});return new eN({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async bookmarks(e={}){let t=await this.getCurrentUserV2Object(),s=await this.get("users/:id/bookmarks",e,{fullResponse:!0,params:{id:t.data.id}});return new eW({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:e,sharedParams:{id:t.data.id}})}me(e={}){return this.get("users/me",e)}user(e,t={}){return this.get("users/:id",t,{params:{id:e}})}users(e,t={}){let s=Array.isArray(e)?e.join(","):e;return this.get("users",{...t,ids:s})}userByUsername(e,t={}){return this.get("users/by/username/:username",t,{params:{username:e}})}usersByUsernames(e,t={}){return e=Array.isArray(e)?e.join(","):e,this.get("users/by",{...t,usernames:e})}async followers(e,t={}){let{asPaginator:s,...r}=t,i={id:e};if(!s)return this.get("users/:id/followers",r,{params:i});let a=await this.get("users/:id/followers",r,{fullResponse:!0,params:i});return new eX({realData:a.data,rateLimit:a.rateLimit,instance:this,queryParams:r,sharedParams:i})}async following(e,t={}){let{asPaginator:s,...r}=t,i={id:e};if(!s)return this.get("users/:id/following",r,{params:i});let a=await this.get("users/:id/following",r,{fullResponse:!0,params:i});return new eZ({realData:a.data,rateLimit:a.rateLimit,instance:this,queryParams:r,sharedParams:i})}async userLikedTweets(e,t={}){let s={id:e},r=await this.get("users/:id/liked_tweets",t,{fullResponse:!0,params:s});return new ez({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async userBlockingUsers(e,t={}){let s={id:e},r=await this.get("users/:id/blocking",t,{fullResponse:!0,params:s});return new eQ({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async userMutingUsers(e,t={}){let s={id:e},r=await this.get("users/:id/muting",t,{fullResponse:!0,params:s});return new eG({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}list(e,t={}){return this.get("lists/:id",t,{params:{id:e}})}async listsOwned(e,t={}){let s={id:e},r=await this.get("users/:id/owned_lists",t,{fullResponse:!0,params:s});return new e5({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listMemberships(e,t={}){let s={id:e},r=await this.get("users/:id/list_memberships",t,{fullResponse:!0,params:s});return new e3({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listFollowed(e,t={}){let s={id:e},r=await this.get("users/:id/followed_lists",t,{fullResponse:!0,params:s});return new e6({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listTweets(e,t={}){let s={id:e},r=await this.get("lists/:id/tweets",t,{fullResponse:!0,params:s});return new eY({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listMembers(e,t={}){let s={id:e},r=await this.get("lists/:id/members",t,{fullResponse:!0,params:s});return new e0({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listFollowers(e,t={}){let s={id:e},r=await this.get("lists/:id/followers",t,{fullResponse:!0,params:s});return new e1({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listDmEvents(e={}){let t=await this.get("dm_events",e,{fullResponse:!0});return new te({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...e}})}async listDmEventsWithParticipant(e,t={}){let s={participant_id:e},r=await this.get("dm_conversations/with/:participant_id/dm_events",t,{fullResponse:!0,params:s});return new tt({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listDmEventsOfConversation(e,t={}){let s={dm_conversation_id:e},r=await this.get("dm_conversations/:dm_conversation_id/dm_events",t,{fullResponse:!0,params:s});return new ts({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}space(e,t={}){return this.get("spaces/:id",t,{params:{id:e}})}spaces(e,t={}){return this.get("spaces",{ids:e,...t})}spacesByCreators(e,t={}){return this.get("spaces/by/creator_ids",{user_ids:e,...t})}searchSpaces(e){return this.get("spaces/search",e)}spaceBuyers(e,t={}){return this.get("spaces/:id/buyers",t,{params:{id:e}})}spaceTweets(e,t={}){return this.get("spaces/:id/tweets",t,{params:{id:e}})}searchStream({autoConnect:e,...t}={}){return this.getStream("tweets/search/stream",t,{payloadIsError:L,autoConnect:e})}streamRules(e={}){return this.get("tweets/search/stream/rules",e)}updateStreamRules(e,t={}){return this.post("tweets/search/stream/rules",e,{query:t})}sampleStream({autoConnect:e,...t}={}){return this.getStream("tweets/sample/stream",t,{payloadIsError:L,autoConnect:e})}sample10Stream({autoConnect:e,...t}={}){return this.getStream("tweets/sample10/stream",t,{payloadIsError:L,autoConnect:e})}complianceJobs(e){return this.get("compliance/jobs",e)}complianceJob(e){return this.get("compliance/jobs/:id",void 0,{params:{id:e}})}async sendComplianceJob(e){let t=await this.post("compliance/jobs",{type:e.type,name:e.name}),s=e.ids instanceof Buffer?e.ids:Buffer.from(e.ids.join("\n"));return await this.put(t.data.upload_url,s,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),t}async complianceJobResult(e){let t=e;for(;"complete"!==t.status;){if("expired"===t.status||"failed"===t.status)throw Error("Job failed to be completed.");await new Promise(e=>setTimeout(e,3500)),t=(await this.complianceJob(e.id)).data}return(await this.get(e.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split("\n").filter(e=>e).map(e=>JSON.parse(e))}async usage(e={}){return this.get("usage/tweets",e)}community(e,t={}){return this.get("communities/:id",t,{params:{id:e}})}searchCommunities(e,t={}){return this.get("communities/search",{query:e,...t})}}class ti extends e7{constructor(){super(...arguments),this._prefix=i}get readOnly(){return this}}class ta extends tr{constructor(){super(...arguments),this._prefix=r}get readOnly(){return this}get labs(){return this._labs?this._labs:this._labs=new ti(this)}hideReply(e,t){return this.put("tweets/:id/hidden",{hidden:t},{params:{id:e}})}like(e,t){return this.post("users/:id/likes",{tweet_id:t},{params:{id:e}})}unlike(e,t){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:e,tweet_id:t}})}retweet(e,t){return this.post("users/:id/retweets",{tweet_id:t},{params:{id:e}})}unretweet(e,t){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:e,tweet_id:t}})}tweet(e,t={}){return t="object"==typeof e?e:{text:e,...t},this.post("tweets",t)}async uploadMedia(e,t,s=1048576){let r=t.media_category;!t.media_category&&(t.media_type.includes("gif")?r="tweet_gif":t.media_type.includes("image")?r="tweet_image":t.media_type.includes("video")&&(r="tweet_video"));let i={additional_owners:t.additional_owners,media_type:t.media_type,total_bytes:e.length,media_category:r},a=(await this.post("media/upload/initialize",i)).data.id,n=Math.ceil(e.length/s),o=new Uint8Array(e);for(let t=0;t<n;t++){let r=t*s,i=Math.min(r+s,e.length),n=o.slice(r,i),l={segment_index:t,media:Buffer.from(n)};await this.post(`media/upload/${a}/append`,l,{forceBodyMode:"form-data"})}return(await this.post(`media/upload/${a}/finalize`)).data.processing_info&&await this.waitForMediaProcessing(a),a}async waitForMediaProcessing(e){var t;let s=(await this.get("media/upload",{command:"STATUS",media_id:e})).data.processing_info;if(s)switch(s.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${null===(t=s.error)||void 0===t?void 0:t.message}`);case"pending":case"in_progress":{let t=null==s?void 0:s.check_after_secs;t&&t>0&&(await new Promise(e=>setTimeout(e,1e3*t)),await this.waitForMediaProcessing(e))}}}createMediaMetadata(e,t){return this.post("media/metadata",{id:e,metadata:t})}reply(e,t,s={}){var r;let i={in_reply_to_tweet_id:t,...null!==(r=s.reply)&&void 0!==r?r:{}};return this.post("tweets",{text:e,...s,reply:i})}quote(e,t,s={}){return this.tweet(e,{...s,quote_tweet_id:t})}async tweetThread(e){var t,s;let r=[];for(let i of e){let e=r.length?r[r.length-1]:null,a={..."string"==typeof i?{text:i}:i},n=e?e.data.id:null===(t=a.reply)||void 0===t?void 0:t.in_reply_to_tweet_id,o=null!==(s=a.text)&&void 0!==s?s:"";n?r.push(await this.reply(o,n,a)):r.push(await this.tweet(o,a))}return r}deleteTweet(e){return this.delete("tweets/:id",void 0,{params:{id:e}})}async bookmark(e){let t=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:e},{params:{id:t.data.id}})}async deleteBookmark(e){let t=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:t.data.id,tweet_id:e}})}follow(e,t){return this.post("users/:id/following",{target_user_id:t},{params:{id:e}})}unfollow(e,t){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}block(e,t){return this.post("users/:id/blocking",{target_user_id:t},{params:{id:e}})}unblock(e,t){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}mute(e,t){return this.post("users/:id/muting",{target_user_id:t},{params:{id:e}})}unmute(e,t){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}createList(e){return this.post("lists",e)}updateList(e,t={}){return this.put("lists/:id",t,{params:{id:e}})}removeList(e){return this.delete("lists/:id",void 0,{params:{id:e}})}addListMember(e,t){return this.post("lists/:id/members",{user_id:t},{params:{id:e}})}removeListMember(e,t){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:e,user_id:t}})}subscribeToList(e,t){return this.post("users/:id/followed_lists",{list_id:t},{params:{id:e}})}unsubscribeOfList(e,t){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:e,list_id:t}})}pinList(e,t){return this.post("users/:id/pinned_lists",{list_id:t},{params:{id:e}})}unpinList(e,t){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:e,list_id:t}})}sendDmInConversation(e,t){return this.post("dm_conversations/:dm_conversation_id/messages",t,{params:{dm_conversation_id:e}})}sendDmToParticipant(e,t){return this.post("dm_conversations/with/:participant_id/messages",t,{params:{participant_id:e}})}createDmConversation(e){return this.post("dm_conversations",e)}}class tn extends ti{constructor(){super(...arguments),this._prefix=i}get readWrite(){return this}}class to extends ta{constructor(){super(...arguments),this._prefix=r}get readWrite(){return this}get labs(){return this._labs?this._labs:this._labs=new tn(this)}}class tl extends ee{get v1(){return this._v1?this._v1:this._v1=new eR(this)}get v2(){return this._v2?this._v2:this._v2=new tr(this)}async currentUser(e=!1){return await this.getCurrentUserObject(e)}async currentUserV2(e=!1){return await this.getCurrentUserV2Object(e)}search(e,t){return this.v2.search(e,t)}async generateAuthLink(e="oob",{authAccessType:t,linkMode:s="authenticate",forceLogin:r,screenName:i}={}){let a=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:e,x_auth_access_type:t}),n=`https://api.x.com/oauth/${s}?oauth_token=${encodeURIComponent(a.oauth_token)}`;return void 0!==r&&(n+=`&force_login=${encodeURIComponent(r)}`),void 0!==i&&(n+=`&screen_name=${encodeURIComponent(i)}`),this._requestMaker.hasPlugins()&&this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:n,oauthResult:a}),{url:n,...a}}async login(e){let t=this.getActiveTokens();if("oauth-1.0a"!==t.type)throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let s=await this.post("https://api.x.com/oauth/access_token",{oauth_token:t.accessToken,oauth_verifier:e}),r=new this.constructor({appKey:t.appKey,appSecret:t.appSecret,accessToken:s.oauth_token,accessSecret:s.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:s.oauth_token,accessSecret:s.oauth_token_secret,userId:s.user_id,screenName:s.screen_name,client:r}}async appLogin(){let e=this.getActiveTokens();if("oauth-1.0a"!==e.type)throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let t=new this.constructor({username:e.appKey,password:e.appSecret},this._requestMaker.clientSettings),s=await t.post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor(s.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(e,t={}){var s,r;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 i=null!==(s=t.state)&&void 0!==s?s:X.generateRandomString(32),a=X.getCodeVerifier(),n=X.getCodeChallengeFromVerifier(a),o=null!==(r=t.scope)&&void 0!==r?r:"",l=Array.isArray(o)?o.join(" "):o,u=new URL("https://x.com/i/oauth2/authorize"),d={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:e,state:i,code_challenge:n,code_challenge_method:"s256",scope:l};G.addQueryParamsToUrl(u,d);let c={url:u.toString(),state:i,codeVerifier:a,codeChallenge:n};return this._requestMaker.hasPlugins()&&this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:c,redirectUri:e}),c}async loginWithOAuth2({code:e,codeVerifier:t,redirectUri:s}){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 r=await this.post("https://api.x.com/2/oauth2/token",{code:e,code_verifier:t,redirect_uri:s,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(r)}async refreshOAuth2Token(e){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let t=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:e,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(t)}async revokeOAuth2Token(e,t="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:e,token_type_hint:t})}parseOAuth2AccessTokenResult(e){let t=new this.constructor(e.access_token,this._requestMaker.clientSettings),s=e.scope.split(" ").filter(e=>e);return{client:t,expiresIn:e.expires_in,accessToken:e.access_token,scope:s,refreshToken:e.refresh_token}}}class tu extends tl{get v1(){return this._v1?this._v1:this._v1=new eL(this)}get v2(){return this._v2?this._v2:this._v2=new ta(this)}get readOnly(){return this}}class td extends et{constructor(){super(...arguments),this._prefix=o}}class tc extends td{constructor(){super(...arguments),this._prefix=o}get readOnly(){return this}}class th extends et{constructor(){super(...arguments),this._prefix=l}}class tp extends th{constructor(){super(...arguments),this._prefix=l}get readOnly(){return this}}class tm extends tp{constructor(){super(...arguments),this._prefix=l}get readWrite(){return this}}class tg extends tc{constructor(){super(...arguments),this._prefix=o}get readWrite(){return this}get sandbox(){return this._sandbox?this._sandbox:this._sandbox=new tm(this)}}class t_ extends tu{get v1(){return this._v1?this._v1:this._v1=new eq(this)}get v2(){return this._v2?this._v2:this._v2=new to(this)}get readWrite(){return this}get ads(){return this._ads?this._ads:this._ads=new tg(this)}static getErrors(e){var t;return"object"==typeof e&&"data"in e&&null!==(t=e.data.errors)&&void 0!==t?t:[]}static getProfileImageInSize(e,t){let s=e.split("/").pop(),r=e;for(let t of["normal","bigger","mini"])if(s.includes(`_${t}`)){r=e.replace(`_${t}`,"");break}if("original"===t)return r;let i=r.lastIndexOf(".");if(-1===i)return r+"_"+t;{let e=r.slice(i+1);return r.slice(0,i)+"_"+t+"."+e}}}let tf=t_},3794:(e,t,s)=>{"use strict";s.r(t),s.d(t,{executeSocialTask:()=>z,isSocialTask:()=>K,readSocialFreshness:()=>Y});var r=s(2048),i=s(5315),a=s(9576);let n=function(){let e=process.cwd();if(r.existsSync(i.join(e,"data","config.json")))return e;try{for(let t of r.readdirSync(e,{withFileTypes:!0}))if(t.isDirectory()){let s=i.join(e,t.name,"data","config.json");if(r.existsSync(s))return i.join(e,t.name)}}catch{}let t=e;for(let e=0;e<5;e++){let e=i.dirname(t);if(e===t)break;if(r.existsSync(i.join(e,"data","config.json")))return e;t=e}return e}(),o=i.join(n,"data");i.join(n,"STATUS.md"),i.join(n,"TODO.md"),i.join(n,"MEMORY.md");let l=i.join(o,"ideas.json"),u=i.join(o,"goals.json");i.join(o,"sessions.json"),i.join(o,"config.json"),i.join(o,"business-context.json"),i.join(o,"hypotheses.json"),i.join(o,"implementations.json"),i.join(o,"roadmap.json"),i.join(o,"competitors.json");let d=i.join(o,"positioning.json");i.join(o,"pages.json"),i.join(o,"payments.json"),i.join(o,"posthog.json");let c=i.join(o,"social.json"),h=i.join(__dirname,"..","..","templates");function p(){let e=function(e){let t=i.join(e,".env");if(!r.existsSync(t))return{};let s=r.readFileSync(t,"utf-8"),a={};for(let e of s.split("\n")){let t=e.trim();if(!t||t.startsWith("#"))continue;let s=t.indexOf("=");if(-1===s)continue;let r=t.slice(0,s).trim(),i=t.slice(s+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),a[r]=i}return a}(n),t=e.X_API_KEY||process.env.X_API_KEY,s=e.X_API_SECRET||process.env.X_API_SECRET,a=e.X_ACCESS_TOKEN||process.env.X_ACCESS_TOKEN,o=e.X_ACCESS_SECRET||process.env.X_ACCESS_SECRET;return t&&s&&a&&o?{apiKey:t,apiSecret:s,accessToken:a,accessSecret:o}:null}function m(e){let t;try{let e=s(1401).resolve("twitter-api-v2",{paths:[n]}),r=s(1401)(e);t=r.TwitterApi||r.default?.TwitterApi||r.default}catch{try{let e=s(5883);t=e.TwitterApi||e.default?.TwitterApi||e.default}catch{throw Error("twitter-api-v2 is not installed. Run: npm install twitter-api-v2")}}if("function"!=typeof t)throw Error("Could not find TwitterApi constructor in twitter-api-v2");return new t({appKey:e.apiKey,appSecret:e.apiSecret,accessToken:e.accessToken,accessSecret:e.accessSecret})}async function g(e){try{let t=await e.v2.me({"user.fields":["public_metrics"]}),s=t?.data;if(!s?.username)return{valid:!1,username:null,followersCount:null};return{valid:!0,username:`@${s.username}`,followersCount:s.public_metrics?.followers_count??null}}catch{return{valid:!1,username:null,followersCount:null}}}async function _(e,t){if(t.length>280)throw Error(`Tweet exceeds 280 characters (${t.length})`);let s=await e.v2.tweet(t),r=s?.data?.id;if(!r)throw Error("Tweet posted but no ID returned");return{id:r,url:`https://x.com/i/status/${r}`}}async function f(e,t){if(!s(2048).existsSync(t))throw Error(`Media file not found: ${t}`);let r=await e.v1.uploadMedia(t);if(!r)throw Error("Media uploaded but no media_id returned");return String(r)}async function w(e,t,s){if(t.length>280)throw Error(`Tweet exceeds 280 characters (${t.length})`);if(0===s.length)throw Error("No media IDs provided");if(s.length>4)throw Error("X allows max 4 media attachments per tweet");let r=await e.v2.tweet(t,{media:{media_ids:s}}),i=r?.data?.id;if(!i)throw Error("Tweet posted but no ID returned");return{id:i,url:`https://x.com/i/status/${i}`}}async function y(e,t){try{let s=await e.v2.singleTweet(t,{"tweet.fields":["public_metrics","non_public_metrics","organic_metrics"]}),r=s?.data;if(!r)return null;let i=r.public_metrics??{},a=r.non_public_metrics??{},n=r.organic_metrics??{},o=a.impression_count??n.impression_count??0,l=(i.like_count??0)+(i.retweet_count??0)+(i.reply_count??0)+(i.bookmark_count??0)+(a.url_link_clicks??0)+(a.user_profile_clicks??0);return{tweet_id:t,impressions:o,likes:i.like_count??0,retweets:i.retweet_count??0,replies:i.reply_count??0,bookmarks:i.bookmark_count??0,profile_clicks:a.user_profile_clicks??0,engagements:l,engagement_rate:o>0?l/o:0,fetched_at:new Date().toISOString()}}catch(e){return console.error(`Failed to fetch metrics for tweet ${t}:`,e),null}}async function v(e,t){let s=[];for(let r of t){let t=await y(e,r);t&&s.push(t)}return s}async function b(e,t,s){if(0===t.length)throw Error("Thread must have at least one tweet");if(t.length>25)throw Error("Thread cannot exceed 25 tweets");for(let e=0;e<t.length;e++)if(t[e].length>280)throw Error(`Tweet ${e+1} exceeds 280 characters (${t[e].length})`);let r=[];for(let i=0;i<t.length;i++){let a=t[i],n=s?.[i],o={};i>0&&(o.reply={in_reply_to_tweet_id:r[i-1].id}),n&&(o.media={media_ids:[n]});let l=await e.v2.tweet(a,o),u=l?.data?.id;if(!u)throw Error(`Thread tweet ${i+1} posted but no ID returned`);r.push({id:u,url:`https://x.com/i/status/${u}`})}return r}i.join(h,"commands");let x="#buildinpublic";function k(e,t=280){return e.length<=t?e:e.slice(0,t-3).trimEnd()+"..."}function R(e,t){try{if(!r.existsSync(e))return t;return JSON.parse(r.readFileSync(e,"utf-8"))}catch{return t}}function T(e){if(!e){let t=R(l,{ideas:[]}).ideas.filter(e=>"shipped"===e.stage).sort((e,t)=>(t.implementation?.completed_at||t.updated_at).localeCompare(e.implementation?.completed_at||e.updated_at));if(0===t.length)return null;e=t[0]}return k(`Just shipped: ${e.title}. ${e.summary} ${x}`)}var S=s(1282);let D=i.join(process.env.HOME||"",".ai-analyst"),P=i.join(D,"provider.json");async function E(e){let t=Date.now(),s=process.env.ANTHROPIC_API_KEY;if(!s)return{output:"",provider:"anthropic-api",durationMs:0,error:"ANTHROPIC_API_KEY not set"};try{let r=e.model||"claude-sonnet-4-5-20250929",i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":s,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:r,max_tokens:16384,messages:[{role:"user",content:e.prompt}]}),signal:AbortSignal.timeout(e.timeoutMs||3e5)});if(!i.ok){let e=await i.text();return{output:"",provider:"anthropic-api",durationMs:Date.now()-t,error:`Anthropic API error ${i.status}: ${e}`}}return{output:(await i.json()).content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),provider:"anthropic-api",durationMs:Date.now()-t}}catch(e){return{output:"",provider:"anthropic-api",durationMs:Date.now()-t,error:`Anthropic API call failed: ${e.message}`}}}async function A(e){let t=function(){try{if(r.existsSync(P))return JSON.parse(r.readFileSync(P,"utf-8"))}catch{}return null}(),s=function(e){let t=function(e){let t=e||"claude";try{let e=(0,S.execSync)(`${t} --version 2>/dev/null`,{timeout:1e4,encoding:"utf-8"}).trim();return{found:!0,path:t,version:e}}catch{for(let e of["/usr/local/bin/claude",i.join(process.env.HOME||"",".claude","bin","claude"),i.join(process.env.HOME||"",".local","bin","claude")])try{if(r.existsSync(e)){let t=(0,S.execSync)(`${e} --version 2>/dev/null`,{timeout:1e4,encoding:"utf-8"}).trim();return{found:!0,path:e,version:t}}}catch{continue}return{found:!1,path:t}}}(e?.claudePath);if(t.found)return{provider:"claude-cli",version:t.version,message:`Found Claude Code CLI${t.version?` (${t.version})`:""}. Using your Claude subscription for AI reasoning.`};let s=process.env.ANTHROPIC_API_KEY?{provider:"anthropic-api",key:process.env.ANTHROPIC_API_KEY}:process.env.OPENAI_API_KEY?{provider:"openai-api",key:process.env.OPENAI_API_KEY}:process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY?{provider:"google-api",key:process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY}:null;return s?{provider:s.provider,message:`Using ${({"claude-cli":"Claude CLI","anthropic-api":"Anthropic API","openai-api":"OpenAI API","google-api":"Google AI API"})[s.provider]} key for AI reasoning.`}:{provider:"claude-cli",message:"No AI provider found. Install Claude Code CLI or set an API key (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)."}}(t||void 0);switch(s.provider){case"claude-cli":return function(e,t){let s=t||"claude",r=["--print"];e.model&&r.push("--model",e.model),e.claudeFlags&&r.push(...e.claudeFlags);let i=!1!==e.useStdin&&e.prompt.length>1e4;i||r.push("-p",e.prompt);let a=Date.now(),n=e.timeoutMs||3e5;return new Promise(t=>{let o=(0,S.spawn)(s,r,{cwd:e.cwd||process.cwd(),env:process.env,stdio:i?["pipe","pipe","pipe"]:["ignore","pipe","pipe"]}),l="",u="";o.stdout?.on("data",e=>{l+=e.toString()}),o.stderr?.on("data",e=>{u+=e.toString()}),i&&o.stdin&&(o.stdin.write(e.prompt),o.stdin.end());let d=setTimeout(()=>{o.kill("SIGTERM"),t({output:l,provider:"claude-cli",durationMs:Date.now()-a,error:`Timeout after ${n}ms`})},n);o.on("close",e=>{clearTimeout(d),t({output:l.trim(),provider:"claude-cli",durationMs:Date.now()-a,error:0!==e?`Claude CLI exited with code ${e}: ${u}`:void 0})}),o.on("error",e=>{clearTimeout(d),t({output:"",provider:"claude-cli",durationMs:Date.now()-a,error:`Failed to spawn Claude CLI: ${e.message}`})})})}(e,t?.claudePath);case"anthropic-api":return E(e);case"openai-api":case"google-api":return{output:"",provider:s.provider,durationMs:0,error:`${s.provider} provider not yet implemented. Use Claude CLI or set ANTHROPIC_API_KEY.`};default:return{output:"",provider:"claude-cli",durationMs:0,error:s.message}}}function L(e,t){try{if(!r.existsSync(e))return t;return JSON.parse(r.readFileSync(e,"utf-8"))}catch{return t}}function I(e){if(!e||0===e.length)return"No historical data yet.";let t=[...e].sort((e,t)=>t.engagement_rate-e.engagement_rate),s=e.reduce((e,t)=>e+t.engagement_rate,0)/e.length,r=t[0];return`Average engagement rate: ${(100*s).toFixed(2)}%
1
+ exports.id=3794,exports.ids=[3794],exports.modules={1401:e=>{function t(e){var t=Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=1401,e.exports=t},5883:(e,t,s)=>{"use strict";s.r(t),s.d(t,{ApiPartialResponseError:()=>f,ApiRequestError:()=>_,ApiResponseError:()=>w,DmEventsV1Paginator:()=>p,EApiV1ErrorCode:()=>x,EApiV2ErrorCode:()=>S,EDirectMessageEventTypeV1:()=>b,ETwitterApiError:()=>k,ETwitterStreamEvent:()=>R,EUploadMimeType:()=>v,FriendshipsIncomingV1Paginator:()=>eg,FriendshipsOutgoingV1Paginator:()=>e_,HomeTimelineV1Paginator:()=>er,ListMembersV1Paginator:()=>ek,ListMembershipsV1Paginator:()=>ew,ListOwnershipsV1Paginator:()=>ey,ListSubscribersV1Paginator:()=>ex,ListSubscriptionsV1Paginator:()=>ev,ListTimelineV1Paginator:()=>en,MentionTimelineV1Paginator:()=>ei,MuteUserIdsV1Paginator:()=>eu,MuteUserListV1Paginator:()=>el,PreviousableTwitterPaginator:()=>d,QuotedTweetsTimelineV2Paginator:()=>eU,TweetBookmarksTimelineV2Paginator:()=>eV,TweetHomeTimelineV2Paginator:()=>eB,TweetLikingUsersV2Paginator:()=>e2,TweetRetweetersUsersV2Paginator:()=>e4,TweetSearchAllV2Paginator:()=>eN,TweetSearchRecentV2Paginator:()=>eF,TweetStream:()=>H,TweetUserMentionTimelineV2Paginator:()=>eW,TweetUserTimelineV2Paginator:()=>eH,TweetV2ListTweetsPaginator:()=>ez,TweetV2UserLikedTweetsPaginator:()=>eY,TwitterApi:()=>t_,TwitterApiPluginResponseOverride:()=>y,TwitterApiReadOnly:()=>tl,TwitterApiReadWrite:()=>tu,TwitterApiV2Settings:()=>P,TwitterApiv1:()=>eI,TwitterApiv2:()=>to,TwitterApiv2Labs:()=>tn,TwitterPaginator:()=>u,TwitterV2IncludesHelper:()=>ej,UserBlockingUsersV2Paginator:()=>eG,UserFavoritesV1Paginator:()=>eo,UserFollowerIdsV1Paginator:()=>ec,UserFollowerListV1Paginator:()=>ed,UserFollowersIdsV1Paginator:()=>ep,UserFollowersV2Paginator:()=>eX,UserFollowingV2Paginator:()=>eZ,UserFriendListV1Paginator:()=>eh,UserListFollowedV2Paginator:()=>e7,UserListFollowersV2Paginator:()=>e1,UserListMembersV2Paginator:()=>e0,UserListMembershipsV2Paginator:()=>e3,UserMutingUsersV2Paginator:()=>eQ,UserOwnedListsV2Paginator:()=>e5,UserSearchV1Paginator:()=>em,UserTimelineV1Paginator:()=>ea,WelcomeDmV1Paginator:()=>m,default:()=>tf});let r="https://api.x.com/2/",i="https://api.x.com/labs/2/",a="https://api.x.com/1.1/",n="https://upload.x.com/1.1/",o="https://ads-api.x.com/12/",l="https://ads-api-sandbox.twitter.com/12/";class u{constructor({realData:e,rateLimit:t,instance:s,queryParams:r,sharedParams:i}){this._maxResultsWhenFetchLast=100,this._realData=e,this._rateLimit=t,this._instance=s,this._queryParams=r,this._sharedParams=i}get _isRateLimitOk(){return!!(!this._rateLimit||1e3*this._rateLimit.reset<Date.now())||this._rateLimit.remaining>0}makeRequest(e){return this._instance.get(this.getEndpoint(),e,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(e,t){return new this.constructor({realData:e.data,rateLimit:e.rateLimit,instance:this._instance,queryParams:t,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(e){return{...e?{max_results:e}:{},...this._queryParams}}async next(e){let t=this.getNextQueryParams(e),s=await this.makeRequest(t);return this.makeNewInstanceFromResult(s,t)}async fetchNext(e){let t=this.getNextQueryParams(e),s=await this.makeRequest(t);return await this.refreshInstanceFromResult(s,!0),this}async fetchLast(e=1/0){let t=this.getNextQueryParams(this._maxResultsWhenFetchLast),s=0;for(;s<e&&this._isRateLimitOk;){let e=await this.makeRequest(t);if(await this.refreshInstanceFromResult(e,!0),s+=this.getPageLengthFromRequest(e),this.isFetchLastOver(e))break;t=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var e;return{...null!==(e=this._rateLimit)&&void 0!==e?e:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async *[Symbol.asyncIterator](){yield*this.getItemArray();let e=this,t=this.canFetchNextPage(this._realData);for(;t&&this._isRateLimitOk&&e.getItemArray().length>0;){let s=await e.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:s._realData,headers:{},rateLimit:s._rateLimit},!0),t=this.canFetchNextPage(s._realData);let r=s.getItemArray();yield*r,e=s}}async *fetchAndIterate(){for(let e of this.getItemArray())yield[e,this];let e=this,t=this.canFetchNextPage(this._realData);for(;t&&this._isRateLimitOk&&e.getItemArray().length>0;){let s=await e.next(this._maxResultsWhenFetchLast);for(let e of(this.refreshInstanceFromResult({data:s._realData,headers:{},rateLimit:s._rateLimit},!0),t=this.canFetchNextPage(s._realData),s.getItemArray()))yield[e,s];this._rateLimit=s._rateLimit,e=s}}}class d extends u{async previous(e){let t=this.getPreviousQueryParams(e),s=await this.makeRequest(t);return this.makeNewInstanceFromResult(s,t)}async fetchPrevious(e){let t=this.getPreviousQueryParams(e),s=await this.makeRequest(t);return await this.refreshInstanceFromResult(s,!1),this}}let c=u;class h extends c{getNextQueryParams(e){var t;return{...this._queryParams,cursor:null!==(t=this._realData.next_cursor_str)&&void 0!==t?t:this._realData.next_cursor,...e?{count:e}:{}}}isFetchLastOver(e){return!this.canFetchNextPage(e.data)}canFetchNextPage(e){return!this.isNextCursorInvalid(e.next_cursor)||!this.isNextCursorInvalid(e.next_cursor_str)}isNextCursorInvalid(e){return void 0===e||0===e||-1===e||"0"===e||"-1"===e}}class p extends h{constructor(){super(...arguments),this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.events.push(...s.events),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class m extends h{constructor(){super(...arguments),this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.welcome_messages.push(...s.welcome_messages),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}(function(e){e.Jpeg="image/jpeg",e.Mp4="video/mp4",e.Mov="video/quicktime",e.Gif="image/gif",e.Png="image/png",e.Srt="text/plain",e.Webp="image/webp"})(v||(v={})),function(e){e.Create="message_create",e.WelcomeCreate="welcome_message"}(b||(b={})),function(e){e.Request="request",e.PartialResponse="partial-response",e.Response="response"}(k||(k={}));class g extends Error{constructor(){super(...arguments),this.error=!0}}class _ extends g{constructor(e,t){super(e),this.type=k.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class f extends g{constructor(e,t){super(e),this.type=k.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t})}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 w extends g{constructor(e,t){if(super(e),this.type=k.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t}),this.code=t.code,this.headers=t.headers,this.rateLimit=t.rateLimit,t.data&&"object"==typeof t.data&&"error"in t.data&&!t.data.errors){let e={...t.data};e.errors=[{code:x.InternalError,message:e.error}],this.data=e}else this.data=t.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...e){let t=this.errors;if(!(null==t?void 0:t.length))return!1;if("code"in t[0])return t.some(t=>e.includes(t.code));let s=this.data;return e.includes(s.type)}get errors(){var e;return null===(e=this.data)||void 0===e?void 0:e.errors}get rateLimitError(){return 420===this.code||429===this.code}get isAuthError(){return 401===this.code||this.hasErrorCode(x.AuthTimestampInvalid,x.AuthenticationFail,x.BadAuthenticationData,x.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}(function(e){e[e.InvalidCoordinates=3]="InvalidCoordinates",e[e.NoLocationFound=13]="NoLocationFound",e[e.AuthenticationFail=32]="AuthenticationFail",e[e.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",e[e.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",e[e.AuthTimestampInvalid=135]="AuthTimestampInvalid",e[e.BadAuthenticationData=215]="BadAuthenticationData",e[e.NoUserMatch=17]="NoUserMatch",e[e.UserNotFound=50]="UserNotFound",e[e.ResourceNotFound=34]="ResourceNotFound",e[e.TweetNotFound=144]="TweetNotFound",e[e.TweetNotVisible=179]="TweetNotVisible",e[e.NotAllowedResource=220]="NotAllowedResource",e[e.MediaIdNotFound=325]="MediaIdNotFound",e[e.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",e[e.TweetViolatedRules=422]="TweetViolatedRules",e[e.TargetUserSuspended=63]="TargetUserSuspended",e[e.YouAreSuspended=64]="YouAreSuspended",e[e.AccountUpdateFailed=120]="AccountUpdateFailed",e[e.NoSelfSpamReport=36]="NoSelfSpamReport",e[e.NoSelfMute=271]="NoSelfMute",e[e.AccountLocked=326]="AccountLocked",e[e.RateLimitExceeded=88]="RateLimitExceeded",e[e.NoDMRightForApp=93]="NoDMRightForApp",e[e.OverCapacity=130]="OverCapacity",e[e.InternalError=131]="InternalError",e[e.TooManyFollowings=161]="TooManyFollowings",e[e.TweetLimitExceeded=185]="TweetLimitExceeded",e[e.DuplicatedTweet=187]="DuplicatedTweet",e[e.TooManySpamReports=205]="TooManySpamReports",e[e.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",e[e.NoWriteRightForApp=261]="NoWriteRightForApp",e[e.TweetActionsDisabled=425]="TweetActionsDisabled",e[e.TweetRepliesRestricted=433]="TweetRepliesRestricted",e[e.NamedParameterMissing=38]="NamedParameterMissing",e[e.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",e[e.TweetTextTooLong=186]="TweetTextTooLong",e[e.MissingUrlParameter=195]="MissingUrlParameter",e[e.NoMultipleGifs=323]="NoMultipleGifs",e[e.InvalidMediaIds=324]="InvalidMediaIds",e[e.InvalidUrl=407]="InvalidUrl",e[e.TooManyTweetAttachments=386]="TooManyTweetAttachments",e[e.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",e[e.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",e[e.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",e[e.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",e[e.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",e[e.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",e[e.UnableToSendDM=151]="UnableToSendDM",e[e.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",e[e.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",e[e.DMTextTooLong=354]="DMTextTooLong",e[e.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",e[e.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",e[e.SuspendedApplication=416]="SuspendedApplication",e[e.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(x||(x={})),function(e){e.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",e.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",e.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",e.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",e.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",e.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",e.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",e.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",e.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",e.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",e.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",e.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",e.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"}(S||(S={})),function(e){e.Connected="connected",e.ConnectError="connect error",e.ConnectionError="connection error",e.ConnectionClosed="connection closed",e.ConnectionLost="connection lost",e.ReconnectAttempt="reconnect attempt",e.Reconnected="reconnected",e.ReconnectError="reconnect error",e.ReconnectLimitExceeded="reconnect limit exceeded",e.DataKeepAlive="data keep-alive",e.Data="data event content",e.DataError="data twitter error",e.TweetParseError="data tweet parse error",e.Error="stream error"}(R||(R={}));class y{constructor(e){this.value=e}}var v,b,k,x,S,R,T,D=s(2048);let P={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function E(e){let t={value:void 0,promise:e().then(e=>(t.value=e,e))};return t}function A(e){return Array.isArray(e)?e:[e]}function L(e){return"object"==typeof e&&"errors"in e&&!("data"in e)}function I(e){return!!Array.isArray(e)&&e.length>1||e.toString().includes(",")}let q=new Set;function j(e){if("undefined"==typeof console||!console.warn||!P.deprecationWarnings)return;let t=`${e.instance}-${e.method}-${e.problem}`;q.has(t)||(console.warn(`[twitter-api-v2] Deprecation warning: In ${e.instance}.${e.method}() call, ${e.problem}.
2
+ ${e.resolution}.`),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),q.add(t))}var C=s(7702),M=s(8791),O=s(1568);class ${constructor(e){this.requestData=e,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let e=this.requestData.url;return e.hostname+e.pathname}isCompressionDisabled(){return!this.requestData.compression||"identity"===this.requestData.compression}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(e){return P.debug&&P.logger.log("Request error:",e),new _("Request failed.",{request:this.req,error:e})}createPartialResponseError(e,t){let s=this.res,r=`Request failed with partial response with HTTP code ${s.statusCode}`;return t?r+=" (connection abruptly closed)":r+=" (parse error)",new f(r,{request:this.req,response:this.res,responseError:e,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(e){return e.map(({code:e,message:t})=>`${t} (Twitter code ${e})`).join(", ")}formatV2Error(e){return`${e.title}: ${e.detail} (see ${e.type})`}createResponseError({res:e,data:t,rateLimit:s,code:r}){var i;P.debug&&(P.logger.log(`Request failed with code ${r}, data:`,t),P.logger.log("Response headers:",e.headers));let a=`Request failed with code ${r}`;if(null===(i=null==t?void 0:t.errors)||void 0===i?void 0:i.length){let e=t.errors;"object"==typeof e[0]&&"code"in e[0]?a+=" - "+this.formatV1Errors(e):a+=" - "+this.formatV2Error(t)}return new w(a,{code:r,data:t,headers:e.headers,request:this.req,response:e,rateLimit:s})}getResponseDataStream(e){if(this.isCompressionDisabled())return e;let t=(e.headers["content-encoding"]||"identity").trim().toLowerCase();if("br"===t){let t=O.createBrotliDecompress({flush:O.constants.BROTLI_OPERATION_FLUSH,finishFlush:O.constants.BROTLI_OPERATION_FLUSH});return e.pipe(t),t}if("gzip"===t){let t=O.createGunzip({flush:O.constants.Z_SYNC_FLUSH,finishFlush:O.constants.Z_SYNC_FLUSH});return e.pipe(t),t}if("deflate"===t){let t=O.createInflate({flush:O.constants.Z_SYNC_FLUSH,finishFlush:O.constants.Z_SYNC_FLUSH});return e.pipe(t),t}return e}detectResponseType(e){var t,s;return(null===(t=e.headers["content-type"])||void 0===t?void 0:t.includes("application/json"))||(null===(s=e.headers["content-type"])||void 0===s?void 0:s.includes("application/problem+json"))?"json":this.isFormEncodedEndpoint()?"url":"text"}getParsedResponse(e){let t=this.responseData,s=this.requestData.forceParseMode||this.detectResponseType(e);if("buffer"===s)return Buffer.concat(t);if("text"===s)return Buffer.concat(t).toString();if("json"===s){let e=Buffer.concat(t).toString();return e.length?JSON.parse(e):void 0}{if("url"!==s)return;let e=Buffer.concat(t).toString(),r={};for(let[t,s]of new URLSearchParams(e))r[t]=s;return r}}getRateLimitFromResponse(e){let t;return e.headers["x-rate-limit-limit"]&&(t={limit:Number(e.headers["x-rate-limit-limit"]),remaining:Number(e.headers["x-rate-limit-remaining"]),reset:Number(e.headers["x-rate-limit-reset"])},e.headers["x-app-limit-24hour-limit"]&&(t.day={limit:Number(e.headers["x-app-limit-24hour-limit"]),remaining:Number(e.headers["x-app-limit-24hour-remaining"]),reset:Number(e.headers["x-app-limit-24hour-reset"])}),e.headers["x-user-limit-24hour-limit"]&&(t.userDay={limit:Number(e.headers["x-user-limit-24hour-limit"]),remaining:Number(e.headers["x-user-limit-24hour-remaining"]),reset:Number(e.headers["x-user-limit-24hour-reset"])}),this.requestData.rateLimitSaver&&this.requestData.rateLimitSaver(t)),t}onSocketEventHandler(e,t,s){let r=this.onSocketCloseHandler.bind(this,e);s.on("close",r),t.on("complete",()=>s.off("close",r))}onSocketCloseHandler(e){if(this.req.removeAllListeners("timeout"),!this.res&&!this.requestErrorHandled)return e(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(e,t){var s,r;null===(r=(s=this.requestData).requestEventDebugHandler)||void 0===r||r.call(s,"request-error",{requestError:t}),this.requestErrorHandled=!0,e(this.createRequestError(t))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(e,t,s){this.res=s;let r=this.getResponseDataStream(s);r.on("data",e=>this.responseData.push(e)),r.on("end",this.onResponseEndHandler.bind(this,e,t)),r.on("close",this.onResponseCloseHandler.bind(this,e,t)),this.requestData.requestEventDebugHandler&&(this.requestData.requestEventDebugHandler("response",{res:s}),s.on("aborted",e=>this.requestData.requestEventDebugHandler("response-aborted",{error:e})),s.on("error",e=>this.requestData.requestEventDebugHandler("response-error",{error:e})),s.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),s.on("end",()=>this.requestData.requestEventDebugHandler("response-end")))}onResponseEndHandler(e,t){let s;let r=this.getRateLimitFromResponse(this.res);try{s=this.getParsedResponse(this.res)}catch(e){t(this.createPartialResponseError(e,!1));return}let i=this.res.statusCode;if(i>=400){t(this.createResponseError({data:s,res:this.res,rateLimit:r,code:i}));return}P.debug&&(P.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),P.logger.log("Response body:",s)),e({data:s,headers:this.res.headers,rateLimit:r})}onResponseCloseHandler(e,t){let s=this.res;if(s.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(e,t)}catch(e){return t(this.createPartialResponseError(e,!0))}if(!s.complete)return t(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(e,t,s){if(s.statusCode<400){P.debug&&P.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${s.statusCode} (starting stream)`);let t=this.getResponseDataStream(s);e({req:this.req,res:t,originalResponse:s,requestData:this.requestData})}else this.classicResponseHandler(()=>void 0,t,s)}debugRequest(){let e=this.requestData.url;P.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),e.search&&P.logger.log("Request parameters:",[...e.searchParams.entries()].map(([e,t])=>`${e}: ${t}`)),this.requestData.body&&P.logger.log("Request body:",this.requestData.body)}buildRequest(){var e;let t=this.requestData.url,s=t.username?`${t.username}:${t.password}`:void 0,r=null!==(e=this.requestData.options.headers)&&void 0!==e?e:{};!0===this.requestData.compression||"brotli"===this.requestData.compression?r["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1":"gzip"===this.requestData.compression?r["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1":"deflate"===this.requestData.compression&&(r["accept-encoding"]="deflate;q=1, *;q=0.1"),P.debug&&this.debugRequest(),this.req=(0,M.request)({...this.requestData.options,host:t.hostname,port:t.port||void 0,path:t.pathname+t.search,protocol:t.protocol,auth:s,headers:r})}registerRequestEventDebugHandlers(e){e.on("close",()=>this.requestData.requestEventDebugHandler("close")),e.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),e.on("socket",e=>{this.requestData.requestEventDebugHandler("socket",{socket:e}),e.on("error",t=>this.requestData.requestEventDebugHandler("socket-error",{socket:e,error:t})),e.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:e})),e.on("close",t=>this.requestData.requestEventDebugHandler("socket-close",{socket:e,withError:t})),e.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:e})),e.on("lookup",(...t)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:e,data:t})),e.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:e}))})}makeRequest(){return this.buildRequest(),new Promise((e,t)=>{let s=e=>{r.emit("complete"),t(e)},r=new C.EventEmitter,i=this.req;i.on("error",this.requestErrorHandler.bind(this,s)),i.on("socket",this.onSocketEventHandler.bind(this,s,r)),i.on("response",this.classicResponseHandler.bind(this,t=>{r.emit("complete"),e(t)},s)),this.requestData.options.timeout&&i.on("timeout",this.timeoutErrorHandler.bind(this)),this.requestData.requestEventDebugHandler&&this.registerRequestEventDebugHandlers(i),this.requestData.body&&i.write(this.requestData.body),i.end()})}async makeRequestAsStream(){let{req:e,res:t,requestData:s,originalResponse:r}=await this.makeRequestAndResolveWhenReady();return new W(s,{req:e,res:t,originalResponse:r})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((e,t)=>{let s=this.req;s.on("error",this.requestErrorHandler.bind(this,t)),s.on("response",this.streamResponseHandler.bind(this,e,t)),this.requestData.body&&s.write(this.requestData.body),s.end()})}}class F extends C.EventEmitter{constructor(e){super(),this.stream=e,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),e.on(R.Data,this.onStreamData),e.on(R.ConnectionError,this.onStreamError),e.on(R.TweetParseError,this.onStreamError),e.on(R.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let e=this.stack;return this.stack=[],e}destroy(){this.removeAllListeners(),this.stream.off(R.Data,this.onStreamData),this.stream.off(R.ConnectionError,this.onStreamError),this.stream.off(R.TweetParseError,this.onStreamError),this.stream.off(R.ConnectionClosed,this.onStreamError)}emitEvent(e,t){this.emit("event",{type:e,payload:t})}onStreamError(e){this.emitEvent("error",e)}onStreamData(e){this.stack.push(e),this.emitEvent("data",e)}}class N extends C.EventEmitter{constructor(){super(...arguments),this.currentMessage=""}push(e){this.currentMessage+=e;let t=(e=this.currentMessage).length,s=0,r=0;for(;r<t;){if("\r\n"===e.slice(r,r+2)){let t=e.slice(s,r);if(s=r+=2,!t.length)continue;try{let e=JSON.parse(t);if(e){this.emit(T.ParsedData,e);continue}}catch(e){this.emit(T.ParseError,e)}}r++}this.currentMessage=e.slice(s,t)}reset(){this.currentMessage=""}}!function(e){e.ParsedData="parsed data",e.ParseError="parse error"}(T||(T={}));let U=[5,15,30,60,90,120,180,300,600,900],B=e=>e>U.length?901e3:1e3*U[e-1];class H extends C.EventEmitter{constructor(e,t){super(),this.requestData=e,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=12e4,this.nextRetryTimeout=B,this.parser=new N,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),t&&(this.req=t.req,this.res=t.res,this.originalResponse=t.originalResponse,this.initEventsFromRequest())}on(e,t){return super.on(e,t)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let e=e=>{this.emit(R.ConnectionError,e),this.emit(R.Error,{type:R.ConnectionError,error:e,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",e),this.res.on("error",e),this.res.on("close",()=>e(Error("Connection closed by Twitter."))),this.res.on("data",e=>{if(this.resetKeepAliveTimeout(),"\r\n"===e.toString())return this.emit(R.DataKeepAlive);this.parser.push(e.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let e=this.requestData.payloadIsError;this.parser.on(T.ParsedData,t=>{e&&e(t)?(this.emit(R.DataError,t),this.emit(R.Error,{type:R.DataError,error:t,message:"Twitter sent a payload that is detected as an error payload."})):this.emit(R.Data,t)}),this.parser.on(T.ParseError,e=>{this.emit(R.TweetParseError,e),this.emit(R.Error,{type:R.TweetParseError,error:e,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0&&(this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs))}onKeepAliveTimeout(){this.emit(R.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){this.keepAliveTimeout&&(clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0)}unbindRetryTimeout(){this.retryTimeout&&(clearTimeout(this.retryTimeout),this.retryTimeout=void 0)}closeWithoutEmit(){this.unbindTimeouts(),this.res&&(this.res.removeAllListeners(),this.res.destroy()),this.req&&(this.req.removeAllListeners(),this.req.destroy())}close(){this.emit(R.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let e=new $(this.requestData),t=await e.makeRequestAsStream();for(let e of this.eventNames())for(let s of this.listeners(e))t.on(e,s);return t}async connect(e={}){void 0!==e.autoReconnect&&(this.autoReconnect=e.autoReconnect),void 0!==e.autoReconnectRetries&&(this.autoReconnectRetries="unlimited"===e.autoReconnectRetries?1/0:e.autoReconnectRetries),void 0!==e.keepAliveTimeout&&(this.keepAliveTimeoutMs="disable"===e.keepAliveTimeout?1/0:e.keepAliveTimeout),void 0!==e.nextRetryTimeout&&(this.nextRetryTimeout=e.nextRetryTimeout),this.unbindTimeouts();try{await this.reconnect()}catch(e){if(this.emit(R.ConnectError,0),this.emit(R.Error,{type:R.ConnectError,error:e,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,e);else throw e}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let e=!0;this.req&&(e=!1,this.closeWithoutEmit());let{req:t,res:s,originalResponse:r}=await new $(this.requestData).makeRequestAndResolveWhenReady();this.req=t,this.res=s,this.originalResponse=r,this.emit(e?R.Connected:R.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(e=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(R.ConnectionClosed);return}if(e>=this.autoReconnectRetries){this.emit(R.ReconnectLimitExceeded),this.emit(R.ConnectionClosed);return}try{this.emit(R.ReconnectAttempt,e),await this.reconnect()}catch(t){this.emit(R.ReconnectError,e),this.emit(R.Error,{type:R.ReconnectError,error:t,message:`Reconnect error - ${e+1} attempts made yet.`}),this.makeAutoReconnectRetry(e,t)}}makeAutoReconnectRetry(e,t){let s=this.nextRetryTimeout(e+1,t);this.retryTimeout=setTimeout(()=>{this.onConnectionError(e+1)},s)}async *[Symbol.asyncIterator](){let e=new F(this);try{for(;;){if(!this.req||this.req.aborted)throw Error("Connection closed");e.hasStack()&&(yield*e.popStack());let{type:t,payload:s}=await e.nextEvent();if("error"===t)throw s}}finally{e.destroy()}}}let W=H;async function V(e,t,s,r){let i;return(r instanceof _||r instanceof f?i=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,error:r}):r instanceof w&&(i=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,error:r})),i&&i instanceof y)?i.value:Promise.reject(r)}var K=s(4770);class Y{constructor(e){this.nonceLength=32,this.consumerKeys=e.consumerKeys}static percentEncode(e){return encodeURIComponent(e).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(e,t){return K.createHmac("sha1",t).update(e).digest("base64")}authorize(e,t={}){let s={oauth_consumer_key:this.consumerKeys.key,oauth_nonce:this.getNonce(),oauth_signature_method:"HMAC-SHA1",oauth_timestamp:this.getTimestamp(),oauth_version:"1.0"};return void 0!==t.key&&(s.oauth_token=t.key),e.data||(e.data={}),s.oauth_signature=this.getSignature(e,t.secret,s),s}toHeader(e){let t=J(e),s="OAuth ";for(let e of t)0===e.key.indexOf("oauth_")&&(s+=Y.percentEncode(e.key)+'="'+Y.percentEncode(e.value)+'",');return{Authorization:s.slice(0,s.length-1)}}getNonce(){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let s=0;s<this.nonceLength;s++)t+=e[Math.trunc(Math.random()*e.length)];return t}getTimestamp(){return Math.trunc(new Date().getTime()/1e3)}getSignature(e,t,s){return this.hash(this.getBaseString(e,s),this.getSigningKey(t))}getSigningKey(e){return Y.percentEncode(this.consumerKeys.secret)+"&"+Y.percentEncode(e||"")}getBaseString(e,t){return e.method.toUpperCase()+"&"+Y.percentEncode(this.getBaseUrl(e.url))+"&"+Y.percentEncode(this.getParameterString(e,t))}getParameterString(e,t){let s=J(function(e){let t={};for(let s in e){let r=e[s];r=r&&Array.isArray(r)?r.map(e=>Y.percentEncode(e)):Y.percentEncode(r),t[Y.percentEncode(s)]=r}return t}(z(t,z(e.data,function(e){let t=e.split("?");return 1===t.length?{}:function(e){let t=e.split("&"),s={};for(let e of t){let[t,r=""]=e.split("=");s[t]?(Array.isArray(s[t])||(s[t]=[s[t]]),s[t].push(decodeURIComponent(r))):s[t]=decodeURIComponent(r)}return s}(t[1])}(e.url))))),r="";for(let{key:e,value:t}of s)if(t&&Array.isArray(t)){t.sort();let s="";t.forEach((r,i)=>{s+=e+"="+r,i<t.length&&(s+="&")}),r+=s}else r+=e+"="+t+"&";return r.slice(0,r.length-1)}getBaseUrl(e){return e.split("?")[0]}}function z(e,t){return{...e||{},...t||{}}}function J(e){return Object.keys(e).sort().map(t=>({key:t,value:e[t]}))}class G{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...e){let t=e.map(e=>e instanceof Buffer?e:Buffer.from(e));this._chunks.push(...t)}append(e,t,s){let r=t instanceof Buffer?t:t.toString(),i=this.getMultipartHeader(e,r,s);this.bodyAppend(i,r,G.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((e,t)=>e+t.length,this.getMultipartFooter().length)}getBuffer(){let e=[...this._chunks,this.getMultipartFooter()],t=Buffer.alloc(this.getLength()),s=0;for(let r of e)for(let e=0;e<r.length;s++,e++)t[s]=r[e];return t}getBoundary(){return this._boundary||this.generateBoundary(),this._boundary}generateBoundary(){let e="--------------------------";for(let t=0;t<24;t++)e+=Math.floor(10*Math.random()).toString(16);this._boundary=e}getMultipartHeader(e,t,s){s||(s=t instanceof Buffer?G.DEFAULT_CONTENT_TYPE:"");let r="";for(let[t,i]of Object.entries({"Content-Disposition":["form-data",`name="${e}"`],"Content-Type":s}))i.length&&(r+=t+": "+A(i).join("; ")+G.LINE_BREAK);return"--"+this.getBoundary()+G.LINE_BREAK+r+G.LINE_BREAK}getMultipartFooter(){return this._footerChunk?this._footerChunk:this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+G.LINE_BREAK)}}G.LINE_BREAK="\r\n",G.DEFAULT_CONTENT_TYPE="application/octet-stream";class Q{static formatQueryToString(e){let t={};for(let s in e)"string"==typeof e[s]?t[s]=e[s]:void 0!==e[s]&&(t[s]=String(e[s]));return t}static autoDetectBodyType(e){if(e.pathname.startsWith("/2/")||e.pathname.startsWith("/labs/2/"))return e.password.startsWith("/2/oauth2")?"url":"json";if("upload.x.com"===e.hostname)return"/1.1/media/upload.json"===e.pathname?"form-data":"json";let t=e.pathname.split("/1.1/",2)[1];return this.JSON_1_1_ENDPOINTS.has(t)?"json":"url"}static addQueryParamsToUrl(e,t){let s=Object.entries(t);if(s.length){let t="";for(let[e,r]of s)t+=(t.length?"&":"?")+`${Y.percentEncode(e)}=${Y.percentEncode(r)}`;e.search=t}}static constructBodyParams(e,t,s){if(e instanceof Buffer)return e;if("json"===s)return t["content-type"]||(t["content-type"]="application/json;charset=UTF-8"),JSON.stringify(e);if("url"===s)return(t["content-type"]||(t["content-type"]="application/x-www-form-urlencoded;charset=UTF-8"),Object.keys(e).length)?new URLSearchParams(e).toString().replace(/\*/g,"%2A"):"";if("raw"===s)throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");{let s=new G;for(let t in e)s.append(t,e[t]);if(!t["content-type"]){let e=s.getHeaders();t["content-type"]=e["content-type"]}return s.getBuffer()}}static setBodyLengthHeader(e,t){var s;e.headers=null!==(s=e.headers)&&void 0!==s?s:{},"string"==typeof t?e.headers["content-length"]=Buffer.byteLength(t):e.headers["content-length"]=t.length}static isOAuthSerializable(e){return!(e instanceof Buffer)}static mergeQueryAndBodyForOAuth(e,t){let s={};for(let t in e)s[t]=e[t];if(this.isOAuthSerializable(t))for(let e in t){let r=t[e];this.isOAuthSerializable(r)&&(s[e]="object"==typeof r&&null!==r&&"toString"in r?r.toString():r)}return s}static moveUrlQueryParamsIntoObject(e,t){for(let[s,r]of e.searchParams)t[s]=r;return e.search="",e}static applyRequestParametersToUrl(e,t){return e.pathname=e.pathname.replace(/:([A-Z_-]+)/ig,(e,s)=>void 0!==t[s]?String(t[s]):e),e}}Q.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"]);class X{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(e){return this.escapeBase64Url(K.createHash("sha256").update(e).digest("base64"))}static getAuthHeader(e,t){let s=encodeURIComponent(e)+":"+encodeURIComponent(t);return Buffer.from(s).toString("base64")}static generateRandomString(e){let t="",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let r=0;r<e;r++)t+=s[Math.floor(Math.random()*s.length)];return t}static escapeBase64Url(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class Z{constructor(e){this.rateLimits={},this.clientSettings={},e&&(this.clientSettings=e)}getRateLimits(){return this.rateLimits}saveRateLimit(e,t){this.rateLimits[e]=t}async send(e){var t,s,r,i,a;if(null===(t=this.clientSettings.plugins)||void 0===t?void 0:t.length){let t=await this.applyPreRequestConfigHooks(e);if(t)return t}let n=this.getHttpRequestArgs(e),o={method:n.method,headers:n.headers,timeout:e.timeout,agent:this.clientSettings.httpAgent},l=!1!==e.enableRateLimitSave;n.body&&Q.setBodyLengthHeader(o,n.body),(null===(s=this.clientSettings.plugins)||void 0===s?void 0:s.length)&&await this.applyPreRequestHooks(e,n,o);let u=new $({url:n.url,options:o,body:n.body,rateLimitSaver:l?this.saveRateLimit.bind(this,n.rawUrl):void 0,requestEventDebugHandler:e.requestEventDebugHandler,compression:null===(i=null!==(r=e.compression)&&void 0!==r?r:this.clientSettings.compression)||void 0===i||i,forceParseMode:e.forceParseMode}).makeRequest();(function(e){var t;if(!(null===(t=e.clientSettings.plugins)||void 0===t?void 0:t.length))return!1;for(let t of e.clientSettings.plugins)if(t.onRequestError||t.onResponseError)return!0;return!1})(this)&&(u=this.applyResponseErrorHooks(e,n,o,u));let d=await u;if(null===(a=this.clientSettings.plugins)||void 0===a?void 0:a.length){let t=await this.applyPostRequestHooks(e,n,o,d);if(t)return t.value}return d}sendStream(e){var t,s;this.clientSettings.plugins&&this.applyPreStreamRequestConfigHooks(e);let r=this.getHttpRequestArgs(e),i={method:r.method,headers:r.headers,agent:this.clientSettings.httpAgent},a=!1!==e.enableRateLimitSave,n=!1!==e.autoConnect;r.body&&Q.setBodyLengthHeader(i,r.body);let o=new W({url:r.url,options:i,body:r.body,rateLimitSaver:a?this.saveRateLimit.bind(this,r.rawUrl):void 0,payloadIsError:e.payloadIsError,compression:null===(s=null!==(t=e.compression)&&void 0!==t?t:this.clientSettings.compression)||void 0===s||s});return n?o.connect():o}initializeToken(e){if("string"==typeof e)this.bearerToken=e;else if("object"==typeof e&&"appKey"in e)this.consumerToken=e.appKey,this.consumerSecret=e.appSecret,e.accessToken&&e.accessSecret&&(this.accessToken=e.accessToken,this.accessSecret=e.accessSecret),this._oauth=this.buildOAuth();else if("object"==typeof e&&"username"in e){let t=encodeURIComponent(e.username)+":"+encodeURIComponent(e.password);this.basicToken=Buffer.from(t).toString("base64")}else"object"==typeof e&&"clientId"in e&&(this.clientId=e.clientId,this.clientSecret=e.clientSecret)}getActiveTokens(){return this.bearerToken?{type:"oauth2",bearerToken:this.bearerToken}:this.basicToken?{type:"basic",token:this.basicToken}:this.consumerSecret&&this._oauth?{type:"oauth-1.0a",appKey:this.consumerToken,appSecret:this.consumerSecret,accessToken:this.accessToken,accessSecret:this.accessSecret}:this.clientId?{type:"oauth2-user",clientId:this.clientId}:{type:"none"}}buildOAuth(){if(!this.consumerSecret||!this.consumerToken)throw Error("Invalid consumer tokens");return new Y({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(this.accessSecret&&this.accessToken)return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var e;return null!==(e=this.clientSettings.plugins)&&void 0!==e?e:[]}hasPlugins(){var e;return!!(null===(e=this.clientSettings.plugins)||void 0===e?void 0:e.length)}async applyPluginMethod(e,t){var s;let r;for(let i of this.getPlugins()){let a=await (null===(s=i[e])||void 0===s?void 0:s.call(i,t));a&&a instanceof y&&(r=a)}return r}writeAuthHeaders({headers:e,bodyInSignature:t,url:s,method:r,query:i,body:a}){if(e={...e},this.bearerToken)e.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)e.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)e.Authorization="Basic "+X.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let n=t?Q.mergeQueryAndBodyForOAuth(i,a):i,o=this._oauth.authorize({url:s.toString(),method:r,data:n},this.getOAuthAccessTokens());e={...e,...this._oauth.toHeader(o)}}return e}getUrlObjectFromUrlString(e){return e.startsWith("http")||(e="https://"+e),new URL(e)}getHttpRequestArgs({url:e,method:t,query:s={},body:r={},headers:i,forceBodyMode:a,enableAuth:n,params:o}){let l;t=t.toUpperCase(),(i=null!=i?i:{})["x-user-agent"]||(i["x-user-agent"]="Node.twitter-api-v2");let u=this.getUrlObjectFromUrlString(e),d=u.origin+u.pathname;o&&Q.applyRequestParametersToUrl(u,o);let c=Q.formatQueryToString(s);Q.moveUrlQueryParamsIntoObject(u,c),r instanceof Buffer||function(e){for(let t of Object.keys(e))void 0===e[t]&&delete e[t]}(r);let h=null!=a?a:Q.autoDetectBodyType(u);if(!1!==n){let e=Z.BODY_METHODS.has(t)&&"url"===h;i=this.writeAuthHeaders({headers:i,bodyInSignature:e,method:t,query:c,url:u,body:r})}return Z.BODY_METHODS.has(t)&&(l=Q.constructBodyParams(r,i,h)||void 0),Q.addQueryParamsToUrl(u,c),{rawUrl:d,url:u,method:t,headers:i,body:l}}async applyPreRequestConfigHooks(e){var t;let s=this.getUrlObjectFromUrlString(e.url);for(let r of this.getPlugins()){let i=await (null===(t=r.onBeforeRequestConfig)||void 0===t?void 0:t.call(r,{client:this,url:s,params:e}));if(i)return i}}applyPreStreamRequestConfigHooks(e){var t;let s=this.getUrlObjectFromUrlString(e.url);for(let r of this.getPlugins())null===(t=r.onBeforeStreamRequestConfig)||void 0===t||t.call(r,{client:this,url:s,params:e})}async applyPreRequestHooks(e,t,s){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s})}async applyPostRequestHooks(e,t,s,r){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,response:r})}applyResponseErrorHooks(e,t,s,r){return r.catch(V.bind(this,e,t,s))}}Z.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class ee{constructor(e,t={}){this._currentUser=null,this._currentUserV2=null,e instanceof ee?this._requestMaker=e._requestMaker:(this._requestMaker=new Z(t),this._requestMaker.initializeToken(e))}setPrefix(e){this._prefix=e}cloneWithPrefix(e){let t=this.constructor(this);return t.setPrefix(e),t}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(e){return this.getPlugins().find(t=>t instanceof e)}hasHitRateLimit(e){var t;return!this.isRateLimitStatusObsolete(e)&&(null===(t=this.getLastRateLimitStatus(e))||void 0===t?void 0:t.remaining)===0}isRateLimitStatusObsolete(e){let t=this.getLastRateLimitStatus(e);return void 0===t||1e3*t.reset<Date.now()}getLastRateLimitStatus(e){let t=e.match(/^https?:\/\//)?e:this._prefix+e;return this._requestMaker.getRateLimits()[t]}getCurrentUserObject(e=!1){return!e&&this._currentUser?this._currentUser.value?Promise.resolve(this._currentUser.value):this._currentUser.promise:(this._currentUser=E(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:a})),this._currentUser.promise)}getCurrentUserV2Object(e=!1){return!e&&this._currentUserV2?this._currentUserV2.value?Promise.resolve(this._currentUserV2.value):this._currentUserV2.promise:(this._currentUserV2=E(()=>this.get("users/me",void 0,{prefix:r})),this._currentUserV2.promise)}async get(e,t={},{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"GET",query:t,...i});return s?a:a.data}async delete(e,t={},{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"DELETE",query:t,...i});return s?a:a.data}async post(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"POST",body:t,...i});return s?a:a.data}async put(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"PUT",body:t,...i});return s?a:a.data}async patch(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"PATCH",body:t,...i});return s?a:a.data}getStream(e,t,{prefix:s=this._prefix,...r}={}){return this._requestMaker.sendStream({url:s?s+e:e,method:"GET",query:t,...r})}postStream(e,t,{prefix:s=this._prefix,...r}={}){return this._requestMaker.sendStream({url:s?s+e:e,method:"POST",body:t,...r})}}class et extends ee{constructor(e){if(!(e instanceof ee))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(e)}}class es extends c{constructor(){super(...arguments),this.hasFinishedFetch=!1}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.push(...s),this.hasFinishedFetch=0===s.length)}getNextQueryParams(e){let t=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(e),max_id:(t-BigInt(1)).toString()}}getPageLengthFromRequest(e){return e.data.length}isFetchLastOver(e){return!e.data.length}canFetchNextPage(e){return e.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class er extends es{constructor(){super(...arguments),this._endpoint="statuses/home_timeline.json"}}class ei extends es{constructor(){super(...arguments),this._endpoint="statuses/mentions_timeline.json"}}class ea extends es{constructor(){super(...arguments),this._endpoint="statuses/user_timeline.json"}}class en extends es{constructor(){super(...arguments),this._endpoint="lists/statuses.json"}}class eo extends es{constructor(){super(...arguments),this._endpoint="favorites/list.json"}}class el extends h{constructor(){super(...arguments),this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class eu extends h{constructor(){super(...arguments),this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class ed extends h{constructor(){super(...arguments),this._endpoint="followers/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ec extends h{constructor(){super(...arguments),this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class eh extends h{constructor(){super(...arguments),this._endpoint="friends/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ep extends h{constructor(){super(...arguments),this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class em extends c{constructor(){super(...arguments),this._endpoint="users/search.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&this._realData.push(...s)}getNextQueryParams(e){var t;let s=Number(null!==(t=this._queryParams.page)&&void 0!==t?t:"1");return{...this._queryParams,page:s+1,...e?{count:e}:{}}}getPageLengthFromRequest(e){return e.data.length}isFetchLastOver(e){return!e.data.length}canFetchNextPage(e){return e.length>0}getItemArray(){return this.users}get users(){return this._realData}}class eg extends h{constructor(){super(...arguments),this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class e_ extends eg{constructor(){super(...arguments),this._endpoint="friendships/outgoing.json"}}class ef extends h{refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.lists.push(...s.lists),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class ew extends ef{constructor(){super(...arguments),this._endpoint="lists/memberships.json"}}class ey extends ef{constructor(){super(...arguments),this._endpoint="lists/ownerships.json"}}class ev extends ef{constructor(){super(...arguments),this._endpoint="lists/subscriptions.json"}}class eb extends h{refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ek extends eb{constructor(){super(...arguments),this._endpoint="lists/members.json"}}class ex extends eb{constructor(){super(...arguments),this._endpoint="lists/subscribers.json"}}class eS extends et{constructor(){super(...arguments),this._prefix=a}singleTweet(e,t={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:e,...t})}tweets(e,t={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:e,...t})}oembedTweet(e,t={}){return this.get("oembed",{url:`https://x.com/i/statuses/${e}`,...t},{prefix:"https://publish.x.com/"})}async homeTimeline(e={}){let t={tweet_mode:"extended",...e},s=await this.get("statuses/home_timeline.json",t,{fullResponse:!0});return new er({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async mentionTimeline(e={}){let t={tweet_mode:"extended",...e},s=await this.get("statuses/mentions_timeline.json",t,{fullResponse:!0});return new ei({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userTimeline(e,t={}){let s={tweet_mode:"extended",user_id:e,...t},r=await this.get("statuses/user_timeline.json",s,{fullResponse:!0});return new ea({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async userTimelineByUsername(e,t={}){let s={tweet_mode:"extended",screen_name:e,...t},r=await this.get("statuses/user_timeline.json",s,{fullResponse:!0});return new ea({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async favoriteTimeline(e,t={}){let s={tweet_mode:"extended",user_id:e,...t},r=await this.get("favorites/list.json",s,{fullResponse:!0});return new eo({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async favoriteTimelineByUsername(e,t={}){let s={tweet_mode:"extended",screen_name:e,...t},r=await this.get("favorites/list.json",s,{fullResponse:!0});return new eo({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}user(e){return this.get("users/show.json",{tweet_mode:"extended",...e})}users(e){return this.get("users/lookup.json",{tweet_mode:"extended",...e})}verifyCredentials(e={}){return this.get("account/verify_credentials.json",e)}async listMutedUsers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("mutes/users/list.json",t,{fullResponse:!0});return new el({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listMutedUserIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("mutes/users/ids.json",t,{fullResponse:!0});return new eu({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFriendList(e={}){let t={...e},s=await this.get("friends/list.json",t,{fullResponse:!0});return new eh({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowerList(e={}){let t={...e},s=await this.get("followers/list.json",t,{fullResponse:!0});return new ed({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowerIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("followers/ids.json",t,{fullResponse:!0});return new ec({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowingIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("friends/ids.json",t,{fullResponse:!0});return new ep({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async searchUsers(e,t={}){let s={q:e,tweet_mode:"extended",page:1,...t},r=await this.get("users/search.json",s,{fullResponse:!0});return new em({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}friendship(e){return this.get("friendships/show.json",e)}friendships(e){return this.get("friendships/lookup.json",e)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(e={}){let t={stringify_ids:!0,...e},s=await this.get("friendships/incoming.json",t,{fullResponse:!0});return new eg({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async friendshipsOutgoing(e={}){let t={stringify_ids:!0,...e},s=await this.get("friendships/outgoing.json",t,{fullResponse:!0});return new e_({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(e){return this.get("users/profile_banner.json",e)}list(e){return this.get("lists/show.json",{tweet_mode:"extended",...e})}lists(e={}){return this.get("lists/list.json",{tweet_mode:"extended",...e})}async listMembers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/members.json",t,{fullResponse:!0});return new ek({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}listGetMember(e){return this.get("lists/members/show.json",{tweet_mode:"extended",...e})}async listMemberships(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/memberships.json",t,{fullResponse:!0});return new ew({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listOwnerships(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/ownerships.json",t,{fullResponse:!0});return new ey({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listStatuses(e){let t={tweet_mode:"extended",...e},s=await this.get("lists/statuses.json",t,{fullResponse:!0});return new en({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listSubscribers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/subscribers.json",t,{fullResponse:!0});return new ex({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}listGetSubscriber(e){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...e})}async listSubscriptions(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/subscriptions.json",t,{fullResponse:!0});return new ev({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}mediaInfo(e){return this.get("media/upload.json",{command:"STATUS",media_id:e},{prefix:n})}filterStream({autoConnect:e,...t}={}){let s={};for(let[e,r]of Object.entries(t))"follow"===e||"track"===e?s[e]=r.toString():"locations"===e?s.locations=A(r).map(e=>`${e.lng},${e.lat}`).join(","):s[e]=r;return this.stream.postStream("statuses/filter.json",s,{autoConnect:e})}sampleStream({autoConnect:e,...t}={}){return this.stream.getStream("statuses/sample.json",t,{autoConnect:e})}get stream(){let e=new eq(this);return e.setPrefix("https://stream.x.com/1.1/"),e}trendsByPlace(e,t={}){return this.get("trends/place.json",{id:e,...t})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(e,t){return this.get("trends/closest.json",{lat:e,long:t})}geoPlace(e){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:e}})}geoSearch(e){return this.get("geo/search.json",e)}geoReverseGeoCode(e){return this.get("geo/reverse_geocode.json",e)}rateLimitStatuses(...e){return this.get("application/rate_limit_status.json",{resources:e})}supportedLanguages(){return this.get("help/languages.json")}}async function eR(e){let t=await eT(e);return"number"==typeof t?new Promise((e,s)=>{D.readFile(t,(t,r)=>{if(t)return s(t);e(r)})}):t instanceof Buffer?t:t.readFile()}function eT(e){if("string"==typeof e)return D.promises.open(e,"r");if("number"==typeof e||"object"==typeof e&&!(e instanceof Buffer)||e instanceof Buffer)return e;throw Error("Given file is not valid, please check its type.")}async function eD(e){return"number"==typeof e?(await new Promise((t,s)=>{D.fstat(e,(e,r)=>{e&&s(e),t(r)})})).size:e instanceof Buffer?e.length:(await e.stat()).size}function eP(e){return new Promise(t=>setTimeout(t,1e3*e))}async function eE(e,t,s=0,r){let i;if(e instanceof Buffer){let r=e.slice(s,s+t);return[r,r.length]}if(!r)throw Error("Well, we will need a buffer to store file content.");return i="number"==typeof e?await new Promise((i,a)=>{D.read(e,r,0,t,s,(e,t)=>{e&&a(e),i(t)})}):(await e.read(r,0,t,s)).bytesRead,[r,i]}let eA="media/upload.json";class eL extends eS{constructor(){super(...arguments),this._prefix=a}get readOnly(){return this}tweet(e,t={}){let s={status:e,tweet_mode:"extended",...t};return this.post("statuses/update.json",s)}async quote(e,t,s={}){return this.tweet(e,{...s,attachment_url:"https://x.com/i/statuses/"+t})}async tweetThread(e){let t=[];for(let s of e){let e=t.length?t[t.length-1]:null,r={..."string"==typeof s?{status:s}:s},i=e?e.id_str:r.in_reply_to_status_id,a=r.status;i?t.push(await this.reply(a,i,r)):t.push(await this.tweet(a,r))}return t}reply(e,t,s={}){return this.tweet(e,{auto_populate_reply_metadata:!0,in_reply_to_status_id:t,...s})}deleteTweet(e){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:e}})}reportUserAsSpam(e){return this.post("users/report_spam.json",{tweet_mode:"extended",...e})}updateFriendship(e){return this.post("friendships/update.json",e)}createFriendship(e){return this.post("friendships/create.json",e)}destroyFriendship(e){return this.post("friendships/destroy.json",e)}updateAccountSettings(e){return this.post("account/settings.json",e)}updateAccountProfile(e){return this.post("account/update_profile.json",e)}async updateAccountProfileBanner(e,t={}){let s={banner:await eR(e),...t};return this.post("account/update_profile_banner.json",s,{forceBodyMode:"form-data"})}async updateAccountProfileImage(e,t={}){let s={tweet_mode:"extended",image:await eR(e),...t};return this.post("account/update_profile_image.json",s,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(e){return this.post("lists/create.json",{tweet_mode:"extended",...e})}updateList(e){return this.post("lists/update.json",{tweet_mode:"extended",...e})}removeList(e){return this.post("lists/destroy.json",{tweet_mode:"extended",...e})}addListMembers(e){let t=e.user_id&&I(e.user_id)||e.screen_name&&I(e.screen_name);return this.post(t?"lists/members/create_all.json":"lists/members/create.json",e)}removeListMembers(e){let t=e.user_id&&I(e.user_id)||e.screen_name&&I(e.screen_name);return this.post(t?"lists/members/destroy_all.json":"lists/members/destroy.json",e)}subscribeToList(e){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...e})}unsubscribeOfList(e){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...e})}createMediaMetadata(e,t){return this.post("media/metadata/create.json",{media_id:e,...t},{prefix:n,forceBodyMode:"json"})}createMediaSubtitles(e,t){return this.post("media/subtitles/create.json",{media_id:e,media_category:"TweetVideo",subtitle_info:{subtitles:t}},{prefix:n,forceBodyMode:"json"})}deleteMediaSubtitles(e,...t){return this.post("media/subtitles/delete.json",{media_id:e,media_category:"TweetVideo",subtitle_info:{subtitles:t.map(e=>({language_code:e}))}},{prefix:n,forceBodyMode:"json"})}async uploadMedia(e,t={},s=!1){var r;let i=null!==(r=t.chunkLength)&&void 0!==r?r:1048576,{fileHandle:a,mediaCategory:o,fileSize:l,mimeType:u}=await this.getUploadMediaRequirements(e,t);try{let e=await this.post(eA,{command:"INIT",total_bytes:l,media_type:u,media_category:o,additional_owners:t.additionalOwners,shared:!!t.shared||void 0},{prefix:n});await this.mediaChunkedUpload(a,i,e.media_id_string,t.maxConcurrentUploads);let r=await this.post(eA,{command:"FINALIZE",media_id:e.media_id_string},{prefix:n});if(r.processing_info&&"succeeded"!==r.processing_info.state&&await this.awaitForMediaProcessingCompletion(r),s)return r;return r.media_id_string}finally{"number"==typeof e?D.close(e,()=>{}):"object"!=typeof a||a instanceof Buffer||a.close()}}async awaitForMediaProcessingCompletion(e){for(var t;;){let{processing_info:s}=e=await this.mediaInfo(e.media_id_string);if(!s||"succeeded"===s.state)return;if(null===(t=s.error)||void 0===t?void 0:t.code){let{name:e,message:t}=s.error;throw Error(`Failed to process media: ${e} - ${t}.`)}if("failed"===s.state)throw Error("Failed to process the media.");s.check_after_secs?await eP(s.check_after_secs):await eP(5)}}async getUploadMediaRequirements(e,{mimeType:t,type:s,target:r,longVideo:i}={}){let a;try{let o;a=await eT(e);let l=function(e,t,s){if("string"==typeof s)return s;if("string"==typeof e&&!t)return e.endsWith(".jpeg")||e.endsWith(".jpg")?v.Jpeg:e.endsWith(".png")?v.Png:e.endsWith(".webp")?v.Webp:e.endsWith(".gif")?v.Gif:e.endsWith(".mpeg4")||e.endsWith(".mp4")?v.Mp4:e.endsWith(".mov")||e.endsWith(".mov")?v.Mov:e.endsWith(".srt")?v.Srt:(j({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"}),v.Jpeg);if("string"==typeof t)return(j({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"}),"gif"===t)?v.Gif:"jpg"===t?v.Jpeg:"png"===t?v.Png:"webp"===t?v.Webp:"srt"===t?v.Srt:"mp4"===t||"longmp4"===t?v.Mp4:"mov"===t?v.Mov:t;throw Error("You must specify type if file is a file handle or Buffer.")}(e,s,t);if(l!==v.Mp4||(t||s||"dm"===r)&&!i){var n;n=null!=r?r:"tweet",o=l===v.Mp4||l===v.Mov?"tweet"===n?"TweetVideo":"DmVideo":l===v.Gif?"tweet"===n?"TweetGif":"DmGif":l===v.Srt?"Subtitles":"tweet"===n?"TweetImage":"DmImage"}else o="amplify_video";return{fileHandle:a,mediaCategory:o,fileSize:await eD(a),mimeType:l}}catch(t){throw"number"==typeof e?D.close(e,()=>{}):"object"!=typeof a||a instanceof Buffer||a.close(),t}}async mediaChunkedUpload(e,t,s,r=3){let i,a,o=0;if(r<1)throw RangeError("Bad maxConcurrentUploads parameter.");let l=e instanceof Buffer?void 0:Buffer.alloc(t),u=0;[i,a]=await eE(e,t,u,l),u+=a;let d=new Set;for(;a;){let c=i.slice(0,a);if(c.length){let e=this.post(eA,{command:"APPEND",media_id:s,segment_index:o,media:c},{prefix:n});d.add(e),e.then(()=>{d.delete(e)}),o++}d.size>=r&&await Promise.race(d),[i,a]=await eE(e,t,u,l),u+=a}await Promise.all([...d])}}class eI extends eL{constructor(){super(...arguments),this._prefix=a}get readWrite(){return this}sendDm({recipient_id:e,custom_profile_id:t,...s}){let r={event:{type:b.Create,[b.Create]:{target:{recipient_id:e},message_data:s}}};return t&&(r.event[b.Create].custom_profile_id=t),this.post("direct_messages/events/new.json",r,{forceBodyMode:"json"})}getDmEvent(e){return this.get("direct_messages/events/show.json",{id:e})}deleteDm(e){return this.delete("direct_messages/events/destroy.json",{id:e})}async listDmEvents(e={}){let t={...e},s=await this.get("direct_messages/events/list.json",t,{fullResponse:!0});return new p({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}newWelcomeDm(e,t){let s={[b.WelcomeCreate]:{name:e,message_data:t}};return this.post("direct_messages/welcome_messages/new.json",s,{forceBodyMode:"json"})}getWelcomeDm(e){return this.get("direct_messages/welcome_messages/show.json",{id:e})}deleteWelcomeDm(e){return this.delete("direct_messages/welcome_messages/destroy.json",{id:e})}updateWelcomeDm(e,t){return this.put("direct_messages/welcome_messages/update.json",{message_data:t},{forceBodyMode:"json",query:{id:e}})}async listWelcomeDms(e={}){let t={...e},s=await this.get("direct_messages/welcome_messages/list.json",t,{fullResponse:!0});return new m({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}newWelcomeDmRule(e){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:e}},{forceBodyMode:"json"})}getWelcomeDmRule(e){return this.get("direct_messages/welcome_messages/rules/show.json",{id:e})}deleteWelcomeDmRule(e){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:e})}async listWelcomeDmRules(e={}){let t={...e};return this.get("direct_messages/welcome_messages/rules/list.json",t)}async setWelcomeDm(e,t=!0){var s;let r=await this.listWelcomeDmRules();if(null===(s=r.welcome_message_rules)||void 0===s?void 0:s.length)for(let e of r.welcome_message_rules)await this.deleteWelcomeDmRule(e.id),t&&await this.deleteWelcomeDm(e.welcome_message_id);return this.newWelcomeDmRule(e)}markDmAsRead(e,t){return this.post("direct_messages/mark_read.json",{last_read_event_id:e,recipient_id:t},{forceBodyMode:"url"})}indicateDmTyping(e){return this.post("direct_messages/indicate_typing.json",{recipient_id:e},{forceBodyMode:"url"})}async downloadDmImage(e){if("string"!=typeof e){let t=e[b.Create].message_data.attachment;if(!t)throw Error("The given direct message doesn't contain any attachment");e=t.media.media_url_https}let t=await this.get(e,void 0,{forceParseMode:"buffer",prefix:""});if(!t.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return t}}let eq=eI;class ej{constructor(e){this.result=e}get tweets(){return ej.tweets(this.result)}static tweets(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.tweets)&&void 0!==s?s:[]}tweetById(e){return ej.tweetById(this.result,e)}static tweetById(e,t){return this.tweets(e).find(e=>e.id===t)}retweet(e){return ej.retweet(this.result,e)}static retweet(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"retweeted"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}quote(e){return ej.quote(this.result,e)}static quote(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"quoted"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}repliedTo(e){return ej.repliedTo(this.result,e)}static repliedTo(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"replied_to"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}author(e){return ej.author(this.result,e)}static author(e,t){let s=t.author_id;return s?this.users(e).find(e=>e.id===s):void 0}repliedToAuthor(e){return ej.repliedToAuthor(this.result,e)}static repliedToAuthor(e,t){let s=t.in_reply_to_user_id;return s?this.users(e).find(e=>e.id===s):void 0}get users(){return ej.users(this.result)}static users(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.users)&&void 0!==s?s:[]}userById(e){return ej.userById(this.result,e)}static userById(e,t){return this.users(e).find(e=>e.id===t)}pinnedTweet(e){return ej.pinnedTweet(this.result,e)}static pinnedTweet(e,t){return t.pinned_tweet_id?this.tweets(e).find(e=>e.id===t.pinned_tweet_id):void 0}get media(){return ej.media(this.result)}static media(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.media)&&void 0!==s?s:[]}medias(e){return ej.medias(this.result,e)}static medias(e,t){var s,r;let i=null!==(r=null===(s=t.attachments)||void 0===s?void 0:s.media_keys)&&void 0!==r?r:[];return this.media(e).filter(e=>i.includes(e.media_key))}get polls(){return ej.polls(this.result)}static polls(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.polls)&&void 0!==s?s:[]}poll(e){return ej.poll(this.result,e)}static poll(e,t){var s,r;let i=null!==(r=null===(s=t.attachments)||void 0===s?void 0:s.poll_ids)&&void 0!==r?r:[];if(i.length){let t=i[0];return this.polls(e).find(e=>e.id===t)}}get places(){return ej.places(this.result)}static places(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.places)&&void 0!==s?s:[]}place(e){return ej.place(this.result,e)}static place(e,t){var s;let r=null===(s=t.geo)||void 0===s?void 0:s.place_id;return r?this.places(e).find(e=>e.id===r):void 0}listOwner(e){return ej.listOwner(this.result,e)}static listOwner(e,t){let s=t.owner_id;return s?this.users(e).find(e=>e.id===s):void 0}spaceCreator(e){return ej.spaceCreator(this.result,e)}static spaceCreator(e,t){let s=t.creator_id;return s?this.users(e).find(e=>e.id===s):void 0}spaceHosts(e){return ej.spaceHosts(this.result,e)}static spaceHosts(e,t){var s;let r=null!==(s=t.host_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}spaceSpeakers(e){return ej.spaceSpeakers(this.result,e)}static spaceSpeakers(e,t){var s;let r=null!==(s=t.speaker_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}spaceInvitedUsers(e){return ej.spaceInvitedUsers(this.result,e)}static spaceInvitedUsers(e,t){var s;let r=null!==(s=t.invited_user_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}}class eC extends d{updateIncludes(e){if(e.errors&&(this._realData.errors||(this._realData.errors=[]),this._realData.errors=[...this._realData.errors,...e.errors]),!e.includes)return;this._realData.includes||(this._realData.includes={});let t=this._realData.includes;for(let[s,r]of Object.entries(e.includes))t[s]||(t[s]=[]),t[s]=[...t[s],...r]}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 e;return(null===(e=this._realData)||void 0===e?void 0:e.includes)?this._includesInstance?this._includesInstance:this._includesInstance=new ej(this._realData):new ej(this._realData)}get errors(){var e;return null!==(e=this._realData.errors)&&void 0!==e?e:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class eM extends eC{refreshInstanceFromResult(e,t){var s;let r=e.data,i=null!==(s=r.data)&&void 0!==s?s:[];this._rateLimit=e.rateLimit,this._realData.data||(this._realData.data=[]),t?(this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.next_token=r.meta.next_token,this._realData.data.push(...i)):(this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.previous_token=r.meta.previous_token,this._realData.data.unshift(...i)),this.updateIncludes(r)}getNextQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(e){var t,s;return null!==(s=null===(t=e.data.data)||void 0===t?void 0:t.length)&&void 0!==s?s:0}isFetchLastOver(e){var t;return!(null===(t=e.data.data)||void 0===t?void 0:t.length)||!this.canFetchNextPage(e.data)}canFetchNextPage(e){var t;return!!(null===(t=e.meta)||void 0===t?void 0:t.next_token)}}class eO extends eC{refreshInstanceFromResult(e,t){var s;let r=e.data,i=null!==(s=r.data)&&void 0!==s?s:[];this._rateLimit=e.rateLimit,this._realData.data||(this._realData.data=[]),t?(this._realData.meta.oldest_id=r.meta.oldest_id,this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.next_token=r.meta.next_token,this._realData.data.push(...i)):(this._realData.meta.newest_id=r.meta.newest_id,this._realData.meta.result_count+=r.meta.result_count,this._realData.data.unshift(...i)),this.updateIncludes(r)}getNextQueryParams(e){this.assertUsable();let t={...this.injectQueryParams(e)};return this._realData.meta.next_token?t.next_token=this._realData.meta.next_token:(t.start_time&&(t.since_id=this.dateStringToSnowflakeId(t.start_time),delete t.start_time),t.end_time&&delete t.end_time,t.until_id=this._realData.meta.oldest_id),t}getPreviousQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(e){var t,s;return null!==(s=null===(t=e.data.data)||void 0===t?void 0:t.length)&&void 0!==s?s:0}isFetchLastOver(e){var t;return!(null===(t=e.data.data)||void 0===t?void 0:t.length)||!this.canFetchNextPage(e.data)}canFetchNextPage(e){return!!e.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(e){let t=BigInt("1288834974657"),s=new Date(e);if(isNaN(s.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(s.valueOf())-t<<BigInt("22")).toString()}get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class e$ extends eM{refreshInstanceFromResult(e,t){super.refreshInstanceFromResult(e,t);let s=e.data;t?this._realData.meta.oldest_id=s.meta.oldest_id:this._realData.meta.newest_id=s.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eF extends eO{constructor(){super(...arguments),this._endpoint="tweets/search/recent"}}class eN extends eO{constructor(){super(...arguments),this._endpoint="tweets/search/all"}}class eU extends e${constructor(){super(...arguments),this._endpoint="tweets/:id/quote_tweets"}}class eB extends e${constructor(){super(...arguments),this._endpoint="users/:id/timelines/reverse_chronological"}}class eH extends e${constructor(){super(...arguments),this._endpoint="users/:id/tweets"}}class eW extends e${constructor(){super(...arguments),this._endpoint="users/:id/mentions"}}class eV extends e${constructor(){super(...arguments),this._endpoint="users/:id/bookmarks"}}class eK extends eM{get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class eY extends eK{constructor(){super(...arguments),this._endpoint="users/:id/liked_tweets"}}class ez extends eK{constructor(){super(...arguments),this._endpoint="lists/:id/tweets"}}class eJ extends eM{getItemArray(){return this.users}get users(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eG extends eJ{constructor(){super(...arguments),this._endpoint="users/:id/blocking"}}class eQ extends eJ{constructor(){super(...arguments),this._endpoint="users/:id/muting"}}class eX extends eJ{constructor(){super(...arguments),this._endpoint="users/:id/followers"}}class eZ extends eJ{constructor(){super(...arguments),this._endpoint="users/:id/following"}}class e0 extends eJ{constructor(){super(...arguments),this._endpoint="lists/:id/members"}}class e1 extends eJ{constructor(){super(...arguments),this._endpoint="lists/:id/followers"}}class e2 extends eJ{constructor(){super(...arguments),this._endpoint="tweets/:id/liking_users"}}class e4 extends eJ{constructor(){super(...arguments),this._endpoint="tweets/:id/retweeted_by"}}class e8 extends eM{getItemArray(){return this.lists}get lists(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class e5 extends e8{constructor(){super(...arguments),this._endpoint="users/:id/owned_lists"}}class e3 extends e8{constructor(){super(...arguments),this._endpoint="users/:id/list_memberships"}}class e7 extends e8{constructor(){super(...arguments),this._endpoint="users/:id/followed_lists"}}class e6 extends et{constructor(){super(...arguments),this._prefix=i}}class e9 extends eM{getItemArray(){return this.events}get events(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class te extends e9{constructor(){super(...arguments),this._endpoint="dm_events"}}class tt extends e9{constructor(){super(...arguments),this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class ts extends e9{constructor(){super(...arguments),this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class tr extends et{constructor(){super(...arguments),this._prefix=r}get labs(){return this._labs?this._labs:this._labs=new e6(this)}async search(e,t={}){let s="string"==typeof e?{...t,query:e}:{...e},r=await this.get("tweets/search/recent",s,{fullResponse:!0});return new eF({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async searchAll(e,t={}){let s={...t,query:e},r=await this.get("tweets/search/all",s,{fullResponse:!0});return new eN({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}singleTweet(e,t={}){return this.get("tweets/:id",t,{params:{id:e}})}tweets(e,t={}){return this.get("tweets",{ids:e,...t})}tweetCountRecent(e,t={}){return this.get("tweets/counts/recent",{query:e,...t})}tweetCountAll(e,t={}){return this.get("tweets/counts/all",{query:e,...t})}async tweetRetweetedBy(e,t={}){let{asPaginator:s,...r}=t,i=await this.get("tweets/:id/retweeted_by",r,{fullResponse:!0,params:{id:e}});return s?new e4({realData:i.data,rateLimit:i.rateLimit,instance:this,queryParams:r,sharedParams:{id:e}}):i.data}async tweetLikedBy(e,t={}){let{asPaginator:s,...r}=t,i=await this.get("tweets/:id/liking_users",r,{fullResponse:!0,params:{id:e}});return s?new e2({realData:i.data,rateLimit:i.rateLimit,instance:this,queryParams:r,sharedParams:{id:e}}):i.data}async homeTimeline(e={}){let t=await this.getCurrentUserV2Object(),s=await this.get("users/:id/timelines/reverse_chronological",e,{fullResponse:!0,params:{id:t.data.id}});return new eB({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:e,sharedParams:{id:t.data.id}})}async userTimeline(e,t={}){let s=await this.get("users/:id/tweets",t,{fullResponse:!0,params:{id:e}});return new eH({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async userMentionTimeline(e,t={}){let s=await this.get("users/:id/mentions",t,{fullResponse:!0,params:{id:e}});return new eW({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async quotes(e,t={}){let s=await this.get("tweets/:id/quote_tweets",t,{fullResponse:!0,params:{id:e}});return new eU({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async bookmarks(e={}){let t=await this.getCurrentUserV2Object(),s=await this.get("users/:id/bookmarks",e,{fullResponse:!0,params:{id:t.data.id}});return new eV({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:e,sharedParams:{id:t.data.id}})}me(e={}){return this.get("users/me",e)}user(e,t={}){return this.get("users/:id",t,{params:{id:e}})}users(e,t={}){let s=Array.isArray(e)?e.join(","):e;return this.get("users",{...t,ids:s})}userByUsername(e,t={}){return this.get("users/by/username/:username",t,{params:{username:e}})}usersByUsernames(e,t={}){return e=Array.isArray(e)?e.join(","):e,this.get("users/by",{...t,usernames:e})}async followers(e,t={}){let{asPaginator:s,...r}=t,i={id:e};if(!s)return this.get("users/:id/followers",r,{params:i});let a=await this.get("users/:id/followers",r,{fullResponse:!0,params:i});return new eX({realData:a.data,rateLimit:a.rateLimit,instance:this,queryParams:r,sharedParams:i})}async following(e,t={}){let{asPaginator:s,...r}=t,i={id:e};if(!s)return this.get("users/:id/following",r,{params:i});let a=await this.get("users/:id/following",r,{fullResponse:!0,params:i});return new eZ({realData:a.data,rateLimit:a.rateLimit,instance:this,queryParams:r,sharedParams:i})}async userLikedTweets(e,t={}){let s={id:e},r=await this.get("users/:id/liked_tweets",t,{fullResponse:!0,params:s});return new eY({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async userBlockingUsers(e,t={}){let s={id:e},r=await this.get("users/:id/blocking",t,{fullResponse:!0,params:s});return new eG({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async userMutingUsers(e,t={}){let s={id:e},r=await this.get("users/:id/muting",t,{fullResponse:!0,params:s});return new eQ({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}list(e,t={}){return this.get("lists/:id",t,{params:{id:e}})}async listsOwned(e,t={}){let s={id:e},r=await this.get("users/:id/owned_lists",t,{fullResponse:!0,params:s});return new e5({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listMemberships(e,t={}){let s={id:e},r=await this.get("users/:id/list_memberships",t,{fullResponse:!0,params:s});return new e3({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listFollowed(e,t={}){let s={id:e},r=await this.get("users/:id/followed_lists",t,{fullResponse:!0,params:s});return new e7({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listTweets(e,t={}){let s={id:e},r=await this.get("lists/:id/tweets",t,{fullResponse:!0,params:s});return new ez({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listMembers(e,t={}){let s={id:e},r=await this.get("lists/:id/members",t,{fullResponse:!0,params:s});return new e0({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listFollowers(e,t={}){let s={id:e},r=await this.get("lists/:id/followers",t,{fullResponse:!0,params:s});return new e1({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listDmEvents(e={}){let t=await this.get("dm_events",e,{fullResponse:!0});return new te({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...e}})}async listDmEventsWithParticipant(e,t={}){let s={participant_id:e},r=await this.get("dm_conversations/with/:participant_id/dm_events",t,{fullResponse:!0,params:s});return new tt({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listDmEventsOfConversation(e,t={}){let s={dm_conversation_id:e},r=await this.get("dm_conversations/:dm_conversation_id/dm_events",t,{fullResponse:!0,params:s});return new ts({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}space(e,t={}){return this.get("spaces/:id",t,{params:{id:e}})}spaces(e,t={}){return this.get("spaces",{ids:e,...t})}spacesByCreators(e,t={}){return this.get("spaces/by/creator_ids",{user_ids:e,...t})}searchSpaces(e){return this.get("spaces/search",e)}spaceBuyers(e,t={}){return this.get("spaces/:id/buyers",t,{params:{id:e}})}spaceTweets(e,t={}){return this.get("spaces/:id/tweets",t,{params:{id:e}})}searchStream({autoConnect:e,...t}={}){return this.getStream("tweets/search/stream",t,{payloadIsError:L,autoConnect:e})}streamRules(e={}){return this.get("tweets/search/stream/rules",e)}updateStreamRules(e,t={}){return this.post("tweets/search/stream/rules",e,{query:t})}sampleStream({autoConnect:e,...t}={}){return this.getStream("tweets/sample/stream",t,{payloadIsError:L,autoConnect:e})}sample10Stream({autoConnect:e,...t}={}){return this.getStream("tweets/sample10/stream",t,{payloadIsError:L,autoConnect:e})}complianceJobs(e){return this.get("compliance/jobs",e)}complianceJob(e){return this.get("compliance/jobs/:id",void 0,{params:{id:e}})}async sendComplianceJob(e){let t=await this.post("compliance/jobs",{type:e.type,name:e.name}),s=e.ids instanceof Buffer?e.ids:Buffer.from(e.ids.join("\n"));return await this.put(t.data.upload_url,s,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),t}async complianceJobResult(e){let t=e;for(;"complete"!==t.status;){if("expired"===t.status||"failed"===t.status)throw Error("Job failed to be completed.");await new Promise(e=>setTimeout(e,3500)),t=(await this.complianceJob(e.id)).data}return(await this.get(e.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split("\n").filter(e=>e).map(e=>JSON.parse(e))}async usage(e={}){return this.get("usage/tweets",e)}community(e,t={}){return this.get("communities/:id",t,{params:{id:e}})}searchCommunities(e,t={}){return this.get("communities/search",{query:e,...t})}}class ti extends e6{constructor(){super(...arguments),this._prefix=i}get readOnly(){return this}}class ta extends tr{constructor(){super(...arguments),this._prefix=r}get readOnly(){return this}get labs(){return this._labs?this._labs:this._labs=new ti(this)}hideReply(e,t){return this.put("tweets/:id/hidden",{hidden:t},{params:{id:e}})}like(e,t){return this.post("users/:id/likes",{tweet_id:t},{params:{id:e}})}unlike(e,t){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:e,tweet_id:t}})}retweet(e,t){return this.post("users/:id/retweets",{tweet_id:t},{params:{id:e}})}unretweet(e,t){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:e,tweet_id:t}})}tweet(e,t={}){return t="object"==typeof e?e:{text:e,...t},this.post("tweets",t)}async uploadMedia(e,t,s=1048576){let r=t.media_category;!t.media_category&&(t.media_type.includes("gif")?r="tweet_gif":t.media_type.includes("image")?r="tweet_image":t.media_type.includes("video")&&(r="tweet_video"));let i={additional_owners:t.additional_owners,media_type:t.media_type,total_bytes:e.length,media_category:r},a=(await this.post("media/upload/initialize",i)).data.id,n=Math.ceil(e.length/s),o=new Uint8Array(e);for(let t=0;t<n;t++){let r=t*s,i=Math.min(r+s,e.length),n=o.slice(r,i),l={segment_index:t,media:Buffer.from(n)};await this.post(`media/upload/${a}/append`,l,{forceBodyMode:"form-data"})}return(await this.post(`media/upload/${a}/finalize`)).data.processing_info&&await this.waitForMediaProcessing(a),a}async waitForMediaProcessing(e){var t;let s=(await this.get("media/upload",{command:"STATUS",media_id:e})).data.processing_info;if(s)switch(s.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${null===(t=s.error)||void 0===t?void 0:t.message}`);case"pending":case"in_progress":{let t=null==s?void 0:s.check_after_secs;t&&t>0&&(await new Promise(e=>setTimeout(e,1e3*t)),await this.waitForMediaProcessing(e))}}}createMediaMetadata(e,t){return this.post("media/metadata",{id:e,metadata:t})}reply(e,t,s={}){var r;let i={in_reply_to_tweet_id:t,...null!==(r=s.reply)&&void 0!==r?r:{}};return this.post("tweets",{text:e,...s,reply:i})}quote(e,t,s={}){return this.tweet(e,{...s,quote_tweet_id:t})}async tweetThread(e){var t,s;let r=[];for(let i of e){let e=r.length?r[r.length-1]:null,a={..."string"==typeof i?{text:i}:i},n=e?e.data.id:null===(t=a.reply)||void 0===t?void 0:t.in_reply_to_tweet_id,o=null!==(s=a.text)&&void 0!==s?s:"";n?r.push(await this.reply(o,n,a)):r.push(await this.tweet(o,a))}return r}deleteTweet(e){return this.delete("tweets/:id",void 0,{params:{id:e}})}async bookmark(e){let t=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:e},{params:{id:t.data.id}})}async deleteBookmark(e){let t=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:t.data.id,tweet_id:e}})}follow(e,t){return this.post("users/:id/following",{target_user_id:t},{params:{id:e}})}unfollow(e,t){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}block(e,t){return this.post("users/:id/blocking",{target_user_id:t},{params:{id:e}})}unblock(e,t){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}mute(e,t){return this.post("users/:id/muting",{target_user_id:t},{params:{id:e}})}unmute(e,t){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}createList(e){return this.post("lists",e)}updateList(e,t={}){return this.put("lists/:id",t,{params:{id:e}})}removeList(e){return this.delete("lists/:id",void 0,{params:{id:e}})}addListMember(e,t){return this.post("lists/:id/members",{user_id:t},{params:{id:e}})}removeListMember(e,t){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:e,user_id:t}})}subscribeToList(e,t){return this.post("users/:id/followed_lists",{list_id:t},{params:{id:e}})}unsubscribeOfList(e,t){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:e,list_id:t}})}pinList(e,t){return this.post("users/:id/pinned_lists",{list_id:t},{params:{id:e}})}unpinList(e,t){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:e,list_id:t}})}sendDmInConversation(e,t){return this.post("dm_conversations/:dm_conversation_id/messages",t,{params:{dm_conversation_id:e}})}sendDmToParticipant(e,t){return this.post("dm_conversations/with/:participant_id/messages",t,{params:{participant_id:e}})}createDmConversation(e){return this.post("dm_conversations",e)}}class tn extends ti{constructor(){super(...arguments),this._prefix=i}get readWrite(){return this}}class to extends ta{constructor(){super(...arguments),this._prefix=r}get readWrite(){return this}get labs(){return this._labs?this._labs:this._labs=new tn(this)}}class tl extends ee{get v1(){return this._v1?this._v1:this._v1=new eS(this)}get v2(){return this._v2?this._v2:this._v2=new tr(this)}async currentUser(e=!1){return await this.getCurrentUserObject(e)}async currentUserV2(e=!1){return await this.getCurrentUserV2Object(e)}search(e,t){return this.v2.search(e,t)}async generateAuthLink(e="oob",{authAccessType:t,linkMode:s="authenticate",forceLogin:r,screenName:i}={}){let a=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:e,x_auth_access_type:t}),n=`https://api.x.com/oauth/${s}?oauth_token=${encodeURIComponent(a.oauth_token)}`;return void 0!==r&&(n+=`&force_login=${encodeURIComponent(r)}`),void 0!==i&&(n+=`&screen_name=${encodeURIComponent(i)}`),this._requestMaker.hasPlugins()&&this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:n,oauthResult:a}),{url:n,...a}}async login(e){let t=this.getActiveTokens();if("oauth-1.0a"!==t.type)throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let s=await this.post("https://api.x.com/oauth/access_token",{oauth_token:t.accessToken,oauth_verifier:e}),r=new this.constructor({appKey:t.appKey,appSecret:t.appSecret,accessToken:s.oauth_token,accessSecret:s.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:s.oauth_token,accessSecret:s.oauth_token_secret,userId:s.user_id,screenName:s.screen_name,client:r}}async appLogin(){let e=this.getActiveTokens();if("oauth-1.0a"!==e.type)throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let t=new this.constructor({username:e.appKey,password:e.appSecret},this._requestMaker.clientSettings),s=await t.post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor(s.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(e,t={}){var s,r;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 i=null!==(s=t.state)&&void 0!==s?s:X.generateRandomString(32),a=X.getCodeVerifier(),n=X.getCodeChallengeFromVerifier(a),o=null!==(r=t.scope)&&void 0!==r?r:"",l=Array.isArray(o)?o.join(" "):o,u=new URL("https://x.com/i/oauth2/authorize"),d={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:e,state:i,code_challenge:n,code_challenge_method:"s256",scope:l};Q.addQueryParamsToUrl(u,d);let c={url:u.toString(),state:i,codeVerifier:a,codeChallenge:n};return this._requestMaker.hasPlugins()&&this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:c,redirectUri:e}),c}async loginWithOAuth2({code:e,codeVerifier:t,redirectUri:s}){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 r=await this.post("https://api.x.com/2/oauth2/token",{code:e,code_verifier:t,redirect_uri:s,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(r)}async refreshOAuth2Token(e){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let t=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:e,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(t)}async revokeOAuth2Token(e,t="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:e,token_type_hint:t})}parseOAuth2AccessTokenResult(e){let t=new this.constructor(e.access_token,this._requestMaker.clientSettings),s=e.scope.split(" ").filter(e=>e);return{client:t,expiresIn:e.expires_in,accessToken:e.access_token,scope:s,refreshToken:e.refresh_token}}}class tu extends tl{get v1(){return this._v1?this._v1:this._v1=new eL(this)}get v2(){return this._v2?this._v2:this._v2=new ta(this)}get readOnly(){return this}}class td extends et{constructor(){super(...arguments),this._prefix=o}}class tc extends td{constructor(){super(...arguments),this._prefix=o}get readOnly(){return this}}class th extends et{constructor(){super(...arguments),this._prefix=l}}class tp extends th{constructor(){super(...arguments),this._prefix=l}get readOnly(){return this}}class tm extends tp{constructor(){super(...arguments),this._prefix=l}get readWrite(){return this}}class tg extends tc{constructor(){super(...arguments),this._prefix=o}get readWrite(){return this}get sandbox(){return this._sandbox?this._sandbox:this._sandbox=new tm(this)}}class t_ extends tu{get v1(){return this._v1?this._v1:this._v1=new eq(this)}get v2(){return this._v2?this._v2:this._v2=new to(this)}get readWrite(){return this}get ads(){return this._ads?this._ads:this._ads=new tg(this)}static getErrors(e){var t;return"object"==typeof e&&"data"in e&&null!==(t=e.data.errors)&&void 0!==t?t:[]}static getProfileImageInSize(e,t){let s=e.split("/").pop(),r=e;for(let t of["normal","bigger","mini"])if(s.includes(`_${t}`)){r=e.replace(`_${t}`,"");break}if("original"===t)return r;let i=r.lastIndexOf(".");if(-1===i)return r+"_"+t;{let e=r.slice(i+1);return r.slice(0,i)+"_"+t+"."+e}}}let tf=t_},3794:(e,t,s)=>{"use strict";s.r(t),s.d(t,{executeSocialTask:()=>z,isSocialTask:()=>Y,readSocialFreshness:()=>J});var r=s(2048),i=s(5315),a=s(9576);let n=function(){let e=process.cwd();if(r.existsSync(i.join(e,"data","config.json")))return e;try{for(let t of r.readdirSync(e,{withFileTypes:!0}))if(t.isDirectory()){let s=i.join(e,t.name,"data","config.json");if(r.existsSync(s))return i.join(e,t.name)}}catch{}let t=e;for(let e=0;e<5;e++){let e=i.dirname(t);if(e===t)break;if(r.existsSync(i.join(e,"data","config.json")))return e;t=e}return e}(),o=i.join(n,"data");i.join(n,"STATUS.md"),i.join(n,"TODO.md"),i.join(n,"MEMORY.md");let l=i.join(o,"ideas.json"),u=i.join(o,"goals.json");i.join(o,"sessions.json"),i.join(o,"config.json"),i.join(o,"business-context.json"),i.join(o,"hypotheses.json"),i.join(o,"implementations.json"),i.join(o,"roadmap.json"),i.join(o,"competitors.json");let d=i.join(o,"positioning.json");i.join(o,"pages.json"),i.join(o,"payments.json"),i.join(o,"posthog.json");let c=i.join(o,"social.json"),h=i.join(__dirname,"..","..","templates");function p(){let e=function(e){let t=i.join(e,".env");if(!r.existsSync(t))return{};let s=r.readFileSync(t,"utf-8"),a={};for(let e of s.split("\n")){let t=e.trim();if(!t||t.startsWith("#"))continue;let s=t.indexOf("=");if(-1===s)continue;let r=t.slice(0,s).trim(),i=t.slice(s+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),a[r]=i}return a}(n),t=e.X_API_KEY||process.env.X_API_KEY,s=e.X_API_SECRET||process.env.X_API_SECRET,a=e.X_ACCESS_TOKEN||process.env.X_ACCESS_TOKEN,o=e.X_ACCESS_SECRET||process.env.X_ACCESS_SECRET;return t&&s&&a&&o?{apiKey:t,apiSecret:s,accessToken:a,accessSecret:o}:null}function m(e){let t;try{let e=s(1401).resolve("twitter-api-v2",{paths:[n]}),r=s(1401)(e);t=r.TwitterApi||r.default?.TwitterApi||r.default}catch{try{let e=s(5883);t=e.TwitterApi||e.default?.TwitterApi||e.default}catch{throw Error("twitter-api-v2 is not installed. Run: npm install twitter-api-v2")}}if("function"!=typeof t)throw Error("Could not find TwitterApi constructor in twitter-api-v2");return new t({appKey:e.apiKey,appSecret:e.apiSecret,accessToken:e.accessToken,accessSecret:e.accessSecret})}async function g(e){try{let t=await e.v2.me({"user.fields":["public_metrics"]}),s=t?.data;if(!s?.username)return{valid:!1,username:null,followersCount:null};return{valid:!0,username:`@${s.username}`,followersCount:s.public_metrics?.followers_count??null}}catch{return{valid:!1,username:null,followersCount:null}}}async function _(e,t){if(t.length>280)throw Error(`Tweet exceeds 280 characters (${t.length})`);let s=await e.v2.tweet(t),r=s?.data?.id;if(!r)throw Error("Tweet posted but no ID returned");return{id:r,url:`https://x.com/i/status/${r}`}}async function f(e,t){if(!s(2048).existsSync(t))throw Error(`Media file not found: ${t}`);let r=await e.v1.uploadMedia(t);if(!r)throw Error("Media uploaded but no media_id returned");return String(r)}async function w(e,t,s){if(t.length>280)throw Error(`Tweet exceeds 280 characters (${t.length})`);if(0===s.length)throw Error("No media IDs provided");if(s.length>4)throw Error("X allows max 4 media attachments per tweet");let r=await e.v2.tweet(t,{media:{media_ids:s}}),i=r?.data?.id;if(!i)throw Error("Tweet posted but no ID returned");return{id:i,url:`https://x.com/i/status/${i}`}}async function y(e,t){try{let s=await e.v2.singleTweet(t,{"tweet.fields":["public_metrics","non_public_metrics","organic_metrics"]}),r=s?.data;if(!r)return null;let i=r.public_metrics??{},a=r.non_public_metrics??{},n=r.organic_metrics??{},o=a.impression_count??n.impression_count??0,l=(i.like_count??0)+(i.retweet_count??0)+(i.reply_count??0)+(i.bookmark_count??0)+(a.url_link_clicks??0)+(a.user_profile_clicks??0);return{tweet_id:t,impressions:o,likes:i.like_count??0,retweets:i.retweet_count??0,replies:i.reply_count??0,bookmarks:i.bookmark_count??0,profile_clicks:a.user_profile_clicks??0,engagements:l,engagement_rate:o>0?l/o:0,fetched_at:new Date().toISOString()}}catch(e){return console.error(`Failed to fetch metrics for tweet ${t}:`,e),null}}async function v(e,t){let s=[];for(let r of t){let t=await y(e,r);t&&s.push(t)}return s}async function b(e,t,s){if(0===t.length)throw Error("Thread must have at least one tweet");if(t.length>25)throw Error("Thread cannot exceed 25 tweets");for(let e=0;e<t.length;e++)if(t[e].length>280)throw Error(`Tweet ${e+1} exceeds 280 characters (${t[e].length})`);let r=[];for(let i=0;i<t.length;i++){let a=t[i],n=s?.[i],o={};i>0&&(o.reply={in_reply_to_tweet_id:r[i-1].id}),n&&(o.media={media_ids:[n]});let l=await e.v2.tweet(a,o),u=l?.data?.id;if(!u)throw Error(`Thread tweet ${i+1} posted but no ID returned`);r.push({id:u,url:`https://x.com/i/status/${u}`})}return r}i.join(h,"commands");let k="#buildinpublic";function x(e,t=280){return e.length<=t?e:e.slice(0,t-3).trimEnd()+"..."}function S(e,t){try{if(!r.existsSync(e))return t;return JSON.parse(r.readFileSync(e,"utf-8"))}catch{return t}}function R(e){if(!e){let t=S(l,{ideas:[]}).ideas.filter(e=>"shipped"===e.stage).sort((e,t)=>(t.implementation?.completed_at||t.updated_at).localeCompare(e.implementation?.completed_at||e.updated_at));if(0===t.length)return null;e=t[0]}return x(`Just shipped: ${e.title}. ${e.summary} ${k}`)}var T=s(1282);let D=i.join(process.env.HOME||"",".ai-analyst"),P=i.join(D,"provider.json");async function E(e){let t=Date.now(),s=process.env.ANTHROPIC_API_KEY;if(!s)return{output:"",provider:"anthropic-api",durationMs:0,error:"ANTHROPIC_API_KEY not set"};try{let r=e.model||"claude-sonnet-4-5-20250929",i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":s,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:r,max_tokens:16384,messages:[{role:"user",content:e.prompt}]}),signal:AbortSignal.timeout(e.timeoutMs||3e5)});if(!i.ok){let e=await i.text();return{output:"",provider:"anthropic-api",durationMs:Date.now()-t,error:`Anthropic API error ${i.status}: ${e}`}}return{output:(await i.json()).content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),provider:"anthropic-api",durationMs:Date.now()-t}}catch(e){return{output:"",provider:"anthropic-api",durationMs:Date.now()-t,error:`Anthropic API call failed: ${e.message}`}}}async function A(e){let t=function(){try{if(r.existsSync(P))return JSON.parse(r.readFileSync(P,"utf-8"))}catch{}return null}(),s=function(e){let t=function(e){let t=e||"claude";try{let e=(0,T.execSync)(`${t} --version 2>/dev/null`,{timeout:1e4,encoding:"utf-8"}).trim();return{found:!0,path:t,version:e}}catch{for(let e of["/usr/local/bin/claude",i.join(process.env.HOME||"",".claude","bin","claude"),i.join(process.env.HOME||"",".local","bin","claude")])try{if(r.existsSync(e)){let t=(0,T.execSync)(`${e} --version 2>/dev/null`,{timeout:1e4,encoding:"utf-8"}).trim();return{found:!0,path:e,version:t}}}catch{continue}return{found:!1,path:t}}}(e?.claudePath);if(t.found)return{provider:"claude-cli",version:t.version,message:`Found Claude Code CLI${t.version?` (${t.version})`:""}. Using your Claude subscription for AI reasoning.`};let s=process.env.ANTHROPIC_API_KEY?{provider:"anthropic-api",key:process.env.ANTHROPIC_API_KEY}:process.env.OPENAI_API_KEY?{provider:"openai-api",key:process.env.OPENAI_API_KEY}:process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY?{provider:"google-api",key:process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY}:null;return s?{provider:s.provider,message:`Using ${({"claude-cli":"Claude CLI","anthropic-api":"Anthropic API","openai-api":"OpenAI API","google-api":"Google AI API"})[s.provider]} key for AI reasoning.`}:{provider:"claude-cli",message:"No AI provider found. Install Claude Code CLI or set an API key (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)."}}(t||void 0);switch(s.provider){case"claude-cli":return function(e,t){let s=t||"claude",r=["--print"];e.model&&r.push("--model",e.model),e.claudeFlags&&r.push(...e.claudeFlags);let i=!1!==e.useStdin&&e.prompt.length>1e4;i||r.push("-p",e.prompt);let a=Date.now(),n=e.timeoutMs||3e5;return new Promise(t=>{let o=(0,T.spawn)(s,r,{cwd:e.cwd||process.cwd(),env:process.env,stdio:i?["pipe","pipe","pipe"]:["ignore","pipe","pipe"]}),l="",u="";o.stdout?.on("data",e=>{l+=e.toString()}),o.stderr?.on("data",e=>{u+=e.toString()}),i&&o.stdin&&(o.stdin.write(e.prompt),o.stdin.end());let d=setTimeout(()=>{o.kill("SIGTERM"),t({output:l,provider:"claude-cli",durationMs:Date.now()-a,error:`Timeout after ${n}ms`})},n);o.on("close",e=>{clearTimeout(d),t({output:l.trim(),provider:"claude-cli",durationMs:Date.now()-a,error:0!==e?`Claude CLI exited with code ${e}: ${u}`:void 0})}),o.on("error",e=>{clearTimeout(d),t({output:"",provider:"claude-cli",durationMs:Date.now()-a,error:`Failed to spawn Claude CLI: ${e.message}`})})})}(e,t?.claudePath);case"anthropic-api":return E(e);case"openai-api":case"google-api":return{output:"",provider:s.provider,durationMs:0,error:`${s.provider} provider not yet implemented. Use Claude CLI or set ANTHROPIC_API_KEY.`};default:return{output:"",provider:"claude-cli",durationMs:0,error:s.message}}}function L(e,t){try{if(!r.existsSync(e))return t;return JSON.parse(r.readFileSync(e,"utf-8"))}catch{return t}}function I(e){if(!e||0===e.length)return"No historical data yet.";let t=[...e].sort((e,t)=>t.engagement_rate-e.engagement_rate),s=e.reduce((e,t)=>e+t.engagement_rate,0)/e.length,r=t[0];return`Average engagement rate: ${(100*s).toFixed(2)}%
3
3
  Best tweet: ${r.tweet_id} (${(100*r.engagement_rate).toFixed(2)}% rate, ${r.impressions} impressions, ${r.bookmarks} bookmarks)
4
4
  Total tweets analyzed: ${e.length}`}let q=`
5
5
  X/Twitter Algorithm Knowledge (use this to optimize content):
@@ -98,6 +98,66 @@ Respond in this exact JSON format (no markdown, no code blocks):
98
98
  "score": 75,
99
99
  "feedback": ["specific feedback point 1", "specific feedback point 2", "specific feedback point 3"],
100
100
  "optimized_version": "the improved tweet text (max 280 chars)"
101
- }`,r=await A({prompt:s,model:"haiku"});try{let t=JSON.parse(F(r.output));return t.optimized_version?.length>280&&(t.optimized_version=t.optimized_version.slice(0,277).trimEnd()+"..."),{score:Math.min(100,Math.max(0,Number(t.score)||50)),feedback:Array.isArray(t.feedback)?t.feedback:[],optimized_version:t.optimized_version||e}}catch{return{score:50,feedback:["Could not analyze draft — AI response parsing failed."],optimized_version:e}}}function F(e){let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t)return t[1].trim();let s=e.match(/\{[\s\S]*\}/);return s?s[0]:e.trim()}let U={last_updated:new Date().toISOString(),platform:"x",username:null,credentials_valid:!1,drafts:[],metrics:{followers_count:null,post_streak_days:0,total_posts:0,last_post_date:null}};function $(){if(!r.existsSync(c))return{...U,metrics:{...U.metrics}};try{return JSON.parse(r.readFileSync(c,"utf-8"))}catch{return{...U,metrics:{...U.metrics}}}}function N(e){e.last_updated=new Date().toISOString();let t=i.dirname(c);r.existsSync(t)||r.mkdirSync(t,{recursive:!0}),r.writeFileSync(c,JSON.stringify(e,null,2)+"\n")}function B(e){let t=e.drafts.filter(e=>"published"===e.status&&e.published_at).map(e=>e.published_at.split("T")[0]).sort().reverse();if(0===t.length)return 0;let s=Array.from(new Set(t)),r=new Date().toISOString().split("T")[0];if(s[0]!==r){let e=new Date(Date.now()-864e5).toISOString().split("T")[0];if(s[0]!==e)return 0}let i=1;for(let e=1;e<s.length;e++){let t=new Date(s[e-1]),r=new Date(s[e]);if(1===Math.round((t.getTime()-r.getTime())/864e5))i++;else break}return i}function H(e,t){return e.drafts.some(e=>e.source_ref===t&&("draft"===e.status||"published"===e.status))}function V(e,t,s,r,i=null){let n={id:`draft-${(0,a.Z)().slice(0,8)}`,text:t,source:s,source_ref:r,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,media_paths:i};return e.drafts.push(n),n}let W=["social-setup-x","social-draft-ship-visual","social-draft-ship","social-draft-update","social-draft-milestone","social-draft-digest","social-draft-viral-","social-draft-thread-","social-publish-","social-track-metrics","social-score-","social-check-status"];function K(e){return W.some(t=>e.startsWith(t))}async function z(e,t,s){try{if("social-setup-x"===e)return await J();if("social-draft-ship-visual"===e)return function(){let e=$(),t=T();if(!t)return{success:!1,output:"No shipped ideas found to generate a tweet from."};let{ideas:s}=JSON.parse(r.readFileSync(i.join(i.dirname(c),"ideas.json"),"utf-8")),a=s.filter(e=>"shipped"===e.stage).sort((e,t)=>t.updated_at.localeCompare(e.updated_at))[0];if(a&&H(e,a.id))return{success:!1,output:`Draft already exists for shipped idea ${a.id}`};let n=[];if(a){let e=i.join(o,"reports","visuals",`${a.id}-card.png`);r.existsSync(e)&&n.push(e);let t=i.join(o,"videos",`${a.id}-ship.mp4`);r.existsSync(t)&&(n.length=0,n.push(t))}if(0===n.length)return{success:!1,output:`No ship card or video found for idea ${a?.id||"unknown"}. Run generate-visual-{ideaId} first.`};let l=V(e,t,"ship",a?.id||null,n);return N(e),{success:!0,output:`Created ship draft with media: "${l.text}" (${l.id}) — ${n.length} file(s) attached`}}();if("social-draft-ship"===e)return function(){let e=$(),t=T();if(!t)return{success:!1,output:"No shipped ideas found to generate a tweet from."};let{ideas:s}=JSON.parse(r.readFileSync(i.join(i.dirname(c),"ideas.json"),"utf-8")),a=s.filter(e=>"shipped"===e.stage).sort((e,t)=>t.updated_at.localeCompare(e.updated_at))[0];if(a&&H(e,a.id))return{success:!1,output:`Draft already exists for shipped idea ${a.id}`};let n=V(e,t,"ship",a?.id||null);return N(e),{success:!0,output:`Created ship draft: "${n.text}" (${n.id})`}}();if("social-draft-update"===e)return function(){let e=$(),t=function(e){if(!e&&(e=R(d,null),!e?.current))return null;let t=e.current.tagline,s=e.current.value_proposition,r=s.split(/[.!]/).filter(Boolean)[0]?.trim();return r?k(`${t} — ${r}. ${x}`):k(`${t} ${x}`)}();if(!t)return{success:!1,output:"No positioning data found to generate update tweet."};let s=V(e,t,"update",null);return N(e),{success:!0,output:`Created update draft: "${s.text}" (${s.id})`}}();if("social-draft-milestone"===e)return function(){let e=$(),t=function(e,t,s){for(let e of R(u,{goals:[]}).goals)for(let t of e.kpis)if(null!=t.current_value&&null!=t.target_value&&t.current_value>=t.target_value){let e=Math.round(t.current_value/t.target_value*100);return k(`Hit ${t.current_value} ${t.name}! ${e}% to goal ${x}`)}return null}();if(!t)return{success:!1,output:"No KPI milestones found to celebrate."};let s=V(e,t,"milestone",null);return N(e),{success:!0,output:`Created milestone draft: "${s.text}" (${s.id})`}}();if("social-draft-digest"===e)return function(){let e=$(),t=function(e){if(!e){let t=R(l,{ideas:[]}),s=new Date(Date.now()-6048e5).toISOString(),r=t.ideas.filter(e=>"shipped"===e.stage&&(e.implementation?.completed_at||e.updated_at)>s);if(0===r.length)return null;e={ideasShipped:r.length,kpisMoved:0,topShip:r[0]?.title}}let t=["Weekly recap:"];return t.push(`${e.ideasShipped} feature${1!==e.ideasShipped?"s":""} shipped`),e.kpisMoved>0&&t.push(`${e.kpisMoved} KPI${1!==e.kpisMoved?"s":""} moved`),e.topShip&&t.push(`Top: ${e.topShip}`),k(`${t.join(". ")}. ${x}`)}();if(!t)return{success:!1,output:"No recent activity to summarize in a digest."};let s=V(e,t,"digest",null);return N(e),{success:!0,output:`Created digest draft: "${s.text}" (${s.id})`}}();if(e.startsWith("social-draft-viral-")){let s=e.replace("social-draft-viral-","");return await G(s,t)}if(e.startsWith("social-draft-thread-")){let s=e.replace("social-draft-thread-","");return await X(s,t)}if(e.startsWith("social-publish-")){let t=e.replace("social-publish-","");return await Q(t)}if("social-track-metrics"===e)return await Z();if(e.startsWith("social-score-")){let t=e.replace("social-score-","");return await ee(t)}if("social-check-status"===e)return await es();return{success:!1,output:`Unknown social task: ${e}`}}catch(t){let e=t instanceof Error?t.message:String(t);return{success:!1,output:`Social task failed: ${e}`}}}function Y(){let e=$(),t=e.drafts.filter(e=>"draft"===e.status).length,s=B(e),r=[];for(let t of e.drafts)t.engagement_history&&t.engagement_history.length>0&&r.push(t.engagement_history[t.engagement_history.length-1]);let i=null,a=null,n=null;if(r.length>0){i=r.reduce((e,t)=>e+t.engagement_rate,0)/r.length;let e=r.reduce((e,t)=>e.engagement_rate>t.engagement_rate?e:t);a=e.tweet_id,n=e.engagement_rate}let o=e.drafts.filter(e=>e.is_thread&&"published"===e.status).length;return{configured:e.credentials_valid,credentials_valid:e.credentials_valid,username:e.username,draft_count:t,post_streak_days:s,total_posts:e.metrics.total_posts,last_post_date:e.metrics.last_post_date,avg_engagement_rate:i,best_tweet_id:a,best_engagement_rate:n,thread_count:o}}async function J(){let e=p();if(!e)return{success:!1,output:'X API credentials not found. Add these to your .env file:\n X_API_KEY=your_consumer_api_key\n X_API_SECRET=your_consumer_api_secret\n X_ACCESS_TOKEN=your_access_token\n X_ACCESS_SECRET=your_access_token_secret\n\nGet these at https://developer.x.com/en/portal/dashboard\nCreate a project with "Read and Write" permissions.'};let t=m(e),s=await g(t),r=$();return(r.credentials_valid=s.valid,r.username=s.username,null!=s.followersCount&&(r.metrics.followers_count=s.followersCount),N(r),s.valid)?{success:!0,output:`Connected to X as ${s.username} (${s.followersCount??0} followers)`}:{success:!1,output:"X API credentials are invalid. Check your keys at https://developer.x.com"}}async function Q(e){let t;let s=$(),i=s.drafts.find(t=>t.id===e);if(!i)return{success:!1,output:`Draft not found: ${e}`};if("draft"!==i.status)return{success:!1,output:`Draft ${e} is already ${i.status}`};let a=p();if(!a)return{success:!1,output:"X API credentials not configured. Run social-setup-x first."};let n=m(a);if(i.is_thread&&i.thread_tweets&&i.thread_tweets.length>0){let e=await b(n,i.thread_tweets);return i.status="published",i.published_at=new Date().toISOString(),i.tweet_id=e[0].id,i.tweet_url=e[0].url,i.thread_tweet_ids=e.map(e=>e.id),s.metrics.total_posts++,s.metrics.last_post_date=new Date().toISOString().split("T")[0],s.metrics.post_streak_days=B(s),N(s),er(s),{success:!0,output:`Published thread (${e.length} tweets): ${e[0].url}`}}if(i.media_paths&&i.media_paths.length>0){let e=i.media_paths.filter(e=>r.existsSync(e));if(e.length>0){let s=[];for(let t of e){let e=await f(n,t);s.push(e)}t=await w(n,i.text,s)}else t=await _(n,i.text)}else t=await _(n,i.text);return i.status="published",i.published_at=new Date().toISOString(),i.tweet_id=t.id,i.tweet_url=t.url,s.metrics.total_posts++,s.metrics.last_post_date=new Date().toISOString().split("T")[0],s.metrics.post_streak_days=B(s),N(s),er(s),{success:!0,output:`Published tweet: ${t.url}`}}async function G(e,t){let s=$(),r=et(s),i=await C({topic:e,context:t||`A ${e} tweet about our product`,pastPerformance:r}),a=V(s,i.text,"insight"===e||"question"===e?"insight":e,null);return N(s),{success:!0,output:`Created AI-generated ${e} draft: "${a.text}" (${a.id})
101
+ }`,r=await A({prompt:s,model:"haiku"});try{let t=JSON.parse(F(r.output));return t.optimized_version?.length>280&&(t.optimized_version=t.optimized_version.slice(0,277).trimEnd()+"..."),{score:Math.min(100,Math.max(0,Number(t.score)||50)),feedback:Array.isArray(t.feedback)?t.feedback:[],optimized_version:t.optimized_version||e}}catch{return{score:50,feedback:["Could not analyze draft — AI response parsing failed."],optimized_version:e}}}async function $(e){let t=e.positioning??L(d,null),s=new Date,r=s.getDay(),i=new Date(s);i.setDate(s.getDate()+(0===r?1:1===r?0:8-r));let a=[],n=["monday","tuesday","wednesday","thursday","friday","saturday","sunday"];for(let e=0;e<7;e++){let t=new Date(i);t.setDate(i.getDate()+e),a.push({day:n[e],date:t.toISOString().split("T")[0]})}let o=`You are a social media strategist for a developer-focused indie hacker audience on X/Twitter.
102
+
103
+ ${q}
104
+
105
+ ${j}
106
+
107
+ PRODUCT CONTEXT:
108
+ - Product: ${t?.current?.tagline??"VibeBusiness"}
109
+ - Value prop: ${t?.current?.value_proposition??"AI-powered business automation"}
110
+ - Target audience: ${t?.current?.target_audience?.primary??"Indie hackers and solo founders"}
111
+
112
+ CURRENT GOALS:
113
+ ${e.goalsContext||"No specific goals set."}
114
+
115
+ RECENTLY SHIPPED:
116
+ ${e.recentShips||"No recent ships."}
117
+
118
+ KPI HIGHLIGHTS:
119
+ ${e.kpiHighlights||"No KPI data yet."}
120
+
121
+ HISTORICAL PERFORMANCE:
122
+ ${I(e.pastPerformance??[])}
123
+
124
+ WEEK DATES:
125
+ ${a.map(e=>`${e.day}: ${e.date}`).join("\n")}
126
+
127
+ Plan a full week of content (Monday-Sunday). Rules:
128
+ - 5 content days (Mon-Fri) + 2 rest days (Sat-Sun)
129
+ - Include 1-2 threads per week (threads get 200-300% more reach)
130
+ - Mix content types: ship, viral, thread, milestone, insight, question
131
+ - Align content with current goals (especially behind-schedule ones)
132
+ - Use diverse hook patterns — don't repeat the same hook type consecutively
133
+ - Write FULL tweet text for each content day (max 280 chars for single tweets)
134
+ - For threads, provide all tweet texts (5-7 tweets each, max 280 chars per tweet)
135
+ - Each rest day should have type "rest" with empty content
136
+
137
+ Respond in this exact JSON format (no markdown, no code blocks):
138
+ {
139
+ "days": [
140
+ {
141
+ "day": "monday",
142
+ "date": "YYYY-MM-DD",
143
+ "type": "thread",
144
+ "topic": "topic description",
145
+ "content": "First tweet / hook text",
146
+ "thread_tweets": ["tweet 1", "tweet 2", "..."],
147
+ "hook_type": "story",
148
+ "rationale": "Why this content on this day"
149
+ },
150
+ {
151
+ "day": "tuesday",
152
+ "date": "YYYY-MM-DD",
153
+ "type": "viral",
154
+ "topic": "ship",
155
+ "content": "Full tweet text here",
156
+ "hook_type": "bold-claim",
157
+ "rationale": "Why this content on this day"
158
+ }
159
+ ],
160
+ "strategy_summary": "One paragraph explaining the week's strategy"
161
+ }`,l=await A({prompt:o,model:"sonnet"});try{let e=JSON.parse(F(l.output));for(let t of e.days)"rest"!==t.type&&(t.content&&t.content.length>280&&(t.content=t.content.slice(0,277).trimEnd()+"..."),t.thread_tweets&&(t.thread_tweets=t.thread_tweets.map(e=>e.length>280?e.slice(0,277).trimEnd()+"...":e)));return{days:e.days||[],strategy_summary:e.strategy_summary||""}}catch{return{days:[],strategy_summary:"AI failed to generate a valid week plan."}}}function F(e){let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t)return t[1].trim();let s=e.match(/\{[\s\S]*\}/);return s?s[0]:e.trim()}let N={last_updated:new Date().toISOString(),platform:"x",username:null,credentials_valid:!1,drafts:[],metrics:{followers_count:null,post_streak_days:0,total_posts:0,last_post_date:null}};function U(){if(!r.existsSync(c))return{...N,metrics:{...N.metrics}};try{return JSON.parse(r.readFileSync(c,"utf-8"))}catch{return{...N,metrics:{...N.metrics}}}}function B(e){e.last_updated=new Date().toISOString();let t=i.dirname(c);r.existsSync(t)||r.mkdirSync(t,{recursive:!0}),r.writeFileSync(c,JSON.stringify(e,null,2)+"\n")}function H(e){let t=e.drafts.filter(e=>"published"===e.status&&e.published_at).map(e=>e.published_at.split("T")[0]).sort().reverse();if(0===t.length)return 0;let s=Array.from(new Set(t)),r=new Date().toISOString().split("T")[0];if(s[0]!==r){let e=new Date(Date.now()-864e5).toISOString().split("T")[0];if(s[0]!==e)return 0}let i=1;for(let e=1;e<s.length;e++){let t=new Date(s[e-1]),r=new Date(s[e]);if(1===Math.round((t.getTime()-r.getTime())/864e5))i++;else break}return i}function W(e,t){return e.drafts.some(e=>e.source_ref===t&&("draft"===e.status||"published"===e.status))}function V(e,t,s,r,i=null){let n={id:`draft-${(0,a.Z)().slice(0,8)}`,text:t,source:s,source_ref:r,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,media_paths:i};return e.drafts.push(n),n}let K=["social-setup-x","social-plan-week","social-draft-ship-visual","social-draft-ship","social-draft-update","social-draft-milestone","social-draft-digest","social-draft-viral-","social-draft-thread-","social-publish-","social-track-metrics","social-score-","social-check-status"];function Y(e){return K.some(t=>e.startsWith(t))}async function z(e,t,s){try{if("social-setup-x"===e)return await G();if("social-plan-week"===e)return await ee();if("social-draft-ship-visual"===e)return function(){let e=U(),t=R();if(!t)return{success:!1,output:"No shipped ideas found to generate a tweet from."};let{ideas:s}=JSON.parse(r.readFileSync(i.join(i.dirname(c),"ideas.json"),"utf-8")),a=s.filter(e=>"shipped"===e.stage).sort((e,t)=>t.updated_at.localeCompare(e.updated_at))[0];if(a&&W(e,a.id))return{success:!1,output:`Draft already exists for shipped idea ${a.id}`};let n=[];if(a){let e=i.join(o,"reports","visuals",`${a.id}-card.png`);r.existsSync(e)&&n.push(e);let t=i.join(o,"videos",`${a.id}-ship.mp4`);r.existsSync(t)&&(n.length=0,n.push(t))}if(0===n.length)return{success:!1,output:`No ship card or video found for idea ${a?.id||"unknown"}. Run generate-visual-{ideaId} first.`};let l=V(e,t,"ship",a?.id||null,n);return B(e),{success:!0,output:`Created ship draft with media: "${l.text}" (${l.id}) — ${n.length} file(s) attached`}}();if("social-draft-ship"===e)return function(){let e=U(),t=R();if(!t)return{success:!1,output:"No shipped ideas found to generate a tweet from."};let{ideas:s}=JSON.parse(r.readFileSync(i.join(i.dirname(c),"ideas.json"),"utf-8")),a=s.filter(e=>"shipped"===e.stage).sort((e,t)=>t.updated_at.localeCompare(e.updated_at))[0];if(a&&W(e,a.id))return{success:!1,output:`Draft already exists for shipped idea ${a.id}`};let n=V(e,t,"ship",a?.id||null);return B(e),{success:!0,output:`Created ship draft: "${n.text}" (${n.id})`}}();if("social-draft-update"===e)return function(){let e=U(),t=function(e){if(!e&&(e=S(d,null),!e?.current))return null;let t=e.current.tagline,s=e.current.value_proposition,r=s.split(/[.!]/).filter(Boolean)[0]?.trim();return r?x(`${t} — ${r}. ${k}`):x(`${t} ${k}`)}();if(!t)return{success:!1,output:"No positioning data found to generate update tweet."};let s=V(e,t,"update",null);return B(e),{success:!0,output:`Created update draft: "${s.text}" (${s.id})`}}();if("social-draft-milestone"===e)return function(){let e=U(),t=function(e,t,s){for(let e of S(u,{goals:[]}).goals)for(let t of e.kpis)if(null!=t.current_value&&null!=t.target_value&&t.current_value>=t.target_value){let e=Math.round(t.current_value/t.target_value*100);return x(`Hit ${t.current_value} ${t.name}! ${e}% to goal ${k}`)}return null}();if(!t)return{success:!1,output:"No KPI milestones found to celebrate."};let s=V(e,t,"milestone",null);return B(e),{success:!0,output:`Created milestone draft: "${s.text}" (${s.id})`}}();if("social-draft-digest"===e)return function(){let e=U(),t=function(e){if(!e){let t=S(l,{ideas:[]}),s=new Date(Date.now()-6048e5).toISOString(),r=t.ideas.filter(e=>"shipped"===e.stage&&(e.implementation?.completed_at||e.updated_at)>s);if(0===r.length)return null;e={ideasShipped:r.length,kpisMoved:0,topShip:r[0]?.title}}let t=["Weekly recap:"];return t.push(`${e.ideasShipped} feature${1!==e.ideasShipped?"s":""} shipped`),e.kpisMoved>0&&t.push(`${e.kpisMoved} KPI${1!==e.kpisMoved?"s":""} moved`),e.topShip&&t.push(`Top: ${e.topShip}`),x(`${t.join(". ")}. ${k}`)}();if(!t)return{success:!1,output:"No recent activity to summarize in a digest."};let s=V(e,t,"digest",null);return B(e),{success:!0,output:`Created digest draft: "${s.text}" (${s.id})`}}();if(e.startsWith("social-draft-viral-")){let s=e.replace("social-draft-viral-","");return await X(s,t)}if(e.startsWith("social-draft-thread-")){let s=e.replace("social-draft-thread-","");return await Z(s,t)}if(e.startsWith("social-publish-")){let t=e.replace("social-publish-","");return await Q(t)}if("social-track-metrics"===e)return await es();if(e.startsWith("social-score-")){let t=e.replace("social-score-","");return await er(t)}if("social-check-status"===e)return await ea();return{success:!1,output:`Unknown social task: ${e}`}}catch(t){let e=t instanceof Error?t.message:String(t);return{success:!1,output:`Social task failed: ${e}`}}}function J(){let e=U(),t=e.drafts.filter(e=>"draft"===e.status).length,s=H(e),r=[];for(let t of e.drafts)t.engagement_history&&t.engagement_history.length>0&&r.push(t.engagement_history[t.engagement_history.length-1]);let i=null,a=null,n=null;if(r.length>0){i=r.reduce((e,t)=>e+t.engagement_rate,0)/r.length;let e=r.reduce((e,t)=>e.engagement_rate>t.engagement_rate?e:t);a=e.tweet_id,n=e.engagement_rate}let o=e.drafts.filter(e=>e.is_thread&&"published"===e.status).length,l=new Date().toISOString().split("T")[0],u=e.drafts.filter(e=>"draft"===e.status&&e.scheduled_date&&e.scheduled_date>=l).length;return{configured:e.credentials_valid,credentials_valid:e.credentials_valid,username:e.username,draft_count:t,post_streak_days:s,total_posts:e.metrics.total_posts,last_post_date:e.metrics.last_post_date,avg_engagement_rate:i,best_tweet_id:a,best_engagement_rate:n,thread_count:o,scheduled_draft_count:u}}async function G(){let e=p();if(!e)return{success:!1,output:'X API credentials not found. Add these to your .env file:\n X_API_KEY=your_consumer_api_key\n X_API_SECRET=your_consumer_api_secret\n X_ACCESS_TOKEN=your_access_token\n X_ACCESS_SECRET=your_access_token_secret\n\nGet these at https://developer.x.com/en/portal/dashboard\nCreate a project with "Read and Write" permissions.'};let t=m(e),s=await g(t),r=U();return(r.credentials_valid=s.valid,r.username=s.username,null!=s.followersCount&&(r.metrics.followers_count=s.followersCount),B(r),s.valid)?{success:!0,output:`Connected to X as ${s.username} (${s.followersCount??0} followers)`}:{success:!1,output:"X API credentials are invalid. Check your keys at https://developer.x.com"}}async function Q(e){let t;let s=U(),i=s.drafts.find(t=>t.id===e);if(!i)return{success:!1,output:`Draft not found: ${e}`};if("draft"!==i.status)return{success:!1,output:`Draft ${e} is already ${i.status}`};let a=p();if(!a)return{success:!1,output:"X API credentials not configured. Run social-setup-x first."};let n=m(a);if(i.is_thread&&i.thread_tweets&&i.thread_tweets.length>0){let e=await b(n,i.thread_tweets);return i.status="published",i.published_at=new Date().toISOString(),i.tweet_id=e[0].id,i.tweet_url=e[0].url,i.thread_tweet_ids=e.map(e=>e.id),s.metrics.total_posts++,s.metrics.last_post_date=new Date().toISOString().split("T")[0],s.metrics.post_streak_days=H(s),B(s),en(s),{success:!0,output:`Published thread (${e.length} tweets): ${e[0].url}`}}if(i.media_paths&&i.media_paths.length>0){let e=i.media_paths.filter(e=>r.existsSync(e));if(e.length>0){let s=[];for(let t of e){let e=await f(n,t);s.push(e)}t=await w(n,i.text,s)}else t=await _(n,i.text)}else t=await _(n,i.text);return i.status="published",i.published_at=new Date().toISOString(),i.tweet_id=t.id,i.tweet_url=t.url,s.metrics.total_posts++,s.metrics.last_post_date=new Date().toISOString().split("T")[0],s.metrics.post_streak_days=H(s),B(s),en(s),{success:!0,output:`Published tweet: ${t.url}`}}async function X(e,t){let s=U(),r=ei(s),i=await C({topic:e,context:t||`A ${e} tweet about our product`,pastPerformance:r}),a=V(s,i.text,"insight"===e||"question"===e?"insight":e,null);return B(s),{success:!0,output:`Created AI-generated ${e} draft: "${a.text}" (${a.id})
102
162
  Hook type: ${i.hook_type}
103
- Estimated engagement: ${i.estimated_engagement}`}}async function X(e,t){let s=$(),r=et(s),i=await M({topic:e,context:t||`A thread about ${e}`,threadLength:5,pastPerformance:r});if(!i.tweets||0===i.tweets.length)return{success:!1,output:"AI failed to generate thread content."};let n={id:`draft-${(0,a.Z)().slice(0,8)}`,text:i.tweets[0],source:"thread",source_ref:null,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,is_thread:!0,thread_tweets:i.tweets};return s.drafts.push(n),N(s),{success:!0,output:[`Created thread draft (${i.tweets.length} tweets): ${n.id}`,`Hook type: ${i.hook_type}`,"Preview:",...i.tweets.map((e,t)=>` ${t+1}. "${e.slice(0,60)}${e.length>60?"...":""}"`)].join("\n")}}async function Z(){let e=$(),t=p();if(!t)return{success:!1,output:"X API credentials not configured. Run social-setup-x first."};let s=m(t),r=new Date(Date.now()-6048e5).toISOString(),i=e.drafts.filter(e=>"published"===e.status&&e.published_at&&e.published_at>r&&e.tweet_id);if(0===i.length)return{success:!0,output:"No published tweets in the last 7 days to track."};let a=[];for(let e of i)e.thread_tweet_ids&&e.thread_tweet_ids.length>0?a.push(...e.thread_tweet_ids):e.tweet_id&&a.push(e.tweet_id);let n=await v(s,a);if(0===n.length)return{success:!0,output:"Could not fetch metrics (API may require elevated access)."};for(let e of i)if(e.engagement_history||(e.engagement_history=[]),e.thread_tweet_ids&&e.thread_tweet_ids.length>0){let t=n.filter(t=>e.thread_tweet_ids.includes(t.tweet_id));if(t.length>0){let s={tweet_id:e.tweet_id,impressions:t.reduce((e,t)=>e+t.impressions,0),likes:t.reduce((e,t)=>e+t.likes,0),retweets:t.reduce((e,t)=>e+t.retweets,0),replies:t.reduce((e,t)=>e+t.replies,0),bookmarks:t.reduce((e,t)=>e+t.bookmarks,0),profile_clicks:t.reduce((e,t)=>e+t.profile_clicks,0),engagements:t.reduce((e,t)=>e+t.engagements,0),engagement_rate:0,fetched_at:new Date().toISOString()};s.engagement_rate=s.impressions>0?s.engagements/s.impressions:0,e.engagement_history.push(s)}}else{let t=n.find(t=>t.tweet_id===e.tweet_id);t&&e.engagement_history.push(t)}N(e);let o=[`Tracked metrics for ${n.length} tweet(s):`];for(let e of n)o.push(` ${e.tweet_id}: ${e.impressions} impressions, ${e.likes} likes, ${e.bookmarks} bookmarks, ${(100*e.engagement_rate).toFixed(2)}% rate`);return{success:!0,output:o.join("\n")}}async function ee(e){let t=$(),s=t.drafts.find(t=>t.id===e);if(!s)return{success:!1,output:`Draft not found: ${e}`};let r=s.is_thread&&s.thread_tweets?s.thread_tweets.join("\n\n---\n\n"):s.text,i=et(t),a=await O(r,i);return{success:!0,output:[`Draft Score: ${a.score}/100`,"","Feedback:",...a.feedback.map(e=>` - ${e}`),"",`Optimized version: "${a.optimized_version}"`].join("\n")}}function et(e){let t=[];for(let s of e.drafts)s.engagement_history&&s.engagement_history.length>0&&t.push(s.engagement_history[s.engagement_history.length-1]);return t}async function es(){let e=$(),t=Y(),s=["Social Media Status:"];if(t.configured){s.push(" Platform: X"),s.push(` Username: ${t.username}`),s.push(` Credentials: ${t.credentials_valid?"valid":"INVALID"}`);let r=p();if(r)try{let t=m(r),i=await g(t);i.valid&&null!=i.followersCount&&(e.metrics.followers_count=i.followersCount,e.credentials_valid=!0,N(e),s.push(` Followers: ${i.followersCount}`))}catch{s.push(` Followers: ${e.metrics.followers_count??"unknown"}`)}}else s.push(" Platform: X (not connected)"),s.push(" Run social-setup-x to connect.");return s.push(` Pending drafts: ${t.draft_count}`),s.push(` Post streak: ${t.post_streak_days} day(s)`),s.push(` Total posts: ${t.total_posts}`),s.push(` Threads published: ${t.thread_count}`),s.push(` Last post: ${t.last_post_date||"never"}`),null!=t.avg_engagement_rate&&s.push(` Avg engagement rate: ${(100*t.avg_engagement_rate).toFixed(2)}%`),t.best_tweet_id&&s.push(` Best tweet: ${t.best_tweet_id} (${((t.best_engagement_rate??0)*100).toFixed(2)}% rate)`),{success:!0,output:s.join("\n")}}function er(e){try{if(!r.existsSync(u))return;let t=JSON.parse(r.readFileSync(u,"utf-8")),s=!1;for(let r of t.goals)for(let t of r.kpis){if("kpi-daily-posts"===t.id&&e.metrics.post_streak_days>0){t.current_value=e.metrics.post_streak_days;let r=new Date().toISOString().split("T")[0],i=t.history.find(e=>e.date===r);i?i.value=e.metrics.post_streak_days:t.history.push({date:r,value:e.metrics.post_streak_days}),s=!0}if("kpi-twitter-followers"===t.id&&null!=e.metrics.followers_count){t.current_value=e.metrics.followers_count;let r=new Date().toISOString().split("T")[0],i=t.history.find(e=>e.date===r);i?i.value=e.metrics.followers_count:t.history.push({date:r,value:e.metrics.followers_count}),s=!0}}s&&r.writeFileSync(u,JSON.stringify(t,null,2)+"\n")}catch{}}}};
163
+ Estimated engagement: ${i.estimated_engagement}`}}async function Z(e,t){let s=U(),r=ei(s),i=await M({topic:e,context:t||`A thread about ${e}`,threadLength:5,pastPerformance:r});if(!i.tweets||0===i.tweets.length)return{success:!1,output:"AI failed to generate thread content."};let n={id:`draft-${(0,a.Z)().slice(0,8)}`,text:i.tweets[0],source:"thread",source_ref:null,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,is_thread:!0,thread_tweets:i.tweets};return s.drafts.push(n),B(s),{success:!0,output:[`Created thread draft (${i.tweets.length} tweets): ${n.id}`,`Hook type: ${i.hook_type}`,"Preview:",...i.tweets.map((e,t)=>` ${t+1}. "${e.slice(0,60)}${e.length>60?"...":""}"`)].join("\n")}}async function ee(){let e=U(),t=ei(e),s=null;try{r.existsSync(d)&&(s=JSON.parse(r.readFileSync(d,"utf-8")))}catch{}let i="";try{if(r.existsSync(u)){let{goals:e}=JSON.parse(r.readFileSync(u,"utf-8")),t=e.filter(e=>"on_track"===e.status||"at_risk"===e.status||"behind"===e.status).map(e=>{let t=null!=e.current_value&&e.target_value?`${Math.round(e.current_value/e.target_value*100)}%`:"unknown";return`- ${e.title} (${e.status}, ${t} complete, deadline: ${e.deadline})`});i=t.length>0?t.join("\n"):"No active goals."}}catch{}let n="";try{if(r.existsSync(l)){let{ideas:e}=JSON.parse(r.readFileSync(l,"utf-8")),t=new Date(Date.now()-12096e5).toISOString(),s=e.filter(e=>"shipped"===e.stage&&e.updated_at>t).map(e=>`- ${e.title} (shipped ${e.updated_at.split("T")[0]})`);n=s.length>0?s.join("\n"):"No recent ships."}}catch{}let o="";try{if(r.existsSync(u)){let{goals:e}=JSON.parse(r.readFileSync(u,"utf-8")),t=[];for(let s of e)for(let e of s.kpis)if(null!=e.current_value&&null!=e.target_value){let s=Math.round(e.current_value/e.target_value*100);t.push(`- ${e.name}: ${e.current_value}/${e.target_value} ${e.unit} (${s}%)`)}o=t.length>0?t.join("\n"):"No KPI data."}}catch{}let c=await $({positioning:s,pastPerformance:t,goalsContext:i,recentShips:n,kpiHighlights:o});if(0===c.days.length)return{success:!1,output:"AI failed to generate a weekly content plan."};let h=[];for(let t of c.days)if("rest"!==t.type&&t.content){if("thread"===t.type&&t.thread_tweets&&t.thread_tweets.length>0){let s={id:`draft-${(0,a.Z)().slice(0,8)}`,text:t.thread_tweets[0],source:"thread",source_ref:null,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,is_thread:!0,thread_tweets:t.thread_tweets,scheduled_date:t.date};e.drafts.push(s),h.push({day:t.day,date:t.date,type:"thread",id:s.id})}else{let s=["ship","milestone","update","digest","insight"].includes(t.topic)?t.topic:"insight",r=V(e,t.content,s,null);r.scheduled_date=t.date,h.push({day:t.day,date:t.date,type:t.type,id:r.id})}}B(e);let p=c.days.find(e=>"monday"===e.day)?.date??"",m=c.days.find(e=>"sunday"===e.day)?.date??"",g=p&&m?`${et(p)} - ${et(m)}`:"This Week",_=[`Weekly Content Plan (${g})`,""];for(let e of c.days){let t=e.day.charAt(0).toUpperCase()+e.day.slice(1,3);if("rest"===e.type)_.push(`${t} -- Rest`);else{let s="thread"===e.type&&e.thread_tweets?` (${e.thread_tweets.length} tweets)`:"",r=e.content.length>60?`"${e.content.slice(0,57)}..."`:`"${e.content}"`;_.push(`${t} [${e.type}] ${r}${s}`),_.push(` Hook: ${e.hook_type} | ${e.rationale}`)}}return _.push(""),_.push(`${h.length} drafts created. Review and edit at: vibebusiness start -> /social`),{success:!0,output:_.join("\n")}}function et(e){let t=new Date(e+"T00:00:00");return`${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()]} ${t.getDate()}`}async function es(){let e=U(),t=p();if(!t)return{success:!1,output:"X API credentials not configured. Run social-setup-x first."};let s=m(t),r=new Date(Date.now()-6048e5).toISOString(),i=e.drafts.filter(e=>"published"===e.status&&e.published_at&&e.published_at>r&&e.tweet_id);if(0===i.length)return{success:!0,output:"No published tweets in the last 7 days to track."};let a=[];for(let e of i)e.thread_tweet_ids&&e.thread_tweet_ids.length>0?a.push(...e.thread_tweet_ids):e.tweet_id&&a.push(e.tweet_id);let n=await v(s,a);if(0===n.length)return{success:!0,output:"Could not fetch metrics (API may require elevated access)."};for(let e of i)if(e.engagement_history||(e.engagement_history=[]),e.thread_tweet_ids&&e.thread_tweet_ids.length>0){let t=n.filter(t=>e.thread_tweet_ids.includes(t.tweet_id));if(t.length>0){let s={tweet_id:e.tweet_id,impressions:t.reduce((e,t)=>e+t.impressions,0),likes:t.reduce((e,t)=>e+t.likes,0),retweets:t.reduce((e,t)=>e+t.retweets,0),replies:t.reduce((e,t)=>e+t.replies,0),bookmarks:t.reduce((e,t)=>e+t.bookmarks,0),profile_clicks:t.reduce((e,t)=>e+t.profile_clicks,0),engagements:t.reduce((e,t)=>e+t.engagements,0),engagement_rate:0,fetched_at:new Date().toISOString()};s.engagement_rate=s.impressions>0?s.engagements/s.impressions:0,e.engagement_history.push(s)}}else{let t=n.find(t=>t.tweet_id===e.tweet_id);t&&e.engagement_history.push(t)}B(e);let o=[`Tracked metrics for ${n.length} tweet(s):`];for(let e of n)o.push(` ${e.tweet_id}: ${e.impressions} impressions, ${e.likes} likes, ${e.bookmarks} bookmarks, ${(100*e.engagement_rate).toFixed(2)}% rate`);return{success:!0,output:o.join("\n")}}async function er(e){let t=U(),s=t.drafts.find(t=>t.id===e);if(!s)return{success:!1,output:`Draft not found: ${e}`};let r=s.is_thread&&s.thread_tweets?s.thread_tweets.join("\n\n---\n\n"):s.text,i=ei(t),a=await O(r,i);return{success:!0,output:[`Draft Score: ${a.score}/100`,"","Feedback:",...a.feedback.map(e=>` - ${e}`),"",`Optimized version: "${a.optimized_version}"`].join("\n")}}function ei(e){let t=[];for(let s of e.drafts)s.engagement_history&&s.engagement_history.length>0&&t.push(s.engagement_history[s.engagement_history.length-1]);return t}async function ea(){let e=U(),t=J(),s=["Social Media Status:"];if(t.configured){s.push(" Platform: X"),s.push(` Username: ${t.username}`),s.push(` Credentials: ${t.credentials_valid?"valid":"INVALID"}`);let r=p();if(r)try{let t=m(r),i=await g(t);i.valid&&null!=i.followersCount&&(e.metrics.followers_count=i.followersCount,e.credentials_valid=!0,B(e),s.push(` Followers: ${i.followersCount}`))}catch{s.push(` Followers: ${e.metrics.followers_count??"unknown"}`)}}else s.push(" Platform: X (not connected)"),s.push(" Run social-setup-x to connect.");return s.push(` Pending drafts: ${t.draft_count}`),s.push(` Scheduled drafts: ${t.scheduled_draft_count}`),s.push(` Post streak: ${t.post_streak_days} day(s)`),s.push(` Total posts: ${t.total_posts}`),s.push(` Threads published: ${t.thread_count}`),s.push(` Last post: ${t.last_post_date||"never"}`),null!=t.avg_engagement_rate&&s.push(` Avg engagement rate: ${(100*t.avg_engagement_rate).toFixed(2)}%`),t.best_tweet_id&&s.push(` Best tweet: ${t.best_tweet_id} (${((t.best_engagement_rate??0)*100).toFixed(2)}% rate)`),{success:!0,output:s.join("\n")}}function en(e){try{if(!r.existsSync(u))return;let t=JSON.parse(r.readFileSync(u,"utf-8")),s=!1;for(let r of t.goals)for(let t of r.kpis){if("kpi-daily-posts"===t.id&&e.metrics.post_streak_days>0){t.current_value=e.metrics.post_streak_days;let r=new Date().toISOString().split("T")[0],i=t.history.find(e=>e.date===r);i?i.value=e.metrics.post_streak_days:t.history.push({date:r,value:e.metrics.post_streak_days}),s=!0}if("kpi-twitter-followers"===t.id&&null!=e.metrics.followers_count){t.current_value=e.metrics.followers_count;let r=new Date().toISOString().split("T")[0],i=t.history.find(e=>e.date===r);i?i.value=e.metrics.followers_count:t.history.push({date:r,value:e.metrics.followers_count}),s=!0}}s&&r.writeFileSync(u,JSON.stringify(t,null,2)+"\n")}catch{}}}};