tokenizeSearch.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import {escapeDoubleQuotes} from 'sentry/utils';
  2. export enum TokenType {
  3. OPERATOR,
  4. FILTER,
  5. FREE_TEXT,
  6. }
  7. export type Token = {
  8. type: TokenType;
  9. value: string;
  10. key?: string;
  11. };
  12. function isOp(t: Token) {
  13. return t.type === TokenType.OPERATOR;
  14. }
  15. function isBooleanOp(value: string) {
  16. return ['OR', 'AND'].includes(value.toUpperCase());
  17. }
  18. function isParen(token: Token, character: '(' | ')') {
  19. return (
  20. token !== undefined &&
  21. isOp(token) &&
  22. ['(', ')'].includes(token.value) &&
  23. token.value === character
  24. );
  25. }
  26. // TODO(epurkhiser): This is legacy from before the existence of
  27. // searchSyntax/parser. We should absolutely replace the internals of this API
  28. // with `parseSearch`.
  29. export class MutableSearch {
  30. tokens: Token[];
  31. /**
  32. * Creates a MutableSearch from a string query
  33. */
  34. constructor(query: string);
  35. /**
  36. * Creates a mutable search query from a list of query parts
  37. */
  38. constructor(queries: string[]);
  39. constructor(tokensOrQuery: string[] | string) {
  40. const strTokens = Array.isArray(tokensOrQuery)
  41. ? tokensOrQuery
  42. : splitSearchIntoTokens(tokensOrQuery);
  43. this.tokens = [];
  44. for (let token of strTokens) {
  45. let tokenState = TokenType.FREE_TEXT;
  46. if (isBooleanOp(token)) {
  47. this.addOp(token.toUpperCase());
  48. continue;
  49. }
  50. if (token.startsWith('(')) {
  51. const parenMatch = token.match(/^\(+/g);
  52. if (parenMatch) {
  53. parenMatch[0].split('').map(paren => this.addOp(paren));
  54. token = token.replace(/^\(+/g, '');
  55. }
  56. }
  57. // Traverse the token and check if it's a filter condition or free text
  58. for (let i = 0, len = token.length; i < len; i++) {
  59. const char = token[i];
  60. if (i === 0 && (char === '"' || char === ':')) {
  61. break;
  62. }
  63. // We may have entered a filter condition
  64. if (char === ':') {
  65. const nextChar = token[i + 1] || '';
  66. if ([':', ' '].includes(nextChar)) {
  67. tokenState = TokenType.FREE_TEXT;
  68. } else {
  69. tokenState = TokenType.FILTER;
  70. }
  71. break;
  72. }
  73. }
  74. let trailingParen = '';
  75. if (token.endsWith(')') && !token.includes('(')) {
  76. const parenMatch = token.match(/\)+$/g);
  77. if (parenMatch) {
  78. trailingParen = parenMatch[0];
  79. token = token.replace(/\)+$/g, '');
  80. }
  81. }
  82. if (tokenState === TokenType.FREE_TEXT && token.length) {
  83. this.addFreeText(token);
  84. } else if (tokenState === TokenType.FILTER) {
  85. this.addStringFilter(token, false);
  86. }
  87. if (trailingParen !== '') {
  88. trailingParen.split('').map(paren => this.addOp(paren));
  89. }
  90. }
  91. }
  92. formatString() {
  93. const formattedTokens: string[] = [];
  94. for (const token of this.tokens) {
  95. switch (token.type) {
  96. case TokenType.FILTER:
  97. if (token.value === '' || token.value === null) {
  98. formattedTokens.push(`${token.key}:""`);
  99. } else if (/[\s\(\)\\"]/g.test(token.value)) {
  100. formattedTokens.push(`${token.key}:"${escapeDoubleQuotes(token.value)}"`);
  101. } else {
  102. formattedTokens.push(`${token.key}:${token.value}`);
  103. }
  104. break;
  105. case TokenType.FREE_TEXT:
  106. if (/[\s\(\)\\"]/g.test(token.value)) {
  107. formattedTokens.push(`"${escapeDoubleQuotes(token.value)}"`);
  108. } else {
  109. formattedTokens.push(token.value);
  110. }
  111. break;
  112. default:
  113. formattedTokens.push(token.value);
  114. }
  115. }
  116. return formattedTokens.join(' ').trim();
  117. }
  118. addStringFilter(filter: string, shouldEscape = true) {
  119. const [key, value] = parseFilter(filter);
  120. this.addFilterValues(key, [value], shouldEscape);
  121. return this;
  122. }
  123. addFilterValues(key: string, values: string[], shouldEscape = true) {
  124. for (const value of values) {
  125. // Filter values that we insert through the UI can contain special characters
  126. // that need to escaped. User entered filters should not be escaped.
  127. const escaped = shouldEscape ? escapeFilterValue(value) : value;
  128. const token: Token = {type: TokenType.FILTER, key, value: escaped};
  129. this.tokens.push(token);
  130. }
  131. return this;
  132. }
  133. setFilterValues(key: string, values: string[], shouldEscape = true) {
  134. this.removeFilter(key);
  135. this.addFilterValues(key, values, shouldEscape);
  136. return this;
  137. }
  138. get filters() {
  139. type Filters = Record<string, string[]>;
  140. const reducer = (acc: Filters, token: Token) => ({
  141. ...acc,
  142. [token.key!]: [...(acc[token.key!] ?? []), token.value],
  143. });
  144. return this.tokens
  145. .filter(t => t.type === TokenType.FILTER)
  146. .reduce<Filters>(reducer, {});
  147. }
  148. getFilterValues(key: string) {
  149. return this.filters[key] ?? [];
  150. }
  151. getFilterKeys() {
  152. return Object.keys(this.filters);
  153. }
  154. hasFilter(key: string): boolean {
  155. return this.getFilterValues(key).length > 0;
  156. }
  157. removeFilter(key: string) {
  158. const removeErroneousAndOrOps = () => {
  159. let toRemove = -1;
  160. do {
  161. if (toRemove >= 0) {
  162. this.tokens.splice(toRemove, 1);
  163. toRemove = -1;
  164. }
  165. for (let i = 0; i < this.tokens.length; i++) {
  166. const token = this.tokens[i];
  167. const prev = this.tokens[i - 1];
  168. const next = this.tokens[i + 1];
  169. if (isOp(token) && isBooleanOp(token.value)) {
  170. if (prev === undefined || isOp(prev) || next === undefined || isOp(next)) {
  171. // Want to avoid removing `(term) OR (term)` and `term OR (term)`
  172. if (
  173. prev &&
  174. next &&
  175. (isParen(prev, ')') || !isOp(prev)) &&
  176. (isParen(next, '(') || !isOp(next))
  177. ) {
  178. continue;
  179. }
  180. toRemove = i;
  181. break;
  182. }
  183. }
  184. }
  185. } while (toRemove >= 0);
  186. };
  187. this.tokens = this.tokens.filter(token => token.key !== key);
  188. // Remove any AND/OR operators that have become erroneous due to filtering out tokens
  189. removeErroneousAndOrOps();
  190. // Now the really complicated part: removing parens that only have one element in them.
  191. // Since parens are themselves tokens, this gets tricky. In summary, loop through the
  192. // tokens until we find the innermost open paren. Then forward search through the rest of the tokens
  193. // to see if that open paren corresponds to a closed paren with one or fewer items inside.
  194. // If it does, delete those parens, and loop again until there are no more parens to delete.
  195. let parensToDelete: number[] = [];
  196. const cleanParens = (_, idx: number) => !parensToDelete.includes(idx);
  197. do {
  198. if (parensToDelete.length) {
  199. this.tokens = this.tokens.filter(cleanParens);
  200. }
  201. parensToDelete = [];
  202. for (let i = 0; i < this.tokens.length; i++) {
  203. const token = this.tokens[i];
  204. if (!isOp(token) || token.value !== '(') {
  205. continue;
  206. }
  207. let alreadySeen = false;
  208. for (let j = i + 1; j < this.tokens.length; j++) {
  209. const nextToken = this.tokens[j];
  210. if (isOp(nextToken) && nextToken.value === '(') {
  211. // Continue down to the nested parens. We can skip i forward since we know
  212. // everything between i and j is NOT an open paren.
  213. i = j - 1;
  214. break;
  215. } else if (!isOp(nextToken)) {
  216. if (alreadySeen) {
  217. // This has more than one term, no need to delete
  218. break;
  219. }
  220. alreadySeen = true;
  221. } else if (isOp(nextToken) && nextToken.value === ')') {
  222. // We found another paren with zero or one terms inside. Delete the pair.
  223. parensToDelete = [i, j];
  224. break;
  225. }
  226. }
  227. if (parensToDelete.length > 0) {
  228. break;
  229. }
  230. }
  231. } while (parensToDelete.length > 0);
  232. // Now that all erroneous parens are removed we need to remove dangling OR/AND operators.
  233. // I originally removed all the dangling properties in a single loop, but that meant that
  234. // cases like `a OR OR b` would remove both operators, when only one should be removed. So
  235. // instead, we loop until we find an operator to remove, then go back to the start and loop
  236. // again.
  237. removeErroneousAndOrOps();
  238. return this;
  239. }
  240. removeFilterValue(key: string, value: string) {
  241. const values = this.getFilterValues(key);
  242. if (Array.isArray(values) && values.length) {
  243. this.setFilterValues(
  244. key,
  245. values.filter(item => item !== value)
  246. );
  247. }
  248. }
  249. addFreeText(value: string) {
  250. const token: Token = {type: TokenType.FREE_TEXT, value: formatQuery(value)};
  251. this.tokens.push(token);
  252. return this;
  253. }
  254. addOp(value: string) {
  255. const token: Token = {type: TokenType.OPERATOR, value};
  256. this.tokens.push(token);
  257. return this;
  258. }
  259. get freeText(): string[] {
  260. return this.tokens.filter(t => t.type === TokenType.FREE_TEXT).map(t => t.value);
  261. }
  262. set freeText(values: string[]) {
  263. this.tokens = this.tokens.filter(t => t.type !== TokenType.FREE_TEXT);
  264. for (const v of values) {
  265. this.addFreeText(v);
  266. }
  267. }
  268. copy() {
  269. const q = new MutableSearch([]);
  270. q.tokens = [...this.tokens];
  271. return q;
  272. }
  273. isEmpty() {
  274. return this.tokens.length === 0;
  275. }
  276. }
  277. /**
  278. * Splits search strings into tokens for parsing by tokenizeSearch.
  279. *
  280. * Should stay in sync with src.sentry.search.utils:split_query_into_tokens
  281. */
  282. function splitSearchIntoTokens(query: string) {
  283. const queryChars = Array.from(query);
  284. const tokens: string[] = [];
  285. let token = '';
  286. let endOfPrevWord = '';
  287. let quoteType = '';
  288. let quoteEnclosed = false;
  289. for (let idx = 0; idx < queryChars.length; idx++) {
  290. const char = queryChars[idx];
  291. const nextChar = queryChars.length - 1 > idx ? queryChars[idx + 1] : null;
  292. token += char;
  293. if (nextChar !== null && !isSpace(char) && isSpace(nextChar)) {
  294. endOfPrevWord = char;
  295. }
  296. if (isSpace(char) && !quoteEnclosed && endOfPrevWord !== ':' && !isSpace(token)) {
  297. tokens.push(token.trim());
  298. token = '';
  299. }
  300. if (["'", '"'].includes(char) && (!quoteEnclosed || quoteType === char)) {
  301. quoteEnclosed = !quoteEnclosed;
  302. if (quoteEnclosed) {
  303. quoteType = char;
  304. }
  305. }
  306. if (quoteEnclosed && char === '\\' && nextChar === quoteType) {
  307. token += nextChar;
  308. idx++;
  309. }
  310. }
  311. const trimmedToken = token.trim();
  312. if (trimmedToken !== '') {
  313. tokens.push(trimmedToken);
  314. }
  315. return tokens;
  316. }
  317. /**
  318. * Checks if the string is only spaces
  319. */
  320. function isSpace(s: string) {
  321. return s.trim() === '';
  322. }
  323. /**
  324. * Splits a filter on ':' and removes enclosing quotes if present, and returns
  325. * both sides of the split as strings.
  326. */
  327. function parseFilter(filter: string) {
  328. const idx = filter.indexOf(':');
  329. const key = removeSurroundingQuotes(filter.slice(0, idx));
  330. const value = removeSurroundingQuotes(filter.slice(idx + 1));
  331. return [key, value];
  332. }
  333. function removeSurroundingQuotes(text: string) {
  334. const length = text.length;
  335. if (length <= 1) {
  336. return text;
  337. }
  338. let left = 0;
  339. for (; left <= length / 2; left++) {
  340. if (text.charAt(left) !== '"') {
  341. break;
  342. }
  343. }
  344. let right = length - 1;
  345. for (; right >= length / 2; right--) {
  346. if (text.charAt(right) !== '"' || text.charAt(right - 1) === '\\') {
  347. break;
  348. }
  349. }
  350. return text.slice(left, right + 1);
  351. }
  352. /**
  353. * Strips enclosing quotes and parens from a query, if present.
  354. */
  355. function formatQuery(query: string) {
  356. return query.replace(/^["\(]+|["\)]+$/g, '');
  357. }
  358. /**
  359. * Some characters have special meaning in a filter value. So when they are
  360. * directly added as a value, we have to escape them to mean the literal.
  361. */
  362. export function escapeFilterValue(value: string) {
  363. // TODO(txiao): The types here are definitely wrong.
  364. // Need to dig deeper to see where exactly it's wrong.
  365. //
  366. // astericks (*) is used for wildcard searches
  367. return typeof value === 'string' ? value.replace(/([\*])/g, '\\$1') : value;
  368. }