mirror of
https://github.com/JimLiu/baoyu-skills.git
synced 2026-08-07 09:23:04 +08:00
refactor: unify skill cdp and release artifacts
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
"": {
|
||||
"name": "baoyu-post-to-x-scripts",
|
||||
"dependencies": {
|
||||
"baoyu-chrome-cdp": "file:../../../packages/baoyu-chrome-cdp",
|
||||
"front-matter": "^4.0.2",
|
||||
"highlight.js": "^11.11.1",
|
||||
"marked": "^15.0.6",
|
||||
@@ -27,6 +28,8 @@
|
||||
|
||||
"bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
|
||||
|
||||
"baoyu-chrome-cdp": ["baoyu-chrome-cdp@file:../../../packages/baoyu-chrome-cdp", {}],
|
||||
|
||||
"character-entities": ["character-entities@2.0.2", "", {}, "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ=="],
|
||||
|
||||
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"baoyu-chrome-cdp": "file:../../../packages/baoyu-chrome-cdp",
|
||||
"front-matter": "^4.0.2",
|
||||
"highlight.js": "^11.11.1",
|
||||
"marked": "^15.0.6",
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
|
||||
import { parseMarkdown } from './md-to-html.js';
|
||||
import {
|
||||
@@ -11,9 +8,10 @@ import {
|
||||
CdpConnection,
|
||||
copyHtmlToClipboard,
|
||||
copyImageToClipboard,
|
||||
findChromeExecutable,
|
||||
findExistingChromeDebugPort,
|
||||
getDefaultProfileDir,
|
||||
getFreePort,
|
||||
launchChrome,
|
||||
openPageSession,
|
||||
pasteFromClipboard,
|
||||
sleep,
|
||||
waitForChromeDebugPort,
|
||||
@@ -61,25 +59,6 @@ interface ArticleOptions {
|
||||
chromePath?: string;
|
||||
}
|
||||
|
||||
async function findExistingDebugPort(profileDir: string): Promise<number | null> {
|
||||
const portFile = path.join(profileDir, 'DevToolsActivePort');
|
||||
if (!fs.existsSync(portFile)) return null;
|
||||
|
||||
try {
|
||||
const content = fs.readFileSync(portFile, 'utf-8').trim();
|
||||
if (!content) return null;
|
||||
const [portLine] = content.split(/\r?\n/);
|
||||
const port = Number(portLine);
|
||||
if (!Number.isFinite(port) || port <= 0) return null;
|
||||
|
||||
// Verify the port is actually active.
|
||||
await waitForChromeDebugPort(port, 1500, { includeLastError: true });
|
||||
return port;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function publishArticle(options: ArticleOptions): Promise<void> {
|
||||
const { markdownPath, submit = false, profileDir = getDefaultProfileDir() } = options;
|
||||
|
||||
@@ -98,31 +77,17 @@ export async function publishArticle(options: ArticleOptions): Promise<void> {
|
||||
await writeFile(htmlPath, parsed.html, 'utf-8');
|
||||
console.log(`[x-article] HTML saved to: ${htmlPath}`);
|
||||
|
||||
const chromePath = options.chromePath ?? findChromeExecutable(CHROME_CANDIDATES_BASIC);
|
||||
if (!chromePath) throw new Error('Chrome not found');
|
||||
|
||||
await mkdir(profileDir, { recursive: true });
|
||||
const existingPort = await findExistingDebugPort(profileDir);
|
||||
const port = existingPort ?? await getFreePort();
|
||||
const existingPort = await findExistingChromeDebugPort(profileDir);
|
||||
const reusing = existingPort !== null;
|
||||
let port = existingPort ?? 0;
|
||||
|
||||
if (existingPort) {
|
||||
if (reusing) {
|
||||
console.log(`[x-article] Reusing existing Chrome instance on port ${port}`);
|
||||
} else {
|
||||
console.log(`[x-article] Launching Chrome...`);
|
||||
const chromeArgs = [
|
||||
`--remote-debugging-port=${port}`,
|
||||
`--user-data-dir=${profileDir}`,
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--start-maximized',
|
||||
X_ARTICLES_URL,
|
||||
];
|
||||
if (process.platform === 'darwin') {
|
||||
const appPath = chromePath.replace(/\/Contents\/MacOS\/Google Chrome$/, '');
|
||||
spawn('open', ['-na', appPath, '--args', ...chromeArgs], { stdio: 'ignore' });
|
||||
} else {
|
||||
spawn(chromePath, chromeArgs, { stdio: 'ignore' });
|
||||
}
|
||||
const launched = await launchChrome(X_ARTICLES_URL, profileDir, CHROME_CANDIDATES_BASIC, options.chromePath);
|
||||
port = launched.port;
|
||||
}
|
||||
|
||||
let cdp: CdpConnection | null = null;
|
||||
@@ -131,20 +96,16 @@ export async function publishArticle(options: ArticleOptions): Promise<void> {
|
||||
const wsUrl = await waitForChromeDebugPort(port, 30_000, { includeLastError: true });
|
||||
cdp = await CdpConnection.connect(wsUrl, 30_000, { defaultTimeoutMs: 60_000 });
|
||||
|
||||
// Get page target
|
||||
const targets = await cdp.send<{ targetInfos: Array<{ targetId: string; url: string; type: string }> }>('Target.getTargets');
|
||||
let pageTarget = targets.targetInfos.find((t) => t.type === 'page' && t.url.startsWith(X_ARTICLES_URL));
|
||||
|
||||
if (!pageTarget) {
|
||||
const { targetId } = await cdp.send<{ targetId: string }>('Target.createTarget', { url: X_ARTICLES_URL });
|
||||
pageTarget = { targetId, url: X_ARTICLES_URL, type: 'page' };
|
||||
}
|
||||
|
||||
const { sessionId } = await cdp.send<{ sessionId: string }>('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true });
|
||||
|
||||
await cdp.send('Page.enable', {}, { sessionId });
|
||||
await cdp.send('Runtime.enable', {}, { sessionId });
|
||||
await cdp.send('DOM.enable', {}, { sessionId });
|
||||
const page = await openPageSession({
|
||||
cdp,
|
||||
reusing,
|
||||
url: X_ARTICLES_URL,
|
||||
matchTarget: (target) => target.type === 'page' && target.url.startsWith(X_ARTICLES_URL),
|
||||
enablePage: true,
|
||||
enableRuntime: true,
|
||||
enableDom: true,
|
||||
});
|
||||
const { sessionId } = page;
|
||||
|
||||
console.log('[x-article] Waiting for articles page...');
|
||||
await sleep(1000);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import process from 'node:process';
|
||||
@@ -6,9 +5,10 @@ import {
|
||||
CHROME_CANDIDATES_FULL,
|
||||
CdpConnection,
|
||||
copyImageToClipboard,
|
||||
findChromeExecutable,
|
||||
findExistingChromeDebugPort,
|
||||
getDefaultProfileDir,
|
||||
getFreePort,
|
||||
launchChrome,
|
||||
openPageSession,
|
||||
pasteFromClipboard,
|
||||
sleep,
|
||||
waitForChromeDebugPort,
|
||||
@@ -28,22 +28,20 @@ interface XBrowserOptions {
|
||||
export async function postToX(options: XBrowserOptions): Promise<void> {
|
||||
const { text, images = [], submit = false, timeoutMs = 120_000, profileDir = getDefaultProfileDir() } = options;
|
||||
|
||||
const chromePath = options.chromePath ?? findChromeExecutable(CHROME_CANDIDATES_FULL);
|
||||
if (!chromePath) throw new Error('Chrome not found. Set X_BROWSER_CHROME_PATH env var.');
|
||||
|
||||
await mkdir(profileDir, { recursive: true });
|
||||
|
||||
const port = await getFreePort();
|
||||
console.log(`[x-browser] Launching Chrome (profile: ${profileDir})`);
|
||||
const existingPort = await findExistingChromeDebugPort(profileDir);
|
||||
const reusing = existingPort !== null;
|
||||
let port = existingPort ?? 0;
|
||||
let chrome: Awaited<ReturnType<typeof launchChrome>>['chrome'] | null = null;
|
||||
if (!reusing) {
|
||||
const launched = await launchChrome(X_COMPOSE_URL, profileDir, CHROME_CANDIDATES_FULL, options.chromePath);
|
||||
port = launched.port;
|
||||
chrome = launched.chrome;
|
||||
}
|
||||
|
||||
const chrome = spawn(chromePath, [
|
||||
`--remote-debugging-port=${port}`,
|
||||
`--user-data-dir=${profileDir}`,
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--start-maximized',
|
||||
X_COMPOSE_URL,
|
||||
], { stdio: 'ignore' });
|
||||
if (reusing) console.log(`[x-browser] Reusing existing Chrome on port ${port}`);
|
||||
else console.log(`[x-browser] Launching Chrome (profile: ${profileDir})`);
|
||||
|
||||
let cdp: CdpConnection | null = null;
|
||||
|
||||
@@ -51,18 +49,15 @@ export async function postToX(options: XBrowserOptions): Promise<void> {
|
||||
const wsUrl = await waitForChromeDebugPort(port, 30_000, { includeLastError: true });
|
||||
cdp = await CdpConnection.connect(wsUrl, 30_000, { defaultTimeoutMs: 15_000 });
|
||||
|
||||
const targets = await cdp.send<{ targetInfos: Array<{ targetId: string; url: string; type: string }> }>('Target.getTargets');
|
||||
let pageTarget = targets.targetInfos.find((t) => t.type === 'page' && t.url.includes('x.com'));
|
||||
|
||||
if (!pageTarget) {
|
||||
const { targetId } = await cdp.send<{ targetId: string }>('Target.createTarget', { url: X_COMPOSE_URL });
|
||||
pageTarget = { targetId, url: X_COMPOSE_URL, type: 'page' };
|
||||
}
|
||||
|
||||
const { sessionId } = await cdp.send<{ sessionId: string }>('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true });
|
||||
|
||||
await cdp.send('Page.enable', {}, { sessionId });
|
||||
await cdp.send('Runtime.enable', {}, { sessionId });
|
||||
const page = await openPageSession({
|
||||
cdp,
|
||||
reusing,
|
||||
url: X_COMPOSE_URL,
|
||||
matchTarget: (target) => target.type === 'page' && target.url.includes('x.com'),
|
||||
enablePage: true,
|
||||
enableRuntime: true,
|
||||
});
|
||||
const { sessionId } = page;
|
||||
await cdp.send('Input.setIgnoreInputEvents', { ignore: false }, { sessionId });
|
||||
|
||||
console.log('[x-browser] Waiting for X editor...');
|
||||
@@ -192,7 +187,9 @@ export async function postToX(options: XBrowserOptions): Promise<void> {
|
||||
if (cdp) {
|
||||
cdp.close();
|
||||
}
|
||||
chrome.unref();
|
||||
if (chrome) {
|
||||
chrome.unref();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import process from 'node:process';
|
||||
import {
|
||||
CHROME_CANDIDATES_FULL,
|
||||
CdpConnection,
|
||||
findChromeExecutable,
|
||||
findExistingChromeDebugPort,
|
||||
getDefaultProfileDir,
|
||||
getFreePort,
|
||||
killChrome,
|
||||
launchChrome,
|
||||
openPageSession,
|
||||
sleep,
|
||||
waitForChromeDebugPort,
|
||||
} from './x-utils.js';
|
||||
@@ -31,42 +32,39 @@ interface QuoteOptions {
|
||||
export async function quotePost(options: QuoteOptions): Promise<void> {
|
||||
const { tweetUrl, comment, submit = false, timeoutMs = 120_000, profileDir = getDefaultProfileDir() } = options;
|
||||
|
||||
const chromePath = options.chromePath ?? findChromeExecutable(CHROME_CANDIDATES_FULL);
|
||||
if (!chromePath) throw new Error('Chrome not found. Set X_BROWSER_CHROME_PATH env var.');
|
||||
|
||||
await mkdir(profileDir, { recursive: true });
|
||||
|
||||
const port = await getFreePort();
|
||||
console.log(`[x-quote] Launching Chrome (profile: ${profileDir})`);
|
||||
const existingPort = await findExistingChromeDebugPort(profileDir);
|
||||
const reusing = existingPort !== null;
|
||||
let port = existingPort ?? 0;
|
||||
console.log(`[x-quote] Opening tweet: ${tweetUrl}`);
|
||||
let chrome: Awaited<ReturnType<typeof launchChrome>>['chrome'] | null = null;
|
||||
if (!reusing) {
|
||||
const launched = await launchChrome(tweetUrl, profileDir, CHROME_CANDIDATES_FULL, options.chromePath);
|
||||
port = launched.port;
|
||||
chrome = launched.chrome;
|
||||
}
|
||||
|
||||
const chrome = spawn(chromePath, [
|
||||
`--remote-debugging-port=${port}`,
|
||||
`--user-data-dir=${profileDir}`,
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--start-maximized',
|
||||
tweetUrl,
|
||||
], { stdio: 'ignore' });
|
||||
if (reusing) console.log(`[x-quote] Reusing existing Chrome on port ${port}`);
|
||||
else console.log(`[x-quote] Launching Chrome (profile: ${profileDir})`);
|
||||
|
||||
let cdp: CdpConnection | null = null;
|
||||
let targetId: string | null = null;
|
||||
|
||||
try {
|
||||
const wsUrl = await waitForChromeDebugPort(port, 30_000, { includeLastError: true });
|
||||
cdp = await CdpConnection.connect(wsUrl, 30_000, { defaultTimeoutMs: 15_000 });
|
||||
|
||||
const targets = await cdp.send<{ targetInfos: Array<{ targetId: string; url: string; type: string }> }>('Target.getTargets');
|
||||
let pageTarget = targets.targetInfos.find((t) => t.type === 'page' && t.url.includes('x.com'));
|
||||
|
||||
if (!pageTarget) {
|
||||
const { targetId } = await cdp.send<{ targetId: string }>('Target.createTarget', { url: tweetUrl });
|
||||
pageTarget = { targetId, url: tweetUrl, type: 'page' };
|
||||
}
|
||||
|
||||
const { sessionId } = await cdp.send<{ sessionId: string }>('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true });
|
||||
|
||||
await cdp.send('Page.enable', {}, { sessionId });
|
||||
await cdp.send('Runtime.enable', {}, { sessionId });
|
||||
const page = await openPageSession({
|
||||
cdp,
|
||||
reusing,
|
||||
url: tweetUrl,
|
||||
matchTarget: (target) => target.type === 'page' && target.url.includes('x.com'),
|
||||
enablePage: true,
|
||||
enableRuntime: true,
|
||||
});
|
||||
const { sessionId } = page;
|
||||
targetId = page.targetId;
|
||||
|
||||
console.log('[x-quote] Waiting for tweet to load...');
|
||||
await sleep(3000);
|
||||
@@ -175,14 +173,14 @@ export async function quotePost(options: QuoteOptions): Promise<void> {
|
||||
}
|
||||
} finally {
|
||||
if (cdp) {
|
||||
try { await cdp.send('Browser.close', {}, { timeoutMs: 5_000 }); } catch {}
|
||||
if (reusing && targetId) {
|
||||
try { await cdp.send('Target.closeTarget', { targetId }, { timeoutMs: 5_000 }); } catch {}
|
||||
} else if (!reusing) {
|
||||
try { await cdp.send('Browser.close', {}, { timeoutMs: 5_000 }); } catch {}
|
||||
}
|
||||
cdp.close();
|
||||
}
|
||||
|
||||
setTimeout(() => {
|
||||
if (!chrome.killed) try { chrome.kill('SIGKILL'); } catch {}
|
||||
}, 2_000).unref?.();
|
||||
try { chrome.kill('SIGTERM'); } catch {}
|
||||
if (chrome) killChrome(chrome);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
import { execSync, spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import net from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export type PlatformCandidates = {
|
||||
darwin?: string[];
|
||||
win32?: string[];
|
||||
default: string[];
|
||||
};
|
||||
import {
|
||||
CdpConnection,
|
||||
findChromeExecutable as findChromeExecutableBase,
|
||||
findExistingChromeDebugPort as findExistingChromeDebugPortBase,
|
||||
getFreePort as getFreePortBase,
|
||||
killChrome,
|
||||
launchChrome as launchChromeBase,
|
||||
openPageSession,
|
||||
resolveSharedChromeProfileDir,
|
||||
sleep,
|
||||
waitForChromeDebugPort,
|
||||
type PlatformCandidates,
|
||||
} from 'baoyu-chrome-cdp';
|
||||
|
||||
export { CdpConnection, killChrome, openPageSession, sleep, waitForChromeDebugPort };
|
||||
export type { PlatformCandidates } from 'baoyu-chrome-cdp';
|
||||
|
||||
export const CHROME_CANDIDATES_BASIC: PlatformCandidates = {
|
||||
darwin: [
|
||||
@@ -53,20 +61,11 @@ export const CHROME_CANDIDATES_FULL: PlatformCandidates = {
|
||||
],
|
||||
};
|
||||
|
||||
function getCandidatesForPlatform(candidates: PlatformCandidates): string[] {
|
||||
if (process.platform === 'darwin' && candidates.darwin?.length) return candidates.darwin;
|
||||
if (process.platform === 'win32' && candidates.win32?.length) return candidates.win32;
|
||||
return candidates.default;
|
||||
}
|
||||
|
||||
export function findChromeExecutable(candidates: PlatformCandidates): string | undefined {
|
||||
const override = process.env.X_BROWSER_CHROME_PATH?.trim();
|
||||
if (override && fs.existsSync(override)) return override;
|
||||
|
||||
for (const candidate of getCandidatesForPlatform(candidates)) {
|
||||
if (fs.existsSync(candidate)) return candidate;
|
||||
}
|
||||
return undefined;
|
||||
return findChromeExecutableBase({
|
||||
candidates,
|
||||
envNames: ['X_BROWSER_CHROME_PATH'],
|
||||
});
|
||||
}
|
||||
|
||||
let _wslHome: string | null | undefined;
|
||||
@@ -81,158 +80,39 @@ function getWslWindowsHome(): string | null {
|
||||
}
|
||||
|
||||
export function getDefaultProfileDir(): string {
|
||||
const override = process.env.BAOYU_CHROME_PROFILE_DIR?.trim() || process.env.X_BROWSER_PROFILE_DIR?.trim();
|
||||
if (override) return path.resolve(override);
|
||||
const wslHome = getWslWindowsHome();
|
||||
if (wslHome) return path.join(wslHome, '.local', 'share', 'baoyu-skills', 'chrome-profile');
|
||||
const base = process.platform === 'darwin'
|
||||
? path.join(os.homedir(), 'Library', 'Application Support')
|
||||
: process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share');
|
||||
return path.join(base, 'baoyu-skills', 'chrome-profile');
|
||||
}
|
||||
|
||||
export function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
export async function getFreePort(): Promise<number> {
|
||||
const fixed = parseInt(process.env.X_BROWSER_DEBUG_PORT || '', 10);
|
||||
if (fixed > 0) return fixed;
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
server.unref();
|
||||
server.on('error', reject);
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === 'string') {
|
||||
server.close(() => reject(new Error('Unable to allocate a free TCP port.')));
|
||||
return;
|
||||
}
|
||||
const port = address.port;
|
||||
server.close((err) => {
|
||||
if (err) reject(err);
|
||||
else resolve(port);
|
||||
});
|
||||
});
|
||||
return resolveSharedChromeProfileDir({
|
||||
envNames: ['BAOYU_CHROME_PROFILE_DIR', 'X_BROWSER_PROFILE_DIR'],
|
||||
wslWindowsHome: getWslWindowsHome(),
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchJson<T = unknown>(url: string): Promise<T> {
|
||||
const res = await fetch(url, { redirect: 'follow' });
|
||||
if (!res.ok) throw new Error(`Request failed: ${res.status} ${res.statusText}`);
|
||||
return (await res.json()) as T;
|
||||
export async function getFreePort(): Promise<number> {
|
||||
return await getFreePortBase('X_BROWSER_DEBUG_PORT');
|
||||
}
|
||||
|
||||
export async function waitForChromeDebugPort(
|
||||
port: number,
|
||||
timeoutMs: number,
|
||||
options?: { includeLastError?: boolean },
|
||||
): Promise<string> {
|
||||
const start = Date.now();
|
||||
let lastError: unknown = null;
|
||||
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
try {
|
||||
const version = await fetchJson<{ webSocketDebuggerUrl?: string }>(`http://127.0.0.1:${port}/json/version`);
|
||||
if (version.webSocketDebuggerUrl) return version.webSocketDebuggerUrl;
|
||||
lastError = new Error('Missing webSocketDebuggerUrl');
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
await sleep(200);
|
||||
}
|
||||
|
||||
if (options?.includeLastError && lastError) {
|
||||
throw new Error(`Chrome debug port not ready: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
|
||||
}
|
||||
throw new Error('Chrome debug port not ready');
|
||||
export async function findExistingChromeDebugPort(profileDir: string): Promise<number | null> {
|
||||
return await findExistingChromeDebugPortBase({ profileDir });
|
||||
}
|
||||
|
||||
type PendingRequest = {
|
||||
resolve: (value: unknown) => void;
|
||||
reject: (error: Error) => void;
|
||||
timer: ReturnType<typeof setTimeout> | null;
|
||||
};
|
||||
export async function launchChrome(
|
||||
url: string,
|
||||
profileDir: string,
|
||||
candidates: PlatformCandidates,
|
||||
chromePathOverride?: string,
|
||||
): Promise<{ chrome: Awaited<ReturnType<typeof launchChromeBase>>; port: number }> {
|
||||
const chromePath = chromePathOverride?.trim() || findChromeExecutable(candidates);
|
||||
if (!chromePath) throw new Error('Chrome not found. Set X_BROWSER_CHROME_PATH env var.');
|
||||
|
||||
export class CdpConnection {
|
||||
private ws: WebSocket;
|
||||
private nextId = 0;
|
||||
private pending = new Map<number, PendingRequest>();
|
||||
private eventHandlers = new Map<string, Set<(params: unknown) => void>>();
|
||||
private defaultTimeoutMs: number;
|
||||
const port = await getFreePort();
|
||||
const chrome = await launchChromeBase({
|
||||
chromePath,
|
||||
profileDir,
|
||||
port,
|
||||
url,
|
||||
extraArgs: ['--start-maximized'],
|
||||
});
|
||||
|
||||
private constructor(ws: WebSocket, options?: { defaultTimeoutMs?: number }) {
|
||||
this.ws = ws;
|
||||
this.defaultTimeoutMs = options?.defaultTimeoutMs ?? 15_000;
|
||||
|
||||
this.ws.addEventListener('message', (event) => {
|
||||
try {
|
||||
const data = typeof event.data === 'string' ? event.data : new TextDecoder().decode(event.data as ArrayBuffer);
|
||||
const msg = JSON.parse(data) as { id?: number; method?: string; params?: unknown; result?: unknown; error?: { message?: string } };
|
||||
|
||||
if (msg.method) {
|
||||
const handlers = this.eventHandlers.get(msg.method);
|
||||
if (handlers) handlers.forEach((h) => h(msg.params));
|
||||
}
|
||||
|
||||
if (msg.id) {
|
||||
const pending = this.pending.get(msg.id);
|
||||
if (pending) {
|
||||
this.pending.delete(msg.id);
|
||||
if (pending.timer) clearTimeout(pending.timer);
|
||||
if (msg.error?.message) pending.reject(new Error(msg.error.message));
|
||||
else pending.resolve(msg.result);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
});
|
||||
|
||||
this.ws.addEventListener('close', () => {
|
||||
for (const [id, pending] of this.pending.entries()) {
|
||||
this.pending.delete(id);
|
||||
if (pending.timer) clearTimeout(pending.timer);
|
||||
pending.reject(new Error('CDP connection closed.'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static async connect(url: string, timeoutMs: number, options?: { defaultTimeoutMs?: number }): Promise<CdpConnection> {
|
||||
const ws = new WebSocket(url);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('CDP connection timeout.')), timeoutMs);
|
||||
ws.addEventListener('open', () => { clearTimeout(timer); resolve(); });
|
||||
ws.addEventListener('error', () => { clearTimeout(timer); reject(new Error('CDP connection failed.')); });
|
||||
});
|
||||
return new CdpConnection(ws, options);
|
||||
}
|
||||
|
||||
on(method: string, handler: (params: unknown) => void): void {
|
||||
if (!this.eventHandlers.has(method)) this.eventHandlers.set(method, new Set());
|
||||
this.eventHandlers.get(method)!.add(handler);
|
||||
}
|
||||
|
||||
async send<T = unknown>(method: string, params?: Record<string, unknown>, options?: { sessionId?: string; timeoutMs?: number }): Promise<T> {
|
||||
const id = ++this.nextId;
|
||||
const message: Record<string, unknown> = { id, method };
|
||||
if (params) message.params = params;
|
||||
if (options?.sessionId) message.sessionId = options.sessionId;
|
||||
|
||||
const timeoutMs = options?.timeoutMs ?? this.defaultTimeoutMs;
|
||||
|
||||
const result = await new Promise<unknown>((resolve, reject) => {
|
||||
const timer = timeoutMs > 0
|
||||
? setTimeout(() => { this.pending.delete(id); reject(new Error(`CDP timeout: ${method}`)); }, timeoutMs)
|
||||
: null;
|
||||
this.pending.set(id, { resolve, reject, timer });
|
||||
this.ws.send(JSON.stringify(message));
|
||||
});
|
||||
|
||||
return result as T;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
try { this.ws.close(); } catch {}
|
||||
}
|
||||
return { chrome, port };
|
||||
}
|
||||
|
||||
export function getScriptDir(): string {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
@@ -6,9 +5,11 @@ import process from 'node:process';
|
||||
import {
|
||||
CHROME_CANDIDATES_FULL,
|
||||
CdpConnection,
|
||||
findChromeExecutable,
|
||||
findExistingChromeDebugPort,
|
||||
getDefaultProfileDir,
|
||||
getFreePort,
|
||||
killChrome,
|
||||
launchChrome,
|
||||
openPageSession,
|
||||
sleep,
|
||||
waitForChromeDebugPort,
|
||||
} from './x-utils.js';
|
||||
@@ -27,9 +28,6 @@ interface XVideoOptions {
|
||||
export async function postVideoToX(options: XVideoOptions): Promise<void> {
|
||||
const { text, videoPath, submit = false, timeoutMs = 120_000, profileDir = getDefaultProfileDir() } = options;
|
||||
|
||||
const chromePath = options.chromePath ?? findChromeExecutable(CHROME_CANDIDATES_FULL);
|
||||
if (!chromePath) throw new Error('Chrome not found. Set X_BROWSER_CHROME_PATH env var.');
|
||||
|
||||
if (!fs.existsSync(videoPath)) throw new Error(`Video not found: ${videoPath}`);
|
||||
|
||||
const absVideoPath = path.resolve(videoPath);
|
||||
@@ -37,37 +35,37 @@ export async function postVideoToX(options: XVideoOptions): Promise<void> {
|
||||
|
||||
await mkdir(profileDir, { recursive: true });
|
||||
|
||||
const port = await getFreePort();
|
||||
console.log(`[x-video] Launching Chrome (profile: ${profileDir})`);
|
||||
const existingPort = await findExistingChromeDebugPort(profileDir);
|
||||
const reusing = existingPort !== null;
|
||||
let port = existingPort ?? 0;
|
||||
let chrome: Awaited<ReturnType<typeof launchChrome>>['chrome'] | null = null;
|
||||
if (!reusing) {
|
||||
const launched = await launchChrome(X_COMPOSE_URL, profileDir, CHROME_CANDIDATES_FULL, options.chromePath);
|
||||
port = launched.port;
|
||||
chrome = launched.chrome;
|
||||
}
|
||||
|
||||
const chrome = spawn(chromePath, [
|
||||
`--remote-debugging-port=${port}`,
|
||||
`--user-data-dir=${profileDir}`,
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--start-maximized',
|
||||
X_COMPOSE_URL,
|
||||
], { stdio: 'ignore' });
|
||||
if (reusing) console.log(`[x-video] Reusing existing Chrome on port ${port}`);
|
||||
else console.log(`[x-video] Launching Chrome (profile: ${profileDir})`);
|
||||
|
||||
let cdp: CdpConnection | null = null;
|
||||
let targetId: string | null = null;
|
||||
|
||||
try {
|
||||
const wsUrl = await waitForChromeDebugPort(port, 30_000, { includeLastError: true });
|
||||
cdp = await CdpConnection.connect(wsUrl, 30_000, { defaultTimeoutMs: 30_000 });
|
||||
|
||||
const targets = await cdp.send<{ targetInfos: Array<{ targetId: string; url: string; type: string }> }>('Target.getTargets');
|
||||
let pageTarget = targets.targetInfos.find((t) => t.type === 'page' && t.url.includes('x.com'));
|
||||
|
||||
if (!pageTarget) {
|
||||
const { targetId } = await cdp.send<{ targetId: string }>('Target.createTarget', { url: X_COMPOSE_URL });
|
||||
pageTarget = { targetId, url: X_COMPOSE_URL, type: 'page' };
|
||||
}
|
||||
|
||||
const { sessionId } = await cdp.send<{ sessionId: string }>('Target.attachToTarget', { targetId: pageTarget.targetId, flatten: true });
|
||||
|
||||
await cdp.send('Page.enable', {}, { sessionId });
|
||||
await cdp.send('Runtime.enable', {}, { sessionId });
|
||||
await cdp.send('DOM.enable', {}, { sessionId });
|
||||
const page = await openPageSession({
|
||||
cdp,
|
||||
reusing,
|
||||
url: X_COMPOSE_URL,
|
||||
matchTarget: (target) => target.type === 'page' && target.url.includes('x.com'),
|
||||
enablePage: true,
|
||||
enableRuntime: true,
|
||||
enableDom: true,
|
||||
});
|
||||
const { sessionId } = page;
|
||||
targetId = page.targetId;
|
||||
await cdp.send('Input.setIgnoreInputEvents', { ignore: false }, { sessionId });
|
||||
|
||||
console.log('[x-video] Waiting for X editor...');
|
||||
@@ -182,15 +180,12 @@ export async function postVideoToX(options: XVideoOptions): Promise<void> {
|
||||
}
|
||||
} finally {
|
||||
if (cdp) {
|
||||
if (reusing && submit && targetId) {
|
||||
try { await cdp.send('Target.closeTarget', { targetId }, { timeoutMs: 5_000 }); } catch {}
|
||||
}
|
||||
cdp.close();
|
||||
}
|
||||
// Don't kill Chrome in preview mode, let user review
|
||||
if (submit) {
|
||||
setTimeout(() => {
|
||||
if (!chrome.killed) try { chrome.kill('SIGKILL'); } catch {}
|
||||
}, 2_000).unref?.();
|
||||
try { chrome.kill('SIGTERM'); } catch {}
|
||||
}
|
||||
if (chrome && submit) killChrome(chrome);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user