glidercli 0.3.20 → 0.4.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.
Files changed (2) hide show
  1. package/bin/glider.js +1479 -6
  2. package/package.json +1 -1
package/bin/glider.js CHANGED
@@ -1488,6 +1488,198 @@ async function cmdCorsFetch(url, opts = []) {
1488
1488
  }
1489
1489
  }
1490
1490
 
1491
+
1492
+ // Detect if the attached tab is under Chrome hidden-tab throttling.
1493
+ // Primitive: runtime_evaluate_sync_reads.
1494
+ // Recipe: eval document.visibilityState + '|' + document.hidden.
1495
+ // Semantics: 'hidden|true' → macrotasks (setTimeout/fetch/XHR/workers) will not fire.
1496
+ // Exit code: 0 if visible, 1 if hidden (chainable in scripts).
1497
+ async function cmdFrozen(opts = []) {
1498
+ let sessionId = null;
1499
+ for (let i = 0; i < opts.length; i++) {
1500
+ const a = opts[i];
1501
+ if (a === '--session' || a === '--sessionId') sessionId = opts[++i];
1502
+ else if (a === '--help') {
1503
+ console.log('Usage: glider frozen [--session <id>]');
1504
+ console.log(' Detect whether the attached tab is macrotask-frozen (hidden).');
1505
+ console.log(' Exit code: 0 = visible, 1 = hidden (frozen).');
1506
+ return;
1507
+ }
1508
+ }
1509
+ if (!await ensureConnected()) process.exit(1);
1510
+
1511
+ const js = `document.visibilityState + '|' + document.hidden + '|' + (document.wasDiscarded||false)`;
1512
+ try {
1513
+ const cdpParams = { method: 'Runtime.evaluate', params: { expression: js, returnByValue: true } };
1514
+ if (sessionId) cdpParams.sessionId = sessionId;
1515
+ const result = await httpPost('/cdp', cdpParams);
1516
+ if (result && result.error && !result.result) {
1517
+ const msg = `CDP error: ${typeof result.error === 'string' ? result.error : JSON.stringify(result.error)}`;
1518
+ if (jsonOutput) emitJson(false, null, msg);
1519
+ log.fail(msg);
1520
+ process.exit(2);
1521
+ }
1522
+ const value = result?.result?.value;
1523
+ if (!value) {
1524
+ if (jsonOutput) emitJson(false, null, 'no value');
1525
+ log.fail('No value returned');
1526
+ process.exit(2);
1527
+ }
1528
+ const [visibilityState, hidden, wasDiscarded] = String(value).split('|');
1529
+ const frozen = hidden === 'true';
1530
+ const out = { visibilityState, hidden: frozen, wasDiscarded: wasDiscarded === 'true', frozen };
1531
+ if (jsonOutput) {
1532
+ emitJson(true, out);
1533
+ } else {
1534
+ if (frozen) {
1535
+ log.warn(`FROZEN - visibilityState=${visibilityState} hidden=${hidden} wasDiscarded=${wasDiscarded}`);
1536
+ log.info('Macrotasks (setTimeout/fetch/XHR/workers) will not fire until user focuses tab.');
1537
+ } else {
1538
+ log.ok(`live - visibilityState=${visibilityState} hidden=${hidden} wasDiscarded=${wasDiscarded}`);
1539
+ }
1540
+ }
1541
+ process.exit(frozen ? 1 : 0);
1542
+ } catch (e) {
1543
+ if (jsonOutput) emitJson(false, null, e.message);
1544
+ log.fail(`frozen check failed: ${e.message}`);
1545
+ process.exit(2);
1546
+ }
1547
+ }
1548
+
1549
+ // List cookies for a URL (including HttpOnly) via extension chrome.cookies.getAll bridge.
1550
+ // Primitive: extension_ws_bridge (background.js exposes method:'getCookies').
1551
+ // Note: this reads via the CRX cookies API - HttpOnly cookies (ESTSAUTH, s.SessID etc.)
1552
+ // ARE returned because MV3 extensions with "cookies" permission bypass the JS wall.
1553
+ async function cmdCookies(opts = []) {
1554
+ let url = null;
1555
+ let host = null; // convenience: bare host → https://<host>/
1556
+ let name = null; // optional exact-name filter
1557
+ let showValue = false; // print full cookie value (default: mask)
1558
+ let asHeader = false; // emit as ready-to-paste "Cookie: k=v; k=v" line
1559
+
1560
+ const positional = [];
1561
+ for (let i = 0; i < opts.length; i++) {
1562
+ const a = opts[i];
1563
+ if (a === '--url' || a === '-u') url = opts[++i];
1564
+ else if (a === '--host' || a === '-h') host = opts[++i];
1565
+ else if (a === '--name' || a === '-n') name = opts[++i];
1566
+ else if (a === '--value' || a === '--secret' || a === '--full') showValue = true;
1567
+ else if (a === '--header' || a === '--as-header') asHeader = true;
1568
+ else if (a === '--help') {
1569
+ console.log('Usage: glider cookies <url> | --host <h> | --url <u> [--name <n>] [--value] [--header] [--json]');
1570
+ console.log(' Read cookies (INCLUDING HttpOnly) for a URL via the extension cookies API.');
1571
+ console.log(' --host <h> convenience: expands to https://<h>/');
1572
+ console.log(' --name <n> filter to a single cookie by exact name');
1573
+ console.log(' --value print full cookie value (default: masked)');
1574
+ console.log(' --header emit as "Cookie: k=v; k=v" header line');
1575
+ return;
1576
+ }
1577
+ else if (!a.startsWith('-')) positional.push(a);
1578
+ }
1579
+ if (!url && positional.length) url = positional[0];
1580
+ if (!url && host) url = /^https?:\/\//i.test(host) ? host : `https://${host}/`;
1581
+ if (!url) {
1582
+ log.fail('Usage: glider cookies <url> | --host <h> | --url <u>');
1583
+ process.exit(1);
1584
+ }
1585
+
1586
+ if (!await ensureConnected()) process.exit(1);
1587
+
1588
+ try {
1589
+ const payload = await httpPost('/extension', {
1590
+ method: 'getCookies',
1591
+ params: { url }
1592
+ });
1593
+
1594
+ if (!payload || payload.error) {
1595
+ const msg = payload?.error || 'no response from extension';
1596
+ if (jsonOutput) emitJson(false, null, msg);
1597
+ log.fail(`cookies fetch failed: ${msg}`);
1598
+ log.info('Requires glider CRX >= 0.3.21 (bg handler "getCookies"). Reload the extension if just updated.');
1599
+ process.exit(1);
1600
+ }
1601
+
1602
+ let cookies = payload.data || payload.result?.cookies || payload.cookies || [];
1603
+ if (!Array.isArray(cookies)) {
1604
+ if (jsonOutput) emitJson(false, null, 'unexpected response shape');
1605
+ log.fail('unexpected response shape from extension');
1606
+ console.error(JSON.stringify(payload).slice(0, 500));
1607
+ process.exit(1);
1608
+ }
1609
+ if (name) cookies = cookies.filter(c => c.name === name);
1610
+
1611
+ // Filter expired
1612
+ const nowSec = Math.floor(Date.now() / 1000);
1613
+ for (const c of cookies) {
1614
+ if (c.expirationDate) {
1615
+ c._expires_in_sec = Math.floor(c.expirationDate - nowSec);
1616
+ c._expired = c._expires_in_sec < 0;
1617
+ } else {
1618
+ c._expires_in_sec = null;
1619
+ c._expired = false; // session cookie
1620
+ }
1621
+ }
1622
+
1623
+ if (asHeader) {
1624
+ const line = cookies
1625
+ .filter(c => !c._expired)
1626
+ .map(c => `${c.name}=${c.value}`)
1627
+ .join('; ');
1628
+ if (jsonOutput) emitJson(true, { header: line, count: cookies.length });
1629
+ else console.log(line);
1630
+ return;
1631
+ }
1632
+
1633
+ if (jsonOutput) {
1634
+ const out = cookies.map(c => ({
1635
+ name: c.name,
1636
+ domain: c.domain,
1637
+ path: c.path,
1638
+ httpOnly: !!c.httpOnly,
1639
+ secure: !!c.secure,
1640
+ sameSite: c.sameSite,
1641
+ session: !!c.session,
1642
+ expirationDate: c.expirationDate || null,
1643
+ expires_in_sec: c._expires_in_sec,
1644
+ expired: c._expired,
1645
+ value: showValue ? c.value : maskCookieValue(c.value),
1646
+ }));
1647
+ emitJson(true, { url, count: out.length, cookies: out });
1648
+ return;
1649
+ }
1650
+
1651
+ if (cookies.length === 0) {
1652
+ log.warn(name ? `No cookie named "${name}" for ${url}` : `No cookies for ${url}`);
1653
+ return;
1654
+ }
1655
+ log.ok(`${cookies.length} cookie(s) for ${url}:`);
1656
+ for (const c of cookies) {
1657
+ const flags = [
1658
+ c.httpOnly ? 'HttpOnly' : null,
1659
+ c.secure ? 'Secure' : null,
1660
+ c.sameSite ? `SameSite=${c.sameSite}` : null,
1661
+ c.session ? 'Session' : null,
1662
+ ].filter(Boolean).join(' ');
1663
+ const exp = c._expires_in_sec == null
1664
+ ? '(session)'
1665
+ : (c._expired ? `EXPIRED ${-c._expires_in_sec}s ago` : `expires in ${Math.floor(c._expires_in_sec/60)}m ${c._expires_in_sec%60}s`);
1666
+ const val = showValue ? c.value : maskCookieValue(c.value);
1667
+ console.log(` ${c.name}=${val} [${c.domain}${c.path}] ${flags} ${exp}`);
1668
+ }
1669
+ } catch (e) {
1670
+ if (jsonOutput) emitJson(false, null, e.message);
1671
+ log.fail(`cookies fetch failed: ${e.message}`);
1672
+ process.exit(1);
1673
+ }
1674
+ }
1675
+
1676
+ function maskCookieValue(v) {
1677
+ if (v == null) return '(none)';
1678
+ const s = String(v);
1679
+ if (s.length < 20) return s.slice(0, 4) + '...' + s.slice(-2);
1680
+ return s.slice(0, 12) + '...(' + (s.length - 20) + ' chars)...' + s.slice(-6);
1681
+ }
1682
+
1491
1683
  // Spawn multiple tabs
1492
1684
  async function cmdSpawn(urls) {
1493
1685
  if (!urls || urls.length === 0) {
@@ -2196,6 +2388,61 @@ ${YELLOW}DOMAIN EXTENSIONS:${NC}
2196
2388
  }
2197
2389
  console.log('');
2198
2390
  }
