page.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  4. var __getOwnPropNames = Object.getOwnPropertyNames;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __export = (target, all) => {
  7. for (var name in all)
  8. __defProp(target, name, { get: all[name], enumerable: true });
  9. };
  10. var __copyProps = (to, from, except, desc) => {
  11. if (from && typeof from === "object" || typeof from === "function") {
  12. for (let key of __getOwnPropNames(from))
  13. if (!__hasOwnProp.call(to, key) && key !== except)
  14. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  15. }
  16. return to;
  17. };
  18. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  19. var page_exports = {};
  20. __export(page_exports, {
  21. BindingCall: () => BindingCall,
  22. Page: () => Page
  23. });
  24. module.exports = __toCommonJS(page_exports);
  25. var import_artifact = require("./artifact");
  26. var import_channelOwner = require("./channelOwner");
  27. var import_clientHelper = require("./clientHelper");
  28. var import_coverage = require("./coverage");
  29. var import_download = require("./download");
  30. var import_elementHandle = require("./elementHandle");
  31. var import_errors = require("./errors");
  32. var import_events = require("./events");
  33. var import_fileChooser = require("./fileChooser");
  34. var import_frame = require("./frame");
  35. var import_harRouter = require("./harRouter");
  36. var import_input = require("./input");
  37. var import_jsHandle = require("./jsHandle");
  38. var import_network = require("./network");
  39. var import_video = require("./video");
  40. var import_waiter = require("./waiter");
  41. var import_worker = require("./worker");
  42. var import_timeoutSettings = require("./timeoutSettings");
  43. var import_assert = require("../utils/isomorphic/assert");
  44. var import_fileUtils = require("./fileUtils");
  45. var import_headers = require("../utils/isomorphic/headers");
  46. var import_stringUtils = require("../utils/isomorphic/stringUtils");
  47. var import_urlMatch = require("../utils/isomorphic/urlMatch");
  48. var import_manualPromise = require("../utils/isomorphic/manualPromise");
  49. var import_rtti = require("../utils/isomorphic/rtti");
  50. var import_consoleMessage = require("./consoleMessage");
  51. class Page extends import_channelOwner.ChannelOwner {
  52. constructor(parent, type, guid, initializer) {
  53. super(parent, type, guid, initializer);
  54. this._frames = /* @__PURE__ */ new Set();
  55. this._workers = /* @__PURE__ */ new Set();
  56. this._closed = false;
  57. this._closedOrCrashedScope = new import_manualPromise.LongStandingScope();
  58. this._routes = [];
  59. this._webSocketRoutes = [];
  60. this._bindings = /* @__PURE__ */ new Map();
  61. this._video = null;
  62. this._closeWasCalled = false;
  63. this._harRouters = [];
  64. this._locatorHandlers = /* @__PURE__ */ new Map();
  65. this._browserContext = parent;
  66. this._timeoutSettings = new import_timeoutSettings.TimeoutSettings(this._platform, this._browserContext._timeoutSettings);
  67. this.keyboard = new import_input.Keyboard(this);
  68. this.mouse = new import_input.Mouse(this);
  69. this.request = this._browserContext.request;
  70. this.touchscreen = new import_input.Touchscreen(this);
  71. this.clock = this._browserContext.clock;
  72. this._mainFrame = import_frame.Frame.from(initializer.mainFrame);
  73. this._mainFrame._page = this;
  74. this._frames.add(this._mainFrame);
  75. this._viewportSize = initializer.viewportSize;
  76. this._closed = initializer.isClosed;
  77. this._opener = Page.fromNullable(initializer.opener);
  78. this._channel.on("bindingCall", ({ binding }) => this._onBinding(BindingCall.from(binding)));
  79. this._channel.on("close", () => this._onClose());
  80. this._channel.on("crash", () => this._onCrash());
  81. this._channel.on("download", ({ url, suggestedFilename, artifact }) => {
  82. const artifactObject = import_artifact.Artifact.from(artifact);
  83. this.emit(import_events.Events.Page.Download, new import_download.Download(this, url, suggestedFilename, artifactObject));
  84. });
  85. this._channel.on("fileChooser", ({ element, isMultiple }) => this.emit(import_events.Events.Page.FileChooser, new import_fileChooser.FileChooser(this, import_elementHandle.ElementHandle.from(element), isMultiple)));
  86. this._channel.on("frameAttached", ({ frame }) => this._onFrameAttached(import_frame.Frame.from(frame)));
  87. this._channel.on("frameDetached", ({ frame }) => this._onFrameDetached(import_frame.Frame.from(frame)));
  88. this._channel.on("locatorHandlerTriggered", ({ uid }) => this._onLocatorHandlerTriggered(uid));
  89. this._channel.on("route", ({ route }) => this._onRoute(import_network.Route.from(route)));
  90. this._channel.on("webSocketRoute", ({ webSocketRoute }) => this._onWebSocketRoute(import_network.WebSocketRoute.from(webSocketRoute)));
  91. this._channel.on("video", ({ artifact }) => {
  92. const artifactObject = import_artifact.Artifact.from(artifact);
  93. this._forceVideo()._artifactReady(artifactObject);
  94. });
  95. this._channel.on("viewportSizeChanged", ({ viewportSize }) => this._viewportSize = viewportSize);
  96. this._channel.on("webSocket", ({ webSocket }) => this.emit(import_events.Events.Page.WebSocket, import_network.WebSocket.from(webSocket)));
  97. this._channel.on("worker", ({ worker }) => this._onWorker(import_worker.Worker.from(worker)));
  98. this.coverage = new import_coverage.Coverage(this._channel);
  99. this.once(import_events.Events.Page.Close, () => this._closedOrCrashedScope.close(this._closeErrorWithReason()));
  100. this.once(import_events.Events.Page.Crash, () => this._closedOrCrashedScope.close(new import_errors.TargetClosedError()));
  101. this._setEventToSubscriptionMapping(/* @__PURE__ */ new Map([
  102. [import_events.Events.Page.Console, "console"],
  103. [import_events.Events.Page.Dialog, "dialog"],
  104. [import_events.Events.Page.Request, "request"],
  105. [import_events.Events.Page.Response, "response"],
  106. [import_events.Events.Page.RequestFinished, "requestFinished"],
  107. [import_events.Events.Page.RequestFailed, "requestFailed"],
  108. [import_events.Events.Page.FileChooser, "fileChooser"]
  109. ]));
  110. }
  111. static from(page) {
  112. return page._object;
  113. }
  114. static fromNullable(page) {
  115. return page ? Page.from(page) : null;
  116. }
  117. _onFrameAttached(frame) {
  118. frame._page = this;
  119. this._frames.add(frame);
  120. if (frame._parentFrame)
  121. frame._parentFrame._childFrames.add(frame);
  122. this.emit(import_events.Events.Page.FrameAttached, frame);
  123. }
  124. _onFrameDetached(frame) {
  125. this._frames.delete(frame);
  126. frame._detached = true;
  127. if (frame._parentFrame)
  128. frame._parentFrame._childFrames.delete(frame);
  129. this.emit(import_events.Events.Page.FrameDetached, frame);
  130. }
  131. async _onRoute(route) {
  132. route._context = this.context();
  133. const routeHandlers = this._routes.slice();
  134. for (const routeHandler of routeHandlers) {
  135. if (this._closeWasCalled || this._browserContext._closingStatus !== "none")
  136. return;
  137. if (!routeHandler.matches(route.request().url()))
  138. continue;
  139. const index = this._routes.indexOf(routeHandler);
  140. if (index === -1)
  141. continue;
  142. if (routeHandler.willExpire())
  143. this._routes.splice(index, 1);
  144. const handled = await routeHandler.handle(route);
  145. if (!this._routes.length)
  146. this._updateInterceptionPatterns({ internal: true }).catch(() => {
  147. });
  148. if (handled)
  149. return;
  150. }
  151. await this._browserContext._onRoute(route);
  152. }
  153. async _onWebSocketRoute(webSocketRoute) {
  154. const routeHandler = this._webSocketRoutes.find((route) => route.matches(webSocketRoute.url()));
  155. if (routeHandler)
  156. await routeHandler.handle(webSocketRoute);
  157. else
  158. await this._browserContext._onWebSocketRoute(webSocketRoute);
  159. }
  160. async _onBinding(bindingCall) {
  161. const func = this._bindings.get(bindingCall._initializer.name);
  162. if (func) {
  163. await bindingCall.call(func);
  164. return;
  165. }
  166. await this._browserContext._onBinding(bindingCall);
  167. }
  168. _onWorker(worker) {
  169. this._workers.add(worker);
  170. worker._page = this;
  171. this.emit(import_events.Events.Page.Worker, worker);
  172. }
  173. _onClose() {
  174. this._closed = true;
  175. this._browserContext._pages.delete(this);
  176. this._disposeHarRouters();
  177. this.emit(import_events.Events.Page.Close, this);
  178. }
  179. _onCrash() {
  180. this.emit(import_events.Events.Page.Crash, this);
  181. }
  182. context() {
  183. return this._browserContext;
  184. }
  185. async opener() {
  186. if (!this._opener || this._opener.isClosed())
  187. return null;
  188. return this._opener;
  189. }
  190. mainFrame() {
  191. return this._mainFrame;
  192. }
  193. frame(frameSelector) {
  194. const name = (0, import_rtti.isString)(frameSelector) ? frameSelector : frameSelector.name;
  195. const url = (0, import_rtti.isObject)(frameSelector) ? frameSelector.url : void 0;
  196. (0, import_assert.assert)(name || url, "Either name or url matcher should be specified");
  197. return this.frames().find((f) => {
  198. if (name)
  199. return f.name() === name;
  200. return (0, import_urlMatch.urlMatches)(this._browserContext._options.baseURL, f.url(), url);
  201. }) || null;
  202. }
  203. frames() {
  204. return [...this._frames];
  205. }
  206. setDefaultNavigationTimeout(timeout) {
  207. this._timeoutSettings.setDefaultNavigationTimeout(timeout);
  208. }
  209. setDefaultTimeout(timeout) {
  210. this._timeoutSettings.setDefaultTimeout(timeout);
  211. }
  212. _forceVideo() {
  213. if (!this._video)
  214. this._video = new import_video.Video(this, this._connection);
  215. return this._video;
  216. }
  217. video() {
  218. if (!this._browserContext._options.recordVideo)
  219. return null;
  220. return this._forceVideo();
  221. }
  222. async $(selector, options) {
  223. return await this._mainFrame.$(selector, options);
  224. }
  225. async waitForSelector(selector, options) {
  226. return await this._mainFrame.waitForSelector(selector, options);
  227. }
  228. async dispatchEvent(selector, type, eventInit, options) {
  229. return await this._mainFrame.dispatchEvent(selector, type, eventInit, options);
  230. }
  231. async evaluateHandle(pageFunction, arg) {
  232. (0, import_jsHandle.assertMaxArguments)(arguments.length, 2);
  233. return await this._mainFrame.evaluateHandle(pageFunction, arg);
  234. }
  235. async $eval(selector, pageFunction, arg) {
  236. (0, import_jsHandle.assertMaxArguments)(arguments.length, 3);
  237. return await this._mainFrame.$eval(selector, pageFunction, arg);
  238. }
  239. async $$eval(selector, pageFunction, arg) {
  240. (0, import_jsHandle.assertMaxArguments)(arguments.length, 3);
  241. return await this._mainFrame.$$eval(selector, pageFunction, arg);
  242. }
  243. async $$(selector) {
  244. return await this._mainFrame.$$(selector);
  245. }
  246. async addScriptTag(options = {}) {
  247. return await this._mainFrame.addScriptTag(options);
  248. }
  249. async addStyleTag(options = {}) {
  250. return await this._mainFrame.addStyleTag(options);
  251. }
  252. async exposeFunction(name, callback) {
  253. await this._channel.exposeBinding({ name });
  254. const binding = (source, ...args) => callback(...args);
  255. this._bindings.set(name, binding);
  256. }
  257. async exposeBinding(name, callback, options = {}) {
  258. await this._channel.exposeBinding({ name, needsHandle: options.handle });
  259. this._bindings.set(name, callback);
  260. }
  261. async setExtraHTTPHeaders(headers) {
  262. (0, import_network.validateHeaders)(headers);
  263. await this._channel.setExtraHTTPHeaders({ headers: (0, import_headers.headersObjectToArray)(headers) });
  264. }
  265. url() {
  266. return this._mainFrame.url();
  267. }
  268. async content() {
  269. return await this._mainFrame.content();
  270. }
  271. async setContent(html, options) {
  272. return await this._mainFrame.setContent(html, options);
  273. }
  274. async goto(url, options) {
  275. return await this._mainFrame.goto(url, options);
  276. }
  277. async reload(options = {}) {
  278. const waitUntil = (0, import_frame.verifyLoadState)("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
  279. return import_network.Response.fromNullable((await this._channel.reload({ ...options, waitUntil, timeout: this._timeoutSettings.navigationTimeout(options) })).response);
  280. }
  281. async addLocatorHandler(locator, handler, options = {}) {
  282. if (locator._frame !== this._mainFrame)
  283. throw new Error(`Locator must belong to the main frame of this page`);
  284. if (options.times === 0)
  285. return;
  286. const { uid } = await this._channel.registerLocatorHandler({ selector: locator._selector, noWaitAfter: options.noWaitAfter });
  287. this._locatorHandlers.set(uid, { locator, handler, times: options.times });
  288. }
  289. async _onLocatorHandlerTriggered(uid) {
  290. let remove = false;
  291. try {
  292. const handler = this._locatorHandlers.get(uid);
  293. if (handler && handler.times !== 0) {
  294. if (handler.times !== void 0)
  295. handler.times--;
  296. await handler.handler(handler.locator);
  297. }
  298. remove = handler?.times === 0;
  299. } finally {
  300. if (remove)
  301. this._locatorHandlers.delete(uid);
  302. this._channel.resolveLocatorHandlerNoReply({ uid, remove }).catch(() => {
  303. });
  304. }
  305. }
  306. async removeLocatorHandler(locator) {
  307. for (const [uid, data] of this._locatorHandlers) {
  308. if (data.locator._equals(locator)) {
  309. this._locatorHandlers.delete(uid);
  310. await this._channel.unregisterLocatorHandler({ uid }).catch(() => {
  311. });
  312. }
  313. }
  314. }
  315. async waitForLoadState(state, options) {
  316. return await this._mainFrame.waitForLoadState(state, options);
  317. }
  318. async waitForNavigation(options) {
  319. return await this._mainFrame.waitForNavigation(options);
  320. }
  321. async waitForURL(url, options) {
  322. return await this._mainFrame.waitForURL(url, options);
  323. }
  324. async waitForRequest(urlOrPredicate, options = {}) {
  325. const predicate = async (request) => {
  326. if ((0, import_rtti.isString)(urlOrPredicate) || (0, import_rtti.isRegExp)(urlOrPredicate))
  327. return (0, import_urlMatch.urlMatches)(this._browserContext._options.baseURL, request.url(), urlOrPredicate);
  328. return await urlOrPredicate(request);
  329. };
  330. const trimmedUrl = trimUrl(urlOrPredicate);
  331. const logLine = trimmedUrl ? `waiting for request ${trimmedUrl}` : void 0;
  332. return await this._waitForEvent(import_events.Events.Page.Request, { predicate, timeout: options.timeout }, logLine);
  333. }
  334. async waitForResponse(urlOrPredicate, options = {}) {
  335. const predicate = async (response) => {
  336. if ((0, import_rtti.isString)(urlOrPredicate) || (0, import_rtti.isRegExp)(urlOrPredicate))
  337. return (0, import_urlMatch.urlMatches)(this._browserContext._options.baseURL, response.url(), urlOrPredicate);
  338. return await urlOrPredicate(response);
  339. };
  340. const trimmedUrl = trimUrl(urlOrPredicate);
  341. const logLine = trimmedUrl ? `waiting for response ${trimmedUrl}` : void 0;
  342. return await this._waitForEvent(import_events.Events.Page.Response, { predicate, timeout: options.timeout }, logLine);
  343. }
  344. async waitForEvent(event, optionsOrPredicate = {}) {
  345. return await this._waitForEvent(event, optionsOrPredicate, `waiting for event "${event}"`);
  346. }
  347. _closeErrorWithReason() {
  348. return new import_errors.TargetClosedError(this._closeReason || this._browserContext._effectiveCloseReason());
  349. }
  350. async _waitForEvent(event, optionsOrPredicate, logLine) {
  351. return await this._wrapApiCall(async () => {
  352. const timeout = this._timeoutSettings.timeout(typeof optionsOrPredicate === "function" ? {} : optionsOrPredicate);
  353. const predicate = typeof optionsOrPredicate === "function" ? optionsOrPredicate : optionsOrPredicate.predicate;
  354. const waiter = import_waiter.Waiter.createForEvent(this, event);
  355. if (logLine)
  356. waiter.log(logLine);
  357. waiter.rejectOnTimeout(timeout, `Timeout ${timeout}ms exceeded while waiting for event "${event}"`);
  358. if (event !== import_events.Events.Page.Crash)
  359. waiter.rejectOnEvent(this, import_events.Events.Page.Crash, new Error("Page crashed"));
  360. if (event !== import_events.Events.Page.Close)
  361. waiter.rejectOnEvent(this, import_events.Events.Page.Close, () => this._closeErrorWithReason());
  362. const result = await waiter.waitForEvent(this, event, predicate);
  363. waiter.dispose();
  364. return result;
  365. });
  366. }
  367. async goBack(options = {}) {
  368. const waitUntil = (0, import_frame.verifyLoadState)("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
  369. return import_network.Response.fromNullable((await this._channel.goBack({ ...options, waitUntil, timeout: this._timeoutSettings.navigationTimeout(options) })).response);
  370. }
  371. async goForward(options = {}) {
  372. const waitUntil = (0, import_frame.verifyLoadState)("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
  373. return import_network.Response.fromNullable((await this._channel.goForward({ ...options, waitUntil, timeout: this._timeoutSettings.navigationTimeout(options) })).response);
  374. }
  375. async requestGC() {
  376. await this._channel.requestGC();
  377. }
  378. async emulateMedia(options = {}) {
  379. await this._channel.emulateMedia({
  380. media: options.media === null ? "no-override" : options.media,
  381. colorScheme: options.colorScheme === null ? "no-override" : options.colorScheme,
  382. reducedMotion: options.reducedMotion === null ? "no-override" : options.reducedMotion,
  383. forcedColors: options.forcedColors === null ? "no-override" : options.forcedColors,
  384. contrast: options.contrast === null ? "no-override" : options.contrast
  385. });
  386. }
  387. async setViewportSize(viewportSize) {
  388. this._viewportSize = viewportSize;
  389. await this._channel.setViewportSize({ viewportSize });
  390. }
  391. viewportSize() {
  392. return this._viewportSize || null;
  393. }
  394. async evaluate(pageFunction, arg) {
  395. (0, import_jsHandle.assertMaxArguments)(arguments.length, 2);
  396. return await this._mainFrame.evaluate(pageFunction, arg);
  397. }
  398. async _evaluateFunction(functionDeclaration) {
  399. return this._mainFrame._evaluateFunction(functionDeclaration);
  400. }
  401. async addInitScript(script, arg) {
  402. const source = await (0, import_clientHelper.evaluationScript)(this._platform, script, arg);
  403. await this._channel.addInitScript({ source });
  404. }
  405. async route(url, handler, options = {}) {
  406. this._routes.unshift(new import_network.RouteHandler(this._platform, this._browserContext._options.baseURL, url, handler, options.times));
  407. await this._updateInterceptionPatterns({ title: "Route requests" });
  408. }
  409. async routeFromHAR(har, options = {}) {
  410. const localUtils = this._connection.localUtils();
  411. if (!localUtils)
  412. throw new Error("Route from har is not supported in thin clients");
  413. if (options.update) {
  414. await this._browserContext._recordIntoHAR(har, this, options);
  415. return;
  416. }
  417. const harRouter = await import_harRouter.HarRouter.create(localUtils, har, options.notFound || "abort", { urlMatch: options.url });
  418. this._harRouters.push(harRouter);
  419. await harRouter.addPageRoute(this);
  420. }
  421. async routeWebSocket(url, handler) {
  422. this._webSocketRoutes.unshift(new import_network.WebSocketRouteHandler(this._browserContext._options.baseURL, url, handler));
  423. await this._updateWebSocketInterceptionPatterns({ title: "Route WebSockets" });
  424. }
  425. _disposeHarRouters() {
  426. this._harRouters.forEach((router) => router.dispose());
  427. this._harRouters = [];
  428. }
  429. async unrouteAll(options) {
  430. await this._unrouteInternal(this._routes, [], options?.behavior);
  431. this._disposeHarRouters();
  432. }
  433. async unroute(url, handler) {
  434. const removed = [];
  435. const remaining = [];
  436. for (const route of this._routes) {
  437. if ((0, import_urlMatch.urlMatchesEqual)(route.url, url) && (!handler || route.handler === handler))
  438. removed.push(route);
  439. else
  440. remaining.push(route);
  441. }
  442. await this._unrouteInternal(removed, remaining, "default");
  443. }
  444. async _unrouteInternal(removed, remaining, behavior) {
  445. this._routes = remaining;
  446. if (behavior && behavior !== "default") {
  447. const promises = removed.map((routeHandler) => routeHandler.stop(behavior));
  448. await Promise.all(promises);
  449. }
  450. await this._updateInterceptionPatterns({ title: "Unroute requests" });
  451. }
  452. async _updateInterceptionPatterns(options) {
  453. const patterns = import_network.RouteHandler.prepareInterceptionPatterns(this._routes);
  454. await this._wrapApiCall(() => this._channel.setNetworkInterceptionPatterns({ patterns }), options);
  455. }
  456. async _updateWebSocketInterceptionPatterns(options) {
  457. const patterns = import_network.WebSocketRouteHandler.prepareInterceptionPatterns(this._webSocketRoutes);
  458. await this._wrapApiCall(() => this._channel.setWebSocketInterceptionPatterns({ patterns }), options);
  459. }
  460. async screenshot(options = {}) {
  461. const mask = options.mask;
  462. const copy = { ...options, mask: void 0, timeout: this._timeoutSettings.timeout(options) };
  463. if (!copy.type)
  464. copy.type = (0, import_elementHandle.determineScreenshotType)(options);
  465. if (mask) {
  466. copy.mask = mask.map((locator) => ({
  467. frame: locator._frame._channel,
  468. selector: locator._selector
  469. }));
  470. }
  471. const result = await this._channel.screenshot(copy);
  472. if (options.path) {
  473. await (0, import_fileUtils.mkdirIfNeeded)(this._platform, options.path);
  474. await this._platform.fs().promises.writeFile(options.path, result.binary);
  475. }
  476. return result.binary;
  477. }
  478. async _expectScreenshot(options) {
  479. const mask = options?.mask ? options?.mask.map((locator2) => ({
  480. frame: locator2._frame._channel,
  481. selector: locator2._selector
  482. })) : void 0;
  483. const locator = options.locator ? {
  484. frame: options.locator._frame._channel,
  485. selector: options.locator._selector
  486. } : void 0;
  487. return await this._channel.expectScreenshot({
  488. ...options,
  489. isNot: !!options.isNot,
  490. locator,
  491. mask
  492. });
  493. }
  494. async title() {
  495. return await this._mainFrame.title();
  496. }
  497. async bringToFront() {
  498. await this._channel.bringToFront();
  499. }
  500. async [Symbol.asyncDispose]() {
  501. await this.close();
  502. }
  503. async close(options = {}) {
  504. this._closeReason = options.reason;
  505. this._closeWasCalled = true;
  506. try {
  507. if (this._ownedContext)
  508. await this._ownedContext.close();
  509. else
  510. await this._channel.close(options);
  511. } catch (e) {
  512. if ((0, import_errors.isTargetClosedError)(e) && !options.runBeforeUnload)
  513. return;
  514. throw e;
  515. }
  516. }
  517. isClosed() {
  518. return this._closed;
  519. }
  520. async click(selector, options) {
  521. return await this._mainFrame.click(selector, options);
  522. }
  523. async dragAndDrop(source, target, options) {
  524. return await this._mainFrame.dragAndDrop(source, target, options);
  525. }
  526. async dblclick(selector, options) {
  527. await this._mainFrame.dblclick(selector, options);
  528. }
  529. async tap(selector, options) {
  530. return await this._mainFrame.tap(selector, options);
  531. }
  532. async fill(selector, value, options) {
  533. return await this._mainFrame.fill(selector, value, options);
  534. }
  535. async consoleMessages() {
  536. const { messages } = await this._channel.consoleMessages();
  537. return messages.map((message) => new import_consoleMessage.ConsoleMessage(this._platform, message, this, null));
  538. }
  539. async pageErrors() {
  540. const { errors } = await this._channel.pageErrors();
  541. return errors.map((error) => (0, import_errors.parseError)(error));
  542. }
  543. locator(selector, options) {
  544. return this.mainFrame().locator(selector, options);
  545. }
  546. getByTestId(testId) {
  547. return this.mainFrame().getByTestId(testId);
  548. }
  549. getByAltText(text, options) {
  550. return this.mainFrame().getByAltText(text, options);
  551. }
  552. getByLabel(text, options) {
  553. return this.mainFrame().getByLabel(text, options);
  554. }
  555. getByPlaceholder(text, options) {
  556. return this.mainFrame().getByPlaceholder(text, options);
  557. }
  558. getByText(text, options) {
  559. return this.mainFrame().getByText(text, options);
  560. }
  561. getByTitle(text, options) {
  562. return this.mainFrame().getByTitle(text, options);
  563. }
  564. getByRole(role, options = {}) {
  565. return this.mainFrame().getByRole(role, options);
  566. }
  567. frameLocator(selector) {
  568. return this.mainFrame().frameLocator(selector);
  569. }
  570. async focus(selector, options) {
  571. return await this._mainFrame.focus(selector, options);
  572. }
  573. async textContent(selector, options) {
  574. return await this._mainFrame.textContent(selector, options);
  575. }
  576. async innerText(selector, options) {
  577. return await this._mainFrame.innerText(selector, options);
  578. }
  579. async innerHTML(selector, options) {
  580. return await this._mainFrame.innerHTML(selector, options);
  581. }
  582. async getAttribute(selector, name, options) {
  583. return await this._mainFrame.getAttribute(selector, name, options);
  584. }
  585. async inputValue(selector, options) {
  586. return await this._mainFrame.inputValue(selector, options);
  587. }
  588. async isChecked(selector, options) {
  589. return await this._mainFrame.isChecked(selector, options);
  590. }
  591. async isDisabled(selector, options) {
  592. return await this._mainFrame.isDisabled(selector, options);
  593. }
  594. async isEditable(selector, options) {
  595. return await this._mainFrame.isEditable(selector, options);
  596. }
  597. async isEnabled(selector, options) {
  598. return await this._mainFrame.isEnabled(selector, options);
  599. }
  600. async isHidden(selector, options) {
  601. return await this._mainFrame.isHidden(selector, options);
  602. }
  603. async isVisible(selector, options) {
  604. return await this._mainFrame.isVisible(selector, options);
  605. }
  606. async hover(selector, options) {
  607. return await this._mainFrame.hover(selector, options);
  608. }
  609. async selectOption(selector, values, options) {
  610. return await this._mainFrame.selectOption(selector, values, options);
  611. }
  612. async setInputFiles(selector, files, options) {
  613. return await this._mainFrame.setInputFiles(selector, files, options);
  614. }
  615. async type(selector, text, options) {
  616. return await this._mainFrame.type(selector, text, options);
  617. }
  618. async press(selector, key, options) {
  619. return await this._mainFrame.press(selector, key, options);
  620. }
  621. async check(selector, options) {
  622. return await this._mainFrame.check(selector, options);
  623. }
  624. async uncheck(selector, options) {
  625. return await this._mainFrame.uncheck(selector, options);
  626. }
  627. async setChecked(selector, checked, options) {
  628. return await this._mainFrame.setChecked(selector, checked, options);
  629. }
  630. async waitForTimeout(timeout) {
  631. return await this._mainFrame.waitForTimeout(timeout);
  632. }
  633. async waitForFunction(pageFunction, arg, options) {
  634. return await this._mainFrame.waitForFunction(pageFunction, arg, options);
  635. }
  636. async requests() {
  637. const { requests } = await this._channel.requests();
  638. return requests.map((request) => import_network.Request.from(request));
  639. }
  640. workers() {
  641. return [...this._workers];
  642. }
  643. async pause(_options) {
  644. if (this._platform.isJSDebuggerAttached())
  645. return;
  646. const defaultNavigationTimeout = this._browserContext._timeoutSettings.defaultNavigationTimeout();
  647. const defaultTimeout = this._browserContext._timeoutSettings.defaultTimeout();
  648. this._browserContext.setDefaultNavigationTimeout(0);
  649. this._browserContext.setDefaultTimeout(0);
  650. this._instrumentation?.onWillPause({ keepTestTimeout: !!_options?.__testHookKeepTestTimeout });
  651. await this._closedOrCrashedScope.safeRace(this.context()._channel.pause());
  652. this._browserContext.setDefaultNavigationTimeout(defaultNavigationTimeout);
  653. this._browserContext.setDefaultTimeout(defaultTimeout);
  654. }
  655. async pdf(options = {}) {
  656. const transportOptions = { ...options };
  657. if (transportOptions.margin)
  658. transportOptions.margin = { ...transportOptions.margin };
  659. if (typeof options.width === "number")
  660. transportOptions.width = options.width + "px";
  661. if (typeof options.height === "number")
  662. transportOptions.height = options.height + "px";
  663. for (const margin of ["top", "right", "bottom", "left"]) {
  664. const index = margin;
  665. if (options.margin && typeof options.margin[index] === "number")
  666. transportOptions.margin[index] = transportOptions.margin[index] + "px";
  667. }
  668. const result = await this._channel.pdf(transportOptions);
  669. if (options.path) {
  670. const platform = this._platform;
  671. await platform.fs().promises.mkdir(platform.path().dirname(options.path), { recursive: true });
  672. await platform.fs().promises.writeFile(options.path, result.pdf);
  673. }
  674. return result.pdf;
  675. }
  676. async _snapshotForAI(options = {}) {
  677. return await this._channel.snapshotForAI({ timeout: this._timeoutSettings.timeout(options), track: options.track });
  678. }
  679. }
  680. class BindingCall extends import_channelOwner.ChannelOwner {
  681. static from(channel) {
  682. return channel._object;
  683. }
  684. constructor(parent, type, guid, initializer) {
  685. super(parent, type, guid, initializer);
  686. }
  687. async call(func) {
  688. try {
  689. const frame = import_frame.Frame.from(this._initializer.frame);
  690. const source = {
  691. context: frame._page.context(),
  692. page: frame._page,
  693. frame
  694. };
  695. let result;
  696. if (this._initializer.handle)
  697. result = await func(source, import_jsHandle.JSHandle.from(this._initializer.handle));
  698. else
  699. result = await func(source, ...this._initializer.args.map(import_jsHandle.parseResult));
  700. this._channel.resolve({ result: (0, import_jsHandle.serializeArgument)(result) }).catch(() => {
  701. });
  702. } catch (e) {
  703. this._channel.reject({ error: (0, import_errors.serializeError)(e) }).catch(() => {
  704. });
  705. }
  706. }
  707. }
  708. function trimUrl(param) {
  709. if ((0, import_rtti.isRegExp)(param))
  710. return `/${(0, import_stringUtils.trimStringWithEllipsis)(param.source, 50)}/${param.flags}`;
  711. if ((0, import_rtti.isString)(param))
  712. return `"${(0, import_stringUtils.trimStringWithEllipsis)(param, 50)}"`;
  713. }
  714. // Annotate the CommonJS export names for ESM import in node:
  715. 0 && (module.exports = {
  716. BindingCall,
  717. Page
  718. });