@capyclaw/scrapling 1.1.0 → 1.1.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 +7 -6
- package/client/client.js +129 -19
- package/cordis.patch.yml +4 -2
- package/lib/host.mjs +51 -27
- package/package.json +4 -3
- package/server/server.mjs +25 -36
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ Scrapling 网页抓取插件 —— 为 DeepSeek Harness 提供网页数据爬
|
|
|
14
14
|
- `:first-child` / `:last-child` / `:nth-child(k)`
|
|
15
15
|
- 逗号分组按文档序合并去重(XPath union 语义)
|
|
16
16
|
- 支持中文类名/属性值
|
|
17
|
-
-
|
|
17
|
+
- **爬虫工作台**(默认 `http://127.0.0.1:39640/`,端口由 broker 管理)—— 浏览器打开即用:
|
|
18
18
|
- 三步引导:选目标 → 观察流程 → 取数据
|
|
19
19
|
- 爬取流程逐步回放(每步真实耗时:解析 URL → 发请求 → 收响应 → 读内容 → 建文档树 → 提取 → 完成)
|
|
20
20
|
- 选择器试玩(随时改随时提取,不重新请求)
|
|
@@ -37,8 +37,9 @@ node server/server.mjs # 默认 http://127.0.0.1:39640/
|
|
|
37
37
|
# 或指定端口
|
|
38
38
|
node server/server.mjs --port 39641
|
|
39
39
|
|
|
40
|
-
# 方式二:作为 DSH
|
|
41
|
-
# cordis.patch.yml
|
|
40
|
+
# 方式二:作为 DSH 插件加载
|
|
41
|
+
# cordis.patch.yml 会加载 service-broker;Scrapling 通过 ctx.serviceBroker
|
|
42
|
+
# 投递独立工作台服务,Cordis 进程本身不监听业务端口。
|
|
42
43
|
|
|
43
44
|
# 单元测试(32 项)
|
|
44
45
|
npm test
|
|
@@ -78,7 +79,7 @@ export async function apply(ctx) {
|
|
|
78
79
|
|
|
79
80
|
| 接口 | 方法 | 说明 |
|
|
80
81
|
|---|---|---|
|
|
81
|
-
| `/healthz` | GET | `{ ok,
|
|
82
|
+
| `/healthz` | GET | 标准 `{ ok, service, pid, port }` + `{ name, version, contractVersion, crawls, capabilities }` |
|
|
82
83
|
| `/metrics` | GET | Prometheus 文本(`scrapling_up` / `scrapling_crawls_total` 等) |
|
|
83
84
|
| `/api/crawl` | POST | `{ url, timeoutMs?, userAgent?, selectors?: [{key, selector}] }` → 步骤流水线 + 提取结果 |
|
|
84
85
|
| `/api/extract` | POST | `{ crawlId, selectors }` 基于历史记录二次提取(免重新请求) |
|
|
@@ -93,7 +94,7 @@ export async function apply(ctx) {
|
|
|
93
94
|
| 配置 | 环境变量 | 默认 | 说明 |
|
|
94
95
|
|---|---|---|---|
|
|
95
96
|
| `enabled` | `DSH_SCRAPLING_ENABLED` | `true` | 是否注册服务与工作台 |
|
|
96
|
-
| `port` | `DSH_SCRAPLING_PORT` | `
|
|
97
|
+
| `port` | `DSH_SCRAPLING_PORT` | `auto` | 工作台端口(`auto` 由 broker 分配;手动直启默认 39640) |
|
|
97
98
|
| `host` | `DSH_SCRAPLING_HOST` | `127.0.0.1` | 监听地址 |
|
|
98
99
|
| `timeoutMs` | `DSH_SCRAPLING_TIMEOUT_MS` | `20000` | 默认请求超时 |
|
|
99
100
|
| `workbench` | `DSH_SCRAPLING_WORKBENCH` | `true` | 是否拉起工作台界面 |
|
|
@@ -103,7 +104,7 @@ export async function apply(ctx) {
|
|
|
103
104
|
```
|
|
104
105
|
capyclaw-scrapling/
|
|
105
106
|
├── lib/
|
|
106
|
-
│ ├── host.mjs # Cordis
|
|
107
|
+
│ ├── host.mjs # Cordis 入口:注册 fetch/parse API + broker 投递工作台 + boot 全局注入
|
|
107
108
|
│ ├── index.mjs # API 导出
|
|
108
109
|
│ ├── html-parser.mjs # 容错 HTML 解析器(单遍、隐式闭合、实体解码)
|
|
109
110
|
│ ├── selectors.mjs # CSS 选择器引擎(parsel 语义)
|
package/client/client.js
CHANGED
|
@@ -1,42 +1,152 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* dsh-scrapling 浏览器半
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* 装载协议与 tsdown 客户端产物一致:`window.__ModuleLoader__.load({ id, factory })`,
|
|
5
|
+
* factory 内以 CJS 组装 Cordis 插件并返回 module.exports。
|
|
6
|
+
*
|
|
7
|
+
* 面板注册协议与 dsh-port-sidebar(0.2.0 实测基线)对齐:
|
|
8
|
+
* 1. inject slots + sidebarRight + sidebarRightTabs 三个服务;
|
|
9
|
+
* 2. 注册自有 tab 类型(kind 唯一、keepMounted 保活 iframe);
|
|
10
|
+
* 3. 注册正文/标题两个插槽(正文即指向工作台的 iframe);
|
|
11
|
+
* 4. 主动 openTab 打开(会话 store 未就绪时分档重试)。
|
|
12
|
+
*
|
|
13
|
+
* 宿主半把工作台地址注入为 __DSH_SCRAPLING__(webserver/index-inject)。
|
|
14
|
+
* 直接用浏览器打开工作台(无 DSH web 客户端)时本文件不产生任何副作用。
|
|
7
15
|
*/
|
|
8
16
|
window.__ModuleLoader__.load({ id: '@capyclaw/scrapling', factory: (require) => {
|
|
9
17
|
var module = { exports: {} }; var exports = module.exports;
|
|
10
18
|
|
|
19
|
+
var React = require('react')
|
|
20
|
+
|
|
21
|
+
/** 本插件在 tab 系统里的实现 id(正文/标题插槽的 key)。 */
|
|
22
|
+
var TAB_ID = 'dsh-scrapling-workbench'
|
|
23
|
+
/** 本插件独占的 tab kind。 */
|
|
24
|
+
var TAB_KIND = 'scraplingWorkbench'
|
|
25
|
+
/** tab 标题。 */
|
|
26
|
+
var TAB_TITLE = '爬虫工作台'
|
|
27
|
+
/** 打开重试档位(避开 mounted→store 铸造窗口,同 port-sidebar 基线)。 */
|
|
28
|
+
var RETRY_DELAYS_MS = [0, 200, 1000]
|
|
29
|
+
|
|
11
30
|
module.exports = {
|
|
12
31
|
name: 'dsh-scrapling',
|
|
13
|
-
inject: ['slots'],
|
|
32
|
+
inject: ['slots', 'sidebarRight', 'sidebarRightTabs'],
|
|
14
33
|
apply: function (ctx) {
|
|
15
34
|
var boot = globalThis.__DSH_SCRAPLING__
|
|
16
|
-
if (!boot ||
|
|
17
|
-
console.
|
|
35
|
+
if (!boot || typeof boot.url !== 'string') {
|
|
36
|
+
console.warn('[dsh-scrapling] 页面未收到 __DSH_SCRAPLING__(宿主半未加载或工作台未启动),跳过面板注册;可直接访问 http://127.0.0.1:39640/')
|
|
18
37
|
return
|
|
19
38
|
}
|
|
39
|
+
var url = boot.url
|
|
40
|
+
var disposed = false
|
|
41
|
+
var retryTimers = []
|
|
42
|
+
/** 诊断出口(自动化/控制台核对用)。 */
|
|
43
|
+
var diag = { plugin: 'applied', opened: 0, lastError: null, events: [] }
|
|
44
|
+
globalThis.__DSH_SCRAPLING_DEBUG__ = diag
|
|
45
|
+
function note(event) {
|
|
46
|
+
diag.events.push(event + '@' + Date.now())
|
|
47
|
+
if (diag.events.length > 40) diag.events.shift()
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 正文:指向工作台的 iframe。背景取页面主题色,消除加载期白闪。 */
|
|
51
|
+
function createBody(targetUrl) {
|
|
52
|
+
var bg = 'transparent'
|
|
53
|
+
try {
|
|
54
|
+
var cs = getComputedStyle(document.body)
|
|
55
|
+
if (cs && cs.backgroundColor && cs.backgroundColor !== 'rgba(0, 0, 0, 0)') bg = cs.backgroundColor
|
|
56
|
+
} catch (error) { /* 拿不到就用透明 */ }
|
|
57
|
+
return function ScraplingBody() {
|
|
58
|
+
return React.createElement('iframe', {
|
|
59
|
+
src: targetUrl,
|
|
60
|
+
title: TAB_TITLE,
|
|
61
|
+
style: { width: '100%', height: '100%', border: '0', display: 'block', background: bg },
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function ScraplingTitle() {
|
|
67
|
+
return React.createElement('span', null, TAB_TITLE)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/* 1. 注册 tab 类型(kind 唯一 → 关闭回调/清单检查精确命中;keepMounted 切 tab 不重载) */
|
|
71
|
+
ctx.effect(function () {
|
|
72
|
+
return ctx.sidebarRightTabs.register({
|
|
73
|
+
id: TAB_ID,
|
|
74
|
+
kind: TAB_KIND,
|
|
75
|
+
keepMounted: true,
|
|
76
|
+
priority: 'extension',
|
|
77
|
+
title: function () { return TAB_TITLE },
|
|
78
|
+
})
|
|
79
|
+
}, 'dsh-scrapling.type')
|
|
20
80
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
src: boot.url,
|
|
26
|
-
title: 'DSH 爬虫工作台',
|
|
27
|
-
style: { width: '100%', height: '100%', border: 'none' },
|
|
81
|
+
/* 2. 正文插槽 */
|
|
82
|
+
ctx.effect(function () {
|
|
83
|
+
return ctx.slots.inject('sidebar.right.pane.tab', function () {
|
|
84
|
+
return ctx.slots.register({ name: 'sidebar.right.pane.tab', key: TAB_ID }, createBody(url))
|
|
28
85
|
})
|
|
29
|
-
|
|
30
|
-
|
|
86
|
+
}, 'dsh-scrapling.body')
|
|
87
|
+
|
|
88
|
+
/* 3. 标题插槽 */
|
|
89
|
+
ctx.effect(function () {
|
|
90
|
+
return ctx.slots.inject('sidebar.right.pane.tab.title', function () {
|
|
91
|
+
return ctx.slots.register({ name: 'sidebar.right.pane.tab.title', key: TAB_ID }, ScraplingTitle)
|
|
31
92
|
})
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
93
|
+
}, 'dsh-scrapling.title')
|
|
94
|
+
|
|
95
|
+
/* 4. 打开 tab:会话 store 未就绪(mounted === undefined)时分档重试 */
|
|
96
|
+
function openWorkbenchTab() {
|
|
97
|
+
diag.opened += 1
|
|
98
|
+
note('open')
|
|
99
|
+
ctx.sidebarRight.openTab(TAB_KIND, { revealIfOpened: true })
|
|
35
100
|
}
|
|
36
101
|
|
|
102
|
+
function tryOpen(tier) {
|
|
103
|
+
if (disposed) return
|
|
104
|
+
var sessionId
|
|
105
|
+
try {
|
|
106
|
+
sessionId = ctx.sidebarRight.mounted.getSnapshot()
|
|
107
|
+
} catch (error) {
|
|
108
|
+
sessionId = undefined
|
|
109
|
+
}
|
|
110
|
+
if (sessionId === undefined) return schedule(tier)
|
|
111
|
+
try {
|
|
112
|
+
openWorkbenchTab()
|
|
113
|
+
} catch (error) {
|
|
114
|
+
diag.lastError = String(error)
|
|
115
|
+
note('openFail:' + String(error).slice(0, 40))
|
|
116
|
+
schedule(tier)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function schedule(tier) {
|
|
121
|
+
if (disposed || tier >= RETRY_DELAYS_MS.length) return
|
|
122
|
+
if (retryTimers[tier] !== null && retryTimers[tier] !== undefined) return
|
|
123
|
+
retryTimers[tier] = setTimeout(function () {
|
|
124
|
+
retryTimers[tier] = null
|
|
125
|
+
tryOpen(tier + 1)
|
|
126
|
+
}, RETRY_DELAYS_MS[tier])
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/* 会话切换后在新会话补开一次(静默,不抢焦点) */
|
|
130
|
+
var unsubscribeMounted = ctx.sidebarRight.mounted.subscribe(function () {
|
|
131
|
+
try {
|
|
132
|
+
var mounted = ctx.sidebarRight.mounted.getSnapshot()
|
|
133
|
+
if (mounted === undefined) return
|
|
134
|
+
var has = ctx.sidebarRight.openTabs.getSnapshot().some(function (t) {
|
|
135
|
+
return t.sessionId === mounted && t.kind === TAB_KIND
|
|
136
|
+
})
|
|
137
|
+
if (!has) tryOpen(0)
|
|
138
|
+
} catch (error) { /* 清单暂不可读时留给下次订阅 */ }
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
tryOpen(0)
|
|
142
|
+
|
|
37
143
|
ctx.effect(function () {
|
|
38
144
|
return function () {
|
|
39
|
-
|
|
145
|
+
disposed = true
|
|
146
|
+
unsubscribeMounted()
|
|
147
|
+
for (var i = 0; i < retryTimers.length; i++) {
|
|
148
|
+
if (retryTimers[i] !== null && retryTimers[i] !== undefined) clearTimeout(retryTimers[i])
|
|
149
|
+
}
|
|
40
150
|
}
|
|
41
151
|
})
|
|
42
152
|
},
|
package/cordis.patch.yml
CHANGED
|
@@ -3,14 +3,16 @@
|
|
|
3
3
|
#
|
|
4
4
|
# 配置项(cordis config → 环境变量 DSH_SCRAPLING_* → 默认值):
|
|
5
5
|
# enabled 是否启用 DSH_SCRAPLING_ENABLED true
|
|
6
|
-
# port 工作台端口 DSH_SCRAPLING_PORT
|
|
6
|
+
# port 工作台端口 DSH_SCRAPLING_PORT auto(broker 分配;固定值需未被占用)
|
|
7
7
|
# host 监听地址 DSH_SCRAPLING_HOST 127.0.0.1
|
|
8
8
|
# timeoutMs 请求超时(ms) DSH_SCRAPLING_TIMEOUT_MS 20000
|
|
9
9
|
# workbench 是否拉起工作台 DSH_SCRAPLING_WORKBENCH true
|
|
10
10
|
|
|
11
11
|
- insert:
|
|
12
|
+
- id: service-broker
|
|
13
|
+
name: "@capyclaw/service-broker"
|
|
12
14
|
- id: scrapling-host
|
|
13
15
|
name: "@capyclaw/scrapling"
|
|
14
16
|
config:
|
|
15
17
|
enabled: true
|
|
16
|
-
port:
|
|
18
|
+
port: auto
|
package/lib/host.mjs
CHANGED
|
@@ -10,9 +10,9 @@
|
|
|
10
10
|
* scrapling,直接抛 NOT_IMPLEMENTED,不会伪造结果。
|
|
11
11
|
*
|
|
12
12
|
* 工作台服务(server/server.mjs):
|
|
13
|
-
* -
|
|
14
|
-
* - 依赖注入可选:workbench: false
|
|
15
|
-
* - 通过 webserver/index-inject 注入
|
|
13
|
+
* - 由 dsh-service-broker 作为独立进程管理;Cordis 进程不监听业务端口;
|
|
14
|
+
* - 依赖注入可选:workbench: false 可只注册进程内 fetch/parse API;
|
|
15
|
+
* - 通过 webserver/index-inject 注入 broker 返回的 URL,浏览器半挂面板。
|
|
16
16
|
*
|
|
17
17
|
* 配置(resolveConfig:ctx config → 环境变量 → 默认值):
|
|
18
18
|
* enabled 是否注册服务/界面 DSH_SCRAPLING_ENABLED 默认 true
|
|
@@ -31,6 +31,9 @@ import { createSelectorDocument } from './selectors.mjs'
|
|
|
31
31
|
|
|
32
32
|
export const name = '@capyclaw/scrapling'
|
|
33
33
|
export const DEFAULT_PORT = 39640
|
|
34
|
+
export const inject = ['serviceBroker']
|
|
35
|
+
|
|
36
|
+
const SERVICE_ID = 'scrapling-workbench'
|
|
34
37
|
|
|
35
38
|
function notImplemented(feature) {
|
|
36
39
|
const error = new Error(
|
|
@@ -46,14 +49,14 @@ export async function apply(ctx, config = {}) {
|
|
|
46
49
|
envPrefix: 'DSH_SCRAPLING',
|
|
47
50
|
defaults: {
|
|
48
51
|
enabled: true,
|
|
49
|
-
port:
|
|
52
|
+
port: 'auto',
|
|
50
53
|
host: '127.0.0.1',
|
|
51
54
|
timeoutMs: 20000,
|
|
52
55
|
workbench: true,
|
|
53
56
|
},
|
|
54
57
|
fields: {
|
|
55
58
|
enabled: { env: 'ENABLED', type: 'boolean' },
|
|
56
|
-
port: { env: 'PORT', type: '
|
|
59
|
+
port: { env: 'PORT', type: 'string' },
|
|
57
60
|
host: { env: 'HOST' },
|
|
58
61
|
timeoutMs: { env: 'TIMEOUT_MS', type: 'number' },
|
|
59
62
|
userAgent: { env: 'USER_AGENT' },
|
|
@@ -61,6 +64,11 @@ export async function apply(ctx, config = {}) {
|
|
|
61
64
|
},
|
|
62
65
|
})
|
|
63
66
|
for (const issue of issues) ctx.logger?.warn?.(`[dsh-scrapling] 配置: ${issue}`)
|
|
67
|
+
const port = cfg.port === 'auto' ? 'auto' : Number(cfg.port)
|
|
68
|
+
if (port !== 'auto' && (!Number.isInteger(port) || port < 1 || port > 65535)) {
|
|
69
|
+
ctx.logger?.warn?.(`[dsh-scrapling] 非法 port=${cfg.port},回退为 broker 自动分配`)
|
|
70
|
+
}
|
|
71
|
+
const servicePort = port === 'auto' || !Number.isInteger(port) || port < 1 || port > 65535 ? 'auto' : port
|
|
64
72
|
|
|
65
73
|
if (!cfg.enabled) {
|
|
66
74
|
ctx.logger?.info?.('[dsh-scrapling] 已按配置禁用,不注册 scrapling 服务')
|
|
@@ -97,28 +105,44 @@ export async function apply(ctx, config = {}) {
|
|
|
97
105
|
crawler,
|
|
98
106
|
})
|
|
99
107
|
|
|
100
|
-
/*
|
|
101
|
-
let
|
|
108
|
+
/* 工作台由 broker 独立拉起;Cordis 进程只注册 API 与 sidebar URL。 */
|
|
109
|
+
let serviceBroker = null
|
|
110
|
+
let stopServiceOnDispose = false
|
|
111
|
+
let serviceUrl = ''
|
|
102
112
|
if (cfg.workbench) {
|
|
103
|
-
const
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
113
|
+
const broker = ctx.serviceBroker
|
|
114
|
+
serviceBroker = broker || null
|
|
115
|
+
if (!broker || typeof broker.start !== 'function') {
|
|
116
|
+
ctx.logger?.warn?.('[dsh-scrapling] 缺少 ctx.serviceBroker,工作台未启动;fetch/parse API 仍可用')
|
|
117
|
+
} else {
|
|
118
|
+
const serviceFile = path.join(packageDir, 'server', 'server.mjs')
|
|
119
|
+
const spec = {
|
|
120
|
+
id: SERVICE_ID,
|
|
121
|
+
cmd: [process.execPath, serviceFile, '--port', '${PORT}', '--host', cfg.host],
|
|
122
|
+
env: {
|
|
123
|
+
DSH_SCRAPLING_TIMEOUT_MS: String(cfg.timeoutMs),
|
|
124
|
+
...(cfg.userAgent ? { DSH_SCRAPLING_USER_AGENT: String(cfg.userAgent) } : {}),
|
|
125
|
+
},
|
|
126
|
+
ports: { main: servicePort },
|
|
127
|
+
url: 'http://127.0.0.1:${PORT}',
|
|
128
|
+
healthPath: '/healthz',
|
|
129
|
+
keepAlive: true,
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const started = await broker.start(spec)
|
|
133
|
+
if (!started?.url) throw new Error('serviceBroker.start 未返回服务 url')
|
|
134
|
+
serviceUrl = started.url.replace(/\/$/, '')
|
|
135
|
+
stopServiceOnDispose = true
|
|
136
|
+
ctx.logger?.info?.(`[dsh-scrapling] broker 工作台已就绪: ${serviceUrl}/`)
|
|
137
|
+
ctx.on?.('webserver/index-inject', (table) => {
|
|
138
|
+
table.push({ kind: 'global', name: '__DSH_SCRAPLING__', value: { url: `${serviceUrl}/`, version: '1.1.1' } })
|
|
139
|
+
})
|
|
140
|
+
} catch (error) {
|
|
141
|
+
ctx.logger?.warn?.(`[dsh-scrapling] broker 工作台启动失败(fetch/parse API 仍可用): ${error.message}`)
|
|
142
|
+
}
|
|
119
143
|
}
|
|
120
144
|
} else {
|
|
121
|
-
ctx.logger?.info?.('[dsh-scrapling] workbench=false,仅注册 scrapling
|
|
145
|
+
ctx.logger?.info?.('[dsh-scrapling] workbench=false,仅注册 scrapling API,不投递服务')
|
|
122
146
|
}
|
|
123
147
|
|
|
124
148
|
ctx.logger?.info?.(
|
|
@@ -126,9 +150,9 @@ export async function apply(ctx, config = {}) {
|
|
|
126
150
|
)
|
|
127
151
|
|
|
128
152
|
return async () => {
|
|
129
|
-
if (
|
|
130
|
-
await
|
|
131
|
-
ctx.logger?.info?.('[dsh-scrapling]
|
|
153
|
+
if (stopServiceOnDispose && serviceBroker && typeof serviceBroker.stop === 'function') {
|
|
154
|
+
const result = await serviceBroker.stop(SERVICE_ID)
|
|
155
|
+
if (result?.stopped) ctx.logger?.info?.('[dsh-scrapling] broker 已停止工作台服务')
|
|
132
156
|
}
|
|
133
157
|
}
|
|
134
158
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capyclaw/scrapling",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.2",
|
|
4
4
|
"description": "Scrapling 网页抓取集成:HTTP 抓取 + 纯 Node CSS 选择器提取 + 可视化爬虫工作台(浏览器打开即用)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/host.mjs",
|
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
"./package.json": "./package.json"
|
|
12
12
|
},
|
|
13
13
|
"dependencies": {
|
|
14
|
-
"@capyclaw/plugin-kit": "^0.2.0"
|
|
14
|
+
"@capyclaw/plugin-kit": "^0.2.0",
|
|
15
|
+
"@capyclaw/service-broker": "^0.2.1"
|
|
15
16
|
},
|
|
16
17
|
"dsh": {
|
|
17
18
|
"bundle": {
|
|
@@ -19,7 +20,7 @@
|
|
|
19
20
|
},
|
|
20
21
|
"client": {
|
|
21
22
|
"platform": "web",
|
|
22
|
-
"immediately":
|
|
23
|
+
"immediately": true
|
|
23
24
|
},
|
|
24
25
|
"category": "tool",
|
|
25
26
|
"platform": "both"
|
package/server/server.mjs
CHANGED
|
@@ -6,13 +6,13 @@
|
|
|
6
6
|
*
|
|
7
7
|
* 只绑 127.0.0.1;/healthz 报标准服务信息,`/` 是爬虫工作台界面,
|
|
8
8
|
* /demo/* 是内置离线演示页(不依赖外网即可完整体验爬取流程)。
|
|
9
|
-
* lib/host.mjs
|
|
9
|
+
* lib/host.mjs 只通过 serviceBroker 启停本服务,不在 dsh 进程内监听端口。
|
|
10
10
|
*/
|
|
11
11
|
import { readFile } from 'node:fs/promises'
|
|
12
12
|
import path from 'node:path'
|
|
13
|
-
import { createServer } from 'node:http'
|
|
14
13
|
import { fileURLToPath } from 'node:url'
|
|
15
14
|
import { isMain, parseArgs } from '@capyclaw/plugin-kit'
|
|
15
|
+
import { installServiceSignalHandlers, startStandaloneService } from '@capyclaw/plugin-kit/service/server'
|
|
16
16
|
|
|
17
17
|
import { createCrawler } from '../lib/crawler.mjs'
|
|
18
18
|
|
|
@@ -98,32 +98,23 @@ function normalizeSelectors(raw) {
|
|
|
98
98
|
export async function startWorkbenchServer(options = {}) {
|
|
99
99
|
const packageDir = options.packageDir
|
|
100
100
|
|| path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
|
101
|
-
const port = Number(options.port)
|
|
101
|
+
const port = options.port === undefined ? DEFAULT_PORT : Number(options.port)
|
|
102
102
|
const host = options.host || '127.0.0.1'
|
|
103
|
-
const crawler = options.crawler || createCrawler(
|
|
104
|
-
|
|
103
|
+
const crawler = options.crawler || createCrawler({
|
|
104
|
+
timeoutMs: options.timeoutMs,
|
|
105
|
+
userAgent: options.userAgent,
|
|
106
|
+
maxHtmlBytes: options.maxHtmlBytes,
|
|
107
|
+
})
|
|
108
|
+
const version = options.version || '1.1.1'
|
|
105
109
|
const uiDir = path.join(packageDir, 'ui')
|
|
106
110
|
const demoDir = path.join(packageDir, 'demo')
|
|
107
111
|
const files = staticFiles(uiDir, demoDir)
|
|
108
112
|
const startedAt = Date.now()
|
|
109
113
|
|
|
110
|
-
const
|
|
114
|
+
const handler = async (req, res) => {
|
|
111
115
|
const url = new URL(req.url, `http://${req.headers.host || `127.0.0.1:${port}`}`)
|
|
112
116
|
try {
|
|
113
|
-
/* ----
|
|
114
|
-
if (url.pathname === '/healthz' && req.method === 'GET') {
|
|
115
|
-
return sendJson(res, 200, {
|
|
116
|
-
ok: true,
|
|
117
|
-
name: 'scrapling-workbench',
|
|
118
|
-
version,
|
|
119
|
-
contractVersion: CONTRACT_VERSION,
|
|
120
|
-
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
|
|
121
|
-
port,
|
|
122
|
-
pid: process.pid,
|
|
123
|
-
crawls: crawler.counters.total,
|
|
124
|
-
capabilities: { http: true, browser: false, selectors: true },
|
|
125
|
-
})
|
|
126
|
-
}
|
|
117
|
+
/* ---- 指标 ---- */
|
|
127
118
|
if (url.pathname === '/metrics' && req.method === 'GET') {
|
|
128
119
|
const body = [
|
|
129
120
|
'# HELP scrapling_up 服务存活状态',
|
|
@@ -224,20 +215,22 @@ export async function startWorkbenchServer(options = {}) {
|
|
|
224
215
|
}
|
|
225
216
|
return sendError(res, 500, { code: 'INTERNAL', message: error.message || '服务内部错误', hint: '请重试;若持续失败请查看服务日志。' })
|
|
226
217
|
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
await new Promise((resolve, reject) => {
|
|
230
|
-
server.once('error', reject)
|
|
231
|
-
server.listen(port, host, () => resolve())
|
|
232
|
-
})
|
|
218
|
+
}
|
|
233
219
|
|
|
234
|
-
|
|
220
|
+
const instance = await startStandaloneService({
|
|
221
|
+
service: 'scrapling-workbench',
|
|
235
222
|
port,
|
|
236
223
|
host,
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
224
|
+
health: () => ({
|
|
225
|
+
name: 'scrapling-workbench',
|
|
226
|
+
version,
|
|
227
|
+
contractVersion: CONTRACT_VERSION,
|
|
228
|
+
crawls: crawler.counters.total,
|
|
229
|
+
capabilities: { http: true, browser: false, selectors: true },
|
|
230
|
+
}),
|
|
231
|
+
handler,
|
|
232
|
+
})
|
|
233
|
+
return { ...instance, crawler }
|
|
241
234
|
}
|
|
242
235
|
|
|
243
236
|
async function main() {
|
|
@@ -249,11 +242,7 @@ async function main() {
|
|
|
249
242
|
const port = flags.port === undefined ? DEFAULT_PORT : Number(flags.port)
|
|
250
243
|
const instance = await startWorkbenchServer({ port, host: flags.host })
|
|
251
244
|
console.log(`[dsh-scrapling] 工作台已就绪: ${instance.url}/ (浏览器打开即用)`)
|
|
252
|
-
|
|
253
|
-
instance.close().then(() => process.exit(0))
|
|
254
|
-
}
|
|
255
|
-
process.on('SIGINT', shutdown)
|
|
256
|
-
process.on('SIGTERM', shutdown)
|
|
245
|
+
installServiceSignalHandlers(instance, { logger: console })
|
|
257
246
|
}
|
|
258
247
|
|
|
259
248
|
if (isMain(import.meta.url)) {
|