mirror of
https://github.com/jackwener/OpenCLI.git
synced 2026-09-14 18:25:42 +08:00
4fe9a73ebc
* refactor: migrate adapter imports to package exports Replace all relative imports (../../src/registry.js, ../../browser/cdp.js, etc.) with package exports (@jackwener/opencli/registry, @jackwener/opencli/errors, etc.) across all 484 adapter files. This decouples adapter import resolution from directory structure: - User CLIs in ~/.opencli/clis/ resolve via node_modules symlink - Internal adapters resolve via Node.js self-referencing - No more shim files needed for import resolution Changes: - package.json: add sub-path exports for all public modules - clis/**: replace relative imports with @jackwener/opencli/... - discovery.ts: simplify ensureUserCliCompatShims to symlink-only - registry-api.ts: export CommandArgs type - Remove root-level shim directories (browser/, download/, pipeline/) - Remove shim entries from tsconfig.json include and package.json files * test: add regression tests for package exports Prevents regressions like #788/#791 by: 1. Scanning all adapter files for forbidden relative imports (../../src/, ../../browser/, etc.) — fails if any remain 2. Verifying every package.json export maps to an existing source file 18 new test cases. * fix: use junction on Windows + broaden test patterns - discovery.ts: use 'junction' symlink type on Windows (no admin required) - package-exports.test.ts: generalize forbidden patterns to catch any depth of ../ traversal (not just ../../ and ../../../) * fix: update stale vi.mock/importActual paths in adapter tests Test files still used old relative paths for vi.mock() and vi.importActual() calls. Updated 5 test files to use package exports. Also broadened regression test patterns to catch mock/importActual paths. * fix: use rm instead of unlink for symlink cleanup, add warn on failure Addresses review feedback from Astro-Han: - rm() handles both symlinks and stale directories (unlink fails on dirs) - Log a warning when symlink creation fails instead of silent catch * docs: update import examples to use package exports Update all documentation, contributing guides, and skills to use @jackwener/opencli/registry instead of ../../src/registry.js. Without this, users following the docs would write adapters with broken imports since the old shim files are no longer created.
111 lines
4.7 KiB
TypeScript
111 lines
4.7 KiB
TypeScript
import * as fs from 'node:fs';
|
|
import * as path from 'node:path';
|
|
import { cli, Strategy } from '@jackwener/opencli/registry';
|
|
import { CommandExecutionError } from '@jackwener/opencli/errors';
|
|
import type { IPage } from '@jackwener/opencli/types';
|
|
|
|
const MAX_IMAGES = 4;
|
|
const UPLOAD_POLL_MS = 500;
|
|
const UPLOAD_TIMEOUT_MS = 30_000;
|
|
const SUPPORTED_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp']);
|
|
|
|
function validateImagePaths(raw: string): string[] {
|
|
const paths = raw.split(',').map(s => s.trim()).filter(Boolean);
|
|
if (paths.length > MAX_IMAGES) {
|
|
throw new CommandExecutionError(`Too many images: ${paths.length} (max ${MAX_IMAGES})`);
|
|
}
|
|
return paths.map(p => {
|
|
const absPath = path.resolve(p);
|
|
const ext = path.extname(absPath).toLowerCase();
|
|
if (!SUPPORTED_EXTENSIONS.has(ext)) {
|
|
throw new CommandExecutionError(`Unsupported image format "${ext}". Supported: jpg, png, gif, webp`);
|
|
}
|
|
const stat = fs.statSync(absPath, { throwIfNoEntry: false } as any);
|
|
if (!stat || !stat.isFile()) {
|
|
throw new CommandExecutionError(`Not a valid file: ${absPath}`);
|
|
}
|
|
return absPath;
|
|
});
|
|
}
|
|
|
|
cli({
|
|
site: 'twitter',
|
|
name: 'post',
|
|
description: 'Post a new tweet/thread',
|
|
domain: 'x.com',
|
|
strategy: Strategy.UI,
|
|
browser: true,
|
|
args: [
|
|
{ name: 'text', type: 'string', required: true, positional: true, help: 'The text content of the tweet' },
|
|
{ name: 'images', type: 'string', required: false, help: 'Image paths, comma-separated, max 4 (jpg/png/gif/webp)' },
|
|
],
|
|
columns: ['status', 'message', 'text'],
|
|
func: async (page: IPage | null, kwargs: any) => {
|
|
if (!page) throw new CommandExecutionError('Browser session required for twitter post');
|
|
|
|
// Validate images upfront before any browser interaction
|
|
const absPaths = kwargs.images ? validateImagePaths(String(kwargs.images)) : [];
|
|
|
|
// 1. Navigate to compose modal
|
|
await page.goto('https://x.com/compose/tweet');
|
|
await page.wait(3);
|
|
|
|
// 2. Type the text via clipboard paste (handles newlines in Draft.js)
|
|
const typeResult = await page.evaluate(`(async () => {
|
|
try {
|
|
const box = document.querySelector('[data-testid="tweetTextarea_0"]');
|
|
if (!box) return { ok: false, message: 'Could not find the tweet composer text area.' };
|
|
box.focus();
|
|
const dt = new DataTransfer();
|
|
dt.setData('text/plain', ${JSON.stringify(kwargs.text)});
|
|
box.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }));
|
|
return { ok: true };
|
|
} catch (e) { return { ok: false, message: String(e) }; }
|
|
})()`);
|
|
|
|
if (!typeResult.ok) {
|
|
return [{ status: 'failed', message: typeResult.message, text: kwargs.text }];
|
|
}
|
|
|
|
// 3. Attach images if provided
|
|
if (absPaths.length > 0) {
|
|
if (!page.setFileInput) {
|
|
throw new CommandExecutionError('Browser extension does not support file upload. Please update the extension.');
|
|
}
|
|
await page.setFileInput(absPaths, 'input[data-testid="fileInput"]');
|
|
|
|
// Poll until attachments render and tweet button is enabled
|
|
const pollIterations = Math.ceil(UPLOAD_TIMEOUT_MS / UPLOAD_POLL_MS);
|
|
const uploaded = await page.evaluate(`(async () => {
|
|
for (let i = 0; i < ${JSON.stringify(pollIterations)}; i++) {
|
|
await new Promise(r => setTimeout(r, ${JSON.stringify(UPLOAD_POLL_MS)}));
|
|
const container = document.querySelector('[data-testid="attachments"]');
|
|
if (!container) continue;
|
|
if (container.querySelectorAll('[role="group"]').length !== ${JSON.stringify(absPaths.length)}) continue;
|
|
const btn = document.querySelector('[data-testid="tweetButton"]') || document.querySelector('[data-testid="tweetButtonInline"]');
|
|
if (btn && !btn.disabled) return true;
|
|
}
|
|
return false;
|
|
})()`);
|
|
|
|
if (!uploaded) {
|
|
return [{ status: 'failed', message: `Image upload timed out (${UPLOAD_TIMEOUT_MS / 1000}s).`, text: kwargs.text }];
|
|
}
|
|
}
|
|
|
|
// 4. Click the post button
|
|
await page.wait(1);
|
|
const result = await page.evaluate(`(async () => {
|
|
try {
|
|
const btn = document.querySelector('[data-testid="tweetButton"]') || document.querySelector('[data-testid="tweetButtonInline"]');
|
|
if (btn && !btn.disabled) { btn.click(); return { ok: true, message: 'Tweet posted successfully.' }; }
|
|
return { ok: false, message: 'Tweet button is disabled or not found.' };
|
|
} catch (e) { return { ok: false, message: String(e) }; }
|
|
})()`);
|
|
|
|
if (result.ok) await page.wait(3);
|
|
|
|
return [{ status: result.ok ? 'success' : 'failed', message: result.message, text: kwargs.text }];
|
|
}
|
|
});
|