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