feat(mcp): add helpers.dumpDom() to exec_code context

- new dom-helpers.ts exports dumpDom(page, selector?) that evaluates a
  browser-side tree walker returning a lean DomNode structure
- filters ignored tags (svg, script, path, etc.) and hidden elements
- captures role, data-testid, data-qa, data-action, data-element-id,
  id, type, name, href (relativized), checked, disabled, and text
- prunes single-child non-significant divs; discards empty non-sig nodes
- code-executor wraps dumpDom in a pageHelpers object passed as helpers
  param so user scripts can call helpers.dumpDom() or helpers.dumpDom('main')
- 29 unit tests covering all behaviours via fake DOM builder
This commit is contained in:
ars9 committed 2026-04-07 19:33:21 +03:00
1 parent ae8852d738
commit f1dadc602a
3 files changed
+499 -3

No files matched your search

+5 -3
View File
@@ -1,6 +1,7 @@
import { BadRequestException, Injectable, InternalServerErrorException, Logger } from '@nestjs/common';
import { parse } from 'acorn';
import type { Page, BrowserContext } from 'playwright';
import { dumpDom } from './dom-helpers';
export interface ExecResult {
result: unknown;
@@ -15,7 +16,7 @@ export class CodeExecutorService {
* to parse it with acorn. Throws BadRequestException if it is not valid JS.
*/
validate(code: string): void {
const wrapped = `async function __validate__(page, context) { ${code} }`;
const wrapped = `async function __validate__(page, context, helpers) { ${code} }`;
try {
parse(wrapped, { ecmaVersion: 2022 });
} catch (err) {
@@ -29,10 +30,11 @@ export class CodeExecutorService {
*/
async execute(page: Page, context: BrowserContext, code: string): Promise<ExecResult> {
try {
const pageHelpers = { dumpDom: (selector?: string) => dumpDom(page, selector) };
// eslint-disable-next-line no-new-func
const fn = new Function('page', 'context', `return (async (page, context) => { ${code} })(page, context)`);
const fn = new Function('page', 'context', 'helpers', `return (async (page, context, helpers) => { ${code} })(page, context, helpers)`);
this.logger.debug('Executing user code');
const result = await fn(page, context);
const result = await fn(page, context, pageHelpers);
return { result };
} catch (err) {
throw new InternalServerErrorException(`Code execution failed: ${(err as Error).message}`, { cause: err });
+152
View File
@@ -0,0 +1,152 @@
import type { Page } from 'playwright';
export interface DomNode {
tag: string;
role?: string;
testid?: string;
qa?: string;
action?: string;
elementId?: string;
id?: string;
type?: string;
name?: string;
text?: string;
href?: string;
checked?: boolean;
disabled?: boolean;
children: DomNode[];
truncated?: boolean;
}
/**
* Dumps a logical component tree of the live DOM scoped to `rootSelector`.
* Filters out decorative/layout noise — keeps only structural landmarks,
* interactive elements, and elements with semantic attributes
* (role, data-testid, data-qa, data-action, data-element-id).
*
* Useful for debugging Playwright selectors without screenshotting.
*/
export async function dumpDom(page: Page, rootSelector = 'body'): Promise<DomNode> {
return page.evaluate(
([sel, maxDepth]) => {
const root = document.querySelector(sel as string);
if (!root) return { tag: 'ERROR', text: `selector not found: ${sel}`, children: [] };
const STRUCTURAL_TAGS = new Set([
'BODY', 'MAIN', 'HEADER', 'FOOTER', 'NAV', 'ASIDE', 'SECTION',
'FORM', 'DIALOG', 'DETAILS', 'SUMMARY', 'TABLE', 'THEAD', 'TBODY',
'TR', 'FIELDSET', 'LEGEND',
]);
const INTERACTIVE_TAGS = new Set([
'A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA', 'LABEL',
'TH', 'TD',
]);
const IGNORED_TAGS = new Set(['SCRIPT', 'STYLE', 'SVG', 'PATH', 'DEFS', 'USE', 'CIRCLE', 'RECT', 'POLYGON', 'POLYLINE', 'LINE', 'ELLIPSE', 'G', 'CLIPPATH', 'IMAGE']);
function trimText(el: Element): string | undefined {
const t = (el as HTMLElement).innerText?.trim() ?? el.textContent?.trim() ?? '';
// Only include if short enough to be meaningful, not a dump of all child text
const ownText = Array.from(el.childNodes)
.filter(n => n.nodeType === Node.TEXT_NODE)
.map(n => n.textContent?.trim() ?? '')
.filter(Boolean)
.join(' ');
const candidate = ownText || t;
return candidate.length > 0 ? candidate.substring(0, 80) : undefined;
}
function isVisible(el: Element): boolean {
const s = window.getComputedStyle(el);
return s.display !== 'none' && s.visibility !== 'hidden' && (el as HTMLElement).offsetParent !== null;
}
function isSignificant(el: Element): boolean {
if (STRUCTURAL_TAGS.has(el.tagName)) return true;
if (INTERACTIVE_TAGS.has(el.tagName)) return true;
if (el.getAttribute('role')) return true;
if (el.getAttribute('data-testid')) return true;
if (el.getAttribute('data-qa')) return true;
if (el.getAttribute('data-action')) return true;
if (el.getAttribute('data-element-id')) return true;
return false;
}
function build(el: Element, depth: number): DomNode | null {
if (IGNORED_TAGS.has(el.tagName)) return null;
if (!isVisible(el)) return null;
const significant = isSignificant(el);
const childResults: DomNode[] = [];
if (depth < (maxDepth as number)) {
for (const child of Array.from(el.children)) {
const node = build(child, depth + 1);
if (node) childResults.push(node);
}
} else if (el.children.length > 0) {
return significant
? { tag: el.tagName.toLowerCase(), children: [], truncated: true }
: null;
}
// If not significant and no meaningful children, discard
if (!significant && childResults.length === 0) return null;
// If not significant but has exactly one child, pass through (unwrap)
if (!significant && childResults.length === 1) return childResults[0];
// If not significant but has children, keep as anonymous group only if > 1 child
if (!significant) return { tag: el.tagName.toLowerCase(), children: childResults };
const node: DomNode = {
tag: el.tagName.toLowerCase(),
children: childResults,
};
const role = el.getAttribute('role');
if (role) node.role = role;
const testid = el.getAttribute('data-testid');
if (testid) node.testid = testid;
const qa = el.getAttribute('data-qa');
if (qa) node.qa = qa;
const action = el.getAttribute('data-action');
if (action) node.action = action;
const elementId = el.getAttribute('data-element-id');
if (elementId) node.elementId = elementId;
const id = el.id;
if (id) node.id = id;
const type = (el as HTMLInputElement).type;
if (type && type !== 'submit' && el.tagName !== 'BUTTON') node.type = type;
const name = (el as HTMLInputElement).name;
if (name) node.name = name;
const href = (el as HTMLAnchorElement).href;
if (href && el.tagName === 'A') node.href = href.replace(window.location.origin, '');
if ('checked' in el) node.checked = (el as HTMLInputElement).checked;
if ((el as HTMLButtonElement).disabled) node.disabled = true;
const text = trimText(el);
if (text) node.text = text;
return node;
}
const result = build(root, 0);
return result ?? { tag: 'empty', children: [] };
},
[rootSelector, 12] as [string, number],
);
}
export const helpers = { dumpDom };
export type Helpers = typeof helpers;