cdpm-mcp 0.0.0-stage → 0.1.0
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/CHANGELOG.md +33 -0
- package/LICENSE +21 -0
- package/README.ko.md +245 -0
- package/README.md +167 -2
- package/dist/agent-setup.js +134 -0
- package/dist/auto-setup.js +110 -0
- package/dist/cdp/client.js +127 -0
- package/dist/cdp/downloads.js +69 -0
- package/dist/cdp/network.js +118 -0
- package/dist/cdp/sessions.js +519 -0
- package/dist/cdp/targets.js +43 -0
- package/dist/chrome/finder.js +87 -0
- package/dist/chrome/launcher.js +52 -0
- package/dist/chrome/proxy.js +109 -0
- package/dist/claude-md-setup.js +68 -0
- package/dist/cli.js +230 -0
- package/dist/errors.js +3 -0
- package/dist/index.js +26 -0
- package/dist/install.js +34 -0
- package/dist/page/actions.js +1101 -0
- package/dist/page/keys.js +115 -0
- package/dist/page/snapshot.js +283 -0
- package/dist/paths.js +43 -0
- package/dist/pause.js +74 -0
- package/dist/proxy-forwarder.js +191 -0
- package/dist/registry/lock.js +93 -0
- package/dist/registry/messages.js +106 -0
- package/dist/registry/store.js +27 -0
- package/dist/service.js +340 -0
- package/dist/slots.js +72 -0
- package/dist/statusline-setup.js +142 -0
- package/dist/statusline.js +82 -0
- package/dist/taskbar/dock.js +94 -0
- package/dist/taskbar/icon-gdi.js +191 -0
- package/dist/taskbar/icon.js +300 -0
- package/dist/taskbar/watcher.js +65 -0
- package/dist/taskbar/win32.js +135 -0
- package/dist/tools/format.js +48 -0
- package/dist/tools/read.js +81 -0
- package/dist/tools/register.js +907 -0
- package/dist/util.js +111 -0
- package/dist/version.js +3 -0
- package/package.json +62 -4
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CdpmError } from '../errors.js';
|
|
4
|
+
import { pidAlive } from '../util.js';
|
|
5
|
+
import { portOf } from '../slots.js';
|
|
6
|
+
import { paths } from '../paths.js';
|
|
7
|
+
import { withFileLock } from '../registry/lock.js';
|
|
8
|
+
import { CdpConnection, CdpTimeoutError } from './client.js';
|
|
9
|
+
import { NetworkRecorder } from './network.js';
|
|
10
|
+
import { listFrameTargets, listPages, probe } from './targets.js';
|
|
11
|
+
/** 탭 하나에 붙은 연결. dialog 상태와 페이지 이동 이벤트를 추적한다. */
|
|
12
|
+
export class PageSession {
|
|
13
|
+
slot;
|
|
14
|
+
targetId;
|
|
15
|
+
conn;
|
|
16
|
+
dialog;
|
|
17
|
+
/**
|
|
18
|
+
* 에이전트별 ref → backendDOMNodeId. 서브에이전트들은 한 프로세스를 같이 쓰므로,
|
|
19
|
+
* 한 에이전트가 스냅샷을 다시 찍어도 다른 에이전트의 ref가 다른 요소를 가리키지 않게 나눠 둔다.
|
|
20
|
+
*/
|
|
21
|
+
refMaps = new Map();
|
|
22
|
+
snapshots = new Map();
|
|
23
|
+
/** 프레임별 CDPM 전용 실행 공간(isolated world). 페이지 JS는 이 공간을 볼 수 없다. */
|
|
24
|
+
worlds = new Map();
|
|
25
|
+
mainFrameId;
|
|
26
|
+
/** 이 탭에서 마지막으로 시작된 다운로드 (사용자 다운로드 폴더에 저장됨) */
|
|
27
|
+
lastDownload;
|
|
28
|
+
/** CDPM 클릭으로 열리려던 파일 선택 창 (OS 창 대신 가로챔). browser_upload가 여기에 파일을 넣는다. */
|
|
29
|
+
fileChooser;
|
|
30
|
+
network;
|
|
31
|
+
/** 에이전트별로 이 탭에서 마지막 조작을 시작한 시각 (browser_wait response가 그 뒤의 요청부터 찾는다) */
|
|
32
|
+
actionStartedAt = new Map();
|
|
33
|
+
lastUsed = Date.now();
|
|
34
|
+
/** 붙을 때 알림창 때문에 켜지 못한 기능 (탭이 응답하면 켠다) */
|
|
35
|
+
pendingEnable = false;
|
|
36
|
+
renderHolds = 0;
|
|
37
|
+
emulating = false;
|
|
38
|
+
/** 멈춘 탭이 다시 응답하는지 지켜보는 중인지 */
|
|
39
|
+
livenessWatch = false;
|
|
40
|
+
chain = Promise.resolve();
|
|
41
|
+
/** 에이전트별 요소 → ref 번호. 페이지가 바뀌기 전까지 같은 요소는 같은 번호를 쓴다. */
|
|
42
|
+
refAlloc = new Map();
|
|
43
|
+
/** 숨은 탭을 그리기 위해 잠깐 포커스 에뮬레이션 중인지 (이때 visibilityState·hasFocus는 가짜로 보임) */
|
|
44
|
+
get isEmulating() {
|
|
45
|
+
return this.emulating;
|
|
46
|
+
}
|
|
47
|
+
constructor(slot, targetId, conn) {
|
|
48
|
+
this.slot = slot;
|
|
49
|
+
this.targetId = targetId;
|
|
50
|
+
this.conn = conn;
|
|
51
|
+
this.network = new NetworkRecorder(conn);
|
|
52
|
+
conn.on('Page.javascriptDialogOpening', (p) => {
|
|
53
|
+
this.dialog = { type: p.type, message: p.message, at: new Date().toISOString() };
|
|
54
|
+
this.watchLiveness();
|
|
55
|
+
});
|
|
56
|
+
conn.on('Page.javascriptDialogClosed', () => {
|
|
57
|
+
this.dialog = undefined;
|
|
58
|
+
});
|
|
59
|
+
conn.on('Page.frameNavigated', (p) => {
|
|
60
|
+
// 문서가 바뀌면 그 프레임의 실행 공간은 사라진다.
|
|
61
|
+
this.worlds.delete(p.frame.id);
|
|
62
|
+
if (!p.frame.parentId) {
|
|
63
|
+
this.mainFrameId = p.frame.id;
|
|
64
|
+
this.worlds.clear();
|
|
65
|
+
this.refMaps.clear();
|
|
66
|
+
this.snapshots.clear();
|
|
67
|
+
this.refAlloc.clear();
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
conn.on('Page.frameDetached', (p) => this.worlds.delete(p.frameId));
|
|
71
|
+
conn.on('Page.downloadWillBegin', (p) => {
|
|
72
|
+
this.lastDownload = { url: p.url, file: p.suggestedFilename, at: Date.now() };
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* 같은 탭에 대한 조작을 하나씩 실행한다 (동시에 오면 줄 선다). 이 프로세스 안에서 줄 서고,
|
|
77
|
+
* 다른 Claude 세션(다른 프로세스)과도 탭 잠금 파일로 줄 선다 → 두 세션의 입력이 한 탭에서 섞이지 않는다.
|
|
78
|
+
* 잠금을 잡은 프로세스가 죽으면 바로 풀린다. 다른 세션의 조작이 2분 넘게 끝나지 않으면 기다리지 않고 알린다.
|
|
79
|
+
*/
|
|
80
|
+
exclusive(fn) {
|
|
81
|
+
const locked = () => withFileLock(paths.tabLock(this.slot, this.targetId), fn, TAB_LOCK_WAIT_MS, '다른 Claude 세션이 이 탭을 2분 넘게 조작하고 있어요. 그 세션에 slot_send로 물어보거나 자기 탭(browser_tab_new)에서 하세요.');
|
|
82
|
+
const run = this.chain.then(locked, locked);
|
|
83
|
+
this.chain = run.then(() => undefined, () => undefined);
|
|
84
|
+
return run;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* 스냅샷용 ref 번호 배정기: 이 탭의 같은 요소면 같은 번호, 처음 보면 새 번호.
|
|
88
|
+
* 새 번호는 에이전트마다 프로세스 전체에서 하나씩 늘어난다 → 다른 탭이나 예전 페이지의 번호와 절대 겹치지 않는다.
|
|
89
|
+
*/
|
|
90
|
+
refAllocator(agent) {
|
|
91
|
+
let a = this.refAlloc.get(agent);
|
|
92
|
+
if (!a)
|
|
93
|
+
this.refAlloc.set(agent, (a = { byNode: new Map(), next: 0 }));
|
|
94
|
+
const alloc = a;
|
|
95
|
+
// 다른 사이트 iframe은 요소 ID 번호가 따로 매겨지므로 iframe 대상 ID까지 합쳐서 구분한다
|
|
96
|
+
return (id, targetId) => {
|
|
97
|
+
const key = targetId ? `${targetId}:${id}` : id;
|
|
98
|
+
let ref = alloc.byNode.get(key);
|
|
99
|
+
if (!ref) {
|
|
100
|
+
ref = `e${nextRefNo(agent)}`;
|
|
101
|
+
alloc.byNode.set(key, ref);
|
|
102
|
+
}
|
|
103
|
+
return ref;
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** 이 에이전트의 기록(ref·스냅샷·마지막 조작 시각)을 지운다 (오래 안 나타난 에이전트 정리용). */
|
|
107
|
+
forgetAgent(agent) {
|
|
108
|
+
this.refMaps.delete(agent);
|
|
109
|
+
this.snapshots.delete(agent);
|
|
110
|
+
this.refAlloc.delete(agent);
|
|
111
|
+
this.actionStartedAt.delete(agent);
|
|
112
|
+
}
|
|
113
|
+
refsFor(agent) {
|
|
114
|
+
return this.refMaps.get(agent) ?? new Map();
|
|
115
|
+
}
|
|
116
|
+
/** 메인 프레임 ID (처음 한 번 조회 후 이벤트로 갱신). */
|
|
117
|
+
async mainFrame() {
|
|
118
|
+
if (this.mainFrameId)
|
|
119
|
+
return this.mainFrameId;
|
|
120
|
+
const { frameTree } = await this.conn.send('Page.getFrameTree', {}, 5000);
|
|
121
|
+
this.mainFrameId = frameTree.frame.id;
|
|
122
|
+
return this.mainFrameId;
|
|
123
|
+
}
|
|
124
|
+
/** 프레임의 isolated world 실행 컨텍스트 ID. 없으면 만든다. */
|
|
125
|
+
async world(frameId) {
|
|
126
|
+
const fid = frameId ?? (await this.mainFrame());
|
|
127
|
+
let w = this.worlds.get(fid);
|
|
128
|
+
if (!w) {
|
|
129
|
+
w = this.conn.send('Page.createIsolatedWorld', { frameId: fid, worldName: 'cdpm', grantUniveralAccess: false }, 5000)
|
|
130
|
+
.then((r) => r.executionContextId);
|
|
131
|
+
w.catch(() => this.worlds.delete(fid));
|
|
132
|
+
this.worlds.set(fid, w);
|
|
133
|
+
}
|
|
134
|
+
return w;
|
|
135
|
+
}
|
|
136
|
+
/** 실행 공간이 사라졌다는 오류면 다시 만들어 한 번 더 시도한다. */
|
|
137
|
+
async inWorld(frameId, fn) {
|
|
138
|
+
try {
|
|
139
|
+
return await fn(await this.world(frameId));
|
|
140
|
+
}
|
|
141
|
+
catch (e) {
|
|
142
|
+
if (!/context|Cannot find|not found/i.test(e.message))
|
|
143
|
+
throw e;
|
|
144
|
+
this.worlds.delete(frameId ?? this.mainFrameId ?? '');
|
|
145
|
+
if (!frameId)
|
|
146
|
+
this.mainFrameId = undefined;
|
|
147
|
+
return fn(await this.world(frameId));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** isolated world에서 식을 평가한다. */
|
|
151
|
+
async evaluate(expression, opts = {}) {
|
|
152
|
+
return this.inWorld(opts.frameId, async (contextId) => {
|
|
153
|
+
const r = await this.conn.send('Runtime.evaluate', { expression, contextId, returnByValue: true, awaitPromise: opts.awaitPromise ?? false }, opts.timeoutMs);
|
|
154
|
+
if (r.exceptionDetails)
|
|
155
|
+
return { type: 'exception', exception: r.exceptionDetails.exception?.description ?? r.exceptionDetails.text };
|
|
156
|
+
return r.result;
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
setSnapshot(agent, refs, cache) {
|
|
160
|
+
this.refMaps.set(agent, refs);
|
|
161
|
+
this.snapshots.set(agent, cache);
|
|
162
|
+
// 주소가 안 바뀌는 SPA에서는 페이지 이동 때 비우는 일이 없어 요소 → 번호 기록이 계속 늘어난다.
|
|
163
|
+
// 많아지면 지금 스냅샷에 있는 요소만 남긴다 (지금 쓸 수 있는 ref는 그대로 유효).
|
|
164
|
+
const a = this.refAlloc.get(agent);
|
|
165
|
+
if (a && a.byNode.size > REF_ALLOC_MAX) {
|
|
166
|
+
for (const [key, ref] of a.byNode)
|
|
167
|
+
if (!refs.has(ref))
|
|
168
|
+
a.byNode.delete(key);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
snapshotFor(agent) {
|
|
172
|
+
return this.snapshots.get(agent);
|
|
173
|
+
}
|
|
174
|
+
/** 오래된 스냅샷 사본(페이지당 수십만 자일 수 있음)을 지운다. */
|
|
175
|
+
pruneSnapshots(maxAgeMs) {
|
|
176
|
+
const cutoff = Date.now() - maxAgeMs;
|
|
177
|
+
for (const [agent, snap] of this.snapshots)
|
|
178
|
+
if (snap.at < cutoff)
|
|
179
|
+
this.snapshots.delete(agent);
|
|
180
|
+
}
|
|
181
|
+
send(method, params = {}, timeoutMs) {
|
|
182
|
+
return this.conn.send(method, params, timeoutMs);
|
|
183
|
+
}
|
|
184
|
+
/** 명령 실행 중 dialog가 뜨면 기다리지 않고 바로 돌아온다 (dialog가 떠 있으면 렌더러가 멈춰 응답이 안 오므로). */
|
|
185
|
+
async sendUnlessDialog(method, params = {}, timeoutMs) {
|
|
186
|
+
if (this.dialog)
|
|
187
|
+
return 'dialog';
|
|
188
|
+
// 명령 하나마다 거는 감시이므로 명령이 끝나면 바로 푼다 (긴 글을 치면 수천 개가 쌓이지 않게)
|
|
189
|
+
let off = () => { };
|
|
190
|
+
const dialogOpened = new Promise((resolve) => { off = this.conn.on('Page.javascriptDialogOpening', () => resolve('dialog')); });
|
|
191
|
+
try {
|
|
192
|
+
return await Promise.race([this.conn.send(method, params, timeoutMs), dialogOpened]);
|
|
193
|
+
}
|
|
194
|
+
finally {
|
|
195
|
+
off();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* 뒤에 숨은 탭은 Chrome이 다시 그리지 않아서, 숨은 뒤 바뀐 내용은 캡처되지 않고 클릭 위치 판정도 옛 화면 기준이 된다.
|
|
200
|
+
* 그래서 숨은 탭을 조작·캡처하는 동안에만 포커스 에뮬레이션을 켜서 그리게 하고, 끝나면 바로 끈다.
|
|
201
|
+
* 탭 전환·창 이동 같은 사용자 화면 변화는 없다. 앞에 보이는 탭에는 아무것도 하지 않는다.
|
|
202
|
+
*/
|
|
203
|
+
async withRendering(fn) {
|
|
204
|
+
if (this.renderHolds === 0 && !this.emulating) {
|
|
205
|
+
if ((await this.visibility()) !== 'hidden')
|
|
206
|
+
return fn();
|
|
207
|
+
// 성공했을 때만 켜진 것으로 적는다 (실패했는데 켜졌다고 적으면 다음 조작에서 다시 켜지 않음)
|
|
208
|
+
this.emulating = await this.conn.send('Emulation.setFocusEmulationEnabled', { enabled: true }, 3000).then(() => true, () => false);
|
|
209
|
+
if (this.emulating)
|
|
210
|
+
await new Promise((r) => setTimeout(r, 60)); // 첫 프레임이 그려질 시간
|
|
211
|
+
}
|
|
212
|
+
this.renderHolds++;
|
|
213
|
+
try {
|
|
214
|
+
return await fn();
|
|
215
|
+
}
|
|
216
|
+
finally {
|
|
217
|
+
if (--this.renderHolds === 0 && this.emulating) {
|
|
218
|
+
this.emulating = false;
|
|
219
|
+
const off = this.conn.send('Emulation.setFocusEmulationEnabled', { enabled: false }, LONG_WAIT_MS).catch(() => undefined);
|
|
220
|
+
if (!this.dialog)
|
|
221
|
+
await off; // 알림창이 떠 있으면 응답이 늦으므로 보내 두기만 한다
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/** 탭이 실제로 화면에 보이는지. 포커스 에뮬레이션을 쓰지 않으므로 이 값이 곧 '앞에 있는 탭'이다. */
|
|
226
|
+
async visibility(timeoutMs = 2000) {
|
|
227
|
+
if (this.dialog) {
|
|
228
|
+
this.watchLiveness();
|
|
229
|
+
return 'unknown';
|
|
230
|
+
}
|
|
231
|
+
try {
|
|
232
|
+
const r = await this.evaluate('document.visibilityState', { timeoutMs });
|
|
233
|
+
return r.value === 'visible' ? 'visible' : r.value === 'hidden' ? 'hidden' : 'unknown';
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
return 'unknown';
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
lastVisibility;
|
|
240
|
+
/** 앞 탭이 바뀌었을 때(탭 선택) 저장해 둔 보임 상태를 버린다. */
|
|
241
|
+
forgetVisibility() {
|
|
242
|
+
this.lastVisibility = undefined;
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* 탭 목록의 "·앞" 표시용 보임 상태. 매번 묻되 0.3초만 기다린다: 다른 에이전트의 탭이 무거운 페이지를 그리느라 바빠도
|
|
246
|
+
* 내 호출이 그 탭 때문에 늦어지지 않게 한다. 제때 답이 없으면 마지막으로 잰 값을 쓴다.
|
|
247
|
+
*/
|
|
248
|
+
async visibilityForList() {
|
|
249
|
+
const v = await this.visibility(300);
|
|
250
|
+
if (v !== 'unknown') {
|
|
251
|
+
this.lastVisibility = { value: v, at: Date.now() };
|
|
252
|
+
return v;
|
|
253
|
+
}
|
|
254
|
+
return this.lastVisibility?.value ?? v;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* 알림창이 떠 있으면 오류. 단, '닫힘' 신호를 놓쳤을 수 있으므로(다른 프로그램이 닫았거나 연결이 잠깐 끊김)
|
|
258
|
+
* 탭이 짧게라도 응답하면 이미 닫힌 것으로 보고 기록을 지운다. 알림창이 떠 있으면 렌더러가 멈춰 응답이 없다.
|
|
259
|
+
*/
|
|
260
|
+
async ensureNoDialog() {
|
|
261
|
+
if (!this.dialog)
|
|
262
|
+
return;
|
|
263
|
+
this.watchLiveness();
|
|
264
|
+
this.assertNoDialog();
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* 탭이 멈춰 있는 동안(알림창 등) 명령 하나를 걸어 둔다. 그 명령의 응답이 실제로 도착하는 순간이
|
|
268
|
+
* '다시 움직인다'는 확실한 신호다. 알림창 닫힘 이벤트를 놓쳤어도 이걸로 스스로 회복한다.
|
|
269
|
+
*/
|
|
270
|
+
watchLiveness() {
|
|
271
|
+
if (this.livenessWatch || this.conn.closed)
|
|
272
|
+
return;
|
|
273
|
+
this.livenessWatch = true;
|
|
274
|
+
sendUntilAnswered(this.conn, 'Runtime.evaluate', { expression: '0', returnByValue: true })
|
|
275
|
+
.then(async () => {
|
|
276
|
+
this.dialog = undefined;
|
|
277
|
+
if (this.pendingEnable) {
|
|
278
|
+
this.pendingEnable = false;
|
|
279
|
+
await this.network.enable();
|
|
280
|
+
}
|
|
281
|
+
})
|
|
282
|
+
.catch(() => undefined)
|
|
283
|
+
.finally(() => { this.livenessWatch = false; });
|
|
284
|
+
}
|
|
285
|
+
/** 붙을 때 탭이 아직 답하지 않음 (알림창이 떠 있거나 무거운 작업 중). 응답이 오면 자동으로 풀린다. */
|
|
286
|
+
markUnresponsive() {
|
|
287
|
+
this.pendingEnable = true;
|
|
288
|
+
this.dialog ??= { type: '응답 대기', message: '탭이 아직 응답하지 않아요 (알림창이 떠 있거나 무거운 작업 중)', at: new Date().toISOString() };
|
|
289
|
+
}
|
|
290
|
+
/** 붙을 때 보낸 Page.enable이 나중에라도 끝나면: 탭이 다시 움직인다는 신호 */
|
|
291
|
+
enabledLater() {
|
|
292
|
+
if (this.dialog?.type === '응답 대기')
|
|
293
|
+
this.dialog = undefined;
|
|
294
|
+
if (this.pendingEnable) {
|
|
295
|
+
this.pendingEnable = false;
|
|
296
|
+
void this.network.enable();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
assertNoDialog() {
|
|
300
|
+
if (this.dialog) {
|
|
301
|
+
throw new CdpmError(`이 탭에 ${this.dialog.type} 알림창이 떠 있어요: "${this.dialog.message}"\n` +
|
|
302
|
+
'내용을 보고 판단해서 browser_dialog로 직접 처리하세요 (확인 accept: true, 취소 false). 사용자가 시키지 않은 되돌릴 수 없는 일(결제·삭제 등)을 확정하는 창일 때만 사용자에게 물어보세요.');
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/** 다른 세션의 탭 조작이 끝나길 기다리는 최대 시간 */
|
|
307
|
+
const TAB_LOCK_WAIT_MS = 120_000;
|
|
308
|
+
/** 요소 → ref 번호 기록이 이만큼 넘으면 지금 스냅샷에 있는 것만 남긴다 */
|
|
309
|
+
const REF_ALLOC_MAX = 5000;
|
|
310
|
+
/** 응답이 늦을 수 있는 명령(알림창이 떠 있는 탭 등)을 한 번에 기다리는 시간. 넘으면 연결이 살아 있는 동안 다시 건다 */
|
|
311
|
+
const LONG_WAIT_MS = 10 * 60_000;
|
|
312
|
+
/**
|
|
313
|
+
* 답이 올 때까지 보낸다: 10분 안에 답이 없으면 연결이 살아 있는 동안 다시 보낸다.
|
|
314
|
+
* (예전에는 24시간짜리 한 번이었다. 오래 켜 두는 작업에서 걸려 있는 시간을 짧게 나눈다.)
|
|
315
|
+
*/
|
|
316
|
+
async function sendUntilAnswered(conn, method, params) {
|
|
317
|
+
for (;;) {
|
|
318
|
+
try {
|
|
319
|
+
return await conn.send(method, params, LONG_WAIT_MS);
|
|
320
|
+
}
|
|
321
|
+
catch (e) {
|
|
322
|
+
if (!(e instanceof CdpTimeoutError) || conn.closed)
|
|
323
|
+
throw e;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/** 에이전트별 ref 번호 카운터 (프로세스 전체 공용) */
|
|
328
|
+
const refCounters = new Map();
|
|
329
|
+
// ---------- 에이전트 기록 정리 ----------
|
|
330
|
+
// 서브에이전트는 이름이 계속 새로 생긴다. 오래 켜 두면 이름별 기록이 끝없이 늘어나므로,
|
|
331
|
+
// 6시간 동안 한 번도 안 나타난 에이전트는 이 프로세스의 모든 기록(ref·스냅샷·마지막 탭 등)에서 지운다.
|
|
332
|
+
// 오래 켜 두기 시험만 CDPM_TEST_AGENT_FORGET_MS로 짧게 한다
|
|
333
|
+
const AGENT_FORGET_MS = Number(process.env.CDPM_TEST_AGENT_FORGET_MS) || 6 * 3600_000;
|
|
334
|
+
const agentSeen = new Map();
|
|
335
|
+
const forgetHooks = [];
|
|
336
|
+
export function touchAgent(agent) {
|
|
337
|
+
agentSeen.set(agent, Date.now());
|
|
338
|
+
}
|
|
339
|
+
/** 에이전트를 잊을 때 다른 모듈의 기록도 함께 지우도록 등록한다. */
|
|
340
|
+
export function onAgentForgotten(fn) {
|
|
341
|
+
forgetHooks.push(fn);
|
|
342
|
+
}
|
|
343
|
+
function forgetIdleAgents(now = Date.now()) {
|
|
344
|
+
for (const [agent, at] of agentSeen) {
|
|
345
|
+
if (now - at < AGENT_FORGET_MS)
|
|
346
|
+
continue;
|
|
347
|
+
agentSeen.delete(agent);
|
|
348
|
+
// 이 에이전트의 ref가 이 프로세스 어디에도 남지 않으므로 번호를 다시 1부터 써도 겹치지 않는다
|
|
349
|
+
refCounters.delete(agent);
|
|
350
|
+
for (const s of pageSessions.values())
|
|
351
|
+
s.forgetAgent(agent);
|
|
352
|
+
for (const fn of forgetHooks) {
|
|
353
|
+
try {
|
|
354
|
+
fn(agent);
|
|
355
|
+
}
|
|
356
|
+
catch { /* 무시 */ }
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function nextRefNo(agent) {
|
|
361
|
+
const n = (refCounters.get(agent) ?? 0) + 1;
|
|
362
|
+
refCounters.set(agent, n);
|
|
363
|
+
return n;
|
|
364
|
+
}
|
|
365
|
+
const browserConns = new Map();
|
|
366
|
+
const pageSessions = new Map();
|
|
367
|
+
const connecting = new Map();
|
|
368
|
+
/** 슬롯의 모든 탭 연결이 저장해 둔 보임 상태를 버린다 (앞 탭을 바꾼 뒤). */
|
|
369
|
+
export function forgetSlotVisibility(slot) {
|
|
370
|
+
for (const [key, s] of pageSessions)
|
|
371
|
+
if (key.startsWith(`${slot}:`))
|
|
372
|
+
s.forgetVisibility();
|
|
373
|
+
}
|
|
374
|
+
/** 이 프로세스가 이 슬롯 Chrome에 열어 둔 연결이 아직 살아 있는지 (살아 있으면 Chrome도 떠 있다). */
|
|
375
|
+
export function hasLiveBrowserConnection(slot) {
|
|
376
|
+
const c = browserConns.get(slot);
|
|
377
|
+
return !!c && !c.closed;
|
|
378
|
+
}
|
|
379
|
+
export async function browserConnection(slot) {
|
|
380
|
+
const cached = browserConns.get(slot);
|
|
381
|
+
if (cached && !cached.closed)
|
|
382
|
+
return cached;
|
|
383
|
+
const p = await probe(slot);
|
|
384
|
+
if (p.state !== 'chrome')
|
|
385
|
+
throw new CdpmError(`${slot}번 Chrome이 떠 있지 않습니다 (포트 ${portOf(slot)}).`);
|
|
386
|
+
const conn = await CdpConnection.connect(p.version.webSocketDebuggerUrl);
|
|
387
|
+
conn.onClosed(() => browserConns.delete(slot));
|
|
388
|
+
browserConns.set(slot, conn);
|
|
389
|
+
return conn;
|
|
390
|
+
}
|
|
391
|
+
/** 탭 연결을 얻는다. 같은 탭에 동시에 요청이 와도 연결은 하나만 만든다. */
|
|
392
|
+
export async function pageSession(slot, targetId, wsUrl) {
|
|
393
|
+
const key = `${slot}:${targetId}`;
|
|
394
|
+
const cached = pageSessions.get(key);
|
|
395
|
+
if (cached && !cached.conn.closed) {
|
|
396
|
+
cached.lastUsed = Date.now();
|
|
397
|
+
return cached;
|
|
398
|
+
}
|
|
399
|
+
const pending = connecting.get(key);
|
|
400
|
+
if (pending)
|
|
401
|
+
return pending;
|
|
402
|
+
const p = (async () => {
|
|
403
|
+
let url = wsUrl;
|
|
404
|
+
if (!url) {
|
|
405
|
+
const t = (await listPages(slot)).find((x) => x.id === targetId) ?? (await listFrameTargets(slot)).find((x) => x.id === targetId);
|
|
406
|
+
url = t?.webSocketDebuggerUrl;
|
|
407
|
+
}
|
|
408
|
+
if (!url)
|
|
409
|
+
throw new CdpmError('탭을 찾을 수 없습니다 (닫혔을 수 있어요).');
|
|
410
|
+
const conn = await CdpConnection.connect(url);
|
|
411
|
+
const session = new PageSession(slot, targetId, conn);
|
|
412
|
+
conn.onClosed(() => pageSessions.delete(key));
|
|
413
|
+
pageSessions.set(key, session);
|
|
414
|
+
// Page.enable: dialog·로딩 이벤트용. 이미 떠 있는 dialog도 이때 알려준다.
|
|
415
|
+
// Runtime.enable(봇 탐지 흔적)과 Emulation.*(사용자 환경 변경)은 쓰지 않는다.
|
|
416
|
+
// 알림창이 떠 있으면 새 연결의 Page.enable은 응답하지 않는다 (렌더러가 멈춤).
|
|
417
|
+
// 오래 기다리지 않고 '알림창이 떠 있을 수 있음'으로 표시해 두면, 탭이 응답하는 순간 자동으로 지워진다.
|
|
418
|
+
// Page.enable은 끝날 때까지 기다리되(시간 제한으로 실패 처리하지 않음), 도구가 멈추지 않도록 1.5초 안에 안 끝나면
|
|
419
|
+
// '응답 대기' 상태로 먼저 돌려준다. 나중에 끝나는 순간 상태가 풀린다.
|
|
420
|
+
const enable = sendUntilAnswered(conn, 'Page.enable', {}).then(() => true, () => false);
|
|
421
|
+
const quick = await Promise.race([enable, new Promise((r) => setTimeout(() => r('later'), 1500))]);
|
|
422
|
+
if (quick === 'later') {
|
|
423
|
+
session.markUnresponsive();
|
|
424
|
+
void enable.then((ok) => ok && session.enabledLater());
|
|
425
|
+
return session;
|
|
426
|
+
}
|
|
427
|
+
// 네트워크 기록은 붙는 순간부터 (그 전 요청은 볼 수 없음)
|
|
428
|
+
await session.network.enable();
|
|
429
|
+
return session;
|
|
430
|
+
})();
|
|
431
|
+
connecting.set(key, p);
|
|
432
|
+
try {
|
|
433
|
+
return await p;
|
|
434
|
+
}
|
|
435
|
+
finally {
|
|
436
|
+
connecting.delete(key);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
/** 이 프로세스가 붙어 있는 탭의 dialog 상태 (머리말 표시용). */
|
|
440
|
+
export function knownDialog(slot, targetId) {
|
|
441
|
+
return pageSessions.get(`${slot}:${targetId}`)?.dialog;
|
|
442
|
+
}
|
|
443
|
+
export function dropSlotConnections(slot) {
|
|
444
|
+
browserConns.get(slot)?.close();
|
|
445
|
+
for (const [key, s] of pageSessions)
|
|
446
|
+
if (s.slot === slot) {
|
|
447
|
+
s.conn.close();
|
|
448
|
+
pageSessions.delete(key);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
const IDLE_CLOSE_MS = 10 * 60_000;
|
|
452
|
+
/** 알림창이 떠 있거나 응답이 없는 탭이라도 이만큼 안 쓰면 연결을 끊는다 (걸려 있던 명령도 함께 정리됨) */
|
|
453
|
+
const STUCK_CLOSE_MS = 30 * 60_000;
|
|
454
|
+
const SNAPSHOT_MAX_AGE_MS = 5 * 60_000;
|
|
455
|
+
let sweeper;
|
|
456
|
+
/**
|
|
457
|
+
* 1분마다 정리: 10분 동안 안 쓴 탭 연결은 끊고(그 탭의 네트워크 기록도 멈춤),
|
|
458
|
+
* 오래된 스냅샷 사본과 네트워크 기록을 지운다. 요청 막기 규칙이 걸린 탭은 연결을 유지한다.
|
|
459
|
+
*/
|
|
460
|
+
export function startSweeper() {
|
|
461
|
+
if (sweeper)
|
|
462
|
+
return;
|
|
463
|
+
cleanStaleTabLocks();
|
|
464
|
+
sweeper = setInterval(() => {
|
|
465
|
+
const now = Date.now();
|
|
466
|
+
forgetIdleAgents(now);
|
|
467
|
+
cleanStaleTabLocks();
|
|
468
|
+
for (const [key, s] of pageSessions) {
|
|
469
|
+
s.pruneSnapshots(SNAPSHOT_MAX_AGE_MS);
|
|
470
|
+
s.network.prune();
|
|
471
|
+
const idle = now - s.lastUsed;
|
|
472
|
+
if ((idle > IDLE_CLOSE_MS && !s.network.rules.length && !s.dialog) || (idle > STUCK_CLOSE_MS && !s.network.rules.length)) {
|
|
473
|
+
s.conn.close();
|
|
474
|
+
pageSessions.delete(key);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
for (const [slot, c] of browserConns) {
|
|
478
|
+
const used = [...pageSessions.values()].some((s) => s.slot === slot);
|
|
479
|
+
if (!used) {
|
|
480
|
+
c.close();
|
|
481
|
+
browserConns.delete(slot);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}, 60_000);
|
|
485
|
+
sweeper.unref();
|
|
486
|
+
}
|
|
487
|
+
/** 조작 도중 프로세스가 죽어 남은 탭 잠금 파일을 지운다 (잡은 프로세스가 죽은 것만). */
|
|
488
|
+
function cleanStaleTabLocks() {
|
|
489
|
+
const dir = path.dirname(paths.tabLock(1, 'x'));
|
|
490
|
+
let names;
|
|
491
|
+
try {
|
|
492
|
+
names = fs.readdirSync(dir);
|
|
493
|
+
}
|
|
494
|
+
catch {
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
for (const n of names) {
|
|
498
|
+
if (!n.endsWith('.lock'))
|
|
499
|
+
continue;
|
|
500
|
+
const file = path.join(dir, n);
|
|
501
|
+
try {
|
|
502
|
+
const pid = Number(fs.readFileSync(file, 'utf8'));
|
|
503
|
+
if (pid > 0 && !pidAlive(pid))
|
|
504
|
+
fs.unlinkSync(file);
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
// 그 사이 풀렸으면 무시
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
/** 프로세스를 끝내기 전에 모든 CDP 연결을 닫는다. */
|
|
512
|
+
export function closeAllConnections() {
|
|
513
|
+
for (const c of browserConns.values())
|
|
514
|
+
c.close();
|
|
515
|
+
for (const s of pageSessions.values())
|
|
516
|
+
s.conn.close();
|
|
517
|
+
browserConns.clear();
|
|
518
|
+
pageSessions.clear();
|
|
519
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { portOf } from '../slots.js';
|
|
2
|
+
/** 슬롯 포트에 무엇이 있는지 확인한다. */
|
|
3
|
+
export async function probe(slot, timeoutMs = 1500) {
|
|
4
|
+
const url = `http://127.0.0.1:${portOf(slot)}/json/version`;
|
|
5
|
+
let res;
|
|
6
|
+
try {
|
|
7
|
+
res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
|
|
8
|
+
}
|
|
9
|
+
catch (e) {
|
|
10
|
+
if (e?.name === 'TimeoutError')
|
|
11
|
+
return { state: 'slow' };
|
|
12
|
+
const code = e?.cause?.code;
|
|
13
|
+
if (code === 'ECONNREFUSED')
|
|
14
|
+
return { state: 'free' };
|
|
15
|
+
return { state: 'other', detail: String(code ?? e.message) };
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
const body = (await res.json());
|
|
19
|
+
if (body && typeof body.Browser === 'string' && body.webSocketDebuggerUrl)
|
|
20
|
+
return { state: 'chrome', version: body };
|
|
21
|
+
return { state: 'other', detail: `HTTP ${res.status}` };
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return { state: 'other', detail: `HTTP ${res.status} (JSON 아님)` };
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** 탭(page) 목록. Chrome이 돌려주는 순서 그대로 (첫 번째가 가장 최근 활성 탭). */
|
|
28
|
+
export async function listPages(slot, timeoutMs = 10_000) {
|
|
29
|
+
const res = await fetch(`http://127.0.0.1:${portOf(slot)}/json/list`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
30
|
+
const all = (await res.json());
|
|
31
|
+
return all
|
|
32
|
+
.filter((t) => t.type === 'page' && !t.url.startsWith('devtools://'))
|
|
33
|
+
.map((t) => ({ ...t, title: decodeEntities(t.title) }));
|
|
34
|
+
}
|
|
35
|
+
/** 다른 사이트 iframe(별도 프로세스) 대상들. 대상 ID는 그 iframe의 프레임 ID와 같다. */
|
|
36
|
+
export async function listFrameTargets(slot, timeoutMs = 10_000) {
|
|
37
|
+
const res = await fetch(`http://127.0.0.1:${portOf(slot)}/json/list`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
38
|
+
return (await res.json()).filter((t) => t.type === 'iframe');
|
|
39
|
+
}
|
|
40
|
+
/** /json/list는 제목을 HTML 엔티티로 준다 (< 등). */
|
|
41
|
+
function decodeEntities(s) {
|
|
42
|
+
return s.replace(/&(lt|gt|amp|quot|#39|#x27|nbsp);/g, (_, e) => ({ lt: '<', gt: '>', amp: '&', quot: '"', '#39': "'", '#x27': "'", nbsp: ' ' }[e]));
|
|
43
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { CdpmError } from '../errors.js';
|
|
5
|
+
import { paths, readConfig } from '../paths.js';
|
|
6
|
+
const APP_PATHS = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe';
|
|
7
|
+
/** 찾을 후보를 우선순위대로 돌려준다. */
|
|
8
|
+
export function chromeCandidates(deps) {
|
|
9
|
+
const out = [];
|
|
10
|
+
if (deps.configPath)
|
|
11
|
+
out.push(deps.configPath);
|
|
12
|
+
if (deps.platform === 'win32') {
|
|
13
|
+
for (const hive of ['HKLM', 'HKCU']) {
|
|
14
|
+
const v = deps.regQuery(`${hive}\\${APP_PATHS}`);
|
|
15
|
+
if (v)
|
|
16
|
+
out.push(v);
|
|
17
|
+
}
|
|
18
|
+
const { ProgramFiles, LOCALAPPDATA } = deps.env;
|
|
19
|
+
const pf86 = deps.env['ProgramFiles(x86)'];
|
|
20
|
+
for (const base of [ProgramFiles, pf86, LOCALAPPDATA]) {
|
|
21
|
+
if (base)
|
|
22
|
+
out.push(path.win32.join(base, 'Google', 'Chrome', 'Application', 'chrome.exe'));
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
else if (deps.platform === 'darwin') {
|
|
26
|
+
const exe = 'Contents/MacOS/Google Chrome';
|
|
27
|
+
out.push(path.posix.join('/Applications/Google Chrome.app', exe));
|
|
28
|
+
if (deps.env.HOME)
|
|
29
|
+
out.push(path.posix.join(deps.env.HOME, 'Applications/Google Chrome.app', exe));
|
|
30
|
+
// 다른 폴더에 설치했으면 Spotlight(앱 ID com.google.Chrome)로 찾는다
|
|
31
|
+
for (const app of deps.spotlight?.() ?? [])
|
|
32
|
+
out.push(path.posix.join(app, exe));
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
out.push('/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/opt/google/chrome/chrome');
|
|
36
|
+
}
|
|
37
|
+
return [...new Set(out)];
|
|
38
|
+
}
|
|
39
|
+
export function findChromeWith(deps) {
|
|
40
|
+
const candidates = chromeCandidates(deps);
|
|
41
|
+
const found = candidates.find((p) => deps.exists(p));
|
|
42
|
+
if (found)
|
|
43
|
+
return found;
|
|
44
|
+
throw new CdpmError('Chrome을 찾지 못했습니다. 찾아본 경로:\n' +
|
|
45
|
+
candidates.map((c) => ` - ${c}`).join('\n') +
|
|
46
|
+
`\n${paths.config()} 파일에 {"chromePath": "Chrome 실행 파일 전체 경로"}를 넣어 직접 지정할 수 있어요.`);
|
|
47
|
+
}
|
|
48
|
+
function regQuery(key) {
|
|
49
|
+
try {
|
|
50
|
+
const out = execFileSync('reg', ['query', key, '/ve'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
|
|
51
|
+
const m = out.match(/REG_(?:EXPAND_)?SZ\s+(.+)/);
|
|
52
|
+
return m ? m[1].trim().replace(/^"|"$/g, '') : undefined;
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function spotlight() {
|
|
59
|
+
try {
|
|
60
|
+
const out = execFileSync('mdfind', ['kMDItemCFBundleIdentifier == "com.google.Chrome"'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
|
|
61
|
+
return out.split('\n').map((l) => l.trim()).filter((l) => l.endsWith('.app'));
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
let cached;
|
|
68
|
+
export function findChrome() {
|
|
69
|
+
if (cached && fs.existsSync(cached))
|
|
70
|
+
return cached;
|
|
71
|
+
cached = findChromeWith({
|
|
72
|
+
exists: (p) => {
|
|
73
|
+
try {
|
|
74
|
+
return fs.statSync(p).isFile();
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
regQuery,
|
|
81
|
+
spotlight: process.platform === 'darwin' ? spotlight : undefined,
|
|
82
|
+
env: process.env,
|
|
83
|
+
platform: process.platform,
|
|
84
|
+
configPath: readConfig().chromePath,
|
|
85
|
+
});
|
|
86
|
+
return cached;
|
|
87
|
+
}
|