Compare commits

..

83 Commits

Author SHA1 Message Date
jackwener 1f998e4ff0 feat(browser): migrate to self-hosted extension and remove token configuration 2026-03-18 11:49:15 +08:00
jackwener 36b06e9f32 test: cover global mcp discovery paths 2026-03-17 22:27:48 +08:00
Sheng-Yan, Zhang f0273f94bb fix: discover global @playwright/mcp in nvm/npm installs 2026-03-17 19:05:45 +08:00
jackwener 4c8c6e8be7 fix(twitter): migrate bookmarks to direct GraphQL
Release / release (push) Has been cancelled
chore: bump version to 0.7.10
2026-03-17 17:30:01 +08:00
jackwener 7b5bdfa7d5 fix(twitter): harden remaining twitter commands
Co-authored-by: Sheng-Yan, Zhang <yancode@qq.com>
2026-03-17 17:26:36 +08:00
jackwener 546c0b997a feat: Enhance setup output with token save confirmation and improved browser connectivity guidance. 2026-03-17 17:20:16 +08:00
jackwener 1e34e7e6d3 chore: bump version to 0.7.9 2026-03-17 17:11:13 +08:00
jackwener 9ae9eb3fc6 fix(twitter): rewrite timeline adapter to use direct GraphQL API
The previous implementation injected a fetch interceptor after page
navigation, but by that time the HomeTimeline API call had already
completed, resulting in 'no data captured' every time.

Rewrote to directly call Twitter's HomeTimeline GraphQL endpoint
(same pattern as profile.ts and thread.ts):
- Dynamic queryId resolution with hardcoded fallback
- Pagination support with cursor
- Filters out promoted content
- Returns structured tweet data (id, author, text, likes, retweets,
  replies, views, created_at, url)

Fixes #36
2026-03-17 17:11:02 +08:00
jackwener 612c0ab1af v0.7.8: P0 architecture refactor - split browser.ts, unified errors, strict mode
Release / release (push) Has been cancelled
2026-03-17 17:02:03 +08:00
jackwener 68840fc85c refactor: P0 architecture improvements
- Split browser.ts (700 lines) into src/browser/ module (page, mcp, errors, discover, tabs, index)
- Add unified error handling: CliError base class + logger module
- Enable TypeScript strict mode, fix 12 type errors
- Extract inline build scripts to scripts/clean-yaml.cjs and copy-yaml.cjs
- All 178 unit tests pass, build produces 83 entries across 19 sites
2026-03-17 17:01:51 +08:00
jackwener 8263a06a85 fix(completion): insert fpath before compinit in .zshrc
The postinstall script was appending the fpath line at the end of .zshrc,
but compinit (called earlier by oh-my-zsh or directly) would have already
finished scanning. This caused zsh completion to silently fail for most
users.

Now the script detects the first compinit / oh-my-zsh source line and
inserts the fpath entry before it, ensuring completion works immediately.
2026-03-17 16:53:07 +08:00
jackwener eb2c3fdf89 fix: support Chrome Dev and Chrome Beta browser variants
Add Chrome Dev and Chrome Beta profile paths to discoverExtensionToken()
and checkExtensionInstalled() across macOS, Linux, and Windows.

Closes #30
2026-03-17 16:36:19 +08:00
jackwener 43ed0ace59 0.7.6
Release / release (push) Has been cancelled
2026-03-17 16:35:20 +08:00
jackwener de962eb5fb feat: support commands completion (#32)
Add full shell tab-completion for opencli, supporting Bash, Zsh, and Fish.

Co-authored-by: RinChanNOWWW <rin_chan_now@outlook.com>

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-17 16:33:19 +08:00
jackwener d1da293ef9 0.7.5
Release / release (push) Has been cancelled
2026-03-17 16:14:02 +08:00
jackwener 25bd872a24 fix: doctor/setup edge cases — format detection, dynamic profiles, fish shell
- upsertJsonConfigToken: detect format by file path (opencode → mcp format,
  others → mcpServers). Previously empty files always got OpenCode format.
- Dynamic Chrome profile enumeration: scan for Default/Profile N directories
  instead of hardcoding 4 profiles.
- Fish shell: use 'set -gx' syntax for config.fish, not 'export'.
- Pass filePath through all callers (setup.ts, applyBrowserDoctorFix).
- Reduce setup auto-verify timeout from 8s to 5s.
- Add 7 new tests (19 total): empty file format, opencode path detection,
  claude.json path detection, fish shell set/replace/append, zshrc fallback.
2026-03-17 16:13:05 +08:00
jackwener ff3e5c6887 feat: enhance setup with precise token scan errors and auto-verify
- When token scan fails, diagnose exact cause via checkExtensionInstalled()
  (extension not installed vs token not in LevelDB)
- Show actionable fix instructions instead of generic warning
- Auto-verify browser connectivity after writing configs (Step 7)
- Simplify README setup flow to 2 steps (install + setup)
2026-03-17 16:07:38 +08:00
jackwener 2e66e3183c docs: reorder setup flow — doctor → setup → doctor --live 2026-03-17 16:02:37 +08:00
jackwener a1bcb23239 docs: reorder setup flow — doctor first, then setup
Logical flow: install extension → doctor (verify token discoverable) →
setup (distribute token to tools). --fix moved to a Tip block for
post-setup maintenance.
2026-03-17 16:00:46 +08:00
jackwener 6024af3aa0 docs: split doctor --fix into interactive and non-interactive examples 2026-03-17 15:58:53 +08:00
jackwener 1393ce3327 docs: sync Chinese README with doctor --live, command table polish 2026-03-17 14:57:13 +08:00
jackwener 0fe3b9b921 0.7.4
Release / release (push) Has been cancelled
2026-03-17 14:55:54 +08:00
jackwener 375beaa744 docs: polish README and SKILL
- Sort command table by count (descending), add Count column
- Add xiaohongshu `me`, boss `detail` to command references
- Add Self-healing setup highlight for doctor/setup workflow
- Document `doctor --live` and `doctor --fix` options
- Bump SKILL version to 0.7.3, expand tags
- Fix site count to 19, update descriptions
2026-03-17 14:50:14 +08:00
SonicKang 341c42c62f fix(opencode): use 'environment' instead of 'env' for MCP config (#29)
OpenCode config schema uses 'environment' property for MCP server
environment variables, not 'env'.

Schema reference: https://opencode.ai/config.json
2026-03-17 14:46:53 +08:00
jackwener 50b71c0936 fix: use binary read for LevelDB token discovery on all platforms
The previous strings+grep pipeline failed because LevelDB's internal
encoding fragments ASCII strings like 'auth-token' and the extension ID
across byte boundaries. Replace extractTokenViaStrings with a unified
binary read approach that scans for the extension ID prefix and searches
a 500-byte window for base64url tokens.

Also removes unused execSync import.
2026-03-17 14:44:34 +08:00
jackwener 981c167a0b feat(doctor): add extension install check and token connectivity test
- checkExtensionInstalled(): scans Chrome/Edge/Chromium Extensions dirs
- checkTokenConnectivity(): actual MCP handshake via --live flag
- Updated DoctorReport type and report rendering
- Added unit tests for new rendering (12/12 pass)
2026-03-17 14:38:16 +08:00
jackwener 2463689105 0.7.3
Release / release (push) Has been cancelled
2026-03-17 13:34:34 +08:00
jackwener c714254d8f docs: add YouTube video and transcript commands to README and SKILL 2026-03-17 13:30:42 +08:00
Ji 8e7490407c feat(youtube): add video metadata and transcript commands (#25)
Add two new YouTube adapters:

- **youtube video**: fetch metadata (title, views, description, etc.) from ytInitialPlayerResponse and ytInitialData
- **youtube transcript**: fetch subtitles via Android InnerTube API to bypass PoToken requirement on Web client caption URLs
  - Two output modes: --mode grouped (sentence merging, speaker detection, chapter headings) and --mode raw (precise sub-second timestamps)
  - CJK support with 30s time-window fallback for unpunctuated captions
  - Language selection with --lang and stderr warning on fallback
  - URL normalization for watch, youtu.be, shorts, embed, live formats

Co-authored-by: Ji Zhang <jizhang.work@gmail.com>
2026-03-17 13:26:30 +08:00
Ji 14dcd2bc5f feat(reddit): add threaded comment tree to read command (#26)
Replace flat top-level-only read.yaml with recursive tree walker:
- Configurable depth and breadth (--depth, --replies)
- Replies sorted by score, top-K selected at each level
- Hidden replies surfaced as [+N more replies]
- Multiline bodies preserve indentation at all depths
- Configurable --max_length (was hard-coded 500 chars)
- Input validation: all numeric params clamped to safe minimums
2026-03-17 13:18:11 +08:00
SiweiMa e9b9beedfe feat(linkedin): add job search adapter (#28)
* feat: add linkedin job search adapter

* fix(linkedin): fix parseCsvArg undefined bug, regex escapes in page.evaluate, replace hardcoded wait, add IPage type

* refactor(linkedin): extract evaluate logic, add progress logging, improve code structure

- Extract Voyager query/URL building into typed standalone functions
- Split fetchJobCards into its own function with per-batch evaluate
- Add SearchInput interface for type safety
- Add progress logging to enrichJobDetails (stderr)
- Add section comments for code organization
- Deduplicate normalize helpers in evaluate strings

---------

Co-authored-by: Siwei Ma <siweima@Siweis-MacBook-Pro.local>
Co-authored-by: jackwener <jakevingoo@gmail.com>
2026-03-17 13:07:16 +08:00
jackwener 59de5fb3f5 0.7.2
Release / release (push) Has been cancelled
2026-03-17 01:38:29 +08:00
jackwener 7555f14369 refactor: deep code review improvements
- Add *.log to .gitignore, remove debug.log from tracking
- Fix dev-mode FS scan to discover .ts adapter files (not just .js)
- Deduplicate CONNECT_TIMEOUT: browser.ts now uses runtime.ts constant
- Fix CSV output: escape newlines in field values per RFC 4180
- Add proper type interfaces for validate/verify (remove any types)
- Remove unused hadOuterQuotes variable in snapshotFormatter
- Derive CliOptions from CliCommand via Omit+Partial to reduce duplication
- Expand dense one-liner action callbacks in main.ts for readability
2026-03-17 01:38:23 +08:00
jackwener 2652fa40e5 chore: change license from BSD-3-Clause to Apache-2.0 2026-03-17 01:34:51 +08:00
jackwener a7c367a61b docs: update README and SKILL for new Reddit adapters
- Reddit: 4 → 15 commands (popular, read, user, user-posts,
  user-comments, upvote, save, comment, subscribe, saved, upvoted)
- Twitter: add thread command
- Xiaohongshu: remove non-existent me command
- SKILL.md: expand Reddit examples with full 15-command reference
2026-03-17 01:33:43 +08:00
jackwener fbec2f6f5d feat(snapshot): filter contentinfo subtrees, bilibili ad URLs, boilerplate buttons
- Add contentinfo to subtree-level noise filtering (biggest single win)
  - Reuters: 51% → 62%, Google: 57% → 70%, Netflix: 48% → 60%
- Add cm.bilibili.com/cm/api/fees/ ad URL pattern
- Add 广告 keyword to ad detection
- Add back-to-top / 回到顶部 boilerplate button filtering
- Unify ad/boilerplate/contentinfo into single subtree-skip mechanism
- Add vitest config and comprehensive test suite (33 tests)
- Fixture tests skip gracefully when snapshot files are absent

Bump to v0.7.1
2026-03-17 01:26:49 +08:00
jackwener c2a5cbe90e chore(release): 0.7.0
Release / release (push) Has been cancelled
2026-03-16 20:29:27 +08:00
jackwener 34e20d33f2 docs: bump version in SKILL.md to 0.7.0 2026-03-16 20:29:27 +08:00
jackwener 1c496bb85f docs: add new twitter commands (article, follow, unfollow, bookmark, unbookmark)
Also update profile example to use positional argument.
2026-03-16 20:18:50 +08:00
jackwener 0c845d58c8 feat(twitter): implement article, profile, follow, unfollow, bookmark, & unbookmark adapters
This commit introduces the long-form Article adapter, a rewritten Profile adapter, and 4 new UI-based Write commands for managing relationships and bookmarks. Also adds support for positional arguments across the dynamic CLI engine.
2026-03-16 20:17:38 +08:00
jackwener 7f55950fed feat(reddit): add 11 new adapters borrowed from rdt-cli
Phase 1 - YAML adapters (read-only):
- popular: /r/popular feed
- read: read post + comments by ID
- user: view user profile (karma, account age)
- user-posts: user's submitted posts
- user-comments: user's comment history
- search: enhanced with sort/time/subreddit params
- subreddit: enhanced with time filter for top/controversial

Phase 2 - TypeScript adapters (write operations):
- upvote: upvote/downvote posts via /api/vote
- save: save/unsave posts via /api/save
- comment: post comments via /api/comment
- subscribe: subscribe/unsubscribe subreddits
- saved: browse saved posts (auto-resolves username)
- upvoted: browse upvoted posts (auto-resolves username)

Reddit adapters: 4 → 15
2026-03-16 19:56:55 +08:00
jackwener 1576396a21 0.6.3
Release / release (push) Has been cancelled
2026-03-16 19:33:25 +08:00
jackwener 77193a0003 Merge PR #20: feat(boss): add detail adapter + security_id in search
Closes #20

Added boss detail command with fixes:
- district/address field dedup
- template string injection safety
- empty jobInfo guard
- IPage-compatible wait
2026-03-16 19:33:17 +08:00
jackwener 05b7f1bccf fix(boss): improve detail adapter quality
- Fix district/address field duplication (district now uses areaDistrict·businessDistrict)
- Fix template string injection risk in evaluate script (use JSON.stringify)
- Add jobInfo empty guard with user-friendly error message
- Replace raw setTimeout with page.wait for IPage compatibility
- Update README docs to include boss detail command
2026-03-16 19:33:00 +08:00
jackwener 9889a6db11 v0.6.2
Release / release (push) Has been cancelled
2026-03-16 18:14:34 +08:00
jackwener 61ea05bff7 fix: URL injection, strictNullChecks, cross-platform build, +34 tests
Security:
- Fix URL injection in fetch.ts and bilibili.ts (JSON.stringify instead of string interpolation)
- Fix unused scroll() amount parameter

TypeScript:
- Enable strictNullChecks in tsconfig
- Change CliCommand.func signature to IPage (non-null) for browser adapters
- Fix 93 compile errors across all adapters

Build:
- Remove || true from build-manifest (report failures instead of silencing)
- Replace Unix shell commands with Node.js scripts for cross-platform builds

Code quality:
- Remove error-object special detection from pipeline executor
- Unify error handling to throw pattern

Tests:
- New interceptor.test.ts (11 tests)
- New executor.test.ts (13 tests)
- Rewrite output.test.ts with comprehensive coverage (10 tests)
2026-03-16 18:14:27 +08:00
xuelin e781d40408 feat(boss): add security_id to search output
Expose securityId in search results so users can pipe it to
`boss detail` for full job information.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 18:12:46 +08:00
xuelin c230f3e5ad feat(boss): add job detail adapter
Add `boss detail` command to fetch full job posting details using
securityId from search results.

Fields returned: job description, skills, welfare, boss info (name,
title, active time), company info (industry, scale, stage), address.

Tested with real API calls against multiple job postings.

Usage:
  opencli boss detail --security_id <id_from_search>

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 18:09:49 +08:00
jackwener 3b2f88b2cf chore: sync package-lock.json version to 0.6.1 2026-03-16 17:38:13 +08:00
jackwener 7eec7ce89f fix: restore tests/ in vitest include for CI compatibility
vitest run tests/e2e/ intersects the CLI path with include patterns,
so tests/ must be in the include glob for CI to find test files.
2026-03-16 17:37:48 +08:00
AlexYue 788b069c02 feat: add E2E testing infrastructure with real Chrome in CI
## Changes

### E2E Test Suite (~52 test cases)
- public-commands.test.ts — Public API commands (hackernews, v2ex)
- browser-public.test.ts — Browser commands for public data across all sites
- browser-auth.test.ts — Graceful failure verification for login-required commands
- management.test.ts — Full coverage of management commands
- output-formats.test.ts — Output format validation (json/yaml/csv/md)
- smoke/api-health.test.ts — Scheduled API health checks

### Auto-detect Browser Mode
- buildMcpArgs uses CI env var to select mode:
  - Local (no CI) → --extension (connect to user's Chrome)
  - CI → standalone (launches its own browser)

### CI Pipeline
- e2e-headed.yml — Real Chrome via setup-chrome + xvfb in headed mode
- ci.yml — build + unit-test (2 shards) + smoke-test (scheduled/manual)
- Composite action for shared Chrome + xvfb setup

### Documentation
- New TESTING.md — Architecture, coverage, local setup, how to add tests

Co-authored-by: AlexYue <yj976240184@qq.com>
2026-03-16 17:35:16 +08:00
jackwener 433ad3a56a 0.6.1
Release / release (push) Has been cancelled
2026-03-16 14:20:22 +08:00
jackwener 50508b954e docs: expand bilibili commands, add setup hint after install, add doctor to troubleshooting 2026-03-16 14:16:54 +08:00
jackwener 35a843b8bd docs: use explicit PLAYWRIGHT_MCP_EXTENSION_TOKEN in auto-discover description 2026-03-16 14:16:12 +08:00
jackwener 486e513d07 fix(setup): only pre-select shell RC, let user choose other configs 2026-03-16 14:15:43 +08:00
jackwener 6c64f617c6 docs: add opencli setup to READMEs, remove hardcoded counts, update SKILL.md to v0.6.0 2026-03-16 14:13:38 +08:00
jackwener cd186bddd3 0.6.0
Release / release (push) Has been cancelled
2026-03-16 14:05:58 +08:00
jackwener 6486a42def fix(setup): clear screen before TUI to prevent page jumping 2026-03-16 14:04:38 +08:00
jackwener b308d5594a refactor(doctor/setup): polish UX and dedup code
- Doctor: chalk-colored output ([OK] green, [MISSING] red, etc.)
- Doctor: paths shortened with ~ and tool labels ([Codex], etc.)
- Doctor --fix: skip already-configured files
- TUI: hide cursor during interaction, proper Ctrl+C exit
- Setup: source hint after shell write, dedup shared helpers
- Tests: strip ANSI for assertions
2026-03-16 14:02:02 +08:00
jackwener 6f629260e7 feat: add interactive 'opencli setup' command with TUI checkbox
New zero-dependency TUI checkbox component (src/tui.ts) with:
  - ↑↓/jk navigation, Space toggle, Tab toggle+move
  - 'a' toggle all, Enter confirm, q/Esc cancel

New 'opencli setup' command (src/setup.ts) that:
  - Auto-discovers token from Chrome LevelDB extension
  - Shows interactive multi-select for config files
  - Displays tool names (Codex, Cursor, Claude Code, etc.)
  - Color-coded status (green=ok, yellow=mismatch, red=missing)
  - Applies changes only to selected files
2026-03-16 13:53:03 +08:00
jackwener 1e0b83bb84 feat(doctor): add Antigravity and Gemini CLI config paths
Add ~/.gemini/settings.json (Gemini CLI) and
~/.gemini/antigravity/mcp_config.json (Antigravity) to the
default MCP config scan list.
2026-03-16 13:45:02 +08:00
jackwener 1ff184e24d feat(doctor): add Claude Code and project .mcp.json config paths
Add ~/.claude.json (Claude Code user-scoped MCP config) and
.mcp.json (Claude Code project-scoped MCP config) to the
default config scan list.
2026-03-16 13:43:03 +08:00
jackwener 8e84145ccc feat(doctor): auto-discover extension token from Chrome LevelDB
Scan Chrome/Edge/Chromium localStorage LevelDB files to extract the
Playwright MCP Bridge auth-token directly from the extension's storage.
Uses a fast 'strings | grep' shell pipeline (~200ms) on macOS/Linux
with a pure-Node fallback for Windows.

The discovered token is now shown in 'opencli doctor' output and takes
priority as the recommended token when using '--fix'.
2026-03-16 13:38:48 +08:00
jackwener c77c8a8e3a feat: add Coupang search and add-to-cart adapters
Add browser-backed Coupang adapters for search and add-to-cart workflows.
- coupang search: multi-strategy data collection (API/JSON-LD/bootstrap/DOM), structured fields (price, rating, rocket, delivery), pagination and rocket filter support
- coupang add-to-cart: logged-in browser session reuse, stops before checkout
- coupang.ts: comprehensive data normalization layer with badge/rocket/delivery mapping
- browser-tab.ts: withTemporaryTab utility for isolated tab operations
- Unit tests for core normalization functions

Co-authored-by: CodeBBakGoSu <127713112+CodeBBakGoSu@users.noreply.github.com>
2026-03-16 13:30:42 +08:00
jackwener 9e024d4e46 0.5.2
Release / release (push) Has been cancelled
2026-03-16 13:22:18 +08:00
jackwener 34a9bff2b3 refactor: eliminate code duplication, improve type safety, add tests
- NEW: src/interceptor.ts — unified XHR/Fetch interceptor (was duplicated 3x)
- NEW: src/version.ts — centralized PKG_VERSION (was duplicated 2x)
- NEW: src/constants.ts — shared VOLATILE_PARAMS, FIELD_ROLES etc.
- NEW: src/engine.test.ts, src/registry.test.ts — 14 new unit tests

- browser.ts: use shared normalizeEval, interceptor, withTimeoutMs, PKG_VERSION
- intercept.ts, tap.ts: use shared interceptor generators
- cascade.ts: extract shared buildFetchProbeJs (90% dedup)
- engine.ts: use InternalCliCommand (no more 'as any' casts)
- executor.ts: remove all 15 'as StepHandler' type casts
- runtime.ts: add withTimeoutMs, IBrowserFactory interface
- registry.ts: add InternalCliCommand type for internal fields
- validate.ts: add pipeline step name validation
- output.ts: remove 'null as any' and '.filter(() => true)' hacks
- explore.ts, synthesize.ts: use shared constants
- docs: fix V2EX commands (3→6), SKILL.md version, verify example

Tests: 88 passed (was 74), tsc --noEmit: 0 errors
2026-03-16 13:22:12 +08:00
jackwener b0c51ddf19 fix: use Playwright MCP --executable-path flag (kebab-case)
Extract buildMcpArgs() helper and fix --executablePath → --executable-path
to match the Playwright MCP CLI's expected flag format.

Closes #16

Co-authored-by: KasumiChen <KasumiChen@users.noreply.github.com>
2026-03-16 12:58:18 +08:00
jackwener 141c2cf7d5 0.5.1
Release / release (push) Has been cancelled
2026-03-16 12:54:45 +08:00
jackwener 7ee0c9c96b fix: tab cleanup regex to match actual Playwright MCP tab format
The tab list from Playwright MCP uses '- N: (current) [title](url)' format,
but extractTabEntries only matched 'Tab N ...' format. This caused
_initialTabIdentities to always be empty, so tabs were never cleaned up.

Now supports both formats.
2026-03-16 12:54:44 +08:00
jackwener 76eefed83d docs: add opencli doctor hint after token setup 2026-03-16 12:47:59 +08:00
jackwener 08ae9c3fed chore: sync SKILL.md version to 0.5.0 2026-03-16 12:46:30 +08:00
jackwener 5a1581e67a 0.5.0
Release / release (push) Has been cancelled
2026-03-16 12:46:16 +08:00
jackwener 7a24e8d74b fix: add engines field for Node badge, sync SKILL.md version, fix zh-CN intro 2026-03-16 12:46:15 +08:00
jackwener 95fb841fc7 refactor: remove all CDP code, keep extension-only mode
- Remove CDP auto-discovery (discoverChromeEndpoint, isCdpApiAvailable, isPortReachable)
- Remove CDP readiness probe and autoAllowCdpDialog
- Remove forceExtension plumbing from registry, runtime, main, and adapters
- Remove CDP diagnostics from doctor (extractTokenViaCdp, remoteDebugging fields)
- Simplify connect() to always use --extension mode
- Remove CDP env vars (OPENCLI_USE_CDP, OPENCLI_CDP_ENDPOINT, OPENCLI_FORCE_EXTENSION)
- Update README.md, README.zh-CN.md, SKILL.md to remove CDP sections
- Update tests to remove CDP-related assertions

Current state preserved in extension-and-cdp branch.
2026-03-16 12:44:09 +08:00
jackwener 67d50191af fix: CDP mode hanging when using chrome://inspect remote debugging
Release / release (push) Has been cancelled
- Add isCdpApiAvailable() to verify CDP HTTP JSON API before using endpoint
- Chrome's chrome://inspect#remote-debugging writes DevToolsActivePort but
  its CDP endpoint is incompatible with Playwright connectOverCDP (init
  succeeds but all tool calls hang silently)
- Add CDP readiness probe in connect() to catch unresponsive endpoints
- Skip tab cleanup in close() for CDP mode (no bridge tabs to clean)
- Add PlaywrightMCPMode tracking for extension vs CDP lifecycle policy
2026-03-16 02:28:28 +08:00
jackwener 61a62f80c4 0.4.5
Release / release (push) Has been cancelled
2026-03-16 01:51:27 +08:00
jackwener f8491f01ae fix: add 5s timeout for initial tabs fetch during CDP connect
CDP mode on @playwright/mcp v0.0.68 hangs on browser_tabs calls.
This timeout prevents the entire connect() from blocking for 30s.
2026-03-16 01:51:22 +08:00
jackwener 4ec454530a 0.4.4
Release / release (push) Has been cancelled
2026-03-15 23:58:15 +08:00
jackwener e2192a2e8d docs: rename CLI-CREATOR → CLI-EXPLORER, add CLI-ONESHOT refs to READMEs
- Rename CLI-CREATOR.md → CLI-EXPLORER.md (explorer better reflects its purpose)
- Update all references across SKILL.md, README.md, README.zh-CN.md, CLI-ONESHOT.md
- Add quick-mode (CLI-ONESHOT) and full-mode (CLI-EXPLORER) entries in both READMEs
2026-03-15 23:58:10 +08:00
jackwener db8194337b Improve browser session lifecycle handling 2026-03-15 23:31:52 +08:00
jackwener 8e5a61458d docs: add CLI-ONESHOT.md — lightweight one-shot CLI generator guide
- CLI-ONESHOT.md: ~150 lines, 4-step flow for single-URL adapter generation
- Update SKILL.md: add quick-mode tip pointing to CLI-ONESHOT.md
- Update CLI-CREATOR.md: add tip pointing to lightweight alternative
2026-03-15 23:30:13 +08:00
jackwener dca908db90 docs: use bold AND to emphasize required config in zh-CN 2026-03-15 22:13:34 +08:00
jackwener 5a676b9f4b docs: clarify that both env var and MCP config are required for token 2026-03-15 22:12:59 +08:00
114 changed files with 10285 additions and 1843 deletions
@@ -0,0 +1,249 @@
---
name: cross-project-adapter-migration
description: "Cross-project CLI command migration workflow for opencli. Use when importing commands from external CLI projects (python/node) like rdt-cli, twitter-cli, etc. Covers: source analysis → gap matrix → batch migration → README/SKILL.md update."
---
# Cross-Project Adapter Migration
> 从外部 CLI 项目(Python/Node/Go 等)批量迁移命令到 opencli 的标准化流程。
## When to Use
- 用户说"把 xxx-cli 的命令迁移过来"
- 用户说"看看 xxx 项目有什么可以借鉴的"
- 用户说"对齐 xxx-cli 的功能"
- 在为新平台扩展 opencli 时,发现已有第三方 CLI 工具
## Prerequisites
- 熟悉 [CLI-EXPLORER.md](file:///Users/jakevin/code/opencli/CLI-EXPLORER.md)adapter 开发决策树)
- 熟悉 [SKILL.md](file:///Users/jakevin/code/opencli/SKILL.md)(命令参考 & 模板)
---
## Phase 1: 源项目分析
### 1.1 克隆 & 理解源项目
```bash
# 克隆源项目到 /tmp 做分析
git clone <source_repo_url> /tmp/<source-cli>
```
分析重点:
- **命令列表**:找到所有可用命令(查看 CLI 入口文件、help 输出或 README
- **认证方式**CookieAPI KeyOAuth?浏览器自动化?
- **数据源**:公开 APIGraphQL?页面抓取?
- **输出字段**:每个命令返回哪些数据字段
### 1.2 生成命令清单
列出源项目所有命令,包括:
| 命令 | 类型 | API/方法 | 输出字段 |
|------|------|---------|---------|
| `xxx feed` | Read | `GET /api/feed` | title, author, time |
| `xxx post` | Write | `POST /api/tweet` | status, id |
---
## Phase 2: 功能对比矩阵
### 2.1 查看 opencli 现有命令
```bash
ls src/clis/<site>/ # 查看已有适配器
opencli list | grep <site> # 确认已注册命令
```
### 2.2 生成对比矩阵
对每个源项目命令,标注三种状态:
| 功能 | 源项目 | opencli 现有 | 行动 |
|------|--------|-------------|------|
| feed | ✅ `xxx feed` | ❌ 无 | ✅ **新增** |
| search | ✅ `xxx search` | ✅ `search.ts` | ❌ 已有,跳过 |
| hot | ✅ `xxx hot` | ⚠️ `hot.yaml`(不完整) | ✅ **增强** |
| like | ✅ `xxx like` | ✅ `like.ts` | ❌ 已有,跳过 |
### 2.3 筛选迁移目标
去掉已有的、低价值的,保留高价值缺失命令,按 Read/Write 分类:
**筛选原则**
- ✅ 高使用频率的命令优先
- ✅ 已有但不完整的命令标记为"增强"
- ❌ 源项目特有但 opencli 架构不支持的功能(如需要持久化存储的)跳过
- ❌ 与现有功能完全重复的跳过
---
## Phase 3: 批量实现
> [!IMPORTANT]
> 实现前必须查阅 [CLI-EXPLORER.md](file:///Users/jakevin/code/opencli/CLI-EXPLORER.md) 确认策略选择。
### 3.1 选择实现方式
基于决策树分类:
| 类别 | 方式 | 适用条件 |
|------|------|---------|
| **Read + 简单 API** | YAML pipeline | 纯 fetch/select/map,无复杂 JS |
| **Read + GraphQL/分页/签名** | TypeScript adapter | 需要 JS 逻辑 |
| **Write 操作** | TypeScript + `Strategy.UI` | 点击/输入等 DOM 操作 |
| **Write + API** | TypeScript + `Strategy.COOKIE/HEADER` | 直接 POST API |
### 3.2 实现顺序
**先 Read 后 Write,先 YAML 后 TS**
1. **Phase A**: YAML Read 适配器(最快,通常每个 10-20 行)
2. **Phase B**: TS Read 适配器(需要 evaluate/intercept 的)
3. **Phase C**: TS Write 适配器(需 UI 自动化或 POST API
### 3.3 实现模板
#### YAML Read 适配器模板(Cookie 策略)
```yaml
site: <site>
name: <command>
description: <描述>
domain: www.<site>.com
strategy: cookie
browser: true
args:
limit:
type: int
default: 20
pipeline:
- navigate: https://www.<site>.com
- evaluate: |
(async () => {
const res = await fetch('<api_endpoint>', { credentials: 'include' });
const d = await res.json();
return (d.data?.items || []).map(item => ({
title: item.title,
// ... map source fields
}));
})()
- map:
rank: ${{ index + 1 }}
title: ${{ item.title }}
- limit: ${{ args.limit }}
columns: [rank, title]
```
#### TS Write 适配器模板(UI 策略)
```typescript
import { cli, Strategy } from '../../registry.js';
cli({
site: '<site>',
name: '<command>',
description: '<描述>',
strategy: Strategy.UI,
args: [{ name: 'target', required: true, help: '<参数说明>' }],
columns: ['status', 'message'],
func: async (page, kwargs) => {
await page.goto(`https://www.<site>.com/${kwargs.target}`);
await page.wait({ text: '<expected_text>', timeout: 10 });
// 获取 snapshot 找到目标按钮
const snapshot = await page.accessibility.snapshot();
// 点击按钮 ...
return [{ status: 'success', message: '<action> completed' }];
},
});
```
### 3.4 公共模式复用
迁移过程中如果发现多个适配器共享逻辑,考虑提取到 `src/<site>.ts` 工具文件:
```typescript
// src/<site>.ts
export async function fetchWithAuth(page, url) { ... }
export function parseItem(raw) { ... }
```
---
## Phase 4: 验证 & 发布
### 4.1 构建验证
```bash
npx tsc --noEmit # TypeScript 编译检查
opencli list | grep <site> # 确认所有命令已注册
```
### 4.2 运行验证(关键!)
每个新命令必须实际运行:
```bash
# Read 命令
opencli <site> <command> --limit 3 -f json
opencli <site> <command> --limit 3 -v # verbose 查看 pipeline
# Write 命令(谨慎!会实际操作)
opencli <site> <command> <test_target>
```
### 4.3 更新文档
迁移完成后必须更新以下文件:
1. **README.md** — 在对应平台区域添加新命令示例
2. **SKILL.md** — 在 Commands Reference 中添加新命令
### 4.4 提交 & 推送
```bash
git add -A
git commit -m "feat(<site>): migrate <N> commands from <source-cli>
- Phase A: <N> YAML adapters (read operations)
- Phase B: <N> TS adapters (write operations)
- Source: <source_repo_url>"
git push
```
---
## Checklist
- [ ] 源项目命令清单已生成
- [ ] 对比矩阵已确认,高价值缺失命令已筛选
- [ ] 用户确认迁移范围
- [ ] Phase A: YAML Read 适配器已完成
- [ ] Phase B: TS Read 适配器已完成
- [ ] Phase C: TS Write 适配器已完成
- [ ] `npx tsc --noEmit` 编译通过
- [ ] 所有新命令已实际运行验证
- [ ] README.md 已更新
- [ ] SKILL.md 已更新
- [ ] 已 commit + push
## 实战案例参考
### rdt-cli → opencli Reddit2026-03-16
- **源项目**: `rdt-cli`25 个 Python 命令)
- **筛选结果**: 13 个高价值命令
- **实现**: 7 个 YAMLread + 6 个 TSwrite
- **产出**: +11 文件,+767 行代码,Reddit 适配器从 4 → 15+275%
### twitter-cli → opencli Twitter2026-03-16
- **源项目**: `twitter-cli`20+ Python 命令)
- **筛选结果**: 11 个待实现
- **策略**: Read 用 `Strategy.COOKIE` + GraphQL fetchWrite 用 `Strategy.UI`
@@ -0,0 +1,54 @@
---
description: Migrate commands from an external CLI project into opencli adapters
---
// turbo-all
## Steps
1. Clone the source CLI project for analysis:
```bash
git clone <source_repo_url> /tmp/<source-cli>
```
2. Analyze source project: list all commands, auth method, API endpoints, and output fields.
3. Check existing opencli adapters for the target site:
```bash
ls src/clis/<site>/
opencli list | grep <site>
```
4. Generate a comparison matrix table (source commands vs opencli existing). Mark each as: ✅ **New** / ✅ **Enhance** / ❌ **Skip**. Ask user to confirm which commands to migrate.
5. Implement YAML Read adapters first (highest ROI, 10-20 lines each). Place files in `src/clis/<site>/<name>.yaml`.
6. Implement TS Read adapters for complex cases (GraphQL, pagination, signing). Place files in `src/clis/<site>/<name>.ts`.
7. Implement TS Write adapters using `Strategy.UI` or `Strategy.COOKIE`. Place files in `src/clis/<site>/<name>.ts`.
8. Verify build:
```bash
npx tsc --noEmit
```
9. Verify all commands are registered:
```bash
opencli list | grep <site>
```
10. Run each new command to verify it works:
```bash
opencli <site> <command> --limit 3 -f json
```
11. Update README.md with new command examples in the appropriate platform section.
12. Update SKILL.md Commands Reference with new commands.
13. Commit and push:
```bash
git add -A
git commit -m "feat(<site>): migrate <N> commands from <source-cli>"
git push
```
+26
View File
@@ -0,0 +1,26 @@
name: Setup Chrome + xvfb
description: Install real Chrome and xvfb virtual display for headed browser testing
outputs:
chrome-path:
description: Path to the installed Chrome binary
value: ${{ steps.setup-chrome.outputs.chrome-path }}
runs:
using: composite
steps:
- name: Install real Chrome (stable)
uses: browser-actions/setup-chrome@v1
id: setup-chrome
with:
chrome-version: stable
- name: Verify Chrome installation
shell: bash
run: |
echo "Chrome path: ${{ steps.setup-chrome.outputs.chrome-path }}"
${{ steps.setup-chrome.outputs.chrome-path }} --version
- name: Install xvfb for headed mode
shell: bash
run: sudo apt-get install -y xvfb
+59 -3
View File
@@ -2,12 +2,16 @@ name: CI
on:
push:
branches: [main]
branches: [main, dev]
pull_request:
branches: [main]
branches: [main, dev]
schedule:
- cron: '0 8 * * 1' # Weekly Monday 08:00 UTC — smoke tests
workflow_dispatch:
jobs:
check:
# ── Fast gate: typecheck + build ──
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -15,6 +19,7 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
@@ -24,3 +29,54 @@ jobs:
- name: Build
run: npm run build
# ── Unit tests (vitest shard) ──
unit-test:
runs-on: ubuntu-latest
strategy:
matrix:
shard: [1, 2]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run unit tests (shard ${{ matrix.shard }}/2)
run: npx vitest run src/ --reporter=verbose --shard=${{ matrix.shard }}/2
# ── Smoke tests (scheduled / manual only) ──
smoke-test:
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Setup Chrome + xvfb
uses: ./.github/actions/setup-chrome
id: setup-chrome
- name: Build
run: npm run build
- name: Run smoke tests
run: |
xvfb-run --auto-servernum --server-args="-screen 0 1280x720x24" \
npx vitest run tests/smoke/ --reporter=verbose
env:
OPENCLI_BROWSER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
timeout-minutes: 15
+37
View File
@@ -0,0 +1,37 @@
name: E2E Headed Chrome
on:
push:
branches: [main, dev]
pull_request:
branches: [main, dev]
workflow_dispatch:
jobs:
e2e-headed:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Setup Chrome + xvfb
uses: ./.github/actions/setup-chrome
id: setup-chrome
- name: Build
run: npm run build
- name: Run E2E tests (headed Chrome + xvfb)
run: |
xvfb-run --auto-servernum --server-args="-screen 0 1280x720x24" \
npx vitest run tests/e2e/ --reporter=verbose
env:
OPENCLI_BROWSER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
+2
View File
@@ -2,3 +2,5 @@ node_modules/
dist/
*.tsbuildinfo
.opencli/
.mcp.json
*.log
+5 -1
View File
@@ -1,8 +1,12 @@
# CLI-CREATOR — 适配器开发完全指南
# CLI-EXPLORER — 适配器探索式开发完全指南
> 本文档教你(或 AI Agent)如何为 OpenCLI 添加一个新网站的命令。
> 从零到发布,覆盖 API 发现、方案选择、适配器编写、测试验证全流程。
> [!TIP]
> **只想为一个具体页面快速生成一个命令?** 看 [CLI-ONESHOT.md](./CLI-ONESHOT.md)~150 行,4 步搞定)。
> 本文档适合从零探索一个新站点的完整流程。
---
## AI Agent 开发者必读:用 Playwright MCP Bridge 探索
+216
View File
@@ -0,0 +1,216 @@
# CLI-ONESHOT — 单点快速 CLI 生成
> 给一个 URL + 一句话描述,4 步生成一个 CLI 命令。
> 完整探索式开发请看 [CLI-EXPLORER.md](./CLI-EXPLORER.md)。
---
## 输入
| 项目 | 示例 |
|------|------|
| **URL** | `https://x.com/jakevin7/lists` |
| **Goal** | 获取我的 Twitter Lists |
---
## 流程
### Step 1: 打开页面 + 抓包
```
1. browser_navigate → 打开目标 URL
2. 等待 3-5 秒(让页面加载完、API 请求触发)
3. browser_network_requests → 筛选 JSON API
```
**关键**:只关注返回 `application/json` 的请求,忽略静态资源。
如果没有自动触发 API,手动点击目标按钮/标签再抓一次。
### Step 2: 锁定一个接口
从抓包结果中找到**那个**目标 API。看这几个字段:
| 字段 | 关注什么 |
|------|----------|
| URL | API 路径 pattern(如 `/i/api/graphql/xxx/ListsManagePinTimeline` |
| Method | GET / POST |
| Headers | 有 Cookie? Bearer? CSRF? 自定义签名? |
| Response | 数据在哪个路径(如 `data.list.lists` |
### Step 3: 验证接口能复现
`browser_evaluate` 中用 `fetch` 复现请求:
```javascript
// Tier 2 (Cookie): 大多数情况
fetch('/api/endpoint', { credentials: 'include' }).then(r => r.json())
// Tier 3 (Header): 如 Twitter 需要额外 header
const ct0 = document.cookie.match(/ct0=([^;]+)/)?.[1];
fetch('/api/endpoint', {
headers: { 'Authorization': 'Bearer ...', 'X-Csrf-Token': ct0 },
credentials: 'include'
}).then(r => r.json())
```
如果 fetch 能拿到数据 → 用 YAML 或简单 TS adapter。
如果 fetch 拿不到(签名/风控)→ 用 intercept 策略。
### Step 4: 套模板,生成 adapter
根据 Step 3 判定的策略,选一个模板生成文件。
---
## 认证速查
```
fetch(url) 直接能拿到? → Tier 1: public (YAML, browser: false)
fetch(url, {credentials:'include'}) → Tier 2: cookie (YAML)
加 Bearer/CSRF header 后拿到? → Tier 3: header (TS)
都不行,但页面自己能请求成功? → Tier 4: intercept (TS, installInterceptor)
```
---
## 模板
### YAML — Cookie/Public(最简)
```yaml
# src/clis/<site>/<name>.yaml
site: mysite
name: mycommand
description: "一句话描述"
domain: www.example.com
strategy: cookie # 或 public (加 browser: false)
args:
limit:
type: int
default: 20
pipeline:
- navigate: https://www.example.com/target-page
- evaluate: |
(async () => {
const res = await fetch('/api/target', { credentials: 'include' });
const d = await res.json();
return (d.data?.items || []).map(item => ({
title: item.title,
value: item.value,
}));
})()
- map:
rank: ${{ index + 1 }}
title: ${{ item.title }}
value: ${{ item.value }}
- limit: ${{ args.limit }}
columns: [rank, title, value]
```
### TS — Intercept(抓包模式)
```typescript
// src/clis/<site>/<name>.ts
import { cli, Strategy } from '../../registry.js';
cli({
site: 'mysite',
name: 'mycommand',
description: '一句话描述',
domain: 'www.example.com',
strategy: Strategy.INTERCEPT,
browser: true,
args: [
{ name: 'limit', type: 'int', default: 20 },
],
columns: ['rank', 'title', 'value'],
func: async (page, kwargs) => {
// 1. 导航
await page.goto('https://www.example.com/target-page');
await page.wait(3);
// 2. 注入拦截器(URL 子串匹配)
await page.installInterceptor('target-api-keyword');
// 3. 触发 API(滚动/点击)
await page.autoScroll({ times: 2, delayMs: 2000 });
// 4. 读取拦截的响应
const requests = await page.getInterceptedRequests();
if (!requests?.length) return [];
let results: any[] = [];
for (const req of requests) {
const items = req.data?.data?.items || [];
results.push(...items);
}
return results.slice(0, kwargs.limit).map((item, i) => ({
rank: i + 1,
title: item.title || '',
value: item.value || '',
}));
},
});
```
### TS — Header(如 Twitter GraphQL
```typescript
import { cli, Strategy } from '../../registry.js';
cli({
site: 'twitter',
name: 'mycommand',
description: '一句话描述',
domain: 'x.com',
strategy: Strategy.HEADER,
browser: true,
args: [
{ name: 'limit', type: 'int', default: 20 },
],
columns: ['rank', 'name', 'value'],
func: async (page, kwargs) => {
await page.goto('https://x.com');
const data = await page.evaluate(`(async () => {
const ct0 = document.cookie.match(/ct0=([^;]+)/)?.[1];
if (!ct0) return { error: 'Not logged in' };
const bearer = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D...';
const res = await fetch('/i/api/graphql/QUERY_ID/Endpoint', {
headers: {
'Authorization': 'Bearer ' + decodeURIComponent(bearer),
'X-Csrf-Token': ct0,
'X-Twitter-Auth-Type': 'OAuth2Session',
},
credentials: 'include',
});
return res.json();
})()`);
// 解析 data...
return [];
},
});
```
---
## 测试(必做)
```bash
npm run build # 语法检查
opencli list | grep mysite # 确认注册
opencli mysite mycommand --limit 3 -v # 实际运行
```
---
## 就这样,没了
写完文件 → build → run → 提交。有问题再看 [CLI-EXPLORER.md](./CLI-EXPLORER.md)。
+184 -22
View File
@@ -1,28 +1,190 @@
BSD 3-Clause License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) 2025, jackwener
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Definitions.
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2025 jackwener
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.
+79 -42
View File
@@ -1,7 +1,7 @@
# OpenCLI
> **Make any website your CLI.**
> Zero risk · Reuse Chrome login · AI-powered discovery
> Zero risk · Reuse Chrome login · AI-powered discovery · 80+ commands · 19 sites
[中文文档](./README.zh-CN.md)
@@ -9,7 +9,7 @@
[![Node.js Version](https://img.shields.io/node/v/@jackwener/opencli?style=flat-square)](https://nodejs.org)
[![License](https://img.shields.io/npm/l/@jackwener/opencli?style=flat-square)](./LICENSE)
A CLI tool that turns **any website** into a command-line interface. **57 commands** across **17 sites**bilibili, zhihu, xiaohongshu, twitter, reddit, xueqiu, github, v2ex, hackernews, bbc, weibo, boss, yahoo-finance, reuters, smzdm, ctrip, youtube — powered by browser session reuse and AI-native discovery.
A CLI tool that turns **any website** into a command-line interface — Bilibili, Zhihu, 小红书, Twitter/X, Reddit, YouTube, and [many more](#built-in-commands) — powered by browser session reuse and AI-native discovery.
---
@@ -21,6 +21,7 @@ A CLI tool that turns **any website** into a command-line interface. **57 comman
- [Built-in Commands](#built-in-commands)
- [Output Formats](#output-formats)
- [For AI Agents (Developer Guide)](#for-ai-agents-developer-guide)
- [Testing](#testing)
- [Troubleshooting](#troubleshooting)
- [Releasing New Versions](#releasing-new-versions)
- [License](#license)
@@ -31,8 +32,9 @@ A CLI tool that turns **any website** into a command-line interface. **57 comman
- **Account-safe** — Reuses Chrome's logged-in state; your credentials never leave the browser.
- **AI Agent ready** — `explore` discovers APIs, `synthesize` generates adapters, `cascade` finds auth strategies.
- **Self-healing setup** — `opencli setup` auto-discovers tokens; `opencli doctor` diagnoses config across 10+ tools; `--fix` repairs them all.
- **Dynamic Loader** — Simply drop `.ts` or `.yaml` adapters into the `clis/` folder for auto-registration.
- **Dual-Engine Architecture** — Supports both YAML declarative data pipelines and robust browser runtime typescript injections.
- **Dual-Engine Architecture** — Supports both YAML declarative data pipelines and robust browser runtime TypeScript injections.
## Prerequisites
@@ -41,16 +43,35 @@ A CLI tool that turns **any website** into a command-line interface. **57 comman
> **⚠️ Important**: Browser commands reuse your Chrome login session. You must be logged into the target website in Chrome before running commands. If you get empty data or errors, check your login status first.
OpenCLI needs a way to communicate with your browser. We highly recommend configuring **both** of the following methods for maximum reliability.
OpenCLI connects to your browser through the Playwright MCP Bridge extension.
### Connection Method A: Playwright MCP Bridge Extension (Primary)
### Playwright MCP Bridge Extension Setup
1. Install **[Playwright MCP Bridge](https://chromewebstore.google.com/detail/playwright-mcp-bridge/mmlmfjhmonkocbjadbfplnigmagldckm)** extension in Chrome.
2. Obtain your token by clicking the extension icon in the browser toolbar or from the extension settings page.
2. Run `opencli setup` — discovers the token, distributes it to your tools, and verifies connectivity:
**You must configure this token in BOTH your MCP configuration and system environment variables.**
```bash
opencli setup
```
First, add it to your MCP client config (e.g. Claude/Cursor):
The interactive TUI will:
- 🔍 Auto-discover `PLAYWRIGHT_MCP_EXTENSION_TOKEN` from Chrome (no manual copy needed)
- ☑️ Show all detected tools (Codex, Cursor, Claude Code, Gemini CLI, etc.)
- ✏️ Update only the files you select (Space to toggle, Enter to confirm)
- 🔌 Auto-verify browser connectivity after writing configs
> **Tip**: Use `opencli doctor` for ongoing diagnosis and maintenance:
> ```bash
> opencli doctor # Read-only token & config diagnosis
> opencli doctor --live # Also test live browser connectivity
> opencli doctor --fix # Fix mismatched configs (interactive)
> opencli doctor --fix -y # Fix all configs non-interactively
> ```
<details>
<summary>Manual setup (alternative)</summary>
Add token to your MCP client config (e.g. Claude/Cursor):
```json
{
@@ -66,21 +87,13 @@ First, add it to your MCP client config (e.g. Claude/Cursor):
}
```
And, so that `opencli` commands can use it directly in the terminal, export it in your shell environment (e.g. `~/.zshrc`):
Export in shell (e.g. `~/.zshrc`):
```bash
export PLAYWRIGHT_MCP_EXTENSION_TOKEN="<your-token-here>"
```
### Connection Method B: Chrome 144+ Auto-Discovery (Fallback)
No extensions needed. Just enable Chrome's built-in remote debugging:
1. Open `chrome://inspect#remote-debugging` in Chrome
2. Check **"Allow remote debugging for this browser instance"**
3. Set `OPENCLI_USE_CDP=1` before running opencli
*You can also manually specify an endpoint via `OPENCLI_CDP_ENDPOINT` env var.*
</details>
## Quick Start
@@ -88,6 +101,7 @@ No extensions needed. Just enable Chrome's built-in remote debugging:
```bash
npm install -g @jackwener/opencli
opencli setup # One-time: configure Playwright MCP token
```
Then use directly:
@@ -120,25 +134,29 @@ npm install -g @jackwener/opencli@latest
## Built-in Commands
| Site | Commands | Mode |
|------|----------|------|
| **bilibili** | `hot` `search` `me` `favorite` ... (11 commands) | 🔐 Browser |
| **zhihu** | `hot` `search` `question` | 🔐 Browser |
| **xiaohongshu** | `search` `notifications` `feed` `me` `user` | 🔐 Browser |
| **xueqiu** | `feed` `hot-stock` `hot` `search` `stock` `watchlist` | 🔐 Browser |
| **twitter** | `trending` `bookmarks` `profile` `search` `timeline` `following` `followers` `notifications` `post` `reply` `delete` `like` | 🔐 Browser |
| **reddit** | `hot` `frontpage` `search` `subreddit` | 🔐 Browser |
| **weibo** | `hot` | 🔐 Browser |
| **boss** | `search` | 🔐 Browser |
| **youtube** | `search` | 🔐 Browser |
| **yahoo-finance** | `quote` | 🔐 Browser |
| **reuters** | `search` | 🔐 Browser |
| **smzdm** | `search` | 🔐 Browser |
| **ctrip** | `search` | 🔐 Browser |
| **github** | `search` | 🌐 Public |
| **v2ex** | `hot` `latest` `topic` | 🌐 Public |
| **hackernews** | `top` | 🌐 Public |
| **bbc** | `news` | 🌐 Public |
**19 sites · 80+ commands** — run `opencli list` for the live registry.
| Site | Commands | Count | Mode |
|------|----------|:-----:|------|
| **twitter** | `trending` `bookmarks` `profile` `search` `timeline` `thread` `following` `followers` `notifications` `post` `reply` `delete` `like` `article` `follow` `unfollow` `bookmark` `unbookmark` | 18 | 🔐 Browser |
| **reddit** | `hot` `frontpage` `popular` `search` `subreddit` `read` `user` `user-posts` `user-comments` `upvote` `save` `comment` `subscribe` `saved` `upvoted` | 15 | 🔐 Browser |
| **bilibili** | `hot` `search` `me` `favorite` `history` `feed` `subtitle` `dynamic` `ranking` `following` `user-videos` | 11 | 🔐 Browser |
| **v2ex** | `hot` `latest` `topic` `daily` `me` `notifications` | 6 | 🌐 / 🔐 |
| **xueqiu** | `feed` `hot-stock` `hot` `search` `stock` `watchlist` | 6 | 🔐 Browser |
| **xiaohongshu** | `search` `notifications` `feed` `me` `user` | 5 | 🔐 Browser |
| **youtube** | `search` `video` `transcript` | 3 | 🔐 Browser |
| **zhihu** | `hot` `search` `question` | 3 | 🔐 Browser |
| **boss** | `search` `detail` | 2 | 🔐 Browser |
| **coupang** | `search` `add-to-cart` | 2 | 🔐 Browser |
| **bbc** | `news` | 1 | 🌐 Public |
| **ctrip** | `search` | 1 | 🔐 Browser |
| **github** | `search` | 1 | 🌐 Public |
| **hackernews** | `top` | 1 | 🌐 Public |
| **linkedin** | `search` | 1 | 🔐 Browser |
| **reuters** | `search` | 1 | 🔐 Browser |
| **smzdm** | `search` | 1 | 🔐 Browser |
| **weibo** | `hot` | 1 | 🔐 Browser |
| **yahoo-finance** | `quote` | 1 | 🔐 Browser |
## Output Formats
@@ -159,8 +177,9 @@ opencli bilibili hot -v # Verbose: show pipeline debug steps
If you are an AI assistant tasked with creating a new command adapter for `opencli`, please follow the AI Agent workflow below:
> **Information for AI:**
> Before writing any adapter code, you **must** read [CLI-CREATOR.md](./CLI-CREATOR.md). It contains the complete browser exploration workflow, the 5-tier authentication strategy decision tree, and debugging guide. Skipping this will lead to preventable errors.
> **Quick mode**: To generate a single command for a specific page URL, see [CLI-ONESHOT.md](./CLI-ONESHOT.md) — just a URL + one-line goal, 4 steps done.
> **Full mode**: Before writing any adapter code, read [CLI-EXPLORER.md](./CLI-EXPLORER.md). It contains the complete browser exploration workflow, the 5-tier authentication strategy decision tree, and debugging guide.
```bash
# 1. Deep Explore — discover APIs, infer capabilities, detect framework
@@ -178,17 +197,35 @@ opencli cascade https://api.example.com/data
Explore outputs to `.opencli/explore/<site>/` (manifest.json, endpoints.json, capabilities.json, auth.json).
## Testing
See **[TESTING.md](./TESTING.md)** for the full testing guide, including:
- Current test coverage (unit + E2E tests across 19 sites)
- How to run tests locally
- How to add tests when creating new adapters
- CI/CD pipeline with sharding
- Headless browser mode (`OPENCLI_HEADLESS=1`)
```bash
# Quick start
npm run build
npx vitest run # All tests
npx vitest run src/ # Unit tests only
npx vitest run tests/e2e/ # E2E tests
```
## Troubleshooting
- **"Failed to connect to Playwright MCP Bridge"**
- Ensure the Playwright MCP extension is installed and **enabled** in your running Chrome.
- Restart the Chrome browser if you just installed the extension.
- **"CDP command failed" or "boss search blocked"**
- Some sites (like BOSS Zhipin) actively block Chrome DevTools Protocol connections. OpenCLI falls back to cookie extraction, but ensure you didn't force `--chrome-mode` unnecessarily.
- **Empty data returns or 'Unauthorized' error**
- Your login session in Chrome might have expired. Open a normal Chrome tab, navigate to the target site, and log in or refresh the page to prove you are human.
- **Node API errors**
- Make sure you are using Node.js >= 18. Some dependencies require modern Node APIs.
- **Token issues**
- Run `opencli doctor` to diagnose token configuration across all tools.
## Releasing New Versions
@@ -202,4 +239,4 @@ The CI will automatically build, create a GitHub release, and publish to npm.
## License
[BSD-3-Clause](./LICENSE)
[Apache-2.0](./LICENSE)
+61 -42
View File
@@ -1,7 +1,7 @@
# OpenCLI
> **把任何网站变成你的命令行工具。**
> 零风控 · 复用 Chrome 登录 · AI 自动发现接口
> 零风控 · 复用 Chrome 登录 · AI 自动发现接口 · 80+ 命令 · 19 站点
[English](./README.md)
@@ -9,7 +9,7 @@
[![Node.js Version](https://img.shields.io/node/v/@jackwener/opencli?style=flat-square)](https://nodejs.org)
[![License](https://img.shields.io/npm/l/@jackwener/opencli?style=flat-square)](./LICENSE)
OpenCLI 通过 Chrome 浏览器 + [Playwright MCP Bridge](https://github.com/nichochar/playwright-mcp) 扩展,将任何网站变成命令行工具。57个内置命令。不存密码、不泄 token,直接复用浏览器登录态。
OpenCLI 将任何网站变成命令行工具 — B站、知乎、小红书、Twitter/X、Reddit、YouTube 等 [19 个站点](#内置命令) — 复用浏览器登录态AI 驱动探索
---
@@ -29,8 +29,9 @@ OpenCLI 通过 Chrome 浏览器 + [Playwright MCP Bridge](https://github.com/nic
## 亮点
- **57 个命令,17 个站点** — B站、知乎、小红书、Twitter、Reddit、雪球(xueqiu)、GitHub、V2EX、Hacker News、BBC、微博、BOSS直聘、Yahoo Finance、路透社、什么值得买、携程、YouTube
- **多站点覆盖** — B站、知乎、小红书、Twitter、Reddit 等 19 个站点,80+ 命令
- **零风控** — 复用 Chrome 登录态,无需存储任何凭证
- **自修复配置** — `opencli setup` 自动发现 Token`opencli doctor` 诊断 10+ 工具配置;`--fix` 一键修复
- **AI 原生** — `explore` 自动发现 API`synthesize` 生成适配器,`cascade` 探测认证策略
- **动态加载引擎** — 声明式的 `.yaml` 或者底层定制的 `.ts` 适配器,放入 `clis/` 文件夹即可自动注册生效
@@ -41,16 +42,35 @@ OpenCLI 通过 Chrome 浏览器 + [Playwright MCP Bridge](https://github.com/nic
> **⚠️ 重要**:大多数命令复用你的 Chrome 登录状态。运行命令前,你必须已在 Chrome 中打开目标网站并完成登录。如果获取到空数据或报错,请先检查你的浏览器登录状态。
为了让 OpenCLI 能够联通你的浏览器,你需要配置连接方式。**强烈建议以下两种方式都配置上**,互为后备:
OpenCLI 通过 Playwright MCP Bridge 扩展与你的浏览器通信。
### 连接方式 APlaywright MCP Bridge 扩展(首选)
### Playwright MCP Bridge 扩展配置
1. 安装 **[Playwright MCP Bridge](https://chromewebstore.google.com/detail/playwright-mcp-bridge/mmlmfjhmonkocbjadbfplnigmagldckm)** 扩展
2. 在浏览器插件栏点击该插件,或者在插件设置页获取你的 Extension Token。
2. 运行 `opencli setup` — 自动发现 Token、分发到各工具、验证连通性:
**你必须将这个 Token 同时配置到你的 MCP 配置文件以及环境变量中。**
```bash
opencli setup
```
首先,配置你的 MCP 客户端(如 Claude/Cursor 等)
交互式 TUI 会
- 🔍 从 Chrome 自动发现 `PLAYWRIGHT_MCP_EXTENSION_TOKEN`(无需手动复制)
- ☑️ 显示所有支持的工具(Codex、Cursor、Claude Code、Gemini CLI 等)
- ✏️ 只更新你选中的文件(空格切换,回车确认)
- 🔌 完成后自动验证浏览器连通性
> **Tip**:后续诊断和维护用 `opencli doctor`
> ```bash
> opencli doctor # 只读 Token 与配置诊断
> opencli doctor --live # 额外测试浏览器连通性
> opencli doctor --fix # 修复不一致的配置(交互确认)
> opencli doctor --fix -y # 无交互直接修复所有配置
> ```
<details>
<summary>手动配置(备选方案)</summary>
配置你的 MCP 客户端(如 Claude/Cursor 等):
```json
{
@@ -66,21 +86,13 @@ OpenCLI 通过 Chrome 浏览器 + [Playwright MCP Bridge](https://github.com/nic
}
```
并且,为了让 `opencli` 命令行也能直接使用它,你必须在你的终端系统环境变量中导出(建议写进 `~/.zshrc``~/.bashrc`):
在终端环境变量中导出(建议写进 `~/.zshrc`):
```bash
export PLAYWRIGHT_MCP_EXTENSION_TOKEN="<你的-token>"
```
### 连接方式 BChrome 144+ CDP 自动发现(备选)
无需安装任何扩展。只需开启 Chrome 内置的远程调试:
1. 在 Chrome 中打开 `chrome://inspect#remote-debugging`
2. 勾选 **"允许对此浏览器实例进行远程调试" (Allow remote debugging for this browser instance)**
3. 运行时设置环境变量 `OPENCLI_USE_CDP=1`
*也可通过 `OPENCLI_CDP_ENDPOINT` 环境变量手动指定 CDP endpoint 地址。*
</details>
## 快速开始
@@ -88,6 +100,7 @@ export PLAYWRIGHT_MCP_EXTENSION_TOKEN="<你的-token>"
```bash
npm install -g @jackwener/opencli
opencli setup # 首次使用:配置 Playwright MCP token
```
直接使用:
@@ -120,25 +133,29 @@ npm install -g @jackwener/opencli@latest
## 内置命令
| 站点 | 命令 | 模式 |
|------|------|------|
| **bilibili** | `hot` `search` `me` `favorite` ...(共11个) | 🔐 浏览器 |
| **zhihu** | `hot` `search` `question` | 🔐 浏览器 |
| **xiaohongshu** | `search` `notifications` `feed` `me` `user` | 🔐 浏览器 |
| **xueqiu** | `feed` `hot-stock` `hot` `search` `stock` `watchlist` | 🔐 浏览器 |
| **twitter** | `trending` `bookmarks` `profile` `search` `timeline` `following` `followers` `notifications` `post` `reply` `delete` `like` | 🔐 浏览器 |
| **reddit** | `hot` `frontpage` `search` `subreddit` | 🔐 浏览器 |
| **weibo** | `hot` | 🔐 浏览器 |
| **boss** | `search` | 🔐 浏览器 |
| **youtube** | `search` | 🔐 浏览器 |
| **yahoo-finance** | `quote` | 🔐 浏览器 |
| **reuters** | `search` | 🔐 浏览器 |
| **smzdm** | `search` | 🔐 浏览器 |
| **ctrip** | `search` | 🔐 浏览器 |
| **github** | `search` | 🌐 公共 API |
| **v2ex** | `hot` `latest` `topic` | 🌐 公共 API |
| **hackernews** | `top` | 🌐 公共 API |
| **bbc** | `news` | 🌐 公共 API |
**19 个站点 · 80+ 命令** — 运行 `opencli list` 查看完整注册表。
| 站点 | 命令 | 数量 | 模式 |
|------|------|:----:|------|
| **twitter** | `trending` `bookmarks` `profile` `search` `timeline` `thread` `following` `followers` `notifications` `post` `reply` `delete` `like` `article` `follow` `unfollow` `bookmark` `unbookmark` | 18 | 🔐 浏览器 |
| **reddit** | `hot` `frontpage` `popular` `search` `subreddit` `read` `user` `user-posts` `user-comments` `upvote` `save` `comment` `subscribe` `saved` `upvoted` | 15 | 🔐 浏览器 |
| **bilibili** | `hot` `search` `me` `favorite` `history` `feed` `subtitle` `dynamic` `ranking` `following` `user-videos` | 11 | 🔐 浏览器 |
| **v2ex** | `hot` `latest` `topic` `daily` `me` `notifications` | 6 | 🌐 / 🔐 |
| **xueqiu** | `feed` `hot-stock` `hot` `search` `stock` `watchlist` | 6 | 🔐 浏览器 |
| **xiaohongshu** | `search` `notifications` `feed` `me` `user` | 5 | 🔐 浏览器 |
| **youtube** | `search` `video` `transcript` | 3 | 🔐 浏览器 |
| **zhihu** | `hot` `search` `question` | 3 | 🔐 浏览器 |
| **boss** | `search` `detail` | 2 | 🔐 浏览器 |
| **coupang** | `search` `add-to-cart` | 2 | 🔐 浏览器 |
| **bbc** | `news` | 1 | 🌐 公共 API |
| **ctrip** | `search` | 1 | 🔐 浏览器 |
| **github** | `search` | 1 | 🌐 公共 API |
| **hackernews** | `top` | 1 | 🌐 公共 API |
| **linkedin** | `search` | 1 | 🔐 浏览器 |
| **reuters** | `search` | 1 | 🔐 浏览器 |
| **smzdm** | `search` | 1 | 🔐 浏览器 |
| **weibo** | `hot` | 1 | 🔐 浏览器 |
| **yahoo-finance** | `quote` | 1 | 🔐 浏览器 |
## 输出格式
@@ -159,8 +176,9 @@ opencli bilibili hot -v # 详细模式:展示管线执行步骤调试
如果你是一个被要求查阅代码并编写新 `opencli` 适配器的 AI,请遵守以下工作流。
> **给 AI 的提示:**
> 在编写任何新代码前,你**必须首先阅读 [CLI-CREATOR.md](./CLI-CREATOR.md)**。它包含了完整的适配器开发指南、API 探测流程、5级认证策略以及常见陷阱。如果你跳过这一步直接写代码,会导致很多不必要的错误。
> **快速模式**:只想为某个页面快速生成一个命令?看 [CLI-ONESHOT.md](./CLI-ONESHOT.md) — 给一个 URL + 一句话描述,4 步搞定。
> **完整模式**:在编写任何新代码前,先阅读 [CLI-EXPLORER.md](./CLI-EXPLORER.md)。它包含完整的适配器探索开发指南、API 探测流程、5级认证策略以及常见陷阱。
```bash
# 1. Deep Explore — 网络拦截 → 响应分析 → 能力推理 → 框架检测
@@ -183,12 +201,13 @@ opencli cascade https://api.example.com/data
- **"Failed to connect to Playwright MCP Bridge"** 报错
- 确保你当前的 Chrome 已安装且**开启了** Playwright MCP Bridge 浏览器插件。
- 如果是刚装完插件,需要重启 Chrome 浏览器。
- **"CDP command failed" / "被风控拦截"**
- 有些网站(例如 BOSS 直聘)会因为开了 DevTools 或者 CDP 端口拦截验证。OpenCLI 有 cookie 降级机制,通常不需要干预,不用去强行加上 CDP 标识参数即可。
- **返回空数据,或者报错 "Unauthorized"**
- Chrome 里的登录态可能已经过期(甚至被要求过滑动验证码)。请打开当前 Chrome 页面,在新标签页重新手工登录或刷新该页面。
- **Node API 错误 (如 parseArgs, fs 等)**
- 确保 Node.js 版本 `>= 18`。旧版不支持我们使用的现代核心库 API。
- **Token 问题**
- 运行 `opencli doctor` 诊断所有工具的 Token 配置状态。
- 使用 `opencli doctor --live` 测试浏览器连通性。
## 版本发布
@@ -202,4 +221,4 @@ git push --follow-tags
## License
[BSD-3-Clause](./LICENSE)
[Apache-2.0](./LICENSE)
+49 -21
View File
@@ -1,9 +1,9 @@
---
name: opencli
description: "OpenCLI — Make any website your CLI. Zero risk, AI-powered, reuse Chrome login."
version: 0.4.0
description: "OpenCLI — Make any website your CLI. Zero risk, AI-powered, reuse Chrome login. 80+ commands across 19 sites."
version: 0.7.3
author: jackwener
tags: [cli, browser, web, mcp, playwright, bilibili, zhihu, twitter, github, v2ex, hackernews, reddit, xiaohongshu, xueqiu, AI, agent]
tags: [cli, browser, web, mcp, playwright, bilibili, zhihu, twitter, github, v2ex, hackernews, reddit, xiaohongshu, xueqiu, youtube, boss, coupang, AI, agent]
---
# OpenCLI
@@ -11,7 +11,7 @@ tags: [cli, browser, web, mcp, playwright, bilibili, zhihu, twitter, github, v2e
> Make any website your CLI. Reuse Chrome login, zero risk, AI-powered discovery.
> [!CAUTION]
> **AI Agent 必读:创建或修改任何适配器之前,你必须先阅读 [CLI-CREATOR.md](./CLI-CREATOR.md)**
> **AI Agent 必读:创建或修改任何适配器之前,你必须先阅读 [CLI-EXPLORER.md](./CLI-EXPLORER.md)**
> 该文档包含完整的 API 发现工作流(必须使用 Playwright MCP Bridge 浏览器探索)、5 级认证策略决策树、平台 SDK 速查表、`tap` 步骤调试流程、分页 API 模板、级联请求模式、以及常见陷阱。
> **本文件(SKILL.md)仅提供命令参考和简化模板,不足以正确开发适配器。**
@@ -34,8 +34,8 @@ npm update -g @jackwener/opencli
Browser commands require:
1. Chrome browser running **(logged into target sites)**
2. [Playwright MCP Bridge](https://chromewebstore.google.com/detail/playwright-mcp-bridge/mmlmfjhmonkocbjadbfplnigmagldckm) extension (default connection mode)
3. **Alternative**: Chrome 144+ CDP auto-discovery — set `OPENCLI_USE_CDP=1` (no extension needed)
2. [Playwright MCP Bridge](https://chromewebstore.google.com/detail/playwright-mcp-bridge/mmlmfjhmonkocbjadbfplnigmagldckm) extension installed
3. Run `opencli setup` to auto-discover token and configure all tools
> **Note**: You must be logged into the target website in Chrome before running commands. Tabs opened during command execution are auto-closed afterwards.
@@ -68,7 +68,7 @@ opencli zhihu question --id 34816524 # 问题详情和回答
opencli xiaohongshu search --keyword "美食" # 搜索笔记
opencli xiaohongshu notifications # 通知(mentions/likes/connections
opencli xiaohongshu feed --limit 10 # 推荐 Feed
opencli xiaohongshu me # 我的信息
opencli xiaohongshu me # 我的信息
opencli xiaohongshu user --uid xxx # 用户主页
# 雪球 Xueqiu (browser)
@@ -86,20 +86,40 @@ opencli github search --keyword "cli" # 搜索仓库
opencli twitter trending --limit 10 # 热门话题
opencli twitter bookmarks --limit 20 # 获取收藏的书签推文
opencli twitter search --keyword "AI" # 搜索推文
opencli twitter profile --username elonmusk # 用户资料
opencli twitter profile elonmusk # 用户资料
opencli twitter timeline --limit 20 # 时间线
opencli twitter thread 1234567890 # 推文 thread(原文 + 回复)
opencli twitter article 1891511252174299446 # 推文长文内容
opencli twitter follow elonmusk # 关注用户
opencli twitter unfollow elonmusk # 取消关注
opencli twitter bookmark https://x.com/... # 收藏推文
opencli twitter unbookmark https://x.com/... # 取消收藏
# Reddit (browser)
opencli reddit hot --limit 10 # 热门帖子
opencli reddit hot --subreddit programming # 指定子版块
opencli reddit frontpage --limit 10 # 首页
opencli reddit search --keyword "AI" # 搜索
opencli reddit subreddit --name rust # 子版块浏览
opencli reddit frontpage --limit 10 # 首页 /r/all
opencli reddit popular --limit 10 # /r/popular 热门
opencli reddit search --query "AI" --sort top --time week # 搜索(支持排序+时间过滤)
opencli reddit subreddit --name rust --sort top --time month # 子版块浏览(支持时间过滤)
opencli reddit read --post_id 1abc123 # 阅读帖子 + 评论
opencli reddit user --username spez # 用户资料(karma、注册时间)
opencli reddit user-posts --username spez # 用户发帖历史
opencli reddit user-comments --username spez # 用户评论历史
opencli reddit upvote --post_id xxx --direction up # 投票(up/down/none
opencli reddit save --post_id xxx # 收藏帖子
opencli reddit comment --post_id xxx --text "Great!" # 发表评论
opencli reddit subscribe --subreddit python # 订阅子版块
opencli reddit saved --limit 10 # 我的收藏
opencli reddit upvoted --limit 10 # 我的赞
# V2EX (public)
# V2EX (public + browser)
opencli v2ex hot --limit 10 # 热门话题
opencli v2ex latest --limit 10 # 最新话题
opencli v2ex topic --id 1024 # 主题详情
opencli v2ex daily # 每日签到 (browser)
opencli v2ex me # 我的信息 (browser)
opencli v2ex notifications --limit 10 # 通知 (browser)
# Hacker News (public)
opencli hackernews top --limit 10 # Top stories
@@ -112,9 +132,13 @@ opencli weibo hot --limit 10 # 微博热搜
# BOSS直聘 (browser)
opencli boss search --query "AI agent" # 搜索职位
opencli boss detail --securityId xxx # 职位详情
# YouTube (browser)
opencli youtube search --query "rust" # 搜索视频
opencli youtube video --url "https://www.youtube.com/watch?v=xxx" # 视频元数据(标题、播放量、描述等)
opencli youtube transcript --url "https://www.youtube.com/watch?v=xxx" # 获取视频字幕/转录
opencli youtube transcript --url "xxx" --lang zh-Hans --mode raw # 指定语言 + 原始时间戳模式
# Yahoo Finance (browser)
opencli yahoo-finance quote --symbol AAPL # 股票行情
@@ -137,6 +161,11 @@ opencli list --json # JSON output
opencli list -f yaml # YAML output
opencli validate # Validate all CLI definitions
opencli validate bilibili # Validate specific site
opencli setup # Interactive token setup (auto-discover + TUI checkbox)
opencli doctor # Diagnose token & extension config across all tools
opencli doctor --live # Also test live browser connectivity
opencli doctor --fix # Fix mismatched configs (interactive confirmation)
opencli doctor --fix -y # Fix all configs non-interactively
```
### AI Agent Workflow
@@ -157,8 +186,8 @@ opencli cascade <api-url>
# Explore with interactive fuzzing (click buttons to trigger lazy APIs)
opencli explore <url> --auto --click "字幕,CC,评论"
# Verify: smoke-test a generated adapter
opencli verify <site/name> --smoke
# Verify: validate adapter definitions
opencli verify
```
## Output Formats
@@ -183,8 +212,12 @@ opencli bilibili hot -v # Show each pipeline step and data flow
## Creating Adapters
> [!TIP]
> **快速模式**:如果你只想为一个具体页面生成一个命令,直接看 [CLI-ONESHOT.md](./CLI-ONESHOT.md)。
> 只需要一个 URL + 一句话描述,4 步搞定。
> [!IMPORTANT]
> **STOP — 在写任何代码之前,先阅读 [CLI-CREATOR.md](./CLI-CREATOR.md)。**
> **完整模式 — 在写任何代码之前,先阅读 [CLI-EXPLORER.md](./CLI-EXPLORER.md)。**
> 它包含:① AI Agent 浏览器探索工作流(必须用 Playwright MCP 抓包验证 API)② 认证策略决策树 ③ 平台 SDK(如 Bilibili 的 `apiGet`/`fetchJson`)④ YAML vs TS 选择指南 ⑤ `tap` 步骤调试方法 ⑥ 级联请求模板 ⑦ 常见陷阱表。
> **下方仅为简化模板参考,直接使用极易踩坑。**
@@ -335,10 +368,6 @@ ${{ index + 1 }}
| `OPENCLI_BROWSER_CONNECT_TIMEOUT` | 30 | Browser connection timeout (sec) |
| `OPENCLI_BROWSER_COMMAND_TIMEOUT` | 45 | Command execution timeout (sec) |
| `OPENCLI_BROWSER_EXPLORE_TIMEOUT` | 120 | Explore timeout (sec) |
| `OPENCLI_EXTENSION_LOCK_TIMEOUT` | 120 | Extension lock timeout (sec) |
| `OPENCLI_CDP_ENDPOINT` | — | Manual CDP WebSocket endpoint (overrides auto-discovery) |
| `OPENCLI_USE_CDP` | — | Set to `1` to use Chrome 144+ CDP auto-discovery instead of extension |
| `OPENCLI_FORCE_EXTENSION` | — | Set to `1` to skip CDP and force extension mode |
| `PLAYWRIGHT_MCP_EXTENSION_TOKEN` | — | Auto-approve extension connection |
## Troubleshooting
@@ -346,7 +375,6 @@ ${{ index + 1 }}
| Issue | Solution |
|-------|----------|
| `npx not found` | Install Node.js: `brew install node` |
| `Timed out connecting to browser` | 1) Chrome must be open 2) Enable remote debugging at `chrome://inspect#remote-debugging` or install MCP Bridge extension |
| `Extension lock timed out` | Another opencli command is running; browser commands run serially |
| `Timed out connecting to browser` | 1) Chrome must be open 2) Install MCP Bridge extension and configure token |
| `Target page context` error | Add `navigate:` step before `evaluate:` in YAML |
| Empty table data | Check if evaluate returns JSON string (MCP parsing) or data path is wrong |
+233
View File
@@ -0,0 +1,233 @@
# Testing Guide
> 面向开发者和 AI Agent 的测试参考手册。
## 目录
- [测试架构](#测试架构)
- [当前覆盖范围](#当前覆盖范围)
- [本地运行测试](#本地运行测试)
- [如何添加新测试](#如何添加新测试)
- [CI/CD 流水线](#cicd-流水线)
- [浏览器模式](#浏览器模式)
- [站点兼容性](#站点兼容性)
---
## 测试架构
测试分为三层,全部使用 **vitest** 运行:
```
tests/
├── e2e/ # E2E 集成测试(子进程运行真实 CLI)
│ ├── helpers.ts # runCli() 共享工具
│ ├── public-commands.test.ts # 公开 API 命令(无需浏览器)
│ ├── browser-public.test.ts # 浏览器命令(公开数据)
│ ├── browser-auth.test.ts # 需登录命令(graceful failure 测试)
│ ├── management.test.ts # 管理命令(list, validate, verify, help
│ └── output-formats.test.ts # 输出格式(json/yaml/csv/md
├── smoke/ # 烟雾测试(仅定时 / 手动触发)
│ └── api-health.test.ts # 外部 API 可用性检测
src/
├── *.test.ts # 单元测试(已有 8 个)
```
| 层 | 位置 | 运行方式 | 用途 |
|---|---|---|---|
| 单元测试 | `src/**/*.test.ts` | `npx vitest run src/` | 内部模块逻辑 |
| E2E 测试 | `tests/e2e/*.test.ts` | `npx vitest run tests/e2e/` | 真实 CLI 命令执行 |
| 烟雾测试 | `tests/smoke/*.test.ts` | `npx vitest run tests/smoke/` | 外部 API 健康 |
---
## 当前覆盖范围
### 单元测试(8 个文件)
| 文件 | 覆盖内容 |
|---|---|
| `browser.test.ts` | JSON-RPC、tab 管理、extension/standalone 模式切换 |
| `engine.test.ts` | 命令发现与执行 |
| `registry.test.ts` | 命令注册与策略分配 |
| `output.test.ts` | 输出格式渲染 |
| `doctor.test.ts` | Token 诊断 |
| `coupang.test.ts` | 数据归一化 |
| `pipeline/template.test.ts` | 模板表达式求值 |
| `pipeline/transform.test.ts` | 数据变换步骤 |
### E2E 测试(~52 个用例)
| 文件 | 覆盖站点/功能 | 测试数 |
|---|---|---|
| `public-commands.test.ts` | hackernews/top, v2ex/hot, v2ex/latest, v2ex/topic | 5 |
| `browser-public.test.ts` | bbc, bilibili×3, weibo, zhihu×2, reddit×2, twitter, xueqiu×2, reuters, youtube, smzdm, boss, ctrip, coupang, xiaohongshu, yahoo-finance, v2ex/daily | 21 |
| `browser-auth.test.ts` | bilibili/me,dynamic,favorite,history,following + twitter/bookmarks,timeline,notifications + v2ex/me,notifications + xueqiu/feed,watchlist + xiaohongshu/feed,notifications | 14 |
| `management.test.ts` | list×5 格式, validate×3 级别, verify, --version, --help, unknown cmd | 12 |
| `output-formats.test.ts` | json, yaml, csv, md 格式验证 | 5 |
### 烟雾测试
公开 API 可用性(hackernews, v2ex×2, v2ex/topic+ 全站点注册完整性检查。
---
## 本地运行测试
### 前置条件
```bash
npm ci # 安装依赖
npm run build # 编译(E2E 测试需要 dist/main.js
```
### 运行命令
```bash
# 全部单元测试
npx vitest run src/
# 全部 E2E 测试(会真实调用外部 API)
npx vitest run tests/e2e/
# 单个测试文件
npx vitest run tests/e2e/management.test.ts
# 全部测试(单元 + E2E
npx vitest run
# 烟雾测试
npx vitest run tests/smoke/
# watch 模式(开发时推荐)
npx vitest src/
```
### 浏览器命令本地测试须知
-`PLAYWRIGHT_MCP_EXTENSION_TOKEN` 时,opencli 自动启动一个独立浏览器实例
- `browser-public.test.ts` 使用 `tryBrowserCommand()`,站点反爬导致空数据时 warn + pass
- `browser-auth.test.ts` 验证 **graceful failure**(不 crash 不 hang 即通过)
- 如需测试完整登录态,保持 Chrome 登录态 + 设置 `PLAYWRIGHT_MCP_EXTENSION_TOKEN`,手动跑对应测试
---
## 如何添加新测试
### 新增 YAML Adapter(如 `src/clis/producthunt/trending.yaml`
1. **无需额外操作**`validate` 测试会自动覆盖 YAML 结构验证
2. 根据 adapter 类型,在对应文件加一个 `it()` block
```typescript
// 如果 browser: false(公开 API)→ tests/e2e/public-commands.test.ts
it('producthunt trending returns data', async () => {
const { stdout, code } = await runCli(['producthunt', 'trending', '--limit', '3', '-f', 'json']);
expect(code).toBe(0);
const data = parseJsonOutput(stdout);
expect(Array.isArray(data)).toBe(true);
expect(data.length).toBeGreaterThanOrEqual(1);
expect(data[0]).toHaveProperty('title');
}, 30_000);
```
```typescript
// 如果 browser: true 但可公开访问 → tests/e2e/browser-public.test.ts
it('producthunt trending returns data', async () => {
const data = await tryBrowserCommand(['producthunt', 'trending', '--limit', '3', '-f', 'json']);
expectDataOrSkip(data, 'producthunt trending');
}, 60_000);
```
```typescript
// 如果 browser: true 且需登录 → tests/e2e/browser-auth.test.ts
it('producthunt me fails gracefully without login', async () => {
await expectGracefulAuthFailure(['producthunt', 'me', '-f', 'json'], 'producthunt me');
}, 60_000);
```
### 新增管理命令(如 `opencli export`
`tests/e2e/management.test.ts` 添加测试。
### 新增内部模块
`src/` 下对应位置创建 `*.test.ts`
### 决策流程图
```
新增功能 → 是内部模块? → 是 → src/ 下加 *.test.ts
↓ 否
是 CLI 命令? → browser: false? → tests/e2e/public-commands.test.ts
↓ true
公开数据? → tests/e2e/browser-public.test.ts
↓ 需登录
tests/e2e/browser-auth.test.ts
```
---
## CI/CD 流水线
### ci.yml(主流水线)
| Job | 触发条件 | 内容 |
|---|---|---|
| **build** | push/PR to main,dev | typecheck + build |
| **unit-test** | push/PR to main,dev | 单元测试,2 shard 并行 |
| **smoke-test** | 每周一 08:00 UTC / 手动 | xvfb + real Chrome,外部 API 健康检查 |
### e2e-headed.ymlE2E 测试)
| Job | 触发条件 | 内容 |
|---|---|---|
| **e2e-headed** | push/PR to main,dev | xvfb + real Chrome,全部 E2E 测试 |
E2E 使用 `browser-actions/setup-chrome` 安装真实 Chrome,配合 `xvfb-run` 提供虚拟显示器,以 headed 模式运行浏览器。
### Sharding
单元测试使用 vitest 内置 shard
```yaml
strategy:
matrix:
shard: [1, 2]
steps:
- run: npx vitest run src/ --shard=${{ matrix.shard }}/2
```
---
## 浏览器模式
opencli 根据 `PLAYWRIGHT_MCP_EXTENSION_TOKEN` 环境变量自动选择模式:
| 条件 | 模式 | MCP 参数 | 使用场景 |
|---|---|---|---|
| Token 已设置 | Extension 模式 | `--extension` | 本地用户,连接已登录的 Chrome |
| Token 未设置 | Standalone 模式 | (无特殊 flag) | CI 或无扩展环境,自启浏览器 |
CI 中使用 `OPENCLI_BROWSER_EXECUTABLE_PATH` 指定真实 Chrome 路径:
```yaml
env:
OPENCLI_BROWSER_EXECUTABLE_PATH: ${{ steps.setup-chrome.outputs.chrome-path }}
```
---
## 站点兼容性
在 GitHub Actions 美国 runner 上,部分站点因地域限制或登录要求返回空数据。E2E 测试对这些站点使用 warn + pass 策略,不影响 CI 绿灯。
| 站点 | CI 状态 | 限制原因 |
|---|---|---|
| hackernews, bbc, v2ex | ✅ 返回数据 | 无限制 |
| yahoo-finance | ✅ 返回数据 | 无限制 |
| bilibili, zhihu, weibo, xiaohongshu | ⚠️ 空数据 | 地域限制(中国站点) |
| reddit, twitter, youtube | ⚠️ 空数据 | 需登录或 cookie |
| smzdm, boss, ctrip, coupang, xueqiu | ⚠️ 空数据 | 地域限制 / 需登录 |
> 使用 self-hosted runner(国内服务器)可解决地域限制问题。
+28 -68
View File
@@ -1,13 +1,14 @@
{
"name": "@jackwener/opencli",
"version": "0.4.3",
"version": "0.7.10",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@jackwener/opencli",
"version": "0.4.3",
"license": "BSD-3-Clause",
"version": "0.7.10",
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
"chalk": "^5.3.0",
"cli-table3": "^0.6.5",
@@ -18,12 +19,31 @@
"opencli": "dist/main.js"
},
"devDependencies": {
"@playwright/mcp": "^0.0.68",
"@types/js-yaml": "^4.0.9",
"@types/node": "^22.13.10",
"opencli-mcp": "file:../opencli-mcp/packages/playwright-mcp",
"tsx": "^4.19.3",
"typescript": "^5.8.2",
"vitest": "^4.1.0"
},
"engines": {
"node": ">=18.0.0"
}
},
"../opencli-mcp/packages/playwright-mcp": {
"name": "opencli-mcp",
"version": "0.0.68",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.59.0-alpha-1771104257000",
"playwright-core": "1.59.0-alpha-1771104257000"
},
"bin": {
"playwright-mcp": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@colors/colors": {
@@ -556,23 +576,6 @@
"url": "https://github.com/sponsors/Boshen"
}
},
"node_modules/@playwright/mcp": {
"version": "0.0.68",
"resolved": "https://registry.npmjs.org/@playwright/mcp/-/mcp-0.0.68.tgz",
"integrity": "sha512-oP9I9ghXKuQEBo4xaC7HgsS2gRTxyMzlBm3UEhYj4VqqrqbPQUX2shATPaNA/am9joBzq9v0OXISzeIgP+zmHA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.59.0-alpha-1771104257000",
"playwright-core": "1.59.0-alpha-1771104257000"
},
"bin": {
"playwright-mcp": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.0.0-rc.9",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-rc.9.tgz",
@@ -1540,6 +1543,10 @@
],
"license": "MIT"
},
"node_modules/opencli-mcp": {
"resolved": "../opencli-mcp/packages/playwright-mcp",
"link": true
},
"node_modules/pathe": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
@@ -1568,53 +1575,6 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/playwright": {
"version": "1.59.0-alpha-1771104257000",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.0-alpha-1771104257000.tgz",
"integrity": "sha512-6SCMMMJaDRsSqiKVLmb2nhtLES7iTYawTWWrQK6UdIGNzXi8lka4sLKRec3L4DnTWwddAvCuRn8035dhNiHzbg==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.59.0-alpha-1771104257000"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.59.0-alpha-1771104257000",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.0-alpha-1771104257000.tgz",
"integrity": "sha512-YiXup3pnpQUCBMSIW5zx8CErwRx4K6O5Kojkw2BzJui8MazoMUDU6E3xGsb1kzFviEAE09LFQ+y1a0RhIJQ5SA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/playwright/node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/postcss": {
"version": "8.5.8",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz",
+10 -6
View File
@@ -1,10 +1,13 @@
{
"name": "@jackwener/opencli",
"version": "0.4.3",
"version": "0.7.10",
"publishConfig": {
"access": "public"
},
"description": "Make any website your CLI. AI-powered.",
"engines": {
"node": ">=18.0.0"
},
"type": "module",
"main": "dist/main.js",
"bin": {
@@ -13,10 +16,11 @@
"scripts": {
"dev": "tsx src/main.ts",
"build": "tsc && npm run clean-yaml && npm run copy-yaml && npm run build-manifest",
"build-manifest": "node dist/build-manifest.js || true",
"clean-yaml": "find dist/clis -name '*.yaml' -o -name '*.yml' 2>/dev/null | xargs rm -f",
"copy-yaml": "find src/clis -name '*.yaml' -o -name '*.yml' | while read f; do d=\"dist/${f#src/}\"; mkdir -p \"$(dirname \"$d\")\"; cp \"$f\" \"$d\"; done",
"build-manifest": "node dist/build-manifest.js",
"clean-yaml": "node scripts/clean-yaml.cjs",
"copy-yaml": "node scripts/copy-yaml.cjs",
"start": "node dist/main.js",
"postinstall": "node scripts/postinstall.js || true",
"typecheck": "tsc --noEmit",
"lint": "tsc --noEmit",
"prepublishOnly": "npm run build",
@@ -31,7 +35,7 @@
"playwright"
],
"author": "jackwener",
"license": "BSD-3-Clause",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "git+https://github.com/jackwener/opencli.git"
@@ -43,9 +47,9 @@
"js-yaml": "^4.1.0"
},
"devDependencies": {
"@playwright/mcp": "^0.0.68",
"@types/js-yaml": "^4.0.9",
"@types/node": "^22.13.10",
"opencli-mcp": "file:../opencli-mcp/packages/playwright-mcp",
"tsx": "^4.19.3",
"typescript": "^5.8.2",
"vitest": "^4.1.0"
+19
View File
@@ -0,0 +1,19 @@
/**
* Clean YAML files from dist/clis/ before copying fresh ones.
*/
const { readdirSync, rmSync, existsSync, statSync } = require('fs');
const path = require('path');
function walk(dir) {
if (!existsSync(dir)) return;
for (const f of readdirSync(dir)) {
const fp = path.join(dir, f);
if (statSync(fp).isDirectory()) {
walk(fp);
} else if (/\.ya?ml$/.test(f)) {
rmSync(fp);
}
}
}
walk('dist/clis');
+21
View File
@@ -0,0 +1,21 @@
/**
* Copy YAML files from src/clis/ to dist/clis/.
*/
const { readdirSync, copyFileSync, mkdirSync, existsSync, statSync } = require('fs');
const path = require('path');
function walk(src, dst) {
if (!existsSync(src)) return;
for (const f of readdirSync(src)) {
const sp = path.join(src, f);
const dp = path.join(dst, f);
if (statSync(sp).isDirectory()) {
walk(sp, dp);
} else if (/\.ya?ml$/.test(f)) {
mkdirSync(path.dirname(dp), { recursive: true });
copyFileSync(sp, dp);
}
}
}
walk('src/clis', 'dist/clis');
+200
View File
@@ -0,0 +1,200 @@
#!/usr/bin/env node
/**
* postinstall script — automatically install shell completion files.
*
* Detects the user's default shell and writes the completion script to the
* standard system completion directory so that tab-completion works immediately
* after `npm install -g`.
*
* Supported shells: bash, zsh, fish.
*
* This script is intentionally plain Node.js (no TypeScript, no imports from
* the main source tree) so that it can run without a build step.
*/
import { mkdirSync, writeFileSync, existsSync, readFileSync, appendFileSync } from 'node:fs';
import { join } from 'node:path';
import { homedir } from 'node:os';
// ── Completion script content ──────────────────────────────────────────────
const BASH_COMPLETION = `# Bash completion for opencli (auto-installed)
_opencli_completions() {
local cur words cword
_get_comp_words_by_ref -n : cur words cword
local completions
completions=$(opencli --get-completions --cursor "$cword" "\${words[@]:1}" 2>/dev/null)
COMPREPLY=( $(compgen -W "$completions" -- "$cur") )
__ltrim_colon_completions "$cur"
}
complete -F _opencli_completions opencli
`;
const ZSH_COMPLETION = `#compdef opencli
# Zsh completion for opencli (auto-installed)
_opencli() {
local -a completions
local cword=$((CURRENT - 1))
completions=(\${(f)"$(opencli --get-completions --cursor "$cword" "\${words[@]:1}" 2>/dev/null)"})
compadd -a completions
}
_opencli
`;
const FISH_COMPLETION = `# Fish completion for opencli (auto-installed)
complete -c opencli -f -a '(
set -l tokens (commandline -cop)
set -l cursor (count (commandline -cop))
opencli --get-completions --cursor $cursor $tokens[2..] 2>/dev/null
)'
`;
// ── Helpers ────────────────────────────────────────────────────────────────
function detectShell() {
const shell = process.env.SHELL || '';
if (shell.includes('zsh')) return 'zsh';
if (shell.includes('bash')) return 'bash';
if (shell.includes('fish')) return 'fish';
return null;
}
function ensureDir(dir) {
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
}
/**
* Ensure fpath contains the custom completions directory in .zshrc.
*
* Key detail: the fpath line MUST appear BEFORE the first `compinit` call,
* otherwise compinit won't scan our completions directory. This is critical
* for oh-my-zsh users (source $ZSH/oh-my-zsh.sh calls compinit internally).
*/
function ensureZshFpath(completionsDir, zshrcPath) {
const fpathLine = `fpath=(${completionsDir} $fpath)`;
const autoloadLine = `autoload -Uz compinit && compinit`;
const marker = '# opencli completion';
if (!existsSync(zshrcPath)) {
writeFileSync(zshrcPath, `${marker}\n${fpathLine}\n${autoloadLine}\n`, 'utf8');
return;
}
const content = readFileSync(zshrcPath, 'utf8');
// Already configured — nothing to do
if (content.includes(completionsDir)) {
return;
}
// Find the first line that triggers compinit (direct call or oh-my-zsh source)
const lines = content.split('\n');
let insertIdx = -1;
for (let i = 0; i < lines.length; i++) {
const trimmed = lines[i].trim();
// Skip comment-only lines
if (trimmed.startsWith('#')) continue;
if (/compinit/.test(trimmed) || /source\s+.*oh-my-zsh\.sh/.test(trimmed)) {
insertIdx = i;
break;
}
}
if (insertIdx !== -1) {
// Insert fpath BEFORE the compinit / oh-my-zsh source line
lines.splice(insertIdx, 0, marker, fpathLine);
writeFileSync(zshrcPath, lines.join('\n'), 'utf8');
} else {
// No compinit found — append fpath + compinit at the end
let addition = `\n${marker}\n${fpathLine}\n${autoloadLine}\n`;
appendFileSync(zshrcPath, addition, 'utf8');
}
}
// ── Main ───────────────────────────────────────────────────────────────────
function main() {
// Skip in CI environments
if (process.env.CI || process.env.CONTINUOUS_INTEGRATION) {
return;
}
// Only install completion for global installs and npm link
const isGlobal = process.env.npm_config_global === 'true';
if (!isGlobal) {
return;
}
const shell = detectShell();
if (!shell) {
// Cannot determine shell; silently skip
return;
}
const home = homedir();
try {
switch (shell) {
case 'zsh': {
const completionsDir = join(home, '.zsh', 'completions');
const completionFile = join(completionsDir, '_opencli');
ensureDir(completionsDir);
writeFileSync(completionFile, ZSH_COMPLETION, 'utf8');
// Ensure fpath is set up in .zshrc
const zshrcPath = join(home, '.zshrc');
ensureZshFpath(completionsDir, zshrcPath);
console.log(`✓ Zsh completion installed to ${completionFile}`);
console.log(` Restart your shell or run: source ~/.zshrc`);
break;
}
case 'bash': {
// Try system-level first, fall back to user-level
const userCompDir = join(home, '.bash_completion.d');
const completionFile = join(userCompDir, 'opencli');
ensureDir(userCompDir);
writeFileSync(completionFile, BASH_COMPLETION, 'utf8');
// Ensure .bashrc sources the completion directory
const bashrcPath = join(home, '.bashrc');
if (existsSync(bashrcPath)) {
const content = readFileSync(bashrcPath, 'utf8');
if (!content.includes('.bash_completion.d/opencli')) {
appendFileSync(bashrcPath,
`\n# opencli completion\n[ -f "${completionFile}" ] && source "${completionFile}"\n`,
'utf8'
);
}
}
console.log(`✓ Bash completion installed to ${completionFile}`);
console.log(` Restart your shell or run: source ~/.bashrc`);
break;
}
case 'fish': {
const completionsDir = join(home, '.config', 'fish', 'completions');
const completionFile = join(completionsDir, 'opencli.fish');
ensureDir(completionsDir);
writeFileSync(completionFile, FISH_COMPLETION, 'utf8');
console.log(`✓ Fish completion installed to ${completionFile}`);
console.log(` Restart your shell to activate.`);
break;
}
}
} catch (err) {
// Completion install is best-effort; never fail the package install
if (process.env.OPENCLI_VERBOSE) {
console.error(`Warning: Could not install shell completion: ${err.message}`);
}
}
}
main();
+3 -3
View File
@@ -56,7 +56,7 @@ export async function wbiSign(
const mixinKey = getMixinKey(imgKey, subKey);
const wts = Math.floor(Date.now() / 1000);
const sorted: Record<string, string> = {};
const allParams = { ...params, wts: String(wts) };
const allParams: Record<string, any> = { ...params, wts: String(wts) };
for (const key of Object.keys(allParams).sort()) {
sorted[key] = String(allParams[key]).replace(/[!'()*]/g, '');
}
@@ -84,10 +84,10 @@ export async function apiGet(
}
export async function fetchJson(page: IPage, url: string): Promise<any> {
const escapedUrl = url.replace(/"/g, '\\"');
const urlJs = JSON.stringify(url);
return page.evaluate(`
async () => {
const res = await fetch("${escapedUrl}", { credentials: "include" });
const res = await fetch(${urlJs}, { credentials: "include" });
return await res.json();
}
`);
+230 -36
View File
@@ -1,51 +1,245 @@
import { describe, expect, it } from 'vitest';
import { formatBrowserConnectError, getTokenFingerprint } from './browser.js';
import { afterEach, describe, it, expect, vi } from 'vitest';
import { PlaywrightMCP, __test__ } from './browser/index.js';
describe('getTokenFingerprint', () => {
it('returns null for empty token', () => {
expect(getTokenFingerprint(undefined)).toBeNull();
afterEach(() => {
__test__.resetMcpServerPathCache();
__test__.setMcpDiscoveryTestHooks();
delete process.env.OPENCLI_MCP_SERVER_PATH;
});
describe('browser helpers', () => {
it('creates JSON-RPC requests with unique ids', () => {
const first = __test__.createJsonRpcRequest('tools/call', { name: 'browser_tabs' });
const second = __test__.createJsonRpcRequest('tools/call', { name: 'browser_snapshot' });
expect(second.id).toBe(first.id + 1);
expect(first.message).toContain(`"id":${first.id}`);
expect(second.message).toContain(`"id":${second.id}`);
});
it('returns stable short fingerprint for token', () => {
expect(getTokenFingerprint('abc123')).toBe('6ca13d52');
it('extracts tab entries from string snapshots', () => {
const entries = __test__.extractTabEntries('Tab 0 https://example.com\nTab 1 Chrome Extension');
expect(entries).toEqual([
{ index: 0, identity: 'https://example.com' },
{ index: 1, identity: 'Chrome Extension' },
]);
});
it('extracts tab entries from MCP markdown format', () => {
const entries = __test__.extractTabEntries(
'- 0: (current) [Playwright MCP extension](chrome-extension://abc/connect.html)\n- 1: [知乎 - 首页](https://www.zhihu.com/)'
);
expect(entries).toEqual([
{ index: 0, identity: '(current) [Playwright MCP extension](chrome-extension://abc/connect.html)' },
{ index: 1, identity: '[知乎 - 首页](https://www.zhihu.com/)' },
]);
});
it('closes only tabs that were opened during the session', () => {
const tabsToClose = __test__.diffTabIndexes(
['https://example.com', 'Chrome Extension'],
[
{ index: 0, identity: 'https://example.com' },
{ index: 1, identity: 'Chrome Extension' },
{ index: 2, identity: 'https://target.example/page' },
{ index: 3, identity: 'chrome-extension://bridge' },
],
);
expect(tabsToClose).toEqual([3, 2]);
});
it('keeps only the tail of stderr buffers', () => {
expect(__test__.appendLimited('12345', '67890', 8)).toBe('34567890');
});
it('builds extension MCP args in local mode (no CI)', () => {
const savedCI = process.env.CI;
delete process.env.CI;
try {
expect(__test__.buildMcpArgs({
mcpPath: '/tmp/cli.js',
executablePath: '/mnt/c/Program Files/Google/Chrome/Application/chrome.exe',
})).toEqual([
'/tmp/cli.js',
'--extension',
'--executable-path',
'/mnt/c/Program Files/Google/Chrome/Application/chrome.exe',
]);
expect(__test__.buildMcpArgs({
mcpPath: '/tmp/cli.js',
})).toEqual([
'/tmp/cli.js',
'--extension',
]);
} finally {
if (savedCI !== undefined) {
process.env.CI = savedCI;
} else {
delete process.env.CI;
}
}
});
it('builds standalone MCP args in CI mode', () => {
const savedCI = process.env.CI;
process.env.CI = 'true';
try {
// CI mode: no --extension — browser launches in standalone headed mode
expect(__test__.buildMcpArgs({
mcpPath: '/tmp/cli.js',
})).toEqual([
'/tmp/cli.js',
]);
expect(__test__.buildMcpArgs({
mcpPath: '/tmp/cli.js',
executablePath: '/usr/bin/chromium',
})).toEqual([
'/tmp/cli.js',
'--executable-path',
'/usr/bin/chromium',
]);
} finally {
if (savedCI !== undefined) {
process.env.CI = savedCI;
} else {
delete process.env.CI;
}
}
});
it('times out slow promises', async () => {
await expect(__test__.withTimeoutMs(new Promise(() => {}), 10, 'timeout')).rejects.toThrow('timeout');
});
it('prefers OPENCLI_MCP_SERVER_PATH over discovered locations', () => {
process.env.OPENCLI_MCP_SERVER_PATH = '/env/mcp/cli.js';
const existsSync = vi.fn((candidate: any) => candidate === '/env/mcp/cli.js');
const execSync = vi.fn();
__test__.setMcpDiscoveryTestHooks({ existsSync, execSync: execSync as any });
expect(__test__.findMcpServerPath()).toBe('/env/mcp/cli.js');
expect(execSync).not.toHaveBeenCalled();
expect(existsSync).toHaveBeenCalledWith('/env/mcp/cli.js');
});
it('discovers global opencli-mcp from the current Node runtime prefix', () => {
const originalExecPath = process.execPath;
const runtimeExecPath = '/opt/homebrew/Cellar/node/25.2.1/bin/node';
const runtimeGlobalMcp = '/opt/homebrew/Cellar/node/25.2.1/lib/node_modules/opencli-mcp/packages/playwright-mcp/cli.js';
Object.defineProperty(process, 'execPath', {
value: runtimeExecPath,
configurable: true,
});
const existsSync = vi.fn((candidate: any) => candidate === runtimeGlobalMcp);
const execSync = vi.fn();
__test__.setMcpDiscoveryTestHooks({ existsSync, execSync: execSync as any });
try {
expect(__test__.findMcpServerPath()).toBe(runtimeGlobalMcp);
expect(execSync).not.toHaveBeenCalled();
expect(existsSync).toHaveBeenCalledWith(runtimeGlobalMcp);
} finally {
Object.defineProperty(process, 'execPath', {
value: originalExecPath,
configurable: true,
});
}
});
it('falls back to npm root -g when runtime prefix lookup misses', () => {
const originalExecPath = process.execPath;
const runtimeExecPath = '/opt/homebrew/Cellar/node/25.2.1/bin/node';
const runtimeGlobalMcp = '/opt/homebrew/Cellar/node/25.2.1/lib/node_modules/opencli-mcp/packages/playwright-mcp/cli.js';
const npmRootGlobal = '/Users/jakevin/.nvm/versions/node/v22.14.0/lib/node_modules';
const npmGlobalMcp = '/Users/jakevin/.nvm/versions/node/v22.14.0/lib/node_modules/opencli-mcp/packages/playwright-mcp/cli.js';
Object.defineProperty(process, 'execPath', {
value: runtimeExecPath,
configurable: true,
});
const existsSync = vi.fn((candidate: any) => candidate === npmGlobalMcp);
const execSync = vi.fn((command: string) => {
if (String(command).includes('npm root -g')) return `${npmRootGlobal}\n` as any;
throw new Error(`unexpected command: ${String(command)}`);
});
__test__.setMcpDiscoveryTestHooks({ existsSync, execSync: execSync as any });
try {
expect(__test__.findMcpServerPath()).toBe(npmGlobalMcp);
expect(execSync).toHaveBeenCalledOnce();
expect(existsSync).toHaveBeenCalledWith(runtimeGlobalMcp);
expect(existsSync).toHaveBeenCalledWith(npmGlobalMcp);
} finally {
Object.defineProperty(process, 'execPath', {
value: originalExecPath,
configurable: true,
});
}
});
it('returns null when new global discovery paths are unavailable', () => {
const originalExecPath = process.execPath;
const runtimeExecPath = '/opt/homebrew/Cellar/node/25.2.1/bin/node';
Object.defineProperty(process, 'execPath', {
value: runtimeExecPath,
configurable: true,
});
const existsSync = vi.fn(() => false);
const execSync = vi.fn((command: string) => {
if (String(command).includes('npm root -g')) return '/missing/global/node_modules\n' as any;
throw new Error(`missing command: ${String(command)}`);
});
__test__.setMcpDiscoveryTestHooks({ existsSync, execSync: execSync as any });
try {
expect(__test__.findMcpServerPath()).toBeNull();
} finally {
Object.defineProperty(process, 'execPath', {
value: originalExecPath,
configurable: true,
});
}
});
});
describe('formatBrowserConnectError', () => {
it('explains missing extension token clearly', () => {
const err = formatBrowserConnectError({
kind: 'missing-token',
mode: 'extension',
timeout: 30,
hasExtensionToken: false,
});
describe('PlaywrightMCP state', () => {
it('transitions to closed after close()', async () => {
const mcp = new PlaywrightMCP();
expect(err.message).toContain('PLAYWRIGHT_MCP_EXTENSION_TOKEN is not set');
expect(err.message).toContain('manual approval dialog');
expect(mcp.state).toBe('idle');
await mcp.close();
expect(mcp.state).toBe('closed');
});
it('mentions token mismatch as likely cause for extension timeout', () => {
const err = formatBrowserConnectError({
kind: 'extension-timeout',
mode: 'extension',
timeout: 30,
hasExtensionToken: true,
tokenFingerprint: 'deadbeef',
});
it('rejects connect() after the session has been closed', async () => {
const mcp = new PlaywrightMCP();
await mcp.close();
expect(err.message).toContain('does not match the token currently shown by the browser extension');
expect(err.message).toContain('deadbeef');
await expect(mcp.connect()).rejects.toThrow('Playwright MCP session is closed');
});
it('keeps CDP timeout guidance separate', () => {
const err = formatBrowserConnectError({
kind: 'cdp-timeout',
mode: 'cdp',
timeout: 30,
hasExtensionToken: false,
});
it('rejects connect() while already connecting', async () => {
const mcp = new PlaywrightMCP();
(mcp as any)._state = 'connecting';
expect(err.message).toContain('via CDP');
expect(err.message).toContain('chrome://inspect#remote-debugging');
await expect(mcp.connect()).rejects.toThrow('Playwright MCP is already connecting');
});
it('rejects connect() while closing', async () => {
const mcp = new PlaywrightMCP();
(mcp as any)._state = 'closing';
await expect(mcp.connect()).rejects.toThrow('Playwright MCP is closing');
});
});
-704
View File
@@ -1,704 +0,0 @@
/**
* Browser interaction via Chrome DevTools Protocol.
* Connects to an existing Chrome browser through CDP auto-discovery or extension bridge.
*/
import { spawn, execSync, type ChildProcess } from 'node:child_process';
import { createHash } from 'node:crypto';
import * as net from 'node:net';
import { fileURLToPath } from 'node:url';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { formatSnapshot } from './snapshotFormatter.js';
/**
* Chrome 144+ auto-discovery: read DevToolsActivePort file to get CDP endpoint.
*
* Starting with Chrome 144, users can enable remote debugging from
* chrome://inspect#remote-debugging without any command-line flags.
* Chrome writes the active port and browser GUID to a DevToolsActivePort file
* in the user data directory, which we read to construct the WebSocket endpoint.
*
* Priority: OPENCLI_CDP_ENDPOINT env > DevToolsActivePort auto-discovery > --extension fallback
*/
/** Quick TCP port probe to verify Chrome is actually listening */
function isPortReachable(port: number, host = '127.0.0.1', timeoutMs = 800): Promise<boolean> {
return new Promise(resolve => {
const sock = net.createConnection({ port, host });
sock.setTimeout(timeoutMs);
sock.on('connect', () => { sock.destroy(); resolve(true); });
sock.on('error', () => resolve(false));
sock.on('timeout', () => { sock.destroy(); resolve(false); });
});
}
export async function discoverChromeEndpoint(): Promise<string | null> {
const candidates: string[] = [];
// User-specified Chrome data dir takes highest priority
if (process.env.CHROME_USER_DATA_DIR) {
candidates.push(path.join(process.env.CHROME_USER_DATA_DIR, 'DevToolsActivePort'));
}
// Standard Chrome/Edge user data dirs per platform
if (process.platform === 'win32') {
const localAppData = process.env.LOCALAPPDATA ?? path.join(os.homedir(), 'AppData', 'Local');
candidates.push(path.join(localAppData, 'Google', 'Chrome', 'User Data', 'DevToolsActivePort'));
candidates.push(path.join(localAppData, 'Microsoft', 'Edge', 'User Data', 'DevToolsActivePort'));
} else if (process.platform === 'darwin') {
candidates.push(path.join(os.homedir(), 'Library', 'Application Support', 'Google', 'Chrome', 'DevToolsActivePort'));
candidates.push(path.join(os.homedir(), 'Library', 'Application Support', 'Microsoft Edge', 'DevToolsActivePort'));
} else {
candidates.push(path.join(os.homedir(), '.config', 'google-chrome', 'DevToolsActivePort'));
candidates.push(path.join(os.homedir(), '.config', 'chromium', 'DevToolsActivePort'));
candidates.push(path.join(os.homedir(), '.config', 'microsoft-edge', 'DevToolsActivePort'));
}
for (const filePath of candidates) {
try {
const content = fs.readFileSync(filePath, 'utf-8').trim();
const lines = content.split('\n');
if (lines.length >= 2) {
const port = parseInt(lines[0], 10);
const browserPath = lines[1]; // e.g. /devtools/browser/<GUID>
if (port > 0 && browserPath.startsWith('/devtools/browser/')) {
const endpoint = `ws://127.0.0.1:${port}${browserPath}`;
// Verify the port is actually reachable (Chrome may have closed, leaving a stale file)
if (await isPortReachable(port)) {
return endpoint;
}
}
}
} catch {}
}
return null;
}
// Read version from package.json (single source of truth)
const __browser_dirname = path.dirname(fileURLToPath(import.meta.url));
const PKG_VERSION = (() => { try { return JSON.parse(fs.readFileSync(path.resolve(__browser_dirname, '..', 'package.json'), 'utf-8')).version; } catch { return '0.0.0'; } })();
const EXTENSION_LOCK_TIMEOUT = parseInt(process.env.OPENCLI_EXTENSION_LOCK_TIMEOUT ?? '120', 10);
const EXTENSION_LOCK_POLL = parseInt(process.env.OPENCLI_EXTENSION_LOCK_POLL_INTERVAL ?? '1', 10);
const CONNECT_TIMEOUT = parseInt(process.env.OPENCLI_BROWSER_CONNECT_TIMEOUT ?? '30', 10);
const LOCK_DIR = path.join(os.tmpdir(), 'opencli-mcp-lock');
type ConnectFailureKind = 'missing-token' | 'extension-timeout' | 'extension-not-installed' | 'cdp-timeout' | 'mcp-init' | 'process-exit' | 'unknown';
type ConnectFailureInput = {
kind: ConnectFailureKind;
mode: 'extension' | 'cdp';
timeout: number;
hasExtensionToken: boolean;
tokenFingerprint?: string | null;
stderr?: string;
exitCode?: number | null;
rawMessage?: string;
};
export function getTokenFingerprint(token: string | undefined): string | null {
if (!token) return null;
return createHash('sha256').update(token).digest('hex').slice(0, 8);
}
export function formatBrowserConnectError(input: ConnectFailureInput): Error {
const stderr = input.stderr?.trim();
const suffix = stderr ? `\n\nMCP stderr:\n${stderr}` : '';
const tokenHint = input.tokenFingerprint ? ` Token fingerprint: ${input.tokenFingerprint}.` : '';
if (input.mode === 'extension') {
if (input.kind === 'missing-token') {
return new Error(
'Failed to connect to Playwright MCP Bridge: PLAYWRIGHT_MCP_EXTENSION_TOKEN is not set.\n\n' +
'Without this token, Chrome will show a manual approval dialog for every new MCP connection. ' +
'Copy the token from the Playwright MCP Bridge extension and set it in BOTH your shell environment and MCP client config.' +
suffix,
);
}
if (input.kind === 'extension-not-installed') {
return new Error(
'Failed to connect to Playwright MCP Bridge: the browser extension did not attach.\n\n' +
'Make sure Chrome is running and the "Playwright MCP Bridge" extension is installed and enabled. ' +
'If Chrome shows an approval dialog, click Allow.' +
suffix,
);
}
if (input.kind === 'extension-timeout') {
const likelyCause = input.hasExtensionToken
? `The most likely cause is that PLAYWRIGHT_MCP_EXTENSION_TOKEN does not match the token currently shown by the browser extension.${tokenHint} Re-copy the token from the extension and update BOTH your shell environment and MCP client config.`
: 'PLAYWRIGHT_MCP_EXTENSION_TOKEN is not configured, so the extension may be waiting for manual approval.';
return new Error(
`Timed out connecting to Playwright MCP Bridge (${input.timeout}s).\n\n` +
`${likelyCause} If a browser prompt is visible, click Allow. You can also switch to Chrome remote debugging mode with OPENCLI_USE_CDP=1 as a fallback.` +
suffix,
);
}
}
if (input.mode === 'cdp' && input.kind === 'cdp-timeout') {
return new Error(
`Timed out connecting to browser via CDP (${input.timeout}s).\n\n` +
'Make sure Chrome is running and remote debugging is enabled at chrome://inspect#remote-debugging, or set OPENCLI_CDP_ENDPOINT explicitly.' +
suffix,
);
}
if (input.kind === 'mcp-init') {
return new Error(`Failed to initialize Playwright MCP: ${input.rawMessage ?? 'unknown error'}${suffix}`);
}
if (input.kind === 'process-exit') {
return new Error(
`Playwright MCP process exited before the browser connection was established${input.exitCode == null ? '' : ` (code ${input.exitCode})`}.` +
suffix,
);
}
return new Error(input.rawMessage ?? 'Failed to connect to browser');
}
function inferConnectFailureKind(args: {
mode: 'extension' | 'cdp';
hasExtensionToken: boolean;
stderr: string;
rawMessage?: string;
exited?: boolean;
}): ConnectFailureKind {
const haystack = `${args.rawMessage ?? ''}\n${args.stderr}`.toLowerCase();
if (args.mode === 'extension' && !args.hasExtensionToken)
return 'missing-token';
if (haystack.includes('extension connection timeout') || haystack.includes('playwright mcp bridge'))
return 'extension-not-installed';
if (args.rawMessage?.startsWith('MCP init failed:'))
return 'mcp-init';
if (args.exited)
return 'process-exit';
if (args.mode === 'extension')
return 'extension-timeout';
if (args.mode === 'cdp')
return 'cdp-timeout';
return 'unknown';
}
// JSON-RPC helpers
let _nextId = 1;
function jsonRpcRequest(method: string, params: Record<string, any> = {}): string {
return JSON.stringify({ jsonrpc: '2.0', id: _nextId++, method, params }) + '\n';
}
import type { IPage } from './types.js';
/**
* Page abstraction wrapping JSON-RPC calls to Playwright MCP.
*/
export class Page implements IPage {
constructor(private _send: (msg: string) => void, private _recv: () => Promise<any>) {}
async call(method: string, params: Record<string, any> = {}): Promise<any> {
this._send(jsonRpcRequest(method, params));
const resp = await this._recv();
if (resp.error) throw new Error(`page.${method}: ${resp.error.message ?? JSON.stringify(resp.error)}`);
// Extract text content from MCP result
const result = resp.result;
if (result?.content) {
const textParts = result.content.filter((c: any) => c.type === 'text');
if (textParts.length === 1) {
let text = textParts[0].text;
// MCP browser_evaluate returns: "[JSON]\n### Ran Playwright code\n```js\n...\n```"
// Strip the "### Ran Playwright code" suffix to get clean JSON
const codeMarker = text.indexOf('### Ran Playwright code');
if (codeMarker !== -1) {
text = text.slice(0, codeMarker).trim();
}
// Also handle "### Result\n[JSON]" format (some MCP versions)
const resultMarker = text.indexOf('### Result\n');
if (resultMarker !== -1) {
text = text.slice(resultMarker + '### Result\n'.length).trim();
}
try { return JSON.parse(text); } catch { return text; }
}
}
return result;
}
// --- High-level methods ---
async goto(url: string): Promise<void> {
await this.call('tools/call', { name: 'browser_navigate', arguments: { url } });
}
async evaluate(js: string): Promise<any> {
// Normalize IIFE format to function format expected by MCP browser_evaluate
const normalized = this.normalizeEval(js);
return this.call('tools/call', { name: 'browser_evaluate', arguments: { function: normalized } });
}
private normalizeEval(source: string): string {
const s = source.trim();
if (!s) return '() => undefined';
// IIFE: (async () => {...})() → wrap as () => (...)
if (s.startsWith('(') && s.endsWith(')()')) return `() => (${s})`;
// Already a function/arrow
if (/^(async\s+)?\([^)]*\)\s*=>/.test(s)) return s;
if (/^(async\s+)?[A-Za-z_][A-Za-z0-9_]*\s*=>/.test(s)) return s;
if (s.startsWith('function ') || s.startsWith('async function ')) return s;
// Raw expression → wrap
return `() => (${s})`;
}
async snapshot(opts: { interactive?: boolean; compact?: boolean; maxDepth?: number; raw?: boolean } = {}): Promise<any> {
const raw = await this.call('tools/call', { name: 'browser_snapshot', arguments: {} });
if (opts.raw) return raw;
if (typeof raw === 'string') return formatSnapshot(raw, opts);
return raw;
}
async click(ref: string): Promise<void> {
await this.call('tools/call', { name: 'browser_click', arguments: { element: 'click target', ref } });
}
async typeText(ref: string, text: string): Promise<void> {
await this.call('tools/call', { name: 'browser_type', arguments: { element: 'type target', ref, text } });
}
async pressKey(key: string): Promise<void> {
await this.call('tools/call', { name: 'browser_press_key', arguments: { key } });
}
async wait(options: number | { text?: string; time?: number; timeout?: number }): Promise<void> {
if (typeof options === 'number') {
await this.call('tools/call', { name: 'browser_wait_for', arguments: { time: options } });
} else {
// Pass directly to native wait_for, which supports natively awaiting text strings without heavy DOM polling
await this.call('tools/call', { name: 'browser_wait_for', arguments: options });
}
}
async tabs(): Promise<any> {
return this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'list' } });
}
async closeTab(index?: number): Promise<void> {
await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'close', ...(index !== undefined ? { index } : {}) } });
}
async newTab(): Promise<void> {
await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'new' } });
}
async selectTab(index: number): Promise<void> {
await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'select', index } });
}
async networkRequests(includeStatic: boolean = false): Promise<any> {
return this.call('tools/call', { name: 'browser_network_requests', arguments: { includeStatic } });
}
async consoleMessages(level: string = 'info'): Promise<any> {
return this.call('tools/call', { name: 'browser_console_messages', arguments: { level } });
}
async scroll(direction: string = 'down', amount: number = 500): Promise<void> {
await this.call('tools/call', { name: 'browser_press_key', arguments: { key: direction === 'down' ? 'PageDown' : 'PageUp' } });
}
async autoScroll(options: { times?: number; delayMs?: number } = {}): Promise<void> {
const times = options.times ?? 3;
const delayMs = options.delayMs ?? 2000;
const js = `
async () => {
const maxTimes = ${times};
const maxWaitMs = ${delayMs};
for (let i = 0; i < maxTimes; i++) {
const lastHeight = document.body.scrollHeight;
window.scrollTo(0, lastHeight);
await new Promise(resolve => {
let timeoutId;
const observer = new MutationObserver(() => {
if (document.body.scrollHeight > lastHeight) {
clearTimeout(timeoutId);
observer.disconnect();
setTimeout(resolve, 100); // Small debounce for rendering
}
});
observer.observe(document.body, { childList: true, subtree: true });
timeoutId = setTimeout(() => {
observer.disconnect();
resolve(null);
}, maxWaitMs);
});
}
}
`;
await this.evaluate(js);
}
async installInterceptor(pattern: string): Promise<void> {
const js = `
() => {
window.__opencli_xhr = window.__opencli_xhr || [];
window.__opencli_patterns = window.__opencli_patterns || [];
if (!window.__opencli_patterns.includes('${pattern}')) {
window.__opencli_patterns.push('${pattern}');
}
if (!window.__patched_xhr) {
const checkMatch = (url) => window.__opencli_patterns.some(p => url.includes(p));
const XHR = XMLHttpRequest.prototype;
const open = XHR.open;
const send = XHR.send;
XHR.open = function(method, url) {
this._url = url;
return open.call(this, method, url, ...Array.prototype.slice.call(arguments, 2));
};
XHR.send = function() {
this.addEventListener('load', function() {
if (checkMatch(this._url)) {
try { window.__opencli_xhr.push({url: this._url, data: JSON.parse(this.responseText)}); } catch(e){}
}
});
return send.apply(this, arguments);
};
const origFetch = window.fetch;
window.fetch = async function(...args) {
let u = typeof args[0] === 'string' ? args[0] : (args[0] && args[0].url) || '';
const res = await origFetch.apply(this, args);
setTimeout(async () => {
try {
if (checkMatch(u)) {
const clone = res.clone();
const j = await clone.json();
window.__opencli_xhr.push({url: u, data: j});
}
} catch(e) {}
}, 0);
return res;
};
window.__patched_xhr = true;
}
}
`;
await this.evaluate(js);
}
async getInterceptedRequests(): Promise<any[]> {
return (await this.evaluate('() => window.__opencli_xhr')) || [];
}
}
/**
* Playwright MCP process manager.
*/
export class PlaywrightMCP {
private static _activeInsts: Set<PlaywrightMCP> = new Set();
private static _cleanupRegistered = false;
private static _registerGlobalCleanup() {
if (this._cleanupRegistered) return;
this._cleanupRegistered = true;
const cleanup = () => {
for (const inst of this._activeInsts) {
if (inst._lockAcquired) {
try { fs.rmdirSync(LOCK_DIR); } catch {}
inst._lockAcquired = false;
}
if (inst._proc && !inst._proc.killed) {
try { inst._proc.kill('SIGKILL'); } catch {}
}
}
};
process.on('exit', cleanup);
process.on('SIGINT', () => { cleanup(); process.exit(130); });
process.on('SIGTERM', () => { cleanup(); process.exit(143); });
}
private _proc: ChildProcess | null = null;
private _buffer = '';
private _waiters: Array<(data: any) => void> = [];
private _lockAcquired = false;
private _initialTabCount = 0;
private _page: Page | null = null;
async connect(opts: { timeout?: number; forceExtension?: boolean } = {}): Promise<Page> {
await this._acquireLock();
const timeout = opts.timeout ?? CONNECT_TIMEOUT;
const mcpPath = findMcpServerPath();
if (!mcpPath) throw new Error('Playwright MCP server not found. Install: npm install -D @playwright/mcp');
// Connection priority:
// 1. OPENCLI_CDP_ENDPOINT env var → explicit CDP endpoint
// 2. OPENCLI_USE_CDP=1 → auto-discover via DevToolsActivePort
// 3. Default → --extension mode (Playwright MCP Bridge)
// Some anti-bot sites (e.g. BOSS Zhipin) detect CDP — use forceExtension to bypass.
const forceExt = opts.forceExtension || process.env.OPENCLI_FORCE_EXTENSION === '1';
let cdpEndpoint: string | null = null;
if (!forceExt) {
if (process.env.OPENCLI_CDP_ENDPOINT) {
cdpEndpoint = process.env.OPENCLI_CDP_ENDPOINT;
} else if (process.env.OPENCLI_USE_CDP === '1') {
cdpEndpoint = await discoverChromeEndpoint();
}
}
return new Promise<Page>((resolve, reject) => {
const isDebug = process.env.DEBUG?.includes('opencli:mcp');
const debugLog = (msg: string) => isDebug && console.error(`[opencli:mcp] ${msg}`);
const mode: 'extension' | 'cdp' = cdpEndpoint ? 'cdp' : 'extension';
const extensionToken = process.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN;
const tokenFingerprint = getTokenFingerprint(extensionToken);
let stderrBuffer = '';
let settled = false;
const settleError = (kind: ConnectFailureKind, extra: { rawMessage?: string; exitCode?: number | null } = {}) => {
if (settled) return;
settled = true;
clearTimeout(timer);
reject(formatBrowserConnectError({
kind,
mode,
timeout,
hasExtensionToken: !!extensionToken,
tokenFingerprint,
stderr: stderrBuffer,
exitCode: extra.exitCode,
rawMessage: extra.rawMessage,
}));
};
const settleSuccess = (pageToResolve: Page) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(pageToResolve);
};
const timer = setTimeout(() => {
debugLog('Connection timed out');
settleError(inferConnectFailureKind({
mode,
hasExtensionToken: !!extensionToken,
stderr: stderrBuffer,
}));
}, timeout * 1000);
const mcpArgs: string[] = [mcpPath];
if (cdpEndpoint) {
mcpArgs.push('--cdp-endpoint', cdpEndpoint);
} else {
mcpArgs.push('--extension');
}
if (process.env.OPENCLI_VERBOSE) {
console.error(`[opencli] CDP mode: ${cdpEndpoint ? `auto-discovered ${cdpEndpoint}` : 'fallback to --extension'}`);
if (mode === 'extension') {
console.error(`[opencli] Extension token: ${extensionToken ? `configured (fingerprint ${tokenFingerprint})` : 'missing'}`);
}
}
if (process.env.OPENCLI_BROWSER_EXECUTABLE_PATH) {
mcpArgs.push('--executablePath', process.env.OPENCLI_BROWSER_EXECUTABLE_PATH);
}
debugLog(`Spawning node ${mcpArgs.join(' ')}`);
this._proc = spawn('node', mcpArgs, {
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env },
});
// Increase max listeners to avoid warnings
this._proc.setMaxListeners(20);
if (this._proc.stdout) this._proc.stdout.setMaxListeners(20);
const page = new Page(
(msg) => { if (this._proc?.stdin?.writable) this._proc.stdin.write(msg); },
() => new Promise<any>((res) => { this._waiters.push(res); }),
);
this._page = page;
this._proc.stdout?.on('data', (chunk: Buffer) => {
this._buffer += chunk.toString();
const lines = this._buffer.split('\n');
this._buffer = lines.pop() ?? '';
for (const line of lines) {
if (!line.trim()) continue;
debugLog(`RECV: ${line}`);
try {
const parsed = JSON.parse(line);
const waiter = this._waiters.shift();
if (waiter) waiter(parsed);
} catch (e) {
debugLog(`Parse error: ${e}`);
}
}
});
this._proc.stderr?.on('data', (chunk: Buffer) => {
const text = chunk.toString();
stderrBuffer += text;
debugLog(`STDERR: ${text}`);
});
this._proc.on('error', (err) => {
debugLog(`Subprocess error: ${err.message}`);
settleError('process-exit', { rawMessage: err.message });
});
this._proc.on('close', (code) => {
debugLog(`Subprocess closed with code ${code}`);
if (!settled) {
settleError(inferConnectFailureKind({
mode,
hasExtensionToken: !!extensionToken,
stderr: stderrBuffer,
exited: true,
}), { exitCode: code });
}
});
// Initialize: send initialize request
const initMsg = jsonRpcRequest('initialize', {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: 'opencli', version: PKG_VERSION },
});
debugLog(`SEND: ${initMsg.trim()}`);
this._proc.stdin?.write(initMsg);
// Wait for initialize response, then send initialized notification
const origRecv = () => new Promise<any>((res) => { this._waiters.push(res); });
debugLog('Waiting for initialize response...');
origRecv().then((resp) => {
debugLog('Got initialize response');
if (resp.error) {
settleError(inferConnectFailureKind({
mode,
hasExtensionToken: !!extensionToken,
stderr: stderrBuffer,
rawMessage: `MCP init failed: ${resp.error.message}`,
}), { rawMessage: resp.error.message });
return;
}
const initializedMsg = JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n';
debugLog(`SEND: ${initializedMsg.trim()}`);
this._proc?.stdin?.write(initializedMsg);
// Get initial tab count for cleanup
debugLog('Fetching initial tabs count...');
page.tabs().then((tabs: any) => {
debugLog(`Tabs response: ${typeof tabs === 'string' ? tabs : JSON.stringify(tabs)}`);
if (typeof tabs === 'string') {
this._initialTabCount = (tabs.match(/Tab \d+/g) || []).length;
} else if (Array.isArray(tabs)) {
this._initialTabCount = tabs.length;
}
settleSuccess(page);
}).catch((err) => {
debugLog(`Tabs fetch error: ${err.message}`);
settleSuccess(page);
});
}).catch((err) => {
debugLog(`Init promise rejected: ${err.message}`);
settleError('mcp-init', { rawMessage: err.message });
});
});
}
async close(): Promise<void> {
try {
// Close tabs opened during this session (site tabs + extension tabs)
if (this._page && this._proc && !this._proc.killed) {
try {
const tabs = await this._page.tabs();
const tabStr = typeof tabs === 'string' ? tabs : JSON.stringify(tabs);
const allTabs = tabStr.match(/Tab (\d+)/g) || [];
const currentTabCount = allTabs.length;
// Close tabs in reverse order to avoid index shifting issues
// Keep the original tabs that existed before the command started
if (currentTabCount > this._initialTabCount && this._initialTabCount > 0) {
for (let i = currentTabCount - 1; i >= this._initialTabCount; i--) {
try { await this._page.closeTab(i); } catch {}
}
}
} catch {}
}
if (this._proc && !this._proc.killed) {
this._proc.kill('SIGTERM');
await new Promise<void>((res) => { this._proc?.on('exit', () => res()); setTimeout(res, 3000); });
}
} finally {
this._page = null;
this._releaseLock();
PlaywrightMCP._activeInsts.delete(this);
}
}
private async _acquireLock(): Promise<void> {
const start = Date.now();
while (true) {
try { fs.mkdirSync(LOCK_DIR, { recursive: false }); this._lockAcquired = true; return; }
catch (e: any) {
if (e.code !== 'EEXIST') throw e;
if ((Date.now() - start) / 1000 > EXTENSION_LOCK_TIMEOUT) {
// Force remove stale lock
try { fs.rmdirSync(LOCK_DIR); } catch {}
continue;
}
await new Promise(r => setTimeout(r, EXTENSION_LOCK_POLL * 1000));
}
}
}
private _releaseLock(): void {
if (this._lockAcquired) {
try { fs.rmdirSync(LOCK_DIR); } catch {}
this._lockAcquired = false;
}
}
}
function findMcpServerPath(): string | null {
// Check local node_modules first (@playwright/mcp is the modern package)
const localMcp = path.resolve('node_modules', '@playwright', 'mcp', 'cli.js');
if (fs.existsSync(localMcp)) return localMcp;
// Check project-relative path
const __dirname2 = path.dirname(fileURLToPath(import.meta.url));
const projectMcp = path.resolve(__dirname2, '..', 'node_modules', '@playwright', 'mcp', 'cli.js');
if (fs.existsSync(projectMcp)) return projectMcp;
// Check common locations
const candidates = [
path.join(os.homedir(), '.npm', '_npx'),
path.join(os.homedir(), 'node_modules', '.bin'),
'/usr/local/lib/node_modules',
];
// Try npx resolution (legacy package name)
try {
const result = execSync('npx -y --package=@playwright/mcp which mcp-server-playwright 2>/dev/null', { encoding: 'utf-8', timeout: 10000 }).trim();
if (result && fs.existsSync(result)) return result;
} catch {}
// Try which
try {
const result = execSync('which mcp-server-playwright 2>/dev/null', { encoding: 'utf-8', timeout: 5000 }).trim();
if (result && fs.existsSync(result)) return result;
} catch {}
// Search in common npx cache
for (const base of candidates) {
if (!fs.existsSync(base)) continue;
try {
const found = execSync(`find "${base}" -name "cli.js" -path "*playwright*mcp*" 2>/dev/null | head -1`, { encoding: 'utf-8', timeout: 5000 }).trim();
if (found) return found;
} catch {}
}
return null;
}
+126
View File
@@ -0,0 +1,126 @@
/**
* MCP server path discovery and argument building.
*/
import { execSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
let _cachedMcpServerPath: string | null | undefined;
let _existsSync = fs.existsSync;
let _execSync = execSync;
export function resetMcpServerPathCache(): void {
_cachedMcpServerPath = undefined;
}
export function setMcpDiscoveryTestHooks(input?: {
existsSync?: typeof fs.existsSync;
execSync?: typeof execSync;
}): void {
_existsSync = input?.existsSync ?? fs.existsSync;
_execSync = input?.execSync ?? execSync;
}
export function findMcpServerPath(): string | null {
if (_cachedMcpServerPath !== undefined) return _cachedMcpServerPath;
const envMcp = process.env.OPENCLI_MCP_SERVER_PATH;
if (envMcp && _existsSync(envMcp)) {
_cachedMcpServerPath = envMcp;
return _cachedMcpServerPath;
}
// Check local node_modules first (opencli-mcp is the modern package)
const localMcp = path.resolve('node_modules', 'opencli-mcp', 'cli.js');
if (_existsSync(localMcp)) {
_cachedMcpServerPath = localMcp;
return _cachedMcpServerPath;
}
// Check project-relative path
const __dirname2 = path.dirname(fileURLToPath(import.meta.url));
const projectMcp = path.resolve(__dirname2, '..', '..', 'node_modules', 'opencli-mcp', 'cli.js');
if (_existsSync(projectMcp)) {
_cachedMcpServerPath = projectMcp;
return _cachedMcpServerPath;
}
// Check global npm/yarn locations derived from current Node runtime.
const nodePrefix = path.resolve(path.dirname(process.execPath), '..');
const globalNodeModules = path.join(nodePrefix, 'lib', 'node_modules');
const globalMcp = path.join(globalNodeModules, 'opencli-mcp', 'cli.js');
if (_existsSync(globalMcp)) {
_cachedMcpServerPath = globalMcp;
return _cachedMcpServerPath;
}
// Check npm global root directly.
try {
const npmRootGlobal = _execSync('npm root -g 2>/dev/null', {
encoding: 'utf-8',
timeout: 5000,
}).trim();
const npmGlobalMcp = path.join(npmRootGlobal, 'opencli-mcp', 'cli.js');
if (npmRootGlobal && _existsSync(npmGlobalMcp)) {
_cachedMcpServerPath = npmGlobalMcp;
return _cachedMcpServerPath;
}
} catch {}
// Check common locations
const candidates = [
path.join(os.homedir(), '.npm', '_npx'),
path.join(os.homedir(), 'node_modules', '.bin'),
'/usr/local/lib/node_modules',
];
// Try npx resolution (legacy package name)
try {
const result = _execSync('npx -y --package=opencli-mcp which opencli-mcp 2>/dev/null', { encoding: 'utf-8', timeout: 10000 }).trim();
if (result && _existsSync(result)) {
_cachedMcpServerPath = result;
return _cachedMcpServerPath;
}
} catch {}
// Try which
try {
const result = _execSync('which opencli-mcp 2>/dev/null', { encoding: 'utf-8', timeout: 5000 }).trim();
if (result && _existsSync(result)) {
_cachedMcpServerPath = result;
return _cachedMcpServerPath;
}
} catch {}
// Search in common npx cache
for (const base of candidates) {
if (!_existsSync(base)) continue;
try {
const found = _execSync(`find "${base}" -name "cli.js" -path "*opencli*mcp*" 2>/dev/null | head -1`, { encoding: 'utf-8', timeout: 5000 }).trim();
if (found) {
_cachedMcpServerPath = found;
return _cachedMcpServerPath;
}
} catch {}
}
_cachedMcpServerPath = null;
return _cachedMcpServerPath;
}
export function buildMcpArgs(input: { mcpPath: string; executablePath?: string | null }): string[] {
const args = [input.mcpPath];
if (!process.env.CI) {
// Local: always connect to user's running Chrome via MCP Bridge extension
args.push('--extension');
}
// CI: standalone mode — @playwright/mcp launches its own browser (headed by default).
// xvfb provides a virtual display for headed mode in GitHub Actions.
if (input.executablePath) {
args.push('--executable-path', input.executablePath);
}
return args;
}
+65
View File
@@ -0,0 +1,65 @@
/**
* Browser connection error classification and formatting.
*/
export type ConnectFailureKind = 'extension-timeout' | 'extension-not-installed' | 'mcp-init' | 'process-exit' | 'unknown';
export type ConnectFailureInput = {
kind: ConnectFailureKind;
timeout: number;
stderr?: string;
exitCode?: number | null;
rawMessage?: string;
};
export function formatBrowserConnectError(input: ConnectFailureInput): Error {
const stderr = input.stderr?.trim();
const suffix = stderr ? `\n\nMCP stderr:\n${stderr}` : '';
if (input.kind === 'extension-not-installed') {
return new Error(
'Failed to connect to OpenCLI MCP Bridge: the browser extension did not attach.\n\n' +
'Make sure Chrome is running and the "OpenCLI MCP Bridge" extension is installed and enabled in Developer Mode.' +
suffix,
);
}
if (input.kind === 'extension-timeout') {
return new Error(
`Timed out connecting to OpenCLI MCP Bridge (${input.timeout}s).\n\n` +
`Make sure Chrome is running with the OpenCLI MCP Bridge extension enabled.` +
suffix,
);
}
if (input.kind === 'mcp-init') {
return new Error(`Failed to initialize OpenCLI MCP: ${input.rawMessage ?? 'unknown error'}${suffix}`);
}
if (input.kind === 'process-exit') {
return new Error(
`OpenCLI MCP process exited before the browser connection was established${input.exitCode == null ? '' : ` (code ${input.exitCode})`}.` +
suffix,
);
}
return new Error(input.rawMessage ?? 'Failed to connect to browser');
}
export function inferConnectFailureKind(args: {
stderr: string;
rawMessage?: string;
exited?: boolean;
}): ConnectFailureKind {
const haystack = `${args.rawMessage ?? ''}\n${args.stderr}`.toLowerCase();
if (haystack.includes('extension connection timeout') || haystack.includes('opencli mcp bridge') || haystack.includes('playwright mcp bridge'))
return 'extension-not-installed';
if (args.rawMessage?.startsWith('MCP init failed:'))
return 'mcp-init';
if (args.exited)
return 'process-exit';
return 'extension-timeout';
}
+29
View File
@@ -0,0 +1,29 @@
/**
* Browser module — public API re-exports.
*
* This barrel replaces the former monolithic browser.ts.
* External code should import from './browser/index.js' (or './browser.js' via Node resolution).
*/
export { Page } from './page.js';
export { PlaywrightMCP } from './mcp.js';
export { formatBrowserConnectError } from './errors.js';
export type { ConnectFailureKind, ConnectFailureInput } from './errors.js';
// Test-only helpers — exposed for unit tests
import { createJsonRpcRequest } from './mcp.js';
import { extractTabEntries, diffTabIndexes, appendLimited } from './tabs.js';
import { buildMcpArgs, findMcpServerPath, resetMcpServerPathCache, setMcpDiscoveryTestHooks } from './discover.js';
import { withTimeoutMs } from '../runtime.js';
export const __test__ = {
createJsonRpcRequest,
extractTabEntries,
diffTabIndexes,
appendLimited,
buildMcpArgs,
findMcpServerPath,
resetMcpServerPathCache,
setMcpDiscoveryTestHooks,
withTimeoutMs,
};
+298
View File
@@ -0,0 +1,298 @@
/**
* Playwright MCP process manager.
* Handles lifecycle management, JSON-RPC communication, and browser session orchestration.
*/
import { spawn, type ChildProcess } from 'node:child_process';
import type { IPage } from '../types.js';
import { withTimeoutMs, DEFAULT_BROWSER_CONNECT_TIMEOUT } from '../runtime.js';
import { PKG_VERSION } from '../version.js';
import { Page } from './page.js';
import { formatBrowserConnectError, inferConnectFailureKind } from './errors.js';
import { findMcpServerPath, buildMcpArgs } from './discover.js';
import { extractTabIdentities, extractTabEntries, diffTabIndexes, appendLimited } from './tabs.js';
const STDERR_BUFFER_LIMIT = 16 * 1024;
const INITIAL_TABS_TIMEOUT_MS = 1500;
const TAB_CLEANUP_TIMEOUT_MS = 2000;
export type PlaywrightMCPState = 'idle' | 'connecting' | 'connected' | 'closing' | 'closed';
// JSON-RPC helpers
let _nextId = 1;
export function createJsonRpcRequest(method: string, params: Record<string, unknown> = {}): { id: number; message: string } {
const id = _nextId++;
return {
id,
message: JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n',
};
}
/**
* Playwright MCP process manager.
*/
export class PlaywrightMCP {
private static _activeInsts: Set<PlaywrightMCP> = new Set();
private static _cleanupRegistered = false;
private static _registerGlobalCleanup() {
if (this._cleanupRegistered) return;
this._cleanupRegistered = true;
const cleanup = () => {
for (const inst of this._activeInsts) {
if (inst._proc && !inst._proc.killed) {
try { inst._proc.kill('SIGKILL'); } catch {}
}
}
};
process.on('exit', cleanup);
process.on('SIGINT', () => { cleanup(); process.exit(130); });
process.on('SIGTERM', () => { cleanup(); process.exit(143); });
}
private _proc: ChildProcess | null = null;
private _buffer = '';
private _pending = new Map<number, { resolve: (data: any) => void; reject: (error: Error) => void }>();
private _initialTabIdentities: string[] = [];
private _closingPromise: Promise<void> | null = null;
private _state: PlaywrightMCPState = 'idle';
private _page: Page | null = null;
get state(): PlaywrightMCPState {
return this._state;
}
private _sendRequest(method: string, params: Record<string, unknown> = {}): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!this._proc?.stdin?.writable) {
reject(new Error('Playwright MCP process is not writable'));
return;
}
const { id, message } = createJsonRpcRequest(method, params);
this._pending.set(id, { resolve, reject });
this._proc.stdin.write(message, (err) => {
if (!err) return;
this._pending.delete(id);
reject(err);
});
});
}
private _rejectPendingRequests(error: Error): void {
const pending = [...this._pending.values()];
this._pending.clear();
for (const waiter of pending) waiter.reject(error);
}
private _resetAfterFailedConnect(): void {
const proc = this._proc;
this._page = null;
this._proc = null;
this._buffer = '';
this._initialTabIdentities = [];
this._rejectPendingRequests(new Error('Playwright MCP connect failed'));
PlaywrightMCP._activeInsts.delete(this);
if (proc && !proc.killed) {
try { proc.kill('SIGKILL'); } catch {}
}
}
async connect(opts: { timeout?: number } = {}): Promise<IPage> {
if (this._state === 'connected' && this._page) return this._page;
if (this._state === 'connecting') throw new Error('Playwright MCP is already connecting');
if (this._state === 'closing') throw new Error('Playwright MCP is closing');
if (this._state === 'closed') throw new Error('Playwright MCP session is closed');
const mcpPath = findMcpServerPath();
if (!mcpPath) throw new Error('Playwright MCP server not found. Install: npm install -D @playwright/mcp');
PlaywrightMCP._registerGlobalCleanup();
PlaywrightMCP._activeInsts.add(this);
this._state = 'connecting';
const timeout = opts.timeout ?? DEFAULT_BROWSER_CONNECT_TIMEOUT;
return new Promise<Page>((resolve, reject) => {
const isDebug = process.env.DEBUG?.includes('opencli:mcp');
const debugLog = (msg: string) => isDebug && console.error(`[opencli:mcp] ${msg}`);
const useExtension = true; // Always true in dev config or local for opencli-mcp
let stderrBuffer = '';
let settled = false;
const settleError = (kind: Parameters<typeof formatBrowserConnectError>[0]['kind'], extra: { rawMessage?: string; exitCode?: number | null } = {}) => {
if (settled) return;
settled = true;
this._state = 'idle';
clearTimeout(timer);
this._resetAfterFailedConnect();
reject(formatBrowserConnectError({
kind,
timeout,
stderr: stderrBuffer,
exitCode: extra.exitCode,
rawMessage: extra.rawMessage,
}));
};
const settleSuccess = (pageToResolve: Page) => {
if (settled) return;
settled = true;
this._state = 'connected';
clearTimeout(timer);
resolve(pageToResolve);
};
const timer = setTimeout(() => {
debugLog('Connection timed out');
settleError(inferConnectFailureKind({
stderr: stderrBuffer,
}));
}, timeout * 1000);
const mcpArgs = buildMcpArgs({
mcpPath,
executablePath: process.env.OPENCLI_BROWSER_EXECUTABLE_PATH,
});
if (process.env.OPENCLI_VERBOSE) {
console.error(`[opencli] Mode: extension`);
}
debugLog(`Spawning node ${mcpArgs.join(' ')}`);
this._proc = spawn('node', mcpArgs, {
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env },
});
// Increase max listeners to avoid warnings
this._proc.setMaxListeners(20);
if (this._proc.stdout) this._proc.stdout.setMaxListeners(20);
const page = new Page((method, params = {}) => this._sendRequest(method, params));
this._page = page;
this._proc.stdout?.on('data', (chunk: Buffer) => {
this._buffer += chunk.toString();
const lines = this._buffer.split('\n');
this._buffer = lines.pop() ?? '';
for (const line of lines) {
if (!line.trim()) continue;
debugLog(`RECV: ${line}`);
try {
const parsed = JSON.parse(line);
if (typeof parsed?.id === 'number') {
const waiter = this._pending.get(parsed.id);
if (waiter) {
this._pending.delete(parsed.id);
waiter.resolve(parsed);
}
}
} catch (e) {
debugLog(`Parse error: ${e}`);
}
}
});
this._proc.stderr?.on('data', (chunk: Buffer) => {
const text = chunk.toString();
stderrBuffer = appendLimited(stderrBuffer, text, STDERR_BUFFER_LIMIT);
debugLog(`STDERR: ${text}`);
});
this._proc.on('error', (err) => {
debugLog(`Subprocess error: ${err.message}`);
this._rejectPendingRequests(new Error(`Playwright MCP process error: ${err.message}`));
settleError('process-exit', { rawMessage: err.message });
});
this._proc.on('close', (code) => {
debugLog(`Subprocess closed with code ${code}`);
this._rejectPendingRequests(new Error(`Playwright MCP process exited before response${code == null ? '' : ` (code ${code})`}`));
if (!settled) {
settleError(inferConnectFailureKind({
stderr: stderrBuffer,
exited: true,
}), { exitCode: code });
}
});
// Initialize: send initialize request
debugLog('Waiting for initialize response...');
this._sendRequest('initialize', {
protocolVersion: '2024-11-05',
capabilities: {},
clientInfo: { name: 'opencli', version: PKG_VERSION },
}).then((resp: any) => {
debugLog('Got initialize response');
if (resp.error) {
settleError(inferConnectFailureKind({
stderr: stderrBuffer,
rawMessage: `MCP init failed: ${resp.error.message}`,
}), { rawMessage: resp.error.message });
return;
}
const initializedMsg = JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n';
debugLog(`SEND: ${initializedMsg.trim()}`);
this._proc?.stdin?.write(initializedMsg);
// Use tabs as a readiness probe and for tab cleanup bookkeeping.
debugLog('Fetching initial tabs count...');
withTimeoutMs(page.tabs(), INITIAL_TABS_TIMEOUT_MS, 'Timed out fetching initial tabs').then((tabs: any) => {
debugLog(`Tabs response: ${typeof tabs === 'string' ? tabs : JSON.stringify(tabs)}`);
this._initialTabIdentities = extractTabIdentities(tabs);
settleSuccess(page);
}).catch((err: Error) => {
debugLog(`Tabs fetch error: ${err.message}`);
settleSuccess(page);
});
}).catch((err: Error) => {
debugLog(`Init promise rejected: ${err.message}`);
settleError('mcp-init', { rawMessage: err.message });
});
});
}
async close(): Promise<void> {
if (this._closingPromise) return this._closingPromise;
if (this._state === 'closed') return;
this._state = 'closing';
this._closingPromise = (async () => {
try {
// Extension mode opens bridge/session tabs that we can clean up best-effort.
if (this._page && this._proc && !this._proc.killed) {
try {
const tabs = await withTimeoutMs(this._page.tabs(), TAB_CLEANUP_TIMEOUT_MS, 'Timed out fetching tabs during cleanup');
const tabEntries = extractTabEntries(tabs);
const tabsToClose = diffTabIndexes(this._initialTabIdentities, tabEntries);
for (const index of tabsToClose) {
try { await this._page.closeTab(index); } catch {}
}
} catch {}
}
if (this._proc && !this._proc.killed) {
this._proc.kill('SIGTERM');
const exited = await new Promise<boolean>((res) => {
let done = false;
const finish = (value: boolean) => {
if (done) return;
done = true;
res(value);
};
this._proc?.once('exit', () => finish(true));
setTimeout(() => finish(false), 3000);
});
if (!exited && this._proc && !this._proc.killed) {
try { this._proc.kill('SIGKILL'); } catch {}
}
}
} finally {
this._rejectPendingRequests(new Error('Playwright MCP session closed'));
this._page = null;
this._proc = null;
this._state = 'closed';
PlaywrightMCP._activeInsts.delete(this);
}
})();
return this._closingPromise;
}
}
+152
View File
@@ -0,0 +1,152 @@
/**
* Page abstraction wrapping JSON-RPC calls to Playwright MCP.
*/
import { formatSnapshot } from '../snapshotFormatter.js';
import { normalizeEvaluateSource } from '../pipeline/template.js';
import { generateInterceptorJs, generateReadInterceptedJs } from '../interceptor.js';
import type { IPage } from '../types.js';
/**
* Page abstraction wrapping JSON-RPC calls to Playwright MCP.
*/
export class Page implements IPage {
constructor(private _request: (method: string, params?: Record<string, unknown>) => Promise<Record<string, unknown>>) {}
async call(method: string, params: Record<string, unknown> = {}): Promise<any> {
const resp = await this._request(method, params);
if (resp.error) throw new Error(`page.${method}: ${(resp.error as any).message ?? JSON.stringify(resp.error)}`);
// Extract text content from MCP result
const result = resp.result as any;
if (result?.content) {
const textParts = result.content.filter((c: any) => c.type === 'text');
if (textParts.length === 1) {
let text = textParts[0].text;
// MCP browser_evaluate returns: "[JSON]\n### Ran Playwright code\n```js\n...\n```"
// Strip the "### Ran Playwright code" suffix to get clean JSON
const codeMarker = text.indexOf('### Ran Playwright code');
if (codeMarker !== -1) {
text = text.slice(0, codeMarker).trim();
}
// Also handle "### Result\n[JSON]" format (some MCP versions)
const resultMarker = text.indexOf('### Result\n');
if (resultMarker !== -1) {
text = text.slice(resultMarker + '### Result\n'.length).trim();
}
try { return JSON.parse(text); } catch { return text; }
}
}
return result;
}
// --- High-level methods ---
async goto(url: string): Promise<void> {
await this.call('tools/call', { name: 'browser_navigate', arguments: { url } });
}
async evaluate(js: string): Promise<any> {
// Normalize IIFE format to function format expected by MCP browser_evaluate
const normalized = normalizeEvaluateSource(js);
return this.call('tools/call', { name: 'browser_evaluate', arguments: { function: normalized } });
}
async snapshot(opts: { interactive?: boolean; compact?: boolean; maxDepth?: number; raw?: boolean } = {}): Promise<any> {
const raw = await this.call('tools/call', { name: 'browser_snapshot', arguments: {} });
if (opts.raw) return raw;
if (typeof raw === 'string') return formatSnapshot(raw, opts);
return raw;
}
async click(ref: string): Promise<void> {
await this.call('tools/call', { name: 'browser_click', arguments: { element: 'click target', ref } });
}
async typeText(ref: string, text: string): Promise<void> {
await this.call('tools/call', { name: 'browser_type', arguments: { element: 'type target', ref, text } });
}
async pressKey(key: string): Promise<void> {
await this.call('tools/call', { name: 'browser_press_key', arguments: { key } });
}
async wait(options: number | { text?: string; time?: number; timeout?: number }): Promise<void> {
if (typeof options === 'number') {
await this.call('tools/call', { name: 'browser_wait_for', arguments: { time: options } });
} else {
// Pass directly to native wait_for, which supports natively awaiting text strings without heavy DOM polling
await this.call('tools/call', { name: 'browser_wait_for', arguments: options });
}
}
async tabs(): Promise<any> {
return this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'list' } });
}
async closeTab(index?: number): Promise<void> {
await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'close', ...(index !== undefined ? { index } : {}) } });
}
async newTab(): Promise<void> {
await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'new' } });
}
async selectTab(index: number): Promise<void> {
await this.call('tools/call', { name: 'browser_tabs', arguments: { action: 'select', index } });
}
async networkRequests(includeStatic: boolean = false): Promise<any> {
return this.call('tools/call', { name: 'browser_network_requests', arguments: { includeStatic } });
}
async consoleMessages(level: string = 'info'): Promise<any> {
return this.call('tools/call', { name: 'browser_console_messages', arguments: { level } });
}
async scroll(direction: string = 'down', _amount: number = 500): Promise<void> {
await this.call('tools/call', { name: 'browser_press_key', arguments: { key: direction === 'down' ? 'PageDown' : 'PageUp' } });
}
async autoScroll(options: { times?: number; delayMs?: number } = {}): Promise<void> {
const times = options.times ?? 3;
const delayMs = options.delayMs ?? 2000;
const js = `
async () => {
const maxTimes = ${times};
const maxWaitMs = ${delayMs};
for (let i = 0; i < maxTimes; i++) {
const lastHeight = document.body.scrollHeight;
window.scrollTo(0, lastHeight);
await new Promise(resolve => {
let timeoutId;
const observer = new MutationObserver(() => {
if (document.body.scrollHeight > lastHeight) {
clearTimeout(timeoutId);
observer.disconnect();
setTimeout(resolve, 100); // Small debounce for rendering
}
});
observer.observe(document.body, { childList: true, subtree: true });
timeoutId = setTimeout(() => {
observer.disconnect();
resolve(null);
}, maxWaitMs);
});
}
}
`;
await this.evaluate(js);
}
async installInterceptor(pattern: string): Promise<void> {
await this.evaluate(generateInterceptorJs(JSON.stringify(pattern), {
arrayName: '__opencli_xhr',
patchGuard: '__opencli_interceptor_patched',
}));
}
async getInterceptedRequests(): Promise<any[]> {
const result = await this.evaluate(generateReadInterceptedJs('__opencli_xhr'));
return result || [];
}
}
+76
View File
@@ -0,0 +1,76 @@
/**
* Browser tab management helpers: extract, diff, and cleanup tab state.
*/
export function extractTabEntries(raw: unknown): Array<{ index: number; identity: string }> {
if (Array.isArray(raw)) {
return raw.map((tab: Record<string, unknown>, index: number) => ({
index,
identity: [
tab?.id ?? '',
tab?.url ?? '',
tab?.title ?? '',
tab?.name ?? '',
].join('|'),
}));
}
if (typeof raw === 'string') {
return raw
.split('\n')
.map(line => line.trim())
.filter(Boolean)
.map(line => {
// Match actual Playwright MCP format: "- 0: (current) [title](url)" or "- 1: [title](url)"
const mcpMatch = line.match(/^-\s+(\d+):\s*(.*)$/);
if (mcpMatch) {
return {
index: parseInt(mcpMatch[1], 10),
identity: mcpMatch[2].trim() || `tab-${mcpMatch[1]}`,
};
}
// Legacy format: "Tab 0 ..."
const legacyMatch = line.match(/Tab\s+(\d+)\s*(.*)$/);
if (legacyMatch) {
return {
index: parseInt(legacyMatch[1], 10),
identity: legacyMatch[2].trim() || `tab-${legacyMatch[1]}`,
};
}
return null;
})
.filter((entry): entry is { index: number; identity: string } => entry !== null);
}
return [];
}
export function extractTabIdentities(raw: unknown): string[] {
return extractTabEntries(raw).map(tab => tab.identity);
}
export function diffTabIndexes(initialIdentities: string[], currentTabs: Array<{ index: number; identity: string }>): number[] {
if (initialIdentities.length === 0 || currentTabs.length === 0) return [];
const remaining = new Map<string, number>();
for (const identity of initialIdentities) {
remaining.set(identity, (remaining.get(identity) ?? 0) + 1);
}
const tabsToClose: number[] = [];
for (const tab of currentTabs) {
const count = remaining.get(tab.identity) ?? 0;
if (count > 0) {
remaining.set(tab.identity, count - 1);
continue;
}
tabsToClose.push(tab.index);
}
return tabsToClose.sort((a, b) => b - a);
}
export function appendLimited(current: string, chunk: string, limit: number): string {
const next = current + chunk;
if (next.length <= limit) return next;
return next.slice(-limit);
}
+3
View File
@@ -30,6 +30,7 @@ interface ManifestEntry {
type?: string;
default?: any;
required?: boolean;
positional?: boolean;
help?: string;
choices?: string[];
}>;
@@ -140,6 +141,7 @@ function scanTs(filePath: string, site: string): ManifestEntry {
const defaultMatch = body.match(/default\s*:\s*([^,}]+)/);
const requiredMatch = body.match(/required\s*:\s*(true|false)/);
const helpMatch = body.match(/help\s*:\s*['"`]([^'"`]*)['"`]/);
const positionalMatch = body.match(/positional\s*:\s*(true|false)/);
let defaultVal: any = undefined;
if (defaultMatch) {
@@ -156,6 +158,7 @@ function scanTs(filePath: string, site: string): ManifestEntry {
type: typeMatch?.[1] ?? 'str',
default: defaultVal,
required: requiredMatch?.[1] === 'true',
positional: positionalMatch?.[1] === 'true' || undefined,
help: helpMatch?.[1] ?? '',
});
}
+47 -75
View File
@@ -37,6 +37,49 @@ interface CascadeResult {
confidence: number;
}
/**
* Build the JavaScript source for a fetch probe.
* Shared logic for PUBLIC, COOKIE, and HEADER strategies.
*/
function buildFetchProbeJs(url: string, opts: {
credentials?: boolean;
extractCsrf?: boolean;
}): string {
const credentialsLine = opts.credentials ? `credentials: 'include',` : '';
const headerSetup = opts.extractCsrf
? `
const cookies = document.cookie.split(';').map(c => c.trim());
const csrf = cookies.find(c => c.startsWith('ct0=') || c.startsWith('csrf_token=') || c.startsWith('_csrf='))?.split('=').slice(1).join('=');
const headers = {};
if (csrf) { headers['X-Csrf-Token'] = csrf; headers['X-XSRF-Token'] = csrf; }
`
: 'const headers = {};';
return `
async () => {
try {
${headerSetup}
const resp = await fetch(${JSON.stringify(url)}, {
${credentialsLine}
headers
});
const status = resp.status;
if (!resp.ok) return { status, ok: false };
const text = await resp.text();
let hasData = false;
try {
const json = JSON.parse(text);
hasData = !!json && (Array.isArray(json) ? json.length > 0 :
typeof json === 'object' && Object.keys(json).length > 0);
// Check for API-level error codes (common in Chinese sites)
if (json.code !== undefined && json.code !== 0) hasData = false;
} catch {}
return { status, ok: true, hasData, preview: text.slice(0, 200) };
} catch (e) { return { ok: false, error: e.message }; }
}
`;
}
/**
* Probe an endpoint with a specific strategy.
* Returns whether the probe succeeded and basic response info.
@@ -45,32 +88,14 @@ export async function probeEndpoint(
page: IPage,
url: string,
strategy: Strategy,
opts: { timeout?: number } = {},
_opts: { timeout?: number } = {},
): Promise<ProbeResult> {
const result: ProbeResult = { strategy, success: false };
try {
switch (strategy) {
case Strategy.PUBLIC: {
// Try direct fetch without browser (no credentials)
const js = `
async () => {
try {
const resp = await fetch(${JSON.stringify(url)});
const status = resp.status;
if (!resp.ok) return { status, ok: false };
const text = await resp.text();
let hasData = false;
try {
const json = JSON.parse(text);
hasData = !!json && (Array.isArray(json) ? json.length > 0 :
typeof json === 'object' && Object.keys(json).length > 0);
} catch {}
return { status, ok: true, hasData, preview: text.slice(0, 200) };
} catch (e) { return { ok: false, error: e.message }; }
}
`;
const resp = await page.evaluate(js);
const resp = await page.evaluate(buildFetchProbeJs(url, {}));
result.statusCode = resp?.status;
result.success = resp?.ok && resp?.hasData;
result.hasData = resp?.hasData;
@@ -79,27 +104,7 @@ export async function probeEndpoint(
}
case Strategy.COOKIE: {
// Fetch with credentials: 'include' (uses browser cookies)
const js = `
async () => {
try {
const resp = await fetch(${JSON.stringify(url)}, { credentials: 'include' });
const status = resp.status;
if (!resp.ok) return { status, ok: false };
const text = await resp.text();
let hasData = false;
try {
const json = JSON.parse(text);
hasData = !!json && (Array.isArray(json) ? json.length > 0 :
typeof json === 'object' && Object.keys(json).length > 0);
// Check for API-level error codes (common in Chinese sites)
if (json.code !== undefined && json.code !== 0) hasData = false;
} catch {}
return { status, ok: true, hasData, preview: text.slice(0, 200) };
} catch (e) { return { ok: false, error: e.message }; }
}
`;
const resp = await page.evaluate(js);
const resp = await page.evaluate(buildFetchProbeJs(url, { credentials: true }));
result.statusCode = resp?.status;
result.success = resp?.ok && resp?.hasData;
result.hasData = resp?.hasData;
@@ -108,39 +113,7 @@ export async function probeEndpoint(
}
case Strategy.HEADER: {
// Fetch with credentials + try to extract common auth headers
const js = `
async () => {
try {
// Try to extract CSRF tokens from cookies
const cookies = document.cookie.split(';').map(c => c.trim());
const csrf = cookies.find(c => c.startsWith('ct0=') || c.startsWith('csrf_token=') || c.startsWith('_csrf='))?.split('=').slice(1).join('=');
const headers = {};
if (csrf) {
headers['X-Csrf-Token'] = csrf;
headers['X-XSRF-Token'] = csrf;
}
const resp = await fetch(${JSON.stringify(url)}, {
credentials: 'include',
headers
});
const status = resp.status;
if (!resp.ok) return { status, ok: false };
const text = await resp.text();
let hasData = false;
try {
const json = JSON.parse(text);
hasData = !!json && (Array.isArray(json) ? json.length > 0 :
typeof json === 'object' && Object.keys(json).length > 0);
if (json.code !== undefined && json.code !== 0) hasData = false;
} catch {}
return { status, ok: true, hasData, preview: text.slice(0, 200) };
} catch (e) { return { ok: false, error: e.message }; }
}
`;
const resp = await page.evaluate(js);
const resp = await page.evaluate(buildFetchProbeJs(url, { credentials: true, extractCsrf: true }));
result.statusCode = resp?.status;
result.success = resp?.ok && resp?.hasData;
result.hasData = resp?.hasData;
@@ -151,7 +124,6 @@ export async function probeEndpoint(
case Strategy.INTERCEPT:
case Strategy.UI:
// These require specific implementation per-site
// Mark as needing manual implementation
result.success = false;
result.error = `Strategy ${strategy} requires site-specific implementation`;
break;
+115
View File
@@ -0,0 +1,115 @@
/**
* BOSS直聘 job detail — fetch full job posting details via browser cookie API.
*
* Uses securityId from search results to call the detail API.
* Returns: job description, skills, welfare, boss info, company info, address.
*/
import { cli, Strategy } from '../../registry.js';
import type { IPage } from '../../types.js';
cli({
site: 'boss',
name: 'detail',
description: 'BOSS直聘查看职位详情',
domain: 'www.zhipin.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'security_id', required: true, help: 'Security ID from search results (securityId field)' },
],
columns: [
'name', 'salary', 'experience', 'degree', 'city', 'district',
'description', 'skills', 'welfare',
'boss_name', 'boss_title', 'active_time',
'company', 'industry', 'scale', 'stage',
'address', 'url',
],
func: async (page: IPage | null, kwargs) => {
if (!page) throw new Error('Browser page required');
const securityId = kwargs.security_id;
// Navigate to zhipin.com first to establish cookie context (referrer + cookies)
await page.goto('https://www.zhipin.com/web/geek/job');
await page.wait({ time: 1 });
const targetUrl = `https://www.zhipin.com/wapi/zpgeek/job/detail.json?securityId=${encodeURIComponent(securityId)}`;
if (process.env.OPENCLI_VERBOSE || process.env.DEBUG?.includes('opencli')) {
console.error(`[opencli:boss] Fetching job detail...`);
}
const evaluateScript = `
async () => {
return new Promise((resolve, reject) => {
const xhr = new window.XMLHttpRequest();
xhr.open('GET', ${JSON.stringify(targetUrl)}, true);
xhr.withCredentials = true;
xhr.timeout = 15000;
xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
try {
resolve(JSON.parse(xhr.responseText));
} catch (e) {
reject(new Error('Failed to parse JSON. Raw (200 chars): ' + xhr.responseText.substring(0, 200)));
}
} else {
reject(new Error('XHR HTTP Status: ' + xhr.status));
}
};
xhr.onerror = () => reject(new Error('XHR Network Error'));
xhr.ontimeout = () => reject(new Error('XHR Timeout'));
xhr.send();
});
}
`;
let data: any;
try {
data = await page.evaluate(evaluateScript);
} catch (e: any) {
throw new Error('API evaluate failed: ' + e.message);
}
if (data.code !== 0) {
if (data.code === 37) {
throw new Error('Cookie 已过期!请在当前 Chrome 浏览器中重新登录 BOSS 直聘。');
}
throw new Error(`BOSS API error: ${data.message || 'Unknown'} (code=${data.code})`);
}
const zpData = data.zpData || {};
const jobInfo = zpData.jobInfo || {};
const bossInfo = zpData.bossInfo || {};
const brandComInfo = zpData.brandComInfo || {};
if (!jobInfo.jobName) {
throw new Error('该职位信息不存在或已下架');
}
return [{
name: jobInfo.jobName || '',
salary: jobInfo.salaryDesc || '',
experience: jobInfo.experienceName || '',
degree: jobInfo.degreeName || '',
city: jobInfo.locationName || '',
district: [jobInfo.areaDistrict, jobInfo.businessDistrict].filter(Boolean).join('·'),
description: jobInfo.postDescription || '',
skills: (jobInfo.showSkills || []).join(', '),
welfare: (brandComInfo.labels || []).join(', '),
boss_name: bossInfo.name || '',
boss_title: bossInfo.title || '',
active_time: bossInfo.activeTimeDesc || '',
company: brandComInfo.brandName || bossInfo.brandName || '',
industry: brandComInfo.industryName || '',
scale: brandComInfo.scaleName || '',
stage: brandComInfo.stageName || '',
address: jobInfo.address || '',
url: jobInfo.encryptId
? 'https://www.zhipin.com/job_detail/' + jobInfo.encryptId + '.html'
: '',
}];
},
});
+3 -2
View File
@@ -69,7 +69,7 @@ cli({
description: 'BOSS直聘搜索职位',
domain: 'www.zhipin.com',
strategy: Strategy.COOKIE,
forceExtension: true, // BOSS Zhipin detects CDP mode — must use extension bridge
browser: true,
args: [
{ name: 'query', required: true, help: 'Search keyword (e.g. AI agent, 前端)' },
@@ -81,7 +81,7 @@ cli({
{ name: 'page', type: 'int', default: 1, help: 'Page number' },
{ name: 'limit', type: 'int', default: 15, help: 'Number of results' },
],
columns: ['name', 'salary', 'company', 'area', 'experience', 'degree', 'skills', 'boss', 'url'],
columns: ['name', 'salary', 'company', 'area', 'experience', 'degree', 'skills', 'boss', 'security_id', 'url'],
func: async (page: IPage | null, kwargs) => {
if (!page) throw new Error('Browser page required');
@@ -191,6 +191,7 @@ cli({
degree: j.jobDegree,
skills: (j.skills || []).join(','),
boss: j.bossName + ' · ' + j.bossTitle,
security_id: j.securityId || '',
url: 'https://www.zhipin.com/job_detail/' + j.encryptJobId + '.html',
});
addedInBatch++;
+149
View File
@@ -0,0 +1,149 @@
import { cli, Strategy } from '../../registry.js';
import { canonicalizeProductUrl, normalizeProductId } from '../../coupang.js';
function escapeJsString(value: string): string {
return JSON.stringify(value);
}
function buildAddToCartEvaluate(expectedProductId: string): string {
return `
(async () => {
const expectedProductId = ${escapeJsString(expectedProductId)};
const text = document.body.innerText || '';
const loginHints = {
hasLoginLink: Boolean(document.querySelector('a[href*="login"], a[title*="로그인"]')),
hasMyCoupang: /마이쿠팡/.test(text),
};
const pathMatch = location.pathname.match(/\\/vp\\/products\\/(\\d+)/);
const currentProductId = pathMatch?.[1] || '';
if (expectedProductId && currentProductId && expectedProductId !== currentProductId) {
return { ok: false, reason: 'PRODUCT_MISMATCH', currentProductId, loginHints };
}
const optionSelectors = [
'select',
'[role="listbox"]',
'.prod-option, .product-option, .option-select, .option-dropdown',
];
const hasRequiredOption = optionSelectors.some((selector) => {
try {
const nodes = Array.from(document.querySelectorAll(selector));
return nodes.some((node) => {
const label = (node.textContent || '') + ' ' + (node.getAttribute?.('aria-label') || '');
return /옵션|색상|사이즈|용량|선택/i.test(label);
});
} catch {
return false;
}
});
if (hasRequiredOption) {
return { ok: false, reason: 'OPTION_REQUIRED', currentProductId, loginHints };
}
const clickCandidate = (elements) => {
for (const element of elements) {
if (!(element instanceof HTMLElement)) continue;
const label = ((element.innerText || '') + ' ' + (element.getAttribute('aria-label') || '')).trim();
if (/장바구니|카트|cart/i.test(label) && !/sold out|품절/i.test(label)) {
element.click();
return true;
}
}
return false;
};
const beforeCount = (() => {
const node = document.querySelector('[class*="cart"] .count, #headerCartCount, .cart-count');
const text = node?.textContent || '';
const num = Number(text.replace(/[^\\d]/g, ''));
return Number.isFinite(num) ? num : null;
})();
const buttons = Array.from(document.querySelectorAll('button, a[role="button"], input[type="button"]'));
const clicked = clickCandidate(buttons);
if (!clicked) {
return { ok: false, reason: 'ADD_TO_CART_BUTTON_NOT_FOUND', currentProductId, loginHints };
}
await new Promise((resolve) => setTimeout(resolve, 2500));
const afterText = document.body.innerText || '';
const successMessage = /장바구니에 담|장바구니 담기 완료|added to cart/i.test(afterText);
const afterCount = (() => {
const node = document.querySelector('[class*="cart"] .count, #headerCartCount, .cart-count');
const text = node?.textContent || '';
const num = Number(text.replace(/[^\\d]/g, ''));
return Number.isFinite(num) ? num : null;
})();
const countIncreased =
beforeCount != null &&
afterCount != null &&
afterCount >= beforeCount &&
(afterCount > beforeCount || beforeCount === 0);
return {
ok: successMessage || countIncreased,
reason: successMessage || countIncreased ? 'SUCCESS' : 'UNKNOWN',
currentProductId,
beforeCount,
afterCount,
loginHints,
};
})()
`;
}
cli({
site: 'coupang',
name: 'add-to-cart',
description: 'Add a Coupang product to cart using logged-in browser session',
domain: 'www.coupang.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'productId', required: false, help: 'Coupang product ID' },
{ name: 'url', required: false, help: 'Canonical product URL' },
],
columns: ['ok', 'product_id', 'url', 'message'],
func: async (page, kwargs) => {
const rawProductId = kwargs.productId ?? kwargs.product_id;
const productId = normalizeProductId(rawProductId);
const targetUrl = canonicalizeProductUrl(kwargs.url, productId);
if (!productId && !targetUrl) {
throw new Error('Either --product-id or --url is required');
}
const finalUrl = targetUrl || canonicalizeProductUrl('', productId);
await page.goto(finalUrl);
await page.wait(3);
const result = await page.evaluate(buildAddToCartEvaluate(productId));
const loginHints = result?.loginHints ?? {};
if (loginHints.hasLoginLink && !loginHints.hasMyCoupang) {
throw new Error('Coupang login required. Please log into Coupang in Chrome and retry.');
}
const actualProductId = normalizeProductId(result?.currentProductId || productId);
if (result?.reason === 'PRODUCT_MISMATCH') {
throw new Error(`Product mismatch: expected ${productId}, got ${actualProductId || 'unknown'}`);
}
if (result?.reason === 'OPTION_REQUIRED') {
throw new Error('This product requires option selection and is not supported in v1.');
}
if (result?.reason === 'ADD_TO_CART_BUTTON_NOT_FOUND') {
throw new Error('Could not find an add-to-cart button on the product page.');
}
if (!result?.ok) {
throw new Error('Failed to confirm add-to-cart success.');
}
return [{
ok: true,
product_id: actualProductId || productId,
url: finalUrl,
message: 'Added to cart',
}];
},
});
+466
View File
@@ -0,0 +1,466 @@
import { cli, Strategy } from '../../registry.js';
import { mergeSearchItems, normalizeSearchItem, sanitizeSearchItems } from '../../coupang.js';
function escapeJsString(value: string): string {
return JSON.stringify(value);
}
function buildApplyFilterEvaluate(filter: string): string {
return `
() => {
const filter = ${escapeJsString(filter)};
const labels = Array.from(document.querySelectorAll('label'));
const normalize = (value) => (value == null ? '' : String(value).trim().toLowerCase());
const target = labels.find((label) => {
const component = normalize(label.getAttribute('data-component-name'));
const imgAlt = normalize(label.querySelector('img')?.getAttribute('alt'));
const text = normalize(label.textContent);
if (filter === 'rocket') {
return (
component.includes('deliveryfilteroption-rocket_luxury,rocket_wow,coupang_global') ||
imgAlt.includes('rocket_luxury,rocket_wow,coupang_global') ||
imgAlt.includes('rocket-all') ||
text.includes('로켓')
);
}
return component.includes(filter) || imgAlt.includes(filter) || text.includes(filter);
});
if (!target) {
return { ok: false, reason: 'FILTER_NOT_FOUND' };
}
target.click();
return {
ok: true,
reason: 'FILTER_CLICKED',
component: target.getAttribute('data-component-name') || '',
text: (target.textContent || '').trim(),
alt: target.querySelector('img')?.getAttribute('alt') || '',
};
}
`;
}
function buildCurrentLocationEvaluate(): string {
return `
() => ({
href: location.href
})
`;
}
function buildSearchEvaluate(query: string, limit: number, pageNumber: number): string {
return `
(async () => {
const query = ${escapeJsString(query)};
const limit = ${limit};
const pageNumber = ${pageNumber};
const normalizeText = (value) => (value == null ? '' : String(value).trim());
const parseNum = (value) => {
const text = normalizeText(value).replace(/[^\\d.]/g, '');
if (!text) return null;
const num = Number(text);
return Number.isFinite(num) ? num : null;
};
const extractPriceFromText = (text) => {
const matches = normalizeText(text).match(/\\d{1,3}(?:,\\d{3})*원/g) || [];
if (!matches.length) return '';
if (matches.length >= 2) return matches[matches.length - 2];
return matches[0];
};
const extractPriceInfo = (root) => {
const priceArea =
root.querySelector('.PriceArea_priceArea__NntJz, [class*="PriceArea_priceArea"], [class*="priceArea"]') ||
root;
const priceAreaText = normalizeText(priceArea.textContent || '');
const originalPrice = normalizeText(
priceArea.querySelector(
'del, .base-price, .origin-price, .original-price, .strike-price, [class*="base-price"], [class*="origin-price"], [class*="line-through"]'
)?.textContent || ''
);
const originalPriceNum = parseNum(originalPrice);
const unitPrice =
normalizeText(
priceArea.querySelector('.unit-price, [class*="unit-price"], [class*="unitPrice"]')?.textContent || ''
) ||
priceAreaText.match(/\\([^)]*당\\s*[^)]*원[^)]*\\)/)?.[0] ||
'';
const candidates = Array.from(priceArea.querySelectorAll('span, strong, div'))
.map((node) => {
const text = normalizeText(node.textContent || '');
if (!text || !/\\d/.test(text)) return null;
if (/\\d{1,2}:\\d{2}:\\d{2}/.test(text)) return null;
if (/당\\s*\\d/.test(text)) return null;
if (/^\\d+%$/.test(text)) return null;
const num = parseNum(text);
if (num == null) return null;
const className = normalizeText(node.getAttribute('class') || '').toLowerCase();
let score = 0;
if (/price|sale|selling|final/.test(className)) score += 6;
if (/red/.test(className)) score += 5;
if (/font-bold|bold/.test(className)) score += 3;
if (/line-through/.test(className)) score -= 12;
if (text.includes('원')) score += 2;
if (originalPriceNum != null && num === originalPriceNum) score -= 10;
if (num < 100) score -= 10;
return { text, num, score };
})
.filter(Boolean)
.sort((a, b) => {
if (b.score !== a.score) return b.score - a.score;
if (originalPriceNum != null) {
const aPrefer = a.num !== originalPriceNum ? 1 : 0;
const bPrefer = b.num !== originalPriceNum ? 1 : 0;
if (bPrefer !== aPrefer) return bPrefer - aPrefer;
}
return b.num - a.num;
});
const currentPrice =
normalizeText(candidates.find((candidate) => candidate.num !== originalPriceNum)?.text || '') ||
normalizeText(candidates[0]?.text || '') ||
extractPriceFromText(priceAreaText) ||
'';
return {
price: currentPrice,
originalPrice,
unitPrice,
};
};
const canonicalUrl = (url, productId) => {
if (url) {
try {
const parsed = new URL(url, 'https://www.coupang.com');
const match = parsed.pathname.match(/\\/vp\\/products\\/(\\d+)/);
return 'https://www.coupang.com/vp/products/' + (match?.[1] || productId || '');
} catch {}
}
return productId ? 'https://www.coupang.com/vp/products/' + productId : '';
};
const normalize = (raw) => {
const rawText = normalizeText(raw.text || raw.badgeText || raw.deliveryText || raw.summary);
const productId = normalizeText(
raw.productId || raw.product_id || raw.id || raw.productNo ||
raw?.product?.productId || raw?.item?.id
).match(/(\\d{6,})/)?.[1] || '';
const title = normalizeText(
raw.title || raw.name || raw.productName || raw.productTitle || raw.itemName
);
const price = parseNum(raw.price || raw.salePrice || raw.finalPrice || raw.sellingPrice);
const originalPrice = parseNum(raw.originalPrice || raw.basePrice || raw.listPrice || raw.originPrice);
const unitPrice = normalizeText(raw.unitPrice || raw.unit_price || raw.unitPriceText);
const rating = parseNum(raw.rating || raw.star || raw.reviewRating);
const reviewCount = parseNum(raw.reviewCount || raw.ratingCount || raw.reviewCnt || raw.reviews);
const badge = Array.isArray(raw.badges) ? raw.badges.map(normalizeText).filter(Boolean).join(', ') : normalizeText(raw.badge || raw.labels);
const seller = normalizeText(raw.seller || raw.sellerName || raw.vendorName || raw.merchantName);
const category = normalizeText(raw.category || raw.categoryName || raw.categoryPath);
const discountRate = parseNum(raw.discountRate || raw.discount || raw.discountPercent);
const url = canonicalUrl(raw.url || raw.productUrl || raw.link, productId);
return {
productId,
title,
price,
originalPrice,
unitPrice,
discountRate,
rating,
reviewCount,
rocket: normalizeText(raw.rocket || raw.rocketType),
deliveryType: normalizeText(raw.deliveryType || raw.deliveryBadge || raw.shippingType || raw.shippingBadge),
deliveryPromise: normalizeText(raw.deliveryPromise || raw.promise || raw.arrivalText || raw.arrivalBadge),
seller,
badge,
category,
url,
};
};
const byApi = async () => {
const candidates = [
'/np/search?q=' + encodeURIComponent(query) + '&component=&channel=user&page=' + pageNumber,
'/np/search?component=&q=' + encodeURIComponent(query) + '&channel=user&page=' + pageNumber,
];
for (const path of candidates) {
try {
const resp = await fetch(path, { credentials: 'include' });
if (!resp.ok) continue;
const text = await resp.text();
const data = text.trim().startsWith('<') ? null : JSON.parse(text);
const maybeItems =
data?.data?.products ||
data?.data?.productList ||
data?.products ||
data?.productList ||
data?.items;
if (Array.isArray(maybeItems) && maybeItems.length) {
return maybeItems.slice(0, limit).map(normalize);
}
} catch {}
}
return [];
};
const byBootstrap = () => {
const isProductLike = (item) => {
if (!item || typeof item !== 'object') return false;
const values = [item.productId, item.product_id, item.id, item.productNo, item.url, item.productUrl, item.link, item.title, item.productName];
return values.some((value) => /\\/vp\\/products\\/|\\d{6,}/.test(normalizeText(value)));
};
const collectProducts = (node) => {
const queue = [node];
while (queue.length) {
const current = queue.shift();
if (!current || typeof current !== 'object') continue;
if (Array.isArray(current)) {
const productish = current.filter(isProductLike);
if (productish.length >= 3) return productish.slice(0, limit).map(normalize);
queue.push(...current.slice(0, 50));
continue;
}
for (const value of Object.values(current)) queue.push(value);
}
return [];
};
const scriptNodes = Array.from(document.scripts);
for (const script of scriptNodes) {
const text = script.textContent || '';
if (!text || !/product|search/i.test(text)) continue;
const arrayMatches = [
...text.matchAll(/"products?"\\s*:\\s*(\\[[\\s\\S]{100,}?\\])/g),
...text.matchAll(/"itemList"\\s*:\\s*(\\[[\\s\\S]{100,}?\\])/g),
];
for (const match of arrayMatches) {
try {
const products = JSON.parse(match[1]);
if (Array.isArray(products) && products.length) {
return products.slice(0, limit).map(normalize);
}
} catch {}
}
}
const globals = [
window.__NEXT_DATA__,
window.__APOLLO_STATE__,
window.__INITIAL_STATE__,
window.__STATE__,
window.__PRELOADED_STATE__,
];
for (const candidate of globals) {
if (!candidate || typeof candidate !== 'object') continue;
const found = collectProducts(candidate);
if (found.length) return found;
}
return [];
};
const byJsonLd = () => {
const scripts = Array.from(document.querySelectorAll('script[type="application/ld+json"]'));
for (const script of scripts) {
const text = script.textContent || '';
if (!text) continue;
try {
const payload = JSON.parse(text);
const docs = Array.isArray(payload) ? payload : [payload];
for (const doc of docs) {
const items =
doc?.itemListElement ||
doc?.about?.itemListElement ||
doc?.mainEntity?.itemListElement ||
[];
if (!Array.isArray(items) || !items.length) continue;
const mapped = items.map((entry) => {
const item = entry?.item || entry;
return normalize({
productId: item?.url || item?.sku || item?.productID,
title: item?.name,
price: item?.offers?.price,
originalPrice: item?.offers?.highPrice,
rating: item?.aggregateRating?.ratingValue,
reviewCount: item?.aggregateRating?.reviewCount,
seller: item?.offers?.seller?.name,
badge: item?.offers?.availability,
category: item?.category,
url: item?.url,
});
}).filter((item) => item.productId || item.url || item.title);
if (mapped.length) return mapped.slice(0, limit);
}
} catch {}
}
return [];
};
const byDom = () => {
const domScanLimit = Math.max(limit * 6, 60);
const cards = Array.from(new Set([
...document.querySelectorAll('li.search-product'),
...document.querySelectorAll('li[class*="search-product"], div[class*="search-product"], article[class*="search-product"]'),
...document.querySelectorAll('li[class*="ProductUnit_productUnit"], [class*="ProductUnit_productUnit"]'),
...document.querySelectorAll('.impression-logged, [class*="promotion-item"], [class*="product-item"]'),
...document.querySelectorAll('[data-product-id]'),
...document.querySelectorAll('[data-id]'),
...document.querySelectorAll('a[href*="/vp/products/"]'),
])).slice(0, domScanLimit);
const items = [];
for (const el of cards) {
const root = el.closest('li, div, article, section') || el;
const html = root.innerHTML || '';
const priceInfo = extractPriceInfo(root);
const badgeImages = Array.from(root.querySelectorAll('img[data-badge-id]'));
const badgeIds = badgeImages
.map((node) => node.getAttribute('data-badge-id') || '')
.filter(Boolean);
const badgeSrcText = badgeImages
.map((node) => (node.getAttribute('data-badge-id') || '') + ' ' + (node.getAttribute('src') || ''))
.join(' ');
const productId =
root.getAttribute('data-product-id') ||
el.getAttribute('data-product-id') ||
root.querySelector('a[href*="/vp/products/"]')?.getAttribute('data-product-id') ||
root.querySelector('a[href*="/vp/products/"]')?.getAttribute('href')?.match(/\\/vp\\/products\\/(\\d+)/)?.[1] ||
html.match(/\\/vp\\/products\\/(\\d+)/)?.[1] ||
(el.getAttribute('href') || '').match(/\\/vp\\/products\\/(\\d+)/)?.[1] ||
'';
const title =
root.querySelector('.name, .title, .product-name, .search-product-title, .item-title, .ProductUnit_productNameV2__cV9cw, [class*="ProductUnit_productName"], [class*="productName"], [class*="product-name"], [class*="title"]')?.textContent ||
root.querySelector('img[alt]')?.getAttribute('alt') ||
html.match(/alt="([^"]+)"/)?.[1] ||
(root.textContent || '').replace(/\\s+/g, ' ').trim().match(/^(.+?)(\\d{1,3},\\d{3}원|무료배송|내일\\(|오늘\\(|새벽)/)?.[1] ||
el.getAttribute('title') ||
'';
const price = priceInfo.price || '';
const originalPrice = priceInfo.originalPrice || '';
const unitPrice = priceInfo.unitPrice || '';
const rating =
root.querySelector('.rating, .star em, [class*="rating"], [class*="star"], [class*="ProductRating"] [aria-label], [aria-label][class*="ProductRating"]')?.getAttribute?.('aria-label') ||
root.querySelector('.rating, .star em, [class*="rating"], [class*="star"], [class*="ProductRating"]')?.textContent ||
'';
const reviewCount =
root.querySelector('.rating-total-count, .count, .review-count, .promotion-item-review-count, [class*="review"], [class*="count"], [class*="ProductRating"] span, [class*="ProductRating"] [class*="fw-text"]')?.textContent ||
'';
const seller =
root.querySelector('.seller, .vendor, .search-product-wrap .vendor-name, [class*="vendor"], [class*="seller"]')?.textContent ||
'';
const category =
root.getAttribute('data-category') ||
root.querySelector('[class*="category"]')?.textContent ||
'';
const text = (root.textContent || '').replace(/\\s+/g, ' ').trim();
const badgeNodes = Array.from(root.querySelectorAll('.badge, .delivery, .tag, .icon-service, .pdd-text, .delivery-text, [class*="badge"], [class*="delivery"]'));
const hrefNode = root.querySelector('a[href*="/vp/products/"]');
items.push(normalize({
productId,
title,
price,
originalPrice,
unitPrice,
rating,
reviewCount,
seller,
badges: [...badgeIds, ...badgeNodes.map((node) => node.textContent || '').filter(Boolean)],
rocket: badgeSrcText + ' ' + badgeNodes.map((node) => node.textContent || '').join(' '),
deliveryType: badgeNodes.map((node) => node.textContent || '').join(' ') + ' ' + text,
deliveryPromise: badgeNodes.map((node) => node.textContent || '').join(' ') + ' ' + text,
category,
text,
url: hrefNode?.getAttribute('href') || '',
}));
}
return items.slice(0, domScanLimit);
};
let items = await byApi();
if (!items.length) items = byJsonLd();
if (!items.length) items = byBootstrap();
const domItems = byDom();
if (!items.length) items = domItems;
return {
loginHints: {
hasLoginLink: Boolean(document.querySelector('a[href*="login"], a[title*="로그인"]')),
hasMyCoupang: /마이쿠팡/.test(document.body.innerText),
},
items,
domItems,
};
})()
`;
}
cli({
site: 'coupang',
name: 'search',
description: 'Search Coupang products with logged-in browser session',
domain: 'www.coupang.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'query', required: true, help: 'Search keyword' },
{ name: 'page', type: 'int', default: 1, help: 'Search result page number' },
{ name: 'limit', type: 'int', default: 20, help: 'Max results (max 50)' },
{ name: 'filter', required: false, help: 'Optional search filter (currently supports: rocket)' },
],
columns: ['rank', 'title', 'price', 'unit_price', 'rating', 'review_count', 'rocket', 'delivery_type', 'delivery_promise', 'url'],
func: async (page, kwargs) => {
const query = String(kwargs.query || '').trim();
const pageNumber = Math.max(Number(kwargs.page || 1), 1);
const limit = Math.min(Math.max(Number(kwargs.limit || 20), 1), 50);
const filter = String(kwargs.filter || '').trim().toLowerCase();
if (!query) throw new Error('Query is required');
const initialPage = filter ? 1 : pageNumber;
const url = `https://www.coupang.com/np/search?q=${encodeURIComponent(query)}&channel=user&page=${initialPage}`;
await page.goto(url);
await page.wait(3);
if (filter) {
const filterResult = await page.evaluate(buildApplyFilterEvaluate(filter));
if (!filterResult?.ok) {
throw new Error(`Unsupported or unavailable filter: ${filter}`);
}
await page.wait(3);
if (pageNumber > 1) {
const locationInfo = await page.evaluate(buildCurrentLocationEvaluate());
const filteredUrl = new URL(locationInfo?.href || url);
filteredUrl.searchParams.set('page', String(pageNumber));
await page.goto(filteredUrl.toString());
await page.wait(3);
}
}
await page.autoScroll({ times: filter ? 3 : 2, delayMs: 1500 });
const raw = await page.evaluate(buildSearchEvaluate(query, limit, pageNumber));
const loginHints = raw?.loginHints ?? {};
const items = Array.isArray(raw?.items) ? raw.items : [];
const domItems = Array.isArray(raw?.domItems) ? raw.domItems : [];
const normalizedBase = sanitizeSearchItems(
items.map((item: Record<string, unknown>, index: number) => normalizeSearchItem(item, index)),
limit
);
const normalizedDom = sanitizeSearchItems(
domItems.map((item: Record<string, unknown>, index: number) => normalizeSearchItem(item, index)),
Math.max(limit * 6, 60)
);
const normalized = filter
? sanitizeSearchItems(normalizedDom, limit)
: mergeSearchItems(normalizedBase, normalizedDom, limit);
if (!normalized.length && loginHints.hasLoginLink && !loginHints.hasMyCoupang) {
throw new Error('Coupang login required. Please log into Coupang in Chrome and retry.');
}
return normalized;
},
});
+416
View File
@@ -0,0 +1,416 @@
import { cli, Strategy } from '../../registry.js';
import type { IPage } from '../../types.js';
// ── Filter value mappings ──────────────────────────────────────────────
const EXPERIENCE_LEVELS: Record<string, string> = {
internship: '1',
entry: '2',
'entry-level': '2',
associate: '3',
mid: '4',
senior: '4',
'mid-senior': '4',
'mid-senior-level': '4',
director: '5',
executive: '6',
};
const JOB_TYPES: Record<string, string> = {
'full-time': 'F',
fulltime: 'F',
full: 'F',
'part-time': 'P',
parttime: 'P',
part: 'P',
contract: 'C',
temporary: 'T',
temp: 'T',
volunteer: 'V',
internship: 'I',
other: 'O',
};
const DATE_POSTED: Record<string, string> = {
any: 'on',
month: 'r2592000',
'past-month': 'r2592000',
week: 'r604800',
'past-week': 'r604800',
day: 'r86400',
'24h': 'r86400',
'past-24h': 'r86400',
};
const REMOTE_TYPES: Record<string, string> = {
onsite: '1',
'on-site': '1',
hybrid: '3',
remote: '2',
};
// ── Helpers ────────────────────────────────────────────────────────────
function parseCsvArg(value: unknown): string[] {
if (value === undefined || value === null || value === '') return [];
return String(value)
.split(',')
.map(item => item.trim())
.filter(Boolean);
}
function mapFilterValues(input: unknown, mapping: Record<string, string>, label: string): string[] {
const values = parseCsvArg(input);
const resolved = values.map(value => {
const key = value.toLowerCase();
const mapped = mapping[key];
if (!mapped) throw new Error(`Unsupported ${label}: ${value}`);
return mapped;
});
return [...new Set(resolved)];
}
function normalizeWhitespace(value: unknown): string {
return String(value ?? '').replace(/\s+/g, ' ').trim();
}
function decodeLinkedinRedirect(url: string): string {
if (!url) return '';
try {
const parsed = new URL(url);
if (parsed.pathname === '/redir/redirect/') {
return parsed.searchParams.get('url') || url;
}
} catch {}
return url;
}
// ── Voyager query builder (runs in Node, NOT inside page.evaluate) ────
interface SearchInput {
keywords: string;
location: string;
limit: number;
start: number;
companyIds: string[];
experienceLevels: string[];
jobTypes: string[];
datePostedValues: string[];
remoteTypes: string[];
}
function buildVoyagerSearchQuery(input: SearchInput): string {
const hasFilters =
input.companyIds.length ||
input.experienceLevels.length ||
input.jobTypes.length ||
input.datePostedValues.length ||
input.remoteTypes.length;
const parts = [
'origin:' + (hasFilters ? 'JOB_SEARCH_PAGE_JOB_FILTER' : 'JOB_SEARCH_PAGE_OTHER_ENTRY'),
'keywords:' + input.keywords,
];
if (input.location) {
parts.push('locationUnion:(seoLocation:(location:' + input.location + '))');
}
const filters: string[] = [];
if (input.companyIds.length) filters.push('company:List(' + input.companyIds.join(',') + ')');
if (input.experienceLevels.length) filters.push('experience:List(' + input.experienceLevels.join(',') + ')');
if (input.jobTypes.length) filters.push('jobType:List(' + input.jobTypes.join(',') + ')');
if (input.datePostedValues.length) filters.push('timePostedRange:List(' + input.datePostedValues.join(',') + ')');
if (input.remoteTypes.length) filters.push('workplaceType:List(' + input.remoteTypes.join(',') + ')');
if (filters.length) parts.push('selectedFilters:(' + filters.join(',') + ')');
parts.push('spellCorrectionEnabled:true');
return '(' + parts.join(',') + ')';
}
function buildVoyagerUrl(input: SearchInput, offset: number, count: number): string {
const params = new URLSearchParams({
decorationId: 'com.linkedin.voyager.dash.deco.jobs.search.JobSearchCardsCollection-220',
count: String(count),
q: 'jobSearch',
});
const query = encodeURIComponent(buildVoyagerSearchQuery(input))
.replace(/%3A/gi, ':')
.replace(/%2C/gi, ',')
.replace(/%28/gi, '(')
.replace(/%29/gi, ')');
return '/voyager/api/voyagerJobsDashJobCards?' + params.toString() + '&query=' + query + '&start=' + offset;
}
// ── Company ID resolution (requires DOM interaction) ──────────────────
async function resolveCompanyIds(page: IPage, input: unknown): Promise<string[]> {
const rawValues = parseCsvArg(input);
const ids = new Set<string>();
const names: string[] = [];
for (const value of rawValues) {
if (/^\d+$/.test(value)) ids.add(value);
else names.push(value);
}
if (!names.length) return [...ids];
const resolved = await page.evaluate(`(async () => {
const targets = ${JSON.stringify(names)};
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
const normalize = (v) => (v || '').toLowerCase().replace(/\\s+/g, ' ').trim();
// Open "All filters" panel to expose company filter inputs
const allBtn = [...document.querySelectorAll('button')]
.find(b => ((b.innerText || '').trim().replace(/\\s+/g, ' ')) === 'All filters');
if (allBtn) { allBtn.click(); await sleep(300); }
const getCompanyMap = () => {
const map = {};
for (const el of document.querySelectorAll('input[name="company-filter-value"]')) {
const text = (el.parentElement?.innerText || el.closest('label')?.innerText || '')
.replace(/\\s+/g, ' ').trim().replace(/\\s*Filter by.*$/i, '').trim();
if (text) map[normalize(text)] = el.value;
}
return map;
};
const match = (map, name) => {
const n = normalize(name);
if (map[n]) return map[n];
const k = Object.keys(map).find(e => e === n || e.includes(n) || n.includes(e));
return k ? map[k] : null;
};
const results = {};
let map = getCompanyMap();
for (const name of targets) {
let found = match(map, name);
if (!found) {
const inp = [...document.querySelectorAll('input')]
.find(el => el.getAttribute('aria-label') === 'Add a company');
if (inp) {
inp.focus();
inp.value = name;
inp.dispatchEvent(new Event('input', { bubbles: true }));
inp.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', bubbles: true }));
await sleep(1200);
map = getCompanyMap();
found = match(map, name);
inp.value = '';
inp.dispatchEvent(new Event('input', { bubbles: true }));
await sleep(100);
}
}
results[name] = found || null;
}
return results;
})()`);
const unresolved: string[] = [];
for (const name of names) {
const id = resolved?.[name];
if (id) ids.add(id);
else unresolved.push(name);
}
if (unresolved.length) {
throw new Error(`Could not resolve LinkedIn company filter: ${unresolved.join(', ')}`);
}
return [...ids];
}
// ── Voyager API fetch (runs inside page context for cookie access) ────
async function fetchJobCards(
page: IPage,
input: SearchInput,
): Promise<Array<Record<string, any>>> {
const MAX_BATCH = 25;
const allJobs: Array<Record<string, any>> = [];
let offset = input.start;
while (allJobs.length < input.limit) {
const count = Math.min(MAX_BATCH, input.limit - allJobs.length);
const apiPath = buildVoyagerUrl(input, offset, count);
const batch = await page.evaluate(`(async () => {
const jsession = document.cookie.split(';').map(p => p.trim())
.find(p => p.startsWith('JSESSIONID='))?.slice('JSESSIONID='.length);
if (!jsession) return { error: 'LinkedIn JSESSIONID cookie not found. Please sign in to LinkedIn in the browser.' };
const csrf = jsession.replace(/^"|"$/g, '');
const res = await fetch(${JSON.stringify(apiPath)}, {
credentials: 'include',
headers: { 'csrf-token': csrf, 'x-restli-protocol-version': '2.0.0' },
});
if (!res.ok) {
const text = await res.text();
return { error: 'LinkedIn API error: HTTP ' + res.status + ' ' + text.slice(0, 200) };
}
return res.json();
})()`);
if (!batch || batch.error) {
throw new Error(batch?.error || 'LinkedIn search returned an unexpected response');
}
const elements: any[] = Array.isArray(batch?.elements) ? batch.elements : [];
if (elements.length === 0) break;
for (const element of elements) {
const card = element?.jobCardUnion?.jobPostingCard;
if (!card) continue;
// Extract job ID from URN fields
const jobId = [card.jobPostingUrn, card.jobPosting?.entityUrn, card.entityUrn]
.filter(Boolean)
.map(s => String(s).match(/(\d+)/)?.[1])
.find(Boolean) ?? '';
// Extract listed date
const listedItem = (card.footerItems || []).find((i: any) => i?.type === 'LISTED_DATE' && i?.timeAt);
const listed = listedItem?.timeAt ? new Date(listedItem.timeAt).toISOString().slice(0, 10) : '';
allJobs.push({
title: card.jobPostingTitle || card.title?.text || '',
company: card.primaryDescription?.text || '',
location: card.secondaryDescription?.text || '',
listed,
salary: card.tertiaryDescription?.text || '',
url: jobId ? 'https://www.linkedin.com/jobs/view/' + jobId : '',
});
}
if (elements.length < count) break;
offset += elements.length;
}
return allJobs.slice(0, input.limit).map((item, index) => ({
rank: input.start + index + 1,
...item,
}));
}
// ── Job detail enrichment (--details flag) ────────────────────────────
async function enrichJobDetails(
page: IPage,
jobs: Array<Record<string, any>>,
): Promise<Array<Record<string, any>>> {
const enriched: Array<Record<string, any>> = [];
for (let i = 0; i < jobs.length; i++) {
const job = jobs[i];
console.error(`[opencli:linkedin] Fetching details ${i + 1}/${jobs.length}: ${job.title}`);
if (!job.url) {
enriched.push({ ...job, description: '', apply_url: '' });
continue;
}
try {
await page.goto(job.url);
await page.wait({ text: 'About the job', timeout: 8 });
// Expand "Show more" button if present
await page.evaluate(`(() => {
const norm = (v) => (v || '').replace(/\\s+/g, ' ').trim().toLowerCase();
const section = [...document.querySelectorAll('div, section, article')]
.find(el => norm(el.querySelector('h1,h2,h3,h4')?.textContent || '') === 'about the job');
const btn = [...(section?.querySelectorAll('button, a[role="button"]') || [])]
.find(el => /more/.test(norm(el.textContent || '')) || /more/.test(norm(el.getAttribute('aria-label') || '')));
if (btn) btn.click();
})()`);
await page.wait(1);
// Extract description and apply URL
const detail = await page.evaluate(`(() => {
const norm = (v) => (v || '').replace(/\\s+/g, ' ').trim();
// Find the most specific (shortest) container with "About the job" heading
// Shortest = most specific DOM node, avoiding outer wrappers that include unrelated text
const candidates = [...document.querySelectorAll('div, section, article')]
.map(el => ({
heading: norm(el.querySelector('h1,h2,h3,h4')?.textContent || ''),
text: norm(el.innerText || ''),
}))
.filter(c => c.text && c.heading.toLowerCase() === 'about the job' && c.text.length > 'About the job'.length)
.sort((a, b) => a.text.length - b.text.length);
const description = candidates[0]?.text.replace(/^About the job\\s*/i, '') || '';
const applyLink = [...document.querySelectorAll('a[href]')]
.map(a => ({ href: a.href || '', text: norm(a.textContent || ''), aria: norm(a.getAttribute('aria-label') || '') }))
.find(a => /apply/i.test(a.text) || /apply/i.test(a.aria));
return { description, applyUrl: applyLink?.href || '' };
})()`);
enriched.push({
...job,
description: normalizeWhitespace(detail?.description),
apply_url: decodeLinkedinRedirect(String(detail?.applyUrl ?? '')),
});
} catch {
enriched.push({ ...job, description: '', apply_url: '' });
}
}
return enriched;
}
// ── CLI registration ──────────────────────────────────────────────────
cli({
site: 'linkedin',
name: 'search',
description: 'Search LinkedIn jobs',
domain: 'www.linkedin.com',
strategy: Strategy.HEADER,
browser: true,
args: [
{ name: 'query', type: 'string', required: true, help: 'Job search keywords' },
{ name: 'location', type: 'string', required: false, help: 'Location text such as San Francisco Bay Area' },
{ name: 'limit', type: 'int', default: 10, help: 'Number of jobs to return (max 100)' },
{ name: 'start', type: 'int', default: 0, help: 'Result offset for pagination' },
{ name: 'details', type: 'bool', default: false, help: 'Include full job description and apply URL (slower)' },
{ name: 'company', type: 'string', required: false, help: 'Comma-separated company names or LinkedIn company IDs' },
{ name: 'experience_level', type: 'string', required: false, help: 'Comma-separated: internship, entry, associate, mid-senior, director, executive' },
{ name: 'job_type', type: 'string', required: false, help: 'Comma-separated: full-time, part-time, contract, temporary, volunteer, internship, other' },
{ name: 'date_posted', type: 'string', required: false, help: 'One of: any, month, week, 24h' },
{ name: 'remote', type: 'string', required: false, help: 'Comma-separated: on-site, hybrid, remote' },
],
columns: ['rank', 'title', 'company', 'location', 'listed', 'salary', 'url'],
func: async (page, kwargs) => {
const limit = Math.max(1, Math.min(kwargs.limit ?? 10, 100));
const start = Math.max(0, kwargs.start ?? 0);
const includeDetails = Boolean(kwargs.details);
const location = (kwargs.location ?? '').trim();
const keywords = String(kwargs.query ?? '').trim();
if (!keywords) throw new Error('query is required');
const searchParams = new URLSearchParams({ keywords });
if (location) searchParams.set('location', location);
await page.goto(`https://www.linkedin.com/jobs/search/?${searchParams.toString()}`);
await page.wait({ text: 'Jobs', timeout: 10 });
const companyIds = await resolveCompanyIds(page, kwargs.company);
const input: SearchInput = {
keywords,
location,
limit,
start,
companyIds,
experienceLevels: mapFilterValues(kwargs.experience_level, EXPERIENCE_LEVELS, 'experience_level'),
jobTypes: mapFilterValues(kwargs.job_type, JOB_TYPES, 'job_type'),
datePostedValues: mapFilterValues(kwargs.date_posted, DATE_POSTED, 'date_posted'),
remoteTypes: mapFilterValues(kwargs.remote, REMOTE_TYPES, 'remote'),
};
const data = await fetchJobCards(page, input);
if (!includeDetails) return data;
return enrichJobDetails(page, data);
},
});
+60
View File
@@ -0,0 +1,60 @@
import { cli, Strategy } from '../../registry.js';
cli({
site: 'reddit',
name: 'comment',
description: 'Post a comment on a Reddit post',
domain: 'reddit.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'post_id', type: 'string', required: true, help: 'Post ID (e.g. 1abc123) or fullname (t3_xxx)' },
{ name: 'text', type: 'string', required: true, help: 'Comment text' },
],
columns: ['status', 'message'],
func: async (page, kwargs) => {
if (!page) throw new Error('Requires browser');
await page.goto('https://www.reddit.com');
await page.wait(3);
const result = await page.evaluate(`(async () => {
try {
let postId = ${JSON.stringify(kwargs.post_id)};
const urlMatch = postId.match(/comments\\/([a-z0-9]+)/);
if (urlMatch) postId = urlMatch[1];
const fullname = postId.startsWith('t3_') || postId.startsWith('t1_')
? postId : 't3_' + postId;
const text = ${JSON.stringify(kwargs.text)};
// Get modhash
const meRes = await fetch('/api/me.json', { credentials: 'include' });
const me = await meRes.json();
const modhash = me?.data?.modhash || '';
const res = await fetch('/api/comment', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'parent=' + encodeURIComponent(fullname)
+ '&text=' + encodeURIComponent(text)
+ '&api_type=json'
+ (modhash ? '&uh=' + encodeURIComponent(modhash) : ''),
});
if (!res.ok) return { ok: false, message: 'HTTP ' + res.status };
const data = await res.json();
const errors = data?.json?.errors;
if (errors && errors.length > 0) {
return { ok: false, message: errors.map(e => e.join(': ')).join('; ') };
}
return { ok: true, message: 'Comment posted on ' + fullname };
} catch (e) {
return { ok: false, message: e.toString() };
}
})()`);
return [{ status: result.ok ? 'success' : 'failed', message: result.message }];
}
});
+40
View File
@@ -0,0 +1,40 @@
site: reddit
name: popular
description: Reddit Popular posts (/r/popular)
domain: reddit.com
strategy: cookie
browser: true
args:
limit:
type: int
default: 20
columns: [rank, title, subreddit, score, comments, url]
pipeline:
- navigate: https://www.reddit.com
- evaluate: |
(async () => {
const limit = ${{ args.limit }};
const res = await fetch('/r/popular.json?limit=' + limit + '&raw_json=1', {
credentials: 'include'
});
const d = await res.json();
return (d?.data?.children || []).map(c => ({
title: c.data.title,
subreddit: c.data.subreddit_name_prefixed,
score: c.data.score,
comments: c.data.num_comments,
author: c.data.author,
url: 'https://www.reddit.com' + c.data.permalink,
}));
})()
- map:
rank: ${{ index + 1 }}
title: ${{ item.title }}
subreddit: ${{ item.subreddit }}
score: ${{ item.score }}
comments: ${{ item.comments }}
url: ${{ item.url }}
- limit: ${{ args.limit }}
+186
View File
@@ -0,0 +1,186 @@
/**
* Reddit post reader with threaded comment tree.
*
* Replaces the original flat read.yaml with recursive comment traversal:
* - Top-K comments by score at each level
* - Configurable depth and replies-per-level
* - Indented output showing conversation threads
*/
import { cli, Strategy } from '../../registry.js';
cli({
site: 'reddit',
name: 'read',
description: 'Read a Reddit post and its comments',
domain: 'reddit.com',
strategy: Strategy.COOKIE,
args: [
{ name: 'post_id', required: true, help: 'Post ID (e.g. 1abc123) or full URL' },
{ name: 'sort', default: 'best', help: 'Comment sort: best, top, new, controversial, old, qa' },
{ name: 'limit', type: 'int', default: 25, help: 'Number of top-level comments' },
{ name: 'depth', type: 'int', default: 2, help: 'Max reply depth (1=no replies, 2=one level of replies, etc.)' },
{ name: 'replies', type: 'int', default: 5, help: 'Max replies shown per comment at each level (sorted by score)' },
{ name: 'max_length', type: 'int', default: 2000, help: 'Max characters per comment body (min 100)' },
],
columns: ['type', 'author', 'score', 'text'],
func: async (page, kwargs) => {
const sort = kwargs.sort ?? 'best';
const limit = Math.max(1, kwargs.limit ?? 25);
const maxDepth = Math.max(1, kwargs.depth ?? 2);
const maxReplies = Math.max(1, kwargs.replies ?? 5);
const maxLength = Math.max(100, kwargs.max_length ?? 2000);
await page.goto('https://www.reddit.com');
await page.wait(2);
const data = await page.evaluate(`
(async function() {
var postId = ${JSON.stringify(kwargs.post_id)};
var urlMatch = postId.match(/comments\\/([a-z0-9]+)/);
if (urlMatch) postId = urlMatch[1];
var sort = ${JSON.stringify(sort)};
var limit = ${limit};
var maxDepth = ${maxDepth};
var maxReplies = ${maxReplies};
var maxLength = ${maxLength};
// Request more from API than top-level limit to get inline replies
// depth param tells Reddit how deep to inline replies vs "more" stubs
var apiLimit = Math.max(limit * 3, 100);
var res = await fetch(
'/comments/' + postId + '.json?sort=' + sort + '&limit=' + apiLimit + '&depth=' + (maxDepth + 1) + '&raw_json=1',
{ credentials: 'include' }
);
if (!res.ok) return { error: 'Reddit API returned HTTP ' + res.status };
var data;
try { data = await res.json(); } catch(e) { return { error: 'Failed to parse response' }; }
if (!Array.isArray(data) || data.length < 2) return { error: 'Unexpected response format' };
var results = [];
// Post
var post = data[0] && data[0].data && data[0].data.children && data[0].data.children[0] && data[0].data.children[0].data;
if (post) {
var body = post.selftext || '';
if (body.length > maxLength) body = body.slice(0, maxLength) + '\\n... [truncated]';
results.push({
type: 'POST',
author: post.author || '[deleted]',
score: post.score || 0,
text: post.title + (body ? '\\n\\n' + body : '') + (post.url && !post.is_self ? '\\n' + post.url : ''),
});
}
// Recursive comment walker
// depth 0 = top-level comments; maxDepth is exclusive,
// so --depth 1 means top-level only, --depth 2 means one reply level, etc.
function walkComment(node, depth) {
if (!node || node.kind !== 't1') return;
var d = node.data;
var body = d.body || '';
if (body.length > maxLength) body = body.slice(0, maxLength) + '...';
// Indent prefix: apply to every line so multiline bodies stay aligned
var indent = '';
for (var i = 0; i < depth; i++) indent += ' ';
var prefix = depth === 0 ? '' : indent + '> ';
var indentedBody = depth === 0
? body
: body.split('\\n').map(function(line) { return prefix + line; }).join('\\n');
results.push({
type: depth === 0 ? 'L0' : 'L' + depth,
author: d.author || '[deleted]',
score: d.score || 0,
text: indentedBody,
});
// Count all available replies (for accurate "more" count)
var t1Children = [];
var moreCount = 0;
if (d.replies && d.replies.data && d.replies.data.children) {
var children = d.replies.data.children;
for (var i = 0; i < children.length; i++) {
if (children[i].kind === 't1') {
t1Children.push(children[i]);
} else if (children[i].kind === 'more') {
moreCount += children[i].data.count || 0;
}
}
}
// At depth cutoff: don't recurse, but show all replies as hidden
if (depth + 1 >= maxDepth) {
var totalHidden = t1Children.length + moreCount;
if (totalHidden > 0) {
var cutoffIndent = '';
for (var j = 0; j <= depth; j++) cutoffIndent += ' ';
results.push({
type: 'L' + (depth + 1),
author: '',
score: '',
text: cutoffIndent + '[+' + totalHidden + ' more replies]',
});
}
return;
}
// Sort by score descending, take top N
t1Children.sort(function(a, b) { return (b.data.score || 0) - (a.data.score || 0); });
var toProcess = Math.min(t1Children.length, maxReplies);
for (var i = 0; i < toProcess; i++) {
walkComment(t1Children[i], depth + 1);
}
// Show hidden count (skipped replies + "more" stubs)
var hidden = t1Children.length - toProcess + moreCount;
if (hidden > 0) {
var moreIndent = '';
for (var j = 0; j <= depth; j++) moreIndent += ' ';
results.push({
type: 'L' + (depth + 1),
author: '',
score: '',
text: moreIndent + '[+' + hidden + ' more replies]',
});
}
}
// Walk top-level comments
var topLevel = data[1].data.children || [];
var t1TopLevel = [];
for (var i = 0; i < topLevel.length; i++) {
if (topLevel[i].kind === 't1') t1TopLevel.push(topLevel[i]);
}
// Top-level are already sorted by Reddit (sort param), take top N
for (var i = 0; i < Math.min(t1TopLevel.length, limit); i++) {
walkComment(t1TopLevel[i], 0);
}
// Count remaining
var moreTopLevel = topLevel.filter(function(c) { return c.kind === 'more'; })
.reduce(function(sum, c) { return sum + (c.data.count || 0); }, 0);
var hiddenTopLevel = Math.max(0, t1TopLevel.length - limit) + moreTopLevel;
if (hiddenTopLevel > 0) {
results.push({
type: '',
author: '',
score: '',
text: '[+' + hiddenTopLevel + ' more top-level comments]',
});
}
return results;
})()
`);
if (!data || typeof data !== 'object') throw new Error('Failed to fetch post data');
if (!Array.isArray(data) && data.error) throw new Error(data.error);
if (!Array.isArray(data)) throw new Error('Unexpected response');
return data;
},
});
+54
View File
@@ -0,0 +1,54 @@
import { cli, Strategy } from '../../registry.js';
cli({
site: 'reddit',
name: 'save',
description: 'Save or unsave a Reddit post',
domain: 'reddit.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'post_id', type: 'string', required: true, help: 'Post ID (e.g. 1abc123) or fullname (t3_xxx)' },
{ name: 'undo', type: 'boolean', default: false, help: 'Unsave instead of save' },
],
columns: ['status', 'message'],
func: async (page, kwargs) => {
if (!page) throw new Error('Requires browser');
await page.goto('https://www.reddit.com');
await page.wait(3);
const result = await page.evaluate(`(async () => {
try {
let postId = ${JSON.stringify(kwargs.post_id)};
const urlMatch = postId.match(/comments\\/([a-z0-9]+)/);
if (urlMatch) postId = urlMatch[1];
const fullname = postId.startsWith('t3_') || postId.startsWith('t1_')
? postId : 't3_' + postId;
const undo = ${kwargs.undo ? 'true' : 'false'};
const endpoint = undo ? '/api/unsave' : '/api/save';
// Get modhash
const meRes = await fetch('/api/me.json', { credentials: 'include' });
const me = await meRes.json();
const modhash = me?.data?.modhash || '';
const res = await fetch(endpoint, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'id=' + encodeURIComponent(fullname)
+ (modhash ? '&uh=' + encodeURIComponent(modhash) : ''),
});
if (!res.ok) return { ok: false, message: 'HTTP ' + res.status };
return { ok: true, message: (undo ? 'Unsaved' : 'Saved') + ' ' + fullname };
} catch (e) {
return { ok: false, message: e.toString() };
}
})()`);
return [{ status: result.ok ? 'success' : 'failed', message: result.message }];
}
});
+48
View File
@@ -0,0 +1,48 @@
import { cli, Strategy } from '../../registry.js';
cli({
site: 'reddit',
name: 'saved',
description: 'Browse your saved Reddit posts',
domain: 'reddit.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'limit', type: 'int', default: 15 },
],
columns: ['title', 'subreddit', 'score', 'comments', 'url'],
func: async (page, kwargs) => {
if (!page) throw new Error('Requires browser');
await page.goto('https://www.reddit.com');
await page.wait(3);
const result = await page.evaluate(`(async () => {
try {
// Get current username
const meRes = await fetch('/api/me.json?raw_json=1', { credentials: 'include' });
const me = await meRes.json();
const username = me?.name || me?.data?.name;
if (!username) return { error: 'Not logged in — cannot determine username' };
const limit = ${kwargs.limit};
const res = await fetch('/user/' + username + '/saved.json?limit=' + limit + '&raw_json=1', {
credentials: 'include'
});
const d = await res.json();
return (d?.data?.children || []).map(c => ({
title: c.data.title || c.data.body?.slice(0, 100) || '-',
subreddit: c.data.subreddit_name_prefixed || 'r/' + (c.data.subreddit || '?'),
score: c.data.score || 0,
comments: c.data.num_comments || 0,
url: 'https://www.reddit.com' + (c.data.permalink || ''),
}));
} catch (e) {
return { error: e.toString() };
}
})()`);
if (result?.error) throw new Error(result.error);
return (result || []).slice(0, kwargs.limit);
}
});
+37 -11
View File
@@ -9,26 +9,52 @@ args:
query:
type: string
required: true
subreddit:
type: string
default: ""
description: "Search within a specific subreddit"
sort:
type: string
default: relevance
description: "Sort order: relevance, hot, top, new, comments"
time:
type: string
default: all
description: "Time filter: hour, day, week, month, year, all"
limit:
type: int
default: 15
columns: [title, subreddit, author, upvotes, comments, url]
columns: [title, subreddit, author, score, comments, url]
pipeline:
- navigate: https://www.reddit.com
- evaluate: |
(async () => {
const q = encodeURIComponent('${{ args.query }}');
const res = await fetch('/search.json?q=' + q + '&limit=${{ args.limit }}', { credentials: 'include' });
const j = await res.json();
return j?.data?.children || [];
const q = encodeURIComponent(${{ args.query | json }});
const sub = ${{ args.subreddit | json }};
const sort = ${{ args.sort | json }};
const time = ${{ args.time | json }};
const limit = ${{ args.limit }};
const basePath = sub ? '/r/' + sub + '/search.json' : '/search.json';
const params = 'q=' + q + '&sort=' + sort + '&t=' + time + '&limit=' + limit
+ '&restrict_sr=' + (sub ? 'on' : 'off') + '&raw_json=1';
const res = await fetch(basePath + '?' + params, { credentials: 'include' });
const d = await res.json();
return (d?.data?.children || []).map(c => ({
title: c.data.title,
subreddit: c.data.subreddit_name_prefixed,
author: c.data.author,
score: c.data.score,
comments: c.data.num_comments,
url: 'https://www.reddit.com' + c.data.permalink,
}));
})()
- map:
title: ${{ item.data.title }}
subreddit: ${{ item.data.subreddit_name_prefixed }}
author: ${{ item.data.author }}
upvotes: ${{ item.data.score }}
comments: ${{ item.data.num_comments }}
url: https://www.reddit.com${{ item.data.permalink }}
title: ${{ item.title }}
subreddit: ${{ item.subreddit }}
author: ${{ item.author }}
score: ${{ item.score }}
comments: ${{ item.comments }}
url: ${{ item.url }}
- limit: ${{ args.limit }}
+14 -4
View File
@@ -12,7 +12,11 @@ args:
sort:
type: string
default: hot
description: "Sorting method: hot, new, top, rising"
description: "Sorting method: hot, new, top, rising, controversial"
time:
type: string
default: all
description: "Time filter for top/controversial: hour, day, week, month, year, all"
limit:
type: int
default: 15
@@ -23,10 +27,16 @@ pipeline:
- navigate: https://www.reddit.com
- evaluate: |
(async () => {
let sub = '${{ args.name }}';
let sub = ${{ args.name | json }};
if (sub.startsWith('r/')) sub = sub.slice(2);
const sort = '${{ args.sort }}';
const res = await fetch('/r/' + sub + '/' + sort + '.json?limit=${{ args.limit }}', { credentials: 'include' });
const sort = ${{ args.sort | json }};
const time = ${{ args.time | json }};
const limit = ${{ args.limit }};
let url = '/r/' + sub + '/' + sort + '.json?limit=' + limit + '&raw_json=1';
if ((sort === 'top' || sort === 'controversial') && time) {
url += '&t=' + time;
}
const res = await fetch(url, { credentials: 'include' });
const j = await res.json();
return j?.data?.children || [];
})()
+53
View File
@@ -0,0 +1,53 @@
import { cli, Strategy } from '../../registry.js';
cli({
site: 'reddit',
name: 'subscribe',
description: 'Subscribe or unsubscribe to a subreddit',
domain: 'reddit.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'subreddit', type: 'string', required: true, help: 'Subreddit name (e.g. python)' },
{ name: 'undo', type: 'boolean', default: false, help: 'Unsubscribe instead of subscribe' },
],
columns: ['status', 'message'],
func: async (page, kwargs) => {
if (!page) throw new Error('Requires browser');
await page.goto('https://www.reddit.com');
await page.wait(3);
const result = await page.evaluate(`(async () => {
try {
let sub = ${JSON.stringify(kwargs.subreddit)};
if (sub.startsWith('r/')) sub = sub.slice(2);
const undo = ${kwargs.undo ? 'true' : 'false'};
const action = undo ? 'unsub' : 'sub';
// Get modhash
const meRes = await fetch('/api/me.json', { credentials: 'include' });
const me = await meRes.json();
const modhash = me?.data?.modhash || '';
const res = await fetch('/api/subscribe', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'sr_name=' + encodeURIComponent(sub)
+ '&action=' + action
+ (modhash ? '&uh=' + encodeURIComponent(modhash) : ''),
});
if (!res.ok) return { ok: false, message: 'HTTP ' + res.status };
const label = undo ? 'Unsubscribed from' : 'Subscribed to';
return { ok: true, message: label + ' r/' + sub };
} catch (e) {
return { ok: false, message: e.toString() };
}
})()`);
return [{ status: result.ok ? 'success' : 'failed', message: result.message }];
}
});
+67
View File
@@ -0,0 +1,67 @@
import { cli, Strategy } from '../../registry.js';
cli({
site: 'reddit',
name: 'upvote',
description: 'Upvote or downvote a Reddit post',
domain: 'reddit.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'post_id', type: 'string', required: true, help: 'Post ID (e.g. 1abc123) or fullname (t3_xxx)' },
{ name: 'direction', type: 'string', default: 'up', help: 'Vote direction: up, down, none' },
],
columns: ['status', 'message'],
func: async (page, kwargs) => {
if (!page) throw new Error('Requires browser');
await page.goto('https://www.reddit.com');
await page.wait(3);
const result = await page.evaluate(`(async () => {
try {
let postId = ${JSON.stringify(kwargs.post_id)};
// Extract ID from URL if needed
const urlMatch = postId.match(/comments\\/([a-z0-9]+)/);
if (urlMatch) postId = urlMatch[1];
// Build fullname
const fullname = postId.startsWith('t3_') || postId.startsWith('t1_')
? postId : 't3_' + postId;
const dir = ${JSON.stringify(kwargs.direction)};
const direction = dir === 'down' ? -1 : dir === 'none' ? 0 : 1;
// Get modhash from Reddit config
const configEl = document.getElementById('config');
let modhash = '';
if (configEl) {
modhash = configEl.querySelector('[name="uh"]')?.getAttribute('content') || '';
}
if (!modhash) {
// Try fetching from /api/me.json
const meRes = await fetch('/api/me.json', { credentials: 'include' });
const me = await meRes.json();
modhash = me?.data?.modhash || '';
}
const res = await fetch('/api/vote', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: 'id=' + encodeURIComponent(fullname)
+ '&dir=' + direction
+ (modhash ? '&uh=' + encodeURIComponent(modhash) : ''),
});
if (!res.ok) return { ok: false, message: 'HTTP ' + res.status };
const labels = { '1': 'Upvoted', '-1': 'Downvoted', '0': 'Vote removed' };
return { ok: true, message: (labels[String(direction)] || 'Voted') + ' ' + fullname };
} catch (e) {
return { ok: false, message: e.toString() };
}
})()`);
return [{ status: result.ok ? 'success' : 'failed', message: result.message }];
}
});
+48
View File
@@ -0,0 +1,48 @@
import { cli, Strategy } from '../../registry.js';
cli({
site: 'reddit',
name: 'upvoted',
description: 'Browse your upvoted Reddit posts',
domain: 'reddit.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'limit', type: 'int', default: 15 },
],
columns: ['title', 'subreddit', 'score', 'comments', 'url'],
func: async (page, kwargs) => {
if (!page) throw new Error('Requires browser');
await page.goto('https://www.reddit.com');
await page.wait(3);
const result = await page.evaluate(`(async () => {
try {
// Get current username
const meRes = await fetch('/api/me.json?raw_json=1', { credentials: 'include' });
const me = await meRes.json();
const username = me?.name || me?.data?.name;
if (!username) return { error: 'Not logged in — cannot determine username' };
const limit = ${kwargs.limit};
const res = await fetch('/user/' + username + '/upvoted.json?limit=' + limit + '&raw_json=1', {
credentials: 'include'
});
const d = await res.json();
return (d?.data?.children || []).map(c => ({
title: c.data.title || '-',
subreddit: c.data.subreddit_name_prefixed || 'r/' + (c.data.subreddit || '?'),
score: c.data.score || 0,
comments: c.data.num_comments || 0,
url: 'https://www.reddit.com' + (c.data.permalink || ''),
}));
} catch (e) {
return { error: e.toString() };
}
})()`);
if (result?.error) throw new Error(result.error);
return (result || []).slice(0, kwargs.limit);
}
});
+45
View File
@@ -0,0 +1,45 @@
site: reddit
name: user-comments
description: View a Reddit user's comment history
domain: reddit.com
strategy: cookie
browser: true
args:
username:
type: string
required: true
limit:
type: int
default: 15
columns: [subreddit, score, body, url]
pipeline:
- navigate: https://www.reddit.com
- evaluate: |
(async () => {
const username = ${{ args.username | json }};
const name = username.startsWith('u/') ? username.slice(2) : username;
const limit = ${{ args.limit }};
const res = await fetch('/user/' + name + '/comments.json?limit=' + limit + '&raw_json=1', {
credentials: 'include'
});
const d = await res.json();
return (d?.data?.children || []).map(c => {
let body = c.data.body || '';
if (body.length > 300) body = body.slice(0, 300) + '...';
return {
subreddit: c.data.subreddit_name_prefixed,
score: c.data.score,
body: body,
url: 'https://www.reddit.com' + c.data.permalink,
};
});
})()
- map:
subreddit: ${{ item.subreddit }}
score: ${{ item.score }}
body: ${{ item.body }}
url: ${{ item.url }}
- limit: ${{ args.limit }}
+43
View File
@@ -0,0 +1,43 @@
site: reddit
name: user-posts
description: View a Reddit user's submitted posts
domain: reddit.com
strategy: cookie
browser: true
args:
username:
type: string
required: true
limit:
type: int
default: 15
columns: [title, subreddit, score, comments, url]
pipeline:
- navigate: https://www.reddit.com
- evaluate: |
(async () => {
const username = ${{ args.username | json }};
const name = username.startsWith('u/') ? username.slice(2) : username;
const limit = ${{ args.limit }};
const res = await fetch('/user/' + name + '/submitted.json?limit=' + limit + '&raw_json=1', {
credentials: 'include'
});
const d = await res.json();
return (d?.data?.children || []).map(c => ({
title: c.data.title,
subreddit: c.data.subreddit_name_prefixed,
score: c.data.score,
comments: c.data.num_comments,
url: 'https://www.reddit.com' + c.data.permalink,
}));
})()
- map:
title: ${{ item.title }}
subreddit: ${{ item.subreddit }}
score: ${{ item.score }}
comments: ${{ item.comments }}
url: ${{ item.url }}
- limit: ${{ args.limit }}
+39
View File
@@ -0,0 +1,39 @@
site: reddit
name: user
description: View a Reddit user profile
domain: reddit.com
strategy: cookie
browser: true
args:
username:
type: string
required: true
columns: [field, value]
pipeline:
- navigate: https://www.reddit.com
- evaluate: |
(async () => {
const username = ${{ args.username | json }};
const name = username.startsWith('u/') ? username.slice(2) : username;
const res = await fetch('/user/' + name + '/about.json?raw_json=1', {
credentials: 'include'
});
const d = await res.json();
const u = d?.data || d || {};
const created = u.created_utc ? new Date(u.created_utc * 1000).toISOString().split('T')[0] : '-';
return [
{ field: 'Username', value: 'u/' + (u.name || name) },
{ field: 'Post Karma', value: String(u.link_karma || 0) },
{ field: 'Comment Karma', value: String(u.comment_karma || 0) },
{ field: 'Total Karma', value: String(u.total_karma || (u.link_karma||0) + (u.comment_karma||0)) },
{ field: 'Account Created', value: created },
{ field: 'Gold', value: u.is_gold ? '⭐ Yes' : 'No' },
{ field: 'Verified', value: u.verified ? '✅ Yes' : 'No' },
];
})()
- map:
field: ${{ item.field }}
value: ${{ item.value }}
+161
View File
@@ -0,0 +1,161 @@
import { cli, Strategy } from '../../registry.js';
cli({
site: 'twitter',
name: 'article',
description: 'Fetch a Twitter Article (long-form content) and export as Markdown',
domain: 'x.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'tweet_id', type: 'string', positional: true, required: true, help: 'Tweet ID or URL containing the article' },
],
columns: ['title', 'author', 'content', 'url'],
func: async (page, kwargs) => {
// Extract tweet ID from URL if needed
let tweetId = kwargs.tweet_id;
const urlMatch = tweetId.match(/\/(?:status|article)\/(\d+)/);
if (urlMatch) tweetId = urlMatch[1];
// Navigate to the tweet page for cookie context
await page.goto(`https://x.com/i/status/${tweetId}`);
await page.wait(3);
const result = await page.evaluate(`
async () => {
const tweetId = "${tweetId}";
const ct0 = document.cookie.split(';').map(c=>c.trim()).find(c=>c.startsWith('ct0='))?.split('=')[1];
if (!ct0) return {error: 'No ct0 cookie — not logged into x.com'};
const bearer = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA';
const headers = {
'Authorization': 'Bearer ' + decodeURIComponent(bearer),
'X-Csrf-Token': ct0,
'X-Twitter-Auth-Type': 'OAuth2Session',
'X-Twitter-Active-User': 'yes'
};
const variables = JSON.stringify({
tweetId: tweetId,
withCommunity: false,
includePromotedContent: false,
withVoice: false,
});
const features = JSON.stringify({
longform_notetweets_consumption_enabled: true,
responsive_web_twitter_article_tweet_consumption_enabled: true,
longform_notetweets_rich_text_read_enabled: true,
longform_notetweets_inline_media_enabled: true,
articles_preview_enabled: true,
responsive_web_graphql_exclude_directive_enabled: true,
verified_phone_label_enabled: false,
});
const fieldToggles = JSON.stringify({
withArticleRichContentState: true,
withArticlePlainText: true,
});
// Dynamically resolve queryId: GitHub community source → JS bundle scan → hardcoded fallback
async function resolveQueryId(operationName, fallbackId) {
try {
const ghResp = await fetch('https://raw.githubusercontent.com/fa0311/twitter-openapi/refs/heads/main/src/config/placeholder.json');
if (ghResp.ok) {
const data = await ghResp.json();
const entry = data[operationName];
if (entry && entry.queryId) return entry.queryId;
}
} catch {}
try {
const scripts = performance.getEntriesByType('resource')
.filter(r => r.name.includes('client-web') && r.name.endsWith('.js'))
.map(r => r.name);
for (const scriptUrl of scripts.slice(0, 15)) {
try {
const text = await (await fetch(scriptUrl)).text();
const re = new RegExp('queryId:"([A-Za-z0-9_-]+)"[^}]{0,200}operationName:"' + operationName + '"');
const m = text.match(re);
if (m) return m[1];
} catch {}
}
} catch {}
return fallbackId;
}
const queryId = await resolveQueryId('TweetResultByRestId', '7xflPyRiUxGVbJd4uWmbfg');
const url = '/i/api/graphql/' + queryId + '/TweetResultByRestId?variables='
+ encodeURIComponent(variables)
+ '&features=' + encodeURIComponent(features)
+ '&fieldToggles=' + encodeURIComponent(fieldToggles);
const resp = await fetch(url, {headers, credentials: 'include'});
if (!resp.ok) return {error: 'HTTP ' + resp.status, hint: 'Tweet may not exist or queryId expired'};
const d = await resp.json();
const result = d.data?.tweetResult?.result;
if (!result) return {error: 'Article not found'};
// Unwrap TweetWithVisibilityResults
const tw = result.tweet || result;
const legacy = tw.legacy || {};
const user = tw.core?.user_results?.result;
const screenName = user?.legacy?.screen_name || user?.core?.screen_name || 'unknown';
// Extract article content
const articleResults = tw.article?.article_results?.result;
if (!articleResults) {
// Fallback: return note_tweet text if present
const noteText = tw.note_tweet?.note_tweet_results?.result?.text;
if (noteText) {
return [{
title: '(Note Tweet)',
author: screenName,
content: noteText,
url: 'https://x.com/' + screenName + '/status/' + tweetId,
}];
}
return {error: 'Tweet ' + tweetId + ' has no article content'};
}
const title = articleResults.title || '(Untitled)';
const contentState = articleResults.content_state || {};
const blocks = contentState.blocks || [];
// Convert draft.js blocks to Markdown
const parts = [];
let orderedCounter = 0;
for (const block of blocks) {
const blockType = block.type || 'unstyled';
if (blockType === 'atomic') continue;
const text = block.text || '';
if (!text) continue;
if (blockType !== 'ordered-list-item') orderedCounter = 0;
if (blockType === 'header-one') parts.push('# ' + text);
else if (blockType === 'header-two') parts.push('## ' + text);
else if (blockType === 'header-three') parts.push('### ' + text);
else if (blockType === 'blockquote') parts.push('> ' + text);
else if (blockType === 'unordered-list-item') parts.push('- ' + text);
else if (blockType === 'ordered-list-item') {
orderedCounter++;
parts.push(orderedCounter + '. ' + text);
}
else if (blockType === 'code-block') parts.push('\`\`\`\\n' + text + '\\n\`\`\`');
else parts.push(text);
}
return [{
title,
author: screenName,
content: parts.join('\\n\\n') || legacy.full_text || '',
url: 'https://x.com/' + screenName + '/status/' + tweetId,
}];
}
`);
if (result?.error) {
throw new Error(result.error + (result.hint ? ` (${result.hint})` : ''));
}
return result || [];
}
});
+67
View File
@@ -0,0 +1,67 @@
import { cli, Strategy } from '../../registry.js';
import type { IPage } from '../../types.js';
cli({
site: 'twitter',
name: 'bookmark',
description: 'Bookmark a tweet',
domain: 'x.com',
strategy: Strategy.UI,
browser: true,
args: [
{ name: 'url', type: 'string', positional: true, required: true, help: 'Tweet URL to bookmark' },
],
columns: ['status', 'message'],
func: async (page: IPage | null, kwargs: any) => {
if (!page) throw new Error('Requires browser');
await page.goto(kwargs.url);
await page.wait(5);
const result = await page.evaluate(`(async () => {
try {
let attempts = 0;
let bookmarkBtn = null;
let removeBtn = null;
while (attempts < 20) {
// Check if already bookmarked
removeBtn = document.querySelector('[data-testid="removeBookmark"]');
if (removeBtn) {
return { ok: true, message: 'Tweet is already bookmarked.' };
}
bookmarkBtn = document.querySelector('[data-testid="bookmark"]');
if (bookmarkBtn) break;
await new Promise(r => setTimeout(r, 500));
attempts++;
}
if (!bookmarkBtn) {
return { ok: false, message: 'Could not find Bookmark button. Are you logged in?' };
}
bookmarkBtn.click();
await new Promise(r => setTimeout(r, 1000));
// Verify
const verify = document.querySelector('[data-testid="removeBookmark"]');
if (verify) {
return { ok: true, message: 'Tweet successfully bookmarked.' };
} else {
return { ok: false, message: 'Bookmark action initiated but UI did not update.' };
}
} catch (e) {
return { ok: false, message: e.toString() };
}
})()`);
if (result.ok) await page.wait(2);
return [{
status: result.ok ? 'success' : 'failed',
message: result.message
}];
}
});
+201
View File
@@ -0,0 +1,201 @@
import { cli, Strategy } from '../../registry.js';
const BEARER_TOKEN = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA';
const BOOKMARKS_QUERY_ID = 'Fy0QMy4q_aZCpkO0PnyLYw';
const FEATURES = {
rweb_video_screen_enabled: false,
profile_label_improvements_pcf_label_in_post_enabled: true,
responsive_web_profile_redirect_enabled: false,
rweb_tipjar_consumption_enabled: false,
verified_phone_label_enabled: false,
creator_subscriptions_tweet_preview_api_enabled: true,
responsive_web_graphql_timeline_navigation_enabled: true,
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
premium_content_api_read_enabled: false,
communities_web_enable_tweet_community_results_fetch: true,
c9s_tweet_anatomy_moderator_badge_enabled: true,
articles_preview_enabled: true,
responsive_web_edit_tweet_api_enabled: true,
graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
view_counts_everywhere_api_enabled: true,
longform_notetweets_consumption_enabled: true,
responsive_web_twitter_article_tweet_consumption_enabled: true,
tweet_awards_web_tipping_enabled: false,
content_disclosure_indicator_enabled: true,
content_disclosure_ai_generated_indicator_enabled: true,
freedom_of_speech_not_reach_fetch_enabled: true,
standardized_nudges_misinfo: true,
tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,
longform_notetweets_rich_text_read_enabled: true,
longform_notetweets_inline_media_enabled: false,
responsive_web_enhance_cards_enabled: false,
};
interface BookmarkTweet {
id: string;
author: string;
name: string;
text: string;
likes: number;
retweets: number;
created_at: string;
url: string;
}
function buildBookmarksUrl(count: number, cursor?: string | null): string {
const vars: Record<string, any> = {
count,
includePromotedContent: false,
};
if (cursor) vars.cursor = cursor;
return `/i/api/graphql/${BOOKMARKS_QUERY_ID}/Bookmarks`
+ `?variables=${encodeURIComponent(JSON.stringify(vars))}`
+ `&features=${encodeURIComponent(JSON.stringify(FEATURES))}`;
}
function extractBookmarkTweet(result: any, seen: Set<string>): BookmarkTweet | null {
if (!result) return null;
const tw = result.tweet || result;
const legacy = tw.legacy || {};
if (!tw.rest_id || seen.has(tw.rest_id)) return null;
seen.add(tw.rest_id);
const user = tw.core?.user_results?.result;
const screenName = user?.legacy?.screen_name || user?.core?.screen_name || 'unknown';
const displayName = user?.legacy?.name || user?.core?.name || '';
const noteText = tw.note_tweet?.note_tweet_results?.result?.text;
return {
id: tw.rest_id,
author: screenName,
name: displayName,
text: noteText || legacy.full_text || '',
likes: legacy.favorite_count || 0,
retweets: legacy.retweet_count || 0,
created_at: legacy.created_at || '',
url: `https://x.com/${screenName}/status/${tw.rest_id}`,
};
}
function parseBookmarks(data: any, seen: Set<string>): { tweets: BookmarkTweet[]; nextCursor: string | null } {
const tweets: BookmarkTweet[] = [];
let nextCursor: string | null = null;
const instructions =
data?.data?.bookmark_timeline_v2?.timeline?.instructions
|| data?.data?.bookmark_timeline?.timeline?.instructions
|| [];
for (const inst of instructions) {
for (const entry of inst.entries || []) {
const content = entry.content;
if (content?.entryType === 'TimelineTimelineCursor' || content?.__typename === 'TimelineTimelineCursor') {
if (content.cursorType === 'Bottom' || content.cursorType === 'ShowMore') nextCursor = content.value;
continue;
}
if (entry.entryId?.startsWith('cursor-bottom-') || entry.entryId?.startsWith('cursor-showMore-')) {
nextCursor = content?.value || content?.itemContent?.value || nextCursor;
continue;
}
const direct = extractBookmarkTweet(content?.itemContent?.tweet_results?.result, seen);
if (direct) {
tweets.push(direct);
continue;
}
for (const item of content?.items || []) {
const nested = extractBookmarkTweet(item.item?.itemContent?.tweet_results?.result, seen);
if (nested) tweets.push(nested);
}
}
}
return { tweets, nextCursor };
}
cli({
site: 'twitter',
name: 'bookmarks',
description: 'Fetch Twitter/X bookmarks',
domain: 'x.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'limit', type: 'int', default: 20 },
],
columns: ['author', 'text', 'likes', 'url'],
func: async (page, kwargs) => {
const limit = kwargs.limit || 20;
await page.goto('https://x.com');
await page.wait(3);
const ct0 = await page.evaluate(`() => {
return document.cookie.split(';').map(c => c.trim()).find(c => c.startsWith('ct0='))?.split('=')[1] || null;
}`);
if (!ct0) throw new Error('Not logged into x.com (no ct0 cookie)');
const queryId = await page.evaluate(`async () => {
try {
const ghResp = await fetch('https://raw.githubusercontent.com/fa0311/twitter-openapi/refs/heads/main/src/config/placeholder.json');
if (ghResp.ok) {
const data = await ghResp.json();
const entry = data['Bookmarks'];
if (entry && entry.queryId) return entry.queryId;
}
} catch {}
try {
const scripts = performance.getEntriesByType('resource')
.filter(r => r.name.includes('client-web') && r.name.endsWith('.js'))
.map(r => r.name);
for (const scriptUrl of scripts.slice(0, 15)) {
try {
const text = await (await fetch(scriptUrl)).text();
const re = /queryId:"([A-Za-z0-9_-]+)"[^}]{0,200}operationName:"Bookmarks"/;
const m = text.match(re);
if (m) return m[1];
} catch {}
}
} catch {}
return null;
}`) || BOOKMARKS_QUERY_ID;
const headers = JSON.stringify({
'Authorization': `Bearer ${decodeURIComponent(BEARER_TOKEN)}`,
'X-Csrf-Token': ct0,
'X-Twitter-Auth-Type': 'OAuth2Session',
'X-Twitter-Active-User': 'yes',
});
const allTweets: BookmarkTweet[] = [];
const seen = new Set<string>();
let cursor: string | null = null;
for (let i = 0; i < 5 && allTweets.length < limit; i++) {
const fetchCount = Math.min(100, limit - allTweets.length + 10);
const apiUrl = buildBookmarksUrl(fetchCount, cursor).replace(BOOKMARKS_QUERY_ID, queryId);
const data = await page.evaluate(`async () => {
const r = await fetch("${apiUrl}", { headers: ${headers}, credentials: 'include' });
return r.ok ? await r.json() : { error: r.status };
}`);
if (data?.error) {
if (allTweets.length === 0) throw new Error(`HTTP ${data.error}: Failed to fetch bookmarks. queryId may have expired.`);
break;
}
const { tweets, nextCursor } = parseBookmarks(data, seen);
allTweets.push(...tweets);
if (!nextCursor || nextCursor === cursor) break;
cursor = nextCursor;
}
return allTweets.slice(0, limit);
},
});
-85
View File
@@ -1,85 +0,0 @@
site: twitter
name: bookmarks
description: 获取 Twitter 书签列表
domain: x.com
browser: true
args:
limit:
type: int
default: 20
description: Number of bookmarks to return (default 20)
pipeline:
- navigate: https://x.com/i/bookmarks
- wait: 2
- evaluate: |
(async () => {
const ct0 = document.cookie.split(';').map(c=>c.trim()).find(c=>c.startsWith('ct0='))?.split('=')[1];
if (!ct0) throw new Error('No ct0 cookie. Hint: Not logged into x.com.');
const bearer = decodeURIComponent('AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA');
const _h = {'Authorization':'Bearer '+bearer, 'X-Csrf-Token':ct0, 'X-Twitter-Auth-Type':'OAuth2Session', 'X-Twitter-Active-User':'yes'};
const count = Math.min(${{ args.limit }}, 100);
const variables = JSON.stringify({count, includePromotedContent: false});
const features = JSON.stringify({
rweb_video_screen_enabled: false, profile_label_improvements_pcf_label_in_post_enabled: true,
responsive_web_profile_redirect_enabled: false, rweb_tipjar_consumption_enabled: false,
verified_phone_label_enabled: false, creator_subscriptions_tweet_preview_api_enabled: true,
responsive_web_graphql_timeline_navigation_enabled: true,
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
premium_content_api_read_enabled: false, communities_web_enable_tweet_community_results_fetch: true,
c9s_tweet_anatomy_moderator_badge_enabled: true,
articles_preview_enabled: true, responsive_web_edit_tweet_api_enabled: true,
graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
view_counts_everywhere_api_enabled: true, longform_notetweets_consumption_enabled: true,
responsive_web_twitter_article_tweet_consumption_enabled: true,
tweet_awards_web_tipping_enabled: false,
content_disclosure_indicator_enabled: true, content_disclosure_ai_generated_indicator_enabled: true,
freedom_of_speech_not_reach_fetch_enabled: true, standardized_nudges_misinfo: true,
tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,
longform_notetweets_rich_text_read_enabled: true, longform_notetweets_inline_media_enabled: false,
responsive_web_enhance_cards_enabled: false
});
const url = '/i/api/graphql/Fy0QMy4q_aZCpkO0PnyLYw/Bookmarks?variables=' + encodeURIComponent(variables) + '&features=' + encodeURIComponent(features);
const resp = await fetch(url, {headers: _h, credentials: 'include'});
if (!resp.ok) throw new Error('HTTP ' + resp.status + '. Hint: queryId may have changed.');
const d = await resp.json();
const instructions = d.data?.bookmark_timeline_v2?.timeline?.instructions || d.data?.bookmark_timeline?.timeline?.instructions || [];
let tweets = [], seen = new Set();
for (const inst of instructions) {
for (const entry of (inst.entries || [])) {
const r = entry.content?.itemContent?.tweet_results?.result;
if (!r) continue;
const tw = r.tweet || r;
const l = tw.legacy || {};
if (!tw.rest_id || seen.has(tw.rest_id)) continue;
seen.add(tw.rest_id);
const u = tw.core?.user_results?.result;
const nt = tw.note_tweet?.note_tweet_results?.result?.text;
const screenName = u?.legacy?.screen_name || u?.core?.screen_name;
tweets.push({
id: tw.rest_id,
author: screenName,
name: u?.legacy?.name || u?.core?.name,
url: 'https://x.com/' + (screenName || '_') + '/status/' + tw.rest_id,
text: nt || l.full_text || '',
likes: l.favorite_count,
retweets: l.retweet_count,
created_at: l.created_at
});
}
}
return tweets;
})()
- map:
author: ${{ item.author }}
text: ${{ item.text }}
likes: ${{ item.likes }}
url: ${{ item.url }}
- limit: ${{ args.limit }}
columns: [author, text, likes, url]
-1
View File
@@ -15,7 +15,6 @@ cli({
func: async (page: IPage | null, kwargs: any) => {
if (!page) throw new Error('Requires browser');
console.log(`Navigating to tweet: ${kwargs.url}`);
await page.goto(kwargs.url);
await page.wait(5); // Wait for tweet to load completely
+69
View File
@@ -0,0 +1,69 @@
import { cli, Strategy } from '../../registry.js';
import type { IPage } from '../../types.js';
cli({
site: 'twitter',
name: 'follow',
description: 'Follow a Twitter user',
domain: 'x.com',
strategy: Strategy.UI,
browser: true,
args: [
{ name: 'username', type: 'string', positional: true, required: true, help: 'Twitter screen name (without @)' },
],
columns: ['status', 'message'],
func: async (page: IPage | null, kwargs: any) => {
if (!page) throw new Error('Requires browser');
const username = kwargs.username.replace(/^@/, '');
await page.goto(`https://x.com/${username}`);
await page.wait(5);
const result = await page.evaluate(`(async () => {
try {
let attempts = 0;
let followBtn = null;
let unfollowTestId = null;
while (attempts < 20) {
// Check if already following (button shows screen_name-unfollow)
unfollowTestId = document.querySelector('[data-testid$="-unfollow"]');
if (unfollowTestId) {
return { ok: true, message: 'Already following @${username}.' };
}
// Look for the Follow button
followBtn = document.querySelector('[data-testid$="-follow"]');
if (followBtn) break;
await new Promise(r => setTimeout(r, 500));
attempts++;
}
if (!followBtn) {
return { ok: false, message: 'Could not find Follow button. Are you logged in?' };
}
followBtn.click();
await new Promise(r => setTimeout(r, 1500));
// Verify
const verify = document.querySelector('[data-testid$="-unfollow"]');
if (verify) {
return { ok: true, message: 'Successfully followed @${username}.' };
} else {
return { ok: false, message: 'Follow action initiated but UI did not update.' };
}
} catch (e) {
return { ok: false, message: e.toString() };
}
})()`);
if (result.ok) await page.wait(2);
return [{
status: result.ok ? 'success' : 'failed',
message: result.message
}];
}
});
+5 -16
View File
@@ -1,5 +1,4 @@
import { cli, Strategy } from '../../registry.js';
import * as fs from 'fs';
cli({
site: 'twitter',
@@ -37,8 +36,8 @@ cli({
await page.goto(`https://x.com/${targetUser}`);
await page.wait(3);
// 2. Inject interceptor for Followers GraphQL API (or user_flow.json)
await page.installInterceptor('graphql');
// 2. Inject interceptor for the followers GraphQL API
await page.installInterceptor('Followers');
// 3. Click the followers link inside the profile page
await page.evaluate(`() => {
@@ -53,24 +52,14 @@ cli({
// 4. Retrieve data from opencli's registered interceptors
const allRequests = await page.getInterceptedRequests();
const requestList = Array.isArray(allRequests) ? allRequests : [];
// Debug: Force dump all intercepted XHRs that match followers
if (!allRequests || allRequests.length === 0) {
console.log('No GraphQL requests captured by the interceptor backend.');
if (requestList.length === 0) {
return [];
}
console.log('Intercepted keys:', allRequests.map((r: any) => {
try {
const u = new URL(r.url); return u.pathname;
} catch (e) {
return r.url;
}
}));
const requests = allRequests.filter((r: any) => r.url.includes('Followers'));
const requests = requestList.filter((r: any) => r?.url?.includes('Followers'));
if (!requests || requests.length === 0) {
console.log('No specific Followers requests captured. Check keys printed above.');
return [];
}
+3 -5
View File
@@ -1,5 +1,4 @@
import { cli, Strategy } from '../../registry.js';
import * as fs from 'fs';
cli({
site: 'twitter',
@@ -53,15 +52,14 @@ cli({
// 4. Retrieve data from opencli's registered interceptors
const requests = await page.getInterceptedRequests();
const requestList = Array.isArray(requests) ? requests : [];
// Debug: Force dump all intercepted XHRs that match following
if (!requests || requests.length === 0) {
console.log('No Following requests captured by the interceptor backend.');
if (requestList.length === 0) {
return [];
}
let results: any[] = [];
for (const req of requests) {
for (const req of requestList) {
try {
let instructions = req.data?.data?.user?.result?.timeline?.timeline?.instructions;
if (!instructions) continue;
-1
View File
@@ -15,7 +15,6 @@ cli({
func: async (page: IPage | null, kwargs: any) => {
if (!page) throw new Error('Requires browser');
console.log(`Navigating to tweet: ${kwargs.url}`);
await page.goto(kwargs.url);
await page.wait(5); // Wait for tweet to load completely
+19 -10
View File
@@ -1,5 +1,4 @@
import { cli, Strategy } from '../../registry.js';
import * as fs from 'fs';
cli({
site: 'twitter',
@@ -13,13 +12,16 @@ cli({
],
columns: ['id', 'action', 'author', 'text', 'url'],
func: async (page, kwargs) => {
// Install the interceptor before loading the notifications page so we
// capture the initial timeline request triggered during page load.
await page.goto('https://x.com');
await page.wait(2);
await page.installInterceptor('NotificationsTimeline');
// 1. Navigate to notifications
await page.goto('https://x.com/notifications');
await page.wait(5);
// 2. Inject interceptor
await page.installInterceptor('NotificationsTimeline');
// 3. Trigger API by scrolling (if we need to load more)
await page.autoScroll({ times: 2, delayMs: 2000 });
@@ -28,9 +30,10 @@ cli({
if (!requests || requests.length === 0) return [];
let results: any[] = [];
const seen = new Set<string>();
for (const req of requests) {
try {
let instructions = [];
let instructions: any[] = [];
if (req.data?.data?.viewer?.timeline_response?.timeline?.instructions) {
instructions = req.data.data.viewer.timeline_response.timeline.instructions;
} else if (req.data?.data?.viewer_v2?.user_results?.result?.notification_timeline?.timeline?.instructions) {
@@ -75,14 +78,16 @@ cli({
if (item.__typename === 'TimelineNotification') {
// Greet likes, retweet, mentions
text = item.rich_message?.text || item.message?.text || '';
author = item.template?.from_users?.[0]?.user_results?.result?.core?.screen_name || 'unknown';
const fromUser = item.template?.from_users?.[0]?.user_results?.result;
author = fromUser?.legacy?.screen_name || fromUser?.core?.screen_name || 'unknown';
urlStr = item.notification_url?.url || '';
actionText = item.notification_icon || 'Activity';
// If there's an attached tweet
const targetTweet = item.template?.target_objects?.[0]?.tweet_results?.result;
if (targetTweet) {
text += ' | ' + (targetTweet.legacy?.full_text || '');
const targetText = targetTweet.note_tweet?.note_tweet_results?.result?.text || targetTweet.legacy?.full_text || '';
text += text && targetText ? ' | ' + targetText : targetText;
if (!urlStr) {
urlStr = `https://x.com/i/status/${targetTweet.rest_id}`;
}
@@ -91,18 +96,22 @@ cli({
// Direct mention/reply
const tweet = item.tweet_result?.result;
author = tweet?.core?.user_results?.result?.legacy?.screen_name || 'unknown';
text = tweet?.legacy?.full_text || item.message?.text || '';
text = tweet?.note_tweet?.note_tweet_results?.result?.text || tweet?.legacy?.full_text || item.message?.text || '';
actionText = 'Mention/Reply';
urlStr = `https://x.com/i/status/${tweet?.rest_id}`;
} else if (item.__typename === 'Tweet') {
author = item.core?.user_results?.result?.legacy?.screen_name || 'unknown';
text = item.legacy?.full_text || '';
text = item.note_tweet?.note_tweet_results?.result?.text || item.legacy?.full_text || '';
actionText = 'Mention';
urlStr = `https://x.com/i/status/${item.rest_id}`;
}
const id = item.id || item.rest_id || entryId;
if (seen.has(id)) return;
seen.add(id);
results.push({
id: item.id || item.rest_id || entryId,
id,
action: actionText,
author: author,
text: text,
+114 -46
View File
@@ -3,59 +3,127 @@ import { cli, Strategy } from '../../registry.js';
cli({
site: 'twitter',
name: 'profile',
description: 'Fetch tweets from a user profile',
description: 'Fetch a Twitter user profile (bio, stats, etc.)',
domain: 'x.com',
strategy: Strategy.INTERCEPT,
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'username', type: 'string', required: true },
{ name: 'limit', type: 'int', default: 15 },
{ name: 'username', type: 'string', positional: true, help: 'Twitter screen name (without @). Defaults to logged-in user.' },
],
columns: ['id', 'text', 'likes', 'views', 'url'],
columns: ['screen_name', 'name', 'bio', 'location', 'url', 'followers', 'following', 'tweets', 'likes', 'verified', 'created_at'],
func: async (page, kwargs) => {
// Navigate to user profile via search for reliability
await page.goto(`https://x.com/search?q=from:${kwargs.username}&f=live`);
await page.wait(5);
let username = (kwargs.username || '').replace(/^@/, '');
// Inject XHR interceptor
await page.installInterceptor('SearchTimeline');
// Trigger API by scrolling
await page.autoScroll({ times: 3, delayMs: 2000 });
// Retrieve data
const requests = await page.getInterceptedRequests();
if (!requests || requests.length === 0) return [];
let results: any[] = [];
for (const req of requests) {
try {
const insts = req.data.data.search_by_raw_query.search_timeline.timeline.instructions;
const addEntries = insts.find((i: any) => i.type === 'TimelineAddEntries');
if (!addEntries) continue;
for (const entry of addEntries.entries) {
if (!entry.entryId.startsWith('tweet-')) continue;
let tweet = entry.content?.itemContent?.tweet_results?.result;
if (!tweet) continue;
if (tweet.__typename === 'TweetWithVisibilityResults' && tweet.tweet) {
tweet = tweet.tweet;
}
results.push({
id: tweet.rest_id,
text: tweet.legacy?.full_text || '',
likes: tweet.legacy?.favorite_count || 0,
views: tweet.views?.count || '0',
url: `https://x.com/i/status/${tweet.rest_id}`
});
}
} catch (e) {
}
// If no username, detect the logged-in user
if (!username) {
await page.goto('https://x.com/home');
await page.wait(5);
const href = await page.evaluate(`() => {
const link = document.querySelector('a[data-testid="AppTabBar_Profile_Link"]');
return link ? link.getAttribute('href') : null;
}`);
if (!href) throw new Error('Could not detect logged-in user. Are you logged in?');
username = href.replace('/', '');
}
return results.slice(0, kwargs.limit);
// Navigate directly to the user's profile page (gives us cookie context)
await page.goto(`https://x.com/${username}`);
await page.wait(3);
const result = await page.evaluate(`
async () => {
const screenName = "${username}";
const ct0 = document.cookie.split(';').map(c=>c.trim()).find(c=>c.startsWith('ct0='))?.split('=')[1];
if (!ct0) return {error: 'No ct0 cookie — not logged into x.com'};
const bearer = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA';
const headers = {
'Authorization': 'Bearer ' + decodeURIComponent(bearer),
'X-Csrf-Token': ct0,
'X-Twitter-Auth-Type': 'OAuth2Session',
'X-Twitter-Active-User': 'yes'
};
const variables = JSON.stringify({
screen_name: screenName,
withSafetyModeUserFields: true,
});
const features = JSON.stringify({
hidden_profile_subscriptions_enabled: true,
rweb_tipjar_consumption_enabled: true,
responsive_web_graphql_exclude_directive_enabled: true,
verified_phone_label_enabled: false,
subscriptions_verification_info_is_identity_verified_enabled: true,
subscriptions_verification_info_verified_since_enabled: true,
highlights_tweets_tab_ui_enabled: true,
responsive_web_twitter_article_notes_tab_enabled: true,
subscriptions_feature_can_gift_premium: true,
creator_subscriptions_tweet_preview_api_enabled: true,
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
responsive_web_graphql_timeline_navigation_enabled: true,
});
// Dynamically resolve queryId: GitHub community source → JS bundle scan → hardcoded fallback
async function resolveQueryId(operationName, fallbackId) {
try {
const ghResp = await fetch('https://raw.githubusercontent.com/fa0311/twitter-openapi/refs/heads/main/src/config/placeholder.json');
if (ghResp.ok) {
const data = await ghResp.json();
const entry = data[operationName];
if (entry && entry.queryId) return entry.queryId;
}
} catch {}
try {
const scripts = performance.getEntriesByType('resource')
.filter(r => r.name.includes('client-web') && r.name.endsWith('.js'))
.map(r => r.name);
for (const scriptUrl of scripts.slice(0, 15)) {
try {
const text = await (await fetch(scriptUrl)).text();
const re = new RegExp('queryId:"([A-Za-z0-9_-]+)"[^}]{0,200}operationName:"' + operationName + '"');
const m = text.match(re);
if (m) return m[1];
} catch {}
}
} catch {}
return fallbackId;
}
const queryId = await resolveQueryId('UserByScreenName', 'qRednkZG-rn1P6b48NINmQ');
const url = '/i/api/graphql/' + queryId + '/UserByScreenName?variables='
+ encodeURIComponent(variables)
+ '&features=' + encodeURIComponent(features);
const resp = await fetch(url, {headers, credentials: 'include'});
if (!resp.ok) return {error: 'HTTP ' + resp.status, hint: 'User may not exist or queryId expired'};
const d = await resp.json();
const result = d.data?.user?.result;
if (!result) return {error: 'User @' + screenName + ' not found'};
const legacy = result.legacy || {};
const expandedUrl = legacy.entities?.url?.urls?.[0]?.expanded_url || '';
return [{
screen_name: legacy.screen_name || screenName,
name: legacy.name || '',
bio: legacy.description || '',
location: legacy.location || '',
url: expandedUrl,
followers: legacy.followers_count || 0,
following: legacy.friends_count || 0,
tweets: legacy.statuses_count || 0,
likes: legacy.favourites_count || 0,
verified: result.is_blue_verified || legacy.verified || false,
created_at: legacy.created_at || '',
}];
}
`);
if (result?.error) {
throw new Error(result.error + (result.hint ? ` (${result.hint})` : ''));
}
return result || [];
}
});
+14 -7
View File
@@ -13,14 +13,17 @@ cli({
],
columns: ['id', 'author', 'text', 'likes', 'views', 'url'],
func: async (page, kwargs) => {
// Install the interceptor before opening the target page so we don't miss
// the initial SearchTimeline request fired during hydration.
await page.goto('https://x.com');
await page.wait(2);
await page.installInterceptor('SearchTimeline');
// 1. Navigate to the search page
const q = encodeURIComponent(kwargs.query);
await page.goto(`https://x.com/search?q=${q}&f=top`);
await page.wait(5);
// 2. Inject XHR interceptor
await page.installInterceptor('SearchTimeline');
// 3. Trigger API by scrolling
await page.autoScroll({ times: 3, delayMs: 2000 });
@@ -29,11 +32,13 @@ cli({
if (!requests || requests.length === 0) return [];
let results: any[] = [];
const seen = new Set<string>();
for (const req of requests) {
try {
const insts = req.data.data.search_by_raw_query.search_timeline.timeline.instructions;
const addEntries = insts.find((i: any) => i.type === 'TimelineAddEntries');
if (!addEntries) continue;
const insts = req.data?.data?.search_by_raw_query?.search_timeline?.timeline?.instructions || [];
const addEntries = insts.find((i: any) => i.type === 'TimelineAddEntries')
|| insts.find((i: any) => i.entries && Array.isArray(i.entries));
if (!addEntries?.entries) continue;
for (const entry of addEntries.entries) {
if (!entry.entryId.startsWith('tweet-')) continue;
@@ -45,11 +50,13 @@ cli({
if (tweet.__typename === 'TweetWithVisibilityResults' && tweet.tweet) {
tweet = tweet.tweet;
}
if (!tweet.rest_id || seen.has(tweet.rest_id)) continue;
seen.add(tweet.rest_id);
results.push({
id: tweet.rest_id,
author: tweet.core?.user_results?.result?.legacy?.screen_name || 'unknown',
text: tweet.legacy?.full_text || '',
text: tweet.note_tweet?.note_tweet_results?.result?.text || tweet.legacy?.full_text || '',
likes: tweet.legacy?.favorite_count || 0,
views: tweet.views?.count || '0',
url: `https://x.com/i/status/${tweet.rest_id}`
+181
View File
@@ -0,0 +1,181 @@
import { cli, Strategy } from '../../registry.js';
// ── Twitter GraphQL constants ──────────────────────────────────────────
const BEARER_TOKEN = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA';
const TWEET_DETAIL_QUERY_ID = 'nBS-WpgA6ZG0CyNHD517JQ';
const FEATURES = {
responsive_web_graphql_exclude_directive_enabled: true,
verified_phone_label_enabled: false,
creator_subscriptions_tweet_preview_api_enabled: true,
responsive_web_graphql_timeline_navigation_enabled: true,
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
longform_notetweets_consumption_enabled: true,
longform_notetweets_rich_text_read_enabled: true,
longform_notetweets_inline_media_enabled: true,
freedom_of_speech_not_reach_fetch_enabled: true,
};
const FIELD_TOGGLES = { withArticleRichContentState: true, withArticlePlainText: false };
// ── Pure functions (type-safe, testable) ───────────────────────────────
interface ThreadTweet {
id: string;
author: string;
text: string;
likes: number;
retweets: number;
in_reply_to?: string;
created_at?: string;
url: string;
}
function buildTweetDetailUrl(tweetId: string, cursor?: string | null): string {
const vars: Record<string, any> = {
focalTweetId: tweetId,
referrer: 'tweet',
with_rux_injections: false,
includePromotedContent: false,
rankingMode: 'Recency',
withCommunity: true,
withQuickPromoteEligibilityTweetFields: true,
withBirdwatchNotes: true,
withVoice: true,
};
if (cursor) vars.cursor = cursor;
return `/i/api/graphql/${TWEET_DETAIL_QUERY_ID}/TweetDetail`
+ `?variables=${encodeURIComponent(JSON.stringify(vars))}`
+ `&features=${encodeURIComponent(JSON.stringify(FEATURES))}`
+ `&fieldToggles=${encodeURIComponent(JSON.stringify(FIELD_TOGGLES))}`;
}
function extractTweet(r: any, seen: Set<string>): ThreadTweet | null {
if (!r) return null;
const tw = r.tweet || r;
const l = tw.legacy || {};
if (!tw.rest_id || seen.has(tw.rest_id)) return null;
seen.add(tw.rest_id);
const u = tw.core?.user_results?.result;
const noteText = tw.note_tweet?.note_tweet_results?.result?.text;
const screenName = u?.legacy?.screen_name || u?.core?.screen_name || 'unknown';
return {
id: tw.rest_id,
author: screenName,
text: noteText || l.full_text || '',
likes: l.favorite_count || 0,
retweets: l.retweet_count || 0,
in_reply_to: l.in_reply_to_status_id_str || undefined,
created_at: l.created_at,
url: `https://x.com/${screenName}/status/${tw.rest_id}`,
};
}
function parseTweetDetail(data: any, seen: Set<string>): { tweets: ThreadTweet[]; nextCursor: string | null } {
const tweets: ThreadTweet[] = [];
let nextCursor: string | null = null;
const instructions =
data?.data?.threaded_conversation_with_injections_v2?.instructions
|| data?.data?.tweetResult?.result?.timeline?.instructions
|| [];
for (const inst of instructions) {
for (const entry of inst.entries || []) {
// Cursor entries
const c = entry.content;
if (c?.entryType === 'TimelineTimelineCursor' || c?.__typename === 'TimelineTimelineCursor') {
if (c.cursorType === 'Bottom' || c.cursorType === 'ShowMore') nextCursor = c.value;
continue;
}
if (entry.entryId?.startsWith('cursor-bottom-') || entry.entryId?.startsWith('cursor-showMore-')) {
nextCursor = c?.itemContent?.value || c?.value || nextCursor;
continue;
}
// Direct tweet entry
const tw = extractTweet(c?.itemContent?.tweet_results?.result, seen);
if (tw) tweets.push(tw);
// Conversation module (nested replies)
for (const item of c?.items || []) {
const nested = extractTweet(item.item?.itemContent?.tweet_results?.result, seen);
if (nested) tweets.push(nested);
}
}
}
return { tweets, nextCursor };
}
// ── CLI definition ────────────────────────────────────────────────────
cli({
site: 'twitter',
name: 'thread',
description: 'Get a tweet thread (original + all replies)',
domain: 'x.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'tweet_id', type: 'string', required: true },
{ name: 'limit', type: 'int', default: 50 },
],
columns: ['id', 'author', 'text', 'likes', 'retweets', 'url'],
func: async (page, kwargs) => {
let tweetId = kwargs.tweet_id;
const urlMatch = tweetId.match(/\/status\/(\d+)/);
if (urlMatch) tweetId = urlMatch[1];
// Navigate to x.com for cookie context
await page.goto('https://x.com');
await page.wait(3);
// Extract CSRF token — the only thing we need from the browser
const ct0 = await page.evaluate(`() => {
return document.cookie.split(';').map(c=>c.trim()).find(c=>c.startsWith('ct0='))?.split('=')[1] || null;
}`);
if (!ct0) throw new Error('Not logged into x.com (no ct0 cookie)');
// Build auth headers in TypeScript
const headers = JSON.stringify({
'Authorization': `Bearer ${decodeURIComponent(BEARER_TOKEN)}`,
'X-Csrf-Token': ct0,
'X-Twitter-Auth-Type': 'OAuth2Session',
'X-Twitter-Active-User': 'yes',
});
// Paginate — fetch in browser, parse in TypeScript
const allTweets: ThreadTweet[] = [];
const seen = new Set<string>();
let cursor: string | null = null;
for (let i = 0; i < 5; i++) {
const apiUrl = buildTweetDetailUrl(tweetId, cursor);
// Browser-side: just fetch + return JSON (3 lines)
const data = await page.evaluate(`async () => {
const r = await fetch("${apiUrl}", { headers: ${headers}, credentials: 'include' });
return r.ok ? await r.json() : { error: r.status };
}`);
if (data?.error) {
if (allTweets.length === 0) throw new Error(`HTTP ${data.error}: Tweet not found or queryId expired`);
break;
}
// TypeScript-side: type-safe parsing + cursor extraction
const { tweets, nextCursor } = parseTweetDetail(data, seen);
allTweets.push(...tweets);
if (!nextCursor || nextCursor === cursor) break;
cursor = nextCursor;
}
return allTweets.slice(0, kwargs.limit);
},
});
+204 -36
View File
@@ -1,50 +1,218 @@
import { cli, Strategy } from '../../registry.js';
// ── Twitter GraphQL constants ──────────────────────────────────────────
const BEARER_TOKEN = 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA';
const HOME_TIMELINE_QUERY_ID = 'c-CzHF1LboFilMpsx4ZCrQ';
const FEATURES = {
rweb_video_screen_enabled: false,
profile_label_improvements_pcf_label_in_post_enabled: true,
rweb_tipjar_consumption_enabled: true,
verified_phone_label_enabled: false,
creator_subscriptions_tweet_preview_api_enabled: true,
responsive_web_graphql_timeline_navigation_enabled: true,
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
premium_content_api_read_enabled: false,
communities_web_enable_tweet_community_results_fetch: true,
c9s_tweet_anatomy_moderator_badge_enabled: true,
responsive_web_grok_analyze_button_fetch_trends_enabled: false,
responsive_web_grok_analyze_post_followups_enabled: true,
responsive_web_jetfuel_frame: false,
responsive_web_grok_share_attachment_enabled: true,
articles_preview_enabled: true,
responsive_web_edit_tweet_api_enabled: true,
graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
view_counts_everywhere_api_enabled: true,
longform_notetweets_consumption_enabled: true,
responsive_web_twitter_article_tweet_consumption_enabled: true,
tweet_awards_web_tipping_enabled: false,
responsive_web_grok_show_grok_translated_post: false,
responsive_web_grok_analysis_button_from_backend: false,
creator_subscriptions_quote_tweet_preview_enabled: false,
freedom_of_speech_not_reach_fetch_enabled: true,
standardized_nudges_misinfo: true,
tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,
longform_notetweets_rich_text_read_enabled: true,
longform_notetweets_inline_media_enabled: true,
responsive_web_grok_image_annotation_enabled: true,
responsive_web_enhance_cards_enabled: false,
};
// ── Pure functions (type-safe, testable) ───────────────────────────────
interface TimelineTweet {
id: string;
author: string;
text: string;
likes: number;
retweets: number;
replies: number;
views: number;
created_at: string;
url: string;
}
function buildHomeTimelineUrl(count: number, cursor?: string | null): string {
const vars: Record<string, any> = {
count,
includePromotedContent: false,
latestControlAvailable: true,
requestContext: 'launch',
withCommunity: true,
};
if (cursor) vars.cursor = cursor;
return `/i/api/graphql/${HOME_TIMELINE_QUERY_ID}/HomeTimeline`
+ `?variables=${encodeURIComponent(JSON.stringify(vars))}`
+ `&features=${encodeURIComponent(JSON.stringify(FEATURES))}`;
}
function extractTweet(result: any, seen: Set<string>): TimelineTweet | null {
if (!result) return null;
const tw = result.tweet || result;
const l = tw.legacy || {};
if (!tw.rest_id || seen.has(tw.rest_id)) return null;
seen.add(tw.rest_id);
const u = tw.core?.user_results?.result;
const screenName = u?.legacy?.screen_name || u?.core?.screen_name || 'unknown';
const noteText = tw.note_tweet?.note_tweet_results?.result?.text;
const views = tw.views?.count ? parseInt(tw.views.count, 10) : 0;
return {
id: tw.rest_id,
author: screenName,
text: noteText || l.full_text || '',
likes: l.favorite_count || 0,
retweets: l.retweet_count || 0,
replies: l.reply_count || 0,
views,
created_at: l.created_at || '',
url: `https://x.com/${screenName}/status/${tw.rest_id}`,
};
}
function parseHomeTimeline(data: any, seen: Set<string>): { tweets: TimelineTweet[]; nextCursor: string | null } {
const tweets: TimelineTweet[] = [];
let nextCursor: string | null = null;
const instructions =
data?.data?.home?.home_timeline_urt?.instructions || [];
for (const inst of instructions) {
for (const entry of inst.entries || []) {
const c = entry.content;
// Cursor entries
if (c?.entryType === 'TimelineTimelineCursor' || c?.__typename === 'TimelineTimelineCursor') {
if (c.cursorType === 'Bottom') nextCursor = c.value;
continue;
}
if (entry.entryId?.startsWith('cursor-bottom-')) {
nextCursor = c?.value || nextCursor;
continue;
}
// Single tweet entry
const tweetResult = c?.itemContent?.tweet_results?.result;
if (tweetResult) {
// Skip promoted content
if (c?.itemContent?.promotedMetadata) continue;
const tw = extractTweet(tweetResult, seen);
if (tw) tweets.push(tw);
continue;
}
// Conversation module (grouped tweets)
for (const item of c?.items || []) {
const nested = item.item?.itemContent?.tweet_results?.result;
if (nested) {
if (item.item?.itemContent?.promotedMetadata) continue;
const tw = extractTweet(nested, seen);
if (tw) tweets.push(tw);
}
}
}
}
return { tweets, nextCursor };
}
// ── CLI definition ────────────────────────────────────────────────────
cli({
site: 'twitter',
name: 'timeline',
description: 'Twitter Home Timeline',
description: 'Fetch Twitter Home Timeline',
domain: 'x.com',
strategy: Strategy.COOKIE,
browser: true,
args: [
{ name: 'limit', type: 'int', default: 20 },
],
columns: ['responseType', 'first'],
columns: ['id', 'author', 'text', 'likes', 'retweets', 'replies', 'views', 'created_at', 'url'],
func: async (page, kwargs) => {
await page.goto('https://x.com/home');
await page.wait(5);
// Inject the fetch interceptor manually to see exactly what happens
await page.evaluate(`
() => {
window.__intercept_data = [];
const origFetch = window.fetch;
window.fetch = async function(...args) {
let u = typeof args[0] === 'string' ? args[0] : (args[0] && args[0].url) || '';
const res = await origFetch.apply(this, args);
setTimeout(async () => {
try {
if (u.includes('HomeTimeline')) {
const clone = res.clone();
const j = await clone.json();
window.__intercept_data.push(j);
}
} catch(e) {}
}, 0);
return res;
};
const limit = kwargs.limit || 20;
// Navigate to x.com for cookie context
await page.goto('https://x.com');
await page.wait(3);
// Extract CSRF token
const ct0 = await page.evaluate(`() => {
return document.cookie.split(';').map(c=>c.trim()).find(c=>c.startsWith('ct0='))?.split('=')[1] || null;
}`);
if (!ct0) throw new Error('Not logged into x.com (no ct0 cookie)');
// Dynamically resolve queryId
const queryId = await page.evaluate(`async () => {
try {
const ghResp = await fetch('https://raw.githubusercontent.com/fa0311/twitter-openapi/refs/heads/main/src/config/placeholder.json');
if (ghResp.ok) {
const data = await ghResp.json();
const entry = data['HomeTimeline'];
if (entry && entry.queryId) return entry.queryId;
}
} catch {}
return null;
}`) || HOME_TIMELINE_QUERY_ID;
// Build auth headers
const headers = JSON.stringify({
'Authorization': `Bearer ${decodeURIComponent(BEARER_TOKEN)}`,
'X-Csrf-Token': ct0,
'X-Twitter-Auth-Type': 'OAuth2Session',
'X-Twitter-Active-User': 'yes',
});
// Paginate — fetch in browser, parse in TypeScript
const allTweets: TimelineTweet[] = [];
const seen = new Set<string>();
let cursor: string | null = null;
for (let i = 0; i < 5 && allTweets.length < limit; i++) {
const fetchCount = Math.min(40, limit - allTweets.length + 5); // over-fetch slightly for promoted filtering
const apiUrl = buildHomeTimelineUrl(fetchCount, cursor)
.replace(HOME_TIMELINE_QUERY_ID, queryId);
const data = await page.evaluate(`async () => {
const r = await fetch("${apiUrl}", { headers: ${headers}, credentials: 'include' });
return r.ok ? await r.json() : { error: r.status };
}`);
if (data?.error) {
if (allTweets.length === 0) throw new Error(`HTTP ${data.error}: Failed to fetch timeline. queryId may have expired.`);
break;
}
`);
// trigger scroll
for(let i=0; i<3; i++) {
await page.evaluate('() => window.scrollTo(0, document.body.scrollHeight)');
await page.wait(2);
const { tweets, nextCursor } = parseHomeTimeline(data, seen);
allTweets.push(...tweets);
if (!nextCursor || nextCursor === cursor) break;
cursor = nextCursor;
}
// extract
const data = await page.evaluate('() => window.__intercept_data');
if (!data || data.length === 0) return [{responseType: 'no data captured'}];
return [{responseType: `captured ${data.length} responses`, first: JSON.stringify(data[0]).substring(0,300)}];
}
return allTweets.slice(0, limit);
},
});
+8 -2
View File
@@ -25,9 +25,15 @@ pipeline:
credentials: 'include',
headers: { 'x-twitter-active-user': 'yes', 'x-csrf-token': csrfToken, 'authorization': 'Bearer ' + bearerToken }
});
if (!res.ok) throw new Error('HTTP ' + res.status + '. Hint: trending endpoint may require login or API shape changed.');
const data = await res.json();
const trends = data?.timeline?.instructions?.[1]?.addEntries?.entries || [];
return trends.filter(e => e.content?.timelineModule).flatMap(e => e.content.timelineModule.items || []).map(t => t?.item?.content?.trend).filter(Boolean);
const instructions = data?.timeline?.instructions || [];
const entries = instructions.flatMap(inst => inst?.addEntries?.entries || inst?.entries || []);
return entries
.filter(e => e.content?.timelineModule)
.flatMap(e => e.content.timelineModule.items || [])
.map(t => t?.item?.content?.trend)
.filter(Boolean);
})()
- map:
+66
View File
@@ -0,0 +1,66 @@
import { cli, Strategy } from '../../registry.js';
import type { IPage } from '../../types.js';
cli({
site: 'twitter',
name: 'unbookmark',
description: 'Remove a tweet from bookmarks',
domain: 'x.com',
strategy: Strategy.UI,
browser: true,
args: [
{ name: 'url', type: 'string', positional: true, required: true, help: 'Tweet URL to unbookmark' },
],
columns: ['status', 'message'],
func: async (page: IPage | null, kwargs: any) => {
if (!page) throw new Error('Requires browser');
await page.goto(kwargs.url);
await page.wait(5);
const result = await page.evaluate(`(async () => {
try {
let attempts = 0;
let removeBtn = null;
while (attempts < 20) {
// Check if not bookmarked
const bookmarkBtn = document.querySelector('[data-testid="bookmark"]');
if (bookmarkBtn) {
return { ok: true, message: 'Tweet is not bookmarked (already removed).' };
}
removeBtn = document.querySelector('[data-testid="removeBookmark"]');
if (removeBtn) break;
await new Promise(r => setTimeout(r, 500));
attempts++;
}
if (!removeBtn) {
return { ok: false, message: 'Could not find Remove Bookmark button. Are you logged in?' };
}
removeBtn.click();
await new Promise(r => setTimeout(r, 1000));
// Verify
const verify = document.querySelector('[data-testid="bookmark"]');
if (verify) {
return { ok: true, message: 'Tweet successfully removed from bookmarks.' };
} else {
return { ok: false, message: 'Unbookmark action initiated but UI did not update.' };
}
} catch (e) {
return { ok: false, message: e.toString() };
}
})()`);
if (result.ok) await page.wait(2);
return [{
status: result.ok ? 'success' : 'failed',
message: result.message
}];
}
});
+75
View File
@@ -0,0 +1,75 @@
import { cli, Strategy } from '../../registry.js';
import type { IPage } from '../../types.js';
cli({
site: 'twitter',
name: 'unfollow',
description: 'Unfollow a Twitter user',
domain: 'x.com',
strategy: Strategy.UI,
browser: true,
args: [
{ name: 'username', type: 'string', positional: true, required: true, help: 'Twitter screen name (without @)' },
],
columns: ['status', 'message'],
func: async (page: IPage | null, kwargs: any) => {
if (!page) throw new Error('Requires browser');
const username = kwargs.username.replace(/^@/, '');
await page.goto(`https://x.com/${username}`);
await page.wait(5);
const result = await page.evaluate(`(async () => {
try {
let attempts = 0;
let unfollowBtn = null;
while (attempts < 20) {
// Check if already not following
const followBtn = document.querySelector('[data-testid$="-follow"]');
if (followBtn) {
return { ok: true, message: 'Not following @${username} (already unfollowed).' };
}
unfollowBtn = document.querySelector('[data-testid$="-unfollow"]');
if (unfollowBtn) break;
await new Promise(r => setTimeout(r, 500));
attempts++;
}
if (!unfollowBtn) {
return { ok: false, message: 'Could not find Unfollow button. Are you logged in?' };
}
// Click the unfollow button — this opens a confirmation dialog
unfollowBtn.click();
await new Promise(r => setTimeout(r, 1000));
// Confirm the unfollow in the dialog
const confirmBtn = document.querySelector('[data-testid="confirmationSheetConfirm"]');
if (confirmBtn) {
confirmBtn.click();
await new Promise(r => setTimeout(r, 1000));
}
// Verify
const verify = document.querySelector('[data-testid$="-follow"]');
if (verify) {
return { ok: true, message: 'Successfully unfollowed @${username}.' };
} else {
return { ok: false, message: 'Unfollow action initiated but UI did not update.' };
}
} catch (e) {
return { ok: false, message: e.toString() };
}
})()`);
if (result.ok) await page.wait(2);
return [{
status: result.ok ? 'success' : 'failed',
message: result.message
}];
}
});
+1 -1
View File
@@ -11,7 +11,7 @@ cli({
domain: 'www.v2ex.com',
strategy: Strategy.COOKIE,
browser: true,
forceExtension: true,
args: [],
columns: ['status', 'message'],
func: async (page: IPage | null) => {
+1 -1
View File
@@ -11,7 +11,7 @@ cli({
domain: 'www.v2ex.com',
strategy: Strategy.COOKIE,
browser: true,
forceExtension: true,
args: [],
columns: ['username', 'balance', 'unread_notifications', 'daily_reward_ready'],
func: async (page: IPage | null) => {
+1 -1
View File
@@ -11,7 +11,7 @@ cli({
domain: 'www.v2ex.com',
strategy: Strategy.COOKIE,
browser: true,
forceExtension: true,
args: [
{ name: 'limit', type: 'int', default: 20, help: 'Number of notifications' }
],
+108
View File
@@ -0,0 +1,108 @@
import { describe, it, expect } from 'vitest';
import { groupTranscriptSegments, formatGroupedTranscript } from './transcript-group.js';
describe('groupTranscriptSegments', () => {
it('groups segments by sentence boundaries', () => {
const segments = [
{ start: 0, text: 'Hello there.' },
{ start: 2, text: 'How are you doing today?' },
{ start: 5, text: 'I am' },
{ start: 6, text: 'doing well.' },
];
const result = groupTranscriptSegments(segments);
expect(result).toHaveLength(3);
expect(result[0].text).toBe('Hello there.');
expect(result[1].text).toBe('How are you doing today?');
expect(result[2].text).toBe('I am doing well.');
});
it('flushes on large time gaps', () => {
const segments = [
{ start: 0, text: 'First part' },
{ start: 2, text: 'still first' },
{ start: 25, text: 'second part after gap' },
];
const result = groupTranscriptSegments(segments);
expect(result).toHaveLength(2);
expect(result[0].text).toBe('First part still first');
expect(result[1].text).toBe('second part after gap');
});
it('respects 30s max group span for unpunctuated text', () => {
// Simulate CJK captions without punctuation
const segments = Array.from({ length: 20 }, (_, i) => ({
start: i * 2,
text: `segment${i}`,
}));
const result = groupTranscriptSegments(segments);
// 20 segments * 2s = 40s total, should be split into at least 2 groups
expect(result.length).toBeGreaterThanOrEqual(2);
// No single group should span more than ~30s
for (const g of result) {
const words = g.text.split(' ');
// With 2s per segment and 30s max, each group should have at most ~16 segments
expect(words.length).toBeLessThanOrEqual(16);
}
});
it('detects speaker changes via >> markers', () => {
const segments = [
{ start: 0, text: '>> How are you?' },
{ start: 3, text: '>> I am fine.' },
];
const result = groupTranscriptSegments(segments);
expect(result.some(g => g.speakerChange)).toBe(true);
expect(result.some(g => g.speaker !== undefined)).toBe(true);
});
it('recognizes CJK sentence-ending punctuation', () => {
const segments = [
{ start: 0, text: '你好世界。' },
{ start: 2, text: '这是测试' },
{ start: 4, text: '内容。' },
];
const result = groupTranscriptSegments(segments);
expect(result).toHaveLength(2);
expect(result[0].text).toBe('你好世界。');
expect(result[1].text).toBe('这是测试 内容。');
});
it('returns empty array for empty input', () => {
expect(groupTranscriptSegments([])).toEqual([]);
});
});
describe('formatGroupedTranscript', () => {
it('formats timestamps correctly', () => {
const segments = [
{ start: 65, text: 'One minute five.', speakerChange: false },
{ start: 3661, text: 'One hour one minute.', speakerChange: false },
];
const { rows } = formatGroupedTranscript(segments);
expect(rows[0].timestamp).toBe('1:05');
expect(rows[1].timestamp).toBe('1:01:01');
});
it('inserts chapter headings at correct positions', () => {
const segments = [
{ start: 0, text: 'Intro text.', speakerChange: false },
{ start: 60, text: 'Chapter content.', speakerChange: false },
];
const chapters = [{ title: 'Introduction', start: 0 }, { title: 'Main', start: 50 }];
const { rows } = formatGroupedTranscript(segments, chapters);
expect(rows[0].text).toBe('[Chapter] Introduction');
expect(rows[1].text).toBe('Intro text.');
expect(rows[2].text).toBe('[Chapter] Main');
expect(rows[3].text).toBe('Chapter content.');
});
it('labels speakers', () => {
const segments = [
{ start: 0, text: 'Hello.', speakerChange: true, speaker: 0 },
{ start: 5, text: 'Hi there.', speakerChange: true, speaker: 1 },
];
const { rows } = formatGroupedTranscript(segments);
expect(rows[0].speaker).toBe('Speaker 1');
expect(rows[1].speaker).toBe('Speaker 2');
});
});
+287
View File
@@ -0,0 +1,287 @@
/**
* Transcript grouping: sentence merging, speaker detection, and chapter support.
* Ported and simplified from Defuddle's YouTube extractor.
*
* Raw segments (2-3 second fragments) are grouped into readable paragraphs:
* - Sentence boundaries: merge until sentence-ending punctuation (.!?)
* - Speaker turns: detect ">>" markers from YouTube auto-captions
* - Chapters: optional chapter headings inserted at appropriate timestamps
*/
// Include CJK sentence-ending punctuation: 。!? (fullwidth: .!?)
const SENTENCE_END = /[.!?\u3002\uFF01\uFF1F\uFF0E]["'\u2019\u201D)]*\s*$/;
const QUESTION_END = /[?\uFF1F]["'\u2019\u201D)]*\s*$/;
const TRANSCRIPT_GROUP_GAP_SECONDS = 20;
const TURN_MERGE_MAX_WORDS = 80;
const TURN_MERGE_MAX_SPAN_SECONDS = 45;
const SHORT_UTTERANCE_MAX_WORDS = 3;
const FIRST_GROUP_MERGE_MIN_WORDS = 8;
export interface RawSegment {
start: number;
end: number;
text: string;
}
export interface GroupedSegment {
start: number;
text: string;
speakerChange: boolean;
speaker?: number;
}
export interface Chapter {
title: string;
start: number;
}
function countWords(text: string): number {
return text.split(/\s+/).filter(Boolean).length;
}
/**
* Group raw transcript segments into readable blocks.
* If speaker markers (>>) are present, groups by speaker turn.
* Otherwise, groups by sentence boundaries.
*/
export function groupTranscriptSegments(
segments: { start: number; text: string }[],
): GroupedSegment[] {
if (segments.length === 0) return [];
const hasSpeakerMarkers = segments.some(s => /^>>/.test(s.text));
return hasSpeakerMarkers ? groupBySpeaker(segments) : groupBySentence(segments);
}
/**
* Format grouped segments + chapters into a final text output.
*/
export function formatGroupedTranscript(
segments: GroupedSegment[],
chapters: Chapter[] = [],
): { rows: Array<{ timestamp: string; speaker: string; text: string }>; plainText: string } {
const sortedChapters = [...chapters].sort((a, b) => a.start - b.start);
let chapterIdx = 0;
const rows: Array<{ timestamp: string; speaker: string; text: string }> = [];
const textParts: string[] = [];
for (const segment of segments) {
// Insert chapter headings
while (chapterIdx < sortedChapters.length && sortedChapters[chapterIdx].start <= segment.start) {
const title = sortedChapters[chapterIdx].title;
rows.push({ timestamp: fmtTime(sortedChapters[chapterIdx].start), speaker: '', text: `[Chapter] ${title}` });
if (textParts.length > 0) textParts.push('');
textParts.push(`### ${title}`);
textParts.push('');
chapterIdx++;
}
const timestamp = fmtTime(segment.start);
const speaker = segment.speaker !== undefined ? `Speaker ${segment.speaker + 1}` : '';
rows.push({ timestamp, speaker, text: segment.text });
if (segment.speakerChange && textParts.length > 0) {
textParts.push('');
}
textParts.push(`${timestamp} ${segment.text}`);
}
return { rows, plainText: textParts.join('\n') };
}
function fmtTime(sec: number): string {
const h = Math.floor(sec / 3600);
const m = Math.floor((sec % 3600) / 60);
const s = Math.floor(sec % 60);
if (h > 0) {
return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}
return `${m}:${String(s).padStart(2, '0')}`;
}
// ── Sentence grouping ─────────────────────────────────────────────────────
// Max time span (seconds) for a single group when no sentence boundaries are found.
// Prevents unbounded merging for languages without punctuation (Chinese, etc.).
const MAX_GROUP_SPAN_SECONDS = 30;
function groupBySentence(
segments: { start: number; text: string }[],
): GroupedSegment[] {
const groups: GroupedSegment[] = [];
let buffer = '';
let bufferStart = 0;
let lastStart = 0;
const flush = () => {
if (buffer.trim()) {
groups.push({ start: bufferStart, text: buffer.trim(), speakerChange: false });
buffer = '';
}
};
for (const seg of segments) {
// Large gap between segments — always flush
if (buffer && seg.start - lastStart > TRANSCRIPT_GROUP_GAP_SECONDS) {
flush();
}
// Time-based flush: prevent unbounded groups for unpunctuated languages
if (buffer && seg.start - bufferStart > MAX_GROUP_SPAN_SECONDS) {
flush();
}
if (!buffer) bufferStart = seg.start;
buffer += (buffer ? ' ' : '') + seg.text;
lastStart = seg.start;
if (SENTENCE_END.test(seg.text)) flush();
}
flush();
return groups;
}
// ── Speaker grouping ──────────────────────────────────────────────────────
function groupBySpeaker(
segments: { start: number; text: string }[],
): GroupedSegment[] {
type Turn = {
start: number;
segments: { start: number; text: string }[];
speakerChange: boolean;
speaker?: number;
};
const turns: Turn[] = [];
let currentTurn: Turn | null = null;
let speakerIndex = -1;
let prevSegText = '';
for (const seg of segments) {
const isSpeakerChange = /^>>/.test(seg.text);
const cleanText = seg.text.replace(/^>>\s*/, '').replace(/^-\s+/, '');
const prevEndsWithComma = /,\s*$/.test(prevSegText);
const prevEndedSentence = (SENTENCE_END.test(prevSegText) || !prevSegText) && !prevEndsWithComma;
const isRealSpeakerChange = isSpeakerChange && prevEndedSentence;
if (isRealSpeakerChange) {
if (currentTurn) turns.push(currentTurn);
speakerIndex = (speakerIndex + 1) % 2;
currentTurn = {
start: seg.start,
segments: [{ start: seg.start, text: cleanText }],
speakerChange: true,
speaker: speakerIndex,
};
} else {
if (!currentTurn) {
currentTurn = { start: seg.start, segments: [], speakerChange: false };
}
currentTurn.segments.push({ start: seg.start, text: cleanText });
}
prevSegText = cleanText;
}
if (currentTurn) turns.push(currentTurn);
splitAffirmativeTurns(turns);
const groups: GroupedSegment[] = [];
for (const turn of turns) {
const sentenceGroups = turn.speaker === undefined
? groupBySentence(turn.segments)
: mergeSentenceGroupsWithinTurn(groupBySentence(turn.segments));
for (let i = 0; i < sentenceGroups.length; i++) {
groups.push({
...sentenceGroups[i],
speakerChange: i === 0 && turn.speakerChange,
speaker: turn.speaker,
});
}
}
return groups;
}
function splitAffirmativeTurns(turns: Array<{
start: number;
segments: { start: number; text: string }[];
speakerChange: boolean;
speaker?: number;
}>): void {
const affirmativePattern = /^(mhm|yeah|yes|yep|right|okay|ok|absolutely|sure|exactly|uh-huh|mm-hmm)[.!,]?\s+/i;
for (let i = 0; i < turns.length; i++) {
const turn = turns[i];
if (turn.speaker === undefined || turn.segments.length === 0) continue;
const firstSeg = turn.segments[0];
const match = affirmativePattern.exec(firstSeg.text);
if (!match) continue;
if (/,\s*$/.test(match[0])) continue;
const remainder = firstSeg.text.slice(match[0].length).trim();
const restSegments = turn.segments.slice(1);
const restWords = countWords(remainder) + restSegments.reduce((sum, s) => sum + countWords(s.text), 0);
if (restWords < 30) continue;
const affirmativeText = match[0].trimEnd();
const newRestSegments = remainder
? [{ start: firstSeg.start, text: remainder }, ...restSegments]
: restSegments;
turns.splice(i, 1, {
start: turn.start,
segments: [{ start: firstSeg.start, text: affirmativeText }],
speakerChange: turn.speakerChange,
speaker: turn.speaker,
}, {
start: newRestSegments[0].start,
segments: newRestSegments,
speakerChange: true,
speaker: turn.speaker === 0 ? 1 : 0,
});
i++;
}
}
function mergeSentenceGroupsWithinTurn(groups: GroupedSegment[]): GroupedSegment[] {
if (groups.length <= 1) return groups;
const merged: GroupedSegment[] = [];
let current = { ...groups[0] };
let currentIsFirstInTurn = true;
for (let i = 1; i < groups.length; i++) {
const next = groups[i];
if (shouldMergeSentenceGroups(current, next, currentIsFirstInTurn)) {
current.text = `${current.text} ${next.text}`;
continue;
}
merged.push(current);
current = { ...next };
currentIsFirstInTurn = false;
}
merged.push(current);
return merged;
}
function shouldMergeSentenceGroups(
current: { start: number; text: string },
next: { start: number; text: string },
currentIsFirstInTurn: boolean,
): boolean {
const currentWords = countWords(current.text);
const nextWords = countWords(next.text);
if (isShortStandaloneUtterance(current.text, currentWords)
|| isShortStandaloneUtterance(next.text, nextWords)) return false;
if (currentIsFirstInTurn && currentWords < FIRST_GROUP_MERGE_MIN_WORDS) return false;
if (QUESTION_END.test(current.text) || QUESTION_END.test(next.text)) return false;
if (currentWords + nextWords > TURN_MERGE_MAX_WORDS) return false;
if (next.start - current.start > TURN_MERGE_MAX_SPAN_SECONDS) return false;
return true;
}
function isShortStandaloneUtterance(text: string, words?: number): boolean {
const w = words ?? countWords(text);
return w > 0 && w <= SHORT_UTTERANCE_MAX_WORDS && SENTENCE_END.test(text);
}
+280
View File
@@ -0,0 +1,280 @@
/**
* YouTube transcript — uses InnerTube player API with Android client context.
*
* The Web client's caption URLs require a PoToken (proof of origin) generated
* by BotGuard at runtime. The Android client returns caption URLs that work
* without PoToken — same approach used by youtube-transcript-api (Python).
*
* Modes:
* --mode grouped (default): sentences merged, speaker detection, chapters
* --mode raw: every caption segment as-is with precise timestamps
*/
import { cli, Strategy } from '../../registry.js';
import { parseVideoId } from './utils.js';
import {
groupTranscriptSegments,
formatGroupedTranscript,
type RawSegment,
type Chapter,
} from './transcript-group.js';
cli({
site: 'youtube',
name: 'transcript',
description: 'Get YouTube video transcript/subtitles',
domain: 'www.youtube.com',
strategy: Strategy.COOKIE,
args: [
{ name: 'url', required: true, help: 'YouTube video URL or video ID' },
{ name: 'lang', required: false, help: 'Language code (e.g. en, zh-Hans). Omit to auto-select' },
{ name: 'mode', required: false, default: 'grouped', help: 'Output mode: grouped (readable paragraphs) or raw (every segment)' },
],
// columns intentionally omitted — raw and grouped modes return different schemas,
// so we let the renderer auto-detect columns from the data keys.
func: async (page, kwargs) => {
const videoId = parseVideoId(kwargs.url);
const videoUrl = `https://www.youtube.com/watch?v=${videoId}`;
await page.goto(videoUrl);
await page.wait(3);
const lang = kwargs.lang || '';
const mode = kwargs.mode || 'grouped';
// Step 1: Get caption track URL via Android InnerTube API
const captionData = await page.evaluate(`
(async () => {
const cfg = window.ytcfg?.data_ || {};
const apiKey = cfg.INNERTUBE_API_KEY;
if (!apiKey) return { error: 'INNERTUBE_API_KEY not found on page' };
const resp = await fetch('/youtubei/v1/player?key=' + apiKey + '&prettyPrint=false', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
context: { client: { clientName: 'ANDROID', clientVersion: '20.10.38' } },
videoId: ${JSON.stringify(videoId)}
})
});
if (!resp.ok) return { error: 'InnerTube player API returned HTTP ' + resp.status };
const data = await resp.json();
const renderer = data.captions?.playerCaptionsTracklistRenderer;
if (!renderer?.captionTracks?.length) {
return { error: 'No captions available for this video' };
}
const tracks = renderer.captionTracks;
const available = tracks.map(t => t.languageCode + (t.kind === 'asr' ? ' (auto)' : ''));
const langPref = ${JSON.stringify(lang)};
let track = null;
if (langPref) {
track = tracks.find(t => t.languageCode === langPref)
|| tracks.find(t => t.languageCode.startsWith(langPref));
}
if (!track) {
track = tracks.find(t => t.kind !== 'asr') || tracks[0];
}
return {
captionUrl: track.baseUrl,
language: track.languageCode,
kind: track.kind || 'manual',
available,
requestedLang: langPref || null,
langMatched: !!(langPref && track.languageCode === langPref),
langPrefixMatched: !!(langPref && track.languageCode !== langPref && track.languageCode.startsWith(langPref))
};
})()
`);
if (!captionData || typeof captionData === 'string') {
throw new Error(`Failed to get caption info: ${typeof captionData === 'string' ? captionData : 'null response'}`);
}
if (captionData.error) {
throw new Error(`${captionData.error}${captionData.available ? ' (available: ' + captionData.available.join(', ') + ')' : ''}`);
}
// Warn if --lang was specified but not matched
if (captionData.requestedLang && !captionData.langMatched && !captionData.langPrefixMatched) {
console.error(`Warning: --lang "${captionData.requestedLang}" not found. Using "${captionData.language}" instead. Available: ${captionData.available.join(', ')}`);
}
// Step 2: Fetch caption XML and parse segments
const segments: RawSegment[] = await page.evaluate(`
(async () => {
const resp = await fetch(${JSON.stringify(captionData.captionUrl)});
const xml = await resp.text();
if (!xml?.length) {
return { error: 'Caption URL returned empty response' };
}
function getAttr(tag, name) {
const needle = name + '="';
const idx = tag.indexOf(needle);
if (idx === -1) return '';
const valStart = idx + needle.length;
const valEnd = tag.indexOf('"', valStart);
if (valEnd === -1) return '';
return tag.substring(valStart, valEnd);
}
function decodeEntities(s) {
return s
.replaceAll('&amp;', '&')
.replaceAll('&lt;', '<')
.replaceAll('&gt;', '>')
.replaceAll('&quot;', '"')
.replaceAll('&#39;', "'");
}
const isFormat3 = xml.includes('<p t="');
const marker = isFormat3 ? '<p ' : '<text ';
const endMarker = isFormat3 ? '</p>' : '</text>';
const results = [];
let pos = 0;
while (true) {
const tagStart = xml.indexOf(marker, pos);
if (tagStart === -1) break;
let contentStart = xml.indexOf('>', tagStart);
if (contentStart === -1) break;
contentStart += 1;
const tagEnd = xml.indexOf(endMarker, contentStart);
if (tagEnd === -1) break;
const attrStr = xml.substring(tagStart + marker.length, contentStart - 1);
const content = xml.substring(contentStart, tagEnd);
let startSec, durSec;
if (isFormat3) {
startSec = (parseFloat(getAttr(attrStr, 't')) || 0) / 1000;
durSec = (parseFloat(getAttr(attrStr, 'd')) || 0) / 1000;
} else {
startSec = parseFloat(getAttr(attrStr, 'start')) || 0;
durSec = parseFloat(getAttr(attrStr, 'dur')) || 0;
}
// Strip inner tags (e.g. <s> in srv3 format) and decode entities
const text = decodeEntities(content.replace(/<[^>]+>/g, '')).split('\\\\n').join(' ').trim();
if (text) {
results.push({ start: startSec, end: startSec + durSec, text });
}
pos = tagEnd + endMarker.length;
}
if (results.length === 0) {
return { error: 'Parsed 0 segments from caption XML' };
}
return results;
})()
`);
if (!Array.isArray(segments)) {
throw new Error((segments as any)?.error || 'Failed to parse caption segments');
}
if (segments.length === 0) {
throw new Error('No caption segments found');
}
// Step 3: Fetch chapters (for grouped mode)
let chapters: Chapter[] = [];
if (mode === 'grouped') {
try {
const chapterData = await page.evaluate(`
(async () => {
const cfg = window.ytcfg?.data_ || {};
const apiKey = cfg.INNERTUBE_API_KEY;
if (!apiKey) return [];
const resp = await fetch('/youtubei/v1/next?key=' + apiKey + '&prettyPrint=false', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
context: { client: { clientName: 'WEB', clientVersion: '2.20240101.00.00' } },
videoId: ${JSON.stringify(videoId)}
})
});
if (!resp.ok) return [];
const data = await resp.json();
const chapters = [];
// Try chapterRenderer from player bar
const panels = data.playerOverlays?.playerOverlayRenderer
?.decoratedPlayerBarRenderer?.decoratedPlayerBarRenderer
?.playerBar?.multiMarkersPlayerBarRenderer?.markersMap;
if (Array.isArray(panels)) {
for (const panel of panels) {
const markers = panel.value?.chapters;
if (!Array.isArray(markers)) continue;
for (const marker of markers) {
const ch = marker.chapterRenderer;
if (!ch) continue;
const title = ch.title?.simpleText || '';
const startMs = ch.timeRangeStartMillis;
if (title && typeof startMs === 'number') {
chapters.push({ title, start: startMs / 1000 });
}
}
}
}
if (chapters.length > 0) return chapters;
// Fallback: macroMarkersListItemRenderer from engagement panels
const engPanels = data.engagementPanels;
if (!Array.isArray(engPanels)) return [];
for (const ep of engPanels) {
const content = ep.engagementPanelSectionListRenderer?.content;
const items = content?.macroMarkersListRenderer?.contents;
if (!Array.isArray(items)) continue;
for (const item of items) {
const renderer = item.macroMarkersListItemRenderer;
if (!renderer) continue;
const t = renderer.title?.simpleText || '';
const ts = renderer.timeDescription?.simpleText || '';
if (!t || !ts) continue;
const parts = ts.split(':').map(Number);
let secs = null;
if (parts.length === 3 && parts.every(n => !isNaN(n))) secs = parts[0]*3600 + parts[1]*60 + parts[2];
else if (parts.length === 2 && parts.every(n => !isNaN(n))) secs = parts[0]*60 + parts[1];
if (secs !== null) chapters.push({ title: t, start: secs });
}
}
return chapters;
})()
`);
if (Array.isArray(chapterData)) {
chapters = chapterData;
}
} catch {
// Chapters are optional — proceed without them
}
}
// Step 4: Format output based on mode
if (mode === 'raw') {
// Precise timestamps in seconds with decimals, matching bilibili/subtitle format
return segments.map((seg, i) => ({
index: i + 1,
start: Number(seg.start).toFixed(2) + 's',
end: Number(seg.end).toFixed(2) + 's',
text: seg.text,
}));
}
// Grouped mode: merge sentences, detect speakers, insert chapters
const grouped = groupTranscriptSegments(
segments.map(s => ({ start: s.start, text: s.text })),
);
const { rows } = formatGroupedTranscript(grouped, chapters);
return rows;
},
});
+28
View File
@@ -0,0 +1,28 @@
/**
* Shared YouTube utilities — URL parsing, video ID extraction, etc.
*/
/**
* Extract a YouTube video ID from a URL or bare video ID string.
* Supports: watch?v=, youtu.be/, /shorts/, /embed/, /live/, /v/
*/
export function parseVideoId(input: string): string {
if (!input.startsWith('http')) return input;
try {
const parsed = new URL(input);
if (parsed.searchParams.has('v')) {
return parsed.searchParams.get('v')!;
}
if (parsed.hostname === 'youtu.be') {
return parsed.pathname.slice(1).split('/')[0];
}
// Handle /shorts/xxx, /embed/xxx, /live/xxx, /v/xxx
const pathMatch = parsed.pathname.match(/^\/(shorts|embed|live|v)\/([^/?]+)/);
if (pathMatch) return pathMatch[2];
} catch {
// Not a valid URL — treat entire input as video ID
}
return input;
}
+116
View File
@@ -0,0 +1,116 @@
/**
* YouTube video metadata — read ytInitialPlayerResponse + ytInitialData from video page.
*/
import { cli, Strategy } from '../../registry.js';
import { parseVideoId } from './utils.js';
cli({
site: 'youtube',
name: 'video',
description: 'Get YouTube video metadata (title, views, description, etc.)',
domain: 'www.youtube.com',
strategy: Strategy.COOKIE,
args: [
{ name: 'url', required: true, help: 'YouTube video URL or video ID' },
],
columns: ['field', 'value'],
func: async (page, kwargs) => {
const videoId = parseVideoId(kwargs.url);
const videoUrl = `https://www.youtube.com/watch?v=${videoId}`;
await page.goto(videoUrl);
await page.wait(3);
const data = await page.evaluate(`
(async () => {
const player = window.ytInitialPlayerResponse;
const yt = window.ytInitialData;
if (!player) return { error: 'ytInitialPlayerResponse not found' };
const details = player.videoDetails || {};
const microformat = player.microformat?.playerMicroformatRenderer || {};
// Try to get full description from ytInitialData
let fullDescription = details.shortDescription || '';
try {
const contents = yt?.contents?.twoColumnWatchNextResults
?.results?.results?.contents;
if (contents) {
for (const c of contents) {
const desc = c.videoSecondaryInfoRenderer?.attributedDescription?.content;
if (desc) { fullDescription = desc; break; }
}
}
} catch {}
// Get like count if available
let likes = '';
try {
const contents = yt?.contents?.twoColumnWatchNextResults
?.results?.results?.contents;
if (contents) {
for (const c of contents) {
const buttons = c.videoPrimaryInfoRenderer?.videoActions
?.menuRenderer?.topLevelButtons;
if (buttons) {
for (const b of buttons) {
const toggle = b.segmentedLikeDislikeButtonViewModel
?.likeButtonViewModel?.likeButtonViewModel?.toggleButtonViewModel
?.toggleButtonViewModel?.defaultButtonViewModel?.buttonViewModel;
if (toggle?.title) { likes = toggle.title; break; }
}
}
}
}
} catch {}
// Get publish date
const publishDate = microformat.publishDate
|| microformat.uploadDate
|| details.publishDate || '';
// Get category
const category = microformat.category || '';
// Get channel subscriber count if available
let subscribers = '';
try {
const contents = yt?.contents?.twoColumnWatchNextResults
?.results?.results?.contents;
if (contents) {
for (const c of contents) {
const owner = c.videoSecondaryInfoRenderer?.owner
?.videoOwnerRenderer?.subscriberCountText?.simpleText;
if (owner) { subscribers = owner; break; }
}
}
} catch {}
return {
title: details.title || '',
channel: details.author || '',
channelId: details.channelId || '',
videoId: details.videoId || '',
views: details.viewCount || '',
likes,
subscribers,
duration: details.lengthSeconds ? details.lengthSeconds + 's' : '',
publishDate,
category,
description: fullDescription,
keywords: (details.keywords || []).join(', '),
isLive: details.isLiveContent || false,
thumbnail: details.thumbnail?.thumbnails?.slice(-1)?.[0]?.url || '',
};
})()
`);
if (!data || typeof data !== 'object') throw new Error('Failed to extract video metadata from page');
if (data.error) throw new Error(data.error);
// Return as field/value pairs for table display
return Object.entries(data).map(([field, value]) => ({
field,
value: String(value),
}));
},
});
+129
View File
@@ -0,0 +1,129 @@
/**
* Shell tab-completion support for opencli.
*
* Provides:
* - Shell script generators for bash, zsh, and fish
* - Dynamic completion logic that returns candidates for the current cursor position
*/
import { getRegistry } from './registry.js';
import { CliError } from './errors.js';
// ── Dynamic completion logic ───────────────────────────────────────────────
/**
* Built-in (non-dynamic) top-level commands.
*/
const BUILTIN_COMMANDS = [
'list',
'validate',
'verify',
'explore',
'probe', // alias for explore
'synthesize',
'generate',
'cascade',
'doctor',
'setup',
'completion',
];
/**
* Return completion candidates given the current command-line words and cursor index.
*
* @param words - The argv after 'opencli' (words[0] is the first arg, e.g. site name)
* @param cursor - 1-based position of the word being completed (1 = first arg)
*/
export function getCompletions(words: string[], cursor: number): string[] {
// cursor === 1 → completing the first argument (site name or built-in command)
if (cursor <= 1) {
const sites = new Set<string>();
for (const [, cmd] of getRegistry()) {
sites.add(cmd.site);
}
return [...BUILTIN_COMMANDS, ...sites].sort();
}
const site = words[0];
// If the first word is a built-in command, no further completion
if (BUILTIN_COMMANDS.includes(site)) {
return [];
}
// cursor === 2 → completing the sub-command name under a site
if (cursor === 2) {
const subcommands: string[] = [];
for (const [, cmd] of getRegistry()) {
if (cmd.site === site) {
subcommands.push(cmd.name);
}
}
return subcommands.sort();
}
// cursor >= 3 → no further completion
return [];
}
// ── Shell script generators ────────────────────────────────────────────────
export function bashCompletionScript(): string {
return `# Bash completion for opencli
# Add to ~/.bashrc: eval "$(opencli completion bash)"
_opencli_completions() {
local cur words cword
_get_comp_words_by_ref -n : cur words cword
local completions
completions=$(opencli --get-completions --cursor "$cword" "\${words[@]:1}" 2>/dev/null)
COMPREPLY=( $(compgen -W "$completions" -- "$cur") )
__ltrim_colon_completions "$cur"
}
complete -F _opencli_completions opencli
`;
}
export function zshCompletionScript(): string {
return `# Zsh completion for opencli
# Add to ~/.zshrc: eval "$(opencli completion zsh)"
_opencli() {
local -a completions
local cword=$((CURRENT - 1))
completions=(\${(f)"$(opencli --get-completions --cursor "$cword" "\${words[@]:1}" 2>/dev/null)"})
compadd -a completions
}
compdef _opencli opencli
`;
}
export function fishCompletionScript(): string {
return `# Fish completion for opencli
# Add to ~/.config/fish/config.fish: opencli completion fish | source
complete -c opencli -f -a '(
set -l tokens (commandline -cop)
set -l cursor (count (commandline -cop))
opencli --get-completions --cursor $cursor $tokens[2..] 2>/dev/null
)'
`;
}
/**
* Print the completion script for the requested shell.
*/
export function printCompletionScript(shell: string): void {
switch (shell) {
case 'bash':
process.stdout.write(bashCompletionScript());
break;
case 'zsh':
process.stdout.write(zshCompletionScript());
break;
case 'fish':
process.stdout.write(fishCompletionScript());
break;
default:
throw new CliError('UNSUPPORTED_SHELL', `Unsupported shell: ${shell}. Supported: bash, zsh, fish`);
}
}
+35
View File
@@ -0,0 +1,35 @@
/**
* Shared constants used across explore, synthesize, and pipeline modules.
*/
/** URL query params that are volatile/ephemeral and should be stripped from patterns */
export const VOLATILE_PARAMS = new Set([
'w_rid', 'wts', '_', 'callback', 'timestamp', 't', 'nonce', 'sign',
]);
/** Search-related query parameter names */
export const SEARCH_PARAMS = new Set([
'q', 'query', 'keyword', 'search', 'wd', 'kw', 'search_query', 'w',
]);
/** Pagination-related query parameter names */
export const PAGINATION_PARAMS = new Set([
'page', 'pn', 'offset', 'cursor', 'next', 'page_num',
]);
/** Limit/page-size query parameter names */
export const LIMIT_PARAMS = new Set([
'limit', 'count', 'size', 'per_page', 'page_size', 'ps', 'num',
]);
/** Field role → common API field names mapping */
export const FIELD_ROLES: Record<string, string[]> = {
title: ['title', 'name', 'text', 'content', 'desc', 'description', 'headline', 'subject'],
url: ['url', 'uri', 'link', 'href', 'permalink', 'jump_url', 'web_url', 'share_url'],
author: ['author', 'username', 'user_name', 'nickname', 'nick', 'owner', 'creator', 'up_name', 'uname'],
score: ['score', 'hot', 'heat', 'likes', 'like_count', 'view_count', 'views', 'play', 'favorite_count', 'reply_count'],
time: ['time', 'created_at', 'publish_time', 'pub_time', 'date', 'ctime', 'mtime', 'pubdate', 'created'],
id: ['id', 'aid', 'bvid', 'mid', 'uid', 'oid', 'note_id', 'item_id'],
cover: ['cover', 'pic', 'image', 'thumbnail', 'poster', 'avatar'],
category: ['category', 'tag', 'type', 'tname', 'channel', 'section'],
};
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, it } from 'vitest';
import {
canonicalizeProductUrl,
dedupeSearchItems,
normalizeProductId,
normalizeSearchItem,
sanitizeSearchItems,
} from './coupang.js';
describe('normalizeProductId', () => {
it('extracts product id from canonical path', () => {
expect(normalizeProductId('https://www.coupang.com/vp/products/123456789')).toBe('123456789');
});
it('preserves numeric ids', () => {
expect(normalizeProductId('987654321')).toBe('987654321');
});
});
describe('canonicalizeProductUrl', () => {
it('normalizes relative Coupang paths', () => {
expect(canonicalizeProductUrl('/vp/products/123456789?itemId=1', '')).toBe(
'https://www.coupang.com/vp/products/123456789'
);
});
it('builds url from product id', () => {
expect(canonicalizeProductUrl('', '123456789')).toBe('https://www.coupang.com/vp/products/123456789');
});
});
describe('normalizeSearchItem', () => {
it('maps raw fields into compare-ready shape', () => {
const item = normalizeSearchItem({
productId: '123456789',
productName: '무선 마우스',
salePrice: '29,900원',
originalPrice: '39,900원',
rating: '4.8',
reviewCount: '1,234',
sellerName: '쿠팡',
badge: ['ROCKET', 'TOMORROW', '무료배송'],
categoryName: 'PC',
url: '/vp/products/123456789?itemId=1',
}, 0);
expect(item).toMatchObject({
rank: 1,
product_id: '123456789',
title: '무선 마우스',
price: 29900,
original_price: 39900,
rating: 4.8,
review_count: 1234,
rocket: '로켓배송',
delivery_type: '무료배송',
delivery_promise: '내일도착',
seller: '쿠팡',
category: 'PC',
url: 'https://www.coupang.com/vp/products/123456789',
});
});
});
describe('sanitizeSearchItems', () => {
it('drops duplicates and invalid rows', () => {
const rows = [
normalizeSearchItem({ productId: '1', productName: 'A', price: '1000', url: '/vp/products/1' }, 0),
normalizeSearchItem({ productId: '1', productName: 'A', price: '1000', url: '/vp/products/1' }, 1),
normalizeSearchItem({ productId: '', productName: '', price: '1000' }, 2),
normalizeSearchItem({ productId: '2', productName: 'B', price: '2000', url: '/vp/products/2' }, 3),
];
expect(dedupeSearchItems(rows)).toHaveLength(3);
expect(sanitizeSearchItems(rows, 10)).toHaveLength(2);
expect(sanitizeSearchItems(rows, 10).map(item => item.rank)).toEqual([1, 2]);
});
});
+302
View File
@@ -0,0 +1,302 @@
export interface CoupangSearchItem {
rank: number;
product_id: string;
title: string;
price: number | null;
original_price: number | null;
unit_price: string;
discount_rate: number | null;
rating: number | null;
review_count: number | null;
rocket: string;
delivery_type: string;
delivery_promise: string;
seller: string;
badge: string;
category: string;
url: string;
}
function itemKey(item: CoupangSearchItem): string {
return item.url || item.product_id || `${item.title}:${item.price ?? ''}`;
}
const ROCKET_PATTERNS = ['판매자로켓', '로켓프레시', '로켓와우', '로켓배송', '로켓직구'] as const;
const DELIVERY_TYPE_PATTERNS = ['무료배송', '일반배송'] as const;
const DELIVERY_PROMISE_PATTERNS = ['오늘도착', '내일도착', '새벽도착', '오늘출발'] as const;
const BADGE_ID_TO_ROCKET: Record<string, string> = {
ROCKET: '로켓배송',
ROCKET_MERCHANT: '판매자로켓',
ROCKET_WOW: '로켓와우',
WOW: '로켓와우',
ROCKET_FRESH: '로켓프레시',
FRESH: '로켓프레시',
SELLER_ROCKET: '판매자로켓',
ROCKET_JIKGU: '로켓직구',
JIKGU: '로켓직구',
COUPANG_GLOBAL: '로켓직구',
};
const BADGE_ID_TO_PROMISE: Record<string, string> = {
DAWN: '새벽도착',
EARLY_DAWN: '새벽도착',
TOMORROW: '내일도착',
TODAY: '오늘도착',
SAME_DAY: '오늘도착',
TODAY_SHIP: '오늘출발',
TODAY_DISPATCH: '오늘출발',
};
function asString(value: unknown): string {
if (value == null) return '';
return String(value).trim();
}
function toNumber(value: unknown): number | null {
if (typeof value === 'number' && Number.isFinite(value)) return value;
const text = asString(value).replace(/[^\d.]/g, '');
if (!text) return null;
const num = Number(text);
return Number.isFinite(num) ? num : null;
}
function pickFirst(obj: Record<string, unknown>, paths: string[]): unknown {
for (const path of paths) {
const parts = path.split('.');
let current: unknown = obj;
let ok = true;
for (const part of parts) {
if (!current || typeof current !== 'object' || !(part in (current as Record<string, unknown>))) {
ok = false;
break;
}
current = (current as Record<string, unknown>)[part];
}
if (ok && current != null && asString(current) !== '') return current;
}
return null;
}
export function normalizeProductId(raw: unknown): string {
const text = asString(raw);
if (!text) return '';
const match = text.match(/\/vp\/products\/(\d+)/) || text.match(/\b(\d{6,})\b/);
return match?.[1] ?? text;
}
export function canonicalizeProductUrl(rawUrl: unknown, productId?: unknown): string {
const raw = asString(rawUrl);
if (raw) {
try {
const url = new URL(raw.startsWith('http') ? raw : `https://www.coupang.com${raw}`);
if (!url.hostname.includes('coupang.com')) return '';
const id = normalizeProductId(url.pathname) || normalizeProductId(productId);
if (!id) return url.toString();
return `https://www.coupang.com/vp/products/${id}`;
} catch {
return '';
}
}
const id = normalizeProductId(productId);
return id ? `https://www.coupang.com/vp/products/${id}` : '';
}
function extractTokens(values: unknown[]): string[] {
return values
.flatMap((value) => {
const text = asString(value);
if (!text) return [];
return text.split(/[,\s|]+/);
})
.map((token) => token.trim().toUpperCase())
.filter(Boolean);
}
function normalizeJoinedText(...values: unknown[]): string {
return values
.map(asString)
.filter(Boolean)
.join(' ')
.replace(/schema\.org\/[A-Za-z]+/gi, ' ')
.replace(/\s+/g, ' ')
.trim();
}
function normalizeRocket(...values: unknown[]): string {
const tokens = extractTokens(values);
for (const token of tokens) {
if (BADGE_ID_TO_ROCKET[token]) return BADGE_ID_TO_ROCKET[token];
}
const text = normalizeJoinedText(...values);
if (!text) return '';
if (/판매자\s*로켓/.test(text)) return '판매자로켓';
if (/로켓\s*프레시|새벽\s*도착\s*보장/.test(text)) return '로켓프레시';
if (/로켓\s*와우/.test(text)) return '로켓와우';
if (/로켓\s*직구|직구/.test(text)) return '로켓직구';
if (/로켓\s*배송/.test(text)) return '로켓배송';
return ROCKET_PATTERNS.find(pattern => text.includes(pattern)) ?? '';
}
function normalizeDeliveryType(...values: unknown[]): string {
const text = normalizeJoinedText(...values);
if (!text) return '';
if (/무료\s*배송/.test(text)) return '무료배송';
if (/일반\s*배송/.test(text)) return '일반배송';
return DELIVERY_TYPE_PATTERNS.find(pattern => text.includes(pattern)) ?? '';
}
function normalizeDeliveryPromise(...values: unknown[]): string {
const tokens = extractTokens(values);
for (const token of tokens) {
if (BADGE_ID_TO_PROMISE[token]) return BADGE_ID_TO_PROMISE[token];
}
const text = normalizeJoinedText(...values);
if (!text) return '';
if (/오늘\s*출발/.test(text)) return '오늘출발';
if (/오늘.*도착/.test(text)) return '오늘도착';
if (/새벽.*도착/.test(text)) return '새벽도착';
if (/내일.*도착/.test(text)) return '내일도착';
return DELIVERY_PROMISE_PATTERNS.find(pattern => text.includes(pattern)) ?? '';
}
function normalizeBadge(value: unknown): string {
const normalizeOne = (entry: unknown): string => {
const text = asString(entry);
if (!text) return '';
if (/schema\.org\//i.test(text)) {
return text.split('/').pop() ?? '';
}
return text;
};
if (Array.isArray(value)) {
return value.map(normalizeOne).filter(Boolean).join(', ');
}
return normalizeOne(value);
}
export function normalizeSearchItem(raw: Record<string, unknown>, index: number): CoupangSearchItem {
const productId = normalizeProductId(
pickFirst(raw, ['productId', 'product_id', 'id', 'productNo', 'item.id', 'product.productId', 'url'])
);
const title = asString(
pickFirst(raw, ['title', 'name', 'productName', 'productTitle', 'itemName', 'item.title'])
);
const price = toNumber(
pickFirst(raw, ['price', 'salePrice', 'finalPrice', 'sellingPrice', 'discountPrice', 'item.price'])
);
const originalPrice = toNumber(
pickFirst(raw, ['originalPrice', 'basePrice', 'listPrice', 'originPrice', 'strikePrice'])
);
const unitPrice = asString(
pickFirst(raw, ['unitPrice', 'unit_price', 'unitPriceText'])
);
const rating = toNumber(
pickFirst(raw, ['rating', 'star', 'reviewRating', 'review.rating', 'item.rating'])
);
const reviewCount = toNumber(
pickFirst(raw, ['reviewCount', 'ratingCount', 'reviews', 'reviewCnt', 'item.reviewCount'])
);
const deliveryHintValues = [
pickFirst(raw, ['deliveryType', 'deliveryBadge', 'badgeLabel', 'shippingType', 'shippingBadge']),
pickFirst(raw, ['badge', 'badges', 'labels', 'benefitBadge', 'promotionBadge']),
pickFirst(raw, ['text', 'summary']),
pickFirst(raw, ['deliveryPromise', 'promise', 'arrivalText', 'arrivalBadge']),
pickFirst(raw, ['rocket', 'rocketType']),
];
const deliveryType = normalizeDeliveryType(...deliveryHintValues);
const deliveryPromise = normalizeDeliveryPromise(...deliveryHintValues);
const rocket = normalizeRocket(...deliveryHintValues);
const badge = normalizeBadge(
pickFirst(raw, ['badge', 'badges', 'labels', 'benefitBadge', 'promotionBadge'])
);
const category = asString(
pickFirst(raw, ['category', 'categoryName', 'categoryPath', 'item.category'])
);
const seller = asString(
pickFirst(raw, ['seller', 'sellerName', 'vendorName', 'merchantName', 'item.seller'])
);
const url = canonicalizeProductUrl(
pickFirst(raw, ['url', 'productUrl', 'link', 'item.url']),
productId
);
const discountRate = toNumber(
pickFirst(raw, ['discountRate', 'discount', 'discountPercent', 'discount_rate'])
);
return {
rank: index + 1,
product_id: productId,
title,
price,
original_price: originalPrice,
unit_price: unitPrice,
discount_rate: discountRate,
rating,
review_count: reviewCount,
rocket,
delivery_type: deliveryType,
delivery_promise: deliveryPromise,
seller,
badge,
category,
url,
};
}
export function dedupeSearchItems(items: CoupangSearchItem[]): CoupangSearchItem[] {
const seen = new Set<string>();
const out: CoupangSearchItem[] = [];
for (const item of items) {
const key = itemKey(item);
if (!key || seen.has(key)) continue;
seen.add(key);
out.push({ ...item, rank: out.length + 1 });
}
return out;
}
export function sanitizeSearchItems(items: CoupangSearchItem[], limit: number): CoupangSearchItem[] {
return dedupeSearchItems(
items.filter(item => Boolean(item.title && (item.product_id || item.url)))
).slice(0, limit);
}
export function mergeSearchItems(base: CoupangSearchItem[], extra: CoupangSearchItem[], limit: number): CoupangSearchItem[] {
const extraMap = new Map<string, CoupangSearchItem>();
for (const item of extra) {
const key = itemKey(item);
if (key) extraMap.set(key, item);
}
const merged = base.map((item) => {
const key = itemKey(item);
const patch = key ? extraMap.get(key) : null;
if (!patch) return item;
return {
...item,
price: patch.price ?? item.price,
original_price: patch.original_price ?? item.original_price,
unit_price: patch.unit_price || item.unit_price,
discount_rate: patch.discount_rate ?? item.discount_rate,
rating: patch.rating ?? item.rating,
review_count: patch.review_count ?? item.review_count,
rocket: patch.rocket || item.rocket,
delivery_type: patch.delivery_type || item.delivery_type,
delivery_promise: patch.delivery_promise || item.delivery_promise,
seller: patch.seller || item.seller,
badge: patch.badge || item.badge,
category: patch.category || item.category,
url: patch.url || item.url,
};
});
const mergedKeys = new Set(merged.map(item => itemKey(item)).filter(Boolean));
const appended = extra.filter(item => {
const key = itemKey(item);
return key && !mergedKeys.has(key);
});
return sanitizeSearchItems([...merged, ...appended], limit);
}
+62 -107
View File
@@ -2,132 +2,87 @@ import { describe, expect, it } from 'vitest';
import {
readTokenFromShellContent,
renderBrowserDoctorReport,
upsertShellToken,
readTomlConfigToken,
upsertTomlConfigToken,
upsertJsonConfigToken,
} from './doctor.js';
describe('shell token helpers', () => {
it('reads token from shell export', () => {
expect(readTokenFromShellContent('export PLAYWRIGHT_MCP_EXTENSION_TOKEN="abc123"\n')).toBe('abc123');
});
it('appends token export when missing', () => {
const next = upsertShellToken('export PATH="/usr/bin"\n', 'abc123');
expect(next).toContain('export PLAYWRIGHT_MCP_EXTENSION_TOKEN="abc123"');
});
it('replaces token export when present', () => {
const next = upsertShellToken('export PLAYWRIGHT_MCP_EXTENSION_TOKEN="old"\n', 'new');
expect(next).toContain('export PLAYWRIGHT_MCP_EXTENSION_TOKEN="new"');
expect(next).not.toContain('"old"');
});
});
describe('toml token helpers', () => {
it('reads token from playwright env section', () => {
const content = `
[mcp_servers.playwright.env]
PLAYWRIGHT_MCP_EXTENSION_TOKEN = "abc123"
`;
expect(readTomlConfigToken(content)).toBe('abc123');
});
it('updates token inside existing env section', () => {
const content = `
[mcp_servers.playwright.env]
PLAYWRIGHT_MCP_EXTENSION_TOKEN = "old"
`;
const next = upsertTomlConfigToken(content, 'new');
expect(next).toContain('PLAYWRIGHT_MCP_EXTENSION_TOKEN = "new"');
expect(next).not.toContain('"old"');
});
it('creates env section when missing', () => {
const content = `
[mcp_servers.playwright]
type = "stdio"
`;
const next = upsertTomlConfigToken(content, 'abc123');
expect(next).toContain('[mcp_servers.playwright.env]');
expect(next).toContain('PLAYWRIGHT_MCP_EXTENSION_TOKEN = "abc123"');
});
});
describe('json token helpers', () => {
it('writes token into standard mcpServers config', () => {
const next = upsertJsonConfigToken(JSON.stringify({
mcpServers: {
playwright: {
command: 'npx',
args: ['-y', '@playwright/mcp@latest', '--extension'],
},
},
}), 'abc123');
const parsed = JSON.parse(next);
expect(parsed.mcpServers.playwright.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN).toBe('abc123');
});
it('writes token into opencode mcp config', () => {
const next = upsertJsonConfigToken(JSON.stringify({
$schema: 'https://opencode.ai/config.json',
mcp: {
playwright: {
command: ['npx', '-y', '@playwright/mcp@latest', '--extension'],
enabled: true,
type: 'local',
},
},
}), 'abc123');
const parsed = JSON.parse(next);
expect(parsed.mcp.playwright.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN).toBe('abc123');
});
});
describe('doctor report rendering', () => {
const strip = (s: string) => s.replace(/\x1b\[[0-9;]*m/g, '');
it('renders OK-style report when tokens match', () => {
const text = renderBrowserDoctorReport({
const text = strip(renderBrowserDoctorReport({
envToken: 'abc123',
envFingerprint: 'fp1',
shellFiles: [{ path: '/tmp/.zshrc', exists: true, token: 'abc123', fingerprint: 'fp1' }],
configs: [{ path: '/tmp/mcp.json', exists: true, format: 'json', token: 'abc123', fingerprint: 'fp1', writable: true }],
remoteDebuggingEnabled: true,
remoteDebuggingEndpoint: 'ws://127.0.0.1:9222/devtools/browser/test',
cdpEnabled: false,
cdpToken: null,
cdpFingerprint: null,
extensionToken: 'abc123',
extensionInstalled: true,
extensionBrowsers: ['Chrome'],
shellFiles: [{ path: '/tmp/.zshrc', exists: true, token: 'abc123' }],
configs: [{ path: '/tmp/mcp.json', exists: true, format: 'json', token: 'abc123', writable: true }],
recommendedToken: 'abc123',
recommendedFingerprint: 'fp1',
warnings: [],
issues: [],
});
}));
expect(text).toContain('[OK] Chrome remote debugging: enabled');
expect(text).toContain('[OK] Environment token: configured (fp1)');
expect(text).toContain('[OK] MCP config /tmp/mcp.json: configured (fp1)');
expect(text).toContain('[OK] Extension installed (Chrome)');
expect(text).toContain('[OK] Environment token: configured');
expect(text).toContain('[OK] /tmp/mcp.json');
expect(text).toContain('configured');
});
it('renders MISMATCH-style report when fingerprints differ', () => {
const text = renderBrowserDoctorReport({
it('renders MISSING-style report when components are not installed', () => {
const text = strip(renderBrowserDoctorReport({
envToken: 'abc123',
envFingerprint: 'fp1',
shellFiles: [{ path: '/tmp/.zshrc', exists: true, token: 'def456', fingerprint: 'fp2' }],
configs: [{ path: '/tmp/mcp.json', exists: true, format: 'json', token: 'abc123', fingerprint: 'fp1', writable: true }],
remoteDebuggingEnabled: false,
remoteDebuggingEndpoint: null,
cdpEnabled: false,
cdpToken: null,
cdpFingerprint: null,
extensionToken: null,
extensionInstalled: false,
extensionBrowsers: [],
shellFiles: [{ path: '/tmp/.zshrc', exists: true, token: 'def456' }],
configs: [{ path: '/tmp/mcp.json', exists: true, format: 'json', token: 'abc123', writable: true }],
recommendedToken: 'abc123',
recommendedFingerprint: 'fp1',
warnings: ['Chrome remote debugging appears to be disabled or Chrome is not currently exposing a DevTools endpoint.'],
issues: ['Detected inconsistent Playwright MCP tokens across env/config files.'],
});
warnings: [],
issues: [],
}));
expect(text).toContain('[WARN] Chrome remote debugging: disabled');
expect(text).toContain('[MISMATCH] Environment token: configured (fp1)');
expect(text).toContain('[MISMATCH] Shell file /tmp/.zshrc: configured (fp2)');
expect(text).toContain('[MISMATCH] Recommended token fingerprint: fp1');
expect(text).toContain('[MISSING] Extension not installed in any browser');
expect(text).toContain('[OK] Environment token: configured');
expect(text).toContain('[OK] /tmp/.zshrc');
expect(text).toContain('configured');
expect(text).toContain('[OK] Token Configuration: Not required for OpenCLI MCP');
});
it('renders connectivity OK when live test succeeds', () => {
const text = strip(renderBrowserDoctorReport({
envToken: 'abc123',
extensionToken: 'abc123',
extensionInstalled: true,
extensionBrowsers: ['Chrome'],
shellFiles: [],
configs: [],
recommendedToken: 'abc123',
connectivity: { ok: true, durationMs: 1234 },
warnings: [],
issues: [],
}));
expect(text).toContain('[OK] Browser connectivity: connected in 1.2s');
});
it('renders connectivity WARN when not tested', () => {
const text = strip(renderBrowserDoctorReport({
envToken: 'abc123',
extensionToken: 'abc123',
extensionInstalled: true,
extensionBrowsers: ['Chrome'],
shellFiles: [],
configs: [],
recommendedToken: 'abc123',
warnings: [],
issues: [],
}));
expect(text).toContain('[WARN] Browser connectivity: not tested (use --live)');
});
});
+352 -211
View File
@@ -1,19 +1,22 @@
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { createInterface } from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
import chalk from 'chalk';
import type { IPage } from './types.js';
import { PlaywrightMCP, discoverChromeEndpoint, getTokenFingerprint } from './browser.js';
import { PlaywrightMCP } from './browser/index.js';
import { browserSession } from './runtime.js';
const PLAYWRIGHT_SERVER_NAME = 'playwright';
const PLAYWRIGHT_TOKEN_ENV = 'PLAYWRIGHT_MCP_EXTENSION_TOKEN';
export const PLAYWRIGHT_TOKEN_ENV = 'PLAYWRIGHT_MCP_EXTENSION_TOKEN';
const PLAYWRIGHT_EXTENSION_ID = 'mmlmfjhmonkocbjadbfplnigmagldckm';
const TOKEN_LINE_RE = /^(\s*export\s+PLAYWRIGHT_MCP_EXTENSION_TOKEN=)(['"]?)([^'"\\\n]+)\2\s*$/m;
export type DoctorOptions = {
fix?: boolean;
yes?: boolean;
live?: boolean;
shellRc?: string;
configPaths?: string[];
token?: string;
@@ -24,7 +27,6 @@ export type ShellFileStatus = {
path: string;
exists: boolean;
token: string | null;
fingerprint: string | null;
};
export type McpConfigFormat = 'json' | 'toml';
@@ -34,41 +36,67 @@ export type McpConfigStatus = {
exists: boolean;
format: McpConfigFormat;
token: string | null;
fingerprint: string | null;
writable: boolean;
parseError?: string;
};
export type ConnectivityResult = {
ok: boolean;
error?: string;
durationMs: number;
};
export type DoctorReport = {
cliVersion?: string;
envToken: string | null;
envFingerprint: string | null;
extensionToken: string | null;
extensionInstalled: boolean;
extensionBrowsers: string[];
shellFiles: ShellFileStatus[];
configs: McpConfigStatus[];
remoteDebuggingEnabled: boolean;
remoteDebuggingEndpoint: string | null;
cdpEnabled: boolean;
cdpToken: string | null;
cdpFingerprint: string | null;
recommendedToken: string | null;
recommendedFingerprint: string | null;
connectivity?: ConnectivityResult;
warnings: string[];
issues: string[];
};
type ReportStatus = 'OK' | 'MISSING' | 'MISMATCH' | 'WARN';
function label(status: ReportStatus): string {
return `[${status}]`;
function colorLabel(status: ReportStatus): string {
switch (status) {
case 'OK': return chalk.green('[OK]');
case 'MISSING': return chalk.red('[MISSING]');
case 'MISMATCH': return chalk.yellow('[MISMATCH]');
case 'WARN': return chalk.yellow('[WARN]');
}
}
function statusLine(status: ReportStatus, text: string): string {
return `${label(status)} ${text}`;
return `${colorLabel(status)} ${text}`;
}
function tokenSummary(token: string | null, fingerprint: string | null): string {
if (!token) return 'missing';
return `configured (${fingerprint})`;
function tokenSummary(token: string | null): string {
if (!token) return chalk.dim('missing');
return `configured`;
}
export function shortenPath(p: string): string {
const home = os.homedir();
return home && p.startsWith(home) ? '~' + p.slice(home.length) : p;
}
export function toolName(p: string): string {
if (p.includes('.codex/')) return 'Codex';
if (p.includes('.cursor/')) return 'Cursor';
if (p.includes('.claude.json')) return 'Claude Code';
if (p.includes('antigravity')) return 'Antigravity';
if (p.includes('.gemini/settings')) return 'Gemini CLI';
if (p.includes('opencode')) return 'OpenCode';
if (p.includes('Claude/claude_desktop')) return 'Claude Desktop';
if (p.includes('.vscode/')) return 'VS Code';
if (p.includes('.mcp.json')) return 'Project MCP';
if (p.includes('.zshrc') || p.includes('.bashrc') || p.includes('.profile')) return 'Shell';
return '';
}
export function getDefaultShellRcPath(): string {
@@ -78,18 +106,31 @@ export function getDefaultShellRcPath(): string {
return path.join(os.homedir(), '.zshrc');
}
function isFishConfig(filePath: string): boolean {
return filePath.endsWith('config.fish') || filePath.includes('/fish/');
}
/** Detect if a JSON config file uses OpenCode's `mcp` format vs standard `mcpServers` */
function isOpenCodeConfig(filePath: string): boolean {
return filePath.includes('opencode');
}
export function getDefaultMcpConfigPaths(cwd: string = process.cwd()): string[] {
const home = os.homedir();
const candidates = [
path.join(home, '.codex', 'config.toml'),
path.join(home, '.codex', 'mcp.json'),
path.join(home, '.cursor', 'mcp.json'),
path.join(home, '.claude.json'),
path.join(home, '.gemini', 'settings.json'),
path.join(home, '.gemini', 'antigravity', 'mcp_config.json'),
path.join(home, '.config', 'opencode', 'opencode.json'),
path.join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'),
path.join(home, '.config', 'Claude', 'claude_desktop_config.json'),
path.join(cwd, '.cursor', 'mcp.json'),
path.join(cwd, '.vscode', 'mcp.json'),
path.join(cwd, '.opencode', 'opencode.json'),
path.join(cwd, '.mcp.json'),
];
return [...new Set(candidates)];
}
@@ -99,83 +140,9 @@ export function readTokenFromShellContent(content: string): string | null {
return m?.[3] ?? null;
}
export function upsertShellToken(content: string, token: string): string {
const nextLine = `export ${PLAYWRIGHT_TOKEN_ENV}="${token}"`;
if (!content.trim()) return `${nextLine}\n`;
if (TOKEN_LINE_RE.test(content)) return content.replace(TOKEN_LINE_RE, `$1"${
token
}"`);
return `${content.replace(/\s*$/, '')}\n${nextLine}\n`;
}
function readJsonConfigToken(content: string): string | null {
try {
const parsed = JSON.parse(content);
return readTokenFromJsonObject(parsed);
} catch {
return null;
}
}
function readTokenFromJsonObject(parsed: any): string | null {
const direct = parsed?.mcpServers?.[PLAYWRIGHT_SERVER_NAME]?.env?.[PLAYWRIGHT_TOKEN_ENV];
if (typeof direct === 'string' && direct) return direct;
const opencode = parsed?.mcp?.[PLAYWRIGHT_SERVER_NAME]?.env?.[PLAYWRIGHT_TOKEN_ENV];
if (typeof opencode === 'string' && opencode) return opencode;
return null;
}
export function upsertJsonConfigToken(content: string, token: string): string {
const parsed = content.trim() ? JSON.parse(content) : {};
if (parsed?.mcpServers) {
parsed.mcpServers[PLAYWRIGHT_SERVER_NAME] = parsed.mcpServers[PLAYWRIGHT_SERVER_NAME] ?? {
command: 'npx',
args: ['-y', '@playwright/mcp@latest', '--extension'],
};
parsed.mcpServers[PLAYWRIGHT_SERVER_NAME].env = parsed.mcpServers[PLAYWRIGHT_SERVER_NAME].env ?? {};
parsed.mcpServers[PLAYWRIGHT_SERVER_NAME].env[PLAYWRIGHT_TOKEN_ENV] = token;
} else {
parsed.mcp = parsed.mcp ?? {};
parsed.mcp[PLAYWRIGHT_SERVER_NAME] = parsed.mcp[PLAYWRIGHT_SERVER_NAME] ?? {
command: ['npx', '-y', '@playwright/mcp@latest', '--extension'],
enabled: true,
type: 'local',
};
parsed.mcp[PLAYWRIGHT_SERVER_NAME].env = parsed.mcp[PLAYWRIGHT_SERVER_NAME].env ?? {};
parsed.mcp[PLAYWRIGHT_SERVER_NAME].env[PLAYWRIGHT_TOKEN_ENV] = token;
}
return `${JSON.stringify(parsed, null, 2)}\n`;
}
export function readTomlConfigToken(content: string): string | null {
const sectionMatch = content.match(/\[mcp_servers\.playwright\.env\][\s\S]*?(?=\n\[|$)/);
if (!sectionMatch) return null;
const tokenMatch = sectionMatch[0].match(/^\s*PLAYWRIGHT_MCP_EXTENSION_TOKEN\s*=\s*"([^"\n]+)"/m);
return tokenMatch?.[1] ?? null;
}
export function upsertTomlConfigToken(content: string, token: string): string {
const envSectionRe = /(\[mcp_servers\.playwright\.env\][\s\S]*?)(?=\n\[|$)/;
const tokenLine = `PLAYWRIGHT_MCP_EXTENSION_TOKEN = "${token}"`;
if (envSectionRe.test(content)) {
return content.replace(envSectionRe, (section) => {
if (/^\s*PLAYWRIGHT_MCP_EXTENSION_TOKEN\s*=/m.test(section)) {
return section.replace(/^\s*PLAYWRIGHT_MCP_EXTENSION_TOKEN\s*=.*$/m, tokenLine);
}
return `${section.replace(/\s*$/, '')}\n${tokenLine}\n`;
});
}
const baseSectionRe = /(\[mcp_servers\.playwright\][\s\S]*?)(?=\n\[|$)/;
if (baseSectionRe.test(content)) {
return content.replace(baseSectionRe, (section) => `${section.replace(/\s*$/, '')}\n\n[mcp_servers.playwright.env]\n${tokenLine}\n`);
}
const prefix = content.trim() ? `${content.replace(/\s*$/, '')}\n\n` : '';
return `${prefix}[mcp_servers.playwright]\ntype = "stdio"\ncommand = "npx"\nargs = ["-y", "@playwright/mcp@latest", "--extension"]\n\n[mcp_servers.playwright.env]\n${tokenLine}\n`;
}
function fileExists(filePath: string): boolean {
export function fileExists(filePath: string): boolean {
try {
return fs.existsSync(filePath);
} catch {
@@ -199,17 +166,17 @@ function canWrite(filePath: string): boolean {
function readConfigStatus(filePath: string): McpConfigStatus {
const format: McpConfigFormat = filePath.endsWith('.toml') ? 'toml' : 'json';
if (!fileExists(filePath)) {
return { path: filePath, exists: false, format, token: null, fingerprint: null, writable: canWrite(filePath) };
return { path: filePath, exists: false, format, token: null, writable: canWrite(filePath) };
}
try {
const content = fs.readFileSync(filePath, 'utf-8');
const token = format === 'toml' ? readTomlConfigToken(content) : readJsonConfigToken(content);
// Deprecated token extraction.
const token = null;
return {
path: filePath,
exists: true,
format,
token,
fingerprint: getTokenFingerprint(token ?? undefined),
writable: canWrite(filePath),
};
} catch (error: any) {
@@ -218,158 +185,361 @@ function readConfigStatus(filePath: string): McpConfigStatus {
exists: true,
format,
token: null,
fingerprint: null,
writable: canWrite(filePath),
parseError: error?.message ?? String(error),
};
}
}
async function extractTokenViaCdp(): Promise<string | null> {
if (!(process.env.OPENCLI_USE_CDP === '1' || process.env.OPENCLI_CDP_ENDPOINT))
return null;
const candidates = [
`chrome-extension://${PLAYWRIGHT_EXTENSION_ID}/options.html`,
`chrome-extension://${PLAYWRIGHT_EXTENSION_ID}/popup.html`,
`chrome-extension://${PLAYWRIGHT_EXTENSION_ID}/connect.html`,
`chrome-extension://${PLAYWRIGHT_EXTENSION_ID}/index.html`,
];
const result = await browserSession(PlaywrightMCP, async (page: IPage) => {
for (const url of candidates) {
try {
await page.goto(url);
await page.wait(1);
const token = await page.evaluate(`() => {
const values = new Set();
const push = (value) => {
if (!value || typeof value !== 'string') return;
for (const match of value.matchAll(/[A-Za-z0-9_-]{24,}/g)) values.add(match[0]);
};
document.querySelectorAll('input, textarea, code, pre, span, div').forEach((el) => {
push(el.value);
push(el.textContent || '');
push(el.getAttribute && el.getAttribute('value'));
});
return Array.from(values);
}`);
const matches = Array.isArray(token) ? token.filter((v: string) => v.length >= 24) : [];
if (matches.length > 0) return matches.sort((a: string, b: string) => b.length - a.length)[0];
} catch {}
/**
* Dynamically enumerate Chrome profiles by scanning for 'Default' and 'Profile *'
* directories across all browser base paths. Falls back to ['Default'] if none found.
*/
function enumerateProfiles(baseDirs: string[]): string[] {
const profiles = new Set<string>();
for (const base of baseDirs) {
if (!fileExists(base)) continue;
try {
for (const entry of fs.readdirSync(base, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
if (entry.name === 'Default' || /^Profile \d+$/.test(entry.name)) {
profiles.add(entry.name);
}
}
} catch { /* permission denied, etc. */ }
}
return profiles.size > 0 ? [...profiles].sort() : ['Default'];
}
/**
* Discover the auth token stored by the Playwright MCP Bridge extension
* by scanning Chrome's LevelDB localStorage files directly.
*
* Reads LevelDB .ldb/.log files as raw binary and searches for the
* extension ID near base64url token values. This works reliably across
* platforms because LevelDB's internal encoding can split ASCII strings
* like "auth-token" and the extension ID across byte boundaries, making
* text-based tools like `strings` + `grep` unreliable.
*/
export function discoverExtensionToken(): string | null {
const home = os.homedir();
const platform = os.platform();
const bases: string[] = [];
if (platform === 'darwin') {
bases.push(
path.join(home, 'Library', 'Application Support', 'Google', 'Chrome'),
path.join(home, 'Library', 'Application Support', 'Google', 'Chrome Dev'),
path.join(home, 'Library', 'Application Support', 'Google', 'Chrome Beta'),
path.join(home, 'Library', 'Application Support', 'Google', 'Chrome Canary'),
path.join(home, 'Library', 'Application Support', 'Chromium'),
path.join(home, 'Library', 'Application Support', 'Microsoft Edge'),
);
} else if (platform === 'linux') {
bases.push(
path.join(home, '.config', 'google-chrome'),
path.join(home, '.config', 'google-chrome-unstable'),
path.join(home, '.config', 'google-chrome-beta'),
path.join(home, '.config', 'chromium'),
path.join(home, '.config', 'microsoft-edge'),
);
} else if (platform === 'win32') {
const appData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
bases.push(
path.join(appData, 'Google', 'Chrome', 'User Data'),
path.join(appData, 'Google', 'Chrome Dev', 'User Data'),
path.join(appData, 'Google', 'Chrome Beta', 'User Data'),
path.join(appData, 'Microsoft', 'Edge', 'User Data'),
);
}
const profiles = enumerateProfiles(bases);
const tokenRe = /([A-Za-z0-9_-]{40,50})/;
for (const base of bases) {
for (const profile of profiles) {
const dir = path.join(base, profile, 'Local Storage', 'leveldb');
if (!fileExists(dir)) continue;
const token = extractTokenViaBinaryRead(dir, tokenRe);
if (token) return token;
}
return null;
}
return null;
}
function extractTokenViaBinaryRead(dir: string, tokenRe: RegExp): string | null {
// LevelDB fragments strings across byte boundaries, so we can't search
// for the full extension ID or "auth-token" as contiguous ASCII. Instead,
// search for a short prefix of the extension ID that reliably appears as
// contiguous bytes, then scan a window around each match for a base64url
// token value.
//
// Observed LevelDB layout near the auth-token entry:
// ... auth-t<binary> ... 4,mmlmfjh<binary>Pocbjadbfplnigmagldckm.7 ...
// <binary> hqI86ncsD1QpcVcj-k9CyzTF-ieCQd_4KreZ_wy1WHA <binary> ...
//
// The extension ID prefix "mmlmfjh" appears ~44 bytes before the token.
const extIdBuf = Buffer.from(PLAYWRIGHT_EXTENSION_ID);
const extIdPrefix = Buffer.from(PLAYWRIGHT_EXTENSION_ID.slice(0, 7)); // "mmlmfjh"
let files: string[];
try {
files = fs.readdirSync(dir)
.filter(f => f.endsWith('.ldb') || f.endsWith('.log'))
.map(f => path.join(dir, f));
} catch { return null; }
// Sort by mtime descending so we find the freshest token first
files.sort((a, b) => {
try { return fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs; } catch { return 0; }
});
return typeof result === 'string' && result ? result : null;
for (const file of files) {
let data: Buffer;
try { data = fs.readFileSync(file); } catch { continue; }
// Quick check: file must contain at least the prefix
if (data.indexOf(extIdPrefix) === -1) continue;
// Strategy 1: scan after each occurrence of the extension ID prefix
// for base64url tokens within a 500-byte window
let idx = 0;
while (true) {
const pos = data.indexOf(extIdPrefix, idx);
if (pos === -1) break;
const scanStart = pos;
const scanEnd = Math.min(data.length, pos + 500);
const window = data.subarray(scanStart, scanEnd).toString('latin1');
const m = window.match(tokenRe);
if (m && validateBase64urlToken(m[1])) {
// Make sure this isn't another extension ID that happens to match
if (m[1] !== PLAYWRIGHT_EXTENSION_ID) return m[1];
}
idx = pos + 1;
}
// Strategy 2 (fallback): original approach using full extension ID + auth-token key
const keyBuf = Buffer.from('auth-token');
idx = 0;
while (true) {
const kp = data.indexOf(keyBuf, idx);
if (kp === -1) break;
const contextStart = Math.max(0, kp - 500);
if (data.indexOf(extIdBuf, contextStart) !== -1 && data.indexOf(extIdBuf, contextStart) < kp) {
const after = data.subarray(kp + keyBuf.length, kp + keyBuf.length + 200).toString('latin1');
const m = after.match(tokenRe);
if (m && validateBase64urlToken(m[1])) return m[1];
}
idx = kp + 1;
}
}
return null;
}
function validateBase64urlToken(token: string): boolean {
try {
const b64 = token.replace(/-/g, '+').replace(/_/g, '/');
const decoded = Buffer.from(b64, 'base64');
return decoded.length >= 28 && decoded.length <= 36;
} catch { return false; }
}
/**
* Check whether the Playwright MCP Bridge extension is installed in any browser.
* Scans Chrome/Chromium/Edge Extensions directories for the known extension ID.
*/
export function checkExtensionInstalled(): { installed: boolean; browsers: string[] } {
const home = os.homedir();
const platform = os.platform();
const browserDirs: Array<{ name: string; base: string }> = [];
if (platform === 'darwin') {
browserDirs.push(
{ name: 'Chrome', base: path.join(home, 'Library', 'Application Support', 'Google', 'Chrome') },
{ name: 'Chrome Dev', base: path.join(home, 'Library', 'Application Support', 'Google', 'Chrome Dev') },
{ name: 'Chrome Beta', base: path.join(home, 'Library', 'Application Support', 'Google', 'Chrome Beta') },
{ name: 'Chrome Canary', base: path.join(home, 'Library', 'Application Support', 'Google', 'Chrome Canary') },
{ name: 'Chromium', base: path.join(home, 'Library', 'Application Support', 'Chromium') },
{ name: 'Edge', base: path.join(home, 'Library', 'Application Support', 'Microsoft Edge') },
);
} else if (platform === 'linux') {
browserDirs.push(
{ name: 'Chrome', base: path.join(home, '.config', 'google-chrome') },
{ name: 'Chrome Dev', base: path.join(home, '.config', 'google-chrome-unstable') },
{ name: 'Chrome Beta', base: path.join(home, '.config', 'google-chrome-beta') },
{ name: 'Chromium', base: path.join(home, '.config', 'chromium') },
{ name: 'Edge', base: path.join(home, '.config', 'microsoft-edge') },
);
} else if (platform === 'win32') {
const appData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
browserDirs.push(
{ name: 'Chrome', base: path.join(appData, 'Google', 'Chrome', 'User Data') },
{ name: 'Chrome Dev', base: path.join(appData, 'Google', 'Chrome Dev', 'User Data') },
{ name: 'Chrome Beta', base: path.join(appData, 'Google', 'Chrome Beta', 'User Data') },
{ name: 'Edge', base: path.join(appData, 'Microsoft', 'Edge', 'User Data') },
);
}
const profiles = enumerateProfiles(browserDirs.map(d => d.base));
const foundBrowsers: string[] = [];
for (const { name, base } of browserDirs) {
for (const profile of profiles) {
const extDir = path.join(base, profile, 'Extensions', PLAYWRIGHT_EXTENSION_ID);
if (fileExists(extDir)) {
foundBrowsers.push(name);
break; // one match per browser is enough
}
}
}
return { installed: foundBrowsers.length > 0, browsers: [...new Set(foundBrowsers)] };
}
/**
* Test token connectivity by attempting a real MCP connection.
* Connects, does the JSON-RPC handshake, and immediately closes.
*/
export async function checkTokenConnectivity(opts?: { timeout?: number }): Promise<ConnectivityResult> {
const timeout = opts?.timeout ?? 8;
const start = Date.now();
try {
const mcp = new PlaywrightMCP();
await mcp.connect({ timeout });
await mcp.close();
return { ok: true, durationMs: Date.now() - start };
} catch (err: any) {
return { ok: false, error: err?.message ?? String(err), durationMs: Date.now() - start };
}
}
export async function runBrowserDoctor(opts: DoctorOptions = {}): Promise<DoctorReport> {
const envToken = process.env[PLAYWRIGHT_TOKEN_ENV] ?? null;
const remoteDebuggingEndpoint = await discoverChromeEndpoint().catch(() => null);
const shellPath = opts.shellRc ?? getDefaultShellRcPath();
const shellFiles: ShellFileStatus[] = [shellPath].map((filePath) => {
if (!fileExists(filePath)) return { path: filePath, exists: false, token: null, fingerprint: null };
if (!fileExists(filePath)) return { path: filePath, exists: false, token: null };
const content = fs.readFileSync(filePath, 'utf-8');
const token = readTokenFromShellContent(content);
return { path: filePath, exists: true, token, fingerprint: getTokenFingerprint(token ?? undefined) };
return { path: filePath, exists: true, token };
});
const configPaths = opts.configPaths?.length ? opts.configPaths : getDefaultMcpConfigPaths();
const configs = configPaths.map(readConfigStatus);
const cdpToken = !opts.token && !envToken ? await extractTokenViaCdp().catch(() => null) : null;
// Try to discover the token directly from the Chrome extension's localStorage
const extensionToken = discoverExtensionToken();
const allTokens = [
opts.token ?? null,
extensionToken,
envToken,
...shellFiles.map(s => s.token),
...configs.map(c => c.token),
cdpToken,
].filter((v): v is string => !!v);
const uniqueTokens = [...new Set(allTokens)];
const recommendedToken = opts.token ?? envToken ?? (uniqueTokens.length === 1 ? uniqueTokens[0] : cdpToken) ?? null;
const recommendedToken = opts.token ?? extensionToken ?? envToken ?? (uniqueTokens.length === 1 ? uniqueTokens[0] : null) ?? null;
// Check extension installation
const extInstall = checkExtensionInstalled();
// Connectivity test (only when --live)
let connectivity: ConnectivityResult | undefined;
if (opts.live) {
connectivity = await checkTokenConnectivity();
}
const report: DoctorReport = {
cliVersion: opts.cliVersion,
envToken,
envFingerprint: getTokenFingerprint(envToken ?? undefined),
extensionToken,
extensionInstalled: extInstall.installed,
extensionBrowsers: extInstall.browsers,
shellFiles,
configs,
remoteDebuggingEnabled: !!remoteDebuggingEndpoint,
remoteDebuggingEndpoint,
cdpEnabled: process.env.OPENCLI_USE_CDP === '1' || !!process.env.OPENCLI_CDP_ENDPOINT,
cdpToken,
cdpFingerprint: getTokenFingerprint(cdpToken ?? undefined),
recommendedToken,
recommendedFingerprint: getTokenFingerprint(recommendedToken ?? undefined),
connectivity,
warnings: [],
issues: [],
};
if (!envToken) report.issues.push(`Current environment is missing ${PLAYWRIGHT_TOKEN_ENV}.`);
if (!shellFiles.some(s => s.token)) report.issues.push('Shell startup file does not export PLAYWRIGHT_MCP_EXTENSION_TOKEN.');
if (!configs.some(c => c.token)) report.issues.push('No scanned MCP config currently contains a Playwright extension token.');
if (uniqueTokens.length > 1) report.issues.push('Detected inconsistent Playwright MCP tokens across env/config files.');
if (!report.remoteDebuggingEnabled) report.warnings.push('Chrome remote debugging appears to be disabled or Chrome is not currently exposing a DevTools endpoint.');
if (!extInstall.installed) report.issues.push('OpenCLI MCP Bridge extension is not installed in any browser.');
if (connectivity && !connectivity.ok) report.issues.push(`Browser connectivity test failed: ${connectivity.error ?? 'unknown'}`);
for (const config of configs) {
if (config.parseError) report.warnings.push(`Could not parse ${config.path}: ${config.parseError}`);
}
if (!recommendedToken) {
if (report.cdpEnabled) report.warnings.push('CDP is enabled, but no token could be extracted automatically from the extension UI.');
else report.warnings.push('No token source found. Enable OPENCLI_USE_CDP=1 to allow a best-effort token read from the extension page.');
//
}
return report;
}
export function renderBrowserDoctorReport(report: DoctorReport): string {
const tokenFingerprints = [
report.envFingerprint,
...report.shellFiles.map(shell => shell.fingerprint),
...report.configs.filter(config => config.exists).map(config => config.fingerprint),
].filter((value): value is string => !!value);
const uniqueFingerprints = [...new Set(tokenFingerprints)];
const hasMismatch = uniqueFingerprints.length > 1;
const lines = [`opencli v${report.cliVersion ?? 'unknown'} doctor`, ''];
lines.push(statusLine(report.remoteDebuggingEnabled ? 'OK' : 'WARN', `Chrome remote debugging: ${report.remoteDebuggingEnabled ? 'enabled' : 'disabled'}`));
if (report.remoteDebuggingEndpoint) lines.push(` ${report.remoteDebuggingEndpoint}`);
const lines = [chalk.bold(`opencli v${report.cliVersion ?? 'unknown'} doctor`), ''];
const envStatus: ReportStatus = !report.envToken ? 'MISSING' : hasMismatch ? 'MISMATCH' : 'OK';
lines.push(statusLine(envStatus, `Environment token: ${tokenSummary(report.envToken, report.envFingerprint)}`));
const installStatus: ReportStatus = report.extensionInstalled ? 'OK' : 'MISSING';
const installDetail = report.extensionInstalled
? `Extension installed (${report.extensionBrowsers.join(', ')})`
: 'Extension not installed in any browser';
lines.push(statusLine(installStatus, installDetail));
const extStatus: ReportStatus = 'OK';
lines.push(statusLine(extStatus, `Extension token (Chrome LevelDB): ${tokenSummary(report.extensionToken)}`));
const envStatus: ReportStatus = 'OK';
lines.push(statusLine(envStatus, `Environment token: ${tokenSummary(report.envToken)}`));
for (const shell of report.shellFiles) {
const shellStatus: ReportStatus = !shell.token ? 'MISSING' : hasMismatch ? 'MISMATCH' : 'OK';
lines.push(statusLine(shellStatus, `Shell file ${shell.path}: ${tokenSummary(shell.token, shell.fingerprint)}`));
const shellStatus: ReportStatus = 'OK';
const tool = toolName(shell.path);
const suffix = tool ? chalk.dim(` [${tool}]`) : '';
lines.push(statusLine(shellStatus, `${shortenPath(shell.path)}${suffix}: ${tokenSummary(shell.token)}`));
}
const existingConfigs = report.configs.filter(config => config.exists);
const missingConfigCount = report.configs.length - existingConfigs.length;
if (existingConfigs.length > 0) {
for (const config of existingConfigs) {
const parseSuffix = config.parseError ? ` (parse error: ${config.parseError})` : '';
const parseSuffix = config.parseError ? chalk.red(` (parse error)`) : '';
const configStatus: ReportStatus = config.parseError
? 'WARN'
: !config.token
? 'MISSING'
: hasMismatch
? 'MISMATCH'
: 'OK';
lines.push(statusLine(configStatus, `MCP config ${config.path}: ${tokenSummary(config.token, config.fingerprint)}${parseSuffix}`));
: 'OK';
const tool = toolName(config.path);
const suffix = tool ? chalk.dim(` [${tool}]`) : '';
lines.push(statusLine(configStatus, `${shortenPath(config.path)}${suffix}: ${tokenSummary(config.token)}${parseSuffix}`));
}
} else {
lines.push(statusLine('MISSING', 'MCP config: no existing config files found in scanned locations'));
}
if (missingConfigCount > 0) lines.push(` Other scanned config locations not present: ${missingConfigCount}`);
if (report.cdpEnabled) {
const cdpStatus: ReportStatus = report.cdpToken ? 'OK' : 'WARN';
lines.push(statusLine(cdpStatus, `CDP token probe: ${tokenSummary(report.cdpToken, report.cdpFingerprint)}`));
lines.push(statusLine('MISSING', 'MCP config: no existing config files found'));
}
if (missingConfigCount > 0) lines.push(chalk.dim(` Other scanned config locations not present: ${missingConfigCount}`));
lines.push('');
// Connectivity result
if (report.connectivity) {
const connStatus: ReportStatus = report.connectivity.ok ? 'OK' : 'WARN';
const connDetail = report.connectivity.ok
? `Browser connectivity: connected in ${(report.connectivity.durationMs / 1000).toFixed(1)}s`
: `Browser connectivity: failed (${report.connectivity.error ?? 'unknown'})`;
lines.push(statusLine(connStatus, connDetail));
} else {
lines.push(statusLine('WARN', 'Browser connectivity: not tested (use --live)'));
}
lines.push(statusLine(
hasMismatch ? 'MISMATCH' : report.recommendedToken ? 'OK' : 'WARN',
`Recommended token fingerprint: ${report.recommendedFingerprint ?? 'unavailable'}`,
'OK',
`Token Configuration: Not required for OpenCLI MCP`,
));
if (report.issues.length) {
lines.push('', 'Issues:');
for (const issue of report.issues) lines.push(`- ${issue}`);
lines.push('', chalk.yellow('Issues:'));
for (const issue of report.issues) lines.push(chalk.dim(` ${issue}`));
}
if (report.warnings.length) {
lines.push('', 'Warnings:');
for (const warning of report.warnings) lines.push(`- ${warning}`);
lines.push('', chalk.yellow('Warnings:'));
for (const warning of report.warnings) lines.push(chalk.dim(` ${warning}`));
}
return lines.join('\n');
}
@@ -384,41 +554,12 @@ async function confirmPrompt(question: string): Promise<boolean> {
}
}
function writeFileWithMkdir(filePath: string, content: string): void {
export function writeFileWithMkdir(filePath: string, content: string): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content, 'utf-8');
}
export async function applyBrowserDoctorFix(report: DoctorReport, opts: DoctorOptions = {}): Promise<string[]> {
const token = opts.token ?? report.recommendedToken;
if (!token) throw new Error('No Playwright MCP token is available to write. Provide --token or enable CDP token probing first.');
const plannedWrites: string[] = [];
const shellPath = opts.shellRc ?? report.shellFiles[0]?.path ?? getDefaultShellRcPath();
plannedWrites.push(shellPath);
for (const config of report.configs) {
if (!config.writable) continue;
plannedWrites.push(config.path);
}
if (!opts.yes) {
const ok = await confirmPrompt(`Update ${plannedWrites.length} file(s) with Playwright MCP token fingerprint ${getTokenFingerprint(token)}?`);
if (!ok) return [];
}
const written: string[] = [];
const shellBefore = fileExists(shellPath) ? fs.readFileSync(shellPath, 'utf-8') : '';
writeFileWithMkdir(shellPath, upsertShellToken(shellBefore, token));
written.push(shellPath);
for (const config of report.configs) {
if (!config.writable || config.parseError) continue;
const before = fileExists(config.path) ? fs.readFileSync(config.path, 'utf-8') : '';
const next = config.format === 'toml' ? upsertTomlConfigToken(before, token) : upsertJsonConfigToken(before, token);
writeFileWithMkdir(config.path, next);
written.push(config.path);
}
process.env[PLAYWRIGHT_TOKEN_ENV] = token;
return written;
console.log(chalk.green('OpenCLI MCP Bridge does not require token configuration!'));
return [];
}
+77
View File
@@ -0,0 +1,77 @@
/**
* Tests for engine.ts: CLI discovery and command execution.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { discoverClis, executeCommand } from './engine.js';
import { getRegistry, cli, Strategy } from './registry.js';
describe('discoverClis', () => {
it('handles non-existent directories gracefully', async () => {
// Should not throw for missing directories
await expect(discoverClis('/tmp/nonexistent-opencli-test-dir')).resolves.not.toThrow();
});
});
describe('executeCommand', () => {
it('executes a command with func', async () => {
const cmd = cli({
site: 'test-engine',
name: 'func-test',
description: 'test command with func',
browser: false,
strategy: Strategy.PUBLIC,
func: async (_page, kwargs) => {
return [{ title: kwargs.query ?? 'default' }];
},
});
const result = await executeCommand(cmd, null, { query: 'hello' });
expect(result).toEqual([{ title: 'hello' }]);
});
it('executes a command with pipeline', async () => {
const cmd = cli({
site: 'test-engine',
name: 'pipe-test',
description: 'test command with pipeline',
browser: false,
strategy: Strategy.PUBLIC,
pipeline: [
{ evaluate: '() => [{ n: 1 }, { n: 2 }, { n: 3 }]' },
{ limit: '2' },
],
});
// Pipeline commands require page for evaluate step, so we'll test the error path
await expect(executeCommand(cmd, null, {})).rejects.toThrow();
});
it('throws for command with no func or pipeline', async () => {
const cmd = cli({
site: 'test-engine',
name: 'empty-test',
description: 'empty command',
browser: false,
});
await expect(executeCommand(cmd, null, {})).rejects.toThrow('has no func or pipeline');
});
it('passes debug flag to func', async () => {
let receivedDebug = false;
const cmd = cli({
site: 'test-engine',
name: 'debug-test',
description: 'debug test',
browser: false,
func: async (_page, _kwargs, debug) => {
receivedDebug = debug ?? false;
return [];
},
});
await executeCommand(cmd, null, {}, true);
expect(receivedDebug).toBe(true);
});
});
+20 -12
View File
@@ -11,9 +11,11 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import yaml from 'js-yaml';
import { type CliCommand, type Arg, Strategy, registerCommand } from './registry.js';
import { type CliCommand, type InternalCliCommand, type Arg, Strategy, registerCommand } from './registry.js';
import type { IPage } from './types.js';
import { executePipeline } from './pipeline.js';
import { log } from './logger.js';
import { AdapterLoadError } from './errors.js';
/** Set of TS module paths that have been loaded */
const _loadedModules = new Set<string>();
@@ -66,7 +68,7 @@ function loadFromManifest(manifestPath: string, clisDir: string): void {
// The actual module is loaded lazily on first executeCommand().
const strategy = (Strategy as any)[(entry.strategy ?? 'cookie').toUpperCase()] ?? Strategy.COOKIE;
const modulePath = path.resolve(clisDir, entry.modulePath);
const cmd: CliCommand = {
const cmd: InternalCliCommand = {
site: entry.site,
name: entry.name,
description: entry.description ?? '',
@@ -77,7 +79,6 @@ function loadFromManifest(manifestPath: string, clisDir: string): void {
columns: entry.columns,
timeoutSeconds: entry.timeout,
source: modulePath,
// Mark as lazy — executeCommand will load the module before running
_lazy: true,
_modulePath: modulePath,
};
@@ -85,7 +86,7 @@ function loadFromManifest(manifestPath: string, clisDir: string): void {
}
}
} catch (err: any) {
process.stderr.write(`Warning: failed to load manifest ${manifestPath}: ${err.message}\n`);
log.warn(`Failed to load manifest ${manifestPath}: ${err.message}`);
}
}
@@ -102,10 +103,13 @@ async function discoverClisFromFs(dir: string): Promise<void> {
const filePath = path.join(siteDir, file);
if (file.endsWith('.yaml') || file.endsWith('.yml')) {
registerYamlCli(filePath, site);
} else if (file.endsWith('.js') && !file.endsWith('.d.js')) {
} else if (
(file.endsWith('.js') && !file.endsWith('.d.js')) ||
(file.endsWith('.ts') && !file.endsWith('.d.ts') && !file.endsWith('.test.ts'))
) {
promises.push(
import(`file://${filePath}`).catch((err: any) => {
process.stderr.write(`Warning: failed to load module ${filePath}: ${err.message}\n`);
log.warn(`Failed to load module ${filePath}: ${err.message}`);
})
);
}
@@ -156,7 +160,7 @@ function registerYamlCli(filePath: string, defaultSite: string): void {
registerCommand(cmd);
} catch (err: any) {
process.stderr.write(`Warning: failed to load ${filePath}: ${err.message}\n`);
log.warn(`Failed to load ${filePath}: ${err.message}`);
}
}
@@ -170,14 +174,18 @@ export async function executeCommand(
debug: boolean = false,
): Promise<any> {
// Lazy-load TS module on first execution
if ((cmd as any)._lazy && (cmd as any)._modulePath) {
const modulePath = (cmd as any)._modulePath;
const internal = cmd as InternalCliCommand;
if (internal._lazy && internal._modulePath) {
const modulePath = internal._modulePath;
if (!_loadedModules.has(modulePath)) {
try {
await import(`file://${modulePath}`);
_loadedModules.add(modulePath);
} catch (err: any) {
throw new Error(`Failed to load adapter module ${modulePath}: ${err.message}`);
throw new AdapterLoadError(
`Failed to load adapter module ${modulePath}: ${err.message}`,
'Check that the adapter file exists and has no syntax errors.',
);
}
}
// After loading, the module's cli() call will have updated the registry
@@ -185,7 +193,7 @@ export async function executeCommand(
const { getRegistry, fullName } = await import('./registry.js');
const updated = getRegistry().get(fullName(cmd));
if (updated && updated.func) {
return updated.func(page, kwargs, debug);
return updated.func(page!, kwargs, debug);
}
if (updated && updated.pipeline) {
return executePipeline(page, updated.pipeline, { args: kwargs, debug });
@@ -193,7 +201,7 @@ export async function executeCommand(
}
if (cmd.func) {
return cmd.func(page, kwargs, debug);
return cmd.func(page!, kwargs, debug);
}
if (cmd.pipeline) {
return executePipeline(page, cmd.pipeline, { args: kwargs, debug });
+48
View File
@@ -0,0 +1,48 @@
/**
* Unified error types for opencli.
*
* All errors thrown by the framework should extend CliError so that
* the top-level handler in main.ts can render consistent, helpful output.
*/
export class CliError extends Error {
/** Machine-readable error code (e.g. 'BROWSER_CONNECT', 'ADAPTER_LOAD') */
readonly code: string;
/** Human-readable hint on how to fix the problem */
readonly hint?: string;
constructor(code: string, message: string, hint?: string) {
super(message);
this.name = 'CliError';
this.code = code;
this.hint = hint;
}
}
export class BrowserConnectError extends CliError {
constructor(message: string, hint?: string) {
super('BROWSER_CONNECT', message, hint);
this.name = 'BrowserConnectError';
}
}
export class AdapterLoadError extends CliError {
constructor(message: string, hint?: string) {
super('ADAPTER_LOAD', message, hint);
this.name = 'AdapterLoadError';
}
}
export class CommandExecutionError extends CliError {
constructor(message: string, hint?: string) {
super('COMMAND_EXEC', message, hint);
this.name = 'CommandExecutionError';
}
}
export class ConfigError extends CliError {
constructor(message: string, hint?: string) {
super('CONFIG', message, hint);
this.name = 'ConfigError';
}
}
+2 -15
View File
@@ -9,6 +9,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import { DEFAULT_BROWSER_EXPLORE_TIMEOUT, browserSession, runWithTimeout } from './runtime.js';
import { VOLATILE_PARAMS, SEARCH_PARAMS, PAGINATION_PARAMS, LIMIT_PARAMS, FIELD_ROLES } from './constants.js';
// ── Site name detection ────────────────────────────────────────────────────
@@ -43,21 +44,7 @@ export function slugify(value: string): string {
// ── Field & capability inference ───────────────────────────────────────────
const FIELD_ROLES: Record<string, string[]> = {
title: ['title', 'name', 'text', 'content', 'desc', 'description', 'headline', 'subject'],
url: ['url', 'uri', 'link', 'href', 'permalink', 'jump_url', 'web_url', 'share_url'],
author: ['author', 'username', 'user_name', 'nickname', 'nick', 'owner', 'creator', 'up_name', 'uname'],
score: ['score', 'hot', 'heat', 'likes', 'like_count', 'view_count', 'views', 'play', 'favorite_count', 'reply_count'],
time: ['time', 'created_at', 'publish_time', 'pub_time', 'date', 'ctime', 'mtime', 'pubdate', 'created'],
id: ['id', 'aid', 'bvid', 'mid', 'uid', 'oid', 'note_id', 'item_id'],
cover: ['cover', 'pic', 'image', 'thumbnail', 'poster', 'avatar'],
category: ['category', 'tag', 'type', 'tname', 'channel', 'section'],
};
const SEARCH_PARAMS = new Set(['q', 'query', 'keyword', 'search', 'wd', 'kw', 'search_query', 'w']);
const PAGINATION_PARAMS = new Set(['page', 'pn', 'offset', 'cursor', 'next', 'page_num']);
const LIMIT_PARAMS = new Set(['limit', 'count', 'size', 'per_page', 'page_size', 'ps', 'num']);
const VOLATILE_PARAMS = new Set(['w_rid', 'wts', '_', 'callback', 'timestamp', 't', 'nonce', 'sign']);
// (constants now imported from constants.ts)
// ── Network analysis ───────────────────────────────────────────────────────
+94
View File
@@ -0,0 +1,94 @@
/**
* Tests for interceptor.ts: JavaScript code generators for XHR/Fetch interception.
*/
import { describe, it, expect } from 'vitest';
import { generateInterceptorJs, generateReadInterceptedJs, generateTapInterceptorJs } from './interceptor.js';
describe('generateInterceptorJs', () => {
it('generates valid JavaScript function source', () => {
const js = generateInterceptorJs('"api/search"');
expect(js).toContain('window.fetch');
expect(js).toContain('XMLHttpRequest');
expect(js).toContain('"api/search"');
// Should be a function expression wrapping
expect(js.trim()).toMatch(/^\(\)\s*=>/);
});
it('uses default array name and patch guard', () => {
const js = generateInterceptorJs('"test"');
expect(js).toContain('__opencli_intercepted');
expect(js).toContain('__opencli_interceptor_patched');
});
it('uses custom array name and patch guard', () => {
const js = generateInterceptorJs('"test"', {
arrayName: '__my_data',
patchGuard: '__my_guard',
});
expect(js).toContain('__my_data');
expect(js).toContain('__my_guard');
expect(js).not.toContain('__opencli_intercepted');
});
it('includes fetch clone and json parsing', () => {
const js = generateInterceptorJs('"api"');
expect(js).toContain('response.clone()');
expect(js).toContain('clone.json()');
});
it('includes XHR open and send patching', () => {
const js = generateInterceptorJs('"api"');
expect(js).toContain('XMLHttpRequest.prototype');
expect(js).toContain('__origOpen');
expect(js).toContain('__origSend');
});
});
describe('generateReadInterceptedJs', () => {
it('generates valid JavaScript to read and clear data', () => {
const js = generateReadInterceptedJs();
expect(js).toContain('__opencli_intercepted');
// Should clear the array after reading
expect(js).toContain('= []');
});
it('uses custom array name', () => {
const js = generateReadInterceptedJs('__custom_arr');
expect(js).toContain('__custom_arr');
expect(js).not.toContain('__opencli_intercepted');
});
});
describe('generateTapInterceptorJs', () => {
it('returns all required fields', () => {
const tap = generateTapInterceptorJs('"api/data"');
expect(tap.setupVar).toBeDefined();
expect(tap.capturedVar).toBe('captured');
expect(tap.promiseVar).toBe('capturePromise');
expect(tap.resolveVar).toBe('captureResolve');
expect(tap.fetchPatch).toBeDefined();
expect(tap.xhrPatch).toBeDefined();
expect(tap.restorePatch).toBeDefined();
});
it('contains the capture pattern in setup', () => {
const tap = generateTapInterceptorJs('"my-pattern"');
expect(tap.setupVar).toContain('"my-pattern"');
});
it('restores original fetch and XHR in restorePatch', () => {
const tap = generateTapInterceptorJs('"test"');
expect(tap.restorePatch).toContain('origFetch');
expect(tap.restorePatch).toContain('origXhrOpen');
expect(tap.restorePatch).toContain('origXhrSend');
});
it('uses first-match capture (only first response)', () => {
const tap = generateTapInterceptorJs('"test"');
// Both fetch and xhr patches should check !captured before storing
expect(tap.fetchPatch).toContain('!captured');
expect(tap.xhrPatch).toContain('!captured');
});
});
+153
View File
@@ -0,0 +1,153 @@
/**
* Shared XHR/Fetch interceptor JavaScript generators.
*
* Provides a single source of truth for monkey-patching browser
* fetch() and XMLHttpRequest to capture API responses matching
* a URL pattern. Used by:
* - Page.installInterceptor() (browser.ts)
* - stepIntercept (pipeline/steps/intercept.ts)
* - stepTap (pipeline/steps/tap.ts)
*/
/**
* Generate JavaScript source that installs a fetch/XHR interceptor.
* Captured responses are pushed to `window.__opencli_intercepted`.
*
* @param patternExpr - JS expression resolving to a URL substring to match (e.g. a JSON.stringify'd string)
* @param opts.arrayName - Global array name for captured data (default: '__opencli_intercepted')
* @param opts.patchGuard - Global boolean name to prevent double-patching (default: '__opencli_interceptor_patched')
*/
export function generateInterceptorJs(
patternExpr: string,
opts: { arrayName?: string; patchGuard?: string } = {},
): string {
const arr = opts.arrayName ?? '__opencli_intercepted';
const guard = opts.patchGuard ?? '__opencli_interceptor_patched';
return `
() => {
window.${arr} = window.${arr} || [];
const __pattern = ${patternExpr};
if (!window.${guard}) {
const __checkMatch = (url) => __pattern && url.includes(__pattern);
// ── Patch fetch ──
const __origFetch = window.fetch;
window.fetch = async function(...args) {
const reqUrl = typeof args[0] === 'string' ? args[0]
: (args[0] && args[0].url) || '';
const response = await __origFetch.apply(this, args);
if (__checkMatch(reqUrl)) {
try {
const clone = response.clone();
const json = await clone.json();
window.${arr}.push(json);
} catch(e) {}
}
return response;
};
// ── Patch XMLHttpRequest ──
const __XHR = XMLHttpRequest.prototype;
const __origOpen = __XHR.open;
const __origSend = __XHR.send;
__XHR.open = function(method, url) {
this.__opencli_url = String(url);
return __origOpen.apply(this, arguments);
};
__XHR.send = function() {
if (__checkMatch(this.__opencli_url)) {
this.addEventListener('load', function() {
try {
window.${arr}.push(JSON.parse(this.responseText));
} catch(e) {}
});
}
return __origSend.apply(this, arguments);
};
window.${guard} = true;
}
}
`;
}
/**
* Generate JavaScript source to read and clear intercepted data.
*/
export function generateReadInterceptedJs(arrayName: string = '__opencli_intercepted'): string {
return `
() => {
const data = window.${arrayName} || [];
window.${arrayName} = [];
return data;
}
`;
}
/**
* Generate a self-contained tap interceptor for store-action bridge.
* Unlike the global interceptor, this one:
* - Installs temporarily, restores originals in finally block
* - Resolves a promise on first capture (for immediate await)
* - Returns captured data directly
*/
export function generateTapInterceptorJs(patternExpr: string): {
setupVar: string;
capturedVar: string;
promiseVar: string;
resolveVar: string;
fetchPatch: string;
xhrPatch: string;
restorePatch: string;
} {
return {
setupVar: `
let captured = null;
let captureResolve;
const capturePromise = new Promise(r => { captureResolve = r; });
const capturePattern = ${patternExpr};
`,
capturedVar: 'captured',
promiseVar: 'capturePromise',
resolveVar: 'captureResolve',
fetchPatch: `
const origFetch = window.fetch;
window.fetch = async function(...fetchArgs) {
const resp = await origFetch.apply(this, fetchArgs);
try {
const url = typeof fetchArgs[0] === 'string' ? fetchArgs[0]
: fetchArgs[0] instanceof Request ? fetchArgs[0].url : String(fetchArgs[0]);
if (capturePattern && url.includes(capturePattern) && !captured) {
try { captured = await resp.clone().json(); captureResolve(); } catch {}
}
} catch {}
return resp;
};
`,
xhrPatch: `
const origXhrOpen = XMLHttpRequest.prototype.open;
const origXhrSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function(method, url) {
this.__tapUrl = String(url);
return origXhrOpen.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function(body) {
if (capturePattern && this.__tapUrl?.includes(capturePattern)) {
this.addEventListener('load', function() {
if (!captured) {
try { captured = JSON.parse(this.responseText); captureResolve(); } catch {}
}
});
}
return origXhrSend.apply(this, arguments);
};
`,
restorePatch: `
window.fetch = origFetch;
XMLHttpRequest.prototype.open = origXhrOpen;
XMLHttpRequest.prototype.send = origXhrSend;
`,
};
}
+57
View File
@@ -0,0 +1,57 @@
/**
* Unified logging for opencli.
*
* All framework output (warnings, debug info, errors) should go through
* this module so that verbosity levels are respected consistently.
*/
import chalk from 'chalk';
function isVerbose(): boolean {
return !!process.env.OPENCLI_VERBOSE;
}
function isDebug(): boolean {
return !!process.env.DEBUG?.includes('opencli');
}
export const log = {
/** Informational message (always shown) */
info(msg: string): void {
process.stderr.write(`${chalk.blue('')} ${msg}\n`);
},
/** Warning (always shown) */
warn(msg: string): void {
process.stderr.write(`${chalk.yellow('⚠')} ${msg}\n`);
},
/** Error (always shown) */
error(msg: string): void {
process.stderr.write(`${chalk.red('✖')} ${msg}\n`);
},
/** Verbose output (only when OPENCLI_VERBOSE is set or -v flag) */
verbose(msg: string): void {
if (isVerbose()) {
process.stderr.write(`${chalk.dim('[verbose]')} ${msg}\n`);
}
},
/** Debug output (only when DEBUG includes 'opencli') */
debug(msg: string): void {
if (isDebug()) {
process.stderr.write(`${chalk.dim('[debug]')} ${msg}\n`);
}
},
/** Step-style debug (for pipeline steps, etc.) */
step(stepNum: number, total: number, op: string, preview: string = ''): void {
process.stderr.write(` ${chalk.dim(`[${stepNum}/${total}]`)} ${chalk.bold.cyan(op)}${preview}\n`);
},
/** Step result summary */
stepResult(summary: string): void {
process.stderr.write(` ${chalk.dim(`${summary}`)}\n`);
},
};
+85 -17
View File
@@ -3,7 +3,6 @@
* opencli — Make any website your CLI. AI-powered.
*/
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -12,20 +11,40 @@ import chalk from 'chalk';
import { discoverClis, executeCommand } from './engine.js';
import { type CliCommand, fullName, getRegistry, strategyLabel } from './registry.js';
import { render as renderOutput } from './output.js';
import { PlaywrightMCP } from './browser.js';
import { PlaywrightMCP } from './browser/index.js';
import { browserSession, DEFAULT_BROWSER_COMMAND_TIMEOUT, runWithTimeout } from './runtime.js';
import { PKG_VERSION } from './version.js';
import { getCompletions, printCompletionScript } from './completion.js';
import { CliError } from './errors.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const BUILTIN_CLIS = path.resolve(__dirname, 'clis');
const USER_CLIS = path.join(os.homedir(), '.opencli', 'clis');
// Read version from package.json (single source of truth)
const pkgJsonPath = path.resolve(__dirname, '..', 'package.json');
const PKG_VERSION = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf-8')).version ?? '0.0.0';
await discoverClis(BUILTIN_CLIS, USER_CLIS);
// ── Fast-path: handle --get-completions before commander parses ─────────
// Usage: opencli --get-completions --cursor <N> [word1 word2 ...]
const getCompIdx = process.argv.indexOf('--get-completions');
if (getCompIdx !== -1) {
const rest = process.argv.slice(getCompIdx + 1);
let cursor: number | undefined;
const words: string[] = [];
for (let i = 0; i < rest.length; i++) {
if (rest[i] === '--cursor' && i + 1 < rest.length) {
cursor = parseInt(rest[i + 1], 10);
i++; // skip the value
} else {
words.push(rest[i]);
}
}
if (cursor === undefined) cursor = words.length;
const candidates = getCompletions(words, cursor);
process.stdout.write(candidates.join('\n') + '\n');
process.exit(0);
}
const program = new Command();
program.name('opencli').description('Make any website your CLI. Zero setup. AI-powered.').version(PKG_VERSION);
@@ -66,10 +85,18 @@ program.command('list').description('List all available CLI commands').option('-
});
program.command('validate').description('Validate CLI definitions').argument('[target]', 'site or site/name')
.action(async (target) => { const { validateClisWithTarget, renderValidationReport } = await import('./validate.js'); console.log(renderValidationReport(validateClisWithTarget([BUILTIN_CLIS, USER_CLIS], target))); });
.action(async (target) => {
const { validateClisWithTarget, renderValidationReport } = await import('./validate.js');
console.log(renderValidationReport(validateClisWithTarget([BUILTIN_CLIS, USER_CLIS], target)));
});
program.command('verify').description('Validate + smoke test').argument('[target]').option('--smoke', 'Run smoke tests', false)
.action(async (target, opts) => { const { verifyClis, renderVerifyReport } = await import('./verify.js'); const r = await verifyClis({ builtinClis: BUILTIN_CLIS, userClis: USER_CLIS, target, smoke: opts.smoke }); console.log(renderVerifyReport(r)); process.exitCode = r.ok ? 0 : 1; });
.action(async (target, opts) => {
const { verifyClis, renderVerifyReport } = await import('./verify.js');
const r = await verifyClis({ builtinClis: BUILTIN_CLIS, userClis: USER_CLIS, target, smoke: opts.smoke });
console.log(renderVerifyReport(r));
process.exitCode = r.ok ? 0 : 1;
});
program.command('explore').alias('probe').description('Explore a website: discover APIs, stores, and recommend strategies').argument('<url>').option('--site <name>').option('--goal <text>').option('--wait <s>', '', '3').option('--auto', 'Enable interactive fuzzing (simulate clicks to trigger lazy APIs)').option('--click <labels>', 'Comma-separated labels to click before fuzzing (e.g. "字幕,CC,评论")')
.action(async (url, opts) => { const { exploreUrl, renderExploreSummary } = await import('./explore.js'); const clickLabels = opts.click ? opts.click.split(',').map((s: string) => s.trim()) : undefined; console.log(renderExploreSummary(await exploreUrl(url, { BrowserFactory: PlaywrightMCP, site: opts.site, goal: opts.goal, waitSeconds: parseFloat(opts.wait), auto: opts.auto, clickLabels }))); });
@@ -96,12 +123,13 @@ program.command('doctor')
.option('--fix', 'Apply suggested fixes to shell rc and detected MCP configs', false)
.option('-y, --yes', 'Skip confirmation prompts when applying fixes', false)
.option('--token <token>', 'Override token to write instead of auto-detecting')
.option('--live', 'Test browser connectivity (requires Chrome running)', false)
.option('--shell-rc <path>', 'Shell startup file to update')
.option('--mcp-config <paths>', 'Comma-separated MCP config paths to scan/update')
.action(async (opts) => {
const { runBrowserDoctor, renderBrowserDoctorReport, applyBrowserDoctorFix } = await import('./doctor.js');
const configPaths = opts.mcpConfig ? String(opts.mcpConfig).split(',').map((s: string) => s.trim()).filter(Boolean) : undefined;
const report = await runBrowserDoctor({ token: opts.token, shellRc: opts.shellRc, configPaths, cliVersion: PKG_VERSION });
const report = await runBrowserDoctor({ token: opts.token, live: opts.live, shellRc: opts.shellRc, configPaths, cliVersion: PKG_VERSION });
console.log(renderBrowserDoctorReport(report));
if (opts.fix) {
const written = await applyBrowserDoctorFix(report, { fix: true, yes: opts.yes, token: opts.token, shellRc: opts.shellRc, configPaths });
@@ -115,6 +143,21 @@ program.command('doctor')
}
});
program.command('setup')
.description('Interactive setup: configure Playwright MCP token across all detected tools')
.option('--token <token>', 'Provide token directly instead of auto-detecting')
.action(async (opts) => {
const { runSetup } = await import('./setup.js');
await runSetup({ cliVersion: PKG_VERSION, token: opts.token });
});
program.command('completion')
.description('Output shell completion script')
.argument('<shell>', 'Shell type: bash, zsh, or fish')
.action((shell) => {
printCompletionScript(shell);
});
// ── Dynamic site commands ──────────────────────────────────────────────────
const registry = getRegistry();
@@ -125,18 +168,37 @@ for (const [, cmd] of registry) {
if (!siteCmd) { siteCmd = program.command(cmd.site).description(`${cmd.site} commands`); siteGroups.set(cmd.site, siteCmd); }
const subCmd = siteCmd.command(cmd.name).description(cmd.description);
// Register positional args first, then named options
const positionalArgs: typeof cmd.args = [];
for (const arg of cmd.args) {
const flag = arg.required ? `--${arg.name} <value>` : `--${arg.name} [value]`;
if (arg.required) subCmd.requiredOption(flag, arg.help ?? '');
else if (arg.default != null) subCmd.option(flag, arg.help ?? '', String(arg.default));
else subCmd.option(flag, arg.help ?? '');
if (arg.positional) {
const bracket = arg.required ? `<${arg.name}>` : `[${arg.name}]`;
subCmd.argument(bracket, arg.help ?? '');
positionalArgs.push(arg);
} else {
const flag = arg.required ? `--${arg.name} <value>` : `--${arg.name} [value]`;
if (arg.required) subCmd.requiredOption(flag, arg.help ?? '');
else if (arg.default != null) subCmd.option(flag, arg.help ?? '', String(arg.default));
else subCmd.option(flag, arg.help ?? '');
}
}
subCmd.option('-f, --format <fmt>', 'Output format: table, json, yaml, md, csv', 'table').option('-v, --verbose', 'Debug output', false);
subCmd.action(async (actionOpts) => {
subCmd.action(async (...actionArgs: any[]) => {
// Commander passes positional args first, then options object, then the Command
const actionOpts = actionArgs[positionalArgs.length] ?? {};
const startTime = Date.now();
const kwargs: Record<string, any> = {};
// Collect positional args
for (let i = 0; i < positionalArgs.length; i++) {
const arg = positionalArgs[i];
const v = actionArgs[i];
if (v !== undefined) kwargs[arg.name] = coerce(v, arg.type ?? 'str');
else if (arg.default != null) kwargs[arg.name] = arg.default;
}
// Collect named options
for (const arg of cmd.args) {
if (arg.positional) continue;
const v = actionOpts[arg.name]; if (v !== undefined) kwargs[arg.name] = coerce(v, arg.type ?? 'str');
else if (arg.default != null) kwargs[arg.name] = arg.default;
}
@@ -144,15 +206,21 @@ for (const [, cmd] of registry) {
if (actionOpts.verbose) process.env.OPENCLI_VERBOSE = '1';
let result: any;
if (cmd.browser) {
result = await browserSession(PlaywrightMCP, async (page) => runWithTimeout(executeCommand(cmd, page, kwargs, actionOpts.verbose), { timeout: cmd.timeoutSeconds ?? DEFAULT_BROWSER_COMMAND_TIMEOUT, label: fullName(cmd) }), { forceExtension: cmd.forceExtension });
result = await browserSession(PlaywrightMCP, async (page) => runWithTimeout(executeCommand(cmd, page, kwargs, actionOpts.verbose), { timeout: cmd.timeoutSeconds ?? DEFAULT_BROWSER_COMMAND_TIMEOUT, label: fullName(cmd) }));
} else { result = await executeCommand(cmd, null, kwargs, actionOpts.verbose); }
if (actionOpts.verbose && (!result || (Array.isArray(result) && result.length === 0))) {
console.error(chalk.yellow(`[Verbose] Warning: Command returned an empty result. If the website structural API changed or requires authentication, check the network or update the adapter.`));
}
renderOutput(result, { fmt: actionOpts.format, columns: cmd.columns, title: `${cmd.site}/${cmd.name}`, elapsed: (Date.now() - startTime) / 1000, source: fullName(cmd) });
} catch (err: any) {
if (actionOpts.verbose && err.stack) { console.error(chalk.red(err.stack)); }
else { console.error(chalk.red(`Error: ${err.message ?? err}`)); }
if (err instanceof CliError) {
console.error(chalk.red(`Error [${err.code}]: ${err.message}`));
if (err.hint) console.error(chalk.yellow(`Hint: ${err.hint}`));
} else if (actionOpts.verbose && err.stack) {
console.error(chalk.red(err.stack));
} else {
console.error(chalk.red(`Error: ${err.message ?? err}`));
}
process.exitCode = 1;
}
});
+69 -4
View File
@@ -1,3 +1,7 @@
/**
* Tests for output.ts: render function format coverage.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render } from './output.js';
@@ -6,11 +10,67 @@ afterEach(() => {
});
describe('render', () => {
it('renders JSON output', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
render([{ title: 'Hello', rank: 1 }], { fmt: 'json' });
expect(log).toHaveBeenCalledOnce();
const output = log.mock.calls[0]?.[0];
const parsed = JSON.parse(output);
expect(parsed).toEqual([{ title: 'Hello', rank: 1 }]);
});
it('renders Markdown table output', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
render([{ name: 'Alice', score: 100 }], { fmt: 'md', columns: ['name', 'score'] });
const calls = log.mock.calls.map(c => c[0]);
expect(calls[0]).toContain('| name | score |');
expect(calls[1]).toContain('| --- | --- |');
expect(calls[2]).toContain('| Alice | 100 |');
});
it('renders CSV output with proper quoting', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
render([{ name: 'Alice, Bob', value: 'say "hi"' }], { fmt: 'csv' });
const calls = log.mock.calls.map(c => c[0]);
// Header
expect(calls[0]).toBe('name,value');
// Values with commas/quotes are quoted
expect(calls[1]).toContain('"Alice, Bob"');
expect(calls[1]).toContain('"say ""hi"""');
});
it('handles null and undefined data', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
render(null, { fmt: 'json' });
expect(log).toHaveBeenCalledWith(null);
});
it('renders single object as single-row table', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
render({ title: 'Test' }, { fmt: 'json' });
const output = log.mock.calls[0]?.[0];
const parsed = JSON.parse(output);
expect(parsed).toEqual({ title: 'Test' });
});
it('handles empty array gracefully', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
render([], { fmt: 'table' });
// Should show "(no data)" for empty arrays
expect(log).toHaveBeenCalled();
});
it('uses custom columns for CSV', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
render([{ a: 1, b: 2, c: 3 }], { fmt: 'csv', columns: ['a', 'c'] });
const calls = log.mock.calls.map(c => c[0]);
expect(calls[0]).toBe('a,c');
expect(calls[1]).toBe('1,3');
});
it('renders YAML output', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
render([{ title: 'Hello', rank: 1 }], { fmt: 'yaml' });
expect(log).toHaveBeenCalledOnce();
expect(log.mock.calls[0]?.[0]).toContain('- title: Hello');
expect(log.mock.calls[0]?.[0]).toContain('rank: 1');
@@ -18,10 +78,15 @@ describe('render', () => {
it('renders yml alias as YAML output', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
render({ title: 'Hello' }, { fmt: 'yml' });
expect(log).toHaveBeenCalledOnce();
expect(log.mock.calls[0]?.[0]).toContain('title: Hello');
});
it('handles null values in CSV cells', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {});
render([{ name: 'test', value: null }], { fmt: 'csv' });
const calls = log.mock.calls.map(c => c[0]);
expect(calls[1]).toBe('test,');
});
});
+2 -5
View File
@@ -40,10 +40,6 @@ function renderTable(data: any, opts: RenderOptions): void {
style: { head: [], border: [] },
wordWrap: true,
wrapOnWordBoundary: true,
colWidths: columns.map((_c, i) => {
if (i === 0) return 6;
return null as any;
}).filter(() => true),
});
for (const row of rows) {
@@ -86,7 +82,8 @@ function renderCsv(data: any, opts: RenderOptions): void {
for (const row of rows) {
console.log(columns.map(c => {
const v = String(row[c] ?? '');
return v.includes(',') || v.includes('"') ? `"${v.replace(/"/g, '""')}"` : v;
return v.includes(',') || v.includes('"') || v.includes('\n')
? `"${v.replace(/"/g, '""')}"` : v;
}).join(','));
}
}
+161
View File
@@ -0,0 +1,161 @@
/**
* Tests for pipeline/executor.ts: pipeline execution with mock page.
*/
import { describe, it, expect, vi } from 'vitest';
import { executePipeline } from './index.js';
import type { IPage } from '../types.js';
/** Create a minimal mock page for testing */
function createMockPage(overrides: Partial<IPage> = {}): IPage {
return {
goto: vi.fn(),
evaluate: vi.fn().mockResolvedValue(null),
snapshot: vi.fn().mockResolvedValue(''),
click: vi.fn(),
typeText: vi.fn(),
pressKey: vi.fn(),
wait: vi.fn(),
tabs: vi.fn().mockResolvedValue([]),
closeTab: vi.fn(),
newTab: vi.fn(),
selectTab: vi.fn(),
networkRequests: vi.fn().mockResolvedValue([]),
consoleMessages: vi.fn().mockResolvedValue(''),
scroll: vi.fn(),
autoScroll: vi.fn(),
installInterceptor: vi.fn(),
getInterceptedRequests: vi.fn().mockResolvedValue([]),
...overrides,
};
}
describe('executePipeline', () => {
it('returns null for empty pipeline', async () => {
const result = await executePipeline(null, []);
expect(result).toBeNull();
});
it('skips null/invalid steps', async () => {
const result = await executePipeline(null, [null, undefined, 42] as any);
expect(result).toBeNull();
});
it('executes navigate step', async () => {
const page = createMockPage();
await executePipeline(page, [
{ navigate: 'https://example.com' },
]);
expect(page.goto).toHaveBeenCalledWith('https://example.com');
});
it('executes evaluate + select pipeline', async () => {
const page = createMockPage({
evaluate: vi.fn().mockResolvedValue({ data: { list: [{ name: 'a' }, { name: 'b' }] } }),
});
const result = await executePipeline(page, [
{ evaluate: '() => ({ data: { list: [{name: "a"}, {name: "b"}] } })' },
{ select: 'data.list' },
]);
expect(result).toEqual([{ name: 'a' }, { name: 'b' }]);
});
it('executes map step to transform items', async () => {
const page = createMockPage({
evaluate: vi.fn().mockResolvedValue([
{ title: 'Hello', count: 10 },
{ title: 'World', count: 20 },
]),
});
const result = await executePipeline(page, [
{ evaluate: 'test' },
{ map: { name: '${{ item.title }}', score: '${{ item.count }}' } },
]);
expect(result).toEqual([
{ name: 'Hello', score: 10 },
{ name: 'World', score: 20 },
]);
});
it('executes limit step', async () => {
const page = createMockPage({
evaluate: vi.fn().mockResolvedValue([1, 2, 3, 4, 5]),
});
const result = await executePipeline(page, [
{ evaluate: 'test' },
{ limit: '3' },
]);
expect(result).toEqual([1, 2, 3]);
});
it('executes sort step', async () => {
const page = createMockPage({
evaluate: vi.fn().mockResolvedValue([{ n: 3 }, { n: 1 }, { n: 2 }]),
});
const result = await executePipeline(page, [
{ evaluate: 'test' },
{ sort: { by: 'n', order: 'asc' } },
]);
expect(result).toEqual([{ n: 1 }, { n: 2 }, { n: 3 }]);
});
it('executes sort step with desc order', async () => {
const page = createMockPage({
evaluate: vi.fn().mockResolvedValue([{ n: 1 }, { n: 3 }, { n: 2 }]),
});
const result = await executePipeline(page, [
{ evaluate: 'test' },
{ sort: { by: 'n', order: 'desc' } },
]);
expect(result).toEqual([{ n: 3 }, { n: 2 }, { n: 1 }]);
});
it('executes wait step with number', async () => {
const page = createMockPage();
await executePipeline(page, [
{ wait: 2 },
]);
expect(page.wait).toHaveBeenCalledWith(2);
});
it('handles unknown steps gracefully in debug mode', async () => {
const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
await executePipeline(null, [
{ unknownStep: 'test' },
], { debug: true });
expect(stderr).toHaveBeenCalledWith(expect.stringContaining('Unknown step'));
stderr.mockRestore();
});
it('passes args through template rendering', async () => {
const page = createMockPage({
evaluate: vi.fn().mockResolvedValue([1, 2, 3, 4, 5]),
});
const result = await executePipeline(page, [
{ evaluate: 'test' },
{ limit: '${{ args.count }}' },
], { args: { count: 2 } });
expect(result).toEqual([1, 2]);
});
it('click step calls page.click', async () => {
const page = createMockPage();
await executePipeline(page, [
{ click: '@5' },
]);
expect(page.click).toHaveBeenCalledWith('5');
});
it('navigate preserves existing data through pipeline', async () => {
const page = createMockPage({
evaluate: vi.fn().mockResolvedValue([{ a: 1 }]),
});
const result = await executePipeline(page, [
{ evaluate: 'test' },
{ navigate: 'https://example.com' },
]);
// navigate should preserve existing data
expect(result).toEqual([{ a: 1 }]);
expect(page.goto).toHaveBeenCalledWith('https://example.com');
});
});
+23 -27
View File
@@ -9,32 +9,33 @@ import { stepFetch } from './steps/fetch.js';
import { stepSelect, stepMap, stepFilter, stepSort, stepLimit } from './steps/transform.js';
import { stepIntercept } from './steps/intercept.js';
import { stepTap } from './steps/tap.js';
import { log } from '../logger.js';
export interface PipelineContext {
args?: Record<string, any>;
debug?: boolean;
}
/** Step handler signature */
/** Step handler: all steps conform to (page, params, data, args) => Promise<any> */
type StepHandler = (page: IPage | null, params: any, data: any, args: Record<string, any>) => Promise<any>;
/** Registry of all available step handlers */
const STEP_HANDLERS: Record<string, StepHandler> = {
navigate: stepNavigate as StepHandler,
navigate: stepNavigate,
fetch: stepFetch,
select: stepSelect as StepHandler,
evaluate: stepEvaluate as StepHandler,
snapshot: stepSnapshot as StepHandler,
click: stepClick as StepHandler,
type: stepType as StepHandler,
wait: stepWait as StepHandler,
press: stepPress as StepHandler,
map: stepMap as StepHandler,
filter: stepFilter as StepHandler,
sort: stepSort as StepHandler,
limit: stepLimit as StepHandler,
intercept: stepIntercept as StepHandler,
tap: stepTap as StepHandler,
select: stepSelect,
evaluate: stepEvaluate,
snapshot: stepSnapshot,
click: stepClick,
type: stepType,
wait: stepWait,
press: stepPress,
map: stepMap,
filter: stepFilter,
sort: stepSort,
limit: stepLimit,
intercept: stepIntercept,
tap: stepTap,
};
export async function executePipeline(
@@ -57,14 +58,9 @@ export async function executePipeline(
if (handler) {
data = await handler(page, params, data, args);
} else {
if (debug) process.stderr.write(` ${chalk.yellow('⚠')} Unknown step: ${op}\n`);
if (debug) log.warn(`Unknown step: ${op}`);
}
// Detect error objects returned by steps (e.g. tap store not found)
if (data && typeof data === 'object' && !Array.isArray(data) && data.error) {
process.stderr.write(` ${chalk.yellow('⚠')} ${chalk.yellow(op)}: ${data.error}\n`);
if (data.hint) process.stderr.write(` ${chalk.dim('💡')} ${chalk.dim(data.hint)}\n`);
}
if (debug) debugStepResult(op, data);
}
}
@@ -78,21 +74,21 @@ function debugStepStart(stepNum: number, total: number, op: string, params: any)
} else if (params && typeof params === 'object' && !Array.isArray(params)) {
preview = ` (${Object.keys(params).join(', ')})`;
}
process.stderr.write(` ${chalk.dim(`[${stepNum}/${total}]`)} ${chalk.bold.cyan(op)}${preview}\n`);
log.step(stepNum, total, op, preview);
}
function debugStepResult(op: string, data: any): void {
if (data === null || data === undefined) {
process.stderr.write(` ${chalk.dim('(no data)')}\n`);
log.stepResult('(no data)');
} else if (Array.isArray(data)) {
process.stderr.write(` ${chalk.dim(`${data.length} items`)}\n`);
log.stepResult(`${data.length} items`);
} else if (typeof data === 'object') {
const keys = Object.keys(data).slice(0, 5);
process.stderr.write(` ${chalk.dim(`dict (${keys.join(', ')}${Object.keys(data).length > 5 ? '...' : ''})`)}\n`);
log.stepResult(`dict (${keys.join(', ')}${Object.keys(data).length > 5 ? '...' : ''})`);
} else if (typeof data === 'string') {
const p = data.slice(0, 60).replace(/\n/g, '\\n');
process.stderr.write(` ${chalk.dim(`"${p}${data.length > 60 ? '...' : ''}"`)}\n`);
log.stepResult(`"${p}${data.length > 60 ? '...' : ''}"`);
} else {
process.stderr.write(` ${chalk.dim(`${typeof data}`)}\n`);
log.stepResult(`${typeof data}`);
}
}
+18 -18
View File
@@ -6,53 +6,53 @@
import type { IPage } from '../../types.js';
import { render, normalizeEvaluateSource } from '../template.js';
export async function stepNavigate(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
export async function stepNavigate(page: IPage | null, params: any, data: any, args: Record<string, any>): Promise<any> {
const url = render(params, { args, data });
await page.goto(String(url));
await page!.goto(String(url));
return data;
}
export async function stepClick(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
await page.click(String(render(params, { args, data })).replace(/^@/, ''));
export async function stepClick(page: IPage | null, params: any, data: any, args: Record<string, any>): Promise<any> {
await page!.click(String(render(params, { args, data })).replace(/^@/, ''));
return data;
}
export async function stepType(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
export async function stepType(page: IPage | null, params: any, data: any, args: Record<string, any>): Promise<any> {
if (typeof params === 'object' && params) {
const ref = String(render(params.ref ?? '', { args, data })).replace(/^@/, '');
const text = String(render(params.text ?? '', { args, data }));
await page.typeText(ref, text);
if (params.submit) await page.pressKey('Enter');
await page!.typeText(ref, text);
if (params.submit) await page!.pressKey('Enter');
}
return data;
}
export async function stepWait(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
if (typeof params === 'number') await page.wait(params);
export async function stepWait(page: IPage | null, params: any, data: any, args: Record<string, any>): Promise<any> {
if (typeof params === 'number') await page!.wait(params);
else if (typeof params === 'object' && params) {
if ('text' in params) {
await page.wait({
await page!.wait({
text: String(render(params.text, { args, data })),
timeout: params.timeout
});
} else if ('time' in params) await page.wait(Number(params.time));
} else if (typeof params === 'string') await page.wait(Number(render(params, { args, data })));
} else if ('time' in params) await page!.wait(Number(params.time));
} else if (typeof params === 'string') await page!.wait(Number(render(params, { args, data })));
return data;
}
export async function stepPress(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
await page.pressKey(String(render(params, { args, data })));
export async function stepPress(page: IPage | null, params: any, data: any, args: Record<string, any>): Promise<any> {
await page!.pressKey(String(render(params, { args, data })));
return data;
}
export async function stepSnapshot(page: IPage, params: any, _data: any, _args: Record<string, any>): Promise<any> {
export async function stepSnapshot(page: IPage | null, params: any, _data: any, _args: Record<string, any>): Promise<any> {
const opts = (typeof params === 'object' && params) ? params : {};
return page.snapshot({ interactive: opts.interactive ?? false, compact: opts.compact ?? false, maxDepth: opts.max_depth, raw: opts.raw ?? false });
return page!.snapshot({ interactive: opts.interactive ?? false, compact: opts.compact ?? false, maxDepth: opts.max_depth, raw: opts.raw ?? false });
}
export async function stepEvaluate(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
export async function stepEvaluate(page: IPage | null, params: any, data: any, args: Record<string, any>): Promise<any> {
const js = String(render(params, { args, data }));
let result = await page.evaluate(normalizeEvaluateSource(js));
let result = await page!.evaluate(normalizeEvaluateSource(js));
// MCP may return JSON as a string — auto-parse it
if (typeof result === 'string') {
const trimmed = result.trim();
+4 -3
View File
@@ -45,11 +45,12 @@ async function fetchSingle(
}
const headersJs = JSON.stringify(renderedHeaders);
const escapedUrl = finalUrl.replace(/"/g, '\\"');
const urlJs = JSON.stringify(finalUrl);
const methodJs = JSON.stringify(method.toUpperCase());
return page.evaluate(`
async () => {
const resp = await fetch("${escapedUrl}", {
method: "${method}", headers: ${headersJs}, credentials: "include"
const resp = await fetch(${urlJs}, {
method: ${methodJs}, headers: ${headersJs}, credentials: "include"
});
return await resp.json();
}
+10 -61
View File
@@ -4,8 +4,9 @@
import type { IPage } from '../../types.js';
import { render } from '../template.js';
import { generateInterceptorJs, generateReadInterceptedJs } from '../../interceptor.js';
export async function stepIntercept(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
export async function stepIntercept(page: IPage | null, params: any, data: any, args: Record<string, any>): Promise<any> {
const cfg = typeof params === 'object' ? params : {};
const trigger = cfg.trigger ?? '';
const capturePattern = cfg.capture ?? '';
@@ -15,82 +16,30 @@ export async function stepIntercept(page: IPage, params: any, data: any, args: R
if (!capturePattern) return data;
// Step 1: Inject fetch/XHR interceptor BEFORE trigger
await page.evaluate(`
() => {
window.__opencli_intercepted = window.__opencli_intercepted || [];
const pattern = ${JSON.stringify(capturePattern)};
if (!window.__opencli_fetch_patched) {
const origFetch = window.fetch;
window.fetch = async function(...args) {
const reqUrl = typeof args[0] === 'string' ? args[0] : (args[0] && args[0].url) || '';
const response = await origFetch.apply(this, args);
setTimeout(async () => {
try {
if (reqUrl.includes(pattern)) {
const clone = response.clone();
const json = await clone.json();
window.__opencli_intercepted.push(json);
}
} catch(e) {}
}, 0);
return response;
};
window.__opencli_fetch_patched = true;
}
if (!window.__opencli_xhr_patched) {
const XHR = XMLHttpRequest.prototype;
const open = XHR.open;
const send = XHR.send;
XHR.open = function(method, url, ...args) {
this._reqUrl = url;
return open.call(this, method, url, ...args);
};
XHR.send = function(...args) {
this.addEventListener('load', function() {
try {
if (this._reqUrl && this._reqUrl.includes(pattern)) {
window.__opencli_intercepted.push(JSON.parse(this.responseText));
}
} catch(e) {}
});
return send.apply(this, args);
};
window.__opencli_xhr_patched = true;
}
}
`);
await page!.evaluate(generateInterceptorJs(JSON.stringify(capturePattern)));
// Step 2: Execute the trigger action
if (trigger.startsWith('navigate:')) {
const url = render(trigger.slice('navigate:'.length), { args, data });
await page.goto(String(url));
await page!.goto(String(url));
} else if (trigger.startsWith('evaluate:')) {
const js = trigger.slice('evaluate:'.length);
const { normalizeEvaluateSource } = await import('../template.js');
await page.evaluate(normalizeEvaluateSource(render(js, { args, data }) as string));
await page!.evaluate(normalizeEvaluateSource(render(js, { args, data }) as string));
} else if (trigger.startsWith('click:')) {
const ref = render(trigger.slice('click:'.length), { args, data });
await page.click(String(ref).replace(/^@/, ''));
await page!.click(String(ref).replace(/^@/, ''));
} else if (trigger === 'scroll') {
await page.scroll('down');
await page!.scroll('down');
}
// Step 3: Wait a bit for network requests to fire
await page.wait(Math.min(timeout, 3));
await page!.wait(Math.min(timeout, 3));
// Step 4: Retrieve captured data
const matchingResponses = await page.evaluate(`
() => {
const data = window.__opencli_intercepted || [];
window.__opencli_intercepted = []; // clear after reading
return data;
}
`);
const matchingResponses = await page!.evaluate(generateReadInterceptedJs());
// Step 4: Select from response if specified
// Step 5: Select from response if specified
let result = matchingResponses.length === 1 ? matchingResponses[0] :
matchingResponses.length > 1 ? matchingResponses : data;
+14 -53
View File
@@ -11,8 +11,9 @@
import type { IPage } from '../../types.js';
import { render } from '../template.js';
import { generateTapInterceptorJs } from '../../interceptor.js';
export async function stepTap(page: IPage, params: any, data: any, args: Record<string, any>): Promise<any> {
export async function stepTap(page: IPage | null, params: any, data: any, args: Record<string, any>): Promise<any> {
const cfg = typeof params === 'object' ? params : {};
const storeName = String(render(cfg.store ?? '', { args, data }));
const actionName = String(render(cfg.action ?? '', { args, data }));
@@ -38,53 +39,15 @@ export async function stepTap(page: IPage, params: any, data: any, args: Record<
? `store[${JSON.stringify(actionName)}](${actionArgsRendered.join(', ')})`
: `store[${JSON.stringify(actionName)}]()`;
// Use shared interceptor generator for fetch/XHR patching
const tap = generateTapInterceptorJs(JSON.stringify(capturePattern));
const js = `
async () => {
// ── 1. Setup capture proxy (fetch + XHR dual interception) ──
let captured = null;
let captureResolve;
const capturePromise = new Promise(r => { captureResolve = r; });
const capturePattern = ${JSON.stringify(capturePattern)};
// Intercept fetch API
const origFetch = window.fetch;
window.fetch = async function(...fetchArgs) {
const resp = await origFetch.apply(this, fetchArgs);
try {
const url = typeof fetchArgs[0] === 'string' ? fetchArgs[0]
: fetchArgs[0] instanceof Request ? fetchArgs[0].url : String(fetchArgs[0]);
if (capturePattern && url.includes(capturePattern) && !captured) {
try { captured = await resp.clone().json(); captureResolve(); } catch {}
}
} catch {}
return resp;
};
// Intercept XMLHttpRequest
const origXhrOpen = XMLHttpRequest.prototype.open;
const origXhrSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function(method, url) {
this.__tapUrl = String(url);
return origXhrOpen.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function(body) {
if (capturePattern && this.__tapUrl?.includes(capturePattern)) {
const xhr = this;
const origHandler = xhr.onreadystatechange;
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && !captured) {
try { captured = JSON.parse(xhr.responseText); captureResolve(); } catch {}
}
if (origHandler) origHandler.apply(this, arguments);
};
const origOnload = xhr.onload;
xhr.onload = function() {
if (!captured) { try { captured = JSON.parse(xhr.responseText); captureResolve(); } catch {} }
if (origOnload) origOnload.apply(this, arguments);
};
}
return origXhrSend.apply(this, arguments);
};
${tap.setupVar}
${tap.fetchPatch}
${tap.xhrPatch}
try {
// ── 2. Find store ──
@@ -119,21 +82,19 @@ export async function stepTap(page: IPage, params: any, data: any, args: Record<
await ${actionCall};
// ── 4. Wait for network response ──
if (!captured) {
if (!${tap.capturedVar}) {
const timeoutPromise = new Promise(r => setTimeout(r, ${timeout} * 1000));
await Promise.race([capturePromise, timeoutPromise]);
await Promise.race([${tap.promiseVar}, timeoutPromise]);
}
} finally {
// ── 5. Always restore originals ──
window.fetch = origFetch;
XMLHttpRequest.prototype.open = origXhrOpen;
XMLHttpRequest.prototype.send = origXhrSend;
${tap.restorePatch}
}
if (!captured) return { error: 'No matching response captured for pattern: ' + capturePattern };
return captured${selectChain} ?? captured;
if (!${tap.capturedVar}) return { error: 'No matching response captured for pattern: ' + capturePattern };
return ${tap.capturedVar}${selectChain} ?? ${tap.capturedVar};
}
`;
return page.evaluate(js);
return page!.evaluate(js);
}
+106
View File
@@ -0,0 +1,106 @@
/**
* Tests for registry.ts: Strategy enum, cli() registration, helpers.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { cli, getRegistry, fullName, strategyLabel, registerCommand, Strategy, type CliCommand } from './registry.js';
describe('cli() registration', () => {
it('registers a command and returns it', () => {
const cmd = cli({
site: 'test-registry',
name: 'hello',
description: 'A test command',
strategy: Strategy.PUBLIC,
browser: false,
});
expect(cmd.site).toBe('test-registry');
expect(cmd.name).toBe('hello');
expect(cmd.strategy).toBe(Strategy.PUBLIC);
expect(cmd.browser).toBe(false);
expect(cmd.args).toEqual([]);
});
it('puts registered command in the registry', () => {
cli({
site: 'test-registry',
name: 'registered',
description: 'test',
});
const registry = getRegistry();
expect(registry.has('test-registry/registered')).toBe(true);
});
it('defaults strategy to COOKIE when browser is true', () => {
const cmd = cli({
site: 'test-registry',
name: 'default-strategy',
});
expect(cmd.strategy).toBe(Strategy.COOKIE);
expect(cmd.browser).toBe(true);
});
it('defaults strategy to PUBLIC when browser is false', () => {
const cmd = cli({
site: 'test-registry',
name: 'no-browser',
browser: false,
});
expect(cmd.strategy).toBe(Strategy.PUBLIC);
});
it('overwrites existing command on re-registration', () => {
cli({ site: 'test-registry', name: 'overwrite', description: 'v1' });
cli({ site: 'test-registry', name: 'overwrite', description: 'v2' });
const reg = getRegistry();
expect(reg.get('test-registry/overwrite')?.description).toBe('v2');
});
});
describe('fullName', () => {
it('returns site/name', () => {
const cmd: CliCommand = {
site: 'bilibili', name: 'hot', description: '', args: [],
};
expect(fullName(cmd)).toBe('bilibili/hot');
});
});
describe('strategyLabel', () => {
it('returns strategy string', () => {
const cmd: CliCommand = {
site: 'test', name: 'test', description: '', args: [],
strategy: Strategy.INTERCEPT,
};
expect(strategyLabel(cmd)).toBe('intercept');
});
it('returns public when no strategy set', () => {
const cmd: CliCommand = {
site: 'test', name: 'test', description: '', args: [],
};
expect(strategyLabel(cmd)).toBe('public');
});
});
describe('registerCommand', () => {
it('registers a pre-built command', () => {
const cmd: CliCommand = {
site: 'test-registry',
name: 'direct-reg',
description: 'directly registered',
args: [],
strategy: Strategy.HEADER,
browser: true,
};
registerCommand(cmd);
const reg = getRegistry();
expect(reg.get('test-registry/direct-reg')?.strategy).toBe(Strategy.HEADER);
});
});
+8 -18
View File
@@ -17,6 +17,7 @@ export interface Arg {
type?: string;
default?: any;
required?: boolean;
positional?: boolean;
help?: string;
choices?: string[];
}
@@ -30,33 +31,23 @@ export interface CliCommand {
browser?: boolean;
args: Arg[];
columns?: string[];
func?: (page: IPage | null, kwargs: Record<string, any>, debug?: boolean) => Promise<any>;
func?: (page: IPage, kwargs: Record<string, any>, debug?: boolean) => Promise<any>;
pipeline?: any[];
timeoutSeconds?: number;
source?: string;
/** Internal: lazy-loaded TS module support */
_lazy?: boolean;
_modulePath?: string;
/** Force extension bridge mode (bypass CDP), for anti-bot sites */
forceExtension?: boolean;
}
export interface CliOptions {
/** Internal extension for lazy-loaded TS modules (not exposed in public API) */
export interface InternalCliCommand extends CliCommand {
_lazy?: boolean;
_modulePath?: string;
}
export interface CliOptions extends Partial<Omit<CliCommand, 'args' | 'description'>> {
site: string;
name: string;
description?: string;
domain?: string;
strategy?: Strategy;
browser?: boolean;
args?: Arg[];
columns?: string[];
func?: (page: IPage | null, kwargs: Record<string, any>, debug?: boolean) => Promise<any>;
pipeline?: any[];
timeoutSeconds?: number;
/** Force extension bridge mode (bypass CDP), for anti-bot sites */
forceExtension?: boolean;
}
const _registry = new Map<string, CliCommand>();
export function cli(opts: CliOptions): CliCommand {
@@ -72,7 +63,6 @@ export function cli(opts: CliOptions): CliCommand {
func: opts.func,
pipeline: opts.pipeline,
timeoutSeconds: opts.timeoutSeconds,
forceExtension: opts.forceExtension,
};
const key = fullName(cmd);
+23 -10
View File
@@ -9,29 +9,42 @@ export const DEFAULT_BROWSER_COMMAND_TIMEOUT = parseInt(process.env.OPENCLI_BROW
export const DEFAULT_BROWSER_EXPLORE_TIMEOUT = parseInt(process.env.OPENCLI_BROWSER_EXPLORE_TIMEOUT ?? '120', 10);
export const DEFAULT_BROWSER_SMOKE_TIMEOUT = parseInt(process.env.OPENCLI_BROWSER_SMOKE_TIMEOUT ?? '60', 10);
/**
* Timeout with seconds unit. Used for high-level command timeouts.
*/
export async function runWithTimeout<T>(
promise: Promise<T>,
opts: { timeout: number; label?: string },
): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`${opts.label ?? 'Operation'} timed out after ${opts.timeout}s`));
}, opts.timeout * 1000);
return withTimeoutMs(promise, opts.timeout * 1000, `${opts.label ?? 'Operation'} timed out after ${opts.timeout}s`);
}
promise
.then((result) => { clearTimeout(timer); resolve(result); })
.catch((err) => { clearTimeout(timer); reject(err); });
/**
* Timeout with milliseconds unit. Used for low-level internal timeouts.
*/
export function withTimeoutMs<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(message)), timeoutMs);
promise.then(
(value) => { clearTimeout(timer); resolve(value); },
(error) => { clearTimeout(timer); reject(error); },
);
});
}
/** Interface for browser factory (PlaywrightMCP or test mocks) */
export interface IBrowserFactory {
connect(opts?: { timeout?: number }): Promise<IPage>;
close(): Promise<void>;
}
export async function browserSession<T>(
BrowserFactory: new () => any,
BrowserFactory: new () => IBrowserFactory,
fn: (page: IPage) => Promise<T>,
opts?: { forceExtension?: boolean },
): Promise<T> {
const mcp = new BrowserFactory();
try {
const page = await mcp.connect({ timeout: DEFAULT_BROWSER_CONNECT_TIMEOUT, forceExtension: opts?.forceExtension });
const page = await mcp.connect({ timeout: DEFAULT_BROWSER_CONNECT_TIMEOUT });
return await fn(page);
} finally {
await mcp.close().catch(() => {});
+36
View File
@@ -0,0 +1,36 @@
/**
* setup.ts — OpenCLI MCP token setup
*
* OpenCLI MCP is now tokenless. This file simply informs the user
* that token configuration is no longer required.
*/
import chalk from 'chalk';
import { checkTokenConnectivity } from './doctor.js';
export async function runSetup(opts: { cliVersion?: string; token?: string } = {}) {
console.log();
console.log(chalk.bold(' opencli setup') + chalk.dim(' — OpenCLI MCP configuration'));
console.log();
console.log(` ${chalk.green('✓')} Configuration complete.`);
console.log(` ${chalk.dim('OpenCLI MCP Bridge no longer requires token configuration.')}`);
console.log();
// Auto-verify browser connectivity
console.log(chalk.dim(' Verifying browser connectivity...'));
try {
const result = await checkTokenConnectivity({ timeout: 5 });
if (result.ok) {
console.log(` ${chalk.green('✓')} Browser connected in ${(result.durationMs / 1000).toFixed(1)}s`);
} else {
console.log(` ${chalk.yellow('!')} Browser connectivity test failed: ${result.error ?? 'unknown'}`);
console.log(chalk.dim(' To use opencli, make sure Chrome is running with Developer Mode'));
console.log(chalk.dim(' and the OpenCLI MCP Bridge extension is enabled.'));
console.log(chalk.dim(` Run ${chalk.bold('opencli doctor --live')} to re-test connectivity.`));
}
} catch {
console.log(` ${chalk.yellow('!')} Browser connectivity test skipped (Chrome may not be running).`);
console.log(chalk.dim(' Start Chrome to begin using opencli.'));
console.log(chalk.dim(` Run ${chalk.bold('opencli doctor --live')} to re-test connectivity.`));
}
console.log();
}
+579
View File
@@ -0,0 +1,579 @@
/**
* Tests for snapshotFormatter.ts: Playwright MCP snapshot tree filtering.
*
* Uses sanitized excerpts from real websites (GitHub, Bilibili, Twitter)
* to validate noise filtering, annotation stripping, and output quality.
*/
import { describe, it, expect } from 'vitest';
import { formatSnapshot } from './snapshotFormatter.js';
// ---------------------------------------------------------------------------
// Fixtures: sanitized excerpts from real Playwright MCP snapshots
// ---------------------------------------------------------------------------
/** GitHub dashboard navigation bar (generic-heavy, refs, /url: lines) */
const GITHUB_NAV = `\
- generic [ref=e2]:
- region
- generic [ref=e3]:
- link "Skip to content" [ref=e4] [cursor=pointer]:
- /url: "#start-of-content"
- banner "Global Navigation Menu" [ref=e8]:
- generic [ref=e9]:
- generic [ref=e10]:
- button "Open menu" [ref=e12] [cursor=pointer]:
- img [ref=e13]
- link "Homepage" [ref=e15] [cursor=pointer]:
- /url: /
- img [ref=e16]
- generic [ref=e18]:
- navigation "Breadcrumbs" [ref=e19]:
- list [ref=e20]:
- listitem [ref=e21]:
- link "Dashboard" [ref=e22] [cursor=pointer]:
- /url: https://github.com/
- generic [ref=e23]: Dashboard
- button "Search or jump to…" [ref=e26] [cursor=pointer]:
- generic [ref=e27]:
- generic:
- img
- generic [ref=e28]:
- generic:
- text: Type
- generic: /
- text: to search`;
/** GitHub repo list sidebar (repetitive structure) */
const GITHUB_REPOS = `\
- navigation "Repositories" [ref=e79]:
- generic [ref=e80]:
- generic [ref=e81]:
- heading "Top repositories" [level=2] [ref=e82]
- link "New" [ref=e83] [cursor=pointer]:
- /url: /new
- generic [ref=e84]:
- generic:
- img
- generic [ref=e85]: New
- search "Top repositories" [ref=e86]:
- textbox "Find a repository…" [ref=e87]
- list [ref=e88]:
- listitem [ref=e89]:
- generic [ref=e90]:
- link "Repository" [ref=e91] [cursor=pointer]:
- /url: /jackwener/twitter-cli
- img "Repository" [ref=e92]
- link "jackwener/twitter-cli" [ref=e94] [cursor=pointer]:
- /url: /jackwener/twitter-cli
- listitem [ref=e95]:
- generic [ref=e96]:
- link "Repository" [ref=e97] [cursor=pointer]:
- /url: /jackwener/opencli
- img "Repository" [ref=e98]
- link "jackwener/opencli" [ref=e100] [cursor=pointer]:
- /url: /jackwener/opencli`;
/** Bilibili nav bar (Chinese text, multiple link categories) */
const BILIBILI_NAV = `\
- generic [ref=e3]:
- generic [ref=e4]:
- generic [ref=e5]:
- list [ref=e6]:
- listitem [ref=e7]:
- link "首页" [ref=e8] [cursor=pointer]:
- /url: //www.bilibili.com
- img [ref=e9]
- generic [ref=e11]: 首页
- listitem [ref=e12]:
- link "番剧" [ref=e13] [cursor=pointer]:
- /url: //www.bilibili.com/anime/
- listitem [ref=e14]:
- link "直播" [ref=e15] [cursor=pointer]:
- /url: //live.bilibili.com
- generic [ref=e32]:
- textbox "冷知识 金廷26年胜率100%" [ref=e34]
- img [ref=e36] [cursor=pointer]`;
/** Bilibili video card (deeply nested generic wrappers, view counts) */
const BILIBILI_VIDEO = `\
- generic [ref=e363]:
- link "超酷时刻 即将到来 3.3万 40 16:24" [ref=e364] [cursor=pointer]:
- /url: https://www.bilibili.com/video/BV1zVw5zoEFt
- generic [ref=e365]:
- img "超酷时刻 即将到来" [ref=e368]
- generic:
- generic:
- generic:
- generic:
- img
- generic: 3.3万
- generic:
- img
- generic: "40"
- generic: 16:24
- generic [ref=e370]:
- heading "超酷时刻 即将到来" [level=3] [ref=e371]:
- link "超酷时刻 即将到来" [ref=e372] [cursor=pointer]:
- /url: https://www.bilibili.com/video/BV1zVw5zoEFt
- link "Tesla特斯拉中国 · 13小时前" [ref=e374] [cursor=pointer]:
- /url: //space.bilibili.com/491190876
- img [ref=e375]
- generic "Tesla特斯拉中国" [ref=e379]
- generic [ref=e380]: · 13小时前`;
/** Empty paragraph blocks (Bilibili bottom section) */
const BILIBILI_EMPTY = `\
- generic [ref=e576]:
- generic:
- generic:
- generic:
- paragraph
- paragraph
- paragraph
- generic [ref=e577]:
- generic:
- generic:
- generic:
- paragraph
- paragraph
- paragraph`;
/** Twitter-style feed item (simulated based on common patterns) */
const TWITTER_TWEET = `\
- main [ref=e100]:
- region "Timeline" [ref=e101]:
- article [ref=e200]:
- generic [ref=e201]:
- generic [ref=e202]:
- link "@elonmusk" [ref=e203] [cursor=pointer]:
- /url: /elonmusk
- img "@elonmusk" [ref=e204]
- generic [ref=e205]:
- generic [ref=e206]: Elon Musk
- generic [ref=e207]: @elonmusk
- generic [ref=e208]:
- generic [ref=e209]: This is a very long tweet that goes on and on about various things including technology, space, and other random topics that make this text exceed any reasonable length limit we might want to set for display purposes in a CLI interface.
- generic [ref=e210]:
- button "Reply" [ref=e211] [cursor=pointer]:
- img [ref=e212]
- generic [ref=e213]: "42"
- button "Retweet" [ref=e214] [cursor=pointer]:
- img [ref=e215]
- generic [ref=e216]: "1.2K"
- button "Like" [ref=e217] [cursor=pointer]:
- img [ref=e218]
- generic [ref=e219]: "5.3K"
- separator [ref=e300]`;
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe('formatSnapshot', () => {
describe('basic behavior', () => {
it('returns empty string for empty/null input', () => {
expect(formatSnapshot('')).toBe('');
expect(formatSnapshot(null as any)).toBe('');
expect(formatSnapshot(undefined as any)).toBe('');
});
it('strips [ref=...] and [cursor=...] annotations', () => {
const input = '- button "Click me" [ref=e42] [cursor=pointer]';
const result = formatSnapshot(input);
expect(result).not.toContain('[ref=');
expect(result).not.toContain('[cursor=');
expect(result).toContain('button "Click me"');
});
it('removes /url: metadata lines', () => {
const input = `\
- link "Home" [ref=e1] [cursor=pointer]:
- /url: https://example.com
- generic [ref=e2]: Home`;
const result = formatSnapshot(input);
expect(result).not.toContain('/url:');
expect(result).not.toContain('https://example.com');
});
it('assigns sequential [@N] refs to interactive elements', () => {
const input = `\
- button "Save" [ref=e1]
- link "Cancel" [ref=e2]
- textbox "Name" [ref=e3]`;
const result = formatSnapshot(input);
expect(result).toContain('[@1] button "Save"');
expect(result).toContain('[@2] link "Cancel"');
expect(result).toContain('[@3] textbox "Name"');
});
});
describe('noise filtering', () => {
it('removes generic nodes without text', () => {
const input = `\
- generic [ref=e1]:
- generic [ref=e2]:
- button "Click" [ref=e3]`;
const result = formatSnapshot(input);
expect(result).not.toMatch(/^generic/m);
expect(result).toContain('button "Click"');
});
it('keeps generic nodes WITH text content', () => {
const input = '- generic [ref=e23]: Dashboard';
const result = formatSnapshot(input);
expect(result).toContain('generic: Dashboard');
});
it('removes img nodes without alt text', () => {
const input = `\
- img [ref=e13]
- img "Profile photo" [ref=e14]`;
const result = formatSnapshot(input);
expect(result).not.toContain('img\n');
expect(result).toContain('img "Profile photo"');
});
it('removes separator nodes', () => {
const input = '- separator [ref=e304]';
const result = formatSnapshot(input);
expect(result).toBe('');
});
it('removes presentation/none roles', () => {
const input = `\
- presentation [ref=e1]
- none [ref=e2]
- button "OK" [ref=e3]`;
const result = formatSnapshot(input);
expect(result).not.toContain('presentation');
expect(result).not.toContain('none');
expect(result).toContain('button "OK"');
});
});
describe('empty container pruning', () => {
it('prunes containers with no visible children', () => {
const input = `\
- list [ref=e88]:
- listitem [ref=e89]:
- generic [ref=e90]:
- img [ref=e91]`;
// After filtering: generic (no text) → removed, img (no alt) → removed
// listitem becomes empty → pruned, list becomes empty → pruned
const result = formatSnapshot(input);
expect(result).toBe('');
});
it('keeps containers with visible children', () => {
const input = `\
- list [ref=e1]:
- listitem [ref=e2]:
- link "Home" [ref=e3]`;
const result = formatSnapshot(input);
expect(result).toContain('list');
expect(result).toContain('listitem');
expect(result).toContain('link "Home"');
});
});
describe('maxDepth option', () => {
it('limits output to specified depth', () => {
const input = `\
- main [ref=e1]:
- heading "Dashboard" [ref=e2]
- navigation [ref=e3]:
- list [ref=e4]:
- link "Deep link" [ref=e5]`;
const result = formatSnapshot(input, { maxDepth: 2 });
expect(result).toContain('main');
expect(result).toContain('heading "Dashboard"');
// navigation is pruned: its only child list is empty after link is excluded by maxDepth
expect(result).not.toContain('navigation');
expect(result).not.toContain('Deep link');
});
it('handles maxDepth=0 correctly (was a bug)', () => {
const input = `\
- heading "Title" [ref=e1]
- link "Sub" [ref=e2]`;
const result = formatSnapshot(input, { maxDepth: 0 });
expect(result).toContain('heading "Title"');
expect(result).not.toContain('Sub');
});
});
describe('interactive mode', () => {
it('keeps interactive elements and landmarks', () => {
const result = formatSnapshot(GITHUB_NAV, { interactive: true });
// Interactive elements should be present
expect(result).toContain('button');
expect(result).toContain('link');
// Landmarks preserved
expect(result).toContain('banner');
expect(result).toContain('navigation');
});
it('filters non-interactive, non-landmark, textless nodes', () => {
const input = `\
- main [ref=e1]:
- generic [ref=e2]:
- generic [ref=e3]:
- button "Save" [ref=e4]
- generic [ref=e5]: some text content`;
const result = formatSnapshot(input, { interactive: true });
expect(result).toContain('main');
expect(result).toContain('button "Save"');
// generic with text is kept
expect(result).toContain('generic: some text content');
});
});
describe('compact mode', () => {
it('strips bracket annotations and collapses whitespace', () => {
const input = '- button "Save" [ref=e1] [cursor=pointer] [level=2]';
const result = formatSnapshot(input, { compact: true });
// ref/cursor already stripped, but [level=...] should also go in compact
expect(result).not.toContain('[level=');
expect(result).toContain('button');
});
});
describe('maxTextLength option', () => {
it('truncates long content lines', () => {
const input = '- heading "This is a very long heading that should be truncated at some point" [ref=e1]';
const result = formatSnapshot(input, { maxTextLength: 30 });
expect(result.length).toBeLessThanOrEqual(35); // some tolerance for ellipsis
expect(result).toContain('…');
});
});
// ---------------------------------------------------------------------------
// Real-world snapshot integration tests
// ---------------------------------------------------------------------------
describe('GitHub snapshot', () => {
it('drastically reduces nav bar output', () => {
const raw = GITHUB_NAV;
const rawLineCount = raw.split('\n').length;
const result = formatSnapshot(raw);
const resultLineCount = result.split('\n').length;
// Should significantly reduce line count
expect(resultLineCount).toBeLessThan(rawLineCount);
// Key content preserved
expect(result).toContain('link "Skip to content"');
expect(result).toContain('banner "Global Navigation Menu"');
expect(result).toContain('link "Dashboard"');
expect(result).toContain('button "Search or jump to…"');
// Noise removed
expect(result).not.toContain('[ref=');
expect(result).not.toContain('/url:');
});
it('preserves repo list structure', () => {
const result = formatSnapshot(GITHUB_REPOS);
expect(result).toContain('navigation "Repositories"');
expect(result).toContain('heading "Top repositories"');
expect(result).toContain('textbox "Find a repository…"');
expect(result).toContain('link "jackwener/twitter-cli"');
expect(result).toContain('link "jackwener/opencli"');
expect(result).toContain('img "Repository"');
// No refs or urls
expect(result).not.toContain('[ref=');
expect(result).not.toContain('/url:');
});
});
describe('Bilibili snapshot', () => {
it('cleans nav bar with Chinese text', () => {
const result = formatSnapshot(BILIBILI_NAV);
expect(result).toContain('link "首页"');
expect(result).toContain('link "番剧"');
expect(result).toContain('link "直播"');
expect(result).toContain('textbox "冷知识 金廷26年胜率100%"');
expect(result).not.toContain('[ref=');
});
it('handles video card with deeply nested wrappers', () => {
const result = formatSnapshot(BILIBILI_VIDEO);
expect(result).toContain('link "超酷时刻 即将到来 3.3万 40 16:24"');
expect(result).toContain('heading "超酷时刻 即将到来"');
expect(result).toContain('generic "Tesla特斯拉中国"');
// Deeply nested view count generics with text are kept
expect(result).toContain('3.3万');
});
it('prunes empty paragraph blocks', () => {
const result = formatSnapshot(BILIBILI_EMPTY);
// All content is generic (no text) and empty paragraphs
// After noise filtering, everything should be pruned
expect(result.trim()).toBe('');
});
});
describe('Twitter snapshot', () => {
it('preserves tweet structure', () => {
const result = formatSnapshot(TWITTER_TWEET);
expect(result).toContain('main');
expect(result).toContain('region "Timeline"');
expect(result).toContain('link "@elonmusk"');
expect(result).toContain('button "Reply"');
expect(result).toContain('button "Like"');
expect(result).not.toContain('separator');
});
it('truncates long tweet text with maxTextLength', () => {
const result = formatSnapshot(TWITTER_TWEET, { maxTextLength: 60 });
// The long tweet text should be truncated
expect(result).toContain('…');
// But short elements are unaffected
expect(result).toContain('button "Reply"');
});
it('interactive mode keeps only buttons and links', () => {
const result = formatSnapshot(TWITTER_TWEET, { interactive: true });
expect(result).toContain('link "@elonmusk"');
expect(result).toContain('button "Reply"');
expect(result).toContain('button "Retweet"');
expect(result).toContain('button "Like"');
// Structural landmarks kept
expect(result).toContain('main');
expect(result).toContain('region "Timeline"');
expect(result).toContain('article');
});
it('combined options: interactive + maxDepth', () => {
// With maxDepth: 2 and interactive, depth > 2 is filtered.
// article at depth 2 has only generic children (noise-filtered),
// so article gets pruned by container pruning, which cascades up.
const result = formatSnapshot(TWITTER_TWEET, { interactive: true, maxDepth: 2 });
expect(result).toContain('main');
expect(result).not.toContain('button "Reply"');
expect(result).not.toContain('link "@elonmusk"');
});
});
describe('reduction ratios on real data', () => {
it('achieves significant reduction on GitHub nav', () => {
const rawLines = GITHUB_NAV.split('\n').length;
const formatted = formatSnapshot(GITHUB_NAV);
const formattedLines = formatted.split('\n').filter(l => l.trim()).length;
// Expect at least 40% reduction
expect(formattedLines).toBeLessThan(rawLines * 0.6);
});
it('achieves significant reduction on Bilibili video card', () => {
const rawLines = BILIBILI_VIDEO.split('\n').length;
const formatted = formatSnapshot(BILIBILI_VIDEO);
const formattedLines = formatted.split('\n').filter(l => l.trim()).length;
// Expect at least 30% reduction
expect(formattedLines).toBeLessThan(rawLines * 0.7);
});
});
// ---------------------------------------------------------------------------
// Full-page snapshot fixture tests (loaded from __fixtures__/)
// ---------------------------------------------------------------------------
describe('full-page snapshots from fixtures', () => {
const fs = require('node:fs');
const path = require('node:path');
const fixturesDir = path.join(__dirname, '__fixtures__');
function loadFixture(name: string): string | null {
const p = path.join(fixturesDir, name);
if (!fs.existsSync(p)) return null;
return fs.readFileSync(p, 'utf-8');
}
it('GitHub: significant reduction and clean output', () => {
const raw = loadFixture('snapshot_github.txt');
if (!raw) return;
const rawLines = raw.split('\n').length;
const result = formatSnapshot(raw);
const resultLines = result.split('\n').filter((l: string) => l.trim()).length;
// Should achieve > 50% reduction on GitHub dashboard (heavy generic noise)
expect(resultLines).toBeLessThan(rawLines * 0.5);
// No annotations remain
expect(result).not.toContain('[ref=');
expect(result).not.toContain('[cursor=');
expect(result).not.toContain('/url:');
// Key content preserved
expect(result).toContain('link "Skip to content"');
expect(result).toContain('banner "Global Navigation Menu"');
expect(result).toContain('heading "Dashboard"');
});
it('Bilibili: significant reduction and Chinese text preserved', () => {
const raw = loadFixture('snapshot_bilibili.txt');
if (!raw) return;
const rawLines = raw.split('\n').length;
const result = formatSnapshot(raw);
const resultLines = result.split('\n').filter((l: string) => l.trim()).length;
// Should achieve > 40% reduction on Bilibili (lots of imgs and generics)
expect(resultLines).toBeLessThan(rawLines * 0.6);
// No annotations remain
expect(result).not.toContain('[ref=');
expect(result).not.toContain('[cursor=');
// Chinese text preserved
expect(result).toContain('link "首页"');
expect(result).toContain('link "番剧"');
});
it('Twitter/X: significant reduction and tweet structure preserved', () => {
const raw = loadFixture('snapshot_twitter.txt');
if (!raw) return;
const rawLines = raw.split('\n').length;
const result = formatSnapshot(raw);
const resultLines = result.split('\n').filter((l: string) => l.trim()).length;
// Should achieve > 40% reduction on Twitter/X
expect(resultLines).toBeLessThan(rawLines * 0.6);
// No annotations remain
expect(result).not.toContain('[ref=');
expect(result).not.toContain('[cursor=');
expect(result).not.toContain('/url:');
// Key structure preserved
expect(result).toContain('main');
});
it('GitHub interactive mode: drastic reduction', () => {
const raw = loadFixture('snapshot_github.txt');
if (!raw) return;
const result = formatSnapshot(raw, { interactive: true });
const resultLines = result.split('\n').filter((l: string) => l.trim()).length;
// Interactive mode should be much more aggressive
expect(resultLines).toBeLessThan(200);
// Interactive elements still present
expect(result).toContain('button');
expect(result).toContain('link');
expect(result).toContain('textbox');
});
it('Bilibili maxDepth=3: shallow view', () => {
const raw = loadFixture('snapshot_bilibili.txt');
if (!raw) return;
const result = formatSnapshot(raw, { maxDepth: 3 });
const resultLines = result.split('\n').filter((l: string) => l.trim()).length;
// Depth-limited should be very compact
expect(resultLines).toBeLessThan(50);
});
});
});
+401 -15
View File
@@ -1,35 +1,268 @@
/**
* Aria snapshot formatter: parses Playwright MCP snapshot text into clean format.
*
* Multi-pass pipeline:
* 1. Parse & filter: strip annotations, metadata, noise roles, ads, decorators
* 2. Deduplicate: generic/text child matching parent label
* 3. Deduplicate: heading + link with identical labels
* 4. Deduplicate: nested identical links
* 5. Prune: empty containers (iterative bottom-up)
* 6. Collapse: single-child containers
*/
export interface FormatOptions {
interactive?: boolean;
compact?: boolean;
maxDepth?: number;
maxTextLength?: number;
}
const DEFAULT_MAX_TEXT_LENGTH = 200;
// Roles that are pure noise and should always be filtered
const NOISE_ROLES = new Set([
'none', 'presentation', 'separator', 'paragraph', 'tooltip', 'status',
]);
// Roles whose entire subtree should be removed (footer boilerplate, etc.)
const SUBTREE_NOISE_ROLES = new Set([
'contentinfo',
]);
// Roles considered interactive (clickable/typeable)
const INTERACTIVE_ROLES = new Set([
'button', 'link', 'textbox', 'checkbox', 'radio',
'combobox', 'tab', 'menuitem', 'option', 'switch',
'slider', 'spinbutton', 'searchbox',
]);
// Structural landmark roles kept even in interactive mode
const LANDMARK_ROLES = new Set([
'main', 'navigation', 'banner', 'heading', 'search',
'region', 'list', 'listitem', 'article', 'complementary',
'group', 'toolbar', 'tablist',
]);
// Container roles eligible for pruning and collapse
const CONTAINER_ROLES = new Set([
'list', 'listitem', 'group', 'toolbar', 'tablist',
'navigation', 'region', 'complementary',
'search', 'article', 'paragraph', 'figure',
]);
// Decorator / separator text that adds no semantic value
const DECORATOR_TEXT = new Set(['•', '·', '|', '—', '-', '/', '\\']);
// Ad-related URL patterns
const AD_URL_PATTERNS = [
'googleadservices.com/pagead/',
'alb.reddit.com/cr?',
'doubleclick.net/',
'cm.bilibili.com/cm/api/fees/',
];
// Boilerplate button labels to filter (back-to-top, etc.)
const BOILERPLATE_LABELS = [
'回到顶部', 'back to top', 'scroll to top', 'go to top',
];
/**
* Parse role and text from a trimmed snapshot line.
* Handles quoted labels and trailing text after colon correctly,
* including lines wrapped in single quotes by Playwright.
*/
function parseLine(trimmed: string): { role: string; text: string; hasText: boolean; trailingText: string } {
// Unwrap outer single quotes if present (Playwright wraps lines with special chars)
let line = trimmed;
if (line.startsWith("'") && line.endsWith("':")) {
line = line.slice(1, -2) + ':';
} else if (line.startsWith("'") && line.endsWith("'")) {
line = line.slice(1, -1);
}
// Role is the first word
const roleMatch = line.match(/^([a-zA-Z]+)\b/);
const role = roleMatch ? roleMatch[1].toLowerCase() : '';
// Extract quoted text content (the semantic label)
const textMatch = line.match(/"([^"]*)"/);
const text = textMatch ? textMatch[1] : '';
// For trailing text: strip annotations and quoted strings first, then check after last colon
// This avoids matching colons inside quoted labels like "Account: user@email.com"
let stripped = line;
// Remove all quoted strings
stripped = stripped.replace(/"[^"]*"/g, '""');
// Remove all bracket annotations
stripped = stripped.replace(/\[[^\]]*\]/g, '');
const colonIdx = stripped.lastIndexOf(':');
let trailingText = '';
if (colonIdx !== -1) {
const afterColon = stripped.slice(colonIdx + 1).trim();
if (afterColon.length > 0) {
// Get the actual trailing text from original line at same position
const origColonIdx = line.lastIndexOf(':');
if (origColonIdx !== -1) {
trailingText = line.slice(origColonIdx + 1).trim();
}
}
}
return { role, text, hasText: text.length > 0 || trailingText.length > 0, trailingText };
}
/**
* Strip ALL bracket annotations from a content line, preserving quoted strings.
* Handles both double-quoted and outer single-quoted lines from Playwright.
*/
function stripAnnotations(content: string): string {
// Unwrap outer single quotes first
let line = content;
if (line.startsWith("'") && (line.endsWith("':") || line.endsWith("'"))) {
if (line.endsWith("':")) {
line = line.slice(1, -2) + ':';
} else {
line = line.slice(1, -1);
}
}
// Split by double quotes to protect quoted content
const parts = line.split('"');
for (let i = 0; i < parts.length; i += 2) {
// Only strip annotations from non-quoted parts (even indices)
parts[i] = parts[i].replace(/\s*\[[^\]]*\]/g, '');
}
let result = parts.join('"').replace(/\s{2,}/g, ' ').trim();
return result;
}
/**
* Check if a line is a metadata-only line (like /url: ...).
*/
function isMetadataLine(trimmed: string): boolean {
return /^\/[a-zA-Z]+:/.test(trimmed);
}
/**
* Check if text content is purely decorative (separators, dots, etc.)
*/
function isDecoratorText(text: string): boolean {
return DECORATOR_TEXT.has(text.trim());
}
/**
* Check if a node is ad-related based on its text content.
*/
function isAdNode(text: string, trailingText: string): boolean {
const t = (text + ' ' + trailingText).toLowerCase();
if (t.includes('sponsored') || t.includes('advertisement')) return true;
if (t.includes('广告')) return true;
// Check for ad tracking URLs in the label
for (const pattern of AD_URL_PATTERNS) {
if (text.includes(pattern) || trailingText.includes(pattern)) return true;
}
return false;
}
/**
* Check if a node is boilerplate UI (back-to-top, etc.)
*/
function isBoilerplateNode(text: string): boolean {
const t = text.toLowerCase();
return BOILERPLATE_LABELS.some(label => t.includes(label));
}
/**
* Check if a role is noise that should be filtered.
*/
function isNoiseNode(role: string, hasText: boolean, text: string, trailingText: string): boolean {
if (NOISE_ROLES.has(role)) return true;
// generic without text is a wrapper
if (role === 'generic' && !hasText) return true;
// img without alt text is noise
if (role === 'img' && !hasText) return true;
// Decorator-only text nodes
if ((role === 'generic' || role === 'text') && hasText) {
const content = trailingText || text;
if (isDecoratorText(content)) return true;
}
return false;
}
interface Entry {
depth: number;
content: string;
role: string;
text: string;
trailingText: string;
isInteractive: boolean;
isLandmark: boolean;
isSubtreeSkip: boolean; // ad nodes or boilerplate — skip entire subtree
}
export function formatSnapshot(raw: string, opts: FormatOptions = {}): string {
if (!raw || typeof raw !== 'string') return '';
const lines = raw.split('\n');
const result: string[] = [];
let refCounter = 0;
for (const line of lines) {
const maxTextLen = opts.maxTextLength ?? DEFAULT_MAX_TEXT_LENGTH;
const lines = raw.split('\n');
// === Pass 1: Parse, filter, and collect entries ===
const entries: Entry[] = [];
let refCounter = 0;
let skipUntilDepth = -1; // When >= 0, skip all nodes at depth > this value
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!line.trim()) continue;
const indent = line.length - line.trimStart().length;
const depth = Math.floor(indent / 2);
if (opts.maxDepth && depth > opts.maxDepth) continue;
// If we're in a subtree skip zone, check depth
if (skipUntilDepth >= 0) {
if (depth > skipUntilDepth) continue; // still inside subtree
skipUntilDepth = -1; // exited subtree
}
let content = line.trimStart();
// Skip non-interactive elements in interactive mode
if (opts.interactive) {
const interactiveRoles = ['button', 'link', 'textbox', 'checkbox', 'radio', 'combobox', 'tab', 'menuitem', 'option'];
const role = content.split(/[\s[]/)[0]?.toLowerCase() ?? '';
if (!interactiveRoles.some(r => role.includes(r)) && depth > 1) continue;
// Strip leading "- "
if (content.startsWith('- ')) {
content = content.slice(2);
}
// Compact: strip verbose role descriptions
// Skip metadata lines
if (isMetadataLine(content)) continue;
// Apply maxDepth filter
if (opts.maxDepth !== undefined && depth > opts.maxDepth) continue;
const { role, text, hasText, trailingText } = parseLine(content);
// Skip noise nodes
if (isNoiseNode(role, hasText, text, trailingText)) continue;
// Skip subtree noise roles (contentinfo footer, etc.) — skip entire subtree
if (SUBTREE_NOISE_ROLES.has(role)) {
skipUntilDepth = depth;
continue;
}
// Strip annotations
content = stripAnnotations(content);
// Check if node should trigger subtree skip (ads, boilerplate)
const isSubtreeSkip = isAdNode(text, trailingText) || isBoilerplateNode(text);
// Interactive mode filter
const isInteractive = INTERACTIVE_ROLES.has(role);
const isLandmark = LANDMARK_ROLES.has(role);
if (opts.interactive && !isInteractive && !isLandmark && !hasText) continue;
// Compact mode
if (opts.compact) {
content = content
.replace(/\s*\[.*?\]\s*/g, ' ')
@@ -37,15 +270,168 @@ export function formatSnapshot(raw: string, opts: FormatOptions = {}): string {
.trim();
}
// Text truncation
if (maxTextLen > 0 && content.length > maxTextLen) {
content = content.slice(0, maxTextLen) + '…';
}
// Assign refs to interactive elements
const interactivePattern = /^(button|link|textbox|checkbox|radio|combobox|tab|menuitem|option)\b/i;
if (interactivePattern.test(content)) {
if (isInteractive) {
refCounter++;
content = `[@${refCounter}] ${content}`;
}
result.push(' '.repeat(depth) + content);
entries.push({ depth, content, role, text, trailingText, isInteractive, isLandmark, isSubtreeSkip });
}
return result.join('\n');
// === Pass 2: Remove subtree-skip nodes (ads, boilerplate, contentinfo) ===
let noAds: Entry[] = [];
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
if (entry.isSubtreeSkip) {
const skipDepth = entry.depth;
i++;
while (i < entries.length && entries[i].depth > skipDepth) {
i++;
}
i--;
continue;
}
noAds.push(entry);
}
// === Pass 3: Deduplicate child generic/text matching parent label ===
let deduped: Entry[] = [];
for (let i = 0; i < noAds.length; i++) {
const entry = noAds[i];
if (entry.role === 'generic' || entry.role === 'text') {
let parent: Entry | undefined;
for (let j = deduped.length - 1; j >= 0; j--) {
if (deduped[j].depth < entry.depth) {
parent = deduped[j];
break;
}
if (deduped[j].depth === entry.depth) break;
}
if (parent) {
const childText = entry.trailingText || entry.text;
if (childText && parent.text && childText === parent.text) {
continue;
}
}
}
deduped.push(entry);
}
// === Pass 4: Deduplicate heading + child link with identical label ===
// Pattern: heading "Title": → link "Title": (same text) → skip the link
const deduped2: Entry[] = [];
for (let i = 0; i < deduped.length; i++) {
const entry = deduped[i];
if (entry.role === 'heading' && entry.text) {
const next = deduped[i + 1];
if (next && next.role === 'link' && next.text === entry.text && next.depth === entry.depth + 1) {
// Keep the heading, skip the link. But preserve link's children re-parented.
deduped2.push(entry);
i++; // skip the link
continue;
}
}
deduped2.push(entry);
}
// === Pass 5: Deduplicate nested identical links ===
const deduped3: Entry[] = [];
for (let i = 0; i < deduped2.length; i++) {
const entry = deduped2[i];
if (entry.role === 'link' && entry.text) {
const next = deduped2[i + 1];
if (next && next.role === 'link' && next.text === entry.text && next.depth === entry.depth + 1) {
continue; // Skip parent, keep child
}
}
deduped3.push(entry);
}
// === Pass 6: Iteratively prune empty containers (bottom-up) ===
let current = deduped3;
let changed = true;
while (changed) {
changed = false;
const next: Entry[] = [];
for (let i = 0; i < current.length; i++) {
const entry = current[i];
if (CONTAINER_ROLES.has(entry.role) && !entry.text && !entry.trailingText) {
let hasChildren = false;
for (let j = i + 1; j < current.length; j++) {
if (current[j].depth <= entry.depth) break;
if (current[j].depth > entry.depth) {
hasChildren = true;
break;
}
}
if (!hasChildren) {
changed = true;
continue;
}
}
next.push(entry);
}
current = next;
}
// === Pass 7: Collapse single-child containers ===
const collapsed: Entry[] = [];
for (let i = 0; i < current.length; i++) {
const entry = current[i];
if (CONTAINER_ROLES.has(entry.role) && !entry.text && !entry.trailingText) {
let childCount = 0;
let childIdx = -1;
for (let j = i + 1; j < current.length; j++) {
if (current[j].depth <= entry.depth) break;
if (current[j].depth === entry.depth + 1) {
childCount++;
if (childCount === 1) childIdx = j;
}
}
if (childCount === 1 && childIdx !== -1) {
const child = current[childIdx];
let hasGrandchildren = false;
for (let j = childIdx + 1; j < current.length; j++) {
if (current[j].depth <= child.depth) break;
if (current[j].depth > child.depth) {
hasGrandchildren = true;
break;
}
}
if (!hasGrandchildren) {
const mergedContent = entry.content.replace(/:$/, '') + ' > ' + child.content;
collapsed.push({
...entry,
content: mergedContent,
role: child.role,
text: child.text,
trailingText: child.trailingText,
isInteractive: child.isInteractive,
});
i++;
continue;
}
}
}
collapsed.push(entry);
}
return collapsed.map(e => ' '.repeat(e.depth) + e.content).join('\n');
}

Some files were not shown because too many files have changed in this diff Show More