@checkly/playwright-core 1.51.17-beta.2 → 1.54.2-beta.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 (376) hide show
  1. package/ThirdPartyNotices.txt +65 -123
  2. package/browsers.json +16 -14
  3. package/index.js +1 -1
  4. package/lib/androidServerImpl.js +47 -50
  5. package/lib/browserServerImpl.js +89 -69
  6. package/lib/checkly/escapeRegExp.js +23 -27
  7. package/lib/checkly/fetch.js +64 -46
  8. package/lib/checkly/secretsFilter.js +49 -35
  9. package/lib/cli/driver.js +71 -69
  10. package/lib/cli/program.js +400 -359
  11. package/lib/cli/programWithTestStub.js +51 -45
  12. package/lib/client/accessibility.js +31 -32
  13. package/lib/client/android.js +151 -242
  14. package/lib/client/api.js +135 -283
  15. package/lib/client/artifact.js +39 -36
  16. package/lib/client/browser.js +96 -71
  17. package/lib/client/browserContext.js +314 -345
  18. package/lib/client/browserType.js +103 -127
  19. package/lib/client/cdpSession.js +29 -31
  20. package/lib/client/channelOwner.js +90 -113
  21. package/lib/client/clientHelper.js +48 -39
  22. package/lib/client/clientInstrumentation.js +40 -37
  23. package/lib/client/clientStackTrace.js +41 -37
  24. package/lib/client/clock.js +36 -36
  25. package/lib/client/connection.js +188 -214
  26. package/lib/client/consoleMessage.js +31 -28
  27. package/lib/client/coverage.js +25 -22
  28. package/lib/client/dialog.js +30 -31
  29. package/lib/client/download.js +25 -25
  30. package/lib/client/electron.js +80 -77
  31. package/lib/client/elementHandle.js +120 -159
  32. package/lib/client/errors.js +53 -53
  33. package/lib/client/eventEmitter.js +124 -121
  34. package/lib/client/events.js +72 -68
  35. package/lib/client/fetch.js +166 -190
  36. package/lib/client/fileChooser.js +25 -24
  37. package/lib/client/fileUtils.js +31 -28
  38. package/lib/client/frame.js +207 -306
  39. package/lib/client/harRouter.js +42 -52
  40. package/lib/client/input.js +42 -69
  41. package/lib/client/jsHandle.js +54 -69
  42. package/lib/client/jsonPipe.js +27 -23
  43. package/lib/client/localUtils.js +29 -29
  44. package/lib/client/locator.js +145 -237
  45. package/lib/client/network.js +282 -307
  46. package/lib/client/page.js +269 -318
  47. package/lib/client/platform.js +46 -43
  48. package/lib/client/playwright.js +51 -76
  49. package/lib/client/selectors.js +45 -63
  50. package/lib/client/stream.js +29 -25
  51. package/lib/client/timeoutSettings.js +55 -41
  52. package/lib/client/tracing.js +49 -96
  53. package/lib/client/types.js +26 -22
  54. package/lib/client/video.js +35 -27
  55. package/lib/client/waiter.js +69 -88
  56. package/lib/client/webError.js +25 -23
  57. package/lib/client/webSocket.js +43 -56
  58. package/lib/client/worker.js +48 -56
  59. package/lib/client/writableStream.js +27 -23
  60. package/lib/generated/bindingsControllerSource.js +28 -0
  61. package/lib/generated/clockSource.js +26 -6
  62. package/lib/generated/consoleApiSource.js +26 -6
  63. package/lib/generated/injectedScriptSource.js +26 -6
  64. package/lib/generated/pollingRecorderSource.js +26 -6
  65. package/lib/generated/storageScriptSource.js +28 -0
  66. package/lib/generated/utilityScriptSource.js +26 -6
  67. package/lib/generated/webSocketMockSource.js +333 -5
  68. package/lib/inProcessFactory.js +51 -53
  69. package/lib/inprocess.js +2 -19
  70. package/lib/outofprocess.js +51 -46
  71. package/lib/protocol/serializers.js +153 -134
  72. package/lib/protocol/validator.js +2807 -2739
  73. package/lib/protocol/validatorPrimitives.js +114 -73
  74. package/lib/remote/playwrightConnection.js +88 -242
  75. package/lib/remote/playwrightServer.js +305 -92
  76. package/lib/server/accessibility.js +44 -37
  77. package/lib/server/android/android.js +251 -241
  78. package/lib/server/android/backendAdb.js +87 -82
  79. package/lib/server/artifact.js +78 -55
  80. package/lib/server/bidi/bidiBrowser.js +297 -158
  81. package/lib/server/bidi/bidiChromium.js +119 -89
  82. package/lib/server/bidi/bidiConnection.js +66 -83
  83. package/lib/server/bidi/bidiExecutionContext.js +129 -113
  84. package/lib/server/bidi/bidiFirefox.js +86 -76
  85. package/lib/server/bidi/bidiInput.js +106 -117
  86. package/lib/server/bidi/bidiNetworkManager.js +142 -159
  87. package/lib/server/bidi/bidiOverCdp.js +57 -58
  88. package/lib/server/bidi/bidiPage.js +260 -260
  89. package/lib/server/bidi/bidiPdf.js +52 -86
  90. package/lib/server/bidi/third_party/bidiCommands.d.js +22 -0
  91. package/lib/server/bidi/third_party/bidiDeserializer.js +55 -50
  92. package/lib/server/bidi/third_party/bidiKeyboard.js +236 -220
  93. package/lib/server/bidi/third_party/bidiProtocol.js +22 -137
  94. package/lib/server/bidi/third_party/bidiProtocolCore.js +152 -0
  95. package/lib/server/bidi/third_party/bidiProtocolPermissions.js +42 -0
  96. package/lib/server/bidi/third_party/bidiSerializer.js +67 -63
  97. package/lib/server/bidi/third_party/firefoxPrefs.js +141 -119
  98. package/lib/server/browser.js +93 -95
  99. package/lib/server/browserContext.js +419 -429
  100. package/lib/server/browserType.js +186 -216
  101. package/lib/server/callLog.js +47 -44
  102. package/lib/server/chromium/chromium.js +235 -203
  103. package/lib/server/chromium/chromiumSwitches.js +100 -67
  104. package/lib/server/chromium/crAccessibility.js +157 -131
  105. package/lib/server/chromium/crBrowser.js +310 -292
  106. package/lib/server/chromium/crConnection.js +95 -121
  107. package/lib/server/chromium/crCoverage.js +121 -131
  108. package/lib/server/chromium/crDevTools.js +60 -51
  109. package/lib/server/chromium/crDragDrop.js +68 -84
  110. package/lib/server/chromium/crExecutionContext.js +89 -83
  111. package/lib/server/chromium/crInput.js +118 -113
  112. package/lib/server/chromium/crNetworkManager.js +274 -375
  113. package/lib/server/chromium/crPage.js +536 -593
  114. package/lib/server/chromium/crPdf.js +54 -86
  115. package/lib/server/chromium/crProtocolHelper.js +92 -80
  116. package/lib/server/chromium/crServiceWorker.js +84 -73
  117. package/lib/server/chromium/defaultFontFamilies.js +152 -135
  118. package/lib/server/chromium/protocol.d.js +16 -0
  119. package/lib/server/chromium/videoRecorder.js +66 -99
  120. package/lib/server/clock.js +107 -83
  121. package/lib/server/codegen/csharp.js +192 -162
  122. package/lib/server/codegen/java.js +156 -129
  123. package/lib/server/codegen/javascript.js +163 -148
  124. package/lib/server/codegen/jsonl.js +32 -28
  125. package/lib/server/codegen/language.js +75 -52
  126. package/lib/server/codegen/languages.js +65 -27
  127. package/lib/server/codegen/python.js +141 -126
  128. package/lib/server/codegen/types.js +15 -4
  129. package/lib/server/console.js +28 -32
  130. package/lib/server/cookieStore.js +108 -86
  131. package/lib/server/debugController.js +147 -151
  132. package/lib/server/debugger.js +86 -78
  133. package/lib/server/deviceDescriptors.js +37 -24
  134. package/lib/server/deviceDescriptorsSource.json +238 -128
  135. package/lib/server/dialog.js +84 -39
  136. package/lib/server/dispatchers/androidDispatcher.js +257 -148
  137. package/lib/server/dispatchers/artifactDispatcher.js +79 -79
  138. package/lib/server/dispatchers/browserContextDispatcher.js +289 -259
  139. package/lib/server/dispatchers/browserDispatcher.js +96 -148
  140. package/lib/server/dispatchers/browserTypeDispatcher.js +50 -41
  141. package/lib/server/dispatchers/cdpSessionDispatcher.js +35 -39
  142. package/lib/server/dispatchers/debugControllerDispatcher.js +65 -83
  143. package/lib/server/dispatchers/dialogDispatcher.js +34 -31
  144. package/lib/server/dispatchers/dispatcher.js +208 -248
  145. package/lib/server/dispatchers/electronDispatcher.js +66 -70
  146. package/lib/server/dispatchers/elementHandlerDispatcher.js +164 -216
  147. package/lib/server/dispatchers/frameDispatcher.js +211 -272
  148. package/lib/server/dispatchers/jsHandleDispatcher.js +63 -75
  149. package/lib/server/dispatchers/jsonPipeDispatcher.js +37 -38
  150. package/lib/server/dispatchers/localUtilsDispatcher.js +121 -119
  151. package/lib/server/dispatchers/networkDispatchers.js +117 -128
  152. package/lib/server/dispatchers/pageDispatcher.js +256 -248
  153. package/lib/server/dispatchers/playwrightDispatcher.js +92 -87
  154. package/lib/server/dispatchers/streamDispatcher.js +52 -48
  155. package/lib/server/dispatchers/tracingDispatcher.js +47 -52
  156. package/lib/server/dispatchers/webSocketRouteDispatcher.js +126 -150
  157. package/lib/server/dispatchers/writableStreamDispatcher.js +65 -43
  158. package/lib/server/dom.js +485 -582
  159. package/lib/server/download.js +47 -37
  160. package/lib/server/electron/electron.js +216 -243
  161. package/lib/server/electron/loader.js +9 -37
  162. package/lib/server/errors.js +47 -46
  163. package/lib/server/fetch.js +317 -360
  164. package/lib/server/fileChooser.js +25 -24
  165. package/lib/server/fileUploadUtils.js +66 -60
  166. package/lib/server/firefox/ffAccessibility.js +153 -131
  167. package/lib/server/firefox/ffBrowser.js +268 -305
  168. package/lib/server/firefox/ffConnection.js +63 -84
  169. package/lib/server/firefox/ffExecutionContext.js +92 -73
  170. package/lib/server/firefox/ffInput.js +82 -84
  171. package/lib/server/firefox/ffNetworkManager.js +137 -114
  172. package/lib/server/firefox/ffPage.js +261 -293
  173. package/lib/server/firefox/firefox.js +80 -72
  174. package/lib/server/firefox/protocol.d.js +16 -0
  175. package/lib/server/formData.js +107 -35
  176. package/lib/server/frameSelectors.js +98 -114
  177. package/lib/server/frames.js +845 -1055
  178. package/lib/server/har/harRecorder.js +85 -77
  179. package/lib/server/har/harTracer.js +290 -223
  180. package/lib/server/harBackend.js +80 -80
  181. package/lib/server/helper.js +55 -59
  182. package/lib/server/index.js +59 -99
  183. package/lib/server/input.js +151 -189
  184. package/lib/server/instrumentation.js +57 -44
  185. package/lib/server/javascript.js +133 -134
  186. package/lib/server/launchApp.js +113 -75
  187. package/lib/server/localUtils.js +150 -142
  188. package/lib/server/macEditingCommands.js +141 -137
  189. package/lib/server/network.js +299 -303
  190. package/lib/server/page.js +513 -544
  191. package/lib/server/pipeTransport.js +49 -45
  192. package/lib/server/playwright.js +58 -67
  193. package/lib/server/progress.js +137 -68
  194. package/lib/server/protocolError.js +34 -31
  195. package/lib/server/recorder/chat.js +70 -86
  196. package/lib/server/recorder/recorderApp.js +341 -176
  197. package/lib/server/recorder/recorderInTraceViewer.js +65 -94
  198. package/lib/server/recorder/recorderRunner.js +93 -116
  199. package/lib/server/recorder/recorderSignalProcessor.js +83 -0
  200. package/lib/server/recorder/recorderUtils.js +104 -47
  201. package/lib/server/recorder/throttledFile.js +42 -30
  202. package/lib/server/recorder.js +395 -275
  203. package/lib/server/registry/browserFetcher.js +106 -101
  204. package/lib/server/registry/dependencies.js +245 -196
  205. package/lib/server/registry/index.js +930 -803
  206. package/lib/server/registry/nativeDeps.js +1073 -464
  207. package/lib/server/registry/oopDownloadBrowserMain.js +57 -75
  208. package/lib/server/screenshotter.js +160 -191
  209. package/lib/server/selectors.js +90 -51
  210. package/lib/server/socksClientCertificatesInterceptor.js +171 -186
  211. package/lib/server/socksInterceptor.js +62 -70
  212. package/lib/server/trace/recorder/snapshotter.js +76 -102
  213. package/lib/server/trace/recorder/snapshotterInjected.js +238 -217
  214. package/lib/server/trace/recorder/tracing.js +354 -362
  215. package/lib/server/trace/test/inMemorySnapshotter.js +46 -52
  216. package/lib/server/trace/viewer/traceViewer.js +160 -147
  217. package/lib/server/transport.js +119 -134
  218. package/lib/server/types.js +26 -22
  219. package/lib/server/usKeyboardLayout.js +135 -545
  220. package/lib/server/utils/ascii.js +39 -26
  221. package/lib/server/utils/comparators.js +105 -103
  222. package/lib/server/utils/crypto.js +157 -112
  223. package/lib/server/utils/debug.js +36 -32
  224. package/lib/server/utils/debugLogger.js +77 -48
  225. package/lib/server/utils/env.js +52 -37
  226. package/lib/server/utils/eventsHelper.js +29 -28
  227. package/lib/server/utils/expectUtils.js +31 -26
  228. package/lib/server/utils/fileUtils.js +123 -136
  229. package/lib/server/utils/happyEyeballs.js +141 -126
  230. package/lib/server/utils/hostPlatform.js +84 -120
  231. package/lib/server/utils/httpServer.js +106 -121
  232. package/lib/server/utils/image_tools/colorUtils.js +42 -51
  233. package/lib/server/utils/image_tools/compare.js +44 -43
  234. package/lib/server/utils/image_tools/imageChannel.js +38 -30
  235. package/lib/server/utils/image_tools/stats.js +40 -40
  236. package/lib/server/utils/linuxUtils.js +50 -37
  237. package/lib/server/utils/network.js +152 -96
  238. package/lib/server/utils/nodePlatform.js +87 -79
  239. package/lib/server/utils/pipeTransport.js +44 -42
  240. package/lib/server/utils/processLauncher.js +111 -121
  241. package/lib/server/utils/profiler.js +52 -39
  242. package/lib/server/utils/socksProxy.js +280 -339
  243. package/lib/server/utils/spawnAsync.js +37 -41
  244. package/lib/server/utils/task.js +31 -38
  245. package/lib/server/utils/userAgent.js +73 -66
  246. package/lib/server/utils/wsServer.js +68 -75
  247. package/lib/server/utils/zipFile.js +36 -37
  248. package/lib/server/utils/zones.js +37 -34
  249. package/lib/server/webkit/protocol.d.js +16 -0
  250. package/lib/server/webkit/webkit.js +77 -61
  251. package/lib/server/webkit/wkAccessibility.js +161 -118
  252. package/lib/server/webkit/wkBrowser.js +193 -184
  253. package/lib/server/webkit/wkConnection.js +59 -83
  254. package/lib/server/webkit/wkExecutionContext.js +85 -70
  255. package/lib/server/webkit/wkInput.js +97 -95
  256. package/lib/server/webkit/wkInterceptableRequest.js +102 -95
  257. package/lib/server/webkit/wkPage.js +568 -667
  258. package/lib/server/webkit/wkProvisionalPage.js +45 -56
  259. package/lib/server/webkit/wkWorkers.js +79 -79
  260. package/lib/utils/expectUtils.js +31 -26
  261. package/lib/utils/isomorphic/ariaSnapshot.js +149 -152
  262. package/lib/utils/isomorphic/assert.js +28 -22
  263. package/lib/utils/isomorphic/colors.js +66 -59
  264. package/lib/utils/isomorphic/cssParser.js +120 -125
  265. package/lib/utils/isomorphic/cssTokenizer.js +436 -364
  266. package/lib/utils/isomorphic/headers.js +38 -37
  267. package/lib/utils/isomorphic/locatorGenerators.js +358 -357
  268. package/lib/utils/isomorphic/locatorParser.js +96 -105
  269. package/lib/utils/isomorphic/locatorUtils.js +63 -44
  270. package/lib/utils/isomorphic/manualPromise.js +46 -39
  271. package/lib/utils/isomorphic/mimeType.js +447 -25
  272. package/lib/utils/isomorphic/multimap.js +34 -27
  273. package/lib/utils/isomorphic/protocolFormatter.js +68 -0
  274. package/lib/utils/isomorphic/protocolMetainfo.js +321 -0
  275. package/lib/utils/isomorphic/recorderUtils.js +140 -181
  276. package/lib/utils/isomorphic/rtti.js +35 -33
  277. package/lib/utils/isomorphic/selectorParser.js +182 -193
  278. package/lib/utils/isomorphic/semaphore.js +27 -24
  279. package/lib/utils/isomorphic/stackTrace.js +87 -98
  280. package/lib/utils/isomorphic/stringUtils.js +98 -112
  281. package/lib/utils/isomorphic/time.js +46 -22
  282. package/lib/utils/isomorphic/timeoutRunner.js +53 -53
  283. package/lib/utils/isomorphic/traceUtils.js +37 -41
  284. package/lib/utils/isomorphic/types.js +15 -4
  285. package/lib/utils/isomorphic/urlMatch.js +113 -67
  286. package/lib/utils/isomorphic/utilityScriptSerializers.js +251 -0
  287. package/lib/utils.js +101 -443
  288. package/lib/utilsBundle.js +101 -52
  289. package/lib/utilsBundleImpl/index.js +160 -150
  290. package/lib/zipBundle.js +32 -23
  291. package/lib/zipBundleImpl.js +4 -4
  292. package/package.json +1 -1
  293. package/types/protocol.d.ts +1267 -1057
  294. package/types/types.d.ts +131 -29
  295. package/lib/common/socksProxy.js +0 -569
  296. package/lib/common/timeoutSettings.js +0 -73
  297. package/lib/common/types.js +0 -5
  298. package/lib/image_tools/colorUtils.js +0 -98
  299. package/lib/image_tools/compare.js +0 -108
  300. package/lib/image_tools/imageChannel.js +0 -70
  301. package/lib/image_tools/stats.js +0 -102
  302. package/lib/protocol/debug.js +0 -27
  303. package/lib/protocol/transport.js +0 -82
  304. package/lib/server/dispatchers/selectorsDispatcher.js +0 -36
  305. package/lib/server/isomorphic/utilityScriptSerializers.js +0 -229
  306. package/lib/server/recorder/contextRecorder.js +0 -290
  307. package/lib/server/recorder/recorderCollection.js +0 -104
  308. package/lib/server/recorder/recorderFrontend.js +0 -5
  309. package/lib/server/storageScript.js +0 -160
  310. package/lib/server/timeoutSettings.js +0 -74
  311. package/lib/third_party/diff_match_patch.js +0 -2222
  312. package/lib/utils/ascii.js +0 -31
  313. package/lib/utils/comparators.js +0 -171
  314. package/lib/utils/crypto.js +0 -174
  315. package/lib/utils/debug.js +0 -46
  316. package/lib/utils/debugLogger.js +0 -91
  317. package/lib/utils/env.js +0 -49
  318. package/lib/utils/eventsHelper.js +0 -38
  319. package/lib/utils/fileUtils.js +0 -205
  320. package/lib/utils/happy-eyeballs.js +0 -210
  321. package/lib/utils/headers.js +0 -52
  322. package/lib/utils/hostPlatform.js +0 -133
  323. package/lib/utils/httpServer.js +0 -237
  324. package/lib/utils/index.js +0 -368
  325. package/lib/utils/linuxUtils.js +0 -78
  326. package/lib/utils/manualPromise.js +0 -109
  327. package/lib/utils/multimap.js +0 -75
  328. package/lib/utils/network.js +0 -160
  329. package/lib/utils/processLauncher.js +0 -248
  330. package/lib/utils/profiler.js +0 -53
  331. package/lib/utils/rtti.js +0 -44
  332. package/lib/utils/semaphore.js +0 -51
  333. package/lib/utils/spawnAsync.js +0 -45
  334. package/lib/utils/stackTrace.js +0 -121
  335. package/lib/utils/task.js +0 -58
  336. package/lib/utils/time.js +0 -37
  337. package/lib/utils/timeoutRunner.js +0 -66
  338. package/lib/utils/traceUtils.js +0 -44
  339. package/lib/utils/userAgent.js +0 -105
  340. package/lib/utils/wsServer.js +0 -127
  341. package/lib/utils/zipFile.js +0 -75
  342. package/lib/utils/zones.js +0 -62
  343. package/lib/vite/htmlReport/index.html +0 -69
  344. package/lib/vite/recorder/assets/codeMirrorModule-B9YMkrwa.js +0 -24
  345. package/lib/vite/recorder/assets/codeMirrorModule-C3UTv-Ge.css +0 -1
  346. package/lib/vite/recorder/assets/codicon-DCmgc-ay.ttf +0 -0
  347. package/lib/vite/recorder/assets/index-ELPgmkwA.js +0 -184
  348. package/lib/vite/recorder/assets/index-eHBmevrY.css +0 -1
  349. package/lib/vite/recorder/index.html +0 -29
  350. package/lib/vite/recorder/playwright-logo.svg +0 -9
  351. package/lib/vite/traceViewer/assets/codeMirrorModule-gU1OOCQO.js +0 -24
  352. package/lib/vite/traceViewer/assets/defaultSettingsView-B5n_FjMx.js +0 -1
  353. package/lib/vite/traceViewer/assets/inspectorTab-6Tru8Mn_.js +0 -235
  354. package/lib/vite/traceViewer/assets/workbench-B_Nj4NA2.js +0 -25
  355. package/lib/vite/traceViewer/assets/xtermModule-BoAIEibi.js +0 -9
  356. package/lib/vite/traceViewer/codeMirrorModule.C3UTv-Ge.css +0 -1
  357. package/lib/vite/traceViewer/codicon.DCmgc-ay.ttf +0 -0
  358. package/lib/vite/traceViewer/defaultSettingsView.CO3FR0CX.css +0 -1
  359. package/lib/vite/traceViewer/embedded.DpNPH6mk.js +0 -2
  360. package/lib/vite/traceViewer/embedded.html +0 -18
  361. package/lib/vite/traceViewer/embedded.mLhjB5IF.css +0 -1
  362. package/lib/vite/traceViewer/index.CFOW-Ezb.css +0 -1
  363. package/lib/vite/traceViewer/index.CuE3SYGw.js +0 -2
  364. package/lib/vite/traceViewer/index.html +0 -47
  365. package/lib/vite/traceViewer/inspectorTab.CXDulcFG.css +0 -1
  366. package/lib/vite/traceViewer/playwright-logo.svg +0 -9
  367. package/lib/vite/traceViewer/recorder.BD-uZJs7.js +0 -2
  368. package/lib/vite/traceViewer/recorder.html +0 -17
  369. package/lib/vite/traceViewer/recorder.tn0RQdqM.css +0 -0
  370. package/lib/vite/traceViewer/snapshot.html +0 -21
  371. package/lib/vite/traceViewer/sw.bundle.js +0 -3
  372. package/lib/vite/traceViewer/uiMode.BatfzHMG.css +0 -1
  373. package/lib/vite/traceViewer/uiMode.DHrNgddz.js +0 -5
  374. package/lib/vite/traceViewer/uiMode.html +0 -21
  375. package/lib/vite/traceViewer/workbench.B9vIAzH9.css +0 -1
  376. package/lib/vite/traceViewer/xtermModule.Beg8tuEN.css +0 -32
