@vitest/browser 4.1.0-beta.5 → 4.1.0-beta.6
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/README.md +4 -4
- package/context.d.ts +27 -5
- package/dist/client/.vite/manifest.json +1 -1
- package/dist/client/__vitest_browser__/{tester-C0ZOZX6s.js → tester-DVQLxxE-.js} +60 -21
- package/dist/client/tester/tester.html +1 -1
- package/dist/context.js +28 -0
- package/dist/expect-element.js +2 -2
- package/dist/{index-BvKPfXh9.js → index-CDbEr3te.js} +2 -2
- package/dist/index.d.ts +19 -1
- package/dist/index.js +5605 -2
- package/dist/locators.d.ts +2 -1
- package/dist/locators.js +1 -1
- package/package.json +14 -8
package/README.md
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
# @vitest/browser
|
|
2
2
|
|
|
3
|
-
[](https://
|
|
3
|
+
[](https://npmx.dev/package/@vitest/browser)
|
|
4
4
|
|
|
5
5
|
This package exposes utilities to make your own browser provider. If you just need to run tests in the browser, consider installing one of these packages instead:
|
|
6
6
|
|
|
7
|
-
- [@vitest/browser-playwright](https://
|
|
8
|
-
- [@vitest/browser-webdriverio](https://
|
|
9
|
-
- [@vitest/browser-preview](https://
|
|
7
|
+
- [@vitest/browser-playwright](https://npmx.dev/package/@vitest/browser-playwright) - run tests using [playwright](https://playwright.dev/)
|
|
8
|
+
- [@vitest/browser-webdriverio](https://npmx.dev/package/@vitest/browser-webdriverio) - run tests using [webdriverio](https://webdriver.io/)
|
|
9
|
+
- [@vitest/browser-preview](https://npmx.dev/package/@vitest/browser-preview) to see how your tests look like in a real browser.
|
|
10
10
|
|
|
11
11
|
[GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/guide/browser/)
|
package/context.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SerializedConfig } from 'vitest'
|
|
2
|
-
import { StringifyOptions, BrowserCommands } from 'vitest/internal/browser'
|
|
2
|
+
import { StringifyOptions, CDPSession, BrowserCommands } from 'vitest/internal/browser'
|
|
3
3
|
import { ARIARole } from './aria-role.js'
|
|
4
4
|
import {} from './matchers.js'
|
|
5
5
|
|
|
@@ -17,9 +17,7 @@ export type BufferEncoding =
|
|
|
17
17
|
| 'binary'
|
|
18
18
|
| 'hex'
|
|
19
19
|
|
|
20
|
-
export
|
|
21
|
-
// methods are defined by the provider type augmentation
|
|
22
|
-
}
|
|
20
|
+
export { CDPSession };
|
|
23
21
|
|
|
24
22
|
export interface ScreenshotOptions extends SelectorOptions {
|
|
25
23
|
/**
|
|
@@ -43,6 +41,14 @@ export interface ScreenshotOptions extends SelectorOptions {
|
|
|
43
41
|
save?: boolean
|
|
44
42
|
}
|
|
45
43
|
|
|
44
|
+
export interface MarkOptions {
|
|
45
|
+
/**
|
|
46
|
+
* Optional stack string used to resolve marker location.
|
|
47
|
+
* Useful for wrapper libraries that need to forward the end-user callsite.
|
|
48
|
+
*/
|
|
49
|
+
stack?: string
|
|
50
|
+
}
|
|
51
|
+
|
|
46
52
|
interface StandardScreenshotComparators {
|
|
47
53
|
pixelmatch: {
|
|
48
54
|
/**
|
|
@@ -489,7 +495,7 @@ export interface LocatorByRoleOptions extends LocatorOptions {
|
|
|
489
495
|
selected?: boolean
|
|
490
496
|
}
|
|
491
497
|
|
|
492
|
-
interface LocatorScreenshotOptions extends Omit<ScreenshotOptions, 'element'> {}
|
|
498
|
+
export interface LocatorScreenshotOptions extends Omit<ScreenshotOptions, 'element'> {}
|
|
493
499
|
|
|
494
500
|
export interface LocatorSelectors {
|
|
495
501
|
/**
|
|
@@ -653,6 +659,12 @@ export interface Locator extends LocatorSelectors {
|
|
|
653
659
|
}>
|
|
654
660
|
screenshot(options?: LocatorScreenshotOptions): Promise<string>
|
|
655
661
|
|
|
662
|
+
/**
|
|
663
|
+
* Add a trace marker for this locator when browser tracing is enabled.
|
|
664
|
+
* @see {@link https://vitest.dev/api/browser/locators#mark}
|
|
665
|
+
*/
|
|
666
|
+
mark(name: string, options?: MarkOptions): Promise<void>
|
|
667
|
+
|
|
656
668
|
/**
|
|
657
669
|
* Returns an element matching the selector.
|
|
658
670
|
*
|
|
@@ -816,6 +828,16 @@ export interface BrowserPage extends LocatorSelectors {
|
|
|
816
828
|
path: string
|
|
817
829
|
base64: string
|
|
818
830
|
}>
|
|
831
|
+
/**
|
|
832
|
+
* Add a trace marker when browser tracing is enabled.
|
|
833
|
+
* @see {@link https://vitest.dev/api/browser/context#mark}
|
|
834
|
+
*/
|
|
835
|
+
mark(name: string, options?: MarkOptions): Promise<void>
|
|
836
|
+
/**
|
|
837
|
+
* Group multiple operations under a trace marker when browser tracing is enabled.
|
|
838
|
+
* @see {@link https://vitest.dev/api/browser/context#mark}
|
|
839
|
+
*/
|
|
840
|
+
mark<T>(name: string, body: () => T | Promise<T>, options?: MarkOptions): Promise<T>
|
|
819
841
|
/**
|
|
820
842
|
* Extend default `page` object with custom methods.
|
|
821
843
|
*/
|
|
@@ -839,16 +839,13 @@ function createBrowserRunner(runnerClass, mocker, state, coverageModule) {
|
|
|
839
839
|
await ((_a = super.onBeforeTryTask) == null ? void 0 : _a.call(this, ...args));
|
|
840
840
|
const trace = this.config.browser.trace;
|
|
841
841
|
const test = args[0];
|
|
842
|
-
if (trace === "off") {
|
|
843
|
-
return;
|
|
844
|
-
}
|
|
845
842
|
const { retry, repeats } = args[1];
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
if (trace === "on-first-retry" && retry !== 1) {
|
|
843
|
+
const shouldTrace = trace !== "off" && !(trace === "on-all-retries" && retry === 0) && !(trace === "on-first-retry" && retry !== 1);
|
|
844
|
+
if (!shouldTrace) {
|
|
845
|
+
getBrowserState().activeTraceTaskIds.delete(test.id);
|
|
850
846
|
return;
|
|
851
847
|
}
|
|
848
|
+
getBrowserState().activeTraceTaskIds.add(test.id);
|
|
852
849
|
let title = getTestName(test);
|
|
853
850
|
if (retry) {
|
|
854
851
|
title += ` (retry x${retry})`;
|
|
@@ -863,16 +860,14 @@ function createBrowserRunner(runnerClass, mocker, state, coverageModule) {
|
|
|
863
860
|
);
|
|
864
861
|
};
|
|
865
862
|
onAfterRetryTask = async (test, { retry, repeats }) => {
|
|
866
|
-
|
|
867
|
-
if (
|
|
868
|
-
return;
|
|
869
|
-
}
|
|
870
|
-
if (trace === "on-all-retries" && retry === 0) {
|
|
871
|
-
return;
|
|
872
|
-
}
|
|
873
|
-
if (trace === "on-first-retry" && retry !== 1) {
|
|
863
|
+
var _a, _b, _c;
|
|
864
|
+
if (!getBrowserState().activeTraceTaskIds.has(test.id)) {
|
|
874
865
|
return;
|
|
875
866
|
}
|
|
867
|
+
await this.commands.triggerCommand("__vitest_markTrace", [{
|
|
868
|
+
name: `onAfterRetryTask [${(_a = test.result) == null ? void 0 : _a.state}]`,
|
|
869
|
+
stack: (_c = (_b = test.result) == null ? void 0 : _b.errors) == null ? void 0 : _c[0].stack
|
|
870
|
+
}]);
|
|
876
871
|
const name = getTraceName(test, retry, repeats);
|
|
877
872
|
if (!this.traces.has(test.id)) {
|
|
878
873
|
this.traces.set(test.id, []);
|
|
@@ -1989,6 +1984,22 @@ function createModuleMockerInterceptor() {
|
|
|
1989
1984
|
function rpc() {
|
|
1990
1985
|
return getWorkerState().rpc;
|
|
1991
1986
|
}
|
|
1987
|
+
const ACTION_TRACE_COMMANDS = /* @__PURE__ */ new Set([
|
|
1988
|
+
"__vitest_click",
|
|
1989
|
+
"__vitest_dblClick",
|
|
1990
|
+
"__vitest_tripleClick",
|
|
1991
|
+
"__vitest_wheel",
|
|
1992
|
+
"__vitest_type",
|
|
1993
|
+
"__vitest_clear",
|
|
1994
|
+
"__vitest_fill",
|
|
1995
|
+
"__vitest_selectOptions",
|
|
1996
|
+
"__vitest_dragAndDrop",
|
|
1997
|
+
"__vitest_hover",
|
|
1998
|
+
"__vitest_upload",
|
|
1999
|
+
"__vitest_tab",
|
|
2000
|
+
"__vitest_keyboard",
|
|
2001
|
+
"__vitest_takeScreenshot"
|
|
2002
|
+
]);
|
|
1992
2003
|
class CommandsManager {
|
|
1993
2004
|
_listeners = [];
|
|
1994
2005
|
onCommand(listener) {
|
|
@@ -2001,6 +2012,9 @@ class CommandsManager {
|
|
|
2001
2012
|
const { sessionId, traces: traces2 } = getBrowserState();
|
|
2002
2013
|
const filepath = state.filepath || ((_b = (_a = state.current) == null ? void 0 : _a.file) == null ? void 0 : _b.filepath);
|
|
2003
2014
|
args = args.filter((arg) => arg !== void 0);
|
|
2015
|
+
const actionTraceGroupName = ACTION_TRACE_COMMANDS.has(command) ? command : void 0;
|
|
2016
|
+
const currentTest = getWorkerState().current;
|
|
2017
|
+
const shouldMarkTrace = actionTraceGroupName && !!currentTest && getBrowserState().activeTraceTaskIds.has(currentTest.id);
|
|
2004
2018
|
if (this._listeners.length) {
|
|
2005
2019
|
await Promise.all(this._listeners.map((listener) => listener(command, args)));
|
|
2006
2020
|
}
|
|
@@ -2012,13 +2026,37 @@ class CommandsManager {
|
|
|
2012
2026
|
"code.file.path": filepath
|
|
2013
2027
|
}
|
|
2014
2028
|
},
|
|
2015
|
-
|
|
2029
|
+
async () => {
|
|
2016
2030
|
var _a2;
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2031
|
+
if (shouldMarkTrace) {
|
|
2032
|
+
await rpc2.triggerCommand(
|
|
2033
|
+
sessionId,
|
|
2034
|
+
"__vitest_groupTraceStart",
|
|
2035
|
+
filepath,
|
|
2036
|
+
[{
|
|
2037
|
+
name: actionTraceGroupName,
|
|
2038
|
+
stack: clientError.stack
|
|
2039
|
+
}]
|
|
2040
|
+
);
|
|
2041
|
+
}
|
|
2042
|
+
try {
|
|
2043
|
+
return await rpc2.triggerCommand(sessionId, command, filepath, args);
|
|
2044
|
+
} catch (err) {
|
|
2045
|
+
clientError.message = err.message;
|
|
2046
|
+
clientError.name = err.name;
|
|
2047
|
+
clientError.stack = (_a2 = clientError.stack) == null ? void 0 : _a2.replace(clientError.message, err.message);
|
|
2048
|
+
throw clientError;
|
|
2049
|
+
} finally {
|
|
2050
|
+
if (shouldMarkTrace) {
|
|
2051
|
+
await rpc2.triggerCommand(
|
|
2052
|
+
sessionId,
|
|
2053
|
+
"__vitest_groupTraceEnd",
|
|
2054
|
+
filepath,
|
|
2055
|
+
[]
|
|
2056
|
+
);
|
|
2057
|
+
}
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2022
2060
|
);
|
|
2023
2061
|
}
|
|
2024
2062
|
}
|
|
@@ -2098,6 +2136,7 @@ const url = new URL(location.href);
|
|
|
2098
2136
|
const iframeId = url.searchParams.get("iframeId");
|
|
2099
2137
|
const commands = new CommandsManager();
|
|
2100
2138
|
getBrowserState().commands = commands;
|
|
2139
|
+
getBrowserState().activeTraceTaskIds = /* @__PURE__ */ new Set();
|
|
2101
2140
|
getBrowserState().iframeId = iframeId;
|
|
2102
2141
|
let contextSwitched = false;
|
|
2103
2142
|
async function prepareTestEnvironment(options) {
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<link rel="icon" href="{__VITEST_FAVICON__}" type="image/svg+xml">
|
|
6
6
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
7
7
|
<title>Vitest Browser Tester</title>
|
|
8
|
-
<script type="module" crossorigin src="/__vitest_browser__/tester-
|
|
8
|
+
<script type="module" crossorigin src="/__vitest_browser__/tester-DVQLxxE-.js"></script>
|
|
9
9
|
<link rel="modulepreload" crossorigin href="/__vitest_browser__/utils-C2ISqq1C.js">
|
|
10
10
|
</head>
|
|
11
11
|
<body>
|
package/dist/context.js
CHANGED
|
@@ -461,6 +461,34 @@ const page = {
|
|
|
461
461
|
/** TODO */
|
|
462
462
|
)], error));
|
|
463
463
|
},
|
|
464
|
+
mark(name, bodyOrOptions, options) {
|
|
465
|
+
const currentTest = getWorkerState().current;
|
|
466
|
+
const hasActiveTrace = !!currentTest && getBrowserState().activeTraceTaskIds.has(currentTest.id);
|
|
467
|
+
if (typeof bodyOrOptions === "function") {
|
|
468
|
+
return ensureAwaited(async (error) => {
|
|
469
|
+
if (hasActiveTrace) {
|
|
470
|
+
await triggerCommand("__vitest_groupTraceStart", [{
|
|
471
|
+
name,
|
|
472
|
+
stack: options?.stack ?? error?.stack
|
|
473
|
+
}], error);
|
|
474
|
+
}
|
|
475
|
+
try {
|
|
476
|
+
return await bodyOrOptions();
|
|
477
|
+
} finally {
|
|
478
|
+
if (hasActiveTrace) {
|
|
479
|
+
await triggerCommand("__vitest_groupTraceEnd", [], error);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
if (!hasActiveTrace) {
|
|
485
|
+
return Promise.resolve();
|
|
486
|
+
}
|
|
487
|
+
return ensureAwaited((error) => triggerCommand("__vitest_markTrace", [{
|
|
488
|
+
name,
|
|
489
|
+
stack: bodyOrOptions?.stack ?? error?.stack
|
|
490
|
+
}], error));
|
|
491
|
+
},
|
|
464
492
|
getByRole() {
|
|
465
493
|
throw new Error(`Method "getByRole" is not supported by the "${provider}" provider.`);
|
|
466
494
|
},
|
package/dist/expect-element.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{recordArtifact,expect,chai}from"vitest";import{getType}from"vitest/internal/browser";import{k as kAriaCheckedRoles,L as Locator,g as getAriaChecked,a as getAriaRole,b as getAriaDisabled,c as beginAriaCaches,e as endAriaCaches,i as isElementVisible$1,d as getElementAccessibleDescription,f as getElementAccessibleErrorMessage,h as getElementAccessibleName,j as cssEscape,l as convertToSelector,m as getBrowserState,p as processTimeoutOptions}from"./index-
|
|
1
|
+
import{recordArtifact,expect,chai}from"vitest";import{getType}from"vitest/internal/browser";import{k as kAriaCheckedRoles,L as Locator,g as getAriaChecked,a as getAriaRole,b as getAriaDisabled,c as beginAriaCaches,e as endAriaCaches,i as isElementVisible$1,d as getElementAccessibleDescription,f as getElementAccessibleErrorMessage,h as getElementAccessibleName,j as cssEscape,l as convertToSelector,m as getBrowserState,p as processTimeoutOptions,n as getWorkerState}from"./index-CDbEr3te.js";import{server}from"vitest/browser";function getAriaCheckedRoles(){return[...kAriaCheckedRoles]}function queryElementFromUserInput(h,W,G){return h instanceof Locator&&(h=h.query()),h==null?null:getElementFromUserInput(h,W,G)}function getElementFromUserInput(h,W,G){h instanceof Locator&&(h=h.element());let K=h?.ownerDocument?.defaultView||window;if(h instanceof K.HTMLElement||h instanceof K.SVGElement)return h;throw new UserInputElementTypeError(h,W,G)}function getNodeFromUserInput(h,W,G){h instanceof Locator&&(h=h.element());let K=h.ownerDocument?.defaultView||window;if(h instanceof K.Node)return h;throw new UserInputNodeTypeError(h,W,G)}function getMessage(h,W,G,K,q,J){return[`${W}\n`,`${G}:\n${h.utils.EXPECTED_COLOR(redent(display(h,K),2))}`,`${q}:\n${h.utils.RECEIVED_COLOR(redent(display(h,J),2))}`].join(`
|
|
2
2
|
`)}function redent(h,W){return indentString(stripIndent(h),W)}function indentString(h,W){return h.replace(/^(?!\s*$)/gm,` `.repeat(W))}function minIndent(h){let W=h.match(/^[ \t]*(?=\S)/gm);return W?W.reduce((h,W)=>Math.min(h,W.length),1/0):0}function stripIndent(h){let W=minIndent(h);if(W===0)return h;let G=RegExp(`^[ \\t]{${W}}`,`gm`);return h.replace(G,``)}function display(h,W){return typeof W==`string`?W:h.utils.stringify(W)}function toSentence(h,{wordConnector:W=`, `,lastWordConnector:G=` and `}={}){return[h.slice(0,-1).join(W),h.at(-1)].join(h.length>1?G:``)}class GenericTypeError extends Error{constructor(h,W,G,K){super(),Error.captureStackTrace&&Error.captureStackTrace(this,G);let q=``;try{q=K.utils.printWithType(`Received`,W,K.utils.printReceived)}catch{}this.message=[K.utils.matcherHint(`${K.isNot?`.not`:``}.${G.name}`,`received`,``),``,`${K.utils.RECEIVED_COLOR(`received`)} value must ${h} or a Locator that returns ${h}.`,q].join(`
|
|
3
3
|
`)}}class UserInputElementTypeError extends GenericTypeError{constructor(h,W,G){super(`an HTMLElement or an SVGElement`,h,W,G)}}class UserInputNodeTypeError extends GenericTypeError{constructor(h,W,G){super(`a Node`,h,W,G)}}function getTag(h){return h instanceof HTMLFormElement?`FORM`:h.tagName.toUpperCase()}function isInputElement(h){return getTag(h)===`INPUT`}function getSingleElementValue(h){if(h)switch(getTag(h)){case`INPUT`:return getInputValue(h);case`SELECT`:return getSelectValue(h);default:return h.value??getAccessibleValue(h)}}function getSelectValue({multiple:h,options:W}){let G=[...W].filter(h=>h.selected);if(h)return[...G].map(h=>h.value);if(G.length!==0)return G[0].value}function getInputValue(h){switch(h.type){case`number`:return h.value===``?null:Number(h.value);case`checkbox`:return h.checked;default:return h.value}}const rolesSupportingValues=[`meter`,`progressbar`,`slider`,`spinbutton`];function getAccessibleValue(h){if(rolesSupportingValues.includes(h.getAttribute(`role`)||``))return Number(h.getAttribute(`aria-valuenow`))}function normalize(h){return h.replace(/\s+/g,` `).trim()}function matches(h,W){return W instanceof RegExp?W.test(h):h.includes(String(W))}function arrayAsSetComparison(h,W){if(Array.isArray(h)&&Array.isArray(W)){let G=new Set(W);for(let W of new Set(h))if(!G.has(W))return!1;return!0}}const supportedRoles=getAriaCheckedRoles();function toBeChecked(h){let W=getElementFromUserInput(h,toBeChecked,this);if(!(isInputElement(W)&&[`checkbox`,`radio`].includes(W.type))&&!(supportedRoles.includes(getAriaRole(W)||``)&&[`true`,`false`].includes(W.getAttribute(`aria-checked`)||``)))return{pass:!1,message:()=>`only inputs with type="checkbox" or type="radio" or elements with ${supportedRolesSentence()} and a valid aria-checked attribute can be used with .toBeChecked(). Use .toHaveValue() instead`};let G=getAriaChecked(W)===!0;return{pass:G,message:()=>{let h=G?`is`:`is not`;return[this.utils.matcherHint(`${this.isNot?`.not`:``}.toBeChecked`,`element`,``),``,`Received element ${h} checked:`,` ${this.utils.printReceived(W.cloneNode(!1))}`].join(`
|
|
4
4
|
`)}}}function supportedRolesSentence(){return toSentence(supportedRoles.map(h=>`role="${h}"`),{lastWordConnector:` or `})}function toBeEmptyDOMElement(h){let W=getElementFromUserInput(h,toBeEmptyDOMElement,this);return{pass:isEmptyElement(W),message:()=>[this.utils.matcherHint(`${this.isNot?`.not`:``}.toBeEmptyDOMElement`,`element`,``),``,`Received:`,` ${this.utils.printReceived(W.innerHTML)}`].join(`
|
|
@@ -24,4 +24,4 @@ import{recordArtifact,expect,chai}from"vitest";import{getType}from"vitest/intern
|
|
|
24
24
|
|
|
25
25
|
`)}}}function getStyleFromObjectCSS(h){let W=browser===`chrome`||browser===`chromium`?document:document.implementation.createHTMLDocument(``),G=W.createElement(`div`);W.body.appendChild(G);let K=Object.keys(h);K.forEach(W=>{G.style[W]=h[W]});let q={},J=window.getComputedStyle(G);return K.forEach(h=>{let W=(usedValuesProps.has(h)?G.style:J)[h];W!=null&&(q[h]=W)}),G.remove(),q}function computeCSSStyleDeclaration(h){let W=browser===`chrome`||browser===`chromium`||browser===`webkit`?document:document.implementation.createHTMLDocument(``),G=W.createElement(`div`);G.setAttribute(`style`,h.replace(/\n/g,``)),W.body.appendChild(G);let K=window.getComputedStyle(G),q=Array.from(G.style).reduce((h,W)=>(h[W]=usedValuesProps.has(W)?G.style.getPropertyValue(W):K.getPropertyValue(W),h),{});return G.remove(),q}function printoutObjectStyles(h){return Object.keys(h).sort().map(W=>`${W}: ${h[W]};`).join(`
|
|
26
26
|
`)}function isSubset(h,W,G,K){let q=Object.keys(h);return q.length?q.every(q=>{let J=h[q],Y=q.startsWith(`--`),X=[q];return Y||X.push(q.toLowerCase()),X.some(h=>{let Y=K.has(q)&&usedValuesProps.has(q)?W.style:G;return Y[h]===J||Y.getPropertyValue(h)===J})}):!1}function toHaveTextContent(h,W,G={normalizeWhitespace:!0}){let K=getNodeFromUserInput(h,toHaveTextContent,this),q=G.normalizeWhitespace?normalize(K.textContent||``):(K.textContent||``).replace(/\u00A0/g,` `),J=q!==``&&W===``;return{pass:!J&&matches(q,W),message:()=>{let h=this.isNot?`not to`:`to`;return getMessage(this,this.utils.matcherHint(`${this.isNot?`.not`:``}.toHaveTextContent`,`element`,``),J?`Checking with empty string will always match, use .toBeEmptyDOMElement() instead`:`Expected element ${h} have text content`,W,`Received`,q)}}}function toHaveValue(h,W){let G=getElementFromUserInput(h,toHaveValue,this);if(isInputElement(G)&&[`checkbox`,`radio`].includes(G.type))throw Error(`input with type=checkbox or type=radio cannot be used with .toHaveValue(). Use .toBeChecked() for type=checkbox or .toHaveFormValues() instead`);let K=getSingleElementValue(G),q=W!==void 0,J=W,Y=K;return W==K&&W!==K&&(J=`${W} (${typeof W})`,Y=`${K} (${typeof K})`),{pass:q?this.equals(K,W,[arrayAsSetComparison,...this.customTesters]):!!K,message:()=>{let h=this.isNot?`not to`:`to`,G=this.utils.matcherHint(`${this.isNot?`.not`:``}.toHaveValue`,`element`,W);return getMessage(this,G,`Expected the element ${h} have value`,q?J:`(any)`,`Received`,Y)}}}const counters=new Map([]);async function toMatchScreenshot(W,G,K=typeof G==`object`?G:{}){if(this.isNot)throw Error(`'toMatchScreenshot' cannot be used with "not"`);if(this.task===void 0||this.currentTestName===void 0)throw Error(`'toMatchScreenshot' cannot be used without test context`);let q=`${this.task.result?.repeatCount??0}${this.testPath}${this.currentTestName}`,J=counters.get(q);J===void 0&&(J={current:0},counters.set(q,J)),J.current+=1;let Y=typeof G==`string`?G:`${this.currentTestName} ${J.current}`,[X,...Z]=await Promise.all([convertToSelector(W,K),...K.screenshotOptions&&`mask`in K.screenshotOptions?K.screenshotOptions.mask.map(h=>convertToSelector(h,K)):[]]),Q=K.screenshotOptions&&`mask`in K.screenshotOptions?{...K,screenshotOptions:{...K.screenshotOptions,mask:Z}}:K,$=await getBrowserState().commands.triggerCommand(`__vitest_screenshotMatcher`,[Y,this.currentTestName,{element:X,...Q}]);if($.pass===!1){let W=[];$.reference&&W.push({name:`reference`,...$.reference}),$.actual&&W.push({name:`actual`,...$.actual}),$.diff&&W.push({name:`diff`,...$.diff}),W.length>0&&await recordArtifact(this.task,{type:`internal:toMatchScreenshot`,kind:`visual-regression`,message:$.message,attachments:W})}return{pass:$.pass,message:()=>$.pass?``:[this.utils.matcherHint(`toMatchScreenshot`,`element`,``),``,$.message,$.reference?`\nReference screenshot:\n ${this.utils.EXPECTED_COLOR($.reference.path)}`:null,$.actual?`\nActual screenshot:\n ${this.utils.RECEIVED_COLOR($.actual.path)}`:null,$.diff?this.utils.DIM_COLOR(`\nDiff image:\n ${$.diff.path}`):null,``].filter(h=>h!==null).join(`
|
|
27
|
-
`)}}const matchers={toBeDisabled,toBeEnabled,toBeEmptyDOMElement,toBeInTheDocument,toBeInViewport,toBeInvalid,toBeRequired,toBeValid,toBeVisible,toContainElement,toContainHTML,toHaveAccessibleDescription,toHaveAccessibleErrorMessage,toHaveAccessibleName,toHaveAttribute,toHaveClass,toHaveFocus,toHaveFormValues,toHaveStyle,toHaveTextContent,toHaveValue,toHaveDisplayValue,toBeChecked,toBePartiallyChecked,toHaveRole,toHaveSelection,toMatchScreenshot},kLocator=Symbol.for(`$$vitest:locator`);function element(h,q){if(h!=null&&!(h instanceof HTMLElement)&&!(h instanceof SVGElement)&&!(kLocator in h))throw Error(`Invalid element or locator: ${h}. Expected an instance of HTMLElement, SVGElement or Locator, received ${getType(h)}`);let J=expect.poll(function(){if(h instanceof Element||h==null)return h;let W=chai.util.flag(this,`negate`),K=chai.util.flag(this,`_name`);if(W&&K===`toBeInTheDocument`)return h.query();if(K===`toHaveLength`)return h.elements();if(K===`toMatchScreenshot`&&!chai.util.flag(this,`_poll.assert_once`)&&chai.util.flag(this,`_poll.assert_once`,!0),chai.util.flag(this,`_isLastPollAttempt`))return h.element();let q=h.query();if(!q)throw Error(`Cannot find element with locator: ${JSON.stringify(h)}`);return q},processTimeoutOptions(q));
|
|
27
|
+
`)}}const matchers={toBeDisabled,toBeEnabled,toBeEmptyDOMElement,toBeInTheDocument,toBeInViewport,toBeInvalid,toBeRequired,toBeValid,toBeVisible,toContainElement,toContainHTML,toHaveAccessibleDescription,toHaveAccessibleErrorMessage,toHaveAccessibleName,toHaveAttribute,toHaveClass,toHaveFocus,toHaveFormValues,toHaveStyle,toHaveTextContent,toHaveValue,toHaveDisplayValue,toBeChecked,toBePartiallyChecked,toHaveRole,toHaveSelection,toMatchScreenshot},kLocator=Symbol.for(`$$vitest:locator`);function element(h,q){if(h!=null&&!(h instanceof HTMLElement)&&!(h instanceof SVGElement)&&!(kLocator in h))throw Error(`Invalid element or locator: ${h}. Expected an instance of HTMLElement, SVGElement or Locator, received ${getType(h)}`);let J=expect.poll(function(){if(h instanceof Element||h==null)return h;let W=chai.util.flag(this,`negate`),K=chai.util.flag(this,`_name`);if(W&&K===`toBeInTheDocument`)return h.query();if(K===`toHaveLength`)return h.elements();if(K===`toMatchScreenshot`&&!chai.util.flag(this,`_poll.assert_once`)&&chai.util.flag(this,`_poll.assert_once`,!0),chai.util.flag(this,`_isLastPollAttempt`))return h.element();let q=h.query();if(!q)throw Error(`Cannot find element with locator: ${JSON.stringify(h)}`);return q},processTimeoutOptions(q));chai.util.flag(J,`_poll.element`,!0);let Y=getWorkerState().current;if(Y&&getBrowserState().activeTraceTaskIds.has(Y.id)){let W=Error(`__vitest_mark_trace__`);chai.util.flag(J,`_poll.onSettled`,async K=>{let q=chai.util.flag(K.assertion,`negate`),J=chai.util.flag(K.assertion,`_name`)||`<unknown>`,Y=`expect.element().${q?`not.`:``}${J}`,X=K.status===`fail`?`${Y} [ERROR]`:Y,Z=!h||h instanceof Element?void 0:h.selector;await getBrowserState().commands.triggerCommand(`__vitest_markTrace`,[{name:X,selector:Z,stack:W.stack}],W)})}return J}expect.extend(matchers),expect.element=element;
|
|
@@ -3,5 +3,5 @@ import{server,page,utils}from"vitest/browser";import{__INTERNAL,getSafeTimers}fr
|
|
|
3
3
|
`).replace(/[\u200b\u00ad]/g,``).replace(/\s\s*/g,` `)).join(`\xA0`).trim()}function queryInAriaOwned(e,T){let E=[...e.querySelectorAll(T)];for(let D of getIdRefs(e,e.getAttribute(`aria-owns`)))D.matches(T)&&E.push(D),E.push(...D.querySelectorAll(T));return E}function getPseudoContent(e,T){let E=T===`::before`?cachePseudoContentBefore:cachePseudoContentAfter;if(E?.has(e))return E?.get(e)||``;let D=getPseudoContentImpl(getElementComputedStyle(e,T));return E&&E.set(e,D),D}function getPseudoContentImpl(e){if(!e)return``;let T=e.content;if(T[0]===`'`&&T[T.length-1]===`'`||T[0]===`"`&&T[T.length-1]===`"`){let E=T.substring(1,T.length-1);return(e.display||`inline`)===`inline`?E:` ${E} `}return``}function getAriaLabelledByElements(e){let T=e.getAttribute(`aria-labelledby`);return T===null?null:getIdRefs(e,T)}function allowsNameFromContent(e,T){let E=[`button`,`cell`,`checkbox`,`columnheader`,`gridcell`,`heading`,`link`,`menuitem`,`menuitemcheckbox`,`menuitemradio`,`option`,`radio`,`row`,`rowheader`,`switch`,`tab`,`tooltip`,`treeitem`].includes(e),D=T&&[``,`caption`,`code`,`contentinfo`,`definition`,`deletion`,`emphasis`,`insertion`,`list`,`listitem`,`mark`,`none`,`paragraph`,`presentation`,`region`,`row`,`rowgroup`,`section`,`strong`,`subscript`,`superscript`,`table`,`term`,`time`].includes(e);return E||D}function getElementAccessibleName(e,T){let E=T?cacheAccessibleNameHidden:cacheAccessibleName,D=E?.get(e);return D===void 0&&(D=``,[`caption`,`code`,`definition`,`deletion`,`emphasis`,`generic`,`insertion`,`mark`,`paragraph`,`presentation`,`strong`,`subscript`,`suggestion`,`superscript`,`term`,`time`].includes(getAriaRole(e)||``)||(D=asFlatString(getTextAlternativeInternal(e,{includeHidden:T,visitedElements:new Set,embeddedInDescribedBy:void 0,embeddedInLabelledBy:void 0,embeddedInLabel:void 0,embeddedInNativeTextAlternative:void 0,embeddedInTargetElement:`self`}))),E?.set(e,D)),D}function getElementAccessibleDescription(e,T){let E=cacheAccessibleDescription,D=E?.get(e);return D===void 0&&(D=``,D=e.hasAttribute(`aria-describedby`)?asFlatString(getIdRefs(e,e.getAttribute(`aria-describedby`)).map(e=>getTextAlternativeInternal(e,{includeHidden:T,visitedElements:new Set,embeddedInDescribedBy:{element:e,hidden:isElementHiddenForAria(e)}})).join(` `)):e.hasAttribute(`aria-description`)?asFlatString(e.getAttribute(`aria-description`)||``):asFlatString(e.getAttribute(`title`)||``),E?.set(e,D)),D}var kAriaInvalidRoles=[`application`,`checkbox`,`combobox`,`gridcell`,`listbox`,`radiogroup`,`slider`,`spinbutton`,`textbox`,`tree`,`columnheader`,`rowheader`,`searchbox`,`switch`,`treegrid`];function getAriaInvalid(e){let T=getAriaRole(e)||``;if(!T||!kAriaInvalidRoles.includes(T))return`false`;let E=e.getAttribute(`aria-invalid`);return!E||E.trim()===``||E.toLocaleLowerCase()===`false`?`false`:E===`true`||E===`grammar`||E===`spelling`?E:`true`}function getValidityInvalid(e){return`validity`in e?e.validity?.valid===!1:!1}function getElementAccessibleErrorMessage(e){let T=cacheAccessibleErrorMessage,E=cacheAccessibleErrorMessage?.get(e);if(E===void 0){E=``;let D=getAriaInvalid(e)!==`false`,O=getValidityInvalid(e);(D||O)&&(E=getIdRefs(e,e.getAttribute(`aria-errormessage`)).map(e=>asFlatString(getTextAlternativeInternal(e,{visitedElements:new Set,embeddedInDescribedBy:{element:e,hidden:isElementHiddenForAria(e)}}))).join(` `).trim()),T?.set(e,E)}return E}function getTextAlternativeInternal(e,T){if(T.visitedElements.has(e))return``;let E={...T,embeddedInTargetElement:T.embeddedInTargetElement===`self`?`descendant`:T.embeddedInTargetElement};if(!T.includeHidden){let E=!!T.embeddedInLabelledBy?.hidden||!!T.embeddedInDescribedBy?.hidden||!!T.embeddedInNativeTextAlternative?.hidden||!!T.embeddedInLabel?.hidden;if(isElementIgnoredForAria(e)||!E&&isElementHiddenForAria(e))return T.visitedElements.add(e),``}let D=getAriaLabelledByElements(e);if(!T.embeddedInLabelledBy){let e=(D||[]).map(e=>getTextAlternativeInternal(e,{...T,embeddedInLabelledBy:{element:e,hidden:isElementHiddenForAria(e)},embeddedInDescribedBy:void 0,embeddedInTargetElement:void 0,embeddedInLabel:void 0,embeddedInNativeTextAlternative:void 0})).join(` `);if(e)return e}let O=getAriaRole(e)||``,k=elementSafeTagName(e);if(T.embeddedInLabel||T.embeddedInLabelledBy||T.embeddedInTargetElement===`descendant`){let A=[...e.labels||[]].includes(e),j=(D||[]).includes(e);if(!A&&!j){if(O===`textbox`)return T.visitedElements.add(e),k===`INPUT`||k===`TEXTAREA`?e.value:e.textContent||``;if([`combobox`,`listbox`].includes(O)){T.visitedElements.add(e);let D;if(k===`SELECT`)D=[...e.selectedOptions],!D.length&&e.options.length&&D.push(e.options[0]);else{let T=O===`combobox`?queryInAriaOwned(e,`*`).find(e=>getAriaRole(e)===`listbox`):e;D=T?queryInAriaOwned(T,`[aria-selected="true"]`).filter(e=>getAriaRole(e)===`option`):[]}return!D.length&&k===`INPUT`?e.value:D.map(e=>getTextAlternativeInternal(e,E)).join(` `)}if([`progressbar`,`scrollbar`,`slider`,`spinbutton`,`meter`].includes(O))return T.visitedElements.add(e),e.hasAttribute(`aria-valuetext`)?e.getAttribute(`aria-valuetext`)||``:e.hasAttribute(`aria-valuenow`)?e.getAttribute(`aria-valuenow`)||``:e.getAttribute(`value`)||``;if([`menu`].includes(O))return T.visitedElements.add(e),``}}let A=e.getAttribute(`aria-label`)||``;if(trimFlatString(A))return T.visitedElements.add(e),A;if(![`presentation`,`none`].includes(O)){if(k===`INPUT`&&[`button`,`submit`,`reset`].includes(e.type)){T.visitedElements.add(e);let E=e.value||``;return trimFlatString(E)?E:e.type===`submit`?`Submit`:e.type===`reset`?`Reset`:e.getAttribute(`title`)||``}if(k===`INPUT`&&e.type===`image`){T.visitedElements.add(e);let E=e.labels||[];if(E.length&&!T.embeddedInLabelledBy)return getAccessibleNameFromAssociatedLabels(E,T);let D=e.getAttribute(`alt`)||``;if(trimFlatString(D))return D;let O=e.getAttribute(`title`)||``;return trimFlatString(O)?O:`Submit`}if(!D&&k===`BUTTON`){T.visitedElements.add(e);let E=e.labels||[];if(E.length)return getAccessibleNameFromAssociatedLabels(E,T)}if(!D&&k===`OUTPUT`){T.visitedElements.add(e);let E=e.labels||[];return E.length?getAccessibleNameFromAssociatedLabels(E,T):e.getAttribute(`title`)||``}if(!D&&(k===`TEXTAREA`||k===`SELECT`||k===`INPUT`)){T.visitedElements.add(e);let E=e.labels||[];if(E.length)return getAccessibleNameFromAssociatedLabels(E,T);let D=k===`INPUT`&&[`text`,`password`,`search`,`tel`,`email`,`url`].includes(e.type)||k===`TEXTAREA`,O=e.getAttribute(`placeholder`)||``,A=e.getAttribute(`title`)||``;return!D||A?A:O}if(!D&&k===`FIELDSET`){T.visitedElements.add(e);for(let T=e.firstElementChild;T;T=T.nextElementSibling)if(elementSafeTagName(T)===`LEGEND`)return getTextAlternativeInternal(T,{...E,embeddedInNativeTextAlternative:{element:T,hidden:isElementHiddenForAria(T)}});return e.getAttribute(`title`)||``}if(!D&&k===`FIGURE`){T.visitedElements.add(e);for(let T=e.firstElementChild;T;T=T.nextElementSibling)if(elementSafeTagName(T)===`FIGCAPTION`)return getTextAlternativeInternal(T,{...E,embeddedInNativeTextAlternative:{element:T,hidden:isElementHiddenForAria(T)}});return e.getAttribute(`title`)||``}if(k===`IMG`){T.visitedElements.add(e);let E=e.getAttribute(`alt`)||``;return trimFlatString(E)?E:e.getAttribute(`title`)||``}if(k===`TABLE`){T.visitedElements.add(e);for(let T=e.firstElementChild;T;T=T.nextElementSibling)if(elementSafeTagName(T)===`CAPTION`)return getTextAlternativeInternal(T,{...E,embeddedInNativeTextAlternative:{element:T,hidden:isElementHiddenForAria(T)}});let D=e.getAttribute(`summary`)||``;if(D)return D}if(k===`AREA`){T.visitedElements.add(e);let E=e.getAttribute(`alt`)||``;return trimFlatString(E)?E:e.getAttribute(`title`)||``}if(k===`SVG`||e.ownerSVGElement){T.visitedElements.add(e);for(let T=e.firstElementChild;T;T=T.nextElementSibling)if(elementSafeTagName(T)===`TITLE`&&T.ownerSVGElement)return getTextAlternativeInternal(T,{...E,embeddedInLabelledBy:{element:T,hidden:isElementHiddenForAria(T)}})}if(e.ownerSVGElement&&k===`A`){let E=e.getAttribute(`xlink:title`)||``;if(trimFlatString(E))return T.visitedElements.add(e),E}}let j=k===`SUMMARY`&&![`presentation`,`none`].includes(O);if(allowsNameFromContent(O,T.embeddedInTargetElement===`descendant`)||j||T.embeddedInLabelledBy||T.embeddedInDescribedBy||T.embeddedInLabel||T.embeddedInNativeTextAlternative){T.visitedElements.add(e);let D=innerAccumulatedElementText(e,E);if(T.embeddedInTargetElement===`self`?trimFlatString(D):D)return D}if(![`presentation`,`none`].includes(O)||k===`IFRAME`){T.visitedElements.add(e);let E=e.getAttribute(`title`)||``;if(trimFlatString(E))return E}return T.visitedElements.add(e),``}function innerAccumulatedElementText(e,T){let E=[],D=(e,D)=>{if(!(D&&e.assignedSlot))if(e.nodeType===1){let D=getElementComputedStyle(e)?.display||`inline`,O=getTextAlternativeInternal(e,T);(D!==`inline`||e.nodeName===`BR`)&&(O=` `+O+` `),E.push(O)}else e.nodeType===3&&E.push(e.textContent||``)};E.push(getPseudoContent(e,`::before`));let O=e.nodeName===`SLOT`?e.assignedNodes():[];if(O.length)for(let e of O)D(e,!1);else{for(let T=e.firstChild;T;T=T.nextSibling)D(T,!0);if(e.shadowRoot)for(let T=e.shadowRoot.firstChild;T;T=T.nextSibling)D(T,!0);for(let T of getIdRefs(e,e.getAttribute(`aria-owns`)))D(T,!0)}return E.push(getPseudoContent(e,`::after`)),E.join(``)}var kAriaSelectedRoles=[`gridcell`,`option`,`row`,`tab`,`rowheader`,`columnheader`,`treeitem`];function getAriaSelected(e){return elementSafeTagName(e)===`OPTION`?e.selected:kAriaSelectedRoles.includes(getAriaRole(e)||``)?getAriaBoolean(e.getAttribute(`aria-selected`))===!0:!1}var kAriaCheckedRoles=[`checkbox`,`menuitemcheckbox`,`option`,`radio`,`switch`,`menuitemradio`,`treeitem`];function getAriaChecked(e){let T=getChecked(e);return T===`error`?!1:T}function getChecked(e,T){let E=elementSafeTagName(e);if(E===`INPUT`&&e.indeterminate)return`mixed`;if(E===`INPUT`&&[`checkbox`,`radio`].includes(e.type))return e.checked;if(kAriaCheckedRoles.includes(getAriaRole(e)||``)){let T=e.getAttribute(`aria-checked`);return T===`true`?!0:T===`mixed`?`mixed`:!1}return`error`}var kAriaPressedRoles=[`button`];function getAriaPressed(e){if(kAriaPressedRoles.includes(getAriaRole(e)||``)){let T=e.getAttribute(`aria-pressed`);if(T===`true`)return!0;if(T===`mixed`)return`mixed`}return!1}var kAriaExpandedRoles=[`application`,`button`,`checkbox`,`combobox`,`gridcell`,`link`,`listbox`,`menuitem`,`row`,`rowheader`,`tab`,`treeitem`,`columnheader`,`menuitemcheckbox`,`menuitemradio`,`rowheader`,`switch`];function getAriaExpanded(e){if(elementSafeTagName(e)===`DETAILS`)return e.open;if(kAriaExpandedRoles.includes(getAriaRole(e)||``)){let T=e.getAttribute(`aria-expanded`);return T===null?`none`:T===`true`}return`none`}var kAriaLevelRoles=[`heading`,`listitem`,`row`,`treeitem`];function getAriaLevel(e){let T={H1:1,H2:2,H3:3,H4:4,H5:5,H6:6}[elementSafeTagName(e)];if(T)return T;if(kAriaLevelRoles.includes(getAriaRole(e)||``)){let T=e.getAttribute(`aria-level`),E=T===null?NaN:Number(T);if(Number.isInteger(E)&&E>=1)return E}return 0}var kAriaDisabledRoles=`application.button.composite.gridcell.group.input.link.menuitem.scrollbar.separator.tab.checkbox.columnheader.combobox.grid.listbox.menu.menubar.menuitemcheckbox.menuitemradio.option.radio.radiogroup.row.rowheader.searchbox.select.slider.spinbutton.switch.tablist.textbox.toolbar.tree.treegrid.treeitem`.split(`.`);function getAriaDisabled(e){return isNativelyDisabled(e)||hasExplicitAriaDisabled(e)}function isNativelyDisabled(e){return[`BUTTON`,`INPUT`,`SELECT`,`TEXTAREA`,`OPTION`,`OPTGROUP`].includes(e.tagName)&&(e.hasAttribute(`disabled`)||belongsToDisabledFieldSet(e))}function belongsToDisabledFieldSet(e){let T=e?.closest(`FIELDSET[DISABLED]`);if(!T)return!1;let E=T.querySelector(`:scope > LEGEND`);return!E||!E.contains(e)}function hasExplicitAriaDisabled(e){if(!e)return!1;if(kAriaDisabledRoles.includes(getAriaRole(e)||``)){let T=(e.getAttribute(`aria-disabled`)||``).toLowerCase();if(T===`true`)return!0;if(T===`false`)return!1}return hasExplicitAriaDisabled(parentElementOrShadowHost(e))}function getAccessibleNameFromAssociatedLabels(e,T){return[...e].map(e=>getTextAlternativeInternal(e,{...T,embeddedInLabel:{element:e,hidden:isElementHiddenForAria(e)},embeddedInNativeTextAlternative:void 0,embeddedInLabelledBy:void 0,embeddedInDescribedBy:void 0,embeddedInTargetElement:void 0})).filter(e=>!!e).join(` `)}var cacheAccessibleName,cacheAccessibleNameHidden,cacheAccessibleErrorMessage,cacheAccessibleDescription,cacheIsHidden,cachePseudoContentBefore,cachePseudoContentAfter,cachesCounter=0;function beginAriaCaches(){++cachesCounter,cacheAccessibleName??=new Map,cacheAccessibleNameHidden??=new Map,cacheAccessibleDescription??=new Map,cacheAccessibleErrorMessage??=new Map,cacheIsHidden??=new Map,cachePseudoContentBefore??=new Map,cachePseudoContentAfter??=new Map}function endAriaCaches(){--cachesCounter||(cacheAccessibleName=void 0,cacheAccessibleNameHidden=void 0,cacheAccessibleDescription=void 0,cacheAccessibleErrorMessage=void 0,cacheIsHidden=void 0,cachePseudoContentBefore=void 0,cachePseudoContentAfter=void 0)}function matchesAttributePart(e,T){let E=typeof e==`string`&&!T.caseSensitive?e.toUpperCase():e,D=typeof T.value==`string`&&!T.caseSensitive?T.value.toUpperCase():T.value;return T.op===`<truthy>`?!!E:T.op===`=`?D instanceof RegExp?typeof E==`string`&&!!E.match(D):E===D:typeof E!=`string`||typeof D!=`string`?!1:T.op===`*=`?E.includes(D):T.op===`^=`?E.startsWith(D):T.op===`$=`?E.endsWith(D):T.op===`|=`?E===D||E.startsWith(`${D}-`):T.op===`~=`?E.split(` `).includes(D):!1}function shouldSkipForTextMatching(e){let T=e.ownerDocument;return e.nodeName===`SCRIPT`||e.nodeName===`NOSCRIPT`||e.nodeName===`STYLE`||T.head&&T.head.contains(e)}function elementText(e,T){let E=e.get(T);if(E===void 0){if(E={full:``,normalized:``,immediate:[]},!shouldSkipForTextMatching(T)){let D=``;if(T instanceof HTMLInputElement&&(T.type===`submit`||T.type===`button`))E={full:T.value,normalized:normalizeWhiteSpace(T.value),immediate:[T.value]};else{for(let O=T.firstChild;O;O=O.nextSibling)O.nodeType===Node.TEXT_NODE?(E.full+=O.nodeValue||``,D+=O.nodeValue||``):(D&&E.immediate.push(D),D=``,O.nodeType===Node.ELEMENT_NODE&&(E.full+=elementText(e,O).full));D&&E.immediate.push(D),T.shadowRoot&&(E.full+=elementText(e,T.shadowRoot).full),E.full&&(E.normalized=normalizeWhiteSpace(E.full))}}e.set(T,E)}return E}function elementMatchesText(e,T,E){if(shouldSkipForTextMatching(T)||!E(elementText(e,T)))return`none`;for(let D=T.firstChild;D;D=D.nextSibling)if(D.nodeType===Node.ELEMENT_NODE&&E(elementText(e,D)))return`selfAndChildren`;return T.shadowRoot&&E(elementText(e,T.shadowRoot))?`selfAndChildren`:`self`}function getElementLabels(e,T){let E=getAriaLabelledByElements(T);if(E)return E.map(T=>elementText(e,T));let D=T.getAttribute(`aria-label`);if(D!==null&&D.trim())return[{full:D,normalized:normalizeWhiteSpace(D),immediate:[D]}];let O=T.nodeName===`INPUT`&&T.type!==`hidden`;if([`BUTTON`,`METER`,`OUTPUT`,`PROGRESS`,`SELECT`,`TEXTAREA`].includes(T.nodeName)||O){let E=T.labels;if(E)return[...E].map(T=>elementText(e,T))}return[]}var kSupportedAttributes=[`selected`,`checked`,`pressed`,`expanded`,`level`,`disabled`,`name`,`include-hidden`];kSupportedAttributes.sort();function validateSupportedRole(e,T,E){if(!T.includes(E))throw Error(`"${e}" attribute is only supported for roles: ${T.slice().sort().map(e=>`"${e}"`).join(`, `)}`)}function validateSupportedValues(e,T){if(e.op!==`<truthy>`&&!T.includes(e.value))throw Error(`"${e.name}" must be one of ${T.map(e=>JSON.stringify(e)).join(`, `)}`)}function validateSupportedOp(e,T){if(!T.includes(e.op))throw Error(`"${e.name}" does not support "${e.op}" matcher`)}function validateAttributes(e,T){let E={role:T};for(let D of e)switch(D.name){case`checked`:validateSupportedRole(D.name,kAriaCheckedRoles,T),validateSupportedValues(D,[!0,!1,`mixed`]),validateSupportedOp(D,[`<truthy>`,`=`]),E.checked=D.op===`<truthy>`?!0:D.value;break;case`pressed`:validateSupportedRole(D.name,kAriaPressedRoles,T),validateSupportedValues(D,[!0,!1,`mixed`]),validateSupportedOp(D,[`<truthy>`,`=`]),E.pressed=D.op===`<truthy>`?!0:D.value;break;case`selected`:validateSupportedRole(D.name,kAriaSelectedRoles,T),validateSupportedValues(D,[!0,!1]),validateSupportedOp(D,[`<truthy>`,`=`]),E.selected=D.op===`<truthy>`?!0:D.value;break;case`expanded`:validateSupportedRole(D.name,kAriaExpandedRoles,T),validateSupportedValues(D,[!0,!1]),validateSupportedOp(D,[`<truthy>`,`=`]),E.expanded=D.op===`<truthy>`?!0:D.value;break;case`level`:if(validateSupportedRole(D.name,kAriaLevelRoles,T),typeof D.value==`string`&&(D.value=+D.value),D.op!==`=`||typeof D.value!=`number`||Number.isNaN(D.value))throw Error(`"level" attribute must be compared to a number`);E.level=D.value;break;case`disabled`:validateSupportedValues(D,[!0,!1]),validateSupportedOp(D,[`<truthy>`,`=`]),E.disabled=D.op===`<truthy>`?!0:D.value;break;case`name`:if(D.op===`<truthy>`)throw Error(`"name" attribute must have a value`);if(typeof D.value!=`string`&&!(D.value instanceof RegExp))throw TypeError(`"name" attribute must be a string or a regular expression`);E.name=D.value,E.nameOp=D.op,E.exact=D.caseSensitive;break;case`include-hidden`:validateSupportedValues(D,[!0,!1]),validateSupportedOp(D,[`<truthy>`,`=`]),E.includeHidden=D.op===`<truthy>`?!0:D.value;break;default:throw Error(`Unknown attribute "${D.name}", must be one of ${kSupportedAttributes.map(e=>`"${e}"`).join(`, `)}.`)}return E}function queryRole(e,T,E){let D=[],O=e=>{if(getAriaRole(e)===T.role&&!(T.selected!==void 0&&getAriaSelected(e)!==T.selected)&&!(T.checked!==void 0&&getAriaChecked(e)!==T.checked)&&!(T.pressed!==void 0&&getAriaPressed(e)!==T.pressed)&&!(T.expanded!==void 0&&getAriaExpanded(e)!==T.expanded)&&!(T.level!==void 0&&getAriaLevel(e)!==T.level)&&!(T.disabled!==void 0&&getAriaDisabled(e)!==T.disabled)&&!(!T.includeHidden&&isElementHiddenForAria(e))){if(T.name!==void 0){let D=normalizeWhiteSpace(getElementAccessibleName(e,!!T.includeHidden));if(typeof T.name==`string`&&(T.name=normalizeWhiteSpace(T.name)),E&&!T.exact&&T.nameOp===`=`&&(T.nameOp=`*=`),!matchesAttributePart(D,{op:T.nameOp||`=`,value:T.name,caseSensitive:!!T.exact}))return}D.push(e)}},k=e=>{let T=[];e.shadowRoot&&T.push(e.shadowRoot);for(let E of e.querySelectorAll(`*`))O(E),E.shadowRoot&&T.push(E.shadowRoot);T.forEach(k)};return k(e),D}function createRoleEngine(e){return{queryAll:(T,E)=>{let D=parseAttributeSelector(E),O=D.name.toLowerCase();if(!O)throw Error(`Role must not be empty`);let k=validateAttributes(D.attributes,O);beginAriaCaches();try{return queryRole(T,k,e)}finally{endAriaCaches()}}}}function asLocator(e,T,E=!1){return asLocators(e,T,E)[0]}function asLocators(e,T,E=!1,D=20,O){try{return innerAsLocators(new generators[e](O),parseSelector(T),E,D)}catch{return[T]}}function innerAsLocators(e,T,E=!1,D=20){let O=[...T.parts];for(let e=0;e<O.length-1;e++)if(O[e].name===`nth`&&O[e+1].name===`internal:control`&&O[e+1].body===`enter-frame`){let[T]=O.splice(e,1);O.splice(e+1,0,T)}let k=[],A=E?`frame-locator`:`page`;for(let T=0;T<O.length;T++){let E=O[T],j=A;if(A=`locator`,E.name===`nth`){E.body===`0`?k.push([e.generateLocator(j,`first`,``),e.generateLocator(j,`nth`,`0`)]):E.body===`-1`?k.push([e.generateLocator(j,`last`,``),e.generateLocator(j,`nth`,`-1`)]):k.push([e.generateLocator(j,`nth`,E.body)]);continue}if(E.name===`internal:text`){let{exact:T,text:D}=detectExact(E.body);k.push([e.generateLocator(j,`text`,D,{exact:T})]);continue}if(E.name===`internal:has-text`){let{exact:T,text:D}=detectExact(E.body);if(!T){k.push([e.generateLocator(j,`has-text`,D,{exact:T})]);continue}}if(E.name===`internal:has-not-text`){let{exact:T,text:D}=detectExact(E.body);if(!T){k.push([e.generateLocator(j,`has-not-text`,D,{exact:T})]);continue}}if(E.name===`internal:has`){let T=innerAsLocators(e,E.body.parsed,!1,D);k.push(T.map(T=>e.generateLocator(j,`has`,T)));continue}if(E.name===`internal:has-not`){let T=innerAsLocators(e,E.body.parsed,!1,D);k.push(T.map(T=>e.generateLocator(j,`hasNot`,T)));continue}if(E.name===`internal:and`){let T=innerAsLocators(e,E.body.parsed,!1,D);k.push(T.map(T=>e.generateLocator(j,`and`,T)));continue}if(E.name===`internal:or`){let T=innerAsLocators(e,E.body.parsed,!1,D);k.push(T.map(T=>e.generateLocator(j,`or`,T)));continue}if(E.name===`internal:chain`){let T=innerAsLocators(e,E.body.parsed,!1,D);k.push(T.map(T=>e.generateLocator(j,`chain`,T)));continue}if(E.name===`internal:label`){let{exact:T,text:D}=detectExact(E.body);k.push([e.generateLocator(j,`label`,D,{exact:T})]);continue}if(E.name===`internal:role`){let T=parseAttributeSelector(E.body),D={attrs:[]};for(let e of T.attributes)e.name===`name`?(D.exact=e.caseSensitive,D.name=e.value):(e.name===`level`&&typeof e.value==`string`&&(e.value=+e.value),D.attrs.push({name:e.name===`include-hidden`?`includeHidden`:e.name,value:e.value}));k.push([e.generateLocator(j,`role`,T.name,D)]);continue}if(E.name===`internal:testid`){let{value:T}=parseAttributeSelector(E.body).attributes[0];k.push([e.generateLocator(j,`test-id`,T)]);continue}if(E.name===`internal:attr`){let{name:T,value:D,caseSensitive:O}=parseAttributeSelector(E.body).attributes[0],A=D,M=!!O;if(T===`placeholder`){k.push([e.generateLocator(j,`placeholder`,A,{exact:M})]);continue}if(T===`alt`){k.push([e.generateLocator(j,`alt`,A,{exact:M})]);continue}if(T===`title`){k.push([e.generateLocator(j,`title`,A,{exact:M})]);continue}}let M=`default`,N=O[T+1];N&&N.name===`internal:control`&&N.body===`enter-frame`&&(M=`frame`,A=`frame-locator`,T++);let P=stringifySelector({parts:[E]}),F=e.generateLocator(j,M,P);if(M===`default`&&N&&[`internal:has-text`,`internal:has-not-text`].includes(N.name)){let{exact:E,text:D}=detectExact(N.body);if(!E){let O=e.generateLocator(`locator`,N.name===`internal:has-text`?`has-text`:`has-not-text`,D,{exact:E}),A={};N.name===`internal:has-text`?A.hasText=D:A.hasNotText=D;let M=e.generateLocator(j,`default`,P,A);k.push([e.chainLocators([F,O]),M]),T++;continue}}let I;if([`xpath`,`css`].includes(E.name)){let T=stringifySelector({parts:[E]},!0);I=e.generateLocator(j,M,T)}k.push([F,I].filter(Boolean))}return combineTokens(e,k,D)}function combineTokens(e,T,E){let D=T.map(()=>``),O=[],k=A=>{if(A===T.length)return O.push(e.chainLocators(D)),D.length<E;for(let e of T[A])if(D[A]=e,!k(A+1))return!1;return!0};return k(0),O}function detectExact(e){let T=!1,E=e.match(/^\/(.*)\/([igm]*)$/);return E?{text:new RegExp(E[1],E[2])}:(e.endsWith(`"`)?(e=JSON.parse(e),T=!0):e.endsWith(`"s`)?(e=JSON.parse(e.substring(0,e.length-1)),T=!0):e.endsWith(`"i`)&&(e=JSON.parse(e.substring(0,e.length-1)),T=!1),{exact:T,text:e})}var JavaScriptLocatorFactory=class{constructor(e){this.preferredQuote=e}generateLocator(e,T,E,D={}){switch(T){case`default`:return D.hasText===void 0?D.hasNotText===void 0?`locator(${this.quote(E)})`:`locator(${this.quote(E)}, { hasNotText: ${this.toHasText(D.hasNotText)} })`:`locator(${this.quote(E)}, { hasText: ${this.toHasText(D.hasText)} })`;case`frame`:return`frameLocator(${this.quote(E)})`;case`nth`:return`nth(${E})`;case`first`:return`first()`;case`last`:return`last()`;case`role`:{let e=[];isRegExp(D.name)?e.push(`name: ${this.regexToSourceString(D.name)}`):typeof D.name==`string`&&(e.push(`name: ${this.quote(D.name)}`),D.exact&&e.push(`exact: true`));for(let{name:T,value:E}of D.attrs)e.push(`${T}: ${typeof E==`string`?this.quote(E):E}`);let T=e.length?`, { ${e.join(`, `)} }`:``;return`getByRole(${this.quote(E)}${T})`}case`has-text`:return`filter({ hasText: ${this.toHasText(E)} })`;case`has-not-text`:return`filter({ hasNotText: ${this.toHasText(E)} })`;case`has`:return`filter({ has: ${E} })`;case`hasNot`:return`filter({ hasNot: ${E} })`;case`and`:return`and(${E})`;case`or`:return`or(${E})`;case`chain`:return`locator(${E})`;case`test-id`:{let e=this.toTestIdValue(E);return e.startsWith(`'__vitest_`)&&e.endsWith(`__'`)?`page`:`getByTestId(${e})`}case`text`:return this.toCallWithExact(`getByText`,E,!!D.exact);case`alt`:return this.toCallWithExact(`getByAltText`,E,!!D.exact);case`placeholder`:return this.toCallWithExact(`getByPlaceholder`,E,!!D.exact);case`label`:return this.toCallWithExact(`getByLabel`,E,!!D.exact);case`title`:return this.toCallWithExact(`getByTitle`,E,!!D.exact);default:throw Error(`Unknown selector kind ${T}`)}}chainLocators(e){return e.join(`.`)}regexToSourceString(e){return normalizeEscapedRegexQuotes(String(e))}toCallWithExact(e,T,E){return isRegExp(T)?`${e}(${this.regexToSourceString(T)})`:E?`${e}(${this.quote(T)}, { exact: true })`:`${e}(${this.quote(T)})`}toHasText(e){return isRegExp(e)?this.regexToSourceString(e):this.quote(e)}toTestIdValue(e){return isRegExp(e)?this.regexToSourceString(e):this.quote(e)}quote(e){return escapeWithQuotes(e,this.preferredQuote??`'`)}},generators={javascript:JavaScriptLocatorFactory};function isRegExp(e){return e instanceof RegExp}var cacheAllowText=new Map,cacheDisallowText=new Map,kTextScoreRange=10,kExactPenalty=kTextScoreRange/2,kTestIdScore=1,kOtherTestIdScore=2,kIframeByAttributeScore=10,kBeginPenalizedScore=50,kPlaceholderScore=100,kLabelScore=120,kRoleWithNameScore=140,kAltTextScore=160,kTextScore=180,kTitleScore=200,kTextScoreRegex=250,kPlaceholderScoreExact=kPlaceholderScore+kExactPenalty,kLabelScoreExact=kLabelScore+kExactPenalty,kRoleWithNameScoreExact=kRoleWithNameScore+kExactPenalty,kAltTextScoreExact=kAltTextScore+kExactPenalty,kTextScoreExact=kTextScore+kExactPenalty,kTitleScoreExact=kTitleScore+kExactPenalty,kEndPenalizedScore=300,kCSSIdScore=500,kRoleWithoutNameScore=510,kCSSInputTypeNameScore=520,kCSSTagNameScore=530,kNthScore=1e4,kCSSFallbackScore=1e7;function generateSelector(e,T,E){e._evaluator.begin(),beginAriaCaches();try{return joinTokens(generateSelectorFor(e,T,E)||cssFallback(e,T,E))}finally{cacheAllowText.clear(),cacheDisallowText.clear(),endAriaCaches(),e._evaluator.end()}}function filterRegexTokens(e){return e.filter(e=>e[0].selector[0]!==`/`)}function generateSelectorFor(e,T,E){if(T.ownerDocument.documentElement===T)return[{engine:`css`,selector:`html`,score:1}];let D=(D,k)=>{let A=D===T,j=k?buildTextCandidates(e,D,D===T):[];D!==T&&(j=filterRegexTokens(j));let M=buildNoTextCandidates(e,D,E).map(e=>[e]),N=chooseFirstSelector(e,T.ownerDocument,D,[...j,...M],A);j=filterRegexTokens(j);let P=T=>{let E=k&&!T.length,j=[...T,...M].filter(e=>N?combineScores(e)<combineScores(N):!0),P=j[0];if(P)for(let T=parentElementOrShadowHost(D);T;T=parentElementOrShadowHost(T)){let k=O(T,E);if(!k||N&&combineScores([...k,...P])>=combineScores(N))continue;if(P=chooseFirstSelector(e,T,D,j,A),!P)return;let M=[...k,...P];(!N||combineScores(M)<combineScores(N))&&(N=M)}};return P(j),D===T&&j.length&&P([]),N},O=(e,T)=>{let E=T?cacheAllowText:cacheDisallowText,O=E.get(e);return O===void 0&&(O=D(e,T),E.set(e,O)),O};return D(T,!E.noText)}function buildNoTextCandidates(e,T,E){let D=[];for(let e of[`data-testid`,`data-test-id`,`data-test`])e!==E.testIdAttributeName&&T.getAttribute(e)&&D.push({engine:`css`,selector:`[${e}=${quoteCSSAttributeValue(T.getAttribute(e))}]`,score:kOtherTestIdScore});if(!E.noCSSId){let e=T.getAttribute(`id`);e&&!isGuidLike(e)&&D.push({engine:`css`,selector:makeSelectorForId(e),score:kCSSIdScore})}if(D.push({engine:`css`,selector:cssEscape(T.nodeName.toLowerCase()),score:kCSSTagNameScore}),T.nodeName===`IFRAME`){for(let e of[`name`,`title`])T.getAttribute(e)&&D.push({engine:`css`,selector:`${cssEscape(T.nodeName.toLowerCase())}[${e}=${quoteCSSAttributeValue(T.getAttribute(e))}]`,score:kIframeByAttributeScore});return T.getAttribute(E.testIdAttributeName)&&D.push({engine:`css`,selector:`[${E.testIdAttributeName}=${quoteCSSAttributeValue(T.getAttribute(E.testIdAttributeName))}]`,score:kTestIdScore}),penalizeScoreForLength([D]),D}if(T.getAttribute(E.testIdAttributeName)&&D.push({engine:`internal:testid`,selector:`[${E.testIdAttributeName}=${escapeForAttributeSelector(T.getAttribute(E.testIdAttributeName),!0)}]`,score:kTestIdScore}),T.nodeName===`INPUT`||T.nodeName===`TEXTAREA`){let e=T;if(e.placeholder){D.push({engine:`internal:attr`,selector:`[placeholder=${escapeForAttributeSelector(e.placeholder,!0)}]`,score:kPlaceholderScoreExact});for(let T of suitableTextAlternatives(e.placeholder))D.push({engine:`internal:attr`,selector:`[placeholder=${escapeForAttributeSelector(T.text,!1)}]`,score:kPlaceholderScore-T.scoreBouns})}}let O=getElementLabels(e._evaluator._cacheText,T);for(let e of O){let T=e.normalized;D.push({engine:`internal:label`,selector:escapeForTextSelector$1(T,!0),score:kLabelScoreExact});for(let e of suitableTextAlternatives(T))D.push({engine:`internal:label`,selector:escapeForTextSelector$1(e.text,!1),score:kLabelScore-e.scoreBouns})}let k=getAriaRole(T);return k&&![`none`,`presentation`].includes(k)&&D.push({engine:`internal:role`,selector:k,score:kRoleWithoutNameScore}),T.getAttribute(`name`)&&[`BUTTON`,`FORM`,`FIELDSET`,`FRAME`,`IFRAME`,`INPUT`,`KEYGEN`,`OBJECT`,`OUTPUT`,`SELECT`,`TEXTAREA`,`MAP`,`META`,`PARAM`].includes(T.nodeName)&&D.push({engine:`css`,selector:`${cssEscape(T.nodeName.toLowerCase())}[name=${quoteCSSAttributeValue(T.getAttribute(`name`))}]`,score:kCSSInputTypeNameScore}),[`INPUT`,`TEXTAREA`].includes(T.nodeName)&&T.getAttribute(`type`)!==`hidden`&&T.getAttribute(`type`)&&D.push({engine:`css`,selector:`${cssEscape(T.nodeName.toLowerCase())}[type=${quoteCSSAttributeValue(T.getAttribute(`type`))}]`,score:kCSSInputTypeNameScore}),[`INPUT`,`TEXTAREA`,`SELECT`].includes(T.nodeName)&&T.getAttribute(`type`)!==`hidden`&&D.push({engine:`css`,selector:cssEscape(T.nodeName.toLowerCase()),score:kCSSInputTypeNameScore+1}),penalizeScoreForLength([D]),D}function buildTextCandidates(e,T,E){if(T.nodeName===`SELECT`)return[];let D=[],O=T.getAttribute(`title`);if(O){D.push([{engine:`internal:attr`,selector:`[title=${escapeForAttributeSelector(O,!0)}]`,score:kTitleScoreExact}]);for(let e of suitableTextAlternatives(O))D.push([{engine:`internal:attr`,selector:`[title=${escapeForAttributeSelector(e.text,!1)}]`,score:kTitleScore-e.scoreBouns}])}let k=T.getAttribute(`alt`);if(k&&[`APPLET`,`AREA`,`IMG`,`INPUT`].includes(T.nodeName)){D.push([{engine:`internal:attr`,selector:`[alt=${escapeForAttributeSelector(k,!0)}]`,score:kAltTextScoreExact}]);for(let e of suitableTextAlternatives(k))D.push([{engine:`internal:attr`,selector:`[alt=${escapeForAttributeSelector(e.text,!1)}]`,score:kAltTextScore-e.scoreBouns}])}let A=elementText(e._evaluator._cacheText,T).normalized;if(A){let e=suitableTextAlternatives(A);if(E){A.length<=80&&D.push([{engine:`internal:text`,selector:escapeForTextSelector$1(A,!0),score:kTextScoreExact}]);for(let T of e)D.push([{engine:`internal:text`,selector:escapeForTextSelector$1(T.text,!1),score:kTextScore-T.scoreBouns}])}let O={engine:`css`,selector:cssEscape(T.nodeName.toLowerCase()),score:kCSSTagNameScore};for(let T of e)D.push([O,{engine:`internal:has-text`,selector:escapeForTextSelector$1(T.text,!1),score:kTextScore-T.scoreBouns}]);if(A.length<=80){let e=RegExp(`^${escapeRegExp(A)}$`);D.push([O,{engine:`internal:has-text`,selector:escapeForTextSelector$1(e,!1),score:kTextScoreRegex}])}}let j=getAriaRole(T);if(j&&![`none`,`presentation`].includes(j)){let e=getElementAccessibleName(T,!1);if(e){D.push([{engine:`internal:role`,selector:`${j}[name=${escapeForAttributeSelector(e,!0)}]`,score:kRoleWithNameScoreExact}]);for(let T of suitableTextAlternatives(e))D.push([{engine:`internal:role`,selector:`${j}[name=${escapeForAttributeSelector(T.text,!1)}]`,score:kRoleWithNameScore-T.scoreBouns}])}}return penalizeScoreForLength(D),D}function makeSelectorForId(e){return/^[a-z][\w\-]+$/i.test(e)?`#${e}`:`[id="${cssEscape(e)}"]`}function cssFallback(e,T,E){let D=T.ownerDocument,O=[];function k(E){let k=O.slice();E&&k.unshift(E);let A=k.join(` > `),j=e.parseSelector(A);return e.querySelector(j,D,!1)===T?A:void 0}function A(E){let O={engine:`css`,selector:E,score:kCSSFallbackScore},k=e.parseSelector(E),A=e.querySelectorAll(k,D);return A.length===1?[O]:[O,{engine:`nth`,selector:String(A.indexOf(T)),score:kNthScore}]}for(let e=T;e&&e!==D;e=parentElementOrShadowHost(e)){let T=e.nodeName.toLowerCase(),D=``;if(e.id&&!E.noCSSId){let T=makeSelectorForId(e.id),E=k(T);if(E)return A(E);D=T}let j=e.parentNode,M=[...e.classList];for(let e=0;e<M.length;++e){let T=`.${cssEscape(M.slice(0,e+1).join(`.`))}`,E=k(T);if(E)return A(E);!D&&j&&j.querySelectorAll(T).length===1&&(D=T)}if(j){let E=[...j.children],O=E.filter(e=>e.nodeName.toLowerCase()===T).indexOf(e)===0?cssEscape(T):`${cssEscape(T)}:nth-child(${1+E.indexOf(e)})`,M=k(O);if(M)return A(M);D||=O}else D||=cssEscape(T);O.unshift(D)}return A(k())}function penalizeScoreForLength(e){for(let T of e)for(let e of T)e.score>kBeginPenalizedScore&&e.score<kEndPenalizedScore&&(e.score+=Math.min(kTextScoreRange,e.selector.length/10|0))}function joinTokens(e){let T=[],E=``;for(let{engine:D,selector:O}of e)T.length&&(E!==`css`||D!==`css`||O.startsWith(`:nth-match(`))&&T.push(`>>`),E=D,D===`css`?T.push(O):T.push(`${D}=${O}`);return T.join(` `)}function combineScores(e){let T=0;for(let E=0;E<e.length;E++)T+=e[E].score*(e.length-E);return T}function chooseFirstSelector(e,T,E,D,O){let k=D.map(e=>({tokens:e,score:combineScores(e)}));k.sort((e,T)=>e.score-T.score);let A=null;for(let{tokens:D}of k){let k=e.parseSelector(joinTokens(D)),j=e.querySelectorAll(k,T);if(j[0]===E&&j.length===1)return D;let M=j.indexOf(E);if(!O||A||M===-1||j.length>5)continue;let N={engine:`nth`,selector:String(M),score:kNthScore};A=[...D,N]}return A}function isGuidLike(e){let T,E=0;for(let D=0;D<e.length;++D){let O=e[D],k;if(!(O===`-`||O===`_`)){if(k=O>=`a`&&O<=`z`?`lower`:O>=`A`&&O<=`Z`?`upper`:O>=`0`&&O<=`9`?`digit`:`other`,k===`lower`&&T===`upper`){T=k;continue}T&&T!==k&&++E,T=k}}return E>=e.length/4}function trimWordBoundary(e,T){if(e.length<=T)return e;e=e.substring(0,T);let E=e.match(/^(.*)\b(.+)$/);return E?E[1].trimEnd():``}function suitableTextAlternatives(e){let T=[];{let E=e.match(/^([\d.,]+)[^.,\w]/),D=E?E[1].length:0;if(D){let E=trimWordBoundary(e.substring(D).trimStart(),80);T.push({text:E,scoreBouns:E.length<=30?2:1})}}{let E=e.match(/[^.,\w]([\d.,]+)$/),D=E?E[1].length:0;if(D){let E=trimWordBoundary(e.substring(0,e.length-D).trimEnd(),80);T.push({text:E,scoreBouns:E.length<=30?2:1})}}return e.length<=30?T.push({text:e,scoreBouns:0}):(T.push({text:trimWordBoundary(e,80),scoreBouns:0}),T.push({text:trimWordBoundary(e,30),scoreBouns:1})),T=T.filter(e=>e.text),T.length||T.push({text:e.substring(0,80),scoreBouns:0}),T}function boxRightOf(e,T,E){let D=e.left-T.right;if(!(D<0||E!==void 0&&D>E))return D+Math.max(T.bottom-e.bottom,0)+Math.max(e.top-T.top,0)}function boxLeftOf(e,T,E){let D=T.left-e.right;if(!(D<0||E!==void 0&&D>E))return D+Math.max(T.bottom-e.bottom,0)+Math.max(e.top-T.top,0)}function boxAbove(e,T,E){let D=T.top-e.bottom;if(!(D<0||E!==void 0&&D>E))return D+Math.max(e.left-T.left,0)+Math.max(T.right-e.right,0)}function boxBelow(e,T,E){let D=e.top-T.bottom;if(!(D<0||E!==void 0&&D>E))return D+Math.max(e.left-T.left,0)+Math.max(T.right-e.right,0)}function boxNear(e,T,E){let D=E===void 0?50:E,O=0;return e.left-T.right>=0&&(O+=e.left-T.right),T.left-e.right>=0&&(O+=T.left-e.right),T.top-e.bottom>=0&&(O+=T.top-e.bottom),e.top-T.bottom>=0&&(O+=e.top-T.bottom),O>D?void 0:O}var kLayoutSelectorNames=[`left-of`,`right-of`,`above`,`below`,`near`];function layoutSelectorScore(e,T,E,D){let O=T.getBoundingClientRect(),k={"left-of":boxLeftOf,"right-of":boxRightOf,above:boxAbove,below:boxBelow,near:boxNear}[e],A;for(let e of E){if(e===T)continue;let E=k(O,e.getBoundingClientRect(),D);E!==void 0&&(A===void 0||E<A)&&(A=E)}return A}var SelectorEvaluatorImpl=class{constructor(e){__publicField(this,`_engines`,new Map),__publicField(this,`_cacheQueryCSS`,new Map),__publicField(this,`_cacheMatches`,new Map),__publicField(this,`_cacheQuery`,new Map),__publicField(this,`_cacheMatchesSimple`,new Map),__publicField(this,`_cacheMatchesParents`,new Map),__publicField(this,`_cacheCallMatches`,new Map),__publicField(this,`_cacheCallQuery`,new Map),__publicField(this,`_cacheQuerySimple`,new Map),__publicField(this,`_cacheText`,new Map),__publicField(this,`_scoreMap`),__publicField(this,`_retainCacheCounter`,0);for(let[T,E]of e)this._engines.set(T,E);this._engines.set(`not`,notEngine),this._engines.set(`is`,isEngine),this._engines.set(`where`,isEngine),this._engines.set(`has`,hasEngine),this._engines.set(`scope`,scopeEngine),this._engines.set(`light`,lightEngine),this._engines.set(`visible`,visibleEngine),this._engines.set(`text`,textEngine),this._engines.set(`text-is`,textIsEngine),this._engines.set(`text-matches`,textMatchesEngine),this._engines.set(`has-text`,hasTextEngine),this._engines.set(`right-of`,createLayoutEngine(`right-of`)),this._engines.set(`left-of`,createLayoutEngine(`left-of`)),this._engines.set(`above`,createLayoutEngine(`above`)),this._engines.set(`below`,createLayoutEngine(`below`)),this._engines.set(`near`,createLayoutEngine(`near`)),this._engines.set(`nth-match`,nthMatchEngine);let T=[...this._engines.keys()];T.sort();let E=[...customCSSNames];if(E.sort(),T.join(`|`)!==E.join(`|`))throw Error(`Please keep customCSSNames in sync with evaluator engines: ${T.join(`|`)} vs ${E.join(`|`)}`)}begin(){++this._retainCacheCounter}end(){--this._retainCacheCounter,this._retainCacheCounter||(this._cacheQueryCSS.clear(),this._cacheMatches.clear(),this._cacheQuery.clear(),this._cacheMatchesSimple.clear(),this._cacheMatchesParents.clear(),this._cacheCallMatches.clear(),this._cacheCallQuery.clear(),this._cacheQuerySimple.clear(),this._cacheText.clear())}_cached(e,T,E,D){e.has(T)||e.set(T,[]);let O=e.get(T),k=O.find(e=>E.every((T,E)=>e.rest[E]===T));if(k)return k.result;let A=D();return O.push({rest:E,result:A}),A}_checkSelector(e){if(!(typeof e==`object`&&e&&(Array.isArray(e)||`simples`in e&&e.simples.length)))throw Error(`Malformed selector "${e}"`);return e}matches(e,T,E){let D=this._checkSelector(T);this.begin();try{return this._cached(this._cacheMatches,e,[D,E.scope,E.pierceShadow,E.originalScope],()=>Array.isArray(D)?this._matchesEngine(isEngine,e,D,E):(this._hasScopeClause(D)&&(E=this._expandContextForScopeMatching(E)),this._matchesSimple(e,D.simples[D.simples.length-1].selector,E)?this._matchesParents(e,D,D.simples.length-2,E):!1))}finally{this.end()}}query(e,T){let E=this._checkSelector(T);this.begin();try{return this._cached(this._cacheQuery,E,[e.scope,e.pierceShadow,e.originalScope],()=>{if(Array.isArray(E))return this._queryEngine(isEngine,e,E);this._hasScopeClause(E)&&(e=this._expandContextForScopeMatching(e));let T=this._scoreMap;this._scoreMap=new Map;let D=this._querySimple(e,E.simples[E.simples.length-1].selector);return D=D.filter(T=>this._matchesParents(T,E,E.simples.length-2,e)),this._scoreMap.size&&D.sort((e,T)=>{let E=this._scoreMap.get(e),D=this._scoreMap.get(T);return E===D?0:E===void 0?1:D===void 0?-1:E-D}),this._scoreMap=T,D})}finally{this.end()}}_markScore(e,T){this._scoreMap&&this._scoreMap.set(e,T)}_hasScopeClause(e){return e.simples.some(e=>e.selector.functions.some(e=>e.name===`scope`))}_expandContextForScopeMatching(e){if(e.scope.nodeType!==1)return e;let T=parentElementOrShadowHost(e.scope);return T?{...e,scope:T,originalScope:e.originalScope||e.scope}:e}_matchesSimple(e,T,E){return this._cached(this._cacheMatchesSimple,e,[T,E.scope,E.pierceShadow,E.originalScope],()=>{if(e===E.scope||T.css&&!this._matchesCSS(e,T.css))return!1;for(let D of T.functions)if(!this._matchesEngine(this._getEngine(D.name),e,D.args,E))return!1;return!0})}_querySimple(e,T){return T.functions.length?this._cached(this._cacheQuerySimple,T,[e.scope,e.pierceShadow,e.originalScope],()=>{let E=T.css,D=T.functions;E===`*`&&D.length&&(E=void 0);let O,k=-1;E===void 0?(k=D.findIndex(e=>this._getEngine(e.name).query!==void 0),k===-1&&(k=0),O=this._queryEngine(this._getEngine(D[k].name),e,D[k].args)):O=this._queryCSS(e,E);for(let T=0;T<D.length;T++){if(T===k)continue;let E=this._getEngine(D[T].name);E.matches!==void 0&&(O=O.filter(O=>this._matchesEngine(E,O,D[T].args,e)))}for(let T=0;T<D.length;T++){if(T===k)continue;let E=this._getEngine(D[T].name);E.matches===void 0&&(O=O.filter(O=>this._matchesEngine(E,O,D[T].args,e)))}return O}):this._queryCSS(e,T.css||`*`)}_matchesParents(e,T,E,D){return E<0?!0:this._cached(this._cacheMatchesParents,e,[T,E,D.scope,D.pierceShadow,D.originalScope],()=>{let{selector:O,combinator:k}=T.simples[E];if(k===`>`){let k=parentElementOrShadowHostInContext(e,D);return!k||!this._matchesSimple(k,O,D)?!1:this._matchesParents(k,T,E-1,D)}if(k===`+`){let k=previousSiblingInContext(e,D);return!k||!this._matchesSimple(k,O,D)?!1:this._matchesParents(k,T,E-1,D)}if(k===``){let k=parentElementOrShadowHostInContext(e,D);for(;k;){if(this._matchesSimple(k,O,D)){if(this._matchesParents(k,T,E-1,D))return!0;if(T.simples[E-1].combinator===``)break}k=parentElementOrShadowHostInContext(k,D)}return!1}if(k===`~`){let k=previousSiblingInContext(e,D);for(;k;){if(this._matchesSimple(k,O,D)){if(this._matchesParents(k,T,E-1,D))return!0;if(T.simples[E-1].combinator===`~`)break}k=previousSiblingInContext(k,D)}return!1}if(k===`>=`){let k=e;for(;k;){if(this._matchesSimple(k,O,D)){if(this._matchesParents(k,T,E-1,D))return!0;if(T.simples[E-1].combinator===``)break}k=parentElementOrShadowHostInContext(k,D)}return!1}throw Error(`Unsupported combinator "${k}"`)})}_matchesEngine(e,T,E,D){if(e.matches)return this._callMatches(e,T,E,D);if(e.query)return this._callQuery(e,E,D).includes(T);throw Error(`Selector engine should implement "matches" or "query"`)}_queryEngine(e,T,E){if(e.query)return this._callQuery(e,E,T);if(e.matches)return this._queryCSS(T,`*`).filter(D=>this._callMatches(e,D,E,T));throw Error(`Selector engine should implement "matches" or "query"`)}_callMatches(e,T,E,D){return this._cached(this._cacheCallMatches,T,[e,D.scope,D.pierceShadow,D.originalScope,...E],()=>e.matches(T,E,D,this))}_callQuery(e,T,E){return this._cached(this._cacheCallQuery,e,[E.scope,E.pierceShadow,E.originalScope,...T],()=>e.query(E,T,this))}_matchesCSS(e,T){return e.matches(T)}_queryCSS(e,T){return this._cached(this._cacheQueryCSS,T,[e.scope,e.pierceShadow,e.originalScope],()=>{let E=[];function D(O){if(E=E.concat([...O.querySelectorAll(T)]),e.pierceShadow){O.shadowRoot&&D(O.shadowRoot);for(let e of O.querySelectorAll(`*`))e.shadowRoot&&D(e.shadowRoot)}}return D(e.scope),E})}_getEngine(e){let T=this._engines.get(e);if(!T)throw Error(`Unknown selector engine "${e}"`);return T}},isEngine={matches(e,T,E,D){if(T.length===0)throw Error(`"is" engine expects non-empty selector list`);return T.some(T=>D.matches(e,T,E))},query(e,T,E){if(T.length===0)throw Error(`"is" engine expects non-empty selector list`);let D=[];for(let O of T)D=D.concat(E.query(e,O));return T.length===1?D:sortInDOMOrder(D)}},hasEngine={matches(e,T,E,D){if(T.length===0)throw Error(`"has" engine expects non-empty selector list`);return D.query({...E,scope:e},T).length>0}},scopeEngine={matches(e,T,E,D){if(T.length!==0)throw Error(`"scope" engine expects no arguments`);let O=E.originalScope||E.scope;return O.nodeType===9?e===O.documentElement:e===O},query(e,T,E){if(T.length!==0)throw Error(`"scope" engine expects no arguments`);let D=e.originalScope||e.scope;if(D.nodeType===9){let e=D.documentElement;return e?[e]:[]}return D.nodeType===1?[D]:[]}},notEngine={matches(e,T,E,D){if(T.length===0)throw Error(`"not" engine expects non-empty selector list`);return!D.matches(e,T,E)}},lightEngine={query(e,T,E){return E.query({...e,pierceShadow:!1},T)},matches(e,T,E,D){return D.matches(e,T,{...E,pierceShadow:!1})}},visibleEngine={matches(e,T,E,D){if(T.length)throw Error(`"visible" engine expects no arguments`);return isElementVisible(e)}},textEngine={matches(e,T,E,D){if(T.length!==1||typeof T[0]!=`string`)throw Error(`"text" engine expects a single string`);let O=normalizeWhiteSpace(T[0]).toLowerCase();return elementMatchesText(D._cacheText,e,e=>e.normalized.toLowerCase().includes(O))===`self`}},textIsEngine={matches(e,T,E,D){if(T.length!==1||typeof T[0]!=`string`)throw Error(`"text-is" engine expects a single string`);let O=normalizeWhiteSpace(T[0]);return elementMatchesText(D._cacheText,e,e=>!O&&!e.immediate.length?!0:e.immediate.some(e=>normalizeWhiteSpace(e)===O))!==`none`}},textMatchesEngine={matches(e,T,E,D){if(T.length===0||typeof T[0]!=`string`||T.length>2||T.length===2&&typeof T[1]!=`string`)throw Error(`"text-matches" engine expects a regexp body and optional regexp flags`);let O=new RegExp(T[0],T.length===2?T[1]:void 0);return elementMatchesText(D._cacheText,e,e=>O.test(e.full))===`self`}},hasTextEngine={matches(e,T,E,D){if(T.length!==1||typeof T[0]!=`string`)throw Error(`"has-text" engine expects a single string`);if(shouldSkipForTextMatching(e))return!1;let O=normalizeWhiteSpace(T[0]).toLowerCase();return(e=>e.normalized.toLowerCase().includes(O))(elementText(D._cacheText,e))}};function createLayoutEngine(e){return{matches(T,E,D,O){let k=E.length&&typeof E[E.length-1]==`number`?E[E.length-1]:void 0,A=k===void 0?E:E.slice(0,E.length-1);if(E.length<1+(k===void 0?0:1))throw Error(`"${e}" engine expects a selector list and optional maximum distance in pixels`);let j=layoutSelectorScore(e,T,O.query(D,A),k);return j===void 0?!1:(O._markScore(T,j),!0)}}}var nthMatchEngine={query(e,T,E){let D=T[T.length-1];if(T.length<2)throw Error(`"nth-match" engine expects non-empty selector list and an index argument`);if(typeof D!=`number`||D<1)throw Error(`"nth-match" engine expects a one-based index as the last argument`);let O=isEngine.query(e,T.slice(0,T.length-1),E);return D--,D<O.length?[O[D]]:[]}};function parentElementOrShadowHostInContext(e,T){if(e!==T.scope)return T.pierceShadow?parentElementOrShadowHost(e):e.parentElement||void 0}function previousSiblingInContext(e,T){if(e!==T.scope)return e.previousElementSibling||void 0}function sortInDOMOrder(e){let T=new Map,E=[],D=[];function O(e){let D=T.get(e);if(D)return D;let k=parentElementOrShadowHost(e);return k?O(k).children.push(e):E.push(e),D={children:[],taken:!1},T.set(e,D),D}for(let T of e)O(T).taken=!0;function k(e){let E=T.get(e);if(E.taken&&D.push(e),E.children.length>1){let T=new Set(E.children);E.children=[];let D=e.firstElementChild;for(;D&&E.children.length<T.size;)T.has(D)&&E.children.push(D),D=D.nextElementSibling;for(D=e.shadowRoot?e.shadowRoot.firstElementChild:null;D&&E.children.length<T.size;)T.has(D)&&E.children.push(D),D=D.nextElementSibling}E.children.forEach(k)}return E.forEach(k),D}function getByAttributeTextSelector(e,T,E){return`internal:attr=[${e}=${escapeForAttributeSelector(T,E?.exact||!1)}]`}function getByTestIdSelector(e,T){return`internal:testid=[${e}=${escapeForAttributeSelector(T,!0)}]`}function getByLabelSelector(e,T){return`internal:label=${escapeForTextSelector$1(e,!!T?.exact)}`}function getByAltTextSelector(e,T){return getByAttributeTextSelector(`alt`,e,T)}function getByTitleSelector(e,T){return getByAttributeTextSelector(`title`,e,T)}function getByPlaceholderSelector(e,T){return getByAttributeTextSelector(`placeholder`,e,T)}function getByTextSelector(e,T){return`internal:text=${escapeForTextSelector$1(e,!!T?.exact)}`}function getByRoleSelector(e,T={}){let E=[];return T.checked!==void 0&&E.push([`checked`,String(T.checked)]),T.disabled!==void 0&&E.push([`disabled`,String(T.disabled)]),T.selected!==void 0&&E.push([`selected`,String(T.selected)]),T.expanded!==void 0&&E.push([`expanded`,String(T.expanded)]),T.includeHidden!==void 0&&E.push([`include-hidden`,String(T.includeHidden)]),T.level!==void 0&&E.push([`level`,String(T.level)]),T.name!==void 0&&E.push([`name`,escapeForAttributeSelector(T.name,!!T.exact)]),T.pressed!==void 0&&E.push([`pressed`,String(T.pressed)]),`internal:role=${e}${E.map(([e,T])=>`[${e}=${T}]`).join(``)}`}var _Ivya=class e{constructor(){__publicField(this,`_engines`),__publicField(this,`_evaluator`),this._evaluator=new SelectorEvaluatorImpl(new Map),this._engines=new Map,this._engines.set(`xpath`,XPathEngine),this._engines.set(`xpath:light`,XPathEngine),this._engines.set(`role`,createRoleEngine(!1)),this._engines.set(`text`,this._createTextEngine(!0,!1)),this._engines.set(`text:light`,this._createTextEngine(!1,!1)),this._engines.set(`id`,this._createAttributeEngine(`id`,!0)),this._engines.set(`id:light`,this._createAttributeEngine(`id`,!1)),this._engines.set(`data-testid`,this._createAttributeEngine(`data-testid`,!0)),this._engines.set(`data-testid:light`,this._createAttributeEngine(`data-testid`,!1)),this._engines.set(`data-test-id`,this._createAttributeEngine(`data-test-id`,!0)),this._engines.set(`data-test-id:light`,this._createAttributeEngine(`data-test-id`,!1)),this._engines.set(`data-test`,this._createAttributeEngine(`data-test`,!0)),this._engines.set(`data-test:light`,this._createAttributeEngine(`data-test`,!1)),this._engines.set(`css`,this._createCSSEngine()),this._engines.set(`nth`,{queryAll:()=>[]}),this._engines.set(`visible`,this._createVisibleEngine()),this._engines.set(`internal:control`,this._createControlEngine()),this._engines.set(`internal:has`,this._createHasEngine()),this._engines.set(`internal:has-not`,this._createHasNotEngine()),this._engines.set(`internal:and`,{queryAll:()=>[]}),this._engines.set(`internal:or`,{queryAll:()=>[]}),this._engines.set(`internal:chain`,this._createInternalChainEngine()),this._engines.set(`internal:label`,this._createInternalLabelEngine()),this._engines.set(`internal:text`,this._createTextEngine(!0,!0)),this._engines.set(`internal:has-text`,this._createInternalHasTextEngine()),this._engines.set(`internal:has-not-text`,this._createInternalHasNotTextEngine()),this._engines.set(`internal:attr`,this._createNamedAttributeEngine()),this._engines.set(`internal:testid`,this._createNamedAttributeEngine()),this._engines.set(`internal:role`,createRoleEngine(!0))}static create(T){return Object.assign(e.options,T),e.singleton||=new e}queryLocatorSelector(e,T=document.documentElement,E=!0){return this.querySelector(this.parseSelector(e),T,E)}queryLocatorSelectorAll(e,T=document.documentElement){return this.querySelectorAll(this.parseSelector(e),T)}querySelector(e,T,E=!0){let D=this.querySelectorAll(e,T);if(E&&D.length>1)throw this.strictModeViolationError(e,D);return D[0]||null}queryAllByRole(e,T,E=document.documentElement){let D=this.parseSelector(getByRoleSelector(e,T));return this.querySelectorAll(D,E)}queryAllByLabelText(e,T,E=document.documentElement){let D=this.parseSelector(getByLabelSelector(e,T));return this.querySelectorAll(D,E)}queryAllByTestId(T,E=document.documentElement){let D=this.parseSelector(getByTestIdSelector(e.options.testIdAttribute,T));return this.querySelectorAll(D,E)}queryAllByText(e,T,E=document.documentElement){let D=this.parseSelector(getByTextSelector(e,T));return this.querySelectorAll(D,E)}queryAllByTitle(e,T,E=document.documentElement){let D=this.parseSelector(getByTitleSelector(e,T));return this.querySelectorAll(D,E)}queryAllByPlaceholder(e,T,E=document.documentElement){let D=this.parseSelector(getByPlaceholderSelector(e,T));return this.querySelectorAll(D,E)}queryAllByAltText(e,T,E=document.documentElement){let D=this.parseSelector(getByAltTextSelector(e,T));return this.querySelectorAll(D,E)}queryByRole(e,T,E=document.documentElement){let D=this.parseSelector(getByRoleSelector(e,T));return this.querySelector(D,E,!1)}queryByLabelText(e,T,E=document.documentElement){let D=this.parseSelector(getByLabelSelector(e,T));return this.querySelector(D,E,!1)}queryByTestId(T,E=document.documentElement){let D=this.parseSelector(getByTestIdSelector(e.options.testIdAttribute,T));return this.querySelector(D,E,!1)}queryByText(e,T,E=document.documentElement){let D=this.parseSelector(getByTextSelector(e,T));return this.querySelector(D,E,!1)}queryByTitle(e,T,E=document.documentElement){let D=this.parseSelector(getByTitleSelector(e,T));return this.querySelector(D,E,!1)}queryByPlaceholder(e,T,E=document.documentElement){let D=this.parseSelector(getByPlaceholderSelector(e,T));return this.querySelector(D,E,!1)}queryByAltText(e,T,E=document.documentElement){let D=this.parseSelector(getByAltTextSelector(e,T));return this.querySelector(D,E,!1)}strictModeViolationError(e,T){let E=T.slice(0,10).map(e=>({preview:this.previewNode(e),selector:this.generateSelectorSimple(e)})),D=E.map((e,T)=>`
|
|
4
4
|
${T+1}) ${e.preview} aka ${asLocator(`javascript`,e.selector)}`);return E.length<T.length&&D.push(`
|
|
5
5
|
...`),this.createStacklessError(`strict mode violation: ${asLocator(`javascript`,stringifySelector(e))} resolved to ${T.length} elements:${D.join(``)}
|
|
6
|
-
`)}generateSelectorSimple(T,E){return generateSelector(this,T,{...E,testIdAttributeName:e.options.testIdAttribute})}parseSelector(e){let T=parseSelector(e);return visitAllSelectorParts(T,T=>{if(!this._engines.has(T.name))throw this.createStacklessError(`Unknown engine "${T.name}" while parsing selector ${e}`)}),T}previewNode(e){if(e.nodeType===Node.TEXT_NODE)return oneLine(`#text=${e.nodeValue||``}`);if(e.nodeType!==Node.ELEMENT_NODE)return oneLine(`<${e.nodeName.toLowerCase()} />`);let T=e,E=[];for(let e=0;e<T.attributes.length;e++){let{name:D,value:O}=T.attributes[e];D!==`style`&&(!O&&booleanAttributes.has(D)?E.push(` ${D}`):E.push(` ${D}="${O}"`))}E.sort((e,T)=>e.length-T.length);let D=trimStringWithEllipsis(E.join(``),500);if(autoClosingTags.has(T.nodeName))return oneLine(`<${T.nodeName.toLowerCase()}${D}/>`);let O=T.childNodes,k=!1;if(O.length<=5){k=!0;for(let e=0;e<O.length;e++)k&&=O[e].nodeType===Node.TEXT_NODE}let A=k?T.textContent||``:O.length?`…`:``;return oneLine(`<${T.nodeName.toLowerCase()}${D}>${trimStringWithEllipsis(A,50)}</${T.nodeName.toLowerCase()}>`)}querySelectorAll(e,T){if(e.capture!==void 0){if(e.parts.some(e=>e.name===`nth`))throw this.createStacklessError(`Can't query n-th element in a request with the capture.`);let E={parts:e.parts.slice(0,e.capture+1)};if(e.capture<e.parts.length-1){let T={parts:e.parts.slice(e.capture+1)},D={name:`internal:has`,body:{parsed:T},source:stringifySelector(T)};E.parts.push(D)}return this.querySelectorAll(E,T)}if(!T.querySelectorAll)throw this.createStacklessError(`Node is not queryable.`);if(e.capture!==void 0)throw this.createStacklessError(`Internal error: there should not be a capture in the selector.`);if(T.nodeType===11&&e.parts.length===1&&e.parts[0].name===`css`&&e.parts[0].source===`:scope`)return[T];this._evaluator.begin();try{let E=new Set([T]);for(let D of e.parts)if(D.name===`nth`)E=this._queryNth(E,D);else if(D.name===`internal:and`){let e=this.querySelectorAll(D.body.parsed,T);E=new Set(e.filter(e=>E.has(e)))}else if(D.name===`internal:or`){let e=this.querySelectorAll(D.body.parsed,T);E=new Set(sortInDOMOrder(new Set([...E,...e])))}else if(kLayoutSelectorNames.includes(D.name))E=this._queryLayoutSelector(E,D,T);else{let e=new Set;for(let T of E){let E=this._queryEngineAll(D,T);for(let T of E)e.add(T)}E=e}return[...E]}finally{this._evaluator.end()}}_queryEngineAll(e,T){let E=this._engines.get(e.name).queryAll(T,e.body);for(let e of E)if(!(`nodeName`in e))throw this.createStacklessError(`Expected a Node but got ${Object.prototype.toString.call(e)}`);return E}_queryNth(e,T){let E=[...e],D=+T.body;return D===-1&&(D=E.length-1),new Set(E.slice(D,D+1))}_queryLayoutSelector(e,T,E){let D=T.name,O=T.body,k=[],A=this.querySelectorAll(O.parsed,E);for(let T of e){let e=layoutSelectorScore(D,T,A,O.distance);e!==void 0&&k.push({element:T,score:e})}return k.sort((e,T)=>e.score-T.score),new Set(k.map(e=>e.element))}createStacklessError(T){if(e.options.browser===`firefox`){let e=Error(`Error: ${T}`);return e.stack=``,e}let E=Error(T);return delete E.stack,E}_createTextEngine(e,T){return{queryAll:(E,D)=>{let{matcher:O,kind:k}=createTextMatcher(D,T),A=[],j=null,M=e=>{if(k===`lax`&&j&&j.contains(e))return!1;let E=elementMatchesText(this._evaluator._cacheText,e,O);E===`none`&&(j=e),(E===`self`||E===`selfAndChildren`&&k===`strict`&&!T)&&A.push(e)};E.nodeType===Node.ELEMENT_NODE&&M(E);let N=this._evaluator._queryCSS({scope:E,pierceShadow:e},`*`);for(let e of N)M(e);return A}}}_createAttributeEngine(e,T){let E=T=>[{simples:[{selector:{css:`[${e}=${JSON.stringify(T)}]`,functions:[]},combinator:``}]}];return{queryAll:(e,D)=>this._evaluator.query({scope:e,pierceShadow:T},E(D))}}_createCSSEngine(){return{queryAll:(e,T)=>this._evaluator.query({scope:e,pierceShadow:!0},T)}}_createNamedAttributeEngine(){return{queryAll:(e,T)=>{let E=parseAttributeSelector(T);if(E.name||E.attributes.length!==1)throw Error(`Malformed attribute selector: ${T}`);let{name:D,value:O,caseSensitive:k}=E.attributes[0],A=k?null:O.toLowerCase(),j;return j=O instanceof RegExp?e=>!!e.match(O):k?e=>e===O:e=>e.toLowerCase().includes(A),this._evaluator._queryCSS({scope:e,pierceShadow:!0},`[${D}]`).filter(e=>j(e.getAttribute(D)))}}}_createVisibleEngine(){return{queryAll:(e,T)=>e.nodeType===1&&isElementVisible(e)===!!T?[e]:[]}}_createControlEngine(){return{queryAll:(e,T)=>{if(T===`enter-frame`&&e instanceof HTMLIFrameElement){let T=e.contentDocument?.documentElement;return T?[T]:[]}return[]}}}_createHasEngine(){return{queryAll:(e,T)=>e.nodeType===1&&this.querySelector(T.parsed,e,!1)?[e]:[]}}_createHasNotEngine(){return{queryAll:(e,T)=>e.nodeType===1?this.querySelector(T.parsed,e,!1)?[]:[e]:[]}}_createInternalChainEngine(){return{queryAll:(e,T)=>this.querySelectorAll(T.parsed,e)}}_createInternalLabelEngine(){return{queryAll:(e,T)=>{let{matcher:E}=createTextMatcher(T,!0);return this._evaluator._queryCSS({scope:e,pierceShadow:!0},`*`).filter(e=>getElementLabels(this._evaluator._cacheText,e).some(e=>E(e)))}}}_createInternalHasTextEngine(){return{queryAll:(e,T)=>{if(e.nodeType!==1)return[];let E=e,D=elementText(this._evaluator._cacheText,E),{matcher:O}=createTextMatcher(T,!0);return O(D)?[E]:[]}}}_createInternalHasNotTextEngine(){return{queryAll:(e,T)=>{if(e.nodeType!==1)return[];let E=e,D=elementText(this._evaluator._cacheText,E),{matcher:O}=createTextMatcher(T,!0);return O(D)?[]:[E]}}}};__publicField(_Ivya,`options`,{testIdAttribute:`data-testid`,browser:`chromium`}),__publicField(_Ivya,`singleton`,null);var Ivya=_Ivya;function oneLine(e){return e.replace(/\n/g,`↵`).replace(/\t/g,`⇆`)}var booleanAttributes=new Set([`checked`,`selected`,`disabled`,`readonly`,`multiple`]),autoClosingTags=new Set([`AREA`,`BASE`,`BR`,`COL`,`COMMAND`,`EMBED`,`HR`,`IMG`,`INPUT`,`KEYGEN`,`LINK`,`MENUITEM`,`META`,`PARAM`,`SOURCE`,`TRACK`,`WBR`]);function cssUnquote(e){if(e=e.substring(1,e.length-1),!e.includes(`\\`))return e;let T=[],E=0;for(;E<e.length;)e[E]===`\\`&&E+1<e.length&&E++,T.push(e[E++]);return T.join(``)}function createTextMatcher(e,T){if(e[0]===`/`&&e.lastIndexOf(`/`)>0){let T=e.lastIndexOf(`/`),E=new RegExp(e.substring(1,T),e.substring(T+1));return{matcher:e=>E.test(e.full),kind:`regex`}}let E=T?JSON.parse.bind(JSON):cssUnquote,D=!1;return e.length>1&&e[0]===`"`&&e[e.length-1]===`"`?(e=E(e),D=!0):T&&e.length>1&&e[0]===`"`&&e[e.length-2]===`"`&&e[e.length-1]===`i`?(e=E(e.substring(0,e.length-1)),D=!1):T&&e.length>1&&e[0]===`"`&&e[e.length-2]===`"`&&e[e.length-1]===`s`?(e=E(e.substring(0,e.length-1)),D=!0):e.length>1&&e[0]===`'`&&e[e.length-1]===`'`&&(e=E(e),D=!0),e=normalizeWhiteSpace(e),D?T?{kind:`strict`,matcher:T=>T.normalized===e}:{matcher:T=>!e&&!T.immediate.length?!0:T.immediate.some(T=>normalizeWhiteSpace(T)===e),kind:`strict`}:(e=e.toLowerCase(),{kind:`lax`,matcher:T=>T.normalized.toLowerCase().includes(e)})}var XPathEngine={queryAll(e,T){T.startsWith(`/`)&&e.nodeType!==Node.DOCUMENT_NODE&&(T=`.${T}`);let E=[],D=e.ownerDocument||e;if(!D)return E;let O=D.evaluate(T,e,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE);for(let e=O.iterateNext();e;e=O.iterateNext())e.nodeType===Node.ELEMENT_NODE&&E.push(e);return E}};function parentElementOrShadowHost(e){if(e.parentElement)return e.parentElement;if(e.parentNode&&e.parentNode.nodeType===11&&e.parentNode.host)return e.parentNode.host}function enclosingShadowRootOrDocument(e){let T=e;for(;T.parentNode;)T=T.parentNode;if(T.nodeType===11||T.nodeType===9)return T}function enclosingShadowHost(e){for(;e.parentElement;)e=e.parentElement;return parentElementOrShadowHost(e)}function closestCrossShadow(e,T){for(;e;){let E=e.closest(T);if(E)return E;e=enclosingShadowHost(e)}}function getElementComputedStyle(e,T){return e.ownerDocument&&e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,T):void 0}function isElementStyleVisibilityVisible(e,T){if(T??=getElementComputedStyle(e),!T)return!0;if(Element.prototype.checkVisibility&&Ivya.options.browser!==`webkit`){if(!e.checkVisibility())return!1}else{let T=e.closest(`details,summary`);if(T!==e&&T?.nodeName===`DETAILS`&&!T.open)return!1}return T.visibility===`visible`}function isElementVisible(e){let T=getElementComputedStyle(e);if(!T)return!0;if(T.display===`contents`){for(let T=e.firstChild;T;T=T.nextSibling)if(T.nodeType===1&&isElementVisible(T)||T.nodeType===3&&isVisibleTextNode(T))return!0;return!1}if(!isElementStyleVisibilityVisible(e,T))return!1;let E=e.getBoundingClientRect();return E.width>0&&E.height>0}function isVisibleTextNode(e){let T=e.ownerDocument.createRange();T.selectNode(e);let E=T.getBoundingClientRect();return E.width>0&&E.height>0}function elementSafeTagName(e){return e instanceof HTMLFormElement?`FORM`:e.tagName.toUpperCase()}function ensureAwaited(e){let T=getWorkerState().current;if(!T||T.type!==`test`)return e();let E=!1,D=Error(`STACK_TRACE_ERROR`);T.onFinished??=[],T.onFinished.push(()=>{if(!E){let e=Error(`The call was not awaited. This method is asynchronous and must be awaited; otherwise, the call will not start to avoid unhandled rejections.`);throw e.stack=D.stack?.replace(D.message,e.message),e}});let O;return{then(T,k){return E=!0,(O||=e(D)).then(T,k)},catch(T){return(O||=e(D)).catch(T)},finally(T){return(O||=e(D)).finally(T)},[Symbol.toStringTag]:`Promise`}}function getBrowserState(){return window.__vitest_browser_runner__}function getWorkerState(){let e=window.__vitest_worker__;if(!e)throw Error(`Worker state is not found. This is an issue with Vitest. Please, open an issue.`);return e}function convertElementToCssSelector(e){if(!e||!(e instanceof Element))throw Error(`Expected DOM element to be an instance of Element, received ${typeof e}`);return getUniqueCssSelector(e)}function escapeIdForCSSSelector(e){return e.split(``).map(e=>{let T=e.charCodeAt(0);return e===` `||e===`#`||e===`.`||e===`:`||e===`[`||e===`]`||e===`>`||e===`+`||e===`~`||e===`\\`?`\\${e}`:T>=65536?`\\${T.toString(16).toUpperCase().padStart(6,`0`)} `:T<32||T===127||T>=128?`\\${T.toString(16).toUpperCase().padStart(2,`0`)} `:e}).join(``)}function getUniqueCssSelector(e){let T=[],E,D=!1;for(;E=getParent(e);){E.shadowRoot&&(D=!0);let O=e.tagName;if(e.id)T.push(`#${escapeIdForCSSSelector(e.id)}`);else if(!e.nextElementSibling&&!e.previousElementSibling)T.push(O.toLowerCase());else{let D=0,k=0,A=0;for(let T of E.children)D++,T.tagName===O&&k++,T===e&&(A=D);k>1?T.push(`${O.toLowerCase()}:nth-child(${A})`):T.push(O.toLowerCase())}e=E}return`${getBrowserState().provider===`webdriverio`&&D?`>>>`:``}${T.reverse().join(` > `)}`}function getParent(e){let T=e.parentNode;return T instanceof ShadowRoot?T.host:T}const now$1=Date.now;function processTimeoutOptions(e){if(e&&e.timeout!=null||getWorkerState().config.browser.providerOptions.actionTimeout!=null)return e;let T=getBrowserState().runner,E=T._currentTaskStartTime;if(!E)return e;let D=T._currentTaskTimeout;if(D===0||D==null||D===1/0)return e;e||={};let O=now$1(),k=E+D-O;return k<=0||(e.timeout=k-100),e}function getIframeScale(){let e=window.parent.document.querySelector(`iframe[data-vitest]`)?.parentElement;if(!e)throw Error(`Cannot find Tester element. This is a bug in Vitest. Please, open a new issue with reproduction.`);let T=e.getAttribute(`data-scale`),E=Number(T);if(Number.isNaN(E))throw TypeError(`Cannot parse scale value from Tester element (${T}). This is a bug in Vitest. Please, open a new issue with reproduction.`);return E}function escapeRegexForSelector(e){return e.unicode||e.unicodeSets?String(e):String(e).replace(/(^|[^\\])(\\\\)*(["'`])/g,`$1$2\\$3`).replace(/>>/g,`\\>\\>`)}function escapeForTextSelector(e,T){return typeof e==`string`?`${JSON.stringify(e)}i`:escapeRegexForSelector(e)}const provider=getBrowserState().provider,kElementLocator=Symbol.for(`$$vitest:locator-resolved`);async function convertToSelector(e,T){if(!e)throw Error(`Expected element or locator to be defined.`);if(e instanceof Element)return convertElementToCssSelector(e);if(isLocator(e))return provider===`playwright`||kElementLocator in e?e.selector:convertElementToCssSelector(await e.findElement(T));throw Error(`Expected element or locator to be an instance of Element or Locator.`)}const kLocator$1=Symbol.for(`$$vitest:locator`);function isLocator(e){return!!e&&typeof e==`object`&&kLocator$1 in e}const DEFAULT_WHEEL_DELTA=100;function resolveUserEventWheelOptions(e){let T;if(e.delta)T=e.delta;else switch(e.direction){case`up`:T={y:-100};break;case`down`:T={y:100};break;case`left`:T={x:-100};break;case`right`:T={x:100};break}return{delta:T,times:e.times}}__INTERNAL._asLocator=asLocator;const now=Date.now,waitForIntervals=[0,20,50,100,100,500];function sleep(e){let{setTimeout:T}=getSafeTimers();return new Promise(E=>T(E,e))}const selectorEngine=Ivya.create({browser:(e=>{switch(e){case`edge`:case`chrome`:return`chromium`;case`safari`:return`webkit`;default:return e}})(server.config.browser.name),testIdAttribute:server.config.browser.locators.testIdAttribute}),kLocator=Symbol.for(`$$vitest:locator`);class Locator{_parsedSelector;_container;_pwSelector;_errorSource;constructor(){Object.defineProperty(this,kLocator,{enumerable:!1,writable:!1,configurable:!1,value:kLocator})}click(e){return this.triggerCommand(`__vitest_click`,this.selector,e)}dblClick(e){return this.triggerCommand(`__vitest_dblClick`,this.selector,e)}tripleClick(e){return this.triggerCommand(`__vitest_tripleClick`,this.selector,e)}wheel(e){return ensureAwaited(async T=>{await getBrowserState().commands.triggerCommand(`__vitest_wheel`,[this.selector,resolveUserEventWheelOptions(e)],T);let E=getBrowserState().config.browser.name;if(E===`chromium`||E===`chrome`)return new Promise(e=>{requestAnimationFrame(()=>{e()})})})}clear(e){return this.triggerCommand(`__vitest_clear`,this.selector,e)}hover(e){return this.triggerCommand(`__vitest_hover`,this.selector,e)}unhover(e){return this.triggerCommand(`__vitest_hover`,`html > body`,e)}fill(e,T){return this.triggerCommand(`__vitest_fill`,this.selector,e,T)}upload(e,T){return ensureAwaited(async E=>{let D=(Array.isArray(e)?e:[e]).map(async e=>{if(typeof e==`string`)return e;let T=await new Promise((T,E)=>{let D=new FileReader;D.onload=()=>T(D.result),D.onerror=()=>E(Error(`Failed to read file: ${e.name}`)),D.readAsDataURL(e)});return{name:e.name,mimeType:e.type,base64:T.slice(T.indexOf(`,`)+1)}});return getBrowserState().commands.triggerCommand(`__vitest_upload`,[this.selector,await Promise.all(D),T],E)})}dropTo(e,T={}){return this.triggerCommand(`__vitest_dragAndDrop`,this.selector,e.selector,T)}selectOptions(e,T){let E=(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?e:{element:isLocator(e)?e.selector:selectorEngine.generateSelectorSimple(e)});return this.triggerCommand(`__vitest_selectOptions`,this.selector,E,T)}screenshot(e){return page.screenshot({...e,element:this})}getByRole(e,T){return this.locator(getByRoleSelector(e,T))}getByAltText(e,T){return this.locator(getByAltTextSelector(e,T))}getByLabelText(e,T){return this.locator(getByLabelSelector(e,T))}getByPlaceholder(e,T){return this.locator(getByPlaceholderSelector(e,T))}getByTestId(T){return this.locator(getByTestIdSelector(server.config.browser.locators.testIdAttribute,T))}getByText(e,T){return this.locator(getByTextSelector(e,T))}getByTitle(e,T){return this.locator(getByTitleSelector(e,T))}filter(e){let T=[];if(e?.hasText&&T.push(`internal:has-text=${escapeForTextSelector(e.hasText)}`),e?.hasNotText&&T.push(`internal:has-not-text=${escapeForTextSelector(e.hasNotText)}`),e?.has){let E=e.has;T.push(`internal:has=${JSON.stringify(E._pwSelector||E.selector)}`)}if(e?.hasNot){let E=e.hasNot;T.push(`internal:has-not=${JSON.stringify(E._pwSelector||E.selector)}`)}if(!T.length)throw Error(`Locator.filter expects at least one filter. None provided.`);return this.locator(T.join(` >> `))}and(e){return this.locator(`internal:and=${JSON.stringify(e._pwSelector||e.selector)}`)}or(e){return this.locator(`internal:or=${JSON.stringify(e._pwSelector||e.selector)}`)}query(){let e=this._parsedSelector||=selectorEngine.parseSelector(this._pwSelector||this.selector);return selectorEngine.querySelector(e,document.documentElement,!0)}element(){let e=this.query();if(!e)throw utils.getElementError(this._pwSelector||this.selector,this._container||document.body);return e}elements(){let e=this._parsedSelector||=selectorEngine.parseSelector(this._pwSelector||this.selector);return selectorEngine.querySelectorAll(e,document.documentElement)}get length(){return this.elements().length}all(){return this.elements().map(e=>this.elementLocator(e))}nth(e){return this.locator(`nth=${e}`)}first(){return this.nth(0)}last(){return this.nth(-1)}toString(){return this.selector}toJSON(){return this.selector}async findElement(e={}){let T=processTimeoutOptions(e),D=T?.timeout,O=T?.strict??!0,k=now(),A=0;for(;;){let e=this.elements();if(e.length===1)return e[0];if(e.length>1){if(O)throw createStrictModeViolationError(this._pwSelector||this.selector,e);return e[0]}let T=now()-k;if(D!=null&&T>=D)throw utils.getElementError(this._pwSelector||this.selector,this._container||document.body);let j=waitForIntervals[Math.min(A++,waitForIntervals.length-1)];await sleep(D==null?j:Math.min(j,D-T))}}triggerCommand(e,...T){return this._errorSource?triggerCommandWithTrace({name:e,arguments:T,errorSource:this._errorSource}):ensureAwaited(E=>triggerCommandWithTrace({name:e,arguments:T,errorSource:E}))}}function triggerCommandWithTrace(e){return getBrowserState().commands.triggerCommand(e.name,e.arguments,e.errorSource)}function createStrictModeViolationError(e,T){let E=T.slice(0,10).map(e=>({preview:selectorEngine.previewNode(e),selector:selectorEngine.generateSelectorSimple(e)})),D=E.map((e,T)=>`\n ${T+1}) ${e.preview} aka ${asLocator(`javascript`,e.selector)}`);return E.length<T.length&&D.push(`
|
|
7
|
-
...`),Error(`strict mode violation: ${asLocator(`javascript`,e)} resolved to ${T.length} elements:${D.join(``)}\n`)}export{Locator as L,getAriaRole as a,getAriaDisabled as b,beginAriaCaches as c,getElementAccessibleDescription as d,endAriaCaches as e,getElementAccessibleErrorMessage as f,getAriaChecked as g,getElementAccessibleName as h,isElementVisible as i,cssEscape as j,kAriaCheckedRoles as k,convertToSelector as l,getBrowserState as m,
|
|
6
|
+
`)}generateSelectorSimple(T,E){return generateSelector(this,T,{...E,testIdAttributeName:e.options.testIdAttribute})}parseSelector(e){let T=parseSelector(e);return visitAllSelectorParts(T,T=>{if(!this._engines.has(T.name))throw this.createStacklessError(`Unknown engine "${T.name}" while parsing selector ${e}`)}),T}previewNode(e){if(e.nodeType===Node.TEXT_NODE)return oneLine(`#text=${e.nodeValue||``}`);if(e.nodeType!==Node.ELEMENT_NODE)return oneLine(`<${e.nodeName.toLowerCase()} />`);let T=e,E=[];for(let e=0;e<T.attributes.length;e++){let{name:D,value:O}=T.attributes[e];D!==`style`&&(!O&&booleanAttributes.has(D)?E.push(` ${D}`):E.push(` ${D}="${O}"`))}E.sort((e,T)=>e.length-T.length);let D=trimStringWithEllipsis(E.join(``),500);if(autoClosingTags.has(T.nodeName))return oneLine(`<${T.nodeName.toLowerCase()}${D}/>`);let O=T.childNodes,k=!1;if(O.length<=5){k=!0;for(let e=0;e<O.length;e++)k&&=O[e].nodeType===Node.TEXT_NODE}let A=k?T.textContent||``:O.length?`…`:``;return oneLine(`<${T.nodeName.toLowerCase()}${D}>${trimStringWithEllipsis(A,50)}</${T.nodeName.toLowerCase()}>`)}querySelectorAll(e,T){if(e.capture!==void 0){if(e.parts.some(e=>e.name===`nth`))throw this.createStacklessError(`Can't query n-th element in a request with the capture.`);let E={parts:e.parts.slice(0,e.capture+1)};if(e.capture<e.parts.length-1){let T={parts:e.parts.slice(e.capture+1)},D={name:`internal:has`,body:{parsed:T},source:stringifySelector(T)};E.parts.push(D)}return this.querySelectorAll(E,T)}if(!T.querySelectorAll)throw this.createStacklessError(`Node is not queryable.`);if(e.capture!==void 0)throw this.createStacklessError(`Internal error: there should not be a capture in the selector.`);if(T.nodeType===11&&e.parts.length===1&&e.parts[0].name===`css`&&e.parts[0].source===`:scope`)return[T];this._evaluator.begin();try{let E=new Set([T]);for(let D of e.parts)if(D.name===`nth`)E=this._queryNth(E,D);else if(D.name===`internal:and`){let e=this.querySelectorAll(D.body.parsed,T);E=new Set(e.filter(e=>E.has(e)))}else if(D.name===`internal:or`){let e=this.querySelectorAll(D.body.parsed,T);E=new Set(sortInDOMOrder(new Set([...E,...e])))}else if(kLayoutSelectorNames.includes(D.name))E=this._queryLayoutSelector(E,D,T);else{let e=new Set;for(let T of E){let E=this._queryEngineAll(D,T);for(let T of E)e.add(T)}E=e}return[...E]}finally{this._evaluator.end()}}_queryEngineAll(e,T){let E=this._engines.get(e.name).queryAll(T,e.body);for(let e of E)if(!(`nodeName`in e))throw this.createStacklessError(`Expected a Node but got ${Object.prototype.toString.call(e)}`);return E}_queryNth(e,T){let E=[...e],D=+T.body;return D===-1&&(D=E.length-1),new Set(E.slice(D,D+1))}_queryLayoutSelector(e,T,E){let D=T.name,O=T.body,k=[],A=this.querySelectorAll(O.parsed,E);for(let T of e){let e=layoutSelectorScore(D,T,A,O.distance);e!==void 0&&k.push({element:T,score:e})}return k.sort((e,T)=>e.score-T.score),new Set(k.map(e=>e.element))}createStacklessError(T){if(e.options.browser===`firefox`){let e=Error(`Error: ${T}`);return e.stack=``,e}let E=Error(T);return delete E.stack,E}_createTextEngine(e,T){return{queryAll:(E,D)=>{let{matcher:O,kind:k}=createTextMatcher(D,T),A=[],j=null,M=e=>{if(k===`lax`&&j&&j.contains(e))return!1;let E=elementMatchesText(this._evaluator._cacheText,e,O);E===`none`&&(j=e),(E===`self`||E===`selfAndChildren`&&k===`strict`&&!T)&&A.push(e)};E.nodeType===Node.ELEMENT_NODE&&M(E);let N=this._evaluator._queryCSS({scope:E,pierceShadow:e},`*`);for(let e of N)M(e);return A}}}_createAttributeEngine(e,T){let E=T=>[{simples:[{selector:{css:`[${e}=${JSON.stringify(T)}]`,functions:[]},combinator:``}]}];return{queryAll:(e,D)=>this._evaluator.query({scope:e,pierceShadow:T},E(D))}}_createCSSEngine(){return{queryAll:(e,T)=>this._evaluator.query({scope:e,pierceShadow:!0},T)}}_createNamedAttributeEngine(){return{queryAll:(e,T)=>{let E=parseAttributeSelector(T);if(E.name||E.attributes.length!==1)throw Error(`Malformed attribute selector: ${T}`);let{name:D,value:O,caseSensitive:k}=E.attributes[0],A=k?null:O.toLowerCase(),j;return j=O instanceof RegExp?e=>!!e.match(O):k?e=>e===O:e=>e.toLowerCase().includes(A),this._evaluator._queryCSS({scope:e,pierceShadow:!0},`[${D}]`).filter(e=>j(e.getAttribute(D)))}}}_createVisibleEngine(){return{queryAll:(e,T)=>e.nodeType===1&&isElementVisible(e)===!!T?[e]:[]}}_createControlEngine(){return{queryAll:(e,T)=>{if(T===`enter-frame`&&e instanceof HTMLIFrameElement){let T=e.contentDocument?.documentElement;return T?[T]:[]}return[]}}}_createHasEngine(){return{queryAll:(e,T)=>e.nodeType===1&&this.querySelector(T.parsed,e,!1)?[e]:[]}}_createHasNotEngine(){return{queryAll:(e,T)=>e.nodeType===1?this.querySelector(T.parsed,e,!1)?[]:[e]:[]}}_createInternalChainEngine(){return{queryAll:(e,T)=>this.querySelectorAll(T.parsed,e)}}_createInternalLabelEngine(){return{queryAll:(e,T)=>{let{matcher:E}=createTextMatcher(T,!0);return this._evaluator._queryCSS({scope:e,pierceShadow:!0},`*`).filter(e=>getElementLabels(this._evaluator._cacheText,e).some(e=>E(e)))}}}_createInternalHasTextEngine(){return{queryAll:(e,T)=>{if(e.nodeType!==1)return[];let E=e,D=elementText(this._evaluator._cacheText,E),{matcher:O}=createTextMatcher(T,!0);return O(D)?[E]:[]}}}_createInternalHasNotTextEngine(){return{queryAll:(e,T)=>{if(e.nodeType!==1)return[];let E=e,D=elementText(this._evaluator._cacheText,E),{matcher:O}=createTextMatcher(T,!0);return O(D)?[]:[E]}}}};__publicField(_Ivya,`options`,{testIdAttribute:`data-testid`,browser:`chromium`}),__publicField(_Ivya,`singleton`,null);var Ivya=_Ivya;function oneLine(e){return e.replace(/\n/g,`↵`).replace(/\t/g,`⇆`)}var booleanAttributes=new Set([`checked`,`selected`,`disabled`,`readonly`,`multiple`]),autoClosingTags=new Set([`AREA`,`BASE`,`BR`,`COL`,`COMMAND`,`EMBED`,`HR`,`IMG`,`INPUT`,`KEYGEN`,`LINK`,`MENUITEM`,`META`,`PARAM`,`SOURCE`,`TRACK`,`WBR`]);function cssUnquote(e){if(e=e.substring(1,e.length-1),!e.includes(`\\`))return e;let T=[],E=0;for(;E<e.length;)e[E]===`\\`&&E+1<e.length&&E++,T.push(e[E++]);return T.join(``)}function createTextMatcher(e,T){if(e[0]===`/`&&e.lastIndexOf(`/`)>0){let T=e.lastIndexOf(`/`),E=new RegExp(e.substring(1,T),e.substring(T+1));return{matcher:e=>E.test(e.full),kind:`regex`}}let E=T?JSON.parse.bind(JSON):cssUnquote,D=!1;return e.length>1&&e[0]===`"`&&e[e.length-1]===`"`?(e=E(e),D=!0):T&&e.length>1&&e[0]===`"`&&e[e.length-2]===`"`&&e[e.length-1]===`i`?(e=E(e.substring(0,e.length-1)),D=!1):T&&e.length>1&&e[0]===`"`&&e[e.length-2]===`"`&&e[e.length-1]===`s`?(e=E(e.substring(0,e.length-1)),D=!0):e.length>1&&e[0]===`'`&&e[e.length-1]===`'`&&(e=E(e),D=!0),e=normalizeWhiteSpace(e),D?T?{kind:`strict`,matcher:T=>T.normalized===e}:{matcher:T=>!e&&!T.immediate.length?!0:T.immediate.some(T=>normalizeWhiteSpace(T)===e),kind:`strict`}:(e=e.toLowerCase(),{kind:`lax`,matcher:T=>T.normalized.toLowerCase().includes(e)})}var XPathEngine={queryAll(e,T){T.startsWith(`/`)&&e.nodeType!==Node.DOCUMENT_NODE&&(T=`.${T}`);let E=[],D=e.ownerDocument||e;if(!D)return E;let O=D.evaluate(T,e,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE);for(let e=O.iterateNext();e;e=O.iterateNext())e.nodeType===Node.ELEMENT_NODE&&E.push(e);return E}};function parentElementOrShadowHost(e){if(e.parentElement)return e.parentElement;if(e.parentNode&&e.parentNode.nodeType===11&&e.parentNode.host)return e.parentNode.host}function enclosingShadowRootOrDocument(e){let T=e;for(;T.parentNode;)T=T.parentNode;if(T.nodeType===11||T.nodeType===9)return T}function enclosingShadowHost(e){for(;e.parentElement;)e=e.parentElement;return parentElementOrShadowHost(e)}function closestCrossShadow(e,T){for(;e;){let E=e.closest(T);if(E)return E;e=enclosingShadowHost(e)}}function getElementComputedStyle(e,T){return e.ownerDocument&&e.ownerDocument.defaultView?e.ownerDocument.defaultView.getComputedStyle(e,T):void 0}function isElementStyleVisibilityVisible(e,T){if(T??=getElementComputedStyle(e),!T)return!0;if(Element.prototype.checkVisibility&&Ivya.options.browser!==`webkit`){if(!e.checkVisibility())return!1}else{let T=e.closest(`details,summary`);if(T!==e&&T?.nodeName===`DETAILS`&&!T.open)return!1}return T.visibility===`visible`}function isElementVisible(e){let T=getElementComputedStyle(e);if(!T)return!0;if(T.display===`contents`){for(let T=e.firstChild;T;T=T.nextSibling)if(T.nodeType===1&&isElementVisible(T)||T.nodeType===3&&isVisibleTextNode(T))return!0;return!1}if(!isElementStyleVisibilityVisible(e,T))return!1;let E=e.getBoundingClientRect();return E.width>0&&E.height>0}function isVisibleTextNode(e){let T=e.ownerDocument.createRange();T.selectNode(e);let E=T.getBoundingClientRect();return E.width>0&&E.height>0}function elementSafeTagName(e){return e instanceof HTMLFormElement?`FORM`:e.tagName.toUpperCase()}function ensureAwaited(e){let T=getWorkerState().current;if(!T||T.type!==`test`)return e();let E=!1,D=Error(`STACK_TRACE_ERROR`);T.onFinished??=[],T.onFinished.push(()=>{if(!E){let e=Error(`The call was not awaited. This method is asynchronous and must be awaited; otherwise, the call will not start to avoid unhandled rejections.`);throw e.stack=D.stack?.replace(D.message,e.message),e}});let O;return{then(T,k){return E=!0,(O||=e(D)).then(T,k)},catch(T){return(O||=e(D)).catch(T)},finally(T){return(O||=e(D)).finally(T)},[Symbol.toStringTag]:`Promise`}}function getBrowserState(){return window.__vitest_browser_runner__}function getWorkerState(){let e=window.__vitest_worker__;if(!e)throw Error(`Worker state is not found. This is an issue with Vitest. Please, open an issue.`);return e}function convertElementToCssSelector(e){if(!e||!(e instanceof Element))throw Error(`Expected DOM element to be an instance of Element, received ${typeof e}`);return getUniqueCssSelector(e)}function escapeIdForCSSSelector(e){return e.split(``).map(e=>{let T=e.charCodeAt(0);return e===` `||e===`#`||e===`.`||e===`:`||e===`[`||e===`]`||e===`>`||e===`+`||e===`~`||e===`\\`?`\\${e}`:T>=65536?`\\${T.toString(16).toUpperCase().padStart(6,`0`)} `:T<32||T===127||T>=128?`\\${T.toString(16).toUpperCase().padStart(2,`0`)} `:e}).join(``)}function getUniqueCssSelector(e){let T=[],E,D=!1;for(;E=getParent(e);){E.shadowRoot&&(D=!0);let O=e.tagName;if(e.id)T.push(`#${escapeIdForCSSSelector(e.id)}`);else if(!e.nextElementSibling&&!e.previousElementSibling)T.push(O.toLowerCase());else{let D=0,k=0,A=0;for(let T of E.children)D++,T.tagName===O&&k++,T===e&&(A=D);k>1?T.push(`${O.toLowerCase()}:nth-child(${A})`):T.push(O.toLowerCase())}e=E}return`${getBrowserState().provider===`webdriverio`&&D?`>>>`:``}${T.reverse().join(` > `)}`}function getParent(e){let T=e.parentNode;return T instanceof ShadowRoot?T.host:T}const now$1=Date.now;function processTimeoutOptions(e){if(e&&e.timeout!=null||getWorkerState().config.browser.providerOptions.actionTimeout!=null)return e;let T=getBrowserState().runner,E=T._currentTaskStartTime;if(!E)return e;let D=T._currentTaskTimeout;if(D===0||D==null||D===1/0)return e;e||={};let O=now$1(),k=E+D-O;return k<=0||(e.timeout=k-100),e}function getIframeScale(){let e=window.parent.document.querySelector(`iframe[data-vitest]`)?.parentElement;if(!e)throw Error(`Cannot find Tester element. This is a bug in Vitest. Please, open a new issue with reproduction.`);let T=e.getAttribute(`data-scale`),E=Number(T);if(Number.isNaN(E))throw TypeError(`Cannot parse scale value from Tester element (${T}). This is a bug in Vitest. Please, open a new issue with reproduction.`);return E}function escapeRegexForSelector(e){return e.unicode||e.unicodeSets?String(e):String(e).replace(/(^|[^\\])(\\\\)*(["'`])/g,`$1$2\\$3`).replace(/>>/g,`\\>\\>`)}function escapeForTextSelector(e,T){return typeof e==`string`?`${JSON.stringify(e)}i`:escapeRegexForSelector(e)}const provider=getBrowserState().provider,kElementLocator=Symbol.for(`$$vitest:locator-resolved`);async function convertToSelector(e,T){if(!e)throw Error(`Expected element or locator to be defined.`);if(e instanceof Element)return convertElementToCssSelector(e);if(isLocator(e))return provider===`playwright`||kElementLocator in e?e.selector:convertElementToCssSelector(await e.findElement(T));throw Error(`Expected element or locator to be an instance of Element or Locator.`)}const kLocator$1=Symbol.for(`$$vitest:locator`);function isLocator(e){return!!e&&typeof e==`object`&&kLocator$1 in e}const DEFAULT_WHEEL_DELTA=100;function resolveUserEventWheelOptions(e){let T;if(e.delta)T=e.delta;else switch(e.direction){case`up`:T={y:-100};break;case`down`:T={y:100};break;case`left`:T={x:-100};break;case`right`:T={x:100};break}return{delta:T,times:e.times}}__INTERNAL._asLocator=asLocator;const now=Date.now,waitForIntervals=[0,20,50,100,100,500];function sleep(e){let{setTimeout:T}=getSafeTimers();return new Promise(E=>T(E,e))}const selectorEngine=Ivya.create({browser:(e=>{switch(e){case`edge`:case`chrome`:return`chromium`;case`safari`:return`webkit`;default:return e}})(server.config.browser.name),testIdAttribute:server.config.browser.locators.testIdAttribute}),kLocator=Symbol.for(`$$vitest:locator`);class Locator{_parsedSelector;_container;_pwSelector;_errorSource;constructor(){Object.defineProperty(this,kLocator,{enumerable:!1,writable:!1,configurable:!1,value:kLocator})}click(e){return this.triggerCommand(`__vitest_click`,this.selector,e)}dblClick(e){return this.triggerCommand(`__vitest_dblClick`,this.selector,e)}tripleClick(e){return this.triggerCommand(`__vitest_tripleClick`,this.selector,e)}wheel(e){return ensureAwaited(async T=>{await getBrowserState().commands.triggerCommand(`__vitest_wheel`,[this.selector,resolveUserEventWheelOptions(e)],T);let E=getBrowserState().config.browser.name;if(E===`chromium`||E===`chrome`)return new Promise(e=>{requestAnimationFrame(()=>{e()})})})}clear(e){return this.triggerCommand(`__vitest_clear`,this.selector,e)}hover(e){return this.triggerCommand(`__vitest_hover`,this.selector,e)}unhover(e){return this.triggerCommand(`__vitest_hover`,`html > body`,e)}fill(e,T){return this.triggerCommand(`__vitest_fill`,this.selector,e,T)}upload(e,T){return ensureAwaited(async E=>{let D=(Array.isArray(e)?e:[e]).map(async e=>{if(typeof e==`string`)return e;let T=await new Promise((T,E)=>{let D=new FileReader;D.onload=()=>T(D.result),D.onerror=()=>E(Error(`Failed to read file: ${e.name}`)),D.readAsDataURL(e)});return{name:e.name,mimeType:e.type,base64:T.slice(T.indexOf(`,`)+1)}});return getBrowserState().commands.triggerCommand(`__vitest_upload`,[this.selector,await Promise.all(D),T],E)})}dropTo(e,T={}){return this.triggerCommand(`__vitest_dragAndDrop`,this.selector,e.selector,T)}selectOptions(e,T){let E=(Array.isArray(e)?e:[e]).map(e=>typeof e==`string`?e:{element:isLocator(e)?e.selector:selectorEngine.generateSelectorSimple(e)});return this.triggerCommand(`__vitest_selectOptions`,this.selector,E,T)}screenshot(e){return page.screenshot({...e,element:this})}mark(e,T){let E=getWorkerState().current;return!E||!getBrowserState().activeTraceTaskIds.has(E.id)?Promise.resolve():ensureAwaited(E=>getBrowserState().commands.triggerCommand(`__vitest_markTrace`,[{name:e,selector:this.selector,stack:T?.stack??E?.stack}],E))}getByRole(e,T){return this.locator(getByRoleSelector(e,T))}getByAltText(e,T){return this.locator(getByAltTextSelector(e,T))}getByLabelText(e,T){return this.locator(getByLabelSelector(e,T))}getByPlaceholder(e,T){return this.locator(getByPlaceholderSelector(e,T))}getByTestId(T){return this.locator(getByTestIdSelector(server.config.browser.locators.testIdAttribute,T))}getByText(e,T){return this.locator(getByTextSelector(e,T))}getByTitle(e,T){return this.locator(getByTitleSelector(e,T))}filter(e){let T=[];if(e?.hasText&&T.push(`internal:has-text=${escapeForTextSelector(e.hasText)}`),e?.hasNotText&&T.push(`internal:has-not-text=${escapeForTextSelector(e.hasNotText)}`),e?.has){let E=e.has;T.push(`internal:has=${JSON.stringify(E._pwSelector||E.selector)}`)}if(e?.hasNot){let E=e.hasNot;T.push(`internal:has-not=${JSON.stringify(E._pwSelector||E.selector)}`)}if(!T.length)throw Error(`Locator.filter expects at least one filter. None provided.`);return this.locator(T.join(` >> `))}and(e){return this.locator(`internal:and=${JSON.stringify(e._pwSelector||e.selector)}`)}or(e){return this.locator(`internal:or=${JSON.stringify(e._pwSelector||e.selector)}`)}query(){let e=this._parsedSelector||=selectorEngine.parseSelector(this._pwSelector||this.selector);return selectorEngine.querySelector(e,document.documentElement,!0)}element(){let e=this.query();if(!e)throw utils.getElementError(this._pwSelector||this.selector,this._container||document.body);return e}elements(){let e=this._parsedSelector||=selectorEngine.parseSelector(this._pwSelector||this.selector);return selectorEngine.querySelectorAll(e,document.documentElement)}get length(){return this.elements().length}all(){return this.elements().map(e=>this.elementLocator(e))}nth(e){return this.locator(`nth=${e}`)}first(){return this.nth(0)}last(){return this.nth(-1)}toString(){return this.selector}toJSON(){return this.selector}async findElement(e={}){let T=processTimeoutOptions(e),D=T?.timeout,O=T?.strict??!0,k=now(),A=0;for(;;){let e=this.elements();if(e.length===1)return e[0];if(e.length>1){if(O)throw createStrictModeViolationError(this._pwSelector||this.selector,e);return e[0]}let T=now()-k;if(D!=null&&T>=D)throw utils.getElementError(this._pwSelector||this.selector,this._container||document.body);let j=waitForIntervals[Math.min(A++,waitForIntervals.length-1)];await sleep(D==null?j:Math.min(j,D-T))}}triggerCommand(e,...T){return this._errorSource?triggerCommandWithTrace({name:e,arguments:T,errorSource:this._errorSource}):ensureAwaited(E=>triggerCommandWithTrace({name:e,arguments:T,errorSource:E}))}}function triggerCommandWithTrace(e){return getBrowserState().commands.triggerCommand(e.name,e.arguments,e.errorSource)}function createStrictModeViolationError(e,T){let E=T.slice(0,10).map(e=>({preview:selectorEngine.previewNode(e),selector:selectorEngine.generateSelectorSimple(e)})),D=E.map((e,T)=>`\n ${T+1}) ${e.preview} aka ${asLocator(`javascript`,e.selector)}`);return E.length<T.length&&D.push(`
|
|
7
|
+
...`),Error(`strict mode violation: ${asLocator(`javascript`,e)} resolved to ${T.length} elements:${D.join(``)}\n`)}export{triggerCommandWithTrace as A,Locator as L,getAriaRole as a,getAriaDisabled as b,beginAriaCaches as c,getElementAccessibleDescription as d,endAriaCaches as e,getElementAccessibleErrorMessage as f,getAriaChecked as g,getElementAccessibleName as h,isElementVisible as i,cssEscape as j,kAriaCheckedRoles as k,convertToSelector as l,getBrowserState as m,getWorkerState as n,convertElementToCssSelector as o,processTimeoutOptions as p,ensureAwaited as q,getByAltTextSelector as r,getByLabelSelector as s,getByPlaceholderSelector as t,getByRoleSelector as u,getByTestIdSelector as v,getByTextSelector as w,getByTitleSelector as x,getIframeScale as y,selectorEngine as z};
|
package/dist/index.d.ts
CHANGED
|
@@ -62,6 +62,24 @@ declare function parseKeyDef(text: string): {
|
|
|
62
62
|
}[];
|
|
63
63
|
declare function resolveScreenshotPath(testPath: string, name: string, config: ResolvedConfig, customPath: string | undefined): string;
|
|
64
64
|
|
|
65
|
+
/**
|
|
66
|
+
* Copyright (c) Microsoft Corporation.
|
|
67
|
+
*
|
|
68
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
69
|
+
* you may not use this file except in compliance with the License.
|
|
70
|
+
* You may obtain a copy of the License at
|
|
71
|
+
*
|
|
72
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
73
|
+
*
|
|
74
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
75
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
76
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
77
|
+
* See the License for the specific language governing permissions and
|
|
78
|
+
* limitations under the License.
|
|
79
|
+
*/
|
|
80
|
+
type Language = 'javascript';
|
|
81
|
+
declare function asLocator(lang: Language, selector: string, isFrameLocator?: boolean): string;
|
|
82
|
+
|
|
65
83
|
declare function defineBrowserCommand<T extends unknown[]>(fn: BrowserCommand<T>): BrowserCommand<T>;
|
|
66
84
|
|
|
67
85
|
declare const createBrowserServer: BrowserServerFactory;
|
|
@@ -69,5 +87,5 @@ declare function defineBrowserProvider<T extends object = object>(options: Omit<
|
|
|
69
87
|
options?: T;
|
|
70
88
|
}): BrowserProviderOption;
|
|
71
89
|
|
|
72
|
-
export { createBrowserServer, defineBrowserCommand, defineBrowserProvider, parseKeyDef, resolveScreenshotPath };
|
|
90
|
+
export { asLocator, createBrowserServer, defineBrowserCommand, defineBrowserProvider, parseKeyDef, resolveScreenshotPath };
|
|
73
91
|
export type { CustomComparatorsRegistry };
|