/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { launchGhostBrowser, type GhostBrowser, } from "../profiles/ghost"; import { randomWait, scrollHuman } from "../profiles/humanize"; export interface XComProfileData { username: string; markdownSnapshot: string; screenshot?: Uint8Array; } /** Scraper for public X.com profiles using BXC's Ghost profile. */ export class XComScraper { private ghost: GhostBrowser | null = null; async init(_options?: { headless?: boolean }): Promise { if (this.ghost) return; this.ghost = await launchGhostBrowser({ locale: "en-US", timezone: "America/New_York", log: (msg) => console.log(msg), }); if (this.ghost.page.blockResources) { await this.ghost.page.blockResources(["image", "media", "font"]); } } async extractProfile( username: string, withScreenshot = false, ): Promise { if (!this.ghost) { throw new Error("Scraper not initialized. Call init() first."); } const response = await this.ghost.page.goto(`https://x.com/${username}`, { timeoutMs: 30_000, }); if (!response.ok && response.status !== 0) { console.warn( `[XComScraper] Navigation returned status ${response.status}`, ); } await randomWait(3000, 5000); try { await this.ghost.page.waitForSelector("#react-root", 15_000); } catch { console.warn("[XComScraper] #react-root was not found in time."); } await scrollHuman(this.ghost.page, 300); await randomWait(1000, 2000); return { username, markdownSnapshot: await this.ghost.page.markdown(), screenshot: withScreenshot ? await this.ghost.page.screenshot({ format: "png" }) : undefined, }; } async aiExtractProfileInfo(): Promise { if (!this.ghost) throw new Error("Not initialized"); const page = this.ghost.page as typeof this.ghost.page & { aiExtract?: (prompt: string) => Promise<{ data: unknown }>; }; if (!page.aiExtract) { throw new Error("aiExtract is not available on this page object."); } const result = await page.aiExtract( "Extract the user's display name, handle, bio description, number of following, and number of followers.", ); return result.data; } async close(): Promise { if (this.ghost) { await this.ghost.close(); this.ghost = null; } } }