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.
4.7 KiB
4.7 KiB
Contributing
Thanks for your interest in contributing to OpenCLI.
Quick Start
# 1. Fork & clone
git clone git@github.com:<your-username>/opencli.git
cd opencli
# 2. Install dependencies
npm install
# 3. Build
npm run build
# 4. Run a few checks
npx tsc --noEmit
npm test
npm run test:adapter
# 5. Link globally (optional, for testing `opencli` command)
npm link
Adding a New Site Adapter
This is the most common type of contribution. Start with YAML when possible, and use TypeScript only when you need browser-side logic or multi-step flows.
Before you start:
- Prefer positional args for the command's primary subject (
search <query>,topic <id>,download <url>). Reserve named flags for optional modifiers such as--limit,--sort,--lang, and--output. - Normalize expected adapter failures to
CliErrorsubclasses instead of rawErrorwhenever possible. PreferAuthRequiredError,EmptyResultError,CommandExecutionError,TimeoutError, andArgumentErrorso the top-level CLI can render better messages and hints. - If you add a new adapter or make a command newly discoverable, update the matching doc page and the user-facing indexes that expose it.
YAML Adapter (Recommended for data-fetching commands)
Create a file like clis/<site>/<command>.yaml:
::: v-pre
site: mysite
name: trending
description: Trending posts on MySite
domain: www.mysite.com
strategy: public # public | cookie | header
browser: false # true if browser session is needed
args:
limit:
type: int
default: 20
description: Number of items
pipeline:
- fetch:
url: https://api.mysite.com/trending
- map:
rank: ${{ index + 1 }}
title: ${{ item.title }}
score: ${{ item.score }}
url: ${{ item.url }}
- limit: ${{ args.limit }}
columns: [rank, title, score, url]
:::
See hackernews/top.yaml for a real example.
TypeScript Adapter (For complex browser interactions)
Create a file like clis/<site>/<command>.ts:
import { cli, Strategy } from '@jackwener/opencli/registry';
import { CommandExecutionError, EmptyResultError } from '@jackwener/opencli/errors';
cli({
site: 'mysite',
name: 'search',
description: 'Search MySite',
domain: 'www.mysite.com',
strategy: Strategy.COOKIE,
args: [
{ name: 'query', positional: true, required: true, help: 'Search query' },
{ name: 'limit', type: 'int', default: 10, help: 'Max results' },
],
columns: ['title', 'url', 'date'],
func: async (page, kwargs) => {
const { query, limit = 10 } = kwargs;
// ... browser automation logic
if (!Array.isArray(data)) throw new CommandExecutionError('MySite returned an unexpected response');
if (!data.length) throw new EmptyResultError('mysite search', 'Try a different keyword');
return data.slice(0, Number(limit)).map((item: any) => ({
title: item.title,
url: item.url,
date: item.created_at,
}));
},
});
Validate Your Adapter
opencli validate # Validate YAML syntax and schema
opencli <site> <command> --limit 3 -f json # Test your command
opencli <site> <command> -v # Verbose mode for debugging
Code Style
- TypeScript strict mode — avoid
anywhere possible. - ES Modules — use
.jsextensions in imports (TypeScript output). - Naming:
kebab-casefor files,camelCasefor variables/functions,PascalCasefor types/classes. - No default exports — use named exports.
- Errors — throw
CliErrorsubclasses for expected adapter failures; avoid rawErrorfor normal adapter control flow.
Commit Convention
We use Conventional Commits:
feat(twitter): add thread command
fix(browser): handle CDP timeout gracefully
docs: update CONTRIBUTING.md
test(reddit): add e2e test for save command
chore: bump vitest to v4
Submitting a Pull Request
- Create a feature branch:
git checkout -b feat/mysite-trending - Make your changes and add tests when relevant
- Run the checks:
npx tsc --noEmit # Type check npm test # Core unit tests npm run test:adapter # Focused adapter tests (if adapter logic changed) opencli validate # YAML validation (if applicable) - Commit using conventional commit format
- Push and open a PR
If your PR adds a new adapter or changes user-facing commands, also verify:
- Adapter docs exist under
docs/adapters/ docs/adapters/index.mdis updated for new adapters- VitePress sidebar includes the new doc page
README.md/README.zh-CN.mdstay aligned when command discoverability changes