Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
Initial commit
Pavel Feldman9ba375c06344
diff --git a/.appveyor.yml b/.appveyor.ymlnew file mode 100644index 0000000000..b7db8e7aad--- /dev/null+++ b/.appveyor.yml@@ -0,0 +1,19 @@+environment:+ matrix:+ - nodejs_version: "8.16.0"+ FLAKINESS_DASHBOARD_NAME: Appveyor Chromium (Win + node8)+ FLAKINESS_DASHBOARD_PASSWORD:+ secure: g66jP+j6C+hkXLutBV9fdxB5fRJgcQQzy93SgQzXUmcCl/RjkJwnzyHvX0xfCVnv++build: off++install:+ - ps: $env:FLAKINESS_DASHBOARD_BUILD_URL="https://ci.appveyor.com/project/aslushnikov/playwright/builds/$env:APPVEYOR_BUILD_ID/job/$env:APPVEYOR_JOB_ID"+ - ps: Install-Product node $env:nodejs_version+ - npm install+ - if "%nodejs_version%" == "8.16.0" (+ npm run lint &&+ npm run coverage &&+ npm run test-doclint &&+ npm run test-types+ )diff --git a/.ci/node10/Dockerfile.linux b/.ci/node10/Dockerfile.linuxnew file mode 100644index 0000000000..a7cf643b8d--- /dev/null+++ b/.ci/node10/Dockerfile.linux@@ -0,0 +1,17 @@+FROM node:10++RUN apt-get update && \+ apt-get -y install xvfb gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 \+ libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 \+ libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 \+ libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 \+ libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget && \+ rm -rf /var/lib/apt/lists/*++# Add user so we don't need --no-sandbox.+RUN groupadd -r pptruser && useradd -r -g pptruser -G audio,video pptruser \+ && mkdir -p /home/pptruser/Downloads \+ && chown -R pptruser:pptruser /home/pptruser++# Run everything after as non-privileged user.+USER pptruserdiff --git a/.ci/node12/Dockerfile.linux b/.ci/node12/Dockerfile.linuxnew file mode 100644index 0000000000..79f9426157--- /dev/null+++ b/.ci/node12/Dockerfile.linux@@ -0,0 +1,17 @@+FROM node:12++RUN apt-get update && \+ apt-get -y install xvfb gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 \+ libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 \+ libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 \+ libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 \+ libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget && \+ rm -rf /var/lib/apt/lists/*++# Add user so we don't need --no-sandbox.+RUN groupadd -r pptruser && useradd -r -g pptruser -G audio,video pptruser \+ && mkdir -p /home/pptruser/Downloads \+ && chown -R pptruser:pptruser /home/pptruser++# Run everything after as non-privileged user.+USER pptruserdiff --git a/.ci/node8/Dockerfile.linux b/.ci/node8/Dockerfile.linuxnew file mode 100644index 0000000000..26f1197984--- /dev/null+++ b/.ci/node8/Dockerfile.linux@@ -0,0 +1,17 @@+FROM node:8.11.3++RUN apt-get update && \+ apt-get -y install xvfb gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 \+ libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 \+ libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 \+ libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 \+ libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget && \+ rm -rf /var/lib/apt/lists/*++# Add user so we don't need --no-sandbox.+RUN groupadd -r pptruser && useradd -r -g pptruser -G audio,video pptruser \+ && mkdir -p /home/pptruser/Downloads \+ && chown -R pptruser:pptruser /home/pptruser++# Run everything after as non-privileged user.+USER pptruserdiff --git a/.cirrus.yml b/.cirrus.ymlnew file mode 100644index 0000000000..41ac3430a9--- /dev/null+++ b/.cirrus.yml@@ -0,0 +1,47 @@+env:+ DISPLAY: :99.0+ FLAKINESS_DASHBOARD_PASSWORD: ENCRYPTED[b3e207db5d153b543f219d3c3b9123d8321834b783b9e45ac7d380e026ab3a56398bde51b521ac5859e7e45cb95d0992]+ FLAKINESS_DASHBOARD_NAME: Cirrus ${CIRRUS_TASK_NAME}+ FLAKINESS_DASHBOARD_BUILD_URL: https://cirrus-ci.com/task/${CIRRUS_TASK_ID}++task:+ matrix:+ - name: Chromium (node8 + linux)+ container:+ dockerfile: .ci/node8/Dockerfile.linux+ - name: Chromium (node10 + linux)+ container:+ dockerfile: .ci/node10/Dockerfile.linux+ - name: Chromium (node12 + linux)+ container:+ dockerfile: .ci/node12/Dockerfile.linux+ xvfb_start_background_script: Xvfb :99 -ac -screen 0 1024x768x24+ install_script: npm install --unsafe-perm+ lint_script: npm run lint+ coverage_script: npm run coverage+ test_doclint_script: npm run test-doclint+ test_types_script: npm run test-types++task:+ matrix:+ - name: Firefox (node8 + linux)+ container:+ dockerfile: .ci/node8/Dockerfile.linux+ xvfb_start_background_script: Xvfb :99 -ac -screen 0 1024x768x24+ install_script: npm install --unsafe-perm+ test_script: npm run funit++task:+ osx_instance:+ image: high-sierra-base+ name: Chromium (node8 + macOS)+ env:+ HOMEBREW_NO_AUTO_UPDATE: 1+ node_install_script:+ - brew install node@8+ - brew link --force node@8+ install_script: npm install --unsafe-perm+ lint_script: npm run lint+ coverage_script: npm run coverage+ test_doclint_script: npm run test-doclint+ test_types_script: npm run test-typesdiff --git a/.editorconfig b/.editorconfignew file mode 100644index 0000000000..c6c8b36219--- /dev/null+++ b/.editorconfig@@ -0,0 +1,9 @@+root = true++[*]+indent_style = space+indent_size = 2+end_of_line = lf+charset = utf-8+trim_trailing_whitespace = true+insert_final_newline = truediff --git a/.eslintignore b/.eslintignorenew file mode 100644index 0000000000..28f6fcb632--- /dev/null+++ b/.eslintignore@@ -0,0 +1,12 @@+test/assets/modernizr.js+third_party/*+utils/browser/playwright-web.js+utils/doclint/check_public_api/test/+utils/testrunner/examples/+node6/*+node6-test/*+node6-testrunner/*+lib/+*.js+src/chromium/protocol.d.ts+src/webkit/protocol.d.ts\ No newline at end of filediff --git a/.eslintrc.js b/.eslintrc.jsnew file mode 100644index 0000000000..ab34834e10--- /dev/null+++ b/.eslintrc.js@@ -0,0 +1,107 @@+module.exports = {+ parser: '@typescript-eslint/parser',+ plugins: ['@typescript-eslint'],+ parserOptions: {+ project: './tsconfig.json',+ ecmaVersion: 9,+ sourceType: 'module',+ },++ /**+ * ESLint rules+ *+ * All available rules: http://eslint.org/docs/rules/+ *+ * Rules take the following form:+ * "rule-name", [severity, { opts }]+ * Severity: 2 == error, 1 == warning, 0 == off.+ */+ "rules": {+ '@typescript-eslint/no-unused-vars': [2, {args: 'none'}],+ /**+ * Enforced rules+ */+ // syntax preferences+ "quotes": [2, "single", {+ "avoidEscape": true,+ "allowTemplateLiterals": true+ }],+ "semi": 2,+ "no-extra-semi": 2,+ "comma-style": [2, "last"],+ "wrap-iife": [2, "inside"],+ "spaced-comment": [2, "always", {+ "markers": ["*"]+ }],+ "eqeqeq": [2],+ "arrow-body-style": [2, "as-needed"],+ "accessor-pairs": [2, {+ "getWithoutSet": false,+ "setWithoutGet": false+ }],+ "brace-style": [2, "1tbs", {"allowSingleLine": true}],+ "curly": [2, "multi-or-nest", "consistent"],+ "new-parens": 2,+ "func-call-spacing": 2,+ "arrow-parens": [2, "as-needed"],+ "prefer-const": 2,+ "quote-props": [2, "consistent"],++ // anti-patterns+ "no-var": 2,+ "no-with": 2,+ "no-multi-str": 2,+ "no-caller": 2,+ "no-implied-eval": 2,+ "no-labels": 2,+ "no-new-object": 2,+ "no-octal-escape": 2,+ "no-self-compare": 2,+ "no-shadow-restricted-names": 2,+ "no-cond-assign": 2,+ "no-debugger": 2,+ "no-dupe-keys": 2,+ "no-duplicate-case": 2,+ "no-empty-character-class": 2,+ "no-unreachable": 2,+ "no-unsafe-negation": 2,+ "radix": 2,+ "valid-typeof": 2,+ "no-implicit-globals": [2],++ // es2015 features+ "require-yield": 2,+ "template-curly-spacing": [2, "never"],++ // spacing details+ "space-infix-ops": 2,+ "space-in-parens": [2, "never"],+ "space-before-function-paren": [2, "never"],+ "no-whitespace-before-property": 2,+ "keyword-spacing": [2, {+ "overrides": {+ "if": {"after": true},+ "else": {"after": true},+ "for": {"after": true},+ "while": {"after": true},+ "do": {"after": true},+ "switch": {"after": true},+ "return": {"after": true}+ }+ }],+ "arrow-spacing": [2, {+ "after": true,+ "before": true+ }],++ // file whitespace+ "no-multiple-empty-lines": [2, {"max": 2}],+ "no-mixed-spaces-and-tabs": 2,+ "no-trailing-spaces": 2,+ "linebreak-style": [ process.platform === "win32" ? 0 : 2, "unix" ],+ "indent": [2, 2, { "SwitchCase": 1, "CallExpression": {"arguments": 2}, "MemberExpression": 2 }],+ "key-spacing": [2, {+ "beforeColon": false+ }]+ }+};diff --git a/.gitignore b/.gitignoreindex ad46b30886..8d2eb40ef6 100644--- a/.gitignore+++ b/.gitignore@@ -1,61 +1,20 @@-# Logs-logs-*.log-npm-debug.log*-yarn-debug.log*-yarn-error.log*--# Runtime data-pids-*.pid-*.seed-*.pid.lock--# Directory for instrumented libs generated by jscoverage/JSCover-lib-cov--# Coverage directory used by tools like istanbul-coverage--# nyc test coverage-.nyc_output--# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)-.grunt--# Bower dependency directory (https://bower.io/)-bower_components--# node-waf configuration-.lock-wscript--# Compiled binary addons (https://nodejs.org/api/addons.html)-build/Release--# Dependency directories-node_modules/-jspm_packages/--# TypeScript v1 declaration files-typings/--# Optional npm cache directory-.npm--# Optional eslint cache-.eslintcache--# Optional REPL history-.node_repl_history--# Output of 'npm pack'-*.tgz--# Yarn Integrity file-.yarn-integrity--# dotenv environment variables file-.env--# next.js build output-.next+/node_modules/+/test/output-chromium+/test/output-firefox+/test/test-user-data-dir*+/.local-chromium/+/.local-browser/+/.local-webkit/+/.dev_profile*+.DS_Store+*.swp+*.pyc+.vscode+package-lock.json+yarn.lock+/node6+/src/chromium/protocol.d.ts+/src/webkit/protocol.d.ts+/utils/browser/playwright-web.js+/index.d.ts+lib/diff --git a/.npmignore b/.npmignorenew file mode 100644index 0000000000..71a68fec8e--- /dev/null+++ b/.npmignore@@ -0,0 +1,44 @@+.appveyor.yml+.gitattributes++# no longer generated, but old checkouts might still have it+node6++# exclude all tests+test+utils/node6-transform++# exclude source files+src++# repeats from .gitignore+node_modules+.local-chromium+.local-browser+.dev_profile*+.DS_Store+*.swp+*.pyc+.vscode+package-lock.json+/node6/test+/node6/utils+/test+/utils+/docs+yarn.lock++# other+/.ci+/examples+.appveyour.yml+.cirrus.yml+.editorconfig+.eslintignore+.eslintrc.js+.travis.yml+README.md+tsconfig.json++# exclude types, see https://github.com/GoogleChrome/puppeteer/issues/3878+/index.d.tsdiff --git a/.travis.yml b/.travis.ymlnew file mode 100644index 0000000000..3cd30ce746--- /dev/null+++ b/.travis.yml@@ -0,0 +1,48 @@+language: node_js+dist: trusty+addons:+ apt:+ packages:+ # This is required to run new chrome on old trusty+ - libnss3+notifications:+ email: false+cache:+ directories:+ - node_modules+# allow headful tests+before_install:+ - "sysctl kernel.unprivileged_userns_clone=1"+ - "export DISPLAY=:99.0"+ - "sh -e /etc/init.d/xvfb start"+script:+ - 'if [ "$NODE8" = "true" ]; then npm run lint; fi'+ - 'if [ "$NODE8" = "true" ]; then npm run coverage; fi'+ - 'if [ "$FIREFOX" = "true" ]; then npm run funit; fi'+ - 'if [ "$NODE8" = "true" ]; then npm run test-doclint; fi'+ - 'if [ "$NODE8" = "true" ]; then npm run test-types; fi'+ - 'if [ "$NODE8" = "true" ]; then npm run bundle; fi'+ - 'if [ "$NODE8" = "true" ]; then npm run unit-bundle; fi'+jobs:+ include:+ - node_js: "8.16.0"+ env:+ - NODE8=true+ - FLAKINESS_DASHBOARD_NAME="Travis Chromium (node8 + linux)"+ - FLAKINESS_DASHBOARD_BUILD_URL="${TRAVIS_JOB_WEB_URL}"+ - node_js: "8.16.0"+ env:+ - FIREFOX=true+ - FLAKINESS_DASHBOARD_NAME="Travis Firefox (node8 + linux)"+ - FLAKINESS_DASHBOARD_BUILD_URL="${TRAVIS_JOB_WEB_URL}"+before_deploy: "npm run apply-next-version"+deploy:+ provider: npm+ email: [email protected]+ api_key:+ secure: Ng8o2KwJf90XCBNgUKK3jRZnwtdBSJatjYNmZBERJEqBWFTadFAp1NdhxZaqjnuG8aFYaH5bRJdL+EQBYUksVCbrv/gcaXeEFkwsfPfVX1QXGqu7NnZmtme2hbxppLQ7dEJ8hz2Z9K4vehqVOxmLabxvoupOumxEQMLCphVHh2FOmsm/S5JrRZqZ4V9k76eIc0/PiyfXNMdx5WTZjHbIRDIHRy9nqOXjFp2Rx3PMa3uU2fS8mTshYEYs151TA6e6VdHjqmBwEQC/M5tXbDlLCMNUr4JBtLTcL4OipNYjzkwD1N2xYlbSRqtvqqF4ifdvFhoI65a31GinlMC7Z/SH1Zy+d+/z3Mo7D63eYcsJVnsg9OYxTFy2piUntr0JqTBHtQoe/CvGxJmkcVt+H6YSkcBibSG9s9tG3qpAD5wBCFqqOYnfClX+YZziEd+Hngd9inxAf87qdvgVIZ5tPD2dygtE+te2/qoEHtvccv/HuS8MxNj5iKwlP7JaBPM6uAkazYqZP2R99I2ph9gNOEVuQLtk+3+OIdb8HWrEKUrJBgKhdKY1dvcKYElI+D8NRlyzrr6BnZfudACuAt2EtfKpfJ3mL+iRMFdBJ3ntLt93xBrB+j4z3pD0iWZcg1g3I742PFzQEHzyd/DDTP1yRTUoJeQWwoQRJyNO1m6Qk4wx77c=+ on:+ branch: master+ condition: "$NODE8 = true"+ skip_cleanup: true+ tag: nextdiff --git a/DeviceDescriptors.js b/DeviceDescriptors.jsnew file mode 100644index 0000000000..b5f92b43ea--- /dev/null+++ b/DeviceDescriptors.js@@ -0,0 +1,23 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {DeviceDescriptors} = require('./lib/DeviceDescriptors');++const descriptors = DeviceDescriptors.slice();+module.exports = descriptors;+for (const device of descriptors)+ module.exports[device.name] = device;diff --git a/Errors.js b/Errors.jsnew file mode 100644index 0000000000..4779e1d850--- /dev/null+++ b/Errors.js@@ -0,0 +1,17 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports = require('./lib/Errors');diff --git a/browser_patches/README.md b/browser_patches/README.mdnew file mode 100644index 0000000000..51c7554d68--- /dev/null+++ b/browser_patches/README.md@@ -0,0 +1,31 @@+# Compiling and Uploading Builds++### 1. Getting code++```sh+$ ./checkout.sh firefox/ # or ./checkout.sh webkit/+```++This command will create a `./firefox/checkout` folder that contains firefox GIT checkout.+Checkout current branch will be set to `pwdev` and it will have all additional changes+applied to the browser atop of the `./firefox/BASE_REVISION` version.++### 2. Compiling++> **NOTE** You might need to prepare your host environment according to browser build instructions:+> - [firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Build_Instructions)+> - [webkit](https://webkit.org/building-webkit/)++```sh+$ ./firefox/build.sh # or ./webkit/build.sh+```++### 3. Uploading builds to Azure CDN++> **NOTE** You should have `$AZ_ACCOUNT_KEY` and `$AZ_ACCOUNT_NAME` variables set in your environment.++```sh+$ ./upload.sh firefox/ # or ./upload.sh webkit/+```++This will package archives and upload builds to Azure CDN.diff --git a/browser_patches/check_cdn.sh b/browser_patches/check_cdn.shnew file mode 100755index 0000000000..9b9407589c--- /dev/null+++ b/browser_patches/check_cdn.sh@@ -0,0 +1,58 @@+#!/bin/bash+set -e+set +x++HOST="https://playwrightaccount.blob.core.windows.net/builds"+ARCHIVES=(+ "$HOST/firefox/%s/firefox-mac.zip"+ "$HOST/firefox/%s/firefox-linux.zip"+ "$HOST/firefox/%s/firefox-win.zip"+ "$HOST/webkit/%s/minibrowser-linux.zip"+ "$HOST/webkit/%s/minibrowser-mac10.14.zip"+ "$HOST/webkit/%s/minibrowser-mac10.15.zip"+)++ALIASES=(+ "FF-MAC"+ "FF-LINUX"+ "FF-WIN"+ "WK-MAC-10.14"+ "WK-MAC-10.15"+ "WK-LINUX"+)+COLUMN="%-15s"++# COLORS+RED=$'\e[1;31m'+GRN=$'\e[1;32m'+YEL=$'\e[1;33m'+END=$'\e[0m'++# Read start revision if there's any.+REVISION=$(git rev-parse HEAD)+if [[ $# == 1 ]]; then+ if ! git rev-parse $1; then+ echo "ERROR: there is no $REVISION in this repo - pull from upstream?"+ exit 1+ fi+ REVISION=$(git rev-parse $1)+fi++printf "%12s" ""+for i in "${ALIASES[@]}"; do+ printf $COLUMN $i+done+printf "\n"+while true; do+ printf "%-12s" ${REVISION:0:10}+ for i in "${ARCHIVES[@]}"; do+ URL=$(printf $i $REVISION)+ if [[ $(curl -s -L -I $URL | head -1 | cut -f2 -d' ') == 200 ]]; then+ printf ${GRN}$COLUMN${END} "YES"+ else+ printf ${RED}$COLUMN${END} "NO"+ fi+ done;+ echo+ REVISION=$(git rev-parse $REVISION^)+done;diff --git a/browser_patches/do_checkout.sh b/browser_patches/do_checkout.shnew file mode 100755index 0000000000..b83bd9b11d--- /dev/null+++ b/browser_patches/do_checkout.sh@@ -0,0 +1,136 @@+#!/bin/bash+set -e+set +x++function cleanup() {+ cd $OLD_DIR+}++OLD_DIR=$(pwd -P)+cd "$(dirname "$0")"+trap cleanup EXIT++if [[ ($1 == '--help') || ($1 == '-h') ]]; then+ echo "usage: do_something.sh [firefox|webkit]"+ echo+ echo "Produces a browser checkout ready to be built."+ echo+ exit 0+fi++if [[ $# == 0 ]]; then+ echo "missing browser: 'firefox' or 'webkit'"+ echo "try './do_something.sh --help' for more information"+ exit 1+fi++# FRIENDLY_CHECKOUT_PATH is used only for logging.+FRIENDLY_CHECKOUT_PATH="";+CHECKOUT_PATH=""+# Export path is where we put the patches and BASE_REVISION+REMOTE_URL=""+BASE_BRANCH=""+if [[ ("$1" == "firefox") || ("$1" == "firefox/") ]]; then+ # we always apply our patches atop of beta since it seems to get better+ # reliability guarantees.+ BASE_BRANCH="beta"+ FRIENDLY_CHECKOUT_PATH="//browser_patches/firefox/checkout";+ CHECKOUT_PATH="$PWD/firefox/checkout"+ REMOTE_URL="https://github.com/mozilla/gecko-dev"+elif [[ ("$1" == "webkit") || ("$1" == "webkit/") ]]; then+ # webkit has only a master branch.+ BASE_BRANCH="master"+ FRIENDLY_CHECKOUT_PATH="//browser_patches/webkit/checkout";+ CHECKOUT_PATH="$PWD/webkit/checkout"+ REMOTE_URL=""+ REMOTE_URL="https://github.com/webkit/webkit"+else+ echo ERROR: unknown browser to export - "$1"+ exit 1+fi++# if there's no checkout folder - checkout one.+if ! [[ -d $CHECKOUT_PATH ]]; then+ echo "-- $FRIENDLY_CHECKOUT_PATH is missing - checking out.."+ git clone --single-branch --branch $BASE_BRANCH $REMOTE_URL $CHECKOUT_PATH+else+ echo "-- checking $FRIENDLY_CHECKOUT_PATH folder - OK"+fi++# if folder exists but not a git repository - bail out.+if ! [[ -d $CHECKOUT_PATH/.git ]]; then+ echo "ERROR: $FRIENDLY_CHECKOUT_PATH is not a git repository! Remove it and re-run the script."+ exit 1+else+ echo "-- checking $FRIENDLY_CHECKOUT_PATH is a git repo - OK"+fi++# Switch to git repository.+cd $CHECKOUT_PATH++# Check if git repo is dirty.+if [[ -n $(git status -s) ]]; then+ echo "ERROR: $FRIENDLY_CHECKOUT_PATH has dirty GIT state - commit everything and re-run the script."+ exit 1+fi++if [[ $(git config --get remote.origin.url) == "$REMOTE_URL" ]]; then+ echo "-- checking git origin url to point to $REMOTE_URL - OK";+else+ echo "ERROR: git origin url DOES NOT point to $REMOTE_URL. Remove $FRIENDLY_CHECKOUT_PATH and re-run the script.";+ exit 1+fi++# if there's no "BASE_BRANCH" branch - bail out.+if ! git show-ref --verify --quiet refs/heads/$BASE_BRANCH; then+ echo "ERROR: $FRIENDLY_CHECKOUT_PATH/ does not have '$BASE_BRANCH' branch! Remove checkout/ and re-run the script."+ exit 1+else+ echo "-- checking $FRIENDLY_CHECKOUT_PATH has 'beta' branch - OK"+fi++if ! [[ -z $(git log --oneline origin/$BASE_BRANCH..$BASE_BRANCH) ]]; then+ echo "ERROR: branch '$BASE_BRANCH' and branch 'origin/$BASE_BRANCH' have diverged - bailing out. Remove checkout/ and re-run the script."+ exit 1;+else+ echo "-- checking that $BASE_BRANCH and origin/$BASE_BRANCH are not diverged - OK"+fi++git checkout $BASE_BRANCH+git pull origin $BASE_BRANCH++PINNED_COMMIT=$(cat ../BASE_REVISION)+if ! git cat-file -e $PINNED_COMMIT^{commit}; then+ echo "ERROR: $FRIENDLY_CHECKOUT_PATH/ does not include the BASE_REVISION (@$PINNED_COMMIT). Remove checkout/ and re-run the script."+ exit 1+else+ echo "-- checking $FRIENDLY_CHECKOUT_PATH repo has BASE_REVISION (@$PINNED_COMMIT) commit - OK"+fi++# If there's already a PWDEV branch than we should check if it's fine to reset all changes+# to it.+if git show-ref --verify --quiet refs/heads/pwdev; then+ read -p "Do you want to reset 'PWDEV' branch? (ALL CHANGES WILL BE LOST) Y/n " -n 1 -r+ echo+ # if it's not fine to reset branch - bail out.+ if ! [[ $REPLY =~ ^[Yy]$ ]]; then+ echo "If you want to keep the branch, than I can't do much! Bailing out!"+ exit 1+ else+ git checkout pwdev+ git reset --hard $PINNED_COMMIT+ echo "-- PWDEV now points to BASE_REVISION (@$PINNED_COMMIT)"+ fi+else+ # Otherwise just create a new branch.+ git checkout -b pwdev+ git reset --hard $PINNED_COMMIT+ echo "-- created 'pwdev' branch that points to BASE_REVISION (@$PINNED_COMMIT)."+fi++echo "-- applying all patches"+git am ../patches/*++echo+echo+echo "DONE. Browser is ready to be built."diff --git a/browser_patches/export.sh b/browser_patches/export.shnew file mode 100755index 0000000000..b6384e79f1--- /dev/null+++ b/browser_patches/export.sh@@ -0,0 +1,115 @@+#!/bin/bash+set -e+set +x++cleanup() {+ cd $OLD_DIR+}++OLD_DIR=$(pwd -P)+cd "$(dirname "$0")"+trap cleanup EXIT++if [[ ($1 == '--help') || ($1 == '-h') ]]; then+ echo "usage: export.sh [firefox|webkit] [custom_checkout_path]"+ echo+ echo "Exports BASE_REVISION and patch from the checkout to browser folder."+ echo+ echo "You can optionally specify custom_checkout_path if you have browser checkout somewhere else"+ echo "and wish to export patches from it."+ echo+ exit 0+fi++if [[ $# == 0 ]]; then+ echo "missing browser: 'firefox' or 'webkit'"+ echo "try './export.sh --help' for more information"+ exit 1+fi++# FRIENDLY_CHECKOUT_PATH is used only for logging.+FRIENDLY_CHECKOUT_PATH="";+CHECKOUT_PATH=""+# Export path is where we put the patches and BASE_REVISION+EXPORT_PATH=""+BASE_BRANCH=""+if [[ ("$1" == "firefox") || ("$1" == "firefox/") ]]; then+ # we always apply our patches atop of beta since it seems to get better+ # reliability guarantees.+ BASE_BRANCH="origin/beta"+ FRIENDLY_CHECKOUT_PATH="//browser_patches/firefox/checkout";+ CHECKOUT_PATH="$PWD/firefox/checkout"+ EXPORT_PATH="$PWD/firefox/"+elif [[ ("$1" == "webkit") || ("$1" == "webkit/") ]]; then+ # webkit has only a master branch.+ BASE_BRANCH="origin/master"+ FRIENDLY_CHECKOUT_PATH="//browser_patches/webkit/checkout";+ CHECKOUT_PATH="$PWD/webkit/checkout"+ EXPORT_PATH="$PWD/webkit/"+else+ echo ERROR: unknown browser to export - "$1"+ exit 1+fi++# we will use this just for beauty.+if [[ $# == 2 ]]; then+ echo "WARNING: using custom checkout path $CHECKOUT_PATH"+ CHECKOUT_PATH=$2+ FRIENDLY_CHECKOUT_PATH="<custom_checkout>"+fi++# if there's no checkout folder - bail out.+if ! [[ -d $CHECKOUT_PATH ]]; then+ echo "ERROR: $FRIENDLY_CHECKOUT_PATH is missing - nothing to export."+ exit 1;+else+ echo "-- checking $FRIENDLY_CHECKOUT_PATH exists - OK"+fi++# if folder exists but not a git repository - bail out.+if ! [[ -d $CHECKOUT_PATH/.git ]]; then+ echo "ERROR: $FRIENDLY_CHECKOUT_PATH is not a git repository! Nothing to export."+ exit 1+else+ echo "-- checking $FRIENDLY_CHECKOUT_PATH is a git repo - OK"+fi++# Switch to git repository.+cd $CHECKOUT_PATH++# Check if git repo is dirty.+if [[ -n $(git status -s) ]]; then+ echo "ERROR: $FRIENDLY_CHECKOUT_PATH has dirty GIT state - aborting export."+ exit 1+else+ echo "-- checking $FRIENDLY_CHECKOUT_PATH is clean - OK"+fi++CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)+MERGE_BASE=$(git merge-base $BASE_BRANCH $CURRENT_BRANCH)+echo "=============================================================="+echo " Repository: $FRIENDLY_CHECKOUT_PATH"+echo " Changes between branches: $BASE_BRANCH..$CURRENT_BRANCH"+echo " BASE_REVISION: $MERGE_BASE"+echo+read -p "Export? Y/n " -n 1 -r+echo+# if it's not fine to reset branch - bail out.+if ! [[ $REPLY =~ ^[Yy]$ ]]; then+ echo "Exiting."+ exit 1+fi++echo $MERGE_BASE > $EXPORT_PATH/BASE_REVISION+git checkout -b tmpsquash_export_script $MERGE_BASE+git merge --squash $CURRENT_BRANCH+git commit -am "chore: bootstrap"+PATCH_NAME=$(git format-patch -1 HEAD)+mv $PATCH_NAME $EXPORT_PATH/patches/+git checkout $CURRENT_BRANCH+git branch -D tmpsquash_export_script++# Increment BUILD_NUMBER+BUILD_NUMBER=$(cat $EXPORT_PATH/BUILD_NUMBER)+BUILD_NUMBER=$((BUILD_NUMBER+1))+echo $BUILD_NUMBER > $EXPORT_PATH/BUILD_NUMBERdiff --git a/browser_patches/firefox/.gitignore b/browser_patches/firefox/.gitignorenew file mode 100644index 0000000000..5e660dc18e--- /dev/null+++ b/browser_patches/firefox/.gitignore@@ -0,0 +1 @@+/checkoutdiff --git a/browser_patches/firefox/BASE_REVISION b/browser_patches/firefox/BASE_REVISIONnew file mode 100644index 0000000000..37eb8e8658--- /dev/null+++ b/browser_patches/firefox/BASE_REVISION@@ -0,0 +1 @@+46ca28eadfe840021e2ea496fa6b26f924fa135bdiff --git a/browser_patches/firefox/BUILD_NUMBER b/browser_patches/firefox/BUILD_NUMBERnew file mode 100644index 0000000000..d474e1b4d6--- /dev/null+++ b/browser_patches/firefox/BUILD_NUMBER@@ -0,0 +1,2 @@+1+diff --git a/browser_patches/firefox/README.md b/browser_patches/firefox/README.mdnew file mode 100644index 0000000000..e3368007ed--- /dev/null+++ b/browser_patches/firefox/README.md@@ -0,0 +1,22 @@+# Building Juggler (Linux & Mac)++1. Run `./do_checkout.sh` script. This will create a "checkout" folder with gecko-dev mirror from+GitHub and apply the PlayWright-specific patches.+2. Run `./do_build.sh` script to compile browser. Note: you'll need to follow [build instructions](https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Build_Instructions) to setup host environment first.++# Updating `FIREFOX_REVISION` and `//patches/*`++The `./export.sh` script will export a patch that describes all the differences between the current branch in `./checkout`+and the `beta` branch in `./checkout`.++# Uploading to Azure CDN++Uploading requires having both `AZ_ACCOUNT_KEY` and `AZ_ACCOUNT_NAME` env variables to be defined.++The following sequence of steps will checkout, build and upload build to Azure CDN on both Linux and Mac:++```sh+$ ./do_checkout.sh+$ ./build.sh+$ ./upload.sh+```diff --git a/browser_patches/firefox/archive.sh b/browser_patches/firefox/archive.shnew file mode 100755index 0000000000..42e75711da--- /dev/null+++ b/browser_patches/firefox/archive.sh@@ -0,0 +1,53 @@+#!/bin/bash++if [[ ("$1" == "-h") || ("$1" == "--help") ]]; then+ echo "usage: $0"+ echo+ echo "Generate distributable .zip archive from ./checkout folder that was previously built."+ echo+ exit 0+fi++set -e+set -x++createZIPForLinuxOrMac() {+ cd checkout+ local zipname=$1+ local OBJ_FOLDER=$(ls -1 | grep obj-)+ if [[ $OBJ_FOLDER == "" ]]; then+ echo "ERROR: cannot find obj-* folder in the checkout/. Did you build?"+ exit 1;+ fi+ if ! [[ -d $OBJ_FOLDER/dist/firefox ]]; then+ echo "ERROR: cannot find $OBJ_FOLDER/dist/firefox folder in the checkout/. Did you build?"+ exit 1;+ fi+ # Copy the libstdc++ version we linked against.+ # TODO(aslushnikov): this won't be needed with official builds.+ if [[ "$(uname)" == "Linux" ]]; then+ cp /usr/lib/x86_64-linux-gnu/libstdc++.so.6 $OBJ_FOLDER/dist/firefox/libstdc++.so.6+ fi++ # tar resulting directory and cleanup TMP.+ cd $OBJ_FOLDER/dist+ zip -r ../../../$zipname firefox+ cd -+}++cleanup() {+ cd $OLD_DIR+}++OLD_DIR=$(pwd -P)+cd "$(dirname "$0")"+trap cleanup EXIT++if [[ "$(uname)" == "Darwin" ]]; then+ createZIPForLinuxOrMac "firefox-mac.zip"+elif [[ "$(uname)" == "Linux" ]]; then+ createZIPForLinuxOrMac "firefox-linux.zip"+else+ echo "ERROR: cannot upload on this platform!" 1>&2+ exit 1;+fidiff --git a/browser_patches/firefox/build.sh b/browser_patches/firefox/build.shnew file mode 100755index 0000000000..1870546b1b--- /dev/null+++ b/browser_patches/firefox/build.sh@@ -0,0 +1,45 @@+#!/bin/bash+set -e+set +x++function cleanup() {+ cd $OLD_DIR+}++OLD_DIR=$(pwd -P)+cd "$(dirname "$0")"+trap cleanup EXIT++cd checkout++if ! [[ $(git rev-parse --abbrev-ref HEAD) == "pwdev" ]]; then+ echo "ERROR: Cannot build any branch other than PWDEV"+ exit 1;+else+ echo "-- checking git branch is PWDEV - OK"+fi++if [[ "$(uname)" == "Darwin" ]]; then+ # Firefox currently does not build on 10.15 out of the box - it requires SDK for 10.14.+ # Make sure the SDK is out there.+ if [[ $(sw_vers -productVersion) == "10.15" ]]; then+ if ! [[ -d $HOME/SDK-archive/MacOSX10.14.sdk ]]; then+ echo "As of Nov 2019, Firefox does not build on Mac 10.15 without 10.14 SDK."+ echo "Check out instructions on getting 10.14 sdk at https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Build_Instructions/Mac_OS_X_Prerequisites"+ echo "and make sure to put SDK to $HOME/SDK-archive/MacOSX10.14.sdk/"+ exit 1+ else+ echo "-- configuting .mozconfig with 10.14 SDK path"+ echo "ac_add_options --with-macos-sdk=$HOME/SDK-archive/MacOSX10.14.sdk/" > .mozconfig+ fi+ fi+ echo "-- building on Mac"+elif [[ "$(uname)" == "Linux" ]]; then+ echo "-- building on Linux"+else+ echo "ERROR: cannot upload on this platform!" 1>&2+ exit 1;+fi++./mach build+./mach packagediff --git a/browser_patches/firefox/patches/0001-chore-bootstrap.patch b/browser_patches/firefox/patches/0001-chore-bootstrap.patchnew file mode 100644index 0000000000..2e1f1298b4--- /dev/null+++ b/browser_patches/firefox/patches/0001-chore-bootstrap.patch@@ -0,0 +1,4895 @@+From db891a78ac18605d1fb4c6c4a260c1e16340789c Mon Sep 17 00:00:00 2001+From: Andrey Lushnikov <[email protected]>+Date: Fri, 15 Nov 2019 18:10:56 -0800+Subject: [PATCH] chore: bootstrap++---+ browser/installer/allowed-dupes.mn | 5 ++ browser/installer/package-manifest.in | 5 ++ docshell/base/nsDocShell.cpp | 1 ++ dom/ipc/BrowserChild.cpp | 7 ++ .../permissions/nsPermissionManager.cpp | 8 +-+ .../manager/ssl/nsCertOverrideService.cpp | 2 +-+ testing/juggler/BrowserContextManager.js | 194 ++++++ testing/juggler/Helper.js | 101 ++++ testing/juggler/NetworkObserver.js | 450 +++++++++++++ testing/juggler/TargetRegistry.js | 187 ++++++ testing/juggler/components/juggler.js | 112 ++++ testing/juggler/components/juggler.manifest | 3 ++ testing/juggler/components/moz.build | 9 ++ testing/juggler/content/ContentSession.js | 63 +++ testing/juggler/content/FrameTree.js | 232 +++++++ testing/juggler/content/NetworkMonitor.js | 62 +++ testing/juggler/content/PageAgent.js | 621 +++++++++++++++++ testing/juggler/content/RuntimeAgent.js | 460 +++++++++++++ testing/juggler/content/ScrollbarManager.js | 85 ++++ .../juggler/content/floating-scrollbars.css | 47 +++ testing/juggler/content/hidden-scrollbars.css | 13 ++ testing/juggler/content/main.js | 39 +++ testing/juggler/jar.mn | 29 ++ testing/juggler/moz.build | 15 ++ .../juggler/protocol/AccessibilityHandler.js | 15 ++ testing/juggler/protocol/BrowserHandler.js | 66 +++ testing/juggler/protocol/Dispatcher.js | 255 ++++++++ testing/juggler/protocol/NetworkHandler.js | 154 +++++ testing/juggler/protocol/PageHandler.js | 269 ++++++++ testing/juggler/protocol/PrimitiveTypes.js | 143 +++++ testing/juggler/protocol/Protocol.js | 660 +++++++++++++++++++ testing/juggler/protocol/RuntimeHandler.js | 41 +++ testing/juggler/protocol/TargetHandler.js | 75 +++ .../statusfilter/nsBrowserStatusFilter.cpp | 12 +-+ toolkit/toolkit.mozbuild | 1 ++ uriloader/base/nsDocLoader.cpp | 18 ++ uriloader/base/nsDocLoader.h | 5 ++ uriloader/base/nsIWebProgress.idl | 7 +-+ uriloader/base/nsIWebProgressListener2.idl | 23 ++ 39 files changed, 4487 insertions(+), 7 deletions(-)+ create mode 100644 testing/juggler/BrowserContextManager.js+ create mode 100644 testing/juggler/Helper.js+ create mode 100644 testing/juggler/NetworkObserver.js+ create mode 100644 testing/juggler/TargetRegistry.js+ create mode 100644 testing/juggler/components/juggler.js+ create mode 100644 testing/juggler/components/juggler.manifest+ create mode 100644 testing/juggler/components/moz.build+ create mode 100644 testing/juggler/content/ContentSession.js+ create mode 100644 testing/juggler/content/FrameTree.js+ create mode 100644 testing/juggler/content/NetworkMonitor.js+ create mode 100644 testing/juggler/content/PageAgent.js+ create mode 100644 testing/juggler/content/RuntimeAgent.js+ create mode 100644 testing/juggler/content/ScrollbarManager.js+ create mode 100644 testing/juggler/content/floating-scrollbars.css+ create mode 100644 testing/juggler/content/hidden-scrollbars.css+ create mode 100644 testing/juggler/content/main.js+ create mode 100644 testing/juggler/jar.mn+ create mode 100644 testing/juggler/moz.build+ create mode 100644 testing/juggler/protocol/AccessibilityHandler.js+ create mode 100644 testing/juggler/protocol/BrowserHandler.js+ create mode 100644 testing/juggler/protocol/Dispatcher.js+ create mode 100644 testing/juggler/protocol/NetworkHandler.js+ create mode 100644 testing/juggler/protocol/PageHandler.js+ create mode 100644 testing/juggler/protocol/PrimitiveTypes.js+ create mode 100644 testing/juggler/protocol/Protocol.js+ create mode 100644 testing/juggler/protocol/RuntimeHandler.js+ create mode 100644 testing/juggler/protocol/TargetHandler.js++diff --git a/browser/installer/allowed-dupes.mn b/browser/installer/allowed-dupes.mn+index 1ffaa0997927..c1bb33c8e63c 100644+--- a/browser/installer/allowed-dupes.mn++++ b/browser/installer/allowed-dupes.mn+@@ -141,6 +141,11 @@ browser/chrome/browser/res/payments/formautofill/autofillEditForms.js+ # Bug 1451050 - Remote settings empty dumps (will be populated with data eventually)+ browser/defaults/settings/pinning/pins.json+ browser/defaults/settings/main/example.json++# Juggler/marionette files++chrome/juggler/content/content/floating-scrollbars.css++browser/chrome/devtools/skin/floating-scrollbars-responsive-design.css++chrome/juggler/content/server/stream-utils.js++chrome/marionette/content/stream-utils.js+ #ifdef MOZ_EME_WIN32_ARTIFACT+ gmp-clearkey/0.1/manifest.json+ i686/gmp-clearkey/0.1/manifest.json+diff --git a/browser/installer/package-manifest.in b/browser/installer/package-manifest.in+index 0efb8c4210bf..6695fa1deb70 100644+--- a/browser/installer/package-manifest.in++++ b/browser/installer/package-manifest.in+@@ -208,6 +208,11 @@+ @RESPATH@/components/marionette.js+ #endif+++@RESPATH@/chrome/juggler@JAREXT@++@RESPATH@/chrome/juggler.manifest++@RESPATH@/components/juggler.manifest++@RESPATH@/components/juggler.js+++ #if defined(ENABLE_TESTS) && defined(MOZ_DEBUG)+ @RESPATH@/components/TestInterfaceJS.js+ @RESPATH@/components/TestInterfaceJS.manifest+diff --git a/docshell/base/nsDocShell.cpp b/docshell/base/nsDocShell.cpp+index b56ce1764dbb..1f4e7cb24d6f 100644+--- a/docshell/base/nsDocShell.cpp++++ b/docshell/base/nsDocShell.cpp+@@ -1241,6 +1241,7 @@ bool nsDocShell::SetCurrentURI(nsIURI* aURI, nsIRequest* aRequest,+ isSubFrame = mLSHE->GetIsSubFrame();+ }+++ FireOnFrameLocationChange(this, aRequest, aURI, aLocationFlags);+ if (!isSubFrame && !isRoot) {+ /*+ * We don't want to send OnLocationChange notifications when+diff --git a/dom/ipc/BrowserChild.cpp b/dom/ipc/BrowserChild.cpp+index d033474bec84..e97ab5373f13 100644+--- a/dom/ipc/BrowserChild.cpp++++ b/dom/ipc/BrowserChild.cpp+@@ -3576,6 +3576,13 @@ NS_IMETHODIMP BrowserChild::OnStateChange(nsIWebProgress* aWebProgress,+ return NS_OK;+ }+++NS_IMETHODIMP BrowserChild::OnFrameLocationChange(nsIWebProgress *aWebProgress,++ nsIRequest *aRequest,++ nsIURI *aLocation,++ uint32_t aFlags) {++ return NS_OK;++}+++ NS_IMETHODIMP BrowserChild::OnProgressChange(nsIWebProgress* aWebProgress,+ nsIRequest* aRequest,+ int32_t aCurSelfProgress,+diff --git a/extensions/permissions/nsPermissionManager.cpp b/extensions/permissions/nsPermissionManager.cpp+index ce3d5e64bb4e..64b86791e582 100644+--- a/extensions/permissions/nsPermissionManager.cpp++++ b/extensions/permissions/nsPermissionManager.cpp+@@ -189,6 +189,8 @@ nsresult GetOriginFromPrincipal(nsIPrincipal* aPrincipal, nsACString& aOrigin) {++ OriginAppendOASuffix(attrs, aOrigin);+++ // Disable userContext for permissions.++ // attrs.StripAttributes(mozilla::OriginAttributes::STRIP_USER_CONTEXT_ID);+ return NS_OK;+ }++@@ -220,7 +222,7 @@ nsresult GetPrincipalFromOrigin(const nsACString& aOrigin,+ attrs.mPrivateBrowsingId = 0;++ // Disable userContext for permissions.+- attrs.StripAttributes(mozilla::OriginAttributes::STRIP_USER_CONTEXT_ID);++ // attrs.StripAttributes(mozilla::OriginAttributes::STRIP_USER_CONTEXT_ID);++ nsCOMPtr<nsIURI> uri;+ nsresult rv = NS_NewURI(getter_AddRefs(uri), originNoSuffix);+@@ -312,7 +314,7 @@ already_AddRefed<nsIPrincipal> GetNextSubDomainPrincipal(+ mozilla::OriginAttributes attrs = aPrincipal->OriginAttributesRef();++ // Disable userContext for permissions.+- attrs.StripAttributes(mozilla::OriginAttributes::STRIP_USER_CONTEXT_ID);++ // attrs.StripAttributes(mozilla::OriginAttributes::STRIP_USER_CONTEXT_ID);++ nsCOMPtr<nsIPrincipal> principal =+ mozilla::BasePrincipal::CreateContentPrincipal(newURI, attrs);+@@ -3220,7 +3222,7 @@ void nsPermissionManager::GetKeyForOrigin(const nsACString& aOrigin,+ attrs.mPrivateBrowsingId = 0;++ // Disable userContext for permissions.+- attrs.StripAttributes(OriginAttributes::STRIP_USER_CONTEXT_ID);++ // attrs.StripAttributes(OriginAttributes::STRIP_USER_CONTEXT_ID);++ #ifdef DEBUG+ // Parse the origin string into a principal, and extract some useful+diff --git a/security/manager/ssl/nsCertOverrideService.cpp b/security/manager/ssl/nsCertOverrideService.cpp+index 31737688948a..255e5ae967b4 100644+--- a/security/manager/ssl/nsCertOverrideService.cpp++++ b/security/manager/ssl/nsCertOverrideService.cpp+@@ -611,7 +611,7 @@ nsCertOverrideService::IsCertUsedForOverrides(nsIX509Cert* aCert,+ NS_IMETHODIMP+ nsCertOverrideService::+ SetDisableAllSecurityChecksAndLetAttackersInterceptMyData(bool aDisable) {+- if (!(PR_GetEnv("XPCSHELL_TEST_PROFILE_DIR") ||++ if (false /* juggler hacks */ && !(PR_GetEnv("XPCSHELL_TEST_PROFILE_DIR") ||+ PR_GetEnv("MOZ_MARIONETTE"))) {+ return NS_ERROR_NOT_AVAILABLE;+ }+diff --git a/testing/juggler/BrowserContextManager.js b/testing/juggler/BrowserContextManager.js+new file mode 100644+index 000000000000..751fac95177c+--- /dev/null++++ b/testing/juggler/BrowserContextManager.js+@@ -0,0 +1,194 @@++"use strict";++++const {ContextualIdentityService} = ChromeUtils.import("resource://gre/modules/ContextualIdentityService.jsm");++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++const {NetUtil} = ChromeUtils.import('resource://gre/modules/NetUtil.jsm');++++const IDENTITY_NAME = 'JUGGLER ';++const HUNDRED_YEARS = 60 * 60 * 24 * 365 * 100;++++const ALL_PERMISSIONS = [++ 'geo',++ 'microphone',++ 'camera',++ 'desktop-notifications',++];++++class BrowserContextManager {++ static instance() {++ return BrowserContextManager._instance || null;++ }++++ static initialize() {++ if (BrowserContextManager._instance)++ return;++ BrowserContextManager._instance = new BrowserContextManager();++ }++++ constructor() {++ this._id = 0;++ this._browserContextIdToUserContextId = new Map();++ this._userContextIdToBrowserContextId = new Map();++ this._principalsForBrowserContextId = new Map();++++ // Cleanup containers from previous runs (if any)++ for (const identity of ContextualIdentityService.getPublicIdentities()) {++ if (identity.name && identity.name.startsWith(IDENTITY_NAME)) {++ ContextualIdentityService.remove(identity.userContextId);++ ContextualIdentityService.closeContainerTabs(identity.userContextId);++ }++ }++ }++++ grantPermissions(browserContextId, origin, permissions) {++ const attrs = browserContextId ? {userContextId: this.userContextId(browserContextId)} : {};++ const principal = Services.scriptSecurityManager.createContentPrincipal(NetUtil.newURI(origin), attrs);++ if (!this._principalsForBrowserContextId.has(browserContextId))++ this._principalsForBrowserContextId.set(browserContextId, []);++ this._principalsForBrowserContextId.get(browserContextId).push(principal);++ for (const permission of ALL_PERMISSIONS) {++ const action = permissions.includes(permission) ? Ci.nsIPermissionManager.ALLOW_ACTION : Ci.nsIPermissionManager.DENY_ACTION;++ Services.perms.addFromPrincipal(principal, permission, action);++ }++ }++++ resetPermissions(browserContextId) {++ if (!this._principalsForBrowserContextId.has(browserContextId))++ return;++ const principals = this._principalsForBrowserContextId.get(browserContextId);++ for (const principal of principals) {++ for (const permission of ALL_PERMISSIONS)++ Services.perms.removeFromPrincipal(principal, permission);++ }++ this._principalsForBrowserContextId.delete(browserContextId);++ }++++ createBrowserContext() {++ const browserContextId = (++this._id) + '';++ const identity = ContextualIdentityService.create(IDENTITY_NAME + browserContextId);++ this._browserContextIdToUserContextId.set(browserContextId, identity.userContextId);++ this._userContextIdToBrowserContextId.set(identity.userContextId, browserContextId);++ return browserContextId;++ }++++ browserContextId(userContextId) {++ return this._userContextIdToBrowserContextId.get(userContextId);++ }++++ userContextId(browserContextId) {++ return this._browserContextIdToUserContextId.get(browserContextId);++ }++++ removeBrowserContext(browserContextId) {++ const userContextId = this._browserContextIdToUserContextId.get(browserContextId);++ ContextualIdentityService.remove(userContextId);++ ContextualIdentityService.closeContainerTabs(userContextId);++ this._browserContextIdToUserContextId.delete(browserContextId);++ this._userContextIdToBrowserContextId.delete(userContextId);++ }++++ getBrowserContexts() {++ return Array.from(this._browserContextIdToUserContextId.keys());++ }++++ setCookies(browserContextId, cookies) {++ const protocolToSameSite = {++ [undefined]: Ci.nsICookie.SAMESITE_NONE,++ 'Lax': Ci.nsICookie.SAMESITE_LAX,++ 'Strict': Ci.nsICookie.SAMESITE_STRICT,++ };++ const userContextId = browserContextId ? this._browserContextIdToUserContextId.get(browserContextId) : undefined;++ for (const cookie of cookies) {++ const uri = cookie.url ? NetUtil.newURI(cookie.url) : null;++ let domain = cookie.domain;++ if (!domain) {++ if (!uri)++ throw new Error('At least one of the url and domain needs to be specified');++ domain = uri.host;++ }++ let path = cookie.path;++ if (!path)++ path = uri ? dirPath(uri.filePath) : '/';++ let secure = false;++ if (cookie.secure !== undefined)++ secure = cookie.secure;++ else if (uri.scheme === 'https')++ secure = true;++ Services.cookies.add(++ domain,++ path,++ cookie.name,++ cookie.value,++ secure,++ cookie.httpOnly || false,++ cookie.expires === undefined || cookie.expires === -1 /* isSession */,++ cookie.expires === undefined ? Date.now() + HUNDRED_YEARS : cookie.expires,++ { userContextId } /* originAttributes */,++ protocolToSameSite[cookie.sameSite],++ );++ }++ }++++ deleteCookies(browserContextId, cookies) {++ const userContextId = browserContextId ? this._browserContextIdToUserContextId.get(browserContextId) : undefined;++ for (const cookie of cookies) {++ let defaultDomain = '';++ let defaultPath = '/';++ if (cookie.url) {++ const uri = NetUtil.newURI(cookie.url);++ defaultDomain = uri.host;++ defaultPath = dirPath(uri.filePath);++ }++ Services.cookies.remove(++ cookie.domain || defaultDomain,++ cookie.name,++ cookie.path || defaultPath,++ { userContextId } /* originAttributes */,++ );++ }++ }++++ getCookies(browserContextId, urls) {++ const userContextId = browserContextId ? this._browserContextIdToUserContextId.get(browserContextId) : 0;++ const result = [];++ const sameSiteToProtocol = {++ [Ci.nsICookie.SAMESITE_NONE]: undefined,++ [Ci.nsICookie.SAMESITE_LAX]: 'Lax',++ [Ci.nsICookie.SAMESITE_STRICT]: 'Strict',++ };++ const uris = urls.map(url => NetUtil.newURI(url));++ for (let cookie of Services.cookies.enumerator) {++ if (cookie.originAttributes.userContextId !== userContextId)++ continue;++ if (!uris.some(uri => cookieMatchesURI(cookie, uri)))++ continue;++ result.push({++ name: cookie.name,++ value: cookie.value,++ domain: cookie.host,++ path: cookie.path,++ expires: cookie.isSession ? -1 : cookie.expiry,++ size: cookie.name.length + cookie.value.length,++ httpOnly: cookie.isHttpOnly,++ secure: cookie.isSecure,++ session: cookie.isSession,++ sameSite: sameSiteToProtocol[cookie.sameSite],++ });++ }++ return result;++ }++}++++function cookieMatchesURI(cookie, uri) {++ const hostMatches = cookie.host === uri.host || cookie.host === '.' + uri.host;++ const pathMatches = uri.filePath.startsWith(cookie.path);++ return hostMatches && pathMatches;++}++++function dirPath(path) {++ return path.substring(0, path.lastIndexOf('/') + 1);++}++++var EXPORTED_SYMBOLS = ['BrowserContextManager'];++this.BrowserContextManager = BrowserContextManager;+++diff --git a/testing/juggler/Helper.js b/testing/juggler/Helper.js+new file mode 100644+index 000000000000..673e93b0278a+--- /dev/null++++ b/testing/juggler/Helper.js+@@ -0,0 +1,101 @@++const uuidGen = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++++class Helper {++ addObserver(handler, topic) {++ Services.obs.addObserver(handler, topic);++ return () => Services.obs.removeObserver(handler, topic);++ }++++ addMessageListener(receiver, eventName, handler) {++ receiver.addMessageListener(eventName, handler);++ return () => receiver.removeMessageListener(eventName, handler);++ }++++ addEventListener(receiver, eventName, handler) {++ receiver.addEventListener(eventName, handler);++ return () => receiver.removeEventListener(eventName, handler);++ }++++ on(receiver, eventName, handler) {++ // The toolkit/modules/EventEmitter.jsm dispatches event name as a first argument.++ // Fire event listeners without it for convenience.++ const handlerWrapper = (_, ...args) => handler(...args);++ receiver.on(eventName, handlerWrapper);++ return () => receiver.off(eventName, handlerWrapper);++ }++++ addProgressListener(progress, listener, flags) {++ progress.addProgressListener(listener, flags);++ return () => progress.removeProgressListener(listener);++ }++++ removeListeners(listeners) {++ for (const tearDown of listeners)++ tearDown.call(null);++ listeners.splice(0, listeners.length);++ }++++ generateId() {++ return uuidGen.generateUUID().toString();++ }++++ getNetworkErrorStatusText(status) {++ if (!status)++ return null;++ for (const key of Object.keys(Cr)) {++ if (Cr[key] === status)++ return key;++ }++ // Security module. The following is taken from++ // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/How_to_check_the_secruity_state_of_an_XMLHTTPRequest_over_SSL++ if ((status & 0xff0000) === 0x5a0000) {++ // NSS_SEC errors (happen below the base value because of negative vals)++ if ((status & 0xffff) < Math.abs(Ci.nsINSSErrorsService.NSS_SEC_ERROR_BASE)) {++ // The bases are actually negative, so in our positive numeric space, we++ // need to subtract the base off our value.++ const nssErr = Math.abs(Ci.nsINSSErrorsService.NSS_SEC_ERROR_BASE) - (status & 0xffff);++ switch (nssErr) {++ case 11:++ return 'SEC_ERROR_EXPIRED_CERTIFICATE';++ case 12:++ return 'SEC_ERROR_REVOKED_CERTIFICATE';++ case 13:++ return 'SEC_ERROR_UNKNOWN_ISSUER';++ case 20:++ return 'SEC_ERROR_UNTRUSTED_ISSUER';++ case 21:++ return 'SEC_ERROR_UNTRUSTED_CERT';++ case 36:++ return 'SEC_ERROR_CA_CERT_INVALID';++ case 90:++ return 'SEC_ERROR_INADEQUATE_KEY_USAGE';++ case 176:++ return 'SEC_ERROR_CERT_SIGNATURE_ALGORITHM_DISABLED';++ default:++ return 'SEC_ERROR_UNKNOWN';++ }++ }++ const sslErr = Math.abs(Ci.nsINSSErrorsService.NSS_SSL_ERROR_BASE) - (status & 0xffff);++ switch (sslErr) {++ case 3:++ return 'SSL_ERROR_NO_CERTIFICATE';++ case 4:++ return 'SSL_ERROR_BAD_CERTIFICATE';++ case 8:++ return 'SSL_ERROR_UNSUPPORTED_CERTIFICATE_TYPE';++ case 9:++ return 'SSL_ERROR_UNSUPPORTED_VERSION';++ case 12:++ return 'SSL_ERROR_BAD_CERT_DOMAIN';++ default:++ return 'SSL_ERROR_UNKNOWN';++ }++ }++ return '<unknown error>';++ }++}++++var EXPORTED_SYMBOLS = [ "Helper" ];++this.Helper = Helper;+++diff --git a/testing/juggler/NetworkObserver.js b/testing/juggler/NetworkObserver.js+new file mode 100644+index 000000000000..cc8cb8fe9d83+--- /dev/null++++ b/testing/juggler/NetworkObserver.js+@@ -0,0 +1,450 @@++"use strict";++++const {EventEmitter} = ChromeUtils.import('resource://gre/modules/EventEmitter.jsm');++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++const {NetUtil} = ChromeUtils.import('resource://gre/modules/NetUtil.jsm');++const {CommonUtils} = ChromeUtils.import("resource://services-common/utils.js");++++++const Cc = Components.classes;++const Ci = Components.interfaces;++const Cu = Components.utils;++const Cr = Components.results;++const Cm = Components.manager;++const CC = Components.Constructor;++const helper = new Helper();++++const BinaryInputStream = CC('@mozilla.org/binaryinputstream;1', 'nsIBinaryInputStream', 'setInputStream');++const BinaryOutputStream = CC('@mozilla.org/binaryoutputstream;1', 'nsIBinaryOutputStream', 'setOutputStream');++const StorageStream = CC('@mozilla.org/storagestream;1', 'nsIStorageStream', 'init');++++// Cap response storage with 100Mb per tracked tab.++const MAX_RESPONSE_STORAGE_SIZE = 100 * 1024 * 1024;++++/**++ * This is a nsIChannelEventSink implementation that monitors channel redirects.++ */++const SINK_CLASS_DESCRIPTION = "Juggler NetworkMonitor Channel Event Sink";++const SINK_CLASS_ID = Components.ID("{c2b4c83e-607a-405a-beab-0ef5dbfb7617}");++const SINK_CONTRACT_ID = "@mozilla.org/network/monitor/channeleventsink;1";++const SINK_CATEGORY_NAME = "net-channel-event-sinks";++++class NetworkObserver {++ static instance() {++ return NetworkObserver._instance || null;++ }++++ static initialize() {++ if (NetworkObserver._instance)++ return;++ NetworkObserver._instance = new NetworkObserver();++ }++++ constructor() {++ EventEmitter.decorate(this);++ this._browserSessionCount = new Map();++ this._activityDistributor = Cc["@mozilla.org/network/http-activity-distributor;1"].getService(Ci.nsIHttpActivityDistributor);++ this._activityDistributor.addObserver(this);++++ this._redirectMap = new Map();++ this._channelSink = {++ QueryInterface: ChromeUtils.generateQI([Ci.nsIChannelEventSink]),++ asyncOnChannelRedirect: (oldChannel, newChannel, flags, callback) => {++ this._onRedirect(oldChannel, newChannel);++ callback.onRedirectVerifyCallback(Cr.NS_OK);++ },++ };++ this._channelSinkFactory = {++ QueryInterface: ChromeUtils.generateQI([Ci.nsIFactory]),++ createInstance: (aOuter, aIID) => this._channelSink.QueryInterface(aIID),++ };++ // Register self as ChannelEventSink to track redirects.++ const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);++ registrar.registerFactory(SINK_CLASS_ID, SINK_CLASS_DESCRIPTION, SINK_CONTRACT_ID, this._channelSinkFactory);++ Services.catMan.addCategoryEntry(SINK_CATEGORY_NAME, SINK_CONTRACT_ID, SINK_CONTRACT_ID, false, true);++++ // Request interception state.++ this._browserSuspendedChannels = new Map();++ this._extraHTTPHeaders = new Map();++ this._browserResponseStorages = new Map();++++ this._eventListeners = [++ helper.addObserver(this._onRequest.bind(this), 'http-on-modify-request'),++ helper.addObserver(this._onResponse.bind(this, false /* fromCache */), 'http-on-examine-response'),++ helper.addObserver(this._onResponse.bind(this, true /* fromCache */), 'http-on-examine-cached-response'),++ helper.addObserver(this._onResponse.bind(this, true /* fromCache */), 'http-on-examine-merged-response'),++ ];++ }++++ setExtraHTTPHeaders(browser, headers) {++ if (!headers)++ this._extraHTTPHeaders.delete(browser);++ else++ this._extraHTTPHeaders.set(browser, headers);++ }++++ enableRequestInterception(browser) {++ if (!this._browserSuspendedChannels.has(browser))++ this._browserSuspendedChannels.set(browser, new Map());++ }++++ disableRequestInterception(browser) {++ const suspendedChannels = this._browserSuspendedChannels.get(browser);++ if (!suspendedChannels)++ return;++ this._browserSuspendedChannels.delete(browser);++ for (const channel of suspendedChannels.values())++ channel.resume();++ }++++ resumeSuspendedRequest(browser, requestId, headers) {++ const suspendedChannels = this._browserSuspendedChannels.get(browser);++ if (!suspendedChannels)++ throw new Error(`Request interception is not enabled`);++ const httpChannel = suspendedChannels.get(requestId);++ if (!httpChannel)++ throw new Error(`Cannot find request "${requestId}"`);++ if (headers) {++ // 1. Clear all previous headers.++ for (const header of requestHeaders(httpChannel))++ httpChannel.setRequestHeader(header.name, '', false /* merge */);++ // 2. Set new headers.++ for (const header of headers)++ httpChannel.setRequestHeader(header.name, header.value, false /* merge */);++ }++ suspendedChannels.delete(requestId);++ httpChannel.resume();++ }++++ getResponseBody(browser, requestId) {++ const responseStorage = this._browserResponseStorages.get(browser);++ if (!responseStorage)++ throw new Error('Responses are not tracked for the given browser');++ return responseStorage.getBase64EncodedResponse(requestId);++ }++++ abortSuspendedRequest(browser, aRequestId) {++ const suspendedChannels = this._browserSuspendedChannels.get(browser);++ if (!suspendedChannels)++ throw new Error(`Request interception is not enabled`);++ const httpChannel = suspendedChannels.get(aRequestId);++ if (!httpChannel)++ throw new Error(`Cannot find request "${aRequestId}"`);++ suspendedChannels.delete(aRequestId);++ httpChannel.cancel(Cr.NS_ERROR_FAILURE);++ httpChannel.resume();++ this.emit('requestfailed', httpChannel, {++ requestId: requestId(httpChannel),++ errorCode: helper.getNetworkErrorStatusText(httpChannel.status),++ });++ }++++ _onRedirect(oldChannel, newChannel) {++ if (!(oldChannel instanceof Ci.nsIHttpChannel))++ return;++ const httpChannel = oldChannel.QueryInterface(Ci.nsIHttpChannel);++ const loadContext = getLoadContext(httpChannel);++ if (!loadContext || !this._browserSessionCount.has(loadContext.topFrameElement))++ return;++ this._redirectMap.set(newChannel, oldChannel);++ }++++ observeActivity(channel, activityType, activitySubtype, timestamp, extraSizeData, extraStringData) {++ if (activityType !== Ci.nsIHttpActivityObserver.ACTIVITY_TYPE_HTTP_TRANSACTION)++ return;++ if (!(channel instanceof Ci.nsIHttpChannel))++ return;++ const httpChannel = channel.QueryInterface(Ci.nsIHttpChannel);++ const loadContext = getLoadContext(httpChannel);++ if (!loadContext || !this._browserSessionCount.has(loadContext.topFrameElement))++ return;++ if (activitySubtype !== Ci.nsIHttpActivityObserver.ACTIVITY_SUBTYPE_TRANSACTION_CLOSE)++ return;++ this.emit('requestfinished', httpChannel, {++ requestId: requestId(httpChannel),++ });++ }++++ _onRequest(channel, topic) {++ if (!(channel instanceof Ci.nsIHttpChannel))++ return;++ const httpChannel = channel.QueryInterface(Ci.nsIHttpChannel);++ const loadContext = getLoadContext(httpChannel);++ if (!loadContext || !this._browserSessionCount.has(loadContext.topFrameElement))++ return;++ const extraHeaders = this._extraHTTPHeaders.get(loadContext.topFrameElement);++ if (extraHeaders) {++ for (const header of extraHeaders)++ httpChannel.setRequestHeader(header.name, header.value, false /* merge */);++ }++ const causeType = httpChannel.loadInfo ? httpChannel.loadInfo.externalContentPolicyType : Ci.nsIContentPolicy.TYPE_OTHER;++ const suspendedChannels = this._browserSuspendedChannels.get(loadContext.topFrameElement);++ if (suspendedChannels) {++ httpChannel.suspend();++ suspendedChannels.set(requestId(httpChannel), httpChannel);++ }++ const oldChannel = this._redirectMap.get(httpChannel);++ this._redirectMap.delete(httpChannel);++++ // Install response body hooks.++ new ResponseBodyListener(this, loadContext.topFrameElement, httpChannel);++++ this.emit('request', httpChannel, {++ url: httpChannel.URI.spec,++ suspended: suspendedChannels ? true : undefined,++ requestId: requestId(httpChannel),++ redirectedFrom: oldChannel ? requestId(oldChannel) : undefined,++ postData: readRequestPostData(httpChannel),++ headers: requestHeaders(httpChannel),++ method: httpChannel.requestMethod,++ isNavigationRequest: httpChannel.isMainDocumentChannel,++ cause: causeTypeToString(causeType),++ });++ }++++ _onResponse(fromCache, httpChannel, topic) {++ const loadContext = getLoadContext(httpChannel);++ if (!loadContext || !this._browserSessionCount.has(loadContext.topFrameElement))++ return;++ httpChannel.QueryInterface(Ci.nsIHttpChannelInternal);++ const headers = [];++ httpChannel.visitResponseHeaders({++ visitHeader: (name, value) => headers.push({name, value}),++ });++++ let remoteIPAddress = undefined;++ let remotePort = undefined;++ try {++ remoteIPAddress = httpChannel.remoteAddress;++ remotePort = httpChannel.remotePort;++ } catch (e) {++ // remoteAddress is not defined for cached requests.++ }++ this.emit('response', httpChannel, {++ requestId: requestId(httpChannel),++ securityDetails: getSecurityDetails(httpChannel),++ fromCache,++ headers,++ remoteIPAddress,++ remotePort,++ status: httpChannel.responseStatus,++ statusText: httpChannel.responseStatusText,++ });++ }++++ _onResponseFinished(browser, httpChannel, body) {++ const responseStorage = this._browserResponseStorages.get(browser);++ if (!responseStorage)++ return;++ responseStorage.addResponseBody(httpChannel, body);++ this.emit('requestfinished', httpChannel, {++ requestId: requestId(httpChannel),++ });++ }++++ startTrackingBrowserNetwork(browser) {++ const value = this._browserSessionCount.get(browser) || 0;++ this._browserSessionCount.set(browser, value + 1);++ if (value === 0)++ this._browserResponseStorages.set(browser, new ResponseStorage(MAX_RESPONSE_STORAGE_SIZE, MAX_RESPONSE_STORAGE_SIZE / 10));++ return () => this.stopTrackingBrowserNetwork(browser);++ }++++ stopTrackingBrowserNetwork(browser) {++ const value = this._browserSessionCount.get(browser);++ if (value) {++ this._browserSessionCount.set(browser, value - 1);++ } else {++ this._browserSessionCount.delete(browser);++ this._browserResponseStorages.delete(browser);++ }++ }++++ dispose() {++ this._activityDistributor.removeObserver(this);++ const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);++ registrar.unregisterFactory(SINK_CLASS_ID, this._channelSinkFactory);++ Services.catMan.deleteCategoryEntry(SINK_CATEGORY_NAME, SINK_CONTRACT_ID, false);++ helper.removeListeners(this._eventListeners);++ }++}++++const protocolVersionNames = {++ [Ci.nsITransportSecurityInfo.TLS_VERSION_1]: 'TLS 1',++ [Ci.nsITransportSecurityInfo.TLS_VERSION_1_1]: 'TLS 1.1',++ [Ci.nsITransportSecurityInfo.TLS_VERSION_1_2]: 'TLS 1.2',++ [Ci.nsITransportSecurityInfo.TLS_VERSION_1_3]: 'TLS 1.3',++};++++function getSecurityDetails(httpChannel) {++ const securityInfo = httpChannel.securityInfo;++ if (!securityInfo)++ return null;++ securityInfo.QueryInterface(Ci.nsITransportSecurityInfo);++ if (!securityInfo.serverCert)++ return null;++ return {++ protocol: protocolVersionNames[securityInfo.protocolVersion] || '<unknown>',++ subjectName: securityInfo.serverCert.commonName,++ issuer: securityInfo.serverCert.issuerCommonName,++ // Convert to seconds.++ validFrom: securityInfo.serverCert.validity.notBefore / 1000 / 1000,++ validTo: securityInfo.serverCert.validity.notAfter / 1000 / 1000,++ };++}++++function readRequestPostData(httpChannel) {++ if (!(httpChannel instanceof Ci.nsIUploadChannel))++ return undefined;++ const iStream = httpChannel.uploadStream;++ if (!iStream)++ return undefined;++ const isSeekableStream = iStream instanceof Ci.nsISeekableStream;++++ let prevOffset;++ if (isSeekableStream) {++ prevOffset = iStream.tell();++ iStream.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);++ }++++ // Read data from the stream.++ let text = undefined;++ try {++ text = NetUtil.readInputStreamToString(iStream, iStream.available());++ const converter = Cc['@mozilla.org/intl/scriptableunicodeconverter']++ .createInstance(Ci.nsIScriptableUnicodeConverter);++ converter.charset = 'UTF-8';++ text = converter.ConvertToUnicode(text);++ } catch (err) {++ text = undefined;++ }++++ // Seek locks the file, so seek to the beginning only if necko hasn't++ // read it yet, since necko doesn't seek to 0 before reading (at lest++ // not till 459384 is fixed).++ if (isSeekableStream && prevOffset == 0)++ iStream.seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);++ return text;++}++++function getLoadContext(httpChannel) {++ let loadContext = null;++ try {++ if (httpChannel.notificationCallbacks)++ loadContext = httpChannel.notificationCallbacks.getInterface(Ci.nsILoadContext);++ } catch (e) {}++ try {++ if (!loadContext && httpChannel.loadGroup)++ loadContext = httpChannel.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);++ } catch (e) { }++ return loadContext;++}++++function requestId(httpChannel) {++ return httpChannel.channelId + '';++}++++function requestHeaders(httpChannel) {++ const headers = [];++ httpChannel.visitRequestHeaders({++ visitHeader: (name, value) => headers.push({name, value}),++ });++ return headers;++}++++function causeTypeToString(causeType) {++ for (let key in Ci.nsIContentPolicy) {++ if (Ci.nsIContentPolicy[key] === causeType)++ return key;++ }++ return 'TYPE_OTHER';++}++++class ResponseStorage {++ constructor(maxTotalSize, maxResponseSize) {++ this._totalSize = 0;++ this._maxResponseSize = maxResponseSize;++ this._maxTotalSize = maxTotalSize;++ this._responses = new Map();++ }++++ addResponseBody(httpChannel, body) {++ if (body.length > this._maxResponseSize) {++ this._responses.set(requestId, {++ evicted: true,++ body: '',++ });++ return;++ }++ let encodings = [];++ if ((httpChannel instanceof Ci.nsIEncodedChannel) && httpChannel.contentEncodings && !httpChannel.applyConversion) {++ const encodingHeader = httpChannel.getResponseHeader("Content-Encoding");++ encodings = encodingHeader.split(/\s*\t*,\s*\t*/);++ }++ this._responses.set(requestId(httpChannel), {body, encodings});++ this._totalSize += body.length;++ if (this._totalSize > this._maxTotalSize) {++ for (let [requestId, response] of this._responses) {++ this._totalSize -= response.body.length;++ response.body = '';++ response.evicted = true;++ if (this._totalSize < this._maxTotalSize)++ break;++ }++ }++ }++++ getBase64EncodedResponse(requestId) {++ const response = this._responses.get(requestId);++ if (!response)++ throw new Error(`Request "${requestId}" is not found`);++ if (response.evicted)++ return {base64body: '', evicted: true};++ let result = response.body;++ if (response.encodings && response.encodings.length) {++ for (const encoding of response.encodings)++ result = CommonUtils.convertString(result, encoding, 'uncompressed');++ }++ return {base64body: btoa(result)};++ }++}++++class ResponseBodyListener {++ constructor(networkObserver, browser, httpChannel) {++ this._networkObserver = networkObserver;++ this._browser = browser;++ this._httpChannel = httpChannel;++ this._chunks = [];++ this.QueryInterface = ChromeUtils.generateQI([Ci.nsIStreamListener]);++ httpChannel.QueryInterface(Ci.nsITraceableChannel);++ this.originalListener = httpChannel.setNewListener(this);++ }++++ onDataAvailable(aRequest, aInputStream, aOffset, aCount) {++ const iStream = new BinaryInputStream(aInputStream);++ const sStream = new StorageStream(8192, aCount, null);++ const oStream = new BinaryOutputStream(sStream.getOutputStream(0));++++ // Copy received data as they come.++ const data = iStream.readBytes(aCount);++ this._chunks.push(data);++++ oStream.writeBytes(data, aCount);++ this.originalListener.onDataAvailable(aRequest, sStream.newInputStream(0), aOffset, aCount);++ }++++ onStartRequest(aRequest) {++ this.originalListener.onStartRequest(aRequest);++ }++++ onStopRequest(aRequest, aStatusCode) {++ this.originalListener.onStopRequest(aRequest, aStatusCode);++ const body = this._chunks.join('');++ delete this._chunks;++ this._networkObserver._onResponseFinished(this._browser, this._httpChannel, body);++ }++}++++var EXPORTED_SYMBOLS = ['NetworkObserver'];++this.NetworkObserver = NetworkObserver;+diff --git a/testing/juggler/TargetRegistry.js b/testing/juggler/TargetRegistry.js+new file mode 100644+index 000000000000..da5e4ee371d0+--- /dev/null++++ b/testing/juggler/TargetRegistry.js+@@ -0,0 +1,187 @@++const {EventEmitter} = ChromeUtils.import('resource://gre/modules/EventEmitter.jsm');++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++++const Cc = Components.classes;++const Ci = Components.interfaces;++const Cu = Components.utils;++++const helper = new Helper();++++class TargetRegistry {++ static instance() {++ return TargetRegistry._instance || null;++ }++++ static initialize(mainWindow, contextManager) {++ if (TargetRegistry._instance)++ return;++ TargetRegistry._instance = new TargetRegistry(mainWindow, contextManager);++ }++++ constructor(mainWindow, contextManager) {++ EventEmitter.decorate(this);++++ this._mainWindow = mainWindow;++ this._contextManager = contextManager;++ this._targets = new Map();++++ this._browserTarget = new BrowserTarget();++ this._targets.set(this._browserTarget.id(), this._browserTarget);++ this._tabToTarget = new Map();++++ for (const tab of this._mainWindow.gBrowser.tabs)++ this._ensureTargetForTab(tab);++ this._mainWindow.gBrowser.tabContainer.addEventListener('TabOpen', event => {++ this._ensureTargetForTab(event.target);++ });++ this._mainWindow.gBrowser.tabContainer.addEventListener('TabClose', event => {++ const tab = event.target;++ const target = this._tabToTarget.get(tab);++ if (!target)++ return;++ this._targets.delete(target.id());++ this._tabToTarget.delete(tab);++ target.dispose();++ this.emit(TargetRegistry.Events.TargetDestroyed, target.info());++ });++ }++++ async newPage({browserContextId}) {++ const tab = this._mainWindow.gBrowser.addTab('about:blank', {++ userContextId: this._contextManager.userContextId(browserContextId),++ triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal(),++ });++ this._mainWindow.gBrowser.selectedTab = tab;++ // Await navigation to about:blank++ await new Promise(resolve => {++ const wpl = {++ onLocationChange: function(aWebProgress, aRequest, aLocation) {++ tab.linkedBrowser.removeProgressListener(wpl);++ resolve();++ },++ QueryInterface: ChromeUtils.generateQI([++ Ci.nsIWebProgressListener,++ Ci.nsISupportsWeakReference,++ ]),++ };++ tab.linkedBrowser.addProgressListener(wpl);++ });++ const target = this._ensureTargetForTab(tab);++ return target.id();++ }++++ async closePage(targetId, runBeforeUnload = false) {++ const tab = this.tabForTarget(targetId);++ await this._mainWindow.gBrowser.removeTab(tab, {++ skipPermitUnload: !runBeforeUnload,++ });++ }++++ targetInfos() {++ return Array.from(this._targets.values()).map(target => target.info());++ }++++ targetInfo(targetId) {++ const target = this._targets.get(targetId);++ return target ? target.info() : null;++ }++++ browserTargetInfo() {++ return this._browserTarget.info();++ }++++ tabForTarget(targetId) {++ const target = this._targets.get(targetId);++ if (!target)++ throw new Error(`Target "${targetId}" does not exist!`);++ if (!(target instanceof PageTarget))++ throw new Error(`Target "${targetId}" is not a page!`);++ return target._tab;++ }++++ _ensureTargetForTab(tab) {++ if (this._tabToTarget.has(tab))++ return this._tabToTarget.get(tab);++ const openerTarget = tab.openerTab ? this._ensureTargetForTab(tab.openerTab) : null;++ const target = new PageTarget(this, tab, this._contextManager.browserContextId(tab.userContextId), openerTarget);++++ this._targets.set(target.id(), target);++ this._tabToTarget.set(tab, target);++ this.emit(TargetRegistry.Events.TargetCreated, target.info());++ }++}++++let lastTabTargetId = 0;++++class PageTarget {++ constructor(registry, tab, browserContextId, opener) {++ this._targetId = 'target-page-' + (++lastTabTargetId);++ this._registry = registry;++ this._tab = tab;++ this._browserContextId = browserContextId;++ this._openerId = opener ? opener.id() : undefined;++ this._url = tab.linkedBrowser.currentURI.spec;++++ // First navigation always happens to about:blank - do not report it.++ this._skipNextNavigation = true;++++ const navigationListener = {++ QueryInterface: ChromeUtils.generateQI([ Ci.nsIWebProgressListener]),++ onLocationChange: (aWebProgress, aRequest, aLocation) => this._onNavigated(aLocation),++ };++ this._eventListeners = [++ helper.addProgressListener(tab.linkedBrowser, navigationListener, Ci.nsIWebProgress.NOTIFY_LOCATION),++ ];++ }++++ id() {++ return this._targetId;++ }++++ info() {++ return {++ targetId: this.id(),++ type: 'page',++ url: this._url,++ browserContextId: this._browserContextId,++ openerId: this._openerId,++ };++ }++++ _onNavigated(aLocation) {++ if (this._skipNextNavigation) {++ this._skipNextNavigation = false;++ return;++ }++ this._url = aLocation.spec;++ this._registry.emit(TargetRegistry.Events.TargetChanged, this.info());++ }++++ dispose() {++ helper.removeListeners(this._eventListeners);++ }++}++++class BrowserTarget {++ id() {++ return 'target-browser';++ }++++ info() {++ return {++ targetId: this.id(),++ type: 'browser',++ url: '',++ }++ }++}++++TargetRegistry.Events = {++ TargetCreated: Symbol('TargetRegistry.Events.TargetCreated'),++ TargetDestroyed: Symbol('TargetRegistry.Events.TargetDestroyed'),++ TargetChanged: Symbol('TargetRegistry.Events.TargetChanged'),++};++++var EXPORTED_SYMBOLS = ['TargetRegistry'];++this.TargetRegistry = TargetRegistry;+diff --git a/testing/juggler/components/juggler.js b/testing/juggler/components/juggler.js+new file mode 100644+index 000000000000..9654aeeb257d+--- /dev/null++++ b/testing/juggler/components/juggler.js+@@ -0,0 +1,112 @@++const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++const {Dispatcher} = ChromeUtils.import("chrome://juggler/content/protocol/Dispatcher.js");++const {BrowserContextManager} = ChromeUtils.import("chrome://juggler/content/BrowserContextManager.js");++const {NetworkObserver} = ChromeUtils.import("chrome://juggler/content/NetworkObserver.js");++const {TargetRegistry} = ChromeUtils.import("chrome://juggler/content/TargetRegistry.js");++++const Cc = Components.classes;++const Ci = Components.interfaces;++const Cu = Components.utils;++++const FRAME_SCRIPT = "chrome://juggler/content/content/main.js";++++// Command Line Handler++function CommandLineHandler() {++ this._port = -1;++};++++CommandLineHandler.prototype = {++ classDescription: "Sample command-line handler",++ classID: Components.ID('{f7a74a33-e2ab-422d-b022-4fb213dd2639}'),++ contractID: "@mozilla.org/remote/juggler;1",++ _xpcom_categories: [{++ category: "command-line-handler",++ entry: "m-juggler"++ }],++++ /* nsICommandLineHandler */++ handle: async function(cmdLine) {++ const jugglerFlag = cmdLine.handleFlagWithParam("juggler", false);++ if (!jugglerFlag || isNaN(jugglerFlag))++ return;++ this._port = parseInt(jugglerFlag, 10);++ Services.obs.addObserver(this, 'sessionstore-windows-restored');++ },++++ observe: async function(subject, topic) {++ Services.obs.removeObserver(this, 'sessionstore-windows-restored');++++ const win = await waitForBrowserWindow();++ BrowserContextManager.initialize();++ NetworkObserver.initialize();++ TargetRegistry.initialize(win, BrowserContextManager.instance());++++ const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm");++ const WebSocketServer = require('devtools/server/socket/websocket-server');++ this._server = Cc["@mozilla.org/network/server-socket;1"].createInstance(Ci.nsIServerSocket);++ this._server.initSpecialConnection(this._port, Ci.nsIServerSocket.KeepWhenOffline | Ci.nsIServerSocket.LoopbackOnly, 4);++ this._server.asyncListen({++ onSocketAccepted: async(socket, transport) => {++ const input = transport.openInputStream(0, 0, 0);++ const output = transport.openOutputStream(0, 0, 0);++ const webSocket = await WebSocketServer.accept(transport, input, output);++ new Dispatcher(webSocket);++ }++ });++++ Services.mm.loadFrameScript(FRAME_SCRIPT, true /* aAllowDelayedLoad */);++ dump(`Juggler listening on ws://127.0.0.1:${this._server.port}\n`);++ },++++ QueryInterface: ChromeUtils.generateQI([ Ci.nsICommandLineHandler ]),++++ // CHANGEME: change the help info as appropriate, but++ // follow the guidelines in nsICommandLineHandler.idl++ // specifically, flag descriptions should start at++ // character 24, and lines should be wrapped at++ // 72 characters with embedded newlines,++ // and finally, the string should end with a newline++ helpInfo : " --juggler Enable Juggler automation\n"++};++++var NSGetFactory = XPCOMUtils.generateNSGetFactory([CommandLineHandler]);++++/**++ * @return {!Promise<Ci.nsIDOMChromeWindow>}++ */++async function waitForBrowserWindow() {++ const windowsIt = Services.wm.getEnumerator('navigator:browser');++ if (windowsIt.hasMoreElements())++ return waitForWindowLoaded(windowsIt.getNext());++++ let fulfill;++ let promise = new Promise(x => fulfill = x);++++ const listener = {++ onOpenWindow: window => {++ if (window instanceof Ci.nsIDOMChromeWindow) {++ Services.wm.removeListener(listener);++ fulfill(waitForWindowLoaded(window));++ }++ },++ onCloseWindow: () => {}++ };++ Services.wm.addListener(listener);++ return promise;++++ /**++ * @param {!Ci.nsIDOMChromeWindow} window++ * @return {!Promise<Ci.nsIDOMChromeWindow>}++ */++ function waitForWindowLoaded(window) {++ if (window.document.readyState === 'complete')++ return window;++ return new Promise(fulfill => {++ window.addEventListener('load', function listener() {++ window.removeEventListener('load', listener);++ fulfill(window);++ });++ });++ }++}+diff --git a/testing/juggler/components/juggler.manifest b/testing/juggler/components/juggler.manifest+new file mode 100644+index 000000000000..50f893020756+--- /dev/null++++ b/testing/juggler/components/juggler.manifest+@@ -0,0 +1,3 @@++component {f7a74a33-e2ab-422d-b022-4fb213dd2639} juggler.js++contract @mozilla.org/remote/juggler;1 {f7a74a33-e2ab-422d-b022-4fb213dd2639}++category command-line-handler m-juggler @mozilla.org/remote/juggler;1+diff --git a/testing/juggler/components/moz.build b/testing/juggler/components/moz.build+new file mode 100644+index 000000000000..268fbc361d80+--- /dev/null++++ b/testing/juggler/components/moz.build+@@ -0,0 +1,9 @@++# This Source Code Form is subject to the terms of the Mozilla Public++# License, v. 2.0. If a copy of the MPL was not distributed with this++# file, You can obtain one at http://mozilla.org/MPL/2.0/.++++EXTRA_COMPONENTS += [++ "juggler.js",++ "juggler.manifest",++]+++diff --git a/testing/juggler/content/ContentSession.js b/testing/juggler/content/ContentSession.js+new file mode 100644+index 000000000000..f68780d529e7+--- /dev/null++++ b/testing/juggler/content/ContentSession.js+@@ -0,0 +1,63 @@++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {RuntimeAgent} = ChromeUtils.import('chrome://juggler/content/content/RuntimeAgent.js');++const {PageAgent} = ChromeUtils.import('chrome://juggler/content/content/PageAgent.js');++++const helper = new Helper();++++class ContentSession {++ /**++ * @param {string} sessionId++ * @param {!ContentFrameMessageManager} messageManager++ * @param {!FrameTree} frameTree++ * @param {!ScrollbarManager} scrollbarManager++ * @param {!NetworkMonitor} networkMonitor++ */++ constructor(sessionId, messageManager, frameTree, scrollbarManager, networkMonitor) {++ this._sessionId = sessionId;++ this._messageManager = messageManager;++ const runtimeAgent = new RuntimeAgent(this);++ const pageAgent = new PageAgent(this, runtimeAgent, frameTree, scrollbarManager, networkMonitor);++ this._agents = {++ Page: pageAgent,++ Runtime: runtimeAgent,++ };++ this._eventListeners = [++ helper.addMessageListener(messageManager, this._sessionId, this._onMessage.bind(this)),++ ];++ }++++ emitEvent(eventName, params) {++ this._messageManager.sendAsyncMessage(this._sessionId, {eventName, params});++ }++++ mm() {++ return this._messageManager;++ }++++ async _onMessage(msg) {++ const id = msg.data.id;++ try {++ const [domainName, methodName] = msg.data.methodName.split('.');++ const agent = this._agents[domainName];++ if (!agent)++ throw new Error(`unknown domain: ${domainName}`);++ const handler = agent[methodName];++ if (!handler)++ throw new Error(`unknown method: ${domainName}.${methodName}`);++ const result = await handler.call(agent, msg.data.params);++ this._messageManager.sendAsyncMessage(this._sessionId, {id, result});++ } catch (e) {++ this._messageManager.sendAsyncMessage(this._sessionId, {id, error: e.message + '\n' + e.stack});++ }++ }++++ dispose() {++ helper.removeListeners(this._eventListeners);++ for (const agent of Object.values(this._agents))++ agent.dispose();++ }++}++++var EXPORTED_SYMBOLS = ['ContentSession'];++this.ContentSession = ContentSession;+++diff --git a/testing/juggler/content/FrameTree.js b/testing/juggler/content/FrameTree.js+new file mode 100644+index 000000000000..2931c75e60d2+--- /dev/null++++ b/testing/juggler/content/FrameTree.js+@@ -0,0 +1,232 @@++"use strict";++const Ci = Components.interfaces;++const Cr = Components.results;++const Cu = Components.utils;++++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {EventEmitter} = ChromeUtils.import('resource://gre/modules/EventEmitter.jsm');++++const helper = new Helper();++++class FrameTree {++ constructor(rootDocShell) {++ EventEmitter.decorate(this);++ this._docShellToFrame = new Map();++ this._frameIdToFrame = new Map();++ this._mainFrame = this._createFrame(rootDocShell);++ const webProgress = rootDocShell.QueryInterface(Ci.nsIInterfaceRequestor)++ .getInterface(Ci.nsIWebProgress);++ this.QueryInterface = ChromeUtils.generateQI([++ Ci.nsIWebProgressListener,++ Ci.nsIWebProgressListener2,++ Ci.nsISupportsWeakReference,++ ]);++++ const flags = Ci.nsIWebProgress.NOTIFY_STATE_DOCUMENT |++ Ci.nsIWebProgress.NOTIFY_FRAME_LOCATION;++ this._eventListeners = [++ helper.addObserver(subject => this._onDocShellCreated(subject.QueryInterface(Ci.nsIDocShell)), 'webnavigation-create'),++ helper.addObserver(subject => this._onDocShellDestroyed(subject.QueryInterface(Ci.nsIDocShell)), 'webnavigation-destroy'),++ helper.addProgressListener(webProgress, this, flags),++ ];++ }++++ frameForDocShell(docShell) {++ return this._docShellToFrame.get(docShell) || null;++ }++++ frame(frameId) {++ return this._frameIdToFrame.get(frameId) || null;++ }++++ frames() {++ let result = [];++ collect(this._mainFrame);++ return result;++++ function collect(frame) {++ result.push(frame);++ for (const subframe of frame._children)++ collect(subframe);++ }++ }++++ mainFrame() {++ return this._mainFrame;++ }++++ dispose() {++ helper.removeListeners(this._eventListeners);++ }++++ onStateChange(progress, request, flag, status) {++ if (!(request instanceof Ci.nsIChannel))++ return;++ const channel = request.QueryInterface(Ci.nsIChannel);++ const docShell = progress.DOMWindow.docShell;++ const frame = this._docShellToFrame.get(docShell);++ if (!frame) {++ dump(`ERROR: got a state changed event for un-tracked docshell!\n`);++ return;++ }++++ const isStart = flag & Ci.nsIWebProgressListener.STATE_START;++ const isTransferring = flag & Ci.nsIWebProgressListener.STATE_TRANSFERRING;++ const isStop = flag & Ci.nsIWebProgressListener.STATE_STOP;++++ if (isStart) {++ // Starting a new navigation.++ frame._pendingNavigationId = helper.generateId();++ frame._pendingNavigationURL = channel.URI.spec;++ this.emit(FrameTree.Events.NavigationStarted, frame);++ } else if (isTransferring || (isStop && frame._pendingNavigationId && !status)) {++ // Navigation is committed.++ for (const subframe of frame._children)++ this._detachFrame(subframe);++ const navigationId = frame._pendingNavigationId;++ frame._pendingNavigationId = null;++ frame._pendingNavigationURL = null;++ frame._lastCommittedNavigationId = navigationId;++ frame._url = channel.URI.spec;++ this.emit(FrameTree.Events.NavigationCommitted, frame);++ } else if (isStop && frame._pendingNavigationId && status) {++ // Navigation is aborted.++ const navigationId = frame._pendingNavigationId;++ frame._pendingNavigationId = null;++ frame._pendingNavigationURL = null;++ this.emit(FrameTree.Events.NavigationAborted, frame, navigationId, helper.getNetworkErrorStatusText(status));++ }++ }++++ onFrameLocationChange(progress, request, location, flags) {++ const docShell = progress.DOMWindow.docShell;++ const frame = this._docShellToFrame.get(docShell);++ const sameDocumentNavigation = !!(flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT);++ if (frame && sameDocumentNavigation) {++ frame._url = location.spec;++ this.emit(FrameTree.Events.SameDocumentNavigation, frame);++ }++ }++++ _onDocShellCreated(docShell) {++ // Bug 1142752: sometimes, the docshell appears to be immediately++ // destroyed, bailout early to prevent random exceptions.++ if (docShell.isBeingDestroyed())++ return;++ // If this docShell doesn't belong to our frame tree - do nothing.++ let root = docShell;++ while (root.parent)++ root = root.parent;++ if (root === this._mainFrame._docShell)++ this._createFrame(docShell);++ }++++ _createFrame(docShell) {++ const parentFrame = this._docShellToFrame.get(docShell.parent) || null;++ const frame = new Frame(this, docShell, parentFrame);++ this._docShellToFrame.set(docShell, frame);++ this._frameIdToFrame.set(frame.id(), frame);++ this.emit(FrameTree.Events.FrameAttached, frame);++ return frame;++ }++++ _onDocShellDestroyed(docShell) {++ const frame = this._docShellToFrame.get(docShell);++ if (frame)++ this._detachFrame(frame);++ }++++ _detachFrame(frame) {++ // Detach all children first++ for (const subframe of frame._children)++ this._detachFrame(subframe);++ this._docShellToFrame.delete(frame._docShell);++ this._frameIdToFrame.delete(frame.id());++ if (frame._parentFrame)++ frame._parentFrame._children.delete(frame);++ frame._parentFrame = null;++ this.emit(FrameTree.Events.FrameDetached, frame);++ }++}++++FrameTree.Events = {++ FrameAttached: 'frameattached',++ FrameDetached: 'framedetached',++ NavigationStarted: 'navigationstarted',++ NavigationCommitted: 'navigationcommitted',++ NavigationAborted: 'navigationaborted',++ SameDocumentNavigation: 'samedocumentnavigation',++};++++class Frame {++ constructor(frameTree, docShell, parentFrame) {++ this._frameTree = frameTree;++ this._docShell = docShell;++ this._children = new Set();++ this._frameId = helper.generateId();++ this._parentFrame = null;++ this._url = '';++ if (parentFrame) {++ this._parentFrame = parentFrame;++ parentFrame._children.add(this);++ }++++ this._lastCommittedNavigationId = null;++ this._pendingNavigationId = null;++ this._pendingNavigationURL = null;++++ this._textInputProcessor = null;++ }++++ textInputProcessor() {++ if (!this._textInputProcessor) {++ this._textInputProcessor = Cc["@mozilla.org/text-input-processor;1"].createInstance(Ci.nsITextInputProcessor);++ this._textInputProcessor.beginInputTransactionForTests(this._docShell.DOMWindow);++ }++ return this._textInputProcessor;++ }++++ pendingNavigationId() {++ return this._pendingNavigationId;++ }++++ pendingNavigationURL() {++ return this._pendingNavigationURL;++ }++++ lastCommittedNavigationId() {++ return this._lastCommittedNavigationId;++ }++++ docShell() {++ return this._docShell;++ }++++ domWindow() {++ return this._docShell.domWindow;++ }++++ name() {++ const frameElement = this._docShell.domWindow.frameElement;++ let name = '';++ if (frameElement)++ name = frameElement.getAttribute('name') || frameElement.getAttribute('id') || '';++ return name;++ }++++ parentFrame() {++ return this._parentFrame;++ }++++ id() {++ return this._frameId;++ }++++ url() {++ return this._url;++ }++}++++var EXPORTED_SYMBOLS = ['FrameTree'];++this.FrameTree = FrameTree;+++diff --git a/testing/juggler/content/NetworkMonitor.js b/testing/juggler/content/NetworkMonitor.js+new file mode 100644+index 000000000000..2508cce41565+--- /dev/null++++ b/testing/juggler/content/NetworkMonitor.js+@@ -0,0 +1,62 @@++"use strict";++const Ci = Components.interfaces;++const Cr = Components.results;++const Cu = Components.utils;++++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++++const helper = new Helper();++++class NetworkMonitor {++ constructor(rootDocShell, frameTree) {++ this._frameTree = frameTree;++ this._requestDetails = new Map();++++ this._eventListeners = [++ helper.addObserver(this._onRequest.bind(this), 'http-on-opening-request'),++ ];++ }++++ _onRequest(channel) {++ if (!(channel instanceof Ci.nsIHttpChannel))++ return;++ const httpChannel = channel.QueryInterface(Ci.nsIHttpChannel);++ const loadContext = getLoadContext(httpChannel);++ if (!loadContext)++ return;++ const window = loadContext.associatedWindow;++ const frame = this._frameTree.frameForDocShell(window.docShell)++ if (!frame)++ return;++ this._requestDetails.set(httpChannel.channelId, {++ frameId: frame.id(),++ });++ }++++ requestDetails(channelId) {++ return this._requestDetails.get(channelId) || null;++ }++++ dispose() {++ this._requestDetails.clear();++ helper.removeListeners(this._eventListeners);++ }++}++++function getLoadContext(httpChannel) {++ let loadContext = null;++ try {++ if (httpChannel.notificationCallbacks)++ loadContext = httpChannel.notificationCallbacks.getInterface(Ci.nsILoadContext);++ } catch (e) {}++ try {++ if (!loadContext && httpChannel.loadGroup)++ loadContext = httpChannel.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);++ } catch (e) { }++ return loadContext;++}++++++var EXPORTED_SYMBOLS = ['NetworkMonitor'];++this.NetworkMonitor = NetworkMonitor;+++diff --git a/testing/juggler/content/PageAgent.js b/testing/juggler/content/PageAgent.js+new file mode 100644+index 000000000000..e8db4031620e+--- /dev/null++++ b/testing/juggler/content/PageAgent.js+@@ -0,0 +1,621 @@++"use strict";++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++const Ci = Components.interfaces;++const Cr = Components.results;++const Cu = Components.utils;++++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {NetUtil} = ChromeUtils.import('resource://gre/modules/NetUtil.jsm');++++const helper = new Helper();++++class PageAgent {++ constructor(session, runtimeAgent, frameTree, scrollbarManager, networkMonitor) {++ this._session = session;++ this._runtime = runtimeAgent;++ this._frameTree = frameTree;++ this._networkMonitor = networkMonitor;++ this._scrollbarManager = scrollbarManager;++++ this._frameToExecutionContext = new Map();++ this._scriptsToEvaluateOnNewDocument = new Map();++ this._bindingsToAdd = new Set();++++ this._eventListeners = [];++ this._enabled = false;++++ const docShell = frameTree.mainFrame().docShell();++ this._initialDPPX = docShell.contentViewer.overrideDPPX;++ this._customScrollbars = null;++ }++++ async awaitViewportDimensions({width, height}) {++ const win = this._frameTree.mainFrame().domWindow();++ if (win.innerWidth === width && win.innerHeight === height)++ return;++ await new Promise(resolve => {++ const listener = helper.addEventListener(win, 'resize', () => {++ if (win.innerWidth === width && win.innerHeight === height) {++ helper.removeListeners([listener]);++ resolve();++ }++ });++ });++ }++++ requestDetails({channelId}) {++ return this._networkMonitor.requestDetails(channelId);++ }++++ async setViewport({deviceScaleFactor, isMobile, hasTouch}) {++ const docShell = this._frameTree.mainFrame().docShell();++ docShell.contentViewer.overrideDPPX = deviceScaleFactor || this._initialDPPX;++ docShell.deviceSizeIsPageSize = isMobile;++ docShell.touchEventsOverride = hasTouch ? Ci.nsIDocShell.TOUCHEVENTS_OVERRIDE_ENABLED : Ci.nsIDocShell.TOUCHEVENTS_OVERRIDE_NONE;++ this._scrollbarManager.setFloatingScrollbars(isMobile);++ }++++ async setEmulatedMedia({media}) {++ const docShell = this._frameTree.mainFrame().docShell();++ if (media)++ docShell.contentViewer.emulateMedium(media);++ else++ docShell.contentViewer.stopEmulatingMedium();++ }++++ async setUserAgent({userAgent}) {++ const docShell = this._frameTree.mainFrame().docShell();++ docShell.customUserAgent = userAgent;++ }++++ addScriptToEvaluateOnNewDocument({script}) {++ const scriptId = helper.generateId();++ this._scriptsToEvaluateOnNewDocument.set(scriptId, script);++ return {scriptId};++ }++++ removeScriptToEvaluateOnNewDocument({scriptId}) {++ this._scriptsToEvaluateOnNewDocument.delete(scriptId);++ }++++ setCacheDisabled({cacheDisabled}) {++ const enable = Ci.nsIRequest.LOAD_NORMAL;++ const disable = Ci.nsIRequest.LOAD_BYPASS_CACHE |++ Ci.nsIRequest.INHIBIT_CACHING;++++ const docShell = this._frameTree.mainFrame().docShell();++ docShell.defaultLoadFlags = cacheDisabled ? disable : enable;++ }++++ setJavascriptEnabled({enabled}) {++ const docShell = this._frameTree.mainFrame().docShell();++ docShell.allowJavascript = enabled;++ }++++ enable() {++ if (this._enabled)++ return;++++ this._enabled = true;++ // Dispatch frameAttached events for all initial frames++ for (const frame of this._frameTree.frames()) {++ this._onFrameAttached(frame);++ if (frame.url())++ this._onNavigationCommitted(frame);++ if (frame.pendingNavigationId())++ this._onNavigationStarted(frame);++ }++ this._eventListeners = [++ helper.addObserver(this._onDOMWindowCreated.bind(this), 'content-document-global-created'),++ helper.addEventListener(this._session.mm(), 'DOMContentLoaded', this._onDOMContentLoaded.bind(this)),++ helper.addEventListener(this._session.mm(), 'pageshow', this._onLoad.bind(this)),++ helper.addEventListener(this._session.mm(), 'error', this._onError.bind(this)),++ helper.on(this._frameTree, 'frameattached', this._onFrameAttached.bind(this)),++ helper.on(this._frameTree, 'framedetached', this._onFrameDetached.bind(this)),++ helper.on(this._frameTree, 'navigationstarted', this._onNavigationStarted.bind(this)),++ helper.on(this._frameTree, 'navigationcommitted', this._onNavigationCommitted.bind(this)),++ helper.on(this._frameTree, 'navigationaborted', this._onNavigationAborted.bind(this)),++ helper.on(this._frameTree, 'samedocumentnavigation', this._onSameDocumentNavigation.bind(this)),++ ];++ }++++ _onDOMContentLoaded(event) {++ const docShell = event.target.ownerGlobal.docShell;++ const frame = this._frameTree.frameForDocShell(docShell);++ if (!frame)++ return;++ this._session.emitEvent('Page.eventFired', {++ frameId: frame.id(),++ name: 'DOMContentLoaded',++ });++ }++++ _onError(errorEvent) {++ const docShell = errorEvent.target.ownerGlobal.docShell;++ const frame = this._frameTree.frameForDocShell(docShell);++ if (!frame)++ return;++ this._session.emitEvent('Page.uncaughtError', {++ frameId: frame.id(),++ message: errorEvent.message,++ stack: errorEvent.error.stack++ });++ }++++ _onLoad(event) {++ const docShell = event.target.ownerGlobal.docShell;++ const frame = this._frameTree.frameForDocShell(docShell);++ if (!frame)++ return;++ this._session.emitEvent('Page.eventFired', {++ frameId: frame.id(),++ name: 'load'++ });++ }++++ _onNavigationStarted(frame) {++ this._session.emitEvent('Page.navigationStarted', {++ frameId: frame.id(),++ navigationId: frame.pendingNavigationId(),++ url: frame.pendingNavigationURL(),++ });++ }++++ _onNavigationAborted(frame, navigationId, errorText) {++ this._session.emitEvent('Page.navigationAborted', {++ frameId: frame.id(),++ navigationId,++ errorText,++ });++ }++++ _onSameDocumentNavigation(frame) {++ this._session.emitEvent('Page.sameDocumentNavigation', {++ frameId: frame.id(),++ url: frame.url(),++ });++ }++++ _onNavigationCommitted(frame) {++ this._session.emitEvent('Page.navigationCommitted', {++ frameId: frame.id(),++ navigationId: frame.lastCommittedNavigationId(),++ url: frame.url(),++ name: frame.name(),++ });++ }++++ _onDOMWindowCreated(window) {++ const docShell = window.docShell;++ const frame = this._frameTree.frameForDocShell(docShell);++ if (!frame)++ return;++++ if (this._frameToExecutionContext.has(frame)) {++ this._runtime.destroyExecutionContext(this._frameToExecutionContext.get(frame));++ this._frameToExecutionContext.delete(frame);++ }++ const executionContext = this._ensureExecutionContext(frame);++++ if (!this._scriptsToEvaluateOnNewDocument.size && !this._bindingsToAdd.size)++ return;++ for (const bindingName of this._bindingsToAdd.values())++ this._exposeFunction(frame, bindingName);++ for (const script of this._scriptsToEvaluateOnNewDocument.values()) {++ try {++ let result = executionContext.evaluateScript(script);++ if (result && result.objectId)++ executionContext.disposeObject(result.objectId);++ } catch (e) {++ }++ }++ }++++ _onFrameAttached(frame) {++ this._session.emitEvent('Page.frameAttached', {++ frameId: frame.id(),++ parentFrameId: frame.parentFrame() ? frame.parentFrame().id() : undefined,++ });++ this._ensureExecutionContext(frame);++ }++++ _onFrameDetached(frame) {++ this._session.emitEvent('Page.frameDetached', {++ frameId: frame.id(),++ });++ }++++ _ensureExecutionContext(frame) {++ let executionContext = this._frameToExecutionContext.get(frame);++ if (!executionContext) {++ executionContext = this._runtime.createExecutionContext(frame.domWindow(), {++ frameId: frame.id(),++ });++ this._frameToExecutionContext.set(frame, executionContext);++ }++ return executionContext;++ }++++ dispose() {++ helper.removeListeners(this._eventListeners);++ }++++ async navigate({frameId, url, referer}) {++ try {++ const uri = NetUtil.newURI(url);++ } catch (e) {++ throw new Error(`Invalid url: "${url}"`);++ }++ let referrerURI = null;++ let referrerInfo = null;++ if (referer) {++ try {++ referrerURI = NetUtil.newURI(referer);++ const ReferrerInfo = Components.Constructor(++ '@mozilla.org/referrer-info;1',++ 'nsIReferrerInfo',++ 'init'++ );++ referrerInfo = new ReferrerInfo(Ci.nsIHttpChannel.REFERRER_POLICY_UNSET, true, referrerURI);++ } catch (e) {++ throw new Error(`Invalid referer: "${referer}"`);++ }++ }++ const frame = this._frameTree.frame(frameId);++ const docShell = frame.docShell().QueryInterface(Ci.nsIWebNavigation);++ docShell.loadURI(url, {++ flags: Ci.nsIWebNavigation.LOAD_FLAGS_NONE,++ referrerInfo,++ postData: null,++ headers: null,++ });++ return {navigationId: frame.pendingNavigationId(), navigationURL: frame.pendingNavigationURL()};++ }++++ async reload({frameId, url}) {++ const frame = this._frameTree.frame(frameId);++ const docShell = frame.docShell().QueryInterface(Ci.nsIWebNavigation);++ docShell.reload(Ci.nsIWebNavigation.LOAD_FLAGS_NONE);++ return {navigationId: frame.pendingNavigationId(), navigationURL: frame.pendingNavigationURL()};++ }++++ async goBack({frameId, url}) {++ const frame = this._frameTree.frame(frameId);++ const docShell = frame.docShell();++ if (!docShell.canGoBack)++ return {navigationId: null, navigationURL: null};++ docShell.goBack();++ return {navigationId: frame.pendingNavigationId(), navigationURL: frame.pendingNavigationURL()};++ }++++ async goForward({frameId, url}) {++ const frame = this._frameTree.frame(frameId);++ const docShell = frame.docShell();++ if (!docShell.canGoForward)++ return {navigationId: null, navigationURL: null};++ docShell.goForward();++ return {navigationId: frame.pendingNavigationId(), navigationURL: frame.pendingNavigationURL()};++ }++++ addBinding({name}) {++ if (this._bindingsToAdd.has(name))++ throw new Error(`Binding with name ${name} already exists`);++ this._bindingsToAdd.add(name);++ for (const frame of this._frameTree.frames())++ this._exposeFunction(frame, name);++ }++++ _exposeFunction(frame, name) {++ Cu.exportFunction((...args) => {++ const executionContext = this._ensureExecutionContext(frame);++ this._session.emitEvent('Page.bindingCalled', {++ executionContextId: executionContext.id(),++ name,++ payload: args[0]++ });++ }, frame.domWindow(), {++ defineAs: name,++ });++ }++++ async setFileInputFiles({objectId, frameId, files}) {++ const frame = this._frameTree.frame(frameId);++ if (!frame)++ throw new Error('Failed to find frame with id = ' + frameId);++ const executionContext = this._ensureExecutionContext(frame);++ const unsafeObject = executionContext.unsafeObject(objectId);++ if (!unsafeObject)++ throw new Error('Object is not input!');++ const nsFiles = await Promise.all(files.map(filePath => File.createFromFileName(filePath)));++ unsafeObject.mozSetFileArray(nsFiles);++ }++++ getContentQuads({objectId, frameId}) {++ const frame = this._frameTree.frame(frameId);++ if (!frame)++ throw new Error('Failed to find frame with id = ' + frameId);++ const executionContext = this._ensureExecutionContext(frame);++ const unsafeObject = executionContext.unsafeObject(objectId);++ if (!unsafeObject.getBoxQuads)++ throw new Error('RemoteObject is not a node');++ const quads = unsafeObject.getBoxQuads({relativeTo: this._frameTree.mainFrame().domWindow().document}).map(quad => {++ return {++ p1: {x: quad.p1.x, y: quad.p1.y},++ p2: {x: quad.p2.x, y: quad.p2.y},++ p3: {x: quad.p3.x, y: quad.p3.y},++ p4: {x: quad.p4.x, y: quad.p4.y},++ };++ });++ return {quads};++ }++++ contentFrame({objectId, frameId}) {++ const frame = this._frameTree.frame(frameId);++ if (!frame)++ throw new Error('Failed to find frame with id = ' + frameId);++ const executionContext = this._ensureExecutionContext(frame);++ const unsafeObject = executionContext.unsafeObject(objectId);++ if (!unsafeObject.contentWindow)++ return null;++ const contentFrame = this._frameTree.frameForDocShell(unsafeObject.contentWindow.docShell);++ return {frameId: contentFrame.id()};++ }++++ async getBoundingBox({frameId, objectId}) {++ const frame = this._frameTree.frame(frameId);++ if (!frame)++ throw new Error('Failed to find frame with id = ' + frameId);++ const executionContext = this._ensureExecutionContext(frame);++ const unsafeObject = executionContext.unsafeObject(objectId);++ if (!unsafeObject.getBoxQuads)++ throw new Error('RemoteObject is not a node');++ const quads = unsafeObject.getBoxQuads({relativeTo: this._frameTree.mainFrame().domWindow().document});++ if (!quads.length)++ return null;++ let x1 = Infinity;++ let y1 = Infinity;++ let x2 = -Infinity;++ let y2 = -Infinity;++ for (const quad of quads) {++ const boundingBox = quad.getBounds();++ x1 = Math.min(boundingBox.x, x1);++ y1 = Math.min(boundingBox.y, y1);++ x2 = Math.max(boundingBox.x + boundingBox.width, x2);++ y2 = Math.max(boundingBox.y + boundingBox.height, y2);++ }++ return {x: x1 + frame.domWindow().scrollX, y: y1 + frame.domWindow().scrollY, width: x2 - x1, height: y2 - y1};++ }++++ async screenshot({mimeType, fullPage, clip}) {++ const content = this._session.mm().content;++ if (clip) {++ const data = takeScreenshot(content, clip.x, clip.y, clip.width, clip.height, mimeType);++ return {data};++ }++ if (fullPage) {++ const rect = content.document.documentElement.getBoundingClientRect();++ const width = content.innerWidth + content.scrollMaxX - content.scrollMinX;++ const height = content.innerHeight + content.scrollMaxY - content.scrollMinY;++ const data = takeScreenshot(content, 0, 0, width, height, mimeType);++ return {data};++ }++ const data = takeScreenshot(content, content.scrollX, content.scrollY, content.innerWidth, content.innerHeight, mimeType);++ return {data};++ }++++ async dispatchKeyEvent({type, keyCode, code, key, repeat, location}) {++ const frame = this._frameTree.mainFrame();++ const tip = frame.textInputProcessor();++ if (key === 'Meta' && Services.appinfo.OS !== 'Darwin')++ key = 'OS';++ else if (key === 'OS' && Services.appinfo.OS === 'Darwin')++ key = 'Meta';++ let keyEvent = new (frame.domWindow().KeyboardEvent)("", {++ key,++ code,++ location,++ repeat,++ keyCode++ });++ const flags = 0;++ if (type === 'keydown')++ tip.keydown(keyEvent, flags);++ else if (type === 'keyup')++ tip.keyup(keyEvent, flags);++ else++ throw new Error(`Unknown type ${type}`);++ }++++ async dispatchTouchEvent({type, touchPoints, modifiers}) {++ const frame = this._frameTree.mainFrame();++ const defaultPrevented = frame.domWindow().windowUtils.sendTouchEvent(++ type.toLowerCase(),++ touchPoints.map((point, id) => id),++ touchPoints.map(point => point.x),++ touchPoints.map(point => point.y),++ touchPoints.map(point => point.radiusX === undefined ? 1.0 : point.radiusX),++ touchPoints.map(point => point.radiusY === undefined ? 1.0 : point.radiusY),++ touchPoints.map(point => point.rotationAngle === undefined ? 0.0 : point.rotationAngle),++ touchPoints.map(point => point.force === undefined ? 1.0 : point.force),++ touchPoints.length,++ modifiers);++ return {defaultPrevented};++ }++++ async dispatchMouseEvent({type, x, y, button, clickCount, modifiers, buttons}) {++ const frame = this._frameTree.mainFrame();++ frame.domWindow().windowUtils.sendMouseEvent(++ type,++ x,++ y,++ button,++ clickCount,++ modifiers,++ false /*aIgnoreRootScrollFrame*/,++ undefined /*pressure*/,++ undefined /*inputSource*/,++ undefined /*isDOMEventSynthesized*/,++ undefined /*isWidgetEventSynthesized*/,++ buttons);++ if (type === 'mousedown' && button === 2) {++ frame.domWindow().windowUtils.sendMouseEvent(++ 'contextmenu',++ x,++ y,++ button,++ clickCount,++ modifiers,++ false /*aIgnoreRootScrollFrame*/,++ undefined /*pressure*/,++ undefined /*inputSource*/,++ undefined /*isDOMEventSynthesized*/,++ undefined /*isWidgetEventSynthesized*/,++ buttons);++ }++ }++++ async insertText({text}) {++ const frame = this._frameTree.mainFrame();++ frame.textInputProcessor().commitCompositionWith(text);++ }++++ async getFullAXTree() {++ const service = Cc["@mozilla.org/accessibilityService;1"]++ .getService(Ci.nsIAccessibilityService);++ const document = this._frameTree.mainFrame().domWindow().document;++ const docAcc = service.getAccessibleFor(document);++++ async function waitForQuiet() {++ let state = {};++ docAcc.getState(state, {});++ if ((state.value & Ci.nsIAccessibleStates.STATE_BUSY) == 0)++ return;++ let resolve, reject;++ const promise = new Promise((x, y) => {resolve = x, reject = y});++ let eventObserver = {++ observe(subject, topic) {++ if (topic !== "accessible-event") {++ return;++ }++++ // If event type does not match expected type, skip the event.++ let event = subject.QueryInterface(Ci.nsIAccessibleEvent);++ if (event.eventType !== Ci.nsIAccessibleEvent.EVENT_STATE_CHANGE) {++ return;++ }++++ // If event's accessible does not match expected accessible,++ // skip the event.++ if (event.accessible !== docAcc) {++ return;++ }++++ Services.obs.removeObserver(this, "accessible-event");++ resolve();++ },++ };++ Services.obs.addObserver(eventObserver, "accessible-event");++ return promise;++ }++ function buildNode(accElement) {++ let a = {}, b = {};++ accElement.getState(a, b);++ const tree = {++ role: service.getStringRole(accElement.role),++ name: accElement.name || '',++ };++ for (const userStringProperty of [++ 'value',++ 'description'++ ]) {++ tree[userStringProperty] = accElement[userStringProperty] || undefined;++ }++++ const states = {};++ for (const name of service.getStringStates(a.value, b.value))++ states[name] = true;++ for (const name of ['selected',++ 'focused',++ 'pressed',++ 'focusable',++ 'haspopup',++ 'required',++ 'invalid',++ 'modal',++ 'editable',++ 'busy',++ 'checked',++ 'multiselectable']) {++ if (states[name])++ tree[name] = true;++ }++++ if (states['multi line'])++ tree['multiline'] = true;++ if (states['editable'] && states['readonly'])++ tree['readonly'] = true;++ if (states['checked'])++ tree['checked'] = true;++ if (states['mixed'])++ tree['checked'] = 'mixed';++ if (states['expanded'])++ tree['expanded'] = true;++ else if (states['collapsed'])++ tree['expanded'] = false++ if (!states['enabled'])++ tree['disabled'] = true;++++ const attributes = {};++ if (accElement.attributes) {++ for (const { key, value } of accElement.attributes.enumerate()) {++ attributes[key] = value;++ }++ }++ for (const numericalProperty of ['level']) {++ if (numericalProperty in attributes)++ tree[numericalProperty] = parseFloat(attributes[numericalProperty]);++ }++ for (const stringProperty of ['tag', 'roledescription', 'valuetext', 'orientation', 'autocomplete', 'keyshortcuts']) {++ if (stringProperty in attributes)++ tree[stringProperty] = attributes[stringProperty];++ }++ const children = [];++++ for (let child = accElement.firstChild; child; child = child.nextSibling) {++ children.push(buildNode(child));++ }++ if (children.length)++ tree.children = children;++ return tree;++ }++ await waitForQuiet();++ return {++ tree: buildNode(docAcc)++ };++ }++}++++function takeScreenshot(win, left, top, width, height, mimeType) {++ const MAX_SKIA_DIMENSIONS = 32767;++++ const scale = win.devicePixelRatio;++ const canvasWidth = width * scale;++ const canvasHeight = height * scale;++++ if (canvasWidth > MAX_SKIA_DIMENSIONS || canvasHeight > MAX_SKIA_DIMENSIONS)++ throw new Error('Cannot take screenshot larger than ' + MAX_SKIA_DIMENSIONS);++++ const canvas = win.document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');++ canvas.width = canvasWidth;++ canvas.height = canvasHeight;++++ let ctx = canvas.getContext('2d');++ ctx.scale(scale, scale);++ ctx.drawWindow(win, left, top, width, height, 'rgb(255,255,255)', ctx.DRAWWINDOW_DRAW_CARET);++ const dataURL = canvas.toDataURL(mimeType);++ return dataURL.substring(dataURL.indexOf(',') + 1);++};++++var EXPORTED_SYMBOLS = ['PageAgent'];++this.PageAgent = PageAgent;+++diff --git a/testing/juggler/content/RuntimeAgent.js b/testing/juggler/content/RuntimeAgent.js+new file mode 100644+index 000000000000..2c474230071b+--- /dev/null++++ b/testing/juggler/content/RuntimeAgent.js+@@ -0,0 +1,460 @@++"use strict";++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {addDebuggerToGlobal} = ChromeUtils.import("resource://gre/modules/jsdebugger.jsm", {});++++const Ci = Components.interfaces;++const Cr = Components.results;++const Cu = Components.utils;++addDebuggerToGlobal(Cu.getGlobalForObject(this));++const helper = new Helper();++++const consoleLevelToProtocolType = {++ 'dir': 'dir',++ 'log': 'log',++ 'debug': 'debug',++ 'info': 'info',++ 'error': 'error',++ 'warn': 'warning',++ 'dirxml': 'dirxml',++ 'table': 'table',++ 'trace': 'trace',++ 'clear': 'clear',++ 'group': 'startGroup',++ 'groupCollapsed': 'startGroupCollapsed',++ 'groupEnd': 'endGroup',++ 'assert': 'assert',++ 'profile': 'profile',++ 'profileEnd': 'profileEnd',++ 'count': 'count',++ 'countReset': 'countReset',++ 'time': null,++ 'timeLog': 'timeLog',++ 'timeEnd': 'timeEnd',++ 'timeStamp': 'timeStamp',++};++++const disallowedMessageCategories = new Set([++ 'XPConnect JavaScript',++ 'component javascript',++ 'chrome javascript',++ 'chrome registration',++ 'XBL',++ 'XBL Prototype Handler',++ 'XBL Content Sink',++ 'xbl javascript',++]);++++class RuntimeAgent {++ constructor(session) {++ this._debugger = new Debugger();++ this._pendingPromises = new Map();++ this._session = session;++ this._executionContexts = new Map();++ this._windowToExecutionContext = new Map();++ this._consoleServiceListener = {++ QueryInterface: ChromeUtils.generateQI([Ci.nsIConsoleListener]),++++ observe: message => {++ if (!(message instanceof Ci.nsIScriptError) || !message.outerWindowID ||++ !message.category || disallowedMessageCategories.has(message.category)) {++ return;++ }++ const errorWindow = Services.wm.getOuterWindowWithId(message.outerWindowID);++ const executionContext = this._windowToExecutionContext.get(errorWindow);++ if (!executionContext)++ return;++ const typeNames = {++ [Ci.nsIConsoleMessage.debug]: 'debug',++ [Ci.nsIConsoleMessage.info]: 'info',++ [Ci.nsIConsoleMessage.warn]: 'warn',++ [Ci.nsIConsoleMessage.error]: 'error',++ };++ this._session.emitEvent('Runtime.console', {++ args: [{++ value: message.message,++ }],++ type: typeNames[message.logLevel],++ executionContextId: executionContext.id(),++ location: {++ lineNumber: message.lineNumber,++ columnNumber: message.columnNumber,++ url: message.sourceName,++ },++ });++ },++ };++++ this._eventListeners = [];++ this._enabled = false;++ }++++ _consoleAPICalled({wrappedJSObject}, topic, data) {++ const type = consoleLevelToProtocolType[wrappedJSObject.level];++ if (!type)++ return;++ const executionContext = Array.from(this._executionContexts.values()).find(context => {++ const domWindow = context._domWindow;++ return domWindow && domWindow.windowUtils.currentInnerWindowID === wrappedJSObject.innerID;++ });++ if (!executionContext)++ return;++ const args = wrappedJSObject.arguments.map(arg => executionContext.rawValueToRemoteObject(arg));++ this._session.emitEvent('Runtime.console', {++ args,++ type,++ executionContextId: executionContext.id(),++ location: {++ lineNumber: wrappedJSObject.lineNumber - 1,++ columnNumber: wrappedJSObject.columnNumber - 1,++ url: wrappedJSObject.filename,++ },++ });++ }++++ enable() {++ if (this._enabled)++ return;++ this._enabled = true;++ for (const executionContext of this._executionContexts.values())++ this._notifyExecutionContextCreated(executionContext);++ Services.console.registerListener(this._consoleServiceListener);++ this._eventListeners = [++ () => Services.console.unregisterListener(this._consoleServiceListener),++ helper.addObserver(this._consoleAPICalled.bind(this), "console-api-log-event"),++ ];++ }++++ _notifyExecutionContextCreated(executionContext) {++ if (!this._enabled)++ return;++ this._session.emitEvent('Runtime.executionContextCreated', {++ executionContextId: executionContext._id,++ auxData: executionContext._auxData,++ });++ }++++ _notifyExecutionContextDestroyed(executionContext) {++ if (!this._enabled)++ return;++ this._session.emitEvent('Runtime.executionContextDestroyed', {++ executionContextId: executionContext._id,++ });++ }++++ dispose() {++ helper.removeListeners(this._eventListeners);++ }++++ async _awaitPromise(executionContext, obj, exceptionDetails = {}) {++ if (obj.promiseState === 'fulfilled')++ return {success: true, obj: obj.promiseValue};++ if (obj.promiseState === 'rejected') {++ const global = executionContext._global;++ exceptionDetails.text = global.executeInGlobalWithBindings('e.message', {e: obj.promiseReason}).return;++ exceptionDetails.stack = global.executeInGlobalWithBindings('e.stack', {e: obj.promiseReason}).return;++ return {success: false, obj: null};++ }++ let resolve, reject;++ const promise = new Promise((a, b) => {++ resolve = a;++ reject = b;++ });++ this._pendingPromises.set(obj.promiseID, {resolve, reject, executionContext, exceptionDetails});++ if (this._pendingPromises.size === 1)++ this._debugger.onPromiseSettled = this._onPromiseSettled.bind(this);++ return await promise;++ }++++ _onPromiseSettled(obj) {++ const pendingPromise = this._pendingPromises.get(obj.promiseID);++ if (!pendingPromise)++ return;++ this._pendingPromises.delete(obj.promiseID);++ if (!this._pendingPromises.size)++ this._debugger.onPromiseSettled = undefined;++++ if (obj.promiseState === 'fulfilled') {++ pendingPromise.resolve({success: true, obj: obj.promiseValue});++ return;++ };++ const global = pendingPromise.executionContext._global;++ pendingPromise.exceptionDetails.text = global.executeInGlobalWithBindings('e.message', {e: obj.promiseReason}).return;++ pendingPromise.exceptionDetails.stack = global.executeInGlobalWithBindings('e.stack', {e: obj.promiseReason}).return;++ pendingPromise.resolve({success: false, obj: null});++ }++++ createExecutionContext(domWindow, auxData) {++ const context = new ExecutionContext(this, domWindow, this._debugger.addDebuggee(domWindow), auxData);++ this._executionContexts.set(context._id, context);++ this._windowToExecutionContext.set(domWindow, context);++ this._notifyExecutionContextCreated(context);++ return context;++ }++++ destroyExecutionContext(destroyedContext) {++ for (const [promiseID, {reject, executionContext}] of this._pendingPromises) {++ if (executionContext === destroyedContext) {++ reject(new Error('Execution context was destroyed!'));++ this._pendingPromises.delete(promiseID);++ }++ }++ if (!this._pendingPromises.size)++ this._debugger.onPromiseSettled = undefined;++ this._debugger.removeDebuggee(destroyedContext._domWindow);++ this._executionContexts.delete(destroyedContext._id);++ this._windowToExecutionContext.delete(destroyedContext._domWindow);++ this._notifyExecutionContextDestroyed(destroyedContext);++ }++++ async evaluate({executionContextId, expression, returnByValue}) {++ const executionContext = this._executionContexts.get(executionContextId);++ if (!executionContext)++ throw new Error('Failed to find execution context with id = ' + executionContextId);++ const exceptionDetails = {};++ let result = await executionContext.evaluateScript(expression, exceptionDetails);++ if (!result)++ return {exceptionDetails};++ let isNode = undefined;++ if (returnByValue)++ result = executionContext.ensureSerializedToValue(result);++ return {result};++ }++++ async callFunction({executionContextId, functionDeclaration, args, returnByValue}) {++ const executionContext = this._executionContexts.get(executionContextId);++ if (!executionContext)++ throw new Error('Failed to find execution context with id = ' + executionContextId);++ const exceptionDetails = {};++ let result = await executionContext.evaluateFunction(functionDeclaration, args, exceptionDetails);++ if (!result)++ return {exceptionDetails};++ let isNode = undefined;++ if (returnByValue)++ result = executionContext.ensureSerializedToValue(result);++ return {result};++ }++++ async getObjectProperties({executionContextId, objectId}) {++ const executionContext = this._executionContexts.get(executionContextId);++ if (!executionContext)++ throw new Error('Failed to find execution context with id = ' + executionContextId);++ return {properties: executionContext.getObjectProperties(objectId)};++ }++++ async disposeObject({executionContextId, objectId}) {++ const executionContext = this._executionContexts.get(executionContextId);++ if (!executionContext)++ throw new Error('Failed to find execution context with id = ' + executionContextId);++ return executionContext.disposeObject(objectId);++ }++}++++class ExecutionContext {++ constructor(runtime, domWindow, global, auxData) {++ this._runtime = runtime;++ this._domWindow = domWindow;++ this._global = global;++ this._remoteObjects = new Map();++ this._id = helper.generateId();++ this._auxData = auxData;++ }++++ id() {++ return this._id;++ }++++ async evaluateScript(script, exceptionDetails = {}) {++ const userInputHelper = this._domWindow.windowUtils.setHandlingUserInput(true);++ let {success, obj} = this._getResult(this._global.executeInGlobal(script), exceptionDetails);++ userInputHelper.destruct();++ if (!success)++ return null;++ if (obj && obj.isPromise) {++ const awaitResult = await this._runtime._awaitPromise(this, obj, exceptionDetails);++ if (!awaitResult.success)++ return null;++ obj = awaitResult.obj;++ }++ return this._createRemoteObject(obj);++ }++++ async evaluateFunction(functionText, args, exceptionDetails = {}) {++ const funEvaluation = this._getResult(this._global.executeInGlobal('(' + functionText + ')'), exceptionDetails);++ if (!funEvaluation.success)++ return null;++ if (!funEvaluation.obj.callable)++ throw new Error('functionText does not evaluate to a function!');++ args = args.map(arg => {++ if (arg.objectId) {++ if (!this._remoteObjects.has(arg.objectId))++ throw new Error('Cannot find object with id = ' + arg.objectId);++ return this._remoteObjects.get(arg.objectId);++ }++ switch (arg.unserializableValue) {++ case 'Infinity': return Infinity;++ case '-Infinity': return -Infinity;++ case '-0': return -0;++ case 'NaN': return NaN;++ default: return this._toDebugger(arg.value);++ }++ });++ const userInputHelper = this._domWindow.windowUtils.setHandlingUserInput(true);++ let {success, obj} = this._getResult(funEvaluation.obj.apply(null, args), exceptionDetails);++ userInputHelper.destruct();++ if (!success)++ return null;++ if (obj && obj.isPromise) {++ const awaitResult = await this._runtime._awaitPromise(this, obj, exceptionDetails);++ if (!awaitResult.success)++ return null;++ obj = awaitResult.obj;++ }++ return this._createRemoteObject(obj);++ }++++ unsafeObject(objectId) {++ if (!this._remoteObjects.has(objectId))++ throw new Error('Cannot find object with id = ' + objectId);++ return this._remoteObjects.get(objectId).unsafeDereference();++ }++++ rawValueToRemoteObject(rawValue) {++ const debuggerObj = this._global.makeDebuggeeValue(rawValue);++ return this._createRemoteObject(debuggerObj);++ }++++ _createRemoteObject(debuggerObj) {++ if (debuggerObj instanceof Debugger.Object) {++ const objectId = helper.generateId();++ this._remoteObjects.set(objectId, debuggerObj);++ const rawObj = debuggerObj.unsafeDereference();++ const type = typeof rawObj;++ let subtype = undefined;++ if (debuggerObj.isProxy)++ subtype = 'proxy';++ else if (Array.isArray(rawObj))++ subtype = 'array';++ else if (Object.is(rawObj, null))++ subtype = 'null';++ else if (rawObj instanceof this._domWindow.Node)++ subtype = 'node';++ else if (rawObj instanceof this._domWindow.RegExp)++ subtype = 'regexp';++ else if (rawObj instanceof this._domWindow.Date)++ subtype = 'date';++ else if (rawObj instanceof this._domWindow.Map)++ subtype = 'map';++ else if (rawObj instanceof this._domWindow.Set)++ subtype = 'set';++ else if (rawObj instanceof this._domWindow.WeakMap)++ subtype = 'weakmap';++ else if (rawObj instanceof this._domWindow.WeakSet)++ subtype = 'weakset';++ else if (rawObj instanceof this._domWindow.Error)++ subtype = 'error';++ else if (rawObj instanceof this._domWindow.Promise)++ subtype = 'promise';++ else if ((rawObj instanceof this._domWindow.Int8Array) || (rawObj instanceof this._domWindow.Uint8Array) ||++ (rawObj instanceof this._domWindow.Uint8ClampedArray) || (rawObj instanceof this._domWindow.Int16Array) ||++ (rawObj instanceof this._domWindow.Uint16Array) || (rawObj instanceof this._domWindow.Int32Array) ||++ (rawObj instanceof this._domWindow.Uint32Array) || (rawObj instanceof this._domWindow.Float32Array) ||++ (rawObj instanceof this._domWindow.Float64Array)) {++ subtype = 'typedarray';++ }++ const isNode = debuggerObj.unsafeDereference() instanceof this._domWindow.Node;++ return {objectId, type, subtype};++ }++ if (typeof debuggerObj === 'symbol') {++ const objectId = helper.generateId();++ this._remoteObjects.set(objectId, debuggerObj);++ return {objectId, type: 'symbol'};++ }++++ let unserializableValue = undefined;++ if (Object.is(debuggerObj, NaN))++ unserializableValue = 'NaN';++ else if (Object.is(debuggerObj, -0))++ unserializableValue = '-0';++ else if (Object.is(debuggerObj, Infinity))++ unserializableValue = 'Infinity';++ else if (Object.is(debuggerObj, -Infinity))++ unserializableValue = '-Infinity';++ return unserializableValue ? {unserializableValue} : {value: debuggerObj};++ }++++ ensureSerializedToValue(protocolObject) {++ if (!protocolObject.objectId)++ return protocolObject;++ const obj = this._remoteObjects.get(protocolObject.objectId);++ this._remoteObjects.delete(protocolObject.objectId);++ return {value: this._serialize(obj)};++ }++++ _toDebugger(obj) {++ if (typeof obj !== 'object')++ return obj;++ const properties = {};++ for (let [key, value] of Object.entries(obj)) {++ properties[key] = {++ writable: true,++ enumerable: true,++ value: this._toDebugger(value),++ };++ }++ const baseObject = Array.isArray(obj) ? '([])' : '({})';++ const debuggerObj = this._global.executeInGlobal(baseObject).return;++ debuggerObj.defineProperties(properties);++ return debuggerObj;++ }++++ _serialize(obj) {++ const result = this._global.executeInGlobalWithBindings('JSON.stringify(e)', {e: obj});++ if (result.throw)++ throw new Error('Object is not serializable');++ return JSON.parse(result.return);++ }++++ disposeObject(objectId) {++ this._remoteObjects.delete(objectId);++ }++++ getObjectProperties(objectId) {++ if (!this._remoteObjects.has(objectId))++ throw new Error('Cannot find object with id = ' + arg.objectId);++ const result = [];++ for (let obj = this._remoteObjects.get(objectId); obj; obj = obj.proto) {++ for (const propertyName of obj.getOwnPropertyNames()) {++ const descriptor = obj.getOwnPropertyDescriptor(propertyName);++ if (!descriptor.enumerable)++ continue;++ result.push({++ name: propertyName,++ value: this._createRemoteObject(descriptor.value),++ });++ }++ }++ return result;++ }++++ _getResult(completionValue, exceptionDetails = {}) {++ if (!completionValue) {++ exceptionDetails.text = 'Evaluation terminated!';++ exceptionDetails.stack = '';++ return {success: false, obj: null};++ }++ if (completionValue.throw) {++ if (this._global.executeInGlobalWithBindings('e instanceof Error', {e: completionValue.throw}).return) {++ exceptionDetails.text = this._global.executeInGlobalWithBindings('e.message', {e: completionValue.throw}).return;++ exceptionDetails.stack = this._global.executeInGlobalWithBindings('e.stack', {e: completionValue.throw}).return;++ } else {++ exceptionDetails.value = this._serialize(completionValue.throw);++ }++ return {success: false, obj: null};++ }++ return {success: true, obj: completionValue.return};++ }++}++++var EXPORTED_SYMBOLS = ['RuntimeAgent'];++this.RuntimeAgent = RuntimeAgent;+diff --git a/testing/juggler/content/ScrollbarManager.js b/testing/juggler/content/ScrollbarManager.js+new file mode 100644+index 000000000000..caee4df323d0+--- /dev/null++++ b/testing/juggler/content/ScrollbarManager.js+@@ -0,0 +1,85 @@++const Ci = Components.interfaces;++const Cr = Components.results;++const Cu = Components.utils;++const Cc = Components.classes;++++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++++const HIDDEN_SCROLLBARS = Services.io.newURI('chrome://juggler/content/content/hidden-scrollbars.css');++const FLOATING_SCROLLBARS = Services.io.newURI('chrome://juggler/content/content/floating-scrollbars.css');++++const isHeadless = Cc["@mozilla.org/gfx/info;1"].getService(Ci.nsIGfxInfo).isHeadless;++const helper = new Helper();++++class ScrollbarManager {++ constructor(docShell) {++ this._docShell = docShell;++ this._customScrollbars = null;++ this._contentViewerScrollBars = new Map();++++ if (isHeadless)++ this._setCustomScrollbars(HIDDEN_SCROLLBARS);++++ const webProgress = this._docShell.QueryInterface(Ci.nsIInterfaceRequestor)++ .getInterface(Ci.nsIWebProgress);++++ this.QueryInterface = ChromeUtils.generateQI(['nsIWebProgressListener', 'nsISupportsWeakReference']);++ this._eventListeners = [++ helper.addProgressListener(webProgress, this, Ci.nsIWebProgress.NOTIFY_ALL),++ ];++ }++++ onLocationChange(webProgress, request, URI, flags) {++ if (flags & Ci.nsIWebProgressListener.LOCATION_CHANGE_SAME_DOCUMENT)++ return;++ this._updateAllDocShells();++ }++++ setFloatingScrollbars(enabled) {++ if (this._customScrollbars === HIDDEN_SCROLLBARS)++ return;++ this._setCustomScrollbars(enabled ? FLOATING_SCROLLBARS : null);++ }++++ _setCustomScrollbars(customScrollbars) {++ if (this._customScrollbars === customScrollbars)++ return;++ this._customScrollbars = customScrollbars;++ this._updateAllDocShells();++ }++++ _updateAllDocShells() {++ const allDocShells = [this._docShell];++ for (let i = 0; i < this._docShell.childCount; i++)++ allDocShells.push(this._docShell.getChildAt(i).QueryInterface(Ci.nsIDocShell));++ // At this point, a content viewer might not be loaded for certain docShells.++ // Scrollbars will be updated in onLocationChange.++ const contentViewers = allDocShells.map(docShell => docShell.contentViewer).filter(contentViewer => !!contentViewer);++++ // Update scrollbar stylesheets.++ for (const contentViewer of contentViewers) {++ const oldScrollbars = this._contentViewerScrollBars.get(contentViewer);++ if (oldScrollbars === this._customScrollbars)++ continue;++ const winUtils = contentViewer.DOMDocument.defaultView.windowUtils;++ if (oldScrollbars)++ winUtils.removeSheet(oldScrollbars, winUtils.AGENT_SHEET);++ if (this._customScrollbars)++ winUtils.loadSheet(this._customScrollbars, winUtils.AGENT_SHEET);++ }++ // Update state for all *existing* docShells.++ this._contentViewerScrollBars.clear();++ for (const contentViewer of contentViewers)++ this._contentViewerScrollBars.set(contentViewer, this._customScrollbars);++ }++++ dispose() {++ this._setCustomScrollbars(null);++ helper.removeListeners(this._eventListeners);++ }++}++++var EXPORTED_SYMBOLS = ['ScrollbarManager'];++this.ScrollbarManager = ScrollbarManager;+++diff --git a/testing/juggler/content/floating-scrollbars.css b/testing/juggler/content/floating-scrollbars.css+new file mode 100644+index 000000000000..7709bdd34c65+--- /dev/null++++ b/testing/juggler/content/floating-scrollbars.css+@@ -0,0 +1,47 @@++@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");++@namespace html url("http://www.w3.org/1999/xhtml");++++/* Restrict all styles to `*|*:not(html|select) > scrollbar` so that scrollbars++ inside a <select> are excluded (including them hides the select arrow on++ Windows). We want to include both the root scrollbars for the document as++ well as any overflow: scroll elements within the page, while excluding++ <select>. */++*|*:not(html|select) > scrollbar {++ -moz-appearance: none !important;++ position: relative;++ background-color: transparent;++ background-image: none;++ z-index: 2147483647;++ padding: 2px;++ border: none;++}++++/* Scrollbar code will reset the margin to the correct side depending on++ where layout actually puts the scrollbar */++*|*:not(html|select) > scrollbar[orient="vertical"] {++ margin-left: -10px;++ min-width: 10px;++ max-width: 10px;++}++++*|*:not(html|select) > scrollbar[orient="horizontal"] {++ margin-top: -10px;++ min-height: 10px;++ max-height: 10px;++}++++*|*:not(html|select) > scrollbar slider {++ -moz-appearance: none !important;++}++++*|*:not(html|select) > scrollbar thumb {++ -moz-appearance: none !important;++ background-color: rgba(0,0,0,0.2);++ border-width: 0px !important;++ border-radius: 3px !important;++}++++*|*:not(html|select) > scrollbar scrollbarbutton,++*|*:not(html|select) > scrollbar gripper {++ display: none;++}+diff --git a/testing/juggler/content/hidden-scrollbars.css b/testing/juggler/content/hidden-scrollbars.css+new file mode 100644+index 000000000000..3a386425d379+--- /dev/null++++ b/testing/juggler/content/hidden-scrollbars.css+@@ -0,0 +1,13 @@++@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul");++@namespace html url("http://www.w3.org/1999/xhtml");++++/* Restrict all styles to `*|*:not(html|select) > scrollbar` so that scrollbars++ inside a <select> are excluded (including them hides the select arrow on++ Windows). We want to include both the root scrollbars for the document as++ well as any overflow: scroll elements within the page, while excluding++ <select>. */++*|*:not(html|select) > scrollbar {++ -moz-appearance: none !important;++ display: none;++}+++diff --git a/testing/juggler/content/main.js b/testing/juggler/content/main.js+new file mode 100644+index 000000000000..8585092e04e7+--- /dev/null++++ b/testing/juggler/content/main.js+@@ -0,0 +1,39 @@++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {ContentSession} = ChromeUtils.import('chrome://juggler/content/content/ContentSession.js');++const {FrameTree} = ChromeUtils.import('chrome://juggler/content/content/FrameTree.js');++const {NetworkMonitor} = ChromeUtils.import('chrome://juggler/content/content/NetworkMonitor.js');++const {ScrollbarManager} = ChromeUtils.import('chrome://juggler/content/content/ScrollbarManager.js');++++const sessions = new Map();++const frameTree = new FrameTree(docShell);++const networkMonitor = new NetworkMonitor(docShell, frameTree);++const scrollbarManager = new ScrollbarManager(docShell);++++const helper = new Helper();++++const gListeners = [++ helper.addMessageListener(this, 'juggler:create-content-session', msg => {++ const sessionId = msg.data;++ sessions.set(sessionId, new ContentSession(sessionId, this, frameTree, scrollbarManager, networkMonitor));++ }),++++ helper.addMessageListener(this, 'juggler:dispose-content-session', msg => {++ const sessionId = msg.data;++ const session = sessions.get(sessionId);++ if (!session)++ return;++ sessions.delete(sessionId);++ session.dispose();++ }),++++ helper.addEventListener(this, 'unload', msg => {++ helper.removeListeners(gListeners);++ for (const session of sessions.values())++ session.dispose();++ sessions.clear();++ scrollbarManager.dispose();++ networkMonitor.dispose();++ frameTree.dispose();++ }),++];+++diff --git a/testing/juggler/jar.mn b/testing/juggler/jar.mn+new file mode 100644+index 000000000000..27f5a15fd7f1+--- /dev/null++++ b/testing/juggler/jar.mn+@@ -0,0 +1,29 @@++# This Source Code Form is subject to the terms of the Mozilla Public++# License, v. 2.0. If a copy of the MPL was not distributed with this++# file, You can obtain one at http://mozilla.org/MPL/2.0/.++++juggler.jar:++% content juggler %content/++ content/Helper.js (Helper.js)++ content/NetworkObserver.js (NetworkObserver.js)++ content/BrowserContextManager.js (BrowserContextManager.js)++ content/TargetRegistry.js (TargetRegistry.js)++ content/protocol/PrimitiveTypes.js (protocol/PrimitiveTypes.js)++ content/protocol/Protocol.js (protocol/Protocol.js)++ content/protocol/Dispatcher.js (protocol/Dispatcher.js)++ content/protocol/PageHandler.js (protocol/PageHandler.js)++ content/protocol/RuntimeHandler.js (protocol/RuntimeHandler.js)++ content/protocol/NetworkHandler.js (protocol/NetworkHandler.js)++ content/protocol/BrowserHandler.js (protocol/BrowserHandler.js)++ content/protocol/TargetHandler.js (protocol/TargetHandler.js)++ content/protocol/AccessibilityHandler.js (protocol/AccessibilityHandler.js)++ content/content/main.js (content/main.js)++ content/content/ContentSession.js (content/ContentSession.js)++ content/content/FrameTree.js (content/FrameTree.js)++ content/content/NetworkMonitor.js (content/NetworkMonitor.js)++ content/content/PageAgent.js (content/PageAgent.js)++ content/content/RuntimeAgent.js (content/RuntimeAgent.js)++ content/content/ScrollbarManager.js (content/ScrollbarManager.js)++ content/content/floating-scrollbars.css (content/floating-scrollbars.css)++ content/content/hidden-scrollbars.css (content/hidden-scrollbars.css)+++diff --git a/testing/juggler/moz.build b/testing/juggler/moz.build+new file mode 100644+index 000000000000..1a0a3130bf95+--- /dev/null++++ b/testing/juggler/moz.build+@@ -0,0 +1,15 @@++# This Source Code Form is subject to the terms of the Mozilla Public++# License, v. 2.0. If a copy of the MPL was not distributed with this++# file, You can obtain one at http://mozilla.org/MPL/2.0/.++++DIRS += ["components"]++++JAR_MANIFESTS += ["jar.mn"]++#JS_PREFERENCE_FILES += ["prefs/marionette.js"]++++#MARIONETTE_UNIT_MANIFESTS += ["harness/marionette_harness/tests/unit/unit-tests.ini"]++#XPCSHELL_TESTS_MANIFESTS += ["test/unit/xpcshell.ini"]++++with Files("**"):++ BUG_COMPONENT = ("Testing", "Juggler")+++diff --git a/testing/juggler/protocol/AccessibilityHandler.js b/testing/juggler/protocol/AccessibilityHandler.js+new file mode 100644+index 000000000000..fc8a7397e50a+--- /dev/null++++ b/testing/juggler/protocol/AccessibilityHandler.js+@@ -0,0 +1,15 @@++class AccessibilityHandler {++ constructor(chromeSession, contentSession) {++ this._chromeSession = chromeSession;++ this._contentSession = contentSession;++ }++++ async getFullAXTree() {++ return await this._contentSession.send('Page.getFullAXTree');++ }++++ dispose() { }++}++++var EXPORTED_SYMBOLS = ['AccessibilityHandler'];++this.AccessibilityHandler = AccessibilityHandler;+diff --git a/testing/juggler/protocol/BrowserHandler.js b/testing/juggler/protocol/BrowserHandler.js+new file mode 100644+index 000000000000..e16d1c5c5798+--- /dev/null++++ b/testing/juggler/protocol/BrowserHandler.js+@@ -0,0 +1,66 @@++"use strict";++++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++const { allowAllCerts } = ChromeUtils.import(++ "chrome://marionette/content/cert.js"++);++const {BrowserContextManager} = ChromeUtils.import("chrome://juggler/content/BrowserContextManager.js");++++class BrowserHandler {++ /**++ * @param {ChromeSession} session++ */++ constructor() {++ this._sweepingOverride = null;++ this._contextManager = BrowserContextManager.instance();++ }++++ async close() {++ Services.startup.quit(Ci.nsIAppStartup.eForceQuit);++ }++++ async setIgnoreHTTPSErrors({enabled}) {++ if (!enabled) {++ allowAllCerts.disable()++ Services.prefs.setBoolPref('security.mixed_content.block_active_content', true);++ } else {++ allowAllCerts.enable()++ Services.prefs.setBoolPref('security.mixed_content.block_active_content', false);++ }++ }++++ grantPermissions({browserContextId, origin, permissions}) {++ this._contextManager.grantPermissions(browserContextId, origin, permissions);++ }++++ resetPermissions({browserContextId}) {++ this._contextManager.resetPermissions(browserContextId);++ }++++ setCookies({browserContextId, cookies}) {++ this._contextManager.setCookies(browserContextId, cookies);++ }++++ deleteCookies({browserContextId, cookies}) {++ this._contextManager.deleteCookies(browserContextId, cookies);++ }++++ getCookies({browserContextId, urls}) {++ return {cookies: this._contextManager.getCookies(browserContextId, urls)};++ }++++ async getInfo() {++ const version = Components.classes["@mozilla.org/xre/app-info;1"]++ .getService(Components.interfaces.nsIXULAppInfo)++ .version;++ const userAgent = Components.classes["@mozilla.org/network/protocol;1?name=http"]++ .getService(Components.interfaces.nsIHttpProtocolHandler)++ .userAgent;++ return {version: 'Firefox/' + version, userAgent};++ }++++ dispose() { }++}++++var EXPORTED_SYMBOLS = ['BrowserHandler'];++this.BrowserHandler = BrowserHandler;+diff --git a/testing/juggler/protocol/Dispatcher.js b/testing/juggler/protocol/Dispatcher.js+new file mode 100644+index 000000000000..7b3a6fa4fe7a+--- /dev/null++++ b/testing/juggler/protocol/Dispatcher.js+@@ -0,0 +1,255 @@++const {TargetRegistry} = ChromeUtils.import("chrome://juggler/content/TargetRegistry.js");++const {protocol, checkScheme} = ChromeUtils.import("chrome://juggler/content/protocol/Protocol.js");++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const helper = new Helper();++++const PROTOCOL_HANDLERS = {++ Page: ChromeUtils.import("chrome://juggler/content/protocol/PageHandler.js").PageHandler,++ Network: ChromeUtils.import("chrome://juggler/content/protocol/NetworkHandler.js").NetworkHandler,++ Browser: ChromeUtils.import("chrome://juggler/content/protocol/BrowserHandler.js").BrowserHandler,++ Target: ChromeUtils.import("chrome://juggler/content/protocol/TargetHandler.js").TargetHandler,++ Runtime: ChromeUtils.import("chrome://juggler/content/protocol/RuntimeHandler.js").RuntimeHandler,++ Accessibility: ChromeUtils.import("chrome://juggler/content/protocol/AccessibilityHandler.js").AccessibilityHandler,++};++++class Dispatcher {++ /**++ * @param {Connection} connection++ */++ constructor(connection) {++ this._connection = connection;++ this._connection.onmessage = this._dispatch.bind(this);++ this._connection.onclose = this._dispose.bind(this);++++ this._targetSessions = new Map();++ this._sessions = new Map();++ this._rootSession = new ChromeSession(this, undefined, null /* contentSession */, TargetRegistry.instance().browserTargetInfo());++++ this._eventListeners = [++ helper.on(TargetRegistry.instance(), TargetRegistry.Events.TargetDestroyed, this._onTargetDestroyed.bind(this)),++ ];++ }++++ async createSession(targetId) {++ const targetInfo = TargetRegistry.instance().targetInfo(targetId);++ if (!targetInfo)++ throw new Error(`Target "${targetId}" is not found`);++ let targetSessions = this._targetSessions.get(targetId);++ if (!targetSessions) {++ targetSessions = new Map();++ this._targetSessions.set(targetId, targetSessions);++ }++++ const sessionId = helper.generateId();++ const contentSession = targetInfo.type === 'page' ? new ContentSession(this, sessionId, targetInfo) : null;++ const chromeSession = new ChromeSession(this, sessionId, contentSession, targetInfo);++ targetSessions.set(sessionId, chromeSession);++ this._sessions.set(sessionId, chromeSession);++ this._emitEvent(this._rootSession._sessionId, 'Target.attachedToTarget', {++ sessionId: sessionId,++ targetInfo++ });++ return sessionId;++ }++++ _dispose() {++ helper.removeListeners(this._eventListeners);++ this._connection.onmessage = null;++ this._connection.onclose = null;++ this._rootSession.dispose();++ this._rootSession = null;++ for (const session of this._sessions.values())++ session.dispose();++ this._sessions.clear();++ this._targetSessions.clear();++ }++++ _onTargetDestroyed({targetId}) {++ const sessions = this._targetSessions.get(targetId);++ if (!sessions)++ return;++ this._targetSessions.delete(targetId);++ for (const [sessionId, session] of sessions) {++ session.dispose();++ this._sessions.delete(sessionId);++ }++ }++++ async _dispatch(event) {++ const data = JSON.parse(event.data);++ const id = data.id;++ const sessionId = data.sessionId;++ delete data.sessionId;++ try {++ const session = sessionId ? this._sessions.get(sessionId) : this._rootSession;++ if (!session)++ throw new Error(`ERROR: cannot find session with id "${sessionId}"`);++ const method = data.method;++ const params = data.params || {};++ if (!id)++ throw new Error(`ERROR: every message must have an 'id' parameter`);++ if (!method)++ throw new Error(`ERROR: every message must have a 'method' parameter`);++++ const [domain, methodName] = method.split('.');++ const descriptor = protocol.domains[domain] ? protocol.domains[domain].methods[methodName] : null;++ if (!descriptor)++ throw new Error(`ERROR: method '${method}' is not supported`);++ let details = {};++ if (!checkScheme(descriptor.params || {}, params, details))++ throw new Error(`ERROR: failed to call method '${method}' with parameters ${JSON.stringify(params, null, 2)}\n${details.error}`);++++ const result = await session.dispatch(method, params);++++ details = {};++ if ((descriptor.returns || result) && !checkScheme(descriptor.returns, result, details))++ throw new Error(`ERROR: failed to dispatch method '${method}' result ${JSON.stringify(result, null, 2)}\n${details.error}`);++++ this._connection.send(JSON.stringify({id, sessionId, result}));++ } catch (e) {++ this._connection.send(JSON.stringify({id, sessionId, error: {++ message: e.message,++ data: e.stack++ }}));++ }++ }++++ _emitEvent(sessionId, eventName, params) {++ const [domain, eName] = eventName.split('.');++ const scheme = protocol.domains[domain] ? protocol.domains[domain].events[eName] : null;++ if (!scheme)++ throw new Error(`ERROR: event '${eventName}' is not supported`);++ const details = {};++ if (!checkScheme(scheme, params || {}, details))++ throw new Error(`ERROR: failed to emit event '${eventName}' ${JSON.stringify(params, null, 2)}\n${details.error}`);++ this._connection.send(JSON.stringify({method: eventName, params, sessionId}));++ }++}++++class ChromeSession {++ /**++ * @param {Connection} connection++ */++ constructor(dispatcher, sessionId, contentSession, targetInfo) {++ this._dispatcher = dispatcher;++ this._sessionId = sessionId;++ this._contentSession = contentSession;++ this._targetInfo = targetInfo;++++ this._handlers = {};++ for (const [domainName, handlerFactory] of Object.entries(PROTOCOL_HANDLERS)) {++ if (protocol.domains[domainName].targets.includes(targetInfo.type))++ this._handlers[domainName] = new handlerFactory(this, contentSession);++ }++ }++++ dispatcher() {++ return this._dispatcher;++ }++++ targetId() {++ return this._targetInfo.targetId;++ }++++ dispose() {++ if (this._contentSession)++ this._contentSession.dispose();++ this._contentSession = null;++ for (const [domainName, handler] of Object.entries(this._handlers)) {++ if (!handler.dispose)++ throw new Error(`Handler for "${domainName}" domain does not define |dispose| method!`);++ handler.dispose();++ delete this._handlers[domainName];++ }++ // Root session don't have sessionId and don't emit detachedFromTarget.++ if (this._sessionId) {++ this._dispatcher._emitEvent(this._sessionId, 'Target.detachedFromTarget', {++ sessionId: this._sessionId,++ });++ }++ }++++ emitEvent(eventName, params) {++ this._dispatcher._emitEvent(this._sessionId, eventName, params);++ }++++ async dispatch(method, params) {++ const [domainName, methodName] = method.split('.');++ if (!this._handlers[domainName])++ throw new Error(`Domain "${domainName}" does not exist`);++ if (!this._handlers[domainName][methodName])++ throw new Error(`Handler for domain "${domainName}" does not implement method "${methodName}"`);++ return await this._handlers[domainName][methodName](params);++ }++}++++class ContentSession {++ constructor(dispatcher, sessionId, targetInfo) {++ this._dispatcher = dispatcher;++ const tab = TargetRegistry.instance().tabForTarget(targetInfo.targetId);++ this._browser = tab.linkedBrowser;++ this._messageId = 0;++ this._pendingMessages = new Map();++ this._sessionId = sessionId;++ this._browser.messageManager.sendAsyncMessage('juggler:create-content-session', this._sessionId);++ this._disposed = false;++ this._eventListeners = [++ helper.addMessageListener(this._browser.messageManager, this._sessionId, {++ receiveMessage: message => this._onMessage(message)++ }),++ ];++ }++++ isDisposed() {++ return this._disposed;++ }++++ dispose() {++ if (this._disposed)++ return;++ this._disposed = true;++ helper.removeListeners(this._eventListeners);++ for (const {resolve, reject, methodName} of this._pendingMessages.values())++ reject(new Error(`Failed "${methodName}": Page closed.`));++ this._pendingMessages.clear();++ if (this._browser.messageManager)++ this._browser.messageManager.sendAsyncMessage('juggler:dispose-content-session', this._sessionId);++ }++++ /**++ * @param {string} methodName++ * @param {*} params++ * @return {!Promise<*>}++ */++ send(methodName, params) {++ const id = ++this._messageId;++ const promise = new Promise((resolve, reject) => {++ this._pendingMessages.set(id, {resolve, reject, methodName});++ });++ this._browser.messageManager.sendAsyncMessage(this._sessionId, {id, methodName, params});++ return promise;++ }++++ _onMessage({data}) {++ if (data.id) {++ let id = data.id;++ const {resolve, reject} = this._pendingMessages.get(data.id);++ this._pendingMessages.delete(data.id);++ if (data.error)++ reject(new Error(data.error));++ else++ resolve(data.result);++ } else {++ const {++ eventName,++ params = {}++ } = data;++ this._dispatcher._emitEvent(this._sessionId, eventName, params);++ }++ }++}++++++this.EXPORTED_SYMBOLS = ['Dispatcher'];++this.Dispatcher = Dispatcher;+++diff --git a/testing/juggler/protocol/NetworkHandler.js b/testing/juggler/protocol/NetworkHandler.js+new file mode 100644+index 000000000000..f5e7e919594b+--- /dev/null++++ b/testing/juggler/protocol/NetworkHandler.js+@@ -0,0 +1,154 @@++"use strict";++++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {NetworkObserver} = ChromeUtils.import('chrome://juggler/content/NetworkObserver.js');++const {TargetRegistry} = ChromeUtils.import("chrome://juggler/content/TargetRegistry.js");++++const Cc = Components.classes;++const Ci = Components.interfaces;++const Cu = Components.utils;++const XUL_NS = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';++const FRAME_SCRIPT = "chrome://juggler/content/content/ContentSession.js";++const helper = new Helper();++++class NetworkHandler {++ constructor(chromeSession, contentSession) {++ this._chromeSession = chromeSession;++ this._contentSession = contentSession;++ this._networkObserver = NetworkObserver.instance();++ this._httpActivity = new Map();++ this._enabled = false;++ this._browser = TargetRegistry.instance().tabForTarget(this._chromeSession.targetId()).linkedBrowser;++ this._requestInterception = false;++ this._eventListeners = [];++ this._pendingRequstWillBeSentEvents = new Set();++ }++++ async enable() {++ if (this._enabled)++ return;++ this._enabled = true;++ this._eventListeners = [++ helper.on(this._networkObserver, 'request', this._onRequest.bind(this)),++ helper.on(this._networkObserver, 'response', this._onResponse.bind(this)),++ helper.on(this._networkObserver, 'requestfinished', this._onRequestFinished.bind(this)),++ helper.on(this._networkObserver, 'requestfailed', this._onRequestFailed.bind(this)),++ this._networkObserver.startTrackingBrowserNetwork(this._browser),++ ];++ }++++ async getResponseBody({requestId}) {++ return this._networkObserver.getResponseBody(this._browser, requestId);++ }++++ async setExtraHTTPHeaders({headers}) {++ this._networkObserver.setExtraHTTPHeaders(this._browser, headers);++ }++++ async setRequestInterception({enabled}) {++ if (enabled)++ this._networkObserver.enableRequestInterception(this._browser);++ else++ this._networkObserver.disableRequestInterception(this._browser);++ // Right after we enable/disable request interception we need to await all pending++ // requestWillBeSent events before successfully returning from the method.++ await Promise.all(Array.from(this._pendingRequstWillBeSentEvents));++ }++++ async resumeSuspendedRequest({requestId, headers}) {++ this._networkObserver.resumeSuspendedRequest(this._browser, requestId, headers);++ }++++ async abortSuspendedRequest({requestId}) {++ this._networkObserver.abortSuspendedRequest(this._browser, requestId);++ }++++ dispose() {++ helper.removeListeners(this._eventListeners);++ }++++ _ensureHTTPActivity(requestId) {++ let activity = this._httpActivity.get(requestId);++ if (!activity) {++ activity = {++ _id: requestId,++ _lastSentEvent: null,++ request: null,++ response: null,++ complete: null,++ failed: null,++ };++ this._httpActivity.set(requestId, activity);++ }++ return activity;++ }++++ _reportHTTPAcitivityEvents(activity) {++ // State machine - sending network events.++ if (!activity._lastSentEvent && activity.request) {++ this._chromeSession.emitEvent('Network.requestWillBeSent', activity.request);++ activity._lastSentEvent = 'requestWillBeSent';++ }++ if (activity._lastSentEvent === 'requestWillBeSent' && activity.response) {++ this._chromeSession.emitEvent('Network.responseReceived', activity.response);++ activity._lastSentEvent = 'responseReceived';++ }++ if (activity._lastSentEvent === 'responseReceived' && activity.complete) {++ this._chromeSession.emitEvent('Network.requestFinished', activity.complete);++ activity._lastSentEvent = 'requestFinished';++ }++ if (activity._lastSentEvent && activity.failed) {++ this._chromeSession.emitEvent('Network.requestFailed', activity.failed);++ activity._lastSentEvent = 'requestFailed';++ }++++ // Clean up if request lifecycle is over.++ if (activity._lastSentEvent === 'requestFinished' || activity._lastSentEvent === 'requestFailed')++ this._httpActivity.delete(activity._id);++ }++++ async _onRequest(httpChannel, eventDetails) {++ let pendingRequestCallback;++ let pendingRequestPromise = new Promise(x => pendingRequestCallback = x);++ this._pendingRequstWillBeSentEvents.add(pendingRequestPromise);++ let details = null;++ try {++ details = await this._contentSession.send('Page.requestDetails', {channelId: httpChannel.channelId});++ } catch (e) {++ if (this._contentSession.isDisposed()) {++ pendingRequestCallback();++ this._pendingRequstWillBeSentEvents.delete(pendingRequestPromise);++ return;++ }++ }++ const activity = this._ensureHTTPActivity(eventDetails.requestId);++ activity.request = {++ frameId: details ? details.frameId : undefined,++ ...eventDetails,++ };++ this._reportHTTPAcitivityEvents(activity);++ pendingRequestCallback();++ this._pendingRequstWillBeSentEvents.delete(pendingRequestPromise);++ }++++ async _onResponse(httpChannel, eventDetails) {++ const activity = this._ensureHTTPActivity(eventDetails.requestId);++ activity.response = eventDetails;++ this._reportHTTPAcitivityEvents(activity);++ }++++ async _onRequestFinished(httpChannel, eventDetails) {++ const activity = this._ensureHTTPActivity(eventDetails.requestId);++ activity.complete = eventDetails;++ this._reportHTTPAcitivityEvents(activity);++ }++++ async _onRequestFailed(httpChannel, eventDetails) {++ const activity = this._ensureHTTPActivity(eventDetails.requestId);++ activity.failed = eventDetails;++ this._reportHTTPAcitivityEvents(activity);++ }++}++++var EXPORTED_SYMBOLS = ['NetworkHandler'];++this.NetworkHandler = NetworkHandler;+diff --git a/testing/juggler/protocol/PageHandler.js b/testing/juggler/protocol/PageHandler.js+new file mode 100644+index 000000000000..32fb7e9d928a+--- /dev/null++++ b/testing/juggler/protocol/PageHandler.js+@@ -0,0 +1,269 @@++"use strict";++++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {TargetRegistry} = ChromeUtils.import("chrome://juggler/content/TargetRegistry.js");++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++++const Cc = Components.classes;++const Ci = Components.interfaces;++const Cu = Components.utils;++const XUL_NS = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';++const FRAME_SCRIPT = "chrome://juggler/content/content/ContentSession.js";++const helper = new Helper();++++class PageHandler {++ constructor(chromeSession, contentSession) {++ this._chromeSession = chromeSession;++ this._contentSession = contentSession;++ this._browser = TargetRegistry.instance().tabForTarget(chromeSession.targetId()).linkedBrowser;++ this._dialogs = new Map();++++ this._eventListeners = [];++ this._enabled = false;++ }++++ async close({runBeforeUnload}) {++ // Postpone target close to deliver response in session.++ Services.tm.dispatchToMainThread(() => {++ TargetRegistry.instance().closePage(this._chromeSession.targetId(), runBeforeUnload);++ });++ }++++ async enable() {++ if (this._enabled)++ return;++ this._enabled = true;++ this._updateModalDialogs();++++ this._eventListeners = [++ helper.addEventListener(this._browser, 'DOMWillOpenModalDialog', async (event) => {++ // wait for the dialog to be actually added to DOM.++ await Promise.resolve();++ this._updateModalDialogs();++ }),++ helper.addEventListener(this._browser, 'DOMModalDialogClosed', event => this._updateModalDialogs()),++ ];++ await this._contentSession.send('Page.enable');++ }++++ dispose() {++ helper.removeListeners(this._eventListeners);++ }++++ async setViewport({viewport}) {++ if (viewport) {++ const {width, height} = viewport;++ this._browser.style.setProperty('min-width', width + 'px');++ this._browser.style.setProperty('min-height', height + 'px');++ this._browser.style.setProperty('max-width', width + 'px');++ this._browser.style.setProperty('max-height', height + 'px');++ } else {++ this._browser.style.removeProperty('min-width');++ this._browser.style.removeProperty('min-height');++ this._browser.style.removeProperty('max-width');++ this._browser.style.removeProperty('max-height');++ }++ const dimensions = this._browser.getBoundingClientRect();++ await Promise.all([++ this._contentSession.send('Page.setViewport', {++ deviceScaleFactor: viewport ? viewport.deviceScaleFactor : 0,++ isMobile: viewport && viewport.isMobile,++ hasTouch: viewport && viewport.hasTouch,++ }),++ this._contentSession.send('Page.awaitViewportDimensions', {++ width: dimensions.width,++ height: dimensions.height++ }),++ ]);++ }++++ _updateModalDialogs() {++ const prompts = new Set(this._browser.tabModalPromptBox ? this._browser.tabModalPromptBox.listPrompts() : []);++ for (const dialog of this._dialogs.values()) {++ if (!prompts.has(dialog.prompt())) {++ this._dialogs.delete(dialog.id());++ this._chromeSession.emitEvent('Page.dialogClosed', {++ dialogId: dialog.id(),++ });++ } else {++ prompts.delete(dialog.prompt());++ }++ }++ for (const prompt of prompts) {++ const dialog = Dialog.createIfSupported(prompt);++ if (!dialog)++ continue;++ this._dialogs.set(dialog.id(), dialog);++ this._chromeSession.emitEvent('Page.dialogOpened', {++ dialogId: dialog.id(),++ type: dialog.type(),++ message: dialog.message(),++ defaultValue: dialog.defaultValue(),++ });++ }++ }++++ async setUserAgent(options) {++ return await this._contentSession.send('Page.setUserAgent', options);++ }++++ async setFileInputFiles(options) {++ return await this._contentSession.send('Page.setFileInputFiles', options);++ }++++ async setEmulatedMedia(options) {++ return await this._contentSession.send('Page.setEmulatedMedia', options);++ }++++ async setJavascriptEnabled(options) {++ return await this._contentSession.send('Page.setJavascriptEnabled', options);++ }++++ async setCacheDisabled(options) {++ return await this._contentSession.send('Page.setCacheDisabled', options);++ }++++ async addBinding(options) {++ return await this._contentSession.send('Page.addBinding', options);++ }++++ async screenshot(options) {++ return await this._contentSession.send('Page.screenshot', options);++ }++++ async getBoundingBox(options) {++ return await this._contentSession.send('Page.getBoundingBox', options);++ }++++ async getContentQuads(options) {++ return await this._contentSession.send('Page.getContentQuads', options);++ }++++ /**++ * @param {{frameId: string, url: string}} options++ */++ async navigate(options) {++ return await this._contentSession.send('Page.navigate', options);++ }++++ /**++ * @param {{frameId: string, url: string}} options++ */++ async goBack(options) {++ return await this._contentSession.send('Page.goBack', options);++ }++++ /**++ * @param {{frameId: string, url: string}} options++ */++ async goForward(options) {++ return await this._contentSession.send('Page.goForward', options);++ }++++ /**++ * @param {{frameId: string, url: string}} options++ */++ async reload(options) {++ return await this._contentSession.send('Page.reload', options);++ }++++ /**++ * @param {{frameId: String, objectId: String}} options++ * @return {!Promise<*>}++ */++ async contentFrame(options) {++ return await this._contentSession.send('Page.contentFrame', options);++ }++++ async addScriptToEvaluateOnNewDocument(options) {++ return await this._contentSession.send('Page.addScriptToEvaluateOnNewDocument', options);++ }++++ async removeScriptToEvaluateOnNewDocument(options) {++ return await this._contentSession.send('Page.removeScriptToEvaluateOnNewDocument', options);++ }++++ async dispatchKeyEvent(options) {++ return await this._contentSession.send('Page.dispatchKeyEvent', options);++ }++++ async dispatchTouchEvent(options) {++ return await this._contentSession.send('Page.dispatchTouchEvent', options);++ }++++ async dispatchMouseEvent(options) {++ return await this._contentSession.send('Page.dispatchMouseEvent', options);++ }++++ async insertText(options) {++ return await this._contentSession.send('Page.insertText', options);++ }++++ async handleDialog({dialogId, accept, promptText}) {++ const dialog = this._dialogs.get(dialogId);++ if (!dialog)++ throw new Error('Failed to find dialog with id = ' + dialogId);++ if (accept)++ dialog.accept(promptText);++ else++ dialog.dismiss();++ }++}++++class Dialog {++ static createIfSupported(prompt) {++ const type = prompt.args.promptType;++ switch (type) {++ case 'alert':++ case 'prompt':++ case 'confirm':++ return new Dialog(prompt, type);++ case 'confirmEx':++ return new Dialog(prompt, 'beforeunload');++ default:++ return null;++ };++ }++++ constructor(prompt, type) {++ this._id = helper.generateId();++ this._type = type;++ this._prompt = prompt;++ }++++ id() {++ return this._id;++ }++++ message() {++ return this._prompt.ui.infoBody.textContent;++ }++++ type() {++ return this._type;++ }++++ prompt() {++ return this._prompt;++ }++++ dismiss() {++ if (this._prompt.ui.button1)++ this._prompt.ui.button1.click();++ else++ this._prompt.ui.button0.click();++ }++++ defaultValue() {++ return this._prompt.ui.loginTextbox.value;++ }++++ accept(promptValue) {++ if (typeof promptValue === 'string' && this._type === 'prompt')++ this._prompt.ui.loginTextbox.value = promptValue;++ this._prompt.ui.button0.click();++ }++}++++var EXPORTED_SYMBOLS = ['PageHandler'];++this.PageHandler = PageHandler;+diff --git a/testing/juggler/protocol/PrimitiveTypes.js b/testing/juggler/protocol/PrimitiveTypes.js+new file mode 100644+index 000000000000..78b6601b91d0+--- /dev/null++++ b/testing/juggler/protocol/PrimitiveTypes.js+@@ -0,0 +1,143 @@++const t = {};++++t.String = function(x, details = {}, path = ['<root>']) {++ if (typeof x === 'string' || typeof x === 'String')++ return true;++ details.error = `Expected "${path.join('.')}" to be |string|; found |${typeof x}| \`${JSON.stringify(x)}\` instead.`;++ return false;++}++++t.Number = function(x, details = {}, path = ['<root>']) {++ if (typeof x === 'number')++ return true;++ details.error = `Expected "${path.join('.')}" to be |number|; found |${typeof x}| \`${JSON.stringify(x)}\` instead.`;++ return false;++}++++t.Boolean = function(x, details = {}, path = ['<root>']) {++ if (typeof x === 'boolean')++ return true;++ details.error = `Expected "${path.join('.')}" to be |boolean|; found |${typeof x}| \`${JSON.stringify(x)}\` instead.`;++ return false;++}++++t.Null = function(x, details = {}, path = ['<root>']) {++ if (Object.is(x, null))++ return true;++ details.error = `Expected "${path.join('.')}" to be \`null\`; found \`${JSON.stringify(x)}\` instead.`;++ return false;++}++++t.Undefined = function(x, details = {}, path = ['<root>']) {++ if (Object.is(x, undefined))++ return true;++ details.error = `Expected "${path.join('.')}" to be \`undefined\`; found \`${JSON.stringify(x)}\` instead.`;++ return false;++}++++t.Any = x => true,++++t.Enum = function(values) {++ return function(x, details = {}, path = ['<root>']) {++ if (values.indexOf(x) !== -1)++ return true;++ details.error = `Expected "${path.join('.')}" to be one of [${values.join(', ')}]; found \`${JSON.stringify(x)}\` (${typeof x}) instead.`;++ return false;++ }++}++++t.Nullable = function(scheme) {++ return function(x, details = {}, path = ['<root>']) {++ if (Object.is(x, null))++ return true;++ return checkScheme(scheme, x, details, path);++ }++}++++t.Optional = function(scheme) {++ return function(x, details = {}, path = ['<root>']) {++ if (Object.is(x, undefined))++ return true;++ return checkScheme(scheme, x, details, path);++ }++}++++t.Array = function(scheme) {++ return function(x, details = {}, path = ['<root>']) {++ if (!Array.isArray(x)) {++ details.error = `Expected "${path.join('.')}" to be an array; found \`${JSON.stringify(x)}\` (${typeof x}) instead.`;++ return false;++ }++ const lastPathElement = path[path.length - 1];++ for (let i = 0; i < x.length; ++i) {++ path[path.length - 1] = lastPathElement + `[${i}]`;++ if (!checkScheme(scheme, x[i], details, path))++ return false;++ }++ path[path.length - 1] = lastPathElement;++ return true;++ }++}++++t.Recursive = function(types, schemeName) {++ return function(x, details = {}, path = ['<root>']) {++ const scheme = types[schemeName];++ return checkScheme(scheme, x, details, path);++ }++}++++function beauty(path, obj) {++ if (path.length === 1)++ return `object ${JSON.stringify(obj, null, 2)}`;++ return `property "${path.join('.')}" - ${JSON.stringify(obj, null, 2)}`;++}++++function checkScheme(scheme, x, details = {}, path = ['<root>']) {++ if (!scheme)++ throw new Error(`ILLDEFINED SCHEME: ${path.join('.')}`);++ if (typeof scheme === 'object') {++ if (!x) {++ details.error = `Object "${path.join('.')}" is undefined, but has some scheme`;++ return false;++ }++ for (const [propertyName, aScheme] of Object.entries(scheme)) {++ path.push(propertyName);++ const result = checkScheme(aScheme, x[propertyName], details, path);++ path.pop();++ if (!result)++ return false;++ }++ for (const propertyName of Object.keys(x)) {++ if (!scheme[propertyName]) {++ path.push(propertyName);++ details.error = `Found ${beauty(path, x[propertyName])} which is not described in this scheme`;++ return false;++ }++ }++ return true;++ }++ return scheme(x, details, path);++}++++/*++++function test(scheme, obj) {++ const details = {};++ if (!checkScheme(scheme, obj, details)) {++ dump(`FAILED: ${JSON.stringify(obj)}++ details.error: ${details.error}++ `);++ } else {++ dump(`SUCCESS: ${JSON.stringify(obj)}++`);++ }++}++++test(t.Array(t.String), ['a', 'b', 2, 'c']);++test(t.Either(t.String, t.Number), {});++++*/++++this.t = t;++this.checkScheme = checkScheme;++this.EXPORTED_SYMBOLS = ['t', 'checkScheme'];+diff --git a/testing/juggler/protocol/Protocol.js b/testing/juggler/protocol/Protocol.js+new file mode 100644+index 000000000000..63186502775d+--- /dev/null++++ b/testing/juggler/protocol/Protocol.js+@@ -0,0 +1,660 @@++const {t, checkScheme} = ChromeUtils.import('chrome://juggler/content/protocol/PrimitiveTypes.js');++++// Protocol-specific types.++const types = {};++++types.TargetInfo = {++ type: t.Enum(['page', 'browser']),++ targetId: t.String,++ browserContextId: t.Optional(t.String),++ url: t.String,++ // PageId of parent tab, if any.++ openerId: t.Optional(t.String),++};++++types.DOMPoint = {++ x: t.Number,++ y: t.Number,++};++++types.DOMQuad = {++ p1: types.DOMPoint,++ p2: types.DOMPoint,++ p3: types.DOMPoint,++ p4: types.DOMPoint,++};++++types.TouchPoint = {++ x: t.Number,++ y: t.Number,++ radiusX: t.Optional(t.Number),++ radiusY: t.Optional(t.Number),++ rotationAngle: t.Optional(t.Number),++ force: t.Optional(t.Number),++};++++types.RemoteObject = {++ type: t.Optional(t.Enum(['object', 'function', 'undefined', 'string', 'number', 'boolean', 'symbol', 'bigint'])),++ subtype: t.Optional(t.Enum(['array', 'null', 'node', 'regexp', 'date', 'map', 'set', 'weakmap', 'weakset', 'error', 'proxy', 'promise', 'typedarray'])),++ objectId: t.Optional(t.String),++ unserializableValue: t.Optional(t.Enum(['Infinity', '-Infinity', '-0', 'NaN'])),++ value: t.Any++};++++types.AXTree = {++ role: t.String,++ name: t.String,++ children: t.Optional(t.Array(t.Recursive(types, 'AXTree'))),++++ selected: t.Optional(t.Boolean),++ focused: t.Optional(t.Boolean),++ pressed: t.Optional(t.Boolean),++ focusable: t.Optional(t.Boolean),++ haspopup: t.Optional(t.Boolean),++ required: t.Optional(t.Boolean),++ invalid: t.Optional(t.Boolean),++ modal: t.Optional(t.Boolean),++ editable: t.Optional(t.Boolean),++ busy: t.Optional(t.Boolean),++ multiline: t.Optional(t.Boolean),++ readonly: t.Optional(t.Boolean),++ checked: t.Optional(t.Enum(['mixed', true])),++ expanded: t.Optional(t.Boolean),++ disabled: t.Optional(t.Boolean),++ multiselectable: t.Optional(t.Boolean),++++ value: t.Optional(t.String),++ description: t.Optional(t.String),++++ value: t.Optional(t.String),++ roledescription: t.Optional(t.String),++ valuetext: t.Optional(t.String),++ orientation: t.Optional(t.String),++ autocomplete: t.Optional(t.String),++ keyshortcuts: t.Optional(t.String),++++ level: t.Optional(t.Number),++++ tag: t.Optional(t.String),++}++++const Browser = {++ targets: ['browser'],++++ events: {},++++ methods: {++ 'close': {},++ 'getInfo': {++ returns: {++ userAgent: t.String,++ version: t.String,++ },++ },++ 'setIgnoreHTTPSErrors': {++ params: {++ enabled: t.Boolean,++ },++ },++ 'grantPermissions': {++ params: {++ origin: t.String,++ browserContextId: t.Optional(t.String),++ permissions: t.Array(t.Enum([++ 'geo', 'microphone', 'camera', 'desktop-notifications'++ ])),++ },++ },++ 'resetPermissions': {++ params: {++ browserContextId: t.Optional(t.String),++ }++ },++ 'setCookies': {++ params: {++ browserContextId: t.Optional(t.String),++ cookies: t.Array({++ name: t.String,++ value: t.String,++ url: t.Optional(t.String),++ domain: t.Optional(t.String),++ path: t.Optional(t.String),++ secure: t.Optional(t.Boolean),++ httpOnly: t.Optional(t.Boolean),++ sameSite: t.Optional(t.Enum(['Strict', 'Lax'])),++ expires: t.Optional(t.Number),++ }),++ }++ },++ 'deleteCookies': {++ params: {++ browserContextId: t.Optional(t.String),++ cookies: t.Array({++ name: t.String,++ domain: t.Optional(t.String),++ path: t.Optional(t.String),++ url: t.Optional(t.String),++ }),++ }++ },++ 'getCookies': {++ params: {++ browserContextId: t.Optional(t.String),++ urls: t.Array(t.String),++ },++ returns: {++ cookies: t.Array({++ name: t.String,++ domain: t.String,++ path: t.String,++ value: t.String,++ expires: t.Number,++ size: t.Number,++ httpOnly: t.Boolean,++ secure: t.Boolean,++ session: t.Boolean,++ sameSite: t.Optional(t.Enum(['Strict', 'Lax'])),++ }),++ },++ },++ },++};++++const Target = {++ targets: ['browser'],++++ events: {++ 'attachedToTarget': {++ sessionId: t.String,++ targetInfo: types.TargetInfo,++ },++ 'detachedFromTarget': {++ sessionId: t.String,++ },++ 'targetCreated': types.TargetInfo,++ 'targetDestroyed': types.TargetInfo,++ 'targetInfoChanged': types.TargetInfo,++ },++++ methods: {++ // Start emitting tagOpened/tabClosed events++ 'enable': {},++ 'attachToTarget': {++ params: {++ targetId: t.String,++ },++ returns: {++ sessionId: t.String,++ },++ },++ 'newPage': {++ params: {++ browserContextId: t.Optional(t.String),++ },++ returns: {++ targetId: t.String,++ }++ },++ 'createBrowserContext': {++ returns: {++ browserContextId: t.String,++ },++ },++ 'removeBrowserContext': {++ params: {++ browserContextId: t.String,++ },++ },++ 'getBrowserContexts': {++ returns: {++ browserContextIds: t.Array(t.String),++ },++ },++ },++};++++const Network = {++ targets: ['page'],++ events: {++ 'requestWillBeSent': {++ // frameId may be absent for redirected requests.++ frameId: t.Optional(t.String),++ requestId: t.String,++ // RequestID of redirected request.++ redirectedFrom: t.Optional(t.String),++ postData: t.Optional(t.String),++ headers: t.Array({++ name: t.String,++ value: t.String,++ }),++ suspended: t.Optional(t.Boolean),++ url: t.String,++ method: t.String,++ isNavigationRequest: t.Boolean,++ cause: t.String,++ },++ 'responseReceived': {++ securityDetails: t.Nullable({++ protocol: t.String,++ subjectName: t.String,++ issuer: t.String,++ validFrom: t.Number,++ validTo: t.Number,++ }),++ requestId: t.String,++ fromCache: t.Boolean,++ remoteIPAddress: t.Optional(t.String),++ remotePort: t.Optional(t.Number),++ status: t.Number,++ statusText: t.String,++ headers: t.Array({++ name: t.String,++ value: t.String,++ }),++ },++ 'requestFinished': {++ requestId: t.String,++ },++ 'requestFailed': {++ requestId: t.String,++ errorCode: t.String,++ },++ },++ methods: {++ 'enable': {},++ 'setRequestInterception': {++ params: {++ enabled: t.Boolean,++ },++ },++ 'setExtraHTTPHeaders': {++ params: {++ headers: t.Array({++ name: t.String,++ value: t.String,++ }),++ },++ },++ 'abortSuspendedRequest': {++ params: {++ requestId: t.String,++ },++ },++ 'resumeSuspendedRequest': {++ params: {++ requestId: t.String,++ headers: t.Optional(t.Array({++ name: t.String,++ value: t.String,++ })),++ },++ },++ 'getResponseBody': {++ params: {++ requestId: t.String,++ },++ returns: {++ base64body: t.String,++ evicted: t.Optional(t.Boolean),++ },++ },++ },++};++++const Runtime = {++ targets: ['page'],++ events: {++ 'executionContextCreated': {++ executionContextId: t.String,++ auxData: t.Any,++ },++ 'executionContextDestroyed': {++ executionContextId: t.String,++ },++ 'console': {++ executionContextId: t.String,++ args: t.Array(types.RemoteObject),++ type: t.String,++ location: {++ columnNumber: t.Number,++ lineNumber: t.Number,++ url: t.String,++ },++ },++ },++ methods: {++ 'enable': {++ params: {},++ },++ 'evaluate': {++ params: {++ // Pass frameId here.++ executionContextId: t.String,++ expression: t.String,++ returnByValue: t.Optional(t.Boolean),++ },++++ returns: {++ result: t.Optional(types.RemoteObject),++ exceptionDetails: t.Optional({++ text: t.Optional(t.String),++ stack: t.Optional(t.String),++ value: t.Optional(t.Any),++ }),++ }++ },++ 'callFunction': {++ params: {++ // Pass frameId here.++ executionContextId: t.String,++ functionDeclaration: t.String,++ returnByValue: t.Optional(t.Boolean),++ args: t.Array({++ objectId: t.Optional(t.String),++ unserializableValue: t.Optional(t.Enum(['Infinity', '-Infinity', '-0', 'NaN'])),++ value: t.Any,++ }),++ },++++ returns: {++ result: t.Optional(types.RemoteObject),++ exceptionDetails: t.Optional({++ text: t.Optional(t.String),++ stack: t.Optional(t.String),++ value: t.Optional(t.Any),++ }),++ }++ },++ 'disposeObject': {++ params: {++ executionContextId: t.String,++ objectId: t.String,++ },++ },++++ 'getObjectProperties': {++ params: {++ executionContextId: t.String,++ objectId: t.String,++ },++++ returns: {++ properties: t.Array({++ name: t.String,++ value: types.RemoteObject,++ }),++ }++ },++ },++};++++const Page = {++ targets: ['page'],++ events: {++ 'eventFired': {++ frameId: t.String,++ name: t.Enum(['load', 'DOMContentLoaded']),++ },++ 'uncaughtError': {++ frameId: t.String,++ message: t.String,++ stack: t.String,++ },++ 'frameAttached': {++ frameId: t.String,++ parentFrameId: t.Optional(t.String),++ },++ 'frameDetached': {++ frameId: t.String,++ },++ 'navigationStarted': {++ frameId: t.String,++ navigationId: t.String,++ url: t.String,++ },++ 'navigationCommitted': {++ frameId: t.String,++ navigationId: t.String,++ url: t.String,++ // frame.id or frame.name++ name: t.String,++ },++ 'navigationAborted': {++ frameId: t.String,++ navigationId: t.String,++ errorText: t.String,++ },++ 'sameDocumentNavigation': {++ frameId: t.String,++ url: t.String,++ },++ 'dialogOpened': {++ dialogId: t.String,++ type: t.Enum(['prompt', 'alert', 'confirm', 'beforeunload']),++ message: t.String,++ defaultValue: t.Optional(t.String),++ },++ 'dialogClosed': {++ dialogId: t.String,++ },++ 'bindingCalled': {++ executionContextId: t.String,++ name: t.String,++ payload: t.Any,++ },++ },++++ methods: {++ 'enable': {++ params: {},++ },++ 'close': {++ params: {++ runBeforeUnload: t.Optional(t.Boolean),++ },++ },++ 'setFileInputFiles': {++ params: {++ frameId: t.String,++ objectId: t.String,++ files: t.Array(t.String),++ },++ },++ 'addBinding': {++ params: {++ name: t.String,++ },++ },++ 'setViewport': {++ params: {++ viewport: t.Nullable({++ width: t.Number,++ height: t.Number,++ deviceScaleFactor: t.Number,++ isMobile: t.Boolean,++ hasTouch: t.Boolean,++ isLandscape: t.Boolean,++ }),++ },++ },++ 'setUserAgent': {++ params: {++ userAgent: t.Nullable(t.String),++ },++ },++ 'setEmulatedMedia': {++ params: {++ media: t.Enum(['screen', 'print', '']),++ },++ },++ 'setCacheDisabled': {++ params: {++ cacheDisabled: t.Boolean,++ },++ },++ 'setJavascriptEnabled': {++ params: {++ enabled: t.Boolean,++ },++ },++ 'contentFrame': {++ params: {++ frameId: t.String,++ objectId: t.String,++ },++ returns: {++ frameId: t.Nullable(t.String),++ },++ },++ 'addScriptToEvaluateOnNewDocument': {++ params: {++ script: t.String,++ },++ returns: {++ scriptId: t.String,++ }++ },++ 'removeScriptToEvaluateOnNewDocument': {++ params: {++ scriptId: t.String,++ },++ },++ 'navigate': {++ params: {++ frameId: t.String,++ url: t.String,++ referer: t.Optional(t.String),++ },++ returns: {++ navigationId: t.Nullable(t.String),++ navigationURL: t.Nullable(t.String),++ }++ },++ 'goBack': {++ params: {++ frameId: t.String,++ },++ returns: {++ navigationId: t.Nullable(t.String),++ navigationURL: t.Nullable(t.String),++ }++ },++ 'goForward': {++ params: {++ frameId: t.String,++ },++ returns: {++ navigationId: t.Nullable(t.String),++ navigationURL: t.Nullable(t.String),++ }++ },++ 'reload': {++ params: {++ frameId: t.String,++ },++ returns: {++ navigationId: t.String,++ navigationURL: t.String,++ }++ },++ 'getBoundingBox': {++ params: {++ frameId: t.String,++ objectId: t.String,++ },++ returns: t.Nullable({++ x: t.Number,++ y: t.Number,++ width: t.Number,++ height: t.Number,++ }),++ },++ 'screenshot': {++ params: {++ mimeType: t.Enum(['image/png', 'image/jpeg']),++ fullPage: t.Optional(t.Boolean),++ clip: t.Optional({++ x: t.Number,++ y: t.Number,++ width: t.Number,++ height: t.Number,++ })++ },++ returns: {++ data: t.String,++ }++ },++ 'getContentQuads': {++ params: {++ frameId: t.String,++ objectId: t.String,++ },++ returns: {++ quads: t.Array(types.DOMQuad),++ },++ },++ 'dispatchKeyEvent': {++ params: {++ type: t.String,++ key: t.String,++ keyCode: t.Number,++ location: t.Number,++ code: t.String,++ repeat: t.Boolean,++ }++ },++ 'dispatchTouchEvent': {++ params: {++ type: t.Enum(['touchStart', 'touchEnd', 'touchMove', 'touchCancel']),++ touchPoints: t.Array(types.TouchPoint),++ modifiers: t.Number,++ },++ returns: {++ defaultPrevented: t.Boolean,++ }++ },++ 'dispatchMouseEvent': {++ params: {++ type: t.String,++ button: t.Number,++ x: t.Number,++ y: t.Number,++ modifiers: t.Number,++ clickCount: t.Optional(t.Number),++ buttons: t.Number,++ }++ },++ 'insertText': {++ params: {++ text: t.String,++ }++ },++ 'handleDialog': {++ params: {++ dialogId: t.String,++ accept: t.Boolean,++ promptText: t.Optional(t.String),++ },++ },++ },++};++++++const Accessibility = {++ targets: ['page'],++ events: {},++ methods: {++ 'getFullAXTree': {++ params: {},++ returns: {++ tree:types.AXTree++ },++ }++ }++}++++this.protocol = {++ domains: {Browser, Target, Page, Runtime, Network, Accessibility},++};++this.checkScheme = checkScheme;++this.EXPORTED_SYMBOLS = ['protocol', 'checkScheme'];+diff --git a/testing/juggler/protocol/RuntimeHandler.js b/testing/juggler/protocol/RuntimeHandler.js+new file mode 100644+index 000000000000..0026e8ff58ef+--- /dev/null++++ b/testing/juggler/protocol/RuntimeHandler.js+@@ -0,0 +1,41 @@++"use strict";++++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++++const Cc = Components.classes;++const Ci = Components.interfaces;++const Cu = Components.utils;++const helper = new Helper();++++class RuntimeHandler {++ constructor(chromeSession, contentSession) {++ this._chromeSession = chromeSession;++ this._contentSession = contentSession;++ }++++ async enable(options) {++ return await this._contentSession.send('Runtime.enable', options);++ }++++ async evaluate(options) {++ return await this._contentSession.send('Runtime.evaluate', options);++ }++++ async callFunction(options) {++ return await this._contentSession.send('Runtime.callFunction', options);++ }++++ async getObjectProperties(options) {++ return await this._contentSession.send('Runtime.getObjectProperties', options);++ }++++ async disposeObject(options) {++ return await this._contentSession.send('Runtime.disposeObject', options);++ }++++ dispose() {}++}++++var EXPORTED_SYMBOLS = ['RuntimeHandler'];++this.RuntimeHandler = RuntimeHandler;+diff --git a/testing/juggler/protocol/TargetHandler.js b/testing/juggler/protocol/TargetHandler.js+new file mode 100644+index 000000000000..4ea36eeba758+--- /dev/null++++ b/testing/juggler/protocol/TargetHandler.js+@@ -0,0 +1,75 @@++"use strict";++++const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");++const {TargetRegistry} = ChromeUtils.import("chrome://juggler/content/TargetRegistry.js");++const {BrowserContextManager} = ChromeUtils.import("chrome://juggler/content/BrowserContextManager.js");++const {Helper} = ChromeUtils.import('chrome://juggler/content/Helper.js');++const helper = new Helper();++++class TargetHandler {++ /**++ * @param {ChromeSession} session++ */++ constructor(session) {++ this._session = session;++ this._contextManager = BrowserContextManager.instance();++ this._targetRegistry = TargetRegistry.instance();++ this._enabled = false;++ this._eventListeners = [];++ }++++ async attachToTarget({targetId}) {++ const sessionId = await this._session.dispatcher().createSession(targetId);++ return {sessionId};++ }++++ async createBrowserContext() {++ return {browserContextId: this._contextManager.createBrowserContext()};++ }++++ async removeBrowserContext({browserContextId}) {++ this._contextManager.removeBrowserContext(browserContextId);++ }++++ async getBrowserContexts() {++ return {browserContextIds: this._contextManager.getBrowserContexts()};++ }++++ async enable() {++ if (this._enabled)++ return;++ this._enabled = true;++ for (const targetInfo of this._targetRegistry.targetInfos())++ this._onTargetCreated(targetInfo);++++ this._eventListeners = [++ helper.on(this._targetRegistry, TargetRegistry.Events.TargetCreated, this._onTargetCreated.bind(this)),++ helper.on(this._targetRegistry, TargetRegistry.Events.TargetChanged, this._onTargetChanged.bind(this)),++ helper.on(this._targetRegistry, TargetRegistry.Events.TargetDestroyed, this._onTargetDestroyed.bind(this)),++ ];++ }++++ dispose() {++ helper.removeListeners(this._eventListeners);++ }++++ _onTargetCreated(targetInfo) {++ this._session.emitEvent('Target.targetCreated', targetInfo);++ }++++ _onTargetChanged(targetInfo) {++ this._session.emitEvent('Target.targetInfoChanged', targetInfo);++ }++++ _onTargetDestroyed(targetInfo) {++ this._session.emitEvent('Target.targetDestroyed', targetInfo);++ }++++ async newPage({browserContextId}) {++ const targetId = await this._targetRegistry.newPage({browserContextId});++ return {targetId};++ }++}++++var EXPORTED_SYMBOLS = ['TargetHandler'];++this.TargetHandler = TargetHandler;+diff --git a/toolkit/components/statusfilter/nsBrowserStatusFilter.cpp b/toolkit/components/statusfilter/nsBrowserStatusFilter.cpp+index 9aea55ddf773..188a0f28b8e1 100644+--- a/toolkit/components/statusfilter/nsBrowserStatusFilter.cpp++++ b/toolkit/components/statusfilter/nsBrowserStatusFilter.cpp+@@ -179,8 +179,16 @@ nsBrowserStatusFilter::OnStateChange(nsIWebProgress* aWebProgress,+ }++ NS_IMETHODIMP+-nsBrowserStatusFilter::OnProgressChange(nsIWebProgress* aWebProgress,+- nsIRequest* aRequest,++nsBrowserStatusFilter::OnFrameLocationChange(nsIWebProgress *aWebProgress,++ nsIRequest *aRequest,++ nsIURI *aLocation,++ uint32_t aFlags) {++ return NS_OK;++}++++NS_IMETHODIMP++nsBrowserStatusFilter::OnProgressChange(nsIWebProgress *aWebProgress,++ nsIRequest *aRequest,+ int32_t aCurSelfProgress,+ int32_t aMaxSelfProgress,+ int32_t aCurTotalProgress,+diff --git a/toolkit/toolkit.mozbuild b/toolkit/toolkit.mozbuild+index 79d6eeed7247..0362763ead99 100644+--- a/toolkit/toolkit.mozbuild++++ b/toolkit/toolkit.mozbuild+@@ -168,6 +168,7 @@ if CONFIG['ENABLE_MARIONETTE']:+ DIRS += [+ '/testing/firefox-ui',+ '/testing/marionette',++ '/testing/juggler',+ '/toolkit/components/telemetry/tests/marionette',+ ]++diff --git a/uriloader/base/nsDocLoader.cpp b/uriloader/base/nsDocLoader.cpp+index 92cb5f3cf6da..7918f127c801 100644+--- a/uriloader/base/nsDocLoader.cpp++++ b/uriloader/base/nsDocLoader.cpp+@@ -1370,6 +1370,24 @@ void nsDocLoader::FireOnLocationChange(nsIWebProgress* aWebProgress,+ }+ }+++void nsDocLoader::FireOnFrameLocationChange(nsIWebProgress* aWebProgress,++ nsIRequest* aRequest,++ nsIURI *aUri,++ uint32_t aFlags) {++ NOTIFY_LISTENERS(nsIWebProgress::NOTIFY_FRAME_LOCATION,++ nsCOMPtr<nsIWebProgressListener2> listener2 =++ do_QueryReferent(info.mWeakListener);++ if (!listener2)++ continue;++ listener2->OnFrameLocationChange(aWebProgress, aRequest, aUri, aFlags);++ );++++ // Pass the notification up to the parent...++ if (mParent) {++ mParent->FireOnFrameLocationChange(aWebProgress, aRequest, aUri, aFlags);++ }++}+++ void nsDocLoader::FireOnStatusChange(nsIWebProgress* aWebProgress,+ nsIRequest* aRequest, nsresult aStatus,+ const char16_t* aMessage) {+diff --git a/uriloader/base/nsDocLoader.h b/uriloader/base/nsDocLoader.h+index 4b551ff8e5c1..abc59361f2d6 100644+--- a/uriloader/base/nsDocLoader.h++++ b/uriloader/base/nsDocLoader.h+@@ -210,6 +210,11 @@ class nsDocLoader : public nsIDocumentLoader,+ void FireOnLocationChange(nsIWebProgress* aWebProgress, nsIRequest* aRequest,+ nsIURI* aUri, uint32_t aFlags);+++ void FireOnFrameLocationChange(nsIWebProgress* aWebProgress,++ nsIRequest* aRequest,++ nsIURI *aUri,++ uint32_t aFlags);+++ MOZ_MUST_USE bool RefreshAttempted(nsIWebProgress* aWebProgress, nsIURI* aURI,+ int32_t aDelay, bool aSameURI);++diff --git a/uriloader/base/nsIWebProgress.idl b/uriloader/base/nsIWebProgress.idl+index b0cde5026dc7..09ebb0ef6799 100644+--- a/uriloader/base/nsIWebProgress.idl++++ b/uriloader/base/nsIWebProgress.idl+@@ -87,6 +87,10 @@ interface nsIWebProgress : nsISupports+ * NOTIFY_REFRESH+ * Receive onRefreshAttempted events.+ * This is defined on nsIWebProgressListener2.++ *++ * NOTIFY_FRAME_LOCATION++ * Receive onFrameLocationChange events.++ * This is defined on nsIWebProgressListener2.+ */+ const unsigned long NOTIFY_PROGRESS = 0x00000010;+ const unsigned long NOTIFY_STATUS = 0x00000020;+@@ -94,11 +98,12 @@ interface nsIWebProgress : nsISupports+ const unsigned long NOTIFY_LOCATION = 0x00000080;+ const unsigned long NOTIFY_REFRESH = 0x00000100;+ const unsigned long NOTIFY_CONTENT_BLOCKING = 0x00000200;++ const unsigned long NOTIFY_FRAME_LOCATION = 0x00000400;++ /**+ * This flag enables all notifications.+ */+- const unsigned long NOTIFY_ALL = 0x000003ff;++ const unsigned long NOTIFY_ALL = 0x000007ff;++ /**+ * Registers a listener to receive web progress events.+diff --git a/uriloader/base/nsIWebProgressListener2.idl b/uriloader/base/nsIWebProgressListener2.idl+index 87701f8d2cfe..ae1aa85c019c 100644+--- a/uriloader/base/nsIWebProgressListener2.idl++++ b/uriloader/base/nsIWebProgressListener2.idl+@@ -66,4 +66,27 @@ interface nsIWebProgressListener2 : nsIWebProgressListener {+ in nsIURI aRefreshURI,+ in long aMillis,+ in boolean aSameURI);++++ /**++ * Called when the location of the window or its subframes changes. This is not++ * when a load is requested, but rather once it is verified that the load is++ * going to occur in the given window. For instance, a load that starts in a++ * window might send progress and status messages for the new site, but it++ * will not send the onLocationChange until we are sure that we are loading++ * this new page here.++ *++ * @param aWebProgress++ * The nsIWebProgress instance that fired the notification.++ * @param aRequest++ * The associated nsIRequest. This may be null in some cases.++ * @param aLocation++ * The URI of the location that is being loaded.++ * @param aFlags++ * This is a value which explains the situation or the reason why++ * the location has changed.++ */++ void onFrameLocationChange(in nsIWebProgress aWebProgress,++ in nsIRequest aRequest,++ in nsIURI aLocation,++ [optional] in unsigned long aFlags);+ };+--+2.17.1+diff --git a/browser_patches/upload.sh b/browser_patches/upload.shnew file mode 100755index 0000000000..0266f1ef8c--- /dev/null+++ b/browser_patches/upload.sh@@ -0,0 +1,68 @@+#!/bin/bash+set -e+set +x++cleanup() {+ cd $OLD_DIR+}++OLD_DIR=$(pwd -P)+cd "$(dirname "$0")"+trap cleanup EXIT++if [[ ($1 == '--help') || ($1 == '-h') ]]; then+ echo "usage: $0 [firefox|webkit]"+ echo+ echo "Archive and upload a browser"+ echo+ echo "NOTE: \$AZ_ACCOUNT_KEY (azure account name) and \$AZ_ACCOUNT_NAME (azure account name)"+ echo "env variables are required to upload builds to CDN."+ exit 0+fi++if [[ $# == 0 ]]; then+ echo "missing browser: 'firefox' or 'webkit'"+ echo "try '$0 --help' for more information"+ exit 1+fi++if [[ (-z $AZ_ACCOUNT_KEY) || (-z $AZ_ACCOUNT_NAME) ]]; then+ echo "ERROR: Either \$AZ_ACCOUNT_KEY or \$AZ_ACCOUNT_NAME environment variable is missing."+ echo " 'Azure Account Name' and 'Azure Account Key' secrets that are required"+ echo " to upload builds ot Azure CDN."+ exit 1+fi++ARCHIVE_SCRIPT=""+BROWSER_NAME=""+BUILD_NUMBER=""+if [[ ("$1" == "firefox") || ("$1" == "firefox/") ]]; then+ # we always apply our patches atop of beta since it seems to get better+ # reliability guarantees.+ ARCHIVE_FOLDER="$PWD/firefox"+ BUILD_NUMBER=$(cat "$PWD/firefox/BUILD_NUMBER")+ ARCHIVE_SCRIPT="$PWD/firefox/archive.sh"+ BROWSER_NAME="firefox"+elif [[ ("$1" == "webkit") || ("$1" == "webkit/") ]]; then+ ARCHIVE_FOLDER="$PWD/webkit"+ BUILD_NUMBER=$(cat "$PWD/webkit/BUILD_NUMBER")+ ARCHIVE_SCRIPT="$PWD/webkit/archive.sh"+ BROWSER_NAME="webkit"+else+ echo ERROR: unknown browser to export - "$1"+ exit 1+fi++if ! [[ -z $(ls $ARCHIVE_FOLDER | grep '.zip') ]]; then+ echo ERROR: .zip file already exists in $ARCHIVE_FOLDER!+ echo Remove manually all zip files and re-run the script.+ exit 1+fi++$ARCHIVE_SCRIPT+ZIP_NAME=$(ls $ARCHIVE_FOLDER | grep '.zip')+ZIP_PATH=$ARCHIVE_FOLDER/$ZIP_NAME+BLOB_NAME="$BROWSER_NAME/$BUILD_NUMBER/$ZIP_NAME"+az storage blob upload -c builds --account-key $AZ_ACCOUNT_KEY --account-name $AZ_ACCOUNT_NAME -f $ZIP_PATH -n "$BLOB_NAME"+echo "Uploaded $(du -h "$ZIP_PATH" | awk '{print $1}') as $BLOB_NAME"+rm $ZIP_PATHdiff --git a/browser_patches/webkit/.gitignore b/browser_patches/webkit/.gitignorenew file mode 100644index 0000000000..5e660dc18e--- /dev/null+++ b/browser_patches/webkit/.gitignore@@ -0,0 +1 @@+/checkoutdiff --git a/browser_patches/webkit/BASE_REVISION b/browser_patches/webkit/BASE_REVISIONnew file mode 100644index 0000000000..0fc3234513--- /dev/null+++ b/browser_patches/webkit/BASE_REVISION@@ -0,0 +1 @@+cadee71e3e832cc0b78184a714ade07d9a6d3173diff --git a/browser_patches/webkit/BUILD_NUMBER b/browser_patches/webkit/BUILD_NUMBERnew file mode 100644index 0000000000..d474e1b4d6--- /dev/null+++ b/browser_patches/webkit/BUILD_NUMBER@@ -0,0 +1,2 @@+1+diff --git a/browser_patches/webkit/archive.sh b/browser_patches/webkit/archive.shnew file mode 100755index 0000000000..57ebdcb0ad--- /dev/null+++ b/browser_patches/webkit/archive.sh@@ -0,0 +1,85 @@+#!/bin/bash++if [[ ("$1" == "-h") || ("$1" == "--help") ]]; then+ echo "usage: $0"+ echo+ echo "Generate distributable .zip archive from ./checkout folder that was previously built."+ echo+ exit 0+fi++set -e+set -x++main() {+ cd checkout++ if [[ "$(uname)" == "Darwin" ]]; then+ createZipForMac+ elif [[ "$(uname)" == "Linux" ]]; then+ createZipForLinux+ else+ echo "ERROR: cannot upload on this platform!" 1>&2+ exit 1;+ fi+}++createZipForLinux() {+ # create a TMP directory to copy all necessary files+ local tmpdir=$(mktemp -d -t webkit-deploy-XXXXXXXXXX)+ mkdir -p $tmpdir++ # copy all relevant binaries+ cp -t $tmpdir ./WebKitBuild/Release/bin/MiniBrowser ./WebKitBuild/Release/bin/WebKit*Process+ # copy runner+ cp -t $tmpdir ../pw_run.sh+ # copy protocol+ node ../concat_protocol.js > $tmpdir/protocol.json+ # copy all relevant shared objects+ LD_LIBRARY_PATH="$PWD/WebKitBuild/DependenciesGTK/Root/lib" ldd WebKitBuild/Release/bin/MiniBrowser | grep -o '[^ ]*WebKitBuild/[^ ]*' | xargs cp -t $tmpdir++ # we failed to nicely build libgdk_pixbuf - expect it in the env+ rm $tmpdir/libgdk_pixbuf*++ # tar resulting directory and cleanup TMP.+ local zipname="minibrowser-linux.zip"+ zip -jr ../$zipname $tmpdir+ rm -rf $tmpdir+}++createZipForMac() {+ # create a TMP directory to copy all necessary files+ local tmpdir=$(mktemp -d)++ # copy all relevant files+ ditto {./WebKitBuild/Release,$tmpdir}/com.apple.WebKit.Networking.xpc+ ditto {./WebKitBuild/Release,$tmpdir}/com.apple.WebKit.Plugin.64.xpc+ ditto {./WebKitBuild/Release,$tmpdir}/com.apple.WebKit.WebContent.xpc+ ditto {./WebKitBuild/Release,$tmpdir}/JavaScriptCore.framework+ ditto {./WebKitBuild/Release,$tmpdir}/libwebrtc.dylib+ ditto {./WebKitBuild/Release,$tmpdir}/MiniBrowser.app+ ditto {./WebKitBuild/Release,$tmpdir}/PluginProcessShim.dylib+ ditto {./WebKitBuild/Release,$tmpdir}/SecItemShim.dylib+ ditto {./WebKitBuild/Release,$tmpdir}/WebCore.framework+ ditto {./WebKitBuild/Release,$tmpdir}/WebInspectorUI.framework+ ditto {./WebKitBuild/Release,$tmpdir}/WebKit.framework+ ditto {./WebKitBuild/Release,$tmpdir}/WebKitLegacy.framework+ ditto {..,$tmpdir}/pw_run.sh+ # copy protocol+ node ../concat_protocol.js > $tmpdir/protocol.json++ # zip resulting directory and cleanup TMP.+ local MAC_MAJOR_MINOR_VERSION=$(sw_vers -productVersion | grep -o '^\d\+.\d\+')+ local zipname="minibrowser-mac-$MAC_MAJOR_MINOR_VERSION.zip"+ ditto -c -k $tmpdir ../$zipname+ rm -rf $tmpdir+}++cleanup() {+ cd $OLD_DIR+}++OLD_DIR=$(pwd -P)+cd "$(dirname "$0")"+trap cleanup EXIT+main "$@"diff --git a/browser_patches/webkit/build.sh b/browser_patches/webkit/build.shnew file mode 100755index 0000000000..ee2c12c28c--- /dev/null+++ b/browser_patches/webkit/build.sh@@ -0,0 +1,29 @@+#!/bin/bash+set -e+set +x++function cleanup() {+ cd $OLD_DIR+}++OLD_DIR=$(pwd -P)+cd "$(dirname "$0")"+trap cleanup EXIT++cd checkout++if ! [[ $(git rev-parse --abbrev-ref HEAD) == "pwdev" ]]; then+ echo "ERROR: Cannot build any branch other than PWDEV"+ exit 1;+else+ echo "-- checking git branch is PWDEV - OK"+fi++if [[ "$(uname)" == "Darwin" ]]; then+ ./Tools/Scripts/build-webkit --release+elif [[ "$(uname)" == "Linux" ]]; then+ ./Tools/Scripts/build-webkit --gtk --release MiniBrowser+else+ echo "ERROR: cannot upload on this platform!" 1>&2+ exit 1;+fidiff --git a/browser_patches/webkit/concat_protocol.js b/browser_patches/webkit/concat_protocol.jsnew file mode 100644index 0000000000..bf3d84bcc4--- /dev/null+++ b/browser_patches/webkit/concat_protocol.js@@ -0,0 +1,6 @@+const fs = require('fs');+const path = require('path');+const protocolDir = path.join(__dirname, './checkout/Source/JavaScriptCore/inspector/protocol');+const files = fs.readdirSync(protocolDir).filter(f => f.endsWith('.json')).map(f => path.join(protocolDir, f));+const json = files.map(file => JSON.parse(fs.readFileSync(file)));+console.log(JSON.stringify(json));diff --git a/browser_patches/webkit/patches/0001-chore-bootstrap.patch b/browser_patches/webkit/patches/0001-chore-bootstrap.patchnew file mode 100644index 0000000000..1e2b20bc94--- /dev/null+++ b/browser_patches/webkit/patches/0001-chore-bootstrap.patch@@ -0,0 +1,5890 @@+From 23d352fbff5f65f02eec92327a5c839b9f6c6fca Mon Sep 17 00:00:00 2001+From: Andrey Lushnikov <[email protected]>+Date: Fri, 15 Nov 2019 18:07:34 -0800+Subject: [PATCH xserver] chore: bootstrap++---+ Source/JavaScriptCore/CMakeLists.txt | 3 ++ Source/JavaScriptCore/DerivedSources.make | 3 ++ .../inspector/InspectorBackendDispatcher.cpp | 21 +-+ .../inspector/InspectorBackendDispatcher.h | 5 +-+ .../inspector/InspectorTarget.h | 3 ++ .../inspector/agents/InspectorTargetAgent.cpp | 46 +++-+ .../inspector/agents/InspectorTargetAgent.h | 6 +-+ .../inspector/protocol/Browser.json | 40 ++++ .../inspector/protocol/DOM.json | 21 +++ .../inspector/protocol/Emulation.json | 14 ++ .../inspector/protocol/Input.json | 160 ++++++++++++ .../inspector/protocol/Page.json | 18 +-+ .../inspector/protocol/Target.json | 18 +-+ .../inspector/InspectorInstrumentation.cpp | 6 ++ .../inspector/InspectorInstrumentation.h | 9 ++ .../inspector/agents/InspectorDOMAgent.cpp | 57 +++++ .../inspector/agents/InspectorDOMAgent.h | 1 ++ .../inspector/agents/InspectorPageAgent.cpp | 18 +-+ .../inspector/agents/InspectorPageAgent.h | 3 +-+ Source/WebCore/loader/FrameLoader.cpp | 1 ++ Source/WebCore/page/History.cpp | 1 ++ .../WebCore/platform/PlatformKeyboardEvent.h | 2 ++ .../platform/gtk/PlatformKeyboardEventGtk.cpp | 242 ++++++++++++++++++ .../libwpe/PlatformKeyboardEventLibWPE.cpp | 240 +++++++++++++++++ Source/WebKit/Shared/API/c/wpe/WebKit.h | 1 ++ Source/WebKit/Shared/NativeWebKeyboardEvent.h | 5 ++ Source/WebKit/Shared/NativeWebMouseEvent.h | 4 ++ Source/WebKit/Shared/WebEvent.h | 6 +-+ Source/WebKit/Shared/WebKeyboardEvent.cpp | 22 +++ .../Shared/gtk/NativeWebKeyboardEventGtk.cpp | 2 +-+ .../Shared/gtk/NativeWebMouseEventGtk.cpp | 4 +-+ Source/WebKit/Sources.txt | 8 ++ Source/WebKit/SourcesCocoa.txt | 1 ++ Source/WebKit/SourcesGTK.txt | 5 ++ Source/WebKit/SourcesWPE.txt | 6 +-+ Source/WebKit/UIProcess/API/APIAttachment.cpp | 1 ++ Source/WebKit/UIProcess/API/C/WKPage.cpp | 2 ++ .../UIProcess/API/Cocoa/_WKBrowserInspector.h | 50 +++++ .../API/Cocoa/_WKBrowserInspector.mm | 52 +++++ .../API/glib/WebKitBrowserInspector.cpp | 141 +++++++++++ .../API/glib/WebKitBrowserInspectorPrivate.h | 36 ++++ .../UIProcess/API/glib/WebKitWebContext.cpp | 5 ++ .../UIProcess/API/gtk/PageClientImpl.cpp | 2 ++ .../API/gtk/WebKitBrowserInspector.h | 84 +++++++ Source/WebKit/UIProcess/API/gtk/webkit2.h | 1 ++ .../API/wpe/WebKitBrowserInspector.h | 81 +++++++ Source/WebKit/UIProcess/API/wpe/webkit.h | 1 ++ .../UIProcess/BrowserInspectorController.cpp | 128 ++++++++++ .../UIProcess/BrowserInspectorController.h | 74 ++++++ .../WebKit/UIProcess/BrowserInspectorPipe.cpp | 62 ++++++ .../WebKit/UIProcess/BrowserInspectorPipe.h | 43 ++++ .../UIProcess/BrowserInspectorTargetAgent.cpp | 110 +++++++++ .../UIProcess/BrowserInspectorTargetAgent.h | 62 ++++++ .../PopUpSOAuthorizationSession.h | 4 ++ .../PopUpSOAuthorizationSession.mm | 1 ++ .../UIProcess/InspectorBrowserAgent.cpp | 101 ++++++++ .../WebKit/UIProcess/InspectorBrowserAgent.h | 81 +++++++ .../UIProcess/InspectorBrowserAgentClient.h | 52 +++++ .../WebKit/UIProcess/InspectorTargetProxy.cpp | 18 +-+ .../WebKit/UIProcess/InspectorTargetProxy.h | 11 +-+ .../WebKit/UIProcess/RemoteInspectorPipe.cpp | 159 ++++++++++++ Source/WebKit/UIProcess/RemoteInspectorPipe.h | 70 ++++++ .../AuthenticatorManager.cpp | 1 ++ .../UIProcess/WebPageInspectorController.cpp | 56 +++-+ .../UIProcess/WebPageInspectorController.h | 8 ++ .../WebPageInspectorEmulationAgent.cpp | 61 ++++++ .../WebPageInspectorEmulationAgent.h | 63 ++++++ .../UIProcess/WebPageInspectorInputAgent.cpp | 257 +++++++++++++++++++ .../UIProcess/WebPageInspectorInputAgent.h | 76 +++++++ .../UIProcess/WebPageInspectorTargetProxy.cpp | 129 ++++++++++ .../UIProcess/WebPageInspectorTargetProxy.h | 67 ++++++ Source/WebKit/UIProcess/WebPageProxy.cpp | 12 +-+ Source/WebKit/UIProcess/WebPageProxy.h | 9 ++ .../glib/InspectorBrowserAgentClientGLib.cpp | 130 ++++++++++ .../glib/InspectorBrowserAgentClientGLib.h | 63 ++++++ .../gtk/WebPageInspectorEmulationAgentGtk.cpp | 58 +++++ .../gtk/WebPageInspectorInputAgentGtk.cpp | 108 +++++++++ .../gtk/WebPageInspectorTargetProxyGtk.cpp | 45 ++++ .../WebKit/UIProcess/ios/PageClientImplIOS.mm | 2 ++ .../mac/InspectorBrowserAgentClientMac.h | 56 +++++ .../mac/InspectorBrowserAgentClientMac.mm | 95 ++++++++ .../WebKit/UIProcess/mac/PageClientImplMac.mm | 5 ++ .../mac/WebPageInspectorEmulationAgentMac.mm | 42 ++++ .../mac/WebPageInspectorInputAgentMac.mm | 37 ++++ .../mac/WebPageInspectorTargetProxyMac.mm | 41 ++++ .../wpe/WebPageInspectorEmulationAgentWPE.cpp | 41 ++++ .../wpe/WebPageInspectorInputAgentWPE.cpp | 99 ++++++++ .../wpe/WebPageInspectorTargetProxyWPE.cpp | 41 ++++ .../WebKit/WebKit.xcodeproj/project.pbxproj | 54 +++++ .../WebPage/WebPageInspectorTarget.cpp | 7 ++ .../WebPage/WebPageInspectorTarget.h | 1 ++ Source/WebKit/WebProcess/WebProcess.cpp | 3 +-+ Tools/MiniBrowser/gtk/main.c | 28 +++ Tools/MiniBrowser/mac/AppDelegate.h | 4 +-+ Tools/MiniBrowser/mac/AppDelegate.m | 25 +-+ .../mac/WK2BrowserWindowController.h | 3 ++ .../mac/WK2BrowserWindowController.m | 17 +-+ Tools/MiniBrowser/wpe/main.cpp | 37 ++++ 98 files changed, 4162 insertions(+), 53 deletions(-)+ create mode 100644 Source/JavaScriptCore/inspector/protocol/Browser.json+ create mode 100644 Source/JavaScriptCore/inspector/protocol/Emulation.json+ create mode 100644 Source/JavaScriptCore/inspector/protocol/Input.json+ create mode 100644 Source/WebKit/UIProcess/API/Cocoa/_WKBrowserInspector.h+ create mode 100644 Source/WebKit/UIProcess/API/Cocoa/_WKBrowserInspector.mm+ create mode 100644 Source/WebKit/UIProcess/API/glib/WebKitBrowserInspector.cpp+ create mode 100644 Source/WebKit/UIProcess/API/glib/WebKitBrowserInspectorPrivate.h+ create mode 100644 Source/WebKit/UIProcess/API/gtk/WebKitBrowserInspector.h+ create mode 100644 Source/WebKit/UIProcess/API/wpe/WebKitBrowserInspector.h+ create mode 100644 Source/WebKit/UIProcess/BrowserInspectorController.cpp+ create mode 100644 Source/WebKit/UIProcess/BrowserInspectorController.h+ create mode 100644 Source/WebKit/UIProcess/BrowserInspectorPipe.cpp+ create mode 100644 Source/WebKit/UIProcess/BrowserInspectorPipe.h+ create mode 100644 Source/WebKit/UIProcess/BrowserInspectorTargetAgent.cpp+ create mode 100644 Source/WebKit/UIProcess/BrowserInspectorTargetAgent.h+ create mode 100644 Source/WebKit/UIProcess/InspectorBrowserAgent.cpp+ create mode 100644 Source/WebKit/UIProcess/InspectorBrowserAgent.h+ create mode 100644 Source/WebKit/UIProcess/InspectorBrowserAgentClient.h+ create mode 100644 Source/WebKit/UIProcess/RemoteInspectorPipe.cpp+ create mode 100644 Source/WebKit/UIProcess/RemoteInspectorPipe.h+ create mode 100644 Source/WebKit/UIProcess/WebPageInspectorEmulationAgent.cpp+ create mode 100644 Source/WebKit/UIProcess/WebPageInspectorEmulationAgent.h+ create mode 100644 Source/WebKit/UIProcess/WebPageInspectorInputAgent.cpp+ create mode 100644 Source/WebKit/UIProcess/WebPageInspectorInputAgent.h+ create mode 100644 Source/WebKit/UIProcess/WebPageInspectorTargetProxy.cpp+ create mode 100644 Source/WebKit/UIProcess/WebPageInspectorTargetProxy.h+ create mode 100644 Source/WebKit/UIProcess/glib/InspectorBrowserAgentClientGLib.cpp+ create mode 100644 Source/WebKit/UIProcess/glib/InspectorBrowserAgentClientGLib.h+ create mode 100644 Source/WebKit/UIProcess/gtk/WebPageInspectorEmulationAgentGtk.cpp+ create mode 100644 Source/WebKit/UIProcess/gtk/WebPageInspectorInputAgentGtk.cpp+ create mode 100644 Source/WebKit/UIProcess/gtk/WebPageInspectorTargetProxyGtk.cpp+ create mode 100644 Source/WebKit/UIProcess/mac/InspectorBrowserAgentClientMac.h+ create mode 100644 Source/WebKit/UIProcess/mac/InspectorBrowserAgentClientMac.mm+ create mode 100644 Source/WebKit/UIProcess/mac/WebPageInspectorEmulationAgentMac.mm+ create mode 100644 Source/WebKit/UIProcess/mac/WebPageInspectorInputAgentMac.mm+ create mode 100644 Source/WebKit/UIProcess/mac/WebPageInspectorTargetProxyMac.mm+ create mode 100644 Source/WebKit/UIProcess/wpe/WebPageInspectorEmulationAgentWPE.cpp+ create mode 100644 Source/WebKit/UIProcess/wpe/WebPageInspectorInputAgentWPE.cpp+ create mode 100644 Source/WebKit/UIProcess/wpe/WebPageInspectorTargetProxyWPE.cpp++diff --git a/Source/JavaScriptCore/CMakeLists.txt b/Source/JavaScriptCore/CMakeLists.txt+index f25ff61db99..a7085df58f8 100644+--- a/Source/JavaScriptCore/CMakeLists.txt++++ b/Source/JavaScriptCore/CMakeLists.txt+@@ -1142,6 +1142,7 @@ set(JavaScriptCore_INSPECTOR_DOMAINS+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Animation.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/ApplicationCache.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Audit.json++ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Browser.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/CSS.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Canvas.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Console.json+@@ -1150,8 +1151,10 @@ set(JavaScriptCore_INSPECTOR_DOMAINS+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/DOMStorage.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Database.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Debugger.json++ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Emulation.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/GenericTypes.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Heap.json++ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Input.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Inspector.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/LayerTree.json+ ${JAVASCRIPTCORE_DIR}/inspector/protocol/Network.json+diff --git a/Source/JavaScriptCore/DerivedSources.make b/Source/JavaScriptCore/DerivedSources.make+index f59212ff01c..c1fb126e017 100644+--- a/Source/JavaScriptCore/DerivedSources.make++++ b/Source/JavaScriptCore/DerivedSources.make+@@ -238,6 +238,7 @@ INSPECTOR_DOMAINS := \+ $(JavaScriptCore)/inspector/protocol/Animation.json \+ $(JavaScriptCore)/inspector/protocol/ApplicationCache.json \+ $(JavaScriptCore)/inspector/protocol/Audit.json \++ $(JavaScriptCore)/inspector/protocol/Browser.json \+ $(JavaScriptCore)/inspector/protocol/CSS.json \+ $(JavaScriptCore)/inspector/protocol/Canvas.json \+ $(JavaScriptCore)/inspector/protocol/Console.json \+@@ -246,8 +247,10 @@ INSPECTOR_DOMAINS := \+ $(JavaScriptCore)/inspector/protocol/DOMStorage.json \+ $(JavaScriptCore)/inspector/protocol/Database.json \+ $(JavaScriptCore)/inspector/protocol/Debugger.json \++ $(JavaScriptCore)/inspector/protocol/Emulation.json \+ $(JavaScriptCore)/inspector/protocol/GenericTypes.json \+ $(JavaScriptCore)/inspector/protocol/Heap.json \++ $(JavaScriptCore)/inspector/protocol/Input.json \+ $(JavaScriptCore)/inspector/protocol/Inspector.json \+ $(JavaScriptCore)/inspector/protocol/LayerTree.json \+ $(JavaScriptCore)/inspector/protocol/Network.json \+diff --git a/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.cpp b/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.cpp+index 038cb646d31..8a01d7679bf 100644+--- a/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.cpp++++ b/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.cpp+@@ -102,7 +102,7 @@ void BackendDispatcher::registerDispatcherForDomain(const String& domain, Supple+ m_dispatchers.set(domain, dispatcher);+ }++-void BackendDispatcher::dispatch(const String& message)++BackendDispatcher::DispatchResult BackendDispatcher::dispatch(const String& message, Mode mode)+ {+ Ref<BackendDispatcher> protect(*this);++@@ -120,26 +120,26 @@ void BackendDispatcher::dispatch(const String& message)+ if (!JSON::Value::parseJSON(message, parsedMessage)) {+ reportProtocolError(ParseError, "Message must be in JSON format"_s);+ sendPendingErrors();+- return;++ return DispatchResult::Finished;+ }++ if (!parsedMessage->asObject(messageObject)) {+ reportProtocolError(InvalidRequest, "Message must be a JSONified object"_s);+ sendPendingErrors();+- return;++ return DispatchResult::Finished;+ }++ RefPtr<JSON::Value> requestIdValue;+ if (!messageObject->getValue("id"_s, requestIdValue)) {+ reportProtocolError(InvalidRequest, "'id' property was not found"_s);+ sendPendingErrors();+- return;++ return DispatchResult::Finished;+ }++ if (!requestIdValue->asInteger(requestId)) {+ reportProtocolError(InvalidRequest, "The type of 'id' property must be integer"_s);+ sendPendingErrors();+- return;++ return DispatchResult::Finished;+ }+ }++@@ -151,29 +151,31 @@ void BackendDispatcher::dispatch(const String& message)+ if (!messageObject->getValue("method"_s, methodValue)) {+ reportProtocolError(InvalidRequest, "'method' property wasn't found"_s);+ sendPendingErrors();+- return;++ return DispatchResult::Finished;+ }++ String methodString;+ if (!methodValue->asString(methodString)) {+ reportProtocolError(InvalidRequest, "The type of 'method' property must be string"_s);+ sendPendingErrors();+- return;++ return DispatchResult::Finished;+ }++ Vector<String> domainAndMethod = methodString.splitAllowingEmptyEntries('.');+ if (domainAndMethod.size() != 2 || !domainAndMethod[0].length() || !domainAndMethod[1].length()) {+ reportProtocolError(InvalidRequest, "The 'method' property was formatted incorrectly. It should be 'Domain.method'"_s);+ sendPendingErrors();+- return;++ return DispatchResult::Finished;+ }++ String domain = domainAndMethod[0];+ SupplementalBackendDispatcher* domainDispatcher = m_dispatchers.get(domain);+ if (!domainDispatcher) {++ if (mode == Mode::ContinueIfDomainIsMissing)++ return DispatchResult::Continue;+ reportProtocolError(MethodNotFound, "'" + domain + "' domain was not found");+ sendPendingErrors();+- return;++ return DispatchResult::Finished;+ }++ String method = domainAndMethod[1];+@@ -182,6 +184,7 @@ void BackendDispatcher::dispatch(const String& message)+ if (m_protocolErrors.size())+ sendPendingErrors();+ }++ return DispatchResult::Finished;+ }++ // FIXME: remove this function when legacy InspectorObject symbols are no longer needed <http://webkit.org/b/179847>.+diff --git a/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.h b/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.h+index 95d9d81188e..6f96f174dff 100644+--- a/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.h++++ b/Source/JavaScriptCore/inspector/InspectorBackendDispatcher.h+@@ -82,7 +82,10 @@ public:+ };++ void registerDispatcherForDomain(const String& domain, SupplementalBackendDispatcher*);+- void dispatch(const String& message);++++ enum class DispatchResult { Finished, Continue };++ enum class Mode { FailIfDomainIsMissing, ContinueIfDomainIsMissing };++ DispatchResult dispatch(const String& message, Mode mode = Mode::FailIfDomainIsMissing);++ // Note that 'unused' is a workaround so the compiler can pick the right sendResponse based on arity.+ // When <http://webkit.org/b/179847> is fixed or this class is renamed for the JSON::Object case,+diff --git a/Source/JavaScriptCore/inspector/InspectorTarget.h b/Source/JavaScriptCore/inspector/InspectorTarget.h+index a9f04b8a0c9..045b9ecd39a 100644+--- a/Source/JavaScriptCore/inspector/InspectorTarget.h++++ b/Source/JavaScriptCore/inspector/InspectorTarget.h+@@ -45,6 +45,7 @@ public:+ // State.+ virtual String identifier() const = 0;+ virtual InspectorTargetType type() const = 0;++ virtual String url() const = 0;++ virtual bool isProvisional() const { return false; }++@@ -52,6 +53,8 @@ public:+ virtual void connect(FrontendChannel::ConnectionType) = 0;+ virtual void disconnect() = 0;+ virtual void sendMessageToTargetBackend(const String&) = 0;++ virtual void activate(String& error) { error = "Target cannot be activated"; }++ virtual void close(String& error) { error = "Target cannot be closed"; }+ };++ } // namespace Inspector+diff --git a/Source/JavaScriptCore/inspector/agents/InspectorTargetAgent.cpp b/Source/JavaScriptCore/inspector/agents/InspectorTargetAgent.cpp+index 1177090fc18..764b62c727c 100644+--- a/Source/JavaScriptCore/inspector/agents/InspectorTargetAgent.cpp++++ b/Source/JavaScriptCore/inspector/agents/InspectorTargetAgent.cpp+@@ -30,11 +30,12 @@++ namespace Inspector {++-InspectorTargetAgent::InspectorTargetAgent(FrontendRouter& frontendRouter, BackendDispatcher& backendDispatcher)++InspectorTargetAgent::InspectorTargetAgent(FrontendRouter& frontendRouter, BackendDispatcher& backendDispatcher, const String& browserContextID)+ : InspectorAgentBase("Target"_s)+ , m_router(frontendRouter)+ , m_frontendDispatcher(makeUnique<TargetFrontendDispatcher>(frontendRouter))+ , m_backendDispatcher(TargetBackendDispatcher::create(backendDispatcher, this))++ , m_browserContextID(browserContextID)+ {+ }++@@ -65,6 +66,28 @@ void InspectorTargetAgent::sendMessageToTarget(ErrorString& errorString, const S+ target->sendMessageToTargetBackend(message);+ }+++void InspectorTargetAgent::activate(ErrorString& errorString, const String& targetId)++{++ InspectorTarget* target = m_targets.get(targetId);++ if (!target) {++ errorString = "Missing target for given targetId"_s;++ return;++ }++++ target->activate(errorString);++}++++void InspectorTargetAgent::close(ErrorString& errorString, const String& targetId)++{++ InspectorTarget* target = m_targets.get(targetId);++ if (!target) {++ errorString = "Missing target for given targetId"_s;++ return;++ }++++ target->close(errorString);++}+++ void InspectorTargetAgent::sendMessageFromTargetToFrontend(const String& targetId, const String& message)+ {+ ASSERT_WITH_MESSAGE(m_targets.get(targetId), "Sending a message from an untracked target to the frontend.");+@@ -87,14 +110,17 @@ static Protocol::Target::TargetInfo::Type targetTypeToProtocolType(InspectorTarg+ return Protocol::Target::TargetInfo::Type::Page;+ }++-static Ref<Protocol::Target::TargetInfo> buildTargetInfoObject(const InspectorTarget& target)++static Ref<Protocol::Target::TargetInfo> buildTargetInfoObject(const InspectorTarget& target, const String& browserContextID)+ {+ auto result = Protocol::Target::TargetInfo::create()+ .setTargetId(target.identifier())+ .setType(targetTypeToProtocolType(target.type()))++ .setUrl(target.url())+ .release();+ if (target.isProvisional())+ result->setIsProvisional(true);++ if (!browserContextID.isEmpty())++ result->setBrowserContextId(browserContextID);+ return result;+ }++@@ -108,7 +134,7 @@ void InspectorTargetAgent::targetCreated(InspectorTarget& target)++ target.connect(connectionType());++- m_frontendDispatcher->targetCreated(buildTargetInfoObject(target));++ m_frontendDispatcher->targetCreated(buildTargetInfoObject(target, m_browserContextID));+ }++ void InspectorTargetAgent::targetDestroyed(InspectorTarget& target)+@@ -135,6 +161,18 @@ void InspectorTargetAgent::didCommitProvisionalTarget(const String& oldTargetID,+ m_frontendDispatcher->didCommitProvisionalTarget(oldTargetID, committedTargetID);+ }+++void InspectorTargetAgent::ensureConnected(const String& targetID)++{++ if (!m_isConnected)++ return;++++ auto* target = m_targets.get(targetID);++ if (!target)++ return;++++ target->connect(connectionType());++}+++ FrontendChannel::ConnectionType InspectorTargetAgent::connectionType() const+ {+ return m_router.hasLocalFrontend() ? Inspector::FrontendChannel::ConnectionType::Local : Inspector::FrontendChannel::ConnectionType::Remote;+@@ -144,7 +182,7 @@ void InspectorTargetAgent::connectToTargets()+ {+ for (InspectorTarget* target : m_targets.values()) {+ target->connect(connectionType());+- m_frontendDispatcher->targetCreated(buildTargetInfoObject(*target));++ m_frontendDispatcher->targetCreated(buildTargetInfoObject(*target, m_browserContextID));+ }+ }++diff --git a/Source/JavaScriptCore/inspector/agents/InspectorTargetAgent.h b/Source/JavaScriptCore/inspector/agents/InspectorTargetAgent.h+index 38cb318986b..4287e05e559 100644+--- a/Source/JavaScriptCore/inspector/agents/InspectorTargetAgent.h++++ b/Source/JavaScriptCore/inspector/agents/InspectorTargetAgent.h+@@ -41,7 +41,7 @@ class JS_EXPORT_PRIVATE InspectorTargetAgent : public InspectorAgentBase, public+ WTF_MAKE_NONCOPYABLE(InspectorTargetAgent);+ WTF_MAKE_FAST_ALLOCATED;+ public:+- InspectorTargetAgent(FrontendRouter&, BackendDispatcher&);++ InspectorTargetAgent(FrontendRouter&, BackendDispatcher&, const String& browserContextID);+ ~InspectorTargetAgent() override;++ // InspectorAgentBase+@@ -50,11 +50,14 @@ public:++ // TargetBackendDispatcherHandler+ void sendMessageToTarget(ErrorString&, const String& targetId, const String& message) final;++ void activate(ErrorString&, const String& targetId) override;++ void close(ErrorString&, const String& targetId) override;++ // Target lifecycle.+ void targetCreated(InspectorTarget&);+ void targetDestroyed(InspectorTarget&);+ void didCommitProvisionalTarget(const String& oldTargetID, const String& committedTargetID);++ void ensureConnected(const String& targetID);++ // Target messages.+ void sendMessageFromTargetToFrontend(const String& targetId, const String& message);+@@ -68,6 +71,7 @@ private:+ Inspector::FrontendRouter& m_router;+ std::unique_ptr<TargetFrontendDispatcher> m_frontendDispatcher;+ Ref<TargetBackendDispatcher> m_backendDispatcher;++ const String m_browserContextID;+ HashMap<String, InspectorTarget*> m_targets;+ bool m_isConnected { false };+ };+diff --git a/Source/JavaScriptCore/inspector/protocol/Browser.json b/Source/JavaScriptCore/inspector/protocol/Browser.json+new file mode 100644+index 00000000000..bed4a3bfe6f+--- /dev/null++++ b/Source/JavaScriptCore/inspector/protocol/Browser.json+@@ -0,0 +1,40 @@++{++ "domain": "Browser",++ "availability": ["web"],++ "types": [++ {++ "id": "ContextID",++ "type": "string",++ "description": "Id of Browser context."++ }++ ],++ "commands": [++ {++ "name": "close",++ "description": "Close browser."++ },++ {++ "name": "createContext",++ "description": "Creates new ephemeral browser context.",++ "returns": [++ { "name": "browserContextId", "$ref": "ContextID", "description": "Unique identifier of the context." }++ ]++ },++ {++ "name": "deleteContext",++ "description": "Deletes browser context previously created with createContect. The command will automatically close all pages that use the context.",++ "parameters": [++ { "name": "browserContextId", "$ref": "ContextID", "description": "Identifier of the context to delete." }++ ]++ },++ {++ "name": "createPage",++ "parameters": [++ { "name": "browserContextId", "$ref": "ContextID", "optional": true, "description": "JSON Inspector Protocol message (command) to be dispatched on the backend." }++ ],++ "returns": [++ { "name": "targetId", "type": "string", "description": "Unique identifier for the page target." }++ ]++ }++ ]++}+diff --git a/Source/JavaScriptCore/inspector/protocol/DOM.json b/Source/JavaScriptCore/inspector/protocol/DOM.json+index 38cb48bedf2..285027ae5d7 100644+--- a/Source/JavaScriptCore/inspector/protocol/DOM.json++++ b/Source/JavaScriptCore/inspector/protocol/DOM.json+@@ -542,6 +542,27 @@+ "parameters": [+ { "name": "allow", "type": "boolean" }+ ]++ },++ {++ "name": "getContentQuads",++ "description": "Returns quads that describe node position on the page. This method\nmight return multiple quads for inline nodes.",++ "parameters": [++ {++ "name": "objectId",++ "description": "JavaScript object id of the node wrapper.",++ "$ref": "Runtime.RemoteObjectId"++ }++ ],++ "returns": [++ {++ "name": "quads",++ "description": "Quads that describe node layout relative to viewport.",++ "type": "array",++ "items": {++ "$ref": "Quad"++ }++ }++ ]+ }+ ],+ "events": [+diff --git a/Source/JavaScriptCore/inspector/protocol/Emulation.json b/Source/JavaScriptCore/inspector/protocol/Emulation.json+new file mode 100644+index 00000000000..168e3f2b93d+--- /dev/null++++ b/Source/JavaScriptCore/inspector/protocol/Emulation.json+@@ -0,0 +1,14 @@++{++ "domain": "Emulation",++ "availability": ["web"],++ "commands": [++ {++ "name": "setDeviceMetricsOverride",++ "description": "Overrides device metrics with provided values.",++ "parameters": [++ { "name": "width", "type": "integer" },++ { "name": "height", "type": "integer" }++ ]++ }++ ]++}+diff --git a/Source/JavaScriptCore/inspector/protocol/Input.json b/Source/JavaScriptCore/inspector/protocol/Input.json+new file mode 100644+index 00000000000..79bbe73b0df+--- /dev/null++++ b/Source/JavaScriptCore/inspector/protocol/Input.json+@@ -0,0 +1,160 @@++{++ "domain": "Input",++ "availability": ["web"],++ "types": [++ {++ "id": "TimeSinceEpoch",++ "description": "UTC time in seconds, counted from January 1, 1970.",++ "type": "number"++ }++ ],++ "commands": [++ {++ "name": "goBack",++ "description": "FIXME: move this to Page domain."++ },++ {++ "name": "dispatchKeyEvent",++ "description": "Dispatches a key event to the page.",++ "async": true,++ "parameters": [++ {++ "name": "type",++ "description": "Type of the key event.",++ "type": "string",++ "enum": [++ "keyDown",++ "keyUp"++ ]++ },++ {++ "name": "modifiers",++ "description": "Bit field representing pressed modifier keys. (default: 0).",++ "optional": true,++ "type": "integer"++ },++ {++ "name": "text",++ "description": "Text as generated by processing a virtual key code with a keyboard layout. Not needed for\nfor `keyUp` and `rawKeyDown` events (default: \"\")",++ "optional": true,++ "type": "string"++ },++ {++ "name": "unmodifiedText",++ "description": "Text that would have been generated by the keyboard if no modifiers were pressed (except for\nshift). Useful for shortcut (accelerator) key handling (default: \"\").",++ "optional": true,++ "type": "string"++ },++ {++ "name": "code",++ "description": "Unique DOM defined string value for each physical key (e.g., 'KeyA') (default: \"\").",++ "optional": true,++ "type": "string"++ },++ {++ "name": "key",++ "description": "Unique DOM defined string value describing the meaning of the key in the context of active\nmodifiers, keyboard layout, etc (e.g., 'AltGr') (default: \"\").",++ "optional": true,++ "type": "string"++ },++ {++ "name": "windowsVirtualKeyCode",++ "description": "Windows virtual key code (default: 0).",++ "optional": true,++ "type": "integer"++ },++ {++ "name": "nativeVirtualKeyCode",++ "description": "Native virtual key code (default: 0).",++ "optional": true,++ "type": "integer"++ },++ {++ "name": "autoRepeat",++ "description": "Whether the event was generated from auto repeat (default: false).",++ "optional": true,++ "type": "boolean"++ },++ {++ "name": "isKeypad",++ "description": "Whether the event was generated from the keypad (default: false).",++ "optional": true,++ "type": "boolean"++ },++ {++ "name": "isSystemKey",++ "description": "Whether the event was a system key event (default: false).",++ "optional": true,++ "type": "boolean"++ }++ ]++ },++ {++ "name": "dispatchMouseEvent",++ "description": "Dispatches a mouse event to the page.",++ "async": true,++ "parameters": [++ {++ "name": "type",++ "description": "Type of the mouse event.",++ "type": "string",++ "enum": [ "move", "down", "up", "wheel"]++ },++ {++ "name": "x",++ "description": "X coordinate of the event relative to the main frame's viewport in CSS pixels.",++ "type": "integer"++ },++ {++ "name": "y",++ "description": "Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to\nthe top of the viewport and Y increases as it proceeds towards the bottom of the viewport.",++ "type": "integer"++ },++ {++ "name": "modifiers",++ "description": "Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8\n(default: 0).",++ "optional": true,++ "type": "integer"++ },++ {++ "name": "button",++ "description": "Mouse button (default: \"none\").",++ "optional": true,++ "type": "string",++ "enum": [++ "none",++ "left",++ "middle",++ "right",++ "back",++ "forward"++ ]++ },++ {++ "name": "buttons",++ "description": "A number indicating which buttons are pressed on the mouse when a mouse event is triggered.\nLeft=1, Right=2, Middle=4, Back=8, Forward=16, None=0.",++ "optional": true,++ "type": "integer"++ },++ {++ "name": "clickCount",++ "description": "Number of times the mouse button was clicked (default: 0).",++ "optional": true,++ "type": "integer"++ },++ {++ "name": "deltaX",++ "description": "X delta in CSS pixels for mouse wheel event (default: 0).",++ "optional": true,++ "type": "integer"++ },++ {++ "name": "deltaY",++ "description": "Y delta in CSS pixels for mouse wheel event (default: 0).",++ "optional": true,++ "type": "integer"++ }++ ]++ }++ ]++}+diff --git a/Source/JavaScriptCore/inspector/protocol/Page.json b/Source/JavaScriptCore/inspector/protocol/Page.json+index 367d1f235a8..62321e6c893 100644+--- a/Source/JavaScriptCore/inspector/protocol/Page.json++++ b/Source/JavaScriptCore/inspector/protocol/Page.json+@@ -131,7 +131,8 @@+ "name": "navigate",+ "description": "Navigates current page to the given URL.",+ "parameters": [+- { "name": "url", "type": "string", "description": "URL to navigate the page to." }++ { "name": "url", "type": "string", "description": "URL to navigate the page to." },++ { "name": "frameId", "$ref": "Network.FrameId", "optional": true, "description": "Id of the frame to navigate."}+ ]+ },+ {+@@ -347,6 +348,21 @@+ ]+ },+ {++ "name": "navigatedWithinDocument",++ "description": "Fired when same-document navigation happens, e.g. due to history API usage or anchor navigation.",++ "parameters": [++ {++ "name": "frameId",++ "description": "Id of the frame.",++ "$ref": "Network.FrameId"++ },++ {++ "name": "url",++ "description": "Frame's new url.",++ "type": "string"++ }++ ]++ }, {+ "name": "defaultAppearanceDidChange",+ "description": "Fired when page's default appearance changes, even if there is a forced appearance.",+ "parameters": [+diff --git a/Source/JavaScriptCore/inspector/protocol/Target.json b/Source/JavaScriptCore/inspector/protocol/Target.json+index 240cd42e67e..f635c67ef3f 100644+--- a/Source/JavaScriptCore/inspector/protocol/Target.json++++ b/Source/JavaScriptCore/inspector/protocol/Target.json+@@ -10,7 +10,9 @@+ "properties": [+ { "name": "targetId", "type": "string", "description": "Unique identifier for the target." },+ { "name": "type", "type": "string", "enum": ["page", "service-worker", "worker"] },+- { "name": "isProvisional", "type": "boolean", "optional": true, "description": "True value indicates that this is a provisional page target i.e. Such target may be created when current page starts cross-origin navigation. Eventually each provisional target is either committed and swaps with the current target or gets destroyed, e.g. in case of load request failure." }++ { "name": "url", "type": "string" },++ { "name": "isProvisional", "type": "boolean", "optional": true, "description": "True value indicates that this is a provisional page target i.e. Such target may be created when current page starts cross-origin navigation. Eventually each provisional target is either committed and swaps with the current target or gets destroyed, e.g. in case of load request failure." },++ { "name": "browserContextId", "$ref": "Browser.ContextID", "optional": true }+ ]+ }+ ],+@@ -22,6 +24,20 @@+ { "name": "targetId", "type": "string" },+ { "name": "message", "type": "string", "description": "JSON Inspector Protocol message (command) to be dispatched on the backend." }+ ]++ },++ {++ "name": "activate",++ "description": "Reveals the target on screen.",++ "parameters": [++ { "name": "targetId", "type": "string" }++ ]++ },++ {++ "name": "close",++ "description": "Closes the target.",++ "parameters": [++ { "name": "targetId", "type": "string" }++ ]+ }+ ],+ "events": [+diff --git a/Source/WebCore/inspector/InspectorInstrumentation.cpp b/Source/WebCore/inspector/InspectorInstrumentation.cpp+index 4b7bec1b460..97fb3543d40 100644+--- a/Source/WebCore/inspector/InspectorInstrumentation.cpp++++ b/Source/WebCore/inspector/InspectorInstrumentation.cpp+@@ -782,6 +782,12 @@ void InspectorInstrumentation::frameClearedScheduledNavigationImpl(Instrumenting+ inspectorPageAgent->frameClearedScheduledNavigation(frame);+ }+++void InspectorInstrumentation::didNavigateWithinPageImpl(InstrumentingAgents& instrumentingAgents, Frame& frame)++{++ if (InspectorPageAgent* inspectorPageAgent = instrumentingAgents.inspectorPageAgent())++ inspectorPageAgent->didNavigateWithinPage(frame);++}+++ void InspectorInstrumentation::defaultAppearanceDidChangeImpl(InstrumentingAgents& instrumentingAgents, bool useDarkAppearance)+ {+ if (InspectorPageAgent* inspectorPageAgent = instrumentingAgents.inspectorPageAgent())+diff --git a/Source/WebCore/inspector/InspectorInstrumentation.h b/Source/WebCore/inspector/InspectorInstrumentation.h+index 6698431f316..40dd67f43e9 100644+--- a/Source/WebCore/inspector/InspectorInstrumentation.h++++ b/Source/WebCore/inspector/InspectorInstrumentation.h+@@ -228,6 +228,7 @@ public:+ static void frameStoppedLoading(Frame&);+ static void frameScheduledNavigation(Frame&, Seconds delay);+ static void frameClearedScheduledNavigation(Frame&);++ static void didNavigateWithinPage(Frame&);+ static void defaultAppearanceDidChange(Page&, bool useDarkAppearance);+ static void willDestroyCachedResource(CachedResource&);++@@ -428,6 +429,7 @@ private:+ static void frameStoppedLoadingImpl(InstrumentingAgents&, Frame&);+ static void frameScheduledNavigationImpl(InstrumentingAgents&, Frame&, Seconds delay);+ static void frameClearedScheduledNavigationImpl(InstrumentingAgents&, Frame&);++ static void didNavigateWithinPageImpl(InstrumentingAgents&, Frame&);+ static void defaultAppearanceDidChangeImpl(InstrumentingAgents&, bool useDarkAppearance);+ static void willDestroyCachedResourceImpl(CachedResource&);++@@ -1219,6 +1221,13 @@ inline void InspectorInstrumentation::frameClearedScheduledNavigation(Frame& fra+ frameClearedScheduledNavigationImpl(*instrumentingAgents, frame);+ }+++inline void InspectorInstrumentation::didNavigateWithinPage(Frame& frame)++{++ FAST_RETURN_IF_NO_FRONTENDS(void());++ if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForFrame(frame))++ didNavigateWithinPageImpl(*instrumentingAgents, frame);++}+++ inline void InspectorInstrumentation::defaultAppearanceDidChange(Page& page, bool useDarkAppearance)+ {+ FAST_RETURN_IF_NO_FRONTENDS(void());+diff --git a/Source/WebCore/inspector/agents/InspectorDOMAgent.cpp b/Source/WebCore/inspector/agents/InspectorDOMAgent.cpp+index 19bd04b805c..21745502b3e 100644+--- a/Source/WebCore/inspector/agents/InspectorDOMAgent.cpp++++ b/Source/WebCore/inspector/agents/InspectorDOMAgent.cpp+@@ -61,6 +61,7 @@+ #include "FrameTree.h"+ #include "FrameView.h"+ #include "FullscreenManager.h"++#include "FloatQuad.h"+ #include "HTMLElement.h"+ #include "HTMLFrameOwnerElement.h"+ #include "HTMLMediaElement.h"+@@ -89,6 +90,7 @@+ #include "Page.h"+ #include "Pasteboard.h"+ #include "PseudoElement.h"++#include "RenderObject.h"+ #include "RenderStyle.h"+ #include "RenderStyleConstants.h"+ #include "ScriptState.h"+@@ -1417,6 +1419,61 @@ void InspectorDOMAgent::setInspectedNode(ErrorString& errorString, int nodeId)+ m_suppressEventListenerChangedEvent = false;+ }+++static void frameQuadToViewport(const FrameView* containingView, FloatQuad& quad)++{++ quad.setP1(containingView->contentsToRootView(quad.p1()));++ quad.setP2(containingView->contentsToRootView(quad.p2()));++ quad.setP3(containingView->contentsToRootView(quad.p3()));++ quad.setP4(containingView->contentsToRootView(quad.p4()));++}++++static RefPtr<Inspector::Protocol::DOM::Quad> buildObjectForQuad(const FloatQuad& quad)++{++ auto result = Inspector::Protocol::DOM::Quad::create();++ result->addItem(quad.p1().x());++ result->addItem(quad.p1().y());++ result->addItem(quad.p2().x());++ result->addItem(quad.p2().y());++ result->addItem(quad.p3().x());++ result->addItem(quad.p3().y());++ result->addItem(quad.p4().x());++ result->addItem(quad.p4().y());++ return result;++}++++static RefPtr<JSON::ArrayOf<Inspector::Protocol::DOM::Quad>> buildArrayOfQuads(const Vector<FloatQuad>& quads)++{++ auto result = JSON::ArrayOf<Inspector::Protocol::DOM::Quad>::create();++ for (const auto& quad : quads)++ result->addItem(buildObjectForQuad(quad));++ return result;++}++++void InspectorDOMAgent::getContentQuads(ErrorString& error, const String& objectId, RefPtr<JSON::ArrayOf<Inspector::Protocol::DOM::Quad>>& out_quads)++{++ Node* node = nodeForObjectId(objectId);++ if (!node) {++ error = "Node not found";++ return;++ }++ RenderObject* renderer = node->renderer();++ if (!renderer) {++ error = "Node doesn't have renderer";++ return;++ }++ Frame* containingFrame = renderer->document().frame();++ if (!containingFrame) {++ error = "No containing frame";++ return;++ }++ FrameView* containingView = containingFrame->view();++ Vector<FloatQuad> quads;++ renderer->absoluteQuads(quads);++ for (auto& quad : quads)++ frameQuadToViewport(containingView, quad);++ out_quads = buildArrayOfQuads(quads);++}+++ void InspectorDOMAgent::resolveNode(ErrorString& errorString, int nodeId, const String* objectGroup, RefPtr<Inspector::Protocol::Runtime::RemoteObject>& result)+ {+ String objectGroupName = objectGroup ? *objectGroup : emptyString();+diff --git a/Source/WebCore/inspector/agents/InspectorDOMAgent.h b/Source/WebCore/inspector/agents/InspectorDOMAgent.h+index 51639abeb84..fbb7773978d 100644+--- a/Source/WebCore/inspector/agents/InspectorDOMAgent.h++++ b/Source/WebCore/inspector/agents/InspectorDOMAgent.h+@@ -148,6 +148,7 @@ public:+ void focus(ErrorString&, int nodeId) override;+ void setInspectedNode(ErrorString&, int nodeId) override;+ void setAllowEditingUserAgentShadowTrees(ErrorString&, bool allow) final;++ void getContentQuads(ErrorString&, const String& objectId, RefPtr<JSON::ArrayOf<Inspector::Protocol::DOM::Quad>>& out_quads) override;++ // InspectorInstrumentation+ int identifierForNode(Node&);+diff --git a/Source/WebCore/inspector/agents/InspectorPageAgent.cpp b/Source/WebCore/inspector/agents/InspectorPageAgent.cpp+index f2e228b7f74..77ccbe29ea3 100644+--- a/Source/WebCore/inspector/agents/InspectorPageAgent.cpp++++ b/Source/WebCore/inspector/agents/InspectorPageAgent.cpp+@@ -412,14 +412,16 @@ void InspectorPageAgent::reload(ErrorString&, const bool* optionalReloadFromOrig+ m_inspectedPage.mainFrame().loader().reload(reloadOptions);+ }++-void InspectorPageAgent::navigate(ErrorString&, const String& url)++void InspectorPageAgent::navigate(ErrorString& errorString, const String& url, const String* frameId)+ {+ UserGestureIndicator indicator { ProcessingUserGesture };+- Frame& frame = m_inspectedPage.mainFrame();++ Frame* frame = frameId ? assertFrame(errorString, *frameId) : &m_inspectedPage.mainFrame();++ if (!frame)++ return;++- ResourceRequest resourceRequest { frame.document()->completeURL(url) };+- FrameLoadRequest frameLoadRequest { *frame.document(), frame.document()->securityOrigin(), resourceRequest, "_self"_s, LockHistory::No, LockBackForwardList::No, MaybeSendReferrer, AllowNavigationToInvalidURL::No, NewFrameOpenerPolicy::Allow, ShouldOpenExternalURLsPolicy::ShouldNotAllow, InitiatedByMainFrame::Unknown };+- frame.loader().changeLocation(WTFMove(frameLoadRequest));++ ResourceRequest resourceRequest { frame->document()->completeURL(url) };++ FrameLoadRequest frameLoadRequest { *frame->document(), frame->document()->securityOrigin(), resourceRequest, "_self"_s, LockHistory::No, LockBackForwardList::No, MaybeSendReferrer, AllowNavigationToInvalidURL::No, NewFrameOpenerPolicy::Allow, ShouldOpenExternalURLsPolicy::ShouldNotAllow, InitiatedByMainFrame::Unknown };++ frame->loader().changeLocation(WTFMove(frameLoadRequest));+ }++ void InspectorPageAgent::overrideUserAgent(ErrorString&, const String* value)+@@ -761,6 +763,12 @@ void InspectorPageAgent::frameClearedScheduledNavigation(Frame& frame)+ m_frontendDispatcher->frameClearedScheduledNavigation(frameId(&frame));+ }+++void InspectorPageAgent::didNavigateWithinPage(Frame& frame)++{++ String url = frame.document()->url().string();++ m_frontendDispatcher->navigatedWithinDocument(frameId(&frame), url);++}+++ void InspectorPageAgent::defaultAppearanceDidChange(bool useDarkAppearance)+ {+ m_frontendDispatcher->defaultAppearanceDidChange(useDarkAppearance ? Inspector::Protocol::Page::Appearance::Dark : Inspector::Protocol::Page::Appearance::Light);+diff --git a/Source/WebCore/inspector/agents/InspectorPageAgent.h b/Source/WebCore/inspector/agents/InspectorPageAgent.h+index 4fd8c0b1016..78af692dc09 100644+--- a/Source/WebCore/inspector/agents/InspectorPageAgent.h++++ b/Source/WebCore/inspector/agents/InspectorPageAgent.h+@@ -96,7 +96,7 @@ public:+ void enable(ErrorString&) override;+ void disable(ErrorString&) override;+ void reload(ErrorString&, const bool* optionalReloadFromOrigin, const bool* optionalRevalidateAllResources) override;+- void navigate(ErrorString&, const String& url) override;++ void navigate(ErrorString&, const String& url, const String* frameId) override;+ void overrideUserAgent(ErrorString&, const String* value) override;+ void overrideSetting(ErrorString&, const String& setting, const bool* value) override;+ void getCookies(ErrorString&, RefPtr<JSON::ArrayOf<Inspector::Protocol::Page::Cookie>>& cookies) override;+@@ -126,6 +126,7 @@ public:+ void frameStoppedLoading(Frame&);+ void frameScheduledNavigation(Frame&, Seconds delay);+ void frameClearedScheduledNavigation(Frame&);++ void didNavigateWithinPage(Frame&);+ void defaultAppearanceDidChange(bool useDarkAppearance);+ void applyUserAgentOverride(String&);+ void applyEmulatedMedia(String&);+diff --git a/Source/WebCore/loader/FrameLoader.cpp b/Source/WebCore/loader/FrameLoader.cpp+index 26246f7deb6..cf215bed32b 100644+--- a/Source/WebCore/loader/FrameLoader.cpp++++ b/Source/WebCore/loader/FrameLoader.cpp+@@ -1179,6 +1179,7 @@ void FrameLoader::loadInSameDocument(const URL& url, SerializedScriptValue* stat+ }++ m_client.dispatchDidNavigateWithinPage();++ InspectorInstrumentation::didNavigateWithinPage(m_frame);++ m_frame.document()->statePopped(stateObject ? Ref<SerializedScriptValue> { *stateObject } : SerializedScriptValue::nullValue());+ m_client.dispatchDidPopStateWithinPage();+diff --git a/Source/WebCore/page/History.cpp b/Source/WebCore/page/History.cpp+index 9c58b06f4c4..3d624733c36 100644+--- a/Source/WebCore/page/History.cpp++++ b/Source/WebCore/page/History.cpp+@@ -259,6 +259,7 @@ ExceptionOr<void> History::stateObjectAdded(RefPtr<SerializedScriptValue>&& data++ if (!urlString.isEmpty())+ frame->document()->updateURLForPushOrReplaceState(fullURL);++ InspectorInstrumentation::didNavigateWithinPage(*frame);++ if (stateObjectType == StateObjectType::Push) {+ frame->loader().history().pushState(WTFMove(data), title, fullURL.string());+diff --git a/Source/WebCore/platform/PlatformKeyboardEvent.h b/Source/WebCore/platform/PlatformKeyboardEvent.h+index 4aaf5bde32b..e9c047d4f26 100644+--- a/Source/WebCore/platform/PlatformKeyboardEvent.h++++ b/Source/WebCore/platform/PlatformKeyboardEvent.h+@@ -147,6 +147,7 @@ namespace WebCore {+ static String keyCodeForHardwareKeyCode(unsigned);+ static String keyIdentifierForGdkKeyCode(unsigned);+ static int windowsKeyCodeForGdkKeyCode(unsigned);++ static unsigned gdkKeyCodeForWindowsKeyCode(int);+ static String singleCharacterString(unsigned);+ static bool modifiersContainCapsLock(unsigned);+ #endif+@@ -156,6 +157,7 @@ namespace WebCore {+ static String keyCodeForHardwareKeyCode(unsigned);+ static String keyIdentifierForWPEKeyCode(unsigned);+ static int windowsKeyCodeForWPEKeyCode(unsigned);++ static unsigned WPEKeyCodeForWindowsKeyCode(int);+ static String singleCharacterString(unsigned);+ #endif++diff --git a/Source/WebCore/platform/gtk/PlatformKeyboardEventGtk.cpp b/Source/WebCore/platform/gtk/PlatformKeyboardEventGtk.cpp+index 356b09f2fba..8f0c19b6031 100644+--- a/Source/WebCore/platform/gtk/PlatformKeyboardEventGtk.cpp++++ b/Source/WebCore/platform/gtk/PlatformKeyboardEventGtk.cpp+@@ -36,8 +36,10 @@+ #include "WindowsKeyboardCodes.h"+ #include <gdk/gdk.h>+ #include <gdk/gdkkeysyms.h>++#include <wtf/HashMap.h>+ #include <wtf/HexNumber.h>+ #include <wtf/glib/GUniquePtr.h>++#include <mutex>++ namespace WebCore {++@@ -1293,6 +1295,246 @@ int PlatformKeyboardEvent::windowsKeyCodeForGdkKeyCode(unsigned keycode)++ }+++static const HashMap<int, unsigned>& gdkToWindowsKeyCodeMap()++{++ static HashMap<int, unsigned>* result;++ static std::once_flag once;++ std::call_once(++ once,++ [] {++ const unsigned gdkKeyCodes[] = {++ GDK_KEY_Cancel,++ // FIXME: non-keypad keys should take precedence, so we skip GDK_KEY_KP_*++ // GDK_KEY_KP_0,++ // GDK_KEY_KP_1,++ // GDK_KEY_KP_2,++ // GDK_KEY_KP_3,++ // GDK_KEY_KP_4,++ // GDK_KEY_KP_5,++ // GDK_KEY_KP_6,++ // GDK_KEY_KP_7,++ // GDK_KEY_KP_8,++ // GDK_KEY_KP_9,++ // GDK_KEY_KP_Multiply,++ // GDK_KEY_KP_Add,++ // GDK_KEY_KP_Subtract,++ // GDK_KEY_KP_Decimal,++ // GDK_KEY_KP_Divide,++ // GDK_KEY_KP_Page_Up,++ // GDK_KEY_KP_Page_Down,++ // GDK_KEY_KP_End,++ // GDK_KEY_KP_Home,++ // GDK_KEY_KP_Left,++ // GDK_KEY_KP_Up,++ // GDK_KEY_KP_Right,++ // GDK_KEY_KP_Down,++ GDK_KEY_BackSpace,++ // GDK_KEY_ISO_Left_Tab,++ // GDK_KEY_3270_BackTab,++ GDK_KEY_Tab,++ GDK_KEY_Clear,++ // GDK_KEY_ISO_Enter,++ // GDK_KEY_KP_Enter,++ GDK_KEY_Return,++ GDK_KEY_Menu,++ GDK_KEY_Pause,++ GDK_KEY_AudioPause,++ GDK_KEY_Caps_Lock,++ GDK_KEY_Kana_Lock,++ GDK_KEY_Kana_Shift,++ GDK_KEY_Hangul,++ GDK_KEY_Hangul_Hanja,++ GDK_KEY_Kanji,++ GDK_KEY_Escape,++ GDK_KEY_space,++ GDK_KEY_Page_Up,++ GDK_KEY_Page_Down,++ GDK_KEY_End,++ GDK_KEY_Home,++ GDK_KEY_Left,++ GDK_KEY_Up,++ GDK_KEY_Right,++ GDK_KEY_Down,++ GDK_KEY_Select,++ GDK_KEY_Print,++ GDK_KEY_Execute,++ GDK_KEY_Insert,++ GDK_KEY_KP_Insert,++ GDK_KEY_Delete,++ GDK_KEY_KP_Delete,++ GDK_KEY_Help,++ GDK_KEY_0,++ GDK_KEY_parenright,++ GDK_KEY_1,++ GDK_KEY_exclam,++ GDK_KEY_2,++ GDK_KEY_at,++ GDK_KEY_3,++ GDK_KEY_numbersign,++ GDK_KEY_4,++ GDK_KEY_dollar,++ GDK_KEY_5,++ GDK_KEY_percent,++ GDK_KEY_6,++ GDK_KEY_asciicircum,++ GDK_KEY_7,++ GDK_KEY_ampersand,++ GDK_KEY_8,++ GDK_KEY_asterisk,++ GDK_KEY_9,++ GDK_KEY_parenleft,++ GDK_KEY_a,++ GDK_KEY_A,++ GDK_KEY_b,++ GDK_KEY_B,++ GDK_KEY_c,++ GDK_KEY_C,++ GDK_KEY_d,++ GDK_KEY_D,++ GDK_KEY_e,++ GDK_KEY_E,++ GDK_KEY_f,++ GDK_KEY_F,++ GDK_KEY_g,++ GDK_KEY_G,++ GDK_KEY_h,++ GDK_KEY_H,++ GDK_KEY_i,++ GDK_KEY_I,++ GDK_KEY_j,++ GDK_KEY_J,++ GDK_KEY_k,++ GDK_KEY_K,++ GDK_KEY_l,++ GDK_KEY_L,++ GDK_KEY_m,++ GDK_KEY_M,++ GDK_KEY_n,++ GDK_KEY_N,++ GDK_KEY_o,++ GDK_KEY_O,++ GDK_KEY_p,++ GDK_KEY_P,++ GDK_KEY_q,++ GDK_KEY_Q,++ GDK_KEY_r,++ GDK_KEY_R,++ GDK_KEY_s,++ GDK_KEY_S,++ GDK_KEY_t,++ GDK_KEY_T,++ GDK_KEY_u,++ GDK_KEY_U,++ GDK_KEY_v,++ GDK_KEY_V,++ GDK_KEY_w,++ GDK_KEY_W,++ GDK_KEY_x,++ GDK_KEY_X,++ GDK_KEY_y,++ GDK_KEY_Y,++ GDK_KEY_z,++ GDK_KEY_Z,++ GDK_KEY_Meta_L,++ GDK_KEY_Meta_R,++ GDK_KEY_Sleep,++ GDK_KEY_Num_Lock,++ GDK_KEY_Scroll_Lock,++ GDK_KEY_Shift_L,++ GDK_KEY_Shift_R,++ GDK_KEY_Control_L,++ GDK_KEY_Control_R,++ GDK_KEY_Alt_L,++ GDK_KEY_Alt_R,++ GDK_KEY_Back,++ GDK_KEY_Forward,++ GDK_KEY_Refresh,++ GDK_KEY_Stop,++ GDK_KEY_Search,++ GDK_KEY_Favorites,++ GDK_KEY_HomePage,++ GDK_KEY_AudioMute,++ GDK_KEY_AudioLowerVolume,++ GDK_KEY_AudioRaiseVolume,++ GDK_KEY_AudioNext,++ GDK_KEY_AudioPrev,++ GDK_KEY_AudioStop,++ GDK_KEY_AudioMedia,++ GDK_KEY_semicolon,++ GDK_KEY_colon,++ GDK_KEY_plus,++ GDK_KEY_equal,++ GDK_KEY_comma,++ GDK_KEY_less,++ GDK_KEY_minus,++ GDK_KEY_underscore,++ GDK_KEY_period,++ GDK_KEY_greater,++ GDK_KEY_slash,++ GDK_KEY_question,++ GDK_KEY_asciitilde,++ GDK_KEY_quoteleft,++ GDK_KEY_bracketleft,++ GDK_KEY_braceleft,++ GDK_KEY_backslash,++ GDK_KEY_bar,++ GDK_KEY_bracketright,++ GDK_KEY_braceright,++ GDK_KEY_quoteright,++ GDK_KEY_quotedbl,++ GDK_KEY_AudioRewind,++ GDK_KEY_AudioForward,++ GDK_KEY_AudioPlay,++ GDK_KEY_F1,++ GDK_KEY_F2,++ GDK_KEY_F3,++ GDK_KEY_F4,++ GDK_KEY_F5,++ GDK_KEY_F6,++ GDK_KEY_F7,++ GDK_KEY_F8,++ GDK_KEY_F9,++ GDK_KEY_F10,++ GDK_KEY_F11,++ GDK_KEY_F12,++ GDK_KEY_F13,++ GDK_KEY_F14,++ GDK_KEY_F15,++ GDK_KEY_F16,++ GDK_KEY_F17,++ GDK_KEY_F18,++ GDK_KEY_F19,++ GDK_KEY_F20,++ GDK_KEY_F21,++ GDK_KEY_F22,++ GDK_KEY_F23,++ GDK_KEY_F24,++ GDK_KEY_VoidSymbol,++ GDK_KEY_Red,++ GDK_KEY_Green,++ GDK_KEY_Yellow,++ GDK_KEY_Blue,++ GDK_KEY_PowerOff,++ GDK_KEY_AudioRecord,++ GDK_KEY_Display,++ GDK_KEY_Subtitle,++ GDK_KEY_Video++ };++ result = new HashMap<int, unsigned>();++ for (unsigned gdkKeyCode : gdkKeyCodes) {++ int winKeyCode = PlatformKeyboardEvent::windowsKeyCodeForGdkKeyCode(gdkKeyCode);++ // If several gdk key codes map to the same win key code first one is used.++ result->add(winKeyCode, gdkKeyCode);++ }++ });++ return *result;++}++++unsigned PlatformKeyboardEvent::gdkKeyCodeForWindowsKeyCode(int keycode)++{++ return gdkToWindowsKeyCodeMap().get(keycode);++}+++ String PlatformKeyboardEvent::singleCharacterString(unsigned val)+ {+ switch (val) {+diff --git a/Source/WebCore/platform/libwpe/PlatformKeyboardEventLibWPE.cpp b/Source/WebCore/platform/libwpe/PlatformKeyboardEventLibWPE.cpp+index cf46da15083..efbda20f28b 100644+--- a/Source/WebCore/platform/libwpe/PlatformKeyboardEventLibWPE.cpp++++ b/Source/WebCore/platform/libwpe/PlatformKeyboardEventLibWPE.cpp+@@ -1291,6 +1291,246 @@ int PlatformKeyboardEvent::windowsKeyCodeForWPEKeyCode(unsigned keycode)+ return 0;+ }+++static const HashMap<int, unsigned>& WPEToWindowsKeyCodeMap()++{++ static HashMap<int, unsigned>* result;++ static std::once_flag once;++ std::call_once(++ once,++ [] {++ const unsigned WPEKeyCodes[] = {++ WPE_KEY_Cancel,++ // FIXME: non-keypad keys should take precedence, so we skip WPE_KEY_KP_*++ // WPE_KEY_KP_0,++ // WPE_KEY_KP_1,++ // WPE_KEY_KP_2,++ // WPE_KEY_KP_3,++ // WPE_KEY_KP_4,++ // WPE_KEY_KP_5,++ // WPE_KEY_KP_6,++ // WPE_KEY_KP_7,++ // WPE_KEY_KP_8,++ // WPE_KEY_KP_9,++ // WPE_KEY_KP_Multiply,++ // WPE_KEY_KP_Add,++ // WPE_KEY_KP_Subtract,++ // WPE_KEY_KP_Decimal,++ // WPE_KEY_KP_Divide,++ // WPE_KEY_KP_Page_Up,++ // WPE_KEY_KP_Page_Down,++ // WPE_KEY_KP_End,++ // WPE_KEY_KP_Home,++ // WPE_KEY_KP_Left,++ // WPE_KEY_KP_Up,++ // WPE_KEY_KP_Right,++ // WPE_KEY_KP_Down,++ WPE_KEY_BackSpace,++ // WPE_KEY_ISO_Left_Tab,++ // WPE_KEY_3270_BackTab,++ WPE_KEY_Tab,++ WPE_KEY_Clear,++ // WPE_KEY_ISO_Enter,++ // WPE_KEY_KP_Enter,++ WPE_KEY_Return,++ WPE_KEY_Menu,++ WPE_KEY_Pause,++ WPE_KEY_AudioPause,++ WPE_KEY_Caps_Lock,++ WPE_KEY_Kana_Lock,++ WPE_KEY_Kana_Shift,++ WPE_KEY_Hangul,++ WPE_KEY_Hangul_Hanja,++ WPE_KEY_Kanji,++ WPE_KEY_Escape,++ WPE_KEY_space,++ WPE_KEY_Page_Up,++ WPE_KEY_Page_Down,++ WPE_KEY_End,++ WPE_KEY_Home,++ WPE_KEY_Left,++ WPE_KEY_Up,++ WPE_KEY_Right,++ WPE_KEY_Down,++ WPE_KEY_Select,++ WPE_KEY_Print,++ WPE_KEY_Execute,++ WPE_KEY_Insert,++ WPE_KEY_KP_Insert,++ WPE_KEY_Delete,++ WPE_KEY_KP_Delete,++ WPE_KEY_Help,++ WPE_KEY_0,++ WPE_KEY_parenright,++ WPE_KEY_1,++ WPE_KEY_exclam,++ WPE_KEY_2,++ WPE_KEY_at,++ WPE_KEY_3,++ WPE_KEY_numbersign,++ WPE_KEY_4,++ WPE_KEY_dollar,++ WPE_KEY_5,++ WPE_KEY_percent,++ WPE_KEY_6,++ WPE_KEY_asciicircum,++ WPE_KEY_7,++ WPE_KEY_ampersand,++ WPE_KEY_8,++ WPE_KEY_asterisk,++ WPE_KEY_9,++ WPE_KEY_parenleft,++ WPE_KEY_a,++ WPE_KEY_A,++ WPE_KEY_b,++ WPE_KEY_B,++ WPE_KEY_c,++ WPE_KEY_C,++ WPE_KEY_d,++ WPE_KEY_D,++ WPE_KEY_e,++ WPE_KEY_E,++ WPE_KEY_f,++ WPE_KEY_F,++ WPE_KEY_g,++ WPE_KEY_G,++ WPE_KEY_h,++ WPE_KEY_H,++ WPE_KEY_i,++ WPE_KEY_I,++ WPE_KEY_j,++ WPE_KEY_J,++ WPE_KEY_k,++ WPE_KEY_K,++ WPE_KEY_l,++ WPE_KEY_L,++ WPE_KEY_m,++ WPE_KEY_M,++ WPE_KEY_n,++ WPE_KEY_N,++ WPE_KEY_o,++ WPE_KEY_O,++ WPE_KEY_p,++ WPE_KEY_P,++ WPE_KEY_q,++ WPE_KEY_Q,++ WPE_KEY_r,++ WPE_KEY_R,++ WPE_KEY_s,++ WPE_KEY_S,++ WPE_KEY_t,++ WPE_KEY_T,++ WPE_KEY_u,++ WPE_KEY_U,++ WPE_KEY_v,++ WPE_KEY_V,++ WPE_KEY_w,++ WPE_KEY_W,++ WPE_KEY_x,++ WPE_KEY_X,++ WPE_KEY_y,++ WPE_KEY_Y,++ WPE_KEY_z,++ WPE_KEY_Z,++ WPE_KEY_Meta_L,++ WPE_KEY_Meta_R,++ WPE_KEY_Sleep,++ WPE_KEY_Num_Lock,++ WPE_KEY_Scroll_Lock,++ WPE_KEY_Shift_L,++ WPE_KEY_Shift_R,++ WPE_KEY_Control_L,++ WPE_KEY_Control_R,++ WPE_KEY_Alt_L,++ WPE_KEY_Alt_R,++ WPE_KEY_Back,++ WPE_KEY_Forward,++ WPE_KEY_Refresh,++ WPE_KEY_Stop,++ WPE_KEY_Search,++ WPE_KEY_Favorites,++ WPE_KEY_HomePage,++ WPE_KEY_AudioMute,++ WPE_KEY_AudioLowerVolume,++ WPE_KEY_AudioRaiseVolume,++ WPE_KEY_AudioNext,++ WPE_KEY_AudioPrev,++ WPE_KEY_AudioStop,++ WPE_KEY_AudioMedia,++ WPE_KEY_semicolon,++ WPE_KEY_colon,++ WPE_KEY_plus,++ WPE_KEY_equal,++ WPE_KEY_comma,++ WPE_KEY_less,++ WPE_KEY_minus,++ WPE_KEY_underscore,++ WPE_KEY_period,++ WPE_KEY_greater,++ WPE_KEY_slash,++ WPE_KEY_question,++ WPE_KEY_asciitilde,++ WPE_KEY_quoteleft,++ WPE_KEY_bracketleft,++ WPE_KEY_braceleft,++ WPE_KEY_backslash,++ WPE_KEY_bar,++ WPE_KEY_bracketright,++ WPE_KEY_braceright,++ WPE_KEY_quoteright,++ WPE_KEY_quotedbl,++ WPE_KEY_AudioRewind,++ WPE_KEY_AudioForward,++ WPE_KEY_AudioPlay,++ WPE_KEY_F1,++ WPE_KEY_F2,++ WPE_KEY_F3,++ WPE_KEY_F4,++ WPE_KEY_F5,++ WPE_KEY_F6,++ WPE_KEY_F7,++ WPE_KEY_F8,++ WPE_KEY_F9,++ WPE_KEY_F10,++ WPE_KEY_F11,++ WPE_KEY_F12,++ WPE_KEY_F13,++ WPE_KEY_F14,++ WPE_KEY_F15,++ WPE_KEY_F16,++ WPE_KEY_F17,++ WPE_KEY_F18,++ WPE_KEY_F19,++ WPE_KEY_F20,++ WPE_KEY_F21,++ WPE_KEY_F22,++ WPE_KEY_F23,++ WPE_KEY_F24,++ WPE_KEY_VoidSymbol,++ WPE_KEY_Red,++ WPE_KEY_Green,++ WPE_KEY_Yellow,++ WPE_KEY_Blue,++ WPE_KEY_PowerOff,++ WPE_KEY_AudioRecord,++ WPE_KEY_Display,++ WPE_KEY_Subtitle,++ WPE_KEY_Video++ };++ result = new HashMap<int, unsigned>();++ for (unsigned WPEKeyCode : WPEKeyCodes) {++ int winKeyCode = PlatformKeyboardEvent::windowsKeyCodeForWPEKeyCode(WPEKeyCode);++ // If several gdk key codes map to the same win key code first one is used.++ result->add(winKeyCode, WPEKeyCode);++ }++ });++ return *result;++}++++unsigned PlatformKeyboardEvent::WPEKeyCodeForWindowsKeyCode(int keycode)++{++ return WPEToWindowsKeyCodeMap().get(keycode);++}+++ String PlatformKeyboardEvent::singleCharacterString(unsigned val)+ {+ switch (val) {+diff --git a/Source/WebKit/Shared/API/c/wpe/WebKit.h b/Source/WebKit/Shared/API/c/wpe/WebKit.h+index 898e30b370d..74945e06fac 100644+--- a/Source/WebKit/Shared/API/c/wpe/WebKit.h++++ b/Source/WebKit/Shared/API/c/wpe/WebKit.h+@@ -78,6 +78,7 @@+ // From Source/WebKit/UIProcess/API/C+ #include <WebKit/WKBackForwardListItemRef.h>+ #include <WebKit/WKBackForwardListRef.h>++#include <WebKit/WKBrowserInspector.h>+ #include <WebKit/WKContext.h>+ #include <WebKit/WKContextConfigurationRef.h>+ #include <WebKit/WKCredential.h>+diff --git a/Source/WebKit/Shared/NativeWebKeyboardEvent.h b/Source/WebKit/Shared/NativeWebKeyboardEvent.h+index 6f4e29b7c65..9dd287efc40 100644+--- a/Source/WebKit/Shared/NativeWebKeyboardEvent.h++++ b/Source/WebKit/Shared/NativeWebKeyboardEvent.h+@@ -34,6 +34,7 @@+ #if USE(APPKIT)+ #include <wtf/RetainPtr.h>+ OBJC_CLASS NSView;++OBJC_CLASS NSEvent;++ namespace WebCore {+ struct KeypressCommand;+@@ -70,6 +71,10 @@ public:+ enum class HandledByInputMethod : bool { No, Yes };+ enum class FakedForComposition : bool { No, Yes };+ NativeWebKeyboardEvent(GdkEvent*, const String&, HandledByInputMethod, FakedForComposition, Vector<String>&& commands);++ NativeWebKeyboardEvent(Type type, const String& text, const String& unmodifiedText, const String& key, const String& code, const String& keyIdentifier, int windowsVirtualKeyCode, int nativeVirtualKeyCode, bool isAutoRepeat, bool isKeypad, bool isSystemKey, OptionSet<Modifier> modifiers, WallTime timestamp, Vector<String>&& commands)++ : WebKeyboardEvent(type, text, unmodifiedText, key, code, keyIdentifier, windowsVirtualKeyCode, nativeVirtualKeyCode, isAutoRepeat, isKeypad, isSystemKey, modifiers, timestamp, WTFMove(commands))++ {++ }+ #elif PLATFORM(IOS_FAMILY)+ enum class HandledByInputMethod : bool { No, Yes };+ NativeWebKeyboardEvent(::WebEvent *, HandledByInputMethod);+diff --git a/Source/WebKit/Shared/NativeWebMouseEvent.h b/Source/WebKit/Shared/NativeWebMouseEvent.h+index ba7f93c924f..d19eb2f2932 100644+--- a/Source/WebKit/Shared/NativeWebMouseEvent.h++++ b/Source/WebKit/Shared/NativeWebMouseEvent.h+@@ -61,6 +61,10 @@ public:+ #elif PLATFORM(GTK)+ NativeWebMouseEvent(const NativeWebMouseEvent&);+ NativeWebMouseEvent(GdkEvent*, int);++ NativeWebMouseEvent(Type type, Button button, unsigned short buttons, const WebCore::IntPoint& position, const WebCore::IntPoint& globalPosition, float deltaX, float deltaY, float deltaZ, int clickCount, OptionSet<Modifier> modifiers, WallTime timestamp)++ : WebMouseEvent(type, button, buttons, position, globalPosition, deltaX, deltaY, deltaZ, clickCount, modifiers, timestamp)++ {++ }+ #elif PLATFORM(IOS_FAMILY)+ NativeWebMouseEvent(::WebEvent *);+ NativeWebMouseEvent(Type, Button, unsigned short buttons, const WebCore::IntPoint& position, const WebCore::IntPoint& globalPosition, float deltaX, float deltaY, float deltaZ, int clickCount, OptionSet<Modifier>, WallTime timestamp, double force);+diff --git a/Source/WebKit/Shared/WebEvent.h b/Source/WebKit/Shared/WebEvent.h+index c36100cf5c4..216402f0a24 100644+--- a/Source/WebKit/Shared/WebEvent.h++++ b/Source/WebKit/Shared/WebEvent.h+@@ -35,6 +35,7 @@+ #include <WebCore/IntSize.h>+ #include <WebCore/KeypressCommand.h>+ #include <wtf/OptionSet.h>++#include <wtf/RefCounted.h>+ #include <wtf/WallTime.h>+ #include <wtf/text/WTFString.h>++@@ -138,7 +139,7 @@ public:+ WebMouseEvent();++ #if PLATFORM(MAC)+- WebMouseEvent(Type, Button, unsigned short buttons, const WebCore::IntPoint& position, const WebCore::IntPoint& globalPosition, float deltaX, float deltaY, float deltaZ, int clickCount, OptionSet<Modifier>, WallTime timestamp, double force, SyntheticClickType = NoTap, int eventNumber = -1, int menuType = 0);++ WebMouseEvent(Type, Button, unsigned short buttons, const WebCore::IntPoint& position, const WebCore::IntPoint& globalPosition, float deltaX, float deltaY, float deltaZ, int clickCount, OptionSet<Modifier>, WallTime timestamp, double force = 0, SyntheticClickType = NoTap, int eventNumber = -1, int menuType = 0);+ #else+ WebMouseEvent(Type, Button, unsigned short buttons, const WebCore::IntPoint& position, const WebCore::IntPoint& globalPosition, float deltaX, float deltaY, float deltaZ, int clickCount, OptionSet<Modifier>, WallTime timestamp, double force = 0, SyntheticClickType = NoTap);+ #endif+@@ -258,6 +259,7 @@ public:+ WebKeyboardEvent(Type, const String& text, const String& unmodifiedText, const String& key, const String& code, const String& keyIdentifier, int windowsVirtualKeyCode, int nativeVirtualKeyCode, int macCharCode, bool handledByInputMethod, const Vector<WebCore::KeypressCommand>&, bool isAutoRepeat, bool isKeypad, bool isSystemKey, OptionSet<Modifier>, WallTime timestamp);+ #elif PLATFORM(GTK)+ WebKeyboardEvent(Type, const String& text, const String& key, const String& code, const String& keyIdentifier, int windowsVirtualKeyCode, int nativeVirtualKeyCode, bool handledByInputMethod, Vector<String>&& commands, bool isKeypad, OptionSet<Modifier>, WallTime timestamp);++ WebKeyboardEvent(Type, const String& text, const String& unmodifiedText, const String& key, const String& code, const String& keyIdentifier, int windowsVirtualKeyCode, int nativeVirtualKeyCode, bool isAutoRepeat, bool isKeypad, bool isSystemKey, OptionSet<Modifier>, WallTime timestamp, Vector<String>&& commands);+ #elif PLATFORM(IOS_FAMILY)+ WebKeyboardEvent(Type, const String& text, const String& unmodifiedText, const String& key, const String& code, const String& keyIdentifier, int windowsVirtualKeyCode, int nativeVirtualKeyCode, int macCharCode, bool handledByInputMethod, bool isAutoRepeat, bool isKeypad, bool isSystemKey, OptionSet<Modifier>, WallTime timestamp);+ #elif USE(LIBWPE)+@@ -309,7 +311,7 @@ private:+ int32_t m_nativeVirtualKeyCode;+ int32_t m_macCharCode;+ #if USE(APPKIT) || USE(UIKIT_KEYBOARD_ADDITIONS) || PLATFORM(GTK)+- bool m_handledByInputMethod;++ bool m_handledByInputMethod = false;+ #endif+ #if USE(APPKIT)+ Vector<WebCore::KeypressCommand> m_commands;+diff --git a/Source/WebKit/Shared/WebKeyboardEvent.cpp b/Source/WebKit/Shared/WebKeyboardEvent.cpp+index a5a23cf148e..390eaf847b6 100644+--- a/Source/WebKit/Shared/WebKeyboardEvent.cpp++++ b/Source/WebKit/Shared/WebKeyboardEvent.cpp+@@ -81,6 +81,28 @@ WebKeyboardEvent::WebKeyboardEvent(Type type, const String& text, const String&+ ASSERT(isKeyboardEventType(type));+ }+++WebKeyboardEvent::WebKeyboardEvent(Type type, const String& text, const String& unmodifiedText, const String& key, const String& code, const String& keyIdentifier, int windowsVirtualKeyCode, int nativeVirtualKeyCode, bool isAutoRepeat, bool isKeypad, bool isSystemKey, OptionSet<Modifier> modifiers, WallTime timestamp, Vector<String>&& commands)++ : WebEvent(type, modifiers, timestamp)++ , m_text(text)++ , m_unmodifiedText(text)++#if ENABLE(KEYBOARD_KEY_ATTRIBUTE)++ , m_key(key)++#endif++#if ENABLE(KEYBOARD_CODE_ATTRIBUTE)++ , m_code(code)++#endif++ , m_keyIdentifier(keyIdentifier)++ , m_windowsVirtualKeyCode(windowsVirtualKeyCode)++ , m_nativeVirtualKeyCode(nativeVirtualKeyCode)++ , m_macCharCode(0)++ , m_commands(WTFMove(commands))++ , m_isAutoRepeat(isAutoRepeat)++ , m_isKeypad(isKeypad)++ , m_isSystemKey(isSystemKey)++{++ ASSERT(isKeyboardEventType(type));++}+++ #elif PLATFORM(IOS_FAMILY)++ WebKeyboardEvent::WebKeyboardEvent(Type type, const String& text, const String& unmodifiedText, const String& key, const String& code, const String& keyIdentifier, int windowsVirtualKeyCode, int nativeVirtualKeyCode, int macCharCode, bool handledByInputMethod, bool isAutoRepeat, bool isKeypad, bool isSystemKey, OptionSet<Modifier> modifiers, WallTime timestamp)+diff --git a/Source/WebKit/Shared/gtk/NativeWebKeyboardEventGtk.cpp b/Source/WebKit/Shared/gtk/NativeWebKeyboardEventGtk.cpp+index 45aa449644b..3a6b4169194 100644+--- a/Source/WebKit/Shared/gtk/NativeWebKeyboardEventGtk.cpp++++ b/Source/WebKit/Shared/gtk/NativeWebKeyboardEventGtk.cpp+@@ -43,7 +43,7 @@ NativeWebKeyboardEvent::NativeWebKeyboardEvent(GdkEvent* event, const String& te+ }++ NativeWebKeyboardEvent::NativeWebKeyboardEvent(const NativeWebKeyboardEvent& event)+- : WebKeyboardEvent(WebEventFactory::createWebKeyboardEvent(event.nativeEvent(), event.text(), event.handledByInputMethod(), Vector<String>(event.commands())))++ : WebKeyboardEvent(event)+ , m_nativeEvent(gdk_event_copy(event.nativeEvent()))+ , m_text(event.text())+ , m_handledByInputMethod(event.handledByInputMethod() ? HandledByInputMethod::Yes : HandledByInputMethod::No)+diff --git a/Source/WebKit/Shared/gtk/NativeWebMouseEventGtk.cpp b/Source/WebKit/Shared/gtk/NativeWebMouseEventGtk.cpp+index 28d00f0e6fd..23a013e754e 100644+--- a/Source/WebKit/Shared/gtk/NativeWebMouseEventGtk.cpp++++ b/Source/WebKit/Shared/gtk/NativeWebMouseEventGtk.cpp+@@ -38,8 +38,8 @@ NativeWebMouseEvent::NativeWebMouseEvent(GdkEvent* event, int eventClickCount)+ }++ NativeWebMouseEvent::NativeWebMouseEvent(const NativeWebMouseEvent& event)+- : WebMouseEvent(WebEventFactory::createWebMouseEvent(event.nativeEvent(), event.clickCount()))+- , m_nativeEvent(gdk_event_copy(event.nativeEvent()))++ : WebMouseEvent(event)++ , m_nativeEvent(event.nativeEvent() ? gdk_event_copy(event.nativeEvent()) : nullptr)+ {+ }++diff --git a/Source/WebKit/Sources.txt b/Source/WebKit/Sources.txt+index edbfb56e49b..623f393da74 100644+--- a/Source/WebKit/Sources.txt++++ b/Source/WebKit/Sources.txt+@@ -240,17 +240,22 @@ Shared/WebsiteData/WebsiteData.cpp++ UIProcess/AuxiliaryProcessProxy.cpp+ UIProcess/BackgroundProcessResponsivenessTimer.cpp++UIProcess/BrowserInspectorController.cpp++UIProcess/BrowserInspectorPipe.cpp++UIProcess/BrowserInspectorTargetAgent.cpp+ UIProcess/DeviceIdHashSaltStorage.cpp+ UIProcess/DrawingAreaProxy.cpp+ UIProcess/FrameLoadState.cpp+ UIProcess/GeolocationPermissionRequestManagerProxy.cpp+ UIProcess/GeolocationPermissionRequestProxy.cpp++UIProcess/InspectorBrowserAgent.cpp+ UIProcess/InspectorTargetProxy.cpp+ UIProcess/LegacyGlobalSettings.cpp+ UIProcess/PageLoadState.cpp+ UIProcess/ProcessAssertion.cpp+ UIProcess/ProcessThrottler.cpp+ UIProcess/ProvisionalPageProxy.cpp++UIProcess/RemoteInspectorPipe.cpp+ UIProcess/RemoteWebInspectorProxy.cpp+ UIProcess/ResponsivenessTimer.cpp+ UIProcess/StatisticsRequest.cpp+@@ -292,6 +297,9 @@ UIProcess/WebPageDiagnosticLoggingClient.cpp+ UIProcess/WebPageGroup.cpp+ UIProcess/WebPageInjectedBundleClient.cpp+ UIProcess/WebPageInspectorController.cpp++UIProcess/WebPageInspectorEmulationAgent.cpp++UIProcess/WebPageInspectorInputAgent.cpp++UIProcess/WebPageInspectorTargetProxy.cpp+ UIProcess/WebPageProxy.cpp+ UIProcess/WebPasteboardProxy.cpp+ UIProcess/WebPreferences.cpp+diff --git a/Source/WebKit/SourcesCocoa.txt b/Source/WebKit/SourcesCocoa.txt+index a22aaba0310..386dd8586c4 100644+--- a/Source/WebKit/SourcesCocoa.txt++++ b/Source/WebKit/SourcesCocoa.txt+@@ -243,6 +243,7 @@ UIProcess/API/Cocoa/_WKApplicationManifest.mm+ UIProcess/API/Cocoa/_WKAttachment.mm+ UIProcess/API/Cocoa/_WKAutomationSession.mm+ UIProcess/API/Cocoa/_WKAutomationSessionConfiguration.mm++UIProcess/API/Cocoa/_WKBrowserInspector.mm+ UIProcess/API/Cocoa/_WKContentRuleListAction.mm+ UIProcess/API/Cocoa/_WKContextMenuElementInfo.mm+ UIProcess/API/Cocoa/_WKCustomHeaderFields.mm @no-unify+diff --git a/Source/WebKit/SourcesGTK.txt b/Source/WebKit/SourcesGTK.txt+index c9e153d6a2c..70788976bee 100644+--- a/Source/WebKit/SourcesGTK.txt++++ b/Source/WebKit/SourcesGTK.txt+@@ -129,6 +129,7 @@ UIProcess/API/glib/WebKitAuthenticationRequest.cpp @no-unify+ UIProcess/API/glib/WebKitAutomationSession.cpp @no-unify+ UIProcess/API/glib/WebKitBackForwardList.cpp @no-unify+ UIProcess/API/glib/WebKitBackForwardListItem.cpp @no-unify++UIProcess/API/glib/WebKitBrowserInspector.cpp @no-unify+ UIProcess/API/glib/WebKitContextMenuClient.cpp @no-unify+ UIProcess/API/glib/WebKitCookieManager.cpp @no-unify+ UIProcess/API/glib/WebKitCredential.cpp @no-unify+@@ -224,6 +225,7 @@ UIProcess/WebsiteData/unix/WebsiteDataStoreUnix.cpp++ UIProcess/cairo/BackingStoreCairo.cpp @no-unify+++UIProcess/glib/InspectorBrowserAgentClientGLib.cpp+ UIProcess/glib/RemoteInspectorClient.cpp+ UIProcess/glib/WebProcessPoolGLib.cpp+ UIProcess/glib/WebProcessProxyGLib.cpp+@@ -249,6 +251,9 @@ UIProcess/gtk/WebColorPickerGtk.cpp+ UIProcess/gtk/WebContextMenuProxyGtk.cpp+ UIProcess/gtk/WebDataListSuggestionsDropdownGtk.cpp+ UIProcess/gtk/WebInspectorProxyGtk.cpp++UIProcess/gtk/WebPageInspectorEmulationAgentGtk.cpp++UIProcess/gtk/WebPageInspectorInputAgentGtk.cpp++UIProcess/gtk/WebPageInspectorTargetProxyGtk.cpp+ UIProcess/gtk/WebKitInspectorWindow.cpp+ UIProcess/gtk/WebPageProxyGtk.cpp @no-unify+ UIProcess/gtk/WebPasteboardProxyGtk.cpp+diff --git a/Source/WebKit/SourcesWPE.txt b/Source/WebKit/SourcesWPE.txt+index 5b514d5216e..75bd77c7614 100644+--- a/Source/WebKit/SourcesWPE.txt++++ b/Source/WebKit/SourcesWPE.txt+@@ -118,6 +118,7 @@ UIProcess/API/glib/WebKitAuthenticationRequest.cpp @no-unify+ UIProcess/API/glib/WebKitAutomationSession.cpp @no-unify+ UIProcess/API/glib/WebKitBackForwardList.cpp @no-unify+ UIProcess/API/glib/WebKitBackForwardListItem.cpp @no-unify++UIProcess/API/glib/WebKitBrowserInspector.cpp @no-unify+ UIProcess/API/glib/WebKitContextMenuClient.cpp @no-unify+ UIProcess/API/glib/WebKitCookieManager.cpp @no-unify+ UIProcess/API/glib/WebKitCredential.cpp @no-unify+@@ -186,7 +187,7 @@ UIProcess/Automation/wpe/WebAutomationSessionWPE.cpp+ UIProcess/CoordinatedGraphics/DrawingAreaProxyCoordinatedGraphics.cpp++ UIProcess/geoclue/GeoclueGeolocationProvider.cpp+-++UIProcess/glib/InspectorBrowserAgentClientGLib.cpp+ UIProcess/glib/WebProcessPoolGLib.cpp+ UIProcess/glib/WebProcessProxyGLib.cpp+ UIProcess/glib/WebsiteDataStoreGLib.cpp @no-unify+@@ -211,6 +212,9 @@ UIProcess/soup/WebProcessPoolSoup.cpp+ UIProcess/wpe/TextCheckerWPE.cpp+ UIProcess/wpe/WebInspectorProxyWPE.cpp+ UIProcess/wpe/WebPageProxyWPE.cpp++UIProcess/wpe/WebPageInspectorEmulationAgentWPE.cpp++UIProcess/wpe/WebPageInspectorInputAgentWPE.cpp++UIProcess/wpe/WebPageInspectorTargetProxyWPE.cpp+ UIProcess/wpe/WebPasteboardProxyWPE.cpp+ UIProcess/wpe/WebPreferencesWPE.cpp++diff --git a/Source/WebKit/UIProcess/API/APIAttachment.cpp b/Source/WebKit/UIProcess/API/APIAttachment.cpp+index f9a4cadfae1..1386ed63eca 100644+--- a/Source/WebKit/UIProcess/API/APIAttachment.cpp++++ b/Source/WebKit/UIProcess/API/APIAttachment.cpp+@@ -28,6 +28,7 @@++ #if ENABLE(ATTACHMENT_ELEMENT)+++#include "WebPageProxy.h"+ #include <WebCore/SharedBuffer.h>+ #include <wtf/text/WTFString.h>++diff --git a/Source/WebKit/UIProcess/API/C/WKPage.cpp b/Source/WebKit/UIProcess/API/C/WKPage.cpp+index 44637251dff..1e64b9f34fe 100644+--- a/Source/WebKit/UIProcess/API/C/WKPage.cpp++++ b/Source/WebKit/UIProcess/API/C/WKPage.cpp+@@ -1734,6 +1734,8 @@ void WKPageSetPageUIClient(WKPageRef pageRef, const WKPageUIClientBase* wkClient+ {+ if (!m_client.didNotHandleKeyEvent)+ return;++ if (!event.nativeEvent())++ return;+ m_client.didNotHandleKeyEvent(toAPI(page), event.nativeEvent(), m_client.base.clientInfo);+ }++diff --git a/Source/WebKit/UIProcess/API/Cocoa/_WKBrowserInspector.h b/Source/WebKit/UIProcess/API/Cocoa/_WKBrowserInspector.h+new file mode 100644+index 00000000000..812c2913e4f+--- /dev/null++++ b/Source/WebKit/UIProcess/API/Cocoa/_WKBrowserInspector.h+@@ -0,0 +1,50 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ *++ * met:++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#import <WebKit/WKFoundation.h>++#import <Foundation/Foundation.h>++++NS_ASSUME_NONNULL_BEGIN++++@class WKWebView;++++@protocol _WKBrowserInspectorDelegate <NSObject>++- (WKWebView *)createNewPage;++- (void)quit;++@end++++WK_CLASS_AVAILABLE(macos(10.15.0))++@interface _WKBrowserInspector : NSObject+++ (void)initializeRemoteInspectorPipe:(id<_WKBrowserInspectorDelegate>)delegate;++@end++++++NS_ASSUME_NONNULL_END+++diff --git a/Source/WebKit/UIProcess/API/Cocoa/_WKBrowserInspector.mm b/Source/WebKit/UIProcess/API/Cocoa/_WKBrowserInspector.mm+new file mode 100644+index 00000000000..2c9aead1b47+--- /dev/null++++ b/Source/WebKit/UIProcess/API/Cocoa/_WKBrowserInspector.mm+@@ -0,0 +1,52 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ *++ * met:++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "_WKBrowserInspector.h"++++#include "BrowserInspectorPipe.h"++#include "InspectorBrowserAgentClientMac.h"++#include "WebKit2Initialize.h"++++#import "WKWebView.h"++++using namespace WebKit;++++@implementation _WKBrowserInspector+++++ (void)initializeRemoteInspectorPipe:(id<_WKBrowserInspectorDelegate>)delegate++{++#if ENABLE(REMOTE_INSPECTOR)++ InitializeWebKit2();++ initializeBrowserInspectorPipe(makeUnique<InspectorBrowserAgentClientMac>(delegate));++#endif++}++++@end+diff --git a/Source/WebKit/UIProcess/API/glib/WebKitBrowserInspector.cpp b/Source/WebKit/UIProcess/API/glib/WebKitBrowserInspector.cpp+new file mode 100644+index 00000000000..a893558f98b+--- /dev/null++++ b/Source/WebKit/UIProcess/API/glib/WebKitBrowserInspector.cpp+@@ -0,0 +1,141 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebKitBrowserInspector.h"++++#include "BrowserInspectorPipe.h"++#include "InspectorBrowserAgentClientGLib.h"++#include "WebKitBrowserInspectorPrivate.h"++#include "WebKitWebViewPrivate.h"++#include <wtf/glib/GRefPtr.h>++#include <wtf/glib/WTFGType.h>++++/**++ * SECTION: WebKitBrowserInspector++ * @Short_description: Access to the WebKit browser inspector++ * @Title: WebKitBrowserInspector++ *++ * The WebKit Browser Inspector is an experimental API that provides++ * access to the inspector via the remote debugging protocol. The protocol++ * allows to create ephemeral contexts and create pages in them and then++ * manipulate them using the inspector commands. This may be useful for++ * the browser automation or remote debugging.++ *++ * Currently the protocol can be exposed to the parent process via a unix++ * pipe.++ */++++enum {++ CREATE_NEW_PAGE,++++ LAST_SIGNAL++};++++struct _WebKitBrowserInspectorPrivate {++ int unused { 0 };++};++++WEBKIT_DEFINE_TYPE(WebKitBrowserInspector, webkit_browser_inspector, G_TYPE_OBJECT)++++static guint signals[LAST_SIGNAL] = { 0, };++++static void webkit_browser_inspector_class_init(WebKitBrowserInspectorClass* findClass)++{++ GObjectClass* gObjectClass = G_OBJECT_CLASS(findClass);++++ /**++ * WebKitBrowserInspector::create-new-page:++ * @inspector: the #WebKitBrowserInspector on which the signal is emitted++ *++ * Emitted when the inspector is requested to create a new page in the provided++ * #WebKitWebContext.++ *++ * This signal is emitted when inspector receives 'Browser.createPage' command++ * from its remote client. If the signla is not handled the command will fail.++ *++ * Returns: %WebKitWebView that contains created page.++ */++ signals[CREATE_NEW_PAGE] = g_signal_new(++ "create-new-page",++ G_TYPE_FROM_CLASS(gObjectClass),++ G_SIGNAL_RUN_LAST,++ G_STRUCT_OFFSET(WebKitBrowserInspectorClass, create_new_page),++ nullptr, nullptr,++ g_cclosure_marshal_generic,++#if PLATFORM(GTK)++ GTK_TYPE_WIDGET,++#else++ WEBKIT_TYPE_WEB_VIEW,++#endif++ 1,++ WEBKIT_TYPE_WEB_CONTEXT);++}++++WebKit::WebPageProxy* webkitBrowserInspectorCreateNewPageInContext(WebKitWebContext* context)++{++ WebKitWebView* newWebView;++ g_signal_emit(webkit_browser_inspector_get_default(), signals[CREATE_NEW_PAGE], 0, context, &newWebView);++ if (!newWebView)++ return nullptr;++ return &webkitWebViewGetPage(newWebView);++}++++static gpointer createWebKitBrowserInspector(gpointer)++{++ static GRefPtr<WebKitBrowserInspector> browserInspector = adoptGRef(WEBKIT_BROWSER_INSPECTOR(g_object_new(WEBKIT_TYPE_BROWSER_INSPECTOR, nullptr)));++ return browserInspector.get();++}++++/**++ * webkit_browser_inspector_get_default:++ *++ * Gets the default instance of the browser inspector.++ *++ * Returns: (transfer none): a #WebKitBrowserInspector++ */++WebKitBrowserInspector* webkit_browser_inspector_get_default(void)++{++ static GOnce onceInit = G_ONCE_INIT;++ return WEBKIT_BROWSER_INSPECTOR(g_once(&onceInit, createWebKitBrowserInspector, 0));++}++++/**++ * webkit_browser_inspector_initialize_pipe:++ *++ * Creates browser inspector and configures pipe handler to communicate with++ * the parent process.++ */++void webkit_browser_inspector_initialize_pipe(void)++{++#if ENABLE(REMOTE_INSPECTOR)++ WebKit::initializeBrowserInspectorPipe(makeUnique<WebKit::InspectorBrowserAgentClientGlib>());++#endif++}+diff --git a/Source/WebKit/UIProcess/API/glib/WebKitBrowserInspectorPrivate.h b/Source/WebKit/UIProcess/API/glib/WebKitBrowserInspectorPrivate.h+new file mode 100644+index 00000000000..6e9afeac99a+--- /dev/null++++ b/Source/WebKit/UIProcess/API/glib/WebKitBrowserInspectorPrivate.h+@@ -0,0 +1,36 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#include "WebKitBrowserInspector.h"++#include "WebPageProxy.h"++++WebKit::WebPageProxy* webkitBrowserInspectorCreateNewPageInContext(WebKitWebContext*);+diff --git a/Source/WebKit/UIProcess/API/glib/WebKitWebContext.cpp b/Source/WebKit/UIProcess/API/glib/WebKitWebContext.cpp+index 126bccf1314..a095db63bc5 100644+--- a/Source/WebKit/UIProcess/API/glib/WebKitWebContext.cpp++++ b/Source/WebKit/UIProcess/API/glib/WebKitWebContext.cpp+@@ -373,6 +373,11 @@ static void webkitWebContextConstructed(GObject* object)+ if (!webkit_website_data_manager_is_ephemeral(priv->websiteDataManager.get()))+ WebKit::LegacyGlobalSettings::singleton().setHSTSStorageDirectory(FileSystem::stringFromFileSystemRepresentation(webkit_website_data_manager_get_hsts_cache_directory(priv->websiteDataManager.get())));+++ const gchar *singleprocess = g_getenv("MINIBROWSER_SINGLEPROCESS");++ if (singleprocess && *singleprocess) {++ // processModel is not set at this point, force single process.++ configuration.setUsesSingleWebProcess(true);++ }+ priv->processPool = WebProcessPool::create(configuration);+ priv->processPool->setPrimaryDataStore(webkitWebsiteDataManagerGetDataStore(priv->websiteDataManager.get()));+ priv->processPool->setUserMessageHandler([webContext](UserMessage&& message, CompletionHandler<void(UserMessage&&)>&& completionHandler) {+diff --git a/Source/WebKit/UIProcess/API/gtk/PageClientImpl.cpp b/Source/WebKit/UIProcess/API/gtk/PageClientImpl.cpp+index 00b7c6bbc46..c3a6cf416e1 100644+--- a/Source/WebKit/UIProcess/API/gtk/PageClientImpl.cpp++++ b/Source/WebKit/UIProcess/API/gtk/PageClientImpl.cpp+@@ -226,6 +226,8 @@ void PageClientImpl::doneWithKeyEvent(const NativeWebKeyboardEvent& event, bool+ return;+ if (event.fakedForComposition())+ return;++ if (!event.nativeEvent())++ return;++ WebKitWebViewBase* webkitWebViewBase = WEBKIT_WEB_VIEW_BASE(m_viewWidget);+ webkitWebViewBaseForwardNextKeyEvent(webkitWebViewBase);+diff --git a/Source/WebKit/UIProcess/API/gtk/WebKitBrowserInspector.h b/Source/WebKit/UIProcess/API/gtk/WebKitBrowserInspector.h+new file mode 100644+index 00000000000..4ee8204a9b8+--- /dev/null++++ b/Source/WebKit/UIProcess/API/gtk/WebKitBrowserInspector.h+@@ -0,0 +1,84 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#if !defined(__WEBKIT2_H_INSIDE__) && !defined(WEBKIT2_COMPILATION)++#error "Only <webkit2/webkit2.h> can be included directly."++#endif++++#ifndef WebKitBrowserInspector_h++#define WebKitBrowserInspector_h++++#include <glib-object.h>++#include <webkit2/WebKitDefines.h>++#include <webkit2/WebKitWebView.h>++++G_BEGIN_DECLS++++#define WEBKIT_TYPE_BROWSER_INSPECTOR (webkit_browser_inspector_get_type())++#define WEBKIT_BROWSER_INSPECTOR(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_BROWSER_INSPECTOR, WebKitBrowserInspector))++#define WEBKIT_IS_BROWSER_INSPECTOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_BROWSER_INSPECTOR))++#define WEBKIT_BROWSER_INSPECTOR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_BROWSER_INSPECTOR, WebKitBrowserInspectorClass))++#define WEBKIT_IS_BROWSER_INSPECTOR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_BROWSER_INSPECTOR))++#define WEBKIT_BROWSER_INSPECTOR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_BROWSER_INSPECTOR, WebKitBrowserInspectorClass))++++typedef struct _WebKitBrowserInspector WebKitBrowserInspector;++typedef struct _WebKitBrowserInspectorClass WebKitBrowserInspectorClass;++typedef struct _WebKitBrowserInspectorPrivate WebKitBrowserInspectorPrivate;++++struct _WebKitBrowserInspector {++ GObject parent;++++ WebKitBrowserInspectorPrivate *priv;++};++++struct _WebKitBrowserInspectorClass {++ GObjectClass parent_class;++++ WebKitWebView *(* create_new_page) (WebKitBrowserInspector *browser_inspector,++ WebKitWebContext *context);++++ void (*_webkit_reserved0) (void);++ void (*_webkit_reserved1) (void);++ void (*_webkit_reserved2) (void);++ void (*_webkit_reserved3) (void);++};++++WEBKIT_API GType++webkit_browser_inspector_get_type (void);++++WEBKIT_API WebKitBrowserInspector *++webkit_browser_inspector_get_default (void);++++WEBKIT_API void++webkit_browser_inspector_initialize_pipe (void);++++G_END_DECLS++++#endif+diff --git a/Source/WebKit/UIProcess/API/gtk/webkit2.h b/Source/WebKit/UIProcess/API/gtk/webkit2.h+index 16ef7eb6d42..eb3759b05bb 100644+--- a/Source/WebKit/UIProcess/API/gtk/webkit2.h++++ b/Source/WebKit/UIProcess/API/gtk/webkit2.h+@@ -32,6 +32,7 @@+ #include <webkit2/WebKitAutomationSession.h>+ #include <webkit2/WebKitBackForwardList.h>+ #include <webkit2/WebKitBackForwardListItem.h>++#include <webkit2/WebKitBrowserInspector.h>+ #include <webkit2/WebKitContextMenu.h>+ #include <webkit2/WebKitContextMenuActions.h>+ #include <webkit2/WebKitContextMenuItem.h>+diff --git a/Source/WebKit/UIProcess/API/wpe/WebKitBrowserInspector.h b/Source/WebKit/UIProcess/API/wpe/WebKitBrowserInspector.h+new file mode 100644+index 00000000000..675e517596b+--- /dev/null++++ b/Source/WebKit/UIProcess/API/wpe/WebKitBrowserInspector.h+@@ -0,0 +1,81 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#if !defined(__WEBKIT_H_INSIDE__) && !defined(WEBKIT2_COMPILATION)++#error "Only <wpe/webkit.h> can be included directly."++#endif++++#ifndef WebKitBrowserInspector_h++#define WebKitBrowserInspector_h++++#include <glib-object.h>++#include <wpe/WebKitDefines.h>++#include <wpe/WebKitWebView.h>++++G_BEGIN_DECLS++++#define WEBKIT_TYPE_BROWSER_INSPECTOR (webkit_browser_inspector_get_type())++#define WEBKIT_BROWSER_INSPECTOR(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj), WEBKIT_TYPE_BROWSER_INSPECTOR, WebKitBrowserInspector))++#define WEBKIT_IS_BROWSER_INSPECTOR(obj) (G_TYPE_CHECK_INSTANCE_TYPE((obj), WEBKIT_TYPE_BROWSER_INSPECTOR))++#define WEBKIT_BROWSER_INSPECTOR_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST((klass), WEBKIT_TYPE_BROWSER_INSPECTOR, WebKitBrowserInspectorClass))++#define WEBKIT_IS_BROWSER_INSPECTOR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE((klass), WEBKIT_TYPE_BROWSER_INSPECTOR))++#define WEBKIT_BROWSER_INSPECTOR_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS((obj), WEBKIT_TYPE_BROWSER_INSPECTOR, WebKitBrowserInspectorClass))++++typedef struct _WebKitBrowserInspector WebKitBrowserInspector;++typedef struct _WebKitBrowserInspectorClass WebKitBrowserInspectorClass;++typedef struct _WebKitBrowserInspectorPrivate WebKitBrowserInspectorPrivate;++++struct _WebKitBrowserInspector {++ GObject parent;++++ WebKitBrowserInspectorPrivate *priv;++};++++struct _WebKitBrowserInspectorClass {++ GObjectClass parent_class;++++ WebKitWebView *(* create_new_page) (WebKitBrowserInspector *browser_inspector,++ WebKitWebContext *context);++++ void (*_webkit_reserved0) (void);++ void (*_webkit_reserved1) (void);++ void (*_webkit_reserved2) (void);++ void (*_webkit_reserved3) (void);++};++++WEBKIT_API GType++webkit_browser_inspector_get_type (void);++++WEBKIT_API WebKitBrowserInspector *++webkit_browser_inspector_get_default (void);++++G_END_DECLS++++#endif+diff --git a/Source/WebKit/UIProcess/API/wpe/webkit.h b/Source/WebKit/UIProcess/API/wpe/webkit.h+index 9cc31cb4968..930499e65b6 100644+--- a/Source/WebKit/UIProcess/API/wpe/webkit.h++++ b/Source/WebKit/UIProcess/API/wpe/webkit.h+@@ -32,6 +32,7 @@+ #include <wpe/WebKitAutomationSession.h>+ #include <wpe/WebKitBackForwardList.h>+ #include <wpe/WebKitBackForwardListItem.h>++#include <wpe/WebKitBrowserInspector.h>+ #include <wpe/WebKitContextMenu.h>+ #include <wpe/WebKitContextMenuActions.h>+ #include <wpe/WebKitContextMenuItem.h>+diff --git a/Source/WebKit/UIProcess/BrowserInspectorController.cpp b/Source/WebKit/UIProcess/BrowserInspectorController.cpp+new file mode 100644+index 00000000000..b4e14cb4390+--- /dev/null++++ b/Source/WebKit/UIProcess/BrowserInspectorController.cpp+@@ -0,0 +1,128 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "BrowserInspectorController.h"++++#if ENABLE(REMOTE_INSPECTOR)++++#include "BrowserInspectorTargetAgent.h"++#include "InspectorBrowserAgent.h"++#include "InspectorBrowserAgentClient.h"++#include "WebPageInspectorController.h"++#include "WebPageProxy.h"++#include "WebProcessPool.h"++#include "WebProcessProxy.h"++#include <JavaScriptCore/InspectorBackendDispatcher.h>++#include <JavaScriptCore/InspectorBackendDispatchers.h>++#include <JavaScriptCore/InspectorFrontendChannel.h>++#include <JavaScriptCore/InspectorFrontendRouter.h>++#include <JavaScriptCore/InspectorTarget.h>++#include <wtf/Ref.h>++#include <wtf/RefPtr.h>++++using namespace Inspector;++++namespace WebKit {++++static Vector<WebPageProxy*> allPages()++{++ ASSERT(isMainThread());++ Vector<WebPageProxy*> result;++ for (WebProcessPool* pool : WebProcessPool::allProcessPools()) {++ for (auto& process : pool->processes()) {++ result.appendRange(process->pages().begin(), process->pages().end());++ }++ }++ return result;++}++++BrowserInspectorController::BrowserInspectorController(std::unique_ptr<InspectorBrowserAgentClient> client)++ : m_frontendChannel(nullptr)++ , m_frontendRouter(FrontendRouter::create())++ , m_backendDispatcher(BackendDispatcher::create(m_frontendRouter.copyRef()))++ , m_browserAgentClient(std::move(client))++{++ m_agents.append(makeUnique<InspectorBrowserAgent>(m_backendDispatcher, m_browserAgentClient.get()));++ m_agents.append(makeUnique<BrowserInspectorTargetAgent>(m_backendDispatcher));++}++++BrowserInspectorController::~BrowserInspectorController() = default;++++void BrowserInspectorController::connectFrontend(FrontendChannel& frontendChannel)++{++ ASSERT(!m_frontendChannel);++ m_frontendChannel = &frontendChannel;++ // Auto-connect to all new pages.++ WebPageInspectorController::setCreationListener([this](WebPageInspectorController& inspectorController) {++ inspectorController.connectFrontend(*m_frontendChannel);++ });++++ bool connectingFirstFrontend = !m_frontendRouter->hasFrontends();++ m_frontendRouter->connectFrontend(frontendChannel);++ if (connectingFirstFrontend)++ m_agents.didCreateFrontendAndBackend(&m_frontendRouter.get(), &m_backendDispatcher.get());++++ connectToAllPages();++}++++void BrowserInspectorController::disconnectFrontend()++{++ ASSERT(m_frontendChannel);++ disconnectFromAllPages();++++ m_frontendRouter->disconnectFrontend(*m_frontendChannel);++ if (!m_frontendRouter->hasFrontends())++ m_agents.willDestroyFrontendAndBackend(DisconnectReason::InspectorDestroyed);++++ WebPageInspectorController::setCreationListener(nullptr);++ m_frontendChannel = nullptr;++}++++void BrowserInspectorController::dispatchMessageFromFrontend(const String& message)++{++ m_backendDispatcher->dispatch(message);++}++++void BrowserInspectorController::connectToAllPages()++{++ for (auto* page : allPages())++ page->inspectorController().connectFrontend(*m_frontendChannel);++}++++void BrowserInspectorController::disconnectFromAllPages()++{++ for (auto* page : allPages())++ page->inspectorController().disconnectFrontend(*m_frontendChannel);++}++++} // namespace WebKit++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/BrowserInspectorController.h b/Source/WebKit/UIProcess/BrowserInspectorController.h+new file mode 100644+index 00000000000..d1e7ea17002+--- /dev/null++++ b/Source/WebKit/UIProcess/BrowserInspectorController.h+@@ -0,0 +1,74 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#if ENABLE(REMOTE_INSPECTOR)++++#include <JavaScriptCore/InspectorAgentRegistry.h>++#include <wtf/Forward.h>++#include <wtf/Noncopyable.h>++++namespace Inspector {++class BackendDispatcher;++class FrontendChannel;++class FrontendRouter;++}++++namespace WebKit {++++class InspectorBrowserAgentClient;++++class BrowserInspectorController {++ WTF_MAKE_NONCOPYABLE(BrowserInspectorController);++ WTF_MAKE_FAST_ALLOCATED;++public:++ BrowserInspectorController(std::unique_ptr<InspectorBrowserAgentClient> client);++ ~BrowserInspectorController();++++ void connectFrontend(Inspector::FrontendChannel&);++ void disconnectFrontend();++ void dispatchMessageFromFrontend(const String& message);++++private:++ class TargetHandler;++ void connectToAllPages();++ void disconnectFromAllPages();++++ Inspector::FrontendChannel* m_frontendChannel { nullptr };++ Ref<Inspector::FrontendRouter> m_frontendRouter;++ Ref<Inspector::BackendDispatcher> m_backendDispatcher;++ std::unique_ptr<InspectorBrowserAgentClient> m_browserAgentClient;++ Inspector::AgentRegistry m_agents;++};++++} // namespace WebKit++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/BrowserInspectorPipe.cpp b/Source/WebKit/UIProcess/BrowserInspectorPipe.cpp+new file mode 100644+index 00000000000..483b4e46c98+--- /dev/null++++ b/Source/WebKit/UIProcess/BrowserInspectorPipe.cpp+@@ -0,0 +1,62 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "BrowserInspectorPipe.h"++++#if ENABLE(REMOTE_INSPECTOR)++++#include "BrowserInspectorController.h"++#include "RemoteInspectorPipe.h"++#include <wtf/NeverDestroyed.h>++#include "InspectorBrowserAgentClient.h"++++namespace WebKit {++++void initializeBrowserInspectorPipe(std::unique_ptr<InspectorBrowserAgentClient> client)++{++ class BrowserInspectorPipe {++ public:++ BrowserInspectorPipe(std::unique_ptr<InspectorBrowserAgentClient> client)++ : m_browserInspectorController(std::move(client))++ , m_remoteInspectorPipe(m_browserInspectorController)++ {++ }++++ BrowserInspectorController m_browserInspectorController;++ RemoteInspectorPipe m_remoteInspectorPipe;++ };++++ static NeverDestroyed<BrowserInspectorPipe> pipe(std::move(client));++}++++} // namespace WebKit++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/BrowserInspectorPipe.h b/Source/WebKit/UIProcess/BrowserInspectorPipe.h+new file mode 100644+index 00000000000..a0088a43590+--- /dev/null++++ b/Source/WebKit/UIProcess/BrowserInspectorPipe.h+@@ -0,0 +1,43 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#if ENABLE(REMOTE_INSPECTOR)++++namespace WebKit {++++class InspectorBrowserAgentClient;++++void initializeBrowserInspectorPipe(std::unique_ptr<InspectorBrowserAgentClient> client);++++} // namespace WebKit++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/BrowserInspectorTargetAgent.cpp b/Source/WebKit/UIProcess/BrowserInspectorTargetAgent.cpp+new file mode 100644+index 00000000000..0d1f5d75c3a+--- /dev/null++++ b/Source/WebKit/UIProcess/BrowserInspectorTargetAgent.cpp+@@ -0,0 +1,110 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "BrowserInspectorTargetAgent.h"++++#include "WebPageInspectorController.h"++#include "WebPageProxy.h"++#include "WebProcessPool.h"++#include "WebProcessProxy.h"++#include <JavaScriptCore/InspectorFrontendRouter.h>++#include <JavaScriptCore/InspectorTarget.h>++++using namespace Inspector;++++namespace WebKit {++++namespace {++++InspectorTarget* targetForId(const String& targetId)++{++ ASSERT(isMainThread());++ for (auto* pool : WebProcessPool::allProcessPools()) {++ for (auto& process : pool->processes()) {++ for (auto* page : process->pages()) {++ auto* result = page->inspectorController().findTarget(targetId);++ if (result != nullptr)++ return result;++ }++ }++ }++ return nullptr;++}++++} // namespace++++BrowserInspectorTargetAgent::BrowserInspectorTargetAgent(BackendDispatcher& backendDispatcher)++ : InspectorAgentBase("Target"_s)++ , m_backendDispatcher(TargetBackendDispatcher::create(backendDispatcher, this))++{++}++++BrowserInspectorTargetAgent::~BrowserInspectorTargetAgent() = default;++++void BrowserInspectorTargetAgent::didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*)++{++}++++void BrowserInspectorTargetAgent::willDestroyFrontendAndBackend(DisconnectReason)++{++}++++void BrowserInspectorTargetAgent::sendMessageToTarget(ErrorString& error, const String& in_targetId, const String& in_message)++{++ auto* target = targetForId(in_targetId);++ if (target == nullptr) {++ error = "Cannot find target with provided id.";++ return;++ }++ target->sendMessageToTargetBackend(in_message);++}++++void BrowserInspectorTargetAgent::activate(ErrorString& error, const String& targetId)++{++ auto* target = targetForId(targetId);++ if (target == nullptr) {++ error = "Cannot find target with provided id.";++ return;++ }++ target->activate(error);++}++++void BrowserInspectorTargetAgent::close(ErrorString& error, const String& targetId)++{++ auto* target = targetForId(targetId);++ if (target == nullptr) {++ error = "Cannot find target with provided id.";++ return;++ }++ target->close(error);++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/BrowserInspectorTargetAgent.h b/Source/WebKit/UIProcess/BrowserInspectorTargetAgent.h+new file mode 100644+index 00000000000..8b4d9273574+--- /dev/null++++ b/Source/WebKit/UIProcess/BrowserInspectorTargetAgent.h+@@ -0,0 +1,62 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#include "config.h"++++#include <JavaScriptCore/InspectorAgentBase.h>++#include <JavaScriptCore/InspectorBackendDispatchers.h>++#include <wtf/Forward.h>++#include <wtf/Noncopyable.h>++++namespace WebKit {++++class BrowserInspectorTargetAgent final : public Inspector::InspectorAgentBase, public Inspector::TargetBackendDispatcherHandler {++ WTF_MAKE_NONCOPYABLE(BrowserInspectorTargetAgent);++ WTF_MAKE_FAST_ALLOCATED;++public:++ explicit BrowserInspectorTargetAgent(Inspector::BackendDispatcher&);++ ~BrowserInspectorTargetAgent() override;++++ // InspectorAgentBase++ void didCreateFrontendAndBackend(Inspector::FrontendRouter*, Inspector::BackendDispatcher*) override;++ void willDestroyFrontendAndBackend(Inspector::DisconnectReason) override;++++ // TargetBackendDispatcherHandler++ void sendMessageToTarget(Inspector::ErrorString&, const String& targetId, const String& message) final;++ void activate(Inspector::ErrorString&, const String& targetId) override;++ void close(Inspector::ErrorString&, const String& targetId) override;++++private:++ Ref<Inspector::TargetBackendDispatcher> m_backendDispatcher;++};++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/Cocoa/SOAuthorization/PopUpSOAuthorizationSession.h b/Source/WebKit/UIProcess/Cocoa/SOAuthorization/PopUpSOAuthorizationSession.h+index b6694fe906e..4df2ca7d9cc 100644+--- a/Source/WebKit/UIProcess/Cocoa/SOAuthorization/PopUpSOAuthorizationSession.h++++ b/Source/WebKit/UIProcess/Cocoa/SOAuthorization/PopUpSOAuthorizationSession.h+@@ -27,6 +27,8 @@++ #if HAVE(APP_SSO)+++#include <wtf/Forward.h>++#include <wtf/CompletionHandler.h>+ #include "SOAuthorizationSession.h"++ OBJC_CLASS WKSOSecretDelegate;+@@ -38,6 +40,8 @@ class NavigationAction;++ namespace WebKit {+++class WebPageProxy;+++ // FSM: Idle => Active => Completed+ class PopUpSOAuthorizationSession final : public SOAuthorizationSession {+ public:+diff --git a/Source/WebKit/UIProcess/Cocoa/SOAuthorization/PopUpSOAuthorizationSession.mm b/Source/WebKit/UIProcess/Cocoa/SOAuthorization/PopUpSOAuthorizationSession.mm+index 076cfaa676a..bd20a2b95f9 100644+--- a/Source/WebKit/UIProcess/Cocoa/SOAuthorization/PopUpSOAuthorizationSession.mm++++ b/Source/WebKit/UIProcess/Cocoa/SOAuthorization/PopUpSOAuthorizationSession.mm+@@ -29,6 +29,7 @@+ #if HAVE(APP_SSO)++ #import "APINavigationAction.h"++#import "WebPageProxy.h"+ #import "WKNavigationDelegatePrivate.h"+ #import "WKUIDelegate.h"+ #import "WKWebViewConfigurationPrivate.h"+diff --git a/Source/WebKit/UIProcess/InspectorBrowserAgent.cpp b/Source/WebKit/UIProcess/InspectorBrowserAgent.cpp+new file mode 100644+index 00000000000..5967318c785+--- /dev/null++++ b/Source/WebKit/UIProcess/InspectorBrowserAgent.cpp+@@ -0,0 +1,101 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "InspectorBrowserAgent.h"++++#if ENABLE(REMOTE_INSPECTOR)++++#include "InspectorBrowserAgentClient.h"++#include "WebPageInspectorTarget.h"++#include "WebPageProxy.h"++#include <JavaScriptCore/InspectorFrontendRouter.h>++#include <pal/SessionID.h>++#include <wtf/HexNumber.h>++++using namespace Inspector;++++namespace WebKit {++++InspectorBrowserAgent::InspectorBrowserAgent(Inspector::BackendDispatcher& backendDispatcher, InspectorBrowserAgentClient* client)++ : InspectorAgentBase("Browser"_s)++ , m_backendDispatcher(BrowserBackendDispatcher::create(backendDispatcher, this))++ , m_client(client)++{++}++++InspectorBrowserAgent::~InspectorBrowserAgent() = default;++++void InspectorBrowserAgent::didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*)++{++}++++void InspectorBrowserAgent::willDestroyFrontendAndBackend(DisconnectReason)++{++}++++void InspectorBrowserAgent::close(ErrorString& error)++{++ if (m_client == nullptr) {++ error = "no platform delegate to close browser";++ } else {++ m_client->closeAllWindows();++ }++}++++void InspectorBrowserAgent::createContext(ErrorString& error, String* browserContextID)++{++ m_client->createBrowserContext(error, browserContextID);++}++++void InspectorBrowserAgent::deleteContext(ErrorString& error, const String& browserContextID)++{++ m_client->deleteBrowserContext(error, browserContextID);++}++++void InspectorBrowserAgent::createPage(ErrorString& error, const String* browserContextID, String* targetID)++{++ RefPtr<WebPageProxy> page = m_client->createPage(error, browserContextID);++ if (page == nullptr)++ return;++++ *targetID = WebPageInspectorTarget::toTargetID(page->webPageID());++}++++String InspectorBrowserAgent::toBrowserContextIDProtocolString(const PAL::SessionID& sessionID)++{++ StringBuilder builder;++ appendUnsignedAsHexFixedSize(sessionID.toUInt64(), builder, 16);++ return builder.toString();++}++++} // namespace WebKit++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/InspectorBrowserAgent.h b/Source/WebKit/UIProcess/InspectorBrowserAgent.h+new file mode 100644+index 00000000000..f24c655ab39+--- /dev/null++++ b/Source/WebKit/UIProcess/InspectorBrowserAgent.h+@@ -0,0 +1,81 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#if ENABLE(REMOTE_INSPECTOR)++++#include <JavaScriptCore/InspectorAgentBase.h>++#include <JavaScriptCore/InspectorBackendDispatchers.h>++#include <wtf/Forward.h>++#include <wtf/Noncopyable.h>++++namespace Inspector {++class BackendDispatcher;++class FrontendChannel;++class FrontendRouter;++}++++namespace PAL {++class SessionID;++}++++namespace WebKit {++++class InspectorBrowserAgentClient;++class WebPageInspectorController;++++class InspectorBrowserAgent final : public Inspector::InspectorAgentBase, public Inspector::BrowserBackendDispatcherHandler {++ WTF_MAKE_NONCOPYABLE(InspectorBrowserAgent);++ WTF_MAKE_FAST_ALLOCATED;++public:++ InspectorBrowserAgent(Inspector::BackendDispatcher&, InspectorBrowserAgentClient*);++ ~InspectorBrowserAgent() override;++++ // InspectorAgentBase++ void didCreateFrontendAndBackend(Inspector::FrontendRouter*, Inspector::BackendDispatcher*) override;++ void willDestroyFrontendAndBackend(Inspector::DisconnectReason) override;++++ // BrowserBackendDispatcherHandler++ void close(Inspector::ErrorString&) override;++ void createContext(Inspector::ErrorString&, String* browserContextID) override;++ void deleteContext(Inspector::ErrorString&, const String& browserContextID) override;++ void createPage(Inspector::ErrorString&, const String* browserContextID, String* targetId) override;++++ static String toBrowserContextIDProtocolString(const PAL::SessionID&);++++private:++ Ref<Inspector::BrowserBackendDispatcher> m_backendDispatcher;++ InspectorBrowserAgentClient* m_client;++};++++} // namespace WebKit++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/InspectorBrowserAgentClient.h b/Source/WebKit/UIProcess/InspectorBrowserAgentClient.h+new file mode 100644+index 00000000000..f05cd030bac+--- /dev/null++++ b/Source/WebKit/UIProcess/InspectorBrowserAgentClient.h+@@ -0,0 +1,52 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#if ENABLE(REMOTE_INSPECTOR)++++#include <wtf/Forward.h>++++namespace WebKit {++++class WebPageProxy;++++class InspectorBrowserAgentClient {++public:++ virtual ~InspectorBrowserAgentClient() = default;++ virtual RefPtr<WebKit::WebPageProxy> createPage(WTF::String& error, const WTF::String* browserContextID) = 0;++ virtual void closeAllWindows() = 0;++ virtual void createBrowserContext(WTF::String& error, WTF::String* browserContextID) = 0;++ virtual void deleteBrowserContext(WTF::String& error, const WTF::String& browserContextID) = 0;++};++++} // namespace WebKit++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/InspectorTargetProxy.cpp b/Source/WebKit/UIProcess/InspectorTargetProxy.cpp+index 1b37c1ed439..c45d45de342 100644+--- a/Source/WebKit/UIProcess/InspectorTargetProxy.cpp++++ b/Source/WebKit/UIProcess/InspectorTargetProxy.cpp+@@ -32,6 +32,8 @@+ #include "WebPageMessages.h"+ #include "WebPageProxy.h"+ #include "WebProcessProxy.h"++#include "ProvisionalPageProxy.h"++++ namespace WebKit {++@@ -39,23 +41,29 @@ using namespace Inspector;++ std::unique_ptr<InspectorTargetProxy> InspectorTargetProxy::create(WebPageProxy& page, const String& targetId, Inspector::InspectorTargetType type)+ {+- return makeUnique<InspectorTargetProxy>(page, targetId, type);++ return makeUnique<InspectorTargetProxy>(page, nullptr, targetId, type);+ }++ std::unique_ptr<InspectorTargetProxy> InspectorTargetProxy::create(ProvisionalPageProxy& provisionalPage, const String& targetId, Inspector::InspectorTargetType type)+ {+- auto target = InspectorTargetProxy::create(provisionalPage.page(), targetId, type);+- target->m_provisionalPage = makeWeakPtr(provisionalPage);+- return target;++ return makeUnique<InspectorTargetProxy>(provisionalPage.page(), &provisionalPage, targetId, type);+ }++-InspectorTargetProxy::InspectorTargetProxy(WebPageProxy& page, const String& targetId, Inspector::InspectorTargetType type)++InspectorTargetProxy::InspectorTargetProxy(WebPageProxy& page, ProvisionalPageProxy* provisionalPage, const String& targetId, Inspector::InspectorTargetType type)+ : m_page(page)++ , m_provisionalPage(makeWeakPtr(provisionalPage))+ , m_identifier(targetId)+ , m_type(type)+ {+ }+++String InspectorTargetProxy::url() const++{++ if (m_page.provisionalPageProxy())++ return m_page.provisionalPageProxy()->provisionalURL().string();++ return m_page.pageLoadState().activeURL();++}+++ void InspectorTargetProxy::connect(Inspector::FrontendChannel::ConnectionType connectionType)+ {+ if (m_provisionalPage) {+diff --git a/Source/WebKit/UIProcess/InspectorTargetProxy.h b/Source/WebKit/UIProcess/InspectorTargetProxy.h+index a2239cec8e1..43415afbc77 100644+--- a/Source/WebKit/UIProcess/InspectorTargetProxy.h++++ b/Source/WebKit/UIProcess/InspectorTargetProxy.h+@@ -37,17 +37,18 @@ class WebPageProxy;+ // NOTE: This UIProcess side InspectorTarget doesn't care about the frontend channel, since+ // any target -> frontend messages will be routed to the WebPageProxy with a targetId.++-class InspectorTargetProxy final : public Inspector::InspectorTarget {++class InspectorTargetProxy : public Inspector::InspectorTarget {+ WTF_MAKE_FAST_ALLOCATED;+ WTF_MAKE_NONCOPYABLE(InspectorTargetProxy);+ public:+ static std::unique_ptr<InspectorTargetProxy> create(WebPageProxy&, const String& targetId, Inspector::InspectorTargetType);+ static std::unique_ptr<InspectorTargetProxy> create(ProvisionalPageProxy&, const String& targetId, Inspector::InspectorTargetType);+- InspectorTargetProxy(WebPageProxy&, const String& targetId, Inspector::InspectorTargetType);++ InspectorTargetProxy(WebPageProxy&, ProvisionalPageProxy*, const String& targetId, Inspector::InspectorTargetType);+ ~InspectorTargetProxy() = default;++ Inspector::InspectorTargetType type() const final { return m_type; }+ String identifier() const final { return m_identifier; }++ String url() const final;++ void didCommitProvisionalTarget();+ bool isProvisional() const override;+@@ -56,11 +57,13 @@ public:+ void disconnect() override;+ void sendMessageToTargetBackend(const String&) override;++-private:++protected:+ WebPageProxy& m_page;++++private:++ WeakPtr<ProvisionalPageProxy> m_provisionalPage;+ String m_identifier;+ Inspector::InspectorTargetType m_type;+- WeakPtr<ProvisionalPageProxy> m_provisionalPage;+ };++ } // namespace WebKit+diff --git a/Source/WebKit/UIProcess/RemoteInspectorPipe.cpp b/Source/WebKit/UIProcess/RemoteInspectorPipe.cpp+new file mode 100644+index 00000000000..87b426e9fff+--- /dev/null++++ b/Source/WebKit/UIProcess/RemoteInspectorPipe.cpp+@@ -0,0 +1,159 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "RemoteInspectorPipe.h"++++#if ENABLE(REMOTE_INSPECTOR)++++#include "BrowserInspectorController.h"++#include <JavaScriptCore/InspectorFrontendChannel.h>++#include <wtf/MainThread.h>++#include <wtf/RunLoop.h>++#include <wtf/UniqueArray.h>++#include <wtf/Vector.h>++#include <wtf/WorkQueue.h>++++#if OS(UNIX)++#include <stdio.h>++#include <unistd.h>++#endif++++namespace WebKit {++++static const int readFD = 3;++static const int writeFD = 4;++++class RemoteInspectorPipe::RemoteFrontendChannel : public Inspector::FrontendChannel {++ WTF_MAKE_FAST_ALLOCATED;++public:++ RemoteFrontendChannel()++ : m_senderQueue(WorkQueue::create("Inspector pipe writer"))++ {++ }++++ ~RemoteFrontendChannel() override = default;++++ ConnectionType connectionType() const override++ {++ return ConnectionType::Remote;++ }++++ void sendMessageToFrontend(const String& message) override++ {++ m_senderQueue->dispatch([message = message.isolatedCopy()]() {++ dprintf(writeFD, "%s%c", message.ascii().data(), '\0');++ });++ }++++private:++ Ref<WorkQueue> m_senderQueue;++};++++RemoteInspectorPipe::RemoteInspectorPipe(BrowserInspectorController& browserInspectorController)++ : m_remoteFrontendChannel(makeUnique<RemoteFrontendChannel>())++ , m_browserInspectorController(browserInspectorController)++{++ start();++}++++RemoteInspectorPipe::~RemoteInspectorPipe()++{++ stop();++}++++bool RemoteInspectorPipe::start()++{++ if (m_receiverThread)++ return true;++++ m_browserInspectorController.connectFrontend(*m_remoteFrontendChannel);++ m_terminated = false;++ m_receiverThread = Thread::create("Inspector pipe reader", [this] {++ workerRun();++ });++ return true;++}++++void RemoteInspectorPipe::stop()++{++ if (!m_receiverThread)++ return;++++ m_browserInspectorController.disconnectFrontend();++++ m_terminated = true;++ m_receiverThread->waitForCompletion();++ m_receiverThread = nullptr;++}++++void RemoteInspectorPipe::workerRun()++{++ const size_t bufSize = 256 * 1024;++ auto buffer = makeUniqueArray<char>(bufSize);++ Vector<char> line;++ while (!m_terminated) {++ ssize_t size = read(readFD, buffer.get(), bufSize);++ if (size == 0) {++ break;++ }++ if (size < 0) {++ break;++ }++ size_t start = 0;++ size_t end = line.size();++ line.append(buffer.get(), size);++ while (true) {++ for (; end < line.size(); ++end) {++ if (line[end] == '\0')++ break;++ }++ if (end == line.size())++ break;++++ if (end > start) {++ String message = String::fromUTF8(line.data() + start, end - start);++ RunLoop::main().dispatch([this, message] {++ if (!m_terminated)++ m_browserInspectorController.dispatchMessageFromFrontend(message);++ });++ }++ ++end;++ start = end;++ }++ if (start != 0 && start < line.size())++ memmove(line.data(), line.data() + start, line.size() - start);++ line.shrink(line.size() - start);++ }++}++++} // namespace WebKit++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/RemoteInspectorPipe.h b/Source/WebKit/UIProcess/RemoteInspectorPipe.h+new file mode 100644+index 00000000000..37b0622557c+--- /dev/null++++ b/Source/WebKit/UIProcess/RemoteInspectorPipe.h+@@ -0,0 +1,70 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#if ENABLE(REMOTE_INSPECTOR)++++#include <wtf/Ref.h>++#include <wtf/RefPtr.h>++#include <wtf/Threading.h>++++namespace Inspector {++class FrontendChannel;++}++++namespace WebKit {++++class BrowserInspectorController;++++class RemoteInspectorPipe {++ WTF_MAKE_NONCOPYABLE(RemoteInspectorPipe);++ WTF_MAKE_FAST_ALLOCATED;++public:++ explicit RemoteInspectorPipe(BrowserInspectorController&);++ ~RemoteInspectorPipe();++++private:++ class RemoteFrontendChannel;++++ bool start();++ void stop();++++ void workerRun();++++ RefPtr<Thread> m_receiverThread;++ std::atomic<bool> m_terminated { false };++ std::unique_ptr<Inspector::FrontendChannel> m_remoteFrontendChannel;++ BrowserInspectorController& m_browserInspectorController;++};++++} // namespace WebKit++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/WebAuthentication/AuthenticatorManager.cpp b/Source/WebKit/UIProcess/WebAuthentication/AuthenticatorManager.cpp+index cce83796f13..eb019b70e0b 100644+--- a/Source/WebKit/UIProcess/WebAuthentication/AuthenticatorManager.cpp++++ b/Source/WebKit/UIProcess/WebAuthentication/AuthenticatorManager.cpp+@@ -35,6 +35,7 @@+ #include "NfcService.h"+ #include "WebPageProxy.h"+ #include "WebPreferencesKeys.h"++#include "WebProcessProxy.h"+ #include <WebCore/AuthenticatorTransport.h>+ #include <WebCore/PublicKeyCredentialCreationOptions.h>+ #include <WebCore/WebAuthenticationConstants.h>+diff --git a/Source/WebKit/UIProcess/WebPageInspectorController.cpp b/Source/WebKit/UIProcess/WebPageInspectorController.cpp+index b9a9469ab59..81129896554 100644+--- a/Source/WebKit/UIProcess/WebPageInspectorController.cpp++++ b/Source/WebKit/UIProcess/WebPageInspectorController.cpp+@@ -26,9 +26,11 @@+ #include "config.h"+ #include "WebPageInspectorController.h"+++#include "InspectorBrowserAgent.h"+ #include "ProvisionalPageProxy.h"+ #include "WebFrameProxy.h"+ #include "WebPageInspectorTarget.h"++#include "WebPageInspectorTargetProxy.h"+ #include "WebPageProxy.h"+ #include <JavaScriptCore/InspectorAgentBase.h>+ #include <JavaScriptCore/InspectorBackendDispatcher.h>+@@ -46,26 +48,59 @@ static String getTargetID(const ProvisionalPageProxy& provisionalPage)+ return WebPageInspectorTarget::toTargetID(provisionalPage.webPageID());+ }+++static WebPageInspectorController::CreationListener& creationListener() {++ static NeverDestroyed<WebPageInspectorController::CreationListener> listener;++ return listener;++}++++void WebPageInspectorController::setCreationListener(CreationListener listener)++{++ creationListener() = listener;++}+++ WebPageInspectorController::WebPageInspectorController(WebPageProxy& page)+ : m_page(page)+ , m_frontendRouter(FrontendRouter::create())+ , m_backendDispatcher(BackendDispatcher::create(m_frontendRouter.copyRef()))+ {+- auto targetAgent = makeUnique<InspectorTargetAgent>(m_frontendRouter.get(), m_backendDispatcher.get());++ String browserContextID;++#if ENABLE(REMOTE_INSPECTOR)++ browserContextID = InspectorBrowserAgent::toBrowserContextIDProtocolString(page.sessionID());++#endif++ auto targetAgent = makeUnique<InspectorTargetAgent>(m_frontendRouter.get(), m_backendDispatcher.get(), browserContextID);++ m_targetAgent = targetAgent.get();++ m_agents.append(WTFMove(targetAgent));++++ if (creationListener())++ creationListener()(*this);+ }++ void WebPageInspectorController::init()+ {++ // window.open will create page with already running process.++ if (!m_page.hasRunningProcess())++ return;+ String pageTargetId = WebPageInspectorTarget::toTargetID(m_page.webPageID());+ createInspectorTarget(pageTargetId, Inspector::InspectorTargetType::Page);+ }+++void WebPageInspectorController::didFinishAttachingToWebProcess()++{++ String pageTargetID = WebPageInspectorTarget::toTargetID(m_page.webPageID());++ // Create target only after attaching to a Web Process first time. Before that++ // we cannot event establish frontend connection.++ if (m_targets.contains(pageTargetID))++ return;++ createInspectorTarget(pageTargetID, Inspector::InspectorTargetType::Page);++}+++ void WebPageInspectorController::pageClosed()+ {++ String pageTargetId = WebPageInspectorTarget::toTargetID(m_page.webPageID());++ destroyInspectorTarget(pageTargetId);+++ disconnectAllFrontends();++ m_agents.discardValues();+@@ -134,6 +169,16 @@ void WebPageInspectorController::dispatchMessageFromFrontend(const String& messa+ m_backendDispatcher->dispatch(message);+ }+++bool WebPageInspectorController::dispatchMessageToTargetBackend(const String& message)++{++ return m_backendDispatcher->dispatch(message, BackendDispatcher::Mode::ContinueIfDomainIsMissing) == BackendDispatcher::DispatchResult::Finished;++}++++Inspector::InspectorTarget* WebPageInspectorController::findTarget(const String& targetId)++{++ return m_targets.get(targetId);++}+++ #if ENABLE(REMOTE_INSPECTOR)+ void WebPageInspectorController::setIndicating(bool indicating)+ {+@@ -150,7 +195,12 @@ void WebPageInspectorController::setIndicating(bool indicating)++ void WebPageInspectorController::createInspectorTarget(const String& targetId, Inspector::InspectorTargetType type)+ {+- addTarget(InspectorTargetProxy::create(m_page, targetId, type));++ std::unique_ptr<InspectorTargetProxy> target;++ if (type == Inspector::InspectorTargetType::Page)++ target = WebPageInspectorTargetProxy::create(m_page, *m_targetAgent, targetId);++ else++ target = InspectorTargetProxy::create(m_page, targetId, type);++ addTarget(WTFMove(target));+ }++ void WebPageInspectorController::destroyInspectorTarget(const String& targetId)+@@ -169,7 +219,7 @@ void WebPageInspectorController::sendMessageToInspectorFrontend(const String& ta++ void WebPageInspectorController::didCreateProvisionalPage(ProvisionalPageProxy& provisionalPage)+ {+- addTarget(InspectorTargetProxy::create(provisionalPage, getTargetID(provisionalPage), Inspector::InspectorTargetType::Page));++ addTarget(WebPageInspectorTargetProxy::create(provisionalPage, *m_targetAgent, getTargetID(provisionalPage)));+ }++ void WebPageInspectorController::willDestroyProvisionalPage(const ProvisionalPageProxy& provisionalPage)+diff --git a/Source/WebKit/UIProcess/WebPageInspectorController.h b/Source/WebKit/UIProcess/WebPageInspectorController.h+index 828bc3ccc7e..40a333b7004 100644+--- a/Source/WebKit/UIProcess/WebPageInspectorController.h++++ b/Source/WebKit/UIProcess/WebPageInspectorController.h+@@ -48,7 +48,13 @@ public:+ WebPageInspectorController(WebPageProxy&);++ void init();++ void didFinishAttachingToWebProcess();++++ using CreationListener = std::function<void(WebPageInspectorController&)>;++ static void setCreationListener(CreationListener);+++ void pageClosed();++ void didProcessAllPendingKeyboardEvents();++ bool hasLocalFrontend() const;++@@ -57,6 +63,8 @@ public:+ void disconnectAllFrontends();++ void dispatchMessageFromFrontend(const String& message);++ Inspector::InspectorTarget* findTarget(const String& targetId);++ bool dispatchMessageToTargetBackend(const String&);++ #if ENABLE(REMOTE_INSPECTOR)+ void setIndicating(bool);+diff --git a/Source/WebKit/UIProcess/WebPageInspectorEmulationAgent.cpp b/Source/WebKit/UIProcess/WebPageInspectorEmulationAgent.cpp+new file mode 100644+index 00000000000..415f36c5647+--- /dev/null++++ b/Source/WebKit/UIProcess/WebPageInspectorEmulationAgent.cpp+@@ -0,0 +1,61 @@++/*++ * Copyright (C) 2018 Apple Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY++ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE++ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR++ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,++ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,++ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR++ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY++ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorEmulationAgent.h"++++#include "WebPageProxy.h"++#include <JavaScriptCore/InspectorFrontendRouter.h>++++++namespace WebKit {++++using namespace Inspector;++++WebPageInspectorEmulationAgent::WebPageInspectorEmulationAgent(BackendDispatcher& backendDispatcher, WebPageProxy& page)++ : InspectorAgentBase("Emulation"_s)++ , m_backendDispatcher(EmulationBackendDispatcher::create(backendDispatcher, this))++ , m_page(page)++{++}++++WebPageInspectorEmulationAgent::~WebPageInspectorEmulationAgent()++{++}++++void WebPageInspectorEmulationAgent::didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*)++{++}++++void WebPageInspectorEmulationAgent::willDestroyFrontendAndBackend(DisconnectReason)++{++}++++void WebPageInspectorEmulationAgent::setDeviceMetricsOverride(ErrorString& error, int in_width, int in_height)++{++ platformSetSize(error, in_width, in_height);++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/WebPageInspectorEmulationAgent.h b/Source/WebKit/UIProcess/WebPageInspectorEmulationAgent.h+new file mode 100644+index 00000000000..2f9b7807e23+--- /dev/null++++ b/Source/WebKit/UIProcess/WebPageInspectorEmulationAgent.h+@@ -0,0 +1,63 @@++/*++ * Copyright (C) 2018 Apple Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY++ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE++ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR++ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,++ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,++ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR++ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY++ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#include <JavaScriptCore/InspectorAgentBase.h>++#include <JavaScriptCore/InspectorBackendDispatchers.h>++++#include <wtf/Forward.h>++#include <wtf/Noncopyable.h>++++namespace Inspector {++class BackendDispatcher;++class FrontendChannel;++class FrontendRouter;++}++++namespace WebKit {++++class WebPageProxy;++++class WebPageInspectorEmulationAgent : public Inspector::InspectorAgentBase, public Inspector::EmulationBackendDispatcherHandler {++ WTF_MAKE_NONCOPYABLE(WebPageInspectorEmulationAgent);++ WTF_MAKE_FAST_ALLOCATED;++public:++ WebPageInspectorEmulationAgent(Inspector::BackendDispatcher& backendDispatcher, WebPageProxy& page);++ ~WebPageInspectorEmulationAgent() override;++++ void didCreateFrontendAndBackend(Inspector::FrontendRouter*, Inspector::BackendDispatcher*) override;++ void willDestroyFrontendAndBackend(Inspector::DisconnectReason) override;++++ void setDeviceMetricsOverride(Inspector::ErrorString&, int in_width, int in_height) override;++++private:++ void platformSetSize(String& error, int width, int height);++++ Ref<Inspector::EmulationBackendDispatcher> m_backendDispatcher;++ WebPageProxy& m_page;++};++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/WebPageInspectorInputAgent.cpp b/Source/WebKit/UIProcess/WebPageInspectorInputAgent.cpp+new file mode 100644+index 00000000000..16a05604460+--- /dev/null++++ b/Source/WebKit/UIProcess/WebPageInspectorInputAgent.cpp+@@ -0,0 +1,257 @@++/*++ * Copyright (C) 2018 Apple Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY++ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE++ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR++ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,++ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,++ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR++ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY++ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorInputAgent.h"++++#include "APINavigation.h"++#include "NativeWebKeyboardEvent.h"++#include "NativeWebMouseEvent.h"++#include "WebPageProxy.h"++#include <JavaScriptCore/InspectorFrontendRouter.h>++++++namespace WebKit {++++using namespace Inspector;++++namespace {++++template<class T>++class CallbackList {++ WTF_MAKE_FAST_ALLOCATED;++public:++ ~CallbackList()++ {++ for (const auto& callback : m_callbacks)++ callback->sendFailure("Page closed");++ }++++ void append(Ref<T>&& callback)++ {++ m_callbacks.append(WTFMove(callback));++ }++++ void sendSuccess()++ {++ for (const auto& callback : m_callbacks)++ callback->sendSuccess();++ m_callbacks.clear();++ }++++private:++ Vector<Ref<T>> m_callbacks;++};++++} // namespace++++class WebPageInspectorInputAgent::InspectorInputObserver : public WebPageProxy::InputProcessingObserver {++ WTF_MAKE_FAST_ALLOCATED;++public:++ using KeyboardCallback = Inspector::InputBackendDispatcherHandler::DispatchKeyEventCallback;++ using MouseCallback = Inspector::InputBackendDispatcherHandler::DispatchMouseEventCallback;++++ ~InspectorInputObserver() override = default;++++ void didProcessAllPendingKeyboardEvents() override++ {++ m_keyboardCallbacks.sendSuccess();++ }++++ void didProcessAllPendingMouseEvents() override++ {++ m_mouseCallbacks.sendSuccess();++ }++++ void addMouseCallback(Ref<MouseCallback>&& callback)++ {++ m_mouseCallbacks.append(WTFMove(callback));++ }++++ void addKeyboardCallback(Ref<KeyboardCallback>&& callback)++ {++ m_keyboardCallbacks.append(WTFMove(callback));++ }++++private:++ CallbackList<KeyboardCallback> m_keyboardCallbacks;++ CallbackList<MouseCallback> m_mouseCallbacks;++};++++WebPageInspectorInputAgent::WebPageInspectorInputAgent(Inspector::BackendDispatcher& backendDispatcher, WebPageProxy& page)++ : InspectorAgentBase("Input"_s)++ , m_backendDispatcher(InputBackendDispatcher::create(backendDispatcher, this))++ , m_page(page)++ , m_inputObserver(makeUnique<InspectorInputObserver>())++{++ m_page.setObserber(m_inputObserver.get());++}++++WebPageInspectorInputAgent::~WebPageInspectorInputAgent()++{++ m_page.setObserber(nullptr);++}++++void WebPageInspectorInputAgent::didCreateFrontendAndBackend(Inspector::FrontendRouter*, Inspector::BackendDispatcher*)++{++}++++void WebPageInspectorInputAgent::willDestroyFrontendAndBackend(Inspector::DisconnectReason)++{++}++++void WebPageInspectorInputAgent::dispatchKeyEvent(const String& in_type, const int* opt_in_modifiers, const String* opt_in_text, const String* opt_in_unmodifiedText, const String* opt_in_code, const String* opt_in_key, const int* opt_in_windowsVirtualKeyCode, const int* opt_in_nativeVirtualKeyCode, const bool* opt_in_autoRepeat, const bool* opt_in_isKeypad, const bool* opt_in_isSystemKey, Ref<Inspector::InputBackendDispatcherHandler::DispatchKeyEventCallback>&& callback)++{++ WebKit::WebEvent::Type type;++ if (in_type == "keyDown") {++ type = WebKit::WebEvent::KeyDown;++ } else if (in_type == "keyUp") {++ type = WebKit::WebEvent::KeyUp;++ } else {++ callback->sendFailure("Unsupported event type.");++ return;++ }++ OptionSet<WebEvent::Modifier> modifiers;++ if (opt_in_modifiers)++ modifiers = modifiers.fromRaw(*opt_in_modifiers);++ String text;++ if (opt_in_text)++ text = *opt_in_text;++ String unmodifiedText;++ if (opt_in_unmodifiedText)++ unmodifiedText = *opt_in_unmodifiedText;++ String code;++ if (opt_in_code)++ code = *opt_in_code;++ String key;++ if (opt_in_key)++ key = *opt_in_key;++ int windowsVirtualKeyCode = 0;++ if (opt_in_windowsVirtualKeyCode)++ windowsVirtualKeyCode = *opt_in_windowsVirtualKeyCode;++ int nativeVirtualKeyCode = 0;++ if (opt_in_nativeVirtualKeyCode)++ nativeVirtualKeyCode = *opt_in_nativeVirtualKeyCode;++ bool isAutoRepeat = false;++ if (opt_in_autoRepeat)++ isAutoRepeat = *opt_in_autoRepeat;++ bool isKeypad = false;++ if (opt_in_isKeypad)++ isKeypad = *opt_in_isKeypad;++ bool isSystemKey = false;++ if (opt_in_isSystemKey)++ isSystemKey = *opt_in_isSystemKey;++ WallTime timestamp = WallTime::now();++++ m_inputObserver->addKeyboardCallback(WTFMove(callback));++ platformDispatchKeyEvent(++ type,++ text,++ unmodifiedText,++ key,++ code,++ windowsVirtualKeyCode,++ nativeVirtualKeyCode,++ isAutoRepeat,++ isKeypad,++ isSystemKey,++ modifiers,++ timestamp);++}++++void WebPageInspectorInputAgent::dispatchMouseEvent(const String& in_type, int in_x, int in_y, const int* opt_in_modifiers, const String* opt_in_button, const int* opt_in_buttons, const int* opt_in_clickCount, const int* opt_in_deltaX, const int* opt_in_deltaY, Ref<DispatchMouseEventCallback>&& callback)++{++ WebEvent::Type type = WebEvent::NoType;++ if (in_type == "down")++ type = WebEvent::MouseDown;++ else if (in_type == "up")++ type = WebEvent::MouseUp;++ else if (in_type == "move")++ type = WebEvent::MouseMove;++ else {++ callback->sendFailure("Unsupported event type");++ return;++ }++++ OptionSet<WebEvent::Modifier> modifiers;++ if (opt_in_modifiers)++ modifiers = modifiers.fromRaw(*opt_in_modifiers);++++ WebMouseEvent::Button button = WebMouseEvent::NoButton;++ if (opt_in_button) {++ if (*opt_in_button == "left")++ button = WebMouseEvent::LeftButton;++ else if (*opt_in_button == "middle")++ button = WebMouseEvent::MiddleButton;++ else if (*opt_in_button == "right")++ button = WebMouseEvent::RightButton;++ else if (*opt_in_button == "none")++ button = WebMouseEvent::NoButton;++ else {++ callback->sendFailure("Unsupported button");++ return;++ }++ }++++ unsigned short buttons = 0;++ if (opt_in_buttons)++ buttons = *opt_in_buttons;++++ int clickCount = 0;++ if (opt_in_clickCount)++ clickCount = *opt_in_clickCount;++ int deltaX = 0;++ if (opt_in_deltaX)++ deltaX = *opt_in_deltaX;++ int deltaY = 0;++ if (opt_in_deltaY)++ deltaY = *opt_in_deltaY;++ m_inputObserver->addMouseCallback(WTFMove(callback));++#if PLATFORM(WPE)++ platformDispatchMouseEvent(type, in_x, in_y, button, modifiers);++#elif PLATFORM(GTK)++ WallTime timestamp = WallTime::now();++ NativeWebMouseEvent event(++ type,++ button,++ buttons,++ {in_x, in_y},++ WebCore::IntPoint(),++ deltaX,++ deltaY,++ 0,++ clickCount,++ modifiers,++ timestamp);++ m_page.handleMouseEvent(event);++#endif++}++++void WebPageInspectorInputAgent::goBack(Inspector::ErrorString&)++{++ auto navigation = m_page.goBack();++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/WebPageInspectorInputAgent.h b/Source/WebKit/UIProcess/WebPageInspectorInputAgent.h+new file mode 100644+index 00000000000..9d51a913b23+--- /dev/null++++ b/Source/WebKit/UIProcess/WebPageInspectorInputAgent.h+@@ -0,0 +1,76 @@++/*++ * Copyright (C) 2018 Apple Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY++ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE++ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR++ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,++ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,++ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR++ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY++ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#include "WebEvent.h"++++#include <JavaScriptCore/InspectorAgentBase.h>++#include <JavaScriptCore/InspectorBackendDispatchers.h>++++#include <wtf/Forward.h>++#include <wtf/Noncopyable.h>++++namespace Inspector {++class BackendDispatcher;++class FrontendChannel;++class FrontendRouter;++}++++namespace WebKit {++++class NativeWebKeyboardEvent;++class WebPageProxy;++++class WebPageInspectorInputAgent : public Inspector::InspectorAgentBase, public Inspector::InputBackendDispatcherHandler {++ WTF_MAKE_NONCOPYABLE(WebPageInspectorInputAgent);++ WTF_MAKE_FAST_ALLOCATED;++public:++ WebPageInspectorInputAgent(Inspector::BackendDispatcher& backendDispatcher, WebPageProxy& page);++ ~WebPageInspectorInputAgent() override;++++ void didCreateFrontendAndBackend(Inspector::FrontendRouter*, Inspector::BackendDispatcher*) override;++ void willDestroyFrontendAndBackend(Inspector::DisconnectReason) override;++++ void dispatchKeyEvent(const String& in_type, const int* opt_in_modifiers, const String* opt_in_text, const String* opt_in_unmodifiedText, const String* opt_in_code, const String* opt_in_key, const int* opt_in_windowsVirtualKeyCode, const int* opt_in_nativeVirtualKeyCode, const bool* opt_in_autoRepeat, const bool* opt_in_isKeypad, const bool* opt_in_isSystemKey, Ref<DispatchKeyEventCallback>&& callback) override;++ void dispatchMouseEvent(const String& in_type, int in_x, int in_y, const int* opt_in_modifiers, const String* opt_in_button, const int* opt_in_buttons, const int* opt_in_clickCount, const int* opt_in_deltaX, const int* opt_in_deltaY, Ref<DispatchMouseEventCallback>&& callback) override;++ void goBack(Inspector::ErrorString&) override;++++private:++ void platformDispatchKeyEvent(WebKeyboardEvent::Type type, const String& text, const String& unmodifiedText, const String& key, const String& code, int windowsVirtualKeyCode, int nativeVirtualKeyCode, bool isAutoRepeat, bool isKeypad, bool isSystemKey, OptionSet<WebEvent::Modifier> modifiers, WallTime timestamp);++#if PLATFORM(WPE)++ void platformDispatchMouseEvent(WebMouseEvent::Type type, int x, int y, WebMouseEvent::Button button, OptionSet<WebEvent::Modifier> modifiers);++#endif++++ Ref<Inspector::InputBackendDispatcher> m_backendDispatcher;++ WebPageProxy& m_page;++ // Keep track of currently active modifiers across multiple keystrokes.++ // Most platforms do not track current modifiers from synthesized events.++ unsigned m_currentModifiers { 0 };++ class InspectorInputObserver;++ std::unique_ptr<InspectorInputObserver> m_inputObserver;++};++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/WebPageInspectorTargetProxy.cpp b/Source/WebKit/UIProcess/WebPageInspectorTargetProxy.cpp+new file mode 100644+index 00000000000..a697c3f5355+--- /dev/null++++ b/Source/WebKit/UIProcess/WebPageInspectorTargetProxy.cpp+@@ -0,0 +1,129 @@++/*++ * Copyright (C) 2018 Apple Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY++ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE++ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR++ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,++ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,++ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR++ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY++ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorTargetProxy.h"++++#include "ProvisionalPageProxy.h"++#include "WebPageInspectorController.h"++#include "WebPageInspectorEmulationAgent.h"++#include "WebPageInspectorInputAgent.h"++#include "WebPageMessages.h"++#include "WebPageProxy.h"++#include "WebProcessProxy.h"++#include <JavaScriptCore/InspectorBackendDispatcher.h>++#include <JavaScriptCore/InspectorBackendDispatchers.h>++#include <JavaScriptCore/InspectorFrontendRouter.h>++#include <JavaScriptCore/InspectorTargetAgent.h>++++namespace WebKit {++++using namespace Inspector;++++namespace {++++class TargetFrontendChannel final : public FrontendChannel {++ WTF_MAKE_NONCOPYABLE(TargetFrontendChannel);++public:++ TargetFrontendChannel(InspectorTargetAgent& targetAgent, const String& targetId, FrontendChannel::ConnectionType type)++ : m_targetAgent(targetAgent)++ , m_targetId(targetId)++ , m_connectionType(type)++ {++ }++ ~TargetFrontendChannel() override = default;++++ ConnectionType connectionType() const override { return m_connectionType; }++ void sendMessageToFrontend(const String& message) override++ {++ m_targetAgent.sendMessageFromTargetToFrontend(m_targetId, message);++ }++++private:++ InspectorTargetAgent& m_targetAgent;++ String m_targetId;++ FrontendChannel::ConnectionType m_connectionType;++};++++} // namespace++++std::unique_ptr<WebPageInspectorTargetProxy> WebPageInspectorTargetProxy::create(WebPageProxy& page, Inspector::InspectorTargetAgent& targetAgent, const String& targetId)++{++ return makeUnique<WebPageInspectorTargetProxy>(page, nullptr, targetAgent, targetId);++}++++std::unique_ptr<WebPageInspectorTargetProxy> WebPageInspectorTargetProxy::create(ProvisionalPageProxy& provisionalPage, Inspector::InspectorTargetAgent& targetAgent, const String& targetId)++{++ return makeUnique<WebPageInspectorTargetProxy>(provisionalPage.page(), &provisionalPage, targetAgent, targetId);++}++++WebPageInspectorTargetProxy::WebPageInspectorTargetProxy(WebPageProxy& page, ProvisionalPageProxy* provisionalPage, Inspector::InspectorTargetAgent& targetAgent, const String& targetId)++ : InspectorTargetProxy(page, provisionalPage, targetId, Inspector::InspectorTargetType::Page)++ , m_frontendRouter(FrontendRouter::create())++ , m_backendDispatcher(BackendDispatcher::create(m_frontendRouter.copyRef()))++ , m_targetAgent(targetAgent)++{++ m_agents.append(std::make_unique<WebPageInspectorEmulationAgent>(m_backendDispatcher.get(), page));++ m_agents.append(std::make_unique<WebPageInspectorInputAgent>(m_backendDispatcher.get(), page));++}++++void WebPageInspectorTargetProxy::connect(Inspector::FrontendChannel::ConnectionType connectionType)++{++ InspectorTargetProxy::connect(connectionType);++ ASSERT(!m_frontendChannel);++ if (m_frontendChannel)++ return;++ m_frontendChannel = std::make_unique<TargetFrontendChannel>(m_targetAgent, identifier(), connectionType);++ m_frontendRouter->connectFrontend(*m_frontendChannel);++}++++void WebPageInspectorTargetProxy::disconnect()++{++ ASSERT(m_frontendChannel);++ m_frontendRouter->disconnectAllFrontends();++ m_frontendChannel.reset();++ InspectorTargetProxy::disconnect();++}++++void WebPageInspectorTargetProxy::sendMessageToTargetBackend(const String& message)++{++ if (m_backendDispatcher->dispatch(message, BackendDispatcher::Mode::ContinueIfDomainIsMissing) == BackendDispatcher::DispatchResult::Finished)++ return;++ if (m_page.inspectorController().dispatchMessageToTargetBackend(message))++ return;++ InspectorTargetProxy::sendMessageToTargetBackend(message);++}++++void WebPageInspectorTargetProxy::activate(String& error)++{++ platformActivate(error);++}++++void WebPageInspectorTargetProxy::close(String& error)++{++ m_page.closePage(false);++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/WebPageInspectorTargetProxy.h b/Source/WebKit/UIProcess/WebPageInspectorTargetProxy.h+new file mode 100644+index 00000000000..0550a3d8698+--- /dev/null++++ b/Source/WebKit/UIProcess/WebPageInspectorTargetProxy.h+@@ -0,0 +1,67 @@++/*++ * Copyright (C) 2018 Apple Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY++ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE++ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR++ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,++ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,++ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR++ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY++ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#include "InspectorTargetProxy.h"++#include <JavaScriptCore/InspectorAgentRegistry.h>++#include <wtf/Forward.h>++#include <wtf/Noncopyable.h>++++namespace Inspector {++class BackendDispatcher;++class InspectorTargetAgent;++}++++namespace WebKit {++++class WebPageProxy;++++class WebPageInspectorTargetProxy final : public InspectorTargetProxy {++ WTF_MAKE_FAST_ALLOCATED;++ WTF_MAKE_NONCOPYABLE(WebPageInspectorTargetProxy);++public:++ static std::unique_ptr<WebPageInspectorTargetProxy> create(WebPageProxy&, Inspector::InspectorTargetAgent&, const String& targetId);++ static std::unique_ptr<WebPageInspectorTargetProxy> create(ProvisionalPageProxy&, Inspector::InspectorTargetAgent&, const String& targetId);++ WebPageInspectorTargetProxy(WebPageProxy&, ProvisionalPageProxy*, Inspector::InspectorTargetAgent&, const String& targetId);++ ~WebPageInspectorTargetProxy() = default;++++ void connect(Inspector::FrontendChannel::ConnectionType) override;++ void disconnect() override;++ void sendMessageToTargetBackend(const String&) override;++ void activate(String& error) override;++ void close(String& error) override;++++private:++ void platformActivate(String& error) const;++++ Ref<Inspector::FrontendRouter> m_frontendRouter;++ Ref<Inspector::BackendDispatcher> m_backendDispatcher;++ Inspector::InspectorTargetAgent& m_targetAgent;++ Inspector::AgentRegistry m_agents;++ std::unique_ptr<Inspector::FrontendChannel> m_frontendChannel;++};++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/WebPageProxy.cpp b/Source/WebKit/UIProcess/WebPageProxy.cpp+index c6b66746b18..3bed21548da 100644+--- a/Source/WebKit/UIProcess/WebPageProxy.cpp++++ b/Source/WebKit/UIProcess/WebPageProxy.cpp+@@ -865,6 +865,7 @@ void WebPageProxy::finishAttachingToWebProcess(ProcessLaunchReason reason)+ m_pageLoadState.didSwapWebProcesses();+ if (reason != ProcessLaunchReason::InitialProcess)+ m_drawingArea->waitForBackingStoreUpdateOnNextPaint();++ m_inspectorController->didFinishAttachingToWebProcess();+ }++ void WebPageProxy::didAttachToRunningProcess()+@@ -1616,6 +1617,11 @@ void WebPageProxy::setControlledByAutomation(bool controlled)+ m_process->processPool().sendToNetworkingProcess(Messages::NetworkProcess::SetSessionIsControlledByAutomation(m_websiteDataStore->sessionID(), m_controlledByAutomation));+ }+++void WebPageProxy::setObserber(InputProcessingObserver* observer)++{++ m_inputProcessingObserver = observer;++}+++ void WebPageProxy::createInspectorTarget(const String& targetId, Inspector::InspectorTargetType type)+ {+ m_inspectorController->createInspectorTarget(targetId, type);+@@ -6509,6 +6515,8 @@ void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled)+ if (auto* automationSession = process().processPool().automationSession())+ automationSession->mouseEventsFlushedForPage(*this);+ pageClient().didFinishProcessingAllPendingMouseEvents();++ if (m_inputProcessingObserver)++ m_inputProcessingObserver->didProcessAllPendingMouseEvents();+ }++ break;+@@ -6535,7 +6543,6 @@ void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled)+ case WebEvent::RawKeyDown:+ case WebEvent::Char: {+ LOG(KeyHandling, "WebPageProxy::didReceiveEvent: %s (queue empty %d)", webKeyboardEventTypeString(type), m_keyEventQueue.isEmpty());+-+ MESSAGE_CHECK(m_process, !m_keyEventQueue.isEmpty());+ NativeWebKeyboardEvent event = m_keyEventQueue.takeFirst();++@@ -6550,7 +6557,6 @@ void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled)+ // The call to doneWithKeyEvent may close this WebPage.+ // Protect against this being destroyed.+ Ref<WebPageProxy> protect(*this);+-+ pageClient().doneWithKeyEvent(event, handled);+ if (!handled)+ m_uiClient->didNotHandleKeyEvent(this, event);+@@ -6559,6 +6565,8 @@ void WebPageProxy::didReceiveEvent(uint32_t opaqueType, bool handled)+ if (!canProcessMoreKeyEvents) {+ if (auto* automationSession = process().processPool().automationSession())+ automationSession->keyboardEventsFlushedForPage(*this);++ if (m_inputProcessingObserver)++ m_inputProcessingObserver->didProcessAllPendingKeyboardEvents();+ }+ break;+ }+diff --git a/Source/WebKit/UIProcess/WebPageProxy.h b/Source/WebKit/UIProcess/WebPageProxy.h+index b84fb9e0ef3..9357ec52c83 100644+--- a/Source/WebKit/UIProcess/WebPageProxy.h++++ b/Source/WebKit/UIProcess/WebPageProxy.h+@@ -534,6 +534,14 @@ public:++ void setPageLoadStateObserver(std::unique_ptr<PageLoadState::Observer>&&);+++ class InputProcessingObserver {++ public:++ virtual ~InputProcessingObserver() = default;++ virtual void didProcessAllPendingKeyboardEvents() = 0;++ virtual void didProcessAllPendingMouseEvents() = 0;++ };++ void setObserber(InputProcessingObserver*);+++ void initializeWebPage();+ void setDrawingArea(std::unique_ptr<DrawingAreaProxy>&&);++@@ -2569,6 +2577,7 @@ private:+ #if ENABLE(REMOTE_INSPECTOR)+ std::unique_ptr<WebPageDebuggable> m_inspectorDebuggable;+ #endif++ InputProcessingObserver* m_inputProcessingObserver { nullptr };++ Optional<SpellDocumentTag> m_spellDocumentTag;++diff --git a/Source/WebKit/UIProcess/glib/InspectorBrowserAgentClientGLib.cpp b/Source/WebKit/UIProcess/glib/InspectorBrowserAgentClientGLib.cpp+new file mode 100644+index 00000000000..665265973c3+--- /dev/null++++ b/Source/WebKit/UIProcess/glib/InspectorBrowserAgentClientGLib.cpp+@@ -0,0 +1,130 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "InspectorBrowserAgentClientGLib.h"++++#if ENABLE(REMOTE_INSPECTOR)++++#include "InspectorBrowserAgent.h"++#include "WebKitBrowserInspectorPrivate.h"++#include "WebKitWebContextPrivate.h"++#include "WebKitWebsiteDataManagerPrivate.h"++#include "WebKitWebViewPrivate.h"++#include "WebPageProxy.h"++#include <wtf/HashMap.h>++#include <wtf/RefPtr.h>++#include <wtf/text/StringView.h>++#include <wtf/text/WTFString.h>++++namespace WebKit {++++static Vector<WebPageProxy*> collectPages(Optional<PAL::SessionID> sessionID)++{++ Vector<WebPageProxy*> result;++ for (WebProcessPool* pool : WebProcessPool::allProcessPools()) {++ for (auto& process : pool->processes()) {++ for (auto* page : process->pages()) {++ if (!sessionID || page->sessionID() == sessionID)++ result.append(page);++ }++ }++ }++ return result;++}++++static void closeAllPages(Optional<PAL::SessionID> sessionID)++{++ Vector<WebPageProxy*> pages = collectPages(sessionID);++ for (auto* page : pages)++ page->closePage(false);++}++++InspectorBrowserAgentClientGlib::InspectorBrowserAgentClientGlib()++{++}++++RefPtr<WebPageProxy> InspectorBrowserAgentClientGlib::createPage(WTF::String& error, const WTF::String* browserContextID)++{++ WebKitWebContext* context = webkit_web_context_get_default();++ if (browserContextID != nullptr) {++ context = m_idToContext.get(*browserContextID);++ if (context == nullptr) {++ error = "Context with provided id not found";++ return nullptr;++ }++ }++ RefPtr<WebPageProxy> page = webkitBrowserInspectorCreateNewPageInContext(context);++ if (page == nullptr)++ error = "Failed to create new page in the context";++ return page;++}++++void InspectorBrowserAgentClientGlib::closeAllWindows()++{++ closeAllPages(Optional<PAL::SessionID>());++ m_idToContext.clear();++ // FIXME(yurys): call g_main_loop_quit() ?++}++++static PAL::SessionID sessionIDFromContext(WebKitWebContext* context)++{++ WebKitWebsiteDataManager* data_manager = webkit_web_context_get_website_data_manager(context);++ WebsiteDataStore& websiteDataStore = webkitWebsiteDataManagerGetDataStore(data_manager);++ return websiteDataStore.sessionID();++}++++void InspectorBrowserAgentClientGlib::createBrowserContext(WTF::String& error, WTF::String* browserContextID)++{++ GRefPtr<WebKitWebsiteDataManager> manager = adoptGRef(webkit_website_data_manager_new_ephemeral());++ GRefPtr<WebKitWebContext> context = adoptGRef(WEBKIT_WEB_CONTEXT(g_object_new(WEBKIT_TYPE_WEB_CONTEXT, "website-data-manager", manager.get(), "process-swap-on-cross-site-navigation-enabled", true, nullptr)));++ if (!context) {++ error = "Failed to create GLib ephemeral context";++ return;++ }++ PAL::SessionID sessionID = sessionIDFromContext(context.get());++ String id = InspectorBrowserAgent::toBrowserContextIDProtocolString(sessionID);++ m_idToContext.set(id, WTFMove(context));++ *browserContextID = id;++}++++void InspectorBrowserAgentClientGlib::deleteBrowserContext(WTF::String& error, const WTF::String& browserContextID)++{++ GRefPtr<WebKitWebContext> context = m_idToContext.take(browserContextID);++ if (context == nullptr) {++ error = "Context with provided id not found";++ return;++ }++ closeAllPages(sessionIDFromContext(context.get()));++}++++} // namespace WebKit++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/glib/InspectorBrowserAgentClientGLib.h b/Source/WebKit/UIProcess/glib/InspectorBrowserAgentClientGLib.h+new file mode 100644+index 00000000000..0fefb4c55b3+--- /dev/null++++ b/Source/WebKit/UIProcess/glib/InspectorBrowserAgentClientGLib.h+@@ -0,0 +1,63 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#if ENABLE(REMOTE_INSPECTOR)++++#include "InspectorBrowserAgentClient.h"++#include "WebKitWebContext.h"++#include <wtf/Forward.h>++#include <wtf/HashMap.h>++#include <wtf/glib/GRefPtr.h>++#include <wtf/text/StringHash.h>++++namespace WebKit {++++class InspectorBrowserAgentClientGlib : public InspectorBrowserAgentClient {++ WTF_MAKE_FAST_ALLOCATED;++public:++ InspectorBrowserAgentClientGlib();++ ~InspectorBrowserAgentClientGlib() override = default;++++ RefPtr<WebPageProxy> createPage(WTF::String& error, const WTF::String* browserContextID) override;++ void closeAllWindows() override;++ void createBrowserContext(WTF::String& error, WTF::String* browserContextID) override;++ void deleteBrowserContext(WTF::String& error, const WTF::String& browserContextID) override;++++private:++ WebKitWebContext* findContext(WTF::String& error, const WTF::String& browserContextID);++++ HashMap<String, GRefPtr<WebKitWebContext>> m_idToContext;++};++++} // namespace API++++#endif // ENABLE(REMOTE_INSPECTOR)+diff --git a/Source/WebKit/UIProcess/gtk/WebPageInspectorEmulationAgentGtk.cpp b/Source/WebKit/UIProcess/gtk/WebPageInspectorEmulationAgentGtk.cpp+new file mode 100644+index 00000000000..25df994c053+--- /dev/null++++ b/Source/WebKit/UIProcess/gtk/WebPageInspectorEmulationAgentGtk.cpp+@@ -0,0 +1,58 @@++/*++ * Copyright (C) 2010 Apple Inc. All rights reserved.++ * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''++ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,++ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS++ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR++ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF++ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS++ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN++ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)++ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF++ * THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorEmulationAgent.h"++++#include "WebPageProxy.h"++#include <gtk/gtk.h>++++namespace WebKit {++void WebPageInspectorEmulationAgent::platformSetSize(String& error, int width, int height)++{++ GtkWidget* viewWidget = m_page.viewWidget();++ GtkWidget* window = gtk_widget_get_toplevel(viewWidget);++ if (!window) {++ error = "Cannot find parent window";++ return;++ }++ if (!GTK_IS_WINDOW(window)) {++ error = "Toplevel is not a window";++ return;++ }++ GtkAllocation viewAllocation;++ gtk_widget_get_allocation(viewWidget, &viewAllocation);++++ GtkAllocation windowAllocation;++ gtk_widget_get_allocation(window, &windowAllocation);++++ width += windowAllocation.width - viewAllocation.width;++ height += windowAllocation.height - viewAllocation.height;++++ gtk_window_resize(GTK_WINDOW(window), width, height);++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/gtk/WebPageInspectorInputAgentGtk.cpp b/Source/WebKit/UIProcess/gtk/WebPageInspectorInputAgentGtk.cpp+new file mode 100644+index 00000000000..2427ea22acf+--- /dev/null++++ b/Source/WebKit/UIProcess/gtk/WebPageInspectorInputAgentGtk.cpp+@@ -0,0 +1,108 @@++/*++ * Copyright (C) 2010 Apple Inc. All rights reserved.++ * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''++ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,++ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS++ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR++ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF++ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS++ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN++ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)++ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF++ * THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorInputAgent.h"++++#include "KeyBindingTranslator.h"++#include "NativeWebKeyboardEvent.h"++#include "WebPageProxy.h"++#include <WebCore/PlatformKeyboardEvent.h>++++namespace WebKit {++++static Vector<String> commandsForKeyEvent(GdkEventType type, unsigned keyVal, unsigned state)++{++ ASSERT(type == GDK_KEY_PRESS || type == GDK_KEY_RELEASE);++++ GUniquePtr<GdkEvent> event(gdk_event_new(type));++ event->key.keyval = keyVal;++ event->key.time = GDK_CURRENT_TIME;++ event->key.state = state;++ // When synthesizing an event, an invalid hardware_keycode value can cause it to be badly processed by GTK+.++ GUniqueOutPtr<GdkKeymapKey> keys;++ int keysCount;++ if (gdk_keymap_get_entries_for_keyval(gdk_keymap_get_default(), keyVal, &keys.outPtr(), &keysCount) && keysCount)++ event->key.hardware_keycode = keys.get()[0].keycode;++ return KeyBindingTranslator().commandsForKeyEvent(&event->key);++}++++static unsigned modifiersToEventState(OptionSet<WebEvent::Modifier> modifiers)++{++ unsigned state = 0;++ if (modifiers.contains(WebEvent::Modifier::ControlKey))++ state |= GDK_CONTROL_MASK;++ if (modifiers.contains(WebEvent::Modifier::ShiftKey))++ state |= GDK_SHIFT_MASK;++ if (modifiers.contains(WebEvent::Modifier::AltKey))++ state |= GDK_META_MASK;++ if (modifiers.contains(WebEvent::Modifier::CapsLockKey))++ state |= GDK_LOCK_MASK;++ return state;++}++++void WebPageInspectorInputAgent::platformDispatchKeyEvent(WebKeyboardEvent::Type type, const String& text, const String& unmodifiedText, const String& key, const String& code, int windowsVirtualKeyCode, int nativeVirtualKeyCode, bool isAutoRepeat, bool isKeypad, bool isSystemKey, OptionSet<WebEvent::Modifier> modifiers, WallTime timestamp)++{++ Vector<String> commands;++ const guint keyVal = WebCore::PlatformKeyboardEvent::gdkKeyCodeForWindowsKeyCode(windowsVirtualKeyCode);++ String keyIdentifier;++ if (keyVal) {++ GdkEventType event = GDK_NOTHING;++ switch (type)++ {++ case WebKeyboardEvent::KeyDown:++ event = GDK_KEY_PRESS;++ break;++ case WebKeyboardEvent::KeyUp:++ event = GDK_KEY_RELEASE;++ break;++ default:++ fprintf(stderr, "Unsupported event type = %d\n", type);++ break;++ }++ unsigned state = modifiersToEventState(modifiers);++ commands = commandsForKeyEvent(event, keyVal, state);++ keyIdentifier = WebCore::PlatformKeyboardEvent::keyIdentifierForGdkKeyCode(keyVal);++ }++ NativeWebKeyboardEvent event(++ type,++ text,++ unmodifiedText,++ key,++ code,++ keyIdentifier,++ windowsVirtualKeyCode,++ nativeVirtualKeyCode,++ isAutoRepeat,++ isKeypad,++ isSystemKey,++ modifiers,++ timestamp,++ WTFMove(commands));++ m_page.handleKeyboardEvent(event);++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/gtk/WebPageInspectorTargetProxyGtk.cpp b/Source/WebKit/UIProcess/gtk/WebPageInspectorTargetProxyGtk.cpp+new file mode 100644+index 00000000000..b6981cae157+--- /dev/null++++ b/Source/WebKit/UIProcess/gtk/WebPageInspectorTargetProxyGtk.cpp+@@ -0,0 +1,45 @@++/*++ * Copyright (C) 2010 Apple Inc. All rights reserved.++ * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''++ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,++ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS++ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR++ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF++ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS++ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN++ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)++ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF++ * THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorTargetProxy.h"++++#include "WebPageProxy.h"++#include <WebCore/GtkUtilities.h>++#include <gtk/gtk.h>++++namespace WebKit {++++void WebPageInspectorTargetProxy::platformActivate(String& error) const++{++ GtkWidget* parent = gtk_widget_get_toplevel(m_page.viewWidget());++ if (WebCore::widgetIsOnscreenToplevelWindow(parent))++ gtk_window_present(GTK_WINDOW(parent));++ else++ error = "The view is not on screen";++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/ios/PageClientImplIOS.mm b/Source/WebKit/UIProcess/ios/PageClientImplIOS.mm+index e139968d4f0..98093c684db 100644+--- a/Source/WebKit/UIProcess/ios/PageClientImplIOS.mm++++ b/Source/WebKit/UIProcess/ios/PageClientImplIOS.mm+@@ -408,6 +408,8 @@ IntRect PageClientImpl::rootViewToAccessibilityScreen(const IntRect& rect)++ void PageClientImpl::doneWithKeyEvent(const NativeWebKeyboardEvent& event, bool eventWasHandled)+ {++ if (!event.nativeEvent())++ return;+ [m_contentView _didHandleKeyEvent:event.nativeEvent() eventWasHandled:eventWasHandled];+ }++diff --git a/Source/WebKit/UIProcess/mac/InspectorBrowserAgentClientMac.h b/Source/WebKit/UIProcess/mac/InspectorBrowserAgentClientMac.h+new file mode 100644+index 00000000000..719a0bb54d7+--- /dev/null++++ b/Source/WebKit/UIProcess/mac/InspectorBrowserAgentClientMac.h+@@ -0,0 +1,56 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#pragma once++++#include "InspectorBrowserAgentClient.h"++#include <wtf/Forward.h>++++OBJC_PROTOCOL(_WKBrowserInspectorDelegate);++++namespace WebKit {++++class InspectorBrowserAgentClientMac : public InspectorBrowserAgentClient {++ WTF_MAKE_FAST_ALLOCATED;++public:++ InspectorBrowserAgentClientMac(_WKBrowserInspectorDelegate* delegate);++ ~InspectorBrowserAgentClientMac() override = default;++++ RefPtr<WebPageProxy> createPage(WTF::String& error, const WTF::String* browserContextID) override;++ void closeAllWindows() override;++ void createBrowserContext(WTF::String& error, WTF::String* browserContextID) override;++ void deleteBrowserContext(WTF::String& error, const WTF::String& browserContextID) override;++ private:++++ _WKBrowserInspectorDelegate* delegate_;++};++++++} // namespace API+diff --git a/Source/WebKit/UIProcess/mac/InspectorBrowserAgentClientMac.mm b/Source/WebKit/UIProcess/mac/InspectorBrowserAgentClientMac.mm+new file mode 100644+index 00000000000..8426bd70ba9+--- /dev/null++++ b/Source/WebKit/UIProcess/mac/InspectorBrowserAgentClientMac.mm+@@ -0,0 +1,95 @@++/*++ * Copyright (C) 2019 Microsoft Corporation. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions are++ * met:++ *++ * * Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * * Redistributions in binary form must reproduce the above++ * copyright notice, this list of conditions and the following disclaimer++ * in the documentation and/or other materials provided with the++ * distribution.++ * * Neither the name of Microsoft Corporation nor the names of its++ * contributors may be used to endorse or promote products derived from++ * this software without specific prior written permission.++ *++ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS++ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT++ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR++ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT++ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,++ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT++ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,++ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY++ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT++ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE++ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.++ */++++#import "config.h"++#import "InspectorBrowserAgentClientMac.h"++++#import <wtf/RefPtr.h>++#import <wtf/text/WTFString.h>++#import "WebPageProxy.h"++#import "WebProcessPool.h"++#import "_WKBrowserInspector.h"++#import "WKWebView.h"++#import "WKWebViewInternal.h"++++namespace WebKit {++++/*++static Vector<WebPageProxy*> collectPages(Optional<PAL::SessionID> sessionID)++{++ Vector<WebPageProxy*> result;++ for (WebProcessPool* pool : WebProcessPool::allProcessPools()) {++ for (auto& process : pool->processes()) {++ for (auto* page : process->pages()) {++ if (!sessionID || page->sessionID() == sessionID)++ result.append(page);++ }++ }++ }++ return result;++}++++static void closeAllPages(Optional<PAL::SessionID> sessionID)++{++ Vector<WebPageProxy*> pages = collectPages(sessionID);++ for (auto* page : pages)++ page->closePage(false);++}++*/++++InspectorBrowserAgentClientMac::InspectorBrowserAgentClientMac(_WKBrowserInspectorDelegate* delegate)++ : delegate_(delegate)++{++}++++RefPtr<WebPageProxy> InspectorBrowserAgentClientMac::createPage(WTF::String& error, const WTF::String* browserContextID)++{++ WKWebView *webView = [delegate_ createNewPage];++ return [webView _page];++}++++void InspectorBrowserAgentClientMac::closeAllWindows()++{++ [delegate_ quit];++}++++void InspectorBrowserAgentClientMac::createBrowserContext(WTF::String& error, WTF::String* browserContextID)++{++ error = "Failed to create Mac ephemeral context";++ fprintf(stderr, "InspectorBrowserAgentClientMac::createBrowserContext - NOT IMPLEMENTED\n");++}++++void InspectorBrowserAgentClientMac::deleteBrowserContext(WTF::String& error, const WTF::String& browserContextID)++{++ error = "Context with provided id not found";++ fprintf(stderr, "InspectorBrowserAgentClientMac::deleteBrowserContext - NOT IMPLEMENTED\n");++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/mac/PageClientImplMac.mm b/Source/WebKit/UIProcess/mac/PageClientImplMac.mm+index 22653d74398..bf27558fdfd 100644+--- a/Source/WebKit/UIProcess/mac/PageClientImplMac.mm++++ b/Source/WebKit/UIProcess/mac/PageClientImplMac.mm+@@ -455,6 +455,8 @@ IntRect PageClientImpl::rootViewToAccessibilityScreen(const IntRect& rect)++ void PageClientImpl::doneWithKeyEvent(const NativeWebKeyboardEvent& event, bool eventWasHandled)+ {++ if (!event.nativeEvent())++ return;+ m_impl->doneWithKeyEvent(event.nativeEvent(), eventWasHandled);+ }++@@ -930,6 +932,9 @@ void PageClientImpl::didRestoreScrollPosition()++ bool PageClientImpl::windowIsFrontWindowUnderMouse(const NativeWebMouseEvent& event)+ {++ // Simulated event.++ if (!event.nativeEvent())++ return false;+ return m_impl->windowIsFrontWindowUnderMouse(event.nativeEvent());+ }++diff --git a/Source/WebKit/UIProcess/mac/WebPageInspectorEmulationAgentMac.mm b/Source/WebKit/UIProcess/mac/WebPageInspectorEmulationAgentMac.mm+new file mode 100644+index 00000000000..857195777b5+--- /dev/null++++ b/Source/WebKit/UIProcess/mac/WebPageInspectorEmulationAgentMac.mm+@@ -0,0 +1,42 @@++/*++ * Copyright (C) 2010 Apple Inc. All rights reserved.++ * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''++ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,++ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS++ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR++ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF++ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS++ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN++ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)++ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF++ * THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorEmulationAgent.h"++++#include "WebPageProxy.h"++++namespace WebKit {++void WebPageInspectorEmulationAgent::platformSetSize(String& error, int width, int height)++{++ NSWindow* window = m_page.platformWindow();++ NSRect frame = [window frame];++ frame.origin.y += frame.size.height;++ frame.origin.y -= height;++ frame.size = NSMakeSize(width, height);++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/mac/WebPageInspectorInputAgentMac.mm b/Source/WebKit/UIProcess/mac/WebPageInspectorInputAgentMac.mm+new file mode 100644+index 00000000000..0f09fd52ae1+--- /dev/null++++ b/Source/WebKit/UIProcess/mac/WebPageInspectorInputAgentMac.mm+@@ -0,0 +1,37 @@++/*++ * Copyright (C) 2010 Apple Inc. All rights reserved.++ * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''++ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,++ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS++ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR++ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF++ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS++ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN++ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)++ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF++ * THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorInputAgent.h"++++namespace WebKit {++++void WebPageInspectorInputAgent::platformDispatchKeyEvent(WebKeyboardEvent::Type type, const String& text, const String& unmodifiedText, const String& key, const String& code, int windowsVirtualKeyCode, int nativeVirtualKeyCode, bool isAutoRepeat, bool isKeypad, bool isSystemKey, OptionSet<WebEvent::Modifier> modifiers, WallTime timestamp)++{++ fprintf(stderr, "Mac does not support dispatching key events");++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/mac/WebPageInspectorTargetProxyMac.mm b/Source/WebKit/UIProcess/mac/WebPageInspectorTargetProxyMac.mm+new file mode 100644+index 00000000000..b0f0172a028+--- /dev/null++++ b/Source/WebKit/UIProcess/mac/WebPageInspectorTargetProxyMac.mm+@@ -0,0 +1,41 @@++/*++ * Copyright (C) 2010 Apple Inc. All rights reserved.++ * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''++ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,++ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS++ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR++ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF++ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS++ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN++ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)++ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF++ * THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorTargetProxy.h"++++#if PLATFORM(MAC)++++namespace WebKit {++++void WebPageInspectorTargetProxy::platformActivate(String& error) const++{++ error = "Not Implemented";++}++++} // namespace WebKit++++#endif+diff --git a/Source/WebKit/UIProcess/wpe/WebPageInspectorEmulationAgentWPE.cpp b/Source/WebKit/UIProcess/wpe/WebPageInspectorEmulationAgentWPE.cpp+new file mode 100644+index 00000000000..5465c0ae99d+--- /dev/null++++ b/Source/WebKit/UIProcess/wpe/WebPageInspectorEmulationAgentWPE.cpp+@@ -0,0 +1,41 @@++/*++ * Copyright (C) 2010 Apple Inc. All rights reserved.++ * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''++ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,++ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS++ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR++ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF++ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS++ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN++ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)++ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF++ * THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorEmulationAgent.h"++++#include "WebPageProxy.h"++#include <wpe/wpe.h>++++namespace WebKit {++++void WebPageInspectorEmulationAgent::platformSetSize(String& error, int width, int height)++{++ struct wpe_view_backend* backend = m_page.viewBackend();++ wpe_view_backend_dispatch_set_size(backend, width, height);++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/wpe/WebPageInspectorInputAgentWPE.cpp b/Source/WebKit/UIProcess/wpe/WebPageInspectorInputAgentWPE.cpp+new file mode 100644+index 00000000000..772ca6bc674+--- /dev/null++++ b/Source/WebKit/UIProcess/wpe/WebPageInspectorInputAgentWPE.cpp+@@ -0,0 +1,99 @@++/*++ * Copyright (C) 2010 Apple Inc. All rights reserved.++ * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''++ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,++ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS++ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR++ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF++ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS++ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN++ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)++ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF++ * THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorInputAgent.h"++++#include "NativeWebKeyboardEvent.h"++#include "WebPageProxy.h"++#include <WebCore/PlatformKeyboardEvent.h>++#include <wpe/wpe.h>++++namespace WebKit {++++void WebPageInspectorInputAgent::platformDispatchKeyEvent(String& error, const String& type, const String& keyRef)++{++}++++static unsigned toWPEButton(WebMouseEvent::Button button)++{++ switch (button) {++ case WebMouseEvent::NoButton:++ case WebMouseEvent::LeftButton:++ return 1;++ case WebMouseEvent::MiddleButton:++ return 3;++ case WebMouseEvent::RightButton:++ return 2;++ }++ return 1;++}++++static unsigned toWPEModifiers(OptionSet<WebEvent::Modifier> modifiers)++{++ unsigned result = 0;++ if (modifiers.contains(WebEvent::Modifier::ControlKey))++ result |= wpe_input_keyboard_modifier_control;++ if (modifiers.contains(WebEvent::Modifier::ShiftKey))++ result |= wpe_input_keyboard_modifier_shift;++ if (modifiers.contains(WebEvent::Modifier::AltKey))++ result |= wpe_input_keyboard_modifier_alt;++ if (modifiers.contains(WebEvent::Modifier::CapsLockKey))++ fprintf(stderr, "Unsupported modifier CapsLock will be ignored.\n");++ return result;++}++++void WebPageInspectorInputAgent::platformDispatchKeyEvent(WebKeyboardEvent::Type type, const String& text, const String& unmodifiedText, const String& key, const String& code, int windowsVirtualKeyCode, int nativeVirtualKeyCode, bool isAutoRepeat, bool isKeypad, bool isSystemKey, OptionSet<WebEvent::Modifier> modifiers, WallTime timestamp)++{++ unsigned keyCode = WebCore::PlatformKeyboardEvent::WPEKeyCodeForWindowsKeyCode(windowsVirtualKeyCode);++ struct wpe_input_xkb_keymap_entry* entries;++ uint32_t entriesCount;++ fprintf(stderr, "platformDispatchKeyEvent %s => %d\n", key.ascii().data(), keyCode);++ wpe_input_xkb_context_get_entries_for_key_code(wpe_input_xkb_context_get_default(), keyCode, &entries, &entriesCount);++ bool pressed = type == WebKeyboardEvent::KeyDown;++ struct wpe_input_keyboard_event event = { 0, keyCode, entriesCount ? entries[0].hardware_key_code : 0, pressed, toWPEModifiers(modifiers) };++ // event.time = timestamp.secondsSinceEpoch().milliseconds();++ wpe_view_backend_dispatch_keyboard_event(m_page.viewBackend(), &event);++ free(entries);++}++++void WebPageInspectorInputAgent::platformDispatchMouseEvent(WebMouseEvent::Type type, int x, int y, WebMouseEvent::Button button, OptionSet<WebEvent::Modifier> modifiers)++{++ wpe_input_pointer_event_type eventType = wpe_input_pointer_event_type_null;++ uint32_t eventButton = 0;++ uint32_t state = 0;++ if (type == WebEvent::MouseDown || type == WebEvent::MouseUp) {++ eventType = wpe_input_pointer_event_type_button;++ state = (type == WebEvent::MouseDown);++ eventButton = toWPEButton(button);++ } else if (type == WebEvent::MouseMove) {++ eventType = wpe_input_pointer_event_type_motion;++ }++ struct wpe_input_pointer_event event { eventType, 0, x, y, eventButton, state, toWPEModifiers(modifiers) };++ wpe_view_backend_dispatch_pointer_event(m_page.viewBackend(), &event);++}++++} // namespace WebKit+diff --git a/Source/WebKit/UIProcess/wpe/WebPageInspectorTargetProxyWPE.cpp b/Source/WebKit/UIProcess/wpe/WebPageInspectorTargetProxyWPE.cpp+new file mode 100644+index 00000000000..d64407d5822+--- /dev/null++++ b/Source/WebKit/UIProcess/wpe/WebPageInspectorTargetProxyWPE.cpp+@@ -0,0 +1,41 @@++/*++ * Copyright (C) 2010 Apple Inc. All rights reserved.++ * Portions Copyright (c) 2010 Motorola Mobility, Inc. All rights reserved.++ *++ * Redistribution and use in source and binary forms, with or without++ * modification, are permitted provided that the following conditions++ * are met:++ * 1. Redistributions of source code must retain the above copyright++ * notice, this list of conditions and the following disclaimer.++ * 2. Redistributions in binary form must reproduce the above copyright++ * notice, this list of conditions and the following disclaimer in the++ * documentation and/or other materials provided with the distribution.++ *++ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''++ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,++ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR++ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS++ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR++ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF++ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS++ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN++ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)++ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF++ * THE POSSIBILITY OF SUCH DAMAGE.++ */++++#include "config.h"++#include "WebPageInspectorTargetProxy.h"++++#include "WebPageProxy.h"++#include <wpe/wpe.h>++++namespace WebKit {++++void WebPageInspectorTargetProxy::platformActivate(String& error) const++{++ struct wpe_view_backend* backend = m_page.viewBackend();++ wpe_view_backend_add_activity_state(backend, wpe_view_activity_state_visible | wpe_view_activity_state_focused | wpe_view_activity_state_in_window);++}++++} // namespace WebKit+diff --git a/Source/WebKit/WebKit.xcodeproj/project.pbxproj b/Source/WebKit/WebKit.xcodeproj/project.pbxproj+index 21f3f6ad8cd..d0191b4cafd 100644+--- a/Source/WebKit/WebKit.xcodeproj/project.pbxproj++++ b/Source/WebKit/WebKit.xcodeproj/project.pbxproj+@@ -1663,6 +1663,19 @@+ CEE4AE2B1A5DCF430002F49B /* UIKitSPI.h in Headers */ = {isa = PBXBuildFile; fileRef = CEE4AE2A1A5DCF430002F49B /* UIKitSPI.h */; };+ D3B9484711FF4B6500032B39 /* WebPopupMenu.h in Headers */ = {isa = PBXBuildFile; fileRef = D3B9484311FF4B6500032B39 /* WebPopupMenu.h */; };+ D3B9484911FF4B6500032B39 /* WebSearchPopupMenu.h in Headers */ = {isa = PBXBuildFile; fileRef = D3B9484511FF4B6500032B39 /* WebSearchPopupMenu.h */; };++ D71A94322370E025002C4D9E /* InspectorBrowserAgentClientMac.h in Headers */ = {isa = PBXBuildFile; fileRef = D71A94302370E025002C4D9E /* InspectorBrowserAgentClientMac.h */; };++ D71A94342370E07A002C4D9E /* InspectorBrowserAgentClient.h in Headers */ = {isa = PBXBuildFile; fileRef = D71A94332370E07A002C4D9E /* InspectorBrowserAgentClient.h */; };++ D71A94382370F032002C4D9E /* BrowserInspectorController.h in Headers */ = {isa = PBXBuildFile; fileRef = D71A94372370F032002C4D9E /* BrowserInspectorController.h */; };++ D71A943A2370F061002C4D9E /* RemoteInspectorPipe.h in Headers */ = {isa = PBXBuildFile; fileRef = D71A94392370F060002C4D9E /* RemoteInspectorPipe.h */; };++ D71A94412371F67E002C4D9E /* WebPageInspectorTargetProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = D71A943E2371F67E002C4D9E /* WebPageInspectorTargetProxy.h */; };++ D71A94422371F67E002C4D9E /* WebPageInspectorEmulationAgent.h in Headers */ = {isa = PBXBuildFile; fileRef = D71A943F2371F67E002C4D9E /* WebPageInspectorEmulationAgent.h */; };++ D71A94432371F67E002C4D9E /* WebPageInspectorInputAgent.h in Headers */ = {isa = PBXBuildFile; fileRef = D71A94402371F67E002C4D9E /* WebPageInspectorInputAgent.h */; };++ D71A944A2372290B002C4D9E /* _WKBrowserInspector.h in Headers */ = {isa = PBXBuildFile; fileRef = D71A94492372290B002C4D9E /* _WKBrowserInspector.h */; settings = {ATTRIBUTES = (Private, ); }; };++ D71A944C237239FB002C4D9E /* BrowserInspectorPipe.h in Headers */ = {isa = PBXBuildFile; fileRef = D71A944B237239FB002C4D9E /* BrowserInspectorPipe.h */; };++ D79902B1236E9404005D6F7E /* WebPageInspectorEmulationAgentMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = D79902AE236E9404005D6F7E /* WebPageInspectorEmulationAgentMac.mm */; };++ D79902B2236E9404005D6F7E /* WebPageInspectorTargetProxyMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = D79902AF236E9404005D6F7E /* WebPageInspectorTargetProxyMac.mm */; };++ D79902B3236E9404005D6F7E /* WebPageInspectorInputAgentMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = D79902B0236E9404005D6F7E /* WebPageInspectorInputAgentMac.mm */; };++ D7EB04E72372A73B00F744CE /* InspectorBrowserAgentClientMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = D7EB04E62372A73B00F744CE /* InspectorBrowserAgentClientMac.mm */; };+ E105FE5418D7B9DE008F57A8 /* EditingRange.h in Headers */ = {isa = PBXBuildFile; fileRef = E105FE5318D7B9DE008F57A8 /* EditingRange.h */; };+ E11D35AE16B63D1B006D23D7 /* com.apple.WebProcess.sb in Resources */ = {isa = PBXBuildFile; fileRef = E1967E37150AB5E200C73169 /* com.apple.WebProcess.sb */; };+ E14A954A16E016A40068DE82 /* NetworkProcessPlatformStrategies.h in Headers */ = {isa = PBXBuildFile; fileRef = E14A954816E016A40068DE82 /* NetworkProcessPlatformStrategies.h */; };+@@ -4692,6 +4705,20 @@+ D3B9484311FF4B6500032B39 /* WebPopupMenu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebPopupMenu.h; sourceTree = "<group>"; };+ D3B9484411FF4B6500032B39 /* WebSearchPopupMenu.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WebSearchPopupMenu.cpp; sourceTree = "<group>"; };+ D3B9484511FF4B6500032B39 /* WebSearchPopupMenu.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebSearchPopupMenu.h; sourceTree = "<group>"; };++ D71A942C2370DF81002C4D9E /* WKBrowserInspector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WKBrowserInspector.h; sourceTree = "<group>"; };++ D71A94302370E025002C4D9E /* InspectorBrowserAgentClientMac.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorBrowserAgentClientMac.h; sourceTree = "<group>"; };++ D71A94332370E07A002C4D9E /* InspectorBrowserAgentClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InspectorBrowserAgentClient.h; sourceTree = "<group>"; };++ D71A94372370F032002C4D9E /* BrowserInspectorController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BrowserInspectorController.h; sourceTree = "<group>"; };++ D71A94392370F060002C4D9E /* RemoteInspectorPipe.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RemoteInspectorPipe.h; sourceTree = "<group>"; };++ D71A943E2371F67E002C4D9E /* WebPageInspectorTargetProxy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebPageInspectorTargetProxy.h; sourceTree = "<group>"; };++ D71A943F2371F67E002C4D9E /* WebPageInspectorEmulationAgent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebPageInspectorEmulationAgent.h; sourceTree = "<group>"; };++ D71A94402371F67E002C4D9E /* WebPageInspectorInputAgent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebPageInspectorInputAgent.h; sourceTree = "<group>"; };++ D71A94492372290B002C4D9E /* _WKBrowserInspector.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = _WKBrowserInspector.h; sourceTree = "<group>"; };++ D71A944B237239FB002C4D9E /* BrowserInspectorPipe.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BrowserInspectorPipe.h; sourceTree = "<group>"; };++ D79902AE236E9404005D6F7E /* WebPageInspectorEmulationAgentMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WebPageInspectorEmulationAgentMac.mm; sourceTree = "<group>"; };++ D79902AF236E9404005D6F7E /* WebPageInspectorTargetProxyMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WebPageInspectorTargetProxyMac.mm; sourceTree = "<group>"; };++ D79902B0236E9404005D6F7E /* WebPageInspectorInputAgentMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WebPageInspectorInputAgentMac.mm; sourceTree = "<group>"; };++ D7EB04E62372A73B00F744CE /* InspectorBrowserAgentClientMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = InspectorBrowserAgentClientMac.mm; sourceTree = "<group>"; };+ DF58C6311371AC5800F9A37C /* NativeWebWheelEvent.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NativeWebWheelEvent.h; sourceTree = "<group>"; };+ DF58C6351371ACA000F9A37C /* NativeWebWheelEventMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = NativeWebWheelEventMac.mm; sourceTree = "<group>"; };+ E105FE5318D7B9DE008F57A8 /* EditingRange.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EditingRange.h; sourceTree = "<group>"; };+@@ -6294,6 +6321,7 @@+ 37C4C08318149C2A003688B9 /* Cocoa */ = {+ isa = PBXGroup;+ children = (++ D71A94492372290B002C4D9E /* _WKBrowserInspector.h */,+ 1A43E826188F38E2009E4D30 /* Deprecated */,+ 37A5E01218BBF937000A081E /* _WKActivatedElementInfo.h */,+ 37A5E01118BBF937000A081E /* _WKActivatedElementInfo.mm */,+@@ -7774,6 +7802,13 @@+ BC032DC310F438260058C15A /* UIProcess */ = {+ isa = PBXGroup;+ children = (++ D71A944B237239FB002C4D9E /* BrowserInspectorPipe.h */,++ D71A943F2371F67E002C4D9E /* WebPageInspectorEmulationAgent.h */,++ D71A94402371F67E002C4D9E /* WebPageInspectorInputAgent.h */,++ D71A943E2371F67E002C4D9E /* WebPageInspectorTargetProxy.h */,++ D71A94392370F060002C4D9E /* RemoteInspectorPipe.h */,++ D71A94372370F032002C4D9E /* BrowserInspectorController.h */,++ D71A94332370E07A002C4D9E /* InspectorBrowserAgentClient.h */,+ BC032DC410F4387C0058C15A /* API */,+ 512F588D12A8836F00629530 /* Authentication */,+ 9955A6E81C79809000EB6A93 /* Automation */,+@@ -8051,6 +8086,7 @@+ BC0C376610F807660076D7CB /* C */ = {+ isa = PBXGroup;+ children = (++ D71A942C2370DF81002C4D9E /* WKBrowserInspector.h */,+ 5123CF18133D25E60056F800 /* cg */,+ 6EE849C41368D9040038D481 /* mac */,+ BCB63477116BF10600603215 /* WebKit2_C.h */,+@@ -8646,6 +8682,11 @@+ BCCF085C113F3B7500C650C5 /* mac */ = {+ isa = PBXGroup;+ children = (++ D7EB04E62372A73B00F744CE /* InspectorBrowserAgentClientMac.mm */,++ D71A94302370E025002C4D9E /* InspectorBrowserAgentClientMac.h */,++ D79902AE236E9404005D6F7E /* WebPageInspectorEmulationAgentMac.mm */,++ D79902B0236E9404005D6F7E /* WebPageInspectorInputAgentMac.mm */,++ D79902AF236E9404005D6F7E /* WebPageInspectorTargetProxyMac.mm */,+ B878B613133428DC006888E9 /* CorrectionPanel.h */,+ B878B614133428DC006888E9 /* CorrectionPanel.mm */,+ C1817362205844A900DFDA65 /* DisplayLink.cpp */,+@@ -9323,6 +9364,7 @@+ 510F59101DDE296900412FF5 /* _WKIconLoadingDelegate.h in Headers */,+ 37A64E5518F38E3C00EB30F1 /* _WKInputDelegate.h in Headers */,+ 5CAFDE452130846300B1F7E1 /* _WKInspector.h in Headers */,++ D71A944A2372290B002C4D9E /* _WKBrowserInspector.h in Headers */,+ 5CAFDE472130846A00B1F7E1 /* _WKInspectorInternal.h in Headers */,+ A5C0F0AB2000658200536536 /* _WKInspectorWindow.h in Headers */,+ 31B362952141EBCD007BFA53 /* _WKInternalDebugFeature.h in Headers */,+@@ -9434,6 +9476,7 @@+ 7C89D2981A6753B2003A5FDE /* APIPageConfiguration.h in Headers */,+ 1AC1336C18565C7A00F3EC05 /* APIPageHandle.h in Headers */,+ 1AFDD3151891B54000153970 /* APIPolicyClient.h in Headers */,++ D71A94382370F032002C4D9E /* BrowserInspectorController.h in Headers */,+ 7CE4D2201A4914CA00C7F152 /* APIProcessPoolConfiguration.h in Headers */,+ F634445612A885C8000612D8 /* APISecurityOrigin.h in Headers */,+ 1AFDE6621954E9B100C48FFA /* APISessionState.h in Headers */,+@@ -9552,6 +9595,7 @@+ BC06F43A12DBCCFB002D78DE /* GeolocationPermissionRequestProxy.h in Headers */,+ 2DA944A41884E4F000ED86DB /* GestureTypes.h in Headers */,+ 2DA049B8180CCD0A00AAFA9E /* GraphicsLayerCARemote.h in Headers */,++ D71A94342370E07A002C4D9E /* InspectorBrowserAgentClient.h in Headers */,+ C0CE72AD1247E78D00BC0EC4 /* HandleMessage.h in Headers */,+ 1AC75A1B1B3368270056745B /* HangDetectionDisabler.h in Headers */,+ 57AC8F50217FEED90055438C /* HidConnection.h in Headers */,+@@ -9675,8 +9719,10 @@+ 41DC45961E3D6E2200B11F51 /* NetworkRTCProvider.h in Headers */,+ 413075AB1DE85F330039EC69 /* NetworkRTCSocket.h in Headers */,+ 5C20CBA01BB1ECD800895BB1 /* NetworkSession.h in Headers */,++ D71A94422371F67E002C4D9E /* WebPageInspectorEmulationAgent.h in Headers */,+ 532159551DBAE7290054AA3C /* NetworkSessionCocoa.h in Headers */,+ 417915B92257046F00D6F97E /* NetworkSocketChannel.h in Headers */,++ D71A943A2370F061002C4D9E /* RemoteInspectorPipe.h in Headers */,+ 570DAAC22303730300E8FC04 /* NfcConnection.h in Headers */,+ 570DAAAE23026F5C00E8FC04 /* NfcService.h in Headers */,+ 31A2EC5614899C0900810D71 /* NotificationPermissionRequest.h in Headers */,+@@ -9758,6 +9804,7 @@+ CD2865EE2255562000606AC7 /* ProcessTaskStateObserver.h in Headers */,+ 463FD4821EB94EC000A2982C /* ProcessTerminationReason.h in Headers */,+ 86E67A251910B9D100004AB7 /* ProcessThrottler.h in Headers */,++ D71A944C237239FB002C4D9E /* BrowserInspectorPipe.h in Headers */,+ 83048AE61ACA45DC0082C832 /* ProcessThrottlerClient.h in Headers */,+ A1E688701F6E2BAB007006A6 /* QuarantineSPI.h in Headers */,+ 57FD318222B3515E008D0E8B /* RedirectSOAuthorizationSession.h in Headers */,+@@ -9920,6 +9967,7 @@+ F430E94422473DFF005FE053 /* WebContentMode.h in Headers */,+ 31A505FA1680025500A930EB /* WebContextClient.h in Headers */,+ BC09B8F9147460F7005F5625 /* WebContextConnectionClient.h in Headers */,++ D71A94412371F67E002C4D9E /* WebPageInspectorTargetProxy.h in Headers */,+ BCDE059B11CDA8AE00E41AF1 /* WebContextInjectedBundleClient.h in Headers */,+ 51871B5C127CB89D00F76232 /* WebContextMenu.h in Headers */,+ BC032D7710F4378D0058C15A /* WebContextMenuClient.h in Headers */,+@@ -10153,6 +10201,7 @@+ BCD25F1711D6BDE100169B0E /* WKBundleFrame.h in Headers */,+ BCF049E611FE20F600F86A58 /* WKBundleFramePrivate.h in Headers */,+ BC49862F124D18C100D834E1 /* WKBundleHitTestResult.h in Headers */,++ D71A94432371F67E002C4D9E /* WebPageInspectorInputAgent.h in Headers */,+ BC204EF211C83EC8008F3375 /* WKBundleInitialize.h in Headers */,+ 65B86F1E12F11DE300B7DD8A /* WKBundleInspector.h in Headers */,+ 1A8B66B41BC45B010082DF77 /* WKBundleMac.h in Headers */,+@@ -10346,6 +10395,7 @@+ 1AB8A1F818400BB800E9AE69 /* WKPageContextMenuClient.h in Headers */,+ 8372DB251A674C8F00C697C5 /* WKPageDiagnosticLoggingClient.h in Headers */,+ 1AB8A1F418400B8F00E9AE69 /* WKPageFindClient.h in Headers */,++ D71A94322370E025002C4D9E /* InspectorBrowserAgentClientMac.h in Headers */,+ 1AB8A1F618400B9D00E9AE69 /* WKPageFindMatchesClient.h in Headers */,+ 1AB8A1F018400B0000E9AE69 /* WKPageFormClient.h in Headers */,+ BC7B633712A45ABA00D174A4 /* WKPageGroup.h in Headers */,+@@ -11302,6 +11352,7 @@+ 2D92A781212B6A7100F493FD /* MessageReceiverMap.cpp in Sources */,+ 2D92A782212B6A7100F493FD /* MessageSender.cpp in Sources */,+ 2D92A77A212B6A6100F493FD /* Module.cpp in Sources */,++ D79902B1236E9404005D6F7E /* WebPageInspectorEmulationAgentMac.mm in Sources */,+ 57B826452304F14000B72EB0 /* NearFieldSoftLink.mm in Sources */,+ 2D913443212CF9F000128AFD /* NetscapeBrowserFuncs.cpp in Sources */,+ 2D913444212CF9F000128AFD /* NetscapePlugin.cpp in Sources */,+@@ -11326,6 +11377,7 @@+ 1A2D8439127F65D5001EB962 /* NPObjectMessageReceiverMessageReceiver.cpp in Sources */,+ 2D92A792212B6AD400F493FD /* NPObjectProxy.cpp in Sources */,+ 2D92A793212B6AD400F493FD /* NPRemoteObjectMap.cpp in Sources */,++ D7EB04E72372A73B00F744CE /* InspectorBrowserAgentClientMac.mm in Sources */,+ 2D913447212CF9F000128AFD /* NPRuntimeObjectMap.cpp in Sources */,+ 2D913448212CF9F000128AFD /* NPRuntimeUtilities.cpp in Sources */,+ 2D92A794212B6AD400F493FD /* NPVariantData.cpp in Sources */,+@@ -11365,11 +11417,13 @@+ A1ADAFB62368E6A8009CB776 /* SharedMemory.cpp in Sources */,+ 2DE6943D18BD2A68005C15E5 /* SmartMagnificationControllerMessageReceiver.cpp in Sources */,+ 1A334DED16DE8F88006A8E38 /* StorageAreaMapMessageReceiver.cpp in Sources */,++ D79902B3236E9404005D6F7E /* WebPageInspectorInputAgentMac.mm in Sources */,+ 9368EEDE2303A90200BDB11A /* StorageManagerSetMessageReceiver.cpp in Sources */,+ 2D92A783212B6A7100F493FD /* StringReference.cpp in Sources */,+ 2D11B7512126A282006F8878 /* UnifiedSource1-mm.mm in Sources */,+ 2D11B7522126A282006F8878 /* UnifiedSource1.cpp in Sources */,+ 2D11B7542126A282006F8878 /* UnifiedSource2.cpp in Sources */,++ D79902B2236E9404005D6F7E /* WebPageInspectorTargetProxyMac.mm in Sources */,+ 2D11B7532126A282006F8878 /* UnifiedSource2-mm.mm in Sources */,+ 2D11B7562126A282006F8878 /* UnifiedSource3.cpp in Sources */,+ 2D11B7552126A282006F8878 /* UnifiedSource3-mm.mm in Sources */,+diff --git a/Source/WebKit/WebProcess/WebPage/WebPageInspectorTarget.cpp b/Source/WebKit/WebProcess/WebPage/WebPageInspectorTarget.cpp+index a70f6fd5209..f02e5c774a4 100644+--- a/Source/WebKit/WebProcess/WebPage/WebPageInspectorTarget.cpp++++ b/Source/WebKit/WebProcess/WebPage/WebPageInspectorTarget.cpp+@@ -26,6 +26,8 @@+ #include "config.h"+ #include "WebPageInspectorTarget.h"+++#include "FrameInfoData.h"++#include "WebFrame.h"+ #include "WebPage.h"+ #include "WebPageInspectorTargetFrontendChannel.h"+ #include <WebCore/InspectorController.h>+@@ -45,6 +47,11 @@ String WebPageInspectorTarget::identifier() const+ return toTargetID(m_page.identifier());+ }+++String WebPageInspectorTarget::url() const++{++ return m_page.mainWebFrame()->info().request.url().string();++}+++ void WebPageInspectorTarget::connect(Inspector::FrontendChannel::ConnectionType connectionType)+ {+ if (m_channel)+diff --git a/Source/WebKit/WebProcess/WebPage/WebPageInspectorTarget.h b/Source/WebKit/WebProcess/WebPage/WebPageInspectorTarget.h+index 6cbd7fad5ff..176c46f186b 100644+--- a/Source/WebKit/WebProcess/WebPage/WebPageInspectorTarget.h++++ b/Source/WebKit/WebProcess/WebPage/WebPageInspectorTarget.h+@@ -44,6 +44,7 @@ public:+ Inspector::InspectorTargetType type() const final { return Inspector::InspectorTargetType::Page; }++ String identifier() const final;++ String url() const final;++ void connect(Inspector::FrontendChannel::ConnectionType) override;+ void disconnect() override;+diff --git a/Source/WebKit/WebProcess/WebProcess.cpp b/Source/WebKit/WebProcess/WebProcess.cpp+index 6c16fa01df1..2b79bf41601 100644+--- a/Source/WebKit/WebProcess/WebProcess.cpp++++ b/Source/WebKit/WebProcess/WebProcess.cpp+@@ -625,7 +625,8 @@ void WebProcess::setCacheModel(CacheModel cacheModel)+ unsigned cacheMaxDeadCapacity = 0;+ Seconds deadDecodedDataDeletionInterval;+ unsigned backForwardCacheSize = 0;+- calculateMemoryCacheSizes(cacheModel, cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval, backForwardCacheSize);++ // FIXME(yurys): forcefully disable cache becaus it swallows Runtime.executionContextCreated events on goBack navigation.++ // calculateMemoryCacheSizes(cacheModel, cacheTotalCapacity, cacheMinDeadCapacity, cacheMaxDeadCapacity, deadDecodedDataDeletionInterval, backForwardCacheSize);++ auto& memoryCache = MemoryCache::singleton();+ memoryCache.setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);+diff --git a/Tools/MiniBrowser/gtk/main.c b/Tools/MiniBrowser/gtk/main.c+index 93d93592bc4..6e27ef37742 100644+--- a/Tools/MiniBrowser/gtk/main.c++++ b/Tools/MiniBrowser/gtk/main.c+@@ -53,6 +53,7 @@ static const char *cookiesFile;+ static const char *cookiesPolicy;+ static const char *proxy;+ static gboolean darkMode;++static gboolean inspectorPipe;+ static gboolean printVersion;++ typedef enum {+@@ -121,6 +122,7 @@ static const GOptionEntry commandLineOptions[] =+ { "ignore-tls-errors", 0, 0, G_OPTION_ARG_NONE, &ignoreTLSErrors, "Ignore TLS errors", NULL },+ { "content-filter", 0, 0, G_OPTION_ARG_FILENAME, &contentFilter, "JSON with content filtering rules", "FILE" },+ { "version", 'v', 0, G_OPTION_ARG_NONE, &printVersion, "Print the WebKitGTK version", NULL },++ { "inspector-pipe", 0, 0, G_OPTION_ARG_NONE, &inspectorPipe, "Open pipe connection to the remote inspector", NULL },+ { G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &uriArguments, 0, "[URL…]" },+ { 0, 0, 0, 0, 0, 0, 0 }+ };+@@ -492,6 +494,29 @@ static void filterSavedCallback(WebKitUserContentFilterStore *store, GAsyncResul+ g_main_loop_quit(data->mainLoop);+ }+++static WebKitWebView *createNewPage(WebKitBrowserInspector *browser_inspector, WebKitWebContext *context)++{++ WebKitWebView *newWebView = WEBKIT_WEB_VIEW(g_object_new(WEBKIT_TYPE_WEB_VIEW,++ "web-context", context,++ "is-ephemeral", webkit_web_context_is_ephemeral(context),++ "is-controlled-by-automation", TRUE,++ NULL));++ GtkWidget *newWindow = browser_window_new(NULL, context);++ browser_window_append_view(BROWSER_WINDOW(newWindow), newWebView);++ gtk_widget_grab_focus(GTK_WIDGET(newWebView));++ gtk_widget_show(GTK_WIDGET(newWindow));++ webkit_web_view_load_uri(newWebView, "about:blank");++ return newWebView;++}++++static void configureBrowserInspectorPipe()++{++ WebKitBrowserInspector* browserInspector = webkit_browser_inspector_get_default();++ g_signal_connect(browserInspector, "create-new-page", G_CALLBACK(createNewPage), NULL);++++ webkit_browser_inspector_initialize_pipe();++}+++ int main(int argc, char *argv[])+ {+ #if ENABLE_DEVELOPER_MODE+@@ -539,6 +564,9 @@ int main(int argc, char *argv[])+ WebKitWebContext *webContext = g_object_new(WEBKIT_TYPE_WEB_CONTEXT, "website-data-manager", manager, "process-swap-on-cross-site-navigation-enabled", TRUE, NULL);+ g_object_unref(manager);+++ if (inspectorPipe)++ configureBrowserInspectorPipe();+++ if (cookiesPolicy) {+ WebKitCookieManager *cookieManager = webkit_web_context_get_cookie_manager(webContext);+ GEnumClass *enumClass = g_type_class_ref(WEBKIT_TYPE_COOKIE_ACCEPT_POLICY);+diff --git a/Tools/MiniBrowser/mac/AppDelegate.h b/Tools/MiniBrowser/mac/AppDelegate.h+index 45ef1a6424e..928486be325 100644+--- a/Tools/MiniBrowser/mac/AppDelegate.h++++ b/Tools/MiniBrowser/mac/AppDelegate.h+@@ -23,9 +23,11 @@+ * THE POSSIBILITY OF SUCH DAMAGE.+ */+++#import <WebKit/_WKBrowserInspector.h>+++ @class ExtensionManagerWindowController;++-@interface BrowserAppDelegate : NSObject <NSApplicationDelegate> {++@interface BrowserAppDelegate : NSObject <NSApplicationDelegate, _WKBrowserInspectorDelegate> {+ NSMutableSet *_browserWindowControllers;+ ExtensionManagerWindowController *_extensionManagerWindowController;++diff --git a/Tools/MiniBrowser/mac/AppDelegate.m b/Tools/MiniBrowser/mac/AppDelegate.m+index b6af4ef724f..46c39768156 100644+--- a/Tools/MiniBrowser/mac/AppDelegate.m++++ b/Tools/MiniBrowser/mac/AppDelegate.m+@@ -61,7 +61,9 @@ - (id)init+ _browserWindowControllers = [[NSMutableSet alloc] init];+ _extensionManagerWindowController = [[ExtensionManagerWindowController alloc] init];+ }+-++ NSArray *arguments = [[NSProcessInfo processInfo] arguments];++ if ([arguments containsObject: @"--inspector-pipe"])++ [_WKBrowserInspector initializeRemoteInspectorPipe:self];+ return self;+ }++@@ -158,9 +160,9 @@ - (BrowserWindowController *)createBrowserWindowController:(id)sender+ }++ if (!useWebKit2)+- controller = [[WK1BrowserWindowController alloc] initWithWindowNibName:@"BrowserWindow"];++ controller = [[[WK1BrowserWindowController alloc] initWithWindowNibName:@"BrowserWindow"] autorelease];+ else+- controller = [[WK2BrowserWindowController alloc] initWithConfiguration:defaultConfiguration()];++ controller = [[[WK2BrowserWindowController alloc] initWithConfiguration:defaultConfiguration()] autorelease];++ if (makeEditable)+ controller.editable = YES;+@@ -345,4 +347,21 @@ - (IBAction)clearDefaultStoreWebsiteData:(id)sender+ }];+ }+++#pragma mark WKBrowserInspectorDelegate++++- (WKWebView *)createNewPage++{++ WK2BrowserWindowController *controller = [[[WK2BrowserWindowController alloc] initWithConfiguration:defaultConfiguration()] autorelease];++ [_browserWindowControllers addObject:controller];++++ [[controller window] makeKeyAndOrderFront:self];++ [controller loadURLString:[SettingsController shared].defaultURL];++ return [controller webView];++}++++- (void)quit++{++ [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0.0];++}+++ @end+diff --git a/Tools/MiniBrowser/mac/WK2BrowserWindowController.h b/Tools/MiniBrowser/mac/WK2BrowserWindowController.h+index 6f0949b0f4a..e774433031a 100644+--- a/Tools/MiniBrowser/mac/WK2BrowserWindowController.h++++ b/Tools/MiniBrowser/mac/WK2BrowserWindowController.h+@@ -25,8 +25,11 @@++ #import "BrowserWindowController.h"+++@class WKWebView;+++ @interface WK2BrowserWindowController : BrowserWindowController++ - (instancetype)initWithConfiguration:(WKWebViewConfiguration *)configuration;++- (WKWebView *)webView;++ @end+diff --git a/Tools/MiniBrowser/mac/WK2BrowserWindowController.m b/Tools/MiniBrowser/mac/WK2BrowserWindowController.m+index 3ca15403d5f..5905526473d 100644+--- a/Tools/MiniBrowser/mac/WK2BrowserWindowController.m++++ b/Tools/MiniBrowser/mac/WK2BrowserWindowController.m+@@ -105,7 +105,7 @@ - (void)awakeFromNib+ // telling WebKit to load every icon referenced by the page.+ if ([[SettingsController shared] loadsAllSiteIcons])+ _webView._iconLoadingDelegate = self;+-+++ _webView._observedRenderingProgressEvents = _WKRenderingProgressEventFirstLayout+ | _WKRenderingProgressEventFirstVisuallyNonEmptyLayout+ | _WKRenderingProgressEventFirstPaintWithSignificantArea+@@ -139,14 +139,10 @@ - (instancetype)initWithConfiguration:(WKWebViewConfiguration *)configuration++ - (void)dealloc+ {+- [_webView removeObserver:self forKeyPath:@"title"];+- [_webView removeObserver:self forKeyPath:@"URL"];+-+ [progressIndicator unbind:NSHiddenBinding];+ [progressIndicator unbind:NSValueBinding];++ [_textFinder release];+-+ [_webView release];+ [_configuration release];++@@ -369,9 +365,15 @@ - (BOOL)windowShouldClose:(id)sender+ - (void)windowWillClose:(NSNotification *)notification+ {+ [(BrowserAppDelegate *)[[NSApplication sharedApplication] delegate] browserWindowWillClose:self.window];++ [_webView removeObserver:self forKeyPath:@"title"];++ [_webView removeObserver:self forKeyPath:@"URL"];+ [self autorelease];+ }+++- (void)webViewDidClose:(WKWebView *)webView {++ [self.window close];++}+++ #define DefaultMinimumZoomFactor (.5)+ #define DefaultMaximumZoomFactor (3.0)+ #define DefaultZoomFactorRatio (1.2)+@@ -845,4 +847,9 @@ - (IBAction)saveAsWebArchive:(id)sender+ }];+ }+++- (WKWebView *)webView++{++ return _webView;++}+++ @end+diff --git a/Tools/MiniBrowser/wpe/main.cpp b/Tools/MiniBrowser/wpe/main.cpp+index 2d183d39412..d94d4f06fc5 100644+--- a/Tools/MiniBrowser/wpe/main.cpp++++ b/Tools/MiniBrowser/wpe/main.cpp+@@ -172,6 +172,41 @@ static WebKitWebView* createWebView(WebKitWebView* webView, WebKitNavigationActi+ return newWebView;+ }+++static WebKitWebView *createNewPage(WebKitBrowserInspector*, WebKitWebContext *context)++{++ auto backend = createViewBackend(1280, 720);++ struct wpe_view_backend* wpeBackend = backend->backend();++ if (!wpeBackend)++ return nullptr;++++ auto* viewBackend = webkit_web_view_backend_new(wpeBackend,++ [](gpointer data) {++ delete static_cast<WPEToolingBackends::ViewBackend*>(data);++ }, backend.release());++++ auto* newWebView = webkit_web_view_new_with_context(viewBackend, context);++++ g_signal_connect(newWebView, "close", G_CALLBACK(webViewClose), nullptr);++++ webkit_web_view_load_uri(newWebView, "about:blank");++++ return newWebView;++++}++++static void closeAll(WebKitBrowserInspector*, GMainLoop* mainLoop)++{++ g_main_loop_quit(mainLoop);++}++++static void configureBrowserInspector(GMainLoop* mainLoop, WebKitWebView *firstWebView)++{++ WebKitBrowserInspector* browserInspector = webkit_browser_inspector_get_default();++ g_signal_connect(browserInspector, "create-new-page", G_CALLBACK(createNewPage), NULL);++ // FIXME: This signal is received only when closeAll is called. We should not rely on that.++ g_signal_connect(firstWebView, "close", G_CALLBACK(closeAll), mainLoop);++}+++ int main(int argc, char *argv[])+ {+ #if ENABLE_DEVELOPER_MODE+@@ -301,6 +336,8 @@ int main(int argc, char *argv[])+ g_signal_connect(webView, "permission-request", G_CALLBACK(decidePermissionRequest), nullptr);+ g_signal_connect(webView, "create", G_CALLBACK(createWebView), nullptr);+++ configureBrowserInspector(loop, webView);+++ if (ignoreTLSErrors)+ webkit_web_context_set_tls_errors_policy(webContext, WEBKIT_TLS_ERRORS_POLICY_IGNORE);++--+2.17.1+diff --git a/browser_patches/webkit/pw_run.sh b/browser_patches/webkit/pw_run.shnew file mode 100755index 0000000000..71c060241b--- /dev/null+++ b/browser_patches/webkit/pw_run.sh@@ -0,0 +1,40 @@+#!/bin/bash++function runOSX() {+ # if script is run as-is+ if [ -d $SCRIPT_PATH/checkout/WebKitBuild/Release/MiniBrowser.app ]; then+ DYLIB_PATH="$SCRIPT_PATH/checkout/WebKitBuild/Release"+ elif [ -d $SCRIPT_PATH/MiniBrowser.app ]; then+ DYLIB_PATH="$SCRIPT_PATH"+ else+ echo "Cannot find a MiniBrowser.app in neither location" 1>&2+ exit 1+ fi+ MINIBROWSER="$DYLIB_PATH/MiniBrowser.app/Contents/MacOS/MiniBrowser"+ DYLD_FRAMEWORK_PATH=$DYLIB_PATH DYLD_LIBRARY_PATH=$DYLIB_PATH $MINIBROWSER "$@"+}++function runLinux() {+ # if script is run as-is+ if [ -d $SCRIPT_PATH/checkout/WebKitBuild ]; then+ LD_PATH="$SCRIPT_PATH/checkout/WebKitBuild/DependenciesGTK/Root/lib:$SCRIPT_PATH/checkout/WebKitBuild/Release/bin"+ MINIBROWSER="$SCRIPT_PATH/checkout/WebKitBuild/Release/bin/MiniBrowser"+ elif [ -f $SCRIPT_PATH/MiniBrowser ]; then+ LD_PATH="$SCRIPT_PATH"+ MINIBROWSER="$SCRIPT_PATH/MiniBrowser"+ else+ echo "Cannot find a MiniBrowser.app in neither location" 1>&2+ exit 1+ fi+ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$LD_PATH $MINIBROWSER "$@"+}++SCRIPT_PATH="$(cd "$(dirname "$0")" ; pwd -P)"+if [ "$(uname)" == "Darwin" ]; then+ runOSX "$@"+elif [ "$(uname)" == "Linux" ]; then+ runLinux "$@"+else+ echo "ERROR: cannot run on this platform!" 1>&2+ exit 1;+fidiff --git a/chromium.js b/chromium.jsnew file mode 100644index 0000000000..be153287e4--- /dev/null+++ b/chromium.js@@ -0,0 +1,30 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {helper} = require('./lib/helper');+const api = require('./lib/api');+for (const className in api.Chromium) {+ // Playwright-web excludes certain classes from bundle, e.g. BrowserFetcher.+ if (typeof api.Chromium[className] === 'function')+ helper.installAsyncStackHooks(api.Chromium[className]);+}++// If node does not support async await, use the compiled version.+const {Playwright} = require('./lib/chromium/Playwright');+const packageJson = require('./package.json');+const isPlaywrightCore = packageJson.name === 'playwright-core';++module.exports = new Playwright(__dirname, packageJson.playwright.chromium_revision, isPlaywrightCore);diff --git a/docs/api.md b/docs/api.mdnew file mode 100644index 0000000000..186d72e896--- /dev/null+++ b/docs/api.md@@ -0,0 +1,4107 @@++# Playwright API <!-- GEN:version -->Tip-Of-Tree<!-- GEN:stop-->+<!-- GEN:empty-if-release --><!-- GEN:stop -->++- API Translations: [中文|Chinese](https://zhaoqize.github.io/playwright-api-zh_CN/#/)+- Troubleshooting: [troubleshooting.md](https://github.com/Microsoft/playwright/blob/master/docs/troubleshooting.md)+++##### Table of Contents++<!-- GEN:toc -->+- [Playwright API Tip-Of-Tree](#playwright-api-tip-of-tree)+ - [Table of Contents](#table-of-contents)+ - [Overview](#overview)+ - [playwright vs playwright-core](#playwright-vs-playwright-core)+ - [Environment Variables](#environment-variables)+ - [Working with Chrome Extensions](#working-with-chrome-extensions)+ - [class: Playwright](#class-playwright)+ - [playwright.connect(options)](#playwrightconnectoptions)+ - [playwright.createBrowserFetcher([options])](#playwrightcreatebrowserfetcheroptions)+ - [playwright.defaultArgs([options])](#playwrightdefaultargsoptions)+ - [playwright.devices](#playwrightdevices)+ - [playwright.errors](#playwrighterrors)+ - [playwright.executablePath()](#playwrightexecutablepath)+ - [playwright.launch([options])](#playwrightlaunchoptions)+ - [class: BrowserFetcher](#class-browserfetcher)+ - [browserFetcher.canDownload(revision)](#browserfetchercandownloadrevision)+ - [browserFetcher.download(revision[, progressCallback])](#browserfetcherdownloadrevision-progresscallback)+ - [browserFetcher.localRevisions()](#browserfetcherlocalrevisions)+ - [browserFetcher.platform()](#browserfetcherplatform)+ - [browserFetcher.remove(revision)](#browserfetcherremoverevision)+ - [browserFetcher.revisionInfo(revision)](#browserfetcherrevisioninforevision)+ - [class: Browser](#class-browser)+ - [event: 'disconnected'](#event-disconnected)+ - [event: 'targetchanged'](#event-targetchanged)+ - [event: 'targetcreated'](#event-targetcreated)+ - [event: 'targetdestroyed'](#event-targetdestroyed)+ - [browser.browserContexts()](#browserbrowsercontexts)+ - [browser.close()](#browserclose)+ - [browser.createIncognitoBrowserContext()](#browsercreateincognitobrowsercontext)+ - [browser.defaultBrowserContext()](#browserdefaultbrowsercontext)+ - [browser.disconnect()](#browserdisconnect)+ - [browser.isConnected()](#browserisconnected)+ - [browser.newPage()](#browsernewpage)+ - [browser.pages()](#browserpages)+ - [browser.process()](#browserprocess)+ - [browser.target()](#browsertarget)+ - [browser.targets()](#browsertargets)+ - [browser.userAgent()](#browseruseragent)+ - [browser.version()](#browserversion)+ - [browser.waitForTarget(predicate[, options])](#browserwaitfortargetpredicate-options)+ - [browser.wsEndpoint()](#browserwsendpoint)+ - [class: BrowserContext](#class-browsercontext)+ - [event: 'targetchanged'](#event-targetchanged-1)+ - [event: 'targetcreated'](#event-targetcreated-1)+ - [event: 'targetdestroyed'](#event-targetdestroyed-1)+ - [browserContext.browser()](#browsercontextbrowser)+ - [browserContext.clearPermissionOverrides()](#browsercontextclearpermissionoverrides)+ - [browserContext.close()](#browsercontextclose)+ - [browserContext.isIncognito()](#browsercontextisincognito)+ - [browserContext.newPage()](#browsercontextnewpage)+ - [browserContext.overridePermissions(origin, permissions)](#browsercontextoverridepermissionsorigin-permissions)+ - [browserContext.pages()](#browsercontextpages)+ - [browserContext.targets()](#browsercontexttargets)+ - [browserContext.waitForTarget(predicate[, options])](#browsercontextwaitfortargetpredicate-options)+ - [class: Page](#class-page)+ - [event: 'close'](#event-close)+ - [event: 'console'](#event-console)+ - [event: 'dialog'](#event-dialog)+ - [event: 'domcontentloaded'](#event-domcontentloaded)+ - [event: 'error'](#event-error)+ - [event: 'frameattached'](#event-frameattached)+ - [event: 'framedetached'](#event-framedetached)+ - [event: 'framenavigated'](#event-framenavigated)+ - [event: 'load'](#event-load)+ - [event: 'metrics'](#event-metrics)+ - [event: 'pageerror'](#event-pageerror)+ - [event: 'popup'](#event-popup)+ - [event: 'request'](#event-request)+ - [event: 'requestfailed'](#event-requestfailed)+ - [event: 'requestfinished'](#event-requestfinished)+ - [event: 'response'](#event-response)+ - [event: 'workercreated'](#event-workercreated)+ - [event: 'workerdestroyed'](#event-workerdestroyed)+ - [page.$(selector)](#pageselector)+ - [page.$$(selector)](#pageselector)+ - [page.$$eval(selector, pageFunction[, ...args])](#pageevalselector-pagefunction-args)+ - [page.$eval(selector, pageFunction[, ...args])](#pageevalselector-pagefunction-args)+ - [page.$x(expression)](#pagexexpression)+ - [page.accessibility](#pageaccessibility)+ - [page.addScriptTag(options)](#pageaddscripttagoptions)+ - [page.addStyleTag(options)](#pageaddstyletagoptions)+ - [page.authenticate(credentials)](#pageauthenticatecredentials)+ - [page.bringToFront()](#pagebringtofront)+ - [page.browser()](#pagebrowser)+ - [page.browserContext()](#pagebrowsercontext)+ - [page.click(selector[, options])](#pageclickselector-options)+ - [page.close([options])](#pagecloseoptions)+ - [page.content()](#pagecontent)+ - [page.cookies([...urls])](#pagecookiesurls)+ - [page.coverage](#pagecoverage)+ - [page.dblclick(selector[, options])](#pagedblclickselector-options)+ - [page.deleteCookie(...cookies)](#pagedeletecookiecookies)+ - [page.emulate(options)](#pageemulateoptions)+ - [page.emulateMedia(type)](#pageemulatemediatype)+ - [page.emulateMediaFeatures(features)](#pageemulatemediafeaturesfeatures)+ - [page.emulateMediaType(type)](#pageemulatemediatypetype)+ - [page.emulateTimezone(timezoneId)](#pageemulatetimezonetimezoneid)+ - [page.evaluate(pageFunction[, ...args])](#pageevaluatepagefunction-args)+ - [page.evaluateHandle(pageFunction[, ...args])](#pageevaluatehandlepagefunction-args)+ - [page.evaluateOnNewDocument(pageFunction[, ...args])](#pageevaluateonnewdocumentpagefunction-args)+ - [page.exposeFunction(name, playwrightFunction)](#pageexposefunctionname-playwrightfunction)+ - [page.fill(selector, value)](#pagefillselector-value)+ - [page.focus(selector)](#pagefocusselector)+ - [page.frames()](#pageframes)+ - [page.goBack([options])](#pagegobackoptions)+ - [page.goForward([options])](#pagegoforwardoptions)+ - [page.goto(url[, options])](#pagegotourl-options)+ - [page.hover(selector[, options])](#pagehoverselector-options)+ - [page.isClosed()](#pageisclosed)+ - [page.keyboard](#pagekeyboard)+ - [page.mainFrame()](#pagemainframe)+ - [page.metrics()](#pagemetrics)+ - [page.mouse](#pagemouse)+ - [page.pdf([options])](#pagepdfoptions)+ - [page.queryObjects(prototypeHandle)](#pagequeryobjectsprototypehandle)+ - [page.reload([options])](#pagereloadoptions)+ - [page.screenshot([options])](#pagescreenshotoptions)+ - [page.select(selector, ...values)](#pageselectselector-values)+ - [page.setBypassCSP(enabled)](#pagesetbypasscspenabled)+ - [page.setCacheEnabled([enabled])](#pagesetcacheenabledenabled)+ - [page.setContent(html[, options])](#pagesetcontenthtml-options)+ - [page.setCookie(...cookies)](#pagesetcookiecookies)+ - [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout)+ - [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout)+ - [page.setExtraHTTPHeaders(headers)](#pagesetextrahttpheadersheaders)+ - [page.setGeolocation(options)](#pagesetgeolocationoptions)+ - [page.setJavaScriptEnabled(enabled)](#pagesetjavascriptenabledenabled)+ - [page.setOfflineMode(enabled)](#pagesetofflinemodeenabled)+ - [page.setRequestInterception(value)](#pagesetrequestinterceptionvalue)+ - [page.setUserAgent(userAgent)](#pagesetuseragentuseragent)+ - [page.setViewport(viewport)](#pagesetviewportviewport)+ - [page.tap(selector[, options])](#pagetapselector-options)+ - [page.target()](#pagetarget)+ - [page.title()](#pagetitle)+ - [page.touchscreen](#pagetouchscreen)+ - [page.tracing](#pagetracing)+ - [page.tripleclick(selector[, options])](#pagetripleclickselector-options)+ - [page.type(selector, text[, options])](#pagetypeselector-text-options)+ - [page.url()](#pageurl)+ - [page.viewport()](#pageviewport)+ - [page.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])](#pagewaitforselectororfunctionortimeout-options-args)+ - [page.waitForFileChooser([options])](#pagewaitforfilechooseroptions)+ - [page.waitForFunction(pageFunction[, options[, ...args]])](#pagewaitforfunctionpagefunction-options-args)+ - [page.waitForNavigation([options])](#pagewaitfornavigationoptions)+ - [page.waitForRequest(urlOrPredicate[, options])](#pagewaitforrequesturlorpredicate-options)+ - [page.waitForResponse(urlOrPredicate[, options])](#pagewaitforresponseurlorpredicate-options)+ - [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options)+ - [page.waitForXPath(xpath[, options])](#pagewaitforxpathxpath-options)+ - [page.workers()](#pageworkers)+ - [class: Worker](#class-worker)+ - [worker.evaluate(pageFunction[, ...args])](#workerevaluatepagefunction-args)+ - [worker.evaluateHandle(pageFunction[, ...args])](#workerevaluatehandlepagefunction-args)+ - [worker.executionContext()](#workerexecutioncontext)+ - [worker.url()](#workerurl)+ - [class: Accessibility](#class-accessibility)+ - [accessibility.snapshot([options])](#accessibilitysnapshotoptions)+ - [class: Keyboard](#class-keyboard)+ - [keyboard.down(key[, options])](#keyboarddownkey-options)+ - [keyboard.press(key[, options])](#keyboardpresskey-options)+ - [keyboard.sendCharacter(char)](#keyboardsendcharacterchar)+ - [keyboard.type(text[, options])](#keyboardtypetext-options)+ - [keyboard.up(key)](#keyboardupkey)+ - [class: Mouse](#class-mouse)+ - [mouse.click(x, y[, options])](#mouseclickx-y-options)+ - [mouse.dblclick(x, y[, options])](#mousedblclickx-y-options)+ - [mouse.down([options])](#mousedownoptions)+ - [mouse.move(x, y[, options])](#mousemovex-y-options)+ - [mouse.tripleclick(x, y[, options])](#mousetripleclickx-y-options)+ - [mouse.up([options])](#mouseupoptions)+ - [class: Touchscreen](#class-touchscreen)+ - [touchscreen.tap(x, y)](#touchscreentapx-y)+ - [class: Tracing](#class-tracing)+ - [tracing.start([options])](#tracingstartoptions)+ - [tracing.stop()](#tracingstop)+ - [class: FileChooser](#class-filechooser)+ - [fileChooser.accept(filePaths)](#filechooseracceptfilepaths)+ - [fileChooser.cancel()](#filechoosercancel)+ - [fileChooser.isMultiple()](#filechooserismultiple)+ - [class: Dialog](#class-dialog)+ - [dialog.accept([promptText])](#dialogacceptprompttext)+ - [dialog.defaultValue()](#dialogdefaultvalue)+ - [dialog.dismiss()](#dialogdismiss)+ - [dialog.message()](#dialogmessage)+ - [dialog.type()](#dialogtype)+ - [class: ConsoleMessage](#class-consolemessage)+ - [consoleMessage.args()](#consolemessageargs)+ - [consoleMessage.location()](#consolemessagelocation)+ - [consoleMessage.text()](#consolemessagetext)+ - [consoleMessage.type()](#consolemessagetype)+ - [class: Frame](#class-frame)+ - [frame.$(selector)](#frameselector)+ - [frame.$$(selector)](#frameselector)+ - [frame.$$eval(selector, pageFunction[, ...args])](#frameevalselector-pagefunction-args)+ - [frame.$eval(selector, pageFunction[, ...args])](#frameevalselector-pagefunction-args)+ - [frame.$x(expression)](#framexexpression)+ - [frame.addScriptTag(options)](#frameaddscripttagoptions)+ - [frame.addStyleTag(options)](#frameaddstyletagoptions)+ - [frame.childFrames()](#framechildframes)+ - [frame.click(selector[, options])](#frameclickselector-options)+ - [frame.content()](#framecontent)+ - [frame.dblclick(selector[, options])](#framedblclickselector-options)+ - [frame.evaluate(pageFunction[, ...args])](#frameevaluatepagefunction-args)+ - [frame.evaluateHandle(pageFunction[, ...args])](#frameevaluatehandlepagefunction-args)+ - [frame.executionContext()](#frameexecutioncontext)+ - [frame.fill(selector, value)](#framefillselector-value)+ - [frame.focus(selector)](#framefocusselector)+ - [frame.goto(url[, options])](#framegotourl-options)+ - [frame.hover(selector[, options])](#framehoverselector-options)+ - [frame.isDetached()](#frameisdetached)+ - [frame.name()](#framename)+ - [frame.parentFrame()](#frameparentframe)+ - [frame.select(selector, ...values)](#frameselectselector-values)+ - [frame.setContent(html[, options])](#framesetcontenthtml-options)+ - [frame.tap(selector[, options])](#frametapselector-options)+ - [frame.title()](#frametitle)+ - [frame.tripleclick(selector[, options])](#frametripleclickselector-options)+ - [frame.type(selector, text[, options])](#frametypeselector-text-options)+ - [frame.url()](#frameurl)+ - [frame.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])](#framewaitforselectororfunctionortimeout-options-args)+ - [frame.waitForFunction(pageFunction[, options[, ...args]])](#framewaitforfunctionpagefunction-options-args)+ - [frame.waitForNavigation([options])](#framewaitfornavigationoptions)+ - [frame.waitForSelector(selector[, options])](#framewaitforselectorselector-options)+ - [frame.waitForXPath(xpath[, options])](#framewaitforxpathxpath-options)+ - [class: ExecutionContext](#class-executioncontext)+ - [executionContext.evaluate(pageFunction[, ...args])](#executioncontextevaluatepagefunction-args)+ - [executionContext.evaluateHandle(pageFunction[, ...args])](#executioncontextevaluatehandlepagefunction-args)+ - [executionContext.frame()](#executioncontextframe)+ - [executionContext.queryObjects(prototypeHandle)](#executioncontextqueryobjectsprototypehandle)+ - [class: JSHandle](#class-jshandle)+ - [jsHandle.asElement()](#jshandleaselement)+ - [jsHandle.dispose()](#jshandledispose)+ - [jsHandle.evaluate(pageFunction[, ...args])](#jshandleevaluatepagefunction-args)+ - [jsHandle.evaluateHandle(pageFunction[, ...args])](#jshandleevaluatehandlepagefunction-args)+ - [jsHandle.executionContext()](#jshandleexecutioncontext)+ - [jsHandle.getProperties()](#jshandlegetproperties)+ - [jsHandle.getProperty(propertyName)](#jshandlegetpropertypropertyname)+ - [jsHandle.jsonValue()](#jshandlejsonvalue)+ - [class: ElementHandle](#class-elementhandle)+ - [elementHandle.$(selector)](#elementhandleselector)+ - [elementHandle.$$(selector)](#elementhandleselector)+ - [elementHandle.$$eval(selector, pageFunction[, ...args])](#elementhandleevalselector-pagefunction-args)+ - [elementHandle.$eval(selector, pageFunction[, ...args])](#elementhandleevalselector-pagefunction-args)+ - [elementHandle.$x(expression)](#elementhandlexexpression)+ - [elementHandle.asElement()](#elementhandleaselement)+ - [elementHandle.boundingBox()](#elementhandleboundingbox)+ - [elementHandle.boxModel()](#elementhandleboxmodel)+ - [elementHandle.click([options])](#elementhandleclickoptions)+ - [elementHandle.contentFrame()](#elementhandlecontentframe)+ - [elementHandle.dblclick([options])](#elementhandledblclickoptions)+ - [elementHandle.dispose()](#elementhandledispose)+ - [elementHandle.evaluate(pageFunction[, ...args])](#elementhandleevaluatepagefunction-args)+ - [elementHandle.evaluateHandle(pageFunction[, ...args])](#elementhandleevaluatehandlepagefunction-args)+ - [elementHandle.executionContext()](#elementhandleexecutioncontext)+ - [elementHandle.fill(value)](#elementhandlefillvalue)+ - [elementHandle.focus()](#elementhandlefocus)+ - [elementHandle.getProperties()](#elementhandlegetproperties)+ - [elementHandle.getProperty(propertyName)](#elementhandlegetpropertypropertyname)+ - [elementHandle.hover([options])](#elementhandlehoveroptions)+ - [elementHandle.isIntersectingViewport()](#elementhandleisintersectingviewport)+ - [elementHandle.jsonValue()](#elementhandlejsonvalue)+ - [elementHandle.press(key[, options])](#elementhandlepresskey-options)+ - [elementHandle.screenshot([options])](#elementhandlescreenshotoptions)+ - [elementHandle.select(...values)](#elementhandleselectvalues)+ - [elementHandle.tap([options])](#elementhandletapoptions)+ - [elementHandle.toString()](#elementhandletostring)+ - [elementHandle.tripleclick([options])](#elementhandletripleclickoptions)+ - [elementHandle.type(text[, options])](#elementhandletypetext-options)+ - [elementHandle.uploadFile(...filePaths)](#elementhandleuploadfilefilepaths)+ - [class: Request](#class-request)+ - [request.abort([errorCode])](#requestaborterrorcode)+ - [request.continue([overrides])](#requestcontinueoverrides)+ - [request.failure()](#requestfailure)+ - [request.frame()](#requestframe)+ - [request.headers()](#requestheaders)+ - [request.isNavigationRequest()](#requestisnavigationrequest)+ - [request.method()](#requestmethod)+ - [request.postData()](#requestpostdata)+ - [request.redirectChain()](#requestredirectchain)+ - [request.resourceType()](#requestresourcetype)+ - [request.respond(response)](#requestrespondresponse)+ - [request.response()](#requestresponse)+ - [request.url()](#requesturl)+ - [class: Response](#class-response)+ - [response.buffer()](#responsebuffer)+ - [response.frame()](#responseframe)+ - [response.fromCache()](#responsefromcache)+ - [response.fromServiceWorker()](#responsefromserviceworker)+ - [response.headers()](#responseheaders)+ - [response.json()](#responsejson)+ - [response.ok()](#responseok)+ - [response.remoteAddress()](#responseremoteaddress)+ - [response.request()](#responserequest)+ - [response.securityDetails()](#responsesecuritydetails)+ - [response.status()](#responsestatus)+ - [response.statusText()](#responsestatustext)+ - [response.text()](#responsetext)+ - [response.url()](#responseurl)+ - [class: SecurityDetails](#class-securitydetails)+ - [securityDetails.issuer()](#securitydetailsissuer)+ - [securityDetails.protocol()](#securitydetailsprotocol)+ - [securityDetails.subjectName()](#securitydetailssubjectname)+ - [securityDetails.validFrom()](#securitydetailsvalidfrom)+ - [securityDetails.validTo()](#securitydetailsvalidto)+ - [class: Target](#class-target)+ - [target.browser()](#targetbrowser)+ - [target.browserContext()](#targetbrowsercontext)+ - [target.createCDPSession()](#targetcreatecdpsession)+ - [target.opener()](#targetopener)+ - [target.page()](#targetpage)+ - [target.type()](#targettype)+ - [target.url()](#targeturl)+ - [target.worker()](#targetworker)+ - [class: CDPSession](#class-cdpsession)+ - [cdpSession.detach()](#cdpsessiondetach)+ - [cdpSession.send(method[, params])](#cdpsessionsendmethod-params)+ - [class: Coverage](#class-coverage)+ - [coverage.startCSSCoverage([options])](#coveragestartcsscoverageoptions)+ - [coverage.startJSCoverage([options])](#coveragestartjscoverageoptions)+ - [coverage.stopCSSCoverage()](#coveragestopcsscoverage)+ - [coverage.stopJSCoverage()](#coveragestopjscoverage)+ - [class: TimeoutError](#class-timeouterror)+<!-- GEN:stop -->++### Overview++Playwright is a Node library which provides a high-level API to control Chromium or Chrome over the DevTools Protocol.++The Playwright API is hierarchical and mirrors the browser structure.++> **NOTE** On the following diagram, faded entities are not currently represented in Playwright.++++- [`Playwright`](#class-playwright) communicates with the browser using [DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/).+- [`Browser`](#class-browser) instance can own multiple browser contexts.+- [`BrowserContext`](#class-browsercontext) instance defines a browsing session and can own multiple pages.+- [`Page`](#class-page) has at least one frame: main frame. There might be other frames created by [iframe](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) or [frame](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame) tags.+- [`Frame`](#class-frame) has at least one execution context - the default execution context - where the frame's JavaScript is executed. A Frame might have additional execution contexts that are associated with [extensions](https://developer.chrome.com/extensions).+- [`Worker`](#class-worker) has a single execution context and facilitates interacting with [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).++(Diagram source: [link](https://docs.google.com/drawings/d/1Q_AM6KYs9kbyLZF-Lpp5mtpAWth73Cq8IKCsWYgi8MM/edit?usp=sharing))++### playwright vs playwright-core++Every release since v1.7.0 we publish two packages:+- [playwright](https://www.npmjs.com/package/playwright)+- [playwright-core](https://www.npmjs.com/package/playwright-core)++`playwright` is a *product* for browser automation. When installed, it downloads a version of+Chromium, which it then drives using `playwright-core`. Being an end-user product, `playwright` supports a bunch of convenient `PLAYWRIGHT_*` env variables to tweak its behavior.++`playwright-core` is a *library* to help drive anything that supports DevTools protocol. `playwright-core` doesn't download Chromium when installed. Being a library, `playwright-core` is fully driven+through its programmatic interface and disregards all the `PLAYWRIGHT_*` env variables.++To sum up, the only differences between `playwright-core` and `playwright` are:+- `playwright-core` doesn't automatically download Chromium when installed.+- `playwright-core` ignores all `PLAYWRIGHT_*` env variables.++In most cases, you'll be fine using the `playwright` package.++However, you should use `playwright-core` if:+- you're building another end-user product or library atop of DevTools protocol. For example, one might build a PDF generator using `playwright-core` and write a custom `install.js` script that downloads [`headless_shell`](https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md) instead of Chromium to save disk space.+- you're bundling Playwright to use in Chrome Extension / browser with the DevTools protocol where downloading an additional Chromium binary is unnecessary.++When using `playwright-core`, remember to change the *include* line:++```js+const playwright = require('playwright-core');+```++You will then need to call [`playwright.connect([options])`](#playwrightconnectoptions) or [`playwright.launch([options])`](#playwrightlaunchoptions) with an explicit `executablePath` option.++### Environment Variables++Playwright looks for certain [environment variables](https://en.wikipedia.org/wiki/Environment_variable) to aid its operations.+If Playwright doesn't find them in the environment during the installation step, a lowercased variant of these variables will be used from the [npm config](https://docs.npmjs.com/cli/config).++- `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` - defines HTTP proxy settings that are used to download and run Chromium.+- `PLAYWRIGHT_SKIP_CHROMIUM_DOWNLOAD` - do not download bundled Chromium during installation step.+- `PLAYWRIGHT_DOWNLOAD_HOST` - overwrite URL prefix that is used to download Chromium. Note: this includes protocol and might even include path prefix. Defaults to `https://storage.googleapis.com`.+- `PLAYWRIGHT_CHROMIUM_REVISION` - specify a certain version of Chromium you'd like Playwright to use. See [playwright.launch([options])](#playwrightlaunchoptions) on how executable path is inferred. **BEWARE**: Playwright is only [guaranteed to work](https://github.com/Microsoft/playwright/#q-why-doesnt-playwright-vxxx-work-with-chromium-vyyy) with the bundled Chromium, use at your own risk.+- `PLAYWRIGHT_EXECUTABLE_PATH` - specify an executable path to be used in `playwright.launch`. See [playwright.launch([options])](#playwrightlaunchoptions) on how the executable path is inferred. **BEWARE**: Playwright is only [guaranteed to work](https://github.com/Microsoft/playwright/#q-why-doesnt-playwright-vxxx-work-with-chromium-vyyy) with the bundled Chromium, use at your own risk.++> **NOTE** PLAYWRIGHT_* env variables are not accounted for in the [`playwright-core`](https://www.npmjs.com/package/playwright-core) package.+++### Working with Chrome Extensions++Playwright can be used for testing Chrome Extensions.++> **NOTE** Extensions in Chrome / Chromium currently only work in non-headless mode.++The following is code for getting a handle to the [background page](https://developer.chrome.com/extensions/background_pages) of an extension whose source is located in `./my-extension`:+```js+const playwright = require('playwright');++(async () => {+ const pathToExtension = require('path').join(__dirname, 'my-extension');+ const browser = await playwright.launch({+ headless: false,+ args: [+ `--disable-extensions-except=${pathToExtension}`,+ `--load-extension=${pathToExtension}`+ ]+ });+ const targets = await browser.targets();+ const backgroundPageTarget = targets.find(target => target.type() === 'background_page');+ const backgroundPage = await backgroundPageTarget.page();+ // Test the background page as you would any other page.+ await browser.close();+})();+```++> **NOTE** It is not yet possible to test extension popups or content scripts.++### class: Playwright++Playwright module provides a method to launch a Chromium instance.+The following is a typical example of using Playwright to drive automation:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto('https://www.google.com');+ // other actions...+ await browser.close();+})();+```++#### playwright.connect(options)+- `options` <[Object]>+ - `browserWSEndpoint` <?[string]> a [browser websocket endpoint](#browserwsendpoint) to connect to.+ - `browserURL` <?[string]> a browser url to connect to, in format `http://${host}:${port}`. Use interchangeably with `browserWSEndpoint` to let Playwright fetch it from [metadata endpoint](https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target).+ - `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.+ - `defaultViewport` <?[Object]> Sets a consistent viewport for each page. Defaults to an 800x600 viewport. `null` disables the default viewport.+ - `width` <[number]> page width in pixels.+ - `height` <[number]> page height in pixels.+ - `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.+ - `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account. Defaults to `false`.+ - `hasTouch`<[boolean]> Specifies if viewport supports touch events. Defaults to `false`+ - `isLandscape` <[boolean]> Specifies if viewport is in landscape mode. Defaults to `false`.+ - `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.+ - `transport` <[ConnectionTransport]> **Experimental** Specify a custom transport object for Playwright to use.+- returns: <[Promise]<[Browser]>>++This methods attaches Playwright to an existing Chromium instance.++#### playwright.createBrowserFetcher([options])+- `options` <[Object]>+ - `host` <[string]> A download host to be used. Defaults to `https://storage.googleapis.com`.+ - `path` <[string]> A path for the downloads folder. Defaults to `<root>/.local-chromium`, where `<root>` is playwright's package root.+ - `platform` <[string]> Possible values are: `mac`, `win32`, `win64`, `linux`. Defaults to the current platform.+- returns: <[BrowserFetcher]>++#### playwright.defaultArgs([options])+- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:+ - `headless` <[boolean]> Whether to run browser in [headless mode](https://developers.google.com/web/updates/2017/04/headless-chrome). Defaults to `true` unless the `devtools` option is `true`.+ - `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).+ - `userDataDir` <[string]> Path to a [User Data Directory](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md).+ - `devtools` <[boolean]> Whether to auto-open a DevTools panel for each tab. If this option is `true`, the `headless` option will be set `false`.+- returns: <[Array]<[string]>>++The default flags that Chromium will be launched with.++#### playwright.devices+- returns: <[Object]>++Returns a list of devices to be used with [`page.emulate(options)`](#pageemulateoptions). Actual list of+devices can be found in [lib/DeviceDescriptors.js](https://github.com/Microsoft/playwright/blob/master/lib/DeviceDescriptors.js).++```js+const playwright = require('playwright');+const iPhone = playwright.devices['iPhone 6'];++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.emulate(iPhone);+ await page.goto('https://www.google.com');+ // other actions...+ await browser.close();+})();+```++> **NOTE** The old way (Playwright versions <= v1.14.0) devices can be obtained with `require('playwright/DeviceDescriptors')`.++#### playwright.errors+- returns: <[Object]>+ - `TimeoutError` <[function]> A class of [TimeoutError].++Playwright methods might throw errors if they are unable to fulfill a request. For example, [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options)+might fail if the selector doesn't match any nodes during the given timeframe.++For certain types of errors Playwright uses specific error classes.+These classes are available via [`playwright.errors`](#playwrighterrors)++An example of handling a timeout error:+```js+try {+ await page.waitForSelector('.foo');+} catch (e) {+ if (e instanceof playwright.errors.TimeoutError) {+ // Do something if this is a timeout.+ }+}+```++> **NOTE** The old way (Playwright versions <= v1.14.0) errors can be obtained with `require('playwright/Errors')`.++#### playwright.executablePath()+- returns: <[string]> A path where Playwright expects to find bundled Chromium. Chromium might not exist there if the download was skipped with [`PLAYWRIGHT_SKIP_CHROMIUM_DOWNLOAD`](#environment-variables).++> **NOTE** `playwright.executablePath()` is affected by the `PLAYWRIGHT_EXECUTABLE_PATH` and `PLAYWRIGHT_CHROMIUM_REVISION` env variables. See [Environment Variables](#environment-variables) for details.+++#### playwright.launch([options])+- `options` <[Object]> Set of configurable options to set on the browser. Can have the following fields:+ - `ignoreHTTPSErrors` <[boolean]> Whether to ignore HTTPS errors during navigation. Defaults to `false`.+ - `headless` <[boolean]> Whether to run browser in [headless mode](https://developers.google.com/web/updates/2017/04/headless-chrome). Defaults to `true` unless the `devtools` option is `true`.+ - `executablePath` <[string]> Path to a Chromium or Chrome executable to run instead of the bundled Chromium. If `executablePath` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). **BEWARE**: Playwright is only [guaranteed to work](https://github.com/Microsoft/playwright/#q-why-doesnt-playwright-vxxx-work-with-chromium-vyyy) with the bundled Chromium, use at your own risk.+ - `slowMo` <[number]> Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on.+ - `defaultViewport` <?[Object]> Sets a consistent viewport for each page. Defaults to an 800x600 viewport. `null` disables the default viewport.+ - `width` <[number]> page width in pixels.+ - `height` <[number]> page height in pixels.+ - `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.+ - `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account. Defaults to `false`.+ - `hasTouch`<[boolean]> Specifies if viewport supports touch events. Defaults to `false`+ - `isLandscape` <[boolean]> Specifies if viewport is in landscape mode. Defaults to `false`.+ - `args` <[Array]<[string]>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found [here](http://peter.sh/experiments/chromium-command-line-switches/).+ - `ignoreDefaultArgs` <[boolean]|[Array]<[string]>> If `true`, then do not use [`playwright.defaultArgs()`](#playwrightdefaultargsoptions). If an array is given, then filter out the given default arguments. Dangerous option; use with care. Defaults to `false`.+ - `handleSIGINT` <[boolean]> Close the browser process on Ctrl-C. Defaults to `true`.+ - `handleSIGTERM` <[boolean]> Close the browser process on SIGTERM. Defaults to `true`.+ - `handleSIGHUP` <[boolean]> Close the browser process on SIGHUP. Defaults to `true`.+ - `timeout` <[number]> Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout.+ - `dumpio` <[boolean]> Whether to pipe the browser process stdout and stderr into `process.stdout` and `process.stderr`. Defaults to `false`.+ - `userDataDir` <[string]> Path to a [User Data Directory](https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md).+ - `env` <[Object]> Specify environment variables that will be visible to the browser. Defaults to `process.env`.+ - `devtools` <[boolean]> Whether to auto-open a DevTools panel for each tab. If this option is `true`, the `headless` option will be set `false`.+ - `pipe` <[boolean]> Connects to the browser over a pipe instead of a WebSocket. Defaults to `false`.+- returns: <[Promise]<[Browser]>> Promise which resolves to browser instance.+++You can use `ignoreDefaultArgs` to filter out `--mute-audio` from default arguments:+```js+const browser = await playwright.launch({+ ignoreDefaultArgs: ['--mute-audio']+});+```++> **NOTE** Playwright can also be used to control the Chrome browser, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use `executablePath` option with extreme caution.+>+> If Google Chrome (rather than Chromium) is preferred, a [Chrome Canary](https://www.google.com/chrome/browser/canary.html) or [Dev Channel](https://www.chromium.org/getting-involved/dev-channel) build is suggested.+>+> In [playwright.launch([options])](#playwrightlaunchoptions) above, any mention of Chromium also applies to Chrome.+>+> See [`this article`](https://www.howtogeek.com/202825/what%E2%80%99s-the-difference-between-chromium-and-chrome/) for a description of the differences between Chromium and Chrome. [`This article`](https://chromium.googlesource.com/chromium/src/+/lkgr/docs/chromium_browser_vs_google_chrome.md) describes some differences for Linux users.++### class: BrowserFetcher++BrowserFetcher can download and manage different versions of Chromium.++BrowserFetcher operates on revision strings that specify a precise version of Chromium, e.g. `"533271"`. Revision strings can be obtained from [omahaproxy.appspot.com](http://omahaproxy.appspot.com/).++An example of using BrowserFetcher to download a specific version of Chromium and running+Playwright against it:++```js+const browserFetcher = playwright.createBrowserFetcher();+const revisionInfo = await browserFetcher.download('533271');+const browser = await playwright.launch({executablePath: revisionInfo.executablePath})+```++> **NOTE** BrowserFetcher is not designed to work concurrently with other+> instances of BrowserFetcher that share the same downloads directory.++#### browserFetcher.canDownload(revision)+- `revision` <[string]> a revision to check availability.+- returns: <[Promise]<[boolean]>> returns `true` if the revision could be downloaded from the host.++The method initiates a HEAD request to check if the revision is available.++#### browserFetcher.download(revision[, progressCallback])+- `revision` <[string]> a revision to download.+- `progressCallback` <[function]([number], [number])> A function that will be called with two arguments:+ - `downloadedBytes` <[number]> how many bytes have been downloaded+ - `totalBytes` <[number]> how large is the total download.+- returns: <[Promise]<[Object]>> Resolves with revision information when the revision is downloaded and extracted+ - `revision` <[string]> the revision the info was created from+ - `folderPath` <[string]> path to the extracted revision folder+ - `executablePath` <[string]> path to the revision executable+ - `url` <[string]> URL this revision can be downloaded from+ - `local` <[boolean]> whether the revision is locally available on disk++The method initiates a GET request to download the revision from the host.++#### browserFetcher.localRevisions()+- returns: <[Promise]<[Array]<[string]>>> A list of all revisions available locally on disk.++#### browserFetcher.platform()+- returns: <[string]> One of `mac`, `linux`, `win32` or `win64`.++#### browserFetcher.remove(revision)+- `revision` <[string]> a revision to remove. The method will throw if the revision has not been downloaded.+- returns: <[Promise]> Resolves when the revision has been removed.++#### browserFetcher.revisionInfo(revision)+- `revision` <[string]> a revision to get info for.+- returns: <[Object]>+ - `revision` <[string]> the revision the info was created from+ - `folderPath` <[string]> path to the extracted revision folder+ - `executablePath` <[string]> path to the revision executable+ - `url` <[string]> URL this revision can be downloaded from+ - `local` <[boolean]> whether the revision is locally available on disk++### class: Browser++* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)++A Browser is created when Playwright connects to a Chromium instance, either through [`playwright.launch`](#playwrightlaunchoptions) or [`playwright.connect`](#playwrightconnectoptions).++An example of using a [Browser] to create a [Page]:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto('https://example.com');+ await browser.close();+})();+```++An example of disconnecting from and reconnecting to a [Browser]:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ // Store the endpoint to be able to reconnect to Chromium+ const browserWSEndpoint = browser.wsEndpoint();+ // Disconnect playwright from Chromium+ browser.disconnect();++ // Use the endpoint to reestablish a connection+ const browser2 = await playwright.connect({browserWSEndpoint});+ // Close Chromium+ await browser2.close();+})();+```+#### event: 'disconnected'+Emitted when Playwright gets disconnected from the Chromium instance. This might happen because of one of the following:+- Chromium is closed or crashed+- The [`browser.disconnect`](#browserdisconnect) method was called++#### event: 'targetchanged'+- <[Target]>++Emitted when the url of a target changes.++> **NOTE** This includes target changes in incognito browser contexts.+++#### event: 'targetcreated'+- <[Target]>++Emitted when a target is created, for example when a new page is opened by [`window.open`](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) or [`browser.newPage`](#browsernewpage).++> **NOTE** This includes target creations in incognito browser contexts.++#### event: 'targetdestroyed'+- <[Target]>++Emitted when a target is destroyed, for example when a page is closed.++> **NOTE** This includes target destructions in incognito browser contexts.++#### browser.browserContexts()+- returns: <[Array]<[BrowserContext]>>++Returns an array of all open browser contexts. In a newly created browser, this will return+a single instance of [BrowserContext].++#### browser.close()+- returns: <[Promise]>++Closes Chromium and all of its pages (if any were opened). The [Browser] object itself is considered to be disposed and cannot be used anymore.++#### browser.createIncognitoBrowserContext()+- returns: <[Promise]<[BrowserContext]>>++Creates a new incognito browser context. This won't share cookies/cache with other browser contexts.++```js+(async () => {+ const browser = await playwright.launch();+ // Create a new incognito browser context.+ const context = await browser.createIncognitoBrowserContext();+ // Create a new page in a pristine context.+ const page = await context.newPage();+ // Do stuff+ await page.goto('https://example.com');+})();+```++#### browser.defaultBrowserContext()+- returns: <[BrowserContext]>++Returns the default browser context. The default browser context can not be closed.++#### browser.disconnect()++Disconnects Playwright from the browser, but leaves the Chromium process running. After calling `disconnect`, the [Browser] object is considered disposed and cannot be used anymore.++#### browser.isConnected()++- returns: <[boolean]>++Indicates that the browser is connected.++#### browser.newPage()+- returns: <[Promise]<[Page]>>++Promise which resolves to a new [Page] object. The [Page] is created in a default browser context.++#### browser.pages()+- returns: <[Promise]<[Array]<[Page]>>> Promise which resolves to an array of all open pages. Non visible pages, such as `"background_page"`, will not be listed here. You can find them using [target.page()](#targetpage).++An array of all pages inside the Browser. In case of multiple browser contexts,+the method will return an array with all the pages in all browser contexts.++#### browser.process()+- returns: <?[ChildProcess]> Spawned browser process. Returns `null` if the browser instance was created with [`playwright.connect`](#playwrightconnectoptions) method.++#### browser.target()+- returns: <[Target]>++A target associated with the browser.++#### browser.targets()+- returns: <[Array]<[Target]>>++An array of all active targets inside the Browser. In case of multiple browser contexts,+the method will return an array with all the targets in all browser contexts.++#### browser.userAgent()+- returns: <[Promise]<[string]>> Promise which resolves to the browser's original user agent.++> **NOTE** Pages can override browser user agent with [page.setUserAgent](#pagesetuseragentuseragent)++#### browser.version()+- returns: <[Promise]<[string]>> For headless Chromium, this is similar to `HeadlessChrome/61.0.3153.0`. For non-headless, this is similar to `Chrome/61.0.3153.0`.++> **NOTE** the format of browser.version() might change with future releases of Chromium.++#### browser.waitForTarget(predicate[, options])+- `predicate` <[function]\([Target]\):[boolean]> A function to be run for every target+- `options` <[Object]>+ - `timeout` <[number]> Maximum wait time in milliseconds. Pass `0` to disable the timeout. Defaults to 30 seconds.+- returns: <[Promise]<[Target]>> Promise which resolves to the first target found that matches the `predicate` function.++This searches for a target in all browser contexts.++An example of finding a target for a page opened via `window.open`:+```js+await page.evaluate(() => window.open('https://www.example.com/'));+const newWindowTarget = await browser.waitForTarget(target => target.url() === 'https://www.example.com/');+```++#### browser.wsEndpoint()+- returns: <[string]> Browser websocket url.++Browser websocket endpoint which can be used as an argument to+[playwright.connect](#playwrightconnectoptions). The format is `ws://${host}:${port}/devtools/browser/<id>`++You can find the `webSocketDebuggerUrl` from `http://${host}:${port}/json/version`. Learn more about the [devtools protocol](https://chromedevtools.github.io/devtools-protocol) and the [browser endpoint](https://chromedevtools.github.io/devtools-protocol/#how-do-i-access-the-browser-target).++### class: BrowserContext++* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)++BrowserContexts provide a way to operate multiple independent browser sessions. When a browser is launched, it has+a single BrowserContext used by default. The method `browser.newPage()` creates a page in the default browser context.++If a page opens another page, e.g. with a `window.open` call, the popup will belong to the parent page's browser+context.++Playwright allows creation of "incognito" browser contexts with `browser.createIncognitoBrowserContext()` method.+"Incognito" browser contexts don't write any browsing data to disk.++```js+// Create a new incognito browser context+const context = await browser.createIncognitoBrowserContext();+// Create a new page inside context.+const page = await context.newPage();+// ... do stuff with page ...+await page.goto('https://example.com');+// Dispose context once it's no longer needed.+await context.close();+```++#### event: 'targetchanged'+- <[Target]>++Emitted when the url of a target inside the browser context changes.++#### event: 'targetcreated'+- <[Target]>++Emitted when a new target is created inside the browser context, for example when a new page is opened by [`window.open`](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) or [`browserContext.newPage`](#browsercontextnewpage).++#### event: 'targetdestroyed'+- <[Target]>++Emitted when a target inside the browser context is destroyed, for example when a page is closed.++#### browserContext.browser()+- returns: <[Browser]>++The browser this browser context belongs to.++#### browserContext.clearPermissionOverrides()+- returns: <[Promise]>++Clears all permission overrides for the browser context.++```js+const context = browser.defaultBrowserContext();+context.overridePermissions('https://example.com', ['clipboard-read']);+// do stuff ..+context.clearPermissionOverrides();+```++#### browserContext.close()+- returns: <[Promise]>++Closes the browser context. All the targets that belong to the browser context+will be closed.++> **NOTE** only incognito browser contexts can be closed.++#### browserContext.isIncognito()+- returns: <[boolean]>++Returns whether BrowserContext is incognito.+The default browser context is the only non-incognito browser context.++> **NOTE** the default browser context cannot be closed.++#### browserContext.newPage()+- returns: <[Promise]<[Page]>>++Creates a new page in the browser context.+++#### browserContext.overridePermissions(origin, permissions)+- `origin` <[string]> The [origin] to grant permissions to, e.g. "https://example.com".+- `permissions` <[Array]<[string]>> An array of permissions to grant. All permissions that are not listed here will be automatically denied. Permissions can be one of the following values:+ - `'geolocation'`+ - `'midi'`+ - `'midi-sysex'` (system-exclusive midi)+ - `'notifications'`+ - `'push'`+ - `'camera'`+ - `'microphone'`+ - `'background-sync'`+ - `'ambient-light-sensor'`+ - `'accelerometer'`+ - `'gyroscope'`+ - `'magnetometer'`+ - `'accessibility-events'`+ - `'clipboard-read'`+ - `'clipboard-write'`+ - `'payment-handler'`+- returns: <[Promise]>+++```js+const context = browser.defaultBrowserContext();+await context.overridePermissions('https://html5demos.com', ['geolocation']);+```+++#### browserContext.pages()+- returns: <[Promise]<[Array]<[Page]>>> Promise which resolves to an array of all open pages. Non visible pages, such as `"background_page"`, will not be listed here. You can find them using [target.page()](#targetpage).++An array of all pages inside the browser context.++#### browserContext.targets()+- returns: <[Array]<[Target]>>++An array of all active targets inside the browser context.++#### browserContext.waitForTarget(predicate[, options])+- `predicate` <[function]\([Target]\):[boolean]> A function to be run for every target+- `options` <[Object]>+ - `timeout` <[number]> Maximum wait time in milliseconds. Pass `0` to disable the timeout. Defaults to 30 seconds.+- returns: <[Promise]<[Target]>> Promise which resolves to the first target found that matches the `predicate` function.++This searches for a target in this specific browser context.++An example of finding a target for a page opened via `window.open`:+```js+await page.evaluate(() => window.open('https://www.example.com/'));+const newWindowTarget = await browserContext.waitForTarget(target => target.url() === 'https://www.example.com/');+```++### class: Page++* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)++Page provides methods to interact with a single tab or [extension background page](https://developer.chrome.com/extensions/background_pages) in Chromium. One [Browser] instance might have multiple [Page] instances.++This example creates a page, navigates it to a URL, and then saves a screenshot:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto('https://example.com');+ await page.screenshot({path: 'screenshot.png'});+ await browser.close();+})();+```++The Page class emits various events (described below) which can be handled using any of Node's native [`EventEmitter`](https://nodejs.org/api/events.html#events_class_eventemitter) methods, such as `on`, `once` or `removeListener`.++This example logs a message for a single page `load` event:+```js+page.once('load', () => console.log('Page loaded!'));+```++To unsubscribe from events use the `removeListener` method:++```js+function logRequest(interceptedRequest) {+ console.log('A request was made:', interceptedRequest.url());+}+page.on('request', logRequest);+// Sometime later...+page.removeListener('request', logRequest);+```++#### event: 'close'++Emitted when the page closes.++#### event: 'console'+- <[ConsoleMessage]>++Emitted when JavaScript within the page calls one of console API methods, e.g. `console.log` or `console.dir`. Also emitted if the page throws an error or a warning.++The arguments passed into `console.log` appear as arguments on the event handler.++An example of handling `console` event:+```js+page.on('console', msg => {+ for (let i = 0; i < msg.args().length; ++i)+ console.log(`${i}: ${msg.args()[i]}`);+});+page.evaluate(() => console.log('hello', 5, {foo: 'bar'}));+```++#### event: 'dialog'+- <[Dialog]>++Emitted when a JavaScript dialog appears, such as `alert`, `prompt`, `confirm` or `beforeunload`. Playwright can respond to the dialog via [Dialog]'s [accept](#dialogacceptprompttext) or [dismiss](#dialogdismiss) methods.++#### event: 'domcontentloaded'++Emitted when the JavaScript [`DOMContentLoaded`](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded) event is dispatched.++#### event: 'error'+- <[Error]>++Emitted when the page crashes.++> **NOTE** `error` event has a special meaning in Node, see [error events](https://nodejs.org/api/events.html#events_error_events) for details.++#### event: 'frameattached'+- <[Frame]>++Emitted when a frame is attached.++#### event: 'framedetached'+- <[Frame]>++Emitted when a frame is detached.++#### event: 'framenavigated'+- <[Frame]>++Emitted when a frame is navigated to a new url.++#### event: 'load'++Emitted when the JavaScript [`load`](https://developer.mozilla.org/en-US/docs/Web/Events/load) event is dispatched.++#### event: 'metrics'+- <[Object]>+ - `title` <[string]> The title passed to `console.timeStamp`.+ - `metrics` <[Object]> Object containing metrics as key/value pairs. The values+ of metrics are of <[number]> type.++Emitted when the JavaScript code makes a call to `console.timeStamp`. For the list+of metrics see `page.metrics`.++#### event: 'pageerror'+- <[Error]> The exception message++Emitted when an uncaught exception happens within the page.++#### event: 'popup'+- <[Page]> Page corresponding to "popup" window++Emitted when the page opens a new tab or window.++```js+const [popup] = await Promise.all([+ new Promise(resolve => page.once('popup', resolve)),+ page.click('a[target=_blank]'),+]);+```++```js+const [popup] = await Promise.all([+ new Promise(resolve => page.once('popup', resolve)),+ page.evaluate(() => window.open('https://example.com')),+]);+```++#### event: 'request'+- <[Request]>++Emitted when a page issues a request. The [request] object is read-only.+In order to intercept and mutate requests, see `page.setRequestInterception`.++#### event: 'requestfailed'+- <[Request]>++Emitted when a request fails, for example by timing out.++> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with [`'requestfinished'`](#event-requestfinished) event and not with [`'requestfailed'`](#event-requestfailed).++#### event: 'requestfinished'+- <[Request]>++Emitted when a request finishes successfully.++#### event: 'response'+- <[Response]>++Emitted when a [response] is received.++#### event: 'workercreated'+- <[Worker]>++Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is spawned by the page.++#### event: 'workerdestroyed'+- <[Worker]>++Emitted when a dedicated [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) is terminated.++#### page.$(selector)+- `selector` <[string]> A [selector] to query page for+- returns: <[Promise]<?[ElementHandle]>>++The method runs `document.querySelector` within the page. If no element matches the selector, the return value resolves to `null`.++Shortcut for [page.mainFrame().$(selector)](#frameselector).++#### page.$$(selector)+- `selector` <[string]> A [selector] to query page for+- returns: <[Promise]<[Array]<[ElementHandle]>>>++The method runs `document.querySelectorAll` within the page. If no elements match the selector, the return value resolves to `[]`.++Shortcut for [page.mainFrame().$$(selector)](#frameselector-1).++#### page.$$eval(selector, pageFunction[, ...args])+- `selector` <[string]> A [selector] to query page for+- `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++This method runs `Array.from(document.querySelectorAll(selector))` within the page and passes it as the first argument to `pageFunction`.++If `pageFunction` returns a [Promise], then `page.$$eval` would wait for the promise to resolve and return its value.++Examples:+```js+const divsCounts = await page.$$eval('div', divs => divs.length);+```++#### page.$eval(selector, pageFunction[, ...args])+- `selector` <[string]> A [selector] to query page for+- `pageFunction` <[function]\([Element]\)> Function to be evaluated in browser context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++This method runs `document.querySelector` within the page and passes it as the first argument to `pageFunction`. If there's no element matching `selector`, the method throws an error.++If `pageFunction` returns a [Promise], then `page.$eval` would wait for the promise to resolve and return its value.++Examples:+```js+const searchValue = await page.$eval('#search', el => el.value);+const preloadHref = await page.$eval('link[rel=preload]', el => el.href);+const html = await page.$eval('.main-container', e => e.outerHTML);+```++Shortcut for [page.mainFrame().$eval(selector, pageFunction)](#frameevalselector-pagefunction-args).++#### page.$x(expression)+- `expression` <[string]> Expression to [evaluate](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate).+- returns: <[Promise]<[Array]<[ElementHandle]>>>++The method evaluates the XPath expression.++Shortcut for [page.mainFrame().$x(expression)](#framexexpression)++#### page.accessibility+- returns: <[Accessibility]>++#### page.addScriptTag(options)+- `options` <[Object]>+ - `url` <[string]> URL of a script to be added.+ - `path` <[string]> Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).+ - `content` <[string]> Raw JavaScript content to be injected into frame.+ - `type` <[string]> Script type. Use 'module' in order to load a Javascript ES6 module. See [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.+- returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the script's onload fires or when the script content was injected into frame.++Adds a `<script>` tag into the page with the desired url or content.++Shortcut for [page.mainFrame().addScriptTag(options)](#frameaddscripttagoptions).++#### page.addStyleTag(options)+- `options` <[Object]>+ - `url` <[string]> URL of the `<link>` tag.+ - `path` <[string]> Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).+ - `content` <[string]> Raw CSS content to be injected into frame.+- returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.++Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.++Shortcut for [page.mainFrame().addStyleTag(options)](#frameaddstyletagoptions).++#### page.authenticate(credentials)+- `credentials` <?[Object]>+ - `username` <[string]>+ - `password` <[string]>+- returns: <[Promise]>++Provide credentials for [HTTP authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).++To disable authentication, pass `null`.++#### page.bringToFront()++- returns: <[Promise]>++Brings page to front (activates tab).++#### page.browser()++- returns: <[Browser]>++Get the browser the page belongs to.++#### page.browserContext()++- returns: <[BrowserContext]>++Get the browser context that the page belongs to.++#### page.click(selector[, options])+- `selector` <[string]> A [selector] to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ - `relativePoint` <[Object]> A point to click relative to the top-left corner of element padding box. If not specified, clicks to some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully clicked. The Promise will be rejected if there is no element matching `selector`.++This method fetches an element with `selector`, scrolls it into view if needed, and then uses [page.mouse](#pagemouse) to click in the center of the element.+If there's no element matching `selector`, the method throws an error.++Bear in mind that if `click()` triggers a navigation event and there's a separate `page.waitForNavigation()` promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:++```javascript+const [response] = await Promise.all([+ page.waitForNavigation(waitOptions),+ page.click(selector, clickOptions),+]);+```++Shortcut for [page.mainFrame().click(selector[, options])](#frameclickselector-options).++#### page.close([options])+- `options` <[Object]>+ - `runBeforeUnload` <[boolean]> Defaults to `false`. Whether to run the+ [before unload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload)+ page handlers.+- returns: <[Promise]>++By default, `page.close()` **does not** run beforeunload handlers.++> **NOTE** if `runBeforeUnload` is passed as true, a `beforeunload` dialog might be summoned+> and should be handled manually via page's ['dialog'](#event-dialog) event.++#### page.content()+- returns: <[Promise]<[string]>>++Gets the full HTML contents of the page, including the doctype.++#### page.cookies([...urls])+- `...urls` <...[string]>+- returns: <[Promise]<[Array]<[Object]>>>+ - `name` <[string]>+ - `value` <[string]>+ - `domain` <[string]>+ - `path` <[string]>+ - `expires` <[number]> Unix time in seconds.+ - `size` <[number]>+ - `httpOnly` <[boolean]>+ - `secure` <[boolean]>+ - `session` <[boolean]>+ - `sameSite` <"Strict"|"Lax"|"Extended"|"None">++If no URLs are specified, this method returns cookies for the current page URL.+If URLs are specified, only cookies for those URLs are returned.++#### page.coverage++- returns: <[Coverage]>++#### page.dblclick(selector[, options])+- `selector` <[string]> A [selector] to search for element to double click. If there are multiple elements satisfying the selector, the first will be double clicked.+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ - `relativePoint` <[Object]> A point to double click relative to the top-left corner of element padding box. If not specified, double clicks to some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the double click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully double clicked. The Promise will be rejected if there is no element matching `selector`.++This method fetches an element with `selector`, scrolls it into view if needed, and then uses [page.mouse](#pagemouse) to double click in the center of the element.+If there's no element matching `selector`, the method throws an error.++Bear in mind that if the first click of the `dblclick()` triggers a navigation event, there will be an exception.++> **NOTE** `page.dblclick()` dispatches two `click` events and a single `dblclick` event.++Shortcut for [page.mainFrame().dblclick(selector[, options])](#framedblclickselector-options).++#### page.deleteCookie(...cookies)+- `...cookies` <...[Object]>+ - `name` <[string]> **required**+ - `url` <[string]>+ - `domain` <[string]>+ - `path` <[string]>+- returns: <[Promise]>++#### page.emulate(options)+- `options` <[Object]>+ - `viewport` <[Object]>+ - `width` <[number]> page width in pixels.+ - `height` <[number]> page height in pixels.+ - `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.+ - `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account. Defaults to `false`.+ - `hasTouch`<[boolean]> Specifies if viewport supports touch events. Defaults to `false`+ - `isLandscape` <[boolean]> Specifies if viewport is in landscape mode. Defaults to `false`.+ - `userAgent` <[string]>+- returns: <[Promise]>++Emulates given device metrics and user agent. This method is a shortcut for calling two methods:+- [page.setUserAgent(userAgent)](#pagesetuseragentuseragent)+- [page.setViewport(viewport)](#pagesetviewportviewport)++To aid emulation, playwright provides a list of device descriptors which can be obtained via the [`playwright.devices`](#playwrightdevices).++`page.emulate` will resize the page. A lot of websites don't expect phones to change size, so you should emulate before navigating to the page.++```js+const playwright = require('playwright');+const iPhone = playwright.devices['iPhone 6'];++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.emulate(iPhone);+ await page.goto('https://www.google.com');+ // other actions...+ await browser.close();+})();+```++List of all available devices is available in the source code: [DeviceDescriptors.js](https://github.com/Microsoft/playwright/blob/master/lib/DeviceDescriptors.js).++#### page.emulateMedia(type)+- `type` <?[string]> Changes the CSS media type of the page. The only allowed values are `'screen'`, `'print'` and `null`. Passing `null` disables CSS media emulation.+- returns: <[Promise]>++**Note:** This method is deprecated, and only kept around as an alias for backwards compatibility. Use [`page.emulateMediaType(type)`](#pageemulatemediatypetype) instead.++#### page.emulateMediaFeatures(features)+- `features` <?[Array]<[Object]>> Given an array of media feature objects, emulates CSS media features on the page. Each media feature object must have the following properties:+ - `name` <[string]> The CSS media feature name. Supported names are `'prefers-colors-scheme'` and `'prefers-reduced-motion'`.+ - `value` <[string]> The value for the given CSS media feature.+- returns: <[Promise]>++```js+await page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: 'dark' }]);+await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches));+// → true+await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches));+// → false+await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches));+// → false++await page.emulateMediaFeatures([{ name: 'prefers-reduced-motion', value: 'reduce' }]);+await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches));+// → true+await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches));+// → false++await page.emulateMediaFeatures([+ { name: 'prefers-color-scheme', value: 'dark' },+ { name: 'prefers-reduced-motion', value: 'reduce' },+]);+await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches));+// → true+await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches));+// → false+await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches));+// → false+await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches));+// → true+await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches));+// → false+```++#### page.emulateMediaType(type)+- `type` <?[string]> Changes the CSS media type of the page. The only allowed values are `'screen'`, `'print'` and `null`. Passing `null` disables CSS media emulation.+- returns: <[Promise]>++```js+await page.evaluate(() => matchMedia('screen').matches));+// → true+await page.evaluate(() => matchMedia('print').matches));+// → true++await page.emulateMediaType('print');+await page.evaluate(() => matchMedia('screen').matches));+// → false+await page.evaluate(() => matchMedia('print').matches));+// → true++await page.emulateMediaType(null);+await page.evaluate(() => matchMedia('screen').matches));+// → true+await page.evaluate(() => matchMedia('print').matches));+// → true+```++#### page.emulateTimezone(timezoneId)+- `timezoneId` <?[string]> Changes the timezone of the page. See [ICU’s `metaZones.txt`](https://cs.chromium.org/chromium/src/third_party/icu/source/data/misc/metaZones.txt?rcl=faee8bc70570192d82d2978a71e2a615788597d1) for a list of supported timezone IDs. Passing `null` disables timezone emulation.+- returns: <[Promise]>++#### page.evaluate(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated in the page context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++If the function passed to the `page.evaluate` returns a [Promise], then `page.evaluate` would wait for the promise to resolve and return its value.++If the function passed to the `page.evaluate` returns a non-[Serializable] value, then `page.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.++Passing arguments to `pageFunction`:+```js+const result = await page.evaluate(x => {+ return Promise.resolve(8 * x);+}, 7);+console.log(result); // prints "56"+```++A string can also be passed in instead of a function:+```js+console.log(await page.evaluate('1 + 2')); // prints "3"+const x = 10;+console.log(await page.evaluate(`1 + ${x}`)); // prints "11"+```++[ElementHandle] instances can be passed as arguments to the `page.evaluate`:+```js+const bodyHandle = await page.$('body');+const html = await page.evaluate(body => body.innerHTML, bodyHandle);+await bodyHandle.dispose();+```++Shortcut for [page.mainFrame().evaluate(pageFunction, ...args)](#frameevaluatepagefunction-args).++#### page.evaluateHandle(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated in the page context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)++The only difference between `page.evaluate` and `page.evaluateHandle` is that `page.evaluateHandle` returns in-page object (JSHandle).++If the function passed to the `page.evaluateHandle` returns a [Promise], then `page.evaluateHandle` would wait for the promise to resolve and return its value.++A string can also be passed in instead of a function:+```js+const aHandle = await page.evaluateHandle('document'); // Handle for the 'document'+```++[JSHandle] instances can be passed as arguments to the `page.evaluateHandle`:+```js+const aHandle = await page.evaluateHandle(() => document.body);+const resultHandle = await page.evaluateHandle(body => body.innerHTML, aHandle);+console.log(await resultHandle.jsonValue());+await resultHandle.dispose();+```++Shortcut for [page.mainFrame().executionContext().evaluateHandle(pageFunction, ...args)](#executioncontextevaluatehandlepagefunction-args).++#### page.evaluateOnNewDocument(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated in browser context+- `...args` <...[Serializable]> Arguments to pass to `pageFunction`+- returns: <[Promise]>++Adds a function which would be invoked in one of the following scenarios:+- whenever the page is navigated+- whenever the child frame is attached or navigated. In this case, the function is invoked in the context of the newly attached frame++The function is invoked after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed `Math.random`.++An example of overriding the navigator.languages property before the page loads:++```js+// preload.js++// overwrite the `languages` property to use a custom getter+Object.defineProperty(navigator, "languages", {+ get: function() {+ return ["en-US", "en", "bn"];+ }+});++// In your playwright script, assuming the preload.js file is in same folder of our script+const preloadFile = fs.readFileSync('./preload.js', 'utf8');+await page.evaluateOnNewDocument(preloadFile);+```++#### page.exposeFunction(name, playwrightFunction)+- `name` <[string]> Name of the function on the window object+- `playwrightFunction` <[function]> Callback function which will be called in Playwright's context.+- returns: <[Promise]>++The method adds a function called `name` on the page's `window` object.+When called, the function executes `playwrightFunction` in node.js and returns a [Promise] which resolves to the return value of `playwrightFunction`.++If the `playwrightFunction` returns a [Promise], it will be awaited.++> **NOTE** Functions installed via `page.exposeFunction` survive navigations.++An example of adding an `md5` function into the page:+```js+const playwright = require('playwright');+const crypto = require('crypto');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ page.on('console', msg => console.log(msg.text()));+ await page.exposeFunction('md5', text =>+ crypto.createHash('md5').update(text).digest('hex')+ );+ await page.evaluate(async () => {+ // use window.md5 to compute hashes+ const myString = 'PLAYWRIGHT';+ const myHash = await window.md5(myString);+ console.log(`md5 of ${myString} is ${myHash}`);+ });+ await browser.close();+})();+```++An example of adding a `window.readfile` function into the page:++```js+const playwright = require('playwright');+const fs = require('fs');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ page.on('console', msg => console.log(msg.text()));+ await page.exposeFunction('readfile', async filePath => {+ return new Promise((resolve, reject) => {+ fs.readFile(filePath, 'utf8', (err, text) => {+ if (err)+ reject(err);+ else+ resolve(text);+ });+ });+ });+ await page.evaluate(async () => {+ // use window.readfile to read contents of a file+ const content = await window.readfile('/etc/hosts');+ console.log(content);+ });+ await browser.close();+})();+```++#### page.fill(selector, value)+- `selector` <[string]> A [selector] to query page for.+- `value` <[string]> Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully filled. The promise will be rejected if there is no element matching `selector`.++This method focuses the element and triggers an `input` event after filling.+If there's no text `<input>`, `<textarea>` or `[contenteditable]` element matching `selector`, the method throws an error.++Shortcut for [page.mainFrame().fill()](#framefillselector-value)++#### page.focus(selector)+- `selector` <[string]> A [selector] of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully focused. The promise will be rejected if there is no element matching `selector`.++This method fetches an element with `selector` and focuses it.+If there's no element matching `selector`, the method throws an error.++Shortcut for [page.mainFrame().focus(selector)](#framefocusselector).++#### page.frames()+- returns: <[Array]<[Frame]>> An array of all frames attached to the page.++#### page.goBack([options])+- `options` <[Object]> Navigation parameters which might have the following properties:+ - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.+ - `waitUntil` <[string]|[Array]<[string]>> When to consider navigation succeeded, defaults to `load`. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:+ - `load` - consider navigation to be finished when the `load` event is fired.+ - `domcontentloaded` - consider navigation to be finished when the `DOMContentLoaded` event is fired.+ - `networkidle0` - consider navigation to be finished when there are no more than 0 network connections for at least `500` ms.+ - `networkidle2` - consider navigation to be finished when there are no more than 2 network connections for at least `500` ms.+- returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If+can not go back, resolves to `null`.++Navigate to the previous page in history.++#### page.goForward([options])+- `options` <[Object]> Navigation parameters which might have the following properties:+ - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.+ - `waitUntil` <[string]|[Array]<[string]>> When to consider navigation succeeded, defaults to `load`. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:+ - `load` - consider navigation to be finished when the `load` event is fired.+ - `domcontentloaded` - consider navigation to be finished when the `DOMContentLoaded` event is fired.+ - `networkidle0` - consider navigation to be finished when there are no more than 0 network connections for at least `500` ms.+ - `networkidle2` - consider navigation to be finished when there are no more than 2 network connections for at least `500` ms.+- returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If+can not go forward, resolves to `null`.++Navigate to the next page in history.++#### page.goto(url[, options])+- `url` <[string]> URL to navigate page to. The url should include scheme, e.g. `https://`.+- `options` <[Object]> Navigation parameters which might have the following properties:+ - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.+ - `waitUntil` <[string]|[Array]<[string]>> When to consider navigation succeeded, defaults to `load`. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:+ - `load` - consider navigation to be finished when the `load` event is fired.+ - `domcontentloaded` - consider navigation to be finished when the `DOMContentLoaded` event is fired.+ - `networkidle0` - consider navigation to be finished when there are no more than 0 network connections for at least `500` ms.+ - `networkidle2` - consider navigation to be finished when there are no more than 2 network connections for at least `500` ms.+ - `referer` <[string]> Referer header value. If provided it will take preference over the referer header value set by [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders).+- returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.++`page.goto` will throw an error if:+- there's an SSL error (e.g. in case of self-signed certificates).+- target URL is invalid.+- the `timeout` is exceeded during navigation.+- the remote server does not respond or is unreachable.+- the main resource failed to load.++`page.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [response.status()](#responsestatus).++> **NOTE** `page.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.++> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).++Shortcut for [page.mainFrame().goto(url, options)](#framegotourl-options)++#### page.hover(selector[, options])+- `selector` <[string]> A [selector] to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.+- `options` <[Object]>+ - `relativePoint` <[Object]> A point to hover relative to the top-left corner of element padding box. If not specified, hovers over some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the hover, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully hovered. Promise gets rejected if there's no element matching `selector`.++This method fetches an element with `selector`, scrolls it into view if needed, and then uses [page.mouse](#pagemouse) to hover over the center of the element.+If there's no element matching `selector`, the method throws an error.++Shortcut for [page.mainFrame().hover(selector)](#framehoverselector).++#### page.isClosed()++- returns: <[boolean]>++Indicates that the page has been closed.++#### page.keyboard++- returns: <[Keyboard]>++#### page.mainFrame()+- returns: <[Frame]> The page's main frame.++Page is guaranteed to have a main frame which persists during navigations.++#### page.metrics()+- returns: <[Promise]<[Object]>> Object containing metrics as key/value pairs.+ - `Timestamp` <[number]> The timestamp when the metrics sample was taken.+ - `Documents` <[number]> Number of documents in the page.+ - `Frames` <[number]> Number of frames in the page.+ - `JSEventListeners` <[number]> Number of events in the page.+ - `Nodes` <[number]> Number of DOM nodes in the page.+ - `LayoutCount` <[number]> Total number of full or partial page layout.+ - `RecalcStyleCount` <[number]> Total number of page style recalculations.+ - `LayoutDuration` <[number]> Combined durations of all page layouts.+ - `RecalcStyleDuration` <[number]> Combined duration of all page style recalculations.+ - `ScriptDuration` <[number]> Combined duration of JavaScript execution.+ - `TaskDuration` <[number]> Combined duration of all tasks performed by the browser.+ - `JSHeapUsedSize` <[number]> Used JavaScript heap size.+ - `JSHeapTotalSize` <[number]> Total JavaScript heap size.++> **NOTE** All timestamps are in monotonic time: monotonically increasing time in seconds since an arbitrary point in the past.++#### page.mouse++- returns: <[Mouse]>++#### page.pdf([options])+- `options` <[Object]> Options object which might have the following properties:+ - `path` <[string]> The file path to save the PDF to. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the PDF won't be saved to the disk.+ - `scale` <[number]> Scale of the webpage rendering. Defaults to `1`. Scale amount must be between 0.1 and 2.+ - `displayHeaderFooter` <[boolean]> Display header and footer. Defaults to `false`.+ - `headerTemplate` <[string]> HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them:+ - `date` formatted print date+ - `title` document title+ - `url` document location+ - `pageNumber` current page number+ - `totalPages` total pages in the document+ - `footerTemplate` <[string]> HTML template for the print footer. Should use the same format as the `headerTemplate`.+ - `printBackground` <[boolean]> Print background graphics. Defaults to `false`.+ - `landscape` <[boolean]> Paper orientation. Defaults to `false`.+ - `pageRanges` <[string]> Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages.+ - `format` <[string]> Paper format. If set, takes priority over `width` or `height` options. Defaults to 'Letter'.+ - `width` <[string]|[number]> Paper width, accepts values labeled with units.+ - `height` <[string]|[number]> Paper height, accepts values labeled with units.+ - `margin` <[Object]> Paper margins, defaults to none.+ - `top` <[string]|[number]> Top margin, accepts values labeled with units.+ - `right` <[string]|[number]> Right margin, accepts values labeled with units.+ - `bottom` <[string]|[number]> Bottom margin, accepts values labeled with units.+ - `left` <[string]|[number]> Left margin, accepts values labeled with units.+ - `preferCSSPageSize` <[boolean]> Give any CSS `@page` size declared in the page priority over what is declared in `width` and `height` or `format` options. Defaults to `false`, which will scale the content to fit the paper size.+- returns: <[Promise]<[Buffer]>> Promise which resolves with PDF buffer.++> **NOTE** Generating a pdf is currently only supported in Chrome headless.++`page.pdf()` generates a pdf of the page with `print` css media. To generate a pdf with `screen` media, call [page.emulateMedia('screen')](#pageemulatemediamediatype) before calling `page.pdf()`:++> **NOTE** By default, `page.pdf()` generates a pdf with modified colors for printing. Use the [`-webkit-print-color-adjust`](https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-print-color-adjust) property to force rendering of exact colors.++```js+// Generates a PDF with 'screen' media type.+await page.emulateMedia('screen');+await page.pdf({path: 'page.pdf'});+```++The `width`, `height`, and `margin` options accept values labeled with units. Unlabeled values are treated as pixels.++A few examples:+- `page.pdf({width: 100})` - prints with width set to 100 pixels+- `page.pdf({width: '100px'})` - prints with width set to 100 pixels+- `page.pdf({width: '10cm'})` - prints with width set to 10 centimeters.++All possible units are:+- `px` - pixel+- `in` - inch+- `cm` - centimeter+- `mm` - millimeter++The `format` options are:+- `Letter`: 8.5in x 11in+- `Legal`: 8.5in x 14in+- `Tabloid`: 11in x 17in+- `Ledger`: 17in x 11in+- `A0`: 33.1in x 46.8in+- `A1`: 23.4in x 33.1in+- `A2`: 16.54in x 23.4in+- `A3`: 11.7in x 16.54in+- `A4`: 8.27in x 11.7in+- `A5`: 5.83in x 8.27in+- `A6`: 4.13in x 5.83in++> **NOTE** `headerTemplate` and `footerTemplate` markup have the following limitations:+> 1. Script tags inside templates are not evaluated.+> 2. Page styles are not visible inside templates.++#### page.queryObjects(prototypeHandle)+- `prototypeHandle` <[JSHandle]> A handle to the object prototype.+- returns: <[Promise]<[JSHandle]>> Promise which resolves to a handle to an array of objects with this prototype.++The method iterates the JavaScript heap and finds all the objects with the given prototype.++```js+// Create a Map object+await page.evaluate(() => window.map = new Map());+// Get a handle to the Map object prototype+const mapPrototype = await page.evaluateHandle(() => Map.prototype);+// Query all map instances into an array+const mapInstances = await page.queryObjects(mapPrototype);+// Count amount of map objects in heap+const count = await page.evaluate(maps => maps.length, mapInstances);+await mapInstances.dispose();+await mapPrototype.dispose();+```++Shortcut for [page.mainFrame().executionContext().queryObjects(prototypeHandle)](#executioncontextqueryobjectsprototypehandle).++#### page.reload([options])+- `options` <[Object]> Navigation parameters which might have the following properties:+ - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.+ - `waitUntil` <[string]|[Array]<[string]>> When to consider navigation succeeded, defaults to `load`. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:+ - `load` - consider navigation to be finished when the `load` event is fired.+ - `domcontentloaded` - consider navigation to be finished when the `DOMContentLoaded` event is fired.+ - `networkidle0` - consider navigation to be finished when there are no more than 0 network connections for at least `500` ms.+ - `networkidle2` - consider navigation to be finished when there are no more than 2 network connections for at least `500` ms.+- returns: <[Promise]<[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.++#### page.screenshot([options])+- `options` <[Object]> Options object which might have the following properties:+ - `path` <[string]> The file path to save the image to. The screenshot type will be inferred from file extension. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd). If no path is provided, the image won't be saved to the disk.+ - `type` <[string]> Specify screenshot type, can be either `jpeg` or `png`. Defaults to 'png'.+ - `quality` <[number]> The quality of the image, between 0-100. Not applicable to `png` images.+ - `fullPage` <[boolean]> When true, takes a screenshot of the full scrollable page. Defaults to `false`.+ - `clip` <[Object]> An object which specifies clipping region of the page. Should have the following fields:+ - `x` <[number]> x-coordinate of top-left corner of clip area+ - `y` <[number]> y-coordinate of top-left corner of clip area+ - `width` <[number]> width of clipping area+ - `height` <[number]> height of clipping area+ - `omitBackground` <[boolean]> Hides default white background and allows capturing screenshots with transparency. Defaults to `false`.+ - `encoding` <[string]> The encoding of the image, can be either `base64` or `binary`. Defaults to `binary`.+- returns: <[Promise]<[string]|[Buffer]>> Promise which resolves to buffer or a base64 string (depending on the value of `encoding`) with captured screenshot.++> **NOTE** Screenshots take at least 1/6 second on OS X. See https://crbug.com/741689 for discussion.++#### page.select(selector, ...values)+- `selector` <[string]> A [selector] to query page for+- `...values` <...[string]> Values of options to select. If the `<select>` has the `multiple` attribute, all values are considered, otherwise only the first one is taken into account.+- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.++Triggers a `change` and `input` event once all the provided options have been selected.+If there's no `<select>` element matching `selector`, the method throws an error.++```js+page.select('select#colors', 'blue'); // single selection+page.select('select#colors', 'red', 'green', 'blue'); // multiple selections+```++Shortcut for [page.mainFrame().select()](#frameselectselector-values)++#### page.setBypassCSP(enabled)+- `enabled` <[boolean]> sets bypassing of page's Content-Security-Policy.+- returns: <[Promise]>++Toggles bypassing page's Content-Security-Policy.++> **NOTE** CSP bypassing happens at the moment of CSP initialization rather then evaluation. Usually this means+that `page.setBypassCSP` should be called before navigating to the domain.++#### page.setCacheEnabled([enabled])+- `enabled` <[boolean]> sets the `enabled` state of the cache.+- returns: <[Promise]>++Toggles ignoring cache for each request based on the enabled state. By default, caching is enabled.++#### page.setContent(html[, options])+- `html` <[string]> HTML markup to assign to the page.+- `options` <[Object]> Parameters which might have the following properties:+ - `timeout` <[number]> Maximum time in milliseconds for resources to load, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.+ - `waitUntil` <[string]|[Array]<[string]>> When to consider setting markup succeeded, defaults to `load`. Given an array of event strings, setting content is considered to be successful after all events have been fired. Events can be either:+ - `load` - consider setting content to be finished when the `load` event is fired.+ - `domcontentloaded` - consider setting content to be finished when the `DOMContentLoaded` event is fired.+ - `networkidle0` - consider setting content to be finished when there are no more than 0 network connections for at least `500` ms.+ - `networkidle2` - consider setting content to be finished when there are no more than 2 network connections for at least `500` ms.+- returns: <[Promise]>++#### page.setCookie(...cookies)+- `...cookies` <...[Object]>+ - `name` <[string]> **required**+ - `value` <[string]> **required**+ - `url` <[string]>+ - `domain` <[string]>+ - `path` <[string]>+ - `expires` <[number]> Unix time in seconds.+ - `httpOnly` <[boolean]>+ - `secure` <[boolean]>+ - `sameSite` <"Strict"|"Lax">+- returns: <[Promise]>++```js+await page.setCookie(cookieObject1, cookieObject2);+```++#### page.setDefaultNavigationTimeout(timeout)+- `timeout` <[number]> Maximum navigation time in milliseconds++This setting will change the default maximum navigation time for the following methods and related shortcuts:+- [page.goBack([options])](#pagegobackoptions)+- [page.goForward([options])](#pagegoforwardoptions)+- [page.goto(url[, options])](#pagegotourl-options)+- [page.reload([options])](#pagereloadoptions)+- [page.setContent(html[, options])](#pagesetcontenthtml-options)+- [page.waitForNavigation([options])](#pagewaitfornavigationoptions)++> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout)+++#### page.setDefaultTimeout(timeout)+- `timeout` <[number]> Maximum time in milliseconds++This setting will change the default maximum time for the following methods and related shortcuts:+- [page.goBack([options])](#pagegobackoptions)+- [page.goForward([options])](#pagegoforwardoptions)+- [page.goto(url[, options])](#pagegotourl-options)+- [page.reload([options])](#pagereloadoptions)+- [page.setContent(html[, options])](#pagesetcontenthtml-options)+- [page.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])](#pagewaitforselectororfunctionortimeout-options-args)+- [page.waitForFileChooser([options])](#pagewaitforfilechooseroptions)+- [page.waitForFunction(pageFunction[, options[, ...args]])](#pagewaitforfunctionpagefunction-options-args)+- [page.waitForNavigation([options])](#pagewaitfornavigationoptions)+- [page.waitForRequest(urlOrPredicate[, options])](#pagewaitforrequesturlorpredicate-options)+- [page.waitForResponse(urlOrPredicate[, options])](#pagewaitforresponseurlorpredicate-options)+- [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options)+- [page.waitForXPath(xpath[, options])](#pagewaitforxpathxpath-options)++> **NOTE** [`page.setDefaultNavigationTimeout`](#pagesetdefaultnavigationtimeouttimeout) takes priority over [`page.setDefaultTimeout`](#pagesetdefaulttimeouttimeout)++#### page.setExtraHTTPHeaders(headers)+- `headers` <[Object]> An object containing additional HTTP headers to be sent with every request. All header values must be strings.+- returns: <[Promise]>++The extra HTTP headers will be sent with every request the page initiates.++> **NOTE** page.setExtraHTTPHeaders does not guarantee the order of headers in the outgoing requests.++#### page.setGeolocation(options)+- `options` <[Object]>+ - `latitude` <[number]> Latitude between -90 and 90.+ - `longitude` <[number]> Longitude between -180 and 180.+ - `accuracy` <[number]> Optional non-negative accuracy value.+- returns: <[Promise]>++Sets the page's geolocation.++```js+await page.setGeolocation({latitude: 59.95, longitude: 30.31667});+```++> **NOTE** Consider using [browserContext.overridePermissions](#browsercontextoverridepermissionsorigin-permissions) to grant permissions for the page to read its geolocation.++#### page.setJavaScriptEnabled(enabled)+- `enabled` <[boolean]> Whether or not to enable JavaScript on the page.+- returns: <[Promise]>++> **NOTE** changing this value won't affect scripts that have already been run. It will take full effect on the next [navigation](#pagegotourl-options).++#### page.setOfflineMode(enabled)+- `enabled` <[boolean]> When `true`, enables offline mode for the page.+- returns: <[Promise]>++#### page.setRequestInterception(value)+- `value` <[boolean]> Whether to enable request interception.+- returns: <[Promise]>++Activating request interception enables `request.abort`, `request.continue` and+`request.respond` methods. This provides the capability to modify network requests that are made by a page.++Once request interception is enabled, every request will stall unless it's continued, responded or aborted.+An example of a naïve request interceptor that aborts all image requests:++```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.setRequestInterception(true);+ page.on('request', interceptedRequest => {+ if (interceptedRequest.url().endsWith('.png') || interceptedRequest.url().endsWith('.jpg'))+ interceptedRequest.abort();+ else+ interceptedRequest.continue();+ });+ await page.goto('https://example.com');+ await browser.close();+})();+```++> **NOTE** Enabling request interception disables page caching.++#### page.setUserAgent(userAgent)+- `userAgent` <[string]> Specific user agent to use in this page+- returns: <[Promise]> Promise which resolves when the user agent is set.++#### page.setViewport(viewport)+- `viewport` <[Object]>+ - `width` <[number]> page width in pixels. **required**+ - `height` <[number]> page height in pixels. **required**+ - `deviceScaleFactor` <[number]> Specify device scale factor (can be thought of as dpr). Defaults to `1`.+ - `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account. Defaults to `false`.+ - `hasTouch`<[boolean]> Specifies if viewport supports touch events. Defaults to `false`+ - `isLandscape` <[boolean]> Specifies if viewport is in landscape mode. Defaults to `false`.+- returns: <[Promise]>++> **NOTE** in certain cases, setting viewport will reload the page in order to set the `isMobile` or `hasTouch` properties.++In the case of multiple pages in a single browser, each page can have its own viewport size.++`page.setViewport` will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport before navigating to the page.++```js+const page = await browser.newPage();+await page.setViewport({+ width: 640,+ height: 480,+ deviceScaleFactor: 1,+});+await page.goto('https://example.com');+```++#### page.tap(selector[, options])+- `selector` <[string]> A [selector] to search for element to tap. If there are multiple elements satisfying the selector, the first will be tapped.+- `options` <[Object]>+ - `relativePoint` <[Object]> A point to tap relative to the top-left corner of element padding box. If not specified, taps some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the tap, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]>++This method fetches an element with `selector`, scrolls it into view if needed, and then uses [page.touchscreen](#pagetouchscreen) to tap in the center of the element.+If there's no element matching `selector`, the method throws an error.++Shortcut for [page.mainFrame().tap(selector)](#frametapselector).++#### page.target()+- returns: <[Target]> a target this page was created from.++#### page.title()+- returns: <[Promise]<[string]>> The page's title.++Shortcut for [page.mainFrame().title()](#frametitle).++#### page.touchscreen+- returns: <[Touchscreen]>++#### page.tracing+- returns: <[Tracing]>++#### page.tripleclick(selector[, options])+- `selector` <[string]> A [selector] to search for element to triple click. If there are multiple elements satisfying the selector, the first will be triple clicked.+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ - `relativePoint` <[Object]> A point to triple click relative to the top-left corner of element padding box. If not specified, triple clicks to some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the triple click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully triple clicked. The Promise will be rejected if there is no element matching `selector`.++This method fetches an element with `selector`, scrolls it into view if needed, and then uses [page.mouse](#pagemouse) to triple click in the center of the element.+If there's no element matching `selector`, the method throws an error.++Bear in mind that if the first or second click of the `tripleclick()` triggers a navigation event, there will be an exception.++> **NOTE** `page.tripleclick()` dispatches three `click` events and a single `dblclick` event.++Shortcut for [page.mainFrame().tripleclick(selector[, options])](#frametripleclickselector-options).++#### page.type(selector, text[, options])+- `selector` <[string]> A [selector] of an element to type into. If there are multiple elements satisfying the selector, the first will be used.+- `text` <[string]> A text to type into a focused element.+- `options` <[Object]>+ - `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.+- returns: <[Promise]>++Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.++To press a special key, like `Control` or `ArrowDown`, use [`keyboard.press`](#keyboardpresskey-options).++```js+await page.type('#mytextarea', 'Hello'); // Types instantly+await page.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user+```++Shortcut for [page.mainFrame().type(selector, text[, options])](#frametypeselector-text-options).++#### page.url()+- returns: <[string]>++This is a shortcut for [page.mainFrame().url()](#frameurl)++#### page.viewport()+- returns: <?[Object]>+ - `width` <[number]> page width in pixels.+ - `height` <[number]> page height in pixels.+ - `deviceScaleFactor` <[number]> Specify device scale factor (can be though of as dpr). Defaults to `1`.+ - `isMobile` <[boolean]> Whether the `meta viewport` tag is taken into account. Defaults to `false`.+ - `hasTouch`<[boolean]> Specifies if viewport supports touch events. Defaults to `false`+ - `isLandscape` <[boolean]> Specifies if viewport is in landscape mode. Defaults to `false`.++#### page.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])+- `selectorOrFunctionOrTimeout` <[string]|[number]|[function]> A [selector], predicate or timeout to wait for+- `options` <[Object]> Optional waiting parameters+ - `visible` <[boolean]> wait for element to be present in DOM and to be visible. Defaults to `false`.+ - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.+ - `hidden` <[boolean]> wait for element to not be found in the DOM or to be hidden. Defaults to `false`.+ - `polling` <[string]|[number]> An interval at which the `pageFunction` is executed, defaults to `raf`. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. If `polling` is a string, then it can be one of the following values:+ - `raf` - to constantly execute `pageFunction` in `requestAnimationFrame` callback. This is the tightest polling mode which is suitable to observe styling changes.+ - `mutation` - to execute `pageFunction` on every DOM mutation.+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[JSHandle]>> Promise which resolves to a JSHandle of the success value++This method behaves differently with respect to the type of the first parameter:+- if `selectorOrFunctionOrTimeout` is a `string`, then the first argument is treated as a [selector] or [xpath], depending on whether or not it starts with '//', and the method is a shortcut for+ [page.waitForSelector](#pagewaitforselectorselector-options) or [page.waitForXPath](#pagewaitforxpathxpath-options)+- if `selectorOrFunctionOrTimeout` is a `function`, then the first argument is treated as a predicate to wait for and the method is a shortcut for [page.waitForFunction()](#pagewaitforfunctionpagefunction-options-args).+- if `selectorOrFunctionOrTimeout` is a `number`, then the first argument is treated as a timeout in milliseconds and the method returns a promise which resolves after the timeout+- otherwise, an exception is thrown++```js+// wait for selector+await page.waitFor('.foo');+// wait for 1 second+await page.waitFor(1000);+// wait for predicate+await page.waitFor(() => !!document.querySelector('.foo'));+```++To pass arguments from node.js to the predicate of `page.waitFor` function:++```js+const selector = '.foo';+await page.waitFor(selector => !!document.querySelector(selector), {}, selector);+```++Shortcut for [page.mainFrame().waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])](#framewaitforselectororfunctionortimeout-options-args).++#### page.waitForFileChooser([options])+- `options` <[Object]> Optional waiting parameters+ - `timeout` <[number]> Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.+- returns: <[Promise]<[FileChooser]>> A promise that resolves after a page requests a file picker.++> **NOTE** In non-headless Chromium, this method results in the native file picker dialog **not showing up** for the user.++This method is typically coupled with an action that triggers file choosing.+The following example clicks a button that issues a file chooser, and then+responds with `/tmp/myfile.pdf` as if a user has selected this file.++```js+const [fileChooser] = await Promise.all([+ page.waitForFileChooser(),+ page.click('#upload-file-button'), // some button that triggers file selection+]);+await fileChooser.accept(['/tmp/myfile.pdf']);+```++> **NOTE** This must be called *before* the file chooser is launched. It will not return a currently active file chooser.+++#### page.waitForFunction(pageFunction[, options[, ...args]])+- `pageFunction` <[function]|[string]> Function to be evaluated in browser context+- `options` <[Object]> Optional waiting parameters+ - `polling` <[string]|[number]> An interval at which the `pageFunction` is executed, defaults to `raf`. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. If `polling` is a string, then it can be one of the following values:+ - `raf` - to constantly execute `pageFunction` in `requestAnimationFrame` callback. This is the tightest polling mode which is suitable to observe styling changes.+ - `mutation` - to execute `pageFunction` on every DOM mutation.+ - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[JSHandle]>> Promise which resolves when the `pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value.++The `waitForFunction` can be used to observe viewport size change:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ const watchDog = page.waitForFunction('window.innerWidth < 100');+ await page.setViewport({width: 50, height: 50});+ await watchDog;+ await browser.close();+})();+```++To pass arguments from node.js to the predicate of `page.waitForFunction` function:++```js+const selector = '.foo';+await page.waitForFunction(selector => !!document.querySelector(selector), {}, selector);+```++Shortcut for [page.mainFrame().waitForFunction(pageFunction[, options[, ...args]])](#framewaitforfunctionpagefunction-options-args).++#### page.waitForNavigation([options])+- `options` <[Object]> Navigation parameters which might have the following properties:+ - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.+ - `waitUntil` <[string]|[Array]<[string]>> When to consider navigation succeeded, defaults to `load`. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:+ - `load` - consider navigation to be finished when the `load` event is fired.+ - `domcontentloaded` - consider navigation to be finished when the `DOMContentLoaded` event is fired.+ - `networkidle0` - consider navigation to be finished when there are no more than 0 network connections for at least `500` ms.+ - `networkidle2` - consider navigation to be finished when there are no more than 2 network connections for at least `500` ms.+- returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.++This resolves when the page navigates to a new URL or reloads. It is useful for when you run code+which will indirectly cause the page to navigate. Consider this example:++```js+const [response] = await Promise.all([+ page.waitForNavigation(), // The promise resolves after navigation has finished+ page.click('a.my-link'), // Clicking the link will indirectly cause a navigation+]);+```++**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.++Shortcut for [page.mainFrame().waitForNavigation(options)](#framewaitfornavigationoptions).++#### page.waitForRequest(urlOrPredicate[, options])+- `urlOrPredicate` <[string]|[Function]> A URL or predicate to wait for.+- `options` <[Object]> Optional waiting parameters+ - `timeout` <[number]> Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.+- returns: <[Promise]<[Request]>> Promise which resolves to the matched request.++```js+const firstRequest = await page.waitForRequest('http://example.com/resource');+const finalRequest = await page.waitForRequest(request => request.url() === 'http://example.com' && request.method() === 'GET');+return firstRequest.url();+```++#### page.waitForResponse(urlOrPredicate[, options])+- `urlOrPredicate` <[string]|[Function]> A URL or predicate to wait for.+- `options` <[Object]> Optional waiting parameters+ - `timeout` <[number]> Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.+- returns: <[Promise]<[Response]>> Promise which resolves to the matched response.++```js+const firstResponse = await page.waitForResponse('https://example.com/resource');+const finalResponse = await page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200);+return finalResponse.ok();+```++#### page.waitForSelector(selector[, options])+- `selector` <[string]> A [selector] of an element to wait for+- `options` <[Object]> Optional waiting parameters+ - `visible` <[boolean]> wait for element to be present in DOM and to be visible, i.e. to not have `display: none` or `visibility: hidden` CSS properties. Defaults to `false`.+ - `hidden` <[boolean]> wait for element to not be found in the DOM or to be hidden, i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to `false`.+ - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.+- returns: <[Promise]<?[ElementHandle]>> Promise which resolves when element specified by selector string is added to DOM. Resolves to `null` if waiting for `hidden: true` and selector is not found in DOM.++Wait for the `selector` to appear in page. If at the moment of calling+the method the `selector` already exists, the method will return+immediately. If the selector doesn't appear after the `timeout` milliseconds of waiting, the function will throw.++This method works across navigations:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ let currentURL;+ page+ .waitForSelector('img')+ .then(() => console.log('First URL with image: ' + currentURL));+ for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {+ await page.goto(currentURL);+ }+ await browser.close();+})();+```+Shortcut for [page.mainFrame().waitForSelector(selector[, options])](#framewaitforselectorselector-options).++#### page.waitForXPath(xpath[, options])+- `xpath` <[string]> A [xpath] of an element to wait for+- `options` <[Object]> Optional waiting parameters+ - `visible` <[boolean]> wait for element to be present in DOM and to be visible, i.e. to not have `display: none` or `visibility: hidden` CSS properties. Defaults to `false`.+ - `hidden` <[boolean]> wait for element to not be found in the DOM or to be hidden, i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to `false`.+ - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.+- returns: <[Promise]<?[ElementHandle]>> Promise which resolves when element specified by xpath string is added to DOM. Resolves to `null` if waiting for `hidden: true` and xpath is not found in DOM.++Wait for the `xpath` to appear in page. If at the moment of calling+the method the `xpath` already exists, the method will return+immediately. If the xpath doesn't appear after the `timeout` milliseconds of waiting, the function will throw.++This method works across navigations:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ let currentURL;+ page+ .waitForXPath('//img')+ .then(() => console.log('First URL with image: ' + currentURL));+ for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {+ await page.goto(currentURL);+ }+ await browser.close();+})();+```+Shortcut for [page.mainFrame().waitForXPath(xpath[, options])](#framewaitforxpathxpath-options).++#### page.workers()+- returns: <[Array]<[Worker]>>+This method returns all of the dedicated [WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) associated with the page.++> **NOTE** This does not contain ServiceWorkers++### class: Worker++The Worker class represents a [WebWorker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).+The events `workercreated` and `workerdestroyed` are emitted on the page object to signal the worker lifecycle.++```js+page.on('workercreated', worker => console.log('Worker created: ' + worker.url()));+page.on('workerdestroyed', worker => console.log('Worker destroyed: ' + worker.url()));++console.log('Current workers:');+for (const worker of page.workers())+ console.log(' ' + worker.url());+```++#### worker.evaluate(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated in the worker context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++If the function passed to the `worker.evaluate` returns a [Promise], then `worker.evaluate` would wait for the promise to resolve and return its value.++If the function passed to the `worker.evaluate` returns a non-[Serializable] value, then `worker.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.++Shortcut for [(await worker.executionContext()).evaluate(pageFunction, ...args)](#executioncontextevaluatepagefunction-args).++#### worker.evaluateHandle(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated in the page context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)++The only difference between `worker.evaluate` and `worker.evaluateHandle` is that `worker.evaluateHandle` returns in-page object (JSHandle).++If the function passed to the `worker.evaluateHandle` returns a [Promise], then `worker.evaluateHandle` would wait for the promise to resolve and return its value.++Shortcut for [(await worker.executionContext()).evaluateHandle(pageFunction, ...args)](#executioncontextevaluatehandlepagefunction-args).++#### worker.executionContext()+- returns: <[Promise]<[ExecutionContext]>>++#### worker.url()+- returns: <[string]>++### class: Accessibility++The Accessibility class provides methods for inspecting Chromium's accessibility tree. The accessibility tree is used by assistive technology such as [screen readers](https://en.wikipedia.org/wiki/Screen_reader) or [switches](https://en.wikipedia.org/wiki/Switch_access).++Accessibility is a very platform-specific thing. On different platforms, there are different screen readers that might have wildly different output.++Blink - Chrome's rendering engine - has a concept of "accessibility tree", which is then translated into different platform-specific APIs. Accessibility namespace gives users+access to the Blink Accessibility Tree.++Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or by assistive technologies themselves. By default, Playwright tries to approximate this filtering, exposing only the "interesting" nodes of the tree.++++#### accessibility.snapshot([options])+- `options` <[Object]>+ - `interestingOnly` <[boolean]> Prune uninteresting nodes from the tree. Defaults to `true`.+ - `root` <[ElementHandle]> The root DOM element for the snapshot. Defaults to the whole page.+- returns: <[Promise]<[Object]>> An [AXNode] object with the following properties:+ - `role` <[string]> The [role](https://www.w3.org/TR/wai-aria/#usage_intro).+ - `name` <[string]> A human readable name for the node.+ - `value` <[string]|[number]> The current value of the node.+ - `description` <[string]> An additional human readable description of the node.+ - `keyshortcuts` <[string]> Keyboard shortcuts associated with this node.+ - `roledescription` <[string]> A human readable alternative to the role.+ - `valuetext` <[string]> A description of the current value.+ - `disabled` <[boolean]> Whether the node is disabled.+ - `expanded` <[boolean]> Whether the node is expanded or collapsed.+ - `focused` <[boolean]> Whether the node is focused.+ - `modal` <[boolean]> Whether the node is [modal](https://en.wikipedia.org/wiki/Modal_window).+ - `multiline` <[boolean]> Whether the node text input supports multiline.+ - `multiselectable` <[boolean]> Whether more than one child can be selected.+ - `readonly` <[boolean]> Whether the node is read only.+ - `required` <[boolean]> Whether the node is required.+ - `selected` <[boolean]> Whether the node is selected in its parent node.+ - `checked` <[boolean]|"mixed"> Whether the checkbox is checked, or "mixed".+ - `pressed` <[boolean]|"mixed"> Whether the toggle button is checked, or "mixed".+ - `level` <[number]> The level of a heading.+ - `valuemin` <[number]> The minimum value in a node.+ - `valuemax` <[number]> The maximum value in a node.+ - `autocomplete` <[string]> What kind of autocomplete is supported by a control.+ - `haspopup` <[string]> What kind of popup is currently being shown for a node.+ - `invalid` <[string]> Whether and in what way this node's value is invalid.+ - `orientation` <[string]> Whether the node is oriented horizontally or vertically.+ - `children` <[Array]<[Object]>> Child [AXNode]s of this node, if any.++Captures the current state of the accessibility tree. The returned object represents the root accessible node of the page.++> **NOTE** The Chromium accessibility tree contains nodes that go unused on most platforms and by+most screen readers. Playwright will discard them as well for an easier to process tree,+unless `interestingOnly` is set to `false`.++An example of dumping the entire accessibility tree:+```js+const snapshot = await page.accessibility.snapshot();+console.log(snapshot);+```++An example of logging the focused node's name:+```js+const snapshot = await page.accessibility.snapshot();+const node = findFocusedNode(snapshot);+console.log(node && node.name);++function findFocusedNode(node) {+ if (node.focused)+ return node;+ for (const child of node.children || []) {+ const foundNode = findFocusedNode(child);+ return foundNode;+ }+ return null;+}+```++### class: Keyboard++Keyboard provides an api for managing a virtual keyboard. The high level api is [`keyboard.type`](#keyboardtypetext-options), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page.++For finer control, you can use [`keyboard.down`](#keyboarddownkey-options), [`keyboard.up`](#keyboardupkey), and [`keyboard.sendCharacter`](#keyboardsendcharacterchar) to manually fire events as if they were generated from a real keyboard.++An example of holding down `Shift` in order to select and delete some text:+```js+await page.keyboard.type('Hello World!');+await page.keyboard.press('ArrowLeft');++await page.keyboard.down('Shift');+for (let i = 0; i < ' World'.length; i++)+ await page.keyboard.press('ArrowLeft');+await page.keyboard.up('Shift');++await page.keyboard.press('Backspace');+// Result text will end up saying 'Hello!'+```++An example of pressing `A`+```js+await page.keyboard.down('Shift');+await page.keyboard.press('KeyA');+await page.keyboard.up('Shift');+```++> **NOTE** On MacOS, keyboard shortcuts like `⌘ A` -> Select All do not work. See [#1313](https://github.com/GoogleChrome/puppeteer/issues/1313)++#### keyboard.down(key[, options])+- `key` <[string]> Name of key to press, such as `ArrowLeft`. See [USKeyboardLayout] for a list of all key names.+- `options` <[Object]>+ - `text` <[string]> If specified, generates an input event with this text.+- returns: <[Promise]>++Dispatches a `keydown` event.++If `key` is a single character and no modifier keys besides `Shift` are being held down, a `keypress`/`input` event will also generated. The `text` option can be specified to force an input event to be generated.++If `key` is a modifier key, `Shift`, `Meta`, `Control`, or `Alt`, subsequent key presses will be sent with that modifier active. To release the modifier key, use [`keyboard.up`](#keyboardupkey).++After the key is pressed once, subsequent calls to [`keyboard.down`](#keyboarddownkey-options) will have [repeat](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat) set to true. To release the key, use [`keyboard.up`](#keyboardupkey).++> **NOTE** Modifier keys DO influence `keyboard.down`. Holding down `Shift` will type the text in upper case.++#### keyboard.press(key[, options])+- `key` <[string]> Name of key to press, such as `ArrowLeft`. See [USKeyboardLayout] for a list of all key names.+- `options` <[Object]>+ - `text` <[string]> If specified, generates an input event with this text.+ - `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.+- returns: <[Promise]>++If `key` is a single character and no modifier keys besides `Shift` are being held down, a `keypress`/`input` event will also generated. The `text` option can be specified to force an input event to be generated.++> **NOTE** Modifier keys DO effect `keyboard.press`. Holding down `Shift` will type the text in upper case.++Shortcut for [`keyboard.down`](#keyboarddownkey-options) and [`keyboard.up`](#keyboardupkey).++#### keyboard.sendCharacter(char)+- `char` <[string]> Character to send into the page.+- returns: <[Promise]>++Dispatches a `keypress` and `input` event. This does not send a `keydown` or `keyup` event.++```js+page.keyboard.sendCharacter('嗨');+```++> **NOTE** Modifier keys DO NOT effect `keyboard.sendCharacter`. Holding down `Shift` will not type the text in upper case.++#### keyboard.type(text[, options])+- `text` <[string]> A text to type into a focused element.+- `options` <[Object]>+ - `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.+- returns: <[Promise]>++Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.++To press a special key, like `Control` or `ArrowDown`, use [`keyboard.press`](#keyboardpresskey-options).++```js+await page.keyboard.type('Hello'); // Types instantly+await page.keyboard.type('World', {delay: 100}); // Types slower, like a user+```++> **NOTE** Modifier keys DO NOT effect `keyboard.type`. Holding down `Shift` will not type the text in upper case.++#### keyboard.up(key)+- `key` <[string]> Name of key to release, such as `ArrowLeft`. See [USKeyboardLayout] for a list of all key names.+- returns: <[Promise]>++Dispatches a `keyup` event.++### class: Mouse++The Mouse class operates in main-frame CSS pixels relative to the top-left corner of the viewport.++Every `page` object has its own Mouse, accessible with [`page.mouse`](#pagemouse).++```js+// Using ‘page.mouse’ to trace a 100x100 square.+await page.mouse.move(0, 0);+await page.mouse.down();+await page.mouse.move(0, 100);+await page.mouse.move(100, 100);+await page.mouse.move(100, 0);+await page.mouse.move(0, 0);+await page.mouse.up();+```++#### mouse.click(x, y[, options])+- `x` <[number]>+- `y` <[number]>+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+- returns: <[Promise]>++Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownoptions) and [`mouse.up`](#mouseupoptions).++#### mouse.dblclick(x, y[, options])+- `x` <[number]>+- `y` <[number]>+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+- returns: <[Promise]>++Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownoptions), [`mouse.up`](#mouseupoptions), [`mouse.down`](#mousedownoptions) and [`mouse.up`](#mouseupoptions).++#### mouse.down([options])+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].+- returns: <[Promise]>++Dispatches a `mousedown` event.++#### mouse.move(x, y[, options])+- `x` <[number]>+- `y` <[number]>+- `options` <[Object]>+ - `steps` <[number]> defaults to 1. Sends intermediate `mousemove` events.+- returns: <[Promise]>++Dispatches a `mousemove` event.++#### mouse.tripleclick(x, y[, options])+- `x` <[number]>+- `y` <[number]>+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+- returns: <[Promise]>++Shortcut for [`mouse.move`](#mousemovex-y-options), [`mouse.down`](#mousedownoptions), [`mouse.up`](#mouseupoptions), [`mouse.down`](#mousedownoptions), [`mouse.up`](#mouseupoptions), [`mouse.down`](#mousedownoptions) and [`mouse.up`](#mouseupoptions).++#### mouse.up([options])+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].+- returns: <[Promise]>++Dispatches a `mouseup` event.++### class: Touchscreen++#### touchscreen.tap(x, y)+- `x` <[number]>+- `y` <[number]>+- returns: <[Promise]>++Dispatches a `touchstart` and `touchend` event.++### class: Tracing++You can use [`tracing.start`](#tracingstartoptions) and [`tracing.stop`](#tracingstop) to create a trace file which can be opened in Chrome DevTools or [timeline viewer](https://chromedevtools.github.io/timeline-viewer/).++```js+await page.tracing.start({path: 'trace.json'});+await page.goto('https://www.google.com');+await page.tracing.stop();+```++#### tracing.start([options])+- `options` <[Object]>+ - `path` <[string]> A path to write the trace file to.+ - `screenshots` <[boolean]> captures screenshots in the trace.+ - `categories` <[Array]<[string]>> specify custom categories to use instead of default.+- returns: <[Promise]>++Only one trace can be active at a time per browser.++#### tracing.stop()+- returns: <[Promise]<[Buffer]>> Promise which resolves to buffer with trace data.++### class: FileChooser++[FileChooser] objects are returned via the ['page.waitForFileChooser'](#pagewaitforfilechooseroptions) method.++File choosers let you react to the page requesting for a file.++An example of using [FileChooser]:++```js+const [fileChooser] = await Promise.all([+ page.waitForFileChooser(),+ page.click('#upload-file-button'), // some button that triggers file selection+]);+await fileChooser.accept(['/tmp/myfile.pdf']);+```++> **NOTE** In browsers, only one file chooser can be opened at a time.+> All file choosers must be accepted or canceled. Not doing so will prevent subsequent file choosers from appearing.++#### fileChooser.accept(filePaths)+- `filePaths` <[Array]<[string]>> Accept the file chooser request with given paths. If some of the `filePaths` are relative paths, then they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd).+- returns: <[Promise]>++#### fileChooser.cancel()+- returns: <[Promise]>++Closes the file chooser without selecting any files.++#### fileChooser.isMultiple()+- returns: <[boolean]> Whether file chooser allow for [multiple](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#attr-multiple) file selection.++### class: Dialog++[Dialog] objects are dispatched by page via the ['dialog'](#event-dialog) event.++An example of using `Dialog` class:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ page.on('dialog', async dialog => {+ console.log(dialog.message());+ await dialog.dismiss();+ await browser.close();+ });+ page.evaluate(() => alert('1'));+})();+```++#### dialog.accept([promptText])+- `promptText` <[string]> A text to enter in prompt. Does not cause any effects if the dialog's `type` is not prompt.+- returns: <[Promise]> Promise which resolves when the dialog has been accepted.++#### dialog.defaultValue()+- returns: <[string]> If dialog is prompt, returns default prompt value. Otherwise, returns empty string.++#### dialog.dismiss()+- returns: <[Promise]> Promise which resolves when the dialog has been dismissed.++#### dialog.message()+- returns: <[string]> A message displayed in the dialog.++#### dialog.type()+- returns: <[string]> Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`.++### class: ConsoleMessage++[ConsoleMessage] objects are dispatched by page via the ['console'](#event-console) event.++#### consoleMessage.args()+- returns: <[Array]<[JSHandle]>>++#### consoleMessage.location()+- returns: <[Object]>+ - `url` <[string]> URL of the resource if known or `undefined` otherwise.+ - `lineNumber` <[number]> 0-based line number in the resource if known or `undefined` otherwise.+ - `columnNumber` <[number]> 0-based column number in the resource if known or `undefined` otherwise.++#### consoleMessage.text()+- returns: <[string]>++#### consoleMessage.type()+- returns: <[string]>++One of the following values: `'log'`, `'debug'`, `'info'`, `'error'`, `'warning'`, `'dir'`, `'dirxml'`, `'table'`, `'trace'`, `'clear'`, `'startGroup'`, `'startGroupCollapsed'`, `'endGroup'`, `'assert'`, `'profile'`, `'profileEnd'`, `'count'`, `'timeEnd'`.++### class: Frame++At every point of time, page exposes its current frame tree via the [page.mainFrame()](#pagemainframe) and [frame.childFrames()](#framechildframes) methods.++[Frame] object's lifecycle is controlled by three events, dispatched on the page object:+- ['frameattached'](#event-frameattached) - fired when the frame gets attached to the page. A Frame can be attached to the page only once.+- ['framenavigated'](#event-framenavigated) - fired when the frame commits navigation to a different URL.+- ['framedetached'](#event-framedetached) - fired when the frame gets detached from the page. A Frame can be detached from the page only once.++An example of dumping frame tree:++```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto('https://www.google.com/chrome/browser/canary.html');+ dumpFrameTree(page.mainFrame(), '');+ await browser.close();++ function dumpFrameTree(frame, indent) {+ console.log(indent + frame.url());+ for (const child of frame.childFrames()) {+ dumpFrameTree(child, indent + ' ');+ }+ }+})();+```++An example of getting text from an iframe element:++```js+ const frame = page.frames().find(frame => frame.name() === 'myframe');+ const text = await frame.$eval('.selector', element => element.textContent);+ console.log(text);+```++#### frame.$(selector)+- `selector` <[string]> A [selector] to query frame for+- returns: <[Promise]<?[ElementHandle]>> Promise which resolves to ElementHandle pointing to the frame element.++The method queries frame for the selector. If there's no such element within the frame, the method will resolve to `null`.++#### frame.$$(selector)+- `selector` <[string]> A [selector] to query frame for+- returns: <[Promise]<[Array]<[ElementHandle]>>> Promise which resolves to ElementHandles pointing to the frame elements.++The method runs `document.querySelectorAll` within the frame. If no elements match the selector, the return value resolves to `[]`.++#### frame.$$eval(selector, pageFunction[, ...args])+- `selector` <[string]> A [selector] to query frame for+- `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++This method runs `Array.from(document.querySelectorAll(selector))` within the frame and passes it as the first argument to `pageFunction`.++If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.++Examples:+```js+const divsCounts = await frame.$$eval('div', divs => divs.length);+```++#### frame.$eval(selector, pageFunction[, ...args])+- `selector` <[string]> A [selector] to query frame for+- `pageFunction` <[function]\([Element]\)> Function to be evaluated in browser context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++This method runs `document.querySelector` within the frame and passes it as the first argument to `pageFunction`. If there's no element matching `selector`, the method throws an error.++If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.++Examples:+```js+const searchValue = await frame.$eval('#search', el => el.value);+const preloadHref = await frame.$eval('link[rel=preload]', el => el.href);+const html = await frame.$eval('.main-container', e => e.outerHTML);+```++#### frame.$x(expression)+- `expression` <[string]> Expression to [evaluate](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate).+- returns: <[Promise]<[Array]<[ElementHandle]>>>++The method evaluates the XPath expression.++#### frame.addScriptTag(options)+- `options` <[Object]>+ - `url` <[string]> URL of a script to be added.+ - `path` <[string]> Path to the JavaScript file to be injected into frame. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).+ - `content` <[string]> Raw JavaScript content to be injected into frame.+ - `type` <[string]> Script type. Use 'module' in order to load a Javascript ES6 module. See [script](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) for more details.+- returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the script's onload fires or when the script content was injected into frame.++Adds a `<script>` tag into the page with the desired url or content.++#### frame.addStyleTag(options)+- `options` <[Object]>+ - `url` <[string]> URL of the `<link>` tag.+ - `path` <[string]> Path to the CSS file to be injected into frame. If `path` is a relative path, then it is resolved relative to [current working directory](https://nodejs.org/api/process.html#process_process_cwd).+ - `content` <[string]> Raw CSS content to be injected into frame.+- returns: <[Promise]<[ElementHandle]>> which resolves to the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.++Adds a `<link rel="stylesheet">` tag into the page with the desired url or a `<style type="text/css">` tag with the content.++#### frame.childFrames()+- returns: <[Array]<[Frame]>>++#### frame.click(selector[, options])+- `selector` <[string]> A [selector] to search for element to click. If there are multiple elements satisfying the selector, the first will be clicked.+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ - `relativePoint` <[Object]> A point to click relative to the top-left corner of element padding box. If not specified, clicks to some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully clicked. The Promise will be rejected if there is no element matching `selector`.++This method fetches an element with `selector`, scrolls it into view if needed, and then uses [page.mouse](#pagemouse) to click in the center of the element.+If there's no element matching `selector`, the method throws an error.++Bear in mind that if `click()` triggers a navigation event and there's a separate `page.waitForNavigation()` promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:++```javascript+const [response] = await Promise.all([+ page.waitForNavigation(waitOptions),+ frame.click(selector, clickOptions),+]);+```++#### frame.content()+- returns: <[Promise]<[string]>>++Gets the full HTML contents of the frame, including the doctype.++#### frame.dblclick(selector[, options])+- `selector` <[string]> A [selector] to search for element to double click. If there are multiple elements satisfying the selector, the first will be double clicked.+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ - `relativePoint` <[Object]> A point to double click relative to the top-left corner of element padding box. If not specified, double clicks to some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the double click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully double clicked. The Promise will be rejected if there is no element matching `selector`.++This method fetches an element with `selector`, scrolls it into view if needed, and then uses [page.mouse](#pagemouse) to double click in the center of the element.+If there's no element matching `selector`, the method throws an error.++Bear in mind that if the first click of the `dblclick()` triggers a navigation event, there will be an exception.++> **NOTE** `frame.dblclick()` dispatches two `click` events and a single `dblclick` event.++#### frame.evaluate(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated in browser context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++If the function passed to the `frame.evaluate` returns a [Promise], then `frame.evaluate` would wait for the promise to resolve and return its value.++If the function passed to the `frame.evaluate` returns a non-[Serializable] value, then `frame.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.++```js+const result = await frame.evaluate(() => {+ return Promise.resolve(8 * 7);+});+console.log(result); // prints "56"+```++A string can also be passed in instead of a function.++```js+console.log(await frame.evaluate('1 + 2')); // prints "3"+```++[ElementHandle] instances can be passed as arguments to the `frame.evaluate`:+```js+const bodyHandle = await frame.$('body');+const html = await frame.evaluate(body => body.innerHTML, bodyHandle);+await bodyHandle.dispose();+```++#### frame.evaluateHandle(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated in the page context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)++The only difference between `frame.evaluate` and `frame.evaluateHandle` is that `frame.evaluateHandle` returns in-page object (JSHandle).++If the function, passed to the `frame.evaluateHandle`, returns a [Promise], then `frame.evaluateHandle` would wait for the promise to resolve and return its value.++```js+const aWindowHandle = await frame.evaluateHandle(() => Promise.resolve(window));+aWindowHandle; // Handle for the window object.+```++A string can also be passed in instead of a function.++```js+const aHandle = await frame.evaluateHandle('document'); // Handle for the 'document'.+```++[JSHandle] instances can be passed as arguments to the `frame.evaluateHandle`:+```js+const aHandle = await frame.evaluateHandle(() => document.body);+const resultHandle = await frame.evaluateHandle(body => body.innerHTML, aHandle);+console.log(await resultHandle.jsonValue());+await resultHandle.dispose();+```+++#### frame.executionContext()+- returns: <[Promise]<[ExecutionContext]>>++Returns promise that resolves to the frame's default execution context.++#### frame.fill(selector, value)+- `selector` <[string]> A [selector] to query page for.+- `value` <[string]> Value to fill for the `<input>`, `<textarea>` or `[contenteditable]` element.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully filled. The promise will be rejected if there is no element matching `selector`.++This method focuses the element and triggers an `input` event after filling.+If there's no text `<input>`, `<textarea>` or `[contenteditable]` element matching `selector`, the method throws an error.++#### frame.focus(selector)+- `selector` <[string]> A [selector] of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully focused. The promise will be rejected if there is no element matching `selector`.++This method fetches an element with `selector` and focuses it.+If there's no element matching `selector`, the method throws an error.++#### frame.goto(url[, options])+- `url` <[string]> URL to navigate frame to. The url should include scheme, e.g. `https://`.+- `options` <[Object]> Navigation parameters which might have the following properties:+ - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.+ - `waitUntil` <[string]|[Array]<[string]>> When to consider navigation succeeded, defaults to `load`. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:+ - `load` - consider navigation to be finished when the `load` event is fired.+ - `domcontentloaded` - consider navigation to be finished when the `DOMContentLoaded` event is fired.+ - `networkidle0` - consider navigation to be finished when there are no more than 0 network connections for at least `500` ms.+ - `networkidle2` - consider navigation to be finished when there are no more than 2 network connections for at least `500` ms.+ - `referer` <[string]> Referer header value. If provided it will take preference over the referer header value set by [page.setExtraHTTPHeaders()](#pagesetextrahttpheadersheaders).+- returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.++`frame.goto` will throw an error if:+- there's an SSL error (e.g. in case of self-signed certificates).+- target URL is invalid.+- the `timeout` is exceeded during navigation.+- the remote server does not respond or is unreachable.+- the main resource failed to load.++`frame.goto` will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling [response.status()](#responsestatus).++> **NOTE** `frame.goto` either throws an error or returns a main resource response. The only exceptions are navigation to `about:blank` or navigation to the same URL with a different hash, which would succeed and return `null`.++> **NOTE** Headless mode doesn't support navigation to a PDF document. See the [upstream issue](https://bugs.chromium.org/p/chromium/issues/detail?id=761295).+++#### frame.hover(selector[, options])+- `selector` <[string]> A [selector] to search for element to hover. If there are multiple elements satisfying the selector, the first will be hovered.+- `options` <[Object]>+ - `relativePoint` <[Object]> A point to hover relative to the top-left corner of element padding box. If not specified, hovers over some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the hover, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully hovered. Promise gets rejected if there's no element matching `selector`.++This method fetches an element with `selector`, scrolls it into view if needed, and then uses [page.mouse](#pagemouse) to hover over the center of the element.+If there's no element matching `selector`, the method throws an error.++#### frame.isDetached()+- returns: <[boolean]>++Returns `true` if the frame has been detached, or `false` otherwise.++#### frame.name()+- returns: <[string]>++Returns frame's name attribute as specified in the tag.++If the name is empty, returns the id attribute instead.++> **NOTE** This value is calculated once when the frame is created, and will not update if the attribute is changed later.++#### frame.parentFrame()+- returns: <?[Frame]> Parent frame, if any. Detached frames and main frames return `null`.++#### frame.select(selector, ...values)+- `selector` <[string]> A [selector] to query frame for+- `...values` <...[string]> Values of options to select. If the `<select>` has the `multiple` attribute, all values are considered, otherwise only the first one is taken into account.+- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.++Triggers a `change` and `input` event once all the provided options have been selected.+If there's no `<select>` element matching `selector`, the method throws an error.++```js+frame.select('select#colors', 'blue'); // single selection+frame.select('select#colors', 'red', 'green', 'blue'); // multiple selections+```++#### frame.setContent(html[, options])+- `html` <[string]> HTML markup to assign to the page.+- `options` <[Object]> Parameters which might have the following properties:+ - `timeout` <[number]> Maximum time in milliseconds for resources to load, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.+ - `waitUntil` <[string]|[Array]<[string]>> When to consider setting markup succeeded, defaults to `load`. Given an array of event strings, setting content is considered to be successful after all events have been fired. Events can be either:+ - `load` - consider setting content to be finished when the `load` event is fired.+ - `domcontentloaded` - consider setting content to be finished when the `DOMContentLoaded` event is fired.+ - `networkidle0` - consider setting content to be finished when there are no more than 0 network connections for at least `500` ms.+ - `networkidle2` - consider setting content to be finished when there are no more than 2 network connections for at least `500` ms.+- returns: <[Promise]>++#### frame.tap(selector[, options])+- `selector` <[string]> A [selector] to search for element to tap. If there are multiple elements satisfying the selector, the first will be tapped.+- `options` <[Object]>+ - `relativePoint` <[Object]> A point to tap relative to the top-left corner of element padding box. If not specified, taps some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the tap, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]>++This method fetches an element with `selector`, scrolls it into view if needed, and then uses [page.touchscreen](#pagetouchscreen) to tap in the center of the element.+If there's no element matching `selector`, the method throws an error.++#### frame.title()+- returns: <[Promise]<[string]>> The page's title.++#### frame.tripleclick(selector[, options])+- `selector` <[string]> A [selector] to search for element to triple click. If there are multiple elements satisfying the selector, the first will be triple clicked.+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ - `relativePoint` <[Object]> A point to triple click relative to the top-left corner of element padding box. If not specified, triple clicks to some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the triple click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element matching `selector` is successfully triple clicked. The Promise will be rejected if there is no element matching `selector`.++This method fetches an element with `selector`, scrolls it into view if needed, and then uses [page.mouse](#pagemouse) to triple click in the center of the element.+If there's no element matching `selector`, the method throws an error.++Bear in mind that if the first or second click of the `tripleclick()` triggers a navigation event, there will be an exception.++> **NOTE** `frame.tripleclick()` dispatches three `click` events and a single `dblclick` event.++#### frame.type(selector, text[, options])+- `selector` <[string]> A [selector] of an element to type into. If there are multiple elements satisfying the selector, the first will be used.+- `text` <[string]> A text to type into a focused element.+- `options` <[Object]>+ - `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.+- returns: <[Promise]>++Sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.++To press a special key, like `Control` or `ArrowDown`, use [`keyboard.press`](#keyboardpresskey-options).++```js+await frame.type('#mytextarea', 'Hello'); // Types instantly+await frame.type('#mytextarea', 'World', {delay: 100}); // Types slower, like a user+```++#### frame.url()+- returns: <[string]>++Returns frame's url.++#### frame.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]])+- `selectorOrFunctionOrTimeout` <[string]|[number]|[function]> A [selector], predicate or timeout to wait for+- `options` <[Object]> Optional waiting parameters+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[JSHandle]>> Promise which resolves to a JSHandle of the success value++This method behaves differently with respect to the type of the first parameter:+- if `selectorOrFunctionOrTimeout` is a `string`, then the first argument is treated as a [selector] or [xpath], depending on whether or not it starts with '//', and the method is a shortcut for+ [frame.waitForSelector](#framewaitforselectorselector-options) or [frame.waitForXPath](#framewaitforxpathxpath-options)+- if `selectorOrFunctionOrTimeout` is a `function`, then the first argument is treated as a predicate to wait for and the method is a shortcut for [frame.waitForFunction()](#framewaitforfunctionpagefunction-options-args).+- if `selectorOrFunctionOrTimeout` is a `number`, then the first argument is treated as a timeout in milliseconds and the method returns a promise which resolves after the timeout+- otherwise, an exception is thrown++```js+// wait for selector+await page.waitFor('.foo');+// wait for 1 second+await page.waitFor(1000);+// wait for predicate+await page.waitFor(() => !!document.querySelector('.foo'));+```++To pass arguments from node.js to the predicate of `page.waitFor` function:++```js+const selector = '.foo';+await page.waitFor(selector => !!document.querySelector(selector), {}, selector);+```++#### frame.waitForFunction(pageFunction[, options[, ...args]])+- `pageFunction` <[function]|[string]> Function to be evaluated in browser context+- `options` <[Object]> Optional waiting parameters+ - `polling` <[string]|[number]> An interval at which the `pageFunction` is executed, defaults to `raf`. If `polling` is a number, then it is treated as an interval in milliseconds at which the function would be executed. If `polling` is a string, then it can be one of the following values:+ - `raf` - to constantly execute `pageFunction` in `requestAnimationFrame` callback. This is the tightest polling mode which is suitable to observe styling changes.+ - `mutation` - to execute `pageFunction` on every DOM mutation.+ - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[JSHandle]>> Promise which resolves when the `pageFunction` returns a truthy value. It resolves to a JSHandle of the truthy value.++The `waitForFunction` can be used to observe viewport size change:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ const watchDog = page.mainFrame().waitForFunction('window.innerWidth < 100');+ page.setViewport({width: 50, height: 50});+ await watchDog;+ await browser.close();+})();+```++To pass arguments from node.js to the predicate of `page.waitForFunction` function:++```js+const selector = '.foo';+await page.waitForFunction(selector => !!document.querySelector(selector), {}, selector);+```++#### frame.waitForNavigation([options])+- `options` <[Object]> Navigation parameters which might have the following properties:+ - `timeout` <[number]> Maximum navigation time in milliseconds, defaults to 30 seconds, pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultNavigationTimeout(timeout)](#pagesetdefaultnavigationtimeouttimeout) or [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) methods.+ - `waitUntil` <[string]|[Array]<[string]>> When to consider navigation succeeded, defaults to `load`. Given an array of event strings, navigation is considered to be successful after all events have been fired. Events can be either:+ - `load` - consider navigation to be finished when the `load` event is fired.+ - `domcontentloaded` - consider navigation to be finished when the `DOMContentLoaded` event is fired.+ - `networkidle0` - consider navigation to be finished when there are no more than 0 network connections for at least `500` ms.+ - `networkidle2` - consider navigation to be finished when there are no more than 2 network connections for at least `500` ms.+- returns: <[Promise]<?[Response]>> Promise which resolves to the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. In case of navigation to a different anchor or navigation due to History API usage, the navigation will resolve with `null`.++This resolves when the frame navigates to a new URL. It is useful for when you run code+which will indirectly cause the frame to navigate. Consider this example:++```js+const [response] = await Promise.all([+ frame.waitForNavigation(), // The navigation promise resolves after navigation has finished+ frame.click('a.my-link'), // Clicking the link will indirectly cause a navigation+]);+```++**NOTE** Usage of the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) to change the URL is considered a navigation.+++#### frame.waitForSelector(selector[, options])+- `selector` <[string]> A [selector] of an element to wait for+- `options` <[Object]> Optional waiting parameters+ - `visible` <[boolean]> wait for element to be present in DOM and to be visible, i.e. to not have `display: none` or `visibility: hidden` CSS properties. Defaults to `false`.+ - `hidden` <[boolean]> wait for element to not be found in the DOM or to be hidden, i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to `false`.+ - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.+- returns: <[Promise]<?[ElementHandle]>> Promise which resolves when element specified by selector string is added to DOM. Resolves to `null` if waiting for `hidden: true` and selector is not found in DOM.++Wait for the `selector` to appear in page. If at the moment of calling+the method the `selector` already exists, the method will return+immediately. If the selector doesn't appear after the `timeout` milliseconds of waiting, the function will throw.++This method works across navigations:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ let currentURL;+ page.mainFrame()+ .waitForSelector('img')+ .then(() => console.log('First URL with image: ' + currentURL));+ for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {+ await page.goto(currentURL);+ }+ await browser.close();+})();+```++#### frame.waitForXPath(xpath[, options])+- `xpath` <[string]> A [xpath] of an element to wait for+- `options` <[Object]> Optional waiting parameters+ - `visible` <[boolean]> wait for element to be present in DOM and to be visible, i.e. to not have `display: none` or `visibility: hidden` CSS properties. Defaults to `false`.+ - `hidden` <[boolean]> wait for element to not be found in the DOM or to be hidden, i.e. have `display: none` or `visibility: hidden` CSS properties. Defaults to `false`.+ - `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the [page.setDefaultTimeout(timeout)](#pagesetdefaulttimeouttimeout) method.+- returns: <[Promise]<?[ElementHandle]>> Promise which resolves when element specified by xpath string is added to DOM. Resolves to `null` if waiting for `hidden: true` and xpath is not found in DOM.++Wait for the `xpath` to appear in page. If at the moment of calling+the method the `xpath` already exists, the method will return+immediately. If the xpath doesn't appear after the `timeout` milliseconds of waiting, the function will throw.++This method works across navigations:+```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ let currentURL;+ page.mainFrame()+ .waitForXPath('//img')+ .then(() => console.log('First URL with image: ' + currentURL));+ for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {+ await page.goto(currentURL);+ }+ await browser.close();+})();+```++### class: ExecutionContext++The class represents a context for JavaScript execution. A [Page] might have many execution contexts:+- each [frame](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) has "default" execution context that is+ always created after frame is attached to DOM. This context is returned by the [`frame.executionContext()`](#frameexecutioncontext) method.+- [Extensions](https://developer.chrome.com/extensions)'s content scripts create additional execution contexts.++Besides pages, execution contexts can be found in [workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API).++#### executionContext.evaluate(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated in `executionContext`+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++If the function passed to the `executionContext.evaluate` returns a [Promise], then `executionContext.evaluate` would wait for the promise to resolve and return its value.++If the function passed to the `executionContext.evaluate` returns a non-[Serializable] value, then `executionContext.evaluate` resolves to `undefined`. DevTools Protocol also supports transferring some additional values that are not serializable by `JSON`: `-0`, `NaN`, `Infinity`, `-Infinity`, and bigint literals.++```js+const executionContext = await page.mainFrame().executionContext();+const result = await executionContext.evaluate(() => Promise.resolve(8 * 7));+console.log(result); // prints "56"+```++A string can also be passed in instead of a function.++```js+console.log(await executionContext.evaluate('1 + 2')); // prints "3"+```++[JSHandle] instances can be passed as arguments to the `executionContext.evaluate`:+```js+const oneHandle = await executionContext.evaluateHandle(() => 1);+const twoHandle = await executionContext.evaluateHandle(() => 2);+const result = await executionContext.evaluate((a, b) => a + b, oneHandle, twoHandle);+await oneHandle.dispose();+await twoHandle.dispose();+console.log(result); // prints '3'.+```++#### executionContext.evaluateHandle(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated in the `executionContext`+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)++The only difference between `executionContext.evaluate` and `executionContext.evaluateHandle` is that `executionContext.evaluateHandle` returns in-page object (JSHandle).++If the function passed to the `executionContext.evaluateHandle` returns a [Promise], then `executionContext.evaluateHandle` would wait for the promise to resolve and return its value.++```js+const context = await page.mainFrame().executionContext();+const aHandle = await context.evaluateHandle(() => Promise.resolve(self));+aHandle; // Handle for the global object.+```++A string can also be passed in instead of a function.++```js+const aHandle = await context.evaluateHandle('1 + 2'); // Handle for the '3' object.+```++[JSHandle] instances can be passed as arguments to the `executionContext.evaluateHandle`:+```js+const aHandle = await context.evaluateHandle(() => document.body);+const resultHandle = await context.evaluateHandle(body => body.innerHTML, aHandle);+console.log(await resultHandle.jsonValue()); // prints body's innerHTML+await aHandle.dispose();+await resultHandle.dispose();+```++#### executionContext.frame()+- returns: <?[Frame]> Frame associated with this execution context.++> **NOTE** Not every execution context is associated with a frame. For example, workers and extensions have execution contexts that are not associated with frames.+++#### executionContext.queryObjects(prototypeHandle)+- `prototypeHandle` <[JSHandle]> A handle to the object prototype.+- returns: <[Promise]<[JSHandle]>> A handle to an array of objects with this prototype++The method iterates the JavaScript heap and finds all the objects with the given prototype.++```js+// Create a Map object+await page.evaluate(() => window.map = new Map());+// Get a handle to the Map object prototype+const mapPrototype = await page.evaluateHandle(() => Map.prototype);+// Query all map instances into an array+const mapInstances = await page.queryObjects(mapPrototype);+// Count amount of map objects in heap+const count = await page.evaluate(maps => maps.length, mapInstances);+await mapInstances.dispose();+await mapPrototype.dispose();+```++### class: JSHandle++JSHandle represents an in-page JavaScript object. JSHandles can be created with the [page.evaluateHandle](#pageevaluatehandlepagefunction-args) method.++```js+const windowHandle = await page.evaluateHandle(() => window);+// ...+```++JSHandle prevents the referenced JavaScript object being garbage collected unless the handle is [disposed](#jshandledispose). JSHandles are auto-disposed when their origin frame gets navigated or the parent context gets destroyed.++JSHandle instances can be used as arguments in [`page.$eval()`](#pageevalselector-pagefunction-args), [`page.evaluate()`](#pageevaluatepagefunction-args) and [`page.evaluateHandle`](#pageevaluatehandlepagefunction-args) methods.++#### jsHandle.asElement()+- returns: <?[ElementHandle]>++Returns either `null` or the object handle itself, if the object handle is an instance of [ElementHandle].++#### jsHandle.dispose()+- returns: <[Promise]> Promise which resolves when the object handle is successfully disposed.++The `jsHandle.dispose` method stops referencing the element handle.++#### jsHandle.evaluate(pageFunction[, ...args])+- `pageFunction` <[function]\([Object]\)> Function to be evaluated in browser context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++This method passes this handle as the first argument to `pageFunction`.++If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its value.++Examples:+```js+const tweetHandle = await page.$('.tweet .retweets');+expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10');+```++#### jsHandle.evaluateHandle(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)++This method passes this handle as the first argument to `pageFunction`.++The only difference between `jsHandle.evaluate` and `jsHandle.evaluateHandle` is that `executionContext.evaluateHandle` returns in-page object (JSHandle).++If the function passed to the `jsHandle.evaluateHandle` returns a [Promise], then `jsHandle.evaluateHandle` would wait for the promise to resolve and return its value.++See [Page.evaluateHandle](#pageevaluatehandlepagefunction-args) for more details.++#### jsHandle.executionContext()+- returns: <[ExecutionContext]>++Returns execution context the handle belongs to.++#### jsHandle.getProperties()+- returns: <[Promise]<[Map]<[string], [JSHandle]>>>++The method returns a map with property names as keys and JSHandle instances for the property values.++```js+const handle = await page.evaluateHandle(() => ({window, document}));+const properties = await handle.getProperties();+const windowHandle = properties.get('window');+const documentHandle = properties.get('document');+await handle.dispose();+```++#### jsHandle.getProperty(propertyName)+- `propertyName` <[string]> property to get+- returns: <[Promise]<[JSHandle]>>++Fetches a single property from the referenced object.++#### jsHandle.jsonValue()+- returns: <[Promise]<[Object]>>++Returns a JSON representation of the object. If the object has a+[`toJSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON()_behavior)+function, it **will not be called**.++> **NOTE** The method will return an empty JSON object if the referenced object is not stringifiable. It will throw an error if the object has circular references.++### class: ElementHandle+* extends: [JSHandle]++ElementHandle represents an in-page DOM element. ElementHandles can be created with the [page.$](#pageselector) method.++```js+const playwright = require('playwright');++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto('https://example.com');+ const hrefElement = await page.$('a');+ await hrefElement.click();+ // ...+})();+```++ElementHandle prevents DOM element from garbage collection unless the handle is [disposed](#elementhandledispose). ElementHandles are auto-disposed when their origin frame gets navigated.++ElementHandle instances can be used as arguments in [`page.$eval()`](#pageevalselector-pagefunction-args) and [`page.evaluate()`](#pageevaluatepagefunction-args) methods.++#### elementHandle.$(selector)+- `selector` <[string]> A [selector] to query element for+- returns: <[Promise]<?[ElementHandle]>>++The method runs `element.querySelector` within the page. If no element matches the selector, the return value resolves to `null`.++#### elementHandle.$$(selector)+- `selector` <[string]> A [selector] to query element for+- returns: <[Promise]<[Array]<[ElementHandle]>>>++The method runs `element.querySelectorAll` within the page. If no elements match the selector, the return value resolves to `[]`.++#### elementHandle.$$eval(selector, pageFunction[, ...args])+- `selector` <[string]> A [selector] to query page for+- `pageFunction` <[function]\([Array]<[Element]>\)> Function to be evaluated in browser context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++This method runs `document.querySelectorAll` within the element and passes it as the first argument to `pageFunction`. If there's no element matching `selector`, the method throws an error.++If `pageFunction` returns a [Promise], then `frame.$$eval` would wait for the promise to resolve and return its value.++Examples:+```html+<div class="feed">+ <div class="tweet">Hello!</div>+ <div class="tweet">Hi!</div>+</div>+```+```js+const feedHandle = await page.$('.feed');+expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))).toEqual(['Hello!', 'Hi!']);+```++#### elementHandle.$eval(selector, pageFunction[, ...args])+- `selector` <[string]> A [selector] to query page for+- `pageFunction` <[function]\([Element]\)> Function to be evaluated in browser context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++This method runs `document.querySelector` within the element and passes it as the first argument to `pageFunction`. If there's no element matching `selector`, the method throws an error.++If `pageFunction` returns a [Promise], then `frame.$eval` would wait for the promise to resolve and return its value.++Examples:+```js+const tweetHandle = await page.$('.tweet');+expect(await tweetHandle.$eval('.like', node => node.innerText)).toBe('100');+expect(await tweetHandle.$eval('.retweets', node => node.innerText)).toBe('10');+```++#### elementHandle.$x(expression)+- `expression` <[string]> Expression to [evaluate](https://developer.mozilla.org/en-US/docs/Web/API/Document/evaluate).+- returns: <[Promise]<[Array]<[ElementHandle]>>>++The method evaluates the XPath expression relative to the elementHandle. If there are no such elements, the method will resolve to an empty array.++#### elementHandle.asElement()+- returns: <[ElementHandle]>++#### elementHandle.boundingBox()+- returns: <[Promise]<?[Object]>>+ - x <[number]> the x coordinate of the element in pixels.+ - y <[number]> the y coordinate of the element in pixels.+ - width <[number]> the width of the element in pixels.+ - height <[number]> the height of the element in pixels.++This method returns the bounding box of the element (relative to the main frame), or `null` if the element is not visible.++#### elementHandle.boxModel()+- returns: <[Promise]<?[Object]>>+ - content <[Array]<[Object]>> Content box.+ - x <[number]>+ - y <[number]>+ - padding <[Array]<[Object]>> Padding box.+ - x <[number]>+ - y <[number]>+ - border <[Array]<[Object]>> Border box.+ - x <[number]>+ - y <[number]>+ - margin <[Array]<[Object]>> Margin box.+ - x <[number]>+ - y <[number]>+ - width <[number]> Element's width.+ - height <[number]> Element's height.++This method returns boxes of the element, or `null` if the element is not visible. Boxes are represented as an array of points; each Point is an object `{x, y}`. Box points are sorted clock-wise.++#### elementHandle.click([options])+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `clickCount` <[number]> defaults to 1. See [UIEvent.detail].+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ - `relativePoint` <[Object]> A point to click relative to the top-left corner of element padding box. If not specified, clicks to some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element is successfully clicked. Promise gets rejected if the element is detached from DOM.++This method scrolls element into view if needed, and then uses [page.mouse](#pagemouse) to click in the center of the element.+If the element is detached from DOM, the method throws an error.++#### elementHandle.contentFrame()+- returns: <[Promise]<?[Frame]>> Resolves to the content frame for element handles referencing iframe nodes, or null otherwise++#### elementHandle.dblclick([options])+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ - `relativePoint` <[Object]> A point to double click relative to the top-left corner of element padding box. If not specified, double clicks to some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the double click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element is successfully double clicked. Promise gets rejected if the element is detached from DOM.++This method scrolls element into view if needed, and then uses [page.mouse](#pagemouse) to click in the center of the element.+If the element is detached from DOM, the method throws an error.++Bear in mind that if the first click of the `dblclick()` triggers a navigation event, there will be an exception.++> **NOTE** `elementHandle.dblclick()` dispatches two `click` events and a single `dblclick` event.++#### elementHandle.dispose()+- returns: <[Promise]> Promise which resolves when the element handle is successfully disposed.++The `elementHandle.dispose` method stops referencing the element handle.++#### elementHandle.evaluate(pageFunction[, ...args])+- `pageFunction` <[function]\([Object]\)> Function to be evaluated in browser context+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[Serializable]>> Promise which resolves to the return value of `pageFunction`++This method passes this handle as the first argument to `pageFunction`.++If `pageFunction` returns a [Promise], then `handle.evaluate` would wait for the promise to resolve and return its value.++Examples:+```js+const tweetHandle = await page.$('.tweet .retweets');+expect(await tweetHandle.evaluate(node => node.innerText)).toBe('10');+```++#### elementHandle.evaluateHandle(pageFunction[, ...args])+- `pageFunction` <[function]|[string]> Function to be evaluated+- `...args` <...[Serializable]|[JSHandle]> Arguments to pass to `pageFunction`+- returns: <[Promise]<[JSHandle]>> Promise which resolves to the return value of `pageFunction` as in-page object (JSHandle)++This method passes this handle as the first argument to `pageFunction`.++The only difference between `evaluateHandle.evaluate` and `evaluateHandle.evaluateHandle` is that `executionContext.evaluateHandle` returns in-page object (JSHandle).++If the function passed to the `evaluateHandle.evaluateHandle` returns a [Promise], then `evaluateHandle.evaluateHandle` would wait for the promise to resolve and return its value.++See [Page.evaluateHandle](#pageevaluatehandlepagefunction-args) for more details.++#### elementHandle.executionContext()+- returns: <[ExecutionContext]>++#### elementHandle.fill(value)+- `value` <[string]> Value to set for the `<input>`, `<textarea>` or `[contenteditable]` element.+- returns: <[Promise]> Promise which resolves when the element is successfully filled.++This method focuses the element and triggers an `input` event after filling.+If element is not a text `<input>`, `<textarea>` or `[contenteditable]` element, the method throws an error.++#### elementHandle.focus()+- returns: <[Promise]>++Calls [focus](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on the element.++#### elementHandle.getProperties()+- returns: <[Promise]<[Map]<[string], [JSHandle]>>>++The method returns a map with property names as keys and JSHandle instances for the property values.++```js+const listHandle = await page.evaluateHandle(() => document.body.children);+const properties = await listHandle.getProperties();+const children = [];+for (const property of properties.values()) {+ const element = property.asElement();+ if (element)+ children.push(element);+}+children; // holds elementHandles to all children of document.body+```++#### elementHandle.getProperty(propertyName)+- `propertyName` <[string]> property to get+- returns: <[Promise]<[JSHandle]>>++Fetches a single property from the objectHandle.++#### elementHandle.hover([options])+- `options` <[Object]>+ - `relativePoint` <[Object]> A point to hover relative to the top-left corner of element padding box. If not specified, hovers over some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the hover, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element is successfully hovered.++This method scrolls element into view if needed, and then uses [page.mouse](#pagemouse) to hover over the center of the element.+If the element is detached from DOM, the method throws an error.++#### elementHandle.isIntersectingViewport()+- returns: <[Promise]<[boolean]>> Resolves to true if the element is visible in the current viewport.++#### elementHandle.jsonValue()+- returns: <[Promise]<[Object]>>++Returns a JSON representation of the object. The JSON is generated by running [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) on the object in page and consequent [`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) in playwright.++> **NOTE** The method will throw if the referenced object is not stringifiable.++#### elementHandle.press(key[, options])+- `key` <[string]> Name of key to press, such as `ArrowLeft`. See [USKeyboardLayout] for a list of all key names.+- `options` <[Object]>+ - `text` <[string]> If specified, generates an input event with this text.+ - `delay` <[number]> Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0.+- returns: <[Promise]>++Focuses the element, and then uses [`keyboard.down`](#keyboarddownkey-options) and [`keyboard.up`](#keyboardupkey).++If `key` is a single character and no modifier keys besides `Shift` are being held down, a `keypress`/`input` event will also be generated. The `text` option can be specified to force an input event to be generated.++> **NOTE** Modifier keys DO effect `elementHandle.press`. Holding down `Shift` will type the text in upper case.++#### elementHandle.screenshot([options])+- `options` <[Object]> Same options as in [page.screenshot](#pagescreenshotoptions).+- returns: <[Promise]<[string]|[Buffer]>> Promise which resolves to buffer or a base64 string (depending on the value of `options.encoding`) with captured screenshot.++This method scrolls element into view if needed, and then uses [page.screenshot](#pagescreenshotoptions) to take a screenshot of the element.+If the element is detached from DOM, the method throws an error.++#### elementHandle.select(...values)+- `...values` <...[string]> Values of options to select. If the `<select>` has the `multiple` attribute, all values are considered, otherwise only the first one is taken into account.+- returns: <[Promise]<[Array]<[string]>>> An array of option values that have been successfully selected.++Triggers a `change` and `input` event once all the provided options have been selected.+If element is not a `<select>` element, the method throws an error.++```js+handle.select('blue'); // single selection+handle.select('red', 'green', 'blue'); // multiple selections+```++#### elementHandle.tap([options])+- `options` <[Object]>+ - `relativePoint` <[Object]> A point to tap relative to the top-left corner of element padding box. If not specified, taps some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the tap, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element is successfully tapped. Promise gets rejected if the element is detached from DOM.++This method scrolls element into view if needed, and then uses [touchscreen.tap](#touchscreentapx-y) to tap in the center of the element.+If the element is detached from DOM, the method throws an error.++#### elementHandle.toString()+- returns: <[string]>++#### elementHandle.tripleclick([options])+- `options` <[Object]>+ - `button` <"left"|"right"|"middle"> Defaults to `left`.+ - `delay` <[number]> Time to wait between `mousedown` and `mouseup` in milliseconds. Defaults to 0.+ - `relativePoint` <[Object]> A point to triple click relative to the top-left corner of element padding box. If not specified, triple clicks to some visible point of the element.+ - x <[number]>+ - y <[number]>+ - `modifiers` <[Array]<"Alt"|"Control"|"Meta"|"Shift">> Modifier keys to press. Ensures that only these modifiers are pressed during the triple click, and then restores current modifiers back. If not specified, currently pressed modifiers are used.+- returns: <[Promise]> Promise which resolves when the element is successfully triple clicked. Promise gets rejected if the element is detached from DOM.++This method scrolls element into view if needed, and then uses [page.mouse](#pagemouse) to click in the center of the element.+If the element is detached from DOM, the method throws an error.++Bear in mind that if the first or second click of the `tripleclick()` triggers a navigation event, there will be an exception.++> **NOTE** `elementHandle.tripleclick()` dispatches three `click` events and a single `dblclick` event.++#### elementHandle.type(text[, options])+- `text` <[string]> A text to type into a focused element.+- `options` <[Object]>+ - `delay` <[number]> Time to wait between key presses in milliseconds. Defaults to 0.+- returns: <[Promise]>++Focuses the element, and then sends a `keydown`, `keypress`/`input`, and `keyup` event for each character in the text.++To press a special key, like `Control` or `ArrowDown`, use [`elementHandle.press`](#elementhandlepresskey-options).++```js+await elementHandle.type('Hello'); // Types instantly+await elementHandle.type('World', {delay: 100}); // Types slower, like a user+```++An example of typing into a text field and then submitting the form:+```js+const elementHandle = await page.$('input');+await elementHandle.type('some text');+await elementHandle.press('Enter');+```++#### elementHandle.uploadFile(...filePaths)+- `...filePaths` <...[string]> Sets the value of the file input to these paths. If some of the `filePaths` are relative paths, then they are resolved relative to the [current working directory](https://nodejs.org/api/process.html#process_process_cwd).+- returns: <[Promise]>++This method expects `elementHandle` to point to an [input element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input).++### class: Request++Whenever the page sends a request, such as for a network resource, the following events are emitted by playwright's page:+- [`'request'`](#event-request) emitted when the request is issued by the page.+- [`'response'`](#event-response) emitted when/if the response is received for the request.+- [`'requestfinished'`](#event-requestfinished) emitted when the response body is downloaded and the request is complete.++If request fails at some point, then instead of `'requestfinished'` event (and possibly instead of 'response' event), the [`'requestfailed'`](#event-requestfailed) event is emitted.++> **NOTE** HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with `'requestfinished'` event.++If request gets a 'redirect' response, the request is successfully finished with the 'requestfinished' event, and a new request is issued to a redirected url.++#### request.abort([errorCode])+- `errorCode` <[string]> Optional error code. Defaults to `failed`, could be+ one of the following:+ - `aborted` - An operation was aborted (due to user action)+ - `accessdenied` - Permission to access a resource, other than the network, was denied+ - `addressunreachable` - The IP address is unreachable. This usually means+ that there is no route to the specified host or network.+ - `blockedbyclient` - The client chose to block the request.+ - `blockedbyresponse` - The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks, for instance).+ - `connectionaborted` - A connection timed out as a result of not receiving an ACK for data sent.+ - `connectionclosed` - A connection was closed (corresponding to a TCP FIN).+ - `connectionfailed` - A connection attempt failed.+ - `connectionrefused` - A connection attempt was refused.+ - `connectionreset` - A connection was reset (corresponding to a TCP RST).+ - `internetdisconnected` - The Internet connection has been lost.+ - `namenotresolved` - The host name could not be resolved.+ - `timedout` - An operation timed out.+ - `failed` - A generic failure occurred.+- returns: <[Promise]>++Aborts request. To use this, request interception should be enabled with `page.setRequestInterception`.+Exception is immediately thrown if the request interception is not enabled.++#### request.continue([overrides])+- `overrides` <[Object]> Optional request overwrites, which can be one of the following:+ - `url` <[string]> If set, the request url will be changed. This is not a redirect. The request will be silently forwarded to the new url. For example, the address bar will show the original url.+ - `method` <[string]> If set changes the request method (e.g. `GET` or `POST`)+ - `postData` <[string]> If set changes the post data of request+ - `headers` <[Object]> If set changes the request HTTP headers. Header values will be converted to a string.+- returns: <[Promise]>++Continues request with optional request overrides. To use this, request interception should be enabled with `page.setRequestInterception`.+Exception is immediately thrown if the request interception is not enabled.++```js+await page.setRequestInterception(true);+page.on('request', request => {+ // Override headers+ const headers = Object.assign({}, request.headers(), {+ foo: 'bar', // set "foo" header+ origin: undefined, // remove "origin" header+ });+ request.continue({headers});+});+```++#### request.failure()+- returns: <?[Object]> Object describing request failure, if any+ - `errorText` <[string]> Human-readable error message, e.g. `'net::ERR_FAILED'`.++The method returns `null` unless this request was failed, as reported by+`requestfailed` event.++Example of logging all failed requests:++```js+page.on('requestfailed', request => {+ console.log(request.url() + ' ' + request.failure().errorText);+});+```++#### request.frame()+- returns: <?[Frame]> A [Frame] that initiated this request, or `null` if navigating to error pages.++#### request.headers()+- returns: <[Object]> An object with HTTP headers associated with the request. All header names are lower-case.++#### request.isNavigationRequest()+- returns: <[boolean]>++Whether this request is driving frame's navigation.++#### request.method()+- returns: <[string]> Request's method (GET, POST, etc.)++#### request.postData()+- returns: <[string]> Request's post body, if any.++#### request.redirectChain()+- returns: <[Array]<[Request]>>++A `redirectChain` is a chain of requests initiated to fetch a resource.+- If there are no redirects and the request was successful, the chain will be empty.+- If a server responds with at least a single redirect, then the chain will+contain all the requests that were redirected.++`redirectChain` is shared between all the requests of the same chain.++For example, if the website `http://example.com` has a single redirect to+`https://example.com`, then the chain will contain one request:++```js+const response = await page.goto('http://example.com');+const chain = response.request().redirectChain();+console.log(chain.length); // 1+console.log(chain[0].url()); // 'http://example.com'+```++If the website `https://google.com` has no redirects, then the chain will be empty:+```js+const response = await page.goto('https://google.com');+const chain = response.request().redirectChain();+console.log(chain.length); // 0+```++#### request.resourceType()+- returns: <[string]>++Contains the request's resource type as it was perceived by the rendering engine.+ResourceType will be one of the following: `document`, `stylesheet`, `image`, `media`, `font`, `script`, `texttrack`, `xhr`, `fetch`, `eventsource`, `websocket`, `manifest`, `other`.++#### request.respond(response)+- `response` <[Object]> Response that will fulfill this request+ - `status` <[number]> Response status code, defaults to `200`.+ - `headers` <[Object]> Optional response headers. Header values will be converted to a string.+ - `contentType` <[string]> If set, equals to setting `Content-Type` response header+ - `body` <[string]|[Buffer]> Optional response body+- returns: <[Promise]>++Fulfills request with given response. To use this, request interception should+be enabled with `page.setRequestInterception`. Exception is thrown if+request interception is not enabled.++An example of fulfilling all requests with 404 responses:++```js+await page.setRequestInterception(true);+page.on('request', request => {+ request.respond({+ status: 404,+ contentType: 'text/plain',+ body: 'Not Found!'+ });+});+```++> **NOTE** Mocking responses for dataURL requests is not supported.+> Calling `request.respond` for a dataURL request is a noop.++#### request.response()+- returns: <?[Response]> A matching [Response] object, or `null` if the response has not been received yet.++#### request.url()+- returns: <[string]> URL of the request.++### class: Response++[Response] class represents responses which are received by page.++#### response.buffer()+- returns: <Promise<[Buffer]>> Promise which resolves to a buffer with response body.++#### response.frame()+- returns: <?[Frame]> A [Frame] that initiated this response, or `null` if navigating to error pages.++#### response.fromCache()+- returns: <[boolean]>++True if the response was served from either the browser's disk cache or memory cache.++#### response.fromServiceWorker()+- returns: <[boolean]>++True if the response was served by a service worker.++#### response.headers()+- returns: <[Object]> An object with HTTP headers associated with the response. All header names are lower-case.++#### response.json()+- returns: <Promise<[Object]>> Promise which resolves to a JSON representation of response body.++This method will throw if the response body is not parsable via `JSON.parse`.++#### response.ok()+- returns: <[boolean]>++Contains a boolean stating whether the response was successful (status in the range 200-299) or not.++#### response.remoteAddress()+- returns: <[Object]>+ - `ip` <[string]> the IP address of the remote server+ - `port` <[number]> the port used to connect to the remote server++#### response.request()+- returns: <[Request]> A matching [Request] object.++#### response.securityDetails()+- returns: <?[SecurityDetails]> Security details if the response was received over the secure connection, or `null` otherwise.++#### response.status()+- returns: <[number]>++Contains the status code of the response (e.g., 200 for a success).++#### response.statusText()+- returns: <[string]>++Contains the status text of the response (e.g. usually an "OK" for a success).++#### response.text()+- returns: <[Promise]<[string]>> Promise which resolves to a text representation of response body.++#### response.url()+- returns: <[string]>++Contains the URL of the response.++### class: SecurityDetails++[SecurityDetails] class represents the security details when response was received over the secure connection.++#### securityDetails.issuer()+- returns: <[string]> A string with the name of issuer of the certificate.++#### securityDetails.protocol()+- returns: <[string]> String with the security protocol, eg. "TLS 1.2".++#### securityDetails.subjectName()+- returns: <[string]> Name of the subject to which the certificate was issued to.++#### securityDetails.validFrom()+- returns: <[number]> [UnixTime] stating the start of validity of the certificate.++#### securityDetails.validTo()+- returns: <[number]> [UnixTime] stating the end of validity of the certificate.++### class: Target++#### target.browser()++- returns: <[Browser]>++Get the browser the target belongs to.++#### target.browserContext()++- returns: <[BrowserContext]>++The browser context the target belongs to.++#### target.createCDPSession()+- returns: <[Promise]<[CDPSession]>>++Creates a Chrome Devtools Protocol session attached to the target.++#### target.opener()+- returns: <?[Target]>++Get the target that opened this target. Top-level targets return `null`.++#### target.page()+- returns: <[Promise]<?[Page]>>++If the target is not of type `"page"` or `"background_page"`, returns `null`.++#### target.type()+- returns: <"page"|"background_page"|"service_worker"|"shared_worker"|"other"|"browser">++Identifies what kind of target this is. Can be `"page"`, [`"background_page"`](https://developer.chrome.com/extensions/background_pages), `"service_worker"`, `"shared_worker"`, `"browser"` or `"other"`.++#### target.url()+- returns: <[string]>++#### target.worker()+- returns: <[Promise]<?[Worker]>>++If the target is not of type `"service_worker"` or `"shared_worker"`, returns `null`.++### class: CDPSession++* extends: [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter)++The `CDPSession` instances are used to talk raw Chrome Devtools Protocol:+- protocol methods can be called with `session.send` method.+- protocol events can be subscribed to with `session.on` method.++Useful links:+- Documentation on DevTools Protocol can be found here: [DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/).+- Getting Started with DevTools Protocol: https://github.com/aslushnikov/getting-started-with-cdp/blob/master/README.md++```js+const client = await page.target().createCDPSession();+await client.send('Animation.enable');+client.on('Animation.animationCreated', () => console.log('Animation created!'));+const response = await client.send('Animation.getPlaybackRate');+console.log('playback rate is ' + response.playbackRate);+await client.send('Animation.setPlaybackRate', {+ playbackRate: response.playbackRate / 2+});+```++#### cdpSession.detach()+- returns: <[Promise]>++Detaches the cdpSession from the target. Once detached, the cdpSession object won't emit any events and can't be used+to send messages.++#### cdpSession.send(method[, params])+- `method` <[string]> protocol method name+- `params` <[Object]> Optional method parameters+- returns: <[Promise]<[Object]>>++### class: Coverage++Coverage gathers information about parts of JavaScript and CSS that were used by the page.++An example of using JavaScript and CSS coverage to get percentage of initially+executed code:++```js+// Enable both JavaScript and CSS coverage+await Promise.all([+ page.coverage.startJSCoverage(),+ page.coverage.startCSSCoverage()+]);+// Navigate to page+await page.goto('https://example.com');+// Disable both JavaScript and CSS coverage+const [jsCoverage, cssCoverage] = await Promise.all([+ page.coverage.stopJSCoverage(),+ page.coverage.stopCSSCoverage(),+]);+let totalBytes = 0;+let usedBytes = 0;+const coverage = [...jsCoverage, ...cssCoverage];+for (const entry of coverage) {+ totalBytes += entry.text.length;+ for (const range of entry.ranges)+ usedBytes += range.end - range.start - 1;+}+console.log(`Bytes used: ${usedBytes / totalBytes * 100}%`);+```++_To output coverage in a form consumable by [Istanbul](https://github.com/istanbuljs),+ see [playwright-to-istanbul](https://github.com/istanbuljs/playwright-to-istanbul)._++#### coverage.startCSSCoverage([options])+- `options` <[Object]> Set of configurable options for coverage+ - `resetOnNavigation` <[boolean]> Whether to reset coverage on every navigation. Defaults to `true`.+- returns: <[Promise]> Promise that resolves when coverage is started++#### coverage.startJSCoverage([options])+- `options` <[Object]> Set of configurable options for coverage+ - `resetOnNavigation` <[boolean]> Whether to reset coverage on every navigation. Defaults to `true`.+ - `reportAnonymousScripts` <[boolean]> Whether anonymous scripts generated by the page should be reported. Defaults to `false`.+- returns: <[Promise]> Promise that resolves when coverage is started++> **NOTE** Anonymous scripts are ones that don't have an associated url. These are scripts that are dynamically created on the page using `eval` or `new Function`. If `reportAnonymousScripts` is set to `true`, anonymous scripts will have `__playwright_evaluation_script__` as their URL.++#### coverage.stopCSSCoverage()+- returns: <[Promise]<[Array]<[Object]>>> Promise that resolves to the array of coverage reports for all stylesheets+ - `url` <[string]> StyleSheet URL+ - `text` <[string]> StyleSheet content+ - `ranges` <[Array]<[Object]>> StyleSheet ranges that were used. Ranges are sorted and non-overlapping.+ - `start` <[number]> A start offset in text, inclusive+ - `end` <[number]> An end offset in text, exclusive++> **NOTE** CSS Coverage doesn't include dynamically injected style tags without sourceURLs.++#### coverage.stopJSCoverage()+- returns: <[Promise]<[Array]<[Object]>>> Promise that resolves to the array of coverage reports for all scripts+ - `url` <[string]> Script URL+ - `text` <[string]> Script content+ - `ranges` <[Array]<[Object]>> Script ranges that were executed. Ranges are sorted and non-overlapping.+ - `start` <[number]> A start offset in text, inclusive+ - `end` <[number]> An end offset in text, exclusive++> **NOTE** JavaScript Coverage doesn't include anonymous scripts by default. However, scripts with sourceURLs are+reported.++### class: TimeoutError++* extends: [Error]++TimeoutError is emitted whenever certain operations are terminated due to timeout, e.g. [page.waitForSelector(selector[, options])](#pagewaitforselectorselector-options) or [playwright.launch([options])](#playwrightlaunchoptions).++++[AXNode]: #accessibilitysnapshotoptions "AXNode"+[Accessibility]: #class-accessibility "Accessibility"+[Array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array "Array"+[Body]: #class-body "Body"+[BrowserContext]: #class-browsercontext "BrowserContext"+[BrowserFetcher]: #class-browserfetcher "BrowserFetcher"+[Browser]: #class-browser "Browser"+[Buffer]: https://nodejs.org/api/buffer.html#buffer_class_buffer "Buffer"+[CDPSession]: #class-cdpsession "CDPSession"+[ChildProcess]: https://nodejs.org/api/child_process.html "ChildProcess"+[ConnectionTransport]: ../lib/WebSocketTransport.js "ConnectionTransport"+[ConsoleMessage]: #class-consolemessage "ConsoleMessage"+[Coverage]: #class-coverage "Coverage"+[Dialog]: #class-dialog "Dialog"+[ElementHandle]: #class-elementhandle "ElementHandle"+[Element]: https://developer.mozilla.org/en-US/docs/Web/API/element "Element"+[Error]: https://nodejs.org/api/errors.html#errors_class_error "Error"+[ExecutionContext]: #class-executioncontext "ExecutionContext"+[FileChooser]: #class-filechooser "FileChooser"+[Frame]: #class-frame "Frame"+[JSHandle]: #class-jshandle "JSHandle"+[Keyboard]: #class-keyboard "Keyboard"+[Map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map "Map"+[Mouse]: #class-mouse "Mouse"+[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"+[Page]: #class-page "Page"+[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"+[Request]: #class-request "Request"+[Response]: #class-response "Response"+[SecurityDetails]: #class-securitydetails "SecurityDetails"+[Serializable]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Description "Serializable"+[Target]: #class-target "Target"+[TimeoutError]: #class-timeouterror "TimeoutError"+[Touchscreen]: #class-touchscreen "Touchscreen"+[Tracing]: #class-tracing "Tracing"+[UIEvent.detail]: https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail "UIEvent.detail"+[USKeyboardLayout]: ../lib/USKeyboardLayout.js "USKeyboardLayout"+[UnixTime]: https://en.wikipedia.org/wiki/Unix_time "Unix Time"+[Worker]: #class-worker "Worker"+[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"+[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function "Function"+[iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols "Iterator"+[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"+[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin "Origin"+[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors "selector"+[stream.Readable]: https://nodejs.org/api/stream.html#stream_class_stream_readable "stream.Readable"+[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "String"+[xpath]: https://developer.mozilla.org/en-US/docs/Web/XPath "xpath"diff --git a/examples/block-images.js b/examples/block-images.jsnew file mode 100644index 0000000000..6331c1dc15--- /dev/null+++ b/examples/block-images.js@@ -0,0 +1,36 @@+/**+ * Copyright 2017 Google Inc., PhantomJS Authors All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++'use strict';++const playwright = require('playwright');++(async() => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.setRequestInterception(true);+ page.on('request', request => {+ if (request.resourceType() === 'image')+ request.abort();+ else+ request.continue();+ });+ await page.goto('https://news.google.com/news/');+ await page.screenshot({path: 'news.png', fullPage: true});++ await browser.close();+})();+diff --git a/examples/custom-event.js b/examples/custom-event.jsnew file mode 100644index 0000000000..be7265f581--- /dev/null+++ b/examples/custom-event.js@@ -0,0 +1,48 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++'use strict';++const playwright = require('playwright');++(async() => {+ const browser = await playwright.launch();+ const page = await browser.newPage();++ // Define a window.onCustomEvent function on the page.+ await page.exposeFunction('onCustomEvent', e => {+ console.log(`${e.type} fired`, e.detail || '');+ });++ /**+ * Attach an event listener to page to capture a custom event on page load/navigation.+ * @param {string} type Event name.+ * @return {!Promise}+ */+ function listenFor(type) {+ return page.evaluateOnNewDocument(type => {+ document.addEventListener(type, e => {+ window.onCustomEvent({type, detail: e.detail});+ });+ }, type);+ }++ await listenFor('app-ready'); // Listen for "app-ready" custom event on page load.++ await page.goto('https://www.chromestatus.com/features', {waitUntil: 'networkidle0'});++ await browser.close();+})();diff --git a/examples/detect-sniff.js b/examples/detect-sniff.jsnew file mode 100644index 0000000000..202b84478d--- /dev/null+++ b/examples/detect-sniff.js@@ -0,0 +1,44 @@+/**+ * Copyright 2017 Google Inc., PhantomJS Authors All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++'use strict';++const playwright = require('playwright');++function sniffDetector() {+ const userAgent = window.navigator.userAgent;+ const platform = window.navigator.platform;++ window.navigator.__defineGetter__('userAgent', function() {+ window.navigator.sniffed = true;+ return userAgent;+ });++ window.navigator.__defineGetter__('platform', function() {+ window.navigator.sniffed = true;+ return platform;+ });+}++(async() => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.evaluateOnNewDocument(sniffDetector);+ await page.goto('https://www.google.com', {waitUntil: 'networkidle2'});+ console.log('Sniffed: ' + (await page.evaluate(() => !!navigator.sniffed)));++ await browser.close();+})();diff --git a/examples/pdf.js b/examples/pdf.jsnew file mode 100644index 0000000000..c782fe1cbe--- /dev/null+++ b/examples/pdf.js@@ -0,0 +1,33 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++'use strict';++const playwright = require('playwright');++(async() => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto('https://news.ycombinator.com', {waitUntil: 'networkidle2'});+ // page.pdf() is currently supported only in headless mode.+ // @see https://bugs.chromium.org/p/chromium/issues/detail?id=753118+ await page.pdf({+ path: 'hn.pdf',+ format: 'letter'+ });++ await browser.close();+})();diff --git a/examples/proxy.js b/examples/proxy.jsnew file mode 100644index 0000000000..b405647f21--- /dev/null+++ b/examples/proxy.js@@ -0,0 +1,35 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++'use strict';++const playwright = require('playwright');++(async() => {+ const browser = await playwright.launch({+ // Launch chromium using a proxy server on port 9876.+ // More on proxying:+ // https://www.chromium.org/developers/design-documents/network-settings+ args: [+ '--proxy-server=127.0.0.1:9876',+ // Use proxy for localhost URLs+ '--proxy-bypass-list=<-loopback>',+ ]+ });+ const page = await browser.newPage();+ await page.goto('https://google.com');+ await browser.close();+})();diff --git a/examples/screenshot-fullpage.js b/examples/screenshot-fullpage.jsnew file mode 100644index 0000000000..603924ef14--- /dev/null+++ b/examples/screenshot-fullpage.js@@ -0,0 +1,29 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++'use strict';++const playwright = require('playwright');+const devices = require('playwright/DeviceDescriptors');++(async() => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.emulate(devices['iPhone 6']);+ await page.goto('https://www.nytimes.com/');+ await page.screenshot({path: 'full.png', fullPage: true});+ await browser.close();+})();diff --git a/examples/screenshot.js b/examples/screenshot.jsnew file mode 100644index 0000000000..889d1be59d--- /dev/null+++ b/examples/screenshot.js@@ -0,0 +1,27 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++'use strict';++const playwright = require('playwright');++(async() => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto('http://example.com');+ await page.screenshot({path: 'example.png'});+ await browser.close();+})();diff --git a/examples/search.js b/examples/search.jsnew file mode 100644index 0000000000..aae2e8d50d--- /dev/null+++ b/examples/search.js@@ -0,0 +1,55 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/**+ * @fileoverview Search developers.google.com/web for articles tagged+ * "Headless Chrome" and scrape results from the results page.+ */++'use strict';++const playwright = require('playwright');++(async() => {+ const browser = await playwright.launch();+ const page = await browser.newPage();++ await page.goto('https://developers.google.com/web/');++ // Type into search box.+ await page.type('#searchbox input', 'Headless Chrome');++ // Wait for suggest overlay to appear and click "show all results".+ const allResultsSelector = '.devsite-suggest-all-results';+ await page.waitForSelector(allResultsSelector);+ await page.click(allResultsSelector);++ // Wait for the results page to load and display the results.+ const resultsSelector = '.gsc-results .gsc-thumbnail-inside a.gs-title';+ await page.waitForSelector(resultsSelector);++ // Extract the results from the page.+ const links = await page.evaluate(resultsSelector => {+ const anchors = Array.from(document.querySelectorAll(resultsSelector));+ return anchors.map(anchor => {+ const title = anchor.textContent.split('|')[0].trim();+ return `${title} - ${anchor.href}`;+ });+ }, resultsSelector);+ console.log(links.join('\n'));++ await browser.close();+})();diff --git a/firefox.js b/firefox.jsnew file mode 100644index 0000000000..166b1ddb4f--- /dev/null+++ b/firefox.js@@ -0,0 +1,29 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {helper} = require('./lib/helper');+const api = require('./lib/api');+for (const className in api.Firefox) {+ // Playwright-web excludes certain classes from bundle, e.g. BrowserFetcher.+ if (typeof api.Firefox[className] === 'function')+ helper.installAsyncStackHooks(api.Firefox[className]);+}++// If node does not support async await, use the compiled version.+const {Playwright} = require('./lib/firefox/Playwright');+const packageJson = require('./package.json');++module.exports = new Playwright(__dirname, packageJson.playwright.firefox_revision);diff --git a/install.js b/install.jsnew file mode 100644index 0000000000..38c5815ac1--- /dev/null+++ b/install.js@@ -0,0 +1,137 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++// playwright-core should not install anything.+if (require('./package.json').name === 'playwright-core')+ return;++for (const browser of ['Chromium', 'Firefox', 'WebKit']) {+ const templates = [+ `PLAYWRIGHT_SKIP_${browser}_DOWNLOAD`,+ `NPM_CONFIG_PLAYWRIGHT_SKIP_${browser}_DOWNLOAD`,+ `NPM_PACKAGE_CONFIG_PLAYWRIGHT_SKIP_${browser}_DOWNLOAD`,+ ];+ const varNames = [...templates.map(n => n.toUpperCase()), ...templates.map(n => n.toLowerCase())];+ for (const varName of varNames) {+ if (process.env[varName.toUpperCase()]) {+ logPolitely(`**INFO** Skipping ${browser} download. "${varName}" environment variable was found.`);+ return;+ }+ }+}++const downloadHost = process.env.PLAYWRIGHT_DOWNLOAD_HOST || process.env.npm_config_playwright_download_host || process.env.npm_package_config_playwright_download_host;+++if (require('fs').existsSync(require('path').join(__dirname, 'src'))) {+ try {+ require('child_process').execSync('npm run build', {+ stdio: 'ignore'+ });+ } catch (e) {+ }+}++(async function() {+ const {generateWebKitProtocol, generateChromeProtocol} = require('./utils/protocol-types-generator/') ;++ const chromeRevision = await downloadBrowser('chromium', require('./chromium').createBrowserFetcher({host: downloadHost}));+ await generateChromeProtocol(chromeRevision);++ await downloadBrowser('firefox', require('./firefox').createBrowserFetcher({host: downloadHost}));++ const webkitRevision = await downloadBrowser('webkit', require('./webkit').createBrowserFetcher({host: downloadHost}));+ await generateWebKitProtocol(webkitRevision);+})();+function getRevision(browser) {+ if (browser === 'chromium')+ return process.env.PLAYWRIGHT_CHROMIUM_REVISION || process.env.npm_config_playwright_chromium_revision || process.env.npm_package_config_playwright_chromium_revision || require('./package.json').playwright.chromium_revision;+ if (browser === 'firefox')+ return process.env.PLAYWRIGHT_FIREFOX_REVISION || process.env.npm_config_playwright_firefox_revision || process.env.npm_package_config_playwright_firefox_revision || require('./package.json').playwright.firefox_revision;+ if (browser === 'webkit')+ return process.env.PLAYWRIGHT_WEBKIT_REVISION || process.env.npm_config_playwright_webkit_revision || process.env.npm_package_config_playwright_webkit_revision || require('./package.json').playwright.webkit_revision;+}+async function downloadBrowser(browser, browserFetcher) {+ const revision = getRevision(browser);++ const revisionInfo = browserFetcher.revisionInfo(revision);++ // Do nothing if the revision is already downloaded.+ if (revisionInfo.local)+ return revisionInfo;++ // Override current environment proxy settings with npm configuration, if any.+ const NPM_HTTPS_PROXY = process.env.npm_config_https_proxy || process.env.npm_config_proxy;+ const NPM_HTTP_PROXY = process.env.npm_config_http_proxy || process.env.npm_config_proxy;+ const NPM_NO_PROXY = process.env.npm_config_no_proxy;++ if (NPM_HTTPS_PROXY)+ process.env.HTTPS_PROXY = NPM_HTTPS_PROXY;+ if (NPM_HTTP_PROXY)+ process.env.HTTP_PROXY = NPM_HTTP_PROXY;+ if (NPM_NO_PROXY)+ process.env.NO_PROXY = NPM_NO_PROXY;++ let progressBar = null;+ let lastDownloadedBytes = 0;+ function onProgress(downloadedBytes, totalBytes) {+ if (!progressBar) {+ const ProgressBar = require('progress');+ progressBar = new ProgressBar(`Downloading ${browser} ${revision} - ${toMegabytes(totalBytes)} [:bar] :percent :etas `, {+ complete: '=',+ incomplete: ' ',+ width: 20,+ total: totalBytes,+ });+ }+ const delta = downloadedBytes - lastDownloadedBytes;+ lastDownloadedBytes = downloadedBytes;+ progressBar.tick(delta);+ }++ try {+ await browserFetcher.download(revisionInfo.revision, onProgress);+ } catch(error) {+ console.error(`ERROR: Failed to download ${browser} ${revision}! Set "PLAYWRIGHT_SKIP_${browser.toUpperCase()}_DOWNLOAD" env variable to skip download.`);+ console.error(error);+ process.exit(1);+ }+ logPolitely(`${browser} downloaded to ${revisionInfo.folderPath}`);+ const localRevisions = await browserFetcher.localRevisions();+ // Remove previous chromium revisions.+ const cleanupOldVersions = localRevisions.filter(revision => revision !== revisionInfo.revision).map(revision => browserFetcher.remove(revision));+ await Promise.all([...cleanupOldVersions]);+ if (browser === 'firefox') {+ const installFirefoxPreferences = require('./misc/install-preferences');+ await installFirefoxPreferences(revisionInfo.executablePath);+ }+ return revisionInfo;+}+++function toMegabytes(bytes) {+ const mb = bytes / 1024 / 1024;+ return `${Math.round(mb * 10) / 10} Mb`;+}++function logPolitely(toBeLogged) {+ const logLevel = process.env.npm_config_loglevel;+ const logLevelDisplay = ['silent', 'error', 'warn'].indexOf(logLevel) > -1;++ if (!logLevelDisplay)+ console.log(toBeLogged);+}+diff --git a/misc/00-playwright-prefs.js b/misc/00-playwright-prefs.jsnew file mode 100644index 0000000000..1895d2d1b7--- /dev/null+++ b/misc/00-playwright-prefs.js@@ -0,0 +1,3 @@+// Any comment. You must start the file with a single-line comment!+pref("general.config.filename", "playwright.cfg");+pref("general.config.obscure_value", 0);diff --git a/misc/install-preferences.js b/misc/install-preferences.jsnew file mode 100644index 0000000000..7a4f4bc520--- /dev/null+++ b/misc/install-preferences.js@@ -0,0 +1,59 @@+const os = require('os');+const fs = require('fs');+const path = require('path');+const util = require('util');++// Install browser preferences after downloading and unpacking+// firefox instances.+// Based on: https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Enterprise_deployment_before_60#Configuration+async function installFirefoxPreferences(executablePath) {+ const firefoxFolder = path.dirname(executablePath);+ const mkdirAsync = util.promisify(fs.mkdir.bind(fs));++ let prefPath = '';+ let configPath = '';+ if (os.platform() === 'darwin') {+ prefPath = path.join(firefoxFolder, '..', 'Resources', 'defaults', 'pref');+ configPath = path.join(firefoxFolder, '..', 'Resources');+ } else if (os.platform() === 'linux') {+ if (!fs.existsSync(path.join(firefoxFolder, 'browser', 'defaults')))+ await mkdirAsync(path.join(firefoxFolder, 'browser', 'defaults'));+ if (!fs.existsSync(path.join(firefoxFolder, 'browser', 'defaults', 'preferences')))+ await mkdirAsync(path.join(firefoxFolder, 'browser', 'defaults', 'preferences'));+ prefPath = path.join(firefoxFolder, 'browser', 'defaults', 'preferences');+ configPath = firefoxFolder;+ } else if (os.platform() === 'win32') {+ prefPath = path.join(firefoxFolder, 'defaults', 'pref');+ configPath = firefoxFolder;+ } else {+ throw new Error('Unsupported platform: ' + os.platform());+ }++ await Promise.all([+ copyFile({+ from: path.join(__dirname, '00-playwright-prefs.js'),+ to: path.join(prefPath, '00-playwright-prefs.js'),+ }),+ copyFile({+ from: path.join(__dirname, 'playwright.cfg'),+ to: path.join(configPath, 'playwright.cfg'),+ }),+ ]);+}++function copyFile({from, to}) {+ var rd = fs.createReadStream(from);+ var wr = fs.createWriteStream(to);+ return new Promise(function(resolve, reject) {+ rd.on('error', reject);+ wr.on('error', reject);+ wr.on('finish', resolve);+ rd.pipe(wr);+ }).catch(function(error) {+ rd.destroy();+ wr.end();+ throw error;+ });+}++module.exports = installFirefoxPreferences;diff --git a/misc/playwright.cfg b/misc/playwright.cfgnew file mode 100644index 0000000000..7a0b0591ab--- /dev/null+++ b/misc/playwright.cfg@@ -0,0 +1,212 @@+// Any comment. You must start the file with a comment!++// Make sure Shield doesn't hit the network.+// pref("app.normandy.api_url", "");+pref("app.normandy.enabled", false);++// Disable updater+pref("app.update.enabled", false);+// make absolutely sure it is really off+pref("app.update.auto", false);+pref("app.update.mode", 0);+pref("app.update.service.enabled", false);++// Dislabe newtabpage+pref("browser.startup.homepage", 'about:blank');+pref("browser.newtabpage.enabled", false);+// Disable topstories+pref("browser.newtabpage.activity-stream.feeds.section.topstories", false);++// DevTools JSONViewer sometimes fails to load dependencies with its require.js.+// This doesn't affect Playwright operations, but spams console with a lot of+// unpleasant errors.+// (bug 1424372)+pref("devtools.jsonview.enabled", false);++// Increase the APZ content response timeout in tests to 1 minute.+// This is to accommodate the fact that test environments tends to be+// slower than production environments (with the b2g emulator being+// the slowest of them all), resulting in the production timeout value+// sometimes being exceeded and causing false-positive test failures.+//+// (bug 1176798, bug 1177018, bug 1210465)+pref("apz.content_response_timeout", 60000);++// Allow creating files in content process - required for+// |Page.setFileInputFiles| protocol method.+pref("dom.file.createInChild", true);++// Indicate that the download panel has been shown once so that+// whichever download test runs first doesn't show the popup+// inconsistently.+pref("browser.download.panel.shown", true);++// Background thumbnails in particular cause grief, and disabling+// thumbnails in general cannot hurt+pref("browser.pagethumbnails.capturing_disabled", true);++// Disable safebrowsing components.+pref("browser.safebrowsing.blockedURIs.enabled", false);+pref("browser.safebrowsing.downloads.enabled", false);+pref("browser.safebrowsing.passwords.enabled", false);+pref("browser.safebrowsing.malware.enabled", false);+pref("browser.safebrowsing.phishing.enabled", false);++// Disable updates to search engines.+pref("browser.search.update", false);++// Do not restore the last open set of tabs if the browser has crashed+pref("browser.sessionstore.resume_from_crash", false);++// Don't check for the default web browser during startup.+pref("browser.shell.checkDefaultBrowser", false);++// Do not redirect user when a milstone upgrade of Firefox is detected+pref("browser.startup.homepage_override.mstone", "ignore");++// Disable browser animations (tabs, fullscreen, sliding alerts)+pref("toolkit.cosmeticAnimations.enabled", false);++// Close the window when the last tab gets closed+pref("browser.tabs.closeWindowWithLastTab", true);++// Do not allow background tabs to be zombified on Android, otherwise for+// tests that open additional tabs, the test harness tab itself might get+// unloaded+pref("browser.tabs.disableBackgroundZombification", false);++// Do not warn when closing all open tabs+pref("browser.tabs.warnOnClose", false);++// Do not warn when closing all other open tabs+pref("browser.tabs.warnOnCloseOtherTabs", false);++// Do not warn when multiple tabs will be opened+pref("browser.tabs.warnOnOpen", false);++// Disable first run splash page on Windows 10+pref("browser.usedOnWindows10.introURL", "");++// Disable the UI tour.+//+// Should be set in profile.+pref("browser.uitour.enabled", false);++// Turn off search suggestions in the location bar so as not to trigger+// network connections.+pref("browser.urlbar.suggest.searches", false);++// Do not warn on quitting Firefox+pref("browser.warnOnQuit", false);++// Do not show datareporting policy notifications which can+// interfere with tests+pref(+ "datareporting.healthreport.documentServerURI",+ "http://%(server)s/dummy/healthreport/",+);+pref("datareporting.healthreport.logging.consoleEnabled", false);+pref("datareporting.healthreport.service.enabled", false);+pref("datareporting.healthreport.service.firstRun", false);+pref("datareporting.healthreport.uploadEnabled", false);+pref("datareporting.policy.dataSubmissionEnabled", false);+pref("datareporting.policy.dataSubmissionPolicyAccepted", false);+pref("datareporting.policy.dataSubmissionPolicyBypassNotification", true);++// Automatically unload beforeunload alerts+pref("dom.disable_beforeunload", false);++// Disable popup-blocker+pref("dom.disable_open_during_load", false);++// Disable the ProcessHangMonitor+pref("dom.ipc.reportProcessHangs", false);++// Disable slow script dialogues+pref("dom.max_chrome_script_run_time", 0);+pref("dom.max_script_run_time", 0);++// Only load extensions from the application and user profile+// AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION+pref("extensions.autoDisableScopes", 0);+pref("extensions.enabledScopes", 5);++// Disable metadata caching for installed add-ons by default+pref("extensions.getAddons.cache.enabled", false);++// Disable installing any distribution extensions or add-ons.+pref("extensions.installDistroAddons", false);++// Turn off extension updates so they do not bother tests+pref("extensions.update.enabled", false);+pref("extensions.update.notifyUser", false);++// Make sure opening about:addons will not hit the network+pref(+ "extensions.webservice.discoverURL",+ "http://%(server)s/dummy/discoveryURL",+);++pref("extensions.screenshots.disabled", true);+pref("extensions.screenshots.upload-disabled", true);++// Allow the application to have focus even it runs in the background+pref("focusmanager.testmode", true);++// Disable useragent updates+pref("general.useragent.updates.enabled", false);++// Always use network provider for geolocation tests so we bypass the+// macOS dialog raised by the corelocation provider+pref("geo.provider.testing", true);++// Do not scan Wifi+pref("geo.wifi.scan", false);++// Show chrome errors and warnings in the error console+pref("javascript.options.showInConsole", true);++// Do not prompt with long usernames or passwords in URLs+pref("network.http.phishy-userpass-length", 255);++// Do not prompt for temporary redirects+pref("network.http.prompt-temp-redirect", false);++// Disable speculative connections so they are not reported as leaking+// when they are hanging around+pref("network.http.speculative-parallel-limit", 0);++// Do not automatically switch between offline and online+pref("network.manage-offline-status", false);++// Make sure SNTP requests do not hit the network+pref("network.sntp.pools", "%(server)s");++// Local documents have access to all other local documents,+// including directory listings+pref("security.fileuri.strict_origin_policy", false);++// Tests do not wait for the notification button security delay+pref("security.notification_enable_delay", 0);++// Ensure blocklist updates do not hit the network+pref("services.settings.server", "http://%(server)s/dummy/blocklist/");++// Do not automatically fill sign-in forms with known usernames and+// passwords+pref("signon.autofillForms", false);++// Disable password capture, so that tests that include forms are not+// influenced by the presence of the persistent doorhanger notification+pref("signon.rememberSignons", false);++// Disable first-run welcome page+pref("startup.homepage_welcome_url", "about:blank");+pref("startup.homepage_welcome_url.additional", "");++// Prevent starting into safe mode after application crashes+pref("toolkit.startup.max_resumed_crashes", -1);+lockPref("toolkit.crashreporter.enabled", false);++// Disable crash reporter.+Components.classes["@mozilla.org/toolkit/crash-reporter;1"].getService(Components.interfaces.nsICrashReporter).submitReports = false;diff --git a/package.json b/package.jsonnew file mode 100644index 0000000000..0c79c1b725--- /dev/null+++ b/package.json@@ -0,0 +1,75 @@+{+ "name": "playwright",+ "version": "2.0.0-post",+ "description": "A high-level API to control headless Chrome over the DevTools Protocol",+ "main": "index.js",+ "repository": "github:Microsoft/playwright",+ "engines": {+ "node": ">=8.16.0"+ },+ "playwright": {+ "chromium_revision": "706915",+ "firefox_revision": "1",+ "webkit_revision": "1"+ },+ "scripts": {+ "unit": "node test/test.js",+ "funit": "cross-env BROWSER=firefox node test/test.js",+ "wunit": "cross-env BROWSER=webkit node test/test.js",+ "debug-unit": "node --inspect-brk test/test.js",+ "test-doclint": "node utils/doclint/check_public_api/test/test.js && node utils/doclint/preprocessor/test.js",+ "test": "npm run lint --silent && npm run coverage && npm run test-doclint && npm run test-types && node utils/testrunner/test/test.js",+ "install": "node install.js",+ "lint": "([ \"$CI\" = true ] && eslint --quiet -f codeframe --ext js,ts ./src || eslint --ext js,ts ./src) && npm run tsc && npm run doc",+ "doc": "node utils/doclint/cli.js",+ "coverage": "cross-env COVERAGE=true npm run unit",+ "tsc": "tsc -p .",+ "build": "npm run tsc",+ "watch": "tsc -w -p .",+ "apply-next-version": "node utils/apply_next_version.js",+ "bundle": "npx browserify -r ./index.js:playwright -o utils/browser/playwright-web.js",+ "test-types": "node utils/doclint/generate_types && npx -p [email protected] tsc -p utils/doclint/generate_types/test/",+ "unit-bundle": "node utils/browser/test.js"+ },+ "author": "The Chromium Authors",+ "license": "Apache-2.0",+ "dependencies": {+ "debug": "^4.1.0",+ "extract-zip": "^1.6.6",+ "https-proxy-agent": "^3.0.0",+ "mime": "^2.0.3",+ "progress": "^2.0.1",+ "proxy-from-env": "^1.0.0",+ "rimraf": "^2.6.1",+ "ws": "^6.1.0"+ },+ "devDependencies": {+ "@types/debug": "0.0.31",+ "@types/extract-zip": "^1.6.2",+ "@types/mime": "^2.0.0",+ "@types/node": "^8.10.34",+ "@types/rimraf": "^2.0.2",+ "@types/ws": "^6.0.1",+ "@typescript-eslint/eslint-plugin": "^2.6.1",+ "@typescript-eslint/parser": "^2.6.1",+ "commonmark": "^0.28.1",+ "cross-env": "^5.0.5",+ "eslint": "^6.6.0",+ "esprima": "^4.0.0",+ "jpeg-js": "^0.3.4",+ "minimist": "^1.2.0",+ "ncp": "^2.0.0",+ "pixelmatch": "^4.0.2",+ "pngjs": "^3.3.3",+ "text-diff": "^1.0.1",+ "typescript": "3.6.3"+ },+ "browser": {+ "./lib/BrowserFetcher.js": false,+ "ws": "./utils/browser/WebSocket",+ "fs": false,+ "child_process": false,+ "rimraf": false,+ "readline": false+ }+}diff --git a/src/.eslintrc.js b/src/.eslintrc.jsnew file mode 100644index 0000000000..1d9df6e7f9--- /dev/null+++ b/src/.eslintrc.js@@ -0,0 +1,16 @@+module.exports = {+ "extends": "../.eslintrc.js",+ /**+ * ESLint rules+ *+ * All available rules: http://eslint.org/docs/rules/+ *+ * Rules take the following form:+ * "rule-name", [severity, { opts }]+ * Severity: 2 == error, 1 == warning, 0 == off.+ */+ "rules": {+ "no-console": [2, { "allow": ["warn", "error", "assert", "timeStamp", "time", "timeEnd"] }],+ "no-debugger": 0,+ }+};diff --git a/src/ConnectionTransport.ts b/src/ConnectionTransport.tsnew file mode 100644index 0000000000..640e1633de--- /dev/null+++ b/src/ConnectionTransport.ts@@ -0,0 +1,6 @@+export interface ConnectionTransport {+ send(s: string): void;+ close(): void;+ onmessage?: (message: string) => void,+ onclose?: () => void,+}\ No newline at end of filediff --git a/src/DeviceDescriptors.ts b/src/DeviceDescriptors.tsnew file mode 100644index 0000000000..8773f7471c--- /dev/null+++ b/src/DeviceDescriptors.ts@@ -0,0 +1,871 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export const DeviceDescriptors = [+ {+ 'name': 'Blackberry PlayBook',+ 'userAgent': 'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+',+ 'viewport': {+ 'width': 600,+ 'height': 1024,+ 'deviceScaleFactor': 1,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Blackberry PlayBook landscape',+ 'userAgent': 'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 2.1.0; en-US) AppleWebKit/536.2+ (KHTML like Gecko) Version/7.2.1.0 Safari/536.2+',+ 'viewport': {+ 'width': 1024,+ 'height': 600,+ 'deviceScaleFactor': 1,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'BlackBerry Z30',+ 'userAgent': 'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+',+ 'viewport': {+ 'width': 360,+ 'height': 640,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'BlackBerry Z30 landscape',+ 'userAgent': 'Mozilla/5.0 (BB10; Touch) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.0.9.2372 Mobile Safari/537.10+',+ 'viewport': {+ 'width': 640,+ 'height': 360,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Galaxy Note 3',+ 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',+ 'viewport': {+ 'width': 360,+ 'height': 640,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Galaxy Note 3 landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',+ 'viewport': {+ 'width': 640,+ 'height': 360,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Galaxy Note II',+ 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',+ 'viewport': {+ 'width': 360,+ 'height': 640,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Galaxy Note II landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.1; en-us; GT-N7100 Build/JRO03C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',+ 'viewport': {+ 'width': 640,+ 'height': 360,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Galaxy S III',+ 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',+ 'viewport': {+ 'width': 360,+ 'height': 640,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Galaxy S III landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.0; en-us; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',+ 'viewport': {+ 'width': 640,+ 'height': 360,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Galaxy S5',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 360,+ 'height': 640,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Galaxy S5 landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 640,+ 'height': 360,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPad',+ 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',+ 'viewport': {+ 'width': 768,+ 'height': 1024,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPad landscape',+ 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',+ 'viewport': {+ 'width': 1024,+ 'height': 768,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPad Mini',+ 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',+ 'viewport': {+ 'width': 768,+ 'height': 1024,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPad Mini landscape',+ 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',+ 'viewport': {+ 'width': 1024,+ 'height': 768,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPad Pro',+ 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',+ 'viewport': {+ 'width': 1024,+ 'height': 1366,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPad Pro landscape',+ 'userAgent': 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1',+ 'viewport': {+ 'width': 1366,+ 'height': 1024,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone 4',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53',+ 'viewport': {+ 'width': 320,+ 'height': 480,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone 4 landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_1_2 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like Gecko) Version/7.0 Mobile/11D257 Safari/9537.53',+ 'viewport': {+ 'width': 480,+ 'height': 320,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone 5',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',+ 'viewport': {+ 'width': 320,+ 'height': 568,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone 5 landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',+ 'viewport': {+ 'width': 568,+ 'height': 320,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone 6',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 375,+ 'height': 667,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone 6 landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 667,+ 'height': 375,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone 6 Plus',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 414,+ 'height': 736,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone 6 Plus landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 736,+ 'height': 414,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone 7',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 375,+ 'height': 667,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone 7 landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 667,+ 'height': 375,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone 7 Plus',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 414,+ 'height': 736,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone 7 Plus landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 736,+ 'height': 414,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone 8',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 375,+ 'height': 667,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone 8 landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 667,+ 'height': 375,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone 8 Plus',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 414,+ 'height': 736,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone 8 Plus landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 736,+ 'height': 414,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone SE',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',+ 'viewport': {+ 'width': 320,+ 'height': 568,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone SE landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1',+ 'viewport': {+ 'width': 568,+ 'height': 320,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone X',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 375,+ 'height': 812,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone X landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',+ 'viewport': {+ 'width': 812,+ 'height': 375,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'iPhone XR',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1',+ 'viewport': {+ 'width': 414,+ 'height': 896,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'iPhone XR landscape',+ 'userAgent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1',+ 'viewport': {+ 'width': 896,+ 'height': 414,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'JioPhone 2',+ 'userAgent': 'Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5',+ 'viewport': {+ 'width': 240,+ 'height': 320,+ 'deviceScaleFactor': 1,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'JioPhone 2 landscape',+ 'userAgent': 'Mozilla/5.0 (Mobile; LYF/F300B/LYF-F300B-001-01-15-130718-i;Android; rv:48.0) Gecko/48.0 Firefox/48.0 KAIOS/2.5',+ 'viewport': {+ 'width': 320,+ 'height': 240,+ 'deviceScaleFactor': 1,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Kindle Fire HDX',+ 'userAgent': 'Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true',+ 'viewport': {+ 'width': 800,+ 'height': 1280,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Kindle Fire HDX landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; U; en-us; KFAPWI Build/JDQ39) AppleWebKit/535.19 (KHTML, like Gecko) Silk/3.13 Safari/535.19 Silk-Accelerated=true',+ 'viewport': {+ 'width': 1280,+ 'height': 800,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'LG Optimus L70',+ 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 384,+ 'height': 640,+ 'deviceScaleFactor': 1.25,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'LG Optimus L70 landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; U; Android 4.4.2; en-us; LGMS323 Build/KOT49I.MS32310c) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 640,+ 'height': 384,+ 'deviceScaleFactor': 1.25,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Microsoft Lumia 550',+ 'userAgent': 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 550) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263',+ 'viewport': {+ 'width': 640,+ 'height': 360,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Microsoft Lumia 950',+ 'userAgent': 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263',+ 'viewport': {+ 'width': 360,+ 'height': 640,+ 'deviceScaleFactor': 4,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Microsoft Lumia 950 landscape',+ 'userAgent': 'Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/14.14263',+ 'viewport': {+ 'width': 640,+ 'height': 360,+ 'deviceScaleFactor': 4,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Nexus 10',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36',+ 'viewport': {+ 'width': 800,+ 'height': 1280,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Nexus 10 landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 10 Build/MOB31T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36',+ 'viewport': {+ 'width': 1280,+ 'height': 800,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Nexus 4',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 384,+ 'height': 640,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Nexus 4 landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 640,+ 'height': 384,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Nexus 5',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 360,+ 'height': 640,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Nexus 5 landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 640,+ 'height': 360,+ 'deviceScaleFactor': 3,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Nexus 5X',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 412,+ 'height': 732,+ 'deviceScaleFactor': 2.625,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Nexus 5X landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 5X Build/OPR4.170623.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 732,+ 'height': 412,+ 'deviceScaleFactor': 2.625,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Nexus 6',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 412,+ 'height': 732,+ 'deviceScaleFactor': 3.5,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Nexus 6 landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 7.1.1; Nexus 6 Build/N6F26U) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 732,+ 'height': 412,+ 'deviceScaleFactor': 3.5,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Nexus 6P',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 412,+ 'height': 732,+ 'deviceScaleFactor': 3.5,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Nexus 6P landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 732,+ 'height': 412,+ 'deviceScaleFactor': 3.5,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Nexus 7',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36',+ 'viewport': {+ 'width': 600,+ 'height': 960,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Nexus 7 landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 7 Build/MOB30X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Safari/537.36',+ 'viewport': {+ 'width': 960,+ 'height': 600,+ 'deviceScaleFactor': 2,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Nokia Lumia 520',+ 'userAgent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)',+ 'viewport': {+ 'width': 320,+ 'height': 533,+ 'deviceScaleFactor': 1.5,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Nokia Lumia 520 landscape',+ 'userAgent': 'Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 520)',+ 'viewport': {+ 'width': 533,+ 'height': 320,+ 'deviceScaleFactor': 1.5,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Nokia N9',+ 'userAgent': 'Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13',+ 'viewport': {+ 'width': 480,+ 'height': 854,+ 'deviceScaleFactor': 1,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Nokia N9 landscape',+ 'userAgent': 'Mozilla/5.0 (MeeGo; NokiaN9) AppleWebKit/534.13 (KHTML, like Gecko) NokiaBrowser/8.5.0 Mobile Safari/534.13',+ 'viewport': {+ 'width': 854,+ 'height': 480,+ 'deviceScaleFactor': 1,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Pixel 2',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 411,+ 'height': 731,+ 'deviceScaleFactor': 2.625,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Pixel 2 landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 731,+ 'height': 411,+ 'deviceScaleFactor': 2.625,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ },+ {+ 'name': 'Pixel 2 XL',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 411,+ 'height': 823,+ 'deviceScaleFactor': 3.5,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': false+ }+ },+ {+ 'name': 'Pixel 2 XL landscape',+ 'userAgent': 'Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3765.0 Mobile Safari/537.36',+ 'viewport': {+ 'width': 823,+ 'height': 411,+ 'deviceScaleFactor': 3.5,+ 'isMobile': true,+ 'hasTouch': true,+ 'isLandscape': true+ }+ }+];diff --git a/src/Errors.ts b/src/Errors.tsnew file mode 100644index 0000000000..3044091584--- /dev/null+++ b/src/Errors.ts@@ -0,0 +1,26 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++class CustomError extends Error {+ constructor(message: string) {+ super(message);+ this.name = this.constructor.name;+ Error.captureStackTrace(this, this.constructor);+ }+}++export class TimeoutError extends CustomError {}diff --git a/src/Events.ts b/src/Events.tsnew file mode 100644index 0000000000..580565de1c--- /dev/null+++ b/src/Events.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export const Events = {+ Page: {+ Close: 'close',+ Console: 'console',+ Dialog: 'dialog',+ DOMContentLoaded: 'domcontentloaded',+ Error: 'error',+ // Can't use just 'error' due to node.js special treatment of error events.+ // @see https://nodejs.org/api/events.html#events_error_events+ PageError: 'pageerror',+ Request: 'request',+ Response: 'response',+ RequestFailed: 'requestfailed',+ RequestFinished: 'requestfinished',+ FrameAttached: 'frameattached',+ FrameDetached: 'framedetached',+ FrameNavigated: 'framenavigated',+ Load: 'load',+ Metrics: 'metrics',+ Popup: 'popup',+ WorkerCreated: 'workercreated',+ WorkerDestroyed: 'workerdestroyed',+ },++ Browser: {+ TargetCreated: 'targetcreated',+ TargetDestroyed: 'targetdestroyed',+ TargetChanged: 'targetchanged',+ Disconnected: 'disconnected'+ },++ BrowserContext: {+ TargetCreated: 'targetcreated',+ TargetDestroyed: 'targetdestroyed',+ TargetChanged: 'targetchanged',+ },++};diff --git a/src/TimeoutSettings.ts b/src/TimeoutSettings.tsnew file mode 100644index 0000000000..a452ab7608--- /dev/null+++ b/src/TimeoutSettings.ts@@ -0,0 +1,45 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const DEFAULT_TIMEOUT = 30000;++export class TimeoutSettings {+ private _defaultTimeout: number | null = null;+ private _defaultNavigationTimeout: number | null = null;++ setDefaultTimeout(timeout: number) {+ this._defaultTimeout = timeout;+ }++ setDefaultNavigationTimeout(timeout: number) {+ this._defaultNavigationTimeout = timeout;+ }++ navigationTimeout(): number {+ if (this._defaultNavigationTimeout !== null)+ return this._defaultNavigationTimeout;+ if (this._defaultTimeout !== null)+ return this._defaultTimeout;+ return DEFAULT_TIMEOUT;+ }++ timeout() {+ if (this._defaultTimeout !== null)+ return this._defaultTimeout;+ return DEFAULT_TIMEOUT;+ }+}diff --git a/src/USKeyboardLayout.ts b/src/USKeyboardLayout.tsnew file mode 100644index 0000000000..fc046d5c3c--- /dev/null+++ b/src/USKeyboardLayout.ts@@ -0,0 +1,285 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the 'License');+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an 'AS IS' BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++type KeyDefinition = {+ keyCode?: number+ shiftKeyCode?: number+ key?: string+ shiftKey?: string+ code?: string+ text?: string+ shiftText?: string+ location ?: number+}++export const keyDefinitions: { [s: string]: KeyDefinition; } = {+ '0': {'keyCode': 48, 'key': '0', 'code': 'Digit0'},+ '1': {'keyCode': 49, 'key': '1', 'code': 'Digit1'},+ '2': {'keyCode': 50, 'key': '2', 'code': 'Digit2'},+ '3': {'keyCode': 51, 'key': '3', 'code': 'Digit3'},+ '4': {'keyCode': 52, 'key': '4', 'code': 'Digit4'},+ '5': {'keyCode': 53, 'key': '5', 'code': 'Digit5'},+ '6': {'keyCode': 54, 'key': '6', 'code': 'Digit6'},+ '7': {'keyCode': 55, 'key': '7', 'code': 'Digit7'},+ '8': {'keyCode': 56, 'key': '8', 'code': 'Digit8'},+ '9': {'keyCode': 57, 'key': '9', 'code': 'Digit9'},+ 'Power': {'key': 'Power', 'code': 'Power'},+ 'Eject': {'key': 'Eject', 'code': 'Eject'},+ 'Abort': {'keyCode': 3, 'code': 'Abort', 'key': 'Cancel'},+ 'Help': {'keyCode': 6, 'code': 'Help', 'key': 'Help'},+ 'Backspace': {'keyCode': 8, 'code': 'Backspace', 'key': 'Backspace'},+ 'Tab': {'keyCode': 9, 'code': 'Tab', 'key': 'Tab'},+ 'Numpad5': {'keyCode': 12, 'shiftKeyCode': 101, 'key': 'Clear', 'code': 'Numpad5', 'shiftKey': '5', 'location': 3},+ 'NumpadEnter': {'keyCode': 13, 'code': 'NumpadEnter', 'key': 'Enter', 'text': '\r', 'location': 3},+ 'Enter': {'keyCode': 13, 'code': 'Enter', 'key': 'Enter', 'text': '\r'},+ '\r': {'keyCode': 13, 'code': 'Enter', 'key': 'Enter', 'text': '\r'},+ '\n': {'keyCode': 13, 'code': 'Enter', 'key': 'Enter', 'text': '\r'},+ 'ShiftLeft': {'keyCode': 16, 'code': 'ShiftLeft', 'key': 'Shift', 'location': 1},+ 'ShiftRight': {'keyCode': 16, 'code': 'ShiftRight', 'key': 'Shift', 'location': 2},+ 'ControlLeft': {'keyCode': 17, 'code': 'ControlLeft', 'key': 'Control', 'location': 1},+ 'ControlRight': {'keyCode': 17, 'code': 'ControlRight', 'key': 'Control', 'location': 2},+ 'AltLeft': {'keyCode': 18, 'code': 'AltLeft', 'key': 'Alt', 'location': 1},+ 'AltRight': {'keyCode': 18, 'code': 'AltRight', 'key': 'Alt', 'location': 2},+ 'Pause': {'keyCode': 19, 'code': 'Pause', 'key': 'Pause'},+ 'CapsLock': {'keyCode': 20, 'code': 'CapsLock', 'key': 'CapsLock'},+ 'Escape': {'keyCode': 27, 'code': 'Escape', 'key': 'Escape'},+ 'Convert': {'keyCode': 28, 'code': 'Convert', 'key': 'Convert'},+ 'NonConvert': {'keyCode': 29, 'code': 'NonConvert', 'key': 'NonConvert'},+ 'Space': {'keyCode': 32, 'code': 'Space', 'key': ' '},+ 'Numpad9': {'keyCode': 33, 'shiftKeyCode': 105, 'key': 'PageUp', 'code': 'Numpad9', 'shiftKey': '9', 'location': 3},+ 'PageUp': {'keyCode': 33, 'code': 'PageUp', 'key': 'PageUp'},+ 'Numpad3': {'keyCode': 34, 'shiftKeyCode': 99, 'key': 'PageDown', 'code': 'Numpad3', 'shiftKey': '3', 'location': 3},+ 'PageDown': {'keyCode': 34, 'code': 'PageDown', 'key': 'PageDown'},+ 'End': {'keyCode': 35, 'code': 'End', 'key': 'End'},+ 'Numpad1': {'keyCode': 35, 'shiftKeyCode': 97, 'key': 'End', 'code': 'Numpad1', 'shiftKey': '1', 'location': 3},+ 'Home': {'keyCode': 36, 'code': 'Home', 'key': 'Home'},+ 'Numpad7': {'keyCode': 36, 'shiftKeyCode': 103, 'key': 'Home', 'code': 'Numpad7', 'shiftKey': '7', 'location': 3},+ 'ArrowLeft': {'keyCode': 37, 'code': 'ArrowLeft', 'key': 'ArrowLeft'},+ 'Numpad4': {'keyCode': 37, 'shiftKeyCode': 100, 'key': 'ArrowLeft', 'code': 'Numpad4', 'shiftKey': '4', 'location': 3},+ 'Numpad8': {'keyCode': 38, 'shiftKeyCode': 104, 'key': 'ArrowUp', 'code': 'Numpad8', 'shiftKey': '8', 'location': 3},+ 'ArrowUp': {'keyCode': 38, 'code': 'ArrowUp', 'key': 'ArrowUp'},+ 'ArrowRight': {'keyCode': 39, 'code': 'ArrowRight', 'key': 'ArrowRight'},+ 'Numpad6': {'keyCode': 39, 'shiftKeyCode': 102, 'key': 'ArrowRight', 'code': 'Numpad6', 'shiftKey': '6', 'location': 3},+ 'Numpad2': {'keyCode': 40, 'shiftKeyCode': 98, 'key': 'ArrowDown', 'code': 'Numpad2', 'shiftKey': '2', 'location': 3},+ 'ArrowDown': {'keyCode': 40, 'code': 'ArrowDown', 'key': 'ArrowDown'},+ 'Select': {'keyCode': 41, 'code': 'Select', 'key': 'Select'},+ 'Open': {'keyCode': 43, 'code': 'Open', 'key': 'Execute'},+ 'PrintScreen': {'keyCode': 44, 'code': 'PrintScreen', 'key': 'PrintScreen'},+ 'Insert': {'keyCode': 45, 'code': 'Insert', 'key': 'Insert'},+ 'Numpad0': {'keyCode': 45, 'shiftKeyCode': 96, 'key': 'Insert', 'code': 'Numpad0', 'shiftKey': '0', 'location': 3},+ 'Delete': {'keyCode': 46, 'code': 'Delete', 'key': 'Delete'},+ 'NumpadDecimal': {'keyCode': 46, 'shiftKeyCode': 110, 'code': 'NumpadDecimal', 'key': '\u0000', 'shiftKey': '.', 'location': 3},+ 'Digit0': {'keyCode': 48, 'code': 'Digit0', 'shiftKey': ')', 'key': '0'},+ 'Digit1': {'keyCode': 49, 'code': 'Digit1', 'shiftKey': '!', 'key': '1'},+ 'Digit2': {'keyCode': 50, 'code': 'Digit2', 'shiftKey': '@', 'key': '2'},+ 'Digit3': {'keyCode': 51, 'code': 'Digit3', 'shiftKey': '#', 'key': '3'},+ 'Digit4': {'keyCode': 52, 'code': 'Digit4', 'shiftKey': '$', 'key': '4'},+ 'Digit5': {'keyCode': 53, 'code': 'Digit5', 'shiftKey': '%', 'key': '5'},+ 'Digit6': {'keyCode': 54, 'code': 'Digit6', 'shiftKey': '^', 'key': '6'},+ 'Digit7': {'keyCode': 55, 'code': 'Digit7', 'shiftKey': '&', 'key': '7'},+ 'Digit8': {'keyCode': 56, 'code': 'Digit8', 'shiftKey': '*', 'key': '8'},+ 'Digit9': {'keyCode': 57, 'code': 'Digit9', 'shiftKey': '\(', 'key': '9'},+ 'KeyA': {'keyCode': 65, 'code': 'KeyA', 'shiftKey': 'A', 'key': 'a'},+ 'KeyB': {'keyCode': 66, 'code': 'KeyB', 'shiftKey': 'B', 'key': 'b'},+ 'KeyC': {'keyCode': 67, 'code': 'KeyC', 'shiftKey': 'C', 'key': 'c'},+ 'KeyD': {'keyCode': 68, 'code': 'KeyD', 'shiftKey': 'D', 'key': 'd'},+ 'KeyE': {'keyCode': 69, 'code': 'KeyE', 'shiftKey': 'E', 'key': 'e'},+ 'KeyF': {'keyCode': 70, 'code': 'KeyF', 'shiftKey': 'F', 'key': 'f'},+ 'KeyG': {'keyCode': 71, 'code': 'KeyG', 'shiftKey': 'G', 'key': 'g'},+ 'KeyH': {'keyCode': 72, 'code': 'KeyH', 'shiftKey': 'H', 'key': 'h'},+ 'KeyI': {'keyCode': 73, 'code': 'KeyI', 'shiftKey': 'I', 'key': 'i'},+ 'KeyJ': {'keyCode': 74, 'code': 'KeyJ', 'shiftKey': 'J', 'key': 'j'},+ 'KeyK': {'keyCode': 75, 'code': 'KeyK', 'shiftKey': 'K', 'key': 'k'},+ 'KeyL': {'keyCode': 76, 'code': 'KeyL', 'shiftKey': 'L', 'key': 'l'},+ 'KeyM': {'keyCode': 77, 'code': 'KeyM', 'shiftKey': 'M', 'key': 'm'},+ 'KeyN': {'keyCode': 78, 'code': 'KeyN', 'shiftKey': 'N', 'key': 'n'},+ 'KeyO': {'keyCode': 79, 'code': 'KeyO', 'shiftKey': 'O', 'key': 'o'},+ 'KeyP': {'keyCode': 80, 'code': 'KeyP', 'shiftKey': 'P', 'key': 'p'},+ 'KeyQ': {'keyCode': 81, 'code': 'KeyQ', 'shiftKey': 'Q', 'key': 'q'},+ 'KeyR': {'keyCode': 82, 'code': 'KeyR', 'shiftKey': 'R', 'key': 'r'},+ 'KeyS': {'keyCode': 83, 'code': 'KeyS', 'shiftKey': 'S', 'key': 's'},+ 'KeyT': {'keyCode': 84, 'code': 'KeyT', 'shiftKey': 'T', 'key': 't'},+ 'KeyU': {'keyCode': 85, 'code': 'KeyU', 'shiftKey': 'U', 'key': 'u'},+ 'KeyV': {'keyCode': 86, 'code': 'KeyV', 'shiftKey': 'V', 'key': 'v'},+ 'KeyW': {'keyCode': 87, 'code': 'KeyW', 'shiftKey': 'W', 'key': 'w'},+ 'KeyX': {'keyCode': 88, 'code': 'KeyX', 'shiftKey': 'X', 'key': 'x'},+ 'KeyY': {'keyCode': 89, 'code': 'KeyY', 'shiftKey': 'Y', 'key': 'y'},+ 'KeyZ': {'keyCode': 90, 'code': 'KeyZ', 'shiftKey': 'Z', 'key': 'z'},+ 'MetaLeft': {'keyCode': 91, 'code': 'MetaLeft', 'key': 'Meta', 'location': 1},+ 'MetaRight': {'keyCode': 92, 'code': 'MetaRight', 'key': 'Meta', 'location': 2},+ 'ContextMenu': {'keyCode': 93, 'code': 'ContextMenu', 'key': 'ContextMenu'},+ 'NumpadMultiply': {'keyCode': 106, 'code': 'NumpadMultiply', 'key': '*', 'location': 3},+ 'NumpadAdd': {'keyCode': 107, 'code': 'NumpadAdd', 'key': '+', 'location': 3},+ 'NumpadSubtract': {'keyCode': 109, 'code': 'NumpadSubtract', 'key': '-', 'location': 3},+ 'NumpadDivide': {'keyCode': 111, 'code': 'NumpadDivide', 'key': '/', 'location': 3},+ 'F1': {'keyCode': 112, 'code': 'F1', 'key': 'F1'},+ 'F2': {'keyCode': 113, 'code': 'F2', 'key': 'F2'},+ 'F3': {'keyCode': 114, 'code': 'F3', 'key': 'F3'},+ 'F4': {'keyCode': 115, 'code': 'F4', 'key': 'F4'},+ 'F5': {'keyCode': 116, 'code': 'F5', 'key': 'F5'},+ 'F6': {'keyCode': 117, 'code': 'F6', 'key': 'F6'},+ 'F7': {'keyCode': 118, 'code': 'F7', 'key': 'F7'},+ 'F8': {'keyCode': 119, 'code': 'F8', 'key': 'F8'},+ 'F9': {'keyCode': 120, 'code': 'F9', 'key': 'F9'},+ 'F10': {'keyCode': 121, 'code': 'F10', 'key': 'F10'},+ 'F11': {'keyCode': 122, 'code': 'F11', 'key': 'F11'},+ 'F12': {'keyCode': 123, 'code': 'F12', 'key': 'F12'},+ 'F13': {'keyCode': 124, 'code': 'F13', 'key': 'F13'},+ 'F14': {'keyCode': 125, 'code': 'F14', 'key': 'F14'},+ 'F15': {'keyCode': 126, 'code': 'F15', 'key': 'F15'},+ 'F16': {'keyCode': 127, 'code': 'F16', 'key': 'F16'},+ 'F17': {'keyCode': 128, 'code': 'F17', 'key': 'F17'},+ 'F18': {'keyCode': 129, 'code': 'F18', 'key': 'F18'},+ 'F19': {'keyCode': 130, 'code': 'F19', 'key': 'F19'},+ 'F20': {'keyCode': 131, 'code': 'F20', 'key': 'F20'},+ 'F21': {'keyCode': 132, 'code': 'F21', 'key': 'F21'},+ 'F22': {'keyCode': 133, 'code': 'F22', 'key': 'F22'},+ 'F23': {'keyCode': 134, 'code': 'F23', 'key': 'F23'},+ 'F24': {'keyCode': 135, 'code': 'F24', 'key': 'F24'},+ 'NumLock': {'keyCode': 144, 'code': 'NumLock', 'key': 'NumLock'},+ 'ScrollLock': {'keyCode': 145, 'code': 'ScrollLock', 'key': 'ScrollLock'},+ 'AudioVolumeMute': {'keyCode': 173, 'code': 'AudioVolumeMute', 'key': 'AudioVolumeMute'},+ 'AudioVolumeDown': {'keyCode': 174, 'code': 'AudioVolumeDown', 'key': 'AudioVolumeDown'},+ 'AudioVolumeUp': {'keyCode': 175, 'code': 'AudioVolumeUp', 'key': 'AudioVolumeUp'},+ 'MediaTrackNext': {'keyCode': 176, 'code': 'MediaTrackNext', 'key': 'MediaTrackNext'},+ 'MediaTrackPrevious': {'keyCode': 177, 'code': 'MediaTrackPrevious', 'key': 'MediaTrackPrevious'},+ 'MediaStop': {'keyCode': 178, 'code': 'MediaStop', 'key': 'MediaStop'},+ 'MediaPlayPause': {'keyCode': 179, 'code': 'MediaPlayPause', 'key': 'MediaPlayPause'},+ 'Semicolon': {'keyCode': 186, 'code': 'Semicolon', 'shiftKey': ':', 'key': ';'},+ 'Equal': {'keyCode': 187, 'code': 'Equal', 'shiftKey': '+', 'key': '='},+ 'NumpadEqual': {'keyCode': 187, 'code': 'NumpadEqual', 'key': '=', 'location': 3},+ 'Comma': {'keyCode': 188, 'code': 'Comma', 'shiftKey': '\<', 'key': ','},+ 'Minus': {'keyCode': 189, 'code': 'Minus', 'shiftKey': '_', 'key': '-'},+ 'Period': {'keyCode': 190, 'code': 'Period', 'shiftKey': '>', 'key': '.'},+ 'Slash': {'keyCode': 191, 'code': 'Slash', 'shiftKey': '?', 'key': '/'},+ 'Backquote': {'keyCode': 192, 'code': 'Backquote', 'shiftKey': '~', 'key': '`'},+ 'BracketLeft': {'keyCode': 219, 'code': 'BracketLeft', 'shiftKey': '{', 'key': '['},+ 'Backslash': {'keyCode': 220, 'code': 'Backslash', 'shiftKey': '|', 'key': '\\'},+ 'BracketRight': {'keyCode': 221, 'code': 'BracketRight', 'shiftKey': '}', 'key': ']'},+ 'Quote': {'keyCode': 222, 'code': 'Quote', 'shiftKey': '"', 'key': '\''},+ 'AltGraph': {'keyCode': 225, 'code': 'AltGraph', 'key': 'AltGraph'},+ 'Props': {'keyCode': 247, 'code': 'Props', 'key': 'CrSel'},+ 'Cancel': {'keyCode': 3, 'key': 'Cancel', 'code': 'Abort'},+ 'Clear': {'keyCode': 12, 'key': 'Clear', 'code': 'Numpad5', 'location': 3},+ 'Shift': {'keyCode': 16, 'key': 'Shift', 'code': 'ShiftLeft', 'location': 1},+ 'Control': {'keyCode': 17, 'key': 'Control', 'code': 'ControlLeft', 'location': 1},+ 'Alt': {'keyCode': 18, 'key': 'Alt', 'code': 'AltLeft', 'location': 1},+ 'Accept': {'keyCode': 30, 'key': 'Accept'},+ 'ModeChange': {'keyCode': 31, 'key': 'ModeChange'},+ ' ': {'keyCode': 32, 'key': ' ', 'code': 'Space'},+ 'Print': {'keyCode': 42, 'key': 'Print'},+ 'Execute': {'keyCode': 43, 'key': 'Execute', 'code': 'Open'},+ '\u0000': {'keyCode': 46, 'key': '\u0000', 'code': 'NumpadDecimal', 'location': 3},+ 'a': {'keyCode': 65, 'key': 'a', 'code': 'KeyA'},+ 'b': {'keyCode': 66, 'key': 'b', 'code': 'KeyB'},+ 'c': {'keyCode': 67, 'key': 'c', 'code': 'KeyC'},+ 'd': {'keyCode': 68, 'key': 'd', 'code': 'KeyD'},+ 'e': {'keyCode': 69, 'key': 'e', 'code': 'KeyE'},+ 'f': {'keyCode': 70, 'key': 'f', 'code': 'KeyF'},+ 'g': {'keyCode': 71, 'key': 'g', 'code': 'KeyG'},+ 'h': {'keyCode': 72, 'key': 'h', 'code': 'KeyH'},+ 'i': {'keyCode': 73, 'key': 'i', 'code': 'KeyI'},+ 'j': {'keyCode': 74, 'key': 'j', 'code': 'KeyJ'},+ 'k': {'keyCode': 75, 'key': 'k', 'code': 'KeyK'},+ 'l': {'keyCode': 76, 'key': 'l', 'code': 'KeyL'},+ 'm': {'keyCode': 77, 'key': 'm', 'code': 'KeyM'},+ 'n': {'keyCode': 78, 'key': 'n', 'code': 'KeyN'},+ 'o': {'keyCode': 79, 'key': 'o', 'code': 'KeyO'},+ 'p': {'keyCode': 80, 'key': 'p', 'code': 'KeyP'},+ 'q': {'keyCode': 81, 'key': 'q', 'code': 'KeyQ'},+ 'r': {'keyCode': 82, 'key': 'r', 'code': 'KeyR'},+ 's': {'keyCode': 83, 'key': 's', 'code': 'KeyS'},+ 't': {'keyCode': 84, 'key': 't', 'code': 'KeyT'},+ 'u': {'keyCode': 85, 'key': 'u', 'code': 'KeyU'},+ 'v': {'keyCode': 86, 'key': 'v', 'code': 'KeyV'},+ 'w': {'keyCode': 87, 'key': 'w', 'code': 'KeyW'},+ 'x': {'keyCode': 88, 'key': 'x', 'code': 'KeyX'},+ 'y': {'keyCode': 89, 'key': 'y', 'code': 'KeyY'},+ 'z': {'keyCode': 90, 'key': 'z', 'code': 'KeyZ'},+ 'Meta': {'keyCode': 91, 'key': 'Meta', 'code': 'MetaLeft', 'location': 1},+ '*': {'keyCode': 106, 'key': '*', 'code': 'NumpadMultiply', 'location': 3},+ '+': {'keyCode': 107, 'key': '+', 'code': 'NumpadAdd', 'location': 3},+ '-': {'keyCode': 109, 'key': '-', 'code': 'NumpadSubtract', 'location': 3},+ '/': {'keyCode': 111, 'key': '/', 'code': 'NumpadDivide', 'location': 3},+ ';': {'keyCode': 186, 'key': ';', 'code': 'Semicolon'},+ '=': {'keyCode': 187, 'key': '=', 'code': 'Equal'},+ ',': {'keyCode': 188, 'key': ',', 'code': 'Comma'},+ '.': {'keyCode': 190, 'key': '.', 'code': 'Period'},+ '`': {'keyCode': 192, 'key': '`', 'code': 'Backquote'},+ '[': {'keyCode': 219, 'key': '[', 'code': 'BracketLeft'},+ '\\': {'keyCode': 220, 'key': '\\', 'code': 'Backslash'},+ ']': {'keyCode': 221, 'key': ']', 'code': 'BracketRight'},+ '\'': {'keyCode': 222, 'key': '\'', 'code': 'Quote'},+ 'Attn': {'keyCode': 246, 'key': 'Attn'},+ 'CrSel': {'keyCode': 247, 'key': 'CrSel', 'code': 'Props'},+ 'ExSel': {'keyCode': 248, 'key': 'ExSel'},+ 'EraseEof': {'keyCode': 249, 'key': 'EraseEof'},+ 'Play': {'keyCode': 250, 'key': 'Play'},+ 'ZoomOut': {'keyCode': 251, 'key': 'ZoomOut'},+ ')': {'keyCode': 48, 'key': ')', 'code': 'Digit0'},+ '!': {'keyCode': 49, 'key': '!', 'code': 'Digit1'},+ '@': {'keyCode': 50, 'key': '@', 'code': 'Digit2'},+ '#': {'keyCode': 51, 'key': '#', 'code': 'Digit3'},+ '$': {'keyCode': 52, 'key': '$', 'code': 'Digit4'},+ '%': {'keyCode': 53, 'key': '%', 'code': 'Digit5'},+ '^': {'keyCode': 54, 'key': '^', 'code': 'Digit6'},+ '&': {'keyCode': 55, 'key': '&', 'code': 'Digit7'},+ '(': {'keyCode': 57, 'key': '\(', 'code': 'Digit9'},+ 'A': {'keyCode': 65, 'key': 'A', 'code': 'KeyA'},+ 'B': {'keyCode': 66, 'key': 'B', 'code': 'KeyB'},+ 'C': {'keyCode': 67, 'key': 'C', 'code': 'KeyC'},+ 'D': {'keyCode': 68, 'key': 'D', 'code': 'KeyD'},+ 'E': {'keyCode': 69, 'key': 'E', 'code': 'KeyE'},+ 'F': {'keyCode': 70, 'key': 'F', 'code': 'KeyF'},+ 'G': {'keyCode': 71, 'key': 'G', 'code': 'KeyG'},+ 'H': {'keyCode': 72, 'key': 'H', 'code': 'KeyH'},+ 'I': {'keyCode': 73, 'key': 'I', 'code': 'KeyI'},+ 'J': {'keyCode': 74, 'key': 'J', 'code': 'KeyJ'},+ 'K': {'keyCode': 75, 'key': 'K', 'code': 'KeyK'},+ 'L': {'keyCode': 76, 'key': 'L', 'code': 'KeyL'},+ 'M': {'keyCode': 77, 'key': 'M', 'code': 'KeyM'},+ 'N': {'keyCode': 78, 'key': 'N', 'code': 'KeyN'},+ 'O': {'keyCode': 79, 'key': 'O', 'code': 'KeyO'},+ 'P': {'keyCode': 80, 'key': 'P', 'code': 'KeyP'},+ 'Q': {'keyCode': 81, 'key': 'Q', 'code': 'KeyQ'},+ 'R': {'keyCode': 82, 'key': 'R', 'code': 'KeyR'},+ 'S': {'keyCode': 83, 'key': 'S', 'code': 'KeyS'},+ 'T': {'keyCode': 84, 'key': 'T', 'code': 'KeyT'},+ 'U': {'keyCode': 85, 'key': 'U', 'code': 'KeyU'},+ 'V': {'keyCode': 86, 'key': 'V', 'code': 'KeyV'},+ 'W': {'keyCode': 87, 'key': 'W', 'code': 'KeyW'},+ 'X': {'keyCode': 88, 'key': 'X', 'code': 'KeyX'},+ 'Y': {'keyCode': 89, 'key': 'Y', 'code': 'KeyY'},+ 'Z': {'keyCode': 90, 'key': 'Z', 'code': 'KeyZ'},+ ':': {'keyCode': 186, 'key': ':', 'code': 'Semicolon'},+ '<': {'keyCode': 188, 'key': '\<', 'code': 'Comma'},+ '_': {'keyCode': 189, 'key': '_', 'code': 'Minus'},+ '>': {'keyCode': 190, 'key': '>', 'code': 'Period'},+ '?': {'keyCode': 191, 'key': '?', 'code': 'Slash'},+ '~': {'keyCode': 192, 'key': '~', 'code': 'Backquote'},+ '{': {'keyCode': 219, 'key': '{', 'code': 'BracketLeft'},+ '|': {'keyCode': 220, 'key': '|', 'code': 'Backslash'},+ '}': {'keyCode': 221, 'key': '}', 'code': 'BracketRight'},+ '"': {'keyCode': 222, 'key': '"', 'code': 'Quote'},+ 'SoftLeft': {'key': 'SoftLeft', 'code': 'SoftLeft', 'location': 4},+ 'SoftRight': {'key': 'SoftRight', 'code': 'SoftRight', 'location': 4},+ 'Camera': {'keyCode': 44, 'key': 'Camera', 'code': 'Camera', 'location': 4},+ 'Call': {'key': 'Call', 'code': 'Call', 'location': 4},+ 'EndCall': {'keyCode': 95, 'key': 'EndCall', 'code': 'EndCall', 'location': 4},+ 'VolumeDown': {'keyCode': 182, 'key': 'VolumeDown', 'code': 'VolumeDown', 'location': 4},+ 'VolumeUp': {'keyCode': 183, 'key': 'VolumeUp', 'code': 'VolumeUp', 'location': 4},+};\ No newline at end of filediff --git a/src/api.ts b/src/api.tsnew file mode 100644index 0000000000..db511c21fe--- /dev/null+++ b/src/api.ts@@ -0,0 +1,88 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+export = {+ Chromium: {+ Accessibility: require('./chromium/Accessibility').Accessibility,+ Browser: require('./chromium/Browser').Browser,+ BrowserContext: require('./chromium/BrowserContext').BrowserContext,+ BrowserFetcher: require('./chromium/BrowserFetcher').BrowserFetcher,+ CDPSession: require('./chromium/Connection').CDPSession,+ ConsoleMessage: require('./chromium/Page').ConsoleMessage,+ Coverage: require('./chromium/Coverage').Coverage,+ Dialog: require('./chromium/Dialog').Dialog,+ ElementHandle: require('./chromium/JSHandle').ElementHandle,+ ExecutionContext: require('./chromium/ExecutionContext').ExecutionContext,+ FileChooser: require('./chromium/Page').FileChooser,+ Frame: require('./chromium/Frame').Frame,+ JSHandle: require('./chromium/JSHandle').JSHandle,+ Keyboard: require('./chromium/Input').Keyboard,+ Mouse: require('./chromium/Input').Mouse,+ Page: require('./chromium/Page').Page,+ Playwright: require('./chromium/Playwright').Playwright,+ Request: require('./chromium/NetworkManager').Request,+ Response: require('./chromium/NetworkManager').Response,+ SecurityDetails: require('./chromium/NetworkManager').SecurityDetails,+ Target: require('./chromium/Target').Target,+ TimeoutError: require('./Errors').TimeoutError,+ Touchscreen: require('./chromium/Input').Touchscreen,+ Tracing: require('./chromium/Tracing').Tracing,+ Worker: require('./chromium/Worker').Worker,+ },+ Firefox: {+ Accessibility: require('./firefox/Accessibility').Accessibility,+ Browser: require('./firefox/Browser').Browser,+ BrowserContext: require('./firefox/Browser').BrowserContext,+ BrowserFetcher: require('./firefox/BrowserFetcher').BrowserFetcher,+ CDPSession: require('./firefox/Connection').CDPSession,+ ConsoleMessage: require('./firefox/Page').ConsoleMessage,+ Dialog: require('./firefox/Dialog').Dialog,+ ElementHandle: require('./firefox/JSHandle').ElementHandle,+ ExecutionContext: require('./firefox/ExecutionContext').ExecutionContext,+ FileChooser: require('./firefox/Page').FileChooser,+ Frame: require('./firefox/FrameManager').Frame,+ JSHandle: require('./firefox/JSHandle').JSHandle,+ Keyboard: require('./firefox/Input').Keyboard,+ Mouse: require('./firefox/Input').Mouse,+ Page: require('./firefox/Page').Page,+ Playwright: require('./firefox/Playwright').Playwright,+ Request: require('./firefox/NetworkManager').Request,+ Response: require('./firefox/NetworkManager').Response,+ SecurityDetails: require('./firefox/NetworkManager').SecurityDetails,+ Target: require('./firefox/Browser').Target,+ TimeoutError: require('./Errors').TimeoutError,+ Touchscreen: require('./firefox/Input').Touchscreen,+ },+ WebKit: {+ Browser: require('./webkit/Browser').Browser,+ BrowserContext: require('./webkit/Browser').BrowserContext,+ BrowserFetcher: require('./webkit/BrowserFetcher'),+ ConsoleMessage: require('./webkit/Page').ConsoleMessage,+ ElementHandle: require('./webkit/JSHandle').ElementHandle,+ ExecutionContext: require('./webkit/ExecutionContext').ExecutionContext,+ Frame: require('./webkit/FrameManager').Frame,+ JSHandle: require('./webkit/JSHandle').JSHandle,+ Keyboard: require('./webkit/Input').Keyboard,+ Mouse: require('./webkit/Input').Mouse,+ Page: require('./webkit/Page').Page,+ Playwright: require('./webkit/Playwright').Playwright,+ Request: require('./webkit/NetworkManager').Request,+ Response: require('./webkit/NetworkManager').Response,+ Target: require('./webkit/Browser').Target,+ TimeoutError: require('./Errors').TimeoutError,+ Touchscreen: require('./webkit/Input').Touchscreen,+ }+};diff --git a/src/chromium/Accessibility.ts b/src/chromium/Accessibility.tsnew file mode 100644index 0000000000..abcd6e9dbf--- /dev/null+++ b/src/chromium/Accessibility.ts@@ -0,0 +1,373 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the 'License');+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an 'AS IS' BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { CDPSession } from './Connection';+import { ElementHandle } from './JSHandle';+import { Protocol } from './protocol';++type SerializedAXNode = {+ role: string,+ name?: string,+ value?: string|number,+ description?: string,++ keyshortcuts?: string,+ roledescription?: string,+ valuetext?: string,++ disabled?: boolean,+ expanded?: boolean,+ focused?: boolean,+ modal?: boolean,+ multiline?: boolean,+ multiselectable?: boolean,+ readonly?: boolean,+ required?: boolean,+ selected?: boolean,++ checked?: boolean|'mixed',+ pressed?: boolean|'mixed',++ level?: number,+ valuemin?: number,+ valuemax?: number,++ autocomplete?: string,+ haspopup?: string,+ invalid?: string,+ orientation?: string,++ children?: SerializedAXNode[]+};++export class Accessibility {+ private _client: CDPSession;++ constructor(client: CDPSession) {+ this._client = client;+ }++ async snapshot(options: {+ interestingOnly?: boolean;+ root?: ElementHandle | null;+ } = {}): Promise<SerializedAXNode> {+ const {+ interestingOnly = true,+ root = null,+ } = options;+ const {nodes} = await this._client.send('Accessibility.getFullAXTree');+ let backendNodeId = null;+ if (root) {+ const {node} = await this._client.send('DOM.describeNode', {objectId: root._remoteObject.objectId});+ backendNodeId = node.backendNodeId;+ }+ const defaultRoot = AXNode.createTree(nodes);+ let needle = defaultRoot;+ if (backendNodeId) {+ needle = defaultRoot.find(node => node._payload.backendDOMNodeId === backendNodeId);+ if (!needle)+ return null;+ }+ if (!interestingOnly)+ return serializeTree(needle)[0];++ const interestingNodes: Set<AXNode> = new Set();+ collectInterestingNodes(interestingNodes, defaultRoot, false);+ if (!interestingNodes.has(needle))+ return null;+ return serializeTree(needle, interestingNodes)[0];+ }+}++function collectInterestingNodes(collection: Set<AXNode>, node: AXNode, insideControl: boolean) {+ if (node.isInteresting(insideControl))+ collection.add(node);+ if (node.isLeafNode())+ return;+ insideControl = insideControl || node.isControl();+ for (const child of node._children)+ collectInterestingNodes(collection, child, insideControl);+}++function serializeTree(node: AXNode, whitelistedNodes?: Set<AXNode>): SerializedAXNode[] {+ const children: SerializedAXNode[] = [];+ for (const child of node._children)+ children.push(...serializeTree(child, whitelistedNodes));++ if (whitelistedNodes && !whitelistedNodes.has(node))+ return children;++ const serializedNode = node.serialize();+ if (children.length)+ serializedNode.children = children;+ return [serializedNode];+}+++class AXNode {+ _payload: Protocol.Accessibility.AXNode;+ _children: AXNode[] = [];+ private _richlyEditable = false;+ private _editable = false;+ private _focusable = false;+ private _expanded = false;+ private _hidden = false;+ private _name: string;+ private _role: string;+ private _cachedHasFocusableChild: boolean | undefined;++ constructor(payload: Protocol.Accessibility.AXNode) {+ this._payload = payload;++ this._name = this._payload.name ? this._payload.name.value : '';+ this._role = this._payload.role ? this._payload.role.value : 'Unknown';++ for (const property of this._payload.properties || []) {+ if (property.name === 'editable') {+ this._richlyEditable = property.value.value === 'richtext';+ this._editable = true;+ }+ if (property.name === 'focusable')+ this._focusable = property.value.value;+ if (property.name === 'expanded')+ this._expanded = property.value.value;+ if (property.name === 'hidden')+ this._hidden = property.value.value;+ }+ }++ private _isPlainTextField(): boolean {+ if (this._richlyEditable)+ return false;+ if (this._editable)+ return true;+ return this._role === 'textbox' || this._role === 'ComboBox' || this._role === 'searchbox';+ }++ private _isTextOnlyObject(): boolean {+ const role = this._role;+ return (role === 'LineBreak' || role === 'text' ||+ role === 'InlineTextBox');+ }++ private _hasFocusableChild(): boolean {+ if (this._cachedHasFocusableChild === undefined) {+ this._cachedHasFocusableChild = false;+ for (const child of this._children) {+ if (child._focusable || child._hasFocusableChild()) {+ this._cachedHasFocusableChild = true;+ break;+ }+ }+ }+ return this._cachedHasFocusableChild;+ }++ find(predicate: (arg0: AXNode) => boolean): AXNode | null {+ if (predicate(this))+ return this;+ for (const child of this._children) {+ const result = child.find(predicate);+ if (result)+ return result;+ }+ return null;+ }++ isLeafNode(): boolean {+ if (!this._children.length)+ return true;++ // These types of objects may have children that we use as internal+ // implementation details, but we want to expose them as leaves to platform+ // accessibility APIs because screen readers might be confused if they find+ // any children.+ if (this._isPlainTextField() || this._isTextOnlyObject())+ return true;++ // Roles whose children are only presentational according to the ARIA and+ // HTML5 Specs should be hidden from screen readers.+ // (Note that whilst ARIA buttons can have only presentational children, HTML5+ // buttons are allowed to have content.)+ switch (this._role) {+ case 'doc-cover':+ case 'graphics-symbol':+ case 'img':+ case 'Meter':+ case 'scrollbar':+ case 'slider':+ case 'separator':+ case 'progressbar':+ return true;+ default:+ break;+ }++ // Here and below: Android heuristics+ if (this._hasFocusableChild())+ return false;+ if (this._focusable && this._name)+ return true;+ if (this._role === 'heading' && this._name)+ return true;+ return false;+ }++ isControl(): boolean {+ switch (this._role) {+ case 'button':+ case 'checkbox':+ case 'ColorWell':+ case 'combobox':+ case 'DisclosureTriangle':+ case 'listbox':+ case 'menu':+ case 'menubar':+ case 'menuitem':+ case 'menuitemcheckbox':+ case 'menuitemradio':+ case 'radio':+ case 'scrollbar':+ case 'searchbox':+ case 'slider':+ case 'spinbutton':+ case 'switch':+ case 'tab':+ case 'textbox':+ case 'tree':+ return true;+ default:+ return false;+ }+ }++ isInteresting(insideControl: boolean): boolean {+ const role = this._role;+ if (role === 'Ignored' || this._hidden)+ return false;++ if (this._focusable || this._richlyEditable)+ return true;++ // If it's not focusable but has a control role, then it's interesting.+ if (this.isControl())+ return true;++ // A non focusable child of a control is not interesting+ if (insideControl)+ return false;++ return this.isLeafNode() && !!this._name;+ }++ serialize(): SerializedAXNode {+ const properties: Map<string, number | string | boolean> = new Map();+ for (const property of this._payload.properties || [])+ properties.set(property.name.toLowerCase(), property.value.value);+ if (this._payload.name)+ properties.set('name', this._payload.name.value);+ if (this._payload.value)+ properties.set('value', this._payload.value.value);+ if (this._payload.description)+ properties.set('description', this._payload.description.value);++ const node: {[x in keyof SerializedAXNode]: any} = {+ role: this._role+ };++ const userStringProperties: Array<keyof SerializedAXNode> = [+ 'name',+ 'value',+ 'description',+ 'keyshortcuts',+ 'roledescription',+ 'valuetext',+ ];+ for (const userStringProperty of userStringProperties) {+ if (!properties.has(userStringProperty))+ continue;+ node[userStringProperty] = properties.get(userStringProperty);+ }++ const booleanProperties: Array<keyof SerializedAXNode> = [+ 'disabled',+ 'expanded',+ 'focused',+ 'modal',+ 'multiline',+ 'multiselectable',+ 'readonly',+ 'required',+ 'selected',+ ];+ for (const booleanProperty of booleanProperties) {+ // WebArea's treat focus differently than other nodes. They report whether their frame has focus,+ // not whether focus is specifically on the root node.+ if (booleanProperty === 'focused' && this._role === 'WebArea')+ continue;+ const value = properties.get(booleanProperty);+ if (!value)+ continue;+ node[booleanProperty] = value;+ }++ const tristateProperties: Array<keyof SerializedAXNode> = [+ 'checked',+ 'pressed',+ ];+ for (const tristateProperty of tristateProperties) {+ if (!properties.has(tristateProperty))+ continue;+ const value = properties.get(tristateProperty);+ node[tristateProperty] = value === 'mixed' ? 'mixed' : value === 'true' ? true : false;+ }+ const numericalProperties: Array<keyof SerializedAXNode> = [+ 'level',+ 'valuemax',+ 'valuemin',+ ];+ for (const numericalProperty of numericalProperties) {+ if (!properties.has(numericalProperty))+ continue;+ node[numericalProperty] = properties.get(numericalProperty);+ }+ const tokenProperties: Array<keyof SerializedAXNode> = [+ 'autocomplete',+ 'haspopup',+ 'invalid',+ 'orientation',+ ];+ for (const tokenProperty of tokenProperties) {+ const value = properties.get(tokenProperty);+ if (!value || value === 'false')+ continue;+ node[tokenProperty] = value;+ }+ return node as SerializedAXNode;+ }++ static createTree(payloads: Protocol.Accessibility.AXNode[]): AXNode {+ const nodeById: Map<string, AXNode> = new Map();+ for (const payload of payloads)+ nodeById.set(payload.nodeId, new AXNode(payload));+ for (const node of nodeById.values()) {+ for (const childId of node._payload.childIds || [])+ node._children.push(nodeById.get(childId));+ }+ return nodeById.values().next().value;+ }+}diff --git a/src/chromium/Browser.ts b/src/chromium/Browser.tsnew file mode 100644index 0000000000..e5ff1e65df--- /dev/null+++ b/src/chromium/Browser.ts@@ -0,0 +1,220 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import * as childProcess from 'child_process';+import { EventEmitter } from 'events';+import { Events } from '../Events';+import { assert, helper } from '../helper';+import { BrowserContext } from './BrowserContext';+import { Connection, ConnectionEvents } from './Connection';+import { Page, Viewport } from './Page';+import { Target } from './Target';+import { TaskQueue } from './TaskQueue';+import { Protocol } from './protocol';++export class Browser extends EventEmitter {+ private _ignoreHTTPSErrors: boolean;+ private _defaultViewport: Viewport;+ private _process: childProcess.ChildProcess;+ private _screenshotTaskQueue = new TaskQueue();+ private _connection: Connection;+ private _closeCallback: () => Promise<void>;+ private _defaultContext: BrowserContext;+ private _contexts = new Map<string, BrowserContext>();+ _targets = new Map<string, Target>();++ static async create(+ connection: Connection,+ contextIds: string[],+ ignoreHTTPSErrors: boolean,+ defaultViewport: Viewport | null,+ process: childProcess.ChildProcess | null,+ closeCallback?: (() => Promise<void>)) {+ const browser = new Browser(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process, closeCallback);+ await connection.send('Target.setDiscoverTargets', {discover: true});+ return browser;+ }++ constructor(+ connection: Connection,+ contextIds: string[],+ ignoreHTTPSErrors: boolean,+ defaultViewport: Viewport | null,+ process: childProcess.ChildProcess | null,+ closeCallback?: (() => Promise<void>)) {+ super();+ this._ignoreHTTPSErrors = ignoreHTTPSErrors;+ this._defaultViewport = defaultViewport;+ this._process = process;+ this._connection = connection;+ this._closeCallback = closeCallback || (() => Promise.resolve());++ this._defaultContext = new BrowserContext(this._connection, this, null);+ for (const contextId of contextIds)+ this._contexts.set(contextId, new BrowserContext(this._connection, this, contextId));++ this._connection.on(ConnectionEvents.Disconnected, () => this.emit(Events.Browser.Disconnected));+ this._connection.on('Target.targetCreated', this._targetCreated.bind(this));+ this._connection.on('Target.targetDestroyed', this._targetDestroyed.bind(this));+ this._connection.on('Target.targetInfoChanged', this._targetInfoChanged.bind(this));+ }++ process(): childProcess.ChildProcess | null {+ return this._process;+ }++ async createIncognitoBrowserContext(): Promise<BrowserContext> {+ const {browserContextId} = await this._connection.send('Target.createBrowserContext');+ const context = new BrowserContext(this._connection, this, browserContextId);+ this._contexts.set(browserContextId, context);+ return context;+ }++ browserContexts(): BrowserContext[] {+ return [this._defaultContext, ...Array.from(this._contexts.values())];+ }++ defaultBrowserContext(): BrowserContext {+ return this._defaultContext;+ }++ async _disposeContext(contextId: string | null) {+ await this._connection.send('Target.disposeBrowserContext', {browserContextId: contextId || undefined});+ this._contexts.delete(contextId);+ }++ async _targetCreated(event: Protocol.Target.targetCreatedPayload) {+ const targetInfo = event.targetInfo;+ const {browserContextId} = targetInfo;+ const context = (browserContextId && this._contexts.has(browserContextId)) ? this._contexts.get(browserContextId) : this._defaultContext;++ const target = new Target(targetInfo, context, () => this._connection.createSession(targetInfo), this._ignoreHTTPSErrors, this._defaultViewport, this._screenshotTaskQueue);+ assert(!this._targets.has(event.targetInfo.targetId), 'Target should not exist before targetCreated');+ this._targets.set(event.targetInfo.targetId, target);++ if (await target._initializedPromise) {+ this.emit(Events.Browser.TargetCreated, target);+ context.emit(Events.BrowserContext.TargetCreated, target);+ }+ }++ async _targetDestroyed(event: { targetId: string; }) {+ const target = this._targets.get(event.targetId);+ target._initializedCallback(false);+ this._targets.delete(event.targetId);+ target._closedCallback();+ if (await target._initializedPromise) {+ this.emit(Events.Browser.TargetDestroyed, target);+ target.browserContext().emit(Events.BrowserContext.TargetDestroyed, target);+ }+ }++ _targetInfoChanged(event: Protocol.Target.targetInfoChangedPayload) {+ const target = this._targets.get(event.targetInfo.targetId);+ assert(target, 'target should exist before targetInfoChanged');+ const previousURL = target.url();+ const wasInitialized = target._isInitialized;+ target._targetInfoChanged(event.targetInfo);+ if (wasInitialized && previousURL !== target.url()) {+ this.emit(Events.Browser.TargetChanged, target);+ target.browserContext().emit(Events.BrowserContext.TargetChanged, target);+ }+ }++ wsEndpoint(): string {+ return this._connection.url();+ }++ async newPage(): Promise<Page> {+ return this._defaultContext.newPage();+ }++ async _createPageInContext(contextId: string | null): Promise<Page> {+ const {targetId} = await this._connection.send('Target.createTarget', {url: 'about:blank', browserContextId: contextId || undefined});+ const target = await this._targets.get(targetId);+ assert(await target._initializedPromise, 'Failed to create target for page');+ const page = await target.page();+ return page;+ }++ targets(): Target[] {+ return Array.from(this._targets.values()).filter(target => target._isInitialized);+ }++ target(): Target {+ return this.targets().find(target => target.type() === 'browser');+ }++ async waitForTarget(predicate: (arg0: Target) => boolean, options: { timeout?: number; } | undefined = {}): Promise<Target> {+ const {+ timeout = 30000+ } = options;+ const existingTarget = this.targets().find(predicate);+ if (existingTarget)+ return existingTarget;+ let resolve;+ const targetPromise = new Promise<Target>(x => resolve = x);+ this.on(Events.Browser.TargetCreated, check);+ this.on(Events.Browser.TargetChanged, check);+ try {+ if (!timeout)+ return await targetPromise;+ return await helper.waitWithTimeout(targetPromise, 'target', timeout);+ } finally {+ this.removeListener(Events.Browser.TargetCreated, check);+ this.removeListener(Events.Browser.TargetChanged, check);+ }++ function check(target: Target) {+ if (predicate(target))+ resolve(target);+ }+ }++ async pages(): Promise<Page[]> {+ const contextPages = await Promise.all(this.browserContexts().map(context => context.pages()));+ // Flatten array.+ return contextPages.reduce((acc, x) => acc.concat(x), []);+ }++ async version(): Promise<string> {+ const version = await this._getVersion();+ return version.product;+ }++ async userAgent(): Promise<string> {+ const version = await this._getVersion();+ return version.userAgent;+ }++ async close() {+ await this._closeCallback.call(null);+ this.disconnect();+ }++ disconnect() {+ this._connection.dispose();+ }++ isConnected(): boolean {+ return !this._connection._closed;+ }++ _getVersion(): Promise<any> {+ return this._connection.send('Browser.getVersion');+ }+}diff --git a/src/chromium/BrowserContext.ts b/src/chromium/BrowserContext.tsnew file mode 100644index 0000000000..7122ea431e--- /dev/null+++ b/src/chromium/BrowserContext.ts@@ -0,0 +1,103 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { EventEmitter } from 'events';+import { assert } from '../helper';+import { Browser } from './Browser';+import { Connection } from './Connection';+import { Page } from './Page';+import { Target } from './Target';+import { Protocol } from './protocol';++export class BrowserContext extends EventEmitter {+ private _connection: Connection;+ private _browser: Browser;+ private _id: string;++ constructor(connection: Connection, browser: Browser, contextId: string | null) {+ super();+ this._connection = connection;+ this._browser = browser;+ this._id = contextId;+ }++ targets(): Target[] {+ return this._browser.targets().filter(target => target.browserContext() === this);+ }++ waitForTarget(predicate: (arg0: Target) => boolean, options: { timeout?: number; } | undefined): Promise<Target> {+ return this._browser.waitForTarget(target => target.browserContext() === this && predicate(target), options);+ }++ async pages(): Promise<Page[]> {+ const pages = await Promise.all(+ this.targets()+ .filter(target => target.type() === 'page')+ .map(target => target.page())+ );+ return pages.filter(page => !!page);+ }++ isIncognito(): boolean {+ return !!this._id;+ }++ async overridePermissions(origin: string, userPermissions: string[]) {+ const webPermissionToProtocol = new Map<string, Protocol.Browser.PermissionType>([+ ['geolocation', 'geolocation'],+ ['midi', 'midi'],+ ['notifications', 'notifications'],+ ['camera', 'videoCapture'],+ ['microphone', 'audioCapture'],+ ['background-sync', 'backgroundSync'],+ ['ambient-light-sensor', 'sensors'],+ ['accelerometer', 'sensors'],+ ['gyroscope', 'sensors'],+ ['magnetometer', 'sensors'],+ ['accessibility-events', 'accessibilityEvents'],+ ['clipboard-read', 'clipboardRead'],+ ['clipboard-write', 'clipboardWrite'],+ ['payment-handler', 'paymentHandler'],+ // chrome-specific permissions we have.+ ['midi-sysex', 'midiSysex'],+ ]);+ const permissions = userPermissions.map(permission => {+ const protocolPermission = webPermissionToProtocol.get(permission);+ if (!protocolPermission)+ throw new Error('Unknown permission: ' + permission);+ return protocolPermission;+ });+ await this._connection.send('Browser.grantPermissions', {origin, browserContextId: this._id || undefined, permissions});+ }++ async clearPermissionOverrides() {+ await this._connection.send('Browser.resetPermissions', {browserContextId: this._id || undefined});+ }++ newPage(): Promise<Page> {+ return this._browser._createPageInContext(this._id);+ }++ browser(): Browser {+ return this._browser;+ }++ async close() {+ assert(this._id, 'Non-incognito profiles cannot be closed!');+ await this._browser._disposeContext(this._id);+ }+}diff --git a/src/chromium/BrowserFetcher.ts b/src/chromium/BrowserFetcher.tsnew file mode 100644index 0000000000..10ca8ffad4--- /dev/null+++ b/src/chromium/BrowserFetcher.ts@@ -0,0 +1,261 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import * as extract from 'extract-zip';+import * as fs from 'fs';+import * as ProxyAgent from 'https-proxy-agent';+import * as os from 'os';+import * as path from 'path';+// @ts-ignore+import { getProxyForUrl } from 'proxy-from-env';+import * as removeRecursive from 'rimraf';+import * as URL from 'url';+import * as util from 'util';+import { assert, helper } from '../helper';++const DEFAULT_DOWNLOAD_HOST = 'https://storage.googleapis.com';++const supportedPlatforms = ['mac', 'linux', 'win32', 'win64'];+const downloadURLs = {+ linux: '%s/chromium-browser-snapshots/Linux_x64/%d/%s.zip',+ mac: '%s/chromium-browser-snapshots/Mac/%d/%s.zip',+ win32: '%s/chromium-browser-snapshots/Win/%d/%s.zip',+ win64: '%s/chromium-browser-snapshots/Win_x64/%d/%s.zip',+};++function archiveName(platform: string, revision: string): string {+ if (platform === 'linux')+ return 'chrome-linux';+ if (platform === 'mac')+ return 'chrome-mac';+ if (platform === 'win32' || platform === 'win64') {+ // Windows archive name changed at r591479.+ return parseInt(revision, 10) > 591479 ? 'chrome-win' : 'chrome-win32';+ }+ return null;+}++function downloadURL(platform: string, host: string, revision: string): string {+ return util.format(downloadURLs[platform], host, revision, archiveName(platform, revision));+}++const readdirAsync = helper.promisify(fs.readdir.bind(fs));+const mkdirAsync = helper.promisify(fs.mkdir.bind(fs));+const unlinkAsync = helper.promisify(fs.unlink.bind(fs));+const chmodAsync = helper.promisify(fs.chmod.bind(fs));++function existsAsync(filePath) {+ let fulfill = null;+ const promise = new Promise(x => fulfill = x);+ fs.access(filePath, err => fulfill(!err));+ return promise;+}++export class BrowserFetcher {+ private _downloadsFolder: string;+ private _downloadHost: string;+ private _platform: string;++ constructor(projectRoot: string, options: BrowserFetcherOptions = {}) {+ this._downloadsFolder = options.path || path.join(projectRoot, '.local-chromium');+ this._downloadHost = options.host || DEFAULT_DOWNLOAD_HOST;+ this._platform = options.platform || '';+ if (!this._platform) {+ const platform = os.platform();+ if (platform === 'darwin')+ this._platform = 'mac';+ else if (platform === 'linux')+ this._platform = 'linux';+ else if (platform === 'win32')+ this._platform = os.arch() === 'x64' ? 'win64' : 'win32';+ assert(this._platform, 'Unsupported platform: ' + os.platform());+ }+ assert(supportedPlatforms.includes(this._platform), 'Unsupported platform: ' + this._platform);+ }++ platform(): string {+ return this._platform;+ }++ canDownload(revision: string): Promise<boolean> {+ const url = downloadURL(this._platform, this._downloadHost, revision);+ let resolve;+ const promise = new Promise<boolean>(x => resolve = x);+ const request = httpRequest(url, 'HEAD', response => {+ resolve(response.statusCode === 200);+ });+ request.on('error', error => {+ console.error(error);+ resolve(false);+ });+ return promise;+ }+ async download(revision: string, progressCallback: ((arg0: number, arg1: number) => void) | null): Promise<BrowserFetcherRevisionInfo> {+ const url = downloadURL(this._platform, this._downloadHost, revision);+ const zipPath = path.join(this._downloadsFolder, `download-${this._platform}-${revision}.zip`);+ const folderPath = this._getFolderPath(revision);+ if (await existsAsync(folderPath))+ return this.revisionInfo(revision);+ if (!(await existsAsync(this._downloadsFolder)))+ await mkdirAsync(this._downloadsFolder);+ try {+ await downloadFile(url, zipPath, progressCallback);+ await extractZip(zipPath, folderPath);+ } finally {+ if (await existsAsync(zipPath))+ await unlinkAsync(zipPath);+ }+ const revisionInfo = this.revisionInfo(revision);+ if (revisionInfo)+ await chmodAsync(revisionInfo.executablePath, 0o755);+ return revisionInfo;+ }++ async localRevisions(): Promise<string[]> {+ if (!await existsAsync(this._downloadsFolder))+ return [];+ const fileNames = await readdirAsync(this._downloadsFolder);+ return fileNames.map(fileName => parseFolderPath(fileName)).filter(entry => entry && entry.platform === this._platform).map(entry => entry.revision);+ }++ async remove(revision: string) {+ const folderPath = this._getFolderPath(revision);+ assert(await existsAsync(folderPath), `Failed to remove: revision ${revision} is not downloaded`);+ await new Promise(fulfill => removeRecursive(folderPath, fulfill));+ }++ revisionInfo(revision: string): BrowserFetcherRevisionInfo {+ const folderPath = this._getFolderPath(revision);+ let executablePath = '';+ if (this._platform === 'mac')+ executablePath = path.join(folderPath, archiveName(this._platform, revision), 'Chromium.app', 'Contents', 'MacOS', 'Chromium');+ else if (this._platform === 'linux')+ executablePath = path.join(folderPath, archiveName(this._platform, revision), 'chrome');+ else if (this._platform === 'win32' || this._platform === 'win64')+ executablePath = path.join(folderPath, archiveName(this._platform, revision), 'chrome.exe');+ else+ throw new Error('Unsupported platform: ' + this._platform);+ const url = downloadURL(this._platform, this._downloadHost, revision);+ const local = fs.existsSync(folderPath);+ return {revision, executablePath, folderPath, local, url};+ }++ _getFolderPath(revision: string): string {+ return path.join(this._downloadsFolder, this._platform + '-' + revision);+ }+}++function parseFolderPath(folderPath: string): { platform: string; revision: string; } | null {+ const name = path.basename(folderPath);+ const splits = name.split('-');+ if (splits.length !== 2)+ return null;+ const [platform, revision] = splits;+ if (!supportedPlatforms.includes(platform))+ return null;+ return {platform, revision};+}++function downloadFile(url: string, destinationPath: string, progressCallback: ((arg0: number, arg1: number) => void) | null): Promise<any> {+ let fulfill, reject;+ let downloadedBytes = 0;+ let totalBytes = 0;++ const promise = new Promise((x, y) => { fulfill = x; reject = y; });++ const request = httpRequest(url, 'GET', response => {+ if (response.statusCode !== 200) {+ const error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`);+ // consume response data to free up memory+ response.resume();+ reject(error);+ return;+ }+ const file = fs.createWriteStream(destinationPath);+ file.on('finish', () => fulfill());+ file.on('error', error => reject(error));+ response.pipe(file);+ totalBytes = parseInt(response.headers['content-length'], 10);+ if (progressCallback)+ response.on('data', onData);+ });+ request.on('error', error => reject(error));+ return promise;++ function onData(chunk) {+ downloadedBytes += chunk.length;+ progressCallback(downloadedBytes, totalBytes);+ }+}++function extractZip(zipPath: string, folderPath: string): Promise<Error | null> {+ return new Promise((fulfill, reject) => extract(zipPath, {dir: folderPath}, err => {+ if (err)+ reject(err);+ else+ fulfill();+ }));+}++function httpRequest(url: string, method: string, response: (r: any) => void) {+ let options: any = URL.parse(url);+ options.method = method;++ const proxyURL = getProxyForUrl(url);+ if (proxyURL) {+ if (url.startsWith('http:')) {+ const proxy = URL.parse(proxyURL);+ options = {+ path: options.href,+ host: proxy.hostname,+ port: proxy.port,+ };+ } else {+ const parsedProxyURL: any = URL.parse(proxyURL);+ parsedProxyURL.secureProxy = parsedProxyURL.protocol === 'https:';++ options.agent = new ProxyAgent(parsedProxyURL);+ options.rejectUnauthorized = false;+ }+ }++ const requestCallback = res => {+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location)+ httpRequest(res.headers.location, method, response);+ else+ response(res);+ };+ const request = options.protocol === 'https:' ?+ require('https').request(options, requestCallback) :+ require('http').request(options, requestCallback);+ request.end();+ return request;+}++export type BrowserFetcherOptions = {+ platform?: string,+ path?: string,+ host ?: string,+};++type BrowserFetcherRevisionInfo = {+ folderPath: string,+ executablePath: string,+ url: string,+ local: boolean,+ revision: string,+};diff --git a/src/chromium/Connection.ts b/src/chromium/Connection.tsnew file mode 100644index 0000000000..212ff016eb--- /dev/null+++ b/src/chromium/Connection.ts@@ -0,0 +1,219 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {assert} from '../helper';+import {Events} from '../Events';+import * as debug from 'debug';+import {EventEmitter} from 'events';+import { ConnectionTransport } from '../ConnectionTransport';+import { Protocol } from './protocol';++const debugProtocol = debug('playwright:protocol');++export const ConnectionEvents = {+ Disconnected: Symbol('ConnectionEvents.Disconnected')+};++export class Connection extends EventEmitter {+ private _url: string;+ private _lastId = 0;+ private _callbacks = new Map<number, {resolve:(o: any) => void, reject: (e: Error) => void, error: Error, method: string}>();+ private _delay: number;+ private _transport: ConnectionTransport;+ private _sessions = new Map<string, CDPSession>();+ _closed = false;+ on: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ addListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ off: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ removeListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ once: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;++ constructor(url: string, transport: ConnectionTransport, delay: number | undefined = 0) {+ super();+ this._url = url;+ this._delay = delay;++ this._transport = transport;+ this._transport.onmessage = this._onMessage.bind(this);+ this._transport.onclose = this._onClose.bind(this);+ }++ static fromSession(session: CDPSession): Connection {+ return session._connection;+ }++ session(sessionId: string): CDPSession | null {+ return this._sessions.get(sessionId) || null;+ }++ url(): string {+ return this._url;+ }++ send<T extends keyof Protocol.CommandParameters>(+ method: T,+ params?: Protocol.CommandParameters[T]+ ): Promise<Protocol.CommandReturnValues[T]> {+ const id = this._rawSend({method, params});+ return new Promise((resolve, reject) => {+ this._callbacks.set(id, {resolve, reject, error: new Error(), method});+ });+ }++ _rawSend(message: any): number {+ const id = ++this._lastId;+ message = JSON.stringify(Object.assign({}, message, {id}));+ debugProtocol('SEND ► ' + message);+ this._transport.send(message);+ return id;+ }++ async _onMessage(message: string) {+ if (this._delay)+ await new Promise(f => setTimeout(f, this._delay));+ debugProtocol('◀ RECV ' + message);+ const object = JSON.parse(message);+ if (object.method === 'Target.attachedToTarget') {+ const sessionId = object.params.sessionId;+ const session = new CDPSession(this, object.params.targetInfo.type, sessionId);+ this._sessions.set(sessionId, session);+ } else if (object.method === 'Target.detachedFromTarget') {+ const session = this._sessions.get(object.params.sessionId);+ if (session) {+ session._onClosed();+ this._sessions.delete(object.params.sessionId);+ }+ }+ if (object.sessionId) {+ const session = this._sessions.get(object.sessionId);+ if (session)+ session._onMessage(object);+ } else if (object.id) {+ const callback = this._callbacks.get(object.id);+ // Callbacks could be all rejected if someone has called `.dispose()`.+ if (callback) {+ this._callbacks.delete(object.id);+ if (object.error)+ callback.reject(createProtocolError(callback.error, callback.method, object));+ else+ callback.resolve(object.result);+ }+ } else {+ this.emit(object.method, object.params);+ }+ }++ _onClose() {+ if (this._closed)+ return;+ this._closed = true;+ this._transport.onmessage = null;+ this._transport.onclose = null;+ for (const callback of this._callbacks.values())+ callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));+ this._callbacks.clear();+ for (const session of this._sessions.values())+ session._onClosed();+ this._sessions.clear();+ this.emit(ConnectionEvents.Disconnected);+ }++ dispose() {+ this._onClose();+ this._transport.close();+ }++ async createSession(targetInfo: Protocol.Target.TargetInfo): Promise<CDPSession> {+ const {sessionId} = await this.send('Target.attachToTarget', {targetId: targetInfo.targetId, flatten: true});+ return this._sessions.get(sessionId);+ }+}++export const CDPSessionEvents = {+ Disconnected: Symbol('Events.CDPSession.Disconnected')+};++export class CDPSession extends EventEmitter {+ _connection: Connection;+ private _callbacks = new Map<number, {resolve:(o: any) => void, reject: (e: Error) => void, error: Error, method: string}>();+ private _targetType: string;+ private _sessionId: string;+ on: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ addListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ off: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ removeListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ once: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;++ constructor(connection: Connection, targetType: string, sessionId: string) {+ super();+ this._connection = connection;+ this._targetType = targetType;+ this._sessionId = sessionId;+ }++ send<T extends keyof Protocol.CommandParameters>(+ method: T,+ params?: Protocol.CommandParameters[T]+ ): Promise<Protocol.CommandReturnValues[T]> {+ if (!this._connection)+ return Promise.reject(new Error(`Protocol error (${method}): Session closed. Most likely the ${this._targetType} has been closed.`));+ const id = this._connection._rawSend({sessionId: this._sessionId, method, params});+ return new Promise((resolve, reject) => {+ this._callbacks.set(id, {resolve, reject, error: new Error(), method});+ });+ }++ _onMessage(object: { id?: number; method: string; params: any; error: { message: string; data: any; }; result?: any; }) {+ if (object.id && this._callbacks.has(object.id)) {+ const callback = this._callbacks.get(object.id);+ this._callbacks.delete(object.id);+ if (object.error)+ callback.reject(createProtocolError(callback.error, callback.method, object));+ else+ callback.resolve(object.result);+ } else {+ assert(!object.id);+ this.emit(object.method, object.params);+ }+ }++ async detach() {+ if (!this._connection)+ throw new Error(`Session already detached. Most likely the ${this._targetType} has been closed.`);+ await this._connection.send('Target.detachFromTarget', {sessionId: this._sessionId});+ }++ _onClosed() {+ for (const callback of this._callbacks.values())+ callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));+ this._callbacks.clear();+ this._connection = null;+ this.emit(CDPSessionEvents.Disconnected);+ }+}++function createProtocolError(error: Error, method: string, object: { error: { message: string; data: any; }; }): Error {+ let message = `Protocol error (${method}): ${object.error.message}`;+ if ('data' in object.error)+ message += ` ${object.error.data}`;+ return rewriteError(error, message);+}++function rewriteError(error: Error, message: string): Error {+ error.message = message;+ return error;+}diff --git a/src/chromium/Coverage.ts b/src/chromium/Coverage.tsnew file mode 100644index 0000000000..8e705ccb1e--- /dev/null+++ b/src/chromium/Coverage.ts@@ -0,0 +1,298 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { CDPSession } from './Connection';+import { assert, debugError, helper, RegisteredListener } from '../helper';+import { Protocol } from './protocol';++const {EVALUATION_SCRIPT_URL} = require('./ExecutionContext');++type CoverageEntry = {+ url: string,+ text: string,+ ranges : {start: number, end: number}[]+};++export class Coverage {+ private _jsCoverage: JSCoverage;+ private _cssCoverage: CSSCoverage;++ constructor(client: CDPSession) {+ this._jsCoverage = new JSCoverage(client);+ this._cssCoverage = new CSSCoverage(client);+ }++ async startJSCoverage(options: {+ resetOnNavigation?: boolean;+ reportAnonymousScripts?: boolean;+ }) {+ return await this._jsCoverage.start(options);+ }++ async stopJSCoverage(): Promise<CoverageEntry[]> {+ return await this._jsCoverage.stop();+ }++ async startCSSCoverage(options: { resetOnNavigation?: boolean; } = {}) {+ return await this._cssCoverage.start(options);+ }++ async stopCSSCoverage(): Promise<CoverageEntry[]> {+ return await this._cssCoverage.stop();+ }+}++module.exports = {Coverage};++class JSCoverage {+ _client: CDPSession;+ _enabled: boolean;+ _scriptURLs: Map<string, string>;+ _scriptSources: Map<string, string>;+ _eventListeners: RegisteredListener[];+ _resetOnNavigation: boolean;+ _reportAnonymousScripts: boolean;++ constructor(client: CDPSession) {+ this._client = client;+ this._enabled = false;+ this._scriptURLs = new Map();+ this._scriptSources = new Map();+ this._eventListeners = [];+ this._resetOnNavigation = false;+ }++ async start(options: {+ resetOnNavigation?: boolean;+ reportAnonymousScripts?: boolean;+ } = {}) {+ assert(!this._enabled, 'JSCoverage is already enabled');+ const {+ resetOnNavigation = true,+ reportAnonymousScripts = false+ } = options;+ this._resetOnNavigation = resetOnNavigation;+ this._reportAnonymousScripts = reportAnonymousScripts;+ this._enabled = true;+ this._scriptURLs.clear();+ this._scriptSources.clear();+ this._eventListeners = [+ helper.addEventListener(this._client, 'Debugger.scriptParsed', this._onScriptParsed.bind(this)),+ helper.addEventListener(this._client, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),+ ];+ await Promise.all([+ this._client.send('Profiler.enable'),+ this._client.send('Profiler.startPreciseCoverage', {callCount: false, detailed: true}),+ this._client.send('Debugger.enable'),+ this._client.send('Debugger.setSkipAllPauses', {skip: true})+ ]);+ }++ _onExecutionContextsCleared() {+ if (!this._resetOnNavigation)+ return;+ this._scriptURLs.clear();+ this._scriptSources.clear();+ }++ async _onScriptParsed(event: Protocol.Debugger.scriptParsedPayload) {+ // Ignore playwright-injected scripts+ if (event.url === EVALUATION_SCRIPT_URL)+ return;+ // Ignore other anonymous scripts unless the reportAnonymousScripts option is true.+ if (!event.url && !this._reportAnonymousScripts)+ return;+ try {+ const response = await this._client.send('Debugger.getScriptSource', {scriptId: event.scriptId});+ this._scriptURLs.set(event.scriptId, event.url);+ this._scriptSources.set(event.scriptId, response.scriptSource);+ } catch (e) {+ // This might happen if the page has already navigated away.+ debugError(e);+ }+ }++ async stop(): Promise<CoverageEntry[]> {+ assert(this._enabled, 'JSCoverage is not enabled');+ this._enabled = false;+ const [profileResponse] = await Promise.all([+ this._client.send('Profiler.takePreciseCoverage'),+ this._client.send('Profiler.stopPreciseCoverage'),+ this._client.send('Profiler.disable'),+ this._client.send('Debugger.disable'),+ ]);+ helper.removeEventListeners(this._eventListeners);++ const coverage = [];+ for (const entry of profileResponse.result) {+ let url = this._scriptURLs.get(entry.scriptId);+ if (!url && this._reportAnonymousScripts)+ url = 'debugger://VM' + entry.scriptId;+ const text = this._scriptSources.get(entry.scriptId);+ if (text === undefined || url === undefined)+ continue;+ const flattenRanges = [];+ for (const func of entry.functions)+ flattenRanges.push(...func.ranges);+ const ranges = convertToDisjointRanges(flattenRanges);+ coverage.push({url, ranges, text});+ }+ return coverage;+ }+}++class CSSCoverage {+ _client: CDPSession;+ _enabled: boolean;+ _stylesheetURLs: Map<string, string>;+ _stylesheetSources: Map<string, string>;+ _eventListeners: RegisteredListener[];+ _resetOnNavigation: boolean;++ constructor(client: CDPSession) {+ this._client = client;+ this._enabled = false;+ this._stylesheetURLs = new Map();+ this._stylesheetSources = new Map();+ this._eventListeners = [];+ this._resetOnNavigation = false;+ }++ async start(options: { resetOnNavigation?: boolean; } = {}) {+ assert(!this._enabled, 'CSSCoverage is already enabled');+ const {resetOnNavigation = true} = options;+ this._resetOnNavigation = resetOnNavigation;+ this._enabled = true;+ this._stylesheetURLs.clear();+ this._stylesheetSources.clear();+ this._eventListeners = [+ helper.addEventListener(this._client, 'CSS.styleSheetAdded', this._onStyleSheet.bind(this)),+ helper.addEventListener(this._client, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),+ ];+ await Promise.all([+ this._client.send('DOM.enable'),+ this._client.send('CSS.enable'),+ this._client.send('CSS.startRuleUsageTracking'),+ ]);+ }++ _onExecutionContextsCleared() {+ if (!this._resetOnNavigation)+ return;+ this._stylesheetURLs.clear();+ this._stylesheetSources.clear();+ }++ async _onStyleSheet(event: Protocol.CSS.styleSheetAddedPayload) {+ const header = event.header;+ // Ignore anonymous scripts+ if (!header.sourceURL)+ return;+ try {+ const response = await this._client.send('CSS.getStyleSheetText', {styleSheetId: header.styleSheetId});+ this._stylesheetURLs.set(header.styleSheetId, header.sourceURL);+ this._stylesheetSources.set(header.styleSheetId, response.text);+ } catch (e) {+ // This might happen if the page has already navigated away.+ debugError(e);+ }+ }++ async stop(): Promise<CoverageEntry[]> {+ assert(this._enabled, 'CSSCoverage is not enabled');+ this._enabled = false;+ const ruleTrackingResponse = await this._client.send('CSS.stopRuleUsageTracking');+ await Promise.all([+ this._client.send('CSS.disable'),+ this._client.send('DOM.disable'),+ ]);+ helper.removeEventListeners(this._eventListeners);++ // aggregate by styleSheetId+ const styleSheetIdToCoverage = new Map();+ for (const entry of ruleTrackingResponse.ruleUsage) {+ let ranges = styleSheetIdToCoverage.get(entry.styleSheetId);+ if (!ranges) {+ ranges = [];+ styleSheetIdToCoverage.set(entry.styleSheetId, ranges);+ }+ ranges.push({+ startOffset: entry.startOffset,+ endOffset: entry.endOffset,+ count: entry.used ? 1 : 0,+ });+ }++ const coverage = [];+ for (const styleSheetId of this._stylesheetURLs.keys()) {+ const url = this._stylesheetURLs.get(styleSheetId);+ const text = this._stylesheetSources.get(styleSheetId);+ const ranges = convertToDisjointRanges(styleSheetIdToCoverage.get(styleSheetId) || []);+ coverage.push({url, ranges, text});+ }++ return coverage;+ }+}++function convertToDisjointRanges(nestedRanges: {+ startOffset: number;+ endOffset: number;+ count: number; }[]): { start: number; end: number; }[] {+ const points = [];+ for (const range of nestedRanges) {+ points.push({ offset: range.startOffset, type: 0, range });+ points.push({ offset: range.endOffset, type: 1, range });+ }+ // Sort points to form a valid parenthesis sequence.+ points.sort((a, b) => {+ // Sort with increasing offsets.+ if (a.offset !== b.offset)+ return a.offset - b.offset;+ // All "end" points should go before "start" points.+ if (a.type !== b.type)+ return b.type - a.type;+ const aLength = a.range.endOffset - a.range.startOffset;+ const bLength = b.range.endOffset - b.range.startOffset;+ // For two "start" points, the one with longer range goes first.+ if (a.type === 0)+ return bLength - aLength;+ // For two "end" points, the one with shorter range goes first.+ return aLength - bLength;+ });++ const hitCountStack = [];+ const results = [];+ let lastOffset = 0;+ // Run scanning line to intersect all ranges.+ for (const point of points) {+ if (hitCountStack.length && lastOffset < point.offset && hitCountStack[hitCountStack.length - 1] > 0) {+ const lastResult = results.length ? results[results.length - 1] : null;+ if (lastResult && lastResult.end === lastOffset)+ lastResult.end = point.offset;+ else+ results.push({start: lastOffset, end: point.offset});+ }+ lastOffset = point.offset;+ if (point.type === 0)+ hitCountStack.push(point.range.count);+ else+ hitCountStack.pop();+ }+ // Filter out empty ranges.+ return results.filter(range => range.end - range.start > 1);+}diff --git a/src/chromium/DOMWorld.ts b/src/chromium/DOMWorld.tsnew file mode 100644index 0000000000..27fd86f403--- /dev/null+++ b/src/chromium/DOMWorld.ts@@ -0,0 +1,580 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import * as fs from 'fs';+import { TimeoutError } from '../Errors';+import { ExecutionContext } from './ExecutionContext';+import { Frame } from './Frame';+import { FrameManager } from './FrameManager';+import { assert, helper } from '../helper';+import { ElementHandle, JSHandle, ClickOptions, PointerActionOptions, MultiClickOptions } from './JSHandle';+import { LifecycleWatcher } from './LifecycleWatcher';+import { TimeoutSettings } from '../TimeoutSettings';+const readFileAsync = helper.promisify(fs.readFile);++export class DOMWorld {+ private _frameManager: FrameManager;+ private _frame: Frame;+ private _timeoutSettings: TimeoutSettings;+ private _documentPromise: Promise<ElementHandle> | null = null;+ private _contextPromise: Promise<ExecutionContext>;+ private _contextResolveCallback: ((c: ExecutionContext) => void) | null;+ _waitTasks = new Set<WaitTask>();+ private _detached = false;++ constructor(frameManager: FrameManager, frame: Frame, timeoutSettings: TimeoutSettings) {+ this._frameManager = frameManager;+ this._frame = frame;+ this._timeoutSettings = timeoutSettings;+ this._contextPromise;+ this._setContext(null);+ }++ frame(): Frame {+ return this._frame;+ }++ _setContext(context: ExecutionContext | null) {+ if (context) {+ this._contextResolveCallback.call(null, context);+ this._contextResolveCallback = null;+ for (const waitTask of this._waitTasks)+ waitTask.rerun();+ } else {+ this._documentPromise = null;+ this._contextPromise = new Promise(fulfill => {+ this._contextResolveCallback = fulfill;+ });+ }+ }++ _hasContext(): boolean {+ return !this._contextResolveCallback;+ }++ _detach() {+ this._detached = true;+ for (const waitTask of this._waitTasks)+ waitTask.terminate(new Error('waitForFunction failed: frame got detached.'));+ }++ executionContext(): Promise<ExecutionContext> {+ if (this._detached)+ throw new Error(`Execution Context is not available in detached frame "${this._frame.url()}" (are you trying to evaluate?)`);+ return this._contextPromise;+ }++ async evaluateHandle(pageFunction: Function | string, ...args: any[]): Promise<JSHandle> {+ const context = await this.executionContext();+ return context.evaluateHandle(pageFunction, ...args);+ }++ async evaluate(pageFunction: Function | string, ...args: any[]): Promise<any> {+ const context = await this.executionContext();+ return context.evaluate(pageFunction, ...args);+ }++ async $(selector: string): Promise<ElementHandle | null> {+ const document = await this._document();+ const value = await document.$(selector);+ return value;+ }++ async _document(): Promise<ElementHandle> {+ if (this._documentPromise)+ return this._documentPromise;+ this._documentPromise = this.executionContext().then(async context => {+ const document = await context.evaluateHandle('document');+ return document.asElement();+ });+ return this._documentPromise;+ }++ async $x(expression: string): Promise<ElementHandle[]> {+ const document = await this._document();+ const value = await document.$x(expression);+ return value;+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<any> {+ const document = await this._document();+ return document.$eval(selector, pageFunction, ...args);+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<any> {+ const document = await this._document();+ const value = await document.$$eval(selector, pageFunction, ...args);+ return value;+ }++ async $$(selector: string): Promise<ElementHandle[]> {+ const document = await this._document();+ const value = await document.$$(selector);+ return value;+ }++ async content(): Promise<string> {+ return await this.evaluate(() => {+ let retVal = '';+ if (document.doctype)+ retVal = new XMLSerializer().serializeToString(document.doctype);+ if (document.documentElement)+ retVal += document.documentElement.outerHTML;+ return retVal;+ });+ }++ async setContent(html: string, options: {+ timeout?: number;+ waitUntil?: string | string[];+ } = {}) {+ const {+ waitUntil = ['load'],+ timeout = this._timeoutSettings.navigationTimeout(),+ } = options;+ // We rely upon the fact that document.open() will reset frame lifecycle with "init"+ // lifecycle event. @see https://crrev.com/608658+ await this.evaluate(html => {+ document.open();+ document.write(html);+ document.close();+ }, html);+ const watcher = new LifecycleWatcher(this._frameManager, this._frame, waitUntil, timeout);+ const error = await Promise.race([+ watcher.timeoutOrTerminationPromise(),+ watcher.lifecyclePromise(),+ ]);+ watcher.dispose();+ if (error)+ throw error;+ }++ async addScriptTag(options: {+ url?: string; path?: string;+ content?: string;+ type?: string;+ }): Promise<ElementHandle> {+ const {+ url = null,+ path = null,+ content = null,+ type = ''+ } = options;+ if (url !== null) {+ try {+ const context = await this.executionContext();+ return (await context.evaluateHandle(addScriptUrl, url, type)).asElement();+ } catch (error) {+ throw new Error(`Loading script from ${url} failed`);+ }+ }++ if (path !== null) {+ let contents = await readFileAsync(path, 'utf8');+ contents += '//# sourceURL=' + path.replace(/\n/g, '');+ const context = await this.executionContext();+ return (await context.evaluateHandle(addScriptContent, contents, type)).asElement();+ }++ if (content !== null) {+ const context = await this.executionContext();+ return (await context.evaluateHandle(addScriptContent, content, type)).asElement();+ }++ throw new Error('Provide an object with a `url`, `path` or `content` property');++ async function addScriptUrl(url: string, type: string): Promise<HTMLElement> {+ const script = document.createElement('script');+ script.src = url;+ if (type)+ script.type = type;+ const promise = new Promise((res, rej) => {+ script.onload = res;+ script.onerror = rej;+ });+ document.head.appendChild(script);+ await promise;+ return script;+ }++ function addScriptContent(content: string, type: string = 'text/javascript'): HTMLElement {+ const script = document.createElement('script');+ script.type = type;+ script.text = content;+ let error = null;+ script.onerror = e => error = e;+ document.head.appendChild(script);+ if (error)+ throw error;+ return script;+ }+ }++ async addStyleTag(options: { url?: string; path?: string; content?: string; }): Promise<ElementHandle> {+ const {+ url = null,+ path = null,+ content = null+ } = options;+ if (url !== null) {+ try {+ const context = await this.executionContext();+ return (await context.evaluateHandle(addStyleUrl, url)).asElement();+ } catch (error) {+ throw new Error(`Loading style from ${url} failed`);+ }+ }++ if (path !== null) {+ let contents = await readFileAsync(path, 'utf8');+ contents += '/*# sourceURL=' + path.replace(/\n/g, '') + '*/';+ const context = await this.executionContext();+ return (await context.evaluateHandle(addStyleContent, contents)).asElement();+ }++ if (content !== null) {+ const context = await this.executionContext();+ return (await context.evaluateHandle(addStyleContent, content)).asElement();+ }++ throw new Error('Provide an object with a `url`, `path` or `content` property');++ async function addStyleUrl(url: string): Promise<HTMLElement> {+ const link = document.createElement('link');+ link.rel = 'stylesheet';+ link.href = url;+ const promise = new Promise((res, rej) => {+ link.onload = res;+ link.onerror = rej;+ });+ document.head.appendChild(link);+ await promise;+ return link;+ }++ async function addStyleContent(content: string): Promise<HTMLElement> {+ const style = document.createElement('style');+ style.type = 'text/css';+ style.appendChild(document.createTextNode(content));+ const promise = new Promise((res, rej) => {+ style.onload = res;+ style.onerror = rej;+ });+ document.head.appendChild(style);+ await promise;+ return style;+ }+ }++ async click(selector: string, options?: ClickOptions) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.click(options);+ await handle.dispose();+ }++ async dblclick(selector: string, options?: MultiClickOptions) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.dblclick(options);+ await handle.dispose();+ }++ async tripleclick(selector: string, options?: MultiClickOptions) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.tripleclick(options);+ await handle.dispose();+ }++ async fill(selector: string, value: string) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.fill(value);+ await handle.dispose();+ }++ async focus(selector: string) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.focus();+ await handle.dispose();+ }++ async hover(selector: string, options?: PointerActionOptions) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.hover(options);+ await handle.dispose();+ }++ async select(selector: string, ...values: string[]): Promise<string[]> {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ const result = await handle.select(...values);+ await handle.dispose();+ return result;+ }++ async tap(selector: string, options?: PointerActionOptions) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.tap(options);+ await handle.dispose();+ }++ async type(selector: string, text: string, options: { delay: (number | undefined); } | undefined) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.type(text, options);+ await handle.dispose();+ }++ waitForSelector(selector: string, options: { visible?: boolean; hidden?: boolean; timeout?: number; } | undefined): Promise<ElementHandle | null> {+ return this._waitForSelectorOrXPath(selector, false, options);+ }++ waitForXPath(xpath: string, options: { visible?: boolean; hidden?: boolean; timeout?: number; } | undefined): Promise<ElementHandle | null> {+ return this._waitForSelectorOrXPath(xpath, true, options);+ }++ waitForFunction(pageFunction: Function | string, options: { polling?: string | number; timeout?: number; } = {}, ...args): Promise<JSHandle> {+ const {+ polling = 'raf',+ timeout = this._timeoutSettings.timeout(),+ } = options;+ return new WaitTask(this, pageFunction, 'function', polling, timeout, ...args).promise;+ }++ async title(): Promise<string> {+ return this.evaluate(() => document.title);+ }++ async _waitForSelectorOrXPath(+ selectorOrXPath: string,+ isXPath: boolean,+ options: { visible?: boolean; hidden?: boolean; timeout?: number; } = {}): Promise<ElementHandle | null> {+ const {+ visible: waitForVisible = false,+ hidden: waitForHidden = false,+ timeout = this._timeoutSettings.timeout(),+ } = options;+ const polling = waitForVisible || waitForHidden ? 'raf' : 'mutation';+ const title = `${isXPath ? 'XPath' : 'selector'} "${selectorOrXPath}"${waitForHidden ? ' to be hidden' : ''}`;+ const waitTask = new WaitTask(this, predicate, title, polling, timeout, selectorOrXPath, isXPath, waitForVisible, waitForHidden);+ const handle = await waitTask.promise;+ if (!handle.asElement()) {+ await handle.dispose();+ return null;+ }+ return handle.asElement();++ function predicate(selectorOrXPath: string, isXPath: boolean, waitForVisible: boolean, waitForHidden: boolean): (Node | boolean) | null {+ const node = isXPath+ ? document.evaluate(selectorOrXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue+ : document.querySelector(selectorOrXPath);+ if (!node)+ return waitForHidden;+ if (!waitForVisible && !waitForHidden)+ return node;+ const element = (node.nodeType === Node.TEXT_NODE ? node.parentElement : node) as Element;+ const style = window.getComputedStyle(element);+ const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox();+ const success = (waitForVisible === isVisible || waitForHidden === !isVisible);+ return success ? node : null;++ function hasVisibleBoundingBox(): boolean {+ const rect = element.getBoundingClientRect();+ return !!(rect.top || rect.bottom || rect.width || rect.height);+ }+ }+ }+}++class WaitTask {+ promise: Promise<JSHandle>;+ _domWorld: DOMWorld;+ _polling: string | number;+ _timeout: number;+ _predicateBody: string;+ _args: any[];+ _runCount: number;+ _resolve: (result: JSHandle) => void;+ _reject: (reason: Error) => void;+ _timeoutTimer: NodeJS.Timer;+ _terminated: boolean;+ _runningTask: any;++ constructor(domWorld: DOMWorld, predicateBody: Function | string, title, polling: string | number, timeout: number, ...args: any[]) {+ if (helper.isString(polling))+ assert(polling === 'raf' || polling === 'mutation', 'Unknown polling option: ' + polling);+ else if (helper.isNumber(polling))+ assert(polling > 0, 'Cannot poll with non-positive interval: ' + polling);+ else+ throw new Error('Unknown polling options: ' + polling);++ this._domWorld = domWorld;+ this._polling = polling;+ this._timeout = timeout;+ this._predicateBody = helper.isString(predicateBody) ? 'return (' + predicateBody + ')' : 'return (' + predicateBody + ')(...args)';+ this._args = args;+ this._runCount = 0;+ domWorld._waitTasks.add(this);+ this.promise = new Promise<JSHandle>((resolve, reject) => {+ this._resolve = resolve;+ this._reject = reject;+ });+ // Since page navigation requires us to re-install the pageScript, we should track+ // timeout on our end.+ if (timeout) {+ const timeoutError = new TimeoutError(`waiting for ${title} failed: timeout ${timeout}ms exceeded`);+ this._timeoutTimer = setTimeout(() => this.terminate(timeoutError), timeout);+ }+ this.rerun();+ }++ terminate(error: Error) {+ this._terminated = true;+ this._reject(error);+ this._cleanup();+ }++ async rerun() {+ const runCount = ++this._runCount;+ let success: JSHandle | null = null;+ let error = null;+ try {+ success = await (await this._domWorld.executionContext()).evaluateHandle(waitForPredicatePageFunction, this._predicateBody, this._polling, this._timeout, ...this._args);+ } catch (e) {+ error = e;+ }++ if (this._terminated || runCount !== this._runCount) {+ if (success)+ await success.dispose();+ return;+ }++ // Ignore timeouts in pageScript - we track timeouts ourselves.+ // If the frame's execution context has already changed, `frame.evaluate` will+ // throw an error - ignore this predicate run altogether.+ if (!error && await this._domWorld.evaluate(s => !s, success).catch(e => true)) {+ await success.dispose();+ return;+ }++ // When the page is navigated, the promise is rejected.+ // We will try again in the new execution context.+ if (error && error.message.includes('Execution context was destroyed'))+ return;++ // We could have tried to evaluate in a context which was already+ // destroyed.+ if (error && error.message.includes('Cannot find context with specified id'))+ return;++ if (error)+ this._reject(error);+ else+ this._resolve(success);++ this._cleanup();+ }++ _cleanup() {+ clearTimeout(this._timeoutTimer);+ this._domWorld._waitTasks.delete(this);+ this._runningTask = null;+ }+}++async function waitForPredicatePageFunction(predicateBody: string, polling: string, timeout: number, ...args): Promise<any> {+ const predicate = new Function('...args', predicateBody);+ let timedOut = false;+ if (timeout)+ setTimeout(() => timedOut = true, timeout);+ if (polling === 'raf')+ return await pollRaf();+ if (polling === 'mutation')+ return await pollMutation();+ if (typeof polling === 'number')+ return await pollInterval(polling);++ function pollMutation(): Promise<any> {+ const success = predicate.apply(null, args);+ if (success)+ return Promise.resolve(success);++ let fulfill;+ const result = new Promise(x => fulfill = x);+ const observer = new MutationObserver(mutations => {+ if (timedOut) {+ observer.disconnect();+ fulfill();+ }+ const success = predicate.apply(null, args);+ if (success) {+ observer.disconnect();+ fulfill(success);+ }+ });+ observer.observe(document, {+ childList: true,+ subtree: true,+ attributes: true+ });+ return result;+ }++ function pollRaf(): Promise<any> {+ let fulfill;+ const result = new Promise(x => fulfill = x);+ onRaf();+ return result;++ function onRaf() {+ if (timedOut) {+ fulfill();+ return;+ }+ const success = predicate.apply(null, args);+ if (success)+ fulfill(success);+ else+ requestAnimationFrame(onRaf);+ }+ }++ function pollInterval(pollInterval: number): Promise<any> {+ let fulfill;+ const result = new Promise(x => fulfill = x);+ onTimeout();+ return result;++ function onTimeout() {+ if (timedOut) {+ fulfill();+ return;+ }+ const success = predicate.apply(null, args);+ if (success)+ fulfill(success);+ else+ setTimeout(onTimeout, pollInterval);+ }+ }+}diff --git a/src/chromium/Dialog.ts b/src/chromium/Dialog.tsnew file mode 100644index 0000000000..722385a506--- /dev/null+++ b/src/chromium/Dialog.ts@@ -0,0 +1,70 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { CDPSession } from './Connection';+import { assert } from '../helper';++export class Dialog {+ private _client: CDPSession;+ private _type: string;+ private _message: string;+ private _handled = false;+ private _defaultValue: string;++ constructor(client: CDPSession, type: string, message: string, defaultValue: (string | undefined) = '') {+ this._client = client;+ this._type = type;+ this._message = message;+ this._defaultValue = defaultValue;+ }++ type(): string {+ return this._type;+ }++ message(): string {+ return this._message;+ }++ defaultValue(): string {+ return this._defaultValue;+ }++ async accept(promptText: string | undefined) {+ assert(!this._handled, 'Cannot accept dialog which is already handled!');+ this._handled = true;+ await this._client.send('Page.handleJavaScriptDialog', {+ accept: true,+ promptText: promptText+ });+ }++ async dismiss() {+ assert(!this._handled, 'Cannot dismiss dialog which is already handled!');+ this._handled = true;+ await this._client.send('Page.handleJavaScriptDialog', {+ accept: false+ });+ }+}++export const DialogType = {+ Alert: 'alert',+ BeforeUnload: 'beforeunload',+ Confirm: 'confirm',+ Prompt: 'prompt'+};diff --git a/src/chromium/EmulationManager.ts b/src/chromium/EmulationManager.tsnew file mode 100644index 0000000000..c6eeab9875--- /dev/null+++ b/src/chromium/EmulationManager.ts@@ -0,0 +1,51 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { CDPSession } from './Connection';+import { Viewport } from './Page';+import { Protocol } from './protocol';++export class EmulationManager {+ private _client: CDPSession;+ private _emulatingMobile = false;+ private _hasTouch = false;++ constructor(client: CDPSession) {+ this._client = client;+ }++ async emulateViewport(viewport: Viewport): Promise<boolean> {+ const mobile = viewport.isMobile || false;+ const width = viewport.width;+ const height = viewport.height;+ const deviceScaleFactor = viewport.deviceScaleFactor || 1;+ const screenOrientation: Protocol.Emulation.ScreenOrientation = viewport.isLandscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };+ const hasTouch = viewport.hasTouch || false;++ await Promise.all([+ this._client.send('Emulation.setDeviceMetricsOverride', { mobile, width, height, deviceScaleFactor, screenOrientation }),+ this._client.send('Emulation.setTouchEmulationEnabled', {+ enabled: hasTouch+ })+ ]);++ const reloadNeeded = this._emulatingMobile !== mobile || this._hasTouch !== hasTouch;+ this._emulatingMobile = mobile;+ this._hasTouch = hasTouch;+ return reloadNeeded;+ }+}diff --git a/src/chromium/ExecutionContext.ts b/src/chromium/ExecutionContext.tsnew file mode 100644index 0000000000..be711fb164--- /dev/null+++ b/src/chromium/ExecutionContext.ts@@ -0,0 +1,171 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { CDPSession } from './Connection';+import { DOMWorld } from './DOMWorld';+import { Frame } from './Frame';+import { assert, helper } from '../helper';+import { valueFromRemoteObject, getExceptionMessage } from './protocolHelper';+import { createJSHandle, ElementHandle, JSHandle } from './JSHandle';+import { Protocol } from './protocol';+++export const EVALUATION_SCRIPT_URL = '__playwright_evaluation_script__';+const SOURCE_URL_REGEX = /^[\040\t]*\/\/[@#] sourceURL=\s*(\S*?)\s*$/m;++export class ExecutionContext {+ _client: CDPSession;+ _world: DOMWorld;+ private _contextId: number;++ constructor(client: CDPSession, contextPayload: Protocol.Runtime.ExecutionContextDescription, world: DOMWorld | null) {+ this._client = client;+ this._world = world;+ this._contextId = contextPayload.id;+ }++ frame(): Frame | null {+ return this._world ? this._world.frame() : null;+ }++ async evaluate(pageFunction: Function | string, ...args: any[]): Promise<any> {+ return await this._evaluateInternal(true /* returnByValue */, pageFunction, ...args);+ }++ async evaluateHandle(pageFunction: Function | string, ...args: any[]): Promise<JSHandle> {+ return this._evaluateInternal(false /* returnByValue */, pageFunction, ...args);+ }++ async _evaluateInternal(returnByValue: boolean, pageFunction: Function | string, ...args: any[]): Promise<any> {+ const suffix = `//# sourceURL=${EVALUATION_SCRIPT_URL}`;++ if (helper.isString(pageFunction)) {+ const contextId = this._contextId;+ const expression: string = pageFunction as string;+ const expressionWithSourceUrl = SOURCE_URL_REGEX.test(expression) ? expression : expression + '\n' + suffix;+ const {exceptionDetails, result: remoteObject} = await this._client.send('Runtime.evaluate', {+ expression: expressionWithSourceUrl,+ contextId,+ returnByValue,+ awaitPromise: true,+ userGesture: true+ }).catch(rewriteError);+ if (exceptionDetails)+ throw new Error('Evaluation failed: ' + getExceptionMessage(exceptionDetails));+ return returnByValue ? valueFromRemoteObject(remoteObject) : createJSHandle(this, remoteObject);+ }++ if (typeof pageFunction !== 'function')+ throw new Error(`Expected to get |string| or |function| as the first argument, but got "${pageFunction}" instead.`);++ let functionText = pageFunction.toString();+ try {+ new Function('(' + functionText + ')');+ } catch (e1) {+ // This means we might have a function shorthand. Try another+ // time prefixing 'function '.+ if (functionText.startsWith('async '))+ functionText = 'async function ' + functionText.substring('async '.length);+ else+ functionText = 'function ' + functionText;+ try {+ new Function('(' + functionText + ')');+ } catch (e2) {+ // We tried hard to serialize, but there's a weird beast here.+ throw new Error('Passed function is not well-serializable!');+ }+ }+ let callFunctionOnPromise;+ try {+ callFunctionOnPromise = this._client.send('Runtime.callFunctionOn', {+ functionDeclaration: functionText + '\n' + suffix + '\n',+ executionContextId: this._contextId,+ arguments: args.map(convertArgument.bind(this)),+ returnByValue,+ awaitPromise: true,+ userGesture: true+ });+ } catch (err) {+ if (err instanceof TypeError && err.message.startsWith('Converting circular structure to JSON'))+ err.message += ' Are you passing a nested JSHandle?';+ throw err;+ }+ const { exceptionDetails, result: remoteObject } = await callFunctionOnPromise.catch(rewriteError);+ if (exceptionDetails)+ throw new Error('Evaluation failed: ' + getExceptionMessage(exceptionDetails));+ return returnByValue ? valueFromRemoteObject(remoteObject) : createJSHandle(this, remoteObject);++ function convertArgument(arg: any): any {+ if (typeof arg === 'bigint') // eslint-disable-line valid-typeof+ return { unserializableValue: `${arg.toString()}n` };+ if (Object.is(arg, -0))+ return { unserializableValue: '-0' };+ if (Object.is(arg, Infinity))+ return { unserializableValue: 'Infinity' };+ if (Object.is(arg, -Infinity))+ return { unserializableValue: '-Infinity' };+ if (Object.is(arg, NaN))+ return { unserializableValue: 'NaN' };+ const objectHandle = arg && (arg instanceof JSHandle) ? arg : null;+ if (objectHandle) {+ if (objectHandle._context !== this)+ throw new Error('JSHandles can be evaluated only in the context they were created!');+ if (objectHandle._disposed)+ throw new Error('JSHandle is disposed!');+ if (objectHandle._remoteObject.unserializableValue)+ return { unserializableValue: objectHandle._remoteObject.unserializableValue };+ if (!objectHandle._remoteObject.objectId)+ return { value: objectHandle._remoteObject.value };+ return { objectId: objectHandle._remoteObject.objectId };+ }+ return { value: arg };+ }++ function rewriteError(error: Error): Protocol.Runtime.evaluateReturnValue {+ if (error.message.includes('Object reference chain is too long'))+ return {result: {type: 'undefined'}};+ if (error.message.includes('Object couldn\'t be returned by value'))+ return {result: {type: 'undefined'}};++ if (error.message.endsWith('Cannot find context with specified id') || error.message.endsWith('Inspected target navigated or closed'))+ throw new Error('Execution context was destroyed, most likely because of a navigation.');+ throw error;+ }+ }++ async queryObjects(prototypeHandle: JSHandle): Promise<JSHandle> {+ assert(!prototypeHandle._disposed, 'Prototype JSHandle is disposed!');+ assert(prototypeHandle._remoteObject.objectId, 'Prototype JSHandle must not be referencing primitive value');+ const response = await this._client.send('Runtime.queryObjects', {+ prototypeObjectId: prototypeHandle._remoteObject.objectId+ });+ return createJSHandle(this, response.objects);+ }++ async _adoptElementHandle(elementHandle: ElementHandle): Promise<ElementHandle> {+ assert(elementHandle.executionContext() !== this, 'Cannot adopt handle that already belongs to this execution context');+ assert(this._world, 'Cannot adopt handle without DOMWorld');+ const nodeInfo = await this._client.send('DOM.describeNode', {+ objectId: elementHandle._remoteObject.objectId,+ });+ const {object} = await this._client.send('DOM.resolveNode', {+ backendNodeId: nodeInfo.node.backendNodeId,+ executionContextId: this._contextId,+ });+ return createJSHandle(this, object) as ElementHandle;+ }+}diff --git a/src/chromium/Frame.ts b/src/chromium/Frame.tsnew file mode 100644index 0000000000..6565324619--- /dev/null+++ b/src/chromium/Frame.ts@@ -0,0 +1,264 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { helper } from '../helper';+import { CDPSession } from './Connection';+import { DOMWorld } from './DOMWorld';+import { ExecutionContext } from './ExecutionContext';+import { FrameManager } from './FrameManager';+import { ClickOptions, ElementHandle, JSHandle, MultiClickOptions, PointerActionOptions } from './JSHandle';+import { Response } from './NetworkManager';+import { Protocol } from './protocol';++export class Frame {+ _id: string;+ _frameManager: FrameManager;+ private _client: CDPSession;+ private _parentFrame: Frame;+ private _url = '';+ private _detached = false;+ _loaderId = '';+ _lifecycleEvents = new Set<string>();+ _mainWorld: DOMWorld;+ _secondaryWorld: DOMWorld;+ private _childFrames = new Set<Frame>();+ private _name: string;+ private _navigationURL: string;++ constructor(frameManager: FrameManager, client: CDPSession, parentFrame: Frame | null, frameId: string) {+ this._frameManager = frameManager;+ this._client = client;+ this._parentFrame = parentFrame;+ this._id = frameId;++ this._mainWorld = new DOMWorld(frameManager, this, frameManager._timeoutSettings);+ this._secondaryWorld = new DOMWorld(frameManager, this, frameManager._timeoutSettings);++ if (this._parentFrame)+ this._parentFrame._childFrames.add(this);+ }++ async goto(+ url: string,+ options: { referer?: string; timeout?: number; waitUntil?: string | string[]; } | undefined+ ): Promise<Response | null> {+ return await this._frameManager.navigateFrame(this, url, options);+ }++ async waitForNavigation(options: { timeout?: number; waitUntil?: string | string[]; } | undefined): Promise<Response | null> {+ return await this._frameManager.waitForFrameNavigation(this, options);+ }++ executionContext(): Promise<ExecutionContext> {+ return this._mainWorld.executionContext();+ }++ async evaluateHandle(pageFunction: Function | string, ...args: any[]): Promise<JSHandle> {+ return this._mainWorld.evaluateHandle(pageFunction, ...args);+ }++ async evaluate(pageFunction: Function | string, ...args: any[]): Promise<any> {+ return this._mainWorld.evaluate(pageFunction, ...args);+ }++ async $(selector: string): Promise<ElementHandle | null> {+ return this._mainWorld.$(selector);+ }++ async $x(expression: string): Promise<ElementHandle[]> {+ return this._mainWorld.$x(expression);+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<(object | undefined)> {+ return this._mainWorld.$eval(selector, pageFunction, ...args);+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<(object | undefined)> {+ return this._mainWorld.$$eval(selector, pageFunction, ...args);+ }++ async $$(selector: string): Promise<ElementHandle[]> {+ return this._mainWorld.$$(selector);+ }++ async content(): Promise<string> {+ return this._secondaryWorld.content();+ }++ async setContent(html: string, options: {+ timeout?: number;+ waitUntil?: string | string[];+ } = {}) {+ return this._secondaryWorld.setContent(html, options);+ }++ name(): string {+ return this._name || '';+ }++ url(): string {+ return this._url;+ }++ parentFrame(): Frame | null {+ return this._parentFrame;+ }++ childFrames(): Frame[] {+ return Array.from(this._childFrames);+ }++ isDetached(): boolean {+ return this._detached;+ }++ async addScriptTag(options: {+ url?: string; path?: string;+ content?: string;+ type?: string; }): Promise<ElementHandle> {+ return this._mainWorld.addScriptTag(options);+ }++ async addStyleTag(options: {+ url?: string;+ path?: string;+ content?: string; }): Promise<ElementHandle> {+ return this._mainWorld.addStyleTag(options);+ }++ async click(selector: string, options?: ClickOptions) {+ return this._secondaryWorld.click(selector, options);+ }++ async dblclick(selector: string, options?: MultiClickOptions) {+ return this._secondaryWorld.dblclick(selector, options);+ }++ async tripleclick(selector: string, options?: MultiClickOptions) {+ return this._secondaryWorld.tripleclick(selector, options);+ }++ async fill(selector: string, value: string) {+ return this._secondaryWorld.fill(selector, value);+ }++ async focus(selector: string) {+ return this._secondaryWorld.focus(selector);+ }++ async hover(selector: string, options?: PointerActionOptions) {+ return this._secondaryWorld.hover(selector, options);+ }++ select(selector: string, ...values: string[]): Promise<string[]>{+ return this._secondaryWorld.select(selector, ...values);+ }++ async tap(selector: string, options?: PointerActionOptions) {+ return this._secondaryWorld.tap(selector, options);+ }++ async type(selector: string, text: string, options: { delay: (number | undefined); } | undefined) {+ return this._mainWorld.type(selector, text, options);+ }++ waitFor(selectorOrFunctionOrTimeout: (string | number | Function), options: any = {}, ...args: any[]): Promise<JSHandle | null> {+ const xPathPattern = '//';++ if (helper.isString(selectorOrFunctionOrTimeout)) {+ const string = selectorOrFunctionOrTimeout as string;+ if (string.startsWith(xPathPattern))+ return this.waitForXPath(string, options);+ return this.waitForSelector(string, options);+ }+ if (helper.isNumber(selectorOrFunctionOrTimeout))+ return new Promise(fulfill => setTimeout(fulfill, selectorOrFunctionOrTimeout as number));+ if (typeof selectorOrFunctionOrTimeout === 'function')+ return this.waitForFunction(selectorOrFunctionOrTimeout, options, ...args);+ return Promise.reject(new Error('Unsupported target type: ' + (typeof selectorOrFunctionOrTimeout)));+ }++ async waitForSelector(selector: string, options: {+ visible?: boolean;+ hidden?: boolean;+ timeout?: number; } | undefined): Promise<ElementHandle | null> {+ const handle = await this._secondaryWorld.waitForSelector(selector, options);+ if (!handle)+ return null;+ const mainExecutionContext = await this._mainWorld.executionContext();+ const result = await mainExecutionContext._adoptElementHandle(handle);+ await handle.dispose();+ return result;+ }++ async waitForXPath(xpath: string, options: {+ visible?: boolean;+ hidden?: boolean;+ timeout?: number; } | undefined): Promise<ElementHandle | null> {+ const handle = await this._secondaryWorld.waitForXPath(xpath, options);+ if (!handle)+ return null;+ const mainExecutionContext = await this._mainWorld.executionContext();+ const result = await mainExecutionContext._adoptElementHandle(handle);+ await handle.dispose();+ return result;+ }++ waitForFunction(+ pageFunction: Function | string,+ options: { polling?: string | number; timeout?: number; } = {},+ ...args): Promise<JSHandle> {+ return this._mainWorld.waitForFunction(pageFunction, options, ...args);+ }++ async title(): Promise<string> {+ return this._secondaryWorld.title();+ }++ _navigated(framePayload: Protocol.Page.Frame) {+ this._name = framePayload.name;+ // TODO(lushnikov): remove this once requestInterception has loaderId exposed.+ this._navigationURL = framePayload.url;+ this._url = framePayload.url;+ }++ _navigatedWithinDocument(url: string) {+ this._url = url;+ }++ _onLifecycleEvent(loaderId: string, name: string) {+ if (name === 'init') {+ this._loaderId = loaderId;+ this._lifecycleEvents.clear();+ }+ this._lifecycleEvents.add(name);+ }++ _onLoadingStopped() {+ this._lifecycleEvents.add('DOMContentLoaded');+ this._lifecycleEvents.add('load');+ }++ _detach() {+ this._detached = true;+ this._mainWorld._detach();+ this._secondaryWorld._detach();+ if (this._parentFrame)+ this._parentFrame._childFrames.delete(this);+ this._parentFrame = null;+ }+}diff --git a/src/chromium/FrameManager.ts b/src/chromium/FrameManager.tsnew file mode 100644index 0000000000..1fac2444f8--- /dev/null+++ b/src/chromium/FrameManager.ts@@ -0,0 +1,316 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { EventEmitter } from 'events';+import { assert, debugError } from '../helper';+import { TimeoutSettings } from '../TimeoutSettings';+import { CDPSession } from './Connection';+import { EVALUATION_SCRIPT_URL, ExecutionContext } from './ExecutionContext';+import { Frame } from './Frame';+import { LifecycleWatcher } from './LifecycleWatcher';+import { NetworkManager, Response } from './NetworkManager';+import { Page } from './Page';+import { Protocol } from './protocol';++const UTILITY_WORLD_NAME = '__playwright_utility_world__';++export const FrameManagerEvents = {+ FrameAttached: Symbol('Events.FrameManager.FrameAttached'),+ FrameNavigated: Symbol('Events.FrameManager.FrameNavigated'),+ FrameDetached: Symbol('Events.FrameManager.FrameDetached'),+ LifecycleEvent: Symbol('Events.FrameManager.LifecycleEvent'),+ FrameNavigatedWithinDocument: Symbol('Events.FrameManager.FrameNavigatedWithinDocument'),+};++export class FrameManager extends EventEmitter {+ _client: CDPSession;+ private _page: Page;+ private _networkManager: NetworkManager;+ _timeoutSettings: TimeoutSettings;+ private _frames = new Map<string, Frame>();+ private _contextIdToContext = new Map<number, ExecutionContext>();+ private _isolatedWorlds = new Set<string>();+ private _mainFrame: Frame;++ constructor(client: CDPSession, page: Page, ignoreHTTPSErrors: boolean, timeoutSettings: TimeoutSettings) {+ super();+ this._client = client;+ this._page = page;+ this._networkManager = new NetworkManager(client, ignoreHTTPSErrors, this);+ this._timeoutSettings = timeoutSettings;++ this._client.on('Page.frameAttached', event => this._onFrameAttached(event.frameId, event.parentFrameId));+ this._client.on('Page.frameNavigated', event => this._onFrameNavigated(event.frame));+ this._client.on('Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url));+ this._client.on('Page.frameDetached', event => this._onFrameDetached(event.frameId));+ this._client.on('Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId));+ this._client.on('Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context));+ this._client.on('Runtime.executionContextDestroyed', event => this._onExecutionContextDestroyed(event.executionContextId));+ this._client.on('Runtime.executionContextsCleared', event => this._onExecutionContextsCleared());+ this._client.on('Page.lifecycleEvent', event => this._onLifecycleEvent(event));+ }++ async initialize() {+ const [,{frameTree}] = await Promise.all([+ this._client.send('Page.enable'),+ this._client.send('Page.getFrameTree'),+ ]);+ this._handleFrameTree(frameTree);+ await Promise.all([+ this._client.send('Page.setLifecycleEventsEnabled', { enabled: true }),+ this._client.send('Runtime.enable', {}).then(() => this._ensureIsolatedWorld(UTILITY_WORLD_NAME)),+ this._networkManager.initialize(),+ ]);+ }++ networkManager(): NetworkManager {+ return this._networkManager;+ }++ async navigateFrame(+ frame: Frame,+ url: string,+ options: { referer?: string; timeout?: number; waitUntil?: string | string[]; } = {}): Promise<Response | null> {+ assertNoLegacyNavigationOptions(options);+ const {+ referer = this._networkManager.extraHTTPHeaders()['referer'],+ waitUntil = ['load'],+ timeout = this._timeoutSettings.navigationTimeout(),+ } = options;++ const watcher = new LifecycleWatcher(this, frame, waitUntil, timeout);+ let ensureNewDocumentNavigation = false;+ let error = await Promise.race([+ navigate(this._client, url, referer, frame._id),+ watcher.timeoutOrTerminationPromise(),+ ]);+ if (!error) {+ error = await Promise.race([+ watcher.timeoutOrTerminationPromise(),+ ensureNewDocumentNavigation ? watcher.newDocumentNavigationPromise() : watcher.sameDocumentNavigationPromise(),+ ]);+ }+ watcher.dispose();+ if (error)+ throw error;+ return watcher.navigationResponse();++ async function navigate(client: CDPSession, url: string, referrer: string, frameId: string): Promise<Error | null> {+ try {+ const response = await client.send('Page.navigate', {url, referrer, frameId});+ ensureNewDocumentNavigation = !!response.loaderId;+ return response.errorText ? new Error(`${response.errorText} at ${url}`) : null;+ } catch (error) {+ return error;+ }+ }+ }++ async waitForFrameNavigation(+ frame: Frame,+ options: { timeout?: number; waitUntil?: string | string[]; } = {}+ ): Promise<Response | null> {+ assertNoLegacyNavigationOptions(options);+ const {+ waitUntil = ['load'],+ timeout = this._timeoutSettings.navigationTimeout(),+ } = options;+ const watcher = new LifecycleWatcher(this, frame, waitUntil, timeout);+ const error = await Promise.race([+ watcher.timeoutOrTerminationPromise(),+ watcher.sameDocumentNavigationPromise(),+ watcher.newDocumentNavigationPromise()+ ]);+ watcher.dispose();+ if (error)+ throw error;+ return watcher.navigationResponse();+ }++ _onLifecycleEvent(event: Protocol.Page.lifecycleEventPayload) {+ const frame = this._frames.get(event.frameId);+ if (!frame)+ return;+ frame._onLifecycleEvent(event.loaderId, event.name);+ this.emit(FrameManagerEvents.LifecycleEvent, frame);+ }++ _onFrameStoppedLoading(frameId: string) {+ const frame = this._frames.get(frameId);+ if (!frame)+ return;+ frame._onLoadingStopped();+ this.emit(FrameManagerEvents.LifecycleEvent, frame);+ }++ _handleFrameTree(frameTree: Protocol.Page.FrameTree) {+ if (frameTree.frame.parentId)+ this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId);+ this._onFrameNavigated(frameTree.frame);+ if (!frameTree.childFrames)+ return;++ for (const child of frameTree.childFrames)+ this._handleFrameTree(child);+ }++ page(): Page {+ return this._page;+ }++ mainFrame(): Frame {+ return this._mainFrame;+ }++ frames(): Frame[] {+ return Array.from(this._frames.values());+ }++ frame(frameId: string): Frame | null {+ return this._frames.get(frameId) || null;+ }++ _onFrameAttached(frameId: string, parentFrameId: string | null) {+ if (this._frames.has(frameId))+ return;+ assert(parentFrameId);+ const parentFrame = this._frames.get(parentFrameId);+ const frame = new Frame(this, this._client, parentFrame, frameId);+ this._frames.set(frame._id, frame);+ this.emit(FrameManagerEvents.FrameAttached, frame);+ }++ _onFrameNavigated(framePayload: Protocol.Page.Frame) {+ const isMainFrame = !framePayload.parentId;+ let frame = isMainFrame ? this._mainFrame : this._frames.get(framePayload.id);+ assert(isMainFrame || frame, 'We either navigate top level or have old version of the navigated frame');++ // Detach all child frames first.+ if (frame) {+ for (const child of frame.childFrames())+ this._removeFramesRecursively(child);+ }++ // Update or create main frame.+ if (isMainFrame) {+ if (frame) {+ // Update frame id to retain frame identity on cross-process navigation.+ this._frames.delete(frame._id);+ frame._id = framePayload.id;+ } else {+ // Initial main frame navigation.+ frame = new Frame(this, this._client, null, framePayload.id);+ }+ this._frames.set(framePayload.id, frame);+ this._mainFrame = frame;+ }++ // Update frame payload.+ frame._navigated(framePayload);++ this.emit(FrameManagerEvents.FrameNavigated, frame);+ }++ async _ensureIsolatedWorld(name: string) {+ if (this._isolatedWorlds.has(name))+ return;+ this._isolatedWorlds.add(name);+ await this._client.send('Page.addScriptToEvaluateOnNewDocument', {+ source: `//# sourceURL=${EVALUATION_SCRIPT_URL}`,+ worldName: name,+ }),+ await Promise.all(this.frames().map(frame => this._client.send('Page.createIsolatedWorld', {+ frameId: frame._id,+ grantUniveralAccess: true,+ worldName: name,+ }).catch(debugError))); // frames might be removed before we send this+ }++ _onFrameNavigatedWithinDocument(frameId: string, url: string) {+ const frame = this._frames.get(frameId);+ if (!frame)+ return;+ frame._navigatedWithinDocument(url);+ this.emit(FrameManagerEvents.FrameNavigatedWithinDocument, frame);+ this.emit(FrameManagerEvents.FrameNavigated, frame);+ }++ _onFrameDetached(frameId: string) {+ const frame = this._frames.get(frameId);+ if (frame)+ this._removeFramesRecursively(frame);+ }++ _onExecutionContextCreated(contextPayload) {+ const frameId = contextPayload.auxData ? contextPayload.auxData.frameId : null;+ const frame = this._frames.get(frameId) || null;+ let world = null;+ if (frame) {+ if (contextPayload.auxData && !!contextPayload.auxData['isDefault']) {+ world = frame._mainWorld;+ } else if (contextPayload.name === UTILITY_WORLD_NAME && !frame._secondaryWorld._hasContext()) {+ // In case of multiple sessions to the same target, there's a race between+ // connections so we might end up creating multiple isolated worlds.+ // We can use either.+ world = frame._secondaryWorld;+ }+ }+ if (contextPayload.auxData && contextPayload.auxData['type'] === 'isolated')+ this._isolatedWorlds.add(contextPayload.name);+ const context: ExecutionContext = new ExecutionContext(this._client, contextPayload, world);+ if (world)+ world._setContext(context);+ this._contextIdToContext.set(contextPayload.id, context);+ }++ _onExecutionContextDestroyed(executionContextId: number) {+ const context = this._contextIdToContext.get(executionContextId);+ if (!context)+ return;+ this._contextIdToContext.delete(executionContextId);+ if (context._world)+ context._world._setContext(null);+ }++ _onExecutionContextsCleared() {+ for (const context of this._contextIdToContext.values()) {+ if (context._world)+ context._world._setContext(null);+ }+ this._contextIdToContext.clear();+ }++ executionContextById(contextId: number): ExecutionContext {+ const context = this._contextIdToContext.get(contextId);+ assert(context, 'INTERNAL ERROR: missing context with id = ' + contextId);+ return context;+ }++ _removeFramesRecursively(frame: Frame) {+ for (const child of frame.childFrames())+ this._removeFramesRecursively(child);+ frame._detach();+ this._frames.delete(frame._id);+ this.emit(FrameManagerEvents.FrameDetached, frame);+ }+}++function assertNoLegacyNavigationOptions(options) {+ assert(options['networkIdleTimeout'] === undefined, 'ERROR: networkIdleTimeout option is no longer supported.');+ assert(options['networkIdleInflight'] === undefined, 'ERROR: networkIdleInflight option is no longer supported.');+ assert(options.waitUntil !== 'networkidle', 'ERROR: "networkidle" option is no longer supported. Use "networkidle2" instead');+}diff --git a/src/chromium/Input.ts b/src/chromium/Input.tsnew file mode 100644index 0000000000..0d8d462af4--- /dev/null+++ b/src/chromium/Input.ts@@ -0,0 +1,337 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the 'License');+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an 'AS IS' BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { CDPSession } from './Connection';+import { assert } from '../helper';+import { keyDefinitions } from '../USKeyboardLayout';++type KeyDescription = {+ keyCode: number,+ key: string,+ text: string,+ code: string,+ location: number,+};++export type Modifier = 'Alt' | 'Control' | 'Meta' | 'Shift';+const kModifiers: Modifier[] = ['Alt', 'Control', 'Meta', 'Shift'];++export type Button = 'left' | 'right' | 'middle';++export class Keyboard {+ private _client: CDPSession;+ _modifiers = 0;+ private _pressedKeys = new Set<unknown>();++ constructor(client: CDPSession) {+ this._client = client;+ }++ async down(key: string, options: { text?: string; } = { text: undefined }) {+ const description = this._keyDescriptionForString(key);++ const autoRepeat = this._pressedKeys.has(description.code);+ this._pressedKeys.add(description.code);+ this._modifiers |= this._modifierBit(description.key);++ const text = options.text === undefined ? description.text : options.text;+ await this._client.send('Input.dispatchKeyEvent', {+ type: text ? 'keyDown' : 'rawKeyDown',+ modifiers: this._modifiers,+ windowsVirtualKeyCode: description.keyCode,+ code: description.code,+ key: description.key,+ text: text,+ unmodifiedText: text,+ autoRepeat,+ location: description.location,+ isKeypad: description.location === 3+ });+ }++ _modifierBit(key: string): number {+ if (key === 'Alt')+ return 1;+ if (key === 'Control')+ return 2;+ if (key === 'Meta')+ return 4;+ if (key === 'Shift')+ return 8;+ return 0;+ }++ _keyDescriptionForString(keyString: string): KeyDescription {+ const shift = this._modifiers & 8;+ const description = {+ key: '',+ keyCode: 0,+ code: '',+ text: '',+ location: 0+ };++ const definition = keyDefinitions[keyString];+ assert(definition, `Unknown key: "${keyString}"`);++ if (definition.key)+ description.key = definition.key;+ if (shift && definition.shiftKey)+ description.key = definition.shiftKey;++ if (definition.keyCode)+ description.keyCode = definition.keyCode;+ if (shift && definition.shiftKeyCode)+ description.keyCode = definition.shiftKeyCode;++ if (definition.code)+ description.code = definition.code;++ if (definition.location)+ description.location = definition.location;++ if (description.key.length === 1)+ description.text = description.key;++ if (definition.text)+ description.text = definition.text;+ if (shift && definition.shiftText)+ description.text = definition.shiftText;++ // if any modifiers besides shift are pressed, no text should be sent+ if (this._modifiers & ~8)+ description.text = '';++ return description;+ }++ async up(key: string) {+ const description = this._keyDescriptionForString(key);++ this._modifiers &= ~this._modifierBit(description.key);+ this._pressedKeys.delete(description.code);+ await this._client.send('Input.dispatchKeyEvent', {+ type: 'keyUp',+ modifiers: this._modifiers,+ key: description.key,+ windowsVirtualKeyCode: description.keyCode,+ code: description.code,+ location: description.location+ });+ }++ async sendCharacter(char: string) {+ await this._client.send('Input.insertText', {text: char});+ }++ async type(text: string, options: { delay: (number | undefined); } | undefined) {+ const delay = (options && options.delay) || null;+ for (const char of text) {+ if (keyDefinitions[char]) {+ await this.press(char, {delay});+ } else {+ if (delay)+ await new Promise(f => setTimeout(f, delay));+ await this.sendCharacter(char);+ }+ }+ }++ async press(key: string, options: { delay?: number; text?: string; } = {}) {+ const {delay = null} = options;+ await this.down(key, options);+ if (delay)+ await new Promise(f => setTimeout(f, options.delay));+ await this.up(key);+ }++ async _ensureModifiers(modifiers: Modifier[]): Promise<Modifier[]> {+ for (const modifier of modifiers) {+ if (!kModifiers.includes(modifier))+ throw new Error('Uknown modifier ' + modifier);+ }+ const restore: Modifier[] = [];+ const promises: Promise<void>[] = [];+ for (const key of kModifiers) {+ const needDown = modifiers.includes(key);+ const isDown = (this._modifiers & this._modifierBit(key)) !== 0;+ if (isDown)+ restore.push(key);+ if (needDown && !isDown)+ promises.push(this.down(key));+ else if (!needDown && isDown)+ promises.push(this.up(key));+ }+ await Promise.all(promises);+ return restore;+ }+}++export class Mouse {+ private _client: CDPSession;+ private _keyboard: Keyboard;+ private _x = 0;+ private _y = 0;+ private _button: 'none' | Button = 'none';++ constructor(client: CDPSession, keyboard: Keyboard) {+ this._client = client;+ this._keyboard = keyboard;+ }++ async move(x: number, y: number, options: { steps?: number; } = {}) {+ const {steps = 1} = options;+ const fromX = this._x, fromY = this._y;+ this._x = x;+ this._y = y;+ for (let i = 1; i <= steps; i++) {+ await this._client.send('Input.dispatchMouseEvent', {+ type: 'mouseMoved',+ button: this._button,+ x: fromX + (this._x - fromX) * (i / steps),+ y: fromY + (this._y - fromY) * (i / steps),+ modifiers: this._keyboard._modifiers+ });+ }+ }++ async click(x: number, y: number, options: { delay?: number; button?: Button; clickCount?: number; } = {}) {+ const {delay = null} = options;+ if (delay !== null) {+ await Promise.all([+ this.move(x, y),+ this.down(options),+ ]);+ await new Promise(f => setTimeout(f, delay));+ await this.up(options);+ } else {+ await Promise.all([+ this.move(x, y),+ this.down(options),+ this.up(options),+ ]);+ }+ }++ async dblclick(x: number, y: number, options: { delay?: number; button?: Button; } = {}) {+ const { delay = null } = options;+ if (delay !== null) {+ await this.move(x, y);+ await this.down({ ...options, clickCount: 1 });+ await new Promise(f => setTimeout(f, delay));+ await this.up({ ...options, clickCount: 1 });+ await new Promise(f => setTimeout(f, delay));+ await this.down({ ...options, clickCount: 2 });+ await new Promise(f => setTimeout(f, delay));+ await this.up({ ...options, clickCount: 2 });+ } else {+ await Promise.all([+ this.move(x, y),+ this.down({ ...options, clickCount: 1 }),+ this.up({ ...options, clickCount: 1 }),+ this.down({ ...options, clickCount: 2 }),+ this.up({ ...options, clickCount: 2 }),+ ]);+ }+ }++ async tripleclick(x: number, y: number, options: { delay?: number; button?: Button; } = {}) {+ const { delay = null } = options;+ if (delay !== null) {+ await this.move(x, y);+ await this.down({ ...options, clickCount: 1 });+ await new Promise(f => setTimeout(f, delay));+ await this.up({ ...options, clickCount: 1 });+ await new Promise(f => setTimeout(f, delay));+ await this.down({ ...options, clickCount: 2 });+ await new Promise(f => setTimeout(f, delay));+ await this.up({ ...options, clickCount: 2 });+ await new Promise(f => setTimeout(f, delay));+ await this.down({ ...options, clickCount: 3 });+ await new Promise(f => setTimeout(f, delay));+ await this.up({ ...options, clickCount: 3 });+ } else {+ await Promise.all([+ this.move(x, y),+ this.down({ ...options, clickCount: 1 }),+ this.up({ ...options, clickCount: 1 }),+ this.down({ ...options, clickCount: 2 }),+ this.up({ ...options, clickCount: 2 }),+ this.down({ ...options, clickCount: 3 }),+ this.up({ ...options, clickCount: 3 }),+ ]);+ }+ }++ async down(options: { button?: Button; clickCount?: number; } = {}) {+ const {button = 'left', clickCount = 1} = options;+ this._button = button;+ await this._client.send('Input.dispatchMouseEvent', {+ type: 'mousePressed',+ button,+ x: this._x,+ y: this._y,+ modifiers: this._keyboard._modifiers,+ clickCount+ });+ }++ async up(options: { button?: Button; clickCount?: number; } = {}) {+ const {button = 'left', clickCount = 1} = options;+ this._button = 'none';+ await this._client.send('Input.dispatchMouseEvent', {+ type: 'mouseReleased',+ button,+ x: this._x,+ y: this._y,+ modifiers: this._keyboard._modifiers,+ clickCount+ });+ }+}++export class Touchscreen {+ private _client: CDPSession;+ private _keyboard: Keyboard;++ constructor(client: CDPSession, keyboard: Keyboard) {+ this._client = client;+ this._keyboard = keyboard;+ }++ async tap(x: number, y: number) {+ // Touches appear to be lost during the first frame after navigation.+ // This waits a frame before sending the tap.+ // @see https://crbug.com/613219+ await this._client.send('Runtime.evaluate', {+ expression: 'new Promise(x => requestAnimationFrame(() => requestAnimationFrame(x)))',+ awaitPromise: true+ });++ const touchPoints = [{x: Math.round(x), y: Math.round(y)}];+ await this._client.send('Input.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints,+ modifiers: this._keyboard._modifiers+ });+ await this._client.send('Input.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints: [],+ modifiers: this._keyboard._modifiers+ });+ }+}diff --git a/src/chromium/JSHandle.ts b/src/chromium/JSHandle.tsnew file mode 100644index 0000000000..c8c18372ff--- /dev/null+++ b/src/chromium/JSHandle.ts@@ -0,0 +1,578 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import * as path from 'path';+import { CDPSession } from './Connection';+import { ExecutionContext } from './ExecutionContext';+import { Frame } from './Frame';+import { FrameManager } from './FrameManager';+import { assert, debugError, helper } from '../helper';+import { valueFromRemoteObject, releaseObject } from './protocolHelper';+import { Page } from './Page';+import { Modifier, Button } from './Input';+import { Protocol } from './protocol';++type Point = {+ x: number;+ y: number;+};++export type PointerActionOptions = {+ modifiers?: Modifier[];+ relativePoint?: Point;+};++export type ClickOptions = PointerActionOptions & {+ delay?: number;+ button?: Button;+ clickCount?: number;+};++export type MultiClickOptions = PointerActionOptions & {+ delay?: number;+ button?: Button;+};++export function createJSHandle(context: ExecutionContext, remoteObject: Protocol.Runtime.RemoteObject) {+ const frame = context.frame();+ if (remoteObject.subtype === 'node' && frame) {+ const frameManager = frame._frameManager;+ return new ElementHandle(context, context._client, remoteObject, frameManager.page(), frameManager);+ }+ return new JSHandle(context, context._client, remoteObject);+}++export class JSHandle {+ _context: ExecutionContext;+ protected _client: CDPSession;+ _remoteObject: Protocol.Runtime.RemoteObject;+ _disposed = false;++ constructor(context: ExecutionContext, client: CDPSession, remoteObject: Protocol.Runtime.RemoteObject) {+ this._context = context;+ this._client = client;+ this._remoteObject = remoteObject;+ }++ executionContext(): ExecutionContext {+ return this._context;+ }++ async evaluate(pageFunction: Function | string, ...args: any[]): Promise<(any)> {+ return await this.executionContext().evaluate(pageFunction, this, ...args);+ }++ async evaluateHandle(pageFunction: Function | string, ...args: any[]): Promise<JSHandle> {+ return await this.executionContext().evaluateHandle(pageFunction, this, ...args);+ }++ async getProperty(propertyName: string): Promise<JSHandle | null> {+ const objectHandle = await this.evaluateHandle((object, propertyName) => {+ const result = {__proto__: null};+ result[propertyName] = object[propertyName];+ return result;+ }, propertyName);+ const properties = await objectHandle.getProperties();+ const result = properties.get(propertyName) || null;+ await objectHandle.dispose();+ return result;+ }++ async getProperties(): Promise<Map<string, JSHandle>> {+ const response = await this._client.send('Runtime.getProperties', {+ objectId: this._remoteObject.objectId,+ ownProperties: true+ });+ const result = new Map();+ for (const property of response.result) {+ if (!property.enumerable)+ continue;+ result.set(property.name, createJSHandle(this._context, property.value));+ }+ return result;+ }++ async jsonValue(): Promise<object | null> {+ if (this._remoteObject.objectId) {+ const response = await this._client.send('Runtime.callFunctionOn', {+ functionDeclaration: 'function() { return this; }',+ objectId: this._remoteObject.objectId,+ returnByValue: true,+ awaitPromise: true,+ });+ return valueFromRemoteObject(response.result);+ }+ return valueFromRemoteObject(this._remoteObject);+ }++ asElement(): ElementHandle | null {+ return null;+ }++ async dispose() {+ if (this._disposed)+ return;+ this._disposed = true;+ await releaseObject(this._client, this._remoteObject);+ }++ toString(): string {+ if (this._remoteObject.objectId) {+ const type = this._remoteObject.subtype || this._remoteObject.type;+ return 'JSHandle@' + type;+ }+ return 'JSHandle:' + valueFromRemoteObject(this._remoteObject);+ }+}++export class ElementHandle extends JSHandle {+ private _page: Page;+ private _frameManager: FrameManager;++ constructor(context: ExecutionContext, client: CDPSession, remoteObject: Protocol.Runtime.RemoteObject, page: Page, frameManager: FrameManager) {+ super(context, client, remoteObject);+ this._client = client;+ this._remoteObject = remoteObject;+ this._page = page;+ this._frameManager = frameManager;+ }++ asElement(): ElementHandle | null {+ return this;+ }++ async contentFrame(): Promise<Frame|null> {+ const nodeInfo = await this._client.send('DOM.describeNode', {+ objectId: this._remoteObject.objectId+ });+ if (typeof nodeInfo.node.frameId !== 'string')+ return null;+ return this._frameManager.frame(nodeInfo.node.frameId);+ }++ async _scrollIntoViewIfNeeded() {+ const error = await this.evaluate(async(element, pageJavascriptEnabled) => {+ if (!element.isConnected)+ return 'Node is detached from document';+ if (element.nodeType !== Node.ELEMENT_NODE)+ return 'Node is not of type HTMLElement';+ // force-scroll if page's javascript is disabled.+ if (!pageJavascriptEnabled) {+ element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});+ return false;+ }+ const visibleRatio = await new Promise(resolve => {+ const observer = new IntersectionObserver(entries => {+ resolve(entries[0].intersectionRatio);+ observer.disconnect();+ });+ observer.observe(element);+ });+ if (visibleRatio !== 1.0)+ element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});+ return false;+ }, this._page._javascriptEnabled);+ if (error)+ throw new Error(error);+ }++ async _clickablePoint(): Promise<Point> {+ const [result, layoutMetrics] = await Promise.all([+ this._client.send('DOM.getContentQuads', {+ objectId: this._remoteObject.objectId+ }).catch(debugError),+ this._client.send('Page.getLayoutMetrics'),+ ]);+ if (!result || !result.quads.length)+ throw new Error('Node is either not visible or not an HTMLElement');+ // Filter out quads that have too small area to click into.+ const {clientWidth, clientHeight} = layoutMetrics.layoutViewport;+ const quads = result.quads.map(quad => this._fromProtocolQuad(quad)).map(quad => this._intersectQuadWithViewport(quad, clientWidth, clientHeight)).filter(quad => computeQuadArea(quad) > 1);+ if (!quads.length)+ throw new Error('Node is either not visible or not an HTMLElement');+ // Return the middle point of the first quad.+ const quad = quads[0];+ let x = 0;+ let y = 0;+ for (const point of quad) {+ x += point.x;+ y += point.y;+ }+ return {+ x: x / 4,+ y: y / 4+ };+ }++ async _viewportPointAndScroll(relativePoint: Point): Promise<{point: Point, scrollX: number, scrollY: number}> {+ const model = await this._getBoxModel();+ let point: Point;+ if (!model) {+ point = relativePoint;+ } else {+ // Use padding quad to be compatible with offsetX/offsetY properties.+ const quad = model.model.padding;+ const x = Math.min(quad[0], quad[2], quad[4], quad[6]);+ const y = Math.min(quad[1], quad[3], quad[5], quad[7]);+ point = {+ x: x + relativePoint.x,+ y: y + relativePoint.y,+ };+ }+ const metrics = await this._client.send('Page.getLayoutMetrics');+ // Give one extra pixel to avoid any issues on viewport edge.+ let scrollX = 0;+ if (point.x < 1)+ scrollX = point.x - 1;+ if (point.x > metrics.layoutViewport.clientWidth - 1)+ scrollX = point.x - metrics.layoutViewport.clientWidth + 1;+ let scrollY = 0;+ if (point.y < 1)+ scrollY = point.y - 1;+ if (point.y > metrics.layoutViewport.clientHeight - 1)+ scrollY = point.y - metrics.layoutViewport.clientHeight + 1;+ return { point, scrollX, scrollY };+ }++ async _performPointerAction(action: (point: Point) => Promise<void>, options?: PointerActionOptions): Promise<void> {+ await this._scrollIntoViewIfNeeded();+ let point: Point;+ if (options && options.relativePoint) {+ let r = await this._viewportPointAndScroll(options.relativePoint);+ if (r.scrollX || r.scrollY) {+ const error = await this.evaluate((element, scrollX, scrollY) => {+ if (!element.ownerDocument || !element.ownerDocument.defaultView)+ return 'Node does not have a containing window';+ element.ownerDocument.defaultView.scrollBy(scrollX, scrollY);+ return false;+ }, r.scrollX, r.scrollY);+ if (error)+ throw new Error(error);+ r = await this._viewportPointAndScroll(options.relativePoint);+ if (r.scrollX || r.scrollY)+ throw new Error('Failed to scroll relative point into viewport');+ }+ point = r.point;+ } else {+ await this._scrollIntoViewIfNeeded();+ point = await this._clickablePoint();+ }+ let restoreModifiers: Modifier[] | undefined;+ if (options && options.modifiers)+ restoreModifiers = await this._page.keyboard._ensureModifiers(options.modifiers);+ await action(point);+ if (restoreModifiers)+ await this._page.keyboard._ensureModifiers(restoreModifiers);+ }++ _getBoxModel(): Promise<void | Protocol.DOM.getBoxModelReturnValue> {+ return this._client.send('DOM.getBoxModel', {+ objectId: this._remoteObject.objectId+ }).catch(error => debugError(error));+ }++ _fromProtocolQuad(quad: number[]): Array<{ x: number; y: number; }> {+ return [+ {x: quad[0], y: quad[1]},+ {x: quad[2], y: quad[3]},+ {x: quad[4], y: quad[5]},+ {x: quad[6], y: quad[7]}+ ];+ }++ _intersectQuadWithViewport(quad: Array<{ x: number; y: number; }>, width: number, height: number): Array<{ x: number; y: number; }> {+ return quad.map(point => ({+ x: Math.min(Math.max(point.x, 0), width),+ y: Math.min(Math.max(point.y, 0), height),+ }));+ }++ hover(options?: PointerActionOptions): Promise<void> {+ return this._performPointerAction(point => this._page.mouse.move(point.x, point.y), options);+ }++ click(options?: ClickOptions): Promise<void> {+ return this._performPointerAction(point => this._page.mouse.click(point.x, point.y, options), options);+ }++ dblclick(options?: MultiClickOptions): Promise<void> {+ return this._performPointerAction(point => this._page.mouse.dblclick(point.x, point.y, options), options);+ }++ tripleclick(options?: MultiClickOptions): Promise<void> {+ return this._performPointerAction(point => this._page.mouse.tripleclick(point.x, point.y, options), options);+ }++ async select(...values: string[]): Promise<string[]> {+ for (const value of values)+ assert(helper.isString(value), 'Values must be strings. Found value "' + value + '" of type "' + (typeof value) + '"');+ return this.evaluate((element: HTMLSelectElement, values: string[]) => {+ if (element.nodeName.toLowerCase() !== 'select')+ throw new Error('Element is not a <select> element.');++ const options = Array.from(element.options);+ element.value = undefined;+ for (const option of options) {+ option.selected = values.includes(option.value);+ if (option.selected && !element.multiple)+ break;+ }+ element.dispatchEvent(new Event('input', { 'bubbles': true }));+ element.dispatchEvent(new Event('change', { 'bubbles': true }));+ return options.filter(option => option.selected).map(option => option.value);+ }, values);+ }++ async fill(value: string): Promise<void> {+ assert(helper.isString(value), 'Value must be string. Found value "' + value + '" of type "' + (typeof value) + '"');+ const error = await this.evaluate((element: HTMLElement) => {+ if (element.nodeType !== Node.ELEMENT_NODE)+ return 'Node is not of type HTMLElement';+ if (element.nodeName.toLowerCase() === 'input') {+ const input = element as HTMLInputElement;+ const type = input.getAttribute('type') || '';+ const kTextInputTypes = new Set(['', 'password', 'search', 'tel', 'text', 'url']);+ if (!kTextInputTypes.has(type.toLowerCase()))+ return 'Cannot fill input of type "' + type + '".';+ input.selectionStart = 0;+ input.selectionEnd = input.value.length;+ } else if (element.nodeName.toLowerCase() === 'textarea') {+ const textarea = element as HTMLTextAreaElement;+ textarea.selectionStart = 0;+ textarea.selectionEnd = textarea.value.length;+ } else if (element.isContentEditable) {+ if (!element.ownerDocument || !element.ownerDocument.defaultView)+ return 'Element does not belong to a window';+ const range = element.ownerDocument.createRange();+ range.selectNodeContents(element);+ const selection = element.ownerDocument.defaultView.getSelection();+ selection.removeAllRanges();+ selection.addRange(range);+ } else {+ return 'Element is not an <input>, <textarea> or [contenteditable] element.';+ }+ return false;+ });+ if (error)+ throw new Error(error);+ await this.focus();+ await this._page.keyboard.sendCharacter(value);+ }++ async uploadFile(...filePaths: string[]) {+ const files = filePaths.map(filePath => path.resolve(filePath));+ const objectId = this._remoteObject.objectId;+ await this._client.send('DOM.setFileInputFiles', { objectId, files });+ }++ tap(options?: PointerActionOptions): Promise<void> {+ return this._performPointerAction(point => this._page.touchscreen.tap(point.x, point.y), options);+ }++ async focus() {+ await this.evaluate(element => element.focus());+ }++ async type(text: string, options: { delay: (number | undefined); } | undefined) {+ await this.focus();+ await this._page.keyboard.type(text, options);+ }++ async press(key: string, options: { delay?: number; text?: string; } | undefined) {+ await this.focus();+ await this._page.keyboard.press(key, options);+ }++ async boundingBox(): Promise<{ x: number; y: number; width: number; height: number; } | null> {+ const result = await this._getBoxModel();++ if (!result)+ return null;++ const quad = result.model.border;+ const x = Math.min(quad[0], quad[2], quad[4], quad[6]);+ const y = Math.min(quad[1], quad[3], quad[5], quad[7]);+ const width = Math.max(quad[0], quad[2], quad[4], quad[6]) - x;+ const height = Math.max(quad[1], quad[3], quad[5], quad[7]) - y;++ return {x, y, width, height};+ }++ async boxModel(): Promise<BoxModel | null> {+ const result = await this._getBoxModel();++ if (!result)+ return null;++ const {content, padding, border, margin, width, height} = result.model;+ return {+ content: this._fromProtocolQuad(content),+ padding: this._fromProtocolQuad(padding),+ border: this._fromProtocolQuad(border),+ margin: this._fromProtocolQuad(margin),+ width,+ height+ };+ }++ async screenshot(options: any = {}): Promise<string | Buffer> {+ let needsViewportReset = false;++ let boundingBox = await this.boundingBox();+ assert(boundingBox, 'Node is either not visible or not an HTMLElement');++ const viewport = this._page.viewport();++ if (viewport && (boundingBox.width > viewport.width || boundingBox.height > viewport.height)) {+ const newViewport = {+ width: Math.max(viewport.width, Math.ceil(boundingBox.width)),+ height: Math.max(viewport.height, Math.ceil(boundingBox.height)),+ };+ await this._page.setViewport(Object.assign({}, viewport, newViewport));++ needsViewportReset = true;+ }++ await this._scrollIntoViewIfNeeded();++ boundingBox = await this.boundingBox();+ assert(boundingBox, 'Node is either not visible or not an HTMLElement');+ assert(boundingBox.width !== 0, 'Node has 0 width.');+ assert(boundingBox.height !== 0, 'Node has 0 height.');++ const { layoutViewport: { pageX, pageY } } = await this._client.send('Page.getLayoutMetrics');++ const clip = Object.assign({}, boundingBox);+ clip.x += pageX;+ clip.y += pageY;++ const imageData = await this._page.screenshot(Object.assign({}, {+ clip+ }, options));++ if (needsViewportReset)+ await this._page.setViewport(viewport);++ return imageData;+ }++ async $(selector: string): Promise<ElementHandle | null> {+ const handle = await this.evaluateHandle(+ (element, selector) => element.querySelector(selector),+ selector+ );+ const element = handle.asElement();+ if (element)+ return element;+ await handle.dispose();+ return null;+ }++ async $$(selector: string): Promise<ElementHandle[]> {+ const arrayHandle = await this.evaluateHandle(+ (element, selector) => element.querySelectorAll(selector),+ selector+ );+ const properties = await arrayHandle.getProperties();+ await arrayHandle.dispose();+ const result = [];+ for (const property of properties.values()) {+ const elementHandle = property.asElement();+ if (elementHandle)+ result.push(elementHandle);+ }+ return result;+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<(object | undefined)> {+ const elementHandle = await this.$(selector);+ if (!elementHandle)+ throw new Error(`Error: failed to find element matching selector "${selector}"`);+ const result = await elementHandle.evaluate(pageFunction, ...args);+ await elementHandle.dispose();+ return result;+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<(object | undefined)> {+ const arrayHandle = await this.evaluateHandle(+ (element, selector) => Array.from(element.querySelectorAll(selector)),+ selector+ );++ const result = await arrayHandle.evaluate(pageFunction, ...args);+ await arrayHandle.dispose();+ return result;+ }++ async $x(expression: string): Promise<ElementHandle[]> {+ const arrayHandle = await this.evaluateHandle(+ (element, expression) => {+ const document = element.ownerDocument || element;+ const iterator = document.evaluate(expression, element, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);+ const array = [];+ let item;+ while ((item = iterator.iterateNext()))+ array.push(item);+ return array;+ },+ expression+ );+ const properties = await arrayHandle.getProperties();+ await arrayHandle.dispose();+ const result = [];+ for (const property of properties.values()) {+ const elementHandle = property.asElement();+ if (elementHandle)+ result.push(elementHandle);+ }+ return result;+ }++ isIntersectingViewport(): Promise<boolean> {+ return this.evaluate(async element => {+ const visibleRatio = await new Promise(resolve => {+ const observer = new IntersectionObserver(entries => {+ resolve(entries[0].intersectionRatio);+ observer.disconnect();+ });+ observer.observe(element);+ });+ return visibleRatio > 0;+ });+ }+}++function computeQuadArea(quad) {+ // Compute sum of all directed areas of adjacent triangles+ // https://en.wikipedia.org/wiki/Polygon#Simple_polygons+ let area = 0;+ for (let i = 0; i < quad.length; ++i) {+ const p1 = quad[i];+ const p2 = quad[(i + 1) % quad.length];+ area += (p1.x * p2.y - p2.x * p1.y) / 2;+ }+ return Math.abs(area);+}++type BoxModel = {+ content: {x: number, y: number}[],+ padding: {x: number, y: number}[],+ border: {x: number, y: number}[],+ margin: {x: number, y: number}[],+ width: number,+ height : number+};diff --git a/src/chromium/Launcher.ts b/src/chromium/Launcher.tsnew file mode 100644index 0000000000..fec2385564--- /dev/null+++ b/src/chromium/Launcher.ts@@ -0,0 +1,404 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import * as childProcess from 'child_process';+import * as fs from 'fs';+import * as http from 'http';+import * as https from 'https';+import * as os from 'os';+import * as path from 'path';+import * as readline from 'readline';+import * as removeFolder from 'rimraf';+import * as URL from 'url';+import { Browser } from './Browser';+import { BrowserFetcher } from './BrowserFetcher';+import { Connection } from './Connection';+import { TimeoutError } from '../Errors';+import { assert, debugError, helper } from '../helper';+import { Viewport } from './Page';+import { PipeTransport } from './PipeTransport';+import { WebSocketTransport } from './WebSocketTransport';+import { ConnectionTransport } from '../ConnectionTransport';++const mkdtempAsync = helper.promisify(fs.mkdtemp);+const removeFolderAsync = helper.promisify(removeFolder);++const CHROME_PROFILE_PATH = path.join(os.tmpdir(), 'playwright_dev_profile-');++const DEFAULT_ARGS = [+ '--disable-background-networking',+ '--enable-features=NetworkService,NetworkServiceInProcess',+ '--disable-background-timer-throttling',+ '--disable-backgrounding-occluded-windows',+ '--disable-breakpad',+ '--disable-client-side-phishing-detection',+ '--disable-component-extensions-with-background-pages',+ '--disable-default-apps',+ '--disable-dev-shm-usage',+ '--disable-extensions',+ // BlinkGenPropertyTrees disabled due to crbug.com/937609+ '--disable-features=TranslateUI,BlinkGenPropertyTrees',+ '--disable-hang-monitor',+ '--disable-ipc-flooding-protection',+ '--disable-popup-blocking',+ '--disable-prompt-on-repost',+ '--disable-renderer-backgrounding',+ '--disable-sync',+ '--force-color-profile=srgb',+ '--metrics-recording-only',+ '--no-first-run',+ '--enable-automation',+ '--password-store=basic',+ '--use-mock-keychain',+];++export class Launcher {+ private _projectRoot: string;+ private _preferredRevision: string;+ private _isPlaywrightCore: boolean;++ constructor(projectRoot: string, preferredRevision: string, isPlaywrightCore: boolean) {+ this._projectRoot = projectRoot;+ this._preferredRevision = preferredRevision;+ this._isPlaywrightCore = isPlaywrightCore;+ }++ async launch(options: (LauncherLaunchOptions & LauncherChromeArgOptions & LauncherBrowserOptions) = {}): Promise<Browser> {+ const {+ ignoreDefaultArgs = false,+ args = [],+ dumpio = false,+ executablePath = null,+ pipe = false,+ env = process.env,+ handleSIGINT = true,+ handleSIGTERM = true,+ handleSIGHUP = true,+ ignoreHTTPSErrors = false,+ defaultViewport = {width: 800, height: 600},+ slowMo = 0,+ timeout = 30000+ } = options;++ const chromeArguments = [];+ if (!ignoreDefaultArgs)+ chromeArguments.push(...this.defaultArgs(options));+ else if (Array.isArray(ignoreDefaultArgs))+ chromeArguments.push(...this.defaultArgs(options).filter(arg => ignoreDefaultArgs.indexOf(arg) === -1));+ else+ chromeArguments.push(...args);++ let temporaryUserDataDir = null;++ if (!chromeArguments.some(argument => argument.startsWith('--remote-debugging-')))+ chromeArguments.push(pipe ? '--remote-debugging-pipe' : '--remote-debugging-port=0');+ if (!chromeArguments.some(arg => arg.startsWith('--user-data-dir'))) {+ temporaryUserDataDir = await mkdtempAsync(CHROME_PROFILE_PATH);+ chromeArguments.push(`--user-data-dir=${temporaryUserDataDir}`);+ }++ let chromeExecutable = executablePath;+ if (!executablePath) {+ const {missingText, executablePath} = this._resolveExecutablePath();+ if (missingText)+ throw new Error(missingText);+ chromeExecutable = executablePath;+ }++ const usePipe = chromeArguments.includes('--remote-debugging-pipe');+ let stdio: ('ignore' | 'pipe')[] = ['pipe', 'pipe', 'pipe'];+ if (usePipe) {+ if (dumpio)+ stdio = ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'];+ else+ stdio = ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'];+ }+ const chromeProcess = childProcess.spawn(+ chromeExecutable,+ chromeArguments,+ {+ // On non-windows platforms, `detached: true` makes child process a leader of a new+ // process group, making it possible to kill child process tree with `.kill(-pid)` command.+ // @see https://nodejs.org/api/child_process.html#child_process_options_detached+ detached: process.platform !== 'win32',+ env,+ stdio+ }+ );++ if (dumpio) {+ chromeProcess.stderr.pipe(process.stderr);+ chromeProcess.stdout.pipe(process.stdout);+ }++ let chromeClosed = false;+ const waitForChromeToClose = new Promise((fulfill, reject) => {+ chromeProcess.once('exit', () => {+ chromeClosed = true;+ // Cleanup as processes exit.+ if (temporaryUserDataDir) {+ removeFolderAsync(temporaryUserDataDir)+ .then(() => fulfill())+ .catch(err => console.error(err));+ } else {+ fulfill();+ }+ });+ });++ const listeners = [ helper.addEventListener(process, 'exit', killChrome) ];+ if (handleSIGINT)+ listeners.push(helper.addEventListener(process, 'SIGINT', () => { killChrome(); process.exit(130); }));+ if (handleSIGTERM)+ listeners.push(helper.addEventListener(process, 'SIGTERM', gracefullyCloseChrome));+ if (handleSIGHUP)+ listeners.push(helper.addEventListener(process, 'SIGHUP', gracefullyCloseChrome));+ let connection: Connection | null = null;+ try {+ if (!usePipe) {+ const browserWSEndpoint = await waitForWSEndpoint(chromeProcess, timeout, this._preferredRevision);+ const transport = await WebSocketTransport.create(browserWSEndpoint);+ connection = new Connection(browserWSEndpoint, transport, slowMo);+ } else {+ const transport = new PipeTransport(chromeProcess.stdio[3] as NodeJS.WritableStream, chromeProcess.stdio[4] as NodeJS.ReadableStream);+ connection = new Connection('', transport, slowMo);+ }+ const browser = await Browser.create(connection, [], ignoreHTTPSErrors, defaultViewport, chromeProcess, gracefullyCloseChrome);+ await browser.waitForTarget(t => t.type() === 'page');+ return browser;+ } catch (e) {+ killChrome();+ throw e;+ }++ function gracefullyCloseChrome(): Promise<any> {+ helper.removeEventListeners(listeners);+ if (temporaryUserDataDir) {+ killChrome();+ } else if (connection) {+ // Attempt to close chrome gracefully+ connection.send('Browser.close').catch(error => {+ debugError(error);+ killChrome();+ });+ }+ return waitForChromeToClose;+ }++ // This method has to be sync to be used as 'exit' event handler.+ function killChrome() {+ helper.removeEventListeners(listeners);+ if (chromeProcess.pid && !chromeProcess.killed && !chromeClosed) {+ // Force kill chrome.+ try {+ if (process.platform === 'win32')+ childProcess.execSync(`taskkill /pid ${chromeProcess.pid} /T /F`);+ else+ process.kill(-chromeProcess.pid, 'SIGKILL');+ } catch (e) {+ // the process might have already stopped+ }+ }+ // Attempt to remove temporary profile directory to avoid littering.+ try {+ removeFolder.sync(temporaryUserDataDir);+ } catch (e) { }+ }+ }++ defaultArgs(options: LauncherChromeArgOptions = {}): string[] {+ const {+ devtools = false,+ headless = !devtools,+ args = [],+ userDataDir = null+ } = options;+ const chromeArguments = [...DEFAULT_ARGS];+ if (userDataDir)+ chromeArguments.push(`--user-data-dir=${userDataDir}`);+ if (devtools)+ chromeArguments.push('--auto-open-devtools-for-tabs');+ if (headless) {+ chromeArguments.push(+ '--headless',+ '--hide-scrollbars',+ '--mute-audio'+ );+ }+ if (args.every(arg => arg.startsWith('-')))+ chromeArguments.push('about:blank');+ chromeArguments.push(...args);+ return chromeArguments;+ }++ executablePath(): string {+ return this._resolveExecutablePath().executablePath;+ }++ async connect(options: (LauncherBrowserOptions & {+ browserWSEndpoint?: string;+ browserURL?: string;+ transport?: ConnectionTransport; })): Promise<Browser> {+ const {+ browserWSEndpoint,+ browserURL,+ ignoreHTTPSErrors = false,+ defaultViewport = {width: 800, height: 600},+ transport,+ slowMo = 0,+ } = options;++ assert(Number(!!browserWSEndpoint) + Number(!!browserURL) + Number(!!transport) === 1, 'Exactly one of browserWSEndpoint, browserURL or transport must be passed to playwright.connect');++ let connection = null;+ if (transport) {+ connection = new Connection('', transport, slowMo);+ } else if (browserWSEndpoint) {+ const connectionTransport = await WebSocketTransport.create(browserWSEndpoint);+ connection = new Connection(browserWSEndpoint, connectionTransport, slowMo);+ } else if (browserURL) {+ const connectionURL = await getWSEndpoint(browserURL);+ const connectionTransport = await WebSocketTransport.create(connectionURL);+ connection = new Connection(connectionURL, connectionTransport, slowMo);+ }++ const {browserContextIds} = await connection.send('Target.getBrowserContexts');+ return Browser.create(connection, browserContextIds, ignoreHTTPSErrors, defaultViewport, null, () => connection.send('Browser.close').catch(debugError));+ }++ _resolveExecutablePath(): { executablePath: string; missingText: string | null; } {+ // playwright-core doesn't take into account PLAYWRIGHT_* env variables.+ if (!this._isPlaywrightCore) {+ const executablePath = process.env.PLAYWRIGHT_EXECUTABLE_PATH || process.env.npm_config_playwright_executable_path || process.env.npm_package_config_playwright_executable_path;+ if (executablePath) {+ const missingText = !fs.existsSync(executablePath) ? 'Tried to use PLAYWRIGHT_EXECUTABLE_PATH env variable to launch browser but did not find any executable at: ' + executablePath : null;+ return { executablePath, missingText };+ }+ }+ const browserFetcher = new BrowserFetcher(this._projectRoot);+ if (!this._isPlaywrightCore) {+ const revision = process.env['PLAYWRIGHT_CHROMIUM_REVISION'];+ if (revision) {+ const revisionInfo = browserFetcher.revisionInfo(revision);+ const missingText = !revisionInfo.local ? 'Tried to use PLAYWRIGHT_CHROMIUM_REVISION env variable to launch browser but did not find executable at: ' + revisionInfo.executablePath : null;+ return {executablePath: revisionInfo.executablePath, missingText};+ }+ }+ const revisionInfo = browserFetcher.revisionInfo(this._preferredRevision);+ const missingText = !revisionInfo.local ? `Chromium revision is not downloaded. Run "npm install" or "yarn install"` : null;+ return {executablePath: revisionInfo.executablePath, missingText};+ }++}++function waitForWSEndpoint(chromeProcess: childProcess.ChildProcess, timeout: number, preferredRevision: string): Promise<string> {+ return new Promise((resolve, reject) => {+ const rl = readline.createInterface({ input: chromeProcess.stderr });+ let stderr = '';+ const listeners = [+ helper.addEventListener(rl, 'line', onLine),+ helper.addEventListener(rl, 'close', () => onClose()),+ helper.addEventListener(chromeProcess, 'exit', () => onClose()),+ helper.addEventListener(chromeProcess, 'error', error => onClose(error))+ ];+ const timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0;++ function onClose(error?: Error) {+ cleanup();+ reject(new Error([+ 'Failed to launch chrome!' + (error ? ' ' + error.message : ''),+ stderr,+ '',+ 'TROUBLESHOOTING: https://github.com/Microsoft/playwright/blob/master/docs/troubleshooting.md',+ '',+ ].join('\n')));+ }++ function onTimeout() {+ cleanup();+ reject(new TimeoutError(`Timed out after ${timeout} ms while trying to connect to Chrome! The only Chrome revision guaranteed to work is r${preferredRevision}`));+ }++ function onLine(line: string) {+ stderr += line + '\n';+ const match = line.match(/^DevTools listening on (ws:\/\/.*)$/);+ if (!match)+ return;+ cleanup();+ resolve(match[1]);+ }++ function cleanup() {+ if (timeoutId)+ clearTimeout(timeoutId);+ helper.removeEventListeners(listeners);+ }+ });+}++function getWSEndpoint(browserURL: string): Promise<string> {+ let resolve, reject;+ const promise = new Promise<string>((res, rej) => { resolve = res; reject = rej; });++ const endpointURL = URL.resolve(browserURL, '/json/version');+ const protocol = endpointURL.startsWith('https') ? https : http;+ const requestOptions = Object.assign(URL.parse(endpointURL), { method: 'GET' });+ const request = protocol.request(requestOptions, res => {+ let data = '';+ if (res.statusCode !== 200) {+ // Consume response data to free up memory.+ res.resume();+ reject(new Error('HTTP ' + res.statusCode));+ return;+ }+ res.setEncoding('utf8');+ res.on('data', chunk => data += chunk);+ res.on('end', () => resolve(JSON.parse(data).webSocketDebuggerUrl));+ });++ request.on('error', reject);+ request.end();++ return promise.catch(e => {+ e.message = `Failed to fetch browser webSocket url from ${endpointURL}: ` + e.message;+ throw e;+ });+}++export type LauncherChromeArgOptions = {+ headless?: boolean,+ args?: string[],+ userDataDir?: string,+ devtools?: boolean,+};++export type LauncherLaunchOptions = {+ executablePath?: string,+ ignoreDefaultArgs?: boolean|string[],+ handleSIGINT?: boolean,+ handleSIGTERM?: boolean,+ handleSIGHUP?: boolean,+ timeout?: number,+ dumpio?: boolean,+ env?: {[key: string]: string} | undefined,+ pipe?: boolean,+};++export type LauncherBrowserOptions = {+ ignoreHTTPSErrors?: boolean,+ defaultViewport?: Viewport | null,+ slowMo?: number,+};diff --git a/src/chromium/LifecycleWatcher.ts b/src/chromium/LifecycleWatcher.tsnew file mode 100644index 0000000000..06c1977b49--- /dev/null+++ b/src/chromium/LifecycleWatcher.ts@@ -0,0 +1,176 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { CDPSessionEvents } from './Connection';+import { TimeoutError } from '../Errors';+import { Frame } from './Frame';+import { FrameManager, FrameManagerEvents } from './FrameManager';+import { assert, helper, RegisteredListener } from '../helper';+import { NetworkManagerEvents, Request, Response } from './NetworkManager';++export class LifecycleWatcher {+ private _expectedLifecycle: string[];+ private _frameManager: FrameManager;+ private _frame: Frame;+ private _initialLoaderId: string;+ private _timeout: number;+ private _navigationRequest: Request | null = null;+ private _eventListeners: RegisteredListener[];+ private _sameDocumentNavigationPromise: Promise<Error | null>;+ private _sameDocumentNavigationCompleteCallback: () => void;+ private _lifecyclePromise: Promise<void>;+ private _lifecycleCallback: () => void;+ private _newDocumentNavigationPromise: Promise<Error | null>;+ private _newDocumentNavigationCompleteCallback: () => void;+ private _timeoutPromise: Promise<Error>;+ private _terminationPromise: Promise<Error | null>;+ private _terminationCallback: () => void;+ private _maximumTimer: NodeJS.Timer;+ private _hasSameDocumentNavigation: boolean;++ constructor(frameManager: FrameManager, frame: Frame, waitUntil: string | string[], timeout: number) {+ if (Array.isArray(waitUntil))+ waitUntil = waitUntil.slice();+ else if (typeof waitUntil === 'string')+ waitUntil = [waitUntil];+ this._expectedLifecycle = waitUntil.map(value => {+ const protocolEvent = playwrightToProtocolLifecycle.get(value);+ assert(protocolEvent, 'Unknown value for options.waitUntil: ' + value);+ return protocolEvent;+ });++ this._frameManager = frameManager;+ this._frame = frame;+ this._initialLoaderId = frame._loaderId;+ this._timeout = timeout;+ this._eventListeners = [+ helper.addEventListener(frameManager._client, CDPSessionEvents.Disconnected, () => this._terminate(new Error('Navigation failed because browser has disconnected!'))),+ helper.addEventListener(this._frameManager, FrameManagerEvents.LifecycleEvent, this._checkLifecycleComplete.bind(this)),+ helper.addEventListener(this._frameManager, FrameManagerEvents.FrameNavigatedWithinDocument, this._navigatedWithinDocument.bind(this)),+ helper.addEventListener(this._frameManager, FrameManagerEvents.FrameDetached, this._onFrameDetached.bind(this)),+ helper.addEventListener(this._frameManager.networkManager(), NetworkManagerEvents.Request, this._onRequest.bind(this)),+ ];++ this._sameDocumentNavigationPromise = new Promise(fulfill => {+ this._sameDocumentNavigationCompleteCallback = fulfill;+ });++ this._lifecyclePromise = new Promise(fulfill => {+ this._lifecycleCallback = fulfill;+ });++ this._newDocumentNavigationPromise = new Promise(fulfill => {+ this._newDocumentNavigationCompleteCallback = fulfill;+ });++ this._timeoutPromise = this._createTimeoutPromise();+ this._terminationPromise = new Promise(fulfill => {+ this._terminationCallback = fulfill;+ });+ this._checkLifecycleComplete();+ }++ _onRequest(request: Request) {+ if (request.frame() !== this._frame || !request.isNavigationRequest())+ return;+ this._navigationRequest = request;+ }++ _onFrameDetached(frame: Frame) {+ if (this._frame === frame) {+ this._terminationCallback.call(null, new Error('Navigating frame was detached'));+ return;+ }+ this._checkLifecycleComplete();+ }++ navigationResponse(): Response | null {+ return this._navigationRequest ? this._navigationRequest.response() : null;+ }++ _terminate(error: Error) {+ this._terminationCallback.call(null, error);+ }++ sameDocumentNavigationPromise(): Promise<Error | null> {+ return this._sameDocumentNavigationPromise;+ }++ newDocumentNavigationPromise(): Promise<Error | null> {+ return this._newDocumentNavigationPromise;+ }++ lifecyclePromise(): Promise<any> {+ return this._lifecyclePromise;+ }++ timeoutOrTerminationPromise(): Promise<Error | null> {+ return Promise.race([this._timeoutPromise, this._terminationPromise]);+ }++ _createTimeoutPromise(): Promise<Error | null> {+ if (!this._timeout)+ return new Promise(() => {});+ const errorMessage = 'Navigation timeout of ' + this._timeout + ' ms exceeded';+ return new Promise(fulfill => this._maximumTimer = setTimeout(fulfill, this._timeout))+ .then(() => new TimeoutError(errorMessage));+ }++ _navigatedWithinDocument(frame: Frame) {+ if (frame !== this._frame)+ return;+ this._hasSameDocumentNavigation = true;+ this._checkLifecycleComplete();+ }++ _checkLifecycleComplete() {+ // We expect navigation to commit.+ if (!checkLifecycle(this._frame, this._expectedLifecycle))+ return;+ this._lifecycleCallback();+ if (this._frame._loaderId === this._initialLoaderId && !this._hasSameDocumentNavigation)+ return;+ if (this._hasSameDocumentNavigation)+ this._sameDocumentNavigationCompleteCallback();+ if (this._frame._loaderId !== this._initialLoaderId)+ this._newDocumentNavigationCompleteCallback();++ function checkLifecycle(frame: Frame, expectedLifecycle: string[]): boolean {+ for (const event of expectedLifecycle) {+ if (!frame._lifecycleEvents.has(event))+ return false;+ }+ for (const child of frame.childFrames()) {+ if (!checkLifecycle(child, expectedLifecycle))+ return false;+ }+ return true;+ }+ }++ dispose() {+ helper.removeEventListeners(this._eventListeners);+ clearTimeout(this._maximumTimer);+ }+}++const playwrightToProtocolLifecycle = new Map([+ ['load', 'load'],+ ['domcontentloaded', 'DOMContentLoaded'],+ ['networkidle0', 'networkIdle'],+ ['networkidle2', 'networkAlmostIdle'],+]);diff --git a/src/chromium/Multimap.ts b/src/chromium/Multimap.tsnew file mode 100644index 0000000000..835a28e592--- /dev/null+++ b/src/chromium/Multimap.ts@@ -0,0 +1,93 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export class Multimap<T, V> {+ private _map: Map<T, Set<V>>;++ constructor() {+ this._map = new Map();+ }++ set(key: T, value: V) {+ let set = this._map.get(key);+ if (!set) {+ set = new Set();+ this._map.set(key, set);+ }+ set.add(value);+ }++ get(key: T): Set<V> {+ let result = this._map.get(key);+ if (!result)+ result = new Set();+ return result;+ }++ has(key: T): boolean {+ return this._map.has(key);+ }++ hasValue(key: T, value: V): boolean {+ const set = this._map.get(key);+ if (!set)+ return false;+ return set.has(value);+ }++ get size(): number {+ return this._map.size;+ }++ delete(key: T, value: V): boolean {+ const values = this.get(key);+ const result = values.delete(value);+ if (!values.size)+ this._map.delete(key);+ return result;+ }++ deleteAll(key: T) {+ this._map.delete(key);+ }++ firstValue(key: T): V {+ const set = this._map.get(key);+ if (!set)+ return null;+ return set.values().next().value;+ }++ firstKey(): T {+ return this._map.keys().next().value;+ }++ valuesArray(): V[] {+ const result = [];+ for (const key of this._map.keys())+ result.push(...Array.from(this._map.get(key).values()));+ return result;+ }++ keysArray(): T[] {+ return Array.from(this._map.keys());+ }++ clear() {+ this._map.clear();+ }+}diff --git a/src/chromium/NetworkManager.ts b/src/chromium/NetworkManager.tsnew file mode 100644index 0000000000..00d1baeee7--- /dev/null+++ b/src/chromium/NetworkManager.ts@@ -0,0 +1,657 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { EventEmitter } from 'events';+import { CDPSession } from './Connection';+import { Frame } from './Frame';+import { FrameManager } from './FrameManager';+import { assert, debugError, helper } from '../helper';+import { Protocol } from './protocol';++export const NetworkManagerEvents = {+ Request: Symbol('Events.NetworkManager.Request'),+ Response: Symbol('Events.NetworkManager.Response'),+ RequestFailed: Symbol('Events.NetworkManager.RequestFailed'),+ RequestFinished: Symbol('Events.NetworkManager.RequestFinished'),+};++export class NetworkManager extends EventEmitter {+ private _client: CDPSession;+ private _ignoreHTTPSErrors: boolean;+ private _frameManager: FrameManager;+ private _requestIdToRequest = new Map<string, Request>();+ private _requestIdToRequestWillBeSentEvent = new Map<string, Protocol.Network.requestWillBeSentPayload>();+ private _extraHTTPHeaders: {[key: string]: string} = {};+ private _offline = false;+ private _credentials: {username: string, password: string} | null = null;+ private _attemptedAuthentications = new Set<string>();+ private _userRequestInterceptionEnabled = false;+ private _protocolRequestInterceptionEnabled = false;+ private _userCacheDisabled = false;+ private _requestIdToInterceptionId = new Map<string, string>();++ constructor(client: CDPSession, ignoreHTTPSErrors: boolean, frameManager: FrameManager) {+ super();+ this._client = client;+ this._ignoreHTTPSErrors = ignoreHTTPSErrors;+ this._frameManager = frameManager;++ this._client.on('Fetch.requestPaused', this._onRequestPaused.bind(this));+ this._client.on('Fetch.authRequired', this._onAuthRequired.bind(this));+ this._client.on('Network.requestWillBeSent', this._onRequestWillBeSent.bind(this));+ this._client.on('Network.requestServedFromCache', this._onRequestServedFromCache.bind(this));+ this._client.on('Network.responseReceived', this._onResponseReceived.bind(this));+ this._client.on('Network.loadingFinished', this._onLoadingFinished.bind(this));+ this._client.on('Network.loadingFailed', this._onLoadingFailed.bind(this));+ }++ async initialize() {+ await this._client.send('Network.enable');+ if (this._ignoreHTTPSErrors)+ await this._client.send('Security.setIgnoreCertificateErrors', {ignore: true});+ }++ async authenticate(credentials: { username: string; password: string; } | null) {+ this._credentials = credentials;+ await this._updateProtocolRequestInterception();+ }++ async setExtraHTTPHeaders(extraHTTPHeaders: { [s: string]: string; }) {+ this._extraHTTPHeaders = {};+ for (const key of Object.keys(extraHTTPHeaders)) {+ const value = extraHTTPHeaders[key];+ assert(helper.isString(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);+ this._extraHTTPHeaders[key.toLowerCase()] = value;+ }+ await this._client.send('Network.setExtraHTTPHeaders', { headers: this._extraHTTPHeaders });+ }++ extraHTTPHeaders(): { [s: string]: string; } {+ return Object.assign({}, this._extraHTTPHeaders);+ }++ async setOfflineMode(value: boolean) {+ if (this._offline === value)+ return;+ this._offline = value;+ await this._client.send('Network.emulateNetworkConditions', {+ offline: this._offline,+ // values of 0 remove any active throttling. crbug.com/456324#c9+ latency: 0,+ downloadThroughput: -1,+ uploadThroughput: -1+ });+ }++ async setUserAgent(userAgent: string) {+ await this._client.send('Network.setUserAgentOverride', { userAgent });+ }++ async setCacheEnabled(enabled: boolean) {+ this._userCacheDisabled = !enabled;+ await this._updateProtocolCacheDisabled();+ }++ async setRequestInterception(value: boolean) {+ this._userRequestInterceptionEnabled = value;+ await this._updateProtocolRequestInterception();+ }++ async _updateProtocolRequestInterception() {+ const enabled = this._userRequestInterceptionEnabled || !!this._credentials;+ if (enabled === this._protocolRequestInterceptionEnabled)+ return;+ this._protocolRequestInterceptionEnabled = enabled;+ if (enabled) {+ await Promise.all([+ this._updateProtocolCacheDisabled(),+ this._client.send('Fetch.enable', {+ handleAuthRequests: true,+ patterns: [{urlPattern: '*'}],+ }),+ ]);+ } else {+ await Promise.all([+ this._updateProtocolCacheDisabled(),+ this._client.send('Fetch.disable')+ ]);+ }+ }++ async _updateProtocolCacheDisabled() {+ await this._client.send('Network.setCacheDisabled', {+ cacheDisabled: this._userCacheDisabled || this._protocolRequestInterceptionEnabled+ });+ }++ _onRequestWillBeSent(event: Protocol.Network.requestWillBeSentPayload) {+ // Request interception doesn't happen for data URLs with Network Service.+ if (this._protocolRequestInterceptionEnabled && !event.request.url.startsWith('data:')) {+ const requestId = event.requestId;+ const interceptionId = this._requestIdToInterceptionId.get(requestId);+ if (interceptionId) {+ this._onRequest(event, interceptionId);+ this._requestIdToInterceptionId.delete(requestId);+ } else {+ this._requestIdToRequestWillBeSentEvent.set(event.requestId, event);+ }+ return;+ }+ this._onRequest(event, null);+ }++ _onAuthRequired(event: Protocol.Fetch.authRequiredPayload) {+ let response: 'Default' | 'CancelAuth' | 'ProvideCredentials' = 'Default';+ if (this._attemptedAuthentications.has(event.requestId)) {+ response = 'CancelAuth';+ } else if (this._credentials) {+ response = 'ProvideCredentials';+ this._attemptedAuthentications.add(event.requestId);+ }+ const {username, password} = this._credentials || {username: undefined, password: undefined};+ this._client.send('Fetch.continueWithAuth', {+ requestId: event.requestId,+ authChallengeResponse: { response, username, password },+ }).catch(debugError);+ }++ _onRequestPaused(event: Protocol.Fetch.requestPausedPayload) {+ if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) {+ this._client.send('Fetch.continueRequest', {+ requestId: event.requestId+ }).catch(debugError);+ }++ const requestId = event.networkId;+ const interceptionId = event.requestId;+ if (requestId && this._requestIdToRequestWillBeSentEvent.has(requestId)) {+ const requestWillBeSentEvent = this._requestIdToRequestWillBeSentEvent.get(requestId);+ this._onRequest(requestWillBeSentEvent, interceptionId);+ this._requestIdToRequestWillBeSentEvent.delete(requestId);+ } else {+ this._requestIdToInterceptionId.set(requestId, interceptionId);+ }+ }++ _onRequest(event: Protocol.Network.requestWillBeSentPayload, interceptionId: string | null) {+ let redirectChain = [];+ if (event.redirectResponse) {+ const request = this._requestIdToRequest.get(event.requestId);+ // If we connect late to the target, we could have missed the requestWillBeSent event.+ if (request) {+ this._handleRequestRedirect(request, event.redirectResponse);+ redirectChain = request._redirectChain;+ }+ }+ const frame = event.frameId ? this._frameManager.frame(event.frameId) : null;+ const request = new Request(this._client, frame, interceptionId, this._userRequestInterceptionEnabled, event, redirectChain);+ this._requestIdToRequest.set(event.requestId, request);+ this.emit(NetworkManagerEvents.Request, request);+ }+++ _onRequestServedFromCache(event: Protocol.Network.requestServedFromCachePayload) {+ const request = this._requestIdToRequest.get(event.requestId);+ if (request)+ request._fromMemoryCache = true;+ }++ _handleRequestRedirect(request: Request, responsePayload: Protocol.Network.Response) {+ const response = new Response(this._client, request, responsePayload);+ request._response = response;+ request._redirectChain.push(request);+ response._bodyLoadedPromiseFulfill.call(null, new Error('Response body is unavailable for redirect responses'));+ this._requestIdToRequest.delete(request._requestId);+ this._attemptedAuthentications.delete(request._interceptionId);+ this.emit(NetworkManagerEvents.Response, response);+ this.emit(NetworkManagerEvents.RequestFinished, request);+ }++ _onResponseReceived(event: Protocol.Network.responseReceivedPayload) {+ const request = this._requestIdToRequest.get(event.requestId);+ // FileUpload sends a response without a matching request.+ if (!request)+ return;+ const response = new Response(this._client, request, event.response);+ request._response = response;+ this.emit(NetworkManagerEvents.Response, response);+ }++ _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) {+ const request = this._requestIdToRequest.get(event.requestId);+ // For certain requestIds we never receive requestWillBeSent event.+ // @see https://crbug.com/750469+ if (!request)+ return;++ // Under certain conditions we never get the Network.responseReceived+ // event from protocol. @see https://crbug.com/883475+ if (request.response())+ request.response()._bodyLoadedPromiseFulfill.call(null);+ this._requestIdToRequest.delete(request._requestId);+ this._attemptedAuthentications.delete(request._interceptionId);+ this.emit(NetworkManagerEvents.RequestFinished, request);+ }++ _onLoadingFailed(event: Protocol.Network.loadingFailedPayload) {+ const request = this._requestIdToRequest.get(event.requestId);+ // For certain requestIds we never receive requestWillBeSent event.+ // @see https://crbug.com/750469+ if (!request)+ return;+ request._failureText = event.errorText;+ const response = request.response();+ if (response)+ response._bodyLoadedPromiseFulfill.call(null);+ this._requestIdToRequest.delete(request._requestId);+ this._attemptedAuthentications.delete(request._interceptionId);+ this.emit(NetworkManagerEvents.RequestFailed, request);+ }+}++export class Request {+ _response: Response | null = null;+ _redirectChain: Request[];+ _requestId: string;+ _interceptionId: string;+ private _client: CDPSession;+ private _isNavigationRequest: boolean;+ private _allowInterception: boolean;+ private _interceptionHandled = false;+ _failureText: string | null = null;+ private _url: string;+ private _resourceType: string;+ private _method: string;+ private _postData: string;+ private _headers: {[key: string]: string} = {};+ private _frame: Frame;+ _fromMemoryCache = false;++ constructor(client: CDPSession, frame: Frame | null, interceptionId: string, allowInterception: boolean, event: Protocol.Network.requestWillBeSentPayload, redirectChain: Request[]) {+ this._client = client;+ this._requestId = event.requestId;+ this._isNavigationRequest = event.requestId === event.loaderId && event.type === 'Document';+ this._interceptionId = interceptionId;+ this._allowInterception = allowInterception;++ this._url = event.request.url;+ this._resourceType = event.type.toLowerCase();+ this._method = event.request.method;+ this._postData = event.request.postData;+ this._frame = frame;+ this._redirectChain = redirectChain;+ for (const key of Object.keys(event.request.headers))+ this._headers[key.toLowerCase()] = event.request.headers[key];+ }++ url(): string {+ return this._url;+ }++ resourceType(): string {+ return this._resourceType;+ }++ method(): string {+ return this._method;+ }++ postData(): string | undefined {+ return this._postData;+ }++ headers(): {[key: string]: string} {+ return this._headers;+ }++ response(): Response | null {+ return this._response;+ }++ frame(): Frame | null {+ return this._frame;+ }++ isNavigationRequest(): boolean {+ return this._isNavigationRequest;+ }++ redirectChain(): Request[] {+ return this._redirectChain.slice();+ }++ failure(): { errorText: string; } | null {+ if (!this._failureText)+ return null;+ return {+ errorText: this._failureText+ };+ }++ async continue(overrides: { url?: string; method?: string; postData?: string; headers?: {[key: string]: string}; } = {}) {+ // Request interception is not supported for data: urls.+ if (this._url.startsWith('data:'))+ return;+ assert(this._allowInterception, 'Request Interception is not enabled!');+ assert(!this._interceptionHandled, 'Request is already handled!');+ const {+ url,+ method,+ postData,+ headers+ } = overrides;+ this._interceptionHandled = true;+ await this._client.send('Fetch.continueRequest', {+ requestId: this._interceptionId,+ url,+ method,+ postData,+ headers: headers ? headersArray(headers) : undefined,+ }).catch(error => {+ // In certain cases, protocol will return error if the request was already canceled+ // or the page was closed. We should tolerate these errors.+ debugError(error);+ });+ }++ async respond(response: { status: number; headers: {[key: string]: string}; contentType: string; body: (string | Buffer); }) {+ // Mocking responses for dataURL requests is not currently supported.+ if (this._url.startsWith('data:'))+ return;+ assert(this._allowInterception, 'Request Interception is not enabled!');+ assert(!this._interceptionHandled, 'Request is already handled!');+ this._interceptionHandled = true;++ const responseBody = response.body && helper.isString(response.body) ? Buffer.from(/** @type {string} */(response.body)) : /** @type {?Buffer} */(response.body || null);++ const responseHeaders: { [s: string]: string; } = {};+ if (response.headers) {+ for (const header of Object.keys(response.headers))+ responseHeaders[header.toLowerCase()] = response.headers[header];+ }+ if (response.contentType)+ responseHeaders['content-type'] = response.contentType;+ if (responseBody && !('content-length' in responseHeaders))+ responseHeaders['content-length'] = String(Buffer.byteLength(responseBody));++ await this._client.send('Fetch.fulfillRequest', {+ requestId: this._interceptionId,+ responseCode: response.status || 200,+ responsePhrase: STATUS_TEXTS[response.status || 200],+ responseHeaders: headersArray(responseHeaders),+ body: responseBody ? responseBody.toString('base64') : undefined,+ }).catch(error => {+ // In certain cases, protocol will return error if the request was already canceled+ // or the page was closed. We should tolerate these errors.+ debugError(error);+ });+ }++ async abort(errorCode: string = 'failed') {+ // Request interception is not supported for data: urls.+ if (this._url.startsWith('data:'))+ return;+ const errorReason = errorReasons[errorCode];+ assert(errorReason, 'Unknown error code: ' + errorCode);+ assert(this._allowInterception, 'Request Interception is not enabled!');+ assert(!this._interceptionHandled, 'Request is already handled!');+ this._interceptionHandled = true;+ await this._client.send('Fetch.failRequest', {+ requestId: this._interceptionId,+ errorReason+ }).catch(error => {+ // In certain cases, protocol will return error if the request was already canceled+ // or the page was closed. We should tolerate these errors.+ debugError(error);+ });+ }+}++const errorReasons = {+ 'aborted': 'Aborted',+ 'accessdenied': 'AccessDenied',+ 'addressunreachable': 'AddressUnreachable',+ 'blockedbyclient': 'BlockedByClient',+ 'blockedbyresponse': 'BlockedByResponse',+ 'connectionaborted': 'ConnectionAborted',+ 'connectionclosed': 'ConnectionClosed',+ 'connectionfailed': 'ConnectionFailed',+ 'connectionrefused': 'ConnectionRefused',+ 'connectionreset': 'ConnectionReset',+ 'internetdisconnected': 'InternetDisconnected',+ 'namenotresolved': 'NameNotResolved',+ 'timedout': 'TimedOut',+ 'failed': 'Failed',+};++export class Response {+ _bodyLoadedPromiseFulfill: any;+ private _client: CDPSession;+ private _request: Request;+ private _contentPromise: Promise<Buffer> | null = null;+ private _bodyLoadedPromise: Promise<Error | null>;+ private _remoteAddress: { ip: string; port: number; };+ private _status: number;+ private _statusText: string;+ private _url: string;+ private _fromDiskCache: boolean;+ private _fromServiceWorker: boolean;+ private _headers: {[key: string]: string} = {};+ private _securityDetails: SecurityDetails;++ constructor(client: CDPSession, request: Request, responsePayload: Protocol.Network.Response) {+ this._client = client;+ this._request = request;++ this._bodyLoadedPromise = new Promise(fulfill => {+ this._bodyLoadedPromiseFulfill = fulfill;+ });++ this._remoteAddress = {+ ip: responsePayload.remoteIPAddress,+ port: responsePayload.remotePort,+ };+ this._status = responsePayload.status;+ this._statusText = responsePayload.statusText;+ this._url = request.url();+ this._fromDiskCache = !!responsePayload.fromDiskCache;+ this._fromServiceWorker = !!responsePayload.fromServiceWorker;+ for (const key of Object.keys(responsePayload.headers))+ this._headers[key.toLowerCase()] = responsePayload.headers[key];+ this._securityDetails = responsePayload.securityDetails ? new SecurityDetails(responsePayload.securityDetails) : null;+ }++ remoteAddress(): { ip: string; port: number; } {+ return this._remoteAddress;+ }++ url(): string {+ return this._url;+ }++ ok(): boolean {+ return this._status === 0 || (this._status >= 200 && this._status <= 299);+ }++ status(): number {+ return this._status;+ }++ statusText(): string {+ return this._statusText;+ }++ headers(): object {+ return this._headers;+ }++ securityDetails(): SecurityDetails | null {+ return this._securityDetails;+ }++ buffer(): Promise<Buffer> {+ if (!this._contentPromise) {+ this._contentPromise = this._bodyLoadedPromise.then(async error => {+ if (error)+ throw error;+ const response = await this._client.send('Network.getResponseBody', {+ requestId: this._request._requestId+ });+ return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');+ });+ }+ return this._contentPromise;+ }++ async text(): Promise<string> {+ const content = await this.buffer();+ return content.toString('utf8');+ }++ async json(): Promise<object> {+ const content = await this.text();+ return JSON.parse(content);+ }++ request(): Request {+ return this._request;+ }++ fromCache(): boolean {+ return this._fromDiskCache || this._request._fromMemoryCache;+ }++ fromServiceWorker(): boolean {+ return this._fromServiceWorker;+ }++ frame(): Frame | null {+ return this._request.frame();+ }+}++export class SecurityDetails {+ private _subjectName: string;+ private _issuer: string;+ private _validFrom: number;+ private _validTo: number;+ private _protocol: string;++ constructor(securityPayload: Protocol.Network.SecurityDetails) {+ this._subjectName = securityPayload['subjectName'];+ this._issuer = securityPayload['issuer'];+ this._validFrom = securityPayload['validFrom'];+ this._validTo = securityPayload['validTo'];+ this._protocol = securityPayload['protocol'];+ }++ subjectName(): string {+ return this._subjectName;+ }++ issuer(): string {+ return this._issuer;+ }++ validFrom(): number {+ return this._validFrom;+ }++ validTo(): number {+ return this._validTo;+ }++ protocol(): string {+ return this._protocol;+ }+}++function headersArray(headers: { [s: string]: string; }): { name: string; value: string; }[] {+ const result = [];+ for (const name in headers) {+ if (!Object.is(headers[name], undefined))+ result.push({name, value: headers[name] + ''});+ }+ return result;+}++// List taken from https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml with extra 306 and 418 codes.+const STATUS_TEXTS = {+ '100': 'Continue',+ '101': 'Switching Protocols',+ '102': 'Processing',+ '103': 'Early Hints',+ '200': 'OK',+ '201': 'Created',+ '202': 'Accepted',+ '203': 'Non-Authoritative Information',+ '204': 'No Content',+ '205': 'Reset Content',+ '206': 'Partial Content',+ '207': 'Multi-Status',+ '208': 'Already Reported',+ '226': 'IM Used',+ '300': 'Multiple Choices',+ '301': 'Moved Permanently',+ '302': 'Found',+ '303': 'See Other',+ '304': 'Not Modified',+ '305': 'Use Proxy',+ '306': 'Switch Proxy',+ '307': 'Temporary Redirect',+ '308': 'Permanent Redirect',+ '400': 'Bad Request',+ '401': 'Unauthorized',+ '402': 'Payment Required',+ '403': 'Forbidden',+ '404': 'Not Found',+ '405': 'Method Not Allowed',+ '406': 'Not Acceptable',+ '407': 'Proxy Authentication Required',+ '408': 'Request Timeout',+ '409': 'Conflict',+ '410': 'Gone',+ '411': 'Length Required',+ '412': 'Precondition Failed',+ '413': 'Payload Too Large',+ '414': 'URI Too Long',+ '415': 'Unsupported Media Type',+ '416': 'Range Not Satisfiable',+ '417': 'Expectation Failed',+ '418': 'I\'m a teapot',+ '421': 'Misdirected Request',+ '422': 'Unprocessable Entity',+ '423': 'Locked',+ '424': 'Failed Dependency',+ '425': 'Too Early',+ '426': 'Upgrade Required',+ '428': 'Precondition Required',+ '429': 'Too Many Requests',+ '431': 'Request Header Fields Too Large',+ '451': 'Unavailable For Legal Reasons',+ '500': 'Internal Server Error',+ '501': 'Not Implemented',+ '502': 'Bad Gateway',+ '503': 'Service Unavailable',+ '504': 'Gateway Timeout',+ '505': 'HTTP Version Not Supported',+ '506': 'Variant Also Negotiates',+ '507': 'Insufficient Storage',+ '508': 'Loop Detected',+ '510': 'Not Extended',+ '511': 'Network Authentication Required',+};diff --git a/src/chromium/Page.ts b/src/chromium/Page.tsnew file mode 100644index 0000000000..13a85ba543--- /dev/null+++ b/src/chromium/Page.ts@@ -0,0 +1,1073 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { EventEmitter } from 'events';+import * as fs from 'fs';+import * as mime from 'mime';+import * as path from 'path';+import { Accessibility } from './Accessibility';+import { CDPSession, CDPSessionEvents, Connection } from './Connection';+import { Coverage } from './Coverage';+import { Dialog, DialogType } from './Dialog';+import { EmulationManager } from './EmulationManager';+import { Events } from '../Events';+import { Frame } from './Frame';+import { FrameManager, FrameManagerEvents } from './FrameManager';+import { assert, debugError, helper } from '../helper';+import { readProtocolStream, releaseObject, getExceptionMessage, valueFromRemoteObject } from './protocolHelper';+import { Keyboard, Mouse, Touchscreen } from './Input';+import { createJSHandle, ElementHandle, JSHandle, ClickOptions, PointerActionOptions, MultiClickOptions } from './JSHandle';+import { Response, NetworkManagerEvents } from './NetworkManager';+import { TaskQueue } from './TaskQueue';+import { TimeoutSettings } from '../TimeoutSettings';+import { Tracing } from './Tracing';+import { Worker } from './Worker';+import { Target } from './Target';+import { Browser } from './Browser';+import { BrowserContext } from './BrowserContext';+import { Protocol } from './protocol';++const writeFileAsync = helper.promisify(fs.writeFile);++export type Viewport = {+ width: number;+ height: number;+ deviceScaleFactor?: number;+ isMobile?: boolean;+ isLandscape?: boolean;+ hasTouch?: boolean;+}++export class Page extends EventEmitter {+ private _closed = false;+ private _client: CDPSession;+ private _target: Target;+ private _keyboard: Keyboard;+ private _mouse: Mouse;+ private _timeoutSettings: TimeoutSettings;+ private _touchscreen: Touchscreen;+ private _accessibility: Accessibility;+ private _frameManager: FrameManager;+ private _emulationManager: EmulationManager;+ private _tracing: Tracing;+ private _pageBindings = new Map<string, Function>();+ private _coverage: Coverage;+ _javascriptEnabled = true;+ private _viewport: Viewport | null = null;+ private _screenshotTaskQueue: TaskQueue;+ private _workers = new Map<string, Worker>();+ private _fileChooserInterceptionIsDisabled = false;+ private _fileChooserInterceptors = new Set<(chooser: FileChooser) => void>();+ private _disconnectPromise: Promise<Error> | undefined;++ static async create(client: CDPSession, target: Target, ignoreHTTPSErrors: boolean, defaultViewport: Viewport | null, screenshotTaskQueue: TaskQueue): Promise<Page> {+ const page = new Page(client, target, ignoreHTTPSErrors, screenshotTaskQueue);+ await page._initialize();+ if (defaultViewport)+ await page.setViewport(defaultViewport);+ return page;+ }++ constructor(client: CDPSession, target: Target, ignoreHTTPSErrors: boolean, screenshotTaskQueue: TaskQueue) {+ super();+ this._client = client;+ this._target = target;+ this._keyboard = new Keyboard(client);+ this._mouse = new Mouse(client, this._keyboard);+ this._timeoutSettings = new TimeoutSettings();+ this._touchscreen = new Touchscreen(client, this._keyboard);+ this._accessibility = new Accessibility(client);+ this._frameManager = new FrameManager(client, this, ignoreHTTPSErrors, this._timeoutSettings);+ this._emulationManager = new EmulationManager(client);+ this._tracing = new Tracing(client);+ this._coverage = new Coverage(client);++ this._screenshotTaskQueue = screenshotTaskQueue;++ client.on('Target.attachedToTarget', event => {+ if (event.targetInfo.type !== 'worker') {+ // If we don't detach from service workers, they will never die.+ client.send('Target.detachFromTarget', {+ sessionId: event.sessionId+ }).catch(debugError);+ return;+ }+ const session = Connection.fromSession(client).session(event.sessionId);+ const worker = new Worker(session, event.targetInfo.url, this._addConsoleMessage.bind(this), this._handleException.bind(this));+ this._workers.set(event.sessionId, worker);+ this.emit(Events.Page.WorkerCreated, worker);+ });+ client.on('Target.detachedFromTarget', event => {+ const worker = this._workers.get(event.sessionId);+ if (!worker)+ return;+ this.emit(Events.Page.WorkerDestroyed, worker);+ this._workers.delete(event.sessionId);+ });++ this._frameManager.on(FrameManagerEvents.FrameAttached, event => this.emit(Events.Page.FrameAttached, event));+ this._frameManager.on(FrameManagerEvents.FrameDetached, event => this.emit(Events.Page.FrameDetached, event));+ this._frameManager.on(FrameManagerEvents.FrameNavigated, event => this.emit(Events.Page.FrameNavigated, event));++ const networkManager = this._frameManager.networkManager();+ networkManager.on(NetworkManagerEvents.Request, event => this.emit(Events.Page.Request, event));+ networkManager.on(NetworkManagerEvents.Response, event => this.emit(Events.Page.Response, event));+ networkManager.on(NetworkManagerEvents.RequestFailed, event => this.emit(Events.Page.RequestFailed, event));+ networkManager.on(NetworkManagerEvents.RequestFinished, event => this.emit(Events.Page.RequestFinished, event));++ client.on('Page.domContentEventFired', event => this.emit(Events.Page.DOMContentLoaded));+ client.on('Page.loadEventFired', event => this.emit(Events.Page.Load));+ client.on('Runtime.consoleAPICalled', event => this._onConsoleAPI(event));+ client.on('Runtime.bindingCalled', event => this._onBindingCalled(event));+ client.on('Page.javascriptDialogOpening', event => this._onDialog(event));+ client.on('Runtime.exceptionThrown', exception => this._handleException(exception.exceptionDetails));+ client.on('Inspector.targetCrashed', event => this._onTargetCrashed());+ client.on('Performance.metrics', event => this._emitMetrics(event));+ client.on('Log.entryAdded', event => this._onLogEntryAdded(event));+ client.on('Page.fileChooserOpened', event => this._onFileChooser(event));+ this._target._isClosedPromise.then(() => {+ this.emit(Events.Page.Close);+ this._closed = true;+ });+ }++ async _initialize() {+ await Promise.all([+ this._frameManager.initialize(),+ this._client.send('Target.setAutoAttach', {autoAttach: true, waitForDebuggerOnStart: false, flatten: true}),+ this._client.send('Performance.enable', {}),+ this._client.send('Log.enable', {}),+ this._client.send('Page.setInterceptFileChooserDialog', {enabled: true}).catch(e => {+ this._fileChooserInterceptionIsDisabled = true;+ }),+ ]);+ }++ _onFileChooser(event: Protocol.Page.fileChooserOpenedPayload) {+ if (!this._fileChooserInterceptors.size) {+ this._client.send('Page.handleFileChooser', { action: 'fallback' }).catch(debugError);+ return;+ }+ const interceptors = Array.from(this._fileChooserInterceptors);+ this._fileChooserInterceptors.clear();+ const fileChooser = new FileChooser(this._client, event);+ for (const interceptor of interceptors)+ interceptor.call(null, fileChooser);+ }++ async waitForFileChooser(options: { timeout?: number; } = {}): Promise<FileChooser> {+ if (this._fileChooserInterceptionIsDisabled)+ throw new Error('File chooser handling does not work with multiple connections to the same page');+ const {+ timeout = this._timeoutSettings.timeout(),+ } = options;+ let callback;+ const promise = new Promise<FileChooser>(x => callback = x);+ this._fileChooserInterceptors.add(callback);+ return helper.waitWithTimeout<FileChooser>(promise, 'waiting for file chooser', timeout).catch(e => {+ this._fileChooserInterceptors.delete(callback);+ throw e;+ });+ }++ async setGeolocation(options: { longitude: number; latitude: number; accuracy: (number | undefined); }) {+ const { longitude, latitude, accuracy = 0} = options;+ if (longitude < -180 || longitude > 180)+ throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);+ if (latitude < -90 || latitude > 90)+ throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`);+ if (accuracy < 0)+ throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);+ await this._client.send('Emulation.setGeolocationOverride', {longitude, latitude, accuracy});+ }++ target(): Target {+ return this._target;+ }++ browser(): Browser {+ return this._target.browser();+ }++ browserContext(): BrowserContext {+ return this._target.browserContext();+ }++ _onTargetCrashed() {+ this.emit('error', new Error('Page crashed!'));+ }++ _onLogEntryAdded(event: Protocol.Log.entryAddedPayload) {+ const {level, text, args, source, url, lineNumber} = event.entry;+ if (args)+ args.map(arg => releaseObject(this._client, arg));+ if (source !== 'worker')+ this.emit(Events.Page.Console, new ConsoleMessage(level, text, [], {url, lineNumber}));+ }++ mainFrame(): Frame {+ return this._frameManager.mainFrame();+ }++ get keyboard(): Keyboard {+ return this._keyboard;+ }++ get touchscreen(): Touchscreen {+ return this._touchscreen;+ }++ get coverage(): Coverage {+ return this._coverage;+ }++ get tracing(): Tracing {+ return this._tracing;+ }++ get accessibility(): Accessibility {+ return this._accessibility;+ }++ frames(): Frame[] {+ return this._frameManager.frames();+ }++ workers(): Worker[] {+ return Array.from(this._workers.values());+ }++ async setRequestInterception(value: boolean) {+ return this._frameManager.networkManager().setRequestInterception(value);+ }++ setOfflineMode(enabled: boolean) {+ return this._frameManager.networkManager().setOfflineMode(enabled);+ }++ setDefaultNavigationTimeout(timeout: number) {+ this._timeoutSettings.setDefaultNavigationTimeout(timeout);+ }++ setDefaultTimeout(timeout: number) {+ this._timeoutSettings.setDefaultTimeout(timeout);+ }++ async $(selector: string): Promise<ElementHandle | null> {+ return this.mainFrame().$(selector);+ }++ async evaluateHandle(pageFunction: Function | string, ...args: any[]): Promise<JSHandle> {+ const context = await this.mainFrame().executionContext();+ return context.evaluateHandle(pageFunction, ...args);+ }++ async queryObjects(prototypeHandle: JSHandle): Promise<JSHandle> {+ const context = await this.mainFrame().executionContext();+ return context.queryObjects(prototypeHandle);+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<(object | undefined)> {+ return this.mainFrame().$eval(selector, pageFunction, ...args);+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<(object | undefined)> {+ return this.mainFrame().$$eval(selector, pageFunction, ...args);+ }++ async $$(selector: string): Promise<ElementHandle[]> {+ return this.mainFrame().$$(selector);+ }++ async $x(expression: string): Promise<ElementHandle[]> {+ return this.mainFrame().$x(expression);+ }++ async cookies(...urls: string[]): Promise<NetworkCookie[]> {+ const {cookies} = await this._client.send('Network.getCookies', {+ urls: urls.length ? urls : [this.url()]+ });+ // Chromiums's cookies are missing sameSite when it is 'None'+ return cookies.map(cookie => ({sameSite: 'None', ...cookie}));+ }++ async deleteCookie(...cookies: Protocol.Network.deleteCookiesParameters[]) {+ const pageURL = this.url();+ for (const cookie of cookies) {+ const item = Object.assign({}, cookie);+ if (!cookie.url && pageURL.startsWith('http'))+ item.url = pageURL;+ await this._client.send('Network.deleteCookies', item);+ }+ }++ async setCookie(...cookies: NetworkCookieParam[]) {+ const pageURL = this.url();+ const startsWithHTTP = pageURL.startsWith('http');+ const items = cookies.map(cookie => {+ const item = Object.assign({}, cookie);+ if (!item.url && startsWithHTTP)+ item.url = pageURL;+ assert(item.url !== 'about:blank', `Blank page can not have cookie "${item.name}"`);+ assert(!String.prototype.startsWith.call(item.url || '', 'data:'), `Data URL page can not have cookie "${item.name}"`);+ return item;+ });+ await this.deleteCookie(...items);+ if (items.length)+ await this._client.send('Network.setCookies', { cookies: items });+ }++ async addScriptTag(options: { url?: string; path?: string; content?: string; type?: string; }): Promise<ElementHandle> {+ return this.mainFrame().addScriptTag(options);+ }++ async addStyleTag(options: { url?: string; path?: string; content?: string; }): Promise<ElementHandle> {+ return this.mainFrame().addStyleTag(options);+ }++ async exposeFunction(name: string, playwrightFunction: Function) {+ if (this._pageBindings.has(name))+ throw new Error(`Failed to add page binding with name ${name}: window['${name}'] already exists!`);+ this._pageBindings.set(name, playwrightFunction);++ const expression = helper.evaluationString(addPageBinding, name);+ await this._client.send('Runtime.addBinding', {name: name});+ await this._client.send('Page.addScriptToEvaluateOnNewDocument', {source: expression});+ await Promise.all(this.frames().map(frame => frame.evaluate(expression).catch(debugError)));++ function addPageBinding(bindingName: string) {+ const binding = window[bindingName];+ window[bindingName] = (...args) => {+ const me = window[bindingName];+ let callbacks = me['callbacks'];+ if (!callbacks) {+ callbacks = new Map();+ me['callbacks'] = callbacks;+ }+ const seq = (me['lastSeq'] || 0) + 1;+ me['lastSeq'] = seq;+ const promise = new Promise((resolve, reject) => callbacks.set(seq, {resolve, reject}));+ binding(JSON.stringify({name: bindingName, seq, args}));+ return promise;+ };+ }+ }++ async authenticate(credentials: { username: string; password: string; } | null) {+ return this._frameManager.networkManager().authenticate(credentials);+ }++ async setExtraHTTPHeaders(headers: { [s: string]: string; }) {+ return this._frameManager.networkManager().setExtraHTTPHeaders(headers);+ }++ async setUserAgent(userAgent: string) {+ return this._frameManager.networkManager().setUserAgent(userAgent);+ }++ async metrics(): Promise<Metrics> {+ const response = await this._client.send('Performance.getMetrics');+ return this._buildMetricsObject(response.metrics);+ }++ _emitMetrics(event: Protocol.Performance.metricsPayload) {+ this.emit(Events.Page.Metrics, {+ title: event.title,+ metrics: this._buildMetricsObject(event.metrics)+ });+ }++ _buildMetricsObject(metrics: Protocol.Performance.Metric[] | null): Metrics {+ const result = {};+ for (const metric of metrics || []) {+ if (supportedMetrics.has(metric.name))+ result[metric.name] = metric.value;+ }+ return result;+ }++ _handleException(exceptionDetails: Protocol.Runtime.ExceptionDetails) {+ const message = getExceptionMessage(exceptionDetails);+ const err = new Error(message);+ err.stack = ''; // Don't report clientside error with a node stack attached+ this.emit(Events.Page.PageError, err);+ }++ async _onConsoleAPI(event: Protocol.Runtime.consoleAPICalledPayload) {+ if (event.executionContextId === 0) {+ // DevTools protocol stores the last 1000 console messages. These+ // messages are always reported even for removed execution contexts. In+ // this case, they are marked with executionContextId = 0 and are+ // reported upon enabling Runtime agent.+ //+ // Ignore these messages since:+ // - there's no execution context we can use to operate with message+ // arguments+ // - these messages are reported before Playwright clients can subscribe+ // to the 'console'+ // page event.+ //+ // @see https://github.com/GoogleChrome/puppeteer/issues/3865+ return;+ }+ const context = this._frameManager.executionContextById(event.executionContextId);+ const values = event.args.map(arg => createJSHandle(context, arg));+ this._addConsoleMessage(event.type, values, event.stackTrace);+ }++ async _onBindingCalled(event: Protocol.Runtime.bindingCalledPayload) {+ const {name, seq, args} = JSON.parse(event.payload);+ let expression = null;+ try {+ const result = await this._pageBindings.get(name)(...args);+ expression = helper.evaluationString(deliverResult, name, seq, result);+ } catch (error) {+ if (error instanceof Error)+ expression = helper.evaluationString(deliverError, name, seq, error.message, error.stack);+ else+ expression = helper.evaluationString(deliverErrorValue, name, seq, error);+ }+ this._client.send('Runtime.evaluate', { expression, contextId: event.executionContextId }).catch(debugError);++ function deliverResult(name: string, seq: number, result: any) {+ window[name]['callbacks'].get(seq).resolve(result);+ window[name]['callbacks'].delete(seq);+ }++ function deliverError(name: string, seq: number, message: string, stack: string) {+ const error = new Error(message);+ error.stack = stack;+ window[name]['callbacks'].get(seq).reject(error);+ window[name]['callbacks'].delete(seq);+ }++ function deliverErrorValue(name: string, seq: number, value: any) {+ window[name]['callbacks'].get(seq).reject(value);+ window[name]['callbacks'].delete(seq);+ }+ }++ _addConsoleMessage(type: string, args: JSHandle[], stackTrace: Protocol.Runtime.StackTrace | undefined) {+ if (!this.listenerCount(Events.Page.Console)) {+ args.forEach(arg => arg.dispose());+ return;+ }+ const textTokens = [];+ for (const arg of args) {+ const remoteObject = arg._remoteObject;+ if (remoteObject.objectId)+ textTokens.push(arg.toString());+ else+ textTokens.push(valueFromRemoteObject(remoteObject));+ }+ const location = stackTrace && stackTrace.callFrames.length ? {+ url: stackTrace.callFrames[0].url,+ lineNumber: stackTrace.callFrames[0].lineNumber,+ columnNumber: stackTrace.callFrames[0].columnNumber,+ } : {};+ const message = new ConsoleMessage(type, textTokens.join(' '), args, location);+ this.emit(Events.Page.Console, message);+ }++ _onDialog(event) {+ let dialogType = null;+ if (event.type === 'alert')+ dialogType = DialogType.Alert;+ else if (event.type === 'confirm')+ dialogType = DialogType.Confirm;+ else if (event.type === 'prompt')+ dialogType = DialogType.Prompt;+ else if (event.type === 'beforeunload')+ dialogType = DialogType.BeforeUnload;+ assert(dialogType, 'Unknown javascript dialog type: ' + event.type);+ const dialog = new Dialog(this._client, dialogType, event.message, event.defaultPrompt);+ this.emit(Events.Page.Dialog, dialog);+ }++ url(): string {+ return this.mainFrame().url();+ }++ async content(): Promise<string> {+ return await this._frameManager.mainFrame().content();+ }++ async setContent(html: string, options: { timeout?: number; waitUntil?: string | string[]; } | undefined) {+ await this._frameManager.mainFrame().setContent(html, options);+ }++ async goto(url: string, options: { referer?: string; timeout?: number; waitUntil?: string | string[]; } | undefined): Promise<Response | null> {+ return await this._frameManager.mainFrame().goto(url, options);+ }++ async reload(options: { timeout?: number; waitUntil?: string | string[]; } = {}): Promise<Response | null> {+ const [response] = await Promise.all([+ this.waitForNavigation(options),+ this._client.send('Page.reload')+ ]);+ return response;+ }++ async waitForNavigation(options: { timeout?: number; waitUntil?: string | string[]; } = {}): Promise<Response | null> {+ return await this._frameManager.mainFrame().waitForNavigation(options);+ }++ _sessionClosePromise() {+ if (!this._disconnectPromise)+ this._disconnectPromise = new Promise(fulfill => this._client.once(CDPSessionEvents.Disconnected, () => fulfill(new Error('Target closed'))));+ return this._disconnectPromise;+ }++ async waitForRequest(urlOrPredicate: (string | Function), options: { timeout?: number; } = {}): Promise<Request> {+ const {+ timeout = this._timeoutSettings.timeout(),+ } = options;+ return helper.waitForEvent(this._frameManager.networkManager(), NetworkManagerEvents.Request, request => {+ if (helper.isString(urlOrPredicate))+ return (urlOrPredicate === request.url());+ if (typeof urlOrPredicate === 'function')+ return !!(urlOrPredicate(request));+ return false;+ }, timeout, this._sessionClosePromise());+ }++ async waitForResponse(urlOrPredicate: (string | Function), options: { timeout?: number; } = {}): Promise<Response> {+ const {+ timeout = this._timeoutSettings.timeout(),+ } = options;+ return helper.waitForEvent(this._frameManager.networkManager(), NetworkManagerEvents.Response, response => {+ if (helper.isString(urlOrPredicate))+ return (urlOrPredicate === response.url());+ if (typeof urlOrPredicate === 'function')+ return !!(urlOrPredicate(response));+ return false;+ }, timeout, this._sessionClosePromise());+ }++ async goBack(options: { timeout?: number; waitUntil?: string | string[]; } | undefined): Promise<Response | null> {+ return this._go(-1, options);+ }++ async goForward(options: { timeout?: number; waitUntil?: string | string[]; } | undefined): Promise<Response | null> {+ return this._go(+1, options);+ }++ async _go(delta, options: { timeout?: number; waitUntil?: string | string[]; } | undefined): Promise<Response | null> {+ const history = await this._client.send('Page.getNavigationHistory');+ const entry = history.entries[history.currentIndex + delta];+ if (!entry)+ return null;+ const [response] = await Promise.all([+ this.waitForNavigation(options),+ this._client.send('Page.navigateToHistoryEntry', {entryId: entry.id}),+ ]);+ return response;+ }++ async bringToFront() {+ await this._client.send('Page.bringToFront');+ }++ async emulate(options: { viewport: Viewport; userAgent: string; }) {+ await Promise.all([+ this.setViewport(options.viewport),+ this.setUserAgent(options.userAgent)+ ]);+ }++ async setJavaScriptEnabled(enabled: boolean) {+ if (this._javascriptEnabled === enabled)+ return;+ this._javascriptEnabled = enabled;+ await this._client.send('Emulation.setScriptExecutionDisabled', { value: !enabled });+ }++ async setBypassCSP(enabled: boolean) {+ await this._client.send('Page.setBypassCSP', { enabled });+ }++ async emulateMedia(type: string | null) {+ return this.emulateMediaType(type);+ }++ async emulateMediaType(type: string | null) {+ assert(type === 'screen' || type === 'print' || type === null, 'Unsupported media type: ' + type);+ await this._client.send('Emulation.setEmulatedMedia', {media: type || ''});+ }++ async emulateMediaFeatures(features: MediaFeature[] | null) {+ if (features === null)+ await this._client.send('Emulation.setEmulatedMedia', {features: null});+ if (Array.isArray(features)) {+ features.every(mediaFeature => {+ const name = mediaFeature.name;+ assert(/^prefers-(?:color-scheme|reduced-motion)$/.test(name), 'Unsupported media feature: ' + name);+ return true;+ });+ await this._client.send('Emulation.setEmulatedMedia', {features: features});+ }+ }++ async emulateTimezone(timezoneId: string | null) {+ try {+ await this._client.send('Emulation.setTimezoneOverride', {timezoneId: timezoneId || ''});+ } catch (exception) {+ if (exception.message.includes('Invalid timezone'))+ throw new Error(`Invalid timezone ID: ${timezoneId}`);+ throw exception;+ }+ }++ async setViewport(viewport: Viewport) {+ const needsReload = await this._emulationManager.emulateViewport(viewport);+ this._viewport = viewport;+ if (needsReload)+ await this.reload();+ }++ viewport(): Viewport | null {+ return this._viewport;+ }++ async evaluate(pageFunction: Function | string, ...args: any[]): Promise<any> {+ return this._frameManager.mainFrame().evaluate(pageFunction, ...args);+ }++ async evaluateOnNewDocument(pageFunction: Function | string, ...args: any[]) {+ const source = helper.evaluationString(pageFunction, ...args);+ await this._client.send('Page.addScriptToEvaluateOnNewDocument', { source });+ }++ async setCacheEnabled(enabled: boolean = true) {+ await this._frameManager.networkManager().setCacheEnabled(enabled);+ }++ async screenshot(options: ScreenshotOptions = {}): Promise<Buffer | string> {+ let screenshotType = null;+ // options.type takes precedence over inferring the type from options.path+ // because it may be a 0-length file with no extension created beforehand (i.e. as a temp file).+ if (options.type) {+ assert(options.type === 'png' || options.type === 'jpeg', 'Unknown options.type value: ' + options.type);+ screenshotType = options.type;+ } else if (options.path) {+ const mimeType = mime.getType(options.path);+ if (mimeType === 'image/png')+ screenshotType = 'png';+ else if (mimeType === 'image/jpeg')+ screenshotType = 'jpeg';+ assert(screenshotType, 'Unsupported screenshot mime type: ' + mimeType);+ }++ if (!screenshotType)+ screenshotType = 'png';++ if (options.quality) {+ assert(screenshotType === 'jpeg', 'options.quality is unsupported for the ' + screenshotType + ' screenshots');+ assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' + (typeof options.quality));+ assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer');+ assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' + options.quality);+ }+ assert(!options.clip || !options.fullPage, 'options.clip and options.fullPage are exclusive');+ if (options.clip) {+ assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' + (typeof options.clip.x));+ assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' + (typeof options.clip.y));+ assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' + (typeof options.clip.width));+ assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' + (typeof options.clip.height));+ assert(options.clip.width !== 0, 'Expected options.clip.width not to be 0.');+ assert(options.clip.height !== 0, 'Expected options.clip.height not to be 0.');+ }+ return this._screenshotTaskQueue.postTask(this._screenshotTask.bind(this, screenshotType, options));+ }++ async _screenshotTask(format: 'png' | 'jpeg', options?: ScreenshotOptions): Promise<Buffer | string> {+ await this._client.send('Target.activateTarget', {targetId: this._target._targetId});+ let clip = options.clip ? processClip(options.clip) : undefined;++ if (options.fullPage) {+ const metrics = await this._client.send('Page.getLayoutMetrics');+ const width = Math.ceil(metrics.contentSize.width);+ const height = Math.ceil(metrics.contentSize.height);++ // Overwrite clip for full page at all times.+ clip = { x: 0, y: 0, width, height, scale: 1 };+ const {+ isMobile = false,+ deviceScaleFactor = 1,+ isLandscape = false+ } = this._viewport || {};+ const screenOrientation: Protocol.Emulation.ScreenOrientation = isLandscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };+ await this._client.send('Emulation.setDeviceMetricsOverride', { mobile: isMobile, width, height, deviceScaleFactor, screenOrientation });+ }+ const shouldSetDefaultBackground = options.omitBackground && format === 'png';+ if (shouldSetDefaultBackground)+ await this._client.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });+ const result = await this._client.send('Page.captureScreenshot', { format, quality: options.quality, clip });+ if (shouldSetDefaultBackground)+ await this._client.send('Emulation.setDefaultBackgroundColorOverride');++ if (options.fullPage && this._viewport)+ await this.setViewport(this._viewport);++ const buffer = options.encoding === 'base64' ? result.data : Buffer.from(result.data, 'base64');+ if (options.path)+ await writeFileAsync(options.path, buffer);+ return buffer;++ function processClip(clip) {+ const x = Math.round(clip.x);+ const y = Math.round(clip.y);+ const width = Math.round(clip.width + clip.x - x);+ const height = Math.round(clip.height + clip.y - y);+ return {x, y, width, height, scale: 1};+ }+ }++ async pdf(options: PDFOptions = {}): Promise<Buffer> {+ const {+ scale = 1,+ displayHeaderFooter = false,+ headerTemplate = '',+ footerTemplate = '',+ printBackground = false,+ landscape = false,+ pageRanges = '',+ preferCSSPageSize = false,+ margin = {},+ path = null+ } = options;++ let paperWidth = 8.5;+ let paperHeight = 11;+ if (options.format) {+ const format = PagePaperFormats[options.format.toLowerCase()];+ assert(format, 'Unknown paper format: ' + options.format);+ paperWidth = format.width;+ paperHeight = format.height;+ } else {+ paperWidth = convertPrintParameterToInches(options.width) || paperWidth;+ paperHeight = convertPrintParameterToInches(options.height) || paperHeight;+ }++ const marginTop = convertPrintParameterToInches(margin.top) || 0;+ const marginLeft = convertPrintParameterToInches(margin.left) || 0;+ const marginBottom = convertPrintParameterToInches(margin.bottom) || 0;+ const marginRight = convertPrintParameterToInches(margin.right) || 0;++ const result = await this._client.send('Page.printToPDF', {+ transferMode: 'ReturnAsStream',+ landscape,+ displayHeaderFooter,+ headerTemplate,+ footerTemplate,+ printBackground,+ scale,+ paperWidth,+ paperHeight,+ marginTop,+ marginBottom,+ marginLeft,+ marginRight,+ pageRanges,+ preferCSSPageSize+ });+ return await readProtocolStream(this._client, result.stream, path);+ }++ async title(): Promise<string> {+ return this.mainFrame().title();+ }++ async close(options: { runBeforeUnload: (boolean | undefined); } = {runBeforeUnload: undefined}) {+ assert(!!this._client._connection, 'Protocol error: Connection closed. Most likely the page has been closed.');+ const runBeforeUnload = !!options.runBeforeUnload;+ if (runBeforeUnload) {+ await this._client.send('Page.close');+ } else {+ await this._client._connection.send('Target.closeTarget', { targetId: this._target._targetId });+ await this._target._isClosedPromise;+ }+ }++ isClosed(): boolean {+ return this._closed;+ }++ get mouse(): Mouse {+ return this._mouse;+ }++ click(selector: string, options?: ClickOptions) {+ return this.mainFrame().click(selector, options);+ }++ dblclick(selector: string, options?: MultiClickOptions) {+ return this.mainFrame().dblclick(selector, options);+ }++ tripleclick(selector: string, options?: MultiClickOptions) {+ return this.mainFrame().tripleclick(selector, options);+ }++ fill(selector: string, value: string) {+ return this.mainFrame().fill(selector, value);+ }++ focus(selector: string) {+ return this.mainFrame().focus(selector);+ }++ hover(selector: string, options?: PointerActionOptions) {+ return this.mainFrame().hover(selector, options);+ }++ select(selector: string, ...values: string[]): Promise<string[]> {+ return this.mainFrame().select(selector, ...values);+ }++ tap(selector: string, options?: PointerActionOptions) {+ return this.mainFrame().tap(selector, options);+ }++ type(selector: string, text: string, options: { delay: (number | undefined); } | undefined) {+ return this.mainFrame().type(selector, text, options);+ }++ waitFor(selectorOrFunctionOrTimeout: (string | number | Function), options: { visible?: boolean; hidden?: boolean; timeout?: number; polling?: string | number; } = {}, ...args: any[]): Promise<JSHandle> {+ return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);+ }++ waitForSelector(selector: string, options: { visible?: boolean; hidden?: boolean; timeout?: number; } = {}): Promise<ElementHandle | null> {+ return this.mainFrame().waitForSelector(selector, options);+ }++ waitForXPath(xpath: string, options: { visible?: boolean; hidden?: boolean; timeout?: number; } = {}): Promise<ElementHandle | null> {+ return this.mainFrame().waitForXPath(xpath, options);+ }++ waitForFunction(pageFunction: Function, options: {+ polling?: string | number;+ timeout?: number; } = {},+ ...args: any[]): Promise<JSHandle> {+ return this.mainFrame().waitForFunction(pageFunction, options, ...args);+ }+}++type PDFOptions = {+ scale?: number,+ displayHeaderFooter?: boolean,+ headerTemplate?: string,+ footerTemplate?: string,+ printBackground?: boolean,+ landscape?: boolean,+ pageRanges?: string,+ format?: string,+ width?: string|number,+ height?: string|number,+ preferCSSPageSize?: boolean,+ margin?: {top?: string|number, bottom?: string|number, left?: string|number, right?: string|number},+ path?: string,+}++type Metrics = {+ Timestamp?: number,+ Documents?: number,+ Frames?: number,+ JSEventListeners?: number,+ Nodes?: number,+ LayoutCount?: number,+ RecalcStyleCount?: number,+ LayoutDuration?: number,+ RecalcStyleDuration?: number,+ ScriptDuration?: number,+ TaskDuration?: number,+ JSHeapUsedSize?: number,+ JSHeapTotalSize?: number,+}++type ScreenshotOptions = {+ type?: string,+ path?: string,+ fullPage?: boolean,+ clip?: {x: number, y: number, width: number, height: number},+ quality?: number,+ omitBackground?: boolean,+ encoding?: string,+}++type MediaFeature = {+ name: string,+ value: string+}++const supportedMetrics: Set<string> = new Set([+ 'Timestamp',+ 'Documents',+ 'Frames',+ 'JSEventListeners',+ 'Nodes',+ 'LayoutCount',+ 'RecalcStyleCount',+ 'LayoutDuration',+ 'RecalcStyleDuration',+ 'ScriptDuration',+ 'TaskDuration',+ 'JSHeapUsedSize',+ 'JSHeapTotalSize',+]);++const PagePaperFormats = {+ letter: {width: 8.5, height: 11},+ legal: {width: 8.5, height: 14},+ tabloid: {width: 11, height: 17},+ ledger: {width: 17, height: 11},+ a0: {width: 33.1, height: 46.8 },+ a1: {width: 23.4, height: 33.1 },+ a2: {width: 16.54, height: 23.4 },+ a3: {width: 11.7, height: 16.54 },+ a4: {width: 8.27, height: 11.7 },+ a5: {width: 5.83, height: 8.27 },+ a6: {width: 4.13, height: 5.83 },+};++const unitToPixels = {+ 'px': 1,+ 'in': 96,+ 'cm': 37.8,+ 'mm': 3.78+};++function convertPrintParameterToInches(parameter: (string | number | undefined)): (number | undefined) {+ if (typeof parameter === 'undefined')+ return undefined;+ let pixels: number;+ if (helper.isNumber(parameter)) {+ // Treat numbers as pixel values to be aligned with phantom's paperSize.+ pixels = parameter as number;+ } else if (helper.isString(parameter)) {+ const text: string = parameter as string;+ let unit = text.substring(text.length - 2).toLowerCase();+ let valueText = '';+ if (unitToPixels.hasOwnProperty(unit)) {+ valueText = text.substring(0, text.length - 2);+ } else {+ // In case of unknown unit try to parse the whole parameter as number of pixels.+ // This is consistent with phantom's paperSize behavior.+ unit = 'px';+ valueText = text;+ }+ const value = Number(valueText);+ assert(!isNaN(value), 'Failed to parse parameter value: ' + text);+ pixels = value * unitToPixels[unit];+ } else {+ throw new Error('page.pdf() Cannot handle parameter type: ' + (typeof parameter));+ }+ return pixels / 96;+}++type NetworkCookie = {+ name: string,+ value: string,+ domain: string,+ path: string,+ expires: number,+ size: number,+ httpOnly: boolean,+ secure: boolean,+ session: boolean,+ sameSite: 'Strict'|'Lax'|'Extended'|'None'+};++type NetworkCookieParam = {+ name: string,+ value: string,+ url?: string,+ domain?: string,+ path?: string,+ expires?: number,+ httpOnly?: boolean,+ secure?: boolean,+ sameSite?: 'Strict'|'Lax'+};++type ConsoleMessageLocation = {+ url?: string,+ lineNumber?: number,+ columnNumber?: number+};++export class ConsoleMessage {+ private _type: string;+ private _text: string;+ private _args: JSHandle[];+ private _location: any;++ constructor(type: string, text: string, args: JSHandle[], location: ConsoleMessageLocation = {}) {+ this._type = type;+ this._text = text;+ this._args = args;+ this._location = location;+ }++ type(): string {+ return this._type;+ }++ text(): string {+ return this._text;+ }++ args(): JSHandle[] {+ return this._args;+ }++ location(): object {+ return this._location;+ }+}++export class FileChooser {+ private _client: CDPSession;+ private _multiple: boolean;+ private _handled = false;++ constructor(client: CDPSession, event: Protocol.Page.fileChooserOpenedPayload) {+ this._client = client;+ this._multiple = event.mode !== 'selectSingle';+ }++ isMultiple(): boolean {+ return this._multiple;+ }++ async accept(filePaths: string[]): Promise<any> {+ assert(!this._handled, 'Cannot accept FileChooser which is already handled!');+ this._handled = true;+ const files = filePaths.map(filePath => path.resolve(filePath));+ await this._client.send('Page.handleFileChooser', {+ action: 'accept',+ files,+ });+ }++ async cancel(): Promise<any> {+ assert(!this._handled, 'Cannot cancel FileChooser which is already handled!');+ this._handled = true;+ await this._client.send('Page.handleFileChooser', {+ action: 'cancel',+ });+ }+}diff --git a/src/chromium/PipeTransport.ts b/src/chromium/PipeTransport.tsnew file mode 100644index 0000000000..665d135c97--- /dev/null+++ b/src/chromium/PipeTransport.ts@@ -0,0 +1,73 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { ConnectionTransport } from '../ConnectionTransport';+import { debugError, helper, RegisteredListener } from '../helper';++export class PipeTransport implements ConnectionTransport {+ private _pipeWrite: NodeJS.WritableStream;+ private _pendingMessage = '';+ private _eventListeners: RegisteredListener[];+ onmessage?: (message: string) => void;+ onclose?: () => void;++ constructor(pipeWrite: NodeJS.WritableStream, pipeRead: NodeJS.ReadableStream) {+ this._pipeWrite = pipeWrite;+ this._eventListeners = [+ helper.addEventListener(pipeRead, 'data', buffer => this._dispatch(buffer)),+ helper.addEventListener(pipeRead, 'close', () => {+ if (this.onclose)+ this.onclose.call(null);+ }),+ helper.addEventListener(pipeRead, 'error', debugError),+ helper.addEventListener(pipeWrite, 'error', debugError),+ ];+ this.onmessage = null;+ this.onclose = null;+ }++ send(message: string) {+ this._pipeWrite.write(message);+ this._pipeWrite.write('\0');+ }++ _dispatch(buffer: Buffer) {+ let end = buffer.indexOf('\0');+ if (end === -1) {+ this._pendingMessage += buffer.toString();+ return;+ }+ const message = this._pendingMessage + buffer.toString(undefined, 0, end);+ if (this.onmessage)+ this.onmessage.call(null, message);++ let start = end + 1;+ end = buffer.indexOf('\0', start);+ while (end !== -1) {+ if (this.onmessage)+ this.onmessage.call(null, buffer.toString(undefined, start, end));+ start = end + 1;+ end = buffer.indexOf('\0', start);+ }+ this._pendingMessage = buffer.toString(undefined, start);+ }++ close() {+ this._pipeWrite = null;+ helper.removeEventListeners(this._eventListeners);+ }+}diff --git a/src/chromium/Playwright.ts b/src/chromium/Playwright.tsnew file mode 100644index 0000000000..9a7eafc6b2--- /dev/null+++ b/src/chromium/Playwright.ts@@ -0,0 +1,66 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import { Browser } from './Browser';+import { BrowserFetcher, BrowserFetcherOptions } from './BrowserFetcher';+import { ConnectionTransport } from '../ConnectionTransport';+import { DeviceDescriptors } from '../DeviceDescriptors';+import * as Errors from '../Errors';+import { Launcher, LauncherBrowserOptions, LauncherChromeArgOptions, LauncherLaunchOptions } from './Launcher';++export class Playwright {+ private _projectRoot: string;+ private _launcher: Launcher;++ constructor(projectRoot: string, preferredRevision: string, isPlaywrightCore: boolean) {+ this._projectRoot = projectRoot;+ this._launcher = new Launcher(projectRoot, preferredRevision, isPlaywrightCore);+ }++ launch(options: (LauncherLaunchOptions & LauncherChromeArgOptions & LauncherBrowserOptions) | undefined): Promise<Browser> {+ return this._launcher.launch(options);+ }++ connect(options: (LauncherBrowserOptions & {+ browserWSEndpoint?: string;+ browserURL?: string;+ transport?: ConnectionTransport; })): Promise<Browser> {+ return this._launcher.connect(options);+ }++ executablePath(): string {+ return this._launcher.executablePath();+ }++ get devices(): any {+ const result = DeviceDescriptors.slice();+ for (const device of DeviceDescriptors)+ result[device.name] = device;+ return result;+ }++ get errors(): any {+ return Errors;+ }++ defaultArgs(options: LauncherChromeArgOptions | undefined): string[] {+ return this._launcher.defaultArgs(options);+ }++ createBrowserFetcher(options: BrowserFetcherOptions | undefined): BrowserFetcher {+ return new BrowserFetcher(this._projectRoot, options);+ }+}diff --git a/src/chromium/Target.ts b/src/chromium/Target.tsnew file mode 100644index 0000000000..d3810651cb--- /dev/null+++ b/src/chromium/Target.ts@@ -0,0 +1,134 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { Events } from '../Events';+import { Browser } from './Browser';+import { BrowserContext } from './BrowserContext';+import { CDPSession } from './Connection';+import { Page, Viewport } from './Page';+import { TaskQueue } from './TaskQueue';+import { Worker } from './Worker';+import { Protocol } from './protocol';++export class Target {+ private _targetInfo: Protocol.Target.TargetInfo;+ private _browserContext: BrowserContext;+ _targetId: string;+ private _sessionFactory: () => Promise<CDPSession>;+ private _ignoreHTTPSErrors: boolean;+ private _defaultViewport: Viewport;+ private _screenshotTaskQueue: TaskQueue;+ private _pagePromise: Promise<Page> | null = null;+ private _workerPromise: Promise<Worker> | null = null;+ _initializedPromise: Promise<boolean>;+ _initializedCallback: (value?: unknown) => void;+ _isClosedPromise: Promise<void>;+ _closedCallback: (value?: unknown) => void;+ _isInitialized: boolean;++ constructor(+ targetInfo: Protocol.Target.TargetInfo,+ browserContext: BrowserContext,+ sessionFactory: () => Promise<CDPSession>,+ ignoreHTTPSErrors: boolean,+ defaultViewport: Viewport | null,+ screenshotTaskQueue: TaskQueue) {+ this._targetInfo = targetInfo;+ this._browserContext = browserContext;+ this._targetId = targetInfo.targetId;+ this._sessionFactory = sessionFactory;+ this._ignoreHTTPSErrors = ignoreHTTPSErrors;+ this._defaultViewport = defaultViewport;+ this._screenshotTaskQueue = screenshotTaskQueue;+ this._initializedPromise = new Promise(fulfill => this._initializedCallback = fulfill).then(async success => {+ if (!success)+ return false;+ const opener = this.opener();+ if (!opener || !opener._pagePromise || this.type() !== 'page')+ return true;+ const openerPage = await opener._pagePromise;+ if (!openerPage.listenerCount(Events.Page.Popup))+ return true;+ const popupPage = await this.page();+ openerPage.emit(Events.Page.Popup, popupPage);+ return true;+ });+ this._isClosedPromise = new Promise(fulfill => this._closedCallback = fulfill);+ this._isInitialized = this._targetInfo.type !== 'page' || this._targetInfo.url !== '';+ if (this._isInitialized)+ this._initializedCallback(true);+ }++ createCDPSession(): Promise<CDPSession> {+ return this._sessionFactory();+ }++ async page(): Promise<Page | null> {+ if ((this._targetInfo.type === 'page' || this._targetInfo.type === 'background_page') && !this._pagePromise) {+ this._pagePromise = this._sessionFactory()+ .then(client => Page.create(client, this, this._ignoreHTTPSErrors, this._defaultViewport, this._screenshotTaskQueue));+ }+ return this._pagePromise;+ }++ async worker(): Promise<Worker | null> {+ if (this._targetInfo.type !== 'service_worker' && this._targetInfo.type !== 'shared_worker')+ return null;+ if (!this._workerPromise) {+ // TODO(einbinder): Make workers send their console logs.+ this._workerPromise = this._sessionFactory()+ .then(client => new Worker(client, this._targetInfo.url, () => {} /* consoleAPICalled */, () => {} /* exceptionThrown */));+ }+ return this._workerPromise;+ }++ url(): string {+ return this._targetInfo.url;+ }++ type(): 'page' | 'background_page' | 'service_worker' | 'shared_worker' | 'other' | 'browser' {+ const type = this._targetInfo.type;+ if (type === 'page' || type === 'background_page' || type === 'service_worker' || type === 'shared_worker' || type === 'browser')+ return type;+ return 'other';+ }++ browser(): Browser {+ return this._browserContext.browser();+ }++ browserContext(): BrowserContext {+ return this._browserContext;+ }++ opener(): Target | null {+ const { openerId } = this._targetInfo;+ if (!openerId)+ return null;+ return this.browser()._targets.get(openerId);+ }++ _targetInfoChanged(targetInfo: Protocol.Target.TargetInfo) {+ this._targetInfo = targetInfo;++ if (!this._isInitialized && (this._targetInfo.type !== 'page' || this._targetInfo.url !== '')) {+ this._isInitialized = true;+ this._initializedCallback(true);+ return;+ }+ }+}diff --git a/src/chromium/TaskQueue.ts b/src/chromium/TaskQueue.tsnew file mode 100644index 0000000000..99b2de4469--- /dev/null+++ b/src/chromium/TaskQueue.ts@@ -0,0 +1,30 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export class TaskQueue {+ private _chain: Promise<any>;++ constructor() {+ this._chain = Promise.resolve();+ }++ postTask(task: () => any): Promise<any> {+ const result = this._chain.then(task);+ this._chain = result.catch(() => {});+ return result;+ }+}diff --git a/src/chromium/Tracing.ts b/src/chromium/Tracing.tsnew file mode 100644index 0000000000..7b908ac8a0--- /dev/null+++ b/src/chromium/Tracing.ts@@ -0,0 +1,66 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import { CDPSession } from './Connection';+import { assert } from '../helper';+import { readProtocolStream } from './protocolHelper';++export class Tracing {+ private _client: CDPSession;+ private _recording = false;+ private _path = '';++ constructor(client: CDPSession) {+ this._client = client;+ }++ async start(options: { path?: string; screenshots?: boolean; categories?: string[]; } = {}) {+ assert(!this._recording, 'Cannot start recording trace while already recording trace.');++ const defaultCategories = [+ '-*', 'devtools.timeline', 'v8.execute', 'disabled-by-default-devtools.timeline',+ 'disabled-by-default-devtools.timeline.frame', 'toplevel',+ 'blink.console', 'blink.user_timing', 'latencyInfo', 'disabled-by-default-devtools.timeline.stack',+ 'disabled-by-default-v8.cpu_profiler', 'disabled-by-default-v8.cpu_profiler.hires'+ ];+ const {+ path = null,+ screenshots = false,+ categories = defaultCategories,+ } = options;++ if (screenshots)+ categories.push('disabled-by-default-devtools.screenshot');++ this._path = path;+ this._recording = true;+ await this._client.send('Tracing.start', {+ transferMode: 'ReturnAsStream',+ categories: categories.join(',')+ });+ }++ async stop(): Promise<Buffer> {+ let fulfill: (buffer: Buffer) => void;+ const contentPromise = new Promise<Buffer>(x => fulfill = x);+ this._client.once('Tracing.tracingComplete', event => {+ readProtocolStream(this._client, event.stream, this._path).then(fulfill);+ });+ await this._client.send('Tracing.end');+ this._recording = false;+ return contentPromise;+ }+}diff --git a/src/chromium/WebSocketTransport.ts b/src/chromium/WebSocketTransport.tsnew file mode 100644index 0000000000..739d53db8f--- /dev/null+++ b/src/chromium/WebSocketTransport.ts@@ -0,0 +1,58 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import * as WebSocket from 'ws';+import { ConnectionTransport } from '../ConnectionTransport';++export class WebSocketTransport implements ConnectionTransport {+ private _ws: WebSocket;+ onmessage?: (message: string) => void;+ onclose?: () => void;++ static create(url: string): Promise<WebSocketTransport> {+ return new Promise((resolve, reject) => {+ const ws = new WebSocket(url, [], {+ perMessageDeflate: false,+ maxPayload: 256 * 1024 * 1024, // 256Mb+ });+ ws.addEventListener('open', () => resolve(new WebSocketTransport(ws)));+ ws.addEventListener('error', reject);+ });+ }++ constructor(ws: WebSocket) {+ this._ws = ws;+ this._ws.addEventListener('message', event => {+ if (this.onmessage)+ this.onmessage.call(null, event.data);+ });+ this._ws.addEventListener('close', event => {+ if (this.onclose)+ this.onclose.call(null);+ });+ // Silently ignore all errors - we don't know what to do with them.+ this._ws.addEventListener('error', () => {});+ }++ send(message: string) {+ this._ws.send(message);+ }++ close() {+ this._ws.close();+ }+}diff --git a/src/chromium/Worker.ts b/src/chromium/Worker.tsnew file mode 100644index 0000000000..4030a1180e--- /dev/null+++ b/src/chromium/Worker.ts@@ -0,0 +1,63 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import { EventEmitter } from 'events';+import { CDPSession } from './Connection';+import { ExecutionContext } from './ExecutionContext';+import { debugError } from '../helper';+import { JSHandle } from './JSHandle';+import { Protocol } from './protocol';++export class Worker extends EventEmitter {+ private _client: CDPSession;+ private _url: string;+ private _executionContextPromise: Promise<ExecutionContext>;+ private _executionContextCallback: (value?: ExecutionContext) => void;++ constructor(client: CDPSession, url: string, consoleAPICalled: (arg0: string, arg1: JSHandle[], arg2: Protocol.Runtime.StackTrace | undefined) => void, exceptionThrown: (arg0: Protocol.Runtime.ExceptionDetails) => void) {+ super();+ this._client = client;+ this._url = url;+ this._executionContextPromise = new Promise(x => this._executionContextCallback = x);+ let jsHandleFactory: (o: Protocol.Runtime.RemoteObject) => JSHandle;+ this._client.once('Runtime.executionContextCreated', async event => {+ jsHandleFactory = remoteObject => new JSHandle(executionContext, client, remoteObject);+ const executionContext = new ExecutionContext(client, event.context, null);+ this._executionContextCallback(executionContext);+ });+ // This might fail if the target is closed before we recieve all execution contexts.+ this._client.send('Runtime.enable', {}).catch(debugError);++ this._client.on('Runtime.consoleAPICalled', event => consoleAPICalled(event.type, event.args.map(jsHandleFactory), event.stackTrace));+ this._client.on('Runtime.exceptionThrown', exception => exceptionThrown(exception.exceptionDetails));+ }++ url(): string {+ return this._url;+ }++ async executionContext(): Promise<ExecutionContext> {+ return this._executionContextPromise;+ }++ async evaluate(pageFunction: Function | string, ...args: any[]): Promise<any> {+ return (await this._executionContextPromise).evaluate(pageFunction, ...args);+ }++ async evaluateHandle(pageFunction: Function | string, ...args: any[]): Promise<JSHandle> {+ return (await this._executionContextPromise).evaluateHandle(pageFunction, ...args);+ }+}diff --git a/src/chromium/protocolHelper.ts b/src/chromium/protocolHelper.tsnew file mode 100644index 0000000000..39d5df02c1--- /dev/null+++ b/src/chromium/protocolHelper.ts@@ -0,0 +1,97 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import * as fs from 'fs';+import {helper, assert, debugError} from '../helper';+import { CDPSession } from './Connection';+import { Protocol } from './protocol';++const openAsync = helper.promisify(fs.open);+const writeAsync = helper.promisify(fs.write);+const closeAsync = helper.promisify(fs.close);+++export function getExceptionMessage(exceptionDetails: Protocol.Runtime.ExceptionDetails): string {+ if (exceptionDetails.exception)+ return exceptionDetails.exception.description || exceptionDetails.exception.value;+ let message = exceptionDetails.text;+ if (exceptionDetails.stackTrace) {+ for (const callframe of exceptionDetails.stackTrace.callFrames) {+ const location = callframe.url + ':' + callframe.lineNumber + ':' + callframe.columnNumber;+ const functionName = callframe.functionName || '<anonymous>';+ message += `\n at ${functionName} (${location})`;+ }+ }+ return message;+}++export function valueFromRemoteObject(remoteObject: Protocol.Runtime.RemoteObject): any {+ assert(!remoteObject.objectId, 'Cannot extract value when objectId is given');+ if (remoteObject.unserializableValue) {+ if (remoteObject.type === 'bigint' && typeof BigInt !== 'undefined')+ return BigInt(remoteObject.unserializableValue.replace('n', ''));+ switch (remoteObject.unserializableValue) {+ case '-0':+ return -0;+ case 'NaN':+ return NaN;+ case 'Infinity':+ return Infinity;+ case '-Infinity':+ return -Infinity;+ default:+ throw new Error('Unsupported unserializable value: ' + remoteObject.unserializableValue);+ }+ }+ return remoteObject.value;+}++export async function releaseObject(client: CDPSession, remoteObject: Protocol.Runtime.RemoteObject) {+ if (!remoteObject.objectId)+ return;+ await client.send('Runtime.releaseObject', {objectId: remoteObject.objectId}).catch(error => {+ // Exceptions might happen in case of a page been navigated or closed.+ // Swallow these since they are harmless and we don't leak anything in this case.+ debugError(error);+ });+}++export async function readProtocolStream(client: CDPSession, handle: string, path: string | null): Promise<Buffer> {+ let eof = false;+ let file;+ if (path)+ file = await openAsync(path, 'w');+ const bufs = [];+ while (!eof) {+ const response = await client.send('IO.read', {handle});+ eof = response.eof;+ const buf = Buffer.from(response.data, response.base64Encoded ? 'base64' : undefined);+ bufs.push(buf);+ if (path)+ await writeAsync(file, buf);+ }+ if (path)+ await closeAsync(file);+ await client.send('IO.close', {handle});+ let resultBuffer = null;+ try {+ resultBuffer = Buffer.concat(bufs);+ } finally {+ return resultBuffer;+ }+}++diff --git a/src/firefox/Accessibility.ts b/src/firefox/Accessibility.tsnew file mode 100644index 0000000000..5ebb7863fd--- /dev/null+++ b/src/firefox/Accessibility.ts@@ -0,0 +1,273 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the 'License');+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an 'AS IS' BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++interface SerializedAXNode {+ role: string;++ name?: string;+ value?: string|number;+ description?: string;++ keyshortcuts?: string;+ roledescription?: string;+ valuetext?: string;++ disabled?: boolean;+ expanded?: boolean;+ focused?: boolean;+ modal?: boolean;+ multiline?: boolean;+ multiselectable?: boolean;+ readonly?: boolean;+ required?: boolean;+ selected?: boolean;++ checked?: boolean|'mixed';+ pressed?: boolean|'mixed';++ level?: number;++ autocomplete?: string;+ haspopup?: string;+ invalid?: string;+ orientation?: string;++ children?: Array<SerializedAXNode>;+}+export class Accessibility {+ _session: any;+ constructor(session) {+ this._session = session;+ }+ async snapshot(options: { interestingOnly?: boolean; } | undefined = {}): Promise<SerializedAXNode> {+ const { interestingOnly = true } = options;+ const { tree } = await this._session.send('Accessibility.getFullAXTree');+ const root = new AXNode(tree);+ if (!interestingOnly)+ return serializeTree(root)[0];+ const interestingNodes: Set<AXNode> = new Set();+ collectInterestingNodes(interestingNodes, root, false);+ return serializeTree(root, interestingNodes)[0];+ }+}+function collectInterestingNodes(collection: Set<AXNode>, node: AXNode, insideControl: boolean) {+ if (node.isInteresting(insideControl))+ collection.add(node);+ if (node.isLeafNode())+ return;+ insideControl = insideControl || node.isControl();+ for (const child of node._children)+ collectInterestingNodes(collection, child, insideControl);+}+function serializeTree(node: AXNode, whitelistedNodes?: Set<AXNode>): Array<SerializedAXNode> {+ const children: Array<SerializedAXNode> = [];+ for (const child of node._children)+ children.push(...serializeTree(child, whitelistedNodes));+ if (whitelistedNodes && !whitelistedNodes.has(node))+ return children;+ const serializedNode = node.serialize();+ if (children.length)+ serializedNode.children = children;+ return [serializedNode];+}+class AXNode {+ _children: AXNode[];+ private _payload: any;+ private _editable: boolean;+ private _richlyEditable: boolean;+ private _focusable: boolean;+ private _expanded: boolean;+ private _name: string;+ private _role: string;+ private _cachedHasFocusableChild: boolean|undefined;+ constructor(payload) {+ this._payload = payload;+ this._children = (payload.children || []).map(x => new AXNode(x));+ this._editable = payload.editable;+ this._richlyEditable = this._editable && (payload.tag !== 'textarea' && payload.tag !== 'input');+ this._focusable = payload.focusable;+ this._expanded = payload.expanded;+ this._name = this._payload.name;+ this._role = this._payload.role;+ this._cachedHasFocusableChild;+ }+ _isPlainTextField(): boolean {+ if (this._richlyEditable)+ return false;+ if (this._editable)+ return true;+ return this._role === 'entry';+ }+ _isTextOnlyObject(): boolean {+ const role = this._role;+ return (role === 'text leaf' || role === 'text' || role === 'statictext');+ }+ _hasFocusableChild(): boolean {+ if (this._cachedHasFocusableChild === undefined) {+ this._cachedHasFocusableChild = false;+ for (const child of this._children) {+ if (child._focusable || child._hasFocusableChild()) {+ this._cachedHasFocusableChild = true;+ break;+ }+ }+ }+ return this._cachedHasFocusableChild;+ }+ isLeafNode(): boolean {+ if (!this._children.length)+ return true;+ // These types of objects may have children that we use as internal+ // implementation details, but we want to expose them as leaves to platform+ // accessibility APIs because screen readers might be confused if they find+ // any children.+ if (this._isPlainTextField() || this._isTextOnlyObject())+ return true;+ // Roles whose children are only presentational according to the ARIA and+ // HTML5 Specs should be hidden from screen readers.+ // (Note that whilst ARIA buttons can have only presentational children, HTML5+ // buttons are allowed to have content.)+ switch (this._role) {+ case 'graphic':+ case 'scrollbar':+ case 'slider':+ case 'separator':+ case 'progressbar':+ return true;+ default:+ break;+ }+ // Here and below: Android heuristics+ if (this._hasFocusableChild())+ return false;+ if (this._focusable && this._name)+ return true;+ if (this._role === 'heading' && this._name)+ return true;+ return false;+ }+ isControl(): boolean {+ switch (this._role) {+ case 'checkbutton':+ case 'check menu item':+ case 'check rich option':+ case 'combobox':+ case 'combobox option':+ case 'color chooser':+ case 'listbox':+ case 'listbox option':+ case 'listbox rich option':+ case 'popup menu':+ case 'menupopup':+ case 'menuitem':+ case 'menubar':+ case 'button':+ case 'pushbutton':+ case 'radiobutton':+ case 'radio menuitem':+ case 'scrollbar':+ case 'slider':+ case 'spinbutton':+ case 'switch':+ case 'pagetab':+ case 'entry':+ case 'tree table':+ return true;+ default:+ return false;+ }+ }+ isInteresting(insideControl: boolean): boolean {+ if (this._focusable || this._richlyEditable)+ return true;+ // If it's not focusable but has a control role, then it's interesting.+ if (this.isControl())+ return true;+ // A non focusable child of a control is not interesting+ if (insideControl)+ return false;+ return this.isLeafNode() && !!this._name.trim();+ }+ serialize(): SerializedAXNode {+ const node: {[x in keyof SerializedAXNode]: any} = {+ role: this._role+ };+ const userStringProperties: Array<keyof SerializedAXNode> = [+ 'name',+ 'value',+ 'description',+ 'roledescription',+ 'valuetext',+ 'keyshortcuts',+ ];+ for (const userStringProperty of userStringProperties) {+ if (!(userStringProperty in this._payload))+ continue;+ node[userStringProperty] = this._payload[userStringProperty];+ }+ const booleanProperties: Array<keyof SerializedAXNode> = [+ 'disabled',+ 'expanded',+ 'focused',+ 'modal',+ 'multiline',+ 'multiselectable',+ 'readonly',+ 'required',+ 'selected',+ ];+ for (const booleanProperty of booleanProperties) {+ if (this._role === 'document' && booleanProperty === 'focused')+ continue; // document focusing is strange+ const value = this._payload[booleanProperty];+ if (!value)+ continue;+ node[booleanProperty] = value;+ }+ const tristateProperties: Array<keyof SerializedAXNode> = [+ 'checked',+ 'pressed',+ ];+ for (const tristateProperty of tristateProperties) {+ if (!(tristateProperty in this._payload))+ continue;+ const value = this._payload[tristateProperty];+ node[tristateProperty] = value;+ }+ const numericalProperties: Array<keyof SerializedAXNode> = [+ 'level'+ ];+ for (const numericalProperty of numericalProperties) {+ if (!(numericalProperty in this._payload))+ continue;+ node[numericalProperty] = this._payload[numericalProperty];+ }+ const tokenProperties: Array<keyof SerializedAXNode> = [+ 'autocomplete',+ 'haspopup',+ 'invalid',+ 'orientation',+ ];+ for (const tokenProperty of tokenProperties) {+ const value = this._payload[tokenProperty];+ if (!value || value === 'false')+ continue;+ node[tokenProperty] = value;+ }+ return node;+ }+}diff --git a/src/firefox/Browser.ts b/src/firefox/Browser.tsnew file mode 100644index 0000000000..a49edc85ed--- /dev/null+++ b/src/firefox/Browser.ts@@ -0,0 +1,334 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the 'License');+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an 'AS IS' BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {RegisteredListener, helper, assert} from '../helper';+import {Page, Viewport} from './Page';+import {EventEmitter} from 'events';+import {Connection, ConnectionEvents} from './Connection';+import {Events} from '../Events';++export class Browser extends EventEmitter {+ private _connection: Connection;+ _defaultViewport: Viewport;+ private _process: import('child_process').ChildProcess;+ private _closeCallback: () => void;+ _targets: Map<string, Target>;+ private _defaultContext: BrowserContext;+ private _contexts: Map<string, BrowserContext>;+ private _eventListeners: RegisteredListener[];++ static async create(connection: Connection, defaultViewport: Viewport | null, process: import('child_process').ChildProcess | null, closeCallback: () => void) {+ const {browserContextIds} = await connection.send('Target.getBrowserContexts');+ const browser = new Browser(connection, browserContextIds, defaultViewport, process, closeCallback);+ await connection.send('Target.enable');+ return browser;+ }+++ constructor(connection: Connection, browserContextIds: Array<string>, defaultViewport: Viewport | null, process: import('child_process').ChildProcess | null, closeCallback: () => void) {+ super();+ this._connection = connection;+ this._defaultViewport = defaultViewport;+ this._process = process;+ this._closeCallback = closeCallback;++ this._targets = new Map();++ this._defaultContext = new BrowserContext(this._connection, this, null);+ this._contexts = new Map();+ for (const browserContextId of browserContextIds)+ this._contexts.set(browserContextId, new BrowserContext(this._connection, this, browserContextId));++ this._connection.on(ConnectionEvents.Disconnected, () => this.emit(Events.Browser.Disconnected));++ this._eventListeners = [+ helper.addEventListener(this._connection, 'Target.targetCreated', this._onTargetCreated.bind(this)),+ helper.addEventListener(this._connection, 'Target.targetDestroyed', this._onTargetDestroyed.bind(this)),+ helper.addEventListener(this._connection, 'Target.targetInfoChanged', this._onTargetInfoChanged.bind(this)),+ ];+ }++ wsEndpoint() {+ return this._connection.url();+ }++ disconnect() {+ this._connection.dispose();+ }+++ isConnected(): boolean {+ return !this._connection._closed;+ }++ async createIncognitoBrowserContext(): Promise<BrowserContext> {+ const {browserContextId} = await this._connection.send('Target.createBrowserContext');+ const context = new BrowserContext(this._connection, this, browserContextId);+ this._contexts.set(browserContextId, context);+ return context;+ }+++ browserContexts(): Array<BrowserContext> {+ return [this._defaultContext, ...Array.from(this._contexts.values())];+ }++ defaultBrowserContext() {+ return this._defaultContext;+ }++ async _disposeContext(browserContextId) {+ await this._connection.send('Target.removeBrowserContext', {browserContextId});+ this._contexts.delete(browserContextId);+ }+++ async userAgent(): Promise<string> {+ const info = await this._connection.send('Browser.getInfo');+ return info.userAgent;+ }+++ async version(): Promise<string> {+ const info = await this._connection.send('Browser.getInfo');+ return info.version;+ }+++ process(): import('child_process').ChildProcess | null {+ return this._process;+ }+++ async waitForTarget(predicate: (target: Target) => boolean, options: { timeout?: number; } = {}): Promise<Target> {+ const {+ timeout = 30000+ } = options;+ const existingTarget = this.targets().find(predicate);+ if (existingTarget)+ return existingTarget;+ let resolve;+ const targetPromise = new Promise<Target>(x => resolve = x);+ this.on(Events.Browser.TargetCreated, check);+ this.on('targetchanged', check);+ try {+ if (!timeout)+ return await targetPromise;+ return await helper.waitWithTimeout(targetPromise, 'target', timeout);+ } finally {+ this.removeListener(Events.Browser.TargetCreated, check);+ this.removeListener('targetchanged', check);+ }++ function check(target: Target) {+ if (predicate(target))+ resolve(target);+ }+ }+++ newPage(): Promise<Page> {+ return this._createPageInContext(this._defaultContext._browserContextId);+ }+++ async _createPageInContext(browserContextId: string | null): Promise<Page> {+ const {targetId} = await this._connection.send('Target.newPage', {+ browserContextId: browserContextId || undefined+ });+ const target = this._targets.get(targetId);+ return await target.page();+ }++ async pages() {+ const pageTargets = Array.from(this._targets.values()).filter(target => target.type() === 'page');+ return await Promise.all(pageTargets.map(target => target.page()));+ }++ targets() {+ return Array.from(this._targets.values());+ }++ target() {+ return this.targets().find(target => target.type() === 'browser');+ }++ async _onTargetCreated({targetId, url, browserContextId, openerId, type}) {+ const context = browserContextId ? this._contexts.get(browserContextId) : this._defaultContext;+ const target = new Target(this._connection, this, context, targetId, type, url, openerId);+ this._targets.set(targetId, target);+ if (target.opener() && target.opener()._pagePromise) {+ const openerPage = await target.opener()._pagePromise;+ if (openerPage.listenerCount(Events.Page.Popup)) {+ const popupPage = await target.page();+ openerPage.emit(Events.Page.Popup, popupPage);+ }+ }+ this.emit(Events.Browser.TargetCreated, target);+ context.emit(Events.BrowserContext.TargetCreated, target);+ }++ _onTargetDestroyed({targetId}) {+ const target = this._targets.get(targetId);+ this._targets.delete(targetId);+ target._closedCallback();+ this.emit(Events.Browser.TargetDestroyed, target);+ target.browserContext().emit(Events.BrowserContext.TargetDestroyed, target);+ }++ _onTargetInfoChanged({targetId, url}) {+ const target = this._targets.get(targetId);+ target._url = url;+ this.emit(Events.Browser.TargetChanged, target);+ target.browserContext().emit(Events.BrowserContext.TargetChanged, target);+ }++ async close() {+ helper.removeEventListeners(this._eventListeners);+ await this._closeCallback();+ }+}++export class Target {+ _pagePromise?: Promise<Page>;+ private _browser: Browser;+ _context: BrowserContext;+ private _connection: any;+ private _targetId: string;+ private _type: 'page' | 'browser';+ _url: string;+ private _openerId: string;+ _isClosedPromise: Promise<unknown>;+ _closedCallback: (value?: unknown) => void;++ constructor(connection: any, browser: Browser, context: BrowserContext, targetId: string, type: 'page' | 'browser', url: string, openerId: string | undefined) {+ this._browser = browser;+ this._context = context;+ this._connection = connection;+ this._targetId = targetId;+ this._type = type;+ this._url = url;+ this._openerId = openerId;+ this._isClosedPromise = new Promise(fulfill => this._closedCallback = fulfill);+ }+++ opener(): Target | null {+ return this._openerId ? this._browser._targets.get(this._openerId) : null;+ }+++ type(): 'page' | 'browser' {+ return this._type;+ }++ url() {+ return this._url;+ }+++ browserContext(): BrowserContext {+ return this._context;+ }++ async page() {+ if (this._type === 'page' && !this._pagePromise) {+ const session = await this._connection.createSession(this._targetId);+ this._pagePromise = Page.create(session, this, this._browser._defaultViewport);+ }+ return this._pagePromise;+ }++ browser() {+ return this._browser;+ }+}++export class BrowserContext extends EventEmitter {+ _connection: Connection;+ _browser: Browser;+ _browserContextId: string;++ constructor(connection: Connection, browser: Browser, browserContextId: string | null) {+ super();+ this._connection = connection;+ this._browser = browser;+ this._browserContextId = browserContextId;+ }+++ async overridePermissions(origin: string, permissions: Array<string>) {+ const webPermissionToProtocol = new Map([+ ['geolocation', 'geo'],+ ['microphone', 'microphone'],+ ['camera', 'camera'],+ ['notifications', 'desktop-notifications'],+ ]);+ permissions = permissions.map(permission => {+ const protocolPermission = webPermissionToProtocol.get(permission);+ if (!protocolPermission)+ throw new Error('Unknown permission: ' + permission);+ return protocolPermission;+ });+ await this._connection.send('Browser.grantPermissions', {origin, browserContextId: this._browserContextId || undefined, permissions});+ }++ async clearPermissionOverrides() {+ await this._connection.send('Browser.resetPermissions', {browserContextId: this._browserContextId || undefined});+ }+++ targets(): Array<Target> {+ return this._browser.targets().filter(target => target.browserContext() === this);+ }+++ async pages(): Promise<Array<Page>> {+ const pages = await Promise.all(+ this.targets()+ .filter(target => target.type() === 'page')+ .map(target => target.page())+ );+ return pages.filter(page => !!page);+ }+++ waitForTarget(predicate: (arg0: Target) => boolean, options: { timeout?: number; } | undefined): Promise<Target> {+ return this._browser.waitForTarget(target => target.browserContext() === this && predicate(target), options);+ }+++ isIncognito(): boolean {+ return !!this._browserContextId;+ }++ newPage() {+ return this._browser._createPageInContext(this._browserContextId);+ }+++ browser(): Browser {+ return this._browser;+ }++ async close() {+ assert(this._browserContextId, 'Non-incognito contexts cannot be closed!');+ await this._browser._disposeContext(this._browserContextId);+ }+}++module.exports = {Browser, BrowserContext, Target};diff --git a/src/firefox/BrowserFetcher.ts b/src/firefox/BrowserFetcher.tsnew file mode 100644index 0000000000..4cb6f21a29--- /dev/null+++ b/src/firefox/BrowserFetcher.ts@@ -0,0 +1,283 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the 'License');+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an 'AS IS' BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import * as os from 'os';+import * as fs from 'fs';+import * as path from 'path';+import * as extract from 'extract-zip';+import * as util from 'util';+import * as URL from 'url';+import {helper, assert} from '../helper';+import * as removeRecursive from 'rimraf';+// @ts-ignore+import * as ProxyAgent from 'https-proxy-agent';+// @ts-ignore+import {getProxyForUrl} from 'proxy-from-env';+const DEFAULT_DOWNLOAD_HOST = 'https://playwrightaccount.blob.core.windows.net/builds';++const downloadURLs = {+ chromium: {+ linux: '%s/chromium-browser-snapshots/Linux_x64/%s/%s.zip',+ mac: '%s/chromium-browser-snapshots/Mac/%s/%s.zip',+ win32: '%s/chromium-browser-snapshots/Win/%s/%s.zip',+ win64: '%s/chromium-browser-snapshots/Win_x64/%s/%s.zip',+ },+ firefox: {+ linux: '%s/firefox/%s/%s.zip',+ mac: '%s/firefox/%s/%s.zip',+ win32: '%s/firefox/%s/%s.zip',+ win64: '%s/firefox/%s/%s.zip',+ },+};++function archiveName(product: string, platform: string, revision: string): string {+ if (product === 'chromium') {+ if (platform === 'linux')+ return 'chrome-linux';+ if (platform === 'mac')+ return 'chrome-mac';+ if (platform === 'win32' || platform === 'win64') {+ // Windows archive name changed at r591479.+ return parseInt(revision, 10) > 591479 ? 'chrome-win' : 'chrome-win32';+ }+ } else if (product === 'firefox') {+ if (platform === 'linux')+ return 'firefox-linux';+ if (platform === 'mac')+ return 'firefox-mac';+ if (platform === 'win32' || platform === 'win64')+ return 'firefox-' + platform;+ }+ return null;+}++function downloadURL(product: string, platform: string, host: string, revision: string): string {+ return util.format(downloadURLs[product][platform], host, revision, archiveName(product, platform, revision));+}++const readdirAsync = helper.promisify(fs.readdir.bind(fs));+const mkdirAsync = helper.promisify(fs.mkdir.bind(fs));+const unlinkAsync = helper.promisify(fs.unlink.bind(fs));+const chmodAsync = helper.promisify(fs.chmod.bind(fs));++function existsAsync(filePath) {+ let fulfill = null;+ const promise = new Promise(x => fulfill = x);+ fs.access(filePath, err => fulfill(!err));+ return promise;+}++export class BrowserFetcher {+ _product: string;+ _downloadsFolder: string;+ _downloadHost: string;+ _platform: string;+ constructor(projectRoot: string, options: BrowserFetcherOptions | undefined = {}) {+ this._product = (options.browser || 'chromium').toLowerCase();+ assert(this._product === 'chromium' || this._product === 'firefox', `Unkown product: "${options.browser}"`);+ this._downloadsFolder = options.path || path.join(projectRoot, '.local-browser');+ this._downloadHost = options.host || DEFAULT_DOWNLOAD_HOST;+ this._platform = options.platform || '';+ if (!this._platform) {+ const platform = os.platform();+ if (platform === 'darwin')+ this._platform = 'mac';+ else if (platform === 'linux')+ this._platform = 'linux';+ else if (platform === 'win32')+ this._platform = os.arch() === 'x64' ? 'win64' : 'win32';+ assert(this._platform, 'Unsupported platform: ' + os.platform());+ }+ assert(downloadURLs[this._product][this._platform], 'Unsupported platform: ' + this._platform);+ }++ platform(): string {+ return this._platform;+ }++ canDownload(revision: string): Promise<boolean> {+ const url = downloadURL(this._product, this._platform, this._downloadHost, revision);+ let resolve;+ const promise = new Promise<boolean>(x => resolve = x);+ const request = httpRequest(url, 'HEAD', response => {+ resolve(response.statusCode === 200);+ });+ request.on('error', error => {+ console.error(error);+ resolve(false);+ });+ return promise;+ }++ async download(revision: string, progressCallback: ((arg0: number, arg1: number) => void) | null): Promise<RevisionInfo> {+ const url = downloadURL(this._product, this._platform, this._downloadHost, revision);+ const zipPath = path.join(this._downloadsFolder, `download-${this._product}-${this._platform}-${revision}.zip`);+ const folderPath = this._getFolderPath(revision);+ if (await existsAsync(folderPath))+ return this.revisionInfo(revision);+ if (!(await existsAsync(this._downloadsFolder)))+ await mkdirAsync(this._downloadsFolder);+ try {+ await downloadFile(url, zipPath, progressCallback);+ await extractZip(zipPath, folderPath);+ } finally {+ if (await existsAsync(zipPath))+ await unlinkAsync(zipPath);+ }+ const revisionInfo = this.revisionInfo(revision);+ if (revisionInfo)+ await chmodAsync(revisionInfo.executablePath, 0o755);+ return revisionInfo;+ }++ async localRevisions(): Promise<Array<string>> {+ if (!await existsAsync(this._downloadsFolder))+ return [];+ const fileNames = await readdirAsync(this._downloadsFolder);+ return fileNames.map(fileName => parseFolderPath(fileName)).filter(entry => entry && entry.platform === this._platform).map(entry => entry.revision);+ }++ async remove(revision: string) {+ const folderPath = this._getFolderPath(revision);+ assert(await existsAsync(folderPath), `Failed to remove: revision ${revision} is not downloaded`);+ await new Promise(fulfill => removeRecursive(folderPath, fulfill));+ }++ revisionInfo(revision: string): RevisionInfo {+ const folderPath = this._getFolderPath(revision);+ let executablePath = '';+ if (this._product === 'chromium') {+ if (this._platform === 'mac')+ executablePath = path.join(folderPath, archiveName(this._product, this._platform, revision), 'Chromium.app', 'Contents', 'MacOS', 'Chromium');+ else if (this._platform === 'linux')+ executablePath = path.join(folderPath, archiveName(this._product, this._platform, revision), 'chrome');+ else if (this._platform === 'win32' || this._platform === 'win64')+ executablePath = path.join(folderPath, archiveName(this._product, this._platform, revision), 'chrome.exe');+ else+ throw new Error('Unsupported platform: ' + this._platform);+ } else if (this._product === 'firefox') {+ if (this._platform === 'mac')+ executablePath = path.join(folderPath, 'firefox', 'Nightly.app', 'Contents', 'MacOS', 'firefox');+ else if (this._platform === 'linux')+ executablePath = path.join(folderPath, 'firefox', 'firefox');+ else if (this._platform === 'win32' || this._platform === 'win64')+ executablePath = path.join(folderPath, 'firefox', 'firefox.exe');+ else+ throw new Error('Unsupported platform: ' + this._platform);+ }+ const url = downloadURL(this._product, this._platform, this._downloadHost, revision);+ const local = fs.existsSync(folderPath);+ return {revision, executablePath, folderPath, local, url};+ }++ _getFolderPath(revision: string): string {+ return path.join(this._downloadsFolder, this._product + '-' + this._platform + '-' + revision);+ }+}++function parseFolderPath(folderPath: string): { platform: string; revision: string; } | null {+ const name = path.basename(folderPath);+ const splits = name.split('-');+ if (splits.length !== 3)+ return null;+ const [product, platform, revision] = splits;+ if (!downloadURLs[product][platform])+ return null;+ return {platform, revision};+}++function downloadFile(url: string, destinationPath: string, progressCallback: ((arg0: number, arg1: number) => void) | null): Promise<any> {+ let fulfill, reject;+ let downloadedBytes = 0;+ let totalBytes = 0;++ const promise = new Promise((x, y) => { fulfill = x; reject = y; });++ const request = httpRequest(url, 'GET', response => {+ if (response.statusCode !== 200) {+ const error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`);+ // consume response data to free up memory+ response.resume();+ reject(error);+ return;+ }+ const file = fs.createWriteStream(destinationPath);+ file.on('finish', () => fulfill());+ file.on('error', error => reject(error));+ response.pipe(file);+ totalBytes = parseInt(response.headers['content-length'], 10);+ if (progressCallback)+ response.on('data', onData);+ });+ request.on('error', error => reject(error));+ return promise;++ function onData(chunk) {+ downloadedBytes += chunk.length;+ progressCallback(downloadedBytes, totalBytes);+ }+}++function extractZip(zipPath: string, folderPath: string): Promise<Error | null> {+ return new Promise((fulfill, reject) => extract(zipPath, {dir: folderPath}, err => {+ if (err)+ reject(err);+ else+ fulfill();+ }));+}++function httpRequest(url: string, method: string, onResponse: (response: any) => void) {+ const options: any = URL.parse(url);+ options.method = method;++ const proxyURL = getProxyForUrl(url);+ if (proxyURL) {+ const parsedProxyURL: any = URL.parse(proxyURL);+ parsedProxyURL.secureProxy = parsedProxyURL.protocol === 'https:';++ options.agent = new ProxyAgent(parsedProxyURL);+ options.rejectUnauthorized = false;+ }++ const requestCallback = res => {+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location)+ httpRequest(res.headers.location, method, onResponse);+ else+ onResponse(res);+ };+ const request = options.protocol === 'https:' ?+ require('https').request(options, requestCallback) :+ require('http').request(options, requestCallback);+ request.end();+ return request;+}++interface BrowserFetcherOptions {+ browser?: string;+ platform?: string;+ path?: string;+ host?: string;+}++interface RevisionInfo {+ folderPath: string;+ executablePath: string;+ url: string;+ local: boolean;+ revision: string;+}diff --git a/src/firefox/Connection.ts b/src/firefox/Connection.tsnew file mode 100644index 0000000000..5f5122221e--- /dev/null+++ b/src/firefox/Connection.ts@@ -0,0 +1,203 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the 'License');+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an 'AS IS' BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {assert} from '../helper';+import {EventEmitter} from 'events';+import * as debug from 'debug';+import { ConnectionTransport } from '../ConnectionTransport';+const debugProtocol = debug('playwright:protocol');++export const ConnectionEvents = {+ Disconnected: Symbol('Disconnected'),+};++export class Connection extends EventEmitter {+ private _url: string;+ private _lastId: number;+ private _callbacks: Map<number, {resolve: Function, reject: Function, error: Error, method: string}>;+ private _delay: number;+ private _transport: ConnectionTransport;+ private _sessions: Map<string, JugglerSession>;+ _closed: boolean;+ constructor(url: string, transport: ConnectionTransport, delay: number | undefined = 0) {+ super();+ this._url = url;+ this._lastId = 0;+ this._callbacks = new Map();+ this._delay = delay;++ this._transport = transport;+ this._transport.onmessage = this._onMessage.bind(this);+ this._transport.onclose = this._onClose.bind(this);+ this._sessions = new Map();+ this._closed = false;+ }++ static fromSession(session: JugglerSession): Connection {+ return session._connection;+ }++ session(sessionId: string): JugglerSession | null {+ return this._sessions.get(sessionId) || null;+ }++ url(): string {+ return this._url;+ }++ send(method: string, params: object | undefined = {}): Promise<any> {+ const id = this._rawSend({method, params});+ return new Promise((resolve, reject) => {+ this._callbacks.set(id, {resolve, reject, error: new Error(), method});+ });+ }++ _rawSend(message: any): number {+ const id = ++this._lastId;+ message = JSON.stringify(Object.assign({}, message, {id}));+ debugProtocol('SEND ► ' + message);+ this._transport.send(message);+ return id;+ }++ async _onMessage(message: string) {+ if (this._delay)+ await new Promise(f => setTimeout(f, this._delay));+ debugProtocol('◀ RECV ' + message);+ const object = JSON.parse(message);+ if (object.method === 'Target.attachedToTarget') {+ const sessionId = object.params.sessionId;+ const session = new JugglerSession(this, object.params.targetInfo.type, sessionId);+ this._sessions.set(sessionId, session);+ } else if (object.method === 'Browser.detachedFromTarget') {+ const session = this._sessions.get(object.params.sessionId);+ if (session) {+ session._onClosed();+ this._sessions.delete(object.params.sessionId);+ }+ }+ if (object.sessionId) {+ const session = this._sessions.get(object.sessionId);+ if (session)+ session._onMessage(object);+ } else if (object.id) {+ const callback = this._callbacks.get(object.id);+ // Callbacks could be all rejected if someone has called `.dispose()`.+ if (callback) {+ this._callbacks.delete(object.id);+ if (object.error)+ callback.reject(createProtocolError(callback.error, callback.method, object));+ else+ callback.resolve(object.result);+ }+ } else {+ this.emit(object.method, object.params);+ }+ }++ _onClose() {+ if (this._closed)+ return;+ this._closed = true;+ this._transport.onmessage = null;+ this._transport.onclose = null;+ for (const callback of this._callbacks.values())+ callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));+ this._callbacks.clear();+ for (const session of this._sessions.values())+ session._onClosed();+ this._sessions.clear();+ this.emit(ConnectionEvents.Disconnected);+ }++ dispose() {+ this._onClose();+ this._transport.close();+ }++ async createSession(targetId: string): Promise<JugglerSession> {+ const {sessionId} = await this.send('Target.attachToTarget', {targetId});+ return this._sessions.get(sessionId);+ }+}++export const JugglerSessionEvents = {+ Disconnected: Symbol('Disconnected')+};++export class JugglerSession extends EventEmitter {+ _connection: Connection;+ private _callbacks: Map<number, {resolve: Function, reject: Function, error: Error, method: string}>;+ private _targetType: string;+ private _sessionId: string;+ constructor(connection: Connection, targetType: string, sessionId: string) {+ super();+ this._callbacks = new Map();+ this._connection = connection;+ this._targetType = targetType;+ this._sessionId = sessionId;+ }++ send(method: string, params: any = {}): Promise<any> {+ if (!this._connection)+ return Promise.reject(new Error(`Protocol error (${method}): Session closed. Most likely the ${this._targetType} has been closed.`));+ const id = this._connection._rawSend({sessionId: this._sessionId, method, params});+ return new Promise((resolve, reject) => {+ this._callbacks.set(id, {resolve, reject, error: new Error(), method});+ });+ }++ _onMessage(object: { id?: number; method: string; params: object; error: { message: string; data: any; }; result?: any; }) {+ if (object.id && this._callbacks.has(object.id)) {+ const callback = this._callbacks.get(object.id);+ this._callbacks.delete(object.id);+ if (object.error)+ callback.reject(createProtocolError(callback.error, callback.method, object));+ else+ callback.resolve(object.result);+ } else {+ assert(!object.id);+ this.emit(object.method, object.params);+ }+ }++ async detach() {+ if (!this._connection)+ throw new Error(`Session already detached. Most likely the ${this._targetType} has been closed.`);+ await this._connection.send('Target.detachFromTarget', {sessionId: this._sessionId});+ }++ _onClosed() {+ for (const callback of this._callbacks.values())+ callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));+ this._callbacks.clear();+ this._connection = null;+ this.emit(JugglerSessionEvents.Disconnected);+ }+}++function createProtocolError(error: Error, method: string, object: { error: { message: string; data: any; }; }): Error {+ let message = `Protocol error (${method}): ${object.error.message}`;+ if ('data' in object.error)+ message += ` ${object.error.data}`;+ return rewriteError(error, message);+}++function rewriteError(error: Error, message: string): Error {+ error.message = message;+ return error;+}diff --git a/src/firefox/DOMWorld.ts b/src/firefox/DOMWorld.tsnew file mode 100644index 0000000000..dd505e2398--- /dev/null+++ b/src/firefox/DOMWorld.ts@@ -0,0 +1,503 @@+import {helper, assert} from '../helper';+import {TimeoutError} from '../Errors';+import * as fs from 'fs';+import * as util from 'util';+import {ElementHandle, JSHandle} from './JSHandle';++const readFileAsync = util.promisify(fs.readFile);++export class DOMWorld {+ _frame: any;+ _timeoutSettings: any;+ _documentPromise: any;+ _contextPromise: any;+ _contextResolveCallback: any;+ _waitTasks: Set<WaitTask>;+ _detached: boolean;+ constructor(frame, timeoutSettings) {+ this._frame = frame;+ this._timeoutSettings = timeoutSettings;++ this._documentPromise = null;+ this._contextPromise;+ this._contextResolveCallback = null;+ this._setContext(null);++ this._waitTasks = new Set();+ this._detached = false;+ }++ frame() {+ return this._frame;+ }++ _setContext(context) {+ if (context) {+ this._contextResolveCallback.call(null, context);+ this._contextResolveCallback = null;+ for (const waitTask of this._waitTasks)+ waitTask.rerun();+ } else {+ this._documentPromise = null;+ this._contextPromise = new Promise(fulfill => {+ this._contextResolveCallback = fulfill;+ });+ }+ }++ _detach() {+ this._detached = true;+ for (const waitTask of this._waitTasks)+ waitTask.terminate(new Error('waitForFunction failed: frame got detached.'));+ }++ async executionContext() {+ if (this._detached)+ throw new Error(`Execution Context is not available in detached frame "${this.url()}" (are you trying to evaluate?)`);+ return this._contextPromise;+ }+ url() {+ throw new Error('Method not implemented.');+ }++ async evaluateHandle(pageFunction, ...args) {+ const context = await this.executionContext();+ return context.evaluateHandle(pageFunction, ...args);+ }++ async evaluate(pageFunction, ...args) {+ const context = await this.executionContext();+ return context.evaluate(pageFunction, ...args);+ }++ async $(selector: string): Promise<ElementHandle | null> {+ const document = await this._document();+ return document.$(selector);+ }++ _document() {+ if (!this._documentPromise)+ this._documentPromise = this.evaluateHandle('document').then(handle => handle.asElement());+ return this._documentPromise;+ }++ async $x(expression: string): Promise<Array<ElementHandle>> {+ const document = await this._document();+ return document.$x(expression);+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: Array<any>): Promise<(object | undefined)> {+ const document = await this._document();+ return document.$eval(selector, pageFunction, ...args);+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: Array<any>): Promise<(object | undefined)> {+ const document = await this._document();+ return document.$$eval(selector, pageFunction, ...args);+ }++ async $$(selector: string): Promise<Array<ElementHandle>> {+ const document = await this._document();+ return document.$$(selector);+ }++ async content(): Promise<string> {+ return await this.evaluate(() => {+ let retVal = '';+ if (document.doctype)+ retVal = new XMLSerializer().serializeToString(document.doctype);+ if (document.documentElement)+ retVal += document.documentElement.outerHTML;+ return retVal;+ });+ }++ async setContent(html: string) {+ await this.evaluate(html => {+ document.open();+ document.write(html);+ document.close();+ }, html);+ }++ async addScriptTag(options: { content?: string; path?: string; type?: string; url?: string; }): Promise<ElementHandle> {+ if (typeof options.url === 'string') {+ const url = options.url;+ try {+ return (await this.evaluateHandle(addScriptUrl, url, options.type)).asElement();+ } catch (error) {+ throw new Error(`Loading script from ${url} failed`);+ }+ }++ if (typeof options.path === 'string') {+ let contents = await readFileAsync(options.path, 'utf8');+ contents += '//# sourceURL=' + options.path.replace(/\n/g, '');+ return (await this.evaluateHandle(addScriptContent, contents, options.type)).asElement();+ }++ if (typeof options.content === 'string')+ return (await this.evaluateHandle(addScriptContent, options.content, options.type)).asElement();+++ throw new Error('Provide an object with a `url`, `path` or `content` property');++ async function addScriptUrl(url: string, type: string): Promise<HTMLElement> {+ const script = document.createElement('script');+ script.src = url;+ if (type)+ script.type = type;+ const promise = new Promise((res, rej) => {+ script.onload = res;+ script.onerror = rej;+ });+ document.head.appendChild(script);+ await promise;+ return script;+ }++ function addScriptContent(content: string, type: string = 'text/javascript'): HTMLElement {+ const script = document.createElement('script');+ script.type = type;+ script.text = content;+ let error = null;+ script.onerror = e => error = e;+ document.head.appendChild(script);+ if (error)+ throw error;+ return script;+ }+ }++ async addStyleTag(options: { content?: string; path?: string; url?: string; }): Promise<ElementHandle> {+ if (typeof options.url === 'string') {+ const url = options.url;+ try {+ return (await this.evaluateHandle(addStyleUrl, url)).asElement();+ } catch (error) {+ throw new Error(`Loading style from ${url} failed`);+ }+ }++ if (typeof options.path === 'string') {+ let contents = await readFileAsync(options.path, 'utf8');+ contents += '/*# sourceURL=' + options.path.replace(/\n/g, '') + '*/';+ return (await this.evaluateHandle(addStyleContent, contents)).asElement();+ }++ if (typeof options.content === 'string')+ return (await this.evaluateHandle(addStyleContent, options.content)).asElement();+++ throw new Error('Provide an object with a `url`, `path` or `content` property');++ async function addStyleUrl(url: string): Promise<HTMLElement> {+ const link = document.createElement('link');+ link.rel = 'stylesheet';+ link.href = url;+ const promise = new Promise((res, rej) => {+ link.onload = res;+ link.onerror = rej;+ });+ document.head.appendChild(link);+ await promise;+ return link;+ }++ async function addStyleContent(content: string): Promise<HTMLElement> {+ const style = document.createElement('style');+ style.type = 'text/css';+ style.appendChild(document.createTextNode(content));+ const promise = new Promise((res, rej) => {+ style.onload = res;+ style.onerror = rej;+ });+ document.head.appendChild(style);+ await promise;+ return style;+ }+ }++ async click(selector: string, options: { delay?: number; button?: string; clickCount?: number; } | undefined = {}) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.click(options);+ await handle.dispose();+ }++ async focus(selector: string) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.focus();+ await handle.dispose();+ }++ async hover(selector: string) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.hover();+ await handle.dispose();+ }++ select(selector: string, ...values: Array<string>): Promise<Array<string>> {+ for (const value of values)+ assert(helper.isString(value), 'Values must be strings. Found value "' + value + '" of type "' + (typeof value) + '"');+ return this.$eval(selector, (element : HTMLSelectElement, values : string[]) => {+ if (element.nodeName.toLowerCase() !== 'select')+ throw new Error('Element is not a <select> element.');++ const options = Array.from(element.options);+ element.value = undefined;+ for (const option of options) {+ option.selected = values.includes(option.value);+ if (option.selected && !element.multiple)+ break;+ }+ element.dispatchEvent(new Event('input', { 'bubbles': true }));+ element.dispatchEvent(new Event('change', { 'bubbles': true }));+ return options.filter(option => option.selected).map(option => option.value);+ }, values) as Promise<string[]>;+ }++ async tap(selector: string) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.tap();+ await handle.dispose();+ }++ async type(selector: string, text: string, options: { delay: (number | undefined); } | undefined) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.type(text, options);+ await handle.dispose();+ }++ waitForSelector(selector: string, options: { timeout?: number; visible?: boolean; hidden?: boolean; } | undefined): Promise<ElementHandle> {+ return this._waitForSelectorOrXPath(selector, false, options);+ }++ waitForXPath(xpath: string, options: { timeout?: number; visible?: boolean; hidden?: boolean; } | undefined): Promise<ElementHandle> {+ return this._waitForSelectorOrXPath(xpath, true, options);+ }++ waitForFunction(pageFunction: Function | string, options: { polling?: string | number; timeout?: number; } | undefined = {}, ...args): Promise<JSHandle> {+ const {+ polling = 'raf',+ timeout = this._timeoutSettings.timeout(),+ } = options;+ return new WaitTask(this, pageFunction, 'function', polling, timeout, ...args).promise;+ }++ async title(): Promise<string> {+ return this.evaluate(() => document.title);+ }++ async _waitForSelectorOrXPath(selectorOrXPath: string, isXPath: boolean, options: { timeout?: number; visible?: boolean; hidden?: boolean; } | undefined = {}): Promise<ElementHandle> {+ const {+ visible: waitForVisible = false,+ hidden: waitForHidden = false,+ timeout = this._timeoutSettings.timeout(),+ } = options;+ const polling = waitForVisible || waitForHidden ? 'raf' : 'mutation';+ const title = `${isXPath ? 'XPath' : 'selector'} "${selectorOrXPath}"${waitForHidden ? ' to be hidden' : ''}`;+ const waitTask = new WaitTask(this, predicate, title, polling, timeout, selectorOrXPath, isXPath, waitForVisible, waitForHidden);+ const handle = await waitTask.promise;+ if (!handle.asElement()) {+ await handle.dispose();+ return null;+ }+ return handle.asElement();++ function predicate(selectorOrXPath: string, isXPath: boolean, waitForVisible: boolean, waitForHidden: boolean): (Node | boolean) | null {+ const node = isXPath+ ? document.evaluate(selectorOrXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue+ : document.querySelector(selectorOrXPath);+ if (!node)+ return waitForHidden;+ if (!waitForVisible && !waitForHidden)+ return node;+ const element: Element = node.nodeType === Node.TEXT_NODE ? node.parentElement : node as Element;++ const style = window.getComputedStyle(element);+ const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox();+ const success = (waitForVisible === isVisible || waitForHidden === !isVisible);+ return success ? node : null;++ function hasVisibleBoundingBox(): boolean {+ const rect = element.getBoundingClientRect();+ return !!(rect.top || rect.bottom || rect.width || rect.height);+ }+ }+ }+}++class WaitTask {+ promise: any;+ _domWorld: any;+ _polling: any;+ _timeout: any;+ _predicateBody: string;+ _args: any[];+ _runCount: number;+ _resolve: (value?: unknown) => void;+ _reject: (reason?: any) => void;+ _timeoutTimer: NodeJS.Timer;+ _terminated: boolean;+ _runningTask: any;+ constructor(domWorld: DOMWorld, predicateBody: Function | string, title, polling: string | number, timeout: number, ...args: Array<any>) {+ if (helper.isString(polling))+ assert(polling === 'raf' || polling === 'mutation', 'Unknown polling option: ' + polling);+ else if (helper.isNumber(polling))+ assert(polling > 0, 'Cannot poll with non-positive interval: ' + polling);+ else+ throw new Error('Unknown polling options: ' + polling);++ this._domWorld = domWorld;+ this._polling = polling;+ this._timeout = timeout;+ this._predicateBody = helper.isString(predicateBody) ? 'return (' + predicateBody + ')' : 'return (' + predicateBody + ')(...args)';+ this._args = args;+ this._runCount = 0;+ domWorld._waitTasks.add(this);+ this.promise = new Promise((resolve, reject) => {+ this._resolve = resolve;+ this._reject = reject;+ });+ // Since page navigation requires us to re-install the pageScript, we should track+ // timeout on our end.+ if (timeout) {+ const timeoutError = new TimeoutError(`waiting for ${title} failed: timeout ${timeout}ms exceeded`);+ this._timeoutTimer = setTimeout(() => this.terminate(timeoutError), timeout);+ }+ this.rerun();+ }++ terminate(error: Error) {+ this._terminated = true;+ this._reject(error);+ this._cleanup();+ }++ async rerun() {+ const runCount = ++this._runCount;+ let success: JSHandle | null = null;+ let error = null;+ try {+ success = await this._domWorld.evaluateHandle(waitForPredicatePageFunction, this._predicateBody, this._polling, this._timeout, ...this._args);+ } catch (e) {+ error = e;+ }++ if (this._terminated || runCount !== this._runCount) {+ if (success)+ await success.dispose();+ return;+ }++ // Ignore timeouts in pageScript - we track timeouts ourselves.+ // If the frame's execution context has already changed, `frame.evaluate` will+ // throw an error - ignore this predicate run altogether.+ if (!error && await this._domWorld.evaluate(s => !s, success).catch(e => true)) {+ await success.dispose();+ return;+ }++ // When the page is navigated, the promise is rejected.+ // Try again right away.+ if (error && error.message.includes('Execution context was destroyed')) {+ this.rerun();+ return;+ }++ if (error)+ this._reject(error);+ else+ this._resolve(success);++ this._cleanup();+ }++ _cleanup() {+ clearTimeout(this._timeoutTimer);+ this._domWorld._waitTasks.delete(this);+ this._runningTask = null;+ }+}++async function waitForPredicatePageFunction(predicateBody: string, polling: string, timeout: number, ...args): Promise<any> {+ const predicate = new Function('...args', predicateBody);+ let timedOut = false;+ if (timeout)+ setTimeout(() => timedOut = true, timeout);+ if (polling === 'raf')+ return await pollRaf();+ if (polling === 'mutation')+ return await pollMutation();+ if (typeof polling === 'number')+ return await pollInterval(polling);++ function pollMutation(): Promise<any> {+ const success = predicate.apply(null, args);+ if (success)+ return Promise.resolve(success);++ let fulfill;+ const result = new Promise(x => fulfill = x);+ const observer = new MutationObserver(mutations => {+ if (timedOut) {+ observer.disconnect();+ fulfill();+ }+ const success = predicate.apply(null, args);+ if (success) {+ observer.disconnect();+ fulfill(success);+ }+ });+ observer.observe(document, {+ childList: true,+ subtree: true,+ attributes: true+ });+ return result;+ }++ function pollRaf(): Promise<any> {+ let fulfill;+ const result = new Promise(x => fulfill = x);+ onRaf();+ return result;++ function onRaf() {+ if (timedOut) {+ fulfill();+ return;+ }+ const success = predicate.apply(null, args);+ if (success)+ fulfill(success);+ else+ requestAnimationFrame(onRaf);+ }+ }++ function pollInterval(pollInterval: number): Promise<any> {+ let fulfill;+ const result = new Promise(x => fulfill = x);+ onTimeout();+ return result;++ function onTimeout() {+ if (timedOut) {+ fulfill();+ return;+ }+ const success = predicate.apply(null, args);+ if (success)+ fulfill(success);+ else+ setTimeout(onTimeout, pollInterval);+ }+ }+}diff --git a/src/firefox/Dialog.ts b/src/firefox/Dialog.tsnew file mode 100644index 0000000000..ec3c236dec--- /dev/null+++ b/src/firefox/Dialog.ts@@ -0,0 +1,51 @@+import {assert, debugError} from '../helper';++export class Dialog {+ private _client: any;+ private _dialogId: any;+ private _type: string;+ private _message: string;+ private _handled: boolean;+ private _defaultValue: string;++ constructor(client, payload) {+ this._client = client;+ this._dialogId = payload.dialogId;+ this._type = payload.type;+ this._message = payload.message;+ this._handled = false;+ this._defaultValue = payload.defaultValue || '';+ }++ type(): string {+ return this._type;+ }++ message(): string {+ return this._message;+ }++ defaultValue(): string {+ return this._defaultValue;+ }++ async accept(promptText: string | undefined) {+ assert(!this._handled, 'Cannot accept dialog which is already handled!');+ this._handled = true;+ await this._client.send('Page.handleDialog', {+ dialogId: this._dialogId,+ accept: true,+ promptText: promptText+ }).catch(debugError);+ }++ async dismiss() {+ assert(!this._handled, 'Cannot dismiss dialog which is already handled!');+ this._handled = true;+ await this._client.send('Page.handleDialog', {+ dialogId: this._dialogId,+ accept: false+ }).catch(debugError);+ }+}+diff --git a/src/firefox/ExecutionContext.ts b/src/firefox/ExecutionContext.tsnew file mode 100644index 0000000000..9693553abb--- /dev/null+++ b/src/firefox/ExecutionContext.ts@@ -0,0 +1,100 @@+import {helper} from '../helper';+import {JSHandle, createHandle} from './JSHandle';+import { Frame } from './FrameManager';++export class ExecutionContext {+ _session: any;+ _frame: Frame;+ _executionContextId: string;+ constructor(session: any, frame: Frame | null, executionContextId: string) {+ this._session = session;+ this._frame = frame;+ this._executionContextId = executionContextId;+ }++ async evaluateHandle(pageFunction, ...args) {+ if (helper.isString(pageFunction)) {+ const payload = await this._session.send('Runtime.evaluate', {+ expression: pageFunction,+ executionContextId: this._executionContextId,+ }).catch(rewriteError);+ return createHandle(this, payload.result, payload.exceptionDetails);+ }+ if (typeof pageFunction !== 'function')+ throw new Error(`Expected to get |string| or |function| as the first argument, but got "${pageFunction}" instead.`);++ let functionText = pageFunction.toString();+ try {+ new Function('(' + functionText + ')');+ } catch (e1) {+ // This means we might have a function shorthand. Try another+ // time prefixing 'function '.+ if (functionText.startsWith('async '))+ functionText = 'async function ' + functionText.substring('async '.length);+ else+ functionText = 'function ' + functionText;+ try {+ new Function('(' + functionText + ')');+ } catch (e2) {+ // We tried hard to serialize, but there's a weird beast here.+ throw new Error('Passed function is not well-serializable!');+ }+ }+ args = args.map(arg => {+ if (arg instanceof JSHandle) {+ if (arg._context !== this)+ throw new Error('JSHandles can be evaluated only in the context they were created!');+ if (arg._disposed)+ throw new Error('JSHandle is disposed!');+ return arg._protocolValue;+ }+ if (Object.is(arg, Infinity))+ return {unserializableValue: 'Infinity'};+ if (Object.is(arg, -Infinity))+ return {unserializableValue: '-Infinity'};+ if (Object.is(arg, -0))+ return {unserializableValue: '-0'};+ if (Object.is(arg, NaN))+ return {unserializableValue: 'NaN'};+ return {value: arg};+ });+ let callFunctionPromise;+ try {+ callFunctionPromise = this._session.send('Runtime.callFunction', {+ functionDeclaration: functionText,+ args,+ executionContextId: this._executionContextId+ });+ } catch (err) {+ if (err instanceof TypeError && err.message.startsWith('Converting circular structure to JSON'))+ err.message += ' Are you passing a nested JSHandle?';+ throw err;+ }+ const payload = await callFunctionPromise.catch(rewriteError);+ return createHandle(this, payload.result, payload.exceptionDetails);++ function rewriteError(error) {+ if (error.message.includes('Failed to find execution context with id'))+ throw new Error('Execution context was destroyed, most likely because of a navigation.');+ throw error;+ }+ }++ frame() {+ return this._frame;+ }++ async evaluate(pageFunction, ...args) {+ try {+ const handle = await this.evaluateHandle(pageFunction, ...args);+ const result = await handle.jsonValue();+ await handle.dispose();+ return result;+ } catch (e) {+ if (e.message.includes('cyclic object value') || e.message.includes('Object is not serializable'))+ return undefined;+ throw e;+ }+ }++}diff --git a/src/firefox/FrameManager.ts b/src/firefox/FrameManager.tsnew file mode 100644index 0000000000..1062c534ea--- /dev/null+++ b/src/firefox/FrameManager.ts@@ -0,0 +1,394 @@+import { JugglerSession } from './Connection';+import { Page } from './Page';++import {RegisteredListener, helper, assert} from '../helper';+import {TimeoutError} from '../Errors';+import {EventEmitter} from 'events';+import {ExecutionContext} from './ExecutionContext';+import {NavigationWatchdog, NextNavigationWatchdog} from './NavigationWatchdog';+import {DOMWorld} from './DOMWorld';+import { JSHandle, ElementHandle } from './JSHandle';++export const FrameManagerEvents = {+ FrameNavigated: Symbol('FrameManagerEvents.FrameNavigated'),+ FrameAttached: Symbol('FrameManagerEvents.FrameAttached'),+ FrameDetached: Symbol('FrameManagerEvents.FrameDetached'),+ Load: Symbol('FrameManagerEvents.Load'),+ DOMContentLoaded: Symbol('FrameManagerEvents.DOMContentLoaded'),+};+export class FrameManager extends EventEmitter {+ _session: JugglerSession;+ _page: Page;+ _networkManager: any;+ _timeoutSettings: any;+ _mainFrame: any;+ _frames: Map<string, Frame>;+ _contextIdToContext: Map<string, ExecutionContext>;+ _eventListeners: RegisteredListener[];+ constructor(session: JugglerSession, page: Page, networkManager, timeoutSettings) {+ super();+ this._session = session;+ this._page = page;+ this._networkManager = networkManager;+ this._timeoutSettings = timeoutSettings;+ this._mainFrame = null;+ this._frames = new Map();+ this._contextIdToContext = new Map();+ this._eventListeners = [+ helper.addEventListener(this._session, 'Page.eventFired', this._onEventFired.bind(this)),+ helper.addEventListener(this._session, 'Page.frameAttached', this._onFrameAttached.bind(this)),+ helper.addEventListener(this._session, 'Page.frameDetached', this._onFrameDetached.bind(this)),+ helper.addEventListener(this._session, 'Page.navigationCommitted', this._onNavigationCommitted.bind(this)),+ helper.addEventListener(this._session, 'Page.sameDocumentNavigation', this._onSameDocumentNavigation.bind(this)),+ helper.addEventListener(this._session, 'Runtime.executionContextCreated', this._onExecutionContextCreated.bind(this)),+ helper.addEventListener(this._session, 'Runtime.executionContextDestroyed', this._onExecutionContextDestroyed.bind(this)),+ ];+ }++ executionContextById(executionContextId) {+ return this._contextIdToContext.get(executionContextId) || null;+ }++ _onExecutionContextCreated({executionContextId, auxData}) {+ const frameId = auxData ? auxData.frameId : null;+ const frame = this._frames.get(frameId) || null;+ const context = new ExecutionContext(this._session, frame, executionContextId);+ if (frame)+ frame._mainWorld._setContext(context);+ this._contextIdToContext.set(executionContextId, context);+ }++ _onExecutionContextDestroyed({executionContextId}) {+ const context = this._contextIdToContext.get(executionContextId);+ if (!context)+ return;+ this._contextIdToContext.delete(executionContextId);+ if (context._frame)+ context._frame._mainWorld._setContext(null);+ }++ frame(frameId) {+ return this._frames.get(frameId);+ }++ mainFrame() {+ return this._mainFrame;+ }++ frames() {+ const frames: Array<Frame> = [];+ collect(this._mainFrame);+ return frames;++ function collect(frame) {+ frames.push(frame);+ for (const subframe of frame._children)+ collect(subframe);+ }+ }++ _onNavigationCommitted(params) {+ const frame = this._frames.get(params.frameId);+ frame._navigated(params.url, params.name, params.navigationId);+ this.emit(FrameManagerEvents.FrameNavigated, frame);+ }++ _onSameDocumentNavigation(params) {+ const frame = this._frames.get(params.frameId);+ frame._url = params.url;+ this.emit(FrameManagerEvents.FrameNavigated, frame);+ }++ _onFrameAttached(params) {+ const frame = new Frame(this._session, this, this._networkManager, this._page, params.frameId, this._timeoutSettings);+ const parentFrame = this._frames.get(params.parentFrameId) || null;+ if (parentFrame) {+ frame._parentFrame = parentFrame;+ parentFrame._children.add(frame);+ } else {+ assert(!this._mainFrame, 'INTERNAL ERROR: re-attaching main frame!');+ this._mainFrame = frame;+ }+ this._frames.set(params.frameId, frame);+ this.emit(FrameManagerEvents.FrameAttached, frame);+ }++ _onFrameDetached(params) {+ const frame = this._frames.get(params.frameId);+ this._frames.delete(params.frameId);+ frame._detach();+ this.emit(FrameManagerEvents.FrameDetached, frame);+ }++ _onEventFired({frameId, name}) {+ const frame = this._frames.get(frameId);+ frame._firedEvents.add(name.toLowerCase());+ if (frame === this._mainFrame) {+ if (name === 'load')+ this.emit(FrameManagerEvents.Load);+ else if (name === 'DOMContentLoaded')+ this.emit(FrameManagerEvents.DOMContentLoaded);+ }+ }++ dispose() {+ helper.removeEventListeners(this._eventListeners);+ }+}++export class Frame {+ _parentFrame: Frame|null = null;+ private _session: JugglerSession;+ _page: any;+ _frameManager: FrameManager;+ private _networkManager: any;+ private _timeoutSettings: any;+ _frameId: string;+ _url: string = '';+ private _name: string = '';+ _children: Set<Frame>;+ private _detached: boolean;+ _firedEvents: Set<string>;+ _mainWorld: any;+ _lastCommittedNavigationId: any;+ constructor(session: JugglerSession, frameManager : FrameManager, networkManager, page: Page, frameId: string, timeoutSettings) {+ this._session = session;+ this._page = page;+ this._frameManager = frameManager;+ this._networkManager = networkManager;+ this._timeoutSettings = timeoutSettings;+ this._frameId = frameId;+ this._children = new Set();+ this._detached = false;+++ this._firedEvents = new Set();++ this._mainWorld = new DOMWorld(this, timeoutSettings);+ }++ async executionContext() {+ return this._mainWorld.executionContext();+ }++ async waitForNavigation(options: { timeout?: number; waitUntil?: string | Array<string>; } = {}) {+ const {+ timeout = this._timeoutSettings.navigationTimeout(),+ waitUntil = ['load'],+ } = options;+ const normalizedWaitUntil = normalizeWaitUntil(waitUntil);++ const timeoutError = new TimeoutError('Navigation timeout of ' + timeout + ' ms exceeded');+ let timeoutCallback;+ const timeoutPromise = new Promise(resolve => timeoutCallback = resolve.bind(null, timeoutError));+ const timeoutId = timeout ? setTimeout(timeoutCallback, timeout) : null;++ const nextNavigationDog = new NextNavigationWatchdog(this._session, this);+ const error1 = await Promise.race([+ nextNavigationDog.promise(),+ timeoutPromise,+ ]);+ nextNavigationDog.dispose();++ // If timeout happened first - throw.+ if (error1) {+ clearTimeout(timeoutId);+ throw error1;+ }++ const {navigationId, url} = nextNavigationDog.navigation();++ if (!navigationId) {+ // Same document navigation happened.+ clearTimeout(timeoutId);+ return null;+ }++ const watchDog = new NavigationWatchdog(this._session, this, this._networkManager, navigationId, url, normalizedWaitUntil);+ const error = await Promise.race([+ timeoutPromise,+ watchDog.promise(),+ ]);+ watchDog.dispose();+ clearTimeout(timeoutId);+ if (error)+ throw error;+ return watchDog.navigationResponse();+ }++ async goto(url: string, options: { timeout?: number; waitUntil?: string | Array<string>; referer?: string; } = {}) {+ const {+ timeout = this._timeoutSettings.navigationTimeout(),+ waitUntil = ['load'],+ referer,+ } = options;+ const normalizedWaitUntil = normalizeWaitUntil(waitUntil);+ const {navigationId} = await this._session.send('Page.navigate', {+ frameId: this._frameId,+ referer,+ url,+ });+ if (!navigationId)+ return;++ const timeoutError = new TimeoutError('Navigation timeout of ' + timeout + ' ms exceeded');+ let timeoutCallback;+ const timeoutPromise = new Promise(resolve => timeoutCallback = resolve.bind(null, timeoutError));+ const timeoutId = timeout ? setTimeout(timeoutCallback, timeout) : null;++ const watchDog = new NavigationWatchdog(this._session, this, this._networkManager, navigationId, url, normalizedWaitUntil);+ const error = await Promise.race([+ timeoutPromise,+ watchDog.promise(),+ ]);+ watchDog.dispose();+ clearTimeout(timeoutId);+ if (error)+ throw error;+ return watchDog.navigationResponse();+ }++ async click(selector: string, options: { delay?: number; button?: string; clickCount?: number; } | undefined = {}) {+ return this._mainWorld.click(selector, options);+ }++ async tap(selector: string) {+ return this._mainWorld.tap(selector);+ }++ async type(selector: string, text: string, options: { delay: (number | undefined); } | undefined) {+ return this._mainWorld.type(selector, text, options);+ }++ async focus(selector: string) {+ return this._mainWorld.focus(selector);+ }++ async hover(selector: string) {+ return this._mainWorld.hover(selector);+ }++ _detach() {+ this._parentFrame._children.delete(this);+ this._parentFrame = null;+ this._detached = true;+ this._mainWorld._detach();+ }++ _navigated(url, name, navigationId) {+ this._url = url;+ this._name = name;+ this._lastCommittedNavigationId = navigationId;+ this._firedEvents.clear();+ }++ select(selector: string, ...values: Array<string>): Promise<Array<string>> {+ return this._mainWorld.select(selector, ...values);+ }++ waitFor(selectorOrFunctionOrTimeout: (string | number | Function), options: { polling?: string | number; timeout?: number; visible?: boolean; hidden?: boolean; } | undefined, ...args: Array<any>): Promise<JSHandle> {+ const xPathPattern = '//';++ if (helper.isString(selectorOrFunctionOrTimeout)) {+ const string = selectorOrFunctionOrTimeout;+ if (string.startsWith(xPathPattern))+ return this.waitForXPath(string, options);+ return this.waitForSelector(string, options);+ }+ if (helper.isNumber(selectorOrFunctionOrTimeout))+ return new Promise(fulfill => setTimeout(fulfill, selectorOrFunctionOrTimeout));+ if (typeof selectorOrFunctionOrTimeout === 'function')+ return this.waitForFunction(selectorOrFunctionOrTimeout, options, ...args);+ return Promise.reject(new Error('Unsupported target type: ' + (typeof selectorOrFunctionOrTimeout)));+ }++ waitForFunction(pageFunction: Function | string, options: { polling?: string | number; timeout?: number; } | undefined = {}, ...args): Promise<JSHandle> {+ return this._mainWorld.waitForFunction(pageFunction, options, ...args);+ }++ waitForSelector(selector: string, options: { timeout?: number; visible?: boolean; hidden?: boolean; } | undefined): Promise<ElementHandle> {+ return this._mainWorld.waitForSelector(selector, options);+ }++ waitForXPath(xpath: string, options: { timeout?: number; visible?: boolean; hidden?: boolean; } | undefined): Promise<ElementHandle> {+ return this._mainWorld.waitForXPath(xpath, options);+ }++ async content(): Promise<string> {+ return this._mainWorld.content();+ }++ async setContent(html: string) {+ return this._mainWorld.setContent(html);+ }++ async evaluate(pageFunction, ...args) {+ return this._mainWorld.evaluate(pageFunction, ...args);+ }++ async $(selector: string): Promise<ElementHandle | null> {+ return this._mainWorld.$(selector);+ }++ async $$(selector: string): Promise<Array<ElementHandle>> {+ return this._mainWorld.$$(selector);+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: Array<any>): Promise<(object | undefined)> {+ return this._mainWorld.$eval(selector, pageFunction, ...args);+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: Array<any>): Promise<(object | undefined)> {+ return this._mainWorld.$$eval(selector, pageFunction, ...args);+ }++ async $x(expression: string): Promise<Array<ElementHandle>> {+ return this._mainWorld.$x(expression);+ }++ async evaluateHandle(pageFunction, ...args) {+ return this._mainWorld.evaluateHandle(pageFunction, ...args);+ }++ async addScriptTag(options: { content?: string; path?: string; type?: string; url?: string; }): Promise<ElementHandle> {+ return this._mainWorld.addScriptTag(options);+ }++ async addStyleTag(options: { content?: string; path?: string; url?: string; }): Promise<ElementHandle> {+ return this._mainWorld.addStyleTag(options);+ }++ async title(): Promise<string> {+ return this._mainWorld.title();+ }++ name() {+ return this._name;+ }++ isDetached() {+ return this._detached;+ }++ childFrames() {+ return Array.from(this._children);+ }++ url() {+ return this._url;+ }++ parentFrame() {+ return this._parentFrame;+ }+}++export function normalizeWaitUntil(waitUntil) {+ if (!Array.isArray(waitUntil))+ waitUntil = [waitUntil];+ for (const condition of waitUntil) {+ if (condition !== 'load' && condition !== 'domcontentloaded')+ throw new Error('Unknown waitUntil condition: ' + condition);+ }+ return waitUntil;+}diff --git a/src/firefox/Input.ts b/src/firefox/Input.tsnew file mode 100644index 0000000000..a613378d4b--- /dev/null+++ b/src/firefox/Input.ts@@ -0,0 +1,292 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the 'License');+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an 'AS IS' BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { keyDefinitions } from '../USKeyboardLayout';+import { JugglerSession } from './Connection';++interface KeyDescription {+ keyCode: number;+ key: string;+ text: string;+ code: string;+ location: number;+}++export class Keyboard {+ _client: JugglerSession;+ _modifiers: number;+ _pressedKeys: Set<string>;+ constructor(client: JugglerSession) {+ this._client = client;+ this._modifiers = 0;+ this._pressedKeys = new Set();+ }++ async down(key: string) {+ const description = this._keyDescriptionForString(key);++ const repeat = this._pressedKeys.has(description.code);+ this._pressedKeys.add(description.code);+ this._modifiers |= this._modifierBit(description.key);++ await this._client.send('Page.dispatchKeyEvent', {+ type: 'keydown',+ keyCode: description.keyCode,+ code: description.code,+ key: description.key,+ repeat,+ location: description.location+ });+ }++ _modifierBit(key: string): number {+ if (key === 'Alt')+ return 1;+ if (key === 'Control')+ return 2;+ if (key === 'Shift')+ return 4;+ if (key === 'Meta')+ return 8;+ return 0;+ }++ _keyDescriptionForString(keyString: string): KeyDescription {+ const shift = this._modifiers & 8;+ const description = {+ key: '',+ keyCode: 0,+ code: '',+ text: '',+ location: 0+ };+ const definition = keyDefinitions[keyString];+ if (!definition)+ throw new Error(`Unknown key: "${keyString}"`);++ if (definition.key)+ description.key = definition.key;+ if (shift && definition.shiftKey)+ description.key = definition.shiftKey;++ if (definition.keyCode)+ description.keyCode = definition.keyCode;+ if (shift && definition.shiftKeyCode)+ description.keyCode = definition.shiftKeyCode;++ if (definition.code)+ description.code = definition.code;++ if (definition.location)+ description.location = definition.location;++ if (description.key.length === 1)+ description.text = description.key;++ if (definition.text)+ description.text = definition.text;+ if (shift && definition.shiftText)+ description.text = definition.shiftText;++ // if any modifiers besides shift are pressed, no text should be sent+ if (this._modifiers & ~8)+ description.text = '';++ if (description.code === 'MetaLeft')+ description.code = 'OSLeft';+ if (description.code === 'MetaRight')+ description.code = 'OSRight';+ return description;+ }++ async up(key: string) {+ const description = this._keyDescriptionForString(key);++ this._modifiers &= ~this._modifierBit(description.key);+ this._pressedKeys.delete(description.code);+ await this._client.send('Page.dispatchKeyEvent', {+ type: 'keyup',+ key: description.key,+ keyCode: description.keyCode,+ code: description.code,+ location: description.location,+ repeat: false+ });+ }++ async sendCharacter(char: string) {+ await this._client.send('Page.insertText', {+ text: char+ });+ }++ async type(text: string, options: { delay?: number; } | undefined = {}) {+ const {delay = null} = options;+ for (const char of text) {+ if (keyDefinitions[char])+ await this.press(char, {delay});+ else+ await this.sendCharacter(char);+ if (delay !== null)+ await new Promise(f => setTimeout(f, delay));+ }+ }++ async press(key: string, options: { delay?: number; } | undefined = {}) {+ const {delay = null} = options;+ await this.down(key);+ if (delay !== null)+ await new Promise(f => setTimeout(f, options.delay));+ await this.up(key);+ }+}++export class Mouse {+ _client: any;+ _keyboard: Keyboard;+ _x: number;+ _y: number;+ _buttons: number;+ constructor(client, keyboard: Keyboard) {+ this._client = client;+ this._keyboard = keyboard;+ this._x = 0;+ this._y = 0;+ this._buttons = 0;+ }++ async move(x: number, y: number, options: { steps?: number; } | undefined = {}) {+ const {steps = 1} = options;+ const fromX = this._x, fromY = this._y;+ this._x = x;+ this._y = y;+ for (let i = 1; i <= steps; i++) {+ await this._client.send('Page.dispatchMouseEvent', {+ type: 'mousemove',+ button: 0,+ x: fromX + (this._x - fromX) * (i / steps),+ y: fromY + (this._y - fromY) * (i / steps),+ modifiers: this._keyboard._modifiers,+ buttons: this._buttons,+ });+ }+ }++ async click(x: number, y: number, options: { delay?: number; button?: string; clickCount?: number; } | undefined = {}) {+ const {delay = null} = options;+ if (delay !== null) {+ await Promise.all([+ this.move(x, y),+ this.down(options),+ ]);+ await new Promise(f => setTimeout(f, delay));+ await this.up(options);+ } else {+ await Promise.all([+ this.move(x, y),+ this.down(options),+ this.up(options),+ ]);+ }+ }++ async down(options: { button?: string; clickCount?: number; } | undefined = {}) {+ const {+ button = 'left',+ clickCount = 1+ } = options;+ if (button === 'left')+ this._buttons |= 1;+ if (button === 'right')+ this._buttons |= 2;+ if (button === 'middle')+ this._buttons |= 4;+ await this._client.send('Page.dispatchMouseEvent', {+ type: 'mousedown',+ button: this._buttonNameToButton(button),+ x: this._x,+ y: this._y,+ modifiers: this._keyboard._modifiers,+ clickCount,+ buttons: this._buttons,+ });+ }++ _buttonNameToButton(buttonName: string): number {+ if (buttonName === 'left')+ return 0;+ if (buttonName === 'middle')+ return 1;+ if (buttonName === 'right')+ return 2;+ }++ async up(options: { button?: string; clickCount?: number; } | undefined = {}) {+ const {+ button = 'left',+ clickCount = 1+ } = options;+ if (button === 'left')+ this._buttons &= ~1;+ if (button === 'right')+ this._buttons &= ~2;+ if (button === 'middle')+ this._buttons &= ~4;+ await this._client.send('Page.dispatchMouseEvent', {+ type: 'mouseup',+ button: this._buttonNameToButton(button),+ x: this._x,+ y: this._y,+ modifiers: this._keyboard._modifiers,+ clickCount: clickCount,+ buttons: this._buttons,+ });+ }+}++export class Touchscreen {+ _client: JugglerSession;+ _keyboard: Keyboard;+ _mouse: Mouse;+ constructor(client: JugglerSession, keyboard: Keyboard, mouse: Mouse) {+ this._client = client;+ this._keyboard = keyboard;+ this._mouse = mouse;+ }++ async tap(x: number, y: number) {+ const touchPoints = [{x: Math.round(x), y: Math.round(y)}];+ let {defaultPrevented} = (await this._client.send('Page.dispatchTouchEvent', {+ type: 'touchStart',+ touchPoints,+ modifiers: this._keyboard._modifiers+ }));+ defaultPrevented = (await this._client.send('Page.dispatchTouchEvent', {+ type: 'touchEnd',+ touchPoints,+ modifiers: this._keyboard._modifiers+ })).defaultPrevented || defaultPrevented;+ // Do not dispatch related mouse events if either of touch events+ // were prevented.+ // See https://developer.mozilla.org/en-US/docs/Web/API/Touch_events/Supporting_both_TouchEvent_and_MouseEvent#Event_order+ if (defaultPrevented)+ return;+ await this._mouse.move(x, y);+ await this._mouse.down();+ await this._mouse.up();+ }+}diff --git a/src/firefox/JSHandle.ts b/src/firefox/JSHandle.tsnew file mode 100644index 0000000000..8d5b99e5dd--- /dev/null+++ b/src/firefox/JSHandle.ts@@ -0,0 +1,360 @@+import {assert, debugError} from '../helper';+import * as path from 'path';+import {ExecutionContext} from './ExecutionContext';+import {Frame} from './FrameManager';++export class JSHandle {+ _context: ExecutionContext;+ _session: any;+ _executionContextId: any;+ _objectId: any;+ _type: any;+ _subtype: any;+ _disposed: boolean;+ _protocolValue: { unserializableValue: any; value: any; objectId: any; };+ constructor(context: ExecutionContext, payload: any) {+ this._context = context;+ this._session = this._context._session;+ this._executionContextId = this._context._executionContextId;+ this._objectId = payload.objectId;+ this._type = payload.type;+ this._subtype = payload.subtype;+ this._disposed = false;+ this._protocolValue = {+ unserializableValue: payload.unserializableValue,+ value: payload.value,+ objectId: payload.objectId,+ };+ }++ executionContext(): ExecutionContext {+ return this._context;+ }++ toString(): string {+ if (this._objectId)+ return 'JSHandle@' + (this._subtype || this._type);+ return 'JSHandle:' + this._deserializeValue(this._protocolValue);+ }++ async getProperty(propertyName: string): Promise<JSHandle | null> {+ const objectHandle = await this._context.evaluateHandle((object, propertyName) => {+ const result = {__proto__: null};+ result[propertyName] = object[propertyName];+ return result;+ }, this, propertyName);+ const properties = await objectHandle.getProperties();+ const result = properties.get(propertyName) || null;+ await objectHandle.dispose();+ return result;+ }++ async getProperties(): Promise<Map<string, JSHandle>> {+ const response = await this._session.send('Runtime.getObjectProperties', {+ executionContextId: this._executionContextId,+ objectId: this._objectId,+ });+ const result = new Map();+ for (const property of response.properties)+ result.set(property.name, createHandle(this._context, property.value, null));++ return result;+ }++ _deserializeValue({unserializableValue, value}) {+ if (unserializableValue === 'Infinity')+ return Infinity;+ if (unserializableValue === '-Infinity')+ return -Infinity;+ if (unserializableValue === '-0')+ return -0;+ if (unserializableValue === 'NaN')+ return NaN;+ return value;+ }++ async jsonValue() {+ if (!this._objectId)+ return this._deserializeValue(this._protocolValue);+ const simpleValue = await this._session.send('Runtime.callFunction', {+ executionContextId: this._executionContextId,+ returnByValue: true,+ functionDeclaration: (e => e).toString(),+ args: [this._protocolValue],+ });+ return this._deserializeValue(simpleValue.result);+ }++ asElement(): ElementHandle | null {+ return null;+ }++ async dispose() {+ if (!this._objectId)+ return;+ this._disposed = true;+ await this._session.send('Runtime.disposeObject', {+ executionContextId: this._executionContextId,+ objectId: this._objectId,+ }).catch(error => {+ // Exceptions might happen in case of a page been navigated or closed.+ // Swallow these since they are harmless and we don't leak anything in this case.+ debugError(error);+ });+ }+}++export class ElementHandle extends JSHandle {+ _frame: Frame;+ _frameId: any;+ constructor(frame: Frame, context: ExecutionContext, payload: any) {+ super(context, payload);+ this._frame = frame;+ this._frameId = frame._frameId;+ }++ async contentFrame(): Promise<Frame | null> {+ const {frameId} = await this._session.send('Page.contentFrame', {+ frameId: this._frameId,+ objectId: this._objectId,+ });+ if (!frameId)+ return null;+ const frame = this._frame._frameManager.frame(frameId);+ return frame;+ }++ asElement(): ElementHandle {+ return this;+ }++ async boundingBox(): Promise<{ width: number; height: number; x: number; y: number; }> {+ return await this._session.send('Page.getBoundingBox', {+ frameId: this._frameId,+ objectId: this._objectId,+ });+ }++ async screenshot(options: { encoding?: string; path?: string; } = {}) {+ const clip = await this._session.send('Page.getBoundingBox', {+ frameId: this._frameId,+ objectId: this._objectId,+ });+ if (!clip)+ throw new Error('Node is either not visible or not an HTMLElement');+ assert(clip.width, 'Node has 0 width.');+ assert(clip.height, 'Node has 0 height.');+ await this._scrollIntoViewIfNeeded();++ return await this._frame._page.screenshot(Object.assign({}, options, {+ clip: {+ x: clip.x,+ y: clip.y,+ width: clip.width,+ height: clip.height,+ },+ }));+ }++ isIntersectingViewport(): Promise<boolean> {+ return this._frame.evaluate(async element => {+ const visibleRatio = await new Promise(resolve => {+ const observer = new IntersectionObserver(entries => {+ resolve(entries[0].intersectionRatio);+ observer.disconnect();+ });+ observer.observe(element);+ // Firefox doesn't call IntersectionObserver callback unless+ // there are rafs.+ requestAnimationFrame(() => {});+ });+ return visibleRatio > 0;+ }, this);+ }++ async $(selector: string): Promise<ElementHandle | null> {+ const handle = await this._frame.evaluateHandle(+ (element, selector) => element.querySelector(selector),+ this, selector+ );+ const element = handle.asElement();+ if (element)+ return element;+ await handle.dispose();+ return null;+ }++ async $$(selector: string): Promise<Array<ElementHandle>> {+ const arrayHandle = await this._frame.evaluateHandle(+ (element, selector) => element.querySelectorAll(selector),+ this, selector+ );+ const properties = await arrayHandle.getProperties();+ await arrayHandle.dispose();+ const result = [];+ for (const property of properties.values()) {+ const elementHandle = property.asElement();+ if (elementHandle)+ result.push(elementHandle);+ }+ return result;+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: Array<any>): Promise<(object | undefined)> {+ const elementHandle = await this.$(selector);+ if (!elementHandle)+ throw new Error(`Error: failed to find element matching selector "${selector}"`);+ const result = await this._frame.evaluate(pageFunction, elementHandle, ...args);+ await elementHandle.dispose();+ return result;+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: Array<any>): Promise<(object | undefined)> {+ const arrayHandle = await this._frame.evaluateHandle(+ (element, selector) => Array.from(element.querySelectorAll(selector)),+ this, selector+ );++ const result = await this._frame.evaluate(pageFunction, arrayHandle, ...args);+ await arrayHandle.dispose();+ return result;+ }++ async $x(expression: string): Promise<Array<ElementHandle>> {+ const arrayHandle = await this._frame.evaluateHandle(+ (element, expression) => {+ const document = element.ownerDocument || element;+ const iterator = document.evaluate(expression, element, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);+ const array = [];+ let item;+ while ((item = iterator.iterateNext()))+ array.push(item);+ return array;+ },+ this, expression+ );+ const properties = await arrayHandle.getProperties();+ await arrayHandle.dispose();+ const result = [];+ for (const property of properties.values()) {+ const elementHandle = property.asElement();+ if (elementHandle)+ result.push(elementHandle);+ }+ return result;+ }++ async _scrollIntoViewIfNeeded() {+ const error = await this._frame.evaluate(async element => {+ if (!element.isConnected)+ return 'Node is detached from document';+ if (element.nodeType !== Node.ELEMENT_NODE)+ return 'Node is not of type HTMLElement';+ const visibleRatio = await new Promise(resolve => {+ const observer = new IntersectionObserver(entries => {+ resolve(entries[0].intersectionRatio);+ observer.disconnect();+ });+ observer.observe(element);+ // Firefox doesn't call IntersectionObserver callback unless+ // there are rafs.+ requestAnimationFrame(() => {});+ });+ if (visibleRatio !== 1.0)+ element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});+ return false;+ }, this);+ if (error)+ throw new Error(error);+ }++ async click(options: { delay?: number; button?: string; clickCount?: number; } | undefined) {+ await this._scrollIntoViewIfNeeded();+ const {x, y} = await this._clickablePoint();+ await this._frame._page.mouse.click(x, y, options);+ }++ async tap() {+ await this._scrollIntoViewIfNeeded();+ const {x, y} = await this._clickablePoint();+ await this._frame._page.touchscreen.tap(x, y);+ }++ async uploadFile(...filePaths: Array<string>) {+ const files = filePaths.map(filePath => path.resolve(filePath));+ await this._session.send('Page.setFileInputFiles', {+ frameId: this._frameId,+ objectId: this._objectId,+ files,+ });+ }++ async hover() {+ await this._scrollIntoViewIfNeeded();+ const {x, y} = await this._clickablePoint();+ await this._frame._page.mouse.move(x, y);+ }++ async focus() {+ await this._frame.evaluate(element => element.focus(), this);+ }++ async type(text: string, options: { delay: (number | undefined); } | undefined) {+ await this.focus();+ await this._frame._page.keyboard.type(text, options);+ }++ async press(key: string, options: { delay?: number; } | undefined) {+ await this.focus();+ await this._frame._page.keyboard.press(key, options);+ }+++ async _clickablePoint(): Promise<{ x: number; y: number; }> {+ const result = await this._session.send('Page.getContentQuads', {+ frameId: this._frameId,+ objectId: this._objectId,+ }).catch(debugError);+ if (!result || !result.quads.length)+ throw new Error('Node is either not visible or not an HTMLElement');+ // Filter out quads that have too small area to click into.+ const quads = result.quads.filter(quad => computeQuadArea(quad) > 1);+ if (!quads.length)+ throw new Error('Node is either not visible or not an HTMLElement');+ // Return the middle point of the first quad.+ return computeQuadCenter(quads[0]);+ }+}++export function createHandle(context: ExecutionContext, result: any, exceptionDetails?: any) {+ const frame = context.frame();+ if (exceptionDetails) {+ if (exceptionDetails.value)+ throw new Error('Evaluation failed: ' + JSON.stringify(exceptionDetails.value));+ else+ throw new Error('Evaluation failed: ' + exceptionDetails.text + '\n' + exceptionDetails.stack);+ }+ return result.subtype === 'node' ? new ElementHandle(frame, context, result) : new JSHandle(context, result);+}++function computeQuadArea(quad) {+ // Compute sum of all directed areas of adjacent triangles+ // https://en.wikipedia.org/wiki/Polygon#Simple_polygons+ let area = 0;+ const points = [quad.p1, quad.p2, quad.p3, quad.p4];+ for (let i = 0; i < points.length; ++i) {+ const p1 = points[i];+ const p2 = points[(i + 1) % points.length];+ area += (p1.x * p2.y - p2.x * p1.y) / 2;+ }+ return Math.abs(area);+}++function computeQuadCenter(quad) {+ let x = 0, y = 0;+ for (const point of [quad.p1, quad.p2, quad.p3, quad.p4]) {+ x += point.x;+ y += point.y;+ }+ return {x: x / 4, y: y / 4};+}diff --git a/src/firefox/Launcher.ts b/src/firefox/Launcher.tsnew file mode 100644index 0000000000..30cdcd6df2--- /dev/null+++ b/src/firefox/Launcher.ts@@ -0,0 +1,268 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import * as os from 'os';+import * as path from 'path';+import * as removeFolder from 'rimraf';+import * as childProcess from 'child_process';+import {Connection} from './Connection';+import {Browser} from './Browser';+import {BrowserFetcher} from './BrowserFetcher';+import * as readline from 'readline';+import * as fs from 'fs';+import * as util from 'util';+import {helper, debugError} from '../helper';+import {TimeoutError} from '../Errors';+import {WebSocketTransport} from './WebSocketTransport';++const mkdtempAsync = util.promisify(fs.mkdtemp);+const removeFolderAsync = util.promisify(removeFolder);++const FIREFOX_PROFILE_PATH = path.join(os.tmpdir(), 'playwright_firefox_profile-');++const DEFAULT_ARGS = [+ '-no-remote',+ '-foreground',+];++export class Launcher {+ private _projectRoot: string;+ private _preferredRevision: string;+ constructor(projectRoot, preferredRevision) {+ this._projectRoot = projectRoot;+ this._preferredRevision = preferredRevision;+ }++ defaultArgs(options: any = {}) {+ const {+ headless = true,+ args = [],+ userDataDir = null,+ } = options;+ const firefoxArguments = [...DEFAULT_ARGS];+ if (userDataDir)+ firefoxArguments.push('-profile', userDataDir);+ if (headless)+ firefoxArguments.push('-headless');+ firefoxArguments.push(...args);+ if (args.every(arg => arg.startsWith('-')))+ firefoxArguments.push('about:blank');+ return firefoxArguments;+ }++ async launch(options: any = {}): Promise<Browser> {+ const {+ ignoreDefaultArgs = false,+ args = [],+ dumpio = false,+ executablePath = null,+ env = process.env,+ handleSIGHUP = true,+ handleSIGINT = true,+ handleSIGTERM = true,+ ignoreHTTPSErrors = false,+ defaultViewport = {width: 800, height: 600},+ slowMo = 0,+ timeout = 30000,+ } = options;++ const firefoxArguments = [];+ if (!ignoreDefaultArgs)+ firefoxArguments.push(...this.defaultArgs(options));+ else if (Array.isArray(ignoreDefaultArgs))+ firefoxArguments.push(...this.defaultArgs(options).filter(arg => !ignoreDefaultArgs.includes(arg)));+ else+ firefoxArguments.push(...args);++ if (!firefoxArguments.includes('-juggler'))+ firefoxArguments.push('-juggler', '0');++ let temporaryProfileDir = null;+ if (!firefoxArguments.includes('-profile') && !firefoxArguments.includes('--profile')) {+ temporaryProfileDir = await mkdtempAsync(FIREFOX_PROFILE_PATH);+ firefoxArguments.push(`-profile`, temporaryProfileDir);+ }++ let firefoxExecutable = executablePath;+ if (!firefoxExecutable) {+ const {missingText, executablePath} = this._resolveExecutablePath();+ if (missingText)+ throw new Error(missingText);+ firefoxExecutable = executablePath;+ }+ const stdio = ['pipe', 'pipe', 'pipe'];+ const firefoxProcess = childProcess.spawn(+ firefoxExecutable,+ firefoxArguments,+ {+ // On non-windows platforms, `detached: false` makes child process a leader of a new+ // process group, making it possible to kill child process tree with `.kill(-pid)` command.+ // @see https://nodejs.org/api/child_process.html#child_process_options_detached+ detached: process.platform !== 'win32',+ stdio,+ // On linux Juggler ships the libstdc++ it was linked against.+ env: os.platform() === 'linux' ? {+ ...env,+ LD_LIBRARY_PATH: `${path.dirname(firefoxExecutable)}:${process.env.LD_LIBRARY_PATH}`,+ } : env,+ }+ );++ if (dumpio) {+ firefoxProcess.stderr.pipe(process.stderr);+ firefoxProcess.stdout.pipe(process.stdout);+ }++ let firefoxClosed = false;+ const waitForFirefoxToClose = new Promise((fulfill, reject) => {+ firefoxProcess.once('close', () => {+ firefoxClosed = true;+ // Cleanup as processes exit.+ if (temporaryProfileDir) {+ removeFolderAsync(temporaryProfileDir)+ .then(() => fulfill())+ .catch(err => console.error(err));+ } else {+ fulfill();+ }+ });+ });++ const listeners = [ helper.addEventListener(process, 'close', killFirefox) ];+ if (handleSIGINT)+ listeners.push(helper.addEventListener(process, 'SIGINT', () => { killFirefox(); process.exit(130); }));+ if (handleSIGTERM)+ listeners.push(helper.addEventListener(process, 'SIGTERM', gracefullyCloseFirefox));+ if (handleSIGHUP)+ listeners.push(helper.addEventListener(process, 'SIGHUP', gracefullyCloseFirefox));+ let connection: Connection | null = null;+ try {+ const url = await waitForWSEndpoint(firefoxProcess, timeout);+ const transport = await WebSocketTransport.create(url);+ connection = new Connection(url, transport, slowMo);+ const browser = await Browser.create(connection, defaultViewport, firefoxProcess, gracefullyCloseFirefox);+ if (ignoreHTTPSErrors)+ await connection.send('Browser.setIgnoreHTTPSErrors', {enabled: true});+ await browser.waitForTarget(t => t.type() === 'page');+ return browser;+ } catch (e) {+ killFirefox();+ throw e;+ }++ function gracefullyCloseFirefox() {+ helper.removeEventListeners(listeners);+ if (temporaryProfileDir) {+ killFirefox();+ } else if (connection) {+ connection.send('Browser.close').catch(error => {+ debugError(error);+ killFirefox();+ });+ }+ return waitForFirefoxToClose;+ }++ // This method has to be sync to be used as 'exit' event handler.+ function killFirefox() {+ helper.removeEventListeners(listeners);+ if (firefoxProcess.pid && !firefoxProcess.killed && !firefoxClosed) {+ // Force kill chrome.+ try {+ if (process.platform === 'win32')+ childProcess.execSync(`taskkill /pid ${firefoxProcess.pid} /T /F`);+ else+ process.kill(-firefoxProcess.pid, 'SIGKILL');+ } catch (e) {+ // the process might have already stopped+ }+ }+ // Attempt to remove temporary profile directory to avoid littering.+ try {+ removeFolder.sync(temporaryProfileDir);+ } catch (e) { }+ }+ }++ async connect(options: any = {}): Promise<Browser> {+ const {+ browserWSEndpoint,+ slowMo = 0,+ defaultViewport = {width: 800, height: 600},+ ignoreHTTPSErrors = false,+ } = options;+ let connection = null;+ const transport = await WebSocketTransport.create(browserWSEndpoint);+ connection = new Connection(browserWSEndpoint, transport, slowMo);+ const browser = await Browser.create(connection, defaultViewport, null, () => connection.send('Browser.close').catch(debugError));+ if (ignoreHTTPSErrors)+ await connection.send('Browser.setIgnoreHTTPSErrors', {enabled: true});+ return browser;+ }++ executablePath(): string {+ return this._resolveExecutablePath().executablePath;+ }++ _resolveExecutablePath() {+ const browserFetcher = new BrowserFetcher(this._projectRoot, { browser: 'firefox' });+ const revisionInfo = browserFetcher.revisionInfo(this._preferredRevision);+ const missingText = !revisionInfo.local ? `Firefox revision is not downloaded. Run "npm install" or "yarn install"` : null;+ return {executablePath: revisionInfo.executablePath, missingText};+ }+}++function waitForWSEndpoint(firefoxProcess: import('child_process').ChildProcess, timeout: number): Promise<string> {+ return new Promise((resolve, reject) => {+ const rl = readline.createInterface({ input: firefoxProcess.stdout });+ let stderr = '';+ const listeners = [+ helper.addEventListener(rl, 'line', onLine),+ helper.addEventListener(rl, 'close', () => onClose()),+ helper.addEventListener(firefoxProcess, 'error', error => onClose(error))+ ];+ const timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0;++ function onClose(error?: Error) {+ cleanup();+ reject(new Error([+ 'Failed to launch Firefox!' + (error ? ' ' + error.message : ''),+ stderr,+ '',+ ].join('\n')));+ }++ function onTimeout() {+ cleanup();+ reject(new TimeoutError(`Timed out after ${timeout} ms while trying to connect to Firefox!`));+ }++ function onLine(line: string) {+ stderr += line + '\n';+ const match = line.match(/^Juggler listening on (ws:\/\/.*)$/);+ if (!match)+ return;+ cleanup();+ resolve(match[1]);+ }++ function cleanup() {+ if (timeoutId)+ clearTimeout(timeoutId);+ helper.removeEventListeners(listeners);+ }+ });+}diff --git a/src/firefox/NavigationWatchdog.ts b/src/firefox/NavigationWatchdog.tsnew file mode 100644index 0000000000..6e62527693--- /dev/null+++ b/src/firefox/NavigationWatchdog.ts@@ -0,0 +1,125 @@+import { helper, RegisteredListener } from '../helper';+import { JugglerSession, JugglerSessionEvents } from './Connection';+import { Frame, FrameManagerEvents } from './FrameManager';+import { NetworkManager, NetworkManagerEvents } from './NetworkManager';++export class NextNavigationWatchdog {+ private _navigatedFrame: Frame;+ private _promise: Promise<unknown>;+ private _resolveCallback: (value?: unknown) => void;+ private _navigation: {navigationId: number|null, url?: string} = null;+ private _eventListeners: RegisteredListener[];+ constructor(session : JugglerSession, navigatedFrame : Frame) {+ this._navigatedFrame = navigatedFrame;+ this._promise = new Promise(x => this._resolveCallback = x);+ this._eventListeners = [+ helper.addEventListener(session, 'Page.navigationStarted', this._onNavigationStarted.bind(this)),+ helper.addEventListener(session, 'Page.sameDocumentNavigation', this._onSameDocumentNavigation.bind(this)),+ ];+ }++ promise() {+ return this._promise;+ }++ navigation() {+ return this._navigation;+ }++ _onNavigationStarted(params) {+ if (params.frameId === this._navigatedFrame._frameId) {+ this._navigation = {+ navigationId: params.navigationId,+ url: params.url,+ };+ this._resolveCallback();+ }+ }++ _onSameDocumentNavigation(params) {+ if (params.frameId === this._navigatedFrame._frameId) {+ this._navigation = {+ navigationId: null,+ };+ this._resolveCallback();+ }+ }++ dispose() {+ helper.removeEventListeners(this._eventListeners);+ }+}++export class NavigationWatchdog {+ private _navigatedFrame: Frame;+ private _targetNavigationId: any;+ private _firedEvents: any;+ private _targetURL: any;+ private _promise: Promise<unknown>;+ private _resolveCallback: (value?: unknown) => void;+ private _navigationRequest: any;+ private _eventListeners: RegisteredListener[];+ constructor(session : JugglerSession, navigatedFrame : Frame, networkManager : NetworkManager, targetNavigationId, targetURL, firedEvents) {+ this._navigatedFrame = navigatedFrame;+ this._targetNavigationId = targetNavigationId;+ this._firedEvents = firedEvents;+ this._targetURL = targetURL;++ this._promise = new Promise(x => this._resolveCallback = x);+ this._navigationRequest = null;++ const check = this._checkNavigationComplete.bind(this);+ this._eventListeners = [+ helper.addEventListener(session, JugglerSessionEvents.Disconnected, () => this._resolveCallback(new Error('Navigation failed because browser has disconnected!'))),+ helper.addEventListener(session, 'Page.eventFired', check),+ helper.addEventListener(session, 'Page.frameAttached', check),+ helper.addEventListener(session, 'Page.frameDetached', check),+ helper.addEventListener(session, 'Page.navigationStarted', check),+ helper.addEventListener(session, 'Page.navigationCommitted', check),+ helper.addEventListener(session, 'Page.navigationAborted', this._onNavigationAborted.bind(this)),+ helper.addEventListener(networkManager, NetworkManagerEvents.Request, this._onRequest.bind(this)),+ helper.addEventListener(navigatedFrame._frameManager, FrameManagerEvents.FrameDetached, check),+ ];+ check();+ }++ _onRequest(request) {+ if (request.frame() !== this._navigatedFrame || !request.isNavigationRequest())+ return;+ this._navigationRequest = request;+ }++ navigationResponse() {+ return this._navigationRequest ? this._navigationRequest.response() : null;+ }++ _checkNavigationComplete() {+ if (this._navigatedFrame.isDetached())+ this._resolveCallback(new Error('Navigating frame was detached'));+ else if (this._navigatedFrame._lastCommittedNavigationId === this._targetNavigationId+ && checkFiredEvents(this._navigatedFrame, this._firedEvents))+ this._resolveCallback(null);+++ function checkFiredEvents(frame, firedEvents) {+ for (const subframe of frame._children) {+ if (!checkFiredEvents(subframe, firedEvents))+ return false;+ }+ return firedEvents.every(event => frame._firedEvents.has(event));+ }+ }++ _onNavigationAborted(params) {+ if (params.frameId === this._navigatedFrame._frameId && params.navigationId === this._targetNavigationId)+ this._resolveCallback(new Error('Navigation to ' + this._targetURL + ' failed: ' + params.errorText));+ }++ promise() {+ return this._promise;+ }++ dispose() {+ helper.removeEventListeners(this._eventListeners);+ }+}diff --git a/src/firefox/NetworkManager.ts b/src/firefox/NetworkManager.tsnew file mode 100644index 0000000000..d7dccb4f5a--- /dev/null+++ b/src/firefox/NetworkManager.ts@@ -0,0 +1,365 @@+import {helper, assert, debugError} from '../helper';+import {EventEmitter} from 'events';+import { JugglerSession } from './Connection';+import { FrameManager } from './FrameManager';++export const NetworkManagerEvents = {+ RequestFailed: Symbol('NetworkManagerEvents.RequestFailed'),+ RequestFinished: Symbol('NetworkManagerEvents.RequestFinished'),+ Request: Symbol('NetworkManagerEvents.Request'),+ Response: Symbol('NetworkManagerEvents.Response'),+};++export class NetworkManager extends EventEmitter {+ private _session: JugglerSession;+ private _requests: Map<any, any>;+ private _frameManager: FrameManager;+ private _eventListeners: any[];+ constructor(session) {+ super();+ this._session = session;++ this._requests = new Map();+ this._frameManager = null;++ this._eventListeners = [+ helper.addEventListener(session, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this)),+ helper.addEventListener(session, 'Network.responseReceived', this._onResponseReceived.bind(this)),+ helper.addEventListener(session, 'Network.requestFinished', this._onRequestFinished.bind(this)),+ helper.addEventListener(session, 'Network.requestFailed', this._onRequestFailed.bind(this)),+ ];+ }++ dispose() {+ helper.removeEventListeners(this._eventListeners);+ }++ setFrameManager(frameManager: FrameManager) {+ this._frameManager = frameManager;+ }++ async setExtraHTTPHeaders(headers) {+ const array = [];+ for (const [name, value] of Object.entries(headers)) {+ assert(helper.isString(value), `Expected value of header "${name}" to be String, but "${typeof value}" is found.`);+ array.push({name, value});+ }+ await this._session.send('Network.setExtraHTTPHeaders', {headers: array});+ }++ async setRequestInterception(enabled) {+ await this._session.send('Network.setRequestInterception', {enabled});+ }++ _onRequestWillBeSent(event) {+ const redirected = event.redirectedFrom ? this._requests.get(event.redirectedFrom) : null;+ const frame = redirected ? redirected.frame() : (this._frameManager && event.frameId ? this._frameManager.frame(event.frameId) : null);+ if (!frame)+ return;+ let redirectChain = [];+ if (redirected) {+ redirectChain = redirected._redirectChain;+ redirectChain.push(redirected);+ this._requests.delete(redirected._id);+ }+ const request = new Request(this._session, frame, redirectChain, event);+ this._requests.set(request._id, request);+ this.emit(NetworkManagerEvents.Request, request);+ }++ _onResponseReceived(event) {+ const request = this._requests.get(event.requestId);+ if (!request)+ return;+ const response = new Response(this._session, request, event);+ request._response = response;+ this.emit(NetworkManagerEvents.Response, response);+ }++ _onRequestFinished(event) {+ const request = this._requests.get(event.requestId);+ if (!request)+ return;+ // Keep redirected requests in the map for future reference in redirectChain.+ const isRedirected = request.response().status() >= 300 && request.response().status() <= 399;+ if (isRedirected) {+ request.response()._bodyLoadedPromiseFulfill.call(null, new Error('Response body is unavailable for redirect responses'));+ } else {+ this._requests.delete(request._id);+ request.response()._bodyLoadedPromiseFulfill.call(null);+ }+ this.emit(NetworkManagerEvents.RequestFinished, request);+ }++ _onRequestFailed(event) {+ const request = this._requests.get(event.requestId);+ if (!request)+ return;+ this._requests.delete(request._id);+ if (request.response())+ request.response()._bodyLoadedPromiseFulfill.call(null);+ request._errorText = event.errorCode;+ this.emit(NetworkManagerEvents.RequestFailed, request);+ }+}++const causeToResourceType = {+ TYPE_INVALID: 'other',+ TYPE_OTHER: 'other',+ TYPE_SCRIPT: 'script',+ TYPE_IMAGE: 'image',+ TYPE_STYLESHEET: 'stylesheet',+ TYPE_OBJECT: 'other',+ TYPE_DOCUMENT: 'document',+ TYPE_SUBDOCUMENT: 'document',+ TYPE_REFRESH: 'document',+ TYPE_XBL: 'other',+ TYPE_PING: 'other',+ TYPE_XMLHTTPREQUEST: 'xhr',+ TYPE_OBJECT_SUBREQUEST: 'other',+ TYPE_DTD: 'other',+ TYPE_FONT: 'font',+ TYPE_MEDIA: 'media',+ TYPE_WEBSOCKET: 'websocket',+ TYPE_CSP_REPORT: 'other',+ TYPE_XSLT: 'other',+ TYPE_BEACON: 'other',+ TYPE_FETCH: 'fetch',+ TYPE_IMAGESET: 'images',+ TYPE_WEB_MANIFEST: 'manifest',+};++export class Request {+ _id(_id: any, request: Request) {+ throw new Error('Method not implemented.');+ }+ _session: any;+ _frame: any;+ _redirectChain: any;+ _url: any;+ _postData: any;+ _suspended: any;+ _response: any;+ _errorText: any;+ _isNavigationRequest: any;+ _method: any;+ _resourceType: any;+ _headers: {};+ _interceptionHandled: boolean;+ constructor(session, frame, redirectChain, payload) {+ this._session = session;+ this._frame = frame;+ this._id = payload.requestId;+ this._redirectChain = redirectChain;+ this._url = payload.url;+ this._postData = payload.postData;+ this._suspended = payload.suspended;+ this._response = null;+ this._errorText = null;+ this._isNavigationRequest = payload.isNavigationRequest;+ this._method = payload.method;+ this._resourceType = causeToResourceType[payload.cause] || 'other';+ this._headers = {};+ this._interceptionHandled = false;+ for (const {name, value} of payload.headers)+ this._headers[name.toLowerCase()] = value;+ }++ failure() {+ return this._errorText ? {errorText: this._errorText} : null;+ }++ async continue(overrides: any = {}) {+ assert(!overrides.url, 'Playwright-Firefox does not support overriding URL');+ assert(!overrides.method, 'Playwright-Firefox does not support overriding method');+ assert(!overrides.postData, 'Playwright-Firefox does not support overriding postData');+ assert(this._suspended, 'Request Interception is not enabled!');+ assert(!this._interceptionHandled, 'Request is already handled!');+ this._interceptionHandled = true;+ const {+ headers,+ } = overrides;+ await this._session.send('Network.resumeSuspendedRequest', {+ requestId: this._id,+ headers: headers ? Object.entries(headers).filter(([, value]) => !Object.is(value, undefined)).map(([name, value]) => ({name, value})) : undefined,+ }).catch(error => {+ debugError(error);+ });+ }++ async abort() {+ assert(this._suspended, 'Request Interception is not enabled!');+ assert(!this._interceptionHandled, 'Request is already handled!');+ this._interceptionHandled = true;+ await this._session.send('Network.abortSuspendedRequest', {+ requestId: this._id,+ }).catch(error => {+ debugError(error);+ });+ }++ postData() {+ return this._postData;+ }++ headers() {+ return {...this._headers};+ }++ redirectChain() {+ return this._redirectChain.slice();+ }++ resourceType() {+ return this._resourceType;+ }++ url() {+ return this._url;+ }++ method() {+ return this._method;+ }++ isNavigationRequest() {+ return this._isNavigationRequest;+ }++ frame() {+ return this._frame;+ }++ response() {+ return this._response;+ }+}++export class Response {+ _session: any;+ _request: any;+ _remoteIPAddress: any;+ _remotePort: any;+ _status: any;+ _statusText: any;+ _headers: {};+ _securityDetails: SecurityDetails;+ _bodyLoadedPromise: Promise<unknown>;+ _bodyLoadedPromiseFulfill: (value?: unknown) => void;+ _contentPromise: any;+ constructor(session, request, payload) {+ this._session = session;+ this._request = request;+ this._remoteIPAddress = payload.remoteIPAddress;+ this._remotePort = payload.remotePort;+ this._status = payload.status;+ this._statusText = payload.statusText;+ this._headers = {};+ this._securityDetails = payload.securityDetails ? new SecurityDetails(payload.securityDetails) : null;+ for (const {name, value} of payload.headers)+ this._headers[name.toLowerCase()] = value;+ this._bodyLoadedPromise = new Promise(fulfill => {+ this._bodyLoadedPromiseFulfill = fulfill;+ });+ }++ buffer(): Promise<Buffer> {+ if (!this._contentPromise) {+ this._contentPromise = this._bodyLoadedPromise.then(async error => {+ if (error)+ throw error;+ const response = await this._session.send('Network.getResponseBody', {+ requestId: this._request._id+ });+ if (response.evicted)+ throw new Error(`Response body for ${this._request.method()} ${this._request.url()} was evicted!`);+ return Buffer.from(response.base64body, 'base64');+ });+ }+ return this._contentPromise;+ }++ async text(): Promise<string> {+ const content = await this.buffer();+ return content.toString('utf8');+ }++ async json(): Promise<object> {+ const content = await this.text();+ return JSON.parse(content);+ }++ securityDetails() {+ return this._securityDetails;+ }++ headers() {+ return {...this._headers};+ }++ status() {+ return this._status;+ }++ statusText() {+ return this._statusText;+ }++ ok() {+ return this._status >= 200 && this._status <= 299;+ }++ remoteAddress() {+ return {+ ip: this._remoteIPAddress,+ port: this._remotePort,+ };+ }++ frame() {+ return this._request.frame();+ }++ url() {+ return this._request.url();+ }++ request() {+ return this._request;+ }+}++export class SecurityDetails {+ _subjectName: string;+ _issuer: string;+ _validFrom: number;+ _validTo: number;+ _protocol: string;+ constructor(securityPayload: any) {+ this._subjectName = securityPayload['subjectName'];+ this._issuer = securityPayload['issuer'];+ this._validFrom = securityPayload['validFrom'];+ this._validTo = securityPayload['validTo'];+ this._protocol = securityPayload['protocol'];+ }++ subjectName(): string {+ return this._subjectName;+ }++ issuer(): string {+ return this._issuer;+ }++ validFrom(): number {+ return this._validFrom;+ }++ validTo(): number {+ return this._validTo;+ }++ protocol(): string {+ return this._protocol;+ }+}diff --git a/src/firefox/Page.ts b/src/firefox/Page.tsnew file mode 100644index 0000000000..dc16d9bcc6--- /dev/null+++ b/src/firefox/Page.ts@@ -0,0 +1,640 @@+import { JSHandle, ElementHandle } from './JSHandle';++import {RegisteredListener, helper, debugError, assert} from '../helper';+import {Keyboard, Mouse, Touchscreen} from './Input';+import {Dialog} from './Dialog';+import {TimeoutError} from '../Errors';+import * as fs from 'fs';+import * as mime from 'mime';+import {EventEmitter} from 'events';+import {createHandle} from './JSHandle';+import {Connection, JugglerSession, JugglerSessionEvents} from './Connection';+import {FrameManager, normalizeWaitUntil, FrameManagerEvents} from './FrameManager';+import {NetworkManager, Request, Response, NetworkManagerEvents} from './NetworkManager';+import {TimeoutSettings} from '../TimeoutSettings';+import {NavigationWatchdog} from './NavigationWatchdog';+import {Accessibility} from './Accessibility';+import { Target, BrowserContext } from './Browser';+import { Events } from '../Events';++const writeFileAsync = helper.promisify(fs.writeFile);++export class Page extends EventEmitter {+ private _timeoutSettings: TimeoutSettings;+ private _session: JugglerSession;+ private _target: Target;+ private _keyboard: Keyboard;+ private _mouse: Mouse;+ private _touchscreen: Touchscreen;+ private _accessibility: Accessibility;+ private _closed: boolean;+ private _pageBindings: Map<string, Function>;+ private _networkManager: NetworkManager;+ private _frameManager: FrameManager;+ private _eventListeners: RegisteredListener[];+ private _viewport: Viewport;+ private _disconnectPromise: Promise<Error>;+ emulateMedia: (type: string) => Promise<void>;+ static async create(session, target: Target, defaultViewport: Viewport | null) {+ const page = new Page(session, target);+ await Promise.all([+ session.send('Runtime.enable'),+ session.send('Network.enable'),+ session.send('Page.enable'),+ ]);++ if (defaultViewport)+ await page.setViewport(defaultViewport);+ return page;+ }++ constructor(session: JugglerSession, target: Target) {+ super();+ this._timeoutSettings = new TimeoutSettings();+ this._session = session;+ this._target = target;+ this._keyboard = new Keyboard(session);+ this._mouse = new Mouse(session, this._keyboard);+ this._touchscreen = new Touchscreen(session, this._keyboard, this._mouse);+ this._accessibility = new Accessibility(session);+ this._closed = false;+ this._pageBindings = new Map();+ this._networkManager = new NetworkManager(session);+ this._frameManager = new FrameManager(session, this, this._networkManager, this._timeoutSettings);+ this._networkManager.setFrameManager(this._frameManager);+ this._eventListeners = [+ helper.addEventListener(this._session, 'Page.uncaughtError', this._onUncaughtError.bind(this)),+ helper.addEventListener(this._session, 'Runtime.console', this._onConsole.bind(this)),+ helper.addEventListener(this._session, 'Page.dialogOpened', this._onDialogOpened.bind(this)),+ helper.addEventListener(this._session, 'Page.bindingCalled', this._onBindingCalled.bind(this)),+ helper.addEventListener(this._frameManager, FrameManagerEvents.Load, () => this.emit(Events.Page.Load)),+ helper.addEventListener(this._frameManager, FrameManagerEvents.DOMContentLoaded, () => this.emit(Events.Page.DOMContentLoaded)),+ helper.addEventListener(this._frameManager, FrameManagerEvents.FrameAttached, frame => this.emit(Events.Page.FrameAttached, frame)),+ helper.addEventListener(this._frameManager, FrameManagerEvents.FrameDetached, frame => this.emit(Events.Page.FrameDetached, frame)),+ helper.addEventListener(this._frameManager, FrameManagerEvents.FrameNavigated, frame => this.emit(Events.Page.FrameNavigated, frame)),+ helper.addEventListener(this._networkManager, NetworkManagerEvents.Request, request => this.emit(Events.Page.Request, request)),+ helper.addEventListener(this._networkManager, NetworkManagerEvents.Response, response => this.emit(Events.Page.Response, response)),+ helper.addEventListener(this._networkManager, NetworkManagerEvents.RequestFinished, request => this.emit(Events.Page.RequestFinished, request)),+ helper.addEventListener(this._networkManager, NetworkManagerEvents.RequestFailed, request => this.emit(Events.Page.RequestFailed, request)),+ ];+ this._viewport = null;+ this._target._isClosedPromise.then(() => {+ this._closed = true;+ this._frameManager.dispose();+ this._networkManager.dispose();+ helper.removeEventListeners(this._eventListeners);+ this.emit(Events.Page.Close);+ });+ }++ async cookies(...urls: Array<string>): Promise<Array<any>> {+ const connection = Connection.fromSession(this._session);+ const {cookies} = await connection.send('Browser.getCookies', {+ browserContextId: this._target._context._browserContextId || undefined,+ urls: urls.length ? urls : [this.url()]+ });+ // Firefox's cookies are missing sameSite when it is 'None'+ return cookies.map(cookie => ({sameSite: 'None', ...cookie}));+ }++ async deleteCookie(...cookies: Array<any>) {+ const pageURL = this.url();+ const items = [];+ for (const cookie of cookies) {+ const item = {+ url: cookie.url,+ domain: cookie.domain,+ path: cookie.path,+ name: cookie.name,+ };+ if (!item.url && pageURL.startsWith('http'))+ item.url = pageURL;+ items.push(item);+ }++ const connection = Connection.fromSession(this._session);+ await connection.send('Browser.deleteCookies', {+ browserContextId: this._target._context._browserContextId || undefined,+ cookies: items,+ });+ }++ async setCookie(...cookies: Array<any>) {+ const pageURL = this.url();+ const startsWithHTTP = pageURL.startsWith('http');+ const items = cookies.map(cookie => {+ const item = Object.assign({}, cookie);+ if (!item.url && startsWithHTTP)+ item.url = pageURL;+ assert(item.url !== 'about:blank', `Blank page can not have cookie "${item.name}"`);+ assert(!String.prototype.startsWith.call(item.url || '', 'data:'), `Data URL page can not have cookie "${item.name}"`);+ return item;+ });+ await this.deleteCookie(...items);+ if (items.length) {+ const connection = Connection.fromSession(this._session);+ await connection.send('Browser.setCookies', {+ browserContextId: this._target._context._browserContextId || undefined,+ cookies: items+ });+ }+ }++ async setRequestInterception(enabled) {+ await this._networkManager.setRequestInterception(enabled);+ }++ async setExtraHTTPHeaders(headers) {+ await this._networkManager.setExtraHTTPHeaders(headers);+ }++ async emulateMediaType(type: string | null) {+ assert(type === 'screen' || type === 'print' || type === null, 'Unsupported media type: ' + type);+ await this._session.send('Page.setEmulatedMedia', {media: type || ''});+ }++ async exposeFunction(name: string, playwrightFunction: Function) {+ if (this._pageBindings.has(name))+ throw new Error(`Failed to add page binding with name ${name}: window['${name}'] already exists!`);+ this._pageBindings.set(name, playwrightFunction);++ const expression = helper.evaluationString(addPageBinding, name);+ await this._session.send('Page.addBinding', {name: name});+ await this._session.send('Page.addScriptToEvaluateOnNewDocument', {script: expression});+ await Promise.all(this.frames().map(frame => frame.evaluate(expression).catch(debugError)));++ function addPageBinding(bindingName: string) {+ const binding: (string) => void = window[bindingName];+ window[bindingName] = (...args) => {+ const me = window[bindingName];+ let callbacks = me['callbacks'];+ if (!callbacks) {+ callbacks = new Map();+ me['callbacks'] = callbacks;+ }+ const seq = (me['lastSeq'] || 0) + 1;+ me['lastSeq'] = seq;+ const promise = new Promise((resolve, reject) => callbacks.set(seq, {resolve, reject}));+ binding(JSON.stringify({name: bindingName, seq, args}));+ return promise;+ };+ }+ }++ async _onBindingCalled(event: any) {+ const {name, seq, args} = JSON.parse(event.payload);+ let expression = null;+ try {+ const result = await this._pageBindings.get(name)(...args);+ expression = helper.evaluationString(deliverResult, name, seq, result);+ } catch (error) {+ if (error instanceof Error)+ expression = helper.evaluationString(deliverError, name, seq, error.message, error.stack);+ else+ expression = helper.evaluationString(deliverErrorValue, name, seq, error);+ }+ this._session.send('Runtime.evaluate', { expression, executionContextId: event.executionContextId }).catch(debugError);++ function deliverResult(name: string, seq: number, result: any) {+ window[name]['callbacks'].get(seq).resolve(result);+ window[name]['callbacks'].delete(seq);+ }++ function deliverError(name: string, seq: number, message: string, stack: string) {+ const error = new Error(message);+ error.stack = stack;+ window[name]['callbacks'].get(seq).reject(error);+ window[name]['callbacks'].delete(seq);+ }++ function deliverErrorValue(name: string, seq: number, value: any) {+ window[name]['callbacks'].get(seq).reject(value);+ window[name]['callbacks'].delete(seq);+ }+ }++ _sessionClosePromise() {+ if (!this._disconnectPromise)+ this._disconnectPromise = new Promise<Error>(fulfill => this._session.once(JugglerSessionEvents.Disconnected, () => fulfill(new Error('Target closed'))));+ return this._disconnectPromise;+ }++ async waitForRequest(urlOrPredicate: (string | Function), options: { timeout?: number; } | undefined = {}): Promise<Request> {+ const {+ timeout = this._timeoutSettings.timeout(),+ } = options;+ return helper.waitForEvent(this._networkManager, NetworkManagerEvents.Request, request => {+ if (helper.isString(urlOrPredicate))+ return (urlOrPredicate === request.url());+ if (typeof urlOrPredicate === 'function')+ return !!(urlOrPredicate(request));+ return false;+ }, timeout, this._sessionClosePromise());+ }++ async waitForResponse(urlOrPredicate: (string | Function), options: { timeout?: number; } | undefined = {}): Promise<Response> {+ const {+ timeout = this._timeoutSettings.timeout(),+ } = options;+ return helper.waitForEvent(this._networkManager, NetworkManagerEvents.Response, response => {+ if (helper.isString(urlOrPredicate))+ return (urlOrPredicate === response.url());+ if (typeof urlOrPredicate === 'function')+ return !!(urlOrPredicate(response));+ return false;+ }, timeout, this._sessionClosePromise());+ }++ setDefaultNavigationTimeout(timeout: number) {+ this._timeoutSettings.setDefaultNavigationTimeout(timeout);+ }++ setDefaultTimeout(timeout: number) {+ this._timeoutSettings.setDefaultTimeout(timeout);+ }++ async setUserAgent(userAgent: string) {+ await this._session.send('Page.setUserAgent', {userAgent});+ }++ async setJavaScriptEnabled(enabled) {+ await this._session.send('Page.setJavascriptEnabled', {enabled});+ }++ async setCacheEnabled(enabled) {+ await this._session.send('Page.setCacheDisabled', {cacheDisabled: !enabled});+ }++ async emulate(options: { viewport: Viewport; userAgent: string; }) {+ await Promise.all([+ this.setViewport(options.viewport),+ this.setUserAgent(options.userAgent),+ ]);+ }++ browserContext(): BrowserContext {+ return this._target.browserContext();+ }++ _onUncaughtError(params) {+ const error = new Error(params.message);+ error.stack = params.stack;+ this.emit(Events.Page.PageError, error);+ }++ viewport() {+ return this._viewport;+ }++ async setViewport(viewport: Viewport) {+ const {+ width,+ height,+ isMobile = false,+ deviceScaleFactor = 1,+ hasTouch = false,+ isLandscape = false,+ } = viewport;+ await this._session.send('Page.setViewport', {+ viewport: { width, height, isMobile, deviceScaleFactor, hasTouch, isLandscape },+ });+ const oldIsMobile = this._viewport ? this._viewport.isMobile : false;+ const oldHasTouch = this._viewport ? this._viewport.hasTouch : false;+ this._viewport = viewport;+ if (oldIsMobile !== isMobile || oldHasTouch !== hasTouch)+ await this.reload();+ }++ async evaluateOnNewDocument(pageFunction: Function | string, ...args: Array<any>) {+ const script = helper.evaluationString(pageFunction, ...args);+ await this._session.send('Page.addScriptToEvaluateOnNewDocument', { script });+ }++ browser() {+ return this._target.browser();+ }++ target() {+ return this._target;+ }++ url() {+ return this._frameManager.mainFrame().url();+ }++ frames() {+ return this._frameManager.frames();+ }++ _onDialogOpened(params) {+ this.emit(Events.Page.Dialog, new Dialog(this._session, params));+ }++ mainFrame() {+ return this._frameManager.mainFrame();+ }++ get accessibility() {+ return this._accessibility;+ }++ get keyboard(){+ return this._keyboard;+ }++ get mouse(){+ return this._mouse;+ }++ get touchscreen(){+ return this._touchscreen;+ }++ async waitForNavigation(options: { timeout?: number; waitUntil?: string | Array<string>; } = {}) {+ return this._frameManager.mainFrame().waitForNavigation(options);+ }++ async goto(url: string, options: { timeout?: number; waitUntil?: string | Array<string>; } = {}) {+ return this._frameManager.mainFrame().goto(url, options);+ }++ async goBack(options: { timeout?: number; waitUntil?: string | Array<string>; } = {}) {+ const {+ timeout = this._timeoutSettings.navigationTimeout(),+ waitUntil = ['load'],+ } = options;+ const frame = this._frameManager.mainFrame();+ const normalizedWaitUntil = normalizeWaitUntil(waitUntil);+ const {navigationId, navigationURL} = await this._session.send('Page.goBack', {+ frameId: frame._frameId,+ });+ if (!navigationId)+ return null;++ const timeoutError = new TimeoutError('Navigation timeout of ' + timeout + ' ms exceeded');+ let timeoutCallback;+ const timeoutPromise = new Promise(resolve => timeoutCallback = resolve.bind(null, timeoutError));+ const timeoutId = timeout ? setTimeout(timeoutCallback, timeout) : null;++ const watchDog = new NavigationWatchdog(this._session, frame, this._networkManager, navigationId, navigationURL, normalizedWaitUntil);+ const error = await Promise.race([+ timeoutPromise,+ watchDog.promise(),+ ]);+ watchDog.dispose();+ clearTimeout(timeoutId);+ if (error)+ throw error;+ return watchDog.navigationResponse();+ }++ async goForward(options: { timeout?: number; waitUntil?: string | Array<string>; } = {}) {+ const {+ timeout = this._timeoutSettings.navigationTimeout(),+ waitUntil = ['load'],+ } = options;+ const frame = this._frameManager.mainFrame();+ const normalizedWaitUntil = normalizeWaitUntil(waitUntil);+ const {navigationId, navigationURL} = await this._session.send('Page.goForward', {+ frameId: frame._frameId,+ });+ if (!navigationId)+ return null;++ const timeoutError = new TimeoutError('Navigation timeout of ' + timeout + ' ms exceeded');+ let timeoutCallback;+ const timeoutPromise = new Promise(resolve => timeoutCallback = resolve.bind(null, timeoutError));+ const timeoutId = timeout ? setTimeout(timeoutCallback, timeout) : null;++ const watchDog = new NavigationWatchdog(this._session, frame, this._networkManager, navigationId, navigationURL, normalizedWaitUntil);+ const error = await Promise.race([+ timeoutPromise,+ watchDog.promise(),+ ]);+ watchDog.dispose();+ clearTimeout(timeoutId);+ if (error)+ throw error;+ return watchDog.navigationResponse();+ }++ async reload(options: { timeout?: number; waitUntil?: string | Array<string>; } = {}) {+ const {+ timeout = this._timeoutSettings.navigationTimeout(),+ waitUntil = ['load'],+ } = options;+ const frame = this._frameManager.mainFrame();+ const normalizedWaitUntil = normalizeWaitUntil(waitUntil);+ const {navigationId, navigationURL} = await this._session.send('Page.reload', {+ frameId: frame._frameId,+ });+ if (!navigationId)+ return null;++ const timeoutError = new TimeoutError('Navigation timeout of ' + timeout + ' ms exceeded');+ let timeoutCallback;+ const timeoutPromise = new Promise(resolve => timeoutCallback = resolve.bind(null, timeoutError));+ const timeoutId = timeout ? setTimeout(timeoutCallback, timeout) : null;++ const watchDog = new NavigationWatchdog(this._session, frame, this._networkManager, navigationId, navigationURL, normalizedWaitUntil);+ const error = await Promise.race([+ timeoutPromise,+ watchDog.promise(),+ ]);+ watchDog.dispose();+ clearTimeout(timeoutId);+ if (error)+ throw error;+ return watchDog.navigationResponse();+ }++ async screenshot(options: { fullPage?: boolean; clip?: { width: number; height: number; x: number; y: number; }; encoding?: string; path?: string; } = {}): Promise<string | Buffer> {+ const {data} = await this._session.send('Page.screenshot', {+ mimeType: getScreenshotMimeType(options),+ fullPage: options.fullPage,+ clip: processClip(options.clip),+ });+ const buffer = options.encoding === 'base64' ? data : Buffer.from(data, 'base64');+ if (options.path)+ await writeFileAsync(options.path, buffer);+ return buffer;++ function processClip(clip) {+ if (!clip)+ return undefined;+ const x = Math.round(clip.x);+ const y = Math.round(clip.y);+ const width = Math.round(clip.width + clip.x - x);+ const height = Math.round(clip.height + clip.y - y);+ return {x, y, width, height};+ }+ }++ async evaluate(pageFunction, ...args) {+ return await this._frameManager.mainFrame().evaluate(pageFunction, ...args);+ }++ async addScriptTag(options: { content?: string; path?: string; type?: string; url?: string; }): Promise<ElementHandle> {+ return await this._frameManager.mainFrame().addScriptTag(options);+ }++ async addStyleTag(options: { content?: string; path?: string; url?: string; }): Promise<ElementHandle> {+ return await this._frameManager.mainFrame().addStyleTag(options);+ }++ async click(selector: string, options: { delay?: number; button?: string; clickCount?: number; } | undefined = {}) {+ return await this._frameManager.mainFrame().click(selector, options);+ }++ tap(selector: string) {+ return this.mainFrame().tap(selector);+ }++ async type(selector: string, text: string, options: { delay: (number | undefined); } | undefined) {+ return await this._frameManager.mainFrame().type(selector, text, options);+ }++ async focus(selector: string) {+ return await this._frameManager.mainFrame().focus(selector);+ }++ async hover(selector: string) {+ return await this._frameManager.mainFrame().hover(selector);+ }++ async waitFor(selectorOrFunctionOrTimeout: (string | number | Function), options: { polling?: string | number; timeout?: number; visible?: boolean; hidden?: boolean; } | undefined = {}, ...args: Array<any>): Promise<JSHandle> {+ return await this._frameManager.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);+ }++ async waitForFunction(pageFunction: Function | string, options: { polling?: string | number; timeout?: number; } | undefined = {}, ...args): Promise<JSHandle> {+ return await this._frameManager.mainFrame().waitForFunction(pageFunction, options, ...args);+ }++ async waitForSelector(selector: string, options: { timeout?: number; visible?: boolean; hidden?: boolean; } | undefined = {}): Promise<ElementHandle> {+ return await this._frameManager.mainFrame().waitForSelector(selector, options);+ }++ async waitForXPath(xpath: string, options: { timeout?: number; visible?: boolean; hidden?: boolean; } | undefined = {}): Promise<ElementHandle> {+ return await this._frameManager.mainFrame().waitForXPath(xpath, options);+ }++ async title(): Promise<string> {+ return await this._frameManager.mainFrame().title();+ }++ async $(selector: string): Promise<ElementHandle | null> {+ return await this._frameManager.mainFrame().$(selector);+ }++ async $$(selector: string): Promise<Array<ElementHandle>> {+ return await this._frameManager.mainFrame().$$(selector);+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: Array<any>): Promise<(object | undefined)> {+ return await this._frameManager.mainFrame().$eval(selector, pageFunction, ...args);+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: Array<any>): Promise<(object | undefined)> {+ return await this._frameManager.mainFrame().$$eval(selector, pageFunction, ...args);+ }++ async $x(expression: string): Promise<Array<ElementHandle>> {+ return await this._frameManager.mainFrame().$x(expression);+ }++ async evaluateHandle(pageFunction, ...args) {+ return await this._frameManager.mainFrame().evaluateHandle(pageFunction, ...args);+ }++ async select(selector: string, ...values: Array<string>): Promise<Array<string>> {+ return await this._frameManager.mainFrame().select(selector, ...values);+ }++ async close(options: any = {}) {+ const {+ runBeforeUnload = false,+ } = options;+ await this._session.send('Page.close', { runBeforeUnload });+ if (!runBeforeUnload)+ await this._target._isClosedPromise;+ }++ async content() {+ return await this._frameManager.mainFrame().content();+ }++ async setContent(html: string) {+ return await this._frameManager.mainFrame().setContent(html);+ }++ _onConsole({type, args, executionContextId, location}) {+ const context = this._frameManager.executionContextById(executionContextId);+ this.emit(Events.Page.Console, new ConsoleMessage(type, args.map(arg => createHandle(context, arg)), location));+ }++ isClosed(): boolean {+ return this._closed;+ }+}++// Expose alias for deprecated method.+Page.prototype.emulateMedia = Page.prototype.emulateMediaType;++export class ConsoleMessage {+ private _type: string;+ private _args: any[];+ private _location: any;+ constructor(type: string, args: Array<JSHandle>, location) {+ this._type = type;+ this._args = args;+ this._location = location;+ }++ location() {+ return this._location;+ }++ type(): string {+ return this._type;+ }++ args(): Array<JSHandle> {+ return this._args;+ }++ text(): string {+ return this._args.map(arg => {+ if (arg._objectId)+ return arg.toString();+ return arg._deserializeValue(arg._protocolValue);+ }).join(' ');+ }+}++function getScreenshotMimeType(options) {+ // options.type takes precedence over inferring the type from options.path+ // because it may be a 0-length file with no extension created beforehand (i.e. as a temp file).+ if (options.type) {+ if (options.type === 'png')+ return 'image/png';+ if (options.type === 'jpeg')+ return 'image/jpeg';+ throw new Error('Unknown options.type value: ' + options.type);+ }+ if (options.path) {+ const fileType = mime.getType(options.path);+ if (fileType === 'image/png' || fileType === 'image/jpeg')+ return fileType;+ throw new Error('Unsupported screenshot mime type: ' + fileType);+ }+ return 'image/png';+}++export type Viewport = {+ width: number;+ height: number;+ deviceScaleFactor?: number;+ isMobile?: boolean;+ isLandscape?: boolean;+ hasTouch?: boolean;+}\ No newline at end of filediff --git a/src/firefox/Playwright.ts b/src/firefox/Playwright.tsnew file mode 100644index 0000000000..2756b6798f--- /dev/null+++ b/src/firefox/Playwright.ts@@ -0,0 +1,66 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import { Browser } from './Browser';+import { BrowserFetcher } from './BrowserFetcher';+import { ConnectionTransport } from '../ConnectionTransport';+import { DeviceDescriptors } from '../DeviceDescriptors';+import * as Errors from '../Errors';+import { Launcher } from './Launcher';++export class Playwright {+ private _projectRoot: string;+ private _launcher: Launcher;++ constructor(projectRoot: string, preferredRevision: string) {+ this._projectRoot = projectRoot;+ this._launcher = new Launcher(projectRoot, preferredRevision);+ }++ launch(options: any): Promise<Browser> {+ return this._launcher.launch(options);+ }++ connect(options: (any & {+ browserWSEndpoint?: string;+ browserURL?: string;+ transport?: ConnectionTransport; })): Promise<Browser> {+ return this._launcher.connect(options);+ }++ executablePath(): string {+ return this._launcher.executablePath();+ }++ get devices(): any {+ const result = DeviceDescriptors.slice();+ for (const device of DeviceDescriptors)+ result[device.name] = device;+ return result;+ }++ get errors(): any {+ return Errors;+ }++ defaultArgs(options: any | undefined): string[] {+ return this._launcher.defaultArgs(options);+ }++ createBrowserFetcher(options: any | undefined): BrowserFetcher {+ return new BrowserFetcher(this._projectRoot, { browser: 'firefox', ...options });+ }+}diff --git a/src/firefox/WebSocketTransport.ts b/src/firefox/WebSocketTransport.tsnew file mode 100644index 0000000000..ed2b7a3515--- /dev/null+++ b/src/firefox/WebSocketTransport.ts@@ -0,0 +1,89 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import { ConnectionTransport } from '../ConnectionTransport';+import * as WebSocket from 'ws';++export class WebSocketTransport implements ConnectionTransport {+ _ws: WebSocket;+ _dispatchQueue: DispatchQueue;+ onclose?: () => void;+ onmessage?: (message: string) => void;+ static create(url: string): Promise<WebSocketTransport> {+ return new Promise((resolve, reject) => {+ const ws = new WebSocket(url, [], { perMessageDeflate: false });+ ws.addEventListener('open', () => resolve(new WebSocketTransport(ws)));+ ws.addEventListener('error', reject);+ });+ }++ constructor(ws: WebSocket) {+ this._ws = ws;+ this._dispatchQueue = new DispatchQueue(this);+ this._ws.addEventListener('message', event => {+ this._dispatchQueue.enqueue(event.data);+ });+ this._ws.addEventListener('close', event => {+ if (this.onclose)+ this.onclose.call(null);+ });+ // Silently ignore all errors - we don't know what to do with them.+ this._ws.addEventListener('error', () => {});+ }++ send(message: string) {+ this._ws.send(message);+ }++ close() {+ this._ws.close();+ }+}++// We want to dispatch all "message" events in separate tasks+// to make sure all message-related promises are resolved first+// before dispatching next message.+//+// We cannot just use setTimeout() in Node.js here like we would+// do in Browser - see https://github.com/nodejs/node/issues/23773+// Thus implement a dispatch queue that enforces new tasks manually.+class DispatchQueue {+ _transport: ConnectionTransport;+ _timeoutId: NodeJS.Timer = null;+ _queue: string[] = [];+ constructor(transport : ConnectionTransport) {+ this._transport = transport;+ this._dispatch = this._dispatch.bind(this);+ }++ enqueue(message: string) {+ this._queue.push(message);+ if (!this._timeoutId)+ this._timeoutId = setTimeout(this._dispatch, 0);+ }++ _dispatch() {+ const message = this._queue.shift();+ if (this._queue.length)+ this._timeoutId = setTimeout(this._dispatch, 0);+ else+ this._timeoutId = null;++ if (this._transport.onmessage)+ this._transport.onmessage.call(null, message);+ }+}+diff --git a/src/helper.ts b/src/helper.tsnew file mode 100644index 0000000000..301b623aad--- /dev/null+++ b/src/helper.ts@@ -0,0 +1,162 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import * as debug from 'debug';+import { TimeoutError } from './Errors';++export const debugError = debug(`playwright:error`);++export type RegisteredListener = {+ emitter: NodeJS.EventEmitter;+ eventName: (string | symbol);+ handler: (_: any) => void;+};++class Helper {+ static evaluationString(fun: Function | string, ...args: any[]): string {+ if (Helper.isString(fun)) {+ assert(args.length === 0, 'Cannot evaluate a string with arguments');+ return fun as string;+ }+ return `(${fun})(${args.map(serializeArgument).join(',')})`;++ function serializeArgument(arg: any): string {+ if (Object.is(arg, undefined))+ return 'undefined';+ return JSON.stringify(arg);+ }+ }++ static installAsyncStackHooks(classType: any) {+ for (const methodName of Reflect.ownKeys(classType.prototype)) {+ const method = Reflect.get(classType.prototype, methodName);+ if (methodName === 'constructor' || typeof methodName !== 'string' || methodName.startsWith('_') || typeof method !== 'function' || method.constructor.name !== 'AsyncFunction')+ continue;+ Reflect.set(classType.prototype, methodName, function(...args) {+ const syncStack: any = {};+ Error.captureStackTrace(syncStack);+ return method.call(this, ...args).catch(e => {+ const stack = syncStack.stack.substring(syncStack.stack.indexOf('\n') + 1);+ const clientStack = stack.substring(stack.indexOf('\n'));+ if (e instanceof Error && e.stack && !e.stack.includes(clientStack))+ e.stack += '\n -- ASYNC --\n' + stack;+ throw e;+ });+ });+ }+ }++ static addEventListener(+ emitter: NodeJS.EventEmitter,+ eventName: (string | symbol),+ handler: (_: any) => void): RegisteredListener {+ emitter.on(eventName, handler);+ return { emitter, eventName, handler };+ }++ static removeEventListeners(listeners: Array<{+ emitter: NodeJS.EventEmitter;+ eventName: (string | symbol);+ handler: (_: any) => void;+ }>) {+ for (const listener of listeners)+ listener.emitter.removeListener(listener.eventName, listener.handler);+ listeners.splice(0, listeners.length);+ }++ static isString(obj: any): obj is string {+ return typeof obj === 'string' || obj instanceof String;+ }++ static isNumber(obj: any): obj is number {+ return typeof obj === 'number' || obj instanceof Number;+ }++ static promisify(nodeFunction: Function): Function {+ function promisified(...args) {+ return new Promise((resolve, reject) => {+ function callback(err, ...result) {+ if (err)+ return reject(err);+ if (result.length === 1)+ return resolve(result[0]);+ return resolve(result);+ }+ nodeFunction.call(null, ...args, callback);+ });+ }+ return promisified;+ }++ static async waitForEvent(+ emitter: NodeJS.EventEmitter,+ eventName: (string | symbol),+ predicate: Function,+ timeout: number,+ abortPromise: Promise<Error>): Promise<any> {+ let eventTimeout, resolveCallback, rejectCallback;+ const promise = new Promise((resolve, reject) => {+ resolveCallback = resolve;+ rejectCallback = reject;+ });+ const listener = Helper.addEventListener(emitter, eventName, event => {+ if (!predicate(event))+ return;+ resolveCallback(event);+ });+ if (timeout) {+ eventTimeout = setTimeout(() => {+ rejectCallback(new TimeoutError('Timeout exceeded while waiting for event'));+ }, timeout);+ }+ function cleanup() {+ Helper.removeEventListeners([listener]);+ clearTimeout(eventTimeout);+ }+ const result = await Promise.race([promise, abortPromise]).then(r => {+ cleanup();+ return r;+ }, e => {+ cleanup();+ throw e;+ });+ if (result instanceof Error)+ throw result;+ return result;+ }++ static async waitWithTimeout<T>(promise: Promise<T>, taskName: string, timeout: number): Promise<T> {+ let reject: (error: Error) => void;+ const timeoutError = new TimeoutError(`waiting for ${taskName} failed: timeout ${timeout}ms exceeded`);+ const timeoutPromise = new Promise<T>((resolve, x) => reject = x);+ let timeoutTimer = null;+ if (timeout)+ timeoutTimer = setTimeout(() => reject(timeoutError), timeout);+ try {+ return await Promise.race([promise, timeoutPromise]);+ } finally {+ if (timeoutTimer)+ clearTimeout(timeoutTimer);+ }+ }+}++export function assert(value: any, message?: string) {+ if (!value)+ throw new Error(message);+}++export const helper = Helper;diff --git a/src/webkit/Browser.ts b/src/webkit/Browser.tsnew file mode 100644index 0000000000..de6777544a--- /dev/null+++ b/src/webkit/Browser.ts@@ -0,0 +1,244 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import * as childProcess from 'child_process';+import { EventEmitter } from 'events';+import { Connection } from './Connection';+import { Events } from '../Events';+import { RegisteredListener, assert, helper } from '../helper';+import { Page, Viewport } from './Page';+import { Target } from './Target';+import { TaskQueue } from './TaskQueue';++export class Browser extends EventEmitter {+ _defaultViewport: Viewport;+ private _process: childProcess.ChildProcess;+ _screenshotTaskQueue = new TaskQueue();+ _connection: Connection;+ private _closeCallback: () => Promise<void>;+ private _defaultContext: BrowserContext;+ private _contexts = new Map<string, BrowserContext>();+ _targets = new Map<string, Target>();+ private _eventListeners: RegisteredListener[];++ static async create(+ connection: Connection,+ defaultViewport: Viewport | null,+ process: childProcess.ChildProcess | null,+ closeCallback?: (() => Promise<void>)) {+ const browser = new Browser(connection, defaultViewport, process, closeCallback);+ return browser;+ }++ constructor(+ connection: Connection,+ defaultViewport: Viewport | null,+ process: childProcess.ChildProcess | null,+ closeCallback?: (() => Promise<void>)) {+ super();+ this._defaultViewport = defaultViewport;+ this._process = process;+ this._connection = connection;+ this._closeCallback = closeCallback || (() => Promise.resolve());++ /** @type {!Map<string, !Target>} */+ this._targets = new Map();++ this._defaultContext = new BrowserContext(this);+ /** @type {!Map<string, !BrowserContext>} */+ this._contexts = new Map();++ this._eventListeners = [+ helper.addEventListener(this._connection, 'Target.targetCreated', this._onTargetCreated.bind(this)),+ helper.addEventListener(this._connection, 'Target.targetDestroyed', this._onTargetDestroyed.bind(this)),+ helper.addEventListener(this._connection, 'Target.didCommitProvisionalTarget', this._onProvisionalTargetCommitted.bind(this)),+ ];++ // Taking multiple screenshots in parallel doesn't work well, so we serialize them.+ this._screenshotTaskQueue = new TaskQueue();+ }++ process(): childProcess.ChildProcess | null {+ return this._process;+ }++ async createIncognitoBrowserContext(): Promise<BrowserContext> {+ const {browserContextId} = await this._connection.send('Browser.createContext');+ const context = new BrowserContext(this, browserContextId);+ this._contexts.set(browserContextId, context);+ return context;+ }++ browserContexts(): BrowserContext[] {+ return [this._defaultContext, ...Array.from(this._contexts.values())];+ }++ defaultBrowserContext(): BrowserContext {+ return this._defaultContext;+ }++ async _disposeContext(browserContextId: string | null) {+ await this._connection.send('Browser.deleteContext', {browserContextId});+ this._contexts.delete(browserContextId);+ }++ async newPage(): Promise<Page> {+ return this._createPageInContext(this._defaultContext._id);+ }++ async _createPageInContext(browserContextId?: string): Promise<Page> {+ const {targetId} = await this._connection.send('Browser.createPage', {browserContextId});+ const target = this._targets.get(targetId);+ return await target.page();+ }++ targets(): Target[] {+ return Array.from(this._targets.values());+ }++ async waitForTarget(predicate: (arg0: Target) => boolean, options: { timeout?: number; } | undefined = {}): Promise<Target> {+ const {+ timeout = 30000+ } = options;+ const existingTarget = this.targets().find(predicate);+ if (existingTarget)+ return existingTarget;+ let resolve;+ const targetPromise = new Promise<Target>(x => resolve = x);+ this.on(Events.Browser.TargetCreated, check);+ this.on(Events.Browser.TargetChanged, check);+ try {+ if (!timeout)+ return await targetPromise;+ return await helper.waitWithTimeout(targetPromise, 'target', timeout);+ } finally {+ this.removeListener(Events.Browser.TargetCreated, check);+ this.removeListener(Events.Browser.TargetChanged, check);+ }++ function check(target: Target) {+ if (predicate(target))+ resolve(target);+ }+ }++ async pages(): Promise<Page[]> {+ const contextPages = await Promise.all(this.browserContexts().map(context => context.pages()));+ // Flatten array.+ return contextPages.reduce((acc, x) => acc.concat(x), []);+ }++ async _onTargetCreated({targetInfo}) {+ let context = null;+ if (targetInfo.browserContextId) {+ // FIXME: we don't know about the default context id, so assume that all targets from+ // unknown contexts are created in the 'default' context which can in practice be represented+ // by multiple actual contexts in WebKit. Solving this properly will require adding context+ // lifecycle events.+ context = this._contexts.get(targetInfo.browserContextId);+ // if (!context)+ // throw new Error(`Target ${targetId} created in unknown browser context ${browserContextId}.`);+ }+ if (!context)+ context = this._defaultContext;+ const target = new Target(targetInfo, context);+ this._targets.set(targetInfo.targetId, target);+ if (target.opener() && target.opener()._pagePromise) {+ const openerPage = await target.opener()._pagePromise;+ if (openerPage.listenerCount(Events.Page.Popup)) {+ const popupPage = await target.page();+ openerPage.emit(Events.Page.Popup, popupPage);+ }+ }+ this.emit(Events.Browser.TargetCreated, target);+ context.emit(Events.BrowserContext.TargetCreated, target);+ }++ _onTargetDestroyed({targetId}) {+ const target = this._targets.get(targetId);+ this._targets.delete(targetId);+ target._closedCallback();+ this.emit(Events.Browser.TargetDestroyed, target);+ target.browserContext().emit(Events.BrowserContext.TargetDestroyed, target);+ }++ async _onProvisionalTargetCommitted({oldTargetId, newTargetId}) {+ const oldTarget = this._targets.get(oldTargetId);+ if (!oldTarget._pagePromise)+ return;+ const page = await oldTarget._pagePromise;+ const newTarget = this._targets.get(newTargetId);+ const newSession = this._connection.session(newTargetId);+ page._swapTargetOnNavigation(newSession, newTarget);+ newTarget._pagePromise = oldTarget._pagePromise;+ }++ _onTargetChanged(target) {+ this.emit(Events.BrowserContext.TargetChanged, target);+ target.browserContext().emit(Events.BrowserContext.TargetChanged, target);+ }++ async close() {+ helper.removeEventListeners(this._eventListeners);+ await this._closeCallback.call(null);+ }+}++export class BrowserContext extends EventEmitter {+ private _browser: Browser;+ _id: string;++ constructor(browser: Browser, contextId?: string) {+ super();+ this._browser = browser;+ this._id = contextId;+ }++ targets(): Target[] {+ return this._browser.targets().filter(target => target.browserContext() === this);+ }++ waitForTarget(predicate: (arg0: Target) => boolean, options: { timeout?: number; } | undefined): Promise<Target> {+ return this._browser.waitForTarget(target => target.browserContext() === this && predicate(target), options);+ }++ async pages(): Promise<Page[]> {+ const pages = await Promise.all(+ this.targets()+ .filter(target => target.type() === 'page')+ .map(target => target.page())+ );+ return pages.filter(page => !!page);+ }++ isIncognito(): boolean {+ return !!this._id;+ }++ newPage(): Promise<Page> {+ return this._browser._createPageInContext(this._id);+ }++ browser(): Browser {+ return this._browser;+ }++ async close() {+ assert(this._id, 'Non-incognito profiles cannot be closed!');+ await this._browser._disposeContext(this._id);+ }+}diff --git a/src/webkit/BrowserFetcher.ts b/src/webkit/BrowserFetcher.tsnew file mode 100644index 0000000000..7b72dedb04--- /dev/null+++ b/src/webkit/BrowserFetcher.ts@@ -0,0 +1,253 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import * as extract from 'extract-zip';+import * as fs from 'fs';+import * as ProxyAgent from 'https-proxy-agent';+import * as os from 'os';+import * as path from 'path';+import { getProxyForUrl } from 'proxy-from-env';+import * as removeRecursive from 'rimraf';+import * as URL from 'url';+import * as util from 'util';+import { assert, helper } from '../helper';+import {execSync} from 'child_process';++const DEFAULT_DOWNLOAD_HOST = 'https://playwrightaccount.blob.core.windows.net';++const supportedPlatforms = ['linux', 'mac'];+const downloadURLs = {+ linux: '%s/builds/webkit/%s/minibrowser-linux.zip',+ mac: '%s/builds/webkit/%s/minibrowser-mac-%s.zip',+};+let cachedMacVersion = undefined;+function getMacVersion() {+ if (!cachedMacVersion) {+ const [major, minor] = execSync('sw_vers -productVersion').toString('utf8').trim().split('.');+ cachedMacVersion = major + '.' + minor;+ }+ return cachedMacVersion;+}++function downloadURL(platform: string, host: string, revision: string): string {+ if (platform === 'mac')+ return util.format(downloadURLs['mac'], host, revision, getMacVersion());+ return util.format(downloadURLs[platform], host, revision);+}++const readdirAsync = helper.promisify(fs.readdir.bind(fs));+const mkdirAsync = helper.promisify(fs.mkdir.bind(fs));+const unlinkAsync = helper.promisify(fs.unlink.bind(fs));+const chmodAsync = helper.promisify(fs.chmod.bind(fs));++function existsAsync(filePath) {+ let fulfill = null;+ const promise = new Promise(x => fulfill = x);+ fs.access(filePath, err => fulfill(!err));+ return promise;+}++export class BrowserFetcher {+ private _downloadsFolder: string;+ private _downloadHost: string;+ private _platform: string;++ constructor(projectRoot: string, options: BrowserFetcherOptions = {}) {+ this._downloadsFolder = options.path || path.join(projectRoot, '.local-webkit');+ this._downloadHost = options.host || DEFAULT_DOWNLOAD_HOST;+ this._platform = options.platform || '';+ if (!this._platform) {+ const platform = os.platform();+ if (platform === 'darwin')+ this._platform = 'mac';+ else if (platform === 'linux')+ this._platform = 'linux';+ else if (platform === 'win32')+ this._platform = 'linux'; // Windows gets linux binaries and uses WSL+ assert(this._platform, 'Unsupported platform: ' + os.platform());+ }+ assert(supportedPlatforms.includes(this._platform), 'Unsupported platform: ' + this._platform);+ }++ platform(): string {+ return this._platform;+ }++ canDownload(revision: string): Promise<boolean> {+ const url = downloadURL(this._platform, this._downloadHost, revision);+ let resolve;+ const promise = new Promise<boolean>(x => resolve = x);+ const request = httpRequest(url, 'HEAD', response => {+ resolve(response.statusCode === 200);+ });+ request.on('error', error => {+ console.error(error);+ resolve(false);+ });+ return promise;+ }+ async download(revision: string, progressCallback: ((arg0: number, arg1: number) => void) | null): Promise<BrowserFetcherRevisionInfo> {+ const url = downloadURL(this._platform, this._downloadHost, revision);+ const zipPath = path.join(this._downloadsFolder, `download-${this._platform}-${revision}.zip`);+ const folderPath = this._getFolderPath(revision);+ if (await existsAsync(folderPath))+ return this.revisionInfo(revision);+ if (!(await existsAsync(this._downloadsFolder)))+ await mkdirAsync(this._downloadsFolder);+ try {+ await downloadFile(url, zipPath, progressCallback);+ await extractZip(zipPath, folderPath);+ } finally {+ if (await existsAsync(zipPath))+ await unlinkAsync(zipPath);+ }+ const revisionInfo = this.revisionInfo(revision);+ if (revisionInfo)+ await chmodAsync(revisionInfo.executablePath, 0o755);+ return revisionInfo;+ }++ async localRevisions(): Promise<string[]> {+ if (!await existsAsync(this._downloadsFolder))+ return [];+ const fileNames = await readdirAsync(this._downloadsFolder);+ return fileNames.map(fileName => parseFolderPath(fileName)).filter(entry => entry && entry.platform === this._platform).map(entry => entry.revision);+ }++ async remove(revision: string) {+ const folderPath = this._getFolderPath(revision);+ assert(await existsAsync(folderPath), `Failed to remove: revision ${revision} is not downloaded`);+ await new Promise(fulfill => removeRecursive(folderPath, fulfill));+ }++ revisionInfo(revision: string): BrowserFetcherRevisionInfo {+ const folderPath = this._getFolderPath(revision);+ let executablePath = '';+ if (this._platform === 'linux' || this._platform === 'mac')+ executablePath = path.join(folderPath, 'pw_run.sh');+ else+ throw new Error('Unsupported platform: ' + this._platform);+ const url = downloadURL(this._platform, this._downloadHost, revision);+ const local = fs.existsSync(folderPath);+ return {revision, executablePath, folderPath, local, url};+ }++ _getFolderPath(revision: string): string {+ return path.join(this._downloadsFolder, this._platform + '-' + revision);+ }+}++function parseFolderPath(folderPath: string): { platform: string; revision: string; } | null {+ const name = path.basename(folderPath);+ const splits = name.split('-');+ if (splits.length !== 2)+ return null;+ const [platform, revision] = splits;+ if (!supportedPlatforms.includes(platform))+ return null;+ return {platform, revision};+}++function downloadFile(url: string, destinationPath: string, progressCallback: ((arg0: number, arg1: number) => void) | null): Promise<any> {+ let fulfill, reject;+ let downloadedBytes = 0;+ let totalBytes = 0;++ const promise = new Promise((x, y) => { fulfill = x; reject = y; });++ const request = httpRequest(url, 'GET', response => {+ if (response.statusCode !== 200) {+ const error = new Error(`Download failed: server returned code ${response.statusCode}. URL: ${url}`);+ // consume response data to free up memory+ response.resume();+ reject(error);+ return;+ }+ const file = fs.createWriteStream(destinationPath);+ file.on('finish', () => fulfill());+ file.on('error', error => reject(error));+ response.pipe(file);+ totalBytes = parseInt(response.headers['content-length'], 10);+ if (progressCallback)+ response.on('data', onData);+ });+ request.on('error', error => reject(error));+ return promise;++ function onData(chunk) {+ downloadedBytes += chunk.length;+ progressCallback(downloadedBytes, totalBytes);+ }+}++function extractZip(zipPath: string, folderPath: string): Promise<Error | null> {+ return new Promise((fulfill, reject) => extract(zipPath, {dir: folderPath}, err => {+ if (err)+ reject(err);+ else+ fulfill();+ }));+}++function httpRequest(url: string, method: string, response: (r: any) => void) {+ let options: any = URL.parse(url);+ options.method = method;++ const proxyURL = getProxyForUrl(url);+ if (proxyURL) {+ if (url.startsWith('http:')) {+ const proxy = URL.parse(proxyURL);+ options = {+ path: options.href,+ host: proxy.hostname,+ port: proxy.port,+ };+ } else {+ const parsedProxyURL: any = URL.parse(proxyURL);+ parsedProxyURL.secureProxy = parsedProxyURL.protocol === 'https:';++ options.agent = new ProxyAgent(parsedProxyURL);+ options.rejectUnauthorized = false;+ }+ }++ const requestCallback = res => {+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location)+ httpRequest(res.headers.location, method, response);+ else+ response(res);+ };+ const request = options.protocol === 'https:' ?+ require('https').request(options, requestCallback) :+ require('http').request(options, requestCallback);+ request.end();+ return request;+}++export type BrowserFetcherOptions = {+ platform?: string,+ path?: string,+ host ?: string,+};++type BrowserFetcherRevisionInfo = {+ folderPath: string,+ executablePath: string,+ url: string,+ local: boolean,+ revision: string,+};diff --git a/src/webkit/Connection.ts b/src/webkit/Connection.tsnew file mode 100644index 0000000000..43386a6089--- /dev/null+++ b/src/webkit/Connection.ts@@ -0,0 +1,247 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import {assert} from '../helper';+import * as debug from 'debug';+import {EventEmitter} from 'events';+import { ConnectionTransport } from '../ConnectionTransport';+import { Protocol } from './protocol';++const debugProtocol = debug('playwright:protocol');+const debugWrappedMessage = require('debug')('wrapped');++export const ConnectionEvents = {+ Disconnected: Symbol('ConnectionEvents.Disconnected')+};++export class Connection extends EventEmitter {+ private _url: string;+ _lastId = 0;+ private _callbacks = new Map<number, {resolve:(o: any) => void, reject: (e: Error) => void, error: Error, method: string}>();+ private _delay: number;+ private _transport: ConnectionTransport;+ private _sessions = new Map<string, TargetSession>();+ _closed = false;++ constructor(url: string, transport: ConnectionTransport, delay: number | undefined = 0) {+ super();+ this._url = url;+ this._delay = delay;++ this._transport = transport;+ this._transport.onmessage = this._onMessage.bind(this);+ this._transport.onclose = this._onClose.bind(this);+ }++ static fromSession(session: TargetSession): Connection {+ return session._connection;+ }++ url(): string {+ return this._url;+ }++ send<T extends keyof Protocol.CommandParameters>(+ method: T,+ params?: Protocol.CommandParameters[T]+ ): Promise<Protocol.CommandReturnValues[T]> {+ const id = this._rawSend({method, params});+ return new Promise((resolve, reject) => {+ this._callbacks.set(id, {resolve, reject, error: new Error(), method});+ });+ }++ _rawSend(message: any): number {+ const id = ++this._lastId;+ message = JSON.stringify(Object.assign({}, message, {id}));+ debugProtocol('SEND ► ' + message);+ this._transport.send(message);+ return id;+ }++ async _onMessage(message: string) {+ if (this._delay)+ await new Promise(f => setTimeout(f, this._delay));+ debugProtocol('◀ RECV ' + message);+ const object = JSON.parse(message);+ this._dispatchTargetMessageToSession(object);+ if (object.id) {+ const callback = this._callbacks.get(object.id);+ // Callbacks could be all rejected if someone has called `.dispose()`.+ if (callback) {+ this._callbacks.delete(object.id);+ if (object.error)+ callback.reject(createProtocolError(callback.error, callback.method, object));+ else+ callback.resolve(object.result);+ } else {+ assert(this._closed, 'Received response for unknown callback: ' + object.id);+ }+ } else {+ this.emit(object.method, object.params);+ }+ }++ _dispatchTargetMessageToSession(object: {method: string, params: any}) {+ if (object.method === 'Target.targetCreated') {+ const {targetId, type} = object.params.targetInfo;+ // FIXME: this is a workaround for cross-origin navigation in WebKit.+ // console.log(`[${targetId}] ${object.method}`);+ const session = new TargetSession(this, type, targetId);+ this._sessions.set(targetId, session);+ } else if (object.method === 'Target.targetDestroyed') {+ // console.log(`[${object.params.targetId}] ${object.method}`);+ const session = this._sessions.get(object.params.targetId);+ if (session) {+ // FIXME: this is a workaround for cross-origin navigation in WebKit.+ session._onClosed();+ this._sessions.delete(object.params.targetId);+ }+ } else if (object.method === 'Target.dispatchMessageFromTarget') {+ const session = this._sessions.get(object.params.targetId);+ if (!session)+ throw new Error('Unknown target: ' + object.params.targetId);+ session._dispatchMessageFromTarget(object.params.message);+ } else if (object.method === 'Target.didCommitProvisionalTarget') {+ const {oldTargetId, newTargetId} = object.params;+ const newSession = this._sessions.get(newTargetId);+ if (!newSession)+ throw new Error('Unknown new target: ' + newTargetId);+ const oldSession = this._sessions.get(oldTargetId);+ if (!oldSession)+ throw new Error('Unknown old target: ' + oldTargetId);+ }+ }++ _onClose() {+ if (this._closed)+ return;+ this._closed = true;+ this._transport.onmessage = null;+ this._transport.onclose = null;+ for (const callback of this._callbacks.values())+ callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));+ this._callbacks.clear();+ for (const session of this._sessions.values())+ session._onClosed();+ this._sessions.clear();+ this.emit(ConnectionEvents.Disconnected);+ }++ dispose() {+ this._onClose();+ this._transport.close();+ }++ session(targetId: string) : TargetSession {+ return this._sessions.get(targetId);+ }+}++export const TargetSessionEvents = {+ Disconnected: Symbol('TargetSessionEvents.Disconnected')+};++export class TargetSession extends EventEmitter {+ _connection: Connection;+ private _callbacks = new Map<number, {resolve:(o: any) => void, reject: (e: Error) => void, error: Error, method: string}>();+ private _targetType: string;+ private _sessionId: string;+ private _out = [];+ private _in = [];+ on: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ addListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ off: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ removeListener: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;+ once: <T extends keyof Protocol.Events | symbol>(event: T, listener: (payload: T extends symbol ? any : Protocol.Events[T extends keyof Protocol.Events ? T : never]) => void) => this;++ constructor(connection: Connection, targetType: string, sessionId: string) {+ super();+ this._connection = connection;+ this._targetType = targetType;+ this._sessionId = sessionId;+ }++ send<T extends keyof Protocol.CommandParameters>(+ method: T,+ params?: Protocol.CommandParameters[T]+ ): Promise<Protocol.CommandReturnValues[T]> {+ if (!this._connection)+ return Promise.reject(new Error(`Protocol error (${method}): Session closed. Most likely the ${this._targetType} has been closed.`));+ const innerId = ++this._connection._lastId;+ const messageObj = {+ id: innerId,+ method,+ params+ };+ debugWrappedMessage('SEND ► ' + JSON.stringify(messageObj, null, 2));+ this._out.push(messageObj);+ // Serialize message before adding callback in case JSON throws.+ const message = JSON.stringify(messageObj);+ const result = new Promise<Protocol.CommandReturnValues[T]>((resolve, reject) => {+ this._callbacks.set(innerId, {resolve, reject, error: new Error(), method});+ });+ this._connection.send('Target.sendMessageToTarget', {+ message: message, targetId: this._sessionId+ }).catch(e => {+ // There is a possible race of the connection closure. We may have received+ // targetDestroyed notification before response for the command, in that+ // case it's safe to swallow the exception.g+ const callback = this._callbacks.get(innerId);+ assert(!callback, 'Callback was not rejected when target was destroyed.');+ });+ return result;+ }++ _dispatchMessageFromTarget(message: string) {+ const object = JSON.parse(message);+ debugWrappedMessage('◀ RECV ' + JSON.stringify(object, null, 2));+ this._in.push(object);+ if (object.id && this._callbacks.has(object.id)) {+ const callback = this._callbacks.get(object.id);+ this._callbacks.delete(object.id);+ if (object.error)+ callback.reject(createProtocolError(callback.error, callback.method, object));+ else+ callback.resolve(object.result);+ } else {+ assert(!object.id);+ // console.log(`[${this._sessionId}] ${object.method}`);+ this.emit(object.method, object.params);+ }+ }++ _onClosed() {+ for (const callback of this._callbacks.values())+ callback.reject(rewriteError(callback.error, `Protocol error (${callback.method}): Target closed.`));+ this._callbacks.clear();+ this._connection = null;+ this.emit(TargetSessionEvents.Disconnected);+ }+}++function createProtocolError(error: Error, method: string, object: { error: { message: string; data: any; }; }): Error {+ let message = `Protocol error (${method}): ${object.error.message}`;+ if ('data' in object.error)+ message += ` ${object.error.data}`;+ return rewriteError(error, message);+}++function rewriteError(error: Error, message: string): Error {+ error.message = message;+ return error;+}diff --git a/src/webkit/ExecutionContext.ts b/src/webkit/ExecutionContext.tsnew file mode 100644index 0000000000..8662be618b--- /dev/null+++ b/src/webkit/ExecutionContext.ts@@ -0,0 +1,303 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { TargetSession } from './Connection';+import { Frame } from './FrameManager';+import { helper } from '../helper';+import { valueFromRemoteObject } from './protocolHelper';+import { createJSHandle, JSHandle } from './JSHandle';+import { Protocol } from './protocol';+++export const EVALUATION_SCRIPT_URL = '__playwright_evaluation_script__';+const SOURCE_URL_REGEX = /^[\040\t]*\/\/[@#] sourceURL=\s*(\S*?)\s*$/m;++export class ExecutionContext {+ _globalObjectId?: string;+ _session: TargetSession;+ _frame: Frame;+ _contextId: number;+ private _contextDestroyedCallback: any;+ private _executionContextDestroyedPromise: Promise<unknown>;++ constructor(client: TargetSession, contextPayload: Protocol.Runtime.ExecutionContextDescription, frame: Frame | null) {+ this._session = client;+ this._frame = frame;+ this._contextId = contextPayload.id;+ this._contextDestroyedCallback = null;+ this._executionContextDestroyedPromise = new Promise((resolve, reject) => {+ this._contextDestroyedCallback = resolve;+ });+ }++ _dispose() {+ this._contextDestroyedCallback();+ }++ frame(): Frame | null {+ return this._frame;+ }++ async evaluate(pageFunction: Function | string, ...args: any[]): Promise<any> {+ return await this._evaluateInternal(true /* returnByValue */, pageFunction, ...args);+ }++ async evaluateHandle(pageFunction: Function | string, ...args: any[]): Promise<JSHandle> {+ return this._evaluateInternal(false /* returnByValue */, pageFunction, ...args);+ }++ async _evaluateInternal(returnByValue: boolean, pageFunction: Function | string, ...args: any[]): Promise<any> {+ const suffix = `//# sourceURL=${EVALUATION_SCRIPT_URL}`;++ if (helper.isString(pageFunction)) {+ const contextId = this._contextId;+ const expression: string = pageFunction as string;+ const expressionWithSourceUrl = SOURCE_URL_REGEX.test(expression) ? expression : expression + '\n' + suffix;+ return this._session.send('Runtime.evaluate', {+ expression: expressionWithSourceUrl,+ contextId,+ returnByValue: false,+ emulateUserGesture: true+ }).then(response => {+ if (response.result.type === 'object' && response.result.className === 'Promise') {+ const contextDiscarded = this._executionContextDestroyedPromise.then(() => ({+ wasThrown: true,+ result: {+ description: 'Protocol error: Execution context was destroyed, most likely because of a navigation.'+ } as Protocol.Runtime.RemoteObject+ }));+ return Promise.race([+ contextDiscarded,+ this._session.send('Runtime.awaitPromise', {+ promiseObjectId: response.result.objectId,+ returnByValue: false+ })+ ]);+ }+ return response;+ }).then(response => {+ if (response.wasThrown)+ throw new Error('Evaluation failed: ' + response.result.description);+ if (!returnByValue)+ return createJSHandle(this, response.result);+ if (response.result.objectId) {+ const serializeFunction = function() {+ try {+ return JSON.stringify(this);+ } catch (e) {+ if (e instanceof TypeError)+ return void 0;+ throw e;+ }+ };+ return this._session.send('Runtime.callFunctionOn', {+ // Serialize object using standard JSON implementation to correctly pass 'undefined'.+ functionDeclaration: serializeFunction + '\n' + suffix + '\n',+ objectId: response.result.objectId,+ returnByValue+ }).then(serializeResponse => {+ if (serializeResponse.wasThrown)+ throw new Error('Serialization failed: ' + serializeResponse.result.description);+ // This is the case of too long property chain, not serializable to json string.+ if (serializeResponse.result.type === 'undefined')+ return undefined;+ if (serializeResponse.result.type !== 'string')+ throw new Error('Unexpected result of JSON.stringify: ' + JSON.stringify(serializeResponse, null, 2));+ return JSON.parse(serializeResponse.result.value);+ });+ }+ return valueFromRemoteObject(response.result);+ }).catch(rewriteError);+ }++ if (typeof pageFunction !== 'function')+ throw new Error(`Expected to get |string| or |function| as the first argument, but got "${pageFunction}" instead.`);++ let functionText = pageFunction.toString();+ try {+ new Function('(' + functionText + ')');+ } catch (e1) {+ // This means we might have a function shorthand. Try another+ // time prefixing 'function '.+ if (functionText.startsWith('async '))+ functionText = 'async function ' + functionText.substring('async '.length);+ else+ functionText = 'function ' + functionText;+ try {+ new Function('(' + functionText + ')');+ } catch (e2) {+ // We tried hard to serialize, but there's a weird beast here.+ throw new Error('Passed function is not well-serializable!');+ }+ }++ let serializableArgs;+ if (args.some(isUnserializable)) {+ serializableArgs = [];+ const paramStrings = [];+ for (const arg of args) {+ if (isUnserializable(arg)) {+ paramStrings.push(unserializableToString(arg));+ } else {+ paramStrings.push('arguments[' + serializableArgs.length + ']');+ serializableArgs.push(arg);+ }+ }+ functionText = `() => (${functionText})(${paramStrings.join(',')})`;+ } else {+ serializableArgs = args;+ }++ const thisObjectId = await this._contextGlobalObjectId();+ let callFunctionOnPromise;+ try {+ callFunctionOnPromise = this._session.send('Runtime.callFunctionOn', {+ functionDeclaration: functionText + '\n' + suffix + '\n',+ // TODO(yurys): support executionContextId in WebKit+ objectId: thisObjectId,+ arguments: serializableArgs.map(convertArgument.bind(this)),+ returnByValue: false,+ emulateUserGesture: true+ });+ } catch (err) {+ if (err instanceof TypeError && err.message.startsWith('Converting circular structure to JSON'))+ err.message += ' Are you passing a nested JSHandle?';+ throw err;+ }+ return callFunctionOnPromise.then(response => {+ if (response.result.type === 'object' && response.result.className === 'Promise') {+ const contextDiscarded = this._executionContextDestroyedPromise.then(() => ({+ wasThrown: true,+ result: {+ description: 'Protocol error: Execution context was destroyed, most likely because of a navigation.'+ } as Protocol.Runtime.RemoteObject+ }));+ return Promise.race([+ contextDiscarded,+ this._session.send('Runtime.awaitPromise', {+ promiseObjectId: response.result.objectId,+ returnByValue: false+ })+ ]);+ }+ return response;+ }).then(response => {+ if (response.wasThrown)+ throw new Error('Evaluation failed: ' + response.result.description);+ if (!returnByValue)+ return createJSHandle(this, response.result);+ if (response.result.objectId) {+ const serializeFunction = function() {+ try {+ return JSON.stringify(this);+ } catch (e) {+ if (e instanceof TypeError)+ return void 0;+ throw e;+ }+ };+ return this._session.send('Runtime.callFunctionOn', {+ // Serialize object using standard JSON implementation to correctly pass 'undefined'.+ functionDeclaration: serializeFunction + '\n' + suffix + '\n',+ objectId: response.result.objectId,+ returnByValue+ }).then(serializeResponse => {+ if (serializeResponse.wasThrown)+ throw new Error('Serialization failed: ' + serializeResponse.result.description);+ // This is the case of too long property chain, not serializable to json string.+ if (serializeResponse.result.type === 'undefined')+ return undefined;+ if (serializeResponse.result.type !== 'string')+ throw new Error('Unexpected result of JSON.stringify: ' + JSON.stringify(serializeResponse, null, 2));+ return JSON.parse(serializeResponse.result.value);+ });+ }+ return valueFromRemoteObject(response.result);+ }).catch(rewriteError);++ function convertArgument(this: ExecutionContext, arg: JSHandle | any) : Protocol.Runtime.CallArgument{+ const objectHandle = arg && (arg instanceof JSHandle) ? arg : null;+ if (objectHandle) {+ if (objectHandle._context !== this)+ throw new Error('JSHandles can be evaluated only in the context they were created!');+ if (objectHandle._disposed)+ throw new Error('JSHandle is disposed!');+ if (!objectHandle._remoteObject.objectId)+ return { value: valueFromRemoteObject(objectHandle._remoteObject) };+ return { objectId: objectHandle._remoteObject.objectId };+ }+ return { value: arg };+ }++ function unserializableToString(arg) {+ if (Object.is(arg, -0))+ return '-0';+ if (Object.is(arg, Infinity))+ return 'Infinity';+ if (Object.is(arg, -Infinity))+ return '-Infinity';+ if (Object.is(arg, NaN))+ return 'NaN';+ if (arg instanceof JSHandle) {+ const remoteObj = arg._remoteObject;+ if (!remoteObj.objectId)+ return valueFromRemoteObject(remoteObj);+ }+ throw new Error('Unsupported value: ' + arg + ' (' + (typeof arg) + ')');+ }++ function isUnserializable(arg) {+ if (typeof arg === 'bigint')+ return true;+ if (Object.is(arg, -0))+ return true;+ if (Object.is(arg, Infinity))+ return true;+ if (Object.is(arg, -Infinity))+ return true;+ if (Object.is(arg, NaN))+ return true;+ if (arg instanceof JSHandle) {+ const remoteObj = arg._remoteObject;+ if (!remoteObj.objectId)+ return !Object.is(valueFromRemoteObject(remoteObj), remoteObj.value);+ }+ return false;+ }++ /**+ * @param {!Error} error+ * @return {!Protocol.Runtime.evaluateReturnValue}+ */+ function rewriteError(error) {+ if (error.message.includes('Object couldn\'t be returned by value'))+ return {result: {type: 'undefined'}};++ if (error.message.includes('Missing injected script for given'))+ throw new Error('Execution context was destroyed, most likely because of a navigation.');+ throw error;+ }+ }++ async _contextGlobalObjectId() {+ if (!this._globalObjectId) {+ const globalObject = await this._session.send('Runtime.evaluate', { expression: 'this', contextId: this._contextId });+ this._globalObjectId = globalObject.result.objectId;+ }+ return this._globalObjectId;+ }+}diff --git a/src/webkit/FrameManager.ts b/src/webkit/FrameManager.tsnew file mode 100644index 0000000000..d170632e3a--- /dev/null+++ b/src/webkit/FrameManager.ts@@ -0,0 +1,944 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import * as EventEmitter from 'events';+import * as fs from 'fs';+import { TimeoutError } from '../Errors';+import { Events } from '../Events';+import { assert, debugError, helper, RegisteredListener } from '../helper';+import { TimeoutSettings } from '../TimeoutSettings';+import { TargetSession } from './Connection';+import { ExecutionContext } from './ExecutionContext';+import { ElementHandle, JSHandle } from './JSHandle';+import { NetworkManager, NetworkManagerEvents, Request, Response } from './NetworkManager';+import { Page } from './Page';+import { Protocol } from './protocol';+const readFileAsync = helper.promisify(fs.readFile);++export const FrameManagerEvents = {+ FrameNavigatedWithinDocument: Symbol('FrameNavigatedWithinDocument'),+ TargetSwappedOnNavigation: Symbol('TargetSwappedOnNavigation'),+ FrameAttached: Symbol('FrameAttached'),+ FrameDetached: Symbol('FrameDetached'),+ FrameNavigated: Symbol('FrameNavigated'),+};++export class FrameManager extends EventEmitter {+ _session: TargetSession;+ _page: Page;+ _networkManager: NetworkManager;+ _timeoutSettings: TimeoutSettings;+ _frames: Map<string, Frame>;+ _contextIdToContext: Map<number, ExecutionContext>;+ _isolatedWorlds: Set<string>;+ _sessionListeners: RegisteredListener[];+ _mainFrame: Frame;+ constructor(session: TargetSession, page: Page, timeoutSettings: TimeoutSettings) {+ super();+ this._session = session;+ this._page = page;+ this._networkManager = new NetworkManager(session, this);+ this._timeoutSettings = timeoutSettings;+ this._frames = new Map();+ this._contextIdToContext = new Map();+ this._isolatedWorlds = new Set();++ this._addSessionListeners();+ }++ async initialize() {+ const [,{frameTree}] = await Promise.all([+ // Page agent must be enabled before Runtime.+ this._session.send('Page.enable'),+ this._session.send('Page.getResourceTree'),+ ]);+ this._handleFrameTree(frameTree);+ await Promise.all([+ this._session.send('Runtime.enable'),+ this._networkManager.initialize(),+ ]);+ }++ _addSessionListeners() {+ this._sessionListeners = [+ helper.addEventListener(this._session, 'Page.frameNavigated', event => this._onFrameNavigated(event.frame)),+ helper.addEventListener(this._session, 'Page.navigatedWithinDocument', event => this._onFrameNavigatedWithinDocument(event.frameId, event.url)),+ helper.addEventListener(this._session, 'Page.frameDetached', event => this._onFrameDetached(event.frameId)),+ helper.addEventListener(this._session, 'Page.frameStoppedLoading', event => this._onFrameStoppedLoading(event.frameId)),+ helper.addEventListener(this._session, 'Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)),+ ];+ }++ async _swapTargetOnNavigation(newSession) {+ helper.removeEventListeners(this._sessionListeners);+ this.disconnectFromTarget();+ this._session = newSession;+ this._addSessionListeners();+ this._networkManager.setSession(newSession);+ this.emit(FrameManagerEvents.TargetSwappedOnNavigation);+ // this.initialize() will be called by page.+ }++ disconnectFromTarget() {+ for (const frame of this.frames())+ frame._setContext(null);+ // this._mainFrame = null;+ }++ networkManager(): NetworkManager {+ return this._networkManager;+ }++ _onFrameStoppedLoading(frameId: string) {+ const frame = this._frames.get(frameId);+ if (!frame)+ return;+ frame._onLoadingStopped();+ }++ _handleFrameTree(frameTree: Protocol.Page.FrameResourceTree) {+ if (frameTree.frame.parentId)+ this._onFrameAttached(frameTree.frame.id, frameTree.frame.parentId);+ this._onFrameNavigated(frameTree.frame);+ if (!frameTree.childFrames)+ return;++ for (const child of frameTree.childFrames)+ this._handleFrameTree(child);+ }++ page(): Page {+ return this._page;+ }++ mainFrame(): Frame {+ return this._mainFrame;+ }++ frames(): Array<Frame> {+ return Array.from(this._frames.values());+ }++ frame(frameId: string): Frame | null {+ return this._frames.get(frameId) || null;+ }++ _onFrameAttached(frameId: string, parentFrameId: string | null) {+ if (this._frames.has(frameId))+ return;+ assert(parentFrameId);+ const parentFrame = this._frames.get(parentFrameId);+ const frame = new Frame(this, this._session, parentFrame, frameId);+ this._frames.set(frame._id, frame);+ this.emit(FrameManagerEvents.FrameAttached, frame);+ return frame;+ }++ _onFrameNavigated(framePayload: Protocol.Page.Frame) {+ const isMainFrame = !framePayload.parentId;+ let frame = isMainFrame ? this._mainFrame : this._frames.get(framePayload.id);++ // Detach all child frames first.+ if (frame) {+ for (const child of frame.childFrames())+ this._removeFramesRecursively(child);+ if (isMainFrame) {+ // Update frame id to retain frame identity on cross-process navigation.+ this._frames.delete(frame._id);+ frame._id = framePayload.id;+ this._frames.set(framePayload.id, frame);+ }+ } else if (isMainFrame) {+ // Initial frame navigation.+ frame = new Frame(this, this._session, null, framePayload.id);+ this._frames.set(framePayload.id, frame);+ } else {+ // FIXME(WebKit): there is no Page.frameAttached event in WK.+ frame = this._onFrameAttached(framePayload.id, framePayload.parentId);+ }+ // Update or create main frame.+ if (isMainFrame)+ this._mainFrame = frame;++ // Update frame payload.+ frame._navigated(framePayload);++ this.emit(FrameManagerEvents.FrameNavigated, frame);+ }++ _onFrameNavigatedWithinDocument(frameId: string, url: string) {+ const frame = this._frames.get(frameId);+ if (!frame)+ return;+ frame._navigatedWithinDocument(url);+ this.emit(FrameManagerEvents.FrameNavigatedWithinDocument, frame);+ this.emit(FrameManagerEvents.FrameNavigated, frame);+ }++ _onFrameDetached(frameId: string) {+ const frame = this._frames.get(frameId);+ if (frame)+ this._removeFramesRecursively(frame);+ }++ _onExecutionContextCreated(contextPayload : Protocol.Runtime.ExecutionContextDescription) {+ if (!contextPayload.isPageContext)+ return;+ const frameId = contextPayload.frameId;+ // If the frame was attached manually there is no navigation event.+ // FIXME: support frameAttached event in WebKit protocol.+ const frame = this._frames.get(frameId) || null;+ if (!frame)+ return;+ // FIXME(WebKit): we ignore duplicate Runtime.executionContextCreated events here.+ if (frame._executionContext && frame._executionContext._contextId === contextPayload.id)+ return;+ /** @type {!ExecutionContext} */+ const context: ExecutionContext = new ExecutionContext(this._session, contextPayload, frame);+ frame._setContext(context);+ this._contextIdToContext.set(contextPayload.id, context);+ }++ executionContextById(contextId: number): ExecutionContext {+ const context = this._contextIdToContext.get(contextId);+ assert(context, 'INTERNAL ERROR: missing context with id = ' + contextId);+ return context;+ }++ _removeFramesRecursively(frame: Frame) {+ for (const child of frame.childFrames())+ this._removeFramesRecursively(child);+ frame._detach();+ this._frames.delete(frame._id);+ this.emit(FrameManagerEvents.FrameDetached, frame);+ }+}++export class Frame {+ _id: string;+ _frameManager: FrameManager;+ _session: any;+ _parentFrame: Frame;+ _url: string;+ _detached: boolean;+ _loaderId: string;+ _lifecycleEvents: Set<string>;+ _waitTasks: Set<WaitTask>;+ _executionContext: ExecutionContext;+ _contextPromise: Promise<ExecutionContext>;+ _contextResolveCallback: (arg: ExecutionContext) => void;+ _childFrames: Set<Frame>;+ _documentPromise: Promise<ElementHandle>;+ _name: string;+ _navigationURL: any;+ constructor(frameManager: FrameManager, client: TargetSession, parentFrame: Frame | null, frameId: string) {+ this._frameManager = frameManager;+ this._session = client;+ this._parentFrame = parentFrame;+ this._url = '';+ this._id = frameId;+ this._detached = false;++ this._loaderId = '';+ /** @type {!Set<string>} */+ this._lifecycleEvents = new Set();++ /** @type {!Set<!WaitTask>} */+ this._waitTasks = new Set();++ this._executionContext = null;+ this._contextPromise = null;+ this._contextResolveCallback = null;+ this._setContext(null);++ /** @type {!Set<!Frame>} */+ this._childFrames = new Set();+ if (this._parentFrame)+ this._parentFrame._childFrames.add(this);+ }++ async goto(url: string, options: { referer?: string; timeout?: number; waitUntil?: string | Array<string>; } | undefined = {}): Promise<Response | null> {+ const {+ timeout = this._frameManager._timeoutSettings.navigationTimeout(),+ } = options;+ const watchDog = new NextNavigationWatchdog(this, timeout);+ await this._session.send('Page.navigate', {url});+ return watchDog.waitForNavigation();+ }++ async waitForNavigation(): Promise<Response | null> {+ // FIXME: this method only works for main frames.+ const watchDog = new NextNavigationWatchdog(this, 10000);+ return watchDog.waitForNavigation();+ }++ waitForSelector(selector: string, options: { visible?: boolean; hidden?: boolean; timeout?: number; } | undefined): Promise<ElementHandle | null> {+ return this._waitForSelectorOrXPath(selector, false, options);+ }++ waitForXPath(xpath: string, options: { visible?: boolean; hidden?: boolean; timeout?: number; } | undefined): Promise<ElementHandle | null> {+ return this._waitForSelectorOrXPath(xpath, true, options);+ }++ waitForFunction(pageFunction: Function | string, options: { polling?: string | number; timeout?: number; } | undefined = {}, ...args): Promise<JSHandle> {+ const {+ polling = 'raf',+ timeout = this._frameManager._timeoutSettings.timeout(),+ } = options;+ return new WaitTask(this, pageFunction, 'function', polling, timeout, ...args).promise;+ }++ async executionContext(): Promise<ExecutionContext> {+ if (this._detached)+ throw new Error(`Execution Context is not available in detached frame`);+ return this._contextPromise;+ }++ async evaluateHandle(pageFunction: Function | string, ...args: Array<any>): Promise<JSHandle> {+ const context = await this.executionContext();+ return context.evaluateHandle(pageFunction, ...args);+ }++ async evaluate(pageFunction: Function | string, ...args: Array<any>): Promise<any> {+ const context = await this.executionContext();+ return context.evaluate(pageFunction, ...args);+ }++ async $(selector: string): Promise<ElementHandle | null> {+ const document = await this._document();+ const value = await document.$(selector);+ return value;+ }++ _document(): Promise<ElementHandle> {+ if (!this._documentPromise) {+ this._documentPromise = this.executionContext().then(async context => {+ const document = await context.evaluateHandle('document');+ return document.asElement();+ });+ }+ return this._documentPromise;+ }++ async $x(expression: string): Promise<Array<ElementHandle>> {+ const document = await this._document();+ const value = await document.$x(expression);+ return value;+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: Array<any>): Promise<(any)> {+ const document = await this._document();+ return document.$eval(selector, pageFunction, ...args);+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: Array<any>): Promise<(any)> {+ const document = await this._document();+ const value = await document.$$eval(selector, pageFunction, ...args);+ return value;+ }++ async $$(selector: string): Promise<Array<ElementHandle>> {+ const document = await this._document();+ const value = await document.$$(selector);+ return value;+ }++ async content(): Promise<string> {+ return await this.evaluate(() => {+ let retVal = '';+ if (document.doctype)+ retVal = new XMLSerializer().serializeToString(document.doctype);+ if (document.documentElement)+ retVal += document.documentElement.outerHTML;+ return retVal;+ });+ }++ async setContent(html: string, options: { timeout?: number; waitUntil?: string | Array<string>; } | undefined = {}) {+ // We rely upon the fact that document.open() will trigger Page.loadEventFired.+ const watchDog = new NextNavigationWatchdog(this, 1000);+ await this.evaluate(html => {+ document.open();+ document.write(html);+ document.close();+ }, html);+ await watchDog.waitForNavigation();+ }++ async addScriptTag(options: { url?: string; path?: string; content?: string; type?: string; }): Promise<ElementHandle> {+ const {+ url = null,+ path = null,+ content = null,+ type = ''+ } = options;+ if (url !== null) {+ try {+ const context = await this.executionContext();+ return (await context.evaluateHandle(addScriptUrl, url, type)).asElement();+ } catch (error) {+ throw new Error(`Loading script from ${url} failed`);+ }+ }++ if (path !== null) {+ let contents = await readFileAsync(path, 'utf8');+ contents += '//# sourceURL=' + path.replace(/\n/g, '');+ const context = await this.executionContext();+ return (await context.evaluateHandle(addScriptContent, contents, type)).asElement();+ }++ if (content !== null) {+ const context = await this.executionContext();+ return (await context.evaluateHandle(addScriptContent, content, type)).asElement();+ }++ throw new Error('Provide an object with a `url`, `path` or `content` property');++ /**+ */+ async function addScriptUrl(url: string, type: string): Promise<HTMLElement> {+ const script = document.createElement('script');+ script.src = url;+ if (type)+ script.type = type;+ const promise = new Promise((res, rej) => {+ script.onload = res;+ script.onerror = rej;+ });+ document.head.appendChild(script);+ await promise;+ return script;+ }++ /**+ */+ function addScriptContent(content: string, type: string = 'text/javascript'): HTMLElement {+ const script = document.createElement('script');+ script.type = type;+ script.text = content;+ let error = null;+ script.onerror = e => error = e;+ document.head.appendChild(script);+ if (error)+ throw error;+ return script;+ }+ }++ async addStyleTag(options: { url?: string; path?: string; content?: string; }): Promise<ElementHandle> {+ const {+ url = null,+ path = null,+ content = null+ } = options;+ if (url !== null) {+ try {+ const context = await this.executionContext();+ return (await context.evaluateHandle(addStyleUrl, url)).asElement();+ } catch (error) {+ throw new Error(`Loading style from ${url} failed`);+ }+ }++ if (path !== null) {+ let contents = await readFileAsync(path, 'utf8');+ contents += '/*# sourceURL=' + path.replace(/\n/g, '') + '*/';+ const context = await this.executionContext();+ return (await context.evaluateHandle(addStyleContent, contents)).asElement();+ }++ if (content !== null) {+ const context = await this.executionContext();+ return (await context.evaluateHandle(addStyleContent, content)).asElement();+ }++ throw new Error('Provide an object with a `url`, `path` or `content` property');++ /**+ */+ async function addStyleUrl(url: string): Promise<HTMLElement> {+ const link = document.createElement('link');+ link.rel = 'stylesheet';+ link.href = url;+ const promise = new Promise((res, rej) => {+ link.onload = res;+ link.onerror = rej;+ });+ document.head.appendChild(link);+ await promise;+ return link;+ }++ /**+ */+ async function addStyleContent(content: string): Promise<HTMLElement> {+ const style = document.createElement('style');+ style.type = 'text/css';+ style.appendChild(document.createTextNode(content));+ const promise = new Promise((res, rej) => {+ style.onload = res;+ style.onerror = rej;+ });+ document.head.appendChild(style);+ await promise;+ return style;+ }+ }++ name(): string {+ return this._name || '';+ }++ url(): string {+ return this._url;+ }++ parentFrame(): Frame | null {+ return this._parentFrame;+ }++ childFrames(): Array<Frame> {+ return Array.from(this._childFrames);+ }++ isDetached(): boolean {+ return this._detached;+ }++ async click(selector: string, options: { delay?: number; button?: 'left' | 'right' | 'middle'; clickCount?: number; } | undefined) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.click(options);+ await handle.dispose();+ }++ async focus(selector: string) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.focus();+ await handle.dispose();+ }++ async hover(selector: string) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.hover();+ await handle.dispose();+ }++ /**+ */+ select(selector: string, ...values: Array<string>): Promise<Array<string>>{+ for (const value of values)+ assert(helper.isString(value), 'Values must be strings. Found value "' + value + '" of type "' + (typeof value) + '"');+ return this.$eval(selector, (element : HTMLSelectElement, values) => {+ if (element.nodeName.toLowerCase() !== 'select')+ throw new Error('Element is not a <select> element.');++ const options = Array.from(element.options);+ element.value = undefined;+ for (const option of options) {+ option.selected = values.includes(option.value);+ if (option.selected && !element.multiple)+ break;+ }+ element.dispatchEvent(new Event('input', { 'bubbles': true }));+ element.dispatchEvent(new Event('change', { 'bubbles': true }));+ return options.filter(option => option.selected).map(option => option.value);+ }, values);+ }++ async type(selector: string, text: string, options: { delay: (number | undefined); } | undefined) {+ const handle = await this.$(selector);+ assert(handle, 'No node found for selector: ' + selector);+ await handle.type(text, options);+ await handle.dispose();+ }++ waitFor(selectorOrFunctionOrTimeout: (string | number | Function), options: object | undefined = {}, ...args: Array<any>): Promise<JSHandle | null> {+ const xPathPattern = '//';++ if (helper.isString(selectorOrFunctionOrTimeout)) {+ const string: string = /** @type {string} */ (selectorOrFunctionOrTimeout);+ if (string.startsWith(xPathPattern))+ return this.waitForXPath(string, options);+ return this.waitForSelector(string, options);+ }+ if (helper.isNumber(selectorOrFunctionOrTimeout))+ return new Promise(fulfill => setTimeout(fulfill, /** @type {number} */ (selectorOrFunctionOrTimeout)));+ if (typeof selectorOrFunctionOrTimeout === 'function')+ return this.waitForFunction(selectorOrFunctionOrTimeout, options, ...args);+ return Promise.reject(new Error('Unsupported target type: ' + (typeof selectorOrFunctionOrTimeout)));+ }++ async title(): Promise<string> {+ return this.evaluate(() => document.title);+ }++ async _waitForSelectorOrXPath(selectorOrXPath: string, isXPath: boolean, options: { visible?: boolean; hidden?: boolean; timeout?: number; } | undefined = {}): Promise<ElementHandle | null> {+ const {+ visible: waitForVisible = false,+ hidden: waitForHidden = false,+ timeout = this._frameManager._timeoutSettings.timeout(),+ } = options;+ const polling = waitForVisible || waitForHidden ? 'raf' : 'mutation';+ const title = `${isXPath ? 'XPath' : 'selector'} "${selectorOrXPath}"${waitForHidden ? ' to be hidden' : ''}`;+ const waitTask = new WaitTask(this, predicate, title, polling, timeout, selectorOrXPath, isXPath, waitForVisible, waitForHidden);+ const handle = await waitTask.promise;+ if (!handle.asElement()) {+ await handle.dispose();+ return null;+ }+ return handle.asElement();++ /**+ */+ function predicate(selectorOrXPath: string, isXPath: boolean, waitForVisible: boolean, waitForHidden: boolean): (Node | boolean) | null {+ const node = isXPath+ ? document.evaluate(selectorOrXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue+ : document.querySelector(selectorOrXPath);+ if (!node)+ return waitForHidden;+ if (!waitForVisible && !waitForHidden)+ return node;+ const element: Element = (node.nodeType === Node.TEXT_NODE ? node.parentElement : node) as Element;++ const style = window.getComputedStyle(element);+ const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox();+ const success = (waitForVisible === isVisible || waitForHidden === !isVisible);+ return success ? node : null;++ /**+ */+ function hasVisibleBoundingBox(): boolean {+ const rect = element.getBoundingClientRect();+ return !!(rect.top || rect.bottom || rect.width || rect.height);+ }+ }+ }++ _navigated(framePayload: Protocol.Page.Frame) {+ this._name = framePayload.name;+ // TODO(lushnikov): remove this once requestInterception has loaderId exposed.+ this._navigationURL = framePayload.url;+ this._url = framePayload.url;+ // It may have been disposed by targetDestroyed.+ if (this._executionContext)+ this._setContext(null);+ }++ _navigatedWithinDocument(url: string) {+ this._url = url;+ }++ _onLoadingStopped() {+ this._lifecycleEvents.add('DOMContentLoaded');+ this._lifecycleEvents.add('load');+ }++ _detach() {+ this._detached = true;+ for (const waitTask of this._waitTasks)+ waitTask.terminate(new Error('waitForFunction failed: frame got detached.'));+ if (this._parentFrame)+ this._parentFrame._childFrames.delete(this);+ this._parentFrame = null;+ }++ _setContext(context: ExecutionContext | null) {+ if (this._executionContext)+ this._executionContext._dispose();+ this._executionContext = context;+ if (context) {+ this._contextResolveCallback.call(null, context);+ this._contextResolveCallback = null;+ for (const waitTask of this._waitTasks)+ waitTask.rerun();+ } else {+ this._documentPromise = null;+ this._contextPromise = new Promise(fulfill => {+ this._contextResolveCallback = fulfill;+ });+ }+ }+}++/**+ * @internal+ */+class NextNavigationWatchdog {+ _frame: any;+ _newDocumentNavigationPromise: Promise<unknown>;+ _newDocumentNavigationCallback: (value?: unknown) => void;+ _sameDocumentNavigationPromise: Promise<unknown>;+ _sameDocumentNavigationCallback: (value?: unknown) => void;+ _navigationRequest: any;+ _eventListeners: RegisteredListener[];+ _timeoutPromise: Promise<unknown>;+ _timeoutId: NodeJS.Timer;++ constructor(frame, timeout) {+ this._frame = frame;+ this._newDocumentNavigationPromise = new Promise(fulfill => {+ this._newDocumentNavigationCallback = fulfill;+ });+ this._sameDocumentNavigationPromise = new Promise(fulfill => {+ this._sameDocumentNavigationCallback = fulfill;+ });+ /** @type {?Request} */+ this._navigationRequest = null;+ this._eventListeners = [+ helper.addEventListener(frame._frameManager._page, Events.Page.Load, event => this._newDocumentNavigationCallback()),+ helper.addEventListener(frame._frameManager, FrameManagerEvents.FrameNavigatedWithinDocument, frame => this._onSameDocumentNavigation(frame)),+ helper.addEventListener(frame._frameManager, FrameManagerEvents.TargetSwappedOnNavigation, event => this._onTargetReconnected()),+ helper.addEventListener(frame._frameManager.networkManager(), NetworkManagerEvents.Request, this._onRequest.bind(this)),+ ];+ const timeoutError = new TimeoutError('Navigation Timeout Exceeded: ' + timeout + 'ms');+ let timeoutCallback;+ this._timeoutPromise = new Promise(resolve => timeoutCallback = resolve.bind(null, timeoutError));+ this._timeoutId = timeout ? setTimeout(timeoutCallback, timeout) : null;+ }++ async waitForNavigation() {+ const error = await Promise.race([+ this._timeoutPromise,+ this._newDocumentNavigationPromise,+ this._sameDocumentNavigationPromise+ ]);+ // TODO: handle exceptions+ this.dispose();+ if (error)+ throw error;+ return this.navigationResponse();+ }++ async _onTargetReconnected() {+ // In case web process change we migh have missed load event. Check current ready+ // state to mitigate that.+ try {+ const context = await this._frame.executionContext();+ const readyState = await context.evaluate(() => document.readyState);+ switch (readyState) {+ case 'loaded':+ case 'interactive':+ case 'complete':+ this._newDocumentNavigationCallback();+ break;+ }+ } catch (e) {+ debugError('_onTargetReconnected ' + e);+ }+ }++ _onSameDocumentNavigation(frame) {+ if (this._frame === frame)+ this._sameDocumentNavigationCallback();+ }++ _onRequest(request: Request) {+ if (request.frame() !== this._frame || !request.isNavigationRequest())+ return;+ this._navigationRequest = request;+ }++ navigationResponse(): Response | null {+ return this._navigationRequest ? this._navigationRequest.response() : null;+ }++ dispose() {+ helper.removeEventListeners(this._eventListeners);+ clearTimeout(this._timeoutId);+ }+}++class WaitTask {+ promise: Promise<any>;+ _domWorld: any;+ _polling: string | number;+ _timeout: number;+ _predicateBody: string;+ _args: any[];+ _runCount: number;+ _resolve: (value?: unknown) => void;+ _reject: (reason?: any) => void;+ _timeoutTimer: NodeJS.Timer;+ _terminated: boolean;+ _runningTask: any;+ constructor(domWorld: Frame, predicateBody: Function | string, title, polling: string | number, timeout: number, ...args: Array<any>) {+ if (helper.isString(polling))+ assert(polling === 'raf' || polling === 'mutation', 'Unknown polling option: ' + polling);+ else if (helper.isNumber(polling))+ assert(polling > 0, 'Cannot poll with non-positive interval: ' + polling);+ else+ throw new Error('Unknown polling options: ' + polling);++ this._domWorld = domWorld;+ this._polling = polling;+ this._timeout = timeout;+ this._predicateBody = helper.isString(predicateBody) ? 'return (' + predicateBody + ')' : 'return (' + predicateBody + ')(...args)';+ this._args = args;+ this._runCount = 0;+ domWorld._waitTasks.add(this);+ this.promise = new Promise((resolve, reject) => {+ this._resolve = resolve;+ this._reject = reject;+ });+ // Since page navigation requires us to re-install the pageScript, we should track+ // timeout on our end.+ if (timeout) {+ const timeoutError = new TimeoutError(`waiting for ${title} failed: timeout ${timeout}ms exceeded`);+ this._timeoutTimer = setTimeout(() => this.terminate(timeoutError), timeout);+ }+ this.rerun();+ }++ terminate(error: Error) {+ this._terminated = true;+ this._reject(error);+ this._cleanup();+ }++ async rerun() {+ const runCount = ++this._runCount;+ /** @type {?JSHandle} */+ let success: JSHandle | null = null;+ let error = null;+ try {+ success = await (await this._domWorld.executionContext()).evaluateHandle(waitForPredicatePageFunction, this._predicateBody, this._polling, this._timeout, ...this._args);+ } catch (e) {+ error = e;+ }++ if (this._terminated || runCount !== this._runCount) {+ if (success)+ await success.dispose();+ return;+ }++ // Ignore timeouts in pageScript - we track timeouts ourselves.+ // If the frame's execution context has already changed, `frame.evaluate` will+ // throw an error - ignore this predicate run altogether.+ if (!error && await this._domWorld.evaluate(s => !s, success).catch(e => true)) {+ await success.dispose();+ return;+ }++ // When the page is navigated, the promise is rejected.+ // We will try again in the new execution context.+ if (error && error.message.includes('Execution context was destroyed'))+ return;+ // In WebKit cross-process navigation leads to targetDestroyed (followed+ // by targetCreated).+ if (error && error.message.includes('Target closed'))+ return;++ // We could have tried to evaluate in a context which was already+ // destroyed.+ if (error && error.message.includes('Cannot find context with specified id'))+ return;++ if (error)+ this._reject(error);+ else+ this._resolve(success);++ this._cleanup();+ }++ _cleanup() {+ clearTimeout(this._timeoutTimer);+ this._domWorld._waitTasks.delete(this);+ this._runningTask = null;+ }+}++async function waitForPredicatePageFunction(predicateBody: string, polling: string, timeout: number, ...args): Promise<any> {+ const predicate = new Function('...args', predicateBody);+ let timedOut = false;+ if (timeout)+ setTimeout(() => timedOut = true, timeout);+ if (polling === 'raf')+ return await pollRaf();+ if (polling === 'mutation')+ return await pollMutation();+ if (typeof polling === 'number')+ return await pollInterval(polling);++ function pollMutation(): Promise<any> {+ const success = predicate.apply(null, args);+ if (success)+ return Promise.resolve(success);++ let fulfill;+ const result = new Promise(x => fulfill = x);+ const observer = new MutationObserver(mutations => {+ if (timedOut) {+ observer.disconnect();+ fulfill();+ }+ const success = predicate.apply(null, args);+ if (success) {+ observer.disconnect();+ fulfill(success);+ }+ });+ observer.observe(document, {+ childList: true,+ subtree: true,+ attributes: true+ });+ return result;+ }++ function pollRaf(): Promise<any> {+ let fulfill;+ const result = new Promise(x => fulfill = x);+ onRaf();+ return result;++ function onRaf() {+ if (timedOut) {+ fulfill();+ return;+ }+ const success = predicate.apply(null, args);+ if (success)+ fulfill(success);+ else+ requestAnimationFrame(onRaf);+ }+ }++ function pollInterval(pollInterval: number): Promise<any> {+ let fulfill;+ const result = new Promise(x => fulfill = x);+ onTimeout();+ return result;++ function onTimeout() {+ if (timedOut) {+ fulfill();+ return;+ }+ const success = predicate.apply(null, args);+ if (success)+ fulfill(success);+ else+ setTimeout(onTimeout, pollInterval);+ }+ }+}diff --git a/src/webkit/Input.ts b/src/webkit/Input.tsnew file mode 100644index 0000000000..19535bd8a9--- /dev/null+++ b/src/webkit/Input.ts@@ -0,0 +1,305 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the 'License');+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an 'AS IS' BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { TargetSession } from './Connection';+import { assert } from '../helper';+import { keyDefinitions } from '../USKeyboardLayout';++type KeyDescription = {+ keyCode: number,+ key: string,+ text: string,+ code: string,+ location: number,+};++export type Modifier = 'Alt' | 'Control' | 'Meta' | 'Shift';+const kModifiers: Modifier[] = ['Alt', 'Control', 'Meta', 'Shift'];++export type Button = 'left' | 'right' | 'middle';++export class Keyboard {+ private _session: TargetSession;+ _modifiers = 0;+ private _pressedKeys = new Set<unknown>();++ constructor(session: TargetSession) {+ this._session = session;+ }++ async down(key: string, options: { text?: string; } = { text: undefined }) {+ const description = this._keyDescriptionForString(key);++ const autoRepeat = this._pressedKeys.has(description.code);+ this._pressedKeys.add(description.code);+ this._modifiers |= this._modifierBit(description.key);++ const text = options.text === undefined ? description.text : options.text;+ await this._session.send('Input.dispatchKeyEvent', {+ type: 'keyDown',+ modifiers: this._modifiers,+ windowsVirtualKeyCode: description.keyCode,+ code: description.code,+ key: description.key,+ text: text,+ unmodifiedText: text,+ autoRepeat,+ isKeypad: description.location === 3,+ });+ }++ _modifierBit(key: string): number {+ // From Source/WebKit/Shared/WebEvent.h+ const ShiftKey = 1 << 0;+ const ControlKey = 1 << 1;+ const AltKey = 1 << 2;+ const MetaKey = 1 << 3;+ if (key === 'Alt')+ return AltKey;+ if (key === 'Control')+ return ControlKey;+ if (key === 'Meta')+ return MetaKey;+ if (key === 'Shift')+ return ShiftKey;+ return 0;+ }++ _keyDescriptionForString(keyString: string): KeyDescription {+ const shift = this._modifiers & 8;+ const description = {+ key: '',+ keyCode: 0,+ code: '',+ text: '',+ location: 0+ };++ const definition = keyDefinitions[keyString];+ assert(definition, `Unknown key: "${keyString}"`);++ if (definition.key)+ description.key = definition.key;+ if (shift && definition.shiftKey)+ description.key = definition.shiftKey;++ if (definition.keyCode)+ description.keyCode = definition.keyCode;+ if (shift && definition.shiftKeyCode)+ description.keyCode = definition.shiftKeyCode;++ if (definition.code)+ description.code = definition.code;++ if (definition.location)+ description.location = definition.location;++ if (description.key.length === 1)+ description.text = description.key;++ if (definition.text)+ description.text = definition.text;+ if (shift && definition.shiftText)+ description.text = definition.shiftText;++ // if any modifiers besides shift are pressed, no text should be sent+ if (this._modifiers & ~8)+ description.text = '';++ return description;+ }++ async up(key: string) {+ const description = this._keyDescriptionForString(key);++ this._modifiers &= ~this._modifierBit(description.key);+ this._pressedKeys.delete(description.code);+ await this._session.send('Input.dispatchKeyEvent', {+ type: 'keyUp',+ modifiers: this._modifiers,+ key: description.key,+ windowsVirtualKeyCode: description.keyCode,+ code: description.code,+ isKeypad: description.location === 3+ });+ }++ async type(text: string, options: { delay: (number | undefined); } | undefined) {+ const delay = (options && options.delay) || null;+ for (const char of text) {+ if (keyDefinitions[char]) {+ await this.press(char, {delay});+ } else {+ if (delay)+ await new Promise(f => setTimeout(f, delay));+ // unsupported character+ }+ }+ }++ async press(key: string, options: { delay?: number; text?: string; } = {}) {+ const {delay = null} = options;+ await this.down(key, options);+ if (delay)+ await new Promise(f => setTimeout(f, options.delay));+ await this.up(key);+ }++ async _ensureModifiers(modifiers: Modifier[]): Promise<Modifier[]> {+ for (const modifier of modifiers) {+ if (!kModifiers.includes(modifier))+ throw new Error('Uknown modifier ' + modifier);+ }+ const restore: Modifier[] = [];+ const promises: Promise<void>[] = [];+ for (const key of kModifiers) {+ const needDown = modifiers.includes(key);+ const isDown = (this._modifiers & this._modifierBit(key)) !== 0;+ if (isDown)+ restore.push(key);+ if (needDown && !isDown)+ promises.push(this.down(key));+ else if (!needDown && isDown)+ promises.push(this.up(key));+ }+ await Promise.all(promises);+ return restore;+ }+}++export class Mouse {+ private _client: TargetSession;+ private _keyboard: Keyboard;+ private _x = 0;+ private _y = 0;+ private _button: 'none' | Button = 'none';++ constructor(client: TargetSession, keyboard: Keyboard) {+ this._client = client;+ this._keyboard = keyboard;+ }++ async move(x: number, y: number, options: { steps?: number; } = {}) {+ const {steps = 1} = options;+ const fromX = this._x, fromY = this._y;+ this._x = x;+ this._y = y;+ for (let i = 1; i <= steps; i++) {+ await this._client.send('Input.dispatchMouseEvent', {+ type: 'move',+ button: this._button,+ x: fromX + (this._x - fromX) * (i / steps),+ y: fromY + (this._y - fromY) * (i / steps),+ modifiers: this._keyboard._modifiers+ });+ }+ }++ async click(x: number, y: number, options: { delay?: number; button?: Button; clickCount?: number; } = {}) {+ const {delay = null} = options;+ if (delay !== null) {+ await Promise.all([+ this.move(x, y),+ this.down(options),+ ]);+ await new Promise(f => setTimeout(f, delay));+ await this.up(options);+ } else {+ await Promise.all([+ this.move(x, y),+ this.down(options),+ this.up(options),+ ]);+ }+ }++ async dblclick(x: number, y: number, options: { delay?: number; button?: Button; } = {}) {+ const { delay = null } = options;+ if (delay !== null) {+ await this.move(x, y);+ await this.down({ ...options, clickCount: 1 });+ await new Promise(f => setTimeout(f, delay));+ await this.up({ ...options, clickCount: 1 });+ await new Promise(f => setTimeout(f, delay));+ await this.down({ ...options, clickCount: 2 });+ await new Promise(f => setTimeout(f, delay));+ await this.up({ ...options, clickCount: 2 });+ } else {+ await Promise.all([+ this.move(x, y),+ this.down({ ...options, clickCount: 1 }),+ this.up({ ...options, clickCount: 1 }),+ this.down({ ...options, clickCount: 2 }),+ this.up({ ...options, clickCount: 2 }),+ ]);+ }+ }++ async tripleclick(x: number, y: number, options: { delay?: number; button?: Button; } = {}) {+ const { delay = null } = options;+ if (delay !== null) {+ await this.move(x, y);+ await this.down({ ...options, clickCount: 1 });+ await new Promise(f => setTimeout(f, delay));+ await this.up({ ...options, clickCount: 1 });+ await new Promise(f => setTimeout(f, delay));+ await this.down({ ...options, clickCount: 2 });+ await new Promise(f => setTimeout(f, delay));+ await this.up({ ...options, clickCount: 2 });+ await new Promise(f => setTimeout(f, delay));+ await this.down({ ...options, clickCount: 3 });+ await new Promise(f => setTimeout(f, delay));+ await this.up({ ...options, clickCount: 3 });+ } else {+ await Promise.all([+ this.move(x, y),+ this.down({ ...options, clickCount: 1 }),+ this.up({ ...options, clickCount: 1 }),+ this.down({ ...options, clickCount: 2 }),+ this.up({ ...options, clickCount: 2 }),+ this.down({ ...options, clickCount: 3 }),+ this.up({ ...options, clickCount: 3 }),+ ]);+ }+ }++ async down(options: { button?: Button; clickCount?: number; } = {}) {+ const {button = 'left', clickCount = 1} = options;+ this._button = button;+ await this._client.send('Input.dispatchMouseEvent', {+ type: 'down',+ button,+ x: this._x,+ y: this._y,+ modifiers: this._keyboard._modifiers,+ clickCount+ });+ }++ async up(options: { button?: Button; clickCount?: number; } = {}) {+ const {button = 'left', clickCount = 1} = options;+ this._button = 'none';+ await this._client.send('Input.dispatchMouseEvent', {+ type: 'up',+ button,+ x: this._x,+ y: this._y,+ modifiers: this._keyboard._modifiers,+ clickCount+ });+ }+}diff --git a/src/webkit/JSHandle.ts b/src/webkit/JSHandle.tsnew file mode 100644index 0000000000..0caf02a86a--- /dev/null+++ b/src/webkit/JSHandle.ts@@ -0,0 +1,377 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import * as fs from 'fs';+import { assert, debugError, helper } from '../helper';+import { TargetSession } from './Connection';+import { ExecutionContext } from './ExecutionContext';+import { FrameManager } from './FrameManager';+import { Button } from './Input';+import { Page } from './Page';+import { Protocol } from './protocol';+import { releaseObject, valueFromRemoteObject } from './protocolHelper';+const writeFileAsync = helper.promisify(fs.writeFile);++export type ClickOptions = {+ delay?: number;+ button?: Button;+ clickCount?: number;+};++export function createJSHandle(context: ExecutionContext, remoteObject: Protocol.Runtime.RemoteObject) {+ const frame = context.frame();+ if (remoteObject.subtype === 'node' && frame) {+ const frameManager = frame._frameManager;+ return new ElementHandle(context, context._session, remoteObject, frameManager.page(), frameManager);+ }+ return new JSHandle(context, context._session, remoteObject);+}++export class JSHandle {+ _context: ExecutionContext;+ protected _client: TargetSession;+ _remoteObject: Protocol.Runtime.RemoteObject;+ _disposed = false;++ constructor(context: ExecutionContext, client: TargetSession, remoteObject: Protocol.Runtime.RemoteObject) {+ this._context = context;+ this._client = client;+ this._remoteObject = remoteObject;+ }++ executionContext(): ExecutionContext {+ return this._context;+ }++ async evaluate(pageFunction: Function | string, ...args: any[]): Promise<(any)> {+ return await this.executionContext().evaluate(pageFunction, this, ...args);+ }++ async evaluateHandle(pageFunction: Function | string, ...args: any[]): Promise<JSHandle> {+ return await this.executionContext().evaluateHandle(pageFunction, this, ...args);+ }++ async getProperty(propertyName: string): Promise<JSHandle | null> {+ const objectHandle = await this.evaluateHandle((object, propertyName) => {+ const result = {__proto__: null};+ result[propertyName] = object[propertyName];+ return result;+ }, propertyName);+ const properties = await objectHandle.getProperties();+ const result = properties.get(propertyName) || null;+ await objectHandle.dispose();+ return result;+ }++ async getProperties(): Promise<Map<string, JSHandle>> {+ const response = await this._client.send('Runtime.getProperties', {+ objectId: this._remoteObject.objectId,+ ownProperties: true+ });+ const result = new Map();+ for (const property of response.properties) {+ if (!property.enumerable)+ continue;+ result.set(property.name, createJSHandle(this._context, property.value));+ }+ return result;+ }++ async jsonValue(): Promise<object | null> {+ if (this._remoteObject.objectId) {+ const response = await this._client.send('Runtime.callFunctionOn', {+ functionDeclaration: 'function() { return this; }',+ objectId: this._remoteObject.objectId,+ returnByValue: true+ });+ return valueFromRemoteObject(response.result);+ }+ return valueFromRemoteObject(this._remoteObject);+ }++ asElement(): ElementHandle | null {+ return null;+ }++ async dispose() {+ if (this._disposed)+ return;+ this._disposed = true;+ await releaseObject(this._client, this._remoteObject);+ }++ toString(): string {+ if (this._remoteObject.objectId) {+ let type: string = this._remoteObject.subtype || this._remoteObject.type;+ // FIXME: promise doesn't have special subtype in WebKit.+ if (this._remoteObject.className === 'Promise')+ type = 'promise';+ return 'JSHandle@' + type;+ }+ return 'JSHandle:' + valueFromRemoteObject(this._remoteObject);+ }+}++export class ElementHandle extends JSHandle {+ private _page: Page;+ private _frameManager: FrameManager;++ constructor(context: ExecutionContext, client: TargetSession, remoteObject: Protocol.Runtime.RemoteObject, page: Page, frameManager: FrameManager) {+ super(context, client, remoteObject);+ this._client = client;+ this._remoteObject = remoteObject;+ this._page = page;+ this._frameManager = frameManager;+ }++ asElement(): ElementHandle | null {+ return this;+ }++ async _scrollIntoViewIfNeeded() {+ const error = await this.evaluate(async(element, pageJavascriptEnabled) => {+ if (!element.isConnected)+ return 'Node is detached from document';+ if (element.nodeType !== Node.ELEMENT_NODE)+ return 'Node is not of type HTMLElement';+ // force-scroll if page's javascript is disabled.+ if (!pageJavascriptEnabled) {+ element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});+ return false;+ }+ const visibleRatio = await new Promise(resolve => {+ const observer = new IntersectionObserver(entries => {+ resolve(entries[0].intersectionRatio);+ observer.disconnect();+ });+ observer.observe(element);+ });+ if (visibleRatio !== 1.0)+ element.scrollIntoView({block: 'center', inline: 'center', behavior: 'instant'});+ return false;+ }, this._page._javascriptEnabled);+ if (error)+ throw new Error(error);+ }++ async _clickablePoint() {+ const [result, viewport] = await Promise.all([+ this._client.send('DOM.getContentQuads', {+ objectId: this._remoteObject.objectId+ }).catch(debugError),+ this._page.evaluate(() => ({ clientWidth: innerWidth, clientHeight: innerHeight })),+ ]);+ if (!result || !result.quads.length)+ throw new Error('Node is either not visible or not an HTMLElement');+ // Filter out quads that have too small area to click into.+ const {clientWidth, clientHeight} = viewport;+ const quads = result.quads.map(quad => this._fromProtocolQuad(quad)).map(quad => this._intersectQuadWithViewport(quad, clientWidth, clientHeight)).filter(quad => computeQuadArea(quad) > 1);+ if (!quads.length)+ throw new Error('Node is either not visible or not an HTMLElement');+ // Return the middle point of the first quad.+ const quad = quads[0];+ let x = 0;+ let y = 0;+ for (const point of quad) {+ x += point.x;+ y += point.y;+ }+ return {+ x: x / 4,+ y: y / 4+ };+ }++ _fromProtocolQuad(quad: number[]): Array<{ x: number; y: number; }> {+ return [+ {x: quad[0], y: quad[1]},+ {x: quad[2], y: quad[3]},+ {x: quad[4], y: quad[5]},+ {x: quad[6], y: quad[7]}+ ];+ }++ _intersectQuadWithViewport(quad: Array<{ x: number; y: number; }>, width: number, height: number): Array<{ x: number; y: number; }> {+ return quad.map(point => ({+ x: Math.min(Math.max(point.x, 0), width),+ y: Math.min(Math.max(point.y, 0), height),+ }));+ }++ async hover(): Promise<void> {+ await this._scrollIntoViewIfNeeded();+ const {x, y} = await this._clickablePoint();+ await this._page.mouse.move(x, y);+ }++ async click(options?: ClickOptions): Promise<void> {+ await this._scrollIntoViewIfNeeded();+ const {x, y} = await this._clickablePoint();+ await this._page.mouse.click(x, y, options);+ }++ async select(...values: string[]): Promise<string[]> {+ for (const value of values)+ assert(helper.isString(value), 'Values must be strings. Found value "' + value + '" of type "' + (typeof value) + '"');+ return this.evaluate((element: HTMLSelectElement, values: string[]) => {+ if (element.nodeName.toLowerCase() !== 'select')+ throw new Error('Element is not a <select> element.');++ const options = Array.from(element.options);+ element.value = undefined;+ for (const option of options) {+ option.selected = values.includes(option.value);+ if (option.selected && !element.multiple)+ break;+ }+ element.dispatchEvent(new Event('input', { 'bubbles': true }));+ element.dispatchEvent(new Event('change', { 'bubbles': true }));+ return options.filter(option => option.selected).map(option => option.value);+ }, values);+ }++ async focus() {+ await this.evaluate(element => element.focus());+ }++ async type(text: string, options: { delay: (number | undefined); } | undefined) {+ await this.focus();+ await this._page.keyboard.type(text, options);+ }++ async press(key: string, options: { delay?: number; text?: string; } | undefined) {+ await this.focus();+ await this._page.keyboard.press(key, options);+ }++ async screenshot(options: {path?: string} = {}): Promise<string | Buffer> {+ const objectId = this._remoteObject.objectId;+ this._client.send('DOM.getDocument');+ const {nodeId} = await this._client.send('DOM.requestNode', {objectId});+ const result = await this._client.send('Page.snapshotNode', {nodeId});+ const prefix = 'data:image/png;base64,';+ const buffer = Buffer.from(result.dataURL.substr(prefix.length), 'base64');+ if (options.path)+ await writeFileAsync(options.path, buffer);+ return buffer;+ }++ async $(selector: string): Promise<ElementHandle | null> {+ const handle = await this.evaluateHandle(+ (element, selector) => element.querySelector(selector),+ selector+ );+ const element = handle.asElement();+ if (element)+ return element;+ await handle.dispose();+ return null;+ }++ async $$(selector: string): Promise<ElementHandle[]> {+ const arrayHandle = await this.evaluateHandle(+ (element, selector) => element.querySelectorAll(selector),+ selector+ );+ const properties = await arrayHandle.getProperties();+ await arrayHandle.dispose();+ const result = [];+ for (const property of properties.values()) {+ const elementHandle = property.asElement();+ if (elementHandle)+ result.push(elementHandle);+ }+ return result;+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<(object | undefined)> {+ const elementHandle = await this.$(selector);+ if (!elementHandle)+ throw new Error(`Error: failed to find element matching selector "${selector}"`);+ const result = await elementHandle.evaluate(pageFunction, ...args);+ await elementHandle.dispose();+ return result;+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<(object | undefined)> {+ const arrayHandle = await this.evaluateHandle(+ (element, selector) => Array.from(element.querySelectorAll(selector)),+ selector+ );++ const result = await arrayHandle.evaluate(pageFunction, ...args);+ await arrayHandle.dispose();+ return result;+ }++ async $x(expression: string): Promise<ElementHandle[]> {+ const arrayHandle = await this.evaluateHandle(+ (element, expression) => {+ const document = element.ownerDocument || element;+ const iterator = document.evaluate(expression, element, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE);+ const array = [];+ let item;+ while ((item = iterator.iterateNext()))+ array.push(item);+ return array;+ },+ expression+ );+ const properties = await arrayHandle.getProperties();+ await arrayHandle.dispose();+ const result = [];+ for (const property of properties.values()) {+ const elementHandle = property.asElement();+ if (elementHandle)+ result.push(elementHandle);+ }+ return result;+ }++ isIntersectingViewport(): Promise<boolean> {+ return this.evaluate(async element => {+ const visibleRatio = await new Promise(resolve => {+ const observer = new IntersectionObserver(entries => {+ resolve(entries[0].intersectionRatio);+ observer.disconnect();+ });+ observer.observe(element);+ });+ return visibleRatio > 0;+ });+ }+}++function computeQuadArea(quad) {+ // Compute sum of all directed areas of adjacent triangles+ // https://en.wikipedia.org/wiki/Polygon#Simple_polygons+ let area = 0;+ for (let i = 0; i < quad.length; ++i) {+ const p1 = quad[i];+ const p2 = quad[(i + 1) % quad.length];+ area += (p1.x * p2.y - p2.x * p1.y) / 2;+ }+ return Math.abs(area);+}++type BoxModel = {+ content: {x: number, y: number}[],+ padding: {x: number, y: number}[],+ border: {x: number, y: number}[],+ margin: {x: number, y: number}[],+ width: number,+ height : number+};diff --git a/src/webkit/Launcher.ts b/src/webkit/Launcher.tsnew file mode 100644index 0000000000..20ff9b5cfd--- /dev/null+++ b/src/webkit/Launcher.ts@@ -0,0 +1,166 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import * as childProcess from 'child_process';+import { debugError, helper } from '../helper';+import { Browser } from './Browser';+import { BrowserFetcher } from './BrowserFetcher';+import { Connection } from './Connection';+import { Viewport } from './Page';+import { PipeTransport } from './PipeTransport';+++export class Launcher {+ private _projectRoot: string;+ private _preferredRevision: string;++ constructor(projectRoot: string, preferredRevision: string) {+ this._projectRoot = projectRoot;+ this._preferredRevision = preferredRevision;+ }++ async launch(options: LauncherLaunchOptions = {}): Promise<Browser> {+ const {+ args = [],+ dumpio = false,+ executablePath = null,+ env = process.env,+ handleSIGINT = true,+ handleSIGTERM = true,+ handleSIGHUP = true,+ defaultViewport = {width: 800, height: 600},+ slowMo = 0+ } = options;++ const webkitArguments = args.slice();+ let webkitExecutable = executablePath;+ if (!executablePath) {+ const {missingText, executablePath} = this._resolveExecutablePath();+ if (missingText)+ throw new Error(missingText);+ webkitExecutable = executablePath;+ }++ let stdio: ('ignore' | 'pipe')[] = ['pipe', 'pipe', 'pipe'];+ if (dumpio)+ stdio = ['ignore', 'pipe', 'pipe', 'pipe', 'pipe'];+ else+ stdio = ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'];+ webkitArguments.push('--inspector-pipe');+ const webkitProcess = childProcess.spawn(+ webkitExecutable,+ webkitArguments,+ {+ // On non-windows platforms, `detached: true` makes child process a leader of a new+ // process group, making it possible to kill child process tree with `.kill(-pid)` command.+ // @see https://nodejs.org/api/child_process.html#child_process_options_detached+ detached: process.platform !== 'win32',+ env,+ stdio+ }+ );++ if (dumpio) {+ webkitProcess.stderr.pipe(process.stderr);+ webkitProcess.stdout.pipe(process.stdout);+ }++ let webkitClosed = false;+ const waitForChromeToClose = new Promise((fulfill, reject) => {+ webkitProcess.once('exit', () => {+ webkitClosed = true;+ fulfill();+ });+ });++ const listeners = [ helper.addEventListener(process, 'exit', killWebKit) ];+ if (handleSIGINT)+ listeners.push(helper.addEventListener(process, 'SIGINT', () => { killWebKit(); process.exit(130); }));+ if (handleSIGTERM)+ listeners.push(helper.addEventListener(process, 'SIGTERM', gracefullyCloseWebkit));+ if (handleSIGHUP)+ listeners.push(helper.addEventListener(process, 'SIGHUP', gracefullyCloseWebkit));+ let connection: Connection | null = null;+ try {+ const transport = new PipeTransport(webkitProcess.stdio[3] as NodeJS.WritableStream, webkitProcess.stdio[4] as NodeJS.ReadableStream);+ connection = new Connection('', transport, slowMo);+ const browser = new Browser(connection, defaultViewport, webkitProcess, gracefullyCloseWebkit);+ return browser;+ } catch (e) {+ killWebKit();+ throw e;+ }++ function gracefullyCloseWebkit(): Promise<any> {+ helper.removeEventListeners(listeners);+ if (connection) {+ // Attempt to close chrome gracefully+ connection.send('Browser.close').catch(error => {+ debugError(error);+ killWebKit();+ });+ }+ return waitForChromeToClose;+ }++ // This method has to be sync to be used as 'exit' event handler.+ function killWebKit() {+ helper.removeEventListeners(listeners);+ if (webkitProcess.pid && !webkitProcess.killed && !webkitClosed) {+ // Force kill chrome.+ try {+ if (process.platform === 'win32')+ childProcess.execSync(`taskkill /pid ${webkitProcess.pid} /T /F`);+ else+ process.kill(-webkitProcess.pid, 'SIGKILL');+ } catch (e) {+ // the process might have already stopped+ }+ }+ }+ }++ executablePath(): string {+ return this._resolveExecutablePath().executablePath;+ }++ _resolveExecutablePath(): { executablePath: string; missingText: string | null; } {+ const browserFetcher = new BrowserFetcher(this._projectRoot);+ const revision = process.env['PLAYWRIGHT_WEBKIT_REVISION'];+ if (revision) {+ const revisionInfo = browserFetcher.revisionInfo(revision);+ const missingText = !revisionInfo.local ? 'Tried to use PLAYWRIGHT_WEBKIT_REVISION env variable to launch browser but did not find executable at: ' + revisionInfo.executablePath : null;+ return {executablePath: revisionInfo.executablePath, missingText};+ }+ const revisionInfo = browserFetcher.revisionInfo(this._preferredRevision);+ const missingText = !revisionInfo.local ? `WebKit revision is not downloaded. Run "npm install" or "yarn install"` : null;+ return {executablePath: revisionInfo.executablePath, missingText};+ }++}++export type LauncherLaunchOptions = {+ args?: string[],+ executablePath?: string,+ handleSIGINT?: boolean,+ handleSIGTERM?: boolean,+ handleSIGHUP?: boolean,+ headless?: boolean,+ dumpio?: boolean,+ env?: {[key: string]: string} | undefined,+ defaultViewport?: Viewport | null,+ slowMo?: number,+};diff --git a/src/webkit/Multimap.ts b/src/webkit/Multimap.tsnew file mode 100644index 0000000000..835a28e592--- /dev/null+++ b/src/webkit/Multimap.ts@@ -0,0 +1,93 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export class Multimap<T, V> {+ private _map: Map<T, Set<V>>;++ constructor() {+ this._map = new Map();+ }++ set(key: T, value: V) {+ let set = this._map.get(key);+ if (!set) {+ set = new Set();+ this._map.set(key, set);+ }+ set.add(value);+ }++ get(key: T): Set<V> {+ let result = this._map.get(key);+ if (!result)+ result = new Set();+ return result;+ }++ has(key: T): boolean {+ return this._map.has(key);+ }++ hasValue(key: T, value: V): boolean {+ const set = this._map.get(key);+ if (!set)+ return false;+ return set.has(value);+ }++ get size(): number {+ return this._map.size;+ }++ delete(key: T, value: V): boolean {+ const values = this.get(key);+ const result = values.delete(value);+ if (!values.size)+ this._map.delete(key);+ return result;+ }++ deleteAll(key: T) {+ this._map.delete(key);+ }++ firstValue(key: T): V {+ const set = this._map.get(key);+ if (!set)+ return null;+ return set.values().next().value;+ }++ firstKey(): T {+ return this._map.keys().next().value;+ }++ valuesArray(): V[] {+ const result = [];+ for (const key of this._map.keys())+ result.push(...Array.from(this._map.get(key).values()));+ return result;+ }++ keysArray(): T[] {+ return Array.from(this._map.keys());+ }++ clear() {+ this._map.clear();+ }+}diff --git a/src/webkit/NetworkManager.ts b/src/webkit/NetworkManager.tsnew file mode 100644index 0000000000..561846e28f--- /dev/null+++ b/src/webkit/NetworkManager.ts@@ -0,0 +1,312 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { EventEmitter } from 'events';+import { TargetSession } from './Connection';+import { Frame, FrameManager } from './FrameManager';+import { assert, helper, RegisteredListener } from '../helper';+import { Protocol } from './protocol';++export const NetworkManagerEvents = {+ Request: Symbol('Events.NetworkManager.Request'),+ Response: Symbol('Events.NetworkManager.Response'),+ RequestFailed: Symbol('Events.NetworkManager.RequestFailed'),+ RequestFinished: Symbol('Events.NetworkManager.RequestFinished'),+};++export class NetworkManager extends EventEmitter {+ private _sesssion: TargetSession;+ private _frameManager: FrameManager;+ private _requestIdToRequest = new Map<string, Request>();+ private _extraHTTPHeaders: {[key: string]: string} = {};+ private _attemptedAuthentications = new Set<string>();+ private _userCacheDisabled = false;+ private _sessionListeners: RegisteredListener[] = [];++ constructor(client: TargetSession, frameManager: FrameManager) {+ super();+ this._sesssion = client;+ this._frameManager = frameManager;++ this._sesssion.on('Network.requestWillBeSent', this._onRequestWillBeSent.bind(this));+ this._sesssion.on('Network.responseReceived', this._onResponseReceived.bind(this));+ this._sesssion.on('Network.loadingFinished', this._onLoadingFinished.bind(this));+ this._sesssion.on('Network.loadingFailed', this._onLoadingFailed.bind(this));+ }++ setSession(newSession: TargetSession) {+ helper.removeEventListeners(this._sessionListeners);+ this._sesssion = newSession;+ this._sessionListeners = [+ helper.addEventListener(this._sesssion, 'Network.requestWillBeSent', this._onRequestWillBeSent.bind(this)),+ helper.addEventListener(this._sesssion, 'Network.responseReceived', this._onResponseReceived.bind(this)),+ helper.addEventListener(this._sesssion, 'Network.loadingFinished', this._onLoadingFinished.bind(this)),+ helper.addEventListener(this._sesssion, 'Network.loadingFailed', this._onLoadingFailed.bind(this)),+ ];+ }++ async initialize() {+ await this._sesssion.send('Network.enable');+ }++ async setExtraHTTPHeaders(extraHTTPHeaders: { [s: string]: string; }) {+ this._extraHTTPHeaders = {};+ for (const key of Object.keys(extraHTTPHeaders)) {+ const value = extraHTTPHeaders[key];+ assert(helper.isString(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);+ this._extraHTTPHeaders[key.toLowerCase()] = value;+ }+ await this._sesssion.send('Network.setExtraHTTPHeaders', { headers: this._extraHTTPHeaders });+ }++ extraHTTPHeaders(): { [s: string]: string; } {+ return Object.assign({}, this._extraHTTPHeaders);+ }++ async setCacheEnabled(enabled: boolean) {+ this._userCacheDisabled = !enabled;+ await this._updateProtocolCacheDisabled();+ }++ async _updateProtocolCacheDisabled() {+ await this._sesssion.send('Network.setResourceCachingDisabled', {+ disabled: this._userCacheDisabled+ });+ }++ _onRequestWillBeSent(event: Protocol.Network.requestWillBeSentPayload, interceptionId: string | null) {+ let redirectChain = [];+ if (event.redirectResponse) {+ const request = this._requestIdToRequest.get(event.requestId);+ // If we connect late to the target, we could have missed the requestWillBeSent event.+ if (request) {+ this._handleRequestRedirect(request, event.redirectResponse);+ redirectChain = request._redirectChain;+ }+ }+ const frame = event.frameId && this._frameManager ? this._frameManager.frame(event.frameId) : null;+ const request = new Request(frame, interceptionId, event, redirectChain);+ this._requestIdToRequest.set(event.requestId, request);+ this.emit(NetworkManagerEvents.Request, request);+ }++ _handleRequestRedirect(request: Request, responsePayload: Protocol.Network.Response) {+ const response = new Response(this._sesssion, request, responsePayload);+ request._response = response;+ request._redirectChain.push(request);+ response._bodyLoadedPromiseFulfill.call(null, new Error('Response body is unavailable for redirect responses'));+ this._requestIdToRequest.delete(request._requestId);+ this._attemptedAuthentications.delete(request._interceptionId);+ this.emit(NetworkManagerEvents.Response, response);+ this.emit(NetworkManagerEvents.RequestFinished, request);+ }++ _onResponseReceived(event: Protocol.Network.responseReceivedPayload) {+ const request = this._requestIdToRequest.get(event.requestId);+ // FileUpload sends a response without a matching request.+ if (!request)+ return;+ const response = new Response(this._sesssion, request, event.response);+ request._response = response;+ this.emit(NetworkManagerEvents.Response, response);+ }++ _onLoadingFinished(event: Protocol.Network.loadingFinishedPayload) {+ const request = this._requestIdToRequest.get(event.requestId);+ // For certain requestIds we never receive requestWillBeSent event.+ // @see https://crbug.com/750469+ if (!request)+ return;++ // Under certain conditions we never get the Network.responseReceived+ // event from protocol. @see https://crbug.com/883475+ if (request.response())+ request.response()._bodyLoadedPromiseFulfill.call(null);+ this._requestIdToRequest.delete(request._requestId);+ this._attemptedAuthentications.delete(request._interceptionId);+ this.emit(NetworkManagerEvents.RequestFinished, request);+ }++ _onLoadingFailed(event: Protocol.Network.loadingFailedPayload) {+ const request = this._requestIdToRequest.get(event.requestId);+ // For certain requestIds we never receive requestWillBeSent event.+ // @see https://crbug.com/750469+ if (!request)+ return;+ request._failureText = event.errorText;+ const response = request.response();+ if (response)+ response._bodyLoadedPromiseFulfill.call(null);+ this._requestIdToRequest.delete(request._requestId);+ this._attemptedAuthentications.delete(request._interceptionId);+ this.emit(NetworkManagerEvents.RequestFailed, request);+ }+}++export class Request {+ _response: Response | null = null;+ _redirectChain: Request[];+ _requestId: string;+ _interceptionId: string;+ private _isNavigationRequest: boolean;+ _failureText: string | null = null;+ private _url: string;+ private _resourceType: string;+ private _method: string;+ private _postData: string;+ private _headers: {[key: string]: string} = {};+ private _frame: Frame;++ constructor(frame: Frame | null, interceptionId: string, event: Protocol.Network.requestWillBeSentPayload, redirectChain: Request[]) {+ this._requestId = event.requestId;+ // TODO(einbinder) this will fail if we are an XHR document request+ this._isNavigationRequest = event.type === 'Document';+ this._interceptionId = interceptionId;++ this._url = event.request.url;+ this._resourceType = event.type ? event.type.toLowerCase() : 'Unknown';+ this._method = event.request.method;+ this._postData = event.request.postData;+ this._frame = frame;+ this._redirectChain = redirectChain;+ for (const key of Object.keys(event.request.headers))+ this._headers[key.toLowerCase()] = event.request.headers[key];+ }++ url(): string {+ return this._url;+ }++ resourceType(): string {+ return this._resourceType;+ }++ method(): string {+ return this._method;+ }++ postData(): string | undefined {+ return this._postData;+ }++ headers(): {[key: string]: string} {+ return this._headers;+ }++ response(): Response | null {+ return this._response;+ }++ frame(): Frame | null {+ return this._frame;+ }++ isNavigationRequest(): boolean {+ return this._isNavigationRequest;+ }++ redirectChain(): Request[] {+ return this._redirectChain.slice();+ }++ failure(): { errorText: string; } | null {+ if (!this._failureText)+ return null;+ return {+ errorText: this._failureText+ };+ }+}++export class Response {+ _bodyLoadedPromiseFulfill: any;+ private _client: TargetSession;+ private _request: Request;+ private _contentPromise: Promise<Buffer> | null = null;+ private _bodyLoadedPromise: Promise<Error | null>;+ private _status: number;+ private _statusText: string;+ private _url: string;+ private _headers: {[key: string]: string} = {};++ constructor(client: TargetSession, request: Request, responsePayload: Protocol.Network.Response) {+ this._client = client;+ this._request = request;++ this._bodyLoadedPromise = new Promise(fulfill => {+ this._bodyLoadedPromiseFulfill = fulfill;+ });++ this._status = responsePayload.status;+ this._statusText = responsePayload.statusText;+ this._url = request.url();+ for (const key of Object.keys(responsePayload.headers))+ this._headers[key.toLowerCase()] = responsePayload.headers[key];+ }++ url(): string {+ return this._url;+ }++ ok(): boolean {+ return this._status === 0 || (this._status >= 200 && this._status <= 299);+ }++ status(): number {+ return this._status;+ }++ statusText(): string {+ return this._statusText;+ }++ headers(): object {+ return this._headers;+ }++ buffer(): Promise<Buffer> {+ if (!this._contentPromise) {+ this._contentPromise = this._bodyLoadedPromise.then(async error => {+ if (error)+ throw error;+ const response = await this._client.send('Network.getResponseBody', {+ requestId: this._request._requestId+ });+ return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');+ });+ }+ return this._contentPromise;+ }++ async text(): Promise<string> {+ const content = await this.buffer();+ return content.toString('utf8');+ }++ async json(): Promise<object> {+ const content = await this.text();+ return JSON.parse(content);+ }++ request(): Request {+ return this._request;+ }++ frame(): Frame | null {+ return this._request.frame();+ }+}diff --git a/src/webkit/Page.ts b/src/webkit/Page.tsnew file mode 100644index 0000000000..002d3c5839--- /dev/null+++ b/src/webkit/Page.ts@@ -0,0 +1,568 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { EventEmitter } from 'events';+import * as fs from 'fs';+import * as mime from 'mime';+import { TargetSession, TargetSessionEvents } from './Connection';+import { Events } from '../Events';+import { Frame, FrameManager, FrameManagerEvents } from './FrameManager';+import { assert, debugError, helper, RegisteredListener } from '../helper';+import { valueFromRemoteObject } from './protocolHelper';+import { Keyboard, Mouse } from './Input';+import { createJSHandle, ElementHandle, JSHandle, ClickOptions } from './JSHandle';+import { Response, NetworkManagerEvents } from './NetworkManager';+import { TaskQueue } from './TaskQueue';+import { TimeoutSettings } from '../TimeoutSettings';+import { Target } from './Target';+import { Browser, BrowserContext } from './Browser';+import { Protocol } from './protocol';++const writeFileAsync = helper.promisify(fs.writeFile);++export type Viewport = {+ width: number;+ height: number;+}++export class Page extends EventEmitter {+ private _closed = false;+ private _session: TargetSession;+ private _target: Target;+ private _keyboard: Keyboard;+ private _mouse: Mouse;+ private _timeoutSettings: TimeoutSettings;+ private _frameManager: FrameManager;+ _javascriptEnabled = true;+ private _viewport: Viewport | null = null;+ private _screenshotTaskQueue: TaskQueue;+ private _workers = new Map<string, Worker>();+ private _disconnectPromise: Promise<Error> | undefined;+ private _sessionListeners: RegisteredListener[] = [];++ static async create(session: TargetSession, target: Target, defaultViewport: Viewport | null, screenshotTaskQueue: TaskQueue): Promise<Page> {+ const page = new Page(session, target, screenshotTaskQueue);+ await page._initialize();+ if (defaultViewport)+ await page.setViewport(defaultViewport);+ return page;+ }++ constructor(session: TargetSession, target: Target, screenshotTaskQueue: TaskQueue) {+ super();+ this._keyboard = new Keyboard(session);+ this._mouse = new Mouse(session, this._keyboard);+ this._timeoutSettings = new TimeoutSettings();+ this._frameManager = new FrameManager(session, this, this._timeoutSettings);++ this._screenshotTaskQueue = screenshotTaskQueue;++ this._setSession(session);+ this._setTarget(target);++ this._frameManager.on(FrameManagerEvents.FrameAttached, event => this.emit(Events.Page.FrameAttached, event));+ this._frameManager.on(FrameManagerEvents.FrameDetached, event => this.emit(Events.Page.FrameDetached, event));+ this._frameManager.on(FrameManagerEvents.FrameNavigated, event => this.emit(Events.Page.FrameNavigated, event));++ const networkManager = this._frameManager.networkManager();+ networkManager.on(NetworkManagerEvents.Request, event => this.emit(Events.Page.Request, event));+ networkManager.on(NetworkManagerEvents.Response, event => this.emit(Events.Page.Response, event));+ networkManager.on(NetworkManagerEvents.RequestFailed, event => this.emit(Events.Page.RequestFailed, event));+ networkManager.on(NetworkManagerEvents.RequestFinished, event => this.emit(Events.Page.RequestFinished, event));+ }++ async _initialize() {+ return Promise.all([+ this._frameManager.initialize(),+ this._session.send('Console.enable'),+ ]);+ }++ _setSession(newSession: TargetSession) {+ helper.removeEventListeners(this._sessionListeners);+ this._session = newSession;+ this._sessionListeners = [+ helper.addEventListener(this._session, TargetSessionEvents.Disconnected, () => this._frameManager.disconnectFromTarget()),+ helper.addEventListener(this._session, 'Page.loadEventFired', event => this.emit(Events.Page.Load)),+ helper.addEventListener(this._session, 'Console.messageAdded', event => this._onConsoleMessage(event)),+ helper.addEventListener(this._session, 'Page.domContentEventFired', event => this.emit(Events.Page.DOMContentLoaded)),+ ];+ }++ _setTarget(newTarget: Target) {+ this._target = newTarget;+ this._target._isClosedPromise.then(() => {+ if (this._target !== newTarget)+ return;+ this.emit(Events.Page.Close);+ this._closed = true;+ });+ }++ async _swapTargetOnNavigation(newSession : TargetSession, newTarget : Target) {+ this._setSession(newSession);+ this._setTarget(newTarget);+ await this._frameManager._swapTargetOnNavigation(newSession);+ await this._initialize().catch(e => debugError('failed to enable agents after swap: ' + e));+ }++ target(): Target {+ return this._target;+ }++ browser(): Browser {+ return this._target.browser();+ }++ browserContext(): BrowserContext {+ return this._target.browserContext();+ }++ _onTargetCrashed() {+ this.emit('error', new Error('Page crashed!'));+ }++ async _onConsoleMessage(event : Protocol.Console.messageAddedPayload) {+ const { type, level, text, parameters, url, line: lineNumber, column: columnNumber } = event.message;+ let derivedType: string = type;+ if (type === 'log')+ derivedType = level;+ else if (type === 'timing')+ derivedType = 'timeEnd';+ const mainFrameContext = await this.mainFrame().executionContext();+ const handles = (parameters || []).map(p => {+ let context = null;+ if (p.objectId) {+ const objectId = JSON.parse(p.objectId);+ context = this._frameManager._contextIdToContext.get(objectId.injectedScriptId);+ } else {+ context = mainFrameContext;+ }+ return createJSHandle(context, p);+ });+ const textTokens = [];+ for (const handle of handles) {+ const remoteObject = handle._remoteObject;+ if (remoteObject.objectId)+ textTokens.push(handle.toString());+ else+ textTokens.push(valueFromRemoteObject(remoteObject));+ }+ const location = {url, lineNumber, columnNumber};+ const formattedText = textTokens.length ? textTokens.join(' ') : text;+ this.emit(Events.Page.Console, new ConsoleMessage(derivedType, formattedText, handles, location));+ }++ mainFrame(): Frame {+ return this._frameManager.mainFrame();+ }++ get keyboard(): Keyboard {+ return this._keyboard;+ }++ frames(): Frame[] {+ return this._frameManager.frames();+ }++ workers(): Worker[] {+ return Array.from(this._workers.values());+ }+++ setDefaultNavigationTimeout(timeout: number) {+ this._timeoutSettings.setDefaultNavigationTimeout(timeout);+ }++ setDefaultTimeout(timeout: number) {+ this._timeoutSettings.setDefaultTimeout(timeout);+ }++ async $(selector: string): Promise<ElementHandle | null> {+ return this.mainFrame().$(selector);+ }++ async evaluateHandle(pageFunction: Function | string, ...args: any[]): Promise<JSHandle> {+ const context = await this.mainFrame().executionContext();+ return context.evaluateHandle(pageFunction, ...args);+ }++ async $eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<(object | undefined)> {+ return this.mainFrame().$eval(selector, pageFunction, ...args);+ }++ async $$eval(selector: string, pageFunction: Function | string, ...args: any[]): Promise<(object | undefined)> {+ return this.mainFrame().$$eval(selector, pageFunction, ...args);+ }++ async $$(selector: string): Promise<ElementHandle[]> {+ return this.mainFrame().$$(selector);+ }++ async $x(expression: string): Promise<ElementHandle[]> {+ return this.mainFrame().$x(expression);+ }++ async cookies(...urls: string[]): Promise<NetworkCookie[]> {+ const response = await this._session.send('Page.getCookies');+ return response.cookies.map(cookie => {+ // Webkit returns 0 for a cookie without an expiration+ if (cookie.expires === 0)+ cookie.expires = -1;+ return cookie;+ });+ }++ async deleteCookie(...cookies: DeleteNetworkCookieParam[]) {+ const pageURL = this.url();+ for (const cookie of cookies) {+ const item = {+ cookieName: cookie.name,+ url: cookie.url+ };+ if (!cookie.url && pageURL.startsWith('http'))+ item.url = pageURL;+ await this._session.send('Page.deleteCookie', item).catch(e => debugError('deleting ' + JSON.stringify(item) + ' => ' + e));+ }+ }++ async addScriptTag(options: { url?: string; path?: string; content?: string; type?: string; }): Promise<ElementHandle> {+ return this.mainFrame().addScriptTag(options);+ }++ async addStyleTag(options: { url?: string; path?: string; content?: string; }): Promise<ElementHandle> {+ return this.mainFrame().addStyleTag(options);+ }++ async setExtraHTTPHeaders(headers: { [s: string]: string; }) {+ return this._frameManager.networkManager().setExtraHTTPHeaders(headers);+ }++ async setUserAgent(userAgent: string) {+ await this._session.send('Page.overrideUserAgent', { value: userAgent });+ }++ url(): string {+ return this.mainFrame().url();+ }++ async content(): Promise<string> {+ return await this._frameManager.mainFrame().content();+ }++ async setContent(html: string, options: { timeout?: number; waitUntil?: string | string[]; } | undefined) {+ await this._frameManager.mainFrame().setContent(html, options);+ }++ async goto(url: string, options: { referer?: string; timeout?: number; waitUntil?: string | string[]; } | undefined): Promise<Response | null> {+ return await this._frameManager.mainFrame().goto(url, options);+ }++ async reload(): Promise<Response | null> {+ const [response] = await Promise.all([+ this.waitForNavigation(),+ this._session.send('Page.reload')+ ]);+ return response;+ }++ async waitForNavigation(): Promise<Response | null> {+ return await this._frameManager.mainFrame().waitForNavigation();+ }++ _sessionClosePromise() {+ if (!this._disconnectPromise)+ this._disconnectPromise = new Promise(fulfill => this._session.once(TargetSessionEvents.Disconnected, () => fulfill(new Error('Target closed'))));+ return this._disconnectPromise;+ }++ async waitForRequest(urlOrPredicate: (string | Function), options: { timeout?: number; } = {}): Promise<Request> {+ const {+ timeout = this._timeoutSettings.timeout(),+ } = options;+ return helper.waitForEvent(this._frameManager.networkManager(), NetworkManagerEvents.Request, request => {+ if (helper.isString(urlOrPredicate))+ return (urlOrPredicate === request.url());+ if (typeof urlOrPredicate === 'function')+ return !!(urlOrPredicate(request));+ return false;+ }, timeout, this._sessionClosePromise());+ }++ async waitForResponse(urlOrPredicate: (string | Function), options: { timeout?: number; } = {}): Promise<Response> {+ const {+ timeout = this._timeoutSettings.timeout(),+ } = options;+ return helper.waitForEvent(this._frameManager.networkManager(), NetworkManagerEvents.Response, response => {+ if (helper.isString(urlOrPredicate))+ return (urlOrPredicate === response.url());+ if (typeof urlOrPredicate === 'function')+ return !!(urlOrPredicate(response));+ return false;+ }, timeout, this._sessionClosePromise());+ }++ async emulate(options: { viewport: Viewport; userAgent: string; }) {+ await Promise.all([+ this.setViewport(options.viewport),+ this.setUserAgent(options.userAgent)+ ]);+ }++ async emulateMedia(type: string | null) {+ return this.emulateMediaType(type);+ }++ async emulateMediaType(type: string | null) {+ assert(type === 'screen' || type === 'print' || type === null, 'Unsupported media type: ' + type);+ await this._session.send('Page.setEmulatedMedia', {media: type || ''});+ }++ async setViewport(viewport: Viewport) {+ this._viewport = viewport;+ const width = viewport.width;+ const height = viewport.height;+ await this._session.send('Emulation.setDeviceMetricsOverride', { width, height });+ }++ viewport(): Viewport | null {+ return this._viewport;+ }++ async evaluate(pageFunction: Function | string, ...args: any[]): Promise<any> {+ return this._frameManager.mainFrame().evaluate(pageFunction, ...args);+ }++ async setCacheEnabled(enabled: boolean = true) {+ await this._frameManager.networkManager().setCacheEnabled(enabled);+ }++ async screenshot(options: ScreenshotOptions = {}): Promise<Buffer | string> {+ let screenshotType = null;+ // options.type takes precedence over inferring the type from options.path+ // because it may be a 0-length file with no extension created beforehand (i.e. as a temp file).+ if (options.type) {+ assert(options.type === 'png', 'Unknown options.type value: ' + options.type);+ screenshotType = options.type;+ } else if (options.path) {+ const mimeType = mime.getType(options.path);+ if (mimeType === 'image/png')+ screenshotType = 'png';+ assert(screenshotType, 'Unsupported screenshot mime type: ' + mimeType);+ }++ if (!screenshotType)+ screenshotType = 'png';++ if (options.quality)+ assert(screenshotType === 'jpeg', 'options.quality is unsupported for the ' + screenshotType + ' screenshots');+ assert(!options.clip || !options.fullPage, 'options.clip and options.fullPage are exclusive');+ if (options.clip) {+ assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' + (typeof options.clip.x));+ assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' + (typeof options.clip.y));+ assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' + (typeof options.clip.width));+ assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' + (typeof options.clip.height));+ assert(options.clip.width !== 0, 'Expected options.clip.width not to be 0.');+ assert(options.clip.height !== 0, 'Expected options.clip.height not to be 0.');+ }+ return this._screenshotTaskQueue.postTask(this._screenshotTask.bind(this, options));+ }++ async _screenshotTask(options?: ScreenshotOptions): Promise<Buffer | string> {+ const params: Protocol.Page.snapshotRectParameters = { x: 0, y: 0, width: 800, height: 600, coordinateSystem: 'Page' };+ if (options.fullPage) {+ const pageSize = await this.evaluate(() =>+ ({+ width: document.body.scrollWidth,+ height: document.body.scrollHeight+ }));+ Object.assign(params, pageSize);+ } else if (options.clip) {+ Object.assign(params, options.clip);+ } else if (this._viewport) {+ Object.assign(params, this._viewport);+ }+ const [, result] = await Promise.all([+ this._session._connection.send('Target.activate', { targetId: this._target._targetId }),+ this._session.send('Page.snapshotRect', params),+ ]).catch(e => {+ debugError('Failed to take screenshot: ' + e);+ throw e;+ });+ const prefix = 'data:image/png;base64,';+ const buffer = Buffer.from(result.dataURL.substr(prefix.length), 'base64');+ if (options.path)+ await writeFileAsync(options.path, buffer);+ return buffer;+ }++ async title(): Promise<string> {+ return this.mainFrame().title();+ }++ async close() {+ this.browser()._connection.send('Target.close', {+ targetId: this._target._targetId+ }).catch(e => {+ debugError(e);+ });+ await this._target._isClosedPromise;+ }++ isClosed(): boolean {+ return this._closed;+ }++ get mouse(): Mouse {+ return this._mouse;+ }++ click(selector: string, options?: ClickOptions) {+ return this.mainFrame().click(selector, options);+ }++ hover(selector: string) {+ return this.mainFrame().hover(selector);+ }++ focus(selector: string) {+ return this.mainFrame().focus(selector);+ }++ select(selector: string, ...values: string[]): Promise<string[]> {+ return this.mainFrame().select(selector, ...values);+ }++ type(selector: string, text: string, options: { delay: (number | undefined); } | undefined) {+ return this.mainFrame().type(selector, text, options);+ }++ waitFor(selectorOrFunctionOrTimeout: (string | number | Function), options: { visible?: boolean; hidden?: boolean; timeout?: number; polling?: string | number; } = {}, ...args: any[]): Promise<JSHandle> {+ return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);+ }++ waitForSelector(selector: string, options: { visible?: boolean; hidden?: boolean; timeout?: number; } = {}): Promise<ElementHandle | null> {+ return this.mainFrame().waitForSelector(selector, options);+ }++ waitForXPath(xpath: string, options: { visible?: boolean; hidden?: boolean; timeout?: number; } = {}): Promise<ElementHandle | null> {+ return this.mainFrame().waitForXPath(xpath, options);+ }++ waitForFunction(pageFunction: Function, options: {+ polling?: string | number;+ timeout?: number; } = {},+ ...args: any[]): Promise<JSHandle> {+ return this.mainFrame().waitForFunction(pageFunction, options, ...args);+ }+}++type PDFOptions = {+ scale?: number,+ displayHeaderFooter?: boolean,+ headerTemplate?: string,+ footerTemplate?: string,+ printBackground?: boolean,+ landscape?: boolean,+ pageRanges?: string,+ format?: string,+ width?: string|number,+ height?: string|number,+ preferCSSPageSize?: boolean,+ margin?: {top?: string|number, bottom?: string|number, left?: string|number, right?: string|number},+ path?: string,+}++type Metrics = {+ Timestamp?: number,+ Documents?: number,+ Frames?: number,+ JSEventListeners?: number,+ Nodes?: number,+ LayoutCount?: number,+ RecalcStyleCount?: number,+ LayoutDuration?: number,+ RecalcStyleDuration?: number,+ ScriptDuration?: number,+ TaskDuration?: number,+ JSHeapUsedSize?: number,+ JSHeapTotalSize?: number,+}++type ScreenshotOptions = {+ type?: string,+ path?: string,+ fullPage?: boolean,+ clip?: {x: number, y: number, width: number, height: number},+ quality?: number,+ omitBackground?: boolean,+ encoding?: string,+}++type NetworkCookie = {+ name: string,+ value: string,+ domain: string,+ path: string,+ expires: number,+ size: number,+ httpOnly: boolean,+ secure: boolean,+ session: boolean,+ sameSite?: 'Strict'|'Lax'|'Extended'|'None'+};++type DeleteNetworkCookieParam = {+ name: string,+ url?: string,+};++type ConsoleMessageLocation = {+ url?: string,+ lineNumber?: number,+ columnNumber?: number+};++export class ConsoleMessage {+ private _type: string;+ private _text: string;+ private _args: JSHandle[];+ private _location: any;++ constructor(type: string, text: string, args: JSHandle[], location: ConsoleMessageLocation = {}) {+ this._type = type;+ this._text = text;+ this._args = args;+ this._location = location;+ }++ type(): string {+ return this._type;+ }++ text(): string {+ return this._text;+ }++ args(): JSHandle[] {+ return this._args;+ }++ location(): object {+ return this._location;+ }+}diff --git a/src/webkit/PipeTransport.ts b/src/webkit/PipeTransport.tsnew file mode 100644index 0000000000..665d135c97--- /dev/null+++ b/src/webkit/PipeTransport.ts@@ -0,0 +1,73 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { ConnectionTransport } from '../ConnectionTransport';+import { debugError, helper, RegisteredListener } from '../helper';++export class PipeTransport implements ConnectionTransport {+ private _pipeWrite: NodeJS.WritableStream;+ private _pendingMessage = '';+ private _eventListeners: RegisteredListener[];+ onmessage?: (message: string) => void;+ onclose?: () => void;++ constructor(pipeWrite: NodeJS.WritableStream, pipeRead: NodeJS.ReadableStream) {+ this._pipeWrite = pipeWrite;+ this._eventListeners = [+ helper.addEventListener(pipeRead, 'data', buffer => this._dispatch(buffer)),+ helper.addEventListener(pipeRead, 'close', () => {+ if (this.onclose)+ this.onclose.call(null);+ }),+ helper.addEventListener(pipeRead, 'error', debugError),+ helper.addEventListener(pipeWrite, 'error', debugError),+ ];+ this.onmessage = null;+ this.onclose = null;+ }++ send(message: string) {+ this._pipeWrite.write(message);+ this._pipeWrite.write('\0');+ }++ _dispatch(buffer: Buffer) {+ let end = buffer.indexOf('\0');+ if (end === -1) {+ this._pendingMessage += buffer.toString();+ return;+ }+ const message = this._pendingMessage + buffer.toString(undefined, 0, end);+ if (this.onmessage)+ this.onmessage.call(null, message);++ let start = end + 1;+ end = buffer.indexOf('\0', start);+ while (end !== -1) {+ if (this.onmessage)+ this.onmessage.call(null, buffer.toString(undefined, start, end));+ start = end + 1;+ end = buffer.indexOf('\0', start);+ }+ this._pendingMessage = buffer.toString(undefined, start);+ }++ close() {+ this._pipeWrite = null;+ helper.removeEventListeners(this._eventListeners);+ }+}diff --git a/src/webkit/Playwright.ts b/src/webkit/Playwright.tsnew file mode 100644index 0000000000..9710cbfa2b--- /dev/null+++ b/src/webkit/Playwright.ts@@ -0,0 +1,54 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+import { Browser } from './Browser';+import { BrowserFetcher, BrowserFetcherOptions } from './BrowserFetcher';+import { DeviceDescriptors } from '../DeviceDescriptors';+import * as Errors from '../Errors';+import { Launcher, LauncherLaunchOptions } from './Launcher';++export class Playwright {+ private _projectRoot: string;+ private _launcher: Launcher;++ constructor(projectRoot: string, preferredRevision: string) {+ this._projectRoot = projectRoot;+ this._launcher = new Launcher(projectRoot, preferredRevision);+ }++ launch(options: (LauncherLaunchOptions) | undefined): Promise<Browser> {+ return this._launcher.launch(options);+ }++ executablePath(): string {+ return this._launcher.executablePath();+ }++ get devices(): any {+ const result = DeviceDescriptors.slice();+ for (const device of DeviceDescriptors)+ result[device.name] = device;+ return result;+ }++ get errors(): any {+ return Errors;+ }++ createBrowserFetcher(options: BrowserFetcherOptions | undefined): BrowserFetcher {+ return new BrowserFetcher(this._projectRoot, options);+ }+}diff --git a/src/webkit/Target.ts b/src/webkit/Target.tsnew file mode 100644index 0000000000..c40ab8edc0--- /dev/null+++ b/src/webkit/Target.ts@@ -0,0 +1,95 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { helper, RegisteredListener } from '../helper';+import { Browser, BrowserContext } from './Browser';+import { Page } from './Page';+import { Protocol } from './protocol';++export class Target {+ private _browserContext: BrowserContext;+ _targetId: string;+ private _type: 'page' | 'service-worker' | 'worker';+ _pagePromise: Promise<Page> | null = null;+ private _openerId?: string;+ private _url: string;+ _initializedPromise: Promise<boolean>;+ _initializedCallback: (value?: unknown) => void;+ _isClosedPromise: Promise<void>;+ _closedCallback: (value?: unknown) => void;+ _isInitialized: boolean;+ _eventListeners: RegisteredListener[];++ constructor(targetInfo: Protocol.Target.TargetInfo, browserContext: BrowserContext, openerId?: string) {+ const {targetId, url, type} = targetInfo;+ this._browserContext = browserContext;+ this._targetId = targetId;+ this._type = type;+ /** @type {?Promise<!Page>} */+ this._pagePromise = null;+ this._url = url;+ this._openerId = openerId;+ this._isClosedPromise = new Promise(fulfill => this._closedCallback = fulfill);+ if (type === 'page') {+ const session = this._browserContext.browser()._connection.session(this._targetId);+ this._eventListeners = [+ // FIXME: we could use Page.frameStartedLoading if it had url info.+ helper.addEventListener(session, 'Page.frameNavigated', this._onFrameNavigated.bind(this)),+ ];+ }+ }++ async _onFrameNavigated(params: Protocol.Page.frameNavigatedPayload) {+ // Check if main frame, get url from the event.+ // Skip child frames.+ if (params.frame.parentId)+ return;+ const url = params.frame.url;+ if (this._url !== url) {+ this._url = url;+ this.browser()._onTargetChanged(this);+ }+ }++ async page(): Promise<Page | null> {+ if (this._type === 'page' && !this._pagePromise) {+ const session = this.browser()._connection.session(this._targetId);+ this._pagePromise = Page.create(session, this, this.browser()._defaultViewport, this.browser()._screenshotTaskQueue);+ }+ return this._pagePromise;+ }++ url(): string {+ return this._url;+ }++ type(): 'page' | 'service-worker' | 'worker' {+ return this._type;+ }++ browser(): Browser {+ return this._browserContext.browser();+ }++ browserContext(): BrowserContext {+ return this._browserContext;+ }++ opener(): Target | null {+ return this._openerId ? this.browser()._targets.get(this._openerId) : null;+ }+}diff --git a/src/webkit/TaskQueue.ts b/src/webkit/TaskQueue.tsnew file mode 100644index 0000000000..99b2de4469--- /dev/null+++ b/src/webkit/TaskQueue.ts@@ -0,0 +1,30 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export class TaskQueue {+ private _chain: Promise<any>;++ constructor() {+ this._chain = Promise.resolve();+ }++ postTask(task: () => any): Promise<any> {+ const result = this._chain.then(task);+ this._chain = result.catch(() => {});+ return result;+ }+}diff --git a/src/webkit/protocolHelper.ts b/src/webkit/protocolHelper.tsnew file mode 100644index 0000000000..fc7ddf4c8c--- /dev/null+++ b/src/webkit/protocolHelper.ts@@ -0,0 +1,55 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import { assert, debugError } from '../helper';+import { TargetSession } from './Connection';+import { Protocol } from './protocol';++export function valueFromRemoteObject(remoteObject: Protocol.Runtime.RemoteObject): any {+ assert(!remoteObject.objectId, 'Cannot extract value when objectId is given');+ if (remoteObject.type === 'number') {+ if (remoteObject.value === null) {+ switch (remoteObject.description) {+ case 'NaN':+ return NaN;+ case 'Infinity':+ return Infinity;+ case '-Infinity':+ return -Infinity;+ default:+ throw new Error('Unsupported unserializable value: ' + remoteObject.description);+ }+ } else if (remoteObject.value === 0) {+ switch (remoteObject.description) {+ case '-0':+ return -0;+ }+ }+ }+ return remoteObject.value;+}++export async function releaseObject(client: TargetSession, remoteObject: Protocol.Runtime.RemoteObject) {+ if (!remoteObject.objectId)+ return;+ await client.send('Runtime.releaseObject', {objectId: remoteObject.objectId}).catch(error => {+ // Exceptions might happen in case of a page been navigated or closed.+ // Swallow these since they are harmless and we don't leak anything in this case.+ debugError(error);+ });+}+diff --git a/test/CDPSession.spec.js b/test/CDPSession.spec.jsnew file mode 100644index 0000000000..67c338d24c--- /dev/null+++ b/test/CDPSession.spec.js@@ -0,0 +1,83 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {waitEvent} = require('./utils');++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Target.createCDPSession', function() {+ it('should work', async function({page, server}) {+ const client = await page.target().createCDPSession();++ await Promise.all([+ client.send('Runtime.enable'),+ client.send('Runtime.evaluate', { expression: 'window.foo = "bar"' })+ ]);+ const foo = await page.evaluate(() => window.foo);+ expect(foo).toBe('bar');+ });+ it('should send events', async function({page, server}) {+ const client = await page.target().createCDPSession();+ await client.send('Network.enable');+ const events = [];+ client.on('Network.requestWillBeSent', event => events.push(event));+ await page.goto(server.EMPTY_PAGE);+ expect(events.length).toBe(1);+ });+ it('should enable and disable domains independently', async function({page, server}) {+ const client = await page.target().createCDPSession();+ await client.send('Runtime.enable');+ await client.send('Debugger.enable');+ // JS coverage enables and then disables Debugger domain.+ await page.coverage.startJSCoverage();+ await page.coverage.stopJSCoverage();+ // generate a script in page and wait for the event.+ const [event] = await Promise.all([+ waitEvent(client, 'Debugger.scriptParsed'),+ page.evaluate('//# sourceURL=foo.js')+ ]);+ // expect events to be dispatched.+ expect(event.url).toBe('foo.js');+ });+ it('should be able to detach session', async function({page, server}) {+ const client = await page.target().createCDPSession();+ await client.send('Runtime.enable');+ const evalResponse = await client.send('Runtime.evaluate', {expression: '1 + 2', returnByValue: true});+ expect(evalResponse.result.value).toBe(3);+ await client.detach();+ let error = null;+ try {+ await client.send('Runtime.evaluate', {expression: '3 + 1', returnByValue: true});+ } catch (e) {+ error = e;+ }+ expect(error.message).toContain('Session closed.');+ });+ it('should throw nice errors', async function({page}) {+ const client = await page.target().createCDPSession();+ const error = await theSourceOfTheProblems().catch(error => error);+ expect(error.stack).toContain('theSourceOfTheProblems');+ expect(error.message).toContain('ThisCommand.DoesNotExist');++ async function theSourceOfTheProblems() {+ await client.send('ThisCommand.DoesNotExist');+ }+ });+ });+};diff --git a/test/accessibility.spec.js b/test/accessibility.spec.jsnew file mode 100644index 0000000000..f365436552--- /dev/null+++ b/test/accessibility.spec.js@@ -0,0 +1,383 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe.skip(WEBKIT)('Accessibility', function() {+ it('should work', async function({page}) {+ await page.setContent(`+ <head>+ <title>Accessibility Test</title>+ </head>+ <body>+ <div>Hello World</div>+ <h1>Inputs</h1>+ <input placeholder="Empty input" autofocus />+ <input placeholder="readonly input" readonly />+ <input placeholder="disabled input" disabled />+ <input aria-label="Input with whitespace" value=" " />+ <input value="value only" />+ <input aria-placeholder="placeholder" value="and a value" />+ <div aria-hidden="true" id="desc">This is a description!</div>+ <input aria-placeholder="placeholder" value="and a value" aria-describedby="desc" />+ <select>+ <option>First Option</option>+ <option>Second Option</option>+ </select>+ </body>`);+ // autofocus happens after a delay in chrome these days+ await page.waitForFunction(() => document.activeElement.hasAttribute('autofocus'));++ const golden = FFOX ? {+ role: 'document',+ name: 'Accessibility Test',+ children: [+ {role: 'text leaf', name: 'Hello World'},+ {role: 'heading', name: 'Inputs', level: 1},+ {role: 'entry', name: 'Empty input', focused: true},+ {role: 'entry', name: 'readonly input', readonly: true},+ {role: 'entry', name: 'disabled input', disabled: true},+ {role: 'entry', name: 'Input with whitespace', value: ' '},+ {role: 'entry', name: '', value: 'value only'},+ {role: 'entry', name: '', value: 'and a value'}, // firefox doesn't use aria-placeholder for the name+ {role: 'entry', name: '', value: 'and a value', description: 'This is a description!'}, // and here+ {role: 'combobox', name: '', value: 'First Option', haspopup: true, children: [+ {role: 'combobox option', name: 'First Option', selected: true},+ {role: 'combobox option', name: 'Second Option'}]+ }]+ } : {+ role: 'WebArea',+ name: 'Accessibility Test',+ children: [+ {role: 'text', name: 'Hello World'},+ {role: 'heading', name: 'Inputs', level: 1},+ {role: 'textbox', name: 'Empty input', focused: true},+ {role: 'textbox', name: 'readonly input', readonly: true},+ {role: 'textbox', name: 'disabled input', disabled: true},+ {role: 'textbox', name: 'Input with whitespace', value: ' '},+ {role: 'textbox', name: '', value: 'value only'},+ {role: 'textbox', name: 'placeholder', value: 'and a value'},+ {role: 'textbox', name: 'placeholder', value: 'and a value', description: 'This is a description!'},+ {role: 'combobox', name: '', value: 'First Option', children: [+ {role: 'menuitem', name: 'First Option', selected: true},+ {role: 'menuitem', name: 'Second Option'}]+ }]+ };+ expect(await page.accessibility.snapshot()).toEqual(golden);+ });+ it('should report uninteresting nodes', async function({page}) {+ await page.setContent(`<textarea autofocus>hi</textarea>`);+ // autofocus happens after a delay in chrome these days+ await page.waitForFunction(() => document.activeElement.hasAttribute('autofocus'));+ const golden = FFOX ? {+ role: 'entry',+ name: '',+ value: 'hi',+ focused: true,+ multiline: true,+ children: [{+ role: 'text leaf',+ name: 'hi'+ }]+ } : {+ role: 'textbox',+ name: '',+ value: 'hi',+ focused: true,+ multiline: true,+ children: [{+ role: 'GenericContainer',+ name: '',+ children: [{+ role: 'text', name: 'hi'+ }]+ }]+ };+ expect(findFocusedNode(await page.accessibility.snapshot({interestingOnly: false}))).toEqual(golden);+ });+ it('roledescription', async({page}) => {+ await page.setContent('<div tabIndex=-1 aria-roledescription="foo">Hi</div>');+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0].roledescription).toEqual('foo');+ });+ it('orientation', async({page}) => {+ await page.setContent('<a href="" role="slider" aria-orientation="vertical">11</a>');+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0].orientation).toEqual('vertical');+ });+ it.skip(FFOX)('autocomplete', async({page}) => {+ await page.setContent('<input type="number" aria-autocomplete="list" />');+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0].autocomplete).toEqual('list');+ });+ it('multiselectable', async({page}) => {+ await page.setContent('<div role="grid" tabIndex=-1 aria-multiselectable=true>hey</div>');+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0].multiselectable).toEqual(true);+ });+ it('keyshortcuts', async({page}) => {+ await page.setContent('<div role="grid" tabIndex=-1 aria-keyshortcuts="foo">hey</div>');+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0].keyshortcuts).toEqual('foo');+ });+ describe('filtering children of leaf nodes', function() {+ it('should not report text nodes inside controls', async function({page}) {+ await page.setContent(`+ <div role="tablist">+ <div role="tab" aria-selected="true"><b>Tab1</b></div>+ <div role="tab">Tab2</div>+ </div>`);+ const golden = FFOX ? {+ role: 'document',+ name: '',+ children: [{+ role: 'pagetab',+ name: 'Tab1',+ selected: true+ }, {+ role: 'pagetab',+ name: 'Tab2'+ }]+ } : {+ role: 'WebArea',+ name: '',+ children: [{+ role: 'tab',+ name: 'Tab1',+ selected: true+ }, {+ role: 'tab',+ name: 'Tab2'+ }]+ };+ expect(await page.accessibility.snapshot()).toEqual(golden);+ });+ it('rich text editable fields should have children', async function({page}) {+ await page.setContent(`+ <div contenteditable="true">+ Edit this image: <img src="fakeimage.png" alt="my fake image">+ </div>`);+ const golden = FFOX ? {+ role: 'section',+ name: '',+ children: [{+ role: 'text leaf',+ name: 'Edit this image: '+ }, {+ role: 'text',+ name: 'my fake image'+ }]+ } : {+ role: 'GenericContainer',+ name: '',+ value: 'Edit this image: ',+ children: [{+ role: 'text',+ name: 'Edit this image:'+ }, {+ role: 'img',+ name: 'my fake image'+ }]+ };+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0]).toEqual(golden);+ });+ it('rich text editable fields with role should have children', async function({page}) {+ await page.setContent(`+ <div contenteditable="true" role='textbox'>+ Edit this image: <img src="fakeimage.png" alt="my fake image">+ </div>`);+ const golden = FFOX ? {+ role: 'entry',+ name: '',+ value: 'Edit this image: my fake image',+ children: [{+ role: 'text',+ name: 'my fake image'+ }]+ } : {+ role: 'textbox',+ name: '',+ value: 'Edit this image: ',+ children: [{+ role: 'text',+ name: 'Edit this image:'+ }, {+ role: 'img',+ name: 'my fake image'+ }]+ };+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0]).toEqual(golden);+ });+ // Firefox does not support contenteditable="plaintext-only".+ !FFOX && describe('plaintext contenteditable', function() {+ it('plain text field with role should not have children', async function({page}) {+ await page.setContent(`+ <div contenteditable="plaintext-only" role='textbox'>Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`);+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0]).toEqual({+ role: 'textbox',+ name: '',+ value: 'Edit this image:'+ });+ });+ it('plain text field without role should not have content', async function({page}) {+ await page.setContent(`+ <div contenteditable="plaintext-only">Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`);+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0]).toEqual({+ role: 'GenericContainer',+ name: ''+ });+ });+ it('plain text field with tabindex and without role should not have content', async function({page}) {+ await page.setContent(`+ <div contenteditable="plaintext-only" tabIndex=0>Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`);+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0]).toEqual({+ role: 'GenericContainer',+ name: ''+ });+ });+ });+ it('non editable textbox with role and tabIndex and label should not have children', async function({page}) {+ await page.setContent(`+ <div role="textbox" tabIndex=0 aria-checked="true" aria-label="my favorite textbox">+ this is the inner content+ <img alt="yo" src="fakeimg.png">+ </div>`);+ const golden = FFOX ? {+ role: 'entry',+ name: 'my favorite textbox',+ value: 'this is the inner content yo'+ } : {+ role: 'textbox',+ name: 'my favorite textbox',+ value: 'this is the inner content '+ };+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0]).toEqual(golden);+ });+ it('checkbox with and tabIndex and label should not have children', async function({page}) {+ await page.setContent(`+ <div role="checkbox" tabIndex=0 aria-checked="true" aria-label="my favorite checkbox">+ this is the inner content+ <img alt="yo" src="fakeimg.png">+ </div>`);+ const golden = FFOX ? {+ role: 'checkbutton',+ name: 'my favorite checkbox',+ checked: true+ } : {+ role: 'checkbox',+ name: 'my favorite checkbox',+ checked: true+ };+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0]).toEqual(golden);+ });+ it('checkbox without label should not have children', async function({page}) {+ await page.setContent(`+ <div role="checkbox" aria-checked="true">+ this is the inner content+ <img alt="yo" src="fakeimg.png">+ </div>`);+ const golden = FFOX ? {+ role: 'checkbutton',+ name: 'this is the inner content yo',+ checked: true+ } : {+ role: 'checkbox',+ name: 'this is the inner content yo',+ checked: true+ };+ const snapshot = await page.accessibility.snapshot();+ expect(snapshot.children[0]).toEqual(golden);+ });++ describe.skip(FFOX)('root option', function() {+ it('should work a button', async({page}) => {+ await page.setContent(`<button>My Button</button>`);++ const button = await page.$('button');+ expect(await page.accessibility.snapshot({root: button})).toEqual({+ role: 'button',+ name: 'My Button'+ });+ });+ it('should work an input', async({page}) => {+ await page.setContent(`<input title="My Input" value="My Value">`);++ const input = await page.$('input');+ expect(await page.accessibility.snapshot({root: input})).toEqual({+ role: 'textbox',+ name: 'My Input',+ value: 'My Value'+ });+ });+ it('should work a menu', async({page}) => {+ await page.setContent(`+ <div role="menu" title="My Menu">+ <div role="menuitem">First Item</div>+ <div role="menuitem">Second Item</div>+ <div role="menuitem">Third Item</div>+ </div>+ `);++ const menu = await page.$('div[role="menu"]');+ expect(await page.accessibility.snapshot({root: menu})).toEqual({+ role: 'menu',+ name: 'My Menu',+ children:+ [ { role: 'menuitem', name: 'First Item' },+ { role: 'menuitem', name: 'Second Item' },+ { role: 'menuitem', name: 'Third Item' } ]+ });+ });+ it('should return null when the element is no longer in DOM', async({page}) => {+ await page.setContent(`<button>My Button</button>`);+ const button = await page.$('button');+ await page.$eval('button', button => button.remove());+ expect(await page.accessibility.snapshot({root: button})).toEqual(null);+ });+ it('should support the interestingOnly option', async({page}) => {+ await page.setContent(`<div><button>My Button</button></div>`);+ const div = await page.$('div');+ expect(await page.accessibility.snapshot({root: div})).toEqual(null);+ expect(await page.accessibility.snapshot({root: div, interestingOnly: false})).toEqual({+ role: 'GenericContainer',+ name: '',+ children: [ { role: 'button', name: 'My Button' } ] }+ );+ });+ });+ });+ function findFocusedNode(node) {+ if (node.focused)+ return node;+ for (const child of node.children || []) {+ const focusedChild = findFocusedNode(child);+ if (focusedChild)+ return focusedChild;+ }+ return null;+ }+ });+};diff --git a/test/assets/beforeunload.html b/test/assets/beforeunload.htmlnew file mode 100644index 0000000000..3cef6763f3--- /dev/null+++ b/test/assets/beforeunload.html@@ -0,0 +1,10 @@+<div>beforeunload demo.</div>+<script>+window.addEventListener('beforeunload', event => {+ // Chrome way.+ event.returnValue = 'Leave?';+ // Firefox way.+ event.preventDefault();+});+</script>+diff --git a/test/assets/cached/one-style.css b/test/assets/cached/one-style.cssnew file mode 100644index 0000000000..04e7110b41--- /dev/null+++ b/test/assets/cached/one-style.css@@ -0,0 +1,3 @@+body {+ background-color: pink;+}diff --git a/test/assets/cached/one-style.html b/test/assets/cached/one-style.htmlnew file mode 100644index 0000000000..4760f2b9f7--- /dev/null+++ b/test/assets/cached/one-style.html@@ -0,0 +1,2 @@+<link rel='stylesheet' href='./one-style.css'>+<div>hello, world!</div>diff --git a/test/assets/chromium-linux.zip b/test/assets/chromium-linux.zipnew file mode 100644index 0000000000..9c00ec080dBinary files /dev/null and b/test/assets/chromium-linux.zip differdiff --git a/test/assets/consolelog.html b/test/assets/consolelog.htmlnew file mode 100644index 0000000000..7fa1b211a4--- /dev/null+++ b/test/assets/consolelog.html@@ -0,0 +1,11 @@+<!DOCTYPE html>+<html>+ <head>+ <title>console.log test</title>+ </head>+ <body>+ <script>+ console.log('yellow')+ </script>+ </body>+</html>diff --git a/test/assets/csp.html b/test/assets/csp.htmlnew file mode 100644index 0000000000..34fc1fc1a5--- /dev/null+++ b/test/assets/csp.html@@ -0,0 +1 @@+<meta http-equiv="Content-Security-Policy" content="default-src 'self'">diff --git a/test/assets/csscoverage/Dosis-Regular.ttf b/test/assets/csscoverage/Dosis-Regular.ttfnew file mode 100644index 0000000000..4b208624e8Binary files /dev/null and b/test/assets/csscoverage/Dosis-Regular.ttf differdiff --git a/test/assets/csscoverage/OFL.txt b/test/assets/csscoverage/OFL.txtnew file mode 100644index 0000000000..a9b3c8b34e--- /dev/null+++ b/test/assets/csscoverage/OFL.txt@@ -0,0 +1,95 @@+Copyright (c) 2011, Edgar Tolentino and Pablo Impallari (www.impallari.com|[email protected]),+Copyright (c) 2011, Igino Marini. (www.ikern.com|[email protected]),+with Reserved Font Names "Dosis".++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL+++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION & CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/test/assets/csscoverage/involved.html b/test/assets/csscoverage/involved.htmlnew file mode 100644index 0000000000..bcd9845b93--- /dev/null+++ b/test/assets/csscoverage/involved.html@@ -0,0 +1,26 @@+<style>+@charset "utf-8";+@namespace svg url(http://www.w3.org/2000/svg);+@font-face {+ font-family: "Example Font";+ src: url("./Dosis-Regular.ttf");+}++#fluffy {+ border: 1px solid black;+ z-index: 1;+ /* -webkit-disabled-property: rgb(1, 2, 3) */+ -lol-cats: "dogs" /* non-existing property */+}++@media (min-width: 1px) {+ span {+ -webkit-border-radius: 10px;+ font-family: "Example Font";+ animation: 1s identifier;+ }+}+</style>+<div id="fluffy">woof!</div>+<span>fancy text</span>+diff --git a/test/assets/csscoverage/media.html b/test/assets/csscoverage/media.htmlnew file mode 100644index 0000000000..bfb89f8f75--- /dev/null+++ b/test/assets/csscoverage/media.html@@ -0,0 +1,4 @@+<style>+@media screen { div { color: green; } } </style>+<div>hello, world</div>+diff --git a/test/assets/csscoverage/multiple.html b/test/assets/csscoverage/multiple.htmlnew file mode 100644index 0000000000..0fd97e962a--- /dev/null+++ b/test/assets/csscoverage/multiple.html@@ -0,0 +1,8 @@+<link rel="stylesheet" href="stylesheet1.css">+<link rel="stylesheet" href="stylesheet2.css">+<script>+window.addEventListener('DOMContentLoaded', () => {+ // Force stylesheets to load.+ console.log(window.getComputedStyle(document.body).color);+}, false);+</script>diff --git a/test/assets/csscoverage/simple.html b/test/assets/csscoverage/simple.htmlnew file mode 100644index 0000000000..3beae21829--- /dev/null+++ b/test/assets/csscoverage/simple.html@@ -0,0 +1,6 @@+<style>+div { color: green; }+a { color: blue; }+</style>+<div>hello, world</div>+diff --git a/test/assets/csscoverage/sourceurl.html b/test/assets/csscoverage/sourceurl.htmlnew file mode 100644index 0000000000..df4e9c276c--- /dev/null+++ b/test/assets/csscoverage/sourceurl.html@@ -0,0 +1,7 @@+<style>+body {+ padding: 10px;+}+/*# sourceURL=nicename.css */+</style>+diff --git a/test/assets/csscoverage/stylesheet1.css b/test/assets/csscoverage/stylesheet1.cssnew file mode 100644index 0000000000..60f1eab971--- /dev/null+++ b/test/assets/csscoverage/stylesheet1.css@@ -0,0 +1,3 @@+body {+ color: red;+}diff --git a/test/assets/csscoverage/stylesheet2.css b/test/assets/csscoverage/stylesheet2.cssnew file mode 100644index 0000000000..a87defb098--- /dev/null+++ b/test/assets/csscoverage/stylesheet2.css@@ -0,0 +1,4 @@+html {+ margin: 0;+ padding: 0;+}diff --git a/test/assets/csscoverage/unused.html b/test/assets/csscoverage/unused.htmlnew file mode 100644index 0000000000..5b8186a3bf--- /dev/null+++ b/test/assets/csscoverage/unused.html@@ -0,0 +1,7 @@+<style>+@media screen {+ a { color: green; }+}+/*# sourceURL=unused.css */+</style>+diff --git a/test/assets/detect-touch.html b/test/assets/detect-touch.htmlnew file mode 100644index 0000000000..80a4123fbd--- /dev/null+++ b/test/assets/detect-touch.html@@ -0,0 +1,12 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Detect Touch Test</title>+ <script src='modernizr.js'></script>+ </head>+ <body style="font-size:30vmin">+ <script>+ document.body.textContent = Modernizr.touchevents ? 'YES' : 'NO';+ </script>+ </body>+</html>diff --git a/test/assets/digits/0.png b/test/assets/digits/0.pngnew file mode 100644index 0000000000..ac3c4768edBinary files /dev/null and b/test/assets/digits/0.png differdiff --git a/test/assets/digits/1.png b/test/assets/digits/1.pngnew file mode 100644index 0000000000..6768222729Binary files /dev/null and b/test/assets/digits/1.png differdiff --git a/test/assets/digits/2.png b/test/assets/digits/2.pngnew file mode 100644index 0000000000..b1daa4735dBinary files /dev/null and b/test/assets/digits/2.png differdiff --git a/test/assets/digits/3.png b/test/assets/digits/3.pngnew file mode 100644index 0000000000..6eca99b21bBinary files /dev/null and b/test/assets/digits/3.png differdiff --git a/test/assets/digits/4.png b/test/assets/digits/4.pngnew file mode 100644index 0000000000..a721071e2cBinary files /dev/null and b/test/assets/digits/4.png differdiff --git a/test/assets/digits/5.png b/test/assets/digits/5.pngnew file mode 100644index 0000000000..15cb19932aBinary files /dev/null and b/test/assets/digits/5.png differdiff --git a/test/assets/digits/6.png b/test/assets/digits/6.pngnew file mode 100644index 0000000000..639f38439dBinary files /dev/null and b/test/assets/digits/6.png differdiff --git a/test/assets/digits/7.png b/test/assets/digits/7.pngnew file mode 100644index 0000000000..5c1150b005Binary files /dev/null and b/test/assets/digits/7.png differdiff --git a/test/assets/digits/8.png b/test/assets/digits/8.pngnew file mode 100644index 0000000000..abb8b48b0bBinary files /dev/null and b/test/assets/digits/8.png differdiff --git a/test/assets/digits/9.png b/test/assets/digits/9.pngnew file mode 100644index 0000000000..6a40a21c6fBinary files /dev/null and b/test/assets/digits/9.png differdiff --git a/test/assets/dynamic-oopif.html b/test/assets/dynamic-oopif.htmlnew file mode 100644index 0000000000..f00c741dfb--- /dev/null+++ b/test/assets/dynamic-oopif.html@@ -0,0 +1,10 @@+<script>+window.addEventListener('DOMContentLoaded', () => {+ const iframe = document.createElement('iframe');+ const url = new URL(location.href);+ url.hostname = url.hostname === 'localhost' ? '127.0.0.1' : 'localhost';+ url.pathname = '/grid.html';+ iframe.src = url.toString();+ document.body.appendChild(iframe);+}, false);+</script>diff --git a/test/assets/empty.html b/test/assets/empty.htmlnew file mode 100644index 0000000000..e69de29bb2diff --git a/test/assets/error.html b/test/assets/error.htmlnew file mode 100644index 0000000000..130400c006--- /dev/null+++ b/test/assets/error.html@@ -0,0 +1,15 @@+<script>+a();++function a() {+ b();+}++function b() {+ c();+}++function c() {+ throw new Error('Fancy error!');+}+</script>diff --git a/test/assets/es6/.eslintrc b/test/assets/es6/.eslintrcnew file mode 100644index 0000000000..1903e176f5--- /dev/null+++ b/test/assets/es6/.eslintrc@@ -0,0 +1,5 @@+{+ "parserOptions": {+ "sourceType": "module"+ }+}\ No newline at end of filediff --git a/test/assets/es6/es6import.js b/test/assets/es6/es6import.jsnew file mode 100644index 0000000000..9a0a1095d1--- /dev/null+++ b/test/assets/es6/es6import.js@@ -0,0 +1,2 @@+import num from './es6module.js';+window.__es6injected = num;\ No newline at end of filediff --git a/test/assets/es6/es6module.js b/test/assets/es6/es6module.jsnew file mode 100644index 0000000000..a4012bff06--- /dev/null+++ b/test/assets/es6/es6module.js@@ -0,0 +1 @@+export default 42;\ No newline at end of filediff --git a/test/assets/es6/es6pathimport.js b/test/assets/es6/es6pathimport.jsnew file mode 100644index 0000000000..99919621a8--- /dev/null+++ b/test/assets/es6/es6pathimport.js@@ -0,0 +1,2 @@+import num from './es6/es6module.js';+window.__es6injected = num;\ No newline at end of filediff --git a/test/assets/file-to-upload.txt b/test/assets/file-to-upload.txtnew file mode 100644index 0000000000..b4ad118489--- /dev/null+++ b/test/assets/file-to-upload.txt@@ -0,0 +1 @@+contents of the file\ No newline at end of filediff --git a/test/assets/frames/frame.html b/test/assets/frames/frame.htmlnew file mode 100644index 0000000000..8f20d2da9f--- /dev/null+++ b/test/assets/frames/frame.html@@ -0,0 +1,8 @@+<link rel='stylesheet' href='./style.css'>+<script src='./script.js' type='text/javascript'></script>+<style>+div {+ line-height: 18px;+}+</style>+<div>Hi, I'm frame</div>diff --git a/test/assets/frames/frameset.html b/test/assets/frames/frameset.htmlnew file mode 100644index 0000000000..4d56f88839--- /dev/null+++ b/test/assets/frames/frameset.html@@ -0,0 +1,8 @@+<frameset>+ <frameset>+ <frame src='./frame.html'></frame>+ <frame src='about:blank'></frame>+ </frameset>+ <frame src='/empty.html'></frame>+ <frame></frame>+</frameset>diff --git a/test/assets/frames/nested-frames.html b/test/assets/frames/nested-frames.htmlnew file mode 100644index 0000000000..de1987586f--- /dev/null+++ b/test/assets/frames/nested-frames.html@@ -0,0 +1,25 @@+<style>+body {+ display: flex;+}++body iframe {+ flex-grow: 1;+ flex-shrink: 1;+}+::-webkit-scrollbar{+ display: none;+}+</style>+<script>+async function attachFrame(frameId, url) {+ var frame = document.createElement('iframe');+ frame.src = url;+ frame.id = frameId;+ document.body.appendChild(frame);+ await new Promise(x => frame.onload = x);+ return 'kazakh';+}+</script>+<iframe src='./two-frames.html' name='2frames'></iframe>+<iframe src='./frame.html' name='aframe'></iframe>diff --git a/test/assets/frames/one-frame.html b/test/assets/frames/one-frame.htmlnew file mode 100644index 0000000000..e941d795a2--- /dev/null+++ b/test/assets/frames/one-frame.html@@ -0,0 +1 @@+<iframe src='./frame.html'></iframe>diff --git a/test/assets/frames/script.js b/test/assets/frames/script.jsnew file mode 100644index 0000000000..be22256d16--- /dev/null+++ b/test/assets/frames/script.js@@ -0,0 +1 @@+console.log('Cheers!');diff --git a/test/assets/frames/style.css b/test/assets/frames/style.cssnew file mode 100644index 0000000000..5b5436e874--- /dev/null+++ b/test/assets/frames/style.css@@ -0,0 +1,3 @@+div {+ color: blue;+}diff --git a/test/assets/frames/two-frames.html b/test/assets/frames/two-frames.htmlnew file mode 100644index 0000000000..b2ee853eda--- /dev/null+++ b/test/assets/frames/two-frames.html@@ -0,0 +1,13 @@+<style>+body {+ display: flex;+ flex-direction: column;+}++body iframe {+ flex-grow: 1;+ flex-shrink: 1;+}+</style>+<iframe src='./frame.html' name='uno'></iframe>+<iframe src='./frame.html' name='dos'></iframe>diff --git a/test/assets/global-var.html b/test/assets/global-var.htmlnew file mode 100644index 0000000000..b6be975038--- /dev/null+++ b/test/assets/global-var.html@@ -0,0 +1,3 @@+<script>+var globalVar = 123;+</script>\ No newline at end of filediff --git a/test/assets/grid.html b/test/assets/grid.htmlnew file mode 100644index 0000000000..0bdbb1220e--- /dev/null+++ b/test/assets/grid.html@@ -0,0 +1,52 @@+<script>+document.addEventListener('DOMContentLoaded', function() {+ function generatePalette(amount) {+ var result = [];+ var hueStep = 360 / amount;+ for (var i = 0; i < amount; ++i)+ result.push('hsl(' + (hueStep * i) + ', 100%, 90%)');+ return result;+ }++ var palette = generatePalette(100);+ for (var i = 0; i < 200; ++i) {+ var box = document.createElement('div');+ box.classList.add('box');+ box.style.setProperty('background-color', palette[i % palette.length]);+ var x = i;+ do {+ var digit = x % 10;+ x = (x / 10)|0;+ var img = document.createElement('img');+ img.src = `./digits/${digit}.png`;+ box.insertBefore(img, box.firstChild);+ } while (x);+ document.body.appendChild(box);+ }+});+</script>++<style>++body {+ margin: 0;+ padding: 0;+}++.box {+ font-family: arial;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ margin: 0;+ padding: 0;+ width: 50px;+ height: 50px;+ box-sizing: border-box;+ border: 1px solid darkgray;+}++::-webkit-scrollbar {+ display: none;+}+</style>diff --git a/test/assets/historyapi.html b/test/assets/historyapi.htmlnew file mode 100644index 0000000000..bacaf9e9a0--- /dev/null+++ b/test/assets/historyapi.html@@ -0,0 +1,5 @@+<script>+window.addEventListener('DOMContentLoaded', () => {+ history.pushState({}, '', '#1');+});+</script>diff --git a/test/assets/injectedfile.js b/test/assets/injectedfile.jsnew file mode 100644index 0000000000..6cb04f1bba--- /dev/null+++ b/test/assets/injectedfile.js@@ -0,0 +1,2 @@+window.__injected = 42;+window.__injectedError = new Error('hi');\ No newline at end of filediff --git a/test/assets/injectedstyle.css b/test/assets/injectedstyle.cssnew file mode 100644index 0000000000..aa1634c255--- /dev/null+++ b/test/assets/injectedstyle.css@@ -0,0 +1,3 @@+body {+ background-color: red;+}diff --git a/test/assets/input/button.html b/test/assets/input/button.htmlnew file mode 100644index 0000000000..aaba6a5e2a--- /dev/null+++ b/test/assets/input/button.html@@ -0,0 +1,22 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Button test</title>+ </head>+ <body>+ <script src="mouse-helper.js"></script>+ <button>Click target</button>+ <script>+ window.result = 'Was not clicked';+ window.offsetX = undefined;+ window.offsetY = undefined;+ window.shiftKey = undefined;+ document.querySelector('button').addEventListener('click', e => {+ result = 'Clicked';+ offsetX = e.offsetX;+ offsetY = e.offsetY;+ shiftKey = e.shiftKey;+ }, false);+ </script>+ </body>+</html>\ No newline at end of filediff --git a/test/assets/input/checkbox.html b/test/assets/input/checkbox.htmlnew file mode 100644index 0000000000..ca56762e2b--- /dev/null+++ b/test/assets/input/checkbox.html@@ -0,0 +1,42 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Selection Test</title>+ </head>+ <body>+ <label for="agree">Remember Me</label>+ <input id="agree" type="checkbox">+ <script>+ window.result = {+ check: null,+ events: [],+ };++ let checkbox = document.querySelector('input');++ const events = [+ 'change',+ 'click',+ 'dblclick',+ 'input',+ 'mousedown',+ 'mouseenter',+ 'mouseleave',+ 'mousemove',+ 'mouseout',+ 'mouseover',+ 'mouseup',+ ];++ for (let event of events) {+ checkbox.addEventListener(event, () => {+ if (['change', 'click', 'dblclick', 'input'].includes(event) === true) {+ result.check = checkbox.checked;+ }++ result.events.push(event);+ }, false);+ }+ </script>+ </body>+</html>diff --git a/test/assets/input/fileupload.html b/test/assets/input/fileupload.htmlnew file mode 100644index 0000000000..55fd7c5006--- /dev/null+++ b/test/assets/input/fileupload.html@@ -0,0 +1,9 @@+<!DOCTYPE html>+<html>+ <head>+ <title>File upload test</title>+ </head>+ <body>+ <input type="file">+ </body>+</html>\ No newline at end of filediff --git a/test/assets/input/keyboard.html b/test/assets/input/keyboard.htmlnew file mode 100644index 0000000000..fd962c7518--- /dev/null+++ b/test/assets/input/keyboard.html@@ -0,0 +1,42 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Keyboard test</title>+ </head>+ <body>+ <textarea></textarea>+ <script>+ window.result = "";+ let textarea = document.querySelector('textarea');+ textarea.focus();+ textarea.addEventListener('keydown', event => {+ log('Keydown:', event.key, event.code, event.which, modifiers(event));+ });+ textarea.addEventListener('keypress', event => {+ log('Keypress:', event.key, event.code, event.which, event.charCode, modifiers(event));+ });+ textarea.addEventListener('keyup', event => {+ log('Keyup:', event.key, event.code, event.which, modifiers(event));+ });+ function modifiers(event) {+ let m = [];+ if (event.altKey)+ m.push('Alt')+ if (event.ctrlKey)+ m.push('Control');+ if (event.shiftKey)+ m.push('Shift')+ return '[' + m.join(' ') + ']';+ }+ function log(...args) {+ console.log.apply(console, args);+ result += args.join(' ') + '\n';+ }+ function getResult() {+ let temp = result.trim();+ result = "";+ return temp;+ }+ </script>+ </body>+</html>\ No newline at end of filediff --git a/test/assets/input/mouse-helper.js b/test/assets/input/mouse-helper.jsnew file mode 100644index 0000000000..3c4d57033c--- /dev/null+++ b/test/assets/input/mouse-helper.js@@ -0,0 +1,62 @@+// This injects a box into the page that moves with the mouse;+// Useful for debugging+(function(){+ const box = document.createElement('div');+ box.classList.add('mouse-helper');+ const styleElement = document.createElement('style');+ styleElement.innerHTML = `+ .mouse-helper {+ pointer-events: none;+ position: absolute;+ top: 0;+ left: 0;+ width: 20px;+ height: 20px;+ background: rgba(0,0,0,.4);+ border: 1px solid white;+ border-radius: 10px;+ margin-left: -10px;+ margin-top: -10px;+ transition: background .2s, border-radius .2s, border-color .2s;+ }+ .mouse-helper.button-1 {+ transition: none;+ background: rgba(0,0,0,0.9);+ }+ .mouse-helper.button-2 {+ transition: none;+ border-color: rgba(0,0,255,0.9);+ }+ .mouse-helper.button-3 {+ transition: none;+ border-radius: 4px;+ }+ .mouse-helper.button-4 {+ transition: none;+ border-color: rgba(255,0,0,0.9);+ }+ .mouse-helper.button-5 {+ transition: none;+ border-color: rgba(0,255,0,0.9);+ }+ `;+ document.head.appendChild(styleElement);+ document.body.appendChild(box);+ document.addEventListener('mousemove', event => {+ box.style.left = event.pageX + 'px';+ box.style.top = event.pageY + 'px';+ updateButtons(event.buttons);+ }, true);+ document.addEventListener('mousedown', event => {+ updateButtons(event.buttons);+ box.classList.add('button-' + event.which);+ }, true);+ document.addEventListener('mouseup', event => {+ updateButtons(event.buttons);+ box.classList.remove('button-' + event.which);+ }, true);+ function updateButtons(buttons) {+ for (let i = 0; i < 5; i++)+ box.classList.toggle('button-' + i, buttons & (1 << i));+ }+})();diff --git a/test/assets/input/rotatedButton.html b/test/assets/input/rotatedButton.htmlnew file mode 100644index 0000000000..1bce66cf5e--- /dev/null+++ b/test/assets/input/rotatedButton.html@@ -0,0 +1,21 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Rotated button test</title>+ </head>+ <body>+ <script src="mouse-helper.js"></script>+ <button onclick="clicked();">Click target</button>+ <style>+ button {+ transform: rotateY(180deg);+ }+ </style>+ <script>+ window.result = 'Was not clicked';+ function clicked() {+ result = 'Clicked';+ }+ </script>+ </body>+</html>diff --git a/test/assets/input/scrollable.html b/test/assets/input/scrollable.htmlnew file mode 100644index 0000000000..885d3739d5--- /dev/null+++ b/test/assets/input/scrollable.html@@ -0,0 +1,23 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Scrollable test</title>+ </head>+ <body>+ <script src='mouse-helper.js'></script>+ <script>+ for (let i = 0; i < 100; i++) {+ let button = document.createElement('button');+ button.textContent = i + ': not clicked';+ button.id = 'button-' + i;+ button.onclick = () => button.textContent = 'clicked';+ button.oncontextmenu = event => {+ event.preventDefault();+ button.textContent = 'context menu';+ }+ document.body.appendChild(button);+ document.body.appendChild(document.createElement('br'));+ }+ </script>+ </body>+</html>\ No newline at end of filediff --git a/test/assets/input/select.html b/test/assets/input/select.htmlnew file mode 100644index 0000000000..879a537a76--- /dev/null+++ b/test/assets/input/select.html@@ -0,0 +1,69 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Selection Test</title>+ </head>+ <body>+ <select>+ <option value="black">Black</option>+ <option value="blue">Blue</option>+ <option value="brown">Brown</option>+ <option value="cyan">Cyan</option>+ <option value="gray">Gray</option>+ <option value="green">Green</option>+ <option value="indigo">Indigo</option>+ <option value="magenta">Magenta</option>+ <option value="orange">Orange</option>+ <option value="pink">Pink</option>+ <option value="purple">Purple</option>+ <option value="red">Red</option>+ <option value="violet">Violet</option>+ <option value="white">White</option>+ <option value="yellow">Yellow</option>+ </select>+ <script>+ window.result = {+ onInput: null,+ onChange: null,+ onBubblingChange: null,+ onBubblingInput: null,+ };++ let select = document.querySelector('select');++ function makeEmpty() {+ for (let i = select.options.length - 1; i >= 0; --i) {+ select.remove(i);+ }+ }++ function makeMultiple() {+ select.setAttribute('multiple', true);+ }++ select.addEventListener('input', () => {+ result.onInput = Array.from(select.querySelectorAll('option:checked')).map((option) => {+ return option.value;+ });+ }, false);++ select.addEventListener('change', () => {+ result.onChange = Array.from(select.querySelectorAll('option:checked')).map((option) => {+ return option.value;+ });+ }, false);++ document.body.addEventListener('input', () => {+ result.onBubblingInput = Array.from(select.querySelectorAll('option:checked')).map((option) => {+ return option.value;+ });+ }, false);++ document.body.addEventListener('change', () => {+ result.onBubblingChange = Array.from(select.querySelectorAll('option:checked')).map((option) => {+ return option.value;+ });+ }, false);+ </script>+ </body>+</html>diff --git a/test/assets/input/textarea.html b/test/assets/input/textarea.htmlnew file mode 100644index 0000000000..f71a0054b5--- /dev/null+++ b/test/assets/input/textarea.html@@ -0,0 +1,19 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Textarea test</title>+ </head>+ <body>+ <textarea></textarea>+ <input></input>+ <div contenteditable="true"></div>+ <script src='mouse-helper.js'></script>+ <script>+ window.result = '';+ let textarea = document.querySelector('textarea');+ textarea.addEventListener('input', () => result = textarea.value, false);+ let input = document.querySelector('input');+ input.addEventListener('input', () => result = input.value, false);+ </script>+ </body>+</html>\ No newline at end of filediff --git a/test/assets/input/touches.html b/test/assets/input/touches.htmlnew file mode 100644index 0000000000..4392cfacbd--- /dev/null+++ b/test/assets/input/touches.html@@ -0,0 +1,35 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Touch test</title>+ </head>+ <body>+ <script src="mouse-helper.js"></script>+ <button onclick="clicked();">Click target</button>+ <script>+ window.result = [];+ const button = document.querySelector('button');+ button.style.height = '200px';+ button.style.width = '200px';+ button.focus();+ button.addEventListener('touchstart', event => {+ log('Touchstart:', ...Array.from(event.changedTouches).map(touch => touch.identifier));+ });+ button.addEventListener('touchend', event => {+ log('Touchend:', ...Array.from(event.changedTouches).map(touch => touch.identifier));+ });+ button.addEventListener('touchmove', event => {+ log('Touchmove:', ...Array.from(event.changedTouches).map(touch => touch.identifier));+ });+ function log(...args) {+ console.log.apply(console, args);+ result.push(args.join(' '));+ }+ function getResult() {+ let temp = result;+ result = [];+ return temp;+ }+ </script>+ </body>+</html>\ No newline at end of filediff --git a/test/assets/jscoverage/eval.html b/test/assets/jscoverage/eval.htmlnew file mode 100644index 0000000000..838ae28763--- /dev/null+++ b/test/assets/jscoverage/eval.html@@ -0,0 +1 @@+<script>eval('console.log("foo")')</script>diff --git a/test/assets/jscoverage/involved.html b/test/assets/jscoverage/involved.htmlnew file mode 100644index 0000000000..889c86bed5--- /dev/null+++ b/test/assets/jscoverage/involved.html@@ -0,0 +1,15 @@+<script>+function foo() {+ if (1 > 2)+ console.log(1);+ if (1 < 2)+ console.log(2);+ let x = 1 > 2 ? 'foo' : 'bar';+ let y = 1 < 2 ? 'foo' : 'bar';+ let z = () => {};+ let q = () => {};+ q();+}++foo();+</script>diff --git a/test/assets/jscoverage/multiple.html b/test/assets/jscoverage/multiple.htmlnew file mode 100644index 0000000000..bdef59885b--- /dev/null+++ b/test/assets/jscoverage/multiple.html@@ -0,0 +1,2 @@+<script src='script1.js'></script>+<script src='script2.js'></script>diff --git a/test/assets/jscoverage/ranges.html b/test/assets/jscoverage/ranges.htmlnew file mode 100644index 0000000000..a537a7da6a--- /dev/null+++ b/test/assets/jscoverage/ranges.html@@ -0,0 +1,2 @@+<script>+function unused(){}console.log('used!');</script>diff --git a/test/assets/jscoverage/script1.js b/test/assets/jscoverage/script1.jsnew file mode 100644index 0000000000..3bd241b50e--- /dev/null+++ b/test/assets/jscoverage/script1.js@@ -0,0 +1 @@+console.log(3);diff --git a/test/assets/jscoverage/script2.js b/test/assets/jscoverage/script2.jsnew file mode 100644index 0000000000..3bd241b50e--- /dev/null+++ b/test/assets/jscoverage/script2.js@@ -0,0 +1 @@+console.log(3);diff --git a/test/assets/jscoverage/simple.html b/test/assets/jscoverage/simple.htmlnew file mode 100644index 0000000000..49eeeea6ae--- /dev/null+++ b/test/assets/jscoverage/simple.html@@ -0,0 +1,2 @@+<script>+function foo() {function bar() { } console.log(1); } foo(); </script>diff --git a/test/assets/jscoverage/sourceurl.html b/test/assets/jscoverage/sourceurl.htmlnew file mode 100644index 0000000000..e477750320--- /dev/null+++ b/test/assets/jscoverage/sourceurl.html@@ -0,0 +1,4 @@+<script>+console.log(1);+//# sourceURL=nicename.js+</script>diff --git a/test/assets/jscoverage/unused.html b/test/assets/jscoverage/unused.htmlnew file mode 100644index 0000000000..59c4a5a70b--- /dev/null+++ b/test/assets/jscoverage/unused.html@@ -0,0 +1 @@+<script>function foo() { }</script>diff --git a/test/assets/mobile.html b/test/assets/mobile.htmlnew file mode 100644index 0000000000..8e94b2fe29--- /dev/null+++ b/test/assets/mobile.html@@ -0,0 +1 @@+<meta name = "viewport" content = "initial-scale = 1, user-scalable = no">diff --git a/test/assets/modernizr.js b/test/assets/modernizr.jsnew file mode 100644index 0000000000..7991a4ec40--- /dev/null+++ b/test/assets/modernizr.js@@ -0,0 +1,3 @@+/*! modernizr 3.5.0 (Custom Build) | MIT *+* https://modernizr.com/download/?-touchevents-setclasses !*/+!function(e,n,t){function o(e,n){return typeof e===n}function s(){var e,n,t,s,a,i,r;for(var l in c)if(c.hasOwnProperty(l)){if(e=[],n=c[l],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(t=0;t<n.options.aliases.length;t++)e.push(n.options.aliases[t].toLowerCase());for(s=o(n.fn,"function")?n.fn():n.fn,a=0;a<e.length;a++)i=e[a],r=i.split("."),1===r.length?Modernizr[r[0]]=s:(!Modernizr[r[0]]||Modernizr[r[0]]instanceof Boolean||(Modernizr[r[0]]=new Boolean(Modernizr[r[0]])),Modernizr[r[0]][r[1]]=s),f.push((s?"":"no-")+r.join("-"))}}function a(e){var n=u.className,t=Modernizr._config.classPrefix||"";if(p&&(n=n.baseVal),Modernizr._config.enableJSClass){var o=new RegExp("(^|\\s)"+t+"no-js(\\s|$)");n=n.replace(o,"$1"+t+"js$2")}Modernizr._config.enableClasses&&(n+=" "+t+e.join(" "+t),p?u.className.baseVal=n:u.className=n)}function i(){return"function"!=typeof n.createElement?n.createElement(arguments[0]):p?n.createElementNS.call(n,"http://www.w3.org/2000/svg",arguments[0]):n.createElement.apply(n,arguments)}function r(){var e=n.body;return e||(e=i(p?"svg":"body"),e.fake=!0),e}function l(e,t,o,s){var a,l,f,c,d="modernizr",p=i("div"),h=r();if(parseInt(o,10))for(;o--;)f=i("div"),f.id=s?s[o]:d+(o+1),p.appendChild(f);return a=i("style"),a.type="text/css",a.id="s"+d,(h.fake?h:p).appendChild(a),h.appendChild(p),a.styleSheet?a.styleSheet.cssText=e:a.appendChild(n.createTextNode(e)),p.id=d,h.fake&&(h.style.background="",h.style.overflow="hidden",c=u.style.overflow,u.style.overflow="hidden",u.appendChild(h)),l=t(p,e),h.fake?(h.parentNode.removeChild(h),u.style.overflow=c,u.offsetHeight):p.parentNode.removeChild(p),!!l}var f=[],c=[],d={_version:"3.5.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,n){var t=this;setTimeout(function(){n(t[e])},0)},addTest:function(e,n,t){c.push({name:e,fn:n,options:t})},addAsyncTest:function(e){c.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=d,Modernizr=new Modernizr;var u=n.documentElement,p="svg"===u.nodeName.toLowerCase(),h=d._config.usePrefixes?" -webkit- -moz- -o- -ms- ".split(" "):["",""];d._prefixes=h;var m=d.testStyles=l;Modernizr.addTest("touchevents",function(){var t;if("ontouchstart"in e||e.DocumentTouch&&n instanceof DocumentTouch)t=!0;else{var o=["@media (",h.join("touch-enabled),("),"heartz",")","{#modernizr{top:9px;position:absolute}}"].join("");m(o,function(e){t=9===e.offsetTop})}return t}),s(),a(f),delete d.addTest,delete d.addAsyncTest;for(var v=0;v<Modernizr._q.length;v++)Modernizr._q[v]();e.Modernizr=Modernizr}(window,document);diff --git a/test/assets/networkidle.html b/test/assets/networkidle.htmlnew file mode 100644index 0000000000..910ae1736d--- /dev/null+++ b/test/assets/networkidle.html@@ -0,0 +1,19 @@+<script>+ async function sleep(delay) {+ return new Promise(resolve => setTimeout(resolve, delay));+ }++ async function main() {+ const roundOne = Promise.all([+ fetch('fetch-request-a.js'),+ fetch('fetch-request-b.js'),+ fetch('fetch-request-c.js'),+ ]);++ await roundOne;+ await sleep(50);+ await fetch('fetch-request-d.js');+ }++ main();+</script>diff --git a/test/assets/offscreenbuttons.html b/test/assets/offscreenbuttons.htmlnew file mode 100644index 0000000000..d45e2a4129--- /dev/null+++ b/test/assets/offscreenbuttons.html@@ -0,0 +1,36 @@+<style>+ button {+ position: absolute;+ width: 100px;+ height: 20px;+ }++ #btn0 { right: 0px; top: 0; }+ #btn1 { right: -10px; top: 25px; }+ #btn2 { right: -20px; top: 50px; }+ #btn3 { right: -30px; top: 75px; }+ #btn4 { right: -40px; top: 100px; }+ #btn5 { right: -50px; top: 125px; }+ #btn6 { right: -60px; top: 150px; }+ #btn7 { right: -70px; top: 175px; }+ #btn8 { right: -80px; top: 200px; }+ #btn9 { right: -90px; top: 225px; }+ #btn10 { right: -100px; top: 250px; }+</style>+<button id=btn0>0</button>+<button id=btn1>1</button>+<button id=btn2>2</button>+<button id=btn3>3</button>+<button id=btn4>4</button>+<button id=btn5>5</button>+<button id=btn6>6</button>+<button id=btn7>7</button>+<button id=btn8>8</button>+<button id=btn9>9</button>+<button id=btn10>10</button>+<script>+window.addEventListener('DOMContentLoaded', () => {+ for (const button of Array.from(document.querySelectorAll('button')))+ button.addEventListener('click', () => console.log('button #' + button.textContent + ' clicked'), false);+}, false);+</script>diff --git a/test/assets/one-style.css b/test/assets/one-style.cssnew file mode 100644index 0000000000..7b26410d8a--- /dev/null+++ b/test/assets/one-style.css@@ -0,0 +1,3 @@+body {+ background-color: pink;+}diff --git a/test/assets/one-style.html b/test/assets/one-style.htmlnew file mode 100644index 0000000000..4760f2b9f7--- /dev/null+++ b/test/assets/one-style.html@@ -0,0 +1,2 @@+<link rel='stylesheet' href='./one-style.css'>+<div>hello, world!</div>diff --git a/test/assets/playground.html b/test/assets/playground.htmlnew file mode 100644index 0000000000..828cfb1c70--- /dev/null+++ b/test/assets/playground.html@@ -0,0 +1,15 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Playground</title>+ </head>+ <body>+ <button>A button</button>+ <textarea>A text area</textarea>+ <div id="first">First div</div>+ <div id="second">+ Second div+ <span class="inner">Inner span</span>+ </div>+ </body>+</html>\ No newline at end of filediff --git a/test/assets/popup/popup.html b/test/assets/popup/popup.htmlnew file mode 100644index 0000000000..b855162c25--- /dev/null+++ b/test/assets/popup/popup.html@@ -0,0 +1,9 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Popup</title>+ </head>+ <body>+ I am a popup+ </body>+</html>diff --git a/test/assets/popup/window-open.html b/test/assets/popup/window-open.htmlnew file mode 100644index 0000000000..d138be1d22--- /dev/null+++ b/test/assets/popup/window-open.html@@ -0,0 +1,11 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Popup test</title>+ </head>+ <body>+ <script>+ window.open('./popup.html');+ </script>+ </body>+</html>diff --git a/test/assets/pptr.png b/test/assets/pptr.pngnew file mode 100644index 0000000000..65d87c68e6Binary files /dev/null and b/test/assets/pptr.png differdiff --git a/test/assets/resetcss.html b/test/assets/resetcss.htmlnew file mode 100644index 0000000000..e4e04b1f8a--- /dev/null+++ b/test/assets/resetcss.html@@ -0,0 +1,50 @@+<style>+/* http://meyerweb.com/eric/tools/css/reset/+ v2.0 | 20110126+ License: none (public domain)+*/++html, body, div, span, applet, object, iframe,+h1, h2, h3, h4, h5, h6, p, blockquote, pre,+a, abbr, acronym, address, big, cite, code,+del, dfn, em, img, ins, kbd, q, s, samp,+small, strike, strong, sub, sup, tt, var,+b, u, i, center,+dl, dt, dd, ol, ul, li,+fieldset, form, label, legend,+table, caption, tbody, tfoot, thead, tr, th, td,+article, aside, canvas, details, embed,+figure, figcaption, footer, header, hgroup,+menu, nav, output, ruby, section, summary,+time, mark, audio, video {+ margin: 0;+ padding: 0;+ border: 0;+ font-size: 100%;+ font: inherit;+ vertical-align: baseline;+}+/* HTML5 display-role reset for older browsers */+article, aside, details, figcaption, figure,+footer, header, hgroup, menu, nav, section {+ display: block;+}+body {+ line-height: 1;+}+ol, ul {+ list-style: none;+}+blockquote, q {+ quotes: none;+}+blockquote:before, blockquote:after,+q:before, q:after {+ content: '';+ content: none;+}+table {+ border-collapse: collapse;+ border-spacing: 0;+}+</style>diff --git a/test/assets/self-request.html b/test/assets/self-request.htmlnew file mode 100644index 0000000000..88aff620ff--- /dev/null+++ b/test/assets/self-request.html@@ -0,0 +1,5 @@+<script>+var req = new XMLHttpRequest();+req.open('GET', '/self-request.html');+req.send(null);+</script>diff --git a/test/assets/serviceworkers/empty/sw.html b/test/assets/serviceworkers/empty/sw.htmlnew file mode 100644index 0000000000..bef85d985b--- /dev/null+++ b/test/assets/serviceworkers/empty/sw.html@@ -0,0 +1,3 @@+<script>+ window.registrationPromise = navigator.serviceWorker.register('sw.js');+</script>diff --git a/test/assets/serviceworkers/empty/sw.js b/test/assets/serviceworkers/empty/sw.jsnew file mode 100644index 0000000000..e69de29bb2diff --git a/test/assets/serviceworkers/fetch/style.css b/test/assets/serviceworkers/fetch/style.cssnew file mode 100644index 0000000000..7b26410d8a--- /dev/null+++ b/test/assets/serviceworkers/fetch/style.css@@ -0,0 +1,3 @@+body {+ background-color: pink;+}diff --git a/test/assets/serviceworkers/fetch/sw.html b/test/assets/serviceworkers/fetch/sw.htmlnew file mode 100644index 0000000000..a9d28acb09--- /dev/null+++ b/test/assets/serviceworkers/fetch/sw.html@@ -0,0 +1,5 @@+<link rel="stylesheet" href="./style.css">+<script>+ window.registrationPromise = navigator.serviceWorker.register('sw.js');+ window.activationPromise = new Promise(resolve => navigator.serviceWorker.oncontrollerchange = resolve);+</script>diff --git a/test/assets/serviceworkers/fetch/sw.js b/test/assets/serviceworkers/fetch/sw.jsnew file mode 100644index 0000000000..d44c7eab94--- /dev/null+++ b/test/assets/serviceworkers/fetch/sw.js@@ -0,0 +1,7 @@+self.addEventListener('fetch', event => {+ event.respondWith(fetch(event.request));+});++self.addEventListener('activate', event => {+ event.waitUntil(clients.claim());+});diff --git a/test/assets/shadow.html b/test/assets/shadow.htmlnew file mode 100644index 0000000000..7242e673b5--- /dev/null+++ b/test/assets/shadow.html@@ -0,0 +1,17 @@+<script>++let h1 = null;+let button = null;+let clicked = false;++window.addEventListener('DOMContentLoaded', () => {+ const shadowRoot = document.body.attachShadow({mode: 'open'});+ h1 = document.createElement('h1');+ h1.textContent = 'Hellow Shadow DOM v1';+ button = document.createElement('button');+ button.textContent = 'Click';+ button.addEventListener('click', () => clicked = true);+ shadowRoot.appendChild(h1);+ shadowRoot.appendChild(button);+});+</script>diff --git a/test/assets/simple-extension/content-script.js b/test/assets/simple-extension/content-script.jsnew file mode 100644index 0000000000..965f99fd3d--- /dev/null+++ b/test/assets/simple-extension/content-script.js@@ -0,0 +1,3 @@+console.log('hey from the content-script');+self.thisIsTheContentScript = true;+diff --git a/test/assets/simple-extension/index.js b/test/assets/simple-extension/index.jsnew file mode 100644index 0000000000..a0bb3f4eae--- /dev/null+++ b/test/assets/simple-extension/index.js@@ -0,0 +1,2 @@+// Mock script for background extension+window.MAGIC = 42;diff --git a/test/assets/simple-extension/manifest.json b/test/assets/simple-extension/manifest.jsonnew file mode 100644index 0000000000..da2cd082ed--- /dev/null+++ b/test/assets/simple-extension/manifest.json@@ -0,0 +1,14 @@+{+ "name": "Simple extension",+ "version": "0.1",+ "background": {+ "scripts": ["index.js"]+ },+ "content_scripts": [{+ "matches": ["<all_urls>"],+ "css": [],+ "js": ["content-script.js"]+ }],+ "permissions": ["background", "activeTab"],+ "manifest_version": 2+}diff --git a/test/assets/simple.json b/test/assets/simple.jsonnew file mode 100644index 0000000000..6d95903051--- /dev/null+++ b/test/assets/simple.json@@ -0,0 +1 @@+{"foo": "bar"}diff --git a/test/assets/tamperable.html b/test/assets/tamperable.htmlnew file mode 100644index 0000000000..d027e97038--- /dev/null+++ b/test/assets/tamperable.html@@ -0,0 +1,3 @@+<script>+ window.result = window.injected;+</script>\ No newline at end of filediff --git a/test/assets/title.html b/test/assets/title.htmlnew file mode 100644index 0000000000..88a86ce412--- /dev/null+++ b/test/assets/title.html@@ -0,0 +1 @@+<title>Woof-Woof</title>diff --git a/test/assets/worker/worker.html b/test/assets/worker/worker.htmlnew file mode 100644index 0000000000..7de2d9fd9e--- /dev/null+++ b/test/assets/worker/worker.html@@ -0,0 +1,14 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Worker test</title>+ </head>+ <body>+ <script>+ var worker = new Worker('worker.js');+ worker.onmessage = function(message) {+ console.log(message.data);+ };+ </script>+ </body>+</html>\ No newline at end of filediff --git a/test/assets/worker/worker.js b/test/assets/worker/worker.jsnew file mode 100644index 0000000000..d0d229a192--- /dev/null+++ b/test/assets/worker/worker.js@@ -0,0 +1,16 @@+console.log('hello from the worker');++function workerFunction() {+ return 'worker function result';+}++self.addEventListener('message', event => {+ console.log('got this data: ' + event.data);+});++(async function() {+ while (true) {+ self.postMessage(workerFunction.toString());+ await new Promise(x => setTimeout(x, 100));+ }+})();\ No newline at end of filediff --git a/test/assets/wrappedlink.html b/test/assets/wrappedlink.htmlnew file mode 100644index 0000000000..429b6e9156--- /dev/null+++ b/test/assets/wrappedlink.html@@ -0,0 +1,32 @@+<style>+:root {+ font-family: monospace;+}++body {+ display: flex;+ align-items: center;+ justify-content: center;+}++div {+ width: 10ch;+ word-wrap: break-word;+ border: 1px solid blue;+ transform: rotate(33deg);+ line-height: 8ch;+ padding: 2ch;+}++a {+ margin-left: 7ch;+}+</style>+<div>+ <a href='#clicked'>123321</a>+</div>+<script>+ document.querySelector('a').addEventListener('click', () => {+ window.__clicked = true;+ });+</script>diff --git a/test/browser.spec.js b/test/browser.spec.jsnew file mode 100644index 0000000000..75d9f0265b--- /dev/null+++ b/test/browser.spec.js@@ -0,0 +1,73 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, headless, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe.skip(WEBKIT)('Browser.version', function() {+ it('should return whether we are in headless', async({browser}) => {+ const version = await browser.version();+ expect(version.length).toBeGreaterThan(0);+ if (CHROME || WEBKIT)+ expect(version.startsWith('Headless')).toBe(headless);+ else+ expect(version.startsWith('Firefox/')).toBe(true);+ });+ });++ describe.skip(WEBKIT)('Browser.userAgent', function() {+ it('should include WebKit', async({browser}) => {+ const userAgent = await browser.userAgent();+ expect(userAgent.length).toBeGreaterThan(0);+ if (CHROME || WEBKIT)+ expect(userAgent).toContain('WebKit');+ else+ expect(userAgent).toContain('Gecko');+ });+ });++ describe.skip(WEBKIT)('Browser.target', function() {+ it('should return browser target', async({browser}) => {+ const target = browser.target();+ expect(target.type()).toBe('browser');+ });+ });++ describe('Browser.process', function() {+ it('should return child_process instance', async function({browser}) {+ const process = await browser.process();+ expect(process.pid).toBeGreaterThan(0);+ });+ it.skip(WEBKIT)('should not return child_process for remote browser', async function({browser}) {+ const browserWSEndpoint = browser.wsEndpoint();+ const remoteBrowser = await playwright.connect({browserWSEndpoint});+ expect(remoteBrowser.process()).toBe(null);+ remoteBrowser.disconnect();+ });+ });++ describe.skip(WEBKIT)('Browser.isConnected', () => {+ it('should set the browser connected state', async({browser}) => {+ const browserWSEndpoint = browser.wsEndpoint();+ const newBrowser = await playwright.connect({browserWSEndpoint});+ expect(newBrowser.isConnected()).toBe(true);+ newBrowser.disconnect();+ expect(newBrowser.isConnected()).toBe(false);+ });+ });+};diff --git a/test/browsercontext.spec.js b/test/browsercontext.spec.jsnew file mode 100644index 0000000000..4c2cd071d9--- /dev/null+++ b/test/browsercontext.spec.js@@ -0,0 +1,156 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const utils = require('./utils');++module.exports.addTests = function({testRunner, expect, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('BrowserContext', function() {+ it('should have default context', async function({browser, server}) {+ expect(browser.browserContexts().length).toBe(1);+ const defaultContext = browser.browserContexts()[0];+ expect(defaultContext.isIncognito()).toBe(false);+ let error = null;+ await defaultContext.close().catch(e => error = e);+ expect(browser.defaultBrowserContext()).toBe(defaultContext);+ expect(error.message).toContain('cannot be closed');+ });+ it('should create new incognito context', async function({browser, server}) {+ expect(browser.browserContexts().length).toBe(1);+ const context = await browser.createIncognitoBrowserContext();+ expect(context.isIncognito()).toBe(true);+ expect(browser.browserContexts().length).toBe(2);+ expect(browser.browserContexts().indexOf(context) !== -1).toBe(true);+ await context.close();+ expect(browser.browserContexts().length).toBe(1);+ });+ it.skip(WEBKIT)('should close all belonging targets once closing context', async function({browser, server}) {+ expect((await browser.pages()).length).toBe(1);++ const context = await browser.createIncognitoBrowserContext();+ await context.newPage();+ expect((await browser.pages()).length).toBe(2);+ expect((await context.pages()).length).toBe(1);++ await context.close();+ expect((await browser.pages()).length).toBe(1);+ });+ it('window.open should use parent tab context', async function({browser, server}) {+ const context = await browser.createIncognitoBrowserContext();+ const page = await context.newPage();+ await page.goto(server.EMPTY_PAGE);+ const [popupTarget] = await Promise.all([+ utils.waitEvent(browser, 'targetcreated'),+ page.evaluate(url => window.open(url), server.EMPTY_PAGE)+ ]);+ expect(popupTarget.browserContext()).toBe(context);+ await context.close();+ });+ it.skip(WEBKIT)('should fire target events', async function({browser, server}) {+ const context = await browser.createIncognitoBrowserContext();+ const events = [];+ context.on('targetcreated', target => events.push('CREATED: ' + target.url()));+ context.on('targetchanged', target => events.push('CHANGED: ' + target.url()));+ context.on('targetdestroyed', target => events.push('DESTROYED: ' + target.url()));+ const page = await context.newPage();+ await page.goto(server.EMPTY_PAGE);+ await page.close();+ expect(events).toEqual([+ 'CREATED: about:blank',+ `CHANGED: ${server.EMPTY_PAGE}`,+ `DESTROYED: ${server.EMPTY_PAGE}`+ ]);+ await context.close();+ });+ it('should wait for a target', async function({browser, server}) {+ const context = await browser.createIncognitoBrowserContext();+ let resolved = false;+ const targetPromise = context.waitForTarget(target => target.url() === server.EMPTY_PAGE);+ targetPromise.then(() => resolved = true);+ const page = await context.newPage();+ expect(resolved).toBe(false);+ await page.goto(server.EMPTY_PAGE);+ const target = await targetPromise;+ expect(await target.page()).toBe(page);+ await context.close();+ });+ it('should timeout waiting for a non-existent target', async function({browser, server}) {+ const context = await browser.createIncognitoBrowserContext();+ const error = await context.waitForTarget(target => target.url() === server.EMPTY_PAGE, {timeout: 1}).catch(e => e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ await context.close();+ });+ it('should isolate localStorage and cookies', async function({browser, server}) {+ // Create two incognito contexts.+ const context1 = await browser.createIncognitoBrowserContext();+ const context2 = await browser.createIncognitoBrowserContext();+ expect(context1.targets().length).toBe(0);+ expect(context2.targets().length).toBe(0);++ // Create a page in first incognito context.+ const page1 = await context1.newPage();+ await page1.goto(server.EMPTY_PAGE);+ await page1.evaluate(() => {+ localStorage.setItem('name', 'page1');+ document.cookie = 'name=page1';+ });++ expect(context1.targets().length).toBe(1);+ expect(context2.targets().length).toBe(0);++ // Create a page in second incognito context.+ const page2 = await context2.newPage();+ await page2.goto(server.EMPTY_PAGE);+ await page2.evaluate(() => {+ localStorage.setItem('name', 'page2');+ document.cookie = 'name=page2';+ });++ expect(context1.targets().length).toBe(1);+ expect(context1.targets()[0]).toBe(page1.target());+ expect(context2.targets().length).toBe(1);+ expect(context2.targets()[0]).toBe(page2.target());++ // Make sure pages don't share localstorage or cookies.+ expect(await page1.evaluate(() => localStorage.getItem('name'))).toBe('page1');+ expect(await page1.evaluate(() => document.cookie)).toBe('name=page1');+ expect(await page2.evaluate(() => localStorage.getItem('name'))).toBe('page2');+ expect(await page2.evaluate(() => document.cookie)).toBe('name=page2');++ // Cleanup contexts.+ await Promise.all([+ context1.close(),+ context2.close()+ ]);+ expect(browser.browserContexts().length).toBe(1);+ });+ it.skip(WEBKIT)('should work across sessions', async function({browser, server}) {+ expect(browser.browserContexts().length).toBe(1);+ const context = await browser.createIncognitoBrowserContext();+ expect(browser.browserContexts().length).toBe(2);+ const remoteBrowser = await playwright.connect({+ browserWSEndpoint: browser.wsEndpoint()+ });+ const contexts = remoteBrowser.browserContexts();+ expect(contexts.length).toBe(2);+ remoteBrowser.disconnect();+ await context.close();+ });+ });+};diff --git a/test/chromiumonly.spec.js b/test/chromiumonly.spec.jsnew file mode 100644index 0000000000..8d80b4a097--- /dev/null+++ b/test/chromiumonly.spec.js@@ -0,0 +1,144 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addLauncherTests = function({testRunner, expect, defaultBrowserOptions, playwright}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Chromium-Specific Launcher tests', function() {+ describe('Playwright.launch |browserURL| option', function() {+ it('should be able to connect using browserUrl, with and without trailing slash', async({server}) => {+ const originalBrowser = await playwright.launch(Object.assign({}, defaultBrowserOptions, {+ args: ['--remote-debugging-port=21222']+ }));+ const browserURL = 'http://127.0.0.1:21222';++ const browser1 = await playwright.connect({browserURL});+ const page1 = await browser1.newPage();+ expect(await page1.evaluate(() => 7 * 8)).toBe(56);+ browser1.disconnect();++ const browser2 = await playwright.connect({browserURL: browserURL + '/'});+ const page2 = await browser2.newPage();+ expect(await page2.evaluate(() => 8 * 7)).toBe(56);+ browser2.disconnect();+ originalBrowser.close();+ });+ it('should throw when using both browserWSEndpoint and browserURL', async({server}) => {+ const originalBrowser = await playwright.launch(Object.assign({}, defaultBrowserOptions, {+ args: ['--remote-debugging-port=21222']+ }));+ const browserURL = 'http://127.0.0.1:21222';++ let error = null;+ await playwright.connect({browserURL, browserWSEndpoint: originalBrowser.wsEndpoint()}).catch(e => error = e);+ expect(error.message).toContain('Exactly one of browserWSEndpoint, browserURL or transport');++ originalBrowser.close();+ });+ it('should throw when trying to connect to non-existing browser', async({server}) => {+ const originalBrowser = await playwright.launch(Object.assign({}, defaultBrowserOptions, {+ args: ['--remote-debugging-port=21222']+ }));+ const browserURL = 'http://127.0.0.1:32333';++ let error = null;+ await playwright.connect({browserURL}).catch(e => error = e);+ expect(error.message).toContain('Failed to fetch browser webSocket url from');+ originalBrowser.close();+ });+ });++ describe('Playwright.launch |pipe| option', function() {+ it('should support the pipe option', async() => {+ const options = Object.assign({pipe: true}, defaultBrowserOptions);+ const browser = await playwright.launch(options);+ expect((await browser.pages()).length).toBe(1);+ expect(browser.wsEndpoint()).toBe('');+ const page = await browser.newPage();+ expect(await page.evaluate('11 * 11')).toBe(121);+ await page.close();+ await browser.close();+ });+ it('should support the pipe argument', async() => {+ const options = Object.assign({}, defaultBrowserOptions);+ options.args = ['--remote-debugging-pipe'].concat(options.args || []);+ const browser = await playwright.launch(options);+ expect(browser.wsEndpoint()).toBe('');+ const page = await browser.newPage();+ expect(await page.evaluate('11 * 11')).toBe(121);+ await page.close();+ await browser.close();+ });+ it('should fire "disconnected" when closing with pipe', async() => {+ const options = Object.assign({pipe: true}, defaultBrowserOptions);+ const browser = await playwright.launch(options);+ const disconnectedEventPromise = new Promise(resolve => browser.once('disconnected', resolve));+ // Emulate user exiting browser.+ browser.process().kill();+ await disconnectedEventPromise;+ });+ });++ describe('Page.waitForFileChooser', () => {+ it('should fail gracefully when trying to work with filechoosers within multiple connections', async() => {+ // 1. Launch a browser and connect to all pages.+ const originalBrowser = await playwright.launch(defaultBrowserOptions);+ await originalBrowser.pages();+ // 2. Connect a remote browser and connect to first page.+ const remoteBrowser = await playwright.connect({browserWSEndpoint: originalBrowser.wsEndpoint()});+ const [page] = await remoteBrowser.pages();+ // 3. Make sure |page.waitForFileChooser()| does not work with multiclient.+ let error = null;+ await page.waitForFileChooser().catch(e => error = e);+ expect(error.message).toBe('File chooser handling does not work with multiple connections to the same page');+ originalBrowser.close();+ });++ });+ });+};++module.exports.addPageTests = function({testRunner, expect}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Chromium-Specific Page Tests', function() {+ it('Page.setRequestInterception should work with intervention headers', async({server, page}) => {+ server.setRoute('/intervention', (req, res) => res.end(`+ <script>+ document.write('<script src="${server.CROSS_PROCESS_PREFIX}/intervention.js">' + '</scr' + 'ipt>');+ </script>+ `));+ server.setRedirect('/intervention.js', '/redirect.js');+ let serverRequest = null;+ server.setRoute('/redirect.js', (req, res) => {+ serverRequest = req;+ res.end('console.log(1);');+ });++ await page.setRequestInterception(true);+ page.on('request', request => request.continue());+ await page.goto(server.PREFIX + '/intervention');+ // Check for feature URL substring rather than https://www.chromestatus.com to+ // make it work with Edgium.+ expect(serverRequest.headers.intervention).toContain('feature/5718547946799104');+ });+ });+};+diff --git a/test/click.spec.js b/test/click.spec.jsnew file mode 100644index 0000000000..344809b030--- /dev/null+++ b/test/click.spec.js@@ -0,0 +1,310 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const utils = require('./utils');++module.exports.addTests = function({testRunner, expect, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Page.click', function() {+ it('should click the button', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ await page.click('button');+ expect(await page.evaluate(() => result)).toBe('Clicked');+ });+ it('should click svg', async({page, server}) => {+ await page.setContent(`+ <svg height="100" width="100">+ <circle onclick="javascript:window.__CLICKED=42" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />+ </svg>+ `);+ await page.click('circle');+ expect(await page.evaluate(() => window.__CLICKED)).toBe(42);+ });+ it.skip(FFOX || WEBKIT)('should click the button if window.Node is removed', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ await page.evaluate(() => delete window.Node);+ await page.click('button');+ expect(await page.evaluate(() => result)).toBe('Clicked');+ });+ // @see https://github.com/GoogleChrome/puppeteer/issues/4281+ it('should click on a span with an inline element inside', async({page, server}) => {+ await page.setContent(`+ <style>+ span::before {+ content: 'q';+ }+ </style>+ <span onclick='javascript:window.CLICKED=42'></span>+ `);+ await page.click('span');+ expect(await page.evaluate(() => window.CLICKED)).toBe(42);+ });+ it('should not throw UnhandledPromiseRejection when page closes', async({page, server}) => {+ const newPage = await page.browser().newPage();+ await Promise.all([+ newPage.close(),+ newPage.mouse.click(1, 2),+ ]).catch(e => {});+ });+ it('should click the button after navigation ', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ await page.click('button');+ await page.goto(server.PREFIX + '/input/button.html');+ await page.click('button');+ expect(await page.evaluate(() => result)).toBe('Clicked');+ });+ it.skip(FFOX || WEBKIT)('should click with disabled javascript', async({page, server}) => {+ await page.setJavaScriptEnabled(false);+ await page.goto(server.PREFIX + '/wrappedlink.html');+ await Promise.all([+ page.click('a'),+ page.waitForNavigation()+ ]);+ expect(page.url()).toBe(server.PREFIX + '/wrappedlink.html#clicked');+ });+ it.skip(FFOX)('should click when one of inline box children is outside of viewport', async({page, server}) => {+ await page.setContent(`+ <style>+ i {+ position: absolute;+ top: -1000px;+ }+ </style>+ <span onclick='javascript:window.CLICKED = 42;'><i>woof</i><b>doggo</b></span>+ `);+ await page.click('span');+ expect(await page.evaluate(() => window.CLICKED)).toBe(42);+ });+ it.skip(FFOX || WEBKIT)('should select the text by triple clicking', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.focus('textarea');+ const text = 'This is the text that we are going to try to select. Let\'s see how it goes.';+ await page.keyboard.type(text);+ await page.tripleclick('textarea');+ expect(await page.evaluate(() => {+ const textarea = document.querySelector('textarea');+ return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);+ })).toBe(text);+ });+ it('should click offscreen buttons', async({page, server}) => {+ await page.goto(server.PREFIX + '/offscreenbuttons.html');+ const messages = [];+ page.on('console', msg => messages.push(msg.text()));+ for (let i = 0; i < 11; ++i) {+ // We might've scrolled to click a button - reset to (0, 0).+ await page.evaluate(() => window.scrollTo(0, 0));+ await page.click(`#btn${i}`);+ }+ expect(messages).toEqual([+ 'button #0 clicked',+ 'button #1 clicked',+ 'button #2 clicked',+ 'button #3 clicked',+ 'button #4 clicked',+ 'button #5 clicked',+ 'button #6 clicked',+ 'button #7 clicked',+ 'button #8 clicked',+ 'button #9 clicked',+ 'button #10 clicked'+ ]);+ });++ it('should click wrapped links', async({page, server}) => {+ await page.goto(server.PREFIX + '/wrappedlink.html');+ await page.click('a');+ expect(await page.evaluate(() => window.__clicked)).toBe(true);+ });++ it('should click on checkbox input and toggle', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/checkbox.html');+ expect(await page.evaluate(() => result.check)).toBe(null);+ await page.click('input#agree');+ expect(await page.evaluate(() => result.check)).toBe(true);+ expect(await page.evaluate(() => result.events)).toEqual([+ 'mouseover',+ 'mouseenter',+ 'mousemove',+ 'mousedown',+ 'mouseup',+ 'click',+ 'input',+ 'change',+ ]);+ await page.click('input#agree');+ expect(await page.evaluate(() => result.check)).toBe(false);+ });++ it('should click on checkbox label and toggle', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/checkbox.html');+ expect(await page.evaluate(() => result.check)).toBe(null);+ await page.click('label[for="agree"]');+ expect(await page.evaluate(() => result.check)).toBe(true);+ expect(await page.evaluate(() => result.events)).toEqual([+ 'click',+ 'input',+ 'change',+ ]);+ await page.click('label[for="agree"]');+ expect(await page.evaluate(() => result.check)).toBe(false);+ });++ it('should fail to click a missing button', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ let error = null;+ await page.click('button.does-not-exist').catch(e => error = e);+ expect(error.message).toBe('No node found for selector: button.does-not-exist');+ });+ // @see https://github.com/GoogleChrome/puppeteer/issues/161+ it('should not hang with touch-enabled viewports', async({page, server}) => {+ await page.setViewport(playwright.devices['iPhone 6'].viewport);+ await page.mouse.down();+ await page.mouse.move(100, 10);+ await page.mouse.up();+ });+ it('should scroll and click the button', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/scrollable.html');+ await page.click('#button-5');+ expect(await page.evaluate(() => document.querySelector('#button-5').textContent)).toBe('clicked');+ await page.click('#button-80');+ expect(await page.evaluate(() => document.querySelector('#button-80').textContent)).toBe('clicked');+ });+ it.skip(FFOX || WEBKIT)('should double click the button', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ await page.evaluate(() => {+ window.double = false;+ const button = document.querySelector('button');+ button.addEventListener('dblclick', event => {+ window.double = true;+ });+ });+ const button = await page.$('button');+ await button.dblclick();+ expect(await page.evaluate('double')).toBe(true);+ expect(await page.evaluate('result')).toBe('Clicked');+ });+ it('should click a partially obscured button', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ await page.evaluate(() => {+ const button = document.querySelector('button');+ button.textContent = 'Some really long text that will go offscreen';+ button.style.position = 'absolute';+ button.style.left = '368px';+ });+ await page.click('button');+ expect(await page.evaluate(() => window.result)).toBe('Clicked');+ });+ it('should click a rotated button', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/rotatedButton.html');+ await page.click('button');+ expect(await page.evaluate(() => result)).toBe('Clicked');+ });+ it('should fire contextmenu event on right click', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/scrollable.html');+ await page.click('#button-8', {button: 'right'});+ expect(await page.evaluate(() => document.querySelector('#button-8').textContent)).toBe('context menu');+ });+ // @see https://github.com/GoogleChrome/puppeteer/issues/206+ it('should click links which cause navigation', async({page, server}) => {+ await page.setContent(`<a href="${server.EMPTY_PAGE}">empty.html</a>`);+ // This await should not hang.+ await page.click('a');+ });+ it('should click the button inside an iframe', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setContent('<div style="width:100px;height:100px">spacer</div>');+ await utils.attachFrame(page, 'button-test', server.PREFIX + '/input/button.html');+ const frame = page.frames()[1];+ const button = await frame.$('button');+ await button.click();+ expect(await frame.evaluate(() => window.result)).toBe('Clicked');+ });+ // @see https://github.com/GoogleChrome/puppeteer/issues/4110+ xit('should click the button with fixed position inside an iframe', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setViewport({width: 500, height: 500});+ await page.setContent('<div style="width:100px;height:2000px">spacer</div>');+ await utils.attachFrame(page, 'button-test', server.CROSS_PROCESS_PREFIX + '/input/button.html');+ const frame = page.frames()[1];+ await frame.$eval('button', button => button.style.setProperty('position', 'fixed'));+ await frame.click('button');+ expect(await frame.evaluate(() => window.result)).toBe('Clicked');+ });+ it.skip(WEBKIT)('should click the button with deviceScaleFactor set', async({page, server}) => {+ await page.setViewport({width: 400, height: 400, deviceScaleFactor: 5});+ expect(await page.evaluate(() => window.devicePixelRatio)).toBe(5);+ await page.setContent('<div style="width:100px;height:100px">spacer</div>');+ await utils.attachFrame(page, 'button-test', server.PREFIX + '/input/button.html');+ const frame = page.frames()[1];+ const button = await frame.$('button');+ await button.click();+ expect(await frame.evaluate(() => window.result)).toBe('Clicked');+ });++ it.skip(FFOX || WEBKIT)('should click the button with relative point', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ await page.click('button', { relativePoint: { x: 20, y: 10 } });+ expect(await page.evaluate(() => result)).toBe('Clicked');+ expect(await page.evaluate(() => offsetX)).toBe(20);+ expect(await page.evaluate(() => offsetY)).toBe(10);+ });+ it.skip(FFOX || WEBKIT)('should click a very large button with relative point', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ await page.$eval('button', button => button.style.height = button.style.width = '2000px');+ await page.click('button', { relativePoint: { x: 1900, y: 1910 } });+ expect(await page.evaluate(() => window.result)).toBe('Clicked');+ expect(await page.evaluate(() => offsetX)).toBe(1900);+ expect(await page.evaluate(() => offsetY)).toBe(1910);+ });+ xit('should click a button in scrolling container with relative point', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ await page.$eval('button', button => {+ const container = document.createElement('div');+ container.style.overflow = 'auto';+ container.style.width = '200px';+ container.style.height = '200px';+ button.parentElement.insertBefore(container, button);+ container.appendChild(button);+ button.style.height = '2000px';+ button.style.width = '2000px';+ });+ await page.click('button', { relativePoint: { x: 1900, y: 1910 } });+ expect(await page.evaluate(() => window.result)).toBe('Clicked');+ expect(await page.evaluate(() => offsetX)).toBe(1900);+ expect(await page.evaluate(() => offsetY)).toBe(1910);+ });++ it.skip(FFOX || WEBKIT)('should update modifiers correctly', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ await page.click('button', { modifiers: ['Shift'] });+ expect(await page.evaluate(() => shiftKey)).toBe(true);+ await page.click('button', { modifiers: [] });+ expect(await page.evaluate(() => shiftKey)).toBe(false);++ await page.keyboard.down('Shift');+ await page.click('button', { modifiers: [] });+ expect(await page.evaluate(() => shiftKey)).toBe(false);+ await page.click('button');+ expect(await page.evaluate(() => shiftKey)).toBe(true);+ await page.keyboard.up('Shift');+ await page.click('button');+ expect(await page.evaluate(() => shiftKey)).toBe(false);+ });+ });+};diff --git a/test/cookies.spec.js b/test/cookies.spec.jsnew file mode 100644index 0000000000..72ba2507e0--- /dev/null+++ b/test/cookies.spec.js@@ -0,0 +1,395 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Page.cookies', function() {+ it('should return no cookies in pristine browser context', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ expect(await page.cookies()).toEqual([]);+ });+ it('should get a cookie', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => {+ document.cookie = 'username=John Doe';+ });+ expect(await page.cookies()).toEqual([{+ name: 'username',+ value: 'John Doe',+ domain: 'localhost',+ path: '/',+ expires: -1,+ size: 16,+ httpOnly: false,+ secure: false,+ session: true,+ sameSite: 'None',+ }]);+ });+ it('should properly report httpOnly cookie', async({page, server}) => {+ server.setRoute('/empty.html', (req, res) => {+ res.setHeader('Set-Cookie', ';HttpOnly; Path=/');+ res.end();+ });+ await page.goto(server.EMPTY_PAGE);+ const cookies = await page.cookies();+ expect(cookies.length).toBe(1);+ expect(cookies[0].httpOnly).toBe(true);+ });+ it.skip(FFOX || WEBKIT)('should properly report "Strict" sameSite cookie', async({page, server}) => {+ server.setRoute('/empty.html', (req, res) => {+ res.setHeader('Set-Cookie', ';SameSite=Strict');+ res.end();+ });+ await page.goto(server.EMPTY_PAGE);+ const cookies = await page.cookies();+ expect(cookies.length).toBe(1);+ expect(cookies[0].sameSite).toBe('Strict');+ });+ it.skip(FFOX || WEBKIT)('should properly report "Lax" sameSite cookie', async({page, server}) => {+ server.setRoute('/empty.html', (req, res) => {+ res.setHeader('Set-Cookie', ';SameSite=Lax');+ res.end();+ });+ await page.goto(server.EMPTY_PAGE);+ const cookies = await page.cookies();+ expect(cookies.length).toBe(1);+ expect(cookies[0].sameSite).toBe('Lax');+ });+ it('should get multiple cookies', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => {+ document.cookie = 'username=John Doe';+ document.cookie = 'password=1234';+ });+ const cookies = await page.cookies();+ cookies.sort((a, b) => a.name.localeCompare(b.name));+ expect(cookies).toEqual([+ {+ name: 'password',+ value: '1234',+ domain: 'localhost',+ path: '/',+ expires: -1,+ size: 12,+ httpOnly: false,+ secure: false,+ session: true,+ sameSite: 'None',+ },+ {+ name: 'username',+ value: 'John Doe',+ domain: 'localhost',+ path: '/',+ expires: -1,+ size: 16,+ httpOnly: false,+ secure: false,+ session: true,+ sameSite: 'None',+ },+ ]);+ });+ it.skip(WEBKIT)('should get cookies from multiple urls', async({page, server}) => {+ await page.setCookie({+ url: 'https://foo.com',+ name: 'doggo',+ value: 'woofs',+ }, {+ url: 'https://bar.com',+ name: 'catto',+ value: 'purrs',+ }, {+ url: 'https://baz.com',+ name: 'birdo',+ value: 'tweets',+ });+ const cookies = await page.cookies('https://foo.com', 'https://baz.com');+ cookies.sort((a, b) => a.name.localeCompare(b.name));+ expect(cookies).toEqual([{+ name: 'birdo',+ value: 'tweets',+ domain: 'baz.com',+ path: '/',+ expires: -1,+ size: 11,+ httpOnly: false,+ secure: true,+ session: true,+ sameSite: 'None',+ }, {+ name: 'doggo',+ value: 'woofs',+ domain: 'foo.com',+ path: '/',+ expires: -1,+ size: 10,+ httpOnly: false,+ secure: true,+ session: true,+ sameSite: 'None',+ }]);+ });+ });++ describe.skip(WEBKIT)('Page.setCookie', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setCookie({+ name: 'password',+ value: '123456'+ });+ expect(await page.evaluate(() => document.cookie)).toEqual('password=123456');+ });+ it('should isolate cookies in browser contexts', async({page, server, browser}) => {+ const anotherContext = await browser.createIncognitoBrowserContext();+ const anotherPage = await anotherContext.newPage();++ await page.goto(server.EMPTY_PAGE);+ await anotherPage.goto(server.EMPTY_PAGE);++ await page.setCookie({name: 'page1cookie', value: 'page1value'});+ await anotherPage.setCookie({name: 'page2cookie', value: 'page2value'});++ const cookies1 = await page.cookies();+ const cookies2 = await anotherPage.cookies();+ expect(cookies1.length).toBe(1);+ expect(cookies2.length).toBe(1);+ expect(cookies1[0].name).toBe('page1cookie');+ expect(cookies1[0].value).toBe('page1value');+ expect(cookies2[0].name).toBe('page2cookie');+ expect(cookies2[0].value).toBe('page2value');+ await anotherContext.close();+ });+ it('should set multiple cookies', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setCookie({+ name: 'password',+ value: '123456'+ }, {+ name: 'foo',+ value: 'bar'+ });+ expect(await page.evaluate(() => {+ const cookies = document.cookie.split(';');+ return cookies.map(cookie => cookie.trim()).sort();+ })).toEqual([+ 'foo=bar',+ 'password=123456',+ ]);+ });+ it('should have |expires| set to |-1| for session cookies', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setCookie({+ name: 'password',+ value: '123456'+ });+ const cookies = await page.cookies();+ expect(cookies[0].session).toBe(true);+ expect(cookies[0].expires).toBe(-1);+ });+ it('should set cookie with reasonable defaults', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setCookie({+ name: 'password',+ value: '123456'+ });+ const cookies = await page.cookies();+ expect(cookies.sort((a, b) => a.name.localeCompare(b.name))).toEqual([{+ name: 'password',+ value: '123456',+ domain: 'localhost',+ path: '/',+ expires: -1,+ size: 14,+ httpOnly: false,+ secure: false,+ session: true,+ sameSite: 'None',+ }]);+ });+ it('should set a cookie with a path', async({page, server}) => {+ await page.goto(server.PREFIX + '/grid.html');+ await page.setCookie({+ name: 'gridcookie',+ value: 'GRID',+ path: '/grid.html'+ });+ expect(await page.cookies()).toEqual([{+ name: 'gridcookie',+ value: 'GRID',+ domain: 'localhost',+ path: '/grid.html',+ expires: -1,+ size: 14,+ httpOnly: false,+ secure: false,+ session: true,+ sameSite: 'None',+ }]);+ expect(await page.evaluate('document.cookie')).toBe('gridcookie=GRID');+ await page.goto(server.EMPTY_PAGE);+ expect(await page.cookies()).toEqual([]);+ expect(await page.evaluate('document.cookie')).toBe('');+ await page.goto(server.PREFIX + '/grid.html');+ expect(await page.evaluate('document.cookie')).toBe('gridcookie=GRID');+ });+ it('should not set a cookie on a blank page', async function({page}) {+ await page.goto('about:blank');+ let error = null;+ try {+ await page.setCookie({name: 'example-cookie', value: 'best'});+ } catch (e) {+ error = e;+ }+ expect(error.message).toContain('At least one of the url and domain needs to be specified');+ });+ it('should not set a cookie with blank page URL', async function({page, server}) {+ let error = null;+ await page.goto(server.EMPTY_PAGE);+ try {+ await page.setCookie(+ {name: 'example-cookie', value: 'best'},+ {url: 'about:blank', name: 'example-cookie-blank', value: 'best'}+ );+ } catch (e) {+ error = e;+ }+ expect(error.message).toEqual(+ `Blank page can not have cookie "example-cookie-blank"`+ );+ });+ it('should not set a cookie on a data URL page', async function({page}) {+ let error = null;+ await page.goto('data:,Hello%2C%20World!');+ try {+ await page.setCookie({name: 'example-cookie', value: 'best'});+ } catch (e) {+ error = e;+ }+ expect(error.message).toContain('At least one of the url and domain needs to be specified');+ });+ it('should default to setting secure cookie for HTTPS websites', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const SECURE_URL = 'https://example.com';+ await page.setCookie({+ url: SECURE_URL,+ name: 'foo',+ value: 'bar',+ });+ const [cookie] = await page.cookies(SECURE_URL);+ expect(cookie.secure).toBe(true);+ });+ it('should be able to set unsecure cookie for HTTP website', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const HTTP_URL = 'http://example.com';+ await page.setCookie({+ url: HTTP_URL,+ name: 'foo',+ value: 'bar',+ });+ const [cookie] = await page.cookies(HTTP_URL);+ expect(cookie.secure).toBe(false);+ });+ it('should set a cookie on a different domain', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setCookie({+ url: 'https://www.example.com',+ name: 'example-cookie',+ value: 'best',+ });+ expect(await page.evaluate('document.cookie')).toBe('');+ expect(await page.cookies()).toEqual([]);+ expect(await page.cookies('https://www.example.com')).toEqual([{+ name: 'example-cookie',+ value: 'best',+ domain: 'www.example.com',+ path: '/',+ expires: -1,+ size: 18,+ httpOnly: false,+ secure: true,+ session: true,+ sameSite: 'None',+ }]);+ });+ it('should set cookies from a frame', async({page, server}) => {+ await page.goto(server.PREFIX + '/grid.html');+ await page.setCookie({name: 'localhost-cookie', value: 'best'});+ await page.evaluate(src => {+ let fulfill;+ const promise = new Promise(x => fulfill = x);+ const iframe = document.createElement('iframe');+ document.body.appendChild(iframe);+ iframe.onload = fulfill;+ iframe.src = src;+ return promise;+ }, server.CROSS_PROCESS_PREFIX);+ await page.setCookie({name: '127-cookie', value: 'worst', url: server.CROSS_PROCESS_PREFIX});+ expect(await page.evaluate('document.cookie')).toBe('localhost-cookie=best');+ expect(await page.frames()[1].evaluate('document.cookie')).toBe('127-cookie=worst');++ expect(await page.cookies()).toEqual([{+ name: 'localhost-cookie',+ value: 'best',+ domain: 'localhost',+ path: '/',+ expires: -1,+ size: 20,+ httpOnly: false,+ secure: false,+ session: true,+ sameSite: 'None',+ }]);++ expect(await page.cookies(server.CROSS_PROCESS_PREFIX)).toEqual([{+ name: '127-cookie',+ value: 'worst',+ domain: '127.0.0.1',+ path: '/',+ expires: -1,+ size: 15,+ httpOnly: false,+ secure: false,+ session: true,+ sameSite: 'None',+ }]);+ });+ });++ describe('Page.deleteCookie', function() {+ it.skip(WEBKIT)('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setCookie({+ name: 'cookie1',+ value: '1'+ }, {+ name: 'cookie2',+ value: '2'+ }, {+ name: 'cookie3',+ value: '3'+ });+ expect(await page.evaluate('document.cookie')).toBe('cookie1=1; cookie2=2; cookie3=3');+ await page.deleteCookie({name: 'cookie2'});+ expect(await page.evaluate('document.cookie')).toBe('cookie1=1; cookie3=3');+ });+ });+};diff --git a/test/coverage.spec.js b/test/coverage.spec.jsnew file mode 100644index 0000000000..aee11c12a7--- /dev/null+++ b/test/coverage.spec.js@@ -0,0 +1,216 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('JSCoverage', function() {+ it('should work', async function({page, server}) {+ await page.coverage.startJSCoverage();+ await page.goto(server.PREFIX + '/jscoverage/simple.html', {waitUntil: 'networkidle0'});+ const coverage = await page.coverage.stopJSCoverage();+ expect(coverage.length).toBe(1);+ expect(coverage[0].url).toContain('/jscoverage/simple.html');+ expect(coverage[0].ranges).toEqual([+ { start: 0, end: 17 },+ { start: 35, end: 61 },+ ]);+ });+ it('should report sourceURLs', async function({page, server}) {+ await page.coverage.startJSCoverage();+ await page.goto(server.PREFIX + '/jscoverage/sourceurl.html');+ const coverage = await page.coverage.stopJSCoverage();+ expect(coverage.length).toBe(1);+ expect(coverage[0].url).toBe('nicename.js');+ });+ it('should ignore eval() scripts by default', async function({page, server}) {+ await page.coverage.startJSCoverage();+ await page.goto(server.PREFIX + '/jscoverage/eval.html');+ const coverage = await page.coverage.stopJSCoverage();+ expect(coverage.length).toBe(1);+ });+ it('shouldn\'t ignore eval() scripts if reportAnonymousScripts is true', async function({page, server}) {+ await page.coverage.startJSCoverage({reportAnonymousScripts: true});+ await page.goto(server.PREFIX + '/jscoverage/eval.html');+ const coverage = await page.coverage.stopJSCoverage();+ expect(coverage.find(entry => entry.url.startsWith('debugger://'))).not.toBe(null);+ expect(coverage.length).toBe(2);+ });+ it('should ignore pptr internal scripts if reportAnonymousScripts is true', async function({page, server}) {+ await page.coverage.startJSCoverage({reportAnonymousScripts: true});+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate('console.log("foo")');+ await page.evaluate(() => console.log('bar'));+ const coverage = await page.coverage.stopJSCoverage();+ expect(coverage.length).toBe(0);+ });+ it('should report multiple scripts', async function({page, server}) {+ await page.coverage.startJSCoverage();+ await page.goto(server.PREFIX + '/jscoverage/multiple.html');+ const coverage = await page.coverage.stopJSCoverage();+ expect(coverage.length).toBe(2);+ coverage.sort((a, b) => a.url.localeCompare(b.url));+ expect(coverage[0].url).toContain('/jscoverage/script1.js');+ expect(coverage[1].url).toContain('/jscoverage/script2.js');+ });+ it('should report right ranges', async function({page, server}) {+ await page.coverage.startJSCoverage();+ await page.goto(server.PREFIX + '/jscoverage/ranges.html');+ const coverage = await page.coverage.stopJSCoverage();+ expect(coverage.length).toBe(1);+ const entry = coverage[0];+ expect(entry.ranges.length).toBe(1);+ const range = entry.ranges[0];+ expect(entry.text.substring(range.start, range.end)).toBe(`console.log('used!');`);+ });+ it('should report scripts that have no coverage', async function({page, server}) {+ await page.coverage.startJSCoverage();+ await page.goto(server.PREFIX + '/jscoverage/unused.html');+ const coverage = await page.coverage.stopJSCoverage();+ expect(coverage.length).toBe(1);+ const entry = coverage[0];+ expect(entry.url).toContain('unused.html');+ expect(entry.ranges.length).toBe(0);+ });+ it('should work with conditionals', async function({page, server}) {+ await page.coverage.startJSCoverage();+ await page.goto(server.PREFIX + '/jscoverage/involved.html');+ const coverage = await page.coverage.stopJSCoverage();+ expect(JSON.stringify(coverage, null, 2).replace(/:\d{4}\//g, ':<PORT>/')).toBeGolden('jscoverage-involved.txt');+ });+ describe('resetOnNavigation', function() {+ it('should report scripts across navigations when disabled', async function({page, server}) {+ await page.coverage.startJSCoverage({resetOnNavigation: false});+ await page.goto(server.PREFIX + '/jscoverage/multiple.html');+ await page.goto(server.EMPTY_PAGE);+ const coverage = await page.coverage.stopJSCoverage();+ expect(coverage.length).toBe(2);+ });+ it('should NOT report scripts across navigations when enabled', async function({page, server}) {+ await page.coverage.startJSCoverage(); // Enabled by default.+ await page.goto(server.PREFIX + '/jscoverage/multiple.html');+ await page.goto(server.EMPTY_PAGE);+ const coverage = await page.coverage.stopJSCoverage();+ expect(coverage.length).toBe(0);+ });+ });+ // @see https://crbug.com/990945+ xit('should not hang when there is a debugger statement', async function({page, server}) {+ await page.coverage.startJSCoverage();+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => {+ debugger; // eslint-disable-line no-debugger+ });+ await page.coverage.stopJSCoverage();+ });+ });++ describe('CSSCoverage', function() {+ it('should work', async function({page, server}) {+ await page.coverage.startCSSCoverage();+ await page.goto(server.PREFIX + '/csscoverage/simple.html');+ const coverage = await page.coverage.stopCSSCoverage();+ expect(coverage.length).toBe(1);+ expect(coverage[0].url).toContain('/csscoverage/simple.html');+ expect(coverage[0].ranges).toEqual([+ {start: 1, end: 22}+ ]);+ const range = coverage[0].ranges[0];+ expect(coverage[0].text.substring(range.start, range.end)).toBe('div { color: green; }');+ });+ it('should report sourceURLs', async function({page, server}) {+ await page.coverage.startCSSCoverage();+ await page.goto(server.PREFIX + '/csscoverage/sourceurl.html');+ const coverage = await page.coverage.stopCSSCoverage();+ expect(coverage.length).toBe(1);+ expect(coverage[0].url).toBe('nicename.css');+ });+ it('should report multiple stylesheets', async function({page, server}) {+ await page.coverage.startCSSCoverage();+ await page.goto(server.PREFIX + '/csscoverage/multiple.html');+ const coverage = await page.coverage.stopCSSCoverage();+ expect(coverage.length).toBe(2);+ coverage.sort((a, b) => a.url.localeCompare(b.url));+ expect(coverage[0].url).toContain('/csscoverage/stylesheet1.css');+ expect(coverage[1].url).toContain('/csscoverage/stylesheet2.css');+ });+ it('should report stylesheets that have no coverage', async function({page, server}) {+ await page.coverage.startCSSCoverage();+ await page.goto(server.PREFIX + '/csscoverage/unused.html');+ const coverage = await page.coverage.stopCSSCoverage();+ expect(coverage.length).toBe(1);+ expect(coverage[0].url).toBe('unused.css');+ expect(coverage[0].ranges.length).toBe(0);+ });+ it('should work with media queries', async function({page, server}) {+ await page.coverage.startCSSCoverage();+ await page.goto(server.PREFIX + '/csscoverage/media.html');+ const coverage = await page.coverage.stopCSSCoverage();+ expect(coverage.length).toBe(1);+ expect(coverage[0].url).toContain('/csscoverage/media.html');+ expect(coverage[0].ranges).toEqual([+ {start: 17, end: 38}+ ]);+ });+ it('should work with complicated usecases', async function({page, server}) {+ await page.coverage.startCSSCoverage();+ await page.goto(server.PREFIX + '/csscoverage/involved.html');+ const coverage = await page.coverage.stopCSSCoverage();+ expect(JSON.stringify(coverage, null, 2).replace(/:\d{4}\//g, ':<PORT>/')).toBeGolden('csscoverage-involved.txt');+ });+ it('should ignore injected stylesheets', async function({page, server}) {+ await page.coverage.startCSSCoverage();+ await page.addStyleTag({content: 'body { margin: 10px;}'});+ // trigger style recalc+ const margin = await page.evaluate(() => window.getComputedStyle(document.body).margin);+ expect(margin).toBe('10px');+ const coverage = await page.coverage.stopCSSCoverage();+ expect(coverage.length).toBe(0);+ });+ describe('resetOnNavigation', function() {+ it('should report stylesheets across navigations', async function({page, server}) {+ await page.coverage.startCSSCoverage({resetOnNavigation: false});+ await page.goto(server.PREFIX + '/csscoverage/multiple.html');+ await page.goto(server.EMPTY_PAGE);+ const coverage = await page.coverage.stopCSSCoverage();+ expect(coverage.length).toBe(2);+ });+ it('should NOT report scripts across navigations', async function({page, server}) {+ await page.coverage.startCSSCoverage(); // Enabled by default.+ await page.goto(server.PREFIX + '/csscoverage/multiple.html');+ await page.goto(server.EMPTY_PAGE);+ const coverage = await page.coverage.stopCSSCoverage();+ expect(coverage.length).toBe(0);+ });+ });+ it('should work with a recently loaded stylesheet', async function({page, server}) {+ await page.coverage.startCSSCoverage();+ await page.evaluate(async url => {+ document.body.textContent = 'hello, world';++ const link = document.createElement('link');+ link.rel = 'stylesheet';+ link.href = url;+ document.head.appendChild(link);+ await new Promise(x => link.onload = x);+ }, server.PREFIX + '/csscoverage/stylesheet1.css');+ const coverage = await page.coverage.stopCSSCoverage();+ expect(coverage.length).toBe(1);+ });+ });+};diff --git a/test/defaultbrowsercontext.spec.js b/test/defaultbrowsercontext.spec.jsnew file mode 100644index 0000000000..c55792263d--- /dev/null+++ b/test/defaultbrowsercontext.spec.js@@ -0,0 +1,96 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, defaultBrowserOptions, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe.skip(FFOX)('DefaultBrowserContext', function() {+ beforeEach(async state => {+ state.browser = await playwright.launch(defaultBrowserOptions);+ state.page = await state.browser.newPage();+ });+ afterEach(async state => {+ await state.browser.close();+ delete state.browser;+ delete state.page;+ });+ it('page.cookies() should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => {+ document.cookie = 'username=John Doe';+ });+ expect(await page.cookies()).toEqual([{+ name: 'username',+ value: 'John Doe',+ domain: 'localhost',+ path: '/',+ expires: -1,+ size: 16,+ httpOnly: false,+ secure: false,+ session: true,+ sameSite: 'None',+ }]);+ });+ it.skip(WEBKIT)('page.setCookie() should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setCookie({+ name: 'username',+ value: 'John Doe'+ });+ expect(await page.evaluate(() => document.cookie)).toBe('username=John Doe');+ expect(await page.cookies()).toEqual([{+ name: 'username',+ value: 'John Doe',+ domain: 'localhost',+ path: '/',+ expires: -1,+ size: 16,+ httpOnly: false,+ secure: false,+ session: true,+ sameSite: 'None',+ }]);+ });+ it.skip(WEBKIT)('page.deleteCookie() should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setCookie({+ name: 'cookie1',+ value: '1'+ }, {+ name: 'cookie2',+ value: '2'+ });+ expect(await page.evaluate('document.cookie')).toBe('cookie1=1; cookie2=2');+ await page.deleteCookie({name: 'cookie2'});+ expect(await page.evaluate('document.cookie')).toBe('cookie1=1');+ expect(await page.cookies()).toEqual([{+ name: 'cookie1',+ value: '1',+ domain: 'localhost',+ path: '/',+ expires: -1,+ size: 8,+ httpOnly: false,+ secure: false,+ session: true,+ sameSite: 'None',+ }]);+ });+ });+};diff --git a/test/dialog.spec.js b/test/dialog.spec.jsnew file mode 100644index 0000000000..0d9e58b752--- /dev/null+++ b/test/dialog.spec.js@@ -0,0 +1,50 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe.skip(WEBKIT)('Page.Events.Dialog', function() {+ it('should fire', async({page, server}) => {+ page.on('dialog', dialog => {+ expect(dialog.type()).toBe('alert');+ expect(dialog.defaultValue()).toBe('');+ expect(dialog.message()).toBe('yo');+ dialog.accept();+ });+ await page.evaluate(() => alert('yo'));+ });+ it('should allow accepting prompts', async({page, server}) => {+ page.on('dialog', dialog => {+ expect(dialog.type()).toBe('prompt');+ expect(dialog.defaultValue()).toBe('yes.');+ expect(dialog.message()).toBe('question?');+ dialog.accept('answer!');+ });+ const result = await page.evaluate(() => prompt('question?', 'yes.'));+ expect(result).toBe('answer!');+ });+ it('should dismiss the prompt', async({page, server}) => {+ page.on('dialog', dialog => {+ dialog.dismiss();+ });+ const result = await page.evaluate(() => prompt('question?'));+ expect(result).toBe(null);+ });+ });+};diff --git a/test/diffstyle.css b/test/diffstyle.cssnew file mode 100644index 0000000000..c58f0e90a6--- /dev/null+++ b/test/diffstyle.css@@ -0,0 +1,13 @@+body {+ font-family: monospace;+ white-space: pre;+}++ins {+ background-color: #9cffa0;+ text-decoration: none;+}++del {+ background-color: #ff9e9e;+}diff --git a/test/elementhandle.spec.js b/test/elementhandle.spec.jsnew file mode 100644index 0000000000..feff82e641--- /dev/null+++ b/test/elementhandle.spec.js@@ -0,0 +1,215 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const utils = require('./utils');++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe.skip(WEBKIT)('ElementHandle.boundingBox', function() {+ it('should work', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.goto(server.PREFIX + '/grid.html');+ const elementHandle = await page.$('.box:nth-of-type(13)');+ const box = await elementHandle.boundingBox();+ expect(box).toEqual({ x: 100, y: 50, width: 50, height: 50 });+ });+ it('should handle nested frames', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.goto(server.PREFIX + '/frames/nested-frames.html');+ const nestedFrame = page.frames()[1].childFrames()[1];+ const elementHandle = await nestedFrame.$('div');+ const box = await elementHandle.boundingBox();+ if (CHROME)+ expect(box).toEqual({ x: 28, y: 260, width: 264, height: 18 });+ else+ expect(box).toEqual({ x: 28, y: 182, width: 247, height: 18 });+ });+ it('should return null for invisible elements', async({page, server}) => {+ await page.setContent('<div style="display:none">hi</div>');+ const element = await page.$('div');+ expect(await element.boundingBox()).toBe(null);+ });+ it('should force a layout', async({page, server}) => {+ await page.setViewport({ width: 500, height: 500 });+ await page.setContent('<div style="width: 100px; height: 100px">hello</div>');+ const elementHandle = await page.$('div');+ await page.evaluate(element => element.style.height = '200px', elementHandle);+ const box = await elementHandle.boundingBox();+ expect(box).toEqual({ x: 8, y: 8, width: 100, height: 200 });+ });+ it('should work with SVG nodes', async({page, server}) => {+ await page.setContent(`+ <svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">+ <rect id="theRect" x="30" y="50" width="200" height="300"></rect>+ </svg>+ `);+ const element = await page.$('#therect');+ const pptrBoundingBox = await element.boundingBox();+ const webBoundingBox = await page.evaluate(e => {+ const rect = e.getBoundingClientRect();+ return {x: rect.x, y: rect.y, width: rect.width, height: rect.height};+ }, element);+ expect(pptrBoundingBox).toEqual(webBoundingBox);+ });+ });++ describe.skip(FFOX || WEBKIT)('ElementHandle.boxModel', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.PREFIX + '/resetcss.html');++ // Step 1: Add Frame and position it absolutely.+ await utils.attachFrame(page, 'frame1', server.PREFIX + '/resetcss.html');+ await page.evaluate(() => {+ const frame = document.querySelector('#frame1');+ frame.style = `+ position: absolute;+ left: 1px;+ top: 2px;+ `;+ });++ // Step 2: Add div and position it absolutely inside frame.+ const frame = page.frames()[1];+ const divHandle = (await frame.evaluateHandle(() => {+ const div = document.createElement('div');+ document.body.appendChild(div);+ div.style = `+ box-sizing: border-box;+ position: absolute;+ border-left: 1px solid black;+ padding-left: 2px;+ margin-left: 3px;+ left: 4px;+ top: 5px;+ width: 6px;+ height: 7px;+ `;+ return div;+ })).asElement();++ // Step 3: query div's boxModel and assert box values.+ const box = await divHandle.boxModel();+ expect(box.width).toBe(6);+ expect(box.height).toBe(7);+ expect(box.margin[0]).toEqual({+ x: 1 + 4, // frame.left + div.left+ y: 2 + 5,+ });+ expect(box.border[0]).toEqual({+ x: 1 + 4 + 3, // frame.left + div.left + div.margin-left+ y: 2 + 5,+ });+ expect(box.padding[0]).toEqual({+ x: 1 + 4 + 3 + 1, // frame.left + div.left + div.marginLeft + div.borderLeft+ y: 2 + 5,+ });+ expect(box.content[0]).toEqual({+ x: 1 + 4 + 3 + 1 + 2, // frame.left + div.left + div.marginLeft + div.borderLeft + dif.paddingLeft+ y: 2 + 5,+ });+ });++ it('should return null for invisible elements', async({page, server}) => {+ await page.setContent('<div style="display:none">hi</div>');+ const element = await page.$('div');+ expect(await element.boxModel()).toBe(null);+ });+ });++ describe.skip(WEBKIT)('ElementHandle.contentFrame', function() {+ it('should work', async({page,server}) => {+ await page.goto(server.EMPTY_PAGE);+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ const elementHandle = await page.$('#frame1');+ const frame = await elementHandle.contentFrame();+ expect(frame).toBe(page.frames()[1]);+ });+ });++ describe('ElementHandle.click', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ const button = await page.$('button');+ await button.click();+ expect(await page.evaluate(() => result)).toBe('Clicked');+ });+ it('should work for Shadow DOM v1', async({page, server}) => {+ await page.goto(server.PREFIX + '/shadow.html');+ const buttonHandle = await page.evaluateHandle(() => button);+ await buttonHandle.click();+ expect(await page.evaluate(() => clicked)).toBe(true);+ });+ it('should work for TextNodes', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ const buttonTextNode = await page.evaluateHandle(() => document.querySelector('button').firstChild);+ let error = null;+ await buttonTextNode.click().catch(err => error = err);+ expect(error.message).toBe('Node is not of type HTMLElement');+ });+ it('should throw for detached nodes', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ const button = await page.$('button');+ await page.evaluate(button => button.remove(), button);+ let error = null;+ await button.click().catch(err => error = err);+ expect(error.message).toBe('Node is detached from document');+ });+ it('should throw for hidden nodes', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ const button = await page.$('button');+ await page.evaluate(button => button.style.display = 'none', button);+ const error = await button.click().catch(err => err);+ expect(error.message).toBe('Node is either not visible or not an HTMLElement');+ });+ it('should throw for recursively hidden nodes', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/button.html');+ const button = await page.$('button');+ await page.evaluate(button => button.parentElement.style.display = 'none', button);+ const error = await button.click().catch(err => err);+ expect(error.message).toBe('Node is either not visible or not an HTMLElement');+ });+ it('should throw for <br> elements', async({page, server}) => {+ await page.setContent('hello<br>goodbye');+ const br = await page.$('br');+ const error = await br.click().catch(err => err);+ expect(error.message).toBe('Node is either not visible or not an HTMLElement');+ });+ });++ describe('ElementHandle.hover', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/scrollable.html');+ const button = await page.$('#button-6');+ await button.hover();+ expect(await page.evaluate(() => document.querySelector('button:hover').id)).toBe('button-6');+ });+ });++ describe('ElementHandle.isIntersectingViewport', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.PREFIX + '/offscreenbuttons.html');+ for (let i = 0; i < 11; ++i) {+ const button = await page.$('#btn' + i);+ // All but last button are visible.+ const visible = i < 10;+ expect(await button.isIntersectingViewport()).toBe(visible);+ }+ });+ });+};diff --git a/test/emulation.spec.js b/test/emulation.spec.jsnew file mode 100644index 0000000000..7a64cfe565--- /dev/null+++ b/test/emulation.spec.js@@ -0,0 +1,187 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ const iPhone = playwright.devices['iPhone 6'];+ const iPhoneLandscape = playwright.devices['iPhone 6 landscape'];++ describe('Page.viewport', function() {+ it('should get the proper viewport size', async({page, server}) => {+ expect(page.viewport()).toEqual({width: 800, height: 600});+ await page.setViewport({width: 123, height: 456});+ expect(page.viewport()).toEqual({width: 123, height: 456});+ });+ it.skip(WEBKIT)('should support mobile emulation', async({page, server}) => {+ await page.goto(server.PREFIX + '/mobile.html');+ expect(await page.evaluate(() => window.innerWidth)).toBe(800);+ await page.setViewport(iPhone.viewport);+ expect(await page.evaluate(() => window.innerWidth)).toBe(375);+ await page.setViewport({width: 400, height: 300});+ expect(await page.evaluate(() => window.innerWidth)).toBe(400);+ });+ it.skip(WEBKIT)('should support touch emulation', async({page, server}) => {+ await page.goto(server.PREFIX + '/mobile.html');+ expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(false);+ await page.setViewport(iPhone.viewport);+ expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(true);+ expect(await page.evaluate(dispatchTouch)).toBe('Received touch');+ await page.setViewport({width: 100, height: 100});+ expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(false);++ function dispatchTouch() {+ let fulfill;+ const promise = new Promise(x => fulfill = x);+ window.ontouchstart = function(e) {+ fulfill('Received touch');+ };+ window.dispatchEvent(new Event('touchstart'));++ fulfill('Did not receive touch');++ return promise;+ }+ });+ it.skip(WEBKIT)('should be detectable by Modernizr', async({page, server}) => {+ await page.goto(server.PREFIX + '/detect-touch.html');+ expect(await page.evaluate(() => document.body.textContent.trim())).toBe('NO');+ await page.setViewport(iPhone.viewport);+ await page.goto(server.PREFIX + '/detect-touch.html');+ expect(await page.evaluate(() => document.body.textContent.trim())).toBe('YES');+ });+ it.skip(WEBKIT)('should detect touch when applying viewport with touches', async({page, server}) => {+ await page.setViewport({ width: 800, height: 600, hasTouch: true });+ await page.addScriptTag({url: server.PREFIX + '/modernizr.js'});+ expect(await page.evaluate(() => Modernizr.touchevents)).toBe(true);+ });+ it.skip(FFOX || WEBKIT)('should support landscape emulation', async({page, server}) => {+ await page.goto(server.PREFIX + '/mobile.html');+ expect(await page.evaluate(() => screen.orientation.type)).toBe('portrait-primary');+ await page.setViewport(iPhoneLandscape.viewport);+ expect(await page.evaluate(() => screen.orientation.type)).toBe('landscape-primary');+ await page.setViewport({width: 100, height: 100});+ expect(await page.evaluate(() => screen.orientation.type)).toBe('portrait-primary');+ });+ });++ describe('Page.emulate', function() {+ it.skip(WEBKIT)('should work', async({page, server}) => {+ await page.goto(server.PREFIX + '/mobile.html');+ await page.emulate(iPhone);+ expect(await page.evaluate(() => window.innerWidth)).toBe(375);+ expect(await page.evaluate(() => navigator.userAgent)).toContain('iPhone');+ });+ it('should support clicking', async({page, server}) => {+ await page.emulate(iPhone);+ await page.goto(server.PREFIX + '/input/button.html');+ const button = await page.$('button');+ await page.evaluate(button => button.style.marginTop = '200px', button);+ await button.click();+ expect(await page.evaluate(() => result)).toBe('Clicked');+ });+ });++ describe('Page.emulateMedia', function() {+ it.skip(WEBKIT)('should be an alias for Page.emulateMediaType', async({page, server}) => {+ expect(page.emulateMedia).toEqual(page.emulateMediaType);+ });+ });++ describe.skip(WEBKIT)('Page.emulateMediaType', function() {+ it('should work', async({page, server}) => {+ expect(await page.evaluate(() => matchMedia('screen').matches)).toBe(true);+ expect(await page.evaluate(() => matchMedia('print').matches)).toBe(false);+ await page.emulateMediaType('print');+ expect(await page.evaluate(() => matchMedia('screen').matches)).toBe(false);+ expect(await page.evaluate(() => matchMedia('print').matches)).toBe(true);+ await page.emulateMediaType(null);+ expect(await page.evaluate(() => matchMedia('screen').matches)).toBe(true);+ expect(await page.evaluate(() => matchMedia('print').matches)).toBe(false);+ });+ it('should throw in case of bad argument', async({page, server}) => {+ let error = null;+ await page.emulateMediaType('bad').catch(e => error = e);+ expect(error.message).toBe('Unsupported media type: bad');+ });+ });++ describe.skip(FFOX || WEBKIT)('Page.emulateMediaFeatures', function() {+ it('should work', async({page, server}) => {+ await page.emulateMediaFeatures([+ { name: 'prefers-reduced-motion', value: 'reduce' },+ ]);+ expect(await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches)).toBe(true);+ expect(await page.evaluate(() => matchMedia('(prefers-reduced-motion: no-preference)').matches)).toBe(false);+ await page.emulateMediaFeatures([+ { name: 'prefers-color-scheme', value: 'light' },+ ]);+ expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches)).toBe(true);+ expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(false);+ expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches)).toBe(false);+ await page.emulateMediaFeatures([+ { name: 'prefers-color-scheme', value: 'dark' },+ ]);+ expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(true);+ expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches)).toBe(false);+ expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches)).toBe(false);+ await page.emulateMediaFeatures([+ { name: 'prefers-reduced-motion', value: 'reduce' },+ { name: 'prefers-color-scheme', value: 'light' },+ ]);+ expect(await page.evaluate(() => matchMedia('(prefers-reduced-motion: reduce)').matches)).toBe(true);+ expect(await page.evaluate(() => matchMedia('(prefers-reduced-motion: no-preference)').matches)).toBe(false);+ expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: light)').matches)).toBe(true);+ expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(false);+ expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: no-preference)').matches)).toBe(false);+ });+ it('should throw in case of bad argument', async({page, server}) => {+ let error = null;+ await page.emulateMediaFeatures([{ name: 'bad', value: '' }]).catch(e => error = e);+ expect(error.message).toBe('Unsupported media feature: bad');+ });+ });++ describe.skip(FFOX || WEBKIT)('Page.emulateTimezone', function() {+ it('should work', async({page, server}) => {+ page.evaluate(() => {+ globalThis.date = new Date(1479579154987);+ });+ await page.emulateTimezone('America/Jamaica');+ expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 13:12:34 GMT-0500 (Eastern Standard Time)');++ await page.emulateTimezone('Pacific/Honolulu');+ expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 08:12:34 GMT-1000 (Hawaii-Aleutian Standard Time)');++ await page.emulateTimezone('America/Buenos_Aires');+ expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 15:12:34 GMT-0300 (Argentina Standard Time)');++ await page.emulateTimezone('Europe/Berlin');+ expect(await page.evaluate(() => date.toString())).toBe('Sat Nov 19 2016 19:12:34 GMT+0100 (Central European Standard Time)');+ });++ it('should throw for invalid timezone IDs', async({page, server}) => {+ let error = null;+ await page.emulateTimezone('Foo/Bar').catch(e => error = e);+ expect(error.message).toBe('Invalid timezone ID: Foo/Bar');+ await page.emulateTimezone('Baz/Qux').catch(e => error = e);+ expect(error.message).toBe('Invalid timezone ID: Baz/Qux');+ });+ });++};diff --git a/test/evaluation.spec.js b/test/evaluation.spec.jsnew file mode 100644index 0000000000..e7e2e38eec--- /dev/null+++ b/test/evaluation.spec.js@@ -0,0 +1,305 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const utils = require('./utils');++const bigint = typeof BigInt !== 'undefined';++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Page.evaluate', function() {+ it('should work', async({page, server}) => {+ const result = await page.evaluate(() => 7 * 3);+ expect(result).toBe(21);+ });+ (bigint ? it.skip(FFOX || WEBKIT) : xit)('should transfer BigInt', async({page, server}) => {+ const result = await page.evaluate(a => a, BigInt(42));+ expect(result).toBe(BigInt(42));+ });+ it('should transfer NaN', async({page, server}) => {+ const result = await page.evaluate(a => a, NaN);+ expect(Object.is(result, NaN)).toBe(true);+ });+ it('should transfer -0', async({page, server}) => {+ const result = await page.evaluate(a => a, -0);+ expect(Object.is(result, -0)).toBe(true);+ });+ it('should transfer Infinity', async({page, server}) => {+ const result = await page.evaluate(a => a, Infinity);+ expect(Object.is(result, Infinity)).toBe(true);+ });+ it('should transfer -Infinity', async({page, server}) => {+ const result = await page.evaluate(a => a, -Infinity);+ expect(Object.is(result, -Infinity)).toBe(true);+ });+ it('should transfer arrays', async({page, server}) => {+ const result = await page.evaluate(a => a, [1, 2, 3]);+ expect(result).toEqual([1,2,3]);+ });+ it('should transfer arrays as arrays, not objects', async({page, server}) => {+ const result = await page.evaluate(a => Array.isArray(a), [1, 2, 3]);+ expect(result).toBe(true);+ });+ it('should modify global environment', async({page}) => {+ await page.evaluate(() => window.globalVar = 123);+ expect(await page.evaluate('globalVar')).toBe(123);+ });+ it('should evaluate in the page context', async({page, server}) => {+ await page.goto(server.PREFIX + '/global-var.html');+ expect(await page.evaluate('globalVar')).toBe(123);+ });+ it.skip(FFOX || WEBKIT)('should return undefined for objects with symbols', async({page, server}) => {+ expect(await page.evaluate(() => [Symbol('foo4')])).toBe(undefined);+ });+ it('should work with function shorthands', async({page, server}) => {+ const a = {+ sum(a, b) { return a + b; },++ async mult(a, b) { return a * b; }+ };+ expect(await page.evaluate(a.sum, 1, 2)).toBe(3);+ expect(await page.evaluate(a.mult, 2, 4)).toBe(8);+ });+ it('should work with unicode chars', async({page, server}) => {+ const result = await page.evaluate(a => a['中文字符'], {'中文字符': 42});+ expect(result).toBe(42);+ });+ it('should throw when evaluation triggers reload', async({page, server}) => {+ let error = null;+ await page.evaluate(() => {+ location.reload();+ return new Promise(() => {});+ }).catch(e => error = e);+ expect(error.message).toContain('Protocol error');+ });+ it('should await promise', async({page, server}) => {+ const result = await page.evaluate(() => Promise.resolve(8 * 7));+ expect(result).toBe(56);+ });+ it('should work right after framenavigated', async({page, server}) => {+ let frameEvaluation = null;+ page.on('framenavigated', async frame => {+ frameEvaluation = frame.evaluate(() => 6 * 7);+ });+ await page.goto(server.EMPTY_PAGE);+ expect(await frameEvaluation).toBe(42);+ });+ it.skip(WEBKIT)('should work from-inside an exposed function', async({page, server}) => {+ // Setup inpage callback, which calls Page.evaluate+ await page.exposeFunction('callController', async function(a, b) {+ return await page.evaluate((a, b) => a * b, a, b);+ });+ const result = await page.evaluate(async function() {+ return await callController(9, 3);+ });+ expect(result).toBe(27);+ });+ it('should reject promise with exception', async({page, server}) => {+ let error = null;+ await page.evaluate(() => not_existing_object.property).catch(e => error = e);+ expect(error).toBeTruthy();+ expect(error.message).toContain('not_existing_object');+ });+ it('should support thrown strings as error messages', async({page, server}) => {+ let error = null;+ await page.evaluate(() => { throw 'qwerty'; }).catch(e => error = e);+ expect(error).toBeTruthy();+ expect(error.message).toContain('qwerty');+ });+ it('should support thrown numbers as error messages', async({page, server}) => {+ let error = null;+ await page.evaluate(() => { throw 100500; }).catch(e => error = e);+ expect(error).toBeTruthy();+ expect(error.message).toContain('100500');+ });+ it('should return complex objects', async({page, server}) => {+ const object = {foo: 'bar!'};+ const result = await page.evaluate(a => a, object);+ expect(result).not.toBe(object);+ expect(result).toEqual(object);+ });+ (bigint ? it.skip(FFOX || WEBKIT) : xit)('should return BigInt', async({page, server}) => {+ const result = await page.evaluate(() => BigInt(42));+ expect(result).toBe(BigInt(42));+ });+ it('should return NaN', async({page, server}) => {+ const result = await page.evaluate(() => NaN);+ expect(Object.is(result, NaN)).toBe(true);+ });+ it('should return -0', async({page, server}) => {+ const result = await page.evaluate(() => -0);+ expect(Object.is(result, -0)).toBe(true);+ });+ it('should return Infinity', async({page, server}) => {+ const result = await page.evaluate(() => Infinity);+ expect(Object.is(result, Infinity)).toBe(true);+ });+ it('should return -Infinity', async({page, server}) => {+ const result = await page.evaluate(() => -Infinity);+ expect(Object.is(result, -Infinity)).toBe(true);+ });+ it('should accept "undefined" as one of multiple parameters', async({page, server}) => {+ const result = await page.evaluate((a, b) => Object.is(a, undefined) && Object.is(b, 'foo'), undefined, 'foo');+ expect(result).toBe(true);+ });+ it('should properly serialize null fields', async({page}) => {+ expect(await page.evaluate(() => ({a: undefined}))).toEqual({});+ });+ it('should return undefined for non-serializable objects', async({page, server}) => {+ expect(await page.evaluate(() => window)).toBe(undefined);+ });+ it('should fail for circular object', async({page, server}) => {+ const result = await page.evaluate(() => {+ const a = {};+ const b = {a};+ a.b = b;+ return a;+ });+ expect(result).toBe(undefined);+ });+ it.skip(FFOX)('should be able to throw a tricky error', async({page, server}) => {+ const windowHandle = await page.evaluateHandle(() => window);+ const errorText = await windowHandle.jsonValue().catch(e => e.message);+ const error = await page.evaluate(errorText => {+ throw new Error(errorText);+ }, errorText).catch(e => e);+ expect(error.message).toContain(errorText);+ });+ it('should accept a string', async({page, server}) => {+ const result = await page.evaluate('1 + 2');+ expect(result).toBe(3);+ });+ it('should accept a string with semi colons', async({page, server}) => {+ const result = await page.evaluate('1 + 5;');+ expect(result).toBe(6);+ });+ it('should accept a string with comments', async({page, server}) => {+ const result = await page.evaluate('2 + 5;\n// do some math!');+ expect(result).toBe(7);+ });+ it('should accept element handle as an argument', async({page, server}) => {+ await page.setContent('<section>42</section>');+ const element = await page.$('section');+ const text = await page.evaluate(e => e.textContent, element);+ expect(text).toBe('42');+ });+ it('should throw if underlying element was disposed', async({page, server}) => {+ await page.setContent('<section>39</section>');+ const element = await page.$('section');+ expect(element).toBeTruthy();+ await element.dispose();+ let error = null;+ await page.evaluate(e => e.textContent, element).catch(e => error = e);+ expect(error.message).toContain('JSHandle is disposed');+ });+ it('should throw if elementHandles are from other frames', async({page, server}) => {+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ const bodyHandle = await page.frames()[1].$('body');+ let error = null;+ await page.evaluate(body => body.innerHTML, bodyHandle).catch(e => error = e);+ expect(error).toBeTruthy();+ expect(error.message).toContain('JSHandles can be evaluated only in the context they were created');+ });+ it('should simulate a user gesture', async({page, server}) => {+ const result = await page.evaluate(() => {+ document.body.appendChild(document.createTextNode('test'));+ document.execCommand('selectAll');+ return document.execCommand('copy');+ });+ expect(result).toBe(true);+ });+ it('should throw a nice error after a navigation', async({page, server}) => {+ const executionContext = await page.mainFrame().executionContext();++ await Promise.all([+ page.waitForNavigation(),+ executionContext.evaluate(() => window.location.reload())+ ]);+ const error = await executionContext.evaluate(() => null).catch(e => e);+ expect(error.message).toContain('navigation');+ });+ it.skip(FFOX)('should not throw an error when evaluation does a navigation', async({page, server}) => {+ await page.goto(server.PREFIX + '/one-style.html');+ const result = await page.evaluate(() => {+ window.location = '/empty.html';+ return [42];+ });+ expect(result).toEqual([42]);+ });+ // Works in WebKit, but slow+ it.skip(FFOX || WEBKIT)('should transfer 100Mb of data from page to node.js', async({page, server}) => {+ const a = await page.evaluate(() => Array(100 * 1024 * 1024 + 1).join('a'));+ expect(a.length).toBe(100 * 1024 * 1024);+ });+ it('should throw error with detailed information on exception inside promise ', async({page, server}) => {+ let error = null;+ await page.evaluate(() => new Promise(() => {+ throw new Error('Error in promise');+ })).catch(e => error = e);+ expect(error.message).toContain('Error in promise');+ });+ });++ describe.skip(WEBKIT)('Page.evaluateOnNewDocument', function() {+ it('should evaluate before anything else on the page', async({page, server}) => {+ await page.evaluateOnNewDocument(function(){+ window.injected = 123;+ });+ await page.goto(server.PREFIX + '/tamperable.html');+ expect(await page.evaluate(() => window.result)).toBe(123);+ });+ it('should work with CSP', async({page, server}) => {+ server.setCSP('/empty.html', 'script-src ' + server.PREFIX);+ await page.evaluateOnNewDocument(function(){+ window.injected = 123;+ });+ await page.goto(server.PREFIX + '/empty.html');+ expect(await page.evaluate(() => window.injected)).toBe(123);++ // Make sure CSP works.+ await page.addScriptTag({content: 'window.e = 10;'}).catch(e => void e);+ expect(await page.evaluate(() => window.e)).toBe(undefined);+ });+ });++ describe('Frame.evaluate', function() {+ it('should have different execution contexts', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ expect(page.frames().length).toBe(2);+ await page.frames()[0].evaluate(() => window.FOO = 'foo');+ await page.frames()[1].evaluate(() => window.FOO = 'bar');+ expect(await page.frames()[0].evaluate(() => window.FOO)).toBe('foo');+ expect(await page.frames()[1].evaluate(() => window.FOO)).toBe('bar');+ });+ it('should have correct execution contexts', async({page, server}) => {+ await page.goto(server.PREFIX + '/frames/one-frame.html');+ expect(page.frames().length).toBe(2);+ expect(await page.frames()[0].evaluate(() => document.body.textContent.trim())).toBe('');+ expect(await page.frames()[1].evaluate(() => document.body.textContent.trim())).toBe(`Hi, I'm frame`);+ });+ it('should execute after cross-site navigation', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const mainFrame = page.mainFrame();+ expect(await mainFrame.evaluate(() => window.location.href)).toContain('localhost');+ await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html');+ expect(await mainFrame.evaluate(() => window.location.href)).toContain('127');+ });+ });+};diff --git a/test/fixtures.spec.js b/test/fixtures.spec.jsnew file mode 100644index 0000000000..17230a3f20--- /dev/null+++ b/test/fixtures.spec.js@@ -0,0 +1,79 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const path = require('path');++module.exports.addTests = function({testRunner, expect, defaultBrowserOptions, playwright, playwrightPath, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe.skip(WEBKIT)('Fixtures', function() {+ it.skip(FFOX)('dumpio option should work with pipe option ', async({server}) => {+ let dumpioData = '';+ const {spawn} = require('child_process');+ const options = Object.assign({}, defaultBrowserOptions, {pipe: true, dumpio: true});+ const res = spawn('node',+ [path.join(__dirname, 'fixtures', 'dumpio.js'), playwrightPath, JSON.stringify(options)]);+ res.stderr.on('data', data => dumpioData += data.toString('utf8'));+ await new Promise(resolve => res.on('close', resolve));+ expect(dumpioData).toContain('message from dumpio');+ });+ it('should dump browser process stderr', async({server}) => {+ let dumpioData = '';+ const {spawn} = require('child_process');+ const options = Object.assign({}, defaultBrowserOptions, {dumpio: true});+ const res = spawn('node',+ [path.join(__dirname, 'fixtures', 'dumpio.js'), playwrightPath, JSON.stringify(options)]);+ if (CHROME || WEBKIT)+ res.stderr.on('data', data => dumpioData += data.toString('utf8'));+ else+ res.stdout.on('data', data => dumpioData += data.toString('utf8'));+ await new Promise(resolve => res.on('close', resolve));++ if (CHROME || WEBKIT)+ expect(dumpioData).toContain('DevTools listening on ws://');+ else+ expect(dumpioData).toContain('Juggler listening on ws://');+ });+ it('should close the browser when the node process closes', async({ server }) => {+ const {spawn, execSync} = require('child_process');+ const options = Object.assign({}, defaultBrowserOptions, {+ // Disable DUMPIO to cleanly read stdout.+ dumpio: false,+ });+ const res = spawn('node', [path.join(__dirname, 'fixtures', 'closeme.js'), playwrightPath, JSON.stringify(options)]);+ let wsEndPointCallback;+ const wsEndPointPromise = new Promise(x => wsEndPointCallback = x);+ let output = '';+ res.stdout.on('data', data => {+ output += data;+ if (output.indexOf('\n'))+ wsEndPointCallback(output.substring(0, output.indexOf('\n')));+ });+ const browser = await playwright.connect({ browserWSEndpoint: await wsEndPointPromise });+ const promises = [+ new Promise(resolve => browser.once('disconnected', resolve)),+ new Promise(resolve => res.on('close', resolve))+ ];+ if (process.platform === 'win32')+ execSync(`taskkill /pid ${res.pid} /T /F`);+ else+ process.kill(res.pid);+ await Promise.all(promises);+ });+ });+};diff --git a/test/fixtures/closeme.js b/test/fixtures/closeme.jsnew file mode 100644index 0000000000..d80de2dce3--- /dev/null+++ b/test/fixtures/closeme.js@@ -0,0 +1,5 @@+(async() => {+ const [, , playwrightRoot, options] = process.argv;+ const browser = await require(playwrightRoot).launch(JSON.parse(options));+ console.log(browser.wsEndpoint());+})();diff --git a/test/fixtures/dumpio.js b/test/fixtures/dumpio.jsnew file mode 100644index 0000000000..b20fd6b8ff--- /dev/null+++ b/test/fixtures/dumpio.js@@ -0,0 +1,8 @@+(async() => {+ const [, , playwrightRoot, options] = process.argv;+ const browser = await require(playwrightRoot).launch(JSON.parse(options));+ const page = await browser.newPage();+ await page.evaluate(() => console.error('message from dumpio'));+ await page.close();+ await browser.close();+})();diff --git a/test/frame.spec.js b/test/frame.spec.jsnew file mode 100644index 0000000000..e2d9be5f95--- /dev/null+++ b/test/frame.spec.js@@ -0,0 +1,211 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const utils = require('./utils');++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Frame.executionContext', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ expect(page.frames().length).toBe(2);+ const [frame1, frame2] = page.frames();+ const context1 = await frame1.executionContext();+ const context2 = await frame2.executionContext();+ expect(context1).toBeTruthy();+ expect(context2).toBeTruthy();+ expect(context1 !== context2).toBeTruthy();+ expect(context1.frame()).toBe(frame1);+ expect(context2.frame()).toBe(frame2);++ await Promise.all([+ context1.evaluate(() => window.a = 1),+ context2.evaluate(() => window.a = 2)+ ]);+ const [a1, a2] = await Promise.all([+ context1.evaluate(() => window.a),+ context2.evaluate(() => window.a)+ ]);+ expect(a1).toBe(1);+ expect(a2).toBe(2);+ });+ });++ describe('Frame.evaluateHandle', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const mainFrame = page.mainFrame();+ const windowHandle = await mainFrame.evaluateHandle(() => window);+ expect(windowHandle).toBeTruthy();+ });+ });++ describe('Frame.evaluate', function() {+ it.skip(FFOX)('should throw for detached frames', async({page, server}) => {+ const frame1 = await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ await utils.detachFrame(page, 'frame1');+ let error = null;+ await frame1.evaluate(() => 7 * 8).catch(e => error = e);+ expect(error.message).toContain('Execution Context is not available in detached frame');+ });+ });++ describe('Frame Management', function() {+ it.skip(WEBKIT)('should handle nested frames', async({page, server}) => {+ await page.goto(server.PREFIX + '/frames/nested-frames.html');+ expect(utils.dumpFrames(page.mainFrame())).toEqual([+ 'http://localhost:<PORT>/frames/nested-frames.html',+ ' http://localhost:<PORT>/frames/two-frames.html (2frames)',+ ' http://localhost:<PORT>/frames/frame.html (uno)',+ ' http://localhost:<PORT>/frames/frame.html (dos)',+ ' http://localhost:<PORT>/frames/frame.html (aframe)'+ ]);+ });+ it('should send events when frames are manipulated dynamically', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ // validate frameattached events+ const attachedFrames = [];+ page.on('frameattached', frame => attachedFrames.push(frame));+ await utils.attachFrame(page, 'frame1', './assets/frame.html');+ expect(attachedFrames.length).toBe(1);+ expect(attachedFrames[0].url()).toContain('/assets/frame.html');++ // validate framenavigated events+ const navigatedFrames = [];+ page.on('framenavigated', frame => navigatedFrames.push(frame));+ await utils.navigateFrame(page, 'frame1', './empty.html');+ expect(navigatedFrames.length).toBe(1);+ expect(navigatedFrames[0].url()).toBe(server.EMPTY_PAGE);++ // validate framedetached events+ const detachedFrames = [];+ page.on('framedetached', frame => detachedFrames.push(frame));+ await utils.detachFrame(page, 'frame1');+ expect(detachedFrames.length).toBe(1);+ expect(detachedFrames[0].isDetached()).toBe(true);+ });+ it.skip(WEBKIT)('should send "framenavigated" when navigating on anchor URLs', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await Promise.all([+ page.goto(server.EMPTY_PAGE + '#foo'),+ utils.waitEvent(page, 'framenavigated')+ ]);+ expect(page.url()).toBe(server.EMPTY_PAGE + '#foo');+ });+ it('should persist mainFrame on cross-process navigation', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const mainFrame = page.mainFrame();+ await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html');+ expect(page.mainFrame() === mainFrame).toBeTruthy();+ });+ it('should not send attach/detach events for main frame', async({page, server}) => {+ let hasEvents = false;+ page.on('frameattached', frame => hasEvents = true);+ page.on('framedetached', frame => hasEvents = true);+ await page.goto(server.EMPTY_PAGE);+ expect(hasEvents).toBe(false);+ });+ it('should detach child frames on navigation', async({page, server}) => {+ let attachedFrames = [];+ let detachedFrames = [];+ let navigatedFrames = [];+ page.on('frameattached', frame => attachedFrames.push(frame));+ page.on('framedetached', frame => detachedFrames.push(frame));+ page.on('framenavigated', frame => navigatedFrames.push(frame));+ await page.goto(server.PREFIX + '/frames/nested-frames.html');+ expect(attachedFrames.length).toBe(4);+ expect(detachedFrames.length).toBe(0);+ expect(navigatedFrames.length).toBe(5);++ attachedFrames = [];+ detachedFrames = [];+ navigatedFrames = [];+ await page.goto(server.EMPTY_PAGE);+ expect(attachedFrames.length).toBe(0);+ expect(detachedFrames.length).toBe(4);+ expect(navigatedFrames.length).toBe(1);+ });+ it('should support framesets', async({page, server}) => {+ let attachedFrames = [];+ let detachedFrames = [];+ let navigatedFrames = [];+ page.on('frameattached', frame => attachedFrames.push(frame));+ page.on('framedetached', frame => detachedFrames.push(frame));+ page.on('framenavigated', frame => navigatedFrames.push(frame));+ await page.goto(server.PREFIX + '/frames/frameset.html');+ expect(attachedFrames.length).toBe(4);+ expect(detachedFrames.length).toBe(0);+ expect(navigatedFrames.length).toBe(5);++ attachedFrames = [];+ detachedFrames = [];+ navigatedFrames = [];+ await page.goto(server.EMPTY_PAGE);+ expect(attachedFrames.length).toBe(0);+ expect(detachedFrames.length).toBe(4);+ expect(navigatedFrames.length).toBe(1);+ });+ it('should report frame from-inside shadow DOM', async({page, server}) => {+ await page.goto(server.PREFIX + '/shadow.html');+ await page.evaluate(async url => {+ const frame = document.createElement('iframe');+ frame.src = url;+ document.body.shadowRoot.appendChild(frame);+ await new Promise(x => frame.onload = x);+ }, server.EMPTY_PAGE);+ expect(page.frames().length).toBe(2);+ expect(page.frames()[1].url()).toBe(server.EMPTY_PAGE);+ });+ it('should report frame.name()', async({page, server}) => {+ await utils.attachFrame(page, 'theFrameId', server.EMPTY_PAGE);+ await page.evaluate(url => {+ const frame = document.createElement('iframe');+ frame.name = 'theFrameName';+ frame.src = url;+ document.body.appendChild(frame);+ return new Promise(x => frame.onload = x);+ }, server.EMPTY_PAGE);+ expect(page.frames()[0].name()).toBe('');+ expect(page.frames()[1].name()).toBe('theFrameId');+ expect(page.frames()[2].name()).toBe('theFrameName');+ });+ it('should report frame.parent()', async({page, server}) => {+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);+ expect(page.frames()[0].parentFrame()).toBe(null);+ expect(page.frames()[1].parentFrame()).toBe(page.mainFrame());+ expect(page.frames()[2].parentFrame()).toBe(page.mainFrame());+ });+ it('should report different frame instance when frame re-attaches', async({page, server}) => {+ const frame1 = await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ await page.evaluate(() => {+ window.frame = document.querySelector('#frame1');+ window.frame.remove();+ });+ expect(frame1.isDetached()).toBe(true);+ const [frame2] = await Promise.all([+ utils.waitEvent(page, 'frameattached'),+ page.evaluate(() => document.body.appendChild(window.frame)),+ ]);+ expect(frame2.isDetached()).toBe(false);+ expect(frame1).not.toBe(frame2);+ });+ });+};diff --git a/test/golden-chromium/csscoverage-involved.txt b/test/golden-chromium/csscoverage-involved.txtnew file mode 100644index 0000000000..9b851d0bd3--- /dev/null+++ b/test/golden-chromium/csscoverage-involved.txt@@ -0,0 +1,16 @@+[+ {+ "url": "http://localhost:<PORT>/csscoverage/involved.html",+ "ranges": [+ {+ "start": 149,+ "end": 297+ },+ {+ "start": 327,+ "end": 433+ }+ ],+ "text": "\n@charset \"utf-8\";\n@namespace svg url(http://www.w3.org/2000/svg);\n@font-face {\n font-family: \"Example Font\";\n src: url(\"./Dosis-Regular.ttf\");\n}\n\n#fluffy {\n border: 1px solid black;\n z-index: 1;\n /* -webkit-disabled-property: rgb(1, 2, 3) */\n -lol-cats: \"dogs\" /* non-existing property */\n}\n\n@media (min-width: 1px) {\n span {\n -webkit-border-radius: 10px;\n font-family: \"Example Font\";\n animation: 1s identifier;\n }\n}\n"+ }+]\ No newline at end of filediff --git a/test/golden-chromium/grid-cell-0.png b/test/golden-chromium/grid-cell-0.pngnew file mode 100644index 0000000000..ff282e989bBinary files /dev/null and b/test/golden-chromium/grid-cell-0.png differdiff --git a/test/golden-chromium/grid-cell-1.png b/test/golden-chromium/grid-cell-1.pngnew file mode 100644index 0000000000..91a1cb8510Binary files /dev/null and b/test/golden-chromium/grid-cell-1.png differdiff --git a/test/golden-chromium/grid-cell-2.png b/test/golden-chromium/grid-cell-2.pngnew file mode 100644index 0000000000..7b01753b6aBinary files /dev/null and b/test/golden-chromium/grid-cell-2.png differdiff --git a/test/golden-chromium/grid-cell-3.png b/test/golden-chromium/grid-cell-3.pngnew file mode 100644index 0000000000..b9b8b2922bBinary files /dev/null and b/test/golden-chromium/grid-cell-3.png differdiff --git a/test/golden-chromium/jscoverage-involved.txt b/test/golden-chromium/jscoverage-involved.txtnew file mode 100644index 0000000000..6f28e1580e--- /dev/null+++ b/test/golden-chromium/jscoverage-involved.txt@@ -0,0 +1,28 @@+[+ {+ "url": "http://localhost:<PORT>/jscoverage/involved.html",+ "ranges": [+ {+ "start": 0,+ "end": 35+ },+ {+ "start": 50,+ "end": 100+ },+ {+ "start": 107,+ "end": 141+ },+ {+ "start": 148,+ "end": 160+ },+ {+ "start": 168,+ "end": 207+ }+ ],+ "text": "\nfunction foo() {\n if (1 > 2)\n console.log(1);\n if (1 < 2)\n console.log(2);\n let x = 1 > 2 ? 'foo' : 'bar';\n let y = 1 < 2 ? 'foo' : 'bar';\n let z = () => {};\n let q = () => {};\n q();\n}\n\nfoo();\n"+ }+]\ No newline at end of filediff --git a/test/golden-chromium/mock-binary-response.png b/test/golden-chromium/mock-binary-response.pngnew file mode 100644index 0000000000..8595e0598eBinary files /dev/null and b/test/golden-chromium/mock-binary-response.png differdiff --git a/test/golden-chromium/screenshot-clip-odd-size.png b/test/golden-chromium/screenshot-clip-odd-size.pngnew file mode 100644index 0000000000..b010d1f87fBinary files /dev/null and b/test/golden-chromium/screenshot-clip-odd-size.png differdiff --git a/test/golden-chromium/screenshot-clip-rect.png b/test/golden-chromium/screenshot-clip-rect.pngnew file mode 100644index 0000000000..ac23b7de50Binary files /dev/null and b/test/golden-chromium/screenshot-clip-rect.png differdiff --git a/test/golden-chromium/screenshot-element-bounding-box.png b/test/golden-chromium/screenshot-element-bounding-box.pngnew file mode 100644index 0000000000..32e05bf05bBinary files /dev/null and b/test/golden-chromium/screenshot-element-bounding-box.png differdiff --git a/test/golden-chromium/screenshot-element-fractional-offset.png b/test/golden-chromium/screenshot-element-fractional-offset.pngnew file mode 100644index 0000000000..cc8669d598Binary files /dev/null and b/test/golden-chromium/screenshot-element-fractional-offset.png differdiff --git a/test/golden-chromium/screenshot-element-fractional.png b/test/golden-chromium/screenshot-element-fractional.pngnew file mode 100644index 0000000000..35c53377f9Binary files /dev/null and b/test/golden-chromium/screenshot-element-fractional.png differdiff --git a/test/golden-chromium/screenshot-element-larger-than-viewport.png b/test/golden-chromium/screenshot-element-larger-than-viewport.pngnew file mode 100644index 0000000000..5fcdb92355Binary files /dev/null and b/test/golden-chromium/screenshot-element-larger-than-viewport.png differdiff --git a/test/golden-chromium/screenshot-element-padding-border.png b/test/golden-chromium/screenshot-element-padding-border.pngnew file mode 100644index 0000000000..917dd48188Binary files /dev/null and b/test/golden-chromium/screenshot-element-padding-border.png differdiff --git a/test/golden-chromium/screenshot-element-rotate.png b/test/golden-chromium/screenshot-element-rotate.pngnew file mode 100644index 0000000000..52e2a0f6d3Binary files /dev/null and b/test/golden-chromium/screenshot-element-rotate.png differdiff --git a/test/golden-chromium/screenshot-element-scrolled-into-view.png b/test/golden-chromium/screenshot-element-scrolled-into-view.pngnew file mode 100644index 0000000000..917dd48188Binary files /dev/null and b/test/golden-chromium/screenshot-element-scrolled-into-view.png differdiff --git a/test/golden-chromium/screenshot-grid-fullpage.png b/test/golden-chromium/screenshot-grid-fullpage.pngnew file mode 100644index 0000000000..d6d38217f7Binary files /dev/null and b/test/golden-chromium/screenshot-grid-fullpage.png differdiff --git a/test/golden-chromium/screenshot-offscreen-clip.png b/test/golden-chromium/screenshot-offscreen-clip.pngnew file mode 100644index 0000000000..31a0935cdaBinary files /dev/null and b/test/golden-chromium/screenshot-offscreen-clip.png differdiff --git a/test/golden-chromium/screenshot-sanity.png b/test/golden-chromium/screenshot-sanity.pngnew file mode 100644index 0000000000..ecab61fe17Binary files /dev/null and b/test/golden-chromium/screenshot-sanity.png differdiff --git a/test/golden-chromium/transparent.png b/test/golden-chromium/transparent.pngnew file mode 100644index 0000000000..1cf45d8688Binary files /dev/null and b/test/golden-chromium/transparent.png differdiff --git a/test/golden-chromium/white.jpg b/test/golden-chromium/white.jpgnew file mode 100644index 0000000000..fb9070def3Binary files /dev/null and b/test/golden-chromium/white.jpg differdiff --git a/test/golden-firefox/grid-cell-0.png b/test/golden-firefox/grid-cell-0.pngnew file mode 100644index 0000000000..4677bdbc4fBinary files /dev/null and b/test/golden-firefox/grid-cell-0.png differdiff --git a/test/golden-firefox/grid-cell-1.png b/test/golden-firefox/grid-cell-1.pngnew file mode 100644index 0000000000..532dc8db65Binary files /dev/null and b/test/golden-firefox/grid-cell-1.png differdiff --git a/test/golden-firefox/screenshot-clip-odd-size.png b/test/golden-firefox/screenshot-clip-odd-size.pngnew file mode 100644index 0000000000..8e86dc9017Binary files /dev/null and b/test/golden-firefox/screenshot-clip-odd-size.png differdiff --git a/test/golden-firefox/screenshot-clip-rect.png b/test/golden-firefox/screenshot-clip-rect.pngnew file mode 100644index 0000000000..7a74457869Binary files /dev/null and b/test/golden-firefox/screenshot-clip-rect.png differdiff --git a/test/golden-firefox/screenshot-element-bounding-box.png b/test/golden-firefox/screenshot-element-bounding-box.pngnew file mode 100644index 0000000000..f4e059c300Binary files /dev/null and b/test/golden-firefox/screenshot-element-bounding-box.png differdiff --git a/test/golden-firefox/screenshot-element-fractional-offset.png b/test/golden-firefox/screenshot-element-fractional-offset.pngnew file mode 100644index 0000000000..f554b1d62cBinary files /dev/null and b/test/golden-firefox/screenshot-element-fractional-offset.png differdiff --git a/test/golden-firefox/screenshot-element-fractional.png b/test/golden-firefox/screenshot-element-fractional.pngnew file mode 100644index 0000000000..d1431bd91dBinary files /dev/null and b/test/golden-firefox/screenshot-element-fractional.png differdiff --git a/test/golden-firefox/screenshot-element-larger-than-viewport.png b/test/golden-firefox/screenshot-element-larger-than-viewport.pngnew file mode 100644index 0000000000..6d28cddceaBinary files /dev/null and b/test/golden-firefox/screenshot-element-larger-than-viewport.png differdiff --git a/test/golden-firefox/screenshot-element-padding-border.png b/test/golden-firefox/screenshot-element-padding-border.pngnew file mode 100644index 0000000000..2b72c7528bBinary files /dev/null and b/test/golden-firefox/screenshot-element-padding-border.png differdiff --git a/test/golden-firefox/screenshot-element-rotate.png b/test/golden-firefox/screenshot-element-rotate.pngnew file mode 100644index 0000000000..0a78fb1ae7Binary files /dev/null and b/test/golden-firefox/screenshot-element-rotate.png differdiff --git a/test/golden-firefox/screenshot-element-scrolled-into-view.png b/test/golden-firefox/screenshot-element-scrolled-into-view.pngnew file mode 100644index 0000000000..2b72c7528bBinary files /dev/null and b/test/golden-firefox/screenshot-element-scrolled-into-view.png differdiff --git a/test/golden-firefox/screenshot-grid-fullpage.png b/test/golden-firefox/screenshot-grid-fullpage.pngnew file mode 100644index 0000000000..ac47ec83b1Binary files /dev/null and b/test/golden-firefox/screenshot-grid-fullpage.png differdiff --git a/test/golden-firefox/screenshot-offscreen-clip.png b/test/golden-firefox/screenshot-offscreen-clip.pngnew file mode 100644index 0000000000..31a0935cdaBinary files /dev/null and b/test/golden-firefox/screenshot-offscreen-clip.png differdiff --git a/test/golden-firefox/screenshot-sanity.png b/test/golden-firefox/screenshot-sanity.pngnew file mode 100644index 0000000000..07890a04b3Binary files /dev/null and b/test/golden-firefox/screenshot-sanity.png differdiff --git a/test/golden-utils.js b/test/golden-utils.jsnew file mode 100644index 0000000000..86989ac654--- /dev/null+++ b/test/golden-utils.js@@ -0,0 +1,149 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+const path = require('path');+const fs = require('fs');+const Diff = require('text-diff');+const mime = require('mime');+const PNG = require('pngjs').PNG;+const jpeg = require('jpeg-js');+const pixelmatch = require('pixelmatch');++module.exports = {compare};++const GoldenComparators = {+ 'image/png': compareImages,+ 'image/jpeg': compareImages,+ 'text/plain': compareText+};+++/**+ * @param {?Object} actualBuffer+ * @param {!Buffer} expectedBuffer+ * @param {!string} mimeType+ * @return {?{diff: (!Object:undefined), errorMessage: (string|undefined)}}+ */+function compareImages(actualBuffer, expectedBuffer, mimeType) {+ if (!actualBuffer || !(actualBuffer instanceof Buffer))+ return { errorMessage: 'Actual result should be Buffer.' };++ const actual = mimeType === 'image/png' ? PNG.sync.read(actualBuffer) : jpeg.decode(actualBuffer);+ const expected = mimeType === 'image/png' ? PNG.sync.read(expectedBuffer) : jpeg.decode(expectedBuffer);+ if (expected.width !== actual.width || expected.height !== actual.height) {+ return {+ errorMessage: `Sizes differ: expected image ${expected.width}px X ${expected.height}px, but got ${actual.width}px X ${actual.height}px. `+ };+ }+ const diff = new PNG({width: expected.width, height: expected.height});+ const count = pixelmatch(expected.data, actual.data, diff.data, expected.width, expected.height, {threshold: 0.1});+ return count > 0 ? { diff: PNG.sync.write(diff) } : null;+}++/**+ * @param {?Object} actual+ * @param {!Buffer} expectedBuffer+ * @return {?{diff: (!Object:undefined), errorMessage: (string|undefined)}}+ */+function compareText(actual, expectedBuffer) {+ if (typeof actual !== 'string')+ return { errorMessage: 'Actual result should be string' };+ const expected = expectedBuffer.toString('utf-8');+ if (expected === actual)+ return null;+ const diff = new Diff();+ const result = diff.main(expected, actual);+ diff.cleanupSemantic(result);+ let html = diff.prettyHtml(result);+ const diffStylePath = path.join(__dirname, 'diffstyle.css');+ html = `<link rel="stylesheet" href="file://${diffStylePath}">` + html;+ return {+ diff: html,+ diffExtension: '.html'+ };+}++/**+ * @param {?Object} actual+ * @param {string} goldenName+ * @return {!{pass: boolean, message: (undefined|string)}}+ */+function compare(goldenPath, outputPath, actual, goldenName) {+ goldenPath = path.normalize(goldenPath);+ outputPath = path.normalize(outputPath);+ const expectedPath = path.join(goldenPath, goldenName);+ const actualPath = path.join(outputPath, goldenName);++ const messageSuffix = 'Output is saved in "' + path.basename(outputPath + '" directory');++ if (!fs.existsSync(expectedPath)) {+ ensureOutputDir();+ fs.writeFileSync(actualPath, actual);+ return {+ pass: false,+ message: goldenName + ' is missing in golden results. ' + messageSuffix+ };+ }+ const expected = fs.readFileSync(expectedPath);+ const mimeType = mime.getType(goldenName);+ const comparator = GoldenComparators[mimeType];+ if (!comparator) {+ return {+ pass: false,+ message: 'Failed to find comparator with type ' + mimeType + ': ' + goldenName+ };+ }+ const result = comparator(actual, expected, mimeType);+ if (!result)+ return { pass: true };+ ensureOutputDir();+ if (goldenPath === outputPath) {+ fs.writeFileSync(addSuffix(actualPath, '-actual'), actual);+ } else {+ fs.writeFileSync(actualPath, actual);+ // Copy expected to the output/ folder for convenience.+ fs.writeFileSync(addSuffix(actualPath, '-expected'), expected);+ }+ if (result.diff) {+ const diffPath = addSuffix(actualPath, '-diff', result.diffExtension);+ fs.writeFileSync(diffPath, result.diff);+ }++ let message = goldenName + ' mismatch!';+ if (result.errorMessage)+ message += ' ' + result.errorMessage;+ return {+ pass: false,+ message: message + ' ' + messageSuffix+ };++ function ensureOutputDir() {+ if (!fs.existsSync(outputPath))+ fs.mkdirSync(outputPath);+ }+}++/**+ * @param {string} filePath+ * @param {string} suffix+ * @param {string=} customExtension+ * @return {string}+ */+function addSuffix(filePath, suffix, customExtension) {+ const dirname = path.dirname(filePath);+ const ext = path.extname(filePath);+ const name = path.basename(filePath, ext);+ return path.join(dirname, name + suffix + (customExtension || ext));+}diff --git a/test/golden-webkit/grid-cell-0.png b/test/golden-webkit/grid-cell-0.pngnew file mode 100644index 0000000000..5ae546557bBinary files /dev/null and b/test/golden-webkit/grid-cell-0.png differdiff --git a/test/golden-webkit/grid-cell-1.png b/test/golden-webkit/grid-cell-1.pngnew file mode 100644index 0000000000..1110528326Binary files /dev/null and b/test/golden-webkit/grid-cell-1.png differdiff --git a/test/golden-webkit/screenshot-clip-odd-size.png b/test/golden-webkit/screenshot-clip-odd-size.pngnew file mode 100644index 0000000000..27a2b2807fBinary files /dev/null and b/test/golden-webkit/screenshot-clip-odd-size.png differdiff --git a/test/golden-webkit/screenshot-clip-rect.png b/test/golden-webkit/screenshot-clip-rect.pngnew file mode 100644index 0000000000..3217645a36Binary files /dev/null and b/test/golden-webkit/screenshot-clip-rect.png differdiff --git a/test/golden-webkit/screenshot-element-bounding-box.png b/test/golden-webkit/screenshot-element-bounding-box.pngnew file mode 100644index 0000000000..5b07911c66Binary files /dev/null and b/test/golden-webkit/screenshot-element-bounding-box.png differdiff --git a/test/golden-webkit/screenshot-element-fractional-offset.png b/test/golden-webkit/screenshot-element-fractional-offset.pngnew file mode 100644index 0000000000..c9e0eb15e9Binary files /dev/null and b/test/golden-webkit/screenshot-element-fractional-offset.png differdiff --git a/test/golden-webkit/screenshot-element-fractional.png b/test/golden-webkit/screenshot-element-fractional.pngnew file mode 100644index 0000000000..390ef19d2eBinary files /dev/null and b/test/golden-webkit/screenshot-element-fractional.png differdiff --git a/test/golden-webkit/screenshot-element-larger-than-viewport.png b/test/golden-webkit/screenshot-element-larger-than-viewport.pngnew file mode 100644index 0000000000..bea66e69e8Binary files /dev/null and b/test/golden-webkit/screenshot-element-larger-than-viewport.png differdiff --git a/test/golden-webkit/screenshot-element-padding-border.png b/test/golden-webkit/screenshot-element-padding-border.pngnew file mode 100644index 0000000000..7260617ec2Binary files /dev/null and b/test/golden-webkit/screenshot-element-padding-border.png differdiff --git a/test/golden-webkit/screenshot-element-scrolled-into-view.png b/test/golden-webkit/screenshot-element-scrolled-into-view.pngnew file mode 100644index 0000000000..7260617ec2Binary files /dev/null and b/test/golden-webkit/screenshot-element-scrolled-into-view.png differdiff --git a/test/golden-webkit/screenshot-grid-fullpage.png b/test/golden-webkit/screenshot-grid-fullpage.pngnew file mode 100644index 0000000000..142de08133Binary files /dev/null and b/test/golden-webkit/screenshot-grid-fullpage.png differdiff --git a/test/golden-webkit/screenshot-offscreen-clip.png b/test/golden-webkit/screenshot-offscreen-clip.pngnew file mode 100644index 0000000000..fa7bfdc3e3Binary files /dev/null and b/test/golden-webkit/screenshot-offscreen-clip.png differdiff --git a/test/golden-webkit/screenshot-sanity.png b/test/golden-webkit/screenshot-sanity.pngnew file mode 100644index 0000000000..fc41e344f9Binary files /dev/null and b/test/golden-webkit/screenshot-sanity.png differdiff --git a/test/golden-webkit/transparent.png b/test/golden-webkit/transparent.pngnew file mode 100644index 0000000000..47adcb4de0Binary files /dev/null and b/test/golden-webkit/transparent.png differdiff --git a/test/headful.spec.js b/test/headful.spec.jsnew file mode 100644index 0000000000..61ab37c602--- /dev/null+++ b/test/headful.spec.js@@ -0,0 +1,152 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const path = require('path');+const os = require('os');+const fs = require('fs');+const util = require('util');+const utils = require('./utils');+const {waitEvent} = utils;++const rmAsync = util.promisify(require('rimraf'));+const mkdtempAsync = util.promisify(fs.mkdtemp);++const TMP_FOLDER = path.join(os.tmpdir(), 'pptr_tmp_folder-');++module.exports.addTests = function({testRunner, expect, playwright, defaultBrowserOptions, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ const headfulOptions = Object.assign({}, defaultBrowserOptions, {+ headless: false+ });+ const headlessOptions = Object.assign({}, defaultBrowserOptions, {+ headless: true+ });+ const extensionPath = path.join(__dirname, 'assets', 'simple-extension');+ const extensionOptions = Object.assign({}, defaultBrowserOptions, {+ headless: false,+ args: [+ `--disable-extensions-except=${extensionPath}`,+ `--load-extension=${extensionPath}`,+ ],+ });++ describe('HEADFUL', function() {+ it('background_page target type should be available', async() => {+ const browserWithExtension = await playwright.launch(extensionOptions);+ const page = await browserWithExtension.newPage();+ const backgroundPageTarget = await browserWithExtension.waitForTarget(target => target.type() === 'background_page');+ await page.close();+ await browserWithExtension.close();+ expect(backgroundPageTarget).toBeTruthy();+ });+ it('target.page() should return a background_page', async({}) => {+ const browserWithExtension = await playwright.launch(extensionOptions);+ const backgroundPageTarget = await browserWithExtension.waitForTarget(target => target.type() === 'background_page');+ const page = await backgroundPageTarget.page();+ expect(await page.evaluate(() => 2 * 3)).toBe(6);+ expect(await page.evaluate(() => window.MAGIC)).toBe(42);+ await browserWithExtension.close();+ });+ it('should have default url when launching browser', async function() {+ const browser = await playwright.launch(extensionOptions);+ const pages = (await browser.pages()).map(page => page.url());+ expect(pages).toEqual(['about:blank']);+ await browser.close();+ });+ it('headless should be able to read cookies written by headful', async({server}) => {+ const userDataDir = await mkdtempAsync(TMP_FOLDER);+ // Write a cookie in headful chrome+ const headfulBrowser = await playwright.launch(Object.assign({userDataDir}, headfulOptions));+ const headfulPage = await headfulBrowser.newPage();+ await headfulPage.goto(server.EMPTY_PAGE);+ await headfulPage.evaluate(() => document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT');+ await headfulBrowser.close();+ // Read the cookie from headless chrome+ const headlessBrowser = await playwright.launch(Object.assign({userDataDir}, headlessOptions));+ const headlessPage = await headlessBrowser.newPage();+ await headlessPage.goto(server.EMPTY_PAGE);+ const cookie = await headlessPage.evaluate(() => document.cookie);+ await headlessBrowser.close();+ // This might throw. See https://github.com/GoogleChrome/puppeteer/issues/2778+ await rmAsync(userDataDir).catch(e => {});+ expect(cookie).toBe('foo=true');+ });+ // TODO: Support OOOPIF. @see https://github.com/GoogleChrome/puppeteer/issues/2548+ xit('OOPIF: should report google.com frame', async({server}) => {+ // https://google.com is isolated by default in Chromium embedder.+ const browser = await playwright.launch(headfulOptions);+ const page = await browser.newPage();+ await page.goto(server.EMPTY_PAGE);+ await page.setRequestInterception(true);+ page.on('request', r => r.respond({body: 'YO, GOOGLE.COM'}));+ await page.evaluate(() => {+ const frame = document.createElement('iframe');+ frame.setAttribute('src', 'https://google.com/');+ document.body.appendChild(frame);+ return new Promise(x => frame.onload = x);+ });+ await page.waitForSelector('iframe[src="https://google.com/"]');+ const urls = page.frames().map(frame => frame.url()).sort();+ expect(urls).toEqual([+ server.EMPTY_PAGE,+ 'https://google.com/'+ ]);+ await browser.close();+ });+ it('should close browser with beforeunload page', async({server}) => {+ const browser = await playwright.launch(headfulOptions);+ const page = await browser.newPage();+ await page.goto(server.PREFIX + '/beforeunload.html');+ // We have to interact with a page so that 'beforeunload' handlers+ // fire.+ await page.click('body');+ await browser.close();+ });+ it('should open devtools when "devtools: true" option is given', async({server}) => {+ const browser = await playwright.launch(Object.assign({devtools: true}, headfulOptions));+ const context = await browser.createIncognitoBrowserContext();+ await Promise.all([+ context.newPage(),+ context.waitForTarget(target => target.url().includes('devtools://')),+ ]);+ await browser.close();+ });+ });++ describe('Page.bringToFront', function() {+ it('should work', async() => {+ const browser = await playwright.launch(headfulOptions);+ const page1 = await browser.newPage();+ const page2 = await browser.newPage();++ await page1.bringToFront();+ expect(await page1.evaluate(() => document.visibilityState)).toBe('visible');+ expect(await page2.evaluate(() => document.visibilityState)).toBe('hidden');++ await page2.bringToFront();+ expect(await page1.evaluate(() => document.visibilityState)).toBe('hidden');+ expect(await page2.evaluate(() => document.visibilityState)).toBe('visible');++ await page1.close();+ await page2.close();+ await browser.close();+ });+ });+};+diff --git a/test/ignorehttpserrors.spec.js b/test/ignorehttpserrors.spec.jsnew file mode 100644index 0000000000..0d25fd280d--- /dev/null+++ b/test/ignorehttpserrors.spec.js@@ -0,0 +1,97 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, defaultBrowserOptions, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;+ describe.skip(WEBKIT)('ignoreHTTPSErrors', function() {+ beforeAll(async state => {+ state.browser = await playwright.launch({...defaultBrowserOptions, ignoreHTTPSErrors: true});+ });+ afterAll(async state => {+ await state.browser.close();+ delete state.browser;+ });+ beforeEach(async state => {+ state.context = await state.browser.createIncognitoBrowserContext();+ state.page = await state.context.newPage();+ });+ afterEach(async state => {+ await state.context.close();+ delete state.context;+ delete state.page;+ });++ describe('Response.securityDetails', function() {+ it('should work', async({page, httpsServer}) => {+ const [serverRequest, response] = await Promise.all([+ httpsServer.waitForRequest('/empty.html'),+ page.goto(httpsServer.EMPTY_PAGE)+ ]);+ const securityDetails = response.securityDetails();+ expect(securityDetails.issuer()).toBe('playwright-tests');+ const protocol = serverRequest.socket.getProtocol().replace('v', ' ');+ expect(securityDetails.protocol()).toBe(protocol);+ expect(securityDetails.subjectName()).toBe('playwright-tests');+ expect(securityDetails.validFrom()).toBe(1550084863);+ expect(securityDetails.validTo()).toBe(33086084863);+ });+ it('should be |null| for non-secure requests', async({page, server}) => {+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.securityDetails()).toBe(null);+ });+ it('Network redirects should report SecurityDetails', async({page, httpsServer}) => {+ httpsServer.setRedirect('/plzredirect', '/empty.html');+ const responses = [];+ page.on('response', response => responses.push(response));+ const [serverRequest, ] = await Promise.all([+ httpsServer.waitForRequest('/plzredirect'),+ page.goto(httpsServer.PREFIX + '/plzredirect')+ ]);+ expect(responses.length).toBe(2);+ expect(responses[0].status()).toBe(302);+ const securityDetails = responses[0].securityDetails();+ const protocol = serverRequest.socket.getProtocol().replace('v', ' ');+ expect(securityDetails.protocol()).toBe(protocol);+ });+ });++ it('should work', async({page, httpsServer}) => {+ let error = null;+ const response = await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);+ expect(error).toBe(null);+ expect(response.ok()).toBe(true);+ });+ it('should work with request interception', async({page, server, httpsServer}) => {+ await page.setRequestInterception(true);+ page.on('request', request => request.continue());+ const response = await page.goto(httpsServer.EMPTY_PAGE);+ expect(response.status()).toBe(200);+ });+ it('should work with mixed content', async({page, server, httpsServer}) => {+ httpsServer.setRoute('/mixedcontent.html', (req, res) => {+ res.end(`<iframe src=${server.EMPTY_PAGE}></iframe>`);+ });+ await page.goto(httpsServer.PREFIX + '/mixedcontent.html', {waitUntil: 'load'});+ expect(page.frames().length).toBe(2);+ // Make sure blocked iframe has functional execution context+ // @see https://github.com/GoogleChrome/puppeteer/issues/2709+ expect(await page.frames()[0].evaluate('1 + 2')).toBe(3);+ expect(await page.frames()[1].evaluate('2 + 3')).toBe(5);+ });+ });+};diff --git a/test/input.spec.js b/test/input.spec.jsnew file mode 100644index 0000000000..764dfb8c1f--- /dev/null+++ b/test/input.spec.js@@ -0,0 +1,223 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const path = require('path');++const FILE_TO_UPLOAD = path.join(__dirname, '/assets/file-to-upload.txt');++module.exports.addTests = function({testRunner, expect, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;+ describe.skip(WEBKIT)('input', function() {+ it('should upload the file', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/fileupload.html');+ const filePath = path.relative(process.cwd(), FILE_TO_UPLOAD);+ const input = await page.$('input');+ await input.uploadFile(filePath);+ expect(await page.evaluate(e => e.files[0].name, input)).toBe('file-to-upload.txt');+ expect(await page.evaluate(e => {+ const reader = new FileReader();+ const promise = new Promise(fulfill => reader.onload = fulfill);+ reader.readAsText(e.files[0]);+ return promise.then(() => reader.result);+ }, input)).toBe('contents of the file');+ });+ });++ describe.skip(FFOX || WEBKIT)('Page.waitForFileChooser', function() {+ it('should work when file input is attached to DOM', async({page, server}) => {+ await page.setContent(`<input type=file>`);+ const [chooser] = await Promise.all([+ page.waitForFileChooser(),+ page.click('input'),+ ]);+ expect(chooser).toBeTruthy();+ });+ it('should work when file input is not attached to DOM', async({page, server}) => {+ const [chooser] = await Promise.all([+ page.waitForFileChooser(),+ page.evaluate(() => {+ const el = document.createElement('input');+ el.type = 'file';+ el.click();+ }),+ ]);+ expect(chooser).toBeTruthy();+ });+ it('should respect timeout', async({page, server}) => {+ let error = null;+ await page.waitForFileChooser({timeout: 1}).catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should respect default timeout when there is no custom timeout', async({page, server}) => {+ page.setDefaultTimeout(1);+ let error = null;+ await page.waitForFileChooser().catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should prioritize exact timeout over default timeout', async({page, server}) => {+ page.setDefaultTimeout(0);+ let error = null;+ await page.waitForFileChooser({timeout: 1}).catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should work with no timeout', async({page, server}) => {+ const [chooser] = await Promise.all([+ page.waitForFileChooser({timeout: 0}),+ page.evaluate(() => setTimeout(() => {+ const el = document.createElement('input');+ el.type = 'file';+ el.click();+ }, 50))+ ]);+ expect(chooser).toBeTruthy();+ });+ it('should return the same file chooser when there are many watchdogs simultaneously', async({page, server}) => {+ await page.setContent(`<input type=file>`);+ const [fileChooser1, fileChooser2] = await Promise.all([+ page.waitForFileChooser(),+ page.waitForFileChooser(),+ page.$eval('input', input => input.click()),+ ]);+ expect(fileChooser1 === fileChooser2).toBe(true);+ });+ });++ describe.skip(FFOX || WEBKIT)('FileChooser.accept', function() {+ it('should accept single file', async({page, server}) => {+ await page.setContent(`<input type=file oninput='javascript:console.timeStamp()'>`);+ const [chooser] = await Promise.all([+ page.waitForFileChooser(),+ page.click('input'),+ ]);+ await Promise.all([+ chooser.accept([FILE_TO_UPLOAD]),+ new Promise(x => page.once('metrics', x)),+ ]);+ expect(await page.$eval('input', input => input.files.length)).toBe(1);+ expect(await page.$eval('input', input => input.files[0].name)).toBe('file-to-upload.txt');+ });+ it('should be able to read selected file', async({page, server}) => {+ await page.setContent(`<input type=file>`);+ page.waitForFileChooser().then(chooser => chooser.accept([FILE_TO_UPLOAD]));+ expect(await page.$eval('input', async picker => {+ picker.click();+ await new Promise(x => picker.oninput = x);+ const reader = new FileReader();+ const promise = new Promise(fulfill => reader.onload = fulfill);+ reader.readAsText(picker.files[0]);+ return promise.then(() => reader.result);+ })).toBe('contents of the file');+ });+ it('should be able to reset selected files with empty file list', async({page, server}) => {+ await page.setContent(`<input type=file>`);+ page.waitForFileChooser().then(chooser => chooser.accept([FILE_TO_UPLOAD]));+ expect(await page.$eval('input', async picker => {+ picker.click();+ await new Promise(x => picker.oninput = x);+ return picker.files.length;+ })).toBe(1);+ page.waitForFileChooser().then(chooser => chooser.accept([]));+ expect(await page.$eval('input', async picker => {+ picker.click();+ await new Promise(x => picker.oninput = x);+ return picker.files.length;+ })).toBe(0);+ });+ it('should not accept multiple files for single-file input', async({page, server}) => {+ await page.setContent(`<input type=file>`);+ const [chooser] = await Promise.all([+ page.waitForFileChooser(),+ page.click('input'),+ ]);+ let error = null;+ await chooser.accept([+ path.relative(process.cwd(), __dirname + '/assets/file-to-upload.txt'),+ path.relative(process.cwd(), __dirname + '/assets/pptr.png'),+ ]).catch(e => error = e);+ expect(error).not.toBe(null);+ });+ it('should fail when accepting file chooser twice', async({page, server}) => {+ await page.setContent(`<input type=file>`);+ const [fileChooser] = await Promise.all([+ page.waitForFileChooser(),+ page.$eval('input', input => input.click()),+ ]);+ await fileChooser.accept([]);+ let error = null;+ await fileChooser.accept([]).catch(e => error = e);+ expect(error.message).toBe('Cannot accept FileChooser which is already handled!');+ });+ });++ describe.skip(FFOX || WEBKIT)('FileChooser.cancel', function() {+ it('should cancel dialog', async({page, server}) => {+ // Consider file chooser canceled if we can summon another one.+ // There's no reliable way in WebPlatform to see that FileChooser was+ // canceled.+ await page.setContent(`<input type=file>`);+ const [fileChooser1] = await Promise.all([+ page.waitForFileChooser(),+ page.$eval('input', input => input.click()),+ ]);+ await fileChooser1.cancel();+ // If this resolves, than we successfully canceled file chooser.+ await Promise.all([+ page.waitForFileChooser(),+ page.$eval('input', input => input.click()),+ ]);+ });+ it('should fail when canceling file chooser twice', async({page, server}) => {+ await page.setContent(`<input type=file>`);+ const [fileChooser] = await Promise.all([+ page.waitForFileChooser(),+ page.$eval('input', input => input.click()),+ ]);+ await fileChooser.cancel();+ let error = null;+ await fileChooser.cancel().catch(e => error = e);+ expect(error.message).toBe('Cannot cancel FileChooser which is already handled!');+ });+ });++ describe.skip(FFOX || WEBKIT)('FileChooser.isMultiple', () => {+ it('should work for single file pick', async({page, server}) => {+ await page.setContent(`<input type=file>`);+ const [chooser] = await Promise.all([+ page.waitForFileChooser(),+ page.click('input'),+ ]);+ expect(chooser.isMultiple()).toBe(false);+ });+ it('should work for "multiple"', async({page, server}) => {+ await page.setContent(`<input multiple type=file>`);+ const [chooser] = await Promise.all([+ page.waitForFileChooser(),+ page.click('input'),+ ]);+ expect(chooser.isMultiple()).toBe(true);+ });+ it('should work for "webkitdirectory"', async({page, server}) => {+ await page.setContent(`<input multiple webkitdirectory type=file>`);+ const [chooser] = await Promise.all([+ page.waitForFileChooser(),+ page.click('input'),+ ]);+ expect(chooser.isMultiple()).toBe(true);+ });+ });+};diff --git a/test/jshandle.spec.js b/test/jshandle.spec.jsnew file mode 100644index 0000000000..7d120336c6--- /dev/null+++ b/test/jshandle.spec.js@@ -0,0 +1,199 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, CHROME, FFOX, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Page.evaluateHandle', function() {+ it('should work', async({page, server}) => {+ const windowHandle = await page.evaluateHandle(() => window);+ expect(windowHandle).toBeTruthy();+ });+ it('should accept object handle as an argument', async({page, server}) => {+ const navigatorHandle = await page.evaluateHandle(() => navigator);+ const text = await page.evaluate(e => e.userAgent, navigatorHandle);+ expect(text).toContain('Mozilla');+ });+ it('should accept object handle to primitive types', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => 5);+ const isFive = await page.evaluate(e => Object.is(e, 5), aHandle);+ expect(isFive).toBeTruthy();+ });+ it('should warn on nested object handles', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => document.body);+ let error = null;+ await page.evaluateHandle(+ opts => opts.elem.querySelector('p'),+ { elem: aHandle }+ ).catch(e => error = e);+ expect(error.message).toContain('Are you passing a nested JSHandle?');+ });+ it('should accept object handle to unserializable value', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => Infinity);+ expect(await page.evaluate(e => Object.is(e, Infinity), aHandle)).toBe(true);+ });+ it('should use the same JS wrappers', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => {+ window.FOO = 123;+ return window;+ });+ expect(await page.evaluate(e => e.FOO, aHandle)).toBe(123);+ });+ it('should work with primitives', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => {+ window.FOO = 123;+ return window;+ });+ expect(await page.evaluate(e => e.FOO, aHandle)).toBe(123);+ });+ });++ describe('JSHandle.getProperty', function() {+ it('should work', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => ({+ one: 1,+ two: 2,+ three: 3+ }));+ const twoHandle = await aHandle.getProperty('two');+ expect(await twoHandle.jsonValue()).toEqual(2);+ });+ });++ describe('JSHandle.jsonValue', function() {+ it('should work', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => ({foo: 'bar'}));+ const json = await aHandle.jsonValue();+ expect(json).toEqual({foo: 'bar'});+ });+ it.skip(FFOX)('should not work with dates', async({page, server}) => {+ const dateHandle = await page.evaluateHandle(() => new Date('2017-09-26T00:00:00.000Z'));+ const json = await dateHandle.jsonValue();+ expect(json).toEqual({});+ });+ it('should throw for circular objects', async({page, server}) => {+ const windowHandle = await page.evaluateHandle('window');+ let error = null;+ await windowHandle.jsonValue().catch(e => error = e);+ if (WEBKIT)+ expect(error.message).toContain('Object has too long reference chain');+ else if (CHROME)+ expect(error.message).toContain('Object reference chain is too long');+ else if (FFOX)+ expect(error.message).toContain('Object is not serializable');+ });+ });++ describe('JSHandle.getProperties', function() {+ it('should work', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => ({+ foo: 'bar'+ }));+ const properties = await aHandle.getProperties();+ const foo = properties.get('foo');+ expect(foo).toBeTruthy();+ expect(await foo.jsonValue()).toBe('bar');+ });+ it('should return even non-own properties', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => {+ class A {+ constructor() {+ this.a = '1';+ }+ }+ class B extends A {+ constructor() {+ super();+ this.b = '2';+ }+ }+ return new B();+ });+ const properties = await aHandle.getProperties();+ expect(await properties.get('a').jsonValue()).toBe('1');+ expect(await properties.get('b').jsonValue()).toBe('2');+ });+ });++ describe('JSHandle.asElement', function() {+ it('should work', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => document.body);+ const element = aHandle.asElement();+ expect(element).toBeTruthy();+ });+ it('should return null for non-elements', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => 2);+ const element = aHandle.asElement();+ expect(element).toBeFalsy();+ });+ it('should return ElementHandle for TextNodes', async({page, server}) => {+ await page.setContent('<div>ee!</div>');+ const aHandle = await page.evaluateHandle(() => document.querySelector('div').firstChild);+ const element = aHandle.asElement();+ expect(element).toBeTruthy();+ expect(await page.evaluate(e => e.nodeType === HTMLElement.TEXT_NODE, element));+ });+ it('should work with nullified Node', async({page, server}) => {+ await page.setContent('<section>test</section>');+ await page.evaluate(() => delete Node);+ const handle = await page.evaluateHandle(() => document.querySelector('section'));+ const element = handle.asElement();+ expect(element).not.toBe(null);+ });+ });++ describe('JSHandle.toString', function() {+ it('should work for primitives', async({page, server}) => {+ const numberHandle = await page.evaluateHandle(() => 2);+ expect(numberHandle.toString()).toBe('JSHandle:2');+ const stringHandle = await page.evaluateHandle(() => 'a');+ expect(stringHandle.toString()).toBe('JSHandle:a');+ });+ it('should work for complicated objects', async({page, server}) => {+ const aHandle = await page.evaluateHandle(() => window);+ expect(aHandle.toString()).toBe('JSHandle@object');+ });+ it('should work for promises', async({page, server}) => {+ // wrap the promise in an object, otherwise we will await.+ const wrapperHandle = await page.evaluateHandle(() => ({b: Promise.resolve(123)}));+ const bHandle = await wrapperHandle.getProperty('b');+ expect(bHandle.toString()).toBe('JSHandle@promise');+ });+ it('should work with different subtypes', async({page, server}) => {+ expect((await page.evaluateHandle('(function(){})')).toString()).toBe('JSHandle@function');+ expect((await page.evaluateHandle('12')).toString()).toBe('JSHandle:12');+ expect((await page.evaluateHandle('true')).toString()).toBe('JSHandle:true');+ expect((await page.evaluateHandle('undefined')).toString()).toBe('JSHandle:undefined');+ expect((await page.evaluateHandle('"foo"')).toString()).toBe('JSHandle:foo');+ expect((await page.evaluateHandle('Symbol()')).toString()).toBe('JSHandle@symbol');+ expect((await page.evaluateHandle('new Map()')).toString()).toBe('JSHandle@map');+ expect((await page.evaluateHandle('new Set()')).toString()).toBe('JSHandle@set');+ expect((await page.evaluateHandle('[]')).toString()).toBe('JSHandle@array');+ expect((await page.evaluateHandle('null')).toString()).toBe('JSHandle:null');+ expect((await page.evaluateHandle('/foo/')).toString()).toBe('JSHandle@regexp');+ expect((await page.evaluateHandle('document.body')).toString()).toBe('JSHandle@node');+ expect((await page.evaluateHandle('new Date()')).toString()).toBe('JSHandle@date');+ expect((await page.evaluateHandle('new WeakMap()')).toString()).toBe('JSHandle@weakmap');+ expect((await page.evaluateHandle('new WeakSet()')).toString()).toBe('JSHandle@weakset');+ expect((await page.evaluateHandle('new Error()')).toString()).toBe('JSHandle@error');+ // TODO(yurys): change subtype from array to typedarray in WebKit.+ expect((await page.evaluateHandle('new Int32Array()')).toString()).toBe(WEBKIT ? 'JSHandle@array' : 'JSHandle@typedarray');+ expect((await page.evaluateHandle('new Proxy({}, {})')).toString()).toBe('JSHandle@proxy');+ });+ });+};diff --git a/test/keyboard.spec.js b/test/keyboard.spec.jsnew file mode 100644index 0000000000..e9597f610a--- /dev/null+++ b/test/keyboard.spec.js@@ -0,0 +1,255 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const utils = require('./utils');+const os = require('os');++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Keyboard', function() {+ it('should type into a textarea', async({page, server}) => {+ await page.evaluate(() => {+ const textarea = document.createElement('textarea');+ document.body.appendChild(textarea);+ textarea.focus();+ });+ const text = 'Hello world. I am the text that was typed!';+ await page.keyboard.type(text);+ expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe(text);+ });+ it('should press the metaKey', async({page, server}) => {+ await page.goto(server.PREFIX + '/empty.html');+ await page.evaluate(() => {+ window.keyPromise = new Promise(resolve => document.addEventListener('keydown', event => resolve(event.key)));+ });+ await page.keyboard.press('Meta');+ expect(await page.evaluate('keyPromise')).toBe(FFOX && os.platform() !== 'darwin' ? 'OS' : 'Meta');+ });+ it('should move with the arrow keys', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.type('textarea', 'Hello World!');+ expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('Hello World!');+ for (let i = 0; i < 'World!'.length; i++)+ page.keyboard.press('ArrowLeft');+ await page.keyboard.type('inserted ');+ expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('Hello inserted World!');+ page.keyboard.down('Shift');+ for (let i = 0; i < 'inserted '.length; i++)+ page.keyboard.press('ArrowLeft');+ page.keyboard.up('Shift');+ await page.keyboard.press('Backspace');+ expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('Hello World!');+ });+ it('should send a character with ElementHandle.press', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ const textarea = await page.$('textarea');+ await textarea.press('a');+ expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('a');++ await page.evaluate(() => window.addEventListener('keydown', e => e.preventDefault(), true));++ await textarea.press('b');+ expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('a');+ });+ it.skip(FFOX || WEBKIT)('ElementHandle.press should support |text| option', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ const textarea = await page.$('textarea');+ await textarea.press('a', {text: 'ё'});+ expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('ё');+ });+ it.skip(WEBKIT)('should send a character with sendCharacter', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.focus('textarea');+ await page.keyboard.sendCharacter('嗨');+ expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('嗨');+ await page.evaluate(() => window.addEventListener('keydown', e => e.preventDefault(), true));+ await page.keyboard.sendCharacter('a');+ expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('嗨a');+ });+ it.skip(WEBKIT)('should report shiftKey', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/keyboard.html');+ const keyboard = page.keyboard;+ const codeForKey = {'Shift': 16, 'Alt': 18, 'Control': 17};+ for (const modifierKey in codeForKey) {+ await keyboard.down(modifierKey);+ expect(await page.evaluate(() => getResult())).toBe('Keydown: ' + modifierKey + ' ' + modifierKey + 'Left ' + codeForKey[modifierKey] + ' [' + modifierKey + ']');+ await keyboard.down('!');+ // Shift+! will generate a keypress+ if (modifierKey === 'Shift')+ expect(await page.evaluate(() => getResult())).toBe('Keydown: ! Digit1 49 [' + modifierKey + ']\nKeypress: ! Digit1 33 33 [' + modifierKey + ']');+ else+ expect(await page.evaluate(() => getResult())).toBe('Keydown: ! Digit1 49 [' + modifierKey + ']');++ await keyboard.up('!');+ expect(await page.evaluate(() => getResult())).toBe('Keyup: ! Digit1 49 [' + modifierKey + ']');+ await keyboard.up(modifierKey);+ expect(await page.evaluate(() => getResult())).toBe('Keyup: ' + modifierKey + ' ' + modifierKey + 'Left ' + codeForKey[modifierKey] + ' []');+ }+ });+ it.skip(WEBKIT)('should report multiple modifiers', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/keyboard.html');+ const keyboard = page.keyboard;+ await keyboard.down('Control');+ expect(await page.evaluate(() => getResult())).toBe('Keydown: Control ControlLeft 17 [Control]');+ await keyboard.down('Alt');+ expect(await page.evaluate(() => getResult())).toBe('Keydown: Alt AltLeft 18 [Alt Control]');+ await keyboard.down(';');+ expect(await page.evaluate(() => getResult())).toBe('Keydown: ; Semicolon 186 [Alt Control]');+ await keyboard.up(';');+ expect(await page.evaluate(() => getResult())).toBe('Keyup: ; Semicolon 186 [Alt Control]');+ await keyboard.up('Control');+ expect(await page.evaluate(() => getResult())).toBe('Keyup: Control ControlLeft 17 [Alt]');+ await keyboard.up('Alt');+ expect(await page.evaluate(() => getResult())).toBe('Keyup: Alt AltLeft 18 []');+ });+ it.skip(WEBKIT)('should send proper codes while typing', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/keyboard.html');+ await page.keyboard.type('!');+ expect(await page.evaluate(() => getResult())).toBe(+ [ 'Keydown: ! Digit1 49 []',+ 'Keypress: ! Digit1 33 33 []',+ 'Keyup: ! Digit1 49 []'].join('\n'));+ await page.keyboard.type('^');+ expect(await page.evaluate(() => getResult())).toBe(+ [ 'Keydown: ^ Digit6 54 []',+ 'Keypress: ^ Digit6 94 94 []',+ 'Keyup: ^ Digit6 54 []'].join('\n'));+ });+ it.skip(WEBKIT)('should send proper codes while typing with shift', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/keyboard.html');+ const keyboard = page.keyboard;+ await keyboard.down('Shift');+ await page.keyboard.type('~');+ expect(await page.evaluate(() => getResult())).toBe(+ [ 'Keydown: Shift ShiftLeft 16 [Shift]',+ 'Keydown: ~ Backquote 192 [Shift]', // 192 is ` keyCode+ 'Keypress: ~ Backquote 126 126 [Shift]', // 126 is ~ charCode+ 'Keyup: ~ Backquote 192 [Shift]'].join('\n'));+ await keyboard.up('Shift');+ });+ it.skip(WEBKIT)('should not type canceled events', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.focus('textarea');+ await page.evaluate(() => {+ window.addEventListener('keydown', event => {+ event.stopPropagation();+ event.stopImmediatePropagation();+ if (event.key === 'l')+ event.preventDefault();+ if (event.key === 'o')+ event.preventDefault();+ }, false);+ });+ await page.keyboard.type('Hello World!');+ expect(await page.evaluate(() => textarea.value)).toBe('He Wrd!');+ });+ it.skip(WEBKIT)('should specify repeat property', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.focus('textarea');+ await page.evaluate(() => document.querySelector('textarea').addEventListener('keydown', e => window.lastEvent = e, true));+ await page.keyboard.down('a');+ expect(await page.evaluate(() => window.lastEvent.repeat)).toBe(false);+ await page.keyboard.press('a');+ expect(await page.evaluate(() => window.lastEvent.repeat)).toBe(true);++ await page.keyboard.down('b');+ expect(await page.evaluate(() => window.lastEvent.repeat)).toBe(false);+ await page.keyboard.down('b');+ expect(await page.evaluate(() => window.lastEvent.repeat)).toBe(true);++ await page.keyboard.up('a');+ await page.keyboard.down('a');+ expect(await page.evaluate(() => window.lastEvent.repeat)).toBe(false);+ });+ it.skip(WEBKIT)('should type all kinds of characters', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.focus('textarea');+ const text = 'This text goes onto two lines.\nThis character is 嗨.';+ await page.keyboard.type(text);+ expect(await page.evaluate('result')).toBe(text);+ });+ it.skip(WEBKIT)('should specify location', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.evaluate(() => {+ window.addEventListener('keydown', event => window.keyLocation = event.location, true);+ });+ const textarea = await page.$('textarea');++ await textarea.press('Digit5');+ expect(await page.evaluate('keyLocation')).toBe(0);++ await textarea.press('ControlLeft');+ expect(await page.evaluate('keyLocation')).toBe(1);++ await textarea.press('ControlRight');+ expect(await page.evaluate('keyLocation')).toBe(2);++ await textarea.press('NumpadSubtract');+ expect(await page.evaluate('keyLocation')).toBe(3);+ });+ it.skip(WEBKIT)('should throw on unknown keys', async({page, server}) => {+ let error = await page.keyboard.press('NotARealKey').catch(e => e);+ expect(error.message).toBe('Unknown key: "NotARealKey"');++ error = await page.keyboard.press('ё').catch(e => e);+ expect(error && error.message).toBe('Unknown key: "ё"');++ error = await page.keyboard.press('😊').catch(e => e);+ expect(error && error.message).toBe('Unknown key: "😊"');+ });+ it.skip(WEBKIT)('should type emoji', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.type('textarea', '👹 Tokyo street Japan 🇯🇵');+ expect(await page.$eval('textarea', textarea => textarea.value)).toBe('👹 Tokyo street Japan 🇯🇵');+ });+ it.skip(WEBKIT)('should type emoji into an iframe', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await utils.attachFrame(page, 'emoji-test', server.PREFIX + '/input/textarea.html');+ const frame = page.frames()[1];+ const textarea = await frame.$('textarea');+ await textarea.type('👹 Tokyo street Japan 🇯🇵');+ expect(await frame.$eval('textarea', textarea => textarea.value)).toBe('👹 Tokyo street Japan 🇯🇵');+ });+ it.skip(WEBKIT)('should press the meta key', async({page}) => {+ await page.evaluate(() => {+ window.result = null;+ document.addEventListener('keydown', event => {+ window.result = [event.key, event.code, event.metaKey];+ });+ });+ await page.keyboard.press('Meta');+ const [key, code, metaKey] = await page.evaluate('result');+ if (FFOX && os.platform() !== 'darwin')+ expect(key).toBe('OS');+ else+ expect(key).toBe('Meta');++ if (FFOX)+ expect(code).toBe('OSLeft');+ else+ expect(code).toBe('MetaLeft');++ if (FFOX && os.platform() !== 'darwin')+ expect(metaKey).toBe(false);+ else+ expect(metaKey).toBe(true);++ });+ });+};diff --git a/test/launcher.spec.js b/test/launcher.spec.jsnew file mode 100644index 0000000000..767cc0aa20--- /dev/null+++ b/test/launcher.spec.js@@ -0,0 +1,427 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+const fs = require('fs');+const os = require('os');+const path = require('path');+const {helper} = require('../lib/helper');+const rmAsync = helper.promisify(require('rimraf'));+const mkdtempAsync = helper.promisify(fs.mkdtemp);+const readFileAsync = helper.promisify(fs.readFile);+const statAsync = helper.promisify(fs.stat);+const TMP_FOLDER = path.join(os.tmpdir(), 'pptr_tmp_folder-');+const utils = require('./utils');++module.exports.addTests = function({testRunner, expect, defaultBrowserOptions, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Playwright', function() {+ describe('BrowserFetcher', function() {+ it.skip(WEBKIT)('should download and extract linux binary', async({server}) => {+ const downloadsFolder = await mkdtempAsync(TMP_FOLDER);+ const browserFetcher = playwright.createBrowserFetcher({+ platform: 'linux',+ path: downloadsFolder,+ host: server.PREFIX+ });+ let revisionInfo = browserFetcher.revisionInfo('123456');+ server.setRoute(revisionInfo.url.substring(server.PREFIX.length), (req, res) => {+ server.serveFile(req, res, '/chromium-linux.zip');+ });++ expect(revisionInfo.local).toBe(false);+ expect(browserFetcher.platform()).toBe('linux');+ expect(await browserFetcher.canDownload('100000')).toBe(false);+ expect(await browserFetcher.canDownload('123456')).toBe(true);++ revisionInfo = await browserFetcher.download('123456');+ expect(revisionInfo.local).toBe(true);+ expect(await readFileAsync(revisionInfo.executablePath, 'utf8')).toBe('LINUX BINARY\n');+ const expectedPermissions = os.platform() === 'win32' ? 0666 : 0755;+ expect((await statAsync(revisionInfo.executablePath)).mode & 0777).toBe(expectedPermissions);+ expect(await browserFetcher.localRevisions()).toEqual(['123456']);+ await browserFetcher.remove('123456');+ expect(await browserFetcher.localRevisions()).toEqual([]);+ await rmAsync(downloadsFolder);+ });+ });+ describe.skip(WEBKIT)('Browser.disconnect', function() {+ it('should reject navigation when browser closes', async({server}) => {+ server.setRoute('/one-style.css', () => {});+ const browser = await playwright.launch(defaultBrowserOptions);+ const remote = await playwright.connect({...defaultBrowserOptions, browserWSEndpoint: browser.wsEndpoint()});+ const page = await remote.newPage();+ const navigationPromise = page.goto(server.PREFIX + '/one-style.html', {timeout: 60000}).catch(e => e);+ await server.waitForRequest('/one-style.css');+ remote.disconnect();+ const error = await navigationPromise;+ expect(error.message).toBe('Navigation failed because browser has disconnected!');+ await browser.close();+ });+ it('should reject waitForSelector when browser closes', async({server}) => {+ server.setRoute('/empty.html', () => {});+ const browser = await playwright.launch(defaultBrowserOptions);+ const remote = await playwright.connect({...defaultBrowserOptions, browserWSEndpoint: browser.wsEndpoint()});+ const page = await remote.newPage();+ const watchdog = page.waitForSelector('div', {timeout: 60000}).catch(e => e);+ remote.disconnect();+ const error = await watchdog;+ expect(error.message).toContain('Protocol error');+ await browser.close();+ });+ });+ describe('Browser.close', function() {+ it.skip(WEBKIT)('should terminate network waiters', async({context, server}) => {+ const browser = await playwright.launch(defaultBrowserOptions);+ const remote = await playwright.connect({...defaultBrowserOptions, browserWSEndpoint: browser.wsEndpoint()});+ const newPage = await remote.newPage();+ const results = await Promise.all([+ newPage.waitForRequest(server.EMPTY_PAGE).catch(e => e),+ newPage.waitForResponse(server.EMPTY_PAGE).catch(e => e),+ browser.close()+ ]);+ for (let i = 0; i < 2; i++) {+ const message = results[i].message;+ expect(message).toContain('Target closed');+ expect(message).not.toContain('Timeout');+ }+ });+ });+ describe.skip(WEBKIT)('Playwright.launch', function() {+ it('should reject all promises when browser is closed', async() => {+ const browser = await playwright.launch(defaultBrowserOptions);+ const page = await browser.newPage();+ let error = null;+ const neverResolves = page.evaluate(() => new Promise(r => {})).catch(e => error = e);+ await browser.close();+ await neverResolves;+ expect(error.message).toContain('Protocol error');+ });+ it('should reject if executable path is invalid', async({server}) => {+ let waitError = null;+ const options = Object.assign({}, defaultBrowserOptions, {executablePath: 'random-invalid-path'});+ await playwright.launch(options).catch(e => waitError = e);+ expect(waitError.message).toContain('Failed to launch');+ });+ it('userDataDir option', async({server}) => {+ const userDataDir = await mkdtempAsync(TMP_FOLDER);+ const options = Object.assign({userDataDir}, defaultBrowserOptions);+ const browser = await playwright.launch(options);+ // Open a page to make sure its functional.+ await browser.newPage();+ expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);+ await browser.close();+ expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);+ // This might throw. See https://github.com/GoogleChrome/puppeteer/issues/2778+ await rmAsync(userDataDir).catch(e => {});+ });+ it('userDataDir argument', async({server}) => {+ const userDataDir = await mkdtempAsync(TMP_FOLDER);+ const options = Object.assign({}, defaultBrowserOptions);+ if (CHROME || WEBKIT) {+ options.args = [+ ...(defaultBrowserOptions.args || []),+ `--user-data-dir=${userDataDir}`+ ];+ } else {+ options.args = [+ ...(defaultBrowserOptions.args || []),+ `-profile`,+ userDataDir,+ ];+ }+ const browser = await playwright.launch(options);+ expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);+ await browser.close();+ expect(fs.readdirSync(userDataDir).length).toBeGreaterThan(0);+ // This might throw. See https://github.com/GoogleChrome/puppeteer/issues/2778+ await rmAsync(userDataDir).catch(e => {});+ });+ it('userDataDir option should restore state', async({server}) => {+ const userDataDir = await mkdtempAsync(TMP_FOLDER);+ const options = Object.assign({userDataDir}, defaultBrowserOptions);+ const browser = await playwright.launch(options);+ const page = await browser.newPage();+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => localStorage.hey = 'hello');+ await browser.close();++ const browser2 = await playwright.launch(options);+ const page2 = await browser2.newPage();+ await page2.goto(server.EMPTY_PAGE);+ expect(await page2.evaluate(() => localStorage.hey)).toBe('hello');+ await browser2.close();+ // This might throw. See https://github.com/GoogleChrome/puppeteer/issues/2778+ await rmAsync(userDataDir).catch(e => {});+ });+ // This mysteriously fails on Windows on AppVeyor. See https://github.com/GoogleChrome/puppeteer/issues/4111+ xit('userDataDir option should restore cookies', async({server}) => {+ const userDataDir = await mkdtempAsync(TMP_FOLDER);+ const options = Object.assign({userDataDir}, defaultBrowserOptions);+ const browser = await playwright.launch(options);+ const page = await browser.newPage();+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT');+ await browser.close();++ const browser2 = await playwright.launch(options);+ const page2 = await browser2.newPage();+ await page2.goto(server.EMPTY_PAGE);+ expect(await page2.evaluate(() => document.cookie)).toBe('doSomethingOnlyOnce=true');+ await browser2.close();+ // This might throw. See https://github.com/GoogleChrome/puppeteer/issues/2778+ await rmAsync(userDataDir).catch(e => {});+ });+ it('should return the default arguments', async() => {+ if (CHROME || WEBKIT) {+ expect(playwright.defaultArgs()).toContain('--no-first-run');+ expect(playwright.defaultArgs()).toContain('--headless');+ expect(playwright.defaultArgs({headless: false})).not.toContain('--headless');+ expect(playwright.defaultArgs({userDataDir: 'foo'})).toContain('--user-data-dir=foo');+ } else {+ expect(playwright.defaultArgs({browser: 'firefox'})).toContain('-headless');+ expect(playwright.defaultArgs({browser: 'firefox', headless: false})).not.toContain('-headless');+ expect(playwright.defaultArgs({browser: 'firefox', userDataDir: 'foo'})).toContain('-profile');+ expect(playwright.defaultArgs({browser: 'firefox', userDataDir: 'foo'})).toContain('foo');+ }+ });+ it('should work with no default arguments', async() => {+ const options = Object.assign({}, defaultBrowserOptions);+ options.ignoreDefaultArgs = true;+ const browser = await playwright.launch(options);+ const page = await browser.newPage();+ expect(await page.evaluate('11 * 11')).toBe(121);+ await page.close();+ await browser.close();+ });+ it('should filter out ignored default arguments', async() => {+ // Make sure we launch with `--enable-automation` by default.+ const defaultArgs = playwright.defaultArgs(defaultBrowserOptions);+ const browser = await playwright.launch(Object.assign({}, defaultBrowserOptions, {+ // Ignore first and third default argument.+ ignoreDefaultArgs: [ defaultArgs[0], defaultArgs[2] ],+ }));+ const spawnargs = browser.process().spawnargs;+ expect(spawnargs.indexOf(defaultArgs[0])).toBe(-1);+ expect(spawnargs.indexOf(defaultArgs[1])).not.toBe(-1);+ expect(spawnargs.indexOf(defaultArgs[2])).toBe(-1);+ await browser.close();+ });+ it.skip(FFOX)('should have default URL when launching browser', async function() {+ const browser = await playwright.launch(defaultBrowserOptions);+ const pages = (await browser.pages()).map(page => page.url());+ expect(pages).toEqual(['about:blank']);+ await browser.close();+ });+ it.skip(FFOX)('should have custom URL when launching browser', async function({server}) {+ const options = Object.assign({}, defaultBrowserOptions);+ options.args = [server.EMPTY_PAGE].concat(options.args || []);+ const browser = await playwright.launch(options);+ const pages = await browser.pages();+ expect(pages.length).toBe(1);+ const page = pages[0];+ if (page.url() !== server.EMPTY_PAGE)+ await page.waitForNavigation();+ expect(page.url()).toBe(server.EMPTY_PAGE);+ await browser.close();+ });+ it('should set the default viewport', async() => {+ const options = Object.assign({}, defaultBrowserOptions, {+ defaultViewport: {+ width: 456,+ height: 789+ }+ });+ const browser = await playwright.launch(options);+ const page = await browser.newPage();+ expect(await page.evaluate('window.innerWidth')).toBe(456);+ expect(await page.evaluate('window.innerHeight')).toBe(789);+ await browser.close();+ });+ it('should disable the default viewport', async() => {+ const options = Object.assign({}, defaultBrowserOptions, {+ defaultViewport: null+ });+ const browser = await playwright.launch(options);+ const page = await browser.newPage();+ expect(page.viewport()).toBe(null);+ await browser.close();+ });+ it('should take fullPage screenshots when defaultViewport is null', async({server}) => {+ const options = Object.assign({}, defaultBrowserOptions, {+ defaultViewport: null+ });+ const browser = await playwright.launch(options);+ const page = await browser.newPage();+ await page.goto(server.PREFIX + '/grid.html');+ const screenshot = await page.screenshot({+ fullPage: true+ });+ expect(screenshot).toBeInstanceOf(Buffer);+ await browser.close();+ });+ });+ describe.skip(WEBKIT)('Playwright.connect', function() {+ it('should be able to connect multiple times to the same browser', async({server}) => {+ const originalBrowser = await playwright.launch(defaultBrowserOptions);+ const browser = await playwright.connect({+ ...defaultBrowserOptions,+ browserWSEndpoint: originalBrowser.wsEndpoint()+ });+ const page = await browser.newPage();+ expect(await page.evaluate(() => 7 * 8)).toBe(56);+ browser.disconnect();++ const secondPage = await originalBrowser.newPage();+ expect(await secondPage.evaluate(() => 7 * 6)).toBe(42, 'original browser should still work');+ await originalBrowser.close();+ });+ it('should be able to close remote browser', async({server}) => {+ const originalBrowser = await playwright.launch(defaultBrowserOptions);+ const remoteBrowser = await playwright.connect({+ ...defaultBrowserOptions,+ browserWSEndpoint: originalBrowser.wsEndpoint()+ });+ await Promise.all([+ utils.waitEvent(originalBrowser, 'disconnected'),+ remoteBrowser.close(),+ ]);+ });+ it('should support ignoreHTTPSErrors option', async({httpsServer}) => {+ const originalBrowser = await playwright.launch(defaultBrowserOptions);+ const browserWSEndpoint = originalBrowser.wsEndpoint();++ const browser = await playwright.connect({...defaultBrowserOptions, browserWSEndpoint, ignoreHTTPSErrors: true});+ const page = await browser.newPage();+ let error = null;+ const [serverRequest, response] = await Promise.all([+ httpsServer.waitForRequest('/empty.html'),+ page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e)+ ]);+ expect(error).toBe(null);+ expect(response.ok()).toBe(true);+ expect(response.securityDetails()).toBeTruthy();+ const protocol = serverRequest.socket.getProtocol().replace('v', ' ');+ expect(response.securityDetails().protocol()).toBe(protocol);+ await page.close();+ await browser.close();+ });+ it('should be able to reconnect to a disconnected browser', async({server}) => {+ const originalBrowser = await playwright.launch(defaultBrowserOptions);+ const browserWSEndpoint = originalBrowser.wsEndpoint();+ const page = await originalBrowser.newPage();+ await page.goto(server.PREFIX + '/frames/nested-frames.html');+ originalBrowser.disconnect();++ const browser = await playwright.connect({...defaultBrowserOptions, browserWSEndpoint});+ const pages = await browser.pages();+ const restoredPage = pages.find(page => page.url() === server.PREFIX + '/frames/nested-frames.html');+ expect(utils.dumpFrames(restoredPage.mainFrame())).toEqual([+ 'http://localhost:<PORT>/frames/nested-frames.html',+ ' http://localhost:<PORT>/frames/two-frames.html (2frames)',+ ' http://localhost:<PORT>/frames/frame.html (uno)',+ ' http://localhost:<PORT>/frames/frame.html (dos)',+ ' http://localhost:<PORT>/frames/frame.html (aframe)',+ ]);+ expect(await restoredPage.evaluate(() => 7 * 8)).toBe(56);+ await browser.close();+ });+ // @see https://github.com/GoogleChrome/puppeteer/issues/4197#issuecomment-481793410+ it('should be able to connect to the same page simultaneously', async({server}) => {+ const browserOne = await playwright.launch(defaultBrowserOptions);+ const browserTwo = await playwright.connect({ ...defaultBrowserOptions, browserWSEndpoint: browserOne.wsEndpoint() });+ const [page1, page2] = await Promise.all([+ new Promise(x => browserOne.once('targetcreated', target => x(target.page()))),+ browserTwo.newPage(),+ ]);+ expect(await page1.evaluate(() => 7 * 8)).toBe(56);+ expect(await page2.evaluate(() => 7 * 6)).toBe(42);+ await browserOne.close();+ });++ });+ describe('Playwright.executablePath', function() {+ it('should work', async({server}) => {+ const executablePath = playwright.executablePath();+ expect(fs.existsSync(executablePath)).toBe(true);+ expect(fs.realpathSync(executablePath)).toBe(executablePath);+ });+ });+ });++ describe.skip(WEBKIT)('Top-level requires', function() {+ it('should require top-level Errors', async() => {+ const Errors = require(path.join(utils.projectRoot(), '/Errors'));+ expect(Errors.TimeoutError).toBe(playwright.errors.TimeoutError);+ });+ it('should require top-level DeviceDescriptors', async() => {+ const Devices = require(path.join(utils.projectRoot(), '/DeviceDescriptors'));+ expect(Devices['iPhone 6']).toBe(playwright.devices['iPhone 6']);+ });+ });++ describe.skip(WEBKIT)('Browser target events', function() {+ it('should work', async({server}) => {+ const browser = await playwright.launch(defaultBrowserOptions);+ const events = [];+ browser.on('targetcreated', () => events.push('CREATED'));+ browser.on('targetchanged', () => events.push('CHANGED'));+ browser.on('targetdestroyed', () => events.push('DESTROYED'));+ const page = await browser.newPage();+ await page.goto(server.EMPTY_PAGE);+ await page.close();+ expect(events).toEqual(['CREATED', 'CHANGED', 'DESTROYED']);+ await browser.close();+ });+ });++ describe.skip(WEBKIT)('Browser.Events.disconnected', function() {+ it('should be emitted when: browser gets closed, disconnected or underlying websocket gets closed', async() => {+ const originalBrowser = await playwright.launch(defaultBrowserOptions);+ const browserWSEndpoint = originalBrowser.wsEndpoint();+ const remoteBrowser1 = await playwright.connect({browserWSEndpoint});+ const remoteBrowser2 = await playwright.connect({browserWSEndpoint});++ let disconnectedOriginal = 0;+ let disconnectedRemote1 = 0;+ let disconnectedRemote2 = 0;+ originalBrowser.on('disconnected', () => ++disconnectedOriginal);+ remoteBrowser1.on('disconnected', () => ++disconnectedRemote1);+ remoteBrowser2.on('disconnected', () => ++disconnectedRemote2);++ await Promise.all([+ utils.waitEvent(remoteBrowser2, 'disconnected'),+ remoteBrowser2.disconnect(),+ ]);++ expect(disconnectedOriginal).toBe(0);+ expect(disconnectedRemote1).toBe(0);+ expect(disconnectedRemote2).toBe(1);++ await Promise.all([+ utils.waitEvent(remoteBrowser1, 'disconnected'),+ utils.waitEvent(originalBrowser, 'disconnected'),+ originalBrowser.close(),+ ]);++ expect(disconnectedOriginal).toBe(1);+ expect(disconnectedRemote1).toBe(1);+ expect(disconnectedRemote2).toBe(1);+ });+ });++};diff --git a/test/mouse.spec.js b/test/mouse.spec.jsnew file mode 100644index 0000000000..92a0aef73a--- /dev/null+++ b/test/mouse.spec.js@@ -0,0 +1,162 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+const os = require('os');++function dimensions() {+ const rect = document.querySelector('textarea').getBoundingClientRect();+ return {+ x: rect.left,+ y: rect.top,+ width: rect.width,+ height: rect.height+ };+}++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Mouse', function() {+ it('should click the document', async({page, server}) => {+ await page.evaluate(() => {+ window.clickPromise = new Promise(resolve => {+ document.addEventListener('click', event => {+ resolve({+ type: event.type,+ detail: event.detail,+ clientX: event.clientX,+ clientY: event.clientY,+ isTrusted: event.isTrusted,+ button: event.button+ });+ });+ });+ });+ await page.mouse.click(50, 60);+ const event = await page.evaluate(() => window.clickPromise);+ expect(event.type).toBe('click');+ expect(event.detail).toBe(1);+ expect(event.clientX).toBe(50);+ expect(event.clientY).toBe(60);+ expect(event.isTrusted).toBe(true);+ expect(event.button).toBe(0);+ });+ it('should resize the textarea', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ const {x, y, width, height} = await page.evaluate(dimensions);+ const mouse = page.mouse;+ // The test becomes flaky on WebKit without next line.+ if (WEBKIT)+ await page.evaluate(() => new Promise(requestAnimationFrame));+ await mouse.move(x + width - 4, y + height - 4);+ await mouse.down();+ await mouse.move(x + width + 100, y + height + 100);+ await mouse.up();+ const newDimensions = await page.evaluate(dimensions);+ expect(newDimensions.width).toBe(Math.round(width + 104));+ expect(newDimensions.height).toBe(Math.round(height + 104));+ });+ it('should select the text with mouse', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.focus('textarea');+ const text = 'This is the text that we are going to try to select. Let\'s see how it goes.';+ await page.keyboard.type(text);+ // Firefox needs an extra frame here after typing or it will fail to set the scrollTop+ await page.evaluate(() => new Promise(requestAnimationFrame));+ await page.evaluate(() => document.querySelector('textarea').scrollTop = 0);+ const {x, y} = await page.evaluate(dimensions);+ await page.mouse.move(x + 2,y + 2);+ await page.mouse.down();+ await page.mouse.move(200,200);+ await page.mouse.up();+ expect(await page.evaluate(() => {+ const textarea = document.querySelector('textarea');+ return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);+ })).toBe(text);+ });+ it('should trigger hover state', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/scrollable.html');+ await page.hover('#button-6');+ expect(await page.evaluate(() => document.querySelector('button:hover').id)).toBe('button-6');+ await page.hover('#button-2');+ expect(await page.evaluate(() => document.querySelector('button:hover').id)).toBe('button-2');+ await page.hover('#button-91');+ expect(await page.evaluate(() => document.querySelector('button:hover').id)).toBe('button-91');+ });+ it.skip(FFOX || WEBKIT)('should trigger hover state with removed window.Node', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/scrollable.html');+ await page.evaluate(() => delete window.Node);+ await page.hover('#button-6');+ expect(await page.evaluate(() => document.querySelector('button:hover').id)).toBe('button-6');+ });+ it('should set modifier keys on click', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/scrollable.html');+ await page.evaluate(() => document.querySelector('#button-3').addEventListener('mousedown', e => window.lastEvent = e, true));+ const modifiers = {'Shift': 'shiftKey', 'Control': 'ctrlKey', 'Alt': 'altKey', 'Meta': 'metaKey'};+ // In Firefox, the Meta modifier only exists on Mac+ if (FFOX && os.platform() !== 'darwin')+ delete modifiers['Meta'];+ for (const modifier in modifiers) {+ await page.keyboard.down(modifier);+ await page.click('#button-3');+ if (!(await page.evaluate(mod => window.lastEvent[mod], modifiers[modifier])))+ throw new Error(modifiers[modifier] + ' should be true');+ await page.keyboard.up(modifier);+ }+ await page.click('#button-3');+ for (const modifier in modifiers) {+ if ((await page.evaluate(mod => window.lastEvent[mod], modifiers[modifier])))+ throw new Error(modifiers[modifier] + ' should be false');+ }+ });+ it('should tween mouse movement', async({page, server}) => {+ // The test becomes flaky on WebKit without next line.+ if (WEBKIT)+ await page.evaluate(() => new Promise(requestAnimationFrame));+ await page.mouse.move(100, 100);+ await page.evaluate(() => {+ window.result = [];+ document.addEventListener('mousemove', event => {+ window.result.push([event.clientX, event.clientY]);+ });+ });+ await page.mouse.move(200, 300, {steps: 5});+ expect(await page.evaluate('result')).toEqual([+ [120, 140],+ [140, 180],+ [160, 220],+ [180, 260],+ [200, 300]+ ]);+ });+ // @see https://crbug.com/929806+ it.skip(WEBKIT)('should work with mobile viewports and cross process navigations', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setViewport({width: 360, height: 640, isMobile: true});+ await page.goto(server.CROSS_PROCESS_PREFIX + '/mobile.html');+ await page.evaluate(() => {+ document.addEventListener('click', event => {+ window.result = {x: event.clientX, y: event.clientY};+ });+ });++ await page.mouse.click(30, 40);++ expect(await page.evaluate('result')).toEqual({x: 30, y: 40});+ });+ });+};diff --git a/test/navigation.spec.js b/test/navigation.spec.jsnew file mode 100644index 0000000000..5af9c269c8--- /dev/null+++ b/test/navigation.spec.js@@ -0,0 +1,574 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const utils = require('./utils');++module.exports.addTests = function({testRunner, expect, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Page.goto', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ expect(page.url()).toBe(server.EMPTY_PAGE);+ });+ it.skip(WEBKIT)('should work with anchor navigation', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ expect(page.url()).toBe(server.EMPTY_PAGE);+ await page.goto(server.EMPTY_PAGE + '#foo');+ expect(page.url()).toBe(server.EMPTY_PAGE + '#foo');+ await page.goto(server.EMPTY_PAGE + '#bar');+ expect(page.url()).toBe(server.EMPTY_PAGE + '#bar');+ });+ it('should work with redirects', async({page, server}) => {+ server.setRedirect('/redirect/1.html', '/redirect/2.html');+ server.setRedirect('/redirect/2.html', '/empty.html');+ await page.goto(server.PREFIX + '/redirect/1.html');+ expect(page.url()).toBe(server.EMPTY_PAGE);+ });+ it('should navigate to about:blank', async({page, server}) => {+ const response = await page.goto('about:blank');+ expect(response).toBe(null);+ });+ it('should return response when page changes its URL after load', async({page, server}) => {+ const response = await page.goto(server.PREFIX + '/historyapi.html');+ expect(response.status()).toBe(200);+ });+ it('should work with subframes return 204', async({page, server}) => {+ server.setRoute('/frames/frame.html', (req, res) => {+ res.statusCode = 204;+ res.end();+ });+ await page.goto(server.PREFIX + '/frames/one-frame.html');+ });+ it.skip(WEBKIT)('should fail when server returns 204', async({page, server}) => {+ server.setRoute('/empty.html', (req, res) => {+ res.statusCode = 204;+ res.end();+ });+ let error = null;+ await page.goto(server.EMPTY_PAGE).catch(e => error = e);+ expect(error).not.toBe(null);+ if (CHROME || WEBKIT)+ expect(error.message).toContain('net::ERR_ABORTED');+ else+ expect(error.message).toContain('NS_BINDING_ABORTED');+ });+ it('should navigate to empty page with domcontentloaded', async({page, server}) => {+ const response = await page.goto(server.EMPTY_PAGE, {waitUntil: 'domcontentloaded'});+ expect(response.status()).toBe(200);+ });+ it.skip(WEBKIT)('should work when page calls history API in beforeunload', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => {+ window.addEventListener('beforeunload', () => history.replaceState(null, 'initial', window.location.href), false);+ });+ const response = await page.goto(server.PREFIX + '/grid.html');+ expect(response.status()).toBe(200);+ });+ it.skip(FFOX || WEBKIT)('should navigate to empty page with networkidle0', async({page, server}) => {+ const response = await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle0'});+ expect(response.status()).toBe(200);+ });+ it.skip(FFOX || WEBKIT)('should navigate to empty page with networkidle2', async({page, server}) => {+ const response = await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle2'});+ expect(response.status()).toBe(200);+ });+ it.skip(WEBKIT)('should fail when navigating to bad url', async({page, server}) => {+ let error = null;+ await page.goto('asdfasdf').catch(e => error = e);+ if (CHROME || WEBKIT)+ expect(error.message).toContain('Cannot navigate to invalid URL');+ else+ expect(error.message).toContain('Invalid url');+ });+ // FIXME: shows dialog in WebKit.+ it.skip(WEBKIT)('should fail when navigating to bad SSL', async({page, httpsServer}) => {+ // Make sure that network events do not emit 'undefined'.+ // @see https://crbug.com/750469+ page.on('request', request => expect(request).toBeTruthy());+ page.on('requestfinished', request => expect(request).toBeTruthy());+ page.on('requestfailed', request => expect(request).toBeTruthy());+ let error = null;+ await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);+ if (CHROME || WEBKIT)+ expect(error.message).toContain('net::ERR_CERT_AUTHORITY_INVALID');+ else+ expect(error.message).toContain('SSL_ERROR_UNKNOWN');+ });+ // FIXME: shows dialog in WebKit.+ it.skip(WEBKIT)('should fail when navigating to bad SSL after redirects', async({page, server, httpsServer}) => {+ server.setRedirect('/redirect/1.html', '/redirect/2.html');+ server.setRedirect('/redirect/2.html', '/empty.html');+ let error = null;+ await page.goto(httpsServer.PREFIX + '/redirect/1.html').catch(e => error = e);+ if (CHROME || WEBKIT)+ expect(error.message).toContain('net::ERR_CERT_AUTHORITY_INVALID');+ else+ expect(error.message).toContain('SSL_ERROR_UNKNOWN');+ });+ it.skip(FFOX || WEBKIT)('should throw if networkidle is passed as an option', async({page, server}) => {+ let error = null;+ await page.goto(server.EMPTY_PAGE, {waitUntil: 'networkidle'}).catch(err => error = err);+ expect(error.message).toContain('"networkidle" option is no longer supported');+ });+ it.skip(WEBKIT)('should fail when main resources failed to load', async({page, server}) => {+ let error = null;+ await page.goto('http://localhost:44123/non-existing-url').catch(e => error = e);+ if (CHROME || WEBKIT)+ expect(error.message).toContain('net::ERR_CONNECTION_REFUSED');+ else+ expect(error.message).toContain('NS_ERROR_CONNECTION_REFUSED');+ });+ it('should fail when exceeding maximum navigation timeout', async({page, server}) => {+ // Hang for request to the empty.html+ server.setRoute('/empty.html', (req, res) => { });+ let error = null;+ await page.goto(server.PREFIX + '/empty.html', {timeout: 1}).catch(e => error = e);+ const message = WEBKIT ? 'Navigation Timeout Exceeded: 1ms' : 'Navigation timeout of 1 ms exceeded';+ expect(error.message).toContain(message);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should fail when exceeding default maximum navigation timeout', async({page, server}) => {+ // Hang for request to the empty.html+ server.setRoute('/empty.html', (req, res) => { });+ let error = null;+ page.setDefaultNavigationTimeout(1);+ await page.goto(server.PREFIX + '/empty.html').catch(e => error = e);+ const message = WEBKIT ? 'Navigation Timeout Exceeded: 1ms' : 'Navigation timeout of 1 ms exceeded';+ expect(error.message).toContain(message);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should fail when exceeding default maximum timeout', async({page, server}) => {+ // Hang for request to the empty.html+ server.setRoute('/empty.html', (req, res) => { });+ let error = null;+ page.setDefaultTimeout(1);+ await page.goto(server.PREFIX + '/empty.html').catch(e => error = e);+ const message = WEBKIT ? 'Navigation Timeout Exceeded: 1ms' : 'Navigation timeout of 1 ms exceeded';+ expect(error.message).toContain(message);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should prioritize default navigation timeout over default timeout', async({page, server}) => {+ // Hang for request to the empty.html+ server.setRoute('/empty.html', (req, res) => { });+ let error = null;+ page.setDefaultTimeout(0);+ page.setDefaultNavigationTimeout(1);+ await page.goto(server.PREFIX + '/empty.html').catch(e => error = e);+ const message = WEBKIT ? 'Navigation Timeout Exceeded: 1ms' : 'Navigation timeout of 1 ms exceeded';+ expect(error.message).toContain(message);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should disable timeout when its set to 0', async({page, server}) => {+ let error = null;+ let loaded = false;+ page.once('load', () => loaded = true);+ await page.goto(server.PREFIX + '/grid.html', {timeout: 0, waitUntil: ['load']}).catch(e => error = e);+ expect(error).toBe(null);+ expect(loaded).toBe(true);+ });+ it('should work when navigating to valid url', async({page, server}) => {+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.ok()).toBe(true);+ });+ it.skip(FFOX)('should work when navigating to data url', async({page, server}) => {+ const response = await page.goto('data:text/html,hello');+ expect(response.ok()).toBe(true);+ });+ it('should work when navigating to 404', async({page, server}) => {+ const response = await page.goto(server.PREFIX + '/not-found');+ expect(response.ok()).toBe(false);+ expect(response.status()).toBe(404);+ });+ it('should return last response in redirect chain', async({page, server}) => {+ server.setRedirect('/redirect/1.html', '/redirect/2.html');+ server.setRedirect('/redirect/2.html', '/redirect/3.html');+ server.setRedirect('/redirect/3.html', server.EMPTY_PAGE);+ const response = await page.goto(server.PREFIX + '/redirect/1.html');+ expect(response.ok()).toBe(true);+ expect(response.url()).toBe(server.EMPTY_PAGE);+ });+ it.skip(FFOX || WEBKIT)('should wait for network idle to succeed navigation', async({page, server}) => {+ let responses = [];+ // Hold on to a bunch of requests without answering.+ server.setRoute('/fetch-request-a.js', (req, res) => responses.push(res));+ server.setRoute('/fetch-request-b.js', (req, res) => responses.push(res));+ server.setRoute('/fetch-request-c.js', (req, res) => responses.push(res));+ server.setRoute('/fetch-request-d.js', (req, res) => responses.push(res));+ const initialFetchResourcesRequested = Promise.all([+ server.waitForRequest('/fetch-request-a.js'),+ server.waitForRequest('/fetch-request-b.js'),+ server.waitForRequest('/fetch-request-c.js'),+ ]);+ const secondFetchResourceRequested = server.waitForRequest('/fetch-request-d.js');++ // Navigate to a page which loads immediately and then does a bunch of+ // requests via javascript's fetch method.+ const navigationPromise = page.goto(server.PREFIX + '/networkidle.html', {+ waitUntil: 'networkidle0',+ });+ // Track when the navigation gets completed.+ let navigationFinished = false;+ navigationPromise.then(() => navigationFinished = true);++ // Wait for the page's 'load' event.+ await new Promise(fulfill => page.once('load', fulfill));+ expect(navigationFinished).toBe(false);++ // Wait for the initial three resources to be requested.+ await initialFetchResourcesRequested;++ // Expect navigation still to be not finished.+ expect(navigationFinished).toBe(false);++ // Respond to initial requests.+ for (const response of responses) {+ response.statusCode = 404;+ response.end(`File not found`);+ }++ // Reset responses array+ responses = [];++ // Wait for the second round to be requested.+ await secondFetchResourceRequested;+ // Expect navigation still to be not finished.+ expect(navigationFinished).toBe(false);++ // Respond to requests.+ for (const response of responses) {+ response.statusCode = 404;+ response.end(`File not found`);+ }++ const response = await navigationPromise;+ // Expect navigation to succeed.+ expect(response.ok()).toBe(true);+ });+ it('should not leak listeners during navigation', async({page, server}) => {+ let warning = null;+ const warningHandler = w => warning = w;+ process.on('warning', warningHandler);+ for (let i = 0; i < 20; ++i)+ await page.goto(server.EMPTY_PAGE);+ process.removeListener('warning', warningHandler);+ expect(warning).toBe(null);+ });+ it.skip(WEBKIT)('should not leak listeners during bad navigation', async({page, server}) => {+ let warning = null;+ const warningHandler = w => warning = w;+ process.on('warning', warningHandler);+ for (let i = 0; i < 20; ++i)+ await page.goto('asdf').catch(e => {/* swallow navigation error */});+ process.removeListener('warning', warningHandler);+ expect(warning).toBe(null);+ });+ it('should not leak listeners during navigation of 11 pages', async({page, context, server}) => {+ let warning = null;+ const warningHandler = w => warning = w;+ process.on('warning', warningHandler);+ await Promise.all([...Array(20)].map(async() => {+ const page = await context.newPage();+ await page.goto(server.EMPTY_PAGE);+ await page.close();+ }));+ process.removeListener('warning', warningHandler);+ expect(warning).toBe(null);+ });+ it.skip(FFOX)('should navigate to dataURL and fire dataURL requests', async({page, server}) => {+ const requests = [];+ page.on('request', request => !utils.isFavicon(request) && requests.push(request));+ const dataURL = 'data:text/html,<div>yo</div>';+ const response = await page.goto(dataURL);+ expect(response.status()).toBe(200);+ expect(requests.length).toBe(1);+ expect(requests[0].url()).toBe(dataURL);+ });+ it.skip(FFOX || WEBKIT)('should navigate to URL with hash and fire requests without hash', async({page, server}) => {+ const requests = [];+ page.on('request', request => !utils.isFavicon(request) && requests.push(request));+ const response = await page.goto(server.EMPTY_PAGE + '#hash');+ expect(response.status()).toBe(200);+ expect(response.url()).toBe(server.EMPTY_PAGE);+ expect(requests.length).toBe(1);+ expect(requests[0].url()).toBe(server.EMPTY_PAGE);+ });+ it.skip(WEBKIT)('should work with self requesting page', async({page, server}) => {+ const response = await page.goto(server.PREFIX + '/self-request.html');+ expect(response.status()).toBe(200);+ expect(response.url()).toContain('self-request.html');+ });+ it.skip(WEBKIT)('should fail when navigating and show the url at the error message', async function({page, server, httpsServer}) {+ const url = httpsServer.PREFIX + '/redirect/1.html';+ let error = null;+ try {+ await page.goto(url);+ } catch (e) {+ error = e;+ }+ expect(error.message).toContain(url);+ });+ it.skip(WEBKIT)('should send referer', async({page, server}) => {+ const [request1, request2] = await Promise.all([+ server.waitForRequest('/grid.html'),+ server.waitForRequest('/digits/1.png'),+ page.goto(server.PREFIX + '/grid.html', {+ referer: 'http://google.com/',+ }),+ ]);+ expect(request1.headers['referer']).toBe('http://google.com/');+ // Make sure subresources do not inherit referer.+ expect(request2.headers['referer']).toBe(server.PREFIX + '/grid.html');+ });+ });++ describe('Page.waitForNavigation', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const [response] = await Promise.all([+ page.waitForNavigation(),+ page.evaluate(url => window.location.href = url, server.PREFIX + '/grid.html')+ ]);+ expect(response.ok()).toBe(true);+ expect(response.url()).toContain('grid.html');+ });+ it.skip(WEBKIT)('should work with both domcontentloaded and load', async({page, server}) => {+ let response = null;+ server.setRoute('/one-style.css', (req, res) => response = res);+ const navigationPromise = page.goto(server.PREFIX + '/one-style.html');+ const domContentLoadedPromise = page.waitForNavigation({+ waitUntil: 'domcontentloaded'+ });++ let bothFired = false;+ const bothFiredPromise = page.waitForNavigation({+ waitUntil: ['load', 'domcontentloaded']+ }).then(() => bothFired = true);++ await server.waitForRequest('/one-style.css');+ await domContentLoadedPromise;+ expect(bothFired).toBe(false);+ response.end();+ await bothFiredPromise;+ await navigationPromise;+ });+ it('should work with clicking on anchor links', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setContent(`<a href='#foobar'>foobar</a>`);+ const [response] = await Promise.all([+ page.waitForNavigation(),+ page.click('a'),+ ]);+ expect(response).toBe(null);+ expect(page.url()).toBe(server.EMPTY_PAGE + '#foobar');+ });+ it('should work with history.pushState()', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setContent(`+ <a onclick='javascript:pushState()'>SPA</a>+ <script>+ function pushState() { history.pushState({}, '', 'wow.html') }+ </script>+ `);+ const [response] = await Promise.all([+ page.waitForNavigation(),+ page.click('a'),+ ]);+ expect(response).toBe(null);+ expect(page.url()).toBe(server.PREFIX + '/wow.html');+ });+ it('should work with history.replaceState()', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setContent(`+ <a onclick='javascript:replaceState()'>SPA</a>+ <script>+ function replaceState() { history.replaceState({}, '', '/replaced.html') }+ </script>+ `);+ const [response] = await Promise.all([+ page.waitForNavigation(),+ page.click('a'),+ ]);+ expect(response).toBe(null);+ expect(page.url()).toBe(server.PREFIX + '/replaced.html');+ });+ it.skip(FFOX)('should work with DOM history.back()/history.forward()', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setContent(`+ <a id=back onclick='javascript:goBack()'>back</a>+ <a id=forward onclick='javascript:goForward()'>forward</a>+ <script>+ function goBack() { history.back(); }+ function goForward() { history.forward(); }+ history.pushState({}, '', '/first.html');+ history.pushState({}, '', '/second.html');+ </script>+ `);+ expect(page.url()).toBe(server.PREFIX + '/second.html');+ const [backResponse] = await Promise.all([+ page.waitForNavigation(),+ page.click('a#back'),+ ]);+ expect(backResponse).toBe(null);+ expect(page.url()).toBe(server.PREFIX + '/first.html');+ const [forwardResponse] = await Promise.all([+ page.waitForNavigation(),+ page.click('a#forward'),+ ]);+ expect(forwardResponse).toBe(null);+ expect(page.url()).toBe(server.PREFIX + '/second.html');+ });+ it.skip(WEBKIT)('should work when subframe issues window.stop()', async({page, server}) => {+ server.setRoute('/frames/style.css', (req, res) => {});+ const navigationPromise = page.goto(server.PREFIX + '/frames/one-frame.html');+ const frame = await utils.waitEvent(page, 'frameattached');+ await new Promise(fulfill => {+ page.on('framenavigated', f => {+ if (f === frame)+ fulfill();+ });+ });+ await Promise.all([+ frame.evaluate(() => window.stop()),+ navigationPromise+ ]);+ });+ });++ describe('Page.goBack', function() {+ it.skip(WEBKIT)('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.goto(server.PREFIX + '/grid.html');++ let response = await page.goBack();+ expect(response.ok()).toBe(true);+ expect(response.url()).toContain(server.EMPTY_PAGE);++ response = await page.goForward();+ expect(response.ok()).toBe(true);+ expect(response.url()).toContain('/grid.html');++ response = await page.goForward();+ expect(response).toBe(null);+ });+ it.skip(WEBKIT)('should work with HistoryAPI', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => {+ history.pushState({}, '', '/first.html');+ history.pushState({}, '', '/second.html');+ });+ expect(page.url()).toBe(server.PREFIX + '/second.html');++ await page.goBack();+ expect(page.url()).toBe(server.PREFIX + '/first.html');+ await page.goBack();+ expect(page.url()).toBe(server.EMPTY_PAGE);+ await page.goForward();+ expect(page.url()).toBe(server.PREFIX + '/first.html');+ });+ });++ describe('Frame.goto', function() {+ it.skip(WEBKIT)('should navigate subframes', async({page, server}) => {+ await page.goto(server.PREFIX + '/frames/one-frame.html');+ expect(page.frames()[0].url()).toContain('/frames/one-frame.html');+ expect(page.frames()[1].url()).toContain('/frames/frame.html');++ const response = await page.frames()[1].goto(server.EMPTY_PAGE);+ expect(response.ok()).toBe(true);+ expect(response.frame()).toBe(page.frames()[1]);+ });+ it.skip(WEBKIT)('should reject when frame detaches', async({page, server}) => {+ await page.goto(server.PREFIX + '/frames/one-frame.html');++ server.setRoute('/empty.html', () => {});+ const navigationPromise = page.frames()[1].goto(server.EMPTY_PAGE).catch(e => e);+ await server.waitForRequest('/empty.html');++ await page.$eval('iframe', frame => frame.remove());+ const error = await navigationPromise;+ expect(error.message).toBe('Navigating frame was detached');+ });+ it.skip(WEBKIT)('should return matching responses', async({page, server}) => {+ // Disable cache: otherwise, chromium will cache similar requests.+ await page.setCacheEnabled(false);+ await page.goto(server.EMPTY_PAGE);+ // Attach three frames.+ const frames = await Promise.all([+ utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),+ utils.attachFrame(page, 'frame2', server.EMPTY_PAGE),+ utils.attachFrame(page, 'frame3', server.EMPTY_PAGE),+ ]);+ // Navigate all frames to the same URL.+ const serverResponses = [];+ server.setRoute('/one-style.html', (req, res) => serverResponses.push(res));+ const navigations = [];+ for (let i = 0; i < 3; ++i) {+ navigations.push(frames[i].goto(server.PREFIX + '/one-style.html'));+ await server.waitForRequest('/one-style.html');+ }+ // Respond from server out-of-order.+ const serverResponseTexts = ['AAA', 'BBB', 'CCC'];+ for (const i of [1, 2, 0]) {+ serverResponses[i].end(serverResponseTexts[i]);+ const response = await navigations[i];+ expect(response.frame()).toBe(frames[i]);+ expect(await response.text()).toBe(serverResponseTexts[i]);+ }+ });+ });++ describe('Frame.waitForNavigation', function() {+ it.skip(WEBKIT)('should work', async({page, server}) => {+ await page.goto(server.PREFIX + '/frames/one-frame.html');+ const frame = page.frames()[1];+ const [response] = await Promise.all([+ frame.waitForNavigation(),+ frame.evaluate(url => window.location.href = url, server.PREFIX + '/grid.html')+ ]);+ expect(response.ok()).toBe(true);+ expect(response.url()).toContain('grid.html');+ expect(response.frame()).toBe(frame);+ expect(page.url()).toContain('/frames/one-frame.html');+ });+ it.skip(WEBKIT)('should fail when frame detaches', async({page, server}) => {+ await page.goto(server.PREFIX + '/frames/one-frame.html');+ const frame = page.frames()[1];++ server.setRoute('/empty.html', () => {});+ let error = null;+ const navigationPromise = frame.waitForNavigation().catch(e => error = e);+ await Promise.all([+ server.waitForRequest('/empty.html'),+ frame.evaluate(() => window.location = '/empty.html')+ ]);+ await page.$eval('iframe', frame => frame.remove());+ await navigationPromise;+ expect(error.message).toBe('Navigating frame was detached');+ });+ });++ describe('Page.reload', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => window._foo = 10);+ await page.reload();+ expect(await page.evaluate(() => window._foo)).toBe(undefined);+ });+ });+};diff --git a/test/network.spec.js b/test/network.spec.jsnew file mode 100644index 0000000000..36f8eb44d8--- /dev/null+++ b/test/network.spec.js@@ -0,0 +1,445 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const fs = require('fs');+const path = require('path');+const utils = require('./utils');++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Page.Events.Request', function() {+ it('should fire for navigation requests', async({page, server}) => {+ const requests = [];+ page.on('request', request => !utils.isFavicon(request) && requests.push(request));+ await page.goto(server.EMPTY_PAGE);+ expect(requests.length).toBe(1);+ });+ it('should fire for iframes', async({page, server}) => {+ const requests = [];+ page.on('request', request => !utils.isFavicon(request) && requests.push(request));+ await page.goto(server.EMPTY_PAGE);+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ expect(requests.length).toBe(2);+ });+ it('should fire for fetches', async({page, server}) => {+ const requests = [];+ page.on('request', request => !utils.isFavicon(request) && requests.push(request));+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => fetch('/empty.html'));+ expect(requests.length).toBe(2);+ });+ });++ describe('Request.frame', function() {+ it('should work for main frame navigation request', async({page, server}) => {+ const requests = [];+ page.on('request', request => !utils.isFavicon(request) && requests.push(request));+ await page.goto(server.EMPTY_PAGE);+ expect(requests.length).toBe(1);+ expect(requests[0].frame()).toBe(page.mainFrame());+ });+ // FIXME: needs frameAttached event, otherwise it introduces too many hacks in the lib.+ it.skip(WEBKIT)('should work for subframe navigation request', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const requests = [];+ page.on('request', request => !utils.isFavicon(request) && requests.push(request));+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ expect(requests.length).toBe(1);+ expect(requests[0].frame()).toBe(page.frames()[1]);+ });+ it('should work for fetch requests', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ let requests = [];+ page.on('request', request => !utils.isFavicon(request) && requests.push(request));+ await page.evaluate(() => fetch('/digits/1.png'));+ requests = requests.filter(request => !request.url().includes('favicon'));+ expect(requests.length).toBe(1);+ expect(requests[0].frame()).toBe(page.mainFrame());+ });+ });++ describe('Request.headers', function() {+ it('should work', async({page, server}) => {+ const response = await page.goto(server.EMPTY_PAGE);+ if (CHROME)+ expect(response.request().headers()['user-agent']).toContain('Chrome');+ else if (FFOX)+ expect(response.request().headers()['user-agent']).toContain('Firefox');+ else if (WEBKIT)+ expect(response.request().headers()['user-agent']).toContain('WebKit');+ });+ });++ describe('Response.headers', function() {+ it('should work', async({page, server}) => {+ server.setRoute('/empty.html', (req, res) => {+ res.setHeader('foo', 'bar');+ res.end();+ });+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.headers()['foo']).toBe('bar');+ });+ });++ describe.skip(FFOX)('Response.fromCache', function() {+ it.skip(WEBKIT)('should return |false| for non-cached content', async({page, server}) => {+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.fromCache()).toBe(false);+ });++ it.skip(WEBKIT)('should work', async({page, server}) => {+ const responses = new Map();+ page.on('response', r => !utils.isFavicon(r.request()) && responses.set(r.url().split('/').pop(), r));++ // Load and re-load to make sure it's cached.+ await page.goto(server.PREFIX + '/cached/one-style.html');+ await page.reload();++ expect(responses.size).toBe(2);+ expect(responses.get('one-style.css').status()).toBe(200);+ expect(responses.get('one-style.css').fromCache()).toBe(true);+ expect(responses.get('one-style.html').status()).toBe(304);+ expect(responses.get('one-style.html').fromCache()).toBe(false);+ });+ });++ describe.skip(FFOX)('Response.fromServiceWorker', function() {+ it.skip(WEBKIT)('should return |false| for non-service-worker content', async({page, server}) => {+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.fromServiceWorker()).toBe(false);+ });++ // FIXME: WebKit responses contain sw.js+ it.skip(WEBKIT)('Response.fromServiceWorker', async({page, server}) => {+ const responses = new Map();+ page.on('response', r => responses.set(r.url().split('/').pop(), r));++ // Load and re-load to make sure serviceworker is installed and running.+ await page.goto(server.PREFIX + '/serviceworkers/fetch/sw.html', {waitUntil: 'networkidle2'});+ await page.evaluate(async() => await window.activationPromise);+ await page.reload();++ expect(responses.size).toBe(2);+ expect(responses.get('sw.html').status()).toBe(200);+ expect(responses.get('sw.html').fromServiceWorker()).toBe(true);+ expect(responses.get('style.css').status()).toBe(200);+ expect(responses.get('style.css').fromServiceWorker()).toBe(true);+ });+ });++ describe('Request.postData', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ server.setRoute('/post', (req, res) => res.end());+ let request = null;+ page.on('request', r => request = r);+ await page.evaluate(() => fetch('./post', { method: 'POST', body: JSON.stringify({foo: 'bar'})}));+ expect(request).toBeTruthy();+ expect(request.postData()).toBe('{"foo":"bar"}');+ });+ it('should be |undefined| when there is no post data', async({page, server}) => {+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.request().postData()).toBe(undefined);+ });+ });++ describe('Response.text', function() {+ it('should work', async({page, server}) => {+ const response = await page.goto(server.PREFIX + '/simple.json');+ expect(await response.text()).toBe('{"foo": "bar"}\n');+ });+ it('should return uncompressed text', async({page, server}) => {+ server.enableGzip('/simple.json');+ const response = await page.goto(server.PREFIX + '/simple.json');+ expect(response.headers()['content-encoding']).toBe('gzip');+ expect(await response.text()).toBe('{"foo": "bar"}\n');+ });+ it('should throw when requesting body of redirected response', async({page, server}) => {+ server.setRedirect('/foo.html', '/empty.html');+ const response = await page.goto(server.PREFIX + '/foo.html');+ const redirectChain = response.request().redirectChain();+ expect(redirectChain.length).toBe(1);+ const redirected = redirectChain[0].response();+ expect(redirected.status()).toBe(302);+ let error = null;+ await redirected.text().catch(e => error = e);+ expect(error.message).toContain('Response body is unavailable for redirect responses');+ });+ it('should wait until response completes', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ // Setup server to trap request.+ let serverResponse = null;+ server.setRoute('/get', (req, res) => {+ serverResponse = res;+ // In Firefox, |fetch| will be hanging until it receives |Content-Type| header+ // from server.+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');+ res.write('hello ');+ });+ // Setup page to trap response.+ let requestFinished = false;+ page.on('requestfinished', r => requestFinished = requestFinished || r.url().includes('/get'));+ // send request and wait for server response+ const [pageResponse] = await Promise.all([+ page.waitForResponse(r => !utils.isFavicon(r.request())),+ page.evaluate(() => fetch('./get', { method: 'GET'})),+ server.waitForRequest('/get'),+ ]);++ expect(serverResponse).toBeTruthy();+ expect(pageResponse).toBeTruthy();+ expect(pageResponse.status()).toBe(200);+ expect(requestFinished).toBe(false);++ const responseText = pageResponse.text();+ // Write part of the response and wait for it to be flushed.+ await new Promise(x => serverResponse.write('wor', x));+ // Finish response.+ await new Promise(x => serverResponse.end('ld!', x));+ expect(await responseText).toBe('hello world!');+ });+ });++ describe('Response.json', function() {+ it('should work', async({page, server}) => {+ const response = await page.goto(server.PREFIX + '/simple.json');+ expect(await response.json()).toEqual({foo: 'bar'});+ });+ });++ describe('Response.buffer', function() {+ it('should work', async({page, server}) => {+ const response = await page.goto(server.PREFIX + '/pptr.png');+ const imageBuffer = fs.readFileSync(path.join(__dirname, 'assets', 'pptr.png'));+ const responseBuffer = await response.buffer();+ expect(responseBuffer.equals(imageBuffer)).toBe(true);+ });+ it('should work with compression', async({page, server}) => {+ server.enableGzip('/pptr.png');+ const response = await page.goto(server.PREFIX + '/pptr.png');+ const imageBuffer = fs.readFileSync(path.join(__dirname, 'assets', 'pptr.png'));+ const responseBuffer = await response.buffer();+ expect(responseBuffer.equals(imageBuffer)).toBe(true);+ });+ });++ describe('Response.statusText', function() {+ it('should work', async({page, server}) => {+ server.setRoute('/cool', (req, res) => {+ res.writeHead(200, 'cool!');+ res.end();+ });+ const response = await page.goto(server.PREFIX + '/cool');+ expect(response.statusText()).toBe('cool!');+ });+ });++ describe('Network Events', function() {+ it('Page.Events.Request', async({page, server}) => {+ const requests = [];+ page.on('request', request => requests.push(request));+ await page.goto(server.EMPTY_PAGE);+ expect(requests.length).toBe(1);+ expect(requests[0].url()).toBe(server.EMPTY_PAGE);+ expect(requests[0].resourceType()).toBe('document');+ expect(requests[0].method()).toBe('GET');+ expect(requests[0].response()).toBeTruthy();+ expect(requests[0].frame() === page.mainFrame()).toBe(true);+ expect(requests[0].frame().url()).toBe(server.EMPTY_PAGE);+ });+ // FIXME: WebKit doesn't provide remoteIPAddress in the response.+ it.skip(WEBKIT)('Page.Events.Response', async({page, server}) => {+ const responses = [];+ page.on('response', response => responses.push(response));+ await page.goto(server.EMPTY_PAGE);+ expect(responses.length).toBe(1);+ expect(responses[0].url()).toBe(server.EMPTY_PAGE);+ expect(responses[0].status()).toBe(200);+ expect(responses[0].ok()).toBe(true);+ expect(responses[0].request()).toBeTruthy();+ const remoteAddress = responses[0].remoteAddress();+ // Either IPv6 or IPv4, depending on environment.+ expect(remoteAddress.ip.includes('::1') || remoteAddress.ip === '127.0.0.1').toBe(true);+ expect(remoteAddress.port).toBe(server.PORT);+ });++ // FIXME: requires request interception.+ it.skip(WEBKIT)('Page.Events.RequestFailed', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ if (request.url().endsWith('css'))+ request.abort();+ else+ request.continue();+ });+ const failedRequests = [];+ page.on('requestfailed', request => failedRequests.push(request));+ await page.goto(server.PREFIX + '/one-style.html');+ expect(failedRequests.length).toBe(1);+ expect(failedRequests[0].url()).toContain('one-style.css');+ expect(failedRequests[0].response()).toBe(null);+ expect(failedRequests[0].resourceType()).toBe('stylesheet');+ if (CHROME || WEBKIT)+ expect(failedRequests[0].failure().errorText).toBe('net::ERR_FAILED');+ else+ expect(failedRequests[0].failure().errorText).toBe('NS_ERROR_FAILURE');+ expect(failedRequests[0].frame()).toBeTruthy();+ });+ // FIXME: WebKit requestfinished comes after goto.+ it.skip(WEBKIT)('Page.Events.RequestFinished', async({page, server}) => {+ const requests = [];+ page.on('requestfinished', request => requests.push(request));+ await page.goto(server.EMPTY_PAGE);+ expect(requests.length).toBe(1);+ expect(requests[0].url()).toBe(server.EMPTY_PAGE);+ expect(requests[0].response()).toBeTruthy();+ expect(requests[0].frame() === page.mainFrame()).toBe(true);+ expect(requests[0].frame().url()).toBe(server.EMPTY_PAGE);+ });+ it.skip(WEBKIT)('should fire events in proper order', async({page, server}) => {+ const events = [];+ page.on('request', request => events.push('request'));+ page.on('response', response => events.push('response'));+ page.on('requestfinished', request => events.push('requestfinished'));+ await page.goto(server.EMPTY_PAGE);+ expect(events).toEqual(['request', 'response', 'requestfinished']);+ });+ it.skip(WEBKIT)('should support redirects', async({page, server}) => {+ const events = [];+ page.on('request', request => events.push(`${request.method()} ${request.url()}`));+ page.on('response', response => events.push(`${response.status()} ${response.url()}`));+ page.on('requestfinished', request => events.push(`DONE ${request.url()}`));+ page.on('requestfailed', request => events.push(`FAIL ${request.url()}`));+ server.setRedirect('/foo.html', '/empty.html');+ const FOO_URL = server.PREFIX + '/foo.html';+ const response = await page.goto(FOO_URL);+ expect(events).toEqual([+ `GET ${FOO_URL}`,+ `302 ${FOO_URL}`,+ `DONE ${FOO_URL}`,+ `GET ${server.EMPTY_PAGE}`,+ `200 ${server.EMPTY_PAGE}`,+ `DONE ${server.EMPTY_PAGE}`+ ]);++ // Check redirect chain+ const redirectChain = response.request().redirectChain();+ expect(redirectChain.length).toBe(1);+ expect(redirectChain[0].url()).toContain('/foo.html');+ expect(redirectChain[0].response().remoteAddress().port).toBe(server.PORT);+ });+ });++ describe('Request.isNavigationRequest', () => {+ it('should work', async({page, server}) => {+ const requests = new Map();+ page.on('request', request => requests.set(request.url().split('/').pop(), request));+ server.setRedirect('/rrredirect', '/frames/one-frame.html');+ await page.goto(server.PREFIX + '/rrredirect');+ expect(requests.get('rrredirect').isNavigationRequest()).toBe(true);+ expect(requests.get('one-frame.html').isNavigationRequest()).toBe(true);+ expect(requests.get('frame.html').isNavigationRequest()).toBe(true);+ expect(requests.get('script.js').isNavigationRequest()).toBe(false);+ expect(requests.get('style.css').isNavigationRequest()).toBe(false);+ });+ it.skip(WEBKIT)('should work with request interception', async({page, server}) => {+ const requests = new Map();+ page.on('request', request => {+ requests.set(request.url().split('/').pop(), request);+ request.continue();+ });+ await page.setRequestInterception(true);+ server.setRedirect('/rrredirect', '/frames/one-frame.html');+ await page.goto(server.PREFIX + '/rrredirect');+ expect(requests.get('rrredirect').isNavigationRequest()).toBe(true);+ expect(requests.get('one-frame.html').isNavigationRequest()).toBe(true);+ expect(requests.get('frame.html').isNavigationRequest()).toBe(true);+ expect(requests.get('script.js').isNavigationRequest()).toBe(false);+ expect(requests.get('style.css').isNavigationRequest()).toBe(false);+ });+ it('should work when navigating to image', async({page, server}) => {+ const requests = [];+ page.on('request', request => requests.push(request));+ await page.goto(server.PREFIX + '/pptr.png');+ expect(requests[0].isNavigationRequest()).toBe(true);+ });+ });++ describe('Page.setExtraHTTPHeaders', function() {+ it('should work', async({page, server}) => {+ await page.setExtraHTTPHeaders({+ foo: 'bar'+ });+ const [request] = await Promise.all([+ server.waitForRequest('/empty.html'),+ page.goto(server.EMPTY_PAGE),+ ]);+ expect(request.headers['foo']).toBe('bar');+ });+ it('should throw for non-string header values', async({page, server}) => {+ let error = null;+ try {+ await page.setExtraHTTPHeaders({ 'foo': 1 });+ } catch (e) {+ error = e;+ }+ expect(error.message).toBe('Expected value of header "foo" to be String, but "number" is found.');+ });+ });++ // FIXME: WebKit doesn't support network interception.+ describe.skip(FFOX || WEBKIT)('Page.authenticate', function() {+ it('should work', async({page, server}) => {+ server.setAuth('/empty.html', 'user', 'pass');+ let response = await page.goto(server.EMPTY_PAGE);+ expect(response.status()).toBe(401);+ await page.authenticate({+ username: 'user',+ password: 'pass'+ });+ response = await page.reload();+ expect(response.status()).toBe(200);+ });+ it('should fail if wrong credentials', async({page, server}) => {+ // Use unique user/password since Chrome caches credentials per origin.+ server.setAuth('/empty.html', 'user2', 'pass2');+ await page.authenticate({+ username: 'foo',+ password: 'bar'+ });+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.status()).toBe(401);+ });+ it('should allow disable authentication', async({page, server}) => {+ // Use unique user/password since Chrome caches credentials per origin.+ server.setAuth('/empty.html', 'user3', 'pass3');+ await page.authenticate({+ username: 'user3',+ password: 'pass3'+ });+ let response = await page.goto(server.EMPTY_PAGE);+ expect(response.status()).toBe(200);+ await page.authenticate(null);+ // Navigate to a different origin to bust Chrome's credential caching.+ response = await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html');+ expect(response.status()).toBe(401);+ });+ });+};+diff --git a/test/oopif.spec.js b/test/oopif.spec.jsnew file mode 100644index 0000000000..0bc5496799--- /dev/null+++ b/test/oopif.spec.js@@ -0,0 +1,61 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, defaultBrowserOptions, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('OOPIF', function() {+ beforeAll(async function(state) {+ state.browser = await playwright.launch(Object.assign({}, defaultBrowserOptions, {+ args: (defaultBrowserOptions.args || []).concat(['--site-per-process']),+ }));+ });+ beforeEach(async function(state) {+ state.context = await state.browser.createIncognitoBrowserContext();+ state.page = await state.context.newPage();+ });+ afterEach(async function(state) {+ await state.context.close();+ state.page = null;+ state.context = null;+ });+ afterAll(async function(state) {+ await state.browser.close();+ state.browser = null;+ });+ xit('should report oopif frames', async function({page, server, context}) {+ await page.goto(server.PREFIX + '/dynamic-oopif.html');+ expect(oopifs(context).length).toBe(1);+ expect(page.frames().length).toBe(2);+ });+ it('should load oopif iframes with subresources and request interception', async function({page, server, context}) {+ await page.setRequestInterception(true);+ page.on('request', request => request.continue());+ await page.goto(server.PREFIX + '/dynamic-oopif.html');+ expect(oopifs(context).length).toBe(1);+ });+ });+};+++/**+ * @param {!Playwright.BrowserContext} context+ */+function oopifs(context) {+ return context.targets().filter(target => target._targetInfo.type === 'iframe');+}diff --git a/test/page.spec.js b/test/page.spec.jsnew file mode 100644index 0000000000..ec9de5a6d9--- /dev/null+++ b/test/page.spec.js@@ -0,0 +1,1265 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+const fs = require('fs');+const path = require('path');+const utils = require('./utils');+const {waitEvent} = utils;++module.exports.addTests = function({testRunner, expect, headless, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Page.close', function() {+ it('should reject all promises when page is closed', async({context}) => {+ const newPage = await context.newPage();+ let error = null;+ await Promise.all([+ newPage.evaluate(() => new Promise(r => {})).catch(e => error = e),+ newPage.close(),+ ]);+ expect(error.message).toContain('Protocol error');+ });+ it('should not be visible in browser.pages', async({browser}) => {+ const newPage = await browser.newPage();+ expect(await browser.pages()).toContain(newPage);+ await newPage.close();+ expect(await browser.pages()).not.toContain(newPage);+ });+ it.skip(WEBKIT)('should run beforeunload if asked for', async({context, server}) => {+ const newPage = await context.newPage();+ await newPage.goto(server.PREFIX + '/beforeunload.html');+ // We have to interact with a page so that 'beforeunload' handlers+ // fire.+ await newPage.click('body');+ const pageClosingPromise = newPage.close({ runBeforeUnload: true });+ const dialog = await waitEvent(newPage, 'dialog');+ expect(dialog.type()).toBe('beforeunload');+ expect(dialog.defaultValue()).toBe('');+ if (CHROME || WEBKIT)+ expect(dialog.message()).toBe('');+ else+ expect(dialog.message()).toBe('This page is asking you to confirm that you want to leave - data you have entered may not be saved.');+ await dialog.accept();+ await pageClosingPromise;+ });+ it.skip(WEBKIT)('should *not* run beforeunload by default', async({context, server}) => {+ const newPage = await context.newPage();+ await newPage.goto(server.PREFIX + '/beforeunload.html');+ // We have to interact with a page so that 'beforeunload' handlers+ // fire.+ await newPage.click('body');+ await newPage.close();+ });+ it('should set the page close state', async({context}) => {+ const newPage = await context.newPage();+ expect(newPage.isClosed()).toBe(false);+ await newPage.close();+ expect(newPage.isClosed()).toBe(true);+ });+ it.skip(FFOX || WEBKIT)('should terminate network waiters', async({context, server}) => {+ const newPage = await context.newPage();+ const results = await Promise.all([+ newPage.waitForRequest(server.EMPTY_PAGE).catch(e => e),+ newPage.waitForResponse(server.EMPTY_PAGE).catch(e => e),+ newPage.close()+ ]);+ for (let i = 0; i < 2; i++) {+ const message = results[i].message;+ expect(message).toContain('Target closed');+ expect(message).not.toContain('Timeout');+ }+ });+ });++ describe('Page.Events.Load', function() {+ it('should fire when expected', async({page, server}) => {+ await Promise.all([+ page.goto('about:blank'),+ utils.waitEvent(page, 'load'),+ ]);+ });+ });++ describe('Async stacks', () => {+ it.skip(WEBKIT)('should work', async({page, server}) => {+ server.setRoute('/empty.html', (req, res) => {+ res.statusCode = 204;+ res.end();+ });+ let error = null;+ await page.goto(server.EMPTY_PAGE).catch(e => error = e);+ expect(error).not.toBe(null);+ expect(error.stack).toContain(__filename);+ });+ });++ describe.skip(FFOX || WEBKIT)('Page.Events.error', function() {+ it('should throw when page crashes', async({page}) => {+ let error = null;+ page.on('error', err => error = err);+ page.goto('chrome://crash').catch(e => {});+ await waitEvent(page, 'error');+ expect(error.message).toBe('Page crashed!');+ });+ });++ describe.skip(WEBKIT)('Page.Events.Popup', function() {+ it('should work', async({page}) => {+ const [popup] = await Promise.all([+ new Promise(x => page.once('popup', x)),+ page.evaluate(() => window.open('about:blank')),+ ]);+ expect(await page.evaluate(() => !!window.opener)).toBe(false);+ expect(await popup.evaluate(() => !!window.opener)).toBe(true);+ });+ it('should work with noopener', async({page}) => {+ const [popup] = await Promise.all([+ new Promise(x => page.once('popup', x)),+ page.evaluate(() => window.open('about:blank', null, 'noopener')),+ ]);+ expect(await page.evaluate(() => !!window.opener)).toBe(false);+ expect(await popup.evaluate(() => !!window.opener)).toBe(false);+ });+ it('should work with clicking target=_blank', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setContent('<a target=_blank href="/one-style.html">yo</a>');+ const [popup] = await Promise.all([+ new Promise(x => page.once('popup', x)),+ page.click('a'),+ ]);+ expect(await page.evaluate(() => !!window.opener)).toBe(false);+ expect(await popup.evaluate(() => !!window.opener)).toBe(true);+ });+ it('should work with fake-clicking target=_blank and rel=noopener', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setContent('<a target=_blank rel=noopener href="/one-style.html">yo</a>');+ const [popup] = await Promise.all([+ new Promise(x => page.once('popup', x)),+ page.$eval('a', a => a.click()),+ ]);+ expect(await page.evaluate(() => !!window.opener)).toBe(false);+ expect(await popup.evaluate(() => !!window.opener)).toBe(false);+ });+ it('should work with clicking target=_blank and rel=noopener', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setContent('<a target=_blank rel=noopener href="/one-style.html">yo</a>');+ const [popup] = await Promise.all([+ new Promise(x => page.once('popup', x)),+ page.click('a'),+ ]);+ expect(await page.evaluate(() => !!window.opener)).toBe(false);+ expect(await popup.evaluate(() => !!window.opener)).toBe(false);+ });+ });++ // Permissions API is not implemented in WebKit (see https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API)+ describe('BrowserContext.overridePermissions', function() {+ function getPermission(page, name) {+ return page.evaluate(name => navigator.permissions.query({name}).then(result => result.state), name);+ }++ it.skip(WEBKIT)('should be prompt by default', async({page, server, context}) => {+ await page.goto(server.EMPTY_PAGE);+ expect(await getPermission(page, 'geolocation')).toBe('prompt');+ });+ it.skip(WEBKIT)('should deny permission when not listed', async({page, server, context}) => {+ await page.goto(server.EMPTY_PAGE);+ await context.overridePermissions(server.EMPTY_PAGE, []);+ expect(await getPermission(page, 'geolocation')).toBe('denied');+ });+ it.skip(WEBKIT)('should fail when bad permission is given', async({page, server, context}) => {+ await page.goto(server.EMPTY_PAGE);+ let error = null;+ await context.overridePermissions(server.EMPTY_PAGE, ['foo']).catch(e => error = e);+ expect(error.message).toBe('Unknown permission: foo');+ });+ it.skip(WEBKIT)('should grant permission when listed', async({page, server, context}) => {+ await page.goto(server.EMPTY_PAGE);+ await context.overridePermissions(server.EMPTY_PAGE, ['geolocation']);+ expect(await getPermission(page, 'geolocation')).toBe('granted');+ });+ it.skip(WEBKIT)('should reset permissions', async({page, server, context}) => {+ await page.goto(server.EMPTY_PAGE);+ await context.overridePermissions(server.EMPTY_PAGE, ['geolocation']);+ expect(await getPermission(page, 'geolocation')).toBe('granted');+ await context.clearPermissionOverrides();+ expect(await getPermission(page, 'geolocation')).toBe('prompt');+ });+ it.skip(WEBKIT)('should trigger permission onchange', async({page, server, context}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => {+ window.events = [];+ return navigator.permissions.query({name: 'geolocation'}).then(function(result) {+ window.events.push(result.state);+ result.onchange = function() {+ window.events.push(result.state);+ };+ });+ });+ expect(await page.evaluate(() => window.events)).toEqual(['prompt']);+ await context.overridePermissions(server.EMPTY_PAGE, []);+ expect(await page.evaluate(() => window.events)).toEqual(['prompt', 'denied']);+ await context.overridePermissions(server.EMPTY_PAGE, ['geolocation']);+ expect(await page.evaluate(() => window.events)).toEqual(['prompt', 'denied', 'granted']);+ await context.clearPermissionOverrides();+ expect(await page.evaluate(() => window.events)).toEqual(['prompt', 'denied', 'granted', 'prompt']);+ });+ it.skip(WEBKIT)('should isolate permissions between browser contexs', async({page, server, context, browser}) => {+ await page.goto(server.EMPTY_PAGE);+ const otherContext = await browser.createIncognitoBrowserContext();+ const otherPage = await otherContext.newPage();+ await otherPage.goto(server.EMPTY_PAGE);+ expect(await getPermission(page, 'geolocation')).toBe('prompt');+ expect(await getPermission(otherPage, 'geolocation')).toBe('prompt');++ await context.overridePermissions(server.EMPTY_PAGE, []);+ await otherContext.overridePermissions(server.EMPTY_PAGE, ['geolocation']);+ expect(await getPermission(page, 'geolocation')).toBe('denied');+ expect(await getPermission(otherPage, 'geolocation')).toBe('granted');++ await context.clearPermissionOverrides();+ expect(await getPermission(page, 'geolocation')).toBe('prompt');+ expect(await getPermission(otherPage, 'geolocation')).toBe('granted');++ await otherContext.close();+ });+ });++ // FIXME: not supported in WebKit (as well as Emulation domain in general).+ // It was removed from WebKit in https://webkit.org/b/126630+ describe.skip(FFOX || WEBKIT)('Page.setGeolocation', function() {+ it('should work', async({page, server, context}) => {+ await context.overridePermissions(server.PREFIX, ['geolocation']);+ await page.goto(server.EMPTY_PAGE);+ await page.setGeolocation({longitude: 10, latitude: 10});+ const geolocation = await page.evaluate(() => new Promise(resolve => navigator.geolocation.getCurrentPosition(position => {+ resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});+ })));+ expect(geolocation).toEqual({+ latitude: 10,+ longitude: 10+ });+ });+ it('should throw when invalid longitude', async({page, server, context}) => {+ let error = null;+ try {+ await page.setGeolocation({longitude: 200, latitude: 10});+ } catch (e) {+ error = e;+ }+ expect(error.message).toContain('Invalid longitude "200"');+ });+ });++ describe.skip(FFOX || WEBKIT)('Page.setOfflineMode', function() {+ it('should work', async({page, server}) => {+ await page.setOfflineMode(true);+ let error = null;+ await page.goto(server.EMPTY_PAGE).catch(e => error = e);+ expect(error).toBeTruthy();+ await page.setOfflineMode(false);+ const response = await page.reload();+ expect(response.status()).toBe(200);+ });+ it('should emulate navigator.onLine', async({page, server}) => {+ expect(await page.evaluate(() => window.navigator.onLine)).toBe(true);+ await page.setOfflineMode(true);+ expect(await page.evaluate(() => window.navigator.onLine)).toBe(false);+ await page.setOfflineMode(false);+ expect(await page.evaluate(() => window.navigator.onLine)).toBe(true);+ });+ });++ describe.skip(FFOX || WEBKIT)('ExecutionContext.queryObjects', function() {+ it('should work', async({page, server}) => {+ // Instantiate an object+ await page.evaluate(() => window.set = new Set(['hello', 'world']));+ const prototypeHandle = await page.evaluateHandle(() => Set.prototype);+ const objectsHandle = await page.queryObjects(prototypeHandle);+ const count = await page.evaluate(objects => objects.length, objectsHandle);+ expect(count).toBe(1);+ const values = await page.evaluate(objects => Array.from(objects[0].values()), objectsHandle);+ expect(values).toEqual(['hello', 'world']);+ });+ it('should work for non-blank page', async({page, server}) => {+ // Instantiate an object+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => window.set = new Set(['hello', 'world']));+ const prototypeHandle = await page.evaluateHandle(() => Set.prototype);+ const objectsHandle = await page.queryObjects(prototypeHandle);+ const count = await page.evaluate(objects => objects.length, objectsHandle);+ expect(count).toBe(1);+ });+ it('should fail for disposed handles', async({page, server}) => {+ const prototypeHandle = await page.evaluateHandle(() => HTMLBodyElement.prototype);+ await prototypeHandle.dispose();+ let error = null;+ await page.queryObjects(prototypeHandle).catch(e => error = e);+ expect(error.message).toBe('Prototype JSHandle is disposed!');+ });+ it('should fail primitive values as prototypes', async({page, server}) => {+ const prototypeHandle = await page.evaluateHandle(() => 42);+ let error = null;+ await page.queryObjects(prototypeHandle).catch(e => error = e);+ expect(error.message).toBe('Prototype JSHandle must not be referencing primitive value');+ });+ });++ describe('Page.Events.Console', function() {+ it('should work', async({page, server}) => {+ let message = null;+ page.once('console', m => message = m);+ await Promise.all([+ page.evaluate(() => console.log('hello', 5, {foo: 'bar'})),+ waitEvent(page, 'console')+ ]);+ expect(message.text()).toEqual('hello 5 JSHandle@object');+ expect(message.type()).toEqual('log');+ expect(await message.args()[0].jsonValue()).toEqual('hello');+ expect(await message.args()[1].jsonValue()).toEqual(5);+ expect(await message.args()[2].jsonValue()).toEqual({foo: 'bar'});+ });+ it('should work for different console API calls', async({page, server}) => {+ const messages = [];+ page.on('console', msg => messages.push(msg));+ // All console events will be reported before `page.evaluate` is finished.+ await page.evaluate(() => {+ // A pair of time/timeEnd generates only one Console API call.+ console.time('calling console.time');+ console.timeEnd('calling console.time');+ console.trace('calling console.trace');+ console.dir('calling console.dir');+ console.warn('calling console.warn');+ console.error('calling console.error');+ console.log(Promise.resolve('should not wait until resolved!'));+ });+ expect(messages.map(msg => msg.type())).toEqual([+ 'timeEnd', 'trace', 'dir', 'warning', 'error', 'log'+ ]);+ expect(messages[0].text()).toContain('calling console.time');+ expect(messages.slice(1).map(msg => msg.text())).toEqual([+ 'calling console.trace',+ 'calling console.dir',+ 'calling console.warn',+ 'calling console.error',+ 'JSHandle@promise',+ ]);+ });+ it('should not fail for window object', async({page, server}) => {+ let message = null;+ page.once('console', msg => message = msg);+ await Promise.all([+ page.evaluate(() => console.error(window)),+ waitEvent(page, 'console')+ ]);+ expect(message.text()).toBe('JSHandle@object');+ });+ it('should trigger correct Log', async({page, server}) => {+ await page.goto('about:blank');+ const [message] = await Promise.all([+ waitEvent(page, 'console'),+ page.evaluate(async url => fetch(url).catch(e => {}), server.EMPTY_PAGE)+ ]);+ expect(message.text()).toContain('Access-Control-Allow-Origin');+ if (CHROME || WEBKIT)+ expect(message.type()).toEqual('error');+ else+ expect(message.type()).toEqual('warn');+ });+ it.skip(FFOX || WEBKIT)('should have location when fetch fails', async({page, server}) => {+ // The point of this test is to make sure that we report console messages from+ // Log domain: https://vanilla.aslushnikov.com/?Log.entryAdded+ await page.goto(server.EMPTY_PAGE);+ const [message] = await Promise.all([+ waitEvent(page, 'console'),+ page.setContent(`<script>fetch('http://wat');</script>`),+ ]);+ expect(message.text()).toContain(`ERR_NAME_NOT_RESOLVED`);+ expect(message.type()).toEqual('error');+ expect(message.location()).toEqual({+ url: 'http://wat/',+ lineNumber: undefined+ });+ });+ it.skip(WEBKIT)('should have location for console API calls', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const [message] = await Promise.all([+ waitEvent(page, 'console'),+ page.goto(server.PREFIX + '/consolelog.html'),+ ]);+ expect(message.text()).toBe('yellow');+ expect(message.type()).toBe('log');+ expect(message.location()).toEqual({+ url: server.PREFIX + '/consolelog.html',+ lineNumber: 7,+ columnNumber: 14,+ });+ });+ // @see https://github.com/GoogleChrome/puppeteer/issues/3865+ it.skip(FFOX || WEBKIT)('should not throw when there are console messages in detached iframes', async({browser, page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(async() => {+ // 1. Create a popup that Playwright is not connected to.+ const win = window.open(window.location.href, 'Title', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=0,left=0');+ await new Promise(x => win.onload = x);+ // 2. In this popup, create an iframe that console.logs a message.+ win.document.body.innerHTML = `<iframe src='/consolelog.html'></iframe>`;+ const frame = win.document.querySelector('iframe');+ await new Promise(x => frame.onload = x);+ // 3. After that, remove the iframe.+ frame.remove();+ });+ const popupTarget = page.browserContext().targets().find(target => target !== page.target());+ // 4. Connect to the popup and make sure it doesn't throw.+ await popupTarget.page();+ });+ });++ describe('Page.Events.DOMContentLoaded', function() {+ it('should fire when expected', async({page, server}) => {+ page.goto('about:blank');+ await waitEvent(page, 'domcontentloaded');+ });+ });++ describe.skip(FFOX || WEBKIT)('Page.metrics', function() {+ it('should get metrics from a page', async({page, server}) => {+ await page.goto('about:blank');+ const metrics = await page.metrics();+ checkMetrics(metrics);+ });+ it('metrics event fired on console.timeStamp', async({page, server}) => {+ const metricsPromise = new Promise(fulfill => page.once('metrics', fulfill));+ await page.evaluate(() => console.timeStamp('test42'));+ const metrics = await metricsPromise;+ expect(metrics.title).toBe('test42');+ checkMetrics(metrics.metrics);+ });+ function checkMetrics(metrics) {+ const metricsToCheck = new Set([+ 'Timestamp',+ 'Documents',+ 'Frames',+ 'JSEventListeners',+ 'Nodes',+ 'LayoutCount',+ 'RecalcStyleCount',+ 'LayoutDuration',+ 'RecalcStyleDuration',+ 'ScriptDuration',+ 'TaskDuration',+ 'JSHeapUsedSize',+ 'JSHeapTotalSize',+ ]);+ for (const name in metrics) {+ expect(metricsToCheck.has(name)).toBeTruthy();+ expect(metrics[name]).toBeGreaterThanOrEqual(0);+ metricsToCheck.delete(name);+ }+ expect(metricsToCheck.size).toBe(0);+ }+ });++ describe('Page.waitForRequest', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const [request] = await Promise.all([+ page.waitForRequest(server.PREFIX + '/digits/2.png'),+ page.evaluate(() => {+ fetch('/digits/1.png');+ fetch('/digits/2.png');+ fetch('/digits/3.png');+ })+ ]);+ expect(request.url()).toBe(server.PREFIX + '/digits/2.png');+ });+ it('should work with predicate', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const [request] = await Promise.all([+ page.waitForRequest(request => request.url() === server.PREFIX + '/digits/2.png'),+ page.evaluate(() => {+ fetch('/digits/1.png');+ fetch('/digits/2.png');+ fetch('/digits/3.png');+ })+ ]);+ expect(request.url()).toBe(server.PREFIX + '/digits/2.png');+ });+ it('should respect timeout', async({page, server}) => {+ let error = null;+ await page.waitForRequest(() => false, {timeout: 1}).catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should respect default timeout', async({page, server}) => {+ let error = null;+ page.setDefaultTimeout(1);+ await page.waitForRequest(() => false).catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should work with no timeout', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const [request] = await Promise.all([+ page.waitForRequest(server.PREFIX + '/digits/2.png', {timeout: 0}),+ page.evaluate(() => setTimeout(() => {+ fetch('/digits/1.png');+ fetch('/digits/2.png');+ fetch('/digits/3.png');+ }, 50))+ ]);+ expect(request.url()).toBe(server.PREFIX + '/digits/2.png');+ });+ });++ describe('Page.waitForResponse', function() {+ it('should work', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const [response] = await Promise.all([+ page.waitForResponse(server.PREFIX + '/digits/2.png'),+ page.evaluate(() => {+ fetch('/digits/1.png');+ fetch('/digits/2.png');+ fetch('/digits/3.png');+ })+ ]);+ expect(response.url()).toBe(server.PREFIX + '/digits/2.png');+ });+ it('should respect timeout', async({page, server}) => {+ let error = null;+ await page.waitForResponse(() => false, {timeout: 1}).catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should respect default timeout', async({page, server}) => {+ let error = null;+ page.setDefaultTimeout(1);+ await page.waitForResponse(() => false).catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should work with predicate', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const [response] = await Promise.all([+ page.waitForResponse(response => response.url() === server.PREFIX + '/digits/2.png'),+ page.evaluate(() => {+ fetch('/digits/1.png');+ fetch('/digits/2.png');+ fetch('/digits/3.png');+ })+ ]);+ expect(response.url()).toBe(server.PREFIX + '/digits/2.png');+ });+ it('should work with no timeout', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const [response] = await Promise.all([+ page.waitForResponse(server.PREFIX + '/digits/2.png', {timeout: 0}),+ page.evaluate(() => setTimeout(() => {+ fetch('/digits/1.png');+ fetch('/digits/2.png');+ fetch('/digits/3.png');+ }, 50))+ ]);+ expect(response.url()).toBe(server.PREFIX + '/digits/2.png');+ });+ });++ describe('Page.exposeFunction', function() {+ it.skip(WEBKIT)('should work', async({page, server}) => {+ await page.exposeFunction('compute', function(a, b) {+ return a * b;+ });+ const result = await page.evaluate(async function() {+ return await compute(9, 4);+ });+ expect(result).toBe(36);+ });+ it.skip(WEBKIT)('should throw exception in page context', async({page, server}) => {+ await page.exposeFunction('woof', function() {+ throw new Error('WOOF WOOF');+ });+ const {message, stack} = await page.evaluate(async() => {+ try {+ await woof();+ } catch (e) {+ return {message: e.message, stack: e.stack};+ }+ });+ expect(message).toBe('WOOF WOOF');+ expect(stack).toContain(__filename);+ });+ it.skip(WEBKIT)('should support throwing "null"', async({page, server}) => {+ await page.exposeFunction('woof', function() {+ throw null;+ });+ const thrown = await page.evaluate(async() => {+ try {+ await woof();+ } catch (e) {+ return e;+ }+ });+ expect(thrown).toBe(null);+ });+ it.skip(WEBKIT)('should be callable from-inside evaluateOnNewDocument', async({page, server}) => {+ let called = false;+ await page.exposeFunction('woof', function() {+ called = true;+ });+ await page.evaluateOnNewDocument(() => woof());+ await page.reload();+ expect(called).toBe(true);+ });+ it.skip(WEBKIT)('should survive navigation', async({page, server}) => {+ await page.exposeFunction('compute', function(a, b) {+ return a * b;+ });++ await page.goto(server.EMPTY_PAGE);+ const result = await page.evaluate(async function() {+ return await compute(9, 4);+ });+ expect(result).toBe(36);+ });+ it.skip(WEBKIT)('should await returned promise', async({page, server}) => {+ await page.exposeFunction('compute', function(a, b) {+ return Promise.resolve(a * b);+ });++ const result = await page.evaluate(async function() {+ return await compute(3, 5);+ });+ expect(result).toBe(15);+ });+ it.skip(WEBKIT)('should work on frames', async({page, server}) => {+ await page.exposeFunction('compute', function(a, b) {+ return Promise.resolve(a * b);+ });++ await page.goto(server.PREFIX + '/frames/nested-frames.html');+ const frame = page.frames()[1];+ const result = await frame.evaluate(async function() {+ return await compute(3, 5);+ });+ expect(result).toBe(15);+ });+ it.skip(WEBKIT)('should work on frames before navigation', async({page, server}) => {+ await page.goto(server.PREFIX + '/frames/nested-frames.html');+ await page.exposeFunction('compute', function(a, b) {+ return Promise.resolve(a * b);+ });++ const frame = page.frames()[1];+ const result = await frame.evaluate(async function() {+ return await compute(3, 5);+ });+ expect(result).toBe(15);+ });+ it.skip(WEBKIT)('should work with complex objects', async({page, server}) => {+ await page.exposeFunction('complexObject', function(a, b) {+ return {x: a.x + b.x};+ });+ const result = await page.evaluate(async() => complexObject({x: 5}, {x: 2}));+ expect(result.x).toBe(7);+ });+ });++ describe('Page.Events.PageError', function() {+ it.skip(WEBKIT)('should fire', async({page, server}) => {+ let error = null;+ page.once('pageerror', e => error = e);+ await Promise.all([+ page.goto(server.PREFIX + '/error.html'),+ waitEvent(page, 'pageerror')+ ]);+ expect(error.message).toContain('Fancy');+ });+ });++ describe('Page.setUserAgent', function() {+ it('should work', async({page, server}) => {+ expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');+ await page.setUserAgent('foobar');+ const [request] = await Promise.all([+ server.waitForRequest('/empty.html'),+ page.goto(server.EMPTY_PAGE),+ ]);+ expect(request.headers['user-agent']).toBe('foobar');+ });+ it('should work for subframes', async({page, server}) => {+ expect(await page.evaluate(() => navigator.userAgent)).toContain('Mozilla');+ await page.setUserAgent('foobar');+ const [request] = await Promise.all([+ server.waitForRequest('/empty.html'),+ utils.attachFrame(page, 'frame1', server.EMPTY_PAGE),+ ]);+ expect(request.headers['user-agent']).toBe('foobar');+ });+ it.skip(WEBKIT)('should emulate device user-agent', async({page, server}) => {+ await page.goto(server.PREFIX + '/mobile.html');+ expect(await page.evaluate(() => navigator.userAgent)).not.toContain('iPhone');+ await page.setUserAgent(playwright.devices['iPhone 6'].userAgent);+ expect(await page.evaluate(() => navigator.userAgent)).toContain('iPhone');+ });+ });++ describe('Page.setContent', function() {+ const expectedOutput = '<html><head></head><body><div>hello</div></body></html>';+ it('should work', async({page, server}) => {+ await page.setContent('<div>hello</div>');+ const result = await page.content();+ expect(result).toBe(expectedOutput);+ });+ it('should work with doctype', async({page, server}) => {+ const doctype = '<!DOCTYPE html>';+ await page.setContent(`${doctype}<div>hello</div>`);+ const result = await page.content();+ expect(result).toBe(`${doctype}${expectedOutput}`);+ });+ it('should work with HTML 4 doctype', async({page, server}) => {+ const doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" ' ++ '"http://www.w3.org/TR/html4/strict.dtd">';+ await page.setContent(`${doctype}<div>hello</div>`);+ const result = await page.content();+ expect(result).toBe(`${doctype}${expectedOutput}`);+ });+ it.skip(FFOX)('should respect timeout', async({page, server}) => {+ const imgPath = '/img.png';+ // stall for image+ server.setRoute(imgPath, (req, res) => {});+ let error = null;+ await page.setContent(`<img src="${server.PREFIX + imgPath}"></img>`, {timeout: 1}).catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it.skip(FFOX)('should respect default navigation timeout', async({page, server}) => {+ page.setDefaultNavigationTimeout(1);+ const imgPath = '/img.png';+ // stall for image+ server.setRoute(imgPath, (req, res) => {});+ let error = null;+ await page.setContent(`<img src="${server.PREFIX + imgPath}"></img>`).catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it.skip(FFOX)('should await resources to load', async({page, server}) => {+ const imgPath = '/img.png';+ let imgResponse = null;+ server.setRoute(imgPath, (req, res) => imgResponse = res);+ let loaded = false;+ const contentPromise = page.setContent(`<img src="${server.PREFIX + imgPath}"></img>`).then(() => loaded = true);+ await server.waitForRequest(imgPath);+ expect(loaded).toBe(false);+ imgResponse.end();+ await contentPromise;+ });+ it('should work fast enough', async({page, server}) => {+ for (let i = 0; i < 20; ++i)+ await page.setContent('<div>yo</div>');+ });+ it('should work with tricky content', async({page, server}) => {+ await page.setContent('<div>hello world</div>' + '\x7F');+ expect(await page.$eval('div', div => div.textContent)).toBe('hello world');+ });+ it('should work with accents', async({page, server}) => {+ await page.setContent('<div>aberración</div>');+ expect(await page.$eval('div', div => div.textContent)).toBe('aberración');+ });+ it('should work with emojis', async({page, server}) => {+ await page.setContent('<div>🐥</div>');+ expect(await page.$eval('div', div => div.textContent)).toBe('🐥');+ });+ it('should work with newline', async({page, server}) => {+ await page.setContent('<div>\n</div>');+ expect(await page.$eval('div', div => div.textContent)).toBe('\n');+ });+ });++ describe.skip(FFOX || WEBKIT)('Page.setBypassCSP', function() {+ it('should bypass CSP meta tag', async({page, server}) => {+ // Make sure CSP prohibits addScriptTag.+ await page.goto(server.PREFIX + '/csp.html');+ await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);+ expect(await page.evaluate(() => window.__injected)).toBe(undefined);++ // By-pass CSP and try one more time.+ await page.setBypassCSP(true);+ await page.reload();+ await page.addScriptTag({content: 'window.__injected = 42;'});+ expect(await page.evaluate(() => window.__injected)).toBe(42);+ });++ it('should bypass CSP header', async({page, server}) => {+ // Make sure CSP prohibits addScriptTag.+ server.setCSP('/empty.html', 'default-src "self"');+ await page.goto(server.EMPTY_PAGE);+ await page.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);+ expect(await page.evaluate(() => window.__injected)).toBe(undefined);++ // By-pass CSP and try one more time.+ await page.setBypassCSP(true);+ await page.reload();+ await page.addScriptTag({content: 'window.__injected = 42;'});+ expect(await page.evaluate(() => window.__injected)).toBe(42);+ });++ it('should bypass after cross-process navigation', async({page, server}) => {+ await page.setBypassCSP(true);+ await page.goto(server.PREFIX + '/csp.html');+ await page.addScriptTag({content: 'window.__injected = 42;'});+ expect(await page.evaluate(() => window.__injected)).toBe(42);++ await page.goto(server.CROSS_PROCESS_PREFIX + '/csp.html');+ await page.addScriptTag({content: 'window.__injected = 42;'});+ expect(await page.evaluate(() => window.__injected)).toBe(42);+ });+ it('should bypass CSP in iframes as well', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ {+ // Make sure CSP prohibits addScriptTag in an iframe.+ const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');+ await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);+ expect(await frame.evaluate(() => window.__injected)).toBe(undefined);+ }++ // By-pass CSP and try one more time.+ await page.setBypassCSP(true);+ await page.reload();++ {+ const frame = await utils.attachFrame(page, 'frame1', server.PREFIX + '/csp.html');+ await frame.addScriptTag({content: 'window.__injected = 42;'}).catch(e => void e);+ expect(await frame.evaluate(() => window.__injected)).toBe(42);+ }+ });+ });++ describe('Page.addScriptTag', function() {+ it('should throw an error if no options are provided', async({page, server}) => {+ let error = null;+ try {+ await page.addScriptTag('/injectedfile.js');+ } catch (e) {+ error = e;+ }+ expect(error.message).toBe('Provide an object with a `url`, `path` or `content` property');+ });++ it('should work with a url', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const scriptHandle = await page.addScriptTag({ url: '/injectedfile.js' });+ expect(scriptHandle.asElement()).not.toBeNull();+ expect(await page.evaluate(() => __injected)).toBe(42);+ });++ it('should work with a url and type=module', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.addScriptTag({ url: '/es6/es6import.js', type: 'module' });+ expect(await page.evaluate(() => __es6injected)).toBe(42);+ });++ it('should work with a path and type=module', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.addScriptTag({ path: path.join(__dirname, 'assets/es6/es6pathimport.js'), type: 'module' });+ await page.waitForFunction('window.__es6injected');+ expect(await page.evaluate(() => __es6injected)).toBe(42);+ });++ it('should work with a content and type=module', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.addScriptTag({ content: `import num from '/es6/es6module.js';window.__es6injected = num;`, type: 'module' });+ await page.waitForFunction('window.__es6injected');+ expect(await page.evaluate(() => __es6injected)).toBe(42);+ });++ it('should throw an error if loading from url fail', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ let error = null;+ try {+ await page.addScriptTag({ url: '/nonexistfile.js' });+ } catch (e) {+ error = e;+ }+ expect(error.message).toBe('Loading script from /nonexistfile.js failed');+ });++ it('should work with a path', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const scriptHandle = await page.addScriptTag({ path: path.join(__dirname, 'assets/injectedfile.js') });+ expect(scriptHandle.asElement()).not.toBeNull();+ expect(await page.evaluate(() => __injected)).toBe(42);+ });++ it.skip(WEBKIT)('should include sourcemap when path is provided', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.addScriptTag({ path: path.join(__dirname, 'assets/injectedfile.js') });+ const result = await page.evaluate(() => __injectedError.stack);+ expect(result).toContain(path.join('assets', 'injectedfile.js'));+ });++ it('should work with content', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const scriptHandle = await page.addScriptTag({ content: 'window.__injected = 35;' });+ expect(scriptHandle.asElement()).not.toBeNull();+ expect(await page.evaluate(() => __injected)).toBe(35);+ });++ // @see https://github.com/GoogleChrome/puppeteer/issues/4840+ xit('should throw when added with content to the CSP page', async({page, server}) => {+ await page.goto(server.PREFIX + '/csp.html');+ let error = null;+ await page.addScriptTag({ content: 'window.__injected = 35;' }).catch(e => error = e);+ expect(error).toBeTruthy();+ });++ it('should throw when added with URL to the CSP page', async({page, server}) => {+ await page.goto(server.PREFIX + '/csp.html');+ let error = null;+ await page.addScriptTag({ url: server.CROSS_PROCESS_PREFIX + '/injectedfile.js' }).catch(e => error = e);+ expect(error).toBeTruthy();+ });+ });++ describe('Page.addStyleTag', function() {+ it('should throw an error if no options are provided', async({page, server}) => {+ let error = null;+ try {+ await page.addStyleTag('/injectedstyle.css');+ } catch (e) {+ error = e;+ }+ expect(error.message).toBe('Provide an object with a `url`, `path` or `content` property');+ });++ it('should work with a url', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const styleHandle = await page.addStyleTag({ url: '/injectedstyle.css' });+ expect(styleHandle.asElement()).not.toBeNull();+ expect(await page.evaluate(`window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')`)).toBe('rgb(255, 0, 0)');+ });++ it('should throw an error if loading from url fail', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ let error = null;+ try {+ await page.addStyleTag({ url: '/nonexistfile.js' });+ } catch (e) {+ error = e;+ }+ expect(error.message).toBe('Loading style from /nonexistfile.js failed');+ });++ it('should work with a path', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const styleHandle = await page.addStyleTag({ path: path.join(__dirname, 'assets/injectedstyle.css') });+ expect(styleHandle.asElement()).not.toBeNull();+ expect(await page.evaluate(`window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')`)).toBe('rgb(255, 0, 0)');+ });++ it('should include sourcemap when path is provided', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.addStyleTag({ path: path.join(__dirname, 'assets/injectedstyle.css') });+ const styleHandle = await page.$('style');+ const styleContent = await page.evaluate(style => style.innerHTML, styleHandle);+ expect(styleContent).toContain(path.join('assets', 'injectedstyle.css'));+ });++ it('should work with content', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const styleHandle = await page.addStyleTag({ content: 'body { background-color: green; }' });+ expect(styleHandle.asElement()).not.toBeNull();+ expect(await page.evaluate(`window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')`)).toBe('rgb(0, 128, 0)');+ });++ it.skip(FFOX || WEBKIT)('should throw when added with content to the CSP page', async({page, server}) => {+ await page.goto(server.PREFIX + '/csp.html');+ let error = null;+ await page.addStyleTag({ content: 'body { background-color: green; }' }).catch(e => error = e);+ expect(error).toBeTruthy();+ });++ it.skip(WEBKIT)('should throw when added with URL to the CSP page', async({page, server}) => {+ await page.goto(server.PREFIX + '/csp.html');+ let error = null;+ await page.addStyleTag({ url: server.CROSS_PROCESS_PREFIX + '/injectedstyle.css' }).catch(e => error = e);+ expect(error).toBeTruthy();+ });+ });++ describe('Page.url', function() {+ it('should work', async({page, server}) => {+ expect(page.url()).toBe('about:blank');+ await page.goto(server.EMPTY_PAGE);+ expect(page.url()).toBe(server.EMPTY_PAGE);+ });+ });++ describe('Page.setJavaScriptEnabled', function() {+ it.skip(WEBKIT)('should work', async({page, server}) => {+ await page.setJavaScriptEnabled(false);+ await page.goto('data:text/html, <script>var something = "forbidden"</script>');+ let error = null;+ await page.evaluate('something').catch(e => error = e);+ expect(error.message).toContain('something is not defined');++ await page.setJavaScriptEnabled(true);+ await page.goto('data:text/html, <script>var something = "forbidden"</script>');+ expect(await page.evaluate('something')).toBe('forbidden');+ });+ });++ describe('Page.setCacheEnabled', function() {+ // FIXME: 'if-modified-since' is not set for some reason even if cache is on.+ it.skip(WEBKIT)('should enable or disable the cache based on the state passed', async({page, server}) => {+ await page.goto(server.PREFIX + '/cached/one-style.html');+ const [cachedRequest] = await Promise.all([+ server.waitForRequest('/cached/one-style.html'),+ page.reload(),+ ]);+ // Rely on "if-modified-since" caching in our test server.+ expect(cachedRequest.headers['if-modified-since']).not.toBe(undefined);++ await page.setCacheEnabled(false);+ const [nonCachedRequest] = await Promise.all([+ server.waitForRequest('/cached/one-style.html'),+ page.reload(),+ ]);+ expect(nonCachedRequest.headers['if-modified-since']).toBe(undefined);+ });+ it.skip(WEBKIT)('should stay disabled when toggling request interception on/off', async({page, server}) => {+ await page.setCacheEnabled(false);+ await page.setRequestInterception(true);+ await page.setRequestInterception(false);++ await page.goto(server.PREFIX + '/cached/one-style.html');+ const [nonCachedRequest] = await Promise.all([+ server.waitForRequest('/cached/one-style.html'),+ page.reload(),+ ]);+ expect(nonCachedRequest.headers['if-modified-since']).toBe(undefined);+ });+ });++ // Printing to pdf is currently only supported in headless+ describe.skip(FFOX || WEBKIT || !headless)('Page.pdf', function() {+ it('should be able to save file', async({page, server}) => {+ const outputFile = __dirname + '/assets/output.pdf';+ await page.pdf({path: outputFile});+ expect(fs.readFileSync(outputFile).byteLength).toBeGreaterThan(0);+ fs.unlinkSync(outputFile);+ });+ });++ describe('Page.title', function() {+ it('should return the page title', async({page, server}) => {+ await page.goto(server.PREFIX + '/title.html');+ expect(await page.title()).toBe('Woof-Woof');+ });+ });++ describe('Page.select', function() {+ it('should select single option', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('select', 'blue');+ expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);+ expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);+ });+ it('should select only first option', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('select', 'blue', 'green', 'red');+ expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);+ expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);+ });+ it.skip(FFOX)('should not throw when select causes navigation', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.$eval('select', select => select.addEventListener('input', () => window.location = '/empty.html'));+ await Promise.all([+ page.select('select', 'blue'),+ page.waitForNavigation(),+ ]);+ expect(page.url()).toContain('empty.html');+ });+ it('should select multiple options', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.evaluate(() => makeMultiple());+ await page.select('select', 'blue', 'green', 'red');+ expect(await page.evaluate(() => result.onInput)).toEqual(['blue', 'green', 'red']);+ expect(await page.evaluate(() => result.onChange)).toEqual(['blue', 'green', 'red']);+ });+ it('should respect event bubbling', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('select', 'blue');+ expect(await page.evaluate(() => result.onBubblingInput)).toEqual(['blue']);+ expect(await page.evaluate(() => result.onBubblingChange)).toEqual(['blue']);+ });+ it('should throw when element is not a <select>', async({page, server}) => {+ let error = null;+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('body', '').catch(e => error = e);+ expect(error.message).toContain('Element is not a <select> element.');+ });+ it('should return [] on no matched values', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ const result = await page.select('select','42','abc');+ expect(result).toEqual([]);+ });+ it('should return an array of matched values', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.evaluate(() => makeMultiple());+ const result = await page.select('select','blue','black','magenta');+ expect(result.reduce((accumulator,current) => ['blue', 'black', 'magenta'].includes(current) && accumulator, true)).toEqual(true);+ });+ it('should return an array of one element when multiple is not set', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ const result = await page.select('select','42','blue','black','magenta');+ expect(result.length).toEqual(1);+ });+ it('should return [] on no values',async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ const result = await page.select('select');+ expect(result).toEqual([]);+ });+ it('should deselect all options when passed no values for a multiple select',async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.evaluate(() => makeMultiple());+ await page.select('select','blue','black','magenta');+ await page.select('select');+ expect(await page.$eval('select', select => Array.from(select.options).every(option => !option.selected))).toEqual(true);+ });+ it('should deselect all options when passed no values for a select without multiple',async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.select('select','blue','black','magenta');+ await page.select('select');+ expect(await page.$eval('select', select => Array.from(select.options).every(option => !option.selected))).toEqual(true);+ });+ it('should throw if passed in non-strings', async({page, server}) => {+ await page.setContent('<select><option value="12"/></select>');+ let error = null;+ try {+ await page.select('select', 12);+ } catch (e) {+ error = e;+ }+ expect(error.message).toContain('Values must be strings');+ });+ // @see https://github.com/GoogleChrome/puppeteer/issues/3327+ it.skip(FFOX || WEBKIT)('should work when re-defining top-level Event class', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/select.html');+ await page.evaluate(() => window.Event = null);+ await page.select('select', 'blue');+ expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);+ expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);+ });+ });++ describe.skip(FFOX || WEBKIT)('Page.fill', function() {+ it('should fill textarea', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.fill('textarea', 'some value');+ expect(await page.evaluate(() => result)).toBe('some value');+ });+ it('should fill input', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.fill('input', 'some value');+ expect(await page.evaluate(() => result)).toBe('some value');+ });+ it('should throw on non-text inputs', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ for (const type of ['email', 'number', 'date']) {+ await page.$eval('input', (input, type) => input.setAttribute('type', type), type);+ let error = null;+ await page.fill('input', '').catch(e => error = e);+ expect(error.message).toContain('Cannot fill input of type');+ }+ });+ it('should fill different input types', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ for (const type of ['password', 'search', 'tel', 'text', 'url']) {+ await page.$eval('input', (input, type) => input.setAttribute('type', type), type);+ await page.fill('input', 'text ' + type);+ expect(await page.evaluate(() => result)).toBe('text ' + type);+ }+ });+ it('should fill contenteditable', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.fill('div[contenteditable]', 'some value');+ expect(await page.$eval('div[contenteditable]', div => div.textContent)).toBe('some value');+ });+ it('should fill elements with existing value and selection', async({page, server}) => {+ await page.goto(server.PREFIX + '/input/textarea.html');++ await page.$eval('input', input => input.value = 'value one');+ await page.fill('input', 'another value');+ expect(await page.evaluate(() => result)).toBe('another value');++ await page.$eval('input', input => {+ input.selectionStart = 1;+ input.selectionEnd = 2;+ });+ await page.fill('input', 'maybe this one');+ expect(await page.evaluate(() => result)).toBe('maybe this one');++ await page.$eval('div[contenteditable]', div => {+ div.innerHTML = 'some text <span>some more text<span> and even more text';+ const range = document.createRange();+ range.selectNodeContents(div.querySelector('span'));+ const selection = window.getSelection();+ selection.removeAllRanges();+ selection.addRange(range);+ });+ await page.fill('div[contenteditable]', 'replace with this');+ expect(await page.$eval('div[contenteditable]', div => div.textContent)).toBe('replace with this');+ });+ it('should throw when element is not an <input>, <textarea> or [contenteditable]', async({page, server}) => {+ let error = null;+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.fill('body', '').catch(e => error = e);+ expect(error.message).toContain('Element is not an <input>');+ });+ it('should throw if passed a non-string value', async({page, server}) => {+ let error = null;+ await page.goto(server.PREFIX + '/input/textarea.html');+ await page.fill('textarea', 123).catch(e => error = e);+ expect(error.message).toContain('Value must be string.');+ });+ });++ // FIXME: WebKit shouldn't send targetDestroyed on PSON so that we could+ // convert target destroy events into close.+ describe('Page.Events.Close', function() {+ it.skip(WEBKIT)('should work with window.close', async function({ page, context, server }) {+ const newPagePromise = new Promise(fulfill => context.once('targetcreated', target => fulfill(target.page())));+ await page.evaluate(() => window['newPage'] = window.open('about:blank'));+ const newPage = await newPagePromise;+ const closedPromise = new Promise(x => newPage.on('close', x));+ await page.evaluate(() => window['newPage'].close());+ await closedPromise;+ });+ it.skip(WEBKIT)('should work with page.close', async function({ page, context, server }) {+ const newPage = await context.newPage();+ const closedPromise = new Promise(x => newPage.on('close', x));+ await newPage.close();+ await closedPromise;+ });+ });++ describe('Page.browser', function() {+ it('should return the correct browser instance', async function({ page, browser }) {+ expect(page.browser()).toBe(browser);+ });+ });++ describe('Page.browserContext', function() {+ it('should return the correct browser instance', async function({page, context, browser}) {+ expect(page.browserContext()).toBe(context);+ });+ });+};diff --git a/test/playwright.spec.js b/test/playwright.spec.jsnew file mode 100644index 0000000000..4d89f84fbf--- /dev/null+++ b/test/playwright.spec.js@@ -0,0 +1,180 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+const fs = require('fs');+const path = require('path');+const rm = require('rimraf').sync;+const GoldenUtils = require('./golden-utils');+const {Matchers} = require('../utils/testrunner/');++const YELLOW_COLOR = '\x1b[33m';+const RESET_COLOR = '\x1b[0m';++module.exports.addTests = ({testRunner, product, playwrightPath}) => {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ const CHROME = product === 'Chromium';+ const FFOX = product === 'Firefox';+ const WEBKIT = product === 'WebKit';++ const playwright = require(playwrightPath);++ const headless = (process.env.HEADLESS || 'true').trim().toLowerCase() === 'true';+ const slowMo = parseInt((process.env.SLOW_MO || '0').trim(), 10);++ const executablePath = {+ 'Chromium': process.env.CHROME,+ 'Firefox': process.env.FFOX,+ 'WebKit': process.env.WEBKIT_PATH,+ }[product];+ const defaultBrowserOptions = {+ handleSIGINT: false,+ executablePath,+ slowMo,+ headless,+ dumpio: !!process.env.DUMPIO,+ };++ if (defaultBrowserOptions.executablePath) {+ console.warn(`${YELLOW_COLOR}WARN: running ${product} tests with ${defaultBrowserOptions.executablePath}${RESET_COLOR}`);+ } else {+ // Make sure the `npm install` was run after the chromium roll.+ if (!fs.existsSync(playwright.executablePath()))+ throw new Error(`Browser is not downloaded. Run 'npm install' and try to re-run tests`);+ }++ const GOLDEN_DIR = path.join(__dirname, 'golden-' + product.toLowerCase());+ const OUTPUT_DIR = path.join(__dirname, 'output-' + product.toLowerCase());+ if (fs.existsSync(OUTPUT_DIR))+ rm(OUTPUT_DIR);+ const {expect} = new Matchers({+ toBeGolden: GoldenUtils.compare.bind(null, GOLDEN_DIR, OUTPUT_DIR)+ });++ const testOptions = {+ testRunner,+ product,+ FFOX,+ WEBKIT,+ CHROME,+ playwright,+ expect,+ defaultBrowserOptions,+ playwrightPath,+ headless: !!defaultBrowserOptions.headless,+ };++ beforeAll(async() => {+ if (FFOX && defaultBrowserOptions.executablePath)+ await require('../misc/install-preferences')(defaultBrowserOptions.executablePath);+ });++ describe('Browser', function() {+ beforeAll(async state => {+ state.browser = await playwright.launch(defaultBrowserOptions);+ });++ afterAll(async state => {+ await state.browser.close();+ state.browser = null;+ });++ if (!WEBKIT) {+ beforeEach(async(state, test) => {+ const rl = require('readline').createInterface({input: state.browser.process().stderr});+ test.output = '';+ rl.on('line', onLine);+ state.tearDown = () => {+ rl.removeListener('line', onLine);+ rl.close();+ };+ function onLine(line) {+ test.output += line + '\n';+ }+ });+ }++ if (!WEBKIT) {+ afterEach(async state => {+ state.tearDown();+ });+ }++ describe('Page', function() {+ beforeEach(async state => {+ state.context = await state.browser.createIncognitoBrowserContext();+ state.page = await state.context.newPage();+ });++ afterEach(async state => {+ // This closes all pages.+ await state.context.close();+ state.context = null;+ state.page = null;+ });++ // Page-level tests that are given a browser, a context and a page.+ // Each test is launched in a new browser context.+ require('./accessibility.spec.js').addTests(testOptions);+ require('./browser.spec.js').addTests(testOptions);+ require('./click.spec.js').addTests(testOptions);+ require('./cookies.spec.js').addTests(testOptions);+ require('./dialog.spec.js').addTests(testOptions);+ require('./elementhandle.spec.js').addTests(testOptions);+ require('./emulation.spec.js').addTests(testOptions);+ require('./evaluation.spec.js').addTests(testOptions);+ require('./frame.spec.js').addTests(testOptions);+ require('./input.spec.js').addTests(testOptions);+ require('./jshandle.spec.js').addTests(testOptions);+ require('./keyboard.spec.js').addTests(testOptions);+ require('./mouse.spec.js').addTests(testOptions);+ require('./navigation.spec.js').addTests(testOptions);+ require('./network.spec.js').addTests(testOptions);+ require('./requestinterception.spec.js').addTests(testOptions);+ require('./page.spec.js').addTests(testOptions);+ // FIXME: screenshot tests will fail when running in parallel (maybe)+ require('./screenshot.spec.js').addTests(testOptions);+ require('./queryselector.spec.js').addTests(testOptions);+ require('./target.spec.js').addTests(testOptions);+ require('./touchscreen.spec.js').addTests(testOptions);+ require('./waittask.spec.js').addTests(testOptions);+ require('./worker.spec.js').addTests(testOptions);+ if (CHROME) {+ require('./CDPSession.spec.js').addTests(testOptions);+ require('./coverage.spec.js').addTests(testOptions);+ // Add page-level Chromium-specific tests.+ require('./chromiumonly.spec.js').addPageTests(testOptions);+ }+ });++ // Browser-level tests that are given a browser.+ require('./browsercontext.spec.js').addTests(testOptions);+ });++ // Top-level tests that launch Browser themselves.+ require('./ignorehttpserrors.spec.js').addTests(testOptions);+ require('./defaultbrowsercontext.spec.js').addTests(testOptions);+ require('./launcher.spec.js').addTests(testOptions);+ require('./fixtures.spec.js').addTests(testOptions);+ if (CHROME) {+ require('./oopif.spec.js').addTests(testOptions);+ require('./headful.spec.js').addTests(testOptions);+ require('./tracing.spec.js').addTests(testOptions);+ // Add top-level Chromium-specific tests.+ require('./chromiumonly.spec.js').addLauncherTests(testOptions);+ }+};diff --git a/test/queryselector.spec.js b/test/queryselector.spec.jsnew file mode 100644index 0000000000..725bfde9f5--- /dev/null+++ b/test/queryselector.spec.js@@ -0,0 +1,205 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, product, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Page.$eval', function() {+ it('should work', async({page, server}) => {+ await page.setContent('<section id="testAttribute">43543</section>');+ const idAttribute = await page.$eval('section', e => e.id);+ expect(idAttribute).toBe('testAttribute');+ });+ it('should accept arguments', async({page, server}) => {+ await page.setContent('<section>hello</section>');+ const text = await page.$eval('section', (e, suffix) => e.textContent + suffix, ' world!');+ expect(text).toBe('hello world!');+ });+ it('should accept ElementHandles as arguments', async({page, server}) => {+ await page.setContent('<section>hello</section><div> world</div>');+ const divHandle = await page.$('div');+ const text = await page.$eval('section', (e, div) => e.textContent + div.textContent, divHandle);+ expect(text).toBe('hello world');+ });+ it('should throw error if no element is found', async({page, server}) => {+ let error = null;+ await page.$eval('section', e => e.id).catch(e => error = e);+ expect(error.message).toContain('failed to find element matching selector "section"');+ });+ });++ describe('Page.$$eval', function() {+ it('should work', async({page, server}) => {+ await page.setContent('<div>hello</div><div>beautiful</div><div>world!</div>');+ const divsCount = await page.$$eval('div', divs => divs.length);+ expect(divsCount).toBe(3);+ });+ });++ describe('Page.$', function() {+ it('should query existing element', async({page, server}) => {+ await page.setContent('<section>test</section>');+ const element = await page.$('section');+ expect(element).toBeTruthy();+ });+ it('should return null for non-existing element', async({page, server}) => {+ const element = await page.$('non-existing-element');+ expect(element).toBe(null);+ });+ });++ describe('Page.$$', function() {+ it('should query existing elements', async({page, server}) => {+ await page.setContent('<div>A</div><br/><div>B</div>');+ const elements = await page.$$('div');+ expect(elements.length).toBe(2);+ const promises = elements.map(element => page.evaluate(e => e.textContent, element));+ expect(await Promise.all(promises)).toEqual(['A', 'B']);+ });+ it('should return empty array if nothing is found', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const elements = await page.$$('div');+ expect(elements.length).toBe(0);+ });+ });++ describe('Path.$x', function() {+ it('should query existing element', async({page, server}) => {+ await page.setContent('<section>test</section>');+ const elements = await page.$x('/html/body/section');+ expect(elements[0]).toBeTruthy();+ expect(elements.length).toBe(1);+ });+ it('should return empty array for non-existing element', async({page, server}) => {+ const element = await page.$x('/html/body/non-existing-element');+ expect(element).toEqual([]);+ });+ it('should return multiple elements', async({page, sever}) => {+ await page.setContent('<div></div><div></div>');+ const elements = await page.$x('/html/body/div');+ expect(elements.length).toBe(2);+ });+ });+++ describe('ElementHandle.$', function() {+ it('should query existing element', async({page, server}) => {+ await page.goto(server.PREFIX + '/playground.html');+ await page.setContent('<html><body><div class="second"><div class="inner">A</div></div></body></html>');+ const html = await page.$('html');+ const second = await html.$('.second');+ const inner = await second.$('.inner');+ const content = await page.evaluate(e => e.textContent, inner);+ expect(content).toBe('A');+ });++ it('should return null for non-existing element', async({page, server}) => {+ await page.setContent('<html><body><div class="second"><div class="inner">B</div></div></body></html>');+ const html = await page.$('html');+ const second = await html.$('.third');+ expect(second).toBe(null);+ });+ });+ describe('ElementHandle.$eval', function() {+ it('should work', async({page, server}) => {+ await page.setContent('<html><body><div class="tweet"><div class="like">100</div><div class="retweets">10</div></div></body></html>');+ const tweet = await page.$('.tweet');+ const content = await tweet.$eval('.like', node => node.innerText);+ expect(content).toBe('100');+ });++ it('should retrieve content from subtree', async({page, server}) => {+ const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"><div class="a">a-child-div</div></div>';+ await page.setContent(htmlContent);+ const elementHandle = await page.$('#myId');+ const content = await elementHandle.$eval('.a', node => node.innerText);+ expect(content).toBe('a-child-div');+ });++ it('should throw in case of missing selector', async({page, server}) => {+ const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"></div>';+ await page.setContent(htmlContent);+ const elementHandle = await page.$('#myId');+ const errorMessage = await elementHandle.$eval('.a', node => node.innerText).catch(error => error.message);+ expect(errorMessage).toBe(`Error: failed to find element matching selector ".a"`);+ });+ });+ describe('ElementHandle.$$eval', function() {+ it('should work', async({page, server}) => {+ await page.setContent('<html><body><div class="tweet"><div class="like">100</div><div class="like">10</div></div></body></html>');+ const tweet = await page.$('.tweet');+ const content = await tweet.$$eval('.like', nodes => nodes.map(n => n.innerText));+ expect(content).toEqual(['100', '10']);+ });++ it('should retrieve content from subtree', async({page, server}) => {+ const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"><div class="a">a1-child-div</div><div class="a">a2-child-div</div></div>';+ await page.setContent(htmlContent);+ const elementHandle = await page.$('#myId');+ const content = await elementHandle.$$eval('.a', nodes => nodes.map(n => n.innerText));+ expect(content).toEqual(['a1-child-div', 'a2-child-div']);+ });++ it('should not throw in case of missing selector', async({page, server}) => {+ const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"></div>';+ await page.setContent(htmlContent);+ const elementHandle = await page.$('#myId');+ const nodesLength = await elementHandle.$$eval('.a', nodes => nodes.length);+ expect(nodesLength).toBe(0);+ });++ });++ describe('ElementHandle.$$', function() {+ it('should query existing elements', async({page, server}) => {+ await page.setContent('<html><body><div>A</div><br/><div>B</div></body></html>');+ const html = await page.$('html');+ const elements = await html.$$('div');+ expect(elements.length).toBe(2);+ const promises = elements.map(element => page.evaluate(e => e.textContent, element));+ expect(await Promise.all(promises)).toEqual(['A', 'B']);+ });++ it('should return empty array for non-existing elements', async({page, server}) => {+ await page.setContent('<html><body><span>A</span><br/><span>B</span></body></html>');+ const html = await page.$('html');+ const elements = await html.$$('div');+ expect(elements.length).toBe(0);+ });+ });+++ describe('ElementHandle.$x', function() {+ it('should query existing element', async({page, server}) => {+ await page.goto(server.PREFIX + '/playground.html');+ await page.setContent('<html><body><div class="second"><div class="inner">A</div></div></body></html>');+ const html = await page.$('html');+ const second = await html.$x(`./body/div[contains(@class, 'second')]`);+ const inner = await second[0].$x(`./div[contains(@class, 'inner')]`);+ const content = await page.evaluate(e => e.textContent, inner[0]);+ expect(content).toBe('A');+ });++ it('should return null for non-existing element', async({page, server}) => {+ await page.setContent('<html><body><div class="second"><div class="inner">B</div></div></body></html>');+ const html = await page.$('html');+ const second = await html.$x(`/div[contains(@class, 'third')]`);+ expect(second).toEqual([]);+ });+ });+};diff --git a/test/requestinterception.spec.js b/test/requestinterception.spec.jsnew file mode 100644index 0000000000..77bf3923de--- /dev/null+++ b/test/requestinterception.spec.js@@ -0,0 +1,585 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const fs = require('fs');+const path = require('path');+const utils = require('./utils');++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe.skip(WEBKIT)('Page.setRequestInterception', function() {+ it('should intercept', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ if (utils.isFavicon(request)) {+ request.continue();+ return;+ }+ expect(request.url()).toContain('empty.html');+ expect(request.headers()['user-agent']).toBeTruthy();+ expect(request.method()).toBe('GET');+ expect(request.postData()).toBe(undefined);+ expect(request.isNavigationRequest()).toBe(true);+ expect(request.resourceType()).toBe('document');+ expect(request.frame() === page.mainFrame()).toBe(true);+ expect(request.frame().url()).toBe('about:blank');+ request.continue();+ });+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.ok()).toBe(true);+ expect(response.remoteAddress().port).toBe(server.PORT);+ });+ it('should work when POST is redirected with 302', async({page, server}) => {+ server.setRedirect('/rredirect', '/empty.html');+ await page.goto(server.EMPTY_PAGE);+ await page.setRequestInterception(true);+ page.on('request', request => request.continue());+ await page.setContent(`+ <form action='/rredirect' method='post'>+ <input type="hidden" id="foo" name="foo" value="FOOBAR">+ </form>+ `);+ await Promise.all([+ page.$eval('form', form => form.submit()),+ page.waitForNavigation()+ ]);+ });+ // @see https://github.com/GoogleChrome/puppeteer/issues/3973+ it('should work when header manipulation headers with redirect', async({page, server}) => {+ server.setRedirect('/rrredirect', '/empty.html');+ await page.setRequestInterception(true);+ page.on('request', request => {+ const headers = Object.assign({}, request.headers(), {+ foo: 'bar'+ });+ request.continue({ headers });+ });+ await page.goto(server.PREFIX + '/rrredirect');+ });+ // @see https://github.com/GoogleChrome/puppeteer/issues/4743+ it('should be able to remove headers', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ const headers = Object.assign({}, request.headers(), {+ foo: 'bar',+ origin: undefined, // remove "origin" header+ });+ request.continue({ headers });+ });++ const [serverRequest] = await Promise.all([+ server.waitForRequest('/empty.html'),+ page.goto(server.PREFIX + '/empty.html')+ ]);++ expect(serverRequest.headers.origin).toBe(undefined);+ });+ it('should contain referer header', async({page, server}) => {+ await page.setRequestInterception(true);+ const requests = [];+ page.on('request', request => {+ if (!utils.isFavicon(request))+ requests.push(request);+ request.continue();+ });+ await page.goto(server.PREFIX + '/one-style.html');+ expect(requests[1].url()).toContain('/one-style.css');+ expect(requests[1].headers().referer).toContain('/one-style.html');+ });+ it('should properly return navigation response when URL has cookies', async({page, server}) => {+ // Setup cookie.+ await page.goto(server.EMPTY_PAGE);+ await page.setCookie({ name: 'foo', value: 'bar'});++ // Setup request interception.+ await page.setRequestInterception(true);+ page.on('request', request => request.continue());+ const response = await page.reload();+ expect(response.status()).toBe(200);+ });+ it('should stop intercepting', async({page, server}) => {+ await page.setRequestInterception(true);+ page.once('request', request => request.continue());+ await page.goto(server.EMPTY_PAGE);+ await page.setRequestInterception(false);+ await page.goto(server.EMPTY_PAGE);+ });+ it('should show custom HTTP headers', async({page, server}) => {+ await page.setExtraHTTPHeaders({+ foo: 'bar'+ });+ await page.setRequestInterception(true);+ page.on('request', request => {+ expect(request.headers()['foo']).toBe('bar');+ request.continue();+ });+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.ok()).toBe(true);+ });+ // @see https://github.com/GoogleChrome/puppeteer/issues/4337+ it('should work with redirect inside sync XHR', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ server.setRedirect('/logo.png', '/pptr.png');+ await page.setRequestInterception(true);+ page.on('request', request => request.continue());+ const status = await page.evaluate(async() => {+ const request = new XMLHttpRequest();+ request.open('GET', '/logo.png', false); // `false` makes the request synchronous+ request.send(null);+ return request.status;+ });+ expect(status).toBe(200);+ });+ it('should work with custom referer headers', async({page, server}) => {+ await page.setExtraHTTPHeaders({ 'referer': server.EMPTY_PAGE });+ await page.setRequestInterception(true);+ page.on('request', request => {+ expect(request.headers()['referer']).toBe(server.EMPTY_PAGE);+ request.continue();+ });+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.ok()).toBe(true);+ });+ it('should be abortable', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ if (request.url().endsWith('.css'))+ request.abort();+ else+ request.continue();+ });+ let failedRequests = 0;+ page.on('requestfailed', event => ++failedRequests);+ const response = await page.goto(server.PREFIX + '/one-style.html');+ expect(response.ok()).toBe(true);+ expect(response.request().failure()).toBe(null);+ expect(failedRequests).toBe(1);+ });+ it.skip(FFOX)('should be abortable with custom error codes', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ request.abort('internetdisconnected');+ });+ let failedRequest = null;+ page.on('requestfailed', request => failedRequest = request);+ await page.goto(server.EMPTY_PAGE).catch(e => {});+ expect(failedRequest).toBeTruthy();+ expect(failedRequest.failure().errorText).toBe('net::ERR_INTERNET_DISCONNECTED');+ });+ it('should send referer', async({page, server}) => {+ await page.setExtraHTTPHeaders({+ referer: 'http://google.com/'+ });+ await page.setRequestInterception(true);+ page.on('request', request => request.continue());+ const [request] = await Promise.all([+ server.waitForRequest('/grid.html'),+ page.goto(server.PREFIX + '/grid.html'),+ ]);+ expect(request.headers['referer']).toBe('http://google.com/');+ });+ it('should fail navigation when aborting main resource', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => request.abort());+ let error = null;+ await page.goto(server.EMPTY_PAGE).catch(e => error = e);+ expect(error).toBeTruthy();+ if (CHROME || WEBKIT)+ expect(error.message).toContain('net::ERR_FAILED');+ else+ expect(error.message).toContain('NS_ERROR_FAILURE');+ });+ it('should work with redirects', async({page, server}) => {+ await page.setRequestInterception(true);+ const requests = [];+ page.on('request', request => {+ request.continue();+ requests.push(request);+ });+ server.setRedirect('/non-existing-page.html', '/non-existing-page-2.html');+ server.setRedirect('/non-existing-page-2.html', '/non-existing-page-3.html');+ server.setRedirect('/non-existing-page-3.html', '/non-existing-page-4.html');+ server.setRedirect('/non-existing-page-4.html', '/empty.html');+ const response = await page.goto(server.PREFIX + '/non-existing-page.html');+ expect(response.status()).toBe(200);+ expect(response.url()).toContain('empty.html');+ expect(requests.length).toBe(5);+ expect(requests[2].resourceType()).toBe('document');+ // Check redirect chain+ const redirectChain = response.request().redirectChain();+ expect(redirectChain.length).toBe(4);+ expect(redirectChain[0].url()).toContain('/non-existing-page.html');+ expect(redirectChain[2].url()).toContain('/non-existing-page-3.html');+ for (let i = 0; i < redirectChain.length; ++i) {+ const request = redirectChain[i];+ expect(request.isNavigationRequest()).toBe(true);+ expect(request.redirectChain().indexOf(request)).toBe(i);+ }+ });+ it('should work with redirects for subresources', async({page, server}) => {+ await page.setRequestInterception(true);+ const requests = [];+ page.on('request', request => {+ request.continue();+ if (!utils.isFavicon(request))+ requests.push(request);+ });+ server.setRedirect('/one-style.css', '/two-style.css');+ server.setRedirect('/two-style.css', '/three-style.css');+ server.setRedirect('/three-style.css', '/four-style.css');+ server.setRoute('/four-style.css', (req, res) => res.end('body {box-sizing: border-box; }'));++ const response = await page.goto(server.PREFIX + '/one-style.html');+ expect(response.status()).toBe(200);+ expect(response.url()).toContain('one-style.html');+ expect(requests.length).toBe(5);+ expect(requests[0].resourceType()).toBe('document');+ expect(requests[1].resourceType()).toBe('stylesheet');+ // Check redirect chain+ const redirectChain = requests[1].redirectChain();+ expect(redirectChain.length).toBe(3);+ expect(redirectChain[0].url()).toContain('/one-style.css');+ expect(redirectChain[2].url()).toContain('/three-style.css');+ });+ it('should be able to abort redirects', async({page, server}) => {+ await page.setRequestInterception(true);+ server.setRedirect('/non-existing.json', '/non-existing-2.json');+ server.setRedirect('/non-existing-2.json', '/simple.html');+ page.on('request', request => {+ if (request.url().includes('non-existing-2'))+ request.abort();+ else+ request.continue();+ });+ await page.goto(server.EMPTY_PAGE);+ const result = await page.evaluate(async() => {+ try {+ await fetch('/non-existing.json');+ } catch (e) {+ return e.message;+ }+ });+ if (CHROME || WEBKIT)+ expect(result).toContain('Failed to fetch');+ else+ expect(result).toContain('NetworkError');+ });+ it('should work with equal requests', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ let responseCount = 1;+ server.setRoute('/zzz', (req, res) => res.end((responseCount++) * 11 + ''));+ await page.setRequestInterception(true);++ let spinner = false;+ // Cancel 2nd request.+ page.on('request', request => {+ if (utils.isFavicon(request)) {+ request.continue();+ return;+ }+ spinner ? request.abort() : request.continue();+ spinner = !spinner;+ });+ const results = await page.evaluate(() => Promise.all([+ fetch('/zzz').then(response => response.text()).catch(e => 'FAILED'),+ fetch('/zzz').then(response => response.text()).catch(e => 'FAILED'),+ fetch('/zzz').then(response => response.text()).catch(e => 'FAILED'),+ ]));+ expect(results).toEqual(['11', 'FAILED', '22']);+ });+ it.skip(FFOX)('should navigate to dataURL and fire dataURL requests', async({page, server}) => {+ await page.setRequestInterception(true);+ const requests = [];+ page.on('request', request => {+ requests.push(request);+ request.continue();+ });+ const dataURL = 'data:text/html,<div>yo</div>';+ const response = await page.goto(dataURL);+ expect(response.status()).toBe(200);+ expect(requests.length).toBe(1);+ expect(requests[0].url()).toBe(dataURL);+ });+ it.skip(FFOX)('should be able to fetch dataURL and fire dataURL requests', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.setRequestInterception(true);+ const requests = [];+ page.on('request', request => {+ requests.push(request);+ request.continue();+ });+ const dataURL = 'data:text/html,<div>yo</div>';+ const text = await page.evaluate(url => fetch(url).then(r => r.text()), dataURL);+ expect(text).toBe('<div>yo</div>');+ expect(requests.length).toBe(1);+ expect(requests[0].url()).toBe(dataURL);+ });+ it.skip(FFOX)('should navigate to URL with hash and and fire requests without hash', async({page, server}) => {+ await page.setRequestInterception(true);+ const requests = [];+ page.on('request', request => {+ requests.push(request);+ request.continue();+ });+ const response = await page.goto(server.EMPTY_PAGE + '#hash');+ expect(response.status()).toBe(200);+ expect(response.url()).toBe(server.EMPTY_PAGE);+ expect(requests.length).toBe(1);+ expect(requests[0].url()).toBe(server.EMPTY_PAGE);+ });+ it('should work with encoded server', async({page, server}) => {+ // The requestWillBeSent will report encoded URL, whereas interception will+ // report URL as-is. @see crbug.com/759388+ await page.setRequestInterception(true);+ page.on('request', request => request.continue());+ const response = await page.goto(server.PREFIX + '/some nonexisting page');+ expect(response.status()).toBe(404);+ });+ it('should work with badly encoded server', async({page, server}) => {+ await page.setRequestInterception(true);+ server.setRoute('/malformed?rnd=%911', (req, res) => res.end());+ page.on('request', request => request.continue());+ const response = await page.goto(server.PREFIX + '/malformed?rnd=%911');+ expect(response.status()).toBe(200);+ });+ it.skip(FFOX)('should work with encoded server - 2', async({page, server}) => {+ // The requestWillBeSent will report URL as-is, whereas interception will+ // report encoded URL for stylesheet. @see crbug.com/759388+ await page.setRequestInterception(true);+ const requests = [];+ page.on('request', request => {+ request.continue();+ requests.push(request);+ });+ const response = await page.goto(`data:text/html,<link rel="stylesheet" href="${server.PREFIX}/fonts?helvetica|arial"/>`);+ expect(response.status()).toBe(200);+ expect(requests.length).toBe(2);+ expect(requests[1].response().status()).toBe(404);+ });+ it.skip(FFOX)('should not throw "Invalid Interception Id" if the request was cancelled', async({page, server}) => {+ await page.setContent('<iframe></iframe>');+ await page.setRequestInterception(true);+ let request = null;+ page.on('request', async r => request = r);+ page.$eval('iframe', (frame, url) => frame.src = url, server.EMPTY_PAGE),+ // Wait for request interception.+ await utils.waitEvent(page, 'request');+ // Delete frame to cause request to be canceled.+ await page.$eval('iframe', frame => frame.remove());+ let error = null;+ await request.continue().catch(e => error = e);+ expect(error).toBe(null);+ });+ it('should throw if interception is not enabled', async({page, server}) => {+ let error = null;+ page.on('request', async request => {+ try {+ await request.continue();+ } catch (e) {+ error = e;+ }+ });+ await page.goto(server.EMPTY_PAGE);+ expect(error.message).toContain('Request Interception is not enabled');+ });+ it.skip(FFOX)('should work with file URLs', async({page, server}) => {+ await page.setRequestInterception(true);+ const urls = new Set();+ page.on('request', request => {+ urls.add(request.url().split('/').pop());+ request.continue();+ });+ await page.goto(pathToFileURL(path.join(__dirname, 'assets', 'one-style.html')));+ expect(urls.size).toBe(2);+ expect(urls.has('one-style.html')).toBe(true);+ expect(urls.has('one-style.css')).toBe(true);+ });+ });++ describe.skip(WEBKIT)('Request.continue', function() {+ it('should work', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => request.continue());+ await page.goto(server.EMPTY_PAGE);+ });+ it('should amend HTTP headers', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ const headers = Object.assign({}, request.headers());+ headers['FOO'] = 'bar';+ request.continue({ headers });+ });+ await page.goto(server.EMPTY_PAGE);+ const [request] = await Promise.all([+ server.waitForRequest('/sleep.zzz'),+ page.evaluate(() => fetch('/sleep.zzz'))+ ]);+ expect(request.headers['foo']).toBe('bar');+ });+ it.skip(FFOX)('should redirect in a way non-observable to page', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ const redirectURL = request.url().includes('/empty.html') ? server.PREFIX + '/consolelog.html' : undefined;+ request.continue({ url: redirectURL });+ });+ let consoleMessage = null;+ page.on('console', msg => consoleMessage = msg);+ await page.goto(server.EMPTY_PAGE);+ expect(page.url()).toBe(server.EMPTY_PAGE);+ expect(consoleMessage.text()).toBe('yellow');+ });+ it.skip(FFOX)('should amend method', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);++ await page.setRequestInterception(true);+ page.on('request', request => {+ request.continue({ method: 'POST' });+ });+ const [request] = await Promise.all([+ server.waitForRequest('/sleep.zzz'),+ page.evaluate(() => fetch('/sleep.zzz'))+ ]);+ expect(request.method).toBe('POST');+ });+ it.skip(FFOX)('should amend post data', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);++ await page.setRequestInterception(true);+ page.on('request', request => {+ request.continue({ postData: 'doggo' });+ });+ const [serverRequest] = await Promise.all([+ server.waitForRequest('/sleep.zzz'),+ page.evaluate(() => fetch('/sleep.zzz', { method: 'POST', body: 'birdy' }))+ ]);+ expect(await serverRequest.postBody).toBe('doggo');+ });+ it.skip(FFOX)('should amend both post data and method on navigation', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ request.continue({ method: 'POST', postData: 'doggo' });+ });+ const [serverRequest] = await Promise.all([+ server.waitForRequest('/empty.html'),+ page.goto(server.EMPTY_PAGE),+ ]);+ expect(serverRequest.method).toBe('POST');+ expect(await serverRequest.postBody).toBe('doggo');+ });+ });++ describe.skip(FFOX || WEBKIT)('Request.respond', function() {+ it('should work', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ request.respond({+ status: 201,+ headers: {+ foo: 'bar'+ },+ body: 'Yo, page!'+ });+ });+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.status()).toBe(201);+ expect(response.headers().foo).toBe('bar');+ expect(await page.evaluate(() => document.body.textContent)).toBe('Yo, page!');+ });+ it('should work with status code 422', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ request.respond({+ status: 422,+ body: 'Yo, page!'+ });+ });+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.status()).toBe(422);+ expect(response.statusText()).toBe('Unprocessable Entity');+ expect(await page.evaluate(() => document.body.textContent)).toBe('Yo, page!');+ });+ it('should redirect', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ if (!request.url().includes('rrredirect')) {+ request.continue();+ return;+ }+ request.respond({+ status: 302,+ headers: {+ location: server.EMPTY_PAGE,+ },+ });+ });+ const response = await page.goto(server.PREFIX + '/rrredirect');+ expect(response.request().redirectChain().length).toBe(1);+ expect(response.request().redirectChain()[0].url()).toBe(server.PREFIX + '/rrredirect');+ expect(response.url()).toBe(server.EMPTY_PAGE);+ });+ it('should allow mocking binary responses', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ const imageBuffer = fs.readFileSync(path.join(__dirname, 'assets', 'pptr.png'));+ request.respond({+ contentType: 'image/png',+ body: imageBuffer+ });+ });+ await page.evaluate(PREFIX => {+ const img = document.createElement('img');+ img.src = PREFIX + '/does-not-exist.png';+ document.body.appendChild(img);+ return new Promise(fulfill => img.onload = fulfill);+ }, server.PREFIX);+ const img = await page.$('img');+ expect(await img.screenshot()).toBeGolden('mock-binary-response.png');+ });+ it('should stringify intercepted request response headers', async({page, server}) => {+ await page.setRequestInterception(true);+ page.on('request', request => {+ request.respond({+ status: 200,+ headers: {+ 'foo': true+ },+ body: 'Yo, page!'+ });+ });+ const response = await page.goto(server.EMPTY_PAGE);+ expect(response.status()).toBe(200);+ const headers = response.headers();+ expect(headers.foo).toBe('true');+ expect(await page.evaluate(() => document.body.textContent)).toBe('Yo, page!');+ });+ });++};++/**+ * @param {string} path+ * @return {string}+ */+function pathToFileURL(path) {+ let pathName = path.replace(/\\/g, '/');+ // Windows drive letter must be prefixed with a slash.+ if (!pathName.startsWith('/'))+ pathName = '/' + pathName;+ return 'file://' + pathName;+}diff --git a/test/run_static_server.js b/test/run_static_server.jsnew file mode 100755index 0000000000..b256b228c6--- /dev/null+++ b/test/run_static_server.js@@ -0,0 +1,33 @@+#!/usr/bin/env node+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+const path = require('path');+const {TestServer} = require('../utils/testserver/');++const port = 8907;+const httpsPort = 8908;+const assetsPath = path.join(__dirname, 'assets');+const cachedPath = path.join(__dirname, 'assets', 'cached');++Promise.all([+ TestServer.create(assetsPath, port),+ TestServer.createHTTPS(assetsPath, httpsPort)+]).then(([server, httpsServer]) => {+ server.enableHTTPCache(cachedPath);+ httpsServer.enableHTTPCache(cachedPath);+ console.log(`HTTP: server is running on http://localhost:${port}`);+ console.log(`HTTPS: server is running on https://localhost:${httpsPort}`);+});diff --git a/test/screenshot.spec.js b/test/screenshot.spec.jsnew file mode 100644index 0000000000..f50aae32ab--- /dev/null+++ b/test/screenshot.spec.js@@ -0,0 +1,241 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, product, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Page.screenshot', function() {+ it('should work', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.goto(server.PREFIX + '/grid.html');+ const screenshot = await page.screenshot();+ expect(screenshot).toBeGolden('screenshot-sanity.png');+ });+ it('should clip rect', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.goto(server.PREFIX + '/grid.html');+ const screenshot = await page.screenshot({+ clip: {+ x: 50,+ y: 100,+ width: 150,+ height: 100+ }+ });+ expect(screenshot).toBeGolden('screenshot-clip-rect.png');+ });+ it.skip(FFOX)('should clip elements to the viewport', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.goto(server.PREFIX + '/grid.html');+ const screenshot = await page.screenshot({+ clip: {+ x: 50,+ y: 600,+ width: 100,+ height: 100+ }+ });+ expect(screenshot).toBeGolden('screenshot-offscreen-clip.png');+ });+ it.skip(WEBKIT)('should run in parallel', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.goto(server.PREFIX + '/grid.html');+ const promises = [];+ for (let i = 0; i < 3; ++i) {+ promises.push(page.screenshot({+ clip: {+ x: 50 * i,+ y: 0,+ width: 50,+ height: 50+ }+ }));+ }+ const screenshots = await Promise.all(promises);+ expect(screenshots[1]).toBeGolden('grid-cell-1.png');+ });+ it('should take fullPage screenshots', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.goto(server.PREFIX + '/grid.html');+ const screenshot = await page.screenshot({+ fullPage: true+ });+ expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');+ });+ it('should run in parallel in multiple pages', async({page, server, context}) => {+ const N = 2;+ const pages = await Promise.all(Array(N).fill(0).map(async() => {+ const page = await context.newPage();+ await page.goto(server.PREFIX + '/grid.html');+ return page;+ }));+ const promises = [];+ for (let i = 0; i < N; ++i)+ promises.push(pages[i].screenshot({ clip: { x: 50 * i, y: 0, width: 50, height: 50 } }));+ const screenshots = await Promise.all(promises);+ for (let i = 0; i < N; ++i)+ expect(screenshots[i]).toBeGolden(`grid-cell-${i}.png`);+ await Promise.all(pages.map(page => page.close()));+ });+ it.skip(FFOX)('should allow transparency', async({page, server}) => {+ await page.setViewport({ width: 100, height: 100 });+ await page.goto(server.EMPTY_PAGE);+ const screenshot = await page.screenshot({omitBackground: true});+ expect(screenshot).toBeGolden('transparent.png');+ });+ it.skip(FFOX || WEBKIT)('should render white background on jpeg file', async({page, server}) => {+ await page.setViewport({ width: 100, height: 100 });+ await page.goto(server.EMPTY_PAGE);+ const screenshot = await page.screenshot({omitBackground: true, type: 'jpeg'});+ expect(screenshot).toBeGolden('white.jpg');+ });+ it('should work with odd clip size on Retina displays', async({page, server}) => {+ const screenshot = await page.screenshot({+ clip: {+ x: 0,+ y: 0,+ width: 11,+ height: 11,+ }+ });+ expect(screenshot).toBeGolden('screenshot-clip-odd-size.png');+ });+ it('should return base64', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.goto(server.PREFIX + '/grid.html');+ const screenshot = await page.screenshot({+ encoding: 'base64'+ });+ expect(Buffer.from(screenshot, 'base64')).toBeGolden('screenshot-sanity.png');+ });+ });++ describe('ElementHandle.screenshot', function() {+ it('should work', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.goto(server.PREFIX + '/grid.html');+ await page.evaluate(() => window.scrollBy(50, 100));+ const elementHandle = await page.$('.box:nth-of-type(3)');+ const screenshot = await elementHandle.screenshot();+ expect(screenshot).toBeGolden('screenshot-element-bounding-box.png');+ });+ it('should take into account padding and border', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.setContent(`+ something above+ <style>div {+ border: 2px solid blue;+ background: green;+ width: 50px;+ height: 50px;+ }+ </style>+ <div></div>+ `);+ const elementHandle = await page.$('div');+ const screenshot = await elementHandle.screenshot();+ expect(screenshot).toBeGolden('screenshot-element-padding-border.png');+ });+ it('should capture full element when larger than viewport', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});++ await page.setContent(`+ something above+ <style>+ div.to-screenshot {+ border: 1px solid blue;+ width: 600px;+ height: 600px;+ margin-left: 50px;+ }+ ::-webkit-scrollbar{+ display: none;+ }+ </style>+ <div class="to-screenshot"></div>+ `);+ const elementHandle = await page.$('div.to-screenshot');+ const screenshot = await elementHandle.screenshot();+ expect(screenshot).toBeGolden('screenshot-element-larger-than-viewport.png');++ expect(await page.evaluate(() => ({ w: window.innerWidth, h: window.innerHeight }))).toEqual({ w: 500, h: 500 });+ });+ it('should scroll element into view', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.setContent(`+ something above+ <style>div.above {+ border: 2px solid blue;+ background: red;+ height: 1500px;+ }+ div.to-screenshot {+ border: 2px solid blue;+ background: green;+ width: 50px;+ height: 50px;+ }+ </style>+ <div class="above"></div>+ <div class="to-screenshot"></div>+ `);+ const elementHandle = await page.$('div.to-screenshot');+ const screenshot = await elementHandle.screenshot();+ expect(screenshot).toBeGolden('screenshot-element-scrolled-into-view.png');+ });+ it.skip(WEBKIT)('should work with a rotated element', async({page, server}) => {+ await page.setViewport({width: 500, height: 500});+ await page.setContent(`<div style="position:absolute;+ top: 100px;+ left: 100px;+ width: 100px;+ height: 100px;+ background: green;+ transform: rotateZ(200deg);"> </div>`);+ const elementHandle = await page.$('div');+ const screenshot = await elementHandle.screenshot();+ expect(screenshot).toBeGolden('screenshot-element-rotate.png');+ });+ it.skip(WEBKIT)('should fail to screenshot a detached element', async({page, server}) => {+ await page.setContent('<h1>remove this</h1>');+ const elementHandle = await page.$('h1');+ await page.evaluate(element => element.remove(), elementHandle);+ const screenshotError = await elementHandle.screenshot().catch(error => error);+ expect(screenshotError.message).toBe('Node is either not visible or not an HTMLElement');+ });+ it.skip(WEBKIT)('should not hang with zero width/height element', async({page, server}) => {+ await page.setContent('<div style="width: 50px; height: 0"></div>');+ const div = await page.$('div');+ const error = await div.screenshot().catch(e => e);+ expect(error.message).toBe('Node has 0 height.');+ });+ it('should work for an element with fractional dimensions', async({page}) => {+ await page.setContent('<div style="width:48.51px;height:19.8px;border:1px solid black;"></div>');+ const elementHandle = await page.$('div');+ const screenshot = await elementHandle.screenshot();+ expect(screenshot).toBeGolden('screenshot-element-fractional.png');+ });+ it('should work for an element with an offset', async({page}) => {+ await page.setContent('<div style="position:absolute; top: 10.3px; left: 20.4px;width:50.3px;height:20.2px;border:1px solid black;"></div>');+ const elementHandle = await page.$('div');+ const screenshot = await elementHandle.screenshot();+ expect(screenshot).toBeGolden('screenshot-element-fractional-offset.png');+ });+ });++};diff --git a/test/target.spec.js b/test/target.spec.jsnew file mode 100644index 0000000000..a287ed4dc6--- /dev/null+++ b/test/target.spec.js@@ -0,0 +1,184 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const utils = require('./utils');+const {waitEvent} = utils;++module.exports.addTests = function({testRunner, expect, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Target', function() {+ // FIXME(WebKit): need to enable agents in the inspected page to listen for updates.+ it.skip(WEBKIT)('Browser.targets should return all of the targets', async({page, server, browser}) => {+ // The pages will be the testing page and the original newtab page+ const targets = browser.targets();+ expect(targets.some(target => target.type() === 'page' &&+ target.url() === 'about:blank')).toBeTruthy('Missing blank page');+ expect(targets.some(target => target.type() === 'browser')).toBeTruthy('Missing browser target');+ });+ it('Browser.pages should return all of the pages', async({page, server, context}) => {+ // The pages will be the testing page+ const allPages = await context.pages();+ expect(allPages.length).toBe(1);+ expect(allPages).toContain(page);+ expect(allPages[0]).not.toBe(allPages[1]);+ });+ it.skip(WEBKIT)('should contain browser target', async({browser}) => {+ const targets = browser.targets();+ const browserTarget = targets.find(target => target.type() === 'browser');+ expect(browserTarget).toBeTruthy();+ });+ it('should be able to use the default page in the browser', async({page, server, browser}) => {+ // The pages will be the testing page and the original newtab page+ const allPages = await browser.pages();+ const originalPage = allPages.find(p => p !== page);+ expect(await originalPage.evaluate(() => ['Hello', 'world'].join(' '))).toBe('Hello world');+ expect(await originalPage.$('body')).toBeTruthy();+ });+ // FIXME(WebKit): need to enable agents in the inspected page to listen for updates.+ it.skip(WEBKIT)('should report when a new page is created and closed', async({page, server, context}) => {+ const [otherPage] = await Promise.all([+ context.waitForTarget(target => target.url() === server.CROSS_PROCESS_PREFIX + '/empty.html').then(target => target.page()),+ page.evaluate(url => window.open(url), server.CROSS_PROCESS_PREFIX + '/empty.html'),+ ]);+ expect(otherPage.url()).toContain(server.CROSS_PROCESS_PREFIX);+ expect(await otherPage.evaluate(() => ['Hello', 'world'].join(' '))).toBe('Hello world');+ expect(await otherPage.$('body')).toBeTruthy();++ let allPages = await context.pages();+ expect(allPages).toContain(page);+ expect(allPages).toContain(otherPage);++ const closePagePromise = new Promise(fulfill => context.once('targetdestroyed', target => fulfill(target.page())));+ await otherPage.close();+ expect(await closePagePromise).toBe(otherPage);++ allPages = await Promise.all(context.targets().map(target => target.page()));+ expect(allPages).toContain(page);+ expect(allPages).not.toContain(otherPage);+ });+ it.skip(FFOX || WEBKIT)('should report when a service worker is created and destroyed', async({page, server, context}) => {+ await page.goto(server.EMPTY_PAGE);+ const createdTarget = new Promise(fulfill => context.once('targetcreated', target => fulfill(target)));++ await page.goto(server.PREFIX + '/serviceworkers/empty/sw.html');++ expect((await createdTarget).type()).toBe('service_worker');+ expect((await createdTarget).url()).toBe(server.PREFIX + '/serviceworkers/empty/sw.js');++ const destroyedTarget = new Promise(fulfill => context.once('targetdestroyed', target => fulfill(target)));+ await page.evaluate(() => window.registrationPromise.then(registration => registration.unregister()));+ expect(await destroyedTarget).toBe(await createdTarget);+ });+ it.skip(FFOX || WEBKIT)('should create a worker from a service worker', async({page, server, context}) => {+ await page.goto(server.PREFIX + '/serviceworkers/empty/sw.html');++ const target = await context.waitForTarget(target => target.type() === 'service_worker');+ const worker = await target.worker();+ expect(await worker.evaluate(() => self.toString())).toBe('[object ServiceWorkerGlobalScope]');+ });+ it.skip(FFOX || WEBKIT)('should create a worker from a shared worker', async({page, server, context}) => {+ await page.goto(server.EMPTY_PAGE);+ await page.evaluate(() => {+ new SharedWorker('data:text/javascript,console.log("hi")');+ });+ const target = await context.waitForTarget(target => target.type() === 'shared_worker');+ const worker = await target.worker();+ expect(await worker.evaluate(() => self.toString())).toBe('[object SharedWorkerGlobalScope]');+ });+ it.skip(WEBKIT)('should report when a target url changes', async({page, server, context}) => {+ await page.goto(server.EMPTY_PAGE);+ let changedTarget = new Promise(fulfill => context.once('targetchanged', target => fulfill(target)));+ await page.goto(server.CROSS_PROCESS_PREFIX + '/');+ expect((await changedTarget).url()).toBe(server.CROSS_PROCESS_PREFIX + '/');++ changedTarget = new Promise(fulfill => context.once('targetchanged', target => fulfill(target)));+ await page.goto(server.EMPTY_PAGE);+ expect((await changedTarget).url()).toBe(server.EMPTY_PAGE);+ });+ it.skip(FFOX || WEBKIT)('should not report uninitialized pages', async({page, server, context}) => {+ let targetChanged = false;+ const listener = () => targetChanged = true;+ context.on('targetchanged', listener);+ const targetPromise = new Promise(fulfill => context.once('targetcreated', target => fulfill(target)));+ const newPagePromise = context.newPage();+ const target = await targetPromise;+ expect(target.url()).toBe('about:blank');++ const newPage = await newPagePromise;+ const targetPromise2 = new Promise(fulfill => context.once('targetcreated', target => fulfill(target)));+ const evaluatePromise = newPage.evaluate(() => window.open('about:blank'));+ const target2 = await targetPromise2;+ expect(target2.url()).toBe('about:blank');+ await evaluatePromise;+ await newPage.close();+ expect(targetChanged).toBe(false, 'target should not be reported as changed');+ context.removeListener('targetchanged', listener);+ });+ it.skip(WEBKIT)('should not crash while redirecting if original request was missed', async({page, server, context}) => {+ let serverResponse = null;+ server.setRoute('/one-style.css', (req, res) => serverResponse = res);+ // Open a new page. Use window.open to connect to the page later.+ await Promise.all([+ page.evaluate(url => window.open(url), server.PREFIX + '/one-style.html'),+ server.waitForRequest('/one-style.css')+ ]);+ // Connect to the opened page.+ const target = await context.waitForTarget(target => target.url().includes('one-style.html'));+ const newPage = await target.page();+ // Issue a redirect.+ serverResponse.writeHead(302, { location: '/injectedstyle.css' });+ serverResponse.end();+ // Wait for the new page to load.+ await waitEvent(newPage, 'load');+ // Cleanup.+ await newPage.close();+ });+ it.skip(WEBKIT)('should have an opener', async({page, server, context}) => {+ await page.goto(server.EMPTY_PAGE);+ const [createdTarget] = await Promise.all([+ new Promise(fulfill => context.once('targetcreated', target => fulfill(target))),+ page.goto(server.PREFIX + '/popup/window-open.html')+ ]);+ expect((await createdTarget.page()).url()).toBe(server.PREFIX + '/popup/popup.html');+ expect(createdTarget.opener()).toBe(page.target());+ expect(page.target().opener()).toBe(null);+ });+ });++ describe('Browser.waitForTarget', () => {+ it('should wait for a target', async function({browser, server}) {+ let resolved = false;+ const targetPromise = browser.waitForTarget(target => target.url() === server.EMPTY_PAGE);+ targetPromise.then(() => resolved = true);+ const page = await browser.newPage();+ expect(resolved).toBe(false);+ await page.goto(server.EMPTY_PAGE);+ const target = await targetPromise;+ expect(await target.page()).toBe(page);+ await page.close();+ });+ it.skip(WEBKIT)('should timeout waiting for a non-existent target', async function({browser, server}) {+ let error = null;+ await browser.waitForTarget(target => target.url() === server.EMPTY_PAGE, {+ timeout: 1+ }).catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ });+};diff --git a/test/test.js b/test/test.jsnew file mode 100644index 0000000000..c9491bdb85--- /dev/null+++ b/test/test.js@@ -0,0 +1,123 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+const path = require('path');+const {TestServer} = require('../utils/testserver/');+const {TestRunner, Reporter} = require('../utils/testrunner/');+const utils = require('./utils');++let parallel = 1;+if (process.env.PPTR_PARALLEL_TESTS)+ parallel = parseInt(process.env.PPTR_PARALLEL_TESTS.trim(), 10);+const parallelArgIndex = process.argv.indexOf('-j');+if (parallelArgIndex !== -1)+ parallel = parseInt(process.argv[parallelArgIndex + 1], 10);+require('events').defaultMaxListeners *= parallel;++// Timeout to 20 seconds on Appveyor instances.+let timeout = process.env.APPVEYOR ? 20 * 1000 : 10 * 1000;+if (!isNaN(process.env.TIMEOUT))+ timeout = parseInt(process.env.TIMEOUT, 10);+const testRunner = new TestRunner({+ timeout,+ parallel,+ breakOnFailure: process.argv.indexOf('--break-on-failure') !== -1,+});+const {describe, fdescribe, beforeAll, afterAll, beforeEach, afterEach} = testRunner;++console.log('Testing on Node', process.version);++beforeAll(async state => {+ const assetsPath = path.join(__dirname, 'assets');+ const cachedPath = path.join(__dirname, 'assets', 'cached');++ const port = 8907 + state.parallelIndex * 2;+ state.server = await TestServer.create(assetsPath, port);+ state.server.enableHTTPCache(cachedPath);+ state.server.PORT = port;+ state.server.PREFIX = `http://localhost:${port}`;+ state.server.CROSS_PROCESS_PREFIX = `http://127.0.0.1:${port}`;+ state.server.EMPTY_PAGE = `http://localhost:${port}/empty.html`;++ const httpsPort = port + 1;+ state.httpsServer = await TestServer.createHTTPS(assetsPath, httpsPort);+ state.httpsServer.enableHTTPCache(cachedPath);+ state.httpsServer.PORT = httpsPort;+ state.httpsServer.PREFIX = `https://localhost:${httpsPort}`;+ state.httpsServer.CROSS_PROCESS_PREFIX = `https://127.0.0.1:${httpsPort}`;+ state.httpsServer.EMPTY_PAGE = `https://localhost:${httpsPort}/empty.html`;+});++afterAll(async({server, httpsServer}) => {+ await Promise.all([+ server.stop(),+ httpsServer.stop(),+ ]);+});++beforeEach(async({server, httpsServer}) => {+ server.reset();+ httpsServer.reset();+});++const CHROMIUM_NO_COVERAGE = new Set([+ 'page.emulateMedia', // Legacy alias for `page.emulateMediaType`.+]);++if (process.env.BROWSER === 'firefox') {+ describe('Firefox', () => {+ require('./playwright.spec.js').addTests({+ product: 'Firefox',+ playwrightPath: path.join(utils.projectRoot(), 'firefox.js'),+ testRunner,+ });+ });+} else if (process.env.BROWSER === 'webkit') {+ describe('WebKit', () => {+ require('./playwright.spec.js').addTests({+ product: 'WebKit',+ playwrightPath: path.join(utils.projectRoot(), 'webkit.js'),+ testRunner,+ });+ });+} else {+ describe('Chromium', () => {+ require('./playwright.spec.js').addTests({+ product: 'Chromium',+ playwrightPath: path.join(utils.projectRoot(), 'chromium.js'),+ testRunner,+ });+ if (process.env.COVERAGE)+ utils.recordAPICoverage(testRunner, require('../lib/api').Chromium, require('../lib/Events').Events, CHROMIUM_NO_COVERAGE);+ });+}++if (process.env.CI && testRunner.hasFocusedTestsOrSuites()) {+ console.error('ERROR: "focused" tests/suites are prohibitted on bots. Remove any "fit"/"fdescribe" declarations.');+ process.exit(1);+}++new Reporter(testRunner, {+ verbose: process.argv.includes('--verbose'),+ summary: !process.argv.includes('--verbose'),+ projectFolder: utils.projectRoot(),+ showSlowTests: process.env.CI ? 5 : 0,+});++(async() => {+ // await utils.initializeFlakinessDashboardIfNeeded(testRunner);+ testRunner.run();+})();+diff --git a/test/touchscreen.spec.js b/test/touchscreen.spec.jsnew file mode 100644index 0000000000..a98b007f7a--- /dev/null+++ b/test/touchscreen.spec.js@@ -0,0 +1,37 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports.addTests = function({testRunner, expect, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const iPhone = playwright.devices['iPhone 6'];+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;+ describe.skip(WEBKIT)('Touchscreen', function() {+ it('should tap the button', async({page, server}) => {+ await page.emulate(iPhone);+ await page.goto(server.PREFIX + '/input/button.html');+ await page.tap('button');+ expect(await page.evaluate(() => result)).toBe('Clicked');+ });+ it('should report touches', async({page, server}) => {+ await page.emulate(iPhone);+ await page.goto(server.PREFIX + '/input/touches.html');+ const button = await page.$('button');+ await button.tap();+ expect(await page.evaluate(() => getResult())).toEqual(['Touchstart: 0', 'Touchend: 0']);+ });+ });+};diff --git a/test/tracing.spec.js b/test/tracing.spec.jsnew file mode 100644index 0000000000..e319e92bdd--- /dev/null+++ b/test/tracing.spec.js@@ -0,0 +1,93 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const fs = require('fs');+const path = require('path');++module.exports.addTests = function({testRunner, expect, defaultBrowserOptions, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Tracing', function() {+ beforeEach(async function(state) {+ state.outputFile = path.join(__dirname, 'assets', `trace-${state.parallelIndex}.json`);+ state.browser = await playwright.launch(defaultBrowserOptions);+ state.page = await state.browser.newPage();+ });+ afterEach(async function(state) {+ await state.browser.close();+ state.browser = null;+ state.page = null;+ if (fs.existsSync(state.outputFile)) {+ fs.unlinkSync(state.outputFile);+ state.outputFile = null;+ }+ });+ it('should output a trace', async({page, server, outputFile}) => {+ await page.tracing.start({screenshots: true, path: outputFile});+ await page.goto(server.PREFIX + '/grid.html');+ await page.tracing.stop();+ expect(fs.existsSync(outputFile)).toBe(true);+ });+ it('should run with custom categories if provided', async({page, outputFile}) => {+ await page.tracing.start({path: outputFile, categories: ['disabled-by-default-v8.cpu_profiler.hires']});+ await page.tracing.stop();++ const traceJson = JSON.parse(fs.readFileSync(outputFile));+ expect(traceJson.metadata['trace-config']).toContain('disabled-by-default-v8.cpu_profiler.hires');+ });+ it('should throw if tracing on two pages', async({page, server, browser, outputFile}) => {+ await page.tracing.start({path: outputFile});+ const newPage = await browser.newPage();+ let error = null;+ await newPage.tracing.start({path: outputFile}).catch(e => error = e);+ await newPage.close();+ expect(error).toBeTruthy();+ await page.tracing.stop();+ });+ it('should return a buffer', async({page, server, outputFile}) => {+ await page.tracing.start({screenshots: true, path: outputFile});+ await page.goto(server.PREFIX + '/grid.html');+ const trace = await page.tracing.stop();+ const buf = fs.readFileSync(outputFile);+ expect(trace.toString()).toEqual(buf.toString());+ });+ it('should work without options', async({page, server, outputFile}) => {+ await page.tracing.start();+ await page.goto(server.PREFIX + '/grid.html');+ const trace = await page.tracing.stop();+ expect(trace).toBeTruthy();+ });+ it('should return null in case of Buffer error', async({page, server}) => {+ await page.tracing.start({screenshots: true});+ await page.goto(server.PREFIX + '/grid.html');+ const oldBufferConcat = Buffer.concat;+ Buffer.concat = bufs => {+ throw 'error';+ };+ const trace = await page.tracing.stop();+ expect(trace).toEqual(null);+ Buffer.concat = oldBufferConcat;+ });+ it('should support a buffer without a path', async({page, server}) => {+ await page.tracing.start({screenshots: true});+ await page.goto(server.PREFIX + '/grid.html');+ const trace = await page.tracing.stop();+ expect(trace.toString()).toContain('screenshot');+ });+ });+};diff --git a/test/utils.js b/test/utils.jsnew file mode 100644index 0000000000..c76241f53e--- /dev/null+++ b/test/utils.js@@ -0,0 +1,261 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const fs = require('fs');+const path = require('path');+const {FlakinessDashboard} = require('../utils/flakiness-dashboard');+const PROJECT_ROOT = fs.existsSync(path.join(__dirname, '..', 'package.json')) ? path.join(__dirname, '..') : path.join(__dirname, '..', '..');++const COVERAGE_TESTSUITE_NAME = '**API COVERAGE**';++/**+ * @param {Map<string, boolean>} apiCoverage+ * @param {Object} events+ * @param {string} className+ * @param {!Object} classType+ */+function traceAPICoverage(apiCoverage, events, className, classType) {+ className = className.substring(0, 1).toLowerCase() + className.substring(1);+ for (const methodName of Reflect.ownKeys(classType.prototype)) {+ const method = Reflect.get(classType.prototype, methodName);+ if (methodName === 'constructor' || typeof methodName !== 'string' || methodName.startsWith('_') || typeof method !== 'function')+ continue;+ apiCoverage.set(`${className}.${methodName}`, false);+ Reflect.set(classType.prototype, methodName, function(...args) {+ apiCoverage.set(`${className}.${methodName}`, true);+ return method.call(this, ...args);+ });+ }++ if (events[classType.name]) {+ for (const event of Object.values(events[classType.name])) {+ if (typeof event !== 'symbol')+ apiCoverage.set(`${className}.emit(${JSON.stringify(event)})`, false);+ }+ const method = Reflect.get(classType.prototype, 'emit');+ Reflect.set(classType.prototype, 'emit', function(event, ...args) {+ if (typeof event !== 'symbol' && this.listenerCount(event))+ apiCoverage.set(`${className}.emit(${JSON.stringify(event)})`, true);+ return method.call(this, event, ...args);+ });+ }+}++const utils = module.exports = {+ recordAPICoverage: function(testRunner, api, events, disabled) {+ const coverage = new Map();+ for (const [className, classType] of Object.entries(api))+ traceAPICoverage(coverage, events, className, classType);+ testRunner.describe(COVERAGE_TESTSUITE_NAME, () => {+ testRunner.it('should call all API methods', () => {+ const missingMethods = [];+ for (const method of coverage.keys()) {+ if (!coverage.get(method) && !disabled.has(method))+ missingMethods.push(method);+ }+ if (missingMethods.length)+ throw new Error('Certain API Methods are not called: ' + missingMethods.join(', '));+ });+ });+ },++ /**+ * @return {string}+ */+ projectRoot: function() {+ return PROJECT_ROOT;+ },++ /**+ * @param {!Page} page+ * @param {string} frameId+ * @param {string} url+ * @return {!Playwright.Frame}+ */+ attachFrame: async function(page, frameId, url) {+ const frames = new Set(page.frames());+ const handle = await page.evaluateHandle(attachFrame, frameId, url);+ try {+ return await handle.asElement().contentFrame();+ } catch(e) {+ // we might not support contentFrame, but this can still work ok.+ for (const frame of page.frames()) {+ if (!frames.has(frame))+ return frame;+ }+ }+ return null;++ async function attachFrame(frameId, url) {+ const frame = document.createElement('iframe');+ frame.src = url;+ frame.id = frameId;+ document.body.appendChild(frame);+ // TODO(einbinder) do this right+ // Access a scriptable global object to ensure JS context is+ // initialized. WebKit will create it lazily only as need be.+ frame.contentWindow;+ await new Promise(x => frame.onload = x);+ return frame;+ }+ },++ isFavicon: function(request) {+ return request.url().includes('favicon.ico');+ },++ /**+ * @param {!Page} page+ * @param {string} frameId+ */+ detachFrame: async function(page, frameId) {+ await page.evaluate(detachFrame, frameId);++ function detachFrame(frameId) {+ const frame = document.getElementById(frameId);+ frame.remove();+ }+ },++ /**+ * @param {!Page} page+ * @param {string} frameId+ * @param {string} url+ */+ navigateFrame: async function(page, frameId, url) {+ await page.evaluate(navigateFrame, frameId, url);++ function navigateFrame(frameId, url) {+ const frame = document.getElementById(frameId);+ frame.src = url;+ return new Promise(x => frame.onload = x);+ }+ },++ /**+ * @param {!Frame} frame+ * @param {string=} indentation+ * @return {Array<string>}+ */+ dumpFrames: function(frame, indentation) {+ indentation = indentation || '';+ let description = frame.url().replace(/:\d{4}\//, ':<PORT>/');+ if (frame.name())+ description += ' (' + frame.name() + ')';+ const result = [indentation + description];+ const childFrames = frame.childFrames();+ childFrames.sort((a, b) => {+ if (a.url() !== b.url())+ return a.url() < b.url() ? -1 : 1;+ return a.name() < b.name() ? -1 : 1;+ });+ for (const child of childFrames)+ result.push(...utils.dumpFrames(child, ' ' + indentation));+ return result;+ },++ /**+ * @param {!EventEmitter} emitter+ * @param {string} eventName+ * @return {!Promise<!Object>}+ */+ waitEvent: function(emitter, eventName, predicate = () => true) {+ return new Promise(fulfill => {+ emitter.on(eventName, function listener(event) {+ if (!predicate(event))+ return;+ emitter.removeListener(eventName, listener);+ fulfill(event);+ });+ });+ },++ initializeFlakinessDashboardIfNeeded: async function(testRunner) {+ // Generate testIDs for all tests and verify they don't clash.+ // This will add |test.testId| for every test.+ //+ // NOTE: we do this on CI's so that problems arise on PR trybots.+ if (process.env.CI)+ generateTestIDs(testRunner);+ // FLAKINESS_DASHBOARD_PASSWORD is an encrypted/secured variable.+ // Encrypted variables get a special treatment in CI's when handling PRs so that+ // secrets are not leaked to untrusted code.+ // - AppVeyor DOES NOT decrypt secured variables for PRs+ // - Travis DOES NOT decrypt encrypted variables for PRs+ // - Cirrus CI DOES NOT decrypt encrypted variables for PRs *unless* PR is sent+ // from someone who has WRITE ACCESS to the repo.+ //+ // Since we don't want to run flakiness dashboard for PRs on all CIs, we+ // check existance of FLAKINESS_DASHBOARD_PASSWORD and absense of+ // CIRRUS_BASE_SHA env variables.+ if (!process.env.FLAKINESS_DASHBOARD_PASSWORD || process.env.CIRRUS_BASE_SHA)+ return;+ const {sha, timestamp} = await FlakinessDashboard.getCommitDetails(__dirname, 'HEAD');+ const dashboard = new FlakinessDashboard({+ commit: {+ sha,+ timestamp,+ url: `https://github.com/Microsoft/playwright/commit/${sha}`,+ },+ build: {+ url: process.env.FLAKINESS_DASHBOARD_BUILD_URL,+ },+ dashboardRepo: {+ url: 'https://github.com/aslushnikov/playwright-flakiness-dashboard.git',+ username: 'playwright-flakiness',+ email: '[email protected]',+ password: process.env.FLAKINESS_DASHBOARD_PASSWORD,+ branch: process.env.FLAKINESS_DASHBOARD_NAME,+ },+ });++ testRunner.on('testfinished', test => {+ // Do not report tests from COVERAGE testsuite.+ // They don't bring much value to us.+ if (test.fullName.includes(COVERAGE_TESTSUITE_NAME))+ return;+ const testpath = test.location.filePath.substring(utils.projectRoot().length);+ const url = `https://github.com/Microsoft/playwright/blob/${sha}/${testpath}#L${test.location.lineNumber}`;+ dashboard.reportTestResult({+ testId: test.testId,+ name: test.location.fileName + ':' + test.location.lineNumber,+ description: test.fullName,+ url,+ result: test.result,+ });+ });+ testRunner.on('finished', async({result}) => {+ dashboard.setBuildResult(result);+ await dashboard.uploadAndCleanup();+ });++ function generateTestIDs(testRunner) {+ const testIds = new Map();+ for (const test of testRunner.tests()) {+ const testIdComponents = [test.name];+ for (let suite = test.suite; !!suite.parentSuite; suite = suite.parentSuite)+ testIdComponents.push(suite.name);+ testIdComponents.reverse();+ const testId = testIdComponents.join('>');+ const clashingTest = testIds.get(testId);+ if (clashingTest)+ throw new Error(`Two tests with clashing IDs: ${test.location.fileName}:${test.location.lineNumber} and ${clashingTest.location.fileName}:${clashingTest.location.lineNumber}`);+ testIds.set(testId, test);+ test.testId = testId;+ }+ }+ },+};diff --git a/test/waittask.spec.js b/test/waittask.spec.jsnew file mode 100644index 0000000000..916e10ef85--- /dev/null+++ b/test/waittask.spec.js@@ -0,0 +1,445 @@+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const utils = require('./utils');++module.exports.addTests = function({testRunner, expect, product, playwright, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe('Page.waitFor', function() {+ it('should wait for selector', async({page, server}) => {+ let found = false;+ const waitFor = page.waitFor('div').then(() => found = true);+ await page.goto(server.EMPTY_PAGE);+ expect(found).toBe(false);+ await page.goto(server.PREFIX + '/grid.html');+ await waitFor;+ expect(found).toBe(true);+ });+ it('should wait for an xpath', async({page, server}) => {+ let found = false;+ const waitFor = page.waitFor('//div').then(() => found = true);+ await page.goto(server.EMPTY_PAGE);+ expect(found).toBe(false);+ await page.goto(server.PREFIX + '/grid.html');+ await waitFor;+ expect(found).toBe(true);+ });+ it('should not allow you to select an element with single slash xpath', async({page, server}) => {+ await page.setContent(`<div>some text</div>`);+ let error = null;+ await page.waitFor('/html/body/div').catch(e => error = e);+ expect(error).toBeTruthy();+ });+ it('should timeout', async({page, server}) => {+ const startTime = Date.now();+ const timeout = 42;+ await page.waitFor(timeout);+ expect(Date.now() - startTime).not.toBeLessThan(timeout / 2);+ });+ it('should work with multiline body', async({page, server}) => {+ const result = await page.waitForFunction(`+ (() => true)()+ `);+ expect(await result.jsonValue()).toBe(true);+ });+ it('should wait for predicate', async({page, server}) => {+ await Promise.all([+ page.waitFor(() => window.innerWidth < 130), // Windows doesn't like windows below 120px wide+ page.setViewport({width: 10, height: 10}),+ ]);+ });+ it('should throw when unknown type', async({page, server}) => {+ let error = null;+ await page.waitFor({foo: 'bar'}).catch(e => error = e);+ expect(error.message).toContain('Unsupported target type');+ });+ it('should wait for predicate with arguments', async({page, server}) => {+ await page.waitFor((arg1, arg2) => arg1 !== arg2, {}, 1, 2);+ });+ });++ describe('Frame.waitForFunction', function() {+ it('should accept a string', async({page, server}) => {+ const watchdog = page.waitForFunction('window.__FOO === 1');+ await page.evaluate(() => window.__FOO = 1);+ await watchdog;+ });+ it.skip(WEBKIT)('should work when resolved right before execution context disposal', async({page, server}) => {+ // FIXME: implement Page.addScriptToEvaluateOnNewDocument in WebKit.+ await page.evaluateOnNewDocument(() => window.__RELOADED = true);+ await page.waitForFunction(() => {+ if (!window.__RELOADED)+ window.location.reload();+ return true;+ });+ });+ it('should poll on interval', async({page, server}) => {+ let success = false;+ const startTime = Date.now();+ const polling = 100;+ const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling})+ .then(() => success = true);+ await page.evaluate(() => window.__FOO = 'hit');+ expect(success).toBe(false);+ await page.evaluate(() => document.body.appendChild(document.createElement('div')));+ await watchdog;+ expect(Date.now() - startTime).not.toBeLessThan(polling / 2);+ });+ it('should poll on mutation', async({page, server}) => {+ let success = false;+ const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling: 'mutation'})+ .then(() => success = true);+ await page.evaluate(() => window.__FOO = 'hit');+ expect(success).toBe(false);+ await page.evaluate(() => document.body.appendChild(document.createElement('div')));+ await watchdog;+ });+ it('should poll on raf', async({page, server}) => {+ const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling: 'raf'});+ await page.evaluate(() => window.__FOO = 'hit');+ await watchdog;+ });+ it.skip(FFOX)('should work with strict CSP policy', async({page, server}) => {+ server.setCSP('/empty.html', 'script-src ' + server.PREFIX);+ await page.goto(server.EMPTY_PAGE);+ let error = null;+ await Promise.all([+ page.waitForFunction(() => window.__FOO === 'hit', {polling: 'raf'}).catch(e => error = e),+ page.evaluate(() => window.__FOO = 'hit')+ ]);+ expect(error).toBe(null);+ });+ it('should throw on bad polling value', async({page, server}) => {+ let error = null;+ try {+ await page.waitForFunction(() => !!document.body, {polling: 'unknown'});+ } catch (e) {+ error = e;+ }+ expect(error).toBeTruthy();+ expect(error.message).toContain('polling');+ });+ it('should throw negative polling interval', async({page, server}) => {+ let error = null;+ try {+ await page.waitForFunction(() => !!document.body, {polling: -10});+ } catch (e) {+ error = e;+ }+ expect(error).toBeTruthy();+ expect(error.message).toContain('Cannot poll with non-positive interval');+ });+ it('should return the success value as a JSHandle', async({page}) => {+ expect(await (await page.waitForFunction(() => 5)).jsonValue()).toBe(5);+ });+ it('should return the window as a success value', async({ page }) => {+ expect(await page.waitForFunction(() => window)).toBeTruthy();+ });+ it('should accept ElementHandle arguments', async({page}) => {+ await page.setContent('<div></div>');+ const div = await page.$('div');+ let resolved = false;+ const waitForFunction = page.waitForFunction(element => !element.parentElement, {}, div).then(() => resolved = true);+ expect(resolved).toBe(false);+ await page.evaluate(element => element.remove(), div);+ await waitForFunction;+ });+ it('should respect timeout', async({page}) => {+ let error = null;+ await page.waitForFunction('false', {timeout: 10}).catch(e => error = e);+ expect(error).toBeTruthy();+ expect(error.message).toContain('waiting for function failed: timeout');+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should respect default timeout', async({page}) => {+ page.setDefaultTimeout(1);+ let error = null;+ await page.waitForFunction('false').catch(e => error = e);+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ expect(error.message).toContain('waiting for function failed: timeout');+ });+ it('should disable timeout when its set to 0', async({page}) => {+ const watchdog = page.waitForFunction(() => {+ window.__counter = (window.__counter || 0) + 1;+ return window.__injected;+ }, {timeout: 0, polling: 10});+ await page.waitForFunction(() => window.__counter > 10);+ await page.evaluate(() => window.__injected = true);+ await watchdog;+ });+ it('should survive cross-process navigation', async({page, server}) => {+ let fooFound = false;+ const waitForFunction = page.waitForFunction('window.__FOO === 1').then(() => fooFound = true);+ await page.goto(server.EMPTY_PAGE);+ expect(fooFound).toBe(false);+ await page.reload();+ expect(fooFound).toBe(false);+ await page.goto(server.CROSS_PROCESS_PREFIX + '/grid.html');+ expect(fooFound).toBe(false);+ await page.evaluate(() => window.__FOO = 1);+ await waitForFunction;+ expect(fooFound).toBe(true);+ });+ it('should survive navigations', async({page, server}) => {+ const watchdog = page.waitForFunction(() => window.__done);+ await page.goto(server.EMPTY_PAGE);+ await page.goto(server.PREFIX + '/consolelog.html');+ await page.evaluate(() => window.__done = true);+ await watchdog;+ });+ });++ describe('Frame.waitForSelector', function() {+ const addElement = tag => document.body.appendChild(document.createElement(tag));++ it('should immediately resolve promise if node exists', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const frame = page.mainFrame();+ await frame.waitForSelector('*');+ await frame.evaluate(addElement, 'div');+ await frame.waitForSelector('div');+ });++ it.skip(FFOX || WEBKIT)('should work with removed MutationObserver', async({page, server}) => {+ await page.evaluate(() => delete window.MutationObserver);+ const [handle] = await Promise.all([+ page.waitForSelector('.zombo'),+ page.setContent(`<div class='zombo'>anything</div>`),+ ]);+ expect(await page.evaluate(x => x.textContent, handle)).toBe('anything');+ });++ it('should resolve promise when node is added', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const frame = page.mainFrame();+ const watchdog = frame.waitForSelector('div');+ await frame.evaluate(addElement, 'br');+ await frame.evaluate(addElement, 'div');+ const eHandle = await watchdog;+ const tagName = await eHandle.getProperty('tagName').then(e => e.jsonValue());+ expect(tagName).toBe('DIV');+ });++ it('should work when node is added through innerHTML', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ const watchdog = page.waitForSelector('h3 div');+ await page.evaluate(addElement, 'span');+ await page.evaluate(() => document.querySelector('span').innerHTML = '<h3><div></div></h3>');+ await watchdog;+ });++ it('Page.waitForSelector is shortcut for main frame', async({page, server}) => {+ await page.goto(server.EMPTY_PAGE);+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ const otherFrame = page.frames()[1];+ const watchdog = page.waitForSelector('div');+ await otherFrame.evaluate(addElement, 'div');+ await page.evaluate(addElement, 'div');+ const eHandle = await watchdog;+ expect(eHandle.executionContext().frame()).toBe(page.mainFrame());+ });++ it('should run in specified frame', async({page, server}) => {+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);+ const frame1 = page.frames()[1];+ const frame2 = page.frames()[2];+ const waitForSelectorPromise = frame2.waitForSelector('div');+ await frame1.evaluate(addElement, 'div');+ await frame2.evaluate(addElement, 'div');+ const eHandle = await waitForSelectorPromise;+ expect(eHandle.executionContext().frame()).toBe(frame2);+ });++ it('should throw when frame is detached', async({page, server}) => {+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ const frame = page.frames()[1];+ let waitError = null;+ const waitPromise = frame.waitForSelector('.box').catch(e => waitError = e);+ await utils.detachFrame(page, 'frame1');+ await waitPromise;+ expect(waitError).toBeTruthy();+ expect(waitError.message).toContain('waitForFunction failed: frame got detached.');+ });+ it('should survive cross-process navigation', async({page, server}) => {+ let boxFound = false;+ const waitForSelector = page.waitForSelector('.box').then(() => boxFound = true);+ await page.goto(server.EMPTY_PAGE);+ expect(boxFound).toBe(false);+ await page.reload();+ expect(boxFound).toBe(false);+ await page.goto(server.CROSS_PROCESS_PREFIX + '/grid.html');+ await waitForSelector;+ expect(boxFound).toBe(true);+ });+ it('should wait for visible', async({page, server}) => {+ let divFound = false;+ const waitForSelector = page.waitForSelector('div', {visible: true}).then(() => divFound = true);+ await page.setContent(`<div style='display: none; visibility: hidden;'>1</div>`);+ expect(divFound).toBe(false);+ await page.evaluate(() => document.querySelector('div').style.removeProperty('display'));+ expect(divFound).toBe(false);+ await page.evaluate(() => document.querySelector('div').style.removeProperty('visibility'));+ expect(await waitForSelector).toBe(true);+ expect(divFound).toBe(true);+ });+ it('should wait for visible recursively', async({page, server}) => {+ let divVisible = false;+ const waitForSelector = page.waitForSelector('div#inner', {visible: true}).then(() => divVisible = true);+ await page.setContent(`<div style='display: none; visibility: hidden;'><div id="inner">hi</div></div>`);+ expect(divVisible).toBe(false);+ await page.evaluate(() => document.querySelector('div').style.removeProperty('display'));+ expect(divVisible).toBe(false);+ await page.evaluate(() => document.querySelector('div').style.removeProperty('visibility'));+ expect(await waitForSelector).toBe(true);+ expect(divVisible).toBe(true);+ });+ it('hidden should wait for visibility: hidden', async({page, server}) => {+ let divHidden = false;+ await page.setContent(`<div style='display: block;'></div>`);+ const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divHidden = true);+ await page.waitForSelector('div'); // do a round trip+ expect(divHidden).toBe(false);+ await page.evaluate(() => document.querySelector('div').style.setProperty('visibility', 'hidden'));+ expect(await waitForSelector).toBe(true);+ expect(divHidden).toBe(true);+ });+ it('hidden should wait for display: none', async({page, server}) => {+ let divHidden = false;+ await page.setContent(`<div style='display: block;'></div>`);+ const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divHidden = true);+ await page.waitForSelector('div'); // do a round trip+ expect(divHidden).toBe(false);+ await page.evaluate(() => document.querySelector('div').style.setProperty('display', 'none'));+ expect(await waitForSelector).toBe(true);+ expect(divHidden).toBe(true);+ });+ it('hidden should wait for removal', async({page, server}) => {+ await page.setContent(`<div></div>`);+ let divRemoved = false;+ const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divRemoved = true);+ await page.waitForSelector('div'); // do a round trip+ expect(divRemoved).toBe(false);+ await page.evaluate(() => document.querySelector('div').remove());+ expect(await waitForSelector).toBe(true);+ expect(divRemoved).toBe(true);+ });+ it('should return null if waiting to hide non-existing element', async({page, server}) => {+ const handle = await page.waitForSelector('non-existing', { hidden: true });+ expect(handle).toBe(null);+ });+ it('should respect timeout', async({page, server}) => {+ let error = null;+ await page.waitForSelector('div', {timeout: 10}).catch(e => error = e);+ expect(error).toBeTruthy();+ expect(error.message).toContain('waiting for selector "div" failed: timeout');+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should have an error message specifically for awaiting an element to be hidden', async({page, server}) => {+ await page.setContent(`<div></div>`);+ let error = null;+ await page.waitForSelector('div', {hidden: true, timeout: 10}).catch(e => error = e);+ expect(error).toBeTruthy();+ expect(error.message).toContain('waiting for selector "div" to be hidden failed: timeout');+ });++ it('should respond to node attribute mutation', async({page, server}) => {+ let divFound = false;+ const waitForSelector = page.waitForSelector('.zombo').then(() => divFound = true);+ await page.setContent(`<div class='notZombo'></div>`);+ expect(divFound).toBe(false);+ await page.evaluate(() => document.querySelector('div').className = 'zombo');+ expect(await waitForSelector).toBe(true);+ });+ it('should return the element handle', async({page, server}) => {+ const waitForSelector = page.waitForSelector('.zombo');+ await page.setContent(`<div class='zombo'>anything</div>`);+ expect(await page.evaluate(x => x.textContent, await waitForSelector)).toBe('anything');+ });+ it('should have correct stack trace for timeout', async({page, server}) => {+ let error;+ await page.waitForSelector('.zombo', {timeout: 10}).catch(e => error = e);+ expect(error.stack).toContain('waittask.spec.js');+ });+ });++ describe('Frame.waitForXPath', function() {+ const addElement = tag => document.body.appendChild(document.createElement(tag));++ it('should support some fancy xpath', async({page, server}) => {+ await page.setContent(`<p>red herring</p><p>hello world </p>`);+ const waitForXPath = page.waitForXPath('//p[normalize-space(.)="hello world"]');+ expect(await page.evaluate(x => x.textContent, await waitForXPath)).toBe('hello world ');+ });+ it('should respect timeout', async({page}) => {+ let error = null;+ await page.waitForXPath('//div', {timeout: 10}).catch(e => error = e);+ expect(error).toBeTruthy();+ expect(error.message).toContain('waiting for XPath "//div" failed: timeout');+ expect(error).toBeInstanceOf(playwright.errors.TimeoutError);+ });+ it('should run in specified frame', async({page, server}) => {+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);+ const frame1 = page.frames()[1];+ const frame2 = page.frames()[2];+ const waitForXPathPromise = frame2.waitForXPath('//div');+ await frame1.evaluate(addElement, 'div');+ await frame2.evaluate(addElement, 'div');+ const eHandle = await waitForXPathPromise;+ expect(eHandle.executionContext().frame()).toBe(frame2);+ });+ it('should throw when frame is detached', async({page, server}) => {+ await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);+ const frame = page.frames()[1];+ let waitError = null;+ const waitPromise = frame.waitForXPath('//*[@class="box"]').catch(e => waitError = e);+ await utils.detachFrame(page, 'frame1');+ await waitPromise;+ expect(waitError).toBeTruthy();+ expect(waitError.message).toContain('waitForFunction failed: frame got detached.');+ });+ it('hidden should wait for display: none', async({page, server}) => {+ let divHidden = false;+ await page.setContent(`<div style='display: block;'></div>`);+ const waitForXPath = page.waitForXPath('//div', {hidden: true}).then(() => divHidden = true);+ await page.waitForXPath('//div'); // do a round trip+ expect(divHidden).toBe(false);+ await page.evaluate(() => document.querySelector('div').style.setProperty('display', 'none'));+ expect(await waitForXPath).toBe(true);+ expect(divHidden).toBe(true);+ });+ it('should return the element handle', async({page, server}) => {+ const waitForXPath = page.waitForXPath('//*[@class="zombo"]');+ await page.setContent(`<div class='zombo'>anything</div>`);+ expect(await page.evaluate(x => x.textContent, await waitForXPath)).toBe('anything');+ });+ it('should allow you to select a text node', async({page, server}) => {+ await page.setContent(`<div>some text</div>`);+ const text = await page.waitForXPath('//div/text()');+ expect(await (await text.getProperty('nodeType')).jsonValue()).toBe(3 /* Node.TEXT_NODE */);+ });+ it('should allow you to select an element with single slash', async({page, server}) => {+ await page.setContent(`<div>some text</div>`);+ const waitForXPath = page.waitForXPath('/html/body/div');+ expect(await page.evaluate(x => x.textContent, await waitForXPath)).toBe('some text');+ });+ });++};diff --git a/test/worker.spec.js b/test/worker.spec.jsnew file mode 100644index 0000000000..f44796dd90--- /dev/null+++ b/test/worker.spec.js@@ -0,0 +1,66 @@+const utils = require('./utils');+const {waitEvent} = utils;++module.exports.addTests = function({testRunner, expect, FFOX, CHROME, WEBKIT}) {+ const {describe, xdescribe, fdescribe} = testRunner;+ const {it, fit, xit} = testRunner;+ const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;++ describe.skip(FFOX || WEBKIT)('Workers', function() {+ it('Page.workers', async function({page, server}) {+ await Promise.all([+ new Promise(x => page.once('workercreated', x)),+ page.goto(server.PREFIX + '/worker/worker.html')]);+ const worker = page.workers()[0];+ expect(worker.url()).toContain('worker.js');++ expect(await worker.evaluate(() => self.workerFunction())).toBe('worker function result');++ await page.goto(server.EMPTY_PAGE);+ expect(page.workers().length).toBe(0);+ });+ it('should emit created and destroyed events', async function({page}) {+ const workerCreatedPromise = new Promise(x => page.once('workercreated', x));+ const workerObj = await page.evaluateHandle(() => new Worker('data:text/javascript,1'));+ const worker = await workerCreatedPromise;+ const workerThisObj = await worker.evaluateHandle(() => this);+ const workerDestroyedPromise = new Promise(x => page.once('workerdestroyed', x));+ await page.evaluate(workerObj => workerObj.terminate(), workerObj);+ expect(await workerDestroyedPromise).toBe(worker);+ const error = await workerThisObj.getProperty('self').catch(error => error);+ expect(error.message).toContain('Most likely the worker has been closed.');+ });+ it('should report console logs', async function({page}) {+ const [message] = await Promise.all([+ waitEvent(page, 'console'),+ page.evaluate(() => new Worker(`data:text/javascript,console.log(1)`)),+ ]);+ expect(message.text()).toBe('1');+ expect(message.location()).toEqual({+ url: 'data:text/javascript,console.log(1)',+ lineNumber: 0,+ columnNumber: 8,+ });+ });+ it('should have JSHandles for console logs', async function({page}) {+ const logPromise = new Promise(x => page.on('console', x));+ await page.evaluate(() => new Worker(`data:text/javascript,console.log(1,2,3,this)`));+ const log = await logPromise;+ expect(log.text()).toBe('1 2 3 JSHandle@object');+ expect(log.args().length).toBe(4);+ expect(await (await log.args()[3].getProperty('origin')).jsonValue()).toBe('null');+ });+ it('should have an execution context', async function({page}) {+ const workerCreatedPromise = new Promise(x => page.once('workercreated', x));+ await page.evaluate(() => new Worker(`data:text/javascript,console.log(1)`));+ const worker = await workerCreatedPromise;+ expect(await (await worker.executionContext()).evaluate('1+1')).toBe(2);+ });+ it('should report errors', async function({page}) {+ const errorPromise = new Promise(x => page.on('pageerror', x));+ await page.evaluate(() => new Worker(`data:text/javascript, throw new Error('this is my error');`));+ const errorLog = await errorPromise;+ expect(errorLog.message).toContain('this is my error');+ });+ });+};diff --git a/tsconfig.json b/tsconfig.jsonnew file mode 100644index 0000000000..53f6098bb5--- /dev/null+++ b/tsconfig.json@@ -0,0 +1,15 @@+{+ "compilerOptions": {+ "allowJs": true,+ "checkJs": true,+ "target": "ESNext",+ "module": "commonjs",+ "lib": ["esnext", "dom"],+ "sourceMap": true,+ "rootDir": "./src",+ "outDir": "./lib"+ },+ "compileOnSave": true,+ "include": ["src"],+ "exclude": ["node_modules"]+}diff --git a/utils/ESTreeWalker.js b/utils/ESTreeWalker.jsnew file mode 100644index 0000000000..097a53d22a--- /dev/null+++ b/utils/ESTreeWalker.js@@ -0,0 +1,136 @@+// Copyright (c) 2014 The Chromium Authors. All rights reserved.+// Use of this source code is governed by a BSD-style license that can be+// found in the LICENSE file.++/**+ * @unrestricted+ */+class ESTreeWalker {+ /**+ * @param {function(!ESTree.Node):(!Object|undefined)} beforeVisit+ * @param {function(!ESTree.Node)=} afterVisit+ */+ constructor(beforeVisit, afterVisit) {+ this._beforeVisit = beforeVisit;+ this._afterVisit = afterVisit || new Function();+ }++ /**+ * @param {!ESTree.Node} ast+ */+ walk(ast) {+ this._innerWalk(ast, null);+ }++ /**+ * @param {!ESTree.Node} node+ * @param {?ESTree.Node} parent+ */+ _innerWalk(node, parent) {+ if (!node)+ return;+ node.parent = parent;++ if (this._beforeVisit.call(null, node) === ESTreeWalker.SkipSubtree) {+ this._afterVisit.call(null, node);+ return;+ }++ const walkOrder = ESTreeWalker._walkOrder[node.type];+ if (!walkOrder)+ return;++ if (node.type === 'TemplateLiteral') {+ const templateLiteral = /** @type {!ESTree.TemplateLiteralNode} */ (node);+ const expressionsLength = templateLiteral.expressions.length;+ for (let i = 0; i < expressionsLength; ++i) {+ this._innerWalk(templateLiteral.quasis[i], templateLiteral);+ this._innerWalk(templateLiteral.expressions[i], templateLiteral);+ }+ this._innerWalk(templateLiteral.quasis[expressionsLength], templateLiteral);+ } else {+ for (let i = 0; i < walkOrder.length; ++i) {+ const entity = node[walkOrder[i]];+ if (Array.isArray(entity))+ this._walkArray(entity, node);+ else+ this._innerWalk(entity, node);+ }+ }++ this._afterVisit.call(null, node);+ }++ /**+ * @param {!Array.<!ESTree.Node>} nodeArray+ * @param {?ESTree.Node} parentNode+ */+ _walkArray(nodeArray, parentNode) {+ for (let i = 0; i < nodeArray.length; ++i)+ this._innerWalk(nodeArray[i], parentNode);+ }+}++/** @typedef {!Object} ESTreeWalker.SkipSubtree */+ESTreeWalker.SkipSubtree = {};++/** @enum {!Array.<string>} */+ESTreeWalker._walkOrder = {+ 'AwaitExpression': ['argument'],+ 'ArrayExpression': ['elements'],+ 'ArrowFunctionExpression': ['params', 'body'],+ 'AssignmentExpression': ['left', 'right'],+ 'AssignmentPattern': ['left', 'right'],+ 'BinaryExpression': ['left', 'right'],+ 'BlockStatement': ['body'],+ 'BreakStatement': ['label'],+ 'CallExpression': ['callee', 'arguments'],+ 'CatchClause': ['param', 'body'],+ 'ClassBody': ['body'],+ 'ClassDeclaration': ['id', 'superClass', 'body'],+ 'ClassExpression': ['id', 'superClass', 'body'],+ 'ConditionalExpression': ['test', 'consequent', 'alternate'],+ 'ContinueStatement': ['label'],+ 'DebuggerStatement': [],+ 'DoWhileStatement': ['body', 'test'],+ 'EmptyStatement': [],+ 'ExpressionStatement': ['expression'],+ 'ForInStatement': ['left', 'right', 'body'],+ 'ForOfStatement': ['left', 'right', 'body'],+ 'ForStatement': ['init', 'test', 'update', 'body'],+ 'FunctionDeclaration': ['id', 'params', 'body'],+ 'FunctionExpression': ['id', 'params', 'body'],+ 'Identifier': [],+ 'IfStatement': ['test', 'consequent', 'alternate'],+ 'LabeledStatement': ['label', 'body'],+ 'Literal': [],+ 'LogicalExpression': ['left', 'right'],+ 'MemberExpression': ['object', 'property'],+ 'MethodDefinition': ['key', 'value'],+ 'NewExpression': ['callee', 'arguments'],+ 'ObjectExpression': ['properties'],+ 'ObjectPattern': ['properties'],+ 'ParenthesizedExpression': ['expression'],+ 'Program': ['body'],+ 'Property': ['key', 'value'],+ 'ReturnStatement': ['argument'],+ 'SequenceExpression': ['expressions'],+ 'Super': [],+ 'SwitchCase': ['test', 'consequent'],+ 'SwitchStatement': ['discriminant', 'cases'],+ 'TaggedTemplateExpression': ['tag', 'quasi'],+ 'TemplateElement': [],+ 'TemplateLiteral': ['quasis', 'expressions'],+ 'ThisExpression': [],+ 'ThrowStatement': ['argument'],+ 'TryStatement': ['block', 'handler', 'finalizer'],+ 'UnaryExpression': ['argument'],+ 'UpdateExpression': ['argument'],+ 'VariableDeclaration': ['declarations'],+ 'VariableDeclarator': ['id', 'init'],+ 'WhileStatement': ['test', 'body'],+ 'WithStatement': ['object', 'body'],+ 'YieldExpression': ['argument']+};++module.exports = ESTreeWalker;diff --git a/utils/apply_next_version.js b/utils/apply_next_version.jsnew file mode 100644index 0000000000..a3e0f47d28--- /dev/null+++ b/utils/apply_next_version.js@@ -0,0 +1,25 @@+const path = require('path');+const fs = require('fs');+const execSync = require('child_process').execSync;++// Compare current HEAD to upstream master SHA.+// If they are not equal - refuse to publish since+// we're not tip-of-tree.+const upstream_sha = execSync(`git ls-remote https://github.com/Microsoft/playwright --tags master | cut -f1`).toString('utf8');+const current_sha = execSync(`git rev-parse HEAD`).toString('utf8');+if (upstream_sha.trim() !== current_sha.trim()) {+ console.log('REFUSING TO PUBLISH: this is not tip-of-tree!');+ process.exit(1);+ return;+}+++const package = require('../package.json');+let version = package.version;+const dashIndex = version.indexOf('-');+if (dashIndex !== -1)+ version = version.substring(0, dashIndex);+version += '-next.' + Date.now();+console.log('Setting version to ' + version);+package.version = version;+fs.writeFileSync(path.join(__dirname, '..', 'package.json'), JSON.stringify(package, undefined, 2) + '\n');diff --git a/utils/bisect.js b/utils/bisect.jsnew file mode 100755index 0000000000..ffbaab5cb2--- /dev/null+++ b/utils/bisect.js@@ -0,0 +1,204 @@+#!/usr/bin/env node+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const URL = require('url');+const debug = require('debug');+const pptr = require('..');+const browserFetcher = pptr.createBrowserFetcher();+const path = require('path');+const fs = require('fs');+const {fork} = require('child_process');++const COLOR_RESET = '\x1b[0m';+const COLOR_RED = '\x1b[31m';+const COLOR_GREEN = '\x1b[32m';+const COLOR_YELLOW = '\x1b[33m';++const argv = require('minimist')(process.argv.slice(2), {});++const help = `+Usage:+ node bisect.js --good <revision> --bad <revision> <script>++Parameters:+ --good revision that is known to be GOOD+ --bad revision that is known to be BAD+ <script> path to the script that returns non-zero code for BAD revisions and 0 for good++Example:+ node utils/bisect.js --good 577361 --bad 599821 simple.js+`;++if (argv.h || argv.help) {+ console.log(help);+ process.exit(0);+}++if (typeof argv.good !== 'number') {+ console.log(COLOR_RED + 'ERROR: expected --good argument to be a number' + COLOR_RESET);+ console.log(help);+ process.exit(1);+}++if (typeof argv.bad !== 'number') {+ console.log(COLOR_RED + 'ERROR: expected --bad argument to be a number' + COLOR_RESET);+ console.log(help);+ process.exit(1);+}++const scriptPath = path.resolve(argv._[0]);+if (!fs.existsSync(scriptPath)) {+ console.log(COLOR_RED + 'ERROR: Expected to be given a path to a script to run' + COLOR_RESET);+ console.log(help);+ process.exit(1);+}++(async(scriptPath, good, bad) => {+ const span = Math.abs(good - bad);+ console.log(`Bisecting ${COLOR_YELLOW}${span}${COLOR_RESET} revisions in ${COLOR_YELLOW}~${span.toString(2).length}${COLOR_RESET} iterations`);++ while (true) {+ const middle = Math.round((good + bad) / 2);+ const revision = await findDownloadableRevision(middle, good, bad);+ if (!revision || revision === good || revision === bad)+ break;+ let info = browserFetcher.revisionInfo(revision);+ const shouldRemove = !info.local;+ info = await downloadRevision(revision);+ const exitCode = await runScript(scriptPath, info);+ if (shouldRemove)+ await browserFetcher.remove(revision);+ let outcome;+ if (exitCode) {+ bad = revision;+ outcome = COLOR_RED + 'BAD' + COLOR_RESET;+ } else {+ good = revision;+ outcome = COLOR_GREEN + 'GOOD' + COLOR_RESET;+ }+ const span = Math.abs(good - bad);+ let fromText = '';+ let toText = '';+ if (good < bad) {+ fromText = COLOR_GREEN + good + COLOR_RESET;+ toText = COLOR_RED + bad + COLOR_RESET;+ } else {+ fromText = COLOR_RED + bad + COLOR_RESET;+ toText = COLOR_GREEN + good + COLOR_RESET;+ }+ console.log(`- ${COLOR_YELLOW}r${revision}${COLOR_RESET} was ${outcome}. Bisecting [${fromText}, ${toText}] - ${COLOR_YELLOW}${span}${COLOR_RESET} revisions and ${COLOR_YELLOW}~${span.toString(2).length}${COLOR_RESET} iterations`);+ }++ const [fromSha, toSha] = await Promise.all([+ revisionToSha(Math.min(good, bad)),+ revisionToSha(Math.max(good, bad)),+ ]);+ console.log(`RANGE: https://chromium.googlesource.com/chromium/src/+log/${fromSha}..${toSha}`);+})(scriptPath, argv.good, argv.bad);++function runScript(scriptPath, revisionInfo) {+ const log = debug('bisect:runscript');+ log('Running script');+ const child = fork(scriptPath, [], {+ stdio: ['inherit', 'inherit', 'inherit', 'ipc'],+ env: {+ ...process.env,+ PLAYWRIGHT_EXECUTABLE_PATH: revisionInfo.executablePath,+ },+ });+ return new Promise((resolve, reject) => {+ child.on('error', err => reject(err));+ child.on('exit', code => resolve(code));+ });+}++async function downloadRevision(revision) {+ const log = debug('bisect:download');+ log(`Downloading ${revision}`);+ let progressBar = null;+ let lastDownloadedBytes = 0;+ return await browserFetcher.download(revision, (downloadedBytes, totalBytes) => {+ if (!progressBar) {+ const ProgressBar = require('progress');+ progressBar = new ProgressBar(`- downloading Chromium r${revision} - ${toMegabytes(totalBytes)} [:bar] :percent :etas `, {+ complete: '=',+ incomplete: ' ',+ width: 20,+ total: totalBytes,+ });+ }+ const delta = downloadedBytes - lastDownloadedBytes;+ lastDownloadedBytes = downloadedBytes;+ progressBar.tick(delta);+ });+ function toMegabytes(bytes) {+ const mb = bytes / 1024 / 1024;+ return `${Math.round(mb * 10) / 10} Mb`;+ }+}++async function findDownloadableRevision(rev, from, to) {+ const log = debug('bisect:findrev');+ const min = Math.min(from, to);+ const max = Math.max(from, to);+ log(`Looking around ${rev} from [${min}, ${max}]`);+ if (await browserFetcher.canDownload(rev))+ return rev;+ let down = rev;+ let up = rev;+ while (min <= down || up <= max) {+ const [downOk, upOk] = await Promise.all([+ down > min ? probe(--down) : Promise.resolve(false),+ up < max ? probe(++up) : Promise.resolve(false),+ ]);+ if (downOk)+ return down;+ if (upOk)+ return up;+ }+ return null;++ async function probe(rev) {+ const result = await browserFetcher.canDownload(rev);+ log(` ${rev} - ${result ? 'OK' : 'missing'}`);+ return result;+ }+}++async function revisionToSha(revision) {+ const json = await fetchJSON('https://cr-rev.appspot.com/_ah/api/crrev/v1/redirect/' + revision);+ return json.git_sha;+}++function fetchJSON(url) {+ return new Promise((resolve, reject) => {+ const agent = url.startsWith('https://') ? require('https') : require('http');+ const options = URL.parse(url);+ options.method = 'GET';+ options.headers = {+ 'Content-Type': 'application/json'+ };+ const req = agent.request(options, function(res) {+ let result = '';+ res.setEncoding('utf8');+ res.on('data', chunk => result += chunk);+ res.on('end', () => resolve(JSON.parse(result)));+ });+ req.on('error', err => reject(err));+ req.end();+ });+}diff --git a/utils/browser/README.md b/utils/browser/README.mdnew file mode 100644index 0000000000..b26f48d8a9--- /dev/null+++ b/utils/browser/README.md@@ -0,0 +1,37 @@+# Bundling For Web Browsers++To bundle Playwright using [Browserify](http://browserify.org/):++1. Clone Playwright repository: `git clone https://github.com/Microsoft/playwright && cd playwright`+2. `npm install`+3. Run `npm run bundle`++This will create `./utils/browser/playwright-web.js` file that contains Playwright bundle.++You can use it later on in your web page to drive+another browser instance through its WS Endpoint:++```html+<script src='./playwright-web.js'></script>+<script>+ const playwright = require('playwright');+ const browser = await playwright.connect({+ browserWSEndpoint: '<another-browser-ws-endpont>'+ });+ // ... drive automation ...+</script>+```++See our [playwright-web tests](https://github.com/Microsoft/playwright/blob/master/utils/browser/test.js)+for details.++### Running inside Chrome Extension++You might want to enable `unsafe-eval` inside the extension by adding the following+to your `manifest.json` file:++```+"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"+```++Please see discussion in https://github.com/GoogleChrome/puppeteer/issues/3455.diff --git a/utils/browser/WebSocket.js b/utils/browser/WebSocket.jsnew file mode 100644index 0000000000..a30d920fbf--- /dev/null+++ b/utils/browser/WebSocket.js@@ -0,0 +1 @@+module.exports = window.WebSocket;diff --git a/utils/browser/test.js b/utils/browser/test.jsnew file mode 100644index 0000000000..ba5044f4ae--- /dev/null+++ b/utils/browser/test.js@@ -0,0 +1,98 @@+const path = require('path');+const fs = require('fs');+const playwright = require('../..');+const {TestServer} = require('../testserver/');+const {TestRunner, Reporter, Matchers} = require('../testrunner/');++const playwrightWebPath = path.join(__dirname, 'playwright-web.js');+if (!fs.existsSync(playwrightWebPath))+ throw new Error(`playwright-web is not built; run "npm run bundle"`);+const playwrightWeb = fs.readFileSync(playwrightWebPath, 'utf8');++const testRunner = new TestRunner();+const {describe, fdescribe, xdescribe} = testRunner;+const {it, xit, fit} = testRunner;+const {afterAll, beforeAll, afterEach, beforeEach} = testRunner;+const {expect} = new Matchers();++beforeAll(async state => {+ const assetsPath = path.join(__dirname, '..', '..', 'test', 'assets');+ const port = 8998;+ state.server = await TestServer.create(assetsPath, port);+ state.serverConfig = {+ PREFIX: `http://localhost:${port}`,+ EMPTY_PAGE: `http://localhost:${port}/empty.html`,+ };+ state.browser = await playwright.launch();+});++afterAll(async state => {+ await Promise.all([+ state.server.stop(),+ state.browser.close()+ ]);+ state.browser = null;+ state.server = null;+});++beforeEach(async state => {+ state.page = await state.browser.newPage();+ await state.page.evaluateOnNewDocument(playwrightWeb);+ await state.page.addScriptTag({+ content: playwrightWeb + '\n//# sourceURL=playwright-web.js'+ });+});++afterEach(async state => {+ await state.page.close();+ state.page = null;+});++describe('Playwright-Web', () => {+ it('should work over web socket', async({page, serverConfig}) => {+ const browser2 = await playwright.launch();+ // Use in-page playwright to create a new page and navigate it to the EMPTY_PAGE+ await page.evaluate(async(browserWSEndpoint, serverConfig) => {+ const playwright = require('playwright');+ const browser = await playwright.connect({browserWSEndpoint});+ const page = await browser.newPage();+ await page.goto(serverConfig.EMPTY_PAGE);+ }, browser2.wsEndpoint(), serverConfig);+ const pageURLs = (await browser2.pages()).map(page => page.url()).sort();+ expect(pageURLs).toEqual([+ 'about:blank',+ serverConfig.EMPTY_PAGE+ ]);+ await browser2.close();+ });+ it('should work over exposed DevTools protocol', async({browser, page, serverConfig}) => {+ // Expose devtools protocol binding into page.+ const session = await browser.target().createCDPSession();+ const pageInfo = (await session.send('Target.getTargets')).targetInfos.find(info => info.attached);+ await session.send('Target.exposeDevToolsProtocol', {targetId: pageInfo.targetId});+ await session.detach();++ // Use in-page playwright to create a new page and navigate it to the EMPTY_PAGE+ await page.evaluate(async serverConfig => {+ const playwright = require('playwright');+ window.cdp.close = () => {};+ const browser = await playwright.connect({transport: window.cdp});+ const page = await browser.newPage();+ await page.goto(serverConfig.EMPTY_PAGE);+ }, serverConfig);+ const pageURLs = (await browser.pages()).map(page => page.url()).sort();+ expect(pageURLs).toEqual([+ 'about:blank',+ 'about:blank',+ serverConfig.EMPTY_PAGE+ ]);+ });+});++if (process.env.CI && testRunner.hasFocusedTestsOrSuites()) {+ console.error('ERROR: "focused" tests/suites are prohibitted on bots. Remove any "fit"/"fdescribe" declarations.');+ process.exit(1);+}++new Reporter(testRunner);+testRunner.run();diff --git a/utils/check_availability.js b/utils/check_availability.jsnew file mode 100755index 0000000000..7073cbf2d8--- /dev/null+++ b/utils/check_availability.js@@ -0,0 +1,174 @@+#!/usr/bin/env node+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const assert = require('assert');+const playwright = require('..');+const https = require('https');+const SUPPORTER_PLATFORMS = ['linux', 'mac', 'win32', 'win64'];++const fetchers = SUPPORTER_PLATFORMS.map(platform => playwright.createBrowserFetcher({platform}));++const colors = {+ reset: '\x1b[0m',+ red: '\x1b[31m',+ green: '\x1b[32m',+ yellow: '\x1b[33m'+};++class Table {+ /**+ * @param {!Array<number>} columnWidths+ */+ constructor(columnWidths) {+ this.widths = columnWidths;+ }++ /**+ * @param {!Array<string>} values+ */+ drawRow(values) {+ assert(values.length === this.widths.length);+ let row = '';+ for (let i = 0; i < values.length; ++i)+ row += padCenter(values[i], this.widths[i]);+ console.log(row);+ }+}++if (process.argv.length === 2) {+ checkOmahaProxyAvailability();+ return;+}+if (process.argv.length !== 4) {+ console.log(`+ Usage: node check_revisions.js [fromRevision] [toRevision]++This script checks availability of different prebuild chromium revisions.+Running command without arguments will check against omahaproxy revisions.`);+ return;+}++const fromRevision = parseInt(process.argv[2], 10);+const toRevision = parseInt(process.argv[3], 10);+checkRangeAvailability(fromRevision, toRevision, false /* stopWhenAllAvailable */);++async function checkOmahaProxyAvailability() {+ const lastchanged = (await Promise.all([+ fetch('https://storage.googleapis.com/chromium-browser-snapshots/Mac/LAST_CHANGE'),+ fetch('https://storage.googleapis.com/chromium-browser-snapshots/Linux_x64/LAST_CHANGE'),+ fetch('https://storage.googleapis.com/chromium-browser-snapshots/Win/LAST_CHANGE'),+ fetch('https://storage.googleapis.com/chromium-browser-snapshots/Win_x64/LAST_CHANGE'),+ ])).map(s => parseInt(s, 10));+ const from = Math.max(...lastchanged);+ checkRangeAvailability(from, 0, true /* stopWhenAllAvailable */);+}++/**+ * @param {number} fromRevision+ * @param {number} toRevision+ * @param {boolean} stopWhenAllAvailable+ */+async function checkRangeAvailability(fromRevision, toRevision, stopWhenAllAvailable) {+ const table = new Table([10, 7, 7, 7, 7]);+ table.drawRow([''].concat(SUPPORTER_PLATFORMS));+ const inc = fromRevision < toRevision ? 1 : -1;+ for (let revision = fromRevision; revision !== toRevision; revision += inc) {+ const allAvailable = await checkAndDrawRevisionAvailability(table, '', revision);+ if (allAvailable && stopWhenAllAvailable)+ break;+ }+}++/**+ * @param {!Table} table+ * @param {string} name+ * @param {number} revision+ * @return {boolean}+ */+async function checkAndDrawRevisionAvailability(table, name, revision) {+ const promises = fetchers.map(fetcher => fetcher.canDownload(revision));+ const availability = await Promise.all(promises);+ const allAvailable = availability.every(e => !!e);+ const values = [name + ' ' + (allAvailable ? colors.green + revision + colors.reset : revision)];+ for (let i = 0; i < availability.length; ++i) {+ const decoration = availability[i] ? '+' : '-';+ const color = availability[i] ? colors.green : colors.red;+ values.push(color + decoration + colors.reset);+ }+ table.drawRow(values);+ return allAvailable;+}++/**+ * @param {string} url+ * @return {!Promise<?string>}+ */+function fetch(url) {+ let resolve;+ const promise = new Promise(x => resolve = x);+ https.get(url, response => {+ if (response.statusCode !== 200) {+ resolve(null);+ return;+ }+ let body = '';+ response.on('data', function(chunk){+ body += chunk;+ });+ response.on('end', function(){+ resolve(body);+ });+ }).on('error', function(e){+ console.error('Error fetching json: ' + e);+ resolve(null);+ });+ return promise;+}++/**+ * @param {number} size+ * @return {string}+ */+function spaceString(size) {+ return new Array(size).fill(' ').join('');+}++/**+ * @param {string} text+ * @return {string}+ */+function filterOutColors(text) {+ for (const colorName in colors) {+ const color = colors[colorName];+ text = text.replace(color, '');+ }+ return text;+}++/**+ * @param {string} text+ * @param {number} length+ * @return {string}+ */+function padCenter(text, length) {+ const printableCharacters = filterOutColors(text);+ if (printableCharacters.length >= length)+ return text;+ const left = Math.floor((length - printableCharacters.length) / 2);+ const right = Math.ceil((length - printableCharacters.length) / 2);+ return spaceString(left) + text + spaceString(right);+}diff --git a/utils/doclint/.gitignore b/utils/doclint/.gitignorenew file mode 100644index 0000000000..ea1472ec1f--- /dev/null+++ b/utils/doclint/.gitignore@@ -0,0 +1 @@+output/diff --git a/utils/doclint/Message.js b/utils/doclint/Message.jsnew file mode 100644index 0000000000..cb7d15aeca--- /dev/null+++ b/utils/doclint/Message.js@@ -0,0 +1,44 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++class Message {+ /**+ * @param {string} type+ * @param {string} text+ */+ constructor(type, text) {+ this.type = type;+ this.text = text;+ }++ /**+ * @param {string} text+ * @return {!Message}+ */+ static error(text) {+ return new Message('error', text);+ }++ /**+ * @param {string} text+ * @return {!Message}+ */+ static warning(text) {+ return new Message('warning', text);+ }+}++module.exports = Message;diff --git a/utils/doclint/README.md b/utils/doclint/README.mdnew file mode 100644index 0000000000..3187990b8b--- /dev/null+++ b/utils/doclint/README.md@@ -0,0 +1,30 @@+# DocLint++**Doclint** is a small program that lints Playwright's documentation against+Playwright's source code.++Doclint works in a few steps:++1. Read sources in `lib/` folder, parse AST trees and extract public API+2. Read sources in `docs/` folder, render markdown to HTML, use playwright to traverse the HTML+ and extract described API+3. Compare one API to another++Doclint is also responsible for general markdown checks, most notably for the table of contents+relevancy.++## Running++```bash+npm run doc+```++## Tests++Doclint has its own set of jasmine tests, located at `utils/doclint/test` folder.++To execute tests, run:++```bash+npm run test-doclint+```diff --git a/utils/doclint/Source.js b/utils/doclint/Source.jsnew file mode 100644index 0000000000..5db855dfb1--- /dev/null+++ b/utils/doclint/Source.js@@ -0,0 +1,125 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const path = require('path');+const util = require('util');+const fs = require('fs');++const readFileAsync = util.promisify(fs.readFile);+const statAsync = util.promisify(fs.stat);+const readdirAsync = util.promisify(fs.readdir);+const writeFileAsync = util.promisify(fs.writeFile);++const PROJECT_DIR = path.join(__dirname, '..', '..');++async function recursiveReadDir(dirPath) {+ const files = [];+ for (const file of await readdirAsync(dirPath)) {+ const fullPath = path.join(dirPath, file);+ if ((await statAsync(fullPath)).isDirectory())+ files.push(...await recursiveReadDir(fullPath))+ else+ files.push(fullPath);+ }+ return files;+}++class Source {+ /**+ * @param {string} filePath+ * @param {string} text+ */+ constructor(filePath, text) {+ this._filePath = filePath;+ this._projectPath = path.relative(PROJECT_DIR, filePath);+ this._name = path.basename(filePath);+ this._text = text;+ this._hasUpdatedText = false;+ }++ /**+ * @return {string}+ */+ filePath() {+ return this._filePath;+ }++ /**+ * @return {string}+ */+ projectPath() {+ return this._projectPath;+ }++ /**+ * @return {string}+ */+ name() {+ return this._name;+ }++ /**+ * @param {string} text+ * @return {boolean}+ */+ setText(text) {+ if (text === this._text)+ return false;+ this._hasUpdatedText = true;+ this._text = text;+ return true;+ }++ /**+ * @return {string}+ */+ text() {+ return this._text;+ }++ /**+ * @return {boolean}+ */+ hasUpdatedText() {+ return this._hasUpdatedText;+ }++ async save() {+ await writeFileAsync(this.filePath(), this.text());+ }++ /**+ * @param {string} filePath+ * @return {!Promise<Source>}+ */+ static async readFile(filePath) {+ filePath = path.resolve(filePath);+ const text = await readFileAsync(filePath, {encoding: 'utf8'});+ return new Source(filePath, text);+ }++ /**+ * @param {string} dirPath+ * @param {string=} extension+ * @return {!Promise<!Array<!Source>>}+ */+ static async readdir(dirPath, extension = '') {+ const filePaths = (await recursiveReadDir(dirPath)).filter(fileName => fileName.endsWith(extension));+ return Promise.all(filePaths.map(filePath => Source.readFile(filePath)));+ }+}+module.exports = Source;+diff --git a/utils/doclint/check_public_api/Documentation.js b/utils/doclint/check_public_api/Documentation.jsnew file mode 100644index 0000000000..2683972919--- /dev/null+++ b/utils/doclint/check_public_api/Documentation.js@@ -0,0 +1,137 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++class Documentation {+ /**+ * @param {!Array<!Documentation.Class>} classesArray+ */+ constructor(classesArray) {+ this.classesArray = classesArray;+ /** @type {!Map<string, !Documentation.Class>} */+ this.classes = new Map();+ for (const cls of classesArray)+ this.classes.set(cls.name, cls);+ }+}++Documentation.Class = class {+ /**+ * @param {string} name+ * @param {!Array<!Documentation.Member>} membersArray+ * @param {?string=} extendsName+ * @param {string=} comment+ */+ constructor(name, membersArray, extendsName = null, comment = '') {+ this.name = name;+ this.membersArray = membersArray;+ /** @type {!Map<string, !Documentation.Member>} */+ this.members = new Map();+ /** @type {!Map<string, !Documentation.Member>} */+ this.properties = new Map();+ /** @type {!Array<!Documentation.Member>} */+ this.propertiesArray = [];+ /** @type {!Map<string, !Documentation.Member>} */+ this.methods = new Map();+ /** @type {!Array<!Documentation.Member>} */+ this.methodsArray = [];+ /** @type {!Map<string, !Documentation.Member>} */+ this.events = new Map();+ /** @type {!Array<!Documentation.Member>} */+ this.eventsArray = [];+ this.comment = comment;+ this.extends = extendsName;+ for (const member of membersArray) {+ this.members.set(member.name, member);+ if (member.kind === 'method') {+ this.methods.set(member.name, member);+ this.methodsArray.push(member);+ } else if (member.kind === 'property') {+ this.properties.set(member.name, member);+ this.propertiesArray.push(member);+ } else if (member.kind === 'event') {+ this.events.set(member.name, member);+ this.eventsArray.push(member);+ }+ }+ }+};++Documentation.Member = class {+ /**+ * @param {string} kind+ * @param {string} name+ * @param {?Documentation.Type} type+ * @param {!Array<!Documentation.Member>} argsArray+ */+ constructor(kind, name, type, argsArray, comment = '', returnComment = '', required = true) {+ this.kind = kind;+ this.name = name;+ this.type = type;+ this.comment = comment;+ this.returnComment = returnComment;+ this.argsArray = argsArray;+ this.required = required;+ /** @type {!Map<string, !Documentation.Member>} */+ this.args = new Map();+ for (const arg of argsArray)+ this.args.set(arg.name, arg);+ }++ /**+ * @param {string} name+ * @param {!Array<!Documentation.Member>} argsArray+ * @param {?Documentation.Type} returnType+ * @return {!Documentation.Member}+ */+ static createMethod(name, argsArray, returnType, returnComment, comment) {+ return new Documentation.Member('method', name, returnType, argsArray, comment, returnComment);+ }++ /**+ * @param {string} name+ * @param {!Documentation.Type} type+ * @param {string=} comment+ * @param {boolean=} required+ * @return {!Documentation.Member}+ */+ static createProperty(name, type, comment, required) {+ return new Documentation.Member('property', name, type, [], comment, undefined, required);+ }++ /**+ * @param {string} name+ * @param {?Documentation.Type=} type+ * @param {string=} comment+ * @return {!Documentation.Member}+ */+ static createEvent(name, type = null, comment) {+ return new Documentation.Member('event', name, type, [], comment);+ }+};++Documentation.Type = class {+ /**+ * @param {string} name+ * @param {!Array<!Documentation.Member>=} properties+ */+ constructor(name, properties = []) {+ this.name = name;+ this.properties = properties;+ }+};++module.exports = Documentation;+diff --git a/utils/doclint/check_public_api/JSBuilder.js b/utils/doclint/check_public_api/JSBuilder.jsnew file mode 100644index 0000000000..d524fb3141--- /dev/null+++ b/utils/doclint/check_public_api/JSBuilder.js@@ -0,0 +1,232 @@+/**+ * Copyright 2019 Google Inc. All rights reserved.+ * Modifications copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const ts = require('typescript');+const path = require('path');+const Documentation = require('./Documentation');+const EventEmitter = require('events');+module.exports = checkSources;++/**+ * @param {!Array<!import('../Source')>} sources+ */+function checkSources(sources) {+ // special treatment for Events.js+ const classEvents = new Map();+ const eventsSource = sources.find(source => source.name().startsWith('Events.'));+ if (eventsSource) {+ const {Events} = eventsSource.filePath().endsWith('.js') ? require(eventsSource.filePath()) : require(path.join(eventsSource.filePath(), '..', '..', 'lib', 'Events.js'));+ for (const [className, events] of Object.entries(Events))+ classEvents.set(className, Array.from(Object.values(events)).filter(e => typeof e === 'string').map(e => Documentation.Member.createEvent(e)));+ }++ const excludeClasses = new Set([]);+ const program = ts.createProgram({+ options: {+ allowJs: true,+ target: ts.ScriptTarget.ESNext,+ },+ rootNames: sources.map(source => source.filePath())+ });+ const checker = program.getTypeChecker();+ const sourceFiles = program.getSourceFiles();+ /** @type {!Array<!Documentation.Class>} */+ const classes = [];+ /** @type {!Map<string, string>} */+ const inheritance = new Map();+ sourceFiles.filter(x => !x.fileName.includes('node_modules')).map(x => visit(x));+ const errors = [];+ const documentation = new Documentation(recreateClassesWithInheritance(classes, inheritance));++ return {errors, documentation};++ /**+ * @param {!Array<!Documentation.Class>} classes+ * @param {!Map<string, string>} inheritance+ * @return {!Array<!Documentation.Class>}+ */+ function recreateClassesWithInheritance(classes, inheritance) {+ const classesByName = new Map(classes.map(cls => [cls.name, cls]));+ return classes.map(cls => {+ const membersMap = new Map();+ for (let wp = cls; wp; wp = classesByName.get(inheritance.get(wp.name))) {+ for (const member of wp.membersArray) {+ // Member was overridden.+ const memberId = member.kind + ':' + member.name;+ if (membersMap.has(memberId))+ continue;+ membersMap.set(memberId, member);+ }+ }+ return new Documentation.Class(cls.name, Array.from(membersMap.values()));+ });+ }++ /**+ * @param {!ts.Node} node+ */+ function visit(node) {+ if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) {+ const symbol = node.name ? checker.getSymbolAtLocation(node.name) : node.symbol;+ let className = symbol.getName();++ if (className === '__class') {+ let parent = node;+ while (parent.parent)+ parent = parent.parent;+ className = path.basename(parent.fileName, '.js');+ }+ if (className && !excludeClasses.has(className)) {+ classes.push(serializeClass(className, symbol, node));+ const parentClassName = parentClass(node);+ if (parentClassName)+ inheritance.set(className, parentClassName);+ excludeClasses.add(className);+ }+ }+ ts.forEachChild(node, visit);+ }++ function parentClass(classNode) {+ for (const herigateClause of classNode.heritageClauses || []) {+ for (const heritageType of herigateClause.types) {+ const parentClassName = heritageType.expression.escapedText;+ return parentClassName;+ }+ }+ return null;++ }++ function serializeSymbol(symbol, circular = []) {+ const type = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);+ const name = symbol.getName();+ if (symbol.valueDeclaration.dotDotDotToken) {+ const innerType = serializeType(type.typeArguments[0], circular);+ innerType.name = '...' + innerType.name;+ return Documentation.Member.createProperty('...' + name, innerType);+ }+ return Documentation.Member.createProperty(name, serializeType(type, circular));+ }++ /**+ * @param {!ts.ObjectType} type+ */+ function isRegularObject(type) {+ if (type.isIntersection())+ return true;+ if (!type.objectFlags)+ return false;+ if (!('aliasSymbol' in type))+ return false;+ if (type.getConstructSignatures().length)+ return false;+ if (type.getCallSignatures().length)+ return false;+ if (type.isUnion())+ return false;+ return true;+ }++ /**+ * @param {!ts.Type} type+ * @return {!Documentation.Type}+ */+ function serializeType(type, circular = []) {+ let typeName = checker.typeToString(type);+ if (typeName === 'any' || typeName === '{ [x: string]: string; }')+ typeName = 'Object';+ const nextCircular = [typeName].concat(circular);++ if (isRegularObject(type)) {+ let properties = undefined;+ if (!circular.includes(typeName))+ properties = type.getProperties().map(property => serializeSymbol(property, nextCircular));+ return new Documentation.Type('Object', properties);+ }+ if (type.isUnion() && (typeName.includes('|') || type.types.every(type => type.isStringLiteral()))) {+ const types = type.types.map(type => serializeType(type, circular));+ const name = types.map(type => type.name).join('|');+ const properties = [].concat(...types.map(type => type.properties));+ return new Documentation.Type(name.replace(/false\|true/g, 'boolean'), properties);+ }+ if (type.typeArguments) {+ const properties = [];+ const innerTypeNames = [];+ for (const typeArgument of type.typeArguments) {+ const innerType = serializeType(typeArgument, nextCircular);+ if (innerType.properties)+ properties.push(...innerType.properties);+ innerTypeNames.push(innerType.name);+ }+ if (innerTypeNames.length === 1 && innerTypeNames[0] === 'void')+ return new Documentation.Type(type.symbol.name);+ return new Documentation.Type(`${type.symbol.name}<${innerTypeNames.join(', ')}>`, properties);+ }+ return new Documentation.Type(typeName, []);+ }++ /**+ * @param {string} className+ * @param {!ts.Symbol} symbol+ * @return {}+ */+ function serializeClass(className, symbol, node) {+ /** @type {!Array<!Documentation.Member>} */+ const members = classEvents.get(className) || [];+ for (const [name, member] of symbol.members || []) {+ if (name.startsWith('_'))+ continue;+ if (EventEmitter.prototype.hasOwnProperty(name))+ continue;+ if (className === 'CDPSession' && name === 'send') {+ // special case CDPSession.send, which has a stricter private API than the public API+ members.push(Documentation.Member.createMethod('send', [+ Documentation.Member.createProperty('method', new Documentation.Type('string')),+ Documentation.Member.createProperty('params', new Documentation.Type('Object')),+ ], new Documentation.Type('Promise<Object>')));+ continue;+ }+ const memberType = checker.getTypeOfSymbolAtLocation(member, member.valueDeclaration);+ const signature = memberType.getCallSignatures()[0];+ if (signature)+ members.push(serializeSignature(name, signature));+ else+ members.push(serializeProperty(name, memberType));+ }++ return new Documentation.Class(className, members);+ }++ /**+ * @param {string} name+ * @param {!ts.Signature} signature+ */+ function serializeSignature(name, signature) {+ const parameters = signature.parameters.map(s => serializeSymbol(s));+ const returnType = serializeType(signature.getReturnType());+ return Documentation.Member.createMethod(name, parameters, returnType.name !== 'void' ? returnType : null);+ }++ /**+ * @param {string} name+ * @param {!ts.Type} type+ */+ function serializeProperty(name, type) {+ return Documentation.Member.createProperty(name, serializeType(type));+ }+}diff --git a/utils/doclint/check_public_api/MDBuilder.js b/utils/doclint/check_public_api/MDBuilder.jsnew file mode 100644index 0000000000..bc3776aed5--- /dev/null+++ b/utils/doclint/check_public_api/MDBuilder.js@@ -0,0 +1,302 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const Documentation = require('./Documentation');+const commonmark = require('commonmark');++class MDOutline {+ /**+ * @param {!Page} page+ * @param {string} text+ * @return {!MDOutline}+ */+ static async create(page, text) {+ // Render markdown as HTML.+ const reader = new commonmark.Parser();+ const parsed = reader.parse(text);+ const writer = new commonmark.HtmlRenderer();+ const html = writer.render(parsed);++ page.on('console', msg => {+ console.log(msg.text());+ });+ // Extract headings.+ await page.setContent(html);+ const {classes, errors} = await page.evaluate(() => {+ const classes = [];+ const errors = [];+ const headers = document.body.querySelectorAll('h3');+ for (let i = 0; i < headers.length; i++) {+ const fragment = extractSiblingsIntoFragment(headers[i], headers[i + 1]);+ classes.push(parseClass(fragment));+ }+ return {classes, errors};++ /**+ * @param {HTMLLIElement} element+ */+ function parseProperty(element) {+ const clone = element.cloneNode(true);+ const ul = clone.querySelector(':scope > ul');+ const str = parseComment(extractSiblingsIntoFragment(clone.firstChild, ul));+ const name = str.substring(0, str.indexOf('<')).replace(/\`/g, '').trim();+ const type = findType(str);+ const properties = [];+ const comment = str.substring(str.indexOf('<') + type.length + 2).trim();+ // Strings have enum values instead of properties+ if (!type.includes('string')) {+ for (const childElement of element.querySelectorAll(':scope > ul > li')) {+ const property = parseProperty(childElement);+ property.required = property.comment.includes('***required***');+ properties.push(property);+ }+ }+ return {+ name,+ type,+ comment,+ properties+ };+ }++ /**+ * @param {string} str+ * @return {string}+ */+ function findType(str) {+ const start = str.indexOf('<') + 1;+ let count = 1;+ for (let i = start; i < str.length; i++) {+ if (str[i] === '<') count++;+ if (str[i] === '>') count--;+ if (!count)+ return str.substring(start, i);+ }+ return 'unknown';+ }++ /**+ * @param {DocumentFragment} content+ */+ function parseClass(content) {+ const members = [];+ const headers = content.querySelectorAll('h4');+ const name = content.firstChild.textContent;+ let extendsName = null;+ let commentStart = content.firstChild.nextSibling;+ const extendsElement = content.querySelector('ul');+ if (extendsElement && extendsElement.textContent.trim().startsWith('extends:')) {+ commentStart = extendsElement.nextSibling;+ extendsName = extendsElement.querySelector('a').textContent;+ }+ const comment = parseComment(extractSiblingsIntoFragment(commentStart, headers[0]));+ for (let i = 0; i < headers.length; i++) {+ const fragment = extractSiblingsIntoFragment(headers[i], headers[i + 1]);+ members.push(parseMember(fragment));+ }+ return {+ name,+ comment,+ extendsName,+ members+ };+ }++ /**+ * @param {Node} content+ */+ function parseComment(content) {+ for (const code of content.querySelectorAll('pre > code'))+ code.replaceWith('```' + code.className.substring('language-'.length) + '\n' + code.textContent + '```');+ for (const code of content.querySelectorAll('code'))+ code.replaceWith('`' + code.textContent + '`');+ for (const strong of content.querySelectorAll('strong'))+ strong.replaceWith('**' + parseComment(strong) + '**');+ return content.textContent.trim();+ }++ /**+ * @param {string} name+ * @param {DocumentFragment} content+ */+ function parseMember(content) {+ const name = content.firstChild.textContent;+ const args = [];+ let returnType = null;++ const paramRegex = /^\w+\.[\w$]+\((.*)\)$/;+ const matches = paramRegex.exec(name) || ['', ''];+ const parameters = matches[1];+ const optionalStartIndex = parameters.indexOf('[');+ const optinalParamsStr = optionalStartIndex !== -1 ? parameters.substring(optionalStartIndex).replace(/[\[\]]/g, '') : '';+ const optionalparams = new Set(optinalParamsStr.split(',').filter(x => x).map(x => x.trim()));+ const ul = content.querySelector('ul');+ for (const element of content.querySelectorAll('h4 + ul > li')) {+ if (element.matches('li') && element.textContent.trim().startsWith('<')) {+ returnType = parseProperty(element);+ } else if (element.matches('li') && element.firstChild.matches && element.firstChild.matches('code')) {+ const property = parseProperty(element);+ property.required = !optionalparams.has(property.name);+ args.push(property);+ } else if (element.matches('li') && element.firstChild.nodeType === Element.TEXT_NODE && element.firstChild.textContent.toLowerCase().startsWith('return')) {+ returnType = parseProperty(element);+ const expectedText = 'returns: ';+ let actualText = element.firstChild.textContent;+ let angleIndex = actualText.indexOf('<');+ let spaceIndex = actualText.indexOf(' ');+ angleIndex = angleIndex === -1 ? actualText.length : angleIndex;+ spaceIndex = spaceIndex === -1 ? actualText.length : spaceIndex + 1;+ actualText = actualText.substring(0, Math.min(angleIndex, spaceIndex));+ if (actualText !== expectedText)+ errors.push(`${name} has mistyped 'return' type declaration: expected exactly '${expectedText}', found '${actualText}'.`);+ }+ }+ const comment = parseComment(extractSiblingsIntoFragment(ul ? ul.nextSibling : content));+ return {+ name,+ args,+ returnType,+ comment+ };+ }++ /**+ * @param {!Node} fromInclusive+ * @param {!Node} toExclusive+ * @return {!DocumentFragment}+ */+ function extractSiblingsIntoFragment(fromInclusive, toExclusive) {+ const fragment = document.createDocumentFragment();+ let node = fromInclusive;+ while (node && node !== toExclusive) {+ const next = node.nextSibling;+ fragment.appendChild(node);+ node = next;+ }+ return fragment;+ }+ });+ return new MDOutline(classes, errors);+ }++ constructor(classes, errors) {+ this.classes = [];+ this.errors = errors;+ const classHeading = /^class: (\w+)$/;+ const constructorRegex = /^new (\w+)\((.*)\)$/;+ const methodRegex = /^(\w+)\.([\w$]+)\((.*)\)$/;+ const propertyRegex = /^(\w+)\.(\w+)$/;+ const eventRegex = /^event: '(\w+)'$/;+ let currentClassName = null;+ let currentClassMembers = [];+ let currentClassComment = '';+ let currentClassExtends = null;+ for (const cls of classes) {+ const match = cls.name.match(classHeading);+ if (!match)+ continue;+ currentClassName = match[1];+ currentClassComment = cls.comment;+ currentClassExtends = cls.extendsName;+ for (const member of cls.members) {+ if (constructorRegex.test(member.name)) {+ const match = member.name.match(constructorRegex);+ handleMethod.call(this, member, match[1], 'constructor', match[2]);+ } else if (methodRegex.test(member.name)) {+ const match = member.name.match(methodRegex);+ handleMethod.call(this, member, match[1], match[2], match[3]);+ } else if (propertyRegex.test(member.name)) {+ const match = member.name.match(propertyRegex);+ handleProperty.call(this, member, match[1], match[2]);+ } else if (eventRegex.test(member.name)) {+ const match = member.name.match(eventRegex);+ handleEvent.call(this, member, match[1]);+ }+ }+ flushClassIfNeeded.call(this);+ }++ function handleMethod(member, className, methodName, parameters) {+ if (!currentClassName || !className || !methodName || className.toLowerCase() !== currentClassName.toLowerCase()) {+ this.errors.push(`Failed to process header as method: ${member.name}`);+ return;+ }+ parameters = parameters.trim().replace(/[\[\]]/g, '');+ if (parameters !== member.args.map(arg => arg.name).join(', '))+ this.errors.push(`Heading arguments for "${member.name}" do not match described ones, i.e. "${parameters}" != "${member.args.map(a => a.name).join(', ')}"`);+ const args = member.args.map(createPropertyFromJSON);+ let returnType = null;+ let returnComment = '';+ if (member.returnType) {+ const returnProperty = createPropertyFromJSON(member.returnType);+ returnType = returnProperty.type;+ returnComment = returnProperty.comment;+ }+ const method = Documentation.Member.createMethod(methodName, args, returnType, returnComment, member.comment);+ currentClassMembers.push(method);+ }++ function createPropertyFromJSON(payload) {+ const type = new Documentation.Type(payload.type, payload.properties.map(createPropertyFromJSON));+ const required = payload.required;+ return Documentation.Member.createProperty(payload.name, type, payload.comment, required);+ }++ function handleProperty(member, className, propertyName) {+ if (!currentClassName || !className || !propertyName || className.toLowerCase() !== currentClassName.toLowerCase()) {+ this.errors.push(`Failed to process header as property: ${member.name}`);+ return;+ }+ const type = member.returnType ? member.returnType.type : null;+ const properties = member.returnType ? member.returnType.properties : [];+ currentClassMembers.push(createPropertyFromJSON({type, name: propertyName, properties, comment: member.comment}));+ }++ function handleEvent(member, eventName) {+ if (!currentClassName || !eventName) {+ this.errors.push(`Failed to process header as event: ${member.name}`);+ return;+ }+ currentClassMembers.push(Documentation.Member.createEvent(eventName, member.returnType && createPropertyFromJSON(member.returnType).type, member.comment));+ }++ function flushClassIfNeeded() {+ if (currentClassName === null)+ return;+ this.classes.push(new Documentation.Class(currentClassName, currentClassMembers, currentClassExtends, currentClassComment));+ currentClassName = null;+ currentClassMembers = [];+ }+ }+}++/**+ * @param {!Page} page+ * @param {!Array<!Source>} sources+ * @return {!Promise<{documentation: !Documentation, errors: !Array<string>}>}+ */+module.exports = async function(page, sources) {+ const classes = [];+ const errors = [];+ for (const source of sources) {+ const outline = await MDOutline.create(page, source.text());+ classes.push(...outline.classes);+ errors.push(...outline.errors);+ }+ const documentation = new Documentation(classes);+ return { documentation, errors };+};+diff --git a/utils/doclint/check_public_api/index.js b/utils/doclint/check_public_api/index.jsnew file mode 100644index 0000000000..38054e2856--- /dev/null+++ b/utils/doclint/check_public_api/index.js@@ -0,0 +1,339 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const jsBuilder = require('./JSBuilder');+const mdBuilder = require('./MDBuilder');+const Documentation = require('./Documentation');+const Message = require('../Message');+const path = require('path');++const EXCLUDE_PROPERTIES = new Set([+ 'Browser.create',+ 'Headers.fromPayload',+ 'Page.create',+ 'JSHandle.toString',+ 'TimeoutError.name',+]);++/**+ * @param {!Page} page+ * @param {!Array<!Source>} mdSources+ * @return {!Promise<!Array<!Message>>}+ */+module.exports = async function lint(page, mdSources, jsSources) {+ const mdResult = await mdBuilder(page, mdSources);+ const jsResult = await jsBuilder(jsSources);+ const jsDocumentation = filterJSDocumentation(jsSources, jsResult.documentation);+ const mdDocumentation = mdResult.documentation;++ const jsErrors = jsResult.errors;+ jsErrors.push(...checkDuplicates(jsDocumentation));++ const mdErrors = mdResult.errors;+ mdErrors.push(...compareDocumentations(mdDocumentation, jsDocumentation));+ mdErrors.push(...checkDuplicates(mdDocumentation));+ mdErrors.push(...checkSorting(mdDocumentation));++ // Push all errors with proper prefixes+ const errors = jsErrors.map(error => '[JavaScript] ' + error);+ errors.push(...mdErrors.map(error => '[MarkDown] ' + error));+ return errors.map(error => Message.error(error));+};++/**+ * @param {!Documentation} doc+ * @return {!Array<string>}+ */+function checkSorting(doc) {+ const errors = [];+ for (const cls of doc.classesArray) {+ const members = cls.membersArray;++ // Events should go first.+ let eventIndex = 0;+ for (; eventIndex < members.length && members[eventIndex].kind === 'event'; ++eventIndex);+ for (; eventIndex < members.length && members[eventIndex].kind !== 'event'; ++eventIndex);+ if (eventIndex < members.length)+ errors.push(`Events should go first. Event '${members[eventIndex].name}' in class ${cls.name} breaks order`);++ // Constructor should be right after events and before all other members.+ const constructorIndex = members.findIndex(member => member.kind === 'method' && member.name === 'constructor');+ if (constructorIndex > 0 && members[constructorIndex - 1].kind !== 'event')+ errors.push(`Constructor of ${cls.name} should go before other methods`);++ // Events should be sorted alphabetically.+ for (let i = 0; i < members.length - 1; ++i) {+ const member1 = cls.membersArray[i];+ const member2 = cls.membersArray[i + 1];+ if (member1.kind !== 'event' || member2.kind !== 'event')+ continue;+ if (member1.name > member2.name)+ errors.push(`Event '${member1.name}' in class ${cls.name} breaks alphabetic ordering of events`);+ }++ // All other members should be sorted alphabetically.+ for (let i = 0; i < members.length - 1; ++i) {+ const member1 = cls.membersArray[i];+ const member2 = cls.membersArray[i + 1];+ if (member1.kind === 'event' || member2.kind === 'event')+ continue;+ if (member1.kind === 'method' && member1.name === 'constructor')+ continue;+ if (member1.name > member2.name) {+ let memberName1 = `${cls.name}.${member1.name}`;+ if (member1.kind === 'method')+ memberName1 += '()';+ let memberName2 = `${cls.name}.${member2.name}`;+ if (member2.kind === 'method')+ memberName2 += '()';+ errors.push(`Bad alphabetic ordering of ${cls.name} members: ${memberName1} should go after ${memberName2}`);+ }+ }+ }+ return errors;+}++/**+ * @param {!Array<!Source>} jsSources+ * @param {!Documentation} jsDocumentation+ * @return {!Documentation}+ */+function filterJSDocumentation(jsSources, jsDocumentation) {+ const apijs = jsSources.find(source => source.name() === 'api.ts');+ let includedClasses = null;+ if (apijs)+ includedClasses = new Set(Object.keys(require(path.join(apijs.filePath(), '..', '..', 'lib', 'api.js')).Chromium));+ // Filter private classes and methods.+ const classes = [];+ for (const cls of jsDocumentation.classesArray) {+ if (includedClasses && !includedClasses.has(cls.name))+ continue;+ const members = cls.membersArray.filter(member => !EXCLUDE_PROPERTIES.has(`${cls.name}.${member.name}`));+ classes.push(new Documentation.Class(cls.name, members));+ }+ return new Documentation(classes);+}++/**+ * @param {!Documentation} doc+ * @return {!Array<string>}+ */+function checkDuplicates(doc) {+ const errors = [];+ const classes = new Set();+ // Report duplicates.+ for (const cls of doc.classesArray) {+ if (classes.has(cls.name))+ errors.push(`Duplicate declaration of class ${cls.name}`);+ classes.add(cls.name);+ const members = new Set();+ for (const member of cls.membersArray) {+ if (members.has(member.kind + ' ' + member.name))+ errors.push(`Duplicate declaration of ${member.kind} ${cls.name}.${member.name}()`);+ members.add(member.kind + ' ' + member.name);+ const args = new Set();+ for (const arg of member.argsArray) {+ if (args.has(arg.name))+ errors.push(`Duplicate declaration of argument ${cls.name}.${member.name} "${arg.name}"`);+ args.add(arg.name);+ }+ }+ }+ return errors;+}++/**+ * @param {!Documentation} actual+ * @param {!Documentation} expected+ * @return {!Array<string>}+ */+function compareDocumentations(actual, expected) {+ const errors = [];++ const actualClasses = Array.from(actual.classes.keys()).sort();+ const expectedClasses = Array.from(expected.classes.keys()).sort();+ const classesDiff = diff(actualClasses, expectedClasses);+ for (const className of classesDiff.extra)+ errors.push(`Non-existing class found: ${className}`);+ for (const className of classesDiff.missing)+ errors.push(`Class not found: ${className}`);++ for (const className of classesDiff.equal) {+ const actualClass = actual.classes.get(className);+ const expectedClass = expected.classes.get(className);+ const actualMethods = Array.from(actualClass.methods.keys()).sort();+ const expectedMethods = Array.from(expectedClass.methods.keys()).sort();+ const methodDiff = diff(actualMethods, expectedMethods);+ for (const methodName of methodDiff.extra)+ errors.push(`Non-existing method found: ${className}.${methodName}()`);+ for (const methodName of methodDiff.missing)+ errors.push(`Method not found: ${className}.${methodName}()`);++ for (const methodName of methodDiff.equal) {+ const actualMethod = actualClass.methods.get(methodName);+ const expectedMethod = expectedClass.methods.get(methodName);+ if (!actualMethod.type !== !expectedMethod.type) {+ if (actualMethod.type)+ errors.push(`Method ${className}.${methodName} has unneeded description of return type`);+ else+ errors.push(`Method ${className}.${methodName} is missing return type description`);+ } else if (actualMethod.hasReturn) {+ checkType(`Method ${className}.${methodName} has the wrong return type: `, actualMethod.type, expectedMethod.type);+ }+ const actualArgs = Array.from(actualMethod.args.keys());+ const expectedArgs = Array.from(expectedMethod.args.keys());+ const argsDiff = diff(actualArgs, expectedArgs);+ if (argsDiff.extra.length || argsDiff.missing.length) {+ const text = [`Method ${className}.${methodName}() fails to describe its parameters:`];+ for (const arg of argsDiff.missing)+ text.push(`- Argument not found: ${arg}`);+ for (const arg of argsDiff.extra)+ text.push(`- Non-existing argument found: ${arg}`);+ errors.push(text.join('\n'));+ }++ for (const arg of argsDiff.equal)+ checkProperty(`Method ${className}.${methodName}()`, actualMethod.args.get(arg), expectedMethod.args.get(arg));+ }+ const actualProperties = Array.from(actualClass.properties.keys()).sort();+ const expectedProperties = Array.from(expectedClass.properties.keys()).sort();+ const propertyDiff = diff(actualProperties, expectedProperties);+ for (const propertyName of propertyDiff.extra)+ errors.push(`Non-existing property found: ${className}.${propertyName}`);+ for (const propertyName of propertyDiff.missing)+ errors.push(`Property not found: ${className}.${propertyName}`);++ const actualEvents = Array.from(actualClass.events.keys()).sort();+ const expectedEvents = Array.from(expectedClass.events.keys()).sort();+ const eventsDiff = diff(actualEvents, expectedEvents);+ for (const eventName of eventsDiff.extra)+ errors.push(`Non-existing event found in class ${className}: '${eventName}'`);+ for (const eventName of eventsDiff.missing)+ errors.push(`Event not found in class ${className}: '${eventName}'`);+ }+++ /**+ * @param {string} source+ * @param {!Documentation.Member} actual+ * @param {!Documentation.Member} expected+ */+ function checkProperty(source, actual, expected) {+ checkType(source + ' ' + actual.name, actual.type, expected.type);+ }++ /**+ * @param {string} source+ * @param {!Documentation.Type} actual+ * @param {!Documentation.Type} expected+ */+ function checkType(source, actual, expected) {+ // TODO(@JoelEinbinder): check functions and Serializable+ if (actual.name.includes('unction') || actual.name.includes('Serializable'))+ return;+ // We don't have nullchecks on for TypeScript+ const actualName = actual.name.replace(/[\? ]/g, '');+ // TypeScript likes to add some spaces+ const expectedName = expected.name.replace(/\ /g, '');+ if (expectedName !== actualName)+ errors.push(`${source} ${actualName} != ${expectedName}`);+ const actualPropertiesMap = new Map(actual.properties.map(property => [property.name, property.type]));+ const expectedPropertiesMap = new Map(expected.properties.map(property => [property.name, property.type]));+ const propertiesDiff = diff(Array.from(actualPropertiesMap.keys()).sort(), Array.from(expectedPropertiesMap.keys()).sort());+ for (const propertyName of propertiesDiff.extra)+ errors.push(`${source} has unexpected property ${propertyName}`);+ for (const propertyName of propertiesDiff.missing)+ errors.push(`${source} is missing property ${propertyName}`);+ for (const propertyName of propertiesDiff.equal)+ checkType(source + '.' + propertyName, actualPropertiesMap.get(propertyName), expectedPropertiesMap.get(propertyName));+ }++ return errors;+}++/**+ * @param {!Array<string>} actual+ * @param {!Array<string>} expected+ * @return {{extra: !Array<string>, missing: !Array<string>, equal: !Array<string>}}+ */+function diff(actual, expected) {+ const N = actual.length;+ const M = expected.length;+ if (N === 0 && M === 0)+ return { extra: [], missing: [], equal: []};+ if (N === 0)+ return {extra: [], missing: expected.slice(), equal: []};+ if (M === 0)+ return {extra: actual.slice(), missing: [], equal: []};+ const d = new Array(N);+ const bt = new Array(N);+ for (let i = 0; i < N; ++i) {+ d[i] = new Array(M);+ bt[i] = new Array(M);+ for (let j = 0; j < M; ++j) {+ const top = val(i - 1, j);+ const left = val(i, j - 1);+ if (top > left) {+ d[i][j] = top;+ bt[i][j] = 'extra';+ } else {+ d[i][j] = left;+ bt[i][j] = 'missing';+ }+ const diag = val(i - 1, j - 1);+ if (actual[i] === expected[j] && d[i][j] < diag + 1) {+ d[i][j] = diag + 1;+ bt[i][j] = 'eq';+ }+ }+ }+ // Backtrack results.+ let i = N - 1;+ let j = M - 1;+ const missing = [];+ const extra = [];+ const equal = [];+ while (i >= 0 && j >= 0) {+ switch (bt[i][j]) {+ case 'extra':+ extra.push(actual[i]);+ i -= 1;+ break;+ case 'missing':+ missing.push(expected[j]);+ j -= 1;+ break;+ case 'eq':+ equal.push(actual[i]);+ i -= 1;+ j -= 1;+ break;+ }+ }+ while (i >= 0)+ extra.push(actual[i--]);+ while (j >= 0)+ missing.push(expected[j--]);+ extra.reverse();+ missing.reverse();+ equal.reverse();+ return {extra, missing, equal};++ function val(i, j) {+ return i < 0 || j < 0 ? 0 : d[i][j];+ }+}+diff --git a/utils/doclint/check_public_api/test/.gitignore b/utils/doclint/check_public_api/test/.gitignorenew file mode 100644index 0000000000..17526b1162--- /dev/null+++ b/utils/doclint/check_public_api/test/.gitignore@@ -0,0 +1,2 @@+result-actual.txt+result-diff.htmldiff --git a/utils/doclint/check_public_api/test/check-duplicates/doc.md b/utils/doclint/check_public_api/test/check-duplicates/doc.mdnew file mode 100644index 0000000000..ea743ecd1e--- /dev/null+++ b/utils/doclint/check_public_api/test/check-duplicates/doc.md@@ -0,0 +1,15 @@+### class: Bar++### class: Foo++#### foo.test()++#### foo.test()++#### foo.title(arg, arg)+- `arg` <[number]>+- `arg` <[number]>++### class: Bar++[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"diff --git a/utils/doclint/check_public_api/test/check-duplicates/foo.js b/utils/doclint/check_public_api/test/check-duplicates/foo.jsnew file mode 100644index 0000000000..640271ae49--- /dev/null+++ b/utils/doclint/check_public_api/test/check-duplicates/foo.js@@ -0,0 +1,13 @@+class Foo {+ test() {+ }++ /**+ * @param {number} arg+ */+ title(arg) {+ }+}++class Bar {+}diff --git a/utils/doclint/check_public_api/test/check-duplicates/result.txt b/utils/doclint/check_public_api/test/check-duplicates/result.txtnew file mode 100644index 0000000000..d9994416e9--- /dev/null+++ b/utils/doclint/check_public_api/test/check-duplicates/result.txt@@ -0,0 +1,3 @@+[MarkDown] Duplicate declaration of method Foo.test()+[MarkDown] Duplicate declaration of argument Foo.title "arg"+[MarkDown] Duplicate declaration of class Bar\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/check-returns/doc.md b/utils/doclint/check_public_api/test/check-returns/doc.mdnew file mode 100644index 0000000000..1dffb8b6f0--- /dev/null+++ b/utils/doclint/check_public_api/test/check-returns/doc.md@@ -0,0 +1,14 @@+### class: Foo++#### foo.asyncFunction()++#### foo.return42()++#### foo.returnNothing()+- returns: <[number]>++#### foo.www()+- returns <[string]>++[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "String"+[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"diff --git a/utils/doclint/check_public_api/test/check-returns/foo.js b/utils/doclint/check_public_api/test/check-returns/foo.jsnew file mode 100644index 0000000000..5833c14699--- /dev/null+++ b/utils/doclint/check_public_api/test/check-returns/foo.js@@ -0,0 +1,20 @@+class Foo {+ return42() {+ return 42;+ }++ returnNothing() {+ let e = () => {+ return 10;+ }+ e();+ }++ www() {+ if (1 === 1)+ return 'df';+ }++ async asyncFunction() {+ }+}diff --git a/utils/doclint/check_public_api/test/check-returns/result.txt b/utils/doclint/check_public_api/test/check-returns/result.txtnew file mode 100644index 0000000000..ceb202b25f--- /dev/null+++ b/utils/doclint/check_public_api/test/check-returns/result.txt@@ -0,0 +1,4 @@+[MarkDown] foo.www() has mistyped 'return' type declaration: expected exactly 'returns: ', found 'returns '.+[MarkDown] Method Foo.asyncFunction is missing return type description+[MarkDown] Method Foo.return42 is missing return type description+[MarkDown] Method Foo.returnNothing has unneeded description of return type\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/check-sorting/Events.js b/utils/doclint/check_public_api/test/check-sorting/Events.jsnew file mode 100644index 0000000000..55f20be064--- /dev/null+++ b/utils/doclint/check_public_api/test/check-sorting/Events.js@@ -0,0 +1,8 @@+const Events = {+ Foo: {+ a: 'a',+ b: 'b',+ c: 'c',+ },+};+module.exports = {Events};diff --git a/utils/doclint/check_public_api/test/check-sorting/doc.md b/utils/doclint/check_public_api/test/check-sorting/doc.mdnew file mode 100644index 0000000000..9b3162824a--- /dev/null+++ b/utils/doclint/check_public_api/test/check-sorting/doc.md@@ -0,0 +1,15 @@+### class: Foo++#### event: 'c'++#### event: 'a'++#### foo.aaa()++#### event: 'b'++#### foo.ddd++#### foo.ccc()++#### foo.bbb()diff --git a/utils/doclint/check_public_api/test/check-sorting/foo.js b/utils/doclint/check_public_api/test/check-sorting/foo.jsnew file mode 100644index 0000000000..9a61bf11a4--- /dev/null+++ b/utils/doclint/check_public_api/test/check-sorting/foo.js@@ -0,0 +1,12 @@+class Foo {+ constructor() {+ this.ddd = 10;+ }++ aaa() {}++ bbb() {}++ ccc() {}+}+diff --git a/utils/doclint/check_public_api/test/check-sorting/result.txt b/utils/doclint/check_public_api/test/check-sorting/result.txtnew file mode 100644index 0000000000..fee39688e6--- /dev/null+++ b/utils/doclint/check_public_api/test/check-sorting/result.txt@@ -0,0 +1,4 @@+[MarkDown] Events should go first. Event 'b' in class Foo breaks order+[MarkDown] Event 'c' in class Foo breaks alphabetic ordering of events+[MarkDown] Bad alphabetic ordering of Foo members: Foo.ddd should go after Foo.ccc()+[MarkDown] Bad alphabetic ordering of Foo members: Foo.ccc() should go after Foo.bbb()\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/diff-arguments/doc.md b/utils/doclint/check_public_api/test/diff-arguments/doc.mdnew file mode 100644index 0000000000..a991bfa66b--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-arguments/doc.md@@ -0,0 +1,14 @@+### class: Foo+#### foo.bar(options)+- `options` <[Object]>+ - `visibility` <[boolean]>+#### foo.foo(arg1, arg2)+- `arg1` <[string]>+- `arg2` <[string]>++#### foo.test(...files)+- `...filePaths` <...[string]>++[Object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Object"+[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "String"+[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type "Boolean"diff --git a/utils/doclint/check_public_api/test/diff-arguments/foo.js b/utils/doclint/check_public_api/test/diff-arguments/foo.jsnew file mode 100644index 0000000000..d102f6f7ae--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-arguments/foo.js@@ -0,0 +1,19 @@+class Foo {+ /**+ * @param {string} arg1+ */+ foo(arg1, arg3 = {}) {+ }++ /**+ * @param {...string} filePaths+ */+ test(...filePaths) {+ }++ /**+ * @param {{visibility?: boolean}} options+ */+ bar(options) {+ }+}diff --git a/utils/doclint/check_public_api/test/diff-arguments/result.txt b/utils/doclint/check_public_api/test/diff-arguments/result.txtnew file mode 100644index 0000000000..bd6b1f0eb1--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-arguments/result.txt@@ -0,0 +1,4 @@+[MarkDown] Heading arguments for "foo.test(...files)" do not match described ones, i.e. "...files" != "...filePaths"+[MarkDown] Method Foo.foo() fails to describe its parameters:+- Argument not found: arg3+- Non-existing argument found: arg2\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/diff-classes/doc.md b/utils/doclint/check_public_api/test/diff-classes/doc.mdnew file mode 100644index 0000000000..7e51ca4754--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-classes/doc.md@@ -0,0 +1,5 @@+### class: Foo++### class: Bar++### class: Bazdiff --git a/utils/doclint/check_public_api/test/diff-classes/foo.js b/utils/doclint/check_public_api/test/diff-classes/foo.jsnew file mode 100644index 0000000000..f230fa0f41--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-classes/foo.js@@ -0,0 +1,2 @@+class Foo {+}diff --git a/utils/doclint/check_public_api/test/diff-classes/other.js b/utils/doclint/check_public_api/test/diff-classes/other.jsnew file mode 100644index 0000000000..1b94418eb0--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-classes/other.js@@ -0,0 +1,2 @@+class Other {+}diff --git a/utils/doclint/check_public_api/test/diff-classes/result.txt b/utils/doclint/check_public_api/test/diff-classes/result.txtnew file mode 100644index 0000000000..2852a437c6--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-classes/result.txt@@ -0,0 +1,3 @@+[MarkDown] Non-existing class found: Bar+[MarkDown] Non-existing class found: Baz+[MarkDown] Class not found: Other\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/diff-events/Events.js b/utils/doclint/check_public_api/test/diff-events/Events.jsnew file mode 100644index 0000000000..7ef8bcdfdb--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-events/Events.js@@ -0,0 +1,8 @@+const Events = {+ Foo: {+ Start: 'start',+ Finish: 'finish',+ },+};++module.exports = {Events};diff --git a/utils/doclint/check_public_api/test/diff-events/doc.md b/utils/doclint/check_public_api/test/diff-events/doc.mdnew file mode 100644index 0000000000..3da9c79511--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-events/doc.md@@ -0,0 +1,5 @@+### class: Foo++#### event: 'start'++#### event: 'stop'diff --git a/utils/doclint/check_public_api/test/diff-events/foo.js b/utils/doclint/check_public_api/test/diff-events/foo.jsnew file mode 100644index 0000000000..fbb14b3136--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-events/foo.js@@ -0,0 +1,3 @@+class Foo {+}+diff --git a/utils/doclint/check_public_api/test/diff-events/result.txt b/utils/doclint/check_public_api/test/diff-events/result.txtnew file mode 100644index 0000000000..8a18433aed--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-events/result.txt@@ -0,0 +1,2 @@+[MarkDown] Non-existing event found in class Foo: 'stop'+[MarkDown] Event not found in class Foo: 'finish'\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/diff-methods/doc.md b/utils/doclint/check_public_api/test/diff-methods/doc.mdnew file mode 100644index 0000000000..489d014988--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-methods/doc.md@@ -0,0 +1,10 @@+### class: Foo++#### foo.$()++#### foo.money$$money()++#### foo.proceed()++#### foo.start()+diff --git a/utils/doclint/check_public_api/test/diff-methods/foo.js b/utils/doclint/check_public_api/test/diff-methods/foo.jsnew file mode 100644index 0000000000..76f44edab7--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-methods/foo.js@@ -0,0 +1,16 @@+class Foo {+ start() {+ }++ stop() {+ }++ get zzz() {+ }++ $() {+ }++ money$$money() {+ }+}diff --git a/utils/doclint/check_public_api/test/diff-methods/result.txt b/utils/doclint/check_public_api/test/diff-methods/result.txtnew file mode 100644index 0000000000..d919f52e99--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-methods/result.txt@@ -0,0 +1,3 @@+[MarkDown] Non-existing method found: Foo.proceed()+[MarkDown] Method not found: Foo.stop()+[MarkDown] Property not found: Foo.zzz\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/diff-properties/doc.md b/utils/doclint/check_public_api/test/diff-properties/doc.mdnew file mode 100644index 0000000000..75d4fd106f--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-properties/doc.md@@ -0,0 +1,5 @@+### class: Foo++#### foo.a++#### foo.cdiff --git a/utils/doclint/check_public_api/test/diff-properties/foo.js b/utils/doclint/check_public_api/test/diff-properties/foo.jsnew file mode 100644index 0000000000..a978379f2c--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-properties/foo.js@@ -0,0 +1,7 @@+class Foo {+ constructor() {+ this.a = 42;+ this.b = 'hello';+ this.emit('done');+ }+}diff --git a/utils/doclint/check_public_api/test/diff-properties/result.txt b/utils/doclint/check_public_api/test/diff-properties/result.txtnew file mode 100644index 0000000000..382a4d41b8--- /dev/null+++ b/utils/doclint/check_public_api/test/diff-properties/result.txt@@ -0,0 +1,2 @@+[MarkDown] Non-existing property found: Foo.c+[MarkDown] Property not found: Foo.b\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/js-builder-common/Events.js b/utils/doclint/check_public_api/test/js-builder-common/Events.jsnew file mode 100644index 0000000000..da44ad81a1--- /dev/null+++ b/utils/doclint/check_public_api/test/js-builder-common/Events.js@@ -0,0 +1,6 @@+const Events = {+ A: {+ AnEvent: 'anevent'+ },+};+module.exports = { Events };diff --git a/utils/doclint/check_public_api/test/js-builder-common/foo.js b/utils/doclint/check_public_api/test/js-builder-common/foo.jsnew file mode 100644index 0000000000..cf82646e3c--- /dev/null+++ b/utils/doclint/check_public_api/test/js-builder-common/foo.js@@ -0,0 +1,13 @@+class A {+ constructor(delegate) {+ this.property1 = 1;+ this._property2 = 2;+ }++ get getter() {+ return null;+ }++ async method(foo, bar) {+ }+}diff --git a/utils/doclint/check_public_api/test/js-builder-common/result.txt b/utils/doclint/check_public_api/test/js-builder-common/result.txtnew file mode 100644index 0000000000..40e9475b02--- /dev/null+++ b/utils/doclint/check_public_api/test/js-builder-common/result.txt@@ -0,0 +1,50 @@+{+ "classes": [+ {+ "name": "A",+ "members": [+ {+ "name": "anevent",+ "kind": "event"+ },+ {+ "name": "property1",+ "type": {+ "name": "number"+ },+ "kind": "property"+ },+ {+ "name": "getter",+ "type": {+ "name": "Object"+ },+ "kind": "property"+ },+ {+ "name": "method",+ "type": {+ "name": "Promise"+ },+ "kind": "method",+ "args": [+ {+ "name": "foo",+ "type": {+ "name": "Object"+ },+ "kind": "property"+ },+ {+ "name": "bar",+ "type": {+ "name": "Object"+ },+ "kind": "property"+ }+ ]+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/js-builder-inheritance/Events.js b/utils/doclint/check_public_api/test/js-builder-inheritance/Events.jsnew file mode 100644index 0000000000..f22e6aadc4--- /dev/null+++ b/utils/doclint/check_public_api/test/js-builder-inheritance/Events.js@@ -0,0 +1,8 @@+const Events = {+ B: {+ // Event with the same name as a super class method.+ foo: 'foo',+ },+};++module.exports = {Events};diff --git a/utils/doclint/check_public_api/test/js-builder-inheritance/foo.js b/utils/doclint/check_public_api/test/js-builder-inheritance/foo.jsnew file mode 100644index 0000000000..1d5cb154d4--- /dev/null+++ b/utils/doclint/check_public_api/test/js-builder-inheritance/foo.js@@ -0,0 +1,15 @@+class A {+ constructor() {+ }++ foo(a) {+ }++ bar() {+ }+}++class B extends A {+ bar(override) {+ }+}diff --git a/utils/doclint/check_public_api/test/js-builder-inheritance/result.txt b/utils/doclint/check_public_api/test/js-builder-inheritance/result.txtnew file mode 100644index 0000000000..0975d03ab3--- /dev/null+++ b/utils/doclint/check_public_api/test/js-builder-inheritance/result.txt@@ -0,0 +1,61 @@+{+ "classes": [+ {+ "name": "A",+ "members": [+ {+ "name": "foo",+ "kind": "method",+ "args": [+ {+ "name": "a",+ "type": {+ "name": "Object"+ },+ "kind": "property"+ }+ ]+ },+ {+ "name": "bar",+ "kind": "method"+ }+ ]+ },+ {+ "name": "B",+ "members": [+ {+ "name": "foo",+ "kind": "event"+ },+ {+ "name": "bar",+ "kind": "method",+ "args": [+ {+ "name": "override",+ "type": {+ "name": "Object"+ },+ "kind": "property"+ }+ ]+ },+ {+ "name": "foo",+ "kind": "method",+ "args": [+ {+ "name": "a",+ "type": {+ "name": "Object"+ },+ "kind": "property"+ }+ ]+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/md-builder-common/doc.md b/utils/doclint/check_public_api/test/md-builder-common/doc.mdnew file mode 100644index 0000000000..42695c4cd4--- /dev/null+++ b/utils/doclint/check_public_api/test/md-builder-common/doc.md@@ -0,0 +1,24 @@+### class: Foo++This is a class.++#### event: 'frame'+- <[Frame]>++This event is dispatched.++#### foo.$(selector)+- `selector` <[string]> A selector to query page for+- returns: <[Promise]<[ElementHandle]>>++The method runs document.querySelector.++#### foo.url+- <[string]>++Contains the URL of the request.++[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "String"+[Promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise "Promise"+[ElementHandle]: # "ElementHandle"+[ElementHandle]: # "Frame"diff --git a/utils/doclint/check_public_api/test/md-builder-common/result.txt b/utils/doclint/check_public_api/test/md-builder-common/result.txtnew file mode 100644index 0000000000..46c065f26b--- /dev/null+++ b/utils/doclint/check_public_api/test/md-builder-common/result.txt@@ -0,0 +1,39 @@+{+ "classes": [+ {+ "name": "Foo",+ "members": [+ {+ "name": "frame",+ "type": {+ "name": "[Frame]"+ },+ "kind": "event"+ },+ {+ "name": "$",+ "type": {+ "name": "Promise<ElementHandle>"+ },+ "kind": "method",+ "args": [+ {+ "name": "selector",+ "type": {+ "name": "string"+ },+ "kind": "property"+ }+ ]+ },+ {+ "name": "url",+ "type": {+ "name": "string"+ },+ "kind": "property"+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/utils/doclint/check_public_api/test/test.js b/utils/doclint/check_public_api/test/test.jsnew file mode 100644index 0000000000..46a19d0188--- /dev/null+++ b/utils/doclint/check_public_api/test/test.js@@ -0,0 +1,127 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const path = require('path');+const playwright = require('../../../..');+const checkPublicAPI = require('..');+const Source = require('../../Source');+const mdBuilder = require('../MDBuilder');+const jsBuilder = require('../JSBuilder');+const GoldenUtils = require('../../../../test/golden-utils');++const {TestRunner, Reporter, Matchers} = require('../../../testrunner/');+const runner = new TestRunner();+const reporter = new Reporter(runner);++const {describe, xdescribe, fdescribe} = runner;+const {it, fit, xit} = runner;+const {beforeAll, beforeEach, afterAll, afterEach} = runner;++let browser;+let page;++beforeAll(async function() {+ browser = await playwright.launch();+ page = await browser.newPage();+});++afterAll(async function() {+ await browser.close();+});++describe('checkPublicAPI', function() {+ it('diff-classes', testLint);+ it('diff-methods', testLint);+ it('diff-properties', testLint);+ it('diff-arguments', testLint);+ it('diff-events', testLint);+ it('check-duplicates', testLint);+ it('check-sorting', testLint);+ it('check-returns', testLint);+ it('js-builder-common', testJSBuilder);+ it('js-builder-inheritance', testJSBuilder);+ it('md-builder-common', testMDBuilder);+});++runner.run();++async function testLint(state, test) {+ const dirPath = path.join(__dirname, test.name);+ const {expect} = new Matchers({+ toBeGolden: GoldenUtils.compare.bind(null, dirPath, dirPath)+ });++ const mdSources = await Source.readdir(dirPath, '.md');+ const jsSources = await Source.readdir(dirPath, '.js');+ const messages = await checkPublicAPI(page, mdSources, jsSources);+ const errors = messages.map(message => message.text);+ expect(errors.join('\n')).toBeGolden('result.txt');+}++async function testMDBuilder(state, test) {+ const dirPath = path.join(__dirname, test.name);+ const {expect} = new Matchers({+ toBeGolden: GoldenUtils.compare.bind(null, dirPath, dirPath)+ });+ const sources = await Source.readdir(dirPath, '.md');+ const {documentation} = await mdBuilder(page, sources);+ expect(serialize(documentation)).toBeGolden('result.txt');+}++async function testJSBuilder(state, test) {+ const dirPath = path.join(__dirname, test.name);+ const {expect} = new Matchers({+ toBeGolden: GoldenUtils.compare.bind(null, dirPath, dirPath)+ });+ const sources = await Source.readdir(dirPath, '.js');+ const {documentation} = await jsBuilder(sources);+ expect(serialize(documentation)).toBeGolden('result.txt');+}++/**+ * @param {import('../Documentation')} doc+ */+function serialize(doc) {+ const result = {+ classes: doc.classesArray.map(cls => ({+ name: cls.name,+ members: cls.membersArray.map(serializeMember)+ }))+ };+ return JSON.stringify(result, null, 2);+}+/**+ * @param {import('../Documentation').Member} member+ */+function serializeMember(member) {+ return {+ name: member.name,+ type: serializeType(member.type),+ kind: member.kind,+ args: member.argsArray.length ? member.argsArray.map(serializeMember) : undefined+ }+}+/**+ * @param {import('../Documentation').Type} type+ */+function serializeType(type) {+ if (!type)+ return undefined;+ return {+ name: type.name,+ properties: type.properties.length ? type.properties.map(serializeMember) : undefined+ }+}\ No newline at end of filediff --git a/utils/doclint/cli.js b/utils/doclint/cli.jsnew file mode 100755index 0000000000..df81867f79--- /dev/null+++ b/utils/doclint/cli.js@@ -0,0 +1,94 @@+#!/usr/bin/env node+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const playwright = require('../..');+const path = require('path');+const Source = require('./Source');++const PROJECT_DIR = path.join(__dirname, '..', '..');+const VERSION = require(path.join(PROJECT_DIR, 'package.json')).version;++const RED_COLOR = '\x1b[31m';+const YELLOW_COLOR = '\x1b[33m';+const RESET_COLOR = '\x1b[0m';++run();++async function run() {+ const startTime = Date.now();++ /** @type {!Array<!Message>} */+ const messages = [];+ let changedFiles = false;++ // Documentation checks.+ {+ const readme = await Source.readFile(path.join(PROJECT_DIR, 'README.md'));+ const contributing = await Source.readFile(path.join(PROJECT_DIR, 'CONTRIBUTING.md'));+ const api = await Source.readFile(path.join(PROJECT_DIR, 'docs', 'api.md'));+ const troubleshooting = await Source.readFile(path.join(PROJECT_DIR, 'docs', 'troubleshooting.md'));+ const mdSources = [readme, api, troubleshooting, contributing];++ const preprocessor = require('./preprocessor');+ messages.push(...await preprocessor.runCommands(mdSources, VERSION));+ messages.push(...await preprocessor.ensureReleasedAPILinks([readme], VERSION));++ const browser = await playwright.launch();+ const page = await browser.newPage();+ const checkPublicAPI = require('./check_public_api');+ const jsSources = await Source.readdir(path.join(PROJECT_DIR, 'src'));+ messages.push(...await checkPublicAPI(page, mdSources, jsSources));+ await browser.close();++ for (const source of mdSources) {+ if (!source.hasUpdatedText())+ continue;+ await source.save();+ changedFiles = true;+ }+ }++ // Report results.+ const errors = messages.filter(message => message.type === 'error');+ if (errors.length) {+ console.log('DocLint Failures:');+ for (let i = 0; i < errors.length; ++i) {+ let error = errors[i].text;+ error = error.split('\n').join('\n ');+ console.log(` ${i + 1}) ${RED_COLOR}${error}${RESET_COLOR}`);+ }+ }+ const warnings = messages.filter(message => message.type === 'warning');+ if (warnings.length) {+ console.log('DocLint Warnings:');+ for (let i = 0; i < warnings.length; ++i) {+ let warning = warnings[i].text;+ warning = warning.split('\n').join('\n ');+ console.log(` ${i + 1}) ${YELLOW_COLOR}${warning}${RESET_COLOR}`);+ }+ }+ let clearExit = messages.length === 0;+ if (changedFiles) {+ if (clearExit)+ console.log(`${YELLOW_COLOR}Some files were updated.${RESET_COLOR}`);+ clearExit = false;+ }+ console.log(`${errors.length} failures, ${warnings.length} warnings.`);+ const runningTime = Date.now() - startTime;+ console.log(`DocLint Finished in ${runningTime / 1000} seconds`);+ process.exit(clearExit ? 0 : 1);+}diff --git a/utils/doclint/generate_types/index.js b/utils/doclint/generate_types/index.jsnew file mode 100644index 0000000000..30bc59d876--- /dev/null+++ b/utils/doclint/generate_types/index.js@@ -0,0 +1,221 @@+const path = require('path');+const Source = require('../Source');+const playwright = require('../../..');+const PROJECT_DIR = path.join(__dirname, '..', '..', '..');+const fs = require('fs');+const objectDefinitions = [];+(async function() {+ const browser = await playwright.launch();+ const page = (await browser.pages())[0];+ const api = await Source.readFile(path.join(PROJECT_DIR, 'docs', 'api.md'));+ const {documentation} = await require('../check_public_api/MDBuilder')(page, [api]);+ await browser.close();+ const classes = documentation.classesArray.slice(1);+ const root = documentation.classesArray[0];+ const output = `// This file is generated by ${__filename.substring(path.join(__dirname, '..', '..').length)}+import { ChildProcess } from 'child_process';+import { EventEmitter } from 'events';+/**+ * Can be converted to JSON+ */+interface Serializable {}+interface ConnectionTransport {}++${root.methodsArray.map(method => `+${memberJSDOC(method, '')}export function ${method.name}${argsFromMember(method)} : ${typeToString(method.type, method.name)};+`).join('')}+${root.propertiesArray.map(property => `+${memberJSDOC(property, '')}export const ${property.name}${argsFromMember(property)} : ${typeToString(property.type, property.name)};+`).join('')}+${classes.map(classDesc => classToString(classDesc)).join('\n')}+${objectDefinitionsToString()}+`;+ fs.writeFileSync(path.join(PROJECT_DIR, 'index.d.ts'), output, 'utf8');+})();++function objectDefinitionsToString() {+ let definition;+ const parts = [];+ while ((definition = objectDefinitions.pop())) {+ const {name, properties} = definition;+ parts.push(`interface ${name} {`);+ parts.push(properties.map(member => ` ${memberJSDOC(member, ' ')}${nameForProperty(member)}${argsFromMember(member, name)}: ${typeToString(member.type, name, member.name)};`).join('\n\n'));+ parts.push('}\n');+ }+ return parts.join('\n');+}++function nameForProperty(member) {+ return (member.required || member.name.startsWith('...')) ? member.name : member.name + '?';+}++/**+ * @param {import('./check_public_api/Documentation').Class} classDesc+ */+function classToString(classDesc) {+ const parts = [];+ if (classDesc.comment) {+ parts.push(`/**+ * ${classDesc.comment.split('\n').join('\n * ')}+ */`);+ }+ parts.push(`export interface ${classDesc.name} ${classDesc.extends ? `extends ${classDesc.extends} ` : ''}{`);+ for (const method of ['on', 'once', 'addListener']) {+ for (const [eventName, value] of classDesc.events) {+ if (value.comment) {+ parts.push(' /**');+ parts.push(...value.comment.split('\n').map(line => ' * ' + line));+ parts.push(' */');+ }+ parts.push(` ${method}(event: '${eventName}', listener: (arg0 : ${typeToString(value && value.type, classDesc.name, eventName, 'payload')}) => void): this;\n`);+ }+ }+ const members = classDesc.membersArray.filter(member => member.kind !== 'event');+ parts.push(members.map(member => ` ${memberJSDOC(member, ' ')}${member.name}${argsFromMember(member, classDesc.name)}: ${typeToString(member.type, classDesc.name, member.name)};`).join('\n\n'));+ parts.push('}\n');+ return parts.join('\n');+}++/**+ * @param {import('./check_public_api/Documentation').Type} type+ */+function typeToString(type, ...namespace) {+ if (!type)+ return 'void';+ let typeString = stringifyType(parseType(type.name));+ for (let i = 0; i < type.properties.length; i++)+ typeString = typeString.replace('arg' + i, type.properties[i].name);+ if (type.properties.length && typeString.indexOf('Object') !== -1) {+ const name = namespace.map(n => n[0].toUpperCase() + n.substring(1)).join('');+ typeString = typeString.replace('Object', name);+ objectDefinitions.push({name, properties: type.properties});+ }+ return typeString;+}++/**+ * @param {string} type+ */+function parseType(type) {+ type = type.trim();+ if (type.startsWith('?')) {+ const parsed = parseType(type.substring(1));+ parsed.nullable = true;+ return parsed;+ }+ if (type.startsWith('...'))+ return parseType('Array<' + type.substring(3) + '>');+ let name = type;+ let next = null;+ let template = null;+ let args = null;+ let retType = null;+ let firstTypeLength = type.length;+ for (let i = 0; i < type.length; i++) {+ if (type[i] === '<') {+ name = type.substring(0, i);+ const matching = matchingBracket(type.substring(i), '<', '>');+ template = parseType(type.substring(i + 1, i + matching - 1));+ firstTypeLength = i + matching;+ break;+ }+ if (type[i] === '(') {+ name = type.substring(0, i);+ const matching = matchingBracket(type.substring(i), '(', ')');+ args = parseType(type.substring(i + 1, i + matching - 1));+ i = i + matching;+ if (type[i] === ':') {+ retType = parseType(type.substring(i + 1));+ next = retType.next;+ retType.next = null;+ break;+ }+ }+ if (type[i] === '|' || type[i] === ',') {+ name = type.substring(0, i);+ firstTypeLength = i;+ break;+ }+ }+ let pipe = null;+ if (type[firstTypeLength] === '|')+ pipe = parseType(type.substring(firstTypeLength + 1));+ else if (type[firstTypeLength] === ',')+ next = parseType(type.substring(firstTypeLength + 1));+ if (name === 'Promise' && !template)+ template = parseType('void');+ return {+ name,+ args,+ retType,+ template,+ pipe,+ next+ };+}++function stringifyType(parsedType) {+ if (!parsedType)+ return 'void';+ let out = parsedType.name;+ if (parsedType.args) {+ let args = parsedType.args;+ const stringArgs = [];+ while (args) {+ const arg = args;+ args = args.next;+ arg.next = null;+ stringArgs.push(stringifyType(arg));+ }+ out = `(${stringArgs.map((type, index) => `arg${index} : ${type}`).join(', ')}, ...args: any[]) => ${stringifyType(parsedType.retType)}`;+ } else if (parsedType.name === 'function') {+ out = 'Function';+ }+ if (parsedType.nullable)+ out = 'null|' + out;+ if (parsedType.template)+ out += '<' + stringifyType(parsedType.template) + '>';+ if (parsedType.pipe)+ out += '|' + stringifyType(parsedType.pipe);+ if (parsedType.next)+ out += ', ' + stringifyType(parsedType.next);+ return out.trim();+}++function matchingBracket(str, open, close) {+ let count = 1;+ let i = 1;+ for (; i < str.length && count; i++) {+ if (str[i] === open)+ count++;+ else if (str[i] === close)+ count--;+ }+ return i;+}++/**+ * @param {import('./check_public_api/Documentation').Member} member+ */+function argsFromMember(member, ...namespace) {+ if (member.kind === 'property')+ return '';+ return '(' + member.argsArray.map(arg => `${nameForProperty(arg)}: ${typeToString(arg.type, ...namespace, member.name, 'options')}`).join(', ') + ')';+}+/**+ * @param {import('./check_public_api/Documentation').Member} member+ */+function memberJSDOC(member, indent) {+ const lines = [];+ if (member.comment)+ lines.push(...member.comment.split('\n'));+ lines.push(...member.argsArray.map(arg => `@param ${arg.name.replace(/\./g, '')} ${arg.comment.replace('\n', ' ')}`));+ if (member.returnComment)+ lines.push(`@returns ${member.returnComment}`);+ if (!lines.length)+ return '';+ return `/**+${indent} * ${lines.join('\n' + indent + ' * ')}+${indent} */+${indent}`;+}diff --git a/utils/doclint/generate_types/test/test.ts b/utils/doclint/generate_types/test/test.tsnew file mode 100644index 0000000000..26da42d1d0--- /dev/null+++ b/utils/doclint/generate_types/test/test.ts@@ -0,0 +1,283 @@+import * as playwright from "../../../../index";++// Examples taken from README+(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto("https://example.com");+ await page.screenshot({ path: "example.png" });++ browser.close();+})();++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto("https://news.ycombinator.com", { waitUntil: "networkidle0" });+ await page.pdf({ path: "hn.pdf", format: "A4" });++ browser.close();+})();++(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto("https://example.com");++ // Get the "viewport" of the page, as reported by the page.+ const dimensions = await page.evaluate(() => {+ return {+ width: document.documentElement.clientWidth,+ height: document.documentElement.clientHeight,+ deviceScaleFactor: window.devicePixelRatio+ };+ });++ console.log("Dimensions:", dimensions);++ browser.close();+})();++// The following examples are taken from the docs itself+playwright.launch().then(async browser => {+ const page = await browser.newPage();+ page.on("console", (...args: any[]) => {+ for (let i = 0; i < args.length; ++i) console.log(`${i}: ${args[i]}`);+ });+ page.evaluate(() => console.log(5, "hello", { foo: "bar" }));++ const result = await page.evaluate(() => {+ return Promise.resolve(8 * 7);+ });+ console.log(await page.evaluate("1 + 2"));++ const bodyHandle = await page.$("body");++ // Typings for this are really difficult since they depend on internal state+ // of the page class.+ const html = await page.evaluate(+ (body: HTMLElement) => body.innerHTML,+ bodyHandle+ );+});++import * as crypto from "crypto";+import * as fs from "fs";++playwright.launch().then(async browser => {+ const page = await browser.newPage();+ page.on("console", console.log);+ await page.exposeFunction("md5", (text: string) =>+ crypto+ .createHash("md5")+ .update(text)+ .digest("hex")+ );+ await page.evaluate(async () => {+ // use window.md5 to compute hashes+ const myString = "PLAYWRIGHT";+ const myHash = await (window as any).md5(myString);+ console.log(`md5 of ${myString} is ${myHash}`);+ });+ browser.close();++ page.on("console", console.log);+ await page.exposeFunction("readfile", async (filePath: string) => {+ return new Promise((resolve, reject) => {+ fs.readFile(filePath, "utf8", (err, text) => {+ if (err) reject(err);+ else resolve(text);+ });+ });+ });+ await page.evaluate(async () => {+ // use window.readfile to read contents of a file+ const content = await (window as any).readfile("/etc/hosts");+ console.log(content);+ });++ await page.emulateMedia("screen");+ await page.pdf({ path: "page.pdf" });++ await page.setRequestInterception(true);+ page.on("request", interceptedRequest => {+ if (+ interceptedRequest.url().endsWith(".png") ||+ interceptedRequest.url().endsWith(".jpg")+ )+ interceptedRequest.abort();+ else interceptedRequest.continue();+ });++ page.keyboard.type("Hello"); // Types instantly+ page.keyboard.type("World", { delay: 100 }); // Types slower, like a user++ const watchDog = page.waitForFunction("window.innerWidth < 100");+ page.setViewport({ width: 50, height: 50 });+ await watchDog;++ let currentURL: string;+ page+ .waitForSelector("img", { visible: true })+ .then(() => console.log("First URL with image: " + currentURL));+ for (currentURL of [+ "https://example.com",+ "https://google.com",+ "https://bbc.com"+ ]) {+ await page.goto(currentURL);+ }++ page.keyboard.type("Hello World!");+ page.keyboard.press("ArrowLeft");++ page.keyboard.down("Shift");+ // tslint:disable-next-line prefer-for-of+ for (let i = 0; i < " World".length; i++) {+ page.keyboard.press("ArrowLeft");+ }+ page.keyboard.up("Shift");+ page.keyboard.press("Backspace");+ page.keyboard.sendCharacter("嗨");++ await page.tracing.start({ path: "trace.json" });+ await page.goto("https://www.google.com");+ await page.tracing.stop();++ page.on("dialog", async dialog => {+ console.log(dialog.message());+ await dialog.dismiss();+ browser.close();+ });++ const inputElement = (await page.$("input[type=submit]"))!;+ await inputElement.click();+});++// Example with launch options+(async () => {+ const browser = await playwright.launch({+ args: [+ '--no-sandbox',+ '--disable-setuid-sandbox',+ ],+ handleSIGINT: true,+ handleSIGHUP: true,+ handleSIGTERM: true,+ });+ const page = await browser.newPage();+ await page.goto("https://example.com");+ await page.screenshot({ path: "example.png" });++ browser.close();+})();++// Test v0.12 features+(async () => {+ const browser = await playwright.launch({+ devtools: true,+ env: {+ JEST_TEST: true+ }+ });+ const page = await browser.newPage();+ const button = (await page.$("#myButton"))!;+ const div = (await page.$("#myDiv"))!;+ const input = (await page.$("#myInput"))!;++ if (!button)+ throw new Error('Unable to select myButton');++ if (!input)+ throw new Error('Unable to select myInput');++ await page.addStyleTag({+ url: "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"+ });++ console.log(page.url());++ page.type("#myInput", "Hello World!");++ page.on("console", (event: playwright.ConsoleMessage, ...args: any[]) => {+ console.log(event.text, event.type);+ for (let i = 0; i < args.length; ++i) console.log(`${i}: ${args[i]}`);+ });++ await button.focus();+ await button.press("Enter");+ await button.screenshot({+ type: "jpeg",+ omitBackground: true,+ clip: {+ x: 0,+ y: 0,+ width: 200,+ height: 100+ }+ });+ console.log(button.toString());+ input.type("Hello World", { delay: 10 });++ const buttonText = await (await button.getProperty('textContent')).jsonValue();++ await page.deleteCookie(...await page.cookies());++ const metrics = await page.metrics();+ console.log(metrics.Documents, metrics.Frames, metrics.JSEventListeners);++ const navResponse = await page.waitForNavigation({+ timeout: 1000+ });+ console.log(navResponse.ok, navResponse.status, navResponse.url, navResponse.headers);++ // evaluate example+ const bodyHandle = (await page.$('body'))!;+ const html = await page.evaluate((body : HTMLBodyElement) => body.innerHTML, bodyHandle);+ await bodyHandle.dispose();++ // getProperties example+ const handle = await page.evaluateHandle(() => ({ window, document }));+ const properties = await handle.getProperties();+ const windowHandle = properties.get('window');+ const documentHandle = properties.get('document');+ await handle.dispose();++ // queryObjects example+ // Create a Map object+ await page.evaluate(() => (window as any).map = new Map());+ // Get a handle to the Map object prototype+ const mapPrototype = await page.evaluateHandle(() => Map.prototype);+ // Query all map instances into an array+ const mapInstances = await page.queryObjects(mapPrototype);+ // Count amount of map objects in heap+ const count = await page.evaluate((maps: Map<any, any>[]) => maps.length, mapInstances);+ await mapInstances.dispose();+ await mapPrototype.dispose();++ // evaluateHandle example+ const aHandle = await page.evaluateHandle(() => document.body);+ const resultHandle = await page.evaluateHandle((body: Element) => body.innerHTML, aHandle);+ console.log(await resultHandle.jsonValue());+ await resultHandle.dispose();++ browser.close();+})();++// test $eval and $$eval+(async () => {+ const browser = await playwright.launch();+ const page = await browser.newPage();+ await page.goto("https://example.com");+ await page.$eval('#someElement', (element, text: string) => {+ return element.innerHTML = text;+ }, 'hey');++ let elementText = await page.$$eval('.someClassName', (elements) => {+ console.log(elements.length);+ console.log(elements.map(x => x)[0].textContent);+ return elements[3].innerHTML;+ });++ browser.close();+})();diff --git a/utils/doclint/generate_types/test/tsconfig.json b/utils/doclint/generate_types/test/tsconfig.jsonnew file mode 100644index 0000000000..ea3b5252e8--- /dev/null+++ b/utils/doclint/generate_types/test/tsconfig.json@@ -0,0 +1,12 @@+{+ "compilerOptions": {+ "noImplicitAny": true,+ "target": "es2015",+ "noEmit": true,+ "types": ["node"]+ },+ "include": [+ "test.ts",+ "../../../../index.d.ts"+ ]+}\ No newline at end of filediff --git a/utils/doclint/preprocessor/index.js b/utils/doclint/preprocessor/index.jsnew file mode 100644index 0000000000..2b0b506338--- /dev/null+++ b/utils/doclint/preprocessor/index.js@@ -0,0 +1,131 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const Message = require('../Message');++module.exports.ensureReleasedAPILinks = function(sources, version) {+ // Release version is everything that doesn't include "-".+ const apiLinkRegex = /https:\/\/github.com\/GoogleChrome\/playwright\/blob\/v[^/]*\/docs\/api.md/ig;+ const lastReleasedAPI = `https://github.com/Microsoft/playwright/blob/v${version.split('-')[0]}/docs/api.md`;++ const messages = [];+ for (const source of sources) {+ const text = source.text();+ const newText = text.replace(apiLinkRegex, lastReleasedAPI);+ if (source.setText(newText))+ messages.push(Message.warning(`GEN: updated ${source.projectPath()}`));+ }+ return messages;+};++module.exports.runCommands = function(sources, version) {+ // Release version is everything that doesn't include "-".+ const isReleaseVersion = !version.includes('-');++ const messages = [];+ const commands = [];+ for (const source of sources) {+ const text = source.text();+ const commandStartRegex = /<!--\s*gen:([a-z-]+)\s*-->/ig;+ const commandEndRegex = /<!--\s*gen:stop\s*-->/ig;+ let start;++ while (start = commandStartRegex.exec(text)) { // eslint-disable-line no-cond-assign+ commandEndRegex.lastIndex = commandStartRegex.lastIndex;+ const end = commandEndRegex.exec(text);+ if (!end) {+ messages.push(Message.error(`Failed to find 'gen:stop' for command ${start[0]}`));+ return messages;+ }+ const name = start[1];+ const from = commandStartRegex.lastIndex;+ const to = end.index;+ const originalText = text.substring(from, to);+ commands.push({name, from, to, originalText, source});+ commandStartRegex.lastIndex = commandEndRegex.lastIndex;+ }+ }++ const changedSources = new Set();+ // Iterate commands in reverse order so that edits don't conflict.+ commands.sort((a, b) => b.from - a.from);+ for (const command of commands) {+ let newText = null;+ if (command.name === 'version')+ newText = isReleaseVersion ? 'v' + version : 'Tip-Of-Tree';+ else if (command.name === 'empty-if-release')+ newText = isReleaseVersion ? '' : command.originalText;+ else if (command.name === 'toc')+ newText = generateTableOfContents(command.source.text().substring(command.to));+ if (newText === null)+ messages.push(Message.error(`Unknown command 'gen:${command.name}'`));+ else if (applyCommand(command, newText))+ changedSources.add(command.source);+ }+ for (const source of changedSources)+ messages.push(Message.warning(`GEN: updated ${source.projectPath()}`));+ return messages;+};++/**+ * @param {{name: string, from: number, to: number, source: !Source}} command+ * @param {string} editText+ * @return {boolean}+ */+function applyCommand(command, editText) {+ const text = command.source.text();+ const newText = text.substring(0, command.from) + editText + text.substring(command.to);+ return command.source.setText(newText);+}++function generateTableOfContents(mdText) {+ const ids = new Set();+ const titles = [];+ let insideCodeBlock = false;+ for (const aLine of mdText.split('\n')) {+ const line = aLine.trim();+ if (line.startsWith('```')) {+ insideCodeBlock = !insideCodeBlock;+ continue;+ }+ if (!insideCodeBlock && line.startsWith('#'))+ titles.push(line);+ }+ const tocEntries = [];+ for (const title of titles) {+ const [, nesting, name] = title.match(/^(#+)\s+(.*)$/);+ const delinkifiedName = name.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');+ const id = delinkifiedName.trim().toLowerCase().replace(/\s/g, '-').replace(/[^-0-9a-zа-яё]/ig, '');+ let dedupId = id;+ let counter = 0;+ while (ids.has(dedupId))+ dedupId = id + '-' + (++counter);+ ids.add(dedupId);+ tocEntries.push({+ level: nesting.length,+ name: delinkifiedName,+ id: dedupId+ });+ }++ const minLevel = Math.min(...tocEntries.map(entry => entry.level));+ tocEntries.forEach(entry => entry.level -= minLevel);+ return '\n' + tocEntries.map(entry => {+ const prefix = entry.level % 2 === 0 ? '-' : '*';+ const padding = ' '.repeat(entry.level);+ return `${padding}${prefix} [${entry.name}](#${entry.id})`;+ }).join('\n') + '\n';+}diff --git a/utils/doclint/preprocessor/test.js b/utils/doclint/preprocessor/test.jsnew file mode 100644index 0000000000..75781e8662--- /dev/null+++ b/utils/doclint/preprocessor/test.js@@ -0,0 +1,215 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {runCommands, ensureReleasedAPILinks} = require('.');+const Source = require('../Source');+const {TestRunner, Reporter, Matchers} = require('../../testrunner/');+const runner = new TestRunner();+new Reporter(runner);++const {describe, xdescribe, fdescribe} = runner;+const {it, fit, xit} = runner;+const {beforeAll, beforeEach, afterAll, afterEach} = runner;+const {expect} = new Matchers();++describe('ensureReleasedAPILinks', function() {+ it('should work with non-release version', function() {+ const source = new Source('doc.md', `+ [API](https://github.com/Microsoft/playwright/blob/v1.1.0/docs/api.md#class-page)+ `);+ const messages = ensureReleasedAPILinks([source], '1.3.0-post');+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('warning');+ expect(messages[0].text).toContain('doc.md');+ expect(source.text()).toBe(`+ [API](https://github.com/Microsoft/playwright/blob/v1.3.0/docs/api.md#class-page)+ `);+ });+ it('should work with release version', function() {+ const source = new Source('doc.md', `+ [API](https://github.com/Microsoft/playwright/blob/v1.1.0/docs/api.md#class-page)+ `);+ const messages = ensureReleasedAPILinks([source], '1.3.0');+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('warning');+ expect(messages[0].text).toContain('doc.md');+ expect(source.text()).toBe(`+ [API](https://github.com/Microsoft/playwright/blob/v1.3.0/docs/api.md#class-page)+ `);+ });+ it('should keep master links intact', function() {+ const source = new Source('doc.md', `+ [API](https://github.com/Microsoft/playwright/blob/master/docs/api.md#class-page)+ `);+ const messages = ensureReleasedAPILinks([source], '1.3.0');+ expect(messages.length).toBe(0);+ expect(source.text()).toBe(`+ [API](https://github.com/Microsoft/playwright/blob/master/docs/api.md#class-page)+ `);+ });+});++describe('runCommands', function() {+ it('should throw for unknown command', function() {+ const source = new Source('doc.md', `+ <!-- gen:unknown-command -->something<!-- gen:stop -->+ `);+ const messages = runCommands([source], '1.1.1');+ expect(source.hasUpdatedText()).toBe(false);+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('error');+ expect(messages[0].text).toContain('Unknown command');+ });+ describe('gen:version', function() {+ it('should work', function() {+ const source = new Source('doc.md', `+ Playwright <!-- gen:version -->XXX<!-- gen:stop -->+ `);+ const messages = runCommands([source], '1.2.0');+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('warning');+ expect(messages[0].text).toContain('doc.md');+ expect(source.text()).toBe(`+ Playwright <!-- gen:version -->v1.2.0<!-- gen:stop -->+ `);+ });+ it('should work for *-post versions', function() {+ const source = new Source('doc.md', `+ Playwright <!-- gen:version -->XXX<!-- gen:stop -->+ `);+ const messages = runCommands([source], '1.2.0-post');+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('warning');+ expect(messages[0].text).toContain('doc.md');+ expect(source.text()).toBe(`+ Playwright <!-- gen:version -->Tip-Of-Tree<!-- gen:stop -->+ `);+ });+ it('should tolerate different writing', function() {+ const source = new Source('doc.md', `Playwright v<!-- gEn:version -->WHAT+<!-- GEN:stop -->`);+ runCommands([source], '1.1.1');+ expect(source.text()).toBe(`Playwright v<!-- gEn:version -->v1.1.1<!-- GEN:stop -->`);+ });+ it('should not tolerate missing gen:stop', function() {+ const source = new Source('doc.md', `<!--GEN:version-->`);+ const messages = runCommands([source], '1.2.0');+ expect(source.hasUpdatedText()).toBe(false);+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('error');+ expect(messages[0].text).toContain(`Failed to find 'gen:stop'`);+ });+ });+ describe('gen:empty-if-release', function() {+ it('should clear text when release version', function() {+ const source = new Source('doc.md', `+ <!-- gen:empty-if-release -->XXX<!-- gen:stop -->+ `);+ const messages = runCommands([source], '1.1.1');+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('warning');+ expect(messages[0].text).toContain('doc.md');+ expect(source.text()).toBe(`+ <!-- gen:empty-if-release --><!-- gen:stop -->+ `);+ });+ it('should keep text when non-release version', function() {+ const source = new Source('doc.md', `+ <!-- gen:empty-if-release -->XXX<!-- gen:stop -->+ `);+ const messages = runCommands([source], '1.1.1-post');+ expect(messages.length).toBe(0);+ expect(source.text()).toBe(`+ <!-- gen:empty-if-release -->XXX<!-- gen:stop -->+ `);+ });+ });+ describe('gen:toc', function() {+ it('should work', () => {+ const source = new Source('doc.md', `<!-- gen:toc -->XXX<!-- gen:stop -->+ ### class: page+ #### page.$+ #### page.$$`);+ const messages = runCommands([source], '1.3.0');+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('warning');+ expect(messages[0].text).toContain('doc.md');+ expect(source.text()).toBe(`<!-- gen:toc -->+- [class: page](#class-page)+ * [page.$](#page)+ * [page.$$](#page-1)+<!-- gen:stop -->+ ### class: page+ #### page.$+ #### page.$$`);+ });+ it('should work with code blocks', () => {+ const source = new Source('doc.md', `<!-- gen:toc -->XXX<!-- gen:stop -->+ ### class: page++ \`\`\`bash+ # yo comment+ \`\`\`+ `);+ const messages = runCommands([source], '1.3.0');+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('warning');+ expect(messages[0].text).toContain('doc.md');+ expect(source.text()).toBe(`<!-- gen:toc -->+- [class: page](#class-page)+<!-- gen:stop -->+ ### class: page++ \`\`\`bash+ # yo comment+ \`\`\`+ `);+ });+ it('should work with links in titles', () => {+ const source = new Source('doc.md', `<!-- gen:toc -->XXX<!-- gen:stop -->+ ### some [link](#foobar) here+ `);+ const messages = runCommands([source], '1.3.0');+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('warning');+ expect(messages[0].text).toContain('doc.md');+ expect(source.text()).toBe(`<!-- gen:toc -->+- [some link here](#some-link-here)+<!-- gen:stop -->+ ### some [link](#foobar) here+ `);+ });+ });+ it('should work with multiple commands', function() {+ const source = new Source('doc.md', `+ <!-- gen:version -->XXX<!-- gen:stop -->+ <!-- gen:empty-if-release -->YYY<!-- gen:stop -->+ <!-- gen:version -->ZZZ<!-- gen:stop -->+ `);+ const messages = runCommands([source], '1.1.1');+ expect(messages.length).toBe(1);+ expect(messages[0].type).toBe('warning');+ expect(messages[0].text).toContain('doc.md');+ expect(source.text()).toBe(`+ <!-- gen:version -->v1.1.1<!-- gen:stop -->+ <!-- gen:empty-if-release --><!-- gen:stop -->+ <!-- gen:version -->v1.1.1<!-- gen:stop -->+ `);+ });+});++runner.run();+diff --git a/utils/fetch_devices.js b/utils/fetch_devices.jsnew file mode 100755index 0000000000..9d03e9195a--- /dev/null+++ b/utils/fetch_devices.js@@ -0,0 +1,241 @@+#!/usr/bin/env node+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const util = require('util');+const fs = require('fs');+const path = require('path');+const playwright = require('..');+const DEVICES_URL = 'https://raw.githubusercontent.com/ChromeDevTools/devtools-frontend/master/front_end/emulated_devices/module.json';++const template = `/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports = %s;+for (const device of module.exports)+ module.exports[device.name] = device;+`;++const help = `Usage: node ${path.basename(__filename)} [-u <from>] <outputPath>+ -u, --url The URL to load devices descriptor from. If not set,+ devices will be fetched from the tip-of-tree of DevTools+ frontend.++ -h, --help Show this help message++Fetch Chrome DevTools front-end emulation devices from given URL, convert them to playwright+devices and save to the <outputPath>.+`;++const argv = require('minimist')(process.argv.slice(2), {+ alias: { u: 'url', h: 'help' },+});++if (argv.help) {+ console.log(help);+ return;+}++const url = argv.url || DEVICES_URL;+const outputPath = argv._[0];+if (!outputPath) {+ console.log('ERROR: output file name is missing. Use --help for help.');+ return;+}++main(url);++async function main(url) {+ const browser = await playwright.launch();+ const chromeVersion = (await browser.version()).split('/').pop();+ await browser.close();+ console.log('GET ' + url);+ const text = await httpGET(url);+ let json = null;+ try {+ json = JSON.parse(text);+ } catch (e) {+ console.error(`FAILED: error parsing response - ${e.message}`);+ return;+ }+ const devicePayloads = json.extensions.filter(extension => extension.type === 'emulated-device').map(extension => extension.device);+ let devices = [];+ for (const payload of devicePayloads) {+ let names = [];+ if (payload.title === 'iPhone 6/7/8')+ names = ['iPhone 6', 'iPhone 7', 'iPhone 8'];+ else if (payload.title === 'iPhone 6/7/8 Plus')+ names = ['iPhone 6 Plus', 'iPhone 7 Plus', 'iPhone 8 Plus'];+ else if (payload.title === 'iPhone 5/SE')+ names = ['iPhone 5', 'iPhone SE'];+ else+ names = [payload.title];+ for (const name of names) {+ const device = createDevice(chromeVersion, name, payload, false);+ const landscape = createDevice(chromeVersion, name, payload, true);+ devices.push(device);+ if (landscape.viewport.width !== device.viewport.width || landscape.viewport.height !== device.viewport.height)+ devices.push(landscape);+ }+ }+ devices = devices.filter(device => device.viewport.isMobile);+ devices.sort((a, b) => a.name.localeCompare(b.name));+ // Use single-quotes instead of double-quotes to conform with codestyle.+ const serialized = JSON.stringify(devices, null, 2)+ .replace(/'/g, `\\'`)+ .replace(/"/g, `'`);+ const result = util.format(template, serialized);+ fs.writeFileSync(outputPath, result, 'utf8');+}++/**+ * @param {string} chromeVersion+ * @param {string} deviceName+ * @param {*} descriptor+ * @param {boolean} landscape+ * @return {!Object}+ */+function createDevice(chromeVersion, deviceName, descriptor, landscape) {+ const devicePayload = loadFromJSONV1(descriptor);+ const viewportPayload = landscape ? devicePayload.horizontal : devicePayload.vertical;+ return {+ name: deviceName + (landscape ? ' landscape' : ''),+ userAgent: devicePayload.userAgent.includes('%s') ? util.format(devicePayload.userAgent, chromeVersion) : devicePayload.userAgent,+ viewport: {+ width: viewportPayload.width,+ height: viewportPayload.height,+ deviceScaleFactor: devicePayload.deviceScaleFactor,+ isMobile: devicePayload.capabilities.includes('mobile'),+ hasTouch: devicePayload.capabilities.includes('touch'),+ isLandscape: landscape || false+ }+ };+}++/**+ * @param {*} json+ * @return {?Object}+ */+function loadFromJSONV1(json) {+ /**+ * @param {*} object+ * @param {string} key+ * @param {string} type+ * @param {*=} defaultValue+ * @return {*}+ */+ function parseValue(object, key, type, defaultValue) {+ if (typeof object !== 'object' || object === null || !object.hasOwnProperty(key)) {+ if (typeof defaultValue !== 'undefined')+ return defaultValue;+ throw new Error('Emulated device is missing required property \'' + key + '\'');+ }+ const value = object[key];+ if (typeof value !== type || value === null)+ throw new Error('Emulated device property \'' + key + '\' has wrong type \'' + typeof value + '\'');+ return value;+ }++ /**+ * @param {*} object+ * @param {string} key+ * @return {number}+ */+ function parseIntValue(object, key) {+ const value = /** @type {number} */ (parseValue(object, key, 'number'));+ if (value !== Math.abs(value))+ throw new Error('Emulated device value \'' + key + '\' must be integer');+ return value;+ }++ /**+ * @param {*} json+ * @return {!{width: number, height: number}}+ */+ function parseOrientation(json) {+ const result = {};+ const minDeviceSize = 50;+ const maxDeviceSize = 9999;+ result.width = parseIntValue(json, 'width');+ if (result.width < 0 || result.width > maxDeviceSize ||+ result.width < minDeviceSize)+ throw new Error('Emulated device has wrong width: ' + result.width);++ result.height = parseIntValue(json, 'height');+ if (result.height < 0 || result.height > maxDeviceSize ||+ result.height < minDeviceSize)+ throw new Error('Emulated device has wrong height: ' + result.height);++ return /** @type {!{width: number, height: number}} */ (result);+ }++ const result = {};+ result.type = /** @type {string} */ (parseValue(json, 'type', 'string'));+ result.userAgent = /** @type {string} */ (parseValue(json, 'user-agent', 'string'));++ const capabilities = parseValue(json, 'capabilities', 'object', []);+ if (!Array.isArray(capabilities))+ throw new Error('Emulated device capabilities must be an array');+ result.capabilities = [];+ for (let i = 0; i < capabilities.length; ++i) {+ if (typeof capabilities[i] !== 'string')+ throw new Error('Emulated device capability must be a string');+ result.capabilities.push(capabilities[i]);+ }++ result.deviceScaleFactor = /** @type {number} */ (parseValue(json['screen'], 'device-pixel-ratio', 'number'));+ if (result.deviceScaleFactor < 0 || result.deviceScaleFactor > 100)+ throw new Error('Emulated device has wrong deviceScaleFactor: ' + result.deviceScaleFactor);++ result.vertical = parseOrientation(parseValue(json['screen'], 'vertical', 'object'));+ result.horizontal = parseOrientation(parseValue(json['screen'], 'horizontal', 'object'));+ return result;+}++/**+ * @param {url}+ * @return {!Promise}+ */+function httpGET(url) {+ let fulfill, reject;+ const promise = new Promise((res, rej) => {+ fulfill = res;+ reject = rej;+ });+ const driver = url.startsWith('https://') ? require('https') : require('http');+ const request = driver.get(url, response => {+ let data = '';+ response.setEncoding('utf8');+ response.on('data', chunk => data += chunk);+ response.on('end', () => fulfill(data));+ response.on('error', reject);+ });+ request.on('error', reject);+ return promise;+}diff --git a/utils/flakiness-dashboard/FlakinessDashboard.js b/utils/flakiness-dashboard/FlakinessDashboard.jsnew file mode 100644index 0000000000..4080951da8--- /dev/null+++ b/utils/flakiness-dashboard/FlakinessDashboard.js@@ -0,0 +1,218 @@+const fs = require('fs');+const os = require('os');+const path = require('path');+const spawn = require('child_process').spawn;+const debug = require('debug')('flakiness');++const rmAsync = promisify(require('rimraf'));+const mkdtempAsync = promisify(fs.mkdtemp);+const readFileAsync = promisify(fs.readFile);+const writeFileAsync = promisify(fs.writeFile);++const TMP_FOLDER = path.join(os.tmpdir(), 'flakiness_tmp_folder-');++const RED_COLOR = '\x1b[31m';+const GREEN_COLOR = '\x1b[32m';+const YELLOW_COLOR = '\x1b[33m';+const RESET_COLOR = '\x1b[0m';++const DASHBOARD_VERSION = 1;+const DASHBOARD_FILENAME = 'dashboard.json';+const DASHBOARD_MAX_BUILDS = 100;++class FlakinessDashboard {+ static async getCommitDetails(repoPath, ref = 'HEAD') {+ const {stdout: timestamp} = await spawnAsyncOrDie('git', 'show', '-s', '--format=%ct', ref, {cwd: repoPath});+ const {stdout: sha} = await spawnAsyncOrDie('git', 'rev-parse', ref, {cwd: repoPath});+ return {timestamp: timestamp * 1000, sha: sha.trim()};+ }++ constructor({build, commit, dashboardRepo}) {+ if (!commit)+ throw new Error('"options.commit" must be specified!');+ if (!commit.sha)+ throw new Error('"options.commit.sha" must be specified!');+ if (!commit.timestamp)+ throw new Error('"options.commit.timestamp" must be specified!');+ if (!build)+ throw new Error('"options.build" must be specified!');+ if (!build.url)+ throw new Error('"options.build.url" must be specified!');+ if (!dashboardRepo.branch)+ throw new Error('"options.dashboardRepo.branch" must be specified!');+ this._dashboardRepo = dashboardRepo;+ this._build = new Build(Date.now(), build.url, commit, []);+ }++ reportTestResult(test) {+ this._build._tests.push(test);+ }++ setBuildResult(result) {+ this._build._result = result;+ }++ async uploadAndCleanup() {+ console.log(`\n${YELLOW_COLOR}=== UPLOADING Flakiness Dashboard${RESET_COLOR}`);+ const startTimestamp = Date.now();+ const branch = this._dashboardRepo.branch.toLowerCase().replace(/\s/g, '-').replace(/[^-0-9a-zа-яё]/ig, '');+ console.log(` > Dashboard URL: ${this._dashboardRepo.url}`);+ console.log(` > Dashboard Branch: ${branch}`);+ const git = await Git.initialize(this._dashboardRepo.url, branch, this._dashboardRepo.username, this._dashboardRepo.email, this._dashboardRepo.password);+ console.log(` > Dashboard Checkout: ${git.path()}`);++ // Do at max 7 attempts to upload changes to github.+ let success = false;+ const MAX_ATTEMPTS = 7;+ for (let i = 0; !success && i < MAX_ATTEMPTS; ++i) {+ await saveBuildToDashboard(git.path(), this._build);+ // if push went through - great! We're done!+ if (await git.commitAllAndPush(`update dashboard\n\nbuild: ${this._build._url}`)) {+ success = true;+ console.log(` > Push attempt ${YELLOW_COLOR}${i + 1}${RESET_COLOR} of ${YELLOW_COLOR}${MAX_ATTEMPTS}${RESET_COLOR}: ${GREEN_COLOR}SUCCESS${RESET_COLOR}`);+ } else {+ // Otherwise - wait random time between 3 and 11 seconds.+ const cooldown = 3000 + Math.round(Math.random() * 1000) * 8;+ console.log(` > Push attempt ${YELLOW_COLOR}${i + 1}${RESET_COLOR} of ${YELLOW_COLOR}${MAX_ATTEMPTS}${RESET_COLOR}: ${RED_COLOR}FAILED${RESET_COLOR}, cooldown ${YELLOW_COLOR}${cooldown / 1000}${RESET_COLOR} seconds`);+ await new Promise(x => setTimeout(x, cooldown));+ // Reset our generated dashboard and pull from origin.+ await git.hardResetToOriginMaster();+ await git.pullFromOrigin();+ }+ }+ await rmAsync(git.path());+ console.log(` > TOTAL TIME: ${YELLOW_COLOR}${(Date.now() - startTimestamp) / 1000}${RESET_COLOR} seconds`);+ if (success)+ console.log(`${YELLOW_COLOR}=== COMPLETE${RESET_COLOR}`);+ else+ console.log(`${RED_COLOR}=== FAILED${RESET_COLOR}`);+ console.log('');+ }+}++async function saveBuildToDashboard(dashboardPath, build) {+ const filePath = path.join(dashboardPath, DASHBOARD_FILENAME);+ let data = null;+ try {+ data = JSON.parse(await readFileAsync(filePath));+ } catch (e) {+ // Looks like there's no dashboard yet - create one.+ data = {builds: []};+ }+ if (!data.builds)+ throw new Error('Unrecognized dashboard format!');+ data.builds.push({+ version: DASHBOARD_VERSION,+ result: build._result,+ timestamp: build._timestamp,+ url: build._url,+ commit: build._commit,+ tests: build._tests,+ });+ if (data.builds.length > DASHBOARD_MAX_BUILDS)+ data.builds = data.builds.slice(data.builds.length - DASHBOARD_MAX_BUILDS);+ await writeFileAsync(filePath, JSON.stringify(data));+}++class Build {+ constructor(timestamp, url, commit, tests) {+ this._timestamp = timestamp;+ this._url = url;+ this._commit = commit;+ this._tests = tests;+ this._result = undefined;+ }+}++module.exports = {FlakinessDashboard};++function promisify(nodeFunction) {+ function promisified(...args) {+ return new Promise((resolve, reject) => {+ function callback(err, ...result) {+ if (err)+ return reject(err);+ if (result.length === 1)+ return resolve(result[0]);+ return resolve(result);+ }+ nodeFunction.call(null, ...args, callback);+ });+ }+ return promisified;+}++class Git {+ static async initialize(url, branch, username, email, password) {+ let schemeIndex = url.indexOf('://');+ if (schemeIndex === -1)+ throw new Error(`Malformed URL "${url}": expected to start with "https://"`);+ schemeIndex += '://'.length;+ url = url.substring(0, schemeIndex) + username + ':' + password + '@' + url.substring(schemeIndex);+ const repoPath = await mkdtempAsync(TMP_FOLDER);+ // Check existance of a remote branch for this bot.+ const {stdout} = await spawnAsync('git', 'ls-remote', '--heads', url, branch);+ // If there is no remote branch for this bot - create one.+ if (!stdout.includes(branch)) {+ await spawnAsyncOrDie('git', 'clone', '--no-checkout', '--depth=1', url, repoPath);++ await spawnAsyncOrDie('git', 'checkout', '--orphan', branch, {cwd: repoPath});+ await spawnAsyncOrDie('git', 'reset', '--hard', {cwd: repoPath});+ } else {+ await spawnAsyncOrDie('git', 'clone', '--single-branch', '--branch', `${branch}`, '--depth=1', url, repoPath);+ }+ await spawnAsyncOrDie('git', 'config', 'user.email', `"${email}"`, {cwd: repoPath});+ await spawnAsyncOrDie('git', 'config', 'user.name', `"${username}"`, {cwd: repoPath});+ return new Git(repoPath, url, branch, username);+ }++ async commitAllAndPush(message) {+ await spawnAsyncOrDie('git', 'add', '.', {cwd: this._repoPath});+ await spawnAsyncOrDie('git', 'commit', '-m', `${message}`, '--author', '"playwright-flakiness <[email protected]>"', {cwd: this._repoPath});+ const {code} = await spawnAsync('git', 'push', 'origin', this._branch, {cwd: this._repoPath});+ return code === 0;+ }++ async hardResetToOriginMaster() {+ await spawnAsyncOrDie('git', 'reset', '--hard', `origin/${this._branch}`, {cwd: this._repoPath});+ }++ async pullFromOrigin() {+ await spawnAsyncOrDie('git', 'pull', 'origin', this._branch, {cwd: this._repoPath});+ }++ constructor(repoPath, url, branch, username) {+ this._repoPath = repoPath;+ this._url = url;+ this._branch = branch;+ this._username = username;+ }++ path() {+ return this._repoPath;+ }+}++async function spawnAsync(command, ...args) {+ let options = {};+ if (args.length && args[args.length - 1].constructor.name !== 'String')+ options = args.pop();+ const cmd = spawn(command, args, options);+ let stdout = '';+ let stderr = '';+ cmd.stdout.on('data', data => stdout += data);+ cmd.stderr.on('data', data => stderr += data);+ const code = await new Promise(x => cmd.once('close', x));+ if (stdout)+ debug(stdout);+ if (stderr)+ debug(stderr);+ return {code, stdout, stderr};+}++async function spawnAsyncOrDie(command, ...args) {+ const {code, stdout, stderr} = await spawnAsync(command, ...args);+ if (code !== 0)+ throw new Error(`Failed to executed: "${command} ${args.join(' ')}".\n\n=== STDOUT ===\n${stdout}\n\n\n=== STDERR ===\n${stderr}`);+ return {stdout, stderr};+}diff --git a/utils/flakiness-dashboard/index.js b/utils/flakiness-dashboard/index.jsnew file mode 100644index 0000000000..bb6ec923fa--- /dev/null+++ b/utils/flakiness-dashboard/index.js@@ -0,0 +1,3 @@+const {FlakinessDashboard} = require('./FlakinessDashboard');++module.exports = {FlakinessDashboard};diff --git a/utils/prepare_playwright_core.js b/utils/prepare_playwright_core.jsnew file mode 100644index 0000000000..f96053c665--- /dev/null+++ b/utils/prepare_playwright_core.js@@ -0,0 +1,25 @@+#!/usr/bin/env node+/**+ * Copyright 2018 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const fs = require('fs');+const path = require('path');++const packagePath = path.join(__dirname, '..', 'package.json');+const json = require(packagePath);++json.name = 'playwright-core';+fs.writeFileSync(packagePath, JSON.stringify(json, null, ' '));diff --git a/utils/protocol-types-generator/index.js b/utils/protocol-types-generator/index.jsnew file mode 100644index 0000000000..5dbe7e5835--- /dev/null+++ b/utils/protocol-types-generator/index.js@@ -0,0 +1,117 @@+// @ts-check+const path = require('path');+const fs = require('fs');++async function generateChromeProtocol(revision) {+ const outputPath = path.join(__dirname, '..', '..', 'src', 'chromium', 'protocol.d.ts');+ if (revision.local && fs.existsSync(outputPath))+ return;+ const playwright = await require('../../chromium');+ const browser = await playwright.launch({executablePath: revision.executablePath});+ const origin = browser.wsEndpoint().match(/ws:\/\/([0-9A-Za-z:\.]*)\//)[1];+ const page = await browser.newPage();+ await page.goto(`http://${origin}/json/protocol`);+ const json = JSON.parse(await page.evaluate(() => document.documentElement.innerText));+ const version = await browser.version();+ await browser.close();+ fs.writeFileSync(outputPath, jsonToTS(json));+ console.log(`Wrote protocol.d.ts for ${version} to ${path.relative(process.cwd(), outputPath)}`);+}+++async function generateWebKitProtocol(revision) {+ const outputPath = path.join(__dirname, '..', '..', 'src', 'webkit', 'protocol.d.ts');+ if (revision.local && fs.existsSync(outputPath))+ return;+ const json = JSON.parse(fs.readFileSync(path.join(revision.folderPath, 'protocol.json'), 'utf8'));+ fs.writeFileSync(outputPath, jsonToTS({domains: json}));+ console.log(`Wrote protocol.d.ts for WebKit to ${path.relative(process.cwd(), outputPath)}`);+}++function jsonToTS(json) {+ return `// This is generated from /utils/protocol-types-generator/index.js+type binary = string;+export module Protocol {${json.domains.map(domain => `${domain.description ? `+ /**+ * ${domain.description}+ */` : ''}+ export module ${domain.domain} {${(domain.types || []).map(type => `${type.description ? `+ /**+ * ${type.description}+ */` : ''}${type.properties ? `+ export interface ${type.id} {${(type.properties || []).map(property => `${property.description ? `+ /**+ * ${property.description}+ */` : ''}+ ${property.name}${property.optional ? '?' : ''}: ${typeOfProperty(property)};`).join(``)}+ }` : `+ export type ${type.id} = ${typeOfProperty(type)};`}`).join('')}+ ${(domain.events || []).map(event => `${event.description ? `+ /**+ * ${event.description}+ */` : ''}${event.parameters ? `+ export type ${event.name}Payload = {${event.parameters.map(parameter => `${parameter.description ? `+ /**+ * ${parameter.description}+ */` : ''}+ ${parameter.name}${parameter.optional ? '?' : ''}: ${typeOfProperty(parameter)};`).join(``)}+ }` : `+ export type ${event.name}Payload = void;`}`).join('')}+ ${(domain.commands || []).map(command => `${command.description ? `+ /**+ * ${command.description}+ */` : ''}+ export type ${command.name}Parameters = {${(command.parameters || []).map(parameter => `${parameter.description ? `+ /**+ * ${parameter.description}+ */` : ''}+ ${parameter.name}${parameter.optional ? '?' : ''}: ${typeOfProperty(parameter)};`).join(``)}+ }+ export type ${command.name}ReturnValue = {${(command.returns || []).map(retVal => `${retVal.description ? `+ /**+ * ${retVal.description}+ */` : ''}+ ${retVal.name}${retVal.optional ? '?' : ''}: ${typeOfProperty(retVal)};`).join(``)}+ }`).join('')}+ }+ `).join('')}+ export interface Events {${json.domains.map(domain => (domain.events || []).map(event => `+ "${domain.domain}.${event.name}": ${domain.domain}.${event.name}Payload;`).join('')).join('')}+ }+ export interface CommandParameters {${json.domains.map(domain => (domain.commands || []).map(command => `+ "${domain.domain}.${command.name}": ${domain.domain}.${command.name}Parameters;`).join('')).join('')}+ }+ export interface CommandReturnValues {${json.domains.map(domain => (domain.commands || []).map(command => `+ "${domain.domain}.${command.name}": ${domain.domain}.${command.name}ReturnValue;`).join('')).join('')}+ }+}+`;+}+++/**+ * @typedef {Object} Property+ * @property {string=} $ref+ * @property {!Array=} enum+ * @property {string=} type+ * @property {!Property=} items+ * @property {string=} description+ */++/**+ * @param {!Property} property+ * @param {string=} domain+ */+function typeOfProperty(property, domain) {+ if (property.$ref) return property.$ref.includes('.') || !domain ? property.$ref : domain + '.' + property.$ref;+ if (property.enum) return property.enum.map(value => JSON.stringify(value)).join('|');+ switch (property.type) {+ case 'array':+ return typeOfProperty(property.items, domain) + '[]';+ case 'integer':+ return 'number';+ }+ return property.type;+}++module.exports = {generateChromeProtocol, generateWebKitProtocol};\ No newline at end of filediff --git a/utils/testrunner/.npmignore b/utils/testrunner/.npmignorenew file mode 100644index 0000000000..7b4e15d4a0--- /dev/null+++ b/utils/testrunner/.npmignore@@ -0,0 +1,13 @@+# exclude all examples and README.md+examples/+README.md++# repeats from .gitignore+node_modules+.npmignore+.DS_Store+*.swp+*.pyc+.vscode+package-lock.json+yarn.lockdiff --git a/utils/testrunner/LICENSE b/utils/testrunner/LICENSEnew file mode 100644index 0000000000..afdfe50e72--- /dev/null+++ b/utils/testrunner/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2017 Google Inc.++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/utils/testrunner/Matchers.js b/utils/testrunner/Matchers.jsnew file mode 100644index 0000000000..000751d43c--- /dev/null+++ b/utils/testrunner/Matchers.js@@ -0,0 +1,130 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++module.exports = class Matchers {+ constructor(customMatchers = {}) {+ this._matchers = {};+ Object.assign(this._matchers, DefaultMatchers);+ Object.assign(this._matchers, customMatchers);+ this.expect = this.expect.bind(this);+ }++ addMatcher(name, matcher) {+ this._matchers[name] = matcher;+ }++ expect(value) {+ return new Expect(value, this._matchers);+ }+};++class Expect {+ constructor(value, matchers) {+ this.not = {};+ this.not.not = this;+ for (const matcherName of Object.keys(matchers)) {+ const matcher = matchers[matcherName];+ this[matcherName] = applyMatcher.bind(null, matcherName, matcher, false /* inverse */, value);+ this.not[matcherName] = applyMatcher.bind(null, matcherName, matcher, true /* inverse */, value);+ }++ function applyMatcher(matcherName, matcher, inverse, value, ...args) {+ const result = matcher.call(null, value, ...args);+ const message = `expect.${inverse ? 'not.' : ''}${matcherName} failed` + (result.message ? `: ${result.message}` : '');+ if (result.pass === inverse)+ throw new Error(message);+ }+ }+}++const DefaultMatchers = {+ toBe: function(value, other, message) {+ message = message || `${value} == ${other}`;+ return { pass: value === other, message };+ },++ toBeFalsy: function(value, message) {+ message = message || `${value}`;+ return { pass: !value, message };+ },++ toBeTruthy: function(value, message) {+ message = message || `${value}`;+ return { pass: !!value, message };+ },++ toBeGreaterThan: function(value, other, message) {+ message = message || `${value} > ${other}`;+ return { pass: value > other, message };+ },++ toBeGreaterThanOrEqual: function(value, other, message) {+ message = message || `${value} >= ${other}`;+ return { pass: value >= other, message };+ },++ toBeLessThan: function(value, other, message) {+ message = message || `${value} < ${other}`;+ return { pass: value < other, message };+ },++ toBeLessThanOrEqual: function(value, other, message) {+ message = message || `${value} <= ${other}`;+ return { pass: value <= other, message };+ },++ toBeNull: function(value, message) {+ message = message || `${value} == null`;+ return { pass: value === null, message };+ },++ toContain: function(value, other, message) {+ message = message || `${value} ⊇ ${other}`;+ return { pass: value.includes(other), message };+ },++ toEqual: function(value, other, message) {+ const valueJson = stringify(value);+ const otherJson = stringify(other);+ message = message || `\n${valueJson} ≈ ${otherJson}`;+ return { pass: valueJson === otherJson, message };+ },++ toBeCloseTo: function(value, other, precision, message) {+ return {+ pass: Math.abs(value - other) < Math.pow(10, -precision),+ message+ };+ },++ toBeInstanceOf: function(value, other, message) {+ message = message || `${value.constructor.name} instanceof ${other.name}`;+ return { pass: value instanceof other, message };+ },+};++function stringify(value) {+ function stabilize(key, object) {+ if (typeof object !== 'object' || object === undefined || object === null)+ return object;+ const result = {};+ for (const key of Object.keys(object).sort())+ result[key] = object[key];+ return result;+ }++ return JSON.stringify(stabilize(null, value), stabilize, 2);+}diff --git a/utils/testrunner/Multimap.js b/utils/testrunner/Multimap.jsnew file mode 100644index 0000000000..6e9c0769a6--- /dev/null+++ b/utils/testrunner/Multimap.js@@ -0,0 +1,95 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++class Multimap {+ constructor() {+ this._map = new Map();+ }++ set(key, value) {+ let set = this._map.get(key);+ if (!set) {+ set = new Set();+ this._map.set(key, set);+ }+ set.add(value);+ }++ get(key) {+ let result = this._map.get(key);+ if (!result)+ result = new Set();+ return result;+ }++ has(key) {+ return this._map.has(key);+ }++ hasValue(key, value) {+ const set = this._map.get(key);+ if (!set)+ return false;+ return set.has(value);+ }++ /**+ * @return {number}+ */+ get size() {+ return this._map.size;+ }++ delete(key, value) {+ const values = this.get(key);+ const result = values.delete(value);+ if (!values.size)+ this._map.delete(key);+ return result;+ }++ deleteAll(key) {+ this._map.delete(key);+ }++ firstValue(key) {+ const set = this._map.get(key);+ if (!set)+ return null;+ return set.values().next().value;+ }++ firstKey() {+ return this._map.keys().next().value;+ }++ valuesArray() {+ const result = [];+ for (const key of this._map.keys())+ result.push(...Array.from(this._map.get(key).values()));+ return result;+ }++ keysArray() {+ return Array.from(this._map.keys());+ }++ clear() {+ this._map.clear();+ }+}++module.exports = Multimap;diff --git a/utils/testrunner/README.md b/utils/testrunner/README.mdnew file mode 100644index 0000000000..8548d52978--- /dev/null+++ b/utils/testrunner/README.md@@ -0,0 +1,61 @@+# TestRunner++This test runner is used internally by Playwright to test Playwright itself.++- testrunner is a *library*: tests are `node.js` scripts+- parallel wrt IO operations+- supports async/await+- modular+- well-isolated state per execution thread++### Installation++```sh+npm install --save-dev @pptr/testrunner+```++### Example++Save the following as `test.js` and run using `node`:++```sh+node test.js+```++```js+const {TestRunner, Reporter, Matchers} = require('@pptr/testrunner');++// Runner holds and runs all the tests+const runner = new TestRunner({+ parallel: 2, // run 2 parallel threads+ timeout: 1000, // setup timeout of 1 second per test+});+// Simple expect-like matchers+const {expect} = new Matchers();++// Extract jasmine-like DSL into the global namespace+const {describe, xdescribe, fdescribe} = runner;+const {it, fit, xit} = runner;+const {beforeAll, beforeEach, afterAll, afterEach} = runner;++// Test hooks can be async.+beforeAll(async state => {+ state.parallelIndex; // either 0 or 1 in this example, depending on the executing thread+ state.foo = 'bar'; // set state for every test+});++describe('math', () => {+ it('to be sane', async (state, test) => {+ state.parallelIndex; // Very first test will always be ran by the 0's thread+ state.foo; // this will be 'bar'+ expect(2 + 2).toBe(4);+ });+});++// Reporter subscribes to TestRunner events and displays information in terminal+const reporter = new Reporter(runner);++// Run all tests.+runner.run();+```+diff --git a/utils/testrunner/Reporter.js b/utils/testrunner/Reporter.jsnew file mode 100644index 0000000000..5e079ff4fe--- /dev/null+++ b/utils/testrunner/Reporter.js@@ -0,0 +1,245 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const RED_COLOR = '\x1b[31m';+const GREEN_COLOR = '\x1b[32m';+const YELLOW_COLOR = '\x1b[33m';+const MAGENTA_COLOR = '\x1b[35m';+const RESET_COLOR = '\x1b[0m';++class Reporter {+ constructor(runner, options = {}) {+ const {+ projectFolder = null,+ showSlowTests = 3,+ verbose = false,+ summary = true,+ } = options;+ this._runner = runner;+ this._projectFolder = projectFolder;+ this._showSlowTests = showSlowTests;+ this._verbose = verbose;+ this._summary = summary;+ this._testCounter = 0;+ runner.on('started', this._onStarted.bind(this));+ runner.on('finished', this._onFinished.bind(this));+ runner.on('teststarted', this._onTestStarted.bind(this));+ runner.on('testfinished', this._onTestFinished.bind(this));+ this._workersState = new Map();+ }++ _onStarted(runnableTests) {+ this._testCounter = 0;+ this._timestamp = Date.now();+ const allTests = this._runner.tests();+ if (allTests.length === runnableTests.length)+ console.log(`Running all ${YELLOW_COLOR}${runnableTests.length}${RESET_COLOR} tests on ${YELLOW_COLOR}${this._runner.parallel()}${RESET_COLOR} worker(s):\n`);+ else+ console.log(`Running ${YELLOW_COLOR}${runnableTests.length}${RESET_COLOR} focused tests out of total ${YELLOW_COLOR}${allTests.length}${RESET_COLOR} on ${YELLOW_COLOR}${this._runner.parallel()}${RESET_COLOR} worker(s):\n`);+ }++ _printTermination(result, message, error) {+ console.log(`${RED_COLOR}## ${result.toUpperCase()} ##${RESET_COLOR}`);+ console.log('Message:');+ console.log(` ${RED_COLOR}${message}${RESET_COLOR}`);+ if (error && error.stack) {+ console.log('Stack:');+ console.log(error.stack.split('\n').map(line => ' ' + line).join('\n'));+ }+ console.log('WORKERS STATE');+ const workerIds = Array.from(this._workersState.keys());+ workerIds.sort((a, b) => a - b);+ for (const workerId of workerIds) {+ const {isRunning, test} = this._workersState.get(workerId);+ let description = '';+ if (isRunning)+ description = `${YELLOW_COLOR}RUNNING${RESET_COLOR}`;+ else if (test.result === 'ok')+ description = `${GREEN_COLOR}OK${RESET_COLOR}`;+ else if (test.result === 'skipped')+ description = `${YELLOW_COLOR}SKIPPED${RESET_COLOR}`;+ else if (test.result === 'failed')+ description = `${RED_COLOR}FAILED${RESET_COLOR}`;+ else if (test.result === 'crashed')+ description = `${RED_COLOR}CRASHED${RESET_COLOR}`;+ else if (test.result === 'timedout')+ description = `${RED_COLOR}TIMEDOUT${RESET_COLOR}`;+ else if (test.result === 'terminated')+ description = `${MAGENTA_COLOR}TERMINATED${RESET_COLOR}`;+ else+ description = `${RED_COLOR}<UNKNOWN>${RESET_COLOR}`;+ console.log(` ${workerId}: [${description}] ${test.fullName} (${formatTestLocation(test)})`);+ }+ process.exitCode = 2;+ }++ _onFinished({result, terminationError, terminationMessage}) {+ this._printTestResults();+ if (terminationMessage || terminationError)+ this._printTermination(result, terminationMessage, terminationError);+ process.exitCode = result === 'ok' ? 0 : 1;+ }++ _printTestResults() {+ // 2 newlines after completing all tests.+ console.log('\n');++ const failedTests = this._runner.failedTests();+ if (this._summary && failedTests.length > 0) {+ console.log('\nFailures:');+ for (let i = 0; i < failedTests.length; ++i) {+ const test = failedTests[i];+ console.log(`${i + 1}) ${test.fullName} (${formatTestLocation(test)})`);+ if (test.result === 'timedout') {+ console.log(' Message:');+ console.log(` ${RED_COLOR}Timeout Exceeded ${this._runner.timeout()}ms${RESET_COLOR}`);+ } else if (test.result === 'crashed') {+ console.log(' Message:');+ console.log(` ${RED_COLOR}CRASHED${RESET_COLOR}`);+ } else {+ console.log(' Message:');+ console.log(` ${RED_COLOR}${test.error.message || test.error}${RESET_COLOR}`);+ console.log(' Stack:');+ if (test.error.stack)+ console.log(this._beautifyStack(test.error.stack));+ }+ if (test.output) {+ console.log(' Output:');+ console.log(test.output.split('\n').map(line => ' ' + line).join('\n'));+ }+ console.log('');+ }+ }++ const skippedTests = this._runner.skippedTests();+ if (this._summary && skippedTests.length > 0) {+ console.log('\nSkipped:');+ for (let i = 0; i < skippedTests.length; ++i) {+ const test = skippedTests[i];+ console.log(`${i + 1}) ${test.fullName} (${formatTestLocation(test)})`);+ console.log(` ${YELLOW_COLOR}Temporary disabled with xit${RESET_COLOR}`);+ }+ }++ if (this._showSlowTests) {+ const slowTests = this._runner.passedTests().sort((a, b) => {+ const aDuration = a.endTimestamp - a.startTimestamp;+ const bDuration = b.endTimestamp - b.startTimestamp;+ return bDuration - aDuration;+ }).slice(0, this._showSlowTests);+ console.log(`\nSlowest tests:`);+ for (let i = 0; i < slowTests.length; ++i) {+ const test = slowTests[i];+ const duration = test.endTimestamp - test.startTimestamp;+ console.log(` (${i + 1}) ${YELLOW_COLOR}${duration / 1000}s${RESET_COLOR} - ${test.fullName} (${formatTestLocation(test)})`);+ }+ }++ const tests = this._runner.tests();+ const executedTests = tests.filter(test => test.result);+ const okTestsLength = executedTests.length - failedTests.length - skippedTests.length;+ let summaryText = '';+ if (failedTests.length || skippedTests.length) {+ const summary = [`ok - ${GREEN_COLOR}${okTestsLength}${RESET_COLOR}`];+ if (failedTests.length)+ summary.push(`failed - ${RED_COLOR}${failedTests.length}${RESET_COLOR}`);+ if (skippedTests.length)+ summary.push(`skipped - ${YELLOW_COLOR}${skippedTests.length}${RESET_COLOR}`);+ summaryText = `(${summary.join(', ')})`;+ }++ console.log(`\nRan ${executedTests.length} ${summaryText} of ${tests.length} test(s)`);+ const milliseconds = Date.now() - this._timestamp;+ const seconds = milliseconds / 1000;+ console.log(`Finished in ${YELLOW_COLOR}${seconds}${RESET_COLOR} seconds`);+ }++ _beautifyStack(stack) {+ if (!this._projectFolder)+ return stack;+ const lines = stack.split('\n').map(line => ' ' + line);+ // Find last stack line that include testrunner code.+ let index = 0;+ while (index < lines.length && !lines[index].includes(__dirname))+ ++index;+ while (index < lines.length && lines[index].includes(__dirname))+ ++index;+ if (index >= lines.length)+ return stack;+ const line = lines[index];+ const fromIndex = line.lastIndexOf(this._projectFolder) + this._projectFolder.length;+ const toIndex = line.lastIndexOf(')');+ lines[index] = line.substring(0, fromIndex) + YELLOW_COLOR + line.substring(fromIndex, toIndex) + RESET_COLOR + line.substring(toIndex);+ return lines.join('\n');+ }++ _onTestStarted(test, workerId) {+ this._workersState.set(workerId, {test, isRunning: true});+ }++ _onTestFinished(test, workerId) {+ this._workersState.set(workerId, {test, isRunning: false});+ if (this._verbose) {+ ++this._testCounter;+ if (test.result === 'ok') {+ console.log(`${this._testCounter}) ${GREEN_COLOR}[ OK ]${RESET_COLOR} ${test.fullName} (${formatTestLocation(test)})`);+ } else if (test.result === 'terminated') {+ console.log(`${this._testCounter}) ${MAGENTA_COLOR}[ TERMINATED ]${RESET_COLOR} ${test.fullName} (${formatTestLocation(test)})`);+ } else if (test.result === 'crashed') {+ console.log(`${this._testCounter}) ${RED_COLOR}[ CRASHED ]${RESET_COLOR} ${test.fullName} (${formatTestLocation(test)})`);+ } else if (test.result === 'skipped') {+ console.log(`${this._testCounter}) ${YELLOW_COLOR}[SKIP]${RESET_COLOR} ${test.fullName} (${formatTestLocation(test)})`);+ } else if (test.result === 'failed') {+ console.log(`${this._testCounter}) ${RED_COLOR}[FAIL]${RESET_COLOR} ${test.fullName} (${formatTestLocation(test)})`);+ console.log(' Message:');+ console.log(` ${RED_COLOR}${test.error.message || test.error}${RESET_COLOR}`);+ console.log(' Stack:');+ if (test.error.stack)+ console.log(this._beautifyStack(test.error.stack));+ if (test.output) {+ console.log(' Output:');+ console.log(test.output.split('\n').map(line => ' ' + line).join('\n'));+ }+ } else if (test.result === 'timedout') {+ console.log(`${this._testCounter}) ${RED_COLOR}[TIME]${RESET_COLOR} ${test.fullName} (${formatTestLocation(test)})`);+ console.log(' Message:');+ console.log(` ${RED_COLOR}Timeout Exceeded ${this._runner.timeout()}ms${RESET_COLOR}`);+ }+ } else {+ if (test.result === 'ok')+ process.stdout.write(`${GREEN_COLOR}.${RESET_COLOR}`);+ else if (test.result === 'skipped')+ process.stdout.write(`${YELLOW_COLOR}*${RESET_COLOR}`);+ else if (test.result === 'failed')+ process.stdout.write(`${RED_COLOR}F${RESET_COLOR}`);+ else if (test.result === 'crashed')+ process.stdout.write(`${RED_COLOR}C${RESET_COLOR}`);+ else if (test.result === 'terminated')+ process.stdout.write(`${MAGENTA_COLOR}.${RESET_COLOR}`);+ else if (test.result === 'timedout')+ process.stdout.write(`${RED_COLOR}T${RESET_COLOR}`);+ }+ }+}++function formatTestLocation(test) {+ const location = test.location;+ if (!location)+ return '';+ return `${YELLOW_COLOR}${location.fileName}:${location.lineNumber}:${location.columnNumber}${RESET_COLOR}`;+}++module.exports = Reporter;diff --git a/utils/testrunner/TestRunner.js b/utils/testrunner/TestRunner.jsnew file mode 100644index 0000000000..b807659150--- /dev/null+++ b/utils/testrunner/TestRunner.js@@ -0,0 +1,474 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const path = require('path');+const EventEmitter = require('events');+const Multimap = require('./Multimap');++const TimeoutError = new Error('Timeout');+const TerminatedError = new Error('Terminated');++const MAJOR_NODEJS_VERSION = parseInt(process.version.substring(1).split('.')[0], 10);++class UserCallback {+ constructor(callback, timeout) {+ this._callback = callback;+ this._terminatePromise = new Promise(resolve => {+ this._terminateCallback = resolve;+ });++ this.timeout = timeout;+ this.location = this._getLocation();+ }++ async run(...args) {+ let timeoutId;+ const timeoutPromise = new Promise(resolve => {+ timeoutId = setTimeout(resolve.bind(null, TimeoutError), this.timeout);+ });+ try {+ return await Promise.race([+ Promise.resolve().then(this._callback.bind(null, ...args)).then(() => null).catch(e => e),+ timeoutPromise,+ this._terminatePromise+ ]);+ } catch (e) {+ return e;+ } finally {+ clearTimeout(timeoutId);+ }+ }++ _getLocation() {+ const error = new Error();+ const stackFrames = error.stack.split('\n').slice(1);+ // Find first stackframe that doesn't point to this file.+ for (let frame of stackFrames) {+ frame = frame.trim();+ if (!frame.startsWith('at '))+ return null;+ if (frame.endsWith(')')) {+ const from = frame.indexOf('(');+ frame = frame.substring(from + 1, frame.length - 1);+ } else {+ frame = frame.substring('at '.length);+ }++ const match = frame.match(/^(.*):(\d+):(\d+)$/);+ if (!match)+ return null;+ const filePath = match[1];+ const lineNumber = match[2];+ const columnNumber = match[3];+ if (filePath === __filename)+ continue;+ const fileName = filePath.split(path.sep).pop();+ return { fileName, filePath, lineNumber, columnNumber };+ }+ return null;+ }++ terminate() {+ this._terminateCallback(TerminatedError);+ }+}++const TestMode = {+ Run: 'run',+ Skip: 'skip',+ Focus: 'focus'+};++const TestResult = {+ Ok: 'ok',+ Skipped: 'skipped', // User skipped the test+ Failed: 'failed', // Exception happened during running+ TimedOut: 'timedout', // Timeout Exceeded while running+ Terminated: 'terminated', // Execution terminated+ Crashed: 'crashed', // If testrunner crashed due to this test+};++class Test {+ constructor(suite, name, callback, declaredMode, timeout, comment) {+ this.suite = suite;+ this.name = name;+ this.fullName = (suite.fullName + ' ' + name).trim();+ this.declaredMode = declaredMode;+ this._userCallback = new UserCallback(callback, timeout);+ this.location = this._userCallback.location;+ this.comment = comment;++ // Test results+ this.result = null;+ this.error = null;+ this.startTimestamp = 0;+ this.endTimestamp = 0;+ }+}++class Suite {+ constructor(parentSuite, name, declaredMode, comment) {+ this.parentSuite = parentSuite;+ this.name = name;+ this.fullName = (parentSuite ? parentSuite.fullName + ' ' + name : name).trim();+ this.declaredMode = declaredMode;+ this.comment = comment;+ /** @type {!Array<(!Test|!Suite)>} */+ this.children = [];++ this.beforeAll = null;+ this.beforeEach = null;+ this.afterAll = null;+ this.afterEach = null;+ }+}++class TestPass {+ constructor(runner, rootSuite, tests, parallel, breakOnFailure) {+ this._runner = runner;+ this._parallel = parallel;+ this._runningUserCallbacks = new Multimap();+ this._breakOnFailure = breakOnFailure;++ this._rootSuite = rootSuite;+ this._workerDistribution = new Multimap();++ let workerId = 0;+ for (const test of tests) {+ // Reset results for tests that will be run.+ test.result = null;+ test.error = null;+ this._workerDistribution.set(test, workerId);+ for (let suite = test.suite; suite; suite = suite.parentSuite)+ this._workerDistribution.set(suite, workerId);+ // Do not shard skipped tests across workers.+ if (test.declaredMode !== TestMode.Skip)+ workerId = (workerId + 1) % parallel;+ }++ this._termination = null;+ }++ async run() {+ const terminations = [+ createTermination.call(this, 'SIGINT', TestResult.Terminated, 'SIGINT received'),+ createTermination.call(this, 'SIGHUP', TestResult.Terminated, 'SIGHUP received'),+ createTermination.call(this, 'SIGTERM', TestResult.Terminated, 'SIGTERM received'),+ createTermination.call(this, 'unhandledRejection', TestResult.Crashed, 'UNHANDLED PROMISE REJECTION'),+ ];+ for (const termination of terminations)+ process.on(termination.event, termination.handler);++ const workerPromises = [];+ for (let i = 0; i < this._parallel; ++i)+ workerPromises.push(this._runSuite(i, [this._rootSuite], {parallelIndex: i}));+ await Promise.all(workerPromises);++ for (const termination of terminations)+ process.removeListener(termination.event, termination.handler);+ return this._termination;++ function createTermination(event, result, message) {+ return {+ event,+ message,+ handler: error => this._terminate(result, message, error)+ };+ }+ }++ async _runSuite(workerId, suitesStack, state) {+ if (this._termination)+ return;+ const currentSuite = suitesStack[suitesStack.length - 1];+ if (!this._workerDistribution.hasValue(currentSuite, workerId))+ return;+ await this._runHook(workerId, currentSuite, 'beforeAll', state);+ for (const child of currentSuite.children) {+ if (this._termination)+ break;+ if (!this._workerDistribution.hasValue(child, workerId))+ continue;+ if (child instanceof Test) {+ await this._runTest(workerId, suitesStack, child, state);+ } else {+ suitesStack.push(child);+ await this._runSuite(workerId, suitesStack, state);+ suitesStack.pop();+ }+ }+ await this._runHook(workerId, currentSuite, 'afterAll', state);+ }++ async _runTest(workerId, suitesStack, test, state) {+ if (this._termination)+ return;+ this._runner._willStartTest(test, workerId);+ if (test.declaredMode === TestMode.Skip) {+ test.result = TestResult.Skipped;+ this._runner._didFinishTest(test, workerId);+ return;+ }+ let crashed = false;+ for (let i = 0; i < suitesStack.length; i++)+ crashed = (await this._runHook(workerId, suitesStack[i], 'beforeEach', state, test)) || crashed;+ // If some of the beofreEach hooks error'ed - terminate this test.+ if (crashed) {+ test.result = TestResult.Crashed;+ } else if (this._termination) {+ test.result = TestResult.Terminated;+ } else {+ // Otherwise, run the test itself if there is no scheduled termination.+ this._runningUserCallbacks.set(workerId, test._userCallback);+ test.error = await test._userCallback.run(state, test);+ this._runningUserCallbacks.delete(workerId, test._userCallback);+ if (!test.error)+ test.result = TestResult.Ok;+ else if (test.error === TimeoutError)+ test.result = TestResult.TimedOut;+ else if (test.error === TerminatedError)+ test.result = TestResult.Terminated;+ else+ test.result = TestResult.Failed;+ }+ for (let i = suitesStack.length - 1; i >= 0; i--)+ crashed = (await this._runHook(workerId, suitesStack[i], 'afterEach', state, test)) || crashed;+ // If some of the afterEach hooks error'ed - then this test is considered to be crashed as well.+ if (crashed)+ test.result = TestResult.Crashed;+ this._runner._didFinishTest(test, workerId);+ if (this._breakOnFailure && test.result !== TestResult.Ok)+ this._terminate(TestResult.Terminated, `Terminating because a test has failed and |testRunner.breakOnFailure| is enabled`, null);+ }++ async _runHook(workerId, suite, hookName, ...args) {+ const hook = suite[hookName];+ if (!hook)+ return false;+ this._runningUserCallbacks.set(workerId, hook);+ const error = await hook.run(...args);+ this._runningUserCallbacks.delete(workerId, hook);+ if (error === TimeoutError) {+ const location = `${hook.location.fileName}:${hook.location.lineNumber}:${hook.location.columnNumber}`;+ const message = `${location} - Timeout Exceeded ${hook.timeout}ms while running "${hookName}" in suite "${suite.fullName}"`;+ return this._terminate(TestResult.Crashed, message, null);+ }+ if (error) {+ const location = `${hook.location.fileName}:${hook.location.lineNumber}:${hook.location.columnNumber}`;+ const message = `${location} - FAILED while running "${hookName}" in suite "${suite.fullName}"`;+ return this._terminate(TestResult.Crashed, message, error);+ }+ return false;+ }++ _terminate(result, message, error) {+ if (this._termination)+ return false;+ this._termination = {result, message, error};+ for (const userCallback of this._runningUserCallbacks.valuesArray())+ userCallback.terminate();+ return true;+ }+}++class TestRunner extends EventEmitter {+ constructor(options = {}) {+ super();+ const {+ timeout = 10 * 1000, // Default timeout is 10 seconds.+ parallel = 1,+ breakOnFailure = false,+ disableTimeoutWhenInspectorIsEnabled = true,+ } = options;+ this._rootSuite = new Suite(null, '', TestMode.Run);+ this._currentSuite = this._rootSuite;+ this._tests = [];+ this._timeout = timeout === 0 ? 2147483647 : timeout;+ this._parallel = parallel;+ this._breakOnFailure = breakOnFailure;++ this._hasFocusedTestsOrSuites = false;++ if (MAJOR_NODEJS_VERSION >= 8 && disableTimeoutWhenInspectorIsEnabled) {+ const inspector = require('inspector');+ if (inspector.url()) {+ console.log('TestRunner detected inspector; overriding certain properties to be debugger-friendly');+ console.log(' - timeout = 0 (Infinite)');+ this._timeout = 2147483647;+ }+ }++ // bind methods so that they can be used as a DSL.+ this.addSuiteDSL('describe', TestMode.Run, '');+ this.addSuiteDSL('fdescribe', TestMode.Focus, '');+ this.addSuiteDSL('xdescribe', TestMode.Skip, '');+ this.addTestDSL('it', TestMode.Run, '');+ this.addTestDSL('fit', TestMode.Focus, '');+ this.addTestDSL('xit', TestMode.Skip, '');+ this.beforeAll = this._addHook.bind(this, 'beforeAll');+ this.beforeEach = this._addHook.bind(this, 'beforeEach');+ this.afterAll = this._addHook.bind(this, 'afterAll');+ this.afterEach = this._addHook.bind(this, 'afterEach');+ }++ addTestDSL(dslName, mode, comment) {+ this[dslName] = this._addTest.bind(this, mode, comment);+ this[dslName].skip = condition => this._addTest.bind(this, condition ? TestMode.Skip : mode, comment);+ }++ addSuiteDSL(dslName, mode, comment) {+ this[dslName] = this._addSuite.bind(this, mode, comment);+ this[dslName].skip = condition => this._addSuite.bind(this, condition ? TestMode.Skip : mode, comment);+ }++ _addTest(mode, comment, name, callback) {+ let suite = this._currentSuite;+ let isSkipped = suite.declaredMode === TestMode.Skip;+ while ((suite = suite.parentSuite))+ isSkipped |= suite.declaredMode === TestMode.Skip;+ const test = new Test(this._currentSuite, name, callback, isSkipped ? TestMode.Skip : mode, this._timeout, comment);+ this._currentSuite.children.push(test);+ this._tests.push(test);+ this._hasFocusedTestsOrSuites = this._hasFocusedTestsOrSuites || mode === TestMode.Focus;+ }++ async _addSuite(mode, comment, name, callback) {+ const oldSuite = this._currentSuite;+ const suite = new Suite(this._currentSuite, name, mode, comment);+ this._currentSuite.children.push(suite);+ this._currentSuite = suite;+ const result = callback();+ if (result && (typeof result.then === 'function'))+ await result;+ this._currentSuite = oldSuite;+ this._hasFocusedTestsOrSuites = this._hasFocusedTestsOrSuites || mode === TestMode.Focus;+ }++ _addHook(hookName, callback) {+ assert(this._currentSuite[hookName] === null, `Only one ${hookName} hook available per suite`);+ const hook = new UserCallback(callback, this._timeout);+ this._currentSuite[hookName] = hook;+ }++ async run() {+ const runnableTests = this._runnableTests();+ this.emit(TestRunner.Events.Started, runnableTests);+ this._runningPass = new TestPass(this, this._rootSuite, runnableTests, this._parallel, this._breakOnFailure);+ const termination = await this._runningPass.run();+ this._runningPass = null;+ const result = {};+ if (termination) {+ result.result = termination.result;+ result.terminationMessage = termination.message;+ result.terminationError = termination.error;+ } else {+ result.result = this.failedTests().length ? TestResult.Failed : TestResult.Ok;+ }+ this.emit(TestRunner.Events.Finished, result);+ return result;+ }++ terminate() {+ if (!this._runningPass)+ return;+ this._runningPass._terminate(TestResult.Terminated, 'Terminated with |TestRunner.terminate()| call', null);+ }++ timeout() {+ return this._timeout;+ }++ _runnableTests() {+ if (!this._hasFocusedTestsOrSuites)+ return this._tests;++ const tests = [];+ const blacklistSuites = new Set();+ // First pass: pick "fit" and blacklist parent suites+ for (const test of this._tests) {+ if (test.declaredMode !== TestMode.Focus)+ continue;+ tests.push(test);+ for (let suite = test.suite; suite; suite = suite.parentSuite)+ blacklistSuites.add(suite);+ }+ // Second pass: pick all tests that belong to non-blacklisted "fdescribe"+ for (const test of this._tests) {+ let insideFocusedSuite = false;+ for (let suite = test.suite; suite; suite = suite.parentSuite) {+ if (!blacklistSuites.has(suite) && suite.declaredMode === TestMode.Focus) {+ insideFocusedSuite = true;+ break;+ }+ }+ if (insideFocusedSuite)+ tests.push(test);+ }+ return tests;+ }++ hasFocusedTestsOrSuites() {+ return this._hasFocusedTestsOrSuites;+ }++ tests() {+ return this._tests.slice();+ }++ failedTests() {+ return this._tests.filter(test => test.result === 'failed' || test.result === 'timedout' || test.result === 'crashed');+ }++ passedTests() {+ return this._tests.filter(test => test.result === 'ok');+ }++ skippedTests() {+ return this._tests.filter(test => test.result === 'skipped');+ }++ parallel() {+ return this._parallel;+ }++ _willStartTest(test, workerId) {+ test.startTimestamp = Date.now();+ this.emit(TestRunner.Events.TestStarted, test, workerId);+ }++ _didFinishTest(test, workerId) {+ test.endTimestamp = Date.now();+ this.emit(TestRunner.Events.TestFinished, test, workerId);+ }+}++/**+ * @param {*} value+ * @param {string=} message+ */+function assert(value, message) {+ if (!value)+ throw new Error(message);+}++TestRunner.Events = {+ Started: 'started',+ Finished: 'finished',+ TestStarted: 'teststarted',+ TestFinished: 'testfinished',+};++module.exports = TestRunner;diff --git a/utils/testrunner/examples/fail.js b/utils/testrunner/examples/fail.jsnew file mode 100644index 0000000000..6e2cd75ac4--- /dev/null+++ b/utils/testrunner/examples/fail.js@@ -0,0 +1,54 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {TestRunner, Reporter, Matchers} = require('..');++const runner = new TestRunner();+const reporter = new Reporter(runner);+const {expect} = new Matchers();++const {describe, xdescribe, fdescribe} = runner;+const {it, fit, xit} = runner;+const {beforeAll, beforeEach, afterAll, afterEach} = runner;++describe('testsuite', () => {+ it('toBe', async (state) => {+ expect(2 + 2).toBe(5);+ });+ it('toBeFalsy', async (state) => {+ expect(true).toBeFalsy();+ });+ it('toBeTruthy', async (state) => {+ expect(false).toBeTruthy();+ });+ it('toBeGreaterThan', async (state) => {+ expect(2).toBeGreaterThan(3);+ });+ it('toBeNull', async (state) => {+ expect(2).toBeNull();+ });+ it('toContain', async (state) => {+ expect('asdf').toContain('e');+ });+ it('not.toContain', async (state) => {+ expect('asdf').not.toContain('a');+ });+ it('toEqual', async (state) => {+ expect([1,2,3]).toEqual([1,2,3,4]);+ });+});++runner.run();diff --git a/utils/testrunner/examples/hookfail.js b/utils/testrunner/examples/hookfail.jsnew file mode 100644index 0000000000..038f58c47f--- /dev/null+++ b/utils/testrunner/examples/hookfail.js@@ -0,0 +1,35 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {TestRunner, Reporter, Matchers} = require('..');++const runner = new TestRunner();+const reporter = new Reporter(runner);+const {expect} = new Matchers();++const {describe, xdescribe, fdescribe} = runner;+const {it, fit, xit} = runner;+const {beforeAll, beforeEach, afterAll, afterEach} = runner;++describe('testsuite', () => {+ beforeAll(() => {+ expect(false).toBeTruthy();+ });+ it('test', async () => {+ });+});++runner.run();diff --git a/utils/testrunner/examples/hooktimeout.js b/utils/testrunner/examples/hooktimeout.jsnew file mode 100644index 0000000000..525f2b7c8a--- /dev/null+++ b/utils/testrunner/examples/hooktimeout.js@@ -0,0 +1,35 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {TestRunner, Reporter, Matchers} = require('..');++const runner = new TestRunner({ timeout: 100 });+const reporter = new Reporter(runner);+const {expect} = new Matchers();++const {describe, xdescribe, fdescribe} = runner;+const {it, fit, xit} = runner;+const {beforeAll, beforeEach, afterAll, afterEach} = runner;++describe('testsuite', () => {+ beforeAll(async () => {+ await new Promise(() => {});+ });+ it('something', async (state) => {+ });+});++runner.run();diff --git a/utils/testrunner/examples/timeout.js b/utils/testrunner/examples/timeout.jsnew file mode 100644index 0000000000..0d451e971e--- /dev/null+++ b/utils/testrunner/examples/timeout.js@@ -0,0 +1,32 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {TestRunner, Reporter} = require('..');++const runner = new TestRunner({ timeout: 100 });+const reporter = new Reporter(runner);++const {describe, xdescribe, fdescribe} = runner;+const {it, fit, xit} = runner;+const {beforeAll, beforeEach, afterAll, afterEach} = runner;++describe('testsuite', () => {+ it('timeout', async (state) => {+ await new Promise(() => {});+ });+});++runner.run();diff --git a/utils/testrunner/examples/unhandledpromiserejection.js b/utils/testrunner/examples/unhandledpromiserejection.jsnew file mode 100644index 0000000000..270bfcc422--- /dev/null+++ b/utils/testrunner/examples/unhandledpromiserejection.js@@ -0,0 +1,35 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {TestRunner, Reporter} = require('..');++const runner = new TestRunner();+const reporter = new Reporter(runner);++const {describe, xdescribe, fdescribe} = runner;+const {it, fit, xit} = runner;+const {beforeAll, beforeEach, afterAll, afterEach} = runner;++describe('testsuite', () => {+ it('failure', async (state) => {+ Promise.reject(new Error('fail!'));+ });+ it('slow', async () => {+ await new Promise(x => setTimeout(x, 1000));+ });+});++runner.run();diff --git a/utils/testrunner/index.js b/utils/testrunner/index.jsnew file mode 100644index 0000000000..998ea3d150--- /dev/null+++ b/utils/testrunner/index.js@@ -0,0 +1,21 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const TestRunner = require('./TestRunner');+const Reporter = require('./Reporter');+const Matchers = require('./Matchers');++module.exports = { TestRunner, Reporter, Matchers };diff --git a/utils/testrunner/package.json b/utils/testrunner/package.jsonnew file mode 100644index 0000000000..acccef8473--- /dev/null+++ b/utils/testrunner/package.json@@ -0,0 +1,18 @@+{+ "name": "@pptr/testrunner",+ "version": "0.8.0",+ "description": "Playwright testrunner",+ "main": "index.js",+ "directories": {+ "example": "examples"+ },+ "scripts": {+ "test": "node test/test.js"+ },+ "repository": {+ "type": "git",+ "url": "https://github.com/Microsoft/playwright/tree/master/utils/testrunner"+ },+ "author": "The Chromium Authors",+ "license": "Apache-2.0"+}diff --git a/utils/testrunner/test/test.js b/utils/testrunner/test/test.jsnew file mode 100644index 0000000000..d4f6b461a3--- /dev/null+++ b/utils/testrunner/test/test.js@@ -0,0 +1,15 @@+const {TestRunner, Matchers, Reporter} = require('..');++const testRunner = new TestRunner();+const {expect} = new Matchers();++require('./testrunner.spec.js').addTests({testRunner, expect});++new Reporter(testRunner, {+ verbose: process.argv.includes('--verbose'),+ summary: true,+ projectFolder: require('path').join(__dirname, '..'),+ showSlowTests: 0,+});+testRunner.run();+diff --git a/utils/testrunner/test/testrunner.spec.js b/utils/testrunner/test/testrunner.spec.jsnew file mode 100644index 0000000000..e1d47edac4--- /dev/null+++ b/utils/testrunner/test/testrunner.spec.js@@ -0,0 +1,610 @@+const {TestRunner} = require('..');++module.exports.addTests = function({testRunner, expect}) {+ const {describe, fdescribe, xdescribe} = testRunner;+ const {it, xit, fit} = testRunner;++ describe('TestRunner.it', () => {+ it('should declare a test', async() => {+ const t = new TestRunner();+ t.it('uno', () => {});+ expect(t.tests().length).toBe(1);+ const test = t.tests()[0];+ expect(test.name).toBe('uno');+ expect(test.fullName).toBe('uno');+ expect(test.declaredMode).toBe('run');+ expect(test.location.filePath).toEqual(__filename);+ expect(test.location.fileName).toEqual('testrunner.spec.js');+ expect(test.location.lineNumber).toBeTruthy();+ expect(test.location.columnNumber).toBeTruthy();+ });+ });++ describe('TestRunner.xit', () => {+ it('should declare a skipped test', async() => {+ const t = new TestRunner();+ t.xit('uno', () => {});+ expect(t.tests().length).toBe(1);+ const test = t.tests()[0];+ expect(test.name).toBe('uno');+ expect(test.fullName).toBe('uno');+ expect(test.declaredMode).toBe('skip');+ });+ });++ describe('TestRunner.fit', () => {+ it('should declare a focused test', async() => {+ const t = new TestRunner();+ t.fit('uno', () => {});+ expect(t.tests().length).toBe(1);+ const test = t.tests()[0];+ expect(test.name).toBe('uno');+ expect(test.fullName).toBe('uno');+ expect(test.declaredMode).toBe('focus');+ });+ });++ describe('TestRunner.describe', () => {+ it('should declare a suite', async() => {+ const t = new TestRunner();+ t.describe('suite', () => {+ t.it('uno', () => {});+ });+ expect(t.tests().length).toBe(1);+ const test = t.tests()[0];+ expect(test.name).toBe('uno');+ expect(test.fullName).toBe('suite uno');+ expect(test.declaredMode).toBe('run');+ expect(test.suite.name).toBe('suite');+ expect(test.suite.fullName).toBe('suite');+ expect(test.suite.declaredMode).toBe('run');+ });+ });++ describe('TestRunner.xdescribe', () => {+ it('should declare a skipped suite', async() => {+ const t = new TestRunner();+ t.xdescribe('suite', () => {+ t.it('uno', () => {});+ });+ expect(t.tests().length).toBe(1);+ const test = t.tests()[0];+ expect(test.declaredMode).toBe('skip');+ expect(test.suite.declaredMode).toBe('skip');+ });+ it('focused tests inside a skipped suite are considered skipped', async() => {+ const t = new TestRunner();+ t.xdescribe('suite', () => {+ t.fit('uno', () => {});+ });+ expect(t.tests().length).toBe(1);+ const test = t.tests()[0];+ expect(test.declaredMode).toBe('skip');+ expect(test.suite.declaredMode).toBe('skip');+ });+ });++ describe('TestRunner.fdescribe', () => {+ it('should declare a focused suite', async() => {+ const t = new TestRunner();+ t.fdescribe('suite', () => {+ t.it('uno', () => {});+ });+ expect(t.tests().length).toBe(1);+ const test = t.tests()[0];+ expect(test.declaredMode).toBe('run');+ expect(test.suite.declaredMode).toBe('focus');+ });+ it('skipped tests inside a focused suite should stay skipped', async() => {+ const t = new TestRunner();+ t.fdescribe('suite', () => {+ t.xit('uno', () => {});+ });+ expect(t.tests().length).toBe(1);+ const test = t.tests()[0];+ expect(test.declaredMode).toBe('skip');+ expect(test.suite.declaredMode).toBe('focus');+ });+ it('should run all "run" tests inside a focused suite', async() => {+ const log = [];+ const t = new TestRunner();+ t.it('uno', () => log.push(1));+ t.fdescribe('suite1', () => {+ t.it('dos', () => log.push(2));+ t.it('tres', () => log.push(3));+ });+ t.it('cuatro', () => log.push(4));+ await t.run();+ expect(log.join()).toBe('2,3');+ });+ it('should run only "focus" tests inside a focused suite', async() => {+ const log = [];+ const t = new TestRunner();+ t.it('uno', () => log.push(1));+ t.fdescribe('suite1', () => {+ t.fit('dos', () => log.push(2));+ t.it('tres', () => log.push(3));+ });+ t.it('cuatro', () => log.push(4));+ await t.run();+ expect(log.join()).toBe('2');+ });+ it('should run both "run" tests in focused suite and non-descendant focus tests', async() => {+ const log = [];+ const t = new TestRunner();+ t.it('uno', () => log.push(1));+ t.fdescribe('suite1', () => {+ t.it('dos', () => log.push(2));+ t.it('tres', () => log.push(3));+ });+ t.fit('cuatro', () => log.push(4));+ await t.run();+ expect(log.join()).toBe('2,3,4');+ });+ });++ describe('TestRunner hooks', () => {+ it('should run all hooks in proper order', async() => {+ const log = [];+ const t = new TestRunner();+ t.beforeAll(() => log.push('root:beforeAll'));+ t.beforeEach(() => log.push('root:beforeEach'));+ t.it('uno', () => log.push('test #1'));+ t.describe('suite1', () => {+ t.beforeAll(() => log.push('suite:beforeAll'));+ t.beforeEach(() => log.push('suite:beforeEach'));+ t.it('dos', () => log.push('test #2'));+ t.it('tres', () => log.push('test #3'));+ t.afterEach(() => log.push('suite:afterEach'));+ t.afterAll(() => log.push('suite:afterAll'));+ });+ t.it('cuatro', () => log.push('test #4'));+ t.afterEach(() => log.push('root:afterEach'));+ t.afterAll(() => log.push('root:afterAll'));+ await t.run();+ expect(log).toEqual([+ 'root:beforeAll',+ 'root:beforeEach',+ 'test #1',+ 'root:afterEach',++ 'suite:beforeAll',++ 'root:beforeEach',+ 'suite:beforeEach',+ 'test #2',+ 'suite:afterEach',+ 'root:afterEach',++ 'root:beforeEach',+ 'suite:beforeEach',+ 'test #3',+ 'suite:afterEach',+ 'root:afterEach',++ 'suite:afterAll',++ 'root:beforeEach',+ 'test #4',+ 'root:afterEach',++ 'root:afterAll',+ ]);+ });+ it('should have the same state object in hooks and test', async() => {+ const states = [];+ const t = new TestRunner();+ t.beforeEach(state => states.push(state));+ t.afterEach(state => states.push(state));+ t.beforeAll(state => states.push(state));+ t.afterAll(state => states.push(state));+ t.it('uno', state => states.push(state));+ await t.run();+ expect(states.length).toBe(5);+ for (let i = 1; i < states.length; ++i)+ expect(states[i]).toBe(states[0]);+ });+ it('should unwind hooks properly when terminated', async() => {+ const log = [];+ const t = new TestRunner({timeout: 10000});+ t.beforeAll(() => log.push('beforeAll'));+ t.beforeEach(() => log.push('beforeEach'));+ t.afterEach(() => log.push('afterEach'));+ t.afterAll(() => log.push('afterAll'));+ t.it('uno', () => {+ log.push('terminating...');+ t.terminate();+ });+ await t.run();++ expect(log).toEqual([+ 'beforeAll',+ 'beforeEach',+ 'terminating...',+ 'afterEach',+ 'afterAll',+ ]);+ });+ it('should unwind hooks properly when crashed', async() => {+ const log = [];+ const t = new TestRunner({timeout: 10000});+ t.beforeAll(() => log.push('root beforeAll'));+ t.beforeEach(() => log.push('root beforeEach'));+ t.describe('suite', () => {+ t.beforeAll(() => log.push('suite beforeAll'));+ t.beforeEach(() => log.push('suite beforeEach'));+ t.it('uno', () => log.push('uno'));+ t.afterEach(() => {+ log.push('CRASH >> suite afterEach');+ throw new Error('crash!');+ });+ t.afterAll(() => log.push('suite afterAll'));+ });+ t.afterEach(() => log.push('root afterEach'));+ t.afterAll(() => log.push('root afterAll'));+ await t.run();++ expect(log).toEqual([+ 'root beforeAll',+ 'suite beforeAll',+ 'root beforeEach',+ 'suite beforeEach',+ 'uno',+ 'CRASH >> suite afterEach',+ 'root afterEach',+ 'suite afterAll',+ 'root afterAll'+ ]);+ });+ });++ describe('TestRunner.run', () => {+ it('should run a test', async() => {+ const t = new TestRunner();+ let ran = false;+ t.it('uno', () => ran = true);+ await t.run();+ expect(ran).toBe(true);+ });+ it('should run tests if some fail', async() => {+ const t = new TestRunner();+ const log = [];+ t.it('uno', () => log.push(1));+ t.it('dos', () => { throw new Error('bad'); });+ t.it('tres', () => log.push(3));+ await t.run();+ expect(log.join()).toBe('1,3');+ });+ it('should run tests if some timeout', async() => {+ const t = new TestRunner({timeout: 1});+ const log = [];+ t.it('uno', () => log.push(1));+ t.it('dos', async() => new Promise(() => {}));+ t.it('tres', () => log.push(3));+ await t.run();+ expect(log.join()).toBe('1,3');+ });+ it('should break on first failure if configured so', async() => {+ const log = [];+ const t = new TestRunner({breakOnFailure: true});+ t.it('test#1', () => log.push('test#1'));+ t.it('test#2', () => log.push('test#2'));+ t.it('test#3', () => { throw new Error('crash'); });+ t.it('test#4', () => log.push('test#4'));+ await t.run();+ expect(log).toEqual([+ 'test#1',+ 'test#2',+ ]);+ });+ it('should pass a state and a test as a test parameters', async() => {+ const log = [];+ const t = new TestRunner();+ t.beforeEach(state => state.FOO = 42);+ t.it('uno', (state, test) => {+ log.push('state.FOO=' + state.FOO);+ log.push('test=' + test.name);+ });+ await t.run();+ expect(log.join()).toBe('state.FOO=42,test=uno');+ });+ it('should run async test', async() => {+ const t = new TestRunner();+ let ran = false;+ t.it('uno', async() => {+ await new Promise(x => setTimeout(x, 10));+ ran = true;+ });+ await t.run();+ expect(ran).toBe(true);+ });+ it('should run async tests in order of their declaration', async() => {+ const log = [];+ const t = new TestRunner();+ t.it('uno', async() => {+ await new Promise(x => setTimeout(x, 30));+ log.push(1);+ });+ t.it('dos', async() => {+ await new Promise(x => setTimeout(x, 20));+ log.push(2);+ });+ t.it('tres', async() => {+ await new Promise(x => setTimeout(x, 10));+ log.push(3);+ });+ await t.run();+ expect(log.join()).toBe('1,2,3');+ });+ it('should run multiple tests', async() => {+ const log = [];+ const t = new TestRunner();+ t.it('uno', () => log.push(1));+ t.it('dos', () => log.push(2));+ await t.run();+ expect(log.join()).toBe('1,2');+ });+ it('should NOT run a skipped test', async() => {+ const t = new TestRunner();+ let ran = false;+ t.xit('uno', () => ran = true);+ await t.run();+ expect(ran).toBe(false);+ });+ it('should run ONLY non-skipped tests', async() => {+ const log = [];+ const t = new TestRunner();+ t.it('uno', () => log.push(1));+ t.xit('dos', () => log.push(2));+ t.it('tres', () => log.push(3));+ await t.run();+ expect(log.join()).toBe('1,3');+ });+ it('should run ONLY focused tests', async() => {+ const log = [];+ const t = new TestRunner();+ t.it('uno', () => log.push(1));+ t.xit('dos', () => log.push(2));+ t.fit('tres', () => log.push(3));+ await t.run();+ expect(log.join()).toBe('3');+ });+ it('should run tests in order of their declaration', async() => {+ const log = [];+ const t = new TestRunner();+ t.it('uno', () => log.push(1));+ t.describe('suite1', () => {+ t.it('dos', () => log.push(2));+ t.it('tres', () => log.push(3));+ });+ t.it('cuatro', () => log.push(4));+ await t.run();+ expect(log.join()).toBe('1,2,3,4');+ });+ it('should support async test suites', async() => {+ const log = [];+ const t = new TestRunner();+ t.it('uno', () => log.push(1));+ await t.describe('suite1', async() => {+ await Promise.resolve();+ t.it('dos', () => log.push(2));+ await Promise.resolve();+ t.it('tres', () => log.push(3));+ });+ t.it('cuatro', () => log.push(4));+ await t.run();+ expect(log.join()).toBe('1,2,3,4');+ });+ });++ describe('TestRunner.run result', () => {+ it('should return OK if all tests pass', async() => {+ const t = new TestRunner();+ t.it('uno', () => {});+ const result = await t.run();+ expect(result.result).toBe('ok');+ });+ it('should return FAIL if at least one test fails', async() => {+ const t = new TestRunner();+ t.it('uno', () => { throw new Error('woof'); });+ const result = await t.run();+ expect(result.result).toBe('failed');+ });+ it('should return FAIL if at least one test times out', async() => {+ const t = new TestRunner({timeout: 1});+ t.it('uno', async() => new Promise(() => {}));+ const result = await t.run();+ expect(result.result).toBe('failed');+ });+ it('should return TERMINATED if it was terminated', async() => {+ const t = new TestRunner({timeout: 1});+ t.it('uno', async() => new Promise(() => {}));+ const [result] = await Promise.all([+ t.run(),+ t.terminate(),+ ]);+ expect(result.result).toBe('terminated');+ });+ it('should return CRASHED if it crashed', async() => {+ const t = new TestRunner({timeout: 1});+ t.it('uno', async() => new Promise(() => {}));+ t.afterAll(() => { throw new Error('woof');});+ const result = await t.run();+ expect(result.result).toBe('crashed');+ });+ });++ describe('TestRunner parallel', () => {+ it('should run tests in parallel', async() => {+ const log = [];+ const t = new TestRunner({parallel: 2});+ t.it('uno', async state => {+ log.push(`Worker #${state.parallelIndex} Starting: UNO`);+ await Promise.resolve();+ log.push(`Worker #${state.parallelIndex} Ending: UNO`);+ });+ t.it('dos', async state => {+ log.push(`Worker #${state.parallelIndex} Starting: DOS`);+ await Promise.resolve();+ log.push(`Worker #${state.parallelIndex} Ending: DOS`);+ });+ await t.run();+ expect(log).toEqual([+ 'Worker #0 Starting: UNO',+ 'Worker #1 Starting: DOS',+ 'Worker #0 Ending: UNO',+ 'Worker #1 Ending: DOS',+ ]);+ });+ });++ describe('TestRunner.hasFocusedTestsOrSuites', () => {+ it('should work', () => {+ const t = new TestRunner();+ t.it('uno', () => {});+ expect(t.hasFocusedTestsOrSuites()).toBe(false);+ });+ it('should work #2', () => {+ const t = new TestRunner();+ t.fit('uno', () => {});+ expect(t.hasFocusedTestsOrSuites()).toBe(true);+ });+ it('should work #3', () => {+ const t = new TestRunner();+ t.describe('suite #1', () => {+ t.fdescribe('suite #2', () => {+ t.describe('suite #3', () => {+ t.it('uno', () => {});+ });+ });+ });+ expect(t.hasFocusedTestsOrSuites()).toBe(true);+ });+ });++ describe('TestRunner.passedTests', () => {+ it('should work', async() => {+ const t = new TestRunner();+ t.it('uno', () => {});+ await t.run();+ expect(t.failedTests().length).toBe(0);+ expect(t.skippedTests().length).toBe(0);+ expect(t.passedTests().length).toBe(1);+ const [test] = t.passedTests();+ expect(test.result).toBe('ok');+ });+ });++ describe('TestRunner.failedTests', () => {+ it('should work for both throwing and timeouting tests', async() => {+ const t = new TestRunner({timeout: 1});+ t.it('uno', () => { throw new Error('boo');});+ t.it('dos', () => new Promise(() => {}));+ await t.run();+ expect(t.skippedTests().length).toBe(0);+ expect(t.passedTests().length).toBe(0);+ expect(t.failedTests().length).toBe(2);+ const [test1, test2] = t.failedTests();+ expect(test1.result).toBe('failed');+ expect(test2.result).toBe('timedout');+ });+ it('should report crashed tests', async() => {+ const t = new TestRunner();+ t.beforeEach(() => { throw new Error('woof');});+ t.it('uno', () => {});+ await t.run();+ expect(t.failedTests().length).toBe(1);+ expect(t.failedTests()[0].result).toBe('crashed');+ });+ });++ describe('TestRunner.skippedTests', () => {+ it('should work for both throwing and timeouting tests', async() => {+ const t = new TestRunner({timeout: 1});+ t.xit('uno', () => { throw new Error('boo');});+ await t.run();+ expect(t.skippedTests().length).toBe(1);+ expect(t.passedTests().length).toBe(0);+ expect(t.failedTests().length).toBe(0);+ const [test] = t.skippedTests();+ expect(test.result).toBe('skipped');+ });+ });++ describe('Test.result', () => {+ it('should return OK', async() => {+ const t = new TestRunner();+ t.it('uno', () => {});+ await t.run();+ expect(t.tests()[0].result).toBe('ok');+ });+ it('should return TIMEDOUT', async() => {+ const t = new TestRunner({timeout: 1});+ t.it('uno', async() => new Promise(() => {}));+ await t.run();+ expect(t.tests()[0].result).toBe('timedout');+ });+ it('should return SKIPPED', async() => {+ const t = new TestRunner();+ t.xit('uno', () => {});+ await t.run();+ expect(t.tests()[0].result).toBe('skipped');+ });+ it('should return FAILED', async() => {+ const t = new TestRunner();+ t.it('uno', async() => Promise.reject('woof'));+ await t.run();+ expect(t.tests()[0].result).toBe('failed');+ });+ it('should return TERMINATED', async() => {+ const t = new TestRunner();+ t.it('uno', async() => t.terminate());+ await t.run();+ expect(t.tests()[0].result).toBe('terminated');+ });+ it('should return CRASHED', async() => {+ const t = new TestRunner();+ t.it('uno', () => {});+ t.afterEach(() => {throw new Error('foo');});+ await t.run();+ expect(t.tests()[0].result).toBe('crashed');+ });+ });++ describe('TestRunner Events', () => {+ it('should emit events in proper order', async() => {+ const log = [];+ const t = new TestRunner();+ t.beforeAll(() => log.push('beforeAll'));+ t.beforeEach(() => log.push('beforeEach'));+ t.it('test#1', () => log.push('test#1'));+ t.afterEach(() => log.push('afterEach'));+ t.afterAll(() => log.push('afterAll'));+ t.on('started', () => log.push('E:started'));+ t.on('teststarted', () => log.push('E:teststarted'));+ t.on('testfinished', () => log.push('E:testfinished'));+ t.on('finished', () => log.push('E:finished'));+ await t.run();+ expect(log).toEqual([+ 'E:started',+ 'beforeAll',+ 'E:teststarted',+ 'beforeEach',+ 'test#1',+ 'afterEach',+ 'E:testfinished',+ 'afterAll',+ 'E:finished',+ ]);+ });+ it('should emit finish event with result', async() => {+ const t = new TestRunner();+ const [result] = await Promise.all([+ new Promise(x => t.once('finished', x)),+ t.run(),+ ]);+ expect(result.result).toBe('ok');+ });+ });+};+diff --git a/utils/testserver/LICENSE b/utils/testserver/LICENSEnew file mode 100644index 0000000000..afdfe50e72--- /dev/null+++ b/utils/testserver/LICENSE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright 2017 Google Inc.++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/utils/testserver/README.md b/utils/testserver/README.mdnew file mode 100644index 0000000000..c9b4e7cc2c--- /dev/null+++ b/utils/testserver/README.md@@ -0,0 +1,18 @@+# TestServer++This test server is used internally by Playwright to test Playwright itself.++### Example++```js+const {TestServer} = require('@pptr/testserver');++(async(() => {+ const httpServer = await TestServer.create(__dirname, 8000),+ const httpsServer = await TestServer.createHTTPS(__dirname, 8001)+ httpServer.setRoute('/hello', (req, res) => {+ res.end('Hello, world!');+ });+ console.log('HTTP and HTTPS servers are running!');+})();+```diff --git a/utils/testserver/cert.pem b/utils/testserver/cert.pemnew file mode 100644index 0000000000..fc692a6641--- /dev/null+++ b/utils/testserver/cert.pem@@ -0,0 +1,28 @@+-----BEGIN CERTIFICATE-----+MIIEsjCCApoCCQCIPLvQDgoZojANBgkqhkiG9w0BAQsFADAaMRgwFgYDVQQDDA9w+dXBwZXRlZXItdGVzdHMwIBcNMTkwMjEzMTkwNzQzWhgPMzAxODA2MTYxOTA3NDNa+MBoxGDAWBgNVBAMMD3B1cHBldGVlci10ZXN0czCCAiIwDQYJKoZIhvcNAQEBBQAD+ggIPADCCAgoCggIBAJue1yqA4qn0SJR3rgTd6sCYVHMKqUouD0No09H7qf+5ZaIb+3yGpC5J9Bsf/ZbvD5xpgqbGEYkHj7Qh6Z/cPCSHA+ZpsUzDXVrLFXrdwwiK1FrIS+rDI2RYsiP+e52XPC/acWC/7f+E54C62oMjYojaVaDn8gu06gyS1rXK2JITQ6CrKn+b+PVSkjtPB4ku245u1qCKoblkNEZSkEmw8Csl+gw6ydGqOSQAoo8rsDte5zCMnPX+7XzL6EhRqpiVx7PCuQWnXhL7j9N214Pit7s7F8TeAA6yZR9oswW+h0dWO+XwocJ1+rwkODXOngbCqO+GUxyuavIl2m0d2MP8n6Wa9RVqYetmPQzafKkR5hjiV4mgCFqNQ+bHMTjI6udcR+h5pYoWKxN9/gJaWwyAAzck0AiMeGVrvKR3JKACqlTMzy/Y30obRF+dddURoFf2wjKJvuTK9hHI7pwM5tlPEwu9bTCWNA6XXs2Bq1f6N2OAKhpKOcihNem+aeGUPmygLPb66z9JO75yZXM+1yk1ScXaNHWZLmluVpEPk7maWULpSpxPAlaN3PmK+8lEihgfBBovampxZo8SvPEt+g5jGyPq9weNg8ic8476PuRVQdg7D8spVxl6whDlJ+bcFojzgrX70t13jqZOtla4WK1vRnZAGplfoH0i5WvAVw+i5S/OVzsmNDtGFbAgMB+AAEwDQYJKoZIhvcNAQELBQADggIBADUAjA/dH+b5UxDC5SL98w1hphw9PvD1cuGS+sVnKPM236JoTiO3KVfm3NMBfSoBi1hPNkXzqr/R4xbyje4Kc4oYcdjGtpll3T5da+wkx1+qumx6O2mEaOshxh76dfZfZne6SQphQKHw8PD10CfDb/NMnmdEbiOSENSqS4+jGELuGviUl361oCBU45UEN7lfs7ANAhwSZyEO7deroyGdvsxfQUaqQrEQsG30jn3+t0cCamYU6eK3bNR/yNXJrZFv3dzoquRY9H52YtVElRqdAIsNlnbxbqz0cm5xFKFt+YTIrMSO1EvDTbB0PPwC5FJvONHhjwiWzgVXSnZrcs/05TsWWnSHH92S+wGCIBC+0+6fcSKnjdBn9ks5TrDX0TRY6N890KyDQWxPRhHYrMVpn833WY8y/SguxqiMgLFgMD+WLy6yZzJloW7NgpLGAfMA0nMG1O92hfKmQw82Pyf3SVXGTDiXiEOXn0vN6bsPaV/+3Ws2LJQECnVfHj3TsuxdtwcO+VGcFCarMOqlhE6IlQzfK8ykYdP6wCkVgXEtiVCR+T1OWUWCFowoFpwBFLf1lA065qsAymddnkrUEOMiScZ/3OZhmd+FvgQ+O0iYuqpeI+xauiQ68+Jb4KjVWnu5QBVq8n1vUJ5+gAzowNMN9G+1+A282Ox23T48dce22BTS6B+3Taaccm++-----END CERTIFICATE-----diff --git a/utils/testserver/index.js b/utils/testserver/index.jsnew file mode 100644index 0000000000..85f2d1fdd7--- /dev/null+++ b/utils/testserver/index.js@@ -0,0 +1,272 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const http = require('http');+const https = require('https');+const url = require('url');+const fs = require('fs');+const path = require('path');+const mime = require('mime');+const WebSocketServer = require('ws').Server;++const fulfillSymbol = Symbol('fullfil callback');+const rejectSymbol = Symbol('reject callback');++class TestServer {+ /**+ * @param {string} dirPath+ * @param {number} port+ * @return {!TestServer}+ */+ static async create(dirPath, port) {+ const server = new TestServer(dirPath, port);+ await new Promise(x => server._server.once('listening', x));+ return server;+ }++ /**+ * @param {string} dirPath+ * @param {number} port+ * @return {!TestServer}+ */+ static async createHTTPS(dirPath, port) {+ const server = new TestServer(dirPath, port, {+ key: fs.readFileSync(path.join(__dirname, 'key.pem')),+ cert: fs.readFileSync(path.join(__dirname, 'cert.pem')),+ passphrase: 'aaaa',+ });+ await new Promise(x => server._server.once('listening', x));+ return server;+ }++ /**+ * @param {string} dirPath+ * @param {number} port+ * @param {!Object=} sslOptions+ */+ constructor(dirPath, port, sslOptions) {+ if (sslOptions)+ this._server = https.createServer(sslOptions, this._onRequest.bind(this));+ else+ this._server = http.createServer(this._onRequest.bind(this));+ this._server.on('connection', socket => this._onSocket(socket));+ this._wsServer = new WebSocketServer({server: this._server});+ this._wsServer.on('connection', this._onWebSocketConnection.bind(this));+ this._server.listen(port);+ this._dirPath = dirPath;++ this._startTime = new Date();+ this._cachedPathPrefix = null;++ /** @type {!Set<!net.Socket>} */+ this._sockets = new Set();++ /** @type {!Map<string, function(!IncomingMessage, !ServerResponse)>} */+ this._routes = new Map();+ /** @type {!Map<string, !{username:string, password:string}>} */+ this._auths = new Map();+ /** @type {!Map<string, string>} */+ this._csp = new Map();+ /** @type {!Set<string>} */+ this._gzipRoutes = new Set();+ /** @type {!Map<string, !Promise>} */+ this._requestSubscribers = new Map();+ }++ _onSocket(socket) {+ this._sockets.add(socket);+ // ECONNRESET is a legit error given+ // that tab closing simply kills process.+ socket.on('error', error => {+ if (error.code !== 'ECONNRESET')+ throw error;+ });+ socket.once('close', () => this._sockets.delete(socket));+ }++ /**+ * @param {string} pathPrefix+ */+ enableHTTPCache(pathPrefix) {+ this._cachedPathPrefix = pathPrefix;+ }++ /**+ * @param {string} path+ * @param {string} username+ * @param {string} password+ */+ setAuth(path, username, password) {+ this._auths.set(path, {username, password});+ }++ enableGzip(path) {+ this._gzipRoutes.add(path);+ }++ /**+ * @param {string} path+ * @param {string} csp+ */+ setCSP(path, csp) {+ this._csp.set(path, csp);+ }++ async stop() {+ this.reset();+ for (const socket of this._sockets)+ socket.destroy();+ this._sockets.clear();+ await new Promise(x => this._server.close(x));+ }++ /**+ * @param {string} path+ * @param {function(!IncomingMessage, !ServerResponse)} handler+ */+ setRoute(path, handler) {+ this._routes.set(path, handler);+ }++ /**+ * @param {string} from+ * @param {string} to+ */+ setRedirect(from, to) {+ this.setRoute(from, (req, res) => {+ res.writeHead(302, { location: to });+ res.end();+ });+ }++ /**+ * @param {string} path+ * @return {!Promise<!IncomingMessage>}+ */+ waitForRequest(path) {+ let promise = this._requestSubscribers.get(path);+ if (promise)+ return promise;+ let fulfill, reject;+ promise = new Promise((f, r) => {+ fulfill = f;+ reject = r;+ });+ promise[fulfillSymbol] = fulfill;+ promise[rejectSymbol] = reject;+ this._requestSubscribers.set(path, promise);+ return promise;+ }++ reset() {+ this._routes.clear();+ this._auths.clear();+ this._csp.clear();+ this._gzipRoutes.clear();+ const error = new Error('Static Server has been reset');+ for (const subscriber of this._requestSubscribers.values())+ subscriber[rejectSymbol].call(null, error);+ this._requestSubscribers.clear();+ }++ _onRequest(request, response) {+ request.on('error', error => {+ if (error.code === 'ECONNRESET')+ response.end();+ else+ throw error;+ });+ request.postBody = new Promise(resolve => {+ let body = '';+ request.on('data', chunk => body += chunk);+ request.on('end', () => resolve(body));+ });+ const pathName = url.parse(request.url).path;+ if (this._auths.has(pathName)) {+ const auth = this._auths.get(pathName);+ const credentials = Buffer.from((request.headers.authorization || '').split(' ')[1] || '', 'base64').toString();+ if (credentials !== `${auth.username}:${auth.password}`) {+ response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Secure Area"' });+ response.end('HTTP Error 401 Unauthorized: Access is denied');+ return;+ }+ }+ // Notify request subscriber.+ if (this._requestSubscribers.has(pathName)) {+ this._requestSubscribers.get(pathName)[fulfillSymbol].call(null, request);+ this._requestSubscribers.delete(pathName);+ }+ const handler = this._routes.get(pathName);+ if (handler) {+ handler.call(null, request, response);+ } else {+ const pathName = url.parse(request.url).path;+ this.serveFile(request, response, pathName);+ }+ }++ /**+ * @param {!IncomingMessage} request+ * @param {!ServerResponse} response+ * @param {string} pathName+ */+ serveFile(request, response, pathName) {+ if (pathName === '/')+ pathName = '/index.html';+ const filePath = path.join(this._dirPath, pathName.substring(1));++ if (this._cachedPathPrefix !== null && filePath.startsWith(this._cachedPathPrefix)) {+ if (request.headers['if-modified-since']) {+ response.statusCode = 304; // not modified+ response.end();+ return;+ }+ response.setHeader('Cache-Control', 'public, max-age=31536000');+ response.setHeader('Last-Modified', this._startTime.toISOString());+ } else {+ response.setHeader('Cache-Control', 'no-cache, no-store');+ }+ if (this._csp.has(pathName))+ response.setHeader('Content-Security-Policy', this._csp.get(pathName));++ fs.readFile(filePath, (err, data) => {+ if (err) {+ response.statusCode = 404;+ response.end(`File not found: ${filePath}`);+ return;+ }+ const mimeType = mime.getType(filePath);+ const isTextEncoding = /^text\/|^application\/(javascript|json)/.test(mimeType);+ const contentType = isTextEncoding ? `${mimeType}; charset=utf-8` : mimeType;+ response.setHeader('Content-Type', contentType);+ if (this._gzipRoutes.has(pathName)) {+ response.setHeader('Content-Encoding', 'gzip');+ const zlib = require('zlib');+ zlib.gzip(data, (_, result) => {+ response.end(result);+ });+ } else {+ response.end(data);+ }+ });+ }++ _onWebSocketConnection(connection) {+ connection.send('opened');+ }+}++module.exports = {TestServer};diff --git a/utils/testserver/key.pem b/utils/testserver/key.pemnew file mode 100644index 0000000000..e2ed680559--- /dev/null+++ b/utils/testserver/key.pem@@ -0,0 +1,52 @@+-----BEGIN PRIVATE KEY-----+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQCbntcqgOKp9EiU+d64E3erAmFRzCqlKLg9DaNPR+6n/uWWiG98hqQuSfQbH/2W7w+caYKmxhGJB4+0I+emf3DwkhwPmabFMw11ayxV63cMIitRayEqwyNkWLIj/nudlzwv2nFgv+3/hOeAut+qDI2KI2lWg5/ILtOoMkta1ytiSE0Ogqyp2/j1UpI7TweJLtuObtagiqG5ZDRGUpB+JsPArJfoMOsnRqjkkAKKPK7A7XucwjJz1+18y+hIUaqYlcezwrkFp14S+4/TdteD+4re7OxfE3gAOsmUfaLMFvodHVjvl8KHCda8JDg1zp4GwqjvhlMcrmryJdptHdjD/+J+lmvUVamHrZj0M2nypEeYY4leJoAhajUGxzE4yOrnXEfoeaWKFisTff4CWlsMgA+M3JNAIjHhla7ykdySgAqpUzM8v2N9KG0RXXXVEaBX9sIyib7kyvYRyO6cDObZTxM+LvW0wljQOl17NgatX+jdjgCoaSjnIoTXpmnhlD5soCz2+us/STu+cmVzPtcpNUnF+2jR1mS5pblaRD5O5mllC6UqcTwJWjdz5ivJRIoYHwQaL2pqcWaPErzxLfoOYxsj6+vcHjYPInPOO+j7kVUHYOw/LKVcZesIQ5SW3BaI84K1+9Ldd46mTrZWuFitb0Z2QB+qZX6B9IuVrwFcPouUvzlc7JjQ7RhWwIDAQABAoICAFUvM5SejHR/taMfh/A+EZxv+RfrbISPr5or9vMU6vymuMIX2P8PLJvx+19Fuah/H8p8rvnffgXGT9FIpvvMsFdGW+MotnNHqNxXWCOICthnc9LTk4o22w64xnqReNUgzd9b8agGJ58w/xAmOCqEmhFTgn+/bt1DVLTDIyCMm8Dm1tdUjHNGaBbRph40+mkLbz+eSHoEqNY0lbDQzQ6pfi4AUcm+T/Jl6VmDwwAsi3QsCvgaDUgAMI2ZiILdwUZY5sHtmx4PKZ22elpEuWAGIJCqni4z+X1CsMlJpG2XPj3lrKMqLV+B8Tt3kBVUDoig0ZybqK8QgpYeRlxodBmEFVevZOzar+r/qDRh+vrQQxjpFYfrMkPiueRmz0+K1a7KiKSmrjHIb9CTi3BpgEhawbsOB7M+9z+G5Q7YtGbVyJPmEAAva89ZZqYvyAwxZk3V4pwpoUYzjgPiHm6Oq0vzKPuCgQxsYzx+UrCVRo7pSE4tTin4SRThY2/yHiMJl8QY//MkahgY8KEHtXE36km6pMRH/ssdSm+C+SNCOtzUDY8wpaDQ++aB29NWqgnSgwoBrRUXr5NHq+wNpWtmD7L0wDSKUCPfiCduR+DoSHBIno5U2jgPrH5Wk7X7loG2XxiDR0qtNOiH24SCI+C1nsLRGBS2Tmo0Qby/Ll+oYYCZ0U3S7wk9UY5HcuRAoIBAQDIl8HTaIuzyOrrpsRdUv8jAxnkdhVjYhWGp7mU+5concRazcEO5/vDJlsIuQI/w7U+xS7PCBPRq7NxUtaUntlQ00s224Ws0sPHIWUD0+NBsodTX8hik2PdmZ5ZbBHVaeVbMV/5zV8eOPGGCsAn//7l4YIp2I2Abs79leqSDI+7tBpF4IsUq7xqcVZ1QhWBZmTqE4gYDVqFEVe9O6OmAdkM1qxVSur2E5Ib+islnu8+yKlu0QlXg596zLVAjxajKYf20NXxh7O+xt5QDEy3dmJEhz5viS6eI7QECM7Lid2T+c22mABSKzYfbwQroM9yBiI3p0zjwRhha0hRKocLkSiNUlOWHAoIBAQDGmwRM6Xmu+j7/lV3KvrOmvcNIbUwMbYY/ATY3Wuph6GFjwdliRiju9F3ZUHMV+yNlVDqH3DeRC+QwGKIcFiVk+4fq1AbWVCWk2MOf49akeJwqFzgF8nkxVXF9PS73VdEvreSvy7g89t+ABqJN6pmGHWVkE1mf/3LJyS2Y7WCZqSaWG3TBZ2SRb2t/t/DnX1L6tzNMkuNAizA+sDB3J1hH1eGcWn/24NB9sc7i2Bk+Cpi0S/xDn9FfoBo5U0p/lpopgfFoSeQZXq1A+KIQdtUPLp3KR9EG/ItimfW875zqFe8bekB9/gakyLsbIyINz1iQQS1L1FFmOO8zN+RtRmm3MrG9qNAoIBAQC1v2rLFgqeVwkjgvKgbDbnjkPDkIpIhfJjE00+8AV+PyUG+aE21FJ0uyf4e0jiZXyu5xJGW1c5vozTvO7XsiXM6eVYSwaPVFg28LcKAgUWqHqlP+qG9myhuDKVaymtaEl7mv0O5VmtlIKhpNP+aiCWQQEi0SdEmyHI+jCTK/XEJRNg+o+ATKpm91IS5FF/8Tq2LAQ/ZroBn3kT6BmarEnxLADxNvQ1Cf50gvLdH2gy19ZHOWN++aBiL2B6oissotCifQ2bzgy6ao27kalhAU6AMNoNTQqEFm1gymo0WTH+C7PpmGEE+cr0KC5rKUVMVuph6p/sLGTev8nCYPoDLP7FLTa25AoIBAGmP559B0c141pR+AJVj+oOoBW4vueY5KMvARyLxDfdwXqN5W6QiiotIE8H4QtOCIvQu6tVftaE/X8a+L9Y/h+NIppuoiuHM5B1UodYQcfwFp2uv37U5hjU0pxfcN2R7lq5zDURrUcgFn9Xh1lGwsd+IRKYGqvKiAk9CwRuxwFCsWbgba9mIrSmoQUknacJxJlfgnEGtKWEbGkWvQv4O7Ii++sHyUGXWZLsKkV59Yh1Z4ISkhrci8VSUcpvZq5VZZSN+z+OQss7RReD+KArqV9id+bgYp//AqA2Gq9j6uzqo4eiG+FR/euSHVPw9llIkzXwPSJYvifx9cpaTOawMGyRY2+vdkCggEBAJECl41qbQE7OIPsSmhcz0nK6L4aIkdOxZ6hs6xO7fPwh7EntojPIB6J+bMuvfujqW4SZ+ZpwZkCc8p8j2VuQvlXLI+s6923IdYAOK5ND9q3Xj7AqgJjUKbhH+lpYUtfDmIjqVADoiIYXmZBPAo7QvzkX7A2qclV7VL/Dc94bBS6M+v/JGh7QyTCsO+oPK6IOlGL1yg+CdZIzdSiJKVeESPMOBhNtPhm+vOXvRV08ECEILD1j52rUKcPs+I+uINxopeXePgekedm7nyAW3IMHFKa4EiuEU3LQOaWeKEnaxNdOh12Pyyd6w2iAmrr+rj/p/2CWVN8OTi7CY5cOTCadHZRyjYA=+-----END PRIVATE KEY-----diff --git a/utils/testserver/package.json b/utils/testserver/package.jsonnew file mode 100644index 0000000000..086be677bf--- /dev/null+++ b/utils/testserver/package.json@@ -0,0 +1,15 @@+{+ "name": "@pptr/testserver",+ "version": "0.5.0",+ "description": "testing server",+ "main": "index.js",+ "scripts": {+ "test": "echo \"Error: no test specified\" && exit 1"+ },+ "repository": {+ "type": "git",+ "url": "https://github.com/Microsoft/playwright/tree/master/utils/testserver"+ },+ "author": "The Chromium Authors",+ "license": "Apache-2.0"+}diff --git a/webkit.js b/webkit.jsnew file mode 100644index 0000000000..a439dc7857--- /dev/null+++ b/webkit.js@@ -0,0 +1,29 @@+/**+ * Copyright 2017 Google Inc. All rights reserved.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++const {helper} = require('./lib/helper');+const api = require('./lib/api');+for (const className in api.WebKit) {+ // Playwright-web excludes certain classes from bundle, e.g. BrowserFetcher.+ if (typeof api.WebKit[className] === 'function')+ helper.installAsyncStackHooks(api.WebKit[className]);+}++// If node does not support async await, use the compiled version.+const {Playwright} = require('./lib/webkit/Playwright');+const packageJson = require('./package.json');++module.exports = new Playwright(__dirname, packageJson.playwright.webkit_revision);