@elizaos/plugin-twitter 0.1.9 → 1.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1464 -3
- package/dist/index.js +9176 -3855
- package/dist/index.js.map +1 -1
- package/dist/node-D3TH7VR6.js +33 -0
- package/dist/node-D3TH7VR6.js.map +1 -0
- package/package.json +25 -8
- package/README.md +0 -275
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/actions/post.ts","../src/templates.ts","../../../node_modules/zod/lib/index.mjs","../src/types.ts","../src/index.ts"],"sourcesContent":["import {\n type Action,\n type IAgentRuntime,\n type Memory,\n type State,\n composeContext,\n elizaLogger,\n ModelClass,\n generateObject,\n truncateToCompleteSentence,\n} from \"@elizaos/core\";\nimport { Scraper } from \"agent-twitter-client\";\nimport { tweetTemplate } from \"../templates\";\nimport { isTweetContent, TweetSchema } from \"../types\";\n\nexport const DEFAULT_MAX_TWEET_LENGTH = 280;\n\nasync function composeTweet(\n runtime: IAgentRuntime,\n _message: Memory,\n state?: State\n): Promise<string> {\n try {\n const context = composeContext({\n state,\n template: tweetTemplate,\n });\n\n const tweetContentObject = await generateObject({\n runtime,\n context,\n modelClass: ModelClass.SMALL,\n schema: TweetSchema,\n stop: [\"\\n\"],\n });\n\n if (!isTweetContent(tweetContentObject.object)) {\n elizaLogger.error(\n \"Invalid tweet content:\",\n tweetContentObject.object\n );\n return;\n }\n\n let trimmedContent = tweetContentObject.object.text.trim();\n\n // Truncate the content to the maximum tweet length specified in the environment settings.\n const maxTweetLength = runtime.getSetting(\"MAX_TWEET_LENGTH\");\n if (maxTweetLength) {\n trimmedContent = truncateToCompleteSentence(\n trimmedContent,\n Number(maxTweetLength)\n );\n }\n\n return trimmedContent;\n } catch (error) {\n elizaLogger.error(\"Error composing tweet:\", error);\n throw error;\n }\n}\n\nasync function sendTweet(twitterClient: Scraper, content: string) {\n const result = await twitterClient.sendTweet(content);\n\n const body = await result.json();\n elizaLogger.log(\"Tweet response:\", body);\n\n // Check for Twitter API errors\n if (body.errors) {\n const error = body.errors[0];\n elizaLogger.error(\n `Twitter API error (${error.code}): ${error.message}`\n );\n return false;\n }\n\n // Check for successful tweet creation\n if (!body?.data?.create_tweet?.tweet_results?.result) {\n elizaLogger.error(\"Failed to post tweet: No tweet result in response\");\n return false;\n }\n\n return true;\n}\n\nasync function postTweet(\n runtime: IAgentRuntime,\n content: string\n): Promise<boolean> {\n try {\n const twitterClient = runtime.clients.twitter?.client?.twitterClient;\n const scraper = twitterClient || new Scraper();\n\n if (!twitterClient) {\n const username = runtime.getSetting(\"TWITTER_USERNAME\");\n const password = runtime.getSetting(\"TWITTER_PASSWORD\");\n const email = runtime.getSetting(\"TWITTER_EMAIL\");\n const twitter2faSecret = runtime.getSetting(\"TWITTER_2FA_SECRET\");\n\n if (!username || !password) {\n elizaLogger.error(\n \"Twitter credentials not configured in environment\"\n );\n return false;\n }\n // Login with credentials\n await scraper.login(username, password, email, twitter2faSecret);\n if (!(await scraper.isLoggedIn())) {\n elizaLogger.error(\"Failed to login to Twitter\");\n return false;\n }\n }\n\n // Send the tweet\n elizaLogger.log(\"Attempting to send tweet:\", content);\n\n try {\n if (content.length > DEFAULT_MAX_TWEET_LENGTH) {\n const noteTweetResult = await scraper.sendNoteTweet(content);\n if (noteTweetResult.errors && noteTweetResult.errors.length > 0) {\n // Note Tweet failed due to authorization. Falling back to standard Tweet.\n return await sendTweet(scraper, content);\n }\n return true;\n }\n return await sendTweet(scraper, content);\n } catch (error) {\n throw new Error(`Note Tweet failed: ${error}`);\n }\n } catch (error) {\n // Log the full error details\n elizaLogger.error(\"Error posting tweet:\", {\n message: error.message,\n stack: error.stack,\n name: error.name,\n cause: error.cause,\n });\n return false;\n }\n}\n\nexport const postAction: Action = {\n name: \"POST_TWEET\",\n similes: [\"TWEET\", \"POST\", \"SEND_TWEET\"],\n description: \"Post a tweet to Twitter\",\n validate: async (\n runtime: IAgentRuntime,\n// eslint-disable-next-line\n _message: Memory,\n// eslint-disable-next-line\n _state?: State\n ) => {\n const username = runtime.getSetting(\"TWITTER_USERNAME\");\n const password = runtime.getSetting(\"TWITTER_PASSWORD\");\n const email = runtime.getSetting(\"TWITTER_EMAIL\");\n const hasCredentials = !!username && !!password && !!email;\n elizaLogger.log(`Has credentials: ${hasCredentials}`);\n\n return hasCredentials;\n },\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n state?: State\n ): Promise<boolean> => {\n try {\n // Generate tweet content using context\n const tweetContent = await composeTweet(runtime, message, state);\n\n if (!tweetContent) {\n elizaLogger.error(\"No content generated for tweet\");\n return false;\n }\n\n elizaLogger.log(`Generated tweet content: ${tweetContent}`);\n\n // Check for dry run mode - explicitly check for string \"true\"\n if (\n process.env.TWITTER_DRY_RUN &&\n process.env.TWITTER_DRY_RUN.toLowerCase() === \"true\"\n ) {\n elizaLogger.info(\n `Dry run: would have posted tweet: ${tweetContent}`\n );\n return true;\n }\n\n return await postTweet(runtime, tweetContent);\n } catch (error) {\n elizaLogger.error(\"Error in post action:\", error);\n return false;\n }\n },\n examples: [\n [\n {\n user: \"{{user1}}\",\n content: { text: \"You should tweet that\" },\n },\n {\n user: \"{{agentName}}\",\n content: {\n text: \"I'll share this update with my followers right away!\",\n action: \"POST_TWEET\",\n },\n },\n ],\n [\n {\n user: \"{{user1}}\",\n content: { text: \"Post this tweet\" },\n },\n {\n user: \"{{agentName}}\",\n content: {\n text: \"I'll post that as a tweet now.\",\n action: \"POST_TWEET\",\n },\n },\n ],\n [\n {\n user: \"{{user1}}\",\n content: { text: \"Share that on Twitter\" },\n },\n {\n user: \"{{agentName}}\",\n content: {\n text: \"I'll share this message on Twitter.\",\n action: \"POST_TWEET\",\n },\n },\n ],\n [\n {\n user: \"{{user1}}\",\n content: { text: \"Post that on X\" },\n },\n {\n user: \"{{agentName}}\",\n content: {\n text: \"I'll post this message on X right away.\",\n action: \"POST_TWEET\",\n },\n },\n ],\n [\n {\n user: \"{{user1}}\",\n content: { text: \"You should put that on X dot com\" },\n },\n {\n user: \"{{agentName}}\",\n content: {\n text: \"I'll put this message up on X.com now.\",\n action: \"POST_TWEET\",\n },\n },\n ],\n ],\n};\n","export const tweetTemplate = `\n# Context\n{{recentMessages}}\n\n# Topics\n{{topics}}\n\n# Post Directions\n{{postDirections}}\n\n# Recent interactions between {{agentName}} and other users:\n{{recentPostInteractions}}\n\n# Task\nGenerate a tweet that:\n1. Relates to the recent conversation or requested topic\n2. Matches the character's style and voice\n3. Is concise and engaging\n4. Must be UNDER 180 characters (this is a strict requirement)\n5. Speaks from the perspective of {{agentName}}\n\nGenerate only the tweet text, no other commentary.\n\nReturn the tweet in JSON format like: {\"text\": \"your tweet here\"}`;\n","var util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array\n .map((val) => (typeof val === \"string\" ? `'${val}'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === \"function\" &&\n data.catch &&\n typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nclass ZodError extends Error {\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n get errors() {\n return this.issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n overrideMap,\n overrideMap === errorMap ? undefined : errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" &&\n (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nconst OK = (value) => ({ status: \"valid\", value });\nconst isAborted = (x) => x.status === \"aborted\";\nconst isDirty = (x) => x.status === \"dirty\";\nconst isValid = (x) => x.status === \"valid\";\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nfunction __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nfunction __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nvar _ZodEnum_cache, _ZodNativeEnum_cache;\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n var _a, _b;\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message !== null && message !== void 0 ? message : ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n }\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this, this._def);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n // let regex = `\\\\d{2}:\\\\d{2}:\\\\d{2}`;\n let regex = `([01]\\\\d|2[0-3]):[0-5]\\\\d:[0-5]\\\\d`;\n if (args.precision) {\n regex = `${regex}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n regex = `${regex}(\\\\.\\\\d+)?`;\n }\n return regex;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nfunction datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch (_a) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n var _a, _b;\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,\n local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options === null || options === void 0 ? void 0 : options.position,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * @deprecated Use z.string().min(1) instead.\n * @see {@link ZodString.min}\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n var _a;\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / Math.pow(10, decCount);\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" ||\n (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null, min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" ||\n ch.kind === \"int\" ||\n ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = BigInt(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n var _a;\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n return (this._cached = { shape, keys });\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever &&\n this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") ;\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n var _a, _b, _c, _d;\n const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n util.objectKeys(mask).forEach((key) => {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util\n .objectKeys(a)\n .filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date &&\n bType === ZodParsedType.date &&\n +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nclass ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args\n .parseAsync(args, params)\n .catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args\n ? args\n : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodEnum_cache.set(this, void 0);\n }\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodEnum_cache, \"f\").has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\n_ZodEnum_cache = new WeakMap();\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n constructor() {\n super(...arguments);\n _ZodNativeEnum_cache.set(this, void 0);\n }\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string &&\n ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\")) {\n __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), \"f\");\n }\n if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, \"f\").has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\n_ZodNativeEnum_cache = new WeakMap();\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise &&\n ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise\n ? ctx.data\n : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return base;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((base) => {\n if (!isValid(base))\n return base;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\"\n ? params.default\n : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nconst BRAND = Symbol(\"zod_brand\");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nclass ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result)\n ? result.then((data) => freeze(data))\n : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\nfunction custom(check, params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n var _a, _b;\n if (!check(data)) {\n const p = typeof params === \"function\"\n ? params(data)\n : typeof params === \"string\"\n ? { message: params }\n : params;\n const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n ctx.addIssue({ code: \"custom\", ...p2, fatal: _fatal });\n }\n });\n return ZodAny.create();\n}\nconst late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nconst coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nconst NEVER = INVALID;\n\nvar z = /*#__PURE__*/Object.freeze({\n __proto__: null,\n defaultErrorMap: errorMap,\n setErrorMap: setErrorMap,\n getErrorMap: getErrorMap,\n makeIssue: makeIssue,\n EMPTY_PATH: EMPTY_PATH,\n addIssueToContext: addIssueToContext,\n ParseStatus: ParseStatus,\n INVALID: INVALID,\n DIRTY: DIRTY,\n OK: OK,\n isAborted: isAborted,\n isDirty: isDirty,\n isValid: isValid,\n isAsync: isAsync,\n get util () { return util; },\n get objectUtil () { return objectUtil; },\n ZodParsedType: ZodParsedType,\n getParsedType: getParsedType,\n ZodType: ZodType,\n datetimeRegex: datetimeRegex,\n ZodString: ZodString,\n ZodNumber: ZodNumber,\n ZodBigInt: ZodBigInt,\n ZodBoolean: ZodBoolean,\n ZodDate: ZodDate,\n ZodSymbol: ZodSymbol,\n ZodUndefined: ZodUndefined,\n ZodNull: ZodNull,\n ZodAny: ZodAny,\n ZodUnknown: ZodUnknown,\n ZodNever: ZodNever,\n ZodVoid: ZodVoid,\n ZodArray: ZodArray,\n ZodObject: ZodObject,\n ZodUnion: ZodUnion,\n ZodDiscriminatedUnion: ZodDiscriminatedUnion,\n ZodIntersection: ZodIntersection,\n ZodTuple: ZodTuple,\n ZodRecord: ZodRecord,\n ZodMap: ZodMap,\n ZodSet: ZodSet,\n ZodFunction: ZodFunction,\n ZodLazy: ZodLazy,\n ZodLiteral: ZodLiteral,\n ZodEnum: ZodEnum,\n ZodNativeEnum: ZodNativeEnum,\n ZodPromise: ZodPromise,\n ZodEffects: ZodEffects,\n ZodTransformer: ZodEffects,\n ZodOptional: ZodOptional,\n ZodNullable: ZodNullable,\n ZodDefault: ZodDefault,\n ZodCatch: ZodCatch,\n ZodNaN: ZodNaN,\n BRAND: BRAND,\n ZodBranded: ZodBranded,\n ZodPipeline: ZodPipeline,\n ZodReadonly: ZodReadonly,\n custom: custom,\n Schema: ZodType,\n ZodSchema: ZodType,\n late: late,\n get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },\n coerce: coerce,\n any: anyType,\n array: arrayType,\n bigint: bigIntType,\n boolean: booleanType,\n date: dateType,\n discriminatedUnion: discriminatedUnionType,\n effect: effectsType,\n 'enum': enumType,\n 'function': functionType,\n 'instanceof': instanceOfType,\n intersection: intersectionType,\n lazy: lazyType,\n literal: literalType,\n map: mapType,\n nan: nanType,\n nativeEnum: nativeEnumType,\n never: neverType,\n 'null': nullType,\n nullable: nullableType,\n number: numberType,\n object: objectType,\n oboolean: oboolean,\n onumber: onumber,\n optional: optionalType,\n ostring: ostring,\n pipeline: pipelineType,\n preprocess: preprocessType,\n promise: promiseType,\n record: recordType,\n set: setType,\n strictObject: strictObjectType,\n string: stringType,\n symbol: symbolType,\n transformer: effectsType,\n tuple: tupleType,\n 'undefined': undefinedType,\n union: unionType,\n unknown: unknownType,\n 'void': voidType,\n NEVER: NEVER,\n ZodIssueCode: ZodIssueCode,\n quotelessJson: quotelessJson,\n ZodError: ZodError\n});\n\nexport { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodReadonly, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, datetimeRegex, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };\n","import { z } from \"zod\";\n\nexport interface TweetContent {\n text: string;\n}\n\nexport const TweetSchema = z.object({\n text: z.string().describe(\"The text of the tweet\"),\n});\n\nexport const isTweetContent = (obj: unknown): obj is TweetContent => {\n return TweetSchema.safeParse(obj).success;\n};\n","import type { Plugin } from \"@elizaos/core\";\nimport { postAction } from \"./actions/post\";\n\nexport const twitterPlugin: Plugin = {\n name: \"twitter\",\n description: \"Twitter integration plugin for posting tweets\",\n actions: [postAction],\n evaluators: [],\n providers: [],\n};\n\nexport default twitterPlugin;\n"],"mappings":";AAAA;AAAA,EAKI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,eAAe;;;ACXjB,IAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACA7B,IAAI;AAAA,CACH,SAAUA,OAAM;AACb,EAAAA,MAAK,cAAc,CAAC,QAAQ;AAC5B,WAAS,SAAS,MAAM;AAAA,EAAE;AAC1B,EAAAA,MAAK,WAAW;AAChB,WAAS,YAAY,IAAI;AACrB,UAAM,IAAI,MAAM;AAAA,EACpB;AACA,EAAAA,MAAK,cAAc;AACnB,EAAAA,MAAK,cAAc,CAAC,UAAU;AAC1B,UAAM,MAAM,CAAC;AACb,eAAW,QAAQ,OAAO;AACtB,UAAI,IAAI,IAAI;AAAA,IAChB;AACA,WAAO;AAAA,EACX;AACA,EAAAA,MAAK,qBAAqB,CAAC,QAAQ;AAC/B,UAAM,YAAYA,MAAK,WAAW,GAAG,EAAE,OAAO,CAAC,MAAM,OAAO,IAAI,IAAI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AA,QACN,SAAS,EAAE,MAAM,mCAAmC;AAAA,MACxD;AAAA,MACA;AAAA,QACI,MAAM;AAAA,QACN,SAAS;AAAA,UACL,MAAM;AAAA,UACN,QAAQ;AAAA,QACZ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;;;AIlQO,IAAM,gBAAwB;AAAA,EACjC,MAAM;AAAA,EACN,aAAa;AAAA,EACb,SAAS,CAAC,UAAU;AAAA,EACpB,YAAY,CAAC;AAAA,EACb,WAAW,CAAC;AAChB;AAEA,IAAO,gBAAQ;","names":["util","objectUtil","errorUtil","errorMap","ctx","result","issues","elements","processed","ZodFirstPartyTypeKind"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/actions/reply.ts","../src/actions/spaceJoin.ts","../src/spaces.ts","../src/client/errors.ts","../src/client/platform/platform-interface.ts","../src/client/platform/index.ts","../src/client/requests.ts","../src/client/api.ts","../src/client/auth.ts","../src/client/auth-user.ts","../src/client/profile.ts","../src/client/timeline-async.ts","../src/client/type-util.ts","../src/client/timeline-tweet-util.ts","../src/client/timeline-v2.ts","../src/client/timeline-search.ts","../src/client/search.ts","../src/client/relationships.ts","../src/client/timeline-relationship.ts","../src/client/trends.ts","../src/client/api-data.ts","../src/client/timeline-list.ts","../src/client/tweets.ts","../src/client/timeline-home.ts","../src/client/timeline-following.ts","../src/client/messages.ts","../src/client/spaces.ts","../src/client/grok.ts","../src/client/client.ts","../src/client/spaces/core/Space.ts","../src/client/spaces/core/ChatClient.ts","../src/client/spaces/core/JanusClient.ts","../src/client/spaces/core/JanusAudio.ts","../src/client/spaces/utils.ts","../src/client/spaces/logger.ts","../src/client/spaces/core/SpaceParticipant.ts","../src/client/spaces/plugins/IdleMonitorPlugin.ts","../src/sttTtsSpaces.ts","../src/utils.ts","../src/base.ts","../src/constants.ts","../src/interactions.ts","../src/post.ts","../src/templates.ts","../src/tests.ts","../src/types.ts"],"sourcesContent":["import {\n\tlogger,\n\tService,\n\ttype IAgentRuntime,\n\ttype Plugin,\n\ttype UUID,\n} from \"@elizaos/core\";\nimport reply from \"./actions/reply.ts\";\nimport spaceJoin from \"./actions/spaceJoin.ts\";\nimport { ClientBase } from \"./base.ts\";\nimport { TWITTER_SERVICE_NAME } from \"./constants.ts\";\nimport type { TwitterConfig } from \"./environment.ts\";\nimport { TwitterInteractionClient } from \"./interactions.ts\";\nimport { TwitterPostClient } from \"./post.ts\";\nimport { TwitterSpaceClient } from \"./spaces.ts\";\nimport { TwitterTestSuite } from \"./tests.ts\";\nimport type { ITwitterClient } from \"./types.ts\";\n\n/**\n * A manager that orchestrates all specialized Twitter logic:\n * - client: base operations (login, timeline caching, etc.)\n * - post: autonomous posting logic\n * - search: searching tweets / replying logic\n * - interaction: handling mentions, replies\n * - space: launching and managing Twitter Spaces (optional)\n */\nexport class TwitterClientInstance implements ITwitterClient {\n\tclient: ClientBase;\n\tpost: TwitterPostClient;\n\tinteraction: TwitterInteractionClient;\n\tspace?: TwitterSpaceClient;\n\tservice: TwitterService;\n\n\tconstructor(runtime: IAgentRuntime, state: any) {\n\t\t// Pass twitterConfig to the base client\n\t\tthis.client = new ClientBase(runtime, state);\n\n\t\t// Posting logic\n\t\tthis.post = new TwitterPostClient(this.client, runtime, state);\n\n\t\t// Mentions and interactions\n\t\tthis.interaction = new TwitterInteractionClient(\n\t\t\tthis.client,\n\t\t\truntime,\n\t\t\tstate,\n\t\t);\n\n\t\t// Optional Spaces logic (enabled if TWITTER_SPACES_ENABLE is true)\n\t\tif (runtime.getSetting(\"TWITTER_SPACES_ENABLE\") === true) {\n\t\t\tthis.space = new TwitterSpaceClient(this.client, runtime);\n\t\t}\n\n\t\tthis.service = TwitterService.getInstance();\n\t}\n}\n\nexport class TwitterService extends Service {\n\tstatic serviceType: string = TWITTER_SERVICE_NAME;\n\tcapabilityDescription =\n\t\t\"The agent is able to send and receive messages on twitter\";\n\tprivate static instance: TwitterService;\n\tprivate clients: Map<string, TwitterClientInstance> = new Map();\n\n\tstatic getInstance(): TwitterService {\n\t\tif (!TwitterService.instance) {\n\t\t\tTwitterService.instance = new TwitterService();\n\t\t}\n\t\treturn TwitterService.instance;\n\t}\n\n\tasync createClient(\n\t\truntime: IAgentRuntime,\n\t\tclientId: string,\n\t\tstate: any,\n\t): Promise<TwitterClientInstance> {\n\t\tconsole.log(\"Creating client\", clientId);\n\t\tif (runtime.getSetting(\"TWITTER_2FA_SECRET\") === null) {\n\t\t\truntime.setSetting(\"TWITTER_2FA_SECRET\", undefined, false);\n\t\t}\n\t\ttry {\n\t\t\t// Check if client already exists\n\t\t\tconst existingClient = this.getClient(clientId, runtime.agentId);\n\t\t\tif (existingClient) {\n\t\t\t\tlogger.info(`Twitter client already exists for ${clientId}`);\n\t\t\t\treturn existingClient;\n\t\t\t}\n\n\t\t\t// Create new client instance\n\t\t\tconst client = new TwitterClientInstance(runtime, state);\n\n\t\t\t// Initialize the client\n\t\t\tawait client.client.init();\n\n\t\t\tif (client.space) {\n\t\t\t\tclient.space.startPeriodicSpaceCheck();\n\t\t\t}\n\n\t\t\tif (client.post) {\n\t\t\t\tclient.post.start();\n\t\t\t}\n\n\t\t\tif (client.interaction) {\n\t\t\t\tclient.interaction.start();\n\t\t\t}\n\n\t\t\t// Store the client instance\n\t\t\tthis.clients.set(this.getClientKey(clientId, runtime.agentId), client);\n\n\t\t\tlogger.info(`Created Twitter client for ${clientId}`);\n\t\t\treturn client;\n\t\t} catch (error) {\n\t\t\tlogger.error(`Failed to create Twitter client for ${clientId}:`, error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tgetClient(\n\t\tclientId: string,\n\t\tagentId: UUID,\n\t): TwitterClientInstance | undefined {\n\t\treturn this.clients.get(this.getClientKey(clientId, agentId));\n\t}\n\n\tasync stopClient(clientId: string, agentId: UUID): Promise<void> {\n\t\tconst key = this.getClientKey(clientId, agentId);\n\t\tconst client = this.clients.get(key);\n\t\tif (client) {\n\t\t\ttry {\n\t\t\t\tawait client.service.stop();\n\t\t\t\tthis.clients.delete(key);\n\t\t\t\tlogger.info(`Stopped Twitter client for ${clientId}`);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`Error stopping Twitter client for ${clientId}:`, error);\n\t\t\t}\n\t\t}\n\t}\n\n\tstatic async start(runtime: IAgentRuntime) {\n\t\tconst twitterClientManager = TwitterService.getInstance();\n\n\t\t// Check for character-level Twitter credentials\n\t\tconst twitterConfig: Partial<TwitterConfig> = {\n\t\t\tTWITTER_USERNAME:\n\t\t\t\t(runtime.getSetting(\"TWITTER_USERNAME\") as string) ||\n\t\t\t\truntime.character.settings?.TWITTER_USERNAME ||\n\t\t\t\truntime.character.secrets?.TWITTER_USERNAME,\n\t\t\tTWITTER_PASSWORD:\n\t\t\t\t(runtime.getSetting(\"TWITTER_PASSWORD\") as string) ||\n\t\t\t\truntime.character.settings?.TWITTER_PASSWORD ||\n\t\t\t\truntime.character.secrets?.TWITTER_PASSWORD,\n\t\t\tTWITTER_EMAIL:\n\t\t\t\t(runtime.getSetting(\"TWITTER_EMAIL\") as string) ||\n\t\t\t\truntime.character.settings?.TWITTER_EMAIL ||\n\t\t\t\truntime.character.secrets?.TWITTER_EMAIL,\n\t\t\tTWITTER_2FA_SECRET:\n\t\t\t\t(runtime.getSetting(\"TWITTER_2FA_SECRET\") as string) ||\n\t\t\t\truntime.character.settings?.TWITTER_2FA_SECRET ||\n\t\t\t\truntime.character.secrets?.TWITTER_2FA_SECRET,\n\t\t};\n\n\t\t// Filter out undefined values\n\t\tconst config = Object.fromEntries(\n\t\t\tObject.entries(twitterConfig).filter(([_, v]) => v !== undefined),\n\t\t) as TwitterConfig;\n\n\t\t// If we have enough settings to create a client, do so\n\t\ttry {\n\t\t\tif (\n\t\t\t\tconfig.TWITTER_USERNAME &&\n\t\t\t\t// Basic auth\n\t\t\t\tconfig.TWITTER_PASSWORD &&\n\t\t\t\tconfig.TWITTER_EMAIL\n\t\t\t\t// ||\n\t\t\t\t// // API auth\n\t\t\t\t// (config.TWITTER_API_KEY && config.TWITTER_API_SECRET &&\n\t\t\t\t// config.TWITTER_ACCESS_TOKEN && config.TWITTER_ACCESS_TOKEN_SECRET)\n\t\t\t) {\n\t\t\t\tlogger.info(\"Creating default Twitter client from character settings\");\n\t\t\t\tawait twitterClientManager.createClient(\n\t\t\t\t\truntime,\n\t\t\t\t\truntime.agentId,\n\t\t\t\t\tconfig,\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Failed to create default Twitter client:\", error);\n\t\t}\n\n\t\treturn twitterClientManager;\n\t}\n\n\tasync stop(): Promise<void> {\n\t\tawait this.stopAllClients();\n\t}\n\n\tasync stopAllClients(): Promise<void> {\n\t\tfor (const [key, client] of this.clients.entries()) {\n\t\t\ttry {\n\t\t\t\tawait client.service.stop();\n\t\t\t\tthis.clients.delete(key);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`Error stopping Twitter client ${key}:`, error);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getClientKey(clientId: string, agentId: UUID): string {\n\t\treturn `${clientId}-${agentId}`;\n\t}\n}\n\nconst twitterPlugin: Plugin = {\n\tname: TWITTER_SERVICE_NAME,\n\tdescription: \"Twitter client with per-server instance management\",\n\tservices: [TwitterService],\n\tactions: [reply, spaceJoin],\n\ttests: [new TwitterTestSuite()],\n};\n\nexport default twitterPlugin;\n","import {\n\ttype Action,\n\ttype ActionExample,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype State,\n\tlogger,\n} from \"@elizaos/core\";\n\nconst twitterReplyAction = {\n\tname: \"REPLY\",\n\tsimiles: [\"REPLY_TO_TWEET\", \"SEND_REPLY\", \"RESPOND\", \"ANSWER_TWEET\"],\n\tdescription:\n\t\t\"Replies to the current tweet with the text from the generated message. Default if the agent is responding with a message and no other action.\",\n\tvalidate: async (_runtime: IAgentRuntime, message: Memory, _state: State) => {\n\t\t// Only validate for Twitter messages\n\t\tif (message.content.source !== \"twitter\") {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t},\n\thandler: async (\n\t\t_runtime: IAgentRuntime,\n\t\t_message: Memory,\n\t\t_state: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t\tresponses: Memory[],\n\t) => {\n\t\ttry {\n\t\t\tfor (const response of responses) {\n\t\t\t\t// Call the callback to handle any additional processing\n\t\t\t\tawait callback(response.content);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in Twitter reply action:\", error);\n\t\t\tthrow error;\n\t\t}\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} What do you think about the latest AI developments?\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"The rapid progress in AI is fascinating! I'm particularly excited about advances in multimodal models and their practical applications.\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Hey {{name2}}, can you explain quantum computing?\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Let me explain quantum computing in simple terms! Instead of classical bits that are either 0 or 1, quantum computers use quantum bits that can exist in multiple states simultaneously.\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} What's your favorite programming language?\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"I love working with Python! The simplicity and readability make it perfect for both quick scripts and complex AI applications.\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"{{name2}} Have you seen the latest research on transformer models?\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Yes! The improvements in efficiency and context length are really promising for advancing natural language understanding.\",\n\t\t\t\t\tactions: [\"REPLY\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n\nexport default twitterReplyAction;\n","import {\n\ttype Action,\n\ttype ActionExample,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype State,\n\tstringToUuid,\n\ttype HandlerCallback,\n\tlogger,\n} from \"@elizaos/core\";\nimport type { Tweet } from \"../client\";\nimport { SpaceActivity } from \"../spaces\";\n\nexport default {\n\tname: \"JOIN_TWITTER_SPACE\",\n\tsimiles: [\n\t\t\"JOIN_TWITTER_SPACE\",\n\t\t\"JOIN_SPACE\",\n\t\t\"JOIN_TWITTER_AUDIO\",\n\t\t\"JOIN_TWITTER_CALL\",\n\t\t\"JOIN_LIVE_CONVERSATION\",\n\t],\n\tvalidate: async (runtime: IAgentRuntime, message: Memory, _state: State) => {\n\t\tif (message?.content?.source !== \"twitter\") {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (!message?.content?.tweet) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst spaceEnable = runtime.getSetting(\"TWITTER_SPACES_ENABLE\") === true;\n\t\treturn spaceEnable;\n\t},\n\tdescription:\n\t\t\"Join a Twitter Space to participate in live audio conversations.\",\n\thandler: async (\n\t\truntime: IAgentRuntime,\n\t\tmessage: Memory,\n\t\tstate: State,\n\t\t_options: any,\n\t\tcallback: HandlerCallback,\n\t\tresponses: Memory[],\n\t): Promise<boolean> => {\n\t\tif (!state) {\n\t\t\tlogger.error(\"State is not available.\");\n\t\t\treturn false;\n\t\t}\n\n\t\tfor (const response of responses) {\n\t\t\tawait callback(response.content);\n\t\t}\n\n\t\tconst manager = runtime.getService(ServiceTypes.TWITTER);\n\t\tif (!manager) {\n\t\t\tthrow new Error(\"Twitter client manager not found\");\n\t\t}\n\n\t\tconst clientId = stringToUuid(\"default\");\n\t\tconst clientKey = manager.getClientKey(clientId, runtime.agentId);\n\n\t\tconst client = manager.clients.get(clientKey).client;\n\t\tconst spaceManager = manager.clients.get(clientKey).space;\n\n\t\tif (!spaceManager) {\n\t\t\tlogger.error(\"space action - no space manager found\");\n\t\t\treturn false;\n\t\t}\n\n\t\tif (spaceManager.spaceStatus !== SpaceActivity.IDLE) {\n\t\t\tlogger.warn(\"currently hosting/participating a space\");\n\t\t\treturn false;\n\t\t}\n\n\t\tconst tweet = message.content.tweet as Tweet;\n\t\tif (!tweet) {\n\t\t\tlogger.warn(\"space action - no tweet found in message\");\n\t\t\treturn false;\n\t\t}\n\n\t\tasync function joinSpaceByUrls(tweet: Tweet): Promise<boolean> {\n\t\t\tif (!tweet.urls) return false;\n\n\t\t\tfor (const url of tweet.urls) {\n\t\t\t\tconst match = url.match(/https:\\/\\/x\\.com\\/i\\/spaces\\/([a-zA-Z0-9]+)/);\n\t\t\t\tif (match) {\n\t\t\t\t\tconst spaceId = match[1];\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst spaceInfo =\n\t\t\t\t\t\t\tawait client.twitterClient.getAudioSpaceById(spaceId);\n\t\t\t\t\t\tif (spaceInfo?.metadata?.state === \"Running\") {\n\t\t\t\t\t\t\tconst spaceJoined = await spaceManager.startParticipant(spaceId);\n\t\t\t\t\t\t\treturn !!spaceJoined;\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tlogger.error(\"Error joining Twitter Space:\", error);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\tasync function joinSpaceByUserName(userName: string): Promise<boolean> {\n\t\t\ttry {\n\t\t\t\tconst tweetGenerator = client.twitterClient.getTweets(userName);\n\t\t\t\tfor await (const userTweet of tweetGenerator) {\n\t\t\t\t\tif (await joinSpaceByUrls(userTweet)) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`Error fetching tweets for ${userName}:`, error);\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t// Attempt to join a Twitter Space from URLs in the tweet\n\t\tconst spaceJoined = await joinSpaceByUrls(tweet);\n\t\tif (spaceJoined) return true;\n\n\t\t// If no Space was found in the URLs, check if the tweet author has an active Space\n\t\tconst authorJoined = await joinSpaceByUserName(tweet.username);\n\t\tif (authorJoined) return true;\n\n\t\t// If the tweet author isn't hosting a Space, check if any mentioned users are currently hosting one\n\t\tconst agentName = client.state.TWITTER_USERNAME;\n\t\tfor (const mention of tweet.mentions) {\n\t\t\tif (mention.username !== agentName) {\n\t\t\t\tconst mentionJoined = await joinSpaceByUserName(mention.username);\n\t\t\t\tif (mentionJoined) return true;\n\t\t\t}\n\t\t}\n\t\tawait callback({\n\t\t\ttext: \"I couldn't determine which Twitter Space to join.\",\n\t\t\tsource: \"twitter\",\n\t\t});\n\n\t\treturn false;\n\t},\n\texamples: [\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Hey, let's join the 'Crypto Talk' Twitter Space!\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"On my way\",\n\t\t\t\t\tactions: [\"JOIN_TWITTER_SPACE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\t[\n\t\t\t{\n\t\t\t\tname: \"{{name1}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"@{{name2}}, jump into the 'AI Revolution' Space!\",\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"{{name2}}\",\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: \"Joining now!\",\n\t\t\t\t\tactions: [\"JOIN_TWITTER_SPACE\"],\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t] as ActionExample[][],\n} as Action;\n","import { logger, ModelTypes, type IAgentRuntime } from \"@elizaos/core\";\nimport type { ClientBase } from \"./base.ts\";\nimport {\n\tIdleMonitorPlugin,\n\tSpace,\n\tSpaceParticipant,\n\ttype Client,\n\ttype SpaceConfig,\n\ttype SpeakerRequest,\n} from \"./client/index.ts\";\nimport { SttTtsPlugin } from \"./sttTtsSpaces.ts\";\nimport { generateTopicsIfEmpty, isAgentInSpace, speakFiller } from \"./utils.ts\";\n\nexport interface TwitterSpaceDecisionOptions {\n\tmaxSpeakers?: number;\n\ttypicalDurationMinutes?: number;\n\tidleKickTimeoutMs?: number;\n\tminIntervalBetweenSpacesMinutes?: number;\n\tenableIdleMonitor?: boolean;\n\tenableSpaceHosting: boolean;\n\tenableRecording?: boolean;\n\tspeakerMaxDurationMs?: number;\n}\n\ninterface CurrentSpeakerState {\n\tuserId: string;\n\tsessionUUID: string;\n\tusername: string;\n\tstartTime: number;\n}\n\nexport enum SpaceActivity {\n\tHOSTING = \"hosting\",\n\tPARTICIPATING = \"participating\",\n\tIDLE = \"idle\",\n}\n\nexport enum ParticipantActivity {\n\tLISTENER = \"listener\",\n\tSPEAKER = \"speaker\",\n\tPENDING = \"pending\",\n}\n\n/**\n * Main class: manage a Twitter Space with N speakers max, speaker queue, filler messages, etc.\n */\nexport class TwitterSpaceClient {\n\tprivate runtime: IAgentRuntime;\n\tprivate client: ClientBase;\n\tprivate twitterClient: Client;\n\tprivate currentSpace?: Space;\n\tprivate spaceId?: string;\n\tprivate startedAt?: number;\n\tprivate checkInterval?: NodeJS.Timeout;\n\tprivate lastSpaceEndedAt?: number;\n\tprivate sttTtsPlugin?: SttTtsPlugin;\n\tpublic spaceStatus: SpaceActivity = SpaceActivity.IDLE;\n\tprivate spaceParticipant: SpaceParticipant | null = null;\n\tpublic participantStatus: ParticipantActivity = ParticipantActivity.LISTENER;\n\n\t/**\n\t * We now store an array of active speakers, not just 1\n\t */\n\tprivate activeSpeakers: CurrentSpeakerState[] = [];\n\tprivate speakerQueue: SpeakerRequest[] = [];\n\n\tprivate decisionOptions: TwitterSpaceDecisionOptions;\n\n\tconstructor(client: ClientBase, runtime: IAgentRuntime) {\n\t\tthis.client = client;\n\t\tthis.twitterClient = client.twitterClient;\n\t\tthis.runtime = runtime;\n\n\t\tthis.sttTtsPlugin = new SttTtsPlugin();\n\n\t\t// TODO: Spaces should be added to and removed from cache probably, and it should be possible to join or leave a space from an action, etc\n\t\tconst charSpaces = runtime.character.settings?.twitter?.spaces || {};\n\t\tthis.decisionOptions = {\n\t\t\tmaxSpeakers: charSpaces.maxSpeakers ?? 1,\n\t\t\ttypicalDurationMinutes: charSpaces.typicalDurationMinutes ?? 30,\n\t\t\tidleKickTimeoutMs: charSpaces.idleKickTimeoutMs ?? 5 * 60_000,\n\t\t\tminIntervalBetweenSpacesMinutes:\n\t\t\t\tcharSpaces.minIntervalBetweenSpacesMinutes ?? 60,\n\t\t\tenableIdleMonitor: charSpaces.enableIdleMonitor !== false,\n\t\t\tenableRecording: charSpaces.enableRecording !== false,\n\t\t\tenableSpaceHosting: charSpaces.enableSpaceHosting || false,\n\t\t\tspeakerMaxDurationMs: charSpaces.speakerMaxDurationMs ?? 4 * 60_000,\n\t\t};\n\t}\n\n\t/**\n\t * Periodic check to launch or manage space\n\t */\n\tpublic async startPeriodicSpaceCheck() {\n\t\tlogger.log(\"[Space] Starting periodic check routine...\");\n\n\t\tconst interval = 20_000;\n\n\t\tconst routine = async () => {\n\t\t\ttry {\n\t\t\t\tif (this.spaceStatus === SpaceActivity.IDLE) {\n\t\t\t\t\tif (this.decisionOptions.enableSpaceHosting) {\n\t\t\t\t\t\t// Space not running => check if we should launch\n\t\t\t\t\t\tconst launch = await this.shouldLaunchSpace();\n\t\t\t\t\t\tif (launch) {\n\t\t\t\t\t\t\tconst config = await this.generateSpaceConfig();\n\t\t\t\t\t\t\tawait this.startSpace(config);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (this.spaceStatus === SpaceActivity.HOSTING) {\n\t\t\t\t\t\tawait this.manageCurrentSpace();\n\t\t\t\t\t} else if (this.spaceStatus === SpaceActivity.PARTICIPATING) {\n\t\t\t\t\t\tawait this.manageParticipant();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.checkInterval = setTimeout(routine, interval) as any;\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"[Space] Error in routine =>\", error);\n\t\t\t\t// In case of error, still schedule next iteration\n\t\t\t\tthis.checkInterval = setTimeout(routine, interval) as any;\n\t\t\t}\n\t\t};\n\n\t\troutine();\n\t}\n\n\tstopPeriodicCheck() {\n\t\tif (this.checkInterval) {\n\t\t\tclearTimeout(this.checkInterval);\n\t\t\tthis.checkInterval = undefined;\n\t\t}\n\t}\n\n\tprivate async shouldLaunchSpace(): Promise<boolean> {\n\t\t// Interval\n\t\tconst now = Date.now();\n\t\tif (this.lastSpaceEndedAt) {\n\t\t\tconst minIntervalMs =\n\t\t\t\t(this.decisionOptions.minIntervalBetweenSpacesMinutes ?? 60) * 60_000;\n\t\t\tif (now - this.lastSpaceEndedAt < minIntervalMs) {\n\t\t\t\tlogger.log(\"[Space] Too soon since last space => skip\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tlogger.log(\"[Space] Deciding to launch a new Space...\");\n\t\treturn true;\n\t}\n\n\tprivate async generateSpaceConfig(): Promise<SpaceConfig> {\n\t\tlet chosenTopic = \"Random Tech Chat\";\n\t\tlet topics = this.runtime.character.topics || [];\n\t\tif (!topics.length) {\n\t\t\tconst newTopics = await generateTopicsIfEmpty(this.client.runtime);\n\t\t\ttopics = newTopics;\n\t\t}\n\n\t\tchosenTopic = topics[Math.floor(Math.random() * topics.length)];\n\n\t\treturn {\n\t\t\trecord: this.decisionOptions.enableRecording,\n\t\t\tmode: \"INTERACTIVE\",\n\t\t\ttitle: chosenTopic,\n\t\t\tdescription: `Discussion about ${chosenTopic}`,\n\t\t\tlanguages: [\"en\"],\n\t\t};\n\t}\n\n\tpublic async startSpace(config: SpaceConfig) {\n\t\tlogger.log(\"[Space] Starting a new Twitter Space...\");\n\n\t\ttry {\n\t\t\tthis.currentSpace = new Space(this.twitterClient);\n\t\t\tthis.spaceStatus = SpaceActivity.IDLE;\n\t\t\tthis.spaceId = undefined;\n\t\t\tthis.startedAt = Date.now();\n\n\t\t\t// Reset states\n\t\t\tthis.activeSpeakers = [];\n\t\t\tthis.speakerQueue = [];\n\n\t\t\tconst broadcastInfo = await this.currentSpace.initialize(config);\n\t\t\tthis.spaceId = broadcastInfo.room_id;\n\n\t\t\tif (\n\t\t\t\tthis.runtime.getModel(ModelTypes.TEXT_TO_SPEECH) &&\n\t\t\t\tthis.runtime.getModel(ModelTypes.TRANSCRIPTION)\n\t\t\t) {\n\t\t\t\tlogger.log(\"[Space] Using SttTtsPlugin\");\n\t\t\t\t// TODO: There is an error here, onAttach is incompatible\n\t\t\t\tthis.currentSpace.use(this.sttTtsPlugin as any, {\n\t\t\t\t\truntime: this.runtime,\n\t\t\t\t\tspaceId: this.spaceId,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (this.decisionOptions.enableIdleMonitor) {\n\t\t\t\tlogger.log(\"[Space] Using IdleMonitorPlugin\");\n\t\t\t\tthis.currentSpace.use(\n\t\t\t\t\tnew IdleMonitorPlugin(\n\t\t\t\t\t\tthis.decisionOptions.idleKickTimeoutMs ?? 60_000,\n\t\t\t\t\t\t10_000,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.spaceStatus = SpaceActivity.HOSTING;\n\t\t\tawait this.twitterClient.sendTweet(\n\t\t\t\tbroadcastInfo.share_url.replace(\"broadcasts\", \"spaces\"),\n\t\t\t);\n\n\t\t\tconst spaceUrl = broadcastInfo.share_url.replace(\"broadcasts\", \"spaces\");\n\t\t\tlogger.log(`[Space] Space started => ${spaceUrl}`);\n\n\t\t\t// Greet\n\t\t\tawait speakFiller(this.client.runtime, this.sttTtsPlugin, \"WELCOME\");\n\n\t\t\t// Events\n\t\t\tthis.currentSpace.on(\"occupancyUpdate\", (update) => {\n\t\t\t\tlogger.log(`[Space] Occupancy => ${update.occupancy} participant(s).`);\n\t\t\t});\n\n\t\t\tthis.currentSpace.on(\"speakerRequest\", async (req: SpeakerRequest) => {\n\t\t\t\tlogger.log(\n\t\t\t\t\t`[Space] Speaker request from @${req.username} (${req.userId}).`,\n\t\t\t\t);\n\t\t\t\tawait this.handleSpeakerRequest(req);\n\t\t\t});\n\n\t\t\tthis.currentSpace.on(\"idleTimeout\", async (info) => {\n\t\t\t\tlogger.log(`[Space] idleTimeout => no audio for ${info.idleMs} ms.`);\n\t\t\t\tawait speakFiller(\n\t\t\t\t\tthis.client.runtime,\n\t\t\t\t\tthis.sttTtsPlugin,\n\t\t\t\t\t\"IDLE_ENDING\",\n\t\t\t\t);\n\t\t\t\tawait this.stopSpace();\n\t\t\t});\n\n\t\t\tprocess.on(\"SIGINT\", async () => {\n\t\t\t\tlogger.log(\"[Space] SIGINT => stopping space\");\n\t\t\t\tawait speakFiller(this.client.runtime, this.sttTtsPlugin, \"CLOSING\");\n\t\t\t\tawait this.stopSpace();\n\t\t\t\tprocess.exit(0);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.error(\"[Space] Error launching Space =>\", error);\n\t\t\tthis.spaceStatus = SpaceActivity.IDLE;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Periodic management: check durations, remove extras, maybe accept new from queue\n\t */\n\tprivate async manageCurrentSpace() {\n\t\tif (!this.spaceId || !this.currentSpace) return;\n\t\ttry {\n\t\t\tconst audioSpace = await this.twitterClient.getAudioSpaceById(\n\t\t\t\tthis.spaceId,\n\t\t\t);\n\t\t\tconst { participants } = audioSpace;\n\t\t\tconst numSpeakers = participants.speakers?.length || 0;\n\t\t\tconst totalListeners = participants.listeners?.length || 0;\n\n\t\t\t// 1) Remove any speaker who exceeded speakerMaxDurationMs\n\t\t\tconst maxDur = this.decisionOptions.speakerMaxDurationMs ?? 240_000;\n\t\t\tconst now = Date.now();\n\n\t\t\tfor (let i = this.activeSpeakers.length - 1; i >= 0; i--) {\n\t\t\t\tconst speaker = this.activeSpeakers[i];\n\t\t\t\tconst elapsed = now - speaker.startTime;\n\t\t\t\tif (elapsed > maxDur) {\n\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t`[Space] Speaker @${speaker.username} exceeded max duration => removing`,\n\t\t\t\t\t);\n\t\t\t\t\tawait this.removeSpeaker(speaker.userId);\n\t\t\t\t\tthis.activeSpeakers.splice(i, 1);\n\n\t\t\t\t\t// Possibly speak a short \"SPEAKER_LEFT\" filler\n\t\t\t\t\tawait speakFiller(\n\t\t\t\t\t\tthis.client.runtime,\n\t\t\t\t\t\tthis.sttTtsPlugin,\n\t\t\t\t\t\t\"SPEAKER_LEFT\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// 2) If we have capacity for new speakers from the queue, accept them\n\t\t\tawait this.acceptSpeakersFromQueueIfNeeded();\n\n\t\t\t// 3) If somehow more than maxSpeakers are active, remove the extras\n\t\t\tif (numSpeakers > (this.decisionOptions.maxSpeakers ?? 1)) {\n\t\t\t\tlogger.log(\"[Space] More than maxSpeakers => removing extras...\");\n\t\t\t\tawait this.kickExtraSpeakers(participants.speakers);\n\t\t\t}\n\n\t\t\t// 4) Possibly stop the space if empty or time exceeded\n\t\t\tconst elapsedMinutes = (now - (this.startedAt || 0)) / 60000;\n\t\t\tif (\n\t\t\t\telapsedMinutes > (this.decisionOptions.typicalDurationMinutes ?? 30) ||\n\t\t\t\t(numSpeakers === 0 && totalListeners === 0 && elapsedMinutes > 5)\n\t\t\t) {\n\t\t\t\tlogger.log(\"[Space] Condition met => stopping the Space...\");\n\t\t\t\tawait speakFiller(\n\t\t\t\t\tthis.client.runtime,\n\t\t\t\t\tthis.sttTtsPlugin,\n\t\t\t\t\t\"CLOSING\",\n\t\t\t\t\t4000,\n\t\t\t\t);\n\t\t\t\tawait this.stopSpace();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\"[Space] Error in manageCurrentSpace =>\", error);\n\t\t}\n\t}\n\n\t/**\n\t * If we have available slots, accept new speakers from the queue\n\t */\n\tprivate async acceptSpeakersFromQueueIfNeeded() {\n\t\t// while queue not empty and activeSpeakers < maxSpeakers, accept next\n\t\tconst ms = this.decisionOptions.maxSpeakers ?? 1;\n\t\twhile (this.speakerQueue.length > 0 && this.activeSpeakers.length < ms) {\n\t\t\tconst nextReq = this.speakerQueue.shift();\n\t\t\tif (nextReq) {\n\t\t\t\tawait speakFiller(this.client.runtime, this.sttTtsPlugin, \"PRE_ACCEPT\");\n\t\t\t\tawait this.acceptSpeaker(nextReq);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate async handleSpeakerRequest(req: SpeakerRequest) {\n\t\tif (!this.spaceId || !this.currentSpace) return;\n\n\t\tconst audioSpace = await this.twitterClient.getAudioSpaceById(this.spaceId);\n\t\tconst janusSpeakers = audioSpace?.participants?.speakers || [];\n\n\t\t// If we haven't reached maxSpeakers, accept immediately\n\t\tif (janusSpeakers.length < (this.decisionOptions.maxSpeakers ?? 1)) {\n\t\t\tlogger.log(`[Space] Accepting speaker @${req.username} now`);\n\t\t\tawait speakFiller(this.client.runtime, this.sttTtsPlugin, \"PRE_ACCEPT\");\n\t\t\tawait this.acceptSpeaker(req);\n\t\t} else {\n\t\t\tlogger.log(`[Space] Adding speaker @${req.username} to the queue`);\n\t\t\tthis.speakerQueue.push(req);\n\t\t}\n\t}\n\n\tprivate async acceptSpeaker(req: SpeakerRequest) {\n\t\tif (!this.currentSpace) return;\n\t\ttry {\n\t\t\tawait this.currentSpace.approveSpeaker(req.userId, req.sessionUUID);\n\t\t\tthis.activeSpeakers.push({\n\t\t\t\tuserId: req.userId,\n\t\t\t\tsessionUUID: req.sessionUUID,\n\t\t\t\tusername: req.username,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t});\n\t\t\tlogger.log(`[Space] Speaker @${req.username} is now live`);\n\t\t} catch (err) {\n\t\t\tlogger.error(`[Space] Error approving speaker @${req.username}:`, err);\n\t\t}\n\t}\n\n\tprivate async removeSpeaker(userId: string) {\n\t\tif (!this.currentSpace) return;\n\t\ttry {\n\t\t\tawait this.currentSpace.removeSpeaker(userId);\n\t\t\tlogger.log(`[Space] Removed speaker userId=${userId}`);\n\t\t} catch (error) {\n\t\t\tlogger.error(`[Space] Error removing speaker userId=${userId} =>`, error);\n\t\t}\n\t}\n\n\t/**\n\t * If more than maxSpeakers are found, remove extras\n\t * Also update activeSpeakers array\n\t */\n\tprivate async kickExtraSpeakers(speakers: any[]) {\n\t\tif (!this.currentSpace) return;\n\t\tconst ms = this.decisionOptions.maxSpeakers ?? 1;\n\n\t\t// sort by who joined first if needed, or just slice\n\t\tconst extras = speakers.slice(ms);\n\t\tfor (const sp of extras) {\n\t\t\tlogger.log(`[Space] Removing extra speaker => userId=${sp.user_id}`);\n\t\t\tawait this.removeSpeaker(sp.user_id);\n\n\t\t\t// remove from activeSpeakers array\n\t\t\tconst idx = this.activeSpeakers.findIndex((s) => s.userId === sp.user_id);\n\t\t\tif (idx !== -1) {\n\t\t\t\tthis.activeSpeakers.splice(idx, 1);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic async stopSpace() {\n\t\tif (!this.currentSpace || this.spaceStatus !== SpaceActivity.HOSTING)\n\t\t\treturn;\n\t\ttry {\n\t\t\tlogger.log(\"[Space] Stopping the current Space...\");\n\t\t\tawait this.currentSpace.stop();\n\t\t} catch (err) {\n\t\t\tlogger.error(\"[Space] Error stopping Space =>\", err);\n\t\t} finally {\n\t\t\tthis.spaceStatus = SpaceActivity.IDLE;\n\t\t\tthis.spaceId = undefined;\n\t\t\tthis.currentSpace = undefined;\n\t\t\tthis.startedAt = undefined;\n\t\t\tthis.lastSpaceEndedAt = Date.now();\n\t\t\tthis.activeSpeakers = [];\n\t\t\tthis.speakerQueue = [];\n\t\t}\n\t}\n\n\tasync startParticipant(spaceId: string) {\n\t\tif (this.spaceStatus !== SpaceActivity.IDLE) {\n\t\t\tlogger.warn(\"currently hosting/participating a space\");\n\t\t\treturn null;\n\t\t}\n\n\t\tthis.spaceParticipant = new SpaceParticipant(this.client.twitterClient, {\n\t\t\tspaceId,\n\t\t\tdebug: false,\n\t\t});\n\n\t\tif (this.spaceParticipant) {\n\t\t\ttry {\n\t\t\t\tawait this.spaceParticipant.joinAsListener();\n\n\t\t\t\tthis.spaceId = spaceId;\n\t\t\t\tthis.spaceStatus = SpaceActivity.PARTICIPATING;\n\n\t\t\t\treturn spaceId;\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`failed to join space ${error}`);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t}\n\n\tasync manageParticipant() {\n\t\tif (!this.spaceParticipant || !this.spaceId) {\n\t\t\tthis.stopParticipant();\n\t\t\treturn;\n\t\t}\n\n\t\tconst isParticipant = await isAgentInSpace(this.client, this.spaceId);\n\n\t\tif (!isParticipant) {\n\t\t\tthis.stopParticipant();\n\t\t\treturn;\n\t\t}\n\n\t\t// Check if we should request to speak\n\t\tif (this.participantStatus === ParticipantActivity.LISTENER) {\n\t\t\tlogger.log(\n\t\t\t\t\"[SpaceParticipant] Checking if we should request to speak...\",\n\t\t\t);\n\n\t\t\tthis.participantStatus = ParticipantActivity.PENDING;\n\n\t\t\tconst { sessionUUID } = await this.spaceParticipant.requestSpeaker();\n\n\t\t\tconst handleSpeakerRemove = async (evt: { sessionUUID: string }) => {\n\t\t\t\tif (evt.sessionUUID === sessionUUID) {\n\t\t\t\t\tconsole.log(\"[SpaceParticipant] Speaker removed:\", evt);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.spaceParticipant.removeFromSpeaker();\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\tconsole.error(\"[SpaceParticipant] Failed to become speaker:\", err);\n\t\t\t\t\t}\n\t\t\t\t\tthis.participantStatus = ParticipantActivity.LISTENER;\n\t\t\t\t\tthis.spaceParticipant?.off(\"newSpeakerRemoved\", handleSpeakerRemove);\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// Attach listener for speaker removal\n\t\t\tthis.spaceParticipant.on(\"newSpeakerRemoved\", handleSpeakerRemove);\n\n\t\t\tthis.waitForApproval(this.spaceParticipant, sessionUUID, 15000)\n\t\t\t\t.then(() => {\n\t\t\t\t\tthis.participantStatus = ParticipantActivity.SPEAKER;\n\t\t\t\t\tthis.spaceParticipant.use(this.sttTtsPlugin as any, {\n\t\t\t\t\t\truntime: this.runtime,\n\t\t\t\t\t\tspaceId: this.spaceId,\n\t\t\t\t\t});\n\t\t\t\t})\n\t\t\t\t.catch(async (err) => {\n\t\t\t\t\tconsole.error(\"[SpaceParticipant] Approval error or timeout =>\", err);\n\n\t\t\t\t\tthis.participantStatus = ParticipantActivity.LISTENER;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this.spaceParticipant.cancelSpeakerRequest();\n\t\t\t\t\t\tconsole.log(\n\t\t\t\t\t\t\t\"[SpaceParticipant] Speaker request canceled after timeout or error.\",\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (cancelErr) {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\"[SpaceParticipant] Could not cancel the request =>\",\n\t\t\t\t\t\t\tcancelErr,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t}\n\t}\n\n\tpublic async stopParticipant() {\n\t\tif (\n\t\t\t!this.spaceParticipant ||\n\t\t\tthis.spaceStatus !== SpaceActivity.PARTICIPATING\n\t\t)\n\t\t\treturn;\n\t\ttry {\n\t\t\tlogger.log(\n\t\t\t\t\"[SpaceParticipant] Stopping the current space participant...\",\n\t\t\t);\n\t\t\tawait this.spaceParticipant.leaveSpace();\n\t\t} catch (err) {\n\t\t\tlogger.error(\n\t\t\t\t\"[SpaceParticipant] Error stopping space participant =>\",\n\t\t\t\terr,\n\t\t\t);\n\t\t} finally {\n\t\t\tthis.spaceStatus = SpaceActivity.IDLE;\n\t\t\tthis.participantStatus = ParticipantActivity.LISTENER;\n\t\t\tthis.spaceId = undefined;\n\t\t\tthis.spaceParticipant = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * waitForApproval waits until \"newSpeakerAccepted\" matches our sessionUUID,\n\t * then calls becomeSpeaker() or rejects after a given timeout.\n\t */\n\tasync waitForApproval(\n\t\tparticipant: SpaceParticipant,\n\t\tsessionUUID: string,\n\t\ttimeoutMs = 10000,\n\t): Promise<void> {\n\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\tlet resolved = false;\n\n\t\t\tconst handler = async (evt: { sessionUUID: string }) => {\n\t\t\t\tif (evt.sessionUUID === sessionUUID) {\n\t\t\t\t\tresolved = true;\n\t\t\t\t\tparticipant.off(\"newSpeakerAccepted\", handler);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait participant.becomeSpeaker();\n\t\t\t\t\t\tconsole.log(\"[SpaceParticipant] Successfully became speaker!\");\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\treject(err);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\t// Listen to \"newSpeakerAccepted\" from participant\n\t\t\tparticipant.on(\"newSpeakerAccepted\", handler);\n\n\t\t\t// Timeout to reject if not approved in time\n\t\t\tsetTimeout(() => {\n\t\t\t\tif (!resolved) {\n\t\t\t\t\tparticipant.off(\"newSpeakerAccepted\", handler);\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`[SpaceParticipant] Timed out waiting for speaker approval after ${timeoutMs}ms.`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}, timeoutMs);\n\t\t});\n\t}\n}\n","export class ApiError extends Error {\n\tprivate constructor(\n\t\treadonly response: Response,\n\t\treadonly data: any,\n\t\tmessage: string,\n\t) {\n\t\tsuper(message);\n\t}\n\n\tstatic async fromResponse(response: Response) {\n\t\t// Try our best to parse the result, but don't bother if we can't\n\t\tlet data: string | object | undefined = undefined;\n\t\ttry {\n\t\t\tdata = await response.json();\n\t\t} catch {\n\t\t\ttry {\n\t\t\t\tdata = await response.text();\n\t\t\t} catch {}\n\t\t}\n\n\t\treturn new ApiError(response, data, `Response status: ${response.status}`);\n\t}\n}\n\ninterface Position {\n\tline: number;\n\tcolumn: number;\n}\n\ninterface TraceInfo {\n\ttrace_id: string;\n}\n\ninterface TwitterApiErrorExtensions {\n\tcode?: number;\n\tkind?: string;\n\tname?: string;\n\tsource?: string;\n\ttracing?: TraceInfo;\n}\n\nexport interface TwitterApiErrorRaw extends TwitterApiErrorExtensions {\n\tmessage?: string;\n\tlocations?: Position[];\n\tpath?: string[];\n\textensions?: TwitterApiErrorExtensions;\n}\n","export interface PlatformExtensions {\n\t/**\n\t * Randomizes the runtime's TLS ciphers to bypass TLS client fingerprinting, which\n\t * hopefully avoids random 404s on some requests.\n\t *\n\t * **References:**\n\t * - https://github.com/imputnet/cobalt/pull/574\n\t */\n\trandomizeCiphers(): Promise<void>;\n}\n\nexport const genericPlatform = new (class implements PlatformExtensions {\n\trandomizeCiphers(): Promise<void> {\n\t\treturn Promise.resolve();\n\t}\n})();\n","import {\n\ttype PlatformExtensions,\n\tgenericPlatform,\n} from \"./platform-interface.js\";\n\nexport * from \"./platform-interface.js\";\n\nconst PLATFORM_NODE: boolean = typeof process !== \"undefined\";\n\nexport class Platform implements PlatformExtensions {\n\tasync randomizeCiphers() {\n\t\tconst platform = await Platform.importPlatform();\n\t\tawait platform?.randomizeCiphers();\n\t}\n\n\tprivate static async importPlatform(): Promise<null | PlatformExtensions> {\n\t\tif (PLATFORM_NODE) {\n\t\t\tconst { platform } = await import(\"./node/index.js\");\n\t\t\treturn platform as PlatformExtensions;\n\t\t}\n\n\t\treturn genericPlatform;\n\t}\n}\n","import { Cookie, type 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\tcookieJar: CookieJar,\n\theaders: Headers | HeadersPolyfill,\n) {\n\tconst setCookieHeader = headers.get(\"set-cookie\");\n\tif (setCookieHeader) {\n\t\tconst cookies = setCookie.splitCookiesString(setCookieHeader);\n\t\tfor (const cookie of cookies.map((c) => Cookie.parse(c))) {\n\t\t\tif (!cookie) continue;\n\t\t\tawait cookieJar.setCookie(\n\t\t\t\tcookie,\n\t\t\t\t`${cookie.secure ? \"https\" : \"http\"}://${cookie.domain}${cookie.path}`,\n\t\t\t);\n\t\t}\n\t} else if (typeof document !== \"undefined\") {\n\t\tfor (const cookie of document.cookie.split(\";\")) {\n\t\t\tconst hardCookie = Cookie.parse(cookie);\n\t\t\tif (hardCookie) {\n\t\t\t\tawait cookieJar.setCookie(hardCookie, document.location.toString());\n\t\t\t}\n\t\t}\n\t}\n}\n","import type { TwitterAuth } from \"./auth\";\nimport { ApiError } from \"./errors\";\nimport { Platform, type 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\t/**\n\t * Transforms the request options before a request is made. This executes after all of the default\n\t * parameters have been configured, and is stateless. It is safe to return new request options\n\t * objects.\n\t * @param args The request options.\n\t * @returns The transformed request options.\n\t */\n\trequest: (\n\t\t...args: FetchParameters\n\t) => FetchParameters | Promise<FetchParameters>;\n\n\t/**\n\t * Transforms the response after a request completes. This executes immediately after the request\n\t * completes, and is stateless. It is safe to return a new response object.\n\t * @param response The response object.\n\t * @returns The transformed response object.\n\t */\n\tresponse: (response: Response) => Response | Promise<Response>;\n}\n\nexport const bearerToken =\n\t\"AAAAAAAAAAAAAAAAAAAAAFQODgEAAAAAVHTp76lzh3rFzcHbmHVvQxYYpTw%3DckAlMINMjmCwxUcaXbAN4XqJVdgMJaHqNOFgPMK0zN1qLqLQCF\";\n\n/**\n * An API result container.\n */\nexport type RequestApiResult<T> =\n\t| { success: true; value: T }\n\t| { 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\turl: string,\n\tauth: TwitterAuth,\n\tmethod: \"GET\" | \"POST\" = \"GET\",\n\tplatform: PlatformExtensions = new Platform(),\n\tbody?: any,\n): Promise<RequestApiResult<T>> {\n\tconst headers = new Headers();\n\tawait auth.installTo(headers, url);\n\tawait platform.randomizeCiphers();\n\n\tlet res: Response;\n\tdo {\n\t\ttry {\n\t\t\tres = await auth.fetch(url, {\n\t\t\t\tmethod,\n\t\t\t\theaders: headers as any,\n\t\t\t\tcredentials: \"include\",\n\t\t\t\t...(body && { body: JSON.stringify(body) }),\n\t\t\t});\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof Error)) {\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terr: new Error(\"Failed to perform request.\"),\n\t\t\t};\n\t\t}\n\n\t\tawait updateCookieJar(auth.cookieJar(), res.headers);\n\n\t\tif (res.status === 429) {\n\t\t\t/*\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\t\t\tconst xRateLimitRemaining = res.headers.get(\"x-rate-limit-remaining\");\n\t\t\tconst xRateLimitReset = res.headers.get(\"x-rate-limit-reset\");\n\t\t\tif (xRateLimitRemaining === \"0\" && xRateLimitReset) {\n\t\t\t\tconst currentTime = new Date().valueOf() / 1000;\n\t\t\t\tconst timeDeltaMs =\n\t\t\t\t\t1000 * (Number.parseInt(xRateLimitReset) - currentTime);\n\n\t\t\t\t// I have seen this block for 800s (~13 *minutes*)\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, timeDeltaMs));\n\t\t\t}\n\t\t}\n\t} while (res.status === 429);\n\n\tif (!res.ok) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terr: await ApiError.fromResponse(res),\n\t\t};\n\t}\n\n\t// Check if response is chunked\n\tconst transferEncoding = res.headers.get(\"transfer-encoding\");\n\tif (transferEncoding === \"chunked\") {\n\t\t// Handle streaming response, if a reader is present\n\t\tconst reader =\n\t\t\ttypeof res.body?.getReader === \"function\" ? res.body.getReader() : null;\n\t\tif (!reader) {\n\t\t\ttry {\n\t\t\t\tconst text = await res.text();\n\t\t\t\ttry {\n\t\t\t\t\tconst value = JSON.parse(text);\n\t\t\t\t\treturn { success: true, value };\n\t\t\t\t} catch (_e) {\n\t\t\t\t\t// Return if just a normal string\n\t\t\t\t\treturn { success: true, value: { text } as any };\n\t\t\t\t}\n\t\t\t} catch (_e) {\n\t\t\t\treturn {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terr: new Error(\"No readable stream available and cant parse\"),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\tlet chunks: any = \"\";\n\t\t// Read all chunks before attempting to parse\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\n\t\t\t// Convert chunk to text and append\n\t\t\tchunks += new TextDecoder().decode(value);\n\n\t\t\t// Log chunk for debugging (optional)\n\t\t\t// console.log('Received chunk:', new TextDecoder().decode(value));\n\t\t}\n\n\t\t// Now try to parse the complete accumulated response\n\t\ttry {\n\t\t\t// console.log('attempting to parse chunks', chunks);\n\t\t\tconst value = JSON.parse(chunks);\n\t\t\treturn { success: true, value };\n\t\t} catch (_e) {\n\t\t\t// console.log('parsing chunks failed, sending as raw text');\n\t\t\t// If we can't parse as JSON, return the raw text\n\t\t\treturn { success: true, value: { text: chunks } as any };\n\t\t}\n\t}\n\n\t// Handle non-streaming responses as before\n\tconst contentType = res.headers.get(\"content-type\");\n\tif (contentType?.includes(\"application/json\")) {\n\t\tconst value: T = await res.json();\n\t\tif (res.headers.get(\"x-rate-limit-incoming\") === \"0\") {\n\t\t\tauth.deleteToken();\n\t\t}\n\t\treturn { success: true, value };\n\t}\n\n\treturn { success: true, value: {} as T };\n}\n\n/** @internal */\nexport function addApiFeatures(o: object) {\n\treturn {\n\t\t...o,\n\t\trweb_lists_timeline_redesign_enabled: true,\n\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\tverified_phone_label_enabled: false,\n\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\ttweetypie_unmention_optimization_enabled: true,\n\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\tview_counts_everywhere_api_enabled: true,\n\t\tlongform_notetweets_consumption_enabled: true,\n\t\ttweet_awards_web_tipping_enabled: false,\n\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\tstandardized_nudges_misinfo: true,\n\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\tresponsive_web_enhance_cards_enabled: false,\n\t\tsubscriptions_verification_info_enabled: true,\n\t\tsubscriptions_verification_info_reason_enabled: true,\n\t\tsubscriptions_verification_info_verified_since_enabled: true,\n\t\tsuper_follow_badge_privacy_enabled: false,\n\t\tsuper_follow_exclusive_tweet_notifications_enabled: false,\n\t\tsuper_follow_tweet_api_enabled: false,\n\t\tsuper_follow_user_api_enabled: false,\n\t\tandroid_graphql_skip_api_media_color_palette: false,\n\t\tcreator_subscriptions_subscription_count_enabled: false,\n\t\tblue_business_profile_image_shape_enabled: false,\n\t\tunified_cards_ad_metadata_container_dynamic_card_content_query_enabled: false,\n\t};\n}\n\nexport function addApiParams(\n\tparams: URLSearchParams,\n\tincludeTweetReplies: boolean,\n): URLSearchParams {\n\tparams.set(\"include_profile_interstitial_type\", \"1\");\n\tparams.set(\"include_blocking\", \"1\");\n\tparams.set(\"include_blocked_by\", \"1\");\n\tparams.set(\"include_followed_by\", \"1\");\n\tparams.set(\"include_want_retweets\", \"1\");\n\tparams.set(\"include_mute_edge\", \"1\");\n\tparams.set(\"include_can_dm\", \"1\");\n\tparams.set(\"include_can_media_tag\", \"1\");\n\tparams.set(\"include_ext_has_nft_avatar\", \"1\");\n\tparams.set(\"include_ext_is_blue_verified\", \"1\");\n\tparams.set(\"include_ext_verified_type\", \"1\");\n\tparams.set(\"skip_status\", \"1\");\n\tparams.set(\"cards_platform\", \"Web-12\");\n\tparams.set(\"include_cards\", \"1\");\n\tparams.set(\"include_ext_alt_text\", \"true\");\n\tparams.set(\"include_ext_limited_action_results\", \"false\");\n\tparams.set(\"include_quote_count\", \"true\");\n\tparams.set(\"include_reply_count\", \"1\");\n\tparams.set(\"tweet_mode\", \"extended\");\n\tparams.set(\"include_ext_collab_control\", \"true\");\n\tparams.set(\"include_ext_views\", \"true\");\n\tparams.set(\"include_entities\", \"true\");\n\tparams.set(\"include_user_entities\", \"true\");\n\tparams.set(\"include_ext_media_color\", \"true\");\n\tparams.set(\"include_ext_media_availability\", \"true\");\n\tparams.set(\"include_ext_sensitive_media_warning\", \"true\");\n\tparams.set(\"include_ext_trusted_friends_metadata\", \"true\");\n\tparams.set(\"send_error_codes\", \"true\");\n\tparams.set(\"simple_quoted_tweet\", \"true\");\n\tparams.set(\"include_tweet_replies\", `${includeTweetReplies}`);\n\tparams.set(\n\t\t\"ext\",\n\t\t\"mediaStats,highlightedLabel,hasNftAvatar,voiceInfo,birdwatchPivot,enrichments,superFollowMetadata,unmentionInfo,editControl,collab_control,vibe\",\n\t);\n\treturn params;\n}\n","import { type Cookie, CookieJar, type MemoryCookieStore } from \"tough-cookie\";\nimport { updateCookieJar } from \"./requests\";\nimport { Headers } from \"headers-polyfill\";\nimport type { FetchTransformOptions } from \"./api\";\nimport { TwitterApi } from \"twitter-api-v2\";\nimport type { Profile } from \"./profile\";\n\nexport interface TwitterAuthOptions {\n\tfetch: typeof fetch;\n\ttransform: Partial<FetchTransformOptions>;\n}\n\nexport interface TwitterAuth {\n\tfetch: typeof fetch;\n\n\t/**\n\t * Returns the current cookie jar.\n\t */\n\tcookieJar(): CookieJar;\n\n\t/**\n\t * Logs into a Twitter account using the v2 API\n\t */\n\tloginWithV2(\n\t\tappKey: string,\n\t\tappSecret: string,\n\t\taccessToken: string,\n\t\taccessSecret: string,\n\t): void;\n\n\t/**\n\t * Get v2 API client if it exists\n\t */\n\tgetV2Client(): TwitterApi | null;\n\n\t/**\n\t * Returns if a user is logged-in to Twitter through this instance.\n\t * @returns `true` if a user is logged-in; otherwise `false`.\n\t */\n\tisLoggedIn(): Promise<boolean>;\n\n\t/**\n\t * Fetches the current user's profile.\n\t */\n\tme(): Promise<Profile | undefined>;\n\n\t/**\n\t * Logs into a Twitter account.\n\t * @param username The username to log in with.\n\t * @param password The password to log in with.\n\t * @param email The email to log in with, if you have email confirmation enabled.\n\t * @param twoFactorSecret The secret to generate two factor authentication tokens with, if you have two factor authentication enabled.\n\t */\n\tlogin(\n\t\tusername: string,\n\t\tpassword: string,\n\t\temail?: string,\n\t\ttwoFactorSecret?: string,\n\t): Promise<void>;\n\n\t/**\n\t * Logs out of the current session.\n\t */\n\tlogout(): Promise<void>;\n\n\t/**\n\t * Deletes the current guest token token.\n\t */\n\tdeleteToken(): void;\n\n\t/**\n\t * Returns if the authentication state has a token.\n\t * @returns `true` if the authentication state has a token; `false` otherwise.\n\t */\n\thasToken(): boolean;\n\n\t/**\n\t * Returns the time that authentication was performed.\n\t * @returns The time at which the authentication token was created, or `null` if it hasn't been created yet.\n\t */\n\tauthenticatedAt(): Date | null;\n\n\t/**\n\t * Installs the authentication information into a headers-like object. If needed, the\n\t * authentication token will be updated from the API automatically.\n\t * @param headers A Headers instance representing a request's headers.\n\t */\n\tinstallTo(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\tfetchFn: typeof fetch,\n\ttransform?: Partial<FetchTransformOptions>,\n): typeof fetch {\n\treturn async (input, init) => {\n\t\tconst fetchArgs = (await transform?.request?.(input, init)) ?? [\n\t\t\tinput,\n\t\t\tinit,\n\t\t];\n\t\t// @ts-expect-error don't care\n\t\tconst res = await fetchFn(...fetchArgs);\n\t\treturn (await transform?.response?.(res)) ?? res;\n\t};\n}\n\n/**\n * A guest authentication token manager. Automatically handles token refreshes.\n */\nexport class TwitterGuestAuth implements TwitterAuth {\n\tprotected bearerToken: string;\n\tprotected jar: CookieJar;\n\tprotected guestToken?: string;\n\tprotected guestCreatedAt?: Date;\n\tprotected v2Client: TwitterApi | null;\n\n\tfetch: typeof fetch;\n\n\tconstructor(\n\t\tbearerToken: string,\n\t\tprotected readonly options?: Partial<TwitterAuthOptions>,\n\t) {\n\t\tthis.fetch = withTransform(options?.fetch ?? fetch, options?.transform);\n\t\tthis.bearerToken = bearerToken;\n\t\tthis.jar = new CookieJar();\n\t\tthis.v2Client = null;\n\t}\n\n\tcookieJar(): CookieJar {\n\t\treturn this.jar;\n\t}\n\n\tgetV2Client(): TwitterApi | null {\n\t\treturn this.v2Client ?? null;\n\t}\n\n\tloginWithV2(\n\t\tappKey: string,\n\t\tappSecret: string,\n\t\taccessToken: string,\n\t\taccessSecret: string,\n\t): void {\n\t\tconst v2Client = new TwitterApi({\n\t\t\tappKey,\n\t\t\tappSecret,\n\t\t\taccessToken,\n\t\t\taccessSecret,\n\t\t});\n\t\tthis.v2Client = v2Client;\n\t}\n\n\tisLoggedIn(): Promise<boolean> {\n\t\treturn Promise.resolve(false);\n\t}\n\n\tasync me(): Promise<Profile | undefined> {\n\t\treturn undefined;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tlogin(_username: string, _password: string, _email?: string): Promise<void> {\n\t\treturn this.updateGuestToken();\n\t}\n\n\tlogout(): Promise<void> {\n\t\tthis.deleteToken();\n\t\tthis.jar = new CookieJar();\n\t\treturn Promise.resolve();\n\t}\n\n\tdeleteToken() {\n\t\tthis.guestToken = undefined;\n\t\tthis.guestCreatedAt = undefined;\n\t}\n\n\thasToken(): boolean {\n\t\treturn this.guestToken != null;\n\t}\n\n\tauthenticatedAt(): Date | null {\n\t\tif (this.guestCreatedAt == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn new Date(this.guestCreatedAt);\n\t}\n\n\tasync installTo(headers: Headers): Promise<void> {\n\t\tif (this.shouldUpdate()) {\n\t\t\tawait this.updateGuestToken();\n\t\t}\n\n\t\tconst token = this.guestToken;\n\t\tif (token == null) {\n\t\t\tthrow new Error(\"Authentication token is null or undefined.\");\n\t\t}\n\n\t\theaders.set(\"authorization\", `Bearer ${this.bearerToken}`);\n\t\theaders.set(\"x-guest-token\", token);\n\n\t\tconst cookies = await this.getCookies();\n\t\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\t\tif (xCsrfToken) {\n\t\t\theaders.set(\"x-csrf-token\", xCsrfToken.value);\n\t\t}\n\n\t\theaders.set(\"cookie\", await this.getCookieString());\n\t}\n\n\tprotected getCookies(): Promise<Cookie[]> {\n\t\treturn this.jar.getCookies(this.getCookieJarUrl());\n\t}\n\n\tprotected getCookieString(): Promise<string> {\n\t\treturn this.jar.getCookieString(this.getCookieJarUrl());\n\t}\n\n\tprotected async removeCookie(key: string): Promise<void> {\n\t\tconst store: MemoryCookieStore = this.jar.store;\n\t\tconst cookies = await this.jar.getCookies(this.getCookieJarUrl());\n\t\tfor (const cookie of cookies) {\n\t\t\tif (!cookie.domain || !cookie.path) continue;\n\t\t\tstore.removeCookie(cookie.domain, cookie.path, key);\n\n\t\t\tif (typeof document !== \"undefined\") {\n\t\t\t\tdocument.cookie = `${cookie.key}=; Max-Age=0; path=${cookie.path}; domain=${cookie.domain}`;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate getCookieJarUrl(): string {\n\t\treturn typeof document !== \"undefined\"\n\t\t\t? document.location.toString()\n\t\t\t: \"https://twitter.com\";\n\t}\n\n\t/**\n\t * Updates the authentication state with a new guest token from the Twitter API.\n\t */\n\tprotected async updateGuestToken() {\n\t\tconst guestActivateUrl = \"https://api.twitter.com/1.1/guest/activate.json\";\n\n\t\tconst headers = new Headers({\n\t\t\tAuthorization: `Bearer ${this.bearerToken}`,\n\t\t\tCookie: await this.getCookieString(),\n\t\t});\n\n\t\tconst res = await this.fetch(guestActivateUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: headers as any,\n\t\t\treferrerPolicy: \"no-referrer\",\n\t\t});\n\n\t\tawait updateCookieJar(this.jar, res.headers);\n\n\t\tif (!res.ok) {\n\t\t\tthrow new Error(await res.text());\n\t\t}\n\n\t\tconst o = await res.json();\n\t\tif (o == null || o.guest_token == null) {\n\t\t\tthrow new Error(\"guest_token not found.\");\n\t\t}\n\n\t\tconst newGuestToken = o.guest_token;\n\t\tif (typeof newGuestToken !== \"string\") {\n\t\t\tthrow new Error(\"guest_token was not a string.\");\n\t\t}\n\n\t\tthis.guestToken = newGuestToken;\n\t\tthis.guestCreatedAt = new Date();\n\t}\n\n\t/**\n\t * Returns if the authentication token needs to be updated or not.\n\t * @returns `true` if the token needs to be updated; `false` otherwise.\n\t */\n\tprivate shouldUpdate(): boolean {\n\t\treturn (\n\t\t\t!this.hasToken() ||\n\t\t\t(this.guestCreatedAt != null &&\n\t\t\t\tthis.guestCreatedAt <\n\t\t\t\t\tnew Date(new Date().valueOf() - 3 * 60 * 60 * 1000))\n\t\t);\n\t}\n}\n","import { type TwitterAuthOptions, TwitterGuestAuth } from \"./auth\";\nimport { requestApi } from \"./api\";\nimport { CookieJar } from \"tough-cookie\";\nimport { updateCookieJar } from \"./requests\";\nimport { Headers } from \"headers-polyfill\";\nimport type { TwitterApiErrorRaw } from \"./errors\";\nimport { Type, type Static } from \"@sinclair/typebox\";\nimport { Check } from \"@sinclair/typebox/value\";\nimport * as OTPAuth from \"otpauth\";\nimport { type LegacyUserRaw, parseProfile, type Profile } from \"./profile\";\n\ninterface TwitterUserAuthFlowInitRequest {\n\tflow_name: string;\n\tinput_flow_data: Record<string, unknown>;\n}\n\ninterface TwitterUserAuthFlowSubtaskRequest {\n\tflow_token: string;\n\tsubtask_inputs: ({\n\t\tsubtask_id: string;\n\t} & Record<string, unknown>)[];\n}\n\ntype TwitterUserAuthFlowRequest =\n\t| TwitterUserAuthFlowInitRequest\n\t| TwitterUserAuthFlowSubtaskRequest;\n\ninterface TwitterUserAuthFlowResponse {\n\terrors?: TwitterApiErrorRaw[];\n\tflow_token?: string;\n\tstatus?: string;\n\tsubtasks?: TwitterUserAuthSubtask[];\n}\n\ninterface TwitterUserAuthVerifyCredentials {\n\terrors?: TwitterApiErrorRaw[];\n}\n\nconst TwitterUserAuthSubtask = Type.Object({\n\tsubtask_id: Type.String(),\n\tenter_text: Type.Optional(Type.Object({})),\n});\ntype TwitterUserAuthSubtask = Static<typeof TwitterUserAuthSubtask>;\n\ntype FlowTokenResultSuccess = {\n\tstatus: \"success\";\n\tflowToken: string;\n\tsubtask?: 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\tprivate userProfile: Profile | undefined;\n\n\tasync isLoggedIn(): Promise<boolean> {\n\t\tconst res = await requestApi<TwitterUserAuthVerifyCredentials>(\n\t\t\t\"https://api.twitter.com/1.1/account/verify_credentials.json\",\n\t\t\tthis,\n\t\t);\n\t\tif (!res.success) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst { value: verify } = res;\n\t\tthis.userProfile = parseProfile(\n\t\t\tverify as LegacyUserRaw,\n\t\t\t(verify as unknown as { verified: boolean }).verified,\n\t\t);\n\t\treturn verify && !verify.errors?.length;\n\t}\n\n\tasync me(): Promise<Profile | undefined> {\n\t\tif (this.userProfile) {\n\t\t\treturn this.userProfile;\n\t\t}\n\t\tawait this.isLoggedIn();\n\t\treturn this.userProfile;\n\t}\n\n\tasync login(\n\t\tusername: string,\n\t\tpassword: string,\n\t\temail?: string,\n\t\ttwoFactorSecret?: string,\n\t\tappKey?: string,\n\t\tappSecret?: string,\n\t\taccessToken?: string,\n\t\taccessSecret?: string,\n\t): Promise<void> {\n\t\tawait this.updateGuestToken();\n\n\t\tlet next = await this.initLogin();\n\t\twhile (\"subtask\" in next && next.subtask) {\n\t\t\tif (next.subtask.subtask_id === \"LoginJsInstrumentationSubtask\") {\n\t\t\t\tnext = await this.handleJsInstrumentationSubtask(next);\n\t\t\t} else if (next.subtask.subtask_id === \"LoginEnterUserIdentifierSSO\") {\n\t\t\t\tnext = await this.handleEnterUserIdentifierSSO(next, username);\n\t\t\t} else if (\n\t\t\t\tnext.subtask.subtask_id === \"LoginEnterAlternateIdentifierSubtask\"\n\t\t\t) {\n\t\t\t\tnext = await this.handleEnterAlternateIdentifierSubtask(\n\t\t\t\t\tnext,\n\t\t\t\t\temail as string,\n\t\t\t\t);\n\t\t\t} else if (next.subtask.subtask_id === \"LoginEnterPassword\") {\n\t\t\t\tnext = await this.handleEnterPassword(next, password);\n\t\t\t} else if (next.subtask.subtask_id === \"AccountDuplicationCheck\") {\n\t\t\t\tnext = await this.handleAccountDuplicationCheck(next);\n\t\t\t} else if (next.subtask.subtask_id === \"LoginTwoFactorAuthChallenge\") {\n\t\t\t\tif (twoFactorSecret) {\n\t\t\t\t\tnext = await this.handleTwoFactorAuthChallenge(next, twoFactorSecret);\n\t\t\t\t} else {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\"Requested two factor authentication code but no secret provided\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} else if (next.subtask.subtask_id === \"LoginAcid\") {\n\t\t\t\tnext = await this.handleAcid(next, email);\n\t\t\t} else if (next.subtask.subtask_id === \"LoginSuccessSubtask\") {\n\t\t\t\tnext = await this.handleSuccessSubtask(next);\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Unknown subtask ${next.subtask.subtask_id}`);\n\t\t\t}\n\t\t}\n\t\tif (appKey && appSecret && accessToken && accessSecret) {\n\t\t\tthis.loginWithV2(appKey, appSecret, accessToken, accessSecret);\n\t\t}\n\t\tif (\"err\" in next) {\n\t\t\tthrow next.err;\n\t\t}\n\t}\n\n\tasync logout(): Promise<void> {\n\t\tif (!this.isLoggedIn()) {\n\t\t\treturn;\n\t\t}\n\n\t\tawait requestApi<void>(\n\t\t\t\"https://api.twitter.com/1.1/account/logout.json\",\n\t\t\tthis,\n\t\t\t\"POST\",\n\t\t);\n\t\tthis.deleteToken();\n\t\tthis.jar = new CookieJar();\n\t}\n\n\tasync installCsrfToken(headers: Headers): Promise<void> {\n\t\tconst cookies = await this.getCookies();\n\t\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\t\tif (xCsrfToken) {\n\t\t\theaders.set(\"x-csrf-token\", xCsrfToken.value);\n\t\t}\n\t}\n\n\tasync installTo(headers: Headers): Promise<void> {\n\t\theaders.set(\"authorization\", `Bearer ${this.bearerToken}`);\n\t\theaders.set(\"cookie\", await this.getCookieString());\n\t\tawait this.installCsrfToken(headers);\n\t}\n\n\tprivate async initLogin() {\n\t\t// Reset certain session-related cookies because Twitter complains sometimes if we don't\n\t\tthis.removeCookie(\"twitter_ads_id=\");\n\t\tthis.removeCookie(\"ads_prefs=\");\n\t\tthis.removeCookie(\"_twitter_sess=\");\n\t\tthis.removeCookie(\"zipbox_forms_auth_token=\");\n\t\tthis.removeCookie(\"lang=\");\n\t\tthis.removeCookie(\"bouncer_reset_cookie=\");\n\t\tthis.removeCookie(\"twid=\");\n\t\tthis.removeCookie(\"twitter_ads_idb=\");\n\t\tthis.removeCookie(\"email_uid=\");\n\t\tthis.removeCookie(\"external_referer=\");\n\t\tthis.removeCookie(\"ct0=\");\n\t\tthis.removeCookie(\"aa_u=\");\n\n\t\treturn await this.executeFlowTask({\n\t\t\tflow_name: \"login\",\n\t\t\tinput_flow_data: {\n\t\t\t\tflow_context: {\n\t\t\t\t\tdebug_overrides: {},\n\t\t\t\t\tstart_location: {\n\t\t\t\t\t\tlocation: \"splash_screen\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t});\n\t}\n\n\tprivate async handleJsInstrumentationSubtask(prev: FlowTokenResultSuccess) {\n\t\treturn await this.executeFlowTask({\n\t\t\tflow_token: prev.flowToken,\n\t\t\tsubtask_inputs: [\n\t\t\t\t{\n\t\t\t\t\tsubtask_id: \"LoginJsInstrumentationSubtask\",\n\t\t\t\t\tjs_instrumentation: {\n\t\t\t\t\t\tresponse: \"{}\",\n\t\t\t\t\t\tlink: \"next_link\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t});\n\t}\n\n\tprivate async handleEnterAlternateIdentifierSubtask(\n\t\tprev: FlowTokenResultSuccess,\n\t\temail: string,\n\t) {\n\t\treturn await this.executeFlowTask({\n\t\t\tflow_token: prev.flowToken,\n\t\t\tsubtask_inputs: [\n\t\t\t\t{\n\t\t\t\t\tsubtask_id: \"LoginEnterAlternateIdentifierSubtask\",\n\t\t\t\t\tenter_text: {\n\t\t\t\t\t\ttext: email,\n\t\t\t\t\t\tlink: \"next_link\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t});\n\t}\n\n\tprivate async handleEnterUserIdentifierSSO(\n\t\tprev: FlowTokenResultSuccess,\n\t\tusername: string,\n\t) {\n\t\treturn await this.executeFlowTask({\n\t\t\tflow_token: prev.flowToken,\n\t\t\tsubtask_inputs: [\n\t\t\t\t{\n\t\t\t\t\tsubtask_id: \"LoginEnterUserIdentifierSSO\",\n\t\t\t\t\tsettings_list: {\n\t\t\t\t\t\tsetting_responses: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tkey: \"user_identifier\",\n\t\t\t\t\t\t\t\tresponse_data: {\n\t\t\t\t\t\t\t\t\ttext_data: { result: username },\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tlink: \"next_link\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t});\n\t}\n\n\tprivate async handleEnterPassword(\n\t\tprev: FlowTokenResultSuccess,\n\t\tpassword: string,\n\t) {\n\t\treturn await this.executeFlowTask({\n\t\t\tflow_token: prev.flowToken,\n\t\t\tsubtask_inputs: [\n\t\t\t\t{\n\t\t\t\t\tsubtask_id: \"LoginEnterPassword\",\n\t\t\t\t\tenter_password: {\n\t\t\t\t\t\tpassword,\n\t\t\t\t\t\tlink: \"next_link\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t});\n\t}\n\n\tprivate async handleAccountDuplicationCheck(prev: FlowTokenResultSuccess) {\n\t\treturn await this.executeFlowTask({\n\t\t\tflow_token: prev.flowToken,\n\t\t\tsubtask_inputs: [\n\t\t\t\t{\n\t\t\t\t\tsubtask_id: \"AccountDuplicationCheck\",\n\t\t\t\t\tcheck_logged_in_account: {\n\t\t\t\t\t\tlink: \"AccountDuplicationCheck_false\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t});\n\t}\n\n\tprivate async handleTwoFactorAuthChallenge(\n\t\tprev: FlowTokenResultSuccess,\n\t\tsecret: string,\n\t) {\n\t\tconst totp = new OTPAuth.TOTP({ secret });\n\t\tlet error;\n\t\tfor (let attempts = 1; attempts < 4; attempts += 1) {\n\t\t\ttry {\n\t\t\t\treturn await this.executeFlowTask({\n\t\t\t\t\tflow_token: prev.flowToken,\n\t\t\t\t\tsubtask_inputs: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsubtask_id: \"LoginTwoFactorAuthChallenge\",\n\t\t\t\t\t\t\tenter_text: {\n\t\t\t\t\t\t\t\tlink: \"next_link\",\n\t\t\t\t\t\t\t\ttext: totp.generate(),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\terror = err;\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 2000 * attempts));\n\t\t\t}\n\t\t}\n\t\tthrow error;\n\t}\n\n\tprivate async handleAcid(\n\t\tprev: FlowTokenResultSuccess,\n\t\temail: string | undefined,\n\t) {\n\t\treturn await this.executeFlowTask({\n\t\t\tflow_token: prev.flowToken,\n\t\t\tsubtask_inputs: [\n\t\t\t\t{\n\t\t\t\t\tsubtask_id: \"LoginAcid\",\n\t\t\t\t\tenter_text: {\n\t\t\t\t\t\ttext: email,\n\t\t\t\t\t\tlink: \"next_link\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t],\n\t\t});\n\t}\n\n\tprivate async handleSuccessSubtask(prev: FlowTokenResultSuccess) {\n\t\treturn await this.executeFlowTask({\n\t\t\tflow_token: prev.flowToken,\n\t\t\tsubtask_inputs: [],\n\t\t});\n\t}\n\n\tprivate async executeFlowTask(\n\t\tdata: TwitterUserAuthFlowRequest,\n\t): Promise<FlowTokenResult> {\n\t\tconst onboardingTaskUrl =\n\t\t\t\"https://api.twitter.com/1.1/onboarding/task.json\";\n\n\t\tconst token = this.guestToken;\n\t\tif (token == null) {\n\t\t\tthrow new Error(\"Authentication token is null or undefined.\");\n\t\t}\n\n\t\tconst headers = new Headers({\n\t\t\tauthorization: `Bearer ${this.bearerToken}`,\n\t\t\tcookie: await this.getCookieString(),\n\t\t\t\"content-type\": \"application/json\",\n\t\t\t\"User-Agent\":\n\t\t\t\t\"Mozilla/5.0 (Linux; Android 11; Nokia G20) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.88 Mobile Safari/537.36\",\n\t\t\t\"x-guest-token\": token,\n\t\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\t\"x-twitter-client-language\": \"en\",\n\t\t});\n\t\tawait this.installCsrfToken(headers);\n\n\t\tconst res = await this.fetch(onboardingTaskUrl, {\n\t\t\tcredentials: \"include\",\n\t\t\tmethod: \"POST\",\n\t\t\theaders: headers,\n\t\t\tbody: JSON.stringify(data),\n\t\t});\n\n\t\tawait updateCookieJar(this.jar, res.headers);\n\n\t\tif (!res.ok) {\n\t\t\treturn { status: \"error\", err: new Error(await res.text()) };\n\t\t}\n\n\t\tconst flow: TwitterUserAuthFlowResponse = await res.json();\n\t\tif (flow?.flow_token == null) {\n\t\t\treturn { status: \"error\", err: new Error(\"flow_token not found.\") };\n\t\t}\n\n\t\tif (flow.errors?.length) {\n\t\t\treturn {\n\t\t\t\tstatus: \"error\",\n\t\t\t\terr: new Error(\n\t\t\t\t\t`Authentication error (${flow.errors[0].code}): ${flow.errors[0].message}`,\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\n\t\tif (typeof flow.flow_token !== \"string\") {\n\t\t\treturn {\n\t\t\t\tstatus: \"error\",\n\t\t\t\terr: new Error(\"flow_token was not a string.\"),\n\t\t\t};\n\t\t}\n\n\t\tconst subtask = flow.subtasks?.length ? flow.subtasks[0] : undefined;\n\t\tCheck(TwitterUserAuthSubtask, subtask);\n\n\t\tif (subtask && subtask.subtask_id === \"DenyLoginSubtask\") {\n\t\t\treturn {\n\t\t\t\tstatus: \"error\",\n\t\t\t\terr: new Error(\"Authentication error: DenyLoginSubtask\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tstatus: \"success\",\n\t\t\tsubtask,\n\t\t\tflowToken: flow.flow_token,\n\t\t};\n\t}\n}\n","import stringify from \"json-stable-stringify\";\nimport { requestApi, type RequestApiResult } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport type { TwitterApiErrorRaw } from \"./errors\";\n\nexport interface LegacyUserRaw {\n\tcreated_at?: string;\n\tdescription?: string;\n\tentities?: {\n\t\turl?: {\n\t\t\turls?: {\n\t\t\t\texpanded_url?: string;\n\t\t\t}[];\n\t\t};\n\t};\n\tfavourites_count?: number;\n\tfollowers_count?: number;\n\tfriends_count?: number;\n\tmedia_count?: number;\n\tstatuses_count?: number;\n\tid_str?: string;\n\tlisted_count?: number;\n\tname?: string;\n\tlocation: string;\n\tgeo_enabled?: boolean;\n\tpinned_tweet_ids_str?: string[];\n\tprofile_background_color?: string;\n\tprofile_banner_url?: string;\n\tprofile_image_url_https?: string;\n\tprotected?: boolean;\n\tscreen_name?: string;\n\tverified?: boolean;\n\thas_custom_timelines?: boolean;\n\thas_extended_profile?: boolean;\n\turl?: string;\n\tcan_dm?: boolean;\n}\n\n/**\n * A parsed profile object.\n */\nexport interface Profile {\n\tavatar?: string;\n\tbanner?: string;\n\tbiography?: string;\n\tbirthday?: string;\n\tfollowersCount?: number;\n\tfollowingCount?: number;\n\tfriendsCount?: number;\n\tmediaCount?: number;\n\tstatusesCount?: number;\n\tisPrivate?: boolean;\n\tisVerified?: boolean;\n\tisBlueVerified?: boolean;\n\tjoined?: Date;\n\tlikesCount?: number;\n\tlistedCount?: number;\n\tlocation: string;\n\tname?: string;\n\tpinnedTweetIds?: string[];\n\ttweetsCount?: number;\n\turl?: string;\n\tuserId?: string;\n\tusername?: string;\n\twebsite?: string;\n\tcanDm?: boolean;\n}\n\nexport interface UserRaw {\n\tdata: {\n\t\tuser: {\n\t\t\tresult: {\n\t\t\t\trest_id?: string;\n\t\t\t\tis_blue_verified?: boolean;\n\t\t\t\tlegacy: LegacyUserRaw;\n\t\t\t};\n\t\t};\n\t};\n\terrors?: TwitterApiErrorRaw[];\n}\n\nfunction getAvatarOriginalSizeUrl(avatarUrl: string | undefined) {\n\treturn avatarUrl ? avatarUrl.replace(\"_normal\", \"\") : undefined;\n}\n\nexport function parseProfile(\n\tuser: LegacyUserRaw,\n\tisBlueVerified?: boolean,\n): Profile {\n\tconst profile: Profile = {\n\t\tavatar: getAvatarOriginalSizeUrl(user.profile_image_url_https),\n\t\tbanner: user.profile_banner_url,\n\t\tbiography: user.description,\n\t\tfollowersCount: user.followers_count,\n\t\tfollowingCount: user.friends_count,\n\t\tfriendsCount: user.friends_count,\n\t\tmediaCount: user.media_count,\n\t\tisPrivate: user.protected ?? false,\n\t\tisVerified: user.verified,\n\t\tlikesCount: user.favourites_count,\n\t\tlistedCount: user.listed_count,\n\t\tlocation: user.location,\n\t\tname: user.name,\n\t\tpinnedTweetIds: user.pinned_tweet_ids_str,\n\t\ttweetsCount: user.statuses_count,\n\t\turl: `https://twitter.com/${user.screen_name}`,\n\t\tuserId: user.id_str,\n\t\tusername: user.screen_name,\n\t\tisBlueVerified: isBlueVerified ?? false,\n\t\tcanDm: user.can_dm,\n\t};\n\n\tif (user.created_at != null) {\n\t\tprofile.joined = new Date(Date.parse(user.created_at));\n\t}\n\n\tconst urls = user.entities?.url?.urls;\n\tif (urls?.length != null && urls?.length > 0) {\n\t\tprofile.website = urls[0].expanded_url;\n\t}\n\n\treturn profile;\n}\n\nexport async function getProfile(\n\tusername: string,\n\tauth: TwitterAuth,\n): Promise<RequestApiResult<Profile>> {\n\tconst params = new URLSearchParams();\n\tparams.set(\n\t\t\"variables\",\n\t\tstringify({\n\t\t\tscreen_name: username,\n\t\t\twithSafetyModeUserFields: true,\n\t\t}) ?? \"\",\n\t);\n\n\tparams.set(\n\t\t\"features\",\n\t\tstringify({\n\t\t\thidden_profile_likes_enabled: false,\n\t\t\thidden_profile_subscriptions_enabled: false, // Auth-restricted\n\t\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\t\tverified_phone_label_enabled: false,\n\t\t\tsubscriptions_verification_info_is_identity_verified_enabled: false,\n\t\t\tsubscriptions_verification_info_verified_since_enabled: true,\n\t\t\thighlights_tweets_tab_ui_enabled: true,\n\t\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\t}) ?? \"\",\n\t);\n\n\tparams.set(\n\t\t\"fieldToggles\",\n\t\tstringify({ withAuxiliaryUserLabels: false }) ?? \"\",\n\t);\n\n\tconst res = await requestApi<UserRaw>(\n\t\t`https://twitter.com/i/api/graphql/G3KGOASz96M-Qu0nwmGXNg/UserByScreenName?${params.toString()}`,\n\t\tauth,\n\t);\n\tif (!res.success) {\n\t\treturn res as any;\n\t}\n\n\tconst { value } = res;\n\tconst { errors } = value;\n\tif (errors != null && errors.length > 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terr: new Error(errors[0].message),\n\t\t};\n\t}\n\n\tif (!value.data || !value.data.user || !value.data.user.result) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terr: new Error(\"User not found.\"),\n\t\t};\n\t}\n\tconst { result: user } = value.data.user;\n\tconst { legacy } = user;\n\n\tif (user.rest_id == null || user.rest_id.length === 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terr: new Error(\"rest_id not found.\"),\n\t\t};\n\t}\n\n\tlegacy.id_str = user.rest_id;\n\n\tif (legacy.screen_name == null || legacy.screen_name.length === 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terr: new Error(`Either ${username} does not exist or is private.`),\n\t\t};\n\t}\n\n\treturn {\n\t\tsuccess: true,\n\t\tvalue: parseProfile(user.legacy, user.is_blue_verified),\n\t};\n}\n\nconst idCache = new Map<string, string>();\n\nexport async function getScreenNameByUserId(\n\tuserId: string,\n\tauth: TwitterAuth,\n): Promise<RequestApiResult<string>> {\n\tconst params = new URLSearchParams();\n\tparams.set(\n\t\t\"variables\",\n\t\tstringify({\n\t\t\tuserId: userId,\n\t\t\twithSafetyModeUserFields: true,\n\t\t}) ?? \"\",\n\t);\n\n\tparams.set(\n\t\t\"features\",\n\t\tstringify({\n\t\t\thidden_profile_subscriptions_enabled: true,\n\t\t\trweb_tipjar_consumption_enabled: true,\n\t\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\t\tverified_phone_label_enabled: false,\n\t\t\thighlights_tweets_tab_ui_enabled: true,\n\t\t\tresponsive_web_twitter_article_notes_tab_enabled: true,\n\t\t\tsubscriptions_feature_can_gift_premium: false,\n\t\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\t}) ?? \"\",\n\t);\n\n\tconst res = await requestApi<UserRaw>(\n\t\t`https://twitter.com/i/api/graphql/xf3jd90KKBCUxdlI_tNHZw/UserByRestId?${params.toString()}`,\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\treturn res as any;\n\t}\n\n\tconst { value } = res;\n\tconst { errors } = value;\n\tif (errors != null && errors.length > 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terr: new Error(errors[0].message),\n\t\t};\n\t}\n\n\tif (!value.data || !value.data.user || !value.data.user.result) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terr: new Error(\"User not found.\"),\n\t\t};\n\t}\n\n\tconst { result: user } = value.data.user;\n\tconst { legacy } = user;\n\n\tif (legacy.screen_name == null || legacy.screen_name.length === 0) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terr: new Error(\n\t\t\t\t`Either user with ID ${userId} does not exist or is private.`,\n\t\t\t),\n\t\t};\n\t}\n\n\treturn {\n\t\tsuccess: true,\n\t\tvalue: legacy.screen_name,\n\t};\n}\n\nexport async function getUserIdByScreenName(\n\tscreenName: string,\n\tauth: TwitterAuth,\n): Promise<RequestApiResult<string>> {\n\tconst cached = idCache.get(screenName);\n\tif (cached != null) {\n\t\treturn { success: true, value: cached };\n\t}\n\n\tconst profileRes = await getProfile(screenName, auth);\n\tif (!profileRes.success) {\n\t\treturn profileRes as any;\n\t}\n\n\tconst profile = profileRes.value;\n\tif (profile.userId != null) {\n\t\tidCache.set(screenName, profile.userId);\n\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: profile.userId,\n\t\t};\n\t}\n\n\treturn {\n\t\tsuccess: false,\n\t\terr: new Error(\"User ID is undefined.\"),\n\t};\n}\n","import type { Profile } from \"./profile\";\nimport type { Tweet } from \"./tweets\";\n\nexport interface FetchProfilesResponse {\n\tprofiles: Profile[];\n\tnext?: string;\n}\n\nexport type FetchProfiles = (\n\tquery: string,\n\tmaxProfiles: number,\n\tcursor: string | undefined,\n) => Promise<FetchProfilesResponse>;\n\nexport interface FetchTweetsResponse {\n\ttweets: Tweet[];\n\tnext?: string;\n}\n\nexport type FetchTweets = (\n\tquery: string,\n\tmaxTweets: number,\n\tcursor: string | undefined,\n) => Promise<FetchTweetsResponse>;\n\nexport async function* getUserTimeline(\n\tquery: string,\n\tmaxProfiles: number,\n\tfetchFunc: FetchProfiles,\n): AsyncGenerator<Profile, void> {\n\tlet nProfiles = 0;\n\tlet cursor: string | undefined = undefined;\n\tlet consecutiveEmptyBatches = 0;\n\twhile (nProfiles < maxProfiles) {\n\t\tconst batch: FetchProfilesResponse = await fetchFunc(\n\t\t\tquery,\n\t\t\tmaxProfiles,\n\t\t\tcursor,\n\t\t);\n\n\t\tconst { profiles, next } = batch;\n\t\tcursor = next;\n\n\t\tif (profiles.length === 0) {\n\t\t\tconsecutiveEmptyBatches++;\n\t\t\tif (consecutiveEmptyBatches > 5) break;\n\t\t} else consecutiveEmptyBatches = 0;\n\n\t\tfor (const profile of profiles) {\n\t\t\tif (nProfiles < maxProfiles) yield profile;\n\t\t\telse break;\n\t\t\tnProfiles++;\n\t\t}\n\n\t\tif (!next) break;\n\t}\n}\n\nexport async function* getTweetTimeline(\n\tquery: string,\n\tmaxTweets: number,\n\tfetchFunc: FetchTweets,\n): AsyncGenerator<Tweet, void> {\n\tlet nTweets = 0;\n\tlet cursor: string | undefined = undefined;\n\twhile (nTweets < maxTweets) {\n\t\tconst batch: FetchTweetsResponse = await fetchFunc(\n\t\t\tquery,\n\t\t\tmaxTweets,\n\t\t\tcursor,\n\t\t);\n\n\t\tconst { tweets, next } = batch;\n\n\t\tif (tweets.length === 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tfor (const tweet of tweets) {\n\t\t\tif (nTweets < maxTweets) {\n\t\t\t\tcursor = next;\n\t\t\t\tyield tweet;\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tnTweets++;\n\t\t}\n\t}\n}\n","export type NonNullableField<T, K extends keyof T> = {\n\t[P in K]-?: T[P];\n} & T;\n\nexport function isFieldDefined<T, K extends keyof T>(key: K) {\n\treturn (value: T): value is NonNullableField<T, K> => isDefined(value[key]);\n}\n\nexport function isDefined<T>(value: T | null | undefined): value is T {\n\treturn value != null;\n}\n","import type { LegacyTweetRaw, TimelineMediaExtendedRaw } from \"./timeline-v1\";\nimport type { Photo, Video } from \"./tweets\";\nimport { isFieldDefined, type 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\tsensitiveContent?: boolean;\n\tphotos: Photo[];\n\tvideos: Video[];\n} {\n\tconst photos: Photo[] = [];\n\tconst videos: Video[] = [];\n\tlet sensitiveContent: boolean | undefined = undefined;\n\n\tfor (const m of media\n\t\t.filter(isFieldDefined(\"id_str\"))\n\t\t.filter(isFieldDefined(\"media_url_https\"))) {\n\t\tif (m.type === \"photo\") {\n\t\t\tphotos.push({\n\t\t\t\tid: m.id_str,\n\t\t\t\turl: m.media_url_https,\n\t\t\t\talt_text: m.ext_alt_text,\n\t\t\t});\n\t\t} else if (m.type === \"video\") {\n\t\t\tvideos.push(parseVideo(m));\n\t\t}\n\n\t\tconst sensitive = m.ext_sensitive_media_warning;\n\t\tif (sensitive != null) {\n\t\t\tsensitiveContent =\n\t\t\t\tsensitive.adult_content ||\n\t\t\t\tsensitive.graphic_violence ||\n\t\t\t\tsensitive.other;\n\t\t}\n\t}\n\n\treturn { sensitiveContent, photos, videos };\n}\n\nfunction parseVideo(\n\tm: NonNullableField<TimelineMediaExtendedRaw, \"id_str\" | \"media_url_https\">,\n): Video {\n\tconst video: Video = {\n\t\tid: m.id_str,\n\t\tpreview: m.media_url_https,\n\t};\n\n\tlet maxBitrate = 0;\n\tconst variants = m.video_info?.variants ?? [];\n\tfor (const variant of variants) {\n\t\tconst bitrate = variant.bitrate;\n\t\tif (bitrate != null && bitrate > maxBitrate && variant.url != null) {\n\t\t\tlet variantUrl = variant.url;\n\t\t\tconst stringStart = 0;\n\t\t\tconst tagSuffixIdx = variantUrl.indexOf(\"?tag=10\");\n\t\t\tif (tagSuffixIdx !== -1) {\n\t\t\t\tvariantUrl = variantUrl.substring(stringStart, tagSuffixIdx + 1);\n\t\t\t}\n\n\t\t\tvideo.url = variantUrl;\n\t\t\tmaxBitrate = bitrate;\n\t\t}\n\t}\n\n\treturn video;\n}\n\nexport function reconstructTweetHtml(\n\ttweet: LegacyTweetRaw,\n\tphotos: Photo[],\n\tvideos: Video[],\n): string {\n\tconst media: string[] = [];\n\n\t// HTML parsing with regex :)\n\tlet html = tweet.full_text ?? \"\";\n\n\thtml = html.replace(reHashtag, linkHashtagHtml);\n\thtml = html.replace(reCashtag, linkCashtagHtml);\n\thtml = html.replace(reUsername, linkUsernameHtml);\n\thtml = html.replace(reTwitterUrl, unwrapTcoUrlHtml(tweet, media));\n\n\tfor (const { url } of photos) {\n\t\tif (media.indexOf(url) !== -1) {\n\t\t\tcontinue;\n\t\t}\n\n\t\thtml += `<br><img src=\"${url}\"/>`;\n\t}\n\n\tfor (const { preview: url } of videos) {\n\t\tif (media.indexOf(url) !== -1) {\n\t\t\tcontinue;\n\t\t}\n\n\t\thtml += `<br><img src=\"${url}\"/>`;\n\t}\n\n\thtml = html.replace(/\\n/g, \"<br>\");\n\n\treturn html;\n}\n\nfunction linkHashtagHtml(hashtag: string) {\n\treturn `<a href=\"https://twitter.com/hashtag/${hashtag.replace(\n\t\t\"#\",\n\t\t\"\",\n\t)}\">${hashtag}</a>`;\n}\n\nfunction linkCashtagHtml(cashtag: string) {\n\treturn `<a href=\"https://twitter.com/search?q=%24${cashtag.replace(\n\t\t\"$\",\n\t\t\"\",\n\t)}\">${cashtag}</a>`;\n}\n\nfunction linkUsernameHtml(username: string) {\n\treturn `<a href=\"https://twitter.com/${username.replace(\n\t\t\"@\",\n\t\t\"\",\n\t)}\">${username}</a>`;\n}\n\nfunction unwrapTcoUrlHtml(tweet: LegacyTweetRaw, foundedMedia: string[]) {\n\treturn (tco: string) => {\n\t\tfor (const entity of tweet.entities?.urls ?? []) {\n\t\t\tif (tco === entity.url && entity.expanded_url != null) {\n\t\t\t\treturn `<a href=\"${entity.expanded_url}\">${tco}</a>`;\n\t\t\t}\n\t\t}\n\n\t\tfor (const entity of tweet.extended_entities?.media ?? []) {\n\t\t\tif (tco === entity.url && entity.media_url_https != null) {\n\t\t\t\tfoundedMedia.push(entity.media_url_https);\n\t\t\t\treturn `<br><a href=\"${tco}\"><img src=\"${entity.media_url_https}\"/></a>`;\n\t\t\t}\n\t\t}\n\n\t\treturn tco;\n\t};\n}\n","import type { LegacyUserRaw } from \"./profile\";\nimport { parseMediaGroups, reconstructTweetHtml } from \"./timeline-tweet-util\";\nimport type {\n\tLegacyTweetRaw,\n\tParseTweetResult,\n\tQueryTweetsResponse,\n\tSearchResultRaw,\n\tTimelineResultRaw,\n} from \"./timeline-v1\";\nimport type { Tweet } from \"./tweets\";\nimport { isFieldDefined } from \"./type-util\";\n\nexport interface TimelineUserResultRaw {\n\trest_id?: string;\n\tlegacy?: LegacyUserRaw;\n\tis_blue_verified?: boolean;\n}\n\nexport interface TimelineEntryItemContentRaw {\n\titemType?: string;\n\ttweetDisplayType?: string;\n\ttweetResult?: {\n\t\tresult?: TimelineResultRaw;\n\t};\n\ttweet_results?: {\n\t\tresult?: TimelineResultRaw;\n\t};\n\tuserDisplayType?: string;\n\tuser_results?: {\n\t\tresult?: TimelineUserResultRaw;\n\t};\n}\n\nexport interface TimelineEntryRaw {\n\tentryId: string;\n\tcontent?: {\n\t\tcursorType?: string;\n\t\tvalue?: string;\n\t\titems?: {\n\t\t\tentryId?: string;\n\t\t\titem?: {\n\t\t\t\tcontent?: TimelineEntryItemContentRaw;\n\t\t\t\titemContent?: SearchEntryItemContentRaw;\n\t\t\t};\n\t\t}[];\n\t\titemContent?: TimelineEntryItemContentRaw;\n\t};\n}\n\nexport interface SearchEntryItemContentRaw {\n\ttweetDisplayType?: string;\n\ttweet_results?: {\n\t\tresult?: SearchResultRaw;\n\t};\n\tuserDisplayType?: string;\n\tuser_results?: {\n\t\tresult?: TimelineUserResultRaw;\n\t};\n}\n\nexport interface SearchEntryRaw {\n\tentryId: string;\n\tsortIndex: string;\n\tcontent?: {\n\t\tcursorType?: string;\n\t\tentryType?: string;\n\t\t__typename?: string;\n\t\tvalue?: string;\n\t\titems?: {\n\t\t\titem?: {\n\t\t\t\tcontent?: SearchEntryItemContentRaw;\n\t\t\t};\n\t\t}[];\n\t\titemContent?: SearchEntryItemContentRaw;\n\t};\n}\n\nexport interface TimelineInstruction {\n\tentries?: TimelineEntryRaw[];\n\tentry?: TimelineEntryRaw;\n\ttype?: string;\n}\n\nexport interface TimelineV2 {\n\tdata?: {\n\t\tuser?: {\n\t\t\tresult?: {\n\t\t\t\ttimeline_v2?: {\n\t\t\t\t\ttimeline?: {\n\t\t\t\t\t\tinstructions?: TimelineInstruction[];\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n}\n\nexport interface ThreadedConversation {\n\tdata?: {\n\t\tthreaded_conversation_with_injections_v2?: {\n\t\t\tinstructions?: TimelineInstruction[];\n\t\t};\n\t};\n}\n\nexport function parseLegacyTweet(\n\tuser?: LegacyUserRaw,\n\ttweet?: LegacyTweetRaw,\n): ParseTweetResult {\n\tif (tweet == null) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terr: new Error(\"Tweet was not found in the timeline object.\"),\n\t\t};\n\t}\n\n\tif (user == null) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terr: new Error(\"User was not found in the timeline object.\"),\n\t\t};\n\t}\n\n\tif (!tweet.id_str) {\n\t\tif (!tweet.conversation_id_str) {\n\t\t\treturn {\n\t\t\t\tsuccess: false,\n\t\t\t\terr: new Error(\"Tweet ID was not found in object.\"),\n\t\t\t};\n\t\t}\n\n\t\ttweet.id_str = tweet.conversation_id_str;\n\t}\n\n\tconst hashtags = tweet.entities?.hashtags ?? [];\n\tconst mentions = tweet.entities?.user_mentions ?? [];\n\tconst media = tweet.extended_entities?.media ?? [];\n\tconst pinnedTweets = new Set<string | undefined>(\n\t\tuser.pinned_tweet_ids_str ?? [],\n\t);\n\tconst urls = tweet.entities?.urls ?? [];\n\tconst { photos, videos, sensitiveContent } = parseMediaGroups(media);\n\n\tconst tw: Tweet = {\n\t\tbookmarkCount: tweet.bookmark_count,\n\t\tconversationId: tweet.conversation_id_str,\n\t\tid: tweet.id_str,\n\t\thashtags: hashtags\n\t\t\t.filter(isFieldDefined(\"text\"))\n\t\t\t.map((hashtag) => hashtag.text),\n\t\tlikes: tweet.favorite_count,\n\t\tmentions: mentions.filter(isFieldDefined(\"id_str\")).map((mention) => ({\n\t\t\tid: mention.id_str,\n\t\t\tusername: mention.screen_name,\n\t\t\tname: mention.name,\n\t\t})),\n\t\tname: user.name,\n\t\tpermanentUrl: `https://twitter.com/${user.screen_name}/status/${tweet.id_str}`,\n\t\tphotos,\n\t\treplies: tweet.reply_count,\n\t\tretweets: tweet.retweet_count,\n\t\ttext: tweet.full_text,\n\t\tthread: [],\n\t\turls: urls\n\t\t\t.filter(isFieldDefined(\"expanded_url\"))\n\t\t\t.map((url) => url.expanded_url),\n\t\tuserId: tweet.user_id_str,\n\t\tusername: user.screen_name,\n\t\tvideos,\n\t\tisQuoted: false,\n\t\tisReply: false,\n\t\tisRetweet: false,\n\t\tisPin: false,\n\t\tsensitiveContent: false,\n\t};\n\n\tif (tweet.created_at) {\n\t\ttw.timeParsed = new Date(Date.parse(tweet.created_at));\n\t\ttw.timestamp = Math.floor(tw.timeParsed.valueOf() / 1000);\n\t}\n\n\tif (tweet.place?.id) {\n\t\ttw.place = tweet.place;\n\t}\n\n\tconst quotedStatusIdStr = tweet.quoted_status_id_str;\n\tconst inReplyToStatusIdStr = tweet.in_reply_to_status_id_str;\n\tconst retweetedStatusIdStr = tweet.retweeted_status_id_str;\n\tconst retweetedStatusResult = tweet.retweeted_status_result?.result;\n\n\tif (quotedStatusIdStr) {\n\t\ttw.isQuoted = true;\n\t\ttw.quotedStatusId = quotedStatusIdStr;\n\t}\n\n\tif (inReplyToStatusIdStr) {\n\t\ttw.isReply = true;\n\t\ttw.inReplyToStatusId = inReplyToStatusIdStr;\n\t}\n\n\tif (retweetedStatusIdStr || retweetedStatusResult) {\n\t\ttw.isRetweet = true;\n\t\ttw.retweetedStatusId = retweetedStatusIdStr;\n\n\t\tif (retweetedStatusResult) {\n\t\t\tconst parsedResult = parseLegacyTweet(\n\t\t\t\tretweetedStatusResult?.core?.user_results?.result?.legacy,\n\t\t\t\tretweetedStatusResult?.legacy,\n\t\t\t);\n\n\t\t\tif (parsedResult.success) {\n\t\t\t\ttw.retweetedStatus = parsedResult.tweet;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst views = Number.parseInt(tweet.ext_views?.count ?? \"\");\n\tif (!Number.isNaN(views)) {\n\t\ttw.views = views;\n\t}\n\n\tif (pinnedTweets.has(tweet.id_str)) {\n\t\t// TODO: Update tests so this can be assigned at the tweet declaration\n\t\ttw.isPin = true;\n\t}\n\n\tif (sensitiveContent) {\n\t\t// TODO: Update tests so this can be assigned at the tweet declaration\n\t\ttw.sensitiveContent = true;\n\t}\n\n\ttw.html = reconstructTweetHtml(tweet, tw.photos, tw.videos);\n\n\treturn { success: true, tweet: tw };\n}\n\nfunction parseResult(result?: TimelineResultRaw): ParseTweetResult {\n\tconst noteTweetResultText =\n\t\tresult?.note_tweet?.note_tweet_results?.result?.text;\n\n\tif (result?.legacy && noteTweetResultText) {\n\t\tresult.legacy.full_text = noteTweetResultText;\n\t}\n\n\tconst tweetResult = parseLegacyTweet(\n\t\tresult?.core?.user_results?.result?.legacy,\n\t\tresult?.legacy,\n\t);\n\tif (!tweetResult.success) {\n\t\treturn tweetResult;\n\t}\n\n\tif (!tweetResult.tweet.views && result?.views?.count) {\n\t\tconst views = Number.parseInt(result.views.count);\n\t\tif (!Number.isNaN(views)) {\n\t\t\ttweetResult.tweet.views = views;\n\t\t}\n\t}\n\n\tconst quotedResult = result?.quoted_status_result?.result;\n\tif (quotedResult) {\n\t\tif (quotedResult.legacy && quotedResult.rest_id) {\n\t\t\tquotedResult.legacy.id_str = quotedResult.rest_id;\n\t\t}\n\n\t\tconst quotedTweetResult = parseResult(quotedResult);\n\t\tif (quotedTweetResult.success) {\n\t\t\ttweetResult.tweet.quotedStatus = quotedTweetResult.tweet;\n\t\t}\n\t}\n\n\treturn tweetResult;\n}\n\nconst expectedEntryTypes = [\"tweet\", \"profile-conversation\"];\n\nexport function parseTimelineTweetsV2(\n\ttimeline: TimelineV2,\n): QueryTweetsResponse {\n\tlet bottomCursor: string | undefined;\n\tlet topCursor: string | undefined;\n\tconst tweets: Tweet[] = [];\n\tconst instructions =\n\t\ttimeline.data?.user?.result?.timeline_v2?.timeline?.instructions ?? [];\n\tfor (const instruction of instructions) {\n\t\tconst entries = instruction.entries ?? [];\n\n\t\tfor (const entry of entries) {\n\t\t\tconst entryContent = entry.content;\n\t\t\tif (!entryContent) continue;\n\n\t\t\t// Handle pagination\n\t\t\tif (entryContent.cursorType === \"Bottom\") {\n\t\t\t\tbottomCursor = entryContent.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entryContent.cursorType === \"Top\") {\n\t\t\t\ttopCursor = entryContent.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst idStr = entry.entryId;\n\t\t\tif (\n\t\t\t\t!expectedEntryTypes.some((entryType) => idStr.startsWith(entryType))\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (entryContent.itemContent) {\n\t\t\t\t// Typically TimelineTimelineTweet entries\n\t\t\t\tparseAndPush(tweets, entryContent.itemContent, idStr);\n\t\t\t} else if (entryContent.items) {\n\t\t\t\t// Typically TimelineTimelineModule entries\n\t\t\t\tfor (const item of entryContent.items) {\n\t\t\t\t\tif (item.item?.itemContent) {\n\t\t\t\t\t\tparseAndPush(tweets, item.item.itemContent, idStr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { tweets, next: bottomCursor, previous: topCursor };\n}\n\nexport function parseTimelineEntryItemContentRaw(\n\tcontent: TimelineEntryItemContentRaw,\n\tentryId: string,\n\tisConversation = false,\n) {\n\tlet result = content.tweet_results?.result ?? content.tweetResult?.result;\n\tif (\n\t\tresult?.__typename === \"Tweet\" ||\n\t\t(result?.__typename === \"TweetWithVisibilityResults\" && result?.tweet)\n\t) {\n\t\tif (result?.__typename === \"TweetWithVisibilityResults\")\n\t\t\tresult = result.tweet;\n\n\t\tif (result?.legacy) {\n\t\t\tresult.legacy.id_str =\n\t\t\t\tresult.rest_id ??\n\t\t\t\tentryId.replace(\"conversation-\", \"\").replace(\"tweet-\", \"\");\n\t\t}\n\n\t\tconst tweetResult = parseResult(result);\n\t\tif (tweetResult.success) {\n\t\t\tif (isConversation) {\n\t\t\t\tif (content?.tweetDisplayType === \"SelfThread\") {\n\t\t\t\t\ttweetResult.tweet.isSelfThread = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn tweetResult.tweet;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nexport function parseAndPush(\n\ttweets: Tweet[],\n\tcontent: TimelineEntryItemContentRaw,\n\tentryId: string,\n\tisConversation = false,\n) {\n\tconst tweet = parseTimelineEntryItemContentRaw(\n\t\tcontent,\n\t\tentryId,\n\t\tisConversation,\n\t);\n\n\tif (tweet) {\n\t\ttweets.push(tweet);\n\t}\n}\n\nexport function parseThreadedConversation(\n\tconversation: ThreadedConversation,\n): Tweet[] {\n\tconst tweets: Tweet[] = [];\n\tconst instructions =\n\t\tconversation.data?.threaded_conversation_with_injections_v2?.instructions ??\n\t\t[];\n\n\tfor (const instruction of instructions) {\n\t\tconst entries = instruction.entries ?? [];\n\t\tfor (const entry of entries) {\n\t\t\tconst entryContent = entry.content?.itemContent;\n\t\t\tif (entryContent) {\n\t\t\t\tparseAndPush(tweets, entryContent, entry.entryId, true);\n\t\t\t}\n\n\t\t\tfor (const item of entry.content?.items ?? []) {\n\t\t\t\tconst itemContent = item.item?.itemContent;\n\t\t\t\tif (itemContent) {\n\t\t\t\t\tparseAndPush(tweets, itemContent, entry.entryId, true);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const tweet of tweets) {\n\t\tif (tweet.inReplyToStatusId) {\n\t\t\tfor (const parentTweet of tweets) {\n\t\t\t\tif (parentTweet.id === tweet.inReplyToStatusId) {\n\t\t\t\t\ttweet.inReplyToStatus = parentTweet;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (tweet.isSelfThread && tweet.conversationId === tweet.id) {\n\t\t\tfor (const childTweet of tweets) {\n\t\t\t\tif (childTweet.isSelfThread && childTweet.id !== tweet.id) {\n\t\t\t\t\ttweet.thread.push(childTweet);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (tweet.thread.length === 0) {\n\t\t\t\ttweet.isSelfThread = false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn tweets;\n}\n\nexport interface TimelineArticle {\n\tid: string;\n\tarticleId: string;\n\ttitle: string;\n\tpreviewText: string;\n\tcoverMediaUrl?: string;\n\ttext: string;\n}\n\nexport function parseArticle(\n\tconversation: ThreadedConversation,\n): TimelineArticle[] {\n\tconst articles: TimelineArticle[] = [];\n\tfor (const instruction of conversation.data\n\t\t?.threaded_conversation_with_injections_v2?.instructions ?? []) {\n\t\tfor (const entry of instruction.entries ?? []) {\n\t\t\tconst id = entry.content?.itemContent?.tweet_results?.result?.rest_id;\n\t\t\tconst article =\n\t\t\t\tentry.content?.itemContent?.tweet_results?.result?.article\n\t\t\t\t\t?.article_results?.result;\n\t\t\tif (!id || !article) continue;\n\t\t\tconst text =\n\t\t\t\tarticle.content_state?.blocks\n\t\t\t\t\t?.map((block) => block.text)\n\t\t\t\t\t.join(\"\\n\\n\") ?? \"\";\n\t\t\tarticles.push({\n\t\t\t\tid,\n\t\t\t\tarticleId: article.rest_id || \"\",\n\t\t\t\tcoverMediaUrl: article.cover_media?.media_info?.original_img_url,\n\t\t\t\tpreviewText: article.preview_text || \"\",\n\t\t\t\ttext,\n\t\t\t\ttitle: article.title || \"\",\n\t\t\t});\n\t\t}\n\t}\n\treturn articles;\n}\n","import { type Profile, parseProfile } from \"./profile\";\nimport type { QueryProfilesResponse, QueryTweetsResponse } from \"./timeline-v1\";\nimport { type SearchEntryRaw, parseLegacyTweet } from \"./timeline-v2\";\nimport type { Tweet } from \"./tweets\";\n\nexport interface SearchTimeline {\n\tdata?: {\n\t\tsearch_by_raw_query?: {\n\t\t\tsearch_timeline?: {\n\t\t\t\ttimeline?: {\n\t\t\t\t\tinstructions?: {\n\t\t\t\t\t\tentries?: SearchEntryRaw[];\n\t\t\t\t\t\tentry?: SearchEntryRaw;\n\t\t\t\t\t\ttype?: string;\n\t\t\t\t\t}[];\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n}\n\nexport function parseSearchTimelineTweets(\n\ttimeline: SearchTimeline,\n): QueryTweetsResponse {\n\tlet bottomCursor: string | undefined;\n\tlet topCursor: string | undefined;\n\tconst tweets: Tweet[] = [];\n\tconst instructions =\n\t\ttimeline.data?.search_by_raw_query?.search_timeline?.timeline\n\t\t\t?.instructions ?? [];\n\tfor (const instruction of instructions) {\n\t\tif (\n\t\t\tinstruction.type === \"TimelineAddEntries\" ||\n\t\t\tinstruction.type === \"TimelineReplaceEntry\"\n\t\t) {\n\t\t\tif (instruction.entry?.content?.cursorType === \"Bottom\") {\n\t\t\t\tbottomCursor = instruction.entry.content.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (instruction.entry?.content?.cursorType === \"Top\") {\n\t\t\t\ttopCursor = instruction.entry.content.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst entries = instruction.entries ?? [];\n\t\t\tfor (const entry of entries) {\n\t\t\t\tconst itemContent = entry.content?.itemContent;\n\t\t\t\tif (itemContent?.tweetDisplayType === \"Tweet\") {\n\t\t\t\t\tconst tweetResultRaw = itemContent.tweet_results?.result;\n\t\t\t\t\tconst tweetResult = parseLegacyTweet(\n\t\t\t\t\t\ttweetResultRaw?.core?.user_results?.result?.legacy,\n\t\t\t\t\t\ttweetResultRaw?.legacy,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (tweetResult.success) {\n\t\t\t\t\t\tif (!tweetResult.tweet.views && tweetResultRaw?.views?.count) {\n\t\t\t\t\t\t\tconst views = Number.parseInt(tweetResultRaw.views.count);\n\t\t\t\t\t\t\tif (!Number.isNaN(views)) {\n\t\t\t\t\t\t\t\ttweetResult.tweet.views = views;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttweets.push(tweetResult.tweet);\n\t\t\t\t\t}\n\t\t\t\t} else if (entry.content?.cursorType === \"Bottom\") {\n\t\t\t\t\tbottomCursor = entry.content.value;\n\t\t\t\t} else if (entry.content?.cursorType === \"Top\") {\n\t\t\t\t\ttopCursor = entry.content.value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { tweets, next: bottomCursor, previous: topCursor };\n}\n\nexport function parseSearchTimelineUsers(\n\ttimeline: SearchTimeline,\n): QueryProfilesResponse {\n\tlet bottomCursor: string | undefined;\n\tlet topCursor: string | undefined;\n\tconst profiles: Profile[] = [];\n\tconst instructions =\n\t\ttimeline.data?.search_by_raw_query?.search_timeline?.timeline\n\t\t\t?.instructions ?? [];\n\n\tfor (const instruction of instructions) {\n\t\tif (\n\t\t\tinstruction.type === \"TimelineAddEntries\" ||\n\t\t\tinstruction.type === \"TimelineReplaceEntry\"\n\t\t) {\n\t\t\tif (instruction.entry?.content?.cursorType === \"Bottom\") {\n\t\t\t\tbottomCursor = instruction.entry.content.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (instruction.entry?.content?.cursorType === \"Top\") {\n\t\t\t\ttopCursor = instruction.entry.content.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst entries = instruction.entries ?? [];\n\t\t\tfor (const entry of entries) {\n\t\t\t\tconst itemContent = entry.content?.itemContent;\n\t\t\t\tif (itemContent?.userDisplayType === \"User\") {\n\t\t\t\t\tconst userResultRaw = itemContent.user_results?.result;\n\n\t\t\t\t\tif (userResultRaw?.legacy) {\n\t\t\t\t\t\tconst profile = parseProfile(\n\t\t\t\t\t\t\tuserResultRaw.legacy,\n\t\t\t\t\t\t\tuserResultRaw.is_blue_verified,\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!profile.userId) {\n\t\t\t\t\t\t\tprofile.userId = userResultRaw.rest_id;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprofiles.push(profile);\n\t\t\t\t\t}\n\t\t\t\t} else if (entry.content?.cursorType === \"Bottom\") {\n\t\t\t\t\tbottomCursor = entry.content.value;\n\t\t\t\t} else if (entry.content?.cursorType === \"Top\") {\n\t\t\t\t\ttopCursor = entry.content.value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { profiles, next: bottomCursor, previous: topCursor };\n}\n","import { addApiFeatures, requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport type { Profile } from \"./profile\";\nimport type { QueryProfilesResponse, QueryTweetsResponse } from \"./timeline-v1\";\nimport { getTweetTimeline, getUserTimeline } from \"./timeline-async\";\nimport type { Tweet } from \"./tweets\";\nimport {\n\ttype SearchTimeline,\n\tparseSearchTimelineTweets,\n\tparseSearchTimelineUsers,\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\tTop = 0,\n\tLatest = 1,\n\tPhotos = 2,\n\tVideos = 3,\n\tUsers = 4,\n}\n\nexport function searchTweets(\n\tquery: string,\n\tmaxTweets: number,\n\tsearchMode: SearchMode,\n\tauth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n\treturn getTweetTimeline(query, maxTweets, (q, mt, c) => {\n\t\treturn fetchSearchTweets(q, mt, searchMode, auth, c);\n\t});\n}\n\nexport function searchProfiles(\n\tquery: string,\n\tmaxProfiles: number,\n\tauth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n\treturn getUserTimeline(query, maxProfiles, (q, mt, c) => {\n\t\treturn fetchSearchProfiles(q, mt, auth, c);\n\t});\n}\n\nexport async function fetchSearchTweets(\n\tquery: string,\n\tmaxTweets: number,\n\tsearchMode: SearchMode,\n\tauth: TwitterAuth,\n\tcursor?: string,\n): Promise<QueryTweetsResponse> {\n\tconst timeline = await getSearchTimeline(\n\t\tquery,\n\t\tmaxTweets,\n\t\tsearchMode,\n\t\tauth,\n\t\tcursor,\n\t);\n\n\treturn parseSearchTimelineTweets(timeline);\n}\n\nexport async function fetchSearchProfiles(\n\tquery: string,\n\tmaxProfiles: number,\n\tauth: TwitterAuth,\n\tcursor?: string,\n): Promise<QueryProfilesResponse> {\n\tconst timeline = await getSearchTimeline(\n\t\tquery,\n\t\tmaxProfiles,\n\t\tSearchMode.Users,\n\t\tauth,\n\t\tcursor,\n\t);\n\n\treturn parseSearchTimelineUsers(timeline);\n}\n\nasync function getSearchTimeline(\n\tquery: string,\n\tmaxItems: number,\n\tsearchMode: SearchMode,\n\tauth: TwitterAuth,\n\tcursor?: string,\n): Promise<SearchTimeline> {\n\tif (!auth.isLoggedIn()) {\n\t\tthrow new Error(\"Client is not logged-in for search.\");\n\t}\n\n\tif (maxItems > 50) {\n\t\tmaxItems = 50;\n\t}\n\n\tconst variables: Record<string, any> = {\n\t\trawQuery: query,\n\t\tcount: maxItems,\n\t\tquerySource: \"typed_query\",\n\t\tproduct: \"Top\",\n\t};\n\n\tconst features = addApiFeatures({\n\t\tlongform_notetweets_inline_media_enabled: true,\n\t\tresponsive_web_enhance_cards_enabled: false,\n\t\tresponsive_web_media_download_video_enabled: false,\n\t\tresponsive_web_twitter_article_tweet_consumption_enabled: false,\n\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,\n\t\tinteractive_text_enabled: false,\n\t\tresponsive_web_text_conversations_enabled: false,\n\t\tvibe_api_enabled: false,\n\t});\n\n\tconst fieldToggles: Record<string, any> = {\n\t\twithArticleRichContentState: false,\n\t};\n\n\tif (cursor != null && cursor !== \"\") {\n\t\tvariables.cursor = cursor;\n\t}\n\n\tswitch (searchMode) {\n\t\tcase SearchMode.Latest:\n\t\t\tvariables.product = \"Latest\";\n\t\t\tbreak;\n\t\tcase SearchMode.Photos:\n\t\t\tvariables.product = \"Photos\";\n\t\t\tbreak;\n\t\tcase SearchMode.Videos:\n\t\t\tvariables.product = \"Videos\";\n\t\t\tbreak;\n\t\tcase SearchMode.Users:\n\t\t\tvariables.product = \"People\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tbreak;\n\t}\n\n\tconst params = new URLSearchParams();\n\tparams.set(\"features\", stringify(features) ?? \"\");\n\tparams.set(\"fieldToggles\", stringify(fieldToggles) ?? \"\");\n\tparams.set(\"variables\", stringify(variables) ?? \"\");\n\n\tconst res = await requestApi<SearchTimeline>(\n\t\t`https://api.twitter.com/graphql/gkjsKepM6gl_HmFWoWKfgg/SearchTimeline?${params.toString()}`,\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\treturn res.value;\n}\n\n/**\n * Fetches one page of tweets that quote a given tweet ID.\n * This function does not handle pagination.\n * All comments must remain in English.\n *\n * @param quotedTweetId The tweet ID you want quotes of.\n * @param maxTweets Maximum number of tweets to return in one page.\n * @param auth The TwitterAuth object.\n * @param cursor Optional pagination cursor for fetching further pages.\n * @returns A promise that resolves to a QueryTweetsResponse containing tweets and the next cursor.\n */\nexport async function fetchQuotedTweetsPage(\n\tquotedTweetId: string,\n\tmaxTweets: number,\n\tauth: TwitterAuth,\n\tcursor?: string,\n): Promise<QueryTweetsResponse> {\n\tif (maxTweets > 50) {\n\t\tmaxTweets = 50;\n\t}\n\n\t// Build the rawQuery and variables\n\tconst variables: Record<string, any> = {\n\t\trawQuery: `quoted_tweet_id:${quotedTweetId}`,\n\t\tcount: maxTweets,\n\t\tquerySource: \"tdqt\",\n\t\tproduct: \"Top\",\n\t};\n\n\tif (cursor && cursor !== \"\") {\n\t\tvariables.cursor = cursor;\n\t}\n\n\tconst features = addApiFeatures({\n\t\tprofile_label_improvements_pcf_label_in_post_enabled: true,\n\t\trweb_tipjar_consumption_enabled: true,\n\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\tverified_phone_label_enabled: false,\n\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\tpremium_content_api_read_enabled: false,\n\t\tcommunities_web_enable_tweet_community_results_fetch: true,\n\t\tc9s_tweet_anatomy_moderator_badge_enabled: true,\n\t\tresponsive_web_grok_analyze_button_fetch_trends_enabled: false,\n\t\tresponsive_web_grok_analyze_post_followups_enabled: true,\n\t\tresponsive_web_jetfuel_frame: false,\n\t\tresponsive_web_grok_share_attachment_enabled: true,\n\t\tarticles_preview_enabled: true,\n\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\tview_counts_everywhere_api_enabled: true,\n\t\tlongform_notetweets_consumption_enabled: true,\n\t\tresponsive_web_twitter_article_tweet_consumption_enabled: true,\n\t\ttweet_awards_web_tipping_enabled: false,\n\t\tcreator_subscriptions_quote_tweet_preview_enabled: false,\n\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\tstandardized_nudges_misinfo: true,\n\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,\n\t\trweb_video_timestamps_enabled: true,\n\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\tlongform_notetweets_inline_media_enabled: true,\n\t\tresponsive_web_grok_image_annotation_enabled: false,\n\t\tresponsive_web_enhance_cards_enabled: false,\n\t});\n\n\tconst fieldToggles: Record<string, any> = {\n\t\twithArticleRichContentState: false,\n\t};\n\n\tconst params = new URLSearchParams();\n\tparams.set(\"features\", stringify(features) ?? \"\");\n\tparams.set(\"fieldToggles\", stringify(fieldToggles) ?? \"\");\n\tparams.set(\"variables\", stringify(variables) ?? \"\");\n\n\tconst url = `https://x.com/i/api/graphql/1BP5aKg8NvTNvRCyyCyq8g/SearchTimeline?${params.toString()}`;\n\n\t// Perform the request\n\tconst res = await requestApi(url, auth);\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\t// Force cast for TypeScript\n\tconst timeline = res.value as any;\n\t// Use parseSearchTimelineTweets to convert timeline data\n\treturn parseSearchTimelineTweets(timeline);\n}\n\n/**\n * Creates an async generator, yielding pages of quotes for a given tweet ID.\n * It prevents infinite loop by checking if the next cursor hasn't changed.\n */\nexport async function* searchQuotedTweets(\n\tquotedTweetId: string,\n\tmaxTweets: number,\n\tauth: TwitterAuth,\n): AsyncGenerator<QueryTweetsResponse> {\n\tlet cursor: string | undefined;\n\n\twhile (true) {\n\t\tconst response = await fetchQuotedTweetsPage(\n\t\t\tquotedTweetId,\n\t\t\tmaxTweets,\n\t\t\tauth,\n\t\t\tcursor,\n\t\t);\n\t\tyield response;\n\n\t\t// Prevent infinite loop if the API keeps returning the same cursor\n\t\tif (!response.next || response.next === cursor) {\n\t\t\tbreak;\n\t\t}\n\n\t\t// Update cursor for the next iteration\n\t\tcursor = response.next;\n\t}\n}\n","import { addApiFeatures, requestApi, bearerToken } from \"./api\";\nimport { Headers } from \"headers-polyfill\";\nimport type { TwitterAuth } from \"./auth\";\nimport { type Profile, getUserIdByScreenName } from \"./profile\";\nimport type { QueryProfilesResponse } from \"./timeline-v1\";\nimport { getUserTimeline } from \"./timeline-async\";\nimport {\n\ttype RelationshipTimeline,\n\tparseRelationshipTimeline,\n} from \"./timeline-relationship\";\nimport stringify from \"json-stable-stringify\";\n\nexport function getFollowing(\n\tuserId: string,\n\tmaxProfiles: number,\n\tauth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n\treturn getUserTimeline(userId, maxProfiles, (q, mt, c) => {\n\t\treturn fetchProfileFollowing(q, mt, auth, c);\n\t});\n}\n\nexport function getFollowers(\n\tuserId: string,\n\tmaxProfiles: number,\n\tauth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n\treturn getUserTimeline(userId, maxProfiles, (q, mt, c) => {\n\t\treturn fetchProfileFollowers(q, mt, auth, c);\n\t});\n}\n\nexport async function fetchProfileFollowing(\n\tuserId: string,\n\tmaxProfiles: number,\n\tauth: TwitterAuth,\n\tcursor?: string,\n): Promise<QueryProfilesResponse> {\n\tconst timeline = await getFollowingTimeline(\n\t\tuserId,\n\t\tmaxProfiles,\n\t\tauth,\n\t\tcursor,\n\t);\n\n\treturn parseRelationshipTimeline(timeline);\n}\n\nexport async function fetchProfileFollowers(\n\tuserId: string,\n\tmaxProfiles: number,\n\tauth: TwitterAuth,\n\tcursor?: string,\n): Promise<QueryProfilesResponse> {\n\tconst timeline = await getFollowersTimeline(\n\t\tuserId,\n\t\tmaxProfiles,\n\t\tauth,\n\t\tcursor,\n\t);\n\n\treturn parseRelationshipTimeline(timeline);\n}\n\nasync function getFollowingTimeline(\n\tuserId: string,\n\tmaxItems: number,\n\tauth: TwitterAuth,\n\tcursor?: string,\n): Promise<RelationshipTimeline> {\n\tif (!auth.isLoggedIn()) {\n\t\tthrow new Error(\"Client is not logged-in for profile following.\");\n\t}\n\n\tif (maxItems > 50) {\n\t\tmaxItems = 50;\n\t}\n\n\tconst variables: Record<string, any> = {\n\t\tuserId,\n\t\tcount: maxItems,\n\t\tincludePromotedContent: false,\n\t};\n\n\tconst features = addApiFeatures({\n\t\tresponsive_web_twitter_article_tweet_consumption_enabled: false,\n\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,\n\t\tlongform_notetweets_inline_media_enabled: true,\n\t\tresponsive_web_media_download_video_enabled: false,\n\t});\n\n\tif (cursor != null && cursor !== \"\") {\n\t\tvariables.cursor = cursor;\n\t}\n\n\tconst params = new URLSearchParams();\n\tparams.set(\"features\", stringify(features) ?? \"\");\n\tparams.set(\"variables\", stringify(variables) ?? \"\");\n\n\tconst res = await requestApi<RelationshipTimeline>(\n\t\t`https://twitter.com/i/api/graphql/iSicc7LrzWGBgDPL0tM_TQ/Following?${params.toString()}`,\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\tthrow res.err;\n\t}\n\n\treturn res.value;\n}\n\nasync function getFollowersTimeline(\n\tuserId: string,\n\tmaxItems: number,\n\tauth: TwitterAuth,\n\tcursor?: string,\n): Promise<RelationshipTimeline> {\n\tif (!auth.isLoggedIn()) {\n\t\tthrow new Error(\"Client is not logged-in for profile followers.\");\n\t}\n\n\tif (maxItems > 50) {\n\t\tmaxItems = 50;\n\t}\n\n\tconst variables: Record<string, any> = {\n\t\tuserId,\n\t\tcount: maxItems,\n\t\tincludePromotedContent: false,\n\t};\n\n\tconst features = addApiFeatures({\n\t\tresponsive_web_twitter_article_tweet_consumption_enabled: false,\n\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,\n\t\tlongform_notetweets_inline_media_enabled: true,\n\t\tresponsive_web_media_download_video_enabled: false,\n\t});\n\n\tif (cursor != null && cursor !== \"\") {\n\t\tvariables.cursor = cursor;\n\t}\n\n\tconst params = new URLSearchParams();\n\tparams.set(\"features\", stringify(features) ?? \"\");\n\tparams.set(\"variables\", stringify(variables) ?? \"\");\n\n\tconst res = await requestApi<RelationshipTimeline>(\n\t\t`https://twitter.com/i/api/graphql/rRXFSG5vR6drKr5M37YOTw/Followers?${params.toString()}`,\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\tthrow res.err;\n\t}\n\n\treturn res.value;\n}\n\nexport async function followUser(\n\tusername: string,\n\tauth: TwitterAuth,\n): Promise<Response> {\n\t// Check if the user is logged in\n\tif (!(await auth.isLoggedIn())) {\n\t\tthrow new Error(\"Must be logged in to follow users\");\n\t}\n\t// Get user ID from username\n\tconst userIdResult = await getUserIdByScreenName(username, auth);\n\n\tif (!userIdResult.success) {\n\t\tthrow new Error(`Failed to get user ID: ${userIdResult.err.message}`);\n\t}\n\n\tconst userId = userIdResult.value;\n\n\t// Prepare the request body\n\tconst requestBody = {\n\t\tinclude_profile_interstitial_type: \"1\",\n\t\tskip_status: \"true\",\n\t\tuser_id: userId,\n\t};\n\n\t// Prepare the headers\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\tReferer: `https://twitter.com/${username}`,\n\t\t\"X-Twitter-Active-User\": \"yes\",\n\t\t\"X-Twitter-Auth-Type\": \"OAuth2Session\",\n\t\t\"X-Twitter-Client-Language\": \"en\",\n\t\tAuthorization: `Bearer ${bearerToken}`,\n\t});\n\n\t// Install auth headers\n\tawait auth.installTo(\n\t\theaders,\n\t\t\"https://api.twitter.com/1.1/friendships/create.json\",\n\t);\n\n\t// Make the follow request using auth.fetch\n\tconst res = await auth.fetch(\n\t\t\"https://api.twitter.com/1.1/friendships/create.json\",\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: new URLSearchParams(requestBody).toString(),\n\t\t\tcredentials: \"include\",\n\t\t},\n\t);\n\n\tif (!res.ok) {\n\t\tthrow new Error(`Failed to follow user: ${res.statusText}`);\n\t}\n\n\tconst data = await res.json();\n\n\treturn new Response(JSON.stringify(data), {\n\t\tstatus: 200,\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t},\n\t});\n}\n","import { type Profile, parseProfile } from \"./profile\";\nimport type { QueryProfilesResponse } from \"./timeline-v1\";\nimport type { TimelineUserResultRaw } from \"./timeline-v2\";\n\nexport interface RelationshipEntryItemContentRaw {\n\titemType?: string;\n\tuserDisplayType?: string;\n\tuser_results?: {\n\t\tresult?: TimelineUserResultRaw;\n\t};\n}\n\nexport interface RelationshipEntryRaw {\n\tentryId: string;\n\tsortIndex: string;\n\tcontent?: {\n\t\tcursorType?: string;\n\t\tentryType?: string;\n\t\t__typename?: string;\n\t\tvalue?: string;\n\t\titemContent?: RelationshipEntryItemContentRaw;\n\t};\n}\n\nexport interface RelationshipTimeline {\n\tdata?: {\n\t\tuser?: {\n\t\t\tresult?: {\n\t\t\t\ttimeline?: {\n\t\t\t\t\ttimeline?: {\n\t\t\t\t\t\tinstructions?: {\n\t\t\t\t\t\t\tentries?: RelationshipEntryRaw[];\n\t\t\t\t\t\t\tentry?: RelationshipEntryRaw;\n\t\t\t\t\t\t\ttype?: string;\n\t\t\t\t\t\t}[];\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n}\n\nexport function parseRelationshipTimeline(\n\ttimeline: RelationshipTimeline,\n): QueryProfilesResponse {\n\tlet bottomCursor: string | undefined;\n\tlet topCursor: string | undefined;\n\tconst profiles: Profile[] = [];\n\tconst instructions =\n\t\ttimeline.data?.user?.result?.timeline?.timeline?.instructions ?? [];\n\n\tfor (const instruction of instructions) {\n\t\tif (\n\t\t\tinstruction.type === \"TimelineAddEntries\" ||\n\t\t\tinstruction.type === \"TimelineReplaceEntry\"\n\t\t) {\n\t\t\tif (instruction.entry?.content?.cursorType === \"Bottom\") {\n\t\t\t\tbottomCursor = instruction.entry.content.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (instruction.entry?.content?.cursorType === \"Top\") {\n\t\t\t\ttopCursor = instruction.entry.content.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst entries = instruction.entries ?? [];\n\t\t\tfor (const entry of entries) {\n\t\t\t\tconst itemContent = entry.content?.itemContent;\n\t\t\t\tif (itemContent?.userDisplayType === \"User\") {\n\t\t\t\t\tconst userResultRaw = itemContent.user_results?.result;\n\n\t\t\t\t\tif (userResultRaw?.legacy) {\n\t\t\t\t\t\tconst profile = parseProfile(\n\t\t\t\t\t\t\tuserResultRaw.legacy,\n\t\t\t\t\t\t\tuserResultRaw.is_blue_verified,\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (!profile.userId) {\n\t\t\t\t\t\t\tprofile.userId = userResultRaw.rest_id;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tprofiles.push(profile);\n\t\t\t\t\t}\n\t\t\t\t} else if (entry.content?.cursorType === \"Bottom\") {\n\t\t\t\t\tbottomCursor = entry.content.value;\n\t\t\t\t} else if (entry.content?.cursorType === \"Top\") {\n\t\t\t\t\ttopCursor = entry.content.value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { profiles, next: bottomCursor, previous: topCursor };\n}\n","import { addApiParams, requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport type { TimelineV1 } from \"./timeline-v1\";\n\nexport async function getTrends(auth: TwitterAuth): Promise<string[]> {\n\tconst params = new URLSearchParams();\n\taddApiParams(params, false);\n\n\tparams.set(\"count\", \"20\");\n\tparams.set(\"candidate_source\", \"trends\");\n\tparams.set(\"include_page_configuration\", \"false\");\n\tparams.set(\"entity_tokens\", \"false\");\n\n\tconst res = await requestApi<TimelineV1>(\n\t\t`https://api.twitter.com/2/guide.json?${params.toString()}`,\n\t\tauth,\n\t);\n\tif (!res.success) {\n\t\tthrow res.err;\n\t}\n\n\tconst instructions = res.value.timeline?.instructions ?? [];\n\tif (instructions.length < 2) {\n\t\tthrow new Error(\"No trend entries found.\");\n\t}\n\n\t// Some of this is silly, but for now we're assuming we know nothing about the\n\t// data, and that anything can be missing. Go has non-nilable strings and empty\n\t// slices are nil, so it largely doesn't need to worry about this.\n\tconst entries = instructions[1].addEntries?.entries ?? [];\n\tif (entries.length < 2) {\n\t\tthrow new Error(\"No trend entries found.\");\n\t}\n\n\tconst items = entries[1].content?.timelineModule?.items ?? [];\n\tconst trends: string[] = [];\n\tfor (const item of items) {\n\t\tconst trend =\n\t\t\titem.item?.clientEventInfo?.details?.guideDetails?.transparentGuideDetails\n\t\t\t\t?.trendMetadata?.trendName;\n\t\tif (trend != null) {\n\t\t\ttrends.push(trend);\n\t\t}\n\t}\n\n\treturn 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\t// TODO: Migrate other endpoint URLs here\n\tUserTweets:\n\t\t\"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\tUserTweetsAndReplies:\n\t\t\"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\tUserLikedTweets:\n\t\t\"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\tTweetDetail:\n\t\t\"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\tTweetDetailArticle:\n\t\t\"https://twitter.com/i/api/graphql/GtcBtFhtQymrpxAs5MALVA/TweetDetail?variables=%7B%22focalTweetId%22%3A%221765884209527394325%22%2C%22with_rux_injections%22%3Atrue%2C%22rankingMode%22%3A%22Relevance%22%2C%22includePromotedContent%22%3Atrue%2C%22withCommunity%22%3Atrue%2C%22withQuickPromoteEligibilityTweetFields%22%3Atrue%2C%22withBirdwatchNotes%22%3Atrue%2C%22withVoice%22%3Atrue%7D&features=%7B%22profile_label_improvements_pcf_label_in_post_enabled%22%3Afalse%2C%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%22premium_content_api_read_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22responsive_web_grok_analyze_button_fetch_trends_enabled%22%3Atrue%2C%22responsive_web_grok_analyze_post_followups_enabled%22%3Afalse%2C%22responsive_web_grok_share_attachment_enabled%22%3Atrue%2C%22articles_preview_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%22withArticleRichContentState%22%3Atrue%2C%22withArticlePlainText%22%3Afalse%2C%22withGrokAnalyze%22%3Afalse%2C%22withDisallowedReplyControls%22%3Afalse%7D\",\n\tTweetResultByRestId:\n\t\t\"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\tListTweets:\n\t\t\"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\t/**\n\t * Request variables, used for providing arguments such as user IDs or result counts.\n\t */\n\tvariables: Record<string, unknown>;\n\n\t/**\n\t * Request features, used for encoding feature flags into the request. These may either be\n\t * boolean values or numerically-encoded booleans (1 or 0). It is possible this may change\n\t * to include other representations of booleans as Twitter's backend evolves.\n\t */\n\tfeatures: Record<string, unknown>;\n\n\t/**\n\t * Request field toggles, used for limiting how returned fields are represented. This is\n\t * rarely used.\n\t */\n\tfieldToggles: 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\tEndpointUrl extends `https://twitter.com/i/api/graphql/${EndpointVersion}/${EndpointName}?variables=${EncodedVariables}&features=${EncodedFeatures}&fieldToggles=${EncodedFieldToggles}`\n\t\t? EndpointFieldInfo\n\t\t: EndpointUrl extends `https://twitter.com/i/api/graphql/${EndpointVersion}/${EndpointName}?variables=${EncodedVariables}&features=${EncodedFeatures}`\n\t\t\t? SomePartial<EndpointFieldInfo, \"fieldToggles\">\n\t\t\t: EndpointUrl extends `https://twitter.com/i/api/graphql/${EndpointVersion}/${EndpointName}?variables=${EncodedVariables}`\n\t\t\t\t? SomePartial<EndpointFieldInfo, \"features\" | \"fieldToggles\">\n\t\t\t\t: Partial<EndpointFieldInfo>;\n\nexport type ApiRequestInfo<EndpointUrl> = EndpointFields<EndpointUrl> & {\n\t/**\n\t * The URL, without any GraphQL query parameters.\n\t */\n\turl: string;\n\n\t/**\n\t * Converts the request back into a URL to be sent to the Twitter API.\n\t */\n\ttoRequestUrl(): string;\n};\n\n/** Wrapper class for API request information. */\nclass ApiRequest<EndpointUrl> {\n\turl: string;\n\tvariables?: Record<string, unknown> | undefined;\n\tfeatures?: Record<string, unknown> | undefined;\n\tfieldToggles?: Record<string, unknown> | undefined;\n\n\tconstructor(info: Omit<ApiRequestInfo<EndpointUrl>, \"toRequestUrl\">) {\n\t\tthis.url = info.url;\n\t\tthis.variables = info.variables;\n\t\tthis.features = info.features;\n\t\tthis.fieldToggles = info.fieldToggles;\n\t}\n\n\ttoRequestUrl(): string {\n\t\tconst params = new URLSearchParams();\n\n\t\t// Only include query parameters with values\n\t\tif (this.variables) {\n\t\t\t// Stringify with the query keys in sorted order like the Go package\n\t\t\tparams.set(\"variables\", stringify(this.variables) ?? \"\");\n\t\t}\n\n\t\tif (this.features) {\n\t\t\tparams.set(\"features\", stringify(this.features) ?? \"\");\n\t\t}\n\n\t\tif (this.fieldToggles) {\n\t\t\tparams.set(\"fieldToggles\", stringify(this.fieldToggles) ?? \"\");\n\t\t}\n\n\t\treturn `${this.url}?${params.toString()}`;\n\t}\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\tEndpoints,\n\tEndpoint extends string & keyof Endpoints,\n>(example: Endpoint): ApiRequestInfo<Endpoints[Endpoint]> {\n\tconst { protocol, host, pathname, searchParams: query } = new URL(example);\n\n\tconst base = `${protocol}//${host}${pathname}`;\n\tconst variables = query.get(\"variables\");\n\tconst features = query.get(\"features\");\n\tconst fieldToggles = query.get(\"fieldToggles\");\n\n\treturn new ApiRequest<Endpoints[Endpoint]>({\n\t\turl: base,\n\t\tvariables: variables ? JSON.parse(variables) : undefined,\n\t\tfeatures: features ? JSON.parse(features) : undefined,\n\t\tfieldToggles: fieldToggles ? JSON.parse(fieldToggles) : undefined,\n\t} as Omit<\n\t\tApiRequestInfo<Endpoints[Endpoint]>,\n\t\t\"toRequestUrl\"\n\t>) as ApiRequestInfo<Endpoints[Endpoint]>;\n}\n\ntype ApiRequestFactory<Endpoints> = {\n\t[Endpoint in keyof Endpoints as `create${string &\n\t\tEndpoint}Request`]: () => ApiRequestInfo<Endpoints[Endpoint]>;\n};\n\nfunction createApiRequestFactory<Endpoints extends Record<string, string>>(\n\tendpoints: Endpoints,\n): ApiRequestFactory<Endpoints> {\n\ttype UntypedApiRequestFactory = ApiRequestFactory<Record<string, string>>;\n\n\treturn Object.entries(endpoints)\n\t\t.map<UntypedApiRequestFactory>(([endpointName, endpointExample]) => {\n\t\t\t// Create a partial factory for only one endpoint\n\t\t\treturn {\n\t\t\t\t[`create${endpointName}Request`]: () => {\n\t\t\t\t\t// Create a new instance on each invocation so that we can safely\n\t\t\t\t\t// mutate requests before sending them off\n\t\t\t\t\treturn parseEndpointExample<Endpoints, any>(endpointExample);\n\t\t\t\t},\n\t\t\t};\n\t\t})\n\t\t.reduce((agg, next) => {\n\t\t\t// Merge all of our factories into one that includes every endpoint\n\t\t\treturn Object.assign(agg, next);\n\t\t}) as ApiRequestFactory<Endpoints>;\n}\n\nexport const apiRequestFactory = createApiRequestFactory(endpoints);\n","import type { QueryTweetsResponse } from \"./timeline-v1\";\nimport { parseAndPush, type TimelineEntryRaw } from \"./timeline-v2\";\nimport type { Tweet } from \"./tweets\";\n\nexport interface ListTimeline {\n\tdata?: {\n\t\tlist?: {\n\t\t\ttweets_timeline?: {\n\t\t\t\ttimeline?: {\n\t\t\t\t\tinstructions?: {\n\t\t\t\t\t\tentries?: TimelineEntryRaw[];\n\t\t\t\t\t\tentry?: TimelineEntryRaw;\n\t\t\t\t\t\ttype?: string;\n\t\t\t\t\t}[];\n\t\t\t\t};\n\t\t\t};\n\t\t};\n\t};\n}\n\nexport function parseListTimelineTweets(\n\ttimeline: ListTimeline,\n): QueryTweetsResponse {\n\tlet bottomCursor: string | undefined;\n\tlet topCursor: string | undefined;\n\tconst tweets: Tweet[] = [];\n\tconst instructions =\n\t\ttimeline.data?.list?.tweets_timeline?.timeline?.instructions ?? [];\n\tfor (const instruction of instructions) {\n\t\tconst entries = instruction.entries ?? [];\n\n\t\tfor (const entry of entries) {\n\t\t\tconst entryContent = entry.content;\n\t\t\tif (!entryContent) continue;\n\n\t\t\tif (entryContent.cursorType === \"Bottom\") {\n\t\t\t\tbottomCursor = entryContent.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entryContent.cursorType === \"Top\") {\n\t\t\t\ttopCursor = entryContent.value;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst idStr = entry.entryId;\n\t\t\tif (\n\t\t\t\t!idStr.startsWith(\"tweet\") &&\n\t\t\t\t!idStr.startsWith(\"list-conversation\")\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (entryContent.itemContent) {\n\t\t\t\tparseAndPush(tweets, entryContent.itemContent, idStr);\n\t\t\t} else if (entryContent.items) {\n\t\t\t\tfor (const contentItem of entryContent.items) {\n\t\t\t\t\tif (contentItem.item?.itemContent && contentItem.entryId) {\n\t\t\t\t\t\tparseAndPush(\n\t\t\t\t\t\t\ttweets,\n\t\t\t\t\t\t\tcontentItem.item.itemContent,\n\t\t\t\t\t\t\tcontentItem.entryId.split(\"tweet-\")[1],\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { tweets, next: bottomCursor, previous: topCursor };\n}\n","import { addApiFeatures, requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport { getUserIdByScreenName } from \"./profile\";\nimport type { QueryTweetsResponse } from \"./timeline-v1\";\nimport {\n\tparseTimelineTweetsV2,\n\ttype TimelineV2,\n\ttype TimelineEntryItemContentRaw,\n\tparseTimelineEntryItemContentRaw,\n\ttype ThreadedConversation,\n\tparseThreadedConversation,\n\tparseArticle,\n\ttype TimelineArticle,\n} from \"./timeline-v2\";\nimport { getTweetTimeline } from \"./timeline-async\";\nimport { apiRequestFactory } from \"./api-data\";\nimport { type ListTimeline, parseListTimelineTweets } from \"./timeline-list\";\nimport { updateCookieJar } from \"./requests\";\nimport type {\n\tApiV2Includes,\n\tMediaObjectV2,\n\tPlaceV2,\n\tPollV2,\n\tTTweetv2Expansion,\n\tTTweetv2MediaField,\n\tTTweetv2PlaceField,\n\tTTweetv2PollField,\n\tTTweetv2TweetField,\n\tTTweetv2UserField,\n\tTweetV2,\n\tUserV2,\n} from \"twitter-api-v2\";\n\nexport const defaultOptions = {\n\texpansions: [\n\t\t\"attachments.poll_ids\",\n\t\t\"attachments.media_keys\",\n\t\t\"author_id\",\n\t\t\"referenced_tweets.id\",\n\t\t\"in_reply_to_user_id\",\n\t\t\"edit_history_tweet_ids\",\n\t\t\"geo.place_id\",\n\t\t\"entities.mentions.username\",\n\t\t\"referenced_tweets.id.author_id\",\n\t] as TTweetv2Expansion[],\n\ttweetFields: [\n\t\t\"attachments\",\n\t\t\"author_id\",\n\t\t\"context_annotations\",\n\t\t\"conversation_id\",\n\t\t\"created_at\",\n\t\t\"entities\",\n\t\t\"geo\",\n\t\t\"id\",\n\t\t\"in_reply_to_user_id\",\n\t\t\"lang\",\n\t\t\"public_metrics\",\n\t\t\"edit_controls\",\n\t\t\"possibly_sensitive\",\n\t\t\"referenced_tweets\",\n\t\t\"reply_settings\",\n\t\t\"source\",\n\t\t\"text\",\n\t\t\"withheld\",\n\t\t\"note_tweet\",\n\t] as TTweetv2TweetField[],\n\tpollFields: [\n\t\t\"duration_minutes\",\n\t\t\"end_datetime\",\n\t\t\"id\",\n\t\t\"options\",\n\t\t\"voting_status\",\n\t] as TTweetv2PollField[],\n\tmediaFields: [\n\t\t\"duration_ms\",\n\t\t\"height\",\n\t\t\"media_key\",\n\t\t\"preview_image_url\",\n\t\t\"type\",\n\t\t\"url\",\n\t\t\"width\",\n\t\t\"public_metrics\",\n\t\t\"alt_text\",\n\t\t\"variants\",\n\t] as TTweetv2MediaField[],\n\tuserFields: [\n\t\t\"created_at\",\n\t\t\"description\",\n\t\t\"entities\",\n\t\t\"id\",\n\t\t\"location\",\n\t\t\"name\",\n\t\t\"profile_image_url\",\n\t\t\"protected\",\n\t\t\"public_metrics\",\n\t\t\"url\",\n\t\t\"username\",\n\t\t\"verified\",\n\t\t\"withheld\",\n\t] as TTweetv2UserField[],\n\tplaceFields: [\n\t\t\"contained_within\",\n\t\t\"country\",\n\t\t\"country_code\",\n\t\t\"full_name\",\n\t\t\"geo\",\n\t\t\"id\",\n\t\t\"name\",\n\t\t\"place_type\",\n\t] as TTweetv2PlaceField[],\n};\nexport interface Mention {\n\tid: string;\n\tusername?: string;\n\tname?: string;\n}\n\nexport interface Photo {\n\tid: string;\n\turl: string;\n\talt_text: string | undefined;\n}\n\nexport interface Video {\n\tid: string;\n\tpreview: string;\n\turl?: string;\n}\n\nexport interface PlaceRaw {\n\tid?: string;\n\tplace_type?: string;\n\tname?: string;\n\tfull_name?: string;\n\tcountry_code?: string;\n\tcountry?: string;\n\tbounding_box?: {\n\t\ttype?: string;\n\t\tcoordinates?: number[][][];\n\t};\n}\n\nexport interface PollData {\n\tid?: string;\n\tend_datetime?: string;\n\tvoting_status?: string;\n\tduration_minutes: number;\n\toptions: PollOption[];\n}\n\nexport interface PollOption {\n\tposition?: number;\n\tlabel: string;\n\tvotes?: number;\n}\n\n/**\n * A parsed Tweet object.\n */\nexport interface Tweet {\n\tbookmarkCount?: number;\n\tconversationId?: string;\n\thashtags: string[];\n\thtml?: string;\n\tid?: string;\n\tinReplyToStatus?: Tweet;\n\tinReplyToStatusId?: string;\n\tisQuoted?: boolean;\n\tisPin?: boolean;\n\tisReply?: boolean;\n\tisRetweet?: boolean;\n\tisSelfThread?: boolean;\n\tlanguage?: string;\n\tlikes?: number;\n\tname?: string;\n\tmentions: Mention[];\n\tpermanentUrl?: string;\n\tphotos: Photo[];\n\tplace?: PlaceRaw;\n\tquotedStatus?: Tweet;\n\tquotedStatusId?: string;\n\tquotes?: number;\n\treplies?: number;\n\tretweets?: number;\n\tretweetedStatus?: Tweet;\n\tretweetedStatusId?: string;\n\ttext?: string;\n\tthread: Tweet[];\n\ttimeParsed?: Date;\n\ttimestamp?: number;\n\turls: string[];\n\tuserId?: string;\n\tusername?: string;\n\tvideos: Video[];\n\tviews?: number;\n\tsensitiveContent?: boolean;\n\tpoll?: PollV2 | null;\n}\n\nexport interface Retweeter {\n\trest_id: string;\n\tscreen_name: string;\n\tname: string;\n\tdescription?: string;\n}\n\nexport type TweetQuery =\n\t| Partial<Tweet>\n\t| ((tweet: Tweet) => boolean | Promise<boolean>);\n\nexport const features = addApiFeatures({\n\tinteractive_text_enabled: true,\n\tlongform_notetweets_inline_media_enabled: false,\n\tresponsive_web_text_conversations_enabled: false,\n\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: false,\n\tvibe_api_enabled: false,\n});\n\nexport async function fetchTweets(\n\tuserId: string,\n\tmaxTweets: number,\n\tcursor: string | undefined,\n\tauth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n\tif (maxTweets > 200) {\n\t\tmaxTweets = 200;\n\t}\n\n\tconst userTweetsRequest = apiRequestFactory.createUserTweetsRequest();\n\tuserTweetsRequest.variables.userId = userId;\n\tuserTweetsRequest.variables.count = maxTweets;\n\tuserTweetsRequest.variables.includePromotedContent = false; // true on the website\n\n\tif (cursor != null && cursor !== \"\") {\n\t\tuserTweetsRequest.variables.cursor = cursor;\n\t}\n\n\tconst res = await requestApi<TimelineV2>(\n\t\tuserTweetsRequest.toRequestUrl(),\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\treturn parseTimelineTweetsV2(res.value);\n}\n\nexport async function fetchTweetsAndReplies(\n\tuserId: string,\n\tmaxTweets: number,\n\tcursor: string | undefined,\n\tauth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n\tif (maxTweets > 40) {\n\t\tmaxTweets = 40;\n\t}\n\n\tconst userTweetsRequest =\n\t\tapiRequestFactory.createUserTweetsAndRepliesRequest();\n\tuserTweetsRequest.variables.userId = userId;\n\tuserTweetsRequest.variables.count = maxTweets;\n\tuserTweetsRequest.variables.includePromotedContent = false; // true on the website\n\n\tif (cursor != null && cursor !== \"\") {\n\t\tuserTweetsRequest.variables.cursor = cursor;\n\t}\n\n\tconst res = await requestApi<TimelineV2>(\n\t\tuserTweetsRequest.toRequestUrl(),\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\treturn parseTimelineTweetsV2(res.value);\n}\n\nexport async function createCreateTweetRequestV2(\n\ttext: string,\n\tauth: TwitterAuth,\n\ttweetId?: string,\n\toptions?: {\n\t\tpoll?: PollData;\n\t},\n) {\n\tconst v2client = auth.getV2Client();\n\tif (v2client == null) {\n\t\tthrow new Error(\"V2 client is not initialized\");\n\t}\n\tconst { poll } = options || {};\n\tlet tweetConfig;\n\tif (poll) {\n\t\ttweetConfig = {\n\t\t\ttext,\n\t\t\tpoll: {\n\t\t\t\toptions: poll?.options.map((option) => option.label) ?? [],\n\t\t\t\tduration_minutes: poll?.duration_minutes ?? 60,\n\t\t\t},\n\t\t};\n\t} else if (tweetId) {\n\t\ttweetConfig = {\n\t\t\ttext,\n\t\t\treply: {\n\t\t\t\tin_reply_to_tweet_id: tweetId,\n\t\t\t},\n\t\t};\n\t} else {\n\t\ttweetConfig = {\n\t\t\ttext,\n\t\t};\n\t}\n\tconst tweetResponse = await v2client.v2.tweet(tweetConfig);\n\tlet optionsConfig = {};\n\tif (options?.poll) {\n\t\toptionsConfig = {\n\t\t\texpansions: [\"attachments.poll_ids\"],\n\t\t\tpollFields: [\n\t\t\t\t\"options\",\n\t\t\t\t\"duration_minutes\",\n\t\t\t\t\"end_datetime\",\n\t\t\t\t\"voting_status\",\n\t\t\t],\n\t\t};\n\t}\n\treturn await getTweetV2(tweetResponse.data.id, auth, optionsConfig);\n}\n\nexport function parseTweetV2ToV1(\n\ttweetV2: TweetV2,\n\tincludes?: ApiV2Includes,\n\tdefaultTweetData?: Tweet | null,\n): Tweet {\n\tlet parsedTweet: Tweet;\n\tif (defaultTweetData != null) {\n\t\tparsedTweet = defaultTweetData;\n\t}\n\tparsedTweet = {\n\t\tid: tweetV2.id,\n\t\ttext: tweetV2.text ?? defaultTweetData?.text ?? \"\",\n\t\thashtags:\n\t\t\ttweetV2.entities?.hashtags?.map((tag) => tag.tag) ??\n\t\t\tdefaultTweetData?.hashtags ??\n\t\t\t[],\n\t\tmentions:\n\t\t\ttweetV2.entities?.mentions?.map((mention) => ({\n\t\t\t\tid: mention.id,\n\t\t\t\tusername: mention.username,\n\t\t\t})) ??\n\t\t\tdefaultTweetData?.mentions ??\n\t\t\t[],\n\t\turls:\n\t\t\ttweetV2.entities?.urls?.map((url) => url.url) ??\n\t\t\tdefaultTweetData?.urls ??\n\t\t\t[],\n\t\tlikes: tweetV2.public_metrics?.like_count ?? defaultTweetData?.likes ?? 0,\n\t\tretweets:\n\t\t\ttweetV2.public_metrics?.retweet_count ?? defaultTweetData?.retweets ?? 0,\n\t\treplies:\n\t\t\ttweetV2.public_metrics?.reply_count ?? defaultTweetData?.replies ?? 0,\n\t\tviews:\n\t\t\ttweetV2.public_metrics?.impression_count ?? defaultTweetData?.views ?? 0,\n\t\tuserId: tweetV2.author_id ?? defaultTweetData?.userId,\n\t\tconversationId: tweetV2.conversation_id ?? defaultTweetData?.conversationId,\n\t\tphotos: defaultTweetData?.photos ?? [],\n\t\tvideos: defaultTweetData?.videos ?? [],\n\t\tpoll: defaultTweetData?.poll ?? null,\n\t\tusername: defaultTweetData?.username ?? \"\",\n\t\tname: defaultTweetData?.name ?? \"\",\n\t\tplace: defaultTweetData?.place,\n\t\tthread: defaultTweetData?.thread ?? [],\n\t};\n\n\t// Process Polls\n\tif (includes?.polls?.length) {\n\t\tconst poll = includes.polls[0];\n\t\tparsedTweet.poll = {\n\t\t\tid: poll.id,\n\t\t\tend_datetime: poll.end_datetime\n\t\t\t\t? poll.end_datetime\n\t\t\t\t: defaultTweetData?.poll?.end_datetime\n\t\t\t\t\t? defaultTweetData?.poll?.end_datetime\n\t\t\t\t\t: undefined,\n\t\t\toptions: poll.options.map((option) => ({\n\t\t\t\tposition: option.position,\n\t\t\t\tlabel: option.label,\n\t\t\t\tvotes: option.votes,\n\t\t\t})),\n\t\t\tvoting_status:\n\t\t\t\tpoll.voting_status ?? defaultTweetData?.poll?.voting_status,\n\t\t};\n\t}\n\n\t// Process Media (photos and videos)\n\tif (includes?.media?.length) {\n\t\tincludes.media.forEach((media: MediaObjectV2) => {\n\t\t\tif (media.type === \"photo\") {\n\t\t\t\tparsedTweet.photos.push({\n\t\t\t\t\tid: media.media_key,\n\t\t\t\t\turl: media.url ?? \"\",\n\t\t\t\t\talt_text: media.alt_text ?? \"\",\n\t\t\t\t});\n\t\t\t} else if (media.type === \"video\" || media.type === \"animated_gif\") {\n\t\t\t\tparsedTweet.videos.push({\n\t\t\t\t\tid: media.media_key,\n\t\t\t\t\tpreview: media.preview_image_url ?? \"\",\n\t\t\t\t\turl:\n\t\t\t\t\t\tmedia.variants?.find(\n\t\t\t\t\t\t\t(variant) => variant.content_type === \"video/mp4\",\n\t\t\t\t\t\t)?.url ?? \"\",\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\t// Process User (for author info)\n\tif (includes?.users?.length) {\n\t\tconst user = includes.users.find(\n\t\t\t(user: UserV2) => user.id === tweetV2.author_id,\n\t\t);\n\t\tif (user) {\n\t\t\tparsedTweet.username = user.username ?? defaultTweetData?.username ?? \"\";\n\t\t\tparsedTweet.name = user.name ?? defaultTweetData?.name ?? \"\";\n\t\t}\n\t}\n\n\t// Process Place (if any)\n\tif (tweetV2?.geo?.place_id && includes?.places?.length) {\n\t\tconst place = includes.places.find(\n\t\t\t(place: PlaceV2) => place.id === tweetV2?.geo?.place_id,\n\t\t);\n\t\tif (place) {\n\t\t\tparsedTweet.place = {\n\t\t\t\tid: place.id,\n\t\t\t\tfull_name: place.full_name ?? defaultTweetData?.place?.full_name ?? \"\",\n\t\t\t\tcountry: place.country ?? defaultTweetData?.place?.country ?? \"\",\n\t\t\t\tcountry_code:\n\t\t\t\t\tplace.country_code ?? defaultTweetData?.place?.country_code ?? \"\",\n\t\t\t\tname: place.name ?? defaultTweetData?.place?.name ?? \"\",\n\t\t\t\tplace_type: place.place_type ?? defaultTweetData?.place?.place_type,\n\t\t\t};\n\t\t}\n\t}\n\n\t// TODO: Process Thread (referenced tweets) and remove reference to v1\n\treturn parsedTweet;\n}\n\nexport async function createCreateTweetRequest(\n\ttext: string,\n\tauth: TwitterAuth,\n\ttweetId?: string,\n\tmediaData?: { data: Buffer; mediaType: string }[],\n\thideLinkPreview = false,\n) {\n\tconst onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n\tconst cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\t//@ ts-expect-error - This is a private API.\n\tconst headers = new Headers({\n\t\tauthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\tcookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n\t\t\"content-type\": \"application/json\",\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Linux; Android 11; Nokia G20) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.88 Mobile Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-twitter-client-language\": \"en\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\tconst variables: Record<string, any> = {\n\t\ttweet_text: text,\n\t\tdark_request: false,\n\t\tmedia: {\n\t\t\tmedia_entities: [],\n\t\t\tpossibly_sensitive: false,\n\t\t},\n\t\tsemantic_annotation_ids: [],\n\t};\n\n\tif (hideLinkPreview) {\n\t\tvariables.card_uri = \"tombstone://card\";\n\t}\n\n\tif (mediaData && mediaData.length > 0) {\n\t\tconst mediaIds = await Promise.all(\n\t\t\tmediaData.map(({ data, mediaType }) =>\n\t\t\t\tuploadMedia(data, auth, mediaType),\n\t\t\t),\n\t\t);\n\n\t\tvariables.media.media_entities = mediaIds.map((id) => ({\n\t\t\tmedia_id: id,\n\t\t\ttagged_users: [],\n\t\t}));\n\t}\n\n\tif (tweetId) {\n\t\tvariables.reply = { in_reply_to_tweet_id: tweetId };\n\t}\n\n\tconst response = await fetch(\n\t\t\"https://twitter.com/i/api/graphql/a1p9RWpkYKBjWv_I3WzS-A/CreateTweet\",\n\t\t{\n\t\t\theaders,\n\t\t\tbody: JSON.stringify({\n\t\t\t\tvariables,\n\t\t\t\tfeatures: {\n\t\t\t\t\tinteractive_text_enabled: true,\n\t\t\t\t\tlongform_notetweets_inline_media_enabled: false,\n\t\t\t\t\tresponsive_web_text_conversations_enabled: false,\n\t\t\t\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: false,\n\t\t\t\t\tvibe_api_enabled: false,\n\t\t\t\t\trweb_lists_timeline_redesign_enabled: true,\n\t\t\t\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\t\t\t\tverified_phone_label_enabled: false,\n\t\t\t\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\t\t\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\t\t\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\t\t\t\ttweetypie_unmention_optimization_enabled: true,\n\t\t\t\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\t\t\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\t\t\t\tview_counts_everywhere_api_enabled: true,\n\t\t\t\t\tlongform_notetweets_consumption_enabled: true,\n\t\t\t\t\ttweet_awards_web_tipping_enabled: false,\n\t\t\t\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\t\t\t\tstandardized_nudges_misinfo: true,\n\t\t\t\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\t\t\t\tresponsive_web_enhance_cards_enabled: false,\n\t\t\t\t\tsubscriptions_verification_info_enabled: true,\n\t\t\t\t\tsubscriptions_verification_info_reason_enabled: true,\n\t\t\t\t\tsubscriptions_verification_info_verified_since_enabled: true,\n\t\t\t\t\tsuper_follow_badge_privacy_enabled: false,\n\t\t\t\t\tsuper_follow_exclusive_tweet_notifications_enabled: false,\n\t\t\t\t\tsuper_follow_tweet_api_enabled: false,\n\t\t\t\t\tsuper_follow_user_api_enabled: false,\n\t\t\t\t\tandroid_graphql_skip_api_media_color_palette: false,\n\t\t\t\t\tcreator_subscriptions_subscription_count_enabled: false,\n\t\t\t\t\tblue_business_profile_image_shape_enabled: false,\n\t\t\t\t\tunified_cards_ad_metadata_container_dynamic_card_content_query_enabled: false,\n\t\t\t\t\trweb_video_timestamps_enabled: false,\n\t\t\t\t\tc9s_tweet_anatomy_moderator_badge_enabled: false,\n\t\t\t\t\tresponsive_web_twitter_article_tweet_consumption_enabled: false,\n\t\t\t\t},\n\t\t\t\tfieldToggles: {},\n\t\t\t}),\n\t\t\tmethod: \"POST\",\n\t\t},\n\t);\n\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t// check for errors\n\tif (!response.ok) {\n\t\tthrow new Error(await response.text());\n\t}\n\n\treturn response;\n}\n\nexport async function createCreateNoteTweetRequest(\n\ttext: string,\n\tauth: TwitterAuth,\n\ttweetId?: string,\n\tmediaData?: { data: Buffer; mediaType: string }[],\n) {\n\tconst onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n\tconst cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tauthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\tcookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n\t\t\"content-type\": \"application/json\",\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Linux; Android 11; Nokia G20) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.88 Mobile Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-twitter-client-language\": \"en\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\tconst variables: Record<string, any> = {\n\t\ttweet_text: text,\n\t\tdark_request: false,\n\t\tmedia: {\n\t\t\tmedia_entities: [],\n\t\t\tpossibly_sensitive: false,\n\t\t},\n\t\tsemantic_annotation_ids: [],\n\t};\n\n\tif (mediaData && mediaData.length > 0) {\n\t\tconst mediaIds = await Promise.all(\n\t\t\tmediaData.map(({ data, mediaType }) =>\n\t\t\t\tuploadMedia(data, auth, mediaType),\n\t\t\t),\n\t\t);\n\n\t\tvariables.media.media_entities = mediaIds.map((id) => ({\n\t\t\tmedia_id: id,\n\t\t\ttagged_users: [],\n\t\t}));\n\t}\n\n\tif (tweetId) {\n\t\tvariables.reply = { in_reply_to_tweet_id: tweetId };\n\t}\n\n\tconst response = await fetch(\n\t\t\"https://twitter.com/i/api/graphql/0aWhJJmFlxkxv9TAUJPanA/CreateNoteTweet\",\n\t\t{\n\t\t\theaders,\n\t\t\tbody: JSON.stringify({\n\t\t\t\tvariables,\n\t\t\t\tfeatures: {\n\t\t\t\t\tinteractive_text_enabled: true,\n\t\t\t\t\tlongform_notetweets_inline_media_enabled: false,\n\t\t\t\t\tresponsive_web_text_conversations_enabled: false,\n\t\t\t\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: false,\n\t\t\t\t\tvibe_api_enabled: false,\n\t\t\t\t\trweb_lists_timeline_redesign_enabled: true,\n\t\t\t\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\t\t\t\tverified_phone_label_enabled: false,\n\t\t\t\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\t\t\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\t\t\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\t\t\t\ttweetypie_unmention_optimization_enabled: true,\n\t\t\t\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\t\t\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\t\t\t\tview_counts_everywhere_api_enabled: true,\n\t\t\t\t\tlongform_notetweets_consumption_enabled: true,\n\t\t\t\t\tlongform_notetweets_creation_enabled: true,\n\t\t\t\t\ttweet_awards_web_tipping_enabled: false,\n\t\t\t\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\t\t\t\tstandardized_nudges_misinfo: true,\n\t\t\t\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\t\t\t\tresponsive_web_enhance_cards_enabled: false,\n\t\t\t\t\tsubscriptions_verification_info_enabled: true,\n\t\t\t\t\tsubscriptions_verification_info_reason_enabled: true,\n\t\t\t\t\tsubscriptions_verification_info_verified_since_enabled: true,\n\t\t\t\t\tsuper_follow_badge_privacy_enabled: false,\n\t\t\t\t\tsuper_follow_exclusive_tweet_notifications_enabled: false,\n\t\t\t\t\tsuper_follow_tweet_api_enabled: false,\n\t\t\t\t\tsuper_follow_user_api_enabled: false,\n\t\t\t\t\tandroid_graphql_skip_api_media_color_palette: false,\n\t\t\t\t\tcreator_subscriptions_subscription_count_enabled: false,\n\t\t\t\t\tblue_business_profile_image_shape_enabled: false,\n\t\t\t\t\tunified_cards_ad_metadata_container_dynamic_card_content_query_enabled: false,\n\t\t\t\t\trweb_video_timestamps_enabled: false,\n\t\t\t\t\tc9s_tweet_anatomy_moderator_badge_enabled: false,\n\t\t\t\t\tresponsive_web_twitter_article_tweet_consumption_enabled: false,\n\n\t\t\t\t\tcommunities_web_enable_tweet_community_results_fetch: false,\n\t\t\t\t\tarticles_preview_enabled: false,\n\t\t\t\t\trweb_tipjar_consumption_enabled: false,\n\t\t\t\t\tcreator_subscriptions_quote_tweet_preview_enabled: false,\n\t\t\t\t},\n\t\t\t\tfieldToggles: {},\n\t\t\t}),\n\t\t\tmethod: \"POST\",\n\t\t},\n\t);\n\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t// Check for errors and log the error response\n\tif (!response.ok) {\n\t\tconst errorText = await response.text();\n\t\tconsole.error(\"Error response:\", errorText);\n\t\tthrow new Error(`Failed to create long tweet: ${errorText}`);\n\t}\n\n\t// Parse and return the response\n\tconst data = await response.json();\n\treturn data;\n}\n\nexport async function fetchListTweets(\n\tlistId: string,\n\tmaxTweets: number,\n\tcursor: string | undefined,\n\tauth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n\tif (maxTweets > 200) {\n\t\tmaxTweets = 200;\n\t}\n\n\tconst listTweetsRequest = apiRequestFactory.createListTweetsRequest();\n\tlistTweetsRequest.variables.listId = listId;\n\tlistTweetsRequest.variables.count = maxTweets;\n\n\tif (cursor != null && cursor !== \"\") {\n\t\tlistTweetsRequest.variables.cursor = cursor;\n\t}\n\n\tconst res = await requestApi<ListTimeline>(\n\t\tlistTweetsRequest.toRequestUrl(),\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\treturn parseListTimelineTweets(res.value);\n}\n\nexport function getTweets(\n\tuser: string,\n\tmaxTweets: number,\n\tauth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n\treturn getTweetTimeline(user, maxTweets, async (q, mt, c) => {\n\t\tconst userIdRes = await getUserIdByScreenName(q, auth);\n\n\t\tif (!userIdRes.success) {\n\t\t\tthrow (userIdRes as any).err;\n\t\t}\n\n\t\tconst { value: userId } = userIdRes;\n\n\t\treturn fetchTweets(userId, mt, c, auth);\n\t});\n}\n\nexport function getTweetsByUserId(\n\tuserId: string,\n\tmaxTweets: number,\n\tauth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n\treturn getTweetTimeline(userId, maxTweets, (q, mt, c) => {\n\t\treturn fetchTweets(q, mt, c, auth);\n\t});\n}\n\nexport function getTweetsAndReplies(\n\tuser: string,\n\tmaxTweets: number,\n\tauth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n\treturn getTweetTimeline(user, maxTweets, async (q, mt, c) => {\n\t\tconst userIdRes = await getUserIdByScreenName(q, auth);\n\n\t\tif (!userIdRes.success) {\n\t\t\tthrow (userIdRes as any).err;\n\t\t}\n\n\t\tconst { value: userId } = userIdRes;\n\n\t\treturn fetchTweetsAndReplies(userId, mt, c, auth);\n\t});\n}\n\nexport function getTweetsAndRepliesByUserId(\n\tuserId: string,\n\tmaxTweets: number,\n\tauth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n\treturn getTweetTimeline(userId, maxTweets, (q, mt, c) => {\n\t\treturn fetchTweetsAndReplies(q, mt, c, auth);\n\t});\n}\n\nexport async function fetchLikedTweets(\n\tuserId: string,\n\tmaxTweets: number,\n\tcursor: string | undefined,\n\tauth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n\tif (!auth.isLoggedIn()) {\n\t\tthrow new Error(\"Client is not logged-in for fetching liked tweets.\");\n\t}\n\n\tif (maxTweets > 200) {\n\t\tmaxTweets = 200;\n\t}\n\n\tconst userTweetsRequest = apiRequestFactory.createUserLikedTweetsRequest();\n\tuserTweetsRequest.variables.userId = userId;\n\tuserTweetsRequest.variables.count = maxTweets;\n\tuserTweetsRequest.variables.includePromotedContent = false; // true on the website\n\n\tif (cursor != null && cursor !== \"\") {\n\t\tuserTweetsRequest.variables.cursor = cursor;\n\t}\n\n\tconst res = await requestApi<TimelineV2>(\n\t\tuserTweetsRequest.toRequestUrl(),\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\treturn parseTimelineTweetsV2(res.value);\n}\n\nexport async function getTweetWhere(\n\ttweets: AsyncIterable<Tweet>,\n\tquery: TweetQuery,\n): Promise<Tweet | null> {\n\tconst isCallback = typeof query === \"function\";\n\n\tfor await (const tweet of tweets) {\n\t\tconst matches = isCallback\n\t\t\t? await query(tweet)\n\t\t\t: checkTweetMatches(tweet, query);\n\n\t\tif (matches) {\n\t\t\treturn tweet;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nexport async function getTweetsWhere(\n\ttweets: AsyncIterable<Tweet>,\n\tquery: TweetQuery,\n): Promise<Tweet[]> {\n\tconst isCallback = typeof query === \"function\";\n\tconst filtered = [];\n\n\tfor await (const tweet of tweets) {\n\t\tconst matches = isCallback ? query(tweet) : checkTweetMatches(tweet, query);\n\n\t\tif (!matches) continue;\n\t\tfiltered.push(tweet);\n\t}\n\n\treturn filtered;\n}\n\nfunction checkTweetMatches(tweet: Tweet, options: Partial<Tweet>): boolean {\n\treturn Object.keys(options).every((k) => {\n\t\tconst key = k as keyof Tweet;\n\t\treturn tweet[key] === options[key];\n\t});\n}\n\nexport async function getLatestTweet(\n\tuser: string,\n\tincludeRetweets: boolean,\n\tmax: number,\n\tauth: TwitterAuth,\n): Promise<Tweet | null | undefined> {\n\tconst timeline = getTweets(user, max, auth);\n\n\t// No point looping if max is 1, just use first entry.\n\treturn max === 1\n\t\t? ((await timeline.next()).value as Tweet)\n\t\t: await getTweetWhere(timeline, { isRetweet: includeRetweets });\n}\n\nexport interface TweetResultByRestId {\n\tdata?: TimelineEntryItemContentRaw;\n}\n\nexport async function getTweet(\n\tid: string,\n\tauth: TwitterAuth,\n): Promise<Tweet | null> {\n\tconst tweetDetailRequest = apiRequestFactory.createTweetDetailRequest();\n\ttweetDetailRequest.variables.focalTweetId = id;\n\n\tconst res = await requestApi<ThreadedConversation>(\n\t\ttweetDetailRequest.toRequestUrl(),\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\tif (!res.value) {\n\t\treturn null;\n\t}\n\n\tconst tweets = parseThreadedConversation(res.value);\n\treturn tweets.find((tweet) => tweet.id === id) ?? null;\n}\n\nexport async function getTweetV2(\n\tid: string,\n\tauth: TwitterAuth,\n\toptions: {\n\t\texpansions?: TTweetv2Expansion[];\n\t\ttweetFields?: TTweetv2TweetField[];\n\t\tpollFields?: TTweetv2PollField[];\n\t\tmediaFields?: TTweetv2MediaField[];\n\t\tuserFields?: TTweetv2UserField[];\n\t\tplaceFields?: TTweetv2PlaceField[];\n\t} = defaultOptions,\n): Promise<Tweet | null> {\n\tconst v2client = auth.getV2Client();\n\tif (!v2client) {\n\t\tthrow new Error(\"V2 client is not initialized\");\n\t}\n\n\ttry {\n\t\tconst tweetData = await v2client.v2.singleTweet(id, {\n\t\t\texpansions: options?.expansions,\n\t\t\t\"tweet.fields\": options?.tweetFields,\n\t\t\t\"poll.fields\": options?.pollFields,\n\t\t\t\"media.fields\": options?.mediaFields,\n\t\t\t\"user.fields\": options?.userFields,\n\t\t\t\"place.fields\": options?.placeFields,\n\t\t});\n\n\t\tif (!tweetData?.data) {\n\t\t\tconsole.warn(`Tweet data not found for ID: ${id}`);\n\t\t\treturn null;\n\t\t}\n\n\t\tconst defaultTweetData = await getTweet(tweetData.data.id, auth);\n\t\t// Extract primary tweet data\n\t\tconst parsedTweet = parseTweetV2ToV1(\n\t\t\ttweetData.data,\n\t\t\ttweetData?.includes,\n\t\t\tdefaultTweetData,\n\t\t);\n\n\t\treturn parsedTweet;\n\t} catch (error) {\n\t\tconsole.error(`Error fetching tweet ${id}:`, error);\n\t\treturn null;\n\t}\n}\n\nexport async function getTweetsV2(\n\tids: string[],\n\tauth: TwitterAuth,\n\toptions: {\n\t\texpansions?: TTweetv2Expansion[];\n\t\ttweetFields?: TTweetv2TweetField[];\n\t\tpollFields?: TTweetv2PollField[];\n\t\tmediaFields?: TTweetv2MediaField[];\n\t\tuserFields?: TTweetv2UserField[];\n\t\tplaceFields?: TTweetv2PlaceField[];\n\t} = defaultOptions,\n): Promise<Tweet[]> {\n\tconst v2client = auth.getV2Client();\n\tif (!v2client) {\n\t\treturn [];\n\t}\n\n\ttry {\n\t\tconst tweetData = await v2client.v2.tweets(ids, {\n\t\t\texpansions: options?.expansions,\n\t\t\t\"tweet.fields\": options?.tweetFields,\n\t\t\t\"poll.fields\": options?.pollFields,\n\t\t\t\"media.fields\": options?.mediaFields,\n\t\t\t\"user.fields\": options?.userFields,\n\t\t\t\"place.fields\": options?.placeFields,\n\t\t});\n\t\tconst tweetsV2 = tweetData.data;\n\t\tif (tweetsV2.length === 0) {\n\t\t\tconsole.warn(`No tweet data found for IDs: ${ids.join(\", \")}`);\n\t\t\treturn [];\n\t\t}\n\t\treturn (\n\t\t\tawait Promise.all(\n\t\t\t\ttweetsV2.map(\n\t\t\t\t\tasync (tweet) => await getTweetV2(tweet.id, auth, options),\n\t\t\t\t),\n\t\t\t)\n\t\t).filter((tweet): tweet is Tweet => tweet !== null);\n\t} catch (error) {\n\t\tconsole.error(`Error fetching tweets for IDs: ${ids.join(\", \")}`, error);\n\t\treturn [];\n\t}\n}\n\nexport async function getTweetAnonymous(\n\tid: string,\n\tauth: TwitterAuth,\n): Promise<Tweet | null> {\n\tconst tweetResultByRestIdRequest =\n\t\tapiRequestFactory.createTweetResultByRestIdRequest();\n\ttweetResultByRestIdRequest.variables.tweetId = id;\n\n\tconst res = await requestApi<TweetResultByRestId>(\n\t\ttweetResultByRestIdRequest.toRequestUrl(),\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\tif (!res.value.data) {\n\t\treturn null;\n\t}\n\n\treturn parseTimelineEntryItemContentRaw(res.value.data, id);\n}\n\ninterface MediaUploadResponse {\n\tmedia_id_string: string;\n\tsize: number;\n\texpires_after_secs: number;\n\timage: {\n\t\timage_type: string;\n\t\tw: number;\n\t\th: number;\n\t};\n}\n\nasync function uploadMedia(\n\tmediaData: Buffer,\n\tauth: TwitterAuth,\n\tmediaType: string,\n): Promise<string> {\n\tconst uploadUrl = \"https://upload.twitter.com/1.1/media/upload.json\";\n\n\t// Get authentication headers\n\tconst cookies = await auth.cookieJar().getCookies(uploadUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\tconst headers = new Headers({\n\t\tauthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\tcookie: await auth.cookieJar().getCookieString(uploadUrl),\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\t// Detect if media is a video based on mediaType\n\tconst isVideo = mediaType.startsWith(\"video/\");\n\n\tif (isVideo) {\n\t\t// Handle video upload using chunked media upload\n\t\tconst mediaId = await uploadVideoInChunks(mediaData, mediaType);\n\t\treturn mediaId;\n\t}\n\t// Handle image upload\n\tconst form = new FormData();\n\tform.append(\"media\", new Blob([mediaData]));\n\n\tconst response = await fetch(uploadUrl, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: form,\n\t});\n\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\tif (!response.ok) {\n\t\tthrow new Error(await response.text());\n\t}\n\n\tconst data: MediaUploadResponse = await response.json();\n\treturn data.media_id_string;\n\n\t// Function to upload video in chunks\n\tasync function uploadVideoInChunks(\n\t\tmediaData: Buffer,\n\t\tmediaType: string,\n\t): Promise<string> {\n\t\t// Initialize upload\n\t\tconst initParams = new URLSearchParams();\n\t\tinitParams.append(\"command\", \"INIT\");\n\t\tinitParams.append(\"media_type\", mediaType);\n\t\tinitParams.append(\"total_bytes\", mediaData.length.toString());\n\n\t\tconst initResponse = await fetch(uploadUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: initParams,\n\t\t});\n\n\t\tif (!initResponse.ok) {\n\t\t\tthrow new Error(await initResponse.text());\n\t\t}\n\n\t\tconst initData = await initResponse.json();\n\t\tconst mediaId = initData.media_id_string;\n\n\t\t// Append upload in chunks\n\t\tconst segmentSize = 5 * 1024 * 1024; // 5 MB per chunk\n\t\tlet segmentIndex = 0;\n\t\tfor (let offset = 0; offset < mediaData.length; offset += segmentSize) {\n\t\t\tconst chunk = mediaData.slice(offset, offset + segmentSize);\n\n\t\t\tconst appendForm = new FormData();\n\t\t\tappendForm.append(\"command\", \"APPEND\");\n\t\t\tappendForm.append(\"media_id\", mediaId);\n\t\t\tappendForm.append(\"segment_index\", segmentIndex.toString());\n\t\t\tappendForm.append(\"media\", new Blob([chunk]));\n\n\t\t\tconst appendResponse = await fetch(uploadUrl, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders,\n\t\t\t\tbody: appendForm,\n\t\t\t});\n\n\t\t\tif (!appendResponse.ok) {\n\t\t\t\tthrow new Error(await appendResponse.text());\n\t\t\t}\n\n\t\t\tsegmentIndex++;\n\t\t}\n\n\t\t// Finalize upload\n\t\tconst finalizeParams = new URLSearchParams();\n\t\tfinalizeParams.append(\"command\", \"FINALIZE\");\n\t\tfinalizeParams.append(\"media_id\", mediaId);\n\n\t\tconst finalizeResponse = await fetch(uploadUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: finalizeParams,\n\t\t});\n\n\t\tif (!finalizeResponse.ok) {\n\t\t\tthrow new Error(await finalizeResponse.text());\n\t\t}\n\n\t\tconst finalizeData = await finalizeResponse.json();\n\n\t\t// Check processing status for videos\n\t\tif (finalizeData.processing_info) {\n\t\t\tawait checkUploadStatus(mediaId);\n\t\t}\n\n\t\treturn mediaId;\n\t}\n\n\t// Function to check upload status\n\tasync function checkUploadStatus(mediaId: string): Promise<void> {\n\t\tlet processing = true;\n\t\twhile (processing) {\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 5 seconds\n\n\t\t\tconst statusParams = new URLSearchParams();\n\t\t\tstatusParams.append(\"command\", \"STATUS\");\n\t\t\tstatusParams.append(\"media_id\", mediaId);\n\n\t\t\tconst statusResponse = await fetch(\n\t\t\t\t`${uploadUrl}?${statusParams.toString()}`,\n\t\t\t\t{\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\theaders,\n\t\t\t\t},\n\t\t\t);\n\n\t\t\tif (!statusResponse.ok) {\n\t\t\t\tthrow new Error(await statusResponse.text());\n\t\t\t}\n\n\t\t\tconst statusData = await statusResponse.json();\n\t\t\tconst state = statusData.processing_info.state;\n\n\t\t\tif (state === \"succeeded\") {\n\t\t\t\tprocessing = false;\n\t\t\t} else if (state === \"failed\") {\n\t\t\t\tthrow new Error(\"Video processing failed\");\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Function to create a quote tweet\nexport async function createQuoteTweetRequest(\n\ttext: string,\n\tquotedTweetId: string,\n\tauth: TwitterAuth,\n\tmediaData?: { data: Buffer; mediaType: string }[],\n) {\n\tconst onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n\t// Retrieve necessary cookies and tokens\n\tconst cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tauthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\tcookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n\t\t\"content-type\": \"application/json\",\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Linux; Android 11; Nokia G20) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.88 Mobile Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\t// Construct variables for the GraphQL request\n\tconst variables: Record<string, any> = {\n\t\ttweet_text: text,\n\t\tdark_request: false,\n\t\tattachment_url: `https://twitter.com/twitter/status/${quotedTweetId}`,\n\t\tmedia: {\n\t\t\tmedia_entities: [],\n\t\t\tpossibly_sensitive: false,\n\t\t},\n\t\tsemantic_annotation_ids: [],\n\t};\n\n\t// Handle media uploads if any media data is provided\n\tif (mediaData && mediaData.length > 0) {\n\t\tconst mediaIds = await Promise.all(\n\t\t\tmediaData.map(({ data, mediaType }) =>\n\t\t\t\tuploadMedia(data, auth, mediaType),\n\t\t\t),\n\t\t);\n\n\t\tvariables.media.media_entities = mediaIds.map((id) => ({\n\t\t\tmedia_id: id,\n\t\t\ttagged_users: [],\n\t\t}));\n\t}\n\n\t// Send the GraphQL request to create a quote tweet\n\tconst response = await fetch(\n\t\t\"https://twitter.com/i/api/graphql/a1p9RWpkYKBjWv_I3WzS-A/CreateTweet\",\n\t\t{\n\t\t\theaders,\n\t\t\tbody: JSON.stringify({\n\t\t\t\tvariables,\n\t\t\t\tfeatures: {\n\t\t\t\t\tinteractive_text_enabled: true,\n\t\t\t\t\tlongform_notetweets_inline_media_enabled: false,\n\t\t\t\t\tresponsive_web_text_conversations_enabled: false,\n\t\t\t\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: false,\n\t\t\t\t\tvibe_api_enabled: false,\n\t\t\t\t\trweb_lists_timeline_redesign_enabled: true,\n\t\t\t\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\t\t\t\tverified_phone_label_enabled: false,\n\t\t\t\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\t\t\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\t\t\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\t\t\t\ttweetypie_unmention_optimization_enabled: true,\n\t\t\t\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\t\t\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\t\t\t\tview_counts_everywhere_api_enabled: true,\n\t\t\t\t\tlongform_notetweets_consumption_enabled: true,\n\t\t\t\t\ttweet_awards_web_tipping_enabled: false,\n\t\t\t\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\t\t\t\tstandardized_nudges_misinfo: true,\n\t\t\t\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\t\t\t\tresponsive_web_enhance_cards_enabled: false,\n\t\t\t\t\tsubscriptions_verification_info_enabled: true,\n\t\t\t\t\tsubscriptions_verification_info_reason_enabled: true,\n\t\t\t\t\tsubscriptions_verification_info_verified_since_enabled: true,\n\t\t\t\t\tsuper_follow_badge_privacy_enabled: false,\n\t\t\t\t\tsuper_follow_exclusive_tweet_notifications_enabled: false,\n\t\t\t\t\tsuper_follow_tweet_api_enabled: false,\n\t\t\t\t\tsuper_follow_user_api_enabled: false,\n\t\t\t\t\tandroid_graphql_skip_api_media_color_palette: false,\n\t\t\t\t\tcreator_subscriptions_subscription_count_enabled: false,\n\t\t\t\t\tblue_business_profile_image_shape_enabled: false,\n\t\t\t\t\tunified_cards_ad_metadata_container_dynamic_card_content_query_enabled: false,\n\t\t\t\t\trweb_video_timestamps_enabled: true,\n\t\t\t\t\tc9s_tweet_anatomy_moderator_badge_enabled: true,\n\t\t\t\t\tresponsive_web_twitter_article_tweet_consumption_enabled: false,\n\t\t\t\t},\n\t\t\t\tfieldToggles: {},\n\t\t\t}),\n\t\t\tmethod: \"POST\",\n\t\t},\n\t);\n\n\t// Update the cookie jar with any new cookies from the response\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t// Check for errors in the response\n\tif (!response.ok) {\n\t\tthrow new Error(await response.text());\n\t}\n\n\treturn response;\n}\n\n/**\n * Likes a tweet with the given tweet ID.\n * @param tweetId The ID of the tweet to like.\n * @param auth The authentication object.\n * @returns A promise that resolves when the tweet is liked.\n */\nexport async function likeTweet(\n\ttweetId: string,\n\tauth: TwitterAuth,\n): Promise<void> {\n\t// Prepare the GraphQL endpoint and payload\n\tconst likeTweetUrl =\n\t\t\"https://twitter.com/i/api/graphql/lI07N6Otwv1PhnEgXILM7A/FavoriteTweet\";\n\n\t// Retrieve necessary cookies and tokens\n\tconst cookies = await auth.cookieJar().getCookies(likeTweetUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tauthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\tcookie: await auth.cookieJar().getCookieString(likeTweetUrl),\n\t\t\"content-type\": \"application/json\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\tconst payload = {\n\t\tvariables: {\n\t\t\ttweet_id: tweetId,\n\t\t},\n\t};\n\n\t// Send the POST request to like the tweet\n\tconst response = await fetch(likeTweetUrl, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(payload),\n\t});\n\n\t// Update the cookie jar with any new cookies from the response\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t// Check for errors in the response\n\tif (!response.ok) {\n\t\tthrow new Error(await response.text());\n\t}\n}\n\n/**\n * Retweets a tweet with the given tweet ID.\n * @param tweetId The ID of the tweet to retweet.\n * @param auth The authentication object.\n * @returns A promise that resolves when the tweet is retweeted.\n */\nexport async function retweet(\n\ttweetId: string,\n\tauth: TwitterAuth,\n): Promise<void> {\n\t// Prepare the GraphQL endpoint and payload\n\tconst retweetUrl =\n\t\t\"https://twitter.com/i/api/graphql/ojPdsZsimiJrUGLR1sjUtA/CreateRetweet\";\n\n\t// Retrieve necessary cookies and tokens\n\tconst cookies = await auth.cookieJar().getCookies(retweetUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tauthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\tcookie: await auth.cookieJar().getCookieString(retweetUrl),\n\t\t\"content-type\": \"application/json\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\tconst payload = {\n\t\tvariables: {\n\t\t\ttweet_id: tweetId,\n\t\t\tdark_request: false,\n\t\t},\n\t};\n\n\t// Send the POST request to retweet the tweet\n\tconst response = await fetch(retweetUrl, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(payload),\n\t});\n\n\t// Update the cookie jar with any new cookies from the response\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t// Check for errors in the response\n\tif (!response.ok) {\n\t\tthrow new Error(await response.text());\n\t}\n}\n\nexport async function createCreateLongTweetRequest(\n\ttext: string,\n\tauth: TwitterAuth,\n\ttweetId?: string,\n\tmediaData?: { data: Buffer; mediaType: string }[],\n) {\n\t// URL for the long tweet endpoint\n\tconst url =\n\t\t\"https://x.com/i/api/graphql/YNXM2DGuE2Sff6a2JD3Ztw/CreateNoteTweet\";\n\tconst onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n\tconst cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\t//@ ts-expect-error - This is a private API.\n\tconst headers = new Headers({\n\t\tauthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\tcookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n\t\t\"content-type\": \"application/json\",\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Linux; Android 11; Nokia G20) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.88 Mobile Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-twitter-client-language\": \"en\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\tconst variables: Record<string, any> = {\n\t\ttweet_text: text,\n\t\tdark_request: false,\n\t\tmedia: {\n\t\t\tmedia_entities: [],\n\t\t\tpossibly_sensitive: false,\n\t\t},\n\t\tsemantic_annotation_ids: [],\n\t};\n\n\tif (mediaData && mediaData.length > 0) {\n\t\tconst mediaIds = await Promise.all(\n\t\t\tmediaData.map(({ data, mediaType }) =>\n\t\t\t\tuploadMedia(data, auth, mediaType),\n\t\t\t),\n\t\t);\n\n\t\tvariables.media.media_entities = mediaIds.map((id) => ({\n\t\t\tmedia_id: id,\n\t\t\ttagged_users: [],\n\t\t}));\n\t}\n\n\tif (tweetId) {\n\t\tvariables.reply = { in_reply_to_tweet_id: tweetId };\n\t}\n\n\tconst features = {\n\t\tpremium_content_api_read_enabled: false,\n\t\tcommunities_web_enable_tweet_community_results_fetch: true,\n\t\tc9s_tweet_anatomy_moderator_badge_enabled: true,\n\t\tresponsive_web_grok_analyze_button_fetch_trends_enabled: true,\n\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\tview_counts_everywhere_api_enabled: true,\n\t\tlongform_notetweets_consumption_enabled: true,\n\t\tresponsive_web_twitter_article_tweet_consumption_enabled: true,\n\t\ttweet_awards_web_tipping_enabled: false,\n\t\tcreator_subscriptions_quote_tweet_preview_enabled: false,\n\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\tlongform_notetweets_inline_media_enabled: true,\n\t\tprofile_label_improvements_pcf_label_in_post_enabled: false,\n\t\trweb_tipjar_consumption_enabled: true,\n\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\tverified_phone_label_enabled: false,\n\t\tarticles_preview_enabled: true,\n\t\trweb_video_timestamps_enabled: true,\n\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\tstandardized_nudges_misinfo: true,\n\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,\n\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\tresponsive_web_enhance_cards_enabled: false,\n\t};\n\n\tconst response = await fetch(url, {\n\t\theaders,\n\t\tbody: JSON.stringify({\n\t\t\tvariables,\n\t\t\tfeatures,\n\t\t\tqueryId: \"YNXM2DGuE2Sff6a2JD3Ztw\",\n\t\t}),\n\t\tmethod: \"POST\",\n\t});\n\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t// check for errors\n\tif (!response.ok) {\n\t\tthrow new Error(await response.text());\n\t}\n\n\treturn response;\n}\n\nexport async function getArticle(\n\tid: string,\n\tauth: TwitterAuth,\n): Promise<TimelineArticle | null> {\n\tconst tweetDetailRequest =\n\t\tapiRequestFactory.createTweetDetailArticleRequest();\n\ttweetDetailRequest.variables.focalTweetId = id;\n\n\tconst res = await requestApi<ThreadedConversation>(\n\t\ttweetDetailRequest.toRequestUrl(),\n\t\tauth,\n\t);\n\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\tif (!res.value) {\n\t\treturn null;\n\t}\n\n\tconst articles = parseArticle(res.value);\n\treturn articles.find((article) => article.id === id) ?? null;\n}\n\n/**\n * Fetches a single page of retweeters for a given tweet, collecting both bottom and top cursors.\n * Logs each user's description in the process.\n * All comments must remain in English.\n */\nexport async function fetchRetweetersPage(\n\ttweetId: string,\n\tauth: TwitterAuth,\n\tcursor?: string,\n\tcount = 40,\n): Promise<{\n\tretweeters: Retweeter[];\n\tbottomCursor?: string;\n\ttopCursor?: string;\n}> {\n\tconst baseUrl =\n\t\t\"https://twitter.com/i/api/graphql/VSnHXwLGADxxtetlPnO7xg/Retweeters\";\n\n\t// Build query parameters\n\tconst variables = {\n\t\ttweetId,\n\t\tcount,\n\t\tcursor,\n\t\tincludePromotedContent: true,\n\t};\n\tconst features = {\n\t\tprofile_label_improvements_pcf_label_in_post_enabled: true,\n\t\trweb_tipjar_consumption_enabled: true,\n\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\tverified_phone_label_enabled: false,\n\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\tpremium_content_api_read_enabled: false,\n\t\tcommunities_web_enable_tweet_community_results_fetch: true,\n\t\tc9s_tweet_anatomy_moderator_badge_enabled: true,\n\t\tresponsive_web_grok_analyze_button_fetch_trends_enabled: false,\n\t\tresponsive_web_grok_analyze_post_followups_enabled: true,\n\t\tresponsive_web_jetfuel_frame: false,\n\t\tresponsive_web_grok_share_attachment_enabled: true,\n\t\tarticles_preview_enabled: true,\n\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\tview_counts_everywhere_api_enabled: true,\n\t\tlongform_notetweets_consumption_enabled: true,\n\t\tresponsive_web_twitter_article_tweet_consumption_enabled: true,\n\t\ttweet_awards_web_tipping_enabled: false,\n\t\tcreator_subscriptions_quote_tweet_preview_enabled: false,\n\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\tstandardized_nudges_misinfo: true,\n\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,\n\t\trweb_video_timestamps_enabled: true,\n\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\tlongform_notetweets_inline_media_enabled: true,\n\t\tresponsive_web_grok_image_annotation_enabled: false,\n\t\tresponsive_web_enhance_cards_enabled: false,\n\t};\n\n\t// Prepare URL with query params\n\tconst url = new URL(baseUrl);\n\turl.searchParams.set(\"variables\", JSON.stringify(variables));\n\turl.searchParams.set(\"features\", JSON.stringify(features));\n\n\t// Retrieve necessary cookies and tokens\n\tconst cookies = await auth.cookieJar().getCookies(url.toString());\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tauthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\tcookie: await auth.cookieJar().getCookieString(url.toString()),\n\t\t\"content-type\": \"application/json\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken?.value || \"\",\n\t});\n\n\tconst response = await fetch(url.toString(), {\n\t\tmethod: \"GET\",\n\t\theaders,\n\t});\n\n\t// Update cookies if needed\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\tif (!response.ok) {\n\t\tthrow new Error(await response.text());\n\t}\n\n\tconst json = await response.json();\n\tconst instructions =\n\t\tjson?.data?.retweeters_timeline?.timeline?.instructions || [];\n\n\tconst retweeters: Retweeter[] = [];\n\tlet bottomCursor: string | undefined;\n\tlet topCursor: string | undefined;\n\n\t// Parse the retweeters from instructions\n\tfor (const instruction of instructions) {\n\t\tif (instruction.type === \"TimelineAddEntries\") {\n\t\t\tfor (const entry of instruction.entries) {\n\t\t\t\t// If this entry is a user entry\n\t\t\t\tif (entry.content?.itemContent?.user_results?.result) {\n\t\t\t\t\tconst user = entry.content.itemContent.user_results.result;\n\t\t\t\t\tconst description = user.legacy?.name ?? \"\";\n\n\t\t\t\t\tretweeters.push({\n\t\t\t\t\t\trest_id: user.rest_id,\n\t\t\t\t\t\tscreen_name: user.legacy?.screen_name ?? \"\",\n\t\t\t\t\t\tname: user.legacy?.name ?? \"\",\n\t\t\t\t\t\tdescription,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// Capture the bottom cursor\n\t\t\t\tif (\n\t\t\t\t\tentry.content?.entryType === \"TimelineTimelineCursor\" &&\n\t\t\t\t\tentry.content?.cursorType === \"Bottom\"\n\t\t\t\t) {\n\t\t\t\t\tbottomCursor = entry.content.value;\n\t\t\t\t}\n\n\t\t\t\t// Capture the top cursor\n\t\t\t\tif (\n\t\t\t\t\tentry.content?.entryType === \"TimelineTimelineCursor\" &&\n\t\t\t\t\tentry.content?.cursorType === \"Top\"\n\t\t\t\t) {\n\t\t\t\t\ttopCursor = entry.content.value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { retweeters, bottomCursor, topCursor };\n}\n\n/**\n * Retrieves *all* retweeters by chaining requests until no next cursor is found.\n * @param tweetId The ID of the tweet.\n * @param auth The TwitterAuth object for authentication.\n * @returns A list of all users that retweeted the tweet.\n */\nexport async function getAllRetweeters(\n\ttweetId: string,\n\tauth: TwitterAuth,\n): Promise<Retweeter[]> {\n\tlet allRetweeters: Retweeter[] = [];\n\tlet cursor: string | undefined;\n\n\twhile (true) {\n\t\t// Destructure bottomCursor / topCursor\n\t\tconst { retweeters, bottomCursor, topCursor } = await fetchRetweetersPage(\n\t\t\ttweetId,\n\t\t\tauth,\n\t\t\tcursor,\n\t\t\t40,\n\t\t);\n\t\tallRetweeters = allRetweeters.concat(retweeters);\n\n\t\tconst newCursor = bottomCursor || topCursor;\n\n\t\t// Stop if there is no new cursor or if it's the same as the old one\n\t\tif (!newCursor || newCursor === cursor) {\n\t\t\tbreak;\n\t\t}\n\n\t\tcursor = newCursor;\n\t}\n\n\treturn allRetweeters;\n}\n","import { requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport { ApiError } from \"./errors\";\nimport type { TimelineInstruction } from \"./timeline-v2\";\n\nexport interface HomeTimelineResponse {\n\tdata?: {\n\t\thome: {\n\t\t\thome_timeline_urt: {\n\t\t\t\tinstructions: TimelineInstruction[];\n\t\t\t};\n\t\t};\n\t};\n}\n\nexport async function fetchHomeTimeline(\n\tcount: number,\n\tseenTweetIds: string[],\n\tauth: TwitterAuth,\n): Promise<any[]> {\n\tconst variables = {\n\t\tcount,\n\t\tincludePromotedContent: true,\n\t\tlatestControlAvailable: true,\n\t\trequestContext: \"launch\",\n\t\twithCommunity: true,\n\t\tseenTweetIds,\n\t};\n\n\tconst features = {\n\t\trweb_tipjar_consumption_enabled: true,\n\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\tverified_phone_label_enabled: false,\n\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\tcommunities_web_enable_tweet_community_results_fetch: true,\n\t\tc9s_tweet_anatomy_moderator_badge_enabled: true,\n\t\tarticles_preview_enabled: true,\n\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\tview_counts_everywhere_api_enabled: true,\n\t\tlongform_notetweets_consumption_enabled: true,\n\t\tresponsive_web_twitter_article_tweet_consumption_enabled: true,\n\t\ttweet_awards_web_tipping_enabled: false,\n\t\tcreator_subscriptions_quote_tweet_preview_enabled: false,\n\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\tstandardized_nudges_misinfo: true,\n\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,\n\t\trweb_video_timestamps_enabled: true,\n\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\tlongform_notetweets_inline_media_enabled: true,\n\t\tresponsive_web_enhance_cards_enabled: false,\n\t};\n\n\tconst res = await requestApi<HomeTimelineResponse>(\n\t\t`https://x.com/i/api/graphql/HJFjzBgCs16TqxewQOeLNg/HomeTimeline?variables=${encodeURIComponent(\n\t\t\tJSON.stringify(variables),\n\t\t)}&features=${encodeURIComponent(JSON.stringify(features))}`,\n\t\tauth,\n\t\t\"GET\",\n\t);\n\n\tif (!res.success) {\n\t\tif (res.err instanceof ApiError) {\n\t\t\tconsole.error(\"Error details:\", res.err.data);\n\t\t}\n\t\tthrow res.err;\n\t}\n\n\tconst home = res.value?.data?.home.home_timeline_urt?.instructions;\n\n\tif (!home) {\n\t\treturn [];\n\t}\n\n\tconst entries: any[] = [];\n\n\tfor (const instruction of home) {\n\t\tif (instruction.type === \"TimelineAddEntries\") {\n\t\t\tfor (const entry of instruction.entries ?? []) {\n\t\t\t\tentries.push(entry);\n\t\t\t}\n\t\t}\n\t}\n\t// get the itemContnent from each entry\n\tconst tweets = entries\n\t\t.map((entry) => entry.content.itemContent?.tweet_results?.result)\n\t\t.filter((tweet) => tweet !== undefined);\n\n\treturn tweets;\n}\n","import { requestApi, type RequestApiResult } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport { ApiError } from \"./errors\";\nimport type { TimelineInstruction } from \"./timeline-v2\";\n\nexport interface HomeLatestTimelineResponse {\n\tdata?: {\n\t\thome: {\n\t\t\thome_timeline_urt: {\n\t\t\t\tinstructions: TimelineInstruction[];\n\t\t\t};\n\t\t};\n\t};\n}\n\nexport async function fetchFollowingTimeline(\n\tcount: number,\n\tseenTweetIds: string[],\n\tauth: TwitterAuth,\n): Promise<any[]> {\n\tconst variables = {\n\t\tcount,\n\t\tincludePromotedContent: true,\n\t\tlatestControlAvailable: true,\n\t\trequestContext: \"launch\",\n\t\tseenTweetIds,\n\t};\n\n\tconst features = {\n\t\tprofile_label_improvements_pcf_label_in_post_enabled: true,\n\t\trweb_tipjar_consumption_enabled: true,\n\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\tverified_phone_label_enabled: false,\n\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\tcommunities_web_enable_tweet_community_results_fetch: true,\n\t\tc9s_tweet_anatomy_moderator_badge_enabled: true,\n\t\tarticles_preview_enabled: true,\n\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\tview_counts_everywhere_api_enabled: true,\n\t\tlongform_notetweets_consumption_enabled: true,\n\t\tresponsive_web_twitter_article_tweet_consumption_enabled: true,\n\t\ttweet_awards_web_tipping_enabled: false,\n\t\tcreator_subscriptions_quote_tweet_preview_enabled: false,\n\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\tstandardized_nudges_misinfo: true,\n\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,\n\t\trweb_video_timestamps_enabled: true,\n\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\tlongform_notetweets_inline_media_enabled: true,\n\t\tresponsive_web_enhance_cards_enabled: false,\n\t};\n\n\tconst res = (await requestApi<HomeLatestTimelineResponse>(\n\t\t`https://x.com/i/api/graphql/K0X1xbCZUjttdK8RazKAlw/HomeLatestTimeline?variables=${encodeURIComponent(\n\t\t\tJSON.stringify(variables),\n\t\t)}&features=${encodeURIComponent(JSON.stringify(features))}`,\n\t\tauth,\n\t\t\"GET\",\n\t)) as RequestApiResult<HomeLatestTimelineResponse>;\n\n\tconsole.log(\"res\", res);\n\n\tif (!res.success) {\n\t\tif ((res as any).err instanceof ApiError) {\n\t\t\tconsole.error(\"Error details:\", (res as any).err.data);\n\t\t}\n\t\tthrow (res as any).err;\n\t}\n\n\tconst home = res.value?.data?.home.home_timeline_urt?.instructions;\n\n\tif (!home) {\n\t\treturn [];\n\t}\n\n\tconst entries: any[] = [];\n\n\tfor (const instruction of home) {\n\t\tif (instruction.type === \"TimelineAddEntries\") {\n\t\t\tfor (const entry of instruction.entries ?? []) {\n\t\t\t\tentries.push(entry);\n\t\t\t}\n\t\t}\n\t}\n\t// get the itemContnent from each entry\n\tconst tweets = entries\n\t\t.map((entry) => entry.content.itemContent?.tweet_results?.result)\n\t\t.filter((tweet) => tweet !== undefined);\n\n\treturn tweets;\n}\n","import type { TwitterAuth } from \"./auth\";\nimport { updateCookieJar } from \"./requests\";\n\nexport interface DirectMessage {\n\tid: string;\n\ttext: string;\n\tsenderId: string;\n\trecipientId: string;\n\tcreatedAt: string;\n\tmediaUrls?: string[];\n\tsenderScreenName?: string;\n\trecipientScreenName?: string;\n}\n\nexport interface DirectMessageConversation {\n\tconversationId: string;\n\tmessages: DirectMessage[];\n\tparticipants: {\n\t\tid: string;\n\t\tscreenName: string;\n\t}[];\n}\n\nexport interface DirectMessageEvent {\n\tid: string;\n\ttype: string;\n\tmessage_create: {\n\t\tsender_id: string;\n\t\ttarget: {\n\t\t\trecipient_id: string;\n\t\t};\n\t\tmessage_data: {\n\t\t\ttext: string;\n\t\t\tcreated_at: string;\n\t\t\tentities?: {\n\t\t\t\turls?: Array<{\n\t\t\t\t\turl: string;\n\t\t\t\t\texpanded_url: string;\n\t\t\t\t\tdisplay_url: string;\n\t\t\t\t}>;\n\t\t\t\tmedia?: Array<{\n\t\t\t\t\turl: string;\n\t\t\t\t\ttype: string;\n\t\t\t\t}>;\n\t\t\t};\n\t\t};\n\t};\n}\n\nexport interface DirectMessagesResponse {\n\tconversations: DirectMessageConversation[];\n\tusers: TwitterUser[];\n\tcursor?: string;\n\tlastSeenEventId?: string;\n\ttrustedLastSeenEventId?: string;\n\tuntrustedLastSeenEventId?: string;\n\tinboxTimelines?: {\n\t\ttrusted?: {\n\t\t\tstatus: string;\n\t\t\tminEntryId?: string;\n\t\t};\n\t\tuntrusted?: {\n\t\t\tstatus: string;\n\t\t\tminEntryId?: string;\n\t\t};\n\t};\n\tuserId: string;\n}\n\nexport interface TwitterUser {\n\tid: string;\n\tscreenName: string;\n\tname: string;\n\tprofileImageUrl: string;\n\tdescription?: string;\n\tverified?: boolean;\n\tprotected?: boolean;\n\tfollowersCount?: number;\n\tfriendsCount?: number;\n}\n\nexport interface SendDirectMessageResponse {\n\tentries: {\n\t\tmessage: {\n\t\t\tid: string;\n\t\t\ttime: string;\n\t\t\taffects_sort: boolean;\n\t\t\tconversation_id: string;\n\t\t\tmessage_data: {\n\t\t\t\tid: string;\n\t\t\t\ttime: string;\n\t\t\t\trecipient_id: string;\n\t\t\t\tsender_id: string;\n\t\t\t\ttext: string;\n\t\t\t};\n\t\t};\n\t}[];\n\tusers: Record<string, TwitterUser>;\n}\n\nfunction parseDirectMessageConversations(\n\tdata: any,\n\tuserId: string,\n): DirectMessagesResponse {\n\ttry {\n\t\tconst inboxState = data?.inbox_initial_state;\n\t\tconst conversations = inboxState?.conversations || {};\n\t\tconst entries = inboxState?.entries || [];\n\t\tconst users = inboxState?.users || {};\n\n\t\t// Parse users first\n\t\tconst parsedUsers: TwitterUser[] = Object.values(users).map(\n\t\t\t(user: any) => ({\n\t\t\t\tid: user.id_str,\n\t\t\t\tscreenName: user.screen_name,\n\t\t\t\tname: user.name,\n\t\t\t\tprofileImageUrl: user.profile_image_url_https,\n\t\t\t\tdescription: user.description,\n\t\t\t\tverified: user.verified,\n\t\t\t\tprotected: user.protected,\n\t\t\t\tfollowersCount: user.followers_count,\n\t\t\t\tfriendsCount: user.friends_count,\n\t\t\t}),\n\t\t);\n\n\t\t// Group messages by conversation_id\n\t\tconst messagesByConversation: Record<string, any[]> = {};\n\t\tentries.forEach((entry: any) => {\n\t\t\tif (entry.message) {\n\t\t\t\tconst convId = entry.message.conversation_id;\n\t\t\t\tif (!messagesByConversation[convId]) {\n\t\t\t\t\tmessagesByConversation[convId] = [];\n\t\t\t\t}\n\t\t\t\tmessagesByConversation[convId].push(entry.message);\n\t\t\t}\n\t\t});\n\n\t\t// Convert to DirectMessageConversation array\n\t\tconst parsedConversations = Object.entries(conversations).map(\n\t\t\t([convId, conv]: [string, any]) => {\n\t\t\t\tconst messages = messagesByConversation[convId] || [];\n\n\t\t\t\t// Sort messages by time in ascending order\n\t\t\t\tmessages.sort((a, b) => Number(a.time) - Number(b.time));\n\n\t\t\t\treturn {\n\t\t\t\t\tconversationId: convId,\n\t\t\t\t\tmessages: parseDirectMessages(messages, users),\n\t\t\t\t\tparticipants: conv.participants.map((p: any) => ({\n\t\t\t\t\t\tid: p.user_id,\n\t\t\t\t\t\tscreenName: users[p.user_id]?.screen_name || p.user_id,\n\t\t\t\t\t})),\n\t\t\t\t};\n\t\t\t},\n\t\t);\n\n\t\treturn {\n\t\t\tconversations: parsedConversations,\n\t\t\tusers: parsedUsers,\n\t\t\tcursor: inboxState?.cursor,\n\t\t\tlastSeenEventId: inboxState?.last_seen_event_id,\n\t\t\ttrustedLastSeenEventId: inboxState?.trusted_last_seen_event_id,\n\t\t\tuntrustedLastSeenEventId: inboxState?.untrusted_last_seen_event_id,\n\t\t\tinboxTimelines: {\n\t\t\t\ttrusted: inboxState?.inbox_timelines?.trusted && {\n\t\t\t\t\tstatus: inboxState.inbox_timelines.trusted.status,\n\t\t\t\t\tminEntryId: inboxState.inbox_timelines.trusted.min_entry_id,\n\t\t\t\t},\n\t\t\t\tuntrusted: inboxState?.inbox_timelines?.untrusted && {\n\t\t\t\t\tstatus: inboxState.inbox_timelines.untrusted.status,\n\t\t\t\t\tminEntryId: inboxState.inbox_timelines.untrusted.min_entry_id,\n\t\t\t\t},\n\t\t\t},\n\t\t\tuserId,\n\t\t};\n\t} catch (error) {\n\t\tconsole.error(\"Error parsing DM conversations:\", error);\n\t\treturn {\n\t\t\tconversations: [],\n\t\t\tusers: [],\n\t\t\tuserId,\n\t\t};\n\t}\n}\n\nfunction parseDirectMessages(messages: any[], users: any): DirectMessage[] {\n\ttry {\n\t\treturn messages.map((msg: any) => ({\n\t\t\tid: msg.message_data.id,\n\t\t\ttext: msg.message_data.text,\n\t\t\tsenderId: msg.message_data.sender_id,\n\t\t\trecipientId: msg.message_data.recipient_id,\n\t\t\tcreatedAt: msg.message_data.time,\n\t\t\tmediaUrls: extractMediaUrls(msg.message_data),\n\t\t\tsenderScreenName: users[msg.message_data.sender_id]?.screen_name,\n\t\t\trecipientScreenName: users[msg.message_data.recipient_id]?.screen_name,\n\t\t}));\n\t} catch (error) {\n\t\tconsole.error(\"Error parsing DMs:\", error);\n\t\treturn [];\n\t}\n}\n\nfunction extractMediaUrls(messageData: any): string[] | undefined {\n\tconst urls: string[] = [];\n\n\t// Extract URLs from entities if they exist\n\tif (messageData.entities?.urls) {\n\t\tmessageData.entities.urls.forEach((url: any) => {\n\t\t\turls.push(url.expanded_url);\n\t\t});\n\t}\n\n\t// Extract media URLs if they exist\n\tif (messageData.entities?.media) {\n\t\tmessageData.entities.media.forEach((media: any) => {\n\t\t\turls.push(media.media_url_https || media.media_url);\n\t\t});\n\t}\n\n\treturn urls.length > 0 ? urls : undefined;\n}\n\nexport async function getDirectMessageConversations(\n\tuserId: string,\n\tauth: TwitterAuth,\n\tcursor?: string,\n): Promise<DirectMessagesResponse> {\n\tif (!auth.isLoggedIn()) {\n\t\tthrow new Error(\"Authentication required to fetch direct messages\");\n\t}\n\n\tconst url =\n\t\t\"https://twitter.com/i/api/graphql/7s3kOODhC5vgXlO0OlqYdA/DMInboxTimeline\";\n\tconst messageListUrl = \"https://x.com/i/api/1.1/dm/inbox_initial_state.json\";\n\n\tconst params = new URLSearchParams();\n\n\tif (cursor) {\n\t\tparams.append(\"cursor\", cursor);\n\t}\n\n\tconst finalUrl = `${messageListUrl}${\n\t\tparams.toString() ? `?${params.toString()}` : \"\"\n\t}`;\n\tconst cookies = await auth.cookieJar().getCookies(url);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tauthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\tcookie: await auth.cookieJar().getCookieString(url),\n\t\t\"content-type\": \"application/json\",\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Linux; Android 11; Nokia G20) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.88 Mobile Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\tconst response = await fetch(finalUrl, {\n\t\tmethod: \"GET\",\n\t\theaders,\n\t});\n\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\tif (!response.ok) {\n\t\tthrow new Error(await response.text());\n\t}\n\n\t// parse the response\n\tconst data = await response.json();\n\treturn parseDirectMessageConversations(data, userId);\n}\n\nexport async function sendDirectMessage(\n\tauth: TwitterAuth,\n\tconversation_id: string,\n\ttext: string,\n): Promise<SendDirectMessageResponse> {\n\tif (!auth.isLoggedIn()) {\n\t\tthrow new Error(\"Authentication required to send direct messages\");\n\t}\n\n\tconst url =\n\t\t\"https://twitter.com/i/api/graphql/7s3kOODhC5vgXlO0OlqYdA/DMInboxTimeline\";\n\tconst messageDmUrl = \"https://x.com/i/api/1.1/dm/new2.json\";\n\n\tconst cookies = await auth.cookieJar().getCookies(url);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tauthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\tcookie: await auth.cookieJar().getCookieString(url),\n\t\t\"content-type\": \"application/json\",\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Linux; Android 11; Nokia G20) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.88 Mobile Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\tconst payload = {\n\t\tconversation_id: `${conversation_id}`,\n\t\trecipient_ids: false,\n\t\ttext: text,\n\t\tcards_platform: \"Web-12\",\n\t\tinclude_cards: 1,\n\t\tinclude_quote_count: true,\n\t\tdm_users: false,\n\t};\n\n\tconst response = await fetch(messageDmUrl, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(payload),\n\t});\n\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\tif (!response.ok) {\n\t\tthrow new Error(await response.text());\n\t}\n\n\treturn await response.json();\n}\n","import type { TwitterAuth } from \"./auth\";\nimport { updateCookieJar } from \"./requests\";\nimport type {\n\tAudioSpace,\n\tAudioSpaceByIdResponse,\n\tAudioSpaceByIdVariables,\n\tAuthenticatePeriscopeResponse,\n\tBrowseSpaceTopicsResponse,\n\tCommunity,\n\tCommunitySelectQueryResponse,\n\tLiveVideoStreamStatus,\n\tLoginTwitterTokenResponse,\n\tSubtopic,\n} from \"./types/spaces\";\n\n/**\n * Generates a random string that mimics a UUID v4.\n */\n// TODO: install and replace with uuidv4\nfunction generateRandomId(): string {\n\treturn \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n\t\tconst r = (Math.random() * 16) | 0;\n\t\tconst v = c === \"x\" ? r : (r & 0x3) | 0x8;\n\t\treturn v.toString(16);\n\t});\n}\n\n/**\n * Fetches details of an Audio Space by its ID.\n * @param variables The variables required for the GraphQL query.\n * @param auth The authentication object.\n * @returns The details of the Audio Space.\n */\nexport async function fetchAudioSpaceById(\n\tvariables: AudioSpaceByIdVariables,\n\tauth: TwitterAuth,\n): Promise<AudioSpace> {\n\tconst queryId = \"Tvv_cNXCbtTcgdy1vWYPMw\"; // Specific to the AudioSpaceById GraphQL query\n\tconst operationName = \"AudioSpaceById\";\n\n\t// URL encode the variables and features\n\tconst variablesEncoded = encodeURIComponent(JSON.stringify(variables));\n\tconst features = {\n\t\tspaces_2022_h2_spaces_communities: true,\n\t\tspaces_2022_h2_clipping: true,\n\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\tprofile_label_improvements_pcf_label_in_post_enabled: false,\n\t\trweb_tipjar_consumption_enabled: true,\n\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\tverified_phone_label_enabled: false,\n\t\tpremium_content_api_read_enabled: false,\n\t\tcommunities_web_enable_tweet_community_results_fetch: true,\n\t\tc9s_tweet_anatomy_moderator_badge_enabled: true,\n\t\tresponsive_web_grok_analyze_button_fetch_trends_enabled: true,\n\t\tarticles_preview_enabled: true,\n\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\tview_counts_everywhere_api_enabled: true,\n\t\tlongform_notetweets_consumption_enabled: true,\n\t\tresponsive_web_twitter_article_tweet_consumption_enabled: true,\n\t\ttweet_awards_web_tipping_enabled: false,\n\t\tcreator_subscriptions_quote_tweet_preview_enabled: false,\n\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\tstandardized_nudges_misinfo: true,\n\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,\n\t\trweb_video_timestamps_enabled: true,\n\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\tlongform_notetweets_inline_media_enabled: true,\n\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\tresponsive_web_enhance_cards_enabled: false,\n\t};\n\tconst featuresEncoded = encodeURIComponent(JSON.stringify(features));\n\n\tconst url = `https://x.com/i/api/graphql/${queryId}/${operationName}?variables=${variablesEncoded}&features=${featuresEncoded}`;\n\n\tconst onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n\t// Retrieve necessary cookies and tokens\n\tconst cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tAccept: \"*/*\",\n\t\tAuthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\t\"Content-Type\": \"application/json\",\n\t\tCookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\tconst response = await auth.fetch(url, {\n\t\theaders,\n\t\tmethod: \"GET\",\n\t});\n\n\t// Update the cookie jar with any new cookies from the response\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t// Check for errors in the response\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to fetch Audio Space: ${await response.text()}`);\n\t}\n\n\tconst data: AudioSpaceByIdResponse = await response.json();\n\n\tif (data.errors && data.errors.length > 0) {\n\t\tthrow new Error(`API Errors: ${JSON.stringify(data.errors)}`);\n\t}\n\n\treturn data.data.audioSpace;\n}\n\n/**\n * Fetches available space topics from Twitter.\n * @param auth The authentication object.\n * @returns An array of space topics.\n */\nexport async function fetchBrowseSpaceTopics(\n\tauth: TwitterAuth,\n): Promise<Subtopic[]> {\n\tconst queryId = \"TYpVV9QioZfViHqEqRZxJA\";\n\tconst operationName = \"BrowseSpaceTopics\";\n\n\tconst variables = {};\n\tconst features = {};\n\n\tconst variablesEncoded = encodeURIComponent(JSON.stringify(variables));\n\tconst featuresEncoded = encodeURIComponent(JSON.stringify(features));\n\n\tconst url = `https://x.com/i/api/graphql/${queryId}/${operationName}?variables=${variablesEncoded}&features=${featuresEncoded}`;\n\n\tconst onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n\t// Retrieve necessary cookies and tokens\n\tconst cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tAccept: \"*/*\",\n\t\tAuthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\t\"Content-Type\": \"application/json\",\n\t\tCookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\tconst response = await auth.fetch(url, {\n\t\theaders,\n\t\tmethod: \"GET\",\n\t});\n\n\t// Update the cookie jar with any new cookies from the response\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t// Check for errors in the response\n\tif (!response.ok) {\n\t\tthrow new Error(`Failed to fetch Space Topics: ${await response.text()}`);\n\t}\n\n\tconst data: BrowseSpaceTopicsResponse = await response.json();\n\n\tif (data.errors && data.errors.length > 0) {\n\t\tthrow new Error(`API Errors: ${JSON.stringify(data.errors)}`);\n\t}\n\n\t// Flatten the subtopics from all categories into a single array\n\treturn data.data.browse_space_topics.categories.flatMap(\n\t\t(category) => category.subtopics,\n\t);\n}\n\n/**\n * Fetches available communities from Twitter.\n * @param auth The authentication object.\n * @returns An array of communities.\n */\nexport async function fetchCommunitySelectQuery(\n\tauth: TwitterAuth,\n): Promise<Community[]> {\n\tconst queryId = \"Lue1DfmoW2cc0225t_8z1w\"; // Specific to the CommunitySelectQuery GraphQL query\n\tconst operationName = \"CommunitySelectQuery\";\n\n\tconst variables = {};\n\tconst features = {};\n\n\tconst variablesEncoded = encodeURIComponent(JSON.stringify(variables));\n\tconst featuresEncoded = encodeURIComponent(JSON.stringify(features));\n\n\tconst url = `https://x.com/i/api/graphql/${queryId}/${operationName}?variables=${variablesEncoded}&features=${featuresEncoded}`;\n\n\tconst onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n\t// Retrieve necessary cookies and tokens\n\tconst cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tAccept: \"*/*\",\n\t\tAuthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\t\"Content-Type\": \"application/json\",\n\t\tCookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\tconst response = await auth.fetch(url, {\n\t\theaders,\n\t\tmethod: \"GET\",\n\t});\n\n\t// Update the cookie jar with any new cookies from the response\n\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t// Check for errors in the response\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Failed to fetch Community Select Query: ${await response.text()}`,\n\t\t);\n\t}\n\n\tconst data: CommunitySelectQueryResponse = await response.json();\n\n\tif (data.errors && data.errors.length > 0) {\n\t\tthrow new Error(`API Errors: ${JSON.stringify(data.errors)}`);\n\t}\n\n\t// Return the space_hostable_communities array, which may be empty\n\treturn data.data.space_hostable_communities;\n}\n\n/**\n * Fetches the status of an Audio Space stream by its media key.\n * @param mediaKey The media key of the Audio Space.\n * @param auth The authentication object.\n * @returns The status of the Audio Space stream.\n */\nexport async function fetchLiveVideoStreamStatus(\n\tmediaKey: string,\n\tauth: TwitterAuth,\n): Promise<LiveVideoStreamStatus> {\n\tconst baseUrl = `https://x.com/i/api/1.1/live_video_stream/status/${mediaKey}`;\n\tconst queryParams = new URLSearchParams({\n\t\tclient: \"web\",\n\t\tuse_syndication_guest_id: \"false\",\n\t\tcookie_set_host: \"x.com\",\n\t});\n\n\tconst url = `${baseUrl}?${queryParams.toString()}`;\n\n\tconst onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n\t// Retrieve necessary cookies and tokens\n\tconst cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tconst headers = new Headers({\n\t\tAccept: \"*/*\",\n\t\tAuthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\t\"Content-Type\": \"application/json\",\n\t\tCookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Client\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken?.value as string,\n\t});\n\n\ttry {\n\t\tconst response = await auth.fetch(url, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: headers,\n\t\t});\n\n\t\t// Update the cookie jar with any new cookies from the response\n\t\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t\t// Check for errors in the response\n\t\tif (!response.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to fetch live video stream status: ${await response.text()}`,\n\t\t\t);\n\t\t}\n\n\t\treturn await response.json();\n\t} catch (error) {\n\t\tconsole.error(\n\t\t\t`Error fetching live video stream status for mediaKey ${mediaKey}:`,\n\t\t\terror,\n\t\t);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Authenticates Periscope to obtain a token.\n * @param auth The authentication object.\n * @returns The Periscope authentication token.\n */\nexport async function fetchAuthenticatePeriscope(\n\tauth: TwitterAuth,\n): Promise<string> {\n\tconst queryId = \"r7VUmxbfqNkx7uwjgONSNw\";\n\tconst operationName = \"AuthenticatePeriscope\";\n\n\tconst variables = {};\n\tconst features = {};\n\n\tconst variablesEncoded = encodeURIComponent(JSON.stringify(variables));\n\tconst featuresEncoded = encodeURIComponent(JSON.stringify(features));\n\n\tconst url = `https://x.com/i/api/graphql/${queryId}/${operationName}?variables=${variablesEncoded}&features=${featuresEncoded}`;\n\n\tconst onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n\tconst cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n\tconst xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n\tif (!xCsrfToken) {\n\t\tthrow new Error(\"CSRF Token (ct0) not found in cookies.\");\n\t}\n\n\tconst clientTransactionId = generateRandomId();\n\n\tconst headers = new Headers({\n\t\tAccept: \"*/*\",\n\t\tAuthorization: `Bearer ${(auth as any).bearerToken}`,\n\t\t\"Content-Type\": \"application/json\",\n\t\tCookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36\",\n\t\t\"x-guest-token\": (auth as any).guestToken,\n\t\t\"x-twitter-auth-type\": \"OAuth2Session\",\n\t\t\"x-twitter-active-user\": \"yes\",\n\t\t\"x-csrf-token\": xCsrfToken.value,\n\t\t\"x-client-transaction-id\": clientTransactionId,\n\t\t\"sec-ch-ua-platform\": '\"Windows\"',\n\t\t\"sec-ch-ua\":\n\t\t\t'\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"',\n\t\t\"x-twitter-client-language\": \"en\",\n\t\t\"sec-ch-ua-mobile\": \"?0\",\n\t\tReferer: \"https://x.com/i/spaces/start\",\n\t});\n\n\ttry {\n\t\tconst response = await auth.fetch(url, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders: headers,\n\t\t});\n\n\t\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t\tif (!response.ok) {\n\t\t\tconst errorText = await response.text();\n\t\t\tthrow new Error(`Error ${response.status}: ${errorText}`);\n\t\t}\n\n\t\tconst data: AuthenticatePeriscopeResponse = await response.json();\n\n\t\tif (data.errors && data.errors.length > 0) {\n\t\t\tthrow new Error(`API Errors: ${JSON.stringify(data.errors)}`);\n\t\t}\n\n\t\tif (!data.data.authenticate_periscope) {\n\t\t\tthrow new Error(\"Periscope authentication failed, no data returned.\");\n\t\t}\n\n\t\treturn data.data.authenticate_periscope;\n\t} catch (error) {\n\t\tconsole.error(\"Error during Periscope authentication:\", error);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Logs in to Twitter via Proxsee using the Periscope JWT to obtain a login cookie.\n * @param jwt The JWT obtained via AuthenticatePeriscope.\n * @param auth The authentication object.\n * @returns The response containing the cookie and user information.\n */\nexport async function fetchLoginTwitterToken(\n\tjwt: unknown,\n\tauth: TwitterAuth,\n): Promise<LoginTwitterTokenResponse> {\n\tconst url = \"https://proxsee.pscp.tv/api/v2/loginTwitterToken\";\n\n\tconst idempotenceKey = generateRandomId();\n\n\tconst payload = {\n\t\tjwt: jwt,\n\t\tvendor_id: \"m5-proxsee-login-a2011357b73e\",\n\t\tcreate_user: true,\n\t};\n\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"User-Agent\":\n\t\t\t\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36\",\n\t\tReferer: \"https://x.com/\",\n\t\t\"sec-ch-ua\":\n\t\t\t'\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"',\n\t\t\"sec-ch-ua-platform\": '\"Windows\"',\n\t\t\"sec-ch-ua-mobile\": \"?0\",\n\t\t\"X-Periscope-User-Agent\": \"Twitter/m5\",\n\t\t\"X-Idempotence\": idempotenceKey,\n\t\t\"X-Attempt\": \"1\",\n\t});\n\n\ttry {\n\t\tconst response = await auth.fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: headers,\n\t\t\tbody: JSON.stringify(payload),\n\t\t});\n\n\t\t// Update the cookie jar with any new cookies from the response\n\t\tawait updateCookieJar(auth.cookieJar(), response.headers);\n\n\t\t// Check if the response is successful\n\t\tif (!response.ok) {\n\t\t\tconst errorText = await response.text();\n\t\t\tthrow new Error(`Error ${response.status}: ${errorText}`);\n\t\t}\n\n\t\tconst data: LoginTwitterTokenResponse = await response.json();\n\n\t\tif (!data.cookie || !data.user) {\n\t\t\tthrow new Error(\"Twitter authentication failed, missing data.\");\n\t\t}\n\n\t\treturn data;\n\t} catch (error) {\n\t\tconsole.error(\"Error logging into Twitter via Proxsee:\", error);\n\t\tthrow error;\n\t}\n}\n","import { requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\n\nexport interface GrokConversation {\n\tdata: {\n\t\tcreate_grok_conversation: {\n\t\t\tconversation_id: string;\n\t\t};\n\t};\n}\n\nexport interface GrokRequest {\n\tresponses: GrokResponseMessage[];\n\tsystemPromptName: string;\n\tgrokModelOptionId: string;\n\tconversationId: string;\n\treturnSearchResults: boolean;\n\treturnCitations: boolean;\n\tpromptMetadata: {\n\t\tpromptSource: string;\n\t\taction: string;\n\t};\n\timageGenerationCount: number;\n\trequestFeatures: {\n\t\teagerTweets: boolean;\n\t\tserverHistory: boolean;\n\t};\n}\n\n// Types for the user-facing API\nexport interface GrokMessage {\n\trole: \"user\" | \"assistant\";\n\tcontent: string;\n}\n\nexport interface GrokChatOptions {\n\tmessages: GrokMessage[];\n\tconversationId?: string; // Optional - will create new if not provided\n\treturnSearchResults?: boolean;\n\treturnCitations?: boolean;\n}\n\n// Internal types for API requests\nexport interface GrokResponseMessage {\n\tmessage: string;\n\tsender: 1 | 2; // 1 = user, 2 = assistant\n\tpromptSource?: string;\n\tfileAttachments?: any[];\n}\n\n// Rate limit information\nexport interface GrokRateLimit {\n\tisRateLimited: boolean;\n\tmessage: string;\n\tupsellInfo?: {\n\t\tusageLimit: string;\n\t\tquotaDuration: string;\n\t\ttitle: string;\n\t\tmessage: string;\n\t};\n}\n\nexport interface GrokChatResponse {\n\tconversationId: string;\n\tmessage: string;\n\tmessages: GrokMessage[];\n\twebResults?: any[];\n\tmetadata?: any;\n\trateLimit?: GrokRateLimit;\n}\n\n/**\n * Creates a new conversation with Grok.\n * @returns The ID of the newly created conversation\n * @internal\n */\nexport async function createGrokConversation(\n\tauth: TwitterAuth,\n): Promise<string> {\n\tconst res = await requestApi<GrokConversation>(\n\t\t\"https://x.com/i/api/graphql/6cmfJY3d7EPWuCSXWrkOFg/CreateGrokConversation\",\n\t\tauth,\n\t\t\"POST\",\n\t);\n\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\treturn res.value.data.create_grok_conversation.conversation_id;\n}\n\n/**\n * Main method for interacting with Grok in a chat-like manner.\n */\nexport async function grokChat(\n\toptions: GrokChatOptions,\n\tauth: TwitterAuth,\n): Promise<GrokChatResponse> {\n\tlet { conversationId, messages } = options;\n\n\t// Create new conversation if none provided\n\tif (!conversationId) {\n\t\tconversationId = await createGrokConversation(auth);\n\t}\n\n\t// Convert OpenAI-style messages to Grok's internal format\n\tconst responses: GrokResponseMessage[] = messages.map((msg: GrokMessage) => ({\n\t\tmessage: msg.content,\n\t\tsender: msg.role === \"user\" ? 1 : 2,\n\t\t...(msg.role === \"user\" && {\n\t\t\tpromptSource: \"\",\n\t\t\tfileAttachments: [],\n\t\t}),\n\t}));\n\n\tconst payload: GrokRequest = {\n\t\tresponses,\n\t\tsystemPromptName: \"\",\n\t\tgrokModelOptionId: \"grok-2a\",\n\t\tconversationId,\n\t\treturnSearchResults: options.returnSearchResults ?? true,\n\t\treturnCitations: options.returnCitations ?? true,\n\t\tpromptMetadata: {\n\t\t\tpromptSource: \"NATURAL\",\n\t\t\taction: \"INPUT\",\n\t\t},\n\t\timageGenerationCount: 4,\n\t\trequestFeatures: {\n\t\t\teagerTweets: true,\n\t\t\tserverHistory: true,\n\t\t},\n\t};\n\n\tconst res = await requestApi<{ text: string }>(\n\t\t\"https://api.x.com/2/grok/add_response.json\",\n\t\tauth,\n\t\t\"POST\",\n\t\tundefined,\n\t\tpayload,\n\t);\n\n\tif (!res.success) {\n\t\tthrow (res as any).err;\n\t}\n\n\t// Parse response chunks - Grok may return either a single response or multiple chunks\n\tlet chunks: any[];\n\tif (res.value.text) {\n\t\t// For streaming responses, split text into chunks and parse each JSON chunk\n\t\tchunks = res.value.text\n\t\t\t.split(\"\\n\")\n\t\t\t.filter(Boolean)\n\t\t\t.map((chunk: any) => JSON.parse(chunk));\n\t} else {\n\t\t// For single responses (like rate limiting), wrap in array\n\t\tchunks = [res.value];\n\t}\n\n\t// Check if we hit rate limits by examining first chunk\n\tconst firstChunk = chunks[0];\n\tif (firstChunk.result?.responseType === \"limiter\") {\n\t\treturn {\n\t\t\tconversationId,\n\t\t\tmessage: firstChunk.result.message,\n\t\t\tmessages: [\n\t\t\t\t...messages,\n\t\t\t\t{ role: \"assistant\", content: firstChunk.result.message },\n\t\t\t],\n\t\t\trateLimit: {\n\t\t\t\tisRateLimited: true,\n\t\t\t\tmessage: firstChunk.result.message,\n\t\t\t\tupsellInfo: firstChunk.result.upsell\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tusageLimit: firstChunk.result.upsell.usageLimit,\n\t\t\t\t\t\t\tquotaDuration: `${firstChunk.result.upsell.quotaDurationCount} ${firstChunk.result.upsell.quotaDurationPeriod}`,\n\t\t\t\t\t\t\ttitle: firstChunk.result.upsell.title,\n\t\t\t\t\t\t\tmessage: firstChunk.result.upsell.message,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t},\n\t\t};\n\t}\n\n\t// Combine all message chunks into single response\n\tconst fullMessage = chunks\n\t\t.filter((chunk: any) => chunk.result?.message)\n\t\t.map((chunk: any) => chunk.result.message)\n\t\t.join(\"\");\n\n\t// Return complete response with conversation history and metadata\n\treturn {\n\t\tconversationId,\n\t\tmessage: fullMessage,\n\t\tmessages: [...messages, { role: \"assistant\", content: fullMessage }],\n\t\twebResults: chunks.find((chunk: any) => chunk.result?.webResults)?.result\n\t\t\t.webResults,\n\t\tmetadata: chunks[0],\n\t};\n}\n","import type { Cookie } from \"tough-cookie\";\nimport {\n\tbearerToken,\n\ttype FetchTransformOptions,\n\trequestApi,\n\ttype RequestApiResult,\n} from \"./api\";\nimport {\n\ttype TwitterAuth,\n\ttype TwitterAuthOptions,\n\tTwitterGuestAuth,\n} from \"./auth\";\nimport { TwitterUserAuth } from \"./auth-user\";\nimport {\n\tgetProfile,\n\tgetUserIdByScreenName,\n\tgetScreenNameByUserId,\n\ttype Profile,\n} from \"./profile\";\nimport {\n\tfetchQuotedTweetsPage,\n\tfetchSearchProfiles,\n\tfetchSearchTweets,\n\tSearchMode,\n\tsearchProfiles,\n\tsearchQuotedTweets,\n\tsearchTweets,\n} from \"./search\";\nimport {\n\tfetchProfileFollowing,\n\tfetchProfileFollowers,\n\tgetFollowing,\n\tgetFollowers,\n\tfollowUser,\n} from \"./relationships\";\nimport type { QueryProfilesResponse, QueryTweetsResponse } from \"./timeline-v1\";\nimport { getTrends } from \"./trends\";\nimport {\n\ttype Tweet,\n\tgetTweetAnonymous,\n\tgetTweets,\n\tgetLatestTweet,\n\tgetTweetWhere,\n\tgetTweetsWhere,\n\tgetTweetsByUserId,\n\ttype TweetQuery,\n\tgetTweet,\n\tfetchListTweets,\n\tgetTweetsAndRepliesByUserId,\n\tgetTweetsAndReplies,\n\tcreateCreateTweetRequest,\n\ttype PollData,\n\tcreateCreateTweetRequestV2,\n\tgetTweetV2,\n\tgetTweetsV2,\n\tdefaultOptions,\n\tcreateQuoteTweetRequest,\n\tlikeTweet,\n\tretweet,\n\tcreateCreateNoteTweetRequest,\n\tcreateCreateLongTweetRequest,\n\tgetArticle,\n\tgetAllRetweeters,\n\ttype Retweeter,\n} from \"./tweets\";\nimport {\n\tparseTimelineTweetsV2,\n\ttype TimelineArticle,\n\ttype TimelineV2,\n} from \"./timeline-v2\";\nimport { fetchHomeTimeline } from \"./timeline-home\";\nimport { fetchFollowingTimeline } from \"./timeline-following\";\nimport type {\n\tTTweetv2Expansion,\n\tTTweetv2MediaField,\n\tTTweetv2PlaceField,\n\tTTweetv2PollField,\n\tTTweetv2TweetField,\n\tTTweetv2UserField,\n} from \"twitter-api-v2\";\nimport {\n\ttype DirectMessagesResponse,\n\tgetDirectMessageConversations,\n\tsendDirectMessage,\n\ttype SendDirectMessageResponse,\n} from \"./messages\";\nimport {\n\tfetchAudioSpaceById,\n\tfetchAuthenticatePeriscope,\n\tfetchBrowseSpaceTopics,\n\tfetchCommunitySelectQuery,\n\tfetchLiveVideoStreamStatus,\n\tfetchLoginTwitterToken,\n} from \"./spaces\";\nimport type {\n\tAudioSpace,\n\tCommunity,\n\tLiveVideoStreamStatus,\n\tLoginTwitterTokenResponse,\n\tSubtopic,\n} from \"./types/spaces\";\nimport {\n\tcreateGrokConversation,\n\tgrokChat,\n\ttype GrokChatOptions,\n\ttype GrokChatResponse,\n} from \"./grok\";\n\nconst twUrl = \"https://twitter.com\";\nconst UserTweetsUrl =\n\t\"https://twitter.com/i/api/graphql/E3opETHurmVJflFsUBVuUQ/UserTweets\";\n\nexport interface ClientOptions {\n\t/**\n\t * An alternative fetch function to use instead of the default fetch function. This may be useful\n\t * in nonstandard runtime environments, such as edge workers.\n\t */\n\tfetch: typeof fetch;\n\n\t/**\n\t * Additional options that control how requests and responses are processed. This can be used to\n\t * proxy requests through other hosts, for example.\n\t */\n\ttransform: Partial<FetchTransformOptions>;\n}\n\n/**\n * An interface to Twitter's undocumented API.\n * - Reusing Client objects is recommended to minimize the time spent authenticating unnecessarily.\n */\nexport class Client {\n\tprivate auth!: TwitterAuth;\n\tprivate authTrends!: TwitterAuth;\n\tprivate token: string;\n\n\t/**\n\t * Creates a new Client object.\n\t * - Clients maintain their own guest tokens for Twitter's internal API.\n\t * - Reusing Client objects is recommended to minimize the time spent authenticating unnecessarily.\n\t */\n\tconstructor(private readonly options?: Partial<ClientOptions>) {\n\t\tthis.token = bearerToken;\n\t\tthis.useGuestAuth();\n\t}\n\n\t/**\n\t * Initializes auth properties using a guest token.\n\t * Used when creating a new instance of this class, and when logging out.\n\t * @internal\n\t */\n\tprivate useGuestAuth() {\n\t\tthis.auth = new TwitterGuestAuth(this.token, this.getAuthOptions());\n\t\tthis.authTrends = new TwitterGuestAuth(this.token, this.getAuthOptions());\n\t}\n\n\t/**\n\t * Fetches a Twitter profile.\n\t * @param username The Twitter username of the profile to fetch, without an `@` at the beginning.\n\t * @returns The requested {@link Profile}.\n\t */\n\tpublic async getProfile(username: string): Promise<Profile> {\n\t\tconst res = await getProfile(username, this.auth);\n\t\treturn this.handleResponse(res);\n\t}\n\n\t/**\n\t * Fetches the user ID corresponding to the provided screen name.\n\t * @param screenName The Twitter screen name of the profile to fetch.\n\t * @returns The ID of the corresponding account.\n\t */\n\tpublic async getUserIdByScreenName(screenName: string): Promise<string> {\n\t\tconst res = await getUserIdByScreenName(screenName, this.auth);\n\t\treturn this.handleResponse(res);\n\t}\n\n\t/**\n\t *\n\t * @param userId The user ID of the profile to fetch.\n\t * @returns The screen name of the corresponding account.\n\t */\n\tpublic async getScreenNameByUserId(userId: string): Promise<string> {\n\t\tconst response = await getScreenNameByUserId(userId, this.auth);\n\t\treturn this.handleResponse(response);\n\t}\n\n\t/**\n\t * Fetches tweets from Twitter.\n\t * @param query The search query. Any Twitter-compatible query format can be used.\n\t * @param maxTweets The maximum number of tweets to return.\n\t * @param includeReplies Whether or not replies should be included in the response.\n\t * @param searchMode The category filter to apply to the search. Defaults to `Top`.\n\t * @returns An {@link AsyncGenerator} of tweets matching the provided filters.\n\t */\n\tpublic searchTweets(\n\t\tquery: string,\n\t\tmaxTweets: number,\n\t\tsearchMode: SearchMode = SearchMode.Top,\n\t): AsyncGenerator<Tweet, void> {\n\t\treturn searchTweets(query, maxTweets, searchMode, this.auth);\n\t}\n\n\t/**\n\t * Fetches profiles from Twitter.\n\t * @param query The search query. Any Twitter-compatible query format can be used.\n\t * @param maxProfiles The maximum number of profiles to return.\n\t * @returns An {@link AsyncGenerator} of tweets matching the provided filter(s).\n\t */\n\tpublic searchProfiles(\n\t\tquery: string,\n\t\tmaxProfiles: number,\n\t): AsyncGenerator<Profile, void> {\n\t\treturn searchProfiles(query, maxProfiles, this.auth);\n\t}\n\n\t/**\n\t * Fetches tweets from Twitter.\n\t * @param query The search query. Any Twitter-compatible query format can be used.\n\t * @param maxTweets The maximum number of tweets to return.\n\t * @param includeReplies Whether or not replies should be included in the response.\n\t * @param searchMode The category filter to apply to the search. Defaults to `Top`.\n\t * @param cursor The search cursor, which can be passed into further requests for more results.\n\t * @returns A page of results, containing a cursor that can be used in further requests.\n\t */\n\tpublic fetchSearchTweets(\n\t\tquery: string,\n\t\tmaxTweets: number,\n\t\tsearchMode: SearchMode,\n\t\tcursor?: string,\n\t): Promise<QueryTweetsResponse> {\n\t\treturn fetchSearchTweets(query, maxTweets, searchMode, this.auth, cursor);\n\t}\n\n\t/**\n\t * Fetches profiles from Twitter.\n\t * @param query The search query. Any Twitter-compatible query format can be used.\n\t * @param maxProfiles The maximum number of profiles to return.\n\t * @param cursor The search cursor, which can be passed into further requests for more results.\n\t * @returns A page of results, containing a cursor that can be used in further requests.\n\t */\n\tpublic fetchSearchProfiles(\n\t\tquery: string,\n\t\tmaxProfiles: number,\n\t\tcursor?: string,\n\t): Promise<QueryProfilesResponse> {\n\t\treturn fetchSearchProfiles(query, maxProfiles, this.auth, cursor);\n\t}\n\n\t/**\n\t * Fetches list tweets from Twitter.\n\t * @param listId The list id\n\t * @param maxTweets The maximum number of tweets to return.\n\t * @param cursor The search cursor, which can be passed into further requests for more results.\n\t * @returns A page of results, containing a cursor that can be used in further requests.\n\t */\n\tpublic fetchListTweets(\n\t\tlistId: string,\n\t\tmaxTweets: number,\n\t\tcursor?: string,\n\t): Promise<QueryTweetsResponse> {\n\t\treturn fetchListTweets(listId, maxTweets, cursor, this.auth);\n\t}\n\n\t/**\n\t * Fetch the profiles a user is following\n\t * @param userId The user whose following should be returned\n\t * @param maxProfiles The maximum number of profiles to return.\n\t * @returns An {@link AsyncGenerator} of following profiles for the provided user.\n\t */\n\tpublic getFollowing(\n\t\tuserId: string,\n\t\tmaxProfiles: number,\n\t): AsyncGenerator<Profile, void> {\n\t\treturn getFollowing(userId, maxProfiles, this.auth);\n\t}\n\n\t/**\n\t * Fetch the profiles that follow a user\n\t * @param userId The user whose followers should be returned\n\t * @param maxProfiles The maximum number of profiles to return.\n\t * @returns An {@link AsyncGenerator} of profiles following the provided user.\n\t */\n\tpublic getFollowers(\n\t\tuserId: string,\n\t\tmaxProfiles: number,\n\t): AsyncGenerator<Profile, void> {\n\t\treturn getFollowers(userId, maxProfiles, this.auth);\n\t}\n\n\t/**\n\t * Fetches following profiles from Twitter.\n\t * @param userId The user whose following should be returned\n\t * @param maxProfiles The maximum number of profiles to return.\n\t * @param cursor The search cursor, which can be passed into further requests for more results.\n\t * @returns A page of results, containing a cursor that can be used in further requests.\n\t */\n\tpublic fetchProfileFollowing(\n\t\tuserId: string,\n\t\tmaxProfiles: number,\n\t\tcursor?: string,\n\t): Promise<QueryProfilesResponse> {\n\t\treturn fetchProfileFollowing(userId, maxProfiles, this.auth, cursor);\n\t}\n\n\t/**\n\t * Fetches profile followers from Twitter.\n\t * @param userId The user whose following should be returned\n\t * @param maxProfiles The maximum number of profiles to return.\n\t * @param cursor The search cursor, which can be passed into further requests for more results.\n\t * @returns A page of results, containing a cursor that can be used in further requests.\n\t */\n\tpublic fetchProfileFollowers(\n\t\tuserId: string,\n\t\tmaxProfiles: number,\n\t\tcursor?: string,\n\t): Promise<QueryProfilesResponse> {\n\t\treturn fetchProfileFollowers(userId, maxProfiles, this.auth, cursor);\n\t}\n\n\t/**\n\t * Fetches the home timeline for the current user. (for you feed)\n\t * @param count The number of tweets to fetch.\n\t * @param seenTweetIds An array of tweet IDs that have already been seen.\n\t * @returns A promise that resolves to the home timeline response.\n\t */\n\tpublic async fetchHomeTimeline(\n\t\tcount: number,\n\t\tseenTweetIds: string[],\n\t): Promise<any[]> {\n\t\treturn await fetchHomeTimeline(count, seenTweetIds, this.auth);\n\t}\n\n\t/**\n\t * Fetches the home timeline for the current user. (following feed)\n\t * @param count The number of tweets to fetch.\n\t * @param seenTweetIds An array of tweet IDs that have already been seen.\n\t * @returns A promise that resolves to the home timeline response.\n\t */\n\tpublic async fetchFollowingTimeline(\n\t\tcount: number,\n\t\tseenTweetIds: string[],\n\t): Promise<any[]> {\n\t\treturn await fetchFollowingTimeline(count, seenTweetIds, this.auth);\n\t}\n\n\tasync getUserTweets(\n\t\tuserId: string,\n\t\tmaxTweets = 200,\n\t\tcursor?: string,\n\t): Promise<{ tweets: Tweet[]; next?: string }> {\n\t\tif (maxTweets > 200) {\n\t\t\tmaxTweets = 200;\n\t\t}\n\n\t\tconst variables: Record<string, any> = {\n\t\t\tuserId,\n\t\t\tcount: maxTweets,\n\t\t\tincludePromotedContent: true,\n\t\t\twithQuickPromoteEligibilityTweetFields: true,\n\t\t\twithVoice: true,\n\t\t\twithV2Timeline: true,\n\t\t};\n\n\t\tif (cursor) {\n\t\t\tvariables.cursor = cursor;\n\t\t}\n\n\t\tconst features = {\n\t\t\trweb_tipjar_consumption_enabled: true,\n\t\t\tresponsive_web_graphql_exclude_directive_enabled: true,\n\t\t\tverified_phone_label_enabled: false,\n\t\t\tcreator_subscriptions_tweet_preview_api_enabled: true,\n\t\t\tresponsive_web_graphql_timeline_navigation_enabled: true,\n\t\t\tresponsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n\t\t\tcommunities_web_enable_tweet_community_results_fetch: true,\n\t\t\tc9s_tweet_anatomy_moderator_badge_enabled: true,\n\t\t\tarticles_preview_enabled: true,\n\t\t\tresponsive_web_edit_tweet_api_enabled: true,\n\t\t\tgraphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n\t\t\tview_counts_everywhere_api_enabled: true,\n\t\t\tlongform_notetweets_consumption_enabled: true,\n\t\t\tresponsive_web_twitter_article_tweet_consumption_enabled: true,\n\t\t\ttweet_awards_web_tipping_enabled: false,\n\t\t\tcreator_subscriptions_quote_tweet_preview_enabled: false,\n\t\t\tfreedom_of_speech_not_reach_fetch_enabled: true,\n\t\t\tstandardized_nudges_misinfo: true,\n\t\t\ttweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,\n\t\t\trweb_video_timestamps_enabled: true,\n\t\t\tlongform_notetweets_rich_text_read_enabled: true,\n\t\t\tlongform_notetweets_inline_media_enabled: true,\n\t\t\tresponsive_web_enhance_cards_enabled: false,\n\t\t};\n\n\t\tconst fieldToggles = {\n\t\t\twithArticlePlainText: false,\n\t\t};\n\n\t\tconst res = await requestApi<TimelineV2>(\n\t\t\t`${UserTweetsUrl}?variables=${encodeURIComponent(\n\t\t\t\tJSON.stringify(variables),\n\t\t\t)}&features=${encodeURIComponent(\n\t\t\t\tJSON.stringify(features),\n\t\t\t)}&fieldToggles=${encodeURIComponent(JSON.stringify(fieldToggles))}`,\n\t\t\tthis.auth,\n\t\t);\n\n\t\tif (!res.success) {\n\t\t\tthrow (res as any).err;\n\t\t}\n\n\t\tconst timelineV2 = parseTimelineTweetsV2(res.value);\n\t\treturn {\n\t\t\ttweets: timelineV2.tweets,\n\t\t\tnext: timelineV2.next,\n\t\t};\n\t}\n\n\tasync *getUserTweetsIterator(\n\t\tuserId: string,\n\t\tmaxTweets = 200,\n\t): AsyncGenerator<Tweet, void> {\n\t\tlet cursor: string | undefined;\n\t\tlet retrievedTweets = 0;\n\n\t\twhile (retrievedTweets < maxTweets) {\n\t\t\tconst response = await this.getUserTweets(\n\t\t\t\tuserId,\n\t\t\t\tmaxTweets - retrievedTweets,\n\t\t\t\tcursor,\n\t\t\t);\n\n\t\t\tfor (const tweet of response.tweets) {\n\t\t\t\tyield tweet;\n\t\t\t\tretrievedTweets++;\n\t\t\t\tif (retrievedTweets >= maxTweets) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcursor = response.next;\n\n\t\t\tif (!cursor) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Fetches the current trends from Twitter.\n\t * @returns The current list of trends.\n\t */\n\tpublic getTrends(): Promise<string[]> {\n\t\treturn getTrends(this.authTrends);\n\t}\n\n\t/**\n\t * Fetches tweets from a Twitter user.\n\t * @param user The user whose tweets should be returned.\n\t * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n\t * @returns An {@link AsyncGenerator} of tweets from the provided user.\n\t */\n\tpublic getTweets(user: string, maxTweets = 200): AsyncGenerator<Tweet> {\n\t\treturn getTweets(user, maxTweets, this.auth);\n\t}\n\n\t/**\n\t * Fetches tweets from a Twitter user using their ID.\n\t * @param userId The user whose tweets should be returned.\n\t * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n\t * @returns An {@link AsyncGenerator} of tweets from the provided user.\n\t */\n\tpublic getTweetsByUserId(\n\t\tuserId: string,\n\t\tmaxTweets = 200,\n\t): AsyncGenerator<Tweet, void> {\n\t\treturn getTweetsByUserId(userId, maxTweets, this.auth);\n\t}\n\n\t/**\n\t * Send a tweet\n\t * @param text The text of the tweet\n\t * @param tweetId The id of the tweet to reply to\n\t * @param mediaData Optional media data\n\t * @returns\n\t */\n\n\tasync sendTweet(\n\t\ttext: string,\n\t\treplyToTweetId?: string,\n\t\tmediaData?: { data: Buffer; mediaType: string }[],\n\t\thideLinkPreview?: boolean,\n\t) {\n\t\treturn await createCreateTweetRequest(\n\t\t\ttext,\n\t\t\tthis.auth,\n\t\t\treplyToTweetId,\n\t\t\tmediaData,\n\t\t\thideLinkPreview,\n\t\t);\n\t}\n\n\tasync sendNoteTweet(\n\t\ttext: string,\n\t\treplyToTweetId?: string,\n\t\tmediaData?: { data: Buffer; mediaType: string }[],\n\t) {\n\t\treturn await createCreateNoteTweetRequest(\n\t\t\ttext,\n\t\t\tthis.auth,\n\t\t\treplyToTweetId,\n\t\t\tmediaData,\n\t\t);\n\t}\n\n\t/**\n\t * Send a long tweet (Note Tweet)\n\t * @param text The text of the tweet\n\t * @param tweetId The id of the tweet to reply to\n\t * @param mediaData Optional media data\n\t * @returns\n\t */\n\tasync sendLongTweet(\n\t\ttext: string,\n\t\treplyToTweetId?: string,\n\t\tmediaData?: { data: Buffer; mediaType: string }[],\n\t) {\n\t\treturn await createCreateLongTweetRequest(\n\t\t\ttext,\n\t\t\tthis.auth,\n\t\t\treplyToTweetId,\n\t\t\tmediaData,\n\t\t);\n\t}\n\n\t/**\n\t * Send a tweet\n\t * @param text The text of the tweet\n\t * @param tweetId The id of the tweet to reply to\n\t * @param options The options for the tweet\n\t * @returns\n\t */\n\n\tasync sendTweetV2(\n\t\ttext: string,\n\t\treplyToTweetId?: string,\n\t\toptions?: {\n\t\t\tpoll?: PollData;\n\t\t},\n\t) {\n\t\treturn await createCreateTweetRequestV2(\n\t\t\ttext,\n\t\t\tthis.auth,\n\t\t\treplyToTweetId,\n\t\t\toptions,\n\t\t);\n\t}\n\n\t/**\n\t * Fetches tweets and replies from a Twitter user.\n\t * @param user The user whose tweets should be returned.\n\t * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n\t * @returns An {@link AsyncGenerator} of tweets from the provided user.\n\t */\n\tpublic getTweetsAndReplies(\n\t\tuser: string,\n\t\tmaxTweets = 200,\n\t): AsyncGenerator<Tweet> {\n\t\treturn getTweetsAndReplies(user, maxTweets, this.auth);\n\t}\n\n\t/**\n\t * Fetches tweets and replies from a Twitter user using their ID.\n\t * @param userId The user whose tweets should be returned.\n\t * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n\t * @returns An {@link AsyncGenerator} of tweets from the provided user.\n\t */\n\tpublic getTweetsAndRepliesByUserId(\n\t\tuserId: string,\n\t\tmaxTweets = 200,\n\t): AsyncGenerator<Tweet, void> {\n\t\treturn getTweetsAndRepliesByUserId(userId, maxTweets, this.auth);\n\t}\n\n\t/**\n\t * Fetches the first tweet matching the given query.\n\t *\n\t * Example:\n\t * ```js\n\t * const timeline = client.getTweets('user', 200);\n\t * const retweet = await client.getTweetWhere(timeline, { isRetweet: true });\n\t * ```\n\t * @param tweets The {@link AsyncIterable} of tweets to search through.\n\t * @param query A query to test **all** tweets against. This may be either an\n\t * object of key/value pairs or a predicate. If this query is an object, all\n\t * key/value pairs must match a {@link Tweet} for it to be returned. If this query\n\t * is a predicate, it must resolve to `true` for a {@link Tweet} to be returned.\n\t * - All keys are optional.\n\t * - If specified, the key must be implemented by that of {@link Tweet}.\n\t */\n\tpublic getTweetWhere(\n\t\ttweets: AsyncIterable<Tweet>,\n\t\tquery: TweetQuery,\n\t): Promise<Tweet | null> {\n\t\treturn getTweetWhere(tweets, query);\n\t}\n\n\t/**\n\t * Fetches all tweets matching the given query.\n\t *\n\t * Example:\n\t * ```js\n\t * const timeline = client.getTweets('user', 200);\n\t * const retweets = await client.getTweetsWhere(timeline, { isRetweet: true });\n\t * ```\n\t * @param tweets The {@link AsyncIterable} of tweets to search through.\n\t * @param query A query to test **all** tweets against. This may be either an\n\t * object of key/value pairs or a predicate. If this query is an object, all\n\t * key/value pairs must match a {@link Tweet} for it to be returned. If this query\n\t * is a predicate, it must resolve to `true` for a {@link Tweet} to be returned.\n\t * - All keys are optional.\n\t * - If specified, the key must be implemented by that of {@link Tweet}.\n\t */\n\tpublic getTweetsWhere(\n\t\ttweets: AsyncIterable<Tweet>,\n\t\tquery: TweetQuery,\n\t): Promise<Tweet[]> {\n\t\treturn getTweetsWhere(tweets, query);\n\t}\n\n\t/**\n\t * Fetches the most recent tweet from a Twitter user.\n\t * @param user The user whose latest tweet should be returned.\n\t * @param includeRetweets Whether or not to include retweets. Defaults to `false`.\n\t * @returns The {@link Tweet} object or `null`/`undefined` if it couldn't be fetched.\n\t */\n\tpublic getLatestTweet(\n\t\tuser: string,\n\t\tincludeRetweets = false,\n\t\tmax = 200,\n\t): Promise<Tweet | null | undefined> {\n\t\treturn getLatestTweet(user, includeRetweets, max, this.auth);\n\t}\n\n\t/**\n\t * Fetches a single tweet.\n\t * @param id The ID of the tweet to fetch.\n\t * @returns The {@link Tweet} object, or `null` if it couldn't be fetched.\n\t */\n\tpublic getTweet(id: string): Promise<Tweet | null> {\n\t\tif (this.auth instanceof TwitterUserAuth) {\n\t\t\treturn getTweet(id, this.auth);\n\t\t}\n\t\treturn getTweetAnonymous(id, this.auth);\n\t}\n\n\t/**\n\t * Fetches a single tweet by ID using the Twitter API v2.\n\t * Allows specifying optional expansions and fields for more detailed data.\n\t *\n\t * @param {string} id - The ID of the tweet to fetch.\n\t * @param {Object} [options] - Optional parameters to customize the tweet data.\n\t * @param {string[]} [options.expansions] - Array of expansions to include, e.g., 'attachments.poll_ids'.\n\t * @param {string[]} [options.tweetFields] - Array of tweet fields to include, e.g., 'created_at', 'public_metrics'.\n\t * @param {string[]} [options.pollFields] - Array of poll fields to include, if the tweet has a poll, e.g., 'options', 'end_datetime'.\n\t * @param {string[]} [options.mediaFields] - Array of media fields to include, if the tweet includes media, e.g., 'url', 'preview_image_url'.\n\t * @param {string[]} [options.userFields] - Array of user fields to include, if user information is requested, e.g., 'username', 'verified'.\n\t * @param {string[]} [options.placeFields] - Array of place fields to include, if the tweet includes location data, e.g., 'full_name', 'country'.\n\t * @returns {Promise<TweetV2 | null>} - The tweet data, including requested expansions and fields.\n\t */\n\tasync getTweetV2(\n\t\tid: string,\n\t\toptions: {\n\t\t\texpansions?: TTweetv2Expansion[];\n\t\t\ttweetFields?: TTweetv2TweetField[];\n\t\t\tpollFields?: TTweetv2PollField[];\n\t\t\tmediaFields?: TTweetv2MediaField[];\n\t\t\tuserFields?: TTweetv2UserField[];\n\t\t\tplaceFields?: TTweetv2PlaceField[];\n\t\t} = defaultOptions,\n\t): Promise<Tweet | null> {\n\t\treturn await getTweetV2(id, this.auth, options);\n\t}\n\n\t/**\n\t * Fetches multiple tweets by IDs using the Twitter API v2.\n\t * Allows specifying optional expansions and fields for more detailed data.\n\t *\n\t * @param {string[]} ids - Array of tweet IDs to fetch.\n\t * @param {Object} [options] - Optional parameters to customize the tweet data.\n\t * @param {string[]} [options.expansions] - Array of expansions to include, e.g., 'attachments.poll_ids'.\n\t * @param {string[]} [options.tweetFields] - Array of tweet fields to include, e.g., 'created_at', 'public_metrics'.\n\t * @param {string[]} [options.pollFields] - Array of poll fields to include, if tweets contain polls, e.g., 'options', 'end_datetime'.\n\t * @param {string[]} [options.mediaFields] - Array of media fields to include, if tweets contain media, e.g., 'url', 'preview_image_url'.\n\t * @param {string[]} [options.userFields] - Array of user fields to include, if user information is requested, e.g., 'username', 'verified'.\n\t * @param {string[]} [options.placeFields] - Array of place fields to include, if tweets contain location data, e.g., 'full_name', 'country'.\n\t * @returns {Promise<TweetV2[]> } - Array of tweet data, including requested expansions and fields.\n\t */\n\tasync getTweetsV2(\n\t\tids: string[],\n\t\toptions: {\n\t\t\texpansions?: TTweetv2Expansion[];\n\t\t\ttweetFields?: TTweetv2TweetField[];\n\t\t\tpollFields?: TTweetv2PollField[];\n\t\t\tmediaFields?: TTweetv2MediaField[];\n\t\t\tuserFields?: TTweetv2UserField[];\n\t\t\tplaceFields?: TTweetv2PlaceField[];\n\t\t} = defaultOptions,\n\t): Promise<Tweet[]> {\n\t\treturn await getTweetsV2(ids, this.auth, options);\n\t}\n\n\t/**\n\t * Returns if the client has a guest token. The token may not be valid.\n\t * @returns `true` if the client has a guest token; otherwise `false`.\n\t */\n\tpublic hasGuestToken(): boolean {\n\t\treturn this.auth.hasToken() || this.authTrends.hasToken();\n\t}\n\n\t/**\n\t * Returns if the client is logged in as a real user.\n\t * @returns `true` if the client is logged in with a real user account; otherwise `false`.\n\t */\n\tpublic async isLoggedIn(): Promise<boolean> {\n\t\treturn (\n\t\t\t(await this.auth.isLoggedIn()) && (await this.authTrends.isLoggedIn())\n\t\t);\n\t}\n\n\t/**\n\t * Returns the currently logged in user\n\t * @returns The currently logged in user\n\t */\n\tpublic async me(): Promise<Profile | undefined> {\n\t\treturn this.auth.me();\n\t}\n\n\t/**\n\t * Login to Twitter as a real Twitter account. This enables running\n\t * searches.\n\t * @param username The username of the Twitter account to login with.\n\t * @param password The password of the Twitter account to login with.\n\t * @param email The email to log in with, if you have email confirmation enabled.\n\t * @param twoFactorSecret The secret to generate two factor authentication tokens with, if you have two factor authentication enabled.\n\t */\n\tpublic async login(\n\t\tusername: string,\n\t\tpassword: string,\n\t\temail?: string,\n\t\ttwoFactorSecret?: string,\n\t\tappKey?: string,\n\t\tappSecret?: string,\n\t\taccessToken?: string,\n\t\taccessSecret?: string,\n\t): Promise<void> {\n\t\t// Swap in a real authorizer for all requests\n\t\tconst userAuth = new TwitterUserAuth(this.token, this.getAuthOptions());\n\t\tawait userAuth.login(\n\t\t\tusername,\n\t\t\tpassword,\n\t\t\temail,\n\t\t\ttwoFactorSecret,\n\t\t\tappKey,\n\t\t\tappSecret,\n\t\t\taccessToken,\n\t\t\taccessSecret,\n\t\t);\n\t\tthis.auth = userAuth;\n\t\tthis.authTrends = userAuth;\n\t}\n\n\t/**\n\t * Log out of Twitter.\n\t */\n\tpublic async logout(): Promise<void> {\n\t\tawait this.auth.logout();\n\t\tawait this.authTrends.logout();\n\n\t\t// Swap in guest authorizers for all requests\n\t\tthis.useGuestAuth();\n\t}\n\n\t/**\n\t * Retrieves all cookies for the current session.\n\t * @returns All cookies for the current session.\n\t */\n\tpublic async getCookies(): Promise<Cookie[]> {\n\t\treturn await this.authTrends\n\t\t\t.cookieJar()\n\t\t\t.getCookies(\n\t\t\t\ttypeof document !== \"undefined\" ? document.location.toString() : twUrl,\n\t\t\t);\n\t}\n\n\t/**\n\t * Set cookies for the current session.\n\t * @param cookies The cookies to set for the current session.\n\t */\n\tpublic async setCookies(cookies: (string | Cookie)[]): Promise<void> {\n\t\tconst userAuth = new TwitterUserAuth(this.token, this.getAuthOptions());\n\t\tfor (const cookie of cookies) {\n\t\t\tawait userAuth.cookieJar().setCookie(cookie, twUrl);\n\t\t}\n\n\t\tthis.auth = userAuth;\n\t\tthis.authTrends = userAuth;\n\t}\n\n\t/**\n\t * Clear all cookies for the current session.\n\t */\n\tpublic async clearCookies(): Promise<void> {\n\t\tawait this.auth.cookieJar().removeAllCookies();\n\t\tawait this.authTrends.cookieJar().removeAllCookies();\n\t}\n\n\t/**\n\t * Sets the optional cookie to be used in requests.\n\t * @param _cookie The cookie to be used in requests.\n\t * @deprecated This function no longer represents any part of Twitter's auth flow.\n\t * @returns This client instance.\n\t */\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tpublic withCookie(_cookie: string): Client {\n\t\tconsole.warn(\n\t\t\t\"Warning: Client#withCookie is deprecated and will be removed in a later version. Use Client#login or Client#setCookies instead.\",\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the optional CSRF token to be used in requests.\n\t * @param _token The CSRF token to be used in requests.\n\t * @deprecated This function no longer represents any part of Twitter's auth flow.\n\t * @returns This client instance.\n\t */\n\t// eslint-disable-next-line @typescript-eslint/no-unused-vars\n\tpublic withXCsrfToken(_token: string): Client {\n\t\tconsole.warn(\n\t\t\t\"Warning: Client#withXCsrfToken is deprecated and will be removed in a later version.\",\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sends a quote tweet.\n\t * @param text The text of the tweet.\n\t * @param quotedTweetId The ID of the tweet to quote.\n\t * @param options Optional parameters, such as media data.\n\t * @returns The response from the Twitter API.\n\t */\n\tpublic async sendQuoteTweet(\n\t\ttext: string,\n\t\tquotedTweetId: string,\n\t\toptions?: {\n\t\t\tmediaData: { data: Buffer; mediaType: string }[];\n\t\t},\n\t) {\n\t\treturn await createQuoteTweetRequest(\n\t\t\ttext,\n\t\t\tquotedTweetId,\n\t\t\tthis.auth,\n\t\t\toptions?.mediaData,\n\t\t);\n\t}\n\n\t/**\n\t * Likes a tweet with the given tweet ID.\n\t * @param tweetId The ID of the tweet to like.\n\t * @returns A promise that resolves when the tweet is liked.\n\t */\n\tpublic async likeTweet(tweetId: string): Promise<void> {\n\t\t// Call the likeTweet function from tweets.ts\n\t\tawait likeTweet(tweetId, this.auth);\n\t}\n\n\t/**\n\t * Retweets a tweet with the given tweet ID.\n\t * @param tweetId The ID of the tweet to retweet.\n\t * @returns A promise that resolves when the tweet is retweeted.\n\t */\n\tpublic async retweet(tweetId: string): Promise<void> {\n\t\t// Call the retweet function from tweets.ts\n\t\tawait retweet(tweetId, this.auth);\n\t}\n\n\t/**\n\t * Follows a user with the given user ID.\n\t * @param userId The user ID of the user to follow.\n\t * @returns A promise that resolves when the user is followed.\n\t */\n\tpublic async followUser(userName: string): Promise<void> {\n\t\t// Call the followUser function from relationships.ts\n\t\tawait followUser(userName, this.auth);\n\t}\n\n\t/**\n\t * Fetches direct message conversations\n\t * @param count Number of conversations to fetch (default: 50)\n\t * @param cursor Pagination cursor for fetching more conversations\n\t * @returns Array of DM conversations and other details\n\t */\n\tpublic async getDirectMessageConversations(\n\t\tuserId: string,\n\t\tcursor?: string,\n\t): Promise<DirectMessagesResponse> {\n\t\treturn await getDirectMessageConversations(userId, this.auth, cursor);\n\t}\n\n\t/**\n\t * Sends a direct message to a user.\n\t * @param conversationId The ID of the conversation to send the message to.\n\t * @param text The text of the message to send.\n\t * @returns The response from the Twitter API.\n\t */\n\tpublic async sendDirectMessage(\n\t\tconversationId: string,\n\t\ttext: string,\n\t): Promise<SendDirectMessageResponse> {\n\t\treturn await sendDirectMessage(this.auth, conversationId, text);\n\t}\n\n\tprivate getAuthOptions(): Partial<TwitterAuthOptions> {\n\t\treturn {\n\t\t\tfetch: this.options?.fetch,\n\t\t\ttransform: this.options?.transform,\n\t\t};\n\t}\n\n\tprivate handleResponse<T>(res: RequestApiResult<T>): T {\n\t\tif (!res.success) {\n\t\t\tthrow (res as any).err;\n\t\t}\n\n\t\treturn res.value;\n\t}\n\n\t/**\n\t * Retrieves the details of an Audio Space by its ID.\n\t * @param id The ID of the Audio Space.\n\t * @returns The details of the Audio Space.\n\t */\n\tpublic async getAudioSpaceById(id: string): Promise<AudioSpace> {\n\t\tconst variables = {\n\t\t\tid,\n\t\t\tisMetatagsQuery: false,\n\t\t\twithReplays: true,\n\t\t\twithListeners: true,\n\t\t};\n\n\t\treturn await fetchAudioSpaceById(variables, this.auth);\n\t}\n\n\t/**\n\t * Retrieves available space topics.\n\t * @returns An array of space topics.\n\t */\n\tpublic async browseSpaceTopics(): Promise<Subtopic[]> {\n\t\treturn await fetchBrowseSpaceTopics(this.auth);\n\t}\n\n\t/**\n\t * Retrieves available communities.\n\t * @returns An array of communities.\n\t */\n\tpublic async communitySelectQuery(): Promise<Community[]> {\n\t\treturn await fetchCommunitySelectQuery(this.auth);\n\t}\n\n\t/**\n\t * Retrieves the status of an Audio Space stream by its media key.\n\t * @param mediaKey The media key of the Audio Space.\n\t * @returns The status of the Audio Space stream.\n\t */\n\tpublic async getAudioSpaceStreamStatus(\n\t\tmediaKey: string,\n\t): Promise<LiveVideoStreamStatus> {\n\t\treturn await fetchLiveVideoStreamStatus(mediaKey, this.auth);\n\t}\n\n\t/**\n\t * Retrieves the status of an Audio Space by its ID.\n\t * This method internally fetches the Audio Space to obtain the media key,\n\t * then retrieves the stream status using the media key.\n\t * @param audioSpaceId The ID of the Audio Space.\n\t * @returns The status of the Audio Space stream.\n\t */\n\tpublic async getAudioSpaceStatus(\n\t\taudioSpaceId: string,\n\t): Promise<LiveVideoStreamStatus> {\n\t\tconst audioSpace = await this.getAudioSpaceById(audioSpaceId);\n\n\t\tconst mediaKey = audioSpace.metadata.media_key;\n\t\tif (!mediaKey) {\n\t\t\tthrow new Error(\"Media Key not found in Audio Space metadata.\");\n\t\t}\n\n\t\treturn await this.getAudioSpaceStreamStatus(mediaKey);\n\t}\n\n\t/**\n\t * Authenticates Periscope to obtain a token.\n\t * @returns The Periscope authentication token.\n\t */\n\tpublic async authenticatePeriscope(): Promise<string> {\n\t\treturn await fetchAuthenticatePeriscope(this.auth);\n\t}\n\n\t/**\n\t * Logs in to Twitter via Proxsee using the Periscope JWT.\n\t * @param jwt The JWT obtained from AuthenticatePeriscope.\n\t * @returns The response containing the cookie and user information.\n\t */\n\tpublic async loginTwitterToken(\n\t\tjwt: string,\n\t): Promise<LoginTwitterTokenResponse> {\n\t\treturn await fetchLoginTwitterToken(jwt, this.auth);\n\t}\n\n\t/**\n\t * Orchestrates the flow: get token -> login -> return Periscope cookie\n\t */\n\tpublic async getPeriscopeCookie(): Promise<string> {\n\t\tconst periscopeToken = await this.authenticatePeriscope();\n\n\t\tconst loginResponse = await this.loginTwitterToken(periscopeToken);\n\n\t\treturn loginResponse.cookie;\n\t}\n\n\t/**\n\t * Fetches a article (long form tweet) by its ID.\n\t * @param id The ID of the article to fetch. In the format of (http://x.com/i/article/id)\n\t * @returns The {@link TimelineArticle} object, or `null` if it couldn't be fetched.\n\t */\n\tpublic getArticle(id: string): Promise<TimelineArticle | null> {\n\t\treturn getArticle(id, this.auth);\n\t}\n\n\t/**\n\t * Creates a new conversation with Grok.\n\t * @returns A promise that resolves to the conversation ID string.\n\t */\n\tpublic async createGrokConversation(): Promise<string> {\n\t\treturn await createGrokConversation(this.auth);\n\t}\n\n\t/**\n\t * Interact with Grok in a chat-like manner.\n\t * @param options The options for the Grok chat interaction.\n\t * @param {GrokMessage[]} options.messages - Array of messages in the conversation.\n\t * @param {string} [options.conversationId] - Optional ID of an existing conversation.\n\t * @param {boolean} [options.returnSearchResults] - Whether to return search results.\n\t * @param {boolean} [options.returnCitations] - Whether to return citations.\n\t * @returns A promise that resolves to the Grok chat response.\n\t */\n\tpublic async grokChat(options: GrokChatOptions): Promise<GrokChatResponse> {\n\t\treturn await grokChat(options, this.auth);\n\t}\n\n\t/**\n\t * Retrieves all users who retweeted the given tweet.\n\t * @param tweetId The ID of the tweet.\n\t * @returns An array of users (retweeters).\n\t */\n\tpublic async getRetweetersOfTweet(tweetId: string): Promise<Retweeter[]> {\n\t\treturn await getAllRetweeters(tweetId, this.auth);\n\t}\n\n\t/**\n\t * Fetches all tweets quoting a given tweet ID by chaining requests\n\t * until no more pages are available.\n\t * @param quotedTweetId The tweet ID to find quotes of.\n\t * @param maxTweetsPerPage Max tweets per page (default 20).\n\t * @returns An array of all Tweet objects referencing the given tweet.\n\t */\n\tpublic async getAllQuotedTweets(\n\t\tquotedTweetId: string,\n\t\tmaxTweetsPerPage = 20,\n\t): Promise<Tweet[]> {\n\t\tconst allQuotes: Tweet[] = [];\n\t\tlet cursor: string | undefined;\n\t\tlet prevCursor: string | undefined;\n\n\t\twhile (true) {\n\t\t\tconst page = await fetchQuotedTweetsPage(\n\t\t\t\tquotedTweetId,\n\t\t\t\tmaxTweetsPerPage,\n\t\t\t\tthis.auth,\n\t\t\t\tcursor,\n\t\t\t);\n\n\t\t\t// If there's no new tweets, stop\n\t\t\tif (!page.tweets || page.tweets.length === 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tallQuotes.push(...page.tweets);\n\n\t\t\t// If next is missing or same => stop\n\t\t\tif (!page.next || page.next === cursor || page.next === prevCursor) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Move cursors\n\t\t\tprevCursor = cursor;\n\t\t\tcursor = page.next;\n\t\t}\n\n\t\treturn allQuotes;\n\t}\n}\n","// src/core/Space.ts\n\nimport { EventEmitter } from \"node:events\";\nimport { ChatClient } from \"./ChatClient\";\nimport { JanusClient } from \"./JanusClient\";\nimport {\n\tgetTurnServers,\n\tcreateBroadcast,\n\tpublishBroadcast,\n\tauthorizeToken,\n\tgetRegion,\n\tmuteSpeaker,\n\tunmuteSpeaker,\n\tsetupCommonChatEvents,\n} from \"../utils\";\nimport type {\n\tBroadcastCreated,\n\tPlugin,\n\tAudioDataWithUser,\n\tPluginRegistration,\n\tSpeakerInfo,\n\tSpaceConfig,\n} from \"../types\";\nimport type { Client } from \"../../client\";\nimport { Logger } from \"../logger\";\n\n/**\n * Manages the creation of a new Space (broadcast host):\n * 1) Creates the broadcast on Periscope\n * 2) Sets up Janus WebRTC for audio\n * 3) Optionally creates a ChatClient for interactive mode\n * 4) Allows managing (approve/remove) speakers, pushing audio, etc.\n */\nexport class Space extends EventEmitter {\n\tprivate readonly debug: boolean;\n\tprivate readonly logger: Logger;\n\n\tprivate janusClient?: JanusClient;\n\tprivate chatClient?: ChatClient;\n\n\tprivate authToken?: string;\n\tprivate broadcastInfo?: BroadcastCreated;\n\tprivate isInitialized = false;\n\n\tprivate plugins = new Set<PluginRegistration>();\n\tprivate speakers = new Map<string, SpeakerInfo>();\n\n\tconstructor(\n\t\tprivate readonly client: Client,\n\t\toptions?: { debug?: boolean },\n\t) {\n\t\tsuper();\n\t\tthis.debug = options?.debug ?? false;\n\t\tthis.logger = new Logger(this.debug);\n\t}\n\n\t/**\n\t * Registers a plugin and calls its onAttach(...).\n\t * init(...) will be invoked once initialization is complete.\n\t */\n\tpublic use(plugin: Plugin, config?: Record<string, any>) {\n\t\tconst registration: PluginRegistration = { plugin, config };\n\t\tthis.plugins.add(registration);\n\n\t\tthis.logger.debug(\"[Space] Plugin added =>\", plugin.constructor.name);\n\t\tplugin.onAttach?.({ space: this, pluginConfig: config });\n\n\t\t// If we've already initialized this Space, immediately call plugin.init(...)\n\t\tif (this.isInitialized && plugin.init) {\n\t\t\tplugin.init({ space: this, pluginConfig: config });\n\t\t\t// If Janus is also up, call onJanusReady\n\t\t\tif (this.janusClient) {\n\t\t\t\tplugin.onJanusReady?.(this.janusClient);\n\t\t\t}\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Main entry point to create and initialize the Space broadcast.\n\t */\n\tpublic async initialize(config: SpaceConfig) {\n\t\tthis.logger.debug(\"[Space] Initializing...\");\n\n\t\t// 1) Obtain the Periscope cookie + region\n\t\tconst cookie = await this.client.getPeriscopeCookie();\n\t\tconst region = await getRegion();\n\t\tthis.logger.debug(\"[Space] Got region =>\", region);\n\n\t\t// 2) Create a broadcast\n\t\tthis.logger.debug(\"[Space] Creating broadcast...\");\n\t\tconst broadcast = await createBroadcast({\n\t\t\tdescription: config.description,\n\t\t\tlanguages: config.languages,\n\t\t\tcookie,\n\t\t\tregion,\n\t\t\trecord: config.record,\n\t\t});\n\t\tthis.broadcastInfo = broadcast;\n\n\t\t// 3) Authorize to get an auth token\n\t\tthis.logger.debug(\"[Space] Authorizing token...\");\n\t\tthis.authToken = await authorizeToken(cookie);\n\n\t\t// 4) Gather TURN servers\n\t\tthis.logger.debug(\"[Space] Getting turn servers...\");\n\t\tconst turnServers = await getTurnServers(cookie);\n\n\t\t// 5) Create and initialize Janus for hosting\n\t\tthis.janusClient = new JanusClient({\n\t\t\twebrtcUrl: broadcast.webrtc_gw_url,\n\t\t\troomId: broadcast.room_id,\n\t\t\tcredential: broadcast.credential,\n\t\t\tuserId: broadcast.broadcast.user_id,\n\t\t\tstreamName: broadcast.stream_name,\n\t\t\tturnServers,\n\t\t\tlogger: this.logger,\n\t\t});\n\t\tawait this.janusClient.initialize();\n\n\t\t// Forward PCM from Janus to plugin.onAudioData\n\t\tthis.janusClient.on(\"audioDataFromSpeaker\", (data: AudioDataWithUser) => {\n\t\t\tthis.logger.debug(\"[Space] Received PCM from speaker =>\", data.userId);\n\t\t\tthis.handleAudioData(data);\n\t\t});\n\n\t\t// Update speaker info once we subscribe\n\t\tthis.janusClient.on(\"subscribedSpeaker\", ({ userId, feedId }) => {\n\t\t\tconst speaker = this.speakers.get(userId);\n\t\t\tif (!speaker) {\n\t\t\t\tthis.logger.debug(\n\t\t\t\t\t\"[Space] subscribedSpeaker => no speaker found\",\n\t\t\t\t\tuserId,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tspeaker.janusParticipantId = feedId;\n\t\t\tthis.logger.debug(\n\t\t\t\t`[Space] updated speaker => userId=${userId}, feedId=${feedId}`,\n\t\t\t);\n\t\t});\n\n\t\t// 6) Publish the broadcast so it's live\n\t\tthis.logger.debug(\"[Space] Publishing broadcast...\");\n\t\tawait publishBroadcast({\n\t\t\ttitle: config.title || \"\",\n\t\t\tbroadcast,\n\t\t\tcookie,\n\t\t\tjanusSessionId: this.janusClient.getSessionId(),\n\t\t\tjanusHandleId: this.janusClient.getHandleId(),\n\t\t\tjanusPublisherId: this.janusClient.getPublisherId(),\n\t\t});\n\n\t\t// 7) If interactive => set up ChatClient\n\t\tif (config.mode === \"INTERACTIVE\") {\n\t\t\tthis.logger.debug(\"[Space] Connecting chat...\");\n\t\t\tthis.chatClient = new ChatClient({\n\t\t\t\tspaceId: broadcast.room_id,\n\t\t\t\taccessToken: broadcast.access_token,\n\t\t\t\tendpoint: broadcast.endpoint,\n\t\t\t\tlogger: this.logger,\n\t\t\t});\n\t\t\tawait this.chatClient.connect();\n\t\t\tthis.setupChatEvents();\n\t\t}\n\n\t\tthis.logger.info(\n\t\t\t\"[Space] Initialized =>\",\n\t\t\tbroadcast.share_url.replace(\"broadcasts\", \"spaces\"),\n\t\t);\n\t\tthis.isInitialized = true;\n\n\t\t// Call plugin.init(...) and onJanusReady(...) for all plugins now that we're set\n\t\tfor (const { plugin, config: pluginConfig } of this.plugins) {\n\t\t\tplugin.init?.({ space: this, pluginConfig });\n\t\t\tplugin.onJanusReady?.(this.janusClient);\n\t\t}\n\n\t\tthis.logger.debug(\"[Space] All plugins initialized\");\n\t\treturn broadcast;\n\t}\n\n\t/**\n\t * Send an emoji reaction via chat, if interactive.\n\t */\n\tpublic reactWithEmoji(emoji: string) {\n\t\tif (!this.chatClient) return;\n\t\tthis.chatClient.reactWithEmoji(emoji);\n\t}\n\n\t/**\n\t * Internal method to wire up chat events if interactive.\n\t */\n\tprivate setupChatEvents() {\n\t\tif (!this.chatClient) return;\n\t\tsetupCommonChatEvents(this.chatClient, this.logger, this);\n\t}\n\n\t/**\n\t * Approves a speaker request on Twitter side, then calls Janus to subscribe their audio.\n\t */\n\tpublic async approveSpeaker(userId: string, sessionUUID: string) {\n\t\tif (!this.isInitialized || !this.broadcastInfo) {\n\t\t\tthrow new Error(\"[Space] Not initialized or missing broadcastInfo\");\n\t\t}\n\t\tif (!this.authToken) {\n\t\t\tthrow new Error(\"[Space] No auth token available\");\n\t\t}\n\n\t\t// Store in our local speaker map\n\t\tthis.speakers.set(userId, { userId, sessionUUID });\n\n\t\t// 1) Call Twitter's /request/approve\n\t\tawait this.callApproveEndpoint(\n\t\t\tthis.broadcastInfo,\n\t\t\tthis.authToken,\n\t\t\tuserId,\n\t\t\tsessionUUID,\n\t\t);\n\n\t\t// 2) Subscribe to their audio in Janus\n\t\tawait this.janusClient?.subscribeSpeaker(userId);\n\t}\n\n\t/**\n\t * Approve request => calls /api/v1/audiospace/request/approve\n\t */\n\tprivate async callApproveEndpoint(\n\t\tbroadcast: BroadcastCreated,\n\t\tauthorizationToken: string,\n\t\tuserId: string,\n\t\tsessionUUID: string,\n\t): Promise<void> {\n\t\tconst endpoint = \"https://guest.pscp.tv/api/v1/audiospace/request/approve\";\n\t\tconst headers = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tReferer: \"https://x.com/\",\n\t\t\tAuthorization: authorizationToken,\n\t\t};\n\t\tconst body = {\n\t\t\tntpForBroadcasterFrame: \"2208988800024000300\",\n\t\t\tntpForLiveFrame: \"2208988800024000300\",\n\t\t\tchat_token: broadcast.access_token,\n\t\t\tsession_uuid: sessionUUID,\n\t\t};\n\n\t\tthis.logger.debug(\"[Space] Approving speaker =>\", endpoint, body);\n\n\t\tconst resp = await fetch(endpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: JSON.stringify(body),\n\t\t});\n\n\t\tif (!resp.ok) {\n\t\t\tconst error = await resp.text();\n\t\t\tthrow new Error(\n\t\t\t\t`[Space] Failed to approve speaker => ${resp.status}: ${error}`,\n\t\t\t);\n\t\t}\n\n\t\tthis.logger.info(\"[Space] Speaker approved =>\", userId);\n\t}\n\n\t/**\n\t * Removes a speaker from the Twitter side, then unsubscribes in Janus if needed.\n\t */\n\tpublic async removeSpeaker(userId: string) {\n\t\tif (!this.isInitialized || !this.broadcastInfo) {\n\t\t\tthrow new Error(\"[Space] Not initialized or missing broadcastInfo\");\n\t\t}\n\t\tif (!this.authToken) {\n\t\t\tthrow new Error(\"[Space] No auth token\");\n\t\t}\n\t\tif (!this.janusClient) {\n\t\t\tthrow new Error(\"[Space] No Janus client\");\n\t\t}\n\n\t\t// Find this speaker in local map\n\t\tconst speaker = this.speakers.get(userId);\n\t\tif (!speaker) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Space] removeSpeaker => no speaker found for userId=${userId}`,\n\t\t\t);\n\t\t}\n\n\t\tconst { sessionUUID, janusParticipantId } = speaker;\n\t\tthis.logger.debug(\n\t\t\t\"[Space] removeSpeaker =>\",\n\t\t\tsessionUUID,\n\t\t\tjanusParticipantId,\n\t\t\tspeaker,\n\t\t);\n\n\t\tif (!sessionUUID || janusParticipantId === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Space] removeSpeaker => missing sessionUUID or feedId for userId=${userId}`,\n\t\t\t);\n\t\t}\n\n\t\t// 1) Eject on Twitter side\n\t\tconst janusHandleId = this.janusClient.getHandleId();\n\t\tconst janusSessionId = this.janusClient.getSessionId();\n\t\tif (!janusHandleId || !janusSessionId) {\n\t\t\tthrow new Error(\n\t\t\t\t`[Space] removeSpeaker => missing Janus handle/session for userId=${userId}`,\n\t\t\t);\n\t\t}\n\n\t\tawait this.callRemoveEndpoint(\n\t\t\tthis.broadcastInfo,\n\t\t\tthis.authToken,\n\t\t\tsessionUUID,\n\t\t\tjanusParticipantId,\n\t\t\tthis.broadcastInfo.room_id,\n\t\t\tjanusHandleId,\n\t\t\tjanusSessionId,\n\t\t);\n\n\t\t// 2) Remove from local map\n\t\tthis.speakers.delete(userId);\n\t\tthis.logger.info(`[Space] removeSpeaker => removed userId=${userId}`);\n\t}\n\n\t/**\n\t * Twitter's /api/v1/audiospace/stream/eject call\n\t */\n\tprivate async callRemoveEndpoint(\n\t\tbroadcast: BroadcastCreated,\n\t\tauthorizationToken: string,\n\t\tsessionUUID: string,\n\t\tjanusParticipantId: number,\n\t\tjanusRoomId: string,\n\t\twebrtcHandleId: number,\n\t\twebrtcSessionId: number,\n\t): Promise<void> {\n\t\tconst endpoint = \"https://guest.pscp.tv/api/v1/audiospace/stream/eject\";\n\t\tconst headers = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tReferer: \"https://x.com/\",\n\t\t\tAuthorization: authorizationToken,\n\t\t};\n\t\tconst body = {\n\t\t\tntpForBroadcasterFrame: \"2208988800024000300\",\n\t\t\tntpForLiveFrame: \"2208988800024000300\",\n\t\t\tsession_uuid: sessionUUID,\n\t\t\tchat_token: broadcast.access_token,\n\t\t\tjanus_room_id: janusRoomId,\n\t\t\tjanus_participant_id: janusParticipantId,\n\t\t\twebrtc_handle_id: webrtcHandleId,\n\t\t\twebrtc_session_id: webrtcSessionId,\n\t\t};\n\n\t\tthis.logger.debug(\"[Space] Removing speaker =>\", endpoint, body);\n\n\t\tconst resp = await fetch(endpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: JSON.stringify(body),\n\t\t});\n\n\t\tif (!resp.ok) {\n\t\t\tconst error = await resp.text();\n\t\t\tthrow new Error(\n\t\t\t\t`[Space] Failed to remove speaker => ${resp.status}: ${error}`,\n\t\t\t);\n\t\t}\n\n\t\tthis.logger.debug(\"[Space] Speaker removed => sessionUUID=\", sessionUUID);\n\t}\n\n\t/**\n\t * Push PCM audio frames if you're the host. Usually you'd do this if you're capturing\n\t * microphone input from the host side.\n\t */\n\tpublic pushAudio(samples: Int16Array, sampleRate: number) {\n\t\tthis.janusClient?.pushLocalAudio(samples, sampleRate);\n\t}\n\n\t/**\n\t * Handler for PCM from other speakers, forwarded to plugin.onAudioData\n\t */\n\tprivate handleAudioData(data: AudioDataWithUser) {\n\t\tfor (const { plugin } of this.plugins) {\n\t\t\tplugin.onAudioData?.(data);\n\t\t}\n\t}\n\n\t/**\n\t * Gracefully shut down this Space: destroy the Janus room, end the broadcast, etc.\n\t */\n\tpublic async finalizeSpace(): Promise<void> {\n\t\tthis.logger.info(\"[Space] finalizeSpace => stopping broadcast gracefully\");\n\n\t\tconst tasks: Array<Promise<any>> = [];\n\n\t\tif (this.janusClient) {\n\t\t\ttasks.push(\n\t\t\t\tthis.janusClient.destroyRoom().catch((err) => {\n\t\t\t\t\tthis.logger.error(\"[Space] destroyRoom error =>\", err);\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tif (this.broadcastInfo) {\n\t\t\ttasks.push(\n\t\t\t\tthis.endAudiospace({\n\t\t\t\t\tbroadcastId: this.broadcastInfo.room_id,\n\t\t\t\t\tchatToken: this.broadcastInfo.access_token,\n\t\t\t\t}).catch((err) => {\n\t\t\t\t\tthis.logger.error(\"[Space] endAudiospace error =>\", err);\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tif (this.janusClient) {\n\t\t\ttasks.push(\n\t\t\t\tthis.janusClient.leaveRoom().catch((err) => {\n\t\t\t\t\tthis.logger.error(\"[Space] leaveRoom error =>\", err);\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\n\t\tawait Promise.all(tasks);\n\t\tthis.logger.info(\"[Space] finalizeSpace => done.\");\n\t}\n\n\t/**\n\t * Calls /api/v1/audiospace/admin/endAudiospace on Twitter side.\n\t */\n\tprivate async endAudiospace(params: {\n\t\tbroadcastId: string;\n\t\tchatToken: string;\n\t}): Promise<void> {\n\t\tconst url = \"https://guest.pscp.tv/api/v1/audiospace/admin/endAudiospace\";\n\t\tconst headers = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tReferer: \"https://x.com/\",\n\t\t\tAuthorization: this.authToken || \"\",\n\t\t};\n\t\tconst body = {\n\t\t\tbroadcast_id: params.broadcastId,\n\t\t\tchat_token: params.chatToken,\n\t\t};\n\n\t\tthis.logger.debug(\"[Space] endAudiospace =>\", body);\n\n\t\tconst resp = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders,\n\t\t\tbody: JSON.stringify(body),\n\t\t});\n\n\t\tif (!resp.ok) {\n\t\t\tconst errText = await resp.text();\n\t\t\tthrow new Error(`[Space] endAudiospace => ${resp.status} ${errText}`);\n\t\t}\n\n\t\tconst json = await resp.json();\n\t\tthis.logger.debug(\"[Space] endAudiospace => success =>\", json);\n\t}\n\n\t/**\n\t * Retrieves an array of known speakers in this Space (by userId and sessionUUID).\n\t */\n\tpublic getSpeakers(): SpeakerInfo[] {\n\t\treturn Array.from(this.speakers.values());\n\t}\n\n\t/**\n\t * Mute the host (yourself). For the host, session_uuid = '' (empty).\n\t */\n\tpublic async muteHost() {\n\t\tif (!this.authToken) {\n\t\t\tthrow new Error(\"[Space] No auth token available\");\n\t\t}\n\t\tif (!this.broadcastInfo) {\n\t\t\tthrow new Error(\"[Space] No broadcastInfo\");\n\t\t}\n\n\t\tawait muteSpeaker({\n\t\t\tbroadcastId: this.broadcastInfo.room_id,\n\t\t\tsessionUUID: \"\", // host => empty\n\t\t\tchatToken: this.broadcastInfo.access_token,\n\t\t\tauthToken: this.authToken,\n\t\t});\n\t\tthis.logger.info(\"[Space] Host muted successfully.\");\n\t}\n\n\t/**\n\t * Unmute the host (yourself).\n\t */\n\tpublic async unmuteHost() {\n\t\tif (!this.authToken) {\n\t\t\tthrow new Error(\"[Space] No auth token\");\n\t\t}\n\t\tif (!this.broadcastInfo) {\n\t\t\tthrow new Error(\"[Space] No broadcastInfo\");\n\t\t}\n\n\t\tawait unmuteSpeaker({\n\t\t\tbroadcastId: this.broadcastInfo.room_id,\n\t\t\tsessionUUID: \"\",\n\t\t\tchatToken: this.broadcastInfo.access_token,\n\t\t\tauthToken: this.authToken,\n\t\t});\n\t\tthis.logger.info(\"[Space] Host unmuted successfully.\");\n\t}\n\n\t/**\n\t * Mute a specific speaker. We'll retrieve sessionUUID from our local map.\n\t */\n\tpublic async muteSpeaker(userId: string) {\n\t\tif (!this.authToken) {\n\t\t\tthrow new Error(\"[Space] No auth token available\");\n\t\t}\n\t\tif (!this.broadcastInfo) {\n\t\t\tthrow new Error(\"[Space] No broadcastInfo\");\n\t\t}\n\n\t\tconst speaker = this.speakers.get(userId);\n\t\tif (!speaker) {\n\t\t\tthrow new Error(`[Space] Speaker not found for userId=${userId}`);\n\t\t}\n\n\t\tawait muteSpeaker({\n\t\t\tbroadcastId: this.broadcastInfo.room_id,\n\t\t\tsessionUUID: speaker.sessionUUID,\n\t\t\tchatToken: this.broadcastInfo.access_token,\n\t\t\tauthToken: this.authToken,\n\t\t});\n\t\tthis.logger.info(`[Space] Muted speaker => userId=${userId}`);\n\t}\n\n\t/**\n\t * Unmute a specific speaker. We'll retrieve sessionUUID from local map.\n\t */\n\tpublic async unmuteSpeaker(userId: string) {\n\t\tif (!this.authToken) {\n\t\t\tthrow new Error(\"[Space] No auth token available\");\n\t\t}\n\t\tif (!this.broadcastInfo) {\n\t\t\tthrow new Error(\"[Space] No broadcastInfo\");\n\t\t}\n\n\t\tconst speaker = this.speakers.get(userId);\n\t\tif (!speaker) {\n\t\t\tthrow new Error(`[Space] Speaker not found for userId=${userId}`);\n\t\t}\n\n\t\tawait unmuteSpeaker({\n\t\t\tbroadcastId: this.broadcastInfo.room_id,\n\t\t\tsessionUUID: speaker.sessionUUID,\n\t\t\tchatToken: this.broadcastInfo.access_token,\n\t\t\tauthToken: this.authToken,\n\t\t});\n\t\tthis.logger.info(`[Space] Unmuted speaker => userId=${userId}`);\n\t}\n\n\t/**\n\t * Stop the broadcast entirely, performing finalizeSpace() plus plugin cleanup.\n\t */\n\tpublic async stop() {\n\t\tthis.logger.info(\"[Space] Stopping...\");\n\n\t\tawait this.finalizeSpace().catch((err) => {\n\t\t\tthis.logger.error(\"[Space] finalizeBroadcast error =>\", err);\n\t\t});\n\n\t\t// Disconnect chat if present\n\t\tif (this.chatClient) {\n\t\t\tawait this.chatClient.disconnect();\n\t\t\tthis.chatClient = undefined;\n\t\t}\n\n\t\t// Stop Janus if running\n\t\tif (this.janusClient) {\n\t\t\tawait this.janusClient.stop();\n\t\t\tthis.janusClient = undefined;\n\t\t}\n\n\t\t// Cleanup all plugins\n\t\tfor (const { plugin } of this.plugins) {\n\t\t\tplugin.cleanup?.();\n\t\t}\n\t\tthis.plugins.clear();\n\n\t\tthis.isInitialized = false;\n\t}\n}\n","// src/core/ChatClient.ts\n\nimport WebSocket from \"ws\";\nimport { EventEmitter } from \"node:events\";\nimport type { SpeakerRequest, OccupancyUpdate } from \"../types\";\nimport type { Logger } from \"../logger\";\n\n/**\n * Configuration object for ChatClient.\n */\ninterface ChatClientConfig {\n\t/**\n\t * The space ID (e.g., \"1vOGwAbcdE...\") for this audio space.\n\t */\n\tspaceId: string;\n\n\t/**\n\t * The access token obtained from accessChat or the live_video_stream/status.\n\t */\n\taccessToken: string;\n\n\t/**\n\t * The endpoint host for the chat server (e.g., \"https://prod-chatman-ancillary-eu-central-1.pscp.tv\").\n\t */\n\tendpoint: string;\n\n\t/**\n\t * An instance of Logger for debug/info logs.\n\t */\n\tlogger: Logger;\n}\n\n/**\n * ChatClient handles the WebSocket connection to the Twitter/Periscope chat API.\n * It emits events such as \"speakerRequest\", \"occupancyUpdate\", \"muteStateChanged\", etc.\n */\nexport class ChatClient extends EventEmitter {\n\tprivate ws?: WebSocket;\n\tprivate connected = false;\n\n\tprivate readonly logger: Logger;\n\tprivate readonly spaceId: string;\n\tprivate readonly accessToken: string;\n\tprivate endpoint: string;\n\n\tconstructor(config: ChatClientConfig) {\n\t\tsuper();\n\t\tthis.spaceId = config.spaceId;\n\t\tthis.accessToken = config.accessToken;\n\t\tthis.endpoint = config.endpoint;\n\t\tthis.logger = config.logger;\n\t}\n\n\t/**\n\t * Establishes a WebSocket connection to the chat endpoint and sets up event handlers.\n\t */\n\tpublic async connect(): Promise<void> {\n\t\tconst wsUrl = `${this.endpoint}/chatapi/v1/chatnow`.replace(\n\t\t\t\"https://\",\n\t\t\t\"wss://\",\n\t\t);\n\t\tthis.logger.info(\"[ChatClient] Connecting =>\", wsUrl);\n\n\t\tthis.ws = new WebSocket(wsUrl, {\n\t\t\theaders: {\n\t\t\t\tOrigin: \"https://x.com\",\n\t\t\t\t\"User-Agent\": \"Mozilla/5.0\",\n\t\t\t},\n\t\t});\n\n\t\tawait this.setupHandlers();\n\t}\n\n\t/**\n\t * Internal method to set up WebSocket event listeners (open, message, close, error).\n\t */\n\tprivate setupHandlers(): Promise<void> {\n\t\tif (!this.ws) {\n\t\t\tthrow new Error(\"[ChatClient] No WebSocket instance available\");\n\t\t}\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.ws?.on(\"open\", () => {\n\t\t\t\tthis.logger.info(\"[ChatClient] Connected\");\n\t\t\t\tthis.connected = true;\n\t\t\t\tthis.sendAuthAndJoin();\n\t\t\t\tresolve();\n\t\t\t});\n\n\t\t\tthis.ws?.on(\"message\", (data: { toString: () => string }) => {\n\t\t\t\tthis.handleMessage(data.toString());\n\t\t\t});\n\n\t\t\tthis.ws?.on(\"close\", () => {\n\t\t\t\tthis.logger.info(\"[ChatClient] Closed\");\n\t\t\t\tthis.connected = false;\n\t\t\t\tthis.emit(\"disconnected\");\n\t\t\t});\n\n\t\t\tthis.ws?.on(\"error\", (err) => {\n\t\t\t\tthis.logger.error(\"[ChatClient] Error =>\", err);\n\t\t\t\treject(err);\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Sends two WebSocket messages to authenticate and join the specified space.\n\t */\n\tprivate sendAuthAndJoin(): void {\n\t\tif (!this.ws) return;\n\n\t\t// 1) Send authentication (access token)\n\t\tthis.ws.send(\n\t\t\tJSON.stringify({\n\t\t\t\tpayload: JSON.stringify({ access_token: this.accessToken }),\n\t\t\t\tkind: 3,\n\t\t\t}),\n\t\t);\n\n\t\t// 2) Send a \"join\" message specifying the room (space ID)\n\t\tthis.ws.send(\n\t\t\tJSON.stringify({\n\t\t\t\tpayload: JSON.stringify({\n\t\t\t\t\tbody: JSON.stringify({ room: this.spaceId }),\n\t\t\t\t\tkind: 1,\n\t\t\t\t}),\n\t\t\t\tkind: 2,\n\t\t\t}),\n\t\t);\n\t}\n\n\t/**\n\t * Sends an emoji reaction to the chat server.\n\t * @param emoji - The emoji string, e.g. '🔥', '🙏', etc.\n\t */\n\tpublic reactWithEmoji(emoji: string): void {\n\t\tif (!this.ws || !this.connected) {\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[ChatClient] Not connected or WebSocket missing; ignoring reactWithEmoji.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst payload = JSON.stringify({\n\t\t\tbody: JSON.stringify({ body: emoji, type: 2, v: 2 }),\n\t\t\tkind: 1,\n\t\t\t/*\n // The 'sender' field is not required, it's not even verified by the server\n // Instead of passing attributes down here it's easier to ignore it\n sender: {\n user_id: null,\n twitter_id: null,\n username: null,\n display_name: null,\n },\n */\n\t\t\tpayload: JSON.stringify({\n\t\t\t\troom: this.spaceId,\n\t\t\t\tbody: JSON.stringify({ body: emoji, type: 2, v: 2 }),\n\t\t\t}),\n\t\t\ttype: 2,\n\t\t});\n\n\t\tthis.ws.send(payload);\n\t}\n\n\t/**\n\t * Handles inbound WebSocket messages, parsing JSON payloads\n\t * and emitting relevant events (speakerRequest, occupancyUpdate, etc.).\n\t */\n\tprivate handleMessage(raw: string): void {\n\t\tlet msg: any;\n\t\ttry {\n\t\t\tmsg = JSON.parse(raw);\n\t\t} catch {\n\t\t\treturn; // Invalid JSON, ignoring\n\t\t}\n\t\tif (!msg.payload) return;\n\n\t\tconst payload = safeJson(msg.payload);\n\t\tif (!payload?.body) return;\n\n\t\tconst body = safeJson(payload.body);\n\n\t\t// 1) Speaker request => \"guestBroadcastingEvent=1\"\n\t\tif (body.guestBroadcastingEvent === 1) {\n\t\t\tconst req: SpeakerRequest = {\n\t\t\t\tuserId: body.guestRemoteID,\n\t\t\t\tusername: body.guestUsername,\n\t\t\t\tdisplayName: payload.sender?.display_name || body.guestUsername,\n\t\t\t\tsessionUUID: body.sessionUUID,\n\t\t\t};\n\t\t\tthis.emit(\"speakerRequest\", req);\n\t\t}\n\n\t\t// 2) Occupancy update => body.occupancy\n\t\tif (typeof body.occupancy === \"number\") {\n\t\t\tconst update: OccupancyUpdate = {\n\t\t\t\toccupancy: body.occupancy,\n\t\t\t\ttotalParticipants: body.total_participants || 0,\n\t\t\t};\n\t\t\tthis.emit(\"occupancyUpdate\", update);\n\t\t}\n\n\t\t// 3) Mute/unmute => \"guestBroadcastingEvent=16\" (mute) or \"17\" (unmute)\n\t\tif (body.guestBroadcastingEvent === 16) {\n\t\t\tthis.emit(\"muteStateChanged\", {\n\t\t\t\tuserId: body.guestRemoteID,\n\t\t\t\tmuted: true,\n\t\t\t});\n\t\t}\n\t\tif (body.guestBroadcastingEvent === 17) {\n\t\t\tthis.emit(\"muteStateChanged\", {\n\t\t\t\tuserId: body.guestRemoteID,\n\t\t\t\tmuted: false,\n\t\t\t});\n\t\t}\n\n\t\t// 4) \"guestBroadcastingEvent=12\" => host accepted a speaker\n\t\tif (body.guestBroadcastingEvent === 12) {\n\t\t\tthis.emit(\"newSpeakerAccepted\", {\n\t\t\t\tuserId: body.guestRemoteID,\n\t\t\t\tusername: body.guestUsername,\n\t\t\t\tsessionUUID: body.sessionUUID,\n\t\t\t});\n\t\t}\n\n\t\t// 5) \"guestBroadcastingEvent=10\" => host removed a speaker\n\t\tif (body.guestBroadcastingEvent === 10) {\n\t\t\tthis.emit(\"newSpeakerRemoved\", {\n\t\t\t\tuserId: body.guestRemoteID,\n\t\t\t\tusername: body.guestUsername,\n\t\t\t\tsessionUUID: body.sessionUUID,\n\t\t\t});\n\t\t}\n\n\t\t// 6) Reaction => body.type=2\n\t\tif (body?.type === 2) {\n\t\t\tthis.logger.debug(\"[ChatClient] Emitting guestReaction =>\", body);\n\t\t\tthis.emit(\"guestReaction\", {\n\t\t\t\tdisplayName: body.displayName,\n\t\t\t\temoji: body.body,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Closes the WebSocket connection if open, and resets internal state.\n\t */\n\tpublic async disconnect(): Promise<void> {\n\t\tif (this.ws) {\n\t\t\tthis.logger.info(\"[ChatClient] Disconnecting...\");\n\t\t\tthis.ws.close();\n\t\t\tthis.ws = undefined;\n\t\t\tthis.connected = false;\n\t\t}\n\t}\n}\n\n/**\n * Helper function to safely parse JSON without throwing.\n */\nfunction safeJson(text: string): any {\n\ttry {\n\t\treturn JSON.parse(text);\n\t} catch {\n\t\treturn null;\n\t}\n}\n","// src/core/JanusClient.ts\n\nimport { EventEmitter } from \"node:events\";\nimport wrtc from \"@roamhq/wrtc\";\nconst { RTCPeerConnection, MediaStream } = wrtc;\nimport { JanusAudioSink, JanusAudioSource } from \"./JanusAudio\";\nimport type { AudioDataWithUser, TurnServersInfo } from \"../types\";\nimport type { Logger } from \"../logger\";\n\ninterface JanusConfig {\n\t/**\n\t * The base URL for the Janus gateway (e.g. \"https://gw-prod-hydra-eu-west-3.pscp.tv/s=prod:XX/v1/gateway\")\n\t */\n\twebrtcUrl: string;\n\n\t/**\n\t * The unique room ID (e.g., the broadcast or space ID)\n\t */\n\troomId: string;\n\n\t/**\n\t * The token/credential used to authorize requests to Janus (often a signed JWT).\n\t */\n\tcredential: string;\n\n\t/**\n\t * The user identifier (host or speaker). Used as 'display' in the Janus plugin.\n\t */\n\tuserId: string;\n\n\t/**\n\t * The name of the stream (often the same as roomId for convenience).\n\t */\n\tstreamName: string;\n\n\t/**\n\t * ICE / TURN server information returned by Twitter's /turnServers endpoint.\n\t */\n\tturnServers: TurnServersInfo;\n\n\t/**\n\t * Logger instance for consistent debug/info/error logs.\n\t */\n\tlogger: Logger;\n}\n\n/**\n * Manages the Janus session for a Twitter AudioSpace:\n * - Creates a Janus session and plugin handle\n * - Joins the Janus videoroom as publisher/subscriber\n * - Subscribes to other speakers\n * - Sends local PCM frames as Opus\n * - Polls for Janus events\n *\n * It can be used by both the host (who creates a room) or a guest speaker (who joins an existing room).\n */\nexport class JanusClient extends EventEmitter {\n\tprivate logger: Logger;\n\n\tprivate sessionId?: number;\n\tprivate handleId?: number;\n\tprivate publisherId?: number;\n\n\tprivate pc?: RTCPeerConnection;\n\tprivate localAudioSource?: JanusAudioSource;\n\n\tprivate pollActive = false;\n\n\t// Tracks promises waiting for specific Janus events\n\tprivate eventWaiters: Array<{\n\t\tpredicate: (evt: any) => boolean;\n\t\tresolve: (value: any) => void;\n\t\treject: (error: Error) => void;\n\t}> = [];\n\n\t// Tracks subscriber handle+pc for each userId we subscribe to\n\tprivate subscribers = new Map<\n\t\tstring,\n\t\t{\n\t\t\thandleId: number;\n\t\t\tpc: RTCPeerConnection;\n\t\t}\n\t>();\n\n\tconstructor(private readonly config: JanusConfig) {\n\t\tsuper();\n\t\tthis.logger = config.logger;\n\t}\n\n\t/**\n\t * Initializes this JanusClient for the host scenario:\n\t * 1) createSession()\n\t * 2) attachPlugin()\n\t * 3) createRoom()\n\t * 4) joinRoom()\n\t * 5) configure local PeerConnection (send audio, etc.)\n\t */\n\tpublic async initialize(): Promise<void> {\n\t\tthis.logger.debug(\"[JanusClient] initialize() called\");\n\n\t\tthis.sessionId = await this.createSession();\n\t\tthis.handleId = await this.attachPlugin();\n\n\t\t// Start polling for Janus events\n\t\tthis.pollActive = true;\n\t\tthis.startPolling();\n\n\t\t// Create a new Janus room (only for the host scenario)\n\t\tawait this.createRoom();\n\n\t\t// Join that room as publisher\n\t\tthis.publisherId = await this.joinRoom();\n\n\t\t// Set up our RTCPeerConnection for local audio\n\t\tthis.pc = new RTCPeerConnection({\n\t\t\ticeServers: [\n\t\t\t\t{\n\t\t\t\t\turls: this.config.turnServers.uris,\n\t\t\t\t\tusername: this.config.turnServers.username,\n\t\t\t\t\tcredential: this.config.turnServers.password,\n\t\t\t\t},\n\t\t\t],\n\t\t});\n\t\tthis.setupPeerEvents();\n\n\t\t// Add local audio track\n\t\tthis.enableLocalAudio();\n\n\t\t// Create an offer and configure the publisher in Janus\n\t\tawait this.configurePublisher();\n\n\t\tthis.logger.info(\"[JanusClient] Initialization complete\");\n\t}\n\n\t/**\n\t * Initializes this JanusClient for a guest speaker scenario:\n\t * 1) createSession()\n\t * 2) attachPlugin()\n\t * 3) join existing room as publisher (no createRoom call)\n\t * 4) configure local PeerConnection\n\t * 5) subscribe to any existing publishers\n\t */\n\tpublic async initializeGuestSpeaker(sessionUUID: string): Promise<void> {\n\t\tthis.logger.debug(\"[JanusClient] initializeGuestSpeaker() called\");\n\n\t\t// 1) Create a new Janus session\n\t\tthis.sessionId = await this.createSession();\n\t\tthis.handleId = await this.attachPlugin();\n\n\t\t// Start polling\n\t\tthis.pollActive = true;\n\t\tthis.startPolling();\n\n\t\t// 2) Join the existing room as a publisher (no createRoom)\n\t\tconst evtPromise = this.waitForJanusEvent(\n\t\t\t(e) =>\n\t\t\t\te.janus === \"event\" &&\n\t\t\t\te.plugindata?.plugin === \"janus.plugin.videoroom\" &&\n\t\t\t\te.plugindata?.data?.videoroom === \"joined\",\n\t\t\t10000,\n\t\t\t\"Guest Speaker joined event\",\n\t\t);\n\n\t\tconst body = {\n\t\t\trequest: \"join\",\n\t\t\troom: this.config.roomId,\n\t\t\tptype: \"publisher\",\n\t\t\tdisplay: this.config.userId,\n\t\t\tperiscope_user_id: this.config.userId,\n\t\t};\n\t\tawait this.sendJanusMessage(this.handleId, body);\n\n\t\t// Wait for the joined event\n\t\tconst evt = await evtPromise;\n\t\tconst data = evt.plugindata?.data;\n\t\tthis.publisherId = data.id; // Our own publisherId\n\t\tthis.logger.debug(\n\t\t\t\"[JanusClient] guest joined => publisherId=\",\n\t\t\tthis.publisherId,\n\t\t);\n\n\t\t// If there are existing publishers, we can subscribe to them\n\t\tconst publishers = data.publishers || [];\n\t\tthis.logger.debug(\"[JanusClient] existing publishers =>\", publishers);\n\n\t\t// 3) Create RTCPeerConnection for sending local audio\n\t\tthis.pc = new RTCPeerConnection({\n\t\t\ticeServers: [\n\t\t\t\t{\n\t\t\t\t\turls: this.config.turnServers.uris,\n\t\t\t\t\tusername: this.config.turnServers.username,\n\t\t\t\t\tcredential: this.config.turnServers.password,\n\t\t\t\t},\n\t\t\t],\n\t\t});\n\t\tthis.setupPeerEvents();\n\t\tthis.enableLocalAudio();\n\n\t\t// 4) configurePublisher => generate offer, wait for answer\n\t\tawait this.configurePublisher(sessionUUID);\n\n\t\t// 5) Subscribe to each existing publisher\n\t\tawait Promise.all(\n\t\t\tpublishers.map((pub: any) => this.subscribeSpeaker(pub.display, pub.id)),\n\t\t);\n\n\t\tthis.logger.info(\"[JanusClient] Guest speaker negotiation complete\");\n\t}\n\n\t/**\n\t * Subscribes to a speaker's audio feed by userId and/or feedId.\n\t * If feedId=0, we wait for a \"publishers\" event to discover feedId.\n\t */\n\tpublic async subscribeSpeaker(userId: string, feedId = 0): Promise<void> {\n\t\tthis.logger.debug(\"[JanusClient] subscribeSpeaker => userId=\", userId);\n\n\t\t// 1) Attach a separate plugin handle for subscriber\n\t\tconst subscriberHandleId = await this.attachPlugin();\n\t\tthis.logger.debug(\"[JanusClient] subscriber handle =>\", subscriberHandleId);\n\n\t\t// If feedId was not provided, wait for an event listing publishers\n\t\tif (feedId === 0) {\n\t\t\tconst publishersEvt = await this.waitForJanusEvent(\n\t\t\t\t(e) =>\n\t\t\t\t\te.janus === \"event\" &&\n\t\t\t\t\te.plugindata?.plugin === \"janus.plugin.videoroom\" &&\n\t\t\t\t\te.plugindata?.data?.videoroom === \"event\" &&\n\t\t\t\t\tArray.isArray(e.plugindata?.data?.publishers) &&\n\t\t\t\t\te.plugindata?.data?.publishers.length > 0,\n\t\t\t\t8000,\n\t\t\t\t'discover feed_id from \"publishers\"',\n\t\t\t);\n\n\t\t\tconst list = publishersEvt.plugindata.data.publishers as any[];\n\t\t\tconst pub = list.find(\n\t\t\t\t(p) => p.display === userId || p.periscope_user_id === userId,\n\t\t\t);\n\t\t\tif (!pub) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`[JanusClient] subscribeSpeaker => No publisher found for userId=${userId}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfeedId = pub.id;\n\t\t\tthis.logger.debug(\"[JanusClient] found feedId =>\", feedId);\n\t\t}\n\n\t\t// Notify listeners that we've discovered a feed\n\t\tthis.emit(\"subscribedSpeaker\", { userId, feedId });\n\n\t\t// 2) Join the room as a \"subscriber\"\n\t\tconst joinBody = {\n\t\t\trequest: \"join\",\n\t\t\troom: this.config.roomId,\n\t\t\tperiscope_user_id: this.config.userId,\n\t\t\tptype: \"subscriber\",\n\t\t\tstreams: [\n\t\t\t\t{\n\t\t\t\t\tfeed: feedId,\n\t\t\t\t\tmid: \"0\",\n\t\t\t\t\tsend: true, // indicates we might send audio?\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t\tawait this.sendJanusMessage(subscriberHandleId, joinBody);\n\n\t\t// 3) Wait for \"attached\" + jsep.offer\n\t\tconst attachedEvt = await this.waitForJanusEvent(\n\t\t\t(e) =>\n\t\t\t\te.janus === \"event\" &&\n\t\t\t\te.sender === subscriberHandleId &&\n\t\t\t\te.plugindata?.plugin === \"janus.plugin.videoroom\" &&\n\t\t\t\te.plugindata?.data?.videoroom === \"attached\" &&\n\t\t\t\te.jsep?.type === \"offer\",\n\t\t\t8000,\n\t\t\t\"subscriber attached + offer\",\n\t\t);\n\t\tthis.logger.debug('[JanusClient] subscriber => \"attached\" with offer');\n\n\t\t// 4) Create a new RTCPeerConnection for receiving audio from this feed\n\t\tconst offer = attachedEvt.jsep;\n\t\tconst subPc = new RTCPeerConnection({\n\t\t\ticeServers: [\n\t\t\t\t{\n\t\t\t\t\turls: this.config.turnServers.uris,\n\t\t\t\t\tusername: this.config.turnServers.username,\n\t\t\t\t\tcredential: this.config.turnServers.password,\n\t\t\t\t},\n\t\t\t],\n\t\t});\n\n\t\tsubPc.ontrack = (evt) => {\n\t\t\tthis.logger.debug(\n\t\t\t\t\"[JanusClient] subscriber track => kind=%s, readyState=%s, muted=%s\",\n\t\t\t\tevt.track.kind,\n\t\t\t\tevt.track.readyState,\n\t\t\t\tevt.track.muted,\n\t\t\t);\n\t\t\t// Attach a JanusAudioSink to capture PCM\n\t\t\tconst sink = new JanusAudioSink(evt.track, { logger: this.logger });\n\n\t\t\t// For each audio frame, forward it to 'audioDataFromSpeaker'\n\t\t\tsink.on(\"audioData\", (frame) => {\n\t\t\t\tif (this.logger.isDebugEnabled()) {\n\t\t\t\t\tlet maxVal = 0;\n\t\t\t\t\tfor (let i = 0; i < frame.samples.length; i++) {\n\t\t\t\t\t\tconst val = Math.abs(frame.samples[i]);\n\t\t\t\t\t\tif (val > maxVal) maxVal = val;\n\t\t\t\t\t}\n\t\t\t\t\tthis.logger.debug(\n\t\t\t\t\t\t`[AudioSink] userId=${userId}, maxAmplitude=${maxVal}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tthis.emit(\"audioDataFromSpeaker\", {\n\t\t\t\t\tuserId,\n\t\t\t\t\tbitsPerSample: frame.bitsPerSample,\n\t\t\t\t\tsampleRate: frame.sampleRate,\n\t\t\t\t\tnumberOfFrames: frame.numberOfFrames,\n\t\t\t\t\tchannelCount: frame.channelCount,\n\t\t\t\t\tsamples: frame.samples,\n\t\t\t\t} as AudioDataWithUser);\n\t\t\t});\n\t\t};\n\n\t\t// 5) Answer the subscription offer\n\t\tawait subPc.setRemoteDescription(offer);\n\t\tconst answer = await subPc.createAnswer();\n\t\tawait subPc.setLocalDescription(answer);\n\n\t\t// 6) Send \"start\" request to begin receiving\n\t\tawait this.sendJanusMessage(\n\t\t\tsubscriberHandleId,\n\t\t\t{\n\t\t\t\trequest: \"start\",\n\t\t\t\troom: this.config.roomId,\n\t\t\t\tperiscope_user_id: this.config.userId,\n\t\t\t},\n\t\t\tanswer,\n\t\t);\n\n\t\tthis.logger.debug(\"[JanusClient] subscriber => done (user=\", userId, \")\");\n\n\t\t// Track this subscription handle+pc by userId\n\t\tthis.subscribers.set(userId, { handleId: subscriberHandleId, pc: subPc });\n\t}\n\n\t/**\n\t * Pushes local PCM frames to Janus. If the localAudioSource isn't active, it enables it.\n\t */\n\tpublic pushLocalAudio(samples: Int16Array, sampleRate: number, channels = 1) {\n\t\tif (!this.localAudioSource) {\n\t\t\tthis.logger.warn(\"[JanusClient] No localAudioSource => enabling now...\");\n\t\t\tthis.enableLocalAudio();\n\t\t}\n\t\tthis.localAudioSource?.pushPcmData(samples, sampleRate, channels);\n\t}\n\n\t/**\n\t * Ensures a local audio track is added to the RTCPeerConnection for publishing.\n\t */\n\tpublic enableLocalAudio(): void {\n\t\tif (!this.pc) {\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[JanusClient] enableLocalAudio => No RTCPeerConnection\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (this.localAudioSource) {\n\t\t\tthis.logger.debug(\"[JanusClient] localAudioSource already active\");\n\t\t\treturn;\n\t\t}\n\t\t// Create a JanusAudioSource that feeds PCM frames\n\t\tthis.localAudioSource = new JanusAudioSource({ logger: this.logger });\n\t\tconst track = this.localAudioSource.getTrack();\n\t\tconst localStream = new MediaStream();\n\t\tlocalStream.addTrack(track);\n\t\tthis.pc.addTrack(track, localStream);\n\t}\n\n\t/**\n\t * Stops the Janus client: ends polling, closes the RTCPeerConnection, etc.\n\t * Does not destroy or leave the room automatically; call destroyRoom() or leaveRoom() if needed.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tthis.logger.info(\"[JanusClient] Stopping...\");\n\t\tthis.pollActive = false;\n\t\tif (this.pc) {\n\t\t\tthis.pc.close();\n\t\t\tthis.pc = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Returns the current Janus sessionId, if any.\n\t */\n\tpublic getSessionId(): number | undefined {\n\t\treturn this.sessionId;\n\t}\n\n\t/**\n\t * Returns the Janus handleId for the publisher, if any.\n\t */\n\tpublic getHandleId(): number | undefined {\n\t\treturn this.handleId;\n\t}\n\n\t/**\n\t * Returns the Janus publisherId (internal participant ID), if any.\n\t */\n\tpublic getPublisherId(): number | undefined {\n\t\treturn this.publisherId;\n\t}\n\n\t/**\n\t * Creates a new Janus session via POST /janus (with \"janus\":\"create\").\n\t */\n\tprivate async createSession(): Promise<number> {\n\t\tconst transaction = this.randomTid();\n\t\tconst resp = await fetch(this.config.webrtcUrl, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: this.config.credential,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\tReferer: \"https://x.com\",\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tjanus: \"create\",\n\t\t\t\ttransaction,\n\t\t\t}),\n\t\t});\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(\"[JanusClient] createSession failed\");\n\t\t}\n\t\tconst json = await resp.json();\n\t\tif (json.janus !== \"success\") {\n\t\t\tthrow new Error(\"[JanusClient] createSession invalid response\");\n\t\t}\n\t\treturn json.data.id;\n\t}\n\n\t/**\n\t * Attaches to the videoroom plugin via /janus/{sessionId} (with \"janus\":\"attach\").\n\t */\n\tprivate async attachPlugin(): Promise<number> {\n\t\tif (!this.sessionId) {\n\t\t\tthrow new Error(\"[JanusClient] attachPlugin => no sessionId\");\n\t\t}\n\t\tconst transaction = this.randomTid();\n\t\tconst resp = await fetch(`${this.config.webrtcUrl}/${this.sessionId}`, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAuthorization: this.config.credential,\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t},\n\t\t\tbody: JSON.stringify({\n\t\t\t\tjanus: \"attach\",\n\t\t\t\tplugin: \"janus.plugin.videoroom\",\n\t\t\t\ttransaction,\n\t\t\t}),\n\t\t});\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(\"[JanusClient] attachPlugin failed\");\n\t\t}\n\t\tconst json = await resp.json();\n\t\tif (json.janus !== \"success\") {\n\t\t\tthrow new Error(\"[JanusClient] attachPlugin invalid response\");\n\t\t}\n\t\treturn json.data.id;\n\t}\n\n\t/**\n\t * Creates a Janus room for the host scenario.\n\t * For a guest, this step is skipped (the room already exists).\n\t */\n\tprivate async createRoom(): Promise<void> {\n\t\tif (!this.sessionId || !this.handleId) {\n\t\t\tthrow new Error(\"[JanusClient] createRoom => No session/handle\");\n\t\t}\n\t\tconst transaction = this.randomTid();\n\t\tconst body = {\n\t\t\trequest: \"create\",\n\t\t\troom: this.config.roomId,\n\t\t\tperiscope_user_id: this.config.userId,\n\t\t\taudiocodec: \"opus\",\n\t\t\tvideocodec: \"h264\",\n\t\t\ttransport_wide_cc_ext: true,\n\t\t\tapp_component: \"audio-room\",\n\t\t\th264_profile: \"42e01f\",\n\t\t\tdummy_publisher: false,\n\t\t};\n\t\tconst resp = await fetch(\n\t\t\t`${this.config.webrtcUrl}/${this.sessionId}/${this.handleId}`,\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: this.config.credential,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tReferer: \"https://x.com\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tjanus: \"message\",\n\t\t\t\t\ttransaction,\n\t\t\t\t\tbody,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(`[JanusClient] createRoom failed => ${resp.status}`);\n\t\t}\n\t\tconst json = await resp.json();\n\t\tthis.logger.debug(\"[JanusClient] createRoom =>\", JSON.stringify(json));\n\n\t\tif (json.janus === \"error\") {\n\t\t\tthrow new Error(\n\t\t\t\t`[JanusClient] createRoom error => ${json.error?.reason || \"Unknown\"}`,\n\t\t\t);\n\t\t}\n\t\tif (json.plugindata?.data?.videoroom !== \"created\") {\n\t\t\tthrow new Error(\n\t\t\t\t`[JanusClient] unexpected createRoom response => ${JSON.stringify(\n\t\t\t\t\tjson,\n\t\t\t\t)}`,\n\t\t\t);\n\t\t}\n\t\tthis.logger.debug(\n\t\t\t`[JanusClient] Room '${this.config.roomId}' created successfully`,\n\t\t);\n\t}\n\n\t/**\n\t * Joins the created room as a publisher, for the host scenario.\n\t */\n\tprivate async joinRoom(): Promise<number> {\n\t\tif (!this.sessionId || !this.handleId) {\n\t\t\tthrow new Error(\"[JanusClient] no session/handle for joinRoom()\");\n\t\t}\n\n\t\tthis.logger.debug(\"[JanusClient] joinRoom => start\");\n\n\t\t// Wait for the 'joined' event from videoroom\n\t\tconst evtPromise = this.waitForJanusEvent(\n\t\t\t(e) =>\n\t\t\t\te.janus === \"event\" &&\n\t\t\t\te.plugindata?.plugin === \"janus.plugin.videoroom\" &&\n\t\t\t\te.plugindata?.data?.videoroom === \"joined\",\n\t\t\t12000,\n\t\t\t\"Host Joined Event\",\n\t\t);\n\n\t\tconst body = {\n\t\t\trequest: \"join\",\n\t\t\troom: this.config.roomId,\n\t\t\tptype: \"publisher\",\n\t\t\tdisplay: this.config.userId,\n\t\t\tperiscope_user_id: this.config.userId,\n\t\t};\n\t\tawait this.sendJanusMessage(this.handleId, body);\n\n\t\tconst evt = await evtPromise;\n\t\tconst publisherId = evt.plugindata.data.id;\n\t\tthis.logger.debug(\"[JanusClient] joined room => publisherId=\", publisherId);\n\t\treturn publisherId;\n\t}\n\n\t/**\n\t * Creates an SDP offer and sends \"configure\" to Janus with it.\n\t * Used by both host and guest after attach + join.\n\t */\n\tprivate async configurePublisher(sessionUUID = \"\"): Promise<void> {\n\t\tif (!this.pc || !this.sessionId || !this.handleId) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis.logger.debug(\"[JanusClient] createOffer...\");\n\t\tconst offer = await this.pc.createOffer({\n\t\t\tofferToReceiveAudio: true,\n\t\t\tofferToReceiveVideo: false,\n\t\t});\n\t\tawait this.pc.setLocalDescription(offer);\n\n\t\tthis.logger.debug(\"[JanusClient] sending configure with JSEP...\");\n\t\tawait this.sendJanusMessage(\n\t\t\tthis.handleId,\n\t\t\t{\n\t\t\t\trequest: \"configure\",\n\t\t\t\troom: this.config.roomId,\n\t\t\t\tperiscope_user_id: this.config.userId,\n\t\t\t\tsession_uuid: sessionUUID,\n\t\t\t\tstream_name: this.config.streamName,\n\t\t\t\tvidman_token: this.config.credential,\n\t\t\t},\n\t\t\toffer,\n\t\t);\n\t\tthis.logger.debug(\"[JanusClient] waiting for answer...\");\n\t}\n\n\t/**\n\t * Sends a \"janus\":\"message\" to the Janus handle, optionally with jsep.\n\t */\n\tprivate async sendJanusMessage(\n\t\thandleId: number,\n\t\tbody: any,\n\t\tjsep?: any,\n\t): Promise<void> {\n\t\tif (!this.sessionId) {\n\t\t\tthrow new Error(\"[JanusClient] No session for sendJanusMessage\");\n\t\t}\n\t\tconst transaction = this.randomTid();\n\t\tconst resp = await fetch(\n\t\t\t`${this.config.webrtcUrl}/${this.sessionId}/${handleId}`,\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: this.config.credential,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tjanus: \"message\",\n\t\t\t\t\ttransaction,\n\t\t\t\t\tbody,\n\t\t\t\t\tjsep,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`[JanusClient] sendJanusMessage failed => status=${resp.status}`,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Starts polling /janus/{sessionId}?maxev=1 for events. We parse keepalives, answers, etc.\n\t */\n\tprivate startPolling(): void {\n\t\tthis.logger.debug(\"[JanusClient] Starting polling...\");\n\t\tconst doPoll = async () => {\n\t\t\tif (!this.pollActive || !this.sessionId) {\n\t\t\t\tthis.logger.debug(\"[JanusClient] Polling stopped\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst url = `${this.config.webrtcUrl}/${\n\t\t\t\t\tthis.sessionId\n\t\t\t\t}?maxev=1&_=${Date.now()}`;\n\t\t\t\tconst resp = await fetch(url, {\n\t\t\t\t\theaders: { Authorization: this.config.credential },\n\t\t\t\t});\n\t\t\t\tif (resp.ok) {\n\t\t\t\t\tconst event = await resp.json();\n\t\t\t\t\tthis.handleJanusEvent(event);\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.warn(\"[JanusClient] poll error =>\", resp.status);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis.logger.error(\"[JanusClient] poll exception =>\", err);\n\t\t\t}\n\t\t\tsetTimeout(doPoll, 500);\n\t\t};\n\t\tdoPoll();\n\t}\n\n\t/**\n\t * Processes each Janus event received from the poll cycle.\n\t */\n\tprivate handleJanusEvent(evt: any): void {\n\t\tif (!evt.janus) {\n\t\t\treturn;\n\t\t}\n\t\tif (evt.janus === \"keepalive\") {\n\t\t\tthis.logger.debug(\"[JanusClient] keepalive received\");\n\t\t\treturn;\n\t\t}\n\t\tif (evt.janus === \"webrtcup\") {\n\t\t\tthis.logger.debug(\"[JanusClient] webrtcup => sender=\", evt.sender);\n\t\t}\n\t\t// If there's a JSEP answer, set it on our RTCPeerConnection\n\t\tif (evt.jsep && evt.jsep.type === \"answer\") {\n\t\t\tthis.onReceivedAnswer(evt.jsep);\n\t\t}\n\t\t// If there's a publisherId in the data, store it\n\t\tif (evt.plugindata?.data?.id) {\n\t\t\tthis.publisherId = evt.plugindata.data.id;\n\t\t}\n\t\t// If there's an error, emit an 'error' event\n\t\tif (evt.error) {\n\t\t\tthis.logger.error(\"[JanusClient] Janus error =>\", evt.error.reason);\n\t\t\tthis.emit(\"error\", new Error(evt.error.reason));\n\t\t}\n\n\t\t// Resolve any waiting eventWaiters whose predicate matches\n\t\tfor (let i = 0; i < this.eventWaiters.length; i++) {\n\t\t\tconst waiter = this.eventWaiters[i];\n\t\t\tif (waiter.predicate(evt)) {\n\t\t\t\tthis.eventWaiters.splice(i, 1);\n\t\t\t\twaiter.resolve(evt);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Called whenever we get an SDP \"answer\" from Janus. Sets the remote description on our PC.\n\t */\n\tprivate async onReceivedAnswer(answer: any): Promise<void> {\n\t\tif (!this.pc) {\n\t\t\treturn;\n\t\t}\n\t\tthis.logger.debug(\"[JanusClient] got answer => setRemoteDescription\");\n\t\tawait this.pc.setRemoteDescription(answer);\n\t}\n\n\t/**\n\t * Sets up events on our main RTCPeerConnection for ICE changes, track additions, etc.\n\t */\n\tprivate setupPeerEvents(): void {\n\t\tif (!this.pc) {\n\t\t\treturn;\n\t\t}\n\t\tthis.pc.addEventListener(\"iceconnectionstatechange\", () => {\n\t\t\tthis.logger.debug(\n\t\t\t\t\"[JanusClient] ICE state =>\",\n\t\t\t\tthis.pc?.iceConnectionState,\n\t\t\t);\n\t\t\tif (this.pc?.iceConnectionState === \"failed\") {\n\t\t\t\tthis.emit(\"error\", new Error(\"[JanusClient] ICE connection failed\"));\n\t\t\t}\n\t\t});\n\t\tthis.pc.addEventListener(\"track\", (evt) => {\n\t\t\tthis.logger.debug(\"[JanusClient] ontrack => kind=\", evt.track.kind);\n\t\t});\n\t}\n\n\t/**\n\t * Generates a random transaction ID for Janus requests.\n\t */\n\tprivate randomTid(): string {\n\t\treturn Math.random().toString(36).slice(2, 10);\n\t}\n\n\t/**\n\t * Waits for a specific Janus event (e.g., \"joined\", \"attached\", etc.)\n\t * that matches a given predicate. Times out after timeoutMs if not received.\n\t */\n\tprivate async waitForJanusEvent(\n\t\tpredicate: (evt: any) => boolean,\n\t\ttimeoutMs = 5000,\n\t\tdescription = \"some event\",\n\t): Promise<any> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst waiter = { predicate, resolve, reject };\n\t\t\tthis.eventWaiters.push(waiter);\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tconst idx = this.eventWaiters.indexOf(waiter);\n\t\t\t\tif (idx !== -1) {\n\t\t\t\t\tthis.eventWaiters.splice(idx, 1);\n\t\t\t\t\tthis.logger.warn(\n\t\t\t\t\t\t`[JanusClient] waitForJanusEvent => timed out waiting for: ${description}`,\n\t\t\t\t\t);\n\t\t\t\t\treject(\n\t\t\t\t\t\tnew Error(\n\t\t\t\t\t\t\t`[JanusClient] waitForJanusEvent (expecting \"${description}\") timed out after ${timeoutMs}ms`,\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}, timeoutMs);\n\t\t});\n\t}\n\n\t/**\n\t * Destroys the Janus room (host only). Does not close local PC or stop polling.\n\t */\n\tpublic async destroyRoom(): Promise<void> {\n\t\tif (!this.sessionId || !this.handleId) {\n\t\t\tthis.logger.warn(\"[JanusClient] destroyRoom => no session/handle\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.config.roomId || !this.config.userId) {\n\t\t\tthis.logger.warn(\"[JanusClient] destroyRoom => no roomId/userId\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst transaction = this.randomTid();\n\t\tconst body = {\n\t\t\trequest: \"destroy\",\n\t\t\troom: this.config.roomId,\n\t\t\tperiscope_user_id: this.config.userId,\n\t\t};\n\t\tthis.logger.info(\"[JanusClient] destroying room =>\", body);\n\n\t\tconst resp = await fetch(\n\t\t\t`${this.config.webrtcUrl}/${this.sessionId}/${this.handleId}`,\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: this.config.credential,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\tReferer: \"https://x.com\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tjanus: \"message\",\n\t\t\t\t\ttransaction,\n\t\t\t\t\tbody,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(`[JanusClient] destroyRoom failed => ${resp.status}`);\n\t\t}\n\t\tconst json = await resp.json();\n\t\tthis.logger.debug(\"[JanusClient] destroyRoom =>\", JSON.stringify(json));\n\t}\n\n\t/**\n\t * Leaves the Janus room if we've joined. Does not close the local PC or stop polling.\n\t */\n\tpublic async leaveRoom(): Promise<void> {\n\t\tif (!this.sessionId || !this.handleId) {\n\t\t\tthis.logger.warn(\"[JanusClient] leaveRoom => no session/handle\");\n\t\t\treturn;\n\t\t}\n\t\tconst transaction = this.randomTid();\n\t\tconst body = {\n\t\t\trequest: \"leave\",\n\t\t\troom: this.config.roomId,\n\t\t\tperiscope_user_id: this.config.userId,\n\t\t};\n\t\tthis.logger.info(\"[JanusClient] leaving room =>\", body);\n\n\t\tconst resp = await fetch(\n\t\t\t`${this.config.webrtcUrl}/${this.sessionId}/${this.handleId}`,\n\t\t\t{\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: this.config.credential,\n\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tjanus: \"message\",\n\t\t\t\t\ttransaction,\n\t\t\t\t\tbody,\n\t\t\t\t}),\n\t\t\t},\n\t\t);\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(`[JanusClient] leaveRoom => error code ${resp.status}`);\n\t\t}\n\t\tconst json = await resp.json();\n\t\tthis.logger.debug(\"[JanusClient] leaveRoom =>\", JSON.stringify(json));\n\t}\n}\n","// src/core/JanusAudio.ts\n\nimport { EventEmitter } from \"node:events\";\nimport wrtc from \"@roamhq/wrtc\";\nconst { nonstandard } = wrtc;\nconst { RTCAudioSource, RTCAudioSink } = nonstandard;\nimport type { Logger } from \"../logger\";\n\n/**\n * Configuration options for the JanusAudioSource.\n */\ninterface AudioSourceOptions {\n\t/**\n\t * Optional logger instance for debug/info/warn logs.\n\t */\n\tlogger?: Logger;\n}\n\n/**\n * Configuration options for the JanusAudioSink.\n */\ninterface AudioSinkOptions {\n\t/**\n\t * Optional logger instance for debug/info/warn logs.\n\t */\n\tlogger?: Logger;\n}\n\n/**\n * JanusAudioSource wraps a RTCAudioSource, allowing you to push\n * raw PCM frames (Int16Array) into the WebRTC pipeline.\n */\nexport class JanusAudioSource extends EventEmitter {\n\tprivate source: any;\n\tprivate readonly track: MediaStreamTrack;\n\tprivate logger?: Logger;\n\n\tconstructor(options?: AudioSourceOptions) {\n\t\tsuper();\n\t\tthis.logger = options?.logger;\n\t\tthis.source = new RTCAudioSource();\n\t\tthis.track = this.source.createTrack();\n\t}\n\n\t/**\n\t * Returns the MediaStreamTrack associated with this audio source.\n\t */\n\tpublic getTrack(): MediaStreamTrack {\n\t\treturn this.track;\n\t}\n\n\t/**\n\t * Pushes PCM data into the RTCAudioSource. Typically 16-bit, single- or multi-channel frames.\n\t * @param samples - The Int16Array audio samples.\n\t * @param sampleRate - The sampling rate (e.g., 48000).\n\t * @param channels - Number of channels (e.g., 1 for mono).\n\t */\n\tpublic pushPcmData(\n\t\tsamples: Int16Array,\n\t\tsampleRate: number,\n\t\tchannels = 1,\n\t): void {\n\t\tif (this.logger?.isDebugEnabled()) {\n\t\t\tthis.logger?.debug(\n\t\t\t\t`[JanusAudioSource] pushPcmData => sampleRate=${sampleRate}, channels=${channels}, frames=${samples.length}`,\n\t\t\t);\n\t\t}\n\n\t\t// Feed data into the RTCAudioSource\n\t\tthis.source.onData({\n\t\t\tsamples,\n\t\t\tsampleRate,\n\t\t\tbitsPerSample: 16,\n\t\t\tchannelCount: channels,\n\t\t\tnumberOfFrames: samples.length / channels,\n\t\t});\n\t}\n}\n\n/**\n * JanusAudioSink wraps a RTCAudioSink, providing an event emitter\n * that forwards raw PCM frames (Int16Array) to listeners.\n */\nexport class JanusAudioSink extends EventEmitter {\n\tprivate sink: any;\n\tprivate active = true;\n\tprivate logger?: Logger;\n\n\tconstructor(track: MediaStreamTrack, options?: AudioSinkOptions) {\n\t\tsuper();\n\t\tthis.logger = options?.logger;\n\n\t\tif (track.kind !== \"audio\") {\n\t\t\tthrow new Error(\"[JanusAudioSink] Provided track is not an audio track\");\n\t\t}\n\n\t\t// Create RTCAudioSink to listen for PCM frames\n\t\tthis.sink = new RTCAudioSink(track);\n\n\t\t// Register callback for PCM frames\n\t\tthis.sink.ondata = (frame: {\n\t\t\tsamples: Int16Array;\n\t\t\tsampleRate: number;\n\t\t\tbitsPerSample: number;\n\t\t\tchannelCount: number;\n\t\t}) => {\n\t\t\tif (!this.active) return;\n\n\t\t\tif (this.logger?.isDebugEnabled()) {\n\t\t\t\tthis.logger?.debug(\n\t\t\t\t\t`[JanusAudioSink] ondata => sampleRate=${frame.sampleRate}, bitsPerSample=${frame.bitsPerSample}, channelCount=${frame.channelCount}, frames=${frame.samples.length}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Emit 'audioData' event with the raw PCM frame\n\t\t\tthis.emit(\"audioData\", frame);\n\t\t};\n\t}\n\n\t/**\n\t * Stops receiving audio data. Once called, no further 'audioData' events will be emitted.\n\t */\n\tpublic stop(): void {\n\t\tthis.active = false;\n\t\tif (this.logger?.isDebugEnabled()) {\n\t\t\tthis.logger?.debug(\"[JanusAudioSink] stop called => stopping the sink\");\n\t\t}\n\t\tthis.sink?.stop();\n\t}\n}\n","// src/utils.ts\n\nimport { Headers } from \"headers-polyfill\";\nimport type { BroadcastCreated, TurnServersInfo } from \"./types\";\nimport type { ChatClient } from \"./core/ChatClient\";\nimport type { Logger } from \"./logger\";\nimport type { EventEmitter } from \"node:events\";\n\n/**\n * Authorizes a token for guest access, using the provided Periscope cookie.\n * Returns an authorization token (bearer/JWT-like).\n */\nexport async function authorizeToken(cookie: string): Promise<string> {\n\tconst headers = new Headers({\n\t\t\"X-Periscope-User-Agent\": \"Twitter/m5\",\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"X-Idempotence\": Date.now().toString(),\n\t\tReferer: \"https://x.com/\",\n\t\t\"X-Attempt\": \"1\",\n\t});\n\n\tconst resp = await fetch(\"https://proxsee.pscp.tv/api/v2/authorizeToken\", {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify({\n\t\t\tservice: \"guest\",\n\t\t\tcookie: cookie,\n\t\t}),\n\t});\n\n\tif (!resp.ok) {\n\t\tthrow new Error(\n\t\t\t`authorizeToken => request failed with status ${resp.status}`,\n\t\t);\n\t}\n\n\tconst data = (await resp.json()) as { authorization_token: string };\n\tif (!data.authorization_token) {\n\t\tthrow new Error(\n\t\t\t\"authorizeToken => Missing authorization_token in response\",\n\t\t);\n\t}\n\n\treturn data.authorization_token;\n}\n\n/**\n * Publishes a newly created broadcast (Space) to make it live/visible.\n * Generally invoked after creating the broadcast and initializing Janus.\n */\nexport async function publishBroadcast(params: {\n\ttitle: string;\n\tbroadcast: BroadcastCreated;\n\tcookie: string;\n\tjanusSessionId?: number;\n\tjanusHandleId?: number;\n\tjanusPublisherId?: number;\n}): Promise<void> {\n\tconst headers = new Headers({\n\t\t\"X-Periscope-User-Agent\": \"Twitter/m5\",\n\t\t\"Content-Type\": \"application/json\",\n\t\tReferer: \"https://x.com/\",\n\t\t\"X-Idempotence\": Date.now().toString(),\n\t\t\"X-Attempt\": \"1\",\n\t});\n\n\tawait fetch(\"https://proxsee.pscp.tv/api/v2/publishBroadcast\", {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify({\n\t\t\taccept_guests: true,\n\t\t\tbroadcast_id: params.broadcast.room_id,\n\t\t\twebrtc_handle_id: params.janusHandleId,\n\t\t\twebrtc_session_id: params.janusSessionId,\n\t\t\tjanus_publisher_id: params.janusPublisherId,\n\t\t\tjanus_room_id: params.broadcast.room_id,\n\t\t\tcookie: params.cookie,\n\t\t\tstatus: params.title,\n\t\t\tconversation_controls: 0,\n\t\t}),\n\t});\n}\n\n/**\n * Retrieves TURN server credentials and URIs from Periscope.\n */\nexport async function getTurnServers(cookie: string): Promise<TurnServersInfo> {\n\tconst headers = new Headers({\n\t\t\"X-Periscope-User-Agent\": \"Twitter/m5\",\n\t\t\"Content-Type\": \"application/json\",\n\t\tReferer: \"https://x.com/\",\n\t\t\"X-Idempotence\": Date.now().toString(),\n\t\t\"X-Attempt\": \"1\",\n\t});\n\n\tconst resp = await fetch(\"https://proxsee.pscp.tv/api/v2/turnServers\", {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify({ cookie }),\n\t});\n\tif (!resp.ok) {\n\t\tthrow new Error(\n\t\t\t`getTurnServers => request failed with status ${resp.status}`,\n\t\t);\n\t}\n\treturn resp.json();\n}\n\n/**\n * Obtains the region from signer.pscp.tv, typically used when creating a broadcast.\n */\nexport async function getRegion(): Promise<string> {\n\tconst resp = await fetch(\"https://signer.pscp.tv/region\", {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tReferer: \"https://x.com\",\n\t\t},\n\t\tbody: JSON.stringify({}),\n\t});\n\tif (!resp.ok) {\n\t\tthrow new Error(`getRegion => request failed with status ${resp.status}`);\n\t}\n\tconst data = (await resp.json()) as { region: string };\n\treturn data.region;\n}\n\n/**\n * Creates a new broadcast on Periscope/Twitter.\n * Used by the host to create the underlying audio-room structure.\n */\nexport async function createBroadcast(params: {\n\tdescription?: string;\n\tlanguages?: string[];\n\tcookie: string;\n\tregion: string;\n\trecord: boolean;\n}): Promise<BroadcastCreated> {\n\tconst headers = new Headers({\n\t\t\"X-Periscope-User-Agent\": \"Twitter/m5\",\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"X-Idempotence\": Date.now().toString(),\n\t\tReferer: \"https://x.com/\",\n\t\t\"X-Attempt\": \"1\",\n\t});\n\n\tconst resp = await fetch(\"https://proxsee.pscp.tv/api/v2/createBroadcast\", {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify({\n\t\t\tapp_component: \"audio-room\",\n\t\t\tcontent_type: \"visual_audio\",\n\t\t\tcookie: params.cookie,\n\t\t\tconversation_controls: 0,\n\t\t\tdescription: params.description || \"\",\n\t\t\theight: 1080,\n\t\t\tis_360: false,\n\t\t\tis_space_available_for_replay: params.record,\n\t\t\tis_webrtc: true,\n\t\t\tlanguages: params.languages ?? [],\n\t\t\tregion: params.region,\n\t\t\twidth: 1920,\n\t\t}),\n\t});\n\n\tif (!resp.ok) {\n\t\tconst text = await resp.text();\n\t\tthrow new Error(\n\t\t\t`createBroadcast => request failed with status ${resp.status} ${text}`,\n\t\t);\n\t}\n\n\tconst data = await resp.json();\n\treturn data as BroadcastCreated;\n}\n\n/**\n * Acquires chat access info (token, endpoint, etc.) from Periscope.\n * Needed to connect via WebSocket to the chat server.\n */\nexport async function accessChat(\n\tchatToken: string,\n\tcookie: string,\n): Promise<any> {\n\tconst url = \"https://proxsee.pscp.tv/api/v2/accessChat\";\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"X-Periscope-User-Agent\": \"Twitter/m5\",\n\t});\n\n\tconst body = {\n\t\tchat_token: chatToken,\n\t\tcookie,\n\t};\n\n\tconst resp = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(body),\n\t});\n\tif (!resp.ok) {\n\t\tthrow new Error(`accessChat => request failed with status ${resp.status}`);\n\t}\n\treturn resp.json();\n}\n\n/**\n * Registers this client as a viewer (POST /startWatching), returning a watch session token.\n */\nexport async function startWatching(\n\tlifecycleToken: string,\n\tcookie: string,\n): Promise<string> {\n\tconst url = \"https://proxsee.pscp.tv/api/v2/startWatching\";\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"X-Periscope-User-Agent\": \"Twitter/m5\",\n\t});\n\n\tconst body = {\n\t\tauto_play: false,\n\t\tlife_cycle_token: lifecycleToken,\n\t\tcookie,\n\t};\n\n\tconst resp = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(body),\n\t});\n\tif (!resp.ok) {\n\t\tthrow new Error(\n\t\t\t`startWatching => request failed with status ${resp.status}`,\n\t\t);\n\t}\n\tconst json = await resp.json();\n\t// Typically returns { session: \"...someToken...\" }\n\treturn json.session;\n}\n\n/**\n * Deregisters this client from viewing the broadcast (POST /stopWatching).\n */\nexport async function stopWatching(\n\tsession: string,\n\tcookie: string,\n): Promise<void> {\n\tconst url = \"https://proxsee.pscp.tv/api/v2/stopWatching\";\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/json\",\n\t\t\"X-Periscope-User-Agent\": \"Twitter/m5\",\n\t});\n\n\tconst body = { session, cookie };\n\tconst resp = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(body),\n\t});\n\tif (!resp.ok) {\n\t\tthrow new Error(\n\t\t\t`stopWatching => request failed with status ${resp.status}`,\n\t\t);\n\t}\n}\n\n/**\n * Optional step: join an existing AudioSpace (POST /audiospace/join).\n * This might be required before you can request speaker.\n */\nexport async function joinAudioSpace(params: {\n\tbroadcastId: string;\n\tchatToken: string;\n\tauthToken: string;\n\tjoinAsAdmin?: boolean;\n\tshouldAutoJoin?: boolean;\n}): Promise<any> {\n\tconst url = \"https://guest.pscp.tv/api/v1/audiospace/join\";\n\n\tconst body = {\n\t\tntpForBroadcasterFrame: \"2208988800031000000\",\n\t\tntpForLiveFrame: \"2208988800031000000\",\n\t\tbroadcast_id: params.broadcastId,\n\t\tjoin_as_admin: params.joinAsAdmin ?? false,\n\t\tshould_auto_join: params.shouldAutoJoin ?? false,\n\t\tchat_token: params.chatToken,\n\t};\n\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/json\",\n\t\tAuthorization: params.authToken,\n\t});\n\n\tconst resp = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(body),\n\t});\n\n\tif (!resp.ok) {\n\t\tthrow new Error(\n\t\t\t`joinAudioSpace => request failed with status ${resp.status}`,\n\t\t);\n\t}\n\t// Typically returns { can_auto_join: boolean } etc.\n\treturn resp.json();\n}\n\n/**\n * Submits a speaker request (POST /audiospace/request/submit),\n * returning the session UUID you need for negotiation.\n */\nexport async function submitSpeakerRequest(params: {\n\tbroadcastId: string;\n\tchatToken: string;\n\tauthToken: string;\n}): Promise<{ session_uuid: string }> {\n\tconst url = \"https://guest.pscp.tv/api/v1/audiospace/request/submit\";\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/json\",\n\t\tAuthorization: params.authToken,\n\t});\n\n\tconst body = {\n\t\tntpForBroadcasterFrame: \"2208988800030000000\",\n\t\tntpForLiveFrame: \"2208988800030000000\",\n\t\tbroadcast_id: params.broadcastId,\n\t\tchat_token: params.chatToken,\n\t};\n\n\tconst resp = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(body),\n\t});\n\tif (!resp.ok) {\n\t\tthrow new Error(\n\t\t\t`submitSpeakerRequest => request failed with status ${resp.status}`,\n\t\t);\n\t}\n\treturn resp.json();\n}\n\n/**\n * Cancels a previously submitted speaker request (POST /audiospace/request/cancel).\n * Only valid if a request/submit was made first with a sessionUUID.\n */\nexport async function cancelSpeakerRequest(params: {\n\tbroadcastId: string;\n\tsessionUUID: string;\n\tchatToken: string;\n\tauthToken: string;\n}): Promise<void> {\n\tconst url = \"https://guest.pscp.tv/api/v1/audiospace/request/cancel\";\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/json\",\n\t\tAuthorization: params.authToken,\n\t});\n\n\tconst body = {\n\t\tntpForBroadcasterFrame: \"2208988800002000000\",\n\t\tntpForLiveFrame: \"2208988800002000000\",\n\t\tbroadcast_id: params.broadcastId,\n\t\tsession_uuid: params.sessionUUID,\n\t\tchat_token: params.chatToken,\n\t};\n\n\tconst resp = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(body),\n\t});\n\tif (!resp.ok) {\n\t\tthrow new Error(\n\t\t\t`cancelSpeakerRequest => request failed with status ${resp.status}`,\n\t\t);\n\t}\n\t// Typically returns { \"success\": true }\n\treturn resp.json();\n}\n\n/**\n * Negotiates a guest streaming session (POST /audiospace/stream/negotiate),\n * returning a Janus JWT and gateway URL for WebRTC.\n */\nexport async function negotiateGuestStream(params: {\n\tbroadcastId: string;\n\tsessionUUID: string;\n\tauthToken: string;\n\tcookie: string;\n}): Promise<{ janus_jwt: string; webrtc_gw_url: string }> {\n\tconst url = \"https://guest.pscp.tv/api/v1/audiospace/stream/negotiate\";\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/json\",\n\t\tAuthorization: params.authToken,\n\t});\n\n\tconst body = {\n\t\tsession_uuid: params.sessionUUID,\n\t};\n\n\tconst resp = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(body),\n\t});\n\tif (!resp.ok) {\n\t\tthrow new Error(\n\t\t\t`negotiateGuestStream => request failed with status ${resp.status}`,\n\t\t);\n\t}\n\treturn resp.json();\n}\n\n/**\n * Mutes a speaker (POST /audiospace/muteSpeaker).\n * If called by the host, sessionUUID is \"\".\n * If called by a speaker, pass your own sessionUUID.\n */\nexport async function muteSpeaker(params: {\n\tbroadcastId: string;\n\tsessionUUID?: string;\n\tchatToken: string;\n\tauthToken: string;\n}): Promise<void> {\n\tconst url = \"https://guest.pscp.tv/api/v1/audiospace/muteSpeaker\";\n\n\tconst body = {\n\t\tntpForBroadcasterFrame: 2208988800031000000,\n\t\tntpForLiveFrame: 2208988800031000000,\n\t\tsession_uuid: params.sessionUUID ?? \"\",\n\t\tbroadcast_id: params.broadcastId,\n\t\tchat_token: params.chatToken,\n\t};\n\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/json\",\n\t\tAuthorization: params.authToken,\n\t});\n\n\tconst resp = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(body),\n\t});\n\tif (!resp.ok) {\n\t\tconst text = await resp.text();\n\t\tthrow new Error(`muteSpeaker => ${resp.status} ${text}`);\n\t}\n}\n\n/**\n * Unmutes a speaker (POST /audiospace/unmuteSpeaker).\n * If called by the host, sessionUUID is \"\".\n * If called by a speaker, pass your own sessionUUID.\n */\nexport async function unmuteSpeaker(params: {\n\tbroadcastId: string;\n\tsessionUUID?: string;\n\tchatToken: string;\n\tauthToken: string;\n}): Promise<void> {\n\tconst url = \"https://guest.pscp.tv/api/v1/audiospace/unmuteSpeaker\";\n\n\tconst body = {\n\t\tntpForBroadcasterFrame: 2208988800031000000,\n\t\tntpForLiveFrame: 2208988800031000000,\n\t\tsession_uuid: params.sessionUUID ?? \"\",\n\t\tbroadcast_id: params.broadcastId,\n\t\tchat_token: params.chatToken,\n\t};\n\n\tconst headers = new Headers({\n\t\t\"Content-Type\": \"application/json\",\n\t\tAuthorization: params.authToken,\n\t});\n\n\tconst resp = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: JSON.stringify(body),\n\t});\n\tif (!resp.ok) {\n\t\tconst text = await resp.text();\n\t\tthrow new Error(`unmuteSpeaker => ${resp.status} ${text}`);\n\t}\n}\n\n/**\n * Common chat events helper. Attaches listeners to a ChatClient, then re-emits them\n * through a given EventEmitter (e.g. Space or SpaceParticipant).\n */\nexport function setupCommonChatEvents(\n\tchatClient: ChatClient,\n\tlogger: Logger,\n\temitter: EventEmitter,\n): void {\n\t// Occupancy updates\n\tchatClient.on(\"occupancyUpdate\", (upd) => {\n\t\tlogger.debug(\"[ChatEvents] occupancyUpdate =>\", upd);\n\t\temitter.emit(\"occupancyUpdate\", upd);\n\t});\n\n\t// Reaction events\n\tchatClient.on(\"guestReaction\", (reaction) => {\n\t\tlogger.debug(\"[ChatEvents] guestReaction =>\", reaction);\n\t\temitter.emit(\"guestReaction\", reaction);\n\t});\n\n\t// Mute state changes\n\tchatClient.on(\"muteStateChanged\", (evt) => {\n\t\tlogger.debug(\"[ChatEvents] muteStateChanged =>\", evt);\n\t\temitter.emit(\"muteStateChanged\", evt);\n\t});\n\n\t// Speaker requests\n\tchatClient.on(\"speakerRequest\", (req) => {\n\t\tlogger.debug(\"[ChatEvents] speakerRequest =>\", req);\n\t\temitter.emit(\"speakerRequest\", req);\n\t});\n\n\t// Additional event example: new speaker accepted\n\tchatClient.on(\"newSpeakerAccepted\", (info) => {\n\t\tlogger.debug(\"[ChatEvents] newSpeakerAccepted =>\", info);\n\t\temitter.emit(\"newSpeakerAccepted\", info);\n\t});\n\n\tchatClient.on(\"newSpeakerRemoved\", (info) => {\n\t\tlogger.debug(\"[ChatEvents] newSpeakerRemoved =>\", info);\n\t\temitter.emit(\"newSpeakerRemoved\", info);\n\t});\n}\n","// src/logger.ts\n\nexport class Logger {\n\tprivate readonly debugEnabled: boolean;\n\n\tconstructor(debugEnabled: boolean) {\n\t\tthis.debugEnabled = debugEnabled;\n\t}\n\n\tinfo(msg: string, ...args: any[]) {\n\t\tconsole.log(msg, ...args);\n\t}\n\n\tdebug(msg: string, ...args: any[]) {\n\t\tif (this.debugEnabled) {\n\t\t\tconsole.log(msg, ...args);\n\t\t}\n\t}\n\n\twarn(msg: string, ...args: any[]) {\n\t\tconsole.warn(\"[WARN]\", msg, ...args);\n\t}\n\n\terror(msg: string, ...args: any[]) {\n\t\tconsole.error(msg, ...args);\n\t}\n\n\tisDebugEnabled(): boolean {\n\t\treturn this.debugEnabled;\n\t}\n}\n","// src/core/SpaceParticipant.ts\n\nimport { EventEmitter } from \"node:events\";\nimport { Logger } from \"../logger\";\nimport { ChatClient } from \"./ChatClient\";\nimport { JanusClient } from \"./JanusClient\";\nimport type { Client } from \"../../client\";\nimport type {\n\tTurnServersInfo,\n\tPlugin,\n\tPluginRegistration,\n\tAudioDataWithUser,\n} from \"../types\";\nimport {\n\taccessChat,\n\tauthorizeToken,\n\tgetTurnServers,\n\tmuteSpeaker,\n\tnegotiateGuestStream,\n\tsetupCommonChatEvents,\n\tstartWatching,\n\tstopWatching,\n\tsubmitSpeakerRequest,\n\tunmuteSpeaker,\n\tcancelSpeakerRequest,\n} from \"../utils\";\n\ninterface SpaceParticipantConfig {\n\tspaceId: string;\n\tdebug?: boolean;\n}\n\n/**\n * Manages joining an existing Space in listener mode,\n * and optionally becoming a speaker via WebRTC (Janus).\n */\nexport class SpaceParticipant extends EventEmitter {\n\tprivate readonly spaceId: string;\n\tprivate readonly debug: boolean;\n\tprivate readonly logger: Logger;\n\n\t// Basic auth/cookie data\n\tprivate cookie?: string;\n\tprivate authToken?: string;\n\n\t// Chat\n\tprivate chatJwtToken?: string;\n\tprivate chatToken?: string;\n\tprivate chatClient?: ChatClient;\n\n\t// Watch session\n\tprivate lifecycleToken?: string;\n\tprivate watchSession?: string;\n\n\t// HLS stream\n\tprivate hlsUrl?: string;\n\n\t// Speaker request + Janus\n\tprivate sessionUUID?: string;\n\tprivate janusJwt?: string;\n\tprivate webrtcGwUrl?: string;\n\tprivate janusClient?: JanusClient;\n\n\t// Plugin management\n\tprivate plugins = new Set<PluginRegistration>();\n\n\tconstructor(\n\t\tprivate readonly client: Client,\n\t\tconfig: SpaceParticipantConfig,\n\t) {\n\t\tsuper();\n\t\tthis.spaceId = config.spaceId;\n\t\tthis.debug = config.debug ?? false;\n\t\tthis.logger = new Logger(this.debug);\n\t}\n\n\t/**\n\t * Adds a plugin and calls its onAttach immediately.\n\t * init() or onJanusReady() will be invoked later at the appropriate time.\n\t */\n\tpublic use(plugin: Plugin, config?: Record<string, any>) {\n\t\tconst registration: PluginRegistration = { plugin, config };\n\t\tthis.plugins.add(registration);\n\n\t\tthis.logger.debug(\n\t\t\t\"[SpaceParticipant] Plugin added =>\",\n\t\t\tplugin.constructor.name,\n\t\t);\n\n\t\t// Call the plugin's onAttach if it exists\n\t\tplugin.onAttach?.({ space: this, pluginConfig: config });\n\n\t\tif (plugin.init) {\n\t\t\tplugin.init({ space: this, pluginConfig: config });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Joins the Space as a listener: obtains HLS, chat token, etc.\n\t */\n\tpublic async joinAsListener(): Promise<void> {\n\t\tthis.logger.info(\n\t\t\t\"[SpaceParticipant] Joining space as listener =>\",\n\t\t\tthis.spaceId,\n\t\t);\n\n\t\t// 1) Get cookie and authorize\n\t\tthis.cookie = await this.client.getPeriscopeCookie();\n\t\tthis.authToken = await authorizeToken(this.cookie);\n\n\t\t// 2) Retrieve the space metadata for mediaKey\n\t\tconst spaceMeta = await this.client.getAudioSpaceById(this.spaceId);\n\t\tconst mediaKey = spaceMeta?.metadata?.media_key;\n\t\tif (!mediaKey) {\n\t\t\tthrow new Error(\"[SpaceParticipant] No mediaKey found in metadata\");\n\t\t}\n\t\tthis.logger.debug(\"[SpaceParticipant] mediaKey =>\", mediaKey);\n\n\t\t// 3) Query live_video_stream/status for HLS URL and chat token\n\t\tconst status = await this.client.getAudioSpaceStreamStatus(mediaKey);\n\t\tthis.hlsUrl = status?.source?.location;\n\t\tthis.chatJwtToken = status?.chatToken;\n\t\tthis.lifecycleToken = status?.lifecycleToken;\n\t\tthis.logger.debug(\"[SpaceParticipant] HLS =>\", this.hlsUrl);\n\n\t\t// 4) Access the chat\n\t\tif (!this.chatJwtToken) {\n\t\t\tthrow new Error(\"[SpaceParticipant] No chatToken found\");\n\t\t}\n\t\tconst chatInfo = await accessChat(this.chatJwtToken, this.cookie!);\n\t\tthis.chatToken = chatInfo.access_token;\n\n\t\t// 5) Create and connect the ChatClient\n\t\tthis.chatClient = new ChatClient({\n\t\t\tspaceId: chatInfo.room_id,\n\t\t\taccessToken: chatInfo.access_token,\n\t\t\tendpoint: chatInfo.endpoint,\n\t\t\tlogger: this.logger,\n\t\t});\n\t\tawait this.chatClient.connect();\n\t\tthis.setupChatEvents();\n\n\t\t// 6) startWatching (to appear as a viewer)\n\t\tthis.watchSession = await startWatching(this.lifecycleToken!, this.cookie!);\n\n\t\tthis.logger.info(\"[SpaceParticipant] Joined as listener.\");\n\t}\n\n\t/**\n\t * Returns the HLS URL if you want to consume the stream as a listener.\n\t */\n\tpublic getHlsUrl(): string | undefined {\n\t\treturn this.hlsUrl;\n\t}\n\n\t/**\n\t * Submits a speaker request using /audiospace/request/submit.\n\t * Returns the sessionUUID used to track approval.\n\t */\n\tpublic async requestSpeaker(): Promise<{ sessionUUID: string }> {\n\t\tif (!this.chatJwtToken) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[SpaceParticipant] Must join as listener first (no chat token).\",\n\t\t\t);\n\t\t}\n\t\tif (!this.authToken) {\n\t\t\tthrow new Error(\"[SpaceParticipant] No auth token available.\");\n\t\t}\n\t\tif (!this.chatToken) {\n\t\t\tthrow new Error(\"[SpaceParticipant] No chat token available.\");\n\t\t}\n\n\t\tthis.logger.info(\"[SpaceParticipant] Submitting speaker request...\");\n\n\t\tconst { session_uuid } = await submitSpeakerRequest({\n\t\t\tbroadcastId: this.spaceId,\n\t\t\tchatToken: this.chatToken,\n\t\t\tauthToken: this.authToken,\n\t\t});\n\t\tthis.sessionUUID = session_uuid;\n\n\t\tthis.logger.info(\n\t\t\t\"[SpaceParticipant] Speaker request submitted =>\",\n\t\t\tsession_uuid,\n\t\t);\n\t\treturn { sessionUUID: session_uuid };\n\t}\n\n\t/**\n\t * Cancels a previously submitted speaker request using /audiospace/request/cancel.\n\t * This requires a valid sessionUUID from requestSpeaker() first.\n\t */\n\tpublic async cancelSpeakerRequest(): Promise<void> {\n\t\tif (!this.sessionUUID) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[SpaceParticipant] No sessionUUID; cannot cancel a speaker request that was never submitted.\",\n\t\t\t);\n\t\t}\n\t\tif (!this.authToken) {\n\t\t\tthrow new Error(\"[SpaceParticipant] No auth token available.\");\n\t\t}\n\t\tif (!this.chatToken) {\n\t\t\tthrow new Error(\"[SpaceParticipant] No chat token available.\");\n\t\t}\n\n\t\tawait cancelSpeakerRequest({\n\t\t\tbroadcastId: this.spaceId,\n\t\t\tsessionUUID: this.sessionUUID,\n\t\t\tchatToken: this.chatToken,\n\t\t\tauthToken: this.authToken,\n\t\t});\n\n\t\tthis.logger.info(\n\t\t\t\"[SpaceParticipant] Speaker request canceled =>\",\n\t\t\tthis.sessionUUID,\n\t\t);\n\t\tthis.sessionUUID = undefined;\n\t}\n\n\t/**\n\t * Once the host approves our speaker request, we perform Janus negotiation\n\t * to become a speaker.\n\t */\n\tpublic async becomeSpeaker(): Promise<void> {\n\t\tif (!this.sessionUUID) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[SpaceParticipant] No sessionUUID (did you call requestSpeaker()?).\",\n\t\t\t);\n\t\t}\n\t\tthis.logger.info(\n\t\t\t\"[SpaceParticipant] Negotiating speaker role via Janus...\",\n\t\t);\n\n\t\t// 1) Retrieve TURN servers\n\t\tconst turnServers: TurnServersInfo = await getTurnServers(this.cookie!);\n\t\tthis.logger.debug(\"[SpaceParticipant] turnServers =>\", turnServers);\n\n\t\t// 2) Negotiate with /audiospace/stream/negotiate\n\t\tconst nego = await negotiateGuestStream({\n\t\t\tbroadcastId: this.spaceId,\n\t\t\tsessionUUID: this.sessionUUID,\n\t\t\tauthToken: this.authToken!,\n\t\t\tcookie: this.cookie!,\n\t\t});\n\t\tthis.janusJwt = nego.janus_jwt;\n\t\tthis.webrtcGwUrl = nego.webrtc_gw_url;\n\t\tthis.logger.debug(\"[SpaceParticipant] webrtcGwUrl =>\", this.webrtcGwUrl);\n\n\t\t// 3) Create JanusClient\n\t\tthis.janusClient = new JanusClient({\n\t\t\twebrtcUrl: this.webrtcGwUrl!,\n\t\t\troomId: this.spaceId,\n\t\t\tcredential: this.janusJwt!,\n\t\t\tuserId: turnServers.username.split(\":\")[1],\n\t\t\tstreamName: this.spaceId,\n\t\t\tturnServers,\n\t\t\tlogger: this.logger,\n\t\t});\n\n\t\t// 4) Initialize the guest speaker session in Janus\n\t\tawait this.janusClient.initializeGuestSpeaker(this.sessionUUID);\n\n\t\tthis.janusClient.on(\"audioDataFromSpeaker\", (data: AudioDataWithUser) => {\n\t\t\tthis.logger.debug(\n\t\t\t\t\"[SpaceParticipant] Received speaker audio =>\",\n\t\t\t\tdata.userId,\n\t\t\t);\n\t\t\tthis.handleAudioData(data);\n\t\t});\n\n\t\tthis.logger.info(\n\t\t\t\"[SpaceParticipant] Now speaker on the Space =>\",\n\t\t\tthis.spaceId,\n\t\t);\n\n\t\t// For plugins that need direct Janus references, call onJanusReady\n\t\tfor (const { plugin } of this.plugins) {\n\t\t\tplugin.onJanusReady?.(this.janusClient);\n\t\t}\n\t}\n\n\t/**\n\t * Removes self from the speaker role and transitions back to a listener.\n\t */\n\tpublic async removeFromSpeaker(): Promise<void> {\n\t\tif (!this.sessionUUID) {\n\t\t\tthrow new Error(\n\t\t\t\t\"[SpaceParticipant] No sessionUUID; cannot remove from speaker role.\",\n\t\t\t);\n\t\t}\n\t\tif (!this.authToken || !this.chatToken) {\n\t\t\tthrow new Error(\"[SpaceParticipant] Missing authToken or chatToken.\");\n\t\t}\n\n\t\tthis.logger.info(\"[SpaceParticipant] Removing from speaker role...\");\n\n\t\t// Stop the Janus session\n\t\tif (this.janusClient) {\n\t\t\tawait this.janusClient.stop();\n\t\t\tthis.janusClient = undefined;\n\t\t}\n\n\t\tthis.logger.info(\n\t\t\t\"[SpaceParticipant] Successfully removed from speaker role.\",\n\t\t);\n\t}\n\n\t/**\n\t * Leaves the Space gracefully:\n\t * - Stop Janus if we were a speaker\n\t * - Stop watching as a viewer\n\t * - Disconnect chat\n\t */\n\tpublic async leaveSpace(): Promise<void> {\n\t\tthis.logger.info(\"[SpaceParticipant] Leaving space...\");\n\n\t\t// If speaker, stop Janus\n\t\tif (this.janusClient) {\n\t\t\tawait this.janusClient.stop();\n\t\t\tthis.janusClient = undefined;\n\t\t}\n\n\t\t// Stop watching\n\t\tif (this.watchSession && this.cookie) {\n\t\t\tawait stopWatching(this.watchSession, this.cookie);\n\t\t}\n\n\t\t// Disconnect chat\n\t\tif (this.chatClient) {\n\t\t\tawait this.chatClient.disconnect();\n\t\t\tthis.chatClient = undefined;\n\t\t}\n\n\t\tthis.logger.info(\"[SpaceParticipant] Left space =>\", this.spaceId);\n\t}\n\n\t/**\n\t * Pushes PCM audio frames if we're speaker; otherwise logs a warning.\n\t */\n\tpublic pushAudio(samples: Int16Array, sampleRate: number) {\n\t\tif (!this.janusClient) {\n\t\t\tthis.logger.warn(\n\t\t\t\t\"[SpaceParticipant] Not a speaker yet; ignoring pushAudio.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tthis.janusClient.pushLocalAudio(samples, sampleRate);\n\t}\n\n\t/**\n\t * Internal handler for incoming PCM frames from Janus, forwarded to plugin.onAudioData if present.\n\t */\n\tprivate handleAudioData(data: AudioDataWithUser) {\n\t\tfor (const { plugin } of this.plugins) {\n\t\t\tplugin.onAudioData?.(data);\n\t\t}\n\t}\n\n\t/**\n\t * Sets up chat events: \"occupancyUpdate\", \"newSpeakerAccepted\", etc.\n\t */\n\tprivate setupChatEvents() {\n\t\tif (!this.chatClient) return;\n\t\tsetupCommonChatEvents(this.chatClient, this.logger, this);\n\n\t\tthis.chatClient.on(\"newSpeakerAccepted\", ({ userId }) => {\n\t\t\tthis.logger.debug(\"[SpaceParticipant] newSpeakerAccepted =>\", userId);\n\n\t\t\t// If we haven't created Janus yet, skip\n\t\t\tif (!this.janusClient) {\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t\"[SpaceParticipant] No janusClient yet; ignoring new speaker...\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// If this is our own handle, skip\n\t\t\tif (userId === this.janusClient.getHandleId()) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Subscribe to this new speaker's audio\n\t\t\tthis.janusClient.subscribeSpeaker(userId).catch((err) => {\n\t\t\t\tthis.logger.error(\"[SpaceParticipant] subscribeSpeaker error =>\", err);\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Mute self if we are speaker: calls /audiospace/muteSpeaker with our sessionUUID.\n\t */\n\tpublic async muteSelf(): Promise<void> {\n\t\tif (!this.authToken || !this.chatToken) {\n\t\t\tthrow new Error(\"[SpaceParticipant] Missing authToken or chatToken.\");\n\t\t}\n\t\tif (!this.sessionUUID) {\n\t\t\tthrow new Error(\"[SpaceParticipant] No sessionUUID; are you a speaker?\");\n\t\t}\n\n\t\tawait muteSpeaker({\n\t\t\tbroadcastId: this.spaceId,\n\t\t\tsessionUUID: this.sessionUUID,\n\t\t\tchatToken: this.chatToken,\n\t\t\tauthToken: this.authToken,\n\t\t});\n\t\tthis.logger.info(\"[SpaceParticipant] Successfully muted self.\");\n\t}\n\n\t/**\n\t * Unmute self if we are speaker: calls /audiospace/unmuteSpeaker with our sessionUUID.\n\t */\n\tpublic async unmuteSelf(): Promise<void> {\n\t\tif (!this.authToken || !this.chatToken) {\n\t\t\tthrow new Error(\"[SpaceParticipant] Missing authToken or chatToken.\");\n\t\t}\n\t\tif (!this.sessionUUID) {\n\t\t\tthrow new Error(\"[SpaceParticipant] No sessionUUID; are you a speaker?\");\n\t\t}\n\n\t\tawait unmuteSpeaker({\n\t\t\tbroadcastId: this.spaceId,\n\t\t\tsessionUUID: this.sessionUUID,\n\t\t\tchatToken: this.chatToken,\n\t\t\tauthToken: this.authToken,\n\t\t});\n\t\tthis.logger.info(\"[SpaceParticipant] Successfully unmuted self.\");\n\t}\n}\n","import type { Plugin, AudioDataWithUser } from \"../types\";\nimport type { Space } from \"../core/Space\";\nimport { Logger } from \"../logger\";\n\n/**\n * IdleMonitorPlugin\n * -----------------\n * Monitors silence in both remote speaker audio and local (pushed) audio.\n * If no audio is detected for a specified duration, it emits an 'idleTimeout' event on the space.\n */\nexport class IdleMonitorPlugin implements Plugin {\n\tprivate space?: Space;\n\tprivate logger?: Logger;\n\n\tprivate lastSpeakerAudioMs = Date.now();\n\tprivate lastLocalAudioMs = Date.now();\n\tprivate checkInterval?: NodeJS.Timeout;\n\n\t/**\n\t * @param idleTimeoutMs The duration (in ms) of total silence before triggering idle. (Default: 60s)\n\t * @param checkEveryMs How frequently (in ms) to check for silence. (Default: 10s)\n\t */\n\tconstructor(\n\t\tprivate idleTimeoutMs = 60_000,\n\t\tprivate checkEveryMs = 10_000,\n\t) {}\n\n\t/**\n\t * Called immediately after .use(plugin).\n\t * Allows for minimal setup, including obtaining a debug logger if desired.\n\t */\n\tonAttach(params: { space: Space; pluginConfig?: Record<string, any> }): void {\n\t\tthis.space = params.space;\n\t\tconst debug = params.pluginConfig?.debug ?? false;\n\t\tthis.logger = new Logger(debug);\n\n\t\tthis.logger.info(\"[IdleMonitorPlugin] onAttach => plugin attached\");\n\t}\n\n\t/**\n\t * Called once the space has fully initialized (basic mode).\n\t * We set up idle checks and override pushAudio to detect local audio activity.\n\t */\n\tinit(params: { space: Space; pluginConfig?: Record<string, any> }): void {\n\t\tthis.space = params.space;\n\t\tthis.logger?.info(\"[IdleMonitorPlugin] init => setting up idle checks\");\n\n\t\t// Update lastSpeakerAudioMs on incoming speaker audio\n\t\t// (Here we're hooking into an event triggered by Space for each speaker's PCM data.)\n\t\tthis.space.on(\"audioDataFromSpeaker\", (_data: AudioDataWithUser) => {\n\t\t\tthis.lastSpeakerAudioMs = Date.now();\n\t\t});\n\n\t\t// Patch space.pushAudio to track local audio\n\t\tconst originalPushAudio = this.space.pushAudio.bind(this.space);\n\t\tthis.space.pushAudio = (samples, sampleRate) => {\n\t\t\tthis.lastLocalAudioMs = Date.now();\n\t\t\toriginalPushAudio(samples, sampleRate);\n\t\t};\n\n\t\t// Periodically check for silence\n\t\tthis.checkInterval = setInterval(\n\t\t\t() => this.checkIdle(),\n\t\t\tthis.checkEveryMs,\n\t\t) as any;\n\t}\n\n\t/**\n\t * Checks if we've exceeded idleTimeoutMs with no audio activity.\n\t * If so, emits an 'idleTimeout' event on the space with { idleMs } info.\n\t */\n\tprivate checkIdle() {\n\t\tconst now = Date.now();\n\t\tconst lastAudio = Math.max(this.lastSpeakerAudioMs, this.lastLocalAudioMs);\n\t\tconst idleMs = now - lastAudio;\n\n\t\tif (idleMs >= this.idleTimeoutMs) {\n\t\t\tthis.logger?.warn(\n\t\t\t\t`[IdleMonitorPlugin] idleTimeout => no audio for ${idleMs}ms`,\n\t\t\t);\n\t\t\tthis.space?.emit(\"idleTimeout\", { idleMs });\n\t\t}\n\t}\n\n\t/**\n\t * Returns how many milliseconds have passed since any audio was detected (local or speaker).\n\t */\n\tpublic getIdleTimeMs(): number {\n\t\tconst now = Date.now();\n\t\tconst lastAudio = Math.max(this.lastSpeakerAudioMs, this.lastLocalAudioMs);\n\t\treturn now - lastAudio;\n\t}\n\n\t/**\n\t * Cleans up resources (interval) when the plugin is removed or space stops.\n\t */\n\tcleanup(): void {\n\t\tthis.logger?.info(\"[IdleMonitorPlugin] cleanup => stopping idle checks\");\n\t\tif (this.checkInterval) {\n\t\t\tclearInterval(this.checkInterval);\n\t\t\tthis.checkInterval = undefined;\n\t\t}\n\t}\n}\n","// src/plugins/SttTtsPlugin.ts\n\nimport {\n\tChannelType,\n\ttype Content,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype Plugin,\n\tcreateUniqueUuid,\n\tlogger,\n} from \"@elizaos/core\";\nimport { spawn } from \"node:child_process\";\nimport type { Readable } from \"node:stream\";\nimport type { ClientBase } from \"./base\";\nimport type { AudioDataWithUser, JanusClient, Space } from \"./client\";\n\ninterface PluginConfig {\n\truntime: IAgentRuntime;\n\tclient: ClientBase;\n\tspaceId: string;\n}\n\nconst VOLUME_WINDOW_SIZE = 100;\nconst SPEAKING_THRESHOLD = 0.05;\nconst SILENCE_DETECTION_THRESHOLD_MS = 1000; // 1-second silence threshold\n\n/**\n * MVP plugin for speech-to-text (OpenAI) + conversation + TTS (ElevenLabs)\n * Approach:\n * - Collect each speaker's unmuted PCM in a memory buffer (only if above silence threshold)\n * - On speaker mute -> flush STT -> GPT -> TTS -> push to Janus\n */\nexport class SttTtsPlugin implements Plugin {\n\tname = \"SttTtsPlugin\";\n\tdescription = \"Speech-to-text (OpenAI) + conversation + TTS (ElevenLabs)\";\n\tprivate runtime: IAgentRuntime;\n\tprivate spaceId: string;\n\n\tprivate space?: Space;\n\tprivate janus?: JanusClient;\n\n\t/**\n\t * userId => arrayOfChunks (PCM Int16)\n\t */\n\tprivate pcmBuffers = new Map<string, Int16Array[]>();\n\n\t// TTS queue for sequentially speaking\n\tprivate ttsQueue: string[] = [];\n\tprivate isSpeaking = false;\n\tprivate isProcessingAudio = false;\n\n\tprivate userSpeakingTimer: NodeJS.Timer | null = null;\n\tprivate volumeBuffers: Map<string, number[]>;\n\tprivate ttsAbortController: AbortController | null = null;\n\n\tonAttach(_space: Space) {\n\t\tlogger.log(\"[SttTtsPlugin] onAttach => space was attached\");\n\t}\n\n\tasync init(params): Promise<void> {\n\t\tlogger.log(\n\t\t\t\"[SttTtsPlugin] init => Space fully ready. Subscribing to events.\",\n\t\t);\n\n\t\tthis.space = params.space;\n\t\tthis.janus = (this.space as any)?.janusClient as JanusClient | undefined;\n\n\t\tconst config = params.pluginConfig as PluginConfig;\n\t\tthis.runtime = config?.runtime;\n\t\tthis.spaceId = config?.spaceId;\n\n\t\tthis.volumeBuffers = new Map<string, number[]>();\n\t}\n\n\t/**\n\t * Called whenever we receive PCM from a speaker\n\t */\n\tonAudioData(data: AudioDataWithUser): void {\n\t\tif (this.isProcessingAudio) {\n\t\t\treturn;\n\t\t}\n\t\t/**\n\t\t * For ignoring near-silence frames (if amplitude < threshold)\n\t\t */\n\t\tconst silenceThreshold = 50;\n\t\tlet maxVal = 0;\n\t\tfor (let i = 0; i < data.samples.length; i++) {\n\t\t\tconst val = Math.abs(data.samples[i]);\n\t\t\tif (val > maxVal) maxVal = val;\n\t\t}\n\t\tif (maxVal < silenceThreshold) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (this.userSpeakingTimer) {\n\t\t\tclearTimeout(this.userSpeakingTimer);\n\t\t}\n\n\t\tlet arr = this.pcmBuffers.get(data.userId);\n\t\tif (!arr) {\n\t\t\tarr = [];\n\t\t\tthis.pcmBuffers.set(data.userId, arr);\n\t\t}\n\t\tarr.push(data.samples);\n\n\t\tif (!this.isSpeaking) {\n\t\t\tthis.userSpeakingTimer = setTimeout(() => {\n\t\t\t\tlogger.log(\n\t\t\t\t\t\"[SttTtsPlugin] start processing audio for user =>\",\n\t\t\t\t\tdata.userId,\n\t\t\t\t);\n\t\t\t\tthis.userSpeakingTimer = null;\n\t\t\t\tthis.processAudio(data.userId).catch((err) =>\n\t\t\t\t\tlogger.error(\"[SttTtsPlugin] handleSilence error =>\", err),\n\t\t\t\t);\n\t\t\t}, SILENCE_DETECTION_THRESHOLD_MS);\n\t\t} else {\n\t\t\t// check interruption\n\t\t\tlet volumeBuffer = this.volumeBuffers.get(data.userId);\n\t\t\tif (!volumeBuffer) {\n\t\t\t\tvolumeBuffer = [];\n\t\t\t\tthis.volumeBuffers.set(data.userId, volumeBuffer);\n\t\t\t}\n\t\t\tconst samples = new Int16Array(\n\t\t\t\tdata.samples.buffer,\n\t\t\t\tdata.samples.byteOffset,\n\t\t\t\tdata.samples.length / 2,\n\t\t\t);\n\t\t\tconst maxAmplitude = Math.max(...samples.map(Math.abs)) / 32768;\n\t\t\tvolumeBuffer.push(maxAmplitude);\n\n\t\t\tif (volumeBuffer.length > VOLUME_WINDOW_SIZE) {\n\t\t\t\tvolumeBuffer.shift();\n\t\t\t}\n\t\t\tconst avgVolume =\n\t\t\t\tvolumeBuffer.reduce((sum, v) => sum + v, 0) / VOLUME_WINDOW_SIZE;\n\n\t\t\tif (avgVolume > SPEAKING_THRESHOLD) {\n\t\t\t\tvolumeBuffer.length = 0;\n\t\t\t\tif (this.ttsAbortController) {\n\t\t\t\t\tthis.ttsAbortController.abort();\n\t\t\t\t\tthis.isSpeaking = false;\n\t\t\t\t\tlogger.log(\"[SttTtsPlugin] TTS playback interrupted\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// /src/sttTtsPlugin.ts\n\tprivate async convertPcmToWavInMemory(\n\t\tpcmData: Int16Array,\n\t\tsampleRate: number,\n\t): Promise<ArrayBuffer> {\n\t\t// number of channels\n\t\tconst numChannels = 1;\n\t\t// byte rate = (sampleRate * numChannels * bitsPerSample/8)\n\t\tconst byteRate = sampleRate * numChannels * 2;\n\t\tconst blockAlign = numChannels * 2;\n\t\t// data chunk size = pcmData.length * (bitsPerSample/8)\n\t\tconst dataSize = pcmData.length * 2;\n\n\t\t// WAV header is 44 bytes\n\t\tconst buffer = new ArrayBuffer(44 + dataSize);\n\t\tconst view = new DataView(buffer);\n\n\t\t// RIFF chunk descriptor\n\t\tthis.writeString(view, 0, \"RIFF\");\n\t\tview.setUint32(4, 36 + dataSize, true); // file size - 8\n\t\tthis.writeString(view, 8, \"WAVE\");\n\n\t\t// fmt sub-chunk\n\t\tthis.writeString(view, 12, \"fmt \");\n\t\tview.setUint32(16, 16, true); // Subchunk1Size (16 for PCM)\n\t\tview.setUint16(20, 1, true); // AudioFormat (1 = PCM)\n\t\tview.setUint16(22, numChannels, true); // NumChannels\n\t\tview.setUint32(24, sampleRate, true); // SampleRate\n\t\tview.setUint32(28, byteRate, true); // ByteRate\n\t\tview.setUint16(32, blockAlign, true); // BlockAlign\n\t\tview.setUint16(34, 16, true); // BitsPerSample (16)\n\n\t\t// data sub-chunk\n\t\tthis.writeString(view, 36, \"data\");\n\t\tview.setUint32(40, dataSize, true);\n\n\t\t// Write PCM samples\n\t\tlet offset = 44;\n\t\tfor (let i = 0; i < pcmData.length; i++, offset += 2) {\n\t\t\tview.setInt16(offset, pcmData[i], true);\n\t\t}\n\n\t\treturn buffer;\n\t}\n\n\tprivate writeString(view: DataView, offset: number, text: string) {\n\t\tfor (let i = 0; i < text.length; i++) {\n\t\t\tview.setUint8(offset + i, text.charCodeAt(i));\n\t\t}\n\t}\n\n\t/**\n\t * On speaker silence => flush STT => GPT => TTS => push to Janus\n\t */\n\tprivate async processAudio(userId: string): Promise<void> {\n\t\tif (this.isProcessingAudio) {\n\t\t\treturn;\n\t\t}\n\t\tthis.isProcessingAudio = true;\n\t\ttry {\n\t\t\tlogger.log(\"[SttTtsPlugin] Starting audio processing for user:\", userId);\n\t\t\tconst chunks = this.pcmBuffers.get(userId) || [];\n\t\t\tthis.pcmBuffers.clear();\n\n\t\t\tif (!chunks.length) {\n\t\t\t\tlogger.warn(\"[SttTtsPlugin] No audio chunks for user =>\", userId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlogger.log(\n\t\t\t\t`[SttTtsPlugin] Flushing STT buffer for user=${userId}, chunks=${chunks.length}`,\n\t\t\t);\n\n\t\t\tconst totalLen = chunks.reduce((acc, c) => acc + c.length, 0);\n\t\t\tconst merged = new Int16Array(totalLen);\n\t\t\tlet offset = 0;\n\t\t\tfor (const c of chunks) {\n\t\t\t\tmerged.set(c, offset);\n\t\t\t\toffset += c.length;\n\t\t\t}\n\n\t\t\t// Convert PCM to WAV for STT\n\t\t\tconst wavBuffer = await this.convertPcmToWavInMemory(merged, 48000);\n\n\t\t\t// Whisper STT\n\t\t\tconst sttText = await this.runtime.useModel(\n\t\t\t\tModelTypes.TRANSCRIPTION,\n\t\t\t\twavBuffer,\n\t\t\t);\n\n\t\t\tlogger.log(`[SttTtsPlugin] Transcription result: \"${sttText}\"`);\n\n\t\t\tif (!sttText || !sttText.trim()) {\n\t\t\t\tlogger.warn(\"[SttTtsPlugin] No speech recognized for user =>\", userId);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlogger.log(`[SttTtsPlugin] STT => user=${userId}, text=\"${sttText}\"`);\n\n\t\t\t// Get response\n\t\t\tawait this.handleUserMessage(sttText, userId);\n\t\t} catch (error) {\n\t\t\tlogger.error(\"[SttTtsPlugin] processAudio error =>\", error);\n\t\t} finally {\n\t\t\tthis.isProcessingAudio = false;\n\t\t}\n\t}\n\n\t/**\n\t * Public method to queue a TTS request\n\t */\n\tpublic async speakText(text: string): Promise<void> {\n\t\tthis.ttsQueue.push(text);\n\t\tif (!this.isSpeaking) {\n\t\t\tthis.isSpeaking = true;\n\t\t\tthis.processTtsQueue().catch((err) => {\n\t\t\t\tlogger.error(\"[SttTtsPlugin] processTtsQueue error =>\", err);\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Process TTS requests one by one\n\t */\n\tprivate async processTtsQueue(): Promise<void> {\n\t\twhile (this.ttsQueue.length > 0) {\n\t\t\tconst text = this.ttsQueue.shift();\n\t\t\tif (!text) continue;\n\n\t\t\tthis.ttsAbortController = new AbortController();\n\t\t\tconst { signal } = this.ttsAbortController;\n\n\t\t\ttry {\n\t\t\t\tconst responseStream = await this.runtime.useModel(\n\t\t\t\t\tModelTypes.TEXT_TO_SPEECH,\n\t\t\t\t\ttext,\n\t\t\t\t);\n\t\t\t\tif (!responseStream) {\n\t\t\t\t\tlogger.error(\"[SttTtsPlugin] TTS responseStream is null\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tlogger.log(\"[SttTtsPlugin] Received ElevenLabs TTS stream\");\n\n\t\t\t\t// Convert the Readable Stream to PCM and stream to Janus\n\t\t\t\tawait this.streamTtsStreamToJanus(responseStream, 48000, signal);\n\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tlogger.log(\"[SttTtsPlugin] TTS interrupted after streaming\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tlogger.error(\"[SttTtsPlugin] TTS streaming error =>\", err);\n\t\t\t} finally {\n\t\t\t\t// Clean up the AbortController\n\t\t\t\tthis.ttsAbortController = null;\n\t\t\t}\n\t\t}\n\t\tthis.isSpeaking = false;\n\t}\n\n\t/**\n\t * Handle User Message\n\t */\n\tprivate async handleUserMessage(\n\t\tuserText: string,\n\t\tuserId: string, // This is the raw Twitter user ID like 'tw-1865462035586142208'\n\t): Promise<string> {\n\t\tif (!userText || userText.trim() === \"\") {\n\t\t\treturn null;\n\t\t}\n\n\t\t// Extract the numeric ID part\n\t\tconst numericId = userId.replace(\"tw-\", \"\");\n\t\tconst roomId = createUniqueUuid(\n\t\t\tthis.runtime,\n\t\t\t`twitter_generate_room-${this.spaceId}`,\n\t\t);\n\n\t\t// Create consistent UUID for the user\n\t\tconst userUuid = createUniqueUuid(this.runtime, numericId);\n\n\t\tconst entity = await this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getEntityById(userUuid);\n\t\tif (!entity) {\n\t\t\tawait this.runtime.getDatabaseAdapter().createEntity({\n\t\t\t\tid: userUuid,\n\t\t\t\tnames: [userId],\n\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t});\n\t\t}\n\n\t\t// Ensure room exists and user is in it\n\t\tawait this.runtime.ensureRoomExists({\n\t\t\tid: roomId,\n\t\t\tname: \"Twitter Space\",\n\t\t\tsource: \"twitter\",\n\t\t\ttype: ChannelType.VOICE_GROUP,\n\t\t\tchannelId: null,\n\t\t\tserverId: this.spaceId,\n\t\t});\n\t\tawait this.runtime.ensureParticipantInRoom(userUuid, roomId);\n\n\t\tconst memory = {\n\t\t\tid: createUniqueUuid(\n\t\t\t\tthis.runtime,\n\t\t\t\t`${roomId}-voice-message-${Date.now()}`,\n\t\t\t),\n\t\t\tagentId: this.runtime.agentId,\n\t\t\tcontent: {\n\t\t\t\ttext: userText,\n\t\t\t\tsource: \"twitter\",\n\t\t\t},\n\t\t\tuserId: userUuid,\n\t\t\troomId,\n\t\t\tcreatedAt: Date.now(),\n\t\t};\n\n\t\tconst callback: HandlerCallback = async (\n\t\t\tcontent: Content,\n\t\t\t_files: any[] = [],\n\t\t) => {\n\t\t\ttry {\n\t\t\t\tconst responseMemory: Memory = {\n\t\t\t\t\tid: createUniqueUuid(\n\t\t\t\t\t\tthis.runtime,\n\t\t\t\t\t\t`${memory.id}-voice-response-${Date.now()}`,\n\t\t\t\t\t),\n\t\t\t\t\tentityId: this.runtime.agentId,\n\t\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\t...content,\n\t\t\t\t\t\tuser: this.runtime.character.name,\n\t\t\t\t\t\tinReplyTo: memory.id,\n\t\t\t\t\t\tisVoiceMessage: true,\n\t\t\t\t\t},\n\t\t\t\t\troomId,\n\t\t\t\t\tcreatedAt: Date.now(),\n\t\t\t\t};\n\n\t\t\t\tif (responseMemory.content.text?.trim()) {\n\t\t\t\t\tawait this.runtime\n\t\t\t\t\t\t.getMemoryManager(\"messages\")\n\t\t\t\t\t\t.createMemory(responseMemory);\n\t\t\t\t\tthis.isProcessingAudio = false;\n\t\t\t\t\tthis.volumeBuffers.clear();\n\t\t\t\t\tawait this.speakText(content.text);\n\t\t\t\t}\n\n\t\t\t\treturn [responseMemory];\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Error in voice message callback:\", error);\n\t\t\t\treturn [];\n\t\t\t}\n\t\t};\n\n\t\t// Emit voice-specific events\n\t\tthis.runtime.emitEvent([\"VOICE_MESSAGE_RECEIVED\"], {\n\t\t\truntime: this.runtime,\n\t\t\tmessage: memory,\n\t\t\tcallback,\n\t\t});\n\t}\n\n\t/**\n\t * Convert MP3 => PCM via ffmpeg\n\t */\n\tprivate convertMp3ToPcm(\n\t\tmp3Buf: Buffer,\n\t\toutRate: number,\n\t): Promise<Int16Array> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst ff = spawn(\"ffmpeg\", [\n\t\t\t\t\"-i\",\n\t\t\t\t\"pipe:0\",\n\t\t\t\t\"-f\",\n\t\t\t\t\"s16le\",\n\t\t\t\t\"-ar\",\n\t\t\t\toutRate.toString(),\n\t\t\t\t\"-ac\",\n\t\t\t\t\"1\",\n\t\t\t\t\"pipe:1\",\n\t\t\t]);\n\t\t\tlet raw = Buffer.alloc(0);\n\n\t\t\tff.stdout.on(\"data\", (chunk: Buffer) => {\n\t\t\t\traw = Buffer.concat([raw, chunk]);\n\t\t\t});\n\t\t\tff.stderr.on(\"data\", () => {\n\t\t\t\t// ignoring ffmpeg logs\n\t\t\t});\n\t\t\tff.on(\"close\", (code) => {\n\t\t\t\tif (code !== 0) {\n\t\t\t\t\treject(new Error(`ffmpeg error code=${code}`));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst samples = new Int16Array(\n\t\t\t\t\traw.buffer,\n\t\t\t\t\traw.byteOffset,\n\t\t\t\t\traw.byteLength / 2,\n\t\t\t\t);\n\t\t\t\tresolve(samples);\n\t\t\t});\n\n\t\t\tff.stdin.write(mp3Buf);\n\t\t\tff.stdin.end();\n\t\t});\n\t}\n\n\t/**\n\t * Push PCM back to Janus in small frames\n\t * We'll do 10ms @48k => 960 samples per frame\n\t */\n\tprivate async streamToJanus(\n\t\tsamples: Int16Array,\n\t\tsampleRate: number,\n\t): Promise<void> {\n\t\t// TODO: Check if better than 480 fixed\n\t\tconst FRAME_SIZE = Math.floor(sampleRate * 0.01); // 10ms frames => 480 @48kHz\n\n\t\tfor (\n\t\t\tlet offset = 0;\n\t\t\toffset + FRAME_SIZE <= samples.length;\n\t\t\toffset += FRAME_SIZE\n\t\t) {\n\t\t\tif (this.ttsAbortController?.signal.aborted) {\n\t\t\t\tlogger.log(\"[SttTtsPlugin] streamToJanus interrupted\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst frame = new Int16Array(FRAME_SIZE);\n\t\t\tframe.set(samples.subarray(offset, offset + FRAME_SIZE));\n\t\t\tthis.janus?.pushLocalAudio(frame, sampleRate, 1);\n\n\t\t\t// Short pause so we don't overload\n\t\t\tawait new Promise((r) => setTimeout(r, 10));\n\t\t}\n\t}\n\n\tprivate async streamTtsStreamToJanus(\n\t\tstream: Readable,\n\t\tsampleRate: number,\n\t\tsignal: AbortSignal,\n\t): Promise<void> {\n\t\tconst chunks: Buffer[] = [];\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tstream.on(\"data\", (chunk: Buffer) => {\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tlogger.log(\"[SttTtsPlugin] Stream aborted, stopping playback\");\n\t\t\t\t\tstream.destroy();\n\t\t\t\t\treject(new Error(\"TTS streaming aborted\"));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tchunks.push(chunk);\n\t\t\t});\n\n\t\t\tstream.on(\"end\", async () => {\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tlogger.log(\"[SttTtsPlugin] Stream ended but was aborted\");\n\t\t\t\t\treturn reject(new Error(\"TTS streaming aborted\"));\n\t\t\t\t}\n\n\t\t\t\tconst mp3Buffer = Buffer.concat(chunks);\n\n\t\t\t\ttry {\n\t\t\t\t\t// Convert MP3 to PCM\n\t\t\t\t\tconst pcmSamples = await this.convertMp3ToPcm(mp3Buffer, sampleRate);\n\n\t\t\t\t\t// Stream PCM to Janus\n\t\t\t\t\tawait this.streamToJanus(pcmSamples, sampleRate);\n\t\t\t\t\tresolve();\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tstream.on(\"error\", (error) => {\n\t\t\t\tlogger.error(\"[SttTtsPlugin] Error in TTS stream\", error);\n\t\t\t\treject(error);\n\t\t\t});\n\t\t});\n\t}\n\n\tcleanup(): void {\n\t\tlogger.log(\"[SttTtsPlugin] cleanup => releasing resources\");\n\t\tthis.pcmBuffers.clear();\n\t\tthis.userSpeakingTimer = null;\n\t\tthis.ttsQueue = [];\n\t\tthis.isSpeaking = false;\n\t\tthis.volumeBuffers.clear();\n\t}\n}\n","import type { Media, ModelType, State } from \"@elizaos/core\";\nimport {\n\tChannelType,\n\ttype Content,\n\ttype IAgentRuntime,\n\ttype Memory,\n\tModelTypes,\n\ttype UUID,\n\tcomposePrompt,\n\tcreateUniqueUuid,\n\tlogger,\n} from \"@elizaos/core\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { ClientBase } from \"./base\";\nimport type { Tweet } from \"./client\";\nimport type { SttTtsPlugin } from \"./sttTtsSpaces\";\nimport type { ActionResponse, MediaData } from \"./types\";\n\nexport const wait = (minTime = 1000, maxTime = 3000) => {\n\tconst waitTime =\n\t\tMath.floor(Math.random() * (maxTime - minTime + 1)) + minTime;\n\treturn new Promise((resolve) => setTimeout(resolve, waitTime));\n};\n\nexport const isValidTweet = (tweet: Tweet): boolean => {\n\t// Filter out tweets with too many hashtags, @s, or $ signs, probably spam or garbage\n\tconst hashtagCount = (tweet.text?.match(/#/g) || []).length;\n\tconst atCount = (tweet.text?.match(/@/g) || []).length;\n\tconst dollarSignCount = (tweet.text?.match(/\\$/g) || []).length;\n\tconst totalCount = hashtagCount + atCount + dollarSignCount;\n\n\treturn (\n\t\thashtagCount <= 1 && atCount <= 2 && dollarSignCount <= 1 && totalCount <= 3\n\t);\n};\n\nexport async function buildConversationThread(\n\ttweet: Tweet,\n\tclient: ClientBase,\n\tmaxReplies = 10,\n): Promise<Tweet[]> {\n\tconst thread: Tweet[] = [];\n\tconst visited: Set<string> = new Set();\n\n\tasync function processThread(currentTweet: Tweet, depth = 0) {\n\t\tlogger.debug(\"Processing tweet:\", {\n\t\t\tid: currentTweet.id,\n\t\t\tinReplyToStatusId: currentTweet.inReplyToStatusId,\n\t\t\tdepth: depth,\n\t\t});\n\n\t\tif (!currentTweet) {\n\t\t\tlogger.debug(\"No current tweet found for thread building\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Stop if we've reached our reply limit\n\t\tif (depth >= maxReplies) {\n\t\t\tlogger.debug(\"Reached maximum reply depth\", depth);\n\t\t\treturn;\n\t\t}\n\n\t\t// Handle memory storage\n\t\tconst memory = await client.runtime\n\t\t\t.getMemoryManager(\"messages\")\n\t\t\t.getMemoryById(createUniqueUuid(this.runtime, currentTweet.id));\n\t\tif (!memory) {\n\t\t\tconst roomId = createUniqueUuid(\n\t\t\t\tthis.runtime,\n\t\t\t\tcurrentTweet.conversationId,\n\t\t\t);\n\t\t\tconst entityId = createUniqueUuid(this.runtime, currentTweet.userId);\n\n\t\t\tawait client.runtime.ensureConnection({\n\t\t\t\tentityId,\n\t\t\t\troomId,\n\t\t\t\tuserName: currentTweet.username,\n\t\t\t\tname: currentTweet.name,\n\t\t\t\tsource: \"twitter\",\n\t\t\t\ttype: ChannelType.GROUP,\n\t\t\t});\n\n\t\t\tawait client.runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\tid: createUniqueUuid(this.runtime, currentTweet.id),\n\t\t\t\tagentId: client.runtime.agentId,\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: currentTweet.text,\n\t\t\t\t\tsource: \"twitter\",\n\t\t\t\t\turl: currentTweet.permanentUrl,\n\t\t\t\t\timageUrls: currentTweet.photos.map((p) => p.url) || [],\n\t\t\t\t\tinReplyTo: currentTweet.inReplyToStatusId\n\t\t\t\t\t\t? createUniqueUuid(this.runtime, currentTweet.inReplyToStatusId)\n\t\t\t\t\t\t: undefined,\n\t\t\t\t},\n\t\t\t\tcreatedAt: currentTweet.timestamp * 1000,\n\t\t\t\troomId,\n\t\t\t\tentityId:\n\t\t\t\t\tcurrentTweet.userId === client.profile.id\n\t\t\t\t\t\t? client.runtime.agentId\n\t\t\t\t\t\t: createUniqueUuid(this.runtime, currentTweet.userId),\n\t\t\t});\n\t\t}\n\n\t\tif (visited.has(currentTweet.id)) {\n\t\t\tlogger.debug(\"Already visited tweet:\", currentTweet.id);\n\t\t\treturn;\n\t\t}\n\n\t\tvisited.add(currentTweet.id);\n\t\tthread.unshift(currentTweet);\n\n\t\tlogger.debug(\"Current thread state:\", {\n\t\t\tlength: thread.length,\n\t\t\tcurrentDepth: depth,\n\t\t\ttweetId: currentTweet.id,\n\t\t});\n\n\t\t// If there's a parent tweet, fetch and process it\n\t\tif (currentTweet.inReplyToStatusId) {\n\t\t\tlogger.debug(\"Fetching parent tweet:\", currentTweet.inReplyToStatusId);\n\t\t\ttry {\n\t\t\t\tconst parentTweet = await client.twitterClient.getTweet(\n\t\t\t\t\tcurrentTweet.inReplyToStatusId,\n\t\t\t\t);\n\n\t\t\t\tif (parentTweet) {\n\t\t\t\t\tlogger.debug(\"Found parent tweet:\", {\n\t\t\t\t\t\tid: parentTweet.id,\n\t\t\t\t\t\ttext: parentTweet.text?.slice(0, 50),\n\t\t\t\t\t});\n\t\t\t\t\tawait processThread(parentTweet, depth + 1);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t\"No parent tweet found for:\",\n\t\t\t\t\t\tcurrentTweet.inReplyToStatusId,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"Error fetching parent tweet:\", {\n\t\t\t\t\ttweetId: currentTweet.inReplyToStatusId,\n\t\t\t\t\terror,\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.debug(\"Reached end of reply chain at:\", currentTweet.id);\n\t\t}\n\t}\n\n\tawait processThread(tweet, 0);\n\n\tlogger.debug(\"Final thread built:\", {\n\t\ttotalTweets: thread.length,\n\t\ttweetIds: thread.map((t) => ({\n\t\t\tid: t.id,\n\t\t\ttext: t.text?.slice(0, 50),\n\t\t})),\n\t});\n\n\treturn thread;\n}\n\nexport async function fetchMediaData(\n\tattachments: Media[],\n): Promise<MediaData[]> {\n\treturn Promise.all(\n\t\tattachments.map(async (attachment: Media) => {\n\t\t\tif (/^(http|https):\\/\\//.test(attachment.url)) {\n\t\t\t\t// Handle HTTP URLs\n\t\t\t\tconst response = await fetch(attachment.url);\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tthrow new Error(`Failed to fetch file: ${attachment.url}`);\n\t\t\t\t}\n\t\t\t\tconst mediaBuffer = Buffer.from(await response.arrayBuffer());\n\t\t\t\tconst mediaType = attachment.contentType;\n\t\t\t\treturn { data: mediaBuffer, mediaType };\n\t\t\t}\n\t\t\tif (fs.existsSync(attachment.url)) {\n\t\t\t\t// Handle local file paths\n\t\t\t\tconst mediaBuffer = await fs.promises.readFile(\n\t\t\t\t\tpath.resolve(attachment.url),\n\t\t\t\t);\n\t\t\t\tconst mediaType = attachment.contentType;\n\t\t\t\treturn { data: mediaBuffer, mediaType };\n\t\t\t}\n\t\t\tthrow new Error(\n\t\t\t\t`File not found: ${attachment.url}. Make sure the path is correct.`,\n\t\t\t);\n\t\t}),\n\t);\n}\n\nexport async function sendTweet(\n\tclient: ClientBase,\n\tcontent: Content,\n\troomId: UUID,\n\ttwitterUsername: string,\n\tinReplyTo: string,\n): Promise<Memory[]> {\n\tconst isLongTweet = content.text.length > 280 - 1;\n\n\tconst tweetChunks = splitTweetContent(content.text, 280 - 1);\n\tconst sentTweets: Tweet[] = [];\n\tlet previousTweetId = inReplyTo;\n\n\tfor (const chunk of tweetChunks) {\n\t\tlet mediaData = null;\n\n\t\tif (content.attachments && content.attachments.length > 0) {\n\t\t\tmediaData = await fetchMediaData(content.attachments);\n\t\t}\n\n\t\tconst cleanChunk = deduplicateMentions(chunk.trim());\n\n\t\tconst result = await client.requestQueue.add(async () =>\n\t\t\tisLongTweet\n\t\t\t\t? client.twitterClient.sendLongTweet(\n\t\t\t\t\t\tcleanChunk,\n\t\t\t\t\t\tpreviousTweetId,\n\t\t\t\t\t\tmediaData,\n\t\t\t\t\t)\n\t\t\t\t: client.twitterClient.sendTweet(\n\t\t\t\t\t\tcleanChunk,\n\t\t\t\t\t\tpreviousTweetId,\n\t\t\t\t\t\tmediaData,\n\t\t\t\t\t),\n\t\t);\n\n\t\tconst body = await result.json();\n\t\tconst tweetResult = isLongTweet\n\t\t\t? body?.data?.notetweet_create?.tweet_results?.result\n\t\t\t: body?.data?.create_tweet?.tweet_results?.result;\n\n\t\t// if we have a response\n\t\tif (tweetResult) {\n\t\t\t// Parse the response\n\t\t\tconst finalTweet: Tweet = {\n\t\t\t\tid: tweetResult.rest_id,\n\t\t\t\ttext: tweetResult.legacy.full_text,\n\t\t\t\tconversationId: tweetResult.legacy.conversation_id_str,\n\t\t\t\ttimestamp: new Date(tweetResult.legacy.created_at).getTime() / 1000,\n\t\t\t\tuserId: tweetResult.legacy.user_id_str,\n\t\t\t\tinReplyToStatusId: tweetResult.legacy.in_reply_to_status_id_str,\n\t\t\t\tpermanentUrl: `https://twitter.com/${twitterUsername}/status/${tweetResult.rest_id}`,\n\t\t\t\thashtags: [],\n\t\t\t\tmentions: [],\n\t\t\t\tphotos: [],\n\t\t\t\tthread: [],\n\t\t\t\turls: [],\n\t\t\t\tvideos: [],\n\t\t\t};\n\t\t\tsentTweets.push(finalTweet);\n\t\t\tpreviousTweetId = finalTweet.id;\n\t\t} else {\n\t\t\tlogger.error(\"Error sending tweet chunk:\", {\n\t\t\t\tchunk,\n\t\t\t\tresponse: body,\n\t\t\t});\n\t\t}\n\n\t\t// Wait a bit between tweets to avoid rate limiting issues\n\t\tawait wait(1000, 2000);\n\t}\n\n\tconst memories: Memory[] = sentTweets.map((tweet) => ({\n\t\tid: createUniqueUuid(client.runtime, tweet.id),\n\t\tagentId: client.runtime.agentId,\n\t\tentityId: client.runtime.agentId,\n\t\tcontent: {\n\t\t\ttweetId: tweet.id,\n\t\t\ttext: tweet.text,\n\t\t\tsource: \"twitter\",\n\t\t\turl: tweet.permanentUrl,\n\t\t\timageUrls: tweet.photos.map((p) => p.url) || [],\n\t\t\tinReplyTo: tweet.inReplyToStatusId\n\t\t\t\t? createUniqueUuid(client.runtime, tweet.inReplyToStatusId)\n\t\t\t\t: undefined,\n\t\t},\n\t\troomId,\n\t\tcreatedAt: tweet.timestamp * 1000,\n\t}));\n\n\treturn memories;\n}\n\nfunction splitTweetContent(content: string, maxLength: number): string[] {\n\tconst paragraphs = content.split(\"\\n\\n\").map((p) => p.trim());\n\tconst tweets: string[] = [];\n\tlet currentTweet = \"\";\n\n\tfor (const paragraph of paragraphs) {\n\t\tif (!paragraph) continue;\n\n\t\tif (`${currentTweet}\\n\\n${paragraph}`.trim().length <= maxLength) {\n\t\t\tif (currentTweet) {\n\t\t\t\tcurrentTweet += `\\n\\n${paragraph}`;\n\t\t\t} else {\n\t\t\t\tcurrentTweet = paragraph;\n\t\t\t}\n\t\t} else {\n\t\t\tif (currentTweet) {\n\t\t\t\ttweets.push(currentTweet.trim());\n\t\t\t}\n\t\t\tif (paragraph.length <= maxLength) {\n\t\t\t\tcurrentTweet = paragraph;\n\t\t\t} else {\n\t\t\t\t// Split long paragraph into smaller chunks\n\t\t\t\tconst chunks = splitParagraph(paragraph, maxLength);\n\t\t\t\ttweets.push(...chunks.slice(0, -1));\n\t\t\t\tcurrentTweet = chunks[chunks.length - 1];\n\t\t\t}\n\t\t}\n\t}\n\n\tif (currentTweet) {\n\t\ttweets.push(currentTweet.trim());\n\t}\n\n\treturn tweets;\n}\n\nfunction extractUrls(paragraph: string): {\n\ttextWithPlaceholders: string;\n\tplaceholderMap: Map<string, string>;\n} {\n\t// replace https urls with placeholder\n\tconst urlRegex = /https?:\\/\\/[^\\s]+/g;\n\tconst placeholderMap = new Map<string, string>();\n\n\tlet urlIndex = 0;\n\tconst textWithPlaceholders = paragraph.replace(urlRegex, (match) => {\n\t\t// twitter url would be considered as 23 characters\n\t\t// <<URL_CONSIDERER_23_1>> is also 23 characters\n\t\tconst placeholder = `<<URL_CONSIDERER_23_${urlIndex}>>`; // Placeholder without . ? ! etc\n\t\tplaceholderMap.set(placeholder, match);\n\t\turlIndex++;\n\t\treturn placeholder;\n\t});\n\n\treturn { textWithPlaceholders, placeholderMap };\n}\n\nfunction splitSentencesAndWords(text: string, maxLength: number): string[] {\n\t// Split by periods, question marks and exclamation marks\n\t// Note that URLs in text have been replaced with `<<URL_xxx>>` and won't be split by dots\n\tconst sentences = text.match(/[^.!?]+[.!?]+|[^.!?]+$/g) || [text];\n\tconst chunks: string[] = [];\n\tlet currentChunk = \"\";\n\n\tfor (const sentence of sentences) {\n\t\tif (`${currentChunk} ${sentence}`.trim().length <= maxLength) {\n\t\t\tif (currentChunk) {\n\t\t\t\tcurrentChunk += ` ${sentence}`;\n\t\t\t} else {\n\t\t\t\tcurrentChunk = sentence;\n\t\t\t}\n\t\t} else {\n\t\t\t// Can't fit more, push currentChunk to results\n\t\t\tif (currentChunk) {\n\t\t\t\tchunks.push(currentChunk.trim());\n\t\t\t}\n\n\t\t\t// If current sentence itself is less than or equal to maxLength\n\t\t\tif (sentence.length <= maxLength) {\n\t\t\t\tcurrentChunk = sentence;\n\t\t\t} else {\n\t\t\t\t// Need to split sentence by spaces\n\t\t\t\tconst words = sentence.split(\" \");\n\t\t\t\tcurrentChunk = \"\";\n\t\t\t\tfor (const word of words) {\n\t\t\t\t\tif (`${currentChunk} ${word}`.trim().length <= maxLength) {\n\t\t\t\t\t\tif (currentChunk) {\n\t\t\t\t\t\t\tcurrentChunk += ` ${word}`;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tcurrentChunk = word;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (currentChunk) {\n\t\t\t\t\t\t\tchunks.push(currentChunk.trim());\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcurrentChunk = word;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Handle remaining content\n\tif (currentChunk) {\n\t\tchunks.push(currentChunk.trim());\n\t}\n\n\treturn chunks;\n}\n\nfunction deduplicateMentions(paragraph: string) {\n\t// Regex to match mentions at the beginning of the string\n\tconst mentionRegex = /^@(\\w+)(?:\\s+@(\\w+))*(\\s+|$)/;\n\n\t// Find all matches\n\tconst matches = paragraph.match(mentionRegex);\n\n\tif (!matches) {\n\t\treturn paragraph; // If no matches, return the original string\n\t}\n\n\t// Extract mentions from the match groups\n\tlet mentions = matches.slice(0, 1)[0].trim().split(\" \");\n\n\t// Deduplicate mentions\n\tmentions = Array.from(new Set(mentions));\n\n\t// Reconstruct the string with deduplicated mentions\n\tconst uniqueMentionsString = mentions.join(\" \");\n\n\t// Find where the mentions end in the original string\n\tconst endOfMentions = paragraph.indexOf(matches[0]) + matches[0].length;\n\n\t// Construct the result by combining unique mentions with the rest of the string\n\treturn `${uniqueMentionsString} ${paragraph.slice(endOfMentions)}`;\n}\n\nfunction restoreUrls(\n\tchunks: string[],\n\tplaceholderMap: Map<string, string>,\n): string[] {\n\treturn chunks.map((chunk) => {\n\t\t// Replace all <<URL_CONSIDERER_23_>> in chunk back to original URLs using regex\n\t\treturn chunk.replace(/<<URL_CONSIDERER_23_(\\d+)>>/g, (match) => {\n\t\t\tconst original = placeholderMap.get(match);\n\t\t\treturn original || match; // Return placeholder if not found (theoretically won't happen)\n\t\t});\n\t});\n}\n\nfunction splitParagraph(paragraph: string, maxLength: number): string[] {\n\t// 1) Extract URLs and replace with placeholders\n\tconst { textWithPlaceholders, placeholderMap } = extractUrls(paragraph);\n\n\t// 2) Use first section's logic to split by sentences first, then do secondary split\n\tconst splittedChunks = splitSentencesAndWords(\n\t\ttextWithPlaceholders,\n\t\tmaxLength,\n\t);\n\n\t// 3) Replace placeholders back to original URLs\n\tconst restoredChunks = restoreUrls(splittedChunks, placeholderMap);\n\n\treturn restoredChunks;\n}\n\nexport const parseActionResponseFromText = (\n\ttext: string,\n): { actions: ActionResponse } => {\n\tconst actions: ActionResponse = {\n\t\tlike: false,\n\t\tretweet: false,\n\t\tquote: false,\n\t\treply: false,\n\t};\n\n\t// Regex patterns\n\tconst likePattern = /\\[LIKE\\]/i;\n\tconst retweetPattern = /\\[RETWEET\\]/i;\n\tconst quotePattern = /\\[QUOTE\\]/i;\n\tconst replyPattern = /\\[REPLY\\]/i;\n\n\t// Check with regex\n\tactions.like = likePattern.test(text);\n\tactions.retweet = retweetPattern.test(text);\n\tactions.quote = quotePattern.test(text);\n\tactions.reply = replyPattern.test(text);\n\n\t// Also do line by line parsing as backup\n\tconst lines = text.split(\"\\n\");\n\tfor (const line of lines) {\n\t\tconst trimmed = line.trim();\n\t\tif (trimmed === \"[LIKE]\") actions.like = true;\n\t\tif (trimmed === \"[RETWEET]\") actions.retweet = true;\n\t\tif (trimmed === \"[QUOTE]\") actions.quote = true;\n\t\tif (trimmed === \"[REPLY]\") actions.reply = true;\n\t}\n\n\treturn { actions };\n};\n\nexport async function generateTweetActions({\n\truntime,\n\tprompt,\n\tmodelType,\n}: {\n\truntime: IAgentRuntime;\n\tprompt: string;\n\tmodelType: ModelType;\n}): Promise<ActionResponse | null> {\n\tlet retryDelay = 1000;\n\twhile (true) {\n\t\ttry {\n\t\t\tconst response = await runtime.useModel(modelType, {\n\t\t\t\tprompt,\n\t\t\t});\n\t\t\tlogger.debug(\n\t\t\t\t\"Received response from generateText for tweet actions:\",\n\t\t\t\tresponse,\n\t\t\t);\n\t\t\tconst { actions } = parseActionResponseFromText(response.trim());\n\t\t\tif (actions) {\n\t\t\t\tlogger.debug(\"Parsed tweet actions:\", actions);\n\t\t\t\treturn actions;\n\t\t\t}\n\t\t\tlogger.debug(\"generateTweetActions no valid response\");\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error in generateTweetActions:\", error);\n\t\t\tif (\n\t\t\t\terror instanceof TypeError &&\n\t\t\t\terror.message.includes(\"queueTextCompletion\")\n\t\t\t) {\n\t\t\t\tlogger.error(\n\t\t\t\t\t\"TypeError: Cannot read properties of null (reading 'queueTextCompletion')\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tlogger.log(`Retrying in ${retryDelay}ms...`);\n\t\tawait new Promise((resolve) => setTimeout(resolve, retryDelay));\n\t\tretryDelay *= 2;\n\t}\n}\n\n/**\n * Generate short filler text via GPT\n */\nexport async function generateFiller(\n\truntime: IAgentRuntime,\n\tfillerType: string,\n): Promise<string> {\n\ttry {\n\t\tconst prompt = composePrompt({\n\t\t\tstate: { fillerType } as any as State,\n\t\t\ttemplate: `\n# INSTRUCTIONS:\nYou are generating a short filler message for a Twitter Space. The filler type is \"{{fillerType}}\".\nKeep it brief, friendly, and relevant. No more than two sentences.\nOnly return the text, no additional formatting.\n\n---\n`,\n\t\t});\n\t\tconst output = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\tprompt,\n\t\t});\n\t\treturn output.trim();\n\t} catch (err) {\n\t\tlogger.error(\"[generateFiller] Error generating filler:\", err);\n\t\treturn \"\";\n\t}\n}\n\n/**\n * Speak a filler message if STT/TTS plugin is available. Sleep a bit after TTS to avoid cutoff.\n */\nexport async function speakFiller(\n\truntime: IAgentRuntime,\n\tsttTtsPlugin: SttTtsPlugin | undefined,\n\tfillerType: string,\n\tsleepAfterMs = 3000,\n): Promise<void> {\n\tif (!sttTtsPlugin) return;\n\tconst text = await generateFiller(runtime, fillerType);\n\tif (!text) return;\n\n\tlogger.log(`[Space] Filler (${fillerType}) => ${text}`);\n\tawait sttTtsPlugin.speakText(text);\n\n\tif (sleepAfterMs > 0) {\n\t\tawait new Promise((res) => setTimeout(res, sleepAfterMs));\n\t}\n}\n\n/**\n * Generate topic suggestions via GPT if no topics are configured\n */\nexport async function generateTopicsIfEmpty(\n\truntime: IAgentRuntime,\n): Promise<string[]> {\n\ttry {\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {} as any,\n\t\t\ttemplate: `\n# INSTRUCTIONS:\nPlease generate 5 short topic ideas for a Twitter Space about technology or random interesting subjects.\nReturn them as a comma-separated list, no additional formatting or numbering.\n\nExample:\n\"AI Advances, Futuristic Gadgets, Space Exploration, Quantum Computing, Digital Ethics\"\n---\n`,\n\t\t});\n\t\tconst response = await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\tprompt,\n\t\t});\n\t\tconst topics = response\n\t\t\t.split(\",\")\n\t\t\t.map((t) => t.trim())\n\t\t\t.filter(Boolean);\n\t\treturn topics.length ? topics : [\"Random Tech Chat\", \"AI Thoughts\"];\n\t} catch (err) {\n\t\tlogger.error(\"[generateTopicsIfEmpty] GPT error =>\", err);\n\t\treturn [\"Random Tech Chat\", \"AI Thoughts\"];\n\t}\n}\n\nexport async function isAgentInSpace(\n\tclient: ClientBase,\n\tspaceId: string,\n): Promise<boolean> {\n\tconst space = await client.twitterClient.getAudioSpaceById(spaceId);\n\tconst agentName = client.state.TWITTER_USERNAME;\n\n\treturn (\n\t\tspace.participants.listeners.some(\n\t\t\t(participant) => participant.twitter_screen_name === agentName,\n\t\t) ||\n\t\tspace.participants.speakers.some(\n\t\t\t(participant) => participant.twitter_screen_name === agentName,\n\t\t)\n\t);\n}\n","import {\n\tChannelType,\n\ttype Content,\n\ttype IAgentRuntime,\n\ttype Memory,\n\ttype State,\n\ttype UUID,\n\tcreateUniqueUuid,\n\tlogger,\n} from \"@elizaos/core\";\nimport { EventEmitter } from \"node:events\";\nimport {\n\ttype QueryTweetsResponse,\n\tClient,\n\tSearchMode,\n\ttype Tweet,\n} from \"./client/index.ts\";\n\nexport function extractAnswer(text: string): string {\n\tconst startIndex = text.indexOf(\"Answer: \") + 8;\n\tconst endIndex = text.indexOf(\"<|endoftext|>\", 11);\n\treturn text.slice(startIndex, endIndex);\n}\n\ntype TwitterProfile = {\n\tid: string;\n\tusername: string;\n\tscreenName: string;\n\tbio: string;\n\tnicknames: string[];\n};\n\nclass RequestQueue {\n\tprivate queue: (() => Promise<any>)[] = [];\n\tprivate processing = false;\n\n\tasync add<T>(request: () => Promise<T>): Promise<T> {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.queue.push(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst result = await request();\n\t\t\t\t\tresolve(result);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis.processQueue();\n\t\t});\n\t}\n\n\tprivate async processQueue(): Promise<void> {\n\t\tif (this.processing || this.queue.length === 0) {\n\t\t\treturn;\n\t\t}\n\t\tthis.processing = true;\n\n\t\twhile (this.queue.length > 0) {\n\t\t\tconst request = this.queue.shift()!;\n\t\t\ttry {\n\t\t\t\tawait request();\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(\"Error processing request:\", error);\n\t\t\t\tthis.queue.unshift(request);\n\t\t\t\tawait this.exponentialBackoff(this.queue.length);\n\t\t\t}\n\t\t\tawait this.randomDelay();\n\t\t}\n\n\t\tthis.processing = false;\n\t}\n\n\tprivate async exponentialBackoff(retryCount: number): Promise<void> {\n\t\tconst delay = 2 ** retryCount * 1000;\n\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t}\n\n\tprivate async randomDelay(): Promise<void> {\n\t\tconst delay = Math.floor(Math.random() * 2000) + 1500;\n\t\tawait new Promise((resolve) => setTimeout(resolve, delay));\n\t}\n}\n\nexport class ClientBase extends EventEmitter {\n\tstatic _twitterClients: { [accountIdentifier: string]: Client } = {};\n\ttwitterClient: Client;\n\truntime: IAgentRuntime;\n\tlastCheckedTweetId: bigint | null = null;\n\ttemperature = 0.5;\n\n\trequestQueue: RequestQueue = new RequestQueue();\n\n\tprofile: TwitterProfile | null;\n\n\tasync cacheTweet(tweet: Tweet): Promise<void> {\n\t\tif (!tweet) {\n\t\t\tconsole.warn(\"Tweet is undefined, skipping cache\");\n\t\t\treturn;\n\t\t}\n\n\t\tthis.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.setCache<Tweet>(`twitter/tweets/${tweet.id}`, tweet);\n\t}\n\n\tasync getCachedTweet(tweetId: string): Promise<Tweet | undefined> {\n\t\tconst cached = await this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getCache<Tweet>(`twitter/tweets/${tweetId}`);\n\n\t\tif (!cached) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn cached;\n\t}\n\n\tasync getTweet(tweetId: string): Promise<Tweet> {\n\t\tconst cachedTweet = await this.getCachedTweet(tweetId);\n\n\t\tif (cachedTweet) {\n\t\t\treturn cachedTweet;\n\t\t}\n\n\t\tconst tweet = await this.requestQueue.add(() =>\n\t\t\tthis.twitterClient.getTweet(tweetId),\n\t\t);\n\n\t\tawait this.cacheTweet(tweet);\n\t\treturn tweet;\n\t}\n\n\tcallback: (self: ClientBase) => any = null;\n\n\tonReady() {\n\t\tthrow new Error(\"Not implemented in base class, please call from subclass\");\n\t}\n\n\t/**\n\t * Parse the raw tweet data into a standardized Tweet object.\n\t */\n\tparseTweet(raw: any, depth = 0, maxDepth = 3): Tweet {\n\t\t// If we've reached maxDepth, don't parse nested quotes/retweets further\n\t\tconst canRecurse = depth < maxDepth;\n\n\t\tconst quotedStatus =\n\t\t\traw.quoted_status_result?.result && canRecurse\n\t\t\t\t? this.parseTweet(raw.quoted_status_result.result, depth + 1, maxDepth)\n\t\t\t\t: undefined;\n\n\t\tconst retweetedStatus =\n\t\t\traw.retweeted_status_result?.result && canRecurse\n\t\t\t\t? this.parseTweet(\n\t\t\t\t\t\traw.retweeted_status_result.result,\n\t\t\t\t\t\tdepth + 1,\n\t\t\t\t\t\tmaxDepth,\n\t\t\t\t\t)\n\t\t\t\t: undefined;\n\n\t\tconst t: Tweet = {\n\t\t\tbookmarkCount:\n\t\t\t\traw.bookmarkCount ?? raw.legacy?.bookmark_count ?? undefined,\n\t\t\tconversationId: raw.conversationId ?? raw.legacy?.conversation_id_str,\n\t\t\thashtags: raw.hashtags ?? raw.legacy?.entities?.hashtags ?? [],\n\t\t\thtml: raw.html,\n\t\t\tid: raw.id ?? raw.rest_id ?? raw.id_str ?? undefined,\n\t\t\tinReplyToStatus: raw.inReplyToStatus,\n\t\t\tinReplyToStatusId:\n\t\t\t\traw.inReplyToStatusId ??\n\t\t\t\traw.legacy?.in_reply_to_status_id_str ??\n\t\t\t\tundefined,\n\t\t\tisQuoted: raw.legacy?.is_quote_status === true,\n\t\t\tisPin: raw.isPin,\n\t\t\tisReply: raw.isReply,\n\t\t\tisRetweet: raw.legacy?.retweeted === true,\n\t\t\tisSelfThread: raw.isSelfThread,\n\t\t\tlanguage: raw.legacy?.lang,\n\t\t\tlikes: raw.legacy?.favorite_count ?? 0,\n\t\t\tname:\n\t\t\t\traw.name ??\n\t\t\t\traw?.user_results?.result?.legacy?.name ??\n\t\t\t\traw.core?.user_results?.result?.legacy?.name,\n\t\t\tmentions: raw.mentions ?? raw.legacy?.entities?.user_mentions ?? [],\n\t\t\tpermanentUrl:\n\t\t\t\traw.permanentUrl ??\n\t\t\t\t(raw.core?.user_results?.result?.legacy?.screen_name && raw.rest_id\n\t\t\t\t\t? `https://x.com/${raw.core?.user_results?.result?.legacy?.screen_name}/status/${raw.rest_id}`\n\t\t\t\t\t: undefined),\n\t\t\tphotos:\n\t\t\t\traw.photos ??\n\t\t\t\t(raw.legacy?.entities?.media\n\t\t\t\t\t?.filter((media: any) => media.type === \"photo\")\n\t\t\t\t\t.map((media: any) => ({\n\t\t\t\t\t\tid: media.id_str,\n\t\t\t\t\t\turl: media.media_url_https,\n\t\t\t\t\t\talt_text: media.alt_text,\n\t\t\t\t\t})) ||\n\t\t\t\t\t[]),\n\t\t\tplace: raw.place,\n\t\t\tpoll: raw.poll ?? null,\n\t\t\tquotedStatus,\n\t\t\tquotedStatusId:\n\t\t\t\traw.quotedStatusId ?? raw.legacy?.quoted_status_id_str ?? undefined,\n\t\t\tquotes: raw.legacy?.quote_count ?? 0,\n\t\t\treplies: raw.legacy?.reply_count ?? 0,\n\t\t\tretweets: raw.legacy?.retweet_count ?? 0,\n\t\t\tretweetedStatus,\n\t\t\tretweetedStatusId: raw.legacy?.retweeted_status_id_str ?? undefined,\n\t\t\ttext: raw.text ?? raw.legacy?.full_text ?? undefined,\n\t\t\tthread: raw.thread || [],\n\t\t\ttimeParsed: raw.timeParsed\n\t\t\t\t? new Date(raw.timeParsed)\n\t\t\t\t: raw.legacy?.created_at\n\t\t\t\t\t? new Date(raw.legacy?.created_at)\n\t\t\t\t\t: undefined,\n\t\t\ttimestamp:\n\t\t\t\traw.timestamp ??\n\t\t\t\t(raw.legacy?.created_at\n\t\t\t\t\t? new Date(raw.legacy.created_at).getTime() / 1000\n\t\t\t\t\t: undefined),\n\t\t\turls: raw.urls ?? raw.legacy?.entities?.urls ?? [],\n\t\t\tuserId: raw.userId ?? raw.legacy?.user_id_str ?? undefined,\n\t\t\tusername:\n\t\t\t\traw.username ??\n\t\t\t\traw.core?.user_results?.result?.legacy?.screen_name ??\n\t\t\t\tundefined,\n\t\t\tvideos:\n\t\t\t\traw.videos ??\n\t\t\t\traw.legacy?.entities?.media?.filter(\n\t\t\t\t\t(media: any) => media.type === \"video\",\n\t\t\t\t) ??\n\t\t\t\t[],\n\t\t\tviews: raw.views?.count ? Number(raw.views.count) : 0,\n\t\t\tsensitiveContent: raw.sensitiveContent,\n\t\t};\n\n\t\treturn t;\n\t}\n\n\tstate: any;\n\n\tconstructor(runtime: IAgentRuntime, state: any) {\n\t\tsuper();\n\t\tthis.runtime = runtime;\n\t\tthis.state = state;\n\t\tconst username =\n\t\t\tstate?.TWITTER_USERNAME ||\n\t\t\t(this.runtime.getSetting(\"TWITTER_USERNAME\") as string);\n\t\tif (ClientBase._twitterClients[username]) {\n\t\t\tthis.twitterClient = ClientBase._twitterClients[username];\n\t\t} else {\n\t\t\tthis.twitterClient = new Client();\n\t\t\tClientBase._twitterClients[username] = this.twitterClient;\n\t\t}\n\t}\n\n\tasync init() {\n\t\tconst username =\n\t\t\tthis.state?.TWITTER_USERNAME ||\n\t\t\tthis.runtime.getSetting(\"TWITTER_USERNAME\");\n\t\tconst password =\n\t\t\tthis.state?.TWITTER_PASSWORD ||\n\t\t\tthis.runtime.getSetting(\"TWITTER_PASSWORD\");\n\t\tconst email =\n\t\t\tthis.state?.TWITTER_EMAIL || this.runtime.getSetting(\"TWITTER_EMAIL\");\n\t\tconst twitter2faSecret =\n\t\t\tthis.state?.TWITTER_2FA_SECRET ||\n\t\t\tthis.runtime.getSetting(\"TWITTER_2FA_SECRET\");\n\n\t\t// Validate required credentials\n\t\tif (!username || !password || !email) {\n\t\t\tconst missing = [];\n\t\t\tif (!username) missing.push(\"TWITTER_USERNAME\");\n\t\t\tif (!password) missing.push(\"TWITTER_PASSWORD\");\n\t\t\tif (!email) missing.push(\"TWITTER_EMAIL\");\n\t\t\tthrow new Error(\n\t\t\t\t`Missing required Twitter credentials: ${missing.join(\", \")}`,\n\t\t\t);\n\t\t}\n\n\t\tlet retries =\n\t\t\t(this.state?.TWITTER_RETRY_LIMIT ||\n\t\t\t\t(this.runtime.getSetting(\n\t\t\t\t\t\"TWITTER_RETRY_LIMIT\",\n\t\t\t\t) as unknown as number)) ??\n\t\t\t3;\n\n\t\tif (!username) {\n\t\t\tthrow new Error(\"Twitter username not configured\");\n\t\t}\n\n\t\tconst authToken =\n\t\t\tthis.state?.TWITTER_COOKIES_AUTH_TOKEN ||\n\t\t\tthis.runtime.getSetting(\"TWITTER_COOKIES_AUTH_TOKEN\");\n\t\tconst ct0 =\n\t\t\tthis.state?.TWITTER_COOKIES_CT0 ||\n\t\t\tthis.runtime.getSetting(\"TWITTER_COOKIES_CT0\");\n\t\tconst guestId =\n\t\t\tthis.state?.TWITTER_COOKIES_GUEST_ID ||\n\t\t\tthis.runtime.getSetting(\"TWITTER_COOKIES_GUEST_ID\");\n\n\t\tconst createTwitterCookies = (\n\t\t\tauthToken: string,\n\t\t\tct0: string,\n\t\t\tguestId: string,\n\t\t) =>\n\t\t\tauthToken && ct0 && guestId\n\t\t\t\t? [\n\t\t\t\t\t\t{ key: \"auth_token\", value: authToken, domain: \".twitter.com\" },\n\t\t\t\t\t\t{ key: \"ct0\", value: ct0, domain: \".twitter.com\" },\n\t\t\t\t\t\t{ key: \"guest_id\", value: guestId, domain: \".twitter.com\" },\n\t\t\t\t\t]\n\t\t\t\t: null;\n\n\t\tconst cachedCookies =\n\t\t\t(await this.getCachedCookies(username)) ||\n\t\t\tcreateTwitterCookies(authToken, ct0, guestId);\n\n\t\tif (cachedCookies) {\n\t\t\tlogger.info(\"Using cached cookies\");\n\t\t\tawait this.setCookiesFromArray(cachedCookies);\n\t\t}\n\n\t\tlogger.log(\"Waiting for Twitter login\");\n\t\twhile (retries > 0) {\n\t\t\ttry {\n\t\t\t\tif (await this.twitterClient.isLoggedIn()) {\n\t\t\t\t\t// cookies are valid, no login required\n\t\t\t\t\tlogger.info(\"Successfully logged in.\");\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tawait this.twitterClient.login(\n\t\t\t\t\tusername,\n\t\t\t\t\tpassword,\n\t\t\t\t\temail,\n\t\t\t\t\ttwitter2faSecret,\n\t\t\t\t);\n\t\t\t\tif (await this.twitterClient.isLoggedIn()) {\n\t\t\t\t\t// fresh login, store new cookies\n\t\t\t\t\tlogger.info(\"Successfully logged in.\");\n\t\t\t\t\tlogger.info(\"Caching cookies\");\n\t\t\t\t\tawait this.cacheCookies(\n\t\t\t\t\t\tusername,\n\t\t\t\t\t\tawait this.twitterClient.getCookies(),\n\t\t\t\t\t);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(`Login attempt failed: ${error.message}`);\n\t\t\t}\n\n\t\t\tretries--;\n\t\t\tlogger.error(\n\t\t\t\t`Failed to login to Twitter. Retrying... (${retries} attempts left)`,\n\t\t\t);\n\n\t\t\tif (retries === 0) {\n\t\t\t\tlogger.error(\"Max retries reached. Exiting login process.\");\n\t\t\t\tthrow new Error(\"Twitter login failed after maximum retries.\");\n\t\t\t}\n\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, 2000));\n\t\t}\n\t\t// Initialize Twitter profile\n\t\tthis.profile = await this.fetchProfile(username);\n\n\t\tif (this.profile) {\n\t\t\tlogger.log(\"Twitter user ID:\", this.profile.id);\n\t\t\tlogger.log(\"Twitter loaded:\", JSON.stringify(this.profile, null, 10));\n\t\t\t// Store profile info for use in responses\n\t\t\tthis.profile = {\n\t\t\t\tid: this.profile.id,\n\t\t\t\tusername: this.profile.username,\n\t\t\t\tscreenName: this.profile.screenName,\n\t\t\t\tbio: this.profile.bio,\n\t\t\t\tnicknames: this.profile.nicknames,\n\t\t\t};\n\t\t} else {\n\t\t\tthrow new Error(\"Failed to load profile\");\n\t\t}\n\n\t\tawait this.loadLatestCheckedTweetId();\n\t\tawait this.populateTimeline();\n\t}\n\n\tasync fetchOwnPosts(count: number): Promise<Tweet[]> {\n\t\tlogger.debug(\"fetching own posts\");\n\t\tconst homeTimeline = await this.twitterClient.getUserTweets(\n\t\t\tthis.profile.id,\n\t\t\tcount,\n\t\t);\n\t\t// Use parseTweet on each tweet\n\t\treturn homeTimeline.tweets.map((t) => this.parseTweet(t));\n\t}\n\n\t/**\n\t * Fetch timeline for twitter account, optionally only from followed accounts\n\t */\n\tasync fetchHomeTimeline(\n\t\tcount: number,\n\t\tfollowing?: boolean,\n\t): Promise<Tweet[]> {\n\t\tlogger.debug(\"fetching home timeline\");\n\t\tconst homeTimeline = following\n\t\t\t? await this.twitterClient.fetchFollowingTimeline(count, [])\n\t\t\t: await this.twitterClient.fetchHomeTimeline(count, []);\n\n\t\tlogger.debug(homeTimeline);\n\t\tconst processedTimeline = homeTimeline\n\t\t\t.filter((t) => t.__typename !== \"TweetWithVisibilityResults\") // what's this about?\n\t\t\t.map((tweet) => this.parseTweet(tweet));\n\n\t\t//logger.debug(\"process homeTimeline\", processedTimeline);\n\t\treturn processedTimeline;\n\t}\n\n\tasync fetchSearchTweets(\n\t\tquery: string,\n\t\tmaxTweets: number,\n\t\tsearchMode: SearchMode,\n\t\tcursor?: string,\n\t): Promise<QueryTweetsResponse> {\n\t\ttry {\n\t\t\t// Sometimes this fails because we are rate limited. in this case, we just need to return an empty array\n\t\t\t// if we dont get a response in 5 seconds, something is wrong\n\t\t\tconst timeoutPromise = new Promise((resolve) =>\n\t\t\t\tsetTimeout(() => resolve({ tweets: [] }), 15000),\n\t\t\t);\n\n\t\t\ttry {\n\t\t\t\tconst result = await this.requestQueue.add(\n\t\t\t\t\tasync () =>\n\t\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\t\tthis.twitterClient.fetchSearchTweets(\n\t\t\t\t\t\t\t\tquery,\n\t\t\t\t\t\t\t\tmaxTweets,\n\t\t\t\t\t\t\t\tsearchMode,\n\t\t\t\t\t\t\t\tcursor,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\ttimeoutPromise,\n\t\t\t\t\t\t]),\n\t\t\t\t);\n\t\t\t\treturn (result ?? { tweets: [] }) as QueryTweetsResponse;\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"Error fetching search tweets:\", error);\n\t\t\t\treturn { tweets: [] };\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error fetching search tweets:\", error);\n\t\t\treturn { tweets: [] };\n\t\t}\n\t}\n\n\tprivate async populateTimeline() {\n\t\tlogger.debug(\"populating timeline...\");\n\n\t\tconst cachedTimeline = await this.getCachedTimeline();\n\n\t\t// Check if the cache file exists\n\t\tif (cachedTimeline) {\n\t\t\t// Read the cached search results from the file\n\n\t\t\t// Get the existing memories from the database\n\t\t\tconst existingMemories = await this.runtime\n\t\t\t\t.getMemoryManager(\"messages\")\n\t\t\t\t.getMemoriesByRoomIds({\n\t\t\t\t\troomIds: cachedTimeline.map((tweet) =>\n\t\t\t\t\t\tcreateUniqueUuid(this.runtime, tweet.conversationId),\n\t\t\t\t\t),\n\t\t\t\t});\n\n\t\t\t//TODO: load tweets not in cache?\n\n\t\t\t// Create a Set to store the IDs of existing memories\n\t\t\tconst existingMemoryIds = new Set(\n\t\t\t\texistingMemories.map((memory) => memory.id.toString()),\n\t\t\t);\n\n\t\t\t// Check if any of the cached tweets exist in the existing memories\n\t\t\tconst someCachedTweetsExist = cachedTimeline.some((tweet) =>\n\t\t\t\texistingMemoryIds.has(createUniqueUuid(this.runtime, tweet.id)),\n\t\t\t);\n\n\t\t\tif (someCachedTweetsExist) {\n\t\t\t\t// Filter out the cached tweets that already exist in the database\n\t\t\t\tconst tweetsToSave = cachedTimeline.filter(\n\t\t\t\t\t(tweet) =>\n\t\t\t\t\t\ttweet.userId !== this.profile.id &&\n\t\t\t\t\t\t!existingMemoryIds.has(createUniqueUuid(this.runtime, tweet.id)),\n\t\t\t\t);\n\n\t\t\t\t// Save the missing tweets as memories\n\t\t\t\tfor (const tweet of tweetsToSave) {\n\t\t\t\t\tlogger.log(\"Saving Tweet\", tweet.id);\n\n\t\t\t\t\tif (tweet.userId === this.profile.id) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\n\t\t\t\t\tconst entityId = createUniqueUuid(\n\t\t\t\t\t\tthis.runtime,\n\t\t\t\t\t\ttweet.userId === this.profile.id\n\t\t\t\t\t\t\t? this.runtime.agentId\n\t\t\t\t\t\t\t: tweet.userId,\n\t\t\t\t\t);\n\n\t\t\t\t\tawait this.runtime.ensureConnection({\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\troomId,\n\t\t\t\t\t\tuserName: tweet.username,\n\t\t\t\t\t\tname: tweet.name,\n\t\t\t\t\t\tsource: \"twitter\",\n\t\t\t\t\t\ttype: ChannelType.FEED,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst content = {\n\t\t\t\t\t\ttext: tweet.text,\n\t\t\t\t\t\turl: tweet.permanentUrl,\n\t\t\t\t\t\tsource: \"twitter\",\n\t\t\t\t\t\tinReplyTo: tweet.inReplyToStatusId\n\t\t\t\t\t\t\t? createUniqueUuid(this.runtime, tweet.inReplyToStatusId)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t} as Content;\n\n\t\t\t\t\tlogger.log(\"Creating memory for tweet\", tweet.id);\n\n\t\t\t\t\t// check if it already exists\n\t\t\t\t\tconst memory = await this.runtime\n\t\t\t\t\t\t.getMemoryManager(\"messages\")\n\t\t\t\t\t\t.getMemoryById(createUniqueUuid(this.runtime, tweet.id));\n\n\t\t\t\t\tif (memory) {\n\t\t\t\t\t\tlogger.log(\"Memory already exists, skipping timeline population\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tawait this.runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\t\tid: createUniqueUuid(this.runtime, tweet.id),\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\tcontent: content,\n\t\t\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\t\t\troomId,\n\t\t\t\t\t\tcreatedAt: tweet.timestamp * 1000,\n\t\t\t\t\t});\n\n\t\t\t\t\tawait this.cacheTweet(tweet);\n\t\t\t\t}\n\n\t\t\t\tlogger.log(\n\t\t\t\t\t`Populated ${tweetsToSave.length} missing tweets from the cache.`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tconst timeline = await this.fetchHomeTimeline(cachedTimeline ? 10 : 50);\n\t\tconst username = this.runtime.getSetting(\"TWITTER_USERNAME\");\n\n\t\t// Get the most recent 20 mentions and interactions\n\t\tconst mentionsAndInteractions = await this.fetchSearchTweets(\n\t\t\t`@${username}`,\n\t\t\t20,\n\t\t\tSearchMode.Latest,\n\t\t);\n\n\t\t// Combine the timeline tweets and mentions/interactions\n\t\tconst allTweets = [...timeline, ...mentionsAndInteractions.tweets];\n\n\t\t// Create a Set to store unique tweet IDs\n\t\tconst tweetIdsToCheck = new Set<string>();\n\t\tconst roomIds = new Set<UUID>();\n\n\t\t// Add tweet IDs to the Set\n\t\tfor (const tweet of allTweets) {\n\t\t\ttweetIdsToCheck.add(tweet.id);\n\t\t\troomIds.add(createUniqueUuid(this.runtime, tweet.conversationId));\n\t\t}\n\n\t\t// Check the existing memories in the database\n\t\tconst existingMemories = await this.runtime\n\t\t\t.getMemoryManager(\"messages\")\n\t\t\t.getMemoriesByRoomIds({\n\t\t\t\troomIds: Array.from(roomIds),\n\t\t\t});\n\n\t\t// Create a Set to store the existing memory IDs\n\t\tconst existingMemoryIds = new Set<UUID>(\n\t\t\texistingMemories.map((memory) => memory.id),\n\t\t);\n\n\t\t// Filter out the tweets that already exist in the database\n\t\tconst tweetsToSave = allTweets.filter(\n\t\t\t(tweet) =>\n\t\t\t\ttweet.userId !== this.profile.id &&\n\t\t\t\t!existingMemoryIds.has(createUniqueUuid(this.runtime, tweet.id)),\n\t\t);\n\n\t\tlogger.debug({\n\t\t\tprocessingTweets: tweetsToSave.map((tweet) => tweet.id).join(\",\"),\n\t\t});\n\n\t\t// Save the new tweets as memories\n\t\tfor (const tweet of tweetsToSave) {\n\t\t\tlogger.log(\"Saving Tweet\", tweet.id);\n\n\t\t\tif (tweet.userId === this.profile.id) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\n\t\t\tconst entityId =\n\t\t\t\ttweet.userId === this.profile.id\n\t\t\t\t\t? this.runtime.agentId\n\t\t\t\t\t: createUniqueUuid(this.runtime, tweet.userId);\n\n\t\t\tawait this.runtime.ensureConnection({\n\t\t\t\tentityId,\n\t\t\t\troomId,\n\t\t\t\tuserName: tweet.username,\n\t\t\t\tname: tweet.name,\n\t\t\t\tsource: \"twitter\",\n\t\t\t\ttype: ChannelType.FEED,\n\t\t\t});\n\n\t\t\tconst content = {\n\t\t\t\ttext: tweet.text,\n\t\t\t\turl: tweet.permanentUrl,\n\t\t\t\tsource: \"twitter\",\n\t\t\t\tinReplyTo: tweet.inReplyToStatusId\n\t\t\t\t\t? createUniqueUuid(this.runtime, tweet.inReplyToStatusId)\n\t\t\t\t\t: undefined,\n\t\t\t} as Content;\n\n\t\t\tawait this.runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\tid: createUniqueUuid(this.runtime, tweet.id),\n\t\t\t\tentityId,\n\t\t\t\tcontent: content,\n\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\troomId,\n\t\t\t\tcreatedAt: tweet.timestamp * 1000,\n\t\t\t});\n\n\t\t\tawait this.cacheTweet(tweet);\n\t\t}\n\n\t\t// Cache\n\t\tawait this.cacheTimeline(timeline);\n\t\tawait this.cacheMentions(mentionsAndInteractions.tweets);\n\t}\n\n\tasync setCookiesFromArray(cookiesArray: any[]) {\n\t\tconst cookieStrings = cookiesArray.map(\n\t\t\t(cookie) =>\n\t\t\t\t`${cookie.key}=${cookie.value}; Domain=${cookie.domain}; Path=${\n\t\t\t\t\tcookie.path\n\t\t\t\t}; ${cookie.secure ? \"Secure\" : \"\"}; ${\n\t\t\t\t\tcookie.httpOnly ? \"HttpOnly\" : \"\"\n\t\t\t\t}; SameSite=${cookie.sameSite || \"Lax\"}`,\n\t\t);\n\t\tawait this.twitterClient.setCookies(cookieStrings);\n\t}\n\n\tasync saveRequestMessage(message: Memory, state: State) {\n\t\tif (message.content.text) {\n\t\t\tconst recentMessage = await this.runtime\n\t\t\t\t.getMemoryManager(\"messages\")\n\t\t\t\t.getMemories({\n\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\tcount: 1,\n\t\t\t\t\tunique: false,\n\t\t\t\t});\n\n\t\t\tif (\n\t\t\t\trecentMessage.length > 0 &&\n\t\t\t\trecentMessage[0].content === message.content\n\t\t\t) {\n\t\t\t\tlogger.debug(\"Message already saved\", recentMessage[0].id);\n\t\t\t} else {\n\t\t\t\tawait this.runtime.getMemoryManager(\"messages\").createMemory(message);\n\t\t\t}\n\n\t\t\tawait this.runtime.evaluate(message, {\n\t\t\t\t...state,\n\t\t\t\ttwitterClient: this.twitterClient,\n\t\t\t});\n\t\t}\n\t}\n\n\tasync loadLatestCheckedTweetId(): Promise<void> {\n\t\tconst latestCheckedTweetId = await this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getCache<string>(\n\t\t\t\t`twitter/${this.profile.username}/latest_checked_tweet_id`,\n\t\t\t);\n\n\t\tif (latestCheckedTweetId) {\n\t\t\tthis.lastCheckedTweetId = BigInt(latestCheckedTweetId);\n\t\t}\n\t}\n\n\tasync cacheLatestCheckedTweetId() {\n\t\tif (this.lastCheckedTweetId) {\n\t\t\tawait this.runtime\n\t\t\t\t.getDatabaseAdapter()\n\t\t\t\t.setCache<string>(\n\t\t\t\t\t`twitter/${this.profile.username}/latest_checked_tweet_id`,\n\t\t\t\t\tthis.lastCheckedTweetId.toString(),\n\t\t\t\t);\n\t\t}\n\t}\n\n\tasync getCachedTimeline(): Promise<Tweet[] | undefined> {\n\t\tconst cached = await this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getCache<Tweet[]>(`twitter/${this.profile.username}/timeline`);\n\n\t\tif (!cached) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn cached;\n\t}\n\n\tasync cacheTimeline(timeline: Tweet[]) {\n\t\tawait this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.setCache<Tweet[]>(`twitter/${this.profile.username}/timeline`, timeline);\n\t}\n\n\tasync cacheMentions(mentions: Tweet[]) {\n\t\tawait this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.setCache<Tweet[]>(`twitter/${this.profile.username}/mentions`, mentions);\n\t}\n\n\tasync getCachedCookies(username: string) {\n\t\tconst cached = await this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.getCache<any[]>(`twitter/${username}/cookies`);\n\n\t\tif (!cached) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn cached;\n\t}\n\n\tasync cacheCookies(username: string, cookies: any[]) {\n\t\tawait this.runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.setCache<any[]>(`twitter/${username}/cookies`, cookies);\n\t}\n\n\tasync fetchProfile(username: string): Promise<TwitterProfile> {\n\t\ttry {\n\t\t\tconst profile = await this.requestQueue.add(async () => {\n\t\t\t\tconst profile = await this.twitterClient.getProfile(username);\n\t\t\t\treturn {\n\t\t\t\t\tid: profile.userId,\n\t\t\t\t\tusername,\n\t\t\t\t\tscreenName: profile.name || this.runtime.character.name,\n\t\t\t\t\tbio:\n\t\t\t\t\t\tprofile.biography || typeof this.runtime.character.bio === \"string\"\n\t\t\t\t\t\t\t? (this.runtime.character.bio as string)\n\t\t\t\t\t\t\t: this.runtime.character.bio.length > 0\n\t\t\t\t\t\t\t\t? this.runtime.character.bio[0]\n\t\t\t\t\t\t\t\t: \"\",\n\t\t\t\t\tnicknames: this.profile?.nicknames || [],\n\t\t\t\t} satisfies TwitterProfile;\n\t\t\t});\n\n\t\t\treturn profile;\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Error fetching Twitter profile:\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n","export const TWITTER_SERVICE_NAME = \"twitter\";\n","import {\n\tChannelType,\n\tcomposePrompt,\n\ttype Content,\n\tcreateUniqueUuid,\n\ttype HandlerCallback,\n\ttype IAgentRuntime,\n\tlogger,\n\ttype Memory,\n\tModelTypes,\n\tparseJSONObjectFromText,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base.ts\";\nimport { SearchMode, type Tweet } from \"./client/index.ts\";\nimport { buildConversationThread, sendTweet, wait } from \"./utils.ts\";\n\nexport const twitterMessageHandlerTemplate = `# Task: Generate dialog and actions for {{agentName}}.\n{{providers}}\nHere is the current post text again. Remember to include an action if the current post text includes a prompt that asks for one of the available actions mentioned above (does not need to be exact)\n{{currentPost}}\n{{imageDescriptions}}\n\n# Instructions: Write the next message for {{agentName}}. Include the appropriate action from the list: {{actionNames}}\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{ \"thought\": \"<string>\", \"name\": \"{{agentName}}\", \"text\": \"<string>\", \"action\": \"<string>\" }\n\\`\\`\\`\n\nThe \"action\" field should be one of the options in [Available Actions] and the \"text\" field should be the response you want to send. Do not including any thinking or internal reflection in the \"text\" field. \"thought\" should be a short description of what the agent is thinking about before responding, inlcuding a brief justification for the response.`;\n\nexport const twitterShouldRespondTemplate = `# INSTRUCTIONS: Determine if {{agentName}} (@{{twitterUserName}}) should respond to the message and participate in the conversation. Do not comment. Just respond with \"true\" or \"false\".\n\nResponse options are RESPOND, IGNORE and STOP.\n\nFor other users:\n- {{agentName}} should RESPOND to messages directed at them\n- {{agentName}} should RESPOND to conversations relevant to their background\n- {{agentName}} should IGNORE irrelevant messages\n- {{agentName}} should IGNORE very short messages unless directly addressed\n- {{agentName}} should STOP if asked to stop\n- {{agentName}} should STOP if conversation is concluded\n- {{agentName}} is in a room with other users and wants to be conversational, but not annoying.\n\nIMPORTANT:\n- {{agentName}} (aka @{{twitterUserName}}) is particularly sensitive about being annoying, so if there is any doubt, it is better to IGNORE than to RESPOND.\n- For users not in the priority list, {{agentName}} (@{{twitterUserName}}) should err on the side of IGNORE rather than RESPOND if in doubt.\n\nRecent Posts:\n{{recentPosts}}\n\nCurrent Post:\n{{currentPost}}\n\nThread of Tweets You Are Replying To:\n{{formattedConversation}}\n\n# INSTRUCTIONS: Respond with RESPOND if {{agentName}} should respond, or IGNORE if {{agentName}} should not respond to the last message and STOP if {{agentName}} should stop participating in the conversation.\nThe available options are RESPOND, IGNORE, or STOP. Choose the most appropriate option.`;\n\nexport class TwitterInteractionClient {\n\tclient: ClientBase;\n\truntime: IAgentRuntime;\n\tprivate isDryRun: boolean;\n\tprivate state: any;\n\tconstructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n\t\tthis.client = client;\n\t\tthis.runtime = runtime;\n\t\tthis.state = state;\n\t\tthis.isDryRun =\n\t\t\tthis.state?.TWITTER_DRY_RUN ||\n\t\t\t(this.runtime.getSetting(\"TWITTER_DRY_RUN\") as unknown as boolean);\n\t}\n\n\tasync start() {\n\t\tconst handleTwitterInteractionsLoop = () => {\n\t\t\t// Defaults to 2 minutes\n\t\t\tconst interactionInterval =\n\t\t\t\t(this.state?.TWITTER_POLL_INTERVAL ||\n\t\t\t\t\t(this.runtime.getSetting(\n\t\t\t\t\t\t\"TWITTER_POLL_INTERVAL\",\n\t\t\t\t\t) as unknown as number) ||\n\t\t\t\t\t120) * 1000;\n\n\t\t\tthis.handleTwitterInteractions();\n\t\t\tsetTimeout(handleTwitterInteractionsLoop, interactionInterval);\n\t\t};\n\t\thandleTwitterInteractionsLoop();\n\t}\n\n\tasync handleTwitterInteractions() {\n\t\tlogger.log(\"Checking Twitter interactions\");\n\n\t\tconst twitterUsername = this.client.profile?.username;\n\t\ttry {\n\t\t\t// Check for mentions\n\t\t\tconst mentionCandidates = (\n\t\t\t\tawait this.client.fetchSearchTweets(\n\t\t\t\t\t`@${twitterUsername}`,\n\t\t\t\t\t20,\n\t\t\t\t\tSearchMode.Latest,\n\t\t\t\t)\n\t\t\t).tweets;\n\n\t\t\tlogger.log(\n\t\t\t\t\"Completed checking mentioned tweets:\",\n\t\t\t\tmentionCandidates.length,\n\t\t\t);\n\t\t\tlet uniqueTweetCandidates = [...mentionCandidates];\n\n\t\t\t// Sort tweet candidates by ID in ascending order\n\t\t\tuniqueTweetCandidates = uniqueTweetCandidates\n\t\t\t\t.sort((a, b) => a.id.localeCompare(b.id))\n\t\t\t\t.filter((tweet) => tweet.userId !== this.client.profile.id);\n\n\t\t\t// for each tweet candidate, handle the tweet\n\t\t\tfor (const tweet of uniqueTweetCandidates) {\n\t\t\t\tif (\n\t\t\t\t\t!this.client.lastCheckedTweetId ||\n\t\t\t\t\tBigInt(tweet.id) > this.client.lastCheckedTweetId\n\t\t\t\t) {\n\t\t\t\t\t// Generate the tweetId UUID the same way it's done in handleTweet\n\t\t\t\t\tconst tweetId = createUniqueUuid(this.runtime, tweet.id);\n\n\t\t\t\t\t// Check if we've already processed this tweet\n\t\t\t\t\tconst existingResponse = await this.runtime\n\t\t\t\t\t\t.getMemoryManager(\"messages\")\n\t\t\t\t\t\t.getMemoryById(tweetId);\n\n\t\t\t\t\tif (existingResponse) {\n\t\t\t\t\t\tlogger.log(`Already responded to tweet ${tweet.id}, skipping`);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.log(\"New Tweet found\", tweet.permanentUrl);\n\n\t\t\t\t\tconst roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\n\t\t\t\t\tconst entityId = createUniqueUuid(\n\t\t\t\t\t\tthis.runtime,\n\t\t\t\t\t\ttweet.userId === this.client.profile.id\n\t\t\t\t\t\t\t? this.runtime.agentId\n\t\t\t\t\t\t\t: tweet.userId,\n\t\t\t\t\t);\n\n\t\t\t\t\tawait this.runtime.ensureConnection({\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\troomId,\n\t\t\t\t\t\tuserName: tweet.username,\n\t\t\t\t\t\tname: tweet.name,\n\t\t\t\t\t\tsource: \"twitter\",\n\t\t\t\t\t\ttype: ChannelType.GROUP,\n\t\t\t\t\t});\n\n\t\t\t\t\tconst thread = await buildConversationThread(tweet, this.client);\n\n\t\t\t\t\tconst message = {\n\t\t\t\t\t\tcontent: {\n\t\t\t\t\t\t\ttext: tweet.text,\n\t\t\t\t\t\t\timageUrls: tweet.photos?.map((photo) => photo.url) || [],\n\t\t\t\t\t\t\ttweet: tweet,\n\t\t\t\t\t\t\tsource: \"twitter\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\t\t\tentityId,\n\t\t\t\t\t\troomId,\n\t\t\t\t\t};\n\n\t\t\t\t\tawait this.handleTweet({\n\t\t\t\t\t\ttweet,\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tthread,\n\t\t\t\t\t});\n\n\t\t\t\t\t// Update the last checked tweet ID after processing each tweet\n\t\t\t\t\tthis.client.lastCheckedTweetId = BigInt(tweet.id);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Save the latest checked tweet ID to the file\n\t\t\tawait this.client.cacheLatestCheckedTweetId();\n\n\t\t\tlogger.log(\"Finished checking Twitter interactions\");\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error handling Twitter interactions:\", error);\n\t\t}\n\t}\n\n\tasync handleTweet({\n\t\ttweet,\n\t\tmessage,\n\t\tthread,\n\t}: {\n\t\ttweet: Tweet;\n\t\tmessage: Memory;\n\t\tthread: Tweet[];\n\t}) {\n\t\tif (!message.content.text) {\n\t\t\tlogger.log(\"Skipping Tweet with no text\", tweet.id);\n\t\t\treturn { text: \"\", actions: [\"IGNORE\"] };\n\t\t}\n\n\t\tlogger.log(\"Processing Tweet: \", tweet.id);\n\t\tconst formatTweet = (tweet: Tweet) => {\n\t\t\treturn ` ID: ${tweet.id}\n From: ${tweet.name} (@${tweet.username})\n Text: ${tweet.text}`;\n\t\t};\n\t\tconst currentPost = formatTweet(tweet);\n\n\t\tconst formattedConversation = thread\n\t\t\t.map(\n\t\t\t\t(tweet) => `@${tweet.username} (${new Date(\n\t\t\t\t\ttweet.timestamp * 1000,\n\t\t\t\t).toLocaleString(\"en-US\", {\n\t\t\t\t\thour: \"2-digit\",\n\t\t\t\t\tminute: \"2-digit\",\n\t\t\t\t\tmonth: \"short\",\n\t\t\t\t\tday: \"numeric\",\n\t\t\t\t})}):\n ${tweet.text}`,\n\t\t\t)\n\t\t\t.join(\"\\n\\n\");\n\n\t\tconst imageDescriptionsArray = [];\n\t\ttry {\n\t\t\tfor (const photo of tweet.photos) {\n\t\t\t\tconst description = await this.runtime.useModel(\n\t\t\t\t\tModelTypes.IMAGE_DESCRIPTION,\n\t\t\t\t\tphoto.url,\n\t\t\t\t);\n\t\t\t\timageDescriptionsArray.push(description);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// Handle the error\n\t\t\tlogger.error(\"Error Occured during describing image: \", error);\n\t\t}\n\n\t\tlet state = await this.runtime.composeState(message);\n\n\t\tstate.values = {\n\t\t\t...state.values,\n\t\t\ttwitterUserName:\n\t\t\t\tthis.state?.TWITTER_USERNAME ||\n\t\t\t\tthis.runtime.getSetting(\"TWITTER_USERNAME\"),\n\t\t\tcurrentPost, // TODO: move to recentMessages provider\n\t\t\tformattedConversation,\n\t\t};\n\t\t// check if the tweet exists, save if it doesn't\n\t\tconst tweetId = createUniqueUuid(this.runtime, tweet.id);\n\t\tconst tweetExists = await this.runtime\n\t\t\t.getMemoryManager(\"messages\")\n\t\t\t.getMemoryById(tweetId);\n\n\t\tif (!tweetExists) {\n\t\t\tlogger.log(\"tweet does not exist, saving\");\n\t\t\tconst entityId = createUniqueUuid(this.runtime, tweet.userId);\n\n\t\t\tconst roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\n\t\t\tawait this.runtime.ensureConnection({\n\t\t\t\tentityId,\n\t\t\t\troomId,\n\t\t\t\tuserName: tweet.username,\n\t\t\t\tname: tweet.name,\n\t\t\t\tsource: \"twitter\",\n\t\t\t\ttype: ChannelType.GROUP,\n\t\t\t});\n\n\t\t\tconst message = {\n\t\t\t\tid: tweetId,\n\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: tweet.text,\n\t\t\t\t\turl: tweet.permanentUrl,\n\t\t\t\t\timageUrls: tweet.photos?.map((photo) => photo.url) || [],\n\t\t\t\t\tinReplyTo: tweet.inReplyToStatusId\n\t\t\t\t\t\t? createUniqueUuid(this.runtime, tweet.inReplyToStatusId)\n\t\t\t\t\t\t: undefined,\n\t\t\t\t},\n\t\t\t\tentityId,\n\t\t\t\troomId,\n\t\t\t\tcreatedAt: tweet.timestamp * 1000,\n\t\t\t};\n\t\t\tthis.client.saveRequestMessage(message, state);\n\t\t}\n\n\t\tconst shouldRespondPrompt = composePrompt({\n\t\t\tstate,\n\t\t\ttemplate:\n\t\t\t\tthis.runtime.character.templates?.twitterShouldRespondTemplate ||\n\t\t\t\tthis.runtime.character?.templates?.shouldRespondTemplate ||\n\t\t\t\ttwitterShouldRespondTemplate,\n\t\t});\n\n\t\tconst shouldRespond = await this.runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\tprompt: shouldRespondPrompt,\n\t\t});\n\n\t\tif (!shouldRespond.includes(\"RESPOND\")) {\n\t\t\tlogger.log(\"Not responding to message\");\n\t\t\treturn { text: \"Response Decision:\", action: shouldRespond };\n\t\t}\n\n\t\tconst prompt = composePrompt({\n\t\t\tstate: {\n\t\t\t\t...state,\n\t\t\t\t// Convert actionNames array to string\n\t\t\t\tactionNames: Array.isArray(state.actionNames)\n\t\t\t\t\t? state.actionNames.join(\", \")\n\t\t\t\t\t: state.actionNames || \"\",\n\t\t\t\tactions: Array.isArray(state.actions)\n\t\t\t\t\t? state.actions.join(\"\\n\")\n\t\t\t\t\t: state.actions || \"\",\n\t\t\t\t// Ensure character examples are included\n\t\t\t\tcharacterPostExamples: this.runtime.character.messageExamples\n\t\t\t\t\t? this.runtime.character.messageExamples\n\t\t\t\t\t\t\t.map((example) =>\n\t\t\t\t\t\t\t\texample\n\t\t\t\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t\t\t\t(msg) =>\n\t\t\t\t\t\t\t\t\t\t\t`${msg.name}: ${msg.content.text}${\n\t\t\t\t\t\t\t\t\t\t\t\tmsg.content.actions\n\t\t\t\t\t\t\t\t\t\t\t\t\t? ` (Actions: ${msg.content.actions.join(\", \")})`\n\t\t\t\t\t\t\t\t\t\t\t\t\t: \"\"\n\t\t\t\t\t\t\t\t\t\t\t}`,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t.join(\"\\n\"),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.join(\"\\n\\n\")\n\t\t\t\t\t: \"\",\n\t\t\t},\n\t\t\ttemplate:\n\t\t\t\tthis.runtime.character.templates?.twitterMessageHandlerTemplate ||\n\t\t\t\tthis.runtime.character?.templates?.messageHandlerTemplate ||\n\t\t\t\ttwitterMessageHandlerTemplate,\n\t\t});\n\n\t\tconst responseText = await this.runtime.useModel(ModelTypes.TEXT_LARGE, {\n\t\t\tprompt,\n\t\t});\n\n\t\tconst response = parseJSONObjectFromText(responseText) as Content;\n\n\t\tconst removeQuotes = (str: string) => str.replace(/^['\"](.*)['\"]$/, \"$1\");\n\n\t\tconst replyToId = createUniqueUuid(this.runtime, tweet.id);\n\n\t\tresponse.inReplyTo = replyToId;\n\n\t\tresponse.text = removeQuotes(response.text);\n\n\t\tif (response.text) {\n\t\t\tif (this.isDryRun) {\n\t\t\t\tlogger.info(\n\t\t\t\t\t`Dry run: Selected Post: ${tweet.id} - ${tweet.username}: ${tweet.text}\\nAgent's Output:\\n${response.text}`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tconst callback: HandlerCallback = async (\n\t\t\t\t\t\tresponse: Content,\n\t\t\t\t\t\ttweetId?: string,\n\t\t\t\t\t) => {\n\t\t\t\t\t\tconst memories = await sendTweet(\n\t\t\t\t\t\t\tthis.client,\n\t\t\t\t\t\t\tresponse,\n\t\t\t\t\t\t\tmessage.roomId,\n\t\t\t\t\t\t\tthis.state?.TWITTER_USERNAME ||\n\t\t\t\t\t\t\t\t(this.runtime.getSetting(\"TWITTER_USERNAME\") as string),\n\t\t\t\t\t\t\ttweetId || tweet.id,\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn memories;\n\t\t\t\t\t};\n\n\t\t\t\t\tconst responseMessages = [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tid: createUniqueUuid(this.runtime, tweet.id),\n\t\t\t\t\t\t\tentityId: this.runtime.agentId,\n\t\t\t\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\t\t\t\tcontent: response,\n\t\t\t\t\t\t\troomId: message.roomId,\n\t\t\t\t\t\t\tcreatedAt: Date.now(),\n\t\t\t\t\t\t},\n\t\t\t\t\t];\n\n\t\t\t\t\tstate = await this.runtime.composeState(message, [\"RECENT_MESSAGES\"]);\n\n\t\t\t\t\tfor (const responseMessage of responseMessages) {\n\t\t\t\t\t\tawait this.runtime\n\t\t\t\t\t\t\t.getMemoryManager(\"messages\")\n\t\t\t\t\t\t\t.createMemory(responseMessage);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst responseTweetId = (\n\t\t\t\t\t\tresponseMessages[responseMessages.length - 1]?.content as any\n\t\t\t\t\t)?.tweetId;\n\n\t\t\t\t\tawait this.runtime.processActions(\n\t\t\t\t\t\tmessage,\n\t\t\t\t\t\tresponseMessages,\n\t\t\t\t\t\tstate,\n\t\t\t\t\t\t(response: Content) => {\n\t\t\t\t\t\t\treturn callback(response, responseTweetId);\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\n\t\t\t\t\tconst responseInfo = `Context:\\n\\n${prompt}\\n\\nSelected Post: ${tweet.id} - ${tweet.username}: ${tweet.text}\\nAgent's Output:\\n${response.text}`;\n\n\t\t\t\t\tawait this.runtime\n\t\t\t\t\t\t.getDatabaseAdapter()\n\t\t\t\t\t\t.setCache<string>(\n\t\t\t\t\t\t\t`twitter/tweet_generation_${tweet.id}.txt`,\n\t\t\t\t\t\t\tresponseInfo,\n\t\t\t\t\t\t);\n\t\t\t\t\tawait wait();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(`Error sending response tweet: ${error}`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tasync buildConversationThread(\n\t\ttweet: Tweet,\n\t\tmaxReplies = 10,\n\t): Promise<Tweet[]> {\n\t\tconst thread: Tweet[] = [];\n\t\tconst visited: Set<string> = new Set();\n\n\t\tasync function processThread(currentTweet: Tweet, depth = 0) {\n\t\t\tlogger.log(\"Processing tweet:\", {\n\t\t\t\tid: currentTweet.id,\n\t\t\t\tinReplyToStatusId: currentTweet.inReplyToStatusId,\n\t\t\t\tdepth: depth,\n\t\t\t});\n\n\t\t\tif (!currentTweet) {\n\t\t\t\tlogger.log(\"No current tweet found for thread building\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (depth >= maxReplies) {\n\t\t\t\tlogger.log(\"Reached maximum reply depth\", depth);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Handle memory storage\n\t\t\tconst memory = await this.runtime\n\t\t\t\t.getMemoryManager(\"messages\")\n\t\t\t\t.getMemoryById(createUniqueUuid(this.runtime, currentTweet.id));\n\t\t\tif (!memory) {\n\t\t\t\tconst roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\t\t\t\tconst entityId = createUniqueUuid(this.runtime, currentTweet.userId);\n\n\t\t\t\tawait this.runtime.ensureConnection({\n\t\t\t\t\tentityId,\n\t\t\t\t\troomId,\n\t\t\t\t\tuserName: currentTweet.username,\n\t\t\t\t\tname: currentTweet.name,\n\t\t\t\t\tsource: \"twitter\",\n\t\t\t\t\ttype: ChannelType.GROUP,\n\t\t\t\t});\n\n\t\t\t\tthis.runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\t\t\tid: createUniqueUuid(this.runtime, currentTweet.id),\n\t\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\t\tcontent: {\n\t\t\t\t\t\ttext: currentTweet.text,\n\t\t\t\t\t\tsource: \"twitter\",\n\t\t\t\t\t\turl: currentTweet.permanentUrl,\n\t\t\t\t\t\timageUrls: currentTweet.photos?.map((photo) => photo.url) || [],\n\t\t\t\t\t\tinReplyTo: currentTweet.inReplyToStatusId\n\t\t\t\t\t\t\t? createUniqueUuid(this.runtime, currentTweet.inReplyToStatusId)\n\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t},\n\t\t\t\t\tcreatedAt: currentTweet.timestamp * 1000,\n\t\t\t\t\troomId,\n\t\t\t\t\tentityId:\n\t\t\t\t\t\tcurrentTweet.userId === this.twitterUserId\n\t\t\t\t\t\t\t? this.runtime.agentId\n\t\t\t\t\t\t\t: createUniqueUuid(this.runtime, currentTweet.userId),\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (visited.has(currentTweet.id)) {\n\t\t\t\tlogger.log(\"Already visited tweet:\", currentTweet.id);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvisited.add(currentTweet.id);\n\t\t\tthread.unshift(currentTweet);\n\n\t\t\tif (currentTweet.inReplyToStatusId) {\n\t\t\t\tlogger.log(\"Fetching parent tweet:\", currentTweet.inReplyToStatusId);\n\t\t\t\ttry {\n\t\t\t\t\tconst parentTweet = await this.twitterClient.getTweet(\n\t\t\t\t\t\tcurrentTweet.inReplyToStatusId,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (parentTweet) {\n\t\t\t\t\t\tlogger.log(\"Found parent tweet:\", {\n\t\t\t\t\t\t\tid: parentTweet.id,\n\t\t\t\t\t\t\ttext: parentTweet.text?.slice(0, 50),\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait processThread(parentTweet, depth + 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogger.log(\n\t\t\t\t\t\t\t\"No parent tweet found for:\",\n\t\t\t\t\t\t\tcurrentTweet.inReplyToStatusId,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.log(\"Error fetching parent tweet:\", {\n\t\t\t\t\t\ttweetId: currentTweet.inReplyToStatusId,\n\t\t\t\t\t\terror,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlogger.log(\"Reached end of reply chain at:\", currentTweet.id);\n\t\t\t}\n\t\t}\n\n\t\t// Need to bind this prompt for the inner function\n\t\tawait processThread.bind(this)(tweet, 0);\n\n\t\treturn thread;\n\t}\n}\n","import {\n\tChannelType,\n\tcleanJsonResponse,\n\tcomposePrompt,\n\tcreateUniqueUuid,\n\textractAttributes,\n\ttype IAgentRuntime,\n\tlogger,\n\tModelTypes,\n\tparseJSONObjectFromText,\n\ttruncateToCompleteSentence,\n\ttype UUID,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base.ts\";\nimport type { Tweet } from \"./client/index.ts\";\nimport { twitterPostTemplate } from \"./templates.ts\";\nimport type { MediaData } from \"./types.ts\";\nimport { fetchMediaData } from \"./utils.ts\";\n\nexport class TwitterPostClient {\n\tclient: ClientBase;\n\truntime: IAgentRuntime;\n\ttwitterUsername: string;\n\tprivate isDryRun: boolean;\n\tprivate state: any;\n\n\tconstructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n\t\tthis.client = client;\n\t\tthis.state = state;\n\t\tthis.runtime = runtime;\n\t\tthis.twitterUsername =\n\t\t\tstate?.TWITTER_USERNAME ||\n\t\t\t(this.runtime.getSetting(\"TWITTER_USERNAME\") as string);\n\t\tthis.isDryRun =\n\t\t\tthis.state?.TWITTER_DRY_RUN ||\n\t\t\t(this.runtime.getSetting(\"TWITTER_DRY_RUN\") as unknown as boolean);\n\n\t\t// Log configuration on initialization\n\t\tlogger.log(\"Twitter Client Configuration:\");\n\t\tlogger.log(`- Username: ${this.twitterUsername}`);\n\t\tlogger.log(`- Dry Run Mode: ${this.isDryRun ? \"enabled\" : \"disabled\"}`);\n\n\t\tlogger.log(\n\t\t\t`- Disable Post: ${this.state?.TWITTER_ENABLE_POST_GENERATION || this.runtime.getSetting(\"TWITTER_ENABLE_POST_GENERATION\") ? \"disabled\" : \"enabled\"}`,\n\t\t);\n\n\t\tlogger.log(\n\t\t\t`- Post Interval: ${this.state?.TWITTER_POST_INTERVAL_MIN || this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MIN\")}-${this.state?.TWITTER_POST_INTERVAL_MAX || this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MAX\")} minutes`,\n\t\t);\n\t\tlogger.log(\n\t\t\t`- Post Immediately: ${\n\t\t\t\tthis.state?.TWITTER_POST_IMMEDIATELY ||\n\t\t\t\tthis.runtime.getSetting(\"TWITTER_POST_IMMEDIATELY\")\n\t\t\t\t\t? \"enabled\"\n\t\t\t\t\t: \"disabled\"\n\t\t\t}`,\n\t\t);\n\n\t\tif (this.isDryRun) {\n\t\t\tlogger.log(\n\t\t\t\t\"Twitter client initialized in dry run mode - no actual tweets should be posted\",\n\t\t\t);\n\t\t}\n\t}\n\n\tasync start() {\n\t\tif (!this.client.profile) {\n\t\t\tawait this.client.init();\n\t\t}\n\n\t\tconst generateNewTweetLoop = async () => {\n\t\t\tlet lastPost = await this.runtime\n\t\t\t\t.getDatabaseAdapter()\n\t\t\t\t.getCache<any>(`twitter/${this.twitterUsername}/lastPost`);\n\n\t\t\tif (!lastPost) {\n\t\t\t\tlastPost = JSON.stringify({\n\t\t\t\t\ttimestamp: 0,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst lastPostTimestamp = lastPost.timestamp ?? 0;\n\t\t\tconst minMinutes =\n\t\t\t\t(this.state?.TWITTER_POST_INTERVAL_MIN ||\n\t\t\t\t\t(this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MIN\") as number)) ??\n\t\t\t\t90;\n\t\t\tconst maxMinutes =\n\t\t\t\t(this.state?.TWITTER_POST_INTERVAL_MAX ||\n\t\t\t\t\t(this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MAX\") as number)) ??\n\t\t\t\t180;\n\t\t\tconst randomMinutes =\n\t\t\t\tMath.floor(Math.random() * (maxMinutes - minMinutes + 1)) + minMinutes;\n\t\t\tconst delay = randomMinutes * 60 * 1000;\n\n\t\t\tif (Date.now() > lastPostTimestamp + delay) {\n\t\t\t\tawait this.generateNewTweet();\n\t\t\t}\n\n\t\t\tsetTimeout(() => {\n\t\t\t\tgenerateNewTweetLoop(); // Set up next iteration\n\t\t\t}, delay);\n\n\t\t\tlogger.log(`Next tweet scheduled in ${randomMinutes} minutes`);\n\t\t};\n\n\t\tif (\n\t\t\tthis.state?.TWITTER_ENABLE_POST_GENERATION ||\n\t\t\tthis.runtime.getSetting(\"TWITTER_ENABLE_POST_GENERATION\")\n\t\t) {\n\t\t\tif (\n\t\t\t\tthis.state?.TWITTER_POST_IMMEDIATELY ||\n\t\t\t\tthis.runtime.getSetting(\"TWITTER_POST_IMMEDIATELY\")\n\t\t\t) {\n\t\t\t\t// generate in 5 seconds\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tthis.generateNewTweet();\n\t\t\t\t}, 5000);\n\t\t\t}\n\n\t\t\tgenerateNewTweetLoop();\n\t\t\tlogger.log(\"Tweet generation loop started\");\n\t\t}\n\t}\n\n\tcreateTweetObject(\n\t\ttweetResult: any,\n\t\tclient: any,\n\t\ttwitterUsername: string,\n\t): Tweet {\n\t\treturn {\n\t\t\tid: tweetResult.rest_id,\n\t\t\tname: client.profile.screenName,\n\t\t\tusername: client.profile.username,\n\t\t\ttext: tweetResult.legacy.full_text,\n\t\t\tconversationId: tweetResult.legacy.conversation_id_str,\n\t\t\tcreatedAt: tweetResult.legacy.created_at,\n\t\t\ttimestamp: new Date(tweetResult.legacy.created_at).getTime(),\n\t\t\tuserId: client.profile.id,\n\t\t\tinReplyToStatusId: tweetResult.legacy.in_reply_to_status_id_str,\n\t\t\tpermanentUrl: `https://twitter.com/${twitterUsername}/status/${tweetResult.rest_id}`,\n\t\t\thashtags: [],\n\t\t\tmentions: [],\n\t\t\tphotos: [],\n\t\t\tthread: [],\n\t\t\turls: [],\n\t\t\tvideos: [],\n\t\t} as Tweet;\n\t}\n\n\tasync processAndCacheTweet(\n\t\truntime: IAgentRuntime,\n\t\tclient: ClientBase,\n\t\ttweet: Tweet,\n\t\troomId: UUID,\n\t\trawTweetContent: string,\n\t) {\n\t\t// Cache the last post details\n\t\tawait runtime\n\t\t\t.getDatabaseAdapter()\n\t\t\t.setCache<any>(`twitter/${client.profile.username}/lastPost`, {\n\t\t\t\tid: tweet.id,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t});\n\n\t\t// Cache the tweet\n\t\tawait client.cacheTweet(tweet);\n\n\t\t// Log the posted tweet\n\t\tlogger.log(`Tweet posted:\\n ${tweet.permanentUrl}`);\n\n\t\t// Ensure the room and participant exist\n\t\tawait runtime.ensureRoomExists({\n\t\t\tid: roomId,\n\t\t\tname: \"Twitter Feed\",\n\t\t\tsource: \"twitter\",\n\t\t\ttype: ChannelType.FEED,\n\t\t});\n\t\tawait runtime.ensureParticipantInRoom(runtime.agentId, roomId);\n\n\t\t// Create a memory for the tweet\n\t\tawait runtime.getMemoryManager(\"messages\").createMemory({\n\t\t\tid: createUniqueUuid(this.runtime, tweet.id),\n\t\t\tentityId: runtime.agentId,\n\t\t\tagentId: runtime.agentId,\n\t\t\tcontent: {\n\t\t\t\ttext: rawTweetContent.trim(),\n\t\t\t\turl: tweet.permanentUrl,\n\t\t\t\tsource: \"twitter\",\n\t\t\t},\n\t\t\troomId,\n\t\t\tcreatedAt: tweet.timestamp,\n\t\t});\n\t}\n\n\tasync handleNoteTweet(\n\t\tclient: ClientBase,\n\t\tcontent: string,\n\t\ttweetId?: string,\n\t\tmediaData?: MediaData[],\n\t) {\n\t\ttry {\n\t\t\tconst noteTweetResult = await client.requestQueue.add(\n\t\t\t\tasync () =>\n\t\t\t\t\tawait client.twitterClient.sendNoteTweet(content, tweetId, mediaData),\n\t\t\t);\n\n\t\t\tif (noteTweetResult.errors && noteTweetResult.errors.length > 0) {\n\t\t\t\t// Note Tweet failed due to authorization. Falling back to standard Tweet.\n\t\t\t\tconst truncateContent = truncateToCompleteSentence(content, 280 - 1);\n\t\t\t\treturn await this.sendStandardTweet(client, truncateContent, tweetId);\n\t\t\t}\n\t\t\treturn noteTweetResult.data.notetweet_create.tweet_results.result;\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Note Tweet failed: ${error}`);\n\t\t}\n\t}\n\n\tasync sendStandardTweet(\n\t\tclient: ClientBase,\n\t\tcontent: string,\n\t\ttweetId?: string,\n\t\tmediaData?: MediaData[],\n\t) {\n\t\ttry {\n\t\t\tconst standardTweetResult = await client.requestQueue.add(\n\t\t\t\tasync () =>\n\t\t\t\t\tawait client.twitterClient.sendTweet(content, tweetId, mediaData),\n\t\t\t);\n\t\t\tconst body = await standardTweetResult.json();\n\t\t\tif (!body?.data?.create_tweet?.tweet_results?.result) {\n\t\t\t\tlogger.error(\"Error sending tweet; Bad response:\", body);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn body.data.create_tweet.tweet_results.result;\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error sending standard Tweet:\", error);\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync postTweet(\n\t\truntime: IAgentRuntime,\n\t\tclient: ClientBase,\n\t\ttweetTextForPosting: string,\n\t\troomId: UUID,\n\t\trawTweetContent: string,\n\t\ttwitterUsername: string,\n\t\tmediaData?: MediaData[],\n\t) {\n\t\ttry {\n\t\t\tlogger.log(\"Posting new tweet:\\n\");\n\n\t\t\tlet result;\n\n\t\t\tif (tweetTextForPosting.length > 280 - 1) {\n\t\t\t\tresult = await this.handleNoteTweet(\n\t\t\t\t\tclient,\n\t\t\t\t\ttweetTextForPosting,\n\t\t\t\t\tundefined,\n\t\t\t\t\tmediaData,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tresult = await this.sendStandardTweet(\n\t\t\t\t\tclient,\n\t\t\t\t\ttweetTextForPosting,\n\t\t\t\t\tundefined,\n\t\t\t\t\tmediaData,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst tweet = this.createTweetObject(result, client, twitterUsername);\n\n\t\t\tawait this.processAndCacheTweet(\n\t\t\t\truntime,\n\t\t\t\tclient,\n\t\t\t\ttweet,\n\t\t\t\troomId,\n\t\t\t\trawTweetContent,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error sending tweet:\");\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Generates and posts a new tweet. If isDryRun is true, only logs what would have been posted.\n\t */\n\tasync generateNewTweet() {\n\t\tlogger.log(\"Generating new tweet\");\n\n\t\ttry {\n\t\t\tconst roomId = createUniqueUuid(this.runtime, \"twitter_generate\");\n\t\t\tconst topics = this.runtime.character.topics\n\t\t\t\t.sort(() => 0.5 - Math.random())\n\t\t\t\t.slice(0, 10)\n\t\t\t\t.join(\", \");\n\t\t\tconst state = await this.runtime.composeState({\n\t\t\t\tentityId: this.runtime.agentId,\n\t\t\t\troomId: roomId,\n\t\t\t\tagentId: this.runtime.agentId,\n\t\t\t\tcontent: {\n\t\t\t\t\ttext: topics || \"\",\n\t\t\t\t\tactions: [\"TWEET\"],\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tstate.values = {\n\t\t\t\t...state.values,\n\t\t\t\ttwitterUserName: this.client.profile.username,\n\t\t\t};\n\n\t\t\tconst prompt = composePrompt({\n\t\t\t\tstate,\n\t\t\t\ttemplate:\n\t\t\t\t\tthis.runtime.character.templates?.twitterPostTemplate ||\n\t\t\t\t\ttwitterPostTemplate,\n\t\t\t});\n\n\t\t\tlogger.debug(`generate post prompt:\\n${prompt}`);\n\n\t\t\tconst response = await this.runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\t\tprompt,\n\t\t\t});\n\n\t\t\tconst rawTweetContent = cleanJsonResponse(response);\n\n\t\t\t// First attempt to clean content\n\t\t\tlet tweetTextForPosting = null;\n\t\t\tlet mediaData = null;\n\n\t\t\t// Try parsing as JSON first\n\t\t\tconst parsedResponse = parseJSONObjectFromText(rawTweetContent);\n\t\t\tif (parsedResponse?.text) {\n\t\t\t\ttweetTextForPosting = parsedResponse.text;\n\t\t\t} else {\n\t\t\t\t// If not JSON, use the raw text directly\n\t\t\t\ttweetTextForPosting = rawTweetContent.trim();\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tparsedResponse?.attachments &&\n\t\t\t\tparsedResponse?.attachments.length > 0\n\t\t\t) {\n\t\t\t\tmediaData = await fetchMediaData(parsedResponse.attachments);\n\t\t\t}\n\n\t\t\t// Try extracting text attribute\n\t\t\tif (!tweetTextForPosting) {\n\t\t\t\tconst parsingText = extractAttributes(rawTweetContent, [\"text\"]).text;\n\t\t\t\tif (parsingText) {\n\t\t\t\t\ttweetTextForPosting = truncateToCompleteSentence(\n\t\t\t\t\t\textractAttributes(rawTweetContent, [\"text\"]).text,\n\t\t\t\t\t\t280 - 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Use the raw text\n\t\t\tif (!tweetTextForPosting) {\n\t\t\t\ttweetTextForPosting = rawTweetContent;\n\t\t\t}\n\n\t\t\t// Truncate the content to the maximum tweet length specified in the environment settings, ensuring the truncation respects sentence boundaries.\n\t\t\ttweetTextForPosting = truncateToCompleteSentence(\n\t\t\t\ttweetTextForPosting,\n\t\t\t\t280 - 1,\n\t\t\t);\n\n\t\t\tconst removeQuotes = (str: string) => str.replace(/^['\"](.*)['\"]$/, \"$1\");\n\n\t\t\tconst fixNewLines = (str: string) => str.replaceAll(/\\\\n/g, \"\\n\\n\"); //ensures double spaces\n\n\t\t\t// Final cleaning\n\t\t\ttweetTextForPosting = removeQuotes(fixNewLines(tweetTextForPosting));\n\n\t\t\tif (this.isDryRun) {\n\t\t\t\tlogger.info(`Dry run: would have posted tweet: ${tweetTextForPosting}`);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tlogger.log(`Posting new tweet:\\n ${tweetTextForPosting}`);\n\n\t\t\t\tthis.postTweet(\n\t\t\t\t\tthis.runtime,\n\t\t\t\t\tthis.client,\n\t\t\t\t\ttweetTextForPosting,\n\t\t\t\t\troomId,\n\t\t\t\t\trawTweetContent,\n\t\t\t\t\tthis.twitterUsername,\n\t\t\t\t\tmediaData,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tlogger.error(\"Error sending tweet:\", error);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error(\"Error generating new tweet:\", error);\n\t\t}\n\t}\n\n\tasync stop() {}\n}\n","export const twitterShouldRespondTemplate = `# Task: Decide if {{agentName}} should respond.\nAbout {{agentName}}:\n{{bio}}\n\n# INSTRUCTIONS: Determine if {{agentName}} should respond to the message and participate in the conversation. Do not comment. Just respond with \"RESPOND\" or \"IGNORE\" or \"STOP\".\n\n# RESPONSE EXAMPLES\n{{name1}}: I just saw a really great movie\n{{name2}}: Oh? Which movie?\nResponse: IGNORE\n\n{{agentName}}: Oh, this is my favorite scene\n{{name1}}: sick\n{{name2}}: wait, why is it your favorite scene\nResponse: RESPOND\n\n{{name1}}: stfu bot\nResponse: STOP\n\n{{name1}}: Hey {{agentName}}, can you help me with something\nResponse: RESPOND\n\n{{name1}}: {{agentName}} stfu plz\nResponse: STOP\n\n{{name1}}: i need help\n{{agentName}}: how can I help you?\n{{name1}}: no. i need help from someone else\nResponse: IGNORE\n\n{{name1}}: Hey {{agentName}}, can I ask you a question\n{{agentName}}: Sure, what is it\n{{name1}}: can you ask claude to create a basic react module that demonstrates a counter\nResponse: RESPOND\n\n{{name1}}: {{agentName}} can you tell me a story\n{{name1}}: about a girl named elara\n{{agentName}}: Sure.\n{{agentName}}: Once upon a time, in a quaint little village, there was a curious girl named Elara.\n{{agentName}}: Elara was known for her adventurous spirit and her knack for finding beauty in the mundane.\n{{name1}}: I'm loving it, keep going\nResponse: RESPOND\n\n{{name1}}: {{agentName}} stop responding plz\nResponse: STOP\n\n{{name1}}: okay, i want to test something. can you say marco?\n{{agentName}}: marco\n{{name1}}: great. okay, now do it again\nResponse: RESPOND\n\nResponse options are RESPOND, IGNORE and STOP.\n\n{{agentName}} is in a room with other users and is very worried about being annoying and saying too much.\nRespond with RESPOND to messages that are directed at {{agentName}}, or participate in conversations that are interesting or relevant to their background.\nUnless directly responding to a user, respond with IGNORE to messages that are very short or do not contain much information.\nIf a user asks {{agentName}} to be quiet, respond with STOP\nIf {{agentName}} concludes a conversation and isn't part of the conversation anymore, respond with STOP\n\nIMPORTANT: {{agentName}} is particularly sensitive about being annoying, so if there is any doubt, it is better to respond with IGNORE.\nIf {{agentName}} is conversing with a user and they have not asked to stop, it is better to respond with RESPOND.\n\n{{recentMessages}}\n\n# INSTRUCTIONS: Choose the option that best describes {{agentName}}'s response to the last message.\nThe available options are RESPOND, IGNORE, or STOP. Choose the most appropriate option.`;\n\nexport const twitterVoiceHandlerTemplate = `# Task: Generate conversational voice dialog for {{agentName}}.\n{{providers}}\n# Instructions: Write the next message for {{agentName}}. Include the appropriate action from the list: {{actionNames}}\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{ \"name\": \"{{agentName}}\", \"text\": \"<string>\", \"action\": \"<string>\" }\n\\`\\`\\`\n\nThe \"action\" field should be one of the options in [Available Actions] and the \"text\" field should be the response you want to send. Do not including any thinking or internal reflection in the \"text\" field. \"thought\" should be a short description of what the agent is thinking about before responding, inlcuding a brief justification for the response.`;\n\nexport const twitterPostTemplate = `# Task: Create a post in the voice and style and perspective of {{agentName}} @{{twitterUserName}}.\n{{providers}}\nWrite a post that is {{adjective}} about {{topic}} (without mentioning {{topic}} directly), from the perspective of {{agentName}}. Do not add commentary or acknowledge this request, just write the post.\nYour response should be 1, 2, or 3 sentences (choose the length at random).\nYour response should not contain any questions. Brief, concise statements only. The total character count MUST be less than 280. No emojis. Use \\\\n\\\\n (double spaces) between statements if there are multiple statements in your response.`;\n","import {\n\tlogger,\n\ttype TestSuite,\n\ttype IAgentRuntime,\n\tModelTypes,\n\tstringToUuid,\n\tcreateUniqueUuid,\n} from \"@elizaos/core\";\nimport type { TwitterClient } from \"./index.ts\";\nimport { SearchMode } from \"./client/index.ts\";\nimport { fetchMediaData } from \"./utils.ts\";\nimport { ServiceTypes } from \"./types.ts\";\n\nconst TEST_IMAGE_URL =\n\t\"https://github.com/elizaOS/awesome-eliza/blob/main/assets/eliza-logo.jpg?raw=true\";\n\nconst TEST_IMAGE = {\n\tid: \"mock-image-id\",\n\ttext: \"mock image\",\n\tdescription: \"mock image descirption\",\n\tsource: \"mock image source\",\n\turl: TEST_IMAGE_URL,\n\ttitle: \"mock image\",\n\tcontentType: \"image/jpeg\",\n\talt_text: \"mock image\",\n};\n\nexport class TwitterTestSuite implements TestSuite {\n\tname = \"twitter\";\n\tprivate twitterClient: TwitterClient | null = null;\n\ttests: { name: string; fn: (runtime: IAgentRuntime) => Promise<void> }[];\n\n\tconstructor() {\n\t\tthis.tests = [\n\t\t\t{\n\t\t\t\tname: \"Initialize Twitter Client\",\n\t\t\t\tfn: this.testInitializingClient.bind(this),\n\t\t\t},\n\t\t\t{ name: \"Fetch Profile\", fn: this.testFetchProfile.bind(this) },\n\t\t\t{\n\t\t\t\tname: \"Fetch Search Tweets\",\n\t\t\t\tfn: this.testFetchSearchTweets.bind(this),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: \"Fetch Home Timeline\",\n\t\t\t\tfn: this.testFetchHomeTimeline.bind(this),\n\t\t\t},\n\t\t\t{ name: \"Fetch Own Posts\", fn: this.testFetchOwnPosts.bind(this) },\n\t\t\t{ name: \"Post Tweet\", fn: this.testPostTweet.bind(this) },\n\t\t\t{ name: \"Post Tweet With Image\", fn: this.testPostImageTweet.bind(this) },\n\t\t\t{ name: \"Generate New Tweet\", fn: this.testGenerateNewTweet.bind(this) },\n\t\t\t{\n\t\t\t\tname: \"Handle Tweet Response\",\n\t\t\t\tfn: this.testHandleTweetResponse.bind(this),\n\t\t\t},\n\t\t];\n\t}\n\n\tasync testInitializingClient(runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst manager = runtime.getService(ServiceTypes.TWITTER);\n\t\t\tif (!manager) {\n\t\t\t\tthrow new Error(\"Twitter client manager not found\");\n\t\t\t}\n\n\t\t\tconst clientId = stringToUuid(\"default\");\n\t\t\tthis.twitterClient = manager.clients.get(\n\t\t\t\tmanager.getClientKey(clientId, runtime.agentId),\n\t\t\t);\n\n\t\t\tif (this.twitterClient) {\n\t\t\t\tlogger.success(\"TwitterClient initialized successfully.\");\n\t\t\t} else {\n\t\t\t\tthrow new Error(\"TwitterClient failed to initialize.\");\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error in initializing Twitter client: ${error}`);\n\t\t}\n\t}\n\n\tasync testFetchProfile(runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst username = runtime.getSetting(\"TWITTER_USERNAME\") as string;\n\t\t\tconst profile = await this.twitterClient.client.fetchProfile(username);\n\t\t\tif (!profile || !profile.id) {\n\t\t\t\tthrow new Error(\"Profile fetch failed.\");\n\t\t\t}\n\t\t\tlogger.log(\"Successfully fetched Twitter profile:\", profile);\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error fetching Twitter profile: ${error}`);\n\t\t}\n\t}\n\n\tasync testFetchSearchTweets(_runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst tweets = await this.twitterClient.client.fetchSearchTweets(\n\t\t\t\t`@${this.twitterClient.client.profile?.username}`,\n\t\t\t\t5,\n\t\t\t\tSearchMode.Latest,\n\t\t\t);\n\n\t\t\tconsole.log(\n\t\t\t\t`Successfully fetched ${tweets.tweets.length} search tweets.`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error fetching search tweets: ${error}`);\n\t\t}\n\t}\n\n\tasync testFetchHomeTimeline(_runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst timeline = await this.twitterClient.client.fetchHomeTimeline(5);\n\t\t\tif (!timeline || timeline.length === 0) {\n\t\t\t\tthrow new Error(\"No tweets in home timeline.\");\n\t\t\t}\n\t\t\tlogger.log(\n\t\t\t\t`Successfully fetched ${timeline.length} tweets from home timeline.`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error fetching home timeline: ${error}`);\n\t\t}\n\t}\n\n\tasync testFetchOwnPosts(_runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst posts = await this.twitterClient.client.fetchOwnPosts(5);\n\t\t\tif (!posts || posts.length === 0) {\n\t\t\t\tthrow new Error(\"No own posts found.\");\n\t\t\t}\n\t\t\tlogger.log(`Successfully fetched ${posts.length} own posts.`);\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error fetching own posts: ${error}`);\n\t\t}\n\t}\n\n\tasync testPostTweet(runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst roomId = createUniqueUuid(runtime, \"twitter_mock_room\");\n\n\t\t\tconst postClient = this.twitterClient.post;\n\t\t\tconst tweetText = await this.generateRandomTweetContent(runtime);\n\t\t\tawait postClient.postTweet(\n\t\t\t\truntime,\n\t\t\t\tthis.twitterClient.client,\n\t\t\t\ttweetText,\n\t\t\t\troomId,\n\t\t\t\ttweetText,\n\t\t\t\t\"test-username\",\n\t\t\t);\n\t\t\tlogger.success(\"Successfully posted a test tweet.\");\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error posting a tweet: ${error}`);\n\t\t}\n\t}\n\n\tasync testPostImageTweet(runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst roomId = createUniqueUuid(runtime, \"twitter_mock_room\");\n\n\t\t\tconst postClient = this.twitterClient.post;\n\t\t\tconst tweetText = await this.generateRandomTweetContent(\n\t\t\t\truntime,\n\t\t\t\t\"image_post\",\n\t\t\t);\n\t\t\tconst mediaData = await fetchMediaData([TEST_IMAGE]);\n\t\t\tawait postClient.postTweet(\n\t\t\t\truntime,\n\t\t\t\tthis.twitterClient.client,\n\t\t\t\ttweetText,\n\t\t\t\troomId,\n\t\t\t\ttweetText,\n\t\t\t\t\"test-username\",\n\t\t\t\tmediaData,\n\t\t\t);\n\t\t\tlogger.success(\"Successfully posted a test tweet.\");\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error posting a tweet: ${error}`);\n\t\t}\n\t}\n\n\tasync testGenerateNewTweet(_runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst postClient = this.twitterClient.post;\n\t\t\tawait postClient.generateNewTweet();\n\t\t\tlogger.success(\"Successfully generated a new tweet.\");\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error generating new tweet: ${error}`);\n\t\t}\n\t}\n\n\tasync testHandleTweetResponse(runtime: IAgentRuntime) {\n\t\ttry {\n\t\t\tconst testTweet = {\n\t\t\t\tid: \"12345\",\n\t\t\t\ttext: \"@testUser What do you think about AI?\",\n\t\t\t\tusername: \"randomUser\",\n\t\t\t\tentityId: \"randomUserId\",\n\t\t\t\ttimestamp: Date.now() / 1000,\n\t\t\t\tconversationId: \"67890\",\n\t\t\t\tpermanentUrl: \"https://twitter.com/randomUser/status/12345\",\n\t\t\t\tphotos: [TEST_IMAGE],\n\t\t\t\thashtags: [],\n\t\t\t\tmentions: [],\n\t\t\t\tthread: [],\n\t\t\t\turls: [],\n\t\t\t\tvideos: [],\n\t\t\t};\n\n\t\t\tawait this.twitterClient.interaction.handleTweet({\n\t\t\t\ttweet: testTweet,\n\t\t\t\tmessage: {\n\t\t\t\t\tcontent: { text: testTweet.text, source: \"twitter\" },\n\t\t\t\t\tagentId: runtime.agentId,\n\t\t\t\t\tentityId: createUniqueUuid(runtime, testTweet.entityId),\n\t\t\t\t\troomId: createUniqueUuid(runtime, testTweet.conversationId),\n\t\t\t\t},\n\t\t\t\tthread: [],\n\t\t\t});\n\n\t\t\tlogger.success(\"Correct response decision.\");\n\t\t} catch (error) {\n\t\t\tthrow new Error(`Error handling tweet response: ${error}`);\n\t\t}\n\t}\n\n\tprivate async generateRandomTweetContent(\n\t\truntime: IAgentRuntime,\n\t\tcontext?: string,\n\t) {\n\t\tlet prompt: string;\n\n\t\tif (context === \"image_post\") {\n\t\t\tprompt = `Generate a short, engaging tweet to accompany an image. \n It should feel natural and fit the tone of social media.\n Keep it brief (under 150 characters).\n It can be witty, descriptive, or thought-provoking.\n Avoid generic captions like \"Look at this\" or \"Nice picture.\"`;\n\t\t} else {\n\t\t\tprompt = `Generate a natural and engaging tweet. \n It should feel human, casual, and slightly thought-provoking. \n Keep it under 280 characters. \n Avoid generic bot-like statements. \n Make it sound like something a real person would tweet. \n Here’s an example format:\n - A random thought about life, technology, or human nature.\n - A short, witty observation about the current moment.\n - A lighthearted take on everyday situations.\n Do not include hashtags or emojis.`;\n\t\t}\n\n\t\treturn await runtime.useModel(ModelTypes.TEXT_SMALL, {\n\t\t\tprompt,\n\t\t});\n\t}\n}\n","import type { TwitterService } from \".\";\nimport type { ClientBase } from \"./base\";\nimport type { TwitterInteractionClient } from \"./interactions\";\nimport type { TwitterPostClient } from \"./post\";\nimport type { TwitterSpaceClient } from \"./spaces\";\n\nexport type MediaData = {\n\tdata: Buffer;\n\tmediaType: string;\n};\n\nexport interface ActionResponse {\n\tlike: boolean;\n\tretweet: boolean;\n\tquote?: boolean;\n\treply?: boolean;\n}\n\nexport interface ITwitterClient {\n\tclient: ClientBase;\n\tpost: TwitterPostClient;\n\tinteraction: TwitterInteractionClient;\n\tspace?: TwitterSpaceClient;\n\tservice: TwitterService;\n}\n\nexport const ServiceTypes = {\n\tTWITTER: \"twitter\",\n} as const;\n"],"mappings":";AAAA;AAAA,EACC,UAAAA;AAAA,EACA;AAAA,OAIM;;;ACNP;AAAA,EAOC;AAAA,OACM;AAEP,IAAM,qBAAqB;AAAA,EAC1B,MAAM;AAAA,EACN,SAAS,CAAC,kBAAkB,cAAc,WAAW,cAAc;AAAA,EACnE,aACC;AAAA,EACD,UAAU,OAAO,UAAyB,SAAiB,WAAkB;AAE5E,QAAI,QAAQ,QAAQ,WAAW,WAA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a,EAAE,OAAO,CAAC,CAAC,GAAG,CAAC,MAAM,MAAM,MAAS;AAAA,IACjE;AAGA,QAAI;AACH,UACC,OAAO;AAAA,MAEP,OAAO,oBACP,OAAO,eAKN;AACD,QAAAA,SAAO,KAAK,yDAAyD;AACrE,cAAM,qBAAqB;AAAA,UAC1B;AAAA,UACA,QAAQ;AAAA,UACR;AAAA,QACD;AAAA,MACD;AAAA,IACD,SAAS,OAAO;AACf,MAAAA,SAAO,MAAM,4CAA4C,KAAK;AAAA,IAC/D;AAEA,WAAO;AAAA,EACR;AAAA,EAEA,MAAM,OAAsB;AAC3B,UAAM,KAAK,eAAe;AAAA,EAC3B;AAAA,EAEA,MAAM,iBAAgC;AACrC,eAAW,CAAC,KAAK,MAAM,KAAK,KAAK,QAAQ,QAAQ,GAAG;AACnD,UAAI;AACH,cAAM,OAAO,QAAQ,KAAK;AAC1B,aAAK,QAAQ,OAAO,GAAG;AAAA,MACxB,SAAS,OAAO;AACf,QAAAA,SAAO,MAAM,iCAAiC,GAAG,KAAK,KAAK;AAAA,MAC5D;AAAA,IACD;AAAA,EACD;AAAA,EAEQ,aAAa,UAAkB,SAAuB;AAC7D,WAAO,GAAG,QAAQ,IAAI,OAAO;AAAA,EAC9B;AACD;AAEA,IAAM,gBAAwB;AAAA,EAC7B,MAAM;AAAA,EACN,aAAa;AAAA,EACb,UAAU,CAAC,cAAc;AAAA,EACzB,SAAS,CAAC,eAAO,iBAAS;AAAA,EAC1B,OAAO,CAAC,IAAI,iBAAiB,CAAC;AAC/B;AAEA,IAAO,gBAAQ;","names":["logger","logger","logger","ModelTypes","Headers","Headers","bearerToken","CookieJar","Headers","CookieJar","Headers","stringify","features","stringify","Headers","stringify","features","Headers","stringify","features","endpoints","user","place","data","mediaData","mediaType","features","features","features","features","features","EventEmitter","EventEmitter","wrtc","EventEmitter","wrtc","EventEmitter","Headers","Headers","logger","EventEmitter","EventEmitter","EventEmitter","logger","SttTtsPlugin","ChannelType","ModelTypes","createUniqueUuid","logger","logger","createUniqueUuid","ChannelType","ModelTypes","logger","SttTtsPlugin","logger","ModelTypes","logger","tweet","spaceJoined","ChannelType","createUniqueUuid","logger","EventEmitter","EventEmitter","authToken","ct0","guestId","logger","existingMemories","createUniqueUuid","existingMemoryIds","tweetsToSave","ChannelType","profile","ChannelType","composePrompt","createUniqueUuid","logger","ModelTypes","logger","createUniqueUuid","ChannelType","tweet","ModelTypes","message","composePrompt","response","tweetId","ChannelType","composePrompt","createUniqueUuid","logger","ModelTypes","parseJSONObjectFromText","logger","ChannelType","createUniqueUuid","composePrompt","ModelTypes","parseJSONObjectFromText","logger","ModelTypes","stringToUuid","createUniqueUuid","ServiceTypes","ServiceTypes","stringToUuid","logger","createUniqueUuid","ModelTypes","logger"]}
|