From 80c17155b1534887a2e75fbeef419c93f9258c44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Mar 2026 16:39:17 +0100 Subject: [PATCH] refactor: decompose selector system into parse/match/resolve/build modules Closes #159 Co-Authored-By: Claude Opus 4.6 (1M context) --- src/daemon/selectors-build.ts | 62 ++++ src/daemon/selectors-match.ts | 65 ++++ src/daemon/selectors-parse.ts | 253 +++++++++++++++ src/daemon/selectors-resolve.ts | 167 ++++++++++ src/daemon/selectors.ts | 547 +------------------------------- 5 files changed, 558 insertions(+), 536 deletions(-) create mode 100644 src/daemon/selectors-build.ts create mode 100644 src/daemon/selectors-match.ts create mode 100644 src/daemon/selectors-parse.ts create mode 100644 src/daemon/selectors-resolve.ts diff --git a/src/daemon/selectors-build.ts b/src/daemon/selectors-build.ts new file mode 100644 index 0000000000..587db4e45e --- /dev/null +++ b/src/daemon/selectors-build.ts @@ -0,0 +1,62 @@ +import type { SnapshotNode } from '../utils/snapshot.ts'; +import { extractNodeText, normalizeType } from './snapshot-processing.ts'; +import { uniqueStrings } from './action-utils.ts'; +import { isNodeVisible } from './selectors-match.ts'; + +export function buildSelectorChainForNode( + node: SnapshotNode, + _platform: 'ios' | 'android', + options: { action?: 'click' | 'fill' | 'get' } = {}, +): string[] { + const chain: string[] = []; + const role = normalizeType(node.type ?? ''); + const id = normalizeSelectorText(node.identifier); + const label = normalizeSelectorText(node.label); + const value = normalizeSelectorText(node.value); + const text = normalizeSelectorText(extractNodeText(node)); + const requireEditable = options.action === 'fill'; + + if (id) { + chain.push(`id=${quoteSelectorValue(id)}`); + } + if (role && label) { + chain.push( + requireEditable + ? `role=${quoteSelectorValue(role)} label=${quoteSelectorValue(label)} editable=true` + : `role=${quoteSelectorValue(role)} label=${quoteSelectorValue(label)}`, + ); + } + if (label) { + chain.push(requireEditable ? `label=${quoteSelectorValue(label)} editable=true` : `label=${quoteSelectorValue(label)}`); + } + if (value) { + chain.push(requireEditable ? `value=${quoteSelectorValue(value)} editable=true` : `value=${quoteSelectorValue(value)}`); + } + if (text && text !== label && text !== value) { + chain.push(requireEditable ? `text=${quoteSelectorValue(text)} editable=true` : `text=${quoteSelectorValue(text)}`); + } + if (role && requireEditable && !chain.some((entry) => entry.includes('editable=true'))) { + chain.push(`role=${quoteSelectorValue(role)} editable=true`); + } + + const deduped = uniqueStrings(chain); + if (deduped.length === 0 && role) { + deduped.push(requireEditable ? `role=${quoteSelectorValue(role)} editable=true` : `role=${quoteSelectorValue(role)}`); + } + if (deduped.length === 0) { + const visible = isNodeVisible(node); + if (visible) deduped.push('visible=true'); + } + return deduped; +} + +function quoteSelectorValue(value: string): string { + return JSON.stringify(value); +} + +function normalizeSelectorText(value: string | undefined): string | null { + if (!value) return null; + const trimmed = value.trim(); + if (!trimmed) return null; + return trimmed; +} diff --git a/src/daemon/selectors-match.ts b/src/daemon/selectors-match.ts new file mode 100644 index 0000000000..63628919de --- /dev/null +++ b/src/daemon/selectors-match.ts @@ -0,0 +1,65 @@ +import type { SnapshotNode } from '../utils/snapshot.ts'; +import { extractNodeText, isFillableType, normalizeType } from './snapshot-processing.ts'; +import type { Selector, SelectorTerm } from './selectors-parse.ts'; + +export function matchesSelector(node: SnapshotNode, selector: Selector, platform: 'ios' | 'android'): boolean { + return selector.terms.every((term) => matchesTerm(node, term, platform)); +} + +export function isNodeVisible(node: SnapshotNode): boolean { + if (node.hittable === true) return true; + if (!node.rect) return false; + return node.rect.width > 0 && node.rect.height > 0; +} + +export function isNodeEditable(node: SnapshotNode, platform: 'ios' | 'android'): boolean { + const type = node.type ?? ''; + return isFillableType(type, platform) && node.enabled !== false; +} + +function matchesTerm(node: SnapshotNode, term: SelectorTerm, platform: 'ios' | 'android'): boolean { + switch (term.key) { + case 'id': + return textEquals(node.identifier, String(term.value)); + case 'role': + return roleEquals(node.type, String(term.value)); + case 'label': + return textEquals(node.label, String(term.value)); + case 'value': + return textEquals(node.value, String(term.value)); + case 'text': { + const query = normalizeText(String(term.value)); + return normalizeText(extractNodeText(node)) === query; + } + case 'visible': + return isNodeVisible(node) === Boolean(term.value); + case 'hidden': + return (!isNodeVisible(node)) === Boolean(term.value); + case 'editable': + return isNodeEditable(node, platform) === Boolean(term.value); + case 'selected': + return Boolean(node.selected === true) === Boolean(term.value); + case 'enabled': + return Boolean(node.enabled !== false) === Boolean(term.value); + case 'hittable': + return Boolean(node.hittable === true) === Boolean(term.value); + default: + return false; + } +} + +function textEquals(value: string | undefined, query: string): boolean { + return normalizeText(value ?? '') === normalizeText(query); +} + +function roleEquals(value: string | undefined, query: string): boolean { + return normalizeRole(value ?? '') === normalizeRole(query); +} + +function normalizeText(value: string): string { + return value.trim().toLowerCase().replace(/\s+/g, ' '); +} + +function normalizeRole(value: string): string { + return normalizeType(value); +} diff --git a/src/daemon/selectors-parse.ts b/src/daemon/selectors-parse.ts new file mode 100644 index 0000000000..1c55c3e524 --- /dev/null +++ b/src/daemon/selectors-parse.ts @@ -0,0 +1,253 @@ +import { AppError } from '../utils/errors.ts'; + +export type SelectorKey = + | 'id' + | 'role' + | 'text' + | 'label' + | 'value' + | 'visible' + | 'hidden' + | 'editable' + | 'selected' + | 'enabled' + | 'hittable'; + +export type SelectorTerm = { + key: SelectorKey; + value: string | boolean; +}; + +export type Selector = { + raw: string; + terms: SelectorTerm[]; +}; + +export type SelectorChain = { + raw: string; + selectors: Selector[]; +}; + +const TEXT_KEYS = new Set(['id', 'role', 'text', 'label', 'value']); +const BOOLEAN_KEYS = new Set([ + 'visible', + 'hidden', + 'editable', + 'selected', + 'enabled', + 'hittable', +]); +const ALL_KEYS = new Set([...TEXT_KEYS, ...BOOLEAN_KEYS]); + +export function parseSelectorChain(expression: string): SelectorChain { + const raw = expression.trim(); + if (!raw) { + throw new AppError('INVALID_ARGS', 'Selector expression cannot be empty'); + } + const segments = splitByFallback(raw); + if (segments.length === 0) { + throw new AppError('INVALID_ARGS', 'Selector expression cannot be empty'); + } + return { + raw, + selectors: segments.map((segment) => parseSelector(segment)), + }; +} + +export function tryParseSelectorChain(expression: string): SelectorChain | null { + try { + return parseSelectorChain(expression); + } catch { + return null; + } +} + +export function isSelectorToken(token: string): boolean { + const trimmed = token.trim(); + if (!trimmed) return false; + if (trimmed === '||') return true; + const equalsIdx = trimmed.indexOf('='); + if (equalsIdx !== -1) { + const key = trimmed.slice(0, equalsIdx).trim().toLowerCase() as SelectorKey; + return ALL_KEYS.has(key); + } + return ALL_KEYS.has(trimmed.toLowerCase() as SelectorKey); +} + +export function splitSelectorFromArgs( + args: string[], + options: { preferTrailingValue?: boolean } = {}, +): { selectorExpression: string; rest: string[] } | null { + if (args.length === 0) return null; + const preferTrailingValue = options.preferTrailingValue ?? false; + let i = 0; + const boundaries: number[] = []; + while (i < args.length && isSelectorToken(args[i])) { + i += 1; + const candidate = args.slice(0, i).join(' ').trim(); + if (!candidate) continue; + if (tryParseSelectorChain(candidate)) { + boundaries.push(i); + } + } + if (boundaries.length === 0) return null; + let boundary = boundaries[boundaries.length - 1]; + if (preferTrailingValue) { + for (let j = boundaries.length - 1; j >= 0; j -= 1) { + if (boundaries[j] < args.length) { + boundary = boundaries[j]; + break; + } + } + } + const selectorExpression = args.slice(0, boundary).join(' ').trim(); + if (!selectorExpression) return null; + return { + selectorExpression, + rest: args.slice(boundary), + }; +} + +export function splitIsSelectorArgs(positionals: string[]): { + predicate: string; + split: { selectorExpression: string; rest: string[] } | null; +} { + const predicate = positionals[0] ?? ''; + const split = splitSelectorFromArgs(positionals.slice(1), { + preferTrailingValue: predicate === 'text', + }); + return { predicate, split }; +} + +function parseSelector(segment: string): Selector { + const raw = segment.trim(); + if (!raw) throw new AppError('INVALID_ARGS', 'Selector segment cannot be empty'); + const tokens = tokenize(raw); + if (tokens.length === 0) { + throw new AppError('INVALID_ARGS', `Invalid selector segment: ${segment}`); + } + const terms = tokens.map(parseTerm); + return { raw, terms }; +} + +function parseTerm(token: string): SelectorTerm { + const normalized = token.trim(); + if (!normalized) { + throw new AppError('INVALID_ARGS', 'Empty selector term'); + } + const equalsIdx = normalized.indexOf('='); + if (equalsIdx === -1) { + const key = normalized.toLowerCase() as SelectorKey; + if (!BOOLEAN_KEYS.has(key)) { + throw new AppError('INVALID_ARGS', `Invalid selector term "${token}", expected key=value`); + } + return { key, value: true }; + } + const keyRaw = normalized.slice(0, equalsIdx).trim().toLowerCase() as SelectorKey; + const valueRaw = normalized.slice(equalsIdx + 1).trim(); + if (!ALL_KEYS.has(keyRaw)) { + throw new AppError('INVALID_ARGS', `Unknown selector key: ${keyRaw}`); + } + if (!valueRaw) { + throw new AppError('INVALID_ARGS', `Missing selector value for key: ${keyRaw}`); + } + if (BOOLEAN_KEYS.has(keyRaw)) { + const parsedBoolean = parseBoolean(valueRaw); + if (parsedBoolean === null) { + throw new AppError('INVALID_ARGS', `Invalid boolean value for ${keyRaw}: ${valueRaw}`); + } + return { key: keyRaw, value: parsedBoolean }; + } + return { key: keyRaw, value: unquote(valueRaw) }; +} + +function splitByFallback(expression: string): string[] { + const segments: string[] = []; + let current = ''; + let quote: '"' | "'" | null = null; + for (let i = 0; i < expression.length; i += 1) { + const ch = expression[i]; + if ((ch === '"' || ch === "'") && !isEscapedQuote(expression, i)) { + if (!quote) { + quote = ch; + } else if (quote === ch) { + quote = null; + } + current += ch; + continue; + } + if (!quote && ch === '|' && expression[i + 1] === '|') { + const segment = current.trim(); + if (!segment) { + throw new AppError('INVALID_ARGS', `Invalid selector fallback expression: ${expression}`); + } + segments.push(segment); + current = ''; + i += 1; + continue; + } + current += ch; + } + const finalSegment = current.trim(); + if (!finalSegment) { + throw new AppError('INVALID_ARGS', `Invalid selector fallback expression: ${expression}`); + } + segments.push(finalSegment); + return segments; +} + +function tokenize(segment: string): string[] { + const tokens: string[] = []; + let current = ''; + let quote: '"' | "'" | null = null; + for (let i = 0; i < segment.length; i += 1) { + const ch = segment[i]; + if ((ch === '"' || ch === "'") && !isEscapedQuote(segment, i)) { + if (!quote) { + quote = ch; + } else if (quote === ch) { + quote = null; + } + current += ch; + continue; + } + if (!quote && /\s/.test(ch)) { + if (current.trim().length > 0) { + tokens.push(current.trim()); + } + current = ''; + continue; + } + current += ch; + } + if (quote) { + throw new AppError('INVALID_ARGS', `Unclosed quote in selector: ${segment}`); + } + if (current.trim().length > 0) { + tokens.push(current.trim()); + } + return tokens; +} + +function unquote(value: string): string { + const trimmed = value.trim(); + if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) { + return trimmed.slice(1, -1).replace(/\\(["'])/g, '$1'); + } + return trimmed; +} + +function parseBoolean(value: string): boolean | null { + const normalized = unquote(value).toLowerCase(); + if (normalized === 'true') return true; + if (normalized === 'false') return false; + return null; +} + +function isEscapedQuote(source: string, index: number): boolean { + let backslashCount = 0; + for (let i = index - 1; i >= 0 && source[i] === '\\'; i -= 1) { + backslashCount += 1; + } + return backslashCount % 2 === 1; +} diff --git a/src/daemon/selectors-resolve.ts b/src/daemon/selectors-resolve.ts new file mode 100644 index 0000000000..c45a3738a4 --- /dev/null +++ b/src/daemon/selectors-resolve.ts @@ -0,0 +1,167 @@ +import type { SnapshotNode, SnapshotState } from '../utils/snapshot.ts'; +import type { Selector, SelectorChain } from './selectors-parse.ts'; +import { matchesSelector } from './selectors-match.ts'; + +export type SelectorDiagnostics = { + selector: string; + matches: number; +}; + +type SelectorResolution = { + node: SnapshotNode; + selector: Selector; + selectorIndex: number; + matches: number; + diagnostics: SelectorDiagnostics[]; +}; + +export function resolveSelectorChain( + nodes: SnapshotState['nodes'], + chain: SelectorChain, + options: { + platform: 'ios' | 'android'; + requireRect?: boolean; + requireUnique?: boolean; + disambiguateAmbiguous?: boolean; + }, +): SelectorResolution | null { + const requireRect = options.requireRect ?? false; + const requireUnique = options.requireUnique ?? true; + const disambiguateAmbiguous = options.disambiguateAmbiguous ?? false; + const diagnostics: SelectorDiagnostics[] = []; + for (let i = 0; i < chain.selectors.length; i += 1) { + const selector = chain.selectors[i]; + const summary = analyzeSelectorMatches(nodes, selector, { + platform: options.platform, + requireRect, + }); + diagnostics.push({ selector: selector.raw, matches: summary.count }); + if (summary.count === 0 || !summary.firstNode) continue; + if (requireUnique && summary.count !== 1) { + if (!disambiguateAmbiguous) continue; + const disambiguatedNode = summary.disambiguated; + if (!disambiguatedNode) continue; + return { + node: disambiguatedNode, + selector, + selectorIndex: i, + matches: summary.count, + diagnostics, + }; + } + return { + node: summary.firstNode, + selector, + selectorIndex: i, + matches: summary.count, + diagnostics, + }; + } + return null; +} + +export function findSelectorChainMatch( + nodes: SnapshotState['nodes'], + chain: SelectorChain, + options: { + platform: 'ios' | 'android'; + requireRect?: boolean; + }, +): { selectorIndex: number; selector: Selector; matches: number; diagnostics: SelectorDiagnostics[] } | null { + const requireRect = options.requireRect ?? false; + const diagnostics: SelectorDiagnostics[] = []; + for (let i = 0; i < chain.selectors.length; i += 1) { + const selector = chain.selectors[i]; + const matches = countSelectorMatchesOnly(nodes, selector, { + platform: options.platform, + requireRect, + }); + diagnostics.push({ selector: selector.raw, matches }); + if (matches > 0) { + return { selectorIndex: i, selector, matches, diagnostics }; + } + } + return null; +} + +export function formatSelectorFailure( + chain: SelectorChain, + diagnostics: SelectorDiagnostics[], + options: { unique?: boolean }, +): string { + const unique = options.unique ?? true; + if (diagnostics.length === 0) { + return `Selector did not match: ${chain.raw}`; + } + const summary = diagnostics.map((entry) => `${entry.selector} -> ${entry.matches}`).join(', '); + if (unique) { + return `Selector did not resolve uniquely (${summary})`; + } + return `Selector did not match (${summary})`; +} + +function analyzeSelectorMatches( + nodes: SnapshotState['nodes'], + selector: Selector, + options: { platform: 'ios' | 'android'; requireRect: boolean }, +): { count: number; firstNode: SnapshotNode | null; disambiguated: SnapshotNode | null } { + let count = 0; + let firstNode: SnapshotNode | null = null; + let best: SnapshotNode | null = null; + let tie = false; + for (const node of nodes) { + if (options.requireRect && !node.rect) continue; + if (!matchesSelector(node, selector, options.platform)) continue; + count += 1; + if (!firstNode) { + firstNode = node; + } + if (!best) { + best = node; + continue; + } + const comparison = compareDisambiguationCandidates(node, best); + if (comparison > 0) { + best = node; + tie = false; + continue; + } + if (comparison === 0) { + tie = true; + } + } + return { + count, + firstNode, + disambiguated: tie ? null : best, + }; +} + +function countSelectorMatchesOnly( + nodes: SnapshotState['nodes'], + selector: Selector, + options: { platform: 'ios' | 'android'; requireRect: boolean }, +): number { + let count = 0; + for (const node of nodes) { + if (options.requireRect && !node.rect) continue; + if (!matchesSelector(node, selector, options.platform)) continue; + count += 1; + } + return count; +} + +function compareDisambiguationCandidates(a: SnapshotNode, b: SnapshotNode): number { + const depthA = a.depth ?? 0; + const depthB = b.depth ?? 0; + if (depthA !== depthB) return depthA > depthB ? 1 : -1; + const areaA = areaOfNode(a); + const areaB = areaOfNode(b); + if (areaA !== areaB) return areaA < areaB ? 1 : -1; + return 0; +} + +function areaOfNode(node: SnapshotNode): number { + if (!node.rect) return Number.POSITIVE_INFINITY; + return node.rect.width * node.rect.height; +} diff --git a/src/daemon/selectors.ts b/src/daemon/selectors.ts index caf46a0070..65c3c63d2a 100644 --- a/src/daemon/selectors.ts +++ b/src/daemon/selectors.ts @@ -1,540 +1,15 @@ -import { AppError } from '../utils/errors.ts'; -import type { SnapshotNode, SnapshotState } from '../utils/snapshot.ts'; -import { extractNodeText, isFillableType, normalizeType } from './snapshot-processing.ts'; -import { uniqueStrings } from './action-utils.ts'; +export type { SelectorChain } from './selectors-parse.ts'; -type SelectorKey = - | 'id' - | 'role' - | 'text' - | 'label' - | 'value' - | 'visible' - | 'hidden' - | 'editable' - | 'selected' - | 'enabled' - | 'hittable'; +export { + parseSelectorChain, + tryParseSelectorChain, + isSelectorToken, + splitSelectorFromArgs, + splitIsSelectorArgs, +} from './selectors-parse.ts'; -type SelectorTerm = { - key: SelectorKey; - value: string | boolean; -}; +export { isNodeVisible, isNodeEditable } from './selectors-match.ts'; -type Selector = { - raw: string; - terms: SelectorTerm[]; -}; +export { resolveSelectorChain, findSelectorChainMatch, formatSelectorFailure } from './selectors-resolve.ts'; -export type SelectorChain = { - raw: string; - selectors: Selector[]; -}; - -type SelectorDiagnostics = { - selector: string; - matches: number; -}; - -type SelectorResolution = { - node: SnapshotNode; - selector: Selector; - selectorIndex: number; - matches: number; - diagnostics: SelectorDiagnostics[]; -}; - -const TEXT_KEYS = new Set(['id', 'role', 'text', 'label', 'value']); -const BOOLEAN_KEYS = new Set([ - 'visible', - 'hidden', - 'editable', - 'selected', - 'enabled', - 'hittable', -]); -const ALL_KEYS = new Set([...TEXT_KEYS, ...BOOLEAN_KEYS]); - -export function parseSelectorChain(expression: string): SelectorChain { - const raw = expression.trim(); - if (!raw) { - throw new AppError('INVALID_ARGS', 'Selector expression cannot be empty'); - } - const segments = splitByFallback(raw); - if (segments.length === 0) { - throw new AppError('INVALID_ARGS', 'Selector expression cannot be empty'); - } - return { - raw, - selectors: segments.map((segment) => parseSelector(segment)), - }; -} - -export function tryParseSelectorChain(expression: string): SelectorChain | null { - try { - return parseSelectorChain(expression); - } catch { - return null; - } -} - -export function resolveSelectorChain( - nodes: SnapshotState['nodes'], - chain: SelectorChain, - options: { - platform: 'ios' | 'android'; - requireRect?: boolean; - requireUnique?: boolean; - disambiguateAmbiguous?: boolean; - }, -): SelectorResolution | null { - const requireRect = options.requireRect ?? false; - const requireUnique = options.requireUnique ?? true; - const disambiguateAmbiguous = options.disambiguateAmbiguous ?? false; - const diagnostics: SelectorDiagnostics[] = []; - for (let i = 0; i < chain.selectors.length; i += 1) { - const selector = chain.selectors[i]; - const summary = analyzeSelectorMatches(nodes, selector, { - platform: options.platform, - requireRect, - }); - diagnostics.push({ selector: selector.raw, matches: summary.count }); - if (summary.count === 0 || !summary.firstNode) continue; - if (requireUnique && summary.count !== 1) { - if (!disambiguateAmbiguous) continue; - const disambiguatedNode = summary.disambiguated; - if (!disambiguatedNode) continue; - return { - node: disambiguatedNode, - selector, - selectorIndex: i, - matches: summary.count, - diagnostics, - }; - } - return { - node: summary.firstNode, - selector, - selectorIndex: i, - matches: summary.count, - diagnostics, - }; - } - return null; -} - -export function findSelectorChainMatch( - nodes: SnapshotState['nodes'], - chain: SelectorChain, - options: { - platform: 'ios' | 'android'; - requireRect?: boolean; - }, -): { selectorIndex: number; selector: Selector; matches: number; diagnostics: SelectorDiagnostics[] } | null { - const requireRect = options.requireRect ?? false; - const diagnostics: SelectorDiagnostics[] = []; - for (let i = 0; i < chain.selectors.length; i += 1) { - const selector = chain.selectors[i]; - const matches = countSelectorMatchesOnly(nodes, selector, { - platform: options.platform, - requireRect, - }); - diagnostics.push({ selector: selector.raw, matches }); - if (matches > 0) { - return { selectorIndex: i, selector, matches, diagnostics }; - } - } - return null; -} - -export function formatSelectorFailure( - chain: SelectorChain, - diagnostics: SelectorDiagnostics[], - options: { unique?: boolean }, -): string { - const unique = options.unique ?? true; - if (diagnostics.length === 0) { - return `Selector did not match: ${chain.raw}`; - } - const summary = diagnostics.map((entry) => `${entry.selector} -> ${entry.matches}`).join(', '); - if (unique) { - return `Selector did not resolve uniquely (${summary})`; - } - return `Selector did not match (${summary})`; -} - -export function isSelectorToken(token: string): boolean { - const trimmed = token.trim(); - if (!trimmed) return false; - if (trimmed === '||') return true; - const equalsIdx = trimmed.indexOf('='); - if (equalsIdx !== -1) { - const key = trimmed.slice(0, equalsIdx).trim().toLowerCase() as SelectorKey; - return ALL_KEYS.has(key); - } - return ALL_KEYS.has(trimmed.toLowerCase() as SelectorKey); -} - -export function splitSelectorFromArgs( - args: string[], - options: { preferTrailingValue?: boolean } = {}, -): { selectorExpression: string; rest: string[] } | null { - if (args.length === 0) return null; - const preferTrailingValue = options.preferTrailingValue ?? false; - let i = 0; - const boundaries: number[] = []; - while (i < args.length && isSelectorToken(args[i])) { - i += 1; - const candidate = args.slice(0, i).join(' ').trim(); - if (!candidate) continue; - if (tryParseSelectorChain(candidate)) { - boundaries.push(i); - } - } - if (boundaries.length === 0) return null; - let boundary = boundaries[boundaries.length - 1]; - if (preferTrailingValue) { - for (let j = boundaries.length - 1; j >= 0; j -= 1) { - if (boundaries[j] < args.length) { - boundary = boundaries[j]; - break; - } - } - } - const selectorExpression = args.slice(0, boundary).join(' ').trim(); - if (!selectorExpression) return null; - return { - selectorExpression, - rest: args.slice(boundary), - }; -} - -export function splitIsSelectorArgs(positionals: string[]): { - predicate: string; - split: { selectorExpression: string; rest: string[] } | null; -} { - const predicate = positionals[0] ?? ''; - const split = splitSelectorFromArgs(positionals.slice(1), { - preferTrailingValue: predicate === 'text', - }); - return { predicate, split }; -} - -export function isNodeVisible(node: SnapshotNode): boolean { - if (node.hittable === true) return true; - if (!node.rect) return false; - return node.rect.width > 0 && node.rect.height > 0; -} - -export function isNodeEditable(node: SnapshotNode, platform: 'ios' | 'android'): boolean { - const type = node.type ?? ''; - return isFillableType(type, platform) && node.enabled !== false; -} - -export function buildSelectorChainForNode( - node: SnapshotNode, - _platform: 'ios' | 'android', - options: { action?: 'click' | 'fill' | 'get' } = {}, -): string[] { - const chain: string[] = []; - const role = normalizeType(node.type ?? ''); - const id = normalizeSelectorText(node.identifier); - const label = normalizeSelectorText(node.label); - const value = normalizeSelectorText(node.value); - const text = normalizeSelectorText(extractNodeText(node)); - const requireEditable = options.action === 'fill'; - - if (id) { - chain.push(`id=${quoteSelectorValue(id)}`); - } - if (role && label) { - chain.push( - requireEditable - ? `role=${quoteSelectorValue(role)} label=${quoteSelectorValue(label)} editable=true` - : `role=${quoteSelectorValue(role)} label=${quoteSelectorValue(label)}`, - ); - } - if (label) { - chain.push(requireEditable ? `label=${quoteSelectorValue(label)} editable=true` : `label=${quoteSelectorValue(label)}`); - } - if (value) { - chain.push(requireEditable ? `value=${quoteSelectorValue(value)} editable=true` : `value=${quoteSelectorValue(value)}`); - } - if (text && text !== label && text !== value) { - chain.push(requireEditable ? `text=${quoteSelectorValue(text)} editable=true` : `text=${quoteSelectorValue(text)}`); - } - if (role && requireEditable && !chain.some((entry) => entry.includes('editable=true'))) { - chain.push(`role=${quoteSelectorValue(role)} editable=true`); - } - - const deduped = uniqueStrings(chain); - if (deduped.length === 0 && role) { - deduped.push(requireEditable ? `role=${quoteSelectorValue(role)} editable=true` : `role=${quoteSelectorValue(role)}`); - } - if (deduped.length === 0) { - const visible = isNodeVisible(node); - if (visible) deduped.push('visible=true'); - } - return deduped; -} - -function parseSelector(segment: string): Selector { - const raw = segment.trim(); - if (!raw) throw new AppError('INVALID_ARGS', 'Selector segment cannot be empty'); - const tokens = tokenize(raw); - if (tokens.length === 0) { - throw new AppError('INVALID_ARGS', `Invalid selector segment: ${segment}`); - } - const terms = tokens.map(parseTerm); - return { raw, terms }; -} - -function parseTerm(token: string): SelectorTerm { - const normalized = token.trim(); - if (!normalized) { - throw new AppError('INVALID_ARGS', 'Empty selector term'); - } - const equalsIdx = normalized.indexOf('='); - if (equalsIdx === -1) { - const key = normalized.toLowerCase() as SelectorKey; - if (!BOOLEAN_KEYS.has(key)) { - throw new AppError('INVALID_ARGS', `Invalid selector term "${token}", expected key=value`); - } - return { key, value: true }; - } - const keyRaw = normalized.slice(0, equalsIdx).trim().toLowerCase() as SelectorKey; - const valueRaw = normalized.slice(equalsIdx + 1).trim(); - if (!ALL_KEYS.has(keyRaw)) { - throw new AppError('INVALID_ARGS', `Unknown selector key: ${keyRaw}`); - } - if (!valueRaw) { - throw new AppError('INVALID_ARGS', `Missing selector value for key: ${keyRaw}`); - } - if (BOOLEAN_KEYS.has(keyRaw)) { - const parsedBoolean = parseBoolean(valueRaw); - if (parsedBoolean === null) { - throw new AppError('INVALID_ARGS', `Invalid boolean value for ${keyRaw}: ${valueRaw}`); - } - return { key: keyRaw, value: parsedBoolean }; - } - return { key: keyRaw, value: unquote(valueRaw) }; -} - -function matchesSelector(node: SnapshotNode, selector: Selector, platform: 'ios' | 'android'): boolean { - return selector.terms.every((term) => matchesTerm(node, term, platform)); -} - -function matchesTerm(node: SnapshotNode, term: SelectorTerm, platform: 'ios' | 'android'): boolean { - switch (term.key) { - case 'id': - return textEquals(node.identifier, String(term.value)); - case 'role': - return roleEquals(node.type, String(term.value)); - case 'label': - return textEquals(node.label, String(term.value)); - case 'value': - return textEquals(node.value, String(term.value)); - case 'text': { - const query = normalizeText(String(term.value)); - return normalizeText(extractNodeText(node)) === query; - } - case 'visible': - return isNodeVisible(node) === Boolean(term.value); - case 'hidden': - return (!isNodeVisible(node)) === Boolean(term.value); - case 'editable': - return isNodeEditable(node, platform) === Boolean(term.value); - case 'selected': - return Boolean(node.selected === true) === Boolean(term.value); - case 'enabled': - return Boolean(node.enabled !== false) === Boolean(term.value); - case 'hittable': - return Boolean(node.hittable === true) === Boolean(term.value); - default: - return false; - } -} - -function splitByFallback(expression: string): string[] { - const segments: string[] = []; - let current = ''; - let quote: '"' | "'" | null = null; - for (let i = 0; i < expression.length; i += 1) { - const ch = expression[i]; - if ((ch === '"' || ch === "'") && !isEscapedQuote(expression, i)) { - if (!quote) { - quote = ch; - } else if (quote === ch) { - quote = null; - } - current += ch; - continue; - } - if (!quote && ch === '|' && expression[i + 1] === '|') { - const segment = current.trim(); - if (!segment) { - throw new AppError('INVALID_ARGS', `Invalid selector fallback expression: ${expression}`); - } - segments.push(segment); - current = ''; - i += 1; - continue; - } - current += ch; - } - const finalSegment = current.trim(); - if (!finalSegment) { - throw new AppError('INVALID_ARGS', `Invalid selector fallback expression: ${expression}`); - } - segments.push(finalSegment); - return segments; -} - -function tokenize(segment: string): string[] { - const tokens: string[] = []; - let current = ''; - let quote: '"' | "'" | null = null; - for (let i = 0; i < segment.length; i += 1) { - const ch = segment[i]; - if ((ch === '"' || ch === "'") && !isEscapedQuote(segment, i)) { - if (!quote) { - quote = ch; - } else if (quote === ch) { - quote = null; - } - current += ch; - continue; - } - if (!quote && /\s/.test(ch)) { - if (current.trim().length > 0) { - tokens.push(current.trim()); - } - current = ''; - continue; - } - current += ch; - } - if (quote) { - throw new AppError('INVALID_ARGS', `Unclosed quote in selector: ${segment}`); - } - if (current.trim().length > 0) { - tokens.push(current.trim()); - } - return tokens; -} - -function unquote(value: string): string { - const trimmed = value.trim(); - if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) { - return trimmed.slice(1, -1).replace(/\\(["'])/g, '$1'); - } - return trimmed; -} - -function parseBoolean(value: string): boolean | null { - const normalized = unquote(value).toLowerCase(); - if (normalized === 'true') return true; - if (normalized === 'false') return false; - return null; -} - -function textEquals(value: string | undefined, query: string): boolean { - return normalizeText(value ?? '') === normalizeText(query); -} - -function roleEquals(value: string | undefined, query: string): boolean { - return normalizeRole(value ?? '') === normalizeRole(query); -} - -function normalizeText(value: string): string { - return value.trim().toLowerCase().replace(/\s+/g, ' '); -} - -function normalizeRole(value: string): string { - return normalizeType(value); -} - -function quoteSelectorValue(value: string): string { - return JSON.stringify(value); -} - -function normalizeSelectorText(value: string | undefined): string | null { - if (!value) return null; - const trimmed = value.trim(); - if (!trimmed) return null; - return trimmed; -} - -function analyzeSelectorMatches( - nodes: SnapshotState['nodes'], - selector: Selector, - options: { platform: 'ios' | 'android'; requireRect: boolean }, -): { count: number; firstNode: SnapshotNode | null; disambiguated: SnapshotNode | null } { - let count = 0; - let firstNode: SnapshotNode | null = null; - let best: SnapshotNode | null = null; - let tie = false; - for (const node of nodes) { - if (options.requireRect && !node.rect) continue; - if (!matchesSelector(node, selector, options.platform)) continue; - count += 1; - if (!firstNode) { - firstNode = node; - } - if (!best) { - best = node; - continue; - } - const comparison = compareDisambiguationCandidates(node, best); - if (comparison > 0) { - best = node; - tie = false; - continue; - } - if (comparison === 0) { - tie = true; - } - } - return { - count, - firstNode, - disambiguated: tie ? null : best, - }; -} - -function countSelectorMatchesOnly( - nodes: SnapshotState['nodes'], - selector: Selector, - options: { platform: 'ios' | 'android'; requireRect: boolean }, -): number { - let count = 0; - for (const node of nodes) { - if (options.requireRect && !node.rect) continue; - if (!matchesSelector(node, selector, options.platform)) continue; - count += 1; - } - return count; -} - -function compareDisambiguationCandidates(a: SnapshotNode, b: SnapshotNode): number { - const depthA = a.depth ?? 0; - const depthB = b.depth ?? 0; - if (depthA !== depthB) return depthA > depthB ? 1 : -1; - const areaA = areaOfNode(a); - const areaB = areaOfNode(b); - if (areaA !== areaB) return areaA < areaB ? 1 : -1; - return 0; -} - -function areaOfNode(node: SnapshotNode): number { - if (!node.rect) return Number.POSITIVE_INFINITY; - return node.rect.width * node.rect.height; -} - -function isEscapedQuote(source: string, index: number): boolean { - let backslashCount = 0; - for (let i = index - 1; i >= 0 && source[i] === '\\'; i -= 1) { - backslashCount += 1; - } - return backslashCount % 2 === 1; -} +export { buildSelectorChainForNode } from './selectors-build.ts';