dom.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __export = (target, all) => {
  9. for (var name in all)
  10. __defProp(target, name, { get: all[name], enumerable: true });
  11. };
  12. var __copyProps = (to, from, except, desc) => {
  13. if (from && typeof from === "object" || typeof from === "function") {
  14. for (let key of __getOwnPropNames(from))
  15. if (!__hasOwnProp.call(to, key) && key !== except)
  16. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  17. }
  18. return to;
  19. };
  20. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  21. // If the importer is in node compatibility mode or this is not an ESM
  22. // file that has been converted to a CommonJS file using a Babel-
  23. // compatible transform (i.e. "__esModule" has not been set), then set
  24. // "default" to the CommonJS "module.exports" for node compatibility.
  25. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  26. mod
  27. ));
  28. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  29. var dom_exports = {};
  30. __export(dom_exports, {
  31. ElementHandle: () => ElementHandle,
  32. FrameExecutionContext: () => FrameExecutionContext,
  33. NonRecoverableDOMError: () => NonRecoverableDOMError,
  34. assertDone: () => assertDone,
  35. isNonRecoverableDOMError: () => isNonRecoverableDOMError,
  36. kUnableToAdoptErrorMessage: () => kUnableToAdoptErrorMessage,
  37. throwElementIsNotAttached: () => throwElementIsNotAttached,
  38. throwRetargetableDOMError: () => throwRetargetableDOMError
  39. });
  40. module.exports = __toCommonJS(dom_exports);
  41. var import_fs = __toESM(require("fs"));
  42. var js = __toESM(require("./javascript"));
  43. var import_utils = require("../utils");
  44. var import_fileUploadUtils = require("./fileUploadUtils");
  45. var rawInjectedScriptSource = __toESM(require("../generated/injectedScriptSource"));
  46. class NonRecoverableDOMError extends Error {
  47. }
  48. function isNonRecoverableDOMError(error) {
  49. return error instanceof NonRecoverableDOMError;
  50. }
  51. class FrameExecutionContext extends js.ExecutionContext {
  52. constructor(delegate, frame, world) {
  53. super(frame, delegate, world || "content-script");
  54. this.frame = frame;
  55. this.world = world;
  56. }
  57. adoptIfNeeded(handle) {
  58. if (handle instanceof ElementHandle && handle._context !== this)
  59. return this.frame._page.delegate.adoptElementHandle(handle, this);
  60. return null;
  61. }
  62. async evaluate(pageFunction, arg) {
  63. return js.evaluate(this, true, pageFunction, arg);
  64. }
  65. async evaluateHandle(pageFunction, arg) {
  66. return js.evaluate(this, false, pageFunction, arg);
  67. }
  68. async evaluateExpression(expression, options, arg) {
  69. return js.evaluateExpression(this, expression, { ...options, returnByValue: true }, arg);
  70. }
  71. async evaluateExpressionHandle(expression, options, arg) {
  72. return js.evaluateExpression(this, expression, { ...options, returnByValue: false }, arg);
  73. }
  74. injectedScript() {
  75. if (!this._injectedScriptPromise) {
  76. const customEngines = [];
  77. const selectorsRegistry = this.frame._page.browserContext.selectors();
  78. for (const [name, { source: source2 }] of selectorsRegistry._engines)
  79. customEngines.push({ name, source: `(${source2})` });
  80. const sdkLanguage = this.frame._page.browserContext._browser.sdkLanguage();
  81. const options = {
  82. isUnderTest: (0, import_utils.isUnderTest)(),
  83. sdkLanguage,
  84. testIdAttributeName: selectorsRegistry.testIdAttributeName(),
  85. stableRafCount: this.frame._page.delegate.rafCountForStablePosition(),
  86. browserName: this.frame._page.browserContext._browser.options.name,
  87. customEngines
  88. };
  89. const source = `
  90. (() => {
  91. const module = {};
  92. ${rawInjectedScriptSource.source}
  93. return new (module.exports.InjectedScript())(globalThis, ${JSON.stringify(options)});
  94. })();
  95. `;
  96. this._injectedScriptPromise = this.rawEvaluateHandle(source).then((handle) => {
  97. handle._setPreview("InjectedScript");
  98. return handle;
  99. });
  100. }
  101. return this._injectedScriptPromise;
  102. }
  103. }
  104. class ElementHandle extends js.JSHandle {
  105. constructor(context, objectId) {
  106. super(context, "node", void 0, objectId);
  107. this.__elementhandle = true;
  108. this._page = context.frame._page;
  109. this._frame = context.frame;
  110. this._initializePreview().catch((e) => {
  111. });
  112. }
  113. async _initializePreview() {
  114. const utility = await this._context.injectedScript();
  115. this._setPreview(await utility.evaluate((injected, e) => "JSHandle@" + injected.previewNode(e), this));
  116. }
  117. asElement() {
  118. return this;
  119. }
  120. async evaluateInUtility(pageFunction, arg) {
  121. try {
  122. const utility = await this._frame._utilityContext();
  123. return await utility.evaluate(pageFunction, [await utility.injectedScript(), this, arg]);
  124. } catch (e) {
  125. if (this._frame.isNonRetriableError(e))
  126. throw e;
  127. return "error:notconnected";
  128. }
  129. }
  130. async evaluateHandleInUtility(pageFunction, arg) {
  131. try {
  132. const utility = await this._frame._utilityContext();
  133. return await utility.evaluateHandle(pageFunction, [await utility.injectedScript(), this, arg]);
  134. } catch (e) {
  135. if (this._frame.isNonRetriableError(e))
  136. throw e;
  137. return "error:notconnected";
  138. }
  139. }
  140. async ownerFrame() {
  141. const frameId = await this._page.delegate.getOwnerFrame(this);
  142. if (!frameId)
  143. return null;
  144. const frame = this._page.frameManager.frame(frameId);
  145. if (frame)
  146. return frame;
  147. for (const page of this._page.browserContext.pages()) {
  148. const frame2 = page.frameManager.frame(frameId);
  149. if (frame2)
  150. return frame2;
  151. }
  152. return null;
  153. }
  154. async isIframeElement() {
  155. return this.evaluateInUtility(([injected, node]) => node && (node.nodeName === "IFRAME" || node.nodeName === "FRAME"), {});
  156. }
  157. async contentFrame() {
  158. const isFrameElement = throwRetargetableDOMError(await this.isIframeElement());
  159. if (!isFrameElement)
  160. return null;
  161. return this._page.delegate.getContentFrame(this);
  162. }
  163. async getAttribute(progress, name) {
  164. return this._frame.getAttribute(progress, ":scope", name, {}, this);
  165. }
  166. async inputValue(progress) {
  167. return this._frame.inputValue(progress, ":scope", {}, this);
  168. }
  169. async textContent(progress) {
  170. return this._frame.textContent(progress, ":scope", {}, this);
  171. }
  172. async innerText(progress) {
  173. return this._frame.innerText(progress, ":scope", {}, this);
  174. }
  175. async innerHTML(progress) {
  176. return this._frame.innerHTML(progress, ":scope", {}, this);
  177. }
  178. async dispatchEvent(progress, type, eventInit = {}) {
  179. return this._frame.dispatchEvent(progress, ":scope", type, eventInit, {}, this);
  180. }
  181. async _scrollRectIntoViewIfNeeded(progress, rect) {
  182. return await progress.race(this._page.delegate.scrollRectIntoViewIfNeeded(this, rect));
  183. }
  184. async _waitAndScrollIntoViewIfNeeded(progress, waitForVisible) {
  185. const result = await this._retryAction(progress, "scroll into view", async () => {
  186. progress.log(` waiting for element to be stable`);
  187. const waitResult = await progress.race(this.evaluateInUtility(async ([injected, node, { waitForVisible: waitForVisible2 }]) => {
  188. return await injected.checkElementStates(node, waitForVisible2 ? ["visible", "stable"] : ["stable"]);
  189. }, { waitForVisible }));
  190. if (waitResult)
  191. return waitResult;
  192. return await this._scrollRectIntoViewIfNeeded(progress);
  193. }, {});
  194. assertDone(throwRetargetableDOMError(result));
  195. }
  196. async scrollIntoViewIfNeeded(progress) {
  197. await this._waitAndScrollIntoViewIfNeeded(
  198. progress,
  199. false
  200. /* waitForVisible */
  201. );
  202. }
  203. async _clickablePoint() {
  204. const intersectQuadWithViewport = (quad) => {
  205. return quad.map((point) => ({
  206. x: Math.min(Math.max(point.x, 0), metrics.width),
  207. y: Math.min(Math.max(point.y, 0), metrics.height)
  208. }));
  209. };
  210. const computeQuadArea = (quad) => {
  211. let area = 0;
  212. for (let i = 0; i < quad.length; ++i) {
  213. const p1 = quad[i];
  214. const p2 = quad[(i + 1) % quad.length];
  215. area += (p1.x * p2.y - p2.x * p1.y) / 2;
  216. }
  217. return Math.abs(area);
  218. };
  219. const [quads, metrics] = await Promise.all([
  220. this._page.delegate.getContentQuads(this),
  221. this._page.mainFrame()._utilityContext().then((utility) => utility.evaluate(() => ({ width: innerWidth, height: innerHeight })))
  222. ]);
  223. if (quads === "error:notconnected")
  224. return quads;
  225. if (!quads || !quads.length)
  226. return "error:notvisible";
  227. const filtered = quads.map((quad) => intersectQuadWithViewport(quad)).filter((quad) => computeQuadArea(quad) > 0.99);
  228. if (!filtered.length)
  229. return "error:notinviewport";
  230. if (this._page.browserContext._browser.options.name === "firefox") {
  231. for (const quad of filtered) {
  232. const integerPoint = findIntegerPointInsideQuad(quad);
  233. if (integerPoint)
  234. return integerPoint;
  235. }
  236. }
  237. return quadMiddlePoint(filtered[0]);
  238. }
  239. async _offsetPoint(offset) {
  240. const [box, border] = await Promise.all([
  241. this.boundingBox(),
  242. this.evaluateInUtility(([injected, node]) => injected.getElementBorderWidth(node), {}).catch((e) => {
  243. })
  244. ]);
  245. if (!box || !border)
  246. return "error:notvisible";
  247. if (border === "error:notconnected")
  248. return border;
  249. return {
  250. x: box.x + border.left + offset.x,
  251. y: box.y + border.top + offset.y
  252. };
  253. }
  254. async _retryAction(progress, actionName, action, options) {
  255. let retry = 0;
  256. const waitTime = [0, 20, 100, 100, 500];
  257. while (true) {
  258. if (retry) {
  259. progress.log(`retrying ${actionName} action${options.trial ? " (trial run)" : ""}`);
  260. const timeout = waitTime[Math.min(retry - 1, waitTime.length - 1)];
  261. if (timeout) {
  262. progress.log(` waiting ${timeout}ms`);
  263. const result2 = await progress.race(this.evaluateInUtility(([injected, node, timeout2]) => new Promise((f) => setTimeout(f, timeout2)), timeout));
  264. if (result2 === "error:notconnected")
  265. return result2;
  266. }
  267. } else {
  268. progress.log(`attempting ${actionName} action${options.trial ? " (trial run)" : ""}`);
  269. }
  270. if (!options.skipActionPreChecks && !options.force)
  271. await this._frame._page.performActionPreChecks(progress);
  272. const result = await action(retry);
  273. ++retry;
  274. if (result === "error:notvisible") {
  275. if (options.force)
  276. throw new NonRecoverableDOMError("Element is not visible");
  277. progress.log(" element is not visible");
  278. continue;
  279. }
  280. if (result === "error:notinviewport") {
  281. if (options.force)
  282. throw new NonRecoverableDOMError("Element is outside of the viewport");
  283. progress.log(" element is outside of the viewport");
  284. continue;
  285. }
  286. if (result === "error:optionsnotfound") {
  287. progress.log(" did not find some options");
  288. continue;
  289. }
  290. if (result === "error:optionnotenabled") {
  291. progress.log(" option being selected is not enabled");
  292. continue;
  293. }
  294. if (typeof result === "object" && "hitTargetDescription" in result) {
  295. progress.log(` ${result.hitTargetDescription} intercepts pointer events`);
  296. continue;
  297. }
  298. if (typeof result === "object" && "missingState" in result) {
  299. progress.log(` element is not ${result.missingState}`);
  300. continue;
  301. }
  302. return result;
  303. }
  304. }
  305. async _retryPointerAction(progress, actionName, waitForEnabled, action, options) {
  306. const skipActionPreChecks = actionName === "move and up";
  307. return await this._retryAction(progress, actionName, async (retry) => {
  308. const scrollOptions = [
  309. void 0,
  310. { block: "end", inline: "end" },
  311. { block: "center", inline: "center" },
  312. { block: "start", inline: "start" }
  313. ];
  314. const forceScrollOptions = scrollOptions[retry % scrollOptions.length];
  315. return await this._performPointerAction(progress, actionName, waitForEnabled, action, forceScrollOptions, options);
  316. }, { ...options, skipActionPreChecks });
  317. }
  318. async _performPointerAction(progress, actionName, waitForEnabled, action, forceScrollOptions, options) {
  319. const { force = false, position } = options;
  320. const doScrollIntoView = async () => {
  321. if (forceScrollOptions) {
  322. return await this.evaluateInUtility(([injected, node, options2]) => {
  323. if (node.nodeType === 1)
  324. node.scrollIntoView(options2);
  325. return "done";
  326. }, forceScrollOptions);
  327. }
  328. return await this._scrollRectIntoViewIfNeeded(progress, position ? { x: position.x, y: position.y, width: 0, height: 0 } : void 0);
  329. };
  330. if (this._frame.parentFrame()) {
  331. await progress.race(doScrollIntoView().catch(() => {
  332. }));
  333. }
  334. if (options.__testHookBeforeStable)
  335. await progress.race(options.__testHookBeforeStable());
  336. if (!force) {
  337. const elementStates = waitForEnabled ? ["visible", "enabled", "stable"] : ["visible", "stable"];
  338. progress.log(` waiting for element to be ${waitForEnabled ? "visible, enabled and stable" : "visible and stable"}`);
  339. const result = await progress.race(this.evaluateInUtility(async ([injected, node, { elementStates: elementStates2 }]) => {
  340. return await injected.checkElementStates(node, elementStates2);
  341. }, { elementStates }));
  342. if (result)
  343. return result;
  344. progress.log(` element is ${waitForEnabled ? "visible, enabled and stable" : "visible and stable"}`);
  345. }
  346. if (options.__testHookAfterStable)
  347. await progress.race(options.__testHookAfterStable());
  348. progress.log(" scrolling into view if needed");
  349. const scrolled = await progress.race(doScrollIntoView());
  350. if (scrolled !== "done")
  351. return scrolled;
  352. progress.log(" done scrolling");
  353. const maybePoint = position ? await progress.race(this._offsetPoint(position)) : await progress.race(this._clickablePoint());
  354. if (typeof maybePoint === "string")
  355. return maybePoint;
  356. const point = roundPoint(maybePoint);
  357. progress.metadata.point = point;
  358. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  359. let hitTargetInterceptionHandle;
  360. if (force) {
  361. progress.log(` forcing action`);
  362. } else {
  363. if (options.__testHookBeforeHitTarget)
  364. await progress.race(options.__testHookBeforeHitTarget());
  365. const frameCheckResult = await progress.race(this._checkFrameIsHitTarget(point));
  366. if (frameCheckResult === "error:notconnected" || "hitTargetDescription" in frameCheckResult)
  367. return frameCheckResult;
  368. const hitPoint = frameCheckResult.framePoint;
  369. const actionType = actionName === "move and up" ? "drag" : actionName === "hover" || actionName === "tap" ? actionName : "mouse";
  370. const handle = await progress.race(this.evaluateHandleInUtility(([injected, node, { actionType: actionType2, hitPoint: hitPoint2, trial }]) => injected.setupHitTargetInterceptor(node, actionType2, hitPoint2, trial), { actionType, hitPoint, trial: !!options.trial }));
  371. if (handle === "error:notconnected")
  372. return handle;
  373. if (!handle._objectId) {
  374. const error = handle.rawValue();
  375. if (error === "error:notconnected")
  376. return error;
  377. return { hitTargetDescription: error };
  378. }
  379. hitTargetInterceptionHandle = handle;
  380. }
  381. const actionResult = await this._page.frameManager.waitForSignalsCreatedBy(progress, options.waitAfter === true, async () => {
  382. if (options.__testHookBeforePointerAction)
  383. await progress.race(options.__testHookBeforePointerAction());
  384. let restoreModifiers;
  385. if (options && options.modifiers)
  386. restoreModifiers = await this._page.keyboard.ensureModifiers(progress, options.modifiers);
  387. progress.log(` performing ${actionName} action`);
  388. await action(point);
  389. if (restoreModifiers)
  390. await this._page.keyboard.ensureModifiers(progress, restoreModifiers);
  391. if (hitTargetInterceptionHandle) {
  392. const stopHitTargetInterception = this._frame.raceAgainstEvaluationStallingEvents(() => {
  393. return hitTargetInterceptionHandle.evaluate((h) => h.stop());
  394. }).catch((e) => "done").finally(() => {
  395. hitTargetInterceptionHandle?.dispose();
  396. });
  397. if (options.waitAfter !== false) {
  398. const hitTargetResult = await progress.race(stopHitTargetInterception);
  399. if (hitTargetResult !== "done")
  400. return hitTargetResult;
  401. }
  402. }
  403. progress.log(` ${options.trial ? "trial " : ""}${actionName} action done`);
  404. progress.log(" waiting for scheduled navigations to finish");
  405. if (options.__testHookAfterPointerAction)
  406. await progress.race(options.__testHookAfterPointerAction());
  407. return "done";
  408. }).finally(() => {
  409. const stopPromise = hitTargetInterceptionHandle?.evaluate((h) => h.stop()).catch(() => {
  410. });
  411. stopPromise?.then(() => hitTargetInterceptionHandle?.dispose());
  412. });
  413. if (actionResult !== "done")
  414. return actionResult;
  415. progress.log(" navigations have finished");
  416. return "done";
  417. }
  418. async _markAsTargetElement(progress) {
  419. if (!progress.metadata.id)
  420. return;
  421. await progress.race(this.evaluateInUtility(([injected, node, callId]) => {
  422. if (node.nodeType === 1)
  423. injected.markTargetElements(/* @__PURE__ */ new Set([node]), callId);
  424. }, progress.metadata.id));
  425. }
  426. async hover(progress, options) {
  427. await this._markAsTargetElement(progress);
  428. const result = await this._hover(progress, options);
  429. return assertDone(throwRetargetableDOMError(result));
  430. }
  431. _hover(progress, options) {
  432. return this._retryPointerAction(progress, "hover", false, (point) => this._page.mouse.move(progress, point.x, point.y), { ...options, waitAfter: "disabled" });
  433. }
  434. async click(progress, options) {
  435. await this._markAsTargetElement(progress);
  436. const result = await this._click(progress, { ...options, waitAfter: !options.noWaitAfter });
  437. return assertDone(throwRetargetableDOMError(result));
  438. }
  439. _click(progress, options) {
  440. return this._retryPointerAction(progress, "click", true, (point) => this._page.mouse.click(progress, point.x, point.y, options), options);
  441. }
  442. async dblclick(progress, options) {
  443. await this._markAsTargetElement(progress);
  444. const result = await this._dblclick(progress, options);
  445. return assertDone(throwRetargetableDOMError(result));
  446. }
  447. _dblclick(progress, options) {
  448. return this._retryPointerAction(progress, "dblclick", true, (point) => this._page.mouse.click(progress, point.x, point.y, { ...options, clickCount: 2 }), { ...options, waitAfter: "disabled" });
  449. }
  450. async tap(progress, options) {
  451. await this._markAsTargetElement(progress);
  452. const result = await this._tap(progress, options);
  453. return assertDone(throwRetargetableDOMError(result));
  454. }
  455. _tap(progress, options) {
  456. return this._retryPointerAction(progress, "tap", true, (point) => this._page.touchscreen.tap(progress, point.x, point.y), { ...options, waitAfter: "disabled" });
  457. }
  458. async selectOption(progress, elements, values, options) {
  459. await this._markAsTargetElement(progress);
  460. const result = await this._selectOption(progress, elements, values, options);
  461. return throwRetargetableDOMError(result);
  462. }
  463. async _selectOption(progress, elements, values, options) {
  464. let resultingOptions = [];
  465. const result = await this._retryAction(progress, "select option", async () => {
  466. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  467. if (!options.force)
  468. progress.log(` waiting for element to be visible and enabled`);
  469. const optionsToSelect = [...elements, ...values];
  470. const result2 = await progress.race(this.evaluateInUtility(async ([injected, node, { optionsToSelect: optionsToSelect2, force }]) => {
  471. if (!force) {
  472. const checkResult = await injected.checkElementStates(node, ["visible", "enabled"]);
  473. if (checkResult)
  474. return checkResult;
  475. }
  476. return injected.selectOptions(node, optionsToSelect2);
  477. }, { optionsToSelect, force: options.force }));
  478. if (Array.isArray(result2)) {
  479. progress.log(" selected specified option(s)");
  480. resultingOptions = result2;
  481. return "done";
  482. }
  483. return result2;
  484. }, options);
  485. if (result === "error:notconnected")
  486. return result;
  487. return resultingOptions;
  488. }
  489. async fill(progress, value, options) {
  490. await this._markAsTargetElement(progress);
  491. const result = await this._fill(progress, value, options);
  492. assertDone(throwRetargetableDOMError(result));
  493. }
  494. async _fill(progress, value, options) {
  495. progress.log(` fill("${value}")`);
  496. return await this._retryAction(progress, "fill", async () => {
  497. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  498. if (!options.force)
  499. progress.log(" waiting for element to be visible, enabled and editable");
  500. const result = await progress.race(this.evaluateInUtility(async ([injected, node, { value: value2, force }]) => {
  501. if (!force) {
  502. const checkResult = await injected.checkElementStates(node, ["visible", "enabled", "editable"]);
  503. if (checkResult)
  504. return checkResult;
  505. }
  506. return injected.fill(node, value2);
  507. }, { value, force: options.force }));
  508. if (result === "needsinput") {
  509. if (value)
  510. await this._page.keyboard.insertText(progress, value);
  511. else
  512. await this._page.keyboard.press(progress, "Delete");
  513. return "done";
  514. } else {
  515. return result;
  516. }
  517. }, options);
  518. }
  519. async selectText(progress, options) {
  520. const result = await this._retryAction(progress, "selectText", async () => {
  521. if (!options.force)
  522. progress.log(" waiting for element to be visible");
  523. return await progress.race(this.evaluateInUtility(async ([injected, node, { force }]) => {
  524. if (!force) {
  525. const checkResult = await injected.checkElementStates(node, ["visible"]);
  526. if (checkResult)
  527. return checkResult;
  528. }
  529. return injected.selectText(node);
  530. }, { force: options.force }));
  531. }, options);
  532. assertDone(throwRetargetableDOMError(result));
  533. }
  534. async setInputFiles(progress, params) {
  535. const inputFileItems = await progress.race((0, import_fileUploadUtils.prepareFilesForUpload)(this._frame, params));
  536. await this._markAsTargetElement(progress);
  537. const result = await this._setInputFiles(progress, inputFileItems);
  538. return assertDone(throwRetargetableDOMError(result));
  539. }
  540. async _setInputFiles(progress, items) {
  541. const { filePayloads, localPaths, localDirectory } = items;
  542. const multiple = filePayloads && filePayloads.length > 1 || localPaths && localPaths.length > 1;
  543. const result = await progress.race(this.evaluateHandleInUtility(([injected, node, { multiple: multiple2, directoryUpload }]) => {
  544. const element = injected.retarget(node, "follow-label");
  545. if (!element)
  546. return;
  547. if (element.tagName !== "INPUT")
  548. throw injected.createStacklessError("Node is not an HTMLInputElement");
  549. const inputElement = element;
  550. if (multiple2 && !inputElement.multiple && !inputElement.webkitdirectory)
  551. throw injected.createStacklessError("Non-multiple file input can only accept single file");
  552. if (directoryUpload && !inputElement.webkitdirectory)
  553. throw injected.createStacklessError("File input does not support directories, pass individual files instead");
  554. if (!directoryUpload && inputElement.webkitdirectory)
  555. throw injected.createStacklessError("[webkitdirectory] input requires passing a path to a directory");
  556. return inputElement;
  557. }, { multiple, directoryUpload: !!localDirectory }));
  558. if (result === "error:notconnected" || !result.asElement())
  559. return "error:notconnected";
  560. const retargeted = result.asElement();
  561. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  562. if (localPaths || localDirectory) {
  563. const localPathsOrDirectory = localDirectory ? [localDirectory] : localPaths;
  564. await progress.race(Promise.all(localPathsOrDirectory.map((localPath) => import_fs.default.promises.access(localPath, import_fs.default.constants.F_OK))));
  565. const waitForInputEvent = localDirectory ? this.evaluate((node) => new Promise((fulfill) => {
  566. node.addEventListener("input", fulfill, { once: true });
  567. })).catch(() => {
  568. }) : Promise.resolve();
  569. await progress.race(this._page.delegate.setInputFilePaths(retargeted, localPathsOrDirectory));
  570. await progress.race(waitForInputEvent);
  571. } else {
  572. await progress.race(retargeted.evaluateInUtility(([injected, node, files]) => injected.setInputFiles(node, files), filePayloads));
  573. }
  574. return "done";
  575. }
  576. async focus(progress) {
  577. await this._markAsTargetElement(progress);
  578. const result = await this._focus(progress);
  579. return assertDone(throwRetargetableDOMError(result));
  580. }
  581. async _focus(progress, resetSelectionIfNotFocused) {
  582. return await progress.race(this.evaluateInUtility(([injected, node, resetSelectionIfNotFocused2]) => injected.focusNode(node, resetSelectionIfNotFocused2), resetSelectionIfNotFocused));
  583. }
  584. async _blur(progress) {
  585. return await progress.race(this.evaluateInUtility(([injected, node]) => injected.blurNode(node), {}));
  586. }
  587. async type(progress, text, options) {
  588. await this._markAsTargetElement(progress);
  589. const result = await this._type(progress, text, options);
  590. return assertDone(throwRetargetableDOMError(result));
  591. }
  592. async _type(progress, text, options) {
  593. progress.log(`elementHandle.type("${text}")`);
  594. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  595. const result = await this._focus(
  596. progress,
  597. true
  598. /* resetSelectionIfNotFocused */
  599. );
  600. if (result !== "done")
  601. return result;
  602. await this._page.keyboard.type(progress, text, options);
  603. return "done";
  604. }
  605. async press(progress, key, options) {
  606. await this._markAsTargetElement(progress);
  607. const result = await this._press(progress, key, options);
  608. return assertDone(throwRetargetableDOMError(result));
  609. }
  610. async _press(progress, key, options) {
  611. progress.log(`elementHandle.press("${key}")`);
  612. await progress.race(this.instrumentation.onBeforeInputAction(this, progress.metadata));
  613. return this._page.frameManager.waitForSignalsCreatedBy(progress, !options.noWaitAfter, async () => {
  614. const result = await this._focus(
  615. progress,
  616. true
  617. /* resetSelectionIfNotFocused */
  618. );
  619. if (result !== "done")
  620. return result;
  621. await this._page.keyboard.press(progress, key, options);
  622. return "done";
  623. });
  624. }
  625. async check(progress, options) {
  626. const result = await this._setChecked(progress, true, options);
  627. return assertDone(throwRetargetableDOMError(result));
  628. }
  629. async uncheck(progress, options) {
  630. const result = await this._setChecked(progress, false, options);
  631. return assertDone(throwRetargetableDOMError(result));
  632. }
  633. async _setChecked(progress, state, options) {
  634. const isChecked = async () => {
  635. const result2 = await progress.race(this.evaluateInUtility(([injected, node]) => injected.elementState(node, "checked"), {}));
  636. if (result2 === "error:notconnected" || result2.received === "error:notconnected")
  637. throwElementIsNotAttached();
  638. return result2.matches;
  639. };
  640. await this._markAsTargetElement(progress);
  641. if (await isChecked() === state)
  642. return "done";
  643. const result = await this._click(progress, { ...options, waitAfter: "disabled" });
  644. if (result !== "done")
  645. return result;
  646. if (options.trial)
  647. return "done";
  648. if (await isChecked() !== state)
  649. throw new NonRecoverableDOMError("Clicking the checkbox did not change its state");
  650. return "done";
  651. }
  652. async boundingBox() {
  653. return this._page.delegate.getBoundingBox(this);
  654. }
  655. async ariaSnapshot() {
  656. return await this.evaluateInUtility(([injected, element]) => injected.ariaSnapshot(element, { mode: "expect" }), {});
  657. }
  658. async screenshot(progress, options) {
  659. return await this._page.screenshotter.screenshotElement(progress, this, options);
  660. }
  661. async querySelector(selector, options) {
  662. return this._frame.selectors.query(selector, options, this);
  663. }
  664. async querySelectorAll(selector) {
  665. return this._frame.selectors.queryAll(selector, this);
  666. }
  667. async evalOnSelector(selector, strict, expression, isFunction, arg) {
  668. return this._frame.evalOnSelector(selector, strict, expression, isFunction, arg, this);
  669. }
  670. async evalOnSelectorAll(selector, expression, isFunction, arg) {
  671. return this._frame.evalOnSelectorAll(selector, expression, isFunction, arg, this);
  672. }
  673. async isVisible(progress) {
  674. return this._frame.isVisible(progress, ":scope", {}, this);
  675. }
  676. async isHidden(progress) {
  677. return this._frame.isHidden(progress, ":scope", {}, this);
  678. }
  679. async isEnabled(progress) {
  680. return this._frame.isEnabled(progress, ":scope", {}, this);
  681. }
  682. async isDisabled(progress) {
  683. return this._frame.isDisabled(progress, ":scope", {}, this);
  684. }
  685. async isEditable(progress) {
  686. return this._frame.isEditable(progress, ":scope", {}, this);
  687. }
  688. async isChecked(progress) {
  689. return this._frame.isChecked(progress, ":scope", {}, this);
  690. }
  691. async waitForElementState(progress, state) {
  692. const actionName = `wait for ${state}`;
  693. const result = await this._retryAction(progress, actionName, async () => {
  694. return await progress.race(this.evaluateInUtility(async ([injected, node, state2]) => {
  695. return await injected.checkElementStates(node, [state2]) || "done";
  696. }, state));
  697. }, {});
  698. assertDone(throwRetargetableDOMError(result));
  699. }
  700. async waitForSelector(progress, selector, options) {
  701. return await this._frame.waitForSelector(progress, selector, true, options, this);
  702. }
  703. async _adoptTo(context) {
  704. if (this._context !== context) {
  705. const adopted = await this._page.delegate.adoptElementHandle(this, context);
  706. this.dispose();
  707. return adopted;
  708. }
  709. return this;
  710. }
  711. async _checkFrameIsHitTarget(point) {
  712. let frame = this._frame;
  713. const data = [];
  714. while (frame.parentFrame()) {
  715. const frameElement = await frame.frameElement();
  716. const box = await frameElement.boundingBox();
  717. const style = await frameElement.evaluateInUtility(([injected, iframe]) => injected.describeIFrameStyle(iframe), {}).catch((e) => "error:notconnected");
  718. if (!box || style === "error:notconnected")
  719. return "error:notconnected";
  720. if (style === "transformed") {
  721. return { framePoint: void 0 };
  722. }
  723. const pointInFrame = { x: point.x - box.x - style.left, y: point.y - box.y - style.top };
  724. data.push({ frame, frameElement, pointInFrame });
  725. frame = frame.parentFrame();
  726. }
  727. data.push({ frame, frameElement: null, pointInFrame: point });
  728. for (let i = data.length - 1; i > 0; i--) {
  729. const element = data[i - 1].frameElement;
  730. const point2 = data[i].pointInFrame;
  731. const hitTargetResult = await element.evaluateInUtility(([injected, element2, hitPoint]) => {
  732. return injected.expectHitTarget(hitPoint, element2);
  733. }, point2);
  734. if (hitTargetResult !== "done")
  735. return hitTargetResult;
  736. }
  737. return { framePoint: data[0].pointInFrame };
  738. }
  739. }
  740. function throwRetargetableDOMError(result) {
  741. if (result === "error:notconnected")
  742. throwElementIsNotAttached();
  743. return result;
  744. }
  745. function throwElementIsNotAttached() {
  746. throw new Error("Element is not attached to the DOM");
  747. }
  748. function assertDone(result) {
  749. }
  750. function roundPoint(point) {
  751. return {
  752. x: (point.x * 100 | 0) / 100,
  753. y: (point.y * 100 | 0) / 100
  754. };
  755. }
  756. function quadMiddlePoint(quad) {
  757. const result = { x: 0, y: 0 };
  758. for (const point of quad) {
  759. result.x += point.x / 4;
  760. result.y += point.y / 4;
  761. }
  762. return result;
  763. }
  764. function triangleArea(p1, p2, p3) {
  765. return Math.abs(p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y)) / 2;
  766. }
  767. function isPointInsideQuad(point, quad) {
  768. const area1 = triangleArea(point, quad[0], quad[1]) + triangleArea(point, quad[1], quad[2]) + triangleArea(point, quad[2], quad[3]) + triangleArea(point, quad[3], quad[0]);
  769. const area2 = triangleArea(quad[0], quad[1], quad[2]) + triangleArea(quad[1], quad[2], quad[3]);
  770. if (Math.abs(area1 - area2) > 0.1)
  771. return false;
  772. return point.x < Math.max(quad[0].x, quad[1].x, quad[2].x, quad[3].x) && point.y < Math.max(quad[0].y, quad[1].y, quad[2].y, quad[3].y);
  773. }
  774. function findIntegerPointInsideQuad(quad) {
  775. const point = quadMiddlePoint(quad);
  776. point.x = Math.floor(point.x);
  777. point.y = Math.floor(point.y);
  778. if (isPointInsideQuad(point, quad))
  779. return point;
  780. point.x += 1;
  781. if (isPointInsideQuad(point, quad))
  782. return point;
  783. point.y += 1;
  784. if (isPointInsideQuad(point, quad))
  785. return point;
  786. point.x -= 1;
  787. if (isPointInsideQuad(point, quad))
  788. return point;
  789. }
  790. const kUnableToAdoptErrorMessage = "Unable to adopt element handle from a different document";
  791. // Annotate the CommonJS export names for ESM import in node:
  792. 0 && (module.exports = {
  793. ElementHandle,
  794. FrameExecutionContext,
  795. NonRecoverableDOMError,
  796. assertDone,
  797. isNonRecoverableDOMError,
  798. kUnableToAdoptErrorMessage,
  799. throwElementIsNotAttached,
  800. throwRetargetableDOMError
  801. });