@jackwener/opencli 1.7.5 → 1.7.7
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 +22 -10
- package/README.zh-CN.md +18 -9
- package/cli-manifest.json +401 -11
- package/clis/51job/company.js +125 -0
- package/clis/51job/detail.js +108 -0
- package/clis/51job/hot.js +55 -0
- package/clis/51job/search.js +79 -0
- package/clis/51job/utils.js +302 -0
- package/clis/51job/utils.test.js +69 -0
- package/clis/bilibili/video.js +68 -0
- package/clis/bilibili/video.test.js +132 -0
- package/clis/chatgpt/image.js +1 -1
- package/clis/deepseek/ask.js +37 -11
- package/clis/deepseek/ask.test.js +165 -0
- package/clis/deepseek/utils.js +192 -24
- package/clis/deepseek/utils.test.js +145 -0
- package/clis/gemini/image.js +1 -1
- package/clis/instagram/download.js +1 -1
- package/clis/jianyu/search.js +139 -3
- package/clis/jianyu/search.test.js +25 -0
- package/clis/jianyu/shared/procurement-detail.js +15 -0
- package/clis/jianyu/shared/procurement-detail.test.js +12 -0
- package/clis/twitter/likes.js +3 -2
- package/clis/twitter/search.js +4 -2
- package/clis/twitter/search.test.js +4 -0
- package/clis/twitter/shared.js +35 -2
- package/clis/twitter/shared.test.js +96 -0
- package/clis/twitter/thread.js +3 -1
- package/clis/twitter/timeline.js +3 -2
- package/clis/twitter/tweets.js +219 -0
- package/clis/twitter/tweets.test.js +125 -0
- package/clis/web/read.js +25 -5
- package/clis/web/read.test.js +76 -0
- package/clis/weread/ai-outline.js +170 -0
- package/clis/weread/ai-outline.test.js +83 -0
- package/clis/weread/book.js +57 -44
- package/clis/weread/commands.test.js +24 -0
- package/clis/xiaoyuzhou/podcast-episodes.js +2 -2
- package/clis/xiaoyuzhou/podcast-episodes.test.js +78 -0
- package/clis/youtube/channel.js +35 -0
- package/dist/src/browser/analyze.d.ts +103 -0
- package/dist/src/browser/analyze.js +230 -0
- package/dist/src/browser/analyze.test.d.ts +1 -0
- package/dist/src/browser/analyze.test.js +164 -0
- package/dist/src/browser/article-extract.d.ts +57 -0
- package/dist/src/browser/article-extract.e2e.test.d.ts +1 -0
- package/dist/src/browser/article-extract.e2e.test.js +105 -0
- package/dist/src/browser/article-extract.js +169 -0
- package/dist/src/browser/article-extract.test.d.ts +1 -0
- package/dist/src/browser/article-extract.test.js +94 -0
- package/dist/src/browser/base-page.d.ts +13 -3
- package/dist/src/browser/base-page.js +35 -25
- package/dist/src/browser/cdp.d.ts +1 -0
- package/dist/src/browser/cdp.js +23 -5
- package/dist/src/browser/compound.d.ts +59 -0
- package/dist/src/browser/compound.js +112 -0
- package/dist/src/browser/compound.test.d.ts +1 -0
- package/dist/src/browser/compound.test.js +175 -0
- package/dist/src/browser/dom-snapshot.d.ts +7 -0
- package/dist/src/browser/dom-snapshot.js +76 -3
- package/dist/src/browser/dom-snapshot.test.js +65 -0
- package/dist/src/browser/extract.d.ts +69 -0
- package/dist/src/browser/extract.js +132 -0
- package/dist/src/browser/extract.test.d.ts +1 -0
- package/dist/src/browser/extract.test.js +129 -0
- package/dist/src/browser/find.d.ts +76 -0
- package/dist/src/browser/find.js +179 -0
- package/dist/src/browser/find.test.d.ts +1 -0
- package/dist/src/browser/find.test.js +120 -0
- package/dist/src/browser/html-tree.d.ts +75 -0
- package/dist/src/browser/html-tree.js +112 -0
- package/dist/src/browser/html-tree.test.d.ts +1 -0
- package/dist/src/browser/html-tree.test.js +181 -0
- package/dist/src/browser/network-cache.d.ts +48 -0
- package/dist/src/browser/network-cache.js +66 -0
- package/dist/src/browser/network-cache.test.d.ts +1 -0
- package/dist/src/browser/network-cache.test.js +58 -0
- package/dist/src/browser/network-key.d.ts +22 -0
- package/dist/src/browser/network-key.js +66 -0
- package/dist/src/browser/network-key.test.d.ts +1 -0
- package/dist/src/browser/network-key.test.js +49 -0
- package/dist/src/browser/shape-filter.d.ts +52 -0
- package/dist/src/browser/shape-filter.js +101 -0
- package/dist/src/browser/shape-filter.test.d.ts +1 -0
- package/dist/src/browser/shape-filter.test.js +101 -0
- package/dist/src/browser/shape.d.ts +23 -0
- package/dist/src/browser/shape.js +95 -0
- package/dist/src/browser/shape.test.d.ts +1 -0
- package/dist/src/browser/shape.test.js +82 -0
- package/dist/src/browser/target-errors.d.ts +14 -1
- package/dist/src/browser/target-errors.js +13 -0
- package/dist/src/browser/target-errors.test.js +39 -6
- package/dist/src/browser/target-resolver.d.ts +57 -10
- package/dist/src/browser/target-resolver.js +195 -75
- package/dist/src/browser/target-resolver.test.js +80 -5
- package/dist/src/browser/verify-fixture.d.ts +59 -0
- package/dist/src/browser/verify-fixture.js +213 -0
- package/dist/src/browser/verify-fixture.test.d.ts +1 -0
- package/dist/src/browser/verify-fixture.test.js +161 -0
- package/dist/src/cli.d.ts +32 -0
- package/dist/src/cli.js +936 -141
- package/dist/src/cli.test.js +1051 -1
- package/dist/src/daemon.d.ts +3 -2
- package/dist/src/daemon.js +16 -4
- package/dist/src/daemon.test.d.ts +1 -0
- package/dist/src/daemon.test.js +19 -0
- package/dist/src/download/article-download.d.ts +12 -0
- package/dist/src/download/article-download.js +141 -17
- package/dist/src/download/article-download.test.js +196 -0
- package/dist/src/download/index.js +73 -86
- package/dist/src/errors.js +4 -2
- package/dist/src/errors.test.js +13 -0
- package/dist/src/execution.js +7 -2
- package/dist/src/execution.test.js +54 -0
- package/dist/src/launcher.d.ts +1 -1
- package/dist/src/launcher.js +3 -3
- package/dist/src/main.js +16 -0
- package/dist/src/output.js +1 -1
- package/dist/src/output.test.js +6 -0
- package/dist/src/types.d.ts +18 -3
- package/package.json +5 -1
package/clis/youtube/channel.js
CHANGED
|
@@ -115,6 +115,41 @@ cli({
|
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
117
|
|
|
118
|
+
// If Home tab has no videos, try Videos tab
|
|
119
|
+
if (recentVideos.length === 0) {
|
|
120
|
+
const videosTab = tabs.find(t => {
|
|
121
|
+
const tab = t.tabRenderer;
|
|
122
|
+
const url = tab?.endpoint?.commandMetadata?.webCommandMetadata?.url || '';
|
|
123
|
+
return tab?.tabIdentifier === 'VIDEOS'
|
|
124
|
+
|| url.endsWith('/videos')
|
|
125
|
+
|| tab?.title === 'Videos';
|
|
126
|
+
});
|
|
127
|
+
const videosTabParams = videosTab?.tabRenderer?.endpoint?.browseEndpoint?.params;
|
|
128
|
+
if (videosTabParams) {
|
|
129
|
+
const videosResp = await fetch('/youtubei/v1/browse?key=' + apiKey + '&prettyPrint=false', {
|
|
130
|
+
method: 'POST', credentials: 'include',
|
|
131
|
+
headers: {'Content-Type': 'application/json'},
|
|
132
|
+
body: JSON.stringify({context, browseId, params: videosTabParams})
|
|
133
|
+
});
|
|
134
|
+
if (videosResp.ok) {
|
|
135
|
+
const videosData = await videosResp.json();
|
|
136
|
+
const richGrid = videosData.contents?.twoColumnBrowseResultsRenderer?.tabs?.[0]?.tabRenderer?.content?.richGridRenderer?.contents || [];
|
|
137
|
+
for (const item of richGrid) {
|
|
138
|
+
if (recentVideos.length >= limit) break;
|
|
139
|
+
const v = item.richItemRenderer?.content?.videoRenderer;
|
|
140
|
+
if (v) {
|
|
141
|
+
recentVideos.push({
|
|
142
|
+
title: v.title?.runs?.[0]?.text || '',
|
|
143
|
+
duration: v.lengthText?.simpleText || '',
|
|
144
|
+
views: (v.shortViewCountText?.simpleText || '') + (v.publishedTimeText?.simpleText ? ' | ' + v.publishedTimeText.simpleText : ''),
|
|
145
|
+
url: 'https://www.youtube.com/watch?v=' + v.videoId,
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
118
153
|
return {
|
|
119
154
|
name: metadata.title || '',
|
|
120
155
|
channelId: metadata.externalId || browseId,
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `browser analyze <url>` — turn site-recon guesswork into deterministic CLI output.
|
|
3
|
+
*
|
|
4
|
+
* When an agent starts a new adapter, the first question is "which pattern am
|
|
5
|
+
* I looking at?" (A/B/C/D/E from site-recon docs) and "will Node-side fetch
|
|
6
|
+
* work, or will anti-bot middleware block me?". Today the agent has to open
|
|
7
|
+
* the page, poke `network`, try cURL, fail, guess again. This module condenses
|
|
8
|
+
* that into one call that returns a classification + evidence.
|
|
9
|
+
*
|
|
10
|
+
* Kept pure (no page imports) so the bulk is unit-testable; the CLI wrapper
|
|
11
|
+
* drives a real page, feeds the resulting signals here, and prints the verdict.
|
|
12
|
+
*/
|
|
13
|
+
import type { CliCommand } from '../registry.js';
|
|
14
|
+
export interface PageSignals {
|
|
15
|
+
/** URL we navigated to (may redirect; both fields help agents notice that). */
|
|
16
|
+
requestedUrl: string;
|
|
17
|
+
finalUrl: string;
|
|
18
|
+
/** document.cookie split into names; value not needed for detection. */
|
|
19
|
+
cookieNames: string[];
|
|
20
|
+
/**
|
|
21
|
+
* Response bodies captured during the navigation + first few seconds.
|
|
22
|
+
* We only need enough body text to spot WAF markers; the CLI truncates
|
|
23
|
+
* per-entry before feeding us.
|
|
24
|
+
*/
|
|
25
|
+
networkEntries: Array<{
|
|
26
|
+
url: string;
|
|
27
|
+
status: number;
|
|
28
|
+
contentType: string;
|
|
29
|
+
/** First N chars of body; null when not available. */
|
|
30
|
+
bodyPreview: string | null;
|
|
31
|
+
}>;
|
|
32
|
+
/**
|
|
33
|
+
* Which globals the page exposes on `window`. We don't care about the values,
|
|
34
|
+
* just presence — distinguishes Pattern B (SSR state) from Pattern A.
|
|
35
|
+
*/
|
|
36
|
+
initialState: {
|
|
37
|
+
__INITIAL_STATE__: boolean;
|
|
38
|
+
__NUXT__: boolean;
|
|
39
|
+
__NEXT_DATA__: boolean;
|
|
40
|
+
__APOLLO_STATE__: boolean;
|
|
41
|
+
};
|
|
42
|
+
/** Document title — only for the human-debug `summary` field. */
|
|
43
|
+
title: string;
|
|
44
|
+
}
|
|
45
|
+
export type AntiBotVendor = 'aliyun_waf' | 'cloudflare' | 'akamai' | 'geetest' | 'unknown';
|
|
46
|
+
export interface AntiBotVerdict {
|
|
47
|
+
detected: boolean;
|
|
48
|
+
vendor: AntiBotVendor | null;
|
|
49
|
+
evidence: string[];
|
|
50
|
+
/** One-line imperative instruction for the agent. */
|
|
51
|
+
implication: string;
|
|
52
|
+
}
|
|
53
|
+
export declare function detectAntiBot(signals: PageSignals): AntiBotVerdict;
|
|
54
|
+
export type Pattern = 'A' | 'B' | 'C' | 'D' | 'E' | 'unknown';
|
|
55
|
+
export interface PatternVerdict {
|
|
56
|
+
pattern: Pattern;
|
|
57
|
+
reason: string;
|
|
58
|
+
/** How many JSON XHR/fetch responses we saw during navigation. */
|
|
59
|
+
json_responses: number;
|
|
60
|
+
/** Count of non-2xx API responses — hint for token-gated (Pattern D). */
|
|
61
|
+
auth_failures: number;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Apply the decision tree from `site-recon.md` mechanically.
|
|
65
|
+
*
|
|
66
|
+
* B beats A when initial-state globals are present: even if the page fetches
|
|
67
|
+
* more data via XHR afterwards, the SSR payload is the highest-leverage source.
|
|
68
|
+
* D (token-gated) dominates when we see 401/403 on what looks like API
|
|
69
|
+
* endpoints — without that, an authenticated route looks identical to A.
|
|
70
|
+
*/
|
|
71
|
+
export declare function classifyPattern(signals: PageSignals): PatternVerdict;
|
|
72
|
+
export interface NearestAdapter {
|
|
73
|
+
site: string;
|
|
74
|
+
example_commands: string[];
|
|
75
|
+
reason: string;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Find existing adapters that target the same site.
|
|
79
|
+
*
|
|
80
|
+
* Keep the hostname match simple — agents extend naming conventions
|
|
81
|
+
* differently per site, so we match on the registered `domain` field and fall
|
|
82
|
+
* back to site-name containment. Returning `null` is fine; agents can always
|
|
83
|
+
* read site-memory docs.
|
|
84
|
+
*/
|
|
85
|
+
export declare function findNearestAdapter(finalUrl: string, registry: Map<string, CliCommand>): NearestAdapter | null;
|
|
86
|
+
export interface AnalyzeReport {
|
|
87
|
+
requested_url: string;
|
|
88
|
+
final_url: string;
|
|
89
|
+
title: string;
|
|
90
|
+
pattern: PatternVerdict;
|
|
91
|
+
anti_bot: AntiBotVerdict;
|
|
92
|
+
initial_state: PageSignals['initialState'];
|
|
93
|
+
nearest_adapter: NearestAdapter | null;
|
|
94
|
+
recommended_next_step: string;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Synthesize the verdict from collected signals + registry.
|
|
98
|
+
*
|
|
99
|
+
* The `recommended_next_step` is deliberately a single imperative
|
|
100
|
+
* sentence — agents act on it directly instead of re-deriving advice from
|
|
101
|
+
* the structured fields.
|
|
102
|
+
*/
|
|
103
|
+
export declare function analyzeSite(signals: PageSignals, registry: Map<string, CliCommand>): AnalyzeReport;
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `browser analyze <url>` — turn site-recon guesswork into deterministic CLI output.
|
|
3
|
+
*
|
|
4
|
+
* When an agent starts a new adapter, the first question is "which pattern am
|
|
5
|
+
* I looking at?" (A/B/C/D/E from site-recon docs) and "will Node-side fetch
|
|
6
|
+
* work, or will anti-bot middleware block me?". Today the agent has to open
|
|
7
|
+
* the page, poke `network`, try cURL, fail, guess again. This module condenses
|
|
8
|
+
* that into one call that returns a classification + evidence.
|
|
9
|
+
*
|
|
10
|
+
* Kept pure (no page imports) so the bulk is unit-testable; the CLI wrapper
|
|
11
|
+
* drives a real page, feeds the resulting signals here, and prints the verdict.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* WAF vendors we can reliably detect from cookies + response body markers
|
|
15
|
+
* alone. Signals are orthogonal per vendor — so when two vendors match
|
|
16
|
+
* simultaneously (rare), we keep all evidence and report the higher-signal
|
|
17
|
+
* vendor first.
|
|
18
|
+
*/
|
|
19
|
+
const WAF_SIGNATURES = [
|
|
20
|
+
{
|
|
21
|
+
vendor: 'aliyun_waf',
|
|
22
|
+
cookiePatterns: [/^acw_sc__v2$/, /^acw_tc$/, /^ssxmod_itna/],
|
|
23
|
+
bodyPatterns: [/arg1\s*=\s*['"][0-9A-F]{30,}/, /\/ntc_captcha\//i],
|
|
24
|
+
implication: 'Direct Node-side fetch/curl will return the slider HTML. Validate the endpoint in browser context first; HTML COOKIE adapters still finish with Node-side fetch + page.getCookies.',
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
vendor: 'cloudflare',
|
|
28
|
+
cookiePatterns: [/^__cf_bm$/, /^cf_clearance$/, /^__cfduid$/],
|
|
29
|
+
bodyPatterns: [/Cloudflare Ray ID/i, /Checking your browser before accessing/i, /cf-chl-/i],
|
|
30
|
+
implication: 'Cloudflare bot check. Start from a real browser session; probe in browser context first. HTML COOKIE adapters still finish with Node-side fetch + page.getCookies.',
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
vendor: 'akamai',
|
|
34
|
+
cookiePatterns: [/^_abck$/, /^bm_sz$/, /^bm_sv$/],
|
|
35
|
+
bodyPatterns: [/akamai/i],
|
|
36
|
+
implication: 'Akamai Bot Manager. Probe in browser context first; keep final HTML COOKIE adapters on Node-side fetch + page.getCookies.',
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
vendor: 'geetest',
|
|
40
|
+
cookiePatterns: [],
|
|
41
|
+
bodyPatterns: [/geetest/i, /gt_captcha/i],
|
|
42
|
+
implication: 'Geetest slider/puzzle captcha. Agent cannot bypass programmatically — requires UI strategy or human-in-loop.',
|
|
43
|
+
},
|
|
44
|
+
];
|
|
45
|
+
export function detectAntiBot(signals) {
|
|
46
|
+
const evidence = [];
|
|
47
|
+
let match = null;
|
|
48
|
+
for (const sig of WAF_SIGNATURES) {
|
|
49
|
+
const hits = [];
|
|
50
|
+
for (const pat of sig.cookiePatterns) {
|
|
51
|
+
const hit = signals.cookieNames.find((c) => pat.test(c));
|
|
52
|
+
if (hit)
|
|
53
|
+
hits.push(`cookie:${hit}`);
|
|
54
|
+
}
|
|
55
|
+
for (const pat of sig.bodyPatterns) {
|
|
56
|
+
for (const entry of signals.networkEntries) {
|
|
57
|
+
if (entry.bodyPreview && pat.test(entry.bodyPreview)) {
|
|
58
|
+
hits.push(`body:${entry.url}`);
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (hits.length > 0 && !match) {
|
|
64
|
+
match = sig;
|
|
65
|
+
evidence.push(...hits);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (!match) {
|
|
69
|
+
return {
|
|
70
|
+
detected: false,
|
|
71
|
+
vendor: null,
|
|
72
|
+
evidence: [],
|
|
73
|
+
implication: 'No known anti-bot signatures. Try Node-side COOKIE fetch first; if endpoint validation is blocked, retry from browser context.',
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
detected: true,
|
|
78
|
+
vendor: match.vendor,
|
|
79
|
+
evidence,
|
|
80
|
+
implication: match.implication,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Apply the decision tree from `site-recon.md` mechanically.
|
|
85
|
+
*
|
|
86
|
+
* B beats A when initial-state globals are present: even if the page fetches
|
|
87
|
+
* more data via XHR afterwards, the SSR payload is the highest-leverage source.
|
|
88
|
+
* D (token-gated) dominates when we see 401/403 on what looks like API
|
|
89
|
+
* endpoints — without that, an authenticated route looks identical to A.
|
|
90
|
+
*/
|
|
91
|
+
export function classifyPattern(signals) {
|
|
92
|
+
const jsonEntries = signals.networkEntries.filter((e) => /json/i.test(e.contentType));
|
|
93
|
+
const authFailures = signals.networkEntries.filter((e) => e.status === 401 || e.status === 403).length;
|
|
94
|
+
const hasInitialState = signals.initialState.__INITIAL_STATE__ ||
|
|
95
|
+
signals.initialState.__NUXT__ ||
|
|
96
|
+
signals.initialState.__NEXT_DATA__ ||
|
|
97
|
+
signals.initialState.__APOLLO_STATE__;
|
|
98
|
+
if (authFailures >= 2 && jsonEntries.length >= 1) {
|
|
99
|
+
return {
|
|
100
|
+
pattern: 'D',
|
|
101
|
+
reason: `${authFailures} auth-failing API responses seen — endpoint is token-gated`,
|
|
102
|
+
json_responses: jsonEntries.length,
|
|
103
|
+
auth_failures: authFailures,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
if (hasInitialState) {
|
|
107
|
+
const which = Object.entries(signals.initialState)
|
|
108
|
+
.filter(([, v]) => v)
|
|
109
|
+
.map(([k]) => k);
|
|
110
|
+
return {
|
|
111
|
+
pattern: 'B',
|
|
112
|
+
reason: `SSR state global present: ${which.join(', ')}`,
|
|
113
|
+
json_responses: jsonEntries.length,
|
|
114
|
+
auth_failures: authFailures,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
if (jsonEntries.length >= 1) {
|
|
118
|
+
return {
|
|
119
|
+
pattern: 'A',
|
|
120
|
+
reason: `${jsonEntries.length} JSON XHR/fetch responses observed — classic API pattern`,
|
|
121
|
+
json_responses: jsonEntries.length,
|
|
122
|
+
auth_failures: authFailures,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
// No API, no SSR state — probably static HTML or a bundled SPA that lazy-loads.
|
|
126
|
+
// Pattern C (HTML scrape) is the default fallback; E (streaming) we can't
|
|
127
|
+
// reliably detect without watching WebSocket frames, so we label 'C' and
|
|
128
|
+
// leave the agent to upgrade to E manually if they see WS traffic.
|
|
129
|
+
return {
|
|
130
|
+
pattern: 'C',
|
|
131
|
+
reason: 'No JSON XHR and no SSR state — HTML scrape (Pattern C); escalate to E manually if WebSocket traffic appears',
|
|
132
|
+
json_responses: jsonEntries.length,
|
|
133
|
+
auth_failures: authFailures,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Find existing adapters that target the same site.
|
|
138
|
+
*
|
|
139
|
+
* Keep the hostname match simple — agents extend naming conventions
|
|
140
|
+
* differently per site, so we match on the registered `domain` field and fall
|
|
141
|
+
* back to site-name containment. Returning `null` is fine; agents can always
|
|
142
|
+
* read site-memory docs.
|
|
143
|
+
*/
|
|
144
|
+
export function findNearestAdapter(finalUrl, registry) {
|
|
145
|
+
let host;
|
|
146
|
+
try {
|
|
147
|
+
host = new URL(finalUrl).hostname;
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
// Strip leading www.; 'www' as a site identifier is never what an adapter uses.
|
|
153
|
+
const cleanedHost = host.replace(/^www\./, '');
|
|
154
|
+
// Extract apex (xx.com) and registrable parts for fuzzy match.
|
|
155
|
+
const parts = cleanedHost.split('.');
|
|
156
|
+
const apex = parts.slice(-2).join('.');
|
|
157
|
+
const siteKey = parts.length > 1 ? parts[parts.length - 2] : cleanedHost;
|
|
158
|
+
const hits = new Map();
|
|
159
|
+
for (const cmd of registry.values()) {
|
|
160
|
+
const domain = cmd.domain?.toLowerCase();
|
|
161
|
+
const siteMatches = (domain && (cleanedHost.endsWith(domain) || domain.endsWith(apex))) ||
|
|
162
|
+
cmd.site.toLowerCase() === siteKey?.toLowerCase() ||
|
|
163
|
+
cleanedHost.includes(cmd.site.toLowerCase());
|
|
164
|
+
if (siteMatches) {
|
|
165
|
+
const list = hits.get(cmd.site) ?? [];
|
|
166
|
+
list.push(cmd);
|
|
167
|
+
hits.set(cmd.site, list);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (hits.size === 0)
|
|
171
|
+
return null;
|
|
172
|
+
// Pick the site with the most commands — likely the most-developed adapter,
|
|
173
|
+
// and the best reference for a new command on the same host.
|
|
174
|
+
let best = null;
|
|
175
|
+
for (const entry of hits) {
|
|
176
|
+
if (!best || entry[1].length > best[1].length)
|
|
177
|
+
best = entry;
|
|
178
|
+
}
|
|
179
|
+
if (!best)
|
|
180
|
+
return null;
|
|
181
|
+
return {
|
|
182
|
+
site: best[0],
|
|
183
|
+
example_commands: best[1].slice(0, 5).map((c) => `${c.site} ${c.name}`),
|
|
184
|
+
reason: `${best[1].length} existing adapter${best[1].length === 1 ? '' : 's'} target this site — reuse strategy/cookie config`,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Synthesize the verdict from collected signals + registry.
|
|
189
|
+
*
|
|
190
|
+
* The `recommended_next_step` is deliberately a single imperative
|
|
191
|
+
* sentence — agents act on it directly instead of re-deriving advice from
|
|
192
|
+
* the structured fields.
|
|
193
|
+
*/
|
|
194
|
+
export function analyzeSite(signals, registry) {
|
|
195
|
+
const pattern = classifyPattern(signals);
|
|
196
|
+
const antiBot = detectAntiBot(signals);
|
|
197
|
+
const nearest = findNearestAdapter(signals.finalUrl, registry);
|
|
198
|
+
let next;
|
|
199
|
+
if (antiBot.detected) {
|
|
200
|
+
next = antiBot.implication;
|
|
201
|
+
}
|
|
202
|
+
else if (pattern.pattern === 'A') {
|
|
203
|
+
next = 'Pick the most specific JSON endpoint from `opencli browser network` and try a bare Node fetch with cookies; escalate to browser-context fetch only if blocked.';
|
|
204
|
+
}
|
|
205
|
+
else if (pattern.pattern === 'B') {
|
|
206
|
+
next = 'Read the SSR global via `opencli browser eval "JSON.stringify(window.__INITIAL_STATE__ ?? window.__NUXT__ ?? window.__NEXT_DATA__ ?? window.__APOLLO_STATE__)"` — no API needed.';
|
|
207
|
+
}
|
|
208
|
+
else if (pattern.pattern === 'C') {
|
|
209
|
+
next = 'No API visible — use SSR HTML scrape (e.g. `opencli browser extract`) against the rendered page.';
|
|
210
|
+
}
|
|
211
|
+
else if (pattern.pattern === 'D') {
|
|
212
|
+
next = 'Endpoints need auth. Re-open the page from a signed-in session, then retry analyze; see `field-decode-playbook` §4 for token tracing.';
|
|
213
|
+
}
|
|
214
|
+
else if (pattern.pattern === 'E') {
|
|
215
|
+
next = 'WebSocket stream detected — find the underlying HTTP poll/long-poll endpoint; raw WS is not supported.';
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
next = 'No strong signal. Manually inspect `opencli browser network --all` and pick a pattern.';
|
|
219
|
+
}
|
|
220
|
+
return {
|
|
221
|
+
requested_url: signals.requestedUrl,
|
|
222
|
+
final_url: signals.finalUrl,
|
|
223
|
+
title: signals.title,
|
|
224
|
+
pattern,
|
|
225
|
+
anti_bot: antiBot,
|
|
226
|
+
initial_state: signals.initialState,
|
|
227
|
+
nearest_adapter: nearest,
|
|
228
|
+
recommended_next_step: next,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { analyzeSite, detectAntiBot, classifyPattern, findNearestAdapter, } from './analyze.js';
|
|
3
|
+
function mkSignals(overrides = {}) {
|
|
4
|
+
return {
|
|
5
|
+
requestedUrl: 'https://example.com/',
|
|
6
|
+
finalUrl: 'https://example.com/',
|
|
7
|
+
cookieNames: [],
|
|
8
|
+
networkEntries: [],
|
|
9
|
+
initialState: {
|
|
10
|
+
__INITIAL_STATE__: false,
|
|
11
|
+
__NUXT__: false,
|
|
12
|
+
__NEXT_DATA__: false,
|
|
13
|
+
__APOLLO_STATE__: false,
|
|
14
|
+
},
|
|
15
|
+
title: 'Example',
|
|
16
|
+
...overrides,
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function mkCmd(site, name, domain) {
|
|
20
|
+
return {
|
|
21
|
+
site,
|
|
22
|
+
name,
|
|
23
|
+
description: '',
|
|
24
|
+
domain,
|
|
25
|
+
args: [],
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
describe('detectAntiBot', () => {
|
|
29
|
+
it('flags Aliyun WAF from cookie', () => {
|
|
30
|
+
const v = detectAntiBot(mkSignals({ cookieNames: ['JSESSIONID', 'acw_sc__v2'] }));
|
|
31
|
+
expect(v.detected).toBe(true);
|
|
32
|
+
expect(v.vendor).toBe('aliyun_waf');
|
|
33
|
+
expect(v.evidence).toContain('cookie:acw_sc__v2');
|
|
34
|
+
expect(v.implication).toMatch(/browser context/i);
|
|
35
|
+
});
|
|
36
|
+
it('flags Aliyun WAF from challenge HTML body', () => {
|
|
37
|
+
const v = detectAntiBot(mkSignals({
|
|
38
|
+
networkEntries: [
|
|
39
|
+
{
|
|
40
|
+
url: 'https://x.com/',
|
|
41
|
+
status: 200,
|
|
42
|
+
contentType: 'text/html',
|
|
43
|
+
bodyPreview: "var arg1 = 'A1B2C3D4E5F6A7B8C9D0E1F2A3B4C5D6';",
|
|
44
|
+
},
|
|
45
|
+
],
|
|
46
|
+
}));
|
|
47
|
+
expect(v.detected).toBe(true);
|
|
48
|
+
expect(v.vendor).toBe('aliyun_waf');
|
|
49
|
+
});
|
|
50
|
+
it('flags Cloudflare from cf_clearance cookie', () => {
|
|
51
|
+
const v = detectAntiBot(mkSignals({ cookieNames: ['cf_clearance'] }));
|
|
52
|
+
expect(v.vendor).toBe('cloudflare');
|
|
53
|
+
expect(v.implication).toMatch(/Cloudflare/i);
|
|
54
|
+
});
|
|
55
|
+
it('flags Akamai from _abck cookie', () => {
|
|
56
|
+
const v = detectAntiBot(mkSignals({ cookieNames: ['_abck', 'bm_sz'] }));
|
|
57
|
+
expect(v.vendor).toBe('akamai');
|
|
58
|
+
});
|
|
59
|
+
it('returns no-match verdict with actionable fallback advice', () => {
|
|
60
|
+
const v = detectAntiBot(mkSignals());
|
|
61
|
+
expect(v.detected).toBe(false);
|
|
62
|
+
expect(v.vendor).toBeNull();
|
|
63
|
+
expect(v.implication).toMatch(/Node-side COOKIE fetch first/);
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
describe('classifyPattern', () => {
|
|
67
|
+
it('returns A for JSON-heavy pages without SSR state', () => {
|
|
68
|
+
const v = classifyPattern(mkSignals({
|
|
69
|
+
networkEntries: [
|
|
70
|
+
{ url: 'https://x.com/api/a', status: 200, contentType: 'application/json', bodyPreview: '{}' },
|
|
71
|
+
{ url: 'https://x.com/api/b', status: 200, contentType: 'application/json;charset=utf-8', bodyPreview: '{}' },
|
|
72
|
+
],
|
|
73
|
+
}));
|
|
74
|
+
expect(v.pattern).toBe('A');
|
|
75
|
+
expect(v.json_responses).toBe(2);
|
|
76
|
+
});
|
|
77
|
+
it('returns B when __INITIAL_STATE__ is present, beating JSON signals', () => {
|
|
78
|
+
const v = classifyPattern(mkSignals({
|
|
79
|
+
initialState: { __INITIAL_STATE__: true, __NUXT__: false, __NEXT_DATA__: false, __APOLLO_STATE__: false },
|
|
80
|
+
networkEntries: [
|
|
81
|
+
{ url: 'https://x.com/api/a', status: 200, contentType: 'application/json', bodyPreview: '{}' },
|
|
82
|
+
],
|
|
83
|
+
}));
|
|
84
|
+
expect(v.pattern).toBe('B');
|
|
85
|
+
});
|
|
86
|
+
it('returns D when auth failures dominate', () => {
|
|
87
|
+
const v = classifyPattern(mkSignals({
|
|
88
|
+
networkEntries: [
|
|
89
|
+
{ url: 'https://x.com/api/a', status: 401, contentType: 'application/json', bodyPreview: '' },
|
|
90
|
+
{ url: 'https://x.com/api/b', status: 403, contentType: 'application/json', bodyPreview: '' },
|
|
91
|
+
],
|
|
92
|
+
}));
|
|
93
|
+
expect(v.pattern).toBe('D');
|
|
94
|
+
expect(v.auth_failures).toBe(2);
|
|
95
|
+
});
|
|
96
|
+
it('returns C by default for static pages', () => {
|
|
97
|
+
const v = classifyPattern(mkSignals());
|
|
98
|
+
expect(v.pattern).toBe('C');
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
describe('findNearestAdapter', () => {
|
|
102
|
+
it('matches by domain suffix', () => {
|
|
103
|
+
const reg = new Map([
|
|
104
|
+
['51job search', mkCmd('51job', 'search', '51job.com')],
|
|
105
|
+
['51job detail', mkCmd('51job', 'detail', '51job.com')],
|
|
106
|
+
['xueqiu search', mkCmd('xueqiu', 'search', 'xueqiu.com')],
|
|
107
|
+
]);
|
|
108
|
+
const v = findNearestAdapter('https://jobs.51job.com/', reg);
|
|
109
|
+
expect(v?.site).toBe('51job');
|
|
110
|
+
expect(v?.example_commands).toContain('51job search');
|
|
111
|
+
});
|
|
112
|
+
it('falls back to site-name containment when no domain is registered', () => {
|
|
113
|
+
const reg = new Map([
|
|
114
|
+
['51job search', mkCmd('51job', 'search')],
|
|
115
|
+
]);
|
|
116
|
+
const v = findNearestAdapter('https://we.51job.com/', reg);
|
|
117
|
+
expect(v?.site).toBe('51job');
|
|
118
|
+
});
|
|
119
|
+
it('returns null when no adapter matches', () => {
|
|
120
|
+
const reg = new Map([
|
|
121
|
+
['xueqiu search', mkCmd('xueqiu', 'search', 'xueqiu.com')],
|
|
122
|
+
]);
|
|
123
|
+
const v = findNearestAdapter('https://random-site.io/', reg);
|
|
124
|
+
expect(v).toBeNull();
|
|
125
|
+
});
|
|
126
|
+
it('prefers the site with the most commands', () => {
|
|
127
|
+
const reg = new Map([
|
|
128
|
+
['a search', mkCmd('a', 'search', 'a.com')],
|
|
129
|
+
['b search', mkCmd('b', 'search', 'a.com')],
|
|
130
|
+
['b detail', mkCmd('b', 'detail', 'a.com')],
|
|
131
|
+
['b company', mkCmd('b', 'company', 'a.com')],
|
|
132
|
+
]);
|
|
133
|
+
const v = findNearestAdapter('https://jobs.a.com/', reg);
|
|
134
|
+
expect(v?.site).toBe('b');
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
describe('analyzeSite', () => {
|
|
138
|
+
it('recommends browser-context fetch when WAF is detected', () => {
|
|
139
|
+
const report = analyzeSite(mkSignals({ cookieNames: ['acw_sc__v2'] }), new Map());
|
|
140
|
+
expect(report.anti_bot.vendor).toBe('aliyun_waf');
|
|
141
|
+
expect(report.recommended_next_step).toMatch(/browser context/i);
|
|
142
|
+
});
|
|
143
|
+
it('recommends reading SSR state when Pattern B fires', () => {
|
|
144
|
+
const report = analyzeSite(mkSignals({
|
|
145
|
+
initialState: { __INITIAL_STATE__: false, __NUXT__: true, __NEXT_DATA__: false, __APOLLO_STATE__: false },
|
|
146
|
+
}), new Map());
|
|
147
|
+
expect(report.pattern.pattern).toBe('B');
|
|
148
|
+
expect(report.recommended_next_step).toMatch(/__NUXT__|__INITIAL_STATE__|__NEXT_DATA__/);
|
|
149
|
+
});
|
|
150
|
+
it('includes __APOLLO_STATE__ in Pattern B next-step guidance', () => {
|
|
151
|
+
const report = analyzeSite(mkSignals({
|
|
152
|
+
initialState: { __INITIAL_STATE__: false, __NUXT__: false, __NEXT_DATA__: false, __APOLLO_STATE__: true },
|
|
153
|
+
}), new Map());
|
|
154
|
+
expect(report.pattern.pattern).toBe('B');
|
|
155
|
+
expect(report.recommended_next_step).toMatch(/__APOLLO_STATE__/);
|
|
156
|
+
});
|
|
157
|
+
it('includes nearest_adapter when the registry has a match', () => {
|
|
158
|
+
const reg = new Map([
|
|
159
|
+
['51job search', mkCmd('51job', 'search', '51job.com')],
|
|
160
|
+
]);
|
|
161
|
+
const report = analyzeSite(mkSignals({ finalUrl: 'https://we.51job.com/' }), reg);
|
|
162
|
+
expect(report.nearest_adapter?.site).toBe('51job');
|
|
163
|
+
});
|
|
164
|
+
});
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Article extraction via Readability — generic `page → article HTML` pipeline.
|
|
3
|
+
*
|
|
4
|
+
* Complements `src/browser/extract.ts`: that one takes a caller-supplied
|
|
5
|
+
* selector. This one works with zero configuration on arbitrary article pages
|
|
6
|
+
* (blogs, news, docs) by running `@mozilla/readability` inside the page
|
|
7
|
+
* context via CDP evaluate.
|
|
8
|
+
*
|
|
9
|
+
* Pipeline:
|
|
10
|
+
* 1. Short-circuit non-HTML documents (`text/plain`, JSON, XML) — a page
|
|
11
|
+
* renderer wrapping a plain-text file would pollute the DOM pipeline.
|
|
12
|
+
* 2. Short-circuit the "body is a single <pre>" case, which browsers use
|
|
13
|
+
* when loading *.txt / *.md over file:// or raw.githubusercontent.com.
|
|
14
|
+
* 3. Deep-clone the document, apply caller-supplied `cleanSelectors` to the
|
|
15
|
+
* clone (preserves live page state for subsequent snapshot/click).
|
|
16
|
+
* 4. Inject Readability + isProbablyReaderable sources into the page,
|
|
17
|
+
* parse on the clone. `isProbablyReaderable` gates the parse unless
|
|
18
|
+
* `force: true`.
|
|
19
|
+
* 5. On Readability miss, walk a fallback selector chain
|
|
20
|
+
* (main → [role="main"] → #main-content → … → body) and return the
|
|
21
|
+
* first root with >80 characters of text.
|
|
22
|
+
*
|
|
23
|
+
* Readability runs in the page's own window because it needs real DOM APIs
|
|
24
|
+
* (getComputedStyle, treeWalker). Running it Node-side would require jsdom —
|
|
25
|
+
* a heavy dep the rest of OpenCLI doesn't need.
|
|
26
|
+
*/
|
|
27
|
+
export interface ExtractArticleOptions {
|
|
28
|
+
/** CSS selectors removed from the cloned document before Readability runs. */
|
|
29
|
+
cleanSelectors?: string[];
|
|
30
|
+
/** Fallback chain when Readability fails. Defaults to the common structural ids. */
|
|
31
|
+
fallbackSelectors?: string[];
|
|
32
|
+
/** Bypass `isProbablyReaderable` and always attempt a parse. */
|
|
33
|
+
force?: boolean;
|
|
34
|
+
}
|
|
35
|
+
export type ExtractSource = 'readability' | 'fallback' | 'raw-text' | 'pre';
|
|
36
|
+
export interface ExtractedArticle {
|
|
37
|
+
html: string;
|
|
38
|
+
title: string;
|
|
39
|
+
byline?: string;
|
|
40
|
+
publishedTime?: string;
|
|
41
|
+
siteName?: string;
|
|
42
|
+
source: ExtractSource;
|
|
43
|
+
}
|
|
44
|
+
export declare const DEFAULT_FALLBACK_SELECTORS: string[];
|
|
45
|
+
/**
|
|
46
|
+
* Build the JS expression evaluated in-page to extract the article. Exported
|
|
47
|
+
* for testability — callers on the host side should use `extractArticle`.
|
|
48
|
+
*/
|
|
49
|
+
export declare function buildExtractArticleJs(options?: ExtractArticleOptions): string;
|
|
50
|
+
export interface PageLike {
|
|
51
|
+
evaluate(js: string): Promise<unknown>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Run the extract pipeline on the given page. Returns `null` when no usable
|
|
55
|
+
* content is found (Readability miss + empty fallback chain).
|
|
56
|
+
*/
|
|
57
|
+
export declare function extractArticle(page: PageLike, options?: ExtractArticleOptions): Promise<ExtractedArticle | null>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|