@probolabs/playwright 1.4.0 → 1.5.0-rc.3

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.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- const highlighterCode = "(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ProboLabs = {}));\n})(this, (function (exports) { 'use strict';\n\n /**\n * Element tag constants for different types of interactive elements\n */\n const ElementTag = {\n CLICKABLE: \"CLICKABLE\",\n FILLABLE: \"FILLABLE\",\n SELECTABLE: \"SELECTABLE\",\n NON_INTERACTIVE_ELEMENT: 'NON_INTERACTIVE_ELEMENT',\n };\n\n var ApplyAIStatus;\n (function (ApplyAIStatus) {\n ApplyAIStatus[\"PREPARE_START\"] = \"PREPARE_START\";\n ApplyAIStatus[\"PREPARE_SUCCESS\"] = \"PREPARE_SUCCESS\";\n ApplyAIStatus[\"PREPARE_ERROR\"] = \"PREPARE_ERROR\";\n ApplyAIStatus[\"SEND_START\"] = \"SEND_START\";\n ApplyAIStatus[\"SEND_SUCCESS\"] = \"SEND_SUCCESS\";\n ApplyAIStatus[\"SEND_ERROR\"] = \"SEND_ERROR\";\n ApplyAIStatus[\"APPLY_AI_ERROR\"] = \"APPLY_AI_ERROR\";\n ApplyAIStatus[\"APPLY_AI_CANCELLED\"] = \"APPLY_AI_CANCELLED\";\n ApplyAIStatus[\"SUMMARY_COMPLETED\"] = \"SUMMARY_COMPLETED\";\n ApplyAIStatus[\"SUMMARY_ERROR\"] = \"SUMMARY_ERROR\";\n })(ApplyAIStatus || (ApplyAIStatus = {}));\n var ReplayStatus;\n (function (ReplayStatus) {\n ReplayStatus[\"REPLAY_START\"] = \"REPLAY_START\";\n ReplayStatus[\"REPLAY_SUCCESS\"] = \"REPLAY_SUCCESS\";\n ReplayStatus[\"REPLAY_ERROR\"] = \"REPLAY_ERROR\";\n ReplayStatus[\"REPLAY_CANCELLED\"] = \"REPLAY_CANCELLED\";\n })(ReplayStatus || (ReplayStatus = {}));\n\n // Action constants\n var PlaywrightAction;\n (function (PlaywrightAction) {\n PlaywrightAction[\"VISIT_BASE_URL\"] = \"VISIT_BASE_URL\";\n PlaywrightAction[\"VISIT_URL\"] = \"VISIT_URL\";\n PlaywrightAction[\"CLICK\"] = \"CLICK\";\n PlaywrightAction[\"FILL_IN\"] = \"FILL_IN\";\n PlaywrightAction[\"SELECT_DROPDOWN\"] = \"SELECT_DROPDOWN\";\n PlaywrightAction[\"SELECT_MULTIPLE_DROPDOWN\"] = \"SELECT_MULTIPLE_DROPDOWN\";\n PlaywrightAction[\"CHECK_CHECKBOX\"] = \"CHECK_CHECKBOX\";\n PlaywrightAction[\"SELECT_RADIO\"] = \"SELECT_RADIO\";\n PlaywrightAction[\"TOGGLE_SWITCH\"] = \"TOGGLE_SWITCH\";\n PlaywrightAction[\"SET_SLIDER\"] = \"SET_SLIDER\";\n PlaywrightAction[\"TYPE_KEYS\"] = \"TYPE_KEYS\";\n PlaywrightAction[\"HOVER\"] = \"HOVER\";\n PlaywrightAction[\"ASSERT_EXACT_VALUE\"] = \"ASSERT_EXACT_VALUE\";\n PlaywrightAction[\"ASSERT_CONTAINS_VALUE\"] = \"ASSERT_CONTAINS_VALUE\";\n PlaywrightAction[\"ASSERT_URL\"] = \"ASSERT_URL\";\n PlaywrightAction[\"SCROLL_TO_ELEMENT\"] = \"SCROLL_TO_ELEMENT\";\n PlaywrightAction[\"EXTRACT_VALUE\"] = \"EXTRACT_VALUE\";\n PlaywrightAction[\"ASK_AI\"] = \"ASK_AI\";\n PlaywrightAction[\"EXECUTE_SCRIPT\"] = \"EXECUTE_SCRIPT\";\n PlaywrightAction[\"UPLOAD_FILES\"] = \"UPLOAD_FILES\";\n PlaywrightAction[\"WAIT_FOR\"] = \"WAIT_FOR\";\n PlaywrightAction[\"WAIT_FOR_OTP\"] = \"WAIT_FOR_OTP\";\n PlaywrightAction[\"GEN_TOTP\"] = \"GEN_TOTP\";\n // Sequence marker actions (not real interactions, used only for grouping)\n PlaywrightAction[\"SEQUENCE_START\"] = \"SEQUENCE_START\";\n PlaywrightAction[\"SEQUENCE_END\"] = \"SEQUENCE_END\";\n })(PlaywrightAction || (PlaywrightAction = {}));\n\n /**\n * Checks if any string in the array matches the given regular expression pattern.\n *\n * @param array - Array of strings to test.\n * @param pattern - Regular expression to test against each string.\n * @returns true if at least one string matches the pattern, false otherwise.\n */\n function testArray(array, pattern) {\n return array.some(item => pattern.test(item));\n }\n /**\n * Determines if an element is clickable\n *\n * @param element The DOM element to check\n * @returns boolean indicating if the element is fillable\n */\n function isClickableElement(element) {\n if (!element)\n return false;\n let depth = 0;\n while (depth < 5 && element && element.nodeType === Node.ELEMENT_NODE) {\n if (isClickableElementHelper(element) === IsClickable.YES)\n return true;\n if (isClickableElementHelper(element) === IsClickable.NO)\n return false;\n // if maybe, continue searching up to 5 levels up the DOM tree\n element = element.parentNode;\n depth++;\n }\n return false;\n }\n // clickable element detection result\n var IsClickable;\n (function (IsClickable) {\n IsClickable[\"YES\"] = \"YES\";\n IsClickable[\"NO\"] = \"NO\";\n IsClickable[\"MAYBE\"] = \"MAYBE\";\n })(IsClickable || (IsClickable = {}));\n function isClickableElementHelper(element) {\n var _a, _b;\n if (!element)\n return IsClickable.NO;\n //check for tag name\n const tagName = element.tagName.toLowerCase();\n const clickableTags = [\n 'a', 'button',\n ];\n if (clickableTags.includes(tagName))\n return IsClickable.YES;\n //check for clickable <input>\n const inputType = (_a = element.type) === null || _a === void 0 ? void 0 : _a.toLowerCase();\n const clickableTypes = [\n 'button', 'submit', 'reset', 'checkbox', 'radio',\n ];\n const ariaAutocompleteValues = [\n 'list', 'both',\n ];\n if (tagName === 'input') {\n if (clickableTypes.includes(inputType) || ariaAutocompleteValues.includes((_b = element.getAttribute('aria-autocomplete')) !== null && _b !== void 0 ? _b : ''))\n return IsClickable.YES;\n if (['date', 'number', 'range'].includes(inputType))\n return IsClickable.NO; //don't record the click as a change event will be generated for elements that generate an input change event\n }\n // check for cursor type\n const style = window.getComputedStyle(element);\n if (style.cursor === 'pointer')\n return IsClickable.YES;\n // check for attributes\n const clickableRoles = [\n 'button', 'combobox', 'listbox', 'dropdown', 'option', 'menu', 'menuitem',\n 'navigation', 'checkbox', 'switch', 'toggle', 'slider', 'textbox', 'listitem',\n 'presentation',\n ];\n const ariaPopupValues = [\n 'true', 'listbox', 'menu',\n ];\n if (element.hasAttribute('onclick') ||\n clickableRoles.includes(element.getAttribute('role') || '') ||\n ariaPopupValues.includes(element.getAttribute('aria-haspopup') || ''))\n return IsClickable.YES;\n // check for tabindex (means element is focusable and therefore clickable)\n if (parseInt(element.getAttribute('tabindex') || '-1') >= 0)\n return IsClickable.YES;\n // extract class names\n const classNames = Array.from(element.classList);\n // check for checkbox/radio-like class name - TODO: check if can be removed\n const checkboxPattern = /checkbox|switch|toggle|slider/i;\n if (testArray(classNames, checkboxPattern))\n return IsClickable.YES;\n // check for Material UI class names\n const muiClickableClassPattern = /MuiButton|MuiIconButton|MuiChip|MuiMenuItem|MuiListItem|MuiInputBase|MuiOutlinedInput|MuiSelect|MuiAutocomplete|MuiToggleButton|MuiBackdrop-root|MuiBackdrop-invisible/;\n if (testArray(classNames, muiClickableClassPattern))\n return IsClickable.YES;\n // check for SalesForce class names\n const sfClassPattern = /slds-button|slds-dropdown|slds-combobox|slds-picklist|slds-tabs|slds-pill|slds-action|slds-row-action|slds-context-bar|slds-input|slds-rich-text-area|slds-radio|slds-checkbox|slds-toggle|slds-link|slds-accordion|slds-tree/;\n if (testArray(classNames, sfClassPattern))\n return IsClickable.YES;\n // check for chart dots\n const chartClickableClassPattern = /recharts-dot/;\n if (testArray(classNames, chartClickableClassPattern))\n return IsClickable.YES;\n // check for React component classes\n const reactClickableClassPattern = /react-select|ant-select|rc-select|react-dropdown|react-autocomplete|react-datepicker|react-modal|react-tooltip|react-popover|react-menu|react-tabs|react-accordion|react-collapse|react-toggle|react-switch|react-checkbox|react-radio|react-button|react-link|react-card|react-list-item|react-menu-item|react-option|react-tab|react-panel|react-drawer|react-sidebar|react-nav|react-breadcrumb|react-pagination|react-stepper|react-wizard|react-carousel|react-slider|react-range|react-progress|react-badge|react-chip|react-tag|react-avatar|react-icon|react-fab|react-speed-dial|react-floating|react-sticky|react-affix|react-backdrop|react-overlay|react-portal|react-transition|react-animate|react-spring|react-framer|react-gesture|react-drag|react-drop|react-sortable|react-resizable|react-split|react-grid|react-table|react-datagrid|react-tree|react-treeview|react-file|react-upload|react-cropper|react-image|react-gallery|react-lightbox|react-player|react-video|react-audio|react-chart|react-graph|react-diagram|react-flow|react-d3|react-plotly|react-vega|react-vis|react-nivo|react-recharts|react-victory|react-echarts|react-highcharts|react-google-charts|react-fusioncharts|react-apexcharts|react-chartjs|react-chartkick|react-sparklines|react-trend|react-smooth|react-animated|react-lottie|react-spring|react-framer-motion|react-pose|react-motion|react-transition-group|react-router|react-navigation/i;\n if (testArray(classNames, reactClickableClassPattern))\n return IsClickable.YES;\n //check for cloudinary class names\n const cloudinaryClickableClassPattern = /cld-combobox|cld-upload-button|cld-controls|cld-player|cld-tab|cld-menu-item|cld-close|cld-play|cld-pause|cld-fullscreen|cld-browse|cld-cancel|cld-retry/;\n if (testArray(classNames, cloudinaryClickableClassPattern))\n return IsClickable.YES;\n return IsClickable.MAYBE;\n }\n function getParentNode(element) {\n if (!element || element.nodeType !== Node.ELEMENT_NODE)\n return null;\n let parent = null;\n // SF is using slots and shadow DOM heavily\n // However, there might be slots in the light DOM which shouldn't be traversed\n if (element.assignedSlot && element.getRootNode() instanceof ShadowRoot)\n parent = element.assignedSlot;\n else\n parent = element.parentNode;\n // Check if we're at a shadow root\n if (parent && parent.nodeType !== Node.ELEMENT_NODE && parent.getRootNode() instanceof ShadowRoot)\n parent = parent.getRootNode().host;\n return parent;\n }\n function getElementDepth(element) {\n let depth = 0;\n let currentElement = element;\n while ((currentElement === null || currentElement === void 0 ? void 0 : currentElement.nodeType) === Node.ELEMENT_NODE) {\n depth++;\n currentElement = getParentNode(currentElement);\n }\n return depth;\n }\n\n // WebSocketsMessageType enum for WebSocket and event message types shared across the app\n var WebSocketsMessageType;\n (function (WebSocketsMessageType) {\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_PREPARE_START\"] = \"INTERACTION_APPLY_AI_PREPARE_START\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_PREPARE_SUCCESS\"] = \"INTERACTION_APPLY_AI_PREPARE_SUCCESS\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_PREPARE_ERROR\"] = \"INTERACTION_APPLY_AI_PREPARE_ERROR\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_SEND_TO_LLM_START\"] = \"INTERACTION_APPLY_AI_SEND_TO_LLM_START\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_SEND_TO_LLM_SUCCESS\"] = \"INTERACTION_APPLY_AI_SEND_TO_LLM_SUCCESS\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_SEND_TO_LLM_ERROR\"] = \"INTERACTION_APPLY_AI_SEND_TO_LLM_ERROR\";\n WebSocketsMessageType[\"INTERACTION_REPLAY_START\"] = \"INTERACTION_REPLAY_START\";\n WebSocketsMessageType[\"INTERACTION_REPLAY_SUCCESS\"] = \"INTERACTION_REPLAY_SUCCESS\";\n WebSocketsMessageType[\"INTERACTION_REPLAY_ERROR\"] = \"INTERACTION_REPLAY_ERROR\";\n WebSocketsMessageType[\"INTERACTION_REPLAY_CANCELLED\"] = \"INTERACTION_REPLAY_CANCELLED\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_CANCELLED\"] = \"INTERACTION_APPLY_AI_CANCELLED\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_ERROR\"] = \"INTERACTION_APPLY_AI_ERROR\";\n WebSocketsMessageType[\"INTERACTION_STEP_CREATED\"] = \"INTERACTION_STEP_CREATED\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_SUMMARY_COMPLETED\"] = \"INTERACTION_APPLY_AI_SUMMARY_COMPLETED\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_SUMMARY_ERROR\"] = \"INTERACTION_APPLY_AI_SUMMARY_ERROR\";\n WebSocketsMessageType[\"OTP_RETRIEVED\"] = \"OTP_RETRIEVED\";\n WebSocketsMessageType[\"TEST_SUITE_RUN_START\"] = \"TEST_SUITE_RUN_START\";\n WebSocketsMessageType[\"TEST_SUITE_RUN_LOG\"] = \"TEST_SUITE_RUN_LOG\";\n WebSocketsMessageType[\"TEST_SUITE_RUN_COMPLETE\"] = \"TEST_SUITE_RUN_COMPLETE\";\n WebSocketsMessageType[\"TEST_SUITE_RUN_ERROR\"] = \"TEST_SUITE_RUN_ERROR\";\n WebSocketsMessageType[\"TEST_SUITE_RUN_REPORTER_EVENT\"] = \"TEST_SUITE_RUN_REPORTER_EVENT\";\n })(WebSocketsMessageType || (WebSocketsMessageType = {}));\n\n /**\n * Logging levels for Probo\n */\n var ProboLogLevel;\n (function (ProboLogLevel) {\n ProboLogLevel[\"DEBUG\"] = \"DEBUG\";\n ProboLogLevel[\"INFO\"] = \"INFO\";\n ProboLogLevel[\"LOG\"] = \"LOG\";\n ProboLogLevel[\"WARN\"] = \"WARN\";\n ProboLogLevel[\"ERROR\"] = \"ERROR\";\n })(ProboLogLevel || (ProboLogLevel = {}));\n const logLevelOrder = {\n [ProboLogLevel.DEBUG]: 0,\n [ProboLogLevel.INFO]: 1,\n [ProboLogLevel.LOG]: 2,\n [ProboLogLevel.WARN]: 3,\n [ProboLogLevel.ERROR]: 4,\n };\n class ProboLogger {\n constructor(prefix, level = ProboLogLevel.INFO) {\n this.prefix = prefix;\n this.level = level;\n }\n setLogLevel(level) {\n console.log(`[${this.prefix}] Setting log level to: ${level} (was: ${this.level})`);\n this.level = level;\n }\n shouldLog(level) {\n return logLevelOrder[level] >= logLevelOrder[this.level];\n }\n preamble(level) {\n const now = new Date();\n const hours = String(now.getHours()).padStart(2, '0');\n const minutes = String(now.getMinutes()).padStart(2, '0');\n const seconds = String(now.getSeconds()).padStart(2, '0');\n const milliseconds = String(now.getMilliseconds()).padStart(3, '0');\n return `[${hours}:${minutes}:${seconds}.${milliseconds}] [${this.prefix}] [${level}]`;\n }\n debug(...args) { if (this.shouldLog(ProboLogLevel.DEBUG))\n console.debug(this.preamble(ProboLogLevel.DEBUG), ...args); }\n info(...args) { if (this.shouldLog(ProboLogLevel.INFO))\n console.info(this.preamble(ProboLogLevel.INFO), ...args); }\n log(...args) { if (this.shouldLog(ProboLogLevel.LOG))\n console.log(this.preamble(ProboLogLevel.LOG), ...args); }\n warn(...args) { if (this.shouldLog(ProboLogLevel.WARN))\n console.warn(this.preamble(ProboLogLevel.WARN), ...args); }\n error(...args) { if (this.shouldLog(ProboLogLevel.ERROR))\n console.error(this.preamble(ProboLogLevel.ERROR), ...args); }\n }\n function doubleQuoteString(str) {\n if (!str)\n return '';\n return `\"${str.replace(/\"/g, '\\\\\"')}\"`;\n }\n\n new ProboLogger('apiclient');\n\n /**\n * Available AI models for LLM operations\n */\n var AIModel;\n (function (AIModel) {\n AIModel[\"AZURE_GPT4\"] = \"azure-gpt4\";\n AIModel[\"AZURE_GPT4_MINI\"] = \"azure-gpt4-mini\";\n AIModel[\"GEMINI_1_5_FLASH\"] = \"gemini-1.5-flash\";\n AIModel[\"GEMINI_2_5_FLASH\"] = \"gemini-2.5-flash\";\n AIModel[\"GPT4\"] = \"gpt4\";\n AIModel[\"GPT4_MINI\"] = \"gpt4-mini\";\n AIModel[\"CLAUDE_3_5\"] = \"claude-3.5\";\n AIModel[\"CLAUDE_SONNET_4_5\"] = \"claude-sonnet-4.5\";\n AIModel[\"CLAUDE_HAIKU_4_5\"] = \"claude-haiku-4.5\";\n AIModel[\"CLAUDE_OPUS_4_1\"] = \"claude-opus-4.1\";\n AIModel[\"GROK_2\"] = \"grok-2\";\n AIModel[\"LLAMA_4_SCOUT\"] = \"llama-4-scout\";\n AIModel[\"DEEPSEEK_V3\"] = \"deepseek-v3\";\n })(AIModel || (AIModel = {}));\n\n const highlighterLogger = new ProboLogger('highlighter');\n\n // Get text content of an element (recursively including child elements)\n function getElementText(element) {\n if (!element) return '';\n return element.textContent || '';\n }\n\n // Get placeholder text of an element\n function getElementPlaceholder(element) {\n if (!element) return '';\n return element.placeholder || '';\n }\n\n // Get CSS selector of an element (not recursively, just for a single element)\n function getElementCssSelector(element) {\n if (!(element instanceof Element)) return '';\n \n const tag = element.tagName.toLowerCase();\n let selector = tag;\n \n // Find nth-of-type for elements without ID\n let nth = 1;\n let sibling = element.previousElementSibling;\n while (sibling) {\n if (sibling.nodeName.toLowerCase() === tag) nth++;\n sibling = sibling.previousElementSibling;\n }\n if (nth > 1 || element.nextElementSibling) selector += `:nth-of-type(${nth})`;\n \n return selector;\n }\n\n // Helper function to check if element is a form control\n function isFormControl(elementInfo) {\n return /^(input|select|textarea|button|label)$/i.test(elementInfo.tag);\n }\n\n // Helper function to check if element is a dropdown item\n const isDropdownItem = (elementInfo) => {\n const dropdownPatterns = [\n /dropdown[-_]?item/i, // matches: dropdown-item, dropdownitem, dropdown_item\n /menu[-_]?item/i, // matches: menu-item, menuitem, menu_item\n /dropdown[-_]?link/i, // matches: dropdown-link, dropdownlink, dropdown_link\n /list[-_]?item/i, // matches: list-item, listitem, list_item\n /select[-_]?item/i, // matches: select-item, selectitem, select_item \n ];\n\n const rolePatterns = [\n /menu[-_]?item/i, // matches: menuitem, menu-item\n /option/i, // matches: option\n /list[-_]?item/i, // matches: listitem, list-item\n /tree[-_]?item/i // matches: treeitem, tree-item\n ];\n\n const hasMatchingClass = elementInfo.element.className && \n dropdownPatterns.some(pattern => \n pattern.test(elementInfo.element.className)\n );\n\n const hasMatchingRole = elementInfo.element.getAttribute('role') && \n rolePatterns.some(pattern => \n pattern.test(elementInfo.element.getAttribute('role'))\n );\n\n return hasMatchingClass || hasMatchingRole;\n };\n\n /**\n * Element Query Utilities\n */\n\n function getAllDocumentElementsIncludingShadow(selectors, root = document) {\n const elements = Array.from(root.querySelectorAll(selectors));\n\n root.querySelectorAll('*').forEach(el => {\n if (el.shadowRoot) {\n elements.push(...getAllDocumentElementsIncludingShadow(selectors, el.shadowRoot));\n }\n });\n return elements;\n }\n\n function getAllFrames(root = document) {\n const result = [root];\n const frames = getAllDocumentElementsIncludingShadow('frame, iframe', root); \n frames.forEach(frame => {\n try {\n const frameDocument = frame.contentDocument || frame.contentWindow.document;\n if (frameDocument) {\n result.push(frameDocument);\n }\n } catch (e) {\n // Skip cross-origin frames\n highlighterLogger.warn('Could not access frame content:', e.message);\n }\n });\n\n return result;\n }\n\n function getAllElementsIncludingShadow(selectors, root = document) {\n const elements = [];\n\n getAllFrames(root).forEach(doc => {\n elements.push(...getAllDocumentElementsIncludingShadow(selectors, doc));\n });\n\n return elements;\n }\n\n /**\n * Finds the first element matching a CSS selector, traversing Shadow DOM if necessary\n * @param {string} selector - CSS selector to search for\n * @param {Element} [root=document] - Root element to start searching from\n * @returns {Element|null} - The first matching element or null if not found\n */\n function robustQuerySelector(selector, root = document, all = false) {\n // First try to find in light DOM\n let elements = all ? root.querySelectorAll(selector) : root.querySelector(selector);\n if (elements) return elements;\n \n // Get all shadow roots\n const shadowElements = Array.from(root.querySelectorAll('*'))\n .filter(el => el.shadowRoot);\n \n // Search through each shadow root until we find a match\n for (const el of shadowElements) {\n elements = robustQuerySelector(selector, el.shadowRoot, all);\n if (elements) return elements;\n }\n \n return all ? [] : null;\n }\n\n\n function isDecendent(parent, child) {\n let element = child;\n while (element && element !== parent && element.nodeType === Node.ELEMENT_NODE) { \n element = getParentNode(element); \n }\n return element === parent;\n }\n\n function generateXPath(element) {\n return '/'+extractElementPath(element).map(item => `${item.tagName}${item.onlyChild ? '' : `[${item.index}]`}`).join('/');\n }\n\n function generateCssPath(element) {\n return extractElementPath(element).map(item => `${item.tagName}:nth-of-type(${item.index})`).join(' > ');\n }\n\n // unified path generation for xpath and css selector\n function extractElementPath(element) {\n if (!element) {\n highlighterLogger.error('ERROR: No element provided to generatePath');\n return [];\n }\n const path = [];\n // traversing up the DOM tree\n while (element && element.nodeType === Node.ELEMENT_NODE) { \n let tagName = element.nodeName.toLowerCase();\n \n let sibling = element;\n let index = 1;\n \n while (sibling = sibling.previousElementSibling) {\n if (sibling.nodeName.toLowerCase() === tagName) index++;\n }\n sibling = element;\n \n let onlyChild = (index === 1);\n while (onlyChild && (sibling = sibling.nextElementSibling)) {\n if (sibling.nodeName.toLowerCase() === tagName) onlyChild = false;\n }\n \n // add a tuple with tagName, index (nth), and onlyChild \n path.unshift({\n tagName: tagName,\n index: index,\n onlyChild: onlyChild \n }); \n\n element = getParentNode(element);\n }\n \n return path;\n }\n\n function cleanHTML(rawHTML) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(rawHTML, \"text/html\");\n\n function cleanElement(element) {\n const allowedAttributes = new Set([\n \"role\",\n \"type\",\n \"class\",\n \"href\",\n \"alt\",\n \"title\",\n \"readonly\",\n \"checked\",\n \"enabled\",\n \"disabled\",\n ]);\n\n [...element.attributes].forEach(attr => {\n const name = attr.name.toLowerCase();\n const value = attr.value;\n\n const isTestAttribute = /^(testid|test-id|data-test-id)$/.test(name);\n const isDataAttribute = name.startsWith(\"data-\") && value;\n const isBooleanAttribute = [\"readonly\", \"checked\", \"enabled\", \"disabled\"].includes(name);\n\n if (!allowedAttributes.has(name) && !isDataAttribute && !isTestAttribute && !isBooleanAttribute) {\n element.removeAttribute(name);\n }\n });\n\n // Handle SVG content - more aggressive replacement\n if (element.tagName.toLowerCase() === \"svg\") {\n // Remove all attributes except class and role\n [...element.attributes].forEach(attr => {\n const name = attr.name.toLowerCase();\n if (name !== \"class\" && name !== \"role\") {\n element.removeAttribute(name);\n }\n });\n element.innerHTML = \"CONTENT REMOVED\";\n } else {\n // Recursively clean child elements\n Array.from(element.children).forEach(cleanElement);\n }\n\n // Only remove empty elements that aren't semantic or icon elements\n const keepEmptyElements = ['i', 'span', 'svg', 'button', 'input'];\n if (!keepEmptyElements.includes(element.tagName.toLowerCase()) && \n !element.children.length && \n !element.textContent.trim()) {\n element.remove();\n }\n }\n\n // Process all elements in the document body\n Array.from(doc.body.children).forEach(cleanElement);\n return doc.body.innerHTML;\n }\n\n function getContainingIFrame(element) {\n // If not in an iframe, return null\n if (element.ownerDocument.defaultView === window.top) {\n return null;\n }\n \n // Try to find the iframe in the parent document that contains our element\n try {\n const parentDocument = element.ownerDocument.defaultView.parent.document;\n const iframes = parentDocument.querySelectorAll('iframe');\n \n for (const iframe of iframes) {\n if (iframe.contentWindow === element.ownerDocument.defaultView) {\n return iframe;\n }\n }\n } catch (e) {\n // Cross-origin restriction\n return \"Cross-origin iframe - cannot access details\";\n }\n \n return null;\n }\n\n function getAriaLabelledByText(elementInfo, includeHidden=true) {\n if (!elementInfo.element.hasAttribute('aria-labelledby')) return '';\n\n const ids = elementInfo.element.getAttribute('aria-labelledby').split(/\\s+/);\n let labelText = '';\n\n //locate root (document or iFrame document if element is contained in an iframe)\n let root = document;\n if (elementInfo.iframe_selector) { \n const frames = getAllDocumentElementsIncludingShadow('iframe', document);\n \n // Iterate over all frames and compare their CSS selectors\n for (const frame of frames) {\n const selector = generateCssPath(frame);\n if (selector === elementInfo.iframe_selector) {\n root = frame.contentDocument || frame.contentWindow.document; \n break;\n }\n } \n }\n\n ids.forEach(id => {\n const el = robustQuerySelector(`#${CSS.escape(id)}`, root);\n if (el) {\n if (includeHidden || el.offsetParent !== null || getComputedStyle(el).display !== 'none') {\n labelText += el.textContent.trim() + ' ';\n }\n }\n });\n\n return labelText.trim();\n }\n\n\n\n const filterZeroDimensions = (elementInfo) => {\n const rect = elementInfo.bounding_box;\n //single pixel elements are typically faux controls and should be filtered too\n const hasSize = rect.width > 1 && rect.height > 1;\n const style = window.getComputedStyle(elementInfo.element);\n const isVisible = style.display !== 'none' && style.visibility !== 'hidden';\n \n if (!hasSize || !isVisible) {\n \n return false;\n }\n return true;\n };\n\n function filterNestedElements(nonZeroElements, parentCandidates, shouldKeepNestedElementFn) {\n /**\n * Filter elements based on parent/child relationships.\n * @param {Array} nonZeroElements - Elements sorted by depth (parents first)\n * @param {Set} parentCandidates - Set of all candidate parent CSS selectors (all nonZeroElements)\n * @param {Function} shouldKeepNestedElementFn - Function(element_info, parentPath, parentElementInfo) => boolean\n * @returns {Array} Filtered elements\n */\n return nonZeroElements.filter(element_info => {\n const parent = findClosestParent(parentCandidates, element_info);\n \n if (parent == null) {\n // No parent found, keep element\n return true;\n }\n \n // Find parent element_info\n const parentElementInfo = nonZeroElements.find(e => e.css_selector === parent);\n \n // Use custom function to determine if we should keep nested element\n return shouldKeepNestedElementFn(element_info, parent, parentElementInfo);\n });\n }\n\n function getDirectHandlers(element) {\n /**\n * Get direct handlers for an element (no bubbling check).\n * Returns array of handler objects.\n */\n const handlers = [];\n \n // Check onclick\n if (element.hasAttribute('onclick') || element.onclick) {\n handlers.push({\n type: 'onclick',\n source: element.hasAttribute('onclick') ? 'attribute' : 'property',\n value: element.getAttribute('onclick') || 'function'\n });\n }\n \n // Check React Fiber\n const reactKey = Object.keys(element).find(key => \n key.startsWith('__reactFiber') || key.startsWith('__reactInternalInstance')\n );\n if (reactKey) {\n const fiber = element[reactKey];\n if (fiber?.memoizedProps?.onClick || fiber?.pendingProps?.onClick) {\n handlers.push({\n type: 'react-onClick',\n source: 'react-fiber',\n hasMemoized: !!fiber?.memoizedProps?.onClick,\n hasPending: !!fiber?.pendingProps?.onClick\n });\n }\n }\n \n return handlers;\n }\n\n function getElementHandlersWithBubbling(element, depth = 0) {\n /**\n * Get handler info including bubbling (recursive DOM traversal).\n * Uses actual DOM relationships (parentElement) instead of CSS selector parsing.\n * Cursor uses getComputedStyle() which already includes inheritance.\n * @param {HTMLElement} element - The element to check\n * @param {number} depth - Recursion depth (safety limit)\n */\n // Safety check: null/undefined element\n if (!element) {\n return { handlers: [], cursorPointer: false, handlerSource: 'none' };\n }\n \n // Safety check: prevent infinite recursion (circular parent references)\n if (depth > 100) {\n throw new Error(`Recursion depth limit exceeded (${depth}) in getElementHandlersWithBubbling. Possible circular parent reference. Element: ${element.tagName || 'unknown'}`);\n }\n \n const directHandlers = getDirectHandlers(element);\n \n // If element has direct handlers, return them\n if (directHandlers.length > 0) {\n // Cursor: getComputedStyle already includes inheritance!\n let cursorPointer = false;\n try {\n const style = window.getComputedStyle(element);\n cursorPointer = style.cursor === 'pointer';\n } catch (e) {\n // getComputedStyle can fail in edge cases (e.g., detached elements)\n // Default to false\n }\n \n return {\n handlers: directHandlers,\n cursorPointer: cursorPointer,\n handlerSource: 'direct'\n };\n }\n \n // No direct handlers - check parent for bubbled handlers (using DOM, not CSS selectors)\n if (element.parentElement) {\n const parentResult = getElementHandlersWithBubbling(element.parentElement, depth + 1);\n if (parentResult.handlers.length > 0) {\n // Parent has handlers that would bubble to this element\n // Cursor: getComputedStyle already includes inheritance!\n let cursorPointer = false;\n try {\n const style = window.getComputedStyle(element);\n cursorPointer = style.cursor === 'pointer';\n } catch (e) {\n // getComputedStyle can fail in edge cases (e.g., detached elements)\n // Default to false\n }\n \n return {\n handlers: parentResult.handlers.map(h => ({\n ...h,\n source: 'bubbled'\n })),\n cursorPointer: cursorPointer,\n handlerSource: 'bubbled'\n };\n }\n }\n \n // No handlers at all\n let cursorPointer = false;\n try {\n const style = window.getComputedStyle(element);\n cursorPointer = style.cursor === 'pointer';\n } catch (e) {\n // getComputedStyle can fail in edge cases (e.g., detached elements)\n // Default to false\n }\n \n return {\n handlers: [],\n cursorPointer: cursorPointer,\n handlerSource: 'none'\n };\n }\n\n function normalizeHandlers(handlers) {\n /**\n * Normalize handlers for comparison (ignore source field, deduplicate).\n * Returns sorted array of unique normalized handler objects.\n */\n const seen = new Set();\n const normalized = [];\n \n for (const h of handlers) {\n // Safety check: skip malformed handlers\n if (!h || !h.type) continue;\n \n const key = h.type === 'react-onClick' \n ? 'react-onClick' \n : `${h.type}:${h.value || 'function'}`;\n \n if (!seen.has(key)) {\n seen.add(key);\n normalized.push({\n type: h.type,\n value: h.type === 'react-onClick' ? undefined : (h.value || 'function')\n });\n }\n }\n \n return normalized.sort((a, b) => {\n if (a.type !== b.type) return a.type.localeCompare(b.type);\n return (a.value || '').localeCompare(b.value || '');\n });\n }\n\n function compareHandlersForUniquify(childHandlers, parentHandlers) {\n /**\n * Compare handlers between child and parent for uniquification.\n * Returns true if handlers are different (should keep child), false if same (can unify).\n */\n const childNormalized = normalizeHandlers(childHandlers.handlers);\n const parentNormalized = normalizeHandlers(parentHandlers.handlers);\n \n const handlersEqual = JSON.stringify(childNormalized) === JSON.stringify(parentNormalized);\n const cursorEqual = childHandlers.cursorPointer === parentHandlers.cursorPointer;\n \n // If handlers or cursor differ, keep child (don't unify)\n return !handlersEqual || !cursorEqual;\n }\n\n function uniquifyElements(elements) {\n highlighterLogger.debug(`Starting uniquification with ${elements.length} elements`);\n\n // Filter out testing infrastructure elements first\n const filteredInfrastructure = elements.filter(element_info => {\n // Skip the highlight-overlay element completely - it's part of the testing infrastructure\n if (element_info.element.id === 'highlight-overlay' || \n (element_info.css_selector && element_info.css_selector.includes('#highlight-overlay'))) {\n highlighterLogger.debug('Filtered out testing infrastructure element:', element_info.css_selector);\n return false;\n }\n \n // Filter out UI framework container/manager elements\n const el = element_info.element;\n // UI framework container checks - generic detection for any framework\n if ((el.getAttribute('data-rendered-by') || \n el.getAttribute('data-reactroot') || \n el.getAttribute('ng-version') || \n el.getAttribute('data-component-id') ||\n el.getAttribute('data-root') ||\n el.getAttribute('data-framework')) && \n (el.className && \n typeof el.className === 'string' && \n (el.className.includes('Container') || \n el.className.includes('container') || \n el.className.includes('Manager') || \n el.className.includes('manager')))) {\n highlighterLogger.debug('Filtered out UI framework container element:', element_info.css_selector);\n return false;\n }\n \n // Direct filter for framework container elements that shouldn't be interactive\n // Consolidating multiple container detection patterns into one efficient check\n const isFullViewport = element_info.bounding_box && \n element_info.bounding_box.x <= 5 && \n element_info.bounding_box.y <= 5 && \n element_info.bounding_box.width >= (window.innerWidth * 0.95) && \n element_info.bounding_box.height >= (window.innerHeight * 0.95);\n \n // Empty content check\n const isEmpty = !el.innerText || el.innerText.trim() === '';\n \n // Check if it's a framework container element\n if (element_info.element.tagName === 'DIV' && \n isFullViewport && \n isEmpty && \n (\n // Pattern matching for root containers\n (element_info.xpath && \n (element_info.xpath.match(/^\\/html\\[\\d+\\]\\/body\\[\\d+\\]\\/div\\[\\d+\\]\\/div\\[\\d+\\]$/) || \n element_info.xpath.match(/^\\/\\/\\*\\[@id='[^']+'\\]\\/div\\[\\d+\\]$/))) ||\n \n // Simple DOM structure\n (element_info.css_selector.split(' > ').length <= 4 && element_info.depth <= 5) ||\n \n // Empty or container-like classes\n (!el.className || el.className === '' || \n (typeof el.className === 'string' && \n (el.className.includes('overlay') || \n el.className.includes('container') || \n el.className.includes('wrapper'))))\n )) {\n highlighterLogger.debug('Filtered out framework container element:', element_info.css_selector);\n return false;\n }\n \n return true;\n });\n\n // First filter out elements with zero dimensions\n const nonZeroElements = filteredInfrastructure.filter(filterZeroDimensions);\n // sort by CSS selector depth so parents are processed first\n nonZeroElements.sort((a, b) => a.depth - b.depth);\n highlighterLogger.debug(`After dimension filtering: ${nonZeroElements.length} elements remain (${elements.length - nonZeroElements.length} removed)`);\n \n // Create parent candidate set with ALL nonZeroElements (before filtering)\n // This allows findClosestParent to find any element as a parent, even if it gets filtered out later\n const parentCandidates = new Set(nonZeroElements.map(e => e.css_selector));\n \n // Filter nested elements using handler comparison and standard logic\n const filteredByParent = filterNestedElements(nonZeroElements, parentCandidates, (element_info, parent, parentElementInfo) => {\n return shouldKeepNestedElement(element_info, parent, parentElementInfo);\n });\n\n highlighterLogger.debug(`After parent/child filtering: ${filteredByParent.length} elements remain (${nonZeroElements.length - filteredByParent.length} removed)`);\n\n // Final overlap filtering\n const filteredResults = filteredByParent.filter(element => {\n\n // Look for any element that came BEFORE this one in the array\n const hasEarlierOverlap = filteredByParent.some(other => {\n // Only check elements that came before (lower index)\n if (filteredByParent.indexOf(other) >= filteredByParent.indexOf(element)) {\n return false;\n }\n \n const isOverlapping = areElementsOverlapping(element, other); \n return isOverlapping;\n }); \n\n // Keep element if it has no earlier overlapping elements\n return !hasEarlierOverlap;\n });\n \n \n \n // Check for overlay removal\n highlighterLogger.debug(`After filtering: ${filteredResults.length} (${filteredByParent.length - filteredResults.length} removed by overlap)`);\n \n const nonOverlaidElements = filteredResults.filter(element => {\n return !isOverlaid(element);\n });\n\n highlighterLogger.debug(`Final elements after overlay removal: ${nonOverlaidElements.length} (${filteredResults.length - nonOverlaidElements.length} removed)`);\n \n return nonOverlaidElements;\n\n }\n\n\n\n const areElementsOverlapping = (element1, element2) => {\n if (element1.css_selector === element2.css_selector) {\n return true;\n }\n \n const box1 = element1.bounding_box;\n const box2 = element2.bounding_box;\n \n return box1.x === box2.x &&\n box1.y === box2.y &&\n box1.width === box2.width &&\n box1.height === box2.height;\n // element1.text === element2.text &&\n // element2.tag === 'a';\n };\n\n function findClosestParent(parentCandidates, element_info) { \n // Split the CSS selector into segments\n const segments = element_info.css_selector.split(' > ');\n \n // Try increasingly shorter paths until we find one in the parentCandidates set\n for (let i = segments.length - 1; i > 0; i--) {\n const parentPath = segments.slice(0, i).join(' > ');\n if (parentCandidates.has(parentPath)) {\n return parentPath;\n }\n }\n\n return null;\n }\n\n function shouldKeepNestedElement(elementInfo, parentPath, parentElementInfo) {\n // Check special cases FIRST (before handler comparison)\n const parentSegments = parentPath.split(' > ');\n\n // If parent is a link, don't keep child\n const isParentLink = /^a(:nth-of-type\\(\\d+\\))?$/.test(parentSegments[parentSegments.length - 1]);\n if (isParentLink) {\n return false; \n }\n \n // If this is a checkbox/radio input inside a label, don't keep the input (keep label instead)\n if (elementInfo.tag === 'input' && \n (elementInfo.type === 'checkbox' || elementInfo.type === 'radio')) {\n const isParentLabel = /^label(:nth-of-type\\(\\d+\\))?$/.test(parentSegments[parentSegments.length - 1]);\n if (isParentLabel) {\n return false;\n }\n }\n \n // Now check if handlers differ (only if special cases don't apply)\n if (parentElementInfo) {\n const childHandlers = getElementHandlersWithBubbling(elementInfo.element);\n const parentHandlers = getElementHandlersWithBubbling(parentElementInfo.element);\n \n // If handlers differ, keep child (don't unify)\n if (compareHandlersForUniquify(childHandlers, parentHandlers)) {\n return true;\n }\n }\n \n return isFormControl(elementInfo) || isDropdownItem(elementInfo) || isTableCell(elementInfo);\n }\n\n function isTableCell(elementInfo) {\n const element = elementInfo.element;\n if(!element || !(element instanceof HTMLElement)) {\n return false;\n }\n const validTags = new Set(['td', 'th']);\n const validRoles = new Set(['cell', 'gridcell', 'columnheader', 'rowheader']);\n \n const tag = element.tagName.toLowerCase();\n const role = element.getAttribute('role')?.toLowerCase();\n\n if (validTags.has(tag) || (role && validRoles.has(role))) {\n return true;\n }\n return false;\n \n }\n\n function isOverlaid(elementInfo) {\n const element = elementInfo.element;\n const boundingRect = elementInfo.bounding_box;\n \n\n \n \n // Create a diagnostic logging function that only logs when needed\n const diagnosticLog = (...args) => {\n { // set to true for debugging\n highlighterLogger.debug('[OVERLAY-DEBUG]', ...args);\n }\n };\n\n // Special handling for tooltips\n if (elementInfo.element.className && typeof elementInfo.element.className === 'string' && \n elementInfo.element.className.includes('tooltip')) {\n diagnosticLog('Element is a tooltip, not considering it overlaid');\n return false;\n }\n \n \n \n // Get element at the center point to check if it's covered by a popup/modal\n const middleX = boundingRect.x + boundingRect.width/2;\n const middleY = boundingRect.y + boundingRect.height/2;\n const elementAtMiddle = element.ownerDocument.elementFromPoint(middleX, middleY);\n \n if (elementAtMiddle && \n elementAtMiddle !== element && \n !isDecendent(element, elementAtMiddle) && \n !isDecendent(elementAtMiddle, element)) {\n\n \n return true;\n }\n \n \n return false;\n \n }\n\n /**\n * Checks if an element is scrollable (has scrollable content)\n * \n * @param element - The element to check\n * @returns boolean indicating if the element is scrollable\n */\n function isScrollableContainer(element) {\n if (!element) return false;\n \n const style = window.getComputedStyle(element);\n \n // Reliable way to detect if an element has scrollbars or is scrollable\n const hasScrollHeight = element.scrollHeight > element.clientHeight;\n const hasScrollWidth = element.scrollWidth > element.clientWidth;\n \n // Check actual style properties\n const hasOverflowY = style.overflowY === 'auto' || \n style.overflowY === 'scroll' || \n style.overflowY === 'overlay';\n const hasOverflowX = style.overflowX === 'auto' || \n style.overflowX === 'scroll' || \n style.overflowX === 'overlay';\n \n // Check common class names and attributes for scrollable containers across frameworks\n const hasScrollClasses = element.classList.contains('scroll') || \n element.classList.contains('scrollable') ||\n element.classList.contains('overflow') ||\n element.classList.contains('overflow-auto') ||\n element.classList.contains('overflow-scroll') ||\n element.getAttribute('data-scrollable') === 'true';\n \n // Check for height/max-height constraints that often indicate scrolling content\n const hasHeightConstraint = style.maxHeight && \n style.maxHeight !== 'none' && \n style.maxHeight !== 'auto';\n \n // An element is scrollable if it has:\n // 1. Actual scrollbars in use (most reliable check) OR\n // 2. Overflow styles allowing scrolling AND content that would require scrolling\n return (hasScrollHeight && hasOverflowY) || \n (hasScrollWidth && hasOverflowX) ||\n (hasScrollClasses && (hasScrollHeight || hasScrollWidth)) ||\n (hasHeightConstraint && hasScrollHeight);\n }\n\n /**\n * Detects scrollable containers that are ancestors of the target element\n * \n * This function traverses up the DOM tree from the target element and identifies\n * all scrollable containers (elements that have scrollable content).\n * \n * @param target - The target element to start the search from\n * @returns Array of objects with selector and scroll properties\n */\n function detectScrollableContainers(target) {\n const scrollableContainers = [];\n \n if (!target) {\n return scrollableContainers;\n }\n \n highlighterLogger.debug('🔍 [detectScrollableContainers] Starting detection for target:', target.tagName, target.id, target.className);\n \n // Detect if target is inside an iframe\n const iframe = getContainingIFrame(target);\n const iframe_selector = iframe ? generateCssPath(iframe) : \"\";\n \n highlighterLogger.debug('🔍 [detectScrollableContainers] Iframe context:', iframe ? 'inside iframe' : 'main document', 'selector:', iframe_selector);\n \n // Start from the target element and traverse up the DOM tree\n let currentElement = target;\n let depth = 0;\n const MAX_DEPTH = 10; // Limit traversal depth to avoid infinite loops\n \n while (currentElement && currentElement.nodeType === Node.ELEMENT_NODE && depth < MAX_DEPTH) { \n // Check if the current element is scrollable\n if (isScrollableContainer(currentElement)) {\n highlighterLogger.debug('🔍 [detectScrollableContainers] Found scrollable container at depth', depth, ':', currentElement.tagName, currentElement.id, currentElement.className);\n \n const container = {\n containerEl: currentElement,\n selector: generateCssPath(currentElement),\n iframe_selector: iframe_selector,\n scrollTop: currentElement.scrollTop,\n scrollLeft: currentElement.scrollLeft,\n scrollHeight: currentElement.scrollHeight,\n scrollWidth: currentElement.scrollWidth,\n clientHeight: currentElement.clientHeight,\n clientWidth: currentElement.clientWidth\n };\n \n scrollableContainers.push(container);\n }\n \n // Move to parent element\n currentElement = getParentNode(currentElement);\n \n depth++;\n }\n \n highlighterLogger.debug('🔍 [detectScrollableContainers] Detection complete. Found', scrollableContainers.length, 'scrollable containers');\n return scrollableContainers;\n }\n\n class DOMSerializer {\n constructor(options = {}) {\n this.options = {\n includeStyles: true,\n includeScripts: false, // Security consideration\n includeFrames: true,\n includeShadowDOM: true,\n maxDepth: 50,\n ...options\n };\n this.serializedFrames = new Map();\n this.shadowRoots = new Map();\n }\n \n /**\n * Serialize a complete document or element\n */\n serialize(rootElement = document) {\n try {\n const serialized = {\n type: 'document',\n doctype: this.serializeDoctype(rootElement),\n documentElement: this.serializeElement(rootElement.documentElement || rootElement),\n frames: [],\n timestamp: Date.now(),\n url: rootElement.URL || window.location?.href,\n metadata: {\n title: rootElement.title,\n charset: rootElement.characterSet,\n contentType: rootElement.contentType\n }\n };\n \n // Serialize frames and iframes if enabled\n if (this.options.includeFrames) {\n serialized.frames = this.serializeFrames(rootElement);\n }\n \n return serialized;\n } catch (error) {\n console.error('Serialization error:', error);\n throw new Error(`DOM serialization failed: ${error.message}`);\n }\n }\n \n /**\n * Serialize document type declaration\n */\n serializeDoctype(doc) {\n if (!doc.doctype) return null;\n \n return {\n name: doc.doctype.name,\n publicId: doc.doctype.publicId,\n systemId: doc.doctype.systemId\n };\n }\n \n /**\n * Serialize an individual element and its children\n */\n serializeElement(element, depth = 0) {\n if (depth > this.options.maxDepth) {\n return { type: 'text', content: '<!-- Max depth exceeded -->' };\n }\n \n const nodeType = element.nodeType;\n \n switch (nodeType) {\n case Node.ELEMENT_NODE:\n return this.serializeElementNode(element, depth);\n case Node.TEXT_NODE:\n return this.serializeTextNode(element);\n case Node.COMMENT_NODE:\n return this.serializeCommentNode(element);\n case Node.DOCUMENT_FRAGMENT_NODE:\n return this.serializeDocumentFragment(element, depth);\n default:\n return null;\n }\n }\n \n /**\n * Serialize element node with attributes and children\n */\n serializeElementNode(element, depth) {\n const tagName = element.tagName.toLowerCase();\n \n // Skip script tags for security unless explicitly enabled\n if (tagName === 'script' && !this.options.includeScripts) {\n return { type: 'comment', content: '<!-- Script tag removed for security -->' };\n }\n \n const serialized = {\n type: 'element',\n tagName: tagName,\n attributes: this.serializeAttributes(element),\n children: [],\n shadowRoot: null\n };\n \n // Handle Shadow DOM\n if (this.options.includeShadowDOM && element.shadowRoot) {\n serialized.shadowRoot = this.serializeShadowRoot(element.shadowRoot, depth + 1);\n }\n \n // Handle special elements\n if (tagName === 'iframe' || tagName === 'frame') {\n serialized.frameData = this.serializeFrameElement(element);\n }\n \n // Serialize children\n for (const child of element.childNodes) {\n const serializedChild = this.serializeElement(child, depth + 1);\n if (serializedChild) {\n serialized.children.push(serializedChild);\n }\n }\n \n // Include computed styles if enabled\n if (this.options.includeStyles && element.nodeType === Node.ELEMENT_NODE) {\n serialized.computedStyle = this.serializeComputedStyle(element);\n }\n \n return serialized;\n }\n \n /**\n * Serialize element attributes\n */\n serializeAttributes(element) {\n const attributes = {};\n \n if (element.attributes) {\n for (const attr of element.attributes) {\n attributes[attr.name] = attr.value;\n }\n }\n \n return attributes;\n }\n \n /**\n * Serialize computed styles\n */\n serializeComputedStyle(element) {\n try {\n const computedStyle = window.getComputedStyle(element);\n const styles = {};\n \n // Only serialize non-default values to reduce size\n const importantStyles = [\n 'display', 'position', 'width', 'height', 'margin', 'padding',\n 'border', 'background', 'color', 'font-family', 'font-size',\n 'text-align', 'visibility', 'z-index', 'transform'\n ];\n \n for (const prop of importantStyles) {\n const value = computedStyle.getPropertyValue(prop);\n if (value && value !== 'initial' && value !== 'normal') {\n styles[prop] = value;\n }\n }\n \n return styles;\n } catch (error) {\n return {};\n }\n }\n \n /**\n * Serialize text node\n */\n serializeTextNode(node) {\n return {\n type: 'text',\n content: node.textContent\n };\n }\n \n /**\n * Serialize comment node\n */\n serializeCommentNode(node) {\n return {\n type: 'comment',\n content: node.textContent\n };\n }\n \n /**\n * Serialize document fragment\n */\n serializeDocumentFragment(fragment, depth) {\n const serialized = {\n type: 'fragment',\n children: []\n };\n \n for (const child of fragment.childNodes) {\n const serializedChild = this.serializeElement(child, depth + 1);\n if (serializedChild) {\n serialized.children.push(serializedChild);\n }\n }\n \n return serialized;\n }\n \n /**\n * Serialize Shadow DOM\n */\n serializeShadowRoot(shadowRoot, depth) {\n const serialized = {\n type: 'shadowRoot',\n mode: shadowRoot.mode,\n children: []\n };\n \n for (const child of shadowRoot.childNodes) {\n const serializedChild = this.serializeElement(child, depth + 1);\n if (serializedChild) {\n serialized.children.push(serializedChild);\n }\n }\n \n return serialized;\n }\n \n /**\n * Serialize frame/iframe elements\n */\n serializeFrameElement(frameElement) {\n const frameData = {\n src: frameElement.src,\n name: frameElement.name,\n id: frameElement.id,\n sandbox: frameElement.sandbox?.toString() || '',\n allowfullscreen: frameElement.allowFullscreen\n };\n \n // Try to access frame content (may fail due to CORS)\n try {\n const frameDoc = frameElement.contentDocument;\n if (frameDoc && this.options.includeFrames) {\n frameData.content = this.serialize(frameDoc);\n }\n } catch (error) {\n frameData.accessError = 'Cross-origin frame content not accessible';\n }\n \n return frameData;\n }\n \n /**\n * Serialize all frames in document\n */\n serializeFrames(doc) {\n const frames = [];\n const frameElements = doc.querySelectorAll('iframe, frame');\n \n for (const frameElement of frameElements) {\n try {\n const frameDoc = frameElement.contentDocument;\n if (frameDoc) {\n frames.push({\n element: this.serializeElement(frameElement),\n content: this.serialize(frameDoc)\n });\n }\n } catch (error) {\n frames.push({\n element: this.serializeElement(frameElement),\n error: 'Frame content not accessible'\n });\n }\n }\n \n return frames;\n }\n \n /**\n * Deserialize serialized DOM data back to DOM nodes\n */\n deserialize(serializedData, targetDocument = document) {\n try {\n if (serializedData.type === 'document') {\n return this.deserializeDocument(serializedData, targetDocument);\n } else {\n return this.deserializeElement(serializedData, targetDocument);\n }\n } catch (error) {\n console.error('Deserialization error:', error);\n throw new Error(`DOM deserialization failed: ${error.message}`);\n }\n }\n \n /**\n * Deserialize complete document\n */\n deserializeDocument(serializedDoc, targetDoc) {\n // Create new document if needed\n const doc = targetDoc || document.implementation.createHTMLDocument();\n \n // Set doctype if present\n if (serializedDoc.doctype) {\n const doctype = document.implementation.createDocumentType(\n serializedDoc.doctype.name,\n serializedDoc.doctype.publicId,\n serializedDoc.doctype.systemId\n );\n doc.replaceChild(doctype, doc.doctype);\n }\n \n // Deserialize document element\n if (serializedDoc.documentElement) {\n const newDocElement = this.deserializeElement(serializedDoc.documentElement, doc);\n doc.replaceChild(newDocElement, doc.documentElement);\n }\n \n // Handle metadata\n if (serializedDoc.metadata) {\n doc.title = serializedDoc.metadata.title || '';\n }\n \n return doc;\n }\n \n /**\n * Deserialize individual element\n */\n deserializeElement(serializedNode, doc) {\n switch (serializedNode.type) {\n case 'element':\n return this.deserializeElementNode(serializedNode, doc);\n case 'text':\n return doc.createTextNode(serializedNode.content);\n case 'comment':\n return doc.createComment(serializedNode.content);\n case 'fragment':\n return this.deserializeDocumentFragment(serializedNode, doc);\n case 'shadowRoot':\n // Shadow roots are handled during element creation\n return null;\n default:\n return null;\n }\n }\n \n /**\n * Deserialize element node\n */\n deserializeElementNode(serializedElement, doc) {\n const element = doc.createElement(serializedElement.tagName);\n \n // Set attributes\n if (serializedElement.attributes) {\n for (const [name, value] of Object.entries(serializedElement.attributes)) {\n try {\n element.setAttribute(name, value);\n } catch (error) {\n console.warn(`Failed to set attribute ${name}:`, error);\n }\n }\n }\n \n // Apply computed styles if available\n if (serializedElement.computedStyle && this.options.includeStyles) {\n for (const [prop, value] of Object.entries(serializedElement.computedStyle)) {\n try {\n element.style.setProperty(prop, value);\n } catch (error) {\n console.warn(`Failed to set style ${prop}:`, error);\n }\n }\n }\n \n // Create shadow root if present\n if (serializedElement.shadowRoot && element.attachShadow) {\n try {\n const shadowRoot = element.attachShadow({ \n mode: serializedElement.shadowRoot.mode || 'open' \n });\n \n // Deserialize shadow root children\n for (const child of serializedElement.shadowRoot.children) {\n const childElement = this.deserializeElement(child, doc);\n if (childElement) {\n shadowRoot.appendChild(childElement);\n }\n }\n } catch (error) {\n console.warn('Failed to create shadow root:', error);\n }\n }\n \n // Deserialize children\n if (serializedElement.children) {\n for (const child of serializedElement.children) {\n const childElement = this.deserializeElement(child, doc);\n if (childElement) {\n element.appendChild(childElement);\n }\n }\n }\n \n // Handle frame content\n if (serializedElement.frameData && serializedElement.frameData.content) {\n // Frame content deserialization would happen after the frame loads\n element.addEventListener('load', () => {\n try {\n const frameDoc = element.contentDocument;\n if (frameDoc) {\n this.deserializeDocument(serializedElement.frameData.content, frameDoc);\n }\n } catch (error) {\n console.warn('Failed to deserialize frame content:', error);\n }\n });\n }\n \n return element;\n }\n \n /**\n * Deserialize document fragment\n */\n deserializeDocumentFragment(serializedFragment, doc) {\n const fragment = doc.createDocumentFragment();\n \n if (serializedFragment.children) {\n for (const child of serializedFragment.children) {\n const childElement = this.deserializeElement(child, doc);\n if (childElement) {\n fragment.appendChild(childElement);\n }\n }\n }\n \n return fragment;\n }\n }\n \n // Usage example and utility functions\n class DOMUtils {\n /**\n * Create serializer with common presets\n */\n static createSerializer(preset = 'default') {\n const presets = {\n default: {\n includeStyles: true,\n includeScripts: false,\n includeFrames: true,\n includeShadowDOM: true\n },\n minimal: {\n includeStyles: false,\n includeScripts: false,\n includeFrames: false,\n includeShadowDOM: false\n },\n complete: {\n includeStyles: true,\n includeScripts: true,\n includeFrames: true,\n includeShadowDOM: true\n },\n secure: {\n includeStyles: true,\n includeScripts: false,\n includeFrames: false,\n includeShadowDOM: true\n }\n };\n \n return new DOMSerializer(presets[preset] || presets.default);\n }\n \n /**\n * Serialize DOM to JSON string\n */\n static serializeToJSON(element, options) {\n const serializer = new DOMSerializer(options);\n const serialized = serializer.serialize(element);\n return JSON.stringify(serialized, null, 2);\n }\n \n /**\n * Deserialize from JSON string\n */\n static deserializeFromJSON(jsonString, targetDocument) {\n const serialized = JSON.parse(jsonString);\n const serializer = new DOMSerializer();\n return serializer.deserialize(serialized, targetDocument);\n }\n \n /**\n * Clone DOM with full fidelity including Shadow DOM\n */\n static deepClone(element, options) {\n const serializer = new DOMSerializer(options);\n const serialized = serializer.serialize(element);\n return serializer.deserialize(serialized, element.ownerDocument);\n }\n \n /**\n * Compare two DOM structures\n */\n static compare(element1, element2, options) {\n const serializer = new DOMSerializer(options);\n const serialized1 = serializer.serialize(element1);\n const serialized2 = serializer.serialize(element2);\n \n return JSON.stringify(serialized1) === JSON.stringify(serialized2);\n }\n }\n \n /*\n // Export for use\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = { DOMSerializer, DOMUtils };\n } else if (typeof window !== 'undefined') {\n window.DOMSerializer = DOMSerializer;\n window.DOMUtils = DOMUtils;\n }\n */\n\n /* Usage Examples:\n \n // Basic serialization\n const serializer = new DOMSerializer();\n const serialized = serializer.serialize(document);\n console.log(JSON.stringify(serialized, null, 2));\n \n // Deserialize back to DOM\n const clonedDoc = serializer.deserialize(serialized);\n \n // Using presets\n const minimalSerializer = DOMUtils.createSerializer('minimal');\n const secureSerializer = DOMUtils.createSerializer('secure');\n \n // Serialize specific element with Shadow DOM\n const customElement = document.querySelector('my-custom-element');\n const serializedElement = serializer.serialize(customElement);\n \n // JSON utilities\n const jsonString = DOMUtils.serializeToJSON(document.body);\n const restored = DOMUtils.deserializeFromJSON(jsonString);\n \n // Deep clone with Shadow DOM support\n const clone = DOMUtils.deepClone(document.body, { includeShadowDOM: true });\n \n */\n\n function serializeNodeToJSON(nodeElement) {\n return DOMUtils.serializeToJSON(nodeElement, {includeStyles: false});\n }\n\n function deserializeNodeFromJSON(jsonString) {\n return DOMUtils.deserializeFromJSON(jsonString);\n }\n\n function findDropdowns() {\n const dropdowns = [];\n \n // Native select elements\n dropdowns.push(...getAllElementsIncludingShadow('select'));\n \n // Elements with dropdown roles that don't have <input>..</input>\n const roleElements = getAllElementsIncludingShadow('[role=\"combobox\"], [role=\"listbox\"], [role=\"dropdown\"], [role=\"option\"], [role=\"menu\"], [role=\"menuitem\"]').filter(el => {\n return el.tagName.toLowerCase() !== 'input' || ![\"button\", \"checkbox\", \"radio\"].includes(el.getAttribute(\"type\"));\n });\n dropdowns.push(...roleElements);\n \n // Common dropdown class patterns\n const dropdownPattern = /.*(dropdown|select|combobox|menu).*/i;\n const elements = getAllElementsIncludingShadow('*');\n const dropdownClasses = Array.from(elements).filter(el => {\n const hasDropdownClass = dropdownPattern.test(el.className);\n const validTag = ['li', 'ul', 'span', 'div', 'p', 'a', 'button'].includes(el.tagName.toLowerCase());\n const style = window.getComputedStyle(el); \n const result = hasDropdownClass && validTag && (style.cursor === 'pointer' || el.tagName.toLowerCase() === 'a' || el.tagName.toLowerCase() === 'button');\n return result;\n });\n \n dropdowns.push(...dropdownClasses);\n \n // Elements with aria-haspopup attribute\n dropdowns.push(...getAllElementsIncludingShadow('[aria-haspopup=\"true\"], [aria-haspopup=\"listbox\"], [aria-haspopup=\"menu\"]'));\n\n // Improve navigation element detection\n // Semantic nav elements with list items\n dropdowns.push(...getAllElementsIncludingShadow('nav ul li, nav ol li'));\n \n // Navigation elements in common design patterns\n dropdowns.push(...getAllElementsIncludingShadow('header a, .header a, .nav a, .navigation a, .menu a, .sidebar a, aside a'));\n \n // Elements in primary navigation areas with common attributes\n dropdowns.push(...getAllElementsIncludingShadow('[role=\"navigation\"] a, [aria-label*=\"navigation\"] a, [aria-label*=\"menu\"] a'));\n\n return dropdowns;\n }\n\n function findClickables() {\n const clickables = [];\n \n const checkboxPattern = /checkbox/i;\n // Collect all clickable elements first\n const nativeLinks = [...getAllElementsIncludingShadow('a')];\n const nativeButtons = [...getAllElementsIncludingShadow('button')];\n const inputButtons = [...getAllElementsIncludingShadow('input[type=\"button\"], input[type=\"submit\"], input[type=\"reset\"]')];\n const roleButtons = [...getAllElementsIncludingShadow('[role=\"button\"]')];\n // const tabbable = [...getAllElementsIncludingShadow('[tabindex=\"0\"]')];\n const clickHandlers = [...getAllElementsIncludingShadow('[onclick]')];\n const dropdowns = findDropdowns();\n const nativeCheckboxes = [...getAllElementsIncludingShadow('input[type=\"checkbox\"]')]; \n const fauxCheckboxes = getAllElementsIncludingShadow('*').filter(el => {\n if (checkboxPattern.test(el.className)) {\n const realCheckboxes = getAllElementsIncludingShadow('input[type=\"checkbox\"]', el);\n if (realCheckboxes.length === 1) {\n const boundingRect = realCheckboxes[0].getBoundingClientRect();\n return boundingRect.width <= 1 && boundingRect.height <= 1 \n }\n }\n return false;\n });\n const nativeRadios = [...getAllElementsIncludingShadow('input[type=\"radio\"]')];\n const toggles = findToggles();\n const pointerElements = findElementsWithPointer();\n // Add all elements at once\n clickables.push(\n ...nativeLinks,\n ...nativeButtons,\n ...inputButtons,\n ...roleButtons,\n // ...tabbable,\n ...clickHandlers,\n ...dropdowns,\n ...nativeCheckboxes,\n ...fauxCheckboxes,\n ...nativeRadios,\n ...toggles,\n ...pointerElements\n );\n\n // Only uniquify once at the end\n return clickables; // Let findElements handle the uniquification\n }\n\n function findToggles() {\n const toggles = [];\n const checkboxes = getAllElementsIncludingShadow('input[type=\"checkbox\"]');\n const togglePattern = /switch|toggle|slider/i;\n\n checkboxes.forEach(checkbox => {\n let isToggle = false;\n\n // Check the checkbox itself\n if (togglePattern.test(checkbox.className) || togglePattern.test(checkbox.getAttribute('role') || '')) {\n isToggle = true;\n }\n\n // Check parent elements (up to 3 levels)\n if (!isToggle) {\n let element = checkbox;\n for (let i = 0; i < 3; i++) {\n const parent = element.parentElement;\n if (!parent) break;\n\n const className = parent.className || '';\n const role = parent.getAttribute('role') || '';\n\n if (togglePattern.test(className) || togglePattern.test(role)) {\n isToggle = true;\n break;\n }\n element = parent;\n }\n }\n\n // Check next sibling\n if (!isToggle) {\n const nextSibling = checkbox.nextElementSibling;\n if (nextSibling) {\n const className = nextSibling.className || '';\n const role = nextSibling.getAttribute('role') || '';\n if (togglePattern.test(className) || togglePattern.test(role)) {\n isToggle = true;\n }\n }\n }\n\n if (isToggle) {\n toggles.push(checkbox);\n }\n });\n\n return toggles;\n }\n\n function findNonInteractiveElements() {\n // Get all elements in the document\n const all = Array.from(getAllElementsIncludingShadow('*'));\n \n // Filter elements based on Python implementation rules\n return all.filter(element => {\n if (!element.firstElementChild) {\n const tag = element.tagName.toLowerCase(); \n if (!['select', 'button', 'a'].includes(tag)) {\n const validTags = ['p', 'span', 'div', 'input', 'textarea','td','th'].includes(tag) || /^h\\d$/.test(tag) || /text/.test(tag);\n const boundingRect = element.getBoundingClientRect();\n return validTags && boundingRect.height > 1 && boundingRect.width > 1;\n }\n }\n return false;\n });\n }\n\n\n\n function findElementsWithPointer() {\n const elements = [];\n const allElements = getAllElementsIncludingShadow('*');\n \n allElements.forEach(element => {\n const style = window.getComputedStyle(element);\n const hasPointer = style.cursor === 'pointer';\n \n if (hasPointer) {\n elements.push(element);\n }\n });\n \n highlighterLogger.debug(`Found ${elements.length} elements with pointer cursor`);\n return elements;\n }\n\n function findCheckables() {\n const elements = [];\n\n elements.push(...getAllElementsIncludingShadow('input[type=\"checkbox\"]'));\n elements.push(...getAllElementsIncludingShadow('input[type=\"radio\"]'));\n const all_elements = getAllElementsIncludingShadow('label');\n const radioClasses = Array.from(all_elements).filter(el => {\n return /.*radio.*/i.test(el.className); \n });\n elements.push(...radioClasses);\n return elements;\n }\n\n function findFillables() {\n const elements = [];\n\n const inputs = [...getAllElementsIncludingShadow('input:not([type=\"radio\"]):not([type=\"checkbox\"])')];\n highlighterLogger.debug('Found inputs:', inputs.length, inputs);\n elements.push(...inputs);\n \n const textareas = [...getAllElementsIncludingShadow('textarea')];\n highlighterLogger.debug('Found textareas:', textareas.length);\n elements.push(...textareas);\n \n const editables = [...getAllElementsIncludingShadow('[contenteditable=\"true\"]')];\n highlighterLogger.debug('Found editables:', editables.length);\n elements.push(...editables);\n\n return elements;\n }\n\n // maximum number of characters in a logical name\n const MAX_LOGICAL_NAME_LENGTH = 25;\n \n /**\n * Query elements by CSS selector with :has-text(\"...\") pseudo-selector\n * @param {string} selector - CSS selector with optional :has-text(\"...\") pseudo-selector\n * @param {Element|Document} context - Context element to query within (defaults to document)\n * @returns {Element[]} Array of matched elements\n * @example\n * // Find all buttons with text \"Submit\"\n * querySelectorAllByText('button:has-text(\"Submit\")')\n * \n * // Find element with specific role and text\n * querySelectorAllByText('[role=\"button\"]:has-text(\"Click me\")')\n * \n * // Complex selector with descendants\n * querySelectorAllByText('button:has-text(\"foo\") > div > ul')\n * \n * // Multiple components\n * querySelectorAllByText('.container > button:has-text(\"Submit\")')\n * \n * // Multiple text filters\n * querySelectorAllByText('button:has-text(\"foo\") > div:has-text(\"bar\") > span')\n */\n function querySelectorAllByText(selector, context = document) {\n \t// Local helper function to compare two strings by normalizing whitespace and ignoring case\n \t// mimic the behavior of Playwright's :has-text() selector modifier\n \tfunction pwHasText(str1, str2) {\n \t\tif (!str1 || !str2) return false;\n \t\t\n \t\t// Normalize whitespace by replacing multiple spaces with single space and trim\n \t\tconst normalize = (str) => cleanText(str.toLowerCase());\n \t\t\n \t\tconst normalized1 = normalize(str1);\n \t\tconst normalized2 = normalize(str2);\n \t\t\n \t\treturn normalized1.includes(normalized2);\n \t}\n \t\n \t// Check if selector contains :has-text() pseudo-selector\n \tif (!selector.includes(':has-text(')) {\n \t\t// No :has-text pseudo-selector, use regular querySelectorAll\n \t\treturn Array.from(robustQuerySelector(selector, context, true));\n \t}\n \t\n \t// Split selector by combinators while preserving them\n \t// Matches: >, +, ~, or space (descendant combinator)\n \tconst parts = [];\n \tlet currentPart = '';\n \tlet inBracket = false;\n \tlet inTextPseudo = false;\n \tlet inTextQuotes = false;\n \tlet i = 0;\n \t\n \twhile (i < selector.length) {\n \t\tconst char = selector[i];\n \t\t\n \t\t// Track :has-text(\"...\") to avoid splitting inside it\n \t\tif (selector.substring(i, i + 10) === ':has-text(') {\n \t\t\tinTextPseudo = true;\n \t\t\tinTextQuotes = false;\n \t\t}\n \t\tif (inTextPseudo && char === '\"' && !inTextQuotes) {\n \t\t\tinTextQuotes = true;\n \t\t} else if (inTextPseudo && char === '\"' && inTextQuotes) {\n \t\t\t// Check if this quote is escaped\n \t\t\tif (i > 0 && selector[i - 1] === '\\\\') ; else {\n \t\t\t\tinTextQuotes = false;\n \t\t\t}\n \t\t}\n \t\tif (inTextPseudo && char === ')' && !inTextQuotes) {\n \t\t\tinTextPseudo = false;\n \t\t\tcurrentPart += char;\n \t\t\ti++;\n \t\t\tcontinue;\n \t\t}\n \t\t\n \t\t// Track brackets to avoid splitting on combinators inside attribute selectors\n \t\tif (char === '[') inBracket = true;\n \t\tif (char === ']') inBracket = false;\n \t\t\n \t\t// Check for combinators (not inside brackets or :has-text())\n \t\tif (!inBracket && !inTextPseudo && (char === '>' || char === '+' || char === '~')) {\n \t\t\tif (currentPart.trim()) parts.push({ selector: currentPart.trim(), combinator: null });\n \t\t\tparts.push({ selector: null, combinator: char.trim() });\n \t\t\tcurrentPart = '';\n \t\t\ti++;\n \t\t\tcontinue;\n \t\t}\n \t\t\n \t\t// Check for space combinator (descendant)\n \t\tif (!inBracket && !inTextPseudo && char === ' ') {\n \t\t\t// Skip multiple spaces\n \t\t\twhile (i < selector.length && selector[i] === ' ') i++;\n \t\t\t// Check if next char is a combinator (>, +, ~)\n \t\t\tif (i < selector.length && !'><+~'.includes(selector[i])) {\n \t\t\t\tif (currentPart.trim()) {\n \t\t\t\t\tparts.push({ selector: currentPart.trim(), combinator: null });\n \t\t\t\t\tparts.push({ selector: null, combinator: ' ' });\n \t\t\t\t\tcurrentPart = '';\n \t\t\t\t}\n \t\t\t}\n \t\t\tcontinue;\n \t\t}\n \t\t\n \t\tcurrentPart += char;\n \t\ti++;\n \t}\n \tif (currentPart.trim()) parts.push({ selector: currentPart.trim(), combinator: null });\n \t\n \t// Filter out combinator-only entries and rebuild as selector+combinator pairs\n \tconst selectorParts = [];\n \tfor (let j = 0; j < parts.length; j++) {\n \t\tif (parts[j].selector) {\n \t\t\tconst combinator = (j + 1 < parts.length && parts[j + 1].combinator) ? parts[j + 1].combinator : null;\n \t\t\t// Extract text value if present\n \t\t\tconst textMatch = parts[j].selector.match(/:has-text\\(\"((?:[^\"\\\\]|\\\\.)*)\"\\)/);\n \t\t\tconst textValue = textMatch ? textMatch[1] : null;\n \t\t\tconst selectorWithoutText = textMatch ? parts[j].selector.replace(/:has-text\\(\"((?:[^\"\\\\]|\\\\.)*)\"\\)/, '') : parts[j].selector;\n \t\t\t\n \t\t\tselectorParts.push({ \n \t\t\t\tselector: parts[j].selector,\n \t\t\t\tselectorWithoutText,\n \t\t\t\ttextValue,\n \t\t\t\tcombinator \n \t\t\t});\n \t\t}\n \t}\n \t\n \t// Process selector parts sequentially, applying text filters as we go\n \tlet currentElements = [context];\n \t\n \tfor (let partIndex = 0; partIndex < selectorParts.length; partIndex++) {\n \t\tconst part = selectorParts[partIndex];\n \t\tconst nextElements = [];\n \t\t\n \t\tfor (const ctx of currentElements) {\n \t\t\tlet candidates;\n \t\t\t\n \t\t\tif (partIndex === 0 && ctx === context) {\n \t\t\t\t// First part, query from document/context\n \t\t\t\tconst querySelector = part.selectorWithoutText.trim() || '*';\n \t\t\t\tcandidates = Array.from(robustQuerySelector(querySelector, ctx, true));\n \t\t\t\thighlighterLogger.debug(`querySelectorAllByText: first part, querySelector=${querySelector}, candidates=`, candidates);\n \t\t\t} \n \t\t\telse {\n \t\t\t\t// Subsequent parts, use combinator\n \t\t\t\tconst prevPart = selectorParts[partIndex - 1];\n \t\t\t\tconst combinator = prevPart.combinator;\n \t\t\t\tconst querySelector = part.selectorWithoutText.trim() || '*';\n \t\t\t\t\n \t\t\t\tif (combinator === '>') {\n \t\t\t\t\t// Direct children\n \t\t\t\t\tcandidates = Array.from(ctx.children).filter(child => {\n \t\t\t\t\t\treturn child.matches(querySelector);\n \t\t\t\t\t});\n \t\t\t\t} else if (combinator === '+') {\n \t\t\t\t\t// Next sibling\n \t\t\t\t\tconst sibling = ctx.nextElementSibling;\n \t\t\t\t\tcandidates = (sibling && sibling.matches(querySelector)) ? [sibling] : [];\n \t\t\t\t} else if (combinator === '~') {\n \t\t\t\t\t// Following siblings\n \t\t\t\t\tcandidates = [];\n \t\t\t\t\tlet sibling = ctx.nextElementSibling;\n \t\t\t\t\twhile (sibling) {\n \t\t\t\t\t\tif (sibling.matches(querySelector)) {\n \t\t\t\t\t\t\tcandidates.push(sibling);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tsibling = sibling.nextElementSibling;\n \t\t\t\t\t}\n \t\t\t\t} \n \t\t\t\telse {\n \t\t\t\t\t// Descendant (space)\n \t\t\t\t\tcandidates = Array.from(robustQuerySelector(querySelector, ctx, true));\n \t\t\t\t}\n \t\t\t}\n \t\t\t\n \t\t\t// Apply text filter if present\n \t\t\tif (part.textValue !== null) {\n \t\t\t\tcandidates = candidates.filter(el => pwHasText(getElementText(el), part.textValue));\n \t\t\t}\n \t\t\t\n \t\t\tnextElements.push(...candidates);\n \t\t}\n \t\t\n \t\tcurrentElements = nextElements;\n \t\t\n \t\t// If no matches, bail early\n \t\tif (currentElements.length === 0) {\n \t\t\treturn [];\n \t\t}\n \t}\n \t\n \treturn currentElements;\n }\n\n const cleanText = (text) => {\n \treturn text.replace(/\\s+/g, ' ').trim();\n };\n\n // Helper function to get name selector\n const getNameSelector = (element) => {\n \tconst text = cleanText(getElementText(element));\n \tconst title = element.getAttribute('title');\n \tconst name = element.getAttribute('name');\n \tconst ariaLabel = element.getAttribute('aria-label');\n \tif (!text && !title && !name && !ariaLabel) throw new Error('No name attribute provided');\n \tif (text) return `:has-text(${doubleQuoteString(text)})`;\n \tif (title) return `[title=${doubleQuoteString(title)}]`;\n \tif (ariaLabel) return `[aria-label=${doubleQuoteString(ariaLabel)}]`;\n \treturn `[name=${doubleQuoteString(name)}]`; \n };\n\n const getLogicalName = (element) => {\n \tconst text = cleanText(getElementText(element));\n \tconst title = element.getAttribute('title');\n \tconst name = element.getAttribute('name');\n \tconst ariaLabel = element.getAttribute('aria-label');\n \tconst role = element.getAttribute('role');\n \tconst logicalName = text || title || name || ariaLabel;\n \treturn {\n \t\thasLogicalName: logicalName && logicalName.length < MAX_LOGICAL_NAME_LENGTH && !role?.startsWith('row'),\n \t\tlogicalName: logicalName\n \t};\n };\n\n\n /**\n * Individual strategy functions\n */\n\n function tryRoleStrategy(element) { \n \tconst role = element.getAttribute('role');\n \tconst tag = element.tagName.toLowerCase();\n \tconst { hasLogicalName, logicalName } = getLogicalName(element);\n \tif (role && hasLogicalName) {\n \t\treturn { \n \t\t\tstrategy: 'role', \n \t\t\tselector: `[role=${doubleQuoteString(role)}]${getNameSelector(element)}`\n \t\t};\n \t}\n \t\n \t// Tag-based role (button, a, input, etc.) + name\n \tif (['button', 'a', 'input', 'textarea', 'select'].includes(tag) && hasLogicalName) {\n \t\treturn { \n \t\t\tstrategy: 'role', \n \t\t\tselector: `${tag}${getNameSelector(element)}`\n \t\t};\n \t}\n \t\n \treturn null;\n }\n\n function tryPlaceholderStrategy(element) {\n \tconst placeholder = element.getAttribute('placeholder');\n \tif (placeholder) {\n \t\treturn { \n \t\t\tstrategy: 'placeholder', \n \t\t\tselector: `[placeholder=${doubleQuoteString(placeholder)}]` \n \t\t};\n \t}\n \treturn null;\n }\n\n function tryLabelStrategy(element) {\n \tconst tag = element.tagName.toLowerCase();\n \tif (['input', 'textarea', 'select'].includes(tag)) {\n \t\tconst id = element.id;\n \t\tif (id) {\n \t\t\tconst labels = robustQuerySelector(`label[for=${doubleQuoteString(id)}]`, document, true);\n \t\t\tif (labels.length === 1) { //make sure id is unique\n \t\t\t\tconst labelText = cleanText(getElementText(labels[0]));\n \t\t\t\tif (labelText) {\n \t\t\t\t\tconst labelSelector = `label:has-text(${doubleQuoteString(labelText)})`;\n \t\t\t\t\ttry {\n \t\t\t\t\t\tconst els = querySelectorAllByText(labelSelector, document);\n \t\t\t\t\t\tif (els.length === 1) {\n \t\t\t\t\t\t\treturn { \n \t\t\t\t\t\t\t\tstrategy: 'label for',\n \t\t\t\t\t\t\t\tlabel_selector: labelSelector\n \t\t\t\t\t\t\t};\n \t\t\t\t\t\t}\n \t\t\t\t\t} catch (error) {\n \t\t\t\t\t\thighlighterLogger.error(`internal error: while querying label selector ${labelSelector} for element ${element.outerHTML}`, error);\n \t\t\t\t\t\tthrow error;\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t}\n \treturn null;\n }\n\n function tryAriaLabelledByStrategy(element) {\n \tconst arialabeledBy = element.getAttribute('aria-labelledby');\n \tconst tag = element.tagName.toLowerCase();\n \t\n \tif (arialabeledBy) {\n \t\tconst labels = robustQuerySelector(`#${CSS.escape(arialabeledBy)}`, document, true);\n \t\tif (labels.length === 1) {\n \t\t\tconst labelText = cleanText(getElementText(labels[0]));\n \t\t\tif (labelText) { //verify the label text is unique\n \t\t\t\tconst labelSelector = `${tag}:has-text(${doubleQuoteString(labelText)})`;\n \t\t\t\ttry {\n \t\t\t\t\tconst els = querySelectorAllByText(labelSelector, document);\n \t\t\t\t\tif (els.length === 1) {\n \t\t\t\t\t\treturn { \n \t\t\t\t\t\t\tstrategy: 'label by', \n \t\t\t\t\t\t\tlabel_selector: labelSelector\n \t\t\t\t\t\t};\n \t\t\t\t\t}\n \t\t\t\t} catch (error) {\n \t\t\t\t\thighlighterLogger.error(`internal error: while querying aria-labelledby selector ${labelSelector} for element ${element.outerHTML}`, error);\n \t\t\t\t\tthrow error;\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t}\n \treturn null;\n }\n\n // Only use text strategy if element is clickable/interactive \n function tryNameStrategy(element) {\t\n \tconst { hasLogicalName } = getLogicalName(element);\n \tconst classes = Array.from(element.classList).map(cls => CSS.escape(cls));\n \t\n \t// Only use name strategy if element is clickable/interactive \n \tif (isClickableElement(element) && hasLogicalName && classes.length > 0) {\n \t\treturn { \n \t\t\tstrategy: 'name', \n \t\t\tselector: `.${classes.join('.')}${getNameSelector(element)}` \n \t\t\t// selector: `${element.tagName.toLowerCase()}${getNameSelector(element)}`\n \t\t};\n \t}\n \treturn null;\n }\n\n function tryDataTestIdStrategy(element) {\n \tconst dataTestId = element.getAttribute('data-testid');\n \tif (dataTestId) {\n \t\treturn { \n \t\t\tstrategy: 'data-testid',\t\t\t\n \t\t\tselector: `[data-testid=${doubleQuoteString(dataTestId)}]` \n \t\t};\n \t}\n \treturn null;\n }\n\n function tryIdStrategy(element) {\n \tconst id = element.getAttribute('id');\n \tif (id && !/:|\\s|\\\\/.test(id)) { //avoid using id if it contain unusual characters (react creates ids like this: \":r:42\")\n \t\treturn { \n \t\t\tstrategy: 'id', \n \t\t\tselector: `#${CSS.escape(id)}` \n \t\t};\n \t}\n \treturn null;\n }\n\n // Try all strategies on an element in order of precedence\n function attemptStrategiesOnElement(element) {\n \tconst strategies = [\n \t\ttryRoleStrategy, \t\t\n \t\ttryAriaLabelledByStrategy,\n \t\ttryNameStrategy,\n \t\ttryLabelStrategy,\n \t\ttryDataTestIdStrategy,\n \t\ttryPlaceholderStrategy,\n \t\ttryIdStrategy,\t\t\n \t\t// tryClassStrategy\n \t];\n \t\n \tfor (const strategy of strategies) {\n \t\tconst result = strategy(element); \n \t\tif (result) { \n \t\t\treturn result;\n \t\t}\n \t}\n \treturn null;\n }\n\n /**\n * Generate a smart selector for an element\n * @param {Element} element - The element to generate a locator for\n * @param {string} childPath - The child path to generate a locator for\n * @returns {Object} The selector for the element\n */\n function generateSmartSelector(element, childPath = '') {\n \t// Terminate recursion\n \tif (!element || element.nodeType !== Node.ELEMENT_NODE) {\n \t\treturn {\n \t\t\tstrategy: 'css',\n \t\t\tselector: childPath\n \t\t};\n \t}\n \t\n \t// Try strategies 1-6 on current element\n \tconst result = attemptStrategiesOnElement(element);\n \tconst is_label = result?.strategy === 'label for' || result?.strategy === 'label by';\n\n \tif (result) { // found a strategy\t\t\t\n \t\t// If we have a child path, concatenate parent strategy result with child CSS path \n \t\tlet extendedResult = result; \n \t\tif (childPath) {\n \t\t\tconst selector = is_label ? `${childPath}` : `${result?.selector} > ${childPath}`;\n \t\t\textendedResult = {\n \t\t\t\t...extendedResult,\n \t\t\t\tselector: selector,\n \t\t\t\tstrategy: `${extendedResult.strategy} (concatenated with child CSS path)`\n \t\t\t};\n \t\t} \t\t\n \t\t// check if the combined selector is unique and if not add the index to the strategy\n \t\tif (!is_label) { //label element is already checked for uniqueness\n \t\t\ttry {\n \t\t\t\tconst matchedElements = querySelectorAllByText(extendedResult?.selector); //query full selector for uniqueness checking \n \t\t\t\thighlighterLogger.debug(`querySelectorAllByText(${extendedResult?.selector}) matched ${matchedElements.length} elements`);\n \t\t\t\thighlighterLogger.debug(matchedElements);\n \t\t\t\tif (matchedElements.length > 1) {\n \t\t\t\t\tconst childElement = childPath ? robustQuerySelector(`:scope > ${childPath}`, element) : element;\n \t\t\t\t\tconst index = matchedElements.findIndex(el => el === childElement);\n \t\t\t\t\tif (index === -1) {\n \t\t\t\t\t\thighlighterLogger.error('internal error: Element not found in matched elements', element, result?.selector, matchedElements);\n \t\t\t\t\t\treturn null;\n \t\t\t\t\t}\n \t\t\t\t\textendedResult = {\n \t\t\t\t\t\t...extendedResult,\n \t\t\t\t\t\tstrategy: `${extendedResult.strategy} (by index)`,\n \t\t\t\t\t\tindex,\n \t\t\t\t\t}; \n \t\t\t\t}\n \t\t\t} catch (error) {\n \t\t\t\thighlighterLogger.error(`internal error: while checking if selector ${result?.selector} is unique for element ${element.outerHTML}`, error);\n \t\t\t\tthrow error;\n \t\t\t}\t\t\t\n \t\t}\n \t\treturn extendedResult;\n \t}\n \t\n \t// Get CSS selector for current element and build child path \n \tlet newChildPath;\n \t// didn't find strategy\n \tconst elementSelector = getElementCssSelector(element);\n \tnewChildPath = childPath ? `${elementSelector} > ${childPath}` : elementSelector;\n \tconst numComponents = newChildPath.split(' > ').length;\n \tif (numComponents > 2) { //require at least 2 components for css strategy\n \t\t// check if the combined selector is unique\n \t\tconst matchedElements = robustQuerySelector(newChildPath, document, true);\n \t\tif (matchedElements.length === 1) {\n \t\t\treturn {\n \t\t\t\tstrategy: 'css',\t\t\t\t\n \t\t\t\tselector: newChildPath\n \t\t\t};\n \t\t}\n \t}\n\n \t// Recursively try parent element\n \treturn generateSmartSelector(getParentNode(element), newChildPath);\n }\n\n const findElementByInfo = (elementInfo, useSmartSelectors = false) => {\n \thighlighterLogger.debug('findElementByInfo:', elementInfo);\n \tif (useSmartSelectors) {\n \t return findElementBySelectors(elementInfo.smart_iframe_selector, elementInfo.smart_selector, true);\n \t}\n \treturn findElementBySelectors(elementInfo.iframe_selector, elementInfo.css_selector, false);\n };\n\n const compareSelectors = (selector1, selector2, useSmartSelectors = false) => {\n \tif (useSmartSelectors) {\n \t\treturn JSON.stringify(selector1) === JSON.stringify(selector2);\n \t}\n \treturn selector1 === selector2;\n };\n\n const findElementBySelectors = (iframeSelector, elementSelector, useSmartSelectors = false) => {\n \tlet element;\n \t\n \t// first find the iframe that contains the element\n \tif (iframeSelector) { \n \t const frames = getAllDocumentElementsIncludingShadow('iframe', document);\n \t \n \t // Iterate over all frames and compare their CSS selectors\n \t for (const frame of frames) {\n \t\tconst selector = useSmartSelectors ? generateSmartSelector(frame) : generateCssPath(frame);\n \t\tif (compareSelectors(selector, iframeSelector, useSmartSelectors)) {\n \t\t const frameDocument = frame.contentDocument || frame.contentWindow.document;\n \t\t element = useSmartSelectors ? findElementBySmartSelector(elementSelector, frameDocument) : robustQuerySelector(elementSelector, frameDocument);\t\t \n \t\t break;\n \t\t} \n \t }\t}\n \telse {\t\t\n \t\telement = useSmartSelectors ? findElementBySmartSelector(elementSelector, document) : robustQuerySelector(elementSelector, document);\t\t\n \t}\n \t \n \tif (element) {\n \t\thighlighterLogger.debug('findElementBySelectors: found element ', element);\n \t}\n \telse {\n \t highlighterLogger.warn('findElementBySelectors: failed to find element with CSS selector:', JSON.stringify(elementSelector));\n \t}\n \n \treturn element;\n };\n \n function findElementBySmartSelector(smartSelector, root = document) {\t\n \thighlighterLogger.debug(`findElementBySmartSelector: called with smartSelector=${JSON.stringify(smartSelector)}`);\n \tlet combinedSelector;\n \tconst mainStrategy = smartSelector.strategy.split(' ')[0]; //extract the main strategy from the full strategy string\n \tswitch(mainStrategy) {\n case 'role': \n case 'placeholder':\n case 'name':\n case 'data-testid':\n case 'id':\n case 'css':\n case 'class':\n \t\t highlighterLogger.debug(`findElementBySmartSelector: strategy='${smartSelector.strategy}', selector=${smartSelector?.selector}, index=${smartSelector?.index}`);\n if (typeof smartSelector?.index === 'number') {\n return querySelectorAllByText(smartSelector.selector, root)[smartSelector.index];\n }\n else {\n return querySelectorAllByText(smartSelector.selector, root)[0];\n }\t\t \n case 'label':\n \t\t\tif (smartSelector.strategy === 'label for') {\n \t\t\t\thighlighterLogger.debug(`findElementBySmartSelector: strategy='label for', label_selector=${smartSelector.label_selector}`);\n \t\t\t\tconst label_for = querySelectorAllByText(smartSelector.label_selector, root)[0];\n \t\t\t\tcombinedSelector = smartSelector?.selector ? `#${label_for.getAttribute('for')} > ${smartSelector.selector}` : `#${label_for.getAttribute('for')}`;\n \t\t\t\treturn robustQuerySelector(combinedSelector, root);\n \t\t\t}\n \t\t\telse if (smartSelector.strategy === 'label by') {\n \t\t\t\thighlighterLogger.debug(`findElementBySmartSelector: strategy='label by', label_selector=${smartSelector.label_selector}`);\n \t\t\t\tconst label_by = querySelectorAllByText(smartSelector.label_selector, root)[0];\n \t\t\t\tcombinedSelector = smartSelector?.selector ? `[aria-labelledby=\"${label_by.getAttribute('id')}\"] > ${smartSelector.selector}` : `[aria-labelledby=\"${label_by.getAttribute('id')}\"]`;\n \t\t\t\treturn robustQuerySelector(combinedSelector, root);\n \t\t\t}\n \t\t\telse {\n \t\t\t\thighlighterLogger.error(`findElementBySmartSelector: unsupported label strategy: ${smartSelector.strategy}`);\n \t\t\t\treturn null;\n \t\t\t} \n default:\n highlighterLogger.error(`findElementBySmartSelector: Unsupported smart selector strategy: ${smartSelector.strategy}`);\n return null;\n }\n }\n\n function getElementInfo(element, index) { \t\t\t\n \tconst iframe = getContainingIFrame(element); \n \tconst iframe_selector = iframe ? generateCssPath(iframe) : \"\";\t\n \tconst smart_iframe_selector = iframe ? generateSmartSelector(iframe) : null;\n \t\n \t// Return element info with pre-calculated values\n \treturn {\n \t\tindex: index ?? -1,\n \t\ttag: element.tagName.toLowerCase(),\n \t\ttype: element.type || '',\n \t\ttext: getElementText(element) || getElementPlaceholder(element),\n \t\thtml: cleanHTML(element.outerHTML),\n \t\txpath: generateXPath(element),\n \t\tcss_selector: generateCssPath(element),\n \t\tbounding_box: element.getBoundingClientRect(),\t\t\n \t\tiframe_selector: iframe_selector,\t\t\n \t\tsmart_selector: generateSmartSelector(element),\n \t\tsmart_iframe_selector: smart_iframe_selector,\n \t\telement: element,\n \t\tdepth: getElementDepth(element)\n \t};\n }\n\n /**\n * Checks if a point is inside a bounding box\n * \n * @param point The point to check\n * @param box The bounding box\n * @returns boolean indicating if the point is inside the box\n */\n function isPointInsideBox(point, box) {\n return point.x >= box.x &&\n point.x <= box.x + box.width &&\n point.y >= box.y &&\n point.y <= box.y + box.height;\n }\n\n /**\n * Calculates the overlap area between two bounding boxes\n * \n * @param box1 First bounding box\n * @param box2 Second bounding box\n * @returns The overlap area\n */\n function calculateOverlap(box1, box2) {\n const xOverlap = Math.max(0,\n Math.min(box1.x + box1.width, box2.x + box2.width) -\n Math.max(box1.x, box2.x)\n );\n const yOverlap = Math.max(0,\n Math.min(box1.y + box1.height, box2.y + box2.height) -\n Math.max(box1.y, box2.y)\n );\n return xOverlap * yOverlap;\n }\n\n /**\n * Finds an exact match between candidate elements and the actual interaction element\n * \n * @param candidate_elements Array of candidate element infos\n * @param actualInteractionElementInfo The actual interaction element info\n * @returns The matching candidate element info, or null if no match is found\n */\n function findExactMatch(candidate_elements, actualInteractionElementInfo) {\n if (!actualInteractionElementInfo.element) {\n return null;\n }\n\n const exactMatch = candidate_elements.find(elementInfo => \n elementInfo.element && elementInfo.element === actualInteractionElementInfo.element\n );\n \n if (exactMatch) {\n highlighterLogger.debug('✅ Found exact element match:', {\n matchedElement: exactMatch.element?.tagName,\n matchedElementClass: exactMatch.element?.className,\n index: exactMatch.index\n });\n return exactMatch;\n }\n \n return null;\n }\n\n /**\n * Finds a match by traversing up the parent elements\n * \n * @param candidate_elements Array of candidate element infos\n * @param actualInteractionElementInfo The actual interaction element info\n * @returns The matching candidate element info, or null if no match is found\n */\n function findParentMatch(candidate_elements, actualInteractionElementInfo) {\n if (!actualInteractionElementInfo.element) {\n return null;\n }\n\n let element = actualInteractionElementInfo.element;\n while (element.parentElement) {\n element = element.parentElement;\n const parentMatch = candidate_elements.find(candidate => \n candidate.element && candidate.element === element\n );\n \n if (parentMatch) {\n highlighterLogger.debug('✅ Found parent element match:', {\n matchedElement: parentMatch.element?.tagName,\n matchedElementClass: parentMatch.element?.className,\n index: parentMatch.index,\n depth: element.tagName\n });\n return parentMatch;\n }\n \n // Stop if we hit another candidate element\n if (candidate_elements.some(candidate => \n candidate.element && candidate.element === element\n )) {\n highlighterLogger.debug('⚠️ Stopped parent search - hit another candidate element:', element.tagName);\n break;\n }\n }\n \n return null;\n }\n\n /**\n * Finds a match based on spatial relationships between elements\n * \n * @param candidate_elements Array of candidate element infos\n * @param actualInteractionElementInfo The actual interaction element info\n * @returns The matching candidate element info, or null if no match is found\n */\n function findSpatialMatch(candidate_elements, actualInteractionElementInfo) {\n if (!actualInteractionElementInfo.element || !actualInteractionElementInfo.bounding_box) {\n return null;\n }\n\n const actualBox = actualInteractionElementInfo.bounding_box;\n let bestMatch = null;\n let bestScore = 0;\n\n for (const candidateInfo of candidate_elements) {\n if (!candidateInfo.bounding_box) continue;\n \n const candidateBox = candidateInfo.bounding_box;\n let score = 0;\n\n // Check if actual element is contained within candidate\n if (isPointInsideBox({ x: actualBox.x, y: actualBox.y }, candidateBox) &&\n isPointInsideBox({ x: actualBox.x + actualBox.width, y: actualBox.y + actualBox.height }, candidateBox)) {\n score += 100; // High score for containment\n }\n\n // Calculate overlap area as a factor\n const overlap = calculateOverlap(actualBox, candidateBox);\n score += overlap;\n\n // Consider proximity if no containment\n if (score === 0) {\n const distance = Math.sqrt(\n Math.pow((actualBox.x + actualBox.width/2) - (candidateBox.x + candidateBox.width/2), 2) +\n Math.pow((actualBox.y + actualBox.height/2) - (candidateBox.y + candidateBox.height/2), 2)\n );\n // Convert distance to a score (closer = higher score)\n score = 1000 / (distance + 1);\n }\n\n if (score > bestScore) {\n bestScore = score;\n bestMatch = candidateInfo;\n highlighterLogger.debug('📏 New best spatial match:', {\n element: candidateInfo.element?.tagName,\n class: candidateInfo.element?.className,\n index: candidateInfo.index,\n score: score\n });\n }\n }\n\n if (bestMatch) {\n highlighterLogger.debug('✅ Final spatial match selected:', {\n element: bestMatch.element?.tagName,\n class: bestMatch.element?.className,\n index: bestMatch.index,\n finalScore: bestScore\n });\n return bestMatch;\n }\n\n return null;\n }\n\n /**\n * Finds a matching candidate element for an actual interaction element\n * \n * @param candidate_elements Array of candidate element infos\n * @param actualInteractionElementInfo The actual interaction element info\n * @returns The matching candidate element info, or null if no match is found\n */\n function findMatchingCandidateElementInfo(candidate_elements, actualInteractionElementInfo) {\n if (!actualInteractionElementInfo.element || !actualInteractionElementInfo.bounding_box) {\n highlighterLogger.error('❌ Missing required properties in actualInteractionElementInfo');\n return null;\n }\n\n highlighterLogger.debug('🔍 Starting element matching for:', {\n clickedElement: actualInteractionElementInfo.element.tagName,\n clickedElementClass: actualInteractionElementInfo.element.className,\n totalCandidates: candidate_elements.length\n });\n\n // First try exact element match\n const exactMatch = findExactMatch(candidate_elements, actualInteractionElementInfo);\n if (exactMatch) {\n return exactMatch;\n }\n highlighterLogger.debug('❌ No exact element match found, trying parent matching...');\n\n // Try finding closest clickable parent\n const parentMatch = findParentMatch(candidate_elements, actualInteractionElementInfo);\n if (parentMatch) {\n return parentMatch;\n }\n highlighterLogger.debug('❌ No parent match found, falling back to spatial matching...');\n\n // If no exact or parent match, look for spatial relationships\n const spatialMatch = findSpatialMatch(candidate_elements, actualInteractionElementInfo);\n if (spatialMatch) {\n return spatialMatch;\n }\n\n highlighterLogger.error('❌ No matching element found for actual interaction element:', actualInteractionElementInfo);\n return null;\n }\n\n const highlight = {\n execute: async function(elementTypes, handleScroll=false) {\n const elements = await findElements(elementTypes);\n highlightElements(elements, false,handleScroll);\n return elements;\n },\n\n unexecute: function(handleScroll=false) {\n unhighlightElements(handleScroll);\n },\n\n generateJSON: async function() {\n const json = {};\n\n // Capture viewport dimensions\n const viewportData = {\n width: window.innerWidth,\n height: window.innerHeight,\n documentWidth: document.documentElement.clientWidth,\n documentHeight: document.documentElement.clientHeight,\n timestamp: new Date().toISOString()\n };\n\n // Add viewport data to the JSON output\n json.viewport = viewportData;\n\n\n await Promise.all(Object.values(ElementTag).map(async elementType => {\n const elements = await findElements(elementType);\n json[elementType] = elements;\n }));\n\n // Serialize the JSON object\n const jsonString = JSON.stringify(json, null, 4); // Pretty print with 4 spaces\n\n highlighterLogger.log(`JSON: ${jsonString}`);\n return jsonString;\n },\n\n getElementInfo\n };\n\n\n function unhighlightElements(handleScroll=false) {\n const documents = getAllFrames();\n documents.forEach(doc => {\n const overlay = doc.getElementById('highlight-overlay');\n if (overlay) {\n if (handleScroll) {\n // Remove event listeners\n doc.removeEventListener('scroll', overlay.scrollHandler, true);\n doc.removeEventListener('resize', overlay.resizeHandler);\n }\n overlay.remove();\n }\n });\n }\n\n\n async function findElements(elementTypes, verbose=true) {\n const typesArray = Array.isArray(elementTypes) ? elementTypes : [elementTypes];\n highlighterLogger.debug('Starting element search for types:', typesArray);\n\n const elements = [];\n typesArray.forEach(elementType => {\n if (elementType === ElementTag.FILLABLE) {\n elements.push(...findFillables());\n }\n if (elementType === ElementTag.SELECTABLE) {\n elements.push(...findDropdowns());\n }\n if (elementType === ElementTag.CLICKABLE) {\n elements.push(...findClickables());\n elements.push(...findToggles());\n elements.push(...findCheckables());\n }\n if (elementType === ElementTag.NON_INTERACTIVE_ELEMENT) {\n elements.push(...findNonInteractiveElements());\n }\n });\n\n // console.log('Before uniquify:', elements.length);\n const elementsWithInfo = elements.map((element, index) => \n getElementInfo(element, index)\n );\n\n \n \n const uniqueElements = uniquifyElements(elementsWithInfo);\n highlighterLogger.debug(`Found ${uniqueElements.length} elements:`);\n \n // More comprehensive visibility check\n const visibleElements = uniqueElements.filter(elementInfo => {\n const el = elementInfo.element;\n const style = getComputedStyle(el);\n \n // Check various style properties that affect visibility\n if (style.display === 'none' || \n style.visibility === 'hidden') {\n return false;\n }\n \n // Check if element has non-zero dimensions\n const rect = el.getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) {\n return false;\n }\n \n // Check if element is within viewport\n if (rect.bottom < 0 || \n rect.top > window.innerHeight || \n rect.right < 0 || \n rect.left > window.innerWidth) {\n // Element is outside viewport, but still might be valid \n // if user scrolls to it, so we'll include it\n return true;\n }\n \n return true;\n });\n \n highlighterLogger.debug(`Out of which ${visibleElements.length} elements are visible:`);\n if (verbose) {\n visibleElements.forEach(info => {\n highlighterLogger.debug(`Element ${info.index}:`, info);\n });\n }\n \n return visibleElements;\n }\n\n // elements is an array of objects with index, xpath\n function highlightElements(elements, enableSmartSelectors=false, handleScroll=false) {\n // console.log('[highlightElements] called with', elements.length, 'elements');\n // Create overlay if it doesn't exist and store it in a dictionary\n const documents = getAllFrames(); \n let overlays = {};\n documents.forEach(doc => {\n let overlay = doc.getElementById('highlight-overlay');\n if (!overlay) {\n overlay = doc.createElement('div');\n overlay.id = 'highlight-overlay';\n overlay.style.cssText = `\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n z-index: 2147483647;\n `;\n doc.body.appendChild(overlay);\n // console.log('[highlightElements] Created overlay in document:', doc);\n }\n overlays[doc.documentURI] = overlay;\n });\n \n\n const updateHighlights = (doc = null) => {\n if (doc) {\n overlays[doc.documentURI].innerHTML = '';\n } else {\n Object.values(overlays).forEach(overlay => { overlay.innerHTML = ''; });\n } \n elements.forEach((elementInfo, idx) => {\n //console.log(`[highlightElements] Processing element ${idx}:`, elementInfo.tag, elementInfo.css_selector, elementInfo.bounding_box);\n let element = elementInfo.element;\n if (!element) {\n element = findElementByInfo(elementInfo, enableSmartSelectors);\n if (!element) {\n highlighterLogger.warn('[highlightElements] Could not find element for:', elementInfo);\n return;\n }\n }\n //if highlights requested for a specific doc, skip unrelated elements\n if (doc && element.ownerDocument !== doc) {\n highlighterLogger.debug(\"[highlightElements] Skipped element since it doesn't belong to document\", doc);\n return;\n }\n const rect = element.getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) {\n highlighterLogger.warn('[highlightElements] Element has zero dimensions:', elementInfo);\n return;\n }\n // Create border highlight (red rectangle)\n // use ownerDocument to support iframes/frames\n const highlight = element.ownerDocument.createElement('div');\n highlight.style.cssText = `\n position: fixed;\n left: ${rect.x}px;\n top: ${rect.y}px;\n width: ${rect.width}px;\n height: ${rect.height}px;\n border: 1px solid rgb(255, 0, 0);\n transition: all 0.2s ease-in-out;\n `;\n // Create index label container - now positioned to the right and slightly up\n const labelContainer = element.ownerDocument.createElement('div');\n labelContainer.style.cssText = `\n position: absolute;\n right: -10px; /* Offset to the right */\n top: -10px; /* Offset upwards */\n padding: 4px;\n background-color: rgba(255, 255, 0, 0.6);\n display: flex;\n align-items: center;\n justify-content: center;\n `;\n const text = element.ownerDocument.createElement('span');\n text.style.cssText = `\n color: rgb(0, 0, 0, 0.8);\n font-family: 'Courier New', Courier, monospace;\n font-size: 12px;\n font-weight: bold;\n line-height: 1;\n `;\n text.textContent = elementInfo.index.toString();\n labelContainer.appendChild(text);\n highlight.appendChild(labelContainer); \n overlays[element.ownerDocument.documentURI].appendChild(highlight);\n \n });\n };\n\n // Initial highlight\n updateHighlights();\n\n if (handleScroll) {\n documents.forEach(doc => {\n // Update highlights on scroll and resize\n highlighterLogger.debug('registering scroll and resize handlers for document: ', doc);\n const scrollHandler = () => {\n requestAnimationFrame(() => updateHighlights(doc));\n };\n const resizeHandler = () => {\n updateHighlights(doc);\n };\n doc.addEventListener('scroll', scrollHandler, true);\n doc.addEventListener('resize', resizeHandler);\n // Store event handlers for cleanup\n overlays[doc.documentURI].scrollHandler = scrollHandler;\n overlays[doc.documentURI].resizeHandler = resizeHandler;\n }); \n }\n }\n\n // function unexecute() {\n // unhighlightElements();\n // }\n\n // Make it available globally for both Extension and Playwright\n if (typeof window !== 'undefined') {\n function stripElementRefs(elementInfo) {\n if (!elementInfo) return null;\n const { element, ...rest } = elementInfo;\n return rest;\n }\n\n window.ProboLabs = window.ProboLabs || {};\n\n // --- Caching State ---\n window.ProboLabs.candidates = [];\n window.ProboLabs.actual = null;\n window.ProboLabs.matchingCandidate = null;\n\n // --- Methods ---\n /**\n * Find and cache candidate elements of a given type (e.g., 'CLICKABLE').\n * NOTE: This function is async and must be awaited from Playwright/Node.\n */\n window.ProboLabs.findAndCacheCandidateElements = async function(elementType) {\n //console.log('[ProboLabs] findAndCacheCandidateElements called with:', elementType);\n const found = await findElements(elementType);\n window.ProboLabs.candidates = found;\n // console.log('[ProboLabs] candidates set to:', found, 'type:', typeof found, 'isArray:', Array.isArray(found));\n return found.length;\n };\n\n window.ProboLabs.findAndCacheActualElement = function(iframeSelector, elementSelector, isHover=false, useSmartSelectors=false) {\n // console.log('[ProboLabs] findAndCacheActualElement called with:', cssSelector, iframeSelector);\n highlighterLogger.debug(`[ProboLabs] findAndCacheActualElement called with: iframeSelector=${iframeSelector}, elementSelector=${elementSelector}, useSmartSelectors=${useSmartSelectors}`);\n let el = findElementBySelectors(iframeSelector, elementSelector, useSmartSelectors);\n if(isHover) {\n const visibleElement = findClosestVisibleElement(el);\n if (visibleElement) {\n el = visibleElement;\n }\n }\n if (!el) {\n window.ProboLabs.actual = null;\n // console.log('[ProboLabs] actual set to null');\n return false;\n }\n window.ProboLabs.actual = getElementInfo(el, -1);\n // console.log('[ProboLabs] actual set to:', window.ProboLabs.actual);\n return true;\n };\n\n window.ProboLabs.findAndCacheMatchingCandidate = function() {\n // console.log('[ProboLabs] findAndCacheMatchingCandidate called');\n if (!window.ProboLabs.candidates.length || !window.ProboLabs.actual) {\n window.ProboLabs.matchingCandidate = null;\n // console.log('[ProboLabs] matchingCandidate set to null');\n return false;\n }\n window.ProboLabs.matchingCandidate = findMatchingCandidateElementInfo(window.ProboLabs.candidates, window.ProboLabs.actual);\n // console.log('[ProboLabs] matchingCandidate set to:', window.ProboLabs.matchingCandidate);\n return !!window.ProboLabs.matchingCandidate;\n };\n\n window.ProboLabs.highlightCachedElements = function(which) {\n let elements = [];\n if (which === 'candidates') elements = window.ProboLabs.candidates;\n if (which === 'actual' && window.ProboLabs.actual) elements = [window.ProboLabs.actual];\n if (which === 'matching' && window.ProboLabs.matchingCandidate) elements = [window.ProboLabs.matchingCandidate];\n highlighterLogger.debug(`[ProboLabs] highlightCachedElements ${which} with ${elements.length} elements`);\n highlightElements(elements);\n };\n\n window.ProboLabs.unhighlight = function() {\n // console.log('[ProboLabs] unhighlight called');\n unhighlightElements();\n };\n\n window.ProboLabs.reset = function() {\n highlighterLogger.debug('[ProboLabs] reset called');\n window.ProboLabs.candidates = [];\n window.ProboLabs.actual = null;\n window.ProboLabs.matchingCandidate = null;\n unhighlightElements();\n };\n\n window.ProboLabs.getCandidates = function() {\n // console.log('[ProboLabs] getCandidates called. candidates:', window.ProboLabs.candidates, 'type:', typeof window.ProboLabs.candidates, 'isArray:', Array.isArray(window.ProboLabs.candidates));\n const arr = Array.isArray(window.ProboLabs.candidates) ? window.ProboLabs.candidates : [];\n return arr.map(stripElementRefs);\n };\n window.ProboLabs.getActual = function() {\n return stripElementRefs(window.ProboLabs.actual);\n };\n window.ProboLabs.getMatchingCandidate = function() {\n return stripElementRefs(window.ProboLabs.matchingCandidate);\n };\n\n window.ProboLabs.setLoggerDebugLevel = function(debugLevel) {\n highlighterLogger.setLogLevel(debugLevel);\n };\n\n // Retain existing API for backward compatibility\n window.ProboLabs.ElementTag = ElementTag;\n window.ProboLabs.highlightElements = highlightElements;\n window.ProboLabs.unhighlightElements = unhighlightElements;\n window.ProboLabs.findElements = findElements;\n window.ProboLabs.getElementInfo = getElementInfo;\n window.ProboLabs.highlight = window.ProboLabs.highlight;\n window.ProboLabs.unhighlight = window.ProboLabs.unhighlight;\n\n // --- Utility Functions ---\n function findClosestVisibleElement(element) {\n let current = element;\n while (current) {\n const style = window.getComputedStyle(current);\n if (\n style &&\n style.display !== 'none' &&\n style.visibility !== 'hidden' &&\n current.offsetWidth > 0 &&\n current.offsetHeight > 0\n ) {\n return current;\n }\n if (!current.parentElement || current === document.body) break;\n current = current.parentElement;\n }\n return null;\n }\n }\n\n exports.deserializeNodeFromJSON = deserializeNodeFromJSON;\n exports.detectScrollableContainers = detectScrollableContainers;\n exports.findElementByInfo = findElementByInfo;\n exports.findElementBySelectors = findElementBySelectors;\n exports.findElements = findElements;\n exports.generateCssPath = generateCssPath;\n exports.generateSmartSelector = generateSmartSelector;\n exports.getAriaLabelledByText = getAriaLabelledByText;\n exports.getContainingIFrame = getContainingIFrame;\n exports.getElementInfo = getElementInfo;\n exports.highlight = highlight;\n exports.highlightElements = highlightElements;\n exports.isScrollableContainer = isScrollableContainer;\n exports.serializeNodeToJSON = serializeNodeToJSON;\n exports.unhighlightElements = unhighlightElements;\n\n}));\n//# sourceMappingURL=probolabs.umd.js.map\n";
1
+ const highlighterCode = "(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ProboLabs = {}));\n})(this, (function (exports) { 'use strict';\n\n /**\n * Element tag constants for different types of interactive elements\n */\n const ElementTag = {\n CLICKABLE: \"CLICKABLE\",\n FILLABLE: \"FILLABLE\",\n SELECTABLE: \"SELECTABLE\",\n NON_INTERACTIVE_ELEMENT: 'NON_INTERACTIVE_ELEMENT',\n };\n\n var ApplyAIStatus;\n (function (ApplyAIStatus) {\n ApplyAIStatus[\"PREPARE_START\"] = \"PREPARE_START\";\n ApplyAIStatus[\"PREPARE_SUCCESS\"] = \"PREPARE_SUCCESS\";\n ApplyAIStatus[\"PREPARE_ERROR\"] = \"PREPARE_ERROR\";\n ApplyAIStatus[\"SEND_START\"] = \"SEND_START\";\n ApplyAIStatus[\"SEND_SUCCESS\"] = \"SEND_SUCCESS\";\n ApplyAIStatus[\"SEND_ERROR\"] = \"SEND_ERROR\";\n ApplyAIStatus[\"APPLY_AI_ERROR\"] = \"APPLY_AI_ERROR\";\n ApplyAIStatus[\"APPLY_AI_CANCELLED\"] = \"APPLY_AI_CANCELLED\";\n ApplyAIStatus[\"SUMMARY_COMPLETED\"] = \"SUMMARY_COMPLETED\";\n ApplyAIStatus[\"SUMMARY_ERROR\"] = \"SUMMARY_ERROR\";\n })(ApplyAIStatus || (ApplyAIStatus = {}));\n var ReplayStatus;\n (function (ReplayStatus) {\n ReplayStatus[\"REPLAY_START\"] = \"REPLAY_START\";\n ReplayStatus[\"REPLAY_SUCCESS\"] = \"REPLAY_SUCCESS\";\n ReplayStatus[\"REPLAY_ERROR\"] = \"REPLAY_ERROR\";\n ReplayStatus[\"REPLAY_CANCELLED\"] = \"REPLAY_CANCELLED\";\n })(ReplayStatus || (ReplayStatus = {}));\n\n // Action constants\n var PlaywrightAction;\n (function (PlaywrightAction) {\n PlaywrightAction[\"VISIT_BASE_URL\"] = \"VISIT_BASE_URL\";\n PlaywrightAction[\"VISIT_URL\"] = \"VISIT_URL\";\n PlaywrightAction[\"CLICK\"] = \"CLICK\";\n PlaywrightAction[\"FILL_IN\"] = \"FILL_IN\";\n PlaywrightAction[\"SELECT_DROPDOWN\"] = \"SELECT_DROPDOWN\";\n PlaywrightAction[\"SELECT_MULTIPLE_DROPDOWN\"] = \"SELECT_MULTIPLE_DROPDOWN\";\n PlaywrightAction[\"CHECK_CHECKBOX\"] = \"CHECK_CHECKBOX\";\n PlaywrightAction[\"SELECT_RADIO\"] = \"SELECT_RADIO\";\n PlaywrightAction[\"TOGGLE_SWITCH\"] = \"TOGGLE_SWITCH\";\n PlaywrightAction[\"SET_SLIDER\"] = \"SET_SLIDER\";\n PlaywrightAction[\"TYPE_KEYS\"] = \"TYPE_KEYS\";\n PlaywrightAction[\"HOVER\"] = \"HOVER\";\n PlaywrightAction[\"ASSERT_EXACT_VALUE\"] = \"ASSERT_EXACT_VALUE\";\n PlaywrightAction[\"ASSERT_CONTAINS_VALUE\"] = \"ASSERT_CONTAINS_VALUE\";\n PlaywrightAction[\"ASSERT_URL\"] = \"ASSERT_URL\";\n PlaywrightAction[\"SCROLL_TO_ELEMENT\"] = \"SCROLL_TO_ELEMENT\";\n PlaywrightAction[\"EXTRACT_VALUE\"] = \"EXTRACT_VALUE\";\n PlaywrightAction[\"ASK_AI\"] = \"ASK_AI\";\n PlaywrightAction[\"EXECUTE_SCRIPT\"] = \"EXECUTE_SCRIPT\";\n PlaywrightAction[\"UPLOAD_FILES\"] = \"UPLOAD_FILES\";\n PlaywrightAction[\"WAIT_FOR\"] = \"WAIT_FOR\";\n PlaywrightAction[\"WAIT_FOR_OTP\"] = \"WAIT_FOR_OTP\";\n PlaywrightAction[\"GEN_TOTP\"] = \"GEN_TOTP\";\n // Sequence marker actions (not real interactions, used only for grouping)\n PlaywrightAction[\"SEQUENCE_START\"] = \"SEQUENCE_START\";\n PlaywrightAction[\"SEQUENCE_END\"] = \"SEQUENCE_END\";\n })(PlaywrightAction || (PlaywrightAction = {}));\n\n /**\n * Checks if any string in the array matches the given regular expression pattern.\n *\n * @param array - Array of strings to test.\n * @param pattern - Regular expression to test against each string.\n * @returns true if at least one string matches the pattern, false otherwise.\n */\n function testArray(array, pattern) {\n return array.some(item => pattern.test(item));\n }\n /**\n * Determines if an element is clickable\n *\n * @param element The DOM element to check\n * @returns boolean indicating if the element is fillable\n */\n function isClickableElement(element) {\n if (!element)\n return false;\n let depth = 0;\n while (depth < 5 && element && element.nodeType === Node.ELEMENT_NODE) {\n if (isClickableElementHelper(element) === IsClickable.YES)\n return true;\n if (isClickableElementHelper(element) === IsClickable.NO)\n return false;\n // if maybe, continue searching up to 5 levels up the DOM tree\n element = element.parentNode;\n depth++;\n }\n return false;\n }\n // clickable element detection result\n var IsClickable;\n (function (IsClickable) {\n IsClickable[\"YES\"] = \"YES\";\n IsClickable[\"NO\"] = \"NO\";\n IsClickable[\"MAYBE\"] = \"MAYBE\";\n })(IsClickable || (IsClickable = {}));\n function isClickableElementHelper(element) {\n var _a, _b;\n if (!element)\n return IsClickable.NO;\n //check for tag name\n const tagName = element.tagName.toLowerCase();\n const clickableTags = [\n 'a', 'button',\n ];\n if (clickableTags.includes(tagName))\n return IsClickable.YES;\n //check for clickable <input>\n const inputType = (_a = element.type) === null || _a === void 0 ? void 0 : _a.toLowerCase();\n const clickableTypes = [\n 'button', 'submit', 'reset', 'checkbox', 'radio',\n ];\n const ariaAutocompleteValues = [\n 'list', 'both',\n ];\n if (tagName === 'input') {\n if (clickableTypes.includes(inputType) || ariaAutocompleteValues.includes((_b = element.getAttribute('aria-autocomplete')) !== null && _b !== void 0 ? _b : ''))\n return IsClickable.YES;\n if (['date', 'number', 'range'].includes(inputType))\n return IsClickable.NO; //don't record the click as a change event will be generated for elements that generate an input change event\n }\n // check for cursor type\n const style = window.getComputedStyle(element);\n if (style.cursor === 'pointer')\n return IsClickable.YES;\n // check for attributes\n const clickableRoles = [\n 'button', 'combobox', 'listbox', 'dropdown', 'option', 'menu', 'menuitem',\n 'navigation', 'checkbox', 'switch', 'toggle', 'slider', 'textbox', 'listitem',\n 'presentation',\n ];\n const ariaPopupValues = [\n 'true', 'listbox', 'menu',\n ];\n if (element.hasAttribute('onclick') ||\n clickableRoles.includes(element.getAttribute('role') || '') ||\n ariaPopupValues.includes(element.getAttribute('aria-haspopup') || ''))\n return IsClickable.YES;\n // check for tabindex (means element is focusable and therefore clickable)\n if (parseInt(element.getAttribute('tabindex') || '-1') >= 0)\n return IsClickable.YES;\n // extract class names\n const classNames = Array.from(element.classList);\n // check for checkbox/radio-like class name - TODO: check if can be removed\n const checkboxPattern = /checkbox|switch|toggle|slider/i;\n if (testArray(classNames, checkboxPattern))\n return IsClickable.YES;\n // check for Material UI class names\n const muiClickableClassPattern = /MuiButton|MuiIconButton|MuiChip|MuiMenuItem|MuiListItem|MuiInputBase|MuiOutlinedInput|MuiSelect|MuiAutocomplete|MuiToggleButton|MuiBackdrop-root|MuiBackdrop-invisible/;\n if (testArray(classNames, muiClickableClassPattern))\n return IsClickable.YES;\n // check for SalesForce class names\n const sfClassPattern = /slds-button|slds-dropdown|slds-combobox|slds-picklist|slds-tabs|slds-pill|slds-action|slds-row-action|slds-context-bar|slds-input|slds-rich-text-area|slds-radio|slds-checkbox|slds-toggle|slds-link|slds-accordion|slds-tree/;\n if (testArray(classNames, sfClassPattern))\n return IsClickable.YES;\n // check for chart dots\n const chartClickableClassPattern = /recharts-dot/;\n if (testArray(classNames, chartClickableClassPattern))\n return IsClickable.YES;\n // check for React component classes\n const reactClickableClassPattern = /react-select|ant-select|rc-select|react-dropdown|react-autocomplete|react-datepicker|react-modal|react-tooltip|react-popover|react-menu|react-tabs|react-accordion|react-collapse|react-toggle|react-switch|react-checkbox|react-radio|react-button|react-link|react-card|react-list-item|react-menu-item|react-option|react-tab|react-panel|react-drawer|react-sidebar|react-nav|react-breadcrumb|react-pagination|react-stepper|react-wizard|react-carousel|react-slider|react-range|react-progress|react-badge|react-chip|react-tag|react-avatar|react-icon|react-fab|react-speed-dial|react-floating|react-sticky|react-affix|react-backdrop|react-overlay|react-portal|react-transition|react-animate|react-spring|react-framer|react-gesture|react-drag|react-drop|react-sortable|react-resizable|react-split|react-grid|react-table|react-datagrid|react-tree|react-treeview|react-file|react-upload|react-cropper|react-image|react-gallery|react-lightbox|react-player|react-video|react-audio|react-chart|react-graph|react-diagram|react-flow|react-d3|react-plotly|react-vega|react-vis|react-nivo|react-recharts|react-victory|react-echarts|react-highcharts|react-google-charts|react-fusioncharts|react-apexcharts|react-chartjs|react-chartkick|react-sparklines|react-trend|react-smooth|react-animated|react-lottie|react-spring|react-framer-motion|react-pose|react-motion|react-transition-group|react-router|react-navigation/i;\n if (testArray(classNames, reactClickableClassPattern))\n return IsClickable.YES;\n //check for cloudinary class names\n const cloudinaryClickableClassPattern = /cld-combobox|cld-upload-button|cld-controls|cld-player|cld-tab|cld-menu-item|cld-close|cld-play|cld-pause|cld-fullscreen|cld-browse|cld-cancel|cld-retry/;\n if (testArray(classNames, cloudinaryClickableClassPattern))\n return IsClickable.YES;\n return IsClickable.MAYBE;\n }\n function getParentNode(element) {\n if (!element || element.nodeType !== Node.ELEMENT_NODE)\n return null;\n let parent = null;\n // SF is using slots and shadow DOM heavily\n // However, there might be slots in the light DOM which shouldn't be traversed\n if (element.assignedSlot && element.getRootNode() instanceof ShadowRoot)\n parent = element.assignedSlot;\n else\n parent = element.parentNode;\n // Check if we're at a shadow root\n if (parent && parent.nodeType !== Node.ELEMENT_NODE && parent.getRootNode() instanceof ShadowRoot)\n parent = parent.getRootNode().host;\n return parent;\n }\n function getElementDepth(element) {\n let depth = 0;\n let currentElement = element;\n while ((currentElement === null || currentElement === void 0 ? void 0 : currentElement.nodeType) === Node.ELEMENT_NODE) {\n depth++;\n currentElement = getParentNode(currentElement);\n }\n return depth;\n }\n\n // WebSocketsMessageType enum for WebSocket and event message types shared across the app\n var WebSocketsMessageType;\n (function (WebSocketsMessageType) {\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_PREPARE_START\"] = \"INTERACTION_APPLY_AI_PREPARE_START\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_PREPARE_SUCCESS\"] = \"INTERACTION_APPLY_AI_PREPARE_SUCCESS\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_PREPARE_ERROR\"] = \"INTERACTION_APPLY_AI_PREPARE_ERROR\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_SEND_TO_LLM_START\"] = \"INTERACTION_APPLY_AI_SEND_TO_LLM_START\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_SEND_TO_LLM_SUCCESS\"] = \"INTERACTION_APPLY_AI_SEND_TO_LLM_SUCCESS\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_SEND_TO_LLM_ERROR\"] = \"INTERACTION_APPLY_AI_SEND_TO_LLM_ERROR\";\n WebSocketsMessageType[\"INTERACTION_REPLAY_START\"] = \"INTERACTION_REPLAY_START\";\n WebSocketsMessageType[\"INTERACTION_REPLAY_SUCCESS\"] = \"INTERACTION_REPLAY_SUCCESS\";\n WebSocketsMessageType[\"INTERACTION_REPLAY_ERROR\"] = \"INTERACTION_REPLAY_ERROR\";\n WebSocketsMessageType[\"INTERACTION_REPLAY_CANCELLED\"] = \"INTERACTION_REPLAY_CANCELLED\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_CANCELLED\"] = \"INTERACTION_APPLY_AI_CANCELLED\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_ERROR\"] = \"INTERACTION_APPLY_AI_ERROR\";\n WebSocketsMessageType[\"INTERACTION_STEP_CREATED\"] = \"INTERACTION_STEP_CREATED\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_SUMMARY_COMPLETED\"] = \"INTERACTION_APPLY_AI_SUMMARY_COMPLETED\";\n WebSocketsMessageType[\"INTERACTION_APPLY_AI_SUMMARY_ERROR\"] = \"INTERACTION_APPLY_AI_SUMMARY_ERROR\";\n WebSocketsMessageType[\"OTP_RETRIEVED\"] = \"OTP_RETRIEVED\";\n WebSocketsMessageType[\"TEST_SUITE_RUN_START\"] = \"TEST_SUITE_RUN_START\";\n WebSocketsMessageType[\"TEST_SUITE_RUN_LOG\"] = \"TEST_SUITE_RUN_LOG\";\n WebSocketsMessageType[\"TEST_SUITE_RUN_COMPLETE\"] = \"TEST_SUITE_RUN_COMPLETE\";\n WebSocketsMessageType[\"TEST_SUITE_RUN_ERROR\"] = \"TEST_SUITE_RUN_ERROR\";\n WebSocketsMessageType[\"TEST_SUITE_RUN_REPORTER_EVENT\"] = \"TEST_SUITE_RUN_REPORTER_EVENT\";\n })(WebSocketsMessageType || (WebSocketsMessageType = {}));\n\n /**\n * Logging levels for Probo\n */\n var ProboLogLevel;\n (function (ProboLogLevel) {\n ProboLogLevel[\"DEBUG\"] = \"DEBUG\";\n ProboLogLevel[\"INFO\"] = \"INFO\";\n ProboLogLevel[\"LOG\"] = \"LOG\";\n ProboLogLevel[\"WARN\"] = \"WARN\";\n ProboLogLevel[\"ERROR\"] = \"ERROR\";\n })(ProboLogLevel || (ProboLogLevel = {}));\n const logLevelOrder = {\n [ProboLogLevel.DEBUG]: 0,\n [ProboLogLevel.INFO]: 1,\n [ProboLogLevel.LOG]: 2,\n [ProboLogLevel.WARN]: 3,\n [ProboLogLevel.ERROR]: 4,\n };\n class ProboLogger {\n constructor(prefix, level = ProboLogLevel.INFO) {\n this.prefix = prefix;\n this.level = level;\n }\n setLogLevel(level) {\n console.log(`[${this.prefix}] Setting log level to: ${level} (was: ${this.level})`);\n this.level = level;\n }\n shouldLog(level) {\n return logLevelOrder[level] >= logLevelOrder[this.level];\n }\n preamble(level) {\n const now = new Date();\n const hours = String(now.getHours()).padStart(2, '0');\n const minutes = String(now.getMinutes()).padStart(2, '0');\n const seconds = String(now.getSeconds()).padStart(2, '0');\n const milliseconds = String(now.getMilliseconds()).padStart(3, '0');\n return `[${hours}:${minutes}:${seconds}.${milliseconds}] [${this.prefix}] [${level}]`;\n }\n debug(...args) { if (this.shouldLog(ProboLogLevel.DEBUG))\n console.debug(this.preamble(ProboLogLevel.DEBUG), ...args); }\n info(...args) { if (this.shouldLog(ProboLogLevel.INFO))\n console.info(this.preamble(ProboLogLevel.INFO), ...args); }\n log(...args) { if (this.shouldLog(ProboLogLevel.LOG))\n console.log(this.preamble(ProboLogLevel.LOG), ...args); }\n warn(...args) { if (this.shouldLog(ProboLogLevel.WARN))\n console.warn(this.preamble(ProboLogLevel.WARN), ...args); }\n error(...args) { if (this.shouldLog(ProboLogLevel.ERROR))\n console.error(this.preamble(ProboLogLevel.ERROR), ...args); }\n }\n new ProboLogger('fetch');\n function doubleQuoteString(str) {\n if (!str)\n return '';\n return `\"${str.replace(/\"/g, '\\\\\"')}\"`;\n }\n\n new ProboLogger('apiclient');\n\n /**\n * Available AI models for LLM operations\n */\n var AIModel;\n (function (AIModel) {\n AIModel[\"AZURE_GPT4\"] = \"azure-gpt4\";\n AIModel[\"AZURE_GPT4_MINI\"] = \"azure-gpt4-mini\";\n AIModel[\"GEMINI_1_5_FLASH\"] = \"gemini-1.5-flash\";\n AIModel[\"GEMINI_2_5_FLASH\"] = \"gemini-2.5-flash\";\n AIModel[\"GPT4\"] = \"gpt4\";\n AIModel[\"GPT4_MINI\"] = \"gpt4-mini\";\n AIModel[\"CLAUDE_3_5\"] = \"claude-3.5\";\n AIModel[\"CLAUDE_SONNET_4_5\"] = \"claude-sonnet-4.5\";\n AIModel[\"CLAUDE_HAIKU_4_5\"] = \"claude-haiku-4.5\";\n AIModel[\"CLAUDE_OPUS_4_1\"] = \"claude-opus-4.1\";\n AIModel[\"GROK_2\"] = \"grok-2\";\n AIModel[\"LLAMA_4_SCOUT\"] = \"llama-4-scout\";\n AIModel[\"DEEPSEEK_V3\"] = \"deepseek-v3\";\n })(AIModel || (AIModel = {}));\n\n const highlighterLogger = new ProboLogger('highlighter');\n\n // Get text content of an element (recursively including child elements)\n function getElementText(element) {\n if (!element) return '';\n return element.textContent || '';\n }\n\n // Get placeholder text of an element\n function getElementPlaceholder(element) {\n if (!element) return '';\n return element.placeholder || '';\n }\n\n // Get CSS selector of an element (not recursively, just for a single element)\n function getElementCssSelector(element) {\n if (!(element instanceof Element)) return '';\n \n const tag = element.tagName.toLowerCase();\n let selector = tag;\n \n // Find nth-of-type for elements without ID\n let nth = 1;\n let sibling = element.previousElementSibling;\n while (sibling) {\n if (sibling.nodeName.toLowerCase() === tag) nth++;\n sibling = sibling.previousElementSibling;\n }\n if (nth > 1 || element.nextElementSibling) selector += `:nth-of-type(${nth})`;\n \n return selector;\n }\n\n // Helper function to check if element is a form control\n function isFormControl(elementInfo) {\n return /^(input|select|textarea|button|label)$/i.test(elementInfo.tag);\n }\n\n // Helper function to check if element is a dropdown item\n const isDropdownItem = (elementInfo) => {\n const dropdownPatterns = [\n /dropdown[-_]?item/i, // matches: dropdown-item, dropdownitem, dropdown_item\n /menu[-_]?item/i, // matches: menu-item, menuitem, menu_item\n /dropdown[-_]?link/i, // matches: dropdown-link, dropdownlink, dropdown_link\n /list[-_]?item/i, // matches: list-item, listitem, list_item\n /select[-_]?item/i, // matches: select-item, selectitem, select_item \n ];\n\n const rolePatterns = [\n /menu[-_]?item/i, // matches: menuitem, menu-item\n /option/i, // matches: option\n /list[-_]?item/i, // matches: listitem, list-item\n /tree[-_]?item/i // matches: treeitem, tree-item\n ];\n\n const hasMatchingClass = elementInfo.element.className && \n dropdownPatterns.some(pattern => \n pattern.test(elementInfo.element.className)\n );\n\n const hasMatchingRole = elementInfo.element.getAttribute('role') && \n rolePatterns.some(pattern => \n pattern.test(elementInfo.element.getAttribute('role'))\n );\n\n return hasMatchingClass || hasMatchingRole;\n };\n\n /**\n * Element Query Utilities\n */\n\n function getAllDocumentElementsIncludingShadow(selectors, root = document) {\n const elements = Array.from(root.querySelectorAll(selectors));\n\n root.querySelectorAll('*').forEach(el => {\n if (el.shadowRoot) {\n elements.push(...getAllDocumentElementsIncludingShadow(selectors, el.shadowRoot));\n }\n });\n return elements;\n }\n\n function getAllFrames(root = document) {\n const result = [root];\n const frames = getAllDocumentElementsIncludingShadow('frame, iframe', root); \n frames.forEach(frame => {\n try {\n const frameDocument = frame.contentDocument || frame.contentWindow.document;\n if (frameDocument) {\n result.push(frameDocument);\n }\n } catch (e) {\n // Skip cross-origin frames\n highlighterLogger.warn('Could not access frame content:', e.message);\n }\n });\n\n return result;\n }\n\n function getAllElementsIncludingShadow(selectors, root = document) {\n const elements = [];\n\n getAllFrames(root).forEach(doc => {\n elements.push(...getAllDocumentElementsIncludingShadow(selectors, doc));\n });\n\n return elements;\n }\n\n /**\n * Finds the first element matching a CSS selector, traversing Shadow DOM if necessary\n * @param {string} selector - CSS selector to search for\n * @param {Element} [root=document] - Root element to start searching from\n * @returns {Element|null} - The first matching element or null if not found\n */\n function robustQuerySelector(selector, root = document, all = false) {\n // First try to find in light DOM\n let elements = all ? root.querySelectorAll(selector) : root.querySelector(selector);\n if (elements) return elements;\n \n // Get all shadow roots\n const shadowElements = Array.from(root.querySelectorAll('*'))\n .filter(el => el.shadowRoot);\n \n // Search through each shadow root until we find a match\n for (const el of shadowElements) {\n elements = robustQuerySelector(selector, el.shadowRoot, all);\n if (elements) return elements;\n }\n \n return all ? [] : null;\n }\n\n\n function isDecendent(parent, child) {\n let element = child;\n while (element && element !== parent && element.nodeType === Node.ELEMENT_NODE) { \n element = getParentNode(element); \n }\n return element === parent;\n }\n\n function generateXPath(element) {\n return '/'+extractElementPath(element).map(item => `${item.tagName}${item.onlyChild ? '' : `[${item.index}]`}`).join('/');\n }\n\n function generateCssPath(element) {\n return extractElementPath(element).map(item => `${item.tagName}:nth-of-type(${item.index})`).join(' > ');\n }\n\n // unified path generation for xpath and css selector\n function extractElementPath(element) {\n if (!element) {\n highlighterLogger.error('ERROR: No element provided to generatePath');\n return [];\n }\n const path = [];\n // traversing up the DOM tree\n while (element && element.nodeType === Node.ELEMENT_NODE) { \n let tagName = element.nodeName.toLowerCase();\n \n let sibling = element;\n let index = 1;\n \n while (sibling = sibling.previousElementSibling) {\n if (sibling.nodeName.toLowerCase() === tagName) index++;\n }\n sibling = element;\n \n let onlyChild = (index === 1);\n while (onlyChild && (sibling = sibling.nextElementSibling)) {\n if (sibling.nodeName.toLowerCase() === tagName) onlyChild = false;\n }\n \n // add a tuple with tagName, index (nth), and onlyChild \n path.unshift({\n tagName: tagName,\n index: index,\n onlyChild: onlyChild \n }); \n\n element = getParentNode(element);\n }\n \n return path;\n }\n\n function cleanHTML(rawHTML) {\n const parser = new DOMParser();\n const doc = parser.parseFromString(rawHTML, \"text/html\");\n\n function cleanElement(element) {\n const allowedAttributes = new Set([\n \"role\",\n \"type\",\n \"class\",\n \"href\",\n \"alt\",\n \"title\",\n \"readonly\",\n \"checked\",\n \"enabled\",\n \"disabled\",\n ]);\n\n [...element.attributes].forEach(attr => {\n const name = attr.name.toLowerCase();\n const value = attr.value;\n\n const isTestAttribute = /^(testid|test-id|data-test-id)$/.test(name);\n const isDataAttribute = name.startsWith(\"data-\") && value;\n const isBooleanAttribute = [\"readonly\", \"checked\", \"enabled\", \"disabled\"].includes(name);\n\n if (!allowedAttributes.has(name) && !isDataAttribute && !isTestAttribute && !isBooleanAttribute) {\n element.removeAttribute(name);\n }\n });\n\n // Handle SVG content - more aggressive replacement\n if (element.tagName.toLowerCase() === \"svg\") {\n // Remove all attributes except class and role\n [...element.attributes].forEach(attr => {\n const name = attr.name.toLowerCase();\n if (name !== \"class\" && name !== \"role\") {\n element.removeAttribute(name);\n }\n });\n element.innerHTML = \"CONTENT REMOVED\";\n } else {\n // Recursively clean child elements\n Array.from(element.children).forEach(cleanElement);\n }\n\n // Only remove empty elements that aren't semantic or icon elements\n const keepEmptyElements = ['i', 'span', 'svg', 'button', 'input'];\n if (!keepEmptyElements.includes(element.tagName.toLowerCase()) && \n !element.children.length && \n !element.textContent.trim()) {\n element.remove();\n }\n }\n\n // Process all elements in the document body\n Array.from(doc.body.children).forEach(cleanElement);\n return doc.body.innerHTML;\n }\n\n function getContainingIFrame(element) {\n // If not in an iframe, return null\n if (element.ownerDocument.defaultView === window.top) {\n return null;\n }\n \n // Try to find the iframe in the parent document that contains our element\n try {\n const parentDocument = element.ownerDocument.defaultView.parent.document;\n const iframes = parentDocument.querySelectorAll('iframe');\n \n for (const iframe of iframes) {\n if (iframe.contentWindow === element.ownerDocument.defaultView) {\n return iframe;\n }\n }\n } catch (e) {\n // Cross-origin restriction\n return \"Cross-origin iframe - cannot access details\";\n }\n \n return null;\n }\n\n function getAriaLabelledByText(elementInfo, includeHidden=true) {\n if (!elementInfo.element.hasAttribute('aria-labelledby')) return '';\n\n const ids = elementInfo.element.getAttribute('aria-labelledby').split(/\\s+/);\n let labelText = '';\n\n //locate root (document or iFrame document if element is contained in an iframe)\n let root = document;\n if (elementInfo.iframe_selector) { \n const frames = getAllDocumentElementsIncludingShadow('iframe', document);\n \n // Iterate over all frames and compare their CSS selectors\n for (const frame of frames) {\n const selector = generateCssPath(frame);\n if (selector === elementInfo.iframe_selector) {\n root = frame.contentDocument || frame.contentWindow.document; \n break;\n }\n } \n }\n\n ids.forEach(id => {\n const el = robustQuerySelector(`#${CSS.escape(id)}`, root);\n if (el) {\n if (includeHidden || el.offsetParent !== null || getComputedStyle(el).display !== 'none') {\n labelText += el.textContent.trim() + ' ';\n }\n }\n });\n\n return labelText.trim();\n }\n\n\n\n const filterZeroDimensions = (elementInfo) => {\n const rect = elementInfo.bounding_box;\n //single pixel elements are typically faux controls and should be filtered too\n const hasSize = rect.width > 1 && rect.height > 1;\n const style = window.getComputedStyle(elementInfo.element);\n const isVisible = style.display !== 'none' && style.visibility !== 'hidden';\n \n if (!hasSize || !isVisible) {\n \n return false;\n }\n return true;\n };\n\n function filterNestedElements(nonZeroElements, parentCandidates, shouldKeepNestedElementFn) {\n /**\n * Filter elements based on parent/child relationships.\n * @param {Array} nonZeroElements - Elements sorted by depth (parents first)\n * @param {Set} parentCandidates - Set of all candidate parent CSS selectors (all nonZeroElements)\n * @param {Function} shouldKeepNestedElementFn - Function(element_info, parentPath, parentElementInfo) => boolean\n * @returns {Array} Filtered elements\n */\n return nonZeroElements.filter(element_info => {\n const parent = findClosestParent(parentCandidates, element_info);\n \n if (parent == null) {\n // No parent found, keep element\n return true;\n }\n \n // Find parent element_info\n const parentElementInfo = nonZeroElements.find(e => e.css_selector === parent);\n \n // Use custom function to determine if we should keep nested element\n return shouldKeepNestedElementFn(element_info, parent, parentElementInfo);\n });\n }\n\n function getDirectHandlers(element) {\n /**\n * Get direct handlers for an element (no bubbling check).\n * Returns array of handler objects.\n */\n const handlers = [];\n \n // Check onclick\n if (element.hasAttribute('onclick') || element.onclick) {\n handlers.push({\n type: 'onclick',\n source: element.hasAttribute('onclick') ? 'attribute' : 'property',\n value: element.getAttribute('onclick') || 'function'\n });\n }\n \n // Check React Fiber\n const reactKey = Object.keys(element).find(key => \n key.startsWith('__reactFiber') || key.startsWith('__reactInternalInstance')\n );\n if (reactKey) {\n const fiber = element[reactKey];\n if (fiber?.memoizedProps?.onClick || fiber?.pendingProps?.onClick) {\n handlers.push({\n type: 'react-onClick',\n source: 'react-fiber',\n hasMemoized: !!fiber?.memoizedProps?.onClick,\n hasPending: !!fiber?.pendingProps?.onClick\n });\n }\n }\n \n return handlers;\n }\n\n function getElementHandlersWithBubbling(element, depth = 0) {\n /**\n * Get handler info including bubbling (recursive DOM traversal).\n * Uses actual DOM relationships (parentElement) instead of CSS selector parsing.\n * Cursor uses getComputedStyle() which already includes inheritance.\n * @param {HTMLElement} element - The element to check\n * @param {number} depth - Recursion depth (safety limit)\n */\n // Safety check: null/undefined element\n if (!element) {\n return { handlers: [], cursorPointer: false, handlerSource: 'none' };\n }\n \n // Safety check: prevent infinite recursion (circular parent references)\n if (depth > 100) {\n throw new Error(`Recursion depth limit exceeded (${depth}) in getElementHandlersWithBubbling. Possible circular parent reference. Element: ${element.tagName || 'unknown'}`);\n }\n \n const directHandlers = getDirectHandlers(element);\n \n // If element has direct handlers, return them\n if (directHandlers.length > 0) {\n // Cursor: getComputedStyle already includes inheritance!\n let cursorPointer = false;\n try {\n const style = window.getComputedStyle(element);\n cursorPointer = style.cursor === 'pointer';\n } catch (e) {\n // getComputedStyle can fail in edge cases (e.g., detached elements)\n // Default to false\n }\n \n return {\n handlers: directHandlers,\n cursorPointer: cursorPointer,\n handlerSource: 'direct'\n };\n }\n \n // No direct handlers - check parent for bubbled handlers (using DOM, not CSS selectors)\n if (element.parentElement) {\n const parentResult = getElementHandlersWithBubbling(element.parentElement, depth + 1);\n if (parentResult.handlers.length > 0) {\n // Parent has handlers that would bubble to this element\n // Cursor: getComputedStyle already includes inheritance!\n let cursorPointer = false;\n try {\n const style = window.getComputedStyle(element);\n cursorPointer = style.cursor === 'pointer';\n } catch (e) {\n // getComputedStyle can fail in edge cases (e.g., detached elements)\n // Default to false\n }\n \n return {\n handlers: parentResult.handlers.map(h => ({\n ...h,\n source: 'bubbled'\n })),\n cursorPointer: cursorPointer,\n handlerSource: 'bubbled'\n };\n }\n }\n \n // No handlers at all\n let cursorPointer = false;\n try {\n const style = window.getComputedStyle(element);\n cursorPointer = style.cursor === 'pointer';\n } catch (e) {\n // getComputedStyle can fail in edge cases (e.g., detached elements)\n // Default to false\n }\n \n return {\n handlers: [],\n cursorPointer: cursorPointer,\n handlerSource: 'none'\n };\n }\n\n function normalizeHandlers(handlers) {\n /**\n * Normalize handlers for comparison (ignore source field, deduplicate).\n * Returns sorted array of unique normalized handler objects.\n */\n const seen = new Set();\n const normalized = [];\n \n for (const h of handlers) {\n // Safety check: skip malformed handlers\n if (!h || !h.type) continue;\n \n const key = h.type === 'react-onClick' \n ? 'react-onClick' \n : `${h.type}:${h.value || 'function'}`;\n \n if (!seen.has(key)) {\n seen.add(key);\n normalized.push({\n type: h.type,\n value: h.type === 'react-onClick' ? undefined : (h.value || 'function')\n });\n }\n }\n \n return normalized.sort((a, b) => {\n if (a.type !== b.type) return a.type.localeCompare(b.type);\n return (a.value || '').localeCompare(b.value || '');\n });\n }\n\n function compareHandlersForUniquify(childHandlers, parentHandlers) {\n /**\n * Compare handlers between child and parent for uniquification.\n * Returns true if handlers are different (should keep child), false if same (can unify).\n */\n const childNormalized = normalizeHandlers(childHandlers.handlers);\n const parentNormalized = normalizeHandlers(parentHandlers.handlers);\n \n const handlersEqual = JSON.stringify(childNormalized) === JSON.stringify(parentNormalized);\n const cursorEqual = childHandlers.cursorPointer === parentHandlers.cursorPointer;\n \n // If handlers or cursor differ, keep child (don't unify)\n return !handlersEqual || !cursorEqual;\n }\n\n function uniquifyElements(elements) {\n highlighterLogger.debug(`Starting uniquification with ${elements.length} elements`);\n\n // Filter out testing infrastructure elements first\n const filteredInfrastructure = elements.filter(element_info => {\n // Skip the highlight-overlay element completely - it's part of the testing infrastructure\n if (element_info.element.id === 'highlight-overlay' || \n (element_info.css_selector && element_info.css_selector.includes('#highlight-overlay'))) {\n highlighterLogger.debug('Filtered out testing infrastructure element:', element_info.css_selector);\n return false;\n }\n \n // Filter out UI framework container/manager elements\n const el = element_info.element;\n // UI framework container checks - generic detection for any framework\n if ((el.getAttribute('data-rendered-by') || \n el.getAttribute('data-reactroot') || \n el.getAttribute('ng-version') || \n el.getAttribute('data-component-id') ||\n el.getAttribute('data-root') ||\n el.getAttribute('data-framework')) && \n (el.className && \n typeof el.className === 'string' && \n (el.className.includes('Container') || \n el.className.includes('container') || \n el.className.includes('Manager') || \n el.className.includes('manager')))) {\n highlighterLogger.debug('Filtered out UI framework container element:', element_info.css_selector);\n return false;\n }\n \n // Direct filter for framework container elements that shouldn't be interactive\n // Consolidating multiple container detection patterns into one efficient check\n const isFullViewport = element_info.bounding_box && \n element_info.bounding_box.x <= 5 && \n element_info.bounding_box.y <= 5 && \n element_info.bounding_box.width >= (window.innerWidth * 0.95) && \n element_info.bounding_box.height >= (window.innerHeight * 0.95);\n \n // Empty content check\n const isEmpty = !el.innerText || el.innerText.trim() === '';\n \n // Check if it's a framework container element\n if (element_info.element.tagName === 'DIV' && \n isFullViewport && \n isEmpty && \n (\n // Pattern matching for root containers\n (element_info.xpath && \n (element_info.xpath.match(/^\\/html\\[\\d+\\]\\/body\\[\\d+\\]\\/div\\[\\d+\\]\\/div\\[\\d+\\]$/) || \n element_info.xpath.match(/^\\/\\/\\*\\[@id='[^']+'\\]\\/div\\[\\d+\\]$/))) ||\n \n // Simple DOM structure\n (element_info.css_selector.split(' > ').length <= 4 && element_info.depth <= 5) ||\n \n // Empty or container-like classes\n (!el.className || el.className === '' || \n (typeof el.className === 'string' && \n (el.className.includes('overlay') || \n el.className.includes('container') || \n el.className.includes('wrapper'))))\n )) {\n highlighterLogger.debug('Filtered out framework container element:', element_info.css_selector);\n return false;\n }\n \n return true;\n });\n\n // First filter out elements with zero dimensions\n const nonZeroElements = filteredInfrastructure.filter(filterZeroDimensions);\n // sort by CSS selector depth so parents are processed first\n nonZeroElements.sort((a, b) => a.depth - b.depth);\n highlighterLogger.debug(`After dimension filtering: ${nonZeroElements.length} elements remain (${elements.length - nonZeroElements.length} removed)`);\n \n // Create parent candidate set with ALL nonZeroElements (before filtering)\n // This allows findClosestParent to find any element as a parent, even if it gets filtered out later\n const parentCandidates = new Set(nonZeroElements.map(e => e.css_selector));\n \n // Filter nested elements using handler comparison and standard logic\n const filteredByParent = filterNestedElements(nonZeroElements, parentCandidates, (element_info, parent, parentElementInfo) => {\n return shouldKeepNestedElement(element_info, parent, parentElementInfo);\n });\n\n highlighterLogger.debug(`After parent/child filtering: ${filteredByParent.length} elements remain (${nonZeroElements.length - filteredByParent.length} removed)`);\n\n // Final overlap filtering\n const filteredResults = filteredByParent.filter(element => {\n\n // Look for any element that came BEFORE this one in the array\n const hasEarlierOverlap = filteredByParent.some(other => {\n // Only check elements that came before (lower index)\n if (filteredByParent.indexOf(other) >= filteredByParent.indexOf(element)) {\n return false;\n }\n \n const isOverlapping = areElementsOverlapping(element, other); \n return isOverlapping;\n }); \n\n // Keep element if it has no earlier overlapping elements\n return !hasEarlierOverlap;\n });\n \n \n \n // Check for overlay removal\n highlighterLogger.debug(`After filtering: ${filteredResults.length} (${filteredByParent.length - filteredResults.length} removed by overlap)`);\n \n const nonOverlaidElements = filteredResults.filter(element => {\n return !isOverlaid(element);\n });\n\n highlighterLogger.debug(`Final elements after overlay removal: ${nonOverlaidElements.length} (${filteredResults.length - nonOverlaidElements.length} removed)`);\n \n return nonOverlaidElements;\n\n }\n\n\n\n const areElementsOverlapping = (element1, element2) => {\n if (element1.css_selector === element2.css_selector) {\n return true;\n }\n \n const box1 = element1.bounding_box;\n const box2 = element2.bounding_box;\n \n return box1.x === box2.x &&\n box1.y === box2.y &&\n box1.width === box2.width &&\n box1.height === box2.height;\n // element1.text === element2.text &&\n // element2.tag === 'a';\n };\n\n function findClosestParent(parentCandidates, element_info) { \n // Split the CSS selector into segments\n const segments = element_info.css_selector.split(' > ');\n \n // Try increasingly shorter paths until we find one in the parentCandidates set\n for (let i = segments.length - 1; i > 0; i--) {\n const parentPath = segments.slice(0, i).join(' > ');\n if (parentCandidates.has(parentPath)) {\n return parentPath;\n }\n }\n\n return null;\n }\n\n function shouldKeepNestedElement(elementInfo, parentPath, parentElementInfo) {\n // Check special cases FIRST (before handler comparison)\n const parentSegments = parentPath.split(' > ');\n\n // If parent is a link, don't keep child\n const isParentLink = /^a(:nth-of-type\\(\\d+\\))?$/.test(parentSegments[parentSegments.length - 1]);\n if (isParentLink) {\n return false; \n }\n \n // If this is a checkbox/radio input inside a label, don't keep the input (keep label instead)\n if (elementInfo.tag === 'input' && \n (elementInfo.type === 'checkbox' || elementInfo.type === 'radio')) {\n const isParentLabel = /^label(:nth-of-type\\(\\d+\\))?$/.test(parentSegments[parentSegments.length - 1]);\n if (isParentLabel) {\n return false;\n }\n }\n \n // Now check if handlers differ (only if special cases don't apply)\n if (parentElementInfo) {\n const childHandlers = getElementHandlersWithBubbling(elementInfo.element);\n const parentHandlers = getElementHandlersWithBubbling(parentElementInfo.element);\n \n // If handlers differ, keep child (don't unify)\n if (compareHandlersForUniquify(childHandlers, parentHandlers)) {\n return true;\n }\n }\n \n return isFormControl(elementInfo) || isDropdownItem(elementInfo) || isTableCell(elementInfo);\n }\n\n function isTableCell(elementInfo) {\n const element = elementInfo.element;\n if(!element || !(element instanceof HTMLElement)) {\n return false;\n }\n const validTags = new Set(['td', 'th']);\n const validRoles = new Set(['cell', 'gridcell', 'columnheader', 'rowheader']);\n \n const tag = element.tagName.toLowerCase();\n const role = element.getAttribute('role')?.toLowerCase();\n\n if (validTags.has(tag) || (role && validRoles.has(role))) {\n return true;\n }\n return false;\n \n }\n\n function isOverlaid(elementInfo) {\n const element = elementInfo.element;\n const boundingRect = elementInfo.bounding_box;\n \n\n \n \n // Create a diagnostic logging function that only logs when needed\n const diagnosticLog = (...args) => {\n { // set to true for debugging\n highlighterLogger.debug('[OVERLAY-DEBUG]', ...args);\n }\n };\n\n // Special handling for tooltips\n if (elementInfo.element.className && typeof elementInfo.element.className === 'string' && \n elementInfo.element.className.includes('tooltip')) {\n diagnosticLog('Element is a tooltip, not considering it overlaid');\n return false;\n }\n \n \n \n // Get element at the center point to check if it's covered by a popup/modal\n const middleX = boundingRect.x + boundingRect.width/2;\n const middleY = boundingRect.y + boundingRect.height/2;\n const elementAtMiddle = element.ownerDocument.elementFromPoint(middleX, middleY);\n \n if (elementAtMiddle && \n elementAtMiddle !== element && \n !isDecendent(element, elementAtMiddle) && \n !isDecendent(elementAtMiddle, element)) {\n\n \n return true;\n }\n \n \n return false;\n \n }\n\n /**\n * Checks if an element is scrollable (has scrollable content)\n * \n * @param element - The element to check\n * @returns boolean indicating if the element is scrollable\n */\n function isScrollableContainer(element) {\n if (!element) return false;\n \n const style = window.getComputedStyle(element);\n \n // Reliable way to detect if an element has scrollbars or is scrollable\n const hasScrollHeight = element.scrollHeight > element.clientHeight;\n const hasScrollWidth = element.scrollWidth > element.clientWidth;\n \n // Check actual style properties\n const hasOverflowY = style.overflowY === 'auto' || \n style.overflowY === 'scroll' || \n style.overflowY === 'overlay';\n const hasOverflowX = style.overflowX === 'auto' || \n style.overflowX === 'scroll' || \n style.overflowX === 'overlay';\n \n // Check common class names and attributes for scrollable containers across frameworks\n const hasScrollClasses = element.classList.contains('scroll') || \n element.classList.contains('scrollable') ||\n element.classList.contains('overflow') ||\n element.classList.contains('overflow-auto') ||\n element.classList.contains('overflow-scroll') ||\n element.getAttribute('data-scrollable') === 'true';\n \n // Check for height/max-height constraints that often indicate scrolling content\n const hasHeightConstraint = style.maxHeight && \n style.maxHeight !== 'none' && \n style.maxHeight !== 'auto';\n \n // An element is scrollable if it has:\n // 1. Actual scrollbars in use (most reliable check) OR\n // 2. Overflow styles allowing scrolling AND content that would require scrolling\n return (hasScrollHeight && hasOverflowY) || \n (hasScrollWidth && hasOverflowX) ||\n (hasScrollClasses && (hasScrollHeight || hasScrollWidth)) ||\n (hasHeightConstraint && hasScrollHeight);\n }\n\n /**\n * Detects scrollable containers that are ancestors of the target element\n * \n * This function traverses up the DOM tree from the target element and identifies\n * all scrollable containers (elements that have scrollable content).\n * \n * @param target - The target element to start the search from\n * @returns Array of objects with selector and scroll properties\n */\n function detectScrollableContainers(target) {\n const scrollableContainers = [];\n \n if (!target) {\n return scrollableContainers;\n }\n \n highlighterLogger.debug('🔍 [detectScrollableContainers] Starting detection for target:', target.tagName, target.id, target.className);\n \n // Detect if target is inside an iframe\n const iframe = getContainingIFrame(target);\n const iframe_selector = iframe ? generateCssPath(iframe) : \"\";\n \n highlighterLogger.debug('🔍 [detectScrollableContainers] Iframe context:', iframe ? 'inside iframe' : 'main document', 'selector:', iframe_selector);\n \n // Start from the target element and traverse up the DOM tree\n let currentElement = target;\n let depth = 0;\n const MAX_DEPTH = 10; // Limit traversal depth to avoid infinite loops\n \n while (currentElement && currentElement.nodeType === Node.ELEMENT_NODE && depth < MAX_DEPTH) { \n // Check if the current element is scrollable\n if (isScrollableContainer(currentElement)) {\n highlighterLogger.debug('🔍 [detectScrollableContainers] Found scrollable container at depth', depth, ':', currentElement.tagName, currentElement.id, currentElement.className);\n \n const container = {\n containerEl: currentElement,\n selector: generateCssPath(currentElement),\n iframe_selector: iframe_selector,\n scrollTop: currentElement.scrollTop,\n scrollLeft: currentElement.scrollLeft,\n scrollHeight: currentElement.scrollHeight,\n scrollWidth: currentElement.scrollWidth,\n clientHeight: currentElement.clientHeight,\n clientWidth: currentElement.clientWidth\n };\n \n scrollableContainers.push(container);\n }\n \n // Move to parent element\n currentElement = getParentNode(currentElement);\n \n depth++;\n }\n \n highlighterLogger.debug('🔍 [detectScrollableContainers] Detection complete. Found', scrollableContainers.length, 'scrollable containers');\n return scrollableContainers;\n }\n\n class DOMSerializer {\n constructor(options = {}) {\n this.options = {\n includeStyles: true,\n includeScripts: false, // Security consideration\n includeFrames: true,\n includeShadowDOM: true,\n maxDepth: 50,\n ...options\n };\n this.serializedFrames = new Map();\n this.shadowRoots = new Map();\n }\n \n /**\n * Serialize a complete document or element\n */\n serialize(rootElement = document) {\n try {\n const serialized = {\n type: 'document',\n doctype: this.serializeDoctype(rootElement),\n documentElement: this.serializeElement(rootElement.documentElement || rootElement),\n frames: [],\n timestamp: Date.now(),\n url: rootElement.URL || window.location?.href,\n metadata: {\n title: rootElement.title,\n charset: rootElement.characterSet,\n contentType: rootElement.contentType\n }\n };\n \n // Serialize frames and iframes if enabled\n if (this.options.includeFrames) {\n serialized.frames = this.serializeFrames(rootElement);\n }\n \n return serialized;\n } catch (error) {\n console.error('Serialization error:', error);\n throw new Error(`DOM serialization failed: ${error.message}`);\n }\n }\n \n /**\n * Serialize document type declaration\n */\n serializeDoctype(doc) {\n if (!doc.doctype) return null;\n \n return {\n name: doc.doctype.name,\n publicId: doc.doctype.publicId,\n systemId: doc.doctype.systemId\n };\n }\n \n /**\n * Serialize an individual element and its children\n */\n serializeElement(element, depth = 0) {\n if (depth > this.options.maxDepth) {\n return { type: 'text', content: '<!-- Max depth exceeded -->' };\n }\n \n const nodeType = element.nodeType;\n \n switch (nodeType) {\n case Node.ELEMENT_NODE:\n return this.serializeElementNode(element, depth);\n case Node.TEXT_NODE:\n return this.serializeTextNode(element);\n case Node.COMMENT_NODE:\n return this.serializeCommentNode(element);\n case Node.DOCUMENT_FRAGMENT_NODE:\n return this.serializeDocumentFragment(element, depth);\n default:\n return null;\n }\n }\n \n /**\n * Serialize element node with attributes and children\n */\n serializeElementNode(element, depth) {\n const tagName = element.tagName.toLowerCase();\n \n // Skip script tags for security unless explicitly enabled\n if (tagName === 'script' && !this.options.includeScripts) {\n return { type: 'comment', content: '<!-- Script tag removed for security -->' };\n }\n \n const serialized = {\n type: 'element',\n tagName: tagName,\n attributes: this.serializeAttributes(element),\n children: [],\n shadowRoot: null\n };\n \n // Handle Shadow DOM\n if (this.options.includeShadowDOM && element.shadowRoot) {\n serialized.shadowRoot = this.serializeShadowRoot(element.shadowRoot, depth + 1);\n }\n \n // Handle special elements\n if (tagName === 'iframe' || tagName === 'frame') {\n serialized.frameData = this.serializeFrameElement(element);\n }\n \n // Serialize children\n for (const child of element.childNodes) {\n const serializedChild = this.serializeElement(child, depth + 1);\n if (serializedChild) {\n serialized.children.push(serializedChild);\n }\n }\n \n // Include computed styles if enabled\n if (this.options.includeStyles && element.nodeType === Node.ELEMENT_NODE) {\n serialized.computedStyle = this.serializeComputedStyle(element);\n }\n \n return serialized;\n }\n \n /**\n * Serialize element attributes\n */\n serializeAttributes(element) {\n const attributes = {};\n \n if (element.attributes) {\n for (const attr of element.attributes) {\n attributes[attr.name] = attr.value;\n }\n }\n \n return attributes;\n }\n \n /**\n * Serialize computed styles\n */\n serializeComputedStyle(element) {\n try {\n const computedStyle = window.getComputedStyle(element);\n const styles = {};\n \n // Only serialize non-default values to reduce size\n const importantStyles = [\n 'display', 'position', 'width', 'height', 'margin', 'padding',\n 'border', 'background', 'color', 'font-family', 'font-size',\n 'text-align', 'visibility', 'z-index', 'transform'\n ];\n \n for (const prop of importantStyles) {\n const value = computedStyle.getPropertyValue(prop);\n if (value && value !== 'initial' && value !== 'normal') {\n styles[prop] = value;\n }\n }\n \n return styles;\n } catch (error) {\n return {};\n }\n }\n \n /**\n * Serialize text node\n */\n serializeTextNode(node) {\n return {\n type: 'text',\n content: node.textContent\n };\n }\n \n /**\n * Serialize comment node\n */\n serializeCommentNode(node) {\n return {\n type: 'comment',\n content: node.textContent\n };\n }\n \n /**\n * Serialize document fragment\n */\n serializeDocumentFragment(fragment, depth) {\n const serialized = {\n type: 'fragment',\n children: []\n };\n \n for (const child of fragment.childNodes) {\n const serializedChild = this.serializeElement(child, depth + 1);\n if (serializedChild) {\n serialized.children.push(serializedChild);\n }\n }\n \n return serialized;\n }\n \n /**\n * Serialize Shadow DOM\n */\n serializeShadowRoot(shadowRoot, depth) {\n const serialized = {\n type: 'shadowRoot',\n mode: shadowRoot.mode,\n children: []\n };\n \n for (const child of shadowRoot.childNodes) {\n const serializedChild = this.serializeElement(child, depth + 1);\n if (serializedChild) {\n serialized.children.push(serializedChild);\n }\n }\n \n return serialized;\n }\n \n /**\n * Serialize frame/iframe elements\n */\n serializeFrameElement(frameElement) {\n const frameData = {\n src: frameElement.src,\n name: frameElement.name,\n id: frameElement.id,\n sandbox: frameElement.sandbox?.toString() || '',\n allowfullscreen: frameElement.allowFullscreen\n };\n \n // Try to access frame content (may fail due to CORS)\n try {\n const frameDoc = frameElement.contentDocument;\n if (frameDoc && this.options.includeFrames) {\n frameData.content = this.serialize(frameDoc);\n }\n } catch (error) {\n frameData.accessError = 'Cross-origin frame content not accessible';\n }\n \n return frameData;\n }\n \n /**\n * Serialize all frames in document\n */\n serializeFrames(doc) {\n const frames = [];\n const frameElements = doc.querySelectorAll('iframe, frame');\n \n for (const frameElement of frameElements) {\n try {\n const frameDoc = frameElement.contentDocument;\n if (frameDoc) {\n frames.push({\n element: this.serializeElement(frameElement),\n content: this.serialize(frameDoc)\n });\n }\n } catch (error) {\n frames.push({\n element: this.serializeElement(frameElement),\n error: 'Frame content not accessible'\n });\n }\n }\n \n return frames;\n }\n \n /**\n * Deserialize serialized DOM data back to DOM nodes\n */\n deserialize(serializedData, targetDocument = document) {\n try {\n if (serializedData.type === 'document') {\n return this.deserializeDocument(serializedData, targetDocument);\n } else {\n return this.deserializeElement(serializedData, targetDocument);\n }\n } catch (error) {\n console.error('Deserialization error:', error);\n throw new Error(`DOM deserialization failed: ${error.message}`);\n }\n }\n \n /**\n * Deserialize complete document\n */\n deserializeDocument(serializedDoc, targetDoc) {\n // Create new document if needed\n const doc = targetDoc || document.implementation.createHTMLDocument();\n \n // Set doctype if present\n if (serializedDoc.doctype) {\n const doctype = document.implementation.createDocumentType(\n serializedDoc.doctype.name,\n serializedDoc.doctype.publicId,\n serializedDoc.doctype.systemId\n );\n doc.replaceChild(doctype, doc.doctype);\n }\n \n // Deserialize document element\n if (serializedDoc.documentElement) {\n const newDocElement = this.deserializeElement(serializedDoc.documentElement, doc);\n doc.replaceChild(newDocElement, doc.documentElement);\n }\n \n // Handle metadata\n if (serializedDoc.metadata) {\n doc.title = serializedDoc.metadata.title || '';\n }\n \n return doc;\n }\n \n /**\n * Deserialize individual element\n */\n deserializeElement(serializedNode, doc) {\n switch (serializedNode.type) {\n case 'element':\n return this.deserializeElementNode(serializedNode, doc);\n case 'text':\n return doc.createTextNode(serializedNode.content);\n case 'comment':\n return doc.createComment(serializedNode.content);\n case 'fragment':\n return this.deserializeDocumentFragment(serializedNode, doc);\n case 'shadowRoot':\n // Shadow roots are handled during element creation\n return null;\n default:\n return null;\n }\n }\n \n /**\n * Deserialize element node\n */\n deserializeElementNode(serializedElement, doc) {\n const element = doc.createElement(serializedElement.tagName);\n \n // Set attributes\n if (serializedElement.attributes) {\n for (const [name, value] of Object.entries(serializedElement.attributes)) {\n try {\n element.setAttribute(name, value);\n } catch (error) {\n console.warn(`Failed to set attribute ${name}:`, error);\n }\n }\n }\n \n // Apply computed styles if available\n if (serializedElement.computedStyle && this.options.includeStyles) {\n for (const [prop, value] of Object.entries(serializedElement.computedStyle)) {\n try {\n element.style.setProperty(prop, value);\n } catch (error) {\n console.warn(`Failed to set style ${prop}:`, error);\n }\n }\n }\n \n // Create shadow root if present\n if (serializedElement.shadowRoot && element.attachShadow) {\n try {\n const shadowRoot = element.attachShadow({ \n mode: serializedElement.shadowRoot.mode || 'open' \n });\n \n // Deserialize shadow root children\n for (const child of serializedElement.shadowRoot.children) {\n const childElement = this.deserializeElement(child, doc);\n if (childElement) {\n shadowRoot.appendChild(childElement);\n }\n }\n } catch (error) {\n console.warn('Failed to create shadow root:', error);\n }\n }\n \n // Deserialize children\n if (serializedElement.children) {\n for (const child of serializedElement.children) {\n const childElement = this.deserializeElement(child, doc);\n if (childElement) {\n element.appendChild(childElement);\n }\n }\n }\n \n // Handle frame content\n if (serializedElement.frameData && serializedElement.frameData.content) {\n // Frame content deserialization would happen after the frame loads\n element.addEventListener('load', () => {\n try {\n const frameDoc = element.contentDocument;\n if (frameDoc) {\n this.deserializeDocument(serializedElement.frameData.content, frameDoc);\n }\n } catch (error) {\n console.warn('Failed to deserialize frame content:', error);\n }\n });\n }\n \n return element;\n }\n \n /**\n * Deserialize document fragment\n */\n deserializeDocumentFragment(serializedFragment, doc) {\n const fragment = doc.createDocumentFragment();\n \n if (serializedFragment.children) {\n for (const child of serializedFragment.children) {\n const childElement = this.deserializeElement(child, doc);\n if (childElement) {\n fragment.appendChild(childElement);\n }\n }\n }\n \n return fragment;\n }\n }\n \n // Usage example and utility functions\n class DOMUtils {\n /**\n * Create serializer with common presets\n */\n static createSerializer(preset = 'default') {\n const presets = {\n default: {\n includeStyles: true,\n includeScripts: false,\n includeFrames: true,\n includeShadowDOM: true\n },\n minimal: {\n includeStyles: false,\n includeScripts: false,\n includeFrames: false,\n includeShadowDOM: false\n },\n complete: {\n includeStyles: true,\n includeScripts: true,\n includeFrames: true,\n includeShadowDOM: true\n },\n secure: {\n includeStyles: true,\n includeScripts: false,\n includeFrames: false,\n includeShadowDOM: true\n }\n };\n \n return new DOMSerializer(presets[preset] || presets.default);\n }\n \n /**\n * Serialize DOM to JSON string\n */\n static serializeToJSON(element, options) {\n const serializer = new DOMSerializer(options);\n const serialized = serializer.serialize(element);\n return JSON.stringify(serialized, null, 2);\n }\n \n /**\n * Deserialize from JSON string\n */\n static deserializeFromJSON(jsonString, targetDocument) {\n const serialized = JSON.parse(jsonString);\n const serializer = new DOMSerializer();\n return serializer.deserialize(serialized, targetDocument);\n }\n \n /**\n * Clone DOM with full fidelity including Shadow DOM\n */\n static deepClone(element, options) {\n const serializer = new DOMSerializer(options);\n const serialized = serializer.serialize(element);\n return serializer.deserialize(serialized, element.ownerDocument);\n }\n \n /**\n * Compare two DOM structures\n */\n static compare(element1, element2, options) {\n const serializer = new DOMSerializer(options);\n const serialized1 = serializer.serialize(element1);\n const serialized2 = serializer.serialize(element2);\n \n return JSON.stringify(serialized1) === JSON.stringify(serialized2);\n }\n }\n \n /*\n // Export for use\n if (typeof module !== 'undefined' && module.exports) {\n module.exports = { DOMSerializer, DOMUtils };\n } else if (typeof window !== 'undefined') {\n window.DOMSerializer = DOMSerializer;\n window.DOMUtils = DOMUtils;\n }\n */\n\n /* Usage Examples:\n \n // Basic serialization\n const serializer = new DOMSerializer();\n const serialized = serializer.serialize(document);\n console.log(JSON.stringify(serialized, null, 2));\n \n // Deserialize back to DOM\n const clonedDoc = serializer.deserialize(serialized);\n \n // Using presets\n const minimalSerializer = DOMUtils.createSerializer('minimal');\n const secureSerializer = DOMUtils.createSerializer('secure');\n \n // Serialize specific element with Shadow DOM\n const customElement = document.querySelector('my-custom-element');\n const serializedElement = serializer.serialize(customElement);\n \n // JSON utilities\n const jsonString = DOMUtils.serializeToJSON(document.body);\n const restored = DOMUtils.deserializeFromJSON(jsonString);\n \n // Deep clone with Shadow DOM support\n const clone = DOMUtils.deepClone(document.body, { includeShadowDOM: true });\n \n */\n\n function serializeNodeToJSON(nodeElement) {\n return DOMUtils.serializeToJSON(nodeElement, {includeStyles: false});\n }\n\n function deserializeNodeFromJSON(jsonString) {\n return DOMUtils.deserializeFromJSON(jsonString);\n }\n\n function findDropdowns() {\n const dropdowns = [];\n \n // Native select elements\n dropdowns.push(...getAllElementsIncludingShadow('select'));\n \n // Elements with dropdown roles that don't have <input>..</input>\n const roleElements = getAllElementsIncludingShadow('[role=\"combobox\"], [role=\"listbox\"], [role=\"dropdown\"], [role=\"option\"], [role=\"menu\"], [role=\"menuitem\"]').filter(el => {\n return el.tagName.toLowerCase() !== 'input' || ![\"button\", \"checkbox\", \"radio\"].includes(el.getAttribute(\"type\"));\n });\n dropdowns.push(...roleElements);\n \n // Common dropdown class patterns\n const dropdownPattern = /.*(dropdown|select|combobox|menu).*/i;\n const elements = getAllElementsIncludingShadow('*');\n const dropdownClasses = Array.from(elements).filter(el => {\n const hasDropdownClass = dropdownPattern.test(el.className);\n const validTag = ['li', 'ul', 'span', 'div', 'p', 'a', 'button'].includes(el.tagName.toLowerCase());\n const style = window.getComputedStyle(el); \n const result = hasDropdownClass && validTag && (style.cursor === 'pointer' || el.tagName.toLowerCase() === 'a' || el.tagName.toLowerCase() === 'button');\n return result;\n });\n \n dropdowns.push(...dropdownClasses);\n \n // Elements with aria-haspopup attribute\n dropdowns.push(...getAllElementsIncludingShadow('[aria-haspopup=\"true\"], [aria-haspopup=\"listbox\"], [aria-haspopup=\"menu\"]'));\n\n // Improve navigation element detection\n // Semantic nav elements with list items\n dropdowns.push(...getAllElementsIncludingShadow('nav ul li, nav ol li'));\n \n // Navigation elements in common design patterns\n dropdowns.push(...getAllElementsIncludingShadow('header a, .header a, .nav a, .navigation a, .menu a, .sidebar a, aside a'));\n \n // Elements in primary navigation areas with common attributes\n dropdowns.push(...getAllElementsIncludingShadow('[role=\"navigation\"] a, [aria-label*=\"navigation\"] a, [aria-label*=\"menu\"] a'));\n\n return dropdowns;\n }\n\n function findClickables() {\n const clickables = [];\n \n const checkboxPattern = /checkbox/i;\n // Collect all clickable elements first\n const nativeLinks = [...getAllElementsIncludingShadow('a')];\n const nativeButtons = [...getAllElementsIncludingShadow('button')];\n const inputButtons = [...getAllElementsIncludingShadow('input[type=\"button\"], input[type=\"submit\"], input[type=\"reset\"]')];\n const roleButtons = [...getAllElementsIncludingShadow('[role=\"button\"]')];\n // const tabbable = [...getAllElementsIncludingShadow('[tabindex=\"0\"]')];\n const clickHandlers = [...getAllElementsIncludingShadow('[onclick]')];\n const dropdowns = findDropdowns();\n const nativeCheckboxes = [...getAllElementsIncludingShadow('input[type=\"checkbox\"]')]; \n const fauxCheckboxes = getAllElementsIncludingShadow('*').filter(el => {\n if (checkboxPattern.test(el.className)) {\n const realCheckboxes = getAllElementsIncludingShadow('input[type=\"checkbox\"]', el);\n if (realCheckboxes.length === 1) {\n const boundingRect = realCheckboxes[0].getBoundingClientRect();\n return boundingRect.width <= 1 && boundingRect.height <= 1 \n }\n }\n return false;\n });\n const nativeRadios = [...getAllElementsIncludingShadow('input[type=\"radio\"]')];\n const toggles = findToggles();\n const pointerElements = findElementsWithPointer();\n // Add all elements at once\n clickables.push(\n ...nativeLinks,\n ...nativeButtons,\n ...inputButtons,\n ...roleButtons,\n // ...tabbable,\n ...clickHandlers,\n ...dropdowns,\n ...nativeCheckboxes,\n ...fauxCheckboxes,\n ...nativeRadios,\n ...toggles,\n ...pointerElements\n );\n\n // Only uniquify once at the end\n return clickables; // Let findElements handle the uniquification\n }\n\n function findToggles() {\n const toggles = [];\n const checkboxes = getAllElementsIncludingShadow('input[type=\"checkbox\"]');\n const togglePattern = /switch|toggle|slider/i;\n\n checkboxes.forEach(checkbox => {\n let isToggle = false;\n\n // Check the checkbox itself\n if (togglePattern.test(checkbox.className) || togglePattern.test(checkbox.getAttribute('role') || '')) {\n isToggle = true;\n }\n\n // Check parent elements (up to 3 levels)\n if (!isToggle) {\n let element = checkbox;\n for (let i = 0; i < 3; i++) {\n const parent = element.parentElement;\n if (!parent) break;\n\n const className = parent.className || '';\n const role = parent.getAttribute('role') || '';\n\n if (togglePattern.test(className) || togglePattern.test(role)) {\n isToggle = true;\n break;\n }\n element = parent;\n }\n }\n\n // Check next sibling\n if (!isToggle) {\n const nextSibling = checkbox.nextElementSibling;\n if (nextSibling) {\n const className = nextSibling.className || '';\n const role = nextSibling.getAttribute('role') || '';\n if (togglePattern.test(className) || togglePattern.test(role)) {\n isToggle = true;\n }\n }\n }\n\n if (isToggle) {\n toggles.push(checkbox);\n }\n });\n\n return toggles;\n }\n\n function findNonInteractiveElements() {\n // Get all elements in the document\n const all = Array.from(getAllElementsIncludingShadow('*'));\n \n // Filter elements based on Python implementation rules\n return all.filter(element => {\n if (!element.firstElementChild) {\n const tag = element.tagName.toLowerCase(); \n if (!['select', 'button', 'a'].includes(tag)) {\n const validTags = ['p', 'span', 'div', 'input', 'textarea','td','th'].includes(tag) || /^h\\d$/.test(tag) || /text/.test(tag);\n const boundingRect = element.getBoundingClientRect();\n return validTags && boundingRect.height > 1 && boundingRect.width > 1;\n }\n }\n return false;\n });\n }\n\n\n\n function findElementsWithPointer() {\n const elements = [];\n const allElements = getAllElementsIncludingShadow('*');\n \n allElements.forEach(element => {\n const style = window.getComputedStyle(element);\n const hasPointer = style.cursor === 'pointer';\n \n if (hasPointer) {\n elements.push(element);\n }\n });\n \n highlighterLogger.debug(`Found ${elements.length} elements with pointer cursor`);\n return elements;\n }\n\n function findCheckables() {\n const elements = [];\n\n elements.push(...getAllElementsIncludingShadow('input[type=\"checkbox\"]'));\n elements.push(...getAllElementsIncludingShadow('input[type=\"radio\"]'));\n const all_elements = getAllElementsIncludingShadow('label');\n const radioClasses = Array.from(all_elements).filter(el => {\n return /.*radio.*/i.test(el.className); \n });\n elements.push(...radioClasses);\n return elements;\n }\n\n function findFillables() {\n const elements = [];\n\n const inputs = [...getAllElementsIncludingShadow('input:not([type=\"radio\"]):not([type=\"checkbox\"])')];\n highlighterLogger.debug('Found inputs:', inputs.length, inputs);\n elements.push(...inputs);\n \n const textareas = [...getAllElementsIncludingShadow('textarea')];\n highlighterLogger.debug('Found textareas:', textareas.length);\n elements.push(...textareas);\n \n const editables = [...getAllElementsIncludingShadow('[contenteditable=\"true\"]')];\n highlighterLogger.debug('Found editables:', editables.length);\n elements.push(...editables);\n\n return elements;\n }\n\n // maximum number of characters in a logical name\n const MAX_LOGICAL_NAME_LENGTH = 25;\n \n /**\n * Query elements by CSS selector with :has-text(\"...\") pseudo-selector\n * @param {string} selector - CSS selector with optional :has-text(\"...\") pseudo-selector\n * @param {Element|Document} context - Context element to query within (defaults to document)\n * @returns {Element[]} Array of matched elements\n * @example\n * // Find all buttons with text \"Submit\"\n * querySelectorAllByText('button:has-text(\"Submit\")')\n * \n * // Find element with specific role and text\n * querySelectorAllByText('[role=\"button\"]:has-text(\"Click me\")')\n * \n * // Complex selector with descendants\n * querySelectorAllByText('button:has-text(\"foo\") > div > ul')\n * \n * // Multiple components\n * querySelectorAllByText('.container > button:has-text(\"Submit\")')\n * \n * // Multiple text filters\n * querySelectorAllByText('button:has-text(\"foo\") > div:has-text(\"bar\") > span')\n */\n function querySelectorAllByText(selector, context = document) {\n \t// Local helper function to compare two strings by normalizing whitespace and ignoring case\n \t// mimic the behavior of Playwright's :has-text() selector modifier\n \tfunction pwHasText(str1, str2) {\n \t\tif (!str1 || !str2) return false;\n \t\t\n \t\t// Normalize whitespace by replacing multiple spaces with single space and trim\n \t\tconst normalize = (str) => cleanText(str.toLowerCase());\n \t\t\n \t\tconst normalized1 = normalize(str1);\n \t\tconst normalized2 = normalize(str2);\n \t\t\n \t\treturn normalized1.includes(normalized2);\n \t}\n \t\n \t// Check if selector contains :has-text() pseudo-selector\n \tif (!selector.includes(':has-text(')) {\n \t\t// No :has-text pseudo-selector, use regular querySelectorAll\n \t\treturn Array.from(robustQuerySelector(selector, context, true));\n \t}\n \t\n \t// Split selector by combinators while preserving them\n \t// Matches: >, +, ~, or space (descendant combinator)\n \tconst parts = [];\n \tlet currentPart = '';\n \tlet inBracket = false;\n \tlet inTextPseudo = false;\n \tlet inTextQuotes = false;\n \tlet i = 0;\n \t\n \twhile (i < selector.length) {\n \t\tconst char = selector[i];\n \t\t\n \t\t// Track :has-text(\"...\") to avoid splitting inside it\n \t\tif (selector.substring(i, i + 10) === ':has-text(') {\n \t\t\tinTextPseudo = true;\n \t\t\tinTextQuotes = false;\n \t\t}\n \t\tif (inTextPseudo && char === '\"' && !inTextQuotes) {\n \t\t\tinTextQuotes = true;\n \t\t} else if (inTextPseudo && char === '\"' && inTextQuotes) {\n \t\t\t// Check if this quote is escaped\n \t\t\tif (i > 0 && selector[i - 1] === '\\\\') ; else {\n \t\t\t\tinTextQuotes = false;\n \t\t\t}\n \t\t}\n \t\tif (inTextPseudo && char === ')' && !inTextQuotes) {\n \t\t\tinTextPseudo = false;\n \t\t\tcurrentPart += char;\n \t\t\ti++;\n \t\t\tcontinue;\n \t\t}\n \t\t\n \t\t// Track brackets to avoid splitting on combinators inside attribute selectors\n \t\tif (char === '[') inBracket = true;\n \t\tif (char === ']') inBracket = false;\n \t\t\n \t\t// Check for combinators (not inside brackets or :has-text())\n \t\tif (!inBracket && !inTextPseudo && (char === '>' || char === '+' || char === '~')) {\n \t\t\tif (currentPart.trim()) parts.push({ selector: currentPart.trim(), combinator: null });\n \t\t\tparts.push({ selector: null, combinator: char.trim() });\n \t\t\tcurrentPart = '';\n \t\t\ti++;\n \t\t\tcontinue;\n \t\t}\n \t\t\n \t\t// Check for space combinator (descendant)\n \t\tif (!inBracket && !inTextPseudo && char === ' ') {\n \t\t\t// Skip multiple spaces\n \t\t\twhile (i < selector.length && selector[i] === ' ') i++;\n \t\t\t// Check if next char is a combinator (>, +, ~)\n \t\t\tif (i < selector.length && !'><+~'.includes(selector[i])) {\n \t\t\t\tif (currentPart.trim()) {\n \t\t\t\t\tparts.push({ selector: currentPart.trim(), combinator: null });\n \t\t\t\t\tparts.push({ selector: null, combinator: ' ' });\n \t\t\t\t\tcurrentPart = '';\n \t\t\t\t}\n \t\t\t}\n \t\t\tcontinue;\n \t\t}\n \t\t\n \t\tcurrentPart += char;\n \t\ti++;\n \t}\n \tif (currentPart.trim()) parts.push({ selector: currentPart.trim(), combinator: null });\n \t\n \t// Filter out combinator-only entries and rebuild as selector+combinator pairs\n \tconst selectorParts = [];\n \tfor (let j = 0; j < parts.length; j++) {\n \t\tif (parts[j].selector) {\n \t\t\tconst combinator = (j + 1 < parts.length && parts[j + 1].combinator) ? parts[j + 1].combinator : null;\n \t\t\t// Extract text value if present\n \t\t\tconst textMatch = parts[j].selector.match(/:has-text\\(\"((?:[^\"\\\\]|\\\\.)*)\"\\)/);\n \t\t\tconst textValue = textMatch ? textMatch[1] : null;\n \t\t\tconst selectorWithoutText = textMatch ? parts[j].selector.replace(/:has-text\\(\"((?:[^\"\\\\]|\\\\.)*)\"\\)/, '') : parts[j].selector;\n \t\t\t\n \t\t\tselectorParts.push({ \n \t\t\t\tselector: parts[j].selector,\n \t\t\t\tselectorWithoutText,\n \t\t\t\ttextValue,\n \t\t\t\tcombinator \n \t\t\t});\n \t\t}\n \t}\n \t\n \t// Process selector parts sequentially, applying text filters as we go\n \tlet currentElements = [context];\n \t\n \tfor (let partIndex = 0; partIndex < selectorParts.length; partIndex++) {\n \t\tconst part = selectorParts[partIndex];\n \t\tconst nextElements = [];\n \t\t\n \t\tfor (const ctx of currentElements) {\n \t\t\tlet candidates;\n \t\t\t\n \t\t\tif (partIndex === 0 && ctx === context) {\n \t\t\t\t// First part, query from document/context\n \t\t\t\tconst querySelector = part.selectorWithoutText.trim() || '*';\n \t\t\t\tcandidates = Array.from(robustQuerySelector(querySelector, ctx, true));\n \t\t\t\thighlighterLogger.debug(`querySelectorAllByText: first part, querySelector=${querySelector}, candidates=`, candidates);\n \t\t\t} \n \t\t\telse {\n \t\t\t\t// Subsequent parts, use combinator\n \t\t\t\tconst prevPart = selectorParts[partIndex - 1];\n \t\t\t\tconst combinator = prevPart.combinator;\n \t\t\t\tconst querySelector = part.selectorWithoutText.trim() || '*';\n \t\t\t\t\n \t\t\t\tif (combinator === '>') {\n \t\t\t\t\t// Direct children\n \t\t\t\t\tcandidates = Array.from(ctx.children).filter(child => {\n \t\t\t\t\t\treturn child.matches(querySelector);\n \t\t\t\t\t});\n \t\t\t\t} else if (combinator === '+') {\n \t\t\t\t\t// Next sibling\n \t\t\t\t\tconst sibling = ctx.nextElementSibling;\n \t\t\t\t\tcandidates = (sibling && sibling.matches(querySelector)) ? [sibling] : [];\n \t\t\t\t} else if (combinator === '~') {\n \t\t\t\t\t// Following siblings\n \t\t\t\t\tcandidates = [];\n \t\t\t\t\tlet sibling = ctx.nextElementSibling;\n \t\t\t\t\twhile (sibling) {\n \t\t\t\t\t\tif (sibling.matches(querySelector)) {\n \t\t\t\t\t\t\tcandidates.push(sibling);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tsibling = sibling.nextElementSibling;\n \t\t\t\t\t}\n \t\t\t\t} \n \t\t\t\telse {\n \t\t\t\t\t// Descendant (space)\n \t\t\t\t\tcandidates = Array.from(robustQuerySelector(querySelector, ctx, true));\n \t\t\t\t}\n \t\t\t}\n \t\t\t\n \t\t\t// Apply text filter if present\n \t\t\tif (part.textValue !== null) {\n \t\t\t\tcandidates = candidates.filter(el => pwHasText(getElementText(el), part.textValue));\n \t\t\t}\n \t\t\t\n \t\t\tnextElements.push(...candidates);\n \t\t}\n \t\t\n \t\tcurrentElements = nextElements;\n \t\t\n \t\t// If no matches, bail early\n \t\tif (currentElements.length === 0) {\n \t\t\treturn [];\n \t\t}\n \t}\n \t\n \treturn currentElements;\n }\n\n const cleanText = (text) => {\n \treturn text.replace(/\\s+/g, ' ').trim();\n };\n\n // Helper function to get name selector\n const getNameSelector = (element) => {\n \tconst text = cleanText(getElementText(element));\n \tconst title = element.getAttribute('title');\n \tconst name = element.getAttribute('name');\n \tconst ariaLabel = element.getAttribute('aria-label');\n \tif (!text && !title && !name && !ariaLabel) throw new Error('No name attribute provided');\n \tif (text) return `:has-text(${doubleQuoteString(text)})`;\n \tif (title) return `[title=${doubleQuoteString(title)}]`;\n \tif (ariaLabel) return `[aria-label=${doubleQuoteString(ariaLabel)}]`;\n \treturn `[name=${doubleQuoteString(name)}]`; \n };\n\n const getLogicalName = (element) => {\n \tconst text = cleanText(getElementText(element));\n \tconst title = element.getAttribute('title');\n \tconst name = element.getAttribute('name');\n \tconst ariaLabel = element.getAttribute('aria-label');\n \tconst role = element.getAttribute('role');\n \tconst logicalName = text || title || name || ariaLabel;\n \treturn {\n \t\thasLogicalName: logicalName && logicalName.length < MAX_LOGICAL_NAME_LENGTH && !role?.startsWith('row'),\n \t\tlogicalName: logicalName\n \t};\n };\n\n\n /**\n * Individual strategy functions\n */\n\n function tryRoleStrategy(element) { \n \tconst role = element.getAttribute('role');\n \tconst tag = element.tagName.toLowerCase();\n \tconst { hasLogicalName, logicalName } = getLogicalName(element);\n \tif (role && hasLogicalName) {\n \t\treturn { \n \t\t\tstrategy: 'role', \n \t\t\tselector: `[role=${doubleQuoteString(role)}]${getNameSelector(element)}`\n \t\t};\n \t}\n \t\n \t// Tag-based role (button, a, input, etc.) + name\n \tif (['button', 'a', 'input', 'textarea', 'select'].includes(tag) && hasLogicalName) {\n \t\treturn { \n \t\t\tstrategy: 'role', \n \t\t\tselector: `${tag}${getNameSelector(element)}`\n \t\t};\n \t}\n \t\n \treturn null;\n }\n\n function tryPlaceholderStrategy(element) {\n \tconst placeholder = element.getAttribute('placeholder');\n \tif (placeholder) {\n \t\treturn { \n \t\t\tstrategy: 'placeholder', \n \t\t\tselector: `[placeholder=${doubleQuoteString(placeholder)}]` \n \t\t};\n \t}\n \treturn null;\n }\n\n function tryLabelStrategy(element) {\n \tconst tag = element.tagName.toLowerCase();\n \tif (['input', 'textarea', 'select'].includes(tag)) {\n \t\tconst id = element.id;\n \t\tif (id) {\n \t\t\tconst labels = robustQuerySelector(`label[for=${doubleQuoteString(id)}]`, document, true);\n \t\t\tif (labels.length === 1) { //make sure id is unique\n \t\t\t\tconst labelText = cleanText(getElementText(labels[0]));\n \t\t\t\tif (labelText) {\n \t\t\t\t\tconst labelSelector = `label:has-text(${doubleQuoteString(labelText)})`;\n \t\t\t\t\ttry {\n \t\t\t\t\t\tconst els = querySelectorAllByText(labelSelector, document);\n \t\t\t\t\t\tif (els.length === 1) {\n \t\t\t\t\t\t\treturn { \n \t\t\t\t\t\t\t\tstrategy: 'label for',\n \t\t\t\t\t\t\t\tlabel_selector: labelSelector\n \t\t\t\t\t\t\t};\n \t\t\t\t\t\t}\n \t\t\t\t\t} catch (error) {\n \t\t\t\t\t\thighlighterLogger.error(`internal error: while querying label selector ${labelSelector} for element ${element.outerHTML}`, error);\n \t\t\t\t\t\tthrow error;\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t}\n \treturn null;\n }\n\n function tryAriaLabelledByStrategy(element) {\n \tconst arialabeledBy = element.getAttribute('aria-labelledby');\n \tconst tag = element.tagName.toLowerCase();\n \t\n \tif (arialabeledBy) {\n \t\tconst labels = robustQuerySelector(`#${CSS.escape(arialabeledBy)}`, document, true);\n \t\tif (labels.length === 1) {\n \t\t\tconst labelText = cleanText(getElementText(labels[0]));\n \t\t\tif (labelText) { //verify the label text is unique\n \t\t\t\tconst labelSelector = `${tag}:has-text(${doubleQuoteString(labelText)})`;\n \t\t\t\ttry {\n \t\t\t\t\tconst els = querySelectorAllByText(labelSelector, document);\n \t\t\t\t\tif (els.length === 1) {\n \t\t\t\t\t\treturn { \n \t\t\t\t\t\t\tstrategy: 'label by', \n \t\t\t\t\t\t\tlabel_selector: labelSelector\n \t\t\t\t\t\t};\n \t\t\t\t\t}\n \t\t\t\t} catch (error) {\n \t\t\t\t\thighlighterLogger.error(`internal error: while querying aria-labelledby selector ${labelSelector} for element ${element.outerHTML}`, error);\n \t\t\t\t\tthrow error;\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t}\n \treturn null;\n }\n\n // Only use text strategy if element is clickable/interactive \n function tryNameStrategy(element) {\t\n \tconst { hasLogicalName } = getLogicalName(element);\n \tconst classes = Array.from(element.classList).map(cls => CSS.escape(cls));\n \t\n \t// Only use name strategy if element is clickable/interactive \n \tif (isClickableElement(element) && hasLogicalName && classes.length > 0) {\n \t\treturn { \n \t\t\tstrategy: 'name', \n \t\t\tselector: `.${classes.join('.')}${getNameSelector(element)}` \n \t\t\t// selector: `${element.tagName.toLowerCase()}${getNameSelector(element)}`\n \t\t};\n \t}\n \treturn null;\n }\n\n function tryDataTestIdStrategy(element) {\n \tconst dataTestId = element.getAttribute('data-testid');\n \tif (dataTestId) {\n \t\treturn { \n \t\t\tstrategy: 'data-testid',\t\t\t\n \t\t\tselector: `[data-testid=${doubleQuoteString(dataTestId)}]` \n \t\t};\n \t}\n \treturn null;\n }\n\n function tryIdStrategy(element) {\n \tconst id = element.getAttribute('id');\n \tif (id && !/:|\\s|\\\\/.test(id)) { //avoid using id if it contain unusual characters (react creates ids like this: \":r:42\")\n \t\treturn { \n \t\t\tstrategy: 'id', \n \t\t\tselector: `#${CSS.escape(id)}` \n \t\t};\n \t}\n \treturn null;\n }\n\n // Try all strategies on an element in order of precedence\n function attemptStrategiesOnElement(element) {\n \tconst strategies = [\n \t\ttryRoleStrategy, \t\t\n \t\ttryAriaLabelledByStrategy,\n \t\ttryNameStrategy,\n \t\ttryLabelStrategy,\n \t\ttryDataTestIdStrategy,\n \t\ttryPlaceholderStrategy,\n \t\ttryIdStrategy,\t\t\n \t\t// tryClassStrategy\n \t];\n \t\n \tfor (const strategy of strategies) {\n \t\tconst result = strategy(element); \n \t\tif (result) { \n \t\t\treturn result;\n \t\t}\n \t}\n \treturn null;\n }\n\n /**\n * Generate a smart selector for an element\n * @param {Element} element - The element to generate a locator for\n * @param {string} childPath - The child path to generate a locator for\n * @returns {Object} The selector for the element\n */\n function generateSmartSelector(element, childPath = '') {\n \t// Terminate recursion\n \tif (!element || element.nodeType !== Node.ELEMENT_NODE) {\n \t\treturn {\n \t\t\tstrategy: 'css',\n \t\t\tselector: childPath\n \t\t};\n \t}\n \t\n \t// Try strategies 1-6 on current element\n \tconst result = attemptStrategiesOnElement(element);\n \tconst is_label = result?.strategy === 'label for' || result?.strategy === 'label by';\n\n \tif (result) { // found a strategy\t\t\t\n \t\t// If we have a child path, concatenate parent strategy result with child CSS path \n \t\tlet extendedResult = result; \n \t\tif (childPath) {\n \t\t\tconst selector = is_label ? `${childPath}` : `${result?.selector} > ${childPath}`;\n \t\t\textendedResult = {\n \t\t\t\t...extendedResult,\n \t\t\t\tselector: selector,\n \t\t\t\tstrategy: `${extendedResult.strategy} (concatenated with child CSS path)`\n \t\t\t};\n \t\t} \t\t\n \t\t// check if the combined selector is unique and if not add the index to the strategy\n \t\tif (!is_label) { //label element is already checked for uniqueness\n \t\t\ttry {\n \t\t\t\tconst matchedElements = querySelectorAllByText(extendedResult?.selector); //query full selector for uniqueness checking \n \t\t\t\thighlighterLogger.debug(`querySelectorAllByText(${extendedResult?.selector}) matched ${matchedElements.length} elements`);\n \t\t\t\thighlighterLogger.debug(matchedElements);\n \t\t\t\tif (matchedElements.length > 1) {\n \t\t\t\t\tconst childElement = childPath ? robustQuerySelector(`:scope > ${childPath}`, element) : element;\n \t\t\t\t\tconst index = matchedElements.findIndex(el => el === childElement);\n \t\t\t\t\tif (index === -1) {\n \t\t\t\t\t\thighlighterLogger.error('internal error: Element not found in matched elements', element, result?.selector, matchedElements);\n \t\t\t\t\t\treturn null;\n \t\t\t\t\t}\n \t\t\t\t\textendedResult = {\n \t\t\t\t\t\t...extendedResult,\n \t\t\t\t\t\tstrategy: `${extendedResult.strategy} (by index)`,\n \t\t\t\t\t\tindex,\n \t\t\t\t\t}; \n \t\t\t\t}\n \t\t\t} catch (error) {\n \t\t\t\thighlighterLogger.error(`internal error: while checking if selector ${result?.selector} is unique for element ${element.outerHTML}`, error);\n \t\t\t\tthrow error;\n \t\t\t}\t\t\t\n \t\t}\n \t\treturn extendedResult;\n \t}\n \t\n \t// Get CSS selector for current element and build child path \n \tlet newChildPath;\n \t// didn't find strategy\n \tconst elementSelector = getElementCssSelector(element);\n \tnewChildPath = childPath ? `${elementSelector} > ${childPath}` : elementSelector;\n \tconst numComponents = newChildPath.split(' > ').length;\n \tif (numComponents > 2) { //require at least 2 components for css strategy\n \t\t// check if the combined selector is unique\n \t\tconst matchedElements = robustQuerySelector(newChildPath, document, true);\n \t\tif (matchedElements.length === 1) {\n \t\t\treturn {\n \t\t\t\tstrategy: 'css',\t\t\t\t\n \t\t\t\tselector: newChildPath\n \t\t\t};\n \t\t}\n \t}\n\n \t// Recursively try parent element\n \treturn generateSmartSelector(getParentNode(element), newChildPath);\n }\n\n const findElementByInfo = (elementInfo, useSmartSelectors = false) => {\n \thighlighterLogger.debug('findElementByInfo:', elementInfo);\n \tif (useSmartSelectors) {\n \t return findElementBySelectors(elementInfo.smart_iframe_selector, elementInfo.smart_selector, true);\n \t}\n \treturn findElementBySelectors(elementInfo.iframe_selector, elementInfo.css_selector, false);\n };\n\n const compareSelectors = (selector1, selector2, useSmartSelectors = false) => {\n \tif (useSmartSelectors) {\n \t\treturn JSON.stringify(selector1) === JSON.stringify(selector2);\n \t}\n \treturn selector1 === selector2;\n };\n\n const findElementBySelectors = (iframeSelector, elementSelector, useSmartSelectors = false) => {\n \tlet element;\n \t\n \t// first find the iframe that contains the element\n \tif (iframeSelector) { \n \t const frames = getAllDocumentElementsIncludingShadow('iframe', document);\n \t \n \t // Iterate over all frames and compare their CSS selectors\n \t for (const frame of frames) {\n \t\tconst selector = useSmartSelectors ? generateSmartSelector(frame) : generateCssPath(frame);\n \t\tif (compareSelectors(selector, iframeSelector, useSmartSelectors)) {\n \t\t const frameDocument = frame.contentDocument || frame.contentWindow.document;\n \t\t element = useSmartSelectors ? findElementBySmartSelector(elementSelector, frameDocument) : robustQuerySelector(elementSelector, frameDocument);\t\t \n \t\t break;\n \t\t} \n \t }\t}\n \telse {\t\t\n \t\telement = useSmartSelectors ? findElementBySmartSelector(elementSelector, document) : robustQuerySelector(elementSelector, document);\t\t\n \t}\n \t \n \tif (element) {\n \t\thighlighterLogger.debug('findElementBySelectors: found element ', element);\n \t}\n \telse {\n \t highlighterLogger.warn('findElementBySelectors: failed to find element with CSS selector:', JSON.stringify(elementSelector));\n \t}\n \n \treturn element;\n };\n \n function findElementBySmartSelector(smartSelector, root = document) {\t\n \thighlighterLogger.debug(`findElementBySmartSelector: called with smartSelector=${JSON.stringify(smartSelector)}`);\n \tlet combinedSelector;\n \tconst mainStrategy = smartSelector.strategy.split(' ')[0]; //extract the main strategy from the full strategy string\n \tswitch(mainStrategy) {\n case 'role': \n case 'placeholder':\n case 'name':\n case 'data-testid':\n case 'id':\n case 'css':\n case 'class':\n \t\t highlighterLogger.debug(`findElementBySmartSelector: strategy='${smartSelector.strategy}', selector=${smartSelector?.selector}, index=${smartSelector?.index}`);\n if (typeof smartSelector?.index === 'number') {\n return querySelectorAllByText(smartSelector.selector, root)[smartSelector.index];\n }\n else {\n return querySelectorAllByText(smartSelector.selector, root)[0];\n }\t\t \n case 'label':\n \t\t\tif (smartSelector.strategy === 'label for') {\n \t\t\t\thighlighterLogger.debug(`findElementBySmartSelector: strategy='label for', label_selector=${smartSelector.label_selector}`);\n \t\t\t\tconst label_for = querySelectorAllByText(smartSelector.label_selector, root)[0];\n \t\t\t\tcombinedSelector = smartSelector?.selector ? `#${label_for.getAttribute('for')} > ${smartSelector.selector}` : `#${label_for.getAttribute('for')}`;\n \t\t\t\treturn robustQuerySelector(combinedSelector, root);\n \t\t\t}\n \t\t\telse if (smartSelector.strategy === 'label by') {\n \t\t\t\thighlighterLogger.debug(`findElementBySmartSelector: strategy='label by', label_selector=${smartSelector.label_selector}`);\n \t\t\t\tconst label_by = querySelectorAllByText(smartSelector.label_selector, root)[0];\n \t\t\t\tcombinedSelector = smartSelector?.selector ? `[aria-labelledby=\"${label_by.getAttribute('id')}\"] > ${smartSelector.selector}` : `[aria-labelledby=\"${label_by.getAttribute('id')}\"]`;\n \t\t\t\treturn robustQuerySelector(combinedSelector, root);\n \t\t\t}\n \t\t\telse {\n \t\t\t\thighlighterLogger.error(`findElementBySmartSelector: unsupported label strategy: ${smartSelector.strategy}`);\n \t\t\t\treturn null;\n \t\t\t} \n default:\n highlighterLogger.error(`findElementBySmartSelector: Unsupported smart selector strategy: ${smartSelector.strategy}`);\n return null;\n }\n }\n\n function getElementInfo(element, index) { \t\t\t\n \tconst iframe = getContainingIFrame(element); \n \tconst iframe_selector = iframe ? generateCssPath(iframe) : \"\";\t\n \tconst smart_iframe_selector = iframe ? generateSmartSelector(iframe) : null;\n \t\n \t// Return element info with pre-calculated values\n \treturn {\n \t\tindex: index ?? -1,\n \t\ttag: element.tagName.toLowerCase(),\n \t\ttype: element.type || '',\n \t\ttext: getElementText(element) || getElementPlaceholder(element),\n \t\thtml: cleanHTML(element.outerHTML),\n \t\txpath: generateXPath(element),\n \t\tcss_selector: generateCssPath(element),\n \t\tbounding_box: element.getBoundingClientRect(),\t\t\n \t\tiframe_selector: iframe_selector,\t\t\n \t\tsmart_selector: generateSmartSelector(element),\n \t\tsmart_iframe_selector: smart_iframe_selector,\n \t\telement: element,\n \t\tdepth: getElementDepth(element)\n \t};\n }\n\n /**\n * Checks if a point is inside a bounding box\n * \n * @param point The point to check\n * @param box The bounding box\n * @returns boolean indicating if the point is inside the box\n */\n function isPointInsideBox(point, box) {\n return point.x >= box.x &&\n point.x <= box.x + box.width &&\n point.y >= box.y &&\n point.y <= box.y + box.height;\n }\n\n /**\n * Calculates the overlap area between two bounding boxes\n * \n * @param box1 First bounding box\n * @param box2 Second bounding box\n * @returns The overlap area\n */\n function calculateOverlap(box1, box2) {\n const xOverlap = Math.max(0,\n Math.min(box1.x + box1.width, box2.x + box2.width) -\n Math.max(box1.x, box2.x)\n );\n const yOverlap = Math.max(0,\n Math.min(box1.y + box1.height, box2.y + box2.height) -\n Math.max(box1.y, box2.y)\n );\n return xOverlap * yOverlap;\n }\n\n /**\n * Finds an exact match between candidate elements and the actual interaction element\n * \n * @param candidate_elements Array of candidate element infos\n * @param actualInteractionElementInfo The actual interaction element info\n * @returns The matching candidate element info, or null if no match is found\n */\n function findExactMatch(candidate_elements, actualInteractionElementInfo) {\n if (!actualInteractionElementInfo.element) {\n return null;\n }\n\n const exactMatch = candidate_elements.find(elementInfo => \n elementInfo.element && elementInfo.element === actualInteractionElementInfo.element\n );\n \n if (exactMatch) {\n highlighterLogger.debug('✅ Found exact element match:', {\n matchedElement: exactMatch.element?.tagName,\n matchedElementClass: exactMatch.element?.className,\n index: exactMatch.index\n });\n return exactMatch;\n }\n \n return null;\n }\n\n /**\n * Finds a match by traversing up the parent elements\n * \n * @param candidate_elements Array of candidate element infos\n * @param actualInteractionElementInfo The actual interaction element info\n * @returns The matching candidate element info, or null if no match is found\n */\n function findParentMatch(candidate_elements, actualInteractionElementInfo) {\n if (!actualInteractionElementInfo.element) {\n return null;\n }\n\n let element = actualInteractionElementInfo.element;\n while (element.parentElement) {\n element = element.parentElement;\n const parentMatch = candidate_elements.find(candidate => \n candidate.element && candidate.element === element\n );\n \n if (parentMatch) {\n highlighterLogger.debug('✅ Found parent element match:', {\n matchedElement: parentMatch.element?.tagName,\n matchedElementClass: parentMatch.element?.className,\n index: parentMatch.index,\n depth: element.tagName\n });\n return parentMatch;\n }\n \n // Stop if we hit another candidate element\n if (candidate_elements.some(candidate => \n candidate.element && candidate.element === element\n )) {\n highlighterLogger.debug('⚠️ Stopped parent search - hit another candidate element:', element.tagName);\n break;\n }\n }\n \n return null;\n }\n\n /**\n * Finds a match based on spatial relationships between elements\n * \n * @param candidate_elements Array of candidate element infos\n * @param actualInteractionElementInfo The actual interaction element info\n * @returns The matching candidate element info, or null if no match is found\n */\n function findSpatialMatch(candidate_elements, actualInteractionElementInfo) {\n if (!actualInteractionElementInfo.element || !actualInteractionElementInfo.bounding_box) {\n return null;\n }\n\n const actualBox = actualInteractionElementInfo.bounding_box;\n let bestMatch = null;\n let bestScore = 0;\n\n for (const candidateInfo of candidate_elements) {\n if (!candidateInfo.bounding_box) continue;\n \n const candidateBox = candidateInfo.bounding_box;\n let score = 0;\n\n // Check if actual element is contained within candidate\n if (isPointInsideBox({ x: actualBox.x, y: actualBox.y }, candidateBox) &&\n isPointInsideBox({ x: actualBox.x + actualBox.width, y: actualBox.y + actualBox.height }, candidateBox)) {\n score += 100; // High score for containment\n }\n\n // Calculate overlap area as a factor\n const overlap = calculateOverlap(actualBox, candidateBox);\n score += overlap;\n\n // Consider proximity if no containment\n if (score === 0) {\n const distance = Math.sqrt(\n Math.pow((actualBox.x + actualBox.width/2) - (candidateBox.x + candidateBox.width/2), 2) +\n Math.pow((actualBox.y + actualBox.height/2) - (candidateBox.y + candidateBox.height/2), 2)\n );\n // Convert distance to a score (closer = higher score)\n score = 1000 / (distance + 1);\n }\n\n if (score > bestScore) {\n bestScore = score;\n bestMatch = candidateInfo;\n highlighterLogger.debug('📏 New best spatial match:', {\n element: candidateInfo.element?.tagName,\n class: candidateInfo.element?.className,\n index: candidateInfo.index,\n score: score\n });\n }\n }\n\n if (bestMatch) {\n highlighterLogger.debug('✅ Final spatial match selected:', {\n element: bestMatch.element?.tagName,\n class: bestMatch.element?.className,\n index: bestMatch.index,\n finalScore: bestScore\n });\n return bestMatch;\n }\n\n return null;\n }\n\n /**\n * Finds a matching candidate element for an actual interaction element\n * \n * @param candidate_elements Array of candidate element infos\n * @param actualInteractionElementInfo The actual interaction element info\n * @returns The matching candidate element info, or null if no match is found\n */\n function findMatchingCandidateElementInfo(candidate_elements, actualInteractionElementInfo) {\n if (!actualInteractionElementInfo.element || !actualInteractionElementInfo.bounding_box) {\n highlighterLogger.error('❌ Missing required properties in actualInteractionElementInfo');\n return null;\n }\n\n highlighterLogger.debug('🔍 Starting element matching for:', {\n clickedElement: actualInteractionElementInfo.element.tagName,\n clickedElementClass: actualInteractionElementInfo.element.className,\n totalCandidates: candidate_elements.length\n });\n\n // First try exact element match\n const exactMatch = findExactMatch(candidate_elements, actualInteractionElementInfo);\n if (exactMatch) {\n return exactMatch;\n }\n highlighterLogger.debug('❌ No exact element match found, trying parent matching...');\n\n // Try finding closest clickable parent\n const parentMatch = findParentMatch(candidate_elements, actualInteractionElementInfo);\n if (parentMatch) {\n return parentMatch;\n }\n highlighterLogger.debug('❌ No parent match found, falling back to spatial matching...');\n\n // If no exact or parent match, look for spatial relationships\n const spatialMatch = findSpatialMatch(candidate_elements, actualInteractionElementInfo);\n if (spatialMatch) {\n return spatialMatch;\n }\n\n highlighterLogger.error('❌ No matching element found for actual interaction element:', actualInteractionElementInfo);\n return null;\n }\n\n const highlight = {\n execute: async function(elementTypes, handleScroll=false) {\n const elements = await findElements(elementTypes);\n highlightElements(elements, false,handleScroll);\n return elements;\n },\n\n unexecute: function(handleScroll=false) {\n unhighlightElements(handleScroll);\n },\n\n generateJSON: async function() {\n const json = {};\n\n // Capture viewport dimensions\n const viewportData = {\n width: window.innerWidth,\n height: window.innerHeight,\n documentWidth: document.documentElement.clientWidth,\n documentHeight: document.documentElement.clientHeight,\n timestamp: new Date().toISOString()\n };\n\n // Add viewport data to the JSON output\n json.viewport = viewportData;\n\n\n await Promise.all(Object.values(ElementTag).map(async elementType => {\n const elements = await findElements(elementType);\n json[elementType] = elements;\n }));\n\n // Serialize the JSON object\n const jsonString = JSON.stringify(json, null, 4); // Pretty print with 4 spaces\n\n highlighterLogger.log(`JSON: ${jsonString}`);\n return jsonString;\n },\n\n getElementInfo\n };\n\n\n function unhighlightElements(handleScroll=false) {\n const documents = getAllFrames();\n documents.forEach(doc => {\n const overlay = doc.getElementById('highlight-overlay');\n if (overlay) {\n if (handleScroll) {\n // Remove event listeners\n doc.removeEventListener('scroll', overlay.scrollHandler, true);\n doc.removeEventListener('resize', overlay.resizeHandler);\n }\n overlay.remove();\n }\n });\n }\n\n\n async function findElements(elementTypes, verbose=true) {\n const typesArray = Array.isArray(elementTypes) ? elementTypes : [elementTypes];\n highlighterLogger.debug('Starting element search for types:', typesArray);\n\n const elements = [];\n typesArray.forEach(elementType => {\n if (elementType === ElementTag.FILLABLE) {\n elements.push(...findFillables());\n }\n if (elementType === ElementTag.SELECTABLE) {\n elements.push(...findDropdowns());\n }\n if (elementType === ElementTag.CLICKABLE) {\n elements.push(...findClickables());\n elements.push(...findToggles());\n elements.push(...findCheckables());\n }\n if (elementType === ElementTag.NON_INTERACTIVE_ELEMENT) {\n elements.push(...findNonInteractiveElements());\n }\n });\n\n // console.log('Before uniquify:', elements.length);\n const elementsWithInfo = elements.map((element, index) => \n getElementInfo(element, index)\n );\n\n \n \n const uniqueElements = uniquifyElements(elementsWithInfo);\n highlighterLogger.debug(`Found ${uniqueElements.length} elements:`);\n \n // More comprehensive visibility check\n const visibleElements = uniqueElements.filter(elementInfo => {\n const el = elementInfo.element;\n const style = getComputedStyle(el);\n \n // Check various style properties that affect visibility\n if (style.display === 'none' || \n style.visibility === 'hidden') {\n return false;\n }\n \n // Check if element has non-zero dimensions\n const rect = el.getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) {\n return false;\n }\n \n // Check if element is within viewport\n if (rect.bottom < 0 || \n rect.top > window.innerHeight || \n rect.right < 0 || \n rect.left > window.innerWidth) {\n // Element is outside viewport, but still might be valid \n // if user scrolls to it, so we'll include it\n return true;\n }\n \n return true;\n });\n \n highlighterLogger.debug(`Out of which ${visibleElements.length} elements are visible:`);\n if (verbose) {\n visibleElements.forEach(info => {\n highlighterLogger.debug(`Element ${info.index}:`, info);\n });\n }\n \n return visibleElements;\n }\n\n // elements is an array of objects with index, xpath\n function highlightElements(elements, enableSmartSelectors=false, handleScroll=false) {\n // console.log('[highlightElements] called with', elements.length, 'elements');\n // Create overlay if it doesn't exist and store it in a dictionary\n const documents = getAllFrames(); \n let overlays = {};\n documents.forEach(doc => {\n let overlay = doc.getElementById('highlight-overlay');\n if (!overlay) {\n overlay = doc.createElement('div');\n overlay.id = 'highlight-overlay';\n overlay.style.cssText = `\n position: fixed;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n pointer-events: none;\n z-index: 2147483647;\n `;\n doc.body.appendChild(overlay);\n // console.log('[highlightElements] Created overlay in document:', doc);\n }\n overlays[doc.documentURI] = overlay;\n });\n \n\n const updateHighlights = (doc = null) => {\n if (doc) {\n overlays[doc.documentURI].innerHTML = '';\n } else {\n Object.values(overlays).forEach(overlay => { overlay.innerHTML = ''; });\n } \n elements.forEach((elementInfo, idx) => {\n //console.log(`[highlightElements] Processing element ${idx}:`, elementInfo.tag, elementInfo.css_selector, elementInfo.bounding_box);\n let element = elementInfo.element;\n if (!element) {\n element = findElementByInfo(elementInfo, enableSmartSelectors);\n if (!element) {\n highlighterLogger.warn('[highlightElements] Could not find element for:', elementInfo);\n return;\n }\n }\n //if highlights requested for a specific doc, skip unrelated elements\n if (doc && element.ownerDocument !== doc) {\n highlighterLogger.debug(\"[highlightElements] Skipped element since it doesn't belong to document\", doc);\n return;\n }\n const rect = element.getBoundingClientRect();\n if (rect.width === 0 || rect.height === 0) {\n highlighterLogger.warn('[highlightElements] Element has zero dimensions:', elementInfo);\n return;\n }\n // Create border highlight (red rectangle)\n // use ownerDocument to support iframes/frames\n const highlight = element.ownerDocument.createElement('div');\n highlight.style.cssText = `\n position: fixed;\n left: ${rect.x}px;\n top: ${rect.y}px;\n width: ${rect.width}px;\n height: ${rect.height}px;\n border: 1px solid rgb(255, 0, 0);\n transition: all 0.2s ease-in-out;\n `;\n // Create index label container - now positioned to the right and slightly up\n const labelContainer = element.ownerDocument.createElement('div');\n labelContainer.style.cssText = `\n position: absolute;\n right: -10px; /* Offset to the right */\n top: -10px; /* Offset upwards */\n padding: 4px;\n background-color: rgba(255, 255, 0, 0.6);\n display: flex;\n align-items: center;\n justify-content: center;\n `;\n const text = element.ownerDocument.createElement('span');\n text.style.cssText = `\n color: rgb(0, 0, 0, 0.8);\n font-family: 'Courier New', Courier, monospace;\n font-size: 12px;\n font-weight: bold;\n line-height: 1;\n `;\n text.textContent = elementInfo.index.toString();\n labelContainer.appendChild(text);\n highlight.appendChild(labelContainer); \n overlays[element.ownerDocument.documentURI].appendChild(highlight);\n \n });\n };\n\n // Initial highlight\n updateHighlights();\n\n if (handleScroll) {\n documents.forEach(doc => {\n // Update highlights on scroll and resize\n highlighterLogger.debug('registering scroll and resize handlers for document: ', doc);\n const scrollHandler = () => {\n requestAnimationFrame(() => updateHighlights(doc));\n };\n const resizeHandler = () => {\n updateHighlights(doc);\n };\n doc.addEventListener('scroll', scrollHandler, true);\n doc.addEventListener('resize', resizeHandler);\n // Store event handlers for cleanup\n overlays[doc.documentURI].scrollHandler = scrollHandler;\n overlays[doc.documentURI].resizeHandler = resizeHandler;\n }); \n }\n }\n\n // function unexecute() {\n // unhighlightElements();\n // }\n\n // Make it available globally for both Extension and Playwright\n if (typeof window !== 'undefined') {\n function stripElementRefs(elementInfo) {\n if (!elementInfo) return null;\n const { element, ...rest } = elementInfo;\n return rest;\n }\n\n window.ProboLabs = window.ProboLabs || {};\n\n // --- Caching State ---\n window.ProboLabs.candidates = [];\n window.ProboLabs.actual = null;\n window.ProboLabs.matchingCandidate = null;\n\n // --- Methods ---\n /**\n * Find and cache candidate elements of a given type (e.g., 'CLICKABLE').\n * NOTE: This function is async and must be awaited from Playwright/Node.\n */\n window.ProboLabs.findAndCacheCandidateElements = async function(elementType) {\n //console.log('[ProboLabs] findAndCacheCandidateElements called with:', elementType);\n const found = await findElements(elementType);\n window.ProboLabs.candidates = found;\n // console.log('[ProboLabs] candidates set to:', found, 'type:', typeof found, 'isArray:', Array.isArray(found));\n return found.length;\n };\n\n window.ProboLabs.findAndCacheActualElement = function(iframeSelector, elementSelector, isHover=false, useSmartSelectors=false) {\n // console.log('[ProboLabs] findAndCacheActualElement called with:', cssSelector, iframeSelector);\n highlighterLogger.debug(`[ProboLabs] findAndCacheActualElement called with: iframeSelector=${iframeSelector}, elementSelector=${elementSelector}, useSmartSelectors=${useSmartSelectors}`);\n let el = findElementBySelectors(iframeSelector, elementSelector, useSmartSelectors);\n if(isHover) {\n const visibleElement = findClosestVisibleElement(el);\n if (visibleElement) {\n el = visibleElement;\n }\n }\n if (!el) {\n window.ProboLabs.actual = null;\n // console.log('[ProboLabs] actual set to null');\n return false;\n }\n window.ProboLabs.actual = getElementInfo(el, -1);\n // console.log('[ProboLabs] actual set to:', window.ProboLabs.actual);\n return true;\n };\n\n window.ProboLabs.findAndCacheMatchingCandidate = function() {\n // console.log('[ProboLabs] findAndCacheMatchingCandidate called');\n if (!window.ProboLabs.candidates.length || !window.ProboLabs.actual) {\n window.ProboLabs.matchingCandidate = null;\n // console.log('[ProboLabs] matchingCandidate set to null');\n return false;\n }\n window.ProboLabs.matchingCandidate = findMatchingCandidateElementInfo(window.ProboLabs.candidates, window.ProboLabs.actual);\n // console.log('[ProboLabs] matchingCandidate set to:', window.ProboLabs.matchingCandidate);\n return !!window.ProboLabs.matchingCandidate;\n };\n\n window.ProboLabs.highlightCachedElements = function(which) {\n let elements = [];\n if (which === 'candidates') elements = window.ProboLabs.candidates;\n if (which === 'actual' && window.ProboLabs.actual) elements = [window.ProboLabs.actual];\n if (which === 'matching' && window.ProboLabs.matchingCandidate) elements = [window.ProboLabs.matchingCandidate];\n highlighterLogger.debug(`[ProboLabs] highlightCachedElements ${which} with ${elements.length} elements`);\n highlightElements(elements);\n };\n\n window.ProboLabs.unhighlight = function() {\n // console.log('[ProboLabs] unhighlight called');\n unhighlightElements();\n };\n\n window.ProboLabs.reset = function() {\n highlighterLogger.debug('[ProboLabs] reset called');\n window.ProboLabs.candidates = [];\n window.ProboLabs.actual = null;\n window.ProboLabs.matchingCandidate = null;\n unhighlightElements();\n };\n\n window.ProboLabs.getCandidates = function() {\n // console.log('[ProboLabs] getCandidates called. candidates:', window.ProboLabs.candidates, 'type:', typeof window.ProboLabs.candidates, 'isArray:', Array.isArray(window.ProboLabs.candidates));\n const arr = Array.isArray(window.ProboLabs.candidates) ? window.ProboLabs.candidates : [];\n return arr.map(stripElementRefs);\n };\n window.ProboLabs.getActual = function() {\n return stripElementRefs(window.ProboLabs.actual);\n };\n window.ProboLabs.getMatchingCandidate = function() {\n return stripElementRefs(window.ProboLabs.matchingCandidate);\n };\n\n window.ProboLabs.setLoggerDebugLevel = function(debugLevel) {\n highlighterLogger.setLogLevel(debugLevel);\n };\n\n // Retain existing API for backward compatibility\n window.ProboLabs.ElementTag = ElementTag;\n window.ProboLabs.highlightElements = highlightElements;\n window.ProboLabs.unhighlightElements = unhighlightElements;\n window.ProboLabs.findElements = findElements;\n window.ProboLabs.getElementInfo = getElementInfo;\n window.ProboLabs.highlight = window.ProboLabs.highlight;\n window.ProboLabs.unhighlight = window.ProboLabs.unhighlight;\n\n // --- Utility Functions ---\n function findClosestVisibleElement(element) {\n let current = element;\n while (current) {\n const style = window.getComputedStyle(current);\n if (\n style &&\n style.display !== 'none' &&\n style.visibility !== 'hidden' &&\n current.offsetWidth > 0 &&\n current.offsetHeight > 0\n ) {\n return current;\n }\n if (!current.parentElement || current === document.body) break;\n current = current.parentElement;\n }\n return null;\n }\n }\n\n exports.deserializeNodeFromJSON = deserializeNodeFromJSON;\n exports.detectScrollableContainers = detectScrollableContainers;\n exports.findElementByInfo = findElementByInfo;\n exports.findElementBySelectors = findElementBySelectors;\n exports.findElements = findElements;\n exports.generateCssPath = generateCssPath;\n exports.generateSmartSelector = generateSmartSelector;\n exports.getAriaLabelledByText = getAriaLabelledByText;\n exports.getContainingIFrame = getContainingIFrame;\n exports.getElementInfo = getElementInfo;\n exports.highlight = highlight;\n exports.highlightElements = highlightElements;\n exports.isScrollableContainer = isScrollableContainer;\n exports.serializeNodeToJSON = serializeNodeToJSON;\n exports.unhighlightElements = unhighlightElements;\n\n}));\n//# sourceMappingURL=probolabs.umd.js.map\n";
2
2
  import * as fs from 'fs';
