page.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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 page_exports = {};
  30. __export(page_exports, {
  31. InitScript: () => InitScript,
  32. Page: () => Page,
  33. PageBinding: () => PageBinding,
  34. Worker: () => Worker
  35. });
  36. module.exports = __toCommonJS(page_exports);
  37. var import_browserContext = require("./browserContext");
  38. var import_console = require("./console");
  39. var import_errors = require("./errors");
  40. var import_fileChooser = require("./fileChooser");
  41. var frames = __toESM(require("./frames"));
  42. var import_helper = require("./helper");
  43. var input = __toESM(require("./input"));
  44. var import_instrumentation = require("./instrumentation");
  45. var js = __toESM(require("./javascript"));
  46. var import_screenshotter = require("./screenshotter");
  47. var import_utils = require("../utils");
  48. var import_utils2 = require("../utils");
  49. var import_comparators = require("./utils/comparators");
  50. var import_debugLogger = require("./utils/debugLogger");
  51. var import_selectorParser = require("../utils/isomorphic/selectorParser");
  52. var import_manualPromise = require("../utils/isomorphic/manualPromise");
  53. var import_utilityScriptSerializers = require("../utils/isomorphic/utilityScriptSerializers");
  54. var import_callLog = require("./callLog");
  55. var rawBindingsControllerSource = __toESM(require("../generated/bindingsControllerSource"));
  56. class Page extends import_instrumentation.SdkObject {
  57. constructor(delegate, browserContext) {
  58. super(browserContext, "page");
  59. this._closedState = "open";
  60. this._closedPromise = new import_manualPromise.ManualPromise();
  61. this._initializedPromise = new import_manualPromise.ManualPromise();
  62. this._consoleMessages = [];
  63. this._pageErrors = [];
  64. this._crashed = false;
  65. this.openScope = new import_utils.LongStandingScope();
  66. this._emulatedMedia = {};
  67. this._fileChooserInterceptedBy = /* @__PURE__ */ new Set();
  68. this._pageBindings = /* @__PURE__ */ new Map();
  69. this.initScripts = [];
  70. this._workers = /* @__PURE__ */ new Map();
  71. this.requestInterceptors = [];
  72. this.video = null;
  73. this._locatorHandlers = /* @__PURE__ */ new Map();
  74. this._lastLocatorHandlerUid = 0;
  75. this._locatorHandlerRunningCounter = 0;
  76. this._networkRequests = [];
  77. // Aiming at 25 fps by default - each frame is 40ms, but we give some slack with 35ms.
  78. // When throttling for tracing, 200ms between frames, except for 10 frames around the action.
  79. this._frameThrottler = new FrameThrottler(10, 35, 200);
  80. this.attribution.page = this;
  81. this.delegate = delegate;
  82. this.browserContext = browserContext;
  83. this.keyboard = new input.Keyboard(delegate.rawKeyboard, this);
  84. this.mouse = new input.Mouse(delegate.rawMouse, this);
  85. this.touchscreen = new input.Touchscreen(delegate.rawTouchscreen, this);
  86. this.screenshotter = new import_screenshotter.Screenshotter(this);
  87. this.frameManager = new frames.FrameManager(this);
  88. if (delegate.pdf)
  89. this.pdf = delegate.pdf.bind(delegate);
  90. this.coverage = delegate.coverage ? delegate.coverage() : null;
  91. this.isStorageStatePage = browserContext.isCreatingStorageStatePage();
  92. }
  93. static {
  94. this.Events = {
  95. Close: "close",
  96. Crash: "crash",
  97. Download: "download",
  98. EmulatedSizeChanged: "emulatedsizechanged",
  99. FileChooser: "filechooser",
  100. FrameAttached: "frameattached",
  101. FrameDetached: "framedetached",
  102. InternalFrameNavigatedToNewDocument: "internalframenavigatedtonewdocument",
  103. LocatorHandlerTriggered: "locatorhandlertriggered",
  104. ScreencastFrame: "screencastframe",
  105. Video: "video",
  106. WebSocket: "websocket",
  107. Worker: "worker"
  108. };
  109. }
  110. async reportAsNew(opener, error) {
  111. if (opener) {
  112. const openerPageOrError = await opener.waitForInitializedOrError();
  113. if (openerPageOrError instanceof Page && !openerPageOrError.isClosed())
  114. this._opener = openerPageOrError;
  115. }
  116. this._markInitialized(error);
  117. }
  118. _markInitialized(error = void 0) {
  119. if (error) {
  120. if (this.browserContext.isClosingOrClosed())
  121. return;
  122. this.frameManager.createDummyMainFrameIfNeeded();
  123. }
  124. this._initialized = error || this;
  125. this.emitOnContext(import_browserContext.BrowserContext.Events.Page, this);
  126. for (const pageError of this._pageErrors)
  127. this.emitOnContext(import_browserContext.BrowserContext.Events.PageError, pageError, this);
  128. for (const message of this._consoleMessages)
  129. this.emitOnContext(import_browserContext.BrowserContext.Events.Console, message);
  130. if (this.isClosed())
  131. this.emit(Page.Events.Close);
  132. else
  133. this.instrumentation.onPageOpen(this);
  134. this._initializedPromise.resolve(this._initialized);
  135. }
  136. initializedOrUndefined() {
  137. return this._initialized ? this : void 0;
  138. }
  139. waitForInitializedOrError() {
  140. return this._initializedPromise;
  141. }
  142. emitOnContext(event, ...args) {
  143. if (this.isStorageStatePage)
  144. return;
  145. this.browserContext.emit(event, ...args);
  146. }
  147. async resetForReuse(progress) {
  148. await this.mainFrame().gotoImpl(progress, "about:blank", {});
  149. this._emulatedSize = void 0;
  150. this._emulatedMedia = {};
  151. this._extraHTTPHeaders = void 0;
  152. await Promise.all([
  153. this.delegate.updateEmulatedViewportSize(),
  154. this.delegate.updateEmulateMedia(),
  155. this.delegate.updateExtraHTTPHeaders()
  156. ]);
  157. await this.delegate.resetForReuse(progress);
  158. }
  159. _didClose() {
  160. this.frameManager.dispose();
  161. this._frameThrottler.dispose();
  162. (0, import_utils.assert)(this._closedState !== "closed", "Page closed twice");
  163. this._closedState = "closed";
  164. this.emit(Page.Events.Close);
  165. this._closedPromise.resolve();
  166. this.instrumentation.onPageClose(this);
  167. this.openScope.close(new import_errors.TargetClosedError());
  168. }
  169. _didCrash() {
  170. this.frameManager.dispose();
  171. this._frameThrottler.dispose();
  172. this.emit(Page.Events.Crash);
  173. this._crashed = true;
  174. this.instrumentation.onPageClose(this);
  175. this.openScope.close(new Error("Page crashed"));
  176. }
  177. async _onFileChooserOpened(handle) {
  178. let multiple;
  179. try {
  180. multiple = await handle.evaluate((element) => !!element.multiple);
  181. } catch (e) {
  182. return;
  183. }
  184. if (!this.listenerCount(Page.Events.FileChooser)) {
  185. handle.dispose();
  186. return;
  187. }
  188. const fileChooser = new import_fileChooser.FileChooser(this, handle, multiple);
  189. this.emit(Page.Events.FileChooser, fileChooser);
  190. }
  191. opener() {
  192. return this._opener;
  193. }
  194. mainFrame() {
  195. return this.frameManager.mainFrame();
  196. }
  197. frames() {
  198. return this.frameManager.frames();
  199. }
  200. async exposeBinding(progress, name, needsHandle, playwrightBinding) {
  201. if (this._pageBindings.has(name))
  202. throw new Error(`Function "${name}" has been already registered`);
  203. if (this.browserContext._pageBindings.has(name))
  204. throw new Error(`Function "${name}" has been already registered in the browser context`);
  205. await progress.race(this.browserContext.exposePlaywrightBindingIfNeeded());
  206. const binding = new PageBinding(name, playwrightBinding, needsHandle);
  207. this._pageBindings.set(name, binding);
  208. try {
  209. await progress.race(this.delegate.addInitScript(binding.initScript));
  210. await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main"));
  211. return binding;
  212. } catch (error) {
  213. this._pageBindings.delete(name);
  214. throw error;
  215. }
  216. }
  217. async removeExposedBindings(bindings) {
  218. bindings = bindings.filter((binding) => this._pageBindings.get(binding.name) === binding);
  219. for (const binding of bindings)
  220. this._pageBindings.delete(binding.name);
  221. await this.delegate.removeInitScripts(bindings.map((binding) => binding.initScript));
  222. const cleanup = bindings.map((binding) => `{ ${binding.cleanupScript} };
  223. `).join("");
  224. await this.safeNonStallingEvaluateInAllFrames(cleanup, "main");
  225. }
  226. async setExtraHTTPHeaders(progress, headers) {
  227. const oldHeaders = this._extraHTTPHeaders;
  228. try {
  229. this._extraHTTPHeaders = headers;
  230. await progress.race(this.delegate.updateExtraHTTPHeaders());
  231. } catch (error) {
  232. this._extraHTTPHeaders = oldHeaders;
  233. this.delegate.updateExtraHTTPHeaders().catch(() => {
  234. });
  235. throw error;
  236. }
  237. }
  238. extraHTTPHeaders() {
  239. return this._extraHTTPHeaders;
  240. }
  241. addNetworkRequest(request) {
  242. this._networkRequests.push(request);
  243. ensureArrayLimit(this._networkRequests, 100);
  244. }
  245. networkRequests() {
  246. return this._networkRequests;
  247. }
  248. async onBindingCalled(payload, context) {
  249. if (this._closedState === "closed")
  250. return;
  251. await PageBinding.dispatch(this, payload, context);
  252. }
  253. addConsoleMessage(worker, type, args, location, text) {
  254. const message = new import_console.ConsoleMessage(this, worker, type, text, args, location);
  255. const intercepted = this.frameManager.interceptConsoleMessage(message);
  256. if (intercepted) {
  257. args.forEach((arg) => arg.dispose());
  258. return;
  259. }
  260. this._consoleMessages.push(message);
  261. ensureArrayLimit(this._consoleMessages, 200);
  262. if (this._initialized)
  263. this.emitOnContext(import_browserContext.BrowserContext.Events.Console, message);
  264. }
  265. consoleMessages() {
  266. return this._consoleMessages;
  267. }
  268. addPageError(pageError) {
  269. this._pageErrors.push(pageError);
  270. ensureArrayLimit(this._pageErrors, 200);
  271. if (this._initialized)
  272. this.emitOnContext(import_browserContext.BrowserContext.Events.PageError, pageError, this);
  273. }
  274. pageErrors() {
  275. return this._pageErrors;
  276. }
  277. async reload(progress, options) {
  278. return this.mainFrame().raceNavigationAction(progress, async () => {
  279. const [response] = await Promise.all([
  280. // Reload must be a new document, and should not be confused with a stray pushState.
  281. this.mainFrame()._waitForNavigation(progress, true, options),
  282. progress.race(this.delegate.reload())
  283. ]);
  284. return response;
  285. });
  286. }
  287. async goBack(progress, options) {
  288. return this.mainFrame().raceNavigationAction(progress, async () => {
  289. let error;
  290. const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {
  291. error = e;
  292. return null;
  293. });
  294. const result = await progress.race(this.delegate.goBack());
  295. if (!result) {
  296. waitPromise.catch(() => {
  297. });
  298. return null;
  299. }
  300. const response = await waitPromise;
  301. if (error)
  302. throw error;
  303. return response;
  304. });
  305. }
  306. async goForward(progress, options) {
  307. return this.mainFrame().raceNavigationAction(progress, async () => {
  308. let error;
  309. const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {
  310. error = e;
  311. return null;
  312. });
  313. const result = await progress.race(this.delegate.goForward());
  314. if (!result) {
  315. waitPromise.catch(() => {
  316. });
  317. return null;
  318. }
  319. const response = await waitPromise;
  320. if (error)
  321. throw error;
  322. return response;
  323. });
  324. }
  325. requestGC() {
  326. return this.delegate.requestGC();
  327. }
  328. registerLocatorHandler(selector, noWaitAfter) {
  329. const uid = ++this._lastLocatorHandlerUid;
  330. this._locatorHandlers.set(uid, { selector, noWaitAfter });
  331. return uid;
  332. }
  333. resolveLocatorHandler(uid, remove) {
  334. const handler = this._locatorHandlers.get(uid);
  335. if (remove)
  336. this._locatorHandlers.delete(uid);
  337. if (handler) {
  338. handler.resolved?.resolve();
  339. handler.resolved = void 0;
  340. }
  341. }
  342. unregisterLocatorHandler(uid) {
  343. this._locatorHandlers.delete(uid);
  344. }
  345. async performActionPreChecks(progress) {
  346. await this._performWaitForNavigationCheck(progress);
  347. await this._performLocatorHandlersCheckpoint(progress);
  348. await this._performWaitForNavigationCheck(progress);
  349. }
  350. async _performWaitForNavigationCheck(progress) {
  351. if (process.env.PLAYWRIGHT_SKIP_NAVIGATION_CHECK)
  352. return;
  353. const mainFrame = this.frameManager.mainFrame();
  354. if (!mainFrame || !mainFrame.pendingDocument())
  355. return;
  356. const url = mainFrame.pendingDocument()?.request?.url();
  357. const toUrl = url ? `" ${(0, import_utils.trimStringWithEllipsis)(url, 200)}"` : "";
  358. progress.log(` waiting for${toUrl} navigation to finish...`);
  359. await import_helper.helper.waitForEvent(progress, mainFrame, frames.Frame.Events.InternalNavigation, (e) => {
  360. if (!e.isPublic)
  361. return false;
  362. if (!e.error)
  363. progress.log(` navigated to "${(0, import_utils.trimStringWithEllipsis)(mainFrame.url(), 200)}"`);
  364. return true;
  365. }).promise;
  366. }
  367. async _performLocatorHandlersCheckpoint(progress) {
  368. if (this._locatorHandlerRunningCounter)
  369. return;
  370. for (const [uid, handler] of this._locatorHandlers) {
  371. if (!handler.resolved) {
  372. if (await this.mainFrame().isVisibleInternal(progress, handler.selector, { strict: true })) {
  373. handler.resolved = new import_manualPromise.ManualPromise();
  374. this.emit(Page.Events.LocatorHandlerTriggered, uid);
  375. }
  376. }
  377. if (handler.resolved) {
  378. ++this._locatorHandlerRunningCounter;
  379. progress.log(` found ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)}, intercepting action to run the handler`);
  380. const promise = handler.resolved.then(async () => {
  381. if (!handler.noWaitAfter) {
  382. progress.log(` locator handler has finished, waiting for ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)} to be hidden`);
  383. await this.mainFrame().waitForSelector(progress, handler.selector, false, { state: "hidden" });
  384. } else {
  385. progress.log(` locator handler has finished`);
  386. }
  387. });
  388. await progress.race(this.openScope.race(promise)).finally(() => --this._locatorHandlerRunningCounter);
  389. progress.log(` interception handler has finished, continuing`);
  390. }
  391. }
  392. }
  393. async emulateMedia(progress, options) {
  394. const oldEmulatedMedia = { ...this._emulatedMedia };
  395. if (options.media !== void 0)
  396. this._emulatedMedia.media = options.media;
  397. if (options.colorScheme !== void 0)
  398. this._emulatedMedia.colorScheme = options.colorScheme;
  399. if (options.reducedMotion !== void 0)
  400. this._emulatedMedia.reducedMotion = options.reducedMotion;
  401. if (options.forcedColors !== void 0)
  402. this._emulatedMedia.forcedColors = options.forcedColors;
  403. if (options.contrast !== void 0)
  404. this._emulatedMedia.contrast = options.contrast;
  405. try {
  406. await progress.race(this.delegate.updateEmulateMedia());
  407. } catch (error) {
  408. this._emulatedMedia = oldEmulatedMedia;
  409. this.delegate.updateEmulateMedia().catch(() => {
  410. });
  411. throw error;
  412. }
  413. }
  414. emulatedMedia() {
  415. const contextOptions = this.browserContext._options;
  416. return {
  417. media: this._emulatedMedia.media || "no-override",
  418. colorScheme: this._emulatedMedia.colorScheme !== void 0 ? this._emulatedMedia.colorScheme : contextOptions.colorScheme ?? "light",
  419. reducedMotion: this._emulatedMedia.reducedMotion !== void 0 ? this._emulatedMedia.reducedMotion : contextOptions.reducedMotion ?? "no-preference",
  420. forcedColors: this._emulatedMedia.forcedColors !== void 0 ? this._emulatedMedia.forcedColors : contextOptions.forcedColors ?? "none",
  421. contrast: this._emulatedMedia.contrast !== void 0 ? this._emulatedMedia.contrast : contextOptions.contrast ?? "no-preference"
  422. };
  423. }
  424. async setViewportSize(progress, viewportSize) {
  425. const oldEmulatedSize = this._emulatedSize;
  426. try {
  427. this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } });
  428. await progress.race(this.delegate.updateEmulatedViewportSize());
  429. } catch (error) {
  430. this._emulatedSize = oldEmulatedSize;
  431. this.delegate.updateEmulatedViewportSize().catch(() => {
  432. });
  433. throw error;
  434. }
  435. }
  436. setEmulatedSizeFromWindowOpen(emulatedSize) {
  437. this._setEmulatedSize(emulatedSize);
  438. }
  439. _setEmulatedSize(emulatedSize) {
  440. this._emulatedSize = emulatedSize;
  441. this.emit(Page.Events.EmulatedSizeChanged);
  442. }
  443. emulatedSize() {
  444. if (this._emulatedSize)
  445. return this._emulatedSize;
  446. const contextOptions = this.browserContext._options;
  447. return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : void 0;
  448. }
  449. async bringToFront() {
  450. await this.delegate.bringToFront();
  451. }
  452. async addInitScript(progress, source) {
  453. const initScript = new InitScript(source);
  454. this.initScripts.push(initScript);
  455. try {
  456. await progress.race(this.delegate.addInitScript(initScript));
  457. } catch (error) {
  458. this.removeInitScripts([initScript]).catch(() => {
  459. });
  460. throw error;
  461. }
  462. return initScript;
  463. }
  464. async removeInitScripts(initScripts) {
  465. const set = new Set(initScripts);
  466. this.initScripts = this.initScripts.filter((script) => !set.has(script));
  467. await this.delegate.removeInitScripts(initScripts);
  468. }
  469. needsRequestInterception() {
  470. return this.requestInterceptors.length > 0 || this.browserContext.requestInterceptors.length > 0;
  471. }
  472. async addRequestInterceptor(progress, handler, prepend) {
  473. if (prepend)
  474. this.requestInterceptors.unshift(handler);
  475. else
  476. this.requestInterceptors.push(handler);
  477. await this.delegate.updateRequestInterception();
  478. }
  479. async removeRequestInterceptor(handler) {
  480. const index = this.requestInterceptors.indexOf(handler);
  481. if (index === -1)
  482. return;
  483. this.requestInterceptors.splice(index, 1);
  484. await this.browserContext.notifyRoutesInFlightAboutRemovedHandler(handler);
  485. await this.delegate.updateRequestInterception();
  486. }
  487. async expectScreenshot(progress, options) {
  488. const locator = options.locator;
  489. const rafrafScreenshot = locator ? async (timeout) => {
  490. return await locator.frame.rafrafTimeoutScreenshotElementWithProgress(progress, locator.selector, timeout, options || {});
  491. } : async (timeout) => {
  492. await this.performActionPreChecks(progress);
  493. await this.mainFrame().rafrafTimeout(progress, timeout);
  494. return await this.screenshotter.screenshotPage(progress, options || {});
  495. };
  496. const comparator = (0, import_comparators.getComparator)("image/png");
  497. if (!options.expected && options.isNot)
  498. return { errorMessage: '"not" matcher requires expected result' };
  499. try {
  500. const format = (0, import_screenshotter.validateScreenshotOptions)(options || {});
  501. if (format !== "png")
  502. throw new Error("Only PNG screenshots are supported");
  503. } catch (error) {
  504. return { errorMessage: error.message };
  505. }
  506. let intermediateResult;
  507. const areEqualScreenshots = (actual, expected, previous) => {
  508. const comparatorResult = actual && expected ? comparator(actual, expected, options) : void 0;
  509. if (comparatorResult !== void 0 && !!comparatorResult === !!options.isNot)
  510. return true;
  511. if (comparatorResult)
  512. intermediateResult = { errorMessage: comparatorResult.errorMessage, diff: comparatorResult.diff, actual, previous };
  513. return false;
  514. };
  515. try {
  516. let actual;
  517. let previous;
  518. const pollIntervals = [0, 100, 250, 500];
  519. progress.log(`${(0, import_utils.renderTitleForCall)(progress.metadata)}${options.timeout ? ` with timeout ${options.timeout}ms` : ""}`);
  520. if (options.expected)
  521. progress.log(` verifying given screenshot expectation`);
  522. else
  523. progress.log(` generating new stable screenshot expectation`);
  524. let isFirstIteration = true;
  525. while (true) {
  526. if (this.isClosed())
  527. throw new Error("The page has closed");
  528. const screenshotTimeout = pollIntervals.shift() ?? 1e3;
  529. if (screenshotTimeout)
  530. progress.log(`waiting ${screenshotTimeout}ms before taking screenshot`);
  531. previous = actual;
  532. actual = await rafrafScreenshot(screenshotTimeout).catch((e) => {
  533. if (this.mainFrame().isNonRetriableError(e))
  534. throw e;
  535. progress.log(`failed to take screenshot - ` + e.message);
  536. return void 0;
  537. });
  538. if (!actual)
  539. continue;
  540. const expectation = options.expected && isFirstIteration ? options.expected : previous;
  541. if (areEqualScreenshots(actual, expectation, previous))
  542. break;
  543. if (intermediateResult)
  544. progress.log(intermediateResult.errorMessage);
  545. isFirstIteration = false;
  546. }
  547. if (!isFirstIteration)
  548. progress.log(`captured a stable screenshot`);
  549. if (!options.expected)
  550. return { actual };
  551. if (isFirstIteration) {
  552. progress.log(`screenshot matched expectation`);
  553. return {};
  554. }
  555. if (areEqualScreenshots(actual, options.expected, void 0)) {
  556. progress.log(`screenshot matched expectation`);
  557. return {};
  558. }
  559. throw new Error(intermediateResult.errorMessage);
  560. } catch (e) {
  561. if (js.isJavaScriptErrorInEvaluate(e) || (0, import_selectorParser.isInvalidSelectorError)(e))
  562. throw e;
  563. let errorMessage = e.message;
  564. if (e instanceof import_errors.TimeoutError && intermediateResult?.previous)
  565. errorMessage = `Failed to take two consecutive stable screenshots.`;
  566. return {
  567. log: (0, import_callLog.compressCallLog)(e.message ? [...progress.metadata.log, e.message] : progress.metadata.log),
  568. ...intermediateResult,
  569. errorMessage,
  570. timedOut: e instanceof import_errors.TimeoutError
  571. };
  572. }
  573. }
  574. async screenshot(progress, options) {
  575. return await this.screenshotter.screenshotPage(progress, options);
  576. }
  577. async close(options = {}) {
  578. if (this._closedState === "closed")
  579. return;
  580. if (options.reason)
  581. this.closeReason = options.reason;
  582. const runBeforeUnload = !!options.runBeforeUnload;
  583. if (this._closedState !== "closing") {
  584. if (!runBeforeUnload)
  585. this._closedState = "closing";
  586. await this.delegate.closePage(runBeforeUnload).catch((e) => import_debugLogger.debugLogger.log("error", e));
  587. }
  588. if (!runBeforeUnload)
  589. await this._closedPromise;
  590. }
  591. isClosed() {
  592. return this._closedState === "closed";
  593. }
  594. hasCrashed() {
  595. return this._crashed;
  596. }
  597. isClosedOrClosingOrCrashed() {
  598. return this._closedState !== "open" || this._crashed;
  599. }
  600. addWorker(workerId, worker) {
  601. this._workers.set(workerId, worker);
  602. this.emit(Page.Events.Worker, worker);
  603. }
  604. removeWorker(workerId) {
  605. const worker = this._workers.get(workerId);
  606. if (!worker)
  607. return;
  608. worker.didClose();
  609. this._workers.delete(workerId);
  610. }
  611. clearWorkers() {
  612. for (const [workerId, worker] of this._workers) {
  613. worker.didClose();
  614. this._workers.delete(workerId);
  615. }
  616. }
  617. async setFileChooserInterceptedBy(enabled, by) {
  618. const wasIntercepted = this.fileChooserIntercepted();
  619. if (enabled)
  620. this._fileChooserInterceptedBy.add(by);
  621. else
  622. this._fileChooserInterceptedBy.delete(by);
  623. if (wasIntercepted !== this.fileChooserIntercepted())
  624. await this.delegate.updateFileChooserInterception();
  625. }
  626. fileChooserIntercepted() {
  627. return this._fileChooserInterceptedBy.size > 0;
  628. }
  629. frameNavigatedToNewDocument(frame) {
  630. this.emit(Page.Events.InternalFrameNavigatedToNewDocument, frame);
  631. const origin = frame.origin();
  632. if (origin)
  633. this.browserContext.addVisitedOrigin(origin);
  634. }
  635. allInitScripts() {
  636. const bindings = [...this.browserContext._pageBindings.values(), ...this._pageBindings.values()].map((binding) => binding.initScript);
  637. if (this.browserContext.bindingsInitScript)
  638. bindings.unshift(this.browserContext.bindingsInitScript);
  639. return [...bindings, ...this.browserContext.initScripts, ...this.initScripts];
  640. }
  641. getBinding(name) {
  642. return this._pageBindings.get(name) || this.browserContext._pageBindings.get(name);
  643. }
  644. setScreencastOptions(options) {
  645. this.delegate.setScreencastOptions(options).catch((e) => import_debugLogger.debugLogger.log("error", e));
  646. this._frameThrottler.setThrottlingEnabled(!!options);
  647. }
  648. throttleScreencastFrameAck(ack) {
  649. this._frameThrottler.ack(ack);
  650. }
  651. temporarilyDisableTracingScreencastThrottling() {
  652. this._frameThrottler.recharge();
  653. }
  654. async safeNonStallingEvaluateInAllFrames(expression, world, options = {}) {
  655. await Promise.all(this.frames().map(async (frame) => {
  656. try {
  657. await frame.nonStallingEvaluateInExistingContext(expression, world);
  658. } catch (e) {
  659. if (options.throwOnJSErrors && js.isJavaScriptErrorInEvaluate(e))
  660. throw e;
  661. }
  662. }));
  663. }
  664. async hideHighlight() {
  665. await Promise.all(this.frames().map((frame) => frame.hideHighlight().catch(() => {
  666. })));
  667. }
  668. async snapshotForAI(progress, options) {
  669. const snapshot = await snapshotFrameForAI(progress, this.mainFrame(), options);
  670. return { full: snapshot.full.join("\n"), incremental: snapshot.incremental?.join("\n") };
  671. }
  672. }
  673. class Worker extends import_instrumentation.SdkObject {
  674. constructor(parent, url) {
  675. super(parent, "worker");
  676. this._executionContextPromise = new import_manualPromise.ManualPromise();
  677. this._workerScriptLoaded = false;
  678. this.existingExecutionContext = null;
  679. this.openScope = new import_utils.LongStandingScope();
  680. this.url = url;
  681. }
  682. static {
  683. this.Events = {
  684. Close: "close"
  685. };
  686. }
  687. createExecutionContext(delegate) {
  688. this.existingExecutionContext = new js.ExecutionContext(this, delegate, "worker");
  689. if (this._workerScriptLoaded)
  690. this._executionContextPromise.resolve(this.existingExecutionContext);
  691. return this.existingExecutionContext;
  692. }
  693. workerScriptLoaded() {
  694. this._workerScriptLoaded = true;
  695. if (this.existingExecutionContext)
  696. this._executionContextPromise.resolve(this.existingExecutionContext);
  697. }
  698. didClose() {
  699. if (this.existingExecutionContext)
  700. this.existingExecutionContext.contextDestroyed("Worker was closed");
  701. this.emit(Worker.Events.Close, this);
  702. this.openScope.close(new Error("Worker closed"));
  703. }
  704. async evaluateExpression(expression, isFunction, arg) {
  705. return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: true, isFunction }, arg);
  706. }
  707. async evaluateExpressionHandle(expression, isFunction, arg) {
  708. return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: false, isFunction }, arg);
  709. }
  710. }
  711. class PageBinding {
  712. static {
  713. this.kController = "__playwright__binding__controller__";
  714. }
  715. static {
  716. this.kBindingName = "__playwright__binding__";
  717. }
  718. static createInitScript() {
  719. return new InitScript(`
  720. (() => {
  721. const module = {};
  722. ${rawBindingsControllerSource.source}
  723. const property = '${PageBinding.kController}';
  724. if (!globalThis[property])
  725. globalThis[property] = new (module.exports.BindingsController())(globalThis, '${PageBinding.kBindingName}');
  726. })();
  727. `);
  728. }
  729. constructor(name, playwrightFunction, needsHandle) {
  730. this.name = name;
  731. this.playwrightFunction = playwrightFunction;
  732. this.initScript = new InitScript(`globalThis['${PageBinding.kController}'].addBinding(${JSON.stringify(name)}, ${needsHandle})`);
  733. this.needsHandle = needsHandle;
  734. this.cleanupScript = `globalThis['${PageBinding.kController}'].removeBinding(${JSON.stringify(name)})`;
  735. }
  736. static async dispatch(page, payload, context) {
  737. const { name, seq, serializedArgs } = JSON.parse(payload);
  738. try {
  739. (0, import_utils.assert)(context.world);
  740. const binding = page.getBinding(name);
  741. if (!binding)
  742. throw new Error(`Function "${name}" is not exposed`);
  743. let result;
  744. if (binding.needsHandle) {
  745. const handle = await context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].takeBindingHandle(arg)`, { isFunction: true }, { name, seq }).catch((e) => null);
  746. result = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, handle);
  747. } else {
  748. if (!Array.isArray(serializedArgs))
  749. throw new Error(`serializedArgs is not an array. This can happen when Array.prototype.toJSON is defined incorrectly`);
  750. const args = serializedArgs.map((a) => (0, import_utilityScriptSerializers.parseEvaluationResultValue)(a));
  751. result = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, ...args);
  752. }
  753. context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, result }).catch((e) => import_debugLogger.debugLogger.log("error", e));
  754. } catch (error) {
  755. context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, error }).catch((e) => import_debugLogger.debugLogger.log("error", e));
  756. }
  757. }
  758. }
  759. class InitScript {
  760. constructor(source) {
  761. this.source = `(() => {
  762. ${source}
  763. })();`;
  764. }
  765. }
  766. class FrameThrottler {
  767. constructor(nonThrottledFrames, defaultInterval, throttlingInterval) {
  768. this._acks = [];
  769. this._throttlingEnabled = false;
  770. this._nonThrottledFrames = nonThrottledFrames;
  771. this._budget = nonThrottledFrames;
  772. this._defaultInterval = defaultInterval;
  773. this._throttlingInterval = throttlingInterval;
  774. this._tick();
  775. }
  776. dispose() {
  777. if (this._timeoutId) {
  778. clearTimeout(this._timeoutId);
  779. this._timeoutId = void 0;
  780. }
  781. }
  782. setThrottlingEnabled(enabled) {
  783. this._throttlingEnabled = enabled;
  784. }
  785. recharge() {
  786. for (const ack of this._acks)
  787. ack();
  788. this._acks = [];
  789. this._budget = this._nonThrottledFrames;
  790. if (this._timeoutId) {
  791. clearTimeout(this._timeoutId);
  792. this._tick();
  793. }
  794. }
  795. ack(ack) {
  796. if (!this._timeoutId) {
  797. ack();
  798. return;
  799. }
  800. this._acks.push(ack);
  801. }
  802. _tick() {
  803. const ack = this._acks.shift();
  804. if (ack) {
  805. --this._budget;
  806. ack();
  807. }
  808. if (this._throttlingEnabled && this._budget <= 0) {
  809. this._timeoutId = setTimeout(() => this._tick(), this._throttlingInterval);
  810. } else {
  811. this._timeoutId = setTimeout(() => this._tick(), this._defaultInterval);
  812. }
  813. }
  814. }
  815. async function snapshotFrameForAI(progress, frame, options) {
  816. const snapshot = await frame.retryWithProgressAndTimeouts(progress, [1e3, 2e3, 4e3, 8e3], async (continuePolling) => {
  817. try {
  818. const context = await progress.race(frame._utilityContext());
  819. const injectedScript = await progress.race(context.injectedScript());
  820. const snapshotOrRetry = await progress.race(injectedScript.evaluate((injected, options2) => {
  821. const node = injected.document.body;
  822. if (!node)
  823. return true;
  824. return injected.incrementalAriaSnapshot(node, { mode: "ai", ...options2 });
  825. }, { refPrefix: frame.seq ? "f" + frame.seq : "", track: options.track }));
  826. if (snapshotOrRetry === true)
  827. return continuePolling;
  828. return snapshotOrRetry;
  829. } catch (e) {
  830. if (frame.isNonRetriableError(e))
  831. throw e;
  832. return continuePolling;
  833. }
  834. });
  835. const childSnapshotPromises = snapshot.iframeRefs.map((ref) => snapshotFrameRefForAI(progress, frame, ref, options));
  836. const childSnapshots = await Promise.all(childSnapshotPromises);
  837. const full = [];
  838. let incremental;
  839. if (snapshot.incremental !== void 0) {
  840. incremental = snapshot.incremental.split("\n");
  841. for (let i = 0; i < snapshot.iframeRefs.length; i++) {
  842. const childSnapshot = childSnapshots[i];
  843. if (childSnapshot.incremental)
  844. incremental.push(...childSnapshot.incremental);
  845. else if (childSnapshot.full.length)
  846. incremental.push("- <changed> iframe [ref=" + snapshot.iframeRefs[i] + "]:", ...childSnapshot.full.map((l) => " " + l));
  847. }
  848. }
  849. for (const line of snapshot.full.split("\n")) {
  850. const match = line.match(/^(\s*)- iframe (?:\[active\] )?\[ref=([^\]]*)\]/);
  851. if (!match) {
  852. full.push(line);
  853. continue;
  854. }
  855. const leadingSpace = match[1];
  856. const ref = match[2];
  857. const childSnapshot = childSnapshots[snapshot.iframeRefs.indexOf(ref)] ?? { full: [] };
  858. full.push(childSnapshot.full.length ? line + ":" : line);
  859. full.push(...childSnapshot.full.map((l) => leadingSpace + " " + l));
  860. }
  861. return { full, incremental };
  862. }
  863. async function snapshotFrameRefForAI(progress, parentFrame, frameRef, options) {
  864. const frameSelector = `aria-ref=${frameRef} >> internal:control=enter-frame`;
  865. const frameBodySelector = `${frameSelector} >> body`;
  866. const child = await progress.race(parentFrame.selectors.resolveFrameForSelector(frameBodySelector, { strict: true }));
  867. if (!child)
  868. return { full: [] };
  869. try {
  870. return await snapshotFrameForAI(progress, child.frame, options);
  871. } catch {
  872. return { full: [] };
  873. }
  874. }
  875. function ensureArrayLimit(array, limit) {
  876. if (array.length > limit)
  877. return array.splice(0, limit / 10);
  878. return [];
  879. }
  880. // Annotate the CommonJS export names for ESM import in node:
  881. 0 && (module.exports = {
  882. InitScript,
  883. Page,
  884. PageBinding,
  885. Worker
  886. });