patchright-core 1.52.4 → 1.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/ThirdPartyNotices.txt +65 -123
  2. package/bin/reinstall_chrome_beta_mac.sh +1 -1
  3. package/bin/reinstall_chrome_stable_mac.sh +1 -1
  4. package/bin/reinstall_msedge_beta_mac.sh +1 -1
  5. package/bin/reinstall_msedge_dev_mac.sh +1 -1
  6. package/bin/reinstall_msedge_stable_mac.sh +1 -1
  7. package/browsers.json +14 -14
  8. package/index.js +1 -1
  9. package/lib/androidServerImpl.js +4 -2
  10. package/lib/browserServerImpl.js +47 -12
  11. package/lib/cli/program.js +116 -50
  12. package/lib/cli/programWithTestStub.js +1 -1
  13. package/lib/client/android.js +30 -34
  14. package/lib/client/browser.js +54 -17
  15. package/lib/client/browserContext.js +67 -71
  16. package/lib/client/browserType.js +25 -34
  17. package/lib/client/channelOwner.js +20 -24
  18. package/lib/client/connection.js +6 -10
  19. package/lib/client/electron.js +8 -3
  20. package/lib/client/elementHandle.js +18 -21
  21. package/lib/client/fetch.js +5 -3
  22. package/lib/client/frame.js +57 -35
  23. package/lib/client/input.js +3 -1
  24. package/lib/client/jsHandle.js +4 -0
  25. package/lib/client/localUtils.js +0 -1
  26. package/lib/client/locator.js +32 -28
  27. package/lib/client/network.js +5 -12
  28. package/lib/client/page.js +32 -32
  29. package/lib/client/playwright.js +6 -16
  30. package/lib/client/selectors.js +18 -38
  31. package/lib/client/timeoutSettings.js +12 -8
  32. package/lib/client/tracing.js +24 -20
  33. package/lib/client/waiter.js +2 -2
  34. package/lib/client/webSocket.js +4 -22
  35. package/lib/generated/bindingsControllerSource.js +28 -0
  36. package/lib/generated/clockSource.js +1 -1
  37. package/lib/generated/injectedScriptSource.js +1 -1
  38. package/lib/generated/pollingRecorderSource.js +1 -1
  39. package/lib/generated/storageScriptSource.js +28 -0
  40. package/lib/generated/utilityScriptSource.js +1 -1
  41. package/lib/generated/webSocketMockSource.js +12 -50
  42. package/lib/inProcessFactory.js +9 -6
  43. package/lib/outofprocess.js +0 -2
  44. package/lib/protocol/validator.js +423 -346
  45. package/lib/protocol/validatorPrimitives.js +18 -4
  46. package/lib/remote/playwrightConnection.js +29 -166
  47. package/lib/remote/playwrightServer.js +233 -35
  48. package/lib/server/android/android.js +97 -83
  49. package/lib/server/android/backendAdb.js +0 -2
  50. package/lib/server/bidi/bidiBrowser.js +139 -73
  51. package/lib/server/bidi/bidiChromium.js +23 -22
  52. package/lib/server/bidi/bidiExecutionContext.js +2 -1
  53. package/lib/server/bidi/bidiFirefox.js +17 -14
  54. package/lib/server/bidi/bidiInput.js +22 -22
  55. package/lib/server/bidi/bidiNetworkManager.js +8 -11
  56. package/lib/server/bidi/bidiPage.js +42 -86
  57. package/lib/server/bidi/third_party/bidiProtocol.js +5 -133
  58. package/lib/server/bidi/third_party/bidiProtocolCore.js +179 -0
  59. package/lib/server/{dispatchers/selectorsDispatcher.js → bidi/third_party/bidiProtocolPermissions.js} +20 -18
  60. package/lib/server/browser.js +30 -21
  61. package/lib/server/browserContext.js +203 -165
  62. package/lib/server/browserType.js +109 -107
  63. package/lib/server/chromium/chromium.js +84 -69
  64. package/lib/server/chromium/chromiumSwitches.js +13 -20
  65. package/lib/server/chromium/crBrowser.js +74 -40
  66. package/lib/server/chromium/crConnection.js +8 -9
  67. package/lib/server/chromium/crCoverage.js +11 -8
  68. package/lib/server/chromium/crDragDrop.js +25 -20
  69. package/lib/server/chromium/crExecutionContext.js +2 -1
  70. package/lib/server/chromium/crInput.js +32 -29
  71. package/lib/server/chromium/crNetworkManager.js +45 -33
  72. package/lib/server/chromium/crPage.js +98 -73
  73. package/lib/server/chromium/crServiceWorker.js +13 -18
  74. package/lib/server/chromium/videoRecorder.js +10 -18
  75. package/lib/server/clock.js +51 -39
  76. package/lib/server/codegen/csharp.js +10 -5
  77. package/lib/server/codegen/java.js +1 -1
  78. package/lib/server/codegen/javascript.js +1 -1
  79. package/lib/server/codegen/jsonl.js +2 -1
  80. package/lib/server/codegen/language.js +22 -1
  81. package/lib/server/codegen/languages.js +4 -4
  82. package/lib/server/codegen/python.js +1 -1
  83. package/lib/server/cookieStore.js +3 -1
  84. package/lib/server/debugController.js +105 -71
  85. package/lib/server/debugger.js +6 -23
  86. package/lib/server/deviceDescriptorsSource.json +237 -127
  87. package/lib/server/dialog.js +50 -6
  88. package/lib/server/dispatchers/androidDispatcher.js +77 -62
  89. package/lib/server/dispatchers/artifactDispatcher.js +18 -18
  90. package/lib/server/dispatchers/browserContextDispatcher.js +141 -91
  91. package/lib/server/dispatchers/browserDispatcher.js +55 -88
  92. package/lib/server/dispatchers/browserTypeDispatcher.js +18 -9
  93. package/lib/server/dispatchers/cdpSessionDispatcher.js +4 -4
  94. package/lib/server/dispatchers/debugControllerDispatcher.js +12 -21
  95. package/lib/server/dispatchers/dialogDispatcher.js +4 -4
  96. package/lib/server/dispatchers/dispatcher.js +78 -53
  97. package/lib/server/dispatchers/electronDispatcher.js +19 -20
  98. package/lib/server/dispatchers/elementHandlerDispatcher.js +83 -93
  99. package/lib/server/dispatchers/frameDispatcher.js +99 -102
  100. package/lib/server/dispatchers/jsHandleDispatcher.js +21 -16
  101. package/lib/server/dispatchers/jsonPipeDispatcher.js +4 -4
  102. package/lib/server/dispatchers/localUtilsDispatcher.js +53 -59
  103. package/lib/server/dispatchers/networkDispatchers.js +41 -35
  104. package/lib/server/dispatchers/pageDispatcher.js +156 -107
  105. package/lib/server/dispatchers/playwrightDispatcher.js +37 -25
  106. package/lib/server/dispatchers/streamDispatcher.js +15 -8
  107. package/lib/server/dispatchers/tracingDispatcher.js +22 -13
  108. package/lib/server/dispatchers/webSocketRouteDispatcher.js +46 -35
  109. package/lib/server/dispatchers/writableStreamDispatcher.js +16 -10
  110. package/lib/server/dom.js +198 -266
  111. package/lib/server/download.js +3 -3
  112. package/lib/server/electron/electron.js +96 -103
  113. package/lib/server/electron/loader.js +1 -1
  114. package/lib/server/fetch.js +22 -41
  115. package/lib/server/fileUploadUtils.js +1 -1
  116. package/lib/server/firefox/ffBrowser.js +79 -55
  117. package/lib/server/firefox/ffExecutionContext.js +2 -1
  118. package/lib/server/firefox/ffInput.js +23 -23
  119. package/lib/server/firefox/ffNetworkManager.js +8 -6
  120. package/lib/server/firefox/ffPage.js +39 -36
  121. package/lib/server/firefox/firefox.js +9 -10
  122. package/lib/server/frameSelectors.js +65 -22
  123. package/lib/server/frames.js +516 -544
  124. package/lib/server/har/harRecorder.js +1 -1
  125. package/lib/server/har/harTracer.js +4 -2
  126. package/lib/server/helper.js +3 -7
  127. package/lib/server/index.js +0 -3
  128. package/lib/server/input.js +47 -54
  129. package/lib/server/instrumentation.js +8 -14
  130. package/lib/server/javascript.js +9 -17
  131. package/lib/server/launchApp.js +48 -30
  132. package/lib/server/localUtils.js +45 -38
  133. package/lib/server/network.js +44 -10
  134. package/lib/server/page.js +233 -178
  135. package/lib/server/pageBinding.js +6 -7
  136. package/lib/server/playwright.js +4 -14
  137. package/lib/server/progress.js +57 -49
  138. package/lib/server/recorder/recorderApp.js +298 -95
  139. package/lib/server/recorder/recorderRunner.js +23 -24
  140. package/lib/server/recorder/recorderSignalProcessor.js +83 -0
  141. package/lib/server/recorder/recorderUtils.js +67 -10
  142. package/lib/server/recorder.js +284 -146
  143. package/lib/server/registry/index.js +83 -48
  144. package/lib/server/registry/nativeDeps.js +175 -0
  145. package/lib/server/registry/oopDownloadBrowserMain.js +1 -1
  146. package/lib/server/screenshotter.js +84 -83
  147. package/lib/server/selectors.js +12 -12
  148. package/lib/server/socksClientCertificatesInterceptor.js +198 -136
  149. package/lib/server/trace/recorder/snapshotter.js +12 -19
  150. package/lib/server/trace/recorder/tracing.js +36 -27
  151. package/lib/server/trace/viewer/traceViewer.js +11 -20
  152. package/lib/server/transport.js +20 -22
  153. package/lib/server/utils/comparators.js +2 -2
  154. package/lib/server/utils/debug.js +3 -8
  155. package/lib/server/utils/debugLogger.js +8 -0
  156. package/lib/server/utils/hostPlatform.js +3 -1
  157. package/lib/server/utils/network.js +35 -25
  158. package/lib/server/utils/nodePlatform.js +1 -1
  159. package/lib/server/utils/processLauncher.js +4 -1
  160. package/lib/server/utils/wsServer.js +11 -17
  161. package/lib/server/webkit/webkit.js +5 -2
  162. package/lib/server/webkit/wkBrowser.js +51 -28
  163. package/lib/server/webkit/wkExecutionContext.js +2 -1
  164. package/lib/server/webkit/wkInput.js +25 -25
  165. package/lib/server/webkit/wkInterceptableRequest.js +1 -1
  166. package/lib/server/webkit/wkPage.js +80 -59
  167. package/lib/server/webkit/wkProvisionalPage.js +1 -1
  168. package/lib/server/webkit/wkWorkers.js +7 -7
  169. package/lib/utils/isomorphic/ariaSnapshot.js +13 -7
  170. package/lib/utils/isomorphic/cssParser.js +1 -2
  171. package/lib/utils/isomorphic/locatorGenerators.js +18 -0
  172. package/lib/utils/isomorphic/manualPromise.js +1 -2
  173. package/lib/utils/isomorphic/mimeType.js +1 -2
  174. package/lib/utils/isomorphic/multimap.js +1 -2
  175. package/lib/utils/isomorphic/oldUtilityScriptSerializers.js +248 -0
  176. package/lib/utils/isomorphic/protocolFormatter.js +78 -0
  177. package/lib/utils/isomorphic/protocolMetainfo.js +318 -0
  178. package/lib/utils/isomorphic/selectorParser.js +3 -4
  179. package/lib/utils/isomorphic/stringUtils.js +3 -24
  180. package/lib/utils/isomorphic/time.js +9 -4
  181. package/lib/utils/isomorphic/timeoutRunner.js +3 -4
  182. package/lib/utils/isomorphic/traceUtils.js +2 -3
  183. package/lib/utils/isomorphic/urlMatch.js +21 -7
  184. package/lib/utils/isomorphic/utilityScriptSerializers.js +208 -205
  185. package/lib/utils.js +8 -2
  186. package/lib/utilsBundleImpl/index.js +160 -150
  187. package/lib/vite/htmlReport/index.html +17 -17
  188. package/lib/vite/recorder/assets/{codeMirrorModule-CXVeovup.js → codeMirrorModule-DzQ0k89p.js} +1 -1
  189. package/lib/vite/recorder/assets/{index-eHBmevrY.css → index-CI4HQ-Zb.css} +1 -1
  190. package/lib/vite/recorder/assets/index-D7C7daHH.js +184 -0
  191. package/lib/vite/recorder/index.html +3 -3
  192. package/lib/vite/traceViewer/assets/{codeMirrorModule-_GLjJL-7.js → codeMirrorModule-Di48jgWx.js} +1 -1
  193. package/lib/vite/traceViewer/assets/defaultSettingsView-szBn8781.js +256 -0
  194. package/lib/vite/traceViewer/defaultSettingsView.DVJHpiGt.css +1 -0
  195. package/lib/vite/traceViewer/index.BFsek2M6.css +1 -0
  196. package/lib/vite/traceViewer/index.DQvXoPLL.js +2 -0
  197. package/lib/vite/traceViewer/index.html +6 -6
  198. package/lib/vite/traceViewer/sw.bundle.js +3 -3
  199. package/lib/vite/traceViewer/uiMode.dBV3oN9h.js +5 -0
  200. package/lib/vite/traceViewer/uiMode.html +4 -4
  201. package/lib/zipBundleImpl.js +4 -4
  202. package/package.json +1 -1
  203. package/types/protocol.d.ts +712 -107
  204. package/types/types.d.ts +148 -37
  205. package/lib/generated/consoleApiSource.js +0 -28
  206. package/lib/protocol/debug.js +0 -211
  207. package/lib/server/recorder/contextRecorder.js +0 -286
  208. package/lib/server/recorder/recorderCollection.js +0 -116
  209. package/lib/server/recorder/recorderFrontend.js +0 -16
  210. package/lib/server/storageScript.js +0 -154
  211. package/lib/server/timeoutSettings.js +0 -89
  212. package/lib/utils/isomorphic/builtins.js +0 -86
  213. package/lib/vite/recorder/assets/index-BsWQsSGl.js +0 -184
  214. package/lib/vite/traceViewer/assets/defaultSettingsView-DtCQiGHe.js +0 -265
  215. package/lib/vite/traceViewer/defaultSettingsView.QdHITyLI.css +0 -1
  216. package/lib/vite/traceViewer/index.CFOW-Ezb.css +0 -1
  217. package/lib/vite/traceViewer/index.cFZzK9RN.js +0 -2
  218. package/lib/vite/traceViewer/uiMode.XVPIqBeS.js +0 -5
