phantomwright-driver-core 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (363) hide show
  1. package/README.md +3 -0
  2. package/ThirdPartyNotices.txt +4076 -0
  3. package/bin/install_media_pack.ps1 +5 -0
  4. package/bin/install_webkit_wsl.ps1 +33 -0
  5. package/bin/reinstall_chrome_beta_linux.sh +42 -0
  6. package/bin/reinstall_chrome_beta_mac.sh +13 -0
  7. package/bin/reinstall_chrome_beta_win.ps1 +24 -0
  8. package/bin/reinstall_chrome_stable_linux.sh +42 -0
  9. package/bin/reinstall_chrome_stable_mac.sh +12 -0
  10. package/bin/reinstall_chrome_stable_win.ps1 +24 -0
  11. package/bin/reinstall_msedge_beta_linux.sh +48 -0
  12. package/bin/reinstall_msedge_beta_mac.sh +11 -0
  13. package/bin/reinstall_msedge_beta_win.ps1 +23 -0
  14. package/bin/reinstall_msedge_dev_linux.sh +48 -0
  15. package/bin/reinstall_msedge_dev_mac.sh +11 -0
  16. package/bin/reinstall_msedge_dev_win.ps1 +23 -0
  17. package/bin/reinstall_msedge_stable_linux.sh +48 -0
  18. package/bin/reinstall_msedge_stable_mac.sh +11 -0
  19. package/bin/reinstall_msedge_stable_win.ps1 +24 -0
  20. package/browsers.json +79 -0
  21. package/cli.js +18 -0
  22. package/index.d.ts +17 -0
  23. package/index.js +32 -0
  24. package/index.mjs +28 -0
  25. package/lib/androidServerImpl.js +65 -0
  26. package/lib/browserServerImpl.js +120 -0
  27. package/lib/cli/driver.js +97 -0
  28. package/lib/cli/program.js +589 -0
  29. package/lib/cli/programWithTestStub.js +74 -0
  30. package/lib/client/android.js +361 -0
  31. package/lib/client/api.js +137 -0
  32. package/lib/client/artifact.js +79 -0
  33. package/lib/client/browser.js +161 -0
  34. package/lib/client/browserContext.js +601 -0
  35. package/lib/client/browserType.js +185 -0
  36. package/lib/client/cdpSession.js +51 -0
  37. package/lib/client/channelOwner.js +194 -0
  38. package/lib/client/clientHelper.js +63 -0
  39. package/lib/client/clientInstrumentation.js +55 -0
  40. package/lib/client/clientStackTrace.js +69 -0
  41. package/lib/client/clock.js +69 -0
  42. package/lib/client/connection.js +318 -0
  43. package/lib/client/consoleMessage.js +58 -0
  44. package/lib/client/coverage.js +44 -0
  45. package/lib/client/dialog.js +56 -0
  46. package/lib/client/download.js +62 -0
  47. package/lib/client/electron.js +138 -0
  48. package/lib/client/elementHandle.js +284 -0
  49. package/lib/client/errors.js +77 -0
  50. package/lib/client/eventEmitter.js +314 -0
  51. package/lib/client/events.js +103 -0
  52. package/lib/client/fetch.js +368 -0
  53. package/lib/client/fileChooser.js +46 -0
  54. package/lib/client/fileUtils.js +34 -0
  55. package/lib/client/frame.js +409 -0
  56. package/lib/client/harRouter.js +87 -0
  57. package/lib/client/input.js +84 -0
  58. package/lib/client/jsHandle.js +109 -0
  59. package/lib/client/jsonPipe.js +39 -0
  60. package/lib/client/localUtils.js +60 -0
  61. package/lib/client/locator.js +390 -0
  62. package/lib/client/network.js +747 -0
  63. package/lib/client/page.js +764 -0
  64. package/lib/client/pageAgent.js +64 -0
  65. package/lib/client/platform.js +77 -0
  66. package/lib/client/playwright.js +71 -0
  67. package/lib/client/selectors.js +55 -0
  68. package/lib/client/stream.js +39 -0
  69. package/lib/client/timeoutSettings.js +79 -0
  70. package/lib/client/tracing.js +120 -0
  71. package/lib/client/types.js +28 -0
  72. package/lib/client/video.js +59 -0
  73. package/lib/client/waiter.js +142 -0
  74. package/lib/client/webError.js +39 -0
  75. package/lib/client/webSocket.js +93 -0
  76. package/lib/client/worker.js +85 -0
  77. package/lib/client/writableStream.js +39 -0
  78. package/lib/generated/bindingsControllerSource.js +28 -0
  79. package/lib/generated/clockSource.js +28 -0
  80. package/lib/generated/injectedScriptSource.js +28 -0
  81. package/lib/generated/pollingRecorderSource.js +28 -0
  82. package/lib/generated/storageScriptSource.js +28 -0
  83. package/lib/generated/utilityScriptSource.js +28 -0
  84. package/lib/generated/webSocketMockSource.js +336 -0
  85. package/lib/inProcessFactory.js +60 -0
  86. package/lib/inprocess.js +3 -0
  87. package/lib/mcpBundle.js +84 -0
  88. package/lib/mcpBundleImpl/index.js +147 -0
  89. package/lib/outofprocess.js +76 -0
  90. package/lib/protocol/serializers.js +197 -0
  91. package/lib/protocol/validator.js +2981 -0
  92. package/lib/protocol/validatorPrimitives.js +193 -0
  93. package/lib/remote/playwrightConnection.js +129 -0
  94. package/lib/remote/playwrightServer.js +334 -0
  95. package/lib/server/agent/actionRunner.js +335 -0
  96. package/lib/server/agent/actions.js +128 -0
  97. package/lib/server/agent/codegen.js +111 -0
  98. package/lib/server/agent/context.js +150 -0
  99. package/lib/server/agent/expectTools.js +156 -0
  100. package/lib/server/agent/pageAgent.js +204 -0
  101. package/lib/server/agent/performTools.js +262 -0
  102. package/lib/server/agent/tool.js +109 -0
  103. package/lib/server/android/android.js +465 -0
  104. package/lib/server/android/backendAdb.js +177 -0
  105. package/lib/server/artifact.js +127 -0
  106. package/lib/server/bidi/bidiBrowser.js +549 -0
  107. package/lib/server/bidi/bidiChromium.js +148 -0
  108. package/lib/server/bidi/bidiConnection.js +213 -0
  109. package/lib/server/bidi/bidiDeserializer.js +116 -0
  110. package/lib/server/bidi/bidiExecutionContext.js +267 -0
  111. package/lib/server/bidi/bidiFirefox.js +128 -0
  112. package/lib/server/bidi/bidiInput.js +146 -0
  113. package/lib/server/bidi/bidiNetworkManager.js +383 -0
  114. package/lib/server/bidi/bidiOverCdp.js +102 -0
  115. package/lib/server/bidi/bidiPage.js +583 -0
  116. package/lib/server/bidi/bidiPdf.js +106 -0
  117. package/lib/server/bidi/third_party/bidiCommands.d.js +22 -0
  118. package/lib/server/bidi/third_party/bidiKeyboard.js +256 -0
  119. package/lib/server/bidi/third_party/bidiProtocol.js +24 -0
  120. package/lib/server/bidi/third_party/bidiProtocolCore.js +180 -0
  121. package/lib/server/bidi/third_party/bidiProtocolPermissions.js +42 -0
  122. package/lib/server/bidi/third_party/bidiSerializer.js +148 -0
  123. package/lib/server/bidi/third_party/firefoxPrefs.js +259 -0
  124. package/lib/server/browser.js +149 -0
  125. package/lib/server/browserContext.js +689 -0
  126. package/lib/server/browserType.js +336 -0
  127. package/lib/server/callLog.js +82 -0
  128. package/lib/server/chromium/appIcon.png +0 -0
  129. package/lib/server/chromium/chromium.js +395 -0
  130. package/lib/server/chromium/chromiumSwitches.js +92 -0
  131. package/lib/server/chromium/crBrowser.js +516 -0
  132. package/lib/server/chromium/crConnection.js +197 -0
  133. package/lib/server/chromium/crCoverage.js +235 -0
  134. package/lib/server/chromium/crDevTools.js +110 -0
  135. package/lib/server/chromium/crDragDrop.js +131 -0
  136. package/lib/server/chromium/crExecutionContext.js +146 -0
  137. package/lib/server/chromium/crInput.js +187 -0
  138. package/lib/server/chromium/crNetworkManager.js +946 -0
  139. package/lib/server/chromium/crPage.js +1079 -0
  140. package/lib/server/chromium/crPdf.js +121 -0
  141. package/lib/server/chromium/crProtocolHelper.js +145 -0
  142. package/lib/server/chromium/crServiceWorker.js +144 -0
  143. package/lib/server/chromium/defaultFontFamilies.js +162 -0
  144. package/lib/server/chromium/protocol.d.js +16 -0
  145. package/lib/server/clock.js +157 -0
  146. package/lib/server/codegen/csharp.js +327 -0
  147. package/lib/server/codegen/java.js +274 -0
  148. package/lib/server/codegen/javascript.js +247 -0
  149. package/lib/server/codegen/jsonl.js +52 -0
  150. package/lib/server/codegen/language.js +132 -0
  151. package/lib/server/codegen/languages.js +68 -0
  152. package/lib/server/codegen/python.js +279 -0
  153. package/lib/server/codegen/types.js +16 -0
  154. package/lib/server/console.js +57 -0
  155. package/lib/server/cookieStore.js +206 -0
  156. package/lib/server/debugController.js +191 -0
  157. package/lib/server/debugger.js +119 -0
  158. package/lib/server/deviceDescriptors.js +39 -0
  159. package/lib/server/deviceDescriptorsSource.json +1779 -0
  160. package/lib/server/dialog.js +116 -0
  161. package/lib/server/dispatchers/androidDispatcher.js +325 -0
  162. package/lib/server/dispatchers/artifactDispatcher.js +118 -0
  163. package/lib/server/dispatchers/browserContextDispatcher.js +384 -0
  164. package/lib/server/dispatchers/browserDispatcher.js +118 -0
  165. package/lib/server/dispatchers/browserTypeDispatcher.js +64 -0
  166. package/lib/server/dispatchers/cdpSessionDispatcher.js +44 -0
  167. package/lib/server/dispatchers/debugControllerDispatcher.js +78 -0
  168. package/lib/server/dispatchers/dialogDispatcher.js +47 -0
  169. package/lib/server/dispatchers/dispatcher.js +364 -0
  170. package/lib/server/dispatchers/electronDispatcher.js +89 -0
  171. package/lib/server/dispatchers/elementHandlerDispatcher.js +181 -0
  172. package/lib/server/dispatchers/frameDispatcher.js +227 -0
  173. package/lib/server/dispatchers/jsHandleDispatcher.js +85 -0
  174. package/lib/server/dispatchers/jsonPipeDispatcher.js +58 -0
  175. package/lib/server/dispatchers/localUtilsDispatcher.js +149 -0
  176. package/lib/server/dispatchers/networkDispatchers.js +213 -0
  177. package/lib/server/dispatchers/pageAgentDispatcher.js +96 -0
  178. package/lib/server/dispatchers/pageDispatcher.js +393 -0
  179. package/lib/server/dispatchers/playwrightDispatcher.js +108 -0
  180. package/lib/server/dispatchers/streamDispatcher.js +67 -0
  181. package/lib/server/dispatchers/tracingDispatcher.js +68 -0
  182. package/lib/server/dispatchers/webSocketRouteDispatcher.js +165 -0
  183. package/lib/server/dispatchers/writableStreamDispatcher.js +79 -0
  184. package/lib/server/dom.js +815 -0
  185. package/lib/server/download.js +70 -0
  186. package/lib/server/electron/electron.js +273 -0
  187. package/lib/server/electron/loader.js +29 -0
  188. package/lib/server/errors.js +69 -0
  189. package/lib/server/fetch.js +621 -0
  190. package/lib/server/fileChooser.js +43 -0
  191. package/lib/server/fileUploadUtils.js +84 -0
  192. package/lib/server/firefox/ffBrowser.js +418 -0
  193. package/lib/server/firefox/ffConnection.js +142 -0
  194. package/lib/server/firefox/ffExecutionContext.js +150 -0
  195. package/lib/server/firefox/ffInput.js +159 -0
  196. package/lib/server/firefox/ffNetworkManager.js +256 -0
  197. package/lib/server/firefox/ffPage.js +497 -0
  198. package/lib/server/firefox/firefox.js +114 -0
  199. package/lib/server/firefox/protocol.d.js +16 -0
  200. package/lib/server/formData.js +147 -0
  201. package/lib/server/frameSelectors.js +322 -0
  202. package/lib/server/frames.js +1802 -0
  203. package/lib/server/har/harRecorder.js +147 -0
  204. package/lib/server/har/harTracer.js +607 -0
  205. package/lib/server/harBackend.js +157 -0
  206. package/lib/server/helper.js +96 -0
  207. package/lib/server/index.js +58 -0
  208. package/lib/server/input.js +277 -0
  209. package/lib/server/instrumentation.js +72 -0
  210. package/lib/server/javascript.js +307 -0
  211. package/lib/server/launchApp.js +128 -0
  212. package/lib/server/localUtils.js +214 -0
  213. package/lib/server/macEditingCommands.js +143 -0
  214. package/lib/server/network.js +667 -0
  215. package/lib/server/page.js +812 -0
  216. package/lib/server/pageBinding.js +87 -0
  217. package/lib/server/pipeTransport.js +89 -0
  218. package/lib/server/playwright.js +69 -0
  219. package/lib/server/progress.js +132 -0
  220. package/lib/server/protocolError.js +52 -0
  221. package/lib/server/recorder/chat.js +161 -0
  222. package/lib/server/recorder/recorderApp.js +366 -0
  223. package/lib/server/recorder/recorderRunner.js +138 -0
  224. package/lib/server/recorder/recorderSignalProcessor.js +83 -0
  225. package/lib/server/recorder/recorderUtils.js +157 -0
  226. package/lib/server/recorder/throttledFile.js +57 -0
  227. package/lib/server/recorder.js +499 -0
  228. package/lib/server/registry/browserFetcher.js +177 -0
  229. package/lib/server/registry/dependencies.js +371 -0
  230. package/lib/server/registry/index.js +1422 -0
  231. package/lib/server/registry/nativeDeps.js +1280 -0
  232. package/lib/server/registry/oopDownloadBrowserMain.js +127 -0
  233. package/lib/server/screencast.js +190 -0
  234. package/lib/server/screenshotter.js +333 -0
  235. package/lib/server/selectors.js +112 -0
  236. package/lib/server/socksClientCertificatesInterceptor.js +383 -0
  237. package/lib/server/socksInterceptor.js +95 -0
  238. package/lib/server/trace/recorder/snapshotter.js +147 -0
  239. package/lib/server/trace/recorder/snapshotterInjected.js +561 -0
  240. package/lib/server/trace/recorder/tracing.js +604 -0
  241. package/lib/server/trace/viewer/traceParser.js +72 -0
  242. package/lib/server/trace/viewer/traceViewer.js +245 -0
  243. package/lib/server/transport.js +181 -0
  244. package/lib/server/types.js +28 -0
  245. package/lib/server/usKeyboardLayout.js +145 -0
  246. package/lib/server/utils/ascii.js +44 -0
  247. package/lib/server/utils/comparators.js +139 -0
  248. package/lib/server/utils/crypto.js +216 -0
  249. package/lib/server/utils/debug.js +42 -0
  250. package/lib/server/utils/debugLogger.js +122 -0
  251. package/lib/server/utils/env.js +73 -0
  252. package/lib/server/utils/eventsHelper.js +39 -0
  253. package/lib/server/utils/expectUtils.js +123 -0
  254. package/lib/server/utils/fileUtils.js +191 -0
  255. package/lib/server/utils/happyEyeballs.js +207 -0
  256. package/lib/server/utils/hostPlatform.js +123 -0
  257. package/lib/server/utils/httpServer.js +203 -0
  258. package/lib/server/utils/imageUtils.js +141 -0
  259. package/lib/server/utils/image_tools/colorUtils.js +89 -0
  260. package/lib/server/utils/image_tools/compare.js +109 -0
  261. package/lib/server/utils/image_tools/imageChannel.js +78 -0
  262. package/lib/server/utils/image_tools/stats.js +102 -0
  263. package/lib/server/utils/linuxUtils.js +71 -0
  264. package/lib/server/utils/network.js +242 -0
  265. package/lib/server/utils/nodePlatform.js +154 -0
  266. package/lib/server/utils/pipeTransport.js +84 -0
  267. package/lib/server/utils/processLauncher.js +241 -0
  268. package/lib/server/utils/profiler.js +65 -0
  269. package/lib/server/utils/socksProxy.js +511 -0
  270. package/lib/server/utils/spawnAsync.js +41 -0
  271. package/lib/server/utils/task.js +51 -0
  272. package/lib/server/utils/userAgent.js +98 -0
  273. package/lib/server/utils/wsServer.js +121 -0
  274. package/lib/server/utils/zipFile.js +74 -0
  275. package/lib/server/utils/zones.js +57 -0
  276. package/lib/server/videoRecorder.js +124 -0
  277. package/lib/server/webkit/protocol.d.js +16 -0
  278. package/lib/server/webkit/webkit.js +108 -0
  279. package/lib/server/webkit/wkBrowser.js +335 -0
  280. package/lib/server/webkit/wkConnection.js +144 -0
  281. package/lib/server/webkit/wkExecutionContext.js +154 -0
  282. package/lib/server/webkit/wkInput.js +181 -0
  283. package/lib/server/webkit/wkInterceptableRequest.js +197 -0
  284. package/lib/server/webkit/wkPage.js +1158 -0
  285. package/lib/server/webkit/wkProvisionalPage.js +83 -0
  286. package/lib/server/webkit/wkWorkers.js +105 -0
  287. package/lib/third_party/pixelmatch.js +255 -0
  288. package/lib/utils/isomorphic/ariaSnapshot.js +455 -0
  289. package/lib/utils/isomorphic/assert.js +31 -0
  290. package/lib/utils/isomorphic/colors.js +72 -0
  291. package/lib/utils/isomorphic/cssParser.js +245 -0
  292. package/lib/utils/isomorphic/cssTokenizer.js +1051 -0
  293. package/lib/utils/isomorphic/headers.js +53 -0
  294. package/lib/utils/isomorphic/locatorGenerators.js +689 -0
  295. package/lib/utils/isomorphic/locatorParser.js +176 -0
  296. package/lib/utils/isomorphic/locatorUtils.js +81 -0
  297. package/lib/utils/isomorphic/lruCache.js +51 -0
  298. package/lib/utils/isomorphic/manualPromise.js +114 -0
  299. package/lib/utils/isomorphic/mimeType.js +459 -0
  300. package/lib/utils/isomorphic/multimap.js +80 -0
  301. package/lib/utils/isomorphic/oldUtilityScriptSerializers.js +248 -0
  302. package/lib/utils/isomorphic/protocolFormatter.js +81 -0
  303. package/lib/utils/isomorphic/protocolMetainfo.js +330 -0
  304. package/lib/utils/isomorphic/rtti.js +43 -0
  305. package/lib/utils/isomorphic/selectorParser.js +386 -0
  306. package/lib/utils/isomorphic/semaphore.js +54 -0
  307. package/lib/utils/isomorphic/stackTrace.js +158 -0
  308. package/lib/utils/isomorphic/stringUtils.js +204 -0
  309. package/lib/utils/isomorphic/time.js +49 -0
  310. package/lib/utils/isomorphic/timeoutRunner.js +66 -0
  311. package/lib/utils/isomorphic/trace/entries.js +16 -0
  312. package/lib/utils/isomorphic/trace/snapshotRenderer.js +499 -0
  313. package/lib/utils/isomorphic/trace/snapshotServer.js +120 -0
  314. package/lib/utils/isomorphic/trace/snapshotStorage.js +89 -0
  315. package/lib/utils/isomorphic/trace/traceLoader.js +131 -0
  316. package/lib/utils/isomorphic/trace/traceModel.js +365 -0
  317. package/lib/utils/isomorphic/trace/traceModernizer.js +400 -0
  318. package/lib/utils/isomorphic/trace/versions/traceV3.js +16 -0
  319. package/lib/utils/isomorphic/trace/versions/traceV4.js +16 -0
  320. package/lib/utils/isomorphic/trace/versions/traceV5.js +16 -0
  321. package/lib/utils/isomorphic/trace/versions/traceV6.js +16 -0
  322. package/lib/utils/isomorphic/trace/versions/traceV7.js +16 -0
  323. package/lib/utils/isomorphic/trace/versions/traceV8.js +16 -0
  324. package/lib/utils/isomorphic/traceUtils.js +58 -0
  325. package/lib/utils/isomorphic/types.js +16 -0
  326. package/lib/utils/isomorphic/urlMatch.js +190 -0
  327. package/lib/utils/isomorphic/utilityScriptSerializers.js +251 -0
  328. package/lib/utils/isomorphic/yaml.js +84 -0
  329. package/lib/utils.js +111 -0
  330. package/lib/utilsBundle.js +109 -0
  331. package/lib/utilsBundleImpl/index.js +218 -0
  332. package/lib/utilsBundleImpl/xdg-open +1066 -0
  333. package/lib/vite/htmlReport/index.html +84 -0
  334. package/lib/vite/recorder/assets/codeMirrorModule-CFUTFUO7.js +32 -0
  335. package/lib/vite/recorder/assets/codeMirrorModule-DYBRYzYX.css +1 -0
  336. package/lib/vite/recorder/assets/codicon-DCmgc-ay.ttf +0 -0
  337. package/lib/vite/recorder/assets/index-BSjZa4pk.css +1 -0
  338. package/lib/vite/recorder/assets/index-CVkBxsGf.js +193 -0
  339. package/lib/vite/recorder/index.html +29 -0
  340. package/lib/vite/recorder/playwright-logo.svg +9 -0
  341. package/lib/vite/traceViewer/assets/codeMirrorModule-BVA4h_ZY.js +32 -0
  342. package/lib/vite/traceViewer/assets/defaultSettingsView-CjfmcdOz.js +266 -0
  343. package/lib/vite/traceViewer/assets/xtermModule-CsJ4vdCR.js +9 -0
  344. package/lib/vite/traceViewer/codeMirrorModule.DYBRYzYX.css +1 -0
  345. package/lib/vite/traceViewer/codicon.DCmgc-ay.ttf +0 -0
  346. package/lib/vite/traceViewer/defaultSettingsView.7ch9cixO.css +1 -0
  347. package/lib/vite/traceViewer/index.BVu7tZDe.css +1 -0
  348. package/lib/vite/traceViewer/index._nZoBaQx.js +2 -0
  349. package/lib/vite/traceViewer/index.html +43 -0
  350. package/lib/vite/traceViewer/manifest.webmanifest +16 -0
  351. package/lib/vite/traceViewer/playwright-logo.svg +9 -0
  352. package/lib/vite/traceViewer/snapshot.html +21 -0
  353. package/lib/vite/traceViewer/sw.bundle.js +5 -0
  354. package/lib/vite/traceViewer/uiMode.Btcz36p_.css +1 -0
  355. package/lib/vite/traceViewer/uiMode.fyrXARf2.js +5 -0
  356. package/lib/vite/traceViewer/uiMode.html +17 -0
  357. package/lib/vite/traceViewer/xtermModule.DYP7pi_n.css +32 -0
  358. package/lib/zipBundle.js +34 -0
  359. package/lib/zipBundleImpl.js +5 -0
  360. package/package.json +43 -0
  361. package/types/protocol.d.ts +23824 -0
  362. package/types/structs.d.ts +45 -0
  363. package/types/types.d.ts +22843 -0
