patchright-bun-core 1.58.0 → 1.58.2

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 (358) hide show
  1. package/README.md +2 -2
  2. package/ThirdPartyNotices.txt +4075 -4075
  3. package/bin/install_media_pack.ps1 +5 -5
  4. package/bin/install_webkit_wsl.ps1 +32 -32
  5. package/bin/reinstall_chrome_beta_linux.sh +42 -42
  6. package/bin/reinstall_chrome_beta_mac.sh +13 -13
  7. package/bin/reinstall_chrome_beta_win.ps1 +24 -24
  8. package/bin/reinstall_chrome_stable_linux.sh +42 -42
  9. package/bin/reinstall_chrome_stable_mac.sh +12 -12
  10. package/bin/reinstall_chrome_stable_win.ps1 +24 -24
  11. package/bin/reinstall_msedge_beta_linux.sh +48 -48
  12. package/bin/reinstall_msedge_beta_mac.sh +11 -11
  13. package/bin/reinstall_msedge_beta_win.ps1 +23 -23
  14. package/bin/reinstall_msedge_dev_linux.sh +48 -48
  15. package/bin/reinstall_msedge_dev_mac.sh +11 -11
  16. package/bin/reinstall_msedge_dev_win.ps1 +23 -23
  17. package/bin/reinstall_msedge_stable_linux.sh +48 -48
  18. package/bin/reinstall_msedge_stable_mac.sh +11 -11
  19. package/bin/reinstall_msedge_stable_win.ps1 +23 -23
  20. package/browsers.json +79 -79
  21. package/cli.js +18 -18
  22. package/index.d.ts +17 -17
  23. package/index.js +32 -32
  24. package/index.mjs +28 -28
  25. package/lib/androidServerImpl.js +65 -65
  26. package/lib/browserServerImpl.js +120 -120
  27. package/lib/cli/driver.js +97 -97
  28. package/lib/cli/program.js +589 -589
  29. package/lib/cli/programWithTestStub.js +74 -74
  30. package/lib/client/android.js +361 -361
  31. package/lib/client/api.js +137 -137
  32. package/lib/client/artifact.js +79 -79
  33. package/lib/client/browser.js +161 -161
  34. package/lib/client/browserContext.js +582 -582
  35. package/lib/client/browserType.js +185 -185
  36. package/lib/client/cdpSession.js +51 -51
  37. package/lib/client/channelOwner.js +194 -194
  38. package/lib/client/clientHelper.js +64 -64
  39. package/lib/client/clientInstrumentation.js +55 -55
  40. package/lib/client/clientStackTrace.js +69 -69
  41. package/lib/client/clock.js +68 -68
  42. package/lib/client/connection.js +318 -318
  43. package/lib/client/consoleMessage.js +58 -58
  44. package/lib/client/coverage.js +44 -44
  45. package/lib/client/dialog.js +56 -56
  46. package/lib/client/download.js +62 -62
  47. package/lib/client/electron.js +138 -138
  48. package/lib/client/elementHandle.js +284 -284
  49. package/lib/client/errors.js +77 -77
  50. package/lib/client/eventEmitter.js +314 -314
  51. package/lib/client/events.js +103 -103
  52. package/lib/client/fetch.js +368 -368
  53. package/lib/client/fileChooser.js +46 -46
  54. package/lib/client/fileUtils.js +34 -34
  55. package/lib/client/frame.js +409 -409
  56. package/lib/client/harRouter.js +87 -87
  57. package/lib/client/input.js +84 -84
  58. package/lib/client/jsHandle.js +109 -109
  59. package/lib/client/jsonPipe.js +39 -39
  60. package/lib/client/localUtils.js +60 -60
  61. package/lib/client/locator.js +369 -369
  62. package/lib/client/network.js +747 -747
  63. package/lib/client/page.js +745 -745
  64. package/lib/client/pageAgent.js +64 -64
  65. package/lib/client/platform.js +77 -77
  66. package/lib/client/playwright.js +71 -71
  67. package/lib/client/selectors.js +55 -55
  68. package/lib/client/stream.js +39 -39
  69. package/lib/client/timeoutSettings.js +79 -79
  70. package/lib/client/tracing.js +119 -119
  71. package/lib/client/types.js +28 -28
  72. package/lib/client/video.js +59 -59
  73. package/lib/client/waiter.js +142 -142
  74. package/lib/client/webError.js +39 -39
  75. package/lib/client/webSocket.js +93 -93
  76. package/lib/client/worker.js +85 -85
  77. package/lib/client/writableStream.js +39 -39
  78. package/lib/generated/bindingsControllerSource.js +28 -28
  79. package/lib/generated/clockSource.js +28 -28
  80. package/lib/generated/injectedScriptSource.js +28 -28
  81. package/lib/generated/pollingRecorderSource.js +28 -28
  82. package/lib/generated/storageScriptSource.js +28 -28
  83. package/lib/generated/utilityScriptSource.js +28 -28
  84. package/lib/generated/webSocketMockSource.js +336 -336
  85. package/lib/inProcessFactory.js +60 -60
  86. package/lib/inprocess.js +3 -3
  87. package/lib/mcpBundle.js +84 -84
  88. package/lib/mcpBundleImpl/index.js +147 -147
  89. package/lib/outofprocess.js +76 -76
  90. package/lib/protocol/serializers.js +197 -197
  91. package/lib/protocol/validator.js +2969 -2969
  92. package/lib/protocol/validatorPrimitives.js +193 -193
  93. package/lib/remote/playwrightConnection.js +129 -129
  94. package/lib/remote/playwrightServer.js +334 -334
  95. package/lib/server/agent/actionRunner.js +335 -335
  96. package/lib/server/agent/actions.js +128 -128
  97. package/lib/server/agent/codegen.js +111 -111
  98. package/lib/server/agent/context.js +150 -150
  99. package/lib/server/agent/expectTools.js +156 -156
  100. package/lib/server/agent/pageAgent.js +204 -204
  101. package/lib/server/agent/performTools.js +262 -262
  102. package/lib/server/agent/tool.js +109 -109
  103. package/lib/server/android/android.js +465 -465
  104. package/lib/server/android/backendAdb.js +177 -177
  105. package/lib/server/artifact.js +127 -127
  106. package/lib/server/bidi/bidiBrowser.js +549 -549
  107. package/lib/server/bidi/bidiChromium.js +149 -148
  108. package/lib/server/bidi/bidiConnection.js +213 -213
  109. package/lib/server/bidi/bidiDeserializer.js +116 -116
  110. package/lib/server/bidi/bidiExecutionContext.js +267 -267
  111. package/lib/server/bidi/bidiFirefox.js +128 -128
  112. package/lib/server/bidi/bidiInput.js +146 -146
  113. package/lib/server/bidi/bidiNetworkManager.js +383 -383
  114. package/lib/server/bidi/bidiOverCdp.js +102 -102
  115. package/lib/server/bidi/bidiPage.js +583 -583
  116. package/lib/server/bidi/bidiPdf.js +106 -106
  117. package/lib/server/bidi/third_party/bidiCommands.d.js +22 -22
  118. package/lib/server/bidi/third_party/bidiKeyboard.js +256 -256
  119. package/lib/server/bidi/third_party/bidiProtocol.js +24 -24
  120. package/lib/server/bidi/third_party/bidiProtocolCore.js +180 -180
  121. package/lib/server/bidi/third_party/bidiProtocolPermissions.js +42 -42
  122. package/lib/server/bidi/third_party/bidiSerializer.js +148 -148
  123. package/lib/server/bidi/third_party/firefoxPrefs.js +259 -259
  124. package/lib/server/browser.js +149 -149
  125. package/lib/server/browserContext.js +702 -702
  126. package/lib/server/browserType.js +336 -336
  127. package/lib/server/callLog.js +82 -82
  128. package/lib/server/chromium/chromium.js +397 -395
  129. package/lib/server/chromium/chromiumSwitches.js +104 -104
  130. package/lib/server/chromium/crBrowser.js +520 -511
  131. package/lib/server/chromium/crConnection.js +197 -197
  132. package/lib/server/chromium/crCoverage.js +235 -235
  133. package/lib/server/chromium/crDevTools.js +111 -111
  134. package/lib/server/chromium/crDragDrop.js +131 -131
  135. package/lib/server/chromium/crExecutionContext.js +146 -146
  136. package/lib/server/chromium/crInput.js +187 -187
  137. package/lib/server/chromium/crNetworkManager.js +707 -707
  138. package/lib/server/chromium/crPage.js +1001 -1001
  139. package/lib/server/chromium/crPdf.js +121 -121
  140. package/lib/server/chromium/crProtocolHelper.js +145 -145
  141. package/lib/server/chromium/crServiceWorker.js +136 -136
  142. package/lib/server/chromium/defaultFontFamilies.js +162 -162
  143. package/lib/server/chromium/protocol.d.js +16 -16
  144. package/lib/server/clock.js +149 -149
  145. package/lib/server/codegen/csharp.js +327 -327
  146. package/lib/server/codegen/java.js +274 -274
  147. package/lib/server/codegen/javascript.js +247 -247
  148. package/lib/server/codegen/jsonl.js +52 -52
  149. package/lib/server/codegen/language.js +132 -132
  150. package/lib/server/codegen/languages.js +68 -68
  151. package/lib/server/codegen/python.js +279 -279
  152. package/lib/server/codegen/types.js +16 -16
  153. package/lib/server/console.js +57 -57
  154. package/lib/server/cookieStore.js +206 -206
  155. package/lib/server/debugController.js +191 -191
  156. package/lib/server/debugger.js +119 -119
  157. package/lib/server/deviceDescriptors.js +39 -39
  158. package/lib/server/deviceDescriptorsSource.json +1778 -1778
  159. package/lib/server/dialog.js +116 -116
  160. package/lib/server/dispatchers/androidDispatcher.js +325 -325
  161. package/lib/server/dispatchers/artifactDispatcher.js +118 -118
  162. package/lib/server/dispatchers/browserContextDispatcher.js +384 -384
  163. package/lib/server/dispatchers/browserDispatcher.js +118 -118
  164. package/lib/server/dispatchers/browserTypeDispatcher.js +64 -64
  165. package/lib/server/dispatchers/cdpSessionDispatcher.js +44 -44
  166. package/lib/server/dispatchers/debugControllerDispatcher.js +78 -78
  167. package/lib/server/dispatchers/dialogDispatcher.js +47 -47
  168. package/lib/server/dispatchers/dispatcher.js +364 -364
  169. package/lib/server/dispatchers/electronDispatcher.js +89 -89
  170. package/lib/server/dispatchers/elementHandlerDispatcher.js +181 -181
  171. package/lib/server/dispatchers/frameDispatcher.js +227 -227
  172. package/lib/server/dispatchers/jsHandleDispatcher.js +85 -85
  173. package/lib/server/dispatchers/jsonPipeDispatcher.js +58 -58
  174. package/lib/server/dispatchers/localUtilsDispatcher.js +149 -149
  175. package/lib/server/dispatchers/networkDispatchers.js +213 -213
  176. package/lib/server/dispatchers/pageAgentDispatcher.js +96 -96
  177. package/lib/server/dispatchers/pageDispatcher.js +393 -393
  178. package/lib/server/dispatchers/playwrightDispatcher.js +108 -108
  179. package/lib/server/dispatchers/streamDispatcher.js +67 -67
  180. package/lib/server/dispatchers/tracingDispatcher.js +68 -68
  181. package/lib/server/dispatchers/webSocketRouteDispatcher.js +165 -165
  182. package/lib/server/dispatchers/writableStreamDispatcher.js +79 -79
  183. package/lib/server/dom.js +815 -815
  184. package/lib/server/download.js +70 -70
  185. package/lib/server/electron/electron.js +273 -273
  186. package/lib/server/electron/loader.js +29 -29
  187. package/lib/server/errors.js +69 -69
  188. package/lib/server/fetch.js +621 -621
  189. package/lib/server/fileChooser.js +43 -43
  190. package/lib/server/fileUploadUtils.js +84 -84
  191. package/lib/server/firefox/ffBrowser.js +418 -418
  192. package/lib/server/firefox/ffConnection.js +142 -142
  193. package/lib/server/firefox/ffExecutionContext.js +150 -150
  194. package/lib/server/firefox/ffInput.js +159 -159
  195. package/lib/server/firefox/ffNetworkManager.js +256 -256
  196. package/lib/server/firefox/ffPage.js +497 -497
  197. package/lib/server/firefox/firefox.js +114 -114
  198. package/lib/server/firefox/protocol.d.js +16 -16
  199. package/lib/server/formData.js +147 -147
  200. package/lib/server/frameSelectors.js +160 -160
  201. package/lib/server/frames.js +1471 -1471
  202. package/lib/server/har/harRecorder.js +147 -147
  203. package/lib/server/har/harTracer.js +607 -607
  204. package/lib/server/harBackend.js +157 -157
  205. package/lib/server/helper.js +96 -96
  206. package/lib/server/index.js +58 -58
  207. package/lib/server/input.js +277 -277
  208. package/lib/server/instrumentation.js +72 -72
  209. package/lib/server/javascript.js +291 -291
  210. package/lib/server/launchApp.js +128 -128
  211. package/lib/server/localUtils.js +214 -214
  212. package/lib/server/macEditingCommands.js +143 -143
  213. package/lib/server/network.js +667 -667
  214. package/lib/server/page.js +830 -830
  215. package/lib/server/pipeTransport.js +89 -89
  216. package/lib/server/playwright.js +69 -69
  217. package/lib/server/progress.js +132 -132
  218. package/lib/server/protocolError.js +52 -52
  219. package/lib/server/recorder/chat.js +161 -161
  220. package/lib/server/recorder/recorderApp.js +366 -366
  221. package/lib/server/recorder/recorderRunner.js +138 -138
  222. package/lib/server/recorder/recorderSignalProcessor.js +83 -83
  223. package/lib/server/recorder/recorderUtils.js +157 -157
  224. package/lib/server/recorder/throttledFile.js +57 -57
  225. package/lib/server/recorder.js +499 -499
  226. package/lib/server/registry/browserFetcher.js +177 -177
  227. package/lib/server/registry/dependencies.js +371 -371
  228. package/lib/server/registry/index.js +1422 -1422
  229. package/lib/server/registry/nativeDeps.js +1280 -1280
  230. package/lib/server/registry/oopDownloadBrowserMain.js +127 -127
  231. package/lib/server/screencast.js +190 -190
  232. package/lib/server/screenshotter.js +333 -333
  233. package/lib/server/selectors.js +112 -112
  234. package/lib/server/socksClientCertificatesInterceptor.js +383 -383
  235. package/lib/server/socksInterceptor.js +95 -95
  236. package/lib/server/trace/recorder/snapshotter.js +147 -147
  237. package/lib/server/trace/recorder/snapshotterInjected.js +561 -561
  238. package/lib/server/trace/recorder/tracing.js +604 -604
  239. package/lib/server/trace/viewer/traceParser.js +72 -72
  240. package/lib/server/trace/viewer/traceViewer.js +245 -245
  241. package/lib/server/transport.js +254 -254
  242. package/lib/server/types.js +28 -28
  243. package/lib/server/usKeyboardLayout.js +145 -145
  244. package/lib/server/utils/ascii.js +44 -44
  245. package/lib/server/utils/comparators.js +139 -139
  246. package/lib/server/utils/crypto.js +216 -216
  247. package/lib/server/utils/debug.js +42 -42
  248. package/lib/server/utils/debugLogger.js +122 -122
  249. package/lib/server/utils/env.js +73 -73
  250. package/lib/server/utils/eventsHelper.js +39 -39
  251. package/lib/server/utils/expectUtils.js +123 -123
  252. package/lib/server/utils/fileUtils.js +191 -191
  253. package/lib/server/utils/happyEyeballs.js +207 -207
  254. package/lib/server/utils/hostPlatform.js +138 -123
  255. package/lib/server/utils/httpServer.js +203 -203
  256. package/lib/server/utils/imageUtils.js +141 -141
  257. package/lib/server/utils/image_tools/colorUtils.js +89 -89
  258. package/lib/server/utils/image_tools/compare.js +109 -109
  259. package/lib/server/utils/image_tools/imageChannel.js +78 -78
  260. package/lib/server/utils/image_tools/stats.js +102 -102
  261. package/lib/server/utils/linuxUtils.js +71 -71
  262. package/lib/server/utils/network.js +242 -242
  263. package/lib/server/utils/nodePlatform.js +154 -154
  264. package/lib/server/utils/pipeTransport.js +84 -84
  265. package/lib/server/utils/processLauncher.js +241 -241
  266. package/lib/server/utils/profiler.js +65 -65
  267. package/lib/server/utils/socksProxy.js +511 -511
  268. package/lib/server/utils/spawnAsync.js +41 -41
  269. package/lib/server/utils/task.js +51 -51
  270. package/lib/server/utils/userAgent.js +98 -98
  271. package/lib/server/utils/wsServer.js +121 -121
  272. package/lib/server/utils/zipFile.js +74 -74
  273. package/lib/server/utils/zones.js +57 -57
  274. package/lib/server/videoRecorder.js +124 -124
  275. package/lib/server/webkit/protocol.d.js +16 -16
  276. package/lib/server/webkit/webkit.js +108 -108
  277. package/lib/server/webkit/wkBrowser.js +335 -335
  278. package/lib/server/webkit/wkConnection.js +144 -144
  279. package/lib/server/webkit/wkExecutionContext.js +154 -154
  280. package/lib/server/webkit/wkInput.js +181 -181
  281. package/lib/server/webkit/wkInterceptableRequest.js +197 -197
  282. package/lib/server/webkit/wkPage.js +1159 -1158
  283. package/lib/server/webkit/wkProvisionalPage.js +83 -83
  284. package/lib/server/webkit/wkWorkers.js +105 -105
  285. package/lib/third_party/pixelmatch.js +255 -255
  286. package/lib/utils/isomorphic/ariaSnapshot.js +455 -455
  287. package/lib/utils/isomorphic/assert.js +31 -31
  288. package/lib/utils/isomorphic/colors.js +72 -72
  289. package/lib/utils/isomorphic/cssParser.js +245 -245
  290. package/lib/utils/isomorphic/cssTokenizer.js +1051 -1051
  291. package/lib/utils/isomorphic/headers.js +53 -53
  292. package/lib/utils/isomorphic/locatorGenerators.js +689 -689
  293. package/lib/utils/isomorphic/locatorParser.js +176 -176
  294. package/lib/utils/isomorphic/locatorUtils.js +81 -81
  295. package/lib/utils/isomorphic/lruCache.js +51 -51
  296. package/lib/utils/isomorphic/manualPromise.js +114 -114
  297. package/lib/utils/isomorphic/mimeType.js +459 -459
  298. package/lib/utils/isomorphic/multimap.js +80 -80
  299. package/lib/utils/isomorphic/protocolFormatter.js +81 -81
  300. package/lib/utils/isomorphic/protocolMetainfo.js +330 -330
  301. package/lib/utils/isomorphic/rtti.js +43 -43
  302. package/lib/utils/isomorphic/selectorParser.js +386 -386
  303. package/lib/utils/isomorphic/semaphore.js +54 -54
  304. package/lib/utils/isomorphic/stackTrace.js +158 -158
  305. package/lib/utils/isomorphic/stringUtils.js +204 -204
  306. package/lib/utils/isomorphic/time.js +49 -49
  307. package/lib/utils/isomorphic/timeoutRunner.js +66 -66
  308. package/lib/utils/isomorphic/trace/entries.js +16 -16
  309. package/lib/utils/isomorphic/trace/snapshotRenderer.js +499 -499
  310. package/lib/utils/isomorphic/trace/snapshotServer.js +120 -120
  311. package/lib/utils/isomorphic/trace/snapshotStorage.js +89 -89
  312. package/lib/utils/isomorphic/trace/traceLoader.js +131 -131
  313. package/lib/utils/isomorphic/trace/traceModel.js +365 -365
  314. package/lib/utils/isomorphic/trace/traceModernizer.js +400 -400
  315. package/lib/utils/isomorphic/trace/versions/traceV3.js +16 -16
  316. package/lib/utils/isomorphic/trace/versions/traceV4.js +16 -16
  317. package/lib/utils/isomorphic/trace/versions/traceV5.js +16 -16
  318. package/lib/utils/isomorphic/trace/versions/traceV6.js +16 -16
  319. package/lib/utils/isomorphic/trace/versions/traceV7.js +16 -16
  320. package/lib/utils/isomorphic/trace/versions/traceV8.js +16 -16
  321. package/lib/utils/isomorphic/traceUtils.js +58 -58
  322. package/lib/utils/isomorphic/types.js +16 -16
  323. package/lib/utils/isomorphic/urlMatch.js +190 -190
  324. package/lib/utils/isomorphic/utilityScriptSerializers.js +251 -251
  325. package/lib/utils/isomorphic/yaml.js +84 -84
  326. package/lib/utils.js +111 -111
  327. package/lib/utilsBundle.js +109 -109
  328. package/lib/utilsBundleImpl/index.js +218 -218
  329. package/lib/utilsBundleImpl/xdg-open +1066 -1066
  330. package/lib/vite/htmlReport/index.html +84 -84
  331. package/lib/vite/recorder/assets/codeMirrorModule-DYBRYzYX.css +1 -1
  332. package/lib/vite/recorder/assets/codeMirrorModule-DadYNm1I.js +32 -32
  333. package/lib/vite/recorder/assets/index-BSjZa4pk.css +1 -1
  334. package/lib/vite/recorder/assets/index-BhTWtUlo.js +193 -193
  335. package/lib/vite/recorder/index.html +29 -29
  336. package/lib/vite/recorder/playwright-logo.svg +9 -9
  337. package/lib/vite/traceViewer/assets/codeMirrorModule-a5XoALAZ.js +32 -32
  338. package/lib/vite/traceViewer/assets/defaultSettingsView-CJSZINFr.js +266 -266
  339. package/lib/vite/traceViewer/assets/xtermModule-CsJ4vdCR.js +9 -9
  340. package/lib/vite/traceViewer/codeMirrorModule.DYBRYzYX.css +1 -1
  341. package/lib/vite/traceViewer/defaultSettingsView.7ch9cixO.css +1 -1
  342. package/lib/vite/traceViewer/{index.Bk2uYQRV.js → index.BDwrLSGN.js} +2 -2
  343. package/lib/vite/traceViewer/index.BVu7tZDe.css +1 -1
  344. package/lib/vite/traceViewer/index.html +43 -43
  345. package/lib/vite/traceViewer/manifest.webmanifest +16 -16
  346. package/lib/vite/traceViewer/playwright-logo.svg +9 -9
  347. package/lib/vite/traceViewer/snapshot.html +21 -21
  348. package/lib/vite/traceViewer/sw.bundle.js +5 -5
  349. package/lib/vite/traceViewer/uiMode.Btcz36p_.css +1 -1
  350. package/lib/vite/traceViewer/uiMode.CQJ9SCIQ.js +5 -5
  351. package/lib/vite/traceViewer/uiMode.html +17 -17
  352. package/lib/vite/traceViewer/xtermModule.DYP7pi_n.css +32 -32
  353. package/lib/zipBundle.js +34 -34
  354. package/lib/zipBundleImpl.js +5 -5
  355. package/package.json +1 -1
  356. package/types/protocol.d.ts +23824 -23824
  357. package/types/structs.d.ts +45 -45
  358. package/types/types.d.ts +22843 -22843
