{"version":3,"sources":["jsdelivr-header.js","/npm/@cicadancr/twitter-scraper@0.14.9/src/errors.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/platform/platform-interface.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/platform/index.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/requests.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/api.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/auth.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/auth-user.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/profile.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/timeline-async.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/type-util.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/timeline-tweet-util.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/timeline-v2.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/timeline-search.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/search.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/timeline-relationship.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/relationships.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/trends.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/api-data.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/timeline-list.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/tweets.ts","/npm/@cicadancr/twitter-scraper@0.14.9/src/scraper.ts"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,4oBCNO,MAAM,iBAAiB,MACpB,WAAA,CACG,EACA,EACT,GAEA,MAAM,GAJG,KAAA,WACA,KAAA,MAAA,CAMX,yBAAa,CAAa,GAExB,IAAI,EACA,IACK,QAAM,EAAS,MAAK,CACrB,MACF,IACK,QAAM,EAAS,MAAK,CACrB,OAAC,CAGX,OAAO,IAAI,SAAS,EAAU,EAAM,oBAAoB,EAAS,SAAQ,ECThE,MAAA,gBAAkB,IAA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rB,UAAW,KAAK,SAAS,UAC3B,CAGM,cAAA,CAAkB,GACpB,IAAC,EAAI,QACP,MAAM,EAAI,IAGZ,OAAO,EAAI,KAAA,E","file":"/npm/@cicadancr/twitter-scraper@0.14.9/dist/default/cjs/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/@cicadancr/twitter-scraper@0.14.9/dist/default/cjs/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","export class ApiError extends Error {\n  private constructor(\n    readonly response: Response,\n    readonly data: any,\n    message: string,\n  ) {\n    super(message);\n  }\n\n  static async fromResponse(response: Response) {\n    // Try our best to parse the result, but don't bother if we can't\n    let data: string | object | undefined = undefined;\n    try {\n      data = await response.json();\n    } catch {\n      try {\n        data = await response.text();\n      } catch {}\n    }\n\n    return new ApiError(response, data, `Response status: ${response.status}`);\n  }\n}\n\ninterface Position {\n  line: number;\n  column: number;\n}\n\ninterface TraceInfo {\n  trace_id: string;\n}\n\ninterface TwitterApiErrorExtensions {\n  code?: number;\n  kind?: string;\n  name?: string;\n  source?: string;\n  tracing?: TraceInfo;\n}\n\nexport interface TwitterApiErrorRaw extends TwitterApiErrorExtensions {\n  message?: string;\n  locations?: Position[];\n  path?: string[];\n  extensions?: TwitterApiErrorExtensions;\n}\n","export interface PlatformExtensions {\n  /**\n   * Randomizes the runtime's TLS ciphers to bypass TLS client fingerprinting, which\n   * hopefully avoids random 404s on some requests.\n   *\n   * **References:**\n   * - https://github.com/imputnet/cobalt/pull/574\n   */\n  randomizeCiphers(): Promise<void>;\n}\n\nexport const genericPlatform = new (class implements PlatformExtensions {\n  randomizeCiphers(): Promise<void> {\n    return Promise.resolve();\n  }\n})();\n","import { PlatformExtensions, genericPlatform } from './platform-interface';\n\nexport * from './platform-interface';\n\ndeclare const PLATFORM_NODE: boolean;\ndeclare const PLATFORM_NODE_JEST: boolean;\n\nexport class Platform implements PlatformExtensions {\n  async randomizeCiphers() {\n    const platform = await Platform.importPlatform();\n    await platform?.randomizeCiphers();\n  }\n\n  private static async importPlatform(): Promise<null | PlatformExtensions> {\n    if (PLATFORM_NODE) {\n      const { platform } = await import('./node/index.js');\n      return platform as PlatformExtensions;\n    } else if (PLATFORM_NODE_JEST) {\n      // Jest gets unhappy when using an await import here, so we just use require instead.\n      // eslint-disable-next-line @typescript-eslint/no-var-requires\n      const { platform } = require('./node');\n      return platform as PlatformExtensions;\n    }\n\n    return genericPlatform;\n  }\n}\n","import { Cookie, CookieJar } from 'tough-cookie';\nimport setCookie from 'set-cookie-parser';\nimport type { Headers as HeadersPolyfill } from 'headers-polyfill';\n\n/**\n * Updates a cookie jar with the Set-Cookie headers from the provided Headers instance.\n * @param cookieJar The cookie jar to update.\n * @param headers The response headers to populate the cookie jar with.\n */\nexport async function updateCookieJar(\n  cookieJar: CookieJar,\n  headers: Headers | HeadersPolyfill,\n) {\n  const setCookieHeader = headers.get('set-cookie');\n  if (setCookieHeader) {\n    const cookies = setCookie.splitCookiesString(setCookieHeader);\n    for (const cookie of cookies.map((c) => Cookie.parse(c))) {\n      if (!cookie) continue;\n      await cookieJar.setCookie(\n        cookie,\n        `${cookie.secure ? 'https' : 'http'}://${cookie.domain}${cookie.path}`,\n      );\n    }\n  } else if (typeof document !== 'undefined') {\n    for (const cookie of document.cookie.split(';')) {\n      const hardCookie = Cookie.parse(cookie);\n      if (hardCookie) {\n        await cookieJar.setCookie(hardCookie, document.location.toString());\n      }\n    }\n  }\n}\n","import { TwitterAuth } from './auth';\nimport { ApiError } from './errors';\nimport { Platform, PlatformExtensions } from './platform';\nimport { updateCookieJar } from './requests';\nimport { Headers } from 'headers-polyfill';\n\n// For some reason using Parameters<typeof fetch> reduces the request transform function to\n// `(url: string) => string` in tests.\ntype FetchParameters = [input: RequestInfo | URL, init?: RequestInit];\n\nexport interface FetchTransformOptions {\n  /**\n   * Transforms the request options before a request is made. This executes after all of the default\n   * parameters have been configured, and is stateless. It is safe to return new request options\n   * objects.\n   * @param args The request options.\n   * @returns The transformed request options.\n   */\n  request: (\n    ...args: FetchParameters\n  ) => FetchParameters | Promise<FetchParameters>;\n\n  /**\n   * Transforms the response after a request completes. This executes immediately after the request\n   * completes, and is stateless. It is safe to return a new response object.\n   * @param response The response object.\n   * @returns The transformed response object.\n   */\n  response: (response: Response) => Response | Promise<Response>;\n}\n\nexport const bearerToken =\n  'AAAAAAAAAAAAAAAAAAAAAFQODgEAAAAAVHTp76lzh3rFzcHbmHVvQxYYpTw%3DckAlMINMjmCwxUcaXbAN4XqJVdgMJaHqNOFgPMK0zN1qLqLQCF';\n\n/**\n * An API result container.\n */\nexport type RequestApiResult<T> =\n  | { success: true; value: T }\n  | { success: false; err: Error };\n\n/**\n * Used internally to send HTTP requests to the Twitter API.\n * @internal\n * @param url - The URL to send the request to.\n * @param auth - The instance of {@link TwitterAuth} that will be used to authorize this request.\n * @param method - The HTTP method used when sending this request.\n */\nexport async function requestApi<T>(\n  url: string,\n  auth: TwitterAuth,\n  method: 'GET' | 'POST' = 'GET',\n  platform: PlatformExtensions = new Platform(),\n): Promise<RequestApiResult<T>> {\n  const headers = new Headers();\n  await auth.installTo(headers, url);\n  await platform.randomizeCiphers();\n\n  let res: Response;\n  do {\n    try {\n      res = await auth.fetch(url, {\n        method,\n        headers,\n        credentials: 'include',\n      });\n    } catch (err) {\n      if (!(err instanceof Error)) {\n        throw err;\n      }\n\n      return {\n        success: false,\n        err: new Error('Failed to perform request.'),\n      };\n    }\n\n    await updateCookieJar(auth.cookieJar(), res.headers);\n\n    if (res.status === 429) {\n      /*\n      Known headers at this point:\n      - x-rate-limit-limit: Maximum number of requests per time period?\n      - x-rate-limit-reset: UNIX timestamp when the current rate limit will be reset.\n      - x-rate-limit-remaining: Number of requests remaining in current time period?\n      */\n      const xRateLimitRemaining = res.headers.get('x-rate-limit-remaining');\n      const xRateLimitReset = res.headers.get('x-rate-limit-reset');\n      if (xRateLimitRemaining == '0' && xRateLimitReset) {\n        const currentTime = new Date().valueOf() / 1000;\n        const timeDeltaMs = 1000 * (parseInt(xRateLimitReset) - currentTime);\n\n        // I have seen this block for 800s (~13 *minutes*)\n        await new Promise((resolve) => setTimeout(resolve, timeDeltaMs));\n      }\n    }\n  } while (res.status === 429);\n\n  if (!res.ok) {\n    return {\n      success: false,\n      err: await ApiError.fromResponse(res),\n    };\n  }\n\n  const value: T = await res.json();\n  if (res.headers.get('x-rate-limit-incoming') == '0') {\n    auth.deleteToken();\n    return { success: true, value };\n  } else {\n    return { success: true, value };\n  }\n}\n\n/** @internal */\nexport function addApiFeatures(o: object) {\n  return {\n    ...o,\n    rweb_lists_timeline_redesign_enabled: true,\n    responsive_web_graphql_exclude_directive_enabled: true,\n    verified_phone_label_enabled: false,\n    creator_subscriptions_tweet_preview_api_enabled: true,\n    responsive_web_graphql_timeline_navigation_enabled: true,\n    responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n    tweetypie_unmention_optimization_enabled: true,\n    responsive_web_edit_tweet_api_enabled: true,\n    graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n    view_counts_everywhere_api_enabled: true,\n    longform_notetweets_consumption_enabled: true,\n    tweet_awards_web_tipping_enabled: false,\n    freedom_of_speech_not_reach_fetch_enabled: true,\n    standardized_nudges_misinfo: true,\n    longform_notetweets_rich_text_read_enabled: true,\n    responsive_web_enhance_cards_enabled: false,\n    subscriptions_verification_info_enabled: true,\n    subscriptions_verification_info_reason_enabled: true,\n    subscriptions_verification_info_verified_since_enabled: true,\n    super_follow_badge_privacy_enabled: false,\n    super_follow_exclusive_tweet_notifications_enabled: false,\n    super_follow_tweet_api_enabled: false,\n    super_follow_user_api_enabled: false,\n    android_graphql_skip_api_media_color_palette: false,\n    creator_subscriptions_subscription_count_enabled: false,\n    blue_business_profile_image_shape_enabled: false,\n    unified_cards_ad_metadata_container_dynamic_card_content_query_enabled:\n      false,\n  };\n}\n\nexport function addApiParams(\n  params: URLSearchParams,\n  includeTweetReplies: boolean,\n): URLSearchParams {\n  params.set('include_profile_interstitial_type', '1');\n  params.set('include_blocking', '1');\n  params.set('include_blocked_by', '1');\n  params.set('include_followed_by', '1');\n  params.set('include_want_retweets', '1');\n  params.set('include_mute_edge', '1');\n  params.set('include_can_dm', '1');\n  params.set('include_can_media_tag', '1');\n  params.set('include_ext_has_nft_avatar', '1');\n  params.set('include_ext_is_blue_verified', '1');\n  params.set('include_ext_verified_type', '1');\n  params.set('skip_status', '1');\n  params.set('cards_platform', 'Web-12');\n  params.set('include_cards', '1');\n  params.set('include_ext_alt_text', 'true');\n  params.set('include_ext_limited_action_results', 'false');\n  params.set('include_quote_count', 'true');\n  params.set('include_reply_count', '1');\n  params.set('tweet_mode', 'extended');\n  params.set('include_ext_collab_control', 'true');\n  params.set('include_ext_views', 'true');\n  params.set('include_entities', 'true');\n  params.set('include_user_entities', 'true');\n  params.set('include_ext_media_color', 'true');\n  params.set('include_ext_media_availability', 'true');\n  params.set('include_ext_sensitive_media_warning', 'true');\n  params.set('include_ext_trusted_friends_metadata', 'true');\n  params.set('send_error_codes', 'true');\n  params.set('simple_quoted_tweet', 'true');\n  params.set('include_tweet_replies', `${includeTweetReplies}`);\n  params.set(\n    'ext',\n    'mediaStats,highlightedLabel,hasNftAvatar,voiceInfo,birdwatchPivot,enrichments,superFollowMetadata,unmentionInfo,editControl,collab_control,vibe',\n  );\n  return params;\n}\n","import { Cookie, CookieJar, MemoryCookieStore } from 'tough-cookie';\nimport { updateCookieJar } from './requests';\nimport { Headers } from 'headers-polyfill';\nimport fetch from 'cross-fetch';\nimport { FetchTransformOptions } from './api';\n\nexport interface TwitterAuthOptions {\n  fetch: typeof fetch;\n  transform: Partial<FetchTransformOptions>;\n}\n\nexport interface TwitterAuth {\n  fetch: typeof fetch;\n\n  /**\n   * Returns the current cookie jar.\n   */\n  cookieJar(): CookieJar;\n\n  /**\n   * Returns if a user is logged-in to Twitter through this instance.\n   * @returns `true` if a user is logged-in; otherwise `false`.\n   */\n  isLoggedIn(): Promise<boolean>;\n\n  /**\n   * Logs into a Twitter account.\n   * @param username The username to log in with.\n   * @param password The password to log in with.\n   * @param email The email to log in with, if you have email confirmation enabled.\n   * @param twoFactorSecret The secret to generate two factor authentication tokens with, if you have two factor authentication enabled.\n   */\n  login(\n    username: string,\n    password: string,\n    email?: string,\n    twoFactorSecret?: string,\n  ): Promise<void>;\n\n  /**\n   * Logs out of the current session.\n   */\n  logout(): Promise<void>;\n\n  /**\n   * Deletes the current guest token token.\n   */\n  deleteToken(): void;\n\n  /**\n   * Returns if the authentication state has a token.\n   * @returns `true` if the authentication state has a token; `false` otherwise.\n   */\n  hasToken(): boolean;\n\n  /**\n   * Returns the time that authentication was performed.\n   * @returns The time at which the authentication token was created, or `null` if it hasn't been created yet.\n   */\n  authenticatedAt(): Date | null;\n\n  /**\n   * Installs the authentication information into a headers-like object. If needed, the\n   * authentication token will be updated from the API automatically.\n   * @param headers A Headers instance representing a request's headers.\n   */\n  installTo(headers: Headers, url: string): Promise<void>;\n}\n\n/**\n * Wraps the provided fetch function with transforms.\n * @param fetchFn The fetch function.\n * @param transform The transform options.\n * @returns The input fetch function, wrapped with the provided transforms.\n */\nfunction withTransform(\n  fetchFn: typeof fetch,\n  transform?: Partial<FetchTransformOptions>,\n): typeof fetch {\n  return async (input, init) => {\n    const fetchArgs = (await transform?.request?.(input, init)) ?? [\n      input,\n      init,\n    ];\n    const res = await fetchFn(...fetchArgs);\n    return (await transform?.response?.(res)) ?? res;\n  };\n}\n\n/**\n * A guest authentication token manager. Automatically handles token refreshes.\n */\nexport class TwitterGuestAuth implements TwitterAuth {\n  protected bearerToken: string;\n  protected jar: CookieJar;\n  protected guestToken?: string;\n  protected guestCreatedAt?: Date;\n\n  fetch: typeof fetch;\n\n  constructor(\n    bearerToken: string,\n    protected readonly options?: Partial<TwitterAuthOptions>,\n  ) {\n    this.fetch = withTransform(options?.fetch ?? fetch, options?.transform);\n    this.bearerToken = bearerToken;\n    this.jar = new CookieJar();\n  }\n\n  cookieJar(): CookieJar {\n    return this.jar;\n  }\n\n  isLoggedIn(): Promise<boolean> {\n    return Promise.resolve(false);\n  }\n\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  login(_username: string, _password: string, _email?: string): Promise<void> {\n    return this.updateGuestToken();\n  }\n\n  logout(): Promise<void> {\n    this.deleteToken();\n    this.jar = new CookieJar();\n    return Promise.resolve();\n  }\n\n  deleteToken() {\n    delete this.guestToken;\n    delete this.guestCreatedAt;\n  }\n\n  hasToken(): boolean {\n    return this.guestToken != null;\n  }\n\n  authenticatedAt(): Date | null {\n    if (this.guestCreatedAt == null) {\n      return null;\n    }\n\n    return new Date(this.guestCreatedAt);\n  }\n\n  async installTo(headers: Headers): Promise<void> {\n    if (this.shouldUpdate()) {\n      await this.updateGuestToken();\n    }\n\n    const token = this.guestToken;\n    if (token == null) {\n      throw new Error('Authentication token is null or undefined.');\n    }\n\n    headers.set('authorization', `Bearer ${this.bearerToken}`);\n    headers.set('x-guest-token', token);\n\n    const cookies = await this.getCookies();\n    const xCsrfToken = cookies.find((cookie) => cookie.key === 'ct0');\n    if (xCsrfToken) {\n      headers.set('x-csrf-token', xCsrfToken.value);\n    }\n\n    headers.set('cookie', await this.getCookieString());\n  }\n\n  protected getCookies(): Promise<Cookie[]> {\n    return this.jar.getCookies(this.getCookieJarUrl());\n  }\n\n  protected getCookieString(): Promise<string> {\n    return this.jar.getCookieString(this.getCookieJarUrl());\n  }\n\n  protected async removeCookie(key: string): Promise<void> {\n    //@ts-expect-error don't care\n    const store: MemoryCookieStore = this.jar.store;\n    const cookies = await this.jar.getCookies(this.getCookieJarUrl());\n    for (const cookie of cookies) {\n      if (!cookie.domain || !cookie.path) continue;\n      store.removeCookie(cookie.domain, cookie.path, key);\n\n      if (typeof document !== 'undefined') {\n        document.cookie = `${cookie.key}=; Max-Age=0; path=${cookie.path}; domain=${cookie.domain}`;\n      }\n    }\n  }\n\n  private getCookieJarUrl(): string {\n    return typeof document !== 'undefined'\n      ? document.location.toString()\n      : 'https://twitter.com';\n  }\n\n  /**\n   * Updates the authentication state with a new guest token from the Twitter API.\n   */\n  protected async updateGuestToken() {\n    const guestActivateUrl = 'https://api.twitter.com/1.1/guest/activate.json';\n\n    const headers = new Headers({\n      Authorization: `Bearer ${this.bearerToken}`,\n      Cookie: await this.getCookieString(),\n    });\n\n    const res = await this.fetch(guestActivateUrl, {\n      method: 'POST',\n      headers: headers,\n      referrerPolicy: 'no-referrer',\n    });\n\n    await updateCookieJar(this.jar, res.headers);\n\n    if (!res.ok) {\n      throw new Error(await res.text());\n    }\n\n    const o = await res.json();\n    if (o == null || o['guest_token'] == null) {\n      throw new Error('guest_token not found.');\n    }\n\n    const newGuestToken = o['guest_token'];\n    if (typeof newGuestToken !== 'string') {\n      throw new Error('guest_token was not a string.');\n    }\n\n    this.guestToken = newGuestToken;\n    this.guestCreatedAt = new Date();\n  }\n\n  /**\n   * Returns if the authentication token needs to be updated or not.\n   * @returns `true` if the token needs to be updated; `false` otherwise.\n   */\n  private shouldUpdate(): boolean {\n    return (\n      !this.hasToken() ||\n      (this.guestCreatedAt != null &&\n        this.guestCreatedAt <\n          new Date(new Date().valueOf() - 3 * 60 * 60 * 1000))\n    );\n  }\n}\n","import { TwitterAuthOptions, TwitterGuestAuth } from './auth';\nimport { requestApi } from './api';\nimport { CookieJar } from 'tough-cookie';\nimport { updateCookieJar } from './requests';\nimport { Headers } from 'headers-polyfill';\nimport { TwitterApiErrorRaw } from './errors';\nimport { Type, type Static } from '@sinclair/typebox';\nimport { Check } from '@sinclair/typebox/value';\nimport * as OTPAuth from 'otpauth';\n\ninterface TwitterUserAuthFlowInitRequest {\n  flow_name: string;\n  input_flow_data: Record<string, unknown>;\n}\n\ninterface TwitterUserAuthFlowSubtaskRequest {\n  flow_token: string;\n  subtask_inputs: ({\n    subtask_id: string;\n  } & Record<string, unknown>)[];\n}\n\ntype TwitterUserAuthFlowRequest =\n  | TwitterUserAuthFlowInitRequest\n  | TwitterUserAuthFlowSubtaskRequest;\n\ninterface TwitterUserAuthFlowResponse {\n  errors?: TwitterApiErrorRaw[];\n  flow_token?: string;\n  status?: string;\n  subtasks?: TwitterUserAuthSubtask[];\n}\n\ninterface TwitterUserAuthVerifyCredentials {\n  errors?: TwitterApiErrorRaw[];\n}\n\nconst TwitterUserAuthSubtask = Type.Object({\n  subtask_id: Type.String(),\n  enter_text: Type.Optional(Type.Object({})),\n});\ntype TwitterUserAuthSubtask = Static<typeof TwitterUserAuthSubtask>;\n\ntype FlowTokenResultSuccess = {\n  status: 'success';\n  flowToken: string;\n  subtask?: TwitterUserAuthSubtask;\n};\n\ntype FlowTokenResult = FlowTokenResultSuccess | { status: 'error'; err: Error };\n\n/**\n * A user authentication token manager.\n */\nexport class TwitterUserAuth extends TwitterGuestAuth {\n  constructor(bearerToken: string, options?: Partial<TwitterAuthOptions>) {\n    super(bearerToken, options);\n  }\n\n  async isLoggedIn(): Promise<boolean> {\n    const res = await requestApi<TwitterUserAuthVerifyCredentials>(\n      'https://api.twitter.com/1.1/account/verify_credentials.json',\n      this,\n    );\n    if (!res.success) {\n      return false;\n    }\n\n    const { value: verify } = res;\n    return verify && !verify.errors?.length;\n  }\n\n  async login(\n    username: string,\n    password: string,\n    email?: string,\n    twoFactorSecret?: string,\n  ): Promise<void> {\n    await this.updateGuestToken();\n\n    let next = await this.initLogin();\n    while ('subtask' in next && next.subtask) {\n      if (next.subtask.subtask_id === 'LoginJsInstrumentationSubtask') {\n        next = await this.handleJsInstrumentationSubtask(next);\n      } else if (next.subtask.subtask_id === 'LoginEnterUserIdentifierSSO') {\n        next = await this.handleEnterUserIdentifierSSO(next, username);\n      } else if (\n        next.subtask.subtask_id === 'LoginEnterAlternateIdentifierSubtask'\n      ) {\n        next = await this.handleEnterAlternateIdentifierSubtask(\n          next,\n          email as string,\n        );\n      } else if (next.subtask.subtask_id === 'LoginEnterPassword') {\n        next = await this.handleEnterPassword(next, password);\n      } else if (next.subtask.subtask_id === 'AccountDuplicationCheck') {\n        next = await this.handleAccountDuplicationCheck(next);\n      } else if (next.subtask.subtask_id === 'LoginTwoFactorAuthChallenge') {\n        if (twoFactorSecret) {\n          next = await this.handleTwoFactorAuthChallenge(next, twoFactorSecret);\n        } else {\n          throw new Error(\n            'Requested two factor authentication code but no secret provided',\n          );\n        }\n      } else if (next.subtask.subtask_id === 'LoginAcid') {\n        next = await this.handleAcid(next, email);\n      } else if (next.subtask.subtask_id === 'LoginSuccessSubtask') {\n        next = await this.handleSuccessSubtask(next);\n      } else {\n        throw new Error(`Unknown subtask ${next.subtask.subtask_id}`);\n      }\n    }\n    if ('err' in next) {\n      throw next.err;\n    }\n  }\n\n  async logout(): Promise<void> {\n    if (!this.isLoggedIn()) {\n      return;\n    }\n\n    await requestApi<void>(\n      'https://api.twitter.com/1.1/account/logout.json',\n      this,\n      'POST',\n    );\n    this.deleteToken();\n    this.jar = new CookieJar();\n  }\n\n  async installCsrfToken(headers: Headers): Promise<void> {\n    const cookies = await this.getCookies();\n    const xCsrfToken = cookies.find((cookie) => cookie.key === 'ct0');\n    if (xCsrfToken) {\n      headers.set('x-csrf-token', xCsrfToken.value);\n    }\n  }\n\n  async installTo(headers: Headers): Promise<void> {\n    headers.set('authorization', `Bearer ${this.bearerToken}`);\n    headers.set('cookie', await this.getCookieString());\n    await this.installCsrfToken(headers);\n  }\n\n  private async initLogin() {\n    // Reset certain session-related cookies because Twitter complains sometimes if we don't\n    this.removeCookie('twitter_ads_id=');\n    this.removeCookie('ads_prefs=');\n    this.removeCookie('_twitter_sess=');\n    this.removeCookie('zipbox_forms_auth_token=');\n    this.removeCookie('lang=');\n    this.removeCookie('bouncer_reset_cookie=');\n    this.removeCookie('twid=');\n    this.removeCookie('twitter_ads_idb=');\n    this.removeCookie('email_uid=');\n    this.removeCookie('external_referer=');\n    this.removeCookie('ct0=');\n    this.removeCookie('aa_u=');\n\n    return await this.executeFlowTask({\n      flow_name: 'login',\n      input_flow_data: {\n        flow_context: {\n          debug_overrides: {},\n          start_location: {\n            location: 'splash_screen',\n          },\n        },\n      },\n    });\n  }\n\n  private async handleJsInstrumentationSubtask(prev: FlowTokenResultSuccess) {\n    return await this.executeFlowTask({\n      flow_token: prev.flowToken,\n      subtask_inputs: [\n        {\n          subtask_id: 'LoginJsInstrumentationSubtask',\n          js_instrumentation: {\n            response: '{}',\n            link: 'next_link',\n          },\n        },\n      ],\n    });\n  }\n\n  private async handleEnterAlternateIdentifierSubtask(\n    prev: FlowTokenResultSuccess,\n    email: string,\n  ) {\n    return await this.executeFlowTask({\n      flow_token: prev.flowToken,\n      subtask_inputs: [\n        {\n          subtask_id: 'LoginEnterAlternateIdentifierSubtask',\n          enter_text: {\n            text: email,\n            link: 'next_link',\n          },\n        },\n      ],\n    });\n  }\n\n  private async handleEnterUserIdentifierSSO(\n    prev: FlowTokenResultSuccess,\n    username: string,\n  ) {\n    return await this.executeFlowTask({\n      flow_token: prev.flowToken,\n      subtask_inputs: [\n        {\n          subtask_id: 'LoginEnterUserIdentifierSSO',\n          settings_list: {\n            setting_responses: [\n              {\n                key: 'user_identifier',\n                response_data: {\n                  text_data: { result: username },\n                },\n              },\n            ],\n            link: 'next_link',\n          },\n        },\n      ],\n    });\n  }\n\n  private async handleEnterPassword(\n    prev: FlowTokenResultSuccess,\n    password: string,\n  ) {\n    return await this.executeFlowTask({\n      flow_token: prev.flowToken,\n      subtask_inputs: [\n        {\n          subtask_id: 'LoginEnterPassword',\n          enter_password: {\n            password,\n            link: 'next_link',\n          },\n        },\n      ],\n    });\n  }\n\n  private async handleAccountDuplicationCheck(prev: FlowTokenResultSuccess) {\n    return await this.executeFlowTask({\n      flow_token: prev.flowToken,\n      subtask_inputs: [\n        {\n          subtask_id: 'AccountDuplicationCheck',\n          check_logged_in_account: {\n            link: 'AccountDuplicationCheck_false',\n          },\n        },\n      ],\n    });\n  }\n\n  private async handleTwoFactorAuthChallenge(\n    prev: FlowTokenResultSuccess,\n    secret: string,\n  ) {\n    const totp = new OTPAuth.TOTP({ secret });\n    let error;\n    for (let attempts = 1; attempts < 4; attempts += 1) {\n      try {\n        return await this.executeFlowTask({\n          flow_token: prev.flowToken,\n          subtask_inputs: [\n            {\n              subtask_id: 'LoginTwoFactorAuthChallenge',\n              enter_text: {\n                link: 'next_link',\n                text: totp.generate(),\n              },\n            },\n          ],\n        });\n      } catch (err) {\n        error = err;\n        await new Promise((resolve) => setTimeout(resolve, 2000 * attempts));\n      }\n    }\n    throw error;\n  }\n\n  private async handleAcid(\n    prev: FlowTokenResultSuccess,\n    email: string | undefined,\n  ) {\n    return await this.executeFlowTask({\n      flow_token: prev.flowToken,\n      subtask_inputs: [\n        {\n          subtask_id: 'LoginAcid',\n          enter_text: {\n            text: email,\n            link: 'next_link',\n          },\n        },\n      ],\n    });\n  }\n\n  private async handleSuccessSubtask(prev: FlowTokenResultSuccess) {\n    return await this.executeFlowTask({\n      flow_token: prev.flowToken,\n      subtask_inputs: [],\n    });\n  }\n\n  private async executeFlowTask(\n    data: TwitterUserAuthFlowRequest,\n  ): Promise<FlowTokenResult> {\n    const onboardingTaskUrl =\n      'https://api.twitter.com/1.1/onboarding/task.json';\n\n    const token = this.guestToken;\n    if (token == null) {\n      throw new Error('Authentication token is null or undefined.');\n    }\n\n    const headers = new Headers({\n      authorization: `Bearer ${this.bearerToken}`,\n      cookie: await this.getCookieString(),\n      'content-type': 'application/json',\n      'User-Agent':\n        'Mozilla/5.0 (Linux; Android 11; Nokia G20) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.88 Mobile Safari/537.36',\n      'x-guest-token': token,\n      'x-twitter-auth-type': 'OAuth2Client',\n      'x-twitter-active-user': 'yes',\n      'x-twitter-client-language': 'en',\n    });\n    await this.installCsrfToken(headers);\n\n    const res = await this.fetch(onboardingTaskUrl, {\n      credentials: 'include',\n      method: 'POST',\n      headers: headers,\n      body: JSON.stringify(data),\n    });\n\n    await updateCookieJar(this.jar, res.headers);\n\n    if (!res.ok) {\n      return { status: 'error', err: new Error(await res.text()) };\n    }\n\n    const flow: TwitterUserAuthFlowResponse = await res.json();\n    if (flow?.flow_token == null) {\n      return { status: 'error', err: new Error('flow_token not found.') };\n    }\n\n    if (flow.errors?.length) {\n      return {\n        status: 'error',\n        err: new Error(\n          `Authentication error (${flow.errors[0].code}): ${flow.errors[0].message}`,\n        ),\n      };\n    }\n\n    if (typeof flow.flow_token !== 'string') {\n      return {\n        status: 'error',\n        err: new Error('flow_token was not a string.'),\n      };\n    }\n\n    const subtask = flow.subtasks?.length ? flow.subtasks[0] : undefined;\n    Check(TwitterUserAuthSubtask, subtask);\n\n    if (subtask && subtask.subtask_id === 'DenyLoginSubtask') {\n      return {\n        status: 'error',\n        err: new Error('Authentication error: DenyLoginSubtask'),\n      };\n    }\n\n    return {\n      status: 'success',\n      subtask,\n      flowToken: flow.flow_token,\n    };\n  }\n}\n","import stringify from 'json-stable-stringify';\nimport { requestApi, RequestApiResult } from './api';\nimport { TwitterAuth } from './auth';\nimport { TwitterApiErrorRaw } from './errors';\n\nexport interface LegacyUserRaw {\n  created_at?: string;\n  description?: string;\n  entities?: {\n    url?: {\n      urls?: {\n        expanded_url?: string;\n      }[];\n    };\n  };\n  favourites_count?: number;\n  followers_count?: number;\n  friends_count?: number;\n  media_count?: number;\n  statuses_count?: number;\n  id_str?: string;\n  listed_count?: number;\n  name?: string;\n  location: string;\n  geo_enabled?: boolean;\n  pinned_tweet_ids_str?: string[];\n  profile_background_color?: string;\n  profile_banner_url?: string;\n  profile_image_url_https?: string;\n  protected?: boolean;\n  screen_name?: string;\n  verified?: boolean;\n  has_custom_timelines?: boolean;\n  has_extended_profile?: boolean;\n  url?: string;\n  can_dm?: boolean;\n}\n\n/**\n * A parsed profile object.\n */\nexport interface Profile {\n  avatar?: string;\n  banner?: string;\n  biography?: string;\n  birthday?: string;\n  followersCount?: number;\n  followingCount?: number;\n  friendsCount?: number;\n  mediaCount?: number;\n  statusesCount?: number;\n  isPrivate?: boolean;\n  isVerified?: boolean;\n  isBlueVerified?: boolean;\n  joined?: Date;\n  likesCount?: number;\n  listedCount?: number;\n  location: string;\n  name?: string;\n  pinnedTweetIds?: string[];\n  tweetsCount?: number;\n  url?: string;\n  userId?: string;\n  username?: string;\n  website?: string;\n  canDm?: boolean;\n}\n\nexport interface UserRaw {\n  data: {\n    user: {\n      result: {\n        rest_id?: string;\n        is_blue_verified?: boolean;\n        legacy: LegacyUserRaw;\n      };\n    };\n  };\n  errors?: TwitterApiErrorRaw[];\n}\n\nfunction getAvatarOriginalSizeUrl(avatarUrl: string | undefined) {\n  return avatarUrl ? avatarUrl.replace('_normal', '') : undefined;\n}\n\nexport function parseProfile(\n  user: LegacyUserRaw,\n  isBlueVerified?: boolean,\n): Profile {\n  const profile: Profile = {\n    avatar: getAvatarOriginalSizeUrl(user.profile_image_url_https),\n    banner: user.profile_banner_url,\n    biography: user.description,\n    followersCount: user.followers_count,\n    followingCount: user.friends_count,\n    friendsCount: user.friends_count,\n    mediaCount: user.media_count,\n    isPrivate: user.protected ?? false,\n    isVerified: user.verified,\n    likesCount: user.favourites_count,\n    listedCount: user.listed_count,\n    location: user.location,\n    name: user.name,\n    pinnedTweetIds: user.pinned_tweet_ids_str,\n    tweetsCount: user.statuses_count,\n    url: `https://twitter.com/${user.screen_name}`,\n    userId: user.id_str,\n    username: user.screen_name,\n    isBlueVerified: isBlueVerified ?? false,\n    canDm: user.can_dm,\n  };\n\n  if (user.created_at != null) {\n    profile.joined = new Date(Date.parse(user.created_at));\n  }\n\n  const urls = user.entities?.url?.urls;\n  if (urls?.length != null && urls?.length > 0) {\n    profile.website = urls[0].expanded_url;\n  }\n\n  return profile;\n}\n\nexport async function getProfile(\n  username: string,\n  auth: TwitterAuth,\n): Promise<RequestApiResult<Profile>> {\n  const params = new URLSearchParams();\n  params.set(\n    'variables',\n    stringify({\n      screen_name: username,\n      withSafetyModeUserFields: true,\n    }),\n  );\n\n  params.set(\n    'features',\n    stringify({\n      hidden_profile_likes_enabled: false,\n      hidden_profile_subscriptions_enabled: false, // Auth-restricted\n      responsive_web_graphql_exclude_directive_enabled: true,\n      verified_phone_label_enabled: false,\n      subscriptions_verification_info_is_identity_verified_enabled: false,\n      subscriptions_verification_info_verified_since_enabled: true,\n      highlights_tweets_tab_ui_enabled: true,\n      creator_subscriptions_tweet_preview_api_enabled: true,\n      responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n      responsive_web_graphql_timeline_navigation_enabled: true,\n    }),\n  );\n\n  params.set('fieldToggles', stringify({ withAuxiliaryUserLabels: false }));\n\n  const res = await requestApi<UserRaw>(\n    `https://twitter.com/i/api/graphql/G3KGOASz96M-Qu0nwmGXNg/UserByScreenName?${params.toString()}`,\n    auth,\n  );\n  if (!res.success) {\n    return res;\n  }\n\n  const { value } = res;\n  const { errors } = value;\n  if (errors != null && errors.length > 0) {\n    return {\n      success: false,\n      err: new Error(errors[0].message),\n    };\n  }\n\n  if (!value.data || !value.data.user || !value.data.user.result) {\n    return {\n      success: false,\n      err: new Error('User not found.'),\n    };\n  }\n  const { result: user } = value.data.user;\n  const { legacy } = user;\n\n  if (user.rest_id == null || user.rest_id.length === 0) {\n    return {\n      success: false,\n      err: new Error('rest_id not found.'),\n    };\n  }\n\n  legacy.id_str = user.rest_id;\n\n  if (legacy.screen_name == null || legacy.screen_name.length === 0) {\n    return {\n      success: false,\n      err: new Error(`Either ${username} does not exist or is private.`),\n    };\n  }\n\n  return {\n    success: true,\n    value: parseProfile(user.legacy, user.is_blue_verified),\n  };\n}\n\nconst idCache = new Map<string, string>();\n\nexport async function getUserIdByScreenName(\n  screenName: string,\n  auth: TwitterAuth,\n): Promise<RequestApiResult<string>> {\n  const cached = idCache.get(screenName);\n  if (cached != null) {\n    return { success: true, value: cached };\n  }\n\n  const profileRes = await getProfile(screenName, auth);\n  if (!profileRes.success) {\n    return profileRes;\n  }\n\n  const profile = profileRes.value;\n  if (profile.userId != null) {\n    idCache.set(screenName, profile.userId);\n\n    return {\n      success: true,\n      value: profile.userId,\n    };\n  }\n\n  return {\n    success: false,\n    err: new Error('User ID is undefined.'),\n  };\n}\n","import { Profile } from './profile';\nimport { Tweet } from './tweets';\n\nexport interface FetchProfilesResponse {\n  profiles: Profile[];\n  next?: string;\n}\n\nexport type FetchProfiles = (\n  query: string,\n  maxProfiles: number,\n  cursor: string | undefined,\n) => Promise<FetchProfilesResponse>;\n\nexport interface FetchTweetsResponse {\n  tweets: Tweet[];\n  next?: string;\n}\n\nexport type FetchTweets = (\n  query: string,\n  maxTweets: number,\n  cursor: string | undefined,\n) => Promise<FetchTweetsResponse>;\n\nexport async function* getUserTimeline(\n  query: string,\n  maxProfiles: number,\n  fetchFunc: FetchProfiles,\n): AsyncGenerator<Profile, void> {\n  yield* getUserTimelineCursor(query, maxProfiles, undefined, fetchFunc);\n}\n\nexport async function* getUserTimelineCursor(\n  query: string,\n  maxProfiles: number,\n  cursor: string | undefined,\n  fetchFunc: FetchProfiles,\n): AsyncGenerator<Profile, void> {\n  let nProfiles = 0;\n  let consecutiveEmptyBatches = 0;\n  while (nProfiles < maxProfiles) {\n    const batch: FetchProfilesResponse = await fetchFunc(\n      query,\n      maxProfiles,\n      cursor,\n    );\n\n    const { profiles, next } = batch;\n    cursor = next;\n\n    if (profiles.length === 0) {\n      consecutiveEmptyBatches++;\n      if (consecutiveEmptyBatches > 5) break;\n    } else consecutiveEmptyBatches = 0;\n\n    for (const profile of profiles) {\n      if (nProfiles < maxProfiles) yield profile;\n      else break;\n      nProfiles++;\n    }\n\n    if (!next) break;\n  }\n}\n\nexport async function* getTweetTimeline(\n  query: string,\n  maxTweets: number,\n  fetchFunc: FetchTweets,\n): AsyncGenerator<Tweet, void> {\n  console.log(\"OUTER\");\n  yield* getTweetTimelineCursor(query, maxTweets, undefined, fetchFunc);\n}\n\n\nexport async function* getTweetTimelineCursor(\n  query: string,\n  maxTweets: number,\n  cursor: string | undefined,\n  fetchFunc: FetchTweets,\n): AsyncGenerator<Tweet, void> {\n  console.log(\"SEARCHING INNER\");\n  let nTweets = 0;\n  while (nTweets < maxTweets) {\n    const batch: FetchTweetsResponse = await fetchFunc(\n      query,\n      maxTweets,\n      cursor,\n    );\n\n    const { tweets, next } = batch;\n\n    if (tweets.length === 0) {\n      break;\n    }\n\n    for (const tweet of tweets) {\n      if (nTweets < maxTweets) {\n        cursor = next;\n        yield tweet;\n      } else {\n        break;\n      }\n\n      nTweets++;\n    }\n  }\n}\n","export type NonNullableField<T, K extends keyof T> = {\n  [P in K]-?: T[P];\n} & T;\n\nexport function isFieldDefined<T, K extends keyof T>(key: K) {\n  return function (value: T): value is NonNullableField<T, K> {\n    return isDefined(value[key]);\n  };\n}\n\nexport function isDefined<T>(value: T | null | undefined): value is T {\n  return value != null;\n}\n","import { LegacyTweetRaw, TimelineMediaExtendedRaw } from './timeline-v1';\nimport { Photo, Video } from './tweets';\nimport { isFieldDefined, NonNullableField } from './type-util';\n\nconst reHashtag = /\\B(\\#\\S+\\b)/g;\nconst reCashtag = /\\B(\\$\\S+\\b)/g;\nconst reTwitterUrl = /https:(\\/\\/t\\.co\\/([A-Za-z0-9]|[A-Za-z]){10})/g;\nconst reUsername = /\\B(\\@\\S{1,15}\\b)/g;\n\nexport function parseMediaGroups(media: TimelineMediaExtendedRaw[]): {\n  sensitiveContent?: boolean;\n  photos: Photo[];\n  videos: Video[];\n} {\n  const photos: Photo[] = [];\n  const videos: Video[] = [];\n  let sensitiveContent: boolean | undefined = undefined;\n\n  for (const m of media\n    .filter(isFieldDefined('id_str'))\n    .filter(isFieldDefined('media_url_https'))) {\n    if (m.type === 'photo') {\n      photos.push({\n        id: m.id_str,\n        url: m.media_url_https,\n        alt_text: m.ext_alt_text,\n      });\n    } else if (m.type === 'video') {\n      videos.push(parseVideo(m));\n    }\n\n    const sensitive = m.ext_sensitive_media_warning;\n    if (sensitive != null) {\n      sensitiveContent =\n        sensitive.adult_content ||\n        sensitive.graphic_violence ||\n        sensitive.other;\n    }\n  }\n\n  return { sensitiveContent, photos, videos };\n}\n\nfunction parseVideo(\n  m: NonNullableField<TimelineMediaExtendedRaw, 'id_str' | 'media_url_https'>,\n): Video {\n  const video: Video = {\n    id: m.id_str,\n    preview: m.media_url_https,\n  };\n\n  let maxBitrate = 0;\n  const variants = m.video_info?.variants ?? [];\n  for (const variant of variants) {\n    const bitrate = variant.bitrate;\n    if (bitrate != null && bitrate > maxBitrate && variant.url != null) {\n      let variantUrl = variant.url;\n      const stringStart = 0;\n      const tagSuffixIdx = variantUrl.indexOf('?tag=10');\n      if (tagSuffixIdx !== -1) {\n        variantUrl = variantUrl.substring(stringStart, tagSuffixIdx + 1);\n      }\n\n      video.url = variantUrl;\n      maxBitrate = bitrate;\n    }\n  }\n\n  return video;\n}\n\nexport function reconstructTweetHtml(\n  tweet: LegacyTweetRaw,\n  photos: Photo[],\n  videos: Video[],\n): string {\n  const media: string[] = [];\n\n  // HTML parsing with regex :)\n  let html = tweet.full_text ?? '';\n\n  html = html.replace(reHashtag, linkHashtagHtml);\n  html = html.replace(reCashtag, linkCashtagHtml);\n  html = html.replace(reUsername, linkUsernameHtml);\n  html = html.replace(reTwitterUrl, unwrapTcoUrlHtml(tweet, media));\n\n  for (const { url } of photos) {\n    if (media.indexOf(url) !== -1) {\n      continue;\n    }\n\n    html += `<br><img src=\"${url}\"/>`;\n  }\n\n  for (const { preview: url } of videos) {\n    if (media.indexOf(url) !== -1) {\n      continue;\n    }\n\n    html += `<br><img src=\"${url}\"/>`;\n  }\n\n  html = html.replace(/\\n/g, '<br>');\n\n  return html;\n}\n\nfunction linkHashtagHtml(hashtag: string) {\n  return `<a href=\"https://twitter.com/hashtag/${hashtag.replace(\n    '#',\n    '',\n  )}\">${hashtag}</a>`;\n}\n\nfunction linkCashtagHtml(cashtag: string) {\n  return `<a href=\"https://twitter.com/search?q=%24${cashtag.replace(\n    '$',\n    '',\n  )}\">${cashtag}</a>`;\n}\n\nfunction linkUsernameHtml(username: string) {\n  return `<a href=\"https://twitter.com/${username.replace(\n    '@',\n    '',\n  )}\">${username}</a>`;\n}\n\nfunction unwrapTcoUrlHtml(tweet: LegacyTweetRaw, foundedMedia: string[]) {\n  return function (tco: string) {\n    for (const entity of tweet.entities?.urls ?? []) {\n      if (tco === entity.url && entity.expanded_url != null) {\n        return `<a href=\"${entity.expanded_url}\">${tco}</a>`;\n      }\n    }\n\n    for (const entity of tweet.extended_entities?.media ?? []) {\n      if (tco === entity.url && entity.media_url_https != null) {\n        foundedMedia.push(entity.media_url_https);\n        return `<br><a href=\"${tco}\"><img src=\"${entity.media_url_https}\"/></a>`;\n      }\n    }\n\n    return tco;\n  };\n}\n","import { LegacyUserRaw } from './profile';\nimport { parseMediaGroups, reconstructTweetHtml } from './timeline-tweet-util';\nimport {\n  EditControlInitialRaw,\n  LegacyTweetRaw,\n  ParseTweetResult,\n  QueryTweetsResponse,\n  SearchResultRaw,\n  TimelineResultRaw,\n} from './timeline-v1';\nimport { Tweet } from './tweets';\nimport { isFieldDefined } from './type-util';\n\nexport interface TimelineUserResultRaw {\n  rest_id?: string;\n  legacy?: LegacyUserRaw;\n  is_blue_verified?: boolean;\n}\n\nexport interface TimelineEntryItemContentRaw {\n  itemType?: string;\n  tweetDisplayType?: string;\n  tweetResult?: {\n    result?: TimelineResultRaw;\n  };\n  tweet_results?: {\n    result?: TimelineResultRaw;\n  };\n  userDisplayType?: string;\n  user_results?: {\n    result?: TimelineUserResultRaw;\n  };\n}\n\nexport interface TimelineEntryRaw {\n  entryId: string;\n  content?: {\n    cursorType?: string;\n    value?: string;\n    items?: {\n      entryId?: string;\n      item?: {\n        content?: TimelineEntryItemContentRaw;\n        itemContent?: SearchEntryItemContentRaw;\n      };\n    }[];\n    itemContent?: TimelineEntryItemContentRaw;\n  };\n}\n\nexport interface SearchEntryItemContentRaw {\n  tweetDisplayType?: string;\n  tweet_results?: {\n    result?: SearchResultRaw;\n  };\n  userDisplayType?: string;\n  user_results?: {\n    result?: TimelineUserResultRaw;\n  };\n}\n\nexport interface SearchEntryRaw {\n  entryId: string;\n  sortIndex: string;\n  content?: {\n    cursorType?: string;\n    entryType?: string;\n    __typename?: string;\n    value?: string;\n    items?: {\n      item?: {\n        content?: SearchEntryItemContentRaw;\n      };\n    }[];\n    itemContent?: SearchEntryItemContentRaw;\n  };\n}\n\nexport interface TimelineInstruction {\n  entries?: TimelineEntryRaw[];\n  entry?: TimelineEntryRaw;\n  type?: string;\n}\n\nexport interface TimelineV2 {\n  data?: {\n    user?: {\n      result?: {\n        timeline_v2?: {\n          timeline?: {\n            instructions?: TimelineInstruction[];\n          };\n        };\n      };\n    };\n  };\n}\n\nexport interface ThreadedConversation {\n  data?: {\n    threaded_conversation_with_injections_v2?: {\n      instructions?: TimelineInstruction[];\n    };\n  };\n}\n\nfunction getLegacyTweetId(tweet: Readonly<LegacyTweetRaw>): string | undefined {\n  if (tweet.id_str) {\n    return tweet.id_str;\n  }\n\n  return tweet.conversation_id_str;\n}\n\nexport function parseLegacyTweet(\n  user?: Readonly<LegacyUserRaw>,\n  tweet?: Readonly<LegacyTweetRaw>,\n  editControl?: Readonly<EditControlInitialRaw>,\n): ParseTweetResult {\n  if (tweet == null) {\n    return {\n      success: false,\n      err: new Error('Tweet was not found in the timeline object.'),\n    };\n  }\n\n  if (user == null) {\n    return {\n      success: false,\n      err: new Error('User was not found in the timeline object.'),\n    };\n  }\n\n  const tweetId = getLegacyTweetId(tweet);\n  if (!tweetId) {\n    return {\n      success: false,\n      err: new Error('Tweet ID was not found in object.'),\n    };\n  }\n\n  const hashtags = tweet.entities?.hashtags ?? [];\n  const mentions = tweet.entities?.user_mentions ?? [];\n  const media = tweet.extended_entities?.media ?? [];\n  const pinnedTweets = new Set<string | undefined>(\n    user.pinned_tweet_ids_str ?? [],\n  );\n  const urls = tweet.entities?.urls ?? [];\n  const { photos, videos, sensitiveContent } = parseMediaGroups(media);\n\n  // The edit tweets array always contains the original tweet, even if it has not been edited\n  const tweetVersions = editControl?.edit_tweet_ids ?? [tweetId];\n  const editIds = tweetVersions.filter((id) => id !== tweetId);\n\n  const tw: Tweet = {\n    __raw_UNSTABLE: tweet,\n    bookmarkCount: tweet.bookmark_count,\n    conversationId: tweet.conversation_id_str,\n    id: tweetId,\n    hashtags: hashtags\n      .filter(isFieldDefined('text'))\n      .map((hashtag) => hashtag.text),\n    likes: tweet.favorite_count,\n    mentions: mentions.filter(isFieldDefined('id_str')).map((mention) => ({\n      id: mention.id_str,\n      username: mention.screen_name,\n      name: mention.name,\n    })),\n    name: user.name,\n    permanentUrl: `https://twitter.com/${user.screen_name}/status/${tweetId}`,\n    photos,\n    replies: tweet.reply_count,\n    retweets: tweet.retweet_count,\n    text: tweet.full_text,\n    thread: [],\n    urls: urls\n      .filter(isFieldDefined('expanded_url'))\n      .map((url) => url.expanded_url),\n    userId: tweet.user_id_str,\n    username: user.screen_name,\n    videos,\n    isQuoted: false,\n    isReply: false,\n    isEdited: editIds.length > 1,\n    versions: tweetVersions,\n    isRetweet: false,\n    isPin: false,\n    sensitiveContent: false,\n  };\n\n  if (tweet.created_at) {\n    tw.timeParsed = new Date(Date.parse(tweet.created_at));\n    tw.timestamp = Math.floor(tw.timeParsed.valueOf() / 1000);\n  }\n\n  if (tweet.place?.id) {\n    tw.place = tweet.place;\n  }\n\n  const quotedStatusIdStr = tweet.quoted_status_id_str;\n  const inReplyToStatusIdStr = tweet.in_reply_to_status_id_str;\n  const retweetedStatusIdStr = tweet.retweeted_status_id_str;\n  const retweetedStatusResult = tweet.retweeted_status_result?.result;\n\n  if (quotedStatusIdStr) {\n    tw.isQuoted = true;\n    tw.quotedStatusId = quotedStatusIdStr;\n  }\n\n  if (inReplyToStatusIdStr) {\n    tw.isReply = true;\n    tw.inReplyToStatusId = inReplyToStatusIdStr;\n  }\n\n  if (retweetedStatusIdStr || retweetedStatusResult) {\n    tw.isRetweet = true;\n    tw.retweetedStatusId = retweetedStatusIdStr;\n\n    if (retweetedStatusResult) {\n      const parsedResult = parseLegacyTweet(\n        retweetedStatusResult?.core?.user_results?.result?.legacy,\n        retweetedStatusResult?.legacy,\n      );\n\n      if (parsedResult.success) {\n        tw.retweetedStatus = parsedResult.tweet;\n      }\n    }\n  }\n\n  const views = parseInt(tweet.ext_views?.count ?? '');\n  if (!isNaN(views)) {\n    tw.views = views;\n  }\n\n  if (pinnedTweets.has(tweetId)) {\n    // TODO: Update tests so this can be assigned at the tweet declaration\n    tw.isPin = true;\n  }\n\n  if (sensitiveContent) {\n    // TODO: Update tests so this can be assigned at the tweet declaration\n    tw.sensitiveContent = true;\n  }\n\n  tw.html = reconstructTweetHtml(tweet, tw.photos, tw.videos);\n\n  return { success: true, tweet: tw };\n}\n\nfunction parseResult(result?: TimelineResultRaw): ParseTweetResult {\n  const noteTweetResultText =\n    result?.note_tweet?.note_tweet_results?.result?.text;\n\n  if (result?.legacy && noteTweetResultText) {\n    result.legacy.full_text = noteTweetResultText;\n  }\n\n  const tweetResult = parseLegacyTweet(\n    result?.core?.user_results?.result?.legacy,\n    result?.legacy,\n  );\n  if (!tweetResult.success) {\n    return tweetResult;\n  }\n\n  if (!tweetResult.tweet.views && result?.views?.count) {\n    const views = parseInt(result.views.count);\n    if (!isNaN(views)) {\n      tweetResult.tweet.views = views;\n    }\n  }\n\n  const quotedResult = result?.quoted_status_result?.result;\n  if (quotedResult) {\n    if (quotedResult.legacy && quotedResult.rest_id) {\n      quotedResult.legacy.id_str = quotedResult.rest_id;\n    }\n\n    const quotedTweetResult = parseResult(quotedResult);\n    if (quotedTweetResult.success) {\n      tweetResult.tweet.quotedStatus = quotedTweetResult.tweet;\n    }\n  }\n\n  return tweetResult;\n}\n\nconst expectedEntryTypes = ['tweet', 'profile-conversation'];\n\nexport function parseTimelineTweetsV2(\n  timeline: TimelineV2,\n): QueryTweetsResponse {\n  let bottomCursor: string | undefined;\n  let topCursor: string | undefined;\n  const tweets: Tweet[] = [];\n  const instructions =\n    timeline.data?.user?.result?.timeline_v2?.timeline?.instructions ?? [];\n  for (const instruction of instructions) {\n    const entries = instruction.entries ?? [];\n\n    for (const entry of entries) {\n      const entryContent = entry.content;\n      if (!entryContent) continue;\n\n      // Handle pagination\n      if (entryContent.cursorType === 'Bottom') {\n        bottomCursor = entryContent.value;\n        continue;\n      } else if (entryContent.cursorType === 'Top') {\n        topCursor = entryContent.value;\n        continue;\n      }\n\n      const idStr = entry.entryId;\n      if (\n        !expectedEntryTypes.some((entryType) => idStr.startsWith(entryType))\n      ) {\n        continue;\n      }\n\n      if (entryContent.itemContent) {\n        // Typically TimelineTimelineTweet entries\n        parseAndPush(tweets, entryContent.itemContent, idStr);\n      } else if (entryContent.items) {\n        // Typically TimelineTimelineModule entries\n        for (const item of entryContent.items) {\n          if (item.item?.itemContent) {\n            parseAndPush(tweets, item.item.itemContent, idStr);\n          }\n        }\n      }\n    }\n  }\n\n  return { tweets, next: bottomCursor, previous: topCursor };\n}\n\nexport function parseTimelineEntryItemContentRaw(\n  content: TimelineEntryItemContentRaw,\n  entryId: string,\n  isConversation = false,\n) {\n  let result = content.tweet_results?.result ?? content.tweetResult?.result;\n  if (\n    result?.__typename === 'Tweet' ||\n    (result?.__typename === 'TweetWithVisibilityResults' && result?.tweet)\n  ) {\n    if (result?.__typename === 'TweetWithVisibilityResults')\n      result = result.tweet;\n\n    if (result?.legacy) {\n      result.legacy.id_str =\n        result.rest_id ??\n        entryId.replace('conversation-', '').replace('tweet-', '');\n    }\n\n    const tweetResult = parseResult(result);\n    if (tweetResult.success) {\n      if (isConversation) {\n        if (content?.tweetDisplayType === 'SelfThread') {\n          tweetResult.tweet.isSelfThread = true;\n        }\n      }\n\n      return tweetResult.tweet;\n    }\n  }\n\n  return null;\n}\n\nexport function parseAndPush(\n  tweets: Tweet[],\n  content: TimelineEntryItemContentRaw,\n  entryId: string,\n  isConversation = false,\n) {\n  const tweet = parseTimelineEntryItemContentRaw(\n    content,\n    entryId,\n    isConversation,\n  );\n\n  if (tweet) {\n    tweets.push(tweet);\n  }\n}\n\nexport function parseThreadedConversation(\n  conversation: ThreadedConversation,\n): Tweet[] {\n  const tweets: Tweet[] = [];\n  const instructions =\n    conversation.data?.threaded_conversation_with_injections_v2?.instructions ??\n    [];\n\n  for (const instruction of instructions) {\n    const entries = instruction.entries ?? [];\n    for (const entry of entries) {\n      const entryContent = entry.content?.itemContent;\n      if (entryContent) {\n        parseAndPush(tweets, entryContent, entry.entryId, true);\n      }\n\n      for (const item of entry.content?.items ?? []) {\n        const itemContent = item.item?.itemContent;\n        if (itemContent) {\n          parseAndPush(tweets, itemContent, entry.entryId, true);\n        }\n      }\n    }\n  }\n\n  for (const tweet of tweets) {\n    if (tweet.inReplyToStatusId) {\n      for (const parentTweet of tweets) {\n        if (parentTweet.id === tweet.inReplyToStatusId) {\n          tweet.inReplyToStatus = parentTweet;\n          break;\n        }\n      }\n    }\n\n    if (tweet.isSelfThread && tweet.conversationId === tweet.id) {\n      for (const childTweet of tweets) {\n        if (childTweet.isSelfThread && childTweet.id !== tweet.id) {\n          tweet.thread.push(childTweet);\n        }\n      }\n\n      if (tweet.thread.length === 0) {\n        tweet.isSelfThread = false;\n      }\n    }\n  }\n\n  return tweets;\n}\n","import { Profile, parseProfile } from './profile';\nimport { QueryProfilesResponse, QueryTweetsResponse } from './timeline-v1';\nimport { SearchEntryRaw, parseLegacyTweet } from './timeline-v2';\nimport { Tweet } from './tweets';\n\nexport interface SearchTimeline {\n  data?: {\n    search_by_raw_query?: {\n      search_timeline?: {\n        timeline?: {\n          instructions?: {\n            entries?: SearchEntryRaw[];\n            entry?: SearchEntryRaw;\n            type?: string;\n          }[];\n        };\n      };\n    };\n  };\n}\n\nexport function parseSearchTimelineTweets(\n  timeline: SearchTimeline,\n): QueryTweetsResponse {\n  let bottomCursor: string | undefined;\n  let topCursor: string | undefined;\n  const tweets: Tweet[] = [];\n  const instructions =\n    timeline.data?.search_by_raw_query?.search_timeline?.timeline\n      ?.instructions ?? [];\n  for (const instruction of instructions) {\n    if (\n      instruction.type === 'TimelineAddEntries' ||\n      instruction.type === 'TimelineReplaceEntry'\n    ) {\n      if (instruction.entry?.content?.cursorType === 'Bottom') {\n        bottomCursor = instruction.entry.content.value;\n        continue;\n      } else if (instruction.entry?.content?.cursorType === 'Top') {\n        topCursor = instruction.entry.content.value;\n        continue;\n      }\n\n      const entries = instruction.entries ?? [];\n      for (const entry of entries) {\n        const itemContent = entry.content?.itemContent;\n        if (itemContent?.tweetDisplayType === 'Tweet') {\n          const tweetResultRaw = itemContent.tweet_results?.result;\n          const tweetResult = parseLegacyTweet(\n            tweetResultRaw?.core?.user_results?.result?.legacy,\n            tweetResultRaw?.legacy,\n            tweetResultRaw?.edit_control?.edit_control_initial,\n          );\n\n          if (tweetResult.success) {\n            if (!tweetResult.tweet.views && tweetResultRaw?.views?.count) {\n              const views = parseInt(tweetResultRaw.views.count);\n              if (!isNaN(views)) {\n                tweetResult.tweet.views = views;\n              }\n            }\n\n            tweets.push(tweetResult.tweet);\n          }\n        } else if (entry.content?.cursorType === 'Bottom') {\n          bottomCursor = entry.content.value;\n        } else if (entry.content?.cursorType === 'Top') {\n          topCursor = entry.content.value;\n        }\n      }\n    }\n  }\n\n  return { tweets, next: bottomCursor, previous: topCursor };\n}\n\nexport function parseSearchTimelineUsers(\n  timeline: SearchTimeline,\n): QueryProfilesResponse {\n  let bottomCursor: string | undefined;\n  let topCursor: string | undefined;\n  const profiles: Profile[] = [];\n  const instructions =\n    timeline.data?.search_by_raw_query?.search_timeline?.timeline\n      ?.instructions ?? [];\n\n  for (const instruction of instructions) {\n    if (\n      instruction.type === 'TimelineAddEntries' ||\n      instruction.type === 'TimelineReplaceEntry'\n    ) {\n      if (instruction.entry?.content?.cursorType === 'Bottom') {\n        bottomCursor = instruction.entry.content.value;\n        continue;\n      } else if (instruction.entry?.content?.cursorType === 'Top') {\n        topCursor = instruction.entry.content.value;\n        continue;\n      }\n\n      const entries = instruction.entries ?? [];\n      for (const entry of entries) {\n        const itemContent = entry.content?.itemContent;\n        if (itemContent?.userDisplayType === 'User') {\n          const userResultRaw = itemContent.user_results?.result;\n\n          if (userResultRaw?.legacy) {\n            const profile = parseProfile(\n              userResultRaw.legacy,\n              userResultRaw.is_blue_verified,\n            );\n\n            if (!profile.userId) {\n              profile.userId = userResultRaw.rest_id;\n            }\n\n            profiles.push(profile);\n          }\n        } else if (entry.content?.cursorType === 'Bottom') {\n          bottomCursor = entry.content.value;\n        } else if (entry.content?.cursorType === 'Top') {\n          topCursor = entry.content.value;\n        }\n      }\n    }\n  }\n\n  return { profiles, next: bottomCursor, previous: topCursor };\n}\n","import { addApiFeatures, requestApi } from './api';\nimport { TwitterAuth } from './auth';\nimport { Profile } from './profile';\nimport { QueryProfilesResponse, QueryTweetsResponse } from './timeline-v1';\nimport { getTweetTimeline, getUserTimeline } from './timeline-async';\nimport { Tweet } from './tweets';\nimport {\n  SearchTimeline,\n  parseSearchTimelineTweets,\n  parseSearchTimelineUsers,\n} from './timeline-search';\nimport stringify from 'json-stable-stringify';\n\n/**\n * The categories that can be used in Twitter searches.\n */\nexport enum SearchMode {\n  Top,\n  Latest,\n  Photos,\n  Videos,\n  Users,\n}\n\nexport function searchTweets(\n  query: string,\n  maxTweets: number,\n  searchMode: SearchMode,\n  auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n  return getTweetTimeline(query, maxTweets, (q, mt, c) => {\n    return fetchSearchTweets(q, mt, searchMode, auth, c);\n  });\n}\n\nexport function searchProfiles(\n  query: string,\n  maxProfiles: number,\n  auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n  return getUserTimeline(query, maxProfiles, (q, mt, c) => {\n    return fetchSearchProfiles(q, mt, auth, c);\n  });\n}\n\nexport async function fetchSearchTweets(\n  query: string,\n  maxTweets: number,\n  searchMode: SearchMode,\n  auth: TwitterAuth,\n  cursor?: string,\n): Promise<QueryTweetsResponse> {\n  const timeline = await getSearchTimeline(\n    query,\n    maxTweets,\n    searchMode,\n    auth,\n    cursor,\n  );\n\n  return parseSearchTimelineTweets(timeline);\n}\n\nexport async function fetchSearchProfiles(\n  query: string,\n  maxProfiles: number,\n  auth: TwitterAuth,\n  cursor?: string,\n): Promise<QueryProfilesResponse> {\n  const timeline = await getSearchTimeline(\n    query,\n    maxProfiles,\n    SearchMode.Users,\n    auth,\n    cursor,\n  );\n\n  return parseSearchTimelineUsers(timeline);\n}\n\nasync function getSearchTimeline(\n  query: string,\n  maxItems: number,\n  searchMode: SearchMode,\n  auth: TwitterAuth,\n  cursor?: string,\n): Promise<SearchTimeline> {\n  if (!auth.isLoggedIn()) {\n    throw new Error('Scraper is not logged-in for search.');\n  }\n\n  if (maxItems > 50) {\n    maxItems = 50;\n  }\n\n  const variables: Record<string, any> = {\n    rawQuery: query,\n    count: maxItems,\n    querySource: 'typed_query',\n    product: 'Top',\n  };\n\n  const features = addApiFeatures({\n    longform_notetweets_inline_media_enabled: true,\n    responsive_web_enhance_cards_enabled: false,\n    responsive_web_media_download_video_enabled: false,\n    responsive_web_twitter_article_tweet_consumption_enabled: false,\n    tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n      true,\n    interactive_text_enabled: false,\n    responsive_web_text_conversations_enabled: false,\n    vibe_api_enabled: false,\n  });\n\n  const fieldToggles: Record<string, any> = {\n    withArticleRichContentState: false,\n  };\n\n  if (cursor != null && cursor != '') {\n    variables['cursor'] = cursor;\n  }\n\n  switch (searchMode) {\n    case SearchMode.Latest:\n      variables.product = 'Latest';\n      break;\n    case SearchMode.Photos:\n      variables.product = 'Photos';\n      break;\n    case SearchMode.Videos:\n      variables.product = 'Videos';\n      break;\n    case SearchMode.Users:\n      variables.product = 'People';\n      break;\n    default:\n      break;\n  }\n\n  const params = new URLSearchParams();\n  params.set('features', stringify(features));\n  params.set('fieldToggles', stringify(fieldToggles));\n  params.set('variables', stringify(variables));\n\n  const res = await requestApi<SearchTimeline>(\n    `https://api.twitter.com/graphql/gkjsKepM6gl_HmFWoWKfgg/SearchTimeline?${params.toString()}`,\n    auth,\n  );\n\n  if (!res.success) {\n    throw res.err;\n  }\n\n  return res.value;\n}\n","import { Profile, parseProfile } from './profile';\nimport { QueryProfilesResponse } from './timeline-v1';\nimport { TimelineUserResultRaw } from './timeline-v2';\n\nexport interface RelationshipEntryItemContentRaw {\n  itemType?: string;\n  userDisplayType?: string;\n  user_results?: {\n    result?: TimelineUserResultRaw;\n  };\n}\n\nexport interface RelationshipEntryRaw {\n  entryId: string;\n  sortIndex: string;\n  content?: {\n    cursorType?: string;\n    entryType?: string;\n    __typename?: string;\n    value?: string;\n    itemContent?: RelationshipEntryItemContentRaw;\n  };\n}\n\nexport interface RelationshipTimeline {\n  data?: {\n    user?: {\n      result?: {\n        timeline?: {\n          timeline?: {\n            instructions?: {\n              entries?: RelationshipEntryRaw[];\n              entry?: RelationshipEntryRaw;\n              type?: string;\n            }[];\n          };\n        };\n      };\n    };\n  };\n}\n\nexport function parseRelationshipTimeline(\n  timeline: RelationshipTimeline,\n): QueryProfilesResponse {\n  let bottomCursor: string | undefined;\n  let topCursor: string | undefined;\n  const profiles: Profile[] = [];\n  const instructions =\n    timeline.data?.user?.result?.timeline?.timeline?.instructions ?? [];\n\n  for (const instruction of instructions) {\n    if (\n      instruction.type === 'TimelineAddEntries' ||\n      instruction.type === 'TimelineReplaceEntry'\n    ) {\n      if (instruction.entry?.content?.cursorType === 'Bottom') {\n        bottomCursor = instruction.entry.content.value;\n        continue;\n      }\n\n      if (instruction.entry?.content?.cursorType === 'Top') {\n        topCursor = instruction.entry.content.value;\n        continue;\n      }\n\n      const entries = instruction.entries ?? [];\n      for (const entry of entries) {\n        const itemContent = entry.content?.itemContent;\n        if (itemContent?.userDisplayType === 'User') {\n          const userResultRaw = itemContent.user_results?.result;\n\n          if (userResultRaw?.legacy) {\n            const profile = parseProfile(\n              userResultRaw.legacy,\n              userResultRaw.is_blue_verified,\n            );\n\n            if (!profile.userId) {\n              profile.userId = userResultRaw.rest_id;\n            }\n\n            profiles.push(profile);\n          }\n        } else if (entry.content?.cursorType === 'Bottom') {\n          bottomCursor = entry.content.value;\n        } else if (entry.content?.cursorType === 'Top') {\n          topCursor = entry.content.value;\n        }\n      }\n    }\n  }\n\n  return { profiles, next: bottomCursor, previous: topCursor };\n}\n","import { addApiFeatures, requestApi } from './api';\nimport { TwitterAuth } from './auth';\nimport { Profile, getUserIdByScreenName } from './profile';\nimport { QueryProfilesResponse } from './timeline-v1';\nimport { getUserTimeline } from './timeline-async';\nimport {\n  RelationshipTimeline,\n  parseRelationshipTimeline,\n} from './timeline-relationship';\nimport stringify from 'json-stable-stringify';\n\nexport function getFollowing(\n  userId: string,\n  maxProfiles: number,\n  auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n  return getUserTimeline(userId, maxProfiles, (q, mt, c) => {\n    return fetchProfileFollowing(q, mt, auth, c);\n  });\n}\n\nexport function getFollowers(\n  userId: string,\n  maxProfiles: number,\n  auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n  return getUserTimeline(userId, maxProfiles, (q, mt, c) => {\n    return fetchProfileFollowers(q, mt, auth, c);\n  });\n}\n\nexport async function fetchProfileFollowing(\n  userId: string,\n  maxProfiles: number,\n  auth: TwitterAuth,\n  cursor?: string,\n): Promise<QueryProfilesResponse> {\n  const timeline = await getFollowingTimeline(\n    userId,\n    maxProfiles,\n    auth,\n    cursor,\n  );\n\n  return parseRelationshipTimeline(timeline);\n}\n\nexport async function fetchProfileFollowers(\n  userId: string,\n  maxProfiles: number,\n  auth: TwitterAuth,\n  cursor?: string,\n): Promise<QueryProfilesResponse> {\n  const timeline = await getFollowersTimeline(\n    userId,\n    maxProfiles,\n    auth,\n    cursor,\n  );\n\n  return parseRelationshipTimeline(timeline);\n}\n\nasync function getFollowingTimeline(\n  userId: string,\n  maxItems: number,\n  auth: TwitterAuth,\n  cursor?: string,\n): Promise<RelationshipTimeline> {\n  if (!auth.isLoggedIn()) {\n    throw new Error('Scraper is not logged-in for profile following.');\n  }\n\n  if (maxItems > 50) {\n    maxItems = 50;\n  }\n\n  const variables: Record<string, any> = {\n    userId,\n    count: maxItems,\n    includePromotedContent: false,\n  };\n\n  const features = addApiFeatures({\n    responsive_web_twitter_article_tweet_consumption_enabled: false,\n    tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n      true,\n    longform_notetweets_inline_media_enabled: true,\n    responsive_web_media_download_video_enabled: false,\n  });\n\n  if (cursor != null && cursor != '') {\n    variables['cursor'] = cursor;\n  }\n\n  const params = new URLSearchParams();\n  params.set('features', stringify(features));\n  params.set('variables', stringify(variables));\n\n  const res = await requestApi<RelationshipTimeline>(\n    `https://twitter.com/i/api/graphql/iSicc7LrzWGBgDPL0tM_TQ/Following?${params.toString()}`,\n    auth,\n  );\n\n  if (!res.success) {\n    throw res.err;\n  }\n\n  return res.value;\n}\n\nasync function getFollowersTimeline(\n  userId: string,\n  maxItems: number,\n  auth: TwitterAuth,\n  cursor?: string,\n): Promise<RelationshipTimeline> {\n  if (!auth.isLoggedIn()) {\n    throw new Error('Scraper is not logged-in for profile followers.');\n  }\n\n  if (maxItems > 50) {\n    maxItems = 50;\n  }\n\n  const variables: Record<string, any> = {\n    userId,\n    count: maxItems,\n    includePromotedContent: false,\n  };\n\n  const features = addApiFeatures({\n    responsive_web_twitter_article_tweet_consumption_enabled: false,\n    tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n      true,\n    longform_notetweets_inline_media_enabled: true,\n    responsive_web_media_download_video_enabled: false,\n  });\n\n  if (cursor != null && cursor != '') {\n    variables['cursor'] = cursor;\n  }\n\n  const params = new URLSearchParams();\n  params.set('features', stringify(features));\n  params.set('variables', stringify(variables));\n\n  const res = await requestApi<RelationshipTimeline>(\n    `https://twitter.com/i/api/graphql/rRXFSG5vR6drKr5M37YOTw/Followers?${params.toString()}`,\n    auth,\n  );\n\n  if (!res.success) {\n    throw res.err;\n  }\n\n  return res.value;\n}\n","import { addApiParams, requestApi } from './api';\nimport { TwitterAuth } from './auth';\nimport { TimelineV1 } from './timeline-v1';\n\nexport async function getTrends(auth: TwitterAuth): Promise<string[]> {\n  const params = new URLSearchParams();\n  addApiParams(params, false);\n\n  params.set('count', '20');\n  params.set('candidate_source', 'trends');\n  params.set('include_page_configuration', 'false');\n  params.set('entity_tokens', 'false');\n\n  const res = await requestApi<TimelineV1>(\n    `https://api.twitter.com/2/guide.json?${params.toString()}`,\n    auth,\n  );\n  if (!res.success) {\n    throw res.err;\n  }\n\n  const instructions = res.value.timeline?.instructions ?? [];\n  if (instructions.length < 2) {\n    throw new Error('No trend entries found.');\n  }\n\n  // Some of this is silly, but for now we're assuming we know nothing about the\n  // data, and that anything can be missing. Go has non-nilable strings and empty\n  // slices are nil, so it largely doesn't need to worry about this.\n  const entries = instructions[1].addEntries?.entries ?? [];\n  if (entries.length < 2) {\n    throw new Error('No trend entries found.');\n  }\n\n  const items = entries[1].content?.timelineModule?.items ?? [];\n  const trends: string[] = [];\n  for (const item of items) {\n    const trend =\n      item.item?.clientEventInfo?.details?.guideDetails?.transparentGuideDetails\n        ?.trendMetadata?.trendName;\n    if (trend != null) {\n      trends.push(trend);\n    }\n  }\n\n  return trends;\n}\n","import stringify from 'json-stable-stringify';\n\n/**\n * Examples of requests to API endpoints. These are parsed at runtime and used\n * as templates for requests to a particular endpoint. Please ensure these do\n * not contain any information that you do not want published to NPM.\n */\nconst endpoints = {\n  // TODO: Migrate other endpoint URLs here\n  UserTweets:\n    'https://twitter.com/i/api/graphql/V7H0Ap3_Hh2FyS75OCDO3Q/UserTweets?variables=%7B%22userId%22%3A%224020276615%22%2C%22count%22%3A20%2C%22includePromotedContent%22%3Atrue%2C%22withQuickPromoteEligibilityTweetFields%22%3Atrue%2C%22withVoice%22%3Atrue%2C%22withV2Timeline%22%3Atrue%7D&features=%7B%22rweb_tipjar_consumption_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22articles_preview_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22creator_subscriptions_quote_tweet_preview_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22rweb_video_timestamps_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticlePlainText%22%3Afalse%7D',\n  UserTweetsAndReplies:\n    'https://twitter.com/i/api/graphql/E4wA5vo2sjVyvpliUffSCw/UserTweetsAndReplies?variables=%7B%22userId%22%3A%224020276615%22%2C%22count%22%3A40%2C%22cursor%22%3A%22DAABCgABGPWl-F-ATiIKAAIY9YfiF1rRAggAAwAAAAEAAA%22%2C%22includePromotedContent%22%3Atrue%2C%22withCommunity%22%3Atrue%2C%22withVoice%22%3Atrue%2C%22withV2Timeline%22%3Atrue%7D&features=%7B%22rweb_tipjar_consumption_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22articles_preview_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22creator_subscriptions_quote_tweet_preview_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22rweb_video_timestamps_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticlePlainText%22%3Afalse%7D',\n  UserLikedTweets:\n    'https://twitter.com/i/api/graphql/eSSNbhECHHWWALkkQq-YTA/Likes?variables=%7B%22userId%22%3A%222244196397%22%2C%22count%22%3A20%2C%22includePromotedContent%22%3Afalse%2C%22withClientEventToken%22%3Afalse%2C%22withBirdwatchNotes%22%3Afalse%2C%22withVoice%22%3Atrue%2C%22withV2Timeline%22%3Atrue%7D&features=%7B%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22rweb_video_timestamps_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D',\n  TweetDetail:\n    'https://twitter.com/i/api/graphql/xOhkmRac04YFZmOzU9PJHg/TweetDetail?variables=%7B%22focalTweetId%22%3A%221237110546383724547%22%2C%22with_rux_injections%22%3Afalse%2C%22includePromotedContent%22%3Atrue%2C%22withCommunity%22%3Atrue%2C%22withQuickPromoteEligibilityTweetFields%22%3Atrue%2C%22withBirdwatchNotes%22%3Atrue%2C%22withVoice%22%3Atrue%2C%22withV2Timeline%22%3Atrue%7D&features=%7B%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Afalse%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_media_download_video_enabled%22%3Afalse%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticleRichContentState%22%3Afalse%7D',\n  TweetResultByRestId:\n    'https://twitter.com/i/api/graphql/DJS3BdhUhcaEpZ7B7irJDg/TweetResultByRestId?variables=%7B%22tweetId%22%3A%221237110546383724547%22%2C%22withCommunity%22%3Afalse%2C%22includePromotedContent%22%3Afalse%2C%22withVoice%22%3Afalse%7D&features=%7B%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Afalse%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22responsive_web_media_download_video_enabled%22%3Afalse%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D',\n  ListTweets:\n    'https://twitter.com/i/api/graphql/whF0_KH1fCkdLLoyNPMoEw/ListLatestTweetsTimeline?variables=%7B%22listId%22%3A%221736495155002106192%22%2C%22count%22%3A20%7D&features=%7B%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Afalse%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22rweb_video_timestamps_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_media_download_video_enabled%22%3Afalse%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D',\n} as const;\n\nexport interface EndpointFieldInfo {\n  /**\n   * Request variables, used for providing arguments such as user IDs or result counts.\n   */\n  variables: Record<string, unknown>;\n\n  /**\n   * Request features, used for encoding feature flags into the request. These may either be\n   * boolean values or numerically-encoded booleans (1 or 0). It is possible this may change\n   * to include other representations of booleans as Twitter's backend evolves.\n   */\n  features: Record<string, unknown>;\n\n  /**\n   * Request field toggles, used for limiting how returned fields are represented. This is\n   * rarely used.\n   */\n  fieldToggles: Record<string, unknown>;\n}\n\ntype SomePartial<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\n\ntype EndpointVersion = string;\ntype EndpointName = string;\ntype EncodedVariables = string;\ntype EncodedFeatures = string;\ntype EncodedFieldToggles = string;\n\n// TODO: Set up field-level Intellisense for the QraphQL parameters in these?\ntype EndpointFields<EndpointUrl> =\n  EndpointUrl extends `https://twitter.com/i/api/graphql/${EndpointVersion}/${EndpointName}?variables=${EncodedVariables}&features=${EncodedFeatures}&fieldToggles=${EncodedFieldToggles}`\n    ? EndpointFieldInfo\n    : EndpointUrl extends `https://twitter.com/i/api/graphql/${EndpointVersion}/${EndpointName}?variables=${EncodedVariables}&features=${EncodedFeatures}`\n    ? SomePartial<EndpointFieldInfo, 'fieldToggles'>\n    : EndpointUrl extends `https://twitter.com/i/api/graphql/${EndpointVersion}/${EndpointName}?variables=${EncodedVariables}`\n    ? SomePartial<EndpointFieldInfo, 'features' | 'fieldToggles'>\n    : Partial<EndpointFieldInfo>;\n\nexport type ApiRequestInfo<EndpointUrl> = EndpointFields<EndpointUrl> & {\n  /**\n   * The URL, without any GraphQL query parameters.\n   */\n  url: string;\n\n  /**\n   * Converts the request back into a URL to be sent to the Twitter API.\n   */\n  toRequestUrl(): string;\n};\n\n/** Wrapper class for API request information. */\nclass ApiRequest<EndpointUrl> {\n  url: string;\n  variables?: Record<string, unknown> | undefined;\n  features?: Record<string, unknown> | undefined;\n  fieldToggles?: Record<string, unknown> | undefined;\n\n  constructor(info: Omit<ApiRequestInfo<EndpointUrl>, 'toRequestUrl'>) {\n    this.url = info.url;\n    this.variables = info.variables;\n    this.features = info.features;\n    this.fieldToggles = info.fieldToggles;\n  }\n\n  toRequestUrl(): string {\n    const params = new URLSearchParams();\n\n    // Only include query parameters with values\n    if (this.variables) {\n      // Stringify with the query keys in sorted order like the Go package\n      params.set('variables', stringify(this.variables));\n    }\n\n    if (this.features) {\n      params.set('features', stringify(this.features));\n    }\n\n    if (this.fieldToggles) {\n      params.set('fieldToggles', stringify(this.fieldToggles));\n    }\n\n    return `${this.url}?${params.toString()}`;\n  }\n}\n\n/**\n * Parses information from a Twitter API endpoint using an example request\n * URL against that endpoint. This can be used to extract GraphQL parameters\n * in order to easily reuse and/or override them later.\n * @param example An example of the endpoint to analyze.\n * @returns The parsed endpoint information.\n */\nfunction parseEndpointExample<\n  Endpoints,\n  Endpoint extends string & keyof Endpoints,\n>(example: Endpoint): ApiRequestInfo<Endpoints[Endpoint]> {\n  const { protocol, host, pathname, searchParams: query } = new URL(example);\n\n  const base = `${protocol}//${host}${pathname}`;\n  const variables = query.get('variables');\n  const features = query.get('features');\n  const fieldToggles = query.get('fieldToggles');\n\n  return new ApiRequest<Endpoints[Endpoint]>({\n    url: base,\n    variables: variables ? JSON.parse(variables) : undefined,\n    features: features ? JSON.parse(features) : undefined,\n    fieldToggles: fieldToggles ? JSON.parse(fieldToggles) : undefined,\n  } as Omit<ApiRequestInfo<Endpoints[Endpoint]>, 'toRequestUrl'>) as ApiRequestInfo<\n    Endpoints[Endpoint]\n  >;\n}\n\ntype ApiRequestFactory<Endpoints> = {\n  [Endpoint in keyof Endpoints as `create${string &\n    Endpoint}Request`]: () => ApiRequestInfo<Endpoints[Endpoint]>;\n};\n\nfunction createApiRequestFactory<Endpoints extends Record<string, string>>(\n  endpoints: Endpoints,\n): ApiRequestFactory<Endpoints> {\n  type UntypedApiRequestFactory = ApiRequestFactory<Record<string, string>>;\n\n  return Object.entries(endpoints)\n    .map<UntypedApiRequestFactory>(([endpointName, endpointExample]) => {\n      // Create a partial factory for only one endpoint\n      return {\n        [`create${endpointName}Request`]: () => {\n          // Create a new instance on each invocation so that we can safely\n          // mutate requests before sending them off\n          return parseEndpointExample<Endpoints, any>(endpointExample);\n        },\n      };\n    })\n    .reduce((agg, next) => {\n      // Merge all of our factories into one that includes every endpoint\n      return Object.assign(agg, next);\n    }) as ApiRequestFactory<Endpoints>;\n}\n\nexport const apiRequestFactory = createApiRequestFactory(endpoints);\n","import { QueryTweetsResponse } from './timeline-v1';\nimport { parseAndPush, TimelineEntryRaw } from './timeline-v2';\nimport { Tweet } from './tweets';\n\nexport interface ListTimeline {\n  data?: {\n    list?: {\n      tweets_timeline?: {\n        timeline?: {\n          instructions?: {\n            entries?: TimelineEntryRaw[];\n            entry?: TimelineEntryRaw;\n            type?: string;\n          }[];\n        };\n      };\n    };\n  };\n}\n\nexport function parseListTimelineTweets(\n  timeline: ListTimeline,\n): QueryTweetsResponse {\n  let bottomCursor: string | undefined;\n  let topCursor: string | undefined;\n  const tweets: Tweet[] = [];\n  const instructions =\n    timeline.data?.list?.tweets_timeline?.timeline?.instructions ?? [];\n  for (const instruction of instructions) {\n    const entries = instruction.entries ?? [];\n\n    for (const entry of entries) {\n      const entryContent = entry.content;\n      if (!entryContent) continue;\n\n      if (entryContent.cursorType === 'Bottom') {\n        bottomCursor = entryContent.value;\n        continue;\n      } else if (entryContent.cursorType === 'Top') {\n        topCursor = entryContent.value;\n        continue;\n      }\n\n      const idStr = entry.entryId;\n      if (\n        !idStr.startsWith('tweet') &&\n        !idStr.startsWith('list-conversation')\n      ) {\n        continue;\n      }\n\n      if (entryContent.itemContent) {\n        parseAndPush(tweets, entryContent.itemContent, idStr);\n      } else if (entryContent.items) {\n        for (const contentItem of entryContent.items) {\n          if (\n            contentItem.item &&\n            contentItem.item.itemContent &&\n            contentItem.entryId\n          ) {\n            parseAndPush(\n              tweets,\n              contentItem.item.itemContent,\n              contentItem.entryId.split('tweet-')[1],\n            );\n          }\n        }\n      }\n    }\n  }\n\n  return { tweets, next: bottomCursor, previous: topCursor };\n}\n","import { addApiFeatures, requestApi } from './api';\nimport { TwitterAuth } from './auth';\nimport { getUserIdByScreenName } from './profile';\nimport { LegacyTweetRaw, QueryTweetsResponse } from './timeline-v1';\nimport {\n  parseTimelineTweetsV2,\n  TimelineV2,\n  TimelineEntryItemContentRaw,\n  parseTimelineEntryItemContentRaw,\n  ThreadedConversation,\n  parseThreadedConversation,\n} from './timeline-v2';\nimport { getTweetTimeline, getTweetTimelineCursor } from './timeline-async';\nimport { apiRequestFactory } from './api-data';\nimport { ListTimeline, parseListTimelineTweets } from './timeline-list';\n\nexport interface Mention {\n  id: string;\n  username?: string;\n  name?: string;\n}\n\nexport interface Photo {\n  id: string;\n  url: string;\n  alt_text: string | undefined;\n}\n\nexport interface Video {\n  id: string;\n  preview: string;\n  url?: string;\n}\n\nexport interface PlaceRaw {\n  id?: string;\n  place_type?: string;\n  name?: string;\n  full_name?: string;\n  country_code?: string;\n  country?: string;\n  bounding_box?: {\n    type?: string;\n    coordinates?: number[][][];\n  };\n}\n\n/**\n * A parsed Tweet object.\n */\nexport interface Tweet {\n  __raw_UNSTABLE?: LegacyTweetRaw;\n  bookmarkCount?: number;\n  conversationId?: string;\n  hashtags: string[];\n  html?: string;\n  id?: string;\n  inReplyToStatus?: Tweet;\n  inReplyToStatusId?: string;\n  isEdited?: boolean;\n  versions?: string[];\n  isQuoted?: boolean;\n  isPin?: boolean;\n  isReply?: boolean;\n  isRetweet?: boolean;\n  isSelfThread?: boolean;\n  likes?: number;\n  name?: string;\n  mentions: Mention[];\n  permanentUrl?: string;\n  photos: Photo[];\n  place?: PlaceRaw;\n  quotedStatus?: Tweet;\n  quotedStatusId?: string;\n  replies?: number;\n  retweets?: number;\n  retweetedStatus?: Tweet;\n  retweetedStatusId?: string;\n  text?: string;\n  thread: Tweet[];\n  timeParsed?: Date;\n  timestamp?: number;\n  urls: string[];\n  userId?: string;\n  username?: string;\n  videos: Video[];\n  views?: number;\n  sensitiveContent?: boolean;\n}\n\nexport type TweetQuery =\n  | Partial<Tweet>\n  | ((tweet: Tweet) => boolean | Promise<boolean>);\n\nexport const features = addApiFeatures({\n  interactive_text_enabled: true,\n  longform_notetweets_inline_media_enabled: false,\n  responsive_web_text_conversations_enabled: false,\n  tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n    false,\n  vibe_api_enabled: false,\n});\n\nexport async function fetchTweets(\n  userId: string,\n  maxTweets: number,\n  cursor: string | undefined,\n  auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n  if (maxTweets > 200) {\n    maxTweets = 200;\n  }\n\n  const userTweetsRequest = apiRequestFactory.createUserTweetsRequest();\n  userTweetsRequest.variables.userId = userId;\n  userTweetsRequest.variables.count = maxTweets;\n  userTweetsRequest.variables.includePromotedContent = false; // true on the website\n\n  if (cursor != null && cursor != '') {\n    userTweetsRequest.variables['cursor'] = cursor;\n  }\n\n  const res = await requestApi<TimelineV2>(\n    userTweetsRequest.toRequestUrl(),\n    auth,\n  );\n\n  if (!res.success) {\n    throw res.err;\n  }\n\n  return parseTimelineTweetsV2(res.value);\n}\n\nexport async function fetchTweetsAndReplies(\n  userId: string,\n  maxTweets: number,\n  cursor: string | undefined,\n  auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n  if (maxTweets > 40) {\n    maxTweets = 40;\n  }\n\n  const userTweetsRequest =\n    apiRequestFactory.createUserTweetsAndRepliesRequest();\n  userTweetsRequest.variables.userId = userId;\n  userTweetsRequest.variables.count = maxTweets;\n  userTweetsRequest.variables.includePromotedContent = false; // true on the website\n\n  if (cursor != null && cursor != '') {\n    userTweetsRequest.variables['cursor'] = cursor;\n  }\n\n  const res = await requestApi<TimelineV2>(\n    userTweetsRequest.toRequestUrl(),\n    auth,\n  );\n\n  if (!res.success) {\n    throw res.err;\n  }\n\n  return parseTimelineTweetsV2(res.value);\n}\n\nexport async function fetchListTweets(\n  listId: string,\n  maxTweets: number,\n  cursor: string | undefined,\n  auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n  if (maxTweets > 200) {\n    maxTweets = 200;\n  }\n\n  const listTweetsRequest = apiRequestFactory.createListTweetsRequest();\n  listTweetsRequest.variables.listId = listId;\n  listTweetsRequest.variables.count = maxTweets;\n\n  if (cursor != null && cursor != '') {\n    listTweetsRequest.variables['cursor'] = cursor;\n  }\n\n  const res = await requestApi<ListTimeline>(\n    listTweetsRequest.toRequestUrl(),\n    auth,\n  );\n\n  if (!res.success) {\n    throw res.err;\n  }\n\n  return parseListTimelineTweets(res.value);\n}\n\nexport function getTweets(\n  user: string,\n  maxTweets: number,\n  auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n  return getTweetTimeline(user, maxTweets, async (q, mt, c) => {\n    const userIdRes = await getUserIdByScreenName(q, auth);\n\n    if (!userIdRes.success) {\n      throw userIdRes.err;\n    }\n\n    const { value: userId } = userIdRes;\n\n    return fetchTweets(userId, mt, c, auth);\n  });\n}\n\nexport function getTweetsByUserId(\n  userId: string,\n  maxTweets: number,\n  auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n  return getTweetTimeline(userId, maxTweets, (q, mt, c) => {\n    return fetchTweets(q, mt, c, auth);\n  });\n}\n\n\nexport function getTweetsByUserIdCursor(\n  userId: string,\n  maxTweets: number,\n  cursor: string | undefined,\n  auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n  return getTweetTimelineCursor(userId, maxTweets, cursor, (q, mt, c) => {\n    return fetchTweets(q, mt, c, auth);\n  });\n}\n\nexport function getTweetsAndReplies(\n  user: string,\n  maxTweets: number,\n  auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n  return getTweetTimeline(user, maxTweets, async (q, mt, c) => {\n    const userIdRes = await getUserIdByScreenName(q, auth);\n\n    if (!userIdRes.success) {\n      throw userIdRes.err;\n    }\n\n    const { value: userId } = userIdRes;\n\n    return fetchTweetsAndReplies(userId, mt, c, auth);\n  });\n}\n\nexport function getTweetsAndRepliesByUserId(\n  userId: string,\n  maxTweets: number,\n  auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n  return getTweetTimeline(userId, maxTweets, (q, mt, c) => {\n    return fetchTweetsAndReplies(q, mt, c, auth);\n  });\n}\n\nexport async function fetchLikedTweets(\n  userId: string,\n  maxTweets: number,\n  cursor: string | undefined,\n  auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n  if (!auth.isLoggedIn()) {\n    throw new Error('Scraper is not logged-in for fetching liked tweets.');\n  }\n\n  if (maxTweets > 200) {\n    maxTweets = 200;\n  }\n\n  const userTweetsRequest = apiRequestFactory.createUserLikedTweetsRequest();\n  userTweetsRequest.variables.userId = userId;\n  userTweetsRequest.variables.count = maxTweets;\n  userTweetsRequest.variables.includePromotedContent = false; // true on the website\n\n  if (cursor != null && cursor != '') {\n    userTweetsRequest.variables['cursor'] = cursor;\n  }\n\n  const res = await requestApi<TimelineV2>(\n    userTweetsRequest.toRequestUrl(),\n    auth,\n  );\n\n  if (!res.success) {\n    throw res.err;\n  }\n\n  return parseTimelineTweetsV2(res.value);\n}\n\nexport function getLikedTweets(\n  user: string,\n  maxTweets: number,\n  auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n  return getTweetTimeline(user, maxTweets, async (q, mt, c) => {\n    const userIdRes = await getUserIdByScreenName(q, auth);\n\n    if (!userIdRes.success) {\n      throw userIdRes.err;\n    }\n\n    const { value: userId } = userIdRes;\n\n    return fetchLikedTweets(userId, mt, c, auth);\n  });\n}\n\nexport async function getTweetWhere(\n  tweets: AsyncIterable<Tweet>,\n  query: TweetQuery,\n): Promise<Tweet | null> {\n  const isCallback = typeof query === 'function';\n\n  for await (const tweet of tweets) {\n    const matches = isCallback\n      ? await query(tweet)\n      : checkTweetMatches(tweet, query);\n\n    if (matches) {\n      return tweet;\n    }\n  }\n\n  return null;\n}\n\nexport async function getTweetsWhere(\n  tweets: AsyncIterable<Tweet>,\n  query: TweetQuery,\n): Promise<Tweet[]> {\n  const isCallback = typeof query === 'function';\n  const filtered = [];\n\n  for await (const tweet of tweets) {\n    const matches = isCallback ? query(tweet) : checkTweetMatches(tweet, query);\n\n    if (!matches) continue;\n    filtered.push(tweet);\n  }\n\n  return filtered;\n}\n\nfunction checkTweetMatches(tweet: Tweet, options: Partial<Tweet>): boolean {\n  return Object.keys(options).every((k) => {\n    const key = k as keyof Tweet;\n    return tweet[key] === options[key];\n  });\n}\n\nexport async function getLatestTweet(\n  user: string,\n  includeRetweets: boolean,\n  max: number,\n  auth: TwitterAuth,\n): Promise<Tweet | null | void> {\n  const timeline = getTweets(user, max, auth);\n\n  // No point looping if max is 1, just use first entry.\n  return max === 1\n    ? (await timeline.next()).value\n    : await getTweetWhere(timeline, { isRetweet: includeRetweets });\n}\n\nexport interface TweetResultByRestId {\n  data?: TimelineEntryItemContentRaw;\n}\n\nexport async function getTweet(\n  id: string,\n  auth: TwitterAuth,\n): Promise<Tweet | null> {\n  const tweetDetailRequest = apiRequestFactory.createTweetDetailRequest();\n  tweetDetailRequest.variables.focalTweetId = id;\n\n  const res = await requestApi<ThreadedConversation>(\n    tweetDetailRequest.toRequestUrl(),\n    auth,\n  );\n\n  if (!res.success) {\n    throw res.err;\n  }\n\n  if (!res.value) {\n    return null;\n  }\n\n  const tweets = parseThreadedConversation(res.value);\n  return tweets.find((tweet) => tweet.id === id) ?? null;\n}\n\nexport async function getTweetAnonymous(\n  id: string,\n  auth: TwitterAuth,\n): Promise<Tweet | null> {\n  const tweetResultByRestIdRequest =\n    apiRequestFactory.createTweetResultByRestIdRequest();\n  tweetResultByRestIdRequest.variables.tweetId = id;\n\n  const res = await requestApi<TweetResultByRestId>(\n    tweetResultByRestIdRequest.toRequestUrl(),\n    auth,\n  );\n\n  if (!res.success) {\n    throw res.err;\n  }\n\n  if (!res.value.data) {\n    return null;\n  }\n\n  return parseTimelineEntryItemContentRaw(res.value.data, id);\n}\n","import { Cookie } from 'tough-cookie';\nimport { bearerToken, FetchTransformOptions, requestApi, RequestApiResult } from './api';\nimport { TwitterAuth, TwitterAuthOptions, TwitterGuestAuth } from './auth';\nimport { TwitterUserAuth } from './auth-user';\nimport { getProfile, getUserIdByScreenName, Profile } from './profile';\nimport {\n  fetchSearchProfiles,\n  fetchSearchTweets,\n  SearchMode,\n  searchProfiles,\n  searchTweets,\n} from './search';\nimport {\n  fetchProfileFollowing,\n  fetchProfileFollowers,\n  getFollowing,\n  getFollowers,\n} from './relationships';\nimport { QueryProfilesResponse, QueryTweetsResponse } from './timeline-v1';\nimport { getTrends } from './trends';\nimport {\n  Tweet,\n  getTweetAnonymous,\n  getTweets,\n  getLatestTweet,\n  getLikedTweets,\n  getTweetWhere,\n  getTweetsWhere,\n  getTweetsByUserId,\n  TweetQuery,\n  getTweet,\n  fetchListTweets,\n  getTweetsAndRepliesByUserId,\n  getTweetsAndReplies,\n  getTweetsByUserIdCursor,\n} from './tweets';\nimport fetch from 'cross-fetch';\nimport { parseTimelineTweetsV2, TimelineV2 } from './timeline-v2';\n\nconst twUrl = 'https://twitter.com';\n\nconst UserTweetsUrl =\n  'https://twitter.com/i/api/graphql/E3opETHurmVJflFsUBVuUQ/UserTweets';\n\n\nexport interface ScraperOptions {\n  /**\n   * An alternative fetch function to use instead of the default fetch function. This may be useful\n   * in nonstandard runtime environments, such as edge workers.\n   */\n  fetch: typeof fetch;\n\n  /**\n   * Additional options that control how requests and responses are processed. This can be used to\n   * proxy requests through other hosts, for example.\n   */\n  transform: Partial<FetchTransformOptions>;\n}\n\n/**\n * An interface to Twitter's undocumented API.\n * - Reusing Scraper objects is recommended to minimize the time spent authenticating unnecessarily.\n */\nexport class Scraper {\n  private auth!: TwitterAuth;\n  private authTrends!: TwitterAuth;\n  private token: string;\n\n  /**\n   * Creates a new Scraper object.\n   * - Scrapers maintain their own guest tokens for Twitter's internal API.\n   * - Reusing Scraper objects is recommended to minimize the time spent authenticating unnecessarily.\n   */\n  constructor(private readonly options?: Partial<ScraperOptions>) {\n    this.token = bearerToken;\n    this.useGuestAuth();\n  }\n\n  /**\n   * Initializes auth properties using a guest token.\n   * Used when creating a new instance of this class, and when logging out.\n   * @internal\n   */\n  private useGuestAuth() {\n    this.auth = new TwitterGuestAuth(this.token, this.getAuthOptions());\n    this.authTrends = new TwitterGuestAuth(this.token, this.getAuthOptions());\n  }\n\n  /**\n   * Fetches a Twitter profile.\n   * @param username The Twitter username of the profile to fetch, without an `@` at the beginning.\n   * @returns The requested {@link Profile}.\n   */\n  public async getProfile(username: string): Promise<Profile> {\n    const res = await getProfile(username, this.auth);\n    return this.handleResponse(res);\n  }\n\n  /**\n   * Fetches the user ID corresponding to the provided screen name.\n   * @param screenName The Twitter screen name of the profile to fetch.\n   * @returns The ID of the corresponding account.\n   */\n  public async getUserIdByScreenName(screenName: string): Promise<string> {\n    const res = await getUserIdByScreenName(screenName, this.auth);\n    return this.handleResponse(res);\n  }\n\n  /**\n   * Fetches tweets from Twitter.\n   * @param query The search query. Any Twitter-compatible query format can be used.\n   * @param maxTweets The maximum number of tweets to return.\n   * @param includeReplies Whether or not replies should be included in the response.\n   * @param searchMode The category filter to apply to the search. Defaults to `Top`.\n   * @returns An {@link AsyncGenerator} of tweets matching the provided filters.\n   */\n  public searchTweets(\n    query: string,\n    maxTweets: number,\n    searchMode: SearchMode = SearchMode.Top,\n  ): AsyncGenerator<Tweet, void> {\n    return searchTweets(query, maxTweets, searchMode, this.auth);\n  }\n\n  /**\n   * Fetches profiles from Twitter.\n   * @param query The search query. Any Twitter-compatible query format can be used.\n   * @param maxProfiles The maximum number of profiles to return.\n   * @returns An {@link AsyncGenerator} of tweets matching the provided filter(s).\n   */\n  public searchProfiles(\n    query: string,\n    maxProfiles: number,\n  ): AsyncGenerator<Profile, void> {\n    return searchProfiles(query, maxProfiles, this.auth);\n  }\n\n  /**\n   * Fetches tweets from Twitter.\n   * @param query The search query. Any Twitter-compatible query format can be used.\n   * @param maxTweets The maximum number of tweets to return.\n   * @param includeReplies Whether or not replies should be included in the response.\n   * @param searchMode The category filter to apply to the search. Defaults to `Top`.\n   * @param cursor The search cursor, which can be passed into further requests for more results.\n   * @returns A page of results, containing a cursor that can be used in further requests.\n   */\n  public fetchSearchTweets(\n    query: string,\n    maxTweets: number,\n    searchMode: SearchMode,\n    cursor?: string,\n  ): Promise<QueryTweetsResponse> {\n    return fetchSearchTweets(query, maxTweets, searchMode, this.auth, cursor);\n  }\n\n  /**\n   * Fetches profiles from Twitter.\n   * @param query The search query. Any Twitter-compatible query format can be used.\n   * @param maxProfiles The maximum number of profiles to return.\n   * @param cursor The search cursor, which can be passed into further requests for more results.\n   * @returns A page of results, containing a cursor that can be used in further requests.\n   */\n  public fetchSearchProfiles(\n    query: string,\n    maxProfiles: number,\n    cursor?: string,\n  ): Promise<QueryProfilesResponse> {\n    return fetchSearchProfiles(query, maxProfiles, this.auth, cursor);\n  }\n\n  /**\n   * Fetches list tweets from Twitter.\n   * @param listId The list id\n   * @param maxTweets The maximum number of tweets to return.\n   * @param cursor The search cursor, which can be passed into further requests for more results.\n   * @returns A page of results, containing a cursor that can be used in further requests.\n   */\n  public fetchListTweets(\n    listId: string,\n    maxTweets: number,\n    cursor?: string,\n  ): Promise<QueryTweetsResponse> {\n    return fetchListTweets(listId, maxTweets, cursor, this.auth);\n  }\n\n  /**\n   * Fetch the profiles a user is following\n   * @param userId The user whose following should be returned\n   * @param maxProfiles The maximum number of profiles to return.\n   * @returns An {@link AsyncGenerator} of following profiles for the provided user.\n   */\n  public getFollowing(\n    userId: string,\n    maxProfiles: number,\n  ): AsyncGenerator<Profile, void> {\n    return getFollowing(userId, maxProfiles, this.auth);\n  }\n\n  /**\n   * Fetch the profiles that follow a user\n   * @param userId The user whose followers should be returned\n   * @param maxProfiles The maximum number of profiles to return.\n   * @returns An {@link AsyncGenerator} of profiles following the provided user.\n   */\n  public getFollowers(\n    userId: string,\n    maxProfiles: number,\n  ): AsyncGenerator<Profile, void> {\n    return getFollowers(userId, maxProfiles, this.auth);\n  }\n\n  /**\n   * Fetches following profiles from Twitter.\n   * @param userId The user whose following should be returned\n   * @param maxProfiles The maximum number of profiles to return.\n   * @param cursor The search cursor, which can be passed into further requests for more results.\n   * @returns A page of results, containing a cursor that can be used in further requests.\n   */\n  public fetchProfileFollowing(\n    userId: string,\n    maxProfiles: number,\n    cursor?: string,\n  ): Promise<QueryProfilesResponse> {\n    return fetchProfileFollowing(userId, maxProfiles, this.auth, cursor);\n  }\n\n  /**\n   * Fetches profile followers from Twitter.\n   * @param userId The user whose following should be returned\n   * @param maxProfiles The maximum number of profiles to return.\n   * @param cursor The search cursor, which can be passed into further requests for more results.\n   * @returns A page of results, containing a cursor that can be used in further requests.\n   */\n  public fetchProfileFollowers(\n    userId: string,\n    maxProfiles: number,\n    cursor?: string,\n  ): Promise<QueryProfilesResponse> {\n    return fetchProfileFollowers(userId, maxProfiles, this.auth, cursor);\n  }\n\n  /**\n   * Fetches the current trends from Twitter.\n   * @returns The current list of trends.\n   */\n  public getTrends(): Promise<string[]> {\n    return getTrends(this.authTrends);\n  }\n\n  /**\n   * Fetches tweets from a Twitter user.\n   * @param user The user whose tweets should be returned.\n   * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n   * @returns An {@link AsyncGenerator} of tweets from the provided user.\n   */\n  public getTweets(user: string, maxTweets = 200): AsyncGenerator<Tweet> {\n    return getTweets(user, maxTweets, this.auth);\n  }\n\n  /**\n   * Fetches liked tweets from a Twitter user. Requires authentication.\n   * @param user The user whose likes should be returned.\n   * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n   * @returns An {@link AsyncGenerator} of liked tweets from the provided user.\n   */\n  public getLikedTweets(user: string, maxTweets = 200): AsyncGenerator<Tweet> {\n    return getLikedTweets(user, maxTweets, this.auth);\n  }\n\n  /**\n   * Fetches tweets from a Twitter user using their ID.\n   * @param userId The user whose tweets should be returned.\n   * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n   * @returns An {@link AsyncGenerator} of tweets from the provided user.\n   */\n  public getTweetsByUserId(\n    userId: string,\n    maxTweets = 200,\n  ): AsyncGenerator<Tweet, void> {\n    return getTweetsByUserId(userId, maxTweets, this.auth);\n  }\n\n  /**\n   * Fetches tweets from a Twitter user using their ID from a given cursor.\n   * @param userId The user whose tweets should be returned.\n   * @param cursor The cursor to fetch the next page of tweets.\n   * @returns An {@link AsyncGenerator} of tweets from the provided user.\n   */\n  public getTweetsByUserIdCursor(\n    userId: string,\n    maxTweets = 200,\n    cursor: string | undefined,\n  ): AsyncGenerator<Tweet, void> {\n    return getTweetsByUserIdCursor(userId, maxTweets, cursor, this.auth);\n  }\n\n\n  /**\n   * Fetches tweets and replies from a Twitter user.\n   * @param user The user whose tweets should be returned.\n   * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n   * @returns An {@link AsyncGenerator} of tweets from the provided user.\n   */\n  public getTweetsAndReplies(\n    user: string,\n    maxTweets = 200,\n  ): AsyncGenerator<Tweet> {\n    return getTweetsAndReplies(user, maxTweets, this.auth);\n  }\n\n  /**\n   * Fetches tweets and replies from a Twitter user using their ID.\n   * @param userId The user whose tweets should be returned.\n   * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n   * @returns An {@link AsyncGenerator} of tweets from the provided user.\n   */\n  public getTweetsAndRepliesByUserId(\n    userId: string,\n    maxTweets = 200,\n  ): AsyncGenerator<Tweet, void> {\n    return getTweetsAndRepliesByUserId(userId, maxTweets, this.auth);\n  }\n\n  public async fetchUserTweets(\n    userId: string,\n    maxTweets = 200,\n    cursor?: string,\n  ): Promise<{ tweets: Tweet[]; next?: string }> {\n    if (maxTweets > 200) {\n      maxTweets = 200;\n    }\n\n    const variables: Record<string, any> = {\n      userId,\n      count: maxTweets,\n      includePromotedContent: true,\n      withQuickPromoteEligibilityTweetFields: true,\n      withVoice: true,\n      withV2Timeline: true,\n    };\n\n    if (cursor) {\n      variables['cursor'] = cursor;\n    }\n\n    const features = {\n      rweb_tipjar_consumption_enabled: true,\n      responsive_web_graphql_exclude_directive_enabled: true,\n      verified_phone_label_enabled: false,\n      creator_subscriptions_tweet_preview_api_enabled: true,\n      responsive_web_graphql_timeline_navigation_enabled: true,\n      responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n      communities_web_enable_tweet_community_results_fetch: true,\n      c9s_tweet_anatomy_moderator_badge_enabled: true,\n      articles_preview_enabled: true,\n      responsive_web_edit_tweet_api_enabled: true,\n      graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n      view_counts_everywhere_api_enabled: true,\n      longform_notetweets_consumption_enabled: true,\n      responsive_web_twitter_article_tweet_consumption_enabled: true,\n      tweet_awards_web_tipping_enabled: false,\n      creator_subscriptions_quote_tweet_preview_enabled: false,\n      freedom_of_speech_not_reach_fetch_enabled: true,\n      standardized_nudges_misinfo: true,\n      tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n        true,\n      rweb_video_timestamps_enabled: true,\n      longform_notetweets_rich_text_read_enabled: true,\n      longform_notetweets_inline_media_enabled: true,\n      responsive_web_enhance_cards_enabled: false,\n    };\n\n    const fieldToggles = {\n      withArticlePlainText: false,\n    };\n\n    const res = await requestApi<TimelineV2>(\n      `${UserTweetsUrl}?variables=${encodeURIComponent(\n        JSON.stringify(variables),\n      )}&features=${encodeURIComponent(\n        JSON.stringify(features),\n      )}&fieldToggles=${encodeURIComponent(JSON.stringify(fieldToggles))}`,\n      this.auth,\n    );\n\n    if (!res.success) {\n      throw res.err;\n    }\n\n    const timelineV2 = parseTimelineTweetsV2(res.value);\n    return {\n      tweets: timelineV2.tweets,\n      next: timelineV2.next,\n    };\n  }\n\n  /**\n   * Fetches the first tweet matching the given query.\n   *\n   * Example:\n   * ```js\n   * const timeline = scraper.getTweets('user', 200);\n   * const retweet = await scraper.getTweetWhere(timeline, { isRetweet: true });\n   * ```\n   * @param tweets The {@link AsyncIterable} of tweets to search through.\n   * @param query A query to test **all** tweets against. This may be either an\n   * object of key/value pairs or a predicate. If this query is an object, all\n   * key/value pairs must match a {@link Tweet} for it to be returned. If this query\n   * is a predicate, it must resolve to `true` for a {@link Tweet} to be returned.\n   * - All keys are optional.\n   * - If specified, the key must be implemented by that of {@link Tweet}.\n   */\n  public getTweetWhere(\n    tweets: AsyncIterable<Tweet>,\n    query: TweetQuery,\n  ): Promise<Tweet | null> {\n    return getTweetWhere(tweets, query);\n  }\n\n  /**\n   * Fetches all tweets matching the given query.\n   *\n   * Example:\n   * ```js\n   * const timeline = scraper.getTweets('user', 200);\n   * const retweets = await scraper.getTweetsWhere(timeline, { isRetweet: true });\n   * ```\n   * @param tweets The {@link AsyncIterable} of tweets to search through.\n   * @param query A query to test **all** tweets against. This may be either an\n   * object of key/value pairs or a predicate. If this query is an object, all\n   * key/value pairs must match a {@link Tweet} for it to be returned. If this query\n   * is a predicate, it must resolve to `true` for a {@link Tweet} to be returned.\n   * - All keys are optional.\n   * - If specified, the key must be implemented by that of {@link Tweet}.\n   */\n  public getTweetsWhere(\n    tweets: AsyncIterable<Tweet>,\n    query: TweetQuery,\n  ): Promise<Tweet[]> {\n    return getTweetsWhere(tweets, query);\n  }\n\n  /**\n   * Fetches the most recent tweet from a Twitter user.\n   * @param user The user whose latest tweet should be returned.\n   * @param includeRetweets Whether or not to include retweets. Defaults to `false`.\n   * @returns The {@link Tweet} object or `null`/`undefined` if it couldn't be fetched.\n   */\n  public getLatestTweet(\n    user: string,\n    includeRetweets = false,\n    max = 200,\n  ): Promise<Tweet | null | void> {\n    return getLatestTweet(user, includeRetweets, max, this.auth);\n  }\n\n  /**\n   * Fetches a single tweet.\n   * @param id The ID of the tweet to fetch.\n   * @returns The {@link Tweet} object, or `null` if it couldn't be fetched.\n   */\n  public getTweet(id: string): Promise<Tweet | null> {\n    if (this.auth instanceof TwitterUserAuth) {\n      return getTweet(id, this.auth);\n    } else {\n      return getTweetAnonymous(id, this.auth);\n    }\n  }\n\n  /**\n   * Returns if the scraper has a guest token. The token may not be valid.\n   * @returns `true` if the scraper has a guest token; otherwise `false`.\n   */\n  public hasGuestToken(): boolean {\n    return this.auth.hasToken() || this.authTrends.hasToken();\n  }\n\n  /**\n   * Returns if the scraper is logged in as a real user.\n   * @returns `true` if the scraper is logged in with a real user account; otherwise `false`.\n   */\n  public async isLoggedIn(): Promise<boolean> {\n    return (\n      (await this.auth.isLoggedIn()) && (await this.authTrends.isLoggedIn())\n    );\n  }\n\n  /**\n   * Login to Twitter as a real Twitter account. This enables running\n   * searches.\n   * @param username The username of the Twitter account to login with.\n   * @param password The password of the Twitter account to login with.\n   * @param email The email to log in with, if you have email confirmation enabled.\n   * @param twoFactorSecret The secret to generate two factor authentication tokens with, if you have two factor authentication enabled.\n   */\n  public async login(\n    username: string,\n    password: string,\n    email?: string,\n    twoFactorSecret?: string,\n  ): Promise<void> {\n    // Swap in a real authorizer for all requests\n    const userAuth = new TwitterUserAuth(this.token, this.getAuthOptions());\n    await userAuth.login(username, password, email, twoFactorSecret);\n    this.auth = userAuth;\n    this.authTrends = userAuth;\n  }\n\n  /**\n   * Log out of Twitter.\n   */\n  public async logout(): Promise<void> {\n    await this.auth.logout();\n    await this.authTrends.logout();\n\n    // Swap in guest authorizers for all requests\n    this.useGuestAuth();\n  }\n\n  /**\n   * Retrieves all cookies for the current session.\n   * @returns All cookies for the current session.\n   */\n  public async getCookies(): Promise<Cookie[]> {\n    return await this.authTrends\n      .cookieJar()\n      .getCookies(\n        typeof document !== 'undefined' ? document.location.toString() : twUrl,\n      );\n  }\n\n  /**\n   * Set cookies for the current session.\n   * @param cookies The cookies to set for the current session.\n   */\n  public async setCookies(cookies: (string | Cookie)[]): Promise<void> {\n    const userAuth = new TwitterUserAuth(this.token, this.getAuthOptions());\n    for (const cookie of cookies) {\n      await userAuth.cookieJar().setCookie(cookie, twUrl);\n    }\n\n    this.auth = userAuth;\n    this.authTrends = userAuth;\n  }\n\n  /**\n   * Clear all cookies for the current session.\n   */\n  public async clearCookies(): Promise<void> {\n    await this.auth.cookieJar().removeAllCookies();\n    await this.authTrends.cookieJar().removeAllCookies();\n  }\n\n  /**\n   * Sets the optional cookie to be used in requests.\n   * @param _cookie The cookie to be used in requests.\n   * @deprecated This function no longer represents any part of Twitter's auth flow.\n   * @returns This scraper instance.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public withCookie(_cookie: string): Scraper {\n    console.warn(\n      'Warning: Scraper#withCookie is deprecated and will be removed in a later version. Use Scraper#login or Scraper#setCookies instead.',\n    );\n    return this;\n  }\n\n  /**\n   * Sets the optional CSRF token to be used in requests.\n   * @param _token The CSRF token to be used in requests.\n   * @deprecated This function no longer represents any part of Twitter's auth flow.\n   * @returns This scraper instance.\n   */\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  public withXCsrfToken(_token: string): Scraper {\n    console.warn(\n      'Warning: Scraper#withXCsrfToken is deprecated and will be removed in a later version.',\n    );\n    return this;\n  }\n\n  private getAuthOptions(): Partial<TwitterAuthOptions> {\n    return {\n      fetch: this.options?.fetch,\n      transform: this.options?.transform,\n    };\n  }\n\n  private handleResponse<T>(res: RequestApiResult<T>): T {\n    if (!res.success) {\n      throw res.err;\n    }\n\n    return res.value;\n  }\n}\n"]}