patchright-core 1.51.3 → 1.52.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 (303) hide show
  1. package/browsers.json +15 -13
  2. package/lib/androidServerImpl.js +42 -48
  3. package/lib/browserServerImpl.js +54 -67
  4. package/lib/cli/driver.js +71 -69
  5. package/lib/cli/program.js +312 -328
  6. package/lib/cli/programWithTestStub.js +51 -45
  7. package/lib/client/accessibility.js +31 -32
  8. package/lib/client/android.js +141 -228
  9. package/lib/client/api.js +135 -283
  10. package/lib/client/artifact.js +39 -36
  11. package/lib/client/browser.js +57 -61
  12. package/lib/client/browserContext.js +297 -326
  13. package/lib/client/browserType.js +92 -106
  14. package/lib/client/cdpSession.js +29 -31
  15. package/lib/client/channelOwner.js +82 -95
  16. package/lib/client/clientHelper.js +46 -38
  17. package/lib/client/clientInstrumentation.js +40 -37
  18. package/lib/client/clientStackTrace.js +41 -37
  19. package/lib/client/clock.js +36 -36
  20. package/lib/client/connection.js +190 -212
  21. package/lib/client/consoleMessage.js +31 -28
  22. package/lib/client/coverage.js +25 -22
  23. package/lib/client/dialog.js +30 -31
  24. package/lib/client/download.js +25 -25
  25. package/lib/client/electron.js +73 -75
  26. package/lib/client/elementHandle.js +111 -147
  27. package/lib/client/errors.js +53 -53
  28. package/lib/client/eventEmitter.js +124 -121
  29. package/lib/client/events.js +72 -68
  30. package/lib/client/fetch.js +135 -158
  31. package/lib/client/fileChooser.js +25 -24
  32. package/lib/client/fileUtils.js +31 -28
  33. package/lib/client/frame.js +187 -306
  34. package/lib/client/harRouter.js +42 -52
  35. package/lib/client/input.js +40 -69
  36. package/lib/client/jsHandle.js +54 -69
  37. package/lib/client/jsonPipe.js +27 -23
  38. package/lib/client/localUtils.js +29 -28
  39. package/lib/client/locator.js +161 -245
  40. package/lib/client/network.js +277 -295
  41. package/lib/client/page.js +270 -318
  42. package/lib/client/platform.js +46 -43
  43. package/lib/client/playwright.js +51 -66
  44. package/lib/client/selectors.js +48 -46
  45. package/lib/client/stream.js +29 -25
  46. package/lib/client/timeoutSettings.js +49 -39
  47. package/lib/client/tracing.js +48 -84
  48. package/lib/client/types.js +26 -22
  49. package/lib/client/video.js +35 -27
  50. package/lib/client/waiter.js +69 -88
  51. package/lib/client/webError.js +25 -23
  52. package/lib/client/webSocket.js +61 -56
  53. package/lib/client/worker.js +48 -58
  54. package/lib/client/writableStream.js +27 -23
  55. package/lib/generated/clockSource.js +26 -5
  56. package/lib/generated/consoleApiSource.js +26 -5
  57. package/lib/generated/injectedScriptSource.js +26 -5
  58. package/lib/generated/pollingRecorderSource.js +26 -5
  59. package/lib/generated/utilityScriptSource.js +26 -5
  60. package/lib/generated/webSocketMockSource.js +375 -4
  61. package/lib/inProcessFactory.js +53 -53
  62. package/lib/inprocess.js +2 -19
  63. package/lib/outofprocess.js +53 -46
  64. package/lib/protocol/debug.js +209 -25
  65. package/lib/protocol/serializers.js +153 -134
  66. package/lib/protocol/validator.js +2714 -2714
  67. package/lib/protocol/validatorPrimitives.js +114 -73
  68. package/lib/remote/playwrightConnection.js +140 -157
  69. package/lib/remote/playwrightServer.js +99 -84
  70. package/lib/server/accessibility.js +44 -37
  71. package/lib/server/android/android.js +216 -209
  72. package/lib/server/android/backendAdb.js +89 -82
  73. package/lib/server/artifact.js +78 -55
  74. package/lib/server/bidi/bidiBrowser.js +221 -155
  75. package/lib/server/bidi/bidiChromium.js +106 -79
  76. package/lib/server/bidi/bidiConnection.js +66 -83
  77. package/lib/server/bidi/bidiExecutionContext.js +128 -113
  78. package/lib/server/bidi/bidiFirefox.js +76 -69
  79. package/lib/server/bidi/bidiInput.js +86 -97
  80. package/lib/server/bidi/bidiNetworkManager.js +137 -154
  81. package/lib/server/bidi/bidiOverCdp.js +57 -58
  82. package/lib/server/bidi/bidiPage.js +247 -219
  83. package/lib/server/bidi/bidiPdf.js +52 -86
  84. package/lib/server/bidi/third_party/bidiCommands.d.js +22 -0
  85. package/lib/server/bidi/third_party/bidiDeserializer.js +55 -50
  86. package/lib/server/bidi/third_party/bidiKeyboard.js +236 -220
  87. package/lib/server/bidi/third_party/bidiProtocol.js +144 -131
  88. package/lib/server/bidi/third_party/bidiSerializer.js +67 -63
  89. package/lib/server/bidi/third_party/firefoxPrefs.js +141 -119
  90. package/lib/server/browser.js +76 -84
  91. package/lib/server/browserContext.js +321 -346
  92. package/lib/server/browserType.js +169 -182
  93. package/lib/server/callLog.js +47 -44
  94. package/lib/server/chromium/chromium.js +212 -190
  95. package/lib/server/chromium/chromiumSwitches.js +86 -64
  96. package/lib/server/chromium/crAccessibility.js +157 -131
  97. package/lib/server/chromium/crBrowser.js +253 -273
  98. package/lib/server/chromium/crConnection.js +91 -116
  99. package/lib/server/chromium/crCoverage.js +113 -127
  100. package/lib/server/chromium/crDevTools.js +59 -51
  101. package/lib/server/chromium/crDragDrop.js +62 -79
  102. package/lib/server/chromium/crExecutionContext.js +88 -83
  103. package/lib/server/chromium/crInput.js +97 -95
  104. package/lib/server/chromium/crNetworkManager.js +284 -404
  105. package/lib/server/chromium/crPage.js +522 -608
  106. package/lib/server/chromium/crPdf.js +54 -86
  107. package/lib/server/chromium/crProtocolHelper.js +92 -80
  108. package/lib/server/chromium/crServiceWorker.js +82 -67
  109. package/lib/server/chromium/defaultFontFamilies.js +152 -135
  110. package/lib/server/chromium/protocol.d.js +16 -0
  111. package/lib/server/chromium/videoRecorder.js +65 -99
  112. package/lib/server/clock.js +62 -50
  113. package/lib/server/codegen/csharp.js +185 -160
  114. package/lib/server/codegen/java.js +155 -128
  115. package/lib/server/codegen/javascript.js +163 -148
  116. package/lib/server/codegen/jsonl.js +32 -28
  117. package/lib/server/codegen/language.js +75 -52
  118. package/lib/server/codegen/languages.js +65 -27
  119. package/lib/server/codegen/python.js +140 -125
  120. package/lib/server/codegen/types.js +15 -4
  121. package/lib/server/console.js +28 -32
  122. package/lib/server/cookieStore.js +105 -86
  123. package/lib/server/debugController.js +97 -124
  124. package/lib/server/debugger.js +82 -78
  125. package/lib/server/deviceDescriptors.js +37 -24
  126. package/lib/server/deviceDescriptorsSource.json +50 -50
  127. package/lib/server/dialog.js +36 -35
  128. package/lib/server/dispatchers/androidDispatcher.js +196 -107
  129. package/lib/server/dispatchers/artifactDispatcher.js +62 -62
  130. package/lib/server/dispatchers/browserContextDispatcher.js +176 -205
  131. package/lib/server/dispatchers/browserDispatcher.js +78 -97
  132. package/lib/server/dispatchers/browserTypeDispatcher.js +35 -35
  133. package/lib/server/dispatchers/cdpSessionDispatcher.js +32 -36
  134. package/lib/server/dispatchers/debugControllerDispatcher.js +48 -66
  135. package/lib/server/dispatchers/dialogDispatcher.js +30 -27
  136. package/lib/server/dispatchers/dispatcher.js +169 -220
  137. package/lib/server/dispatchers/electronDispatcher.js +54 -57
  138. package/lib/server/dispatchers/elementHandlerDispatcher.js +77 -119
  139. package/lib/server/dispatchers/frameDispatcher.js +99 -163
  140. package/lib/server/dispatchers/jsHandleDispatcher.js +49 -66
  141. package/lib/server/dispatchers/jsonPipeDispatcher.js +35 -36
  142. package/lib/server/dispatchers/localUtilsDispatcher.js +95 -80
  143. package/lib/server/dispatchers/networkDispatchers.js +90 -107
  144. package/lib/server/dispatchers/pageDispatcher.js +128 -169
  145. package/lib/server/dispatchers/playwrightDispatcher.js +69 -76
  146. package/lib/server/dispatchers/selectorsDispatcher.js +28 -24
  147. package/lib/server/dispatchers/streamDispatcher.js +42 -45
  148. package/lib/server/dispatchers/tracingDispatcher.js +36 -41
  149. package/lib/server/dispatchers/webSocketRouteDispatcher.js +96 -131
  150. package/lib/server/dispatchers/writableStreamDispatcher.js +54 -38
  151. package/lib/server/dom.js +413 -443
  152. package/lib/server/download.js +45 -35
  153. package/lib/server/electron/electron.js +156 -176
  154. package/lib/server/electron/loader.js +8 -36
  155. package/lib/server/errors.js +47 -46
  156. package/lib/server/fetch.js +289 -323
  157. package/lib/server/fileChooser.js +25 -24
  158. package/lib/server/fileUploadUtils.js +65 -59
  159. package/lib/server/firefox/ffAccessibility.js +153 -131
  160. package/lib/server/firefox/ffBrowser.js +213 -277
  161. package/lib/server/firefox/ffConnection.js +63 -84
  162. package/lib/server/firefox/ffExecutionContext.js +91 -73
  163. package/lib/server/firefox/ffInput.js +67 -69
  164. package/lib/server/firefox/ffNetworkManager.js +131 -110
  165. package/lib/server/firefox/ffPage.js +236 -273
  166. package/lib/server/firefox/firefox.js +76 -67
  167. package/lib/server/firefox/protocol.d.js +16 -0
  168. package/lib/server/formData.js +107 -35
  169. package/lib/server/frameSelectors.js +77 -111
  170. package/lib/server/frames.js +730 -894
  171. package/lib/server/har/harRecorder.js +85 -77
  172. package/lib/server/har/harTracer.js +287 -222
  173. package/lib/server/harBackend.js +80 -80
  174. package/lib/server/helper.js +56 -59
  175. package/lib/server/index.js +59 -99
  176. package/lib/server/input.js +134 -163
  177. package/lib/server/instrumentation.js +49 -44
  178. package/lib/server/javascript.js +143 -134
  179. package/lib/server/launchApp.js +92 -73
  180. package/lib/server/localUtils.js +130 -122
  181. package/lib/server/macEditingCommands.js +141 -137
  182. package/lib/server/network.js +262 -296
  183. package/lib/server/page.js +329 -426
  184. package/lib/server/pageBinding.js +88 -0
  185. package/lib/server/pipeTransport.js +49 -45
  186. package/lib/server/playwright.js +60 -67
  187. package/lib/server/progress.js +56 -51
  188. package/lib/server/protocolError.js +34 -31
  189. package/lib/server/recorder/chat.js +70 -86
  190. package/lib/server/recorder/contextRecorder.js +134 -138
  191. package/lib/server/recorder/recorderApp.js +127 -136
  192. package/lib/server/recorder/recorderCollection.js +56 -44
  193. package/lib/server/recorder/recorderFrontend.js +15 -4
  194. package/lib/server/recorder/recorderRunner.js +79 -103
  195. package/lib/server/recorder/recorderUtils.js +56 -45
  196. package/lib/server/recorder/throttledFile.js +42 -30
  197. package/lib/server/recorder.js +177 -186
  198. package/lib/server/registry/browserFetcher.js +106 -101
  199. package/lib/server/registry/dependencies.js +245 -196
  200. package/lib/server/registry/index.js +904 -792
  201. package/lib/server/registry/nativeDeps.js +1073 -464
  202. package/lib/server/registry/oopDownloadBrowserMain.js +57 -75
  203. package/lib/server/screenshotter.js +166 -182
  204. package/lib/server/selectors.js +85 -46
  205. package/lib/server/socksClientCertificatesInterceptor.js +166 -185
  206. package/lib/server/socksInterceptor.js +62 -70
  207. package/lib/server/storageScript.js +94 -100
  208. package/lib/server/timeoutSettings.js +58 -43
  209. package/lib/server/trace/recorder/snapshotter.js +70 -89
  210. package/lib/server/trace/recorder/snapshotterInjected.js +238 -217
  211. package/lib/server/trace/recorder/tracing.js +321 -333
  212. package/lib/server/trace/test/inMemorySnapshotter.js +46 -52
  213. package/lib/server/trace/viewer/traceViewer.js +168 -146
  214. package/lib/server/transport.js +124 -133
  215. package/lib/server/types.js +26 -22
  216. package/lib/server/usKeyboardLayout.js +135 -545
  217. package/lib/server/utils/ascii.js +39 -26
  218. package/lib/server/utils/comparators.js +105 -103
  219. package/lib/server/utils/crypto.js +157 -112
  220. package/lib/server/utils/debug.js +37 -28
  221. package/lib/server/utils/debugLogger.js +69 -48
  222. package/lib/server/utils/env.js +52 -37
  223. package/lib/server/utils/eventsHelper.js +29 -28
  224. package/lib/server/utils/expectUtils.js +31 -26
  225. package/lib/server/utils/fileUtils.js +123 -136
  226. package/lib/server/utils/happyEyeballs.js +138 -123
  227. package/lib/server/utils/hostPlatform.js +84 -120
  228. package/lib/server/utils/httpServer.js +106 -121
  229. package/lib/server/utils/image_tools/colorUtils.js +42 -51
  230. package/lib/server/utils/image_tools/compare.js +44 -43
  231. package/lib/server/utils/image_tools/imageChannel.js +38 -30
  232. package/lib/server/utils/image_tools/stats.js +40 -40
  233. package/lib/server/utils/linuxUtils.js +50 -37
  234. package/lib/server/utils/network.js +143 -86
  235. package/lib/server/utils/nodePlatform.js +87 -79
  236. package/lib/server/utils/pipeTransport.js +44 -42
  237. package/lib/server/utils/processLauncher.js +111 -121
  238. package/lib/server/utils/profiler.js +52 -39
  239. package/lib/server/utils/socksProxy.js +280 -339
  240. package/lib/server/utils/spawnAsync.js +37 -41
  241. package/lib/server/utils/task.js +31 -38
  242. package/lib/server/utils/userAgent.js +73 -66
  243. package/lib/server/utils/wsServer.js +73 -69
  244. package/lib/server/utils/zipFile.js +36 -37
  245. package/lib/server/utils/zones.js +37 -34
  246. package/lib/server/webkit/protocol.d.js +16 -0
  247. package/lib/server/webkit/webkit.js +76 -63
  248. package/lib/server/webkit/wkAccessibility.js +161 -118
  249. package/lib/server/webkit/wkBrowser.js +159 -176
  250. package/lib/server/webkit/wkConnection.js +59 -83
  251. package/lib/server/webkit/wkExecutionContext.js +84 -70
  252. package/lib/server/webkit/wkInput.js +82 -80
  253. package/lib/server/webkit/wkInterceptableRequest.js +102 -95
  254. package/lib/server/webkit/wkPage.js +525 -619
  255. package/lib/server/webkit/wkProvisionalPage.js +45 -56
  256. package/lib/server/webkit/wkWorkers.js +77 -77
  257. package/lib/utils/isomorphic/ariaSnapshot.js +144 -152
  258. package/lib/utils/isomorphic/assert.js +28 -22
  259. package/lib/utils/isomorphic/builtins.js +90 -0
  260. package/lib/utils/isomorphic/colors.js +66 -59
  261. package/lib/utils/isomorphic/cssParser.js +121 -125
  262. package/lib/utils/isomorphic/cssTokenizer.js +436 -364
  263. package/lib/utils/isomorphic/headers.js +38 -37
  264. package/lib/utils/isomorphic/locatorGenerators.js +340 -357
  265. package/lib/utils/isomorphic/locatorParser.js +96 -105
  266. package/lib/utils/isomorphic/locatorUtils.js +63 -44
  267. package/lib/utils/isomorphic/manualPromise.js +47 -39
  268. package/lib/utils/isomorphic/mimeType.js +448 -25
  269. package/lib/utils/isomorphic/multimap.js +35 -27
  270. package/lib/utils/isomorphic/rtti.js +35 -33
  271. package/lib/utils/isomorphic/selectorParser.js +183 -193
  272. package/lib/utils/isomorphic/semaphore.js +27 -24
  273. package/lib/utils/isomorphic/stackTrace.js +87 -98
  274. package/lib/utils/isomorphic/stringUtils.js +113 -106
  275. package/lib/utils/isomorphic/time.js +41 -22
  276. package/lib/utils/isomorphic/timeoutRunner.js +55 -54
  277. package/lib/utils/isomorphic/traceUtils.js +38 -41
  278. package/lib/utils/isomorphic/types.js +15 -4
  279. package/lib/utils/isomorphic/urlMatch.js +112 -67
  280. package/lib/utils/isomorphic/utilityScriptSerializers.js +248 -0
  281. package/lib/utils.js +97 -443
  282. package/lib/utilsBundle.js +101 -52
  283. package/lib/vite/htmlReport/index.html +21 -15
  284. package/lib/vite/recorder/assets/{codeMirrorModule-B9YMkrwa.js → codeMirrorModule-DVQi6prl.js} +1 -1
  285. package/lib/vite/recorder/assets/index-97EUAAbk.js +184 -0
  286. package/lib/vite/recorder/index.html +1 -1
  287. package/lib/vite/traceViewer/assets/{codeMirrorModule-1DiydmYA.js → codeMirrorModule-dvXVzLxY.js} +1 -1
  288. package/lib/vite/traceViewer/assets/defaultSettingsView-BjymbO6M.js +265 -0
  289. package/lib/vite/traceViewer/{defaultSettingsView.5fN5lw10.css → defaultSettingsView.QdHITyLI.css} +1 -1
  290. package/lib/vite/traceViewer/index.ChIUCJnj.js +2 -0
  291. package/lib/vite/traceViewer/index.html +3 -3
  292. package/lib/vite/traceViewer/sw.bundle.js +3 -3
  293. package/lib/vite/traceViewer/uiMode.html +3 -3
  294. package/lib/vite/traceViewer/uiMode.jUCiCtdp.js +5 -0
  295. package/lib/zipBundle.js +32 -23
  296. package/package.json +1 -1
  297. package/types/protocol.d.ts +436 -17
  298. package/types/types.d.ts +35 -16
  299. package/lib/server/isomorphic/utilityScriptSerializers.js +0 -229
  300. package/lib/vite/recorder/assets/index-ELPgmkwA.js +0 -184
  301. package/lib/vite/traceViewer/assets/defaultSettingsView-l0TyP_G8.js +0 -259
  302. package/lib/vite/traceViewer/index.BqUZLSro.js +0 -2
  303. package/lib/vite/traceViewer/uiMode.C1d2m5sF.js +0 -5
