@itmetsam/samurai-framework 0.1.0 → 0.2.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.
- package/README.md +129 -0
- package/bin/samurai.mjs +31 -0
- package/dist/api.js +3 -0
- package/dist/assert/assertion-error.d.ts +23 -0
- package/dist/assert/assertion-error.js +45 -0
- package/dist/assert/expect.d.ts +55 -0
- package/dist/assert/expect.js +188 -0
- package/dist/browser/browser-context.d.ts +91 -0
- package/dist/browser/browser-context.js +146 -0
- package/dist/browser/browser-finder.d.ts +2 -0
- package/dist/browser/browser-finder.js +95 -0
- package/dist/browser/browser.d.ts +95 -0
- package/dist/browser/browser.js +372 -0
- package/dist/browser/context-tree.d.ts +23 -0
- package/dist/browser/context-tree.js +60 -0
- package/dist/browser/dialog.d.ts +37 -0
- package/dist/browser/dialog.js +61 -0
- package/dist/browser/download.d.ts +71 -0
- package/dist/browser/download.js +137 -0
- package/dist/browser/downloads-dir.d.ts +8 -0
- package/dist/browser/downloads-dir.js +38 -0
- package/dist/browser/emulation.d.ts +61 -0
- package/dist/browser/emulation.js +144 -0
- package/dist/browser/file-chooser.d.ts +39 -0
- package/dist/browser/file-chooser.js +86 -0
- package/dist/browser/file-paths.d.ts +4 -0
- package/dist/browser/file-paths.js +18 -0
- package/dist/browser/index.d.ts +4 -0
- package/dist/browser/index.js +4 -0
- package/dist/browser/navigation-error.d.ts +13 -0
- package/dist/browser/navigation-error.js +19 -0
- package/dist/browser/page-logs.d.ts +86 -0
- package/dist/browser/page-logs.js +149 -0
- package/dist/browser/page-wait.d.ts +9 -0
- package/dist/browser/page-wait.js +17 -0
- package/dist/browser/page.d.ts +370 -0
- package/dist/browser/page.js +1038 -0
- package/dist/browser/pdf.d.ts +72 -0
- package/dist/browser/pdf.js +37 -0
- package/dist/browser/screenshot.d.ts +29 -0
- package/dist/browser/screenshot.js +42 -0
- package/dist/cli/args.d.ts +35 -0
- package/dist/cli/args.js +69 -0
- package/dist/cli/cli.cli-test.d.ts +1 -0
- package/dist/cli/cli.cli-test.js +170 -0
- package/dist/cli/console-reporter.d.ts +15 -0
- package/dist/cli/console-reporter.js +52 -0
- package/dist/cli/init.d.ts +7 -0
- package/dist/cli/init.js +61 -0
- package/dist/cli/main.d.ts +12 -0
- package/dist/cli/main.js +156 -0
- package/dist/config/config.d.ts +24 -0
- package/dist/config/config.js +42 -0
- package/dist/config/default.d.ts +2 -0
- package/dist/config/default.js +3 -0
- package/dist/config/mask.d.ts +11 -0
- package/dist/config/mask.js +85 -0
- package/dist/config/run-settings.d.ts +28 -0
- package/dist/config/run-settings.js +61 -0
- package/dist/config/secrets.d.ts +10 -0
- package/dist/config/secrets.js +67 -0
- package/dist/config/variables.d.ts +11 -0
- package/dist/config/variables.js +26 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +15 -0
- package/dist/locator/action-timeout-error.d.ts +25 -0
- package/dist/locator/action-timeout-error.js +35 -0
- package/dist/locator/element-state.d.ts +44 -0
- package/dist/locator/element-state.js +109 -0
- package/dist/locator/label-locator.d.ts +13 -0
- package/dist/locator/label-locator.js +49 -0
- package/dist/locator/locator.d.ts +168 -0
- package/dist/locator/locator.js +591 -0
- package/dist/locator/selector-errors.d.ts +9 -0
- package/dist/locator/selector-errors.js +15 -0
- package/dist/locator/selector.d.ts +60 -0
- package/dist/locator/selector.js +113 -0
- package/dist/locator/text-locator.d.ts +13 -0
- package/dist/logger/index.d.ts +2 -0
- package/dist/logger/index.js +30 -0
- package/dist/network/data-collector.d.ts +26 -0
- package/dist/network/data-collector.js +77 -0
- package/dist/network/network-tracker.d.ts +94 -0
- package/dist/network/network-tracker.js +198 -0
- package/dist/network/network-wait.d.ts +16 -0
- package/dist/network/network-wait.js +24 -0
- package/dist/network/response.d.ts +22 -0
- package/dist/network/response.js +42 -0
- package/dist/network/router.d.ts +120 -0
- package/dist/network/router.js +343 -0
- package/dist/network/url-match.d.ts +8 -0
- package/dist/network/url-match.js +38 -0
- package/dist/recorder/apply.d.ts +3 -0
- package/dist/recorder/apply.js +10 -0
- package/dist/recorder/capture.d.ts +18 -0
- package/dist/recorder/capture.js +198 -0
- package/dist/recorder/index.d.ts +3 -0
- package/dist/recorder/index.js +3 -0
- package/dist/recorder/normalise.d.ts +68 -0
- package/dist/recorder/normalise.js +104 -0
- package/dist/recorder/ranking.d.ts +9 -0
- package/dist/recorder/ranking.js +21 -0
- package/dist/recorder/recorder.d.ts +52 -0
- package/dist/recorder/recorder.js +143 -0
- package/dist/recorder/session.d.ts +49 -0
- package/dist/recorder/session.js +113 -0
- package/dist/runner/module-type.d.ts +6 -0
- package/dist/runner/module-type.js +29 -0
- package/dist/runner/page-logs-report.d.ts +40 -0
- package/dist/runner/page-logs-report.js +44 -0
- package/dist/runner/prepare-run.d.ts +14 -0
- package/dist/runner/prepare-run.js +20 -0
- package/dist/runner/project.d.ts +17 -0
- package/dist/runner/project.js +33 -0
- package/dist/runner/registry.d.ts +7 -0
- package/dist/runner/registry.js +40 -0
- package/dist/runner/reporter.d.ts +43 -0
- package/dist/runner/reporter.js +83 -0
- package/dist/runner/run.d.ts +27 -0
- package/dist/runner/run.js +34 -0
- package/dist/runner/test-error.d.ts +3 -0
- package/dist/runner/test-error.js +18 -0
- package/dist/runner/test-runner.d.ts +44 -0
- package/dist/runner/test-runner.js +205 -0
- package/dist/script/call-function.d.ts +34 -0
- package/dist/script/call-function.js +71 -0
- package/dist/script/element-handle.d.ts +10 -0
- package/{src/script/element-handle.ts → dist/script/element-handle.js} +4 -4
- package/dist/script/helpers.d.ts +28 -0
- package/dist/script/helpers.js +50 -0
- package/dist/script/preload.d.ts +31 -0
- package/dist/script/preload.js +71 -0
- package/dist/script/serialize.d.ts +29 -0
- package/dist/script/serialize.js +207 -0
- package/dist/steps/build.d.ts +5 -0
- package/dist/steps/build.js +38 -0
- package/dist/steps/edit.d.ts +30 -0
- package/dist/steps/edit.js +80 -0
- package/dist/steps/emit.d.ts +6 -0
- package/dist/steps/emit.js +73 -0
- package/dist/steps/index.d.ts +5 -0
- package/dist/steps/index.js +4 -0
- package/dist/steps/model.d.ts +103 -0
- package/dist/steps/model.js +1 -0
- package/dist/steps/parse.d.ts +3 -0
- package/dist/steps/parse.js +272 -0
- package/dist/transport/bidi-connection.d.ts +46 -0
- package/dist/transport/bidi-connection.js +176 -0
- package/dist/transport/bidi-error.d.ts +10 -0
- package/dist/transport/bidi-error.js +10 -0
- package/dist/transport/subscriptions.d.ts +36 -0
- package/dist/transport/subscriptions.js +81 -0
- package/{src → dist}/types/test.d.ts +10 -4
- package/dist/wait/wait-until.d.ts +20 -0
- package/dist/wait/wait-until.js +63 -0
- package/package.json +44 -7
- package/.claude/settings.local.json +0 -7
- package/.env.example +0 -3
- package/.github/actions/setup/action.yml +0 -16
- package/.github/workflows/ci.yml +0 -71
- package/.trunk/configs/.markdownlint.yaml +0 -2
- package/.trunk/configs/.yamllint.yaml +0 -7
- package/.trunk/configs/svgo.config.mjs +0 -14
- package/.trunk/trunk.yaml +0 -34
- package/docs/superpowers/bidi-roadmap.md +0 -60
- package/docs/superpowers/plans/2026-09-29-auto-wait.md +0 -1827
- package/docs/superpowers/plans/2026-09-29-expect.md +0 -1350
- package/docs/superpowers/plans/2026-10-01-ci.md +0 -350
- package/docs/superpowers/plans/2026-10-01-test-api-alignment.md +0 -1821
- package/docs/superpowers/recorder-roadmap.md +0 -52
- package/docs/superpowers/specs/2026-09-29-auto-wait-design.md +0 -185
- package/docs/superpowers/specs/2026-09-29-bidi-foundation-design.md +0 -130
- package/docs/superpowers/specs/2026-09-29-contexts-and-storage-design.md +0 -88
- package/docs/superpowers/specs/2026-09-29-downloads-and-file-dialogs-design.md +0 -94
- package/docs/superpowers/specs/2026-09-29-emulation-design.md +0 -88
- package/docs/superpowers/specs/2026-09-29-expect-design.md +0 -130
- package/docs/superpowers/specs/2026-09-29-locate-nodes-design.md +0 -90
- package/docs/superpowers/specs/2026-09-29-logs-and-errors-design.md +0 -87
- package/docs/superpowers/specs/2026-09-29-navigation-waits-design.md +0 -83
- package/docs/superpowers/specs/2026-09-29-network-data-design.md +0 -78
- package/docs/superpowers/specs/2026-09-29-network-interception-design.md +0 -91
- package/docs/superpowers/specs/2026-09-29-network-tracking-design.md +0 -86
- package/docs/superpowers/specs/2026-09-29-page-api-design.md +0 -90
- package/docs/superpowers/specs/2026-09-29-preload-scripts-design.md +0 -82
- package/docs/superpowers/specs/2026-09-29-script-call-function-design.md +0 -107
- package/docs/superpowers/specs/2026-09-29-set-files-design.md +0 -62
- package/docs/superpowers/specs/2026-09-29-user-prompts-design.md +0 -75
- package/docs/superpowers/specs/2026-10-01-ci-design.md +0 -106
- package/docs/superpowers/specs/2026-10-01-test-api-alignment-design.md +0 -241
- package/public/logo-dark.svg +0 -236
- package/public/logo-light.svg +0 -262
- package/samurai.config.ts +0 -7
- package/src/assert/assertion-error.test.ts +0 -55
- package/src/assert/assertion-error.ts +0 -62
- package/src/assert/expect-locator.test.ts +0 -217
- package/src/assert/expect.test.ts +0 -73
- package/src/assert/expect.ts +0 -299
- package/src/browser/browser-context.browser-test.ts +0 -201
- package/src/browser/browser-context.test.ts +0 -407
- package/src/browser/browser-context.ts +0 -208
- package/src/browser/browser-finder.ts +0 -110
- package/src/browser/browser.test.ts +0 -88
- package/src/browser/browser.ts +0 -515
- package/src/browser/context-tree.test.ts +0 -86
- package/src/browser/context-tree.ts +0 -70
- package/src/browser/dialog.browser-test.ts +0 -144
- package/src/browser/dialog.test.ts +0 -322
- package/src/browser/dialog.ts +0 -83
- package/src/browser/download.test.ts +0 -161
- package/src/browser/download.ts +0 -172
- package/src/browser/downloads-dir.test.ts +0 -75
- package/src/browser/downloads-dir.ts +0 -39
- package/src/browser/emulation.browser-test.ts +0 -186
- package/src/browser/emulation.test.ts +0 -200
- package/src/browser/emulation.ts +0 -204
- package/src/browser/file-chooser.test.ts +0 -142
- package/src/browser/file-chooser.ts +0 -99
- package/src/browser/file-paths.ts +0 -18
- package/src/browser/goto.browser-test.ts +0 -44
- package/src/browser/navigation-error.ts +0 -26
- package/src/browser/navigation.browser-test.ts +0 -172
- package/src/browser/page-api.browser-test.ts +0 -228
- package/src/browser/page-logs.browser-test.ts +0 -119
- package/src/browser/page-logs.test.ts +0 -212
- package/src/browser/page-logs.ts +0 -208
- package/src/browser/page-wait.ts +0 -19
- package/src/browser/page.test.ts +0 -1567
- package/src/browser/page.ts +0 -1176
- package/src/browser/pdf.ts +0 -62
- package/src/browser/screenshot.ts +0 -65
- package/src/browser/transfers.browser-test.ts +0 -180
- package/src/config/config.ts +0 -33
- package/src/config/default.ts +0 -5
- package/src/config/fixtures.test.ts +0 -137
- package/src/config/mask.test.ts +0 -143
- package/src/config/mask.ts +0 -87
- package/src/config/run-settings.test.ts +0 -163
- package/src/config/run-settings.ts +0 -114
- package/src/config/secrets.ts +0 -70
- package/src/config/variables.ts +0 -31
- package/src/index.ts +0 -10
- package/src/locator/action-timeout-error.test.ts +0 -83
- package/src/locator/action-timeout-error.ts +0 -72
- package/src/locator/element-state.test.ts +0 -181
- package/src/locator/element-state.ts +0 -159
- package/src/locator/locate-nodes.browser-test.ts +0 -169
- package/src/locator/locator-actions.test.ts +0 -355
- package/src/locator/locator-chain.test.ts +0 -292
- package/src/locator/locator.browser-test.ts +0 -137
- package/src/locator/locator.test.ts +0 -179
- package/src/locator/locator.ts +0 -656
- package/src/locator/selector-errors.ts +0 -18
- package/src/locator/selector.test.ts +0 -124
- package/src/locator/selector.ts +0 -107
- package/src/locator/set-files.browser-test.ts +0 -141
- package/src/locator/set-files.test.ts +0 -191
- package/src/locator/text-locator.test.ts +0 -118
- package/src/logger/index.test.ts +0 -28
- package/src/logger/index.ts +0 -40
- package/src/network/data-collector.test.ts +0 -111
- package/src/network/data-collector.ts +0 -92
- package/src/network/network-data.browser-test.ts +0 -192
- package/src/network/network-tracker.browser-test.ts +0 -151
- package/src/network/network-tracker.test.ts +0 -307
- package/src/network/network-tracker.ts +0 -286
- package/src/network/network-wait.ts +0 -28
- package/src/network/response.test.ts +0 -93
- package/src/network/response.ts +0 -58
- package/src/network/router.browser-test.ts +0 -260
- package/src/network/router.test.ts +0 -528
- package/src/network/router.ts +0 -420
- package/src/network/url-match.test.ts +0 -69
- package/src/network/url-match.ts +0 -41
- package/src/runner/page-logs-report.test.ts +0 -144
- package/src/runner/page-logs-report.ts +0 -82
- package/src/runner/prepare-run.test.ts +0 -33
- package/src/runner/prepare-run.ts +0 -36
- package/src/runner/registry.test.ts +0 -59
- package/src/runner/registry.ts +0 -46
- package/src/runner/reporter.test.ts +0 -73
- package/src/runner/reporter.ts +0 -109
- package/src/runner/test-error.test.ts +0 -39
- package/src/runner/test-error.ts +0 -20
- package/src/runner/test-runner.ts +0 -184
- package/src/script/call-function.browser-test.ts +0 -112
- package/src/script/call-function.test.ts +0 -174
- package/src/script/call-function.ts +0 -113
- package/src/script/helpers.test.ts +0 -116
- package/src/script/helpers.ts +0 -68
- package/src/script/preload.browser-test.ts +0 -144
- package/src/script/preload.test.ts +0 -180
- package/src/script/preload.ts +0 -102
- package/src/script/serialize.test.ts +0 -182
- package/src/script/serialize.ts +0 -203
- package/src/testing/browser-fixture.ts +0 -18
- package/src/testing/fake-websocket.ts +0 -72
- package/src/testing/stub-connector.ts +0 -154
- package/src/tests/index.spec.ts +0 -30
- package/src/transport/bidi-connection.test.ts +0 -155
- package/src/transport/bidi-connection.ts +0 -256
- package/src/transport/bidi-error.ts +0 -23
- package/src/transport/foundation.browser-test.ts +0 -73
- package/src/transport/subscriptions.test.ts +0 -140
- package/src/transport/subscriptions.ts +0 -110
- package/src/types/bidi-commands.test-d.ts +0 -55
- package/src/wait/wait-until.test.ts +0 -117
- package/src/wait/wait-until.ts +0 -86
- package/tsconfig.json +0 -44
- /package/{src/api.ts → dist/api.d.ts} +0 -0
- /package/{src/locator/text-locator.ts → dist/locator/text-locator.js} +0 -0
- /package/{src → dist}/types/bidi-modules/browser.d.ts +0 -0
- /package/{src → dist}/types/bidi-modules/browsing-context.d.ts +0 -0
- /package/{src → dist}/types/bidi-modules/emulation.d.ts +0 -0
- /package/{src → dist}/types/bidi-modules/input.d.ts +0 -0
- /package/{src → dist}/types/bidi-modules/log.d.ts +0 -0
- /package/{src → dist}/types/bidi-modules/network.d.ts +0 -0
- /package/{src → dist}/types/bidi-modules/permissions.d.ts +0 -0
- /package/{src → dist}/types/bidi-modules/script.d.ts +0 -0
- /package/{src → dist}/types/bidi-modules/session.d.ts +0 -0
- /package/{src → dist}/types/bidi-modules/storage.d.ts +0 -0
- /package/{src → dist}/types/bidi-modules/web-extensions.d.ts +0 -0
- /package/{src → dist}/types/bidi-protocols/command.d.ts +0 -0
- /package/{src → dist}/types/bidi-protocols/error.d.ts +0 -0
- /package/{src → dist}/types/bidi-protocols/event.d.ts +0 -0
- /package/{src → dist}/types/bidi.d.ts +0 -0
- /package/{src → dist}/types/browser.d.ts +0 -0
- /package/{src → dist}/types/config.d.ts +0 -0
- /package/{src → dist}/types/env.d.ts +0 -0
|
@@ -0,0 +1,1038 @@
|
|
|
1
|
+
import Locator, {} from "../locator/locator.js";
|
|
2
|
+
import { cssSelector, labelSelector, roleSelector, testIdSelector, textSelector, } from "../locator/selector.js";
|
|
3
|
+
import EventEmitter from "node:events";
|
|
4
|
+
import { readConfig } from "../config/config.js";
|
|
5
|
+
import { peekRunSettings } from "../config/run-settings.js";
|
|
6
|
+
import logger from "../logger/index.js";
|
|
7
|
+
import { NetworkTracker, } from "../network/network-tracker.js";
|
|
8
|
+
import { Recorder } from "../recorder/recorder.js";
|
|
9
|
+
import { ContextTree } from "./context-tree.js";
|
|
10
|
+
import { Dialog } from "./dialog.js";
|
|
11
|
+
import { printPdf } from "./pdf.js";
|
|
12
|
+
import { applyEmulation } from "./emulation.js";
|
|
13
|
+
import { Download, DownloadTracker } from "./download.js";
|
|
14
|
+
import { FileChooser, FileChooserTracker } from "./file-chooser.js";
|
|
15
|
+
import { DownloadWaitTimeoutError, FileChooserTimeoutError, } from "./page-wait.js";
|
|
16
|
+
import { takeScreenshot } from "./screenshot.js";
|
|
17
|
+
import { PageLogs, } from "./page-logs.js";
|
|
18
|
+
import { Router } from "../network/router.js";
|
|
19
|
+
import { DataCollector, ResponseBodyUnavailableError, } from "../network/data-collector.js";
|
|
20
|
+
import { Response } from "../network/response.js";
|
|
21
|
+
import { RequestTimeoutError, ResponseTimeoutError, toPredicate, } from "../network/network-wait.js";
|
|
22
|
+
import { UnsupportedOperationError } from "../locator/selector-errors.js";
|
|
23
|
+
import { toFunctionDeclaration } from "../script/call-function.js";
|
|
24
|
+
import { HelperRealm } from "../script/helpers.js";
|
|
25
|
+
import { addPreload } from "../script/preload.js";
|
|
26
|
+
import { BiDiError } from "../transport/bidi-error.js";
|
|
27
|
+
import { WaitTimeoutError } from "../wait/wait-until.js";
|
|
28
|
+
import { LoadStateTimeoutError, NavigationError } from "./navigation-error.js";
|
|
29
|
+
import { callFunction } from "../script/call-function.js";
|
|
30
|
+
/** Time (ms) a navigation or a wait for a load state may take */
|
|
31
|
+
const DEFAULT_NAVIGATION_TIMEOUT = 30000;
|
|
32
|
+
/** Time (ms) without requests in flight that counts as idle */
|
|
33
|
+
const DEFAULT_IDLE_TIME = 500;
|
|
34
|
+
/** The size a page gets unless config `use.viewport` says otherwise */
|
|
35
|
+
const DEFAULT_VIEWPORT = { width: 1280, height: 720 };
|
|
36
|
+
/** Events a connection's browser rejected as unknown, so nothing asks for them again */
|
|
37
|
+
const unsupportedEventsByConnector = new WeakMap();
|
|
38
|
+
function unsupportedEvents(connector) {
|
|
39
|
+
let events = unsupportedEventsByConnector.get(connector);
|
|
40
|
+
if (!events)
|
|
41
|
+
unsupportedEventsByConnector.set(connector, (events = new Set()));
|
|
42
|
+
return events;
|
|
43
|
+
}
|
|
44
|
+
class NetworkTrackingDisabledError extends Error {
|
|
45
|
+
constructor() {
|
|
46
|
+
super("network tracking is disabled");
|
|
47
|
+
this.name = "NetworkTrackingDisabledError";
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
async function readSection(key) {
|
|
51
|
+
try {
|
|
52
|
+
return ((await readConfig(key)) ?? {});
|
|
53
|
+
}
|
|
54
|
+
catch (err) {
|
|
55
|
+
logger.debug("Could not read %s config, using defaults", key, { err });
|
|
56
|
+
return {};
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export default class Page {
|
|
60
|
+
/** `settings` override what `samurai.config.ts` says; without them the config is read when needed */
|
|
61
|
+
constructor(biDiConnector, contextId, settings) {
|
|
62
|
+
this.initScripts = new Set();
|
|
63
|
+
this.pageEvents = new EventEmitter();
|
|
64
|
+
/** How far navigations that did not wait for the load got, by navigation id (the latest few) */
|
|
65
|
+
this.navigationProgress = new Map();
|
|
66
|
+
this.errorsAllowed = false;
|
|
67
|
+
this.isClosed = false;
|
|
68
|
+
this.responses = new WeakMap();
|
|
69
|
+
this.openDialogs = new Map();
|
|
70
|
+
this.onDocumentEvent = (kind) => (info) => {
|
|
71
|
+
if (info.context !== this.id || info.navigation === null)
|
|
72
|
+
return;
|
|
73
|
+
const progress = this.progressOf(info.navigation);
|
|
74
|
+
progress.domContentLoaded = true;
|
|
75
|
+
if (kind === "load")
|
|
76
|
+
progress.load = true;
|
|
77
|
+
};
|
|
78
|
+
this.onDomContentLoaded = this.onDocumentEvent("domContentLoaded");
|
|
79
|
+
this.onLoad = this.onDocumentEvent("load");
|
|
80
|
+
this.onPromptOpened = (params) => {
|
|
81
|
+
if (!this.ownsContext(params.context))
|
|
82
|
+
return;
|
|
83
|
+
this.dispatchDialog(new Dialog(this.biDiConnector, this.id, params), params).catch((err) => logger.error("Handling a dialog failed", { err }));
|
|
84
|
+
};
|
|
85
|
+
this.onPromptClosed = (params) => {
|
|
86
|
+
if (!this.ownsContext(params.context))
|
|
87
|
+
return;
|
|
88
|
+
const dialog = this.openDialogs.get(params.context);
|
|
89
|
+
this.openDialogs.delete(params.context);
|
|
90
|
+
dialog?.markClosed({
|
|
91
|
+
accepted: params.accepted,
|
|
92
|
+
...(params.userText !== undefined && { userText: params.userText }),
|
|
93
|
+
});
|
|
94
|
+
};
|
|
95
|
+
this.biDiConnector = biDiConnector;
|
|
96
|
+
this.id = contextId;
|
|
97
|
+
this.settings = settings;
|
|
98
|
+
this.helperRealm = new HelperRealm(biDiConnector, contextId);
|
|
99
|
+
}
|
|
100
|
+
/** The BiDi browsing context id of this page's top-level context */
|
|
101
|
+
get contextId() {
|
|
102
|
+
return this.id;
|
|
103
|
+
}
|
|
104
|
+
/** The context tree, created on first use and shared by everything that needs to attribute frame events to this page */
|
|
105
|
+
tree() {
|
|
106
|
+
this.contextTree ??= ContextTree.create(this.biDiConnector).then((tree) => (this.loadedTree = tree), (err) => {
|
|
107
|
+
this.contextTree = undefined;
|
|
108
|
+
throw err;
|
|
109
|
+
});
|
|
110
|
+
return this.contextTree;
|
|
111
|
+
}
|
|
112
|
+
/** Locates an element on the page and returns an interactable object */
|
|
113
|
+
locator(xpath) {
|
|
114
|
+
this.assertOpen();
|
|
115
|
+
return new Locator(xpath, this.biDiConnector, this.id, this.helperRealm);
|
|
116
|
+
}
|
|
117
|
+
/** Locates elements with a CSS selector */
|
|
118
|
+
getByCss(css) {
|
|
119
|
+
this.assertOpen();
|
|
120
|
+
return new Locator([cssSelector(css)], this.biDiConnector, this.id, this.helperRealm);
|
|
121
|
+
}
|
|
122
|
+
/** Locates elements by their text: an exact match unless `match: "partial"` */
|
|
123
|
+
getByText(text, options) {
|
|
124
|
+
this.assertOpen();
|
|
125
|
+
return new Locator([textSelector(text, options)], this.biDiConnector, this.id, this.helperRealm);
|
|
126
|
+
}
|
|
127
|
+
/** Locates form controls by their label text: an exact match unless `match: "partial"` */
|
|
128
|
+
getByLabel(text, options) {
|
|
129
|
+
this.assertOpen();
|
|
130
|
+
return new Locator([labelSelector(text, options)], this.biDiConnector, this.id, this.helperRealm);
|
|
131
|
+
}
|
|
132
|
+
/** Locates elements by their `data-testid` attribute */
|
|
133
|
+
getByTestId(testId) {
|
|
134
|
+
this.assertOpen();
|
|
135
|
+
return new Locator([testIdSelector(testId)], this.biDiConnector, this.id, this.helperRealm);
|
|
136
|
+
}
|
|
137
|
+
/** Locates elements by ARIA role and, optionally, accessible name */
|
|
138
|
+
getByRole(role, options) {
|
|
139
|
+
this.assertOpen();
|
|
140
|
+
return new Locator([roleSelector(role, options)], this.biDiConnector, this.id, this.helperRealm);
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Runs `script` before any page script in every document this page loads from now on, and once in
|
|
144
|
+
* the document that is loaded now. It runs in the page's own realm, so the page sees what it sets.
|
|
145
|
+
* A function receives `arg` (which must be JSON-serializable) as its only argument;
|
|
146
|
+
* a string is script source (statements) and takes no argument.
|
|
147
|
+
* @example
|
|
148
|
+
* await page.addInitScript(() => { window.__testMode = true; });
|
|
149
|
+
* await page.addInitScript((flags) => { window.flags = flags; }, { beta: true });
|
|
150
|
+
*/
|
|
151
|
+
async addInitScript(script, arg) {
|
|
152
|
+
this.assertOpen();
|
|
153
|
+
const source = initScriptSource(script, arg);
|
|
154
|
+
const handle = await addPreload(this.biDiConnector, {
|
|
155
|
+
source,
|
|
156
|
+
contexts: [this.id],
|
|
157
|
+
onRunError: "log",
|
|
158
|
+
});
|
|
159
|
+
const tracked = {
|
|
160
|
+
id: handle.id,
|
|
161
|
+
dispose: async () => {
|
|
162
|
+
this.initScripts.delete(tracked);
|
|
163
|
+
await handle.dispose();
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
this.initScripts.add(tracked);
|
|
167
|
+
return tracked;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Starts recording what a person does in the page as steps (see `Recorder`). The page must be driven by
|
|
171
|
+
* a person; stop with `recorder.stop()`.
|
|
172
|
+
*/
|
|
173
|
+
record(options) {
|
|
174
|
+
this.assertOpen();
|
|
175
|
+
return Recorder.start({ page: this, connector: this.biDiConnector, context: this.id }, options);
|
|
176
|
+
}
|
|
177
|
+
/** Removes everything the page registered in the browser: init scripts, framework helpers and event subscriptions */
|
|
178
|
+
async dispose() {
|
|
179
|
+
const scripts = [...this.initScripts];
|
|
180
|
+
const tracker = this.networkTracker;
|
|
181
|
+
this.networkTracker = undefined;
|
|
182
|
+
const results = await Promise.allSettled([
|
|
183
|
+
...scripts.map((handle) => handle.dispose()),
|
|
184
|
+
this.helperRealm.dispose(),
|
|
185
|
+
// The tracker goes before the tree it reads
|
|
186
|
+
tracker?.then((resolved) => resolved.dispose()).catch(() => undefined),
|
|
187
|
+
]);
|
|
188
|
+
const tree = this.contextTree;
|
|
189
|
+
this.contextTree = undefined;
|
|
190
|
+
const documentEvents = this.documentEvents;
|
|
191
|
+
this.documentEvents = undefined;
|
|
192
|
+
const dialogHandling = this.dialogHandling;
|
|
193
|
+
this.dialogHandling = undefined;
|
|
194
|
+
const pageLogs = this.pageLogs;
|
|
195
|
+
this.pageLogs = undefined;
|
|
196
|
+
this.loadedLogs = undefined;
|
|
197
|
+
const downloads = this.downloadTracker;
|
|
198
|
+
this.downloadTracker = undefined;
|
|
199
|
+
const fileChoosers = this.fileChooserTracker;
|
|
200
|
+
this.fileChooserTracker = undefined;
|
|
201
|
+
const collector = this.collectorPromise;
|
|
202
|
+
this.collectorPromise = undefined;
|
|
203
|
+
const router = this.routerPromise;
|
|
204
|
+
this.routerPromise = undefined;
|
|
205
|
+
this.loadedRouter = undefined;
|
|
206
|
+
this.biDiConnector.offEvent("browsingContext.userPromptOpened", this.onPromptOpened);
|
|
207
|
+
this.biDiConnector.offEvent("browsingContext.userPromptClosed", this.onPromptClosed);
|
|
208
|
+
this.openDialogs.clear();
|
|
209
|
+
this.biDiConnector.offEvent("browsingContext.domContentLoaded", this.onDomContentLoaded);
|
|
210
|
+
this.biDiConnector.offEvent("browsingContext.load", this.onLoad);
|
|
211
|
+
results.push(...(await Promise.allSettled([
|
|
212
|
+
tree?.then((resolved) => resolved.dispose()),
|
|
213
|
+
documentEvents?.then((subscription) => subscription.unsubscribe()),
|
|
214
|
+
dialogHandling?.then((subscription) => subscription.unsubscribe()),
|
|
215
|
+
pageLogs?.then((logs) => logs.dispose()),
|
|
216
|
+
router?.then((resolved) => resolved.dispose()),
|
|
217
|
+
collector?.then((resolved) => resolved.dispose()),
|
|
218
|
+
downloads?.then((resolved) => resolved.dispose()),
|
|
219
|
+
fileChoosers?.then((resolved) => resolved.dispose()),
|
|
220
|
+
])));
|
|
221
|
+
const failed = results.find((result) => result.status === "rejected");
|
|
222
|
+
if (failed)
|
|
223
|
+
throw failed.reason;
|
|
224
|
+
}
|
|
225
|
+
/** Sets the base that relative `goto` URLs resolve against; `undefined` falls back to the run's baseURL */
|
|
226
|
+
setBaseURL(url) {
|
|
227
|
+
this.baseURL = url;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Navigates like `navigateTo`, but a URL starting with "/", "./" or "../" resolves against the base URL
|
|
231
|
+
* (`setBaseURL`, else the environment's `baseURL`).
|
|
232
|
+
* @example
|
|
233
|
+
* await page.goto("/products");
|
|
234
|
+
* await page.goto("https://example.com", { wait: "interactive" });
|
|
235
|
+
*/
|
|
236
|
+
async goto(url, options) {
|
|
237
|
+
if (!/^\.{0,2}\//.test(url))
|
|
238
|
+
return this.navigateTo(url, options);
|
|
239
|
+
const base = this.baseURL ?? peekRunSettings()?.baseURL;
|
|
240
|
+
if (!base) {
|
|
241
|
+
throw new Error(`page.goto("${url}") needs a baseURL; set one in samurai.config.ts or the environment`);
|
|
242
|
+
}
|
|
243
|
+
return this.navigateTo(new URL(url, base).href, options);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Navigates to `url` and resolves when the page reached `wait` (default "complete", the load event).
|
|
247
|
+
* A URL without a scheme gets `https://`. Throws NavigationError when the navigation fails or takes too long.
|
|
248
|
+
* The positional form `navigateTo(url, wait, protocol)` still works.
|
|
249
|
+
* @example
|
|
250
|
+
* await page.navigateTo("example.com");
|
|
251
|
+
* await page.navigateTo("localhost:3000", { wait: "interactive", protocol: "http" });
|
|
252
|
+
*/
|
|
253
|
+
async navigateTo(url, options, protocol) {
|
|
254
|
+
const given = typeof options === "string" ? { wait: options } : (options ?? {});
|
|
255
|
+
const settings = await this.navigationSettings();
|
|
256
|
+
const wait = given.wait ?? settings.waitUntil ?? "complete";
|
|
257
|
+
const timeout = given.timeout ?? settings.timeout ?? DEFAULT_NAVIGATION_TIMEOUT;
|
|
258
|
+
// A scheme is letters followed by ":" not directly followed by a digit, so "localhost:3000" is a host
|
|
259
|
+
const hasScheme = /^[a-z][a-z\d+.-]*:(?!\d)/i.test(url);
|
|
260
|
+
const parsedURL = hasScheme
|
|
261
|
+
? url
|
|
262
|
+
: `${given.protocol ?? protocol ?? "https"}://${url}`;
|
|
263
|
+
this.assertOpen();
|
|
264
|
+
return this.navigation("navigateTo", async () => parsedURL, wait, timeout, async (sendOptions) => {
|
|
265
|
+
const result = await this.biDiConnector.send("browsingContext.navigate", { context: this.id, url: parsedURL, wait }, sendOptions);
|
|
266
|
+
return {
|
|
267
|
+
navigation: result.navigation ?? null,
|
|
268
|
+
url: result.url ?? parsedURL,
|
|
269
|
+
};
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Runs a navigation command and settles what waiting for it means: failures become NavigationErrors, and a
|
|
274
|
+
* navigation that did not wait for the load is watched so `waitForLoadState` can tell it from the old page.
|
|
275
|
+
*/
|
|
276
|
+
async navigation(operation, describe, wait, timeout, send) {
|
|
277
|
+
// A navigation that does not wait for the load needs watching, or waitForLoadState cannot tell it from the old page
|
|
278
|
+
if (wait !== "complete")
|
|
279
|
+
await this.watchDocumentEvents();
|
|
280
|
+
try {
|
|
281
|
+
const result = await send({ timeout });
|
|
282
|
+
this.lastNavigation = result.navigation ?? undefined;
|
|
283
|
+
if (result.navigation && wait !== "complete") {
|
|
284
|
+
// Tracked from now on: the document still showing is the old one until this navigation commits
|
|
285
|
+
const progress = this.progressOf(result.navigation);
|
|
286
|
+
if (wait === "interactive")
|
|
287
|
+
progress.domContentLoaded = true;
|
|
288
|
+
}
|
|
289
|
+
return result;
|
|
290
|
+
}
|
|
291
|
+
catch (err) {
|
|
292
|
+
if (err instanceof BiDiError) {
|
|
293
|
+
const reason = err.code === "timeout" ? `timeout after ${timeout}ms` : err.message;
|
|
294
|
+
throw new NavigationError(await describe(), reason, err.code, operation);
|
|
295
|
+
}
|
|
296
|
+
throw err;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Reloads the page and resolves when it reached `wait` (default like `navigateTo`). Firefox does not support
|
|
301
|
+
* `ignoreCache`; asking for it throws UnsupportedOperationError.
|
|
302
|
+
*/
|
|
303
|
+
async reload(options = {}) {
|
|
304
|
+
this.assertOpen();
|
|
305
|
+
const settings = await this.navigationSettings();
|
|
306
|
+
const wait = options.wait ?? settings.waitUntil ?? "complete";
|
|
307
|
+
const timeout = options.timeout ?? settings.timeout ?? DEFAULT_NAVIGATION_TIMEOUT;
|
|
308
|
+
return this.navigation("reload", () => this.url().catch(() => "the page"), wait, timeout, async (sendOptions) => {
|
|
309
|
+
try {
|
|
310
|
+
const result = await this.biDiConnector.send("browsingContext.reload", {
|
|
311
|
+
context: this.id,
|
|
312
|
+
wait,
|
|
313
|
+
...(options.ignoreCache && { ignoreCache: true }),
|
|
314
|
+
}, sendOptions);
|
|
315
|
+
return { navigation: result.navigation ?? null, url: result.url };
|
|
316
|
+
}
|
|
317
|
+
catch (err) {
|
|
318
|
+
if (options.ignoreCache &&
|
|
319
|
+
err instanceof BiDiError &&
|
|
320
|
+
err.code === "unsupported operation") {
|
|
321
|
+
throw new UnsupportedOperationError("reload({ ignoreCache }) is not supported by the browser");
|
|
322
|
+
}
|
|
323
|
+
throw err;
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
/** Goes back one entry in the history. False when there is none to go back to */
|
|
328
|
+
goBack() {
|
|
329
|
+
return this.traverse(-1);
|
|
330
|
+
}
|
|
331
|
+
/** Goes forward one entry in the history. False when there is none */
|
|
332
|
+
goForward() {
|
|
333
|
+
return this.traverse(1);
|
|
334
|
+
}
|
|
335
|
+
async traverse(delta) {
|
|
336
|
+
this.assertOpen();
|
|
337
|
+
try {
|
|
338
|
+
await this.biDiConnector.send("browsingContext.traverseHistory", {
|
|
339
|
+
context: this.id,
|
|
340
|
+
delta,
|
|
341
|
+
});
|
|
342
|
+
return true;
|
|
343
|
+
}
|
|
344
|
+
catch (err) {
|
|
345
|
+
if (err instanceof BiDiError && err.code === "no such history entry")
|
|
346
|
+
return false;
|
|
347
|
+
throw err;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/** The URL of the page now */
|
|
351
|
+
async url() {
|
|
352
|
+
this.assertOpen();
|
|
353
|
+
return callFunction(this.biDiConnector, this.id, "() => location.href", [], { awaitPromise: false });
|
|
354
|
+
}
|
|
355
|
+
/** The title of the document now */
|
|
356
|
+
async title() {
|
|
357
|
+
this.assertOpen();
|
|
358
|
+
return callFunction(this.biDiConnector, this.id, "() => document.title", [], { awaitPromise: false });
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Sets the size of the viewport (and, optionally, the device pixel ratio); `null` puts the browser's own size back.
|
|
362
|
+
* @example
|
|
363
|
+
* await page.setViewport({ width: 390, height: 844, devicePixelRatio: 3 });
|
|
364
|
+
*/
|
|
365
|
+
async setViewport(viewport) {
|
|
366
|
+
this.assertOpen();
|
|
367
|
+
if (viewport === null) {
|
|
368
|
+
await this.biDiConnector.send("browsingContext.setViewport", {
|
|
369
|
+
context: this.id,
|
|
370
|
+
viewport: null,
|
|
371
|
+
devicePixelRatio: null,
|
|
372
|
+
});
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
const { width, height, devicePixelRatio } = viewport;
|
|
376
|
+
for (const [name, value] of [
|
|
377
|
+
["width", width],
|
|
378
|
+
["height", height],
|
|
379
|
+
]) {
|
|
380
|
+
if (!Number.isInteger(value) || value <= 0) {
|
|
381
|
+
throw new RangeError(`setViewport(): ${name} must be a positive integer, got ${value}`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (devicePixelRatio !== undefined &&
|
|
385
|
+
!(devicePixelRatio > 0 && Number.isFinite(devicePixelRatio))) {
|
|
386
|
+
throw new RangeError(`setViewport(): devicePixelRatio must be a positive number, got ${devicePixelRatio}`);
|
|
387
|
+
}
|
|
388
|
+
await this.biDiConnector.send("browsingContext.setViewport", {
|
|
389
|
+
context: this.id,
|
|
390
|
+
viewport: { width, height },
|
|
391
|
+
...(devicePixelRatio !== undefined && { devicePixelRatio }),
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
/** Gives the page the size from config `use.viewport` (1280x720 by default); the browser does this when it opens a page */
|
|
395
|
+
async applyDefaultViewport() {
|
|
396
|
+
const { viewport } = this.settings?.use ?? (await readSection("use"));
|
|
397
|
+
if (viewport === null)
|
|
398
|
+
return;
|
|
399
|
+
await this.setViewport(viewport ?? DEFAULT_VIEWPORT);
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Takes a screenshot and returns the image (also written to `options.path`).
|
|
403
|
+
* @example
|
|
404
|
+
* await page.screenshot({ path: "out/home.png", fullPage: true });
|
|
405
|
+
*/
|
|
406
|
+
async screenshot(options = {}) {
|
|
407
|
+
this.assertOpen();
|
|
408
|
+
return takeScreenshot(this.biDiConnector, this.id, options);
|
|
409
|
+
}
|
|
410
|
+
/** Renders the page as a PDF and returns it (also written to `options.path`) */
|
|
411
|
+
async pdf(options = {}) {
|
|
412
|
+
this.assertOpen();
|
|
413
|
+
return printPdf(this.biDiConnector, this.id, options);
|
|
414
|
+
}
|
|
415
|
+
/** The browser context (cookies, storage) this page belongs to */
|
|
416
|
+
context() {
|
|
417
|
+
if (!this.browserContext)
|
|
418
|
+
throw new Error("this page has no browser context: open it with browser.newPage() or context.newPage()");
|
|
419
|
+
return this.browserContext;
|
|
420
|
+
}
|
|
421
|
+
/** @internal Called when the page is opened in a context */
|
|
422
|
+
setContext(context) {
|
|
423
|
+
this.browserContext = context;
|
|
424
|
+
}
|
|
425
|
+
/** @internal Marks the page closed after its tab is gone (its context was removed) and releases what it registered */
|
|
426
|
+
async detach() {
|
|
427
|
+
this.isClosed = true;
|
|
428
|
+
await this.dispose().catch((err) => logger.debug("Releasing a detached page failed", { err }));
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Pretends things about this page only: locale, timezone, user agent, geolocation, offline, orientation, screen
|
|
432
|
+
* size. It wins over what the page's context says; `null` puts the real (or the context's) value back.
|
|
433
|
+
* @example
|
|
434
|
+
* await page.emulate({ locale: "nl-NL", offline: true });
|
|
435
|
+
*/
|
|
436
|
+
async emulate(options) {
|
|
437
|
+
this.assertOpen();
|
|
438
|
+
await applyEmulation(this.biDiConnector, { contexts: [this.id] }, options);
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Grants a browser permission ("geolocation", "notifications", "camera", …) to the origin this page is on,
|
|
442
|
+
* or to `options.origin`. Geolocation emulation only answers once this is granted.
|
|
443
|
+
*/
|
|
444
|
+
async grantPermission(name, options = {}) {
|
|
445
|
+
this.assertOpen();
|
|
446
|
+
const origin = options.origin ?? new URL(await this.url()).origin;
|
|
447
|
+
// about:blank and data: pages have no origin to grant to
|
|
448
|
+
if (origin === "null")
|
|
449
|
+
throw new Error("grantPermission() needs a page on a web origin, or an explicit origin option");
|
|
450
|
+
const context = this.browserContext;
|
|
451
|
+
await this.biDiConnector.send("permissions.setPermission", {
|
|
452
|
+
descriptor: { name },
|
|
453
|
+
state: "granted",
|
|
454
|
+
origin,
|
|
455
|
+
...(context && !context.isDefault && { userContext: context.id }),
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
/** True once `close()` has run */
|
|
459
|
+
get closed() {
|
|
460
|
+
return this.isClosed;
|
|
461
|
+
}
|
|
462
|
+
assertOpen() {
|
|
463
|
+
if (this.isClosed)
|
|
464
|
+
throw new Error("page closed");
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Closes the tab and releases everything the page registered. Later calls on the page throw "page closed".
|
|
468
|
+
* With `runBeforeUnload` the page's `beforeunload` handlers run first. Closing the browser's last tab may end the browser.
|
|
469
|
+
*/
|
|
470
|
+
async close(options = {}) {
|
|
471
|
+
if (this.isClosed)
|
|
472
|
+
return;
|
|
473
|
+
try {
|
|
474
|
+
await this.biDiConnector.send("browsingContext.close", {
|
|
475
|
+
context: this.id,
|
|
476
|
+
...(options.runBeforeUnload && { promptUnload: true }),
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
catch (err) {
|
|
480
|
+
// Already gone (closed by the page, the browser or another call): the goal is met
|
|
481
|
+
if (!(err instanceof BiDiError && err.code === "no such frame"))
|
|
482
|
+
throw err;
|
|
483
|
+
}
|
|
484
|
+
this.isClosed = true;
|
|
485
|
+
await this.dispose().catch((err) => logger.debug("Releasing a closed page failed", { err }));
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Waits until the page's document reached `state` (default "load"): "domcontentloaded" and "load" follow the
|
|
489
|
+
* document, "networkidle" is "load" plus a quiet network (see `waitForNetworkIdle`). Resolves at once when it
|
|
490
|
+
* is already there. Call it once the navigation has started; a document that is still the old one counts.
|
|
491
|
+
* @example
|
|
492
|
+
* await page.locator("a[@id='next']").click();
|
|
493
|
+
* await page.waitForLoadState("domcontentloaded");
|
|
494
|
+
*/
|
|
495
|
+
async waitForLoadState(state = "load", options = {}) {
|
|
496
|
+
this.assertOpen();
|
|
497
|
+
const timeout = options.timeout ??
|
|
498
|
+
(await this.navigationSettings()).timeout ??
|
|
499
|
+
DEFAULT_NAVIGATION_TIMEOUT;
|
|
500
|
+
try {
|
|
501
|
+
await this.waitForDocumentState(state === "domcontentloaded" ? "domcontentloaded" : "load", timeout);
|
|
502
|
+
}
|
|
503
|
+
catch (err) {
|
|
504
|
+
if (err instanceof WaitTimeoutError)
|
|
505
|
+
throw new LoadStateTimeoutError(state, timeout);
|
|
506
|
+
throw err;
|
|
507
|
+
}
|
|
508
|
+
if (state === "networkidle") {
|
|
509
|
+
const tracker = await this.network();
|
|
510
|
+
const idleTime = (await this.networkSettings()).idleTime ?? DEFAULT_IDLE_TIME;
|
|
511
|
+
await tracker.waitForIdle({ idleTime, timeout });
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
progressOf(navigation) {
|
|
515
|
+
let progress = this.navigationProgress.get(navigation);
|
|
516
|
+
if (!progress) {
|
|
517
|
+
progress = { domContentLoaded: false, load: false };
|
|
518
|
+
this.navigationProgress.set(navigation, progress);
|
|
519
|
+
// Only the latest few navigations matter
|
|
520
|
+
if (this.navigationProgress.size > 20) {
|
|
521
|
+
this.navigationProgress.delete(this.navigationProgress.keys().next().value);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
return progress;
|
|
525
|
+
}
|
|
526
|
+
/** Starts recording which navigations reached DOMContentLoaded and load; kept until dispose */
|
|
527
|
+
watchDocumentEvents() {
|
|
528
|
+
this.documentEvents ??= (async () => {
|
|
529
|
+
this.biDiConnector.onEvent("browsingContext.domContentLoaded", this.onDomContentLoaded);
|
|
530
|
+
this.biDiConnector.onEvent("browsingContext.load", this.onLoad);
|
|
531
|
+
try {
|
|
532
|
+
return await this.biDiConnector.subscribe([
|
|
533
|
+
"browsingContext.domContentLoaded",
|
|
534
|
+
"browsingContext.load",
|
|
535
|
+
]);
|
|
536
|
+
}
|
|
537
|
+
catch (err) {
|
|
538
|
+
this.biDiConnector.offEvent("browsingContext.domContentLoaded", this.onDomContentLoaded);
|
|
539
|
+
this.biDiConnector.offEvent("browsingContext.load", this.onLoad);
|
|
540
|
+
this.documentEvents = undefined;
|
|
541
|
+
throw err;
|
|
542
|
+
}
|
|
543
|
+
})();
|
|
544
|
+
return this.documentEvents;
|
|
545
|
+
}
|
|
546
|
+
canBeAborted() {
|
|
547
|
+
return !unsupportedEvents(this.biDiConnector).has("browsingContext.navigationAborted");
|
|
548
|
+
}
|
|
549
|
+
/** Subscribes to what a wait listens for; a browser that lacks the navigationAborted event (Firefox) is asked only once */
|
|
550
|
+
async subscribeToDocumentEvents(reachedEvent) {
|
|
551
|
+
const required = [
|
|
552
|
+
reachedEvent,
|
|
553
|
+
"browsingContext.navigationFailed",
|
|
554
|
+
];
|
|
555
|
+
if (!this.canBeAborted())
|
|
556
|
+
return this.biDiConnector.subscribe([...required]);
|
|
557
|
+
try {
|
|
558
|
+
return await this.biDiConnector.subscribe([
|
|
559
|
+
...required,
|
|
560
|
+
"browsingContext.navigationAborted",
|
|
561
|
+
]);
|
|
562
|
+
}
|
|
563
|
+
catch (err) {
|
|
564
|
+
if (!(err instanceof BiDiError) || err.code !== "invalid argument")
|
|
565
|
+
throw err;
|
|
566
|
+
unsupportedEvents(this.biDiConnector).add("browsingContext.navigationAborted");
|
|
567
|
+
return this.biDiConnector.subscribe([...required]);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
async waitForDocumentState(target, timeout) {
|
|
571
|
+
const connector = this.biDiConnector;
|
|
572
|
+
const reachedEvent = target === "load"
|
|
573
|
+
? "browsingContext.load"
|
|
574
|
+
: "browsingContext.domContentLoaded";
|
|
575
|
+
const subscription = await this.subscribeToDocumentEvents(reachedEvent);
|
|
576
|
+
const abort = new AbortController();
|
|
577
|
+
const last = this.lastNavigation;
|
|
578
|
+
const listen = { timeout, signal: abort.signal };
|
|
579
|
+
const failure = (info, what) => {
|
|
580
|
+
throw new NavigationError(info.url, what, undefined, "waitForLoadState");
|
|
581
|
+
};
|
|
582
|
+
try {
|
|
583
|
+
// Registered before the state is read, so an event in between is not lost
|
|
584
|
+
const events = Promise.race([
|
|
585
|
+
connector.waitForEvent(reachedEvent, (p) => p.context === this.id, listen),
|
|
586
|
+
connector
|
|
587
|
+
.waitForEvent("browsingContext.navigationFailed", (p) => p.context === this.id &&
|
|
588
|
+
(last === undefined || p.navigation === last), listen)
|
|
589
|
+
.then((p) => failure(p, "navigation failed")),
|
|
590
|
+
...(this.canBeAborted()
|
|
591
|
+
? [
|
|
592
|
+
connector
|
|
593
|
+
.waitForEvent("browsingContext.navigationAborted", (p) => p.context === this.id &&
|
|
594
|
+
last !== undefined &&
|
|
595
|
+
p.navigation === last, listen)
|
|
596
|
+
.then((p) => failure(p, "navigation aborted")),
|
|
597
|
+
]
|
|
598
|
+
: []),
|
|
599
|
+
]);
|
|
600
|
+
events.catch(() => { }); // settled below, or aborted in finally
|
|
601
|
+
const known = last === undefined ? undefined : this.navigationProgress.get(last);
|
|
602
|
+
// A navigation we started and saw fall short of the state beats the document that is showing
|
|
603
|
+
let reached;
|
|
604
|
+
if (known && !(target === "load" ? known.load : known.domContentLoaded)) {
|
|
605
|
+
reached = false;
|
|
606
|
+
}
|
|
607
|
+
else {
|
|
608
|
+
const readyState = await callFunction(connector, this.id, "() => document.readyState", [], {
|
|
609
|
+
awaitPromise: false,
|
|
610
|
+
});
|
|
611
|
+
reached =
|
|
612
|
+
target === "load"
|
|
613
|
+
? readyState === "complete"
|
|
614
|
+
: readyState === "interactive" || readyState === "complete";
|
|
615
|
+
}
|
|
616
|
+
if (!reached)
|
|
617
|
+
await events;
|
|
618
|
+
}
|
|
619
|
+
finally {
|
|
620
|
+
abort.abort();
|
|
621
|
+
await subscription.unsubscribe();
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
networkSettings() {
|
|
625
|
+
return this.settings?.network
|
|
626
|
+
? Promise.resolve(this.settings.network)
|
|
627
|
+
: readSection("network");
|
|
628
|
+
}
|
|
629
|
+
navigationSettings() {
|
|
630
|
+
return this.settings?.navigation
|
|
631
|
+
? Promise.resolve(this.settings.navigation)
|
|
632
|
+
: readSection("navigation");
|
|
633
|
+
}
|
|
634
|
+
/** The network tracker, created on first use. Rejects with NetworkTrackingDisabledError when config turned tracking off */
|
|
635
|
+
network() {
|
|
636
|
+
this.networkTracker ??= (async () => {
|
|
637
|
+
const settings = await this.networkSettings();
|
|
638
|
+
if (settings.track === false)
|
|
639
|
+
throw new NetworkTrackingDisabledError();
|
|
640
|
+
const tracker = await NetworkTracker.start(this.biDiConnector, await this.tree(), this.id);
|
|
641
|
+
tracker.on("request", (request) => this.pageEvents.emit("request", request));
|
|
642
|
+
tracker.on("response", (response) => this.pageEvents.emit("response", this.responseFor(response)));
|
|
643
|
+
tracker.on("requestfailed", (failed) => this.pageEvents.emit("requestfailed", failed));
|
|
644
|
+
if (settings.collectBodies)
|
|
645
|
+
await this.startBodyCollection();
|
|
646
|
+
return tracker;
|
|
647
|
+
})().catch((err) => {
|
|
648
|
+
if (!(err instanceof NetworkTrackingDisabledError))
|
|
649
|
+
this.networkTracker = undefined;
|
|
650
|
+
throw err;
|
|
651
|
+
});
|
|
652
|
+
return this.networkTracker;
|
|
653
|
+
}
|
|
654
|
+
/**
|
|
655
|
+
* Starts following this page's requests now. Tracking only sees requests made after it started, so the
|
|
656
|
+
* browser calls this when it opens a page; without it, tracking starts on first use. Does nothing when
|
|
657
|
+
* config `network.track` is false.
|
|
658
|
+
*/
|
|
659
|
+
async startNetworkTracking() {
|
|
660
|
+
try {
|
|
661
|
+
await this.network();
|
|
662
|
+
}
|
|
663
|
+
catch (err) {
|
|
664
|
+
if (!(err instanceof NetworkTrackingDisabledError))
|
|
665
|
+
throw err;
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Waits until no request has been in flight for `idleTime` ms (default config `network.idleTime`, then 500).
|
|
670
|
+
* Long-lived requests (server-sent events, long polling) keep the page busy until `timeout`.
|
|
671
|
+
*/
|
|
672
|
+
async waitForNetworkIdle(options = {}) {
|
|
673
|
+
const tracker = await this.network();
|
|
674
|
+
const idleTime = options.idleTime ??
|
|
675
|
+
(await this.networkSettings()).idleTime ??
|
|
676
|
+
DEFAULT_IDLE_TIME;
|
|
677
|
+
const timeout = options.timeout ??
|
|
678
|
+
(await this.navigationSettings()).timeout ??
|
|
679
|
+
DEFAULT_NAVIGATION_TIMEOUT;
|
|
680
|
+
await tracker.waitForIdle({ idleTime, timeout });
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Listens for page events: `request`, `response`, `requestfailed` (network), `dialog` (a JavaScript dialog or
|
|
684
|
+
* `beforeunload` prompt opened; answer it with `dialog.accept()` / `dialog.dismiss()`), `console` (a `console.*` call)
|
|
685
|
+
* and `pageerror` (an uncaught exception). Starts what the event needs.
|
|
686
|
+
* A dialog nobody answers is dismissed automatically (a `beforeunload` prompt is accepted), so it cannot hang a test.
|
|
687
|
+
* @example
|
|
688
|
+
* page.on("dialog", (dialog) => dialog.accept());
|
|
689
|
+
*/
|
|
690
|
+
on(event, listener) {
|
|
691
|
+
this.pageEvents.on(event, listener);
|
|
692
|
+
this.trackInBackground(event);
|
|
693
|
+
return this;
|
|
694
|
+
}
|
|
695
|
+
once(event, listener) {
|
|
696
|
+
this.pageEvents.once(event, listener);
|
|
697
|
+
this.trackInBackground(event);
|
|
698
|
+
return this;
|
|
699
|
+
}
|
|
700
|
+
off(event, listener) {
|
|
701
|
+
this.pageEvents.off(event, listener);
|
|
702
|
+
return this;
|
|
703
|
+
}
|
|
704
|
+
trackInBackground(event) {
|
|
705
|
+
const started = event === "dialog"
|
|
706
|
+
? this.startDialogHandling()
|
|
707
|
+
: event === "download"
|
|
708
|
+
? this.startDownloadTracking()
|
|
709
|
+
: event === "filechooser"
|
|
710
|
+
? this.startFileChooserTracking()
|
|
711
|
+
: event === "console" || event === "pageerror"
|
|
712
|
+
? this.startLogging()
|
|
713
|
+
: event === "response"
|
|
714
|
+
? Promise.all([
|
|
715
|
+
this.startNetworkTracking(),
|
|
716
|
+
this.startBodyCollection(),
|
|
717
|
+
])
|
|
718
|
+
: this.startNetworkTracking();
|
|
719
|
+
started.catch((err) => logger.error("Could not start listening for %s", event, { err }));
|
|
720
|
+
}
|
|
721
|
+
/** Starts following downloads; the browser does this when it opens a page, `page.on("download")` and `waitForDownload` when needed */
|
|
722
|
+
async startDownloadTracking() {
|
|
723
|
+
this.downloadTracker ??= (async () => {
|
|
724
|
+
const timeout = (await this.navigationSettings()).timeout ?? DEFAULT_NAVIGATION_TIMEOUT;
|
|
725
|
+
const tracker = await DownloadTracker.start(this.biDiConnector, await this.tree(), this.id, { timeout });
|
|
726
|
+
tracker.on("download", (download) => this.pageEvents.emit("download", download));
|
|
727
|
+
return tracker;
|
|
728
|
+
})().catch((err) => {
|
|
729
|
+
this.downloadTracker = undefined;
|
|
730
|
+
throw err;
|
|
731
|
+
});
|
|
732
|
+
await this.downloadTracker;
|
|
733
|
+
}
|
|
734
|
+
/** Starts following file pickers; the browser does this when it opens a page, `page.on("filechooser")` and `waitForFileChooser` when needed */
|
|
735
|
+
async startFileChooserTracking() {
|
|
736
|
+
this.fileChooserTracker ??= (async () => {
|
|
737
|
+
const tracker = await FileChooserTracker.start(this.biDiConnector, await this.tree(), this.id);
|
|
738
|
+
tracker.on("filechooser", (chooser) => this.pageEvents.emit("filechooser", chooser));
|
|
739
|
+
return tracker;
|
|
740
|
+
})().catch((err) => {
|
|
741
|
+
this.fileChooserTracker = undefined;
|
|
742
|
+
throw err;
|
|
743
|
+
});
|
|
744
|
+
await this.fileChooserTracker;
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Resolves with the next download this page starts (when it starts, not when it ends: use `download.path()` for that).
|
|
748
|
+
* Call it before the download is triggered, or pass `trigger`, which runs once the wait is set up.
|
|
749
|
+
* @example
|
|
750
|
+
* const download = await page.waitForDownload({ trigger: () => link.click() });
|
|
751
|
+
* const file = await download.path();
|
|
752
|
+
*/
|
|
753
|
+
async waitForDownload(options = {}) {
|
|
754
|
+
this.assertOpen();
|
|
755
|
+
await this.startDownloadTracking();
|
|
756
|
+
return this.waitForPageEvent("download", () => true, options, (timeout) => new DownloadWaitTimeoutError(timeout));
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Resolves with the next file picker the page opens (a click on an `<input type=file>` or its label). Nothing shows
|
|
760
|
+
* on screen: answer it with `chooser.setFiles(...)`.
|
|
761
|
+
* @example
|
|
762
|
+
* const chooser = await page.waitForFileChooser({ trigger: () => page.locator("label[@for='avatar']").click() });
|
|
763
|
+
* await chooser.setFiles("./fixtures/avatar.png");
|
|
764
|
+
*/
|
|
765
|
+
async waitForFileChooser(options = {}) {
|
|
766
|
+
this.assertOpen();
|
|
767
|
+
await this.startFileChooserTracking();
|
|
768
|
+
return this.waitForPageEvent("filechooser", () => true, options, (timeout) => new FileChooserTimeoutError(timeout));
|
|
769
|
+
}
|
|
770
|
+
/**
|
|
771
|
+
* Starts keeping response bodies, which is what makes `response.body()` possible: the browser only keeps a body
|
|
772
|
+
* when this ran before the request started. `page.on("response")` and `waitForResponse` call it; config
|
|
773
|
+
* `network.collectBodies` calls it when the browser opens the page.
|
|
774
|
+
*/
|
|
775
|
+
async startBodyCollection() {
|
|
776
|
+
this.collectorPromise ??= (async () => {
|
|
777
|
+
const { maxBodySize } = await this.networkSettings();
|
|
778
|
+
return DataCollector.start(this.biDiConnector, this.id, {
|
|
779
|
+
...(maxBodySize !== undefined && { maxBodySize }),
|
|
780
|
+
});
|
|
781
|
+
})().catch((err) => {
|
|
782
|
+
this.collectorPromise = undefined;
|
|
783
|
+
throw err;
|
|
784
|
+
});
|
|
785
|
+
await this.collectorPromise;
|
|
786
|
+
}
|
|
787
|
+
/** One Response per network response, whoever asks, so a body is read from the browser once */
|
|
788
|
+
responseFor(data) {
|
|
789
|
+
let response = this.responses.get(data);
|
|
790
|
+
if (!response) {
|
|
791
|
+
response = new Response(data, (loaded) => this.loadBody(loaded));
|
|
792
|
+
this.responses.set(data, response);
|
|
793
|
+
}
|
|
794
|
+
return response;
|
|
795
|
+
}
|
|
796
|
+
async loadBody(response) {
|
|
797
|
+
if (!this.collectorPromise) {
|
|
798
|
+
throw new ResponseBodyUnavailableError(response.url, "no body collection was running: call page.startBodyCollection() before the request, or listen with page.on('response')");
|
|
799
|
+
}
|
|
800
|
+
const collector = await this.collectorPromise;
|
|
801
|
+
const body = await collector.read(response.id, response.url);
|
|
802
|
+
void collector.release(response.id);
|
|
803
|
+
return body;
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* Resolves with the next response of this page whose URL matches (a pattern, see `route`) or that the function
|
|
807
|
+
* accepts. Call it before the request is made, or pass `trigger`, which runs once the wait is set up.
|
|
808
|
+
* @example
|
|
809
|
+
* const response = await page.waitForResponse("**\/api/users", { trigger: () => button.click() });
|
|
810
|
+
* const users = await response.json();
|
|
811
|
+
*/
|
|
812
|
+
async waitForResponse(match, options = {}) {
|
|
813
|
+
await Promise.all([this.network(), this.startBodyCollection()]);
|
|
814
|
+
return this.waitForNetworkEvent("response", match, options);
|
|
815
|
+
}
|
|
816
|
+
/** Like `waitForResponse`, for requests */
|
|
817
|
+
async waitForRequest(match, options = {}) {
|
|
818
|
+
await this.network();
|
|
819
|
+
return this.waitForNetworkEvent("request", match, options);
|
|
820
|
+
}
|
|
821
|
+
waitForNetworkEvent(event, match, options) {
|
|
822
|
+
const matches = toPredicate(match);
|
|
823
|
+
const Timeout = event === "request" ? RequestTimeoutError : ResponseTimeoutError;
|
|
824
|
+
return this.waitForPageEvent(event, matches, options, (timeout) => new Timeout(event === "request" ? "waitForRequest" : "waitForResponse", match, timeout));
|
|
825
|
+
}
|
|
826
|
+
/**
|
|
827
|
+
* Resolves with the first `event` `matches` accepts. Listens before `trigger` runs, so what the trigger causes cannot
|
|
828
|
+
* be missed; a trigger that throws rejects the wait with its error. `onTimeout` builds the error for a wait that ran out.
|
|
829
|
+
*/
|
|
830
|
+
async waitForPageEvent(event, matches, options, onTimeout) {
|
|
831
|
+
const timeout = options.timeout ??
|
|
832
|
+
(await this.navigationSettings()).timeout ??
|
|
833
|
+
DEFAULT_NAVIGATION_TIMEOUT;
|
|
834
|
+
return new Promise((resolve, reject) => {
|
|
835
|
+
const done = () => {
|
|
836
|
+
clearTimeout(timer);
|
|
837
|
+
this.pageEvents.off(event, listener);
|
|
838
|
+
};
|
|
839
|
+
const listener = (item) => {
|
|
840
|
+
try {
|
|
841
|
+
if (!matches(item))
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
catch (err) {
|
|
845
|
+
done();
|
|
846
|
+
reject(err);
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
849
|
+
done();
|
|
850
|
+
resolve(item);
|
|
851
|
+
};
|
|
852
|
+
const timer = setTimeout(() => {
|
|
853
|
+
done();
|
|
854
|
+
reject(onTimeout(timeout));
|
|
855
|
+
}, timeout);
|
|
856
|
+
this.pageEvents.on(event, listener);
|
|
857
|
+
const { trigger } = options;
|
|
858
|
+
if (trigger) {
|
|
859
|
+
Promise.resolve()
|
|
860
|
+
.then(trigger)
|
|
861
|
+
.catch((err) => {
|
|
862
|
+
done();
|
|
863
|
+
reject(err);
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
/** Turns the browser's HTTP cache off (`true`) or back on for this page: every request then goes to the server */
|
|
869
|
+
async setCacheDisabled(disabled) {
|
|
870
|
+
try {
|
|
871
|
+
await this.biDiConnector.send("network.setCacheBehavior", {
|
|
872
|
+
cacheBehavior: disabled ? "bypass" : "default",
|
|
873
|
+
contexts: [this.id],
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
catch (err) {
|
|
877
|
+
if (err instanceof BiDiError &&
|
|
878
|
+
(err.code === "unsupported operation" || err.code === "unknown command")) {
|
|
879
|
+
throw new UnsupportedOperationError("page.setCacheDisabled() is not supported by the browser");
|
|
880
|
+
}
|
|
881
|
+
throw err;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
router() {
|
|
885
|
+
this.routerPromise ??= (async () => {
|
|
886
|
+
const routeTimeout = (await this.networkSettings()).routeTimeout;
|
|
887
|
+
const router = new Router(this.biDiConnector, await this.tree(), this.id, {
|
|
888
|
+
...(routeTimeout !== undefined && { routeTimeout }),
|
|
889
|
+
});
|
|
890
|
+
this.loadedRouter = router;
|
|
891
|
+
return router;
|
|
892
|
+
})().catch((err) => {
|
|
893
|
+
this.routerPromise = undefined;
|
|
894
|
+
throw err;
|
|
895
|
+
});
|
|
896
|
+
return this.routerPromise;
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Sends requests whose URL matches to `handler`, which must answer with `route.fulfill()`, `route.continue()`,
|
|
900
|
+
* `route.abort()` or `route.fallback()` (await the answer: a handler that returns first lets the request continue).
|
|
901
|
+
* A string without `*` is an exact URL, with `*` / `**` a glob (`*` stops at `/`), a RegExp is tested on the URL.
|
|
902
|
+
* Routes added later are asked first. Errors a handler throws fail the request and, in the runner, the test.
|
|
903
|
+
* @example
|
|
904
|
+
* await page.route("**\/api/users", (route) => route.fulfill({ json: [{ id: 1 }] }));
|
|
905
|
+
* await page.route(/\.(png|jpg)$/, (route) => route.abort());
|
|
906
|
+
*/
|
|
907
|
+
async route(url, handler) {
|
|
908
|
+
this.assertOpen();
|
|
909
|
+
await (await this.router()).route(url, handler);
|
|
910
|
+
}
|
|
911
|
+
/** Removes the routes for `url` (only the one with `handler`, when given) */
|
|
912
|
+
async unroute(url, handler) {
|
|
913
|
+
if (!this.routerPromise)
|
|
914
|
+
return;
|
|
915
|
+
await (await this.router()).unroute(url, handler);
|
|
916
|
+
}
|
|
917
|
+
async unrouteAll() {
|
|
918
|
+
if (!this.routerPromise)
|
|
919
|
+
return;
|
|
920
|
+
await (await this.router()).unrouteAll();
|
|
921
|
+
}
|
|
922
|
+
/** Errors thrown by route handlers so far */
|
|
923
|
+
routeErrors() {
|
|
924
|
+
return this.loadedRouter?.errors ?? [];
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* Starts collecting the page's console output and uncaught exceptions. The browser does this when it opens a page so
|
|
928
|
+
* early output is kept; `page.on("console" | "pageerror")` starts it when needed.
|
|
929
|
+
*/
|
|
930
|
+
async startLogging() {
|
|
931
|
+
this.pageLogs ??= (async () => {
|
|
932
|
+
const logs = await PageLogs.start(this.biDiConnector, await this.tree(), this.id);
|
|
933
|
+
logs.on("console", (message) => this.pageEvents.emit("console", message));
|
|
934
|
+
logs.on("pageerror", (error) => this.pageEvents.emit("pageerror", error));
|
|
935
|
+
this.loadedLogs = logs;
|
|
936
|
+
return logs;
|
|
937
|
+
})().catch((err) => {
|
|
938
|
+
this.pageLogs = undefined;
|
|
939
|
+
throw err;
|
|
940
|
+
});
|
|
941
|
+
await this.pageLogs;
|
|
942
|
+
}
|
|
943
|
+
/** The newest console and error entries of this page (empty until logging started), oldest first */
|
|
944
|
+
getLogs() {
|
|
945
|
+
return this.loadedLogs?.entries ?? [];
|
|
946
|
+
}
|
|
947
|
+
/** Uncaught exceptions of the page since logging started or `clearLogs()` */
|
|
948
|
+
pageErrors() {
|
|
949
|
+
return this.loadedLogs?.errors ?? [];
|
|
950
|
+
}
|
|
951
|
+
/** How many entries fell out of the page's log buffer */
|
|
952
|
+
get logsDropped() {
|
|
953
|
+
return this.loadedLogs?.dropped ?? 0;
|
|
954
|
+
}
|
|
955
|
+
clearLogs() {
|
|
956
|
+
this.loadedLogs?.clear();
|
|
957
|
+
}
|
|
958
|
+
/** Resolves once everything the page logged before the call has arrived: events and replies share one ordered connection */
|
|
959
|
+
async syncLogs() {
|
|
960
|
+
await this.biDiConnector.send("session.status", {});
|
|
961
|
+
}
|
|
962
|
+
/** Tells the runner not to fail this test on uncaught page exceptions (config `logs.failOnPageError`) */
|
|
963
|
+
allowPageErrors() {
|
|
964
|
+
this.errorsAllowed = true;
|
|
965
|
+
}
|
|
966
|
+
get pageErrorsAllowed() {
|
|
967
|
+
return this.errorsAllowed;
|
|
968
|
+
}
|
|
969
|
+
/** Starts watching for dialogs; the browser does this when it opens a page, `page.on("dialog")` when needed */
|
|
970
|
+
async startDialogHandling() {
|
|
971
|
+
this.dialogHandling ??= (async () => {
|
|
972
|
+
await this.tree();
|
|
973
|
+
this.biDiConnector.onEvent("browsingContext.userPromptOpened", this.onPromptOpened);
|
|
974
|
+
this.biDiConnector.onEvent("browsingContext.userPromptClosed", this.onPromptClosed);
|
|
975
|
+
try {
|
|
976
|
+
return await this.biDiConnector.subscribe([
|
|
977
|
+
"browsingContext.userPromptOpened",
|
|
978
|
+
"browsingContext.userPromptClosed",
|
|
979
|
+
]);
|
|
980
|
+
}
|
|
981
|
+
catch (err) {
|
|
982
|
+
this.biDiConnector.offEvent("browsingContext.userPromptOpened", this.onPromptOpened);
|
|
983
|
+
this.biDiConnector.offEvent("browsingContext.userPromptClosed", this.onPromptClosed);
|
|
984
|
+
this.dialogHandling = undefined;
|
|
985
|
+
throw err;
|
|
986
|
+
}
|
|
987
|
+
})();
|
|
988
|
+
await this.dialogHandling;
|
|
989
|
+
}
|
|
990
|
+
ownsContext(context) {
|
|
991
|
+
return this.loadedTree?.isWithin(context, this.id) ?? context === this.id;
|
|
992
|
+
}
|
|
993
|
+
/** Lets the listeners answer; a dialog still open afterwards gets the default answer, so nothing hangs */
|
|
994
|
+
async dispatchDialog(dialog, params) {
|
|
995
|
+
this.openDialogs.set(params.context, dialog);
|
|
996
|
+
// rawListeners: the wrappers that make a `once` listener remove itself when called
|
|
997
|
+
const listeners = this.pageEvents.rawListeners("dialog");
|
|
998
|
+
await Promise.all(listeners.map(async (listener) => {
|
|
999
|
+
try {
|
|
1000
|
+
await listener(dialog);
|
|
1001
|
+
}
|
|
1002
|
+
catch (err) {
|
|
1003
|
+
logger.error("A dialog listener threw", { err });
|
|
1004
|
+
}
|
|
1005
|
+
}));
|
|
1006
|
+
if (dialog.handled)
|
|
1007
|
+
return;
|
|
1008
|
+
// Staying on a page is not what a test that navigates wants: leave it, dismiss everything else
|
|
1009
|
+
const accept = params.type === "beforeunload";
|
|
1010
|
+
logger.warn('Dialog "%s" was %s automatically; add page.on("dialog") to handle it', params.message, accept ? "accepted" : "dismissed");
|
|
1011
|
+
await (accept ? dialog.accept() : dialog.dismiss());
|
|
1012
|
+
}
|
|
1013
|
+
/** Captures an image of the given navigable, and returns it as a Base64-encoded string */
|
|
1014
|
+
async captureScreenshot(clip, format, origin) {
|
|
1015
|
+
const screenshot = await this.biDiConnector.send("browsingContext.captureScreenshot", {
|
|
1016
|
+
context: this.id,
|
|
1017
|
+
clip,
|
|
1018
|
+
format,
|
|
1019
|
+
origin,
|
|
1020
|
+
});
|
|
1021
|
+
// TODO: Store screenshot according to config specs
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
/** Wraps an init script as one function declaration; the argument is embedded as JSON because preload scripts take no arguments */
|
|
1025
|
+
function initScriptSource(script, arg) {
|
|
1026
|
+
if (typeof script === "string") {
|
|
1027
|
+
if (arg !== undefined) {
|
|
1028
|
+
throw new TypeError("addInitScript(): a string script does not take an argument; pass a function instead");
|
|
1029
|
+
}
|
|
1030
|
+
return `() => {\n${script}\n}`;
|
|
1031
|
+
}
|
|
1032
|
+
const declaration = toFunctionDeclaration(script);
|
|
1033
|
+
const argument = arg === undefined ? "undefined" : JSON.stringify(arg);
|
|
1034
|
+
if (argument === undefined) {
|
|
1035
|
+
throw new TypeError("addInitScript(): the argument must be JSON-serializable");
|
|
1036
|
+
}
|
|
1037
|
+
return `() => (${declaration})(${argument})`;
|
|
1038
|
+
}
|