2391
+
2392
+ // Plugins socket - hydrated from ~/.glider/plugins/*.plugin.{json,js}
2393
+ // (loadPlugins is called from main() before showHelp when invoked as `glider help`,
2394
+ // but a bare `glider --help` runs before main; safe-load here for that path.)
2395
+ if (GLIDER_PLUGIN_REGISTRY.size === 0) {
2396
+ try { loadPlugins(); } catch {}
2397
+ }
2398
+ const seen = new Set();
2399
+ const pluginVerbs = [];
2400
+ for (const [verb, def] of GLIDER_PLUGIN_REGISTRY) {
2401
+ if (def.verb !== verb) continue; // skip aliases
2402
+ if (seen.has(def._source)) continue;
2403
+ seen.add(def._source);
2404
+ pluginVerbs.push({ verb, def });
2405
+ }
2406
+ if (pluginVerbs.length > 0) {
2407
+ console.log(`${YELLOW}PLUGINS:${NC} (from ~/.glider/plugins/)`);
2408
+ for (const { verb, def } of pluginVerbs) {
2409
+ const desc = (Array.isArray(def.help) ? def.help.find(l => !/^Usage:/i.test(l)) : def.help) || '(no description)';
2410
+ const shortDesc = String(desc).replace(/^\s+/, '').slice(0, 60);
2411
+ console.log(` ${GREEN}${verb.padEnd(16)}${NC} ${DIM}${shortDesc}${NC}`);
2412
+ }
2413
+ console.log('');
2414
+ }
2415
+ console.log(`${YELLOW}DOM-SCORCH (waves 1-5):${NC}`);
2416
+ console.log(` ${GREEN}${'read'.padEnd(16)}${NC} ${DIM}read attr/prop/text/html/value; --all --count --exists --visible --enabled${NC}`);
2417
+ console.log(` ${GREEN}${'click'.padEnd(16)}${NC} ${DIM}--text --contains --regex --nth --role --inside --wait --double --right --hold${NC}`);
2418
+ console.log(` ${GREEN}${'type'.padEnd(16)}${NC} ${DIM}--editor auto|ckeditor|tinymce|prosemirror|monaco|slate|contentEditable ; --file --clear-first --commit${NC}`);
2419
+ console.log(` ${GREEN}${'wait'.padEnd(16)}${NC} ${DIM}--selector --text --gone --matches --stable --url-matches --timeout${NC}`);
2420
+ console.log(` ${GREEN}${'hover'.padEnd(16)}${NC} ${DIM}hover a target${NC}`);
2421
+ console.log(` ${GREEN}${'focus/blur'.padEnd(16)}${NC} ${DIM}focus/blur an element${NC}`);
2422
+ console.log(` ${GREEN}${'scroll'.padEnd(16)}${NC} ${DIM}scroll to <sel> | by <dx> <dy> | until <sel>${NC}`);
2423
+ console.log(` ${GREEN}${'key'.padEnd(16)}${NC} ${DIM}"Ctrl+Enter" | "ArrowDown x5" | "Escape" | --text "literal"${NC}`);
2424
+ console.log(` ${GREEN}${'right-click'.padEnd(16)}${NC} ${DIM}right-click (same flags as click)${NC}`);
2425
+ console.log(` ${GREEN}${'double-click'.padEnd(16)}${NC} ${DIM}double-click (same flags as click)${NC}`);
2426
+ console.log(` ${GREEN}${'drag'.padEnd(16)}${NC} ${DIM}drag <src> --to <dst>${NC}`);
2427
+ console.log(` ${GREEN}${'click-at'.padEnd(16)}${NC} ${DIM}click-at x,y${NC}`);
2428
+ console.log(` ${GREEN}${'select'.padEnd(16)}${NC} ${DIM}<sel> --by-text | --by-value | --nth${NC}`);
2429
+ console.log(` ${GREEN}${'eval'.padEnd(16)}${NC} ${DIM}--arg K=V --arg-file K=@path --json --await${NC}`);
2430
+ console.log(` ${GREEN}${'screenshot'.padEnd(16)}${NC} ${DIM}--selector --clip --full-page --format webp|jpg|png${NC}`);
2431
+ console.log(` ${GREEN}${'frames'.padEnd(16)}${NC} ${DIM}list all frames in the page${NC}`);
2432
+ console.log(` ${GREEN}${'frame-eval'.padEnd(16)}${NC} ${DIM}<frameId> <js> - eval inside iframe${NC}`);
2433
+ console.log(` ${GREEN}${'upload'.padEnd(16)}${NC} ${DIM}<input-sel> <file-path> via DOM.setFileInputFiles${NC}`);
2434
+ console.log(` ${GREEN}${'har'.padEnd(16)}${NC} ${DIM}har start | stop | dump [PATH]${NC}`);
2435
+ console.log(` ${GREEN}${'emulate'.padEnd(16)}${NC} ${DIM}tz | geo | viewport | offline | ua | color-scheme${NC}`);
2436
+ console.log(` ${GREEN}${'storage'.padEnd(16)}${NC} ${DIM}get | set | delete | keys | jar (localStorage)${NC}`);
2437
+ console.log(` ${GREEN}${'cookies'.padEnd(16)}${NC} ${DIM}(read: no flags) | --set NAME=VAL --host H | --delete NAME --host H${NC}`);
2438
+ console.log(` ${GREEN}${'history'.padEnd(16)}${NC} ${DIM}back | forward | reload${NC}`);
2439
+ console.log(` ${GREEN}${'dialog'.padEnd(16)}${NC} ${DIM}dialog auto accept|dismiss${NC}`);
2440
+ console.log(` ${GREEN}${'console'.padEnd(16)}${NC} ${DIM}console tail | dump${NC}`);
2441
+ console.log(` ${GREEN}${'pdf'.padEnd(16)}${NC} ${DIM}[PATH] [--landscape] [--margin N] [--scale F]${NC}`);
2442
+ console.log(` ${GREEN}${'mock'.padEnd(16)}${NC} ${DIM}<url-glob> --status N --body FILE | mock clear${NC}`);
2443
+ console.log(` ${GREEN}${'a11y'.padEnd(16)}${NC} ${DIM}Accessibility.getFullAXTree (snapshot --a11y flag equivalent)${NC}`);
2444
+ console.log(` ${GREEN}${'frozen'.padEnd(16)}${NC} ${DIM}freeze/restore page state${NC}`);
2445
+ console.log('');
2199
2446
  }
2200
2447
 
2201
2448
  // Version check - non-blocking, runs in background
@@ -2253,10 +2500,1138 @@ async function cmdUpdate() {
2253
2500
  }
2254
2501
  }
2255
2502
 