3
3
  import * as path from 'path';
4
4
  import * as os from 'os';
@@ -181,6 +181,7 @@ class ProboLogger {
181
181
  error(...args) { if (this.shouldLog(ProboLogLevel.ERROR))
182
182
  console.error(this.preamble(ProboLogLevel.ERROR), ...args); }
183
183
  }
184
+ new ProboLogger('fetch');
184
185
  // Element cleaner logging
185
186
  // const elementLogger = new ProboLogger('element-cleaner');
186
187
  /**
@@ -880,6 +881,52 @@ class ApiClient {
880
881
  // For unknown errors, don't retry to avoid masking issues
881
882
  return false;
882
883
  }
884
+ isNetworkFailure(error) {
885
+ var _a, _b;
886
+ if (!error)
887
+ return false;
888
+ if (error instanceof ApiError && error.status === 0)
889
+ return true;
890
+ if ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('fetch failed'))
891
+ return true;
892
+ const errorCode = error.code || ((_b = error === null || error === void 0 ? void 0 : error.cause) === null || _b === void 0 ? void 0 : _b.code);
893
+ if (['ETIMEDOUT', 'ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ECONNABORTED'].includes(errorCode)) {
894
+ return true;
895
+ }
896
+ if (error.cause && this.isNetworkFailure(error.cause)) {
897
+ return true;
898
+ }
899
+ return false;
900
+ }
901
+ formatNetworkErrorDetails(error, depth = 0) {
902
+ if (!error || depth > 2) {
903
+ return { message: String(error) };
904
+ }
905
+ const details = {
906
+ name: error === null || error === void 0 ? void 0 : error.name,
907
+ message: error === null || error === void 0 ? void 0 : error.message
908
+ };
909
+ for (const key of ['code', 'errno', 'syscall', 'hostname', 'address', 'port', 'type']) {
910
+ if ((error === null || error === void 0 ? void 0 : error[key]) !== undefined) {
911
+ details[key] = error[key];
912
+ }
913
+ }
914
+ if (error === null || error === void 0 ? void 0 : error.cause) {
915
+ details.cause = this.formatNetworkErrorDetails(error.cause, depth + 1);
916
+ }
917
+ return details;
918
+ }
919
+ logNetworkFailure(operationName, error, context) {
920
+ if (!this.isNetworkFailure(error)) {
921
+ return;
922
+ }
923
+ apiLogger.error(`[${operationName}] Network failure`, {
924
+ apiUrl: this.apiUrl,
925
+ attempt: context === null || context === void 0 ? void 0 : context.attempt,
926
+ retriesLeft: context === null || context === void 0 ? void 0 : context.retriesLeft,
927
+ details: this.formatNetworkErrorDetails(error)
928
+ });
929
+ }
883
930
  /**
884
931
  * Generic helper to wrap API requests with retry logic and consistent error handling.
885
932
  */
