publishport-opencli 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +61 -61
- package/README.zh-CN.md +68 -68
- package/cli-manifest.json +502 -59
- package/clis/1688/shared.js +2 -2
- package/clis/36kr/news.js +1 -1
- package/clis/_atlassian/shared.js +1 -1
- package/clis/_shared/article/auth.js +1 -1
- package/clis/_shared/article/publish.js +1 -1
- package/clis/_shared/content-guard.js +1 -1
- package/clis/_shared/self-hosted-sites.js +2 -0
- package/clis/_shared/site-auth.js +1 -1
- package/clis/_shared/token-auth.js +2 -2
- package/clis/_shared/video-publish.js +1 -1
- package/clis/aibase/news.js +1 -1
- package/clis/amazon/shared.js +2 -2
- package/clis/antigravity/SKILL.md +12 -12
- package/clis/antigravity/storage.js +1 -1
- package/clis/apple-podcasts/episodes.js +1 -1
- package/clis/archive/item.js +1 -1
- package/clis/archive/search.js +1 -1
- package/clis/archive/snapshots.js +1 -1
- package/clis/archive/wayback.js +1 -1
- package/clis/arxiv/author.js +1 -1
- package/clis/baijiahao/publish.js +1 -1
- package/clis/bbc/utils.js +1 -1
- package/clis/bloomberg/businessweek.js +1 -1
- package/clis/bloomberg/utils.js +1 -1
- package/clis/booking/search.js +1 -1
- package/clis/boss/utils.js +1 -1
- package/clis/chatgpt/ask.js +1 -1
- package/clis/chatgpt/detail.js +1 -1
- package/clis/chatgpt/history.js +1 -1
- package/clis/chatgpt/project-file-add.js +1 -1
- package/clis/chatgpt/project-list.js +1 -1
- package/clis/chatgpt/utils.js +2 -2
- package/clis/chess/utils.js +1 -1
- package/clis/claude/ask.js +1 -1
- package/clis/claude/history.js +1 -1
- package/clis/claude/utils.js +1 -1
- package/clis/codex/extract-diff.js +1 -1
- package/clis/coingecko/coin.js +1 -1
- package/clis/crates/utils.js +1 -1
- package/clis/csdn/stats.js +1 -1
- package/clis/dblp/utils.js +1 -1
- package/clis/defillama/utils.js +1 -1
- package/clis/devto/publish.js +1 -1
- package/clis/discord-app/utils.js +1 -1
- package/clis/dockerhub/utils.js +1 -1
- package/clis/douban/utils.js +1 -1
- package/clis/douyin/_shared/tos-upload.js +1 -1
- package/clis/douyin/hashtag.js +1 -1
- package/clis/douyin/publish-image.js +1 -1
- package/clis/douyin/publish.js +1 -1
- package/clis/eastmoney/announcement.js +1 -1
- package/clis/eastmoney/rank.js +1 -1
- package/clis/eastmoney/sectors.js +1 -1
- package/clis/endoflife/utils.js +1 -1
- package/clis/flathub/utils.js +1 -1
- package/clis/gemini/detail.js +1 -1
- package/clis/gemini/read.js +1 -1
- package/clis/geogebra/add-circle.js +1 -1
- package/clis/geogebra/add-line.js +1 -1
- package/clis/geogebra/add-point.js +1 -1
- package/clis/geogebra/add-polygon.js +1 -1
- package/clis/geogebra/eval.js +1 -1
- package/clis/geogebra/hexagon.js +1 -1
- package/clis/geogebra/info.js +1 -1
- package/clis/geogebra/triangle.js +1 -1
- package/clis/ghost/login.js +1 -0
- package/clis/ghost/publish.js +1 -1
- package/clis/ghost/shared.js +24 -1
- package/clis/ghost/sites.js +1 -0
- package/clis/ghost/whoami.js +1 -1
- package/clis/gitee/user.js +2 -2
- package/clis/github-trending/repos.js +1 -1
- package/clis/goproxy/utils.js +1 -1
- package/clis/grok/export-all.js +1 -1
- package/clis/grok/export.js +1 -1
- package/clis/hashnode/publish.js +1 -1
- package/clis/hf/datasets.js +1 -1
- package/clis/hf/models.js +1 -1
- package/clis/hf/paper.js +1 -1
- package/clis/hf/spaces.js +1 -1
- package/clis/homebrew/utils.js +1 -1
- package/clis/instagram/note.js +1 -1
- package/clis/jimeng/generate.js +1 -1
- package/clis/juejin/utils.js +1 -1
- package/clis/kuaishou/publish.js +1 -1
- package/clis/lesswrong/tag.js +1 -1
- package/clis/lichess/utils.js +1 -1
- package/clis/linkedin/search.js +2 -2
- package/clis/linux-do/feed.js +2 -2
- package/clis/lobsters/domain.js +1 -1
- package/clis/mastodon/login.js +1 -0
- package/clis/mastodon/post.js +1 -1
- package/clis/mastodon/shared.js +10 -10
- package/clis/mastodon/sites.js +1 -0
- package/clis/mastodon/whoami.js +1 -1
- package/clis/maven/utils.js +1 -1
- package/clis/mdn/search.js +1 -1
- package/clis/medium/tag.js +1 -1
- package/clis/notebooklm/current.js +1 -1
- package/clis/notebooklm/get.js +1 -1
- package/clis/notebooklm/history.js +1 -1
- package/clis/notebooklm/note-list.js +1 -1
- package/clis/notebooklm/notes-get.js +1 -1
- package/clis/notebooklm/open.js +1 -1
- package/clis/notebooklm/source-fulltext.js +1 -1
- package/clis/notebooklm/source-get.js +1 -1
- package/clis/notebooklm/source-guide.js +1 -1
- package/clis/notebooklm/source-list.js +1 -1
- package/clis/notebooklm/summary.js +1 -1
- package/clis/notebooklm/utils.js +1 -1
- package/clis/npm/utils.js +1 -1
- package/clis/nuget/utils.js +1 -1
- package/clis/nvd/cve.js +1 -1
- package/clis/oeis/utils.js +1 -1
- package/clis/ones/common.js +2 -2
- package/clis/ones/me.js +1 -1
- package/clis/ones/tasks.js +1 -1
- package/clis/ones/token-info.js +1 -1
- package/clis/ones/worklog.js +1 -1
- package/clis/openalex/utils.js +1 -1
- package/clis/oschina/stats.js +1 -1
- package/clis/osv/utils.js +1 -1
- package/clis/packagist/utils.js +1 -1
- package/clis/pixiv/detail.js +1 -1
- package/clis/pixiv/user.js +1 -1
- package/clis/producthunt/utils.js +1 -1
- package/clis/pypi/utils.js +1 -1
- package/clis/qiita/gql.js +2 -2
- package/clis/rest-countries/utils.js +1 -1
- package/clis/rfc/utils.js +1 -1
- package/clis/rubygems/utils.js +1 -1
- package/clis/semanticscholar/utils.js +1 -1
- package/clis/slock/errors.js +1 -1
- package/clis/spotify/spotify.js +1 -1
- package/clis/spotify/utils.js +1 -1
- package/clis/stackoverflow/utils.js +1 -1
- package/clis/steam/utils.js +1 -1
- package/clis/substack/auth.js +2 -2
- package/clis/suno/generate.js +2 -2
- package/clis/suno/list.js +3 -3
- package/clis/telegram/send.js +1 -1
- package/clis/tiktok/creator-videos.js +1 -1
- package/clis/tiktok/publish.js +1 -1
- package/clis/tiktok/utils.js +1 -1
- package/clis/trae-cn/activity.js +1 -1
- package/clis/trae-cn/approve.js +1 -1
- package/clis/trae-cn/ask.js +1 -1
- package/clis/trae-cn/dump.js +1 -1
- package/clis/trae-cn/export.js +1 -1
- package/clis/trae-cn/model.js +1 -1
- package/clis/trae-cn/new.js +1 -1
- package/clis/trae-cn/read.js +1 -1
- package/clis/trae-cn/screenshot.js +1 -1
- package/clis/trae-cn/select-model.js +1 -1
- package/clis/trae-cn/send.js +1 -1
- package/clis/trae-cn/setup.js +1 -1
- package/clis/trae-cn/status.js +1 -1
- package/clis/trae-cn/targets.js +1 -1
- package/clis/trae-cn/watch.js +1 -1
- package/clis/trae-solo/state-fs.js +1 -1
- package/clis/tumblr/publish.js +1 -1
- package/clis/tvmaze/utils.js +1 -1
- package/clis/twitter/bookmark-folder.js +1 -1
- package/clis/twitter/download.js +1 -1
- package/clis/twitter/followers.js +2 -2
- package/clis/twitter/following.js +2 -2
- package/clis/twitter/likes.js +1 -1
- package/clis/twitter/list-add-batch.js +1 -1
- package/clis/twitter/list-add-core.js +1 -1
- package/clis/twitter/list-add.js +1 -1
- package/clis/twitter/list-create.js +1 -1
- package/clis/twitter/list-delete.js +3 -3
- package/clis/twitter/list-remove-batch.js +1 -1
- package/clis/twitter/list-remove.js +1 -1
- package/clis/twitter/list-tweets.js +1 -1
- package/clis/twitter/profile.js +1 -1
- package/clis/twitter/search.js +1 -1
- package/clis/twitter/shared.js +1 -1
- package/clis/twitter/tweets.js +1 -1
- package/clis/uisdc/news.js +1 -1
- package/clis/v2ex/daily.js +2 -2
- package/clis/v2ex/me.js +2 -2
- package/clis/v2ex/notifications.js +1 -1
- package/clis/wikidata/utils.js +1 -1
- package/clis/wikipedia/page.js +2 -2
- package/clis/wikipedia/summary.js +1 -1
- package/clis/wikipedia/utils.js +1 -1
- package/clis/wordpress/login.js +1 -1
- package/clis/wordpress/publish.js +1 -1
- package/clis/wordpress/shared.js +3 -3
- package/clis/wordpress/sites.js +1 -0
- package/clis/wordpress/whoami.js +1 -1
- package/clis/woshipm/stats.js +1 -1
- package/clis/xiaoe/content.js +1 -1
- package/clis/xiaohongshu/draft-delete.js +1 -1
- package/clis/xiaohongshu/draft-open.js +1 -1
- package/clis/xiaohongshu/draft-utils.js +2 -2
- package/clis/xiaohongshu/publish-video.js +1 -1
- package/clis/xiaohongshu/publish.js +1 -1
- package/clis/xiaoyuzhou/auth.js +1 -1
- package/clis/xiaoyuzhou/transcript.js +1 -1
- package/clis/yollomi/background.js +1 -1
- package/clis/yollomi/edit.js +1 -1
- package/clis/yollomi/generate.js +1 -1
- package/clis/yollomi/try-on.js +1 -1
- package/clis/youtube/publish.js +1 -1
- package/clis/zhihu/answer-comments.js +1 -1
- package/clis/zhihu/answer-detail.js +1 -1
- package/clis/zhihu/collection.js +2 -2
- package/clis/zhihu/collections.js +1 -1
- package/clis/zhihu/question.js +1 -1
- package/clis/zhihu/search.js +1 -1
- package/clis/zhihu/target.js +1 -1
- package/clis/zhihu/user-arg.js +1 -1
- package/dist/src/adapter-shadow.js +1 -1
- package/dist/src/browser/analyze.js +1 -1
- package/dist/src/browser/article-extract.d.ts +1 -1
- package/dist/src/browser/base-page.js +3 -3
- package/dist/src/browser/cdp.js +1 -1
- package/dist/src/browser/daemon-client.d.ts +1 -1
- package/dist/src/browser/daemon-lifecycle.js +6 -6
- package/dist/src/browser/daemon-version.js +1 -1
- package/dist/src/browser/dom-snapshot.d.ts +1 -1
- package/dist/src/browser/dom-snapshot.js +2 -2
- package/dist/src/browser/errors.js +2 -2
- package/dist/src/browser/network-cache.js +1 -1
- package/dist/src/browser/profile.js +1 -1
- package/dist/src/browser/target-resolver.js +4 -4
- package/dist/src/browser/verify-fixture.js +1 -1
- package/dist/src/browser-session-lock.js +1 -1
- package/dist/src/build-manifest.d.ts +1 -1
- package/dist/src/build-manifest.js +1 -1
- package/dist/src/cli-argv-preprocess.d.ts +4 -4
- package/dist/src/cli-argv-preprocess.js +1 -1
- package/dist/src/cli.d.ts +1 -1
- package/dist/src/cli.js +19 -19
- package/dist/src/commanderAdapter.js +1 -1
- package/dist/src/commands/auth.js +2 -2
- package/dist/src/commands/daemon.d.ts +4 -4
- package/dist/src/commands/daemon.js +1 -1
- package/dist/src/completion-shared.js +12 -12
- package/dist/src/completion.d.ts +2 -2
- package/dist/src/constants.d.ts +1 -1
- package/dist/src/constants.js +1 -1
- package/dist/src/daemon-utils.d.ts +1 -1
- package/dist/src/daemon-utils.js +1 -1
- package/dist/src/daemon.d.ts +2 -2
- package/dist/src/daemon.js +1 -1
- package/dist/src/discovery.d.ts +7 -7
- package/dist/src/discovery.js +2 -2
- package/dist/src/doctor.d.ts +1 -1
- package/dist/src/doctor.js +6 -6
- package/dist/src/electron-apps.d.ts +1 -1
- package/dist/src/electron-apps.js +1 -1
- package/dist/src/errors.d.ts +2 -2
- package/dist/src/errors.js +1 -1
- package/dist/src/execution.js +1 -1
- package/dist/src/external.d.ts +1 -1
- package/dist/src/external.js +1 -1
- package/dist/src/help.d.ts +1 -1
- package/dist/src/help.js +3 -3
- package/dist/src/hooks.d.ts +1 -1
- package/dist/src/launcher.js +2 -2
- package/dist/src/logger.d.ts +1 -1
- package/dist/src/main.d.ts +1 -1
- package/dist/src/main.js +1 -1
- package/dist/src/observation/artifact.js +2 -2
- package/dist/src/package-paths.js +1 -1
- package/dist/src/package-paths.test.d.ts +1 -0
- package/dist/src/plugin-manifest.d.ts +12 -3
- package/dist/src/plugin-manifest.js +1 -1
- package/dist/src/plugin-scaffold.d.ts +2 -2
- package/dist/src/plugin-scaffold.js +9 -9
- package/dist/src/plugin.d.ts +4 -4
- package/dist/src/plugin.js +10 -10
- package/dist/src/rate-limit.js +1 -1
- package/dist/src/registry-api.d.ts +1 -1
- package/dist/src/runtime-detect.d.ts +1 -1
- package/dist/src/serialization.js +1 -1
- package/dist/src/skills.js +6 -6
- package/dist/src/user-runtime.d.ts +8 -0
- package/dist/src/user-runtime.js +1 -0
- package/dist/src/user-runtime.test.d.ts +1 -0
- package/dist/src/validate.js +1 -1
- package/dist/src/validate.test.d.ts +1 -1
- package/docs/guide/browser-bridge.md +23 -23
- package/docs/guide/electron-app-cli.md +3 -3
- package/docs/guide/exit-codes.md +3 -3
- package/docs/guide/extending-opencli.md +37 -37
- package/docs/guide/getting-started.md +19 -19
- package/docs/guide/installation.md +6 -6
- package/docs/guide/plugins.md +32 -32
- package/docs/guide/remote-orchestration.md +5 -5
- package/docs/guide/troubleshooting.md +9 -9
- package/package.json +3 -2
- package/scripts/fetch-adapters.js +6 -6
- package/scripts/postinstall.js +14 -14
- package/skills/opencli-adapter-author/SKILL.md +24 -24
- package/skills/opencli-adapter-author/references/adapter-template.md +13 -13
- package/skills/opencli-adapter-author/references/api-discovery.md +25 -25
- package/skills/opencli-adapter-author/references/coverage-matrix.md +3 -3
- package/skills/opencli-adapter-author/references/field-decode-playbook.md +10 -10
- package/skills/opencli-adapter-author/references/jsdom-fixture-pattern.md +2 -2
- package/skills/opencli-adapter-author/references/site-memory.md +11 -11
- package/skills/opencli-adapter-author/references/site-recon.md +7 -7
- package/skills/opencli-adapter-author/references/strategy-selection.md +3 -3
- package/skills/opencli-adapter-author/references/success-rate-pitfalls.md +4 -4
- package/skills/opencli-adapter-author/references/typed-errors.md +2 -2
- package/skills/opencli-autofix/SKILL.md +29 -29
- package/skills/opencli-browser/SKILL.md +55 -55
- package/skills/opencli-browser-sitemap/SKILL.md +7 -7
- package/skills/opencli-sitemap-author/SKILL.md +11 -11
- package/skills/opencli-sitemap-author/references/sitemap-schema.md +19 -19
- package/skills/opencli-usage/SKILL.md +43 -43
package/dist/src/cli.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
import*as I from"node:fs";import*as zq from"node:os";import*as M from"node:path";import{fileURLToPath as sK}from"node:url";import{Command as _q,InvalidArgumentError as WK,Option as tK}from"commander";import eK from"js-yaml";import{findPackageRoot,getBuiltEntryCandidates as qQ}from"./package-paths.js";import{fullName as Cq,getRegistry as Dq,strategyLabel as JK}from"./registry.js";import{serializeCommand as KQ,formatArgSummary as QQ}from"./serialization.js";import{render as Aq}from"./output.js";import{PKG_VERSION as Fq}from"./version.js";import{printCompletionScript as XQ}from"./completion.js";import{loadExternalClis as Tq,executeExternalCli as YQ,installExternalCli as ZQ,registerExternalCli as $Q,isBinaryInstalled as wq,formatExternalCliLabel as VK}from"./external.js";import{listOpenCliSkills as HQ,readOpenCliSkill as zQ}from"./skills.js";import{registerAllCommands as NQ}from"./commanderAdapter.js";import{classifyAdapter as jK,formatRootAdapterHelpText as UQ,installCommanderNamespaceStructuredHelp as Nq,installStructuredHelp as GQ,leadingPositionalFromUsage as WQ,rootHelpData as JQ}from"./help.js";import{EXIT_CODES as J,getErrorMessage as h,BrowserConnectError as VQ,CliError as hq,toEnvelope as jQ}from"./errors.js";import{TargetError as LK}from"./browser/target-errors.js";import{resolveTargetJs as LQ,getTextResolvedJs as _Q,getValueResolvedJs as DQ,getAttributesResolvedJs as AQ,selectResolvedJs as BQ,isAutocompleteResolvedJs as FQ}from"./browser/target-resolver.js";import{buildFindJs as RQ,buildSemanticFindJs as _K,isFindError as DK}from"./browser/find.js";import{inferShape as AK}from"./browser/shape.js";import{assignKeys as BK}from"./browser/network-key.js";import{DEFAULT_TTL_MS as FK,findEntry as EQ,loadNetworkCache as PQ,saveNetworkCache as OQ}from"./browser/network-cache.js";import{parseFilter as kQ,shapeMatchesFilter as IQ}from"./browser/shape-filter.js";import{buildHtmlTreeJs as MQ}from"./browser/html-tree.js";import{buildExtractHtmlJs as SQ,runExtractFromHtml as bQ}from"./browser/extract.js";import{analyzeSite as CQ}from"./browser/analyze.js";import{registerAuthCommands as TQ}from"./commands/auth.js";import{daemonRestart as wQ,daemonStatus as hQ,daemonStop as yQ,daemonWarm as vQ}from"./commands/daemon.js";import{log as n}from"./logger.js";import{bindTab as fQ,BrowserCommandError as Bq,fetchDaemonStatus as xQ,sendCommand as uQ}from"./browser/daemon-client.js";import{aliasForContextId as RK,listManagedProfiles as yq,loadProfileConfig as cQ,renameProfile as mQ,resolveProfileContextId as dQ,setDefaultProfile as gQ}from"./browser/profile.js";import{createManagedProfile as nQ,ensureManagedChrome as vq,isManagedChromeRunning as lQ,removeManagedProfile as iQ,stopManagedChrome as oQ,resolveManagedOpts as EK,updateManagedProfileConfig as pQ}from"./browser/managed-chrome.js";import{testProxy as aQ,parseProxyUrl as fq}from"./browser/proxy-test.js";import{formatDaemonVersion as rQ,isDaemonStale as sQ}from"./browser/daemon-version.js";import{DEFAULT_BROWSER_CONNECT_TIMEOUT as xq}from"./browser/config.js";const uq=sK(import.meta.url),tQ='Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"',PK=1000;function Rq(N,H){if(N===void 0||N===null||N==="")return null;const $=String(N).trim(),V=/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec($);if(!V)return{error:`--${H} must be a duration like 500ms, 30s, 2m, got "${$}"`};const B=Number.parseFloat(V[1]),j=V[2]??"ms";return Math.round(B*(j==="h"?3600000:j==="m"?60000:j==="s"?1000:1))}function cq(N){return typeof N==="number"&&Number.isFinite(N)&&N>0?N:Date.now()}function Uq(N){if(typeof N!=="number"||!Number.isFinite(N)||N<=0)return;return new Date(N).toISOString()}function mq(N,H,$=Date.now()){const V=H.sinceMs!=null?$-H.sinceMs:void 0,B=H.untilMs!=null?$-H.untilMs:void 0;return N.filter((j)=>{const S=j.timestamp??$;if(V!==void 0&&S<V)return!1;if(B!==void 0&&S>B)return!1;return!0})}export function selectFreshByTimestamp(N,H){const $=N.filter((B)=>Number(B.timestamp??0)>H),V=$.length>0?Math.max(H,...$.map((B)=>Number(B.timestamp??0)).filter(Number.isFinite)):H;return{fresh:$,lastSeenTs:V}}async function Gq(N){if(N.readNetworkCapture){const $=await N.readNetworkCapture();if(Array.isArray($)&&$.length>0)return $.map((V)=>{const B=V.responsePreview??null;let j=null;if(B)try{j=JSON.parse(B)}catch{j=B}const S=typeof V.responseBodyFullSize==="number"?V.responseBodyFullSize:B?B.length:0,F=V.responseBodyTruncated===!0;return{url:V.url||"",method:V.method||"GET",status:V.responseStatus||0,size:S,ct:V.responseContentType||"",body:j,bodyFullSize:S,bodyTruncated:F,timestamp:cq(V.timestamp)}})}const H=await N.evaluate("(function(){ var out = window.__opencli_net || []; window.__opencli_net = []; return JSON.stringify(out); })()");try{return JSON.parse(H).map((V)=>({...V,timestamp:cq(V.timestamp)}))}catch{if(process.env.OPENCLI_VERBOSE)n.warn(`[network] Failed to parse interceptor buffer: ${typeof H==="string"?H.slice(0,200):String(H)}`);return[]}}function OK(N){return N.filter((H)=>{const $=H.ct?.toLowerCase()??"";return($.includes("json")||$.includes("xml")||$.includes("text/plain")||$.includes("javascript"))&&!/\.(js|css|png|jpg|gif|svg|woff|ico|map)(\?|$)/i.test(H.url)&&!/analytics|tracking|telemetry|beacon|pixel|gtag|fbevents/i.test(H.url)})}const eQ={invalid_args:J.USAGE_ERROR,invalid_filter:J.USAGE_ERROR,invalid_max_body:J.USAGE_ERROR};function i(N,H,$={}){console.log(JSON.stringify({error:{code:N,message:H,...$}},null,2));process.exitCode=eQ[N]??J.GENERIC_ERROR}const qX="Site sitemap available. For navigation context, use the opencli-browser-sitemap skill; treat browser state as truth if it disagrees.";function KX(N,H=Dq()){let $;try{$=new URL(N).hostname.toLowerCase().replace(/^www\./,"")}catch{return[]}const V=new Map;for(const F of H.values()){if(!F.domain)continue;let P=F.domain.toLowerCase().trim();try{P=new URL(P.includes("://")?P:`https://${P}`).hostname.toLowerCase()}catch{P=P.split("/")[0]??P}P=P.replace(/^www\./,"");if(!P)continue;if($===P||$.endsWith(`.${P}`))V.set(F.site,Math.max(V.get(F.site)??0,P.length))}const B=[...V.entries()].sort((F,P)=>P[1]-F[1]||F[0].localeCompare(P[0])).map(([F])=>F),j=$.split(".").filter(Boolean),S=j.length>=2?j[j.length-2]:j[0];return[...new Set([...B,...S?[S]:[]])]}function kK(N,H){return N.find(($)=>H($))}function QX(N,H){const $=N.replace(/[^a-zA-Z0-9_-]+/g,"-");if(!$)return{};const V=M.join(H.homeDir,".
|
|
2
|
-
`)}function SK(){return process.env.OPENCLI_CACHE_DIR||M.join(zq.homedir(),".
|
|
1
|
+
import*as I from"node:fs";import*as zq from"node:os";import*as M from"node:path";import{fileURLToPath as sK}from"node:url";import{Command as _q,InvalidArgumentError as WK,Option as tK}from"commander";import eK from"js-yaml";import{findPackageRoot,getBuiltEntryCandidates as qQ}from"./package-paths.js";import{fullName as Cq,getRegistry as Dq,strategyLabel as JK}from"./registry.js";import{serializeCommand as KQ,formatArgSummary as QQ}from"./serialization.js";import{render as Aq}from"./output.js";import{PKG_VERSION as Fq}from"./version.js";import{printCompletionScript as XQ}from"./completion.js";import{loadExternalClis as Tq,executeExternalCli as YQ,installExternalCli as ZQ,registerExternalCli as $Q,isBinaryInstalled as wq,formatExternalCliLabel as VK}from"./external.js";import{listOpenCliSkills as HQ,readOpenCliSkill as zQ}from"./skills.js";import{registerAllCommands as NQ}from"./commanderAdapter.js";import{classifyAdapter as jK,formatRootAdapterHelpText as UQ,installCommanderNamespaceStructuredHelp as Nq,installStructuredHelp as GQ,leadingPositionalFromUsage as WQ,rootHelpData as JQ}from"./help.js";import{EXIT_CODES as J,getErrorMessage as h,BrowserConnectError as VQ,CliError as hq,toEnvelope as jQ}from"./errors.js";import{TargetError as LK}from"./browser/target-errors.js";import{resolveTargetJs as LQ,getTextResolvedJs as _Q,getValueResolvedJs as DQ,getAttributesResolvedJs as AQ,selectResolvedJs as BQ,isAutocompleteResolvedJs as FQ}from"./browser/target-resolver.js";import{buildFindJs as RQ,buildSemanticFindJs as _K,isFindError as DK}from"./browser/find.js";import{inferShape as AK}from"./browser/shape.js";import{assignKeys as BK}from"./browser/network-key.js";import{DEFAULT_TTL_MS as FK,findEntry as EQ,loadNetworkCache as PQ,saveNetworkCache as OQ}from"./browser/network-cache.js";import{parseFilter as kQ,shapeMatchesFilter as IQ}from"./browser/shape-filter.js";import{buildHtmlTreeJs as MQ}from"./browser/html-tree.js";import{buildExtractHtmlJs as SQ,runExtractFromHtml as bQ}from"./browser/extract.js";import{analyzeSite as CQ}from"./browser/analyze.js";import{registerAuthCommands as TQ}from"./commands/auth.js";import{daemonRestart as wQ,daemonStatus as hQ,daemonStop as yQ,daemonWarm as vQ}from"./commands/daemon.js";import{log as n}from"./logger.js";import{bindTab as fQ,BrowserCommandError as Bq,fetchDaemonStatus as xQ,sendCommand as uQ}from"./browser/daemon-client.js";import{aliasForContextId as RK,listManagedProfiles as yq,loadProfileConfig as cQ,renameProfile as mQ,resolveProfileContextId as dQ,setDefaultProfile as gQ}from"./browser/profile.js";import{createManagedProfile as nQ,ensureManagedChrome as vq,isManagedChromeRunning as lQ,removeManagedProfile as iQ,stopManagedChrome as oQ,resolveManagedOpts as EK,updateManagedProfileConfig as pQ}from"./browser/managed-chrome.js";import{testProxy as aQ,parseProxyUrl as fq}from"./browser/proxy-test.js";import{formatDaemonVersion as rQ,isDaemonStale as sQ}from"./browser/daemon-version.js";import{DEFAULT_BROWSER_CONNECT_TIMEOUT as xq}from"./browser/config.js";const uq=sK(import.meta.url),tQ='Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"',PK=1000;function Rq(N,H){if(N===void 0||N===null||N==="")return null;const $=String(N).trim(),V=/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/.exec($);if(!V)return{error:`--${H} must be a duration like 500ms, 30s, 2m, got "${$}"`};const B=Number.parseFloat(V[1]),j=V[2]??"ms";return Math.round(B*(j==="h"?3600000:j==="m"?60000:j==="s"?1000:1))}function cq(N){return typeof N==="number"&&Number.isFinite(N)&&N>0?N:Date.now()}function Uq(N){if(typeof N!=="number"||!Number.isFinite(N)||N<=0)return;return new Date(N).toISOString()}function mq(N,H,$=Date.now()){const V=H.sinceMs!=null?$-H.sinceMs:void 0,B=H.untilMs!=null?$-H.untilMs:void 0;return N.filter((j)=>{const S=j.timestamp??$;if(V!==void 0&&S<V)return!1;if(B!==void 0&&S>B)return!1;return!0})}export function selectFreshByTimestamp(N,H){const $=N.filter((B)=>Number(B.timestamp??0)>H),V=$.length>0?Math.max(H,...$.map((B)=>Number(B.timestamp??0)).filter(Number.isFinite)):H;return{fresh:$,lastSeenTs:V}}async function Gq(N){if(N.readNetworkCapture){const $=await N.readNetworkCapture();if(Array.isArray($)&&$.length>0)return $.map((V)=>{const B=V.responsePreview??null;let j=null;if(B)try{j=JSON.parse(B)}catch{j=B}const S=typeof V.responseBodyFullSize==="number"?V.responseBodyFullSize:B?B.length:0,F=V.responseBodyTruncated===!0;return{url:V.url||"",method:V.method||"GET",status:V.responseStatus||0,size:S,ct:V.responseContentType||"",body:j,bodyFullSize:S,bodyTruncated:F,timestamp:cq(V.timestamp)}})}const H=await N.evaluate("(function(){ var out = window.__opencli_net || []; window.__opencli_net = []; return JSON.stringify(out); })()");try{return JSON.parse(H).map((V)=>({...V,timestamp:cq(V.timestamp)}))}catch{if(process.env.OPENCLI_VERBOSE)n.warn(`[network] Failed to parse interceptor buffer: ${typeof H==="string"?H.slice(0,200):String(H)}`);return[]}}function OK(N){return N.filter((H)=>{const $=H.ct?.toLowerCase()??"";return($.includes("json")||$.includes("xml")||$.includes("text/plain")||$.includes("javascript"))&&!/\.(js|css|png|jpg|gif|svg|woff|ico|map)(\?|$)/i.test(H.url)&&!/analytics|tracking|telemetry|beacon|pixel|gtag|fbevents/i.test(H.url)})}const eQ={invalid_args:J.USAGE_ERROR,invalid_filter:J.USAGE_ERROR,invalid_max_body:J.USAGE_ERROR};function i(N,H,$={}){console.log(JSON.stringify({error:{code:N,message:H,...$}},null,2));process.exitCode=eQ[N]??J.GENERIC_ERROR}const qX="Site sitemap available. For navigation context, use the opencli-browser-sitemap skill; treat browser state as truth if it disagrees.";function KX(N,H=Dq()){let $;try{$=new URL(N).hostname.toLowerCase().replace(/^www\./,"")}catch{return[]}const V=new Map;for(const F of H.values()){if(!F.domain)continue;let P=F.domain.toLowerCase().trim();try{P=new URL(P.includes("://")?P:`https://${P}`).hostname.toLowerCase()}catch{P=P.split("/")[0]??P}P=P.replace(/^www\./,"");if(!P)continue;if($===P||$.endsWith(`.${P}`))V.set(F.site,Math.max(V.get(F.site)??0,P.length))}const B=[...V.entries()].sort((F,P)=>P[1]-F[1]||F[0].localeCompare(P[0])).map(([F])=>F),j=$.split(".").filter(Boolean),S=j.length>=2?j[j.length-2]:j[0];return[...new Set([...B,...S?[S]:[]])]}function kK(N,H){return N.find(($)=>H($))}function QX(N,H){const $=N.replace(/[^a-zA-Z0-9_-]+/g,"-");if(!$)return{};const V=M.join(H.homeDir,".ppcli","sites",$);return{local:kK([M.join(V,"sitemap"),M.join(V,"sitemap.md")],H.fileExists),global:kK([M.join(H.packageRoot,"sitemaps",$),M.join(H.packageRoot,"sitemaps",`${$}.md`)],H.fileExists)}}export function resolveSitemapAvailabilityForUrl(N,H={}){const $=H.homeDir??zq.homedir(),V=H.packageRoot??findPackageRoot(uq),B=H.registry??Dq(),j=H.fileExists??I.existsSync;for(const S of KX(N,B)){const F=QX(S,{homeDir:$,packageRoot:V,fileExists:j});if(!F.local&&!F.global)continue;const P=F.local&&F.global?"local+global":F.local?"local":"global";return{site:S,available:!0,source:P,hint:qX,paths:F}}return null}function IK(N){const H=N.replace(/[^a-zA-Z0-9_-]+/g,"_");return M.join(SK(),"browser-sitemap-hints",`${H}.json`)}function MK(N){try{const H=JSON.parse(I.readFileSync(IK(N),"utf-8"));if(H&&typeof H==="object"&&Array.isArray(H.seenSites))return{seenSites:H.seenSites.filter(($)=>typeof $==="string"),updatedAt:typeof H.updatedAt==="string"?H.updatedAt:new Date(0).toISOString()}}catch{}return{seenSites:[],updatedAt:new Date(0).toISOString()}}function XX(N,H){const $=MK(N);if(!$.seenSites.includes(H))$.seenSites.push(H);const V=IK(N);I.mkdirSync(M.dirname(V),{recursive:!0});I.writeFileSync(V,JSON.stringify({seenSites:$.seenSites,updatedAt:new Date().toISOString()}),"utf-8")}function YX(N,H,$){const V=resolveSitemapAvailabilityForUrl(N);if(!V)return null;if(!$.oncePerSession)return V;if(MK(H).seenSites.includes(V.site))return null;XX(H,V.site);return V}export function checkSiteMemory(N){const H=M.join(zq.homedir(),".ppcli","sites",N),$=M.join(H,"endpoints.json"),V=M.join(H,"notes.md");let B=0,j=I.existsSync($);if(j)try{const F=JSON.parse(I.readFileSync($,"utf-8"));if(F&&typeof F==="object"&&!Array.isArray(F))B=Object.keys(F).length;else if(Array.isArray(F))B=F.length}catch{j=!1}const S=I.existsSync(V);return{ok:j&&B>0&&S,siteDir:H,endpoints:{present:j,count:B,path:$},notes:{present:S,path:V}}}export function printSiteMemoryReport(N,H){if(N.ok){console.log(` ✓ Memory: endpoints.json (${N.endpoints.count}), notes.md present at ${N.siteDir}`);return}const $=H?"✗":"⚠",V=[];if(!N.endpoints.present)V.push("endpoints.json");else if(N.endpoints.count===0)V.push("endpoints.json (empty)");if(!N.notes.present)V.push("notes.md");console.log(` ${$} Memory: missing ${V.join(", ")} under ${N.siteDir}`);console.log(" Write the endpoint you just verified + a 1-line session note so the next agent starts from minute 0, not minute 95.");if(!H)console.log(" (Re-run with --strict-memory to fail instead of warn.)")}export function normalizeVerifyRows(N){if(Array.isArray(N))return N.map((H)=>H&&typeof H==="object"?H:{value:H});if(N&&typeof N==="object"){const H=N;for(const $ of["rows","items","data","results"])if(Array.isArray(H[$]))return H[$].map((V)=>V&&typeof V==="object"?V:{value:V});return[H]}return[]}export function renderVerifyPreview(N,H={}){const $=H.maxRows??10,V=H.maxCols??6,B=H.cellMax??40;if(N.length===0)return" (no rows)";const j=Array.from(new Set(N.flatMap((D)=>Object.keys(D)))),S=j.slice(0,V),F=N.slice(0,$),P=(D)=>{if(D===null||D===void 0)return"";return(typeof D==="object"?JSON.stringify(D):String(D)).replace(/\s+/g," ").slice(0,B)},Kq=S.map((D)=>Math.max(D.length,...F.map((o)=>P(o[D]).length))),e=(D)=>D.map((o,Xq)=>o.padEnd(Kq[Xq])).join(" "),r=[];r.push(` ${e(S)}`);r.push(` ${Kq.map((D)=>"-".repeat(D)).join(" ")}`);for(const D of F)r.push(` ${e(S.map((o)=>P(D[o])))}`);if(N.length>$)r.push(` ... and ${N.length-$} more row(s)`);if(j.length>V)r.push(` (${j.length-V} more column(s) hidden)`);return r.join(`
|
|
2
|
+
`)}function SK(){return process.env.OPENCLI_CACHE_DIR||M.join(zq.homedir(),".ppcli","cache")}function bK(N){const H=N.replace(/[^a-zA-Z0-9_-]+/g,"_");return M.join(SK(),"browser-state",`${H}.json`)}function CK(N){try{const H=I.readFileSync(bK(N),"utf-8"),$=JSON.parse(H);return $&&typeof $==="object"?$:null}catch{return null}}function Wq(N,H){const $=bK(H);if(!N){I.rmSync($,{force:!0});return}I.mkdirSync(M.dirname($),{recursive:!0});I.writeFileSync($,JSON.stringify({defaultPage:N,updatedAt:new Date().toISOString()}),"utf-8")}function ZX(N,H){return N.some(($)=>{return typeof $==="object"&&$!==null&&"page"in $&&typeof $.page==="string"&&$.page===H})}async function dq(N,H,$){const V=H.trim();if(!V)return;let B;try{B=await N.tabs()}catch(j){if($.source==="saved"){Wq(void 0,$.scope);return}throw Error(`Target tab ${V} could not be validated in the current browser session. The Browser Bridge session may have restarted; re-run "ppcli browser tab list" and choose a current target.`,{cause:j})}if(Array.isArray(B)&&ZX(B,V))return V;if($.source==="saved"){Wq(void 0,$.scope);return}throw Error(`Target tab ${V} is not part of the current browser session. The Browser Bridge session may have restarted; re-run "ppcli browser tab list" and choose a current target.`)}function Eq(N,H){return H?`${H}:${N}`:N}async function $X(N,H){const $=CK(H)?.defaultPage?.trim();if(!$)return;return dq(N,$,{scope:H,source:"saved"})}async function HX(N,H,$,V={}){const{BrowserBridge:B}=await import("./browser/index.js"),j=new B,S=process.env.OPENCLI_BROWSER_IDLE_TIMEOUT,F=S?parseInt(S,10):void 0,P=await j.connect({timeout:xq,session:N,surface:"browser",...$&&{contextId:$},...F&&F>0&&{idleTimeout:F},windowMode:V.windowMode??TK(void 0,"foreground")}),Kq=Eq(N,$),e=H?await dq(P,H,{scope:Kq,source:"explicit"}):await $X(P,Kq);if(e){if(!P.setActivePage)throw Error("This browser session does not support explicit tab targeting");P.setActivePage(e)}return P}function TK(N,H){const $=gq(N,"window");if($!==void 0&&$!==""){if($==="foreground"||$==="background")return $;throw Error(`--window must be one of: foreground, background. Received: "${String($)}"`)}const V=process.env.OPENCLI_WINDOW;if(V!==void 0&&V!==""){if(V==="foreground"||V==="background")return V;throw Error(`OPENCLI_WINDOW must be one of: foreground, background. Received: "${V}"`)}return H}function E(N){return N.option("--tab <targetId>",tQ)}function zX(N){if(!N)return;const H=N.optsWithGlobals?N.optsWithGlobals():N.opts();return typeof H.tab==="string"&&H.tab.trim()?H.tab.trim():void 0}function gq(N,H){let $=N;while($){const V=$.opts();if(Object.prototype.hasOwnProperty.call(V,H)&&V[H]!==void 0)return V[H];$=$.parent}return}function nq(N){const H=gq(N,"session");if(typeof H==="string"&&H.trim())return H.trim();throw Error("<session> is a required positional argument: ppcli browser <session> <command>")}function lq(N){const H=gq(N,"profile");return dQ(typeof H==="string"&&H.trim()?H.trim():void 0)}function iq(N){const H=N.session;if(typeof H==="string"&&H.trim())return H.trim();throw Error("Browser page is missing a session")}function Pq(N){const H=N.contextId;return Eq(iq(N),typeof H==="string"&&H.trim()?H.trim():void 0)}function NX(N){return typeof N==="string"?N:JSON.stringify(N,null,2)}function UX(N,H){const $=NX(N),V=$.match(/^interactive:\s*(\d+)\s*$/m);return{ok:!0,chars:$.length,bytes:Buffer.byteLength($,"utf8"),lines:$?$.split(/\r?\n/).length:0,approx_tokens:Math.ceil($.length/4),refs:($.match(/(^|\n)\s*\[\d+\]/g)??[]).length,frame_sections:($.match(/(^|\n)frame /g)??[]).length,...V?{interactive:Number(V[1])}:{},elapsed_ms:H}}async function wK(N,H){const $=Date.now();try{const V=await N.snapshot({viewportExpand:2000,source:H});return UX(V,Date.now()-$)}catch(V){return{ok:!1,elapsed_ms:Date.now()-$,error:{...V instanceof Error&&"code"in V?{code:String(V.code)}:{},message:V instanceof Error?V.message:String(V)}}}}function hK(N,H){if(typeof N==="string"&&N.trim())return N.trim();const $=H instanceof _q?H.opts().tab:H?.tab;if(typeof $==="string"&&$.trim())return $.trim();return}function yK(N,H,$){if(N===void 0)return $;const V=parseInt(N,10);if(Number.isNaN(V)||V<=0){console.error(`[cli] Invalid ${H}="${N}", using default ${$}`);return $}return V}function vK(N,H){if(!/^\d+$/.test(N))throw new WK(`--${H} must be a positive integer (got "${N}")`);const $=parseInt(N,10);if($<=0)throw new WK(`--${H} must be a positive integer (got "${N}")`);return $}function GX(N){if(N.verbose)process.env.OPENCLI_VERBOSE="1"}function WX(N){return[...new Set(N.commands.map((H)=>H.name()))].sort((H,$)=>H.localeCompare($)).join(", ")}function JX(N){for(const H of N.commands){if(H.commands.length===0)continue;const $=WX(H);if($)H.description($)}}export function createProgram(N,H){const $=new _q;$.name("ppcli").description("Make any website your CLI. Zero setup. AI-powered.").version(Fq).option("--profile <name>","Chrome profile/context alias for Browser Bridge commands").enablePositionalOptions();$.command("list").description("List all available CLI commands").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((q)=>{const K=Dq(),X=[...new Set(K.values())].sort((W,_)=>Cq(W).localeCompare(Cq(_))),Q=q.format,Y=Q==="json"||Q==="yaml";if(Q!=="table"){const W=Y?X.map(KQ):X.map((_)=>({command:Cq(_),site:_.site,name:_.name,aliases:_.aliases?.join(", ")??"",description:_.description,access:_.access,strategy:JK(_),browser:!!_.browser,args:QQ(_.args)}));Aq(W,{fmt:Q,columns:["command","site","name","aliases","description","access","strategy","browser","args",...Y?["columns","domain"]:[]],title:"ppcli/list",source:"ppcli list"});return}const Z=new Map,z=new Map;for(const W of X){const _=jK(W.domain)==="app"?Z:z,R=_.get(W.site)??[];R.push(W);_.set(W.site,R)}const U=(W,_)=>{console.log(` ${W}`);for(const R of _){const k=JK(R),f=k==="public"?"[public]":`[${k}]`,y=R.aliases?.length?` (aliases: ${R.aliases.join(", ")})`:"";console.log(` ${R.name} ${f}${y}${R.description?` — ${R.description}`:""}`)}console.log()};console.log();console.log(" ppcli"+" — available commands");console.log();if(Z.size>0){console.log(" App adapters");console.log();for(const[W,_]of Z)U(W,_)}if(z.size>0){console.log(" Site adapters");console.log();for(const[W,_]of z)U(W,_)}const G=Tq();if(G.length>0){console.log(" external CLIs");for(const W of G){const R=wq(W.binary)?"[installed]":"[auto-install]";console.log(` ${VK(W)} ${R}${W.description?` — ${W.description}`:""}`)}console.log()}console.log(` ${X.length} built-in commands across ${Z.size} apps + ${z.size} sites, ${G.length} external CLIs`);console.log()});$.command("validate").description("Validate CLI definitions").argument("[target]","site or site/name").action(async(q)=>{const{validateClisWithTarget:K,renderValidationReport:X}=await import("./validate.js");console.log(X(K([N,H],q)))});$.command("verify").description("Validate + smoke test").argument("[target]").option("--smoke","Run smoke tests",!1).action(async(q,K)=>{const{verifyClis:X,renderVerifyReport:Q}=await import("./verify.js"),Y=await X({builtinClis:N,userClis:H,target:q,smoke:K.smoke});console.log(Q(Y));process.exitCode=Y.ok?J.SUCCESS:J.GENERIC_ERROR});const V=$.command("skills").description("Read bundled ppcli skills");V.command("list").description("List bundled ppcli-* skills").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((q)=>{const K=HQ();Aq(K,{fmt:q.format,fmtExplicit:!!q.format,columns:["name","description","version","path"],title:"ppcli/skills/list",source:"ppcli skills list"})});V.command("read").description("Print an ppcli-* skill's SKILL.md or reference file").argument("<skill>","Skill name, or skill/path like opencli-browser/references/foo.md").argument("[path]","Path under the skill directory").option("--json","Output a JSON envelope instead of raw markdown",!1).action((q,K,X)=>{let Q;try{Q=zQ(q,K??"")}catch(Y){console.error(`Error: ${h(Y)}`);if(Y instanceof hq&&Y.hint)console.error(`Hint: ${Y.hint}`);process.exitCode=Y instanceof hq?Y.exitCode:J.GENERIC_ERROR;return}if(X.json){console.log(JSON.stringify(Q,null,2));return}process.stdout.write(Q.content);if(!Q.content.endsWith(`
|
|
3
3
|
`))process.stdout.write(`
|
|
4
4
|
`)});const B=TQ($);$.command("convention-audit").description("Scan adapters for agent-native convention violations").argument("[target]","site or site/name").option("--site <site>","Limit audit to one site").option("-f, --format <fmt>","Output format: table, json, yaml","table").option("--strict","Exit non-zero when violations are found",!1).action(async(q,K)=>{const{runConventionAudit:X,renderConventionAuditText:Q}=await import("./convention-audit.js"),Y=X({projectRoot:findPackageRoot(uq),target:q,site:K.site}),Z=String(K.format??"table").toLowerCase();if(Z==="json"||Z==="yaml"||Z==="yml")Aq(Y,{fmt:Z});else console.log(Q(Y));if(K.strict&&!Y.ok)process.exitCode=J.GENERIC_ERROR});const j=$.command("browser").addOption(new tK("--session <name>","Internal — set automatically from the <session> positional").hideHelp()).option("--window <mode>","Browser window mode: foreground or background").description("Browser control — navigate, click, type, extract, wait (no LLM needed)").usage("<session> <command> [options]").addHelpText("after",`
|
|
5
5
|
<session> is a required positional: pass the name of the browser session every subcommand should operate on. Reuse the same name across calls to keep the tab/state alive; pick a different name to isolate parallel browser work.
|
|
6
6
|
|
|
7
7
|
Examples:
|
|
8
|
-
$
|
|
9
|
-
$
|
|
10
|
-
$
|
|
11
|
-
$
|
|
12
|
-
$
|
|
13
|
-
$
|
|
14
|
-
`),S=j.description();async function F(q,K,X={}){const Q=await q.evaluate(LQ(K,X));if(!Q.ok)throw new LK({code:Q.code,message:Q.message,hint:Q.hint,candidates:Q.candidates,matches_n:Q.matches_n});return{matches_n:Q.matches_n,match_level:Q.match_level}}function P(q){if(q===void 0||q===null||q==="")return null;const K=String(q);if(!/^\d+$/.test(K))return{error:`--nth must be a non-negative integer, got "${K}"`};return Number.parseInt(K,10)}function Kq(q){console.log(JSON.stringify({error:{code:q.code,message:q.message,hint:q.hint,...q.candidates&&{candidates:q.candidates},...q.matches_n!==void 0&&{matches_n:q.matches_n}}},null,2))}function e(q){return q.toLowerCase().includes("javascript dialog")}function r(q){console.log(JSON.stringify({error:{code:"javascript_dialog_open",message:q,hint:"Handle the modal first:
|
|
8
|
+
$ ppcli browser work open https://x.com
|
|
9
|
+
$ ppcli browser work open https://x.com --window background
|
|
10
|
+
$ ppcli browser work click 12
|
|
11
|
+
$ ppcli browser work state
|
|
12
|
+
$ ppcli browser work bind
|
|
13
|
+
$ ppcli browser work unbind
|
|
14
|
+
`),S=j.description();async function F(q,K,X={}){const Q=await q.evaluate(LQ(K,X));if(!Q.ok)throw new LK({code:Q.code,message:Q.message,hint:Q.hint,candidates:Q.candidates,matches_n:Q.matches_n});return{matches_n:Q.matches_n,match_level:Q.match_level}}function P(q){if(q===void 0||q===null||q==="")return null;const K=String(q);if(!/^\d+$/.test(K))return{error:`--nth must be a non-negative integer, got "${K}"`};return Number.parseInt(K,10)}function Kq(q){console.log(JSON.stringify({error:{code:q.code,message:q.message,hint:q.hint,...q.candidates&&{candidates:q.candidates},...q.matches_n!==void 0&&{matches_n:q.matches_n}}},null,2))}function e(q){return q.toLowerCase().includes("javascript dialog")}function r(q){console.log(JSON.stringify({error:{code:"javascript_dialog_open",message:q,hint:"Handle the modal first: ppcli browser dialog accept (or dismiss). Use --text for prompt dialogs."}},null,2))}function D(q){return async(...K)=>{let X=null;try{const Q=K.at(-1)instanceof _q?K.at(-1):void 0,Y=zX(Q),Z=nq(Q),z=lq(Q),U=TK(Q,"foreground");X=await HX(Z,Y,z,{windowMode:U});await q(X,...K)}catch(Q){if(Q instanceof VQ){n.error(Q.message);if(Q.hint)n.error(`Hint: ${Q.hint}`)}else if(Q instanceof Bq){if(e(Q.message))r(Q.message);else if(Q.code)console.log(JSON.stringify({error:{code:Q.code,message:Q.message,...Q.hint?{hint:Q.hint}:{}}},null,2));n.error(Q.message);if(Q.hint)n.error(`Hint: ${Q.hint}`)}else if(Q instanceof LK){Kq(Q);n.error(`[${Q.code}] ${Q.message}`);if(Q.hint)n.error(`Hint: ${Q.hint}`)}else{const Y=h(Q);if(e(Y)){r(Y);n.error(Y)}else if(Y.includes("attach failed")||Y.includes("chrome-extension://"))n.error("Browser attach failed — another extension may be interfering. Try disabling 1Password.");else n.error(Y)}process.exitCode=J.GENERIC_ERROR}}}j.command("bind").description("Bind the current Chrome tab/window to the browser session named by <session>").action(async(q,K)=>{const X=q instanceof _q?q:K,Q=nq(X);try{const{BrowserBridge:Y}=await import("./browser/index.js"),Z=new Y,z=lq(X);await Z.connect({timeout:xq,session:Q,surface:"browser",...z&&{contextId:z}});const U=await fQ(Q,{...z&&{contextId:z}});Wq(void 0,Eq(Q,z));console.log(JSON.stringify({session:Q,...U&&typeof U==="object"?U:{data:U}},null,2))}catch(Y){if(Y instanceof Bq&&Y.code)console.log(JSON.stringify({error:{code:Y.code,message:Y.message,...Y.hint?{hint:Y.hint}:{}}},null,2));n.error(Y instanceof Error?Y.message:String(Y));if(Y instanceof Bq&&Y.hint)n.error(`Hint: ${Y.hint}`);process.exitCode=J.GENERIC_ERROR}});j.command("unbind").description("Detach the bound browser session named by <session> without closing the user tab/window").action(async(q,K)=>{const X=q instanceof _q?q:K,Q=nq(X);try{const{BrowserBridge:Y}=await import("./browser/index.js"),Z=new Y,z=lq(X);await Z.connect({timeout:xq,session:Q,surface:"browser",...z&&{contextId:z}});await uQ("close-window",{session:Q,surface:"browser",...z&&{contextId:z}});Wq(void 0,Eq(Q,z));console.log(JSON.stringify({unbound:!0,session:Q},null,2))}catch(Y){if(Y instanceof Bq&&Y.code)console.log(JSON.stringify({error:{code:Y.code,message:Y.message,...Y.hint?{hint:Y.hint}:{}}},null,2));n.error(Y instanceof Error?Y.message:String(Y));if(Y instanceof Bq&&Y.hint)n.error(`Hint: ${Y.hint}`);process.exitCode=J.GENERIC_ERROR}});const o=j.command("tab").description("Tab management — list, create, and close tabs in the browser session");o.command("list").description("List tabs in the browser session with target IDs").action(D(async(q)=>{const K=await q.tabs();console.log(JSON.stringify(K,null,2))}));o.command("new").argument("[url]","Optional URL to open in the new tab").description("Create a new tab and print its target ID").action(D(async(q,K)=>{if(!q.newTab)throw Error("This browser session does not support creating tabs");const X=await q.newTab(K);console.log(JSON.stringify({page:X,url:K??null},null,2))}));E(o.command("select").argument("[targetId]",'Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"').description("Select a tab by target ID and make it the default browser tab")).action(D(async(q,K,X)=>{const Q=hK(K,X);if(!Q)throw Error("Target tab required. Pass it as an argument or --tab <targetId>.");await q.selectTab(Q);Wq(Q,Pq(q));console.log(JSON.stringify({selected:Q},null,2))}));E(o.command("close").argument("[targetId]",'Target tab/page identity returned by "browser open", "browser tab new", or "browser tab list"').description("Close a tab by target ID")).action(D(async(q,K,X)=>{const Q=hK(K,X);if(!q.closeTab)throw Error("This browser session does not support closing tabs");if(!Q)throw Error("Target tab required. Pass it as an argument or --tab <targetId>.");const Y=await dq(q,Q,{scope:Pq(q),source:"explicit"});if(!Y)throw Error(`Target tab ${Q} is not part of the current browser session.`);await q.closeTab(Y);const Z=Pq(q);if(CK(Z)?.defaultPage===Y)Wq(void 0,Z);console.log(JSON.stringify({closed:Y},null,2))}));const Xq="(function(){if(window.__opencli_net)return;window.__opencli_net=[];var M=200,B=1048576,F=window.fetch;function capture(url,method,status,text,ct){if(window.__opencli_net.length>=M)return;var full=text?text.length:0,trunc=full>B,stored=trunc?text.slice(0,B):text,body=null;if(stored){if(trunc){body=stored}else{try{body=JSON.parse(stored)}catch(e){body=stored}}}var e={url:url,method:method||'GET',status:status,size:full,ct:ct,body:body,timestamp:Date.now()};if(trunc){e.bodyTruncated=true;e.bodyFullSize=full}window.__opencli_net.push(e)}window.fetch=async function(){var r=await F.apply(this,arguments);try{var ct=r.headers.get('content-type')||'';if(ct.includes('json')||ct.includes('text')){var c=r.clone(),t=await c.text();capture(r.url||(arguments[0]&&arguments[0].url)||String(arguments[0]),(arguments[1]&&arguments[1].method)||'GET',r.status,t,ct)}}catch(e){}return r};var X=XMLHttpRequest.prototype,O=X.open,S=X.send;X.open=function(m,u){this._om=m;this._ou=u;return O.apply(this,arguments)};X.send=function(){var x=this;x.addEventListener('load',function(){try{var ct=x.getResponseHeader('content-type')||'';if(ct.includes('json')||ct.includes('text')){capture(x._ou,x._om||'GET',x.status,x.responseText||'',ct)}}catch(e){}});return S.apply(this,arguments)}})()";E(j.command("open").argument("<url>").description("Open URL in the browser session")).action(D(async(q,K,X)=>{const Q=await q.startNetworkCapture?.()??!1;await q.goto(K);await q.wait(2);if(!Q)try{await q.evaluate(Xq)}catch{}const Y=await q.getCurrentUrl?.()??K,Z=YX(Y,Pq(q),{oncePerSession:!0});console.log(JSON.stringify({url:Y,...q.getActivePage?.()?{page:q.getActivePage?.()}:{},...Z?{sitemap:Z}:{}},null,2))}));E(j.command("back").description("Go back in browser history")).action(D(async(q,K)=>{await q.evaluate("history.back()");await q.wait(2);console.log("Navigated back")}));E(j.command("scroll").argument("<direction>","up or down").option("--amount <pixels>","Pixels to scroll","500")).description("Scroll page").action(D(async(q,K,X)=>{if(K!=="up"&&K!=="down"){console.error(`Invalid direction "${K}". Use "up" or "down".`);process.exitCode=J.USAGE_ERROR;return}await q.scroll(K,parseInt(X.amount,10));console.log(`Scrolled ${K}`)}));E(j.command("state").description("Page state: URL, title, interactive elements with [N] indices").option("--source <source>","Snapshot backend: dom (default) or ax prototype","dom").option("--compare-sources","Print DOM vs AX snapshot metrics for observation promotion decisions",!1)).action(D(async(q,K)=>{if(K.compareSources===!0){const[Z,z]=await Promise.all([wK(q,"dom"),wK(q,"ax")]);console.log(JSON.stringify({url:await q.getCurrentUrl?.()??"",sources:{dom:Z,ax:z}},null,2));return}const X=String(K.source??"dom").toLowerCase();if(X!=="dom"&&X!=="ax"){console.log(JSON.stringify({error:{code:"invalid_source",message:`--source must be "dom" or "ax", got "${K.source}"`}},null,2));process.exitCode=J.USAGE_ERROR;return}const Q=await q.snapshot({viewportExpand:2000,source:X}),Y=await q.getCurrentUrl?.()??"";console.log(`URL: ${Y}
|
|
15
15
|
`);console.log(typeof Q==="string"?Q:JSON.stringify(Q,null,2))}));E(j.command("frames").description("List cross-origin iframe targets in snapshot order")).action(D(async(q)=>{const K=await q.frames?.()??[];console.log(JSON.stringify(K,null,2))}));E(j.command("screenshot").argument("[path]","Save to file (base64 if omitted)")).option("--full-page","Capture the full scrollable page, not just the viewport",!1).option("--annotate","Overlay visible browser state ref labels on the screenshot",!1).option("--width <n>","Override viewport width in CSS pixels for this screenshot only",(q)=>vK(q,"width")).option("--height <n>","Override viewport height in CSS pixels for this screenshot only (ignored with --full-page)",(q)=>vK(q,"height")).description("Take screenshot").action(D(async(q,K,X)=>{const Q={fullPage:X.fullPage===!0,annotate:X.annotate===!0,width:X.width,height:X.height},Y=X.annotate===!0?(q.annotatedScreenshot??q.screenshot).bind(q):q.screenshot.bind(q);if(K){await Y({...Q,path:K});console.log(`Screenshot saved to: ${K}`)}else console.log(await Y({...Q,format:"png"}))}));const Jq=[".js-mocaptcha-img",".moclickcaptcha-img",".moclickcaptcha-draw",".geetest_item_img",".geetest_widget canvas",".captcha-image img",".captcha img",".captcha canvas",'img[src*="captcha" i]','img[class*="captcha" i]','canvas[class*="captcha" i]'],oq=6;function pq(q){const K=q&&q.trim()?[q.trim(),...Jq]:Jq;return`(() => {
|
|
16
16
|
var sels = ${JSON.stringify(K)};
|
|
17
17
|
var el = null, used = '';
|
|
@@ -69,7 +69,7 @@ Examples:
|
|
|
69
69
|
}
|
|
70
70
|
} catch (e) {}
|
|
71
71
|
return { captcha_present: present, status_text: status, url: (location.href || '').slice(0, 100) };
|
|
72
|
-
})()`}E(j.command("captcha").argument("[selector]","验证码图片元素 CSS 选择器(缺省自动探测常见点选验证码)")).option("--save <path>","把全视口截图存到该路径(缺省存到临时 PNG 文件)").option("--scale <n>","验证码区域裁剪图的放大倍数(1..6,缺省 3;放大后认扭曲字更准)","3").description("抓取点选验证码:存整图 + 只含验证码的放大裁剪图 + 返回坐标与提示文字,供 AI 视觉识别后配合 captcha-click 点击").action(D(async(q,K,X)=>{const Q=await q.evaluate(pq(typeof K==="string"?K:void 0));if(!Q||!Q.found){console.log(JSON.stringify({error:{code:"captcha_not_found",message:'未探测到点选验证码图片。可显式传选择器,如
|
|
72
|
+
})()`}E(j.command("captcha").argument("[selector]","验证码图片元素 CSS 选择器(缺省自动探测常见点选验证码)")).option("--save <path>","把全视口截图存到该路径(缺省存到临时 PNG 文件)").option("--scale <n>","验证码区域裁剪图的放大倍数(1..6,缺省 3;放大后认扭曲字更准)","3").description("抓取点选验证码:存整图 + 只含验证码的放大裁剪图 + 返回坐标与提示文字,供 AI 视觉识别后配合 captcha-click 点击").action(D(async(q,K,X)=>{const Q=await q.evaluate(pq(typeof K==="string"?K:void 0));if(!Q||!Q.found){console.log(JSON.stringify({error:{code:"captcha_not_found",message:'未探测到点选验证码图片。可显式传选择器,如 ppcli browser <s> captcha ".js-mocaptcha-img"',tried:Jq}},null,2));process.exitCode=J.USAGE_ERROR;return}const Y=X?.save&&String(X.save)||M.join(zq.tmpdir(),`opencli-captcha-${Date.now()}.png`);await q.screenshot({format:"png",path:Y});const Z=Q.rect,z=Q.dpr||1,U=Math.max(1,Math.min(6,Number(X?.scale??3)||3)),G=oq;let W=null;const _=q.cdp;if(typeof _==="function"){const R={x:Math.max(0,Z.x-G),y:Math.max(0,Z.y-G),width:Z.w+G*2,height:Z.h+G*2,scale:U},k=await _.call(q,"Page.captureScreenshot",{format:"jpeg",quality:82,clip:R,captureBeyondViewport:!1});if(k&&k.data){W=Y.replace(/\.png$/i,"")+".crop.jpg";I.writeFileSync(W,Buffer.from(k.data,"base64"))}}console.log(JSON.stringify({ok:!0,selector:Q.selector,prompt:Q.prompt||"",crop:W,crop_scale:W?U:null,crop_pad:W?G:null,saved:Y,rect_css:Z,rect_screenshot_px:{x:Math.round(Z.x*z),y:Math.round(Z.y*z),w:Math.round(Z.w*z),h:Math.round(Z.h*z)},dpr:z,natural:Q.natural,viewport:Q.viewport,guide:"① read_local_file 打开 crop(只含验证码、已放大)认清每个待点字与顺序(注意会混入不在 prompt 里的干扰字,只点 prompt 要求的)。"+"② 坐标直接读成「在 crop 这张图里的比例」(0..1,左上角为 0,0)——不用管 pad/rect,看到字在 crop 的哪就填哪。"+'③ 执行:ppcli browser <session> captcha-click --crop --in "'+Q.selector+'" "x1,y1 x2,y2 ..."(--crop 表示坐标是 crop 图比例;空格分隔,顺序即点击顺序)。'+"命令会回读点了几个、验证码是否还在、URL 是否跳转,据此判断成功/补点/重来。"},null,2))}));E(j.command("captcha-click").argument("<points>",'待点击坐标,空格分隔且顺序即点击顺序,如 "0.30,0.46 0.68,0.66"')).option("--in <selector>","坐标映射基准元素(缺省自动探测验证码图片)").option("--crop","坐标按「captcha 裁剪图(crop)里的比例」解释(0..1,左上角为0,0)——AI 看哪张就按那张填,内部自动扣掉 pad。推荐").option("--px","坐标按「截图设备像素」解释(自动按 devicePixelRatio 换算成 CSS 像素)").option("--css","坐标按「CSS 视口像素」解释(直接点击,不做映射)").option("--delay <ms>","每次点击之间的间隔毫秒","250").description("按坐标依次点击(点选验证码用):把 AI 从图上读到的位置一次性点上,点完回读验证码是否还在/是否跳转。默认坐标为相对基准元素的比例(0..1),--crop 则为裁剪图比例").action(D(async(q,K,X)=>{const Y=String(K??"").trim().split(/\s+/).filter(Boolean).map((A)=>{const[b,x]=A.split(",");return{x:Number(b),y:Number(x)}});if(Y.length===0||Y.some((A)=>!Number.isFinite(A.x)||!Number.isFinite(A.y))){console.log(JSON.stringify({error:{code:"usage_error",message:'坐标格式应为 "x,y x,y ...",如 "0.30,0.46 0.68,0.66"'}},null,2));process.exitCode=J.USAGE_ERROR;return}const Z=X?.css?"css":X?.px?"px":X?.crop?"crop":"frac",z=Math.max(0,Number(X?.delay??250)||0);let U={x:0,y:0,w:0,h:0},G=1;if(Z!=="css"){const A=await q.evaluate(pq(typeof X?.in==="string"?X.in:void 0));if(!A||!A.found||!A.rect){console.log(JSON.stringify({error:{code:"captcha_not_found",message:"captcha-click 找不到基准元素,请用 --in <selector> 指定,或用 --css 传绝对坐标"}},null,2));process.exitCode=J.USAGE_ERROR;return}U=A.rect;G=A.dpr||1}const W=oq,_=U.w+W*2,R=U.h+W*2,k=Math.max(0,U.x-W),f=Math.max(0,U.y-W),y=(A)=>{if(Z==="css")return A;if(Z==="px")return{x:A.x/G,y:A.y/G};if(Z==="crop")return{x:k+A.x*_,y:f+A.y*R};return{x:U.x+A.x*U.w,y:U.y+A.y*U.h}},w=q.cdp,T=q.nativeClick,d=(A)=>new Promise((b)=>setTimeout(b,A));async function g(A,b,x,u){if(typeof w==="function"){const c=12+u%4;for(let p=1;p<=c;p++){const t=p/c,C=t*t*(3-2*t),l=Math.sin(t*Math.PI)*10*(u%2===0?1:-1),bq=x.x+(A-x.x)*C,rK=x.y+(b-x.y)*C+l;await w.call(q,"Input.dispatchMouseEvent",{type:"mouseMoved",x:Math.round(bq),y:Math.round(rK)});await d(8+p%3*6)}await w.call(q,"Input.dispatchMouseEvent",{type:"mouseMoved",x:A,y:b});await d(40+u%3*25);await w.call(q,"Input.dispatchMouseEvent",{type:"mousePressed",x:A,y:b,button:"left",clickCount:1});await d(45+u%4*20);await w.call(q,"Input.dispatchMouseEvent",{type:"mouseReleased",x:A,y:b,button:"left",clickCount:1});return"cdp"}if(typeof T==="function"){await T.call(q,A,b);return"native"}await q.evaluate(`(() => { var el = document.elementFromPoint(${A}, ${b}); if (!el) return false; ['mousemove','mousedown','mouseup','click'].forEach(function(t){ el.dispatchEvent(new MouseEvent(t, { bubbles: true, cancelable: true, view: window, clientX: ${A}, clientY: ${b} })); }); return true; })()`);return"synthetic"}const qq=[];let L="synthetic",O={x:Math.round(U.x+U.w/2)||400,y:Math.round(U.y-40)||200};for(let A=0;A<Y.length;A++){const b=y(Y[A]),x=Math.round(b.x),u=Math.round(b.y);L=await g(x,u,O,A);O={x,y:u};qq.push({x,y:u});if(A<Y.length-1&&z>0)await d(z)}await d(700);let a={};try{a=await q.evaluate(fK(typeof X?.in==="string"?X.in:void 0))}catch{}console.log(JSON.stringify({ok:!0,mode:Z,method:L,clicked_n:qq.length,points_css:qq,after:a},null,2))}));E(j.command("console")).option("--level <level>","Console level: all, error, warning, log, info, debug","all").option("--since <duration>","Only include messages from the last duration (for example: 30s, 2m)").option("--until <duration>","Only include messages older than the duration from now").option("--follow","Continuously print new console messages as JSON lines",!1).description("Read recent browser console messages").action(D(async(q,K)=>{const X=Rq(K.since,"since"),Q=Rq(K.until,"until");if(X&&typeof X==="object"){console.log(JSON.stringify({error:{code:"invalid_since",message:X.error}},null,2));process.exitCode=J.USAGE_ERROR;return}if(Q&&typeof Q==="object"){console.log(JSON.stringify({error:{code:"invalid_until",message:Q.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const Y=(U)=>U.map((G)=>{if(G&&typeof G==="object"){const W=G;return{...W,timestamp:cq(W.timestamp)}}return{type:"log",text:String(G),timestamp:Date.now()}}),Z=(U)=>mq(U,{sinceMs:X,untilMs:Q}).filter((G)=>{if(K.level==="all")return!0;const W=String(G.type??G.level??"").toLowerCase();return K.level==="error"?W==="error"||W==="warning":W===String(K.level).toLowerCase()});if(K.follow){let U=0;while(!0){const G=Z(Y(await q.consoleMessages("all"))),W=selectFreshByTimestamp(G,U);for(const _ of W.fresh)console.log(JSON.stringify({..._,timestamp:Uq(_.timestamp)}));U=W.lastSeenTs;await new Promise((_)=>setTimeout(_,PK))}}const z=Z(Y(await q.consoleMessages(K.level)));console.log(JSON.stringify({session:iq(q),captured_at:new Date().toISOString(),count:z.length,messages:z.map((U)=>({...U,timestamp:Uq(U.timestamp)}))},null,2))}));E(j.command("analyze").argument("<url>")).description("Classify site: anti-bot vendor, real-data API candidates, pattern (A/B/C/D), nearest adapter, next step").action(D(async(q,K)=>{const X=await q.startNetworkCapture?.()??!1;await q.goto(K);await q.wait(2);if(!X)try{await q.evaluate(Xq)}catch{}await Gq(q);await q.wait(1);const Y=(await Gq(q)).map((k)=>({url:k.url,status:k.status,contentType:k.ct,bodyPreview:typeof k.body==="string"?k.body.slice(0,2000):k.body?JSON.stringify(k.body).slice(0,2000):null})),Z=`(function(){
|
|
73
73
|
return {
|
|
74
74
|
cookieNames: (document.cookie || '').split(';').map(function(c){ return c.trim().split('=')[0]; }).filter(Boolean),
|
|
75
75
|
initialState: {
|
|
@@ -81,7 +81,7 @@ Examples:
|
|
|
81
81
|
title: document.title || '',
|
|
82
82
|
finalUrl: location.href,
|
|
83
83
|
};
|
|
84
|
-
})()`,z=await q.evaluate(Z),U=(await q.getCookies({url:z.finalUrl||K}).catch(()=>[])).map((k)=>k.name).filter(Boolean),G=[...new Set([...z.cookieNames,...U])],W={requestedUrl:K,finalUrl:z.finalUrl,cookieNames:G,networkEntries:Y,initialState:z.initialState,title:z.title},_=CQ(W,Dq()),R=resolveSitemapAvailabilityForUrl(z.finalUrl||K);console.log(JSON.stringify({..._,...R?{sitemap:R}:{}},null,2))}));const m=(q)=>q.option("--role <role>","Semantic role (button, link, textbox, option, etc.)").option("--name <text>","Accessible name contains text (aria-label, label, title, placeholder, or visible text)").option("--label <text>","Associated label contains text").option("--text <text>","Visible text contains text").option("--testid <id>","data-testid / data-test / test-id contains id"),aq=(q,K)=>q.option(`--${K}-role <role>`,`${K} semantic role`).option(`--${K}-name <text>`,`${K} accessible name contains text`).option(`--${K}-label <text>`,`${K} associated label contains text`).option(`--${K}-text <text>`,`${K} visible text contains text`).option(`--${K}-testid <id>`,`${K} data-testid / data-test / test-id contains id`),Vq=(q)=>{const K={};for(const X of["role","name","label","text","testid"]){const Q=q[X];if(typeof Q==="string"&&Q.trim())K[X]=Q.trim()}return Object.keys(K).length>0?K:null},xK=(q,K)=>{const X={},Q={role:`${K}Role`,name:`${K}Name`,label:`${K}Label`,text:`${K}Text`,testid:`${K}Testid`};for(const Y of["role","name","label","text","testid"]){const Z=q[Q[Y]];if(typeof Z==="string"&&Z.trim())X[Y]=Z.trim()}return Object.keys(X).length>0?X:null},rq=async(q,K,X)=>{const Q=await q.evaluate(_K({...K,limit:6}));if(DK(Q))return Q;if(X==="write"&&Q.matches_n!==1)return{error:{code:"semantic_ambiguous",message:`Semantic locator matched ${Q.matches_n} elements; write actions require a unique target.`,hint:"Add --name/--label/--text/--testid or use browser find with a narrower locator.",matches_n:Q.matches_n,entries:Q.entries}};const Y=Q.entries[0];if(!Y)return{error:{code:"semantic_not_found",message:"Semantic locator matched 0 elements",hint:"Try browser state, --source ax, or relax the semantic locator."}};const Z=String(Y.ref);if(X==="read")return{target:Z,...Q.matches_n>1?{total_matches:Q.matches_n}:{}};return Z},uK=async(q,K,X)=>{const Q=Vq(K);if(!Q)return null;return rq(q,Q,X)},Oq=async(q,K,X,Q)=>{const Y=typeof K==="string"&&K.trim()?K.trim():"",Z=!!Vq(X);if(Y&&Z)return{error:{code:"usage_error",message:"Pass either <target> or semantic locator flags, not both."}};if(Y)return Y;const z=await uK(q,X,Q);if(z)return z;return{error:{code:"usage_error",message:"Missing target. Pass a numeric ref/CSS selector, or semantic flags like --role button --name Submit."}}},Yq=(q)=>{console.log(JSON.stringify(q,null,2));process.exitCode=J.USAGE_ERROR},Zq=async(q,K,X)=>{const Q=await Oq(q,K,X,"write");if(typeof Q==="string")return Q;if("error"in Q)Yq(Q);return null},kq=async(q,K,X,Q,Y)=>{const Z=!!Vq(Q);if(Z&&X!==void 0){Yq({error:{code:"usage_error",message:`When using semantic locator flags, pass only <${Y}> as the positional argument.`}});return null}const z=Z?K:X;if(z===void 0){Yq({error:{code:"usage_error",message:`Missing ${Y}.`,hint:Z?`With semantic locator flags, pass the ${Y} as the only positional argument.`:`Pass both a target and ${Y}.`}});return null}const U=await Zq(q,Z?void 0:K,Q);if(!U)return null;return{target:U,value:String(z)}},sq=async(q,K,X,Q,Y)=>{const Z=typeof K==="string"&&K.trim()?K.trim():"",z=xK(X,Q);if(Z&&z){Yq({error:{code:"usage_error",message:`Pass either <${Y}> or --${Q}-* semantic locator flags, not both.`}});return null}if(Z)return Z;if(z){const U=await rq(q,z,"write");if(typeof U==="string")return U;if("error"in U)Yq(U);return null}Yq({error:{code:"usage_error",message:`Missing ${Y}. Pass a numeric ref/CSS selector, or --${Q}-role/--${Q}-name semantic flags.`}});return null};E(m(j.command("find")).option("--css <selector>","CSS selector (required)").option("--limit <n>","Max entries returned","50").option("--text-max <n>","Max chars of trimmed text per entry","120").description("Find DOM elements by CSS or semantic locator — returns JSON {matches_n, entries[]}")).action(D(async(q,K)=>{const X=Vq(K);if((!K.css||typeof K.css!=="string")&&!X){console.log(JSON.stringify({error:{code:"usage_error",message:"--css <selector> or a semantic locator flag is required",hint:'Examples:
|
|
84
|
+
})()`,z=await q.evaluate(Z),U=(await q.getCookies({url:z.finalUrl||K}).catch(()=>[])).map((k)=>k.name).filter(Boolean),G=[...new Set([...z.cookieNames,...U])],W={requestedUrl:K,finalUrl:z.finalUrl,cookieNames:G,networkEntries:Y,initialState:z.initialState,title:z.title},_=CQ(W,Dq()),R=resolveSitemapAvailabilityForUrl(z.finalUrl||K);console.log(JSON.stringify({..._,...R?{sitemap:R}:{}},null,2))}));const m=(q)=>q.option("--role <role>","Semantic role (button, link, textbox, option, etc.)").option("--name <text>","Accessible name contains text (aria-label, label, title, placeholder, or visible text)").option("--label <text>","Associated label contains text").option("--text <text>","Visible text contains text").option("--testid <id>","data-testid / data-test / test-id contains id"),aq=(q,K)=>q.option(`--${K}-role <role>`,`${K} semantic role`).option(`--${K}-name <text>`,`${K} accessible name contains text`).option(`--${K}-label <text>`,`${K} associated label contains text`).option(`--${K}-text <text>`,`${K} visible text contains text`).option(`--${K}-testid <id>`,`${K} data-testid / data-test / test-id contains id`),Vq=(q)=>{const K={};for(const X of["role","name","label","text","testid"]){const Q=q[X];if(typeof Q==="string"&&Q.trim())K[X]=Q.trim()}return Object.keys(K).length>0?K:null},xK=(q,K)=>{const X={},Q={role:`${K}Role`,name:`${K}Name`,label:`${K}Label`,text:`${K}Text`,testid:`${K}Testid`};for(const Y of["role","name","label","text","testid"]){const Z=q[Q[Y]];if(typeof Z==="string"&&Z.trim())X[Y]=Z.trim()}return Object.keys(X).length>0?X:null},rq=async(q,K,X)=>{const Q=await q.evaluate(_K({...K,limit:6}));if(DK(Q))return Q;if(X==="write"&&Q.matches_n!==1)return{error:{code:"semantic_ambiguous",message:`Semantic locator matched ${Q.matches_n} elements; write actions require a unique target.`,hint:"Add --name/--label/--text/--testid or use browser find with a narrower locator.",matches_n:Q.matches_n,entries:Q.entries}};const Y=Q.entries[0];if(!Y)return{error:{code:"semantic_not_found",message:"Semantic locator matched 0 elements",hint:"Try browser state, --source ax, or relax the semantic locator."}};const Z=String(Y.ref);if(X==="read")return{target:Z,...Q.matches_n>1?{total_matches:Q.matches_n}:{}};return Z},uK=async(q,K,X)=>{const Q=Vq(K);if(!Q)return null;return rq(q,Q,X)},Oq=async(q,K,X,Q)=>{const Y=typeof K==="string"&&K.trim()?K.trim():"",Z=!!Vq(X);if(Y&&Z)return{error:{code:"usage_error",message:"Pass either <target> or semantic locator flags, not both."}};if(Y)return Y;const z=await uK(q,X,Q);if(z)return z;return{error:{code:"usage_error",message:"Missing target. Pass a numeric ref/CSS selector, or semantic flags like --role button --name Submit."}}},Yq=(q)=>{console.log(JSON.stringify(q,null,2));process.exitCode=J.USAGE_ERROR},Zq=async(q,K,X)=>{const Q=await Oq(q,K,X,"write");if(typeof Q==="string")return Q;if("error"in Q)Yq(Q);return null},kq=async(q,K,X,Q,Y)=>{const Z=!!Vq(Q);if(Z&&X!==void 0){Yq({error:{code:"usage_error",message:`When using semantic locator flags, pass only <${Y}> as the positional argument.`}});return null}const z=Z?K:X;if(z===void 0){Yq({error:{code:"usage_error",message:`Missing ${Y}.`,hint:Z?`With semantic locator flags, pass the ${Y} as the only positional argument.`:`Pass both a target and ${Y}.`}});return null}const U=await Zq(q,Z?void 0:K,Q);if(!U)return null;return{target:U,value:String(z)}},sq=async(q,K,X,Q,Y)=>{const Z=typeof K==="string"&&K.trim()?K.trim():"",z=xK(X,Q);if(Z&&z){Yq({error:{code:"usage_error",message:`Pass either <${Y}> or --${Q}-* semantic locator flags, not both.`}});return null}if(Z)return Z;if(z){const U=await rq(q,z,"write");if(typeof U==="string")return U;if("error"in U)Yq(U);return null}Yq({error:{code:"usage_error",message:`Missing ${Y}. Pass a numeric ref/CSS selector, or --${Q}-role/--${Q}-name semantic flags.`}});return null};E(m(j.command("find")).option("--css <selector>","CSS selector (required)").option("--limit <n>","Max entries returned","50").option("--text-max <n>","Max chars of trimmed text per entry","120").description("Find DOM elements by CSS or semantic locator — returns JSON {matches_n, entries[]}")).action(D(async(q,K)=>{const X=Vq(K);if((!K.css||typeof K.css!=="string")&&!X){console.log(JSON.stringify({error:{code:"usage_error",message:"--css <selector> or a semantic locator flag is required",hint:'Examples: ppcli browser find --css ".btn.primary"; ppcli browser find --role button --name Save'}},null,2));process.exitCode=J.USAGE_ERROR;return}if(K.css&&X){console.log(JSON.stringify({error:{code:"usage_error",message:"Pass either --css or semantic locator flags, not both."}},null,2));process.exitCode=J.USAGE_ERROR;return}const Q=P(K.limit);if(Q&&typeof Q==="object"&&"error"in Q){console.log(JSON.stringify({error:{code:"usage_error",message:Q.error.replace("--nth","--limit")}},null,2));process.exitCode=J.USAGE_ERROR;return}const Y=P(K.textMax);if(Y&&typeof Y==="object"&&"error"in Y){console.log(JSON.stringify({error:{code:"usage_error",message:Y.error.replace("--nth","--text-max")}},null,2));process.exitCode=J.USAGE_ERROR;return}const Z=await q.evaluate(X?_K({...X,limit:Q??void 0,textMax:Y??void 0}):RQ(K.css,{limit:Q??void 0,textMax:Y??void 0}));if(DK(Z)){console.log(JSON.stringify(Z,null,2));process.exitCode=J.GENERIC_ERROR;return}console.log(JSON.stringify(Z,null,2))}));const $q=j.command("get").description("Get page properties");E($q.command("title").description("Page title")).action(D(async(q)=>{console.log(await q.evaluate("document.title"))}));E($q.command("url").description("Current page URL")).action(D(async(q)=>{console.log(await q.getCurrentUrl?.()??await q.evaluate("location.href"))}));const Iq=async(q,K,X,Q,Y)=>{const Z=await Oq(q,K,X,"read");if(typeof Z!=="string"&&"error"in Z){console.log(JSON.stringify(Z,null,2));process.exitCode=J.USAGE_ERROR;return}const z=typeof Z==="string"?Z:Z.target,U=typeof Z==="string"?void 0:Z.total_matches,G=P(X.nth);if(G&&typeof G==="object"&&"error"in G){console.log(JSON.stringify({error:{code:"usage_error",message:G.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{matches_n:W,match_level:_}=await F(q,z,{firstOnMulti:G===null,...typeof G==="number"?{nth:G}:{}}),R=await q.evaluate(Q);let k;if(Y==="attributes")try{k=R==null?{}:JSON.parse(String(R))}catch{k=R}else k=R??null;console.log(JSON.stringify({value:k,matches_n:W,match_level:_,...U&&U>1?{total_matches:U}:{}},null,2))};E(m($q.command("text")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","Pick the nth match (0-based) when <target> is a multi-match CSS selector").description("Element text content — JSON envelope {value, matches_n}")).action(D(async(q,K,X)=>Iq(q,K,X??{},_Q(),"text")));E(m($q.command("value")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","Pick the nth match (0-based) when <target> is a multi-match CSS selector").description("Input/textarea value — JSON envelope {value, matches_n}")).action(D(async(q,K,X)=>Iq(q,K,X??{},DQ(),"value")));E($q.command("html").option("--selector <css>","CSS selector scope (first match)").option("--as <format>",'Output format: "html" (default) or "json" for structured tree',"html").option("--max <n>","Max characters of raw HTML to return (0 = unlimited)","0").option("--depth <n>","(--as json) Max tree depth below root (0 = root only, 0 disables = unlimited via empty)","").option("--children-max <n>","(--as json) Max element children kept per node (empty = unlimited)","").option("--text-max <n>","(--as json) Max chars of direct text kept per node (empty = unlimited)","").description("Page HTML (or scoped); use --as json for a {tag, attrs, text, children} tree")).action(D(async(q,K)=>{const X=String(K.as||"html").toLowerCase();if(X!=="html"&&X!=="json"){console.log(JSON.stringify({error:{code:"invalid_format",message:`--as must be "html" or "json", got "${K.as}"`}},null,2));process.exitCode=J.USAGE_ERROR;return}const Q=String(K.max??"0");if(!/^\d+$/.test(Q)){console.log(JSON.stringify({error:{code:"invalid_max",message:`--max must be a non-negative integer, got "${K.max}"`}},null,2));process.exitCode=J.USAGE_ERROR;return}const Y=Number.parseInt(Q,10);if(X==="json"){const G=(w,T)=>{const d=T===void 0||T===null?"":String(T);if(d==="")return null;if(!/^\d+$/.test(d))return{error:`${w} must be a non-negative integer, got "${d}"`};return Number.parseInt(d,10)},W=G("--depth",K.depth),_=G("--children-max",K.childrenMax),R=G("--text-max",K.textMax);for(const w of[W,_,R])if(w&&typeof w==="object"&&"error"in w){console.log(JSON.stringify({error:{code:"invalid_budget",message:w.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const k=MQ({selector:K.selector??null,depth:W,childrenMax:_,textMax:R}),f=await q.evaluate(k);if(f&&typeof f==="object"&&"invalidSelector"in f&&f.invalidSelector){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${K.selector}" is not a valid CSS selector: ${f.reason}`}},null,2));process.exitCode=J.USAGE_ERROR;return}const y=f;if(!y||y.matched===0){console.log(JSON.stringify({error:{code:"selector_not_found",message:K.selector?`Selector "${K.selector}" matched 0 elements.`:"Page has no documentElement."}},null,2));process.exitCode=J.USAGE_ERROR;return}console.log(JSON.stringify(y,null,2));return}const Z=K.selector?JSON.stringify(K.selector):"null",z=await q.evaluate(`(() => {
|
|
85
85
|
const s = ${Z};
|
|
86
86
|
if (s) {
|
|
87
87
|
try {
|
|
@@ -92,15 +92,15 @@ Examples:
|
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
94
|
return { kind: 'ok', html: document.documentElement ? document.documentElement.outerHTML : null };
|
|
95
|
-
})()`);if(z.kind==="invalid_selector"){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${K.selector}" is not a valid CSS selector: ${z.reason}`}},null,2));process.exitCode=J.USAGE_ERROR;return}const U=z.html;if(U===null){if(K.selector){console.log(JSON.stringify({error:{code:"selector_not_found",message:`Selector "${K.selector}" matched 0 elements.`}},null,2));process.exitCode=J.USAGE_ERROR;return}console.log("(empty)");return}if(Y>0&&U.length>Y){console.log(`<!--
|
|
96
|
-
${U.slice(0,Y)}`);return}console.log(U)}));E(m($q.command("attributes")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","Pick the nth match (0-based) when <target> is a multi-match CSS selector").description("Element attributes — JSON envelope {value, matches_n}")).action(D(async(q,K,X)=>Iq(q,K,X??{},AQ(),"attributes")));function s(q){const K=P(q);if(K&&typeof K==="object"&&"error"in K)return K;if(typeof K==="number")return{opts:{nth:K}};return{opts:{}}}function cK(q){const K=Array.isArray(q)?q:[];if(K.length===0)return{error:{code:"usage_error",message:"At least one file path is required.",hint:'Example: opencli browser upload "input[type=file]" ./receipt.pdf'}};const X=[];for(const Q of K){const Y=String(Q),Z=Y==="~"||Y.startsWith(`~${M.sep}`)?M.join(zq.homedir(),Y.slice(2)):Y,z=M.resolve(Z);if(!I.existsSync(z))return{error:{code:"file_not_found",message:`File not found: ${z}`}};if(!I.statSync(z).isFile())return{error:{code:"not_a_file",message:`Not a regular file: ${z}`}};X.push(z)}return{files:X}}function tq(q,K){const X=P(q);if(X&&typeof X==="object"&&"error"in X)return{error:X.error.replace("--nth",K)};if(typeof X==="number")return{opts:{nth:X}};return{opts:{}}}E(m(j.command("click")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Click element — JSON envelope {clicked, target, matches_n}")).action(D(async(q,K,X)=>{const Q=await Oq(q,K,X??{},"write");if(typeof Q!=="string"){console.log(JSON.stringify(Q,null,2));process.exitCode=J.USAGE_ERROR;return}const Y=s(X?.nth);if("error"in Y){console.log(JSON.stringify({error:{code:"usage_error",message:Y.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{matches_n:Z,match_level:z}=await q.click(Q,Y.opts);console.log(JSON.stringify({clicked:!0,target:Q,matches_n:Z,match_level:z},null,2))}));E(m(j.command("type")).argument("[targetOrText]","Numeric ref/CSS target, or text when using --role/--name/etc.").argument("[text]","Text to type").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Click element, then type text — JSON envelope {typed, text, target, matches_n, autocomplete}")).action(D(async(q,K,X,Q)=>{const Y=await kq(q,K,X,Q??{},"text");if(!Y)return;const Z=s(Q?.nth);if("error"in Z){console.log(JSON.stringify({error:{code:"usage_error",message:Z.error}},null,2));process.exitCode=J.USAGE_ERROR;return}await q.click(Y.target,Z.opts);await q.wait(0.3);const{matches_n:z,match_level:U}=await q.typeText(Y.target,Y.value,Z.opts),G=await q.evaluate(FQ());if(G)await q.wait(0.4);console.log(JSON.stringify({typed:!0,text:Y.value,target:Y.target,matches_n:z,match_level:U,autocomplete:!!G},null,2))}));E(m(j.command("hover")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Move the mouse over an element — JSON envelope {hovered, target, matches_n}")).action(D(async(q,K,X)=>{if(typeof q.hover!=="function")throw Error("browser hover is not supported by this browser backend");const Q=await Zq(q,K,X??{});if(!Q)return;const Y=s(X?.nth);if("error"in Y){console.log(JSON.stringify({error:{code:"usage_error",message:Y.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{matches_n:Z,match_level:z}=await q.hover(Q,Y.opts);console.log(JSON.stringify({hovered:!0,target:Q,matches_n:Z,match_level:z},null,2))}));E(m(j.command("focus")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Focus an element — JSON envelope {focused, target, matches_n}")).action(D(async(q,K,X)=>{if(typeof q.focus!=="function")throw Error("browser focus is not supported by this browser backend");const Q=await Zq(q,K,X??{});if(!Q)return;const Y=s(X?.nth);if("error"in Y){console.log(JSON.stringify({error:{code:"usage_error",message:Y.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{focused:Z,matches_n:z,match_level:U}=await q.focus(Q,Y.opts);console.log(JSON.stringify({focused:Z,target:Q,matches_n:z,match_level:U},null,2))}));E(m(j.command("dblclick")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Double-click element — JSON envelope {dblclicked, target, matches_n}")).action(D(async(q,K,X)=>{if(typeof q.dblClick!=="function")throw Error("browser dblclick is not supported by this browser backend");const Q=await Zq(q,K,X??{});if(!Q)return;const Y=s(X?.nth);if("error"in Y){console.log(JSON.stringify({error:{code:"usage_error",message:Y.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{matches_n:Z,match_level:z}=await q.dblClick(Q,Y.opts);console.log(JSON.stringify({dblclicked:!0,target:Q,matches_n:Z,match_level:z},null,2))}));const eq=async(q,K,X,Q)=>{if(typeof q.setChecked!=="function")throw Error(`browser ${Q?"check":"uncheck"} is not supported by this browser backend`);const Y=await Zq(q,K,X);if(!Y)return;const Z=s(X?.nth);if("error"in Z){console.log(JSON.stringify({error:{code:"usage_error",message:Z.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const z=await q.setChecked(Y,Q,Z.opts);console.log(JSON.stringify({checked:z.checked,changed:z.changed,target:Y,matches_n:z.matches_n,match_level:z.match_level,...z.kind?{kind:z.kind}:{}},null,2))};E(m(j.command("check")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Ensure a checkbox/radio/aria-checked control is checked — JSON envelope {checked, changed, target, matches_n}")).action(D(async(q,K,X)=>{await eq(q,K,X??{},!0)}));E(m(j.command("uncheck")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Ensure a checkbox/aria-checked control is unchecked — JSON envelope {checked, changed, target, matches_n}")).action(D(async(q,K,X)=>{await eq(q,K,X??{},!1)}));E(m(j.command("upload")).argument("[targetOrFile]","Numeric ref/CSS target, or first file when using --role/--name/etc.").argument("[files...]","Local file path(s) to attach").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Attach local files to a file input — JSON envelope {uploaded, files, file_names, target, matches_n}")).action(D(async(q,K,X,Q)=>{if(typeof q.uploadFiles!=="function")throw Error("browser upload is not supported by this browser backend");const Y=!!Vq(Q??{}),z=await Zq(q,Y?void 0:K,Q??{});if(!z)return;const U=s(Q?.nth);if("error"in U){console.log(JSON.stringify({error:{code:"usage_error",message:U.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const G=Y?[K,...Array.isArray(X)?X:[]].filter((R)=>R!==void 0):X,W=cK(G);if("error"in W){console.log(JSON.stringify({error:W.error},null,2));process.exitCode=J.USAGE_ERROR;return}const _=await q.uploadFiles(z,W.files,U.opts);console.log(JSON.stringify(_,null,2))}));E(aq(aq(j.command("drag"),"from"),"to").argument("[source]","Numeric ref/CSS selector to drag from, or omit with --from-role/--from-name/etc.").argument("[target]","Numeric ref/CSS selector to drop onto, or omit with --to-role/--to-name/etc.").option("--from-nth <n>","When <source> is a multi-match CSS selector, pick the nth match (0-based)").option("--to-nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Drag one element to another — JSON envelope {dragged, source, target, source_matches_n, target_matches_n}")).action(D(async(q,K,X,Q)=>{if(typeof q.drag!=="function")throw Error("browser drag is not supported by this browser backend");const Y=await sq(q,K,Q??{},"from","source");if(!Y)return;const Z=await sq(q,X,Q??{},"to","target");if(!Z)return;const z=tq(Q?.fromNth,"--from-nth");if("error"in z){console.log(JSON.stringify({error:{code:"usage_error",message:z.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const U=tq(Q?.toNth,"--to-nth");if("error"in U){console.log(JSON.stringify({error:{code:"usage_error",message:U.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const G=await q.drag(Y,Z,{from:z.opts,to:U.opts});console.log(JSON.stringify(G,null,2))}));E(m(j.command("fill")).argument("[targetOrText]","Numeric ref/CSS target, or text when using --role/--name/etc.").argument("[text]","Text to set exactly").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Set input/textarea/contenteditable text exactly and verify the value — JSON envelope {filled, verified, text, actual}")).action(D(async(q,K,X,Q)=>{const Y=await kq(q,K,X,Q??{},"text");if(!Y)return;const Z=s(Q?.nth);if("error"in Z){console.log(JSON.stringify({error:{code:"usage_error",message:Z.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const z=await q.fillText(Y.target,Y.value,Z.opts);if(!z.verified)process.exitCode=J.GENERIC_ERROR;console.log(JSON.stringify({filled:z.filled,verified:z.verified,target:Y.target,text:Y.value,actual:z.actual,length:z.length,matches_n:z.matches_n,match_level:z.match_level,...z.mode?{mode:z.mode}:{}},null,2))}));E(m(j.command("select")).argument("[targetOrOption]","Numeric ref/CSS target, or option text when using --role/--name/etc.").argument("[option]","Option text (or value) to select").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Select dropdown option — JSON envelope {selected, target, matches_n}")).action(D(async(q,K,X,Q)=>{const Y=await kq(q,K,X,Q??{},"option");if(!Y)return;const Z=s(Q?.nth);if("error"in Z){console.log(JSON.stringify({error:{code:"usage_error",message:Z.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{matches_n:z,match_level:U}=await F(q,Y.target,Z.opts),G=await q.evaluate(BQ(Y.value));if(G?.error){console.log(JSON.stringify({error:{code:G.error==="Not a <select>"?"not_a_select":"option_not_found",message:G.error,...G.available&&{available:G.available},matches_n:z}},null,2));process.exitCode=J.GENERIC_ERROR;return}console.log(JSON.stringify({selected:G?.selected??Y.value,target:Y.target,matches_n:z,match_level:U},null,2))}));E(j.command("keys").argument("<key>","Key to press (Enter, Escape, Tab, Control+a)")).description("Press keyboard key").action(D(async(q,K)=>{await q.pressKey(K);console.log(`Pressed: ${K}`)}));const qK=j.command("dialog").description("Handle a blocking JavaScript alert/confirm/prompt dialog");E(qK.command("accept").option("--text <text>","Prompt text to submit for prompt() dialogs").description("Accept the currently open JavaScript dialog")).action(D(async(q,K)=>{if(!q.handleJavaScriptDialog)throw Error("This browser session does not support JavaScript dialog handling");try{await q.handleJavaScriptDialog(!0,K?.text)}catch(X){if(h(X).toLowerCase().includes("no dialog")){console.log(JSON.stringify({error:{code:"no_javascript_dialog",message:"No JavaScript dialog is currently open."}},null,2));process.exitCode=J.USAGE_ERROR;return}throw X}console.log(JSON.stringify({handled:!0,action:"accept",...K?.text!==void 0&&{text:K.text}},null,2))}));E(qK.command("dismiss").description("Dismiss the currently open JavaScript dialog")).action(D(async(q)=>{if(!q.handleJavaScriptDialog)throw Error("This browser session does not support JavaScript dialog handling");try{await q.handleJavaScriptDialog(!1)}catch(K){if(h(K).toLowerCase().includes("no dialog")){console.log(JSON.stringify({error:{code:"no_javascript_dialog",message:"No JavaScript dialog is currently open."}},null,2));process.exitCode=J.USAGE_ERROR;return}throw K}console.log(JSON.stringify({handled:!0,action:"dismiss"},null,2))}));E(j.command("wait")).argument("<type>","selector, text, time, xhr, or download").argument("[value]","CSS selector, text string, seconds, XHR URL regex, or download filename/URL pattern").option("--timeout <ms>","Timeout in milliseconds","10000").description('Wait for selector, text, time, matching XHR, or browser download (e.g. wait selector ".loaded", wait text "Success", wait time 3, wait xhr "/api/search", wait download receipt.pdf)').action(D(async(q,K,X,Q)=>{const Y=parseInt(Q.timeout,10);if(K==="time"){const Z=parseFloat(X??"2");await q.wait(Z);console.log(`Waited ${Z}s`)}else if(K==="selector"){if(!X){console.error("Missing CSS selector");process.exitCode=J.USAGE_ERROR;return}await q.wait({selector:X,timeout:Y/1000});console.log(`Element "${X}" appeared`)}else if(K==="text"){if(!X){console.error("Missing text");process.exitCode=J.USAGE_ERROR;return}await q.wait({text:X,timeout:Y/1000});console.log(`Text "${X}" appeared`)}else if(K==="xhr"){if(!X){console.error("Missing XHR URL regex");process.exitCode=J.USAGE_ERROR;return}let Z;try{Z=new RegExp(X)}catch(_){console.error(`Invalid regex "${X}": ${_ instanceof Error?_.message:String(_)}`);process.exitCode=J.USAGE_ERROR;return}if(!(await q.startNetworkCapture?.()??!1))try{await q.evaluate(Xq)}catch{}await Gq(q);const U=Date.now()+Y,G=400;let W=null;while(Date.now()<U&&!W){W=(await Gq(q)).find((R)=>Z.test(R.url))??null;if(!W)await new Promise((R)=>setTimeout(R,G))}if(!W){console.log(JSON.stringify({error:{code:"xhr_not_seen",message:`No captured XHR matched /${X}/ within ${Y}ms`,hint:"Check the pattern against `browser network` output; the endpoint may not have fired yet, or capture is disabled."}},null,2));process.exitCode=J.GENERIC_ERROR;return}console.log(JSON.stringify({matched:{url:W.url,status:W.status,contentType:W.ct}},null,2))}else if(K==="download"){if(typeof q.waitForDownload!=="function"){console.log(JSON.stringify({error:{code:"download_wait_unavailable",message:"The active browser backend does not support download lifecycle waits.",hint:"Use the Browser Bridge extension version 1.0.8 or newer, then retry the command."}},null,2));process.exitCode=J.GENERIC_ERROR;return}const Z=await q.waitForDownload(String(X??""),Y);if(!Z.downloaded){const z=Z.state==="interrupted"&&Z.id!==void 0?"download_failed":"download_not_seen";console.log(JSON.stringify({error:{code:z,message:Z.error??`No download matched "${X??"*"}" within ${Y}ms`,hint:"Check the pattern against the expected filename or URL; use a longer --timeout if the download starts slowly."},download:Z},null,2));process.exitCode=J.GENERIC_ERROR;return}console.log(JSON.stringify(Z,null,2))}else{console.error(`Unknown wait type "${K}". Use: selector, text, time, xhr, or download`);process.exitCode=J.USAGE_ERROR}}));E(j.command("eval").argument("<js>","JavaScript code").option("--frame <index>",'Cross-origin iframe index from "browser frames"').description("Execute JS in page context, return result")).action(D(async(q,K,X)=>{let Q;if(X.frame!==void 0){const Y=Number.parseInt(X.frame,10);if(!Number.isInteger(Y)||Y<0){console.error(`Invalid frame index "${X.frame}". Use a 0-based index from "browser frames".`);process.exitCode=J.USAGE_ERROR;return}if(!q.evaluateInFrame)throw Error("This browser session does not support frame-targeted evaluation");Q=await q.evaluateInFrame(K,Y)}else Q=await q.evaluate(K);if(typeof Q==="string")console.log(Q);else console.log(JSON.stringify(Q,null,2))}));E(j.command("extract").option("--selector <css>","CSS selector scope; defaults to <main>/<article>/<body>").option("--chunk-size <chars>","Target chunk size in chars","20000").option("--start <char>","Start offset (use next_start_char from a previous extract)","0").description("Extract page content as markdown, paragraph-aware chunks for long pages")).action(D(async(q,K)=>{const X=String(K.chunkSize??"20000");if(!/^\d+$/.test(X)||Number.parseInt(X,10)<=0){console.log(JSON.stringify({error:{code:"invalid_chunk_size",message:`--chunk-size must be a positive integer, got "${K.chunkSize}"`}},null,2));process.exitCode=J.USAGE_ERROR;return}const Q=String(K.start??"0");if(!/^\d+$/.test(Q)){console.log(JSON.stringify({error:{code:"invalid_start",message:`--start must be a non-negative integer, got "${K.start}"`}},null,2));process.exitCode=J.USAGE_ERROR;return}const Y=Number.parseInt(X,10),Z=Number.parseInt(Q,10),z=typeof K.selector==="string"&&K.selector.length>0?K.selector:null,U=SQ(z),G=await q.evaluate(U);if(!G){console.log(JSON.stringify({error:{code:"extract_failed",message:"Page returned no root element."}},null,2));process.exitCode=J.USAGE_ERROR;return}if("invalidSelector"in G){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${z}" is not a valid CSS selector: ${G.reason}`}},null,2));process.exitCode=J.USAGE_ERROR;return}if("notFound"in G){console.log(JSON.stringify({error:{code:"selector_not_found",message:z?`Selector "${z}" matched 0 elements.`:"Page has no body/main/article element."}},null,2));process.exitCode=J.USAGE_ERROR;return}const W=bQ({html:G.html,url:G.url,title:G.title,selector:z,start:Z,chunkSize:Y});console.log(JSON.stringify(W,null,2))}));E(j.command("network")).option("--detail <key>","Emit full body for the entry with this key").option("--all","Include static resources (js/css/images/telemetry)").option("--raw","Emit full bodies for every entry (skip shape preview)").option("--filter <fields>","Comma-separated field names; keep only entries whose body shape has ALL names as path segments").option("--since <duration>","Only include entries from the last duration (for example: 30s, 2m)").option("--until <duration>","Only include entries older than the duration from now").option("--follow","Continuously print new matching entries as JSON lines",!1).option("--failed","Only include failed HTTP requests (status 0 or >= 400)",!1).option("--max-body <chars>","With --detail: cap the emitted body at N chars (0 = unlimited, default)","0").option("--ttl <ms>","Cache TTL in ms for --detail lookups",String(FK)).description("Capture network requests as shape previews; retrieve full bodies by key").action(D(async(q,K)=>{const X=yK(K.ttl,"ttl",FK),Q=iq(q),Y=typeof K.detail==="string"&&K.detail.length>0,Z=typeof K.filter==="string",z=Rq(K.since,"since"),U=Rq(K.until,"until");if(z&&typeof z==="object"){i("invalid_since",z.error);return}if(U&&typeof U==="object"){i("invalid_until",U.error);return}if(Y&&Z){i("invalid_args","--filter and --detail cannot be used together (one narrows a list, the other fetches a specific entry).");return}let G=null;if(Z){const L=kQ(K.filter);if("reason"in L){i("invalid_filter",L.reason);return}G=L.fields}if(Y&&K.follow){i("invalid_args","--follow cannot be used with --detail.");return}if(Y){const L=PQ(Q,{ttlMs:X});if(L.status==="missing"){i("cache_missing",`No cached capture. Run "browser network" first (in session "${Q}").`);return}if(L.status==="expired"){i("cache_expired",`Cache is stale (age ${L.ageMs}ms > ttl ${X}ms). Re-run "browser network" to refresh.`);return}if(L.status==="corrupt"||!L.file){i("cache_corrupt",'Cache file is malformed; re-run "browser network" to regenerate.');return}const O=EQ(L.file,K.detail);if(!O){i("key_not_found",`Key "${K.detail}" not in cache.`,{available_keys:L.file.entries.map((p)=>p.key)});return}const a=String(K.maxBody??"0");if(!/^\d+$/.test(a)){i("invalid_max_body",`--max-body must be a non-negative integer, got "${K.maxBody}"`);return}const A=Number.parseInt(a,10);let b=O.body,x=!1;if(A>0&&typeof O.body==="string"&&O.body.length>A){b=O.body.slice(0,A);x=!0}const u=O.body_truncated===!0,c={key:O.key,url:O.url,method:O.method,status:O.status,ct:O.ct,size:O.size,...typeof O.timestamp==="number"?{timestamp:Uq(O.timestamp)}:{},shape:AK(O.body),body:b};if(u||x){c.body_truncated=!0;c.body_full_size=O.body_full_size??O.size;c.body_truncation_reason=u?"capture-limit":"max-body"}console.log(JSON.stringify(c,null,2));return}if(K.follow){if(!await q.startNetworkCapture?.())try{await q.evaluate(Xq)}catch{}while(!0){const L=await Gq(q).catch((A)=>{i("capture_failed",`Could not read network capture: ${A.message}`);return[]});let O=K.all?L:OK(L);O=mq(O,{sinceMs:z,untilMs:U});if(K.failed)O=O.filter((A)=>A.status===0||A.status>=400);const a=BK(O);for(const A of a)console.log(JSON.stringify({key:A.key,timestamp:Uq(A.timestamp),method:A.method,status:A.status,url:A.url,ct:A.ct,size:A.size,...A.bodyTruncated?{body_truncated:!0}:{}}));await new Promise((A)=>setTimeout(A,PK))}}let W;try{W=await Gq(q)}catch(L){i("capture_failed",`Could not read network capture: ${L.message}`);return}let _=K.all?W:OK(W);_=mq(_,{sinceMs:z,untilMs:U});if(K.failed)_=_.filter((L)=>L.status===0||L.status>=400);const R=W.length-_.length,f=BK(_).map((L)=>({key:L.key,url:L.url,method:L.method,status:L.status,size:L.size,ct:L.ct,body:L.body,...typeof L.timestamp==="number"?{timestamp:L.timestamp}:{},...L.bodyTruncated?{body_truncated:!0}:{},...L.bodyTruncated&&typeof L.bodyFullSize==="number"?{body_full_size:L.bodyFullSize}:{}}));let y=null;try{OQ(Q,f)}catch(L){y=`Could not persist capture cache: ${L.message}. --detail lookups may miss this capture.`}const w=f.map((L)=>({entry:L,shape:AK(L.body)})),T=G?w.filter((L)=>IQ(L.shape,G)):w,d=G?w.length-T.length:0,g={session:Q,captured_at:new Date().toISOString(),count:T.length,filtered_out:R};if(G){g.filter=G;g.filter_dropped=d}if(y)g.cache_warning=y;const qq=T.filter((L)=>L.entry.body_truncated).length;if(qq>0){g.body_truncated_count=qq;g.body_truncated_hint="Some bodies exceeded the capture limit; their `shape` reflects only the captured prefix."}if(K.raw)g.entries=T.map((L)=>({...L.entry,...typeof L.entry.timestamp==="number"?{timestamp:Uq(L.entry.timestamp)}:{}}));else{g.entries=T.map((L)=>({key:L.entry.key,method:L.entry.method,...typeof L.entry.timestamp==="number"?{timestamp:Uq(L.entry.timestamp)}:{},status:L.entry.status,url:L.entry.url,ct:L.entry.ct,size:L.entry.size,shape:L.shape,...L.entry.body_truncated?{body_truncated:!0}:{}}));g.detail_hint='Run "browser network --detail <key>" for full body.'}console.log(JSON.stringify(g,null,2))}));j.command("init").argument("<name>","Adapter name in site/command format (e.g. hn/top)").description("Generate adapter scaffold in ~/.opencli/clis/").action(async(q)=>{try{const K=q.split("/");if(K.length!==2||!K[0]||!K[1]){console.error("Name must be site/command format (e.g. hn/top)");process.exitCode=J.USAGE_ERROR;return}const[X,Q]=K;if(!/^[a-zA-Z0-9_-]+$/.test(X)||!/^[a-zA-Z0-9_-]+$/.test(Q)){console.error("Name parts must be alphanumeric/dash/underscore only");process.exitCode=J.USAGE_ERROR;return}const Y=await import("node:os"),Z=await import("node:fs"),z=await import("node:path"),U=z.join(Y.homedir(),".opencli","clis",X),G=z.join(U,`${Q}.js`);if(Z.existsSync(G)){console.log(`Adapter already exists: ${G}`);return}const _=`import { cli, Strategy } from '@jackwener/opencli/registry';
|
|
95
|
+
})()`);if(z.kind==="invalid_selector"){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${K.selector}" is not a valid CSS selector: ${z.reason}`}},null,2));process.exitCode=J.USAGE_ERROR;return}const U=z.html;if(U===null){if(K.selector){console.log(JSON.stringify({error:{code:"selector_not_found",message:`Selector "${K.selector}" matched 0 elements.`}},null,2));process.exitCode=J.USAGE_ERROR;return}console.log("(empty)");return}if(Y>0&&U.length>Y){console.log(`<!-- ppcli: truncated ${Y} of ${U.length} chars; re-run without --max (or --max 0) for full -->
|
|
96
|
+
${U.slice(0,Y)}`);return}console.log(U)}));E(m($q.command("attributes")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","Pick the nth match (0-based) when <target> is a multi-match CSS selector").description("Element attributes — JSON envelope {value, matches_n}")).action(D(async(q,K,X)=>Iq(q,K,X??{},AQ(),"attributes")));function s(q){const K=P(q);if(K&&typeof K==="object"&&"error"in K)return K;if(typeof K==="number")return{opts:{nth:K}};return{opts:{}}}function cK(q){const K=Array.isArray(q)?q:[];if(K.length===0)return{error:{code:"usage_error",message:"At least one file path is required.",hint:'Example: ppcli browser upload "input[type=file]" ./receipt.pdf'}};const X=[];for(const Q of K){const Y=String(Q),Z=Y==="~"||Y.startsWith(`~${M.sep}`)?M.join(zq.homedir(),Y.slice(2)):Y,z=M.resolve(Z);if(!I.existsSync(z))return{error:{code:"file_not_found",message:`File not found: ${z}`}};if(!I.statSync(z).isFile())return{error:{code:"not_a_file",message:`Not a regular file: ${z}`}};X.push(z)}return{files:X}}function tq(q,K){const X=P(q);if(X&&typeof X==="object"&&"error"in X)return{error:X.error.replace("--nth",K)};if(typeof X==="number")return{opts:{nth:X}};return{opts:{}}}E(m(j.command("click")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Click element — JSON envelope {clicked, target, matches_n}")).action(D(async(q,K,X)=>{const Q=await Oq(q,K,X??{},"write");if(typeof Q!=="string"){console.log(JSON.stringify(Q,null,2));process.exitCode=J.USAGE_ERROR;return}const Y=s(X?.nth);if("error"in Y){console.log(JSON.stringify({error:{code:"usage_error",message:Y.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{matches_n:Z,match_level:z}=await q.click(Q,Y.opts);console.log(JSON.stringify({clicked:!0,target:Q,matches_n:Z,match_level:z},null,2))}));E(m(j.command("type")).argument("[targetOrText]","Numeric ref/CSS target, or text when using --role/--name/etc.").argument("[text]","Text to type").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Click element, then type text — JSON envelope {typed, text, target, matches_n, autocomplete}")).action(D(async(q,K,X,Q)=>{const Y=await kq(q,K,X,Q??{},"text");if(!Y)return;const Z=s(Q?.nth);if("error"in Z){console.log(JSON.stringify({error:{code:"usage_error",message:Z.error}},null,2));process.exitCode=J.USAGE_ERROR;return}await q.click(Y.target,Z.opts);await q.wait(0.3);const{matches_n:z,match_level:U}=await q.typeText(Y.target,Y.value,Z.opts),G=await q.evaluate(FQ());if(G)await q.wait(0.4);console.log(JSON.stringify({typed:!0,text:Y.value,target:Y.target,matches_n:z,match_level:U,autocomplete:!!G},null,2))}));E(m(j.command("hover")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Move the mouse over an element — JSON envelope {hovered, target, matches_n}")).action(D(async(q,K,X)=>{if(typeof q.hover!=="function")throw Error("browser hover is not supported by this browser backend");const Q=await Zq(q,K,X??{});if(!Q)return;const Y=s(X?.nth);if("error"in Y){console.log(JSON.stringify({error:{code:"usage_error",message:Y.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{matches_n:Z,match_level:z}=await q.hover(Q,Y.opts);console.log(JSON.stringify({hovered:!0,target:Q,matches_n:Z,match_level:z},null,2))}));E(m(j.command("focus")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Focus an element — JSON envelope {focused, target, matches_n}")).action(D(async(q,K,X)=>{if(typeof q.focus!=="function")throw Error("browser focus is not supported by this browser backend");const Q=await Zq(q,K,X??{});if(!Q)return;const Y=s(X?.nth);if("error"in Y){console.log(JSON.stringify({error:{code:"usage_error",message:Y.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{focused:Z,matches_n:z,match_level:U}=await q.focus(Q,Y.opts);console.log(JSON.stringify({focused:Z,target:Q,matches_n:z,match_level:U},null,2))}));E(m(j.command("dblclick")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Double-click element — JSON envelope {dblclicked, target, matches_n}")).action(D(async(q,K,X)=>{if(typeof q.dblClick!=="function")throw Error("browser dblclick is not supported by this browser backend");const Q=await Zq(q,K,X??{});if(!Q)return;const Y=s(X?.nth);if("error"in Y){console.log(JSON.stringify({error:{code:"usage_error",message:Y.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{matches_n:Z,match_level:z}=await q.dblClick(Q,Y.opts);console.log(JSON.stringify({dblclicked:!0,target:Q,matches_n:Z,match_level:z},null,2))}));const eq=async(q,K,X,Q)=>{if(typeof q.setChecked!=="function")throw Error(`browser ${Q?"check":"uncheck"} is not supported by this browser backend`);const Y=await Zq(q,K,X);if(!Y)return;const Z=s(X?.nth);if("error"in Z){console.log(JSON.stringify({error:{code:"usage_error",message:Z.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const z=await q.setChecked(Y,Q,Z.opts);console.log(JSON.stringify({checked:z.checked,changed:z.changed,target:Y,matches_n:z.matches_n,match_level:z.match_level,...z.kind?{kind:z.kind}:{}},null,2))};E(m(j.command("check")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Ensure a checkbox/radio/aria-checked control is checked — JSON envelope {checked, changed, target, matches_n}")).action(D(async(q,K,X)=>{await eq(q,K,X??{},!0)}));E(m(j.command("uncheck")).argument("[target]","Numeric ref (from browser state / find), CSS selector, or omit when using --role/--name/etc.").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Ensure a checkbox/aria-checked control is unchecked — JSON envelope {checked, changed, target, matches_n}")).action(D(async(q,K,X)=>{await eq(q,K,X??{},!1)}));E(m(j.command("upload")).argument("[targetOrFile]","Numeric ref/CSS target, or first file when using --role/--name/etc.").argument("[files...]","Local file path(s) to attach").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Attach local files to a file input — JSON envelope {uploaded, files, file_names, target, matches_n}")).action(D(async(q,K,X,Q)=>{if(typeof q.uploadFiles!=="function")throw Error("browser upload is not supported by this browser backend");const Y=!!Vq(Q??{}),z=await Zq(q,Y?void 0:K,Q??{});if(!z)return;const U=s(Q?.nth);if("error"in U){console.log(JSON.stringify({error:{code:"usage_error",message:U.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const G=Y?[K,...Array.isArray(X)?X:[]].filter((R)=>R!==void 0):X,W=cK(G);if("error"in W){console.log(JSON.stringify({error:W.error},null,2));process.exitCode=J.USAGE_ERROR;return}const _=await q.uploadFiles(z,W.files,U.opts);console.log(JSON.stringify(_,null,2))}));E(aq(aq(j.command("drag"),"from"),"to").argument("[source]","Numeric ref/CSS selector to drag from, or omit with --from-role/--from-name/etc.").argument("[target]","Numeric ref/CSS selector to drop onto, or omit with --to-role/--to-name/etc.").option("--from-nth <n>","When <source> is a multi-match CSS selector, pick the nth match (0-based)").option("--to-nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Drag one element to another — JSON envelope {dragged, source, target, source_matches_n, target_matches_n}")).action(D(async(q,K,X,Q)=>{if(typeof q.drag!=="function")throw Error("browser drag is not supported by this browser backend");const Y=await sq(q,K,Q??{},"from","source");if(!Y)return;const Z=await sq(q,X,Q??{},"to","target");if(!Z)return;const z=tq(Q?.fromNth,"--from-nth");if("error"in z){console.log(JSON.stringify({error:{code:"usage_error",message:z.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const U=tq(Q?.toNth,"--to-nth");if("error"in U){console.log(JSON.stringify({error:{code:"usage_error",message:U.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const G=await q.drag(Y,Z,{from:z.opts,to:U.opts});console.log(JSON.stringify(G,null,2))}));E(m(j.command("fill")).argument("[targetOrText]","Numeric ref/CSS target, or text when using --role/--name/etc.").argument("[text]","Text to set exactly").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Set input/textarea/contenteditable text exactly and verify the value — JSON envelope {filled, verified, text, actual}")).action(D(async(q,K,X,Q)=>{const Y=await kq(q,K,X,Q??{},"text");if(!Y)return;const Z=s(Q?.nth);if("error"in Z){console.log(JSON.stringify({error:{code:"usage_error",message:Z.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const z=await q.fillText(Y.target,Y.value,Z.opts);if(!z.verified)process.exitCode=J.GENERIC_ERROR;console.log(JSON.stringify({filled:z.filled,verified:z.verified,target:Y.target,text:Y.value,actual:z.actual,length:z.length,matches_n:z.matches_n,match_level:z.match_level,...z.mode?{mode:z.mode}:{}},null,2))}));E(m(j.command("select")).argument("[targetOrOption]","Numeric ref/CSS target, or option text when using --role/--name/etc.").argument("[option]","Option text (or value) to select").option("--nth <n>","When <target> is a multi-match CSS selector, pick the nth match (0-based)").description("Select dropdown option — JSON envelope {selected, target, matches_n}")).action(D(async(q,K,X,Q)=>{const Y=await kq(q,K,X,Q??{},"option");if(!Y)return;const Z=s(Q?.nth);if("error"in Z){console.log(JSON.stringify({error:{code:"usage_error",message:Z.error}},null,2));process.exitCode=J.USAGE_ERROR;return}const{matches_n:z,match_level:U}=await F(q,Y.target,Z.opts),G=await q.evaluate(BQ(Y.value));if(G?.error){console.log(JSON.stringify({error:{code:G.error==="Not a <select>"?"not_a_select":"option_not_found",message:G.error,...G.available&&{available:G.available},matches_n:z}},null,2));process.exitCode=J.GENERIC_ERROR;return}console.log(JSON.stringify({selected:G?.selected??Y.value,target:Y.target,matches_n:z,match_level:U},null,2))}));E(j.command("keys").argument("<key>","Key to press (Enter, Escape, Tab, Control+a)")).description("Press keyboard key").action(D(async(q,K)=>{await q.pressKey(K);console.log(`Pressed: ${K}`)}));const qK=j.command("dialog").description("Handle a blocking JavaScript alert/confirm/prompt dialog");E(qK.command("accept").option("--text <text>","Prompt text to submit for prompt() dialogs").description("Accept the currently open JavaScript dialog")).action(D(async(q,K)=>{if(!q.handleJavaScriptDialog)throw Error("This browser session does not support JavaScript dialog handling");try{await q.handleJavaScriptDialog(!0,K?.text)}catch(X){if(h(X).toLowerCase().includes("no dialog")){console.log(JSON.stringify({error:{code:"no_javascript_dialog",message:"No JavaScript dialog is currently open."}},null,2));process.exitCode=J.USAGE_ERROR;return}throw X}console.log(JSON.stringify({handled:!0,action:"accept",...K?.text!==void 0&&{text:K.text}},null,2))}));E(qK.command("dismiss").description("Dismiss the currently open JavaScript dialog")).action(D(async(q)=>{if(!q.handleJavaScriptDialog)throw Error("This browser session does not support JavaScript dialog handling");try{await q.handleJavaScriptDialog(!1)}catch(K){if(h(K).toLowerCase().includes("no dialog")){console.log(JSON.stringify({error:{code:"no_javascript_dialog",message:"No JavaScript dialog is currently open."}},null,2));process.exitCode=J.USAGE_ERROR;return}throw K}console.log(JSON.stringify({handled:!0,action:"dismiss"},null,2))}));E(j.command("wait")).argument("<type>","selector, text, time, xhr, or download").argument("[value]","CSS selector, text string, seconds, XHR URL regex, or download filename/URL pattern").option("--timeout <ms>","Timeout in milliseconds","10000").description('Wait for selector, text, time, matching XHR, or browser download (e.g. wait selector ".loaded", wait text "Success", wait time 3, wait xhr "/api/search", wait download receipt.pdf)').action(D(async(q,K,X,Q)=>{const Y=parseInt(Q.timeout,10);if(K==="time"){const Z=parseFloat(X??"2");await q.wait(Z);console.log(`Waited ${Z}s`)}else if(K==="selector"){if(!X){console.error("Missing CSS selector");process.exitCode=J.USAGE_ERROR;return}await q.wait({selector:X,timeout:Y/1000});console.log(`Element "${X}" appeared`)}else if(K==="text"){if(!X){console.error("Missing text");process.exitCode=J.USAGE_ERROR;return}await q.wait({text:X,timeout:Y/1000});console.log(`Text "${X}" appeared`)}else if(K==="xhr"){if(!X){console.error("Missing XHR URL regex");process.exitCode=J.USAGE_ERROR;return}let Z;try{Z=new RegExp(X)}catch(_){console.error(`Invalid regex "${X}": ${_ instanceof Error?_.message:String(_)}`);process.exitCode=J.USAGE_ERROR;return}if(!(await q.startNetworkCapture?.()??!1))try{await q.evaluate(Xq)}catch{}await Gq(q);const U=Date.now()+Y,G=400;let W=null;while(Date.now()<U&&!W){W=(await Gq(q)).find((R)=>Z.test(R.url))??null;if(!W)await new Promise((R)=>setTimeout(R,G))}if(!W){console.log(JSON.stringify({error:{code:"xhr_not_seen",message:`No captured XHR matched /${X}/ within ${Y}ms`,hint:"Check the pattern against `browser network` output; the endpoint may not have fired yet, or capture is disabled."}},null,2));process.exitCode=J.GENERIC_ERROR;return}console.log(JSON.stringify({matched:{url:W.url,status:W.status,contentType:W.ct}},null,2))}else if(K==="download"){if(typeof q.waitForDownload!=="function"){console.log(JSON.stringify({error:{code:"download_wait_unavailable",message:"The active browser backend does not support download lifecycle waits.",hint:"Use the Browser Bridge extension version 1.0.8 or newer, then retry the command."}},null,2));process.exitCode=J.GENERIC_ERROR;return}const Z=await q.waitForDownload(String(X??""),Y);if(!Z.downloaded){const z=Z.state==="interrupted"&&Z.id!==void 0?"download_failed":"download_not_seen";console.log(JSON.stringify({error:{code:z,message:Z.error??`No download matched "${X??"*"}" within ${Y}ms`,hint:"Check the pattern against the expected filename or URL; use a longer --timeout if the download starts slowly."},download:Z},null,2));process.exitCode=J.GENERIC_ERROR;return}console.log(JSON.stringify(Z,null,2))}else{console.error(`Unknown wait type "${K}". Use: selector, text, time, xhr, or download`);process.exitCode=J.USAGE_ERROR}}));E(j.command("eval").argument("<js>","JavaScript code").option("--frame <index>",'Cross-origin iframe index from "browser frames"').description("Execute JS in page context, return result")).action(D(async(q,K,X)=>{let Q;if(X.frame!==void 0){const Y=Number.parseInt(X.frame,10);if(!Number.isInteger(Y)||Y<0){console.error(`Invalid frame index "${X.frame}". Use a 0-based index from "browser frames".`);process.exitCode=J.USAGE_ERROR;return}if(!q.evaluateInFrame)throw Error("This browser session does not support frame-targeted evaluation");Q=await q.evaluateInFrame(K,Y)}else Q=await q.evaluate(K);if(typeof Q==="string")console.log(Q);else console.log(JSON.stringify(Q,null,2))}));E(j.command("extract").option("--selector <css>","CSS selector scope; defaults to <main>/<article>/<body>").option("--chunk-size <chars>","Target chunk size in chars","20000").option("--start <char>","Start offset (use next_start_char from a previous extract)","0").description("Extract page content as markdown, paragraph-aware chunks for long pages")).action(D(async(q,K)=>{const X=String(K.chunkSize??"20000");if(!/^\d+$/.test(X)||Number.parseInt(X,10)<=0){console.log(JSON.stringify({error:{code:"invalid_chunk_size",message:`--chunk-size must be a positive integer, got "${K.chunkSize}"`}},null,2));process.exitCode=J.USAGE_ERROR;return}const Q=String(K.start??"0");if(!/^\d+$/.test(Q)){console.log(JSON.stringify({error:{code:"invalid_start",message:`--start must be a non-negative integer, got "${K.start}"`}},null,2));process.exitCode=J.USAGE_ERROR;return}const Y=Number.parseInt(X,10),Z=Number.parseInt(Q,10),z=typeof K.selector==="string"&&K.selector.length>0?K.selector:null,U=SQ(z),G=await q.evaluate(U);if(!G){console.log(JSON.stringify({error:{code:"extract_failed",message:"Page returned no root element."}},null,2));process.exitCode=J.USAGE_ERROR;return}if("invalidSelector"in G){console.log(JSON.stringify({error:{code:"invalid_selector",message:`Selector "${z}" is not a valid CSS selector: ${G.reason}`}},null,2));process.exitCode=J.USAGE_ERROR;return}if("notFound"in G){console.log(JSON.stringify({error:{code:"selector_not_found",message:z?`Selector "${z}" matched 0 elements.`:"Page has no body/main/article element."}},null,2));process.exitCode=J.USAGE_ERROR;return}const W=bQ({html:G.html,url:G.url,title:G.title,selector:z,start:Z,chunkSize:Y});console.log(JSON.stringify(W,null,2))}));E(j.command("network")).option("--detail <key>","Emit full body for the entry with this key").option("--all","Include static resources (js/css/images/telemetry)").option("--raw","Emit full bodies for every entry (skip shape preview)").option("--filter <fields>","Comma-separated field names; keep only entries whose body shape has ALL names as path segments").option("--since <duration>","Only include entries from the last duration (for example: 30s, 2m)").option("--until <duration>","Only include entries older than the duration from now").option("--follow","Continuously print new matching entries as JSON lines",!1).option("--failed","Only include failed HTTP requests (status 0 or >= 400)",!1).option("--max-body <chars>","With --detail: cap the emitted body at N chars (0 = unlimited, default)","0").option("--ttl <ms>","Cache TTL in ms for --detail lookups",String(FK)).description("Capture network requests as shape previews; retrieve full bodies by key").action(D(async(q,K)=>{const X=yK(K.ttl,"ttl",FK),Q=iq(q),Y=typeof K.detail==="string"&&K.detail.length>0,Z=typeof K.filter==="string",z=Rq(K.since,"since"),U=Rq(K.until,"until");if(z&&typeof z==="object"){i("invalid_since",z.error);return}if(U&&typeof U==="object"){i("invalid_until",U.error);return}if(Y&&Z){i("invalid_args","--filter and --detail cannot be used together (one narrows a list, the other fetches a specific entry).");return}let G=null;if(Z){const L=kQ(K.filter);if("reason"in L){i("invalid_filter",L.reason);return}G=L.fields}if(Y&&K.follow){i("invalid_args","--follow cannot be used with --detail.");return}if(Y){const L=PQ(Q,{ttlMs:X});if(L.status==="missing"){i("cache_missing",`No cached capture. Run "browser network" first (in session "${Q}").`);return}if(L.status==="expired"){i("cache_expired",`Cache is stale (age ${L.ageMs}ms > ttl ${X}ms). Re-run "browser network" to refresh.`);return}if(L.status==="corrupt"||!L.file){i("cache_corrupt",'Cache file is malformed; re-run "browser network" to regenerate.');return}const O=EQ(L.file,K.detail);if(!O){i("key_not_found",`Key "${K.detail}" not in cache.`,{available_keys:L.file.entries.map((p)=>p.key)});return}const a=String(K.maxBody??"0");if(!/^\d+$/.test(a)){i("invalid_max_body",`--max-body must be a non-negative integer, got "${K.maxBody}"`);return}const A=Number.parseInt(a,10);let b=O.body,x=!1;if(A>0&&typeof O.body==="string"&&O.body.length>A){b=O.body.slice(0,A);x=!0}const u=O.body_truncated===!0,c={key:O.key,url:O.url,method:O.method,status:O.status,ct:O.ct,size:O.size,...typeof O.timestamp==="number"?{timestamp:Uq(O.timestamp)}:{},shape:AK(O.body),body:b};if(u||x){c.body_truncated=!0;c.body_full_size=O.body_full_size??O.size;c.body_truncation_reason=u?"capture-limit":"max-body"}console.log(JSON.stringify(c,null,2));return}if(K.follow){if(!await q.startNetworkCapture?.())try{await q.evaluate(Xq)}catch{}while(!0){const L=await Gq(q).catch((A)=>{i("capture_failed",`Could not read network capture: ${A.message}`);return[]});let O=K.all?L:OK(L);O=mq(O,{sinceMs:z,untilMs:U});if(K.failed)O=O.filter((A)=>A.status===0||A.status>=400);const a=BK(O);for(const A of a)console.log(JSON.stringify({key:A.key,timestamp:Uq(A.timestamp),method:A.method,status:A.status,url:A.url,ct:A.ct,size:A.size,...A.bodyTruncated?{body_truncated:!0}:{}}));await new Promise((A)=>setTimeout(A,PK))}}let W;try{W=await Gq(q)}catch(L){i("capture_failed",`Could not read network capture: ${L.message}`);return}let _=K.all?W:OK(W);_=mq(_,{sinceMs:z,untilMs:U});if(K.failed)_=_.filter((L)=>L.status===0||L.status>=400);const R=W.length-_.length,f=BK(_).map((L)=>({key:L.key,url:L.url,method:L.method,status:L.status,size:L.size,ct:L.ct,body:L.body,...typeof L.timestamp==="number"?{timestamp:L.timestamp}:{},...L.bodyTruncated?{body_truncated:!0}:{},...L.bodyTruncated&&typeof L.bodyFullSize==="number"?{body_full_size:L.bodyFullSize}:{}}));let y=null;try{OQ(Q,f)}catch(L){y=`Could not persist capture cache: ${L.message}. --detail lookups may miss this capture.`}const w=f.map((L)=>({entry:L,shape:AK(L.body)})),T=G?w.filter((L)=>IQ(L.shape,G)):w,d=G?w.length-T.length:0,g={session:Q,captured_at:new Date().toISOString(),count:T.length,filtered_out:R};if(G){g.filter=G;g.filter_dropped=d}if(y)g.cache_warning=y;const qq=T.filter((L)=>L.entry.body_truncated).length;if(qq>0){g.body_truncated_count=qq;g.body_truncated_hint="Some bodies exceeded the capture limit; their `shape` reflects only the captured prefix."}if(K.raw)g.entries=T.map((L)=>({...L.entry,...typeof L.entry.timestamp==="number"?{timestamp:Uq(L.entry.timestamp)}:{}}));else{g.entries=T.map((L)=>({key:L.entry.key,method:L.entry.method,...typeof L.entry.timestamp==="number"?{timestamp:Uq(L.entry.timestamp)}:{},status:L.entry.status,url:L.entry.url,ct:L.entry.ct,size:L.entry.size,shape:L.shape,...L.entry.body_truncated?{body_truncated:!0}:{}}));g.detail_hint='Run "browser network --detail <key>" for full body.'}console.log(JSON.stringify(g,null,2))}));j.command("init").argument("<name>","Adapter name in site/command format (e.g. hn/top)").description("Generate adapter scaffold in ~/.ppcli/clis/").action(async(q)=>{try{const K=q.split("/");if(K.length!==2||!K[0]||!K[1]){console.error("Name must be site/command format (e.g. hn/top)");process.exitCode=J.USAGE_ERROR;return}const[X,Q]=K;if(!/^[a-zA-Z0-9_-]+$/.test(X)||!/^[a-zA-Z0-9_-]+$/.test(Q)){console.error("Name parts must be alphanumeric/dash/underscore only");process.exitCode=J.USAGE_ERROR;return}const Y=await import("node:os"),Z=await import("node:fs"),z=await import("node:path"),U=z.join(Y.homedir(),".ppcli","clis",X),G=z.join(U,`${Q}.js`);if(Z.existsSync(G)){console.log(`Adapter already exists: ${G}`);return}const _=`import { cli, Strategy } from '@jackwener/opencli/registry';
|
|
97
97
|
|
|
98
98
|
cli({
|
|
99
99
|
site: '${X}',
|
|
100
100
|
name: '${Q}',
|
|
101
101
|
description: '', // TODO: describe what this command does
|
|
102
102
|
access: 'read', // TODO: 'read' for queries, 'write' for remote/account state changes
|
|
103
|
-
example: '
|
|
103
|
+
example: 'ppcli ${X} ${Q} -f yaml',
|
|
104
104
|
domain: '${X}',
|
|
105
105
|
strategy: Strategy.PUBLIC, // TODO: PUBLIC (no auth), COOKIE (needs login), UI (DOM interaction)
|
|
106
106
|
browser: false, // TODO: set true if needs browser
|
|
@@ -115,10 +115,10 @@ cli({
|
|
|
115
115
|
return [];
|
|
116
116
|
},
|
|
117
117
|
});
|
|
118
|
-
`;Z.mkdirSync(U,{recursive:!0});Z.writeFileSync(G,_,"utf-8");console.log(`Created: ${G}`);console.log("First time on this site? Run:
|
|
119
|
-
`);console.log(` Loading: ${y}`);let T=K.fixture!==!1?z(Q,Y):null;const d=I.readFileSync(y,"utf-8"),g=/['"]limit['"]/.test(d),qq=f(K.seedArgs),L=T?.args??qq,O=k(L);if(L===void 0&&O.length===0&&g)O.push("--limit","3");const a=K.trace&&K.trace!=="off"?["--trace",K.trace]:[],A=[...O,...a].join(" "),b=resolveBrowserVerifyInvocation(),x=[...b.args,Q,Y,...O,...a,"--format","json"];let u;try{u=Z(b.binary,x,{cwd:b.cwd,timeout:30000,encoding:"utf-8",env:process.env,stdio:["pipe","pipe","pipe"],...b.shell?{shell:!0}:{}})}catch(C){console.log(` Executing:
|
|
118
|
+
`;Z.mkdirSync(U,{recursive:!0});Z.writeFileSync(G,_,"utf-8");console.log(`Created: ${G}`);console.log("First time on this site? Run: ppcli browser analyze <url>");console.log(`Edit the file to implement your adapter, then run: ppcli browser verify ${q}`)}catch(K){console.error(`Error: ${K instanceof Error?K.message:String(K)}`);process.exitCode=J.GENERIC_ERROR}});j.command("verify").argument("<name>","Adapter name in site/command format (e.g. hn/top)").option("--write-fixture","Write a starter fixture to ~/.ppcli/sites/<site>/verify/<command>.json if none exists").option("--update-fixture","Overwrite an existing fixture with one derived from current output").option("--no-fixture","Ignore any fixture file for this run (no value-level validation)").option("--strict-memory","Fail (not just warn) when ~/.ppcli/sites/<site>/endpoints.json or notes.md is missing").option("--seed-args <value>","Seed args when no fixture exists; use JSON array/object for multiple args or flags").option("--trace <mode>","Trace capture for the adapter subprocess: off, on, retain-on-failure","off").description("Execute an adapter and validate output; uses fixture at ~/.ppcli/sites/<site>/verify/<cmd>.json when present").action(async(q,K={})=>{try{const X=q.split("/");if(X.length!==2){console.error("Name must be site/command format");process.exitCode=J.USAGE_ERROR;return}const[Q,Y]=X;if(!/^[a-zA-Z0-9_-]+$/.test(Q)||!/^[a-zA-Z0-9_-]+$/.test(Y)){console.error("Name parts must be alphanumeric/dash/underscore only");process.exitCode=J.USAGE_ERROR;return}const{execFileSync:Z}=await import("node:child_process"),{loadFixture:z,writeFixture:U,deriveFixture:G,validateRows:W,validateRowShape:_,fixturePath:R,expandFixtureArgs:k,parseSeedArgs:f}=await import("./browser/verify-fixture.js"),y=M.join(zq.homedir(),".ppcli","clis",Q,`${Y}.js`);if(!I.existsSync(y)){console.error(`Adapter not found: ${y}`);console.error(`Run "ppcli browser init ${q}" to create it.`);process.exitCode=J.GENERIC_ERROR;return}console.log(`\uD83D\uDD0D Verifying ${q}...
|
|
119
|
+
`);console.log(` Loading: ${y}`);let T=K.fixture!==!1?z(Q,Y):null;const d=I.readFileSync(y,"utf-8"),g=/['"]limit['"]/.test(d),qq=f(K.seedArgs),L=T?.args??qq,O=k(L);if(L===void 0&&O.length===0&&g)O.push("--limit","3");const a=K.trace&&K.trace!=="off"?["--trace",K.trace]:[],A=[...O,...a].join(" "),b=resolveBrowserVerifyInvocation(),x=[...b.args,Q,Y,...O,...a,"--format","json"];let u;try{u=Z(b.binary,x,{cwd:b.cwd,timeout:30000,encoding:"utf-8",env:process.env,stdio:["pipe","pipe","pipe"],...b.shell?{shell:!0}:{}})}catch(C){console.log(` Executing: ppcli ${Q} ${Y} ${A}
|
|
120
120
|
`);const l=C;if(l.stdout)console.log(String(l.stdout));if(l.stderr)console.error(String(l.stderr).slice(0,500));console.log(`
|
|
121
|
-
✗ Adapter failed. Fix the code and try again.`);process.exitCode=J.GENERIC_ERROR;return}console.log(` Executing:
|
|
121
|
+
✗ Adapter failed. Fix the code and try again.`);process.exitCode=J.GENERIC_ERROR;return}console.log(` Executing: ppcli ${Q} ${Y} ${A}
|
|
122
122
|
`);let c;try{c=normalizeVerifyRows(JSON.parse(u))}catch{console.log(u);console.log("\n ✗ Could not parse adapter output as JSON. Is `--format json` broken?");process.exitCode=J.GENERIC_ERROR;return}console.log(renderVerifyPreview(c));console.log(`
|
|
123
123
|
→ ${c.length} row${c.length===1?"":"s"}`);const p=_(c);if(p.length>0){console.log(`
|
|
124
124
|
✗ Adapter output violates row shape conventions:`);for(const C of p.slice(0,20)){const l=C.rowIndex!==void 0?`row[${C.rowIndex}] `:"";console.log(` - [${C.rule}] ${l}${C.detail}`)}if(p.length>20)console.log(` ... and ${p.length-20} more failure(s)`);console.log(`
|
|
@@ -127,6 +127,6 @@ cli({
|
|
|
127
127
|
${T?"↻ Updated":"✎ Wrote"} fixture: ${bq}`);console.log(" Review and hand-tune the derived expectations (add patterns / notEmpty, tighten rowCount).");T=l}if(!T){console.log(`
|
|
128
128
|
✓ Adapter runs. (No fixture at ${R(Q,Y)} — consider --write-fixture to seed one.)`);const C=checkSiteMemory(Q);printSiteMemoryReport(C,K.strictMemory);if(!C.ok&&K.strictMemory)process.exitCode=J.GENERIC_ERROR;return}const t=W(c,T);if(t.length===0){console.log(`
|
|
129
129
|
✓ Adapter matches fixture (${R(Q,Y)}).`);const C=checkSiteMemory(Q);printSiteMemoryReport(C,K.strictMemory);if(!C.ok&&K.strictMemory)process.exitCode=J.GENERIC_ERROR;return}console.log(`
|
|
130
|
-
✗ Adapter output does not match fixture:`);for(const C of t.slice(0,20)){const l=C.rowIndex!==void 0?`row[${C.rowIndex}] `:"";console.log(` - [${C.rule}] ${l}${C.detail}`)}if(t.length>20)console.log(` ... and ${t.length-20} more failure(s)`);process.exitCode=J.GENERIC_ERROR}catch(X){console.error(`Error: ${X instanceof Error?X.message:String(X)}`);process.exitCode=J.GENERIC_ERROR}});j.command("close").description("Release the current browser session tab lease").action(D(async(q)=>{await q.closeWindow?.();console.log("Browser session tab lease released")}));$.command("doctor").description("Diagnose
|
|
130
|
+
✗ Adapter output does not match fixture:`);for(const C of t.slice(0,20)){const l=C.rowIndex!==void 0?`row[${C.rowIndex}] `:"";console.log(` - [${C.rule}] ${l}${C.detail}`)}if(t.length>20)console.log(` ... and ${t.length-20} more failure(s)`);process.exitCode=J.GENERIC_ERROR}catch(X){console.error(`Error: ${X instanceof Error?X.message:String(X)}`);process.exitCode=J.GENERIC_ERROR}});j.command("close").description("Release the current browser session tab lease").action(D(async(q)=>{await q.closeWindow?.();console.log("Browser session tab lease released")}));$.command("doctor").description("Diagnose ppcli browser bridge connectivity").option("-v, --verbose","Debug output").action(async(q)=>{GX(q);const{runBrowserDoctor:K,renderBrowserDoctorReport:X}=await import("./doctor.js"),Q=await K({cliVersion:Fq});console.log(X(Q))});$.command("completion").description("Output shell completion script").argument("<shell>","Shell type: bash, zsh, or fish").action((q)=>{XQ(q)});const Qq=$.command("plugin").description("Manage ppcli plugins"),mK=Qq.description();Qq.command("install").description("Install a plugin from a git repository").argument("<source>","Plugin source (e.g. github:user/repo)").action(async(q)=>{const{installPlugin:K}=await import("./plugin.js"),{discoverPlugins:X}=await import("./discovery.js");try{const Q=K(q);await X();if(Array.isArray(Q))if(Q.length===0)console.log("No plugins were installed (all skipped or incompatible).");else console.log(`✅ Installed ${Q.length} plugin(s) from monorepo: ${Q.join(", ")}`);else console.log(`✅ Plugin "${Q}" installed successfully. Commands are ready to use.`)}catch(Q){console.error(`Error: ${h(Q)}`);process.exitCode=J.GENERIC_ERROR}});Qq.command("uninstall").description("Uninstall a plugin").argument("<name>","Plugin name").action(async(q)=>{const{uninstallPlugin:K}=await import("./plugin.js");try{K(q);console.log(`✅ Plugin "${q}" uninstalled.`)}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.GENERIC_ERROR}});Qq.command("update").description("Update a plugin (or all plugins) to the latest version").argument("[name]","Plugin name (required unless --all is passed)").option("--all","Update all installed plugins").action(async(q,K)=>{if(!q&&!K.all){console.error("Error: Please specify a plugin name or use the --all flag.");process.exitCode=J.USAGE_ERROR;return}if(q&&K.all){console.error("Error: Cannot specify both a plugin name and --all.");process.exitCode=J.USAGE_ERROR;return}const{updatePlugin:X,updateAllPlugins:Q}=await import("./plugin.js"),{discoverPlugins:Y}=await import("./discovery.js");if(K.all){const Z=Q();if(Z.length>0)await Y();let z=!1;console.log(" Update Results:");for(const U of Z){if(U.success){console.log(` ✓ ${U.name}`);continue}z=!0;console.log(` ✗ ${U.name} — ${String(U.error)}`)}if(Z.length===0){console.log(" No plugins installed.");return}console.log();if(z){console.error("Completed with some errors.");process.exitCode=J.GENERIC_ERROR}else console.log("✅ All plugins updated successfully.");return}try{X(q);await Y();console.log(`✅ Plugin "${q}" updated successfully.`)}catch(Z){console.error(`Error: ${h(Z)}`);process.exitCode=J.GENERIC_ERROR}});Qq.command("list").description("List installed plugins").option("-f, --format <fmt>","Output format: table, json","table").action(async(q)=>{const{listPlugins:K}=await import("./plugin.js"),X=K();if(X.length===0){console.log(" No plugins installed.");console.log(" Install one with: ppcli plugin install github:user/repo");return}if(q.format==="json"){Aq(X,{fmt:"json",columns:["name","commands","source"],title:"ppcli/plugins",source:"ppcli plugin list"});return}console.log();console.log(" Installed plugins");console.log();const Q=X.filter((Z)=>!Z.monorepoName),Y=new Map;for(const Z of X){if(!Z.monorepoName)continue;const z=Y.get(Z.monorepoName)??[];z.push(Z);Y.set(Z.monorepoName,z)}for(const Z of Q){const z=Z.version?` @${Z.version}`:"",U=Z.description?` — ${Z.description}`:"",G=Z.commands.length>0?` (${Z.commands.join(", ")})`:"",W=Z.source?` ← ${Z.source}`:"";console.log(` ${Z.name}${z}${U}${G}${W}`)}for(const[Z,z]of Y){console.log();console.log(` \uD83D\uDCE6 ${Z} (monorepo)`);for(const U of z){const G=U.version?` @${U.version}`:"",W=U.description?` — ${U.description}`:"",_=U.commands.length>0?` (${U.commands.join(", ")})`:"";console.log(` ${U.name}${G}${W}${_}`)}}console.log();console.log(` ${X.length} plugin(s) installed`);console.log()});Qq.command("create").description("Create a new plugin scaffold").argument("<name>","Plugin name (lowercase, hyphens allowed)").option("-d, --dir <path>","Output directory (default: ./<name>)").option("--description <text>","Plugin description").action(async(q,K)=>{const{createPluginScaffold:X}=await import("./plugin-scaffold.js");try{const Q=X(q,{dir:K.dir,description:K.description});console.log(`✅ Plugin scaffold created at ${Q.dir}`);console.log();console.log(" Files created:");for(const Y of Q.files)console.log(` ${Y}`);console.log();console.log(" Next steps:");console.log(` cd ${Q.dir}`);console.log(` ppcli plugin install file://${Q.dir}`);console.log(` ppcli ${q} hello`)}catch(Q){console.error(`Error: ${h(Q)}`);process.exitCode=J.GENERIC_ERROR}});const jq=$.command("adapter").description("Manage CLI adapters"),dK=jq.description();jq.command("status").description("Show which sites have local overrides vs using official baseline").action(async()=>{const q=await import("node:os"),K=M.join(q.homedir(),".ppcli","clis"),X=N;try{const Y=(await I.promises.readdir(K,{withFileTypes:!0})).filter((z)=>z.isDirectory()).map((z)=>z.name).sort();let Z=[];try{Z=(await I.promises.readdir(X,{withFileTypes:!0})).filter((U)=>U.isDirectory()).map((U)=>U.name).sort()}catch{}if(Y.length===0){console.log("No local adapter overrides. All sites use the official baseline.");return}console.log(`Local overrides in ~/.ppcli/clis/ (${Y.length} sites):
|
|
131
131
|
`);for(const z of Y){const G=Z.includes(z)?"override":"custom";console.log(` ${z} [${G}]`)}console.log(`
|
|
132
|
-
Official baseline: ${Z.length} sites in package`)}catch{console.log("No local adapter overrides. All sites use the official baseline.")}});jq.command("eject").description("Copy an official adapter to ~/.opencli/clis/ for local editing").argument("<site>","Site name (e.g. twitter, bilibili)").action(async(q)=>{const K=await import("node:os"),X=M.join(K.homedir(),".opencli","clis"),Q=M.join(N,q),Y=M.join(X,q);try{await I.promises.access(Q)}catch{console.error(`Error: Site "${q}" not found in official adapters.`);process.exitCode=J.USAGE_ERROR;return}try{await I.promises.access(Y);console.error(`Site "${q}" already exists in ~/.opencli/clis/. Use "opencli adapter reset ${q}" first to restore official version.`);process.exitCode=J.USAGE_ERROR;return}catch{}I.cpSync(Q,Y,{recursive:!0});console.log(`✅ Ejected "${q}" to ~/.opencli/clis/${q}/`);console.log("You can now edit the adapter files. Changes take effect immediately.");console.log("Note: Official updates to this adapter will overwrite your changes.")});jq.command("reset").description("Remove local override and restore official adapter version").argument("[site]","Site name (e.g. twitter, bilibili)").option("--all","Reset all local overrides").action(async(q,K)=>{const X=await import("node:os"),Q=M.join(X.homedir(),".opencli","clis");if(K.all){try{const U=(await I.promises.readdir(Q,{withFileTypes:!0})).filter((G)=>G.isDirectory());if(U.length===0){console.log("No local sites to reset.");return}for(const G of U)I.rmSync(M.join(Q,G.name),{recursive:!0,force:!0});console.log(`✅ Reset ${U.length} site(s). All adapters now use official baseline.`)}catch{console.log("No local sites to reset.")}return}if(!q){console.error("Error: Please specify a site name or use --all.");process.exitCode=J.USAGE_ERROR;return}const Y=M.join(Q,q);try{await I.promises.access(Y)}catch{console.error(`Site "${q}" has no local override.`);return}const Z=I.existsSync(M.join(N,q));I.rmSync(Y,{recursive:!0,force:!0});console.log(Z?`✅ Reset "${q}". Now using official baseline.`:`✅ Removed custom site "${q}".`)});const v=$.command("profile").description("Manage Browser Bridge Chrome profiles"),gK=v.description();v.command("list").description("List Chrome profiles: extension-connected and managed (dedicated Chrome instances)").option("-f, --format <fmt>","Output format: text, json","text").action(async(q)=>{const K=await xQ(),X=cQ(),Q=K?.profiles??[],Y=!!K&&!sQ(K,Fq)&&Array.isArray(K.profiles),Z=await Promise.all(yq().map(async({name:G,entry:W})=>({name:G,port:W.port,userDataDir:W.userDataDir,running:await lQ(W),isDefault:X.defaultContextId===G,createdAt:W.createdAt??"",label:W.label??"",proxy:W.proxy?{scheme:W.proxy.scheme,host:W.proxy.host,port:W.proxy.port,hasAuth:!!W.proxy.username,username:W.proxy.username??""}:null,fingerprint:W.fingerprint?.enabled?{enabled:!0,timezone:W.fingerprint.timezone??"",locale:W.fingerprint.locale??"",hardwareConcurrency:W.fingerprint.hardwareConcurrency??0,deviceMemory:W.fingerprint.deviceMemory??0,screen:W.fingerprint.screen??null,webglVendor:W.fingerprint.webglVendor??"",webglRenderer:W.fingerprint.webglRenderer??"",canvasNoise:W.fingerprint.canvasNoise===!0}:{enabled:!1},webrtc:W.webrtc!==!1,clean:W.clean!==!1})));if(q.format==="json"){const G=Y?Q.map((W)=>({contextId:W.contextId,alias:RK(X,W.contextId)??"",connected:!0,version:W.extensionVersion??"",isDefault:X.defaultContextId===W.contextId})):[];console.log(JSON.stringify({managed:Z,extension:G,daemonRunning:!!K,daemonStale:!!K&&!Y,defaultProfile:X.defaultContextId??""},null,2));return}if(Z.length>0){console.log("Managed profiles (dedicated Chrome instances)");console.log();for(const G of Z){const W=G.isDefault?" default":"";console.log(` ${G.name}${W} — ${G.running?`running on port ${G.port}`:"stopped"}`)}console.log()}if(!K){console.log("Daemon is not running. Run opencli doctor after opening Chrome.");return}if(!Y){console.log(`Daemon ${rQ(K)} is stale for CLI v${Fq}.`);console.log("Run: opencli daemon restart");return}if(Q.length===0){console.log("No Browser Bridge profiles connected.");console.log("Open a Chrome profile with the OpenCLI extension installed, then run opencli profile list again.");return}const z=new Set(Q.map((G)=>G.contextId));console.log("Connected Browser Bridge profiles");console.log();for(const G of Q){const W=RK(X,G.contextId),_=X.defaultContextId===G.contextId?" default":"",R=W?` ${W}`:"",k=G.extensionVersion?` v${G.extensionVersion}`:" version unknown";console.log(` ${G.contextId}${R}${_} — connected${k}`)}const U=Object.entries(X.aliases).filter(([,G])=>!z.has(G));if(U.length>0||X.defaultContextId&&!z.has(X.defaultContextId)){console.log();console.log("Disconnected saved profiles:");const G=new Set;for(const[W,_]of U){G.add(_);console.log(` ${_} ${W} — not connected`)}if(X.defaultContextId&&!G.has(X.defaultContextId)&&!z.has(X.defaultContextId))console.log(` ${X.defaultContextId} — default, not connected`)}});const KK=(q)=>{if(q.config){const Q=JSON.parse(q.config);if(typeof Q.proxy==="string")Q.proxy=fq(Q.proxy);return Q}const K={};if(q.label)K.label=q.label;if(q.proxy)K.proxy=fq(q.proxy);if(q.webrtc===!1)K.webrtc=!1;if(q.clean===!1)K.clean=!1;const X=q.fingerprint;if(X&&X!=="off")K.fingerprint={enabled:!0,spoof:X!=="lite",...q.fpTimezone?{timezone:q.fpTimezone}:{},...q.fpLocale?{locale:q.fpLocale}:{},...q.fpUa?{userAgent:q.fpUa}:{},...q.fpPlatform?{platform:q.fpPlatform}:{},...q.fpSeed?{seed:Number(q.fpSeed)}:{}};return K},QK=(q)=>q?{scheme:q.scheme,host:q.host,port:q.port,hasAuth:!!q.username,username:q.username??""}:null,XK=(q)=>q?.enabled?{enabled:!0,seed:q.seed,timezone:q.timezone??"",locale:q.locale??"",userAgent:q.userAgent??"",platform:q.platform??"",hardwareConcurrency:q.hardwareConcurrency??0,deviceMemory:q.deviceMemory??0,screen:q.screen??null,webglVendor:q.webglVendor??"",webglRenderer:q.webglRenderer??"",canvasNoise:q.canvasNoise===!0}:{enabled:!1},YK=(q)=>q.option("--label <text>","Display label / note for the environment").option("--proxy <url>","Per-env proxy: scheme://[user:pass@]host:port (scheme = http/https/socks5)").option("--fingerprint <mode>","Fingerprint mode: off | on (spoof soft signals) | lite (timezone/locale follow only)").option("--fp-timezone <iana>","Fingerprint timezone, e.g. America/New_York (must be set explicitly)").option("--fp-locale <locale>","Fingerprint locale, e.g. en-US (must be set explicitly)").option("--fp-ua <ua>","Override navigator.userAgent (use with care)").option("--fp-platform <p>","Override navigator.platform, e.g. Win32").option("--fp-seed <n>","Fixed fingerprint seed (for reproducible fingerprint)").option("--no-webrtc","Disable WebRTC leak protection (on by default)").option("--no-clean","Disable lean launch flags / telemetry suppression (on by default)").option("--config <json>","Full config as JSON: { label, proxy, fingerprint } — overrides granular flags");v.command("create").description("Create a managed profile: a dedicated Chrome instance with its own user data dir (for a second account)").argument("<name>","Profile name, e.g. work / brand2").option("--browser-path <path>","Explicit browser executable (defaults to auto-discovered Chrome)").option("--no-start","Create only; do not launch Chrome now").option("-f, --format <fmt>","Output format: text, json","text").action(async(q,K)=>{try{const X=KK(K),{opts:Q}=await EK({...X,browserPath:K.browserPath}),Y=await nQ(q,{...Q,browserPath:K.browserPath});if(K.start!==!1)await vq(q,Y);if(K.format==="json"){console.log(JSON.stringify({ok:!0,name:q,port:Y.port,userDataDir:Y.userDataDir,label:Y.label??"",proxy:QK(Y.proxy),fingerprint:XK(Y.fingerprint),webrtc:Y.webrtc!==!1,clean:Y.clean!==!1,started:K.start!==!1},null,2));return}console.log(`✅ 托管 profile "${q}" 已创建(端口 ${Y.port})`);console.log(` 数据目录:${Y.userDataDir}`);if(Y.proxy)console.log(` 代理:${Y.proxy.scheme}://${Y.proxy.host}:${Y.proxy.port}`);if(Y.fingerprint?.enabled)console.log(` 指纹:已开启${Y.fingerprint.timezone?` 时区 ${Y.fingerprint.timezone}`:""}${Y.fingerprint.locale?` 语言 ${Y.fingerprint.locale}`:""}`);if(K.start!==!1)console.log(` Chrome 已启动。用 opencli <site> login --profile ${q} 在新窗口里登录账号。`)}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.USAGE_ERROR}});YK(v.commands[v.commands.length-1]);v.command("start").description("Launch the dedicated Chrome instance of a managed profile").argument("<name>","Managed profile name").action(async(q)=>{try{const K=yq().find((Q)=>Q.name===q.trim());if(!K)throw Error(`托管 profile "${q}" 不存在,先 opencli profile create ${q}`);const X=await vq(K.name,K.entry);console.log(`✅ profile "${q}" 运行中(${X})`)}catch(K){console.error(`Error: ${h(K)}`);process.exitCode=J.USAGE_ERROR}});v.command("stop").description("Gracefully close the dedicated Chrome instance of a managed profile").argument("<name>","Managed profile name").action(async(q)=>{try{const K=yq().find((Q)=>Q.name===q.trim());if(!K)throw Error(`托管 profile "${q}" 不存在`);const X=await oQ(K.entry);console.log(X?`✅ profile "${q}" 已关闭`:`profile "${q}" 本来就没在运行`)}catch(K){console.error(`Error: ${h(K)}`);process.exitCode=J.USAGE_ERROR}});v.command("remove").description("Remove a managed profile (closes Chrome and deletes its login data)").argument("<name>","Managed profile name").option("--keep-data","Keep the user data dir on disk",!1).action(async(q,K)=>{try{await iQ(q,{keepData:K.keepData===!0});console.log(`✅ 托管 profile "${q}" 已删除${K.keepData?"(保留数据目录)":"(含登录数据)"}`)}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.USAGE_ERROR}});v.command("update").description("Reconfigure a managed profile (label / proxy / fingerprint); takes effect on next start").argument("<name>","Managed profile name").option("--clear-proxy","Remove the proxy from this environment").option("--restart","Relaunch the environment after updating",!1).option("-f, --format <fmt>","Output format: text, json","text").action(async(q,K)=>{try{const X=KK(K),{opts:Q}=await EK(X),Y={};if(X.label!==void 0)Y.label=X.label??null;if(K.clearProxy)Y.proxy=null;else if(Q.proxy)Y.proxy=Q.proxy;if(K.fingerprint==="off")Y.fingerprint=null;else if(Q.fingerprint)Y.fingerprint=Q.fingerprint;if(X.webrtc!==void 0)Y.webrtc=X.webrtc;if(X.clean!==void 0)Y.clean=X.clean;const{entry:Z,wasRunning:z}=await pQ(q,Y);if(K.restart&&z)await vq(q,Z);if(K.format==="json"){console.log(JSON.stringify({ok:!0,name:q,label:Z.label??"",proxy:QK(Z.proxy),fingerprint:XK(Z.fingerprint),webrtc:Z.webrtc!==!1,clean:Z.clean!==!1,wasRunning:z,restarted:!!(K.restart&&z)},null,2));return}console.log(`✅ 托管 profile "${q}" 配置已更新${z?"(已关闭,重启后生效)":""}`)}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.USAGE_ERROR}});YK(v.commands[v.commands.length-1]);v.command("test-proxy").description("Test proxy connectivity and detect exit IP / country / timezone").argument("<url>","Proxy: scheme://[user:pass@]host:port (scheme = http/https/socks5)").option("-f, --format <fmt>","Output format: text, json","text").action(async(q,K)=>{try{const X=fq(q),Q=await aQ(X);if(K.format==="json"){console.log(JSON.stringify(Q,null,2));return}if(Q.ok){console.log(`✅ 代理可用 — 出口 IP ${Q.ip}`);console.log(` 位置:${Q.country??"?"}${Q.city?" / "+Q.city:""}`);console.log(` 时区:${Q.timezone??"?"} 语言:${Q.locale??"?"}`)}else{console.log(`❌ 代理不可用:${Q.error}`);process.exitCode=J.USAGE_ERROR}}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.USAGE_ERROR}});v.command("rename").description("Assign a local alias to a connected Browser Bridge profile").argument("<contextId>","Profile contextId from opencli profile list").argument("<alias>","Local alias, e.g. work or personal").action((q,K)=>{try{mQ(q,K);console.log(`Profile ${q} is now aliased as ${K}.`)}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.USAGE_ERROR}});v.command("use").description("Set the default Browser Bridge profile for future commands").argument("<profile>","Profile alias or contextId").action((q)=>{try{const K=gQ(q);console.log(`Default Browser Bridge profile: ${K.defaultContextId??q}`)}catch(K){console.error(`Error: ${h(K)}`);process.exitCode=J.USAGE_ERROR}});const Hq=$.command("daemon").description("Manage the opencli daemon"),nK=Hq.description();Hq.command("status").description("Show daemon status").action(async()=>{await hQ()});Hq.command("stop").description("Stop the daemon").action(async()=>{await yQ()});Hq.command("restart").description("Restart the daemon").action(async()=>{await wQ()});Hq.command("warm").description("Pre-open the background automation window (keeps a tab alive for reuse)").option("--url <url>","http(s) info page to keep in the warm tab (falls back to about:blank)").action(async(q)=>{await vQ(q.url)});const Lq=Tq(),Mq=$.command("external").description("Manage external CLI passthrough commands");Mq.command("install").description("Install an external CLI").argument("<name>","Name of the external CLI").action((q)=>{const K=Lq.find((X)=>X.name===q);if(!K){console.error(`External CLI '${q}' not found in registry.`);process.exitCode=J.USAGE_ERROR;return}ZQ(K)});Mq.command("register").description("Register an external CLI").argument("<name>","Name of the CLI").option("--binary <bin>","Binary name if different from name").option("--install <cmd>","Auto-install command").option("--desc <text>","Description").action((q,K)=>{$Q(q,{binary:K.binary,install:K.install,description:K.desc})});Mq.command("list").description("List registered external CLIs").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((q)=>{const K=Tq().map((X)=>({name:X.name,package:X.package??"",binary:X.binary,installed:wq(X.binary),description:X.description??"",homepage:X.homepage??"",tags:X.tags?.join(", ")??""}));Aq(K,{fmt:q.format,columns:["name","package","binary","installed","description","homepage","tags"],title:"opencli/external/list",source:"opencli external list"})});function lK(q,K){const X=K??(()=>{const Q=process.argv.indexOf(q);return process.argv.slice(Q+1)})();try{YQ(q,X,Lq)}catch(Q){if(Q instanceof hq){process.stderr.write(eK.dump(jQ(Q),{sortKeys:!1,lineWidth:120,noRefs:!0}));process.exitCode=Q.exitCode}else{console.error(`Error: ${h(Q)}`);process.exitCode=J.GENERIC_ERROR}}}for(const q of Lq){if($.commands.some((K)=>K.name()===q.name))continue;$.command(q.name).description(`(External) ${q.description||q.name}`).argument("[args...]").allowUnknownOption().passThroughOptions().helpOption(!1).action((K)=>lK(q.name,K))}const ZK=$.command("antigravity").description("antigravity commands");ZK.command("serve").description("Start Anthropic-compatible API proxy for Antigravity").option("--port <port>","Server port (default: 8082)","8082").option("--timeout <seconds>","Maximum time to wait for a reply (default: 120s)").action(async(q)=>{const{startServe:K}=await import("../../clis/antigravity/serve.js");await K({port:parseInt(q.port,10),timeout:q.timeout?yK(q.timeout,"--timeout",120):void 0})});const $K=new Map;$K.set("antigravity",ZK);const HK=NQ($,$K);JX($);const iK=Lq.map((q)=>q.name),oK=Lq.map((q)=>({name:q.name,label:VK(q)})),Sq=new Map;for(const[,q]of Dq())if(!Sq.has(q.site))Sq.set(q.site,q.domain);const zK=[],NK=[];for(const q of HK)if(jK(Sq.get(q))==="app")zK.push(q);else NK.push(q);const UK={external:oK,apps:zK,sites:NK},pK=new Set([...iK,...HK]);Nq(j,{globalCommand:$,description:S});Nq(B,{globalCommand:$,description:"Inspect website login status"});Nq(Hq,{globalCommand:$,description:nK});Nq(Qq,{globalCommand:$,description:mK});Nq(jq,{globalCommand:$,description:dK});Nq(v,{globalCommand:$,description:gK});$.configureHelp({visibleCommands:(q)=>q.commands.filter((K)=>q!==$||!pK.has(K.name()))});const aK=(q)=>{const K=[];let X=q.parent;while(X){const Q=WQ(X);K.unshift(Q?`${X.name()} ${Q}`:X.name());X=X.parent}return[...K,q.name(),q.usage()].filter(Boolean).join(" ").trim()};function GK(q){q.configureHelp({commandUsage:aK});for(const K of q.commands)GK(K)}GK(j);GQ($,()=>JQ($,UK),()=>UQ(UK));$.on("command:*",(q)=>{const K=q[0];console.error(`error: unknown command '${K}'`);if(wq(K))console.error(` Tip: '${K}' exists on your PATH. Use 'opencli external register ${K}' to add it as an external CLI.`);$.outputHelp();process.exitCode=J.USAGE_ERROR});return $}export function runCli(N,H){createProgram(N,H).parse()}export{findPackageRoot};export function resolveBrowserVerifyInvocation(N={}){const H=N.platform??process.platform,$=N.fileExists??I.existsSync,V=N.readFile??((F)=>I.readFileSync(F,"utf-8")),B=N.projectRoot??findPackageRoot(uq,$);for(const F of qQ(B,V))if($(F))return{binary:process.execPath,args:[F],cwd:B};const j=M.join(B,"src","main.ts");if(!$(j))throw Error(`Could not find opencli entrypoint under ${B}. Expected built entry from package.json or src/main.ts.`);const S=M.join(B,"node_modules",".bin",H==="win32"?"tsx.cmd":"tsx");if($(S))return{binary:S,args:[j],cwd:B,...H==="win32"?{shell:!0}:{}};return{binary:H==="win32"?"npx.cmd":"npx",args:["tsx",j],cwd:B,...H==="win32"?{shell:!0}:{}}}
|
|
132
|
+
Official baseline: ${Z.length} sites in package`)}catch{console.log("No local adapter overrides. All sites use the official baseline.")}});jq.command("eject").description("Copy an official adapter to ~/.ppcli/clis/ for local editing").argument("<site>","Site name (e.g. twitter, bilibili)").action(async(q)=>{const K=await import("node:os"),X=M.join(K.homedir(),".ppcli","clis"),Q=M.join(N,q),Y=M.join(X,q);try{await I.promises.access(Q)}catch{console.error(`Error: Site "${q}" not found in official adapters.`);process.exitCode=J.USAGE_ERROR;return}try{await I.promises.access(Y);console.error(`Site "${q}" already exists in ~/.ppcli/clis/. Use "ppcli adapter reset ${q}" first to restore official version.`);process.exitCode=J.USAGE_ERROR;return}catch{}I.cpSync(Q,Y,{recursive:!0});console.log(`✅ Ejected "${q}" to ~/.ppcli/clis/${q}/`);console.log("You can now edit the adapter files. Changes take effect immediately.");console.log("Note: Official updates to this adapter will overwrite your changes.")});jq.command("reset").description("Remove local override and restore official adapter version").argument("[site]","Site name (e.g. twitter, bilibili)").option("--all","Reset all local overrides").action(async(q,K)=>{const X=await import("node:os"),Q=M.join(X.homedir(),".ppcli","clis");if(K.all){try{const U=(await I.promises.readdir(Q,{withFileTypes:!0})).filter((G)=>G.isDirectory());if(U.length===0){console.log("No local sites to reset.");return}for(const G of U)I.rmSync(M.join(Q,G.name),{recursive:!0,force:!0});console.log(`✅ Reset ${U.length} site(s). All adapters now use official baseline.`)}catch{console.log("No local sites to reset.")}return}if(!q){console.error("Error: Please specify a site name or use --all.");process.exitCode=J.USAGE_ERROR;return}const Y=M.join(Q,q);try{await I.promises.access(Y)}catch{console.error(`Site "${q}" has no local override.`);return}const Z=I.existsSync(M.join(N,q));I.rmSync(Y,{recursive:!0,force:!0});console.log(Z?`✅ Reset "${q}". Now using official baseline.`:`✅ Removed custom site "${q}".`)});const v=$.command("profile").description("Manage Browser Bridge Chrome profiles"),gK=v.description();v.command("list").description("List Chrome profiles: extension-connected and managed (dedicated Chrome instances)").option("-f, --format <fmt>","Output format: text, json","text").action(async(q)=>{const K=await xQ(),X=cQ(),Q=K?.profiles??[],Y=!!K&&!sQ(K,Fq)&&Array.isArray(K.profiles),Z=await Promise.all(yq().map(async({name:G,entry:W})=>({name:G,port:W.port,userDataDir:W.userDataDir,running:await lQ(W),isDefault:X.defaultContextId===G,createdAt:W.createdAt??"",label:W.label??"",proxy:W.proxy?{scheme:W.proxy.scheme,host:W.proxy.host,port:W.proxy.port,hasAuth:!!W.proxy.username,username:W.proxy.username??""}:null,fingerprint:W.fingerprint?.enabled?{enabled:!0,timezone:W.fingerprint.timezone??"",locale:W.fingerprint.locale??"",hardwareConcurrency:W.fingerprint.hardwareConcurrency??0,deviceMemory:W.fingerprint.deviceMemory??0,screen:W.fingerprint.screen??null,webglVendor:W.fingerprint.webglVendor??"",webglRenderer:W.fingerprint.webglRenderer??"",canvasNoise:W.fingerprint.canvasNoise===!0}:{enabled:!1},webrtc:W.webrtc!==!1,clean:W.clean!==!1})));if(q.format==="json"){const G=Y?Q.map((W)=>({contextId:W.contextId,alias:RK(X,W.contextId)??"",connected:!0,version:W.extensionVersion??"",isDefault:X.defaultContextId===W.contextId})):[];console.log(JSON.stringify({managed:Z,extension:G,daemonRunning:!!K,daemonStale:!!K&&!Y,defaultProfile:X.defaultContextId??""},null,2));return}if(Z.length>0){console.log("Managed profiles (dedicated Chrome instances)");console.log();for(const G of Z){const W=G.isDefault?" default":"";console.log(` ${G.name}${W} — ${G.running?`running on port ${G.port}`:"stopped"}`)}console.log()}if(!K){console.log("Daemon is not running. Run ppcli doctor after opening Chrome.");return}if(!Y){console.log(`Daemon ${rQ(K)} is stale for CLI v${Fq}.`);console.log("Run: ppcli daemon restart");return}if(Q.length===0){console.log("No Browser Bridge profiles connected.");console.log("Open a Chrome profile with the ppcli extension installed, then run ppcli profile list again.");return}const z=new Set(Q.map((G)=>G.contextId));console.log("Connected Browser Bridge profiles");console.log();for(const G of Q){const W=RK(X,G.contextId),_=X.defaultContextId===G.contextId?" default":"",R=W?` ${W}`:"",k=G.extensionVersion?` v${G.extensionVersion}`:" version unknown";console.log(` ${G.contextId}${R}${_} — connected${k}`)}const U=Object.entries(X.aliases).filter(([,G])=>!z.has(G));if(U.length>0||X.defaultContextId&&!z.has(X.defaultContextId)){console.log();console.log("Disconnected saved profiles:");const G=new Set;for(const[W,_]of U){G.add(_);console.log(` ${_} ${W} — not connected`)}if(X.defaultContextId&&!G.has(X.defaultContextId)&&!z.has(X.defaultContextId))console.log(` ${X.defaultContextId} — default, not connected`)}});const KK=(q)=>{if(q.config){const Q=JSON.parse(q.config);if(typeof Q.proxy==="string")Q.proxy=fq(Q.proxy);return Q}const K={};if(q.label)K.label=q.label;if(q.proxy)K.proxy=fq(q.proxy);if(q.webrtc===!1)K.webrtc=!1;if(q.clean===!1)K.clean=!1;const X=q.fingerprint;if(X&&X!=="off")K.fingerprint={enabled:!0,spoof:X!=="lite",...q.fpTimezone?{timezone:q.fpTimezone}:{},...q.fpLocale?{locale:q.fpLocale}:{},...q.fpUa?{userAgent:q.fpUa}:{},...q.fpPlatform?{platform:q.fpPlatform}:{},...q.fpSeed?{seed:Number(q.fpSeed)}:{}};return K},QK=(q)=>q?{scheme:q.scheme,host:q.host,port:q.port,hasAuth:!!q.username,username:q.username??""}:null,XK=(q)=>q?.enabled?{enabled:!0,seed:q.seed,timezone:q.timezone??"",locale:q.locale??"",userAgent:q.userAgent??"",platform:q.platform??"",hardwareConcurrency:q.hardwareConcurrency??0,deviceMemory:q.deviceMemory??0,screen:q.screen??null,webglVendor:q.webglVendor??"",webglRenderer:q.webglRenderer??"",canvasNoise:q.canvasNoise===!0}:{enabled:!1},YK=(q)=>q.option("--label <text>","Display label / note for the environment").option("--proxy <url>","Per-env proxy: scheme://[user:pass@]host:port (scheme = http/https/socks5)").option("--fingerprint <mode>","Fingerprint mode: off | on (spoof soft signals) | lite (timezone/locale follow only)").option("--fp-timezone <iana>","Fingerprint timezone, e.g. America/New_York (must be set explicitly)").option("--fp-locale <locale>","Fingerprint locale, e.g. en-US (must be set explicitly)").option("--fp-ua <ua>","Override navigator.userAgent (use with care)").option("--fp-platform <p>","Override navigator.platform, e.g. Win32").option("--fp-seed <n>","Fixed fingerprint seed (for reproducible fingerprint)").option("--no-webrtc","Disable WebRTC leak protection (on by default)").option("--no-clean","Disable lean launch flags / telemetry suppression (on by default)").option("--config <json>","Full config as JSON: { label, proxy, fingerprint } — overrides granular flags");v.command("create").description("Create a managed profile: a dedicated Chrome instance with its own user data dir (for a second account)").argument("<name>","Profile name, e.g. work / brand2").option("--browser-path <path>","Explicit browser executable (defaults to auto-discovered Chrome)").option("--no-start","Create only; do not launch Chrome now").option("-f, --format <fmt>","Output format: text, json","text").action(async(q,K)=>{try{const X=KK(K),{opts:Q}=await EK({...X,browserPath:K.browserPath}),Y=await nQ(q,{...Q,browserPath:K.browserPath});if(K.start!==!1)await vq(q,Y);if(K.format==="json"){console.log(JSON.stringify({ok:!0,name:q,port:Y.port,userDataDir:Y.userDataDir,label:Y.label??"",proxy:QK(Y.proxy),fingerprint:XK(Y.fingerprint),webrtc:Y.webrtc!==!1,clean:Y.clean!==!1,started:K.start!==!1},null,2));return}console.log(`✅ 托管 profile "${q}" 已创建(端口 ${Y.port})`);console.log(` 数据目录:${Y.userDataDir}`);if(Y.proxy)console.log(` 代理:${Y.proxy.scheme}://${Y.proxy.host}:${Y.proxy.port}`);if(Y.fingerprint?.enabled)console.log(` 指纹:已开启${Y.fingerprint.timezone?` 时区 ${Y.fingerprint.timezone}`:""}${Y.fingerprint.locale?` 语言 ${Y.fingerprint.locale}`:""}`);if(K.start!==!1)console.log(` Chrome 已启动。用 ppcli <site> login --profile ${q} 在新窗口里登录账号。`)}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.USAGE_ERROR}});YK(v.commands[v.commands.length-1]);v.command("start").description("Launch the dedicated Chrome instance of a managed profile").argument("<name>","Managed profile name").action(async(q)=>{try{const K=yq().find((Q)=>Q.name===q.trim());if(!K)throw Error(`托管 profile "${q}" 不存在,先 ppcli profile create ${q}`);const X=await vq(K.name,K.entry);console.log(`✅ profile "${q}" 运行中(${X})`)}catch(K){console.error(`Error: ${h(K)}`);process.exitCode=J.USAGE_ERROR}});v.command("stop").description("Gracefully close the dedicated Chrome instance of a managed profile").argument("<name>","Managed profile name").action(async(q)=>{try{const K=yq().find((Q)=>Q.name===q.trim());if(!K)throw Error(`托管 profile "${q}" 不存在`);const X=await oQ(K.entry);console.log(X?`✅ profile "${q}" 已关闭`:`profile "${q}" 本来就没在运行`)}catch(K){console.error(`Error: ${h(K)}`);process.exitCode=J.USAGE_ERROR}});v.command("remove").description("Remove a managed profile (closes Chrome and deletes its login data)").argument("<name>","Managed profile name").option("--keep-data","Keep the user data dir on disk",!1).action(async(q,K)=>{try{await iQ(q,{keepData:K.keepData===!0});console.log(`✅ 托管 profile "${q}" 已删除${K.keepData?"(保留数据目录)":"(含登录数据)"}`)}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.USAGE_ERROR}});v.command("update").description("Reconfigure a managed profile (label / proxy / fingerprint); takes effect on next start").argument("<name>","Managed profile name").option("--clear-proxy","Remove the proxy from this environment").option("--restart","Relaunch the environment after updating",!1).option("-f, --format <fmt>","Output format: text, json","text").action(async(q,K)=>{try{const X=KK(K),{opts:Q}=await EK(X),Y={};if(X.label!==void 0)Y.label=X.label??null;if(K.clearProxy)Y.proxy=null;else if(Q.proxy)Y.proxy=Q.proxy;if(K.fingerprint==="off")Y.fingerprint=null;else if(Q.fingerprint)Y.fingerprint=Q.fingerprint;if(X.webrtc!==void 0)Y.webrtc=X.webrtc;if(X.clean!==void 0)Y.clean=X.clean;const{entry:Z,wasRunning:z}=await pQ(q,Y);if(K.restart&&z)await vq(q,Z);if(K.format==="json"){console.log(JSON.stringify({ok:!0,name:q,label:Z.label??"",proxy:QK(Z.proxy),fingerprint:XK(Z.fingerprint),webrtc:Z.webrtc!==!1,clean:Z.clean!==!1,wasRunning:z,restarted:!!(K.restart&&z)},null,2));return}console.log(`✅ 托管 profile "${q}" 配置已更新${z?"(已关闭,重启后生效)":""}`)}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.USAGE_ERROR}});YK(v.commands[v.commands.length-1]);v.command("test-proxy").description("Test proxy connectivity and detect exit IP / country / timezone").argument("<url>","Proxy: scheme://[user:pass@]host:port (scheme = http/https/socks5)").option("-f, --format <fmt>","Output format: text, json","text").action(async(q,K)=>{try{const X=fq(q),Q=await aQ(X);if(K.format==="json"){console.log(JSON.stringify(Q,null,2));return}if(Q.ok){console.log(`✅ 代理可用 — 出口 IP ${Q.ip}`);console.log(` 位置:${Q.country??"?"}${Q.city?" / "+Q.city:""}`);console.log(` 时区:${Q.timezone??"?"} 语言:${Q.locale??"?"}`)}else{console.log(`❌ 代理不可用:${Q.error}`);process.exitCode=J.USAGE_ERROR}}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.USAGE_ERROR}});v.command("rename").description("Assign a local alias to a connected Browser Bridge profile").argument("<contextId>","Profile contextId from ppcli profile list").argument("<alias>","Local alias, e.g. work or personal").action((q,K)=>{try{mQ(q,K);console.log(`Profile ${q} is now aliased as ${K}.`)}catch(X){console.error(`Error: ${h(X)}`);process.exitCode=J.USAGE_ERROR}});v.command("use").description("Set the default Browser Bridge profile for future commands").argument("<profile>","Profile alias or contextId").action((q)=>{try{const K=gQ(q);console.log(`Default Browser Bridge profile: ${K.defaultContextId??q}`)}catch(K){console.error(`Error: ${h(K)}`);process.exitCode=J.USAGE_ERROR}});const Hq=$.command("daemon").description("Manage the ppcli daemon"),nK=Hq.description();Hq.command("status").description("Show daemon status").action(async()=>{await hQ()});Hq.command("stop").description("Stop the daemon").action(async()=>{await yQ()});Hq.command("restart").description("Restart the daemon").action(async()=>{await wQ()});Hq.command("warm").description("Pre-open the background automation window (keeps a tab alive for reuse)").option("--url <url>","http(s) info page to keep in the warm tab (falls back to about:blank)").action(async(q)=>{await vQ(q.url)});const Lq=Tq(),Mq=$.command("external").description("Manage external CLI passthrough commands");Mq.command("install").description("Install an external CLI").argument("<name>","Name of the external CLI").action((q)=>{const K=Lq.find((X)=>X.name===q);if(!K){console.error(`External CLI '${q}' not found in registry.`);process.exitCode=J.USAGE_ERROR;return}ZQ(K)});Mq.command("register").description("Register an external CLI").argument("<name>","Name of the CLI").option("--binary <bin>","Binary name if different from name").option("--install <cmd>","Auto-install command").option("--desc <text>","Description").action((q,K)=>{$Q(q,{binary:K.binary,install:K.install,description:K.desc})});Mq.command("list").description("List registered external CLIs").option("-f, --format <fmt>","Output format: table, json, yaml, md, csv","table").action((q)=>{const K=Tq().map((X)=>({name:X.name,package:X.package??"",binary:X.binary,installed:wq(X.binary),description:X.description??"",homepage:X.homepage??"",tags:X.tags?.join(", ")??""}));Aq(K,{fmt:q.format,columns:["name","package","binary","installed","description","homepage","tags"],title:"ppcli/external/list",source:"ppcli external list"})});function lK(q,K){const X=K??(()=>{const Q=process.argv.indexOf(q);return process.argv.slice(Q+1)})();try{YQ(q,X,Lq)}catch(Q){if(Q instanceof hq){process.stderr.write(eK.dump(jQ(Q),{sortKeys:!1,lineWidth:120,noRefs:!0}));process.exitCode=Q.exitCode}else{console.error(`Error: ${h(Q)}`);process.exitCode=J.GENERIC_ERROR}}}for(const q of Lq){if($.commands.some((K)=>K.name()===q.name))continue;$.command(q.name).description(`(External) ${q.description||q.name}`).argument("[args...]").allowUnknownOption().passThroughOptions().helpOption(!1).action((K)=>lK(q.name,K))}const ZK=$.command("antigravity").description("antigravity commands");ZK.command("serve").description("Start Anthropic-compatible API proxy for Antigravity").option("--port <port>","Server port (default: 8082)","8082").option("--timeout <seconds>","Maximum time to wait for a reply (default: 120s)").action(async(q)=>{const{startServe:K}=await import("../../clis/antigravity/serve.js");await K({port:parseInt(q.port,10),timeout:q.timeout?yK(q.timeout,"--timeout",120):void 0})});const $K=new Map;$K.set("antigravity",ZK);const HK=NQ($,$K);JX($);const iK=Lq.map((q)=>q.name),oK=Lq.map((q)=>({name:q.name,label:VK(q)})),Sq=new Map;for(const[,q]of Dq())if(!Sq.has(q.site))Sq.set(q.site,q.domain);const zK=[],NK=[];for(const q of HK)if(jK(Sq.get(q))==="app")zK.push(q);else NK.push(q);const UK={external:oK,apps:zK,sites:NK},pK=new Set([...iK,...HK]);Nq(j,{globalCommand:$,description:S});Nq(B,{globalCommand:$,description:"Inspect website login status"});Nq(Hq,{globalCommand:$,description:nK});Nq(Qq,{globalCommand:$,description:mK});Nq(jq,{globalCommand:$,description:dK});Nq(v,{globalCommand:$,description:gK});$.configureHelp({visibleCommands:(q)=>q.commands.filter((K)=>q!==$||!pK.has(K.name()))});const aK=(q)=>{const K=[];let X=q.parent;while(X){const Q=WQ(X);K.unshift(Q?`${X.name()} ${Q}`:X.name());X=X.parent}return[...K,q.name(),q.usage()].filter(Boolean).join(" ").trim()};function GK(q){q.configureHelp({commandUsage:aK});for(const K of q.commands)GK(K)}GK(j);GQ($,()=>JQ($,UK),()=>UQ(UK));$.on("command:*",(q)=>{const K=q[0];console.error(`error: unknown command '${K}'`);if(wq(K))console.error(` Tip: '${K}' exists on your PATH. Use 'ppcli external register ${K}' to add it as an external CLI.`);$.outputHelp();process.exitCode=J.USAGE_ERROR});return $}export function runCli(N,H){createProgram(N,H).parse()}export{findPackageRoot};export function resolveBrowserVerifyInvocation(N={}){const H=N.platform??process.platform,$=N.fileExists??I.existsSync,V=N.readFile??((F)=>I.readFileSync(F,"utf-8")),B=N.projectRoot??findPackageRoot(uq,$);for(const F of qQ(B,V))if($(F))return{binary:process.execPath,args:[F],cwd:B};const j=M.join(B,"src","main.ts");if(!$(j))throw Error(`Could not find ppcli entrypoint under ${B}. Expected built entry from package.json or src/main.ts.`);const S=M.join(B,"node_modules",".bin",H==="win32"?"tsx.cmd":"tsx");if($(S))return{binary:S,args:[j],cwd:B,...H==="win32"?{shell:!0}:{}};return{binary:H==="win32"?"npx.cmd":"npx",args:["tsx",j],cwd:B,...H==="win32"?{shell:!0}:{}}}
|