2503
+ // ────────────────────────────────────────────────────────────────
2504
+ // PLUGIN SOCKET (v0.3.21)
2505
+ // ────────────────────────────────────────────────────────────────
2506
+ // glidercli itself is verb-agnostic. Local plugins hydrate additional
2507
+ // verbs at runtime from `$HOME/.glider/plugins/*.plugin.{json,js}`.
2508
+ // This lets consumers (org-specific ontologies, private tentacles) ship
2509
+ // their own verbs without ever landing in the public npm package.
2510
+ //
2511
+ // Plugin discovery order:
2512
+ // 1. $GLIDER_PLUGIN_DIR (env override)
2513
+ // 2. $HOME/.glider/plugins/
2514
+ //
2515
+ // Two plugin formats:
2516
+ //
2517
+ // (a) JSON - declarative, for simple eval-based verbs:
2518
+ // {
2519
+ // "verb": "myverb",
2520
+ // "aliases": ["mv"],
2521
+ // "help": ["Usage: glider myverb [--flag]", " Describe it..."],
2522
+ // "primitive": "eval" | "extension" | "cdp",
2523
+ // "recipe": "<javascript expression>" (for primitive=eval)
2524
+ // "method": "<extension method name>" (for primitive=extension)
2525
+ // "args": { "--flag": {"type":"boolean|string|number"} }, optional
2526
+ // "output": { "format":"table|json|raw" } optional
2527
+ // }
2528
+ //
2529
+ // (b) JS - imperative, for complex verbs:
2530
+ // module.exports = {
2531
+ // verb: 'myverb',
2532
+ // aliases: ['mv'],
2533
+ // help: ['Usage: glider myverb ...'],
2534
+ // async run(argv, ctx) {
2535
+ // // ctx = { cdp, ext, log, jsonOutput, emitJson, ensureConnected, mask, httpPost, httpGet, os, fs, path }
2536
+ // const val = await ctx.cdp.eval('1+1', { sessionId: ctx.persistedSessionId });
2537
+ // ctx.log.ok(JSON.stringify(val));
2538
+ // }
2539
+ // };
2540
+ const GLIDER_PLUGIN_REGISTRY = new Map(); // verb → plugin def
2541
+
2542
+ function pluginDirs() {
2543
+ const dirs = [];
2544
+ if (process.env.GLIDER_PLUGIN_DIR) dirs.push(process.env.GLIDER_PLUGIN_DIR);
2545
+ dirs.push(path.join(os.homedir(), '.glider', 'plugins'));
2546
+ return dirs.filter(d => { try { return fs.statSync(d).isDirectory(); } catch { return false; } });
2547
+ }
2548
+
2549
+ function loadPlugins() {
2550
+ const dirs = pluginDirs();
2551
+ for (const dir of dirs) {
2552
+ let entries;
2553
+ try { entries = fs.readdirSync(dir); } catch { continue; }
2554
+ for (const name of entries) {
2555
+ if (!/\.plugin\.(json|js|cjs)$/i.test(name)) continue;
2556
+ const full = path.join(dir, name);
2557
+ try {
2558
+ let def;
2559
+ if (/\.json$/i.test(name)) {
2560
+ def = JSON.parse(fs.readFileSync(full, 'utf8'));
2561
+ def._source = full;
2562
+ def._type = 'json';
2563
+ } else {
2564
+ def = require(full);
2565
+ def._source = full;
2566
+ def._type = 'js';
2567
+ }
2568
+ if (!def.verb || typeof def.verb !== 'string') {
2569
+ log.warn(`Plugin ${name}: missing "verb", skipping`);
2570
+ continue;
2571
+ }
2572
+ GLIDER_PLUGIN_REGISTRY.set(def.verb, def);
2573
+ for (const a of (def.aliases || [])) GLIDER_PLUGIN_REGISTRY.set(a, def);
2574
+ } catch (e) {
2575
+ log.warn(`Plugin ${name}: load failed - ${e.message}`);
2576
+ }
2577
+ }
2578
+ }
2579
+ }
2580
+
2581
+ // Build the helper context passed to JS plugins
2582
+ function makePluginCtx() {
2583
+ return {
2584
+ // Primitives
2585
+ cdp: {
2586
+ async eval(js, opts = {}) {
2587
+ const params = { method: 'Runtime.evaluate', params: { expression: js, returnByValue: true, awaitPromise: !!opts.awaitPromise } };
2588
+ if (opts.sessionId) params.sessionId = opts.sessionId;
2589
+ const r = await httpPost('/cdp', params);
2590
+ if (r && r.error && !r.result) throw new Error(`CDP: ${typeof r.error === 'string' ? r.error : JSON.stringify(r.error)}`);
2591
+ return r?.result?.value;
2592
+ },
2593
+ async call(method, params, opts = {}) {
2594
+ const body = { method, params: params || {} };
2595
+ if (opts.sessionId) body.sessionId = opts.sessionId;
2596
+ return await httpPost('/cdp', body);
2597
+ },
2598
+ },
2599
+ ext: {
2600
+ async call(method, params) {
2601
+ return await httpPost('/extension', { method, params: params || {} });
2602
+ },
2603
+ },
2604
+ // Utilities
2605
+ log,
2606
+ get jsonOutput() { return jsonOutput; },
2607
+ emitJson,
2608
+ ensureConnected,
2609
+ httpPost, httpGet,
2610
+ // Common masks
2611
+ mask: {
2612
+ jwt(s) {
2613
+ if (!s || typeof s !== 'string') return String(s);
2614
+ if (s.length < 40) return s.slice(0,6) + '...' + s.slice(-4);
2615
+ return s.slice(0,20) + '...(' + (s.length - 30) + ' chars)...' + s.slice(-10);
2616
+ },
2617
+ cookie(s) {
2618
+ if (s == null) return '(none)';
2619
+ const t = String(s);
2620
+ if (t.length < 20) return t.slice(0,4) + '...' + t.slice(-2);
2621
+ return t.slice(0,12) + '...(' + (t.length - 20) + ' chars)...' + t.slice(-6);
2622
+ },
2623
+ },
2624
+ // Node built-ins (avoid plugins needing to require these themselves)
2625
+ os, fs, path,
2626
+ // Version marker for plugins to feature-detect
2627
+ apiVersion: 1,
2628
+ };
2629
+ }
2630
+
2631
+ async function runPlugin(def, argv) {
2632
+ const ctx = makePluginCtx();
2633
+
2634
+ // Help dispatch
2635
+ if (argv.includes('--help') || argv.includes('-h')) {
2636
+ if (Array.isArray(def.help)) def.help.forEach(l => console.log(l));
2637
+ else if (typeof def.help === 'string') console.log(def.help);
2638
+ else console.log(`Usage: glider ${def.verb} [args]`);
2639
+ return;
2640
+ }
2641
+
2642
+ // JS plugin - call run()
2643
+ if (def._type === 'js') {
2644
+ if (typeof def.run !== 'function') {
2645
+ log.fail(`Plugin ${def.verb}: JS plugin must export "run(argv, ctx)"`);
2646
+ process.exit(1);
2647
+ }
2648
+ if (!await ensureConnected()) process.exit(1);
2649
+ try {
2650
+ await def.run(argv, ctx);
2651
+ } catch (e) {
2652
+ if (jsonOutput) emitJson(false, null, e.message);
2653
+ log.fail(`Plugin ${def.verb} failed: ${e.message}`);
2654
+ if (process.env.GLIDER_PLUGIN_DEBUG) console.error(e.stack);
2655
+ process.exit(1);
2656
+ }
2657
+ return;
2658
+ }
2659
+
2660
+ // JSON plugin - declarative execution
2661
+ if (!await ensureConnected()) process.exit(1);
2662
+ const parsed = parseJsonPluginArgs(argv, def.args || {});
2663
+ try {
2664
+ let out;
2665
+ if (def.primitive === 'eval') {
2666
+ if (!def.recipe) throw new Error('JSON plugin with primitive=eval requires "recipe"');
2667
+ const sessionId = parsed['--session'] || parsed.sessionId;
2668
+ const val = await ctx.cdp.eval(def.recipe, { sessionId, awaitPromise: !!def.awaitPromise });
2669
+ out = val;
2670
+ } else if (def.primitive === 'extension') {
2671
+ if (!def.method) throw new Error('JSON plugin with primitive=extension requires "method"');
2672
+ const params = { ...parsed };
2673
+ delete params._;
2674
+ out = await ctx.ext.call(def.method, params);
2675
+ } else {
2676
+ throw new Error(`Unknown primitive "${def.primitive}" (expected: eval | extension)`);
2677
+ }
2678
+ if (jsonOutput || def.output?.format === 'json') {
2679
+ emitJson(true, out);
2680
+ } else {
2681
+ console.log(typeof out === 'string' ? out : JSON.stringify(out, null, 2));
2682
+ }
2683
+ } catch (e) {
2684
+ if (jsonOutput) emitJson(false, null, e.message);
2685
+ log.fail(`Plugin ${def.verb} failed: ${e.message}`);
2686
+ process.exit(1);
2687
+ }
2688
+ }
2689
+
2690
+ function parseJsonPluginArgs(argv, schema) {
2691
+ const out = { _: [] };
2692
+ for (let i = 0; i < argv.length; i++) {
2693
+ const a = argv[i];
2694
+ if (a.startsWith('--')) {
2695
+ const spec = schema[a] || { type: 'string' };
2696
+ if (spec.type === 'boolean') out[a] = true;
2697
+ else out[a] = argv[++i];
2698
+ } else out._.push(a);
2699
+ }
2700
+ return out;
2701
+ }
2702
+
2703
+ // ═══════════════════════════════════════════════════════════════════
2704
+ // WAVES 1-5 (dom-scorch) - AGNOSTIC DOM PRIMITIVES
2705
+ // ═══════════════════════════════════════════════════════════════════
2706
+
2707
+ // --- flag parser used by dom-scorch verbs ---------------------------
2708
+ function parseFlags(argv, specs) {
2709
+ // specs: { longName: {short?, type: 'boolean'|'string'|'int'|'float', default?} }
2710
+ const out = { _: [] };
2711
+ for (const k of Object.keys(specs)) if ('default' in specs[k]) out[k] = specs[k].default;
2712
+ const shortMap = {};
2713
+ for (const [k, s] of Object.entries(specs)) if (s.short) shortMap['-' + s.short] = k;
2714
+ for (let i = 0; i < argv.length; i++) {
2715
+ const a = argv[i];
2716
+ let key = null;
2717
+ if (a.startsWith('--')) key = a.slice(2);
2718
+ else if (shortMap[a]) key = shortMap[a];
2719
+ if (key && specs[key]) {
2720
+ const s = specs[key];
2721
+ if (s.type === 'boolean') out[key] = true;
2722
+ else {
2723
+ const v = argv[++i];
2724
+ out[key] = s.type === 'int' ? parseInt(v, 10)
2725
+ : s.type === 'float' ? parseFloat(v)
2726
+ : v;
2727
+ }
2728
+ } else {
2729
+ out._.push(a);
2730
+ }
2731
+ }
2732
+ return out;
2733
+ }
2734
+
2735
+ // --- guard: allow-list check + auto-connect --------------------------
2736
+ async function _guardAndConnect(action) {
2737
+ if (!await ensureConnected()) process.exit(1);
2738
+ try { await assertCurrentUrlAllowed(action); }
2739
+ catch (e) { if (jsonOutput) emitJson(false, null, e.message); log.fail(e.message); process.exit(1); }
2740
+ }
2741
+
2742
+ // --- shared runtime helper: eval JS, unwrap value -------------------
2743
+ async function _rtEval(expression, opts = {}) {
2744
+ const result = await httpPost('/cdp', {
2745
+ method: 'Runtime.evaluate',
2746
+ params: {
2747
+ expression,
2748
+ returnByValue: true,
2749
+ awaitPromise: opts.awaitPromise !== false,
2750
+ ...(opts.contextId !== undefined ? { contextId: opts.contextId } : {}),
2751
+ ...(opts.uniqueContextId ? { uniqueContextId: opts.uniqueContextId } : {}),
2752
+ }
2753
+ });
2754
+ if (result?.exceptionDetails) {
2755
+ throw new Error(result.exceptionDetails.text || result.exceptionDetails.exception?.description || 'eval threw');
2756
+ }
2757
+ return result;
2758
+ }
2759
+
2760
+ // --- WAVE 1: cmdRead ------------------------------------------------
2761
+ // glider read <sel> [--attr X | --prop Y | --text | --html | --value | --all | --count | --exists | --visible | --enabled]
2762
+ async function cmdRead(argv) {
2763
+ const opts = parseFlags(argv, {
2764
+ attr: { type: 'string' },
2765
+ prop: { type: 'string' },
2766
+ text: { type: 'boolean' },
2767
+ html: { type: 'boolean' },
2768
+ value: { type: 'boolean' },
2769
+ all: { type: 'boolean' },
2770
+ count: { type: 'boolean' },
2771
+ exists: { type: 'boolean' },
2772
+ visible: { type: 'boolean' },
2773
+ enabled: { type: 'boolean' },
2774
+ });
2775
+ const sel = opts._[0];
2776
+ if (!sel) { log.fail('Usage: glider read <selector> [--attr X | --prop Y | --text | --html | --value | --all | --count | --exists | --visible | --enabled]'); process.exit(1); }
2777
+ await _guardAndConnect('read');
2778
+ const selJ = JSON.stringify(sel);
2779
+ const attrJ = opts.attr ? JSON.stringify(opts.attr) : 'null';
2780
+ const propJ = opts.prop ? JSON.stringify(opts.prop) : 'null';
2781
+ const mode = opts.count ? 'count'
2782
+ : opts.exists ? 'exists'
2783
+ : opts.visible ? 'visible'
2784
+ : opts.enabled ? 'enabled'
2785
+ : opts.attr ? 'attr'
2786
+ : opts.prop ? 'prop'
2787
+ : opts.value ? 'value'
2788
+ : opts.html ? 'html'
2789
+ : opts.text ? 'text'
2790
+ : 'text';
2791
+ const modeJ = JSON.stringify(mode);
2792
+ const allJ = opts.all ? 'true' : 'false';
2793
+ const js = `(() => {
2794
+ const sel=${selJ}, mode=${modeJ}, attr=${attrJ}, prop=${propJ}, all=${allJ};
2795
+ const els=[...document.querySelectorAll(sel)];
2796
+ if (mode==='count') return els.length;
2797
+ if (mode==='exists') return els.length>0;
2798
+ if (els.length===0) return null;
2799
+ const one=e=>{
2800
+ if (mode==='visible'){const r=e.getBoundingClientRect(); const s=getComputedStyle(e); return r.width>0&&r.height>0&&s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}
2801
+ if (mode==='enabled') return !e.disabled && e.getAttribute('aria-disabled')!=='true';
2802
+ if (mode==='attr') return e.getAttribute(attr);
2803
+ if (mode==='prop') return e[prop];
2804
+ if (mode==='value') return e.value;
2805
+ if (mode==='html') return e.outerHTML;
2806
+ return e.innerText;
2807
+ };
2808
+ return all ? els.map(one) : one(els[0]);
2809
+ })()`;
2810
+ try {
2811
+ const r = await _rtEval(js);
2812
+ const v = r.result?.value;
2813
+ if (jsonOutput) emitJson(true, v);
2814
+ else if (v === null || v === undefined) { /* nothing */ }
2815
+ else if (typeof v === 'string') console.log(v);
2816
+ else console.log(JSON.stringify(v));
2817
+ } catch (e) {
2818
+ if (jsonOutput) emitJson(false, null, e.message);
2819
+ log.fail(`Read failed: ${e.message}`); process.exit(1);
2820
+ }
2821
+ }
2822
+
2823
+ // --- WAVE 1: cmdHover -----------------------------------------------
2824
+ async function cmdHover(argv) {
2825
+ const opts = parseFlags(argv, {
2826
+ text: { type: 'string' },
2827
+ contains: { type: 'string' },
2828
+ nth: { type: 'int' },
2829
+ });
2830
+ const sel = opts._[0];
2831
+ if (!sel && !opts.text && !opts.contains) { log.fail('Usage: glider hover <selector> [--text S | --contains S | --nth N]'); process.exit(1); }
2832
+ await _guardAndConnect('hover');
2833
+ const findExpr = _buildFindElExpr(sel, opts);
2834
+ const js = `(() => {
2835
+ const el = ${findExpr};
2836
+ if (!el) return { error: 'Element not found' };
2837
+ const r = el.getBoundingClientRect();
2838
+ return { x: Math.round(r.left + r.width/2), y: Math.round(r.top + r.height/2) };
2839
+ })()`;
2840
+ try {
2841
+ const r = await _rtEval(js);
2842
+ const v = r.result?.value;
2843
+ if (v?.error) { if (jsonOutput) emitJson(false, null, v.error); log.fail(v.error); process.exit(1); }
2844
+ // dispatch a real mousemove via CDP
2845
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseMoved', x: v.x, y: v.y, button: 'none', clickCount: 0 } });
2846
+ if (jsonOutput) emitJson(true, { hovered: true, at: v });
2847
+ else log.ok(`Hovered at ${v.x},${v.y}`);
2848
+ } catch (e) {
2849
+ if (jsonOutput) emitJson(false, null, e.message);
2850
+ log.fail(`Hover failed: ${e.message}`); process.exit(1);
2851
+ }
2852
+ }
2853
+
2854
+ // --- WAVE 1: cmdFocus / cmdBlur -------------------------------------
2855
+ async function cmdFocusVerb(argv) {
2856
+ const sel = argv[0];
2857
+ if (!sel) { log.fail('Usage: glider focus <selector>'); process.exit(1); }
2858
+ await _guardAndConnect('focus');
2859
+ const js = `(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return { error: 'not found' }; el.focus(); return { focused: true }; })()`;
2860
+ const r = await _rtEval(js);
2861
+ const v = r.result?.value;
2862
+ if (v?.error) { log.fail(v.error); process.exit(1); }
2863
+ if (jsonOutput) emitJson(true, { selector: sel, focused: true });
2864
+ else log.ok(`Focused: ${sel}`);
2865
+ }
2866
+ async function cmdBlurVerb(argv) {
2867
+ const sel = argv[0];
2868
+ await _guardAndConnect('blur');
2869
+ const js = sel
2870
+ ? `(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return { error: 'not found' }; el.blur(); return { blurred: true }; })()`
2871
+ : `(() => { if (document.activeElement && document.activeElement.blur) document.activeElement.blur(); return { blurred: true }; })()`;
2872
+ const r = await _rtEval(js);
2873
+ const v = r.result?.value;
2874
+ if (v?.error) { log.fail(v.error); process.exit(1); }
2875
+ if (jsonOutput) emitJson(true, { blurred: true });
2876
+ else log.ok(`Blurred${sel ? ': ' + sel : ''}`);
2877
+ }
2878
+
2879
+ // --- WAVE 1: cmdScroll -----------------------------------------------
2880
+ // scroll-to <sel> | scroll-by dx dy | scroll-until <sel>
2881
+ async function cmdScroll(argv) {
2882
+ const sub = argv[0];
2883
+ await _guardAndConnect('scroll');
2884
+ if (sub === 'to' && argv[1]) {
2885
+ const sel = argv[1];
2886
+ const js = `(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return { error: 'not found' }; el.scrollIntoView({behavior:'auto',block:'center'}); return { scrolled: true }; })()`;
2887
+ const r = await _rtEval(js);
2888
+ const v = r.result?.value;
2889
+ if (v?.error) { log.fail(v.error); process.exit(1); }
2890
+ if (jsonOutput) emitJson(true, { scrolledTo: sel }); else log.ok(`Scrolled to: ${sel}`);
2891
+ } else if (sub === 'by' && argv[1] && argv[2]) {
2892
+ const dx = parseFloat(argv[1]); const dy = parseFloat(argv[2]);
2893
+ const js = `(() => { window.scrollBy(${dx}, ${dy}); return { x: window.scrollX, y: window.scrollY }; })()`;
2894
+ const r = await _rtEval(js);
2895
+ if (jsonOutput) emitJson(true, r.result?.value); else log.ok(`Scrolled by ${dx},${dy}`);
2896
+ } else if (sub === 'until' && argv[1]) {
2897
+ const sel = argv[1];
2898
+ const timeoutMs = 10000; const start = Date.now();
2899
+ while (Date.now() - start < timeoutMs) {
2900
+ const r = await _rtEval(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return false; const r=el.getBoundingClientRect(); return r.top >= 0 && r.bottom <= window.innerHeight; })()`);
2901
+ if (r.result?.value === true) { if (jsonOutput) emitJson(true, { found: sel }); else log.ok(`Reached: ${sel}`); return; }
2902
+ await _rtEval(`window.scrollBy(0, window.innerHeight * 0.8); void 0;`);
2903
+ await new Promise(r => setTimeout(r, 300));
2904
+ }
2905
+ if (jsonOutput) emitJson(false, null, 'scroll-until timeout');
2906
+ log.fail(`scroll-until timeout: ${sel}`); process.exit(1);
2907
+ } else {
2908
+ log.fail('Usage: glider scroll to <sel> | scroll by <dx> <dy> | scroll until <sel>'); process.exit(1);
2909
+ }
2910
+ }
2911
+
2912
+ // --- WAVE 1: cmdClick (upgraded) -------------------------------------
2913
+ // Backward-compat: glider click <selector>
2914
+ // New: glider click [<sel>] [--text S] [--contains S] [--regex R] [--nth N] [--role R] [--inside S] [--wait MS] [--scroll-into-view] [--double] [--right] [--hold MS] [--modifier ctrl|shift|alt|meta]
2915
+ function _buildFindElExpr(sel, opts) {
2916
+ // returns a JS expression evaluating to element or null; expects `document`
2917
+ const selJ = sel ? JSON.stringify(sel) : 'null';
2918
+ const textJ = opts.text ? JSON.stringify(opts.text) : 'null';
2919
+ const contJ = opts.contains ? JSON.stringify(opts.contains) : 'null';
2920
+ const rxJ = opts.regex ? JSON.stringify(opts.regex) : 'null';
2921
+ const roleJ = opts.role ? JSON.stringify(opts.role) : 'null';
2922
+ const insJ = opts.inside ? JSON.stringify(opts.inside) : 'null';
2923
+ const nthN = Number.isInteger(opts.nth) ? opts.nth : 0;
2924
+ return `(() => {
2925
+ const sel=${selJ}, text=${textJ}, cont=${contJ}, rxs=${rxJ}, role=${roleJ}, inside=${insJ}, nth=${nthN};
2926
+ const root = inside ? document.querySelector(inside) : document;
2927
+ if (!root) return null;
2928
+ let els;
2929
+ if (sel) els = [...root.querySelectorAll(sel)];
2930
+ else if (role) els = [...root.querySelectorAll('[role="'+role+'"]')];
2931
+ else els = [...root.querySelectorAll('button, [role=button], a, [role=link], [role=menuitem], [role=option], [role=listitem], li')];
2932
+ if (text) { const t=text.toLowerCase(); els = els.filter(e => (e.innerText||'').toLowerCase().includes(t)); }
2933
+ if (cont) { const t=cont.toLowerCase(); els = els.filter(e => (e.innerText||'').toLowerCase().includes(t)); }
2934
+ if (rxs) { const rx=new RegExp(rxs, 'i'); els = els.filter(e => rx.test(e.innerText||'')); }
2935
+ return els[nth] || null;
2936
+ })()`;
2937
+ }
2938
+ async function cmdClickV2(argv) {
2939
+ const opts = parseFlags(argv, {
2940
+ text: { type: 'string' }, contains: { type: 'string' }, regex: { type: 'string' },
2941
+ nth: { type: 'int' }, role: { type: 'string' }, inside: { type: 'string' },
2942
+ wait: { type: 'int' }, 'scroll-into-view': { type: 'boolean' },
2943
+ double: { type: 'boolean' }, right: { type: 'boolean' },
2944
+ hold: { type: 'int' }, modifier: { type: 'string' },
2945
+ });
2946
+ const sel = opts._[0];
2947
+ if (!sel && !opts.text && !opts.contains && !opts.regex && !opts.role) {
2948
+ log.fail('Usage: glider click <selector> [--text S | --contains S | --regex R | --nth N | --role R | --inside S | --scroll-into-view | --double | --right | --wait MS]'); process.exit(1);
2949
+ }
2950
+ await _guardAndConnect('click');
2951
+ const findExpr = _buildFindElExpr(sel, opts);
2952
+ const modifiers = { ctrl: 2, shift: 8, alt: 1, meta: 4 };
2953
+ const modBits = opts.modifier ? (modifiers[opts.modifier] || 0) : 0;
2954
+ // Wait for existence if --wait
2955
+ if (opts.wait) {
2956
+ const deadline = Date.now() + opts.wait;
2957
+ while (Date.now() < deadline) {
2958
+ const r = await _rtEval(`(() => { return !!${findExpr}; })()`);
2959
+ if (r.result?.value === true) break;
2960
+ await new Promise(r => setTimeout(r, 100));
2961
+ }
2962
+ }
2963
+ if (opts['scroll-into-view']) {
2964
+ await _rtEval(`(() => { const el=${findExpr}; if (el) el.scrollIntoView({behavior:'auto',block:'center'}); void 0; })()`);
2965
+ await new Promise(r => setTimeout(r, 100));
2966
+ }
2967
+ // For pointer-input path (right/double/hold), we need coords; simple .click() covers left-single
2968
+ if (opts.right || opts.double || opts.hold) {
2969
+ const cr = await _rtEval(`(() => { const el=${findExpr}; if (!el) return {error:'not found'}; const r=el.getBoundingClientRect(); return { x: Math.round(r.left+r.width/2), y: Math.round(r.top+r.height/2) }; })()`);
2970
+ const v = cr.result?.value;
2971
+ if (v?.error) { if (jsonOutput) emitJson(false, null, v.error); log.fail(v.error); process.exit(1); }
2972
+ const button = opts.right ? 'right' : 'left';
2973
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mousePressed', x: v.x, y: v.y, button, clickCount: opts.double ? 2 : 1, modifiers: modBits } });
2974
+ if (opts.hold) await new Promise(r => setTimeout(r, opts.hold));
2975
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseReleased', x: v.x, y: v.y, button, clickCount: opts.double ? 2 : 1, modifiers: modBits } });
2976
+ if (opts.double) {
2977
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mousePressed', x: v.x, y: v.y, button, clickCount: 2, modifiers: modBits } });
2978
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseReleased', x: v.x, y: v.y, button, clickCount: 2, modifiers: modBits } });
2979
+ }
2980
+ if (jsonOutput) emitJson(true, { clicked: true, button, at: v });
2981
+ else log.ok(`Clicked (${button}${opts.double ? ',double' : ''}) at ${v.x},${v.y}`);
2982
+ return;
2983
+ }
2984
+ // Left-single path via el.click()
2985
+ const js = `(() => { const el=${findExpr}; if (!el) return {error:'Element not found'}; el.click(); return { clicked: true }; })()`;
2986
+ try {
2987
+ const r = await _rtEval(js);
2988
+ if (r.result?.value?.error) { if (jsonOutput) emitJson(false, null, r.result.value.error); log.fail(r.result.value.error); process.exit(1); }
2989
+ if (jsonOutput) emitJson(true, { clicked: true });
2990
+ else log.ok(`Clicked${sel ? ': '+sel : ''}${opts.text ? ' text='+opts.text : ''}`);
2991
+ } catch (e) {
2992
+ if (jsonOutput) emitJson(false, null, e.message);
2993
+ log.fail(`Click failed: ${e.message}`); process.exit(1);
2994
+ }
2995
+ }
2996
+
2997
+ // --- WAVE 1: cmdType (upgraded, --editor auto) ----------------------
2998
+ async function cmdTypeV2(argv) {
2999
+ const opts = parseFlags(argv, {
3000
+ editor: { type: 'string' }, // auto|ckeditor|tinymce|prosemirror|monaco|slate|contentEditable|textarea|input
3001
+ file: { type: 'string' },
3002
+ 'clear-first': { type: 'boolean' },
3003
+ commit: { type: 'string' }, // enter|tab|blur|none
3004
+ code: { type: 'boolean' },
3005
+ lang: { type: 'string' },
3006
+ intro: { type: 'string' },
3007
+ raw: { type: 'boolean' },
3008
+ 'delay-ms': { type: 'int' },
3009
+ });
3010
+ const sel = opts._[0];
3011
+ let text = opts._.slice(1).join(' ');
3012
+ if (opts.file) {
3013
+ try { text = fs.readFileSync(opts.file, 'utf8'); } catch (e) { log.fail(`Cannot read --file: ${e.message}`); process.exit(1); }
3014
+ }
3015
+ if (!sel || (text === undefined || text === null)) {
3016
+ log.fail('Usage: glider type <selector> <text> [--editor auto|...] [--file PATH] [--clear-first] [--commit enter|tab|blur|none] [--code --lang X --intro TXT]'); process.exit(1);
3017
+ }
3018
+ await _guardAndConnect('type');
3019
+ const editor = opts.editor || 'auto';
3020
+ const clear = !!opts['clear-first'];
3021
+ const codeBlock = !!opts.code;
3022
+ const b64 = Buffer.from(text, 'utf8').toString('base64');
3023
+ const langJ = JSON.stringify(opts.lang || 'plaintext');
3024
+ const introB64 = Buffer.from(opts.intro || '', 'utf8').toString('base64');
3025
+ const selJ = JSON.stringify(sel);
3026
+ const edJ = JSON.stringify(editor);
3027
+ // The heart: editor-agnostic write
3028
+ const js = `(() => {
3029
+ const dec = b => new TextDecoder().decode(Uint8Array.from(atob(b), c => c.charCodeAt(0)));
3030
+ const body = dec('${b64}');
3031
+ const intro = dec('${introB64}');
3032
+ const el = document.querySelector(${selJ});
3033
+ if (!el) return { error: 'Element not found', selector: ${selJ} };
3034
+ const codeBlock = ${codeBlock ? 'true' : 'false'};
3035
+ const langHint = ${langJ};
3036
+ const clearFirst = ${clear ? 'true' : 'false'};
3037
+ let editor = ${edJ};
3038
+ // auto-detect
3039
+ if (editor === 'auto') {
3040
+ if (el.ckeditorInstance) editor = 'ckeditor';
3041
+ else if (window.tinymce && window.tinymce.get && window.tinymce.get(el.id)) editor = 'tinymce';
3042
+ else if (el.pmView || el.classList.contains('ProseMirror') || el.closest('.ProseMirror')) editor = 'prosemirror';
3043
+ else if (el.classList.contains('monaco-editor') || el.closest('.monaco-editor')) editor = 'monaco';
3044
+ else if (el.hasAttribute('data-slate-editor')) editor = 'slate';
3045
+ else if (el.CodeMirror || el.classList.contains('CodeMirror')) editor = 'codemirror';
3046
+ else if (el.isContentEditable) editor = 'contentEditable';
3047
+ else if (el.tagName === 'TEXTAREA') editor = 'textarea';
3048
+ else editor = 'input';
3049
+ }
3050
+ try {
3051
+ if (editor === 'ckeditor') {
3052
+ const inst = el.ckeditorInstance;
3053
+ if (!inst) return { error: 'ckeditor instance missing' };
3054
+ if (clearFirst) inst.setData('');
3055
+ if (codeBlock) {
3056
+ const pre = document.createElement('pre'), code = document.createElement('code');
3057
+ if (langHint) code.className = 'language-' + langHint;
3058
+ code.textContent = body;
3059
+ pre.appendChild(code);
3060
+ const introHtml = intro ? ('<p>' + intro.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') + '</p>') : '';
3061
+ el.focus(); inst.setData(introHtml + pre.outerHTML);
3062
+ } else {
3063
+ el.focus(); inst.setData(body);
3064
+ }
3065
+ return { editor: 'ckeditor', wrote: inst.getData().length };
3066
+ }
3067
+ if (editor === 'tinymce') {
3068
+ const inst = window.tinymce.get(el.id);
3069
+ if (clearFirst) inst.setContent('');
3070
+ if (codeBlock) inst.setContent('<pre><code class="language-'+langHint+'">'+body.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;')+'</code></pre>');
3071
+ else inst.setContent(body);
3072
+ return { editor: 'tinymce' };
3073
+ }
3074
+ if (editor === 'monaco') {
3075
+ const mEl = el.classList.contains('monaco-editor') ? el : el.closest('.monaco-editor');
3076
+ // Search Monaco global registry for editor bound to this DOM node
3077
+ if (window.monaco && window.monaco.editor) {
3078
+ const eds = window.monaco.editor.getEditors ? window.monaco.editor.getEditors() : [];
3079
+ const me = eds.find(m => m.getContainerDomNode && m.getContainerDomNode() === mEl);
3080
+ if (me) { if (clearFirst) me.setValue(''); me.setValue(body); return { editor: 'monaco' }; }
3081
+ }
3082
+ return { error: 'monaco editor not resolvable' };
3083
+ }
3084
+ if (editor === 'prosemirror' || editor === 'slate' || editor === 'contentEditable') {
3085
+ // Best-effort: focus, select-all, insertText (execCommand path)
3086
+ const target = el.isContentEditable ? el : (el.querySelector('[contenteditable=true]') || el);
3087
+ target.focus();
3088
+ if (clearFirst) {
3089
+ const s = window.getSelection(); const r = document.createRange();
3090
+ r.selectNodeContents(target); s.removeAllRanges(); s.addRange(r);
3091
+ document.execCommand('delete', false, null);
3092
+ }
3093
+ // Insert as either code block or plain
3094
+ if (codeBlock) {
3095
+ document.execCommand('insertHTML', false, '<pre><code>' + body.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') + '</code></pre>');
3096
+ } else {
3097
+ document.execCommand('insertText', false, body);
3098
+ }
3099
+ return { editor };
3100
+ }
3101
+ if (editor === 'textarea' || editor === 'input') {
3102
+ const nativeSetter = Object.getOwnPropertyDescriptor(el.tagName === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype, 'value').set;
3103
+ if (clearFirst) { nativeSetter.call(el, ''); el.dispatchEvent(new Event('input', { bubbles: true })); }
3104
+ nativeSetter.call(el, (clearFirst || !el.value ? '' : el.value) + body);
3105
+ el.dispatchEvent(new Event('input', { bubbles: true }));
3106
+ el.dispatchEvent(new Event('change', { bubbles: true }));
3107
+ return { editor };
3108
+ }
3109
+ return { error: 'unknown editor: ' + editor };
3110
+ } catch (e) { return { error: 'editor write threw: ' + e.message }; }
3111
+ })()`;
3112
+ try {
3113
+ const r = await _rtEval(js);
3114
+ const v = r.result?.value;
3115
+ if (v?.error) { if (jsonOutput) emitJson(false, null, v.error); log.fail(v.error); process.exit(1); }
3116
+ if (opts.commit && opts.commit !== 'none') {
3117
+ // fire commit key via keyboard input layer
3118
+ const keyMap = { enter: 'Enter', tab: 'Tab' };
3119
+ if (opts.commit === 'blur') {
3120
+ await _rtEval(`(() => { const el = document.querySelector(${selJ}); if (el && el.blur) el.blur(); void 0; })()`);
3121
+ } else if (keyMap[opts.commit]) {
3122
+ await _dispatchKey(keyMap[opts.commit]);
3123
+ }
3124
+ }
3125
+ if (jsonOutput) emitJson(true, v);
3126
+ else log.ok(`Typed via ${v.editor || 'unknown'}${v.wrote ? ' (' + v.wrote + ' chars)' : ''}`);
3127
+ } catch (e) {
3128
+ if (jsonOutput) emitJson(false, null, e.message);
3129
+ log.fail(`Type failed: ${e.message}`); process.exit(1);
3130
+ }
3131
+ }
3132
+
3133
+ // --- WAVE 1: cmdWait (upgraded) --------------------------------------
3134
+ async function cmdWait(argv) {
3135
+ const opts = parseFlags(argv, {
3136
+ selector: { type: 'string' }, text: { type: 'string' }, gone: { type: 'string' },
3137
+ matches: { type: 'string' }, stable: { type: 'int' },
3138
+ 'network-idle': { type: 'int' }, 'url-matches': { type: 'string' },
3139
+ 'url-changes-from': { type: 'string' },
3140
+ timeout: { type: 'int', default: 10000 }, poll: { type: 'int', default: 200 },
3141
+ });
3142
+ const positional = opts._[0];
3143
+ // Back-compat: bare number = sleep in seconds
3144
+ if (positional && /^\d+(\.\d+)?$/.test(positional) && !opts.selector && !opts.matches && !opts.text && !opts.gone && !opts['url-matches']) {
3145
+ await new Promise(r => setTimeout(r, parseFloat(positional) * 1000));
3146
+ if (jsonOutput) emitJson(true, { slept_ms: parseFloat(positional) * 1000 });
3147
+ return;
3148
+ }
3149
+ await _guardAndConnect('wait');
3150
+ const deadline = Date.now() + opts.timeout;
3151
+ const buildProbe = () => {
3152
+ if (opts.selector) {
3153
+ const t = opts.text ? JSON.stringify(opts.text.toLowerCase()) : 'null';
3154
+ return `(() => { const e = document.querySelector(${JSON.stringify(opts.selector)}); if (!e) return false; const t=${t}; return t ? (e.innerText||'').toLowerCase().includes(t) : true; })()`;
3155
+ }
3156
+ if (opts.gone) return `!document.querySelector(${JSON.stringify(opts.gone)})`;
3157
+ if (opts.matches) return `!!(${opts.matches})`;
3158
+ if (opts['url-matches']) return `new RegExp(${JSON.stringify(opts['url-matches'])}).test(location.href)`;
3159
+ if (opts['url-changes-from']) return `location.href !== ${JSON.stringify(opts['url-changes-from'])}`;
3160
+ return 'true';
3161
+ };
3162
+ const probe = buildProbe();
3163
+ let lastRect = null; let stableStart = null;
3164
+ while (Date.now() < deadline) {
3165
+ try {
3166
+ const r = await _rtEval(probe, { awaitPromise: false });
3167
+ const v = r.result?.value;
3168
+ if (opts.stable && opts.selector) {
3169
+ const rr = await _rtEval(`(() => { const e = document.querySelector(${JSON.stringify(opts.selector)}); if (!e) return null; const r=e.getBoundingClientRect(); return [r.x,r.y,r.width,r.height]; })()`);
3170
+ const rect = rr.result?.value;
3171
+ if (rect && lastRect && rect.every((n,i)=>n===lastRect[i])) {
3172
+ if (!stableStart) stableStart = Date.now();
3173
+ if (Date.now() - stableStart >= opts.stable) { if (jsonOutput) emitJson(true, { stable_ms: opts.stable }); else log.ok(`stable for ${opts.stable}ms`); return; }
3174
+ } else { stableStart = null; }
3175
+ lastRect = rect;
3176
+ } else if (v === true) {
3177
+ if (jsonOutput) emitJson(true, { matched: true });
3178
+ else log.ok('condition met');
3179
+ return;
3180
+ }
3181
+ } catch (_) { /* ignore transient */ }
3182
+ await new Promise(r => setTimeout(r, opts.poll));
3183
+ }
3184
+ if (jsonOutput) emitJson(false, null, 'wait timeout');
3185
+ log.fail(`wait timeout after ${opts.timeout}ms`); process.exit(1);
3186
+ }
3187
+
3188
+ // --- WAVE 2: cmdKey / cmdRightClick / cmdDoubleClick / cmdDrag --------
3189
+ function _keyEventTemplate(keyName) {
3190
+ const specials = {
3191
+ Enter: { code: 'Enter', keyCode: 13, key: 'Enter', text: '\r' },
3192
+ Tab: { code: 'Tab', keyCode: 9, key: 'Tab' },
3193
+ Escape: { code: 'Escape', keyCode: 27, key: 'Escape' },
3194
+ Backspace: { code: 'Backspace', keyCode: 8, key: 'Backspace' },
3195
+ Delete: { code: 'Delete', keyCode: 46, key: 'Delete' },
3196
+ ArrowUp: { code: 'ArrowUp', keyCode: 38, key: 'ArrowUp' },
3197
+ ArrowDown: { code: 'ArrowDown', keyCode: 40, key: 'ArrowDown' },
3198
+ ArrowLeft: { code: 'ArrowLeft', keyCode: 37, key: 'ArrowLeft' },
3199
+ ArrowRight: { code: 'ArrowRight', keyCode: 39, key: 'ArrowRight' },
3200
+ Home: { code: 'Home', keyCode: 36, key: 'Home' },
3201
+ End: { code: 'End', keyCode: 35, key: 'End' },
3202
+ PageUp: { code: 'PageUp', keyCode: 33, key: 'PageUp' },
3203
+ PageDown: { code: 'PageDown', keyCode: 34, key: 'PageDown' },
3204
+ Space: { code: 'Space', keyCode: 32, key: ' ', text: ' ' },
3205
+ };
3206
+ return specials[keyName] || null;
3207
+ }
3208
+ async function _dispatchKey(keyName, mods = 0) {
3209
+ const tpl = _keyEventTemplate(keyName);
3210
+ if (!tpl) throw new Error('unknown key: ' + keyName);
3211
+ await httpPost('/cdp', { method: 'Input.dispatchKeyEvent', params: { type: 'keyDown', modifiers: mods, ...tpl } });
3212
+ await httpPost('/cdp', { method: 'Input.dispatchKeyEvent', params: { type: 'keyUp', modifiers: mods, ...tpl } });
3213
+ }
3214
+ async function _insertText(text) {
3215
+ await httpPost('/cdp', { method: 'Input.insertText', params: { text } });
3216
+ }
3217
+ async function cmdKey(argv) {
3218
+ await _guardAndConnect('key');
3219
+ // Grammar: `Ctrl+Enter`, `ArrowDown x5`, `Escape`, or `"literal text"`
3220
+ const raw = argv.join(' ');
3221
+ if (!raw) { log.fail('Usage: glider key "<Chord|Sequence>" e.g. "Ctrl+Enter" | "ArrowDown x5" | "Escape" | --text "insert this"'); process.exit(1); }
3222
+ const opts = parseFlags(argv, { text: { type: 'string' } });
3223
+ if (opts.text) { await _insertText(opts.text); if (jsonOutput) emitJson(true, { inserted: opts.text.length }); else log.ok(`Inserted ${opts.text.length} chars`); return; }
3224
+ // parse repeat count: "ArrowDown x5"
3225
+ const m = raw.match(/^([\w+]+)(?:\s+x(\d+))?$/i);
3226
+ if (m) {
3227
+ const chord = m[1]; const times = m[2] ? parseInt(m[2], 10) : 1;
3228
+ const parts = chord.split('+');
3229
+ const key = parts[parts.length - 1];
3230
+ const modMap = { ctrl: 2, control: 2, shift: 8, alt: 1, meta: 4, cmd: 4 };
3231
+ let mods = 0;
3232
+ for (const p of parts.slice(0, -1)) mods |= (modMap[p.toLowerCase()] || 0);
3233
+ for (let i = 0; i < times; i++) await _dispatchKey(key, mods);
3234
+ if (jsonOutput) emitJson(true, { key: chord, times });
3235
+ else log.ok(`Sent ${chord}${times>1 ? ' x'+times : ''}`);
3236
+ return;
3237
+ }
3238
+ log.fail('Could not parse key expression: ' + raw); process.exit(1);
3239
+ }
3240
+ async function cmdRightClick(argv) { await cmdClickV2(['--right', ...argv]); }
3241
+ async function cmdDoubleClick(argv) { await cmdClickV2(['--double', ...argv]); }
3242
+ async function cmdClickAt(argv) {
3243
+ const parts = (argv[0] || '').split(',');
3244
+ if (parts.length !== 2) { log.fail('Usage: glider click-at x,y'); process.exit(1); }
3245
+ const x = parseInt(parts[0], 10); const y = parseInt(parts[1], 10);
3246
+ await _guardAndConnect('click-at');
3247
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mousePressed', x, y, button: 'left', clickCount: 1 } });
3248
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 } });
3249
+ if (jsonOutput) emitJson(true, { clicked: {x, y} });
3250
+ else log.ok(`Clicked at ${x},${y}`);
3251
+ }
3252
+ async function cmdDrag(argv) {
3253
+ const opts = parseFlags(argv, { to: { type: 'string' }, steps: { type: 'int', default: 10 } });
3254
+ const src = opts._[0]; const dst = opts.to;
3255
+ if (!src || !dst) { log.fail('Usage: glider drag <src-sel> --to <dst-sel> [--steps N]'); process.exit(1); }
3256
+ await _guardAndConnect('drag');
3257
+ const r = await _rtEval(`(() => {
3258
+ const a = document.querySelector(${JSON.stringify(src)}); const b = document.querySelector(${JSON.stringify(dst)});
3259
+ if (!a || !b) return { error: 'src or dst not found' };
3260
+ const ra=a.getBoundingClientRect(), rb=b.getBoundingClientRect();
3261
+ return { sx: Math.round(ra.left+ra.width/2), sy: Math.round(ra.top+ra.height/2), dx: Math.round(rb.left+rb.width/2), dy: Math.round(rb.top+rb.height/2) };
3262
+ })()`);
3263
+ const v = r.result?.value;
3264
+ if (v?.error) { log.fail(v.error); process.exit(1); }
3265
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mousePressed', x: v.sx, y: v.sy, button: 'left', clickCount: 1 } });
3266
+ for (let i = 1; i <= opts.steps; i++) {
3267
+ const x = v.sx + Math.round((v.dx - v.sx) * i / opts.steps);
3268
+ const y = v.sy + Math.round((v.dy - v.sy) * i / opts.steps);
3269
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseMoved', x, y, button: 'left' } });
3270
+ }
3271
+ await httpPost('/cdp', { method: 'Input.dispatchMouseEvent', params: { type: 'mouseReleased', x: v.dx, y: v.dy, button: 'left', clickCount: 1 } });
3272
+ if (jsonOutput) emitJson(true, { dragged: {from: [v.sx,v.sy], to: [v.dx,v.dy]} });
3273
+ else log.ok(`Dragged ${v.sx},${v.sy} -> ${v.dx},${v.dy}`);
3274
+ }
3275
+
3276
+ // --- WAVE 2: cmdSelect ----------------------------------------------
3277
+ async function cmdSelect(argv) {
3278
+ const opts = parseFlags(argv, { 'by-text': { type: 'string' }, 'by-value': { type: 'string' }, nth: { type: 'int', default: 0 } });
3279
+ const sel = opts._[0];
3280
+ if (!sel || (!opts['by-text'] && !opts['by-value'] && opts.nth === undefined)) {
3281
+ log.fail('Usage: glider select <selector> --by-text S | --by-value V | --nth N'); process.exit(1);
3282
+ }
3283
+ await _guardAndConnect('select');
3284
+ const wantJ = JSON.stringify(opts['by-text'] || opts['by-value'] || '');
3285
+ const mode = opts['by-text'] ? 'text' : opts['by-value'] ? 'value' : 'nth';
3286
+ const nth = opts.nth || 0;
3287
+ const js = `(() => {
3288
+ const el = document.querySelector(${JSON.stringify(sel)});
3289
+ if (!el) return { error: 'select not found' };
3290
+ const want = ${wantJ}; const mode = ${JSON.stringify(mode)}; const nth = ${nth};
3291
+ if (el.tagName === 'SELECT') {
3292
+ const opts = [...el.options];
3293
+ let target;
3294
+ if (mode === 'text') target = opts.find(o => (o.textContent||'').trim().toLowerCase().includes(want.toLowerCase()));
3295
+ else if (mode === 'value') target = opts.find(o => o.value === want);
3296
+ else target = opts[nth];
3297
+ if (!target) return { error: 'option not found' };
3298
+ el.value = target.value;
3299
+ el.dispatchEvent(new Event('change', { bubbles: true }));
3300
+ return { selected: target.value };
3301
+ }
3302
+ // aria-listbox / aria-combobox path
3303
+ const listbox = el.getAttribute('role') === 'listbox' ? el : el.querySelector('[role=listbox]');
3304
+ if (listbox) {
3305
+ const options = [...listbox.querySelectorAll('[role=option]')];
3306
+ let target;
3307
+ if (mode === 'text') target = options.find(o => (o.textContent||'').toLowerCase().includes(want.toLowerCase()));
3308
+ else if (mode === 'value') target = options.find(o => o.getAttribute('data-value') === want || o.textContent.trim() === want);
3309
+ else target = options[nth];
3310
+ if (!target) return { error: 'aria option not found' };
3311
+ target.click();
3312
+ return { selected: target.textContent.trim() };
3313
+ }
3314
+ return { error: 'not a select or listbox' };
3315
+ })()`;
3316
+ const r = await _rtEval(js);
3317
+ const v = r.result?.value;
3318
+ if (v?.error) { if (jsonOutput) emitJson(false, null, v.error); log.fail(v.error); process.exit(1); }
3319
+ if (jsonOutput) emitJson(true, v);
3320
+ else log.ok(`Selected: ${v.selected}`);
3321
+ }
3322
+
3323
+ // --- WAVE 2: cmdEval upgrade (--arg, --arg-file, --json, --await, --context) ---
3324
+ async function cmdEvalV2(argv) {
3325
+ const opts = parseFlags(argv, {
3326
+ arg: { type: 'string' }, 'arg-file': { type: 'string' },
3327
+ json: { type: 'boolean' }, await: { type: 'boolean', default: true },
3328
+ context: { type: 'string' }, // main|iframe|sw|worker (advisory only for now)
3329
+ });
3330
+ const js = opts._.join(' ');
3331
+ if (!js) { log.fail('Usage: glider eval <js> [--arg K=V ...] [--arg-file K=@path ...] [--await] [--context main|iframe|sw|worker]'); process.exit(1); }
3332
+ if (!await ensureConnected()) process.exit(1);
3333
+ // Build ${K} substitutions safely
3334
+ // Multiple --arg parses: user may pass --arg foo=bar --arg baz=qux ; parseFlags only kept the last one.
3335
+ // So we re-walk argv for all --arg / --arg-file occurrences.
3336
+ const args = {};
3337
+ for (let i = 0; i < argv.length; i++) {
3338
+ if (argv[i] === '--arg' && argv[i+1]) { const [k, ...rest] = argv[++i].split('='); args[k] = rest.join('='); }
3339
+ else if (argv[i] === '--arg-file' && argv[i+1]) {
3340
+ const spec = argv[++i]; const [k, ...rest] = spec.split('='); const path = rest.join('=');
3341
+ const p = path.replace(/^@/, '');
3342
+ args[k] = fs.readFileSync(p, 'utf8');
3343
+ }
3344
+ }
3345
+ // Substitute ${K} with JSON.stringified value so it's injection-safe
3346
+ let expr = js.replace(/\$\{(\w+)\}/g, (m, k) => k in args ? JSON.stringify(args[k]) : m);
3347
+ try {
3348
+ const r = await _rtEval(expr, { awaitPromise: opts.await !== false });
3349
+ const v = r.result?.value;
3350
+ if (opts.json || jsonOutput) emitJson(true, v !== undefined ? v : r.result);
3351
+ else if (v !== undefined) console.log(typeof v === 'string' ? v : JSON.stringify(v));
3352
+ else console.log(JSON.stringify(r));
3353
+ } catch (e) {
3354
+ if (jsonOutput || opts.json) emitJson(false, null, e.message);
3355
+ log.fail(`Eval failed: ${e.message}`); process.exit(1);
3356
+ }
3357
+ }
3358
+
3359
+ // --- WAVE 2: cmdScreenshot upgrade (--selector, --clip, --full-page, --format) ---
3360
+ async function cmdScreenshotV2(argv) {
3361
+ const opts = parseFlags(argv, {
3362
+ selector: { type: 'string' }, clip: { type: 'string' },
3363
+ 'full-page': { type: 'boolean' }, format: { type: 'string', default: 'png' },
3364
+ pad: { type: 'int', default: 0 },
3365
+ });
3366
+ const outPath = opts._[0] || `/tmp/glider-screenshot-${Date.now()}.${opts.format}`;
3367
+ if (!await ensureConnected()) process.exit(1);
3368
+ const params = { format: opts.format };
3369
+ if (opts.selector) {
3370
+ const r = await _rtEval(`(() => { const el = document.querySelector(${JSON.stringify(opts.selector)}); if (!el) return null; const r = el.getBoundingClientRect(); return { x: r.left, y: r.top, width: r.width, height: r.height, dpr: window.devicePixelRatio || 1 }; })()`);
3371
+ const v = r.result?.value;
3372
+ if (!v) { log.fail('selector not found'); process.exit(1); }
3373
+ params.clip = { x: v.x - opts.pad, y: v.y - opts.pad, width: v.width + opts.pad*2, height: v.height + opts.pad*2, scale: 1 };
3374
+ } else if (opts.clip) {
3375
+ const [x, y, w, h] = opts.clip.split(',').map(Number);
3376
+ params.clip = { x, y, width: w, height: h, scale: 1 };
3377
+ }
3378
+ if (opts['full-page']) params.captureBeyondViewport = true;
3379
+ try {
3380
+ const result = await httpPost('/cdp', { method: 'Page.captureScreenshot', params });
3381
+ if (result.data) {
3382
+ fs.writeFileSync(outPath, Buffer.from(result.data, 'base64'));
3383
+ if (jsonOutput) emitJson(true, { path: outPath, bytes: Buffer.byteLength(result.data, 'base64') });
3384
+ else log.ok(`Screenshot: ${outPath}`);
3385
+ } else { log.fail('no screenshot data'); process.exit(1); }
3386
+ } catch (e) { log.fail(`Screenshot failed: ${e.message}`); process.exit(1); }
3387
+ }
3388
+
3389
+ // --- WAVE 2: session_liveness_probe (upgrade cmdUseSession) ---
3390
+ async function cmdUseSessionV2(arg, opts = []) {
3391
+ // Try normal path first
3392
+ try {
3393
+ await cmdUseSession(arg, opts);
3394
+ return;
3395
+ } catch (_) { /* fall through to re-probe */ }
3396
+ // Re-probe: connect + fetch targets, re-match on --url if provided
3397
+ const urlIdx = opts.indexOf('--url');
3398
+ if (urlIdx >= 0 && opts[urlIdx+1]) {
3399
+ log.warn('use-session failed - re-probing');
3400
+ try {
3401
+ const result = await httpPost('/list-targets', {});
3402
+ const targets = result.targets || [];
3403
+ const want = opts[urlIdx+1].toLowerCase();
3404
+ const hit = targets.find(t => (t.url||'').toLowerCase().includes(want));
3405
+ if (hit) { await cmdUseSession(hit.sessionId, opts); return; }
3406
+ } catch (e) { log.fail(`re-probe failed: ${e.message}`); }
3407
+ }
3408
+ log.fail(`use-session: session not live and no --url to re-probe`); process.exit(1);
3409
+ }
3410
+
3411
+ // --- WAVE 3: frames + iframe-scope-eval + upload-file ---
3412
+ async function cmdFrames(argv) {
3413
+ await _guardAndConnect('frames');
3414
+ try {
3415
+ const r = await httpPost('/cdp', { method: 'Page.getFrameTree', params: {} });
3416
+ if (jsonOutput) emitJson(true, r.frameTree);
3417
+ else console.log(JSON.stringify(r.frameTree, null, 2));
3418
+ } catch (e) { log.fail(`frames failed: ${e.message}`); process.exit(1); }
3419
+ }
3420
+ async function cmdFrameEval(argv) {
3421
+ const frameId = argv[0]; const js = argv.slice(1).join(' ');
3422
+ if (!frameId || !js) { log.fail('Usage: glider frame-eval <frameId> <js>'); process.exit(1); }
3423
+ await _guardAndConnect('frame-eval');
3424
+ // Create isolated world in frame, eval there
3425
+ try {
3426
+ const iw = await httpPost('/cdp', { method: 'Page.createIsolatedWorld', params: { frameId, worldName: 'glider' } });
3427
+ const r = await _rtEval(js, { contextId: iw.executionContextId });
3428
+ const v = r.result?.value;
3429
+ if (jsonOutput) emitJson(true, v);
3430
+ else console.log(typeof v === 'string' ? v : JSON.stringify(v));
3431
+ } catch (e) { log.fail(`frame-eval failed: ${e.message}`); process.exit(1); }
3432
+ }
3433
+ async function cmdUpload(argv) {
3434
+ const sel = argv[0]; const filePath = argv[1];
3435
+ if (!sel || !filePath) { log.fail('Usage: glider upload <input-selector> <file-path>'); process.exit(1); }
3436
+ await _guardAndConnect('upload');
3437
+ try {
3438
+ const nodeR = await _rtEval(`(() => { const el = document.querySelector(${JSON.stringify(sel)}); if (!el) return null; return true; })()`);
3439
+ if (!nodeR.result?.value) { log.fail('input not found'); process.exit(1); }
3440
+ // Need backendNodeId via DOM.getDocument -> DOM.querySelector
3441
+ const doc = await httpPost('/cdp', { method: 'DOM.getDocument', params: { depth: -1 } });
3442
+ const q = await httpPost('/cdp', { method: 'DOM.querySelector', params: { nodeId: doc.root.nodeId, selector: sel } });
3443
+ if (!q.nodeId) { log.fail('nodeId lookup failed'); process.exit(1); }
3444
+ await httpPost('/cdp', { method: 'DOM.setFileInputFiles', params: { files: [filePath], nodeId: q.nodeId } });
3445
+ if (jsonOutput) emitJson(true, { uploaded: filePath, to: sel });
3446
+ else log.ok(`Attached ${filePath} to ${sel}`);
3447
+ } catch (e) { log.fail(`upload failed: ${e.message}`); process.exit(1); }
3448
+ }
3449
+
3450
+ // --- WAVE 3: cmdHar (start/stop/dump/replay) ---
3451
+ let HAR_BUFFER = null;
3452
+ async function cmdHar(argv) {
3453
+ const sub = argv[0];
3454
+ await _guardAndConnect('har');
3455
+ const HAR_STATE = path.join(os.homedir(), '.glider', 'har-buffer.json');
3456
+ if (sub === 'start') {
3457
+ await httpPost('/cdp', { method: 'Network.enable', params: {} });
3458
+ HAR_BUFFER = { started: new Date().toISOString(), entries: [] };
3459
+ try { fs.mkdirSync(path.dirname(HAR_STATE), { recursive: true }); } catch {}
3460
+ fs.writeFileSync(HAR_STATE, JSON.stringify(HAR_BUFFER));
3461
+ // Note: full HAR requires event subscription (persistent server); here we mark state; user can dump devtools separately if needed.
3462
+ if (jsonOutput) emitJson(true, { started: true, state_file: HAR_STATE });
3463
+ else log.ok(`HAR capture started; state at ${HAR_STATE} (server-side subscription not implemented - stub)`);
3464
+ } else if (sub === 'stop') {
3465
+ await httpPost('/cdp', { method: 'Network.disable', params: {} });
3466
+ if (jsonOutput) emitJson(true, { stopped: true });
3467
+ else log.ok('HAR capture stopped');
3468
+ } else if (sub === 'dump') {
3469
+ const p = argv[1] || `/tmp/glider-${Date.now()}.har`;
3470
+ let buf; try { buf = JSON.parse(fs.readFileSync(HAR_STATE, 'utf8')); } catch { buf = { entries: [] }; }
3471
+ const har = { log: { version: '1.2', creator: { name: 'glider', version: require('../package.json').version }, entries: buf.entries } };
3472
+ fs.writeFileSync(p, JSON.stringify(har, null, 2));
3473
+ if (jsonOutput) emitJson(true, { path: p, entries: buf.entries.length });
3474
+ else log.ok(`HAR dumped to ${p} (${buf.entries.length} entries - event stream not yet wired)`);
3475
+ } else {
3476
+ log.fail('Usage: glider har start | stop | dump [PATH] | replay <entry-id>'); process.exit(1);
3477
+ }
3478
+ }
3479
+
3480
+ // --- WAVE 4: cmdEmulate ---
3481
+ async function cmdEmulate(argv) {
3482
+ const what = argv[0]; const val = argv.slice(1).join(' ');
3483
+ if (!what) { log.fail('Usage: glider emulate <tz|geo|viewport|offline|ua|color-scheme> <value>'); process.exit(1); }
3484
+ await _guardAndConnect('emulate');
3485
+ try {
3486
+ if (what === 'tz') {
3487
+ await httpPost('/cdp', { method: 'Emulation.setTimezoneOverride', params: { timezoneId: val } });
3488
+ } else if (what === 'geo') {
3489
+ const [lat, lng, acc] = val.split(',').map(Number);
3490
+ await httpPost('/cdp', { method: 'Emulation.setGeolocationOverride', params: { latitude: lat, longitude: lng, accuracy: acc || 100 } });
3491
+ } else if (what === 'viewport') {
3492
+ const m = val.match(/^(\d+)x(\d+)(?:,(\d+(?:\.\d+)?))?(?:,(true|false))?$/);
3493
+ if (!m) { log.fail('viewport format: WxH[,dpr[,mobile]]'); process.exit(1); }
3494
+ await httpPost('/cdp', { method: 'Emulation.setDeviceMetricsOverride', params: { width: parseInt(m[1]), height: parseInt(m[2]), deviceScaleFactor: m[3] ? parseFloat(m[3]) : 1, mobile: m[4] === 'true' } });
3495
+ } else if (what === 'offline') {
3496
+ const presets = { true: { offline: true, latency: 0, downloadThroughput: 0, uploadThroughput: 0 }, 'slow-3g': { offline: false, latency: 400, downloadThroughput: 51200, uploadThroughput: 51200 }, 'fast-4g': { offline: false, latency: 20, downloadThroughput: 4*1024*1024/8, uploadThroughput: 3*1024*1024/8 }, false: { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 } };
3497
+ const p = presets[val]; if (!p) { log.fail('offline: true|slow-3g|fast-4g|false'); process.exit(1); }
3498
+ await httpPost('/cdp', { method: 'Network.emulateNetworkConditions', params: p });
3499
+ } else if (what === 'ua') {
3500
+ await httpPost('/cdp', { method: 'Emulation.setUserAgentOverride', params: { userAgent: val } });
3501
+ } else if (what === 'color-scheme') {
3502
+ await httpPost('/cdp', { method: 'Emulation.setEmulatedMedia', params: { features: [{ name: 'prefers-color-scheme', value: val }] } });
3503
+ } else { log.fail(`unknown emulate target: ${what}`); process.exit(1); }
3504
+ if (jsonOutput) emitJson(true, { emulate: what, value: val });
3505
+ else log.ok(`Emulated ${what}=${val}`);
3506
+ } catch (e) { log.fail(`emulate failed: ${e.message}`); process.exit(1); }
3507
+ }
3508
+
3509
+ // --- WAVE 4: cmdStorage ---
3510
+ async function cmdStorage(argv) {
3511
+ const sub = argv[0];
3512
+ await _guardAndConnect('storage');
3513
+ if (sub === 'get') {
3514
+ const k = argv[1]; if (!k) { log.fail('storage get <key>'); process.exit(1); }
3515
+ const r = await _rtEval(`localStorage.getItem(${JSON.stringify(k)})`);
3516
+ if (jsonOutput) emitJson(true, r.result?.value); else console.log(r.result?.value || '');
3517
+ } else if (sub === 'set') {
3518
+ const k = argv[1]; const v = argv.slice(2).join(' ');
3519
+ await _rtEval(`localStorage.setItem(${JSON.stringify(k)}, ${JSON.stringify(v)}); void 0;`);
3520
+ if (jsonOutput) emitJson(true, { set: k }); else log.ok(`storage set: ${k}`);
3521
+ } else if (sub === 'delete') {
3522
+ const k = argv[1];
3523
+ await _rtEval(`localStorage.removeItem(${JSON.stringify(k)}); void 0;`);
3524
+ if (jsonOutput) emitJson(true, { deleted: k }); else log.ok(`storage deleted: ${k}`);
3525
+ } else if (sub === 'keys') {
3526
+ const r = await _rtEval(`Object.keys(localStorage)`);
3527
+ if (jsonOutput) emitJson(true, r.result?.value);
3528
+ else (r.result?.value || []).forEach(k => console.log(k));
3529
+ } else if (sub === 'jar') {
3530
+ const r = await _rtEval(`(() => { const o={}; for (let i=0;i<localStorage.length;i++){const k=localStorage.key(i); o[k]=localStorage.getItem(k);} return o; })()`);
3531
+ if (jsonOutput) emitJson(true, r.result?.value);
3532
+ else console.log(JSON.stringify(r.result?.value || {}, null, 2));
3533
+ } else {
3534
+ log.fail('Usage: glider storage get <k> | set <k> <v> | delete <k> | keys | jar'); process.exit(1);
3535
+ }
3536
+ }
3537
+
3538
+ // --- WAVE 4: cmdHistory + cmdDialog + cmdConsole + cmdPdf ---
3539
+ async function cmdHistory(argv) {
3540
+ const sub = argv[0]; await _guardAndConnect('history');
3541
+ if (sub === 'back') await _rtEval('history.back(); void 0;');
3542
+ else if (sub === 'forward') await _rtEval('history.forward(); void 0;');
3543
+ else if (sub === 'reload') await httpPost('/cdp', { method: 'Page.reload', params: {} });
3544
+ else { log.fail('Usage: glider history back | forward | reload'); process.exit(1); }
3545
+ if (jsonOutput) emitJson(true, { history: sub }); else log.ok(`history ${sub}`);
3546
+ }
3547
+ async function cmdDialog(argv) {
3548
+ const sub = argv[0]; const action = argv[1];
3549
+ if (sub !== 'auto' || !['accept','dismiss'].includes(action)) { log.fail('Usage: glider dialog auto accept|dismiss'); process.exit(1); }
3550
+ await _guardAndConnect('dialog');
3551
+ // NOTE: needs bg WS subscription to Page.javascriptDialogOpening for full solution.
3552
+ // Here: inject a page-side beforeunload/confirm/alert stub.
3553
+ await _rtEval(`(() => {
3554
+ window.alert = () => ${action === 'accept' ? 'true' : 'undefined'};
3555
+ window.confirm = () => ${action === 'accept' ? 'true' : 'false'};
3556
+ window.prompt = () => ${action === 'accept' ? "''" : 'null'};
3557
+ window.onbeforeunload = null;
3558
+ return { installed: true };
3559
+ })()`);
3560
+ if (jsonOutput) emitJson(true, { dialog: 'auto-' + action });
3561
+ else log.ok(`Dialog auto-${action} installed`);
3562
+ }
3563
+ async function cmdConsole(argv) {
3564
+ const sub = argv[0]; if (sub !== 'tail' && sub !== 'dump') { log.fail('Usage: glider console tail | dump [PATH]'); process.exit(1); }
3565
+ await _guardAndConnect('console');
3566
+ await httpPost('/cdp', { method: 'Runtime.enable', params: {} });
3567
+ // Persistent tail requires bg WS; here we do a one-shot poll: enable console + report installed
3568
+ log.warn('console tail is stub - needs bg WS subscription to Runtime.consoleAPICalled');
3569
+ if (jsonOutput) emitJson(true, { installed: true, note: 'stub - bg subscription required' });
3570
+ }
3571
+ async function cmdPdf(argv) {
3572
+ const opts = parseFlags(argv, { landscape: { type: 'boolean' }, margin: { type: 'float' }, scale: { type: 'float', default: 1.0 } });
3573
+ const outPath = opts._[0] || `/tmp/glider-${Date.now()}.pdf`;
3574
+ await _guardAndConnect('pdf');
3575
+ try {
3576
+ const params = { landscape: !!opts.landscape, scale: opts.scale, printBackground: true };
3577
+ if (opts.margin !== undefined) { params.marginTop = params.marginBottom = params.marginLeft = params.marginRight = opts.margin; }
3578
+ const r = await httpPost('/cdp', { method: 'Page.printToPDF', params });
3579
+ if (r.data) { fs.writeFileSync(outPath, Buffer.from(r.data, 'base64')); if (jsonOutput) emitJson(true, { path: outPath }); else log.ok(`PDF: ${outPath}`); }
3580
+ else { log.fail('no pdf data'); process.exit(1); }
3581
+ } catch (e) { log.fail(`pdf failed: ${e.message}`); process.exit(1); }
3582
+ }
3583
+ async function cmdCookieWrite(argv) {
3584
+ const opts = parseFlags(argv, { set: { type: 'string' }, delete: { type: 'string' }, host: { type: 'string' } });
3585
+ if (!opts.host) { log.fail('Usage: glider cookies --set NAME=VAL --host H | --delete NAME --host H'); process.exit(1); }
3586
+ await _guardAndConnect('cookies-write');
3587
+ try {
3588
+ if (opts.set) {
3589
+ const [name, ...rest] = opts.set.split('='); const value = rest.join('=');
3590
+ const r = await httpPost('/extension', { method: 'setCookie', params: { url: 'https://' + opts.host, name, value } });
3591
+ if (jsonOutput) emitJson(true, r); else log.ok(`cookie set: ${name}@${opts.host}`);
3592
+ } else if (opts.delete) {
3593
+ const r = await httpPost('/extension', { method: 'removeCookie', params: { url: 'https://' + opts.host, name: opts.delete } });
3594
+ if (jsonOutput) emitJson(true, r); else log.ok(`cookie deleted: ${opts.delete}@${opts.host}`);
3595
+ }
3596
+ } catch (e) { log.fail(`cookie write failed: ${e.message}`); process.exit(1); }
3597
+ }
3598
+
3599
+ // --- WAVE 5: cmdMock + cmdA11ySnapshot + cmdRecord/Replay ---
3600
+ async function cmdMock(argv) {
3601
+ const sub = argv[0];
3602
+ await _guardAndConnect('mock');
3603
+ if (sub === 'clear') {
3604
+ await httpPost('/cdp', { method: 'Fetch.disable', params: {} });
3605
+ if (jsonOutput) emitJson(true, { cleared: true }); else log.ok('mocks cleared');
3606
+ return;
3607
+ }
3608
+ const opts = parseFlags(argv.slice(1), { status: { type: 'int', default: 200 }, body: { type: 'string' } });
3609
+ const glob = argv[0];
3610
+ if (!glob || !opts.body) { log.fail('Usage: glider mock <url-glob> --status N --body FILE | glider mock clear'); process.exit(1); }
3611
+ try {
3612
+ await httpPost('/cdp', { method: 'Fetch.enable', params: { patterns: [{ urlPattern: glob }] } });
3613
+ log.warn('mock is stub - needs bg WS subscription to Fetch.requestPaused + Fetch.fulfillRequest');
3614
+ if (jsonOutput) emitJson(true, { registered: glob, note: 'stub' });
3615
+ } catch (e) { log.fail(`mock failed: ${e.message}`); process.exit(1); }
3616
+ }
3617
+ async function cmdA11y(argv) {
3618
+ await _guardAndConnect('a11y');
3619
+ try {
3620
+ await httpPost('/cdp', { method: 'Accessibility.enable', params: {} });
3621
+ const r = await httpPost('/cdp', { method: 'Accessibility.getFullAXTree', params: {} });
3622
+ if (jsonOutput) emitJson(true, r.nodes);
3623
+ else console.log(JSON.stringify(r.nodes, null, 2));
3624
+ } catch (e) { log.fail(`a11y failed: ${e.message}`); process.exit(1); }
3625
+ }
3626
+
3627
+ // End of dom-scorch verb block. Total ≈ 30 verbs / verb-upgrades.
3628
+
3629
+
2256
3630
  // Main
2257
3631
  async function main() {
2258
3632
  const args = parseGlobalFlags(process.argv.slice(2));
2259
3633
  loadPersistedSession();
3634
+ loadPlugins(); // hydrate ~/.glider/plugins/*.plugin.{json,js} - verb-agnostic core
2260
3635
  let cmd = args[0];
2261
3636
 
2262
3637
  // v0.3.15: reload-ext command aliases -
@@ -2357,7 +3732,7 @@ async function main() {
2357
3732
  await cmdTargets();
2358
3733
  break;
2359
3734
  case 'use-session':
2360
- await cmdUseSession(args[1], args.slice(2));
3735
+ await cmdUseSessionV2(args[1], args.slice(2));
2361
3736
  break;
2362
3737
  case 'snapshot':
2363
3738
  await cmdSnapshot(args.slice(1));
@@ -2381,17 +3756,98 @@ async function main() {
2381
3756
  break;
2382
3757
  case 'eval':
2383
3758
  case 'js':
2384
- await cmdEval(args.slice(1).join(' '));
3759
+ await cmdEvalV2(args.slice(1));
2385
3760
  break;
2386
3761
  case 'click':
2387
- await cmdClick(args[1]);
3762
+ await cmdClickV2(args.slice(1));
2388
3763
  break;
2389
3764
  case 'type':
2390
- await cmdType(args[1], args.slice(2).join(' '));
3765
+ await cmdTypeV2(args.slice(1));
2391
3766
  break;
2392
3767
  case 'screenshot':
2393
- await cmdScreenshot(args[1]);
3768
+ await cmdScreenshotV2(args.slice(1));
3769
+ break;
3770
+ // ── dom-scorch waves 1-5 ──
3771
+ case 'read':
3772
+ await cmdRead(args.slice(1));
3773
+ break;
3774
+ case 'hover':
3775
+ await cmdHover(args.slice(1));
3776
+ break;
3777
+ case 'focus':
3778
+ await cmdFocusVerb(args.slice(1));
3779
+ break;
3780
+ case 'blur':
3781
+ await cmdBlurVerb(args.slice(1));
3782
+ break;
3783
+ case 'scroll':
3784
+ case 'scroll-to':
3785
+ case 'scroll-by':
3786
+ case 'scroll-until':
3787
+ if (cmd === 'scroll') await cmdScroll(args.slice(1));
3788
+ else await cmdScroll([cmd.replace('scroll-',''), ...args.slice(1)]);
3789
+ break;
3790
+ case 'wait':
3791
+ await cmdWait(args.slice(1));
3792
+ break;
3793
+ case 'key':
3794
+ await cmdKey(args.slice(1));
3795
+ break;
3796
+ case 'right-click':
3797
+ await cmdRightClick(args.slice(1));
3798
+ break;
3799
+ case 'double-click':
3800
+ await cmdDoubleClick(args.slice(1));
3801
+ break;
3802
+ case 'click-at':
3803
+ await cmdClickAt(args.slice(1));
3804
+ break;
3805
+ case 'drag':
3806
+ await cmdDrag(args.slice(1));
3807
+ break;
3808
+ case 'select':
3809
+ await cmdSelect(args.slice(1));
2394
3810
  break;
3811
+ case 'frames':
3812
+ await cmdFrames(args.slice(1));
3813
+ break;
3814
+ case 'frame-eval':
3815
+ await cmdFrameEval(args.slice(1));
3816
+ break;
3817
+ case 'upload':
3818
+ await cmdUpload(args.slice(1));
3819
+ break;
3820
+ case 'har':
3821
+ await cmdHar(args.slice(1));
3822
+ break;
3823
+ case 'emulate':
3824
+ await cmdEmulate(args.slice(1));
3825
+ break;
3826
+ case 'storage':
3827
+ await cmdStorage(args.slice(1));
3828
+ break;
3829
+ case 'history':
3830
+ await cmdHistory(args.slice(1));
3831
+ break;
3832
+ case 'dialog':
3833
+ await cmdDialog(args.slice(1));
3834
+ break;
3835
+ case 'console':
3836
+ await cmdConsole(args.slice(1));
3837
+ break;
3838
+ case 'pdf':
3839
+ await cmdPdf(args.slice(1));
3840
+ break;
3841
+ case 'mock':
3842
+ await cmdMock(args.slice(1));
3843
+ break;
3844
+ case 'a11y':
3845
+ await cmdA11y(args.slice(1));
3846
+ break;
3847
+ case 'cookies-write':
3848
+ await cmdCookieWrite(args.slice(1));
3849
+ break;
3850
+ // ── /dom-scorch ──
2395
3851
  case 'text':
2396
3852
  await cmdText();
2397
3853
  break;
@@ -2413,6 +3869,16 @@ async function main() {
2413
3869
  case 'cfetch':
2414
3870
  await cmdCorsFetch(args[1], args.slice(2));
2415
3871
  break;
3872
+ case 'frozen':
3873
+ await cmdFrozen(args.slice(1));
3874
+ break;
3875
+ case 'cookies':
3876
+ if (args.slice(1).some(a => a === '--set' || a === '--delete')) {
3877
+ await cmdCookieWrite(args.slice(1));
3878
+ } else {
3879
+ await cmdCookies(args.slice(1));
3880
+ }
3881
+ break;
2416
3882
  case 'spawn':
2417
3883
  await cmdSpawn(args.slice(1));
2418
3884
  break;
@@ -2452,6 +3918,11 @@ async function main() {
2452
3918
  await cmdLoop(taskArg, loopOpts);
2453
3919
  break;
2454
3920
  default:
3921
+ // Plugin registry check FIRST - locally-hydrated verbs win over "unknown"
3922
+ if (GLIDER_PLUGIN_REGISTRY.has(cmd)) {
3923
+ await runPlugin(GLIDER_PLUGIN_REGISTRY.get(cmd), args.slice(1));
3924
+ break;
3925
+ }
2455
3926
  // Check if it's a domain command from config
2456
3927
  if (DOMAINS[cmd]) {
2457
3928
  const domain = DOMAINS[cmd];
@@ -2481,7 +3952,9 @@ async function main() {
2481
3952
  const KNOWN_CMDS = ['status','start','stop','restart','reload-ext','attach-all','install','uninstall',
2482
3953
  'update','version','connect','browser','use','test','domains','resolve','goto','eval','click','type',
2483
3954
  'screenshot','snapshot','text','html','title','url','tabs','targets','use-session','fetch','spawn',
2484
- 'extract','explore','favicon','window','reg','run','loop','ralph'];
3955
+ 'extract','explore','favicon','window','reg','run','loop','ralph',
3956
+ 'read','hover','focus','blur','scroll','wait','key','right-click','double-click','click-at','drag','select',
3957
+ 'frames','frame-eval','upload','har','emulate','storage','history','dialog','console','pdf','mock','a11y','cookies'];
2485
3958
  function lev(a, b) {
2486
3959
  if (Math.abs(a.length - b.length) > 2) return 3;
2487
3960
  const m = Array.from({length: a.length+1}, () => new Array(b.length+1).fill(0));