@@ -31,10 +31,10 @@ __export(page_exports, {
31
31
  InitScript: () => InitScript,
32
32
  Page: () => Page,
33
33
  PageBinding: () => PageBinding,
34
- Worker: () => Worker,
35
- kBuiltinsScript: () => kBuiltinsScript
34
+ Worker: () => Worker
36
35
  });
37
36
  module.exports = __toCommonJS(page_exports);
37
+ var import_pageBinding = require("./pageBinding");
38
38
  var accessibility = __toESM(require("./accessibility"));
39
39
  var import_browserContext = require("./browserContext");
40
40
  var import_console = require("./console");
@@ -44,19 +44,15 @@ var frames = __toESM(require("./frames"));
44
44
  var import_helper = require("./helper");
45
45
  var input = __toESM(require("./input"));
46
46
  var import_instrumentation = require("./instrumentation");
47
- var import_builtins = require("../utils/isomorphic/builtins");
48
- var import_pageBinding = require("./pageBinding");
49
47
  var js = __toESM(require("./javascript"));
50
- var import_progress = require("./progress");
51
48
  var import_screenshotter = require("./screenshotter");
52
- var import_timeoutSettings = require("./timeoutSettings");
53
49
  var import_utils = require("../utils");
54
- var import_crypto = require("./utils/crypto");
55
50
  var import_utils2 = require("../utils");