@@ -0,0 +1,1802 @@
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 frames_exports = {};
30
+ __export(frames_exports, {
31
+ Frame: () => Frame,
32
+ FrameManager: () => FrameManager,
33
+ NavigationAbortedError: () => NavigationAbortedError
34
+ });
35
+ module.exports = __toCommonJS(frames_exports);
36
+ var import_crExecutionContext = require("./chromium/crExecutionContext");
37
+ var import_dom = require("./dom");
38
+ var import_browserContext = require("./browserContext");
39
+ var dom = __toESM(require("./dom"));
40
+ var import_errors = require("./errors");
41
+ var import_fileUploadUtils = require("./fileUploadUtils");
42
+ var import_frameSelectors = require("./frameSelectors");
43
+ var import_helper = require("./helper");
44
+ var import_instrumentation = require("./instrumentation");
45
+ var js = __toESM(require("./javascript"));
46
+ var network = __toESM(require("./network"));
47
+ var import_page = require("./page");
48
+ var import_progress = require("./progress");
49
+ var types = __toESM(require("./types"));
50
+ var import_utils = require("../utils");
51
+ var import_protocolError = require("./protocolError");
52
+ var import_debugLogger = require("./utils/debugLogger");
53
+ var import_eventsHelper = require("./utils/eventsHelper");
54
+ var import_selectorParser = require("../utils/isomorphic/selectorParser");
55
+ var import_manualPromise = require("../utils/isomorphic/manualPromise");
56
+ var import_callLog = require("./callLog");
57
+ class NavigationAbortedError extends Error {
58
+ constructor(documentId, message) {
59
+ super(message);
60
+ this.documentId = documentId;
61
+ }
62
+ }
63
+ const kDummyFrameId = "<dummy>";
64
+ class FrameManager {
65
+ constructor(page) {
66
+ this._frames = /* @__PURE__ */ new Map();
67
+ this._consoleMessageTags = /* @__PURE__ */ new Map();
68
+ this._signalBarriers = /* @__PURE__ */ new Set();
69
+ this._webSockets = /* @__PURE__ */ new Map();
70
+ this._nextFrameSeq = 0;
71
+ this._page = page;
72
+ this._mainFrame = void 0;
73
+ }
74
+ nextFrameSeq() {
75
+ return this._nextFrameSeq++;
76
+ }
77
+ createDummyMainFrameIfNeeded() {
78
+ if (!this._mainFrame)
79
+ this.frameAttached(kDummyFrameId, null);
80
+ }
81
+ dispose() {
82
+ for (const frame of this._frames.values()) {
83
+ frame._stopNetworkIdleTimer();
84
+ frame._invalidateNonStallingEvaluations("Target crashed");
85
+ }
86
+ }
87
+ mainFrame() {
88
+ return this._mainFrame;
89
+ }
90
+ frames() {
91
+ const frames = [];
92
+ collect(this._mainFrame);
93
+ return frames;
94
+ function collect(frame) {
95
+ frames.push(frame);
96
+ for (const subframe of frame.childFrames())
97
+ collect(subframe);
98
+ }
99
+ }
100
+ frame(frameId) {
101
+ return this._frames.get(frameId) || null;
102
+ }
103
+ frameAttached(frameId, parentFrameId) {
104
+ const parentFrame = parentFrameId ? this._frames.get(parentFrameId) : null;
105
+ if (!parentFrame) {
106
+ if (this._mainFrame) {
107
+ this._frames.delete(this._mainFrame._id);
108
+ this._mainFrame._id = frameId;
109
+ } else {
110
+ (0, import_utils.assert)(!this._frames.has(frameId));
111
+ this._mainFrame = new Frame(this._page, frameId, parentFrame);
112
+ }
113
+ this._frames.set(frameId, this._mainFrame);
114
+ return this._mainFrame;
115
+ } else {
116
+ (0, import_utils.assert)(!this._frames.has(frameId));
117
+ const frame = new Frame(this._page, frameId, parentFrame);
118
+ this._frames.set(frameId, frame);
119
+ this._page.emit(import_page.Page.Events.FrameAttached, frame);
120
+ return frame;
121
+ }
122
+ }
123
+ async waitForSignalsCreatedBy(progress, waitAfter, action) {
124
+ if (!waitAfter)
125
+ return action();
126
+ const barrier = new SignalBarrier(progress);
127
+ this._signalBarriers.add(barrier);
128
+ try {
129
+ const result = await action();
130
+ await progress.race(this._page.delegate.inputActionEpilogue());
131
+ await barrier.waitFor();
132
+ await new Promise((0, import_utils.makeWaitForNextTask)());
133
+ return result;
134
+ } finally {
135
+ this._signalBarriers.delete(barrier);
136
+ }
137
+ }
138
+ frameWillPotentiallyRequestNavigation() {
139
+ for (const barrier of this._signalBarriers)
140
+ barrier.retain();
141
+ }
142
+ frameDidPotentiallyRequestNavigation() {
143
+ for (const barrier of this._signalBarriers)
144
+ barrier.release();
145
+ }
146
+ frameRequestedNavigation(frameId, documentId) {
147
+ const frame = this._frames.get(frameId);
148
+ if (!frame)
149
+ return;
150
+ for (const barrier of this._signalBarriers)
151
+ barrier.addFrameNavigation(frame);
152
+ if (frame.pendingDocument() && frame.pendingDocument().documentId === documentId) {
153
+ return;
154
+ }
155
+ const request = documentId ? Array.from(frame._inflightRequests).find((request2) => request2._documentId === documentId) : void 0;
156
+ frame.setPendingDocument({ documentId, request });
157
+ }
158
+ frameCommittedNewDocumentNavigation(frameId, url, name, documentId, initial) {
159
+ const frame = this._frames.get(frameId);
160
+ this.removeChildFramesRecursively(frame);
161
+ this.clearWebSockets(frame);
162
+ frame._url = url;
163
+ frame._name = name;
164
+ let keepPending;
165
+ const pendingDocument = frame.pendingDocument();
166
+ if (pendingDocument) {
167
+ if (pendingDocument.documentId === void 0) {
168
+ pendingDocument.documentId = documentId;
169
+ }
170
+ if (pendingDocument.documentId === documentId) {
171
+ frame._currentDocument = pendingDocument;
172
+ } else {
173
+ keepPending = pendingDocument;
174
+ frame._currentDocument = { documentId, request: void 0 };
175
+ }
176
+ frame.setPendingDocument(void 0);
177
+ } else {
178
+ frame._currentDocument = { documentId, request: void 0 };
179
+ }
180
+ frame._iframeWorld = void 0;
181
+ frame._mainWorld = void 0;
182
+ frame._isolatedWorld = void 0;
183
+ frame._onClearLifecycle();
184
+ const navigationEvent = { url, name, newDocument: frame._currentDocument, isPublic: true };
185
+ this._fireInternalFrameNavigation(frame, navigationEvent);
186
+ if (!initial) {
187
+ import_debugLogger.debugLogger.log("api", ` navigated to "${url}"`);
188
+ this._page.frameNavigatedToNewDocument(frame);
189
+ }
190
+ frame.setPendingDocument(keepPending);
191
+ }
192
+ frameCommittedSameDocumentNavigation(frameId, url) {
193
+ const frame = this._frames.get(frameId);
194
+ if (!frame)
195
+ return;
196
+ const pending = frame.pendingDocument();
197
+ if (pending && pending.documentId === void 0 && pending.request === void 0) {
198
+ frame.setPendingDocument(void 0);
199
+ }
200
+ frame._url = url;
201
+ const navigationEvent = { url, name: frame._name, isPublic: true };
202
+ this._fireInternalFrameNavigation(frame, navigationEvent);
203
+ import_debugLogger.debugLogger.log("api", ` navigated to "${url}"`);
204
+ }
205
+ frameAbortedNavigation(frameId, errorText, documentId) {
206
+ const frame = this._frames.get(frameId);
207
+ if (!frame || !frame.pendingDocument())
208
+ return;
209
+ if (documentId !== void 0 && frame.pendingDocument().documentId !== documentId)
210
+ return;
211
+ const navigationEvent = {
212
+ url: frame._url,
213
+ name: frame._name,
214
+ newDocument: frame.pendingDocument(),
215
+ error: new NavigationAbortedError(documentId, errorText),
216
+ isPublic: !(documentId && frame._redirectedNavigations.has(documentId))
217
+ };
218
+ frame.setPendingDocument(void 0);
219
+ this._fireInternalFrameNavigation(frame, navigationEvent);
220
+ }
221
+ frameDetached(frameId) {
222
+ const frame = this._frames.get(frameId);
223
+ if (frame) {
224
+ this._removeFramesRecursively(frame);
225
+ this._page.mainFrame()._recalculateNetworkIdle();
226
+ }
227
+ }
228
+ frameLifecycleEvent(frameId, event) {
229
+ const frame = this._frames.get(frameId);
230
+ if (frame)
231
+ frame._onLifecycleEvent(event);
232
+ }
233
+ requestStarted(request, route) {
234
+ const frame = request.frame();
235
+ this._inflightRequestStarted(request);
236
+ if (request._documentId)
237
+ frame.setPendingDocument({ documentId: request._documentId, request });
238
+ if (request._isFavicon) {
239
+ route?.abort("aborted").catch(() => {
240
+ });
241
+ return;
242
+ }
243
+ this._page.addNetworkRequest(request);
244
+ this._page.emitOnContext(import_browserContext.BrowserContext.Events.Request, request);
245
+ if (route)
246
+ new network.Route(request, route).handle([...this._page.requestInterceptors, ...this._page.browserContext.requestInterceptors]);
247
+ }
248
+ requestReceivedResponse(response) {
249
+ if (response.request()._isFavicon)
250
+ return;
251
+ this._page.emitOnContext(import_browserContext.BrowserContext.Events.Response, response);
252
+ }
253
+ reportRequestFinished(request, response) {
254
+ this._inflightRequestFinished(request);
255
+ if (request._isFavicon)
256
+ return;
257
+ this._page.emitOnContext(import_browserContext.BrowserContext.Events.RequestFinished, { request, response });
258
+ }
259
+ requestFailed(request, canceled) {
260
+ const frame = request.frame();
261
+ this._inflightRequestFinished(request);
262
+ if (frame.pendingDocument() && frame.pendingDocument().request === request) {
263
+ let errorText = request.failure().errorText;
264
+ if (canceled)
265
+ errorText += "; maybe frame was detached?";
266
+ this.frameAbortedNavigation(frame._id, errorText, frame.pendingDocument().documentId);
267
+ }
268
+ if (request._isFavicon)
269
+ return;
270
+ this._page.emitOnContext(import_browserContext.BrowserContext.Events.RequestFailed, request);
271
+ }
272
+ removeChildFramesRecursively(frame) {
273
+ for (const child of frame.childFrames())
274
+ this._removeFramesRecursively(child);
275
+ }
276
+ _removeFramesRecursively(frame) {
277
+ this.removeChildFramesRecursively(frame);
278
+ frame._onDetached();
279
+ this._frames.delete(frame._id);
280
+ if (!this._page.isClosed())
281
+ this._page.emit(import_page.Page.Events.FrameDetached, frame);
282
+ }
283
+ _inflightRequestFinished(request) {
284
+ const frame = request.frame();
285
+ if (request._isFavicon)
286
+ return;
287
+ if (!frame._inflightRequests.has(request))
288
+ return;
289
+ frame._inflightRequests.delete(request);
290
+ if (frame._inflightRequests.size === 0)
291
+ frame._startNetworkIdleTimer();
292
+ }
293
+ _inflightRequestStarted(request) {
294
+ const frame = request.frame();
295
+ if (request._isFavicon)
296
+ return;
297
+ frame._inflightRequests.add(request);
298
+ if (frame._inflightRequests.size === 1)
299
+ frame._stopNetworkIdleTimer();
300
+ }
301
+ interceptConsoleMessage(message) {
302
+ if (message.type() !== "debug")
303
+ return false;
304
+ const tag = message.text();
305
+ const handler = this._consoleMessageTags.get(tag);
306
+ if (!handler)
307
+ return false;
308
+ this._consoleMessageTags.delete(tag);
309
+ handler();
310
+ return true;
311
+ }
312
+ clearWebSockets(frame) {
313
+ if (frame.parentFrame())
314
+ return;
315
+ this._webSockets.clear();
316
+ }
317
+ onWebSocketCreated(requestId, url) {
318
+ const ws = new network.WebSocket(this._page, url);
319
+ this._webSockets.set(requestId, ws);
320
+ }
321
+ onWebSocketRequest(requestId) {
322
+ const ws = this._webSockets.get(requestId);
323
+ if (ws && ws.markAsNotified())
324
+ this._page.emit(import_page.Page.Events.WebSocket, ws);
325
+ }
326
+ onWebSocketResponse(requestId, status, statusText) {
327
+ const ws = this._webSockets.get(requestId);
328
+ if (status < 400)
329
+ return;
330
+ if (ws)
331
+ ws.error(`${statusText}: ${status}`);
332
+ }
333
+ onWebSocketFrameSent(requestId, opcode, data) {
334
+ const ws = this._webSockets.get(requestId);
335
+ if (ws)
336
+ ws.frameSent(opcode, data);
337
+ }
338
+ webSocketFrameReceived(requestId, opcode, data) {
339
+ const ws = this._webSockets.get(requestId);
340
+ if (ws)
341
+ ws.frameReceived(opcode, data);
342
+ }
343
+ webSocketClosed(requestId) {
344
+ const ws = this._webSockets.get(requestId);
345
+ if (ws)
346
+ ws.closed();
347
+ this._webSockets.delete(requestId);
348
+ }
349
+ webSocketError(requestId, errorMessage) {
350
+ const ws = this._webSockets.get(requestId);
351
+ if (ws)
352
+ ws.error(errorMessage);
353
+ }
354
+ _fireInternalFrameNavigation(frame, event) {
355
+ frame.emit(Frame.Events.InternalNavigation, event);
356
+ }
357
+ }
358
+ const FrameEvent = {
359
+ InternalNavigation: "internalnavigation",
360
+ AddLifecycle: "addlifecycle",
361
+ RemoveLifecycle: "removelifecycle"
362
+ };
363
+ class Frame extends import_instrumentation.SdkObject {
364
+ constructor(page, id, parentFrame) {
365
+ super(page, "frame");
366
+ this._firedLifecycleEvents = /* @__PURE__ */ new Set();
367
+ this._firedNetworkIdleSelf = false;
368
+ this._url = "";
369
+ this._contextData = /* @__PURE__ */ new Map();
370
+ this._childFrames = /* @__PURE__ */ new Set();
371
+ this._name = "";
372
+ this._inflightRequests = /* @__PURE__ */ new Set();
373
+ this._setContentCounter = 0;
374
+ this._detachedScope = new import_utils.LongStandingScope();
375
+ this._raceAgainstEvaluationStallingEventsPromises = /* @__PURE__ */ new Set();
376
+ this._redirectedNavigations = /* @__PURE__ */ new Map();
377
+ this.attribution.frame = this;
378
+ this.seq = page.frameManager.nextFrameSeq();
379
+ this._id = id;
380
+ this._page = page;
381
+ this._parentFrame = parentFrame;
382
+ this._currentDocument = { documentId: void 0, request: void 0 };
383
+ this.selectors = new import_frameSelectors.FrameSelectors(this);
384
+ this._contextData.set("main", { contextPromise: new import_manualPromise.ManualPromise(), context: null });
385
+ this._contextData.set("utility", { contextPromise: new import_manualPromise.ManualPromise(), context: null });
386
+ this._setContext("main", null);
387
+ this._setContext("utility", null);
388
+ if (this._parentFrame)
389
+ this._parentFrame._childFrames.add(this);
390
+ this._firedLifecycleEvents.add("commit");
391
+ if (id !== kDummyFrameId)
392
+ this._startNetworkIdleTimer();
393
+ }
394
+ static {
395
+ this.Events = FrameEvent;
396
+ }
397
+ isDetached() {
398
+ return this._detachedScope.isClosed();
399
+ }
400
+ _onLifecycleEvent(event) {
401
+ if (this._firedLifecycleEvents.has(event))
402
+ return;
403
+ this._firedLifecycleEvents.add(event);
404
+ this.emit(Frame.Events.AddLifecycle, event);
405
+ if (this === this._page.mainFrame() && this._url !== "about:blank")
406
+ import_debugLogger.debugLogger.log("api", ` "${event}" event fired`);
407
+ this._page.mainFrame()._recalculateNetworkIdle();
408
+ }
409
+ _onClearLifecycle() {
410
+ for (const event of this._firedLifecycleEvents)
411
+ this.emit(Frame.Events.RemoveLifecycle, event);
412
+ this._firedLifecycleEvents.clear();
413
+ this._inflightRequests = new Set(Array.from(this._inflightRequests).filter((request) => request === this._currentDocument.request));
414
+ this._stopNetworkIdleTimer();
415
+ if (this._inflightRequests.size === 0)
416
+ this._startNetworkIdleTimer();
417
+ this._page.mainFrame()._recalculateNetworkIdle(this);
418
+ this._onLifecycleEvent("commit");
419
+ }
420
+ setPendingDocument(documentInfo) {
421
+ this._pendingDocument = documentInfo;
422
+ if (documentInfo)
423
+ this._invalidateNonStallingEvaluations("Navigation interrupted the evaluation");
424
+ }
425
+ pendingDocument() {
426
+ return this._pendingDocument;
427
+ }
428
+ _invalidateNonStallingEvaluations(message) {
429
+ if (!this._raceAgainstEvaluationStallingEventsPromises.size)
430
+ return;
431
+ const error = new Error(message);
432
+ for (const promise of this._raceAgainstEvaluationStallingEventsPromises)
433
+ promise.reject(error);
434
+ }
435
+ async raceAgainstEvaluationStallingEvents(cb) {
436
+ if (this._pendingDocument)
437
+ throw new Error("Frame is currently attempting a navigation");
438
+ if (this._page.browserContext.dialogManager.hasOpenDialogsForPage(this._page))
439
+ throw new Error("Open JavaScript dialog prevents evaluation");
440
+ const promise = new import_manualPromise.ManualPromise();
441
+ this._raceAgainstEvaluationStallingEventsPromises.add(promise);
442
+ try {
443
+ return await Promise.race([
444
+ cb(),
445
+ promise
446
+ ]);
447
+ } finally {
448
+ this._raceAgainstEvaluationStallingEventsPromises.delete(promise);
449
+ }
450
+ }
451
+ nonStallingRawEvaluateInExistingMainContext(expression) {
452
+ return this.raceAgainstEvaluationStallingEvents(() => {
453
+ const context = this._existingMainContext();
454
+ if (!context)
455
+ throw new Error("Frame does not yet have a main execution context");
456
+ return context.rawEvaluateJSON(expression);
457
+ });
458
+ }
459
+ nonStallingEvaluateInExistingContext(expression, world) {
460
+ return this.raceAgainstEvaluationStallingEvents(() => {
461
+ const context = this._contextData.get(world)?.context;
462
+ if (!context)
463
+ throw new Error("Frame does not yet have the execution context");
464
+ return context.evaluateExpression(expression, { isFunction: false });
465
+ });
466
+ }
467
+ _recalculateNetworkIdle(frameThatAllowsRemovingNetworkIdle) {
468
+ let isNetworkIdle = this._firedNetworkIdleSelf;
469
+ for (const child of this._childFrames) {
470
+ child._recalculateNetworkIdle(frameThatAllowsRemovingNetworkIdle);
471
+ if (!child._firedLifecycleEvents.has("networkidle"))
472
+ isNetworkIdle = false;
473
+ }
474
+ if (isNetworkIdle && !this._firedLifecycleEvents.has("networkidle")) {
475
+ this._firedLifecycleEvents.add("networkidle");
476
+ this.emit(Frame.Events.AddLifecycle, "networkidle");
477
+ if (this === this._page.mainFrame() && this._url !== "about:blank")
478
+ import_debugLogger.debugLogger.log("api", ` "networkidle" event fired`);
479
+ }
480
+ if (frameThatAllowsRemovingNetworkIdle !== this && this._firedLifecycleEvents.has("networkidle") && !isNetworkIdle) {
481
+ this._firedLifecycleEvents.delete("networkidle");
482
+ this.emit(Frame.Events.RemoveLifecycle, "networkidle");
483
+ }
484
+ }
485
+ async raceNavigationAction(progress, action) {
486
+ return import_utils.LongStandingScope.raceMultiple([
487
+ this._detachedScope,
488
+ this._page.openScope
489
+ ], action().catch((e) => {
490
+ if (e instanceof NavigationAbortedError && e.documentId) {
491
+ const data = this._redirectedNavigations.get(e.documentId);
492
+ if (data) {
493
+ progress.log(`waiting for redirected navigation to "${data.url}"`);
494
+ return progress.race(data.gotoPromise);
495
+ }
496
+ }
497
+ throw e;
498
+ }));
499
+ }
500
+ redirectNavigation(url, documentId, referer) {
501
+ const controller = new import_progress.ProgressController();
502
+ const data = {
503
+ url,
504
+ gotoPromise: controller.run((progress) => this.gotoImpl(progress, url, { referer }), 0)
505
+ };
506
+ this._redirectedNavigations.set(documentId, data);
507
+ data.gotoPromise.finally(() => this._redirectedNavigations.delete(documentId));
508
+ }
509
+ async goto(progress, url, options = {}) {
510
+ const constructedNavigationURL = (0, import_utils.constructURLBasedOnBaseURL)(this._page.browserContext._options.baseURL, url);
511
+ return this.raceNavigationAction(progress, async () => this.gotoImpl(progress, constructedNavigationURL, options));
512
+ }
513
+ async gotoImpl(progress, url, options) {
514
+ const waitUntil = verifyLifecycle("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
515
+ progress.log(`navigating to "${url}", waiting until "${waitUntil}"`);
516
+ const headers = this._page.extraHTTPHeaders() || [];
517
+ const refererHeader = headers.find((h) => h.name.toLowerCase() === "referer");
518
+ let referer = refererHeader ? refererHeader.value : void 0;
519
+ if (options.referer !== void 0) {
520
+ if (referer !== void 0 && referer !== options.referer)
521
+ throw new Error('"referer" is already specified as extra HTTP header');
522
+ referer = options.referer;
523
+ }
524
+ url = import_helper.helper.completeUserURL(url);
525
+ const navigationEvents = [];
526
+ const collectNavigations = (arg) => navigationEvents.push(arg);
527
+ this.on(Frame.Events.InternalNavigation, collectNavigations);
528
+ const navigateResult = await progress.race(this._page.delegate.navigateFrame(this, url, referer)).finally(
529
+ () => this.off(Frame.Events.InternalNavigation, collectNavigations)
530
+ );
531
+ let event;
532
+ if (navigateResult.newDocumentId) {
533
+ const predicate = (event2) => {
534
+ return event2.newDocument && (event2.newDocument.documentId === navigateResult.newDocumentId || !event2.error);
535
+ };
536
+ const events = navigationEvents.filter(predicate);
537
+ if (events.length)
538
+ event = events[0];
539
+ else
540
+ event = await import_helper.helper.waitForEvent(progress, this, Frame.Events.InternalNavigation, predicate).promise;
541
+ if (event.newDocument.documentId !== navigateResult.newDocumentId) {
542
+ throw new NavigationAbortedError(navigateResult.newDocumentId, `Navigation to "${url}" is interrupted by another navigation to "${event.url}"`);
543
+ }
544
+ if (event.error)
545
+ throw event.error;
546
+ } else {
547
+ const predicate = (e) => !e.newDocument;
548
+ const events = navigationEvents.filter(predicate);
549
+ if (events.length)
550
+ event = events[0];
551
+ else
552
+ event = await import_helper.helper.waitForEvent(progress, this, Frame.Events.InternalNavigation, predicate).promise;
553
+ }
554
+ if (!this._firedLifecycleEvents.has(waitUntil))
555
+ await import_helper.helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e) => e === waitUntil).promise;
556
+ const request = event.newDocument ? event.newDocument.request : void 0;
557
+ const response = request ? progress.race(request._finalRequest().response()) : null;
558
+ return response;
559
+ }
560
+ async _waitForNavigation(progress, requiresNewDocument, options) {
561
+ const waitUntil = verifyLifecycle("waitUntil", options.waitUntil === void 0 ? "load" : options.waitUntil);
562
+ progress.log(`waiting for navigation until "${waitUntil}"`);
563
+ const navigationEvent = await import_helper.helper.waitForEvent(progress, this, Frame.Events.InternalNavigation, (event) => {
564
+ if (event.error)
565
+ return true;
566
+ if (requiresNewDocument && !event.newDocument)
567
+ return false;
568
+ progress.log(` navigated to "${this._url}"`);
569
+ return true;
570
+ }).promise;
571
+ if (navigationEvent.error)
572
+ throw navigationEvent.error;
573
+ if (!this._firedLifecycleEvents.has(waitUntil))
574
+ await import_helper.helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e) => e === waitUntil).promise;
575
+ const request = navigationEvent.newDocument ? navigationEvent.newDocument.request : void 0;
576
+ return request ? progress.race(request._finalRequest().response()) : null;
577
+ }
578
+ async waitForLoadState(progress, state) {
579
+ const waitUntil = verifyLifecycle("state", state);
580
+ if (!this._firedLifecycleEvents.has(waitUntil))
581
+ await import_helper.helper.waitForEvent(progress, this, Frame.Events.AddLifecycle, (e) => e === waitUntil).promise;
582
+ }
583
+ async frameElement() {
584
+ return this._page.delegate.getFrameElement(this);
585
+ }
586
+ async _context(world) {
587
+ if (this.isDetached()) throw new Error("Frame was detached");
588
+ try {
589
+ var client = this._page.delegate._sessionForFrame(this)._client;
590
+ } catch (e) {
591
+ var client = this._page.delegate._mainFrameSession._client;
592
+ }
593
+ var iframeExecutionContextId = await this._getFrameMainFrameContextId(client);
594
+ if (world == "main") {
595
+ if (this != this._page.mainFrame() && iframeExecutionContextId && this._iframeWorld == void 0) {
596
+ var executionContextId = iframeExecutionContextId;
597
+ var crContext = new import_crExecutionContext.CRExecutionContext(client, { id: executionContextId }, this._id);
598
+ this._iframeWorld = new import_dom.FrameExecutionContext(crContext, this, world);
599
+ this._page.delegate._mainFrameSession._onExecutionContextCreated({
600
+ id: executionContextId,
601
+ origin: world,
602
+ name: world,
603
+ auxData: { isDefault: this === this._page.mainFrame(), type: "isolated", frameId: this._id }
604
+ });
605
+ } else if (this._mainWorld == void 0) {
606
+ var globalThis2 = await client._sendMayFail("Runtime.evaluate", {
607
+ expression: "globalThis",
608
+ serializationOptions: { serialization: "idOnly" }
609
+ });
610
+ if (!globalThis2) {
611
+ return;
612
+ }
613
+ var globalThisObjId = globalThis2["result"]["objectId"];
614
+ var executionContextId = parseInt(globalThisObjId.split(".")[1], 10);
615
+ var crContext = new import_crExecutionContext.CRExecutionContext(client, { id: executionContextId }, this._id);
616
+ this._mainWorld = new import_dom.FrameExecutionContext(crContext, this, world);
617
+ this._page.delegate._mainFrameSession._onExecutionContextCreated({
618
+ id: executionContextId,
619
+ origin: world,
620
+ name: world,
621
+ auxData: { isDefault: this === this._page.mainFrame(), type: "isolated", frameId: this._id }
622
+ });
623
+ }
624
+ }
625
+ if (world != "main" && this._isolatedWorld == void 0) {
626
+ world = "utility";
627
+ var result = await client._sendMayFail("Page.createIsolatedWorld", {
628
+ frameId: this._id,
629
+ grantUniveralAccess: true,
630
+ worldName: world
631
+ });
632
+ if (!result) {
633
+ return;
634
+ }
635
+ var executionContextId = result.executionContextId;
636
+ var crContext = new import_crExecutionContext.CRExecutionContext(client, { id: executionContextId }, this._id);
637
+ this._isolatedWorld = new import_dom.FrameExecutionContext(crContext, this, world);
638
+ this._page.delegate._mainFrameSession._onExecutionContextCreated({
639
+ id: executionContextId,
640
+ origin: world,
641
+ name: world,
642
+ auxData: { isDefault: this === this._page.mainFrame(), type: "isolated", frameId: this._id }
643
+ });
644
+ }
645
+ if (world != "main") {
646
+ return this._isolatedWorld;
647
+ } else if (this != this._page.mainFrame() && iframeExecutionContextId) {
648
+ return this._iframeWorld;
649
+ } else {
650
+ return this._mainWorld;
651
+ }
652
+ }
653
+ _mainContext() {
654
+ return this._context("main");
655
+ }
656
+ _existingMainContext() {
657
+ return this._contextData.get("main")?.context || null;
658
+ }
659
+ _utilityContext() {
660
+ return this._context("utility");
661
+ }
662
+ async evaluateExpression(expression, options = {}, arg) {
663
+ const context = await this._context(options.world ?? "main");
664
+ const value = await context.evaluateExpression(expression, options, arg);
665
+ return value;
666
+ }
667
+ async evaluateExpressionHandle(expression, options = {}, arg) {
668
+ const context = await this._context(options.world ?? "utility");
669
+ const value = await context.evaluateExpressionHandle(expression, options, arg);
670
+ return value;
671
+ }
672
+ async querySelector(selector, options) {
673
+ return this.querySelectorAll(selector, options).then((handles) => {
674
+ if (handles.length === 0)
675
+ return null;
676
+ if (handles.length > 1 && options?.strict)
677
+ throw new Error(`Strict mode: expected one element matching selector "${selector}", found ${handles.length}`);
678
+ return handles[0];
679
+ });
680
+ }
681
+ async waitForSelector(progress, selector, performActionPreChecksAndLog, options, scope) {
682
+ if (options.visibility)
683
+ throw new Error("options.visibility is not supported, did you mean options.state?");
684
+ if (options.waitFor && options.waitFor !== "visible")
685
+ throw new Error("options.waitFor is not supported, did you mean options.state?");
686
+ const { state = "visible" } = options;
687
+ if (!["attached", "detached", "visible", "hidden"].includes(state))
688
+ throw new Error(`state: expected one of (attached|detached|visible|hidden)`);
689
+ if (performActionPreChecksAndLog)
690
+ progress.log(`waiting for ${this._asLocator(selector)}${state === "attached" ? "" : " to be " + state}`);
691
+ const promise = this._retryWithProgressIfNotConnected(progress, selector, options.strict, true, async (handle) => {
692
+ const attached = !!handle;
693
+ var visible = false;
694
+ if (attached) {
695
+ if (handle.parentNode.constructor.name == "ElementHandle") {
696
+ visible = await handle.parentNode.evaluateInUtility(([injected, node, { handle: handle2 }]) => {
697
+ return handle2 ? injected.utils.isElementVisible(handle2) : false;
698
+ }, { handle });
699
+ } else {
700
+ visible = await handle.parentNode.evaluate((injected, { handle: handle2 }) => {
701
+ return handle2 ? injected.utils.isElementVisible(handle2) : false;
702
+ }, { handle });
703
+ }
704
+ }
705
+ const success = {
706
+ attached,
707
+ detached: !attached,
708
+ visible,
709
+ hidden: !visible
710
+ }[state];
711
+ if (!success) return "internal:continuepolling";
712
+ if (options.omitReturnValue) return null;
713
+ const element = state === "attached" || state === "visible" ? handle : null;
714
+ if (!element) return null;
715
+ if (options.__testHookBeforeAdoptNode) await options.__testHookBeforeAdoptNode();
716
+ try {
717
+ return element;
718
+ } catch (e) {
719
+ return "internal:continuepolling";
720
+ }
721
+ }, "returnOnNotResolved");
722
+ return scope ? scope._context._raceAgainstContextDestroyed(promise) : promise;
723
+ }
724
+ async dispatchEvent(progress, selector, type, eventInit = {}, options, scope) {
725
+ await this._callOnElementOnceMatches(progress, selector, (injectedScript, element, data) => {
726
+ injectedScript.dispatchEvent(element, data.type, data.eventInit);
727
+ }, { type, eventInit }, { mainWorld: true, ...options }, scope);
728
+ }
729
+ async evalOnSelector(selector, strict2, expression, isFunction, arg, scope) {
730
+ const handle = await this.selectors.query(selector, { strict: strict2 }, scope);
731
+ if (!handle)
732
+ throw new Error('Failed to find element matching selector "' + selector + '"');
733
+ const result = await handle.evaluateExpression(expression, { isFunction }, arg, true);
734
+ handle.dispose();
735
+ return result;
736
+ }
737
+ async evalOnSelectorAll(selector, expression, isFunction, arg, scope, isolatedContext) {
738
+ try {
739
+ isolatedContext = this.selectors._parseSelector(selector, { strict: false }).world !== "main" && isolatedContext;
740
+ const arrayHandle = await this.selectors.queryArrayInMainWorld(selector, scope, isolatedContext);
741
+ const result = await arrayHandle.evaluateExpression(expression, { isFunction }, arg, isolatedContext);
742
+ arrayHandle.dispose();
743
+ return result;
744
+ } catch (e) {
745
+ if ("JSHandles can be evaluated only in the context they were created!" === e.message) return await this.evalOnSelectorAll(selector, expression, isFunction, arg, scope, isolatedContext);
746
+ throw e;
747
+ }
748
+ }
749
+ async maskSelectors(selectors, color) {
750
+ const context = await this._utilityContext();
751
+ const injectedScript = await context.injectedScript();
752
+ await injectedScript.evaluate((injected, { parsed, color: color2 }) => {
753
+ injected.maskSelectors(parsed, color2);
754
+ }, { parsed: selectors, color });
755
+ }
756
+ async querySelectorAll(selector) {
757
+ const metadata = { internal: false, log: [], method: "querySelectorAll" };
758
+ const progress = {
759
+ log: (message) => metadata.log.push(message),
760
+ metadata,
761
+ race: (promise) => Promise.race(Array.isArray(promise) ? promise : [promise])
762
+ };
763
+ return await this._retryWithoutProgress(progress, selector, null, false, async (result) => {
764
+ if (!result || !result[0]) return [];
765
+ return result[1];
766
+ }, "returnAll", null);
767
+ }
768
+ async queryCount(selector, options) {
769
+ const metadata = { internal: false, log: [], method: "queryCount" };
770
+ const progress = {
771
+ log: (message) => metadata.log.push(message),
772
+ metadata,
773
+ race: (promise) => Promise.race(Array.isArray(promise) ? promise : [promise])
774
+ };
775
+ return await this._retryWithoutProgress(progress, selector, null, false, async (result) => {
776
+ if (!result) return 0;
777
+ const handle = result[0];
778
+ const handles = result[1];
779
+ return handle ? handles.length : 0;
780
+ }, "returnAll", null);
781
+ }
782
+ async content() {
783
+ try {
784
+ const context = await this._utilityContext();
785
+ return await context.evaluate(() => {
786
+ let retVal = "";
787
+ if (document.doctype)
788
+ retVal = new XMLSerializer().serializeToString(document.doctype);
789
+ if (document.documentElement)
790
+ retVal += document.documentElement.outerHTML;
791
+ return retVal;
792
+ });
793
+ } catch (e) {
794
+ if (this.isNonRetriableError(e))
795
+ throw e;
796
+ throw new Error(`Unable to retrieve content because the page is navigating and changing the content.`);
797
+ }
798
+ }
799
+ async setContent(progress, html, options) {
800
+ await this.raceNavigationAction(progress, async () => {
801
+ const waitUntil = options.waitUntil === void 0 ? "load" : options.waitUntil;
802
+ progress.log(`setting frame content, waiting until "${waitUntil}"`);
803
+ const lifecyclePromise = new Promise((resolve, reject) => {
804
+ this._onClearLifecycle();
805
+ this._waitForLoadState(progress, waitUntil).then(resolve).catch(reject);
806
+ });
807
+ const setContentPromise = this._page.delegate._mainFrameSession._client.send("Page.setDocumentContent", {
808
+ frameId: this._id,
809
+ html
810
+ });
811
+ await Promise.all([setContentPromise, lifecyclePromise]);
812
+ return null;
813
+ });
814
+ }
815
+ name() {
816
+ return this._name || "";
817
+ }
818
+ url() {
819
+ return this._url;
820
+ }
821
+ origin() {
822
+ if (!this._url.startsWith("http"))
823
+ return;
824
+ return network.parseURL(this._url)?.origin;
825
+ }
826
+ parentFrame() {
827
+ return this._parentFrame;
828
+ }
829
+ childFrames() {
830
+ return Array.from(this._childFrames);
831
+ }
832
+ async addScriptTag(params) {
833
+ const {
834
+ url = null,
835
+ content = null,
836
+ type = ""
837
+ } = params;
838
+ if (!url && !content)
839
+ throw new Error("Provide an object with a `url`, `path` or `content` property");
840
+ const context = await this._mainContext();
841
+ return this._raceWithCSPError(async () => {
842
+ if (url !== null)
843
+ return (await context.evaluateHandle(addScriptUrl, { url, type })).asElement();
844
+ const result = (await context.evaluateHandle(addScriptContent, { content, type })).asElement();
845
+ if (this._page.delegate.cspErrorsAsynchronousForInlineScripts)
846
+ await context.evaluate(() => true);
847
+ return result;
848
+ });
849
+ async function addScriptUrl(params2) {
850
+ const script = document.createElement("script");
851
+ script.src = params2.url;
852
+ if (params2.type)
853
+ script.type = params2.type;
854
+ const promise = new Promise((res, rej) => {
855
+ script.onload = res;
856
+ script.onerror = (e) => rej(typeof e === "string" ? new Error(e) : new Error(`Failed to load script at ${script.src}`));
857
+ });
858
+ document.head.appendChild(script);
859
+ await promise;
860
+ return script;
861
+ }
862
+ function addScriptContent(params2) {
863
+ const script = document.createElement("script");
864
+ script.type = params2.type || "text/javascript";
865
+ script.text = params2.content;
866
+ let error = null;
867
+ script.onerror = (e) => error = e;
868
+ document.head.appendChild(script);
869
+ if (error)
870
+ throw error;
871
+ return script;
872
+ }
873
+ }
874
+ async addStyleTag(params) {
875
+ const {
876
+ url = null,
877
+ content = null
878
+ } = params;
879
+ if (!url && !content)
880
+ throw new Error("Provide an object with a `url`, `path` or `content` property");
881
+ const context = await this._mainContext();
882
+ return this._raceWithCSPError(async () => {
883
+ if (url !== null)
884
+ return (await context.evaluateHandle(addStyleUrl, url)).asElement();
885
+ return (await context.evaluateHandle(addStyleContent, content)).asElement();
886
+ });
887
+ async function addStyleUrl(url2) {
888
+ const link = document.createElement("link");
889
+ link.rel = "stylesheet";
890
+ link.href = url2;
891
+ const promise = new Promise((res, rej) => {
892
+ link.onload = res;
893
+ link.onerror = rej;
894
+ });
895
+ document.head.appendChild(link);
896
+ await promise;
897
+ return link;
898
+ }
899
+ async function addStyleContent(content2) {
900
+ const style = document.createElement("style");
901
+ style.type = "text/css";
902
+ style.appendChild(document.createTextNode(content2));
903
+ const promise = new Promise((res, rej) => {
904
+ style.onload = res;
905
+ style.onerror = rej;
906
+ });
907
+ document.head.appendChild(style);
908
+ await promise;
909
+ return style;
910
+ }
911
+ }
912
+ async _raceWithCSPError(func) {
913
+ const listeners = [];
914
+ let result;
915
+ let error;
916
+ let cspMessage;
917
+ const actionPromise = func().then((r) => result = r).catch((e) => error = e);
918
+ const errorPromise = new Promise((resolve) => {
919
+ listeners.push(import_eventsHelper.eventsHelper.addEventListener(this._page.browserContext, import_browserContext.BrowserContext.Events.Console, (message) => {
920
+ if (message.page() !== this._page || message.type() !== "error")
921
+ return;
922
+ if (message.text().includes("Content-Security-Policy") || message.text().includes("Content Security Policy")) {
923
+ cspMessage = message;
924
+ resolve();
925
+ }
926
+ }));
927
+ });
928
+ await Promise.race([actionPromise, errorPromise]);
929
+ import_eventsHelper.eventsHelper.removeEventListeners(listeners);
930
+ if (cspMessage)
931
+ throw new Error(cspMessage.text());
932
+ if (error)
933
+ throw error;
934
+ return result;
935
+ }
936
+ async retryWithProgressAndTimeouts(progress, timeouts, action) {
937
+ const continuePolling = Symbol("continuePolling");
938
+ timeouts = [0, ...timeouts];
939
+ let timeoutIndex = 0;
940
+ while (true) {
941
+ const timeout = timeouts[Math.min(timeoutIndex++, timeouts.length - 1)];
942
+ if (timeout) {
943
+ const actionPromise = new Promise((f) => setTimeout(f, timeout));
944
+ await progress.race(import_utils.LongStandingScope.raceMultiple([
945
+ this._page.openScope,
946
+ this._detachedScope
947
+ ], actionPromise));
948
+ }
949
+ try {
950
+ const result = await action(continuePolling);
951
+ if (result === continuePolling)
952
+ continue;
953
+ return result;
954
+ } catch (e) {
955
+ if (this.isNonRetriableError(e))
956
+ throw e;
957
+ continue;
958
+ }
959
+ }
960
+ }
961
+ isNonRetriableError(e) {
962
+ if ((0, import_progress.isAbortError)(e))
963
+ return true;
964
+ if (js.isJavaScriptErrorInEvaluate(e) || (0, import_protocolError.isSessionClosedError)(e))
965
+ return true;
966
+ if (dom.isNonRecoverableDOMError(e) || (0, import_selectorParser.isInvalidSelectorError)(e))
967
+ return true;
968
+ if (this.isDetached())
969
+ return true;
970
+ return false;
971
+ }
972
+ async _retryWithProgressIfNotConnected(progress, selector, options, action, returnAction) {
973
+ progress.log("waiting for " + this._asLocator(selector));
974
+ return this.retryWithProgressAndTimeouts(progress, [0, 20, 50, 100, 100, 500], async (continuePolling) => {
975
+ return this._retryWithoutProgress(progress, selector, strict, performActionPreChecks, action, returnAction, continuePolling);
976
+ });
977
+ }
978
+ async rafrafTimeoutScreenshotElementWithProgress(progress, selector, timeout, options) {
979
+ return await this._retryWithProgressIfNotConnected(progress, selector, { strict: true, performActionPreChecks: true }, async (handle) => {
980
+ await handle._frame.rafrafTimeout(progress, timeout);
981
+ return await this._page.screenshotter.screenshotElement(progress, handle, options);
982
+ });
983
+ }
984
+ async click(progress, selector, options) {
985
+ return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._click(progress, { ...options, waitAfter: !options.noWaitAfter })));
986
+ }
987
+ async dblclick(progress, selector, options) {
988
+ return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._dblclick(progress, options)));
989
+ }
990
+ async dragAndDrop(progress, source, target, options) {
991
+ dom.assertDone(await this._retryWithProgressIfNotConnected(progress, source, options, async (handle) => {
992
+ return handle._retryPointerAction(progress, "move and down", false, async (point) => {
993
+ await this._page.mouse.move(progress, point.x, point.y);
994
+ await this._page.mouse.down(progress);
995
+ }, {
996
+ ...options,
997
+ waitAfter: "disabled",
998
+ position: options.sourcePosition
999
+ });
1000
+ }));
1001
+ dom.assertDone(await this._retryWithProgressIfNotConnected(progress, target, { ...options, performActionPreChecks: false }, async (handle) => {
1002
+ return handle._retryPointerAction(progress, "move and up", false, async (point) => {
1003
+ await this._page.mouse.move(progress, point.x, point.y, { steps: options.steps });
1004
+ await this._page.mouse.up(progress);
1005
+ }, {
1006
+ ...options,
1007
+ waitAfter: "disabled",
1008
+ position: options.targetPosition
1009
+ });
1010
+ }));
1011
+ }
1012
+ async tap(progress, selector, options) {
1013
+ if (!this._page.browserContext._options.hasTouch)
1014
+ throw new Error("The page does not support tap. Use hasTouch context option to enable touch support.");
1015
+ return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._tap(progress, options)));
1016
+ }
1017
+ async fill(progress, selector, value, options) {
1018
+ return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._fill(progress, value, options)));
1019
+ }
1020
+ async focus(progress, selector, options) {
1021
+ dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._focus(progress)));
1022
+ }
1023
+ async blur(progress, selector, options) {
1024
+ dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._blur(progress)));
1025
+ }
1026
+ async resolveSelector(progress, selector, options = {}) {
1027
+ const element = await progress.race(this.selectors.query(selector, options));
1028
+ if (!element)
1029
+ throw new Error(`No element matching ${selector}`);
1030
+ const generated = await progress.race(element.evaluateInUtility(async ([injected, node]) => {
1031
+ return injected.generateSelectorSimple(node);
1032
+ }, {}));
1033
+ if (!generated)
1034
+ throw new Error(`Unable to generate locator for ${selector}`);
1035
+ let frame = element._frame;
1036
+ const result = [generated];
1037
+ while (frame?.parentFrame()) {
1038
+ const frameElement = await progress.race(frame.frameElement());
1039
+ if (frameElement) {
1040
+ const generated2 = await progress.race(frameElement.evaluateInUtility(async ([injected, node]) => {
1041
+ return injected.generateSelectorSimple(node);
1042
+ }, {}));
1043
+ frameElement.dispose();
1044
+ if (generated2 === "error:notconnected" || !generated2)
1045
+ throw new Error(`Unable to generate locator for ${selector}`);
1046
+ result.push(generated2);
1047
+ }
1048
+ frame = frame.parentFrame();
1049
+ }
1050
+ const resolvedSelector = result.reverse().join(" >> internal:control=enter-frame >> ");
1051
+ return { resolvedSelector };
1052
+ }
1053
+ async textContent(progress, selector, options, scope) {
1054
+ return this._callOnElementOnceMatches(progress, selector, (injected, element) => element.textContent, void 0, options, scope);
1055
+ }
1056
+ async innerText(progress, selector, options, scope) {
1057
+ return this._callOnElementOnceMatches(progress, selector, (injectedScript, element) => {
1058
+ if (element.namespaceURI !== "http://www.w3.org/1999/xhtml")
1059
+ throw injectedScript.createStacklessError("Node is not an HTMLElement");
1060
+ return element.innerText;
1061
+ }, void 0, options, scope);
1062
+ }
1063
+ async innerHTML(progress, selector, options, scope) {
1064
+ return this._callOnElementOnceMatches(progress, selector, (injected, element) => element.innerHTML, void 0, options, scope);
1065
+ }
1066
+ async getAttribute(progress, selector, name, options, scope) {
1067
+ return this._callOnElementOnceMatches(progress, selector, (injected, element, data) => element.getAttribute(data.name), { name }, options, scope);
1068
+ }
1069
+ async inputValue(progress, selector, options, scope) {
1070
+ return this._callOnElementOnceMatches(progress, selector, (injectedScript, node) => {
1071
+ const element = injectedScript.retarget(node, "follow-label");
1072
+ if (!element || element.nodeName !== "INPUT" && element.nodeName !== "TEXTAREA" && element.nodeName !== "SELECT")
1073
+ throw injectedScript.createStacklessError("Node is not an <input>, <textarea> or <select> element");
1074
+ return element.value;
1075
+ }, void 0, options, scope);
1076
+ }
1077
+ async highlight(progress, selector) {
1078
+ const resolved = await progress.race(this.selectors.resolveInjectedForSelector(selector));
1079
+ if (!resolved)
1080
+ return;
1081
+ return await progress.race(resolved.injected.evaluate((injected, { info }) => {
1082
+ return injected.highlight(info.parsed);
1083
+ }, { info: resolved.info }));
1084
+ }
1085
+ async hideHighlight() {
1086
+ return this.raceAgainstEvaluationStallingEvents(async () => {
1087
+ const context = await this._utilityContext();
1088
+ const injectedScript = await context.injectedScript();
1089
+ return await injectedScript.evaluate((injected) => {
1090
+ return injected.hideHighlight();
1091
+ });
1092
+ });
1093
+ }
1094
+ async _elementState(progress, selector, state, options, scope) {
1095
+ const result = await this._callOnElementOnceMatches(progress, selector, (injected, element, data) => {
1096
+ return injected.elementState(element, data.state);
1097
+ }, { state }, options, scope);
1098
+ if (result.received === "error:notconnected")
1099
+ dom.throwElementIsNotAttached();
1100
+ return result.matches;
1101
+ }
1102
+ async isVisible(progress, selector, options = {}, scope) {
1103
+ progress.log(` checking visibility of ${this._asLocator(selector)}`);
1104
+ return await this.isVisibleInternal(progress, selector, options, scope);
1105
+ }
1106
+ async isVisibleInternal(progress, selector, options = {}, scope) {
1107
+ try {
1108
+ const metadata = { internal: false, log: [], method: "isVisible" };
1109
+ const progress2 = {
1110
+ log: (message) => metadata.log.push(message),
1111
+ metadata,
1112
+ race: (promise) => Promise.race(Array.isArray(promise) ? promise : [promise])
1113
+ };
1114
+ progress2.log("waiting for " + this._asLocator(selector));
1115
+ if (selector === ":scope") {
1116
+ const scopeParentNode = scope.parentNode || scope;
1117
+ if (scopeParentNode.constructor.name == "ElementHandle") {
1118
+ return await scopeParentNode.evaluateInUtility(([injected, node, { scope: handle2 }]) => {
1119
+ const state = handle2 ? injected.elementState(handle2, "visible") : {
1120
+ matches: false,
1121
+ received: "error:notconnected"
1122
+ };
1123
+ return state.matches;
1124
+ }, { scope });
1125
+ } else {
1126
+ return await scopeParentNode.evaluate((injected, node, { scope: handle2 }) => {
1127
+ const state = handle2 ? injected.elementState(handle2, "visible") : {
1128
+ matches: false,
1129
+ received: "error:notconnected"
1130
+ };
1131
+ return state.matches;
1132
+ }, { scope });
1133
+ }
1134
+ } else {
1135
+ return await this._retryWithoutProgress(progress2, selector, options.strict, false, async (handle) => {
1136
+ if (!handle) return false;
1137
+ if (handle.parentNode.constructor.name == "ElementHandle") {
1138
+ return await handle.parentNode.evaluateInUtility(([injected, node, { handle: handle2 }]) => {
1139
+ const state = handle2 ? injected.elementState(handle2, "visible") : {
1140
+ matches: false,
1141
+ received: "error:notconnected"
1142
+ };
1143
+ return state.matches;
1144
+ }, { handle });
1145
+ } else {
1146
+ return await handle.parentNode.evaluate((injected, { handle: handle2 }) => {
1147
+ const state = handle2 ? injected.elementState(handle2, "visible") : {
1148
+ matches: false,
1149
+ received: "error:notconnected"
1150
+ };
1151
+ return state.matches;
1152
+ }, { handle });
1153
+ }
1154
+ }, "returnOnNotResolved", null);
1155
+ }
1156
+ } catch (e) {
1157
+ if (this.isNonRetriableError(e)) throw e;
1158
+ return false;
1159
+ }
1160
+ }
1161
+ async isHidden(progress, selector, options = {}, scope) {
1162
+ return !await this.isVisible(progress, selector, options, scope);
1163
+ }
1164
+ async isDisabled(progress, selector, options, scope) {
1165
+ return this._elementState(progress, selector, "disabled", options, scope);
1166
+ }
1167
+ async isEnabled(progress, selector, options, scope) {
1168
+ return this._elementState(progress, selector, "enabled", options, scope);
1169
+ }
1170
+ async isEditable(progress, selector, options, scope) {
1171
+ return this._elementState(progress, selector, "editable", options, scope);
1172
+ }
1173
+ async isChecked(progress, selector, options, scope) {
1174
+ return this._elementState(progress, selector, "checked", options, scope);
1175
+ }
1176
+ async hover(progress, selector, options) {
1177
+ return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._hover(progress, options)));
1178
+ }
1179
+ async selectOption(progress, selector, elements, values, options) {
1180
+ return await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._selectOption(progress, elements, values, options));
1181
+ }
1182
+ async setInputFiles(progress, selector, params) {
1183
+ const inputFileItems = await (0, import_fileUploadUtils.prepareFilesForUpload)(this, params);
1184
+ return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, params, (handle) => handle._setInputFiles(progress, inputFileItems)));
1185
+ }
1186
+ async type(progress, selector, text, options) {
1187
+ return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._type(progress, text, options)));
1188
+ }
1189
+ async press(progress, selector, key, options) {
1190
+ return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._press(progress, key, options)));
1191
+ }
1192
+ async check(progress, selector, options) {
1193
+ return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._setChecked(progress, true, options)));
1194
+ }
1195
+ async uncheck(progress, selector, options) {
1196
+ return dom.assertDone(await this._retryWithProgressIfNotConnected(progress, selector, options, (handle) => handle._setChecked(progress, false, options)));
1197
+ }
1198
+ async waitForTimeout(progress, timeout) {
1199
+ return progress.wait(timeout);
1200
+ }
1201
+ async ariaSnapshot(progress, selector) {
1202
+ return await this._retryWithProgressIfNotConnected(progress, selector, { strict: true, performActionPreChecks: true }, (handle) => progress.race(handle.ariaSnapshot()));
1203
+ }
1204
+ async expect(progress, selector, options) {
1205
+ progress.log(`${(0, import_utils.renderTitleForCall)(progress.metadata)}${options.timeoutForLogs ? ` with timeout ${options.timeoutForLogs}ms` : ""}`);
1206
+ const lastIntermediateResult = { isSet: false };
1207
+ const fixupMetadataError = (result) => {
1208
+ if (result.matches === options.isNot)
1209
+ progress.metadata.error = { error: { name: "Expect", message: "Expect failed" } };
1210
+ };
1211
+ try {
1212
+ if (selector)
1213
+ progress.log(`waiting for ${this._asLocator(selector)}`);
1214
+ if (!options.noAutoWaiting)
1215
+ await this._page.performActionPreChecks(progress);
1216
+ try {
1217
+ const resultOneShot = await this._expectInternal(progress, selector, options, lastIntermediateResult, true);
1218
+ if (options.noAutoWaiting || resultOneShot.matches !== options.isNot)
1219
+ return resultOneShot;
1220
+ } catch (e) {
1221
+ if (options.noAutoWaiting || this.isNonRetriableError(e))
1222
+ throw e;
1223
+ }
1224
+ const result = await this.retryWithProgressAndTimeouts(progress, [100, 250, 500, 1e3], async (continuePolling) => {
1225
+ if (!options.noAutoWaiting)
1226
+ await this._page.performActionPreChecks(progress);
1227
+ const { matches, received } = await this._expectInternal(progress, selector, options, lastIntermediateResult, false);
1228
+ if (matches === options.isNot) {
1229
+ return continuePolling;
1230
+ }
1231
+ return { matches, received };
1232
+ });
1233
+ fixupMetadataError(result);
1234
+ return result;
1235
+ } catch (e) {
1236
+ const result = { matches: options.isNot, log: (0, import_callLog.compressCallLog)(progress.metadata.log) };
1237
+ if ((0, import_selectorParser.isInvalidSelectorError)(e)) {
1238
+ result.errorMessage = "Error: " + e.message;
1239
+ } else if (js.isJavaScriptErrorInEvaluate(e)) {
1240
+ result.errorMessage = e.message;
1241
+ } else if (lastIntermediateResult.isSet) {
1242
+ result.received = lastIntermediateResult.received;
1243
+ result.errorMessage = lastIntermediateResult.errorMessage;
1244
+ }
1245
+ if (e instanceof import_errors.TimeoutError)
1246
+ result.timedOut = true;
1247
+ fixupMetadataError(result);
1248
+ return result;
1249
+ }
1250
+ }
1251
+ async _expectInternal(progress, selector, options, lastIntermediateResult, noAbort) {
1252
+ const race = (p) => noAbort ? p : progress.race(p);
1253
+ const isArray = options.expression === "to.have.count" || options.expression.endsWith(".array");
1254
+ var log, matches, received, missingReceived;
1255
+ if (selector) {
1256
+ const { frame, info } = await race(this.selectors.resolveFrameForSelector(selector, { strict: true }));
1257
+ const action = async (result) => {
1258
+ if (!result) {
1259
+ if (options.expectedNumber === 0)
1260
+ return { matches: true };
1261
+ if (!options.isNot && options.expression === "to.be.hidden")
1262
+ return { matches: true };
1263
+ if (options.isNot && options.expression === "to.be.visible")
1264
+ return { matches: false };
1265
+ if (!options.isNot && options.expression === "to.be.detached")
1266
+ return { matches: true };
1267
+ if (options.isNot && options.expression === "to.be.attached")
1268
+ return { matches: false };
1269
+ if (options.isNot && options.expression === "to.be.in.viewport")
1270
+ return { matches: false };
1271
+ return { matches: options.isNot, missingReceived: true };
1272
+ }
1273
+ const handle = result[0];
1274
+ const handles = result[1];
1275
+ if (handle.parentNode.constructor.name == "ElementHandle") {
1276
+ return await handle.parentNode.evaluateInUtility(async ([injected, node, { handle: handle2, options: options2, handles: handles2 }]) => {
1277
+ return await injected.expect(handle2, options2, handles2);
1278
+ }, { handle, options, handles });
1279
+ } else {
1280
+ return await handle.parentNode.evaluate(async (injected, { handle: handle2, options: options2, handles: handles2 }) => {
1281
+ return await injected.expect(handle2, options2, handles2);
1282
+ }, { handle, options, handles });
1283
+ }
1284
+ };
1285
+ if (noAbort) {
1286
+ var { log, matches, received, missingReceived } = await this._retryWithoutProgress(progress, selector, !isArray, false, action, "returnAll", null);
1287
+ } else {
1288
+ var { log, matches, received, missingReceived } = await race(this._retryWithProgressIfNotConnected(progress, selector, !isArray, false, action, "returnAll"));
1289
+ }
1290
+ } else {
1291
+ const world = options.expression === "to.have.property" ? "main" : "utility";
1292
+ const context = await race(this._context(world));
1293
+ const injected = await race(context.injectedScript());
1294
+ var { matches, received, missingReceived } = await race(injected.evaluate(async (injected2, { options: options2, callId }) => {
1295
+ return { ...await injected2.expect(void 0, options2, []) };
1296
+ }, { options, callId: progress.metadata.id }));
1297
+ }
1298
+ if (log)
1299
+ progress.log(log);
1300
+ if (matches === options.isNot) {
1301
+ lastIntermediateResult.received = missingReceived ? "<element(s) not found>" : received;
1302
+ lastIntermediateResult.isSet = true;
1303
+ if (!missingReceived && !Array.isArray(received))
1304
+ progress.log(` unexpected value "${renderUnexpectedValue(options.expression, received)}"`);
1305
+ }
1306
+ return { matches, received };
1307
+ }
1308
+ async waitForFunctionExpression(progress, expression, isFunction, arg, options, world = "main") {
1309
+ if (typeof options.pollingInterval === "number")
1310
+ (0, import_utils.assert)(options.pollingInterval > 0, "Cannot poll with non-positive interval: " + options.pollingInterval);
1311
+ expression = js.normalizeEvaluationExpression(expression, isFunction);
1312
+ return this.retryWithProgressAndTimeouts(progress, [100], async () => {
1313
+ const context = world === "main" ? await progress.race(this._mainContext()) : await progress.race(this._utilityContext());
1314
+ const injectedScript = await progress.race(context.injectedScript());
1315
+ const handle = await progress.race(injectedScript.evaluateHandle((injected, { expression: expression2, isFunction: isFunction2, polling, arg: arg2 }) => {
1316
+ let evaledExpression;
1317
+ const predicate = () => {
1318
+ let result2 = evaledExpression ?? globalThis.eval(expression2);
1319
+ if (isFunction2 === true) {
1320
+ evaledExpression = result2;
1321
+ result2 = result2(arg2);
1322
+ } else if (isFunction2 === false) {
1323
+ result2 = result2;
1324
+ } else {
1325
+ if (typeof result2 === "function") {
1326
+ evaledExpression = result2;
1327
+ result2 = result2(arg2);
1328
+ }
1329
+ }
1330
+ return result2;
1331
+ };
1332
+ let fulfill;
1333
+ let reject;
1334
+ let aborted = false;
1335
+ const result = new Promise((f, r) => {
1336
+ fulfill = f;
1337
+ reject = r;
1338
+ });
1339
+ const next = () => {
1340
+ if (aborted)
1341
+ return;
1342
+ try {
1343
+ const success = predicate();
1344
+ if (success) {
1345
+ fulfill(success);
1346
+ return;
1347
+ }
1348
+ if (typeof polling !== "number")
1349
+ injected.utils.builtins.requestAnimationFrame(next);
1350
+ else
1351
+ injected.utils.builtins.setTimeout(next, polling);
1352
+ } catch (e) {
1353
+ reject(e);
1354
+ }
1355
+ };
1356
+ next();
1357
+ return { result, abort: () => aborted = true };
1358
+ }, { expression, isFunction, polling: options.pollingInterval, arg }));
1359
+ try {
1360
+ return await progress.race(handle.evaluateHandle((h) => h.result));
1361
+ } catch (error) {
1362
+ await handle.evaluate((h) => h.abort()).catch(() => {
1363
+ });
1364
+ throw error;
1365
+ } finally {
1366
+ handle.dispose();
1367
+ }
1368
+ });
1369
+ }
1370
+ async waitForFunctionValueInUtility(progress, pageFunction) {
1371
+ const expression = `() => {
1372
+ const result = (${pageFunction})();
1373
+ if (!result)
1374
+ return result;
1375
+ return JSON.stringify(result);
1376
+ }`;
1377
+ const handle = await this.waitForFunctionExpression(progress, expression, true, void 0, {}, "utility");
1378
+ return JSON.parse(handle.rawValue());
1379
+ }
1380
+ async title() {
1381
+ const context = await this._utilityContext();
1382
+ return context.evaluate(() => document.title);
1383
+ }
1384
+ async rafrafTimeout(progress, timeout) {
1385
+ if (timeout === 0)
1386
+ return;
1387
+ const context = await progress.race(this._utilityContext());
1388
+ await Promise.all([
1389
+ // wait for double raf
1390
+ progress.race(context.evaluate(() => new Promise((x) => {
1391
+ requestAnimationFrame(() => {
1392
+ requestAnimationFrame(x);
1393
+ });
1394
+ }))),
1395
+ progress.wait(timeout)
1396
+ ]);
1397
+ }
1398
+ _onDetached() {
1399
+ this._stopNetworkIdleTimer();
1400
+ this._detachedScope.close(new Error("Frame was detached"));
1401
+ for (const data of this._contextData.values()) {
1402
+ if (data.context)
1403
+ data.context.contextDestroyed("Frame was detached");
1404
+ data.contextPromise.resolve({ destroyedReason: "Frame was detached" });
1405
+ }
1406
+ if (this._parentFrame)
1407
+ this._parentFrame._childFrames.delete(this);
1408
+ this._parentFrame = null;
1409
+ }
1410
+ async _callOnElementOnceMatches(progress, selector, body, taskData, options, scope) {
1411
+ const callbackText = body.toString();
1412
+ progress.log("waiting for " + this._asLocator(selector));
1413
+ var promise;
1414
+ if (selector === ":scope") {
1415
+ const scopeParentNode = scope.parentNode || scope;
1416
+ if (scopeParentNode.constructor.name == "ElementHandle") {
1417
+ promise = scopeParentNode.evaluateInUtility(([injected, node, { callbackText: callbackText2, scope: handle2, taskData: taskData2 }]) => {
1418
+ const callback = injected.eval(callbackText2);
1419
+ return callback(injected, handle2, taskData2);
1420
+ }, {
1421
+ callbackText,
1422
+ scope,
1423
+ taskData
1424
+ });
1425
+ } else {
1426
+ promise = scopeParentNode.evaluate((injected, { callbackText: callbackText2, scope: handle2, taskData: taskData2 }) => {
1427
+ const callback = injected.eval(callbackText2);
1428
+ return callback(injected, handle2, taskData2);
1429
+ }, {
1430
+ callbackText,
1431
+ scope,
1432
+ taskData
1433
+ });
1434
+ }
1435
+ } else {
1436
+ promise = this._retryWithProgressIfNotConnected(progress, selector, options.strict, false, async (handle) => {
1437
+ if (handle.parentNode.constructor.name == "ElementHandle") {
1438
+ const [taskScope] = Object.values(taskData?.eventInit ?? {});
1439
+ if (taskScope) {
1440
+ const taskScopeContext = taskScope._context;
1441
+ const adoptedHandle = await handle._adoptTo(taskScopeContext);
1442
+ return await taskScopeContext.evaluate(([injected, node, { callbackText: callbackText2, adoptedHandle: handle2, taskData: taskData2 }]) => {
1443
+ const callback = injected.eval(callbackText2);
1444
+ return callback(injected, handle2, taskData2);
1445
+ }, [
1446
+ await taskScopeContext.injectedScript(),
1447
+ adoptedHandle,
1448
+ { callbackText, adoptedHandle, taskData }
1449
+ ]);
1450
+ }
1451
+ return await handle.parentNode.evaluateInUtility(([injected, node, { callbackText: callbackText2, handle: handle2, taskData: taskData2 }]) => {
1452
+ const callback = injected.eval(callbackText2);
1453
+ return callback(injected, handle2, taskData2);
1454
+ }, {
1455
+ callbackText,
1456
+ handle,
1457
+ taskData
1458
+ });
1459
+ } else {
1460
+ return await handle.parentNode.evaluate((injected, { callbackText: callbackText2, handle: handle2, taskData: taskData2 }) => {
1461
+ const callback = injected.eval(callbackText2);
1462
+ return callback(injected, handle2, taskData2);
1463
+ }, {
1464
+ callbackText,
1465
+ handle,
1466
+ taskData
1467
+ });
1468
+ }
1469
+ });
1470
+ }
1471
+ return scope ? scope._context._raceAgainstContextDestroyed(promise) : promise;
1472
+ }
1473
+ _setContext(world, context) {
1474
+ const data = this._contextData.get(world);
1475
+ data.context = context;
1476
+ if (context)
1477
+ data.contextPromise.resolve(context);
1478
+ else
1479
+ data.contextPromise = new import_manualPromise.ManualPromise();
1480
+ }
1481
+ _contextCreated(world, context) {
1482
+ const data = this._contextData.get(world);
1483
+ if (data.context) {
1484
+ data.context.contextDestroyed("Execution context was destroyed, most likely because of a navigation");
1485
+ this._setContext(world, null);
1486
+ }
1487
+ this._setContext(world, context);
1488
+ }
1489
+ _contextDestroyed(context) {
1490
+ if (this._detachedScope.isClosed())
1491
+ return;
1492
+ context.contextDestroyed("Execution context was destroyed, most likely because of a navigation");
1493
+ for (const [world, data] of this._contextData) {
1494
+ if (data.context === context)
1495
+ this._setContext(world, null);
1496
+ }
1497
+ }
1498
+ _startNetworkIdleTimer() {
1499
+ (0, import_utils.assert)(!this._networkIdleTimer);
1500
+ if (this._firedLifecycleEvents.has("networkidle") || this._detachedScope.isClosed())
1501
+ return;
1502
+ this._networkIdleTimer = setTimeout(() => {
1503
+ this._firedNetworkIdleSelf = true;
1504
+ this._page.mainFrame()._recalculateNetworkIdle();
1505
+ }, 500);
1506
+ }
1507
+ _stopNetworkIdleTimer() {
1508
+ if (this._networkIdleTimer)
1509
+ clearTimeout(this._networkIdleTimer);
1510
+ this._networkIdleTimer = void 0;
1511
+ this._firedNetworkIdleSelf = false;
1512
+ }
1513
+ async extendInjectedScript(source, arg) {
1514
+ const context = await this._context("main");
1515
+ const injectedScriptHandle = await context.injectedScript();
1516
+ await injectedScriptHandle.evaluate((injectedScript, { source: source2, arg: arg2 }) => {
1517
+ injectedScript.extend(source2, arg2);
1518
+ }, { source, arg });
1519
+ }
1520
+ _asLocator(selector) {
1521
+ return (0, import_utils.asLocator)(this._page.browserContext._browser.sdkLanguage(), selector);
1522
+ }
1523
+ async _getFrameMainFrameContextId(client) {
1524
+ try {
1525
+ var globalDocument = await client._sendMayFail("DOM.getFrameOwner", { frameId: this._id });
1526
+ if (globalDocument && globalDocument.nodeId) {
1527
+ var describedNode = await client._sendMayFail("DOM.describeNode", {
1528
+ backendNodeId: globalDocument.backendNodeId
1529
+ });
1530
+ if (describedNode) {
1531
+ var resolvedNode = await client._sendMayFail("DOM.resolveNode", {
1532
+ nodeId: describedNode.node.contentDocument.nodeId
1533
+ });
1534
+ var _executionContextId = parseInt(resolvedNode.object.objectId.split(".")[1], 10);
1535
+ return _executionContextId;
1536
+ }
1537
+ }
1538
+ } catch (e) {
1539
+ }
1540
+ return 0;
1541
+ }
1542
+ async _retryWithoutProgress(progress, selector, strict2, performActionPreChecks2, action, returnAction, continuePolling) {
1543
+ if (performActionPreChecks2) await this._page.performActionPreChecks(progress);
1544
+ const resolved = await this.selectors.resolveInjectedForSelector(selector, { strict: strict2 });
1545
+ if (!resolved) {
1546
+ if (returnAction === "returnOnNotResolved" || returnAction === "returnAll") {
1547
+ const result2 = await action(null);
1548
+ return result2 === "internal:continuepolling" ? continuePolling : result2;
1549
+ }
1550
+ return continuePolling;
1551
+ }
1552
+ try {
1553
+ var client = this._page.delegate._sessionForFrame(resolved.frame)._client;
1554
+ } catch (e) {
1555
+ var client = this._page.delegate._mainFrameSession._client;
1556
+ }
1557
+ var utilityContext = await resolved.frame._utilityContext();
1558
+ var mainContext = await resolved.frame._mainContext();
1559
+ const documentNode = await client._sendMayFail("Runtime.evaluate", {
1560
+ expression: "document",
1561
+ serializationOptions: {
1562
+ serialization: "idOnly"
1563
+ },
1564
+ contextId: utilityContext.delegate._contextId
1565
+ });
1566
+ if (!documentNode) return continuePolling;
1567
+ const documentScope = new dom.ElementHandle(utilityContext, documentNode.result.objectId);
1568
+ let currentScopingElements;
1569
+ try {
1570
+ currentScopingElements = await this._customFindElementsByParsed(resolved, client, mainContext, documentScope, progress, resolved.info.parsed);
1571
+ } catch (e) {
1572
+ if ("JSHandles can be evaluated only in the context they were created!" === e.message) return continuePolling3;
1573
+ await progress.race(resolved.injected.evaluateHandle((injected, { error }) => {
1574
+ throw error;
1575
+ }, { error: e }));
1576
+ }
1577
+ if (currentScopingElements.length == 0) {
1578
+ if (returnAction === "returnOnNotResolved" || returnAction === "returnAll") {
1579
+ const result2 = await action(null);
1580
+ return result2 === "internal:continuepolling" ? continuePolling2 : result2;
1581
+ }
1582
+ return continuePolling;
1583
+ }
1584
+ const resultElement = currentScopingElements[0];
1585
+ if (currentScopingElements.length > 1) {
1586
+ if (resolved.info.strict) {
1587
+ await progress.race(resolved.injected.evaluateHandle((injected, {
1588
+ info,
1589
+ elements
1590
+ }) => {
1591
+ throw injected.strictModeViolationError(info.parsed, elements);
1592
+ }, {
1593
+ info: resolved.info,
1594
+ elements: currentScopingElements
1595
+ }));
1596
+ }
1597
+ progress.log(" locator resolved to " + currentScopingElements.length + " elements. Proceeding with the first one: " + resultElement.preview());
1598
+ } else if (resultElement) {
1599
+ progress.log(" locator resolved to " + resultElement.preview());
1600
+ }
1601
+ try {
1602
+ var result = null;
1603
+ if (returnAction === "returnAll") {
1604
+ result = await action([resultElement, currentScopingElements]);
1605
+ } else {
1606
+ result = await action(resultElement);
1607
+ }
1608
+ if (result === "error:notconnected") {
1609
+ progress.log("element was detached from the DOM, retrying");
1610
+ return continuePolling;
1611
+ } else if (result === "internal:continuepolling") {
1612
+ return continuePolling;
1613
+ }
1614
+ return result;
1615
+ } finally {
1616
+ }
1617
+ }
1618
+ async _customFindElementsByParsed(resolved, client, context, documentScope, progress, parsed) {
1619
+ var parsedEdits = { ...parsed };
1620
+ var currentScopingElements = [documentScope];
1621
+ while (parsed.parts.length > 0) {
1622
+ var part = parsed.parts.shift();
1623
+ parsedEdits.parts = [part];
1624
+ var elements = [];
1625
+ var elementsIndexes = [];
1626
+ if (part.name == "nth") {
1627
+ const partNth = Number(part.body);
1628
+ if (currentScopingElements.length == 0) return [];
1629
+ if (partNth > currentScopingElements.length - 1 || partNth < -(currentScopingElements.length - 1)) {
1630
+ if (parsed.capture !== void 0) throw new Error("Can't query n-th element in a request with the capture.");
1631
+ return [];
1632
+ } else {
1633
+ currentScopingElements = [currentScopingElements.at(partNth)];
1634
+ continue;
1635
+ }
1636
+ } else if (part.name == "internal:or") {
1637
+ var orredElements = await this._customFindElementsByParsed(resolved, client, context, documentScope, progress, part.body.parsed);
1638
+ elements = currentScopingElements.concat(orredElements);
1639
+ } else if (part.name == "internal:and") {
1640
+ var andedElements = await this._customFindElementsByParsed(resolved, client, context, documentScope, progress, part.body.parsed);
1641
+ const backendNodeIds = new Set(andedElements.map((item) => item.backendNodeId));
1642
+ elements = currentScopingElements.filter((item) => backendNodeIds.has(item.backendNodeId));
1643
+ } else {
1644
+ for (const scope of currentScopingElements) {
1645
+ let findClosedShadowRoots2 = function(node, results = []) {
1646
+ if (!node || typeof node !== "object") return results;
1647
+ if (node.shadowRoots && Array.isArray(node.shadowRoots)) {
1648
+ for (const shadowRoot2 of node.shadowRoots) {
1649
+ if (shadowRoot2.shadowRootType === "closed" && shadowRoot2.backendNodeId) {
1650
+ results.push(shadowRoot2.backendNodeId);
1651
+ }
1652
+ findClosedShadowRoots2(shadowRoot2, results);
1653
+ }
1654
+ }
1655
+ if (node.nodeName !== "IFRAME" && node.children && Array.isArray(node.children)) {
1656
+ for (const child of node.children) {
1657
+ findClosedShadowRoots2(child, results);
1658
+ }
1659
+ }
1660
+ return results;
1661
+ };
1662
+ var findClosedShadowRoots = findClosedShadowRoots2;
1663
+ const describedScope = await client.send("DOM.describeNode", {
1664
+ objectId: scope._objectId,
1665
+ depth: -1,
1666
+ pierce: true
1667
+ });
1668
+ var queryingElements = [];
1669
+ var shadowRootBackendIds = findClosedShadowRoots2(describedScope.node);
1670
+ var shadowRoots = [];
1671
+ for (var shadowRootBackendId of shadowRootBackendIds) {
1672
+ var resolvedShadowRoot = await client.send("DOM.resolveNode", {
1673
+ backendNodeId: shadowRootBackendId,
1674
+ contextId: context.delegate._contextId
1675
+ });
1676
+ shadowRoots.push(new dom.ElementHandle(context, resolvedShadowRoot.object.objectId));
1677
+ }
1678
+ for (var shadowRoot of shadowRoots) {
1679
+ const shadowElements = await shadowRoot.evaluateHandleInUtility(([injected, node, { parsed: parsed2, callId }]) => {
1680
+ const elements2 = injected.querySelectorAll(parsed2, node);
1681
+ if (callId) injected.markTargetElements(new Set(elements2), callId);
1682
+ return elements2;
1683
+ }, {
1684
+ parsed: parsedEdits,
1685
+ callId: progress.metadata.id
1686
+ });
1687
+ const shadowElementsAmount = await shadowElements.getProperty("length");
1688
+ queryingElements.push([shadowElements, shadowElementsAmount, shadowRoot]);
1689
+ }
1690
+ const rootElements = await scope.evaluateHandleInUtility(([injected, node, { parsed: parsed2, callId }]) => {
1691
+ const elements2 = injected.querySelectorAll(parsed2, node);
1692
+ if (callId) injected.markTargetElements(new Set(elements2), callId);
1693
+ return elements2;
1694
+ }, {
1695
+ parsed: parsedEdits,
1696
+ callId: progress.metadata.id
1697
+ });
1698
+ const rootElementsAmount = await rootElements.getProperty("length");
1699
+ queryingElements.push([rootElements, rootElementsAmount, scope]);
1700
+ for (var queryedElement of queryingElements) {
1701
+ var elementsToCheck = queryedElement[0];
1702
+ var elementsAmount = await queryedElement[1].jsonValue();
1703
+ var parentNode = queryedElement[2];
1704
+ for (var i = 0; i < elementsAmount; i++) {
1705
+ if (parentNode.constructor.name == "ElementHandle") {
1706
+ var elementToCheck = await parentNode.evaluateHandleInUtility(([injected, node, { index, elementsToCheck: elementsToCheck2 }]) => {
1707
+ return elementsToCheck2[index];
1708
+ }, { index: i, elementsToCheck });
1709
+ } else {
1710
+ var elementToCheck = await parentNode.evaluateHandle((injected, { index, elementsToCheck: elementsToCheck2 }) => {
1711
+ return elementsToCheck2[index];
1712
+ }, { index: i, elementsToCheck });
1713
+ }
1714
+ elementToCheck.parentNode = parentNode;
1715
+ var resolvedElement = await client.send("DOM.describeNode", {
1716
+ objectId: elementToCheck._objectId,
1717
+ depth: -1
1718
+ });
1719
+ elementToCheck.backendNodeId = resolvedElement.node.backendNodeId;
1720
+ elementToCheck.nodePosition = this.selectors._findElementPositionInDomTree(elementToCheck, describedScope.node, context, "");
1721
+ elements.push(elementToCheck);
1722
+ }
1723
+ }
1724
+ }
1725
+ }
1726
+ const getParts = (pos) => (pos || "").split(".").filter(Boolean).map(Number);
1727
+ elements.sort((a, b) => {
1728
+ const partA = getParts(a.nodePosition);
1729
+ const partB = getParts(b.nodePosition);
1730
+ const maxLength = Math.max(partA.length, partB.length);
1731
+ for (let i2 = 0; i2 < maxLength; i2++) {
1732
+ const aVal = partA[i2] ?? -1;
1733
+ const bVal = partB[i2] ?? -1;
1734
+ if (aVal !== bVal) return aVal - bVal;
1735
+ }
1736
+ return 0;
1737
+ });
1738
+ currentScopingElements = Array.from(
1739
+ new Map(elements.map((e) => [e.backendNodeId, e])).values()
1740
+ );
1741
+ }
1742
+ return currentScopingElements;
1743
+ }
1744
+ }
1745
+ class SignalBarrier {
1746
+ constructor(progress) {
1747
+ this._protectCount = 0;
1748
+ this._promise = new import_manualPromise.ManualPromise();
1749
+ this._progress = progress;
1750
+ this.retain();
1751
+ }
1752
+ waitFor() {
1753
+ this.release();
1754
+ return this._progress.race(this._promise);
1755
+ }
1756
+ addFrameNavigation(frame) {
1757
+ if (frame.parentFrame())
1758
+ return;
1759
+ this.retain();
1760
+ const waiter = import_helper.helper.waitForEvent(this._progress, frame, Frame.Events.InternalNavigation, (e) => {
1761
+ if (!e.isPublic)
1762
+ return false;
1763
+ if (!e.error && this._progress)
1764
+ this._progress.log(` navigated to "${frame._url}"`);
1765
+ return true;
1766
+ });
1767
+ import_utils.LongStandingScope.raceMultiple([
1768
+ frame._page.openScope,
1769
+ frame._detachedScope
1770
+ ], waiter.promise).catch(() => {
1771
+ }).finally(() => {
1772
+ waiter.dispose();
1773
+ this.release();
1774
+ });
1775
+ }
1776
+ retain() {
1777
+ ++this._protectCount;
1778
+ }
1779
+ release() {
1780
+ --this._protectCount;
1781
+ if (!this._protectCount)
1782
+ this._promise.resolve();
1783
+ }
1784
+ }
1785
+ function verifyLifecycle(name, waitUntil) {
1786
+ if (waitUntil === "networkidle0")
1787
+ waitUntil = "networkidle";
1788
+ if (!types.kLifecycleEvents.has(waitUntil))
1789
+ throw new Error(`${name}: expected one of (load|domcontentloaded|networkidle|commit)`);
1790
+ return waitUntil;
1791
+ }
1792
+ function renderUnexpectedValue(expression, received) {
1793
+ if (expression === "to.match.aria")
1794
+ return received ? received.raw : received;
1795
+ return received;
1796
+ }
1797
+ // Annotate the CommonJS export names for ESM import in node:
1798
+ 0 && (module.exports = {
1799
+ Frame,
1800
+ FrameManager,
1801
+ NavigationAbortedError
1802
+ });