@@ -890,11 +937,20 @@ class ApiClient {
890
937
  shouldRetry: (error) => {
891
938
  const shouldRetry = this.isRetryableError(error);
892
939
  if (!shouldRetry) {
893
- apiLogger.error(`${operationName} failed with non-retryable error: ${error.message || error}`);
940
+ if (this.isNetworkFailure(error)) {
941
+ this.logNetworkFailure(operationName, error);
942
+ }
943
+ else {
944
+ apiLogger.error(`${operationName} failed with non-retryable error: ${error.message || error}`);
945
+ }
894
946
  }
895
947
  return shouldRetry;
896
948
  },
897
949
  onFailedAttempt: error => {
950
+ this.logNetworkFailure(operationName, error, {
951
+ attempt: error.attemptNumber,
952
+ retriesLeft: error.retriesLeft
953
+ });
898
954
  apiLogger.warn(`${operationName} failed (retryable), attempt ${error.attemptNumber} of ${error.retriesLeft + error.attemptNumber}. Error: ${error.message}`);
899
955
  }
900
956
  });
@@ -1166,6 +1222,15 @@ class ApiClient {
1166
1222
  return data.index;
1167
1223
  });
1168
1224
  }
1225
+ async getProjects() {
1226
+ return this.requestWithRetry('getProjects', async () => {
1227
+ const response = await fetch(`${this.apiUrl}/projects/`, {
1228
+ method: 'GET',
1229
+ headers: this.getHeaders()
1230
+ });
1231
+ return this.handleResponse(response);
1232
+ });
1233
+ }
1169
1234
  } /* ApiClient */