56
51
  var import_comparators = require("./utils/comparators");
57
52
  var import_debugLogger = require("./utils/debugLogger");
58
53
  var import_selectorParser = require("../utils/isomorphic/selectorParser");
59
54
  var import_manualPromise = require("../utils/isomorphic/manualPromise");
55
+ var import_utilityScriptSerializers = require("../utils/isomorphic/utilityScriptSerializers");
60
56
  var import_callLog = require("./callLog");
61
57
  class Page extends import_instrumentation.SdkObject {
62
58
  constructor(delegate, browserContext) {
@@ -68,37 +64,39 @@ class Page extends import_instrumentation.SdkObject {
68
64
  this._crashed = false;
69
65
  this.openScope = new import_utils.LongStandingScope();
70
66
  this._emulatedMedia = {};
71
- this._interceptFileChooser = false;
67
+ this._fileChooserInterceptedBy = /* @__PURE__ */ new Set();
72
68
  this._pageBindings = /* @__PURE__ */ new Map();
73
69
  this.initScripts = [];
74
70
  this._workers = /* @__PURE__ */ new Map();
75
- this._video = null;
76
- this._isServerSideOnly = false;
71
+ this.requestInterceptors = [];
72
+ this.video = null;
77
73
  this._locatorHandlers = /* @__PURE__ */ new Map();
78
74
  this._lastLocatorHandlerUid = 0;
79
75
  this._locatorHandlerRunningCounter = 0;
80
76
  // Aiming at 25 fps by default - each frame is 40ms, but we give some slack with 35ms.
81
77
  // When throttling for tracing, 200ms between frames, except for 10 frames around the action.
82
78
  this._frameThrottler = new FrameThrottler(10, 35, 200);
79
+ this.lastSnapshotFrameIds = [];
83
80
  this.attribution.page = this;
84
- this._delegate = delegate;
85
- this._browserContext = browserContext;
81
+ this.delegate = delegate;
82
+ this.browserContext = browserContext;
86
83
  this.accessibility = new accessibility.Accessibility(delegate.getAccessibilityTree.bind(delegate));
87
- this.keyboard = new input.Keyboard(delegate.rawKeyboard);
84
+ this.keyboard = new input.Keyboard(delegate.rawKeyboard, this);
88
85
  this.mouse = new input.Mouse(delegate.rawMouse, this);
89
86
  this.touchscreen = new input.Touchscreen(delegate.rawTouchscreen, this);
90
- this._timeoutSettings = new import_timeoutSettings.TimeoutSettings(browserContext._timeoutSettings);
91
- this._screenshotter = new import_screenshotter.Screenshotter(this);
92
- this._frameManager = new frames.FrameManager(this);
87
+ this.screenshotter = new import_screenshotter.Screenshotter(this);
88
+ this.frameManager = new frames.FrameManager(this);
93
89
  if (delegate.pdf)
94
90
  this.pdf = delegate.pdf.bind(delegate);
95
91
  this.coverage = delegate.coverage ? delegate.coverage() : null;
92
+ this.isStorageStatePage = browserContext.isCreatingStorageStatePage();
96
93
  }
97
94
  static {
98
95
  this.Events = {
99
96
  Close: "close",
100
97
  Crash: "crash",
101
98
  Download: "download",
99
+ EmulatedSizeChanged: "emulatedsizechanged",
102
100
  FileChooser: "filechooser",
103
101
  FrameAttached: "frameattached",
104
102
  FrameDetached: "framedetached",
@@ -120,14 +118,14 @@ class Page extends import_instrumentation.SdkObject {
120
118
  }
121
119
  _markInitialized(error = void 0, contextEvent = import_browserContext.BrowserContext.Events.Page) {
122
120
  if (error) {
123
- if (this._browserContext.isClosingOrClosed())
121
+ if (this.browserContext.isClosingOrClosed())
124
122
  return;
125
- this._frameManager.createDummyMainFrameIfNeeded();
123
+ this.frameManager.createDummyMainFrameIfNeeded();
126
124
  }
127
125
  this._initialized = error || this;
128
126
  this.emitOnContext(contextEvent, this);
129
127
  for (const { event, args } of this._eventsToEmitAfterInitialized)
130
- this._browserContext.emit(event, ...args);
128
+ this.browserContext.emit(event, ...args);
131
129
  this._eventsToEmitAfterInitialized = [];
132
130
  if (this.isClosed())
133
131
  this.emit(Page.Events.Close);
@@ -142,41 +140,32 @@ class Page extends import_instrumentation.SdkObject {
142
140
  return this._initializedPromise;
143
141
  }
144
142
  emitOnContext(event, ...args) {
145
- if (this._isServerSideOnly)
143
+ if (this.isStorageStatePage)
146
144
  return;
147
- this._browserContext.emit(event, ...args);
145
+ this.browserContext.emit(event, ...args);
148
146
  }
149
147
  emitOnContextOnceInitialized(event, ...args) {
150
- if (this._isServerSideOnly)
148
+ if (this.isStorageStatePage)
151
149
  return;
152
150
  if (this._initialized)
153
- this._browserContext.emit(event, ...args);
151
+ this.browserContext.emit(event, ...args);
154
152
  else
155
153
  this._eventsToEmitAfterInitialized.push({ event, args });
156
154
  }
157
- async resetForReuse(metadata) {
158
- this.setDefaultNavigationTimeout(void 0);
159
- this.setDefaultTimeout(void 0);
160
- this._locatorHandlers.clear();
161
- await this._removeExposedBindings();
162
- await this._removeInitScripts();
163
- await this.setClientRequestInterceptor(void 0);
164
- await this._setServerRequestInterceptor(void 0);
165
- await this.setFileChooserIntercepted(false);
166
- await this.mainFrame().goto(metadata, "about:blank");
155
+ async resetForReuse(progress) {
156
+ await this.mainFrame().gotoImpl(progress, "about:blank", {});
167
157
  this._emulatedSize = void 0;
168
158
  this._emulatedMedia = {};
169
159
  this._extraHTTPHeaders = void 0;
170
- this._interceptFileChooser = false;
171
160
  await Promise.all([
172
- this._delegate.updateEmulatedViewportSize(),
173
- this._delegate.updateEmulateMedia(),
174
- this._delegate.updateFileChooserInterception()
161
+ this.delegate.updateEmulatedViewportSize(),
162
+ this.delegate.updateEmulateMedia(),
163
+ this.delegate.updateExtraHTTPHeaders()
175
164
  ]);
176
- await this._delegate.resetForReuse();
165
+ await this.delegate.resetForReuse(progress);
177
166
  }
178
167
  _didClose() {
179
- this._frameManager.dispose();
168
+ this.frameManager.dispose();
180
169
  this._frameThrottler.dispose();
181
170
  (0, import_utils.assert)(this._closedState !== "closed", "Page closed twice");
182
171
  this._closedState = "closed";
@@ -186,7 +175,7 @@ class Page extends import_instrumentation.SdkObject {
186
175
  this.openScope.close(new import_errors.TargetClosedError());
187
176
  }
188
177
  _didCrash() {
189
- this._frameManager.dispose();
178
+ this.frameManager.dispose();
190
179
  this._frameThrottler.dispose();
191
180
  this.emit(Page.Events.Crash);
192
181
  this._crashed = true;
@@ -207,108 +196,110 @@ class Page extends import_instrumentation.SdkObject {
207
196
  const fileChooser = new import_fileChooser.FileChooser(this, handle, multiple);
208
197
  this.emit(Page.Events.FileChooser, fileChooser);
209
198
  }
210
- context() {
211
- return this._browserContext;
212
- }
213
199
  opener() {
214
200
  return this._opener;
215
201
  }
216
202
  mainFrame() {
217
- return this._frameManager.mainFrame();
203
+ return this.frameManager.mainFrame();
218
204
  }
219
205
  frames() {
220
- return this._frameManager.frames();
221
- }
222
- setDefaultNavigationTimeout(timeout) {
223
- this._timeoutSettings.setDefaultNavigationTimeout(timeout);
206
+ return this.frameManager.frames();
224
207
  }
225
- setDefaultTimeout(timeout) {
226
- this._timeoutSettings.setDefaultTimeout(timeout);
227
- }
228
- async exposeBinding(name, needsHandle, playwrightBinding) {
208
+ async exposeBinding(progress, name, needsHandle, playwrightBinding) {
229
209
  if (this._pageBindings.has(name))
230
210
  throw new Error(`Function "${name}" has been already registered`);
231
- if (this._browserContext._pageBindings.has(name))
211
+ if (this.browserContext._pageBindings.has(name))
232
212
  throw new Error(`Function "${name}" has been already registered in the browser context`);
233
213
  const binding = new PageBinding(name, playwrightBinding, needsHandle);
234
214
  this._pageBindings.set(name, binding);
235
- await this._delegate.exposeBinding(binding);
215
+ await this.delegate.exposeBinding(binding);
236
216
  }
237
- async _removeExposedBindings() {
217
+ async removeExposedBindings(bindings) {
238
218
  for (const key of this._pageBindings.keys()) {
239
219
  if (!key.startsWith("__pw"))
240
220
  this._pageBindings.delete(key);
241
221
  }
242
- await this._delegate.removeExposedBindings();
222
+ await this.delegate.removeExposedBindings();
243
223
  }
244
- setExtraHTTPHeaders(headers) {
245
- this._extraHTTPHeaders = headers;
246
- return this._delegate.updateExtraHTTPHeaders();
224
+ async setExtraHTTPHeaders(progress, headers) {
225
+ const oldHeaders = this._extraHTTPHeaders;
226
+ try {
227
+ this._extraHTTPHeaders = headers;
228
+ await progress.race(this.delegate.updateExtraHTTPHeaders());
229
+ } catch (error) {
230
+ this._extraHTTPHeaders = oldHeaders;
231
+ this.delegate.updateExtraHTTPHeaders().catch(() => {
232
+ });
233
+ throw error;
234
+ }
247
235
  }
248
236
  extraHTTPHeaders() {
249
237
  return this._extraHTTPHeaders;
250
238
  }
251
- async _onBindingCalled(payload, context) {
239
+ async onBindingCalled(payload, context) {
252
240
  if (this._closedState === "closed")
253
241
  return;
254
242
  await PageBinding.dispatch(this, payload, context);
255
243
  }
256
- _addConsoleMessage(type, args, location, text) {
244
+ addConsoleMessage(type, args, location, text) {
257
245
  const message = new import_console.ConsoleMessage(this, type, text, args, location);
258
- const intercepted = this._frameManager.interceptConsoleMessage(message);
246
+ const intercepted = this.frameManager.interceptConsoleMessage(message);
259
247
  if (intercepted) {
260
248
  args.forEach((arg) => arg.dispose());
261
249
  return;
262
250
  }
263
251
  this.emitOnContextOnceInitialized(import_browserContext.BrowserContext.Events.Console, message);
264
252
  }
265
- async reload(metadata, options) {
266
- const controller = new import_progress.ProgressController(metadata, this);
267
- return controller.run((progress) => this.mainFrame().raceNavigationAction(progress, options, async () => {
253
+ async reload(progress, options) {
254
+ return this.mainFrame().raceNavigationAction(progress, async () => {
268
255
  const [response] = await Promise.all([
269
256
  // Reload must be a new document, and should not be confused with a stray pushState.
270
257
  this.mainFrame()._waitForNavigation(progress, true, options),
271
- this._delegate.reload()
258
+ progress.race(this.delegate.reload())
272
259
  ]);
273
260
  return response;
274
- }), this._timeoutSettings.navigationTimeout(options));
261
+ });
275
262
  }
276
- async goBack(metadata, options) {
277
- const controller = new import_progress.ProgressController(metadata, this);
278
- return controller.run((progress) => this.mainFrame().raceNavigationAction(progress, options, async () => {
263
+ async goBack(progress, options) {
264
+ return this.mainFrame().raceNavigationAction(progress, async () => {
279
265
  let error;
280
266
  const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {
281
267
  error = e;
282
268
  return null;
283
269
  });
284
- const result = await this._delegate.goBack();
285
- if (!result)
270
+ const result = await progress.race(this.delegate.goBack());
271
+ if (!result) {
272
+ waitPromise.catch(() => {
273
+ });
286
274
  return null;
275
+ }
287
276
  const response = await waitPromise;
288
277
  if (error)
289
278
  throw error;
290
279
  return response;
291
- }), this._timeoutSettings.navigationTimeout(options));
280
+ });
292
281
  }
293
- async goForward(metadata, options) {
294
- const controller = new import_progress.ProgressController(metadata, this);
295
- return controller.run((progress) => this.mainFrame().raceNavigationAction(progress, options, async () => {
282
+ async goForward(progress, options) {
283
+ return this.mainFrame().raceNavigationAction(progress, async () => {
296
284
  let error;
297
285
  const waitPromise = this.mainFrame()._waitForNavigation(progress, false, options).catch((e) => {
298
286
  error = e;
299
287
  return null;
300
288
  });
301
- const result = await this._delegate.goForward();
302
- if (!result)
289
+ const result = await progress.race(this.delegate.goForward());
290
+ if (!result) {
291
+ waitPromise.catch(() => {
292
+ });
303
293
  return null;
294
+ }
304
295
  const response = await waitPromise;
305
296
  if (error)
306
297
  throw error;
307
298
  return response;
308
- }), this._timeoutSettings.navigationTimeout(options));
299
+ });
309
300
  }
310
301
  requestGC() {
311
- return this._delegate.requestGC();
302
+ return this.delegate.requestGC();
312
303
  }
313
304
  registerLocatorHandler(selector, noWaitAfter) {
314
305
  const uid = ++this._lastLocatorHandlerUid;
@@ -329,15 +320,11 @@ class Page extends import_instrumentation.SdkObject {
329
320
  }
330
321
  async performActionPreChecks(progress) {
331
322
  await this._performWaitForNavigationCheck(progress);
332
- progress.throwIfAborted();
333
323
  await this._performLocatorHandlersCheckpoint(progress);
334
- progress.throwIfAborted();
335
324
  await this._performWaitForNavigationCheck(progress);
336
325
  }
337
326
  async _performWaitForNavigationCheck(progress) {
338
- if (process.env.PLAYWRIGHT_SKIP_NAVIGATION_CHECK)
339
- return;
340
- const mainFrame = this._frameManager.mainFrame();
327
+ const mainFrame = this.frameManager.mainFrame();
341
328
  if (!mainFrame || !mainFrame.pendingDocument())
342
329
  return;
343
330
  const url = mainFrame.pendingDocument()?.request?.url();
@@ -356,30 +343,29 @@ class Page extends import_instrumentation.SdkObject {
356
343
  return;
357
344
  for (const [uid, handler] of this._locatorHandlers) {
358
345
  if (!handler.resolved) {
359
- if (await this.mainFrame().isVisibleInternal(handler.selector, { strict: true })) {
346
+ if (await this.mainFrame().isVisibleInternal(progress, handler.selector, { strict: true })) {
360
347
  handler.resolved = new import_manualPromise.ManualPromise();
361
348
  this.emit(Page.Events.LocatorHandlerTriggered, uid);
362
349
  }
363
350
  }
364
351
  if (handler.resolved) {
365
352
  ++this._locatorHandlerRunningCounter;
366
- progress.log(` found ${(0, import_utils2.asLocator)(this.attribution.playwright.options.sdkLanguage, handler.selector)}, intercepting action to run the handler`);
353
+ progress.log(` found ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)}, intercepting action to run the handler`);
367
354
  const promise = handler.resolved.then(async () => {
368
- progress.throwIfAborted();
369
355
  if (!handler.noWaitAfter) {
370
- progress.log(` locator handler has finished, waiting for ${(0, import_utils2.asLocator)(this.attribution.playwright.options.sdkLanguage, handler.selector)} to be hidden`);
371
- await this.mainFrame().waitForSelectorInternal(progress, handler.selector, false, { state: "hidden" });
356
+ progress.log(` locator handler has finished, waiting for ${(0, import_utils2.asLocator)(this.browserContext._browser.sdkLanguage(), handler.selector)} to be hidden`);
357
+ await this.mainFrame().waitForSelector(progress, handler.selector, false, { state: "hidden" });
372
358
  } else {
373
359
  progress.log(` locator handler has finished`);
374
360
  }
375
361
  });
376
- await this.openScope.race(promise).finally(() => --this._locatorHandlerRunningCounter);
377
- progress.throwIfAborted();
362
+ await progress.race(this.openScope.race(promise)).finally(() => --this._locatorHandlerRunningCounter);
378
363
  progress.log(` interception handler has finished, continuing`);
379
364
  }
380
365
  }
381
366
  }
382
- async emulateMedia(options) {
367
+ async emulateMedia(progress, options) {
368
+ const oldEmulatedMedia = { ...this._emulatedMedia };
383
369
  if (options.media !== void 0)
384
370
  this._emulatedMedia.media = options.media;
385
371
  if (options.colorScheme !== void 0)
@@ -390,10 +376,17 @@ class Page extends import_instrumentation.SdkObject {
390
376
  this._emulatedMedia.forcedColors = options.forcedColors;
391
377
  if (options.contrast !== void 0)
392
378
  this._emulatedMedia.contrast = options.contrast;
393
- await this._delegate.updateEmulateMedia();
379
+ try {
380
+ await progress.race(this.delegate.updateEmulateMedia());
381
+ } catch (error) {
382
+ this._emulatedMedia = oldEmulatedMedia;
383
+ this.delegate.updateEmulateMedia().catch(() => {
384
+ });
385
+ throw error;
386
+ }
394
387
  }
395
388
  emulatedMedia() {
396
- const contextOptions = this._browserContext._options;
389
+ const contextOptions = this.browserContext._options;
397
390
  return {
398
391
  media: this._emulatedMedia.media || "no-override",
399
392
  colorScheme: this._emulatedMedia.colorScheme !== void 0 ? this._emulatedMedia.colorScheme : contextOptions.colorScheme ?? "light",
@@ -402,53 +395,78 @@ class Page extends import_instrumentation.SdkObject {
402
395
  contrast: this._emulatedMedia.contrast !== void 0 ? this._emulatedMedia.contrast : contextOptions.contrast ?? "no-preference"
403
396
  };
404
397
  }
405
- async setViewportSize(viewportSize) {
406
- this._emulatedSize = { viewport: { ...viewportSize }, screen: { ...viewportSize } };
407
- await this._delegate.updateEmulatedViewportSize();
398
+ async setViewportSize(progress, viewportSize) {
399
+ const oldEmulatedSize = this._emulatedSize;
400
+ try {
401
+ this._setEmulatedSize({ viewport: { ...viewportSize }, screen: { ...viewportSize } });
402
+ await progress.race(this.delegate.updateEmulatedViewportSize());
403
+ } catch (error) {
404
+ this._emulatedSize = oldEmulatedSize;
405
+ this.delegate.updateEmulatedViewportSize().catch(() => {
406
+ });
407
+ throw error;
408
+ }
409
+ }
410
+ setEmulatedSizeFromWindowOpen(emulatedSize) {
411
+ this._setEmulatedSize(emulatedSize);
408
412
  }
409
- viewportSize() {
410
- return this.emulatedSize()?.viewport || null;
413
+ _setEmulatedSize(emulatedSize) {
414
+ this._emulatedSize = emulatedSize;
415
+ this.emit(Page.Events.EmulatedSizeChanged);
411
416
  }
412
417
  emulatedSize() {
413
418
  if (this._emulatedSize)
414
419
  return this._emulatedSize;
415
- const contextOptions = this._browserContext._options;
416
- return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : null;
420
+ const contextOptions = this.browserContext._options;
421
+ return contextOptions.viewport ? { viewport: contextOptions.viewport, screen: contextOptions.screen || contextOptions.viewport } : void 0;
417
422
  }
418
423
  async bringToFront() {
419
- await this._delegate.bringToFront();
424
+ await this.delegate.bringToFront();
420
425
  }
421
- async addInitScript(source, name) {
422
- const initScript = new InitScript(source, false, name);
426
+ async addInitScript(progress, source) {
427
+ const initScript = new InitScript(source);
423
428
  this.initScripts.push(initScript);
424
- await this._delegate.addInitScript(initScript);
429
+ try {
430
+ await progress.race(this.delegate.addInitScript(initScript));
431
+ } catch (error) {
432
+ this.removeInitScripts([initScript]).catch(() => {
433
+ });
434
+ throw error;
435
+ }
436
+ return initScript;
425
437
  }
426
- async _removeInitScripts() {
438
+ async removeInitScripts(initScripts) {
427
439
  this.initScripts.splice(0, this.initScripts.length);
428
- await this._delegate.removeInitScripts();
440
+ await this.delegate.removeInitScripts();
429
441
  }
430
442
  needsRequestInterception() {
431
- return !!this._clientRequestInterceptor || !!this._serverRequestInterceptor || !!this._browserContext._requestInterceptor;
443
+ return this.requestInterceptors.length > 0 || this.browserContext.requestInterceptors.length > 0;
432
444
  }
433
- async setClientRequestInterceptor(handler) {
434
- this._clientRequestInterceptor = handler;
435
- await this._delegate.updateRequestInterception();
445
+ async addRequestInterceptor(progress, handler, prepend) {
446
+ if (prepend)
447
+ this.requestInterceptors.unshift(handler);
448
+ else
449
+ this.requestInterceptors.push(handler);
450
+ await this.delegate.updateRequestInterception();
436
451
  }
437
- async _setServerRequestInterceptor(handler) {
438
- this._serverRequestInterceptor = handler;
439
- await this._delegate.updateRequestInterception();
452
+ async removeRequestInterceptor(handler) {
453
+ const index = this.requestInterceptors.indexOf(handler);
454
+ if (index === -1)
455
+ return;
456
+ this.requestInterceptors.splice(index, 1);
457
+ await this.browserContext.notifyRoutesInFlightAboutRemovedHandler(handler);
458
+ await this.delegate.updateRequestInterception();
440
459
  }
441
- async expectScreenshot(metadata, options = {}) {
460
+ async expectScreenshot(progress, options) {
442
461
  const locator = options.locator;
443
- const rafrafScreenshot = locator ? async (progress, timeout) => {
462
+ const rafrafScreenshot = locator ? async (timeout) => {
444
463
  return await locator.frame.rafrafTimeoutScreenshotElementWithProgress(progress, locator.selector, timeout, options || {});
445
- } : async (progress, timeout) => {
464
+ } : async (timeout) => {
446
465
  await this.performActionPreChecks(progress);
447
- await this.mainFrame().rafrafTimeout(timeout);
448
- return await this._screenshotter.screenshotPage(progress, options || {});
466
+ await this.mainFrame().rafrafTimeout(progress, timeout);
467
+ return await this.screenshotter.screenshotPage(progress, options || {});
449
468
  };
450
469
  const comparator = (0, import_comparators.getComparator)("image/png");
451
- const controller = new import_progress.ProgressController(metadata, this);
452
470
  if (!options.expected && options.isNot)
453
471
  return { errorMessage: '"not" matcher requires expected result' };
454
472
  try {
@@ -458,7 +476,7 @@ class Page extends import_instrumentation.SdkObject {
458
476
  } catch (error) {
459
477
  return { errorMessage: error.message };
460
478
  }
461
- let intermediateResult = void 0;
479
+ let intermediateResult;
462
480
  const areEqualScreenshots = (actual, expected, previous) => {
463
481
  const comparatorResult = actual && expected ? comparator(actual, expected, options) : void 0;
464
482
  if (comparatorResult !== void 0 && !!comparatorResult === !!options.isNot)
@@ -467,26 +485,26 @@ class Page extends import_instrumentation.SdkObject {
467
485
  intermediateResult = { errorMessage: comparatorResult.errorMessage, diff: comparatorResult.diff, actual, previous };
468
486
  return false;
469
487
  };
470
- const callTimeout = this._timeoutSettings.timeout(options);
471
- return controller.run(async (progress) => {
488
+ try {
472
489
  let actual;
473
490
  let previous;
474
491
  const pollIntervals = [0, 100, 250, 500];
475
- progress.log(`${metadata.apiName}${callTimeout ? ` with timeout ${callTimeout}ms` : ""}`);
492
+ progress.log(`${(0, import_utils.renderTitleForCall)(progress.metadata)}${options.timeout ? ` with timeout ${options.timeout}ms` : ""}`);
476
493
  if (options.expected)
477
494
  progress.log(` verifying given screenshot expectation`);
478
495
  else
479
496
  progress.log(` generating new stable screenshot expectation`);
480
497
  let isFirstIteration = true;
481
498
  while (true) {
482
- progress.throwIfAborted();
483
499
  if (this.isClosed())
484
500
  throw new Error("The page has closed");
485
501
  const screenshotTimeout = pollIntervals.shift() ?? 1e3;
486
502
  if (screenshotTimeout)
487
503
  progress.log(`waiting ${screenshotTimeout}ms before taking screenshot`);
488
504
  previous = actual;
489
- actual = await rafrafScreenshot(progress, screenshotTimeout).catch((e) => {
505
+ actual = await rafrafScreenshot(screenshotTimeout).catch((e) => {
506
+ if (this.mainFrame().isNonRetriableError(e))
507
+ throw e;
490
508
  progress.log(`failed to take screenshot - ` + e.message);
491
509
  return void 0;
492
510
  });
@@ -512,41 +530,35 @@ class Page extends import_instrumentation.SdkObject {
512
530
  return {};
513
531
  }
514
532
  throw new Error(intermediateResult.errorMessage);
515
- }, callTimeout).catch((e) => {
533
+ } catch (e) {
516
534
  if (js.isJavaScriptErrorInEvaluate(e) || (0, import_selectorParser.isInvalidSelectorError)(e))
517
535
  throw e;
518
536
  let errorMessage = e.message;
519
537
  if (e instanceof import_errors.TimeoutError && intermediateResult?.previous)
520
538
  errorMessage = `Failed to take two consecutive stable screenshots.`;
521
539
  return {
522
- log: (0, import_callLog.compressCallLog)(e.message ? [...metadata.log, e.message] : metadata.log),
540
+ log: (0, import_callLog.compressCallLog)(e.message ? [...progress.metadata.log, e.message] : progress.metadata.log),
523
541
  ...intermediateResult,
524
542
  errorMessage,
525
543
  timedOut: e instanceof import_errors.TimeoutError
526
544
  };
527
- });
545
+ }
528
546
  }
529
- async screenshot(metadata, options = {}) {
530
- const controller = new import_progress.ProgressController(metadata, this);
531
- return controller.run(
532
- (progress) => this._screenshotter.screenshotPage(progress, options),
533
- this._timeoutSettings.timeout(options)
534
- );
547
+ async screenshot(progress, options) {
548
+ return await this.screenshotter.screenshotPage(progress, options);
535
549
  }
536
- async close(metadata, options = {}) {
550
+ async close(options = {}) {
537
551
  if (this._closedState === "closed")
538
552
  return;
539
553
  if (options.reason)
540
- this._closeReason = options.reason;
554
+ this.closeReason = options.reason;
541
555
  const runBeforeUnload = !!options.runBeforeUnload;
542
556
  if (this._closedState !== "closing") {
543
557
  this._closedState = "closing";
544
- await this._delegate.closePage(runBeforeUnload).catch((e) => import_debugLogger.debugLogger.log("error", e));
558
+ await this.delegate.closePage(runBeforeUnload).catch((e) => import_debugLogger.debugLogger.log("error", e));
545
559
  }
546
560
  if (!runBeforeUnload)
547
561
  await this._closedPromise;
548
- if (this._ownedContext)
549
- await this._ownedContext.close(options);
550
562
  }
551
563
  isClosed() {
552
564
  return this._closedState === "closed";
@@ -557,41 +569,46 @@ class Page extends import_instrumentation.SdkObject {
557
569
  isClosedOrClosingOrCrashed() {
558
570
  return this._closedState !== "open" || this._crashed;
559
571
  }
560
- _addWorker(workerId, worker) {
572
+ addWorker(workerId, worker) {
561
573
  this._workers.set(workerId, worker);
562
574
  this.emit(Page.Events.Worker, worker);
563
575
  }
564
- _removeWorker(workerId) {
576
+ removeWorker(workerId) {
565
577
  const worker = this._workers.get(workerId);
566
578
  if (!worker)
567
579
  return;
568
580
  worker.didClose();
569
581
  this._workers.delete(workerId);
570
582
  }
571
- _clearWorkers() {
583
+ clearWorkers() {
572
584
  for (const [workerId, worker] of this._workers) {
573
585
  worker.didClose();
574
586
  this._workers.delete(workerId);
575
587
  }
576
588
  }
577
- async setFileChooserIntercepted(enabled) {
578
- this._interceptFileChooser = enabled;
579
- await this._delegate.updateFileChooserInterception();
589
+ async setFileChooserInterceptedBy(enabled, by) {
590
+ const wasIntercepted = this.fileChooserIntercepted();
591
+ if (enabled)
592
+ this._fileChooserInterceptedBy.add(by);
593
+ else
594
+ this._fileChooserInterceptedBy.delete(by);
595
+ if (wasIntercepted !== this.fileChooserIntercepted())
596
+ await this.delegate.updateFileChooserInterception();
580
597
  }
581
598
  fileChooserIntercepted() {
582
- return this._interceptFileChooser;
599
+ return this._fileChooserInterceptedBy.size > 0;
583
600
  }
584
601
  frameNavigatedToNewDocument(frame) {
585
602
  this.emit(Page.Events.InternalFrameNavigatedToNewDocument, frame);
586
603
  const origin = frame.origin();
587
604
  if (origin)
588
- this._browserContext.addVisitedOrigin(origin);
605
+ this.browserContext.addVisitedOrigin(origin);
589
606
  }
590
607
  getBinding(name) {
591
- return this._pageBindings.get(name) || this._browserContext._pageBindings.get(name);
608
+ return this._pageBindings.get(name) || this.browserContext._pageBindings.get(name);
592
609
  }
593
610
  setScreencastOptions(options) {
594
- this._delegate.setScreencastOptions(options).catch((e) => import_debugLogger.debugLogger.log("error", e));
611
+ this.delegate.setScreencastOptions(options).catch((e) => import_debugLogger.debugLogger.log("error", e));
595
612
  this._frameThrottler.setThrottlingEnabled(!!options);
596
613
  }
597
614
  throttleScreencastFrameAck(ack) {
@@ -614,19 +631,21 @@ class Page extends import_instrumentation.SdkObject {
614
631
  await Promise.all(this.frames().map((frame) => frame.hideHighlight().catch(() => {
615
632
  })));
616
633
  }
617
- markAsServerSideOnly() {
618
- this._isServerSideOnly = true;
634
+ async snapshotForAI(progress) {
635
+ this.lastSnapshotFrameIds = [];
636
+ const snapshot = await snapshotFrameForAI(progress, this.mainFrame(), 0, this.lastSnapshotFrameIds);
637
+ return snapshot.join("\n");
619
638
  }
620
639
  allBindings() {
621
- return [...this._browserContext._pageBindings.values(), ...this._pageBindings.values()];
640
+ return [...this.browserContext._pageBindings.values(), ...this._pageBindings.values()];
622
641
  }
623
642
  }
624
643
  class Worker extends import_instrumentation.SdkObject {
625
644
  constructor(parent, url) {
626
645
  super(parent, "worker");
627
- this._existingExecutionContext = null;
646
+ this.existingExecutionContext = null;
628
647
  this.openScope = new import_utils.LongStandingScope();
629
- this._url = url;
648
+ this.url = url;
630
649
  this._executionContextCallback = () => {
631
650
  };
632
651
  this._executionContextPromise = new Promise((x) => this._executionContextCallback = x);
@@ -636,17 +655,14 @@ class Worker extends import_instrumentation.SdkObject {
636
655
  Close: "close"
637
656
  };
638
657
  }
639
- _createExecutionContext(delegate) {
640
- this._existingExecutionContext = new js.ExecutionContext(this, delegate, "worker");
641
- this._executionContextCallback(this._existingExecutionContext);
642
- return this._existingExecutionContext;
643
- }
644
- url() {
645
- return this._url;
658
+ createExecutionContext(delegate) {
659
+ this.existingExecutionContext = new js.ExecutionContext(this, delegate, "worker");
660
+ this._executionContextCallback(this.existingExecutionContext);
661
+ return this.existingExecutionContext;
646
662
  }
647
663
  didClose() {
648
- if (this._existingExecutionContext)
649
- this._existingExecutionContext.contextDestroyed("Worker was closed");
664
+ if (this.existingExecutionContext)
665
+ this.existingExecutionContext.contextDestroyed("Worker was closed");
650
666
  this.emit(Worker.Events.Close, this);
651
667
  this.openScope.close(new Error("Worker closed"));
652
668
  }
@@ -663,7 +679,7 @@ class Worker extends import_instrumentation.SdkObject {
663
679
  }
664
680
  async evaluateExpressionHandle(expression, isFunction, arg, isolatedContext) {
665
681
  let context = await this._executionContextPromise;
666
- if (this._context.constructor.name === "FrameExecutionContext") {
682
+ if (context.constructor.name === "FrameExecutionContext") {
667
683
  const frame = this._context.frame;
668
684
  if (frame) {
669
685
  if (isolatedContext) context = await frame._utilityContext();
@@ -694,7 +710,7 @@ class PageBinding {
694
710
  } else {
695
711
  if (!Array.isArray(serializedArgs))
696
712
  throw new Error(`serializedArgs is not an array. This can happen when Array.prototype.toJSON is defined incorrectly`);
697
- const args = serializedArgs.map((a) => js.parseEvaluationResultValue(a));
713
+ const args = serializedArgs.map((a) => (0, import_utilityScriptSerializers.parseEvaluationResultValue)(a));
698
714
  result = await binding.playwrightFunction({ frame: context.frame, page, context: page._browserContext }, ...args);
699
715
  }
700
716
  context.evaluate(import_pageBinding.deliverBindingResult, { name, seq, result }).catch((e) => import_debugLogger.debugLogger.log("error", e));
@@ -704,18 +720,10 @@ class PageBinding {
704
720
  }
705
721
  }
706
722
  class InitScript {
707
- constructor(source, internal, name) {
708
- const guid = (0, import_crypto.createGuid)();
723
+ constructor(source) {
709
724
  this.source = `(() => { ${source} })();`;
710
- this.internal = !!internal;
711
- this.name = name;
712
725
  }
713
726
  }
714
- const kBuiltinsScript = new InitScript(
715
- `(${import_builtins.builtins})()`,
716
- true
717
- /* internal */
718
- );
719
727
  class FrameThrottler {
720
728
  constructor(nonThrottledFrames, defaultInterval, throttlingInterval) {
721
729
  this._acks = [];
@@ -765,11 +773,58 @@ class FrameThrottler {
765
773
  }
766
774
  }
767
775
  }
776
+ async function snapshotFrameForAI(progress, frame, frameOrdinal, frameIds) {
777
+ const snapshot = await frame.retryWithProgressAndTimeouts(progress, [1e3, 2e3, 4e3, 8e3], async (continuePolling) => {
778
+ try {
779
+ const context = await progress.race(frame._utilityContext());
780
+ const injectedScript = await progress.race(context.injectedScript());
781
+ const snapshotOrRetry = await progress.race(injectedScript.evaluate((injected, refPrefix) => {
782
+ const node = injected.document.body;
783
+ if (!node)
784
+ return true;
785
+ return injected.ariaSnapshot(node, { mode: "ai", refPrefix });
786
+ }, frameOrdinal ? "f" + frameOrdinal : ""));
787
+ if (snapshotOrRetry === true)
788
+ return continuePolling;
789
+ return snapshotOrRetry;
790
+ } catch (e) {
791
+ if (frame.isNonRetriableError(e))
792
+ throw e;
793
+ return continuePolling;
794
+ }
795
+ });
796
+ const lines = snapshot.split("\n");
797
+ const result = [];
798
+ for (const line of lines) {
799
+ const match = line.match(/^(\s*)- iframe (?:\[active\] )?\[ref=([^\]]*)\]/);
800
+ if (!match) {
801
+ result.push(line);
802
+ continue;
803
+ }
804
+ const leadingSpace = match[1];
805
+ const ref = match[2];
806
+ const frameSelector = `aria-ref=${ref} >> internal:control=enter-frame`;
807
+ const frameBodySelector = `${frameSelector} >> body`;
808
+ const child = await progress.race(frame.selectors.resolveFrameForSelector(frameBodySelector, { strict: true }));
809
+ if (!child) {
810
+ result.push(line);
811
+ continue;
812
+ }
813
+ const frameOrdinal2 = frameIds.length + 1;
814
+ frameIds.push(child.frame._id);
815
+ try {
816
+ const childSnapshot = await snapshotFrameForAI(progress, child.frame, frameOrdinal2, frameIds);
817
+ result.push(line + ":", ...childSnapshot.map((l) => leadingSpace + " " + l));
818
+ } catch {
819
+ result.push(line);
820
+ }
821
+ }
822
+ return result;
823
+ }
768
824
  // Annotate the CommonJS export names for ESM import in node:
769
825
  0 && (module.exports = {
770
826
  InitScript,
771
827
  Page,
772
828
  PageBinding,
773
- Worker,
774
- kBuiltinsScript
829
+ Worker
775
830
  });