20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
# File 'lib/headless_browser_tool/tools/search_page_tool.rb', line 20
def execute(query:, case_sensitive: false, regex: false, context_lines: 2, highlight: false)
page_text = browser.text
lines = page_text.split("\n")
pattern = if regex
Regexp.new(query, case_sensitive ? nil : Regexp::IGNORECASE)
else
escaped_query = Regexp.escape(query)
Regexp.new(escaped_query, case_sensitive ? nil : Regexp::IGNORECASE)
end
matches = []
lines.each_with_index do |line, index|
next unless line =~ pattern
match_info = {
line_number: index + 1,
line: line,
matches: line.scan(pattern)
}
if context_lines.positive?
start_idx = [0, index - context_lines].max
end_idx = [lines.length - 1, index + context_lines].min
match_info[:context] = {
before: lines[start_idx...index],
after: lines[(index + 1)..end_idx]
}
end
matches << match_info
end
if highlight && matches.any?
highlight_script = build_highlight_script(query, regex, case_sensitive)
browser.execute_script(highlight_script)
end
result = {
query: query,
total_matches: matches.size,
matches: matches.map do |match|
output = {
line_number: match[:line_number],
line: match[:line].strip,
occurrences: match[:matches].size
}
if match[:context]
output[:context] = {
before: match[:context][:before].map(&:strip),
after: match[:context][:after].map(&:strip)
}
end
output
end
}
if matches.empty?
html_matches = search_html(pattern)
result[:html_matches] = html_matches if html_matches.any?
end
result
end
|