1170
1235
 
1171
1236
  /**
@@ -1611,11 +1676,16 @@ const createUrlSlug = (url) => {
1611
1676
  .replace(/^-+|-+$/g, '');
1612
1677
  }
1613
1678
  };
1679
+ /**
1680
+ * Default @playwright/test version for generated test suites.
1681
+ * Aligns with @probolabs/playwright peer dependency (^1.54.0).
1682
+ */
1683
+ const DEFAULT_PLAYWRIGHT_TEST_VERSION = '^1.57.0';
1614
1684
  /**
1615
1685
  * Generate package.json content for a Playwright test project
1616
1686
  */
1617
1687
  function generatePackageJson(options) {
1618
- const { name, hasSecrets = false, testScript = 'npx playwright test' } = options;
1688
+ const { name, hasSecrets = false, testScript = 'npx playwright test', playwrightTestVersion = DEFAULT_PLAYWRIGHT_TEST_VERSION } = options;
1619
1689
  return `{
1620
1690
  "name": "${name}",
1621
1691
  "version": "1.0.0",
@@ -1625,7 +1695,7 @@ function generatePackageJson(options) {
1625
1695
  "test": "${testScript}"
1626
1696
  },
1627
1697
  "dependencies": {
1628
- "@playwright/test": "^1.40.0",
1698
+ "@playwright/test": "${playwrightTestVersion}",
1629
1699
  "@probolabs/playwright": "latest"${hasSecrets ? ',\n "dotenv": "latest"' : ''}
1630
1700
  }
1631
1701
  }`;
@@ -1928,6 +1998,42 @@ export default class ProboReporter implements Reporter {
1928
1998
  `;
1929
1999
  }
1930
2000
 
2001
+ /**
2002
+ * Node.js/Playwright-specific interpolation utilities.
2003
+ * These functions add process to the context for ${process.env.X} templates,
2004
+ * so they belong in probo-playwright (Node-only) rather than probo-shared (browser-compatible).
2005
+ */
2006
+ /**
2007
+ * Builds the standard interpolation context for template literals.
2008
+ * Merges params with additional context and includes process (when available)
2009
+ * so that ${process.env.VAR_NAME} templates resolve correctly.
2010
+ *
2011
+ * @param params The primary context (e.g., parameter table row)
2012
+ * @param additionalContext Optional extra context (e.g., extractedValues)
2013
+ * @returns Context object suitable for interpolateTemplate
2014
+ */
2015
+ function buildInterpolationContext(params, additionalContext) {
2016
+ return {
2017
+ ...params,
2018
+ ...(additionalContext || {}),
2019
+ ...(typeof process !== 'undefined' && { process }),
2020
+ };
2021
+ }
2022
+ /**
2023
+ * Interpolates a string with params and optional additional context.
2024
+ * Convenience wrapper that builds the standard context (including process for ${process.env.X})
2025
+ * and calls interpolateTemplate.
2026
+ *
2027
+ * @param str The string containing template literal syntax (e.g., "${process.env.TOTP_SECRET}")
2028
+ * @param params The primary context (e.g., parameter table row)
2029
+ * @param additionalContext Optional extra context (e.g., extractedValues)
2030
+ * @returns The interpolated string
2031
+ */
2032
+ function interpolateWithParams(str, params, additionalContext) {
2033
+ const context = buildInterpolationContext(params, additionalContext);
2034
+ return interpolateTemplate(str, context);
2035
+ }
2036
+
1931
2037
  // Default logger instance
1932
2038
  const proboLogger = new ProboLogger('proboLib');
1933
2039
 
@@ -4900,8 +5006,7 @@ class ProboPlaywright {
4900
5006
  * @returns The interpolated string
4901
5007
  */
4902
5008
  interpolate(str, additionalContext = {}) {
4903
- const context = { ...this.params, ...additionalContext };
4904
- return interpolateTemplate(str, context);
5009
+ return interpolateWithParams(str, this.params, additionalContext);
4905
5010
  }
4906
5011
  /**
4907
5012
  * Executes a single step in the test scenario with the specified action on the target element.
@@ -5603,7 +5708,18 @@ class ProboPlaywright {
5603
5708
  const bbox = await locator.boundingBox({ timeout: this.timeoutConfig.playwrightLocatorTimeout });
5604
5709
  if (bbox) {
5605
5710
  if (action === 'click') {
5606
- await this.page.mouse.click(bbox.x + bbox.width / 2, bbox.y + bbox.height / 2);
5711
+ // Move the mouse to the bottom right corner of the page before clicking
5712
+ const viewportSize = this.page.viewportSize();
5713
+ if (viewportSize) {
5714
+ proboLogger.log(`robustMouseAction: moving mouse to the bottom right corner of the page (${viewportSize.width - 1}, ${viewportSize.height - 1})`);
5715
+ await this.page.mouse.move(viewportSize.width - 1, viewportSize.height - 1);
5716
+ }
5717
+ else {
5718
+ proboLogger.warn('robustMouseAction: viewportSize not available, moving mouse to element top left corner');
5719
+ await this.page.mouse.move(bbox.x, bbox.y);
5720
+ }
5721
+ await this.page.waitForTimeout(100);
5722
+ await this.page.mouse.click(bbox.x, bbox.y);
5607
5723
  }
5608
5724
  else if (action === 'hover') {
5609
5725
  await this.page.mouse.move(bbox.x + bbox.width / 2, bbox.y + bbox.height / 2);
@@ -5840,7 +5956,9 @@ class ProboCodeGenerator {
5840
5956
  // Build elementInfo from backend data
5841
5957
  const elementInfo = backendInteraction.elementInfo || null;
5842
5958
  // Build interaction object
5959
+ // localId is the primary key for IndexedDB - always generate unique ID to support duplicated sequences
5843
5960
  const interaction = {
5961
+ localId: crypto.randomUUID(), // Generate unique localId for each interaction
5844
5962
  interactionId: backendInteraction.interactionId,
5845
5963
  action: action,
5846
5964
  argument: backendInteraction.argument || '',
@@ -6134,6 +6252,46 @@ async function updateRunStatus(runId, testSuiteId, updates, apiToken, apiUrl) {
6134
6252
  console.error(`❌ Error updating run status:`, error);
6135
6253
  }
6136
6254
  }
6255
+ /**
6256
+ * Find npm executable, preferring the one bundled with Node.js (for Electron compatibility)
6257
+ * Falls back to PATH for CI/CD environments
6258
+ */
6259
+ function findNpmExecutable() {
6260
+ const nodePath = process.execPath;
6261
+ const nodeDir = path.dirname(nodePath);
6262
+ // On Windows, npm might be npm.cmd
6263
+ const npmPaths = [
6264
+ path.join(nodeDir, 'npm'),
6265
+ path.join(nodeDir, 'npm.cmd'),
6266
+ ];
6267
+ for (const npmPath of npmPaths) {
6268
+ if (fs.existsSync(npmPath)) {
6269
+ return npmPath;
6270
+ }
6271
+ }
6272
+ // Fall back to PATH (works in CI/CD where npm is in PATH)
6273
+ return 'npm';
6274
+ }
6275
+ /**
6276
+ * Find npx executable, preferring the one bundled with Node.js (for Electron compatibility)
6277
+ * Falls back to PATH for CI/CD environments
6278
+ */
6279
+ function findNpxExecutable() {
6280
+ const nodePath = process.execPath;
6281
+ const nodeDir = path.dirname(nodePath);
6282
+ // On Windows, npx might be npx.cmd
6283
+ const npxPaths = [
6284
+ path.join(nodeDir, 'npx'),
6285
+ path.join(nodeDir, 'npx.cmd'),
6286
+ ];
6287
+ for (const npxPath of npxPaths) {
6288
+ if (fs.existsSync(npxPath)) {
6289
+ return npxPath;
6290
+ }
6291
+ }
6292
+ // Fall back to PATH (works in CI/CD where npx is in PATH)
6293
+ return 'npx';
6294
+ }
6137
6295
  /**
6138
6296
  * TestSuiteRunner - Handles test suite file generation and execution
6139
6297
  */
@@ -6377,7 +6535,8 @@ class TestSuiteRunner {
6377
6535
  // Install dependencies
6378
6536
  console.log(`📦 Installing dependencies in ${testSuiteDir}...`);
6379
6537
  try {
6380
- const { stdout: installStdout, stderr: installStderr } = await execAsync('npm install', { cwd: testSuiteDir, timeout: 300000 } // 5 minute timeout for install
6538
+ const npmExecutable = findNpmExecutable();
6539
+ const { stdout: installStdout, stderr: installStderr } = await execAsync(`${npmExecutable} install`, { cwd: testSuiteDir, timeout: 300000 } // 5 minute timeout for install
6381
6540
  );
6382
6541
  console.log('✅ Dependencies installed successfully');
6383
6542
  if (installStdout)
@@ -6413,6 +6572,23 @@ class TestSuiteRunner {
6413
6572
  runId: currentRunId,
6414
6573
  };
6415
6574
  }
6575
+ // Install Playwright Chromium browser (required for test execution)
6576
+ console.log(`🌐 Installing Playwright Chromium browser...`);
6577
+ try {
6578
+ const npxExecutable = findNpxExecutable();
6579
+ const { stdout: browserStdout, stderr: browserStderr } = await execAsync(`${npxExecutable} playwright install chromium`, { cwd: testSuiteDir, timeout: 300000 } // 5 minute timeout for browser install
6580
+ );
6581
+ console.log('✅ Playwright Chromium browser installed successfully');
6582
+ if (browserStdout)
6583
+ console.log(browserStdout);
6584
+ if (browserStderr)
6585
+ console.warn(browserStderr);
6586
+ }
6587
+ catch (browserError) {
6588
+ console.warn('⚠️ Failed to install Playwright browsers:', browserError);
6589
+ // Don't fail the entire run if browser install fails - Playwright might handle it gracefully
6590
+ // or the error will be caught when trying to run tests
6591
+ }
6416
6592
  // Run Playwright tests with streaming output
6417
6593
  console.log(`🚀 Running Playwright tests in ${testSuiteDir}...`);
6418
6594
  if (playwrightArgs.length > 0) {
@@ -6434,10 +6610,16 @@ class TestSuiteRunner {
6434
6610
  let lastStepsUpdate = 0;
6435
6611
  const collectedSteps = [];
6436
6612
  // Use spawn for streaming output
6437
- const testProcess = spawn('npx', ['playwright', 'test', ...playwrightArgs], {
6613
+ const npxExecutable = findNpxExecutable();
6614
+ const testProcess = spawn(npxExecutable, ['playwright', 'test', ...playwrightArgs], {
6438
6615
  cwd: testSuiteDir,
6439
6616
  shell: true,
6440
6617
  stdio: ['ignore', 'pipe', 'pipe'],
6618
+ env: {
6619
+ ...process.env,
6620
+ PROBO_API_KEY: apiToken,
6621
+ PROBO_API_ENDPOINT: apiUrl,
6622
+ },
6441
6623
  });
6442
6624
  // Stream stdout line by line
6443
6625
  (_a = testProcess.stdout) === null || _a === void 0 ? void 0 : _a.on('data', async (data) => {
@@ -6608,7 +6790,11 @@ class TestSuiteRunner {
6608
6790
  }
6609
6791
  const exitCode = code !== null && code !== void 0 ? code : 1;
6610
6792
  const success = exitCode === 0;
6611
- const isTestFailure = exitCode === 1 && stdout.length > 0;
6793
+ // A test failure is when tests actually ran but some failed (exit code 1 with test results)
6794
+ // An execution error is when tests couldn't run (exit code 1 without test results, or with stderr errors)
6795
+ const hasTestResults = reporterStats.passed + reporterStats.failed + reporterStats.skipped > 0;
6796
+ const isTestFailure = exitCode === 1 && hasTestResults;
6797
+ const isExecutionError = exitCode !== 0 && !isTestFailure;
6612
6798
  console.log(success ? '✅ Tests completed successfully' : (isTestFailure ? '⚠️ Tests completed with failures' : '❌ Test execution failed'));
6613
6799
  // Parse final statistics from metadata/stdout as fallback
6614
6800
  let parsedStats = null;
@@ -6622,16 +6808,47 @@ class TestSuiteRunner {
6622
6808
  // Fall back to parsed stats only if reporterStats is empty
6623
6809
  const totalFromReporter = reporterStats.passed + reporterStats.failed + reporterStats.skipped;
6624
6810
  const finalStats = totalFromReporter > 0 ? reporterStats : (parsedStats || { passed: 0, failed: 0, skipped: 0 });
6811
+ // Build error message from stderr or stdout if it's an execution error
6812
+ let errorMessage = undefined;
6813
+ if (isExecutionError) {
6814
+ // Check both stderr and stdout for error messages (errors can appear in either)
6815
+ const stderrLines = stderr.trim().split('\n').filter(line => line.trim().length > 0);
6816
+ const stdoutLines = stdout.trim().split('\n').filter(line => line.trim().length > 0);
6817
+ const allErrorLines = [...stderrLines, ...stdoutLines].filter(line => line.includes('Error:') ||
6818
+ line.includes('Missing') ||
6819
+ line.includes('No tests found') ||
6820
+ line.includes('failed') ||
6821
+ line.includes('Failed'));
6822
+ if (allErrorLines.length > 0) {
6823
+ // Use the last error line found
6824
+ errorMessage = allErrorLines[allErrorLines.length - 1];
6825
+ }
6826
+ else if (stderrLines.length > 0) {
6827
+ // Fall back to last stderr line if no clear error pattern found
6828
+ errorMessage = stderrLines[stderrLines.length - 1];
6829
+ }
6830
+ else if (stdoutLines.length > 0 && stdoutLines.some(line => line.toLowerCase().includes('error'))) {
6831
+ // Check stdout for error messages
6832
+ const errorLines = stdoutLines.filter(line => line.toLowerCase().includes('error'));
6833
+ errorMessage = errorLines[errorLines.length - 1];
6834
+ }
6835
+ else {
6836
+ errorMessage = `Test execution failed with exit code ${exitCode}`;
6837
+ }
6838
+ }
6625
6839
  // Update run status with final steps
6626
6840
  if (currentRunId) {
6627
6841
  const finalStatus = success ? 'success' : 'error';
6842
+ // Ensure error message is set for execution errors
6843
+ const finalErrorMessage = isExecutionError ? (errorMessage || `Test execution failed with exit code ${exitCode}`) : errorMessage;
6844
+ console.log(`📊 [TestSuiteRunner] Updating run ${currentRunId} status: ${finalStatus}, exitCode: ${exitCode}, isExecutionError: ${isExecutionError}, errorMessage: ${finalErrorMessage || 'none'}`);
6628
6845
  await updateRunStatus(currentRunId, testSuiteId, {
6629
6846
  status: finalStatus,
6630
6847
  exit_code: exitCode,
6631
6848
  stdout: stdout,
6632
6849
  stderr: stderr,
6633
6850
  steps: [...collectedSteps], // Save final steps state
6634
- error_message: success || isTestFailure ? undefined : `Test execution failed with exit code ${exitCode}`,
6851
+ error_message: finalErrorMessage,
6635
6852
  tests_passed: finalStats.passed,
6636
6853
  tests_failed: finalStats.failed,
6637
6854
  tests_skipped: finalStats.skipped,
@@ -6642,6 +6859,7 @@ class TestSuiteRunner {
6642
6859
  exit_code: exitCode,
6643
6860
  stdout: stdout,
6644
6861
  stderr: stderr,
6862
+ error_message: errorMessage,
6645
6863
  tests_passed: finalStats.passed,
6646
6864
  tests_failed: finalStats.failed,
6647
6865
  tests_skipped: finalStats.skipped,
@@ -6651,13 +6869,26 @@ class TestSuiteRunner {
6651
6869
  // Upload artifacts functionality preserved but disabled
6652
6870
  // await this.uploadArtifacts(currentRunId, testSuiteId, testSuiteDir, apiToken, apiUrl);
6653
6871
  }
6872
+ // Ensure error message is set for execution errors even if extraction failed
6873
+ let finalError = errorMessage;
6874
+ if (isExecutionError && !finalError) {
6875
+ // Fallback: try to extract any error from stdout/stderr
6876
+ const allOutput = (stdout + '\n' + stderr).trim();
6877
+ const errorMatch = allOutput.match(/Error:.*/);
6878
+ if (errorMatch) {
6879
+ finalError = errorMatch[0].split('\n')[0]; // Take first line of error
6880
+ }
6881
+ else {
6882
+ finalError = `Test execution failed with exit code ${exitCode}`;
6883
+ }
6884
+ }
6654
6885
  resolve({
6655
6886
  success: success,
6656
6887
  exitCode: exitCode,
6657
6888
  stdout: stdout,
6658
6889
  stderr: stderr,
6659
- // Only set error if it's not a success and not a test failure (i.e., real execution error)
6660
- error: success || isTestFailure ? undefined : `Test execution failed with exit code ${exitCode}`,
6890
+ // Set error message for execution errors (not test failures)
6891
+ error: finalError,
6661
6892
  runId: currentRunId,
6662
6893
  });
6663
6894
  });
@@ -6861,7 +7092,8 @@ class TestSuiteRunner {
6861
7092
  // Install dependencies
6862
7093
  console.log(`📦 Installing dependencies in ${projectDir}...`);
6863
7094
  try {
6864
- const { stdout: installStdout, stderr: installStderr } = await execAsync('npm install', { cwd: projectDir, timeout: 300000 } // 5 minute timeout for install
7095
+ const npmExecutable = findNpmExecutable();
7096
+ const { stdout: installStdout, stderr: installStderr } = await execAsync(`${npmExecutable} install`, { cwd: projectDir, timeout: 300000 } // 5 minute timeout for install
6865
7097
  );
6866
7098
  console.log('✅ Dependencies installed successfully');
6867
7099
  if (installStdout)
@@ -6880,6 +7112,23 @@ class TestSuiteRunner {
6880
7112
  error: errorMsg,
6881
7113
  };
6882
7114
  }
7115
+ // Install Playwright Chromium browser (required for test execution)
7116
+ console.log(`🌐 Installing Playwright Chromium browser...`);
7117
+ try {
7118
+ const npxExecutable = findNpxExecutable();
7119
+ const { stdout: browserStdout, stderr: browserStderr } = await execAsync(`${npxExecutable} playwright install chromium`, { cwd: projectDir, timeout: 300000 } // 5 minute timeout for browser install
7120
+ );
7121
+ console.log('✅ Playwright Chromium browser installed successfully');
7122
+ if (browserStdout)
7123
+ console.log(browserStdout);
7124
+ if (browserStderr)
7125
+ console.warn(browserStderr);
7126
+ }
7127
+ catch (browserError) {
7128
+ console.warn('⚠️ Failed to install Playwright browsers:', browserError);
7129
+ // Don't fail the entire run if browser install fails - Playwright might handle it gracefully
7130
+ // or the error will be caught when trying to run tests
7131
+ }
6883
7132
  // Run Playwright tests with streaming output
6884
7133
  console.log(`🚀 Running Playwright tests in ${projectDir}...`);
6885
7134
  if (playwrightArgs.length > 0) {
@@ -6892,10 +7141,16 @@ class TestSuiteRunner {
6892
7141
  let hasResolved = false;
6893
7142
  let stdoutLineBuffer = '';
6894
7143
  // Use spawn for streaming output
6895
- const testProcess = spawn('npx', ['playwright', 'test', ...playwrightArgs], {
7144
+ const npxExecutable = findNpxExecutable();
7145
+ const testProcess = spawn(npxExecutable, ['playwright', 'test', ...playwrightArgs], {
6896
7146
  cwd: projectDir,
6897
7147
  shell: true,
6898
7148
  stdio: ['ignore', 'pipe', 'pipe'],
7149
+ env: {
7150
+ ...process.env,
7151
+ PROBO_API_KEY: apiToken,
7152
+ PROBO_API_ENDPOINT: apiUrl,
7153
+ },
6899
7154
  });
6900
7155
  // Stream stdout line by line
6901
7156
  (_a = testProcess.stdout) === null || _a === void 0 ? void 0 : _a.on('data', async (data) => {
@@ -6937,14 +7192,45 @@ class TestSuiteRunner {
6937
7192
  }
6938
7193
  const exitCode = code !== null && code !== void 0 ? code : 1;
6939
7194
  const success = exitCode === 0;
6940
- const isTestFailure = exitCode === 1 && stdout.length > 0;
7195
+ // A test failure is when tests actually ran but some failed (exit code 1 with test results)
7196
+ // An execution error is when tests couldn't run (exit code 1 without test results)
7197
+ const isTestFailure = exitCode === 1 && stdout.length > 0 && stdout.includes('failed') || stdout.includes('passed');
7198
+ const isExecutionError = exitCode !== 0 && !isTestFailure;
6941
7199
  console.log(success ? '✅ Tests completed successfully' : (isTestFailure ? '⚠️ Tests completed with failures' : '❌ Test execution failed'));
7200
+ // Build error message from stderr or stdout if it's an execution error
7201
+ let errorMessage = undefined;
7202
+ if (isExecutionError) {
7203
+ // Check both stderr and stdout for error messages (errors can appear in either)
7204
+ const stderrLines = stderr.trim().split('\n').filter(line => line.trim().length > 0);
7205
+ const stdoutLines = stdout.trim().split('\n').filter(line => line.trim().length > 0);
7206
+ const allErrorLines = [...stderrLines, ...stdoutLines].filter(line => line.includes('Error:') ||
7207
+ line.includes('Missing') ||
7208
+ line.includes('No tests found') ||
7209
+ line.includes('failed') ||
7210
+ line.includes('Failed'));
7211
+ if (allErrorLines.length > 0) {
7212
+ // Use the last error line found
7213
+ errorMessage = allErrorLines[allErrorLines.length - 1];
7214
+ }
7215
+ else if (stderrLines.length > 0) {
7216
+ // Fall back to last stderr line if no clear error pattern found
7217
+ errorMessage = stderrLines[stderrLines.length - 1];
7218
+ }
7219
+ else if (stdoutLines.length > 0 && stdoutLines.some(line => line.toLowerCase().includes('error'))) {
7220
+ // Check stdout for error messages
7221
+ const errorLines = stdoutLines.filter(line => line.toLowerCase().includes('error'));
7222
+ errorMessage = errorLines[errorLines.length - 1];
7223
+ }
7224
+ else {
7225
+ errorMessage = `Test execution failed with exit code ${exitCode}`;
7226
+ }
7227
+ }
6942
7228
  resolve({
6943
7229
  success: success,
6944
7230
  exitCode: exitCode,
6945
7231
  stdout: stdout,
6946
7232
  stderr: stderr,
6947
- error: success || isTestFailure ? undefined : `Test execution failed with exit code ${exitCode}`,
7233
+ error: errorMessage,
6948
7234
  });
6949
7235
  });
6950
7236
  // Handle process errors
@@ -7050,8 +7336,7 @@ class Probo {
7050
7336
  * @returns The interpolated string
7051
7337
  */
7052
7338
  interpolate(str, additionalContext = {}) {
7053
- const context = { ...this.params, ...additionalContext };
7054
- return interpolateTemplate(str, context);
7339
+ return interpolateWithParams(str, this.params, additionalContext);
7055
7340
  }
7056
7341
  async askAI(page, question, options, assertAnswer = '') {
7057
7342
  var _a, _b;
@@ -7369,5 +7654,5 @@ class Probo {
7369
7654
  }
7370
7655
  }
7371
7656
 
7372
- export { AIModel, Highlighter, NavTracker, OTP, PlaywrightAction, Probo, ProboCodeGenerator, ProboLogLevel, ProboPlaywright, TestSuiteRunner, createUrlSlug, extractRequiredEnvVars, findClosestVisibleElement, generateCode, getRequiredEnvVars };
7657
+ export { AIModel, Highlighter, NavTracker, OTP, PlaywrightAction, Probo, ProboCodeGenerator, ProboLogLevel, ProboPlaywright, TestSuiteRunner, buildInterpolationContext, createUrlSlug, extractRequiredEnvVars, findClosestVisibleElement, generateCode, getRequiredEnvVars, interpolateWithParams };
7373
7658
  //# sourceMappingURL=index.js.map