@@ -1,1001 +1,1001 @@
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 crPage_exports = {};
30
- __export(crPage_exports, {
31
- CRPage: () => CRPage
32
- });
33
- module.exports = __toCommonJS(crPage_exports);
34
- var import_assert = require("../../utils/isomorphic/assert");
35
- var import_eventsHelper = require("../utils/eventsHelper");
36
- var import_stackTrace = require("../../utils/isomorphic/stackTrace");
37
- var dialog = __toESM(require("../dialog"));
38
- var dom = __toESM(require("../dom"));
39
- var frames = __toESM(require("../frames"));
40
- var import_helper = require("../helper");
41
- var network = __toESM(require("../network"));
42
- var import_page = require("../page");
43
- var import_crCoverage = require("./crCoverage");
44
- var import_crDragDrop = require("./crDragDrop");
45
- var import_crExecutionContext = require("./crExecutionContext");
46
- var import_crInput = require("./crInput");
47
- var import_crNetworkManager = require("./crNetworkManager");
48
- var import_crPdf = require("./crPdf");
49
- var import_crProtocolHelper = require("./crProtocolHelper");
50
- var import_defaultFontFamilies = require("./defaultFontFamilies");
51
- var import_errors = require("../errors");
52
- var import_protocolError = require("../protocolError");
53
- class CRPage {
54
- constructor(client, targetId, browserContext, opener, bits) {
55
- this._sessions = /* @__PURE__ */ new Map();
56
- // Holds window features for the next popup being opened via window.open,
57
- // until the popup target arrives. This could be racy if two oopifs
58
- // simultaneously call window.open with window features: the order
59
- // of their Page.windowOpen events is not guaranteed to match the order
60
- // of new popup targets.
61
- this._nextWindowOpenPopupFeatures = [];
62
- this._targetId = targetId;
63
- this._opener = opener;
64
- const dragManager = new import_crDragDrop.DragManager(this);
65
- this.rawKeyboard = new import_crInput.RawKeyboardImpl(client, browserContext._browser._platform() === "mac", dragManager);
66
- this.rawMouse = new import_crInput.RawMouseImpl(this, client, dragManager);
67
- this.rawTouchscreen = new import_crInput.RawTouchscreenImpl(client);
68
- this._pdf = new import_crPdf.CRPDF(client);
69
- this._coverage = new import_crCoverage.CRCoverage(client);
70
- this._browserContext = browserContext;
71
- this._page = new import_page.Page(this, browserContext);
72
- this.utilityWorldName = `__playwright_utility_world_${this._page.guid}`;
73
- this._networkManager = new import_crNetworkManager.CRNetworkManager(this._page, null);
74
- this.updateOffline();
75
- this.updateExtraHTTPHeaders();
76
- this.updateHttpCredentials();
77
- this.updateRequestInterception();
78
- this._mainFrameSession = new FrameSession(this, client, targetId, null);
79
- this._sessions.set(targetId, this._mainFrameSession);
80
- if (opener && !browserContext._options.noDefaultViewport) {
81
- const features = opener._nextWindowOpenPopupFeatures.shift() || [];
82
- const viewportSize = import_helper.helper.getViewportSizeFromWindowFeatures(features);
83
- if (viewportSize)
84
- this._page.setEmulatedSizeFromWindowOpen({ viewport: viewportSize, screen: viewportSize });
85
- }
86
- this._mainFrameSession._initialize(bits.hasUIWindow).then(
87
- () => this._page.reportAsNew(this._opener?._page, void 0),
88
- (error) => this._page.reportAsNew(this._opener?._page, error)
89
- );
90
- }
91
- static mainFrameSession(page) {
92
- const crPage = page.delegate;
93
- return crPage._mainFrameSession;
94
- }
95
- async _forAllFrameSessions(cb) {
96
- const frameSessions = Array.from(this._sessions.values());
97
- await Promise.all(frameSessions.map((frameSession) => {
98
- if (frameSession._isMainFrame())
99
- return cb(frameSession);
100
- return cb(frameSession).catch((e) => {
101
- if ((0, import_protocolError.isSessionClosedError)(e))
102
- return;
103
- throw e;
104
- });
105
- }));
106
- }
107
- _sessionForFrame(frame) {
108
- while (!this._sessions.has(frame._id)) {
109
- const parent = frame.parentFrame();
110
- if (!parent)
111
- throw new Error(`Frame has been detached.`);
112
- frame = parent;
113
- }
114
- return this._sessions.get(frame._id);
115
- }
116
- _sessionForHandle(handle) {
117
- const frame = handle._context.frame;
118
- return this._sessionForFrame(frame);
119
- }
120
- willBeginDownload() {
121
- this._mainFrameSession._willBeginDownload();
122
- }
123
- didClose() {
124
- for (const session of this._sessions.values())
125
- session.dispose();
126
- this._page._didClose();
127
- }
128
- async navigateFrame(frame, url, referrer) {
129
- return this._sessionForFrame(frame)._navigate(frame, url, referrer);
130
- }
131
- async updateExtraHTTPHeaders() {
132
- const headers = network.mergeHeaders([
133
- this._browserContext._options.extraHTTPHeaders,
134
- this._page.extraHTTPHeaders()
135
- ]);
136
- await this._networkManager.setExtraHTTPHeaders(headers);
137
- }
138
- async updateGeolocation() {
139
- await this._forAllFrameSessions((frame) => frame._updateGeolocation(false));
140
- }
141
- async updateOffline() {
142
- await this._networkManager.setOffline(!!this._browserContext._options.offline);
143
- }
144
- async updateHttpCredentials() {
145
- await this._networkManager.authenticate(this._browserContext._options.httpCredentials || null);
146
- }
147
- async updateEmulatedViewportSize(preserveWindowBoundaries) {
148
- await this._mainFrameSession._updateViewport(preserveWindowBoundaries);
149
- }
150
- async bringToFront() {
151
- await this._mainFrameSession._client.send("Page.bringToFront");
152
- }
153
- async updateEmulateMedia() {
154
- await this._forAllFrameSessions((frame) => frame._updateEmulateMedia());
155
- }
156
- async updateUserAgent() {
157
- await this._forAllFrameSessions((frame) => frame._updateUserAgent());
158
- }
159
- async updateRequestInterception() {
160
- await this._networkManager.setRequestInterception(this._page.needsRequestInterception());
161
- }
162
- async updateFileChooserInterception() {
163
- await this._forAllFrameSessions((frame) => frame._updateFileChooserInterception(false));
164
- }
165
- async reload() {
166
- await this._mainFrameSession._client.send("Page.reload");
167
- }
168
- async _go(delta) {
169
- const history = await this._mainFrameSession._client.send("Page.getNavigationHistory");
170
- const entry = history.entries[history.currentIndex + delta];
171
- if (!entry)
172
- return false;
173
- await this._mainFrameSession._client.send("Page.navigateToHistoryEntry", { entryId: entry.id });
174
- return true;
175
- }
176
- goBack() {
177
- return this._go(-1);
178
- }
179
- goForward() {
180
- return this._go(1);
181
- }
182
- async requestGC() {
183
- await this._mainFrameSession._client.send("HeapProfiler.collectGarbage");
184
- }
185
- async addInitScript(initScript, world = "main") {
186
- await this._forAllFrameSessions((frame) => frame._evaluateOnNewDocument(initScript, world));
187
- }
188
- async exposePlaywrightBinding() {
189
- await this._forAllFrameSessions((frame) => frame.exposePlaywrightBinding());
190
- }
191
- async removeInitScripts(initScripts) {
192
- await this._forAllFrameSessions((frame) => frame._removeEvaluatesOnNewDocument(initScripts));
193
- }
194
- async closePage(runBeforeUnload) {
195
- if (runBeforeUnload)
196
- await this._mainFrameSession._client.send("Page.close");
197
- else
198
- await this._browserContext._browser._closePage(this);
199
- }
200
- async setBackgroundColor(color) {
201
- await this._mainFrameSession._client.send("Emulation.setDefaultBackgroundColorOverride", { color });
202
- }
203
- async takeScreenshot(progress, format, documentRect, viewportRect, quality, fitsViewport, scale) {
204
- const { visualViewport } = await progress.race(this._mainFrameSession._client.send("Page.getLayoutMetrics"));
205
- if (!documentRect) {
206
- documentRect = {
207
- x: visualViewport.pageX + viewportRect.x,
208
- y: visualViewport.pageY + viewportRect.y,
209
- ...import_helper.helper.enclosingIntSize({
210
- width: viewportRect.width / visualViewport.scale,
211
- height: viewportRect.height / visualViewport.scale
212
- })
213
- };
214
- }
215
- const clip = { ...documentRect, scale: viewportRect ? visualViewport.scale : 1 };
216
- if (scale === "css") {
217
- const deviceScaleFactor = this._browserContext._options.deviceScaleFactor || 1;
218
- clip.scale /= deviceScaleFactor;
219
- }
220
- const result = await progress.race(this._mainFrameSession._client.send("Page.captureScreenshot", { format, quality, clip, captureBeyondViewport: !fitsViewport }));
221
- return Buffer.from(result.data, "base64");
222
- }
223
- async getContentFrame(handle) {
224
- return this._sessionForHandle(handle)._getContentFrame(handle);
225
- }
226
- async getOwnerFrame(handle) {
227
- return this._sessionForHandle(handle)._getOwnerFrame(handle);
228
- }
229
- async getBoundingBox(handle) {
230
- return this._sessionForHandle(handle)._getBoundingBox(handle);
231
- }
232
- async scrollRectIntoViewIfNeeded(handle, rect) {
233
- return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect);
234
- }
235
- async startScreencast(options) {
236
- await this._mainFrameSession._client.send("Page.startScreencast", {
237
- format: "jpeg",
238
- quality: options.quality,
239
- maxWidth: options.width,
240
- maxHeight: options.height
241
- });
242
- }
243
- async stopScreencast() {
244
- await this._mainFrameSession._client._sendMayFail("Page.stopScreencast");
245
- }
246
- rafCountForStablePosition() {
247
- return 1;
248
- }
249
- async getContentQuads(handle) {
250
- return this._sessionForHandle(handle)._getContentQuads(handle);
251
- }
252
- async setInputFilePaths(handle, files) {
253
- const frame = await handle.ownerFrame();
254
- if (!frame)
255
- throw new Error("Cannot set input files to detached input element");
256
- const parentSession = this._sessionForFrame(frame);
257
- await parentSession._client.send("DOM.setFileInputFiles", {
258
- objectId: handle._objectId,
259
- files
260
- });
261
- }
262
- async adoptElementHandle(handle, to) {
263
- return this._sessionForHandle(handle)._adoptElementHandle(handle, to);
264
- }
265
- async inputActionEpilogue() {
266
- await this._mainFrameSession._client.send("Page.enable").catch((e) => {
267
- });
268
- }
269
- async resetForReuse(progress) {
270
- await this.rawMouse.move(progress, -1, -1, "none", /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set(), true);
271
- }
272
- async pdf(options) {
273
- return this._pdf.generate(options);
274
- }
275
- coverage() {
276
- return this._coverage;
277
- }
278
- async getFrameElement(frame) {
279
- let parent = frame.parentFrame();
280
- if (!parent)
281
- throw new Error("Frame has been detached.");
282
- const parentSession = this._sessionForFrame(parent);
283
- const { backendNodeId } = await parentSession._client.send("DOM.getFrameOwner", { frameId: frame._id }).catch((e) => {
284
- if (e instanceof Error && e.message.includes("Frame with the given id was not found."))
285
- (0, import_stackTrace.rewriteErrorMessage)(e, "Frame has been detached.");
286
- throw e;
287
- });
288
- parent = frame.parentFrame();
289
- if (!parent)
290
- throw new Error("Frame has been detached.");
291
- return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext());
292
- }
293
- shouldToggleStyleSheetToSyncAnimations() {
294
- return false;
295
- }
296
- }
297
- class FrameSession {
298
- constructor(crPage, client, targetId, parentSession) {
299
- this._childSessions = /* @__PURE__ */ new Set();
300
- this._contextIdToContext = /* @__PURE__ */ new Map();
301
- this._eventListeners = [];
302
- this._firstNonInitialNavigationCommittedFulfill = () => {
303
- };
304
- this._firstNonInitialNavigationCommittedReject = (e) => {
305
- };
306
- // Marks the oopif session that remote -> local transition has happened in the parent.
307
- // See Target.detachedFromTarget handler for details.
308
- this._swappedIn = false;
309
- this._workerSessions = /* @__PURE__ */ new Map();
310
- this._initScriptIds = /* @__PURE__ */ new Map();
311
- this._client = client;
312
- this._crPage = crPage;
313
- this._page = crPage._page;
314
- this._targetId = targetId;
315
- this._parentSession = parentSession;
316
- if (parentSession)
317
- parentSession._childSessions.add(this);
318
- this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => {
319
- this._firstNonInitialNavigationCommittedFulfill = f;
320
- this._firstNonInitialNavigationCommittedReject = r;
321
- });
322
- this._firstNonInitialNavigationCommittedPromise.catch(() => {
323
- });
324
- }
325
- _isMainFrame() {
326
- return this._targetId === this._crPage._targetId;
327
- }
328
- _addRendererListeners() {
329
- this._eventListeners.push(...[
330
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Log.entryAdded", (event) => this._onLogEntryAdded(event)),
331
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.fileChooserOpened", (event) => this._onFileChooserOpened(event)),
332
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameAttached", (event) => this._onFrameAttached(event.frameId, event.parentFrameId)),
333
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameDetached", (event) => this._onFrameDetached(event.frameId, event.reason)),
334
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameNavigated", (event) => this._onFrameNavigated(event.frame, false)),
335
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameRequestedNavigation", (event) => this._onFrameRequestedNavigation(event)),
336
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.javascriptDialogOpening", (event) => this._onDialog(event)),
337
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.navigatedWithinDocument", (event) => this._onFrameNavigatedWithinDocument(event.frameId, event.url)),
338
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.bindingCalled", (event) => this._onBindingCalled(event)),
339
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.consoleAPICalled", (event) => this._onConsoleAPI(event)),
340
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.exceptionThrown", (exception) => this._handleException(exception.exceptionDetails)),
341
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextCreated", (event) => this._onExecutionContextCreated(event.context)),
342
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextDestroyed", (event) => this._onExecutionContextDestroyed(event.executionContextId)),
343
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextsCleared", (event) => this._onExecutionContextsCleared())
344
- ]);
345
- }
346
- _addBrowserListeners() {
347
- this._eventListeners.push(...[
348
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Target.attachedToTarget", (event) => this._onAttachedToTarget(event)),
349
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Target.detachedFromTarget", (event) => this._onDetachedFromTarget(event)),
350
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Inspector.targetCrashed", (event) => this._onTargetCrashed()),
351
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.screencastFrame", (event) => this._onScreencastFrame(event)),
352
- import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.windowOpen", (event) => this._onWindowOpen(event))
353
- ]);
354
- }
355
- async _initialize(hasUIWindow) {
356
- if (!this._page.isStorageStatePage && hasUIWindow && !this._crPage._browserContext._browser.isClank() && !this._crPage._browserContext._options.noDefaultViewport) {
357
- const { windowId } = await this._client.send("Browser.getWindowForTarget");
358
- this._windowId = windowId;
359
- }
360
- let videoOptions;
361
- if (!this._page.isStorageStatePage && this._isMainFrame() && hasUIWindow)
362
- videoOptions = this._crPage._page.screencast.launchVideoRecorder();
363
- let lifecycleEventsEnabled;
364
- if (!this._isMainFrame())
365
- this._addRendererListeners();
366
- this._addBrowserListeners();
367
- this._bufferedAttachedToTargetEvents = [];
368
- const promises = [
369
- this._client.send("Page.enable"),
370
- this._client.send("Page.getFrameTree").then(({ frameTree }) => {
371
- if (this._isMainFrame()) {
372
- this._handleFrameTree(frameTree);
373
- this._addRendererListeners();
374
- }
375
- const attachedToTargetEvents = this._bufferedAttachedToTargetEvents || [];
376
- this._bufferedAttachedToTargetEvents = void 0;
377
- for (const event of attachedToTargetEvents)
378
- this._onAttachedToTarget(event);
379
- const localFrames = this._isMainFrame() ? this._page.frames() : [this._page.frameManager.frame(this._targetId)];
380
- for (const frame of localFrames) {
381
- this._client._sendMayFail("Page.createIsolatedWorld", {
382
- frameId: frame._id,
383
- grantUniveralAccess: true,
384
- worldName: this._crPage.utilityWorldName
385
- });
386
- }
387
- const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ":";
388
- if (isInitialEmptyPage) {
389
- lifecycleEventsEnabled.catch((e) => {
390
- }).then(() => {
391
- this._eventListeners.push(import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.lifecycleEvent", (event) => this._onLifecycleEvent(event)));
392
- });
393
- } else {
394
- this._firstNonInitialNavigationCommittedFulfill();
395
- this._eventListeners.push(import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.lifecycleEvent", (event) => this._onLifecycleEvent(event)));
396
- }
397
- }),
398
- this._client.send("Log.enable", {}),
399
- lifecycleEventsEnabled = this._client.send("Page.setLifecycleEventsEnabled", { enabled: true }),
400
- this._client.send("Runtime.enable", {}),
401
- this._client.send("Page.addScriptToEvaluateOnNewDocument", {
402
- source: "",
403
- worldName: this._crPage.utilityWorldName
404
- }),
405
- this._crPage._networkManager.addSession(this._client, void 0, this._isMainFrame()),
406
- this._client.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true })
407
- ];
408
- if (!this._page.isStorageStatePage) {
409
- if (this._crPage._browserContext.needsPlaywrightBinding())
410
- promises.push(this.exposePlaywrightBinding());
411
- if (this._isMainFrame())
412
- promises.push(this._client.send("Emulation.setFocusEmulationEnabled", { enabled: true }));
413
- const options = this._crPage._browserContext._options;
414
- if (options.bypassCSP)
415
- promises.push(this._client.send("Page.setBypassCSP", { enabled: true }));
416
- if (options.ignoreHTTPSErrors || options.internalIgnoreHTTPSErrors)
417
- promises.push(this._client.send("Security.setIgnoreCertificateErrors", { ignore: true }));
418
- if (this._isMainFrame())
419
- promises.push(this._updateViewport());
420
- if (options.hasTouch)
421
- promises.push(this._client.send("Emulation.setTouchEmulationEnabled", { enabled: true }));
422
- if (options.javaScriptEnabled === false)
423
- promises.push(this._client.send("Emulation.setScriptExecutionDisabled", { value: true }));
424
- if (options.userAgent || options.locale)
425
- promises.push(this._updateUserAgent());
426
- if (options.locale)
427
- promises.push(emulateLocale(this._client, options.locale));
428
- if (options.timezoneId)
429
- promises.push(emulateTimezone(this._client, options.timezoneId));
430
- if (!this._crPage._browserContext._browser.options.headful)
431
- promises.push(this._setDefaultFontFamilies(this._client));
432
- promises.push(this._updateGeolocation(true));
433
- promises.push(this._updateEmulateMedia());
434
- promises.push(this._updateFileChooserInterception(true));
435
- for (const initScript of this._crPage._page.allInitScripts())
436
- promises.push(this._evaluateOnNewDocument(
437
- initScript,
438
- "main",
439
- true
440
- /* runImmediately */
441
- ));
442
- if (videoOptions)
443
- promises.push(this._crPage._page.screencast.startVideoRecording(videoOptions));
444
- }
445
- promises.push(this._client.send("Runtime.runIfWaitingForDebugger"));
446
- promises.push(this._firstNonInitialNavigationCommittedPromise);
447
- await Promise.all(promises);
448
- }
449
- dispose() {
450
- this._firstNonInitialNavigationCommittedReject(new import_errors.TargetClosedError(this._page.closeReason()));
451
- for (const childSession of this._childSessions)
452
- childSession.dispose();
453
- if (this._parentSession)
454
- this._parentSession._childSessions.delete(this);
455
- import_eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);
456
- this._crPage._networkManager.removeSession(this._client);
457
- this._crPage._sessions.delete(this._targetId);
458
- this._client.dispose();
459
- }
460
- async _navigate(frame, url, referrer) {
461
- const response = await this._client.send("Page.navigate", { url, referrer, frameId: frame._id, referrerPolicy: "unsafeUrl" });
462
- if (response.isDownload)
463
- throw new frames.NavigationAbortedError(response.loaderId, "Download is starting");
464
- if (response.errorText)
465
- throw new frames.NavigationAbortedError(response.loaderId, `${response.errorText} at ${url}`);
466
- return { newDocumentId: response.loaderId };
467
- }
468
- _onLifecycleEvent(event) {
469
- if (this._eventBelongsToStaleFrame(event.frameId))
470
- return;
471
- if (event.name === "load")
472
- this._page.frameManager.frameLifecycleEvent(event.frameId, "load");
473
- else if (event.name === "DOMContentLoaded")
474
- this._page.frameManager.frameLifecycleEvent(event.frameId, "domcontentloaded");
475
- }
476
- _handleFrameTree(frameTree) {
477
- this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);
478
- this._onFrameNavigated(frameTree.frame, true);
479
- if (!frameTree.childFrames)
480
- return;
481
- for (const child of frameTree.childFrames)
482
- this._handleFrameTree(child);
483
- }
484
- _eventBelongsToStaleFrame(frameId) {
485
- const frame = this._page.frameManager.frame(frameId);
486
- if (!frame)
487
- return true;
488
- const session = this._crPage._sessionForFrame(frame);
489
- return session && session !== this && !session._swappedIn;
490
- }
491
- _onFrameAttached(frameId, parentFrameId) {
492
- const frameSession = this._crPage._sessions.get(frameId);
493
- if (frameSession && frameId !== this._targetId) {
494
- frameSession._swappedIn = true;
495
- const frame = this._page.frameManager.frame(frameId);
496
- if (frame)
497
- this._page.frameManager.removeChildFramesRecursively(frame);
498
- return;
499
- }
500
- if (parentFrameId && !this._page.frameManager.frame(parentFrameId)) {
501
- return;
502
- }
503
- this._page.frameManager.frameAttached(frameId, parentFrameId);
504
- }
505
- _onFrameNavigated(framePayload, initial) {
506
- if (this._eventBelongsToStaleFrame(framePayload.id))
507
- return;
508
- this._page.frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ""), framePayload.name || "", framePayload.loaderId, initial);
509
- if (!initial)
510
- this._firstNonInitialNavigationCommittedFulfill();
511
- }
512
- _onFrameRequestedNavigation(payload) {
513
- if (this._eventBelongsToStaleFrame(payload.frameId))
514
- return;
515
- if (payload.disposition === "currentTab")
516
- this._page.frameManager.frameRequestedNavigation(payload.frameId);
517
- }
518
- _onFrameNavigatedWithinDocument(frameId, url) {
519
- if (this._eventBelongsToStaleFrame(frameId))
520
- return;
521
- this._page.frameManager.frameCommittedSameDocumentNavigation(frameId, url);
522
- }
523
- _onFrameDetached(frameId, reason) {
524
- if (this._crPage._sessions.has(frameId)) {
525
- return;
526
- }
527
- if (reason === "swap") {
528
- const frame = this._page.frameManager.frame(frameId);
529
- if (frame)
530
- this._page.frameManager.removeChildFramesRecursively(frame);
531
- return;
532
- }
533
- this._page.frameManager.frameDetached(frameId);
534
- }
535
- _onExecutionContextCreated(contextPayload) {
536
- const frame = contextPayload.auxData ? this._page.frameManager.frame(contextPayload.auxData.frameId) : null;
537
- if (!frame || this._eventBelongsToStaleFrame(frame._id))
538
- return;
539
- const delegate = new import_crExecutionContext.CRExecutionContext(this._client, contextPayload);
540
- let worldName = null;
541
- if (contextPayload.auxData && !!contextPayload.auxData.isDefault)
542
- worldName = "main";
543
- else if (contextPayload.name === this._crPage.utilityWorldName)
544
- worldName = "utility";
545
- const context = new dom.FrameExecutionContext(delegate, frame, worldName);
546
- if (worldName)
547
- frame._contextCreated(worldName, context);
548
- this._contextIdToContext.set(contextPayload.id, context);
549
- }
550
- _onExecutionContextDestroyed(executionContextId) {
551
- const context = this._contextIdToContext.get(executionContextId);
552
- if (!context)
553
- return;
554
- this._contextIdToContext.delete(executionContextId);
555
- context.frame._contextDestroyed(context);
556
- }
557
- _onExecutionContextsCleared() {
558
- for (const contextId of Array.from(this._contextIdToContext.keys()))
559
- this._onExecutionContextDestroyed(contextId);
560
- }
561
- _onAttachedToTarget(event) {
562
- if (this._bufferedAttachedToTargetEvents) {
563
- this._bufferedAttachedToTargetEvents.push(event);
564
- return;
565
- }
566
- const session = this._client.createChildSession(event.sessionId);
567
- if (event.targetInfo.type === "iframe") {
568
- const targetId = event.targetInfo.targetId;
569
- let frame = this._page.frameManager.frame(targetId);
570
- if (!frame && event.targetInfo.parentFrameId) {
571
- frame = this._page.frameManager.frameAttached(targetId, event.targetInfo.parentFrameId);
572
- }
573
- if (!frame)
574
- return;
575
- this._page.frameManager.removeChildFramesRecursively(frame);
576
- for (const [contextId, context] of this._contextIdToContext) {
577
- if (context.frame === frame)
578
- this._onExecutionContextDestroyed(contextId);
579
- }
580
- const frameSession = new FrameSession(this._crPage, session, targetId, this);
581
- this._crPage._sessions.set(targetId, frameSession);
582
- frameSession._initialize(false).catch((e) => e);
583
- return;
584
- }
585
- if (event.targetInfo.type !== "worker") {
586
- session.detach().catch(() => {
587
- });
588
- return;
589
- }
590
- const url = event.targetInfo.url;
591
- const worker = new import_page.Worker(this._page, url);
592
- this._page.addWorker(event.sessionId, worker);
593
- this._workerSessions.set(event.sessionId, session);
594
- session.once("Runtime.executionContextCreated", async (event2) => {
595
- worker.createExecutionContext(new import_crExecutionContext.CRExecutionContext(session, event2.context));
596
- });
597
- if (this._crPage._browserContext._browser.majorVersion() >= 143)
598
- session.on("Inspector.workerScriptLoaded", () => worker.workerScriptLoaded());
599
- else
600
- worker.workerScriptLoaded();
601
- session._sendMayFail("Runtime.enable");
602
- this._crPage._networkManager.addSession(session, this._page.frameManager.frame(this._targetId) ?? void 0).catch(() => {
603
- });
604
- session._sendMayFail("Runtime.runIfWaitingForDebugger");
605
- session._sendMayFail("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
606
- session.on("Target.attachedToTarget", (event2) => this._onAttachedToTarget(event2));
607
- session.on("Target.detachedFromTarget", (event2) => this._onDetachedFromTarget(event2));
608
- session.on("Runtime.consoleAPICalled", (event2) => {
609
- const args = event2.args.map((o) => (0, import_crExecutionContext.createHandle)(worker.existingExecutionContext, o));
610
- this._page.addConsoleMessage(worker, event2.type, args, (0, import_crProtocolHelper.toConsoleMessageLocation)(event2.stackTrace));
611
- });
612
- session.on("Runtime.exceptionThrown", (exception) => this._page.addPageError((0, import_crProtocolHelper.exceptionToError)(exception.exceptionDetails)));
613
- }
614
- _onDetachedFromTarget(event) {
615
- const workerSession = this._workerSessions.get(event.sessionId);
616
- if (workerSession) {
617
- workerSession.dispose();
618
- this._page.removeWorker(event.sessionId);
619
- return;
620
- }
621
- const childFrameSession = this._crPage._sessions.get(event.targetId);
622
- if (!childFrameSession)
623
- return;
624
- if (childFrameSession._swappedIn) {
625
- childFrameSession.dispose();
626
- return;
627
- }
628
- this._client.send("Page.enable").catch((e) => null).then(() => {
629
- if (!childFrameSession._swappedIn)
630
- this._page.frameManager.frameDetached(event.targetId);
631
- childFrameSession.dispose();
632
- });
633
- }
634
- _onWindowOpen(event) {
635
- this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);
636
- }
637
- async _onConsoleAPI(event) {
638
- if (event.executionContextId === 0) {
639
- return;
640
- }
641
- const context = this._contextIdToContext.get(event.executionContextId);
642
- if (!context)
643
- return;
644
- const values = event.args.map((arg) => (0, import_crExecutionContext.createHandle)(context, arg));
645
- this._page.addConsoleMessage(null, event.type, values, (0, import_crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));
646
- }
647
- async _onBindingCalled(event) {
648
- const pageOrError = await this._crPage._page.waitForInitializedOrError();
649
- if (!(pageOrError instanceof Error)) {
650
- const context = this._contextIdToContext.get(event.executionContextId);
651
- if (context)
652
- await this._page.onBindingCalled(event.payload, context);
653
- }
654
- }
655
- _onDialog(event) {
656
- if (!this._page.frameManager.frame(this._targetId))
657
- return;
658
- this._page.browserContext.dialogManager.dialogDidOpen(new dialog.Dialog(
659
- this._page,
660
- event.type,
661
- event.message,
662
- async (accept, promptText) => {
663
- if (this._isMainFrame() && event.type === "beforeunload" && !accept)
664
- this._page.frameManager.frameAbortedNavigation(this._page.mainFrame()._id, "navigation cancelled by beforeunload dialog");
665
- await this._client.send("Page.handleJavaScriptDialog", { accept, promptText });
666
- },
667
- event.defaultPrompt
668
- ));
669
- }
670
- _handleException(exceptionDetails) {
671
- this._page.addPageError((0, import_crProtocolHelper.exceptionToError)(exceptionDetails));
672
- }
673
- async _onTargetCrashed() {
674
- this._client._markAsCrashed();
675
- this._page._didCrash();
676
- }
677
- _onLogEntryAdded(event) {
678
- const { level, text, args, source, url, lineNumber } = event.entry;
679
- if (args)
680
- args.map((arg) => (0, import_crProtocolHelper.releaseObject)(this._client, arg.objectId));
681
- if (source !== "worker") {
682
- const location = {
683
- url: url || "",
684
- lineNumber: lineNumber || 0,
685
- columnNumber: 0
686
- };
687
- this._page.addConsoleMessage(null, level, [], location, text);
688
- }
689
- }
690
- async _onFileChooserOpened(event) {
691
- if (!event.backendNodeId)
692
- return;
693
- const frame = this._page.frameManager.frame(event.frameId);
694
- if (!frame)
695
- return;
696
- let handle;
697
- try {
698
- const utilityContext = await frame._utilityContext();
699
- handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext);
700
- } catch (e) {
701
- return;
702
- }
703
- await this._page._onFileChooserOpened(handle);
704
- }
705
- _willBeginDownload() {
706
- if (!this._crPage._page.initializedOrUndefined()) {
707
- this._firstNonInitialNavigationCommittedReject(new Error("Starting new page download"));
708
- }
709
- }
710
- _onScreencastFrame(payload) {
711
- this._page.screencast.throttleFrameAck(() => {
712
- this._client._sendMayFail("Page.screencastFrameAck", { sessionId: payload.sessionId });
713
- });
714
- const buffer = Buffer.from(payload.data, "base64");
715
- this._page.emit(import_page.Page.Events.ScreencastFrame, {
716
- buffer,
717
- frameSwapWallTime: payload.metadata.timestamp ? payload.metadata.timestamp * 1e3 : Date.now(),
718
- width: payload.metadata.deviceWidth,
719
- height: payload.metadata.deviceHeight
720
- });
721
- }
722
- async _updateGeolocation(initial) {
723
- const geolocation = this._crPage._browserContext._options.geolocation;
724
- if (!initial || geolocation)
725
- await this._client.send("Emulation.setGeolocationOverride", geolocation || {});
726
- }
727
- async _updateViewport(preserveWindowBoundaries) {
728
- if (this._crPage._browserContext._browser.isClank())
729
- return;
730
- (0, import_assert.assert)(this._isMainFrame());
731
- const options = this._crPage._browserContext._options;
732
- const emulatedSize = this._page.emulatedSize();
733
- if (!emulatedSize)
734
- return;
735
- const viewportSize = emulatedSize.viewport;
736
- const screenSize = emulatedSize.screen;
737
- const isLandscape = screenSize.width > screenSize.height;
738
- const metricsOverride = {
739
- mobile: !!options.isMobile,
740
- width: viewportSize.width,
741
- height: viewportSize.height,
742
- screenWidth: screenSize.width,
743
- screenHeight: screenSize.height,
744
- deviceScaleFactor: options.deviceScaleFactor || 1,
745
- screenOrientation: !!options.isMobile ? isLandscape ? { angle: 90, type: "landscapePrimary" } : { angle: 0, type: "portraitPrimary" } : { angle: 0, type: "landscapePrimary" },
746
- dontSetVisibleSize: preserveWindowBoundaries
747
- };
748
- if (JSON.stringify(this._metricsOverride) === JSON.stringify(metricsOverride))
749
- return;
750
- const promises = [];
751
- if (!preserveWindowBoundaries && this._windowId) {
752
- let insets = { width: 0, height: 0 };
753
- if (this._crPage._browserContext._browser.options.headful) {
754
- insets = { width: 24, height: 88 };
755
- if (process.platform === "win32")
756
- insets = { width: 16, height: 88 };
757
- else if (process.platform === "linux")
758
- insets = { width: 8, height: 85 };
759
- else if (process.platform === "darwin")
760
- insets = { width: 2, height: 80 };
761
- if (this._crPage._browserContext.isPersistentContext()) {
762
- insets.height += 46;
763
- }
764
- }
765
- promises.push(this.setWindowBounds({
766
- width: viewportSize.width + insets.width,
767
- height: viewportSize.height + insets.height
768
- }));
769
- }
770
- promises.push(this._client.send("Emulation.setDeviceMetricsOverride", metricsOverride));
771
- await Promise.all(promises);
772
- this._metricsOverride = metricsOverride;
773
- }
774
- async windowBounds() {
775
- const { bounds } = await this._client.send("Browser.getWindowBounds", {
776
- windowId: this._windowId
777
- });
778
- return bounds;
779
- }
780
- async setWindowBounds(bounds) {
781
- return await this._client.send("Browser.setWindowBounds", {
782
- windowId: this._windowId,
783
- bounds
784
- });
785
- }
786
- async _updateEmulateMedia() {
787
- const emulatedMedia = this._page.emulatedMedia();
788
- const media = emulatedMedia.media === "no-override" ? "" : emulatedMedia.media;
789
- const colorScheme = emulatedMedia.colorScheme === "no-override" ? "" : emulatedMedia.colorScheme;
790
- const reducedMotion = emulatedMedia.reducedMotion === "no-override" ? "" : emulatedMedia.reducedMotion;
791
- const forcedColors = emulatedMedia.forcedColors === "no-override" ? "" : emulatedMedia.forcedColors;
792
- const contrast = emulatedMedia.contrast === "no-override" ? "" : emulatedMedia.contrast;
793
- const features = [
794
- { name: "prefers-color-scheme", value: colorScheme },
795
- { name: "prefers-reduced-motion", value: reducedMotion },
796
- { name: "forced-colors", value: forcedColors },
797
- { name: "prefers-contrast", value: contrast }
798
- ];
799
- await this._client.send("Emulation.setEmulatedMedia", { media, features });
800
- }
801
- async _updateUserAgent() {
802
- const options = this._crPage._browserContext._options;
803
- await this._client.send("Emulation.setUserAgentOverride", {
804
- userAgent: options.userAgent || "",
805
- acceptLanguage: options.locale,
806
- userAgentMetadata: calculateUserAgentMetadata(options)
807
- });
808
- }
809
- async _setDefaultFontFamilies(session) {
810
- const fontFamilies = import_defaultFontFamilies.platformToFontFamilies[this._crPage._browserContext._browser._platform()];
811
- await session.send("Page.setFontFamilies", fontFamilies);
812
- }
813
- async _updateFileChooserInterception(initial) {
814
- const enabled = this._page.fileChooserIntercepted();
815
- if (initial && !enabled)
816
- return;
817
- await this._client.send("Page.setInterceptFileChooserDialog", { enabled }).catch(() => {
818
- });
819
- }
820
- async _evaluateOnNewDocument(initScript, world, runImmediately) {
821
- const worldName = world === "utility" ? this._crPage.utilityWorldName : void 0;
822
- const { identifier } = await this._client.send("Page.addScriptToEvaluateOnNewDocument", { source: initScript.source, worldName, runImmediately });
823
- this._initScriptIds.set(initScript, identifier);
824
- }
825
- async _removeEvaluatesOnNewDocument(initScripts) {
826
- const ids = [];
827
- for (const script of initScripts) {
828
- const id = this._initScriptIds.get(script);
829
- if (id)
830
- ids.push(id);
831
- this._initScriptIds.delete(script);
832
- }
833
- await Promise.all(ids.map((identifier) => this._client.send("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => {
834
- })));
835
- }
836
- async exposePlaywrightBinding() {
837
- await this._client.send("Runtime.addBinding", { name: import_page.PageBinding.kBindingName });
838
- }
839
- async _getContentFrame(handle) {
840
- const nodeInfo = await this._client.send("DOM.describeNode", {
841
- objectId: handle._objectId
842
- });
843
- if (!nodeInfo || typeof nodeInfo.node.frameId !== "string")
844
- return null;
845
- return this._page.frameManager.frame(nodeInfo.node.frameId);
846
- }
847
- async _getOwnerFrame(handle) {
848
- const documentElement = await handle.evaluateHandle((node) => {
849
- const doc = node;
850
- if (doc.documentElement && doc.documentElement.ownerDocument === doc)
851
- return doc.documentElement;
852
- return node.ownerDocument ? node.ownerDocument.documentElement : null;
853
- });
854
- if (!documentElement)
855
- return null;
856
- if (!documentElement._objectId)
857
- return null;
858
- const nodeInfo = await this._client.send("DOM.describeNode", {
859
- objectId: documentElement._objectId
860
- });
861
- const frameId = nodeInfo && typeof nodeInfo.node.frameId === "string" ? nodeInfo.node.frameId : null;
862
- documentElement.dispose();
863
- return frameId;
864
- }
865
- async _getBoundingBox(handle) {
866
- const result = await this._client._sendMayFail("DOM.getBoxModel", {
867
- objectId: handle._objectId
868
- });
869
- if (!result)
870
- return null;
871
- const quad = result.model.border;
872
- const x = Math.min(quad[0], quad[2], quad[4], quad[6]);
873
- const y = Math.min(quad[1], quad[3], quad[5], quad[7]);
874
- const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;
875
- const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;
876
- const position = await this._framePosition();
877
- if (!position)
878
- return null;
879
- return { x: x + position.x, y: y + position.y, width, height };
880
- }
881
- async _framePosition() {
882
- const frame = this._page.frameManager.frame(this._targetId);
883
- if (!frame)
884
- return null;
885
- if (frame === this._page.mainFrame())
886
- return { x: 0, y: 0 };
887
- const element = await frame.frameElement();
888
- const box = await element.boundingBox();
889
- return box;
890
- }
891
- async _scrollRectIntoViewIfNeeded(handle, rect) {
892
- return await this._client.send("DOM.scrollIntoViewIfNeeded", {
893
- objectId: handle._objectId,
894
- rect
895
- }).then(() => "done").catch((e) => {
896
- if (e instanceof Error && e.message.includes("Node does not have a layout object"))
897
- return "error:notvisible";
898
- if (e instanceof Error && e.message.includes("Node is detached from document"))
899
- return "error:notconnected";
900
- throw e;
901
- });
902
- }
903
- async _getContentQuads(handle) {
904
- const result = await this._client._sendMayFail("DOM.getContentQuads", {
905
- objectId: handle._objectId
906
- });
907
- if (!result)
908
- return null;
909
- const position = await this._framePosition();
910
- if (!position)
911
- return null;
912
- return result.quads.map((quad) => [
913
- { x: quad[0] + position.x, y: quad[1] + position.y },
914
- { x: quad[2] + position.x, y: quad[3] + position.y },
915
- { x: quad[4] + position.x, y: quad[5] + position.y },
916
- { x: quad[6] + position.x, y: quad[7] + position.y }
917
- ]);
918
- }
919
- async _adoptElementHandle(handle, to) {
920
- const nodeInfo = await this._client.send("DOM.describeNode", {
921
- objectId: handle._objectId
922
- });
923
- return this._adoptBackendNodeId(nodeInfo.node.backendNodeId, to);
924
- }
925
- async _adoptBackendNodeId(backendNodeId, to) {
926
- const result = await this._client._sendMayFail("DOM.resolveNode", {
927
- backendNodeId,
928
- executionContextId: to.delegate._contextId
929
- });
930
- if (!result || result.object.subtype === "null")
931
- throw new Error(dom.kUnableToAdoptErrorMessage);
932
- return (0, import_crExecutionContext.createHandle)(to, result.object).asElement();
933
- }
934
- }
935
- async function emulateLocale(session, locale) {
936
- try {
937
- await session.send("Emulation.setLocaleOverride", { locale });
938
- } catch (exception) {
939
- if (exception.message.includes("Another locale override is already in effect"))
940
- return;
941
- throw exception;
942
- }
943
- }
944
- async function emulateTimezone(session, timezoneId) {
945
- try {
946
- await session.send("Emulation.setTimezoneOverride", { timezoneId });
947
- } catch (exception) {
948
- if (exception.message.includes("Timezone override is already in effect"))
949
- return;
950
- if (exception.message.includes("Invalid timezone"))
951
- throw new Error(`Invalid timezone ID: ${timezoneId}`);
952
- throw exception;
953
- }
954
- }
955
- function calculateUserAgentMetadata(options) {
956
- const ua = options.userAgent;
957
- if (!ua)
958
- return void 0;
959
- const metadata = {
960
- mobile: !!options.isMobile,
961
- model: "",
962
- architecture: "x86",
963
- platform: "Windows",
964
- platformVersion: ""
965
- };
966
- const androidMatch = ua.match(/Android (\d+(\.\d+)?(\.\d+)?)/);
967
- const iPhoneMatch = ua.match(/iPhone OS (\d+(_\d+)?)/);
968
- const iPadMatch = ua.match(/iPad; CPU OS (\d+(_\d+)?)/);
969
- const macOSMatch = ua.match(/Mac OS X (\d+(_\d+)?(_\d+)?)/);
970
- const windowsMatch = ua.match(/Windows\D+(\d+(\.\d+)?(\.\d+)?)/);
971
- if (androidMatch) {
972
- metadata.platform = "Android";
973
- metadata.platformVersion = androidMatch[1];
974
- metadata.architecture = "arm";
975
- } else if (iPhoneMatch) {
976
- metadata.platform = "iOS";
977
- metadata.platformVersion = iPhoneMatch[1];
978
- metadata.architecture = "arm";
979
- } else if (iPadMatch) {
980
- metadata.platform = "iOS";
981
- metadata.platformVersion = iPadMatch[1];
982
- metadata.architecture = "arm";
983
- } else if (macOSMatch) {
984
- metadata.platform = "macOS";
985
- metadata.platformVersion = macOSMatch[1];
986
- if (!ua.includes("Intel"))
987
- metadata.architecture = "arm";
988
- } else if (windowsMatch) {
989
- metadata.platform = "Windows";
990
- metadata.platformVersion = windowsMatch[1];
991
- } else if (ua.toLowerCase().includes("linux")) {
992
- metadata.platform = "Linux";
993
- }
994
- if (ua.includes("ARM"))
995
- metadata.architecture = "arm";
996
- return metadata;
997
- }
998
- // Annotate the CommonJS export names for ESM import in node:
999
- 0 && (module.exports = {
1000
- CRPage
1001
- });
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 crPage_exports = {};
30
+ __export(crPage_exports, {
31
+ CRPage: () => CRPage
32
+ });
33
+ module.exports = __toCommonJS(crPage_exports);
34
+ var import_assert = require("../../utils/isomorphic/assert");
35
+ var import_eventsHelper = require("../utils/eventsHelper");
36
+ var import_stackTrace = require("../../utils/isomorphic/stackTrace");
37
+ var dialog = __toESM(require("../dialog"));
38
+ var dom = __toESM(require("../dom"));
39
+ var frames = __toESM(require("../frames"));
40
+ var import_helper = require("../helper");
41
+ var network = __toESM(require("../network"));
42
+ var import_page = require("../page");
43
+ var import_crCoverage = require("./crCoverage");
44
+ var import_crDragDrop = require("./crDragDrop");
45
+ var import_crExecutionContext = require("./crExecutionContext");
46
+ var import_crInput = require("./crInput");
47
+ var import_crNetworkManager = require("./crNetworkManager");
48
+ var import_crPdf = require("./crPdf");
49
+ var import_crProtocolHelper = require("./crProtocolHelper");
50
+ var import_defaultFontFamilies = require("./defaultFontFamilies");
51
+ var import_errors = require("../errors");
52
+ var import_protocolError = require("../protocolError");
53
+ class CRPage {
54
+ constructor(client, targetId, browserContext, opener, bits) {
55
+ this._sessions = /* @__PURE__ */ new Map();
56
+ // Holds window features for the next popup being opened via window.open,
57
+ // until the popup target arrives. This could be racy if two oopifs
58
+ // simultaneously call window.open with window features: the order
59
+ // of their Page.windowOpen events is not guaranteed to match the order
60
+ // of new popup targets.
61
+ this._nextWindowOpenPopupFeatures = [];
62
+ this._targetId = targetId;
63
+ this._opener = opener;
64
+ const dragManager = new import_crDragDrop.DragManager(this);
65
+ this.rawKeyboard = new import_crInput.RawKeyboardImpl(client, browserContext._browser._platform() === "mac", dragManager);
66
+ this.rawMouse = new import_crInput.RawMouseImpl(this, client, dragManager);
67
+ this.rawTouchscreen = new import_crInput.RawTouchscreenImpl(client);
68
+ this._pdf = new import_crPdf.CRPDF(client);
69
+ this._coverage = new import_crCoverage.CRCoverage(client);
70
+ this._browserContext = browserContext;
71
+ this._page = new import_page.Page(this, browserContext);
72
+ this.utilityWorldName = `__playwright_utility_world_${this._page.guid}`;
73
+ this._networkManager = new import_crNetworkManager.CRNetworkManager(this._page, null);
74
+ this.updateOffline();
75
+ this.updateExtraHTTPHeaders();
76
+ this.updateHttpCredentials();
77
+ this.updateRequestInterception();
78
+ this._mainFrameSession = new FrameSession(this, client, targetId, null);
79
+ this._sessions.set(targetId, this._mainFrameSession);
80
+ if (opener && !browserContext._options.noDefaultViewport) {
81
+ const features = opener._nextWindowOpenPopupFeatures.shift() || [];
82
+ const viewportSize = import_helper.helper.getViewportSizeFromWindowFeatures(features);
83
+ if (viewportSize)
84
+ this._page.setEmulatedSizeFromWindowOpen({ viewport: viewportSize, screen: viewportSize });
85
+ }
86
+ this._mainFrameSession._initialize(bits.hasUIWindow).then(
87
+ () => this._page.reportAsNew(this._opener?._page, void 0),
88
+ (error) => this._page.reportAsNew(this._opener?._page, error)
89
+ );
90
+ }
91
+ static mainFrameSession(page) {
92
+ const crPage = page.delegate;
93
+ return crPage._mainFrameSession;
94
+ }
95
+ async _forAllFrameSessions(cb) {
96
+ const frameSessions = Array.from(this._sessions.values());
97
+ await Promise.all(frameSessions.map((frameSession) => {
98
+ if (frameSession._isMainFrame())
99
+ return cb(frameSession);
100
+ return cb(frameSession).catch((e) => {
101
+ if ((0, import_protocolError.isSessionClosedError)(e))
102
+ return;
103
+ throw e;
104
+ });
105
+ }));
106
+ }
107
+ _sessionForFrame(frame) {
108
+ while (!this._sessions.has(frame._id)) {
109
+ const parent = frame.parentFrame();
110
+ if (!parent)
111
+ throw new Error(`Frame has been detached.`);
112
+ frame = parent;
113
+ }
114
+ return this._sessions.get(frame._id);
115
+ }
116
+ _sessionForHandle(handle) {
117
+ const frame = handle._context.frame;
118
+ return this._sessionForFrame(frame);
119
+ }
120
+ willBeginDownload() {
121
+ this._mainFrameSession._willBeginDownload();
122
+ }
123
+ didClose() {
124
+ for (const session of this._sessions.values())
125
+ session.dispose();
126
+ this._page._didClose();
127
+ }
128
+ async navigateFrame(frame, url, referrer) {
129
+ return this._sessionForFrame(frame)._navigate(frame, url, referrer);
130
+ }
131
+ async updateExtraHTTPHeaders() {
132
+ const headers = network.mergeHeaders([
133
+ this._browserContext._options.extraHTTPHeaders,
134
+ this._page.extraHTTPHeaders()
135
+ ]);
136
+ await this._networkManager.setExtraHTTPHeaders(headers);
137
+ }
138
+ async updateGeolocation() {
139
+ await this._forAllFrameSessions((frame) => frame._updateGeolocation(false));
140
+ }
141
+ async updateOffline() {
142
+ await this._networkManager.setOffline(!!this._browserContext._options.offline);
143
+ }
144
+ async updateHttpCredentials() {
145
+ await this._networkManager.authenticate(this._browserContext._options.httpCredentials || null);
146
+ }
147
+ async updateEmulatedViewportSize(preserveWindowBoundaries) {
148
+ await this._mainFrameSession._updateViewport(preserveWindowBoundaries);
149
+ }
150
+ async bringToFront() {
151
+ await this._mainFrameSession._client.send("Page.bringToFront");
152
+ }
153
+ async updateEmulateMedia() {
154
+ await this._forAllFrameSessions((frame) => frame._updateEmulateMedia());
155
+ }
156
+ async updateUserAgent() {
157
+ await this._forAllFrameSessions((frame) => frame._updateUserAgent());
158
+ }
159
+ async updateRequestInterception() {
160
+ await this._networkManager.setRequestInterception(this._page.needsRequestInterception());
161
+ }
162
+ async updateFileChooserInterception() {
163
+ await this._forAllFrameSessions((frame) => frame._updateFileChooserInterception(false));
164
+ }
165
+ async reload() {
166
+ await this._mainFrameSession._client.send("Page.reload");
167
+ }
168
+ async _go(delta) {
169
+ const history = await this._mainFrameSession._client.send("Page.getNavigationHistory");
170
+ const entry = history.entries[history.currentIndex + delta];
171
+ if (!entry)
172
+ return false;
173
+ await this._mainFrameSession._client.send("Page.navigateToHistoryEntry", { entryId: entry.id });
174
+ return true;
175
+ }
176
+ goBack() {
177
+ return this._go(-1);
178
+ }
179
+ goForward() {
180
+ return this._go(1);
181
+ }
182
+ async requestGC() {
183
+ await this._mainFrameSession._client.send("HeapProfiler.collectGarbage");
184
+ }
185
+ async addInitScript(initScript, world = "main") {
186
+ await this._forAllFrameSessions((frame) => frame._evaluateOnNewDocument(initScript, world));
187
+ }
188
+ async exposePlaywrightBinding() {
189
+ await this._forAllFrameSessions((frame) => frame.exposePlaywrightBinding());
190
+ }
191
+ async removeInitScripts(initScripts) {
192
+ await this._forAllFrameSessions((frame) => frame._removeEvaluatesOnNewDocument(initScripts));
193
+ }
194
+ async closePage(runBeforeUnload) {
195
+ if (runBeforeUnload)
196
+ await this._mainFrameSession._client.send("Page.close");
197
+ else
198
+ await this._browserContext._browser._closePage(this);
199
+ }
200
+ async setBackgroundColor(color) {
201
+ await this._mainFrameSession._client.send("Emulation.setDefaultBackgroundColorOverride", { color });
202
+ }
203
+ async takeScreenshot(progress, format, documentRect, viewportRect, quality, fitsViewport, scale) {
204
+ const { visualViewport } = await progress.race(this._mainFrameSession._client.send("Page.getLayoutMetrics"));
205
+ if (!documentRect) {
206
+ documentRect = {
207
+ x: visualViewport.pageX + viewportRect.x,
208
+ y: visualViewport.pageY + viewportRect.y,
209
+ ...import_helper.helper.enclosingIntSize({
210
+ width: viewportRect.width / visualViewport.scale,
211
+ height: viewportRect.height / visualViewport.scale
212
+ })
213
+ };
214
+ }
215
+ const clip = { ...documentRect, scale: viewportRect ? visualViewport.scale : 1 };
216
+ if (scale === "css") {
217
+ const deviceScaleFactor = this._browserContext._options.deviceScaleFactor || 1;
218
+ clip.scale /= deviceScaleFactor;
219
+ }
220
+ const result = await progress.race(this._mainFrameSession._client.send("Page.captureScreenshot", { format, quality, clip, captureBeyondViewport: !fitsViewport }));
221
+ return Buffer.from(result.data, "base64");
222
+ }
223
+ async getContentFrame(handle) {
224
+ return this._sessionForHandle(handle)._getContentFrame(handle);
225
+ }
226
+ async getOwnerFrame(handle) {
227
+ return this._sessionForHandle(handle)._getOwnerFrame(handle);
228
+ }
229
+ async getBoundingBox(handle) {
230
+ return this._sessionForHandle(handle)._getBoundingBox(handle);
231
+ }
232
+ async scrollRectIntoViewIfNeeded(handle, rect) {
233
+ return this._sessionForHandle(handle)._scrollRectIntoViewIfNeeded(handle, rect);
234
+ }
235
+ async startScreencast(options) {
236
+ await this._mainFrameSession._client.send("Page.startScreencast", {
237
+ format: "jpeg",
238
+ quality: options.quality,
239
+ maxWidth: options.width,
240
+ maxHeight: options.height
241
+ });
242
+ }
243
+ async stopScreencast() {
244
+ await this._mainFrameSession._client._sendMayFail("Page.stopScreencast");
245
+ }
246
+ rafCountForStablePosition() {
247
+ return 1;
248
+ }
249
+ async getContentQuads(handle) {
250
+ return this._sessionForHandle(handle)._getContentQuads(handle);
251
+ }
252
+ async setInputFilePaths(handle, files) {
253
+ const frame = await handle.ownerFrame();
254
+ if (!frame)
255
+ throw new Error("Cannot set input files to detached input element");
256
+ const parentSession = this._sessionForFrame(frame);
257
+ await parentSession._client.send("DOM.setFileInputFiles", {
258
+ objectId: handle._objectId,
259
+ files
260
+ });
261
+ }
262
+ async adoptElementHandle(handle, to) {
263
+ return this._sessionForHandle(handle)._adoptElementHandle(handle, to);
264
+ }
265
+ async inputActionEpilogue() {
266
+ await this._mainFrameSession._client.send("Page.enable").catch((e) => {
267
+ });
268
+ }
269
+ async resetForReuse(progress) {
270
+ await this.rawMouse.move(progress, -1, -1, "none", /* @__PURE__ */ new Set(), /* @__PURE__ */ new Set(), true);
271
+ }
272
+ async pdf(options) {
273
+ return this._pdf.generate(options);
274
+ }
275
+ coverage() {
276
+ return this._coverage;
277
+ }
278
+ async getFrameElement(frame) {
279
+ let parent = frame.parentFrame();
280
+ if (!parent)
281
+ throw new Error("Frame has been detached.");
282
+ const parentSession = this._sessionForFrame(parent);
283
+ const { backendNodeId } = await parentSession._client.send("DOM.getFrameOwner", { frameId: frame._id }).catch((e) => {
284
+ if (e instanceof Error && e.message.includes("Frame with the given id was not found."))
285
+ (0, import_stackTrace.rewriteErrorMessage)(e, "Frame has been detached.");
286
+ throw e;
287
+ });
288
+ parent = frame.parentFrame();
289
+ if (!parent)
290
+ throw new Error("Frame has been detached.");
291
+ return parentSession._adoptBackendNodeId(backendNodeId, await parent._mainContext());
292
+ }
293
+ shouldToggleStyleSheetToSyncAnimations() {
294
+ return false;
295
+ }
296
+ }
297
+ class FrameSession {
298
+ constructor(crPage, client, targetId, parentSession) {
299
+ this._childSessions = /* @__PURE__ */ new Set();
300
+ this._contextIdToContext = /* @__PURE__ */ new Map();
301
+ this._eventListeners = [];
302
+ this._firstNonInitialNavigationCommittedFulfill = () => {
303
+ };
304
+ this._firstNonInitialNavigationCommittedReject = (e) => {
305
+ };
306
+ // Marks the oopif session that remote -> local transition has happened in the parent.
307
+ // See Target.detachedFromTarget handler for details.
308
+ this._swappedIn = false;
309
+ this._workerSessions = /* @__PURE__ */ new Map();
310
+ this._initScriptIds = /* @__PURE__ */ new Map();
311
+ this._client = client;
312
+ this._crPage = crPage;
313
+ this._page = crPage._page;
314
+ this._targetId = targetId;
315
+ this._parentSession = parentSession;
316
+ if (parentSession)
317
+ parentSession._childSessions.add(this);
318
+ this._firstNonInitialNavigationCommittedPromise = new Promise((f, r) => {
319
+ this._firstNonInitialNavigationCommittedFulfill = f;
320
+ this._firstNonInitialNavigationCommittedReject = r;
321
+ });
322
+ this._firstNonInitialNavigationCommittedPromise.catch(() => {
323
+ });
324
+ }
325
+ _isMainFrame() {
326
+ return this._targetId === this._crPage._targetId;
327
+ }
328
+ _addRendererListeners() {
329
+ this._eventListeners.push(...[
330
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Log.entryAdded", (event) => this._onLogEntryAdded(event)),
331
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.fileChooserOpened", (event) => this._onFileChooserOpened(event)),
332
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameAttached", (event) => this._onFrameAttached(event.frameId, event.parentFrameId)),
333
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameDetached", (event) => this._onFrameDetached(event.frameId, event.reason)),
334
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameNavigated", (event) => this._onFrameNavigated(event.frame, false)),
335
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.frameRequestedNavigation", (event) => this._onFrameRequestedNavigation(event)),
336
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.javascriptDialogOpening", (event) => this._onDialog(event)),
337
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.navigatedWithinDocument", (event) => this._onFrameNavigatedWithinDocument(event.frameId, event.url)),
338
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.bindingCalled", (event) => this._onBindingCalled(event)),
339
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.consoleAPICalled", (event) => this._onConsoleAPI(event)),
340
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.exceptionThrown", (exception) => this._handleException(exception.exceptionDetails)),
341
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextCreated", (event) => this._onExecutionContextCreated(event.context)),
342
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextDestroyed", (event) => this._onExecutionContextDestroyed(event.executionContextId)),
343
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Runtime.executionContextsCleared", (event) => this._onExecutionContextsCleared())
344
+ ]);
345
+ }
346
+ _addBrowserListeners() {
347
+ this._eventListeners.push(...[
348
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Target.attachedToTarget", (event) => this._onAttachedToTarget(event)),
349
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Target.detachedFromTarget", (event) => this._onDetachedFromTarget(event)),
350
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Inspector.targetCrashed", (event) => this._onTargetCrashed()),
351
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.screencastFrame", (event) => this._onScreencastFrame(event)),
352
+ import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.windowOpen", (event) => this._onWindowOpen(event))
353
+ ]);
354
+ }
355
+ async _initialize(hasUIWindow) {
356
+ if (!this._page.isStorageStatePage && hasUIWindow && !this._crPage._browserContext._browser.isClank() && !this._crPage._browserContext._options.noDefaultViewport) {
357
+ const { windowId } = await this._client.send("Browser.getWindowForTarget");
358
+ this._windowId = windowId;
359
+ }
360
+ let videoOptions;
361
+ if (!this._page.isStorageStatePage && this._isMainFrame() && hasUIWindow)
362
+ videoOptions = this._crPage._page.screencast.launchVideoRecorder();
363
+ let lifecycleEventsEnabled;
364
+ if (!this._isMainFrame())
365
+ this._addRendererListeners();
366
+ this._addBrowserListeners();
367
+ this._bufferedAttachedToTargetEvents = [];
368
+ const promises = [
369
+ this._client.send("Page.enable"),
370
+ this._client.send("Page.getFrameTree").then(({ frameTree }) => {
371
+ if (this._isMainFrame()) {
372
+ this._handleFrameTree(frameTree);
373
+ this._addRendererListeners();
374
+ }
375
+ const attachedToTargetEvents = this._bufferedAttachedToTargetEvents || [];
376
+ this._bufferedAttachedToTargetEvents = void 0;
377
+ for (const event of attachedToTargetEvents)
378
+ this._onAttachedToTarget(event);
379
+ const localFrames = this._isMainFrame() ? this._page.frames() : [this._page.frameManager.frame(this._targetId)];
380
+ for (const frame of localFrames) {
381
+ this._client._sendMayFail("Page.createIsolatedWorld", {
382
+ frameId: frame._id,
383
+ grantUniveralAccess: true,
384
+ worldName: this._crPage.utilityWorldName
385
+ });
386
+ }
387
+ const isInitialEmptyPage = this._isMainFrame() && this._page.mainFrame().url() === ":";
388
+ if (isInitialEmptyPage) {
389
+ lifecycleEventsEnabled.catch((e) => {
390
+ }).then(() => {
391
+ this._eventListeners.push(import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.lifecycleEvent", (event) => this._onLifecycleEvent(event)));
392
+ });
393
+ } else {
394
+ this._firstNonInitialNavigationCommittedFulfill();
395
+ this._eventListeners.push(import_eventsHelper.eventsHelper.addEventListener(this._client, "Page.lifecycleEvent", (event) => this._onLifecycleEvent(event)));
396
+ }
397
+ }),
398
+ this._client.send("Log.enable", {}),
399
+ lifecycleEventsEnabled = this._client.send("Page.setLifecycleEventsEnabled", { enabled: true }),
400
+ this._client.send("Runtime.enable", {}),
401
+ this._client.send("Page.addScriptToEvaluateOnNewDocument", {
402
+ source: "",
403
+ worldName: this._crPage.utilityWorldName
404
+ }),
405
+ this._crPage._networkManager.addSession(this._client, void 0, this._isMainFrame()),
406
+ this._client.send("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true })
407
+ ];
408
+ if (!this._page.isStorageStatePage) {
409
+ if (this._crPage._browserContext.needsPlaywrightBinding())
410
+ promises.push(this.exposePlaywrightBinding());
411
+ if (this._isMainFrame())
412
+ promises.push(this._client.send("Emulation.setFocusEmulationEnabled", { enabled: true }));
413
+ const options = this._crPage._browserContext._options;
414
+ if (options.bypassCSP)
415
+ promises.push(this._client.send("Page.setBypassCSP", { enabled: true }));
416
+ if (options.ignoreHTTPSErrors || options.internalIgnoreHTTPSErrors)
417
+ promises.push(this._client.send("Security.setIgnoreCertificateErrors", { ignore: true }));
418
+ if (this._isMainFrame())
419
+ promises.push(this._updateViewport());
420
+ if (options.hasTouch)
421
+ promises.push(this._client.send("Emulation.setTouchEmulationEnabled", { enabled: true }));
422
+ if (options.javaScriptEnabled === false)
423
+ promises.push(this._client.send("Emulation.setScriptExecutionDisabled", { value: true }));
424
+ if (options.userAgent || options.locale)
425
+ promises.push(this._updateUserAgent());
426
+ if (options.locale)
427
+ promises.push(emulateLocale(this._client, options.locale));
428
+ if (options.timezoneId)
429
+ promises.push(emulateTimezone(this._client, options.timezoneId));
430
+ if (!this._crPage._browserContext._browser.options.headful)
431
+ promises.push(this._setDefaultFontFamilies(this._client));
432
+ promises.push(this._updateGeolocation(true));
433
+ promises.push(this._updateEmulateMedia());
434
+ promises.push(this._updateFileChooserInterception(true));
435
+ for (const initScript of this._crPage._page.allInitScripts())
436
+ promises.push(this._evaluateOnNewDocument(
437
+ initScript,
438
+ "main",
439
+ true
440
+ /* runImmediately */
441
+ ));
442
+ if (videoOptions)
443
+ promises.push(this._crPage._page.screencast.startVideoRecording(videoOptions));
444
+ }
445
+ promises.push(this._client.send("Runtime.runIfWaitingForDebugger"));
446
+ promises.push(this._firstNonInitialNavigationCommittedPromise);
447
+ await Promise.all(promises);
448
+ }
449
+ dispose() {
450
+ this._firstNonInitialNavigationCommittedReject(new import_errors.TargetClosedError(this._page.closeReason()));
451
+ for (const childSession of this._childSessions)
452
+ childSession.dispose();
453
+ if (this._parentSession)
454
+ this._parentSession._childSessions.delete(this);
455
+ import_eventsHelper.eventsHelper.removeEventListeners(this._eventListeners);
456
+ this._crPage._networkManager.removeSession(this._client);
457
+ this._crPage._sessions.delete(this._targetId);
458
+ this._client.dispose();
459
+ }
460
+ async _navigate(frame, url, referrer) {
461
+ const response = await this._client.send("Page.navigate", { url, referrer, frameId: frame._id, referrerPolicy: "unsafeUrl" });
462
+ if (response.isDownload)
463
+ throw new frames.NavigationAbortedError(response.loaderId, "Download is starting");
464
+ if (response.errorText)
465
+ throw new frames.NavigationAbortedError(response.loaderId, `${response.errorText} at ${url}`);
466
+ return { newDocumentId: response.loaderId };
467
+ }
468
+ _onLifecycleEvent(event) {
469
+ if (this._eventBelongsToStaleFrame(event.frameId))
470
+ return;
471
+ if (event.name === "load")
472
+ this._page.frameManager.frameLifecycleEvent(event.frameId, "load");
473
+ else if (event.name === "DOMContentLoaded")
474
+ this._page.frameManager.frameLifecycleEvent(event.frameId, "domcontentloaded");
475
+ }
476
+ _handleFrameTree(frameTree) {
477
+ this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId || null);
478
+ this._onFrameNavigated(frameTree.frame, true);
479
+ if (!frameTree.childFrames)
480
+ return;
481
+ for (const child of frameTree.childFrames)
482
+ this._handleFrameTree(child);
483
+ }
484
+ _eventBelongsToStaleFrame(frameId) {
485
+ const frame = this._page.frameManager.frame(frameId);
486
+ if (!frame)
487
+ return true;
488
+ const session = this._crPage._sessionForFrame(frame);
489
+ return session && session !== this && !session._swappedIn;
490
+ }
491
+ _onFrameAttached(frameId, parentFrameId) {
492
+ const frameSession = this._crPage._sessions.get(frameId);
493
+ if (frameSession && frameId !== this._targetId) {
494
+ frameSession._swappedIn = true;
495
+ const frame = this._page.frameManager.frame(frameId);
496
+ if (frame)
497
+ this._page.frameManager.removeChildFramesRecursively(frame);
498
+ return;
499
+ }
500
+ if (parentFrameId && !this._page.frameManager.frame(parentFrameId)) {
501
+ return;
502
+ }
503
+ this._page.frameManager.frameAttached(frameId, parentFrameId);
504
+ }
505
+ _onFrameNavigated(framePayload, initial) {
506
+ if (this._eventBelongsToStaleFrame(framePayload.id))
507
+ return;
508
+ this._page.frameManager.frameCommittedNewDocumentNavigation(framePayload.id, framePayload.url + (framePayload.urlFragment || ""), framePayload.name || "", framePayload.loaderId, initial);
509
+ if (!initial)
510
+ this._firstNonInitialNavigationCommittedFulfill();
511
+ }
512
+ _onFrameRequestedNavigation(payload) {
513
+ if (this._eventBelongsToStaleFrame(payload.frameId))
514
+ return;
515
+ if (payload.disposition === "currentTab")
516
+ this._page.frameManager.frameRequestedNavigation(payload.frameId);
517
+ }
518
+ _onFrameNavigatedWithinDocument(frameId, url) {
519
+ if (this._eventBelongsToStaleFrame(frameId))
520
+ return;
521
+ this._page.frameManager.frameCommittedSameDocumentNavigation(frameId, url);
522
+ }
523
+ _onFrameDetached(frameId, reason) {
524
+ if (this._crPage._sessions.has(frameId)) {
525
+ return;
526
+ }
527
+ if (reason === "swap") {
528
+ const frame = this._page.frameManager.frame(frameId);
529
+ if (frame)
530
+ this._page.frameManager.removeChildFramesRecursively(frame);
531
+ return;
532
+ }
533
+ this._page.frameManager.frameDetached(frameId);
534
+ }
535
+ _onExecutionContextCreated(contextPayload) {
536
+ const frame = contextPayload.auxData ? this._page.frameManager.frame(contextPayload.auxData.frameId) : null;
537
+ if (!frame || this._eventBelongsToStaleFrame(frame._id))
538
+ return;
539
+ const delegate = new import_crExecutionContext.CRExecutionContext(this._client, contextPayload);
540
+ let worldName = null;
541
+ if (contextPayload.auxData && !!contextPayload.auxData.isDefault)
542
+ worldName = "main";
543
+ else if (contextPayload.name === this._crPage.utilityWorldName)
544
+ worldName = "utility";
545
+ const context = new dom.FrameExecutionContext(delegate, frame, worldName);
546
+ if (worldName)
547
+ frame._contextCreated(worldName, context);
548
+ this._contextIdToContext.set(contextPayload.id, context);
549
+ }
550
+ _onExecutionContextDestroyed(executionContextId) {
551
+ const context = this._contextIdToContext.get(executionContextId);
552
+ if (!context)
553
+ return;
554
+ this._contextIdToContext.delete(executionContextId);
555
+ context.frame._contextDestroyed(context);
556
+ }
557
+ _onExecutionContextsCleared() {
558
+ for (const contextId of Array.from(this._contextIdToContext.keys()))
559
+ this._onExecutionContextDestroyed(contextId);
560
+ }
561
+ _onAttachedToTarget(event) {
562
+ if (this._bufferedAttachedToTargetEvents) {
563
+ this._bufferedAttachedToTargetEvents.push(event);
564
+ return;
565
+ }
566
+ const session = this._client.createChildSession(event.sessionId);
567
+ if (event.targetInfo.type === "iframe") {
568
+ const targetId = event.targetInfo.targetId;
569
+ let frame = this._page.frameManager.frame(targetId);
570
+ if (!frame && event.targetInfo.parentFrameId) {
571
+ frame = this._page.frameManager.frameAttached(targetId, event.targetInfo.parentFrameId);
572
+ }
573
+ if (!frame)
574
+ return;
575
+ this._page.frameManager.removeChildFramesRecursively(frame);
576
+ for (const [contextId, context] of this._contextIdToContext) {
577
+ if (context.frame === frame)
578
+ this._onExecutionContextDestroyed(contextId);
579
+ }
580
+ const frameSession = new FrameSession(this._crPage, session, targetId, this);
581
+ this._crPage._sessions.set(targetId, frameSession);
582
+ frameSession._initialize(false).catch((e) => e);
583
+ return;
584
+ }
585
+ if (event.targetInfo.type !== "worker") {
586
+ session.detach().catch(() => {
587
+ });
588
+ return;
589
+ }
590
+ const url = event.targetInfo.url;
591
+ const worker = new import_page.Worker(this._page, url);
592
+ this._page.addWorker(event.sessionId, worker);
593
+ this._workerSessions.set(event.sessionId, session);
594
+ session.once("Runtime.executionContextCreated", async (event2) => {
595
+ worker.createExecutionContext(new import_crExecutionContext.CRExecutionContext(session, event2.context));
596
+ });
597
+ if (this._crPage._browserContext._browser.majorVersion() >= 143)
598
+ session.on("Inspector.workerScriptLoaded", () => worker.workerScriptLoaded());
599
+ else
600
+ worker.workerScriptLoaded();
601
+ session._sendMayFail("Runtime.enable");
602
+ this._crPage._networkManager.addSession(session, this._page.frameManager.frame(this._targetId) ?? void 0).catch(() => {
603
+ });
604
+ session._sendMayFail("Runtime.runIfWaitingForDebugger");
605
+ session._sendMayFail("Target.setAutoAttach", { autoAttach: true, waitForDebuggerOnStart: true, flatten: true });
606
+ session.on("Target.attachedToTarget", (event2) => this._onAttachedToTarget(event2));
607
+ session.on("Target.detachedFromTarget", (event2) => this._onDetachedFromTarget(event2));
608
+ session.on("Runtime.consoleAPICalled", (event2) => {
609
+ const args = event2.args.map((o) => (0, import_crExecutionContext.createHandle)(worker.existingExecutionContext, o));
610
+ this._page.addConsoleMessage(worker, event2.type, args, (0, import_crProtocolHelper.toConsoleMessageLocation)(event2.stackTrace));
611
+ });
612
+ session.on("Runtime.exceptionThrown", (exception) => this._page.addPageError((0, import_crProtocolHelper.exceptionToError)(exception.exceptionDetails)));
613
+ }
614
+ _onDetachedFromTarget(event) {
615
+ const workerSession = this._workerSessions.get(event.sessionId);
616
+ if (workerSession) {
617
+ workerSession.dispose();
618
+ this._page.removeWorker(event.sessionId);
619
+ return;
620
+ }
621
+ const childFrameSession = this._crPage._sessions.get(event.targetId);
622
+ if (!childFrameSession)
623
+ return;
624
+ if (childFrameSession._swappedIn) {
625
+ childFrameSession.dispose();
626
+ return;
627
+ }
628
+ this._client.send("Page.enable").catch((e) => null).then(() => {
629
+ if (!childFrameSession._swappedIn)
630
+ this._page.frameManager.frameDetached(event.targetId);
631
+ childFrameSession.dispose();
632
+ });
633
+ }
634
+ _onWindowOpen(event) {
635
+ this._crPage._nextWindowOpenPopupFeatures.push(event.windowFeatures);
636
+ }
637
+ async _onConsoleAPI(event) {
638
+ if (event.executionContextId === 0) {
639
+ return;
640
+ }
641
+ const context = this._contextIdToContext.get(event.executionContextId);
642
+ if (!context)
643
+ return;
644
+ const values = event.args.map((arg) => (0, import_crExecutionContext.createHandle)(context, arg));
645
+ this._page.addConsoleMessage(null, event.type, values, (0, import_crProtocolHelper.toConsoleMessageLocation)(event.stackTrace));
646
+ }
647
+ async _onBindingCalled(event) {
648
+ const pageOrError = await this._crPage._page.waitForInitializedOrError();
649
+ if (!(pageOrError instanceof Error)) {
650
+ const context = this._contextIdToContext.get(event.executionContextId);
651
+ if (context)
652
+ await this._page.onBindingCalled(event.payload, context);
653
+ }
654
+ }
655
+ _onDialog(event) {
656
+ if (!this._page.frameManager.frame(this._targetId))
657
+ return;
658
+ this._page.browserContext.dialogManager.dialogDidOpen(new dialog.Dialog(
659
+ this._page,
660
+ event.type,
661
+ event.message,
662
+ async (accept, promptText) => {
663
+ if (this._isMainFrame() && event.type === "beforeunload" && !accept)
664
+ this._page.frameManager.frameAbortedNavigation(this._page.mainFrame()._id, "navigation cancelled by beforeunload dialog");
665
+ await this._client.send("Page.handleJavaScriptDialog", { accept, promptText });
666
+ },
667
+ event.defaultPrompt
668
+ ));
669
+ }
670
+ _handleException(exceptionDetails) {
671
+ this._page.addPageError((0, import_crProtocolHelper.exceptionToError)(exceptionDetails));
672
+ }
673
+ async _onTargetCrashed() {
674
+ this._client._markAsCrashed();
675
+ this._page._didCrash();
676
+ }
677
+ _onLogEntryAdded(event) {
678
+ const { level, text, args, source, url, lineNumber } = event.entry;
679
+ if (args)
680
+ args.map((arg) => (0, import_crProtocolHelper.releaseObject)(this._client, arg.objectId));
681
+ if (source !== "worker") {
682
+ const location = {
683
+ url: url || "",
684
+ lineNumber: lineNumber || 0,
685
+ columnNumber: 0
686
+ };
687
+ this._page.addConsoleMessage(null, level, [], location, text);
688
+ }
689
+ }
690
+ async _onFileChooserOpened(event) {
691
+ if (!event.backendNodeId)
692
+ return;
693
+ const frame = this._page.frameManager.frame(event.frameId);
694
+ if (!frame)
695
+ return;
696
+ let handle;
697
+ try {
698
+ const utilityContext = await frame._utilityContext();
699
+ handle = await this._adoptBackendNodeId(event.backendNodeId, utilityContext);
700
+ } catch (e) {
701
+ return;
702
+ }
703
+ await this._page._onFileChooserOpened(handle);
704
+ }
705
+ _willBeginDownload() {
706
+ if (!this._crPage._page.initializedOrUndefined()) {
707
+ this._firstNonInitialNavigationCommittedReject(new Error("Starting new page download"));
708
+ }
709
+ }
710
+ _onScreencastFrame(payload) {
711
+ this._page.screencast.throttleFrameAck(() => {
712
+ this._client._sendMayFail("Page.screencastFrameAck", { sessionId: payload.sessionId });
713
+ });
714
+ const buffer = Buffer.from(payload.data, "base64");
715
+ this._page.emit(import_page.Page.Events.ScreencastFrame, {
716
+ buffer,
717
+ frameSwapWallTime: payload.metadata.timestamp ? payload.metadata.timestamp * 1e3 : Date.now(),
718
+ width: payload.metadata.deviceWidth,
719
+ height: payload.metadata.deviceHeight
720
+ });
721
+ }
722
+ async _updateGeolocation(initial) {
723
+ const geolocation = this._crPage._browserContext._options.geolocation;
724
+ if (!initial || geolocation)
725
+ await this._client.send("Emulation.setGeolocationOverride", geolocation || {});
726
+ }
727
+ async _updateViewport(preserveWindowBoundaries) {
728
+ if (this._crPage._browserContext._browser.isClank())
729
+ return;
730
+ (0, import_assert.assert)(this._isMainFrame());
731
+ const options = this._crPage._browserContext._options;
732
+ const emulatedSize = this._page.emulatedSize();
733
+ if (!emulatedSize)
734
+ return;
735
+ const viewportSize = emulatedSize.viewport;
736
+ const screenSize = emulatedSize.screen;
737
+ const isLandscape = screenSize.width > screenSize.height;
738
+ const metricsOverride = {
739
+ mobile: !!options.isMobile,
740
+ width: viewportSize.width,
741
+ height: viewportSize.height,
742
+ screenWidth: screenSize.width,
743
+ screenHeight: screenSize.height,
744
+ deviceScaleFactor: options.deviceScaleFactor || 1,
745
+ screenOrientation: !!options.isMobile ? isLandscape ? { angle: 90, type: "landscapePrimary" } : { angle: 0, type: "portraitPrimary" } : { angle: 0, type: "landscapePrimary" },
746
+ dontSetVisibleSize: preserveWindowBoundaries
747
+ };
748
+ if (JSON.stringify(this._metricsOverride) === JSON.stringify(metricsOverride))
749
+ return;
750
+ const promises = [];
751
+ if (!preserveWindowBoundaries && this._windowId) {
752
+ let insets = { width: 0, height: 0 };
753
+ if (this._crPage._browserContext._browser.options.headful) {
754
+ insets = { width: 24, height: 88 };
755
+ if (process.platform === "win32")
756
+ insets = { width: 16, height: 88 };
757
+ else if (process.platform === "linux")
758
+ insets = { width: 8, height: 85 };
759
+ else if (process.platform === "darwin")
760
+ insets = { width: 2, height: 80 };
761
+ if (this._crPage._browserContext.isPersistentContext()) {
762
+ insets.height += 46;
763
+ }
764
+ }
765
+ promises.push(this.setWindowBounds({
766
+ width: viewportSize.width + insets.width,
767
+ height: viewportSize.height + insets.height
768
+ }));
769
+ }
770
+ promises.push(this._client.send("Emulation.setDeviceMetricsOverride", metricsOverride));
771
+ await Promise.all(promises);
772
+ this._metricsOverride = metricsOverride;
773
+ }
774
+ async windowBounds() {
775
+ const { bounds } = await this._client.send("Browser.getWindowBounds", {
776
+ windowId: this._windowId
777
+ });
778
+ return bounds;
779
+ }
780
+ async setWindowBounds(bounds) {
781
+ return await this._client.send("Browser.setWindowBounds", {
782
+ windowId: this._windowId,
783
+ bounds
784
+ });
785
+ }
786
+ async _updateEmulateMedia() {
787
+ const emulatedMedia = this._page.emulatedMedia();
788
+ const media = emulatedMedia.media === "no-override" ? "" : emulatedMedia.media;
789
+ const colorScheme = emulatedMedia.colorScheme === "no-override" ? "" : emulatedMedia.colorScheme;
790
+ const reducedMotion = emulatedMedia.reducedMotion === "no-override" ? "" : emulatedMedia.reducedMotion;
791
+ const forcedColors = emulatedMedia.forcedColors === "no-override" ? "" : emulatedMedia.forcedColors;
792
+ const contrast = emulatedMedia.contrast === "no-override" ? "" : emulatedMedia.contrast;
793
+ const features = [
794
+ { name: "prefers-color-scheme", value: colorScheme },
795
+ { name: "prefers-reduced-motion", value: reducedMotion },
796
+ { name: "forced-colors", value: forcedColors },
797
+ { name: "prefers-contrast", value: contrast }
798
+ ];
799
+ await this._client.send("Emulation.setEmulatedMedia", { media, features });
800
+ }
801
+ async _updateUserAgent() {
802
+ const options = this._crPage._browserContext._options;
803
+ await this._client.send("Emulation.setUserAgentOverride", {
804
+ userAgent: options.userAgent || "",
805
+ acceptLanguage: options.locale,
806
+ userAgentMetadata: calculateUserAgentMetadata(options)
807
+ });
808
+ }
809
+ async _setDefaultFontFamilies(session) {
810
+ const fontFamilies = import_defaultFontFamilies.platformToFontFamilies[this._crPage._browserContext._browser._platform()];
811
+ await session.send("Page.setFontFamilies", fontFamilies);
812
+ }
813
+ async _updateFileChooserInterception(initial) {
814
+ const enabled = this._page.fileChooserIntercepted();
815
+ if (initial && !enabled)
816
+ return;
817
+ await this._client.send("Page.setInterceptFileChooserDialog", { enabled }).catch(() => {
818
+ });
819
+ }
820
+ async _evaluateOnNewDocument(initScript, world, runImmediately) {
821
+ const worldName = world === "utility" ? this._crPage.utilityWorldName : void 0;
822
+ const { identifier } = await this._client.send("Page.addScriptToEvaluateOnNewDocument", { source: initScript.source, worldName, runImmediately });
823
+ this._initScriptIds.set(initScript, identifier);
824
+ }
825
+ async _removeEvaluatesOnNewDocument(initScripts) {
826
+ const ids = [];
827
+ for (const script of initScripts) {
828
+ const id = this._initScriptIds.get(script);
829
+ if (id)
830
+ ids.push(id);
831
+ this._initScriptIds.delete(script);
832
+ }
833
+ await Promise.all(ids.map((identifier) => this._client.send("Page.removeScriptToEvaluateOnNewDocument", { identifier }).catch(() => {
834
+ })));
835
+ }
836
+ async exposePlaywrightBinding() {
837
+ await this._client.send("Runtime.addBinding", { name: import_page.PageBinding.kBindingName });
838
+ }
839
+ async _getContentFrame(handle) {
840
+ const nodeInfo = await this._client.send("DOM.describeNode", {
841
+ objectId: handle._objectId
842
+ });
843
+ if (!nodeInfo || typeof nodeInfo.node.frameId !== "string")
844
+ return null;
845
+ return this._page.frameManager.frame(nodeInfo.node.frameId);
846
+ }
847
+ async _getOwnerFrame(handle) {
848
+ const documentElement = await handle.evaluateHandle((node) => {
849
+ const doc = node;
850
+ if (doc.documentElement && doc.documentElement.ownerDocument === doc)
851
+ return doc.documentElement;
852
+ return node.ownerDocument ? node.ownerDocument.documentElement : null;
853
+ });
854
+ if (!documentElement)
855
+ return null;
856
+ if (!documentElement._objectId)
857
+ return null;
858
+ const nodeInfo = await this._client.send("DOM.describeNode", {
859
+ objectId: documentElement._objectId
860
+ });
861
+ const frameId = nodeInfo && typeof nodeInfo.node.frameId === "string" ? nodeInfo.node.frameId : null;
862
+ documentElement.dispose();
863
+ return frameId;
864
+ }
865
+ async _getBoundingBox(handle) {
866
+ const result = await this._client._sendMayFail("DOM.getBoxModel", {
867
+ objectId: handle._objectId
868
+ });
869
+ if (!result)
870
+ return null;
871
+ const quad = result.model.border;
872
+ const x = Math.min(quad[0], quad[2], quad[4], quad[6]);
873
+ const y = Math.min(quad[1], quad[3], quad[5], quad[7]);
874
+ const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;
875
+ const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;
876
+ const position = await this._framePosition();
877
+ if (!position)
878
+ return null;
879
+ return { x: x + position.x, y: y + position.y, width, height };
880
+ }
881
+ async _framePosition() {
882
+ const frame = this._page.frameManager.frame(this._targetId);
883
+ if (!frame)
884
+ return null;
885
+ if (frame === this._page.mainFrame())
886
+ return { x: 0, y: 0 };
887
+ const element = await frame.frameElement();
888
+ const box = await element.boundingBox();
889
+ return box;
890
+ }
891
+ async _scrollRectIntoViewIfNeeded(handle, rect) {
892
+ return await this._client.send("DOM.scrollIntoViewIfNeeded", {
893
+ objectId: handle._objectId,
894
+ rect
895
+ }).then(() => "done").catch((e) => {
896
+ if (e instanceof Error && e.message.includes("Node does not have a layout object"))
897
+ return "error:notvisible";
898
+ if (e instanceof Error && e.message.includes("Node is detached from document"))
899
+ return "error:notconnected";
900
+ throw e;
901
+ });
902
+ }
903
+ async _getContentQuads(handle) {
904
+ const result = await this._client._sendMayFail("DOM.getContentQuads", {
905
+ objectId: handle._objectId
906
+ });
907
+ if (!result)
908
+ return null;
909
+ const position = await this._framePosition();
910
+ if (!position)
911
+ return null;
912
+ return result.quads.map((quad) => [
913
+ { x: quad[0] + position.x, y: quad[1] + position.y },
914
+ { x: quad[2] + position.x, y: quad[3] + position.y },
915
+ { x: quad[4] + position.x, y: quad[5] + position.y },
916
+ { x: quad[6] + position.x, y: quad[7] + position.y }
917
+ ]);
918
+ }
919
+ async _adoptElementHandle(handle, to) {
920
+ const nodeInfo = await this._client.send("DOM.describeNode", {
921
+ objectId: handle._objectId
922
+ });
923
+ return this._adoptBackendNodeId(nodeInfo.node.backendNodeId, to);
924
+ }
925
+ async _adoptBackendNodeId(backendNodeId, to) {
926
+ const result = await this._client._sendMayFail("DOM.resolveNode", {
927
+ backendNodeId,
928
+ executionContextId: to.delegate._contextId
929
+ });
930
+ if (!result || result.object.subtype === "null")
931
+ throw new Error(dom.kUnableToAdoptErrorMessage);
932
+ return (0, import_crExecutionContext.createHandle)(to, result.object).asElement();
933
+ }
934
+ }
935
+ async function emulateLocale(session, locale) {
936
+ try {
937
+ await session.send("Emulation.setLocaleOverride", { locale });
938
+ } catch (exception) {
939
+ if (exception.message.includes("Another locale override is already in effect"))
940
+ return;
941
+ throw exception;
942
+ }
943
+ }
944
+ async function emulateTimezone(session, timezoneId) {
945
+ try {
946
+ await session.send("Emulation.setTimezoneOverride", { timezoneId });
947
+ } catch (exception) {
948
+ if (exception.message.includes("Timezone override is already in effect"))
949
+ return;
950
+ if (exception.message.includes("Invalid timezone"))
951
+ throw new Error(`Invalid timezone ID: ${timezoneId}`);
952
+ throw exception;
953
+ }
954
+ }
955
+ function calculateUserAgentMetadata(options) {
956
+ const ua = options.userAgent;
957
+ if (!ua)
958
+ return void 0;
959
+ const metadata = {
960
+ mobile: !!options.isMobile,
961
+ model: "",
962
+ architecture: "x86",
963
+ platform: "Windows",
964
+ platformVersion: ""
965
+ };
966
+ const androidMatch = ua.match(/Android (\d+(\.\d+)?(\.\d+)?)/);
967
+ const iPhoneMatch = ua.match(/iPhone OS (\d+(_\d+)?)/);
968
+ const iPadMatch = ua.match(/iPad; CPU OS (\d+(_\d+)?)/);
969
+ const macOSMatch = ua.match(/Mac OS X (\d+(_\d+)?(_\d+)?)/);
970
+ const windowsMatch = ua.match(/Windows\D+(\d+(\.\d+)?(\.\d+)?)/);
971
+ if (androidMatch) {
972
+ metadata.platform = "Android";
973
+ metadata.platformVersion = androidMatch[1];
974
+ metadata.architecture = "arm";
975
+ } else if (iPhoneMatch) {
976
+ metadata.platform = "iOS";
977
+ metadata.platformVersion = iPhoneMatch[1];
978
+ metadata.architecture = "arm";
979
+ } else if (iPadMatch) {
980
+ metadata.platform = "iOS";
981
+ metadata.platformVersion = iPadMatch[1];
982
+ metadata.architecture = "arm";
983
+ } else if (macOSMatch) {
984
+ metadata.platform = "macOS";
985
+ metadata.platformVersion = macOSMatch[1];
986
+ if (!ua.includes("Intel"))
987
+ metadata.architecture = "arm";
988
+ } else if (windowsMatch) {
989
+ metadata.platform = "Windows";
990
+ metadata.platformVersion = windowsMatch[1];
991
+ } else if (ua.toLowerCase().includes("linux")) {
992
+ metadata.platform = "Linux";
993
+ }
994
+ if (ua.includes("ARM"))
995
+ metadata.architecture = "arm";
996
+ return metadata;
997
+ }
998
+ // Annotate the CommonJS export names for ESM import in node:
999
+ 0 && (module.exports = {
1000
+ CRPage
1001
+ });