@uncarved/jade 0.3.1 → 0.4.1
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 +1 -0
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/host.d.ts +2 -0
- package/dist/host.js +39 -5
- package/dist/host.js.map +1 -1
- package/dist/remote.js +5 -0
- package/dist/remote.js.map +1 -1
- package/dist/session.d.ts +7 -0
- package/dist/session.js +490 -29
- package/dist/session.js.map +1 -1
- package/package.json +4 -4
- package/plugins/approval/index.ts +36 -14
- package/plugins/approval/policy.ts +15 -10
- package/plugins/approval/review.ts +9 -5
- package/plugins/checks/checks.ts +10 -7
- package/plugins/checks/index.ts +13 -13
- package/plugins/checks/plugin.json +1 -1
- package/plugins/checks/project.ts +37 -38
- package/plugins/commands/index.ts +27 -3
- package/plugins/compact/compact.ts +13 -5
- package/plugins/compact/index.ts +20 -3
- package/plugins/compact/style.ts +13 -14
- package/plugins/completions/index.ts +35 -0
- package/plugins/completions/plugin.json +7 -0
- package/plugins/copy/index.ts +46 -0
- package/plugins/copy/plugin.json +7 -0
- package/plugins/editor/index.ts +10 -4
- package/plugins/fs/diff.ts +7 -6
- package/plugins/fs/fs.ts +8 -4
- package/plugins/fs/grep.ts +42 -9
- package/plugins/fs/index.ts +2 -7
- package/plugins/fs/plugin.json +1 -1
- package/plugins/fs/renderers.ts +16 -15
- package/plugins/fs/style.ts +16 -15
- package/plugins/hooks/index.ts +3 -2
- package/plugins/keys/index.ts +5 -1
- package/plugins/mcp/index.ts +197 -78
- package/plugins/mcp/install.ts +5 -3
- package/plugins/mcp/mcp.ts +163 -11
- package/plugins/mcp/plugin.json +2 -1
- package/plugins/mcp/project.ts +47 -50
- package/plugins/memory/index.ts +4 -4
- package/plugins/memory/style.ts +13 -14
- package/plugins/mentions/candidates.ts +67 -0
- package/plugins/mentions/index.ts +12 -5
- package/plugins/mentions/plugin.json +1 -1
- package/plugins/mentions/style.ts +13 -14
- package/plugins/models/configure.ts +47 -12
- package/plugins/models/index.ts +27 -1
- package/plugins/models/provider.ts +24 -0
- package/plugins/models/saved.ts +1 -1
- package/plugins/modes/index.ts +13 -2
- package/plugins/print/index.ts +7 -4
- package/plugins/prompts/index.ts +0 -0
- package/plugins/renderers/index.ts +10 -5
- package/plugins/repeats/index.ts +8 -8
- package/plugins/schedule/index.ts +5 -1
- package/plugins/screenshot/browser.ts +10 -0
- package/plugins/sessions/index.ts +48 -2
- package/plugins/shell/index.ts +27 -28
- package/plugins/shell/plugin.json +1 -1
- package/plugins/shell/renderers.ts +9 -7
- package/plugins/shell/shell.ts +3 -1
- package/plugins/skills/index.ts +28 -19
- package/plugins/skills/project.ts +12 -7
- package/plugins/steer/index.ts +5 -4
- package/plugins/task/index.ts +80 -50
- package/plugins/task/plugin.json +6 -2
- package/plugins/task/style.ts +13 -14
- package/plugins/task/subagent.ts +67 -184
- package/plugins/todo/index.ts +39 -9
- package/plugins/tools/index.ts +9 -2
- package/plugins/tui/frontend.ts +139 -89
- package/plugins/tui/index.ts +2 -3
- package/plugins/tui/mentions.ts +11 -80
- package/plugins/tui/plugin.json +1 -1
- package/plugins/tui/screen.ts +55 -5
- package/plugins/tui/transcript.ts +17 -7
- package/plugins/tui/tui.ts +337 -101
- package/plugins/tui/vendor.ts +1 -1
- package/plugins/undo/checkpoint.ts +8 -4
- package/plugins/undo/index.ts +170 -31
- package/plugins/undo/plugin.json +1 -0
- package/plugins/undo/snapshot.ts +87 -14
- package/plugins/undo/style.ts +13 -14
- package/plugins/web/index.ts +7 -18
- package/plugins/web/plugin.json +1 -1
- package/plugins-dist/approval/index.js +363 -418
- package/plugins-dist/approval/policy.js +391 -508
- package/plugins-dist/approval/review.js +132 -158
- package/plugins-dist/approval/schema.js +50 -55
- package/plugins-dist/ask/index.js +115 -129
- package/plugins-dist/budget/index.js +27 -31
- package/plugins-dist/checks/checks.js +293 -329
- package/plugins-dist/checks/index.js +119 -139
- package/plugins-dist/checks/plugin.json +2 -1
- package/plugins-dist/checks/project.js +57 -65
- package/plugins-dist/commands/index.js +47 -29
- package/plugins-dist/compact/compact.js +233 -249
- package/plugins-dist/compact/index.js +98 -95
- package/plugins-dist/compact/style.js +9 -14
- package/plugins-dist/completions/index.js +30 -0
- package/plugins-dist/completions/plugin.json +9 -0
- package/plugins-dist/continue/index.js +40 -52
- package/plugins-dist/copy/index.js +40 -0
- package/plugins-dist/copy/plugin.json +9 -0
- package/plugins-dist/cost/index.js +98 -115
- package/plugins-dist/custom-commands/index.js +55 -72
- package/plugins-dist/editor/index.js +64 -72
- package/plugins-dist/fs/diff.js +111 -124
- package/plugins-dist/fs/fs.js +426 -469
- package/plugins-dist/fs/grep.js +262 -253
- package/plugins-dist/fs/index.js +20 -34
- package/plugins-dist/fs/plugin.json +1 -2
- package/plugins-dist/fs/renderers.js +100 -112
- package/plugins-dist/fs/style.js +11 -15
- package/plugins-dist/fs/sys.js +31 -43
- package/plugins-dist/hooks/index.js +107 -127
- package/plugins-dist/keys/index.js +27 -31
- package/plugins-dist/mcp/index.js +271 -199
- package/plugins-dist/mcp/install.js +123 -137
- package/plugins-dist/mcp/mcp.js +638 -577
- package/plugins-dist/mcp/plugin.json +3 -1
- package/plugins-dist/mcp/project.js +98 -115
- package/plugins-dist/memory/index.js +83 -88
- package/plugins-dist/memory/memory.js +111 -128
- package/plugins-dist/memory/style.js +9 -14
- package/plugins-dist/mentions/attach.js +91 -99
- package/plugins-dist/mentions/candidates.js +49 -0
- package/plugins-dist/mentions/index.js +71 -81
- package/plugins-dist/mentions/plugin.json +2 -1
- package/plugins-dist/mentions/style.js +9 -14
- package/plugins-dist/models/config.js +29 -43
- package/plugins-dist/models/configure.js +421 -474
- package/plugins-dist/models/context.js +14 -22
- package/plugins-dist/models/index.js +182 -189
- package/plugins-dist/models/provider.js +263 -307
- package/plugins-dist/models/saved.js +60 -72
- package/plugins-dist/modes/index.js +138 -165
- package/plugins-dist/plugins/index.js +34 -34
- package/plugins-dist/print/index.js +192 -175
- package/plugins-dist/prompts/index.js +86 -89
- package/plugins-dist/prompts/notes.js +31 -37
- package/plugins-dist/prompts/prompts.js +155 -193
- package/plugins-dist/prompts/results.js +40 -53
- package/plugins-dist/prompts/sys.js +39 -50
- package/plugins-dist/renderers/index.js +32 -32
- package/plugins-dist/repeats/index.js +131 -174
- package/plugins-dist/schedule/cron.js +49 -56
- package/plugins-dist/schedule/index.js +230 -247
- package/plugins-dist/schedule/store.js +93 -109
- package/plugins-dist/scratch/index.js +12 -18
- package/plugins-dist/screenshot/browser.js +136 -154
- package/plugins-dist/screenshot/index.js +37 -46
- package/plugins-dist/screenshot/sys.js +53 -65
- package/plugins-dist/screenshot/tool.js +98 -126
- package/plugins-dist/sessions/index.js +149 -117
- package/plugins-dist/shell/index.js +117 -135
- package/plugins-dist/shell/plugin.json +1 -1
- package/plugins-dist/shell/renderers.js +28 -33
- package/plugins-dist/shell/service.js +17 -23
- package/plugins-dist/shell/shell.js +307 -362
- package/plugins-dist/shell/sys.js +64 -79
- package/plugins-dist/skills/index.js +193 -211
- package/plugins-dist/skills/install.js +122 -149
- package/plugins-dist/skills/project.js +65 -73
- package/plugins-dist/skills/skills.js +135 -171
- package/plugins-dist/steer/index.js +108 -125
- package/plugins-dist/suggest/index.js +235 -259
- package/plugins-dist/task/index.js +130 -117
- package/plugins-dist/task/plugin.json +5 -2
- package/plugins-dist/task/style.js +9 -14
- package/plugins-dist/task/subagent.js +156 -279
- package/plugins-dist/todo/index.js +79 -63
- package/plugins-dist/tools/index.js +36 -42
- package/plugins-dist/tui/editor.js +145 -160
- package/plugins-dist/tui/frontend.js +639 -678
- package/plugins-dist/tui/history.js +34 -37
- package/plugins-dist/tui/index.js +16 -18
- package/plugins-dist/tui/markdown.js +203 -247
- package/plugins-dist/tui/mascot.js +266 -355
- package/plugins-dist/tui/mentions.js +67 -144
- package/plugins-dist/tui/plugin.json +1 -2
- package/plugins-dist/tui/render.js +35 -45
- package/plugins-dist/tui/screen.js +197 -180
- package/plugins-dist/tui/transcript.js +436 -468
- package/plugins-dist/tui/tui.js +1554 -1656
- package/plugins-dist/tui/vendor.js +1088 -1388
- package/plugins-dist/undo/checkpoint.js +97 -118
- package/plugins-dist/undo/index.js +281 -192
- package/plugins-dist/undo/plugin.json +3 -0
- package/plugins-dist/undo/snapshot.js +134 -99
- package/plugins-dist/undo/style.js +9 -14
- package/plugins-dist/update/index.js +26 -28
- package/plugins-dist/web/env.js +55 -68
- package/plugins-dist/web/index.js +80 -110
- package/plugins-dist/web/plugin.json +1 -2
- package/plugins-dist/web/renderers.js +4 -5
- package/plugins-dist/web/web.js +514 -593
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/sdk/python/jade_plugin.py +9 -2
- package/src/api.ts +1 -1
- package/src/host.ts +39 -4
- package/src/remote.ts +6 -1
- package/src/session.ts +496 -36
|
@@ -1,125 +1,109 @@
|
|
|
1
|
-
// 定时任务的存储:$JADE_HOME/state/schedules.json。同一台机器上可能开着好几个 jade,
|
|
2
|
-
// 所有读写都在一把目录锁(schedules.lock,mkdir 是原子的)里进行,到点的任务由先拿到锁的进程认领,只投递一次。
|
|
3
1
|
import { randomBytes } from "node:crypto";
|
|
4
2
|
import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
5
3
|
import path from "node:path";
|
|
6
4
|
import { nextRun } from "./cron.js";
|
|
7
|
-
|
|
8
|
-
const
|
|
9
|
-
|
|
5
|
+
const STALE_MS = 1e4;
|
|
6
|
+
const WAIT_MS = 5000;
|
|
7
|
+
|
|
10
8
|
export class ScheduleStore {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
9
|
+
file;
|
|
10
|
+
#lock;
|
|
11
|
+
constructor(home) {
|
|
12
|
+
this.file = path.join(home, "state", "schedules.json");
|
|
13
|
+
this.#lock = path.join(home, "state", "schedules.lock");
|
|
14
|
+
}
|
|
15
|
+
list() {
|
|
16
|
+
return this.#locked(() => this.#read());
|
|
17
|
+
}
|
|
18
|
+
update(fn) {
|
|
19
|
+
return this.#locked(async () => {
|
|
20
|
+
const tasks = await this.#read();
|
|
21
|
+
const before = JSON.stringify(tasks);
|
|
22
|
+
const out = fn(tasks);
|
|
23
|
+
if (JSON.stringify(tasks) !== before) {
|
|
24
|
+
const tmp = `${this.file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
25
|
+
await writeFile(tmp, `${JSON.stringify({ version: 1, tasks }, null, 2)}
|
|
26
|
+
`);
|
|
27
|
+
await rename(tmp, this.file);
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
async#read() {
|
|
33
|
+
let text;
|
|
34
|
+
try {
|
|
35
|
+
text = await readFile(this.file, "utf8");
|
|
36
|
+
} catch (e) {
|
|
37
|
+
if (e.code === "ENOENT")
|
|
38
|
+
return [];
|
|
39
|
+
throw e;
|
|
34
40
|
}
|
|
35
|
-
|
|
36
|
-
|
|
41
|
+
const data = JSON.parse(text);
|
|
42
|
+
if (data.version !== 1 || !Array.isArray(data.tasks))
|
|
43
|
+
throw new Error(`${this.file}: unsupported format`);
|
|
44
|
+
return data.tasks;
|
|
45
|
+
}
|
|
46
|
+
async#locked(fn) {
|
|
47
|
+
await mkdir(path.dirname(this.#lock), { recursive: true });
|
|
48
|
+
const deadline = Date.now() + WAIT_MS;
|
|
49
|
+
const mine = randomBytes(8).toString("hex");
|
|
50
|
+
for (;; ) {
|
|
51
|
+
try {
|
|
52
|
+
await mkdir(this.#lock);
|
|
37
53
|
try {
|
|
38
|
-
|
|
54
|
+
await writeFile(path.join(this.#lock, "owner"), mine);
|
|
55
|
+
} catch (e) {
|
|
56
|
+
await rm(this.#lock, { recursive: true, force: true });
|
|
57
|
+
throw e;
|
|
39
58
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
59
|
+
break;
|
|
60
|
+
} catch (e) {
|
|
61
|
+
if (e.code !== "EEXIST")
|
|
62
|
+
throw e;
|
|
63
|
+
const age = await stat(this.#lock).then((s) => Date.now() - s.mtimeMs, () => 0);
|
|
64
|
+
if (age > STALE_MS)
|
|
65
|
+
await rm(this.#lock, { recursive: true, force: true });
|
|
66
|
+
else if (Date.now() > deadline)
|
|
67
|
+
throw new Error(`${this.#lock} is held by another jade; remove it if no jade is running`);
|
|
68
|
+
else
|
|
69
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
70
|
+
}
|
|
49
71
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
await mkdir(this.#lock);
|
|
59
|
-
try {
|
|
60
|
-
await writeFile(path.join(this.#lock, "owner"), mine);
|
|
61
|
-
}
|
|
62
|
-
catch (e) {
|
|
63
|
-
await rm(this.#lock, { recursive: true, force: true });
|
|
64
|
-
throw e;
|
|
65
|
-
}
|
|
66
|
-
break;
|
|
67
|
-
}
|
|
68
|
-
catch (e) {
|
|
69
|
-
if (e.code !== "EEXIST")
|
|
70
|
-
throw e;
|
|
71
|
-
const age = await stat(this.#lock).then((s) => Date.now() - s.mtimeMs, () => 0);
|
|
72
|
-
if (age > STALE_MS)
|
|
73
|
-
await rm(this.#lock, { recursive: true, force: true });
|
|
74
|
-
else if (Date.now() > deadline)
|
|
75
|
-
throw new Error(`${this.#lock} is held by another jade; remove it if no jade is running`);
|
|
76
|
-
else
|
|
77
|
-
await new Promise((r) => setTimeout(r, 20));
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
try {
|
|
81
|
-
return await fn();
|
|
82
|
-
}
|
|
83
|
-
finally {
|
|
84
|
-
const owner = await readFile(path.join(this.#lock, "owner"), "utf8").catch(() => undefined);
|
|
85
|
-
if (owner === mine)
|
|
86
|
-
await rm(this.#lock, { recursive: true, force: true });
|
|
87
|
-
}
|
|
72
|
+
try {
|
|
73
|
+
return await fn();
|
|
74
|
+
} finally {
|
|
75
|
+
const owner = await readFile(path.join(this.#lock, "owner"), "utf8").catch(() => {
|
|
76
|
+
return;
|
|
77
|
+
});
|
|
78
|
+
if (owner === mine)
|
|
79
|
+
await rm(this.#lock, { recursive: true, force: true });
|
|
88
80
|
}
|
|
81
|
+
}
|
|
89
82
|
}
|
|
90
|
-
/**
|
|
91
|
-
* 两个目录是不是同一个:比较绝对路径(不看末尾的分隔符),Windows 上不分大小写。
|
|
92
|
-
* 和 jade/sessions 的 cwdKey 相同,插件之间不共享代码(只能共享类型),所以这里留一份
|
|
93
|
-
*/
|
|
94
83
|
export function sameDir(a, b) {
|
|
95
|
-
|
|
96
|
-
|
|
84
|
+
const key = (p) => process.platform === "win32" ? path.resolve(p).toLowerCase() : path.resolve(p);
|
|
85
|
+
return key(a) === key(b);
|
|
97
86
|
}
|
|
98
|
-
/** 下一次触发时间;没有了时 undefined */
|
|
99
87
|
export function nextAt(cron, from) {
|
|
100
|
-
|
|
88
|
+
return nextRun(cron, from)?.toISOString();
|
|
101
89
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
due.push({ ...t });
|
|
122
|
-
}
|
|
123
|
-
return due;
|
|
124
|
-
});
|
|
90
|
+
export function claimDue(store, cwd, session, now, skip = new Set) {
|
|
91
|
+
return store.update((tasks) => {
|
|
92
|
+
const due = [];
|
|
93
|
+
for (const t of tasks) {
|
|
94
|
+
if (t.status !== "active" || !sameDir(t.cwd, cwd) || !t.next || Date.parse(t.next) > now.getTime() || skip.has(t.id))
|
|
95
|
+
continue;
|
|
96
|
+
t.last = { at: now.toISOString(), session };
|
|
97
|
+
t.updatedAt = now.toISOString();
|
|
98
|
+
const next = t.recurring ? nextAt(t.cron, now) : undefined;
|
|
99
|
+
if (next)
|
|
100
|
+
t.next = next;
|
|
101
|
+
else {
|
|
102
|
+
t.status = "ended";
|
|
103
|
+
delete t.next;
|
|
104
|
+
}
|
|
105
|
+
due.push({ ...t });
|
|
106
|
+
}
|
|
107
|
+
return due;
|
|
108
|
+
});
|
|
125
109
|
}
|
|
@@ -1,26 +1,20 @@
|
|
|
1
|
-
// jade/scratch:每个会话一个临时目录,放不属于项目的临时文件(试跑的脚本、中间结果),免得弄脏工作目录。
|
|
2
|
-
// 目录在系统临时目录下、按会话 id 命名,恢复会话时还是同一个;不主动删除,由系统清理临时目录。
|
|
3
1
|
import { realpathSync } from "node:fs";
|
|
4
2
|
import { mkdir } from "node:fs/promises";
|
|
5
3
|
import os from "node:os";
|
|
6
4
|
import path from "node:path";
|
|
7
5
|
import { definePlugin } from "@uncarved/jade-api";
|
|
8
|
-
/** 会话 id 对应的临时目录 */
|
|
9
6
|
export const scratchDir = (session) => path.join(os.tmpdir(), "jade-scratch", session);
|
|
10
7
|
export default definePlugin({
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
" Put temporary files there (throwaway scripts, intermediate output, files that do not belong in the project) instead of the working directory or /tmp.",
|
|
24
|
-
});
|
|
25
|
-
},
|
|
8
|
+
async session(ctx) {
|
|
9
|
+
if (!/^[A-Za-z0-9_-][A-Za-z0-9._-]*$/.test(ctx.session.id))
|
|
10
|
+
return;
|
|
11
|
+
const created = scratchDir(ctx.session.id);
|
|
12
|
+
await mkdir(created, { recursive: true });
|
|
13
|
+
const dir = realpathSync.native(created);
|
|
14
|
+
ctx.service("approval@1")?.allowWrite(dir);
|
|
15
|
+
ctx.service("prompts@1")?.add({
|
|
16
|
+
text: `- Scratch directory for this session: ${dir}
|
|
17
|
+
` + " Put temporary files there (throwaway scripts, intermediate output, files that do not belong in the project) instead of the working directory or /tmp."
|
|
18
|
+
});
|
|
19
|
+
}
|
|
26
20
|
});
|
|
@@ -1,109 +1,88 @@
|
|
|
1
|
-
// 用 DevTools 协议(CDP)让无头浏览器截一张图。
|
|
2
|
-
//
|
|
3
|
-
// 不用命令行的 --window-size + --screenshot:Windows 上浏览器窗口最窄 500px,要 390 宽时页面仍按 500 排版,
|
|
4
|
-
// 只截到左边 390px,看起来像内容被裁掉;也不能滚动到页面中间的某一段,页面一直不"加载完"时只有一句超时。
|
|
5
|
-
// 这里用 Emulation.setDeviceMetricsOverride 设视口(多窄都按给的宽度排版),可以先滚动到某个元素再截,
|
|
6
|
-
// 页面迟迟不触发 load 时照样截下当时的样子并说明。
|
|
7
|
-
//
|
|
8
|
-
// 连接用 --remote-debugging-port=0 加 WebSocket(Bun 和 Node ≥22 都有全局的 WebSocket);
|
|
9
|
-
// --remote-debugging-pipe 在 Bun 下收不到数据。端口只监听本机,用完就连同临时用户目录一起关掉。
|
|
10
1
|
import { readFile } from "node:fs/promises";
|
|
11
2
|
import path from "node:path";
|
|
12
3
|
import { spawn } from "./sys.js";
|
|
13
|
-
|
|
14
|
-
const
|
|
15
|
-
/** 等页面 load 事件的最长时间;到时间还没有就按当时的样子截 */
|
|
16
|
-
const LOAD_MS = 15_000;
|
|
17
|
-
/** load 之后等网络安静下来(脚本、图片、字体)的最长时间 */
|
|
4
|
+
const READY_MS = 1e4;
|
|
5
|
+
const LOAD_MS = 15000;
|
|
18
6
|
const SETTLE_MS = 3000;
|
|
19
|
-
|
|
7
|
+
const CLOSE_MS = 5000;
|
|
20
8
|
const SCROLL_SETTLE_MS = 400;
|
|
21
|
-
|
|
9
|
+
|
|
22
10
|
export class CaptureError extends Error {
|
|
23
11
|
}
|
|
24
12
|
function connect(url) {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
13
|
+
return new Promise((resolve, reject) => {
|
|
14
|
+
const ws = new WebSocket(url);
|
|
15
|
+
let next = 0;
|
|
16
|
+
let closed = false;
|
|
17
|
+
const waiting = new Map;
|
|
18
|
+
const events = new Set;
|
|
19
|
+
const listeners = new Set;
|
|
20
|
+
ws.onerror = () => reject(new CaptureError("could not connect to the browser"));
|
|
21
|
+
ws.onclose = () => {
|
|
22
|
+
closed = true;
|
|
23
|
+
for (const w of waiting.values())
|
|
24
|
+
w.reject(new CaptureError("the browser closed before the screenshot was taken"));
|
|
25
|
+
waiting.clear();
|
|
26
|
+
};
|
|
27
|
+
ws.onmessage = (e) => {
|
|
28
|
+
const m = JSON.parse(String(e.data));
|
|
29
|
+
if (m.id !== undefined) {
|
|
30
|
+
const w = waiting.get(m.id);
|
|
31
|
+
waiting.delete(m.id);
|
|
32
|
+
if (m.error)
|
|
33
|
+
w?.reject(new CaptureError(m.error.message));
|
|
34
|
+
else
|
|
35
|
+
w?.resolve(m.result);
|
|
36
|
+
} else if (m.method) {
|
|
37
|
+
const name = m.method === "Page.lifecycleEvent" ? `lifecycle:${m.params?.name}` : m.method;
|
|
38
|
+
events.add(name);
|
|
39
|
+
for (const l of listeners)
|
|
40
|
+
l(name);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
ws.onopen = () => resolve({
|
|
44
|
+
send: (method, params = {}, sessionId) => new Promise((res, rej) => {
|
|
45
|
+
if (closed)
|
|
46
|
+
return rej(new CaptureError("the browser closed before the screenshot was taken"));
|
|
47
|
+
const id = ++next;
|
|
48
|
+
waiting.set(id, { resolve: res, reject: rej });
|
|
49
|
+
ws.send(JSON.stringify({ id, method, params, sessionId }));
|
|
50
|
+
}),
|
|
51
|
+
seen: (method, ms) => new Promise((res) => {
|
|
52
|
+
if (events.has(method))
|
|
53
|
+
return res(true);
|
|
54
|
+
const done = (ok) => {
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
listeners.delete(l);
|
|
57
|
+
res(ok);
|
|
56
58
|
};
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
waiting.set(id, { resolve: res, reject: rej });
|
|
63
|
-
ws.send(JSON.stringify({ id, method, params, sessionId }));
|
|
64
|
-
}),
|
|
65
|
-
seen: (method, ms) => new Promise((res) => {
|
|
66
|
-
if (events.has(method))
|
|
67
|
-
return res(true);
|
|
68
|
-
const done = (ok) => {
|
|
69
|
-
clearTimeout(timer);
|
|
70
|
-
listeners.delete(l);
|
|
71
|
-
res(ok);
|
|
72
|
-
};
|
|
73
|
-
const l = (name) => name === method && done(true);
|
|
74
|
-
const timer = setTimeout(() => done(false), ms);
|
|
75
|
-
listeners.add(l);
|
|
76
|
-
}),
|
|
77
|
-
close: () => ws.close(),
|
|
78
|
-
});
|
|
59
|
+
const l = (name) => name === method && done(true);
|
|
60
|
+
const timer = setTimeout(() => done(false), ms);
|
|
61
|
+
listeners.add(l);
|
|
62
|
+
}),
|
|
63
|
+
close: () => ws.close()
|
|
79
64
|
});
|
|
65
|
+
});
|
|
80
66
|
}
|
|
81
|
-
/** 浏览器把调试端口和连接路径写在用户目录的 DevToolsActivePort 里;等它出现 */
|
|
82
67
|
async function debuggerUrl(profile, proc, signal) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
101
|
-
}
|
|
68
|
+
let exited = false;
|
|
69
|
+
proc.exited.then(() => exited = true);
|
|
70
|
+
const deadline = Date.now() + READY_MS;
|
|
71
|
+
for (;; ) {
|
|
72
|
+
signal.throwIfAborted();
|
|
73
|
+
try {
|
|
74
|
+
const [port, wsPath] = (await readFile(path.join(profile, "DevToolsActivePort"), "utf8")).trim().split(`
|
|
75
|
+
`);
|
|
76
|
+
if (port && wsPath)
|
|
77
|
+
return `ws://127.0.0.1:${port}${wsPath}`;
|
|
78
|
+
} catch {}
|
|
79
|
+
if (exited)
|
|
80
|
+
throw new CaptureError("the browser exited before it was ready");
|
|
81
|
+
if (Date.now() > deadline)
|
|
82
|
+
throw new CaptureError(`the browser was not ready within ${READY_MS / 1000}s`);
|
|
83
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
84
|
+
}
|
|
102
85
|
}
|
|
103
|
-
/**
|
|
104
|
-
* 在页面里执行:滚动到 CSS 选择器匹配的第一个元素;选择器无效或没有匹配时,找第一个包含这段文字的元素。
|
|
105
|
-
* 比视口高的元素对齐到顶部,其余的放在中间
|
|
106
|
-
*/
|
|
107
86
|
const SCROLL = (what) => `(() => {
|
|
108
87
|
const what = ${JSON.stringify(what)};
|
|
109
88
|
let el = null;
|
|
@@ -121,67 +100,70 @@ const SCROLL = (what) => `(() => {
|
|
|
121
100
|
})()`;
|
|
122
101
|
const METRICS = "JSON.stringify({ h: Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0), y: Math.round(scrollY) })";
|
|
123
102
|
export const capture = async (browser, req, signal) => {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
scrolledTo = found;
|
|
166
|
-
await new Promise((r) => setTimeout(r, SCROLL_SETTLE_MS));
|
|
167
|
-
}
|
|
168
|
-
const { h, y } = JSON.parse(await evaluate(METRICS));
|
|
169
|
-
const { data } = await page("Page.captureScreenshot", { format: "png" });
|
|
170
|
-
return {
|
|
171
|
-
png: Buffer.from(data, "base64"),
|
|
172
|
-
pageHeight: h,
|
|
173
|
-
scrollY: y,
|
|
174
|
-
scrolledTo,
|
|
175
|
-
note: loaded ? undefined : `The page had not finished loading after ${LOAD_MS / 1000}s; this is how it looked at that point.`,
|
|
176
|
-
};
|
|
177
|
-
};
|
|
178
|
-
try {
|
|
179
|
-
return await Promise.race([work(), aborted]);
|
|
103
|
+
const proc = await spawn([
|
|
104
|
+
browser,
|
|
105
|
+
"--headless=new",
|
|
106
|
+
"--disable-gpu",
|
|
107
|
+
"--hide-scrollbars",
|
|
108
|
+
"--no-first-run",
|
|
109
|
+
"--no-default-browser-check",
|
|
110
|
+
"--disable-extensions",
|
|
111
|
+
"--mute-audio",
|
|
112
|
+
"--remote-debugging-port=0",
|
|
113
|
+
`--user-data-dir=${req.profile}`,
|
|
114
|
+
"about:blank"
|
|
115
|
+
], { stdout: "ignore", stderr: "ignore" });
|
|
116
|
+
let abort;
|
|
117
|
+
const aborted = new Promise((_, reject) => abort = () => reject(signal.reason));
|
|
118
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
119
|
+
let cdp;
|
|
120
|
+
const work = async () => {
|
|
121
|
+
cdp = await connect(await debuggerUrl(req.profile, proc, signal));
|
|
122
|
+
const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });
|
|
123
|
+
const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });
|
|
124
|
+
const page = (method, params) => cdp.send(method, params, sessionId);
|
|
125
|
+
const evaluate = async (expression) => (await page("Runtime.evaluate", { expression, returnByValue: true })).result.value;
|
|
126
|
+
await page("Emulation.setDeviceMetricsOverride", { width: req.width, height: req.height, deviceScaleFactor: 1, mobile: false });
|
|
127
|
+
await page("Page.enable");
|
|
128
|
+
await page("Page.setLifecycleEventsEnabled", { enabled: true });
|
|
129
|
+
const { errorText } = await page("Page.navigate", { url: req.target });
|
|
130
|
+
if (errorText)
|
|
131
|
+
throw new CaptureError(`the page could not be loaded: ${errorText}`);
|
|
132
|
+
const loaded = await cdp.seen("Page.loadEventFired", LOAD_MS);
|
|
133
|
+
if (loaded)
|
|
134
|
+
await cdp.seen("lifecycle:networkIdle", SETTLE_MS);
|
|
135
|
+
signal.throwIfAborted();
|
|
136
|
+
let scrolledTo;
|
|
137
|
+
if (req.scrollTo !== undefined) {
|
|
138
|
+
const found = await evaluate(SCROLL(req.scrollTo));
|
|
139
|
+
if (found === null) {
|
|
140
|
+
throw new CaptureError(`nothing on the page matches scroll_to ${JSON.stringify(req.scrollTo)} (tried as a CSS selector, then as text)` + (loaded ? "" : `; the page had not finished loading after ${LOAD_MS / 1000}s`));
|
|
141
|
+
}
|
|
142
|
+
scrolledTo = found;
|
|
143
|
+
await new Promise((r) => setTimeout(r, SCROLL_SETTLE_MS));
|
|
180
144
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
145
|
+
const { h, y } = JSON.parse(await evaluate(METRICS));
|
|
146
|
+
const { data } = await page("Page.captureScreenshot", { format: "png" });
|
|
147
|
+
return {
|
|
148
|
+
png: Buffer.from(data, "base64"),
|
|
149
|
+
pageHeight: h,
|
|
150
|
+
scrollY: y,
|
|
151
|
+
scrolledTo,
|
|
152
|
+
note: loaded ? undefined : `The page had not finished loading after ${LOAD_MS / 1000}s; this is how it looked at that point.`
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
try {
|
|
156
|
+
return await Promise.race([work(), aborted]);
|
|
157
|
+
} finally {
|
|
158
|
+
signal.removeEventListener("abort", abort);
|
|
159
|
+
if (cdp && !signal.aborted) {
|
|
160
|
+
cdp.send("Browser.close").catch(() => {});
|
|
161
|
+
let timer;
|
|
162
|
+
await Promise.race([proc.exited, new Promise((r) => timer = setTimeout(r, CLOSE_MS))]);
|
|
163
|
+
clearTimeout(timer);
|
|
186
164
|
}
|
|
165
|
+
cdp?.close();
|
|
166
|
+
proc.kill();
|
|
167
|
+
await proc.exited;
|
|
168
|
+
}
|
|
187
169
|
};
|