dom.js 34 KB

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