|
| 1 | +import { assertOkResponse } from "../../lib/utils.js"; |
| 2 | +import config from "../../config.js"; |
| 3 | + |
| 4 | +interface SelectorMapping { |
| 5 | + originalSelector: string; |
| 6 | + healedSelector: string; |
| 7 | +} |
| 8 | + |
| 9 | +export async function getSelfHealSelectors(sessionId: string) { |
| 10 | + const credentials = `${config.browserstackUsername}:${config.browserstackAccessKey}`; |
| 11 | + const auth = Buffer.from(credentials).toString("base64"); |
| 12 | + const url = `https://api.browserstack.com/automate/sessions/${sessionId}/logs`; |
| 13 | + |
| 14 | + const response = await fetch(url, { |
| 15 | + headers: { |
| 16 | + "Content-Type": "application/json", |
| 17 | + Authorization: `Basic ${auth}`, |
| 18 | + }, |
| 19 | + }); |
| 20 | + |
| 21 | + await assertOkResponse(response, "session logs"); |
| 22 | + const logText = await response.text(); |
| 23 | + return extractHealedSelectors(logText); |
| 24 | +} |
| 25 | + |
| 26 | +function extractHealedSelectors(logText: string): SelectorMapping[] { |
| 27 | + // Pattern to match SELFHEAL entries with healed selectors |
| 28 | + const selfhealPattern = |
| 29 | + /SELFHEAL\s*{\s*"status":"true",\s*"data":\s*{\s*"using":"css selector",\s*"value":"(.*?)"}/g; |
| 30 | + |
| 31 | + // Pattern to match preceding selector requests |
| 32 | + const requestPattern = |
| 33 | + /POST \/session\/[^/]+\/element.*?"using":"css selector","value":"(.*?)"/g; |
| 34 | + |
| 35 | + // Find all healed selectors |
| 36 | + const healedSelectors: string[] = []; |
| 37 | + let healedMatch; |
| 38 | + while ((healedMatch = selfhealPattern.exec(logText)) !== null) { |
| 39 | + healedSelectors.push(healedMatch[1]); |
| 40 | + } |
| 41 | + |
| 42 | + // Find all selector requests |
| 43 | + const selectorRequests: string[] = []; |
| 44 | + let requestMatch; |
| 45 | + while ((requestMatch = requestPattern.exec(logText)) !== null) { |
| 46 | + selectorRequests.push(requestMatch[1]); |
| 47 | + } |
| 48 | + |
| 49 | + // Pair each healed selector with its corresponding original selector |
| 50 | + const healedMappings: SelectorMapping[] = []; |
| 51 | + const minLength = Math.min(selectorRequests.length, healedSelectors.length); |
| 52 | + |
| 53 | + for (let i = 0; i < minLength; i++) { |
| 54 | + healedMappings.push({ |
| 55 | + originalSelector: selectorRequests[i], |
| 56 | + healedSelector: healedSelectors[i], |
| 57 | + }); |
| 58 | + } |
| 59 | + |
| 60 | + return healedMappings; |
| 61 | +} |
0 commit comments