ff-dom 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2809 +1,2 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const reWhiteSpace$1 = /^[\S]+( [\S]+)*$/gi;
6
- let cspEnabled = false;
7
- const xpathCache$1 = {};
8
- let relativeXPathCache = new Map();
9
- let modifiedElementAttributes$1 = [];
10
- let mutationObserver;
11
- const createObserver = (addedNodeCallBack) => {
12
- mutationObserver = new MutationObserver((mutations) => {
13
- mutations.forEach((mutation) => {
14
- if (mutation?.addedNodes?.length) {
15
- addedNodeCallBack(mutation?.addedNodes);
16
- }
17
- if (mutation.target instanceof HTMLElement) {
18
- if (mutation?.type === "attributes" &&
19
- mutation.attributeName === "class" &&
20
- ((isSvg(mutation.target) &&
21
- mutation.oldValue?.trim() ===
22
- mutation.target.classList.value?.trim()) ||
23
- mutation.target.classList?.value
24
- ?.replace(mutation.oldValue, "")
25
- .trim() === "marked-element-temp" ||
26
- mutation?.oldValue
27
- ?.replace(mutation.target.classList?.value, "")
28
- .trim() === "marked-element-temp")) ;
29
- else if (mutation?.type === "attributes" &&
30
- !["flndisabled"].includes(mutation.attributeName)) {
31
- modifiedElementAttributes$1.push({
32
- url: mutation.target.baseURI,
33
- attributeName: mutation.attributeName,
34
- element: mutation.target,
35
- doc: mutation.target.ownerDocument,
36
- });
37
- }
38
- }
39
- });
40
- });
41
- };
42
- const startObserver = (target, options) => {
43
- mutationObserver?.observe(target, options);
44
- };
45
- const stopObserver = () => {
46
- mutationObserver?.disconnect();
47
- };
48
- const isNumberExist = (str) => {
49
- const hasNumber = /\d/;
50
- return hasNumber.test(str);
51
- };
52
- const buildPattern = (pattern, isSvg, tagName) => {
53
- return isSvg
54
- ? `//*[local-name()='${tagName}' and ${pattern}]`
55
- : `//${tagName}[${pattern}]`;
56
- };
57
- const getTextContent = (targetElement) => {
58
- const textContent = targetElement?.textContent;
59
- {
60
- return textContent;
61
- }
62
- };
63
- const getFilteredText = (element) => {
64
- return element?.childNodes[0]?.nodeValue || "";
65
- };
66
- const getCountOfXPath = (xpath, element, docmt, multiElementReferenceMode = false) => {
67
- try {
68
- let count;
69
- // Check if result is cached
70
- if (xpathCache$1[xpath] !== undefined) {
71
- count = xpathCache$1[xpath];
72
- }
73
- else {
74
- const owner = docmt.nodeType === 9 // DOCUMENT_NODE
75
- ? docmt
76
- : docmt.ownerDocument;
77
- count = owner.evaluate(`count(${xpath})`, docmt, null, XPathResult.NUMBER_TYPE, null).numberValue;
78
- xpathCache$1[xpath] = count;
79
- }
80
- if (multiElementReferenceMode && Array.isArray(element)) {
81
- if (count > 1) {
82
- const elementsFromXpath = getElementFromXpath(xpath, docmt, true);
83
- let nodex, matchedCount = 0;
84
- if (elementsFromXpath instanceof XPathResult) {
85
- while ((nodex = elementsFromXpath?.iterateNext())) {
86
- if (element.includes(nodex)) {
87
- matchedCount += 1;
88
- if (matchedCount === 2)
89
- break;
90
- }
91
- }
92
- }
93
- if (matchedCount !== 2)
94
- return 0;
95
- }
96
- }
97
- else {
98
- // Short-circuit if we only need to match one element
99
- if (count === 1) {
100
- const elementFromXpath = getElementFromXpath(xpath, docmt);
101
- return elementFromXpath === element ? count : 0; // Return 0 if no match
102
- }
103
- }
104
- return count; // Return the count
105
- }
106
- catch (error) {
107
- console.error(`Error evaluating XPath: ${xpath}`, error);
108
- return 0; // Return 0 on error to avoid re-processing
109
- }
110
- };
111
- const escapeCharacters = (text) => {
112
- if (text) {
113
- if (!(text.indexOf('"') === -1)) {
114
- return `'${text}'`;
115
- }
116
- if (!(text.indexOf("'") === -1)) {
117
- return `"${text}"`;
118
- }
119
- }
120
- return `'${text}'`;
121
- };
122
- const removeParenthesis = (xpath) => {
123
- const charArr = xpath.split("");
124
- let count = charArr.length;
125
- const indexArray = [];
126
- while (charArr[count - 2] !== "[") {
127
- indexArray.push(charArr[count - 2]);
128
- count--;
129
- }
130
- indexArray.reverse();
131
- let finalStr = "";
132
- for (let i = 0; i < indexArray.length; i++) {
133
- finalStr += indexArray[i];
134
- }
135
- const endBracketLength = finalStr.length + 2;
136
- let firstpart = xpath.slice(0, xpath.length - endBracketLength);
137
- if (firstpart.startsWith("(") && firstpart.endsWith(")")) {
138
- firstpart = firstpart.slice(1, -1);
139
- }
140
- else {
141
- firstpart = xpath;
142
- }
143
- return firstpart;
144
- };
145
- const findXpathWithIndex = (val, node, docmt, count) => {
146
- try {
147
- const owner = docmt.nodeType === 9 // DOCUMENT_NODE
148
- ? docmt
149
- : docmt.ownerDocument;
150
- let index = 0;
151
- if (count) {
152
- if (getCountOfXPath(`${val}[${count}]`, node, docmt) === 1) {
153
- return `${val}[${count}]`;
154
- }
155
- if (getCountOfXPath(`(${val})[${count}]`, node, docmt) === 1) {
156
- return `(${val})[${count}]`;
157
- }
158
- }
159
- const nodes = owner.evaluate(val, docmt, null, XPathResult.ANY_TYPE, null);
160
- let nodex;
161
- while ((nodex = nodes.iterateNext())) {
162
- index++;
163
- if (nodex.isSameNode(node)) {
164
- if (getCountOfXPath(`${val}[${index}]`, node, docmt) === 1) {
165
- return `${val}[${index}]`;
166
- }
167
- if (getCountOfXPath(`(${val})[${index}]`, node, docmt) === 1) {
168
- return `(${val})[${index}]`;
169
- }
170
- return;
171
- }
172
- }
173
- }
174
- catch (error) {
175
- console.log(error);
176
- }
177
- };
178
- const deleteLineGap = (a) => {
179
- a &&= a.split("\n")[0].length > 0 ? a.split("\n")[0] : a.split("\n")[1];
180
- return a;
181
- };
182
- const deleteGarbageFromInnerText = (a) => {
183
- a = deleteLineGap(a);
184
- a = a
185
- .split(/[^\u0000-\u00ff]/)
186
- .reduce((b, c) => {
187
- return b.length > c.length ? b : c;
188
- }, "")
189
- .trim();
190
- return (a = a.split("/")[0].trim());
191
- };
192
- const replaceWhiteSpaces = (str) => {
193
- if (str) {
194
- return str.replace(/\s\s+/g, " ").trim();
195
- }
196
- return str;
197
- };
198
- const getShadowRoot = (a) => {
199
- for (a = a && a.parentElement; a;) {
200
- if (a.toString() === "[object ShadowRoot]")
201
- return a;
202
- a = a.parentElement;
203
- }
204
- return null;
205
- };
206
- const checkBlockedAttributes = (attribute, targetElement, isTarget) => {
207
- if (!attribute?.value ||
208
- typeof attribute?.value === "boolean" ||
209
- ["true", "false", "on", "off", "flntooltip"].some((x) => x === attribute.value) ||
210
- ["type", "style", "locator-data-tooltip", "value"].some((x) => x === attribute.name) ||
211
- modifiedElementAttributes$1?.find((x) => x.doc === targetElement.ownerDocument &&
212
- x.element === targetElement &&
213
- x.attributeName === attribute.name) ||
214
- (attribute?.name?.indexOf("on") === 0 && attribute?.name?.length > 3) ||
215
- typeof attribute.value === "function" ||
216
- (isTarget && isNumberExist(attribute.value))) {
217
- return false;
218
- }
219
- return true;
220
- };
221
- const getRelationship = (a, b) => {
222
- let pos = a.compareDocumentPosition(b);
223
- return pos === 2
224
- ? "preceding"
225
- : pos === 4
226
- ? "following"
227
- : pos === 8
228
- ? "ancestor"
229
- : pos === 16
230
- ? "descendant"
231
- : pos === 32
232
- ? "self"
233
- : "";
234
- };
235
- const isSvg = (element) => {
236
- return element instanceof SVGElement;
237
- };
238
- const replaceTempAttributes = (str) => {
239
- if (!str)
240
- return str;
241
- return str.replace(/\b[a-zA-Z_]*disabled\b/gi, "disabled");
242
- };
243
- const getElementFromXpath = (xpath, docmt, multi = false) => {
244
- const owner = docmt.nodeType === 9 // DOCUMENT_NODE
245
- ? docmt
246
- : docmt.ownerDocument;
247
- if (multi) {
248
- return owner.evaluate(xpath, docmt, null, XPathResult.ANY_TYPE, null);
249
- }
250
- else {
251
- return owner.evaluate(xpath, docmt, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
252
- }
253
- };
254
- const getPropertyXPath = (element, docmt, prop, value, isIndex, isTarget) => {
255
- if (value) {
256
- const { tagName } = element;
257
- let count;
258
- let combinePattern = "";
259
- const mergePattern = [];
260
- let pattern;
261
- if (value && (!isTarget || !isNumberExist(value))) {
262
- if (!reWhiteSpace$1.test(value)) {
263
- pattern = buildPattern(`normalize-space(${prop})=${escapeCharacters(replaceWhiteSpaces(value)).trim()}`, isSvg(element), element.tagName.toLowerCase());
264
- }
265
- else {
266
- pattern = `//${tagName}[${prop}=${escapeCharacters(value)}]`;
267
- }
268
- count = getCountOfXPath(pattern, element, docmt);
269
- if (count === 1 && !isIndex) {
270
- return pattern;
271
- }
272
- }
273
- if (value && isTarget) {
274
- const splitText = value.split(" ");
275
- if (splitText?.length) {
276
- if (splitText.length === 1) {
277
- const contentRes = [...new Set(splitText[0].match(/([^0-9]+)/g))];
278
- if (contentRes?.length >= 1) {
279
- if (contentRes[0] &&
280
- replaceWhiteSpaces(contentRes[0].trim())?.length > 1) {
281
- if (value.startsWith(contentRes[0])) {
282
- if (!reWhiteSpace$1.test(contentRes[0])) {
283
- combinePattern = `starts-with(${prop},${escapeCharacters(replaceWhiteSpaces(contentRes[0])).trim()})`;
284
- }
285
- else {
286
- combinePattern = `starts-with(${prop},${escapeCharacters(contentRes[0]).trim()})`;
287
- }
288
- }
289
- }
290
- }
291
- if (contentRes?.length > 1) {
292
- if (contentRes[contentRes.length - 1] &&
293
- replaceWhiteSpaces(contentRes[contentRes.length - 1].trim())
294
- ?.length > 1) {
295
- if (value.endsWith(contentRes[contentRes.length - 1])) {
296
- if (!reWhiteSpace$1.test(contentRes[contentRes.length - 1])) {
297
- combinePattern = `ends-with(${prop},${escapeCharacters(replaceWhiteSpaces(contentRes[contentRes.length - 1])).trim()})`;
298
- }
299
- else {
300
- combinePattern = `ends-with(${prop},${escapeCharacters(contentRes[contentRes.length - 1]).trim()})`;
301
- }
302
- }
303
- }
304
- }
305
- if (combinePattern?.length) {
306
- if (isSvg(element)) {
307
- pattern = `//*[local-name()='${tagName}' and ${combinePattern}]`;
308
- }
309
- else {
310
- pattern = `//${tagName}[${combinePattern}]`;
311
- }
312
- count = getCountOfXPath(pattern, element, docmt);
313
- if (count === 1 && !isIndex) {
314
- return pattern;
315
- }
316
- }
317
- }
318
- else {
319
- const endIndex = splitText.length % 2 === 0
320
- ? splitText.length / 2
321
- : splitText.length % 2;
322
- const startIndexString = splitText.slice(0, endIndex).join(" ");
323
- let contentRes = [...new Set(startIndexString.match(/([^0-9]+)/g))];
324
- if (contentRes?.length) {
325
- if (contentRes[0] &&
326
- replaceWhiteSpaces(contentRes[0].trim())?.length) {
327
- if (value.startsWith(contentRes[0])) {
328
- if (!reWhiteSpace$1.test(contentRes[0])) {
329
- combinePattern = `starts-with(${prop},${escapeCharacters(replaceWhiteSpaces(contentRes[0])).trim()})`;
330
- }
331
- else {
332
- combinePattern = `starts-with(${prop},${escapeCharacters(contentRes[0]).trim()})`;
333
- }
334
- }
335
- }
336
- }
337
- if (combinePattern?.length) {
338
- if (isSvg(element)) {
339
- pattern = `//*[local-name()='${tagName}' and ${combinePattern}]`;
340
- }
341
- else {
342
- pattern = `//${tagName}[${combinePattern}]`;
343
- }
344
- count = getCountOfXPath(pattern, element, docmt);
345
- if (count === 1 && !isIndex) {
346
- return pattern;
347
- }
348
- }
349
- const endIndexString = splitText
350
- .slice(endIndex, splitText.length - 1)
351
- .join(" ");
352
- contentRes = [...new Set(endIndexString.match(/([^0-9]+)/g))];
353
- if (contentRes?.length) {
354
- if (contentRes[0] &&
355
- replaceWhiteSpaces(contentRes[0].trim())?.length > 3) {
356
- if (value.endsWith(contentRes[0])) {
357
- if (!reWhiteSpace$1.test(contentRes[0])) {
358
- combinePattern = `ends-with(${prop},${escapeCharacters(replaceWhiteSpaces(contentRes[0])).trim()})`;
359
- }
360
- else {
361
- combinePattern = `ends-with(${prop},${escapeCharacters(contentRes[0]).trim()})`;
362
- }
363
- }
364
- }
365
- }
366
- if (combinePattern?.length) {
367
- if (isSvg(element)) {
368
- pattern = `//*[local-name()='${tagName}' and ${combinePattern}]`;
369
- }
370
- else {
371
- pattern = `//${tagName}[${combinePattern}]`;
372
- }
373
- count = getCountOfXPath(pattern, element, docmt);
374
- if (count === 1 && !isIndex) {
375
- return pattern;
376
- }
377
- }
378
- }
379
- }
380
- }
381
- if (value && isTarget && isNumberExist(value)) {
382
- const contentRes = [...new Set(value.match(/([^0-9]+)/g))];
383
- if (contentRes?.length) {
384
- for (let i = 0; i < contentRes?.length; i++) {
385
- if (contentRes[i] &&
386
- replaceWhiteSpaces(contentRes[i].trim())?.length > 1) {
387
- if (!reWhiteSpace$1.test(contentRes[i])) {
388
- mergePattern.push(`contains(${prop},${escapeCharacters(replaceWhiteSpaces(contentRes[i])).trim()})`);
389
- }
390
- else {
391
- mergePattern.push(`contains(${prop},${escapeCharacters(contentRes[i].trim()).trim()})`);
392
- }
393
- }
394
- }
395
- }
396
- if (mergePattern?.length) {
397
- if (isSvg(element)) {
398
- pattern = `//*[local-name()='${tagName}' and ${mergePattern.join(" and ")}]`;
399
- }
400
- else {
401
- pattern = `//${tagName}[${mergePattern.join(" and ")}]`;
402
- }
403
- count = getCountOfXPath(pattern, element, docmt);
404
- if (count === 1 && !isIndex) {
405
- return pattern;
406
- }
407
- }
408
- }
409
- if (isSvg(element)) {
410
- pattern = `//*[local-name()='${tagName}' and text()]`;
411
- }
412
- else {
413
- pattern = `//${tagName}[text()]`;
414
- }
415
- count = getCountOfXPath(pattern, element, docmt);
416
- if (count === 1 && !isIndex) {
417
- return pattern;
418
- }
419
- }
420
- };
421
- const getAbsoluteXPath = (domNode, docmt) => {
422
- try {
423
- if (!domNode) {
424
- return "";
425
- }
426
- let xpathe = isSvg(domNode)
427
- ? `/*[local-name()='${domNode.tagName}']`
428
- : `/${domNode.tagName}`;
429
- // // If this node has siblings of the same tagName, get the index of this node
430
- if (domNode.parentElement) {
431
- // Get the siblings
432
- const childNodes = Array.prototype.slice
433
- .call(domNode.parentElement.children, 0)
434
- .filter((childNode) => childNode.tagName === domNode.tagName);
435
- // // If there's more than one sibling, append the index
436
- if (childNodes.length > 1) {
437
- const index = childNodes.indexOf(domNode);
438
- xpathe += `[${index + 1}]`;
439
- }
440
- }
441
- else if (domNode instanceof HTMLElement) {
442
- if (domNode.offsetParent) {
443
- const childNodes = Array.prototype.slice
444
- .call(domNode.offsetParent.children, 0)
445
- .filter((childNode) => childNode.tagName === domNode.tagName);
446
- // // If there's more than one sibling, append the index
447
- if (childNodes.length > 1) {
448
- const index = childNodes.indexOf(domNode);
449
- xpathe += `[${index + 1}]`;
450
- }
451
- }
452
- }
453
- // // Make a recursive call to this nodes parents and prepend it to this xpath
454
- return getAbsoluteXPath(domNode?.parentElement, docmt) + xpathe;
455
- }
456
- catch (error) {
457
- // If there's an unexpected exception, abort and don't get an XPath
458
- console.log("xpath", error);
459
- return "";
460
- }
461
- };
462
- const getRelativeXPath = (domNode, docmt, isIndex, isTarget = false, attributesArray) => {
463
- try {
464
- // Generate a cache key based on the node's identifier, index, and target flag
465
- // Check if the result for this node is already cached
466
- if (relativeXPathCache.has(domNode)) {
467
- return relativeXPathCache.get(domNode);
468
- }
469
- // Initialize an array to hold parts of the XPath
470
- const xpathParts = [];
471
- let currentNode = domNode;
472
- // Traverse up the DOM tree iteratively instead of using recursion
473
- while (currentNode) {
474
- let xpathe = "";
475
- let hasUniqueAttr = false;
476
- let attributes = domNode === currentNode ? attributesArray ?? currentNode.attributes : currentNode.attributes;
477
- // Loop through attributes to check for unique identifiers
478
- for (const attrName of Array.from(attributes)) {
479
- if (checkBlockedAttributes(attrName, currentNode, isTarget)) {
480
- let attrValue = attrName.nodeValue;
481
- // Clean up attribute value
482
- attrValue = attrValue?.replace("removePointers", "") ?? "";
483
- const elementName = attrName.name;
484
- // Construct an XPath based on attribute
485
- xpathe = getXpathString(currentNode, elementName, attrValue);
486
- let othersWithAttr = 0;
487
- if (xpathe) {
488
- othersWithAttr = getCountOfXPath(xpathe, currentNode, docmt);
489
- if (othersWithAttr === 1) {
490
- xpathParts.unshift(replaceTempAttributes(xpathe));
491
- hasUniqueAttr = true;
492
- break;
493
- }
494
- }
495
- if (othersWithAttr > 1 && isIndex) {
496
- xpathe = findXpathWithIndex(xpathe, currentNode, docmt, othersWithAttr);
497
- if (xpathe) {
498
- xpathParts.unshift(replaceTempAttributes(xpathe));
499
- hasUniqueAttr = true;
500
- break;
501
- }
502
- // return replaceTempAttributes(xpathe);
503
- }
504
- }
505
- }
506
- if (currentNode.textContent) {
507
- if (!isTarget || (isTarget && !isNumberExist(currentNode.textContent))) {
508
- let reWhiteSpace = new RegExp(/^[\S]+( [\S]+)*$/gi);
509
- if (!reWhiteSpace.test(currentNode.textContent)) {
510
- xpathe =
511
- isSvg(currentNode)
512
- ? `//*[local-name()='${currentNode.tagName}' and normalize-space(.)=${escapeCharacters(getFilteredText(currentNode))}]`
513
- : `//${currentNode.tagName || "*"}[normalize-space(.)=${escapeCharacters(getFilteredText(currentNode))}]`;
514
- }
515
- else {
516
- xpathe =
517
- isSvg(currentNode)
518
- ? `//*[local-name()='${currentNode.tagName}' and .=${escapeCharacters(getFilteredText(currentNode))}]`
519
- : `//${currentNode.tagName || "*"}[.=${escapeCharacters(getFilteredText(currentNode))}]`;
520
- }
521
- let othersWithAttr = getCountOfXPath(xpathe, currentNode, docmt);
522
- if (othersWithAttr === 1) {
523
- return xpathe;
524
- }
525
- if (othersWithAttr > 1 && isIndex) {
526
- xpathe = findXpathWithIndex(xpathe, currentNode, docmt, othersWithAttr);
527
- return xpathe;
528
- }
529
- }
530
- else {
531
- let combinePattern = [];
532
- const contentRes = [
533
- ...new Set(getFilteredText(currentNode).match(/([^0-9]+)/g)),
534
- ];
535
- let reWhiteSpace = new RegExp(/^[\S]+( [\S]+)*$/gi);
536
- if (contentRes?.length) {
537
- for (let i = 0; i < contentRes?.length; i++) {
538
- if (contentRes[i] &&
539
- replaceWhiteSpaces(contentRes[i].trim())) {
540
- if (!reWhiteSpace.test(contentRes[i])) {
541
- combinePattern.push(`contains(.,${escapeCharacters(replaceWhiteSpaces(contentRes[i])).trim()})`);
542
- }
543
- else {
544
- combinePattern.push(`contains(.,${escapeCharacters(contentRes[i].trim()).trim()})`);
545
- }
546
- }
547
- }
548
- }
549
- if (combinePattern?.length) {
550
- xpathe =
551
- isSvg(currentNode)
552
- ? `//*[local-name()='${currentNode.tagName}' and ${combinePattern.join(" and ")}]`
553
- : `//${currentNode.tagName || "*"}[${combinePattern.join(" and ")}]`;
554
- let othersWithAttr = getCountOfXPath(xpathe, currentNode, docmt);
555
- if (othersWithAttr === 1) {
556
- return xpathe;
557
- }
558
- if (othersWithAttr > 1 && isIndex) {
559
- xpathe = findXpathWithIndex(xpathe, currentNode, docmt, othersWithAttr);
560
- return xpathe;
561
- }
562
- }
563
- }
564
- }
565
- // If no unique attribute was found, construct XPath by tag name
566
- if (!hasUniqueAttr) {
567
- let tagBasedXPath = isSvg(currentNode)
568
- ? `/*[local-name()='${currentNode.tagName}']`
569
- : `/${currentNode.tagName}`;
570
- // Handle sibling nodes
571
- if (currentNode.parentElement) {
572
- const siblings = Array.from(currentNode.parentElement.children).filter((childNode) => childNode.tagName === currentNode.tagName);
573
- // Append index to distinguish between siblings
574
- if (siblings.length > 1) {
575
- const index = siblings.indexOf(currentNode);
576
- tagBasedXPath += `[${index + 1}]`;
577
- }
578
- }
579
- // Add the constructed tag-based XPath to the parts array
580
- xpathParts.unshift(tagBasedXPath);
581
- }
582
- else {
583
- break;
584
- }
585
- // Move up to the parent node for the next iteration
586
- currentNode = currentNode.parentElement;
587
- }
588
- // Combine all parts into the final XPath
589
- const finalXPath = `${xpathParts.join("")}`;
590
- // Cache the final XPath for this node
591
- relativeXPathCache.set(domNode, finalXPath);
592
- return finalXPath;
593
- }
594
- catch (error) {
595
- console.log(error);
596
- return null;
597
- }
598
- };
599
- const getCombinationXpath = (attribute, domNode) => {
600
- const combinePattern = [];
601
- let pattern = "";
602
- if (attribute &&
603
- !isNumberExist(attribute.value) &&
604
- typeof attribute.nodeValue !== "function" // &&
605
- // !modifiedElementAttributes?.find(
606
- // (x) => x.element === domNode && x.attributeName === attribute.name
607
- // )
608
- ) {
609
- const contentRes = [...new Set(attribute.value.match(/([^0-9]+)/g))];
610
- if (contentRes?.length) {
611
- for (let i = 0; i < contentRes?.length; i++) {
612
- if (contentRes[i] &&
613
- replaceWhiteSpaces(contentRes[i].trim())?.length > 2) {
614
- if (!reWhiteSpace$1.test(contentRes[i])) {
615
- combinePattern.push(`contains(@${attribute.name},${escapeCharacters(replaceWhiteSpaces(contentRes[i])).trim()})`);
616
- }
617
- else {
618
- combinePattern.push(`contains(@${attribute.name},${escapeCharacters(contentRes[i].trim())})`);
619
- }
620
- }
621
- }
622
- }
623
- if (combinePattern?.length) {
624
- pattern = isSvg(domNode)
625
- ? `//*[local-name()='${domNode.tagName}' and ${combinePattern.join(" and ")}]`
626
- : `//${domNode.tagName}[${combinePattern.join(" and ")}]`;
627
- return pattern;
628
- }
629
- }
630
- };
631
- const getAttributeCombinationXpath = (domNode, docmt, uniqueAttributes, isTarget) => {
632
- try {
633
- const xpathAttributes = [];
634
- if (uniqueAttributes.length > 1) {
635
- for (const attrName of uniqueAttributes) {
636
- if (checkBlockedAttributes(attrName, domNode, isTarget)) {
637
- const attrValue = attrName.nodeValue;
638
- if (!reWhiteSpace$1.test(attrValue)) {
639
- xpathAttributes.push(`normalize-space(@${attrName.nodeName})="${attrValue}"`);
640
- }
641
- else if (attrName.nodeName === "class") {
642
- xpathAttributes.push(`contains(@${attrName.nodeName},"${attrValue}")`);
643
- }
644
- else {
645
- xpathAttributes.push(`@${attrName.nodeName}="${attrValue}"`);
646
- }
647
- const xpathe = isSvg(domNode)
648
- ? `//*[local-name()='${domNode.tagName}' and ${xpathAttributes.join(" and ")}]`
649
- : `//${domNode.tagName}[${xpathAttributes.join(" and ")}]`;
650
- let othersWithAttr;
651
- // If the XPath does not parse, move to the next unique attribute
652
- try {
653
- othersWithAttr = getCountOfXPath(xpathe, domNode, docmt);
654
- }
655
- catch (ign) {
656
- continue;
657
- }
658
- if (othersWithAttr === 1 && !xpathe.includes("and")) {
659
- return "";
660
- }
661
- // If the attribute isn't actually unique, get it's index too
662
- if (othersWithAttr === 1 && xpathe.includes("and")) {
663
- return xpathe;
664
- }
665
- }
666
- }
667
- }
668
- }
669
- catch (error) {
670
- // If there's an unexpected exception, abort and don't get an XPath
671
- console.log(`'${JSON.stringify(error, null, 2)}'`);
672
- }
673
- };
674
- const intermediateXpathStep = (targetElemt, attr, isTarget) => {
675
- let isSvgElement = isSvg(targetElemt);
676
- let expression = "";
677
- if (checkBlockedAttributes(attr, targetElemt, isTarget)) {
678
- let attrValue = attr.value;
679
- attrValue = attrValue.replace("removePointers", "");
680
- const elementName = attr.name;
681
- if (!reWhiteSpace$1.test(attrValue)) {
682
- expression = isSvgElement
683
- ? `*[local-name()='${targetElemt.tagName}' and normalize-space(@${elementName})=${escapeCharacters(attrValue)}]`
684
- : `${targetElemt.tagName || "*"}[normalize-space(@${elementName})=${escapeCharacters(attrValue)}]`;
685
- }
686
- else {
687
- expression = isSvgElement
688
- ? `*[local-name()='${targetElemt.tagName}' and @${elementName}=${escapeCharacters(attrValue)}]`
689
- : `${targetElemt.tagName || "*"}[@${elementName}=${escapeCharacters(attrValue)}]`;
690
- }
691
- }
692
- return expression;
693
- };
694
- const getFilteredTextXPath = (node, docmt) => {
695
- if (!node.textContent)
696
- return "";
697
- const filteredText = getFilteredText(node);
698
- let xpathe;
699
- if (!reWhiteSpace$1.test(filteredText)) {
700
- xpathe = isSvg(node)
701
- ? `//*[local-name()='${node.tagName}' and normalize-space(.)=${escapeCharacters(filteredText)}]`
702
- : `//${node.tagName || "*"}[normalize-space(.)=${escapeCharacters(filteredText)}]`;
703
- }
704
- else {
705
- xpathe = isSvg(node)
706
- ? `//*[local-name()='${node.tagName}' and .=${escapeCharacters(filteredText)}]`
707
- : `//${node.tagName || "*"}[.=${escapeCharacters(filteredText)}]`;
708
- }
709
- return xpathe;
710
- };
711
- const getTextXpathFunction = (domNode) => {
712
- const trimmedText = getTextContent(domNode)?.trim();
713
- const filteredText = trimmedText
714
- ? escapeCharacters(deleteGarbageFromInnerText(trimmedText))
715
- : trimmedText;
716
- if (filteredText) {
717
- if (filteredText !== `'${trimmedText}'`) {
718
- return `contains(.,${filteredText})`;
719
- }
720
- return `normalize-space(.)='${trimmedText}'`;
721
- }
722
- };
723
- const getXpathString = (node, attrName, attrValue) => {
724
- const reWhiteSpace = new RegExp(/^[\S]+( [\S]+)*$/gi);
725
- let xpathe = "";
726
- if (attrValue) {
727
- if (!reWhiteSpace.test(attrValue)) {
728
- xpathe = isSvg(node)
729
- ? `//*[local-name()='${node.tagName}' and contains(@${attrName},${escapeCharacters(attrValue)})]`
730
- : `//${node.tagName || "*"}[contains(@${attrName},${escapeCharacters(attrValue)})]`;
731
- }
732
- else if (attrName === "class") {
733
- xpathe = isSvg(node)
734
- ? `//*[local-name()='${node.tagName}' and contains(@${attrName},${escapeCharacters(attrValue)})]`
735
- : `//${node.tagName || "*"}[contains(@${attrName},${escapeCharacters(attrValue)})]`;
736
- }
737
- else {
738
- xpathe = isSvg(node)
739
- ? `//*[local-name()='${node.tagName}' and @${attrName}=${escapeCharacters(attrValue)}]`
740
- : `//${node.tagName || "*"}[@${attrName}=${escapeCharacters(attrValue)}]`;
741
- }
742
- }
743
- return xpathe;
744
- };
745
- const replaceActualAttributes = (str, element) => {
746
- if (str) {
747
- return str.replace(/\bdisabled\b/gi, "flndisabled");
748
- }
749
- return str;
750
- };
751
- const addAttributeSplitCombineXpaths = (attributes, targetElemt, docmt, isTarget) => {
752
- const attributesArray = Array.prototype.slice.call(attributes);
753
- const xpaths = [];
754
- try {
755
- attributesArray.map((element) => {
756
- if (checkBlockedAttributes(element, targetElemt, isTarget)) {
757
- const xpth = getCombinationXpath(element, targetElemt);
758
- if (xpth) {
759
- xpaths.push({
760
- key: `split xpath by ${element.name}`,
761
- value: xpth,
762
- });
763
- }
764
- }
765
- });
766
- }
767
- catch (error) {
768
- console.log(error);
769
- }
770
- return xpaths;
771
- };
772
- const getReferenceElementsXpath = (domNode, docmt, isTarget) => {
773
- let nodeXpath1;
774
- const xpaths1 = [];
775
- if (domNode.textContent &&
776
- (!isTarget || (isTarget && !isNumberExist(domNode.textContent)))) {
777
- if (!reWhiteSpace$1.test(domNode.textContent)) {
778
- nodeXpath1 = isSvg(domNode)
779
- ? `*[local-name()='${domNode.tagName}' and ${getTextXpathFunction(domNode)})]`
780
- : `${domNode.tagName}[${getTextXpathFunction(domNode)}]`;
781
- if (nodeXpath1) {
782
- xpaths1.push({ key: "getReferenceElementsXpath", value: nodeXpath1 });
783
- }
784
- }
785
- else {
786
- nodeXpath1 = isSvg(domNode)
787
- ? `*[local-name()='${domNode.tagName}' and .=${escapeCharacters(getTextContent(domNode))}]`
788
- : `${domNode.tagName}[.=${escapeCharacters(getTextContent(domNode))}]`;
789
- if (nodeXpath1) {
790
- xpaths1.push({ key: "getReferenceElementsXpath", value: nodeXpath1 });
791
- }
792
- }
793
- }
794
- if (domNode.attributes) {
795
- for (const attrName of Array.from(domNode.attributes)) {
796
- if (checkBlockedAttributes(attrName, domNode, isTarget)) {
797
- let attrValue = attrName.nodeValue;
798
- if (attrValue) {
799
- attrValue = attrValue.replace("removePointers", "");
800
- const elementName = attrName.name;
801
- if (elementName === "class") {
802
- nodeXpath1 = isSvg(domNode)
803
- ? `*[local-name()='${domNode.tagName}' and contains(@${elementName},${escapeCharacters(attrValue)})]`
804
- : `${domNode.tagName}[contains(@${elementName},${escapeCharacters(attrValue)})]`;
805
- }
806
- else {
807
- nodeXpath1 = isSvg(domNode)
808
- ? `*[local-name()='${domNode.tagName}' and @${elementName}=${escapeCharacters(attrValue)}]`
809
- : `${domNode.tagName}[@${elementName}=${escapeCharacters(attrValue)}]`;
810
- }
811
- if (nodeXpath1) {
812
- xpaths1.push({
813
- key: "getReferenceElementsXpath",
814
- value: nodeXpath1,
815
- });
816
- }
817
- }
818
- }
819
- }
820
- }
821
- if (!xpaths1?.length) {
822
- const attributesArray = Array.prototype.slice.call(domNode.attributes);
823
- if (attributesArray?.length > 1) {
824
- const combinationXpath = getAttributeCombinationXpath(domNode, docmt, Array.prototype.slice.call(domNode.attributes), isTarget);
825
- if (combinationXpath) {
826
- xpaths1.push({
827
- key: "getReferenceElementsXpath",
828
- value: combinationXpath,
829
- });
830
- }
831
- }
832
- }
833
- if (!xpaths1?.length) {
834
- const combinePattern = [];
835
- let pattern;
836
- const tag = isSvg(domNode);
837
- if (domNode.textContent && isTarget && isNumberExist(domNode.textContent)) {
838
- const contentRes = [...new Set(domNode.textContent.match(/([^0-9]+)/g))];
839
- if (contentRes?.length) {
840
- for (let i = 0; i < contentRes?.length; i++) {
841
- if (contentRes[i] &&
842
- replaceWhiteSpaces(contentRes[i].trim())?.length > 1) {
843
- if (!reWhiteSpace$1.test(contentRes[i])) {
844
- combinePattern.push(`contains(.,${escapeCharacters(replaceWhiteSpaces(contentRes[i])).trim()})`);
845
- }
846
- else {
847
- combinePattern.push(`contains(.,${escapeCharacters(contentRes[i]).trim()})`);
848
- }
849
- }
850
- }
851
- }
852
- if (combinePattern?.length) {
853
- if (tag) {
854
- pattern = `//*[local-name()='${tag}' and ${combinePattern.join(" and ")}]`;
855
- }
856
- else {
857
- pattern = `//${tag}[${combinePattern.join(" and ")}]`;
858
- }
859
- if (pattern)
860
- xpaths1.push({ key: "getReferenceElementsXpath", value: pattern });
861
- }
862
- }
863
- }
864
- if (!xpaths1?.length) {
865
- const xpaths = addAttributeSplitCombineXpaths(domNode.attributes, domNode, docmt, isTarget);
866
- if (xpaths?.length) {
867
- xpaths1.concat(xpaths);
868
- }
869
- }
870
- return xpaths1;
871
- };
872
- const parseXml = (xmlStr, type) => {
873
- if (window.DOMParser) {
874
- return new window.DOMParser().parseFromString(xmlStr, type);
875
- }
876
- return null;
877
- };
878
- const normalizeXPath = (xpath) => {
879
- // Replace text() = "value" or text()='value'
880
- xpath = xpath.replace(/text\(\)\s*=\s*(['"])(.*?)\1/g, "normalize-space(.)=$1$2$1");
881
- // Replace . = "value" or .='value'
882
- xpath = xpath.replace(/\.\s*=\s*(['"])(.*?)\1/g, "normalize-space(.)=$1$2$1");
883
- return xpath;
884
- };
885
- const findMatchingParenthesis = (text, openPos) => {
886
- let closePos = openPos;
887
- let counter = 1;
888
- while (counter > 0) {
889
- const c = text[++closePos];
890
- if (c == "(") {
891
- counter++;
892
- }
893
- else if (c == ")") {
894
- counter--;
895
- }
896
- }
897
- return closePos;
898
- };
899
- const xpathUtils = {
900
- parseXml,
901
- getReferenceElementsXpath,
902
- getAbsoluteXPath,
903
- getRelativeXPath,
904
- getCombinationXpath,
905
- getAttributeCombinationXpath,
906
- getElementFromXpath,
907
- isSvg,
908
- findXpathWithIndex,
909
- isNumberExist,
910
- getTextContent,
911
- getCountOfXPath,
912
- normalizeXPath,
913
- getShadowRoot,
914
- escapeCharacters,
915
- removeParenthesis,
916
- checkBlockedAttributes,
917
- getRelationship,
918
- findMatchingParenthesis,
919
- deleteGarbageFromInnerText,
920
- replaceTempAttributes,
921
- createObserver,
922
- startObserver,
923
- stopObserver,
924
- modifiedElementAttributes: modifiedElementAttributes$1,
925
- cspEnabled
926
- };
927
-
928
- let xpathData$1 = [];
929
- let xpathDataWithIndex$1 = [];
930
- let referenceElementMode = false;
931
- let xpathCache = new Map();
932
- let cache = new Map();
933
- const parentXpathCache = new Map(); // Cache for parent XPaths
934
- const checkRelativeXpathRelation = (nodeXpath1, nodeXpath2, targetElemt, docmt, isIndex, relationType) => {
935
- if (nodeXpath1 && !referenceElementMode) {
936
- let xpaths;
937
- if (relationType === "parent") {
938
- xpaths = [
939
- // `${nodeXpath1}/descendant::${nodeXpath2}`,
940
- `${nodeXpath1}/descendant-or-self::${nodeXpath2}`,
941
- `${nodeXpath1}/following::${nodeXpath2}`,
942
- ];
943
- }
944
- else {
945
- xpaths = [
946
- // `${nodeXpath1}/descendant::${nodeXpath2}`,
947
- `${nodeXpath1}/ancestor-or-self::${nodeXpath2}`,
948
- `${nodeXpath1}/preceding::${nodeXpath2}`,
949
- ];
950
- }
951
- // Iterate through XPath patterns
952
- for (const xpath of xpaths) {
953
- // Check if result is already cached to avoid recomputation
954
- if (!xpathCache?.get(xpath)) {
955
- // Compute and store result in cache
956
- xpathCache.set(xpath, getCountOfXPath(xpath, targetElemt, docmt));
957
- }
958
- const count = xpathCache?.get(xpath);
959
- // Short-circuit: Return the first valid XPath result found
960
- if (count === 1) {
961
- return xpath;
962
- }
963
- if (count > 1) {
964
- if (xpathDataWithIndex$1.length) {
965
- if (count < xpathDataWithIndex$1[0].count) {
966
- xpathDataWithIndex$1.pop();
967
- xpathDataWithIndex$1.push({
968
- key: `relative xpath by unique parent ${isIndex ? "index" : ""}`,
969
- value: xpath,
970
- count,
971
- });
972
- }
973
- }
974
- else {
975
- xpathDataWithIndex$1.push({
976
- key: `relative xpath by unique parent ${isIndex ? "index" : ""}`,
977
- value: xpath,
978
- count,
979
- });
980
- }
981
- }
982
- if (count > 1 && isIndex && !xpathData$1.length) {
983
- // Try finding XPath with index if count is greater than 1
984
- const indexedXpath = findXpathWithIndex(xpath, targetElemt, docmt, count);
985
- // Cache the indexed XPath result
986
- if (indexedXpath &&
987
- getCountOfXPath(indexedXpath, targetElemt, docmt) === 1) {
988
- xpathData$1.push({
989
- key: `relative xpath by unique parent ${isIndex ? "index" : ""}`,
990
- value: indexedXpath,
991
- });
992
- }
993
- }
994
- }
995
- }
996
- return null;
997
- };
998
- const getUniqueParentXpath = (domNode, docmt, node, isTarget, nodeXpath, isIndex) => {
999
- try {
1000
- if (parentXpathCache.has(domNode)) {
1001
- return parentXpathCache.get(domNode);
1002
- }
1003
- // Direct XPath construction without loops
1004
- const xpathParts = [];
1005
- let currentNode = domNode;
1006
- while (currentNode && currentNode.nodeType === 1) {
1007
- const hasUniqueAttr = false;
1008
- for (const attrName of Array.from(currentNode.attributes)) {
1009
- if (checkBlockedAttributes(attrName, currentNode, isTarget)) {
1010
- let attrValue = attrName.nodeValue;
1011
- attrValue = attrValue?.replace("removePointers", "") ?? "";
1012
- const elementName = attrName.name;
1013
- const xpathe = getXpathString(currentNode, elementName, attrValue);
1014
- let othersWithAttr;
1015
- // If the XPath does not parse, move to the next unique attribute
1016
- try {
1017
- othersWithAttr = checkRelativeXpathRelation(xpathe, nodeXpath, node, docmt, isIndex, "parent");
1018
- }
1019
- catch (ign) {
1020
- continue;
1021
- }
1022
- // If the attribute isn't actually unique, get it's index too
1023
- if (othersWithAttr) {
1024
- return othersWithAttr;
1025
- }
1026
- }
1027
- }
1028
- if (currentNode.textContent && !currentNode.textContent) {
1029
- if (!isTarget ||
1030
- (isTarget && !isNumberExist(currentNode.textContent))) {
1031
- let xpathe;
1032
- if (!reWhiteSpace$1.test(currentNode.textContent)) {
1033
- xpathe = isSvg(currentNode)
1034
- ? `//*[local-name()='${currentNode.tagName}' and normalize-space(.)=${escapeCharacters(getFilteredText(currentNode))}]`
1035
- : `//${currentNode.tagName || "*"}[normalize-space(.)=${escapeCharacters(getFilteredText(currentNode))}]`;
1036
- }
1037
- else {
1038
- xpathe = isSvg(currentNode)
1039
- ? `//*[local-name()='${currentNode.tagName}' and .=${escapeCharacters(getFilteredText(currentNode))}]`
1040
- : `//${currentNode.tagName || "*"}[.=${escapeCharacters(getFilteredText(currentNode))}]`;
1041
- }
1042
- const othersWithAttr = checkRelativeXpathRelation(xpathe, nodeXpath, node, docmt, isIndex, "parent");
1043
- if (othersWithAttr) {
1044
- return othersWithAttr;
1045
- }
1046
- }
1047
- else {
1048
- const combinePattern = [];
1049
- const contentRes = [
1050
- ...new Set(getFilteredText(currentNode).match(/([^0-9]+)/g)),
1051
- ];
1052
- const reWhiteSpace = new RegExp(/^[\S]+( [\S]+)*$/gi);
1053
- if (contentRes?.length) {
1054
- for (let i = 0; i < contentRes?.length; i++) {
1055
- if (contentRes[i] && replaceWhiteSpaces(contentRes[i].trim())) {
1056
- if (!reWhiteSpace.test(contentRes[i])) {
1057
- combinePattern.push(`contains(.,${escapeCharacters(replaceWhiteSpaces(contentRes[i])).trim()})`);
1058
- }
1059
- else {
1060
- combinePattern.push(`contains(.,${escapeCharacters(contentRes[i].trim()).trim()})`);
1061
- }
1062
- }
1063
- }
1064
- }
1065
- if (combinePattern?.length) {
1066
- const xpathe = isSvg(currentNode)
1067
- ? `//*[local-name()='${currentNode.tagName}' and ${combinePattern.join(" and ")}]`
1068
- : `//${currentNode.tagName || "*"}[${combinePattern.join(" and ")}]`;
1069
- const othersWithAttr = checkRelativeXpathRelation(xpathe, nodeXpath, node, docmt, isIndex, "parent");
1070
- if (othersWithAttr) {
1071
- return othersWithAttr;
1072
- }
1073
- }
1074
- }
1075
- }
1076
- // Construct the XPath based on the tag name
1077
- if (!hasUniqueAttr) {
1078
- const xpathe = isSvg(currentNode)
1079
- ? `/*[local-name()='${currentNode.tagName}']`
1080
- : `/${currentNode.tagName}`;
1081
- xpathParts.unshift(xpathe);
1082
- }
1083
- // Move to the parent node for the next iteration
1084
- currentNode = currentNode.parentElement;
1085
- }
1086
- // Final constructed XPath
1087
- const finalXPath = xpathParts.join("") + nodeXpath;
1088
- let count = getCountOfXPath(finalXPath, domNode, docmt);
1089
- if (count === 1) {
1090
- parentXpathCache.set(domNode, finalXPath); // Cache final result
1091
- return finalXPath;
1092
- }
1093
- }
1094
- catch (error) {
1095
- console.error(error);
1096
- return null;
1097
- }
1098
- };
1099
- const getParentRelativeXpath = (domNode, docmt, node, isTarget) => {
1100
- const cache = new Map(); // Cache to store computed results
1101
- if (cache.has(domNode)) {
1102
- return cache.get(domNode); // Return cached result if available
1103
- }
1104
- const xpathParts = []; // Initialize an array to hold parts of the XPath
1105
- let currentNode = domNode; // Start with the provided DOM node
1106
- try {
1107
- while (currentNode && currentNode.nodeType === 1) {
1108
- // BASE CASE #1: If this isn't an element, we're above the root, return empty string
1109
- if (!currentNode.tagName) {
1110
- return "";
1111
- }
1112
- // BASE CASE #2: Check for unique attributes
1113
- let uniqueAttrFound = false;
1114
- for (const attr of Array.from(currentNode.attributes)) {
1115
- if (checkBlockedAttributes(attr, currentNode, isTarget)) {
1116
- let attrValue = attr.nodeValue;
1117
- attrValue = attrValue?.replace("removePointers", "") ?? "";
1118
- const elementName = attr.name;
1119
- const xpathe = getXpathString(currentNode, elementName, attrValue);
1120
- let othersWithAttr;
1121
- // If the XPath does not parse, move to the next unique attribute
1122
- try {
1123
- othersWithAttr = getCountOfXPath(xpathe, currentNode, docmt);
1124
- }
1125
- catch (ign) {
1126
- continue;
1127
- }
1128
- // If the attribute is unique, return its XPath
1129
- if (othersWithAttr === 1) {
1130
- xpathParts.unshift(xpathe);
1131
- uniqueAttrFound = true; // Mark that we found at least one unique attribute
1132
- break;
1133
- }
1134
- }
1135
- }
1136
- // If no unique attributes, check for text content
1137
- if (!uniqueAttrFound && currentNode.textContent && !node.textContent) {
1138
- const textXPath = getFilteredTextXPath(currentNode, docmt);
1139
- if (textXPath) {
1140
- const othersWithAttr = getCountOfXPath(textXPath, currentNode, docmt);
1141
- if (othersWithAttr === 1) {
1142
- uniqueAttrFound = true; // Mark that we found at least one unique attribute
1143
- xpathParts.unshift(textXPath);
1144
- break;
1145
- }
1146
- }
1147
- }
1148
- if (!uniqueAttrFound) {
1149
- // Construct the XPath based on the tag name
1150
- const xpathe = isSvg(currentNode)
1151
- ? `/*[local-name()='${currentNode.tagName}']`
1152
- : `/${currentNode.tagName}`;
1153
- // Prepend the current XPath part to the array
1154
- xpathParts.unshift(xpathe);
1155
- }
1156
- else {
1157
- break;
1158
- }
1159
- // Move to the parent node for the next iteration
1160
- currentNode = currentNode.parentElement;
1161
- }
1162
- // Combine all parts into the final XPath
1163
- const finalXpath = xpathParts.join("");
1164
- cache.set(domNode, finalXpath); // Store result in cache
1165
- return finalXpath;
1166
- }
1167
- catch (error) {
1168
- console.log(error);
1169
- return null;
1170
- }
1171
- };
1172
- const getChildRelativeXpath = (domNode, docmt, node) => {
1173
- const xpathParts = []; // Initialize an array to hold parts of the XPath.
1174
- let currentNode;
1175
- const st = [];
1176
- if (domNode.firstElementChild != null &&
1177
- domNode.firstElementChild.classList.contains("flntooltip")) {
1178
- st.unshift(domNode.firstElementChild);
1179
- }
1180
- else if (domNode.nextElementSibling != null)
1181
- st.unshift(domNode.nextElementSibling);
1182
- for (let m = domNode.parentElement; m != null && m.nodeType === 1; m = m.parentElement) {
1183
- if (m.nextElementSibling)
1184
- st.unshift(m.nextElementSibling);
1185
- }
1186
- try {
1187
- do {
1188
- let uniqueAttrFound = false;
1189
- for (currentNode = st.pop(); currentNode !== null;) {
1190
- for (const attr of Array.from(currentNode.attributes)) {
1191
- if (checkBlockedAttributes(attr, currentNode, true)) {
1192
- let attrValue = attr.nodeValue;
1193
- attrValue = attrValue?.replace("removePointers", "") ?? "";
1194
- const elementName = attr.name;
1195
- const xpathe = getXpathString(currentNode, elementName, attrValue);
1196
- let othersWithAttr;
1197
- // If the XPath does not parse, move to the next unique attribute
1198
- try {
1199
- othersWithAttr = getCountOfXPath(xpathe, currentNode, docmt);
1200
- }
1201
- catch (ign) {
1202
- continue;
1203
- }
1204
- // If the attribute is unique, return its XPath
1205
- if (othersWithAttr === 1) {
1206
- uniqueAttrFound = true; // Mark that we found at least one unique attribute
1207
- xpathParts.push(xpathe);
1208
- break;
1209
- }
1210
- }
1211
- }
1212
- // If no unique attributes, check for text content
1213
- if (!uniqueAttrFound && currentNode.textContent && !node.textContent) {
1214
- const textXPath = getFilteredTextXPath(currentNode, docmt);
1215
- if (textXPath) {
1216
- const othersWithAttr = getCountOfXPath(textXPath, currentNode, docmt);
1217
- if (othersWithAttr === 1) {
1218
- uniqueAttrFound = true; // Mark that we found at least one unique attribute
1219
- xpathParts.push(textXPath);
1220
- break;
1221
- }
1222
- }
1223
- }
1224
- if (!uniqueAttrFound) {
1225
- // Construct the XPath based on the tag name
1226
- const xpathe = isSvg(currentNode)
1227
- ? `/*[local-name()='${currentNode.tagName}']`
1228
- : `/${currentNode.tagName}`;
1229
- // Prepend the current XPath part to the array
1230
- xpathParts.push(xpathe);
1231
- if (currentNode.firstElementChild != null) {
1232
- st.push(currentNode.nextElementSibling);
1233
- currentNode = currentNode.firstElementChild;
1234
- }
1235
- else {
1236
- currentNode = currentNode.nextElementSibling;
1237
- }
1238
- }
1239
- else {
1240
- break;
1241
- }
1242
- }
1243
- } while (st.length > 0);
1244
- // Combine all parts into the final XPath
1245
- const finalXpath = xpathParts.join("");
1246
- cache.set(domNode, finalXpath); // Store result in cache
1247
- return finalXpath;
1248
- }
1249
- catch (error) {
1250
- console.log(error);
1251
- return null;
1252
- }
1253
- };
1254
- const getSiblingRelativeXPath = (domNode, docmt, isTarget, nodeXpath) => {
1255
- try {
1256
- const markedSpan = document.querySelector(".flntooltip");
1257
- for (let m = domNode.nextElementSibling; m !== null && m !== markedSpan; m = m.nextElementSibling) {
1258
- processSibling(m, domNode, docmt, nodeXpath, "preceding-sibling", isTarget);
1259
- }
1260
- for (let n = domNode.previousElementSibling; n !== null && n !== markedSpan; n = n.previousElementSibling) {
1261
- processSibling(n, domNode, docmt, nodeXpath, "following-sibling", isTarget);
1262
- }
1263
- }
1264
- catch (error) {
1265
- console.error("sibling error", error);
1266
- return null;
1267
- }
1268
- };
1269
- const processSibling = (sibling, domNode, docmt, nodeXpath, axis, isTarget) => {
1270
- try {
1271
- if (sibling.hasAttributes()) {
1272
- for (const attr of Array.from(sibling.attributes)) {
1273
- let xpathe = intermediateXpathStep(sibling, {
1274
- name: attr.name,
1275
- value: attr.value,
1276
- }, isTarget);
1277
- if (xpathe) {
1278
- xpathe += `/${axis}::${nodeXpath}`;
1279
- const count = getCountOfXPath(xpathe, sibling, docmt);
1280
- if (count === 1) {
1281
- xpathData$1.push({
1282
- key: `xpath by ${axis}`,
1283
- value: xpathe,
1284
- });
1285
- return;
1286
- }
1287
- else if (count > 1) {
1288
- if (xpathDataWithIndex$1.length) {
1289
- if (count < xpathDataWithIndex$1[0].count) {
1290
- xpathDataWithIndex$1.pop();
1291
- xpathDataWithIndex$1.push({
1292
- key: `relative xpath by ${axis}`,
1293
- value: xpathe,
1294
- count,
1295
- });
1296
- }
1297
- }
1298
- else {
1299
- xpathDataWithIndex$1.push({
1300
- key: `relative xpath by ${axis}`,
1301
- value: xpathe,
1302
- count,
1303
- });
1304
- }
1305
- }
1306
- }
1307
- }
1308
- }
1309
- if (!isTarget) {
1310
- let xpathe;
1311
- xpathe = intermediateXpathStep(sibling, {
1312
- name: "text",
1313
- value: sibling.textContent,
1314
- }, isTarget);
1315
- if (xpathe) {
1316
- const count = getCountOfXPath(xpathe, sibling, docmt);
1317
- if (count === 1) {
1318
- xpathData$1.push({
1319
- key: `xpath by ${axis}`,
1320
- value: xpathe,
1321
- });
1322
- return;
1323
- }
1324
- else if (count > 1) {
1325
- if (xpathDataWithIndex$1.length) {
1326
- if (count < xpathDataWithIndex$1[0].count) {
1327
- xpathDataWithIndex$1.pop();
1328
- xpathDataWithIndex$1.push({
1329
- key: `relative xpath by ${axis}`,
1330
- value: xpathe,
1331
- count,
1332
- });
1333
- }
1334
- }
1335
- else {
1336
- xpathDataWithIndex$1.push({
1337
- key: `relative xpath by ${axis}`,
1338
- value: xpathe,
1339
- count,
1340
- });
1341
- }
1342
- }
1343
- }
1344
- }
1345
- }
1346
- catch (error) {
1347
- console.log(`${axis} xpath-error`, error);
1348
- }
1349
- };
1350
- function getXPathUsingAttributeAndText(attributes, targetElemt, docmt, isTarget) {
1351
- const { tagName } = targetElemt;
1352
- const textContent = targetElemt.textContent.trim();
1353
- for (const attrName of attributes) {
1354
- if (checkBlockedAttributes(attrName, targetElemt, isTarget)) {
1355
- let attrValue = attrName.nodeValue;
1356
- attrValue = attrValue?.replace("removePointers", "") ?? "";
1357
- const elementName = attrName.name;
1358
- const xpath = `//${tagName}[@${elementName}='${attrValue}' and text()='${textContent}']`;
1359
- if (xpath) {
1360
- const count = getCountOfXPath(xpath, targetElemt, docmt);
1361
- if (count == 1) {
1362
- return xpath;
1363
- }
1364
- }
1365
- }
1366
- }
1367
- }
1368
- const addRelativeXpaths = (targetElemt, docmt, isIndex, isTarget, attribute) => {
1369
- try {
1370
- let nodeXpath = [];
1371
- let relativeXpath, relativeChildXpath;
1372
- if (!xpathData$1.length && isIndex) {
1373
- if (xpathDataWithIndex$1.length) {
1374
- const xpathWithIndex = findXpathWithIndex(xpathDataWithIndex$1[0].value, targetElemt, docmt, xpathDataWithIndex$1[0].count);
1375
- if (xpathWithIndex) {
1376
- xpathData$1.push({
1377
- key: xpathDataWithIndex$1[0].key,
1378
- value: xpathWithIndex,
1379
- });
1380
- xpathDataWithIndex$1.pop();
1381
- }
1382
- }
1383
- }
1384
- console.log(attribute);
1385
- if (!xpathData$1.length) {
1386
- if (targetElemt.attributes) {
1387
- for (const attrName of attribute) {
1388
- let expression = intermediateXpathStep(targetElemt, {
1389
- name: attrName.name,
1390
- value: attrName.value,
1391
- }, isTarget);
1392
- console.log(expression);
1393
- if (expression) {
1394
- nodeXpath.push(expression);
1395
- }
1396
- }
1397
- }
1398
- if (targetElemt.textContent) {
1399
- let expression = intermediateXpathStep(targetElemt, {
1400
- name: "text",
1401
- value: targetElemt.textContent,
1402
- }, isTarget);
1403
- console.log(expression);
1404
- if (expression) {
1405
- nodeXpath.push(expression);
1406
- }
1407
- }
1408
- if (nodeXpath?.length) {
1409
- for (let i = 0; i < nodeXpath.length; i++) {
1410
- if (!xpathData$1.length) {
1411
- getSiblingRelativeXPath(targetElemt, docmt, isTarget, nodeXpath[i]);
1412
- if (!xpathData$1.length) {
1413
- if (!relativeXpath) {
1414
- relativeXpath = getParentRelativeXpath(targetElemt.parentElement, docmt, targetElemt, isTarget);
1415
- }
1416
- console.log(relativeXpath);
1417
- if (relativeXpath &&
1418
- (relativeXpath.includes("@") ||
1419
- relativeXpath.includes("text()") ||
1420
- relativeXpath.includes(".=")) &&
1421
- relativeXpath.match(/\//g)?.length - 2 < 5) {
1422
- const fullRelativeXpath = relativeXpath + `/${nodeXpath[i]}`;
1423
- const count = getCountOfXPath(fullRelativeXpath, targetElemt, docmt);
1424
- if (count === 1) {
1425
- xpathData$1.push({
1426
- key: "relative xpath by relative parent",
1427
- value: fullRelativeXpath,
1428
- });
1429
- }
1430
- else if (count > 1 && isIndex) {
1431
- const relativeXpathIndex = findXpathWithIndex(fullRelativeXpath, targetElemt, docmt, count);
1432
- if (relativeXpathIndex &&
1433
- getCountOfXPath(relativeXpathIndex, targetElemt, docmt) ===
1434
- 1) {
1435
- xpathData$1.push({
1436
- key: `relative xpath by relative parent ${isIndex ? "index" : ""}`,
1437
- value: relativeXpathIndex,
1438
- });
1439
- }
1440
- }
1441
- else if (count > 1) {
1442
- if (xpathDataWithIndex$1.length) {
1443
- if (count < xpathDataWithIndex$1[0].count) {
1444
- xpathDataWithIndex$1.pop();
1445
- xpathDataWithIndex$1.push({
1446
- key: `relative xpath by relative parent ${isIndex ? "index" : ""}`,
1447
- value: fullRelativeXpath,
1448
- count,
1449
- });
1450
- }
1451
- }
1452
- else {
1453
- xpathDataWithIndex$1.push({
1454
- key: `relative xpath by relative parent ${isIndex ? "index" : ""}`,
1455
- value: fullRelativeXpath,
1456
- count,
1457
- });
1458
- }
1459
- }
1460
- }
1461
- }
1462
- if (!xpathData$1.length) {
1463
- if (!relativeChildXpath) {
1464
- relativeChildXpath = getChildRelativeXpath(targetElemt, docmt, targetElemt);
1465
- }
1466
- if (relativeChildXpath &&
1467
- (relativeChildXpath.includes("@") ||
1468
- relativeChildXpath.includes("text()") ||
1469
- relativeChildXpath.includes(".="))) {
1470
- const fullRelativeXpath = `/${nodeXpath[i] + relativeChildXpath.substring(1)}`;
1471
- const count = getCountOfXPath(fullRelativeXpath, targetElemt, docmt);
1472
- if (count === 1) {
1473
- xpathData$1.push({
1474
- key: "relative xpath by relative child",
1475
- value: fullRelativeXpath,
1476
- });
1477
- }
1478
- else if (count > 1 && isIndex) {
1479
- const relativeXpathIndex = findXpathWithIndex(fullRelativeXpath, targetElemt, docmt, count);
1480
- if (relativeXpathIndex &&
1481
- getCountOfXPath(relativeXpathIndex, targetElemt, docmt) ===
1482
- 1) {
1483
- xpathData$1.push({
1484
- key: `relative xpath by relative parent ${isIndex ? "index" : ""}`,
1485
- value: relativeXpathIndex,
1486
- });
1487
- }
1488
- }
1489
- else if (count > 1) {
1490
- if (xpathDataWithIndex$1.length) {
1491
- if (count < xpathDataWithIndex$1[0].count) {
1492
- xpathDataWithIndex$1.pop();
1493
- xpathDataWithIndex$1.push({
1494
- key: `relative xpath by relative child ${isIndex ? "index" : ""}`,
1495
- value: fullRelativeXpath,
1496
- count,
1497
- });
1498
- }
1499
- }
1500
- else {
1501
- xpathDataWithIndex$1.push({
1502
- key: `relative xpath by relative child ${isIndex ? "index" : ""}`,
1503
- value: fullRelativeXpath,
1504
- count,
1505
- });
1506
- }
1507
- }
1508
- }
1509
- }
1510
- if (xpathData$1?.length === 1 &&
1511
- xpathData$1?.[0]?.value?.match(/\[([0-9]+)\]/gm)?.length > 3 &&
1512
- !referenceElementMode) {
1513
- if (targetElemt.textContent) {
1514
- const txtXpath = getTextXPath(targetElemt, docmt, isIndex, false);
1515
- if (txtXpath) {
1516
- xpathData$1.unshift({
1517
- key: `xpath by text${isIndex ? "index" : ""}`,
1518
- value: txtXpath,
1519
- });
1520
- }
1521
- }
1522
- }
1523
- if (!xpathData$1.length) {
1524
- let tempRelativeXpath = getUniqueParentXpath(targetElemt.parentElement, docmt, targetElemt, isTarget, nodeXpath[i], isIndex);
1525
- if (tempRelativeXpath) {
1526
- xpathData$1.push({
1527
- key: "xpath by unique parent",
1528
- value: tempRelativeXpath,
1529
- });
1530
- }
1531
- }
1532
- }
1533
- }
1534
- }
1535
- }
1536
- return xpathData$1;
1537
- }
1538
- catch (error) {
1539
- console.log(error);
1540
- }
1541
- };
1542
- const attributesBasedXPath = (attr, targetElemt, docmt, isIndex, isTarget) => {
1543
- let attrName;
1544
- attrName = attr.name;
1545
- let xpath = getPropertyXPath(targetElemt, docmt, `@${attrName}`, attr.value, isIndex, isTarget);
1546
- return xpath;
1547
- };
1548
- const getUniqueClassName = (element, docmt, isIndex, isTarget) => {
1549
- let value = element.className;
1550
- if (typeof value !== "string") {
1551
- value = "";
1552
- }
1553
- value = value?.replace("flndisabled", "disabled");
1554
- value = value?.replace("removePointers", "");
1555
- value = value?.trim();
1556
- if (value) {
1557
- return getPropertyXPath(element, docmt, `@class`, value, isIndex, isTarget);
1558
- }
1559
- };
1560
- const getTextXPath = (element, docmt, isIndex, isTarget) => {
1561
- if (element.textContent != "") {
1562
- const text = getTextContent(element);
1563
- if (text) {
1564
- return getPropertyXPath(element, docmt, ".", text, isIndex, isTarget);
1565
- }
1566
- }
1567
- };
1568
- const addAllXPathAttributes = (attributes, targetElemt, docmt, isIndex, isTarget) => {
1569
- const attributesArray = attributes;
1570
- try {
1571
- attributesArray.map((attr) => {
1572
- if (!(attr.name === "className" || attr.name === "class")) {
1573
- if (checkBlockedAttributes(attr, targetElemt, isTarget)) {
1574
- const xpth = attributesBasedXPath(attr, targetElemt, docmt, isIndex, isTarget);
1575
- if (xpth) {
1576
- xpathData$1.push({
1577
- key: `xpath by ${attr.name}${isIndex ? " index" : ""}`,
1578
- value: xpth,
1579
- });
1580
- }
1581
- }
1582
- }
1583
- });
1584
- const txtXpath = getTextXPath(targetElemt, docmt, isIndex, isTarget);
1585
- if (txtXpath) {
1586
- xpathData$1.push({
1587
- key: `xpath by text${isIndex ? " index" : ""}`,
1588
- value: txtXpath,
1589
- });
1590
- }
1591
- if (attributesArray.find((element) => element.name === "className") &&
1592
- checkBlockedAttributes(attributesArray?.find((element) => element.name === "className"), targetElemt, isTarget)) {
1593
- let xpath = getUniqueClassName(targetElemt, docmt, isIndex, isTarget);
1594
- if (xpath) {
1595
- xpathData$1.push({
1596
- key: "xpath by class",
1597
- value: xpath,
1598
- });
1599
- }
1600
- }
1601
- if (!xpathData$1.length) {
1602
- const textAttribute = getXPathUsingAttributeAndText(attributes, targetElemt, docmt, isTarget);
1603
- if (textAttribute)
1604
- xpathData$1.push({
1605
- key: "xpath by textAttribute",
1606
- value: textAttribute,
1607
- });
1608
- }
1609
- if (!xpathData$1.length && attributesArray.length > 1) {
1610
- const combinationXpath = getAttributeCombinationXpath(targetElemt, docmt, attributesArray, isTarget);
1611
- if (combinationXpath)
1612
- xpathData$1.push({
1613
- key: "xpath by combination",
1614
- value: combinationXpath,
1615
- });
1616
- }
1617
- }
1618
- catch (error) {
1619
- console.log(error);
1620
- }
1621
- };
1622
- const parseDOM = (element, doc, isIndex, isTarget) => {
1623
- xpathData$1 = [];
1624
- console.log(element);
1625
- const targetElemt = element;
1626
- const docmt = targetElemt?.ownerDocument || doc;
1627
- const tag = targetElemt.tagName;
1628
- const { attributes } = targetElemt;
1629
- addAllXPathAttributes(Array.from(attributes), targetElemt, docmt, isIndex, isTarget);
1630
- {
1631
- if (xpathData$1.length) {
1632
- const len = xpathData$1.length;
1633
- for (let i = 0; i < len; i++) {
1634
- let xpth = xpathData$1[i].value;
1635
- xpth = "//*" + xpth.substring(xpth.indexOf("//") + 2 + tag.length);
1636
- const count = getCountOfXPath(xpth, element, docmt);
1637
- if (count === 1) {
1638
- xpathData$1.push({
1639
- key: `${xpathData$1[i].key} regex`,
1640
- value: xpth,
1641
- });
1642
- }
1643
- }
1644
- }
1645
- }
1646
- console.log(xpathData$1);
1647
- if (!xpathData$1.length) {
1648
- addRelativeXpaths(targetElemt, docmt, isIndex, isTarget, Array.from(targetElemt.attributes));
1649
- }
1650
- return xpathData$1;
1651
- };
1652
- const xpath = {
1653
- parseDOM,
1654
- getTextXPath,
1655
- getUniqueClassName,
1656
- attributesBasedXPath,
1657
- addAllXPathAttributes,
1658
- addRelativeXpaths,
1659
- getXPathUsingAttributeAndText,
1660
- getSiblingRelativeXPath,
1661
- getChildRelativeXpath,
1662
- getParentRelativeXpath,
1663
- getUniqueParentXpath,
1664
- checkRelativeXpathRelation,
1665
- };
1666
-
1667
- let xpathDataWithIndex = [];
1668
- let xpathData = [];
1669
- const reWhiteSpace = /^[\S]+( [\S]+)*$/gi;
1670
- const findRelativeXpath = (element1, element2, docmt, xpaths1, xpaths2, isIndex, multiElementReferenceMode = false) => {
1671
- // debugger;
1672
- const par1 = element1.parentElement;
1673
- const par2 = element2.parentElement;
1674
- let rel_xpath = [];
1675
- let tempElement;
1676
- let finalXpaths = [];
1677
- if (isIndex) {
1678
- if (xpathDataWithIndex.length) {
1679
- const xpathWithIndex = findXpathWithIndex(xpathDataWithIndex[0].value, element2, element2.ownerDocument, xpathDataWithIndex[0].count);
1680
- if (xpathWithIndex) {
1681
- finalXpaths = finalXpaths.concat({
1682
- key: `${xpathDataWithIndex[0]?.key
1683
- ? xpathDataWithIndex[0]?.key
1684
- : "xpath with "} index`,
1685
- value: xpathWithIndex,
1686
- });
1687
- xpathDataWithIndex.pop();
1688
- }
1689
- }
1690
- }
1691
- if (!finalXpaths.length) {
1692
- // both are same
1693
- if (element1.isSameNode(element2)) {
1694
- // rel_xpath = xpath1 + "/self::" + element1.tagName;
1695
- rel_xpath = getXpathRelationExpression(element1, element2, "self", xpaths1, xpaths2, isIndex, multiElementReferenceMode);
1696
- if (rel_xpath)
1697
- finalXpaths = finalXpaths.concat(rel_xpath);
1698
- }
1699
- // parent
1700
- tempElement = element1.parentElement;
1701
- if (tempElement === element2) {
1702
- rel_xpath = getXpathRelationExpression(element1, element2, "parent", xpaths1, xpaths2, isIndex, multiElementReferenceMode);
1703
- if (rel_xpath)
1704
- finalXpaths = finalXpaths.concat(rel_xpath);
1705
- }
1706
- // ancestor
1707
- tempElement = element1.parentElement;
1708
- while (tempElement !== null) {
1709
- if (tempElement === element2) {
1710
- rel_xpath = getXpathRelationExpression(element1, element2, "ancestor", xpaths1, xpaths2, isIndex, multiElementReferenceMode);
1711
- if (rel_xpath) {
1712
- finalXpaths = finalXpaths.concat(rel_xpath);
1713
- break;
1714
- }
1715
- }
1716
- tempElement = tempElement.parentNode;
1717
- }
1718
- // ancestor-or-self
1719
- tempElement = element1;
1720
- do {
1721
- if (tempElement === element2) {
1722
- rel_xpath = getXpathRelationExpression(element1, element2, "ancestor-or-self", xpaths1, xpaths2, isIndex, multiElementReferenceMode);
1723
- if (rel_xpath) {
1724
- finalXpaths = finalXpaths.concat(rel_xpath);
1725
- break;
1726
- }
1727
- }
1728
- tempElement = tempElement.parentNode;
1729
- } while (tempElement !== null);
1730
- // both has same parent
1731
- if (par1?.isSameNode(par2)) {
1732
- for (let m = element1.nextElementSibling; m != null; m = m.nextElementSibling) {
1733
- if (m != null && m.isSameNode(element2)) {
1734
- rel_xpath = getXpathRelationExpression(element1, element2, "following-sibling", xpaths1, xpaths2, isIndex, multiElementReferenceMode);
1735
- if (rel_xpath) {
1736
- finalXpaths = finalXpaths.concat(rel_xpath);
1737
- break;
1738
- }
1739
- }
1740
- }
1741
- for (let n = element1.previousElementSibling; n != null; n = n.previousElementSibling) {
1742
- if (n != null && n.isSameNode(element2)) {
1743
- rel_xpath = getXpathRelationExpression(element1, element2, "preceding-sibling", xpaths1, xpaths2, isIndex, multiElementReferenceMode);
1744
- if (rel_xpath) {
1745
- finalXpaths = finalXpaths.concat(rel_xpath);
1746
- break;
1747
- }
1748
- }
1749
- }
1750
- }
1751
- // child
1752
- if (element1?.children?.length) {
1753
- for (let m = element1.children[0]; m !== null; m = m?.nextElementSibling) {
1754
- if (m === element2) {
1755
- rel_xpath = getXpathRelationExpression(element1, element2, "child", xpaths1, xpaths2, isIndex, multiElementReferenceMode);
1756
- if (rel_xpath) {
1757
- finalXpaths = finalXpaths.concat(rel_xpath);
1758
- break;
1759
- }
1760
- }
1761
- }
1762
- }
1763
- // following
1764
- const relation = element1.compareDocumentPosition(element2);
1765
- if (relation === 2) {
1766
- rel_xpath = getXpathRelationExpression(element1, element2, "preceding", xpaths1, xpaths2, isIndex, multiElementReferenceMode);
1767
- }
1768
- if (relation === 4) {
1769
- rel_xpath = getXpathRelationExpression(element1, element2, "following", xpaths1, xpaths2, isIndex, multiElementReferenceMode);
1770
- }
1771
- if (rel_xpath) {
1772
- finalXpaths = finalXpaths.concat(rel_xpath);
1773
- }
1774
- const descendantXpath = getDescendantXpath([element1, element2], docmt, xpaths1, xpaths2, "descendant", isIndex, multiElementReferenceMode);
1775
- if (descendantXpath)
1776
- finalXpaths = finalXpaths.concat(descendantXpath);
1777
- const descendantSelfXpath = getDescendantXpath([element1, element2], docmt, xpaths1, xpaths2, "descedant-or-self", isIndex, multiElementReferenceMode);
1778
- if (descendantSelfXpath) {
1779
- finalXpaths = finalXpaths.concat(descendantSelfXpath);
1780
- }
1781
- }
1782
- if (finalXpaths.length) {
1783
- if (finalXpaths.length > 1) {
1784
- finalXpaths.sort(function (a, b) {
1785
- return a.value.length - b.value.length;
1786
- });
1787
- }
1788
- if (finalXpaths.filter((x) => !x.key?.includes("index"))?.length) {
1789
- return [finalXpaths.filter((x) => !x.key?.includes("index"))[0]];
1790
- }
1791
- return [finalXpaths[0]];
1792
- }
1793
- };
1794
- const descendantExpression = (refExpectElement, xpath2, relation, docmt, isIndex, expCommonParentXpathElements, step4, refCommonParentXpathElementLength = 0, multiElementReferenceMode = false) => {
1795
- let finalExpectedElementXpath = "";
1796
- if (xpath2.split(/\/(?=(?:[^']*\'[^\']*\')*[^\']*$)/g)?.length >=
1797
- expCommonParentXpathElements.length) {
1798
- const xpaths2Els = [];
1799
- const xpath2Elements = xpath2.split(/\/(?=(?:[^']*\'[^\']*\')*[^\']*$)/g);
1800
- for (let x = 1; x <= expCommonParentXpathElements.length; x++) {
1801
- xpaths2Els.unshift(x === expCommonParentXpathElements.length
1802
- ? expCommonParentXpathElements[expCommonParentXpathElements.length - x]
1803
- : xpath2Elements[xpath2Elements.length - x]);
1804
- }
1805
- const traverseXpath = getTraverseXpathExpression(`${step4 +
1806
- (refCommonParentXpathElementLength
1807
- ? "]".repeat(refCommonParentXpathElementLength)
1808
- : "")}`, xpaths2Els, refExpectElement[refExpectElement.length - 1], refExpectElement, docmt, relation, isIndex, multiElementReferenceMode);
1809
- if (traverseXpath) {
1810
- return traverseXpath;
1811
- }
1812
- }
1813
- else {
1814
- finalExpectedElementXpath = `//${step4 +
1815
- (refCommonParentXpathElementLength
1816
- ? "]".repeat(refCommonParentXpathElementLength)
1817
- : "")}/${relation}::${replaceActualAttributes(xpath2, refExpectElement[refExpectElement.length - 1])}`;
1818
- let rel_count = getCountOfXPath(finalExpectedElementXpath, refExpectElement[refExpectElement.length - 1], docmt);
1819
- if (rel_count === 1) {
1820
- return [
1821
- {
1822
- key: `dynamic ${relation}`,
1823
- value: replaceTempAttributes(finalExpectedElementXpath),
1824
- },
1825
- ];
1826
- }
1827
- if (rel_count > 1) {
1828
- if (isIndex) {
1829
- finalExpectedElementXpath = findXpathWithIndex(finalExpectedElementXpath, refExpectElement[refExpectElement.length - 1], docmt, rel_count);
1830
- if (finalExpectedElementXpath) {
1831
- rel_count = getCountOfXPath(finalExpectedElementXpath, refExpectElement[refExpectElement.length - 1], docmt);
1832
- if (rel_count === 1) {
1833
- return [
1834
- {
1835
- key: `dynamic ${relation} ${isIndex ? " index" : ""}`,
1836
- value: replaceTempAttributes(finalExpectedElementXpath),
1837
- },
1838
- ];
1839
- }
1840
- }
1841
- }
1842
- }
1843
- }
1844
- };
1845
- const getDescendantXpath = (refExpectElement, docmt, xpaths1, xpaths2, relation, isIndex = false, multiElementReferenceMode = false) => {
1846
- const refElement = refExpectElement[refExpectElement.length - 2];
1847
- const expElement = refExpectElement[refExpectElement.length - 1];
1848
- const expElementDocmnt = getShadowRoot(expElement) ?? expElement.ownerDocument;
1849
- const refAbsoluteXpath = xpaths1.find((x) => x?.key?.includes("absolute"))?.value ||
1850
- getAbsoluteXPath(refElement, refElement.ownerDocument);
1851
- const refFullXpathElements = [];
1852
- const refFullXpathElementsWithoutNumber = [];
1853
- refAbsoluteXpath.split("/").map((x) => refFullXpathElements.push(x));
1854
- refFullXpathElements.map((x) => refFullXpathElementsWithoutNumber.push(x.replace(/\[([0-9]+)\]/gm, "")));
1855
- const expAbsoluteXpath = xpaths2.find((x) => x?.key?.includes("absolute"))?.value ||
1856
- getAbsoluteXPath(expElement, expElement.ownerDocument);
1857
- const expFullXpathElements = [];
1858
- const expFullXpathElementsWithoutNumber = [];
1859
- expAbsoluteXpath.split("/").map((x) => expFullXpathElements.push(x));
1860
- expFullXpathElements.map((x) => expFullXpathElementsWithoutNumber.push(x.replace(/\[([0-9]+)\]/gm, "")));
1861
- for (var parentElementNumber = 0; parentElementNumber < refFullXpathElements.length; parentElementNumber++) {
1862
- if (refFullXpathElements[parentElementNumber] !=
1863
- expFullXpathElements[parentElementNumber]) {
1864
- break;
1865
- }
1866
- }
1867
- const refCommonParentXpathElements = [];
1868
- for (let i = parentElementNumber - 1; i < refFullXpathElements.length; i++) {
1869
- if (refFullXpathElements[i]) {
1870
- refCommonParentXpathElements.push(refFullXpathElementsWithoutNumber[i]);
1871
- }
1872
- }
1873
- const expCommonParentXpathElements = [];
1874
- for (let j = relation === "descendant" ? parentElementNumber : parentElementNumber - 1; j < expFullXpathElements.length; j++) {
1875
- if (expFullXpathElements[j]) {
1876
- if (expCommonParentXpathElements.length)
1877
- expCommonParentXpathElements.push(expFullXpathElementsWithoutNumber[j]);
1878
- else
1879
- expCommonParentXpathElements.push(expFullXpathElementsWithoutNumber[j].replace(/\[([0-9]+)\]/gm, ""));
1880
- }
1881
- }
1882
- xpathData = xpaths2;
1883
- let nodeXpath2;
1884
- if (refExpectElement[refExpectElement.length - 2].textContent) {
1885
- if (!reWhiteSpace.test(refExpectElement[refExpectElement.length - 2].textContent)) {
1886
- nodeXpath2 = isSvg(refExpectElement[refExpectElement.length - 2])
1887
- ? `*[local-name()='${refExpectElement[refExpectElement.length - 2].tagName}' and ${getTextXpathFunction(refExpectElement[refExpectElement.length - 2])})]`
1888
- : `${refExpectElement[refExpectElement.length - 2].tagName}[${getTextXpathFunction(refExpectElement[refExpectElement.length - 2])}]`;
1889
- }
1890
- else {
1891
- nodeXpath2 = isSvg(refExpectElement[refExpectElement.length - 2])
1892
- ? `*[local-name()='${refExpectElement[refExpectElement.length - 2].tagName}' and .=${escapeCharacters(getTextContent(refExpectElement[refExpectElement.length - 2]))}]`
1893
- : `${refExpectElement[refExpectElement.length - 2].tagName}[.=${escapeCharacters(getTextContent(refExpectElement[refExpectElement.length - 2]))}]`;
1894
- }
1895
- refCommonParentXpathElements[refCommonParentXpathElements.length - 1] =
1896
- nodeXpath2;
1897
- const refCommonParentXpath = refCommonParentXpathElements.join("[");
1898
- const refCommonParentXpathElementLength = refCommonParentXpathElements.length - 1;
1899
- const step4 = refCommonParentXpath;
1900
- for (let i = 0; i < xpathData.length; i++) {
1901
- let xpath2;
1902
- if (xpathData[i].value.startsWith("//")) {
1903
- xpath2 = xpathData[i].value.substring(xpathData[i].value.indexOf("//") + 2);
1904
- }
1905
- else {
1906
- xpath2 = xpathData[i].value; // No need to modify the value
1907
- }
1908
- if (xpath2) {
1909
- return descendantExpression(refExpectElement, xpath2, relation, expElementDocmnt || docmt, isIndex, expCommonParentXpathElements, step4, refCommonParentXpathElementLength, multiElementReferenceMode);
1910
- }
1911
- }
1912
- }
1913
- if (refExpectElement[refExpectElement.length - 2].attributes) {
1914
- for (const attrName of Array.from(refExpectElement[refExpectElement.length - 2]
1915
- .attributes)) {
1916
- if (checkBlockedAttributes(attrName, refExpectElement[refExpectElement.length - 2], false)) {
1917
- let attrValue = attrName.nodeValue;
1918
- if (attrValue) {
1919
- attrValue = attrValue.replace("removePointers", "");
1920
- const elementName = attrName.name;
1921
- nodeXpath2 = isSvg(refExpectElement[refExpectElement.length - 2])
1922
- ? `*[local-name()='${refExpectElement[refExpectElement.length - 2].tagName}' and @${elementName}=${escapeCharacters(attrValue)}]`
1923
- : `${refExpectElement[refExpectElement.length - 2].tagName}[@${elementName}=${escapeCharacters(attrValue)}]`;
1924
- refCommonParentXpathElements[refCommonParentXpathElements.length - 1] = nodeXpath2;
1925
- const refCommonParentXpath = refCommonParentXpathElements.join("[");
1926
- const refCommonParentXpathElementLength = refCommonParentXpathElements.length - 1;
1927
- const step4 = refCommonParentXpath;
1928
- for (let i = 0; i < xpathData.length; i++) {
1929
- let xpath2;
1930
- if (xpathData[i].value.startsWith("//")) {
1931
- xpath2 = xpathData[i].value.substring(xpathData[i].value.indexOf("//") + 2);
1932
- }
1933
- else {
1934
- xpath2 = xpathData[i].value; // No need to modify the value
1935
- }
1936
- return descendantExpression(refExpectElement, xpath2, relation, expElementDocmnt || docmt, isIndex, expCommonParentXpathElements, step4, refCommonParentXpathElementLength, multiElementReferenceMode);
1937
- }
1938
- }
1939
- }
1940
- }
1941
- for (const attrName of Array.from(refExpectElement[refExpectElement.length - 2]
1942
- .attributes)) {
1943
- if (checkBlockedAttributes(attrName, refExpectElement[refExpectElement.length - 2], false)) {
1944
- let attrValue = attrName.nodeValue;
1945
- if (attrValue) {
1946
- attrValue = attrValue.replace("removePointers", "");
1947
- const combinationXpath = getCombinationXpath(attrName, refExpectElement[refExpectElement.length - 2]);
1948
- if (combinationXpath) {
1949
- if (combinationXpath.startsWith("//")) {
1950
- nodeXpath2 = combinationXpath.substring(combinationXpath.indexOf("//") + 2);
1951
- }
1952
- else {
1953
- nodeXpath2 = combinationXpath; // No need to modify the value
1954
- }
1955
- refCommonParentXpathElements[refCommonParentXpathElements.length - 1] = nodeXpath2;
1956
- const refCommonParentXpath = refCommonParentXpathElements.join("[");
1957
- const refCommonParentXpathElementLength = refCommonParentXpathElements.length - 1;
1958
- const step4 = refCommonParentXpath;
1959
- for (let i = 0; i < xpathData.length; i++) {
1960
- let xpath2;
1961
- if (xpathData[i].value.startsWith("//")) {
1962
- xpath2 = xpathData[i].value.substring(xpathData[i].value.indexOf("//") + 2);
1963
- }
1964
- else {
1965
- xpath2 = xpathData[i].value; // No need to modify the value
1966
- }
1967
- return descendantExpression(refExpectElement, xpath2, relation, expElementDocmnt || docmt, isIndex, expCommonParentXpathElements, step4, refCommonParentXpathElementLength, multiElementReferenceMode);
1968
- }
1969
- }
1970
- }
1971
- }
1972
- }
1973
- }
1974
- const refCommonParentXpath = refCommonParentXpathElements.join("[");
1975
- const refCommonParentXpathElementLength = refCommonParentXpathElements.length - 1;
1976
- const step4 = refCommonParentXpath;
1977
- const traverseXpath = getTraverseXpathExpression(`${step4 +
1978
- (refCommonParentXpathElementLength
1979
- ? "]".repeat(refCommonParentXpathElementLength)
1980
- : "")}`, expCommonParentXpathElements, refExpectElement[refExpectElement.length - 1], refExpectElement, docmt, relation, isIndex, multiElementReferenceMode);
1981
- if (traverseXpath) {
1982
- return traverseXpath;
1983
- }
1984
- };
1985
- const getXpathRelationExpression = (element1, element2, relation, xpath1, xpath2, isIndex, multiElementReferenceMode) => {
1986
- let xpaths1;
1987
- let xpaths2;
1988
- console.log('getXpathRelationExpression', relation);
1989
- const finalXpaths = [];
1990
- try {
1991
- xpaths1 = xpath1.filter((x) => !x?.key?.includes("absolute"));
1992
- xpaths2 = xpath2.filter((x) => !x?.key?.includes("absolute"));
1993
- for (let i = 0; i < xpaths1.length; i++) {
1994
- for (let j = 0; j < xpaths2.length; j++) {
1995
- let rel_xpath = `//${xpaths1[i].value.indexOf("//") !== 0
1996
- ? replaceActualAttributes(xpaths1[i].value, element1)
1997
- : replaceActualAttributes(xpaths1[i].value.substring(xpaths1[i].value.indexOf("//") + 2), element1)}/${relation}::${xpaths2[j].value.indexOf("//") !== 0
1998
- ? replaceActualAttributes(xpaths2[j].value, element2)
1999
- : replaceActualAttributes(xpaths2[j].value.substring(xpaths2[j].value.indexOf("//") + 2), element2)}`;
2000
- console.log('getXpathRelationExpression', rel_xpath);
2001
- const rel_count = getCountOfXPath(rel_xpath, element2, element2.ownerDocument);
2002
- if (rel_count > 1) {
2003
- if (isIndex) {
2004
- rel_xpath = findXpathWithIndex(rel_xpath, element2, element2.ownerDocument, rel_count);
2005
- if (rel_xpath) {
2006
- finalXpaths.push({
2007
- key: `dynamic ${relation}${isIndex ? " index" : ""}`,
2008
- value: replaceTempAttributes(rel_xpath),
2009
- });
2010
- return finalXpaths;
2011
- }
2012
- }
2013
- else if (rel_count > 1) {
2014
- if (xpathDataWithIndex.length) {
2015
- if (rel_count < xpathDataWithIndex[0].count) {
2016
- xpathDataWithIndex.pop();
2017
- xpathDataWithIndex.push({
2018
- key: `relative xpath by relative child ${isIndex ? "index" : ""}`,
2019
- value: rel_xpath,
2020
- count: rel_count,
2021
- });
2022
- }
2023
- }
2024
- else {
2025
- xpathDataWithIndex.push({
2026
- key: `relative xpath by relative child ${isIndex ? "index" : ""}`,
2027
- value: rel_xpath,
2028
- count: rel_count,
2029
- });
2030
- }
2031
- }
2032
- }
2033
- else if (rel_count === 1) {
2034
- finalXpaths.push({
2035
- key: `dynamic ${relation}`,
2036
- value: replaceTempAttributes(rel_xpath),
2037
- });
2038
- return finalXpaths;
2039
- }
2040
- }
2041
- }
2042
- if (!finalXpaths.length) {
2043
- for (let i = 0; i < xpaths1.length; i++) {
2044
- for (let j = 0; j < xpaths2.length; j++) {
2045
- const tempPath = `${xpaths2[j].value.indexOf("//") !== 0
2046
- ? xpaths2[j].value
2047
- : xpaths2[j].value.substring(xpaths2[j].value.indexOf("//") + 2)}`;
2048
- const xpath2Elements = tempPath.split(/\/(?=(?:[^']*\'[^\']*\')*[^\']*$)/g);
2049
- if (xpath2Elements.length > 1) {
2050
- const traverseXpath = getTraverseXpathExpression(`${xpaths1[i].value.indexOf("//") !== 0
2051
- ? replaceActualAttributes(xpaths1[i].value, element1)
2052
- : replaceActualAttributes(xpaths1[i].value.substring(xpaths1[i].value.indexOf("//") + 2), element1)}`, xpath2Elements, element2, [element1, element2], element2.ownerDocument, relation, isIndex, multiElementReferenceMode);
2053
- console.log('getXpathRelationExpression traverseXpath', traverseXpath);
2054
- if (traverseXpath) {
2055
- finalXpaths.concat(traverseXpath);
2056
- return finalXpaths;
2057
- }
2058
- }
2059
- }
2060
- }
2061
- }
2062
- }
2063
- catch (error) {
2064
- console.log(error);
2065
- }
2066
- return finalXpaths;
2067
- };
2068
- const getReferenceElementXpath = (element) => {
2069
- let xpaths1 = [];
2070
- xpaths1 = parseDOM(element, element.ownerDocument, false, false);
2071
- if (!xpaths1?.length) {
2072
- xpaths1 = parseDOM(element, element.ownerDocument, true, false);
2073
- xpaths1 = xpaths1?.map((x) => x.value.charAt(0) == "(" &&
2074
- findMatchingParenthesis(x.value, 0) + 1 === x.value.lastIndexOf("[")
2075
- ? { key: "", value: removeParenthesis(x.value) }
2076
- : { key: "", value: x.value });
2077
- }
2078
- else {
2079
- let xpaths = parseDOM(element, element.ownerDocument, true, false);
2080
- if (xpaths?.length) {
2081
- xpaths = xpaths?.map((x) => x.value.charAt(0) == "(" &&
2082
- findMatchingParenthesis(x.value, 0) + 1 === x.value.lastIndexOf("[")
2083
- ? { key: "", value: removeParenthesis(x.value) }
2084
- : { key: "", value: x.value });
2085
- xpaths1 = xpaths1.concat(xpaths);
2086
- }
2087
- }
2088
- if (!xpaths1?.length) {
2089
- xpaths1 = [
2090
- {
2091
- key: "",
2092
- value: getRelativeXPath(element, element.ownerDocument, false, false, Array.from(element.attributes)),
2093
- },
2094
- ];
2095
- }
2096
- if (!xpaths1?.length) {
2097
- xpaths1 = [
2098
- {
2099
- key: "",
2100
- value: getRelativeXPath(element, element.ownerDocument, true, false, Array.from(element.attributes)),
2101
- },
2102
- ];
2103
- xpaths1 = xpaths1?.map((x) => x.value.charAt(0) == "(" &&
2104
- findMatchingParenthesis(x.value, 0) + 1 === x.value.lastIndexOf("[")
2105
- ? { key: "", value: removeParenthesis(x.value) }
2106
- : { key: "", value: x.value });
2107
- }
2108
- if (!xpaths1?.length) {
2109
- xpaths1 = getReferenceElementsXpath(element, element.ownerDocument, false);
2110
- }
2111
- else {
2112
- const xpaths = getReferenceElementsXpath(element, element.ownerDocument, false);
2113
- if (xpaths?.length) {
2114
- xpaths1 = xpaths1.concat(xpaths);
2115
- }
2116
- }
2117
- const referenceXpathElement = getAbsoluteXPath(element, element.ownerDocument);
2118
- xpaths1 = xpaths1.filter((x) => x.value !== referenceXpathElement);
2119
- xpaths1.push({
2120
- key: "absolute xpath",
2121
- value: referenceXpathElement.slice(1),
2122
- });
2123
- return xpaths1;
2124
- };
2125
- const getTraverseXpathExpression = (xpathe1, absoluteXpathElements, element2, refExpectElement, docmt, relation, isIndex, multiElementReferenceMode) => {
2126
- let finalExpectedElementXpath;
2127
- if (!multiElementReferenceMode) {
2128
- for (let x = 1; x <= absoluteXpathElements.length; x++) {
2129
- const xpath2 = absoluteXpathElements
2130
- .slice(absoluteXpathElements.length - x, absoluteXpathElements.length)
2131
- .join("/");
2132
- finalExpectedElementXpath = `//${xpathe1}/${relation}::${replaceActualAttributes(xpath2)}`;
2133
- const rel_count = getCountOfXPath(finalExpectedElementXpath, element2, docmt);
2134
- if (rel_count === 1) {
2135
- return [
2136
- {
2137
- key: `dynamic ${relation}`,
2138
- value: replaceTempAttributes(finalExpectedElementXpath),
2139
- },
2140
- ];
2141
- }
2142
- if (rel_count > 1) {
2143
- if (isIndex) {
2144
- finalExpectedElementXpath = findXpathWithIndex(finalExpectedElementXpath, refExpectElement[refExpectElement.length - 1], docmt, rel_count);
2145
- if (finalExpectedElementXpath) {
2146
- return [
2147
- {
2148
- key: `dynamic ${relation}${isIndex ? " index" : ""}`,
2149
- value: replaceTempAttributes(finalExpectedElementXpath),
2150
- },
2151
- ];
2152
- }
2153
- }
2154
- }
2155
- }
2156
- }
2157
- else {
2158
- const xpath2 = absoluteXpathElements.join("/");
2159
- finalExpectedElementXpath = `//${xpathe1}/${relation}::${replaceActualAttributes(xpath2)}`;
2160
- const rel_count = getCountOfXPath(finalExpectedElementXpath, element2, docmt);
2161
- if (rel_count === 1) {
2162
- return [
2163
- {
2164
- key: `dynamic ${relation}`,
2165
- value: replaceTempAttributes(finalExpectedElementXpath),
2166
- },
2167
- ];
2168
- }
2169
- if (rel_count > 1) {
2170
- if (isIndex) {
2171
- finalExpectedElementXpath = findXpathWithIndex(finalExpectedElementXpath, refExpectElement[refExpectElement.length - 1], docmt, rel_count);
2172
- if (finalExpectedElementXpath) {
2173
- return [
2174
- {
2175
- key: `dynamic ${relation}${isIndex ? " index" : ""}`,
2176
- value: replaceTempAttributes(finalExpectedElementXpath),
2177
- },
2178
- ];
2179
- }
2180
- }
2181
- }
2182
- }
2183
- };
2184
- const referenceXpath = {
2185
- findRelativeXpath,
2186
- getDescendantXpath,
2187
- getXpathRelationExpression,
2188
- getTraverseXpathExpression,
2189
- getReferenceElementXpath,
2190
- };
2191
-
2192
- const getElementFromShadowRoot = (el, selector) => {
2193
- // const shadowRoot = (element as HTMLElement).shadowRoot;
2194
- // if (shadowRoot && !selector.includes("dynamic")) {
2195
- // return shadowRoot.querySelector(selector);
2196
- // }
2197
- const elements = Array.from(el.querySelectorAll('*'));
2198
- try {
2199
- for (let i = 0; i < elements.length; i++) {
2200
- if (elements[i].shadowRoot) {
2201
- const { shadowRoot } = elements[i];
2202
- if (shadowRoot) {
2203
- getElementFromShadowRoot(shadowRoot, selector);
2204
- if (shadowRoot && !selector.includes("dynamic")) {
2205
- return shadowRoot.querySelector(selector);
2206
- }
2207
- }
2208
- }
2209
- }
2210
- }
2211
- catch (error) {
2212
- console.log(error);
2213
- }
2214
- return null;
2215
- };
2216
- const getId = (element) => {
2217
- return element?.id || null;
2218
- };
2219
- const getClassName = (element) => {
2220
- return element.className || null;
2221
- };
2222
- const getVisibleText = (element) => {
2223
- return element.textContent?.trim() || null;
2224
- };
2225
- const getName = (element) => {
2226
- const elementEl = element;
2227
- if (elementEl.hasAttribute("name")) {
2228
- const attrValue = elementEl.getAttribute("name");
2229
- const name = `${attrValue}`;
2230
- return name || null;
2231
- }
2232
- return null;
2233
- };
2234
- const relations = [
2235
- "/preceding-sibling",
2236
- "/following-sibling",
2237
- "/parent",
2238
- "/descendant",
2239
- "/ancestor",
2240
- "/self",
2241
- "/ancestor-or-self",
2242
- "/child",
2243
- "/preceding",
2244
- "/following",
2245
- ];
2246
- function getElementFromXPath(docmt, xpath) {
2247
- const window = docmt.defaultView;
2248
- if (!window)
2249
- return null;
2250
- const xpathEvaluator = new window.XPathEvaluator();
2251
- const xpathResult = xpathEvaluator.evaluate(xpath, docmt, null, window.XPathResult.FIRST_ORDERED_NODE_TYPE, null);
2252
- return xpathResult.singleNodeValue;
2253
- }
2254
- function checkReferenceElementIsValid(locator, relation, docmt) {
2255
- if (locator.includes(relation)) {
2256
- const locatotSplitArray = locator.split(relation);
2257
- const sourceLoc = locatotSplitArray[0].trim();
2258
- const window = docmt.defaultView;
2259
- if (!window)
2260
- return null;
2261
- if (!locator.includes("dynamic")) {
2262
- const xpathEvaluator = new window.XPathEvaluator();
2263
- const xpathResult = xpathEvaluator.evaluate(sourceLoc, docmt, null, window.XPathResult.FIRST_ORDERED_NODE_TYPE, null);
2264
- const sourceElement = xpathResult.singleNodeValue;
2265
- if (sourceElement) {
2266
- const xpathResultComplete = xpathEvaluator.evaluate(locator, docmt, null, window.XPathResult.FIRST_ORDERED_NODE_TYPE, null);
2267
- const completeElement = xpathResultComplete.singleNodeValue;
2268
- let relativeXpath;
2269
- if (completeElement) {
2270
- relativeXpath = locator;
2271
- return relativeXpath;
2272
- }
2273
- else {
2274
- console.error("Complete Locator is Invalid:", locator);
2275
- relativeXpath = locator;
2276
- return relativeXpath;
2277
- }
2278
- }
2279
- else {
2280
- console.error("Source Locator Not Found:", sourceLoc);
2281
- }
2282
- }
2283
- }
2284
- return null;
2285
- }
2286
- const getElementsFromHTML = (record, docmt) => {
2287
- const elementsToRemove = docmt.querySelectorAll("script, style, link[rel='stylesheet'], meta, noscript, embed, object, param, source, svg");
2288
- if (elementsToRemove) {
2289
- elementsToRemove.forEach((tag) => {
2290
- tag.remove();
2291
- });
2292
- }
2293
- const finalLocatorsSet = new Set();
2294
- let finalLocators = [];
2295
- function createLocator(base, overrides = {}) {
2296
- const newLocator = {
2297
- name: overrides.name ?? base?.name,
2298
- type: overrides.type ?? base?.type,
2299
- value: overrides.value ?? base?.value,
2300
- reference: overrides.reference ?? base?.reference,
2301
- status: overrides.status ?? base?.status,
2302
- isRecorded: overrides.isRecorded ?? base?.isRecorded,
2303
- };
2304
- if (overrides.hasOwnProperty("isSelfHealed")) {
2305
- newLocator.isSelfHealed = overrides.isSelfHealed;
2306
- }
2307
- else if (base?.hasOwnProperty("isSelfHealed")) {
2308
- newLocator.isSelfHealed = base.isSelfHealed;
2309
- }
2310
- pushUniqueLocator(newLocator);
2311
- }
2312
- function pushUniqueLocator(obj) {
2313
- const key = `${obj.name}:${obj.value}`;
2314
- if (!finalLocatorsSet.has(key)) {
2315
- finalLocatorsSet.add(key);
2316
- finalLocators.push(obj);
2317
- }
2318
- }
2319
- /** Locator Value Cleaner (Handles Special Scenarios) **/
2320
- const cleanLocatorValue = (val, type, isRecorded) => {
2321
- if (!val)
2322
- return null;
2323
- let cleaned = val.trim();
2324
- // Return null for empty or literal "null"
2325
- if (!cleaned || cleaned.toLowerCase() === "null")
2326
- return null;
2327
- // Unescape any escaped quotes
2328
- cleaned = cleaned.replace(/\\"/g, '"').replace(/\\'/g, "'");
2329
- // Remove surrounding single or double quotes
2330
- cleaned = cleaned.replace(/^['"](.+?)['"]$/, "$1");
2331
- // Replace double single quotes with a single quote inside XPath
2332
- cleaned = cleaned.replace(/''/g, "'");
2333
- // Normalize double quotes in XPath attribute selectors [@id="" -> [@id='']
2334
- cleaned = cleaned.replace(/\[@(id|name)=['"]{2}(.+?)['"]{2}\]/g, "[@$1='$2']");
2335
- // For DOM selectors (id or name), remove ALL quotes
2336
- if (type === "id" || type === "name") {
2337
- cleaned = cleaned.replace(/['"]/g, "").trim();
2338
- }
2339
- if (type === "xpath" && isRecorded === "Y" && !val.startsWith("//"))
2340
- return null;
2341
- // Final check for empty strings
2342
- if (!cleaned || /^['"]{2}$/.test(cleaned))
2343
- return null;
2344
- return cleaned;
2345
- };
2346
- locators: for (const locator of record.locators) {
2347
- try {
2348
- const isRecorded = String(locator.isRecorded || "");
2349
- const recordedNLocators = record.locators.filter((l) => l.isRecorded === "N");
2350
- if (recordedNLocators.length > 0) {
2351
- for (const locator of recordedNLocators) {
2352
- createLocator(locator);
2353
- }
2354
- }
2355
- const isDynamic = String(locator.value || locator.type || "");
2356
- if (isDynamic.includes("dynamic") ||
2357
- isDynamic.match("dynamic") ||
2358
- isDynamic.includes("{") ||
2359
- isDynamic.includes("}")) {
2360
- createLocator(locator);
2361
- continue;
2362
- }
2363
- if (record.isShared.includes("Y")) {
2364
- break locators;
2365
- }
2366
- try {
2367
- let targetElement = null;
2368
- if (locator.value.startsWith("iframe")) {
2369
- const iframe = docmt.querySelector(locator.value);
2370
- if (iframe) {
2371
- const iframeDocument = iframe.contentDocument || iframe.contentWindow?.document;
2372
- if (iframeDocument) {
2373
- targetElement = iframeDocument.querySelector(locator.value.slice(6));
2374
- }
2375
- }
2376
- }
2377
- else {
2378
- const selectors = locator.value.split(">>>"); // Custom delimiter for shadow DOM
2379
- for (const selector of selectors) {
2380
- if (docmt) {
2381
- const trimmedSelector = selector.trim();
2382
- if (locator.name.includes("id") ||
2383
- trimmedSelector.startsWith("#")) {
2384
- targetElement = docmt.querySelector("#" + trimmedSelector);
2385
- }
2386
- else if (locator.name.includes("className") ||
2387
- trimmedSelector.startsWith(".")) {
2388
- targetElement = docmt.querySelector("." + trimmedSelector);
2389
- }
2390
- else if ((locator.name.includes("xpath") ||
2391
- trimmedSelector.startsWith("//")) &&
2392
- !locator.type.match("dynamic")) {
2393
- const normalizedXPath = normalizeXPath(trimmedSelector);
2394
- targetElement = getElementFromXPath(docmt, normalizedXPath);
2395
- if (targetElement) {
2396
- createLocator(locator, {
2397
- value: trimmedSelector,
2398
- isRecorded: String(locator.isRecorded).includes("N")
2399
- ? "N"
2400
- : "Y",
2401
- });
2402
- }
2403
- }
2404
- else {
2405
- targetElement = docmt.querySelector(trimmedSelector);
2406
- if (!targetElement) {
2407
- targetElement = getElementFromShadowRoot(docmt.body, trimmedSelector);
2408
- }
2409
- }
2410
- }
2411
- else {
2412
- console.error("Element not found at:", selector);
2413
- break;
2414
- }
2415
- }
2416
- }
2417
- const locatorExists = (name, value) => {
2418
- const key = `${name}:${value}`;
2419
- return finalLocatorsSet.has(key);
2420
- };
2421
- if (targetElement) {
2422
- const idValue = getId(targetElement);
2423
- if (idValue && !locatorExists("id", idValue)) {
2424
- record.locators.forEach((loc) => {
2425
- createLocator(loc, {
2426
- name: "id",
2427
- value: idValue,
2428
- isRecorded: loc.value === idValue && loc.name === "id"
2429
- ? loc.isRecorded
2430
- : "Y",
2431
- isSelfHealed: loc.value === idValue && loc.name === "id"
2432
- ? loc.isSelfHealed
2433
- : "Y",
2434
- });
2435
- });
2436
- }
2437
- const textValue = getVisibleText(targetElement);
2438
- if (textValue) {
2439
- record.locators.forEach((loc) => {
2440
- createLocator(loc, {
2441
- name: "linkText",
2442
- type: "static",
2443
- value: textValue,
2444
- isRecorded: loc.value === textValue ? loc.isRecorded : "Y",
2445
- isSelfHealed: loc.value === textValue ? loc.isSelfHealed : "Y",
2446
- });
2447
- });
2448
- }
2449
- const nameLocator = getName(targetElement);
2450
- if (nameLocator && !locatorExists("name", nameLocator)) {
2451
- record.locators.forEach((loc) => {
2452
- createLocator(loc, {
2453
- name: "name",
2454
- type: "static",
2455
- value: nameLocator,
2456
- isRecorded: loc.value === nameLocator && loc.name === "name"
2457
- ? loc.isRecorded
2458
- : "Y",
2459
- isSelfHealed: loc.value === nameLocator && loc.name === "name"
2460
- ? loc.isSelfHealed
2461
- : "Y",
2462
- });
2463
- });
2464
- }
2465
- const classValue = getClassName(targetElement);
2466
- if (classValue &&
2467
- classValue.trim() !== "" &&
2468
- !locatorExists("className", classValue)) {
2469
- record.locators.forEach((loc) => {
2470
- createLocator(loc, {
2471
- name: "className",
2472
- value: classValue,
2473
- isRecorded: loc.value === classValue && loc.name === "className"
2474
- ? loc.isRecorded
2475
- : "Y",
2476
- isSelfHealed: loc.value === classValue && loc.name === "className"
2477
- ? loc.isSelfHealed
2478
- : "Y",
2479
- });
2480
- });
2481
- }
2482
- const xpathResults = parseDOM(targetElement, docmt, false, true);
2483
- xpathResults.forEach((result) => {
2484
- const fnValue = result.value;
2485
- if (fnValue && !locatorExists(result.key.replace('xpath by', '').trim(), fnValue)) {
2486
- record.locators.forEach((loc) => {
2487
- createLocator(loc, {
2488
- name: 'xpath',
2489
- value: fnValue,
2490
- isRecorded: loc.value === fnValue ? loc.isRecorded : 'Y',
2491
- isSelfHealed: loc.value === fnValue ? loc.isSelfHealed : 'Y',
2492
- });
2493
- });
2494
- }
2495
- });
2496
- for (const locator of record.locators) {
2497
- try {
2498
- for (const loc of record.locators) {
2499
- if (!loc.value)
2500
- continue;
2501
- for (const relation of relations) {
2502
- if (loc.value.includes(relation)) {
2503
- const relativeXpath = checkReferenceElementIsValid(loc.value, relation, docmt);
2504
- if (relativeXpath) {
2505
- createLocator(loc, {
2506
- name: "xpath",
2507
- value: relativeXpath,
2508
- isRecorded: locator.isRecorded !== "" &&
2509
- locator.isRecorded !== null
2510
- ? locator.isRecorded
2511
- : "Y",
2512
- });
2513
- break;
2514
- }
2515
- }
2516
- }
2517
- }
2518
- }
2519
- catch (error) {
2520
- console.error("Error processing locator:", locator, error);
2521
- }
2522
- }
2523
- const finalAutoHealedLocators = finalLocators.map((obj) => ({
2524
- ...obj,
2525
- value: cleanLocatorValue(obj.value, obj.name, obj.isRecorded),
2526
- }));
2527
- const finalUniqueAutoHealedLocators = finalAutoHealedLocators.reduce((unique, locator) => {
2528
- if (locator.value &&
2529
- !unique.some((l) => l.value === locator.value)) {
2530
- unique.push(locator);
2531
- }
2532
- return unique;
2533
- }, []);
2534
- const jsonResult = [
2535
- {
2536
- name: `${record.name}`,
2537
- desc: `${record.desc}`,
2538
- type: `${record.type}`,
2539
- locators: finalUniqueAutoHealedLocators.filter((locator) => locator?.value != null && locator.value !== ""),
2540
- isShared: `${record.isShared}`,
2541
- projectId: `${record.projectId}`,
2542
- projectType: `${record.projectType}`,
2543
- isRecorded: `${record.isRecorded}`,
2544
- folder: `${record.folder}`,
2545
- parentId: `${record.parentId}`,
2546
- parentName: `${record.parentName}`,
2547
- platform: `${record.platform}`,
2548
- licenseId: `${record.licenseId}`,
2549
- licenseType: `${record.licenseType}`,
2550
- userId: `${record.userId}`,
2551
- },
2552
- ];
2553
- return jsonResult;
2554
- }
2555
- }
2556
- catch (error) {
2557
- console.error("Error processing locator:", locator, error);
2558
- continue;
2559
- }
2560
- }
2561
- catch (error) {
2562
- console.error("Error processing locator:", locator, error);
2563
- continue;
2564
- }
2565
- }
2566
- return null;
2567
- };
2568
-
2569
- let modifiedElementAttributes = [];
2570
- const parseCssSelectors = (el, docmt) => {
2571
- let cssSelector = [];
2572
- try {
2573
- let idCssSelector = getIdCssPath(el, docmt);
2574
- if (idCssSelector &&
2575
- idCssSelector.includes('#') &&
2576
- docmt.querySelectorAll(idCssSelector)?.length === 1 &&
2577
- !(idCssSelector.includes('body') ||
2578
- idCssSelector.includes('head') ||
2579
- idCssSelector.includes('html'))) {
2580
- cssSelector.push({ key: 'cssSelector by id', value: idCssSelector });
2581
- }
2582
- else {
2583
- idCssSelector = '';
2584
- }
2585
- let nameCssSelector = getNameCssPath(el, docmt);
2586
- if (nameCssSelector &&
2587
- nameCssSelector !== idCssSelector &&
2588
- nameCssSelector.includes('name') &&
2589
- docmt.querySelectorAll(nameCssSelector)?.length === 1 &&
2590
- !(nameCssSelector.includes('body') ||
2591
- nameCssSelector.includes('head') ||
2592
- nameCssSelector.includes('html'))) {
2593
- cssSelector.push({ key: 'cssSelector by name', value: nameCssSelector });
2594
- }
2595
- else {
2596
- nameCssSelector = '';
2597
- }
2598
- let classCssSelector = getClassCssPath(el, docmt);
2599
- if (classCssSelector &&
2600
- classCssSelector !== idCssSelector &&
2601
- nameCssSelector !== classCssSelector &&
2602
- classCssSelector.includes('.') &&
2603
- docmt.querySelectorAll(classCssSelector)?.length === 1 &&
2604
- !(classCssSelector.includes('body') ||
2605
- classCssSelector.includes('head') ||
2606
- classCssSelector.includes('html'))) {
2607
- cssSelector.push({
2608
- key: 'cssSelector by class',
2609
- value: classCssSelector,
2610
- });
2611
- }
2612
- else {
2613
- classCssSelector = '';
2614
- }
2615
- }
2616
- catch (error) {
2617
- console.log(error);
2618
- }
2619
- if (!cssSelector.length) {
2620
- let abSelector = getAbsoluteCssPath(el, docmt);
2621
- if (abSelector &&
2622
- docmt.querySelectorAll(abSelector)?.length === 1 &&
2623
- !(abSelector.includes('body') ||
2624
- abSelector.includes('head') ||
2625
- abSelector.includes('html'))) {
2626
- cssSelector.push({
2627
- key: 'Absolute cssSelector',
2628
- value: abSelector,
2629
- });
2630
- }
2631
- else {
2632
- abSelector = '';
2633
- }
2634
- }
2635
- return cssSelector;
2636
- };
2637
- const getIdCssPath = (el, docmt) => {
2638
- const tagName = el.tagName.toLowerCase();
2639
- if (docmt?.defaultView?.Element &&
2640
- !(el instanceof docmt?.defaultView?.Element))
2641
- return;
2642
- if (tagName.includes('style') || tagName.includes('script'))
2643
- return;
2644
- const path = [];
2645
- while (el.nodeType === Node.ELEMENT_NODE) {
2646
- let selector = el.nodeName?.toLowerCase();
2647
- if (el.id && !isNumberExist(el.id)) {
2648
- selector += `#${el.id}`;
2649
- path.unshift(selector);
2650
- break;
2651
- }
2652
- else {
2653
- let sib = el;
2654
- let nth = 1;
2655
- if (sib.previousElementSibling) {
2656
- while ((sib = sib.previousElementSibling)) {
2657
- if (sib.nodeName?.toLowerCase() === selector)
2658
- nth++;
2659
- }
2660
- }
2661
- if (nth !== 1) {
2662
- selector += `:nth-of-type(${nth})`;
2663
- }
2664
- if (nth === 1 && sib?.parentElement?.childElementCount > 1) {
2665
- selector += `:nth-child(${nth})`;
2666
- }
2667
- }
2668
- path.unshift(selector);
2669
- el = el.parentElement;
2670
- }
2671
- return path.join(' > ');
2672
- };
2673
- const getNameCssPath = (el, docmt) => {
2674
- const tagName = el.tagName.toLowerCase();
2675
- if (docmt?.defaultView?.Element &&
2676
- !(el instanceof docmt?.defaultView?.Element))
2677
- return;
2678
- if (tagName.includes('style') || tagName.includes('script'))
2679
- return;
2680
- const path = [];
2681
- while (el.nodeType === Node.ELEMENT_NODE) {
2682
- let selector = el.nodeName?.toLowerCase();
2683
- let name = el.getAttribute('name');
2684
- if (name && !isNumberExist(name)) {
2685
- selector += `[name=${name}]`;
2686
- path.unshift(selector);
2687
- break;
2688
- }
2689
- else {
2690
- let sib = el;
2691
- let nth = 1;
2692
- if (sib.previousElementSibling) {
2693
- while ((sib = sib.previousElementSibling)) {
2694
- if (sib.nodeName?.toLowerCase() === selector)
2695
- nth++;
2696
- }
2697
- }
2698
- if (nth !== 1) {
2699
- selector += `:nth-of-type(${nth})`;
2700
- }
2701
- if (nth === 1 && sib?.parentElement?.childElementCount > 1) {
2702
- selector += `:nth-child(${nth})`;
2703
- }
2704
- }
2705
- path.unshift(selector);
2706
- el = el.parentElement;
2707
- }
2708
- return path.join(' > ');
2709
- };
2710
- const getClassCssPath = (el, docmt) => {
2711
- const tagName = el.tagName.toLowerCase();
2712
- if (docmt?.defaultView?.Element &&
2713
- !(el instanceof docmt?.defaultView?.Element))
2714
- return;
2715
- if (tagName.includes('style') || tagName.includes('script'))
2716
- return;
2717
- const path = [];
2718
- while (el.nodeType === Node.ELEMENT_NODE) {
2719
- let selector = el.nodeName?.toLowerCase();
2720
- if (typeof el.className === 'string' &&
2721
- el.className &&
2722
- !isNumberExist(el.className) &&
2723
- !modifiedElementAttributes?.find((x) => x.element === el && x.attributeName === 'class')) {
2724
- el.classList.remove('marked-element-temp');
2725
- el.classList.remove('removePointers');
2726
- if (el.className) {
2727
- selector += `.${el.className.trim().replace(/\s+/g, '.')}`;
2728
- path.unshift(selector);
2729
- break;
2730
- }
2731
- }
2732
- else {
2733
- let sib = el;
2734
- let nth = 1;
2735
- if (sib.previousElementSibling) {
2736
- while ((sib = sib.previousElementSibling)) {
2737
- if (sib.nodeName?.toLowerCase() === selector)
2738
- nth++;
2739
- }
2740
- }
2741
- if (nth !== 1) {
2742
- selector += `:nth-of-type(${nth})`;
2743
- }
2744
- if (nth === 1 && sib?.parentElement?.childElementCount > 1) {
2745
- selector += `:nth-child(${nth})`;
2746
- }
2747
- }
2748
- path.unshift(selector);
2749
- el = el.parentElement;
2750
- }
2751
- return path.join(' > ');
2752
- };
2753
- const getAbsoluteCssPath = (el, docmt) => {
2754
- const tagName = el.tagName.toLowerCase();
2755
- if (docmt?.defaultView?.Element &&
2756
- !(el instanceof docmt?.defaultView?.Element))
2757
- return;
2758
- if (tagName.includes('style') || tagName.includes('script'))
2759
- return;
2760
- const path = [];
2761
- while (el.nodeType === Node.ELEMENT_NODE) {
2762
- let selector = el.nodeName?.toLowerCase();
2763
- if (tagName.includes('body') ||
2764
- tagName.includes('head') ||
2765
- tagName.includes('html')) {
2766
- selector += tagName;
2767
- path.unshift(selector);
2768
- break;
2769
- }
2770
- else {
2771
- let sib = el;
2772
- let nth = 1;
2773
- if (sib.previousElementSibling) {
2774
- while ((sib = sib.previousElementSibling)) {
2775
- if (sib.nodeName?.toLowerCase() === selector)
2776
- nth++;
2777
- }
2778
- }
2779
- if (nth !== 1) {
2780
- selector += `:nth-of-type(${nth})`;
2781
- }
2782
- if (nth === 1 && sib?.parentElement?.childElementCount > 1) {
2783
- selector += `:nth-child(${nth})`;
2784
- }
2785
- }
2786
- path.unshift(selector);
2787
- el = el.parentElement;
2788
- }
2789
- return path.join(' > ');
2790
- };
2791
- const cssSelectors = {
2792
- parseCssSelectors,
2793
- getIdCssPath,
2794
- getNameCssPath,
2795
- getClassCssPath,
2796
- getAbsoluteCssPath
2797
- };
2798
-
2799
- const createXPathAPI = () => ({
2800
- xpath,
2801
- referenceXpaths: referenceXpath,
2802
- xpathUtils,
2803
- getElementsFromHTML,
2804
- cssSelectors
2805
- });
2806
-
2807
- exports.createXPathAPI = createXPathAPI;
2808
- exports.default = createXPathAPI;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});const e=/^[\S]+( [\S]+)*$/gi;const t={};let n,l=new Map,a=[];const r=e=>/\d/.test(e),o=e=>{const t=e?.textContent;return t},s=e=>e?.childNodes[0]?.nodeValue||"",i=(e,n,l,a=!1)=>{try{let r;if(void 0!==t[e])r=t[e];else{r=(9===l.nodeType?l:l.ownerDocument).evaluate(`count(${e})`,l,null,XPathResult.NUMBER_TYPE,null).numberValue,t[e]=r}if(a&&Array.isArray(n)){if(r>1){const t=v(e,l,!0);let a,r=0;if(t instanceof XPathResult)for(;(a=t?.iterateNext())&&(!n.includes(a)||(r+=1,2!==r)););if(2!==r)return 0}}else if(1===r){return v(e,l)===n?r:0}return r}catch(t){return console.error(`Error evaluating XPath: ${e}`,t),0}},c=e=>{if(e){if(-1!==e.indexOf('"'))return`'${e}'`;if(-1!==e.indexOf("'"))return`"${e}"`}return`'${e}'`},u=e=>{const t=e.split("");let n=t.length;const l=[];for(;"["!==t[n-2];)l.push(t[n-2]),n--;l.reverse();let a="";for(let e=0;e<l.length;e++)a+=l[e];const r=a.length+2;let o=e.slice(0,e.length-r);return o=o.startsWith("(")&&o.endsWith(")")?o.slice(1,-1):e,o},m=(e,t,n,l)=>{try{const a=9===n.nodeType?n:n.ownerDocument;let r=0;if(l){if(1===i(`${e}[${l}]`,t,n))return`${e}[${l}]`;if(1===i(`(${e})[${l}]`,t,n))return`(${e})[${l}]`}const o=a.evaluate(e,n,null,XPathResult.ANY_TYPE,null);let s;for(;s=o.iterateNext();)if(r++,s.isSameNode(t))return 1===i(`${e}[${r}]`,t,n)?`${e}[${r}]`:1===i(`(${e})[${r}]`,t,n)?`(${e})[${r}]`:void 0}catch(e){console.log(e)}},h=e=>(e=(e=(e=>(e&&=e.split("\n")[0].length>0?e.split("\n")[0]:e.split("\n")[1],e))(e)).split(/[^\u0000-\u00ff]/).reduce((e,t)=>e.length>t.length?e:t,"").trim()).split("/")[0].trim(),f=e=>e?e.replace(/\s\s+/g," ").trim():e,d=e=>{if(!e||!e?.getRootNode)return null;const t=e.getRootNode();return t&&t?.host?t:null},g=(e,t,n)=>!(!e?.value||"boolean"==typeof e?.value||["true","false","on","off","flntooltip"].some(t=>t===e.value)||["type","style","locator-data-tooltip","value"].some(t=>t===e.name)||a?.find(n=>n.doc===t.ownerDocument&&n.element===t&&n.attributeName===e.name)||0===e?.name?.indexOf("on")&&e?.name?.length>3||"function"==typeof e.value||n&&r(e.value)),p=e=>e instanceof SVGElement,$=e=>e?e.replace(/\b[a-zA-Z_]*disabled\b/gi,"disabled"):e,v=(e,t,n=!1)=>{let l=t;t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&(l=t.host??t);const a=l.nodeType===Node.DOCUMENT_NODE?l:l.ownerDocument;return n?a.evaluate(e,l,null,XPathResult.ANY_TYPE,null):a.evaluate(e,l,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue},y=(t,n,l,a,o,s)=>{if(a){const{tagName:u}=t;let m,h="";const d=[];let g;if(a&&(!s||!r(a))&&(g=e.test(a)?`//${u}[${l}=${c(a)}]`:((e,t,n)=>t?`//*[local-name()='${n}' and ${e}]`:`//${n}[${e}]`)(`normalize-space(${l})=${c(f(a)).trim()}`,p(t),t.tagName.toLowerCase()),m=i(g,t,n),1===m&&!o))return g;if(a&&s){const r=a.split(" ");if(r?.length)if(1===r.length){const s=[...new Set(r[0].match(/([^0-9]+)/g))];if(s?.length>=1&&s[0]&&f(s[0].trim())?.length>1&&a.startsWith(s[0])&&(h=e.test(s[0])?`starts-with(${l},${c(s[0]).trim()})`:`starts-with(${l},${c(f(s[0])).trim()})`),s?.length>1&&s[s.length-1]&&f(s[s.length-1].trim())?.length>1&&a.endsWith(s[s.length-1])&&(h=e.test(s[s.length-1])?`ends-with(${l},${c(s[s.length-1]).trim()})`:`ends-with(${l},${c(f(s[s.length-1])).trim()})`),h?.length&&(g=p(t)?`//*[local-name()='${u}' and ${h}]`:`//${u}[${h}]`,m=i(g,t,n),1===m&&!o))return g}else{const s=r.length%2==0?r.length/2:r.length%2,d=r.slice(0,s).join(" ");let $=[...new Set(d.match(/([^0-9]+)/g))];if($?.length&&$[0]&&f($[0].trim())?.length&&a.startsWith($[0])&&(h=e.test($[0])?`starts-with(${l},${c($[0]).trim()})`:`starts-with(${l},${c(f($[0])).trim()})`),h?.length&&(g=p(t)?`//*[local-name()='${u}' and ${h}]`:`//${u}[${h}]`,m=i(g,t,n),1===m&&!o))return g;const v=r.slice(s,r.length-1).join(" ");if($=[...new Set(v.match(/([^0-9]+)/g))],$?.length&&$[0]&&f($[0].trim())?.length>3&&a.endsWith($[0])&&(h=e.test($[0])?`ends-with(${l},${c($[0]).trim()})`:`ends-with(${l},${c(f($[0])).trim()})`),h?.length&&(g=p(t)?`//*[local-name()='${u}' and ${h}]`:`//${u}[${h}]`,m=i(g,t,n),1===m&&!o))return g}}if(a&&s&&r(a)){const r=[...new Set(a.match(/([^0-9]+)/g))];if(r?.length)for(let t=0;t<r?.length;t++)r[t]&&f(r[t].trim())?.length>1&&(e.test(r[t])?d.push(`contains(${l},${c(r[t].trim()).trim()})`):d.push(`contains(${l},${c(f(r[t])).trim()})`));if(d?.length&&(g=p(t)?`//*[local-name()='${u}' and ${d.join(" and ")}]`:`//${u}[${d.join(" and ")}]`,m=i(g,t,n),1===m&&!o))return g}if(g=p(t)?`//*[local-name()='${u}' and text()]`:`//${u}[text()]`,m=i(g,t,n),1===m&&!o)return g}},b=(e,t)=>{try{if(!e)return"";let n=p(e)?`/*[local-name()='${e.tagName}']`:`/${e.tagName}`;if(e.parentElement){const t=Array.prototype.slice.call(e.parentElement.children,0).filter(t=>t.tagName===e.tagName);if(t.length>1){n+=`[${t.indexOf(e)+1}]`}}else if(e instanceof HTMLElement&&e.offsetParent){const t=Array.prototype.slice.call(e.offsetParent.children,0).filter(t=>t.tagName===e.tagName);if(t.length>1){n+=`[${t.indexOf(e)+1}]`}}return b(e?.parentElement,t)+n}catch(e){return console.log("xpath",e),""}},N=(e,t,n,a=!1,o)=>{try{if(l.has(e))return l.get(e);const u=[];let h=e;for(;h;){let l="",d=!1,v=e===h?o??h.attributes:h.attributes;for(const e of Array.from(v))if(g(e,h,a)){let a=e.nodeValue;a=a?.replace("removePointers","")??"";const r=e.name;l=R(h,r,a);let o=0;if(l&&(o=i(l,h,t),1===o)){u.unshift($(l)),d=!0;break}if(o>1&&n&&(l=m(l,h,t,o),l)){u.unshift($(l)),d=!0;break}}if(h.textContent)if(!a||a&&!r(h.textContent)){l=new RegExp(/^[\S]+( [\S]+)*$/gi).test(h.textContent)?p(h)?`//*[local-name()='${h.tagName}' and .=${c(s(h))}]`:`//${h.tagName||"*"}[.=${c(s(h))}]`:p(h)?`//*[local-name()='${h.tagName}' and normalize-space(.)=${c(s(h))}]`:`//${h.tagName||"*"}[normalize-space(.)=${c(s(h))}]`;let e=i(l,h,t);if(1===e)return l;if(e>1&&n)return l=m(l,h,t,e),l}else{let e=[];const a=[...new Set(s(h).match(/([^0-9]+)/g))];let r=new RegExp(/^[\S]+( [\S]+)*$/gi);if(a?.length)for(let t=0;t<a?.length;t++)a[t]&&f(a[t].trim())&&(r.test(a[t])?e.push(`contains(.,${c(a[t].trim()).trim()})`):e.push(`contains(.,${c(f(a[t])).trim()})`));if(e?.length){l=p(h)?`//*[local-name()='${h.tagName}' and ${e.join(" and ")}]`:`//${h.tagName||"*"}[${e.join(" and ")}]`;let a=i(l,h,t);if(1===a)return l;if(a>1&&n)return l=m(l,h,t,a),l}}if(d)break;{let e=p(h)?`/*[local-name()='${h.tagName}']`:`/${h.tagName}`;if(h.parentElement){const t=Array.from(h.parentElement.children).filter(e=>e.tagName===h.tagName);if(t.length>1){e+=`[${t.indexOf(h)+1}]`}}u.unshift(e)}h=h.parentElement}const d=`${u.join("")}`;return l.set(e,d),d}catch(e){return console.log(e),null}},x=(t,n)=>{const l=[];let a="";if(t&&!r(t.value)&&"function"!=typeof t.nodeValue){const r=[...new Set(t.value.match(/([^0-9]+)/g))];if(r?.length)for(let n=0;n<r?.length;n++)r[n]&&f(r[n].trim())?.length>2&&(e.test(r[n])?l.push(`contains(@${t.name},${c(r[n].trim())})`):l.push(`contains(@${t.name},${c(f(r[n])).trim()})`));if(l?.length)return a=p(n)?`//*[local-name()='${n.tagName}' and ${l.join(" and ")}]`:`//${n.tagName}[${l.join(" and ")}]`,a}},E=(t,n,l,a)=>{try{const r=[];if(l.length>1)for(const o of l)if(g(o,t,a)){const l=o.nodeValue;e.test(l)?"class"===o.nodeName?r.push(`contains(@${o.nodeName},"${l}")`):r.push(`@${o.nodeName}="${l}"`):r.push(`normalize-space(@${o.nodeName})="${l}"`);const a=p(t)?`//*[local-name()='${t.tagName}' and ${r.join(" and ")}]`:`//${t.tagName}[${r.join(" and ")}]`;let s;try{s=i(a,t,n)}catch(e){continue}if(1===s&&!a.includes("and"))return"";if(1===s&&a.includes("and"))return a}}catch(e){console.log(`'${JSON.stringify(e,null,2)}'`)}},S=(t,n,l)=>{let a=p(t),r="";if(g(n,t,l)){let l=n.value;l=l.replace("removePointers","");const o=n.name;r=e.test(l)?a?`*[local-name()='${t.tagName}' and @${o}=${c(l)}]`:`${t.tagName||"*"}[@${o}=${c(l)}]`:a?`*[local-name()='${t.tagName}' and normalize-space(@${o})=${c(l)}]`:`${t.tagName||"*"}[normalize-space(@${o})=${c(l)}]`}return r},w=(t,n)=>{if(!t.textContent)return"";const l=s(t);let a;return a=e.test(l)?p(t)?`//*[local-name()='${t.tagName}' and .=${c(l)}]`:`//${t.tagName||"*"}[.=${c(l)}]`:p(t)?`//*[local-name()='${t.tagName}' and normalize-space(.)=${c(l)}]`:`//${t.tagName||"*"}[normalize-space(.)=${c(l)}]`,a},k=e=>{const t=o(e)?.trim(),n=t?c(h(t)):t;if(n)return n!==`'${t}'`?`contains(.,${n})`:`normalize-space(.)='${t}'`},R=(e,t,n)=>{const l=new RegExp(/^[\S]+( [\S]+)*$/gi);let a="";return n&&(a=l.test(n)?"class"===t?p(e)?`//*[local-name()='${e.tagName}' and contains(@${t},${c(n)})]`:`//${e.tagName||"*"}[contains(@${t},${c(n)})]`:p(e)?`//*[local-name()='${e.tagName}' and @${t}=${c(n)}]`:`//${e.tagName||"*"}[@${t}=${c(n)}]`:p(e)?`//*[local-name()='${e.tagName}' and contains(@${t},${c(n)})]`:`//${e.tagName||"*"}[contains(@${t},${c(n)})]`),a},C=(e,t)=>e?e.replace(/\bdisabled\b/gi,"flndisabled"):e,P=(t,n,l)=>{let a;const s=[];if(t.textContent&&(!l||l&&!r(t.textContent))&&(e.test(t.textContent)?(a=p(t)?`*[local-name()='${t.tagName}' and .=${c(o(t))}]`:`${t.tagName}[.=${c(o(t))}]`,a&&s.push({key:"getReferenceElementsXpath",value:a})):(a=p(t)?`*[local-name()='${t.tagName}' and ${k(t)})]`:`${t.tagName}[${k(t)}]`,a&&s.push({key:"getReferenceElementsXpath",value:a}))),t.attributes)for(const e of Array.from(t.attributes))if(g(e,t,l)){let n=e.nodeValue;if(n){n=n.replace("removePointers","");const l=e.name;a="class"===l?p(t)?`*[local-name()='${t.tagName}' and contains(@${l},${c(n)})]`:`${t.tagName}[contains(@${l},${c(n)})]`:p(t)?`*[local-name()='${t.tagName}' and @${l}=${c(n)}]`:`${t.tagName}[@${l}=${c(n)}]`,a&&s.push({key:"getReferenceElementsXpath",value:a})}}if(!s?.length){const e=Array.prototype.slice.call(t.attributes);if(e?.length>1){const e=E(t,n,Array.prototype.slice.call(t.attributes),l);e&&s.push({key:"getReferenceElementsXpath",value:e})}}if(!s?.length){const n=[];let a;const o=p(t);if(t.textContent&&l&&r(t.textContent)){const l=[...new Set(t.textContent.match(/([^0-9]+)/g))];if(l?.length)for(let t=0;t<l?.length;t++)l[t]&&f(l[t].trim())?.length>1&&(e.test(l[t])?n.push(`contains(.,${c(l[t]).trim()})`):n.push(`contains(.,${c(f(l[t])).trim()})`));n?.length&&(a=o?`//*[local-name()='${o}' and ${n.join(" and ")}]`:`//${o}[${n.join(" and ")}]`,a&&s.push({key:"getReferenceElementsXpath",value:a}))}}if(!s?.length){const e=((e,t,n,l)=>{const a=Array.prototype.slice.call(e),r=[];try{a.map(e=>{if(g(e,t,l)){const n=x(e,t);n&&r.push({key:`split xpath by ${e.name}`,value:n})}})}catch(e){console.log(e)}return r})(t.attributes,t,0,l);e?.length&&s.concat(e)}return s},A=e=>e=(e=e.replace(/text\(\)\s*=\s*(['"])(.*?)\1/g,"normalize-space(.)=$1$2$1")).replace(/\.\s*=\s*(['"])(.*?)\1/g,"normalize-space(.)=$1$2$1"),O=(e,t)=>{let n=t,l=1;for(;l>0;){const t=e[++n];"("==t?l++:")"==t&&l--}return n},D={parseXml:(e,t)=>window.DOMParser?(new window.DOMParser).parseFromString(e,t):null,getReferenceElementsXpath:P,getAbsoluteXPath:b,getRelativeXPath:N,getCombinationXpath:x,getAttributeCombinationXpath:E,getElementFromXpath:v,isSvg:p,findXpathWithIndex:m,isNumberExist:r,getTextContent:o,getCountOfXPath:i,normalizeXPath:A,getShadowRoot:d,escapeCharacters:c,removeParenthesis:u,checkBlockedAttributes:g,getRelationship:(e,t)=>{let n=e.compareDocumentPosition(t);return 2===n?"preceding":4===n?"following":8===n?"ancestor":16===n?"descendant":32===n?"self":""},findMatchingParenthesis:O,deleteGarbageFromInnerText:h,replaceTempAttributes:$,createObserver:e=>{n=new MutationObserver(t=>{t.forEach(t=>{t?.addedNodes?.length&&e(t?.addedNodes),t.target instanceof HTMLElement&&("attributes"===t?.type&&"class"===t.attributeName&&(p(t.target)&&t.oldValue?.trim()===t.target.classList.value?.trim()||"marked-element-temp"===t.target.classList?.value?.replace(t.oldValue,"").trim()||"marked-element-temp"===t?.oldValue?.replace(t.target.classList?.value,"").trim())||"attributes"!==t?.type||["flndisabled"].includes(t.attributeName)||a.push({url:t.target.baseURI,attributeName:t.attributeName,element:t.target,doc:t.target.ownerDocument}))})})},startObserver:(e,t)=>{n?.observe(e,t)},stopObserver:()=>{n?.disconnect()},modifiedElementAttributes:a,cspEnabled:!1};let X=[],T=[],j=new Map,V=new Map;const L=new Map,_=(e,t,n,l,a,r)=>{if(e){let o;o="parent"===r?[`${e}/descendant-or-self::${t}`,`${e}/following::${t}`]:[`${e}/ancestor-or-self::${t}`,`${e}/preceding::${t}`];for(const e of o){j?.get(e)||j.set(e,i(e,n,l));const t=j?.get(e);if(1===t)return e;if(t>1&&(T.length?t<T[0].count&&(T.pop(),T.push({key:"relative xpath by unique parent "+(a?"index":""),value:e,count:t})):T.push({key:"relative xpath by unique parent "+(a?"index":""),value:e,count:t})),t>1&&a&&!X.length){const r=m(e,n,l,t);r&&1===i(r,n,l)&&X.push({key:"relative xpath by unique parent "+(a?"index":""),value:r})}}}return null},Y=(t,n,l,a,o,u)=>{try{if(L.has(t))return L.get(t);const m=[];let h=t;for(;h&&1===h.nodeType;){const t=!1;for(const e of Array.from(h.attributes))if(g(e,h,a)){let t=e.nodeValue;t=t?.replace("removePointers","")??"";const a=e.name,r=R(h,a,t);let s;try{s=_(r,o,l,n,u,"parent")}catch(e){continue}if(s)return s}if(h.textContent&&!h.textContent)if(!a||a&&!r(h.textContent)){let t;t=e.test(h.textContent)?p(h)?`//*[local-name()='${h.tagName}' and .=${c(s(h))}]`:`//${h.tagName||"*"}[.=${c(s(h))}]`:p(h)?`//*[local-name()='${h.tagName}' and normalize-space(.)=${c(s(h))}]`:`//${h.tagName||"*"}[normalize-space(.)=${c(s(h))}]`;const a=_(t,o,l,n,u,"parent");if(a)return a}else{const e=[],t=[...new Set(s(h).match(/([^0-9]+)/g))],a=new RegExp(/^[\S]+( [\S]+)*$/gi);if(t?.length)for(let n=0;n<t?.length;n++)t[n]&&f(t[n].trim())&&(a.test(t[n])?e.push(`contains(.,${c(t[n].trim()).trim()})`):e.push(`contains(.,${c(f(t[n])).trim()})`));if(e?.length){const t=p(h)?`//*[local-name()='${h.tagName}' and ${e.join(" and ")}]`:`//${h.tagName||"*"}[${e.join(" and ")}]`,a=_(t,o,l,n,u,"parent");if(a)return a}}if(!t){const e=p(h)?`/*[local-name()='${h.tagName}']`:`/${h.tagName}`;m.unshift(e)}h=h.parentElement}const d=m.join("")+o;if(1===i(d,t,n))return L.set(t,d),d}catch(e){return console.error(e),null}},M=(e,t,n,l)=>{const a=new Map;if(a.has(e))return a.get(e);const r=[];let o=e;try{for(;o&&1===o.nodeType;){if(!o.tagName)return"";let e=!1;for(const n of Array.from(o.attributes))if(g(n,o,l)){let l=n.nodeValue;l=l?.replace("removePointers","")??"";const a=n.name,s=R(o,a,l);let c;try{c=i(s,o,t)}catch(e){continue}if(1===c){r.unshift(s),e=!0;break}}if(!e&&o.textContent&&!n.textContent){const n=w(o);if(n){if(1===i(n,o,t)){e=!0,r.unshift(n);break}}}if(e)break;{const e=p(o)?`/*[local-name()='${o.tagName}']`:`/${o.tagName}`;r.unshift(e)}o=o.parentElement}const s=r.join("");return a.set(e,s),s}catch(e){return console.log(e),null}},I=(e,t,n)=>{const l=[];let a;const r=[];null!=e.firstElementChild&&e.firstElementChild.classList.contains("flntooltip")?r.unshift(e.firstElementChild):null!=e.nextElementSibling&&r.unshift(e.nextElementSibling);for(let t=e.parentElement;null!=t&&1===t.nodeType;t=t.parentElement)t.nextElementSibling&&r.unshift(t.nextElementSibling);try{do{let e=!1;for(a=r.pop();null!==a;){for(const n of Array.from(a.attributes))if(g(n,a,!0)){let r=n.nodeValue;r=r?.replace("removePointers","")??"";const o=n.name,s=R(a,o,r);let c;try{c=i(s,a,t)}catch(e){continue}if(1===c){e=!0,l.push(s);break}}if(!e&&a.textContent&&!n.textContent){const n=w(a);if(n){if(1===i(n,a,t)){e=!0,l.push(n);break}}}if(e)break;{const e=p(a)?`/*[local-name()='${a.tagName}']`:`/${a.tagName}`;l.push(e),null!=a.firstElementChild?(r.push(a.nextElementSibling),a=a.firstElementChild):a=a.nextElementSibling}}}while(r.length>0);const o=l.join("");return V.set(e,o),o}catch(e){return console.log(e),null}},q=(e,t,n,l)=>{try{const a=document.querySelector(".flntooltip");for(let r=e.nextElementSibling;null!==r&&r!==a;r=r.nextElementSibling)H(r,e,t,l,"preceding-sibling",n);for(let r=e.previousElementSibling;null!==r&&r!==a;r=r.previousElementSibling)H(r,e,t,l,"following-sibling",n)}catch(e){return console.error("sibling error",e),null}},H=(e,t,n,l,a,r)=>{try{if(e.hasAttributes())for(const t of Array.from(e.attributes)){let o=S(e,{name:t.name,value:t.value},r);if(o){o+=`/${a}::${l}`;const t=i(o,e,n);if(1===t)return void X.push({key:`xpath by ${a}`,value:o});t>1&&(T.length?t<T[0].count&&(T.pop(),T.push({key:`relative xpath by ${a}`,value:o,count:t})):T.push({key:`relative xpath by ${a}`,value:o,count:t}))}}if(!r){let t;if(t=S(e,{name:"text",value:e.textContent},r),t){const l=i(t,e,n);if(1===l)return void X.push({key:`xpath by ${a}`,value:t});l>1&&(T.length?l<T[0].count&&(T.pop(),T.push({key:`relative xpath by ${a}`,value:t,count:l})):T.push({key:`relative xpath by ${a}`,value:t,count:l}))}}}catch(e){console.log(`${a} xpath-error`,e)}};function W(e,t,n,l){const{tagName:a}=t,r=t.textContent.trim();for(const o of e)if(g(o,t,l)){let e=o.nodeValue;e=e?.replace("removePointers","")??"";const l=`//${a}[@${o.name}='${e}' and text()='${r}']`;if(l){if(1==i(l,t,n))return l}}}const z=(e,t,n,l,a)=>{try{let r,o,s=[];if(X=[],console.log(a),a)for(const t of a){let n=S(e,{name:t.name,value:t.value},l);console.log(n),n&&s.push(n)}if(e.textContent){let t=S(e,{name:"text",value:e.textContent},l);console.log(t),t&&s.push(t)}if(s.push(e.tagName),s?.length)for(let a=0;a<s.length;a++)if(!X.length){if(q(e,t,l,s[a]),!X.length&&(r||(r=M(e.parentElement,t,e,l)),console.log(r),r&&(r.includes("@")||r.includes("text()")||r.includes(".="))&&r.match(/\//g)?.length-2<5)){const l=r+`/${s[a]}`,o=i(l,e,t);if(1===o)X.push({key:"relative xpath by relative parent",value:l});else if(o>1&&n){const a=m(l,e,t,o);a&&1===i(a,e,t)&&X.push({key:"relative xpath by relative parent "+(n?"index":""),value:a})}}if(!X.length&&(o||(o=I(e,t,e)),o&&(o.includes("@")||o.includes("text()")||o.includes(".=")))){const l=`/${s[a]+o.substring(1)}`,r=i(l,e,t);if(1===r)X.push({key:"relative xpath by relative child",value:l});else if(r>1&&n){const a=m(l,e,t,r);a&&1===i(a,e,t)&&X.push({key:"relative xpath by relative parent "+(n?"index":""),value:a})}}if(1===X?.length&&X?.[0]?.value?.match(/\[([0-9]+)\]/gm)?.length>3&&e.textContent){const l=B(e,t,n,!1);l&&X.unshift({key:"xpath by text"+(n?"index":""),value:l})}if(!X.length){let r=Y(e.parentElement,t,e,l,s[a],n);r&&X.push({key:"xpath by unique parent",value:r})}}return X}catch(e){console.log(e)}},F=(e,t,n,l,a)=>{let r;return r=e.name,y(t,n,`@${r}`,e.value,l,a)},U=(e,t,n,l)=>{let a=e.className;if("string"!=typeof a&&(a=""),a=a?.replace("flndisabled","disabled"),a=a?.replace("removePointers",""),a=a?.trim(),a)return y(e,t,"@class",a,n,l)},B=(e,t,n,l)=>{if(""!=e.textContent){const a=o(e);if(a)return y(e,t,".",a,n,l)}},G=(e,t,n,l,a)=>{const r=e;try{r.map(e=>{if("className"!==e.name&&"class"!==e.name&&g(e,t,a)){const r=F(e,t,n,l,a);r&&X.push({key:`xpath by ${e.name}${l?" index":""}`,value:r})}});const o=B(t,n,l,a);if(o&&X.push({key:"xpath by text"+(l?" index":""),value:o}),r.find(e=>"className"===e.name)&&g(r?.find(e=>"className"===e.name),t,a)){let e=U(t,n,l,a);e&&X.push({key:"xpath by class",value:e})}if(!X.length){const l=W(e,t,n,a);l&&X.push({key:"xpath by textAttribute",value:l})}if(!X.length&&r.length>1){const e=E(t,n,r,a);e&&X.push({key:"xpath by combination",value:e})}}catch(e){console.log(e)}},J=(e,t,n,l)=>{X=[],console.log(e);const a=e,r=a?.ownerDocument||t,o=a.tagName,{attributes:s}=a;if(G(Array.from(s),a,r,n,l),X.length){const t=X.length;for(let n=0;n<t;n++){let t=X[n].value;t="//*"+t.substring(t.indexOf("//")+2+o.length);1===i(t,e,r)&&X.push({key:`${X[n].key} regex`,value:t})}}return console.log(X),X.length||z(a,r,n,l,Array.from(a.attributes)),X},Z={parseDOM:J,getTextXPath:B,getUniqueClassName:U,attributesBasedXPath:F,addAllXPathAttributes:G,addRelativeXpaths:z,getXPathUsingAttributeAndText:W,getSiblingRelativeXPath:q,getChildRelativeXpath:I,getParentRelativeXpath:M,getUniqueParentXpath:Y,checkRelativeXpathRelation:_};let K=[],Q=[];const ee=/^[\S]+( [\S]+)*$/gi,te=(e,t,n,l,a,r,o,s=0,c=!1)=>{let u="";if(t.split(/\/(?=(?:[^']*\'[^\']*\')*[^\']*$)/g)?.length>=r.length){const i=[],u=t.split(/\/(?=(?:[^']*\'[^\']*\')*[^\']*$)/g);for(let e=1;e<=r.length;e++)i.unshift(e===r.length?r[r.length-e]:u[u.length-e]);const m=ae(`${o+(s?"]".repeat(s):"")}`,i,e[e.length-1],e,l,n,a,c);if(m)return m}else{u=`//${o+(s?"]".repeat(s):"")}/${n}::${C(t,e[e.length-1])}`;let r=i(u,e[e.length-1],l);if(1===r)return[{key:`dynamic ${n}`,value:$(u)}];if(r>1&&a&&(u=m(u,e[e.length-1],l,r),u&&(r=i(u,e[e.length-1],l),1===r)))return[{key:`dynamic ${n} ${a?" index":""}`,value:$(u)}]}},ne=(e,t,n,l,a,r=!1,s=!1)=>{const i=e[e.length-2],u=e[e.length-1],m=d(u)??u.ownerDocument,h=n.find(e=>e?.key?.includes("absolute"))?.value||b(i,i.ownerDocument),f=[],$=[];h.split("/").map(e=>f.push(e)),f.map(e=>$.push(e.replace(/\[([0-9]+)\]/gm,"")));const v=l.find(e=>e?.key?.includes("absolute"))?.value||b(u,u.ownerDocument),y=[],N=[];v.split("/").map(e=>y.push(e)),y.map(e=>N.push(e.replace(/\[([0-9]+)\]/gm,"")));for(var E=0;E<f.length&&f[E]==y[E];E++);const S=[];for(let e=E-1;e<f.length;e++)f[e]&&S.push($[e]);const w=[];for(let e="descendant"===a?E:E-1;e<y.length;e++)y[e]&&(w.length?w.push(N[e]):w.push(N[e].replace(/\[([0-9]+)\]/gm,"")));let R;if(Q=l,e[e.length-2].textContent){R=ee.test(e[e.length-2].textContent)?p(e[e.length-2])?`*[local-name()='${e[e.length-2].tagName}' and .=${c(o(e[e.length-2]))}]`:`${e[e.length-2].tagName}[.=${c(o(e[e.length-2]))}]`:p(e[e.length-2])?`*[local-name()='${e[e.length-2].tagName}' and ${k(e[e.length-2])})]`:`${e[e.length-2].tagName}[${k(e[e.length-2])}]`,S[S.length-1]=R;const n=S.join("["),l=S.length-1,i=n;for(let n=0;n<Q.length;n++){let o;if(o=Q[n].value.startsWith("//")?Q[n].value.substring(Q[n].value.indexOf("//")+2):Q[n].value,o)return te(e,o,a,m||t,r,w,i,l,s)}}if(e[e.length-2].attributes){for(const n of Array.from(e[e.length-2].attributes))if(g(n,e[e.length-2],!1)){let l=n.nodeValue;if(l){l=l.replace("removePointers","");const o=n.name;R=p(e[e.length-2])?`*[local-name()='${e[e.length-2].tagName}' and @${o}=${c(l)}]`:`${e[e.length-2].tagName}[@${o}=${c(l)}]`,S[S.length-1]=R;const i=S.join("["),u=S.length-1,h=i;for(let n=0;n<Q.length;n++){let l;return l=Q[n].value.startsWith("//")?Q[n].value.substring(Q[n].value.indexOf("//")+2):Q[n].value,te(e,l,a,m||t,r,w,h,u,s)}}}for(const n of Array.from(e[e.length-2].attributes))if(g(n,e[e.length-2],!1)){let l=n.nodeValue;if(l){l=l.replace("removePointers","");const o=x(n,e[e.length-2]);if(o){R=o.startsWith("//")?o.substring(o.indexOf("//")+2):o,S[S.length-1]=R;const n=S.join("["),l=S.length-1,i=n;for(let n=0;n<Q.length;n++){let o;return o=Q[n].value.startsWith("//")?Q[n].value.substring(Q[n].value.indexOf("//")+2):Q[n].value,te(e,o,a,m||t,r,w,i,l,s)}}}}}const C=S.join("["),P=S.length-1,A=ae(`${C+(P?"]".repeat(P):"")}`,w,e[e.length-1],e,t,a,r,s);if(A)return A},le=(e,t,n,l,a,r,o)=>{let s,c;console.log("getXpathRelationExpression",n);const u=[];try{s=l.filter(e=>!e?.key?.includes("absolute")),c=a.filter(e=>!e?.key?.includes("absolute"));for(let e=0;e<s.length;e++)for(let l=0;l<c.length;l++){let a=`//${0!==s[e].value.indexOf("//")?C(s[e].value):C(s[e].value.substring(s[e].value.indexOf("//")+2))}/${n}::${0!==c[l].value.indexOf("//")?C(c[l].value):C(c[l].value.substring(c[l].value.indexOf("//")+2))}`;console.log("getXpathRelationExpression",a);const o=i(a,t,t.ownerDocument);if(o>1)if(r){if(a=m(a,t,t.ownerDocument,o),a)return u.push({key:`dynamic ${n}${r?" index":""}`,value:$(a)}),u}else o>1&&(K.length?o<K[0].count&&(K.pop(),K.push({key:"relative xpath by relative child "+(r?"index":""),value:a,count:o})):K.push({key:"relative xpath by relative child "+(r?"index":""),value:a,count:o}));else if(1===o)return u.push({key:`dynamic ${n}`,value:$(a)}),u}if(!u.length)for(let l=0;l<s.length;l++)for(let a=0;a<c.length;a++){const i=`${0!==c[a].value.indexOf("//")?c[a].value:c[a].value.substring(c[a].value.indexOf("//")+2)}`.split(/\/(?=(?:[^']*\'[^\']*\')*[^\']*$)/g);if(i.length>1){const a=ae(`${0!==s[l].value.indexOf("//")?C(s[l].value):C(s[l].value.substring(s[l].value.indexOf("//")+2))}`,i,t,[e,t],t.ownerDocument,n,r,o);if(console.log("getXpathRelationExpression traverseXpath",a),a)return u.concat(a),u}}}catch(e){console.log(e)}return u},ae=(e,t,n,l,a,r,o,s)=>{let c;if(s){const s=t.join("/");c=`//${e}/${r}::${C(s)}`;const u=i(c,n,a);if(1===u)return[{key:`dynamic ${r}`,value:$(c)}];if(u>1&&o&&(c=m(c,l[l.length-1],a,u),c))return[{key:`dynamic ${r}${o?" index":""}`,value:$(c)}]}else for(let s=1;s<=t.length;s++){const u=t.slice(t.length-s,t.length).join("/");c=`//${e}/${r}::${C(u)}`;const h=i(c,n,a);if(1===h)return[{key:`dynamic ${r}`,value:$(c)}];if(h>1&&o&&(c=m(c,l[l.length-1],a,h),c))return[{key:`dynamic ${r}${o?" index":""}`,value:$(c)}]}},re={findRelativeXpath:(e,t,n,l,a,r,o=!1)=>{const s=e.parentElement,i=t.parentElement;let c,u=[],h=[];if(r&&K.length){const e=m(K[0].value,t,t.ownerDocument,K[0].count);e&&(h=h.concat({key:`${K[0]?.key?K[0]?.key:"xpath with "} index`,value:e}),K.pop())}if(!h.length){for(e.isSameNode(t)&&(u=le(e,t,"self",l,a,r,o),u&&(h=h.concat(u))),c=e.parentElement,c===t&&(u=le(e,t,"parent",l,a,r,o),u&&(h=h.concat(u))),c=e.parentElement;null!==c;){if(c===t&&(u=le(e,t,"ancestor",l,a,r,o),u)){h=h.concat(u);break}c=c.parentNode}c=e;do{if(c===t&&(u=le(e,t,"ancestor-or-self",l,a,r,o),u)){h=h.concat(u);break}c=c.parentNode}while(null!==c);if(s?.isSameNode(i)){for(let n=e.nextElementSibling;null!=n;n=n.nextElementSibling)if(null!=n&&n.isSameNode(t)&&(u=le(e,t,"following-sibling",l,a,r,o),u)){h=h.concat(u);break}for(let n=e.previousElementSibling;null!=n;n=n.previousElementSibling)if(null!=n&&n.isSameNode(t)&&(u=le(e,t,"preceding-sibling",l,a,r,o),u)){h=h.concat(u);break}}if(e?.children?.length)for(let n=e.children[0];null!==n;n=n?.nextElementSibling)if(n===t&&(u=le(e,t,"child",l,a,r,o),u)){h=h.concat(u);break}const m=e.compareDocumentPosition(t);2===m&&(u=le(e,t,"preceding",l,a,r,o)),4===m&&(u=le(e,t,"following",l,a,r,o)),u&&(h=h.concat(u));const f=ne([e,t],n,l,a,"descendant",r,o);f&&(h=h.concat(f));const d=ne([e,t],n,l,a,"descedant-or-self",r,o);d&&(h=h.concat(d))}if(h.length)return h.length>1&&h.sort(function(e,t){return e.value.length-t.value.length}),h.filter(e=>!e.key?.includes("index"))?.length?[h.filter(e=>!e.key?.includes("index"))[0]]:[h[0]]},getDescendantXpath:ne,getXpathRelationExpression:le,getTraverseXpathExpression:ae,getReferenceElementXpath:e=>{let t=[];if(t=J(e,e.ownerDocument,!1,!1),t?.length){let n=J(e,e.ownerDocument,!0,!1);n?.length&&(n=n?.map(e=>"("==e.value.charAt(0)&&O(e.value,0)+1===e.value.lastIndexOf("[")?{key:"",value:u(e.value)}:{key:"",value:e.value}),t=t.concat(n))}else t=J(e,e.ownerDocument,!0,!1),t=t?.map(e=>"("==e.value.charAt(0)&&O(e.value,0)+1===e.value.lastIndexOf("[")?{key:"",value:u(e.value)}:{key:"",value:e.value});if(t?.length||(t=[{key:"",value:N(e,e.ownerDocument,!1,!1,Array.from(e.attributes))}]),t?.length||(t=[{key:"",value:N(e,e.ownerDocument,!0,!1,Array.from(e.attributes))}],t=t?.map(e=>"("==e.value.charAt(0)&&O(e.value,0)+1===e.value.lastIndexOf("[")?{key:"",value:u(e.value)}:{key:"",value:e.value})),t?.length){const n=P(e,e.ownerDocument,!1);n?.length&&(t=t.concat(n))}else t=P(e,e.ownerDocument,!1);const n=b(e,e.ownerDocument);return t=t.filter(e=>e.value!==n),t.push({key:"absolute xpath",value:n.slice(1)}),t}},oe=(e,t)=>{const n=Array.from(e.querySelectorAll("*"));try{for(let e=0;e<n.length;e++)if(n[e].shadowRoot){const{shadowRoot:l}=n[e];if(l&&(oe(l,t),l&&!t.includes("dynamic")))return l.querySelector(t)}}catch(e){console.log(e)}return null},se=e=>e?.id||null,ie=e=>e.className||null,ce=e=>e.textContent?.trim()||null,ue=e=>{const t=e;if(t.hasAttribute("name")){return`${t.getAttribute("name")}`||null}return null},me=["/preceding-sibling","/following-sibling","/parent","/descendant","/ancestor","/self","/ancestor-or-self","/child","/preceding","/following"];function he(e,t){const n=e.defaultView;if(!n)return null;return(new n.XPathEvaluator).evaluate(t,e,null,n.XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue}function fe(e,t,n){if(e.includes(t)){const l=e.split(t)[0].trim(),a=n.defaultView;if(!a)return null;if(!e.includes("dynamic")){const t=new a.XPathEvaluator;if(t.evaluate(l,n,null,a.XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue){let l;return t.evaluate(e,n,null,a.XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue?(l=e,l):(console.error("Complete Locator is Invalid:",e),l=e,l)}console.error("Source Locator Not Found:",l)}}return null}const de=(e,t)=>{const n=t.querySelectorAll("script, style, link[rel='stylesheet'], meta, noscript, embed, object, param, source, svg");n&&n.forEach(e=>{e.remove()});const l=new Set;let a=[];function r(e,t={}){const n={name:t.name??e?.name,type:t.type??e?.type,value:t.value??e?.value,reference:t.reference??e?.reference,status:t.status??e?.status,isRecorded:t.isRecorded??e?.isRecorded};t.hasOwnProperty("isSelfHealed")?n.isSelfHealed=t.isSelfHealed:e?.hasOwnProperty("isSelfHealed")&&(n.isSelfHealed=e.isSelfHealed),function(e){const t=`${e.name}:${e.value}`;l.has(t)||(l.add(t),a.push(e))}(n)}const o=(e,t,n)=>{if(!e)return null;let l=e.trim();return l&&"null"!==l.toLowerCase()?(l=l.replace(/\\"/g,'"').replace(/\\'/g,"'"),l=l.replace(/^['"](.+?)['"]$/,"$1"),l=l.replace(/''/g,"'"),l=l.replace(/\[@(id|name)=['"]{2}(.+?)['"]{2}\]/g,"[@$1='$2']"),"id"!==t&&"name"!==t||(l=l.replace(/['"]/g,"").trim()),"xpath"!==t||"Y"!==n||e.startsWith("//")?!l||/^['"]{2}$/.test(l)?null:l:null):null};e:for(const n of e.locators)try{String(n.isRecorded||"");const s=e.locators.filter(e=>"N"===e.isRecorded);if(s.length>0)for(const e of s)r(e);const i=String(n.value||n.type||"");if(i.includes("dynamic")||i.match("dynamic")||i.includes("{")||i.includes("}")){r(n);continue}if(e.isShared.includes("Y"))break e;try{let s=null;if(n.value.startsWith("iframe")){const e=t.querySelector(n.value);if(e){const t=e.contentDocument||e.contentWindow?.document;t&&(s=t.querySelector(n.value.slice(6)))}}else{const e=n.value.split(">>>");for(const l of e){if(!t){console.error("Element not found at:",l);break}{const e=l.trim();if(n.name.includes("id")||e.startsWith("#"))s=t.querySelector("#"+e);else if(n.name.includes("className")||e.startsWith("."))s=t.querySelector("."+e);else if(!n.name.includes("xpath")&&!e.startsWith("//")||n.type.match("dynamic"))s=t.querySelector(e),s||(s=oe(t.body,e));else{s=he(t,A(e)),s&&r(n,{value:e,isRecorded:String(n.isRecorded).includes("N")?"N":"Y"})}}}}const i=(e,t)=>{const n=`${e}:${t}`;return l.has(n)};if(s){const n=se(s);n&&!i("id",n)&&e.locators.forEach(e=>{r(e,{name:"id",value:n,isRecorded:e.value===n&&"id"===e.name?e.isRecorded:"Y",isSelfHealed:e.value===n&&"id"===e.name?e.isSelfHealed:"Y"})});const l=ce(s);l&&e.locators.forEach(e=>{r(e,{name:"linkText",type:"static",value:l,isRecorded:e.value===l?e.isRecorded:"Y",isSelfHealed:e.value===l?e.isSelfHealed:"Y"})});const c=ue(s);c&&!i("name",c)&&e.locators.forEach(e=>{r(e,{name:"name",type:"static",value:c,isRecorded:e.value===c&&"name"===e.name?e.isRecorded:"Y",isSelfHealed:e.value===c&&"name"===e.name?e.isSelfHealed:"Y"})});const u=ie(s);u&&""!==u.trim()&&!i("className",u)&&e.locators.forEach(e=>{r(e,{name:"className",value:u,isRecorded:e.value===u&&"className"===e.name?e.isRecorded:"Y",isSelfHealed:e.value===u&&"className"===e.name?e.isSelfHealed:"Y"})});J(s,t,!1,!0).forEach(t=>{const n=t.value;n&&!i(t.key.replace("xpath by","").trim(),n)&&e.locators.forEach(e=>{r(e,{name:"xpath",value:n,isRecorded:e.value===n?e.isRecorded:"Y",isSelfHealed:e.value===n?e.isSelfHealed:"Y"})})});for(const n of e.locators)try{for(const l of e.locators)if(l.value)for(const e of me)if(l.value.includes(e)){const a=fe(l.value,e,t);if(a){r(l,{name:"xpath",value:a,isRecorded:""!==n.isRecorded&&null!==n.isRecorded?n.isRecorded:"Y"});break}}}catch(e){console.error("Error processing locator:",n,e)}const m=a.map(e=>({...e,value:o(e.value,e.name,e.isRecorded)})).reduce((e,t)=>(t.value&&!e.some(e=>e.value===t.value)&&e.push(t),e),[]),h=[{name:`${e.name}`,desc:`${e.desc}`,type:`${e.type}`,locators:m.filter(e=>null!=e?.value&&""!==e.value),isShared:`${e.isShared}`,projectId:`${e.projectId}`,projectType:`${e.projectType}`,isRecorded:`${e.isRecorded}`,folder:`${e.folder}`,parentId:`${e.parentId}`,parentName:`${e.parentName}`,platform:`${e.platform}`,licenseId:`${e.licenseId}`,licenseType:`${e.licenseType}`,userId:`${e.userId}`}];return h}}catch(e){console.error("Error processing locator:",n,e);continue}}catch(e){console.error("Error processing locator:",n,e);continue}return null};let ge=[];const pe=(e,t)=>{const n=e.tagName.toLowerCase();if(t?.defaultView?.Element&&!(e instanceof t?.defaultView?.Element))return;if(n.includes("style")||n.includes("script"))return;const l=[];for(;e?.nodeType===Node.ELEMENT_NODE;){let t=e.nodeName?.toLowerCase();if(e.id&&!r(e.id)){t+=`#${e.id}`,l.unshift(t);break}{let n=e,l=1;if(n.previousElementSibling)for(;n=n.previousElementSibling;)n.nodeName?.toLowerCase()===t&&l++;1!==l&&(t+=`:nth-of-type(${l})`),1===l&&n?.parentElement?.childElementCount>1&&(t+=`:nth-child(${l})`)}l.unshift(t),e=e.parentElement}return l.join(" > ")},$e=(e,t)=>{const n=e.tagName.toLowerCase();if(t?.defaultView?.Element&&!(e instanceof t?.defaultView?.Element))return;if(n.includes("style")||n.includes("script"))return;const l=[];for(;e?.nodeType===Node.ELEMENT_NODE;){let t=e.nodeName?.toLowerCase(),n=e.getAttribute("name");if(n&&!r(n)){t+=`[name=${n}]`,l.unshift(t);break}{let n=e,l=1;if(n.previousElementSibling)for(;n=n.previousElementSibling;)n.nodeName?.toLowerCase()===t&&l++;1!==l&&(t+=`:nth-of-type(${l})`),1===l&&n?.parentElement?.childElementCount>1&&(t+=`:nth-child(${l})`)}l.unshift(t),e=e.parentElement}return l.join(" > ")},ve=(e,t)=>{const n=e.tagName.toLowerCase();if(t?.defaultView?.Element&&!(e instanceof t?.defaultView?.Element))return;if(n.includes("style")||n.includes("script"))return;const l=[];for(;e?.nodeType===Node.ELEMENT_NODE;){let t=e.nodeName?.toLowerCase();if("string"!=typeof e.className||!e.className||r(e.className)||ge?.find(t=>t.element===e&&"class"===t.attributeName)){let n=e,l=1;if(n.previousElementSibling)for(;n=n.previousElementSibling;)n.nodeName?.toLowerCase()===t&&l++;1!==l&&(t+=`:nth-of-type(${l})`),1===l&&n?.parentElement?.childElementCount>1&&(t+=`:nth-child(${l})`)}else if(e.classList.remove("marked-element-temp"),e.classList.remove("removePointers"),e.className){t+=`.${e.className.trim().replace(/\s+/g,".")}`,l.unshift(t);break}l.unshift(t),e=e.parentElement}return l.join(" > ")},ye=(e,t)=>{const n=e.tagName.toLowerCase();if(t?.defaultView?.Element&&!(e instanceof t?.defaultView?.Element))return;if(n.includes("style")||n.includes("script"))return;const l=[];for(;e?.nodeType===Node.ELEMENT_NODE;){let t=e.nodeName?.toLowerCase();if(n.includes("body")||n.includes("head")||n.includes("html")){t+=n,l.unshift(t);break}{let n=e,l=1;if(n.previousElementSibling)for(;n=n.previousElementSibling;)n.nodeName?.toLowerCase()===t&&l++;1!==l&&(t+=`:nth-of-type(${l})`),1===l&&n?.parentElement?.childElementCount>1&&(t+=`:nth-child(${l})`)}l.unshift(t),e=e.parentElement}return l.join(" > ")},be={parseCssSelectors:(e,t)=>{let n=[];try{let l=pe(e,t);l&&l.includes("#")&&1===t.querySelectorAll(l)?.length&&!(l.includes("body")||l.includes("head")||l.includes("html"))?n.push({key:"cssSelector by id",value:l}):l="";let a=$e(e,t);a&&a!==l&&a.includes("name")&&1===t.querySelectorAll(a)?.length&&!(a.includes("body")||a.includes("head")||a.includes("html"))?n.push({key:"cssSelector by name",value:a}):a="";let r=ve(e,t);r&&r!==l&&a!==r&&r.includes(".")&&1===t.querySelectorAll(r)?.length&&!(r.includes("body")||r.includes("head")||r.includes("html"))?n.push({key:"cssSelector by class",value:r}):r=""}catch(e){console.log(e)}if(!n.length){let l=ye(e,t);l&&1===t.querySelectorAll(l)?.length&&!(l.includes("body")||l.includes("head")||l.includes("html"))?n.push({key:"Absolute cssSelector",value:l}):l=""}return n},getIdCssPath:pe,getNameCssPath:$e,getClassCssPath:ve,getAbsoluteCssPath:ye},Ne=()=>({xpath:Z,referenceXpaths:re,xpathUtils:D,getElementsFromHTML:de,cssSelectors:be});exports.createXPathAPI=Ne,exports.default=Ne;
2809
2
  //# sourceMappingURL=index.browser.cjs.map