mirror of
https://github.com/garrytan/gstack.git
synced 2026-05-12 23:43:05 +08:00
* feat: CDP inspector module — persistent sessions, CSS cascade, style modification New browse/src/cdp-inspector.ts with full CDP inspection engine: - inspectElement() via CSS.getMatchedStylesForNode + DOM.getBoxModel - modifyStyle() via CSS.setStyleTexts with headless page.evaluate fallback - Persistent CDP session lifecycle (create, reuse, detach on nav, re-create) - Specificity sorting, overridden property detection, UA rule filtering - Modification history with undo support - formatInspectorResult() for CLI output Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: browse server inspector endpoints + inspect/style/cleanup/prettyscreenshot CLI Server endpoints: POST /inspector/pick, GET /inspector, POST /inspector/apply, POST /inspector/reset, GET /inspector/history, GET /inspector/events (SSE). CLI commands: inspect (CDP cascade), style (live CSS mod), cleanup (page clutter removal), prettyscreenshot (clean screenshot pipeline). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: sidebar CSS inspector — element picker, box model, rule cascade, quick edit Extension changes for the visual CSS inspector: - inspector.js: element picker with hover highlight, CSS selector generation, basic mode fallback (getComputedStyle + CSSOM), page alteration handlers - inspector.css: picker overlay styles (blue highlight + tooltip) - background.js: inspector message routing (picker <-> server <-> sidepanel) - sidepanel: Inspector tab with box model viz (gstack palette), matched rules with specificity badges, computed styles, click-to-edit quick edit, Send to Agent/Code button, empty/loading/error states Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: document inspect, style, cleanup, prettyscreenshot browse commands Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: auto-track user-created tabs and handle tab close browser-manager.ts changes: - context.on('page') listener: automatically tracks tabs opened by the user (Cmd+T, right-click open in new tab, window.open). Previously only programmatic newTab() was tracked, so user tabs were invisible. - page.on('close') handler in wirePageEvents: removes closed tabs from the pages map and switches activeTabId to the last remaining tab. - syncActiveTabByUrl: match Chrome extension's active tab URL to the correct Playwright page for accurate tab identity. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: per-tab agent isolation via BROWSE_TAB environment variable Prevents parallel sidebar agents from interfering with each other's tab context. Three-layer fix: - sidebar-agent.ts: passes BROWSE_TAB=<tabId> env var to each claude process, per-tab processing set allows concurrent agents across tabs - cli.ts: reads process.env.BROWSE_TAB and includes tabId in command request body - server.ts: handleCommand() temporarily switches activeTabId when tabId is present, restores after command completes (safe: Bun event loop is single-threaded) Also: per-tab agent state (TabAgentState map), per-tab message queuing, per-tab chat buffers, verbose streaming narration, stop button endpoint. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: sidebar per-tab chat context, tab bar sync, stop button, UX polish Extension changes: - sidepanel.js: per-tab chat history (tabChatHistories map), switchChatTab() swaps entire chat view, browserTabActivated handler for instant tab sync, stop button wired to /sidebar-agent/stop, pollTabs renders tab bar - sidepanel.html: updated banner text ("Browser co-pilot"), stop button markup, input placeholder "Ask about this page..." - sidepanel.css: tab bar styles, stop button styles, loading state fixes - background.js: chrome.tabs.onActivated sends browserTabActivated to sidepanel with tab URL for instant tab switch detection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: per-tab isolation, BROWSE_TAB pinning, tab tracking, sidebar UX sidebar-agent.test.ts (new tests): - BROWSE_TAB env var passed to claude process - CLI reads BROWSE_TAB and sends tabId in body - handleCommand accepts tabId, saves/restores activeTabId - Tab pinning only activates when tabId provided - Per-tab agent state, queue, concurrency - processingTabs set for parallel agents sidebar-ux.test.ts (new tests): - context.on('page') tracks user-created tabs - page.on('close') removes tabs from pages map - Tab isolation uses BROWSE_TAB not system prompt hack - Per-tab chat context in sidepanel - Tab bar rendering, stop button, banner text Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: resolve merge conflicts — keep security defenses + per-tab isolation Merged main's security improvements (XML escaping, prompt injection defense, allowed commands whitelist, --model opus, Write tool, stderr capture) with our branch's per-tab isolation (BROWSE_TAB env var, processingTabs set, no --resume). Updated test expectations for expanded system prompt. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: bump version and changelog (v0.13.9.0) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add inspector message types to background.js allowlist Pre-existing bug found by Codex: ALLOWED_TYPES in background.js was missing all inspector message types (startInspector, stopInspector, elementPicked, pickerCancelled, applyStyle, toggleClass, injectCSS, resetAll, inspectResult). Messages were silently rejected, making the inspector broken on ALL pages. Also: separate executeScript and insertCSS into individual try blocks in injectInspector(), store inspectorMode for routing, and add content.js fallback when script injection fails (CSP, chrome:// pages). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: basic element picker in content.js for CSP-restricted pages When inspector.js can't be injected (CSP, chrome:// pages), content.js provides a basic picker using getComputedStyle + CSSOM: - startBasicPicker/stopBasicPicker message handlers - captureBasicData() with ~30 key CSS properties, box model, matched rules - Hover highlight with outline save/restore (never leaves artifacts) - Click uses e.target directly (no re-querying by selector) - Sends inspectResult with mode:'basic' for sidebar rendering - Escape key cancels picker and restores outlines Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: cleanup + screenshot buttons in sidebar inspector toolbar Two action buttons in the inspector toolbar: - Cleanup (🧹): POSTs cleanup --all to server, shows spinner, chat notification on success, resets inspector state (element may be removed) - Screenshot (📸): POSTs screenshot to server, shows spinner, chat notification with saved file path Shared infrastructure: - .inspector-action-btn CSS with loading spinner via ::after pseudo-element - chat-notification type in addChatEntry() for system messages - package.json version bump to 0.13.9.0 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: inspector allowlist, CSP fallback, cleanup/screenshot buttons 16 new tests in sidebar-ux.test.ts: - Inspector message allowlist includes all inspector types - content.js basic picker (startBasicPicker, captureBasicData, CSSOM, outline save/restore, inspectResult with mode basic, Escape cleanup) - background.js CSP fallback (separate try blocks, inspectorMode, fallback) - Cleanup button (POST /command, inspector reset after success) - Screenshot button (POST /command, notification rendering) - Chat notification type and CSS styles Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: update project documentation for v0.13.9.0 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: cleanup + screenshot buttons in chat toolbar (not just inspector) Quick actions toolbar (🧹 Cleanup, 📸 Screenshot) now appears above the chat input, always visible. Both inspector and chat buttons share runCleanup() and runScreenshot() helper functions. Clicking either set shows loading state on both simultaneously. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: chat toolbar buttons, shared helpers, quick-action-btn styles Tests that chat toolbar exists (chat-cleanup-btn, chat-screenshot-btn, quick-actions container), CSS styles (.quick-action-btn, .quick-action-btn.loading), shared runCleanup/runScreenshot helper functions, and cleanup inspector reset. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: aggressive cleanup heuristics — overlays, scroll unlock, blur removal Massively expanded CLEANUP_SELECTORS with patterns from uBlock Origin and Readability.js research: - ads: 30+ selectors (Google, Amazon, Outbrain, Taboola, Criteo, etc.) - cookies: OneTrust, Cookiebot, TrustArc, Quantcast + generic patterns - overlays (NEW): paywalls, newsletter popups, interstitials, push prompts, app download banners, survey modals - social: follow prompts, share tools - Cleanup now defaults to --all when no args (sidebar button fix) - Uses !important on all display:none (overrides inline styles) - Unlocks body/html scroll (overflow:hidden from modal lockout) - Removes blur/filter effects (paywall content blur) - Removes max-height truncation (article teaser truncation) - Collapses empty ad placeholder whitespace (empty divs after ad removal) - Skips gstack-ctrl indicator in sticky removal Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: disable action buttons when disconnected, no error spam - setActionButtonsEnabled() toggles .disabled class on all cleanup/screenshot buttons (both chat toolbar and inspector toolbar) - Called with false in updateConnection when server URL is null - Called with true when connection established - runCleanup/runScreenshot silently return when disconnected instead of showing 'Not connected' error notifications - CSS .disabled style: pointer-events:none, opacity:0.3, cursor:not-allowed Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: cleanup heuristics, button disabled state, overlay selectors 17 new tests: - cleanup defaults to --all on empty args - CLEANUP_SELECTORS overlays category (paywall, newsletter, interstitial) - Major ad networks in selectors (doubleclick, taboola, criteo, etc.) - Major consent frameworks (OneTrust, Cookiebot, TrustArc, Quantcast) - !important override for inline styles - Scroll unlock (body overflow:hidden) - Blur removal (paywall content blur) - Article truncation removal (max-height) - Empty placeholder collapse - gstack-ctrl indicator skip in sticky cleanup - setActionButtonsEnabled function - Buttons disabled when disconnected - No error spam from cleanup/screenshot when disconnected - CSS disabled styles for action buttons Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: LLM-based page cleanup — agent analyzes page semantically Instead of brittle CSS selectors, the cleanup button now sends a prompt to the sidebar agent (which IS an LLM). The agent: 1. Runs deterministic $B cleanup --all as a quick first pass 2. Takes a snapshot to see what's left 3. Analyzes the page semantically to identify remaining clutter 4. Removes elements intelligently, preserving site branding This means cleanup works correctly on any site without site-specific selectors. The LLM understands that "Your Daily Puzzles" is clutter, "ADVERTISEMENT" is junk, but the SF Chronicle masthead should stay. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: aggressive cleanup heuristics + preserve top nav bar Deterministic cleanup improvements (used as first pass before LLM analysis): - New 'clutter' category: audio players, podcast widgets, sidebar puzzles/games, recirculation widgets (taboola, outbrain, nativo), cross-promotion banners - Text-content detection: removes "ADVERTISEMENT", "Article continues below", "Sponsored", "Paid content" labels and their parent wrappers - Sticky fix: preserves the topmost full-width element near viewport top (site nav bar) instead of hiding all sticky/fixed elements. Sorts by vertical position, preserves the first one that spans >80% viewport width. Tests: clutter category, ad label removal, nav bar preservation logic. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: LLM-based cleanup architecture, deterministic heuristics, sticky nav 22 new tests covering: - Cleanup button uses /sidebar-command (agent) not /command (deterministic) - Cleanup prompt includes deterministic first pass + agent snapshot analysis - Cleanup prompt lists specific clutter categories for agent guidance - Cleanup prompt preserves site identity (masthead, headline, body, byline) - Cleanup prompt instructs scroll unlock and $B eval removal - Loading state management (async agent, setTimeout) - Deterministic clutter: audio/podcast, games/puzzles, recirculation - Ad label text patterns (ADVERTISEMENT, Sponsored, Article continues) - Ad label parent wrapper hiding for small containers - Sticky nav preservation (sort by position, first full-width near top) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: prevent repeat chat message rendering on reconnect/replay Root cause: server persists chat to disk (chat.jsonl) and replays on restart. Client had no dedup, so every reconnect re-rendered the entire history. Messages from an old HN session would repeat endlessly on the SF Chronicle tab. Fix: renderedEntryIds Set tracks which entry IDs have been rendered. addChatEntry skips entries already in the set. Entries without an id (local notifications) bypass the check. Clear chat resets the set. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: agent stops when done, no focus stealing, opus for prompt injection safety Three fixes for sidebar agent UX: - System prompt: "Be CONCISE. STOP as soon as the task is done. Do NOT keep exploring or doing bonus work." Prevents agent from endlessly taking screenshots and highlighting elements after answering the question. - switchTab(id, opts): new bringToFront option. Internal tab pinning (BROWSE_TAB) uses bringToFront: false so agent commands never steal window focus from the user's active app. - Keep opus model (not sonnet) for prompt injection resistance on untrusted web pages. Remove Write from allowedTools (agent only needs Bash for $B). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: agent conciseness, focus stealing, opus model, switchTab opts Tests for the three UX fixes: - System prompt contains STOP/CONCISE/Do NOT keep exploring - sidebar agent uses opus (not sonnet) for prompt injection resistance - switchTab has bringToFront option, defaults to true (opt-out) - handleCommand tab pinning uses bringToFront: false (no focus steal) - Updated stale tests: switchTab signature, allowedTools excludes Write, narration -> conciseness, tab pinning restore calls Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: sidebar CSS interaction E2E — HN comment highlight round-trip New E2E test (periodic tier, ~$2/run) that exercises the full sidebar agent pipeline with CSS interaction: 1. Agent navigates to Hacker News 2. Clicks into the top story's comments 3. Reads comments and identifies the most insightful one 4. Highlights it with a 4px solid orange outline via style injection Tests: navigation, snapshot, text reading, LLM judgment, CSS modification. Requires real browser + real Claude (ANTHROPIC_API_KEY). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: sidebar CSS E2E test — correct idle timeout (ms not s), pipe stdio Root cause of test failure: BROWSE_IDLE_TIMEOUT is in milliseconds, not seconds. '600' = 0.6 seconds, server died immediately after health check. Fixed to '600000' (10 minutes). Also: use 'pipe' stdio instead of file descriptors (closing fds kills child on macOS/bun), catch ConnectionRefused on poll retry, 4 min poll timeout for the multi-step opus task. Test passes: agent navigates to HN, reads comments, identifies most insightful one, highlights it with orange CSS, stops. 114s, $0.00. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
762 lines
25 KiB
TypeScript
762 lines
25 KiB
TypeScript
/**
|
|
* CDP Inspector — Chrome DevTools Protocol integration for deep CSS inspection
|
|
*
|
|
* Manages a persistent CDP session per active page for:
|
|
* - Full CSS rule cascade inspection (matched rules, computed styles, inline styles)
|
|
* - Box model measurement
|
|
* - Live CSS modification via CSS.setStyleTexts
|
|
* - Modification history with undo/reset
|
|
*
|
|
* Session lifecycle:
|
|
* Create on first inspect call → reuse across inspections → detach on
|
|
* navigation/tab switch/shutdown → re-create transparently on next call
|
|
*/
|
|
|
|
import type { Page } from 'playwright';
|
|
|
|
// ─── Types ──────────────────────────────────────────────────────
|
|
|
|
export interface InspectorResult {
|
|
selector: string;
|
|
tagName: string;
|
|
id: string | null;
|
|
classes: string[];
|
|
attributes: Record<string, string>;
|
|
boxModel: {
|
|
content: { x: number; y: number; width: number; height: number };
|
|
padding: { top: number; right: number; bottom: number; left: number };
|
|
border: { top: number; right: number; bottom: number; left: number };
|
|
margin: { top: number; right: number; bottom: number; left: number };
|
|
};
|
|
computedStyles: Record<string, string>;
|
|
matchedRules: Array<{
|
|
selector: string;
|
|
properties: Array<{ name: string; value: string; important: boolean; overridden: boolean }>;
|
|
source: string;
|
|
sourceLine: number;
|
|
sourceColumn: number;
|
|
specificity: { a: number; b: number; c: number };
|
|
media?: string;
|
|
userAgent: boolean;
|
|
styleSheetId?: string;
|
|
range?: object;
|
|
}>;
|
|
inlineStyles: Record<string, string>;
|
|
pseudoElements: Array<{
|
|
pseudo: string;
|
|
rules: Array<{ selector: string; properties: string }>;
|
|
}>;
|
|
}
|
|
|
|
export interface StyleModification {
|
|
selector: string;
|
|
property: string;
|
|
oldValue: string;
|
|
newValue: string;
|
|
source: string;
|
|
sourceLine: number;
|
|
timestamp: number;
|
|
method: 'setStyleTexts' | 'inline';
|
|
}
|
|
|
|
// ─── Constants ──────────────────────────────────────────────────
|
|
|
|
/** ~55 key CSS properties for computed style output */
|
|
const KEY_CSS_PROPERTIES = [
|
|
'display', 'position', 'top', 'right', 'bottom', 'left',
|
|
'float', 'clear', 'z-index', 'overflow', 'overflow-x', 'overflow-y',
|
|
'width', 'height', 'min-width', 'max-width', 'min-height', 'max-height',
|
|
'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
|
|
'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
|
|
'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width',
|
|
'border-style', 'border-color',
|
|
'font-family', 'font-size', 'font-weight', 'line-height',
|
|
'color', 'background-color', 'background-image', 'opacity',
|
|
'box-shadow', 'border-radius', 'transform', 'transition',
|
|
'flex-direction', 'flex-wrap', 'justify-content', 'align-items', 'gap',
|
|
'grid-template-columns', 'grid-template-rows',
|
|
'text-align', 'text-decoration', 'visibility', 'cursor', 'pointer-events',
|
|
];
|
|
|
|
const KEY_CSS_SET = new Set(KEY_CSS_PROPERTIES);
|
|
|
|
// ─── Session Management ─────────────────────────────────────────
|
|
|
|
/** Map of Page → CDP session. Sessions are reused per page. */
|
|
const cdpSessions = new WeakMap<Page, any>();
|
|
/** Track which pages have initialized DOM+CSS domains */
|
|
const initializedPages = new WeakSet<Page>();
|
|
|
|
/**
|
|
* Get or create a CDP session for the given page.
|
|
* Enables DOM + CSS domains on first use.
|
|
*/
|
|
async function getOrCreateSession(page: Page): Promise<any> {
|
|
let session = cdpSessions.get(page);
|
|
if (session) {
|
|
// Verify session is still alive
|
|
try {
|
|
await session.send('DOM.getDocument', { depth: 0 });
|
|
return session;
|
|
} catch {
|
|
// Session is stale — recreate
|
|
cdpSessions.delete(page);
|
|
initializedPages.delete(page);
|
|
}
|
|
}
|
|
|
|
session = await page.context().newCDPSession(page);
|
|
cdpSessions.set(page, session);
|
|
|
|
// Enable DOM and CSS domains
|
|
await session.send('DOM.enable');
|
|
await session.send('CSS.enable');
|
|
initializedPages.add(page);
|
|
|
|
// Auto-detach on navigation
|
|
page.once('framenavigated', () => {
|
|
try {
|
|
session.detach().catch(() => {});
|
|
} catch {}
|
|
cdpSessions.delete(page);
|
|
initializedPages.delete(page);
|
|
});
|
|
|
|
return session;
|
|
}
|
|
|
|
// ─── Modification History ───────────────────────────────────────
|
|
|
|
const modificationHistory: StyleModification[] = [];
|
|
|
|
// ─── Specificity Calculation ────────────────────────────────────
|
|
|
|
/**
|
|
* Parse a CSS selector and compute its specificity as {a, b, c}.
|
|
* a = ID selectors, b = class/attr/pseudo-class, c = type/pseudo-element
|
|
*/
|
|
function computeSpecificity(selector: string): { a: number; b: number; c: number } {
|
|
let a = 0, b = 0, c = 0;
|
|
|
|
// Remove :not() wrapper but count its contents
|
|
let cleaned = selector;
|
|
|
|
// Count IDs: #foo
|
|
const ids = cleaned.match(/#[a-zA-Z_-][\w-]*/g);
|
|
if (ids) a += ids.length;
|
|
|
|
// Count classes: .foo, attribute selectors: [attr], pseudo-classes: :hover (not ::)
|
|
const classes = cleaned.match(/\.[a-zA-Z_-][\w-]*/g);
|
|
if (classes) b += classes.length;
|
|
const attrs = cleaned.match(/\[[^\]]+\]/g);
|
|
if (attrs) b += attrs.length;
|
|
const pseudoClasses = cleaned.match(/(?<!:):[a-zA-Z][\w-]*/g);
|
|
if (pseudoClasses) b += pseudoClasses.length;
|
|
|
|
// Count type selectors: div, span (not * universal)
|
|
const types = cleaned.match(/(?:^|[\s+~>])([a-zA-Z][\w-]*)/g);
|
|
if (types) c += types.length;
|
|
// Count pseudo-elements: ::before, ::after
|
|
const pseudoElements = cleaned.match(/::[a-zA-Z][\w-]*/g);
|
|
if (pseudoElements) c += pseudoElements.length;
|
|
|
|
return { a, b, c };
|
|
}
|
|
|
|
/**
|
|
* Compare specificities: returns negative if s1 < s2, positive if s1 > s2, 0 if equal.
|
|
*/
|
|
function compareSpecificity(
|
|
s1: { a: number; b: number; c: number },
|
|
s2: { a: number; b: number; c: number }
|
|
): number {
|
|
if (s1.a !== s2.a) return s1.a - s2.a;
|
|
if (s1.b !== s2.b) return s1.b - s2.b;
|
|
return s1.c - s2.c;
|
|
}
|
|
|
|
// ─── Core Functions ─────────────────────────────────────────────
|
|
|
|
/**
|
|
* Inspect an element via CDP, returning full CSS cascade data.
|
|
*/
|
|
export async function inspectElement(
|
|
page: Page,
|
|
selector: string,
|
|
options?: { includeUA?: boolean }
|
|
): Promise<InspectorResult> {
|
|
const session = await getOrCreateSession(page);
|
|
|
|
// Get document root
|
|
const { root } = await session.send('DOM.getDocument', { depth: 0 });
|
|
|
|
// Query for the element
|
|
let nodeId: number;
|
|
try {
|
|
const result = await session.send('DOM.querySelector', {
|
|
nodeId: root.nodeId,
|
|
selector,
|
|
});
|
|
nodeId = result.nodeId;
|
|
if (!nodeId) throw new Error(`Element not found: ${selector}`);
|
|
} catch (err: any) {
|
|
throw new Error(`Element not found: ${selector} — ${err.message}`);
|
|
}
|
|
|
|
// Get element attributes
|
|
const { node } = await session.send('DOM.describeNode', { nodeId, depth: 0 });
|
|
const tagName = (node.localName || node.nodeName || '').toLowerCase();
|
|
const attrPairs = node.attributes || [];
|
|
const attributes: Record<string, string> = {};
|
|
for (let i = 0; i < attrPairs.length; i += 2) {
|
|
attributes[attrPairs[i]] = attrPairs[i + 1];
|
|
}
|
|
const id = attributes.id || null;
|
|
const classes = attributes.class ? attributes.class.split(/\s+/).filter(Boolean) : [];
|
|
|
|
// Get box model
|
|
let boxModel = {
|
|
content: { x: 0, y: 0, width: 0, height: 0 },
|
|
padding: { top: 0, right: 0, bottom: 0, left: 0 },
|
|
border: { top: 0, right: 0, bottom: 0, left: 0 },
|
|
margin: { top: 0, right: 0, bottom: 0, left: 0 },
|
|
};
|
|
|
|
try {
|
|
const boxData = await session.send('DOM.getBoxModel', { nodeId });
|
|
const model = boxData.model;
|
|
|
|
// Content quad: [x1,y1, x2,y2, x3,y3, x4,y4]
|
|
const content = model.content;
|
|
const padding = model.padding;
|
|
const border = model.border;
|
|
const margin = model.margin;
|
|
|
|
const contentX = content[0];
|
|
const contentY = content[1];
|
|
const contentWidth = content[2] - content[0];
|
|
const contentHeight = content[5] - content[1];
|
|
|
|
boxModel = {
|
|
content: { x: contentX, y: contentY, width: contentWidth, height: contentHeight },
|
|
padding: {
|
|
top: content[1] - padding[1],
|
|
right: padding[2] - content[2],
|
|
bottom: padding[5] - content[5],
|
|
left: content[0] - padding[0],
|
|
},
|
|
border: {
|
|
top: padding[1] - border[1],
|
|
right: border[2] - padding[2],
|
|
bottom: border[5] - padding[5],
|
|
left: padding[0] - border[0],
|
|
},
|
|
margin: {
|
|
top: border[1] - margin[1],
|
|
right: margin[2] - border[2],
|
|
bottom: margin[5] - border[5],
|
|
left: border[0] - margin[0],
|
|
},
|
|
};
|
|
} catch {
|
|
// Element may not have a box model (e.g., display:none)
|
|
}
|
|
|
|
// Get matched styles
|
|
const matchedData = await session.send('CSS.getMatchedStylesForNode', { nodeId });
|
|
|
|
// Get computed styles
|
|
const computedData = await session.send('CSS.getComputedStyleForNode', { nodeId });
|
|
const computedStyles: Record<string, string> = {};
|
|
for (const entry of computedData.computedStyle) {
|
|
if (KEY_CSS_SET.has(entry.name)) {
|
|
computedStyles[entry.name] = entry.value;
|
|
}
|
|
}
|
|
|
|
// Get inline styles
|
|
const inlineData = await session.send('CSS.getInlineStylesForNode', { nodeId });
|
|
const inlineStyles: Record<string, string> = {};
|
|
if (inlineData.inlineStyle?.cssProperties) {
|
|
for (const prop of inlineData.inlineStyle.cssProperties) {
|
|
if (prop.name && prop.value && !prop.disabled) {
|
|
inlineStyles[prop.name] = prop.value;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Process matched rules
|
|
const matchedRules: InspectorResult['matchedRules'] = [];
|
|
|
|
// Track all property values to mark overridden ones
|
|
const seenProperties = new Map<string, number>(); // property → index of highest-specificity rule
|
|
|
|
if (matchedData.matchedCSSRules) {
|
|
for (const match of matchedData.matchedCSSRules) {
|
|
const rule = match.rule;
|
|
const isUA = rule.origin === 'user-agent';
|
|
|
|
if (isUA && !options?.includeUA) continue;
|
|
|
|
// Get the matching selector text
|
|
let selectorText = '';
|
|
if (rule.selectorList?.selectors) {
|
|
// Use the specific matching selector
|
|
const matchingIdx = match.matchingSelectors?.[0] ?? 0;
|
|
selectorText = rule.selectorList.selectors[matchingIdx]?.text || rule.selectorList.text || '';
|
|
}
|
|
|
|
// Get source info
|
|
let source = 'inline';
|
|
let sourceLine = 0;
|
|
let sourceColumn = 0;
|
|
let styleSheetId: string | undefined;
|
|
let range: object | undefined;
|
|
|
|
if (rule.styleSheetId) {
|
|
styleSheetId = rule.styleSheetId;
|
|
try {
|
|
// Try to resolve stylesheet URL
|
|
source = rule.origin === 'regular' ? (rule.styleSheetId || 'stylesheet') : rule.origin;
|
|
} catch {}
|
|
}
|
|
|
|
if (rule.style?.range) {
|
|
range = rule.style.range;
|
|
sourceLine = rule.style.range.startLine || 0;
|
|
sourceColumn = rule.style.range.startColumn || 0;
|
|
}
|
|
|
|
// Try to get a friendly source name from stylesheet
|
|
if (styleSheetId) {
|
|
try {
|
|
// Stylesheet URL might be embedded in the rule data
|
|
// CDP provides sourceURL in some cases
|
|
if (rule.style?.cssText) {
|
|
// Parse source from the styleSheetId metadata
|
|
}
|
|
} catch {}
|
|
}
|
|
|
|
// Get media query if present
|
|
let media: string | undefined;
|
|
if (match.rule?.media) {
|
|
const mediaList = match.rule.media;
|
|
if (Array.isArray(mediaList) && mediaList.length > 0) {
|
|
media = mediaList.map((m: any) => m.text).filter(Boolean).join(', ');
|
|
}
|
|
}
|
|
|
|
const specificity = computeSpecificity(selectorText);
|
|
|
|
// Process CSS properties
|
|
const properties: Array<{ name: string; value: string; important: boolean; overridden: boolean }> = [];
|
|
if (rule.style?.cssProperties) {
|
|
for (const prop of rule.style.cssProperties) {
|
|
if (!prop.name || prop.disabled) continue;
|
|
// Skip internal/vendor properties unless they are in our key set
|
|
if (prop.name.startsWith('-') && !KEY_CSS_SET.has(prop.name)) continue;
|
|
|
|
properties.push({
|
|
name: prop.name,
|
|
value: prop.value || '',
|
|
important: prop.important || (prop.value?.includes('!important') ?? false),
|
|
overridden: false, // will be set later
|
|
});
|
|
}
|
|
}
|
|
|
|
matchedRules.push({
|
|
selector: selectorText,
|
|
properties,
|
|
source,
|
|
sourceLine,
|
|
sourceColumn,
|
|
specificity,
|
|
media,
|
|
userAgent: isUA,
|
|
styleSheetId,
|
|
range,
|
|
});
|
|
}
|
|
}
|
|
|
|
// Sort by specificity (highest first — these win)
|
|
matchedRules.sort((a, b) => -compareSpecificity(a.specificity, b.specificity));
|
|
|
|
// Mark overridden properties: the first rule in the sorted list (highest specificity) wins
|
|
for (let i = 0; i < matchedRules.length; i++) {
|
|
for (const prop of matchedRules[i].properties) {
|
|
const key = prop.name;
|
|
if (!seenProperties.has(key)) {
|
|
seenProperties.set(key, i);
|
|
} else {
|
|
// This property was already declared by a higher-specificity rule
|
|
// Unless this one is !important and the earlier one isn't
|
|
const earlierIdx = seenProperties.get(key)!;
|
|
const earlierRule = matchedRules[earlierIdx];
|
|
const earlierProp = earlierRule.properties.find(p => p.name === key);
|
|
if (prop.important && earlierProp && !earlierProp.important) {
|
|
// This !important overrides the earlier non-important
|
|
if (earlierProp) earlierProp.overridden = true;
|
|
seenProperties.set(key, i);
|
|
} else {
|
|
prop.overridden = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Process pseudo-elements
|
|
const pseudoElements: InspectorResult['pseudoElements'] = [];
|
|
if (matchedData.pseudoElements) {
|
|
for (const pseudo of matchedData.pseudoElements) {
|
|
const pseudoType = pseudo.pseudoType || 'unknown';
|
|
const rules: Array<{ selector: string; properties: string }> = [];
|
|
if (pseudo.matches) {
|
|
for (const match of pseudo.matches) {
|
|
const rule = match.rule;
|
|
const sel = rule.selectorList?.text || '';
|
|
const props = (rule.style?.cssProperties || [])
|
|
.filter((p: any) => p.name && !p.disabled)
|
|
.map((p: any) => `${p.name}: ${p.value}`)
|
|
.join('; ');
|
|
if (props) {
|
|
rules.push({ selector: sel, properties: props });
|
|
}
|
|
}
|
|
}
|
|
if (rules.length > 0) {
|
|
pseudoElements.push({ pseudo: `::${pseudoType}`, rules });
|
|
}
|
|
}
|
|
}
|
|
|
|
// Resolve stylesheet URLs for better source info
|
|
for (const rule of matchedRules) {
|
|
if (rule.styleSheetId && rule.source !== 'inline') {
|
|
try {
|
|
const sheetMeta = await session.send('CSS.getStyleSheetText', { styleSheetId: rule.styleSheetId }).catch(() => null);
|
|
// Try to get the stylesheet header for URL info
|
|
// The styleSheetId itself is opaque, but we can try to get source URL
|
|
} catch {}
|
|
}
|
|
}
|
|
|
|
return {
|
|
selector,
|
|
tagName,
|
|
id,
|
|
classes,
|
|
attributes,
|
|
boxModel,
|
|
computedStyles,
|
|
matchedRules,
|
|
inlineStyles,
|
|
pseudoElements,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Modify a CSS property on an element.
|
|
* Uses CSS.setStyleTexts in headed mode, falls back to inline style in headless.
|
|
*/
|
|
export async function modifyStyle(
|
|
page: Page,
|
|
selector: string,
|
|
property: string,
|
|
value: string
|
|
): Promise<StyleModification> {
|
|
// Validate CSS property name
|
|
if (!/^[a-zA-Z-]+$/.test(property)) {
|
|
throw new Error(`Invalid CSS property name: ${property}. Only letters and hyphens allowed.`);
|
|
}
|
|
|
|
let oldValue = '';
|
|
let source = 'inline';
|
|
let sourceLine = 0;
|
|
let method: 'setStyleTexts' | 'inline' = 'inline';
|
|
|
|
try {
|
|
// Try CDP approach first
|
|
const session = await getOrCreateSession(page);
|
|
const result = await inspectElement(page, selector);
|
|
oldValue = result.computedStyles[property] || '';
|
|
|
|
// Find the most-specific matching rule that has this property
|
|
let targetRule: InspectorResult['matchedRules'][0] | null = null;
|
|
for (const rule of result.matchedRules) {
|
|
if (rule.userAgent) continue;
|
|
const hasProp = rule.properties.some(p => p.name === property);
|
|
if (hasProp && rule.styleSheetId && rule.range) {
|
|
targetRule = rule;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (targetRule?.styleSheetId && targetRule.range) {
|
|
// Modify via CSS.setStyleTexts
|
|
const range = targetRule.range as any;
|
|
|
|
// Get current style text
|
|
const styleText = await session.send('CSS.getStyleSheetText', {
|
|
styleSheetId: targetRule.styleSheetId,
|
|
});
|
|
|
|
// Build new style text by replacing the property value
|
|
const currentProps = targetRule.properties;
|
|
const newPropsText = currentProps
|
|
.map(p => {
|
|
if (p.name === property) {
|
|
return `${p.name}: ${value}`;
|
|
}
|
|
return `${p.name}: ${p.value}`;
|
|
})
|
|
.join('; ');
|
|
|
|
try {
|
|
await session.send('CSS.setStyleTexts', {
|
|
edits: [{
|
|
styleSheetId: targetRule.styleSheetId,
|
|
range,
|
|
text: newPropsText,
|
|
}],
|
|
});
|
|
method = 'setStyleTexts';
|
|
source = `${targetRule.source}:${targetRule.sourceLine}`;
|
|
sourceLine = targetRule.sourceLine;
|
|
} catch {
|
|
// Fall back to inline
|
|
}
|
|
}
|
|
|
|
if (method === 'inline') {
|
|
// Fallback: modify via inline style
|
|
await page.evaluate(
|
|
([sel, prop, val]) => {
|
|
const el = document.querySelector(sel);
|
|
if (!el) throw new Error(`Element not found: ${sel}`);
|
|
(el as HTMLElement).style.setProperty(prop, val);
|
|
},
|
|
[selector, property, value]
|
|
);
|
|
}
|
|
} catch (err: any) {
|
|
// Full fallback: use page.evaluate for headless
|
|
await page.evaluate(
|
|
([sel, prop, val]) => {
|
|
const el = document.querySelector(sel);
|
|
if (!el) throw new Error(`Element not found: ${sel}`);
|
|
(el as HTMLElement).style.setProperty(prop, val);
|
|
},
|
|
[selector, property, value]
|
|
);
|
|
}
|
|
|
|
const modification: StyleModification = {
|
|
selector,
|
|
property,
|
|
oldValue,
|
|
newValue: value,
|
|
source,
|
|
sourceLine,
|
|
timestamp: Date.now(),
|
|
method,
|
|
};
|
|
|
|
modificationHistory.push(modification);
|
|
return modification;
|
|
}
|
|
|
|
/**
|
|
* Undo a modification by index (or last if no index given).
|
|
*/
|
|
export async function undoModification(page: Page, index?: number): Promise<void> {
|
|
const idx = index ?? modificationHistory.length - 1;
|
|
if (idx < 0 || idx >= modificationHistory.length) {
|
|
throw new Error(`No modification at index ${idx}. History has ${modificationHistory.length} entries.`);
|
|
}
|
|
|
|
const mod = modificationHistory[idx];
|
|
|
|
if (mod.method === 'setStyleTexts') {
|
|
// Try to restore via CDP
|
|
try {
|
|
await modifyStyle(page, mod.selector, mod.property, mod.oldValue);
|
|
// Remove the undo modification from history (it's a restore, not a new mod)
|
|
modificationHistory.pop();
|
|
} catch {
|
|
// Fall back to inline restore
|
|
await page.evaluate(
|
|
([sel, prop, val]) => {
|
|
const el = document.querySelector(sel);
|
|
if (!el) return;
|
|
if (val) {
|
|
(el as HTMLElement).style.setProperty(prop, val);
|
|
} else {
|
|
(el as HTMLElement).style.removeProperty(prop);
|
|
}
|
|
},
|
|
[mod.selector, mod.property, mod.oldValue]
|
|
);
|
|
}
|
|
} else {
|
|
// Inline modification — restore or remove
|
|
await page.evaluate(
|
|
([sel, prop, val]) => {
|
|
const el = document.querySelector(sel);
|
|
if (!el) return;
|
|
if (val) {
|
|
(el as HTMLElement).style.setProperty(prop, val);
|
|
} else {
|
|
(el as HTMLElement).style.removeProperty(prop);
|
|
}
|
|
},
|
|
[mod.selector, mod.property, mod.oldValue]
|
|
);
|
|
}
|
|
|
|
modificationHistory.splice(idx, 1);
|
|
}
|
|
|
|
/**
|
|
* Get the full modification history.
|
|
*/
|
|
export function getModificationHistory(): StyleModification[] {
|
|
return [...modificationHistory];
|
|
}
|
|
|
|
/**
|
|
* Reset all modifications, restoring original values.
|
|
*/
|
|
export async function resetModifications(page: Page): Promise<void> {
|
|
// Restore in reverse order
|
|
for (let i = modificationHistory.length - 1; i >= 0; i--) {
|
|
const mod = modificationHistory[i];
|
|
try {
|
|
await page.evaluate(
|
|
([sel, prop, val]) => {
|
|
const el = document.querySelector(sel);
|
|
if (!el) return;
|
|
if (val) {
|
|
(el as HTMLElement).style.setProperty(prop, val);
|
|
} else {
|
|
(el as HTMLElement).style.removeProperty(prop);
|
|
}
|
|
},
|
|
[mod.selector, mod.property, mod.oldValue]
|
|
);
|
|
} catch {
|
|
// Best effort
|
|
}
|
|
}
|
|
modificationHistory.length = 0;
|
|
}
|
|
|
|
/**
|
|
* Format an InspectorResult for CLI text output.
|
|
*/
|
|
export function formatInspectorResult(
|
|
result: InspectorResult,
|
|
options?: { includeUA?: boolean }
|
|
): string {
|
|
const lines: string[] = [];
|
|
|
|
// Element header
|
|
const classStr = result.classes.length > 0 ? ` class="${result.classes.join(' ')}"` : '';
|
|
const idStr = result.id ? ` id="${result.id}"` : '';
|
|
lines.push(`Element: <${result.tagName}${idStr}${classStr}>`);
|
|
lines.push(`Selector: ${result.selector}`);
|
|
|
|
const w = Math.round(result.boxModel.content.width + result.boxModel.padding.left + result.boxModel.padding.right);
|
|
const h = Math.round(result.boxModel.content.height + result.boxModel.padding.top + result.boxModel.padding.bottom);
|
|
lines.push(`Dimensions: ${w} x ${h}`);
|
|
lines.push('');
|
|
|
|
// Box model
|
|
lines.push('Box Model:');
|
|
const bm = result.boxModel;
|
|
lines.push(` margin: ${Math.round(bm.margin.top)}px ${Math.round(bm.margin.right)}px ${Math.round(bm.margin.bottom)}px ${Math.round(bm.margin.left)}px`);
|
|
lines.push(` padding: ${Math.round(bm.padding.top)}px ${Math.round(bm.padding.right)}px ${Math.round(bm.padding.bottom)}px ${Math.round(bm.padding.left)}px`);
|
|
lines.push(` border: ${Math.round(bm.border.top)}px ${Math.round(bm.border.right)}px ${Math.round(bm.border.bottom)}px ${Math.round(bm.border.left)}px`);
|
|
lines.push(` content: ${Math.round(bm.content.width)} x ${Math.round(bm.content.height)}`);
|
|
lines.push('');
|
|
|
|
// Matched rules
|
|
const displayRules = options?.includeUA
|
|
? result.matchedRules
|
|
: result.matchedRules.filter(r => !r.userAgent);
|
|
|
|
lines.push(`Matched Rules (${displayRules.length}):`);
|
|
if (displayRules.length === 0) {
|
|
lines.push(' (none)');
|
|
} else {
|
|
for (const rule of displayRules) {
|
|
const propsStr = rule.properties
|
|
.filter(p => !p.overridden)
|
|
.map(p => `${p.name}: ${p.value}${p.important ? ' !important' : ''}`)
|
|
.join('; ');
|
|
if (!propsStr) continue;
|
|
const spec = `[${rule.specificity.a},${rule.specificity.b},${rule.specificity.c}]`;
|
|
lines.push(` ${rule.selector} { ${propsStr} }`);
|
|
lines.push(` -> ${rule.source}:${rule.sourceLine} ${spec}${rule.media ? ` @media ${rule.media}` : ''}`);
|
|
}
|
|
}
|
|
lines.push('');
|
|
|
|
// Inline styles
|
|
lines.push('Inline Styles:');
|
|
const inlineEntries = Object.entries(result.inlineStyles);
|
|
if (inlineEntries.length === 0) {
|
|
lines.push(' (none)');
|
|
} else {
|
|
const inlineStr = inlineEntries.map(([k, v]) => `${k}: ${v}`).join('; ');
|
|
lines.push(` ${inlineStr}`);
|
|
}
|
|
lines.push('');
|
|
|
|
// Computed styles (key properties, compact format)
|
|
lines.push('Computed (key):');
|
|
const cs = result.computedStyles;
|
|
const computedPairs: string[] = [];
|
|
for (const prop of KEY_CSS_PROPERTIES) {
|
|
if (cs[prop] !== undefined) {
|
|
computedPairs.push(`${prop}: ${cs[prop]}`);
|
|
}
|
|
}
|
|
// Group into lines of ~3 properties each
|
|
for (let i = 0; i < computedPairs.length; i += 3) {
|
|
const chunk = computedPairs.slice(i, i + 3);
|
|
lines.push(` ${chunk.join(' | ')}`);
|
|
}
|
|
|
|
// Pseudo-elements
|
|
if (result.pseudoElements.length > 0) {
|
|
lines.push('');
|
|
lines.push('Pseudo-elements:');
|
|
for (const pseudo of result.pseudoElements) {
|
|
for (const rule of pseudo.rules) {
|
|
lines.push(` ${pseudo.pseudo} ${rule.selector} { ${rule.properties} }`);
|
|
}
|
|
}
|
|
}
|
|
|
|
return lines.join('\n');
|
|
}
|
|
|
|
/**
|
|
* Detach CDP session for a page (or all pages).
|
|
*/
|
|
export function detachSession(page?: Page): void {
|
|
if (page) {
|
|
const session = cdpSessions.get(page);
|
|
if (session) {
|
|
try { session.detach().catch(() => {}); } catch {}
|
|
cdpSessions.delete(page);
|
|
initializedPages.delete(page);
|
|
}
|
|
}
|
|
// Note: WeakMap doesn't support iteration, so we can't detach all.
|
|
// Callers with specific pages should call this per-page.
|
|
}
|