@@ -1,320 +1,321 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var page_exports = {};
30
+ __export(page_exports, {
31
+ InitScript: () => InitScript,
32
+ Page: () => Page,
33
+ PageBinding: () => PageBinding,
34
+ Worker: () => Worker
5
35
  });
6
- exports.Worker = exports.PageBinding = exports.Page = exports.InitScript = void 0;
7
- var accessibility = _interopRequireWildcard(require("./accessibility"));
8
- var _browserContext = require("./browserContext");
9
- var _console = require("./console");
10
- var _errors = require("./errors");
11
- var _fileChooser = require("./fileChooser");
12
- var frames = _interopRequireWildcard(require("./frames"));
13
- var _helper = require("./helper");
14
- var input = _interopRequireWildcard(require("./input"));
15
- var _instrumentation = require("./instrumentation");
16
- var _utilityScriptSerializers = require("./isomorphic/utilityScriptSerializers");
17
- var js = _interopRequireWildcard(require("./javascript"));
18
- var _progress = require("./progress");
19
- var _screenshotter = require("./screenshotter");
20
- var _timeoutSettings = require("./timeoutSettings");
21
- var _utils = require("../utils");
22
- var _crypto = require("./utils/crypto");
23
- var _comparators = require("./utils/comparators");
24
- var _debugLogger = require("./utils/debugLogger");
25
- var _selectorParser = require("../utils/isomorphic/selectorParser");
26
- var _manualPromise = require("../utils/isomorphic/manualPromise");
27
- var _callLog = require("./callLog");
28
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
29
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
30
- /**
31
- * Copyright 2017 Google Inc. All rights reserved.
32
- * Modifications copyright (c) Microsoft Corporation.
33
- *
34
- * Licensed under the Apache License, Version 2.0 (the "License");
35
- * you may not use this file except in compliance with the License.
36
- * You may obtain a copy of the License at
37
- *
38
- * http://www.apache.org/licenses/LICENSE-2.0
39
- *
40
- * Unless required by applicable law or agreed to in writing, software
41
- * distributed under the License is distributed on an "AS IS" BASIS,
42
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
43
- * See the License for the specific language governing permissions and
44
- * limitations under the License.
45
- */
46
-
47
- class Page extends _instrumentation.SdkObject {
36
+ module.exports = __toCommonJS(page_exports);
37
+ var accessibility = __toESM(require("./accessibility"));
38
+ var import_browserContext = require("./browserContext");
39
+ var import_console = require("./console");
40
+ var import_errors = require("./errors");
41
+ var import_fileChooser = require("./fileChooser");
42
+ var frames = __toESM(require("./frames"));
43
+ var import_helper = require("./helper");
44
+ var input = __toESM(require("./input"));
45
+ var import_instrumentation = require("./instrumentation");
46
+ var js = __toESM(require("./javascript"));
47
+ var import_screenshotter = require("./screenshotter");
48
+ var import_utils = require("../utils");
49
+ var import_utils2 = require("../utils");
50
+ var import_comparators = require("./utils/comparators");
51
+ var import_debugLogger = require("./utils/debugLogger");
52
+ var import_selectorParser = require("../utils/isomorphic/selectorParser");
53
+ var import_manualPromise = require("../utils/isomorphic/manualPromise");
54
+ var import_utilityScriptSerializers = require("../utils/isomorphic/utilityScriptSerializers");
55
+ var import_callLog = require("./callLog");
56
+ var rawBindingsControllerSource = __toESM(require("../generated/bindingsControllerSource"));
57
+ class Page extends import_instrumentation.SdkObject {
48
58
  constructor(delegate, browserContext) {
49
- super(browserContext, 'page');
50
- this._closedState = 'open';
51
- this._closedPromise = new _manualPromise.ManualPromise();
52
- this._initialized = void 0;
53
- this._initializedPromise = new _manualPromise.ManualPromise();
59
+ super(browserContext, "page");
60
+ this._closedState = "open";
61
+ this._closedPromise = new import_manualPromise.ManualPromise();
62
+ this._initializedPromise = new import_manualPromise.ManualPromise();
54
63
  this._eventsToEmitAfterInitialized = [];
55
64
  this._crashed = false;
56
- this.openScope = new _utils.LongStandingScope();
57
- this._browserContext = void 0;
58
- this.keyboard = void 0;
59
- this.mouse = void 0;
60
- this.touchscreen = void 0;
61
- this._timeoutSettings = void 0;
62
- this._delegate = void 0;
63
- this._emulatedSize = void 0;
64
- this._extraHTTPHeaders = void 0;
65
+ this.openScope = new import_utils.LongStandingScope();
65
66
  this._emulatedMedia = {};
66
- this._interceptFileChooser = false;
67
- this._pageBindings = new Map();
67
+ this._fileChooserInterceptedBy = /* @__PURE__ */ new Set();
68
+ this._pageBindings = /* @__PURE__ */ new Map();
68
69
  this.initScripts = [];
69
- this._screenshotter = void 0;
70
- this._frameManager = void 0;
71
- this.accessibility = void 0;
72
- this._workers = new Map();
73
- this.pdf = void 0;
74
- this.coverage = void 0;
75
- this._clientRequestInterceptor = void 0;
76
- this._serverRequestInterceptor = void 0;
77
- this._ownedContext = void 0;
78
- this._video = null;
79
- this._opener = void 0;
70
+ this._workers = /* @__PURE__ */ new Map();
71
+ this.requestInterceptors = [];
72
+ this.video = null;
80
73
  this._isServerSideOnly = false;
81
- this._locatorHandlers = new Map();
74
+ this._locatorHandlers = /* @__PURE__ */ new Map();
82
75
  this._lastLocatorHandlerUid = 0;
83
76
  this._locatorHandlerRunningCounter = 0;
84
77
  // Aiming at 25 fps by default - each frame is 40ms, but we give some slack with 35ms.
85
78
  // When throttling for tracing, 200ms between frames, except for 10 frames around the action.
86
79
  this._frameThrottler = new FrameThrottler(10, 35, 200);
87
- this._closeReason = void 0;
80
+ this.lastSnapshotFrameIds = [];
88
81
  this.attribution.page = this;
89
- this._delegate = delegate;
90
- this._browserContext = browserContext;
82
+ this.delegate = delegate;
83
+ this.browserContext = browserContext;
91
84
  this.accessibility = new accessibility.Accessibility(delegate.getAccessibilityTree.bind(delegate));
92
- this.keyboard = new input.Keyboard(delegate.rawKeyboard);
85
+ this.keyboard = new input.Keyboard(delegate.rawKeyboard, this);
93
86
  this.mouse = new input.Mouse(delegate.rawMouse, this);
94
87
  this.touchscreen = new input.Touchscreen(delegate.rawTouchscreen, this);
95
- this._timeoutSettings = new _timeoutSettings.TimeoutSettings(browserContext._timeoutSettings);
96
- this._screenshotter = new _screenshotter.Screenshotter(this);
97
- this._frameManager = new frames.FrameManager(this);
98
- if (delegate.pdf) this.pdf = delegate.pdf.bind(delegate);
88
+ this.screenshotter = new import_screenshotter.Screenshotter(this);
89
+ this.frameManager = new frames.FrameManager(this);
90
+ if (delegate.pdf)
91
+ this.pdf = delegate.pdf.bind(delegate);
99
92
  this.coverage = delegate.coverage ? delegate.coverage() : null;
100
93
  }
101
- async reportAsNew(opener, error = undefined, contextEvent = _browserContext.BrowserContext.Events.Page) {
94
+ static {
95
+ this.Events = {
96
+ Close: "close",
97
+ Crash: "crash",
98
+ Download: "download",
99
+ EmulatedSizeChanged: "emulatedsizechanged",
100
+ FileChooser: "filechooser",
101
+ FrameAttached: "frameattached",
102
+ FrameDetached: "framedetached",
103
+ InternalFrameNavigatedToNewDocument: "internalframenavigatedtonewdocument",
104
+ LocatorHandlerTriggered: "locatorhandlertriggered",
105
+ ScreencastFrame: "screencastframe",
106
+ Video: "video",
107
+ WebSocket: "websocket",
108
+ Worker: "worker"
109
+ };
110
+ }
111
+ async reportAsNew(opener, error = void 0, contextEvent = import_browserContext.BrowserContext.Events.Page) {
102
112
  if (opener) {
103
113
  const openerPageOrError = await opener.waitForInitializedOrError();
104
- if (openerPageOrError instanceof Page && !openerPageOrError.isClosed()) this._opener = openerPageOrError;
114
+ if (openerPageOrError instanceof Page && !openerPageOrError.isClosed())
115
+ this._opener = openerPageOrError;
105
116
  }
106
117
  this._markInitialized(error, contextEvent);
107
118
  }
108
- _markInitialized(error = undefined, contextEvent = _browserContext.BrowserContext.Events.Page) {
119
+ _markInitialized(error = void 0, contextEvent = import_browserContext.BrowserContext.Events.Page) {
109
120
  if (error) {
110
- // Initialization error could have happened because of
111
- // context/browser closure. Just ignore the page.
112
- if (this._browserContext.isClosingOrClosed()) return;
113
- this._frameManager.createDummyMainFrameIfNeeded();
121
+ if (this.browserContext.isClosingOrClosed())
122
+ return;
123
+ this.frameManager.createDummyMainFrameIfNeeded();
114
124
  }
115
125
  this._initialized = error || this;
116
126
  this.emitOnContext(contextEvent, this);
117
- for (const {
118
- event,
119
- args
120
- } of this._eventsToEmitAfterInitialized) this._browserContext.emit(event, ...args);
127
+ for (const { event, args } of this._eventsToEmitAfterInitialized)
128
+ this.browserContext.emit(event, ...args);
121
129
  this._eventsToEmitAfterInitialized = [];
122
-
123
- // It may happen that page initialization finishes after Close event has already been sent,
124
- // in that case we fire another Close event to ensure that each reported Page will have
125
- // corresponding Close event after it is reported on the context.
126
- if (this.isClosed()) this.emit(Page.Events.Close);else this.instrumentation.onPageOpen(this);
127
-
128
- // Note: it is important to resolve _initializedPromise at the end,
129
- // so that anyone who awaits waitForInitializedOrError got a ready and reported page.
130
+ if (this.isClosed())
131
+ this.emit(Page.Events.Close);
132
+ else
133
+ this.instrumentation.onPageOpen(this);
130
134
  this._initializedPromise.resolve(this._initialized);
131
135
  }
132
136
  initializedOrUndefined() {
133
- return this._initialized ? this : undefined;
137
+ return this._initialized ? this : void 0;
134
138
  }
135
139
  waitForInitializedOrError() {
136
140
  return this._initializedPromise;
137
141
  }
138
142
  emitOnContext(event, ...args) {
139
- if (this._isServerSideOnly) return;
140
- this._browserContext.emit(event, ...args);
143
+ if (this._isServerSideOnly)
144
+ return;
145
+ this.browserContext.emit(event, ...args);
141
146
  }
142
147
  emitOnContextOnceInitialized(event, ...args) {
143
- if (this._isServerSideOnly) return;
144
- // Some events, like console messages, may come before page is ready.
145
- // In this case, postpone the event until page is initialized,
146
- // and dispatch it to the client later, either on the live Page,
147
- // or on the "errored" Page.
148
- if (this._initialized) this._browserContext.emit(event, ...args);else this._eventsToEmitAfterInitialized.push({
149
- event,
150
- args
151
- });
148
+ if (this._isServerSideOnly)
149
+ return;
150
+ if (this._initialized)
151
+ this.browserContext.emit(event, ...args);
152
+ else
153
+ this._eventsToEmitAfterInitialized.push({ event, args });
152
154
  }
153
- async resetForReuse(metadata) {
154
- this.setDefaultNavigationTimeout(undefined);
155
- this.setDefaultTimeout(undefined);
156
- this._locatorHandlers.clear();
157
- await this._removeExposedBindings();
158
- await this._removeInitScripts();
159
- await this.setClientRequestInterceptor(undefined);
160
- await this._setServerRequestInterceptor(undefined);
161
- await this.setFileChooserIntercepted(false);
162
- // Re-navigate once init scripts are gone.
163
- await this.mainFrame().goto(metadata, 'about:blank');
164
- this._emulatedSize = undefined;
155
+ async resetForReuse(progress) {
156
+ await this.mainFrame().gotoImpl(progress, "about:blank", {});
157
+ this._emulatedSize = void 0;
165
158
  this._emulatedMedia = {};
166
- this._extraHTTPHeaders = undefined;
167
- this._interceptFileChooser = false;
168
- await Promise.all([this._delegate.updateEmulatedViewportSize(), this._delegate.updateEmulateMedia(), this._delegate.updateFileChooserInterception()]);
169
- await this._delegate.resetForReuse();
159
+ this._extraHTTPHeaders = void 0;
160
+ await Promise.all([
161
+ this.delegate.updateEmulatedViewportSize(),
162
+ this.delegate.updateEmulateMedia(),
163
+ this.delegate.updateExtraHTTPHeaders()
164
+ ]);
165
+ await this.delegate.resetForReuse(progress);
170
166
  }
171
167
  _didClose() {
172
- this._frameManager.dispose();
168
+ this.frameManager.dispose();
173
169
  this._frameThrottler.dispose();
174
- (0, _utils.assert)(this._closedState !== 'closed', 'Page closed twice');
175
- this._closedState = 'closed';
170
+ (0, import_utils.assert)(this._closedState !== "closed", "Page closed twice");
171
+ this._closedState = "closed";
176
172
  this.emit(Page.Events.Close);
177
173
  this._closedPromise.resolve();
178
174
  this.instrumentation.onPageClose(this);
179
- this.openScope.close(new _errors.TargetClosedError());
175
+ this.openScope.close(new import_errors.TargetClosedError());
180
176
  }
181
177
  _didCrash() {
182
- this._frameManager.dispose();
178
+ this.frameManager.dispose();
183
179
  this._frameThrottler.dispose();
184
180
  this.emit(Page.Events.Crash);
185
181
  this._crashed = true;
186
182
  this.instrumentation.onPageClose(this);
187
- this.openScope.close(new Error('Page crashed'));
183
+ this.openScope.close(new Error("Page crashed"));
188
184
  }
189
185
  async _onFileChooserOpened(handle) {
190
186
  let multiple;
191
187
  try {
192
- multiple = await handle.evaluate(element => !!element.multiple);
188
+ multiple = await handle.evaluate((element) => !!element.multiple);
193
189
  } catch (e) {
194
- // Frame/context may be gone during async processing. Do not throw.
195
190
  return;
196
191
  }
197
192
  if (!this.listenerCount(Page.Events.FileChooser)) {
198
193
  handle.dispose();
199
194
  return;
200
195
  }
201
- const fileChooser = new _fileChooser.FileChooser(this, handle, multiple);
196
+ const fileChooser = new import_fileChooser.FileChooser(this, handle, multiple);
202
197
  this.emit(Page.Events.FileChooser, fileChooser);
203
198
  }
204
- context() {
205
- return this._browserContext;
206
- }
207
199
  opener() {
208
200
  return this._opener;
209
201
  }
210
202
  mainFrame() {
211
- return this._frameManager.mainFrame();
203
+ return this.frameManager.mainFrame();
212
204
  }
213
205
  frames() {
214
- return this._frameManager.frames();
215
- }
216
- setDefaultNavigationTimeout(timeout) {
217
- this._timeoutSettings.setDefaultNavigationTimeout(timeout);
218
- }
219
- setDefaultTimeout(timeout) {
220
- this._timeoutSettings.setDefaultTimeout(timeout);
221
- }
222
- async exposeBinding(name, needsHandle, playwrightBinding) {
223
- if (this._pageBindings.has(name)) throw new Error(`Function "${name}" has been already registered`);
224
- if (this._browserContext._pageBindings.has(name)) throw new Error(`Function "${name}" has been already registered in the browser context`);
206
+ return this.frameManager.frames();
207
+ }
208
+ async exposeBinding(progress, name, needsHandle, playwrightBinding) {
209
+ if (this._pageBindings.has(name))
210
+ throw new Error(`Function "${name}" has been already registered`);
211
+ if (this.browserContext._pageBindings.has(name))
212
+ throw new Error(`Function "${name}" has been already registered in the browser context`);
213
+ await progress.race(this.browserContext.exposePlaywrightBindingIfNeeded());
225
214
  const binding = new PageBinding(name, playwrightBinding, needsHandle);
226
215
  this._pageBindings.set(name, binding);
227
- await this._delegate.addInitScript(binding.initScript);
228
- await Promise.all(this.frames().map(frame => frame.evaluateExpression(binding.initScript.source).catch(e => {})));
229
- }
230
- async _removeExposedBindings() {
231
- for (const [key, binding] of this._pageBindings) {
232
- if (!binding.internal) this._pageBindings.delete(key);
233
- }
234
- }
235
- setExtraHTTPHeaders(headers) {
216
+ progress.cleanupWhenAborted(() => this._pageBindings.delete(name));
217
+ await progress.race(this.delegate.addInitScript(binding.initScript));
218
+ await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, "main"));
219
+ return binding;
220
+ }
221
+ async removeExposedBindings(bindings) {
222
+ bindings = bindings.filter((binding) => this._pageBindings.get(binding.name) === binding);
223
+ for (const binding of bindings)
224
+ this._pageBindings.delete(binding.name);
225
+ await this.delegate.removeInitScripts(bindings.map((binding) => binding.initScript));
226
+ const cleanup = bindings.map((binding) => `{ ${binding.cleanupScript} };
227
+ `).join("");
228
+ await this.safeNonStallingEvaluateInAllFrames(cleanup, "main");
229
+ }
230
+ async setExtraHTTPHeaders(progress, headers) {
231
+ const oldHeaders = this._extraHTTPHeaders;
236
232
  this._extraHTTPHeaders = headers;
237
- return this._delegate.updateExtraHTTPHeaders();
233
+ progress.cleanupWhenAborted(async () => {
234
+ this._extraHTTPHeaders = oldHeaders;
235
+ await this.delegate.updateExtraHTTPHeaders();
236
+ });
237
+ await progress.race(this.delegate.updateExtraHTTPHeaders());
238
238
  }
239
239
  extraHTTPHeaders() {
240
240
  return this._extraHTTPHeaders;
241
241
  }
242
- async _onBindingCalled(payload, context) {
243
- if (this._closedState === 'closed') return;
242
+ async onBindingCalled(payload, context) {
243
+ if (this._closedState === "closed")
244
+ return;
244
245
  await PageBinding.dispatch(this, payload, context);
245
246
  }
246
- _addConsoleMessage(type, args, location, text) {
247
- const message = new _console.ConsoleMessage(this, type, text, args, location);
248
- const intercepted = this._frameManager.interceptConsoleMessage(message);
247
+ addConsoleMessage(type, args, location, text) {
248
+ const message = new import_console.ConsoleMessage(this, type, text, args, location);
249
+ const intercepted = this.frameManager.interceptConsoleMessage(message);
249
250
  if (intercepted) {
250
- args.forEach(arg => arg.dispose());
251
+ args.forEach((arg) => arg.dispose());
251
252
  return;
252
253
  }
253
- this.emitOnContextOnceInitialized(_browserContext.BrowserContext.Events.Console, message);
254
+ this.emitOnContextOnceInitialized(import_browserContext.BrowserContext.Events.Console, message);
254
255
  }
255
- async reload(metadata, options) {
256
- const controller = new _progress.ProgressController(metadata, this);
257
- return controller.run(progress => this.mainFrame().raceNavigationAction(progress, options, async () => {
258
- // Note: waitForNavigation may fail before we get response to reload(),
259
- // so we should await it immediately.
256
+ async reload(progress, options) {
257
+ return this.mainFrame().raceNavigationAction(progress, async () => {
260
258
  const [response] = await Promise.all([
261
- // Reload must be a new document, and should not be confused with a stray pushState.
262
- this.mainFrame()._waitForNavigation(progress, true /* requiresNewDocument */, options), this._delegate.reload()]);
259
+ // Reload must be a new document, and should not be confused with a stray pushState.
260
+ this.mainFrame()._waitForNavigation(progress, true, options),
261
+ progress.race(this.delegate.reload())
262
+ ]);
263
263
  return response;
264
- }), this._timeoutSettings.navigationTimeout(options));
264
+ });
265
265
  }
266
- async goBack(metadata, options) {
267
- const controller = new _progress.ProgressController(metadata, this);
268
- return controller.run(progress => this.mainFrame().raceNavigationAction(progress, options, async () => {
269
- // Note: waitForNavigation may fail before we get response to goBack,
270
- // so we should catch it immediately.
266
+ async goBack(progress, options) {
267
+ return this.mainFrame().raceNavigationAction(progress, async () => {
271
268
  let error;
272
- const waitPromise = this.mainFrame()._waitForNavigation(progress, false /* requiresNewDocument */, options).catch(e => {
269
+ const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {
273
270
  error = e;
274
271
  return null;
275
272
  });
276
- const result = await this._delegate.goBack();
277
- if (!result) return null;
273
+ const result = await progress.race(this.delegate.goBack());
274
+ if (!result) {
275
+ waitPromise.catch(() => {
276
+ });
277
+ return null;
278
+ }
278
279
  const response = await waitPromise;
279
- if (error) throw error;
280
+ if (error)
281
+ throw error;
280
282
  return response;
281
- }), this._timeoutSettings.navigationTimeout(options));
283
+ });
282
284
  }
283
- async goForward(metadata, options) {
284
- const controller = new _progress.ProgressController(metadata, this);
285
- return controller.run(progress => this.mainFrame().raceNavigationAction(progress, options, async () => {
286
- // Note: waitForNavigation may fail before we get response to goForward,
287
- // so we should catch it immediately.
285
+ async goForward(progress, options) {
286
+ return this.mainFrame().raceNavigationAction(progress, async () => {
288
287
  let error;
289
- const waitPromise = this.mainFrame()._waitForNavigation(progress, false /* requiresNewDocument */, options).catch(e => {
288
+ const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {
290
289
  error = e;
291
290
  return null;
292
291
  });
293
- const result = await this._delegate.goForward();
294
- if (!result) return null;
292
+ const result = await progress.race(this.delegate.goForward());
293
+ if (!result) {
294
+ waitPromise.catch(() => {
295
+ });
296
+ return null;
297
+ }
295
298
  const response = await waitPromise;
296
- if (error) throw error;
299
+ if (error)
300
+ throw error;
297
301
  return response;
298
- }), this._timeoutSettings.navigationTimeout(options));
302
+ });
299
303
  }
300
304
  requestGC() {
301
- return this._delegate.requestGC();
305
+ return this.delegate.requestGC();
302
306
  }
303
307
  registerLocatorHandler(selector, noWaitAfter) {
304
308
  const uid = ++this._lastLocatorHandlerUid;
305
- this._locatorHandlers.set(uid, {
306
- selector,
307
- noWaitAfter
308
- });
309
+ this._locatorHandlers.set(uid, { selector, noWaitAfter });
309
310
  return uid;
310
311
  }
311
312
  resolveLocatorHandler(uid, remove) {
312
313
  const handler = this._locatorHandlers.get(uid);
313
- if (remove) this._locatorHandlers.delete(uid);
314
+ if (remove)
315
+ this._locatorHandlers.delete(uid);
314
316
  if (handler) {
315
- var _handler$resolved;
316
- (_handler$resolved = handler.resolved) === null || _handler$resolved === void 0 || _handler$resolved.resolve();
317
- handler.resolved = undefined;
317
+ handler.resolved?.resolve();
318
+ handler.resolved = void 0;
318
319
  }
319
320
  }
320
321
  unregisterLocatorHandler(uid) {
@@ -322,502 +323,418 @@ class Page extends _instrumentation.SdkObject {
322
323
  }
323
324
  async performActionPreChecks(progress) {
324
325
  await this._performWaitForNavigationCheck(progress);
325
- progress.throwIfAborted();
326
326
  await this._performLocatorHandlersCheckpoint(progress);
327
- progress.throwIfAborted();
328
- // Wait once again, just in case a locator handler caused a navigation.
329
327
  await this._performWaitForNavigationCheck(progress);
330
328
  }
331
329
  async _performWaitForNavigationCheck(progress) {
332
- var _mainFrame$pendingDoc;
333
- if (process.env.PLAYWRIGHT_SKIP_NAVIGATION_CHECK) return;
334
- const mainFrame = this._frameManager.mainFrame();
335
- if (!mainFrame || !mainFrame.pendingDocument()) return;
336
- const url = (_mainFrame$pendingDoc = mainFrame.pendingDocument()) === null || _mainFrame$pendingDoc === void 0 || (_mainFrame$pendingDoc = _mainFrame$pendingDoc.request) === null || _mainFrame$pendingDoc === void 0 ? void 0 : _mainFrame$pendingDoc.url();
337
- const toUrl = url ? `" ${(0, _utils.trimStringWithEllipsis)(url, 200)}"` : '';
330
+ const mainFrame = this.frameManager.mainFrame();
331
+ if (!mainFrame || !mainFrame.pendingDocument())
332
+ return;
333
+ const url = mainFrame.pendingDocument()?.request?.url();
334
+ const toUrl = url ? `" ${(0, import_utils.trimStringWithEllipsis)(url, 200)}"` : "";
338
335
  progress.log(` waiting for${toUrl} navigation to finish...`);
339
- await _helper.helper.waitForEvent(progress, mainFrame, frames.Frame.Events.InternalNavigation, e => {
340
- if (!e.isPublic) return false;
341
- if (!e.error) progress.log(` navigated to "${(0, _utils.trimStringWithEllipsis)(mainFrame.url(), 200)}"`);
336
+ await import_helper.helper.waitForEvent(progress, mainFrame, frames.Frame.Events.InternalNavigation, (e) => {
337
+ if (!e.isPublic)
338
+ return false;
339
+ if (!e.error)
340
+ progress.log(` navigated to "${(0, import_utils.trimStringWithEllipsis)(mainFrame.url(), 200)}"`);
342
341
  return true;
343
342
  }).promise;
344
343
  }
345
344
  async _performLocatorHandlersCheckpoint(progress) {
346
- // Do not run locator handlers from inside locator handler callbacks to avoid deadlocks.
347
- if (this._locatorHandlerRunningCounter) return;
345
+ if (this._locatorHandlerRunningCounter)
346
+ return;
348
347
  for (const [uid, handler] of this._locatorHandlers) {
349
348
  if (!handler.resolved) {
350
- if (await this.mainFrame().isVisibleInternal(handler.selector, {
351
- strict: true
352
- })) {
353
- handler.resolved = new _manualPromise.ManualPromise();
349
+ if (await this.mainFrame().isVisibleInternal(progress, handler.selector, { strict: true })) {
350
+ handler.resolved = new import_manualPromise.ManualPromise();
354
351
  this.emit(Page.Events.LocatorHandlerTriggered, uid);
355
352
  }
356
353
  }
357
354
  if (handler.resolved) {
358
355
  ++this._locatorHandlerRunningCounter;
359
- progress.log(` found ${(0, _utils.asLocator)(this.attribution.playwright.options.sdkLanguage, handler.selector)}, intercepting action to run the handler`);
356
+ progress.log(` found ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)}, intercepting action to run the handler`);
360
357
  const promise = handler.resolved.then(async () => {
361
- progress.throwIfAborted();
362
358
  if (!handler.noWaitAfter) {
363
- progress.log(` locator handler has finished, waiting for ${(0, _utils.asLocator)(this.attribution.playwright.options.sdkLanguage, handler.selector)} to be hidden`);
364
- await this.mainFrame().waitForSelectorInternal(progress, handler.selector, false, {
365
- state: 'hidden'
366
- });
359
+ progress.log(` locator handler has finished, waiting for ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)} to be hidden`);
360
+ await this.mainFrame().waitForSelector(progress, handler.selector, false, { state: "hidden" });
367
361
  } else {
368
362
  progress.log(` locator handler has finished`);
369
363
  }
370
364
  });
371
- await this.openScope.race(promise).finally(() => --this._locatorHandlerRunningCounter);
372
- // Avoid side-effects after long-running operation.
373
- progress.throwIfAborted();
365
+ await progress.race(this.openScope.race(promise)).finally(() => --this._locatorHandlerRunningCounter);
374
366
  progress.log(` interception handler has finished, continuing`);
375
367
  }
376
368
  }
377
369
  }
378
- async emulateMedia(options) {
379
- if (options.media !== undefined) this._emulatedMedia.media = options.media;
380
- if (options.colorScheme !== undefined) this._emulatedMedia.colorScheme = options.colorScheme;
381
- if (options.reducedMotion !== undefined) this._emulatedMedia.reducedMotion = options.reducedMotion;
382
- if (options.forcedColors !== undefined) this._emulatedMedia.forcedColors = options.forcedColors;
383
- if (options.contrast !== undefined) this._emulatedMedia.contrast = options.contrast;
384
- await this._delegate.updateEmulateMedia();
370
+ async emulateMedia(progress, options) {
371
+ const oldEmulatedMedia = { ...this._emulatedMedia };
372
+ progress.cleanupWhenAborted(async () => {
373
+ this._emulatedMedia = oldEmulatedMedia;
374
+ await this.delegate.updateEmulateMedia();
375
+ });
376
+ if (options.media !== void 0)
377
+ this._emulatedMedia.media = options.media;
378
+ if (options.colorScheme !== void 0)
379
+ this._emulatedMedia.colorScheme = options.colorScheme;
380
+ if (options.reducedMotion !== void 0)
381
+ this._emulatedMedia.reducedMotion = options.reducedMotion;
382
+ if (options.forcedColors !== void 0)
383
+ this._emulatedMedia.forcedColors = options.forcedColors;
384
+ if (options.contrast !== void 0)
385
+ this._emulatedMedia.contrast = options.contrast;
386
+ await progress.race(this.delegate.updateEmulateMedia());
385
387
  }
386
388
  emulatedMedia() {
387
- var _contextOptions$color, _contextOptions$reduc, _contextOptions$force, _contextOptions$contr;
388
- const contextOptions = this._browserContext._options;
389
+ const contextOptions = this.browserContext._options;
389
390
  return {
390
- media: this._emulatedMedia.media || 'no-override',
391
- colorScheme: this._emulatedMedia.colorScheme !== undefined ? this._emulatedMedia.colorScheme : (_contextOptions$color = contextOptions.colorScheme) !== null && _contextOptions$color !== void 0 ? _contextOptions$color : 'light',
392
- reducedMotion: this._emulatedMedia.reducedMotion !== undefined ? this._emulatedMedia.reducedMotion : (_contextOptions$reduc = contextOptions.reducedMotion) !== null && _contextOptions$reduc !== void 0 ? _contextOptions$reduc : 'no-preference',
393
- forcedColors: this._emulatedMedia.forcedColors !== undefined ? this._emulatedMedia.forcedColors : (_contextOptions$force = contextOptions.forcedColors) !== null && _contextOptions$force !== void 0 ? _contextOptions$force : 'none',
394
- contrast: this._emulatedMedia.contrast !== undefined ? this._emulatedMedia.contrast : (_contextOptions$contr = contextOptions.contrast) !== null && _contextOptions$contr !== void 0 ? _contextOptions$contr : 'no-preference'
391
+ media: this._emulatedMedia.media || "no-override",
392
+ colorScheme: this._emulatedMedia.colorScheme !== void 0 ? this._emulatedMedia.colorScheme : contextOptions.colorScheme ?? "light",
393
+ reducedMotion: this._emulatedMedia.reducedMotion !== void 0 ? this._emulatedMedia.reducedMotion : contextOptions.reducedMotion ?? "no-preference",
394
+ forcedColors: this._emulatedMedia.forcedColors !== void 0 ? this._emulatedMedia.forcedColors : contextOptions.forcedColors ?? "none",
395
+ contrast: this._emulatedMedia.contrast !== void 0 ? this._emulatedMedia.contrast : contextOptions.contrast ?? "no-preference"
395
396
  };
396
397
  }
397
- async setViewportSize(viewportSize) {
398
- this._emulatedSize = {
399
- viewport: {
400
- ...viewportSize
401
- },
402
- screen: {
403
- ...viewportSize
404
- }
405
- };
406
- await this._delegate.updateEmulatedViewportSize();
398
+ async setViewportSize(progress, viewportSize) {
399
+ const oldEmulatedSize = this._emulatedSize;
400
+ progress.cleanupWhenAborted(async () => {
401
+ this._emulatedSize = oldEmulatedSize;
402
+ await this.delegate.updateEmulatedViewportSize();
403
+ });
404
+ this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } });
405
+ await progress.race(this.delegate.updateEmulatedViewportSize());
406
+ }
407
+ setEmulatedSizeFromWindowOpen(emulatedSize) {
408
+ this._setEmulatedSize(emulatedSize);
407
409
  }
408
- viewportSize() {
409
- var _this$emulatedSize;
410
- return ((_this$emulatedSize = this.emulatedSize()) === null || _this$emulatedSize === void 0 ? void 0 : _this$emulatedSize.viewport) || null;
410
+ _setEmulatedSize(emulatedSize) {
411
+ this._emulatedSize = emulatedSize;
412
+ this.emit(Page.Events.EmulatedSizeChanged);
411
413
  }
412
414
  emulatedSize() {
413
- if (this._emulatedSize) return this._emulatedSize;
414
- const contextOptions = this._browserContext._options;
415
- return contextOptions.viewport ? {
416
- viewport: contextOptions.viewport,
417
- screen: contextOptions.screen || contextOptions.viewport
418
- } : null;
415
+ if (this._emulatedSize)
416
+ return this._emulatedSize;
417
+ const contextOptions = this.browserContext._options;
418
+ return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : void 0;
419
419
  }
420
420
  async bringToFront() {
421
- await this._delegate.bringToFront();
421
+ await this.delegate.bringToFront();
422
422
  }
423
- async addInitScript(source, name) {
424
- const initScript = new InitScript(source, false /* internal */, name);
423
+ async addInitScript(progress, source) {
424
+ const initScript = new InitScript(source);
425
425
  this.initScripts.push(initScript);
426
- await this._delegate.addInitScript(initScript);
426
+ progress.cleanupWhenAborted(() => this.removeInitScripts([initScript]));
427
+ await progress.race(this.delegate.addInitScript(initScript));
428
+ return initScript;
427
429
  }
428
- async _removeInitScripts() {
429
- this.initScripts = this.initScripts.filter(script => script.internal);
430
- await this._delegate.removeNonInternalInitScripts();
430
+ async removeInitScripts(initScripts) {
431
+ const set = new Set(initScripts);
432
+ this.initScripts = this.initScripts.filter((script) => !set.has(script));
433
+ await this.delegate.removeInitScripts(initScripts);
431
434
  }
432
435
  needsRequestInterception() {
433
- return !!this._clientRequestInterceptor || !!this._serverRequestInterceptor || !!this._browserContext._requestInterceptor;
434
- }
435
- async setClientRequestInterceptor(handler) {
436
- this._clientRequestInterceptor = handler;
437
- await this._delegate.updateRequestInterception();
438
- }
439
- async _setServerRequestInterceptor(handler) {
440
- this._serverRequestInterceptor = handler;
441
- await this._delegate.updateRequestInterception();
436
+ return this.requestInterceptors.length > 0 || this.browserContext.requestInterceptors.length > 0;
437
+ }
438
+ async addRequestInterceptor(progress, handler, prepend) {
439
+ if (prepend)
440
+ this.requestInterceptors.unshift(handler);
441
+ else
442
+ this.requestInterceptors.push(handler);
443
+ await this.delegate.updateRequestInterception();
444
+ }
445
+ async removeRequestInterceptor(handler) {
446
+ const index = this.requestInterceptors.indexOf(handler);
447
+ if (index === -1)
448
+ return;
449
+ this.requestInterceptors.splice(index, 1);
450
+ await this.browserContext.notifyRoutesInFlightAboutRemovedHandler(handler);
451
+ await this.delegate.updateRequestInterception();
442
452
  }
443
- async expectScreenshot(metadata, options = {}) {
453
+ async expectScreenshot(progress, options) {
444
454
  const locator = options.locator;
445
- const rafrafScreenshot = locator ? async (progress, timeout) => {
455
+ const rafrafScreenshot = locator ? async (timeout) => {
446
456
  return await locator.frame.rafrafTimeoutScreenshotElementWithProgress(progress, locator.selector, timeout, options || {});
447
- } : async (progress, timeout) => {
457
+ } : async (timeout) => {
448
458
  await this.performActionPreChecks(progress);
449
- await this.mainFrame().rafrafTimeout(timeout);
450
- return await this._screenshotter.screenshotPage(progress, options || {});
451
- };
452
- const comparator = (0, _comparators.getComparator)('image/png');
453
- const controller = new _progress.ProgressController(metadata, this);
454
- if (!options.expected && options.isNot) return {
455
- errorMessage: '"not" matcher requires expected result'
459
+ await this.mainFrame().rafrafTimeout(progress, timeout);
460
+ return await this.screenshotter.screenshotPage(progress, options || {});
456
461
  };
462
+ const comparator = (0, import_comparators.getComparator)("image/png");
463
+ if (!options.expected && options.isNot)
464
+ return { errorMessage: '"not" matcher requires expected result' };
457
465
  try {
458
- const format = (0, _screenshotter.validateScreenshotOptions)(options || {});
459
- if (format !== 'png') throw new Error('Only PNG screenshots are supported');
466
+ const format = (0, import_screenshotter.validateScreenshotOptions)(options || {});
467
+ if (format !== "png")
468
+ throw new Error("Only PNG screenshots are supported");
460
469
  } catch (error) {
461
- return {
462
- errorMessage: error.message
463
- };
470
+ return { errorMessage: error.message };
464
471
  }
465
- let intermediateResult = undefined;
472
+ let intermediateResult;
466
473
  const areEqualScreenshots = (actual, expected, previous) => {
467
- const comparatorResult = actual && expected ? comparator(actual, expected, options) : undefined;
468
- if (comparatorResult !== undefined && !!comparatorResult === !!options.isNot) return true;
469
- if (comparatorResult) intermediateResult = {
470
- errorMessage: comparatorResult.errorMessage,
471
- diff: comparatorResult.diff,
472
- actual,
473
- previous
474
- };
474
+ const comparatorResult = actual && expected ? comparator(actual, expected, options) : void 0;
475
+ if (comparatorResult !== void 0 && !!comparatorResult === !!options.isNot)
476
+ return true;
477
+ if (comparatorResult)
478
+ intermediateResult = { errorMessage: comparatorResult.errorMessage, diff: comparatorResult.diff, actual, previous };
475
479
  return false;
476
480
  };
477
- const callTimeout = this._timeoutSettings.timeout(options);
478
- return controller.run(async progress => {
481
+ const handleError = (e) => {
482
+ if (js.isJavaScriptErrorInEvaluate(e) || (0, import_selectorParser.isInvalidSelectorError)(e))
483
+ throw e;
484
+ let errorMessage = e.message;
485
+ if (e instanceof import_errors.TimeoutError && intermediateResult?.previous)
486
+ errorMessage = `Failed to take two consecutive stable screenshots.`;
487
+ return {
488
+ log: (0, import_callLog.compressCallLog)(e.message ? [...progress.metadata.log, e.message] : progress.metadata.log),
489
+ ...intermediateResult,
490
+ errorMessage,
491
+ timedOut: e instanceof import_errors.TimeoutError
492
+ };
493
+ };
494
+ progress.legacySetErrorHandler(handleError);
495
+ try {
479
496
  let actual;
480
497
  let previous;
481
498
  const pollIntervals = [0, 100, 250, 500];
482
- progress.log(`${metadata.apiName}${callTimeout ? ` with timeout ${callTimeout}ms` : ''}`);
483
- if (options.expected) progress.log(` verifying given screenshot expectation`);else progress.log(` generating new stable screenshot expectation`);
499
+ progress.log(`${(0, import_utils.renderTitleForCall)(progress.metadata)}${options.timeout ? ` with timeout ${options.timeout}ms` : ""}`);
500
+ if (options.expected)
501
+ progress.log(` verifying given screenshot expectation`);
502
+ else
503
+ progress.log(` generating new stable screenshot expectation`);
484
504
  let isFirstIteration = true;
485
505
  while (true) {
486
- var _pollIntervals$shift;
487
- progress.throwIfAborted();
488
- if (this.isClosed()) throw new Error('The page has closed');
489
- const screenshotTimeout = (_pollIntervals$shift = pollIntervals.shift()) !== null && _pollIntervals$shift !== void 0 ? _pollIntervals$shift : 1000;
490
- if (screenshotTimeout) progress.log(`waiting ${screenshotTimeout}ms before taking screenshot`);
506
+ if (this.isClosed())
507
+ throw new Error("The page has closed");
508
+ const screenshotTimeout = pollIntervals.shift() ?? 1e3;
509
+ if (screenshotTimeout)
510
+ progress.log(`waiting ${screenshotTimeout}ms before taking screenshot`);
491
511
  previous = actual;
492
- actual = await rafrafScreenshot(progress, screenshotTimeout).catch(e => {
512
+ actual = await rafrafScreenshot(screenshotTimeout).catch((e) => {
513
+ if (this.mainFrame().isNonRetriableError(e))
514
+ throw e;
493
515
  progress.log(`failed to take screenshot - ` + e.message);
494
- return undefined;
516
+ return void 0;
495
517
  });
496
- if (!actual) continue;
497
- // Compare against expectation for the first iteration.
518
+ if (!actual)
519
+ continue;
498
520
  const expectation = options.expected && isFirstIteration ? options.expected : previous;
499
- if (areEqualScreenshots(actual, expectation, previous)) break;
500
- if (intermediateResult) progress.log(intermediateResult.errorMessage);
521
+ if (areEqualScreenshots(actual, expectation, previous))
522
+ break;
523
+ if (intermediateResult)
524
+ progress.log(intermediateResult.errorMessage);
501
525
  isFirstIteration = false;
502
526
  }
503
- if (!isFirstIteration) progress.log(`captured a stable screenshot`);
504
- if (!options.expected) return {
505
- actual
506
- };
527
+ if (!isFirstIteration)
528
+ progress.log(`captured a stable screenshot`);
529
+ if (!options.expected)
530
+ return { actual };
507
531
  if (isFirstIteration) {
508
532
  progress.log(`screenshot matched expectation`);
509
533
  return {};
510
534
  }
511
- if (areEqualScreenshots(actual, options.expected, undefined)) {
535
+ if (areEqualScreenshots(actual, options.expected, void 0)) {
512
536
  progress.log(`screenshot matched expectation`);
513
537
  return {};
514
538
  }
515
539
  throw new Error(intermediateResult.errorMessage);
516
- }, callTimeout).catch(e => {
517
- var _intermediateResult;
518
- // Q: Why not throw upon isSessionClosedError(e) as in other places?
519
- // A: We want user to receive a friendly diff between actual and expected/previous.
520
- if (js.isJavaScriptErrorInEvaluate(e) || (0, _selectorParser.isInvalidSelectorError)(e)) throw e;
521
- let errorMessage = e.message;
522
- if (e instanceof _errors.TimeoutError && (_intermediateResult = intermediateResult) !== null && _intermediateResult !== void 0 && _intermediateResult.previous) errorMessage = `Failed to take two consecutive stable screenshots.`;
523
- return {
524
- log: (0, _callLog.compressCallLog)(e.message ? [...metadata.log, e.message] : metadata.log),
525
- ...intermediateResult,
526
- errorMessage,
527
- timedOut: e instanceof _errors.TimeoutError
528
- };
529
- });
540
+ } catch (e) {
541
+ return handleError(e);
542
+ }
530
543
  }
531
- async screenshot(metadata, options = {}) {
532
- const controller = new _progress.ProgressController(metadata, this);
533
- return controller.run(progress => this._screenshotter.screenshotPage(progress, options), this._timeoutSettings.timeout(options));
544
+ async screenshot(progress, options) {
545
+ return await this.screenshotter.screenshotPage(progress, options);
534
546
  }
535
- async close(metadata, options = {}) {
536
- if (this._closedState === 'closed') return;
537
- if (options.reason) this._closeReason = options.reason;
547
+ async close(options = {}) {
548
+ if (this._closedState === "closed")
549
+ return;
550
+ if (options.reason)
551
+ this.closeReason = options.reason;
538
552
  const runBeforeUnload = !!options.runBeforeUnload;
539
- if (this._closedState !== 'closing') {
540
- this._closedState = 'closing';
541
- // This might throw if the browser context containing the page closes
542
- // while we are trying to close the page.
543
- await this._delegate.closePage(runBeforeUnload).catch(e => _debugLogger.debugLogger.log('error', e));
553
+ if (this._closedState !== "closing") {
554
+ this._closedState = "closing";
555
+ await this.delegate.closePage(runBeforeUnload).catch((e) => import_debugLogger.debugLogger.log("error", e));
544
556
  }
545
- if (!runBeforeUnload) await this._closedPromise;
546
- if (this._ownedContext) await this._ownedContext.close(options);
557
+ if (!runBeforeUnload)
558
+ await this._closedPromise;
547
559
  }
548
560
  isClosed() {
549
- return this._closedState === 'closed';
561
+ return this._closedState === "closed";
550
562
  }
551
563
  hasCrashed() {
552
564
  return this._crashed;
553
565
  }
554
566
  isClosedOrClosingOrCrashed() {
555
- return this._closedState !== 'open' || this._crashed;
567
+ return this._closedState !== "open" || this._crashed;
556
568
  }
557
- _addWorker(workerId, worker) {
569
+ addWorker(workerId, worker) {
558
570
  this._workers.set(workerId, worker);
559
571
  this.emit(Page.Events.Worker, worker);
560
572
  }
561
- _removeWorker(workerId) {
573
+ removeWorker(workerId) {
562
574
  const worker = this._workers.get(workerId);
563
- if (!worker) return;
575
+ if (!worker)
576
+ return;
564
577
  worker.didClose();
565
578
  this._workers.delete(workerId);
566
579
  }
567
- _clearWorkers() {
580
+ clearWorkers() {
568
581
  for (const [workerId, worker] of this._workers) {
569
582
  worker.didClose();
570
583
  this._workers.delete(workerId);
571
584
  }
572
585
  }
573
- async setFileChooserIntercepted(enabled) {
574
- this._interceptFileChooser = enabled;
575
- await this._delegate.updateFileChooserInterception();
586
+ async setFileChooserInterceptedBy(enabled, by) {
587
+ const wasIntercepted = this.fileChooserIntercepted();
588
+ if (enabled)
589
+ this._fileChooserInterceptedBy.add(by);
590
+ else
591
+ this._fileChooserInterceptedBy.delete(by);
592
+ if (wasIntercepted !== this.fileChooserIntercepted())
593
+ await this.delegate.updateFileChooserInterception();
576
594
  }
577
595
  fileChooserIntercepted() {
578
- return this._interceptFileChooser;
596
+ return this._fileChooserInterceptedBy.size > 0;
579
597
  }
580
598
  frameNavigatedToNewDocument(frame) {
581
599
  this.emit(Page.Events.InternalFrameNavigatedToNewDocument, frame);
582
600
  const origin = frame.origin();
583
- if (origin) this._browserContext.addVisitedOrigin(origin);
601
+ if (origin)
602
+ this.browserContext.addVisitedOrigin(origin);
584
603
  }
585
604
  allInitScripts() {
586
- const bindings = [...this._browserContext._pageBindings.values(), ...this._pageBindings.values()];
587
- return [...bindings.map(binding => binding.initScript), ...this._browserContext.initScripts, ...this.initScripts];
605
+ const bindings = [...this.browserContext._pageBindings.values(), ...this._pageBindings.values()].map((binding) => binding.initScript);
606
+ if (this.browserContext.bindingsInitScript)
607
+ bindings.unshift(this.browserContext.bindingsInitScript);
608
+ return [...bindings, ...this.browserContext.initScripts, ...this.initScripts];
588
609
  }
589
610
  getBinding(name) {
590
- return this._pageBindings.get(name) || this._browserContext._pageBindings.get(name);
611
+ return this._pageBindings.get(name) || this.browserContext._pageBindings.get(name);
591
612
  }
592
613
  setScreencastOptions(options) {
593
- this._delegate.setScreencastOptions(options).catch(e => _debugLogger.debugLogger.log('error', e));
614
+ this.delegate.setScreencastOptions(options).catch((e) => import_debugLogger.debugLogger.log("error", e));
594
615
  this._frameThrottler.setThrottlingEnabled(!!options);
595
616
  }
596
617
  throttleScreencastFrameAck(ack) {
597
- // Don't ack immediately, tracing has smart throttling logic that is implemented here.
598
618
  this._frameThrottler.ack(ack);
599
619
  }
600
620
  temporarilyDisableTracingScreencastThrottling() {
601
621
  this._frameThrottler.recharge();
602
622
  }
603
623
  async safeNonStallingEvaluateInAllFrames(expression, world, options = {}) {
604
- await Promise.all(this.frames().map(async frame => {
624
+ await Promise.all(this.frames().map(async (frame) => {
605
625
  try {
606
626
  await frame.nonStallingEvaluateInExistingContext(expression, world);
607
627
  } catch (e) {
608
- if (options.throwOnJSErrors && js.isJavaScriptErrorInEvaluate(e)) throw e;
628
+ if (options.throwOnJSErrors && js.isJavaScriptErrorInEvaluate(e))
629
+ throw e;
609
630
  }
610
631
  }));
611
632
  }
612
633
  async hideHighlight() {
613
- await Promise.all(this.frames().map(frame => frame.hideHighlight().catch(() => {})));
634
+ await Promise.all(this.frames().map((frame) => frame.hideHighlight().catch(() => {
635
+ })));
614
636
  }
615
637
  markAsServerSideOnly() {
616
638
  this._isServerSideOnly = true;
617
639
  }
640
+ async snapshotForAI(progress) {
641
+ this.lastSnapshotFrameIds = [];
642
+ const snapshot = await snapshotFrameForAI(progress, this.mainFrame(), 0, this.lastSnapshotFrameIds);
643
+ return snapshot.join("\n");
644
+ }
618
645
  }
619
- exports.Page = Page;
620
- Page.Events = {
621
- Close: 'close',
622
- Crash: 'crash',
623
- Download: 'download',
624
- FileChooser: 'filechooser',
625
- FrameAttached: 'frameattached',
626
- FrameDetached: 'framedetached',
627
- InternalFrameNavigatedToNewDocument: 'internalframenavigatedtonewdocument',
628
- LocatorHandlerTriggered: 'locatorhandlertriggered',
629
- ScreencastFrame: 'screencastframe',
630
- Video: 'video',
631
- WebSocket: 'websocket',
632
- Worker: 'worker'
633
- };
634
- class Worker extends _instrumentation.SdkObject {
646
+ class Worker extends import_instrumentation.SdkObject {
635
647
  constructor(parent, url) {
636
- super(parent, 'worker');
637
- this._url = void 0;
638
- this._executionContextPromise = void 0;
639
- this._executionContextCallback = void 0;
640
- this._existingExecutionContext = null;
641
- this.openScope = new _utils.LongStandingScope();
642
- this._url = url;
643
- this._executionContextCallback = () => {};
644
- this._executionContextPromise = new Promise(x => this._executionContextCallback = x);
645
- }
646
- _createExecutionContext(delegate) {
647
- this._existingExecutionContext = new js.ExecutionContext(this, delegate, 'worker');
648
- this._executionContextCallback(this._existingExecutionContext);
649
- return this._existingExecutionContext;
650
- }
651
- url() {
652
- return this._url;
648
+ super(parent, "worker");
649
+ this.existingExecutionContext = null;
650
+ this.openScope = new import_utils.LongStandingScope();
651
+ this.url = url;
652
+ this._executionContextCallback = () => {
653
+ };
654
+ this._executionContextPromise = new Promise((x) => this._executionContextCallback = x);
655
+ }
656
+ static {
657
+ this.Events = {
658
+ Close: "close"
659
+ };
660
+ }
661
+ createExecutionContext(delegate) {
662
+ this.existingExecutionContext = new js.ExecutionContext(this, delegate, "worker");
663
+ this._executionContextCallback(this.existingExecutionContext);
664
+ return this.existingExecutionContext;
653
665
  }
654
666
  didClose() {
655
- if (this._existingExecutionContext) this._existingExecutionContext.contextDestroyed('Worker was closed');
667
+ if (this.existingExecutionContext)
668
+ this.existingExecutionContext.contextDestroyed("Worker was closed");
656
669
  this.emit(Worker.Events.Close, this);
657
- this.openScope.close(new Error('Worker closed'));
670
+ this.openScope.close(new Error("Worker closed"));
658
671
  }
659
672
  async evaluateExpression(expression, isFunction, arg) {
660
- return js.evaluateExpression(await this._executionContextPromise, expression, {
661
- returnByValue: true,
662
- isFunction
663
- }, arg);
673
+ return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: true, isFunction }, arg);
664
674
  }
665
675
  async evaluateExpressionHandle(expression, isFunction, arg) {
666
- return js.evaluateExpression(await this._executionContextPromise, expression, {
667
- returnByValue: false,
668
- isFunction
669
- }, arg);
676
+ return js.evaluateExpression(await this._executionContextPromise, expression, { returnByValue: false, isFunction }, arg);
670
677
  }
671
678
  }
672
- exports.Worker = Worker;
673
- Worker.Events = {
674
- Close: 'close'
675
- };
676
679
  class PageBinding {
680
+ static {
681
+ this.kController = "__playwright__binding__controller__";
682
+ }
683
+ static {
684
+ this.kBindingName = "__playwright__binding__";
685
+ }
686
+ static createInitScript() {
687
+ return new InitScript(`
688
+ (() => {
689
+ const module = {};
690
+ ${rawBindingsControllerSource.source}
691
+ const property = '${PageBinding.kController}';
692
+ if (!globalThis[property])
693
+ globalThis[property] = new (module.exports.BindingsController())(globalThis, '${PageBinding.kBindingName}');
694
+ })();
695
+ `);
696
+ }
677
697
  constructor(name, playwrightFunction, needsHandle) {
678
- this.name = void 0;
679
- this.playwrightFunction = void 0;
680
- this.initScript = void 0;
681
- this.needsHandle = void 0;
682
- this.internal = void 0;
683
698
  this.name = name;
684
699
  this.playwrightFunction = playwrightFunction;
685
- this.initScript = new InitScript(`(${addPageBinding.toString()})(${JSON.stringify(PageBinding.kPlaywrightBinding)}, ${JSON.stringify(name)}, ${needsHandle}, (${_utilityScriptSerializers.source})())`, true /* internal */);
700
+ this.initScript = new InitScript(`globalThis['${PageBinding.kController}'].addBinding(${JSON.stringify(name)}, ${needsHandle})`);
686
701
  this.needsHandle = needsHandle;
687
- this.internal = name.startsWith('__pw');
702
+ this.cleanupScript = `globalThis['${PageBinding.kController}'].removeBinding(${JSON.stringify(name)})`;
688
703
  }
689
704
  static async dispatch(page, payload, context) {
690
- const {
691
- name,
692
- seq,
693
- serializedArgs
694
- } = JSON.parse(payload);
705
+ const { name, seq, serializedArgs } = JSON.parse(payload);
695
706
  try {
696
- (0, _utils.assert)(context.world);
707
+ (0, import_utils.assert)(context.world);
697
708
  const binding = page.getBinding(name);
698
- if (!binding) throw new Error(`Function "${name}" is not exposed`);
709
+ if (!binding)
710
+ throw new Error(`Function "${name}" is not exposed`);
699
711
  let result;
700
712
  if (binding.needsHandle) {
701
- const handle = await context.evaluateHandle(takeHandle, {
702
- name,
703
- seq
704
- }).catch(e => null);
705
- result = await binding.playwrightFunction({
706
- frame: context.frame,
707
- page,
708
- context: page._browserContext
709
- }, handle);
713
+ const handle = await context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].takeBindingHandle(arg)`, { isFunction: true }, { name, seq }).catch((e) => null);
714
+ result = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, handle);
710
715
  } else {
711
- if (!Array.isArray(serializedArgs)) throw new Error(`serializedArgs is not an array. This can happen when Array.prototype.toJSON is defined incorrectly`);
712
- const args = serializedArgs.map(a => (0, _utilityScriptSerializers.parseEvaluationResultValue)(a));
713
- result = await binding.playwrightFunction({
714
- frame: context.frame,
715
- page,
716
- context: page._browserContext
717
- }, ...args);
716
+ if (!Array.isArray(serializedArgs))
717
+ throw new Error(`serializedArgs is not an array. This can happen when Array.prototype.toJSON is defined incorrectly`);
718
+ const args = serializedArgs.map((a) => (0, import_utilityScriptSerializers.parseEvaluationResultValue)(a));
719
+ result = await binding.playwrightFunction({ frame: context.frame, page, context: page.browserContext }, ...args);
718
720
  }
719
- context.evaluate(deliverResult, {
720
- name,
721
- seq,
722
- result
723
- }).catch(e => _debugLogger.debugLogger.log('error', e));
721
+ context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, result }).catch((e) => import_debugLogger.debugLogger.log("error", e));
724
722
  } catch (error) {
725
- context.evaluate(deliverResult, {
726
- name,
727
- seq,
728
- error
729
- }).catch(e => _debugLogger.debugLogger.log('error', e));
730
- }
731
- function takeHandle(arg) {
732
- const handle = globalThis[arg.name]['handles'].get(arg.seq);
733
- globalThis[arg.name]['handles'].delete(arg.seq);
734
- return handle;
735
- }
736
- function deliverResult(arg) {
737
- const callbacks = globalThis[arg.name]['callbacks'];
738
- if ('error' in arg) callbacks.get(arg.seq).reject(arg.error);else callbacks.get(arg.seq).resolve(arg.result);
739
- callbacks.delete(arg.seq);
723
+ context.evaluateExpressionHandle(`arg => globalThis['${PageBinding.kController}'].deliverBindingResult(arg)`, { isFunction: true }, { name, seq, error }).catch((e) => import_debugLogger.debugLogger.log("error", e));
740
724
  }
741
725
  }
742
726
  }
743
- exports.PageBinding = PageBinding;
744
- PageBinding.kPlaywrightBinding = '__playwright__binding__';
745
- function addPageBinding(playwrightBinding, bindingName, needsHandle, utilityScriptSerializers) {
746
- const binding = globalThis[playwrightBinding];
747
- globalThis[bindingName] = (...args) => {
748
- const me = globalThis[bindingName];
749
- if (needsHandle && args.slice(1).some(arg => arg !== undefined)) throw new Error(`exposeBindingHandle supports a single argument, ${args.length} received`);
750
- let callbacks = me['callbacks'];
751
- if (!callbacks) {
752
- callbacks = new Map();
753
- me['callbacks'] = callbacks;
754
- }
755
- const seq = (me['lastSeq'] || 0) + 1;
756
- me['lastSeq'] = seq;
757
- let handles = me['handles'];
758
- if (!handles) {
759
- handles = new Map();
760
- me['handles'] = handles;
761
- }
762
- const promise = new Promise((resolve, reject) => callbacks.set(seq, {
763
- resolve,
764
- reject
765
- }));
766
- let payload;
767
- if (needsHandle) {
768
- handles.set(seq, args[0]);
769
- payload = {
770
- name: bindingName,
771
- seq
772
- };
773
- } else {
774
- const serializedArgs = [];
775
- for (let i = 0; i < args.length; i++) {
776
- serializedArgs[i] = utilityScriptSerializers.serializeAsCallArgument(args[i], v => {
777
- return {
778
- fallThrough: v
779
- };
780
- });
781
- }
782
- payload = {
783
- name: bindingName,
784
- seq,
785
- serializedArgs
786
- };
787
- }
788
- binding(JSON.stringify(payload));
789
- return promise;
790
- };
791
- globalThis[bindingName].__installed = true;
792
- }
793
727
  class InitScript {
794
- constructor(source, internal, name) {
795
- this.source = void 0;
796
- this.internal = void 0;
797
- this.name = void 0;
798
- const guid = (0, _crypto.createGuid)();
728
+ constructor(source) {
799
729
  this.source = `(() => {
800
- globalThis.__pwInitScripts = globalThis.__pwInitScripts || {};
801
- const hasInitScript = globalThis.__pwInitScripts[${JSON.stringify(guid)}];
802
- if (hasInitScript)
803
- return;
804
- globalThis.__pwInitScripts[${JSON.stringify(guid)}] = true;
805
730
  ${source}
806
731
  })();`;
807
- this.internal = !!internal;
808
- this.name = name;
809
732
  }
810
733
  }
811
- exports.InitScript = InitScript;
812
734
  class FrameThrottler {
813
735
  constructor(nonThrottledFrames, defaultInterval, throttlingInterval) {
814
736
  this._acks = [];
815
- this._defaultInterval = void 0;
816
- this._throttlingInterval = void 0;
817
- this._nonThrottledFrames = void 0;
818
- this._budget = void 0;
819
737
  this._throttlingEnabled = false;
820
- this._timeoutId = void 0;
821
738
  this._nonThrottledFrames = nonThrottledFrames;
822
739
  this._budget = nonThrottledFrames;
823
740
  this._defaultInterval = defaultInterval;
@@ -827,15 +744,15 @@ class FrameThrottler {
827
744
  dispose() {
828
745
  if (this._timeoutId) {
829
746
  clearTimeout(this._timeoutId);
830
- this._timeoutId = undefined;
747
+ this._timeoutId = void 0;
831
748
  }
832
749
  }
833
750
  setThrottlingEnabled(enabled) {
834
751
  this._throttlingEnabled = enabled;
835
752
  }
836
753
  recharge() {
837
- // Send all acks, reset budget.
838
- for (const ack of this._acks) ack();
754
+ for (const ack of this._acks)
755
+ ack();
839
756
  this._acks = [];
840
757
  this._budget = this._nonThrottledFrames;
841
758
  if (this._timeoutId) {
@@ -845,7 +762,6 @@ class FrameThrottler {
845
762
  }
846
763
  ack(ack) {
847
764
  if (!this._timeoutId) {
848
- // Already disposed.
849
765
  ack();
850
766
  return;
851
767
  }
@@ -858,11 +774,64 @@ class FrameThrottler {
858
774
  ack();
859
775
  }
860
776
  if (this._throttlingEnabled && this._budget <= 0) {
861
- // Non-throttled frame budget is exceeded. Next ack will be throttled.
862
777
  this._timeoutId = setTimeout(() => this._tick(), this._throttlingInterval);
863
778
  } else {
864
- // Either not throttling, or still under budget. Next ack will be after the default timeout.
865
779
  this._timeoutId = setTimeout(() => this._tick(), this._defaultInterval);
866
780
  }
867
781
  }
868
- }
782
+ }
783
+ async function snapshotFrameForAI(progress, frame, frameOrdinal, frameIds) {
784
+ const snapshot = await frame.retryWithProgressAndTimeouts(progress, [1e3, 2e3, 4e3, 8e3], async (continuePolling) => {
785
+ try {
786
+ const context = await progress.race(frame._utilityContext());
787
+ const injectedScript = await progress.race(context.injectedScript());
788
+ const snapshotOrRetry = await progress.race(injectedScript.evaluate((injected, refPrefix) => {
789
+ const node = injected.document.body;
790
+ if (!node)
791
+ return true;
792
+ return injected.ariaSnapshot(node, { forAI: true, refPrefix });
793
+ }, frameOrdinal ? "f" + frameOrdinal : ""));
794
+ if (snapshotOrRetry === true)
795
+ return continuePolling;
796
+ return snapshotOrRetry;
797
+ } catch (e) {
798
+ if (frame.isNonRetriableError(e))
799
+ throw e;
800
+ return continuePolling;
801
+ }
802
+ });
803
+ const lines = snapshot.split("\n");
804
+ const result = [];
805
+ for (const line of lines) {
806
+ const match = line.match(/^(\s*)- iframe (?:\[active\] )?\[ref=(.*)\]/);
807
+ if (!match) {
808
+ result.push(line);
809
+ continue;
810
+ }
811
+ const leadingSpace = match[1];
812
+ const ref = match[2];
813
+ const frameSelector = `aria-ref=${ref} >> internal:control=enter-frame`;
814
+ const frameBodySelector = `${frameSelector} >> body`;
815
+ const child = await progress.race(frame.selectors.resolveFrameForSelector(frameBodySelector, { strict: true }));
816
+ if (!child) {
817
+ result.push(line);
818
+ continue;
819
+ }
820
+ const frameOrdinal2 = frameIds.length + 1;
821
+ frameIds.push(child.frame._id);
822
+ try {
823
+ const childSnapshot = await snapshotFrameForAI(progress, child.frame, frameOrdinal2, frameIds);
824
+ result.push(line + ":", ...childSnapshot.map((l) => leadingSpace + " " + l));
825
+ } catch {
826
+ result.push(line);
827
+ }
828
+ }
829
+ return result;
830
+ }
831
+ // Annotate the CommonJS export names for ESM import in node:
832
+ 0 && (module.exports = {
833
+ InitScript,
834
+ Page,
835
+ PageBinding,
836
+ Worker
837
+ });