Elffuss BraidHub

kikocis/continue public

main · 5.5 KiBRawPermalink
1/**
2 * Validates and sanitizes regex patterns for use with ripgrep
3 */
4
5export interface RegexValidationResult {
6 isValid: boolean;
7 sanitizedQuery?: string;
8 error?: string;
9 warning?: string;
10}
11
12/**
13 * Validates a regex pattern and attempts to sanitize common issues
14 * @param query The regex pattern to validate
15 * @returns Validation result with sanitized query if possible
16 */
17export function validateAndSanitizeRegex(query: string): RegexValidationResult {
18 // Check for common problematic patterns that often fail with ripgrep
19 const problematicPatterns = [
20 {
21 // Triple-escaped quotes
22 pattern: /\\\\\\/g,
23 issue: "Triple backslash sequences may cause parsing errors",
24 fix: (s: string) => s.replace(/\\\\\\/g, "\\\\"),
25 },
26 {
27 // Unescaped brackets/parentheses that are NOT part of valid regex constructs
28 pattern: /(?<!\\)[\[\]()]/g, // Removed {} from here since they're valid quantifiers
29 issue: "Unescaped brackets or parentheses",
30 fix: null, // Just warn, don't auto-fix as it might be intentional
31 },
32 {
33 // Unescaped braces that are NOT quantifiers (quantifiers are handled separately)
34 pattern: /(?<!\\)\{(?![0-9,}]*\})/g,
35 issue: "Unescaped braces that don't appear to be quantifiers",
36 fix: null,
37 },
38 {
39 // Raw tab/newline characters (not escaped)
40 pattern: /[\t\n\r]/g,
41 issue: "Raw whitespace characters should be escaped",
42 fix: (s: string) =>
43 s.replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r"),
44 },
45 ];
46
47 let sanitizedQuery = query;
48 let warnings: string[] = [];
49
50 // Apply fixes for known issues
51 for (const check of problematicPatterns) {
52 if (check.pattern.test(query)) {
53 if (check.fix) {
54 sanitizedQuery = check.fix(sanitizedQuery);
55 warnings.push(`Fixed: ${check.issue}`);
56 } else {
57 warnings.push(`Warning: ${check.issue}`);
58 }
59 }
60 }
61
62 // Try to compile as a JavaScript regex to catch basic syntax errors
63 try {
64 new RegExp(sanitizedQuery);
65 } catch (e) {
66 let errorMessage = e instanceof Error ? e.message : "Unknown error";
67 // If it fails as a JS regex, it might still be valid for ripgrep
68 // (ripgrep supports some patterns JS doesn't), but warn the user
69 warnings.push(`Pattern may have syntax issues: ${errorMessage}`);
70 }
71
72 // Check for patterns that are valid regex but might not work as expected with ripgrep
73 const ripgrepSpecificIssues = [
74 {
75 pattern: /\\[0-7]{3}/g,
76 warning: "Octal escape sequences may not work as expected in ripgrep",
77 },
78 {
79 pattern: /\(\?[<!=]/,
80 warning:
81 "Lookahead/lookbehind assertions require ripgrep to be compiled with PCRE2",
82 },
83 ];
84
85 for (const issue of ripgrepSpecificIssues) {
86 if (issue.pattern.test(sanitizedQuery)) {
87 warnings.push(issue.warning);
88 }
89 }
90
91 return {
92 isValid: true,
93 sanitizedQuery,
94 warning: warnings.length > 0 ? warnings.join("; ") : undefined,
95 };
96}
97
98/**
99 * Escapes a literal string to be used as a regex pattern
100 * @param literal The literal string to escape
101 * @returns Escaped string safe for regex use
102 */
103export function escapeLiteralForRegex(literal: string): string {
104 // Escape all regex metacharacters
105 return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
106}
107
108/**
109 * Detects if a query looks like it's meant to be a literal search
110 * rather than a regex pattern
111 * @param query The search query
112 * @returns true if it appears to be a literal search
113 */
114export function looksLikeLiteralSearch(query: string): boolean {
115 // If it contains regex metacharacters but they're not escaped,
116 // and it doesn't look like an intentional regex pattern
117 const hasUnescapedMetachars = /[.*+?^${}()|[\]]/g.test(query);
118 const hasEscapedMetachars = /\\[.*+?^${}()|[\]\\]/g.test(query);
119
120 // Check for regex constructs, but be more specific about what we consider regex
121 const hasEscapeSequences = /\\[dws]/g.test(query); // \d, \w, \s
122 const hasQuantifiers = /\{[0-9,]+\}/g.test(query); // {2,4}, {3}
123
124 // Check for bracket patterns and distinguish between character classes and array access
125 const bracketPattern = /\[[^\]]*\]/g;
126 const brackets = query.match(bracketPattern);
127 let hasCharacterClasses = false;
128
129 if (brackets) {
130 hasCharacterClasses = brackets.some((bracket) => {
131 const inside = bracket.slice(1, -1); // Remove [ ]
132 // Character class indicators: ranges (a-z), multiple chars, negation (^)
133 return /-/.test(inside) || inside.length > 1 || inside.startsWith("^");
134 });
135 }
136
137 const hasRegexConstructs =
138 hasEscapeSequences || hasQuantifiers || hasCharacterClasses;
139
140 // Likely a literal search if it has unescaped metachars but no regex constructs
141 return hasUnescapedMetachars && !hasEscapedMetachars && !hasRegexConstructs;
142}
143
144/**
145 * Prepares a query for ripgrep by sanitizing problematic patterns
146 * @param query The search query
147 * @returns Object with sanitized query and any warnings
148 */
149export function prepareQueryForRipgrep(query: string): {
150 query: string;
151 warning?: string;
152} {
153 // Check if it looks like a literal search that should be escaped
154 if (looksLikeLiteralSearch(query)) {
155 return {
156 query: escapeLiteralForRegex(query),
157 warning:
158 "Query contained special regex characters and was escaped for literal text search",
159 };
160 }
161
162 // Otherwise validate and sanitize as regex
163 const validation = validateAndSanitizeRegex(query);
164
165 return {
166 query: validation.sanitizedQuery || query,
167 warning: validation.warning,
168 };
169}