Repository navigation
Expand file tree
/
Copy pathcli.js
More file actions
618 lines (525 loc) · 15.2 KB
/
Copy pathcli.js
File metadata and controls
618 lines (525 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
#!/usr/bin/env node
const CDP = require('chrome-remote-interface');
const { spawn, execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const DEFAULT_PORT = 9222;
const DEFAULT_TIMEOUT = 30000;
const DISPLAY = ':0';
// Cross-platform Chrome binary detection
function findChromeBinary() {
// Allow override via environment variable
if (process.env.CHROME_BINARY) {
return process.env.CHROME_BINARY;
}
const platform = process.platform;
if (platform === 'linux') {
// Try common Linux Chrome/Chromium binaries
const candidates = [
'google-chrome-stable',
'google-chrome',
'chromium-browser',
'chromium'
];
for (const binary of candidates) {
try {
execSync(`which ${binary}`, { stdio: 'ignore' });
return binary;
} catch (err) {
// Binary not found, try next
}
}
} else if (platform === 'darwin') {
// macOS
const macPaths = [
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/Applications/Chromium.app/Contents/MacOS/Chromium'
];
for (const chromePath of macPaths) {
if (fs.existsSync(chromePath)) {
return chromePath;
}
}
} else if (platform === 'win32') {
// Windows
const winPaths = [
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
path.join(process.env.LOCALAPPDATA || '', 'Google\\Chrome\\Application\\chrome.exe')
];
for (const chromePath of winPaths) {
if (fs.existsSync(chromePath)) {
return chromePath;
}
}
}
// Fallback
return 'chromium-browser';
}
// Parse global flags and extract command + positionals
function parseArgs(argv) {
const flags = {
port: DEFAULT_PORT,
timeout: DEFAULT_TIMEOUT,
tab: null,
headless: false
};
const positionals = [];
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--port' && i + 1 < argv.length) {
flags.port = parseInt(argv[i + 1], 10);
i++; // Skip next arg
} else if (arg === '--timeout' && i + 1 < argv.length) {
flags.timeout = parseInt(argv[i + 1], 10);
i++;
} else if (arg === '--tab' && i + 1 < argv.length) {
flags.tab = argv[i + 1];
i++;
} else if (arg === '--headless') {
flags.headless = true;
} else if (!arg.startsWith('--')) {
positionals.push(arg);
}
}
const command = positionals[0] || null;
const commandArgs = positionals.slice(1);
return { flags, command, commandArgs };
}
// Helper to get CDP connection
async function getClient(port = DEFAULT_PORT, targetId = null) {
try {
// List all targets and find the active page
const targets = await CDP.List({ port });
let pageTarget;
if (targetId) {
pageTarget = targets.find(t => t.id === targetId);
if (!pageTarget) {
throw new Error(`Tab with ID ${targetId} not found`);
}
} else {
pageTarget = targets.find(t => t.type === 'page') || targets[0];
}
if (!pageTarget) {
throw new Error('No active page found. Launch Chrome first or open a tab.');
}
const client = await CDP({ port, target: pageTarget.id });
return client;
} catch (err) {
throw new Error(`Failed to connect to Chrome on port ${port}: ${err.message}`);
}
}
// Check if Chrome is already running on the port
async function isPortInUse(port) {
try {
await CDP.List({ port });
return true;
} catch (err) {
return false;
}
}
// Launch Chrome with remote debugging
async function launch(flags) {
const port = flags.port;
// Check if Chrome is already running on this port
if (await isPortInUse(port)) {
console.log(JSON.stringify({
success: true,
alreadyRunning: true,
port: port
}, null, 2));
return;
}
const homeDir = process.env.HOME || process.env.USERPROFILE;
const userDataDir = path.join(homeDir, '.chrome-ctl-data');
const chromeArgs = [
`--remote-debugging-port=${port}`,
`--user-data-dir=${userDataDir}`,
'--no-first-run',
'--no-default-browser-check'
];
if (flags.headless) {
chromeArgs.push('--headless=new');
}
const chromeBinary = findChromeBinary();
const env = { ...process.env, DISPLAY };
const chrome = spawn(chromeBinary, chromeArgs, {
env,
detached: true,
stdio: 'ignore'
});
chrome.unref();
// Wait a bit for Chrome to start
await new Promise(resolve => setTimeout(resolve, 2000));
console.log(JSON.stringify({
success: true,
port: port,
display: DISPLAY,
pid: chrome.pid,
headless: flags.headless
}, null, 2));
}
// List tabs
async function listTabs(flags) {
try {
const targets = await CDP.List({ port: flags.port });
const tabs = targets.filter(t => t.type === 'page').map(t => ({
id: t.id,
title: t.title,
url: t.url,
description: t.description
}));
console.log(JSON.stringify(tabs, null, 2));
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2));
process.exit(1);
}
}
// Close Chrome gracefully
async function close(flags) {
let client;
try {
client = await CDP({ port: flags.port });
const { Browser } = client;
await Browser.close();
console.log(JSON.stringify({
success: true,
message: 'Chrome closed gracefully'
}, null, 2));
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2));
process.exit(1);
} finally {
if (client) {
try {
await client.close();
} catch (e) {
// Browser already closed, ignore
}
}
}
}
// Navigate to URL
async function navigate(url, flags) {
let client;
try {
client = await getClient(flags.port, flags.tab);
const { Page } = client;
await Page.enable();
// Navigate
await Page.navigate({ url });
// Wait for page to load with timeout
const loadPromise = new Promise((resolve) => {
Page.loadEventFired(() => {
resolve({ timedOut: false });
});
});
const timeoutPromise = new Promise((resolve) => {
setTimeout(() => {
resolve({ timedOut: true });
}, flags.timeout);
});
const result = await Promise.race([loadPromise, timeoutPromise]);
console.log(JSON.stringify({
success: true,
url: url,
...result
}, null, 2));
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2));
process.exit(1);
} finally {
if (client) await client.close();
}
}
// Get accessibility tree snapshot
async function snapshot(flags) {
let client;
try {
client = await getClient(flags.port, flags.tab);
const { Accessibility, Page, Runtime } = client;
await Page.enable();
await Accessibility.enable();
// Get the full accessibility tree
const { nodes } = await Accessibility.getFullAXTree();
// Also get the current URL and title
const result = await Runtime.evaluate({ expression: 'document.title' });
const title = result.result.value;
const urlResult = await Runtime.evaluate({ expression: 'window.location.href' });
const url = urlResult.result.value;
console.log(JSON.stringify({
url,
title,
nodes: nodes.map(n => ({
nodeId: n.nodeId,
role: n.role?.value,
name: n.name?.value,
description: n.description?.value,
value: n.value?.value,
children: n.childIds
}))
}, null, 2));
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2));
process.exit(1);
} finally {
if (client) await client.close();
}
}
// Click element by selector
async function click(selector, flags) {
let client;
try {
client = await getClient(flags.port, flags.tab);
const { DOM, Runtime, Page } = client;
await Page.enable();
await DOM.enable();
await Runtime.enable();
// Find element and click it
const { result } = await Runtime.evaluate({
expression: `
(function() {
const el = document.querySelector('${selector.replace(/'/g, "\\'")}');
if (!el) return { error: 'Element not found' };
el.scrollIntoView({ block: 'center' });
const rect = el.getBoundingClientRect();
return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
})()
`,
returnByValue: true
});
if (result.value.error) {
throw new Error(result.value.error);
}
const { x, y } = result.value;
// Use Input domain to click
const { Input } = client;
await Input.dispatchMouseEvent({
type: 'mousePressed',
x, y,
button: 'left',
clickCount: 1
});
await Input.dispatchMouseEvent({
type: 'mouseReleased',
x, y,
button: 'left',
clickCount: 1
});
console.log(JSON.stringify({
success: true,
selector,
position: { x, y }
}, null, 2));
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2));
process.exit(1);
} finally {
if (client) await client.close();
}
}
// Type text into element
async function type(selector, text, flags) {
let client;
try {
client = await getClient(flags.port, flags.tab);
const { Runtime, Input, Page } = client;
await Page.enable();
await Runtime.enable();
// Focus the element first
await Runtime.evaluate({
expression: `
(function() {
const el = document.querySelector('${selector.replace(/'/g, "\\'")}');
if (!el) throw new Error('Element not found');
el.focus();
el.click();
})()
`
});
// Type each character
for (const char of text) {
await Input.dispatchKeyEvent({
type: 'char',
text: char
});
await new Promise(resolve => setTimeout(resolve, 50));
}
console.log(JSON.stringify({
success: true,
selector,
text
}, null, 2));
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2));
process.exit(1);
} finally {
if (client) await client.close();
}
}
// Evaluate JavaScript
async function evaluate(code, flags) {
let client;
try {
client = await getClient(flags.port, flags.tab);
const { Runtime, Page } = client;
await Page.enable();
await Runtime.enable();
const evalPromise = Runtime.evaluate({
expression: code,
returnByValue: true,
awaitPromise: true
});
const timeoutPromise = new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error(`Evaluation timed out after ${flags.timeout}ms`));
}, flags.timeout);
});
const { result, exceptionDetails } = await Promise.race([evalPromise, timeoutPromise]);
if (exceptionDetails) {
throw new Error(exceptionDetails.text);
}
console.log(JSON.stringify({
success: true,
result: result.value
}, null, 2));
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2));
process.exit(1);
} finally {
if (client) await client.close();
}
}
// Take screenshot
async function screenshot(outputPath, flags) {
let client;
try {
client = await getClient(flags.port, flags.tab);
const { Page } = client;
await Page.enable();
const { data } = await Page.captureScreenshot({ format: 'png' });
const finalPath = outputPath || `screenshot-${Date.now()}.png`;
fs.writeFileSync(finalPath, Buffer.from(data, 'base64'));
console.log(JSON.stringify({
success: true,
path: path.resolve(finalPath)
}, null, 2));
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2));
process.exit(1);
} finally {
if (client) await client.close();
}
}
// Wait for milliseconds
async function wait(ms) {
const duration = parseInt(ms, 10);
if (isNaN(duration)) {
console.error(JSON.stringify({ error: 'Invalid duration' }, null, 2));
process.exit(1);
}
await new Promise(resolve => setTimeout(resolve, duration));
console.log(JSON.stringify({
success: true,
waited: duration
}, null, 2));
}
// Main command router
async function main() {
try {
const rawArgs = process.argv.slice(2);
const { flags, command, commandArgs } = parseArgs(rawArgs);
switch (command) {
case 'launch':
await launch(flags);
break;
case 'tabs':
await listTabs(flags);
break;
case 'close':
await close(flags);
break;
case 'navigate':
if (!commandArgs[0]) {
console.error('Usage: chrome-ctl navigate <url>');
process.exit(1);
}
await navigate(commandArgs[0], flags);
break;
case 'snapshot':
await snapshot(flags);
break;
case 'click':
if (!commandArgs[0]) {
console.error('Usage: chrome-ctl click <selector>');
process.exit(1);
}
await click(commandArgs[0], flags);
break;
case 'type':
if (!commandArgs[0] || !commandArgs[1]) {
console.error('Usage: chrome-ctl type <selector> <text>');
process.exit(1);
}
await type(commandArgs[0], commandArgs.slice(1).join(' '), flags);
break;
case 'evaluate':
if (!commandArgs[0]) {
console.error('Usage: chrome-ctl evaluate <javascript>');
process.exit(1);
}
await evaluate(commandArgs.join(' '), flags);
break;
case 'screenshot':
await screenshot(commandArgs[0], flags);
break;
case 'wait':
if (!commandArgs[0]) {
console.error('Usage: chrome-ctl wait <ms>');
process.exit(1);
}
await wait(commandArgs[0]);
break;
default:
console.log(`chrome-ctl v1.1.0 - Chrome DevTools Protocol CLI
Usage:
chrome-ctl [options] <command> [args...]
Global Options:
--port <N> CDP port (default: 9222)
--timeout <ms> Timeout for navigate/evaluate (default: 30000)
--tab <id> Target specific tab by ID (from 'tabs' command)
--headless Launch Chrome in headless mode
Commands:
launch Launch Chrome with remote debugging
close Close Chrome gracefully
tabs List open tabs
navigate <url> Navigate current tab to URL
snapshot Get accessibility tree snapshot
click <selector> Click element by CSS selector
type <selector> <text> Type text into element
evaluate <js> Run JavaScript in the page
screenshot [path] Take a screenshot
wait <ms> Wait milliseconds
Examples:
chrome-ctl --headless launch
chrome-ctl --port 9223 tabs
chrome-ctl --tab <id> navigate https://example.com
chrome-ctl --timeout 60000 navigate https://slow-site.com
`);
break;
}
} catch (err) {
console.error(JSON.stringify({ error: err.message }, null, 2));
process.exit(1);
}
}
// Export for testing
if (require.main === module) {
main();
} else {
module.exports = {
parseArgs,
findChromeBinary,
isPortInUse
};
}