mirror of
https://github.com/Nikolay-Shirokov/cc-1c-skills.git
synced 2026-08-20 18:19:43 +03:00
feat(web-test): embed browser automation engine into skill
Move browser.mjs, dom.mjs, run.mjs from external 1c-web-client-mcp project into .claude/skills/web-test/scripts/. Now the skill is self-contained — copy .claude/skills/ + npm install is all that's needed. - Add scripts/package.json with playwright dependency - Update SKILL.md with relative runner path and setup section - Add node_modules/ and .browser-session.json to .gitignore Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
ba963739d8
commit
c8f58b5461
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* CLI runner for 1C web client automation.
|
||||
*
|
||||
* Architecture: `start` launches browser + HTTP server in one process.
|
||||
* `exec`, `shot`, `stop` send requests to the running server.
|
||||
*
|
||||
* Usage:
|
||||
* node src/run.mjs start <url> — launch browser, connect to 1C, serve requests
|
||||
* node src/run.mjs exec <file|-> — run script against existing session
|
||||
* node src/run.mjs shot [file] — take screenshot
|
||||
* node src/run.mjs stop — logout + close browser
|
||||
* node src/run.mjs status — check session
|
||||
*/
|
||||
import http from 'http';
|
||||
import * as browser from './browser.mjs';
|
||||
import { readFileSync, writeFileSync, unlinkSync, existsSync } from 'fs';
|
||||
import { resolve, dirname } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const SESSION_FILE = resolve(__dirname, '..', '.browser-session.json');
|
||||
|
||||
const [,, cmd, ...args] = process.argv;
|
||||
|
||||
switch (cmd) {
|
||||
case 'start': await cmdStart(args[0]); break;
|
||||
case 'exec': await cmdExec(args[0]); break;
|
||||
case 'shot': await cmdShot(args[0]); break;
|
||||
case 'stop': await cmdStop(); break;
|
||||
case 'status': cmdStatus(); break;
|
||||
default: usage();
|
||||
}
|
||||
|
||||
|
||||
// ============================================================
|
||||
// start: launch browser + HTTP server
|
||||
// ============================================================
|
||||
|
||||
async function cmdStart(url) {
|
||||
if (!url) die('Usage: node src/run.mjs start <url>');
|
||||
|
||||
// Connect to 1C
|
||||
const state = await browser.connect(url);
|
||||
|
||||
// Start HTTP server for exec/shot/stop
|
||||
const httpServer = http.createServer(handleRequest);
|
||||
httpServer.listen(0, '127.0.0.1', () => {
|
||||
const port = httpServer.address().port;
|
||||
const session = {
|
||||
port,
|
||||
url,
|
||||
pid: process.pid,
|
||||
startedAt: new Date().toISOString()
|
||||
};
|
||||
writeFileSync(SESSION_FILE, JSON.stringify(session, null, 2));
|
||||
out({ ok: true, message: 'Browser ready', port, ...state });
|
||||
});
|
||||
|
||||
process.on('SIGINT', async () => {
|
||||
await browser.disconnect();
|
||||
cleanup();
|
||||
process.exit(0);
|
||||
});
|
||||
}
|
||||
|
||||
async function handleRequest(req, res) {
|
||||
try {
|
||||
if (req.method === 'POST' && req.url === '/exec') {
|
||||
const code = await readBody(req);
|
||||
const result = await executeScript(code);
|
||||
json(res, result);
|
||||
|
||||
} else if (req.method === 'GET' && req.url === '/shot') {
|
||||
const png = await browser.screenshot();
|
||||
res.writeHead(200, { 'Content-Type': 'image/png' });
|
||||
res.end(png);
|
||||
|
||||
} else if (req.method === 'POST' && req.url === '/stop') {
|
||||
json(res, { ok: true, message: 'Stopping' });
|
||||
await browser.disconnect();
|
||||
cleanup();
|
||||
process.exit(0);
|
||||
|
||||
} else if (req.method === 'GET' && req.url === '/status') {
|
||||
json(res, { ok: true, connected: browser.isConnected() });
|
||||
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end('Not found');
|
||||
}
|
||||
} catch (e) {
|
||||
json(res, { ok: false, error: e.message }, 500);
|
||||
}
|
||||
}
|
||||
|
||||
async function executeScript(code) {
|
||||
const output = [];
|
||||
const origLog = console.log;
|
||||
const origErr = console.error;
|
||||
console.log = (...a) => output.push(a.map(String).join(' '));
|
||||
console.error = (...a) => output.push('[ERR] ' + a.map(String).join(' '));
|
||||
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
// Build sandbox: all browser.mjs exports + useful Node globals
|
||||
const exports = {};
|
||||
for (const [k, v] of Object.entries(browser)) {
|
||||
if (k !== 'default') exports[k] = v;
|
||||
}
|
||||
exports.writeFileSync = writeFileSync;
|
||||
exports.readFileSync = readFileSync;
|
||||
|
||||
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
|
||||
const fn = new AsyncFunction(...Object.keys(exports), code);
|
||||
await fn(...Object.values(exports));
|
||||
|
||||
console.log = origLog;
|
||||
console.error = origErr;
|
||||
return { ok: true, output: output.join('\n'), elapsed: elapsed(t0) };
|
||||
} catch (e) {
|
||||
console.log = origLog;
|
||||
console.error = origErr;
|
||||
|
||||
// Error screenshot — save with absolute path so model can view it
|
||||
let shotFile;
|
||||
try {
|
||||
const png = await browser.screenshot();
|
||||
shotFile = resolve(__dirname, '..', 'error-shot.png');
|
||||
writeFileSync(shotFile, png);
|
||||
} catch {}
|
||||
|
||||
return { ok: false, error: e.message, output: output.join('\n'), screenshot: shotFile, elapsed: elapsed(t0) };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// ============================================================
|
||||
// exec: send script to running server
|
||||
// ============================================================
|
||||
|
||||
async function cmdExec(fileOrDash) {
|
||||
if (!fileOrDash) die('Usage: node src/run.mjs exec <file|->');
|
||||
|
||||
const code = fileOrDash === '-'
|
||||
? await readStdin()
|
||||
: readFileSync(resolve(fileOrDash), 'utf-8');
|
||||
|
||||
const sess = loadSession();
|
||||
const resp = await fetch(`http://127.0.0.1:${sess.port}/exec`, {
|
||||
method: 'POST',
|
||||
body: code
|
||||
});
|
||||
const result = await resp.json();
|
||||
out(result);
|
||||
if (!result.ok) process.exit(1);
|
||||
}
|
||||
|
||||
|
||||
// ============================================================
|
||||
// shot: take screenshot via server
|
||||
// ============================================================
|
||||
|
||||
async function cmdShot(file) {
|
||||
const sess = loadSession();
|
||||
const resp = await fetch(`http://127.0.0.1:${sess.port}/shot`);
|
||||
if (!resp.ok) {
|
||||
const err = await resp.text();
|
||||
die(`Screenshot failed: ${err}`);
|
||||
}
|
||||
const buf = Buffer.from(await resp.arrayBuffer());
|
||||
const outFile = file || 'shot.png';
|
||||
writeFileSync(outFile, buf);
|
||||
out({ ok: true, file: outFile });
|
||||
}
|
||||
|
||||
|
||||
// ============================================================
|
||||
// stop: send stop to server
|
||||
// ============================================================
|
||||
|
||||
async function cmdStop() {
|
||||
const sess = loadSession();
|
||||
try {
|
||||
const resp = await fetch(`http://127.0.0.1:${sess.port}/stop`, { method: 'POST' });
|
||||
const result = await resp.json();
|
||||
out(result);
|
||||
} catch {
|
||||
// Server may have already exited before responding
|
||||
out({ ok: true, message: 'Stopped' });
|
||||
}
|
||||
cleanup();
|
||||
}
|
||||
|
||||
|
||||
// ============================================================
|
||||
// status: check session
|
||||
// ============================================================
|
||||
|
||||
function cmdStatus() {
|
||||
if (!existsSync(SESSION_FILE)) {
|
||||
out({ ok: false, message: 'No active session' });
|
||||
process.exit(1);
|
||||
}
|
||||
const sess = JSON.parse(readFileSync(SESSION_FILE, 'utf-8'));
|
||||
out({ ok: true, ...sess });
|
||||
}
|
||||
|
||||
|
||||
// ============================================================
|
||||
// helpers
|
||||
// ============================================================
|
||||
|
||||
function loadSession() {
|
||||
if (!existsSync(SESSION_FILE)) {
|
||||
die('No active session. Run: node src/run.mjs start <url>');
|
||||
}
|
||||
return JSON.parse(readFileSync(SESSION_FILE, 'utf-8'));
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
try { unlinkSync(SESSION_FILE); } catch {}
|
||||
}
|
||||
|
||||
async function readBody(req) {
|
||||
const chunks = [];
|
||||
for await (const chunk of req) chunks.push(chunk);
|
||||
return Buffer.concat(chunks).toString('utf-8');
|
||||
}
|
||||
|
||||
async function readStdin() {
|
||||
const chunks = [];
|
||||
for await (const chunk of process.stdin) chunks.push(chunk);
|
||||
return Buffer.concat(chunks).toString('utf-8');
|
||||
}
|
||||
|
||||
function elapsed(t0) {
|
||||
return Math.round((Date.now() - t0) / 100) / 10;
|
||||
}
|
||||
|
||||
function json(res, obj, status = 200) {
|
||||
res.writeHead(status, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify(obj, null, 2));
|
||||
}
|
||||
|
||||
function out(obj) {
|
||||
process.stdout.write(JSON.stringify(obj, null, 2) + '\n');
|
||||
}
|
||||
|
||||
function die(msg) {
|
||||
process.stderr.write(msg + '\n');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function usage() {
|
||||
die(`Usage: node src/run.mjs <command> [args]
|
||||
|
||||
Commands:
|
||||
start <url> Launch browser and connect to 1C web client
|
||||
exec <file|-> Execute script (file path or - for stdin)
|
||||
shot [file] Take screenshot (default: shot.png)
|
||||
stop Logout and close browser
|
||||
status Check session status`);
|
||||
}
|
||||
Reference in New Issue
Block a user