@@ -1,94 +1,109 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var browserContext_exports = {};
30
+ __export(browserContext_exports, {
31
+ BrowserContext: () => BrowserContext,
32
+ assertBrowserContextIsNotOwned: () => assertBrowserContextIsNotOwned,
33
+ normalizeProxySettings: () => normalizeProxySettings,
34
+ validateBrowserContextOptions: () => validateBrowserContextOptions,
35
+ verifyClientCertificates: () => verifyClientCertificates,
36
+ verifyGeolocation: () => verifyGeolocation
5
37
  });
6
- exports.BrowserContext = void 0;
7
- exports.assertBrowserContextIsNotOwned = assertBrowserContextIsNotOwned;
8
- exports.normalizeProxySettings = normalizeProxySettings;
9
- exports.validateBrowserContextOptions = validateBrowserContextOptions;
10
- exports.verifyClientCertificates = verifyClientCertificates;
11
- exports.verifyGeolocation = verifyGeolocation;
12
- var _fs = _interopRequireDefault(require("fs"));
13
- var _path = _interopRequireDefault(require("path"));
14
- var _timeoutSettings = require("./timeoutSettings");
15
- var _crypto = require("./utils/crypto");
16
- var _debug = require("./utils/debug");
17
- var _clock = require("./clock");
18
- var _debugger = require("./debugger");
19
- var _fetch = require("./fetch");
20
- var _fileUtils = require("./utils/fileUtils");
21
- var _harRecorder = require("./har/harRecorder");
22
- var _helper = require("./helper");
23
- var _instrumentation = require("./instrumentation");
24
- var utilityScriptSerializers = _interopRequireWildcard(require("./isomorphic/utilityScriptSerializers"));
25
- var network = _interopRequireWildcard(require("./network"));
26
- var _page6 = require("./page");
27
- var _recorder = require("./recorder");
28
- var _recorderApp = require("./recorder/recorderApp");
29
- var storageScript = _interopRequireWildcard(require("./storageScript"));
30
- var consoleApiSource = _interopRequireWildcard(require("../generated/consoleApiSource"));
31
- var _tracing = require("./trace/recorder/tracing");
32
- function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
33
- function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
34
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
35
- /**
36
- * Copyright 2017 Google Inc. All rights reserved.
37
- * Modifications copyright (c) Microsoft Corporation.
38
- *
39
- * Licensed under the Apache License, Version 2.0 (the "License");
40
- * you may not use this file except in compliance with the License.
41
- * You may obtain a copy of the License at
42
- *
43
- * http://www.apache.org/licenses/LICENSE-2.0
44
- *
45
- * Unless required by applicable law or agreed to in writing, software
46
- * distributed under the License is distributed on an "AS IS" BASIS,
47
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
48
- * See the License for the specific language governing permissions and
49
- * limitations under the License.
50
- */
51
-
52
- class BrowserContext extends _instrumentation.SdkObject {
38
+ module.exports = __toCommonJS(browserContext_exports);
39
+ var import_fs = __toESM(require("fs"));
40
+ var import_path = __toESM(require("path"));
41
+ var import_timeoutSettings = require("./timeoutSettings");
42
+ var import_crypto = require("./utils/crypto");
43
+ var import_debug = require("./utils/debug");
44
+ var import_clock = require("./clock");
45
+ var import_debugger = require("./debugger");
46
+ var import_fetch = require("./fetch");
47
+ var import_fileUtils = require("./utils/fileUtils");
48
+ var import_harRecorder = require("./har/harRecorder");
49
+ var import_helper = require("./helper");
50
+ var import_instrumentation = require("./instrumentation");
51
+ var import_builtins = require("../utils/isomorphic/builtins");
52
+ var utilityScriptSerializers = __toESM(require("../utils/isomorphic/utilityScriptSerializers"));
53
+ var network = __toESM(require("./network"));
54
+ var import_page = require("./page");
55
+ var import_page2 = require("./page");
56
+ var import_recorder = require("./recorder");
57
+ var import_recorderApp = require("./recorder/recorderApp");
58
+ var storageScript = __toESM(require("./storageScript"));
59
+ var consoleApiSource = __toESM(require("../generated/consoleApiSource"));
60
+ var import_tracing = require("./trace/recorder/tracing");
61
+ class BrowserContext extends import_instrumentation.SdkObject {
53
62
  constructor(browser, options, browserContextId) {
54
- super(browser, 'browser-context');
55
- this._timeoutSettings = new _timeoutSettings.TimeoutSettings();
56
- this._pageBindings = new Map();
57
- this._activeProgressControllers = new Set();
58
- this._options = void 0;
59
- this._requestInterceptor = void 0;
60
- this._isPersistentContext = void 0;
61
- this._closedStatus = 'open';
62
- this._closePromise = void 0;
63
- this._closePromiseFulfill = void 0;
64
- this._permissions = new Map();
65
- this._downloads = new Set();
66
- this._browser = void 0;
67
- this._browserContextId = void 0;
68
- this._selectors = void 0;
69
- this._origins = new Set();
70
- this._harRecorders = new Map();
71
- this.tracing = void 0;
72
- this.fetchRequest = void 0;
73
- this._customCloseHandler = void 0;
63
+ super(browser, "browser-context");
64
+ this._timeoutSettings = new import_timeoutSettings.TimeoutSettings();
65
+ this._pageBindings = /* @__PURE__ */ new Map();
66
+ this._activeProgressControllers = /* @__PURE__ */ new Set();
67
+ this._closedStatus = "open";
68
+ this._permissions = /* @__PURE__ */ new Map();
69
+ this._downloads = /* @__PURE__ */ new Set();
70
+ this._origins = /* @__PURE__ */ new Set();
71
+ this._harRecorders = /* @__PURE__ */ new Map();
74
72
  this._tempDirs = [];
75
73
  this._settingStorageState = false;
76
74
  this.initScripts = [];
77
- this._routesInFlight = new Set();
78
- this._debugger = void 0;
79
- this._closeReason = void 0;
80
- this.clock = void 0;
81
- this._clientCertificatesProxy = void 0;
75
+ this._routesInFlight = /* @__PURE__ */ new Set();
82
76
  this.attribution.context = this;
83
77
  this._browser = browser;
84
78
  this._options = options;
85
79
  this._browserContextId = browserContextId;
86
80
  this._isPersistentContext = !browserContextId;
87
- this._closePromise = new Promise(fulfill => this._closePromiseFulfill = fulfill);
88
- this.fetchRequest = new _fetch.BrowserContextAPIRequestContext(this);
89
- if (this._options.recordHar) this._harRecorders.set('', new _harRecorder.HarRecorder(this, null, this._options.recordHar));
90
- this.tracing = new _tracing.Tracing(this, browser.options.tracesDir);
91
- this.clock = new _clock.Clock(this);
81
+ this._closePromise = new Promise((fulfill) => this._closePromiseFulfill = fulfill);
82
+ this.fetchRequest = new import_fetch.BrowserContextAPIRequestContext(this);
83
+ if (this._options.recordHar)
84
+ this._harRecorders.set("", new import_harRecorder.HarRecorder(this, null, this._options.recordHar));
85
+ this.tracing = new import_tracing.Tracing(this, browser.options.tracesDir);
86
+ this.clock = new import_clock.Clock(this);
87
+ }
88
+ static {
89
+ this.Events = {
90
+ Console: "console",
91
+ Close: "close",
92
+ Dialog: "dialog",
93
+ Page: "page",
94
+ // Can't use just 'error' due to node.js special treatment of error events.
95
+ // @see https://nodejs.org/api/events.html#events_error_events
96
+ PageError: "pageerror",
97
+ Request: "request",
98
+ Response: "response",
99
+ RequestFailed: "requestfailed",
100
+ RequestFinished: "requestfinished",
101
+ RequestAborted: "requestaborted",
102
+ RequestFulfilled: "requestfulfilled",
103
+ RequestContinued: "requestcontinued",
104
+ BeforeClose: "beforeclose",
105
+ VideoStarted: "videostarted"
106
+ };
92
107
  }
93
108
  isPersistentContext() {
94
109
  return this._isPersistentContext;
@@ -100,133 +115,128 @@ class BrowserContext extends _instrumentation.SdkObject {
100
115
  return this._selectors || this.attribution.playwright.selectors;
101
116
  }
102
117
  async _initialize() {
103
- if (this.attribution.playwright.options.isInternalPlaywright) return;
104
- // Debugger will pause execution upon page.pause in headed mode.
105
- this._debugger = new _debugger.Debugger(this);
106
-
107
- // When PWDEBUG=1, show inspector for each context.
108
- if ((0, _debug.debugMode)() === 'inspector') await _recorder.Recorder.show(this, _recorderApp.RecorderApp.factory(this), {
109
- pauseOnNextStatement: true
110
- });
111
-
112
- // When paused, show inspector.
113
- if (this._debugger.isPaused()) _recorder.Recorder.showInspectorNoReply(this, _recorderApp.RecorderApp.factory(this));
114
- this._debugger.on(_debugger.Debugger.Events.PausedStateChanged, () => {
115
- if (this._debugger.isPaused()) _recorder.Recorder.showInspectorNoReply(this, _recorderApp.RecorderApp.factory(this));
118
+ if (this.attribution.playwright.options.isInternalPlaywright)
119
+ return;
120
+ this._debugger = new import_debugger.Debugger(this);
121
+ if ((0, import_debug.debugMode)() === "inspector")
122
+ await import_recorder.Recorder.show(this, import_recorderApp.RecorderApp.factory(this), { pauseOnNextStatement: true });
123
+ if (this._debugger.isPaused())
124
+ import_recorder.Recorder.showInspectorNoReply(this, import_recorderApp.RecorderApp.factory(this));
125
+ this._debugger.on(import_debugger.Debugger.Events.PausedStateChanged, () => {
126
+ if (this._debugger.isPaused())
127
+ import_recorder.Recorder.showInspectorNoReply(this, import_recorderApp.RecorderApp.factory(this));
116
128
  });
117
- if ((0, _debug.debugMode)() === 'console') await this.extendInjectedScript(consoleApiSource.source);
118
- if (this._options.serviceWorkers === 'block') await this.addInitScript(`navigator.serviceWorker.register = async () => { };`);
119
- if (this._options.permissions) await this.grantPermissions(this._options.permissions);
129
+ if ((0, import_debug.debugMode)() === "console")
130
+ await this.extendInjectedScript(consoleApiSource.source);
131
+ if (this._options.serviceWorkers === "block")
132
+ await this.addInitScript(`navigator.serviceWorker.register = async () => { };`);
133
+ if (this._options.permissions)
134
+ await this.grantPermissions(this._options.permissions);
120
135
  }
121
136
  debugger() {
122
137
  return this._debugger;
123
138
  }
124
139
  async _ensureVideosPath() {
125
- if (this._options.recordVideo) await (0, _fileUtils.mkdirIfNeeded)(_path.default.join(this._options.recordVideo.dir, 'dummy'));
140
+ if (this._options.recordVideo)
141
+ await (0, import_fileUtils.mkdirIfNeeded)(import_path.default.join(this._options.recordVideo.dir, "dummy"));
126
142
  }
127
143
  canResetForReuse() {
128
- if (this._closedStatus !== 'open') return false;
144
+ if (this._closedStatus !== "open")
145
+ return false;
129
146
  return true;
130
147
  }
131
148
  async stopPendingOperations(reason) {
132
- // When using context reuse, stop pending operations to gracefully terminate all the actions
133
- // with a user-friendly error message containing operation log.
134
- for (const controller of this._activeProgressControllers) controller.abort(new Error(reason));
135
- // Let rejections in microtask generate events before returning.
136
- await new Promise(f => setTimeout(f, 0));
149
+ for (const controller of this._activeProgressControllers)
150
+ controller.abort(new Error(reason));
151
+ await new Promise((f) => setTimeout(f, 0));
137
152
  }
138
153
  static reusableContextHash(params) {
139
- const paramsCopy = {
140
- ...params
141
- };
154
+ const paramsCopy = { ...params };
142
155
  for (const k of Object.keys(paramsCopy)) {
143
156
  const key = k;
144
- if (paramsCopy[key] === defaultNewContextParamValues[key]) delete paramsCopy[key];
157
+ if (paramsCopy[key] === defaultNewContextParamValues[key])
158
+ delete paramsCopy[key];
145
159
  }
146
- for (const key of paramsThatAllowContextReuse) delete paramsCopy[key];
160
+ for (const key of paramsThatAllowContextReuse)
161
+ delete paramsCopy[key];
147
162
  return JSON.stringify(paramsCopy);
148
163
  }
149
164
  async resetForReuse(metadata, params) {
150
- var _page, _page2, _page3, _page4, _page5;
151
- this.setDefaultNavigationTimeout(undefined);
152
- this.setDefaultTimeout(undefined);
165
+ this.setDefaultNavigationTimeout(void 0);
166
+ this.setDefaultTimeout(void 0);
153
167
  this.tracing.resetForReuse();
154
168
  if (params) {
155
- for (const key of paramsThatAllowContextReuse) this._options[key] = params[key];
169
+ for (const key of paramsThatAllowContextReuse)
170
+ this._options[key] = params[key];
156
171
  }
157
172
  await this._cancelAllRoutesInFlight();
158
-
159
- // Close extra pages early.
160
173
  let page = this.pages()[0];
161
174
  const [, ...otherPages] = this.pages();
162
- for (const p of otherPages) await p.close(metadata);
175
+ for (const p of otherPages)
176
+ await p.close(metadata);
163
177
  if (page && page.hasCrashed()) {
164
178
  await page.close(metadata);
165
- page = undefined;
179
+ page = void 0;
166
180
  }
167
-
168
- // Unless dialogs are dismissed, setting extra http headers below does not respond.
169
- (_page = page) === null || _page === void 0 || _page._frameManager.setCloseAllOpeningDialogs(true);
170
- await ((_page2 = page) === null || _page2 === void 0 ? void 0 : _page2._frameManager.closeOpenDialogs());
171
- // Navigate to about:blank first to ensure no page scripts are running after this point.
172
- await ((_page3 = page) === null || _page3 === void 0 ? void 0 : _page3.mainFrame().goto(metadata, 'about:blank', {
173
- timeout: 0
174
- }));
175
- (_page4 = page) === null || _page4 === void 0 || _page4._frameManager.setCloseAllOpeningDialogs(false);
181
+ page?._frameManager.setCloseAllOpeningDialogs(true);
182
+ await page?._frameManager.closeOpenDialogs();
183
+ await page?.mainFrame().goto(metadata, "about:blank", { timeout: 0 });
184
+ page?._frameManager.setCloseAllOpeningDialogs(false);
176
185
  await this._resetStorage();
177
186
  await this._removeExposedBindings();
178
187
  await this._removeInitScripts();
179
188
  this.clock.markAsUninstalled();
180
- // TODO: following can be optimized to not perform noops.
181
- if (this._options.permissions) await this.grantPermissions(this._options.permissions);else await this.clearPermissions();
189
+ if (this._options.permissions)
190
+ await this.grantPermissions(this._options.permissions);
191
+ else
192
+ await this.clearPermissions();
182
193
  await this.setExtraHTTPHeaders(this._options.extraHTTPHeaders || []);
183
194
  await this.setGeolocation(this._options.geolocation);
184
195
  await this.setOffline(!!this._options.offline);
185
196
  await this.setUserAgent(this._options.userAgent);
186
197
  await this.clearCache();
187
198
  await this._resetCookies();
188
- await ((_page5 = page) === null || _page5 === void 0 ? void 0 : _page5.resetForReuse(metadata));
199
+ await page?.resetForReuse(metadata);
189
200
  }
190
201
  _browserClosed() {
191
- for (const page of this.pages()) page._didClose();
202
+ for (const page of this.pages())
203
+ page._didClose();
192
204
  this._didCloseInternal();
193
205
  }
194
206
  _didCloseInternal() {
195
- var _this$_clientCertific;
196
- if (this._closedStatus === 'closed') {
197
- // We can come here twice if we close browser context and browser
198
- // at the same time.
207
+ if (this._closedStatus === "closed") {
199
208
  return;
200
209
  }
201
- (_this$_clientCertific = this._clientCertificatesProxy) === null || _this$_clientCertific === void 0 || _this$_clientCertific.close().catch(() => {});
210
+ this._clientCertificatesProxy?.close().catch(() => {
211
+ });
202
212
  this.tracing.abort();
203
- if (this._isPersistentContext) this.onClosePersistent();
204
- this._closePromiseFulfill(new Error('Context closed'));
213
+ if (this._isPersistentContext)
214
+ this.onClosePersistent();
215
+ this._closePromiseFulfill(new Error("Context closed"));
205
216
  this.emit(BrowserContext.Events.Close);
206
217
  }
207
218
  pages() {
208
- return this.possiblyUninitializedPages().filter(page => page.initializedOrUndefined());
219
+ return this.possiblyUninitializedPages().filter((page) => page.initializedOrUndefined());
209
220
  }
210
-
211
- // BrowserContext methods.
212
-
213
221
  async cookies(urls = []) {
214
- if (urls && !Array.isArray(urls)) urls = [urls];
222
+ if (urls && !Array.isArray(urls))
223
+ urls = [urls];
215
224
  return await this.doGetCookies(urls);
216
225
  }
217
226
  async clearCookies(options) {
218
227
  const currentCookies = await this.cookies();
219
228
  await this.doClearCookies();
220
229
  const matches = (cookie, prop, value) => {
221
- if (!value) return true;
230
+ if (!value)
231
+ return true;
222
232
  if (value instanceof RegExp) {
223
233
  value.lastIndex = 0;
224
234
  return value.test(cookie[prop]);
225
235
  }
226
236
  return cookie[prop] === value;
227
237
  };
228
- const cookiesToReadd = currentCookies.filter(cookie => {
229
- return !matches(cookie, 'name', options.name) || !matches(cookie, 'domain', options.domain) || !matches(cookie, 'path', options.path);
238
+ const cookiesToReadd = currentCookies.filter((cookie) => {
239
+ return !matches(cookie, "name", options.name) || !matches(cookie, "domain", options.domain) || !matches(cookie, "path", options.path);
230
240
  });
231
241
  await this.addCookies(cookiesToReadd);
232
242
  }
@@ -237,28 +247,31 @@ class BrowserContext extends _instrumentation.SdkObject {
237
247
  return this._pageBindings.has(name);
238
248
  }
239
249
  async exposeBinding(name, needsHandle, playwrightBinding) {
240
- if (this._pageBindings.has(name)) throw new Error(`Function "${name}" has been already registered`);
250
+ if (this._pageBindings.has(name))
251
+ throw new Error(`Function "${name}" has been already registered`);
241
252
  for (const page of this.pages()) {
242
- if (page.getBinding(name)) throw new Error(`Function "${name}" has been already registered in one of the pages`);
253
+ if (page.getBinding(name))
254
+ throw new Error(`Function "${name}" has been already registered in one of the pages`);
243
255
  }
244
- const binding = new _page6.PageBinding(name, playwrightBinding, needsHandle);
256
+ const binding = new import_page2.PageBinding(name, playwrightBinding, needsHandle);
245
257
  this._pageBindings.set(name, binding);
246
258
  await this.doExposeBinding(binding);
247
259
  }
248
260
  async _removeExposedBindings() {
249
261
  for (const key of this._pageBindings.keys()) {
250
- if (!key.startsWith('__pw')) this._pageBindings.delete(key);
262
+ if (!key.startsWith("__pw"))
263
+ this._pageBindings.delete(key);
251
264
  }
252
265
  await this.doRemoveExposedBindings();
253
266
  }
254
267
  async grantPermissions(permissions, origin) {
255
- let resolvedOrigin = '*';
268
+ let resolvedOrigin = "*";
256
269
  if (origin) {
257
270
  const url = new URL(origin);
258
271
  resolvedOrigin = url.origin;
259
272
  }
260
273
  const existing = new Set(this._permissions.get(resolvedOrigin) || []);
261
- permissions.forEach(p => existing.add(p));
274
+ permissions.forEach((p) => existing.add(p));
262
275
  const list = [...existing.values()];
263
276
  this._permissions.set(resolvedOrigin, list);
264
277
  await this.doGrantPermissions(resolvedOrigin, list);
@@ -275,62 +288,51 @@ class BrowserContext extends _instrumentation.SdkObject {
275
288
  }
276
289
  async _loadDefaultContextAsIs(progress) {
277
290
  if (!this.possiblyUninitializedPages().length) {
278
- const waitForEvent = _helper.helper.waitForEvent(progress, this, BrowserContext.Events.Page);
291
+ const waitForEvent = import_helper.helper.waitForEvent(progress, this, BrowserContext.Events.Page);
279
292
  progress.cleanupWhenAborted(() => waitForEvent.dispose);
280
- // Race against BrowserContext.close
281
293
  await Promise.race([waitForEvent.promise, this._closePromise]);
282
294
  }
283
295
  const page = this.possiblyUninitializedPages()[0];
284
- if (!page) return;
296
+ if (!page)
297
+ return;
285
298
  const pageOrError = await page.waitForInitializedOrError();
286
- if (pageOrError instanceof Error) throw pageOrError;
287
- await page.mainFrame()._waitForLoadState(progress, 'load');
299
+ if (pageOrError instanceof Error)
300
+ throw pageOrError;
301
+ await page.mainFrame()._waitForLoadState(progress, "load");
288
302
  return page;
289
303
  }
290
304
  async _loadDefaultContext(progress) {
291
305
  const defaultPage = await this._loadDefaultContextAsIs(progress);
292
- if (!defaultPage) return;
306
+ if (!defaultPage)
307
+ return;
293
308
  const browserName = this._browser.options.name;
294
- if (this._options.isMobile && browserName === 'chromium' || this._options.locale && browserName === 'webkit') {
295
- // Workaround for:
296
- // - chromium fails to change isMobile for existing page;
297
- // - webkit fails to change locale for existing page.
309
+ if (this._options.isMobile && browserName === "chromium" || this._options.locale && browserName === "webkit") {
298
310
  await this.newPage(progress.metadata);
299
311
  await defaultPage.close(progress.metadata);
300
312
  }
301
313
  }
302
314
  _authenticateProxyViaHeader() {
303
- const proxy = this._options.proxy || this._browser.options.proxy || {
304
- username: undefined,
305
- password: undefined
306
- };
307
- const {
308
- username,
309
- password
310
- } = proxy;
315
+ const proxy = this._options.proxy || this._browser.options.proxy || { username: void 0, password: void 0 };
316
+ const { username, password } = proxy;
311
317
  if (username) {
312
- this._options.httpCredentials = {
313
- username,
314
- password: password
315
- };
316
- const token = Buffer.from(`${username}:${password}`).toString('base64');
317
- this._options.extraHTTPHeaders = network.mergeHeaders([this._options.extraHTTPHeaders, network.singleHeader('Proxy-Authorization', `Basic ${token}`)]);
318
+ this._options.httpCredentials = { username, password };
319
+ const token = Buffer.from(`${username}:${password}`).toString("base64");
320
+ this._options.extraHTTPHeaders = network.mergeHeaders([
321
+ this._options.extraHTTPHeaders,
322
+ network.singleHeader("Proxy-Authorization", `Basic ${token}`)
323
+ ]);
318
324
  }
319
325
  }
320
326
  _authenticateProxyViaCredentials() {
321
327
  const proxy = this._options.proxy || this._browser.options.proxy;
322
- if (!proxy) return;
323
- const {
324
- username,
325
- password
326
- } = proxy;
327
- if (username) this._options.httpCredentials = {
328
- username,
329
- password: password || ''
330
- };
328
+ if (!proxy)
329
+ return;
330
+ const { username, password } = proxy;
331
+ if (username)
332
+ this._options.httpCredentials = { username, password: password || "" };
331
333
  }
332
334
  async addInitScript(source, name) {
333
- const initScript = new _page6.InitScript(source, false /* internal */, name);
335
+ const initScript = new import_page.InitScript(source, false, name);
334
336
  this.initScripts.push(initScript);
335
337
  await this.doAddInitScript(initScript);
336
338
  }
@@ -343,58 +345,53 @@ class BrowserContext extends _instrumentation.SdkObject {
343
345
  await this.doUpdateRequestInterception();
344
346
  }
345
347
  isClosingOrClosed() {
346
- return this._closedStatus !== 'open';
348
+ return this._closedStatus !== "open";
347
349
  }
348
350
  async _deleteAllDownloads() {
349
- await Promise.all(Array.from(this._downloads).map(download => download.artifact.deleteOnContextClose()));
351
+ await Promise.all(Array.from(this._downloads).map((download) => download.artifact.deleteOnContextClose()));
350
352
  }
351
353
  async _deleteAllTempDirs() {
352
- await Promise.all(this._tempDirs.map(async dir => await _fs.default.promises.unlink(dir).catch(e => {})));
354
+ await Promise.all(this._tempDirs.map(async (dir) => await import_fs.default.promises.unlink(dir).catch((e) => {
355
+ })));
353
356
  }
354
357
  setCustomCloseHandler(handler) {
355
358
  this._customCloseHandler = handler;
356
359
  }
357
360
  async close(options) {
358
- if (this._closedStatus === 'open') {
359
- if (options.reason) this._closeReason = options.reason;
361
+ if (this._closedStatus === "open") {
362
+ if (options.reason)
363
+ this._closeReason = options.reason;
360
364
  this.emit(BrowserContext.Events.BeforeClose);
361
- this._closedStatus = 'closing';
362
- for (const harRecorder of this._harRecorders.values()) await harRecorder.flush();
365
+ this._closedStatus = "closing";
366
+ for (const harRecorder of this._harRecorders.values())
367
+ await harRecorder.flush();
363
368
  await this.tracing.flush();
364
-
365
- // Cleanup.
366
369
  const promises = [];
367
- for (const {
368
- context,
369
- artifact
370
- } of this._browser._idToVideo.values()) {
371
- // Wait for the videos to finish.
372
- if (context === this) promises.push(artifact.finishedPromise());
370
+ for (const { context, artifact } of this._browser._idToVideo.values()) {
371
+ if (context === this)
372
+ promises.push(artifact.finishedPromise());
373
373
  }
374
374
  if (this._customCloseHandler) {
375
375
  await this._customCloseHandler();
376
376
  } else {
377
- // Close the context.
378
377
  await this.doClose(options.reason);
379
378
  }
380
-
381
- // We delete downloads after context closure
382
- // so that browser does not write to the download file anymore.
383
379
  promises.push(this._deleteAllDownloads());
384
380
  promises.push(this._deleteAllTempDirs());
385
381
  await Promise.all(promises);
386
-
387
- // Custom handler should trigger didCloseInternal itself.
388
- if (!this._customCloseHandler) this._didCloseInternal();
382
+ if (!this._customCloseHandler)
383
+ this._didCloseInternal();
389
384
  }
390
385
  await this._closePromise;
391
386
  }
392
387
  async newPage(metadata) {
393
388
  const page = await this.doCreateNewPage();
394
- if (metadata.isServerSide) page.markAsServerSideOnly();
389
+ if (metadata.isServerSide)
390
+ page.markAsServerSideOnly();
395
391
  const pageOrError = await page.waitForInitializedOrError();
396
- if (pageOrError instanceof _page6.Page) {
397
- if (pageOrError.isClosed()) throw new Error('Page has been closed.');
392
+ if (pageOrError instanceof import_page2.Page) {
393
+ if (pageOrError.isClosed())
394
+ throw new Error("Page has been closed.");
398
395
  return pageOrError;
399
396
  }
400
397
  throw pageOrError;
@@ -408,85 +405,68 @@ class BrowserContext extends _instrumentation.SdkObject {
408
405
  origins: []
409
406
  };
410
407
  const originsToSave = new Set(this._origins);
411
- const collectScript = `(${storageScript.collect})((${utilityScriptSerializers.source})(), ${this._browser.options.name === 'firefox'}, ${indexedDB})`;
412
-
413
- // First try collecting storage stage from existing pages.
408
+ const collectScript = `(${storageScript.collect})(${utilityScriptSerializers.source}, (${import_builtins.builtins})(), ${this._browser.options.name === "firefox"}, ${indexedDB})`;
414
409
  for (const page of this.pages()) {
415
410
  const origin = page.mainFrame().origin();
416
- if (!origin || !originsToSave.has(origin)) continue;
411
+ if (!origin || !originsToSave.has(origin))
412
+ continue;
417
413
  try {
418
- var _storage$indexedDB;
419
- const storage = await page.mainFrame().nonStallingEvaluateInExistingContext(collectScript, 'utility');
420
- if (storage.localStorage.length || (_storage$indexedDB = storage.indexedDB) !== null && _storage$indexedDB !== void 0 && _storage$indexedDB.length) result.origins.push({
421
- origin,
422
- localStorage: storage.localStorage,
423
- indexedDB: storage.indexedDB
424
- });
414
+ const storage = await page.mainFrame().nonStallingEvaluateInExistingContext(collectScript, "utility");
415
+ if (storage.localStorage.length || storage.indexedDB?.length)
416
+ result.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB });
425
417
  originsToSave.delete(origin);
426
418
  } catch {
427
- // When failed on the live page, we'll retry on the blank page below.
428
419
  }
429
420
  }
430
-
431
- // If there are still origins to save, create a blank page to iterate over origins.
432
421
  if (originsToSave.size) {
433
- const internalMetadata = (0, _instrumentation.serverSideCallMetadata)();
422
+ const internalMetadata = (0, import_instrumentation.serverSideCallMetadata)();
434
423
  const page = await this.newPage(internalMetadata);
435
- await page._setServerRequestInterceptor(handler => {
436
- handler.fulfill({
437
- body: '<html></html>'
438
- }).catch(() => {});
424
+ await page._setServerRequestInterceptor((handler) => {
425
+ handler.fulfill({ body: "<html></html>" }).catch(() => {
426
+ });
439
427
  return true;
440
428
  });
441
429
  for (const origin of originsToSave) {
442
- var _storage$indexedDB2;
443
430
  const frame = page.mainFrame();
444
431
  await frame.goto(internalMetadata, origin);
445
- const storage = await frame.evaluateExpression(collectScript, {
446
- world: 'utility'
447
- });
448
- if (storage.localStorage.length || (_storage$indexedDB2 = storage.indexedDB) !== null && _storage$indexedDB2 !== void 0 && _storage$indexedDB2.length) result.origins.push({
449
- origin,
450
- localStorage: storage.localStorage,
451
- indexedDB: storage.indexedDB
452
- });
432
+ const storage = await frame.evaluateExpression(collectScript, { world: "utility" });
433
+ if (storage.localStorage.length || storage.indexedDB?.length)
434
+ result.origins.push({ origin, localStorage: storage.localStorage, indexedDB: storage.indexedDB });
453
435
  }
454
436
  await page.close(internalMetadata);
455
437
  }
456
438
  return result;
457
439
  }
458
440
  async _resetStorage() {
459
- var _this$_options$storag;
460
441
  const oldOrigins = this._origins;
461
- const newOrigins = new Map(((_this$_options$storag = this._options.storageState) === null || _this$_options$storag === void 0 || (_this$_options$storag = _this$_options$storag.origins) === null || _this$_options$storag === void 0 ? void 0 : _this$_options$storag.map(p => [p.origin, p])) || []);
462
- if (!oldOrigins.size && !newOrigins.size) return;
442
+ const newOrigins = new Map(this._options.storageState?.origins?.map((p) => [p.origin, p]) || []);
443
+ if (!oldOrigins.size && !newOrigins.size)
444
+ return;
463
445
  let page = this.pages()[0];
464
- const internalMetadata = (0, _instrumentation.serverSideCallMetadata)();
465
- page = page || (await this.newPage({
446
+ const internalMetadata = (0, import_instrumentation.serverSideCallMetadata)();
447
+ page = page || await this.newPage({
466
448
  ...internalMetadata,
467
449
  // Do not mark this page as internal, because we will leave it for later reuse
468
450
  // as a user-visible page.
469
451
  isServerSide: false
470
- }));
471
- await page._setServerRequestInterceptor(handler => {
472
- handler.fulfill({
473
- body: '<html></html>'
474
- }).catch(() => {});
452
+ });
453
+ await page._setServerRequestInterceptor((handler) => {
454
+ handler.fulfill({ body: "<html></html>" }).catch(() => {
455
+ });
475
456
  return true;
476
457
  });
477
- for (const origin of new Set([...oldOrigins, ...newOrigins.keys()])) {
458
+ for (const origin of /* @__PURE__ */ new Set([...oldOrigins, ...newOrigins.keys()])) {
478
459
  const frame = page.mainFrame();
479
460
  await frame.goto(internalMetadata, origin);
480
461
  await frame.resetStorageForCurrentOriginBestEffort(newOrigins.get(origin));
481
462
  }
482
- await page._setServerRequestInterceptor(undefined);
483
- this._origins = new Set([...newOrigins.keys()]);
484
- // It is safe to not restore the URL to about:blank since we are doing it in Page::resetForReuse.
463
+ await page._setServerRequestInterceptor(void 0);
464
+ this._origins = /* @__PURE__ */ new Set([...newOrigins.keys()]);
485
465
  }
486
466
  async _resetCookies() {
487
- var _this$_options$storag2, _this$_options$storag3;
488
467
  await this.doClearCookies();
489
- if ((_this$_options$storag2 = this._options.storageState) !== null && _this$_options$storag2 !== void 0 && _this$_options$storag2.cookies) await this.addCookies((_this$_options$storag3 = this._options.storageState) === null || _this$_options$storag3 === void 0 ? void 0 : _this$_options$storag3.cookies);
468
+ if (this._options.storageState?.cookies)
469
+ await this.addCookies(this._options.storageState?.cookies);
490
470
  }
491
471
  isSettingStorageState() {
492
472
  return this._settingStorageState;
@@ -494,22 +474,20 @@ class BrowserContext extends _instrumentation.SdkObject {
494
474
  async setStorageState(metadata, state) {
495
475
  this._settingStorageState = true;
496
476
  try {
497
- if (state.cookies) await this.addCookies(state.cookies);
477
+ if (state.cookies)
478
+ await this.addCookies(state.cookies);
498
479
  if (state.origins && state.origins.length) {
499
- const internalMetadata = (0, _instrumentation.serverSideCallMetadata)();
480
+ const internalMetadata = (0, import_instrumentation.serverSideCallMetadata)();
500
481
  const page = await this.newPage(internalMetadata);
501
- await page._setServerRequestInterceptor(handler => {
502
- handler.fulfill({
503
- body: '<html></html>'
504
- }).catch(() => {});
482
+ await page._setServerRequestInterceptor((handler) => {
483
+ handler.fulfill({ body: "<html></html>" }).catch(() => {
484
+ });
505
485
  return true;
506
486
  });
507
487
  for (const originState of state.origins) {
508
488
  const frame = page.mainFrame();
509
489
  await frame.goto(metadata, originState.origin);
510
- await frame.evaluateExpression(`(${storageScript.restore})(${JSON.stringify(originState)}, (${utilityScriptSerializers.source})())`, {
511
- world: 'utility'
512
- });
490
+ await frame.evaluateExpression(`(${storageScript.restore})(${utilityScriptSerializers.source}, (${import_builtins.builtins})(), ${JSON.stringify(originState)})`, { world: "utility" });
513
491
  }
514
492
  await page.close(internalMetadata);
515
493
  }
@@ -518,24 +496,25 @@ class BrowserContext extends _instrumentation.SdkObject {
518
496
  }
519
497
  }
520
498
  async extendInjectedScript(source, arg) {
521
- const installInFrame = frame => frame.extendInjectedScript(source, arg).catch(() => {});
522
- const installInPage = page => {
523
- page.on(_page6.Page.Events.InternalFrameNavigatedToNewDocument, installInFrame);
499
+ const installInFrame = (frame) => frame.extendInjectedScript(source, arg).catch(() => {
500
+ });
501
+ const installInPage = (page) => {
502
+ page.on(import_page2.Page.Events.InternalFrameNavigatedToNewDocument, installInFrame);
524
503
  return Promise.all(page.frames().map(installInFrame));
525
504
  };
526
505
  this.on(BrowserContext.Events.Page, installInPage);
527
506
  return Promise.all(this.pages().map(installInPage));
528
507
  }
529
508
  async safeNonStallingEvaluateInAllFrames(expression, world, options = {}) {
530
- await Promise.all(this.pages().map(page => page.safeNonStallingEvaluateInAllFrames(expression, world, options)));
509
+ await Promise.all(this.pages().map((page) => page.safeNonStallingEvaluateInAllFrames(expression, world, options)));
531
510
  }
532
511
  async _harStart(page, options) {
533
- const harId = (0, _crypto.createGuid)();
534
- this._harRecorders.set(harId, new _harRecorder.HarRecorder(this, page, options));
512
+ const harId = (0, import_crypto.createGuid)();
513
+ this._harRecorders.set(harId, new import_harRecorder.HarRecorder(this, page, options));
535
514
  return harId;
536
515
  }
537
516
  async _harExport(harId) {
538
- const recorder = this._harRecorders.get(harId || '');
517
+ const recorder = this._harRecorders.get(harId || "");
539
518
  return recorder.export();
540
519
  }
541
520
  addRouteInFlight(route) {
@@ -545,53 +524,32 @@ class BrowserContext extends _instrumentation.SdkObject {
545
524
  this._routesInFlight.delete(route);
546
525
  }
547
526
  async _cancelAllRoutesInFlight() {
548
- await Promise.all([...this._routesInFlight].map(r => r.abort())).catch(() => {});
527
+ await Promise.all([...this._routesInFlight].map((r) => r.abort())).catch(() => {
528
+ });
549
529
  this._routesInFlight.clear();
550
530
  }
551
531
  }
552
- exports.BrowserContext = BrowserContext;
553
- BrowserContext.Events = {
554
- Console: 'console',
555
- Close: 'close',
556
- Dialog: 'dialog',
557
- Page: 'page',
558
- // Can't use just 'error' due to node.js special treatment of error events.
559
- // @see https://nodejs.org/api/events.html#events_error_events
560
- PageError: 'pageerror',
561
- Request: 'request',
562
- Response: 'response',
563
- RequestFailed: 'requestfailed',
564
- RequestFinished: 'requestfinished',
565
- RequestAborted: 'requestaborted',
566
- RequestFulfilled: 'requestfulfilled',
567
- RequestContinued: 'requestcontinued',
568
- BeforeClose: 'beforeclose',
569
- VideoStarted: 'videostarted'
570
- };
571
532
  function assertBrowserContextIsNotOwned(context) {
572
533
  for (const page of context.pages()) {
573
- if (page._ownedContext) throw new Error('Please use browser.newContext() for multi-page scripts that share the context.');
534
+ if (page._ownedContext)
535
+ throw new Error("Please use browser.newContext() for multi-page scripts that share the context.");
574
536
  }
575
537
  }
576
538
  function validateBrowserContextOptions(options, browserOptions) {
577
- if (options.noDefaultViewport && options.deviceScaleFactor !== undefined) throw new Error(`"deviceScaleFactor" option is not supported with null "viewport"`);
578
- if (options.noDefaultViewport && !!options.isMobile) throw new Error(`"isMobile" option is not supported with null "viewport"`);
579
- if (options.acceptDownloads === undefined && browserOptions.name !== 'electron') options.acceptDownloads = 'accept';
580
- // Electron requires explicit acceptDownloads: true since we wait for
581
- // https://github.com/electron/electron/pull/41718 to be widely shipped.
582
- // In 6-12 months, we can remove this check.
583
- else if (options.acceptDownloads === undefined && browserOptions.name === 'electron') options.acceptDownloads = 'internal-browser-default';
584
- if (!options.viewport && !options.noDefaultViewport) options.viewport = {
585
- width: 1280,
586
- height: 720
587
- };
539
+ if (options.noDefaultViewport && options.deviceScaleFactor !== void 0)
540
+ throw new Error(`"deviceScaleFactor" option is not supported with null "viewport"`);
541
+ if (options.noDefaultViewport && !!options.isMobile)
542
+ throw new Error(`"isMobile" option is not supported with null "viewport"`);
543
+ if (options.acceptDownloads === void 0 && browserOptions.name !== "electron")
544
+ options.acceptDownloads = "accept";
545
+ else if (options.acceptDownloads === void 0 && browserOptions.name === "electron")
546
+ options.acceptDownloads = "internal-browser-default";
547
+ if (!options.viewport && !options.noDefaultViewport)
548
+ options.viewport = { width: 1280, height: 720 };
588
549
  if (options.recordVideo) {
589
550
  if (!options.recordVideo.size) {
590
551
  if (options.noDefaultViewport) {
591
- options.recordVideo.size = {
592
- width: 800,
593
- height: 600
594
- };
552
+ options.recordVideo.size = { width: 800, height: 600 };
595
553
  } else {
596
554
  const size = options.viewport;
597
555
  const scale = Math.min(1, 800 / Math.max(size.width, size.height));
@@ -601,61 +559,69 @@ function validateBrowserContextOptions(options, browserOptions) {
601
559
  };
602
560
  }
603
561
  }
604
- // Make sure both dimensions are odd, this is required for vp8
605
562
  options.recordVideo.size.width &= ~1;
606
563
  options.recordVideo.size.height &= ~1;
607
564
  }
608
- if (options.proxy) options.proxy = normalizeProxySettings(options.proxy);
565
+ if (options.proxy)
566
+ options.proxy = normalizeProxySettings(options.proxy);
609
567
  verifyGeolocation(options.geolocation);
610
568
  }
611
569
  function verifyGeolocation(geolocation) {
612
- if (!geolocation) return;
570
+ if (!geolocation)
571
+ return;
613
572
  geolocation.accuracy = geolocation.accuracy || 0;
614
- const {
615
- longitude,
616
- latitude,
617
- accuracy
618
- } = geolocation;
619
- if (longitude < -180 || longitude > 180) throw new Error(`geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed.`);
620
- if (latitude < -90 || latitude > 90) throw new Error(`geolocation.latitude: precondition -90 <= LATITUDE <= 90 failed.`);
621
- if (accuracy < 0) throw new Error(`geolocation.accuracy: precondition 0 <= ACCURACY failed.`);
573
+ const { longitude, latitude, accuracy } = geolocation;
574
+ if (longitude < -180 || longitude > 180)
575
+ throw new Error(`geolocation.longitude: precondition -180 <= LONGITUDE <= 180 failed.`);
576
+ if (latitude < -90 || latitude > 90)
577
+ throw new Error(`geolocation.latitude: precondition -90 <= LATITUDE <= 90 failed.`);
578
+ if (accuracy < 0)
579
+ throw new Error(`geolocation.accuracy: precondition 0 <= ACCURACY failed.`);
622
580
  }
623
581
  function verifyClientCertificates(clientCertificates) {
624
- if (!clientCertificates) return;
582
+ if (!clientCertificates)
583
+ return;
625
584
  for (const cert of clientCertificates) {
626
- if (!cert.origin) throw new Error(`clientCertificates.origin is required`);
627
- if (!cert.cert && !cert.key && !cert.passphrase && !cert.pfx) throw new Error('None of cert, key, passphrase or pfx is specified');
628
- if (cert.cert && !cert.key) throw new Error('cert is specified without key');
629
- if (!cert.cert && cert.key) throw new Error('key is specified without cert');
630
- if (cert.pfx && (cert.cert || cert.key)) throw new Error('pfx is specified together with cert, key or passphrase');
585
+ if (!cert.origin)
586
+ throw new Error(`clientCertificates.origin is required`);
587
+ if (!cert.cert && !cert.key && !cert.passphrase && !cert.pfx)
588
+ throw new Error("None of cert, key, passphrase or pfx is specified");
589
+ if (cert.cert && !cert.key)
590
+ throw new Error("cert is specified without key");
591
+ if (!cert.cert && cert.key)
592
+ throw new Error("key is specified without cert");
593
+ if (cert.pfx && (cert.cert || cert.key))
594
+ throw new Error("pfx is specified together with cert, key or passphrase");
631
595
  }
632
596
  }
633
597
  function normalizeProxySettings(proxy) {
634
- let {
635
- server,
636
- bypass
637
- } = proxy;
598
+ let { server, bypass } = proxy;
638
599
  let url;
639
600
  try {
640
- // new URL('127.0.0.1:8080') throws
641
- // new URL('localhost:8080') fails to parse host or protocol
642
- // In both of these cases, we need to try re-parse URL with `http://` prefix.
643
601
  url = new URL(server);
644
- if (!url.host || !url.protocol) url = new URL('http://' + server);
602
+ if (!url.host || !url.protocol)
603
+ url = new URL("http://" + server);
645
604
  } catch (e) {
646
- url = new URL('http://' + server);
647
- }
648
- if (url.protocol === 'socks4:' && (proxy.username || proxy.password)) throw new Error(`Socks4 proxy protocol does not support authentication`);
649
- if (url.protocol === 'socks5:' && (proxy.username || proxy.password)) throw new Error(`Browser does not support socks5 proxy authentication`);
650
- server = url.protocol + '//' + url.host;
651
- if (bypass) bypass = bypass.split(',').map(t => t.trim()).join(',');
652
- return {
653
- ...proxy,
654
- server,
655
- bypass
656
- };
605
+ url = new URL("http://" + server);
606
+ }
607
+ if (url.protocol === "socks4:" && (proxy.username || proxy.password))
608
+ throw new Error(`Socks4 proxy protocol does not support authentication`);
609
+ if (url.protocol === "socks5:" && (proxy.username || proxy.password))
610
+ throw new Error(`Browser does not support socks5 proxy authentication`);
611
+ server = url.protocol + "//" + url.host;
612
+ if (bypass)
613
+ bypass = bypass.split(",").map((t) => t.trim()).join(",");
614
+ return { ...proxy, server, bypass };
657
615
  }
658
- const paramsThatAllowContextReuse = ['colorScheme', 'forcedColors', 'reducedMotion', 'contrast', 'screen', 'userAgent', 'viewport'];
616
+ const paramsThatAllowContextReuse = [
617
+ "colorScheme",
618
+ "forcedColors",
619
+ "reducedMotion",
620
+ "contrast",
621
+ "screen",
622
+ "userAgent",
623
+ "viewport"
624
+ ];
659
625
  const defaultNewContextParamValues = {
660
626
  noDefaultViewport: false,
661
627
  ignoreHTTPSErrors: false,
@@ -664,8 +630,17 @@ const defaultNewContextParamValues = {
664
630
  offline: false,
665
631
  isMobile: false,
666
632
  hasTouch: false,
667
- acceptDownloads: 'accept',
633
+ acceptDownloads: "accept",
668
634
  strictSelectors: false,
669
- serviceWorkers: 'allow',
670
- locale: 'en-US'
671
- };
635
+ serviceWorkers: "allow",
636
+ locale: "en-US"
637
+ };
638
+ // Annotate the CommonJS export names for ESM import in node:
639
+ 0 && (module.exports = {
640
+ BrowserContext,
641
+ assertBrowserContextIsNotOwned,
642
+ normalizeProxySettings,
643
+ validateBrowserContextOptions,
644
+ verifyClientCertificates,
645
+ verifyGeolocation
646
+ });