mirror of
https://github.com/appium/appium.git
synced 2026-11-25 05:50:38 +08:00
Compare commits
60
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb5ce47b17 | ||
|
|
7df378f401 | ||
|
|
4dd2e2d47d | ||
|
|
dacc42ba0a | ||
|
|
2502f538ff | ||
|
|
3f38f5cd74 | ||
|
|
6891dd4eae | ||
|
|
4e8e334cbc | ||
|
|
3423e36689 | ||
|
|
14a9d98641 | ||
|
|
f79fafb816 | ||
|
|
443b0bdd03 | ||
|
|
80fbf957c8 | ||
|
|
0443c84ec0 | ||
|
|
a47fdb8e05 | ||
|
|
e2c8f09bb9 | ||
|
|
dc16d6970f | ||
|
|
abfe1243a1 | ||
|
|
9bbf6b72bf | ||
|
|
0fa9c9bd80 | ||
|
|
9a70a44c83 | ||
|
|
65e14685a8 | ||
|
|
29eeb28f86 | ||
|
|
ac412b8723 | ||
|
|
68740320d2 | ||
|
|
9dc6cd0019 | ||
|
|
81c8b9da0a | ||
|
|
726348c2d5 | ||
|
|
6c911debd7 | ||
|
|
8ccb436701 | ||
|
|
f522b64456 | ||
|
|
3180558086 | ||
|
|
9d07f6bc5e | ||
|
|
b234e2b56b | ||
|
|
b635641f24 | ||
|
|
6d720b1112 | ||
|
|
6ab17feb71 | ||
|
|
afa4837530 | ||
|
|
1ada93cf76 | ||
|
|
b32e28d36d | ||
|
|
119e21f067 | ||
|
|
6ba6faf6f5 | ||
|
|
422362a259 | ||
|
|
62bfe1566a | ||
|
|
8a9350b8e9 | ||
|
|
bf51d27137 | ||
|
|
de00df0afa | ||
|
|
c3a48181c8 | ||
|
|
77dc09af36 | ||
|
|
59af10a17c | ||
|
|
6e989bd89a | ||
|
|
557e71f766 | ||
|
|
63d94d03c6 | ||
|
|
8a0022c147 | ||
|
|
72ee77d139 | ||
|
|
70a01da4b2 | ||
|
|
1b705bcd24 | ||
|
|
574bd6cbfb | ||
|
|
9c00b86ce7 | ||
|
|
0c4da64aea |
@@ -23,6 +23,8 @@ targets:
|
||||
path: ./packages/appium
|
||||
- type: npm
|
||||
path: ./packages/base-driver
|
||||
- type: npm
|
||||
path: ./packages/eslint-config-appium-ts
|
||||
- type: npm
|
||||
path: ./packages/fake-driver
|
||||
- type: npm
|
||||
|
||||
@@ -16,21 +16,15 @@ inputs:
|
||||
required: false
|
||||
default: 'true'
|
||||
|
||||
socket-firewall:
|
||||
description: Whether to install dependencies through Socket Firewall
|
||||
required: false
|
||||
default: 'true'
|
||||
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
- name: Use Node.js ${{ inputs.node-version }}
|
||||
uses: actions/setup-node@v7.1.0
|
||||
uses: actions/setup-node@v7.0.0
|
||||
with:
|
||||
node-version: ${{ inputs.node-version }}
|
||||
cache: npm
|
||||
- name: SocketDev Security Check
|
||||
if: ${{ inputs.socket-firewall == 'true' }}
|
||||
uses: SocketDev/action@v1.3.2
|
||||
with:
|
||||
mode: firewall-free
|
||||
@@ -39,12 +33,6 @@ runs:
|
||||
run: |
|
||||
# Replace npm with sfw npm in the install command
|
||||
install_cmd="${{ inputs.install-command }}"
|
||||
|
||||
if [ "${{ inputs.socket-firewall }}" != "true" ]; then
|
||||
$install_cmd
|
||||
exit $?
|
||||
fi
|
||||
|
||||
sfw_install_cmd="${install_cmd//npm /sfw npm }"
|
||||
|
||||
# Socket Firewall can fail to reach its own backend (a transient
|
||||
@@ -84,7 +72,6 @@ runs:
|
||||
exit 1
|
||||
fi
|
||||
- name: Build packages
|
||||
# `npm ci` already builds through the root `prepare` script
|
||||
if: ${{ inputs.run-build == 'true' && !startsWith(inputs.install-command, 'npm ci') }}
|
||||
if: ${{ inputs.run-build == 'true' }}
|
||||
shell: bash
|
||||
run: npm run build
|
||||
|
||||
+5
-5
@@ -43,11 +43,6 @@ labels:
|
||||
matcher:
|
||||
files: ['packages/appium/**']
|
||||
|
||||
- label: '@appium/http-server'
|
||||
sync: true
|
||||
matcher:
|
||||
files: ['packages/http-server/**']
|
||||
|
||||
- label: '@appium/base-driver'
|
||||
sync: true
|
||||
matcher:
|
||||
@@ -73,6 +68,11 @@ labels:
|
||||
matcher:
|
||||
files: ['packages/driver-test-support/**']
|
||||
|
||||
- label: '@appium/eslint-config-appium-ts'
|
||||
sync: true
|
||||
matcher:
|
||||
files: ['packages/eslint-config-appium-ts/**']
|
||||
|
||||
- label: '@appium/oxc-config'
|
||||
sync: true
|
||||
matcher:
|
||||
|
||||
+24
-42
@@ -3,18 +3,15 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- appium4
|
||||
# this list of paths could potentially impact the build
|
||||
paths:
|
||||
- '**/tsconfig*.json'
|
||||
- 'packages/base-driver/test-fixtures/**/*'
|
||||
- 'packages/*/test/**'
|
||||
- 'packages/*/bin'
|
||||
- 'packages/**/*.js'
|
||||
- 'packages/**/*.mjs'
|
||||
- 'packages/**/*.cjs'
|
||||
- 'packages/**/*.ts'
|
||||
- 'packages/**/*.json'
|
||||
- 'packages/**/*.js'
|
||||
- 'package*.json'
|
||||
- 'lerna.json'
|
||||
- '.npmrc'
|
||||
@@ -26,17 +23,14 @@ on:
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
- appium4
|
||||
paths:
|
||||
- '**/tsconfig*.json'
|
||||
- 'packages/base-driver/test-fixtures/**/*'
|
||||
- 'packages/*/test/**'
|
||||
- 'packages/*/bin'
|
||||
- 'packages/**/*.js'
|
||||
- 'packages/**/*.mjs'
|
||||
- 'packages/**/*.cjs'
|
||||
- 'packages/**/*.ts'
|
||||
- 'packages/**/*.json'
|
||||
- 'packages/**/*.js'
|
||||
- 'package*.json'
|
||||
- 'lerna.json'
|
||||
- '.npmrc'
|
||||
@@ -61,19 +55,15 @@ jobs:
|
||||
uses: appium/appium-workflows/.github/workflows/node-lts-matrix.yml@main
|
||||
|
||||
prepare_e2e_packages:
|
||||
needs:
|
||||
- prepare_matrix
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
matrix: ${{ steps.discover-packages.outputs.matrix }}
|
||||
packages: ${{ steps.discover-packages.outputs.packages }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7.0.1
|
||||
- name: Discover packages with e2e tests
|
||||
id: discover-packages
|
||||
env:
|
||||
NODE_VERSIONS: ${{ needs.prepare_matrix.outputs.versions }}
|
||||
run: |
|
||||
targets='[]'
|
||||
packages=()
|
||||
for package_dir in packages/*/; do
|
||||
package_json="${package_dir}package.json"
|
||||
if [[ -f "$package_json" ]]; then
|
||||
@@ -93,26 +83,21 @@ jobs:
|
||||
# Use the directory path without packages/ prefix (remove trailing slash)
|
||||
package_name="${package_dir%/}"
|
||||
package_name="${package_name#packages/}"
|
||||
# Packages with a test:e2e:shards script print a JSON array of shard names
|
||||
shards='[""]'
|
||||
if node -e "process.exit(require('./$package_json').scripts?.['test:e2e:shards'] ? 0 : 1)"; then
|
||||
shards=$(cd "$package_dir" && npm run --silent test:e2e:shards)
|
||||
fi
|
||||
targets=$(jq -c --arg pkg "$package_name" --argjson shards "$shards" \
|
||||
'. + [$shards[] | {package_dir: $pkg, shard: ., name: (if . == "" then $pkg else "\($pkg) [\(.)]" end)}]' \
|
||||
<<< "$targets")
|
||||
packages+=("$package_name")
|
||||
fi
|
||||
fi
|
||||
done
|
||||
echo "Found e2e targets:"
|
||||
echo "$targets" | jq -r '.[].name' | sed 's/^/ - /'
|
||||
# All LTS versions of Node.js on Linux, the newest one on Windows
|
||||
matrix=$(jq -c --argjson versions "$NODE_VERSIONS" '
|
||||
[.[] as $target
|
||||
| ($versions[] | {os: "ubuntu-latest", "node-version": ., target: $target}),
|
||||
{os: "windows-latest", "node-version": ($versions | map(tostring | tonumber) | max), target: $target}]
|
||||
' <<< "$targets")
|
||||
echo "matrix=$matrix" >> $GITHUB_OUTPUT
|
||||
# Convert array to JSON array for GitHub Actions matrix
|
||||
if [[ ${#packages[@]} -eq 0 ]]; then
|
||||
echo "No packages with e2e tests found"
|
||||
packages_json="[]"
|
||||
else
|
||||
# Use jq to create a compact single-line JSON array
|
||||
packages_json=$(printf '%s\n' "${packages[@]}" | jq -R '.' | jq -s '.' | jq -c '.')
|
||||
fi
|
||||
echo "packages=$packages_json" >> $GITHUB_OUTPUT
|
||||
echo "Found packages with e2e tests:"
|
||||
echo "$packages_json" | jq -r '.[]' | sed 's/^/ - /'
|
||||
|
||||
test-smoke:
|
||||
needs:
|
||||
@@ -173,18 +158,16 @@ jobs:
|
||||
|
||||
test-e2e:
|
||||
needs:
|
||||
- prepare_matrix
|
||||
- prepare_e2e_packages
|
||||
name: E2E Tests - ${{ matrix.target.name }} (Node ${{ matrix.node-version }}, ${{ matrix.os }})
|
||||
name: E2E Tests - ${{ matrix.package_dir }} (Node ${{ matrix.node-version }})
|
||||
if: ${{ github.event_name == 'pull_request' }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include: ${{ fromJSON(needs.prepare_e2e_packages.outputs.matrix) }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 30
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
node-version: ${{ fromJSON(needs.prepare_matrix.outputs.versions) }}
|
||||
package_dir: ${{ fromJSON(needs.prepare_e2e_packages.outputs.packages) }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7.0.1
|
||||
- name: Setup, install and build
|
||||
@@ -193,12 +176,11 @@ jobs:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
install-command: npm ci --foreground-scripts
|
||||
run-build: 'true'
|
||||
socket-firewall: 'false'
|
||||
- name: Run E2E tests for ${{ matrix.target.name }}
|
||||
- name: Run E2E tests for ${{ matrix.package_dir }}
|
||||
run: |
|
||||
set -o pipefail
|
||||
cd "packages/${{ matrix.target.package_dir }}"
|
||||
npm run test:e2e -- ${{ matrix.target.shard }}
|
||||
cd "packages/${{ matrix.package_dir }}"
|
||||
npm run test:e2e
|
||||
|
||||
lint:
|
||||
name: Lint
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v7.0.1
|
||||
- name: Use Node.js LTS
|
||||
uses: actions/setup-node@v7.1.0
|
||||
uses: actions/setup-node@v7.0.0
|
||||
with:
|
||||
node-version: lts/*
|
||||
cache: 'npm'
|
||||
|
||||
@@ -16,7 +16,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Use Node.js LTS
|
||||
uses: actions/setup-node@v7.1.0
|
||||
uses: actions/setup-node@v7.0.0
|
||||
with:
|
||||
node-version: lts/*
|
||||
cache: 'npm'
|
||||
|
||||
@@ -17,7 +17,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v7.0.1
|
||||
- name: Use Node.js LTS
|
||||
uses: actions/setup-node@v7.1.0
|
||||
uses: actions/setup-node@v7.0.0
|
||||
with:
|
||||
node-version: lts/*
|
||||
cache: 'npm'
|
||||
|
||||
@@ -10,7 +10,13 @@ permissions:
|
||||
|
||||
jobs:
|
||||
prepare_matrix:
|
||||
uses: appium/appium-workflows/.github/workflows/node-lts-matrix.yml@main
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
versions: ${{ steps.generate-matrix.outputs.lts }}
|
||||
steps:
|
||||
- name: Select all current LTS versions of Node.js
|
||||
id: generate-matrix
|
||||
uses: msimerson/node-lts-versions@v2.0.2
|
||||
|
||||
check:
|
||||
needs:
|
||||
@@ -23,7 +29,7 @@ jobs:
|
||||
os: [ubuntu-latest, windows-latest, macos-latest]
|
||||
steps:
|
||||
- name: Use Node.js ${{ matrix.node-version }}
|
||||
uses: actions/setup-node@v7.1.0
|
||||
uses: actions/setup-node@v7.0.0
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
- name: Install Appium
|
||||
|
||||
@@ -16,7 +16,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v7.0.1
|
||||
- name: Use Node.js LTS
|
||||
uses: actions/setup-node@v7.1.0
|
||||
uses: actions/setup-node@v7.0.0
|
||||
with:
|
||||
node-version: lts/*
|
||||
cache: 'npm'
|
||||
|
||||
@@ -13,11 +13,11 @@ on:
|
||||
required: true
|
||||
type: boolean
|
||||
default: false
|
||||
allow_legacy_peer_deps:
|
||||
description: 'Beta branch only: pass --legacy-peer-deps to lerna''s internal npm calls, for when a dependent''s peerDependencies range still lags a just-bumped major (causes ERESOLVE otherwise). Leave off unless you hit that failure.'
|
||||
required: true
|
||||
type: boolean
|
||||
default: false
|
||||
bootstrap_packages:
|
||||
description: 'One-time beta-branch bootstrap only: comma-separated package names (e.g. @appium/base-driver,@appium/support) to force-bump to their next-major beta (premajor --preid beta), bypassing conventional-commit detection. Leave empty for a normal release.'
|
||||
required: false
|
||||
type: string
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -58,30 +58,41 @@ jobs:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
DRY_RUN: ${{ inputs.dry_run }}
|
||||
RECOVER_MISSING_ONLY: ${{ inputs.recover_missing_only }}
|
||||
ALLOW_LEGACY_PEER_DEPS: ${{ inputs.allow_legacy_peer_deps }}
|
||||
BOOTSTRAP_PACKAGES: ${{ inputs.bootstrap_packages }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# On the beta branch ($BETA_BRANCH), every release is a beta prerelease anchored at its
|
||||
# target major (see packages/semantic-release-config's "Next-major beta branches" docs
|
||||
# for the equivalent semantic-release behavior this mirrors).
|
||||
#
|
||||
# allow_legacy_peer_deps: independent next-major beta.0 bumps can briefly outrun a
|
||||
# dependent's committed peerDependencies range, aborting lerna's internal lockfile
|
||||
# refresh with ERESOLVE. Opt-in only - it masks a real (if temporary) peer mismatch.
|
||||
LEGACY_PEER_DEPS_FLAGS=""
|
||||
if [ "$ALLOW_LEGACY_PEER_DEPS" = "true" ]; then
|
||||
LEGACY_PEER_DEPS_FLAGS="--npm-client-args=--legacy-peer-deps"
|
||||
fi
|
||||
|
||||
BETA_FLAGS=""
|
||||
DIST_TAG_FLAGS=""
|
||||
NPM_TAG_FLAGS=""
|
||||
if [ "${{ github.ref_name }}" = "$BETA_BRANCH" ]; then
|
||||
BETA_FLAGS="--conventional-prerelease --preid beta $LEGACY_PEER_DEPS_FLAGS"
|
||||
BETA_FLAGS="--conventional-prerelease --preid beta"
|
||||
DIST_TAG_FLAGS="--dist-tag beta"
|
||||
# `npm publish` takes --tag; --dist-tag is lerna-only
|
||||
NPM_TAG_FLAGS="--tag beta"
|
||||
fi
|
||||
|
||||
# One-time bootstrap for packages just starting their beta train: force them
|
||||
# straight to <next-major>.0.0-beta.0 instead of waiting for/relying on a commit that
|
||||
# happens to be marked as breaking. Not part of the normal release flow below - this
|
||||
# exits early on its own.
|
||||
if [ -n "$BOOTSTRAP_PACKAGES" ]; then
|
||||
if [ "${{ github.ref_name }}" != "$BETA_BRANCH" ]; then
|
||||
echo "bootstrap_packages is only meaningful on the $BETA_BRANCH branch" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ "$RECOVER_MISSING_ONLY" = "true" ]; then
|
||||
echo "bootstrap_packages cannot be combined with recover_missing_only" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Bootstrapping ${BOOTSTRAP_PACKAGES} to their next-major beta (premajor --preid beta), bypassing conventional-commit detection"
|
||||
if [ "$DRY_RUN" = "true" ]; then
|
||||
printf "n\n" | npx lerna version premajor --preid beta --exact --no-git-tag-version --no-push --force-publish="$BOOTSTRAP_PACKAGES"
|
||||
else
|
||||
npx lerna publish premajor --preid beta --exact --force-publish="$BOOTSTRAP_PACKAGES" --dist-tag beta --yes
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Prints "<pkg_name>@<pkg_version>" to stdout for each non-private workspace package
|
||||
@@ -144,7 +155,7 @@ jobs:
|
||||
|
||||
echo "Publishing ${pkg_spec}"
|
||||
set +e
|
||||
(cd "$pkg_dir" && npm publish $NPM_TAG_FLAGS)
|
||||
(cd "$pkg_dir" && npm publish $DIST_TAG_FLAGS)
|
||||
publish_exit_code=$?
|
||||
set -e
|
||||
if [ $publish_exit_code -ne 0 ]; then
|
||||
@@ -183,7 +194,7 @@ jobs:
|
||||
|
||||
if [ "$DRY_RUN" = "true" ]; then
|
||||
echo "Running lerna publish in dry-run mode"
|
||||
printf "n\n" | npx lerna version --no-git-tag-version --no-push $BETA_FLAGS
|
||||
printf "n\n" | npx lerna version --exact --no-git-tag-version --no-push $BETA_FLAGS
|
||||
else
|
||||
echo "Running lerna publish for real"
|
||||
set +e
|
||||
|
||||
@@ -47,4 +47,4 @@ jobs:
|
||||
if [ "${{ github.ref_name }}" = "$BETA_BRANCH" ]; then
|
||||
BETA_FLAGS="--conventional-prerelease --preid beta"
|
||||
fi
|
||||
npx lerna version --yes $BETA_FLAGS
|
||||
npx lerna version --exact --yes $BETA_FLAGS
|
||||
|
||||
@@ -6,12 +6,14 @@ on:
|
||||
paths:
|
||||
- '.github/workflows/renovate.yml' # this file
|
||||
- '.renovaterc.json'
|
||||
- 'renovate/default.json'
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
paths:
|
||||
- '.github/workflows/renovate.yml' # this file
|
||||
- '.renovaterc.json'
|
||||
- 'renovate/default.json'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -25,4 +27,4 @@ jobs:
|
||||
- name: Validate Renovate Config
|
||||
uses: rinchsan/renovate-config-validator@v0.2.1
|
||||
with:
|
||||
pattern: '.renovaterc.json'
|
||||
pattern: '{.renovaterc.json,renovate/default.json}'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
# Do not disable package-lock. Disabling package-lock also disables npm-shrinkwrap
|
||||
package-lock=true
|
||||
save-exact=true
|
||||
foreground-scripts=true
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": ["github>appium/appium-workflows//renovate/default"],
|
||||
"extends": ["github>appium/appium//renovate/default"],
|
||||
"schedule": ["after 10pm", "before 5:00am"],
|
||||
"timezone": "America/Vancouver"
|
||||
}
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
# Repository guidance
|
||||
|
||||
Before changing code, read and follow the
|
||||
[contributor style guide](packages/appium/docs/en/contributing/index.md#code-style).
|
||||
@@ -0,0 +1,38 @@
|
||||
import appiumConfig from '@appium/eslint-config-appium-ts';
|
||||
import {defineConfig, globalIgnores} from 'eslint/config';
|
||||
|
||||
// Create a modified config subset for test support files:
|
||||
// Extract the test file related configs (Mocha plugin and custom rules),
|
||||
// then override their 'files' property (match by name — resilient to new config entries).
|
||||
const testFileConfigItems = appiumConfig.filter(
|
||||
(item) => typeof item?.name === 'string' && item.name.startsWith('Test Files'),
|
||||
);
|
||||
const testSupportFiles = ['packages/driver-test-support/lib/**', 'packages/plugin-test-support/lib/**'];
|
||||
const testSupportConfig = testFileConfigItems.map((item) => ({...item, files: testSupportFiles}));
|
||||
|
||||
export default defineConfig([
|
||||
{
|
||||
name: 'Base Config',
|
||||
extends: [appiumConfig],
|
||||
},
|
||||
{
|
||||
name: 'Test Support',
|
||||
extends: [testSupportConfig],
|
||||
},
|
||||
{
|
||||
name: 'Consistent type-only imports (all packages)',
|
||||
files: ['**/*.{ts,tsx,mtsx}'],
|
||||
rules: {
|
||||
'@typescript-eslint/consistent-type-imports': [
|
||||
'error',
|
||||
{fixStyle: 'separate-type-imports', prefer: 'type-imports'},
|
||||
],
|
||||
},
|
||||
},
|
||||
globalIgnores([
|
||||
'**/build-fixtures/**',
|
||||
'packages/appium/docs/**/assets/**',
|
||||
'packages/appium/docs/**/js/**',
|
||||
'packages/appium/sample-code/**',
|
||||
]),
|
||||
]);
|
||||
+5
-1
@@ -2,6 +2,9 @@
|
||||
"$schema": "https://json.schemastore.org/lerna",
|
||||
"changelogPreset": "conventional-changelog-conventionalcommits",
|
||||
"command": {
|
||||
"add": {
|
||||
"exact": true
|
||||
},
|
||||
"publish": {
|
||||
"message": "chore: publish"
|
||||
},
|
||||
@@ -11,7 +14,8 @@
|
||||
"version": {
|
||||
"conventionalCommits": true,
|
||||
"createRelease": "github",
|
||||
"allowBranch": ["master", "appium4"]
|
||||
"allowBranch": ["master", "appium4"],
|
||||
"exact": true
|
||||
}
|
||||
},
|
||||
"ignoreChanges": ["**/test/**", "**/*.md"],
|
||||
|
||||
Generated
+7500
-4050
File diff suppressed because it is too large
Load Diff
+23
-11
@@ -48,6 +48,7 @@
|
||||
"docs": "npm run -w packages/appium build:docs",
|
||||
"docs:preview": "npm run -w packages/appium build:docs:preview",
|
||||
"docs:publish": "npm run -w packages/appium publish:docs",
|
||||
"doctor": "node ./scripts/doctor-stub.mjs",
|
||||
"install-docs-deps": "npm run -w packages/appium install-docs-deps",
|
||||
"format": "oxfmt -c oxfmt.config.mjs .",
|
||||
"format:check": "oxfmt -c oxfmt.config.mjs --check .",
|
||||
@@ -61,7 +62,7 @@
|
||||
"rebuild": "run-s clean build",
|
||||
"reinstall": "run-s clean clean:deps ci",
|
||||
"reinstall:angry": "npm run clean:dangerously && npm ci",
|
||||
"release": "lerna publish",
|
||||
"release": "lerna publish --exact",
|
||||
"stage-synced-pkgs": "git add -A packages/appium/README.md \"packages/*/package.json\"",
|
||||
"start": "appium",
|
||||
"sync-pkgs": "node ./scripts/sync-monorepo-packages.mjs",
|
||||
@@ -79,37 +80,48 @@
|
||||
"zip-and-upload": "run-s zip upload"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@appium/oxc-config": "2.0.0-beta.0",
|
||||
"@tsconfig/node22": "22.0.0",
|
||||
"@appium/oxc-config": "1.0.0",
|
||||
"@tsconfig/node20": "20.1.10",
|
||||
"@types/async-lock": "1.4.2",
|
||||
"@types/bluebird": "3.5.42",
|
||||
"@types/content-disposition": "0.5.9",
|
||||
"@types/express": "5.0.6",
|
||||
"@types/finalhandler": "1.2.4",
|
||||
"@types/jsftp": "2.1.5",
|
||||
"@types/json-schema": "7.0.15",
|
||||
"@types/klaw": "3.0.7",
|
||||
"@types/lockfile": "1.0.4",
|
||||
"@types/method-override": "3.0.0",
|
||||
"@types/mime-types": "3.0.1",
|
||||
"@types/morgan": "1.9.10",
|
||||
"@types/node": "24.19.1",
|
||||
"@types/picomatch": "4.0.3",
|
||||
"@types/node": "24.13.6",
|
||||
"@types/plist": "3.0.5",
|
||||
"@types/pluralize": "0.0.33",
|
||||
"@types/semver": "7.8.0",
|
||||
"@types/serve-favicon": "2.5.7",
|
||||
"@types/shell-quote": "1.7.5",
|
||||
"@types/sinon": "22.0.0",
|
||||
"@types/which": "3.0.4",
|
||||
"@types/ws": "8.18.1",
|
||||
"@types/yargs": "17.0.35",
|
||||
"asyncbox": "6.5.0",
|
||||
"asyncbox": "6.4.3",
|
||||
"conventional-changelog-conventionalcommits": "9.3.1",
|
||||
"cpy-cli": "7.0.0",
|
||||
"cross-env": "10.1.0",
|
||||
"finalhandler": "2.1.1",
|
||||
"json-schema-to-typescript": "16.0.0",
|
||||
"lerna": "10.0.1",
|
||||
"mjpeg-consumer": "2.0.0",
|
||||
"mjpeg-server": "0.3.1",
|
||||
"npm-run-all2": "9.0.3",
|
||||
"rewiremock": "3.14.6",
|
||||
"rimraf": "6.1.3",
|
||||
"serve-static": "2.2.1",
|
||||
"sinon": "22.1.0",
|
||||
"teen_process": "4.2.1",
|
||||
"tsd": "0.33.0",
|
||||
"typescript": "6.0.3",
|
||||
"webdriverio": "9.32.0",
|
||||
"ws": "8.22.0"
|
||||
"webdriverio": "9.31.9",
|
||||
"ws": "8.21.3"
|
||||
},
|
||||
"overrides": {
|
||||
"@sidvind/better-ajv-errors": {
|
||||
@@ -118,10 +130,10 @@
|
||||
"ajv-formats": {
|
||||
"ajv": "8.20.0"
|
||||
},
|
||||
"http-cache-semantics": "4.3.0"
|
||||
"http-cache-semantics": "4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.22.2 || ^24.15.0 || >=26.0.0",
|
||||
"node": "^20.19.0 || ^22.12.0 || >=24.0.0",
|
||||
"npm": ">=10"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,257 +3,17 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## [4.0.0-beta.6](https://github.com/appium/appium/compare/appium@4.0.0-beta.5...appium@4.0.0-beta.6) (2026-10-26)
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* **support:** ExtractAllOptions.useSystemUnzip is removed.
|
||||
* **support:** Non-UTF-8-flagged file names now default to utf8 instead of cp437, and cp437 decoding is no longer supported (modern archives use UTF-8). Such archives must be recreated or converted; fileNamesEncoding only accepts Node.js BufferEncodings.
|
||||
* **appium:** install local extensions without global npm links (#23086)
|
||||
* **base-driver:** preserve proxied command validation ordering (#23060)
|
||||
* **base-driver:** The protected BaseDriver#commandsQueueGuard beyond promise-based acquire(key, fn) - it is now an asyncbox AsyncLock, so callback-style acquire() and the internal queues field are gone (use getQueueLength() / isBusy()).
|
||||
* **base-driver:** validate every timeout capability candidate (#23062)
|
||||
* **appium:** removed the --callback-address (-ca) server argument and the server.callback-address config property
|
||||
* **appium:** removed the --callback-port (-cp) server argument and the server.callback-port config property
|
||||
* **appium:** removed the --debug-log-spacing server argument and the server.debug-log-spacing config property
|
||||
* **appium:** removed the --strict-caps server argument and the server.strict-caps config property
|
||||
* **appium:** removed the --trace-dir server argument and the server.trace-dir config property
|
||||
* **base-driver:** POST body has to be a JSON object, otherwise the server returns invalid argument error.
|
||||
## [3.8.0](https://github.com/appium/appium/compare/appium@3.7.0...appium@3.8.0) (2026-09-24)
|
||||
|
||||
### Features
|
||||
|
||||
* **support:** Remove system unzip from extractAllTo ([#23091](https://github.com/appium/appium/issues/23091)) ([0f1a761](https://github.com/appium/appium/commit/0f1a76184b78ee3d60652b9a610c808213196f7c))
|
||||
* **appium:** accept package names for installed extension commands ([#22747](https://github.com/appium/appium/issues/22747)) ([6c911de](https://github.com/appium/appium/commit/6c911debd72cb7fe094d27671d1cf14098ff537a))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **appium:** install local extensions without global npm links ([#23086](https://github.com/appium/appium/issues/23086)) ([3615d6d](https://github.com/appium/appium/commit/3615d6df4c5a785524092f8c28dc338385a4468a))
|
||||
* **appium:** preserve npm arguments on Windows ([#22957](https://github.com/appium/appium/issues/22957)) ([dd71f66](https://github.com/appium/appium/commit/dd71f66e4ac343bc48e78f5b661ca02b351553c1))
|
||||
* **appium:** remove unused server arguments ([#23063](https://github.com/appium/appium/issues/23063)) ([16c84ea](https://github.com/appium/appium/commit/16c84ea20314f605b93070de283818a78c0ed4bb))
|
||||
* **appium:** send log webhooks to ipv6 hosts ([#23061](https://github.com/appium/appium/issues/23061)) ([819905b](https://github.com/appium/appium/commit/819905beb265431446ec56776373ec15f13a0a8f))
|
||||
* **base-driver:** preserve proxied command validation ordering ([#23060](https://github.com/appium/appium/issues/23060)) ([6cc4095](https://github.com/appium/appium/commit/6cc4095c59bc7ce23b47ce768707aae978794824))
|
||||
* **base-driver:** reject command POST bodies that are not JSON objects ([#23007](https://github.com/appium/appium/issues/23007)) ([39e9512](https://github.com/appium/appium/commit/39e9512b4a4c936edae0d7a56bdd4bd613075322))
|
||||
* **base-driver:** use AsyncLock from asyncbox instead of async-lock ([#23066](https://github.com/appium/appium/issues/23066)) ([17421ae](https://github.com/appium/appium/commit/17421ae61fa9f9e74a52b116f3ed2ee3c09fbc1f))
|
||||
* **base-driver:** validate every timeout capability candidate ([#23062](https://github.com/appium/appium/issues/23062)) ([531f482](https://github.com/appium/appium/commit/531f482d8759e7c621276b212489b764a994766a))
|
||||
* **docs:** correct stale instructions in .NET quickstart ([#23049](https://github.com/appium/appium/issues/23049)) ([2dd05e1](https://github.com/appium/appium/commit/2dd05e12d3e5911203856977120813ce56b69552))
|
||||
* **docs:** X-Appium-Is-Sensitive also accepts the value 'yes' ([#23051](https://github.com/appium/appium/issues/23051)) ([2cf7f4e](https://github.com/appium/appium/commit/2cf7f4e6b21fdf36f85986187d5361d980f7cb42))
|
||||
* **support:** prevent zip extraction through symlink chains ([#23002](https://github.com/appium/appium/issues/23002)) ([8e42cbc](https://github.com/appium/appium/commit/8e42cbc82d95da690b73399782f750043464352d))
|
||||
|
||||
|
||||
## [4.0.0-beta.5](https://github.com/appium/appium/compare/appium@4.0.0-beta.4...appium@4.0.0-beta.5) (2026-10-18)
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* **base-driver:** match standard capability names case-sensitively (#22976)
|
||||
* **appium:** Drivers must use base-driver with shared command activity tracking. Custom timeout implementations must delegate timer creation to super.startNewCommandTimeout(); legacy private-counter implementations are no longer protected by method overrides.
|
||||
|
||||
* add fake driver/plugin example
|
||||
|
||||
* remove from readme
|
||||
|
||||
* fix(appium): release one proxied BiDi command per response
|
||||
|
||||
* test(appium): cover overlapping duplicate BiDi command IDs
|
||||
* **appium:** Drivers must use base-driver with shared command activity tracking. Custom timeout implementations must delegate timer creation to super.startNewCommandTimeout(); legacy private-counter implementations are no longer protected by method overrides.
|
||||
|
||||
* add fake driver/plugin example
|
||||
|
||||
* remove from readme
|
||||
|
||||
* Remove actions needed for driver updates in migration guide
|
||||
|
||||
Removed the section detailing actions needed for driver updates related to shared command activity tracking.
|
||||
|
||||
* refactor(base-driver): simplify shutdown promise handling
|
||||
|
||||
* Add actions needed for custom startNewCommandTimeout
|
||||
|
||||
Updated migration guide to include new requirements for custom command timeout implementations.
|
||||
* **types:** the locale, language, autoWebview, orientation and udid capabilities are no longer part of the standard capability constraints. They are not generic enough and must be defined by the corresponding drivers.
|
||||
* **types:** the deprecated appium:autoLaunch capability is no longer part of the standard capability constraints.
|
||||
|
||||
### Features
|
||||
|
||||
* **appium:** fallback to latest compatible extension version for CLI `install` ([#22951](https://github.com/appium/appium/issues/22951)) ([0b3fe1c](https://github.com/appium/appium/commit/0b3fe1ce35fd40eea8f91a3e8f9846ee03445276))
|
||||
* **types:** remove deprecated autoLaunch capability ([#22950](https://github.com/appium/appium/issues/22950)) ([8822cea](https://github.com/appium/appium/commit/8822ceaabb68a213a8244e4f955d8ee68221e329))
|
||||
* **types:** remove driver-specific capabilities from base constraints ([#22952](https://github.com/appium/appium/issues/22952)) ([cce0b58](https://github.com/appium/appium/commit/cce0b5814d94157caa6a25834a469277ad1a4dcc))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **appium:** apply default capabilities to every firstMatch candidate ([#22988](https://github.com/appium/appium/issues/22988)) ([f820e04](https://github.com/appium/appium/commit/f820e04000f138addab57917ef92d01071596f96))
|
||||
* **appium:** classify driver selection failures as session not created ([#22970](https://github.com/appium/appium/issues/22970)) ([9b1ddb8](https://github.com/appium/appium/commit/9b1ddb8bf6cb51ce93114b70c536d0db18b39bfa))
|
||||
* **appium:** suspend idle timeout during BiDi commands ([#22947](https://github.com/appium/appium/issues/22947)) ([3f82e6a](https://github.com/appium/appium/commit/3f82e6a1817de5acb6584b92c98bd156295060d3))
|
||||
* **appium:** track idle timeout across plugin commands ([#22946](https://github.com/appium/appium/issues/22946)) ([c10c413](https://github.com/appium/appium/commit/c10c41384cdb4276faaab1a908cf9f80a77464a5))
|
||||
* **base-driver:** match standard capability names case-sensitively ([#22976](https://github.com/appium/appium/issues/22976)) ([f3edfc5](https://github.com/appium/appium/commit/f3edfc5e03deb6821599614a35cf5ec5df03a3c3)), closes [#22966](https://github.com/appium/appium/issues/22966)
|
||||
* **base-driver:** preserve capability invalid argument errors ([#22977](https://github.com/appium/appium/issues/22977)) ([b452a5e](https://github.com/appium/appium/commit/b452a5eade468d6c20a62c89357f72f492441038)), closes [#22966](https://github.com/appium/appium/issues/22966)
|
||||
* **base-driver:** validate and merge all capability candidates ([#22982](https://github.com/appium/appium/issues/22982)) ([aba33a2](https://github.com/appium/appium/commit/aba33a2d17621e5db28e4505773c6603b075e7f2))
|
||||
* **base-driver:** validate standard timeouts and preserve null values ([#22961](https://github.com/appium/appium/issues/22961)) ([eef8246](https://github.com/appium/appium/commit/eef8246f8a6983c7818c99bfd94d5ae7ec8bfa1e))
|
||||
|
||||
|
||||
## [4.0.0-beta.4](https://github.com/appium/appium/compare/appium@4.0.0-beta.3...appium@4.0.0-beta.4) (2026-10-09)
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* **appium:** Replace the `windows` known-driver shortcut with `wincore` pointing to appium-wincore-driver instead of the obsolete appium-windows-driver
|
||||
|
||||
### Features
|
||||
|
||||
* **appium:** replace obsolete windows driver with appium-wincore-driver ([#22917](https://github.com/appium/appium/issues/22917)) ([7544a10](https://github.com/appium/appium/commit/7544a1008d96f44f19499500314b6ae21d54d4f2))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **appium:** prevent recursion when logging the first BiDi event of a method ([#22897](https://github.com/appium/appium/issues/22897)) ([e230727](https://github.com/appium/appium/commit/e230727090f24a3c777c88de9d43d83ff94ea97d))
|
||||
* centralize URL hostname formatting and bracket IPv6 hosts ([#22914](https://github.com/appium/appium/issues/22914)) ([c5ddcef](https://github.com/appium/appium/commit/c5ddcef8940dfa5fac8d180bed65dc80ba8fafab))
|
||||
* tune wincore driver integration ([#22922](https://github.com/appium/appium/issues/22922)) ([9f8455e](https://github.com/appium/appium/commit/9f8455e1973e97c8a6451a9291de741dadfed775))
|
||||
|
||||
|
||||
## [4.0.0-beta.3](https://github.com/appium/appium/compare/appium@4.0.0-beta.2...appium@4.0.0-beta.3) (2026-10-05)
|
||||
|
||||
### Features
|
||||
|
||||
* **universal-xml-plugin:** add execute methods to toggle translation ([#22862](https://github.com/appium/appium/issues/22862)) ([b95aaac](https://github.com/appium/appium/commit/b95aaac60bed065ce0a0d1e4f7baf9c5e60572b1)), closes [#21630](https://github.com/appium/appium/issues/21630)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **appium:** apply initial settings from selected capabilities ([#22882](https://github.com/appium/appium/issues/22882)) ([95c0461](https://github.com/appium/appium/commit/95c04611e7d1cd8acfa4c6ce51276899938588d3))
|
||||
* **appium:** bracket IPv6 hosts in BiDi websocket URLs ([#22872](https://github.com/appium/appium/issues/22872)) ([3875344](https://github.com/appium/appium/commit/3875344e111dc23e4c99310ad918b769dbb38927))
|
||||
* **appium:** close bidi sockets when a session ends unexpectedly ([#22854](https://github.com/appium/appium/issues/22854)) ([3cdc69b](https://github.com/appium/appium/commit/3cdc69b198e85607b4f35a5b3f57b542b0ae9b80))
|
||||
* **appium:** detect project homes with prerelease dependencies ([#22871](https://github.com/appium/appium/issues/22871)) ([11d9904](https://github.com/appium/appium/commit/11d9904166c9e692e6fa8491acfce4ac892c1a8e))
|
||||
* **appium:** do not crash when a proxied bidi socket closes without a sendable code ([#22835](https://github.com/appium/appium/issues/22835)) ([66ab396](https://github.com/appium/appium/commit/66ab396a71c419f1fb456b8a1ddf23bc3491baf8))
|
||||
* **appium:** explain manual recovery after manifest lock timeouts ([#22875](https://github.com/appium/appium/issues/22875)) ([b9c020c](https://github.com/appium/appium/commit/b9c020c6ebf88643ffe6b6d5e302b43673bbb028))
|
||||
* **appium:** import extensions through escaped file URLs ([#22884](https://github.com/appium/appium/issues/22884)) ([8312252](https://github.com/appium/appium/commit/83122525db72f2d6ff06e27cd3da5269318be3a8))
|
||||
* **appium:** match global and module BiDi event subscriptions ([#22883](https://github.com/appium/appium/issues/22883)) ([879873b](https://github.com/appium/appium/commit/879873bad5669c9b264f3fcb60d05562f6ca3b1e))
|
||||
* **appium:** resolve default extension export conditions ([#22885](https://github.com/appium/appium/issues/22885)) ([3188c9f](https://github.com/appium/appium/commit/3188c9fbab17c16192a6e75ff62f69f4d844be8f))
|
||||
* **appium:** roll back sessions when initialization fails ([#22873](https://github.com/appium/appium/issues/22873)) ([f24e704](https://github.com/appium/appium/commit/f24e7046eb2815822f655a644aee9786d90fd4e8))
|
||||
* **appium:** start idle timeout after session initialization ([#22881](https://github.com/appium/appium/issues/22881)) ([e37f1c1](https://github.com/appium/appium/commit/e37f1c158394617bcaa474da25f1650b9b24ebd1))
|
||||
* **base-driver:** track and remove BiDi subscriptions by ID ([#22876](https://github.com/appium/appium/issues/22876)) ([b791915](https://github.com/appium/appium/commit/b791915ffcf322e1cc84dbde606be55d34f020b3))
|
||||
* use native ESM entrypoint detection ([#22868](https://github.com/appium/appium/issues/22868)) ([e391bb2](https://github.com/appium/appium/commit/e391bb249fec5f700a6d63a747ff921a80689fb5))
|
||||
|
||||
|
||||
## [4.0.0-beta.2](https://github.com/appium/appium/compare/appium@4.0.0-beta.1...appium@4.0.0-beta.2) (2026-09-27)
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* **base-driver:** @appium/base-driver no longer exports server, normalizeBasePath, configureServer, ServerOpts, ConfigureServerOpts, ConfigureHttpOpts, or StartServerOpts, and no longer depends on express/morgan/body-parser/ method-override/path-to-regexp. Use the new @appium/http-server package instead.
|
||||
* **base-driver:** appium/driver.js and driver.d.ts no longer re-export server/normalizeBasePath/configureServer/ServerOpts (or their types), and no longer use a blanket export *. Import from @appium/http-server directly if you were relying on this undocumented path.
|
||||
|
||||
### Features
|
||||
|
||||
* **appium:** accept package names for installed extension commands ([#22747](https://github.com/appium/appium/issues/22747)) ([#22812](https://github.com/appium/appium/issues/22812)) ([b7356ee](https://github.com/appium/appium/commit/b7356ee53eec3e322707eef0d2bd37976a47cfd2))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **appium:** release the manifest lock before errAndQuit exits ([#22821](https://github.com/appium/appium/issues/22821)) ([dc0568b](https://github.com/appium/appium/commit/dc0568bc658961f5d6a28fb955d8092d51cf9523))
|
||||
* **base-driver:** carry proxy req via AsyncLocalStorage instead of args ([#22799](https://github.com/appium/appium/issues/22799)) ([2596da0](https://github.com/appium/appium/commit/2596da02d201d7e5fbfd24cf9dd2801302f8abc7))
|
||||
* **support:** narrow fs.glob overload for default withFileTypes/lazy ([#22795](https://github.com/appium/appium/issues/22795)) ([09a04f4](https://github.com/appium/appium/commit/09a04f48831e17b9b7f3b8dc0a72f0df5096ae51))
|
||||
|
||||
### Code Refactoring
|
||||
|
||||
* **base-driver:** extract the HTTP/Express server into @appium/http-server ([#22800](https://github.com/appium/appium/issues/22800)) ([225a1c6](https://github.com/appium/appium/commit/225a1c6d9d24fa2696699d4b61436a49b847d666))
|
||||
|
||||
|
||||
## [4.0.0-beta.1](https://github.com/appium/appium/compare/appium@4.0.0-beta.0...appium@4.0.0-beta.1) (2026-09-19)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **deps:** catch up peerDependencies to published beta.0; drop bootstrap_packages ([#22793](https://github.com/appium/appium/issues/22793)) ([b09efc3](https://github.com/appium/appium/commit/b09efc31c6967bbcf2c4314db9d2a0b6454fa8fb))
|
||||
|
||||
|
||||
## [4.0.0-beta.0](https://github.com/appium/appium/compare/appium@3.7.0...appium@4.0.0-beta.0) (2026-09-19)
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* **base-driver:** align timeouts endpoints closer to W3C standard (#22776)
|
||||
* users relying on the implicit debug default for console/file logs will now see info-level output unless they explicitly pass --log-level debug.
|
||||
* **support:** Any script or tool that consumes Appium CLI output (driver/plugin list/install/update, doctor, etc.) and relies on the previous stream layout will need to be updated. Previously, non-JSON human-readable output (info/success/warning messages) was written to STDERR, with STDOUT reserved almost exclusively for --json output. Now that output goes to STDOUT, and only actual errors go to STDERR.
|
||||
* **support:** Scripts that discarded STDOUT (1>/dev/null) to suppress "chatter" while relying on STDERR for status text will now see that text on STDOUT instead.
|
||||
* **support:** Scripts that captured STDERR to detect/log informational or success messages will no longer see them there — only genuine errors will appear on STDERR. --json output and error behavior are unaffected: --json continues to write clean JSON to STDOUT only, and errors continue to go to STDERR.
|
||||
* **support:** @appium/logger's Log class changes its default output stream from STDERR to STDOUT for all levels except error, and adds an errorStream/stderrLevel pair of properties. Any code that set .stream on a Log instance expecting it to capture all levels (including error) will now need to also set .errorStream to the same target.
|
||||
* **base-driver:** @appium/base-driver's default export (BaseDriver) and @appium/base-driver's basedriver/helpers.js default export are removed; use the named exports instead. The appium/driver.js and driver.d.ts re-exports of the default are removed accordingly.
|
||||
* **base-driver:** BaseDriver.reset() is removed; it was unused, not part of any protocol route or the Driver interface, and had no callers in this monorepo or any driver package that was checked.
|
||||
* **base-driver:** BaseDriver's constructor is removed in favor of inherited DriverCore construction; opts is no longer a required constructor argument (it now defaults to {}, matching DriverCore).
|
||||
* **support:** @appium/support's fs.glob option shape changed from the glob package's GlobOptions to a smaller, @appium/support-owned GlobOptions interface. Supported fields: cwd, withFileTypes, absolute, lazy. Options like nodir/ignore/nocase are no longer supported directly — callers needing directory filtering can pass withFileTypes: true and filter on .isFile()/.isDirectory(); callers needing path exclusion can filter the returned array by pattern.
|
||||
* **appium:** The --allow-cors CLI flag and allow-cors config file property have been removed. Use --allow-insecure=*:cors (or --relaxed-security, optionally overridden with --deny-insecure=*:cors) instead.
|
||||
* **base-driver:** ISessionHandler.createSession (@appium/types) and LegacyCreateSessionArgs — overload and type deleted, single-argument signature only.
|
||||
* **base-driver:** BaseDriver.createSession and AppiumDriver.createSession — collapsed to the single-argument mplementation; capability validation now checks the one argument directly instead of scanning three positions for the first W3C-shaped value.
|
||||
* **base-driver:** FakeDriver.createSession (and the base-driver e2e test double) — overrides updated to match.
|
||||
* **base-driver:** RelaxedCapsPlugin.createSession — this plugin existed specifically to normalize capabilities across the (now-gone) three positions; its hook is simplified to a single caps argument.
|
||||
* **base-driver:** POST /session wire route (w3c.ts) — payloadParams.optional no longer sends capabilities three times into the command args.
|
||||
* **base-driver:** BaseDriver.getSession, ISessionHandler.getSession, and the GET /session/:sessionId JSONWP route are gone. Use getAppiumSessionCapabilities to retrieve session capabilities and EventCommands.getLogEvents to retrieve event history instead.
|
||||
* **base-driver:** The appium:eventTimings capability is removed; it only ever controlled whether getSession's response was decorated with event history, which getLogEvents already exposes unconditionally.
|
||||
* **support:** move npm-related helpers into appium package (#22721)
|
||||
* **logger:** @appium/logger and @appium/support no longer export a default log — import the named log export instead.
|
||||
* **logger:** AppiumLogger#errorAndThrow has been removed; use errorWithException instead.
|
||||
* **logger:** Logger#enableProgress, disableProgress, progressEnabled, enableUnicode, disableUnicode have been removed; they were already permanently disabled no-ops.
|
||||
* **base-plugin:** Plugin#logger has been removed; use Plugin#log instead.
|
||||
* **base-plugin:** @appium/base-plugin no longer exports BasePlugin as the default export; use the named BasePlugin export.
|
||||
* Core.driverData, DriverData, and the driverData parameter on ISessionHandler.createSession/deleteSession are gone. Any driver overriding get driverData() or relying on the umbrella driver passing sibling-session data into createSession/deleteSession needs to migrate off this mechanism.
|
||||
* FakeDriver no longer supports the uniqueApp capability.
|
||||
* **support:** npm.installPackage now takes a hasAppiumDependency boolean computed by the caller instead of importing the check itself, avoiding a support -> appium dependency.
|
||||
* **support:** The env export is removed from @appium/support.
|
||||
* the minimum supported Node.js engine is set to ^22.22.2 || ^24.15.0 || >=26.0.0
|
||||
* **base-driver:** @appium/base-driver no longer exports statusCodes or getSummaryByCode (the jsonwp-status module was removed).
|
||||
* **base-driver:** errorFromMJSONWPStatusCode (aliased as errorFromCode) has been removed; use errorFromW3CJsonCode for W3C error-signature mapping.
|
||||
* **base-driver:** ProtocolError instances no longer have a jsonwpCode property.
|
||||
* **base-driver:** WebDriverProxy (formerly JWProxy) no longer proxies to or interprets responses from downstream servers speaking the legacy MJSONWP protocol; the ProtocolConverter class, COMMAND_URLS_CONFLICTS, and the downstreamProtocol getter/setter have been removed. Downstream automation servers must speak W3C WebDriver.
|
||||
* **base-driver:** Responses no longer duplicate element references under the legacy ELEMENT key; only the W3C element-6066-11e4-a52e-4f735466cecf key is present. The MJSONWP_ELEMENT_KEY constant has been removed.
|
||||
* **base-driver:** determineProtocol has been removed, and drivers can no longer produce the legacy {sessionId, status, value} response shape; all responses are now W3C-shaped regardless of how the client formatted its createSession capabilities.
|
||||
* **base-driver:** DriverCore#setProtocolMJSONWP() has been removed.
|
||||
* **base-driver:** The deprecated JWProxy export has been removed; use WebDriverProxy instead. Its source also moved from lib/jsonwp-proxy/proxy.js to lib/wd-proxy/proxy.js.
|
||||
* **base-driver:** DriverCore#isMjsonwpProtocol() has been removed.
|
||||
* **support:** The following @appium/support exports have been removed: process (getProcessIds, killProcess), mkdirp, imageUtil (requireSharp, cropBase64Image), mjpeg (MJpegStream), net's FTP upload
|
||||
support (FtpUploadOptions, NotHttpUploadOptions; uploadFile only supports http/https now), util's uuidV1/uuidV3/uuidV5/localIp/cancellableDelay/multiResolve, and fs's readPackageJsonFrom/findRoot/ F_OK/R_OK/W_OK/X_OK.
|
||||
* **appium:** The --nodeconfig server argument and the server.nodeconfig config file property no longer exist. Users who need to register with a Selenium Grid should use the Grid 4 relay feature instead (see the Grid guide).
|
||||
* **base-driver:** TLS-enabled Appium servers no longer negotiate SPDY/HTTP2 (spdy/2, spdy/3, spdy/3.1, h2) via ALPN; connections are now served as plain HTTPS (HTTP/1.1) using Node's native https module. Clients relying on SPDY or HTTP/2 multiplexing against Appium's TLS listener must switch to HTTP/1.1.
|
||||
* **appium:** `npm install -g appium --drivers=... --plugins=...` no longer installs extensions automatically. Use `appium driver/plugin install` or add extensions to package.json instead.
|
||||
* require('@appium/support') no longer works; consumers must import it instead.
|
||||
* require('@appium/base-driver') no longer works; drivers extending BaseDriver via require must switch to import.
|
||||
* require('@appium/base-plugin') no longer works; plugins extending BasePlugin via require must switch to import.
|
||||
* require('appium') no longer works; plugins extending the package via require must switch to import.
|
||||
* require('@appium/fake-plugin') no longer works; consumers must import it instead.
|
||||
* require('@appium/fake-driver') no longer works; consumers must import it instead.
|
||||
* require('@appium/types') no longer works; consumers must import it instead.
|
||||
* require('@appium/logger') no longer works; consumers must import it instead.
|
||||
* require('@appium/schema') no longer works; consumers must import it instead.
|
||||
|
||||
### Features
|
||||
|
||||
* **appium:** add --app-url-rules server arg to restrict remote app URLs ([#22753](https://github.com/appium/appium/issues/22753)) ([0b104f6](https://github.com/appium/appium/commit/0b104f6bf9b7180b111df40fd6a15b26d649eabd))
|
||||
* **appium:** remove postinstall autoinstall-extensions script ([#22675](https://github.com/appium/appium/issues/22675)) ([cd0d8f1](https://github.com/appium/appium/commit/cd0d8f14e9d5906ecd1b438038a7f67f74f742fc))
|
||||
* **appium:** remove Selenium Grid 3 support ([#22677](https://github.com/appium/appium/issues/22677)) ([8fcdcb3](https://github.com/appium/appium/commit/8fcdcb30b07c1ee582256fbef3538d6a3ceea5f2))
|
||||
* **appium:** replace --allow-cors flag with --allow-insecure=*:cors ([#22731](https://github.com/appium/appium/issues/22731)) ([926a0a5](https://github.com/appium/appium/commit/926a0a594935a6cf2e7375eb174eeb15af964f12))
|
||||
* **appium:** validate extension manifests and extensions.yaml via ajv ([#22732](https://github.com/appium/appium/issues/22732)) ([8840f9f](https://github.com/appium/appium/commit/8840f9f9322b63bc8940c390b8230f1e5306fa62))
|
||||
* backport diff from master ([#22749](https://github.com/appium/appium/issues/22749)) ([6323df1](https://github.com/appium/appium/commit/6323df1d7354f85cc631508f5cb6a3e35270d4bd))
|
||||
* **base-driver:** add definitions for all WebDriver BiDi commands ([#22770](https://github.com/appium/appium/issues/22770)) ([ac01aa8](https://github.com/appium/appium/commit/ac01aa83ad73982eea48f856dfc0249b4a26e395))
|
||||
* **base-driver:** align timeouts endpoints closer to W3C standard ([#22776](https://github.com/appium/appium/issues/22776)) ([93115d1](https://github.com/appium/appium/commit/93115d195773b011306ffb2e6d7d6cc935df0148))
|
||||
* **base-driver:** remove legacy (M)JSONWP protocol support ([#22681](https://github.com/appium/appium/issues/22681)) ([0b83e77](https://github.com/appium/appium/commit/0b83e77e7a1c24a885d9895a99db30281cf4acea))
|
||||
* **base-driver:** replace spdy with native https transport ([#22676](https://github.com/appium/appium/issues/22676)) ([ec7de47](https://github.com/appium/appium/commit/ec7de4768fdd8dde9d28db6fc2dfd63be45fd4c6))
|
||||
* bump minimum supported Node.js engine to ^22.22.2 || ^24.15.0 || >=26.0.0 ([#22685](https://github.com/appium/appium/issues/22685)) ([9f4a11e](https://github.com/appium/appium/commit/9f4a11e7190290986d01743557e90e6e44f87638))
|
||||
* Change the default log level to `info` ([#22756](https://github.com/appium/appium/issues/22756)) ([5e644a3](https://github.com/appium/appium/commit/5e644a392fbf11e2ca985408853d7f51aa85be17))
|
||||
* convert remaining monorepo packages to ESM-only ([#22674](https://github.com/appium/appium/issues/22674)) ([3516e50](https://github.com/appium/appium/commit/3516e50ce6d022f4c0dc539071c593bf2983325f))
|
||||
* **support:** move env/APPIUM_HOME resolution into appium package ([#22708](https://github.com/appium/appium/issues/22708)) ([8db8e57](https://github.com/appium/appium/commit/8db8e5748e26a7150cacbea09ba3ec52c5ce3fc0))
|
||||
* **support:** remove deprecated APIs ([#22678](https://github.com/appium/appium/issues/22678)) ([e8ee716](https://github.com/appium/appium/commit/e8ee71685b4c21116e61c88fd8d2f0e39fac2edb))
|
||||
* **types:** check execute method params against the command signature ([#22754](https://github.com/appium/appium/issues/22754)) ([b25fc20](https://github.com/appium/appium/commit/b25fc20c51a191c33695c1c71fbf129de834b52d))
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* address code review cleanups (plist, env memoize, test reuse) ([#22740](https://github.com/appium/appium/issues/22740)) ([0df8834](https://github.com/appium/appium/commit/0df883463812d57d44a0d6d80e9b88f124361934))
|
||||
* Address several TODOs ([#22762](https://github.com/appium/appium/issues/22762)) ([d6ef7e3](https://github.com/appium/appium/commit/d6ef7e3f1240f161df622c850aea06637f9d1078))
|
||||
* adjust deprecated JSONWP/MJSONWP routes ([#22763](https://github.com/appium/appium/issues/22763)) ([b129cbb](https://github.com/appium/appium/commit/b129cbbcd55656ae7f33b80b4b52719eb5179509))
|
||||
* **appium:** lock the extension manifest while driver/plugin commands run ([#22767](https://github.com/appium/appium/issues/22767)) ([a73644f](https://github.com/appium/appium/commit/a73644fb4f4e7b0363117ac1262d7018094b42ff))
|
||||
* **base-driver:** clean up aborted session creation ([#22733](https://github.com/appium/appium/issues/22733)) ([33d866e](https://github.com/appium/appium/commit/33d866e57506e1546aa4870dde75f7209be107bc))
|
||||
* declare dependencies that were only resolving via hoisting ([#22758](https://github.com/appium/appium/issues/22758)) ([bcf1c57](https://github.com/appium/appium/commit/bcf1c579997b8dbb8292b1a77583aeef40b11ba4))
|
||||
* **support:** route non-error CLI console output to stdout ([#22742](https://github.com/appium/appium/issues/22742)) ([4eb4d7f](https://github.com/appium/appium/commit/4eb4d7f317a685d681b6cf4e25c15b617a8cc7df))
|
||||
|
||||
### Code Refactoring
|
||||
|
||||
* **base-driver:** remove deprecated getSession command ([#22725](https://github.com/appium/appium/issues/22725)) ([f71d980](https://github.com/appium/appium/commit/f71d980779d23e9a19d33285646fad128eae4917))
|
||||
* **base-driver:** remove deprecated multi-argument createSession overload ([#22730](https://github.com/appium/appium/issues/22730)) ([db72249](https://github.com/appium/appium/commit/db722498739ae7fe1deef1b98e02d04b455a4f70))
|
||||
* **base-driver:** replace command mixin with explicit named exports ([#22741](https://github.com/appium/appium/issues/22741)) ([506bfee](https://github.com/appium/appium/commit/506bfeeb9aa15c0dd1f481868d347cb9b0d37f86))
|
||||
* **base-plugin:** remove deprecated legacy logger and default export ([#22718](https://github.com/appium/appium/issues/22718)) ([62db5f0](https://github.com/appium/appium/commit/62db5f0b20c496b495ce27d490453861ddefb259))
|
||||
* **logger:** remove default exports and dead logging APIs ([#22719](https://github.com/appium/appium/issues/22719)) ([fe24f52](https://github.com/appium/appium/commit/fe24f527a4412ed86c7b5e5afe0c6e26dc569e6b))
|
||||
* remove deprecated driverData mechanism ([#22716](https://github.com/appium/appium/issues/22716)) ([ef8a8e1](https://github.com/appium/appium/commit/ef8a8e1934bfdc9699c2b9a7eca3e2201b4b9f93))
|
||||
* **support:** move npm-related helpers into appium package ([#22721](https://github.com/appium/appium/issues/22721)) ([d82d496](https://github.com/appium/appium/commit/d82d496f9e80d6628abface3b623601a6f9791f9))
|
||||
* **support:** replace glob package with native node:fs glob ([#22735](https://github.com/appium/appium/issues/22735)) ([add1615](https://github.com/appium/appium/commit/add161560701ac7fb2bc372ddefd9317146fbae8))
|
||||
* **appium:** do not treat a directory as a CLI argument file ([#22709](https://github.com/appium/appium/issues/22709)) ([6ba6faf](https://github.com/appium/appium/commit/6ba6faf6f533192afbdf9462dbbb3a5c1e5d85c5))
|
||||
* **appium:** filter prerelease versions in driver update e2e test ([#22794](https://github.com/appium/appium/issues/22794)) ([4e8e334](https://github.com/appium/appium/commit/4e8e334cbc0ae910f521ae7ff7d3ed15f9be0a6a))
|
||||
* **appium:** match insecure feature prefixes by automationName, case-insensitively ([#22710](https://github.com/appium/appium/issues/22710)) ([6ab17fe](https://github.com/appium/appium/commit/6ab17feb71d74c1f349616f22896faeb256a66ec))
|
||||
|
||||
|
||||
## [3.7.0](https://github.com/appium/appium/compare/appium@3.6.0...appium@3.7.0) (2026-08-24)
|
||||
|
||||
@@ -103,27 +103,6 @@ export APPIUM_WORKSPACE=@appium/base-driver
|
||||
npm run test:unit -w $APPIUM_WORKSPACE
|
||||
```
|
||||
|
||||
### Code Style
|
||||
|
||||
#### JSDoc
|
||||
|
||||
Add concise JSDoc to all public class methods and exported functions.
|
||||
|
||||
#### Module Ordering
|
||||
|
||||
Place exported functions and classes before non-exported functions and classes in each module.
|
||||
This rule does not apply to constants or variables.
|
||||
|
||||
#### Class Member Ordering
|
||||
|
||||
When adding or moving class methods, follow these conventions:
|
||||
|
||||
- Order methods by visibility: public → protected → private. Methods without an explicit visibility
|
||||
modifier belong to the public group.
|
||||
- Place private helper methods at the end of the class.
|
||||
- Preserve existing order within each visibility group.
|
||||
- Before finishing, check the ordering of methods you added or moved.
|
||||
|
||||
### Documentation
|
||||
|
||||
The documentation for this project is [available in the project repository itself](https://github.com/appium/appium/tree/master/packages/appium/docs).
|
||||
|
||||
@@ -229,6 +229,16 @@ async createSession(w3cCaps) {
|
||||
}
|
||||
```
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
Older drivers may still define `createSession` with up to four parameters, e.g.
|
||||
`createSession(jwpCaps, reqCaps, w3cCaps, otherDriverData)`. This shape is a holdover from the
|
||||
retired JSON Wire Protocol, which required desired and required caps as the first two
|
||||
arguments; only the first W3C-shaped argument was ever used. The `otherDriverData` parameter is
|
||||
likewise deprecated in favor of [IPC](#send-messages-to-plugins-running-on-the-same-session) for
|
||||
coordinating with other concurrently-running sessions. New drivers should use the single-argument
|
||||
form shown above.
|
||||
|
||||
You'll want to make sure to call `super.createSession` in order to get the session ID as well as
|
||||
the processed capabilities (note that capabilities are also set on `this.caps`; modifying `caps`
|
||||
locally here would have no effect other than changing what the user sees in the create session
|
||||
@@ -534,7 +544,7 @@ this.proxyCommand = proxy.command.bind(proxy);
|
||||
Here we are creating a proxy object and assigning some of its methods to `this` under the names
|
||||
`proxyReqRes` and `proxyCommand`. This is required for Appium to use the proxy, so don't forget
|
||||
this step! The `WebDriverProxy` has a variety of other options [which you can check out in the
|
||||
source code as well.](https://github.com/appium/appium/blob/master/packages/base-driver/lib/wd-proxy/proxy.ts)
|
||||
source code as well.](https://github.com/appium/appium/blob/master/packages/base-driver/lib/jsonwp-proxy/proxy.ts)
|
||||
|
||||
Finally, we need a way to tell Appium when the proxy is active. For your driver it might always
|
||||
be active, or it might only be active when in a certain context. You can define the logic as an
|
||||
@@ -714,12 +724,6 @@ A couple notes about this system:
|
||||
mode!
|
||||
1. The `executeMethod` helper will reject with an error if a script name doesn't match one of the
|
||||
script names defined as a command in `executeMethodMap`, or if there are missing parameters.
|
||||
1. If your driver is written in TypeScript, declare the map `as const satisfies
|
||||
ExecuteMethodMap<MyDriver>` (with `ExecuteMethodMap` imported from `@appium/types`). The
|
||||
compiler then checks that each `command` names a method of your driver, and that the
|
||||
`required`/`optional` params are consistent with that method's signature: the method must not
|
||||
require a parameter which is listed as `optional` (or not listed at all), and must accept all
|
||||
of the listed parameters.
|
||||
|
||||
One of the nice things about the Execute Method strategy is that methods implemented in this way
|
||||
will be available via the classic or BiDi interfaces (since they will result in the same Appium
|
||||
@@ -794,32 +798,50 @@ that multiple simultaneous sessions don't use the same resources:
|
||||
|
||||
1. Have your users specify resource IDs via capabilities (`appium:driverPort` etc)
|
||||
1. Just always use free resources (find a new random port for each session)
|
||||
1. Have each running instance of your driver publish and subscribe to messages on a shared IPC
|
||||
channel, so sessions can coordinate directly with one another.
|
||||
1. Have each driver express what resources it is using, then examine currently-used resources from
|
||||
other drivers when a new session begins.
|
||||
|
||||
The per-session IPC channel described in [Send messages to plugins running on the same
|
||||
session](#send-messages-to-plugins-running-on-the-same-session) is isolated per session, so it
|
||||
can't be used for this: it doesn't let you talk to *other* sessions of your driver. Instead,
|
||||
construct and hold on to your own `AppiumIpc` instance (exported from `appium/driver.js`) at
|
||||
module scope in your driver's package, for example as a memoized singleton. Since Node.js caches
|
||||
modules, every instance of your driver loaded within the same Appium server process will share
|
||||
that one `AppiumIpc` object, and can use it to publish and subscribe to topics across sessions —
|
||||
the same way the per-session channel works, just not scoped to a single session. See
|
||||
[xcuitest-driver's `session-claim-handler.ts`](https://github.com/appium/appium-xcuitest-driver/blob/master/lib/session-claim-handler.ts)
|
||||
for a real example, which uses this technique to detect and resolve conflicting sessions targeting
|
||||
the same device UDID.
|
||||
!!! warning "Deprecated"
|
||||
|
||||
The `driverData`-based mechanism described below is deprecated. Prefer
|
||||
[IPC](#send-messages-to-plugins-running-on-the-same-session) for coordinating resources across
|
||||
concurrently-running sessions instead.
|
||||
|
||||
To support this third strategy, you can implement `get driverData` in your driver to return what
|
||||
sorts of resources your driver is currently using, for example:
|
||||
|
||||
```js
|
||||
get driverData() {
|
||||
return {specialPort: 1234, specialFile: /path/to/file}
|
||||
}
|
||||
```
|
||||
|
||||
Now, when a new session is started on your driver, the `driverData` response from any other
|
||||
simultaneously running drivers (of the same type) will also be included, as the last parameter of
|
||||
the deprecated, multi-argument form of the `createSession` method:
|
||||
|
||||
```js
|
||||
async createSession(jwpCaps, reqCaps, w3cCaps, driverData)
|
||||
```
|
||||
|
||||
You can dig into this `driverData` array to see what resources other drivers are using to help
|
||||
determine which ones you want to use for this particular session.
|
||||
|
||||
!!! warning
|
||||
|
||||
This only works for sessions running within the same Node.js process (i.e. the same Appium
|
||||
server). It cannot coordinate sessions running on different Appium server processes; for that,
|
||||
consider file-based locking or a similar out-of-process mechanism.
|
||||
Be careful here, since `driverData` is only passed between sessions of a single running Appium
|
||||
server. There's nothing to stop a user from running multiple Appium servers and requesting your
|
||||
driver simultaneously on each of them. In this case, you won't be able to ensure independence
|
||||
of resources via `driverData`, so you might consider using file-based locking mechanisms or
|
||||
something similar.
|
||||
|
||||
!!! warning
|
||||
|
||||
Appium also doesn't provide any features for ensuring unrelated drivers don't interfere with
|
||||
one another, so it's up to the drivers to allow users to specify resource locations or
|
||||
addresses to avoid clashes.
|
||||
It's also important to note you will only receive `driverData` for other instances of *your*
|
||||
driver. So unrelated drivers also running may still be using some system resources. In general
|
||||
Appium doesn't provide any features for ensuring unrelated drivers don't interfere with one
|
||||
another, so it's up to the drivers to allow users to specify resource locations or addresses to
|
||||
avoid clashes.
|
||||
|
||||
### Log events to the Appium event timeline
|
||||
|
||||
@@ -967,15 +989,10 @@ export type IpcMessage<T> = {
|
||||
#### IPC Notes
|
||||
|
||||
There are some important things to keep in mind when using Appium's IPC feature:
|
||||
- The `ipcSubscribe` method (and the IPC channel it subscribes to) is only available once
|
||||
`onIpcInit` has been called, at the end of the `createSession` flow. It cannot be used statically
|
||||
or in `createSession` hooks
|
||||
- The channel that `ipcSubscribe` gives you access to is scoped to the current session, and is
|
||||
shared only with the plugins active in that same session (this is also to prevent drivers/plugins
|
||||
from accessing or reading data sent on IPC channels in other sessions.) To coordinate across
|
||||
multiple concurrent sessions of your own driver instead, see [Make itself aware of resources
|
||||
other concurrent drivers are
|
||||
using](#make-itself-aware-of-resources-other-concurrent-drivers-are-using).
|
||||
- IPC is only available once `onIpcInit` has been called, at the end of the `createSession` flow.
|
||||
It cannot be used statically or in `createSession` hooks
|
||||
- In sum, IPC is only for use during a session (this is also to prevent drivers/plugins from
|
||||
accessing or reading data sent on IPC channels in other sessions.)
|
||||
- The default max size of an IPC message is 1MB. This can be configured by the server-admin by
|
||||
using the `--max-ipc-data-size` arg (value is a number in bytes).
|
||||
- If a message exceeds the configured size, any call to `publish` methods will throw, so be
|
||||
|
||||
@@ -257,7 +257,7 @@ throw new errors.NoSuchElementError();
|
||||
### Log messages to the Appium log
|
||||
|
||||
You can always use `console.log`, of course, but Appium provides a nice logger for you as
|
||||
`this.log` (it has `.info`, `.debug`, `.warn`, `.error` methods on it for differing log
|
||||
`this.logger` (it has `.info`, `.debug`, `.log`, `.warn`, `.error` methods on it for differing log
|
||||
levels). If you want to create an Appium logger outside of a plugin context (say in a script or
|
||||
helper file), you can always construct your own too:
|
||||
|
||||
@@ -476,7 +476,7 @@ capability.
|
||||
|
||||
You probably don't normally need to update the Appium server object (which is an
|
||||
[Express](https://expressjs.com/) server having already been
|
||||
[configured](https://github.com/appium/appium/blob/master/packages/http-server/lib/server.ts)
|
||||
[configured](https://github.com/appium/appium/blob/master/packages/base-driver/lib/express/server.js)
|
||||
in a variety of ways). But, for example, you could add new routes to the server to support your
|
||||
plugin's requirements. To update the server you must implement the `static async updateServer`
|
||||
method in your class. This method takes three parameters:
|
||||
|
||||
@@ -42,7 +42,7 @@ In order to get some value in logs replaced by a generic mask it is necessary:
|
||||
[util.format](https://nodejs.org/api/util.html#utilformatformat-args) API.
|
||||
|
||||
- While sending the appropriate server request, where this log line is used and should be masked,
|
||||
add the custom header `X-Appium-Is-Sensitive` with its value set to `1`, `true` or `yes` (case-insensitive).
|
||||
add the custom header `X-Appium-Is-Sensitive` with its value set to `1` or `true` (case-insensitive).
|
||||
Without such header the above log value is not going to be masked.
|
||||
This way it is possible to conditionally mask log records depending on which
|
||||
request is being handled by the extension if the log expression is used in the
|
||||
|
||||
@@ -69,13 +69,18 @@ appium driver install safari
|
||||
appium driver install uiautomator2
|
||||
```
|
||||
|
||||
### [WinCore](https://github.com/appium/appium-wincore-driver)
|
||||
### [Windows](https://github.com/appium/appium-windows-driver)
|
||||
|
||||
!!! warning
|
||||
|
||||
Only the Node.js-based driver part is maintained by the Appium team. The server part
|
||||
(WinAppDriver executable) is provided by Microsoft, but has not been maintained since 2022.
|
||||
|
||||
* Target: Windows applications
|
||||
* Mode: Native
|
||||
|
||||
```sh title="Install This Driver"
|
||||
appium driver install wincore
|
||||
appium driver install windows
|
||||
```
|
||||
|
||||
### [XCUITest](https://appium.github.io/appium-xcuitest-driver/)
|
||||
@@ -150,6 +155,11 @@ appium driver install --source=npm @itsmeaj/appium-linux-driver
|
||||
|
||||
### [NovaWindows](https://github.com/AutomateThePlanet/appium-novawindows-driver)
|
||||
|
||||
!!! info
|
||||
|
||||
This driver is recommended as a drop-in replacement for the partially unmaintained
|
||||
[Windows driver](#windows)
|
||||
|
||||
* Target: Windows applications
|
||||
* Mode: Native
|
||||
* Supported by: Community / Automate The Planet
|
||||
@@ -192,20 +202,6 @@ npm install appium-tizen-driver
|
||||
appium driver install --source=npm appium-tizen-tv-driver
|
||||
```
|
||||
|
||||
### [Windows (legacy)](https://github.com/appium/appium-windows-driver)
|
||||
|
||||
!!! warning
|
||||
|
||||
This driver relies on WinAppDriver, which has not been maintained since 2022, and is only
|
||||
compatible with Appium 1-3. Use the [WinCore](#wincore) driver with Appium 4 and newer.
|
||||
|
||||
* Target: Windows applications
|
||||
* Mode: Native
|
||||
|
||||
```sh title="Install This Driver"
|
||||
appium driver install --source=npm appium-windows-driver
|
||||
```
|
||||
|
||||
### [You.i Engine](https://github.com/YOU-i-Labs/appium-youiengine-driver)
|
||||
|
||||
!!! warning
|
||||
|
||||
@@ -95,4 +95,4 @@ and the values of any specific configuration it provides are under this. For exa
|
||||
|
||||
All properties are case-sensitive and will be in
|
||||
[kebab-case](https://en.wikipedia.org/wiki/Naming_convention_(programming)#Delimiter-separated_words).
|
||||
For example, `base-path` is allowed, but `basePath` is not.
|
||||
For example, `callback-port` is allowed, but `callbackPort` is not.
|
||||
|
||||
@@ -6,12 +6,14 @@ title: Retrieving Event Timings
|
||||
---
|
||||
|
||||
Appium comes with the ability to retrieve timing information about startup
|
||||
information and command length. This is an advanced feature; event and
|
||||
command timings are collected automatically for the duration of a session.
|
||||
information and command length. This is an advanced feature that is controlled
|
||||
by the use of the `appium:eventTimings` capability (set it to `true` to log event
|
||||
timings).
|
||||
|
||||
The `POST /session/:id/appium/events` response (i.e., the response to
|
||||
`driver.logs.events` or similar, depending on client) has the following
|
||||
structure:
|
||||
With this capability turned on, the `POST /session/:id/appium/events` response (i.e.,
|
||||
the response to `driver.logs.events` or similar, depending on client) will be
|
||||
decorated with an `events` property. This is the structure of that `events`
|
||||
property:
|
||||
|
||||
```
|
||||
{
|
||||
|
||||
@@ -117,3 +117,62 @@ hub, you'll be able to send all your Appium traffic via the single hub endpoint
|
||||
|
||||
And of course, you're able to link up Appium servers and nodes running on different machines in
|
||||
your network to form a larger grid.
|
||||
|
||||
## Using Selenium Grid 3
|
||||
|
||||
It is possible to register your Appium server with a local [Selenium Grid 3](https://www.selenium.dev/documentation/legacy/selenium_3/grid_3/)
|
||||
([setup docs](https://www.selenium.dev/documentation/legacy/grid_3/setting_up_your_own_grid/)) instance by using the
|
||||
`--nodeconfig` server argument.
|
||||
|
||||
```bash
|
||||
appium server --nodeconfig /path/to/nodeconfig.json --base-path=/wd/hub
|
||||
```
|
||||
|
||||
In the referenced config file you have to define the `browserName`, `version` and `platform`
|
||||
capabilities and based on these parameters the grid will re-direct your test to the right device.
|
||||
You will also need to configure your host details and the Selenium Grid details. For a full list of
|
||||
all parameters and descriptions see
|
||||
[here](https://www.selenium.dev/documentation/legacy/selenium_3/grid_setup/).
|
||||
|
||||
Once you start the Appium server it will register with the grid, and you will see your device on
|
||||
the grid console page:
|
||||
|
||||
`http://**\<grid-ip-adress\>**:**\<grid-port\>**/grid/console`
|
||||
|
||||
### Example Grid Node Configuration JSON
|
||||
|
||||
```json
|
||||
{
|
||||
"capabilities":
|
||||
[
|
||||
{
|
||||
"browserName": "<e.g._iPhone5_or_iPad4>",
|
||||
"version":"<version_of_iOS_e.g._7.1>",
|
||||
"maxInstances": 1,
|
||||
"platform":"<platform_e.g._MAC_or_ANDROID>"
|
||||
}
|
||||
],
|
||||
"configuration":
|
||||
{
|
||||
"cleanUpCycle":2000,
|
||||
"timeout":30000,
|
||||
"proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
|
||||
"url":"http://<host_name_appium_server_or_ip-address_appium_server>:<appium_port>/wd/hub",
|
||||
"host": "<host_name_appium_server_or_ip-address_appium_server>",
|
||||
"port": <appium_port>,
|
||||
"maxSession": 1,
|
||||
"register": true,
|
||||
"registerCycle": 5000,
|
||||
"hubPort": <grid_port>,
|
||||
"hubHost": "<Grid_host_name_or_grid_ip-address>",
|
||||
"hubProtocol": "<Protocol_of_Grid_defaults_to_http>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If `url`, `host`, and `port` are not given, the config will be auto updated to point to
|
||||
`localhost:<appium-port>`.
|
||||
|
||||
If your Appium server is running on a different machine to your Selenium Grid server, make sure you
|
||||
use an external name/IP address in your `host` and `url` configuration; `localhost` and `127.0.0.1`
|
||||
will prevent Selenium Grid from connecting correctly.
|
||||
|
||||
@@ -31,6 +31,10 @@ installing it only installs the core Appium server, without any drivers.
|
||||
|
||||
When it comes to installing Appium 2 drivers, there are several approaches you can take:
|
||||
|
||||
* Add the `--drivers` flag when installing Appium, for example:
|
||||
```bash
|
||||
npm i -g appium --drivers=xcuitest,uiautomator2
|
||||
```
|
||||
* Use the [Appium Extension CLI](../reference/cli/extensions.md), for example:
|
||||
```bash
|
||||
appium driver install uiautomator2
|
||||
|
||||
@@ -1,649 +0,0 @@
|
||||
---
|
||||
title: Migrating to Appium 4
|
||||
---
|
||||
<style>
|
||||
.md-typeset .grid {
|
||||
grid-template-columns: repeat(auto-fit,minmax(min(100%,11rem),1fr));
|
||||
}
|
||||
</style>
|
||||
|
||||
This document is a guide for those who are using Appium 3 and would like to upgrade to Appium 4.
|
||||
It contains a list of breaking changes, as well as suggestions for handling them.
|
||||
The [behavior fixes](#behavior-fixes) section also highlights corrections that can affect existing
|
||||
tests, client error handling, and server integrations.
|
||||
|
||||
Appium 4 focuses on modernizing the codebase (Node.js requirements, ESM-only packages, dropping
|
||||
long-deprecated protocol support and APIs) rather than introducing a large number of new
|
||||
user-facing features. Appium users should check the [Node.js version](#node-2222-required),
|
||||
[timeout inputs](#timeouts-endpoint-aligned-with-w3c-standard), and
|
||||
[capability validation](#stricter-capability-validation). The other breaking changes mostly affect
|
||||
driver and plugin developers, or users of specific removed flags/endpoints.
|
||||
|
||||
## Installation
|
||||
|
||||
Appium 4 is currently only available as a beta release, published under the `beta` npm dist-tag.
|
||||
The installation method otherwise remains the same as for Appium 3. If you want to upgrade, you
|
||||
can simply install Appium 4 on top of your existing installation:
|
||||
|
||||
```bash
|
||||
# optional: `appium setup reset`
|
||||
npm install -g appium@beta
|
||||
```
|
||||
|
||||
## Breaking Changes
|
||||
|
||||
### Node 22.22+ Required
|
||||
|
||||
Appium 3 required Node `^20.19.0 || ^22.12.0 || >=24.0.0`. Appium 4 drops Node 20 support and
|
||||
bumps the minimum required version to `^22.22.2 || ^24.15.0 || >=26.0.0`.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Upgrade Node.js to `v22.22.2`/`v24.15.0` or newer
|
||||
|
||||
### All Packages Are Now ESM-Only
|
||||
|
||||
Every `@appium/*` package (and `appium` itself) is now published as `"type": "module"` with no
|
||||
CommonJS build. `require()` no longer works for these packages. This affects anyone importing
|
||||
Appium or a driver/plugin package directly from Node.js code, not just driver/plugin developers.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Import Appium packages with ESM `import` syntax, or use dynamic `import()` from CommonJS code
|
||||
|
||||
### `--nodeconfig` Flag Removed
|
||||
|
||||
Support for registering with a legacy Selenium Grid 3 hub has been removed, along with the
|
||||
`--nodeconfig` server argument and the `server.nodeconfig` config file property.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
If you relied on Grid 3 registration, use the [Selenium Grid 4 relay feature](./grid.md) instead
|
||||
|
||||
### `--allow-cors` Flag Removed
|
||||
|
||||
CORS is now gated behind the same [insecure feature](./security.md) mechanism used for other
|
||||
server-level features (e.g. `session_discovery`), instead of its own dedicated flag.
|
||||
Without CORS enabled, state-changing HTTP requests carrying an `Origin` header and WebSocket
|
||||
upgrades carrying that header now receive HTTP `403`. Ordinary `GET`, `HEAD`, and `OPTIONS`
|
||||
requests are exempt from the HTTP check; requests without `Origin` are unaffected.
|
||||
Library callers of `@appium/http-server`'s `server()` and `configureServer()` now default to
|
||||
`allowCors: false` ([#22990](https://github.com/appium/appium/pull/22990)).
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Replace `--allow-cors` with `--allow-insecure=*:cors` (or enable it via `--relaxed-security`)
|
||||
for browser clients. Library callers that need CORS must explicitly pass `allowCors: true`
|
||||
|
||||
### Unused Server Arguments Removed
|
||||
|
||||
The following server arguments had no effect for a long time and have been removed, together with
|
||||
their `server.*` config file properties:
|
||||
|
||||
* `--callback-address` (`-ca`) and `--callback-port` (`-cp`)
|
||||
* `--debug-log-spacing`
|
||||
* `--strict-caps`
|
||||
* `--trace-dir`
|
||||
|
||||
Passing any of them on the command line now fails with an unrecognized argument error (unless
|
||||
[`--allow-unknown-args`](../reference/cli/server.md) is set), and config files containing them
|
||||
fail schema validation.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Remove these arguments from startup scripts and config files
|
||||
|
||||
### Extension Auto-Install on `npm install` Removed
|
||||
|
||||
The `npm install -g appium --drivers=... --plugins=...` postinstall hook that automatically
|
||||
installed extensions has been removed, since npm postinstall hooks are a supply-chain security
|
||||
risk and newer npm versions no longer support passing custom arguments to them.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Use `appium driver install`/`appium plugin install`, or declare extensions in your project's
|
||||
`package.json`, instead of `--drivers`/`--plugins` install-time arguments
|
||||
|
||||
### Local Extension Installs No Longer Create Global npm Links
|
||||
|
||||
`appium driver install --source=local` and `appium plugin install --source=local` now install
|
||||
directly from the supplied local directory, without first creating an intermediate global npm
|
||||
link. Local installs still link to the source directory, so source changes do not require
|
||||
reinstalling the extension (rebuild the extension first if its source needs compilation).
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Keep using `--source=local` with the extension's directory for local development. If other
|
||||
tooling relied on the package being linked in npm's global prefix, manage that global link
|
||||
separately; Appium no longer creates it as a side effect of a local extension install.
|
||||
|
||||
### `windows` Driver Shortcut Replaced by `wincore`
|
||||
|
||||
The `windows` shortcut for `appium driver install` has been removed, and the new `wincore` shortcut
|
||||
resolves to [`appium-wincore-driver`](https://github.com/appium/appium-wincore-driver). The old
|
||||
`appium-windows-driver` depends on WinAppDriver, which has not been maintained since 2022 and only
|
||||
speaks the legacy JSONWP protocol, so it does not work with Appium 4.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
1. While Appium 3 is still installed, install `appium-wincore-driver` v3 next to the legacy
|
||||
driver and verify that your Windows tests pass with it. The `wincore` shortcut is not
|
||||
available in Appium 3, so the package must be specified explicitly:
|
||||
`appium driver install --source=npm appium-wincore-driver@^3.0.0`
|
||||
2. After upgrading to Appium 4, update to the Appium 4 compatible driver release,
|
||||
since v3 of the driver only works with Appium 3:
|
||||
`appium driver update wincore --unsafe`
|
||||
3. Uninstall the legacy driver, as it does not work with Appium 4:
|
||||
`appium driver uninstall appium-windows-driver`
|
||||
|
||||
### Default Log Level Changed to `info`
|
||||
|
||||
The default `--log-level` changed from `debug` to `info`. Debug-level logging is very verbose and
|
||||
mostly only useful for troubleshooting.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Pass `--log-level debug` explicitly if you rely on the previous verbosity
|
||||
|
||||
### CLI Output Streams Split
|
||||
|
||||
Appium's CLI commands (`driver`/`plugin install|list|update`, `doctor`, etc.) used to write all
|
||||
non-JSON output to `STDERR`. Human-readable output (`log`/`ok`/`info`/`warn`) now goes to
|
||||
`STDOUT`; only `error` output still goes to `STDERR`. The main server's log output (Winston-based)
|
||||
is unaffected, since it already split streams this way.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
If you have scripts that capture Appium CLI output, make sure they read from the correct stream
|
||||
|
||||
### TLS Server No Longer Negotiates SPDY/HTTP2
|
||||
|
||||
Appium's TLS-enabled server used the unmaintained `spdy` package, which allowed negotiating
|
||||
SPDY/HTTP2 over ALPN. It has been replaced with Node's native `https` module, which only serves
|
||||
plain HTTPS (HTTP/1.1).
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Clients relying on SPDY or HTTP/2 multiplexing against Appium's TLS listener must switch to
|
||||
plain HTTPS (HTTP/1.1)
|
||||
|
||||
### Timeout Errors Now Return HTTP 500
|
||||
|
||||
Per the W3C WebDriver standard, `TimeoutError` and `ScriptTimeoutError` now map to HTTP `500`
|
||||
instead of `408`. The stale `408` mapping could cause keep-alive clients/proxies to auto-retry an
|
||||
already-executed timed-out command.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
None, unless your code inspects the raw HTTP status code of a timeout response
|
||||
|
||||
### Timeouts Endpoint Aligned With W3C Standard
|
||||
|
||||
`GET/SET /timeouts` is now closer to [the W3C standard](https://w3c.github.io/webdriver/#timeouts):
|
||||
|
||||
* `script`, `pageLoad`, and `implicit` accept `null` or integers from `0` to `Number.MAX_SAFE_INTEGER`
|
||||
milliseconds. Strings and fractions now return HTTP `400` / `invalid argument`
|
||||
([#22961](https://github.com/appium/appium/pull/22961))
|
||||
* `null` disables the timeout and is preserved in managed drivers and readback. These fields now
|
||||
use `TimeoutValue` (`number | null`), including driver-level `timeouts()`/`ISessionHandler` types
|
||||
* `GET /session/:sessionId/timeouts` now returns `script` and `pageLoad` in addition to the existing
|
||||
`implicit` and Appium-specific `command` values
|
||||
* `POST /session/:sessionId/timeouts` accepts `command` directly as an Appium-specific idle timeout
|
||||
in milliseconds; it is not a standard W3C timeout field
|
||||
* Updates without `script`, `pageLoad`, or `implicit` no longer fail: omitted fields keep their
|
||||
values and `{}` succeeds without changes. Invalid updates change no values
|
||||
([#22960](https://github.com/appium/appium/pull/22960),
|
||||
[#22961](https://github.com/appium/appium/pull/22961))
|
||||
* `command` remains an Appium-specific numeric idle timeout with legacy parsing. The `type`/`ms`
|
||||
parameters are deprecated
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Replace numeric strings and `type`/`ms` with standard fields. Handle `null` in custom setters
|
||||
and readback; `implicit: null` allows unlimited waiting
|
||||
|
||||
Initial `capabilities.timeouts` now initializes BaseDriver's local timeout state before backend
|
||||
startup, using the same value checks as Set Timeouts. Partial objects are accepted and omitted
|
||||
fields keep their defaults; backend handling remains driver-specific
|
||||
([#22983](https://github.com/appium/appium/pull/22983)).
|
||||
|
||||
Timeout capability validation also runs on `alwaysMatch` and every `firstMatch` candidate before
|
||||
driver selection. A malformed timeout object or invalid standard timeout value rejects the request
|
||||
with HTTP `400` / `invalid argument`, even when an earlier candidate could match. Top-level
|
||||
`timeouts: null` is still omitted, nested null timeout values are preserved, and unknown timeout
|
||||
properties are ignored for validation.
|
||||
|
||||
### Command POST Bodies Must Be JSON Objects
|
||||
|
||||
A command `POST` body now has to be a JSON object, as required by the W3C WebDriver standard.
|
||||
A request with no body, or a body that is a JSON array such as `[]`, returns HTTP `400` with
|
||||
`invalid argument` (`HTTP request body must be a JSON object`) and is not forwarded to the driver.
|
||||
`POST` with `{}` is unchanged, including commands that take no parameters. Routes that set
|
||||
`payloadParams.wrap` can still accept a bare array.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Send `{}` instead of an empty body. Clients that already send a JSON object, including the
|
||||
Appium clients, need no change
|
||||
|
||||
### Plugins Intercepting Proxied Commands Receive Unvalidated Arguments
|
||||
|
||||
When a plugin intercepts a command that would otherwise be proxied to a downstream WebDriver
|
||||
server, Appium no longer validates required payload fields or command arguments before calling
|
||||
the plugin. This matches direct proxying, where the downstream remote end already owns those
|
||||
checks ([#23060](https://github.com/appium/appium/pull/23060)). Plugins that previously relied on
|
||||
Appium to validate these arguments can now receive missing or invalid values.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
If your plugin handles such a command without calling `next()`, validate the inputs it uses.
|
||||
A pass-through plugin can call `next()` and delegate validation to the downstream remote end.
|
||||
The downstream driver's validation responsibility is unchanged.
|
||||
|
||||
Local and proxy-avoided commands retain Appium's validation. Session-existence checks and
|
||||
JSON-object request-body checks also remain in place before the plugin is called.
|
||||
|
||||
### BiDi Commands No Longer Accept Stray `sessionId`/`id` Params
|
||||
|
||||
Unlike HTTP endpoints, WebDriver BiDi commands have no URL-derived session/element id, so a stray
|
||||
`sessionId` or `id` key inside BiDi command params is no longer silently accepted; it is now
|
||||
validated like any other unknown parameter.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Remove `sessionId`/`id` from the parameters of any custom BiDi command invocation
|
||||
|
||||
### `getStatus` No Longer Waits In the Commands Queue
|
||||
|
||||
`GET /status` is now exempt from the driver commands queue by default, so it can be answered while
|
||||
a long-running command is still in progress. The new-command idle timer is now only restarted once
|
||||
no commands are executing. Drivers can customize the exemption list by overriding the new
|
||||
`queueExemptCommands` getter.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
None, unless your driver relied on `getStatus` being serialized with other commands
|
||||
|
||||
### Stricter Capability Validation
|
||||
|
||||
* Standard capability keys are case-sensitive (e.g. `platformName`, not `PlatformName`).
|
||||
Value matching and namespaced extensions are unchanged
|
||||
([#22976](https://github.com/appium/appium/pull/22976))
|
||||
* Malformed capability containers and parser `invalid argument` errors now return HTTP `400`,
|
||||
not HTTP `500` / `session not created`. Driver selection/loading failures still use
|
||||
`session not created` ([#22977](https://github.com/appium/appium/pull/22977))
|
||||
* Top-level `null` capabilities are omitted before validation and merging, avoiding false
|
||||
duplicate-key errors. Nested nulls, such as `timeouts: {script: null}`, are preserved
|
||||
([#22975](https://github.com/appium/appium/pull/22975))
|
||||
* An empty `firstMatch` array in the new session request is no longer silently replaced with a
|
||||
single empty entry; it is rejected with `InvalidArgumentError`, as required by the W3C standard
|
||||
* Setting both `appium:noReset` and `appium:fullReset` to `true` now fails with `SessionNotCreatedError`
|
||||
instead of a generic error, and no longer leaves partially initialized session state behind
|
||||
* `appium:newCommandTimeout` values that are `null`, blank strings, or non-finite numeric values are now
|
||||
ignored (the default idle timeout is kept) instead of silently disabling the timeout. Other invalid
|
||||
types, such as nonnumeric strings, still fail capability validation
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Use exact standard key names and vendor-prefixed extensions. Send `firstMatch: [{}]` or omit it.
|
||||
Update error assertions for malformed capabilities; top-level `null` values no longer reach drivers
|
||||
|
||||
Every `firstMatch` candidate is now validated and merged before selection. Invalid supplied values
|
||||
or duplicate keys in any candidate reject the request, even when another candidate could match;
|
||||
missing required driver capabilities and unsupported platforms still allow matching to continue
|
||||
([#22982](https://github.com/appium/appium/pull/22982)).
|
||||
|
||||
### Default Capabilities Apply to Every Candidate
|
||||
|
||||
`--default-capabilities` now fills missing keys in each `firstMatch` candidate independently.
|
||||
Client values in `alwaysMatch` or the current candidate take precedence; a value in another
|
||||
candidate does not suppress the default. Duplicate keys between `alwaysMatch` and `firstMatch`
|
||||
are still rejected. This is Appium-specific defaulting behavior
|
||||
([#22988](https://github.com/appium/appium/pull/22988)); see
|
||||
[Default Capabilities](../reference/cli/server.md#default-capabilities) for an example.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Check defaults when sending multiple candidates: later candidates now receive missing defaults too
|
||||
|
||||
### Storage Plugin Routes Respect `--base-path`
|
||||
|
||||
The [storage plugin](https://github.com/appium/appium/tree/master/packages/storage-plugin) HTTP
|
||||
routes and stream/events WebSocket paths used to be mounted at the server root, ignoring `--base-path`.
|
||||
They are now prefixed with the base path, e.g. `/wd/hub/appium/storage/add`. Also, storage file names
|
||||
starting with a dot, reserved partial-file names, and concurrent WebSocket uploads of the same file
|
||||
are now rejected.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
If the server uses a non-default `--base-path`, update storage plugin clients to include it in the URLs
|
||||
and avoid file names starting with a dot or ending in `.filepart` (case-insensitive).
|
||||
Concurrent WebSocket uploads to the same case-insensitive file name now close with code `1013`;
|
||||
retry with a new connection after the active upload finishes
|
||||
|
||||
Pending upload WebSocket routes are also preserved across retries,
|
||||
and errors on upload event sockets are logged instead of potentially terminating the server.
|
||||
|
||||
## Behavior Fixes
|
||||
|
||||
These fixes are relevant when upgrading from Appium 3, even though they do not remove APIs.
|
||||
Most require no changes unless your tests or integrations depend on the previous behavior.
|
||||
|
||||
### HTTP Responses and WebDriver Errors
|
||||
|
||||
* `HEAD` requests to GET command URLs now return HTTP `405` without executing the GET command.
|
||||
Explicit extension HEAD handlers and custom server routes retain their behavior. Use `GET /status`
|
||||
for health checks ([#22992](https://github.com/appium/appium/pull/22992)).
|
||||
* Unsupported log types and unknown legacy timeout `type` values now return HTTP `400` /
|
||||
`invalid argument` instead of HTTP `500` / `unknown error`
|
||||
([#22986](https://github.com/appium/appium/pull/22986),
|
||||
[#22987](https://github.com/appium/appium/pull/22987)).
|
||||
* WebDriver HTTP responses now include `Cache-Control: no-cache`, including successful responses,
|
||||
errors, and responses reconstructed by `WebDriverProxy`
|
||||
([#22971](https://github.com/appium/appium/pull/22971)). Caches must revalidate these responses
|
||||
before reusing them; this header does not mean `no-store`.
|
||||
* When no installed driver matches the requested platform/automation combination, or the matching
|
||||
driver cannot be loaded or does not export its class, New Session now returns `session not created`
|
||||
instead of `unknown error`. The HTTP status remains `500`, and the diagnostic message is preserved.
|
||||
Validation of missing `platformName`/`appium:automationName` is unchanged
|
||||
([#22970](https://github.com/appium/appium/pull/22970)).
|
||||
* A downstream `detached shadow root` error is now preserved as HTTP `404` with that WebDriver
|
||||
error code instead of being converted to `unknown error` with HTTP `500`
|
||||
([#22968](https://github.com/appium/appium/pull/22968)).
|
||||
* Supplied WebDriver error `data` (e.g. alert text) is preserved in driver and proxy responses;
|
||||
absent data remains omitted
|
||||
([#22974](https://github.com/appium/appium/pull/22974)).
|
||||
* With an empty base path, an unregistered `GET /` now returns a WebDriver JSON `unknown command`
|
||||
response with HTTP `404` instead of Express's HTML 404 page. Extensions can still register their
|
||||
own root route ([#22969](https://github.com/appium/appium/pull/22969)).
|
||||
* Driver commands rejecting with `null` or `undefined` now produce a WebDriver `unknown error`
|
||||
response instead of causing the error handler itself to fail
|
||||
([#22869](https://github.com/appium/appium/pull/22869)).
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Update assertions or retry logic that inspect raw error codes, HTTP status codes, response
|
||||
headers, or root-path response bodies. Use `GET /status` for server health checks
|
||||
|
||||
### Initial Settings and Session Lifecycle
|
||||
|
||||
* Initial settings now come from the selected `firstMatch` candidate, with defaults and
|
||||
`alwaysMatch` settings applied first. Unselected candidates no longer override them, and settings
|
||||
inside `appium:options` are now honored
|
||||
([#22882](https://github.com/appium/appium/pull/22882)).
|
||||
* The new-command idle timeout starts after initial settings and BiDi response setup finish,
|
||||
preventing a session from expiring during initialization
|
||||
([#22881](https://github.com/appium/appium/pull/22881)). If post-create initialization fails,
|
||||
Appium now attempts to delete the newly created session and removes its registration while
|
||||
preserving the original initialization error
|
||||
([#22873](https://github.com/appium/appium/pull/22873)).
|
||||
* Commands still waiting in the queue when their session ends now reject with `invalid session id`
|
||||
instead of remaining pending indefinitely; their driver methods are not executed
|
||||
([#22874](https://github.com/appium/appium/pull/22874)).
|
||||
* A driver cleanup failure during idle-timeout shutdown is now logged instead of becoming an
|
||||
unhandled rejection that can terminate the server and unrelated sessions
|
||||
([#22964](https://github.com/appium/appium/pull/22964)).
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Put initial settings in `alwaysMatch` or the intended `firstMatch` candidate. Handle
|
||||
`invalid session id` for queued requests when a session ends, and make driver cleanup safe
|
||||
to call after a partially completed initialization
|
||||
|
||||
### BiDi Subscription Scope and Event Delivery
|
||||
|
||||
Subscriptions without `contexts` now receive events carrying a context, and module subscriptions
|
||||
such as `events: ["log"]` now match events such as `log.entryAdded`. Overlapping subscriptions
|
||||
deliver each event only once ([#22883](https://github.com/appium/appium/pull/22883)).
|
||||
|
||||
The base implementation of `session.subscribe` now rejects `userContexts` with `unsupported operation`
|
||||
instead of silently creating an unscoped subscription. Malformed `userContexts`, or supplying both
|
||||
`contexts` and `userContexts`, produce `invalid argument`. Drivers implementing user-context support
|
||||
can override `bidiSubscribe` ([#22877](https://github.com/appium/appium/pull/22877)).
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Use `contexts` for browsing-context scope, or a driver that implements `userContexts` for
|
||||
user-context scope. Review event-count assertions and workarounds for previously missing events
|
||||
|
||||
### App Downloads and IPv6 Connections
|
||||
|
||||
Percent-encoded credentials in `appium:app` URLs are now decoded once before Basic authentication,
|
||||
and complete HTTP-compressed downloads are no longer rejected because the decompressed file size
|
||||
differs from `Content-Length` ([#22887](https://github.com/appium/appium/pull/22887),
|
||||
[#22886](https://github.com/appium/appium/pull/22886)). IPv6 literals are now bracketed when constructing
|
||||
URLs, including advertised BiDi WebSocket URLs and execute-driver plugin connections
|
||||
([#22872](https://github.com/appium/appium/pull/22872),
|
||||
[#22912](https://github.com/appium/appium/pull/22912),
|
||||
[#22914](https://github.com/appium/appium/pull/22914)).
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Remove any workarounds for literal percent escapes in download credentials or malformed IPv6 URLs
|
||||
|
||||
## Endpoint Changes
|
||||
|
||||
The following endpoints have been removed:
|
||||
|
||||
* `GET/POST /session/:sessionId/ime/*` (all IME endpoints, legacy JSONWP)
|
||||
* `GET /session/:sessionId/location`, `POST /session/:sessionId/location` (legacy geolocation, legacy JSONWP)
|
||||
* `GET /session/:sessionId/network_connection`, `POST /session/:sessionId/network_connection` (legacy MJSONWP)
|
||||
* `POST /session/:sessionId/receive_async_response` (legacy JSONWP)
|
||||
* `GET /session/:sessionId/element/:elementId` (undocumented legacy JSONWP stub)
|
||||
* `GET /session/:sessionId` (deprecated `getSession`; see [below](#getsession-command-removed) for
|
||||
its replacement)
|
||||
|
||||
The `orientation`, `context`/`contexts`, and `rotation` deprecated endpoints are unaffected and
|
||||
remain available.
|
||||
|
||||
## Changes for Driver and Plugin Developers
|
||||
|
||||
The following changes primarily affect authors of Appium drivers, plugins, or tools that import
|
||||
Appium's internal packages directly (`@appium/base-driver`, `@appium/base-plugin`,
|
||||
`@appium/support`, `@appium/logger`). They do not affect most Appium end users.
|
||||
|
||||
### Remaining Legacy (M)JSONWP Support Removed From `@appium/base-driver`
|
||||
|
||||
Beyond the removed endpoints above, the internal machinery that translated between the legacy
|
||||
(M)JSONWP protocol and W3C WebDriver has been removed:
|
||||
|
||||
* `ProtocolError` instances no longer carry a `jsonwpCode` property, and error responses no longer
|
||||
include a legacy numeric `status` code (`errorFromMJSONWPStatusCode`, aliased as `errorFromCode`,
|
||||
has been removed; use `errorFromW3CJsonCode`)
|
||||
* Responses no longer duplicate element references under the legacy `ELEMENT` key; only the W3C
|
||||
`element-6066-11e4-a52e-4f735466cecf` key is present
|
||||
* `WebDriverProxy` (formerly `JWProxy`, now removed as a name) no longer converts responses from a
|
||||
downstream automation server speaking legacy MJSONWP; downstream servers must speak W3C WebDriver
|
||||
* `determineProtocol`, `DriverCore#setProtocolMJSONWP()`, and `DriverCore#isMjsonwpProtocol()` have
|
||||
been removed; drivers can no longer produce the legacy `{sessionId, status, value}` response shape
|
||||
* `@appium/base-driver` no longer exports `statusCodes`/`getSummaryByCode` (the `jsonwp-status`
|
||||
module was removed)
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Ensure any downstream automation server a driver proxies to (via `WebDriverProxy`) speaks pure
|
||||
W3C WebDriver; update code referencing the removed exports to their W3C equivalents
|
||||
|
||||
### `@appium/base-driver` Default Export Removed
|
||||
|
||||
`BaseDriver` is no longer exported as `@appium/base-driver`'s default export, and
|
||||
`basedriver/helpers.js`'s default export has been removed as well. `BaseDriver`'s constructor no
|
||||
longer takes command-mixin machinery into account, and the unused `BaseDriver.reset()` method has
|
||||
been removed.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Replace `import BaseDriver from '@appium/base-driver'` with `import {BaseDriver} from '@appium/base-driver'`
|
||||
|
||||
### Drivers Must Support Shared Command Activity Tracking
|
||||
|
||||
The idle timer stays suspended through HTTP/BiDi plugin chains, including work after `next()`,
|
||||
and while proxied BiDi commands await a response. Drivers must use `@appium/base-driver` with
|
||||
shared command activity tracking; legacy timer implementations are no longer supported
|
||||
([#22946](https://github.com/appium/appium/pull/22946),
|
||||
[#22947](https://github.com/appium/appium/pull/22947)).
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Custom `startNewCommandTimeout` implementations must delegate timer creation
|
||||
to `super.startNewCommandTimeout()` so they respect shared activity. Custom command execution
|
||||
must delegate to `super.executeCommand()` or wrap the full command in `runWithCommandTimeout`.
|
||||
|
||||
### HTTP Server Extracted Into `@appium/http-server`
|
||||
|
||||
The HTTP/Express server code was moved from `@appium/base-driver` into the new
|
||||
`@appium/http-server` package. `@appium/base-driver` no longer exports `server`,
|
||||
`normalizeBasePath`, `configureServer`, `ServerOpts`, `ConfigureServerOpts`, `ConfigureHttpOpts`,
|
||||
or `StartServerOpts`, and no longer depends on `express` and related middleware packages.
|
||||
`appium/driver.js` stopped re-exporting these symbols as well.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Import the server helpers from `@appium/http-server` instead
|
||||
|
||||
### Driver-Specific Capabilities Removed From Base Constraints
|
||||
|
||||
The `appium:locale`, `appium:language`, `appium:autoWebview`, `appium:orientation`, and
|
||||
`appium:udid` capabilities are no longer part of the standard capability constraints, since they
|
||||
are not generic enough. The deprecated `appium:autoLaunch` capability has been removed as well.
|
||||
The base driver no longer validates them.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Drivers that rely on these capabilities must declare them in their own `desiredCapConstraints`
|
||||
|
||||
### `@appium/base-plugin` Default Export and Legacy Logger Removed
|
||||
|
||||
`BasePlugin` is no longer the default export of `@appium/base-plugin`. `Plugin#logger` has been
|
||||
removed in favor of `Plugin#log`, and `Plugin#name`/`Plugin#cliArgs` are now read-only.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
* Replace `import BasePlugin from '@appium/base-plugin'` with `import {BasePlugin} from '@appium/base-plugin'`
|
||||
* Replace `this.logger` with `this.log` in plugin code
|
||||
|
||||
### `@appium/logger` Default Export and Dead APIs Removed
|
||||
|
||||
`@appium/logger` and `@appium/support` no longer export a default `log`. `AppiumLogger#errorAndThrow`
|
||||
has been removed in favor of `errorWithException`. The long-disabled, no-op progress/unicode
|
||||
methods (`enableProgress`, `disableProgress`, `progressEnabled`, `enableUnicode`, `disableUnicode`)
|
||||
have also been removed.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
* Import the named `log` export instead of the default export
|
||||
* Replace `errorAndThrow` calls with `errorWithException`
|
||||
|
||||
### `driverData` Mechanism Removed
|
||||
|
||||
The deprecated `driverData` mechanism (`Core.driverData`, the `driverData` parameter on
|
||||
`createSession`/`deleteSession`, and the `DriverData` type) has been removed, superseded by
|
||||
`IAppiumIpc`.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Drivers overriding `get driverData()` or relying on it for cross-session coordination need to
|
||||
migrate to `IAppiumIpc`
|
||||
|
||||
### `createSession` Multi-Argument Overload Removed
|
||||
|
||||
`createSession` no longer accepts the legacy multi-argument form
|
||||
(`createSession(jwpCaps, reqCaps, w3cCaps)`), a holdover from JSONWP. Only the single
|
||||
`w3cCapabilities` argument is supported now.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Update any driver or plugin overriding `createSession` to use the single-argument signature
|
||||
|
||||
### `getSession` Command Removed
|
||||
|
||||
`BaseDriver.getSession` and `ISessionHandler.getSession` have been removed (see [Endpoint
|
||||
Changes](#endpoint-changes) for the removed route), along with the `appium:eventTimings`
|
||||
capability that controlled whether its response included event history.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Use `GET /session/:sessionId/appium/capabilities` to retrieve session capabilities, and
|
||||
`POST /session/:sessionId/appium/events` to retrieve event history (now returned unconditionally)
|
||||
|
||||
### `@appium/support` Deprecated APIs Removed
|
||||
|
||||
The following `@appium/support` exports have been removed: `process` (`getProcessIds`,
|
||||
`killProcess`), `mkdirp`, `imageUtil` (`requireSharp`, `cropBase64Image`), `mjpeg` (`MJpegStream`),
|
||||
`net`'s FTP upload support, `util`'s `uuidV1`/`uuidV3`/`uuidV5`/`localIp`/`cancellableDelay`/`multiResolve`,
|
||||
`fs`'s `readPackageJsonFrom`/`findRoot`/`F_OK`/`R_OK`/`W_OK`/`X_OK`, `npm`/`NPM` (moved into the
|
||||
`appium` package), and `env` (moved into the `appium` package). `node.requirePackage()` and
|
||||
`system.macOsxVersion()` have also been removed. `fs.glob()` is now backed by Node's native
|
||||
`fs.promises.glob` instead of the `glob` package, with a narrower `GlobOptions` shape.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
None for typical drivers/plugins, which don't use these low-level helpers directly. If you do,
|
||||
switch to the suggested replacement or a native Node.js API
|
||||
|
||||
### Filesystem and IPC Fixes
|
||||
|
||||
* `@appium/support`'s `fs.mv()` now preserves symlinks inside moved directories and moves source
|
||||
symlinks themselves without moving their targets' contents. Dangling source links are supported,
|
||||
and Windows case-only renames update the entry's spelling
|
||||
([#22880](https://github.com/appium/appium/pull/22880),
|
||||
[#22954](https://github.com/appium/appium/pull/22954),
|
||||
[#22958](https://github.com/appium/appium/pull/22958)).
|
||||
* `fs.walkDir()` now continues after walker errors such as `EACCES` and `ELOOP` instead of hanging.
|
||||
These errors are logged and affected entries skipped; `ENOENT` still rejects the returned promise
|
||||
([#22956](https://github.com/appium/appium/pull/22956)).
|
||||
* Both `ipc.unsubscribe(topic, subscriber)` and `subscription.unsubscribe()` now finish waiting
|
||||
async iterators and notify observers once. An observer that throws still propagates its error
|
||||
to the caller, but no longer prevents waiting iterators from finishing
|
||||
([#22955](https://github.com/appium/appium/pull/22955)).
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
If you intend to move a symlink's target, resolve it explicitly before calling `fs.mv()`.
|
||||
A completed directory walk may have skipped entries; check warnings if completeness matters.
|
||||
Allow IPC consumers to finish when unsubscribed
|
||||
|
||||
### System Unzip Removed From `@appium/support`
|
||||
|
||||
`extractAllTo()` always uses the built-in JS extractor now, so the `useSystemUnzip` option has been
|
||||
removed. The extractor supports only stored and deflate entries and verifies the CRC32 of every
|
||||
entry. File names that are not flagged as UTF-8 by the archive are decoded as `utf8` by default, and
|
||||
the legacy `cp437` decoding is no longer supported. Such names get corrupted, and different names
|
||||
may collapse into the same one, so that entries overwrite each other.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Remove `useSystemUnzip` from `extractAllTo()` calls. Archives with `cp437` file names must be
|
||||
recreated with UTF-8 names (or converted) before extraction. Other single-byte encodings
|
||||
supported by Node.js can be selected via `fileNamesEncoding`. Archives with encrypted entries or
|
||||
other compression methods are rejected with `ZipStreamUnsupportedError`
|
||||
|
||||
### Legacy Test Pages Removed From `@appium/base-driver`
|
||||
|
||||
The built-in test fixture routes (`/welcome`, `/test/guinea-pig*`, `/produce_error`, `/crash`),
|
||||
the `STATIC_DIR` export, and the `APPIUM_ENABLE_LEGACY_TEST_PAGES` environment variable have been
|
||||
removed.
|
||||
|
||||
!!! info "Actions Needed"
|
||||
|
||||
Driver test suites that relied on these fixtures should host their own local test server
|
||||
|
||||
## New Features
|
||||
|
||||
* [`--app-url-rules`](./security.md#restricting-remote-app-urls) lets server operators restrict
|
||||
which hosts/IPs an `appium:app` URL is allowed to be downloaded from (allow/deny lists, HTTPS-only,
|
||||
credentials, redirect limits)
|
||||
* Definitions for all current [WebDriver BiDi](https://w3c.github.io/webdriver-bidi/) commands are
|
||||
now included for introspection/validation purposes
|
||||
* `ExecuteMethodMap` type declarations now check `params` against the target method's signature at
|
||||
compile time, catching mismatched required/optional execute method parameters in driver code
|
||||
* The [Universal XML plugin](../reference/api/plugins.md) provides the `universalXml: setEnabled` and
|
||||
`universalXml: isEnabled` execute methods to toggle the translation during a session, e.g. to
|
||||
retrieve the original page source
|
||||
* Extension manifests and `extensions.yaml` are now validated with `ajv`/JSON Schema; a corrupted
|
||||
`extensions.yaml` now resets to an empty manifest with a warning instead of crashing later with a
|
||||
confusing error
|
||||
* `appium driver`/`appium plugin` CLI commands now lock the extension manifest while running,
|
||||
preventing concurrent processes from silently clobbering each other's changes
|
||||
* The `install` CLI command now attempts to search for and install the newest compatible extension
|
||||
version, if the latest version has an incompatible Appium server requirement
|
||||
@@ -85,118 +85,3 @@ Turn on multiple insecure features for specific drivers:
|
||||
```bash
|
||||
appium --allow-insecure=uiautomator2:adb_shell,xcuitest:get_server_logs
|
||||
```
|
||||
|
||||
## Restricting Remote App URLs
|
||||
|
||||
Several drivers accept a URL instead of a local path in capabilities such as `appium:app`, in which
|
||||
case the Appium server downloads the application package from that URL before starting the session.
|
||||
By default, any `http:` or `https:` URL is accepted. Server hosts who want to control which URLs
|
||||
their server is allowed to download from can do so with the `--app-url-rules` argument (or the
|
||||
`server.app-url-rules` property in a [configuration file](./config.md)). Its value is a JSON object
|
||||
(or a path to a JSON file) with any of the following properties:
|
||||
|
||||
|<div style="width:10em">Rule</div>|Description|Default|
|
||||
|----------------------------------|-----------|-------|
|
||||
|`allow`|List of hostname patterns, IP addresses, or CIDR subnets. If non-empty, a hostname or its resolved address must match _at least one_|`[]`|
|
||||
|`deny`|List of hostname patterns, IP addresses, or CIDR subnets. A matching hostname or resolved address is rejected, even if an `allow` rule also matches|`[]`|
|
||||
|`httpsOnly`|Only accept `https:` URLs|`false`|
|
||||
|`allowCredentials`|Accept URLs containing a username and/or password (e.g. `https://user:pass@host/app.apk`)|`true`|
|
||||
|`maxRedirects`|Maximum number of HTTP redirects to follow while downloading. Set to `0` to reject any redirect|`21`|
|
||||
|
||||
Hostnames are normalized (lowercased, converted to Punycode, trailing dot removed) before matching
|
||||
and resolved on every download. Address rules apply to literal addresses and all dynamically
|
||||
resolved IPv4/IPv6 addresses. The rules are also applied to every redirect, so redirects cannot be
|
||||
used to escape them. If a URL violates any rule, the session is not created and a generic error
|
||||
is returned. The violated rule is deliberately neither reported to the client nor written to the
|
||||
server log, since server logs are often handed over to clients as well. URL schemes, ports, paths,
|
||||
queries, and fragments are not matched.
|
||||
|
||||
Hostname patterns use the [picomatch](https://github.com/micromatch/picomatch#globbing-features)
|
||||
glob syntax and are matched against the whole hostname:
|
||||
|
||||
|Pattern|Matches|
|
||||
|-------|-------|
|
||||
|`artifacts.example.com`|Exactly this hostname|
|
||||
|`*.example.com`|Any subdomain of `example.com` (including nested ones, like `a.b.example.com`), but not `example.com` itself|
|
||||
|`*example.com`|Any hostname ending with `example.com`, including `example.com` itself|
|
||||
|`apps.{staging,prod}.example.com`|`apps.staging.example.com` and `apps.prod.example.com`|
|
||||
|`build-?.example.com`|`build-1.example.com`, `build-a.example.com`, etc.|
|
||||
|`node[0-9].example.com`|`node0.example.com` to `node9.example.com`|
|
||||
|
||||
IP address rules match a single address (`192.0.2.10`, `2001:db8::1`) or a whole subnet in CIDR
|
||||
notation (`10.0.0.0/8`, `2001:db8::/32`). IPv4 rules also match IPv4-mapped IPv6 addresses
|
||||
(e.g. `::ffff:10.1.2.3`).
|
||||
|
||||
!!! note
|
||||
|
||||
These rules only apply to URLs the server downloads via the standard app configuration helper,
|
||||
which is used for `appium:app` and similar capabilities by all official drivers. Drivers may
|
||||
define custom capabilities with URLs that are processed differently and thus are not covered.
|
||||
|
||||
!!! note
|
||||
|
||||
If the server downloads applications through an HTTP proxy (configured via the `HTTP_PROXY`,
|
||||
`HTTPS_PROXY` and `NO_PROXY` environment variables), the proxy resolves the destination host
|
||||
itself, so rules containing IP addresses or subnets cannot be enforced for proxied downloads.
|
||||
Such downloads are rejected; either exclude the download hosts from proxying via `NO_PROXY`
|
||||
or only use hostname-based rules.
|
||||
|
||||
### Examples
|
||||
|
||||
Only allow HTTPS downloads from an internal artifact server, without credentials in the URL and
|
||||
without following redirects:
|
||||
|
||||
```bash
|
||||
appium --app-url-rules='{"allow": ["artifacts.example.com", "10.0.0.0/8"], "httpsOnly": true, "allowCredentials": false, "maxRedirects": 0}'
|
||||
```
|
||||
|
||||
The same configuration as part of a config file:
|
||||
|
||||
```yaml
|
||||
server:
|
||||
app-url-rules:
|
||||
allow:
|
||||
- 'artifacts.example.com'
|
||||
- '10.0.0.0/8'
|
||||
httpsOnly: true
|
||||
allowCredentials: false
|
||||
maxRedirects: 0
|
||||
```
|
||||
|
||||
Allow downloads from any subdomain of `example.com` and from two IPv6 subnets, except from the
|
||||
staging environment:
|
||||
|
||||
```yaml
|
||||
server:
|
||||
app-url-rules:
|
||||
allow:
|
||||
- '*.example.com'
|
||||
- '2001:db8:1::/48'
|
||||
- '2001:db8:2::/48'
|
||||
deny:
|
||||
- '*.staging.example.com'
|
||||
```
|
||||
|
||||
Allow downloads from anywhere, except from the server itself, private networks, link-local
|
||||
addresses (such as cloud metadata services), and any `.internal` hostname:
|
||||
|
||||
```yaml
|
||||
server:
|
||||
app-url-rules:
|
||||
deny:
|
||||
- 'localhost'
|
||||
- '*.internal'
|
||||
- '127.0.0.0/8'
|
||||
- '10.0.0.0/8'
|
||||
- '172.16.0.0/12'
|
||||
- '192.168.0.0/16'
|
||||
- '169.254.0.0/16'
|
||||
- '::1/128'
|
||||
- 'fc00::/7'
|
||||
- 'fe80::/10'
|
||||
```
|
||||
|
||||
The rules in the last example are applied to the addresses each hostname resolves to, so they
|
||||
cannot be bypassed via DNS. Note that the `deny` list also blocks any download from the server's
|
||||
own private network, so a private artifact server must be excluded from the `deny` rules in order
|
||||
to work.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
hide:
|
||||
- toc
|
||||
|
||||
title: SSL/TLS Support
|
||||
title: SSL/TLS/SPDY Support
|
||||
---
|
||||
|
||||
Appium 2.2 introduces the option to start the Appium server with SSL/TLS support.
|
||||
@@ -19,14 +19,15 @@ Both arguments must be provided and should contain paths to a valid
|
||||
[X509 PEM](https://www.ssl.com/guide/pem-der-crt-and-cer-x-509-encodings-and-conversions/)
|
||||
certificate and its corresponding private key.
|
||||
|
||||
After the server is started use the `https` protocol and a client supporting SSL/TLS to
|
||||
communicate to it.
|
||||
After the server is started use the `https` protocol and a client supporting SSL/TLS or
|
||||
[SPDY](https://en.wikipedia.org/wiki/SPDY) to communicate to it.
|
||||
|
||||
### Supported Features
|
||||
|
||||
Once a secure server socket is established it uses Node.js' native
|
||||
[`https`](https://nodejs.org/api/https.html) module to serve connections. All insecure client
|
||||
connections will be rejected by the server.
|
||||
Once a secure server socket is established it supports the following protocols:
|
||||
`['h2', 'spdy/3.1', 'spdy/3', 'spdy/2', 'http/1.1', 'http/1.0']`. See
|
||||
[the SPDY node module documentation](https://www.npmjs.com/package/spdy) to get more details about
|
||||
its features. All insecure client connections will be rejected by the server.
|
||||
|
||||
### Self-Signed Certificates
|
||||
|
||||
|
||||
@@ -39,16 +39,6 @@ So, for example, the `Find Element` command corresponds to an HTTP `POST` reques
|
||||
endpoint `/session/:sessionid/element` (where in this case, `:sessionid` is a placeholder for the
|
||||
unique session ID generated by the server in a previous call to `Create Session`).
|
||||
|
||||
If the client disconnects before Appium finishes sending a `Create Session` response and the
|
||||
request has no `X-Idempotency-Key`, Appium deletes the new session once driver setup completes.
|
||||
Setup is not interrupted. With an accepted idempotency key, a retry that arrives before setup
|
||||
finishes waits for the same session ID, or the same error if setup failed. If the original client
|
||||
and all waiting retries disconnect before setup finishes, Appium deletes the new session and
|
||||
discards its cached result; a later retry starts a new session. Otherwise, Appium keeps the session
|
||||
and caches its response for replay while it remains in the bounded, in-memory idempotency cache.
|
||||
Disconnecting after a response was sent, or during a command in an existing session, does not
|
||||
automatically end that session. Use `Delete Session` when you are done.
|
||||
|
||||
This information is primarily useful for people developing technology that works with the WebDriver
|
||||
spec. It's not particularly useful for people trying to write Appium or Selenium tests. When you
|
||||
write an Appium test, you want to use a programming language you're familiar with. Luckily, there
|
||||
|
||||
@@ -19,7 +19,7 @@ Appium, called `BaseDriver`. You could have something very close to a "working"
|
||||
very simple lines of code:
|
||||
|
||||
```js
|
||||
import {BaseDriver} from '@appium/base-driver'
|
||||
import BaseDriver from '@appium/base-driver'
|
||||
|
||||
class MyNewDriver extends BaseDriver {
|
||||
}
|
||||
|
||||
@@ -8,14 +8,15 @@ title: Write a Test (.NET)
|
||||
The [Appium .NET Client](https://github.com/appium/dotnet-client/) is
|
||||
an official Appium client in C#. This driver is an extension of the Selenium C# client. It has all the functionalities of the regular driver, but add Appium-specific methods on top of this. The driver is available on the public NuGet Gallery as [Appium.WebDriver](https://www.nuget.org/packages/Appium.WebDriver/).
|
||||
|
||||
Now, create a new [NUnit](https://nunit.org/) project. We will also add the references to the Appium.Net driver, and other dependencies.
|
||||
Now, we get inside the directory and create a new [NUnit](https://nunit.org/) project. We will also add the references to the Appium.Net driver, and other dependencies.
|
||||
|
||||
```bash
|
||||
cd dotnet-client
|
||||
dotnet new nunit --name appiumtest
|
||||
|
||||
cd appiumtest
|
||||
|
||||
# This will install the latest version
|
||||
# This will install the latest 5.x version
|
||||
dotnet add package Appium.WebDriver --prerelease
|
||||
dotnet add package Newtonsoft.Json --version 13.0.3
|
||||
```
|
||||
@@ -46,7 +47,7 @@ public class Tests
|
||||
|
||||
driverOptions.AddAdditionalAppiumOption("appPackage", "com.android.settings");
|
||||
driverOptions.AddAdditionalAppiumOption("appActivity", ".Settings");
|
||||
// NoReset assumes the app com.android.settings is preinstalled on the emulator
|
||||
// NoReset assumes the app com.google.android is preinstalled on the emulator
|
||||
driverOptions.AddAdditionalAppiumOption("noReset", true);
|
||||
|
||||
_driver = new AndroidDriver(serverUri, driverOptions, TimeSpan.FromSeconds(180));
|
||||
|
||||
@@ -46,7 +46,7 @@ Subscribes to one or more BiDi events.
|
||||
|
||||
#### Response
|
||||
|
||||
`{subscription: string}` — a unique subscription ID that can be passed to `session.unsubscribe`.
|
||||
`null`
|
||||
|
||||
### bidiUnsubscribe
|
||||
|
||||
@@ -56,20 +56,15 @@ session.unsubscribe
|
||||
|
||||
> WebDriver BiDi documentation: [session.unsubscribe](https://w3c.github.io/webdriver-bidi/#command-session-unsubscribe)
|
||||
|
||||
Unsubscribes using previously returned subscription IDs, or the legacy event/context form.
|
||||
Removing a subscription ID preserves any overlapping subscriptions.
|
||||
Unsubscribes from one or more BiDi events.
|
||||
|
||||
#### Parameters
|
||||
|
||||
|Name|Description|Type|Default|
|
||||
|--|--|--|--|
|
||||
|`subscriptions?`|Non-empty list of subscription IDs returned by `session.subscribe`. Cannot be combined with `events` or `contexts`.|string[]||
|
||||
|`contexts?`|Legacy form only: contexts in which to unsubscribe from the specified events. By default, the global scope is applied.|string[]|`['']`|
|
||||
|`events?`|Legacy form: non-empty list of event names to unsubscribe from. Required when `subscriptions` is omitted.|string[]||
|
||||
|
||||
All subscription IDs must be known to the current session. An unknown ID causes an `invalid argument`
|
||||
error without removing any subscriptions. Subscription IDs are cleared when the session is deleted.
|
||||
|`contexts?`|Contexts in which to unsubscribe from the specified events. By default, the global scope is applied.|string[]|`['']`|
|
||||
|`events`|Names of events to unsubscribe from|string[]||
|
||||
|
||||
#### Response
|
||||
|
||||
`{}`
|
||||
`null`
|
||||
|
||||
@@ -10,6 +10,125 @@ title: JSON Wire Protocol
|
||||
The following is a list of legacy [JSON Wire Protocol (JSONWP)](https://www.selenium.dev/documentation/legacy/json_wire_protocol/)
|
||||
endpoints supported in Appium.
|
||||
|
||||
### getSession
|
||||
|
||||
```
|
||||
GET /session/:sessionId
|
||||
```
|
||||
|
||||
> JSONWP documentation: [/session/:sessionId](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionid)
|
||||
|
||||
Retrieves the capabilities of the current session.
|
||||
|
||||
Appium implements a modified version of this endpoint. If the `appium:eventTimings` capability is
|
||||
set to `true`, the returned result will additionally include the `events` key, whose value contains
|
||||
the event history and timings.
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
For retrieving capabilities, please use [`getAppiumSessionCapabilities`](./appium.md#getappiumsessioncapabilities).<br />
|
||||
For retrieving event history, please use [`getLogEvents`](./appium.md#getlogevents).
|
||||
|
||||
#### Response
|
||||
|
||||
`Capabilities` - an object containing the session capabilities, and the event history (if applicable)
|
||||
|
||||
### availableIMEEngines
|
||||
|
||||
```
|
||||
GET /session/:sessionId/ime/available_engines
|
||||
```
|
||||
|
||||
> JSONWP documentation: [/session/:sessionId/ime/available_engines](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeavailable_engines)
|
||||
|
||||
Retrieves all IME (input method editor) engines available on the device under test.
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
In the future, this endpoint will be moved to the [UiAutomator2 and Espresso drivers](../../ecosystem/drivers.md)
|
||||
|
||||
#### Response
|
||||
|
||||
`string[]` - a list of available IME engines
|
||||
|
||||
### getActiveIMEEngine
|
||||
|
||||
```
|
||||
GET /session/:sessionId/ime/active_engine
|
||||
```
|
||||
|
||||
> JSONWP documentation: [/session/:sessionId/ime/active_engine](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeactive_engine)
|
||||
|
||||
Retrieves the name of the active IME engine.
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
|
||||
|
||||
#### Response
|
||||
|
||||
`string` - the name of the active IME engine
|
||||
|
||||
### isIMEActivated
|
||||
|
||||
```
|
||||
GET /session/:sessionId/ime/activated
|
||||
```
|
||||
|
||||
> JSONWP documentation: [/session/:sessionId/ime/activated](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeactivated)
|
||||
|
||||
Determines if IME input is available and active.
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
|
||||
|
||||
#### Response
|
||||
|
||||
`boolean` - `true` if IME is active, otherwise `false`
|
||||
|
||||
### deactivateIMEEngine
|
||||
|
||||
```
|
||||
POST /session/:sessionId/ime/deactivate
|
||||
```
|
||||
|
||||
> JSONWP documentation: [/session/:sessionId/ime/deactivate](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimedeactivate)
|
||||
|
||||
Deactivates the currently active IME engine.
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
|
||||
|
||||
#### Response
|
||||
|
||||
`null`
|
||||
|
||||
### activateIMEEngine
|
||||
|
||||
```
|
||||
POST /session/:sessionId/ime/activate
|
||||
```
|
||||
|
||||
> JSONWP documentation: [/session/:sessionId/ime/activate](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidimeactivate)
|
||||
|
||||
Activates an IME engine.
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
In the future, this endpoint will be moved to the UiAutomator2 and Espresso drivers
|
||||
|
||||
#### Parameters
|
||||
|
||||
|Name|Description|Type|
|
||||
|--|--|--|
|
||||
|`engine`|Name of the IME engine to activate|string|
|
||||
|
||||
#### Response
|
||||
|
||||
`null`
|
||||
|
||||
### getOrientation
|
||||
|
||||
```
|
||||
@@ -51,3 +170,53 @@ Sets the orientation of the device under test.
|
||||
#### Response
|
||||
|
||||
`null`
|
||||
|
||||
### getGeoLocation
|
||||
|
||||
```
|
||||
GET /session/:sessionId/location
|
||||
```
|
||||
|
||||
> JSONWP documentation: [/session/:sessionId/location](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidlocation)
|
||||
|
||||
Retrieves the current location of the device under test.
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
Please use driver-specific extension methods such as `mobile: getGeoLocation` or
|
||||
`mobile: getSimulatedLocation`
|
||||
|
||||
#### Response
|
||||
|
||||
`Location` - an object with the following properties:
|
||||
|
||||
|Name|Description|Type|
|
||||
|--|--|--|
|
||||
|`altitude`|Altitude of the device location|number|
|
||||
|`latitude`|Latitude of the device location|number|
|
||||
|`longitude`|Longitude of the device location|number|
|
||||
|
||||
### setGeoLocation
|
||||
|
||||
```
|
||||
POST /session/:sessionId/location
|
||||
```
|
||||
|
||||
> JSONWP documentation: [/session/:sessionId/location](https://www.selenium.dev/documentation/legacy/json_wire_protocol/#sessionsessionidlocation)
|
||||
|
||||
Sets the current location of the device under test.
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
Please use driver-specific extension methods such as `mobile: setGeoLocation` or
|
||||
`mobile: setSimulatedLocation`
|
||||
|
||||
#### Parameters
|
||||
|
||||
|Name|Description|Type|
|
||||
|--|--|--|
|
||||
|`location`|New device latitude, longitude and altitude|[`Location`](#response_6)|
|
||||
|
||||
#### Response
|
||||
|
||||
`null`
|
||||
|
||||
@@ -119,3 +119,53 @@ Retrieves all available application contexts.
|
||||
#### Response
|
||||
|
||||
`string[]` - the names of available contexts
|
||||
|
||||
### getNetworkConnection
|
||||
|
||||
```
|
||||
GET /session/:sessionId/network_connection
|
||||
```
|
||||
|
||||
> MJSONWP documentation: [Device Modes](https://github.com/SeleniumHQ/mobile-spec/blob/master/spec-draft.md#device-modes)
|
||||
|
||||
Retrieves the current state of network types (data, Wi-Fi, airplane mode).
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
Please use driver-specific extension methods such as `mobile: getConnectivity`
|
||||
|
||||
#### Response
|
||||
|
||||
`NetworkConnectionState` - a number indicating the current network state:
|
||||
|
||||
|Value|Data|Wi-Fi|Airplane Mode|
|
||||
|--|--|--|--|
|
||||
|`0`|OFF|OFF|OFF|
|
||||
|`1`|OFF|OFF|ON|
|
||||
|`2`|OFF|ON|OFF|
|
||||
|`4`|ON|OFF|OFF|
|
||||
|`6`|ON|ON|OFF|
|
||||
|
||||
### setNetworkConnection
|
||||
|
||||
```
|
||||
POST /session/:sessionId/network_connection
|
||||
```
|
||||
|
||||
> MJSONWP documentation: [Device Modes](https://github.com/SeleniumHQ/mobile-spec/blob/master/spec-draft.md#device-modes)
|
||||
|
||||
Sets the state of network types (data, Wi-Fi, airplane mode).
|
||||
|
||||
!!! warning "Deprecated"
|
||||
|
||||
Please use driver-specific extension methods such as `mobile: setConnectivity`
|
||||
|
||||
#### Parameters
|
||||
|
||||
|<div style="width:6em">Name</div>|Description|<div style="width:18em">Type</div>|
|
||||
|--|--|--|
|
||||
|`parameters`|Object containing the `type` key, whose value is the desired network state|`{"type": `[`NetworkConnectionState`](#response_5)`}`|
|
||||
|
||||
#### Response
|
||||
|
||||
[`NetworkConnectionState`](#response_5) - the new network state
|
||||
|
||||
@@ -265,43 +265,6 @@ preserved, and only the incomplete uploads will be stopped.
|
||||
|
||||
## Universal XML Plugin
|
||||
|
||||
Translation is on by default. It can be turned off and on during a session with the
|
||||
[execute methods](../../guides/execute-methods.md) below, and applies only to the current session.
|
||||
|
||||
### execute
|
||||
|
||||
```
|
||||
POST /session/:sessionId/execute/sync
|
||||
```
|
||||
|
||||
Modifies the [`execute`](./webdriver.md#execute) endpoint:
|
||||
|
||||
* Adds the `universalXml: setEnabled` and `universalXml: isEnabled` execute methods. Any other
|
||||
script is passed on unchanged
|
||||
|
||||
#### universalXml: setEnabled
|
||||
|
||||
Turns translation on or off for the current session. While it is off, `findElement`,
|
||||
`findElements` and `getPageSource` are passed on unchanged.
|
||||
|
||||
##### Parameters
|
||||
|
||||
|Name|Description|Type|
|
||||
|--|--|--|
|
||||
|`enabled`|Whether node/attribute names should be translated|boolean|
|
||||
|
||||
##### Response
|
||||
|
||||
`null`
|
||||
|
||||
#### universalXml: isEnabled
|
||||
|
||||
Returns whether translation is on for the current session.
|
||||
|
||||
##### Response
|
||||
|
||||
`boolean` - `true` if translation is on
|
||||
|
||||
### findElement
|
||||
|
||||
```
|
||||
|
||||
@@ -25,11 +25,18 @@ POST /session
|
||||
|
||||
Creates a new WebDriver session.
|
||||
|
||||
Appium implements a modified version of this endpoint for historical reasons. While the W3C
|
||||
endpoint only accepts 1 parameter, Appium's implementation allows up to 3 parameters, as this was
|
||||
required by the legacy JSON Wire Protocol (JSONWP). Since Appium 2, the JSONWP format is no longer
|
||||
supported, and any of the 3 parameters can be used to specify the W3C capabilities.
|
||||
|
||||
#### Parameters
|
||||
|
||||
|Name|Description|Type|
|
||||
|--|--|--|
|
||||
|`capabilities?`|Capabilities of the new session|`W3CDriverCaps`|
|
||||
|`w3cCapabilities1?`|Capabilities of the new session|`W3CDriverCaps`|
|
||||
|`w3cCapabilities2?`|Another location for the new session capabilities (legacy)|`W3CDriverCaps`|
|
||||
|`w3cCapabilities?`|Another location for the new session capabilities (legacy)|`W3CDriverCaps`|
|
||||
|
||||
#### Response
|
||||
|
||||
@@ -84,19 +91,14 @@ GET /session/:sessionId/timeouts
|
||||
|
||||
Retrieves the timeout values of the current session.
|
||||
|
||||
Appium implements a modified version of this endpoint, by also returning the value of the `command`
|
||||
timeout for supported drivers and contexts.
|
||||
|
||||
#### Response
|
||||
|
||||
`GetTimeoutsResult` - an object with the following properties:
|
||||
|
||||
|Name|Description|Type|
|
||||
|--|--|--|
|
||||
|`script`|Script timeout|number or null|
|
||||
|`pageLoad`|Page load timeout|number or null|
|
||||
|`implicit`|Implicit wait timeout|number or null|
|
||||
|`command`|Appium command timeout|number|
|
||||
|`command`|Command timeout|number|
|
||||
|`implicit`|Implicit wait timeout|number|
|
||||
|
||||
### timeouts
|
||||
|
||||
@@ -108,17 +110,13 @@ POST /session/:sessionId/timeouts
|
||||
|
||||
Sets the timeout values of the current session.
|
||||
|
||||
Appium implements a modified version of this endpoint by adding the optional `command` parameter
|
||||
for supported drivers and contexts.
|
||||
|
||||
#### Parameters
|
||||
|
||||
|Name|Description|Type|
|
||||
|--|--|--|
|
||||
|`script?`|Script timeout (in milliseconds)|number or null|
|
||||
|`implicit?`|Implicit wait timeout (in milliseconds)|number or null|
|
||||
|`pageLoad?`|Page load timeout (in milliseconds)|number or null|
|
||||
|`command?`|Appium command timeout (in milliseconds)|number|
|
||||
|`implicit?`|Implicit wait timeout (in milliseconds)|number|
|
||||
|`pageLoad?`|Page load timeout (in milliseconds)|number|
|
||||
|`script?`|Script timeout (in milliseconds)|number|
|
||||
|
||||
#### Response
|
||||
|
||||
|
||||
@@ -14,7 +14,6 @@ they can only be enabled using the wildcard (`*`) prefix:
|
||||
| Feature Name | Description |
|
||||
|-------------------|-------------------------------------------------------------------------------|
|
||||
|`session_discovery`|Allows retrieving the list of active server sessions via `GET /appium/sessions`|
|
||||
|`cors` |Allows web browser connections to the server from any host |
|
||||
|
||||
|
||||
Of course, Appium drivers and plugins are free to define additional insecure features of their own.
|
||||
|
||||
@@ -27,12 +27,15 @@ appium
|
||||
|<div style="width:15em">Argument</div>|Description|Type|<div style="width:7em">Default</div>|
|
||||
|--|--|--|--|
|
||||
|`--address`, `-a`|IPv4/IPv6 address to listen on|string|`0.0.0.0`|
|
||||
|`--allow-cors`|Allow web browser connections from any host|boolean|`false`|
|
||||
|`--allow-insecure`|List of [insecure features](../../guides/security.md) that should be allowed in this server's sessions. Individual features can be overridden by `--deny-insecure`. Has no effect in combination with `--relaxed-security`.|array<string>|`[]`|
|
||||
|`--allow-unknown-args`|Do not exit if unrecognized command-line arguments are passed to the server; ignore them instead. Useful when the Appium CLI is wrapped by external tooling that appends extra flags.|boolean|`false`|
|
||||
|`--app-url-rules`|Rules that remote application URLs (e.g. in the `appium:app` capability) must satisfy before the server downloads them. See the [Restricting Remote App URLs](../../guides/security.md#restricting-remote-app-urls) guide for details. Can be a path to a JSON file or raw JSON.|object||
|
||||
|`--base-path`, `-pa`|Base path to use as the prefix for all webdriver routes running on the server|string|`""`|
|
||||
|`--callback-address`, `-ca`|Callback IP address|string|`0.0.0.0`|
|
||||
|`--callback-port`, `-cp`|Callback port|integer|`4723`|
|
||||
|`--config`|Path to an [Appium configuration JSON file](../../guides/config.md)|string||
|
||||
|`--default-capabilities`, `-dc`|Capabilities that will be used for each session, unless overridden by received capabilities. See [Default Capabilities](#default-capabilities) for how they are applied.|object||
|
||||
|`--debug-log-spacing`|Add exaggerated spacing in logs to help with visual inspection|boolean|`false`|
|
||||
|`--default-capabilities`, `-dc`|Capabilities that will be used for each session, unless overridden by received capabilities|object||
|
||||
|`--deny-insecure`|List of [insecure features](../../guides/security.md) that should be disabled in this server's sessions. Since all insecure features are disabled by default, this argument has no effect without either `--allow-insecure` or `--relaxed-security`, and is applied after both.|array<string>|`[]`|
|
||||
|`--driver`|Driver-specific configuration. Keys should correspond to driver package names|object||
|
||||
|`--drivers-import-chunk-size`|Maximum number of drivers that can be imported in parallel on server startup|number|`3`|
|
||||
@@ -41,7 +44,7 @@ appium
|
||||
|`--local-timezone`|Use local timezone for log timestamps|boolean|`false`|
|
||||
|`--log`, `-g`|Path to a file where the server logs should be output. This does not affect output on the console.|string||
|
||||
|`--log-filters`|List of log filtering rules. See the [log filtering guide](../../guides/log-filters.md) for details.|array||
|
||||
|`--log-level`|The log level for the server logs. Supported values are `debug`, `info`, `warn`, or `error`. Combining two supported values using a colon (e.g. `warn:debug`) allows to set separate log levels for the console and file outputs, respectively.|string|`info`|
|
||||
|`--log-level`|The log level for the server logs. Supported values are `debug`, `info`, `warn`, or `error`. Combining two supported values using a colon (e.g. `warn:debug`) allows to set separate log levels for the console and file outputs, respectively.|string|`debug`|
|
||||
|`--log-format`|The log format of the server logs. Supported values are `text`, `json`, or `pretty_json`. Setting the value to `json` disables colors.|string|`text`|
|
||||
|`--log-no-colors`|Disable colors in the server log|boolean|`false`|
|
||||
|`--log-timestamp`|Show timestamps in the server log|boolean|`false`|
|
||||
@@ -49,6 +52,7 @@ appium
|
||||
|`--max-ipc-data-size`|Maximum byte size of IPC message objects.|integer|`1048576` (1MB)|
|
||||
|`--max-ipc-topics`|Maximum number of IPC topics per session.|integer|`1000`|
|
||||
|`--no-perms-check`|Skip various permission checks on the server startup|boolean|`false`|
|
||||
|`--nodeconfig`|JSON configuration for registering Appium as a node with Selenium Grid 3|object||
|
||||
|`--plugin`|Plugin-specific configuration. Keys should correspond to plugin package names|object||
|
||||
|`--plugins-import-chunk-size`|Maximum number of plugins that can be imported in parallel on server startup|number|`7`|
|
||||
|`--port`, `-p`|Port to listen on|integer|`4723`|
|
||||
@@ -57,45 +61,12 @@ appium
|
||||
|`--shutdown-timeout`|Timeout (in milliseconds) for waiting on all active connections to close, when shutting down the server|number|`5000`|
|
||||
|`--ssl-cert-path`|Absolute path to the `.cert` file if TLS is used. Must be provided together with `--ssl-key-path`. See the [SSL/TLS/SPDY Support guide](../../guides/tls.md) for details.|string||
|
||||
|`--ssl-key-path`|Absolute path to the `.key` file if TLS is used. Must be provided together with `--ssl-cert-path`. See the [SSL/TLS/SPDY Support guide](../../guides/tls.md) for details.|string||
|
||||
|`--strict-caps`|Prevent creation of new client sessions that use unsupported capabilities|boolean|`false`|
|
||||
|`--tmp`|Absolute path to the directory used for temporary files|string|[`os.tmpdir()`](https://nodejs.org/api/os.html#ostmpdir)|
|
||||
|`--use-drivers`|List of drivers to activate. By default, all installed drivers are activated.|array<string>|`[]`|
|
||||
|`--use-plugins`|List of plugins to activate. By default, no plugins are activated. Set to `["all"]` to activate all installed plugins.|array<string>|`[]`|
|
||||
|`--webhook`, `-G`|URL for an HTTP listener where the server logs should be output. This does not affect output on the console. A bare `host:port` is also accepted, which posts the logs to the root path over plain http; a value having neither a scheme nor a port falls back to `127.0.0.1:9003`.|string||
|
||||
|
||||
### Default Capabilities
|
||||
|
||||
Capabilities set with `--default-capabilities` are added to the received capabilities before a
|
||||
driver is matched. This is Appium's own defaulting behavior, not something defined by the W3C
|
||||
WebDriver specification.
|
||||
|
||||
* A value the client sends in `alwaysMatch`, or in a given `firstMatch` candidate, takes precedence
|
||||
over the server default
|
||||
* Defaults fill missing keys in each `firstMatch` candidate separately. A value in one candidate
|
||||
does not stop the default from being applied to another candidate
|
||||
* A key sent in both `alwaysMatch` and `firstMatch` is still rejected by the usual capability
|
||||
validation. Server defaults do not change that
|
||||
|
||||
For example, with these server defaults:
|
||||
|
||||
```json
|
||||
{"appium:newCommandTimeout": 60}
|
||||
```
|
||||
|
||||
and these received capabilities:
|
||||
|
||||
```json
|
||||
{
|
||||
"alwaysMatch": {"appium:deviceName": "Pixel"},
|
||||
"firstMatch": [
|
||||
{"platformName": "iOS", "appium:newCommandTimeout": 120},
|
||||
{"platformName": "Android"}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
the iOS candidate keeps `appium:newCommandTimeout` of `120`, and the Android candidate gets the
|
||||
default `60`. The session uses the value from whichever candidate it is created with.
|
||||
|
||||
### Info Options
|
||||
|
||||
The following options are used for reference or debug purposes. They are only supported for the base `appium` command (not `appium server`), and will not launch the server.
|
||||
|
||||
@@ -32,7 +32,7 @@ appium setup browser
|
||||
|
||||
Installs the following extensions for desktop application testing:
|
||||
|
||||
* Drivers: `mac2`[^1], `wincore`[^2]
|
||||
* Drivers: `mac2`[^1], `windows`[^2]
|
||||
* Plugins: `images`, `inspector`
|
||||
|
||||
#### Usage
|
||||
|
||||
@@ -32,6 +32,7 @@ default value.
|
||||
| <div style="width:19em">Capability</div> | Description | Type | Default |
|
||||
|--|--|--|--|
|
||||
| `webSocketUrl` | Toggle support of the WebDriver BiDi protocol | `boolean` ||
|
||||
| `appium:eventTimings` (deprecated) | Toggle collection of [Event Timings](../../guides/event-timing.md). This capability is deprecated - please use the [`getLogEvents`](../api/appium.md#getlogevents) endpoint instead. | `boolean` ||
|
||||
| `appium:newCommandTimeout` | Number of seconds the Appium server should wait for clients to send commands before stopping the session. A value of `0` disables the timeout. | `number` | `60` |
|
||||
| `appium:printPageSourceOnFindFailure` | Toggle retrieval of the the page source and its printing to the Appium log, whenever a request to find an element fails | `boolean` ||
|
||||
|
||||
@@ -41,9 +42,15 @@ These capabilities are not directly used in the Appium server/base driver, but a
|
||||
validation checks due to their relevance in other drivers. The actual handling of these
|
||||
capabilities is optional and entirely driver-dependent.
|
||||
|
||||
| Capability | Validation |
|
||||
|--------------------------|---------------------------------------------------------------|
|
||||
| `appium:platformVersion` | Must be `string` |
|
||||
| `appium:app` | Must be `string`; empty values are ignored |
|
||||
| `appium:fullReset` | Must be `boolean`; mutually exclusive with `appium:noReset` |
|
||||
| `appium:noReset` | Must be `boolean`; mutually exclusive with `appium:fullReset` |
|
||||
| Capability | Validation |
|
||||
|-----------------------------------|---------------------------------------------------------------|
|
||||
| `platformVersion` | Must be `string` |
|
||||
| `appium:app` | Must be `string`; empty values are ignored |
|
||||
| `appium:autoLaunch` (deprecated) | Must be `boolean` |
|
||||
| `appium:autoWebview` | Must be `boolean` |
|
||||
| `appium:fullReset` | Must be `boolean`; mutually exclusive with `appium:noReset` |
|
||||
| `appium:language` | Must be `string` |
|
||||
| `appium:locale` | Must be `string` |
|
||||
| `appium:orientation` | Must be either `LANDSCAPE` or `PORTRAIT` |
|
||||
| `appium:noReset` | Must be `boolean`; mutually exclusive with `appium:fullReset` |
|
||||
| `appium:udid` | Must be `string` |
|
||||
|
||||
@@ -46,5 +46,11 @@ capabilities is optional and entirely driver-dependent.
|
||||
| --------------------------------------------------- | ------------------------------------------------------------- |
|
||||
| `platformVersion` | Must be `string` |
|
||||
| `appium:app` | Must be `string`; empty values are ignored |
|
||||
| `appium:autoLaunch` (deprecated) | Must be `boolean` |
|
||||
| `appium:autoWebview` | Must be `boolean` |
|
||||
| `appium:fullReset` | Must be `boolean`; mutually exclusive with `appium:noReset` |
|
||||
| `appium:language` | Must be `string` |
|
||||
| `appium:locale` | Must be `string` |
|
||||
| `appium:orientation` | Must be either `LANDSCAPE` or `PORTRAIT` |
|
||||
| `appium:noReset` | Must be `boolean`; mutually exclusive with `appium:fullReset` |
|
||||
| `appium:udid` | Must be `string` |
|
||||
|
||||
@@ -57,7 +57,6 @@ nav:
|
||||
- reference/api/plugins.md
|
||||
- Guides:
|
||||
- Migration:
|
||||
- guides/migrating-3-to-4.md
|
||||
- guides/migrating-2-to-3.md
|
||||
- guides/migrating-1-to-2.md
|
||||
- Server/Driver Configuration:
|
||||
|
||||
@@ -10,16 +10,18 @@
|
||||
/* eslint-disable promise/prefer-await-to-callbacks */
|
||||
/* eslint-disable promise/prefer-await-to-then */
|
||||
|
||||
import {readFileSync} from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {fileURLToPath} from 'node:url';
|
||||
|
||||
import {deploy, buildSite} from '@appium/docutils';
|
||||
import semver from 'semver';
|
||||
|
||||
import {log, LANGS, DOCS_DIR, DOCS_BRANCH, DOCS_PREFIX, DOCS_REMOTE, LATEST_ALIAS} from './utils.js';
|
||||
|
||||
const {version} = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8'));
|
||||
const {
|
||||
log,
|
||||
LANGS,
|
||||
DOCS_DIR,
|
||||
DOCS_BRANCH,
|
||||
DOCS_PREFIX,
|
||||
DOCS_REMOTE,
|
||||
LATEST_ALIAS,
|
||||
} = require('./utils');
|
||||
const path = require('node:path');
|
||||
const semver = require('semver');
|
||||
const {version} = require('../../package.json');
|
||||
|
||||
const branch = process.env.APPIUM_DOCS_BRANCH ?? DOCS_BRANCH;
|
||||
const basePrefix = process.env.APPIUM_DOCS_PREFIX ?? DOCS_PREFIX;
|
||||
@@ -32,6 +34,9 @@ const push = Boolean(process.env.APPIUM_DOCS_PUBLISH);
|
||||
* Builds and optionally deploys docs for each supported language.
|
||||
*/
|
||||
async function main() {
|
||||
// @appium/docutils is ESM-only; this file is CommonJS, so it must be loaded dynamically
|
||||
const {deploy, buildSite} = await import('@appium/docutils');
|
||||
|
||||
log.info(`Building Appium docs and committing to ${DOCS_BRANCH}`);
|
||||
|
||||
const semVersion = semver.parse(version);
|
||||
@@ -64,10 +69,10 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
if (require.main === module) {
|
||||
main().catch((err) => {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
export default main;
|
||||
module.exports = main;
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// for simplicity this file is not transpiled and is run directly via an npm script
|
||||
/* eslint-disable no-console */
|
||||
/* eslint-disable promise/prefer-await-to-callbacks */
|
||||
/* eslint-disable promise/prefer-await-to-then */
|
||||
|
||||
const path = require('node:path');
|
||||
const {fs} = require('@appium/support');
|
||||
const {AppiumConfigJsonSchema} = require('@appium/schema');
|
||||
|
||||
const DOC_PATH = path.resolve(__dirname, '..', 'en', 'cli', 'args.md');
|
||||
|
||||
const START_TAG = `<!-- AUTOGEN-START -->`;
|
||||
const STOP_TAG = `<!-- AUTOGEN-STOP -->`;
|
||||
|
||||
/**
|
||||
* Regenerates the CLI arguments table in docs.
|
||||
*/
|
||||
async function main() {
|
||||
console.log(`Gathering current cli doc file contents...`);
|
||||
const [preStart, postEnd] = await getDocParts();
|
||||
console.log(`Generating new cli arg table...`);
|
||||
const argTable = getCliArgTable();
|
||||
console.log(`Writing new doc file...`);
|
||||
await writeNewDoc(preStart, argTable, postEnd);
|
||||
console.log(`...done!`);
|
||||
}
|
||||
|
||||
async function getDocParts() {
|
||||
if (!(await fs.exists(DOC_PATH))) {
|
||||
throw new Error(`Cannot find args.md at ${DOC_PATH}`);
|
||||
}
|
||||
|
||||
const curContents = await fs.readFile(DOC_PATH, 'utf-8');
|
||||
|
||||
// attempt to verify the start/stop tags
|
||||
const [preStart, postStart] = curContents.split(START_TAG);
|
||||
if (!postStart) {
|
||||
throw new Error(`Could not find autogen start tag '${START_TAG}'. Make sure it's in place!`);
|
||||
}
|
||||
const [, postEnd] = postStart.split(STOP_TAG);
|
||||
if (!postEnd) {
|
||||
throw new Error(`Could not find autogen stop tag '${STOP_TAG}'. Make sure it's in place!`);
|
||||
}
|
||||
|
||||
return [preStart, postEnd];
|
||||
}
|
||||
|
||||
function getCliArgTable() {
|
||||
const pad = ' '.repeat(30);
|
||||
const header = `|Argument${pad}|Description|Type|Default|Aliases|\n` + `|--|--|--|--|--|`;
|
||||
const serverProps = AppiumConfigJsonSchema.properties.server.properties;
|
||||
const args = Object.keys(serverProps).map((arg) => {
|
||||
let {appiumCliAliases = [], description, type, items, maximum, minimum} = serverProps[arg];
|
||||
let def = serverProps[arg].default;
|
||||
let enums = serverProps[arg].enum;
|
||||
if (type === 'array' || type === 'object' || (type === 'string' && def === '')) {
|
||||
def = JSON.stringify(def);
|
||||
}
|
||||
if (type === 'array' && items.type) {
|
||||
type = `array<${items.type}>`;
|
||||
}
|
||||
if (type === 'integer' && typeof minimum !== 'undefined' && typeof maximum !== 'undefined') {
|
||||
description = `${description} (Value must be between \`${minimum}\` and \`${maximum}\`)`;
|
||||
}
|
||||
if (enums) {
|
||||
const enumsFormatted = enums.map((e) => `\`${e}\``).join(', ');
|
||||
description = `${description} (Value must be one of: ${enumsFormatted})`;
|
||||
}
|
||||
return {
|
||||
arg: `--${arg}`,
|
||||
aliases: appiumCliAliases.map((a) => `-${a}`),
|
||||
type,
|
||||
def,
|
||||
description,
|
||||
};
|
||||
});
|
||||
const body = args
|
||||
.map(({arg, aliases, type, def, description}) => {
|
||||
const aliasStr = aliases.map((a) => `\`${a}\``).join(', ');
|
||||
def = typeof def !== 'undefined' ? `\`${def}\`` : '';
|
||||
return `|\`${arg}\`|${description}|${type}|${def}|${aliasStr}|`;
|
||||
})
|
||||
.join('\n');
|
||||
return `${header}\n${body}`;
|
||||
}
|
||||
|
||||
async function writeNewDoc(preStart, argTable, postEnd) {
|
||||
const newContents = `${preStart}${START_TAG}\n${argTable}\n${STOP_TAG}${postEnd}`;
|
||||
await fs.writeFile(DOC_PATH, newContents);
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((err) => {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = main;
|
||||
@@ -2,19 +2,28 @@
|
||||
|
||||
// for simplicity this file is not transpiled and is run directly via an npm script
|
||||
//
|
||||
import path from 'node:path';
|
||||
|
||||
import {logger} from '@appium/support';
|
||||
const {logger} = require('@appium/support');
|
||||
const path = require('node:path');
|
||||
|
||||
const log = logger.getLogger('Docs');
|
||||
|
||||
const DOCS_REMOTE = 'origin';
|
||||
const DOCS_BRANCH = 'gh-pages';
|
||||
const DOCS_PREFIX = 'docs';
|
||||
const DOCS_DIR = path.resolve(import.meta.dirname, '..');
|
||||
const DOCS_DIR = path.resolve(__dirname, '..');
|
||||
const LATEST_ALIAS = 'latest';
|
||||
const ASSETS_DIR = path.join(DOCS_DIR, 'assets');
|
||||
const LANGS = ['en', 'ja', 'zh'];
|
||||
const DEFAULT_LANG = 'en';
|
||||
|
||||
export {log, DOCS_DIR, ASSETS_DIR, LANGS, DEFAULT_LANG, DOCS_BRANCH, DOCS_PREFIX, DOCS_REMOTE, LATEST_ALIAS};
|
||||
module.exports = {
|
||||
log,
|
||||
DOCS_DIR,
|
||||
ASSETS_DIR,
|
||||
LANGS,
|
||||
DEFAULT_LANG,
|
||||
DOCS_BRANCH,
|
||||
DOCS_PREFIX,
|
||||
DOCS_REMOTE,
|
||||
LATEST_ALIAS,
|
||||
};
|
||||
|
||||
@@ -46,5 +46,11 @@ capabilities is optional and entirely driver-dependent.
|
||||
| --------------------------------------------------- | ------------------------------------------------------------- |
|
||||
| `platformVersion` | Must be `string` |
|
||||
| `appium:app` | Must be `string`; empty values are ignored |
|
||||
| `appium:autoLaunch` (deprecated) | Must be `boolean` |
|
||||
| `appium:autoWebview` | Must be `boolean` |
|
||||
| `appium:fullReset` | Must be `boolean`; mutually exclusive with `appium:noReset` |
|
||||
| `appium:language` | Must be `string` |
|
||||
| `appium:locale` | Must be `string` |
|
||||
| `appium:orientation` | Must be either `LANDSCAPE` or `PORTRAIT` |
|
||||
| `appium:noReset` | Must be `boolean`; mutually exclusive with `appium:fullReset` |
|
||||
| `appium:udid` | Must be `string` |
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
'use strict';
|
||||
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
@@ -5,6 +7,8 @@
|
||||
*
|
||||
* @see https://npm.im/@appium/base-driver
|
||||
* @example
|
||||
* import { BaseDriver, errors } from 'appium/driver.js';
|
||||
* const { BaseDriver, errors } = require('appium/driver');
|
||||
*/
|
||||
export * from '@appium/base-driver';
|
||||
|
||||
/** @type {import('@appium/base-driver')} */
|
||||
module.exports = require('@appium/base-driver');
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import * as appium from './build/lib/main.js';
|
||||
const appium = require('./build/lib/main.js');
|
||||
|
||||
// Node identifies the entry module even when invoked through an installed bin symlink.
|
||||
if (import.meta.main) {
|
||||
void appium.main();
|
||||
if (require.main === module) {
|
||||
appium.main();
|
||||
}
|
||||
|
||||
export * from './build/lib/main.js';
|
||||
module.exports = appium;
|
||||
|
||||
+160
-112
@@ -4,9 +4,9 @@ import {
|
||||
CREATE_SESSION_COMMAND,
|
||||
DELETE_SESSION_COMMAND,
|
||||
DriverCore,
|
||||
errors,
|
||||
type ExtensionCore,
|
||||
generateDriverLogPrefix,
|
||||
getProxyReq,
|
||||
GET_STATUS_COMMAND,
|
||||
isSessionCommand,
|
||||
isW3cCaps,
|
||||
@@ -15,16 +15,14 @@ import {
|
||||
promoteAppiumOptions,
|
||||
promoteAppiumOptionsForObject,
|
||||
PROTOCOLS,
|
||||
runWithCommandTimeout,
|
||||
withoutProxyReq,
|
||||
} from '@appium/base-driver';
|
||||
import {util, net} from '@appium/support';
|
||||
import {util} from '@appium/support';
|
||||
import type {
|
||||
AppiumServer,
|
||||
DriverCaps,
|
||||
DriverData,
|
||||
DriverOpts,
|
||||
ExternalDriver,
|
||||
HTTPMethod,
|
||||
IAppiumIpc,
|
||||
Plugin,
|
||||
PluginClass,
|
||||
@@ -37,20 +35,15 @@ import type {
|
||||
} from '@appium/types';
|
||||
import type WebSocket from 'ws';
|
||||
|
||||
import * as bidiCommands from './bidi-commands.js';
|
||||
import {BIDI_BASE_PATH, DRIVER_TYPE, SESSION_DISCOVERY_FEATURE} from './constants.js';
|
||||
import type {DriverConfig} from './extension/driver-config.js';
|
||||
import {APPIUM_VER, getBuildInfo, updateBuildInfo} from './helpers/build.js';
|
||||
import {
|
||||
makeNonW3cCapsError,
|
||||
parseCapsForInnerDriver,
|
||||
type ParsedDriverCaps,
|
||||
pullSettings,
|
||||
} from './helpers/capability.js';
|
||||
import * as insecureFeatures from './insecure-features.js';
|
||||
import * as inspectorCommands from './inspector-commands.js';
|
||||
import {getDefaultsForExtension} from './schema/index.js';
|
||||
import {pickBy} from './utils/index.js';
|
||||
import * as bidiCommands from './bidi-commands';
|
||||
import {BIDI_BASE_PATH, DRIVER_TYPE, SESSION_DISCOVERY_FEATURE} from './constants';
|
||||
import type {DriverConfig} from './extension/driver-config';
|
||||
import {APPIUM_VER, getBuildInfo, updateBuildInfo} from './helpers/build';
|
||||
import {makeNonW3cCapsError, parseCapsForInnerDriver, type ParsedDriverCaps, pullSettings} from './helpers/capability';
|
||||
import * as insecureFeatures from './insecure-features';
|
||||
import * as inspectorCommands from './inspector-commands';
|
||||
import {getDefaultsForExtension} from './schema';
|
||||
import {compact, pickBy, pull} from './utils';
|
||||
|
||||
const desiredCapabilityConstraints = {
|
||||
automationName: {
|
||||
@@ -66,14 +59,6 @@ const desiredCapabilityConstraints = {
|
||||
export type AppiumDriverConstraints = typeof desiredCapabilityConstraints;
|
||||
export type W3CAppiumDriverCaps = W3CDriverCaps<AppiumDriverConstraints>;
|
||||
|
||||
/**
|
||||
* {@link DriverCaps} with `webSocketUrl` widened to `string`: the client sends it as a boolean,
|
||||
* but the inner driver's response carries the resolved BiDi URL as a string.
|
||||
*/
|
||||
type DriverCapsWithBidiUrl = Omit<DriverCaps<AppiumDriverConstraints>, 'webSocketUrl'> & {
|
||||
webSocketUrl?: string | boolean;
|
||||
};
|
||||
|
||||
/** Result shape for umbrella {@link AppiumDriver.createSession} / {@link AppiumDriver.deleteSession}. */
|
||||
interface SessionHandlerResult<V = unknown> {
|
||||
value?: V;
|
||||
@@ -81,13 +66,28 @@ interface SessionHandlerResult<V = unknown> {
|
||||
protocol?: string;
|
||||
}
|
||||
|
||||
type SessionHandlerCreateResult = SessionHandlerResult<[string, DriverCapsWithBidiUrl, string | undefined]>;
|
||||
type SessionHandlerCreateResult = SessionHandlerResult<
|
||||
[string, DriverCaps<AppiumDriverConstraints>, string | undefined]
|
||||
>;
|
||||
|
||||
type SessionHandlerDeleteResult = SessionHandlerResult<void>;
|
||||
|
||||
/**
|
||||
* Tuple shape of the deprecated multi-argument overload of {@link AppiumDriver.createSession}.
|
||||
* Shared between that overload's declaration and its implementation signature so the parameter
|
||||
* list only needs to be written out once.
|
||||
*
|
||||
* @deprecated Use the single-argument overload of {@link AppiumDriver.createSession} instead.
|
||||
*/
|
||||
type LegacyCreateSessionArgs = [
|
||||
w3cCapabilities1: W3CAppiumDriverCaps,
|
||||
w3cCapabilities2?: W3CAppiumDriverCaps,
|
||||
w3cCapabilities3?: W3CAppiumDriverCaps,
|
||||
];
|
||||
|
||||
/** @internal Not part of {@link ExternalDriver}; used only when wiring session IPC. */
|
||||
type IpcAssignable = {
|
||||
assignIpc: (ipc: IAppiumIpc) => Promise<void>;
|
||||
assignIpc?: (ipc: IAppiumIpc) => Promise<void>;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -97,6 +97,8 @@ type IpcAssignable = {
|
||||
export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
readonly sessions: Record<string, ExternalDriver> = {};
|
||||
|
||||
readonly pendingDrivers: Record<string, ExternalDriver[]> = {};
|
||||
|
||||
/**
|
||||
* The umbrella driver does not observe its own command timeout; inner session drivers do.
|
||||
*/
|
||||
@@ -167,7 +169,7 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
}
|
||||
|
||||
/** The umbrella driver does not queue commands; inner session drivers may. */
|
||||
override get isCommandsQueueEnabled(): boolean {
|
||||
get isCommandsQueueEnabled(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -276,48 +278,46 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
* Creates a session: picks an inner driver from caps, runs plugin hooks, and returns a protocol
|
||||
* envelope with either `[sessionId, caps, protocol]` or an error.
|
||||
*
|
||||
* @param rawW3cCapabilities - the new session capabilities in W3C format
|
||||
* @param w3cCapabilities - the new session capabilities in W3C format
|
||||
*/
|
||||
async createSession(rawW3cCapabilities: W3CAppiumDriverCaps): Promise<SessionHandlerCreateResult> {
|
||||
const defaultCapabilities = promoteAppiumOptionsForObject(structuredClone(this.args.defaultCapabilities ?? {}));
|
||||
const defaultSettings = pullSettings(defaultCapabilities as StringRecord);
|
||||
if (!isW3cCaps(rawW3cCapabilities)) {
|
||||
async createSession(w3cCapabilities: W3CAppiumDriverCaps): Promise<SessionHandlerCreateResult>;
|
||||
/**
|
||||
* @deprecated Legacy call sites may pass the same W3C caps in up to three positions. These
|
||||
* positions are intended to carry the same value; if they differ, which one wins is
|
||||
* unspecified. Use the single-argument overload of {@linkcode createSession} instead.
|
||||
*/
|
||||
async createSession(...legacyArgs: LegacyCreateSessionArgs): Promise<SessionHandlerCreateResult>;
|
||||
async createSession(...legacyArgs: LegacyCreateSessionArgs): Promise<SessionHandlerCreateResult> {
|
||||
const [w3cCapabilities1, w3cCapabilities2, w3cCapabilities3] = legacyArgs;
|
||||
const defaultCapabilities = structuredClone(this.args.defaultCapabilities);
|
||||
const defaultSettings = pullSettings((defaultCapabilities ?? {}) as StringRecord);
|
||||
const w3cCapabilities = structuredClone([w3cCapabilities3, w3cCapabilities2, w3cCapabilities1].find(isW3cCaps));
|
||||
if (!w3cCapabilities) {
|
||||
throw makeNonW3cCapsError();
|
||||
}
|
||||
const w3cCapabilities = promoteAppiumOptions(structuredClone(rawW3cCapabilities));
|
||||
const sharedSettings = {
|
||||
const w3cSettings = {
|
||||
...defaultSettings,
|
||||
...pullSettings(w3cCapabilities.alwaysMatch ?? {}),
|
||||
};
|
||||
if (w3cCapabilities.firstMatch === undefined) {
|
||||
w3cCapabilities.firstMatch = [{}];
|
||||
}
|
||||
// Carry each candidate's settings through capability selection independently.
|
||||
for (const firstMatchEntry of w3cCapabilities.firstMatch ?? []) {
|
||||
const settings = {...sharedSettings, ...pullSettings(firstMatchEntry)};
|
||||
if (util.isPlainObject(firstMatchEntry) && !util.isEmpty(settings)) {
|
||||
(firstMatchEntry as StringRecord)['appium:settings'] = settings;
|
||||
}
|
||||
Object.assign(w3cSettings, pullSettings(firstMatchEntry));
|
||||
}
|
||||
|
||||
const protocol = PROTOCOLS.W3C;
|
||||
let innerSessionId: string;
|
||||
let registeredSessionId: string | undefined;
|
||||
let dCaps: DriverCapsWithBidiUrl;
|
||||
let dCaps: DriverCaps<AppiumDriverConstraints> & {webSocketUrl?: string | boolean};
|
||||
try {
|
||||
// Parse the caps into a format that the InnerDriver will accept
|
||||
const parsedCaps = parseCapsForInnerDriver<AppiumDriverConstraints>(
|
||||
w3cCapabilities,
|
||||
promoteAppiumOptions(w3cCapabilities),
|
||||
this.desiredCapConstraints,
|
||||
defaultCapabilities,
|
||||
defaultCapabilities ? promoteAppiumOptionsForObject(defaultCapabilities) : undefined,
|
||||
);
|
||||
|
||||
if ('error' in parsedCaps && parsedCaps.error) {
|
||||
throw parsedCaps.error;
|
||||
}
|
||||
const {desiredCaps, processedW3CCapabilities} = parsedCaps as ParsedDriverCaps<AppiumDriverConstraints>;
|
||||
const w3cSettings = pullSettings(desiredCaps);
|
||||
pullSettings(processedW3CCapabilities.alwaysMatch);
|
||||
|
||||
const {
|
||||
driver: InnerDriver,
|
||||
@@ -330,6 +330,9 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
await this.deleteAllSessions();
|
||||
}
|
||||
|
||||
let runningDriversData: DriverData[] = [];
|
||||
let otherPendingDriversData: DriverData[] = [];
|
||||
|
||||
const driverInstance = new InnerDriver(this.args, true) as unknown as ExternalDriver;
|
||||
|
||||
this.configureDriverFeatures(driverInstance, driverName);
|
||||
@@ -357,20 +360,38 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
driverInstance.serverPort = this.args.port;
|
||||
driverInstance.serverPath = this.args.basePath;
|
||||
|
||||
[innerSessionId, dCaps] = (await driverInstance.createSession(processedW3CCapabilities as never)) as [
|
||||
string,
|
||||
DriverCapsWithBidiUrl,
|
||||
];
|
||||
this.sessions[innerSessionId] = driverInstance;
|
||||
registeredSessionId = innerSessionId;
|
||||
// create an IPC channel for the driver and all plugins on this session
|
||||
this.sessionIpcs[innerSessionId] = new AppiumIpc({
|
||||
maxObjSize: this.args.maxIpcDataSize,
|
||||
maxTopics: this.args.maxIpcTopics,
|
||||
log: driverInstance.log,
|
||||
});
|
||||
const extDriver = driverInstance as unknown as IpcAssignable;
|
||||
await extDriver.assignIpc(this.sessionIpcs[innerSessionId]);
|
||||
try {
|
||||
runningDriversData = (await this.curSessionDataForDriver(InnerDriver)) ?? [];
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new errors.SessionNotCreatedError(msg);
|
||||
}
|
||||
this.pendingDrivers[InnerDriver.name] = this.pendingDrivers[InnerDriver.name] || [];
|
||||
otherPendingDriversData = compact(this.pendingDrivers[InnerDriver.name].map((drv) => drv.driverData));
|
||||
this.pendingDrivers[InnerDriver.name].push(driverInstance);
|
||||
|
||||
try {
|
||||
[innerSessionId, dCaps] = (await driverInstance.createSession(
|
||||
processedW3CCapabilities as never,
|
||||
processedW3CCapabilities,
|
||||
processedW3CCapabilities,
|
||||
[...runningDriversData, ...otherPendingDriversData],
|
||||
)) as [string, DriverCaps<AppiumDriverConstraints> & {webSocketUrl?: string | boolean}];
|
||||
this.sessions[innerSessionId] = driverInstance;
|
||||
// create an IPC channel for the driver and all plugins on this session
|
||||
this.sessionIpcs[innerSessionId] = new AppiumIpc({
|
||||
maxObjSize: this.args.maxIpcDataSize,
|
||||
maxTopics: this.args.maxIpcTopics,
|
||||
log: driverInstance.log,
|
||||
});
|
||||
const extDriver = driverInstance as unknown as IpcAssignable;
|
||||
if (typeof extDriver.assignIpc === 'function') {
|
||||
// TODO remove this existence guard as a breaking change in Appium 3
|
||||
await extDriver.assignIpc(this.sessionIpcs[innerSessionId]);
|
||||
}
|
||||
} finally {
|
||||
pull(this.pendingDrivers[InnerDriver.name], driverInstance);
|
||||
}
|
||||
|
||||
this.attachUnexpectedShutdownHandler(driverInstance, innerSessionId);
|
||||
|
||||
@@ -379,6 +400,9 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
`${innerSessionId} added to master session list`,
|
||||
);
|
||||
|
||||
// set the New Command Timeout for the inner driver
|
||||
await driverInstance.startNewCommandTimeout();
|
||||
|
||||
// apply initial values to Appium settings (if provided)
|
||||
if (driverInstance.isW3CProtocol() && !util.isEmpty(w3cSettings)) {
|
||||
this.log.info(
|
||||
@@ -394,32 +418,17 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
const {address, port, basePath} = this.args;
|
||||
const scheme = `ws${this.server.isSecure() ? 's' : ''}`;
|
||||
const host = bidiCommands.determineBiDiHost(address);
|
||||
const urlHost = net.formatHostnameForUrl(host);
|
||||
const bidiUrl = `${scheme}://${urlHost}:${port}${basePath}${BIDI_BASE_PATH}/${innerSessionId}`;
|
||||
const bidiUrl = `${scheme}://${host}:${port}${basePath}${BIDI_BASE_PATH}/${innerSessionId}`;
|
||||
this.log.info(
|
||||
`Upstream driver responded with webSocketUrl ${dCaps.webSocketUrl}, will rewrite to ` +
|
||||
`${bidiUrl} for response to client`,
|
||||
);
|
||||
// @ts-ignore webSocketUrl gets sent by the client as a boolean, but then it is supposed
|
||||
// to come back from the server as a string. TODO figure out how to express this in our
|
||||
// capability constraint system
|
||||
dCaps.webSocketUrl = bidiUrl;
|
||||
}
|
||||
|
||||
// The session becomes idle only after all initialization has completed.
|
||||
await driverInstance.startNewCommandTimeout();
|
||||
} catch (error: unknown) {
|
||||
if (registeredSessionId) {
|
||||
try {
|
||||
// A failed initialization must not leave a registered session or an idle timer,
|
||||
// even if the driver's own deleteSession also fails.
|
||||
try {
|
||||
await this.sessions[registeredSessionId]?.clearNewCommandTimeout();
|
||||
} finally {
|
||||
await this.deleteSession(registeredSessionId);
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
const message = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
|
||||
this.log.warn(`Could not clean up failed session ${registeredSessionId}: ${message}`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
protocol,
|
||||
error: error instanceof Error ? error : new Error(String(error)),
|
||||
@@ -446,9 +455,8 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
this.log.debug(`Plugin ${plugin.name} defines an unexpected shutdown handler; calling it now`);
|
||||
try {
|
||||
await plugin.onUnexpectedShutdown(driver, cause);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.log.warn(`Got an error when running plugin ${plugin.name} shutdown handler: ${message}`);
|
||||
} catch (e) {
|
||||
this.log.warn(`Got an error when running plugin ${plugin.name} shutdown handler: ${e}`);
|
||||
}
|
||||
} else {
|
||||
this.log.debug(`Plugin ${plugin.name} does not define an unexpected shutdown handler`);
|
||||
@@ -457,7 +465,6 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
}
|
||||
|
||||
this.log.info(`Removing session '${innerSessionId}' from our master session list`);
|
||||
this.cleanupBidiSockets(innerSessionId);
|
||||
this.deleteLinkedSessionObjects(innerSessionId);
|
||||
};
|
||||
|
||||
@@ -471,15 +478,42 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects `driverData` for every active session whose driver class matches `InnerDriver.name`
|
||||
* (used when creating another session of the same driver type).
|
||||
* @remarks `InnerDriver` is expected to be the driver class; only `.name` is read.
|
||||
*/
|
||||
async curSessionDataForDriver(InnerDriver: {name: string}): Promise<DriverData[]> {
|
||||
const data = compact(
|
||||
Object.values(this.sessions)
|
||||
.filter((s) => s.constructor.name === InnerDriver.name)
|
||||
.map((s) => s.driverData),
|
||||
);
|
||||
for (const datum of data) {
|
||||
if (!datum) {
|
||||
throw new Error(
|
||||
`Problem getting session data for driver type ` + `${InnerDriver.name}; does it implement 'get driverData'?`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends one session: removes it from the master list immediately, then delegates to the inner
|
||||
* driver’s `deleteSession`.
|
||||
* driver’s `deleteSession` with sibling-session metadata.
|
||||
*/
|
||||
async deleteSession(sessionId: string): Promise<SessionHandlerDeleteResult> {
|
||||
let protocol: Protocol | undefined;
|
||||
try {
|
||||
const dstSession: ExternalDriver | undefined = this.sessions[sessionId];
|
||||
if (dstSession) {
|
||||
let otherSessionsData: DriverData[] | undefined;
|
||||
let dstSession: ExternalDriver | undefined;
|
||||
if (this.sessions[sessionId]) {
|
||||
const curConstructorName = this.sessions[sessionId].constructor.name;
|
||||
otherSessionsData = Object.entries(this.sessions)
|
||||
.filter(([key, value]) => value.constructor.name === curConstructorName && key !== sessionId)
|
||||
.map(([, value]) => value.driverData);
|
||||
dstSession = this.sessions[sessionId];
|
||||
protocol = dstSession.protocol;
|
||||
this.cleanupBidiSockets(sessionId);
|
||||
}
|
||||
@@ -491,7 +525,7 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
|
||||
return {
|
||||
protocol,
|
||||
value: await dstSession.deleteSession(sessionId),
|
||||
value: await dstSession.deleteSession(sessionId, otherSessionsData),
|
||||
};
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
@@ -606,9 +640,13 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
const isUmbrellaCmd = isAppiumDriverCommand(cmd);
|
||||
const isSessionCmd = isSessionCommand(cmd);
|
||||
|
||||
// if a plugin overrode proxying for this command and that is why we are here instead of just
|
||||
// letting the protocol proxy the command entirely, get the request object for use later on
|
||||
const reqForProxy = getProxyReq();
|
||||
// if a plugin override proxying for this command and that is why we are here instead of just
|
||||
// letting the protocol proxy the command entirely, determine that, get the request object for
|
||||
// use later on, then clean up the args
|
||||
const reqForProxy = args.at(-1)?.reqForProxy;
|
||||
if (reqForProxy) {
|
||||
args.pop();
|
||||
}
|
||||
|
||||
// first do some error checking. If we're requesting a session command execution, then make
|
||||
// sure that session actually exists on the session driver, and set the session driver itself
|
||||
@@ -633,6 +671,14 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
// get any plugins which are registered as handling this command
|
||||
const plugins = this.pluginsToHandleCmd(cmd, sessionId);
|
||||
|
||||
// if any plugins are going to handle this command, we can't guarantee that the default
|
||||
// driver's executeCommand method will be called, which means we can't guarantee that the
|
||||
// newCommandTimeout will be cleared. So we do it here as well.
|
||||
if (plugins.length && dstSession) {
|
||||
this.log.debug('Clearing new command timeout pre-emptively since plugin(s) will handle this command');
|
||||
await dstSession.clearNewCommandTimeout();
|
||||
}
|
||||
|
||||
// now we define a 'cmdHandledBy' object which will keep track of which plugins have handled this
|
||||
// command. we care about this because (a) multiple plugins can handle the same command, and
|
||||
// (b) there's no guarantee that a plugin will actually call the next() method which runs the
|
||||
@@ -664,12 +710,7 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
if (!dstSession?.proxyCommand) {
|
||||
throw new NoDriverProxyCommandError();
|
||||
}
|
||||
return await dstSession.executeCommand(
|
||||
'proxyCommand',
|
||||
reqForProxy.originalUrl,
|
||||
reqForProxy.method as HTTPMethod,
|
||||
reqForProxy.body,
|
||||
);
|
||||
return await dstSession.proxyCommand(reqForProxy.originalUrl, reqForProxy.method, reqForProxy.body);
|
||||
}
|
||||
|
||||
if (isGetStatus) {
|
||||
@@ -697,18 +738,22 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
cmdHandledBy,
|
||||
next: defaultBehavior,
|
||||
});
|
||||
// clear the ambient proxy request while the plugin/default chain runs, so a plugin that
|
||||
// re-enters executeCommand for a different command doesn't inherit and misuse this one
|
||||
const execute = () => withoutProxyReq(() => this.executeWrappedCommand({wrappedCmd, protocol}));
|
||||
// Keep the timer suspended through the entire plugin chain, including work after next().
|
||||
// Plugins may handle a command themselves or continue processing after the driver returns.
|
||||
const res =
|
||||
dstSession && plugins.length
|
||||
? await runWithCommandTimeout(dstSession, execute, {restart: cmd !== DELETE_SESSION_COMMAND})
|
||||
: await execute();
|
||||
const res = await this.executeWrappedCommand({wrappedCmd, protocol});
|
||||
|
||||
// if we had plugins, make sure to log out the helpful report about which plugins ended up
|
||||
// handling the command and which didn't
|
||||
this.logPluginHandlerReport(plugins, {cmd, cmdHandledBy});
|
||||
|
||||
// if we had plugins, and if they did not ultimately call the default handler, this means our
|
||||
// new command timeout was not restarted by the default handler's executeCommand call, so
|
||||
// restart it here using the same logic as in BaseDriver's executeCommand
|
||||
if (dstSession && !cmdHandledBy.default && dstSession.isCommandsQueueEnabled && cmd !== DELETE_SESSION_COMMAND) {
|
||||
this.log.debug(
|
||||
'Restarting new command timeout via umbrella driver since plugin did not ' + 'allow default handler to execute',
|
||||
);
|
||||
await dstSession.startNewCommandTimeout();
|
||||
}
|
||||
|
||||
// And finally, if the command was createSession, we want to migrate any plugins which were
|
||||
// previously sessionless to use the new sessionId, so that plugins can share state between
|
||||
// their createSession method and other instance methods
|
||||
@@ -726,7 +771,10 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
}
|
||||
// we also want to assign the IPC channel for this session to the plugins
|
||||
const extPlugin = p as unknown as IpcAssignable;
|
||||
await extPlugin.assignIpc(this.sessionIpcs[newSessionId]);
|
||||
if (typeof extPlugin.assignIpc === 'function') {
|
||||
// TODO remove this existence guard as a breaking change in Appium 4
|
||||
await extPlugin.assignIpc(this.sessionIpcs[newSessionId]);
|
||||
}
|
||||
}
|
||||
this.sessionlessPlugins = [];
|
||||
}
|
||||
@@ -751,7 +799,7 @@ export class AppiumDriver extends DriverCore<AppiumDriverConstraints> {
|
||||
plugins: Plugin[];
|
||||
}): () => Promise<unknown> {
|
||||
if (plugins.length) {
|
||||
this.log.info(`Plugins which can handle cmd '${cmd}': ${plugins.map((p) => p.name).join(', ')}`);
|
||||
this.log.info(`Plugins which can handle cmd '${cmd}': ${plugins.map((p) => p.name)}`);
|
||||
}
|
||||
|
||||
// now we can go through each plugin and wrap `next` around its own handler, passing the *old*
|
||||
|
||||
@@ -3,9 +3,8 @@ import os from 'node:os';
|
||||
import {promisify} from 'node:util';
|
||||
|
||||
import type {ExtensionCore} from '@appium/base-driver';
|
||||
import {errors, runWithCommandTimeout} from '@appium/base-driver';
|
||||
import {fetchInterfaces, isBroadcastIp, V4_BROADCAST_IP} from '@appium/http-server';
|
||||
import {net, util} from '@appium/support';
|
||||
import {errors} from '@appium/base-driver';
|
||||
import {util} from '@appium/support';
|
||||
import type {
|
||||
BiDiResultData,
|
||||
ErrorBiDiCommandResponse,
|
||||
@@ -14,17 +13,17 @@ import type {
|
||||
StringRecord,
|
||||
SuccessBiDiCommandResponse,
|
||||
} from '@appium/types';
|
||||
import {WebSocket} from 'ws';
|
||||
import WebSocket from 'ws';
|
||||
|
||||
import type {AppiumDriver} from './appium.js';
|
||||
import {BIDI_BASE_PATH, BIDI_EVENT_NAME} from './constants.js';
|
||||
import {capitalize} from './utils/index.js';
|
||||
import type {AppiumDriver} from './appium';
|
||||
import {BIDI_BASE_PATH, BIDI_EVENT_NAME} from './constants';
|
||||
import {fetchInterfaces, isBroadcastIp, V4_BROADCAST_IP} from './helpers/network';
|
||||
import {capitalize} from './utils';
|
||||
|
||||
type ExtensionPlugin = Plugin & ExtensionCore;
|
||||
type AnyDriver = ExternalDriver | AppiumDriver;
|
||||
type SendData = (data: string | Buffer) => Promise<void>;
|
||||
type LogSocketError = (err: Error) => void;
|
||||
type PendingProxyCommands = Map<number, Set<() => void>>;
|
||||
interface InitBiDiSocketResult {
|
||||
bidiHandlerDriver: AnyDriver;
|
||||
bidiHandlerPlugins: ExtensionPlugin[];
|
||||
@@ -34,12 +33,9 @@ interface InitBiDiSocketResult {
|
||||
logSocketErr: LogSocketError;
|
||||
}
|
||||
|
||||
const {WebSocketCloseCode, MIN_APPLICATION_CLOSE_CODE, MAX_APPLICATION_CLOSE_CODE} = net;
|
||||
const RESERVED_CLOSE_CODES: readonly number[] = [
|
||||
WebSocketCloseCode.RESERVED,
|
||||
WebSocketCloseCode.NO_STATUS_RECEIVED,
|
||||
WebSocketCloseCode.ABNORMAL_CLOSURE,
|
||||
];
|
||||
const MIN_WS_CODE_VAL = 1000;
|
||||
const MAX_WS_CODE_VAL = 1015;
|
||||
const WS_FALLBACK_CODE = 1011; // server encountered an error while fulfilling request
|
||||
const BIDI_EVENTS_MAP: WeakMap<AnyDriver, Record<string, number>> = new WeakMap();
|
||||
const MAX_LOGGED_DATA_LENGTH = 300;
|
||||
|
||||
@@ -124,10 +120,7 @@ export async function onBidiMessage(
|
||||
throw new errors.InvalidArgumentError(`Missing params for BiDi operation in '${dataTruncated}`);
|
||||
}
|
||||
const executeWrappedCommand = wrapCommandWithPlugins(driver as ExtensionCore, plugins, method, params);
|
||||
const result =
|
||||
driver === this
|
||||
? await executeWrappedCommand()
|
||||
: await runWithCommandTimeout(driver as ExternalDriver, executeWrappedCommand);
|
||||
const result = await executeWrappedCommand();
|
||||
resMessage = {
|
||||
id,
|
||||
type: 'success',
|
||||
@@ -175,7 +168,8 @@ export function cleanupBidiSockets(this: AppiumDriver, sessionId: string): void
|
||||
try {
|
||||
this.log.debug(`Closing bidi socket(s) associated with session ${sessionId}`);
|
||||
for (const ws of this.bidiSockets[sessionId]) {
|
||||
ws.close(WebSocketCloseCode.GOING_AWAY);
|
||||
// 1001 means server is going away
|
||||
ws.close(1001);
|
||||
}
|
||||
} catch {}
|
||||
delete this.bidiSockets[sessionId];
|
||||
@@ -186,8 +180,8 @@ export function cleanupBidiSockets(this: AppiumDriver, sessionId: string): void
|
||||
}
|
||||
this.log.debug(`Also closing proxy connection to upstream bidi server`);
|
||||
try {
|
||||
// normal closure seems correct when Appium is acting as the client
|
||||
proxyClient.close(WebSocketCloseCode.NORMAL_CLOSURE);
|
||||
// 1000 means normal closure, which seems correct when Appium is acting as the client
|
||||
proxyClient.close(1000);
|
||||
} catch {}
|
||||
delete this.bidiProxyClients[sessionId];
|
||||
}
|
||||
@@ -341,17 +335,18 @@ function initBidiProxyHandlers(this: AnyDriver, proxyClient: WebSocket, ws: WebS
|
||||
// client as well
|
||||
proxyClient.on('close', (code, reason) => {
|
||||
driverLog.debug(
|
||||
`Upstream bidi socket closed connection (code ${code}, reason: '${reason?.toString()}'). ` +
|
||||
`Upstream bidi socket closed connection (code ${code}, reason: '${reason}'). ` +
|
||||
`Closing proxy connection to client`,
|
||||
);
|
||||
const closeCode = toSendableCloseCode(code);
|
||||
if (closeCode !== code) {
|
||||
const intCode: number = typeof code === 'number' ? (code as number) : parseInt(code, 10);
|
||||
if (Number.isNaN(intCode) || intCode < MIN_WS_CODE_VAL || intCode > MAX_WS_CODE_VAL) {
|
||||
driverLog.warn(
|
||||
`Received code ${code} from upstream socket, but this is not a valid ` +
|
||||
`websocket code. Rewriting to ${closeCode} for ws compatibility`,
|
||||
`websocket code. Rewriting to ${WS_FALLBACK_CODE} for ws compatibility`,
|
||||
);
|
||||
code = WS_FALLBACK_CODE;
|
||||
}
|
||||
ws.close(closeCode, reason);
|
||||
ws.close(code, reason);
|
||||
});
|
||||
|
||||
proxyClient.on('error', (err) => {
|
||||
@@ -385,7 +380,6 @@ function initBidiSocketHandlers(
|
||||
logSocketErr: LogSocketError,
|
||||
): void {
|
||||
const driverLog = bidiHandlerDriver.log;
|
||||
const pendingProxyCommands = trackBidiProxyCommands(proxyClient);
|
||||
// Can't do much with random errors on the connection other than log them
|
||||
ws.on('error', logSocketErr);
|
||||
|
||||
@@ -397,34 +391,29 @@ function initBidiSocketHandlers(
|
||||
// coming from the client
|
||||
// First is incoming messages from the client
|
||||
ws.on('message', async (data: Buffer) => {
|
||||
try {
|
||||
if (proxyClient && sendToProxy) {
|
||||
// if we're meant to proxy to an upstream bidi socket, just do that
|
||||
// TODO trying to determine how this proxying behaviour would interface with plugins is too
|
||||
// complex for now, so just ignore plugins in this case
|
||||
await sendBidiProxyCommand(data, bidiHandlerDriver, proxyClient, sendToProxy, pendingProxyCommands);
|
||||
} else {
|
||||
const res = await this.onBidiMessage(data, bidiHandlerDriver, bidiHandlerPlugins);
|
||||
await send(JSON.stringify(res));
|
||||
}
|
||||
} catch (err) {
|
||||
logSocketErr(err instanceof Error ? err : new Error(String(err)));
|
||||
if (proxyClient && sendToProxy) {
|
||||
// if we're meant to proxy to an upstream bidi socket, just do that
|
||||
// TODO trying to determine how this proxying behaviour would interface with plugins is too
|
||||
// complex for now, so just ignore plugins in this case
|
||||
await sendToProxy(data.toString('utf8'));
|
||||
} else {
|
||||
const res = await this.onBidiMessage(data, bidiHandlerDriver, bidiHandlerPlugins);
|
||||
await send(JSON.stringify(res));
|
||||
}
|
||||
});
|
||||
|
||||
// Next consider if the client closes the socket connection on us
|
||||
ws.on('close', (code, reason) => {
|
||||
finishBidiProxyCommands(pendingProxyCommands);
|
||||
// Not sure if we need to do anything here if the client closes the websocket connection.
|
||||
// Probably if a session was started via the socket, and the socket closes, we should end the
|
||||
// associated session to free up resources. But otherwise, for sockets attached to existing
|
||||
// sessions, doing nothing is probably right.
|
||||
driverLog.debug(`BiDi socket connection closed (code ${code}, reason: '${reason?.toString()}')`);
|
||||
driverLog.debug(`BiDi socket connection closed (code ${code}, reason: '${reason}')`);
|
||||
|
||||
// If we're proxying, might as well close the upstream connection and clean it up
|
||||
if (proxyClient) {
|
||||
driverLog.debug('Also closing BiDi proxy socket connection');
|
||||
proxyClient.close(toSendableCloseCode(code), reason);
|
||||
proxyClient.close(code, reason);
|
||||
}
|
||||
|
||||
const eventLogCounts = BIDI_EVENTS_MAP.get(bidiHandlerDriver);
|
||||
@@ -434,94 +423,6 @@ function initBidiSocketHandlers(
|
||||
});
|
||||
}
|
||||
|
||||
/** Track proxied commands until an upstream response or socket termination. */
|
||||
function trackBidiProxyCommands(proxyClient: WebSocket | null): PendingProxyCommands {
|
||||
const pendingCommands: PendingProxyCommands = new Map();
|
||||
if (!proxyClient) {
|
||||
return pendingCommands;
|
||||
}
|
||||
|
||||
// Sending a frame is not command completion. Events do not complete commands either.
|
||||
proxyClient.on('message', (data) => {
|
||||
try {
|
||||
let payload: Buffer;
|
||||
if (Array.isArray(data)) {
|
||||
payload = Buffer.concat(data);
|
||||
} else if (Buffer.isBuffer(data)) {
|
||||
payload = data;
|
||||
} else {
|
||||
payload = Buffer.from(data);
|
||||
}
|
||||
const response = JSON.parse(payload.toString());
|
||||
if (typeof response.id === 'number' && ['success', 'error'].includes(response.type)) {
|
||||
finishBidiProxyCommands(pendingCommands, response.id);
|
||||
}
|
||||
} catch {
|
||||
// Preserve opaque upstream messages; this observer only manages command activity.
|
||||
}
|
||||
});
|
||||
proxyClient.once('close', () => finishBidiProxyCommands(pendingCommands));
|
||||
proxyClient.on('error', () => finishBidiProxyCommands(pendingCommands));
|
||||
return pendingCommands;
|
||||
}
|
||||
|
||||
/** Forward a command while keeping the idle timer suspended until its response arrives. */
|
||||
async function sendBidiProxyCommand(
|
||||
data: Buffer,
|
||||
driver: AnyDriver,
|
||||
proxyClient: WebSocket,
|
||||
sendToProxy: SendData,
|
||||
pendingCommands: PendingProxyCommands,
|
||||
): Promise<void> {
|
||||
await runWithCommandTimeout(driver as ExternalDriver, async () => {
|
||||
let id: number | undefined;
|
||||
try {
|
||||
const command = JSON.parse(data.toString());
|
||||
if (typeof command.id === 'number') {
|
||||
id = command.id;
|
||||
}
|
||||
} catch {
|
||||
// The upstream server is responsible for rejecting malformed commands.
|
||||
}
|
||||
let response: Promise<void> | undefined;
|
||||
if (id !== undefined) {
|
||||
response = new Promise<void>((resolve) => {
|
||||
const pending = pendingCommands.get(id) ?? new Set();
|
||||
pending.add(resolve);
|
||||
pendingCommands.set(id, pending);
|
||||
});
|
||||
}
|
||||
await sendToProxy(data.toString('utf8'));
|
||||
if (proxyClient.readyState !== WebSocket.OPEN) {
|
||||
finishBidiProxyCommands(pendingCommands);
|
||||
}
|
||||
await response;
|
||||
});
|
||||
}
|
||||
|
||||
/** Release one activity guard per response, or every guard on a terminated connection. */
|
||||
function finishBidiProxyCommands(pendingCommands: PendingProxyCommands, id?: number): void {
|
||||
if (id !== undefined) {
|
||||
const pending = pendingCommands.get(id);
|
||||
const finish = pending?.values().next().value;
|
||||
if (pending && finish) {
|
||||
// BiDi IDs are not necessarily unique. One response completes only one command.
|
||||
pending.delete(finish);
|
||||
if (pending.size === 0) {
|
||||
pendingCommands.delete(id);
|
||||
}
|
||||
finish();
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (const key of pendingCommands.keys()) {
|
||||
for (const finish of pendingCommands.get(key) ?? []) {
|
||||
finish();
|
||||
}
|
||||
pendingCommands.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set up bidi event listeners
|
||||
*
|
||||
@@ -582,24 +483,18 @@ function initBidiEventListeners(
|
||||
return;
|
||||
}
|
||||
|
||||
const moduleName = method.split('.')[0];
|
||||
const isSubscribed = [method, moduleName].some((event) => {
|
||||
const contexts = bidiHandlerDriver.bidiEventSubs[event];
|
||||
return Array.isArray(contexts) && (contexts.includes('') || contexts.includes(context));
|
||||
});
|
||||
if (isSubscribed) {
|
||||
const eventSubs = bidiHandlerDriver.bidiEventSubs[method];
|
||||
if (Array.isArray(eventSubs) && eventSubs.includes(context)) {
|
||||
if (method in eventLogCounts) {
|
||||
++eventLogCounts[method];
|
||||
} else {
|
||||
// must be set before logging: the log line may synchronously come back here as another event
|
||||
// of the same method (e.g. drivers forward server logs as log.entryAdded with get_server_logs)
|
||||
eventLogCounts[method] = 1;
|
||||
ext.log?.debug(
|
||||
// some old plugins might not have the `log` property
|
||||
`<-- BIDI EVENT ${method} (context: '${context}', ` +
|
||||
`params: ${util.truncateString(JSON.stringify(params), {length: MAX_LOGGED_DATA_LENGTH})}). ` +
|
||||
`All further similar events won't be logged.`,
|
||||
);
|
||||
eventLogCounts[method] = 1;
|
||||
}
|
||||
// now we can send the event onto the socket
|
||||
const ev = {type: 'event', context, method, params};
|
||||
@@ -651,17 +546,4 @@ async function assertIsOpen(ws: WebSocket, timeoutMs: number = 5000): Promise<We
|
||||
return ws;
|
||||
}
|
||||
|
||||
/**
|
||||
* 'close' events can report reserved codes like 1005 and 1006, which RFC 6455 forbids in a close
|
||||
* frame and ws throws on, so anything ws would reject is replaced with an internal error
|
||||
*/
|
||||
function toSendableCloseCode(code: number): number {
|
||||
const isStandard =
|
||||
code >= WebSocketCloseCode.NORMAL_CLOSURE &&
|
||||
code <= WebSocketCloseCode.BAD_GATEWAY &&
|
||||
!RESERVED_CLOSE_CODES.includes(code);
|
||||
const isApplication = code >= MIN_APPLICATION_CLOSE_CODE && code <= MAX_APPLICATION_CLOSE_CODE;
|
||||
return isStandard || isApplication ? code : WebSocketCloseCode.INTERNAL_ERROR;
|
||||
}
|
||||
|
||||
// #endregion
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {console as supportConsole, util} from '@appium/support';
|
||||
import {env, util} from '@appium/support';
|
||||
import type {DriverOpts} from '@appium/types';
|
||||
import type {
|
||||
Args,
|
||||
@@ -7,32 +7,31 @@ import type {
|
||||
CliCommandSetupSubcommand,
|
||||
CliExtensionSubcommand,
|
||||
ParsedArgs,
|
||||
} from 'appium/types/index.js';
|
||||
} from 'appium/types';
|
||||
|
||||
import {AppiumDriver, type AppiumDriverConstraints} from '../appium.js';
|
||||
import {injectAppiumSymlinks} from '../cli/extension-command.js';
|
||||
import {runExtensionCommand} from '../cli/extension.js';
|
||||
import {ArgParser, getParser} from '../cli/parser.js';
|
||||
import {runSetupCommand} from '../cli/setup-command.js';
|
||||
import {SERVER_SUBCOMMAND} from '../constants.js';
|
||||
import {type ExtensionConfigs, loadExtensions} from '../extension/index.js';
|
||||
import {log as logger} from '../logger.js';
|
||||
import {init as logsinkInit} from '../logsink.js';
|
||||
import type {ErrorObject} from '../schema/ajv.js';
|
||||
import {AppiumDriver, type AppiumDriverConstraints} from '../appium';
|
||||
import {runExtensionCommand} from '../cli/extension';
|
||||
import {injectAppiumSymlinks} from '../cli/extension-command';
|
||||
import {ArgParser, getParser} from '../cli/parser';
|
||||
import {runSetupCommand} from '../cli/setup-command';
|
||||
import {SERVER_SUBCOMMAND} from '../constants';
|
||||
import {type ExtensionConfigs, loadExtensions} from '../extension';
|
||||
import {log as logger} from '../logger';
|
||||
import {init as logsinkInit} from '../logsink';
|
||||
import {
|
||||
isDriverCommandArgs,
|
||||
isExtensionCommandArgs,
|
||||
isPluginCommandArgs,
|
||||
isServerCommandArgs,
|
||||
isSetupCommandArgs,
|
||||
} from '../schema/cli-args-guards.js';
|
||||
import {getDefaultsForSchema} from '../schema/schema.js';
|
||||
import {defaultsDeep, resolveAppiumHome} from '../utils/index.js';
|
||||
import {readConfigFile} from './config-file.js';
|
||||
import type {InitResult, PreConfigArgs} from './init-types.js';
|
||||
import {determineAppiumHomeSource, preflightChecks} from './main-helpers.js';
|
||||
import {adjustNodePath, requireDir, showDebugInfo} from './node-helpers.js';
|
||||
import {getNonDefaultServerArgs, showConfig} from './startup-config.js';
|
||||
} from '../schema/cli-args-guards';
|
||||
import {getDefaultsForSchema} from '../schema/schema';
|
||||
import {defaultsDeep} from '../utils';
|
||||
import {readConfigFile} from './config-file';
|
||||
import type {InitResult, PreConfigArgs} from './init-types';
|
||||
import {determineAppiumHomeSource, preflightChecks} from './main-helpers';
|
||||
import {adjustNodePath, requireDir, showDebugInfo} from './node-helpers';
|
||||
import {getNonDefaultServerArgs, showConfig} from './startup-config';
|
||||
|
||||
/**
|
||||
* Parses CLI/programmatic args, loads config and extensions, and returns server-ready state or runs extension/setup flows.
|
||||
@@ -52,7 +51,7 @@ export class AppiumInitializer {
|
||||
>(args?: Args<Cmd, SubCmd>): Promise<InitResult<Cmd>> {
|
||||
this.throwInsteadOfExit = false;
|
||||
|
||||
const appiumHome = args?.appiumHome ?? (await resolveAppiumHome());
|
||||
const appiumHome = args?.appiumHome ?? (await env.resolveAppiumHome());
|
||||
const appiumHomeSourceName = determineAppiumHomeSource(args?.appiumHome);
|
||||
await requireDir(appiumHome, false, appiumHomeSourceName);
|
||||
|
||||
@@ -78,7 +77,6 @@ export class AppiumInitializer {
|
||||
}
|
||||
|
||||
if (isSetupCommandArgs(preConfigArgs)) {
|
||||
this.printValidationSummaries(driverConfig, pluginConfig);
|
||||
await runSetupCommand(preConfigArgs, driverConfig, pluginConfig);
|
||||
return {} as InitResult<Cmd>;
|
||||
}
|
||||
@@ -113,16 +111,9 @@ export class AppiumInitializer {
|
||||
|
||||
private assertConfigFileOk(configResult: Awaited<ReturnType<typeof readConfigFile>>): void {
|
||||
if (!util.isEmpty(configResult.errors)) {
|
||||
let errorsListString: string;
|
||||
if (configResult.reason) {
|
||||
errorsListString =
|
||||
typeof configResult.reason !== 'string'
|
||||
? configResult.reason.map((r) => r.error).join(', ')
|
||||
: configResult.reason;
|
||||
} else {
|
||||
errorsListString = (configResult.errors as ErrorObject[])?.map((e) => e.message).join(', ');
|
||||
}
|
||||
throw new Error(`Errors in config file ${configResult.filepath}:\n ${errorsListString}`);
|
||||
throw new Error(
|
||||
`Errors in config file ${configResult.filepath}:\n ${configResult.reason ?? configResult.errors}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,7 +135,6 @@ export class AppiumInitializer {
|
||||
|
||||
if (preConfigArgs.showConfig) {
|
||||
showConfig(getNonDefaultServerArgs(preConfigArgs as Args), configResult, defaults, serverArgs);
|
||||
this.printValidationSummaries(driverConfig, pluginConfig);
|
||||
return {} as InitResult<Cmd>;
|
||||
}
|
||||
|
||||
@@ -154,13 +144,10 @@ export class AppiumInitializer {
|
||||
pluginConfig,
|
||||
appiumHome,
|
||||
});
|
||||
this.printValidationSummaries(driverConfig, pluginConfig);
|
||||
return {} as InitResult<Cmd>;
|
||||
}
|
||||
|
||||
await logsinkInit(serverArgs);
|
||||
// Deferred from loadExtensions() so these render through the now-active (Winston-backed) logger.
|
||||
this.printValidationSummaries(driverConfig, pluginConfig);
|
||||
await this.applyLogFilters(serverArgs);
|
||||
|
||||
if (!serverArgs.noPermsCheck) {
|
||||
@@ -180,15 +167,6 @@ export class AppiumInitializer {
|
||||
} as InitResult<Cmd>;
|
||||
}
|
||||
|
||||
/** Renders each config's pending `loadExtensions()`-time validation summary via the raw logger. */
|
||||
private printValidationSummaries(
|
||||
driverConfig: ExtensionConfigs['driverConfig'],
|
||||
pluginConfig: ExtensionConfigs['pluginConfig'],
|
||||
): void {
|
||||
driverConfig.printValidationSummary(logger);
|
||||
pluginConfig.printValidationSummary(logger);
|
||||
}
|
||||
|
||||
private async applyLogFilters(serverArgs: ParsedArgs<CliCommandServer>): Promise<void> {
|
||||
if (!serverArgs.logFilters) {
|
||||
return;
|
||||
@@ -223,10 +201,7 @@ export class AppiumInitializer {
|
||||
if (isDriverCommandArgs(preConfigArgs) || isPluginCommandArgs(preConfigArgs)) {
|
||||
const cmd = isDriverCommandArgs(preConfigArgs) ? preConfigArgs.driverCommand : preConfigArgs.pluginCommand;
|
||||
if (cmd === 'install') {
|
||||
// Match the same command's own console so a non-fatal symlink error never lands on
|
||||
// STDOUT under `--json` (unlike the raw npmlog logger, which isn't JSON-mode-aware).
|
||||
const symlinkLog = new supportConsole.CliConsole({jsonMode: Boolean(preConfigArgs.json)});
|
||||
await injectAppiumSymlinks(driverConfig, pluginConfig, symlinkLog);
|
||||
await injectAppiumSymlinks(driverConfig, pluginConfig, logger);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,30 @@
|
||||
import type {ServerOpts} from '@appium/http-server';
|
||||
import net from 'node:net';
|
||||
|
||||
import type {ServerOpts} from '@appium/base-driver';
|
||||
import {util} from '@appium/support';
|
||||
import type {AppiumServer} from '@appium/types';
|
||||
import type {
|
||||
Args,
|
||||
CliCommand,
|
||||
CliCommandServer,
|
||||
CliCommandSetupSubcommand,
|
||||
CliExtensionSubcommand,
|
||||
} from 'appium/types/index.js';
|
||||
import type {Args, CliCommand, CliCommandServer, CliCommandSetupSubcommand, CliExtensionSubcommand} from 'appium/types';
|
||||
|
||||
import {getActiveDrivers, getActivePlugins} from '../extension/index.js';
|
||||
import {log as logger} from '../logger.js';
|
||||
import type {InitResult, ServerInitData} from './init-types.js';
|
||||
import {buildServerOpts, createAppiumServer, determineAppiumHomeSource, logStartupInfo} from './main-helpers.js';
|
||||
import {getActiveDrivers, getActivePlugins} from '../extension';
|
||||
import {log as logger} from '../logger';
|
||||
import registerNode from './grid-v3-register';
|
||||
import type {InitResult, ServerInitData} from './init-types';
|
||||
import {
|
||||
buildServerOpts,
|
||||
createAppiumServer,
|
||||
determineAppiumHomeSource,
|
||||
logServerAddress,
|
||||
logStartupInfo,
|
||||
} from './main-helpers';
|
||||
|
||||
const MAX_SERVER_PROCESS_LISTENERS = 100;
|
||||
|
||||
/**
|
||||
* Starts the Appium HTTP server after {@link AppiumInitializer.init}: loads drivers/plugins, binds, signals.
|
||||
* Starts the Appium HTTP server after {@link AppiumInitializer.init}: loads drivers/plugins, binds, grid register, signals.
|
||||
*/
|
||||
export class AppiumMainRunner {
|
||||
/**
|
||||
* For server init: builds listeners and returns the server.
|
||||
* For server init: builds listeners, registers with Grid 3 if configured, and returns the server.
|
||||
* For non-server commands, `initResult` is empty and this resolves to `undefined`.
|
||||
*
|
||||
* @param initResult - Output of {@link AppiumInitializer.init}
|
||||
@@ -52,8 +55,6 @@ export class AppiumMainRunner {
|
||||
await logStartupInfo(parsedArgs);
|
||||
|
||||
appiumDriver.configureGlobalFeatures();
|
||||
// the rules are enforced by the shared app download helper of every driver
|
||||
appiumDriver.helpers.setAppUrlRules(parsedArgs.appUrlRules);
|
||||
|
||||
const appiumHomeSourceName = determineAppiumHomeSource(args?.appiumHome);
|
||||
logger.debug(`The ${appiumHomeSourceName}: ${appiumHome}`);
|
||||
@@ -70,10 +71,12 @@ export class AppiumMainRunner {
|
||||
return undefined as Cmd extends CliCommandServer ? AppiumServer : void;
|
||||
}
|
||||
|
||||
this.warnIfCorsEnabled(serverOpts);
|
||||
this.warnIfCorsEnabled(parsedArgs);
|
||||
appiumDriver.server = server;
|
||||
|
||||
await this.registerGridOrClose(server, parsedArgs, normalizedBasePath);
|
||||
this.attachSignalHandlers(appiumDriver, server);
|
||||
this.logListeningUrl(server, parsedArgs, normalizedBasePath);
|
||||
|
||||
driverConfig.print();
|
||||
pluginConfig.print([...pluginClasses.values()]);
|
||||
@@ -101,8 +104,8 @@ export class AppiumMainRunner {
|
||||
}
|
||||
}
|
||||
|
||||
private warnIfCorsEnabled(serverOpts: ServerOpts): void {
|
||||
if (serverOpts.allowCors) {
|
||||
private warnIfCorsEnabled(parsedArgs: ServerInitData['parsedArgs']): void {
|
||||
if (parsedArgs.allowCors) {
|
||||
logger.warn(
|
||||
'You have enabled CORS requests from any host. Be careful not ' +
|
||||
'to visit sites which could maliciously try to start Appium ' +
|
||||
@@ -111,6 +114,21 @@ export class AppiumMainRunner {
|
||||
}
|
||||
}
|
||||
|
||||
private async registerGridOrClose(
|
||||
server: AppiumServer,
|
||||
parsedArgs: ServerInitData['parsedArgs'],
|
||||
normalizedBasePath: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
if (parsedArgs.nodeconfig) {
|
||||
await registerNode(parsedArgs.nodeconfig, parsedArgs.address, parsedArgs.port, normalizedBasePath);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
await server.close();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
private attachSignalHandlers(appiumDriver: ServerInitData['appiumDriver'], server: AppiumServer): void {
|
||||
process.setMaxListeners(MAX_SERVER_PROCESS_LISTENERS);
|
||||
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
|
||||
@@ -127,4 +145,14 @@ export class AppiumMainRunner {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private logListeningUrl(
|
||||
server: AppiumServer,
|
||||
parsedArgs: ServerInitData['parsedArgs'],
|
||||
normalizedBasePath: string,
|
||||
): void {
|
||||
const protocol = server.isSecure() ? 'https' : 'http';
|
||||
const address = net.isIPv6(parsedArgs.address) ? `[${parsedArgs.address}]` : parsedArgs.address;
|
||||
logServerAddress(`${protocol}://${address}:${parsedArgs.port}${normalizedBasePath}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import {util} from '@appium/support';
|
||||
import type {AppiumConfig, NormalizedAppiumConfig} from '@appium/types';
|
||||
import type {IOutputError} from '@sidvind/better-ajv-errors';
|
||||
import type {ErrorObject, SchemaObject} from 'ajv';
|
||||
import {lilconfig, type LilconfigResult, type LoaderSync} from 'lilconfig';
|
||||
import * as yaml from 'yaml';
|
||||
|
||||
import type {ErrorObject, SchemaObject} from '../schema/ajv.js';
|
||||
import {formatErrors} from '../schema/format-errors.js';
|
||||
import {getSchema, validate} from '../schema/schema.js';
|
||||
import {camelCase, getPath, mapKeys, mapValues} from '../utils/index.js';
|
||||
import {formatErrors} from '../schema/format-errors';
|
||||
import {getSchema, validate} from '../schema/schema';
|
||||
import {camelCase, getPath, mapKeys, mapValues} from '../utils';
|
||||
|
||||
/**
|
||||
* A cache of the raw config file (a JSON string) at a filepath.
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import {fs} from '@appium/support';
|
||||
import type {StringRecord} from '@appium/types';
|
||||
import axios from 'axios';
|
||||
|
||||
import {log as logger} from '../logger';
|
||||
|
||||
/**
|
||||
* Selenium **Grid 3** (legacy hub) node integration.
|
||||
*
|
||||
* Registers this Appium process as a node with a Selenium Grid 3 hub using the classic
|
||||
* `/grid/register` endpoint and `/grid/api/proxy` for re-registration checks.
|
||||
* This does **not** apply to Selenium Grid 4 (which uses a different topology and APIs).
|
||||
*
|
||||
* @see https://www.selenium.dev/documentation/legacy/grid_3/
|
||||
*/
|
||||
|
||||
/** REST paths exposed by a Selenium Grid 3 hub. */
|
||||
const GRID_V3_REGISTER_PATH = '/grid/register';
|
||||
const GRID_V3_PROXY_API_PATH = '/grid/api/proxy';
|
||||
|
||||
interface Grid3HubConfiguration {
|
||||
hubProtocol?: string;
|
||||
hubHost?: string;
|
||||
hubPort?: number;
|
||||
url?: string;
|
||||
host?: string;
|
||||
port?: number;
|
||||
id?: string;
|
||||
register?: boolean;
|
||||
registerCycle?: number;
|
||||
}
|
||||
|
||||
interface Grid3NodeConfig extends StringRecord {
|
||||
configuration?: Grid3HubConfiguration;
|
||||
capabilities?: unknown;
|
||||
}
|
||||
|
||||
interface Grid3ProxyApiResponse {
|
||||
success: boolean;
|
||||
msg?: string;
|
||||
}
|
||||
|
||||
export default async function registerNode(data: string, addr: string, port: number, basePath: string): Promise<void>;
|
||||
export default async function registerNode(
|
||||
data: Grid3NodeConfig,
|
||||
addr?: string,
|
||||
port?: number,
|
||||
basePath?: string,
|
||||
): Promise<void>;
|
||||
/**
|
||||
* Registers this server as a node with a **Selenium Grid 3** hub.
|
||||
*
|
||||
* When `data` is a path to a JSON config file, `addr`, `port`, and `basePath` are required (they define
|
||||
* how the hub reaches this Appium server). When `data` is an inline config object, those parameters are
|
||||
* optional and only used to fill missing node URL fields in the config.
|
||||
*
|
||||
* @deprecated Selenium Grid 3 registration is legacy and slated for removal.
|
||||
* Use Selenium Grid 4 integration (node relay) instead.
|
||||
*
|
||||
* @param data - Path to a JSON file or an inline parsed config object
|
||||
* @param addr - Bind to this address
|
||||
* @param port - Bind to this port
|
||||
* @param basePath - Base path for the Appium server (used in the node URL sent to the hub; may be `''`)
|
||||
*/
|
||||
export default async function registerNode(
|
||||
data: string | Grid3NodeConfig,
|
||||
addr?: string,
|
||||
port?: number,
|
||||
basePath?: string,
|
||||
): Promise<void> {
|
||||
if (typeof data === 'string') {
|
||||
if (addr === undefined || port === undefined || basePath === undefined) {
|
||||
throw logger.errorWithException(
|
||||
'When the first argument is a Selenium Grid 3 node config file path, address, port, and basePath ' +
|
||||
'are required (e.g. match your Appium `--address`, `--port`, and base path).',
|
||||
);
|
||||
}
|
||||
if (typeof port !== 'number' || !Number.isFinite(port)) {
|
||||
throw logger.errorWithException('When registering from a node config file path, port must be a finite number.');
|
||||
}
|
||||
}
|
||||
|
||||
let configHolder: Grid3NodeConfig;
|
||||
if (typeof data === 'string') {
|
||||
const configFilePath = data;
|
||||
let fileContent: string;
|
||||
try {
|
||||
fileContent = await fs.readFile(data, 'utf-8');
|
||||
} catch (err) {
|
||||
logger.error(
|
||||
`Unable to load Selenium Grid 3 node configuration file ${configFilePath} to ` +
|
||||
`register with the hub: ${(err as Error).message}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
configHolder = JSON.parse(fileContent) as Grid3NodeConfig;
|
||||
} catch (err) {
|
||||
throw logger.errorWithException(
|
||||
`Syntax error in Selenium Grid 3 node configuration file ${configFilePath}: ` + (err as Error).message,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
configHolder = data;
|
||||
}
|
||||
|
||||
postRequest(configHolder, addr, port, basePath);
|
||||
}
|
||||
|
||||
/** Base URL for the Selenium Grid 3 hub (protocol + host + port). */
|
||||
function hubUri(config: Grid3HubConfiguration): string {
|
||||
const protocol = config.hubProtocol || 'http';
|
||||
return `${protocol}://${config.hubHost}:${config.hubPort}`;
|
||||
}
|
||||
|
||||
/** POST registration payload to the Selenium Grid 3 hub. */
|
||||
async function registerToGrid(
|
||||
postOptions: {url: string; method: string; data: Grid3NodeConfig},
|
||||
configHolder: Grid3NodeConfig,
|
||||
): Promise<void> {
|
||||
const hubCfg = configHolder.configuration;
|
||||
if (!hubCfg) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const {status} = await axios(postOptions);
|
||||
if (status !== 200) {
|
||||
throw new Error(`Request failed with code ${status}`);
|
||||
}
|
||||
logger.debug(`Appium successfully registered with the Selenium Grid 3 hub at ` + hubUri(hubCfg));
|
||||
} catch (err) {
|
||||
logger.error(`An attempt to register with the Selenium Grid 3 hub was unsuccessful: ` + (err as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
function postRequest(configHolder: Grid3NodeConfig, addr?: string, port?: number, basePath?: string): void {
|
||||
// Move Selenium Grid 3 (flat) configuration properties into `configuration`
|
||||
if (configHolder != null && typeof configHolder === 'object' && !Object.hasOwn(configHolder, 'configuration')) {
|
||||
const configuration: StringRecord = {};
|
||||
const holder = configHolder as StringRecord;
|
||||
for (const property of Object.keys(holder)) {
|
||||
if (property !== 'capabilities') {
|
||||
configuration[property] = holder[property];
|
||||
delete holder[property];
|
||||
}
|
||||
}
|
||||
holder.configuration = configuration as Grid3HubConfiguration;
|
||||
}
|
||||
|
||||
const cfg = configHolder.configuration;
|
||||
if (!cfg) {
|
||||
return;
|
||||
}
|
||||
|
||||
// if the node config does not have the appium/webdriver url, host, and port,
|
||||
// automatically add it based on how appium was initialized
|
||||
// otherwise, we will take whatever the user setup
|
||||
// because we will always set localhost/127.0.0.1. this won't work if your
|
||||
// node and hub aren't in the same place
|
||||
if (!cfg.url || !cfg.host || !cfg.port) {
|
||||
cfg.url = `http://${addr}:${port}${basePath}`;
|
||||
cfg.host = addr;
|
||||
cfg.port = port;
|
||||
}
|
||||
// if the node config does not have id automatically add it
|
||||
if (!cfg.id) {
|
||||
cfg.id = `http://${cfg.host}:${cfg.port}`;
|
||||
}
|
||||
|
||||
// the post options
|
||||
const regRequest = {
|
||||
url: `${hubUri(cfg)}${GRID_V3_REGISTER_PATH}`,
|
||||
method: 'POST',
|
||||
data: configHolder,
|
||||
};
|
||||
|
||||
if (cfg.register !== true) {
|
||||
logger.debug(`No Selenium Grid 3 hub registration sent (${cfg.register} = false)`);
|
||||
return;
|
||||
}
|
||||
|
||||
const registerCycleInterval = cfg.registerCycle;
|
||||
if (registerCycleInterval === undefined || isNaN(registerCycleInterval) || registerCycleInterval <= 0) {
|
||||
logger.warn(
|
||||
`'registerCycle' is not a valid positive number. ` +
|
||||
`No registration request will be sent to the Selenium Grid 3 hub.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
// initiate a new Thread
|
||||
let first = true;
|
||||
logger.debug(
|
||||
`Starting auto-register thread for Selenium Grid 3. ` + `Will try to register every ${registerCycleInterval} ms.`,
|
||||
);
|
||||
setInterval(async function registerRetry() {
|
||||
if (first) {
|
||||
first = false;
|
||||
await registerToGrid(regRequest, configHolder);
|
||||
} else if (!(await isAlreadyRegistered(configHolder))) {
|
||||
// make the http POST to the Selenium Grid 3 hub for registration
|
||||
await registerToGrid(regRequest, configHolder);
|
||||
}
|
||||
}, registerCycleInterval);
|
||||
}
|
||||
|
||||
/** Query the Selenium Grid 3 hub to see if this node id is already registered. */
|
||||
async function isAlreadyRegistered(configHolder: Grid3NodeConfig): Promise<boolean | undefined> {
|
||||
// check if node is already registered
|
||||
const hubCfg = configHolder.configuration;
|
||||
if (!hubCfg?.id) {
|
||||
return;
|
||||
}
|
||||
const id = hubCfg.id;
|
||||
try {
|
||||
const {data, status} = await axios<Grid3ProxyApiResponse>({
|
||||
url: `${hubUri(hubCfg)}${GRID_V3_PROXY_API_PATH}`,
|
||||
params: {id},
|
||||
timeout: 10000,
|
||||
});
|
||||
if (status !== 200) {
|
||||
throw new Error(`Request failed with code ${status}`);
|
||||
}
|
||||
if (!data.success) {
|
||||
// if register fail, print the debug msg
|
||||
logger.debug(`Selenium Grid 3 hub registration check: ${data.msg}`);
|
||||
}
|
||||
return data.success;
|
||||
} catch (err) {
|
||||
logger.debug(`Selenium Grid 3 hub down or not responding: ${(err as Error).message}`);
|
||||
}
|
||||
}
|
||||
@@ -5,10 +5,10 @@ import type {
|
||||
CliCommandSetupSubcommand,
|
||||
CliExtensionSubcommand,
|
||||
ParsedArgs,
|
||||
} from 'appium/types/index.js';
|
||||
} from 'appium/types';
|
||||
|
||||
import type {AppiumDriver} from '../appium.js';
|
||||
import type {ExtensionConfigs} from '../extension/index.js';
|
||||
import type {AppiumDriver} from '../appium';
|
||||
import type {ExtensionConfigs} from '../extension';
|
||||
|
||||
/** Empty object returned when `init` completes for non-server CLI flows (extension/setup). */
|
||||
export type ExtCommandInitResult = Record<string, never>;
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
import type {NetworkInterfaceInfo} from 'node:os';
|
||||
import {inspect as dump, type InspectOptions} from 'node:util';
|
||||
|
||||
import {routeConfiguringFunction as makeRouter} from '@appium/base-driver';
|
||||
import {normalizeBasePath, server as baseServer} from '@appium/http-server';
|
||||
import type {ServerOpts} from '@appium/http-server';
|
||||
import {
|
||||
normalizeBasePath,
|
||||
routeConfiguringFunction as makeRouter,
|
||||
server as baseServer,
|
||||
type ServerOpts,
|
||||
} from '@appium/base-driver';
|
||||
import {console as supportConsole, util} from '@appium/support';
|
||||
import type {AppiumServer, Driver, MethodMap, UpdateServerCallback} from '@appium/types';
|
||||
import type {Args, CliCommandServer, ParsedArgs} from 'appium/types/index.js';
|
||||
import type {Args, CliCommandServer, ParsedArgs} from 'appium/types';
|
||||
import {WebSocketServer} from 'ws';
|
||||
|
||||
import type {AppiumDriver} from '../appium.js';
|
||||
import {BIDI_BASE_PATH, CORS_FEATURE, LONG_STACKTRACE_LIMIT} from '../constants.js';
|
||||
import type {DriverNameMap, PluginNameMap} from '../extension/index.js';
|
||||
import {APPIUM_VER, getBuildInfo, getGitRev, updateBuildInfo} from '../helpers/build.js';
|
||||
import {log as logger} from '../logger.js';
|
||||
import {validate as validateSchema} from '../schema/schema.js';
|
||||
import {checkNodeOk, requireDir} from './node-helpers.js';
|
||||
import {getNonDefaultServerArgs} from './startup-config.js';
|
||||
import type {AppiumDriver} from '../appium';
|
||||
import {BIDI_BASE_PATH, LONG_STACKTRACE_LIMIT} from '../constants';
|
||||
import type {DriverNameMap, PluginNameMap} from '../extension';
|
||||
import {APPIUM_VER, getBuildInfo, getGitRev, updateBuildInfo} from '../helpers/build';
|
||||
import {fetchInterfaces, isBroadcastIp, V4_BROADCAST_IP} from '../helpers/network';
|
||||
import {log as logger} from '../logger';
|
||||
import {validate as validateSchema} from '../schema/schema';
|
||||
import {checkNodeOk, requireDir} from './node-helpers';
|
||||
import {getNonDefaultServerArgs} from './startup-config';
|
||||
|
||||
const isStdoutTTY = process.stdout.isTTY;
|
||||
|
||||
@@ -57,6 +62,28 @@ export function determineAppiumHomeSource(appiumHomeFromArgs?: string | null): s
|
||||
return 'autodetected Appium home path';
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs the REST listener URL; if the bind address is a broadcast address, lists concrete interface URLs.
|
||||
*/
|
||||
export function logServerAddress(url: string): void {
|
||||
const urlObj = new URL(url);
|
||||
logger.info(`Appium REST http interface listener started on ${url}`);
|
||||
if (!isBroadcastIp(urlObj.hostname)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const interfaces = fetchInterfaces(urlObj.hostname === V4_BROADCAST_IP ? 4 : 6);
|
||||
const toLabel = (iface: NetworkInterfaceInfo) => {
|
||||
const href = urlObj.href.replace(urlObj.hostname, iface.address);
|
||||
return iface.internal ? `${href} (only accessible from the same host)` : href;
|
||||
};
|
||||
logger.info(
|
||||
`You can provide the following ${interfaces.length === 1 ? 'URL' : 'URLs'} ` +
|
||||
`in your client code to connect to this server:\n` +
|
||||
interfaces.map((iface) => `\t${toLabel(iface)}`).join('\n'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates Node version, optional long stack traces, schema, tmp dir, and `--build-info` early exit.
|
||||
*
|
||||
@@ -126,7 +153,7 @@ export function getExtraMethodMap(driverClasses: DriverNameMap, pluginClasses: P
|
||||
return [...driverClasses.keys(), ...pluginClasses.keys()].reduce<MethodMap<Driver>>(
|
||||
(map, klass) => ({
|
||||
...map,
|
||||
...klass.newMethodMap,
|
||||
...(klass.newMethodMap ?? {}),
|
||||
}),
|
||||
{},
|
||||
);
|
||||
@@ -146,7 +173,7 @@ export function buildServerOpts(
|
||||
routeConfiguringFunction,
|
||||
port: parsedArgs.port,
|
||||
hostname: parsedArgs.address,
|
||||
allowCors: appiumDriver.isFeatureEnabled(CORS_FEATURE),
|
||||
allowCors: parsedArgs.allowCors,
|
||||
basePath: parsedArgs.basePath,
|
||||
serverUpdaters: getServerUpdaters(driverClasses, pluginClasses),
|
||||
extraMethodMap: getExtraMethodMap(driverClasses, pluginClasses),
|
||||
@@ -179,18 +206,9 @@ export async function createAppiumServer(
|
||||
return server;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server args whose values describe the server's internal network and must not leak to clients
|
||||
* via server logs
|
||||
*/
|
||||
const SENSITIVE_ARGS: ReadonlySet<keyof Args> = new Set(['appUrlRules']);
|
||||
|
||||
function logNonDefaultArgsWarning(args: Args): void {
|
||||
const shownArgs = Object.fromEntries(
|
||||
Object.entries(args).map(([name, value]) => [name, SENSITIVE_ARGS.has(name as keyof Args) ? '<redacted>' : value]),
|
||||
);
|
||||
logger.info('Non-default server args:');
|
||||
inspect(shownArgs);
|
||||
inspect(args);
|
||||
}
|
||||
|
||||
function logDefaultCapabilitiesWarning(caps: ParsedArgs<CliCommandServer>['defaultCapabilities']): void {
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
import {Module} from 'node:module';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
/* eslint-disable no-console */
|
||||
import {fs, system} from '@appium/support';
|
||||
import {fs, npm, system} from '@appium/support';
|
||||
import * as semver from 'semver';
|
||||
|
||||
import {getBuildInfo, updateBuildInfo} from '../helpers/build.js';
|
||||
import {appiumPackageRoot, npm, npmPackage} from '../utils/index.js';
|
||||
import {getBuildInfo, updateBuildInfo} from '../helpers/build';
|
||||
import {appiumPackageRoot, npmPackage} from '../utils';
|
||||
|
||||
const MIN_NODE_VERSION = (npmPackage.engines as Record<string, string>).node;
|
||||
|
||||
interface ModuleWithInitPaths {
|
||||
_initPaths(): void;
|
||||
interface NodeModuleWithInitPaths {
|
||||
Module: {_initPaths(): void};
|
||||
}
|
||||
|
||||
interface DebugInfoInput {
|
||||
@@ -32,19 +31,15 @@ export function checkNodeOk(): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjusts NODE_PATH so CJS drivers/plugins can load peer deps. Does not help ESM
|
||||
* drivers/plugins, since real ESM `import` resolution never consults NODE_PATH.
|
||||
* Adjusts NODE_PATH so CJS drivers/plugins can load peer deps. Does not work with ESM.
|
||||
*/
|
||||
export function adjustNodePath(): void {
|
||||
const appiumModuleSearchRoot = path.dirname(appiumPackageRoot);
|
||||
|
||||
const refreshRequirePaths = (): boolean => {
|
||||
try {
|
||||
// `Module._initPaths()` re-reads `process.env.NODE_PATH` into Node's global CJS module
|
||||
// search paths; a CJS driver/plugin's own later `require()` calls (even though appium
|
||||
// itself is ESM now) see the update, since this affects the whole process, not just the
|
||||
// caller. Private API; see https://gist.github.com/branneman/8048520#7-the-hack
|
||||
(Module as unknown as ModuleWithInitPaths)._initPaths();
|
||||
// Private API; see https://gist.github.com/branneman/8048520#7-the-hack
|
||||
(require('node:module') as NodeModuleWithInitPaths).Module._initPaths();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
@@ -123,13 +118,13 @@ export async function showDebugInfo({driverConfig, pluginConfig, appiumHome}: De
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures a directory exists and (optionally) is writable.
|
||||
* Ensures a directory exists and (optionally) is writeable.
|
||||
*
|
||||
* If the directory does not exist, this attempts to create it recursively.
|
||||
*
|
||||
* @throws {Error}
|
||||
*/
|
||||
export async function requireDir(root: string, requireWritable = true, displayName = 'folder path'): Promise<void> {
|
||||
export async function requireDir(root: string, requireWriteable = true, displayName = 'folder path'): Promise<void> {
|
||||
let stat;
|
||||
try {
|
||||
stat = await fs.stat(root);
|
||||
@@ -145,12 +140,12 @@ export async function requireDir(root: string, requireWritable = true, displayNa
|
||||
if (stat && !stat.isDirectory()) {
|
||||
throw new Error(`The ${displayName} '${root}' must be a valid directory`);
|
||||
}
|
||||
if (requireWritable) {
|
||||
if (requireWriteable) {
|
||||
try {
|
||||
await fs.access(root, fs.constants.W_OK);
|
||||
} catch (e) {
|
||||
throw new Error(
|
||||
`The ${displayName} '${root}' must be writable for the current user account '${os.userInfo().username}'`,
|
||||
`The ${displayName} '${root}' must be writeable for the current user account '${os.userInfo().username}'`,
|
||||
{cause: e},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/* eslint-disable no-console */
|
||||
import {util} from '@appium/support';
|
||||
import type {Args} from 'appium/types/index.js';
|
||||
import type {Args} from 'appium/types';
|
||||
|
||||
import {getAllArgSpecs, getDefaultsForSchema} from '../schema/schema.js';
|
||||
import {difference, getPath, pickBy, setPath} from '../utils/index.js';
|
||||
import type {ReadConfigFileResult} from './config-file.js';
|
||||
import {getAllArgSpecs, getDefaultsForSchema} from '../schema/schema';
|
||||
import {difference, getPath, pickBy, setPath} from '../utils';
|
||||
import type {ReadConfigFileResult} from './config-file';
|
||||
|
||||
interface FlattenedArg {
|
||||
value: unknown;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {util} from '@appium/support';
|
||||
import type {ExtensionType} from '@appium/types';
|
||||
import type {CliExtensionSubcommand} from 'appium/types/index.js';
|
||||
import type {CliExtensionSubcommand} from 'appium/types';
|
||||
import type {ArgumentOptions} from 'argparse';
|
||||
|
||||
import {
|
||||
DRIVER_TYPE,
|
||||
@@ -11,13 +12,14 @@ import {
|
||||
EXT_SUBCOMMAND_UNINSTALL,
|
||||
EXT_SUBCOMMAND_UPDATE,
|
||||
PLUGIN_TYPE,
|
||||
} from '../constants.js';
|
||||
import {INSTALL_TYPES} from '../extension/manifest/index.js';
|
||||
import {toParserArgs} from '../schema/cli-args.js';
|
||||
import type {ArgumentDefinitions} from '../schema/cli-args.js';
|
||||
} from '../constants';
|
||||
import {INSTALL_TYPES} from '../extension/extension-config';
|
||||
import {toParserArgs} from '../schema/cli-args';
|
||||
const DRIVER_EXAMPLE = 'xcuitest';
|
||||
const PLUGIN_EXAMPLE = 'images';
|
||||
|
||||
export type ArgumentDefinitions = Map<[name: string] | [name: string, alias: string], ArgumentOptions>;
|
||||
|
||||
/**
|
||||
* This is necessary because we pass the array into `argparse`. `argparse` is bad and mutates things. We don't want that.
|
||||
* Bad `argparse`! Bad!
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import {console, util} from '@appium/support';
|
||||
import type {ExtMetadata, ExtRecord, InstallType} from 'appium/types/index.js';
|
||||
import type {ExtMetadata, ExtRecord, InstallType} from 'appium/types';
|
||||
|
||||
import {KNOWN_DRIVERS} from '../constants.js';
|
||||
import {ExtensionCliCommand} from './extension-command.js';
|
||||
import {KNOWN_DRIVERS} from '../constants';
|
||||
import {ExtensionCliCommand} from './extension-command';
|
||||
import type {
|
||||
ExtensionArgs,
|
||||
ExtensionCommandOptions,
|
||||
ExtensionUpdateResult,
|
||||
PostInstallText,
|
||||
RunOutput,
|
||||
} from './extension-command.js';
|
||||
} from './extension-command';
|
||||
const REQ_DRIVER_FIELDS = ['driverName', 'automationName', 'platformNames', 'mainClass'];
|
||||
type DriverInstallOpts = {driver: string; installType: InstallType; packageName?: string};
|
||||
type DriverUninstallOpts = {driver: string};
|
||||
|
||||
@@ -3,8 +3,8 @@ import path from 'node:path';
|
||||
import {pathToFileURL} from 'node:url';
|
||||
import {inspect} from 'node:util';
|
||||
|
||||
import {console, fs, system, util} from '@appium/support';
|
||||
import type {ExtensionType, IDoctorCheck, PackageJson} from '@appium/types';
|
||||
import {console, env, fs, npm, system, util} from '@appium/support';
|
||||
import type {AppiumLogger, ExtensionType, IDoctorCheck} from '@appium/types';
|
||||
import type {
|
||||
ExtInstallReceipt as AppiumExtInstallReceipt,
|
||||
ExtManifest as AppiumExtManifest,
|
||||
@@ -12,22 +12,23 @@ import type {
|
||||
ExtPackageJson as AppiumExtPackageJson,
|
||||
ExtRecord as AppiumExtRecord,
|
||||
InstallType,
|
||||
} from 'appium/types/index.js';
|
||||
} from 'appium/types';
|
||||
import {asyncfilter, asyncmap} from 'asyncbox';
|
||||
import * as semver from 'semver';
|
||||
import {SubProcess} from 'teen_process';
|
||||
import type {PackageJson} from 'type-fest';
|
||||
|
||||
import {Doctor, EXIT_CODE as DOCTOR_EXIT_CODE} from '../doctor/doctor.js';
|
||||
import type {ExtensionConfig as BaseExtensionConfig} from '../extension/extension-config.js';
|
||||
import {Doctor, EXIT_CODE as DOCTOR_EXIT_CODE} from '../doctor/doctor';
|
||||
import type {ExtensionConfig as BaseExtensionConfig} from '../extension/extension-config';
|
||||
import {
|
||||
INSTALL_TYPE_DEV,
|
||||
INSTALL_TYPE_GIT,
|
||||
INSTALL_TYPE_GITHUB,
|
||||
INSTALL_TYPE_LOCAL,
|
||||
INSTALL_TYPE_NPM,
|
||||
} from '../extension/manifest/index.js';
|
||||
import {appiumPackageRoot, compact, hasAppiumDependency, npm, npmPackage, packageDidChange} from '../utils/index.js';
|
||||
import {RingBuffer, spinWith} from './utils.js';
|
||||
} from '../extension/extension-config';
|
||||
import {appiumPackageRoot, compact, npmPackage, packageDidChange} from '../utils';
|
||||
import {RingBuffer, spinWith} from './utils';
|
||||
|
||||
const UPDATE_ALL = 'installed';
|
||||
const MAX_CONCURRENT_REPO_FETCHES = 5;
|
||||
@@ -160,9 +161,6 @@ type GetInstallationReceiptOpts<ExtType extends ExtensionType = ExtensionType> =
|
||||
|
||||
type InstalledExtensionLike = {installType?: InstallType; installPath?: string};
|
||||
|
||||
/** Minimal logger shape accepted where callers must control whether output can hit `STDOUT`. */
|
||||
type InfoSink = {info(message?: string, ...args: any[]): void};
|
||||
|
||||
class NotUpdatableError extends Error {}
|
||||
|
||||
class NoUpdatesAvailableError extends Error {}
|
||||
@@ -195,15 +193,6 @@ export abstract class ExtensionCliCommand<ExtType extends ExtensionType = Extens
|
||||
this.isJsonOutput = Boolean(json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the config's pending manifest-validation summary (from the `loadExtensions()` call at
|
||||
* CLI startup) through this command's own JSON-mode-aware console, so it's suppressed under
|
||||
* `--json` just like any other non-JSON output.
|
||||
*/
|
||||
printPendingValidationSummary(): void {
|
||||
this.config.printValidationSummary(this.log);
|
||||
}
|
||||
|
||||
/**
|
||||
* `driver` or `plugin`, depending on the `ExtensionConfig`.
|
||||
*/
|
||||
@@ -380,15 +369,7 @@ export abstract class ExtensionCliCommand<ExtType extends ExtensionType = Extens
|
||||
);
|
||||
}
|
||||
|
||||
if (installType === INSTALL_TYPE_NPM) {
|
||||
const compatibleVersion = await this._findCompatibleExtVersion(installViaNpmOpts);
|
||||
if (compatibleVersion && !installViaNpmOpts.pkgVer) {
|
||||
installViaNpmOpts.pkgVer = compatibleVersion;
|
||||
// installSpec is either the full npm package name, or the known short name, with no version.
|
||||
// Append the found version to it, so that it's shown in the following log messages
|
||||
installViaNpmOpts.installSpec = `${installSpec}@${compatibleVersion}`;
|
||||
}
|
||||
}
|
||||
await this._checkInstallCompatibility(installViaNpmOpts);
|
||||
|
||||
const receipt = await this.installViaNpm(installViaNpmOpts);
|
||||
|
||||
@@ -432,7 +413,7 @@ export abstract class ExtensionCliCommand<ExtType extends ExtensionType = Extens
|
||||
await this.config.addExtension(extName, extManifest as any);
|
||||
|
||||
// update the hash if we've changed the local `package.json`
|
||||
if (await hasAppiumDependency(this.config.appiumHome)) {
|
||||
if (await env.hasAppiumDependency(this.config.appiumHome)) {
|
||||
await packageDidChange(this.config.appiumHome);
|
||||
}
|
||||
|
||||
@@ -827,12 +808,7 @@ export abstract class ExtensionCliCommand<ExtType extends ExtensionType = Extens
|
||||
const {pkg, installPath} = await spinWith(
|
||||
this.isJsonOutput,
|
||||
installMsg,
|
||||
async () =>
|
||||
await npm.installPackage(appiumHome, installStr, {
|
||||
pkgName,
|
||||
installType,
|
||||
hasAppiumDependency: await hasAppiumDependency(appiumHome),
|
||||
}),
|
||||
async () => await npm.installPackage(appiumHome, installStr, {pkgName, installType}),
|
||||
);
|
||||
|
||||
const validatedPkg = await spinWith(this.isJsonOutput, validateMsg, async () =>
|
||||
@@ -1143,119 +1119,30 @@ export abstract class ExtensionCliCommand<ExtType extends ExtensionType = Extens
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the latest extension version compatible with the currently installed server.
|
||||
* If a specific version is requested, only that one is checked.
|
||||
*
|
||||
* @returns the latest compatible version, or `undefined` if the check does not apply
|
||||
* @throws {Error} if no version is compatible
|
||||
* Checks whether the given extension is compatible with the currently installed server
|
||||
*/
|
||||
private async _findCompatibleExtVersion({
|
||||
private async _checkInstallCompatibility({
|
||||
installSpec,
|
||||
pkgName,
|
||||
pkgVer,
|
||||
}: InstallViaNpmArgs): Promise<string | undefined> {
|
||||
const serverVersion = npmPackage.version;
|
||||
const isGivenExtCompatible = await this._checkGivenExtVersionCompatibility(
|
||||
serverVersion,
|
||||
installSpec,
|
||||
pkgName,
|
||||
pkgVer,
|
||||
);
|
||||
|
||||
if (isGivenExtCompatible) {
|
||||
return undefined;
|
||||
installType,
|
||||
}: InstallViaNpmArgs): Promise<void> {
|
||||
if (INSTALL_TYPE_NPM !== installType) {
|
||||
return;
|
||||
}
|
||||
|
||||
return await this._findLatestCompatibleExtVersion(serverVersion, installSpec, pkgName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given extension version (or the latest, if not specified) is compatible
|
||||
* with the currently installed server version.
|
||||
*
|
||||
* @returns whether the extension version is compatible with the server
|
||||
* @throws {Error} if the specified version is incompatible, or if the latest version declares an outdated server range, which means all versions are incompatible
|
||||
*/
|
||||
private async _checkGivenExtVersionCompatibility(
|
||||
serverVersion: string,
|
||||
installSpec: string,
|
||||
pkgName: string,
|
||||
pkgVer?: string,
|
||||
): Promise<boolean> {
|
||||
return await spinWith(this.isJsonOutput, `Checking if '${pkgName}' is compatible`, async () => {
|
||||
const extServerVersion = await getRemoteExtensionVersionReq(pkgName, pkgVer);
|
||||
const isExtCompatible = areVersionsCompatible(serverVersion, extServerVersion);
|
||||
if (!isExtCompatible) {
|
||||
if (pkgVer || (extServerVersion && semver.gtr(serverVersion, extServerVersion, {includePrerelease: true}))) {
|
||||
throw this._createFatalError(
|
||||
`'${installSpec}' cannot be installed because the server version it requires (${extServerVersion}) ` +
|
||||
`does not meet the currently installed one (${serverVersion}). Please install ` +
|
||||
`a compatible server version first.`,
|
||||
);
|
||||
}
|
||||
const latestVerIncompatibleMsg =
|
||||
`The latest version of '${pkgName}' cannot be installed because the server version it requires ` +
|
||||
`(${extServerVersion}) does not meet the currently installed one (${serverVersion}). ` +
|
||||
`Will look for an older, compatible version of '${pkgName}'.`;
|
||||
this.log.warn(console.styleText('yellow', latestVerIncompatibleMsg));
|
||||
await spinWith(this.isJsonOutput, `Checking if '${pkgName}' is compatible`, async () => {
|
||||
const [serverVersion, extVersionRequirement] = await getRemoteExtensionVersionReq(pkgName, pkgVer);
|
||||
if (serverVersion && extVersionRequirement && !semver.satisfies(serverVersion, extVersionRequirement)) {
|
||||
throw this._createFatalError(
|
||||
`'${installSpec}' cannot be installed because the server version it requires (${extVersionRequirement}) ` +
|
||||
`does not meet the currently installed one (${serverVersion}). Please install ` +
|
||||
`a compatible server version first.`,
|
||||
);
|
||||
}
|
||||
return isExtCompatible;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves all published extension versions, checks the latest non-prerelease version
|
||||
* of each major extension version for server compatibility, and returns the latest compatible version
|
||||
*
|
||||
* @returns the latest compatible extension version
|
||||
* @throws {Error} if no extension version is compatible
|
||||
*/
|
||||
private async _findLatestCompatibleExtVersion(
|
||||
serverVersion: string,
|
||||
installSpec: string,
|
||||
pkgName: string,
|
||||
): Promise<string> {
|
||||
const throwIncompatible = () => {
|
||||
throw this._createFatalError(
|
||||
`'${installSpec}' cannot be installed because none of its versions are compatible with the currently ` +
|
||||
`installed server version (${serverVersion}). Please install a compatible server version first.`,
|
||||
);
|
||||
};
|
||||
|
||||
const latestCompatibleVersion = await spinWith(
|
||||
this.isJsonOutput,
|
||||
`Looking for latest compatible version of '${pkgName}'`,
|
||||
async () => {
|
||||
const versions = await getRemoteExtensionLatestStableMajors(pkgName);
|
||||
// If there's at most one package version (= latest), we have already checked it
|
||||
if (versions.length < 2) {
|
||||
return throwIncompatible();
|
||||
}
|
||||
// Check the oldest version first - if it requires a newer server, no version can match
|
||||
const oldestReq = await getRemoteExtensionVersionReq(pkgName, versions[versions.length - 1]);
|
||||
if (oldestReq && semver.ltr(serverVersion, oldestReq, {includePrerelease: true})) {
|
||||
return throwIncompatible();
|
||||
}
|
||||
// Iterate over all other latest major versions, newest first. Skip latest since it was already checked,
|
||||
// and skip oldest since we've already stored its requirement in `oldestReq`
|
||||
for (const version of versions.slice(1, -1)) {
|
||||
if (areVersionsCompatible(serverVersion, await getRemoteExtensionVersionReq(pkgName, version))) {
|
||||
return version;
|
||||
}
|
||||
}
|
||||
// Finally, check the oldest version using the previously retrieved requirement
|
||||
if (areVersionsCompatible(serverVersion, oldestReq)) {
|
||||
return versions[versions.length - 1];
|
||||
}
|
||||
return throwIncompatible();
|
||||
},
|
||||
);
|
||||
|
||||
this.log.info(`Found version ${latestCompatibleVersion} as the latest compatible version of '${pkgName}'`);
|
||||
|
||||
return latestCompatibleVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* For any `package.json` fields which a particular type of extension requires, validate the
|
||||
* presence and form of those fields on the `package.json` data, throwing an error if anything is
|
||||
@@ -1279,14 +1166,13 @@ export abstract class ExtensionCliCommand<ExtType extends ExtensionType = Extens
|
||||
*
|
||||
* @param driverConfig - active driver extension config
|
||||
* @param pluginConfig - active plugin extension config
|
||||
* @param logger - sink for non-fatal symlink errors; pass a JSON-mode-aware `CliConsole` so this
|
||||
* never writes to `STDOUT` under `--json`
|
||||
* @param logger - logger instance used for non-fatal symlink errors
|
||||
* @returns resolves when symlink injection has completed for all extensions
|
||||
*/
|
||||
export async function injectAppiumSymlinks(
|
||||
driverConfig: ExtensionConfig<any>,
|
||||
pluginConfig: ExtensionConfig<any>,
|
||||
logger: InfoSink,
|
||||
logger: AppiumLogger,
|
||||
): Promise<void> {
|
||||
const isNpmInstalledExtension = (
|
||||
details: InstalledExtensionLike,
|
||||
@@ -1331,38 +1217,12 @@ function receiptToManifest<ExtType extends ExtensionType>(receipt: ExtInstallRec
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the latest published non-prerelease version of each major version of the extension, newest first.
|
||||
*
|
||||
* This relies on the following assumptions:
|
||||
* * Extensions do not widen their supported server range to support an older server version
|
||||
* * Extensions can only raise their server range requirement in a major release
|
||||
* * The latest non-prerelease extension version across all npm tags matches the latest extension version
|
||||
* under npm's `latest` tag
|
||||
*
|
||||
* @param pkgName Extension name
|
||||
*/
|
||||
async function getRemoteExtensionLatestStableMajors(pkgName: string): Promise<string[]> {
|
||||
const info = (await npm.getPackageInfo(pkgName, ['versions'])) as unknown;
|
||||
const versions = Array.isArray(info) ? (info as string[]) : typeof info === 'string' ? [info] : [];
|
||||
const stableVersionsDesc = versions.filter((v) => semver.valid(v) && !semver.prerelease(v)).sort(semver.rcompare);
|
||||
const latestPerMajor = new Map<number, string>();
|
||||
for (const v of stableVersionsDesc) {
|
||||
const major = semver.major(v);
|
||||
if (!latestPerMajor.has(major)) {
|
||||
latestPerMajor.set(major, v);
|
||||
}
|
||||
}
|
||||
return [...latestPerMajor.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the remote extension Appium server version requirements
|
||||
* Fetches the remote extension version requirements
|
||||
*
|
||||
* @param pkgName Extension name
|
||||
* @param [pkgVer] Extension version (if not provided then the latest is assumed)
|
||||
* @returns supported Appium server semver range, or null if the extension does not declare one
|
||||
*/
|
||||
async function getRemoteExtensionVersionReq(pkgName: string, pkgVer?: string): Promise<string | null> {
|
||||
async function getRemoteExtensionVersionReq(pkgName: string, pkgVer?: string): Promise<[string, string | null]> {
|
||||
const allDeps = await npm.getPackageInfo(`${pkgName}${pkgVer ? `@${pkgVer}` : ``}`, [
|
||||
'peerDependencies',
|
||||
'dependencies',
|
||||
@@ -1370,19 +1230,7 @@ async function getRemoteExtensionVersionReq(pkgName: string, pkgVer?: string): P
|
||||
const requiredVersionPair = Object.values(allDeps)
|
||||
.flatMap((dep) => Object.entries(dep ?? {}))
|
||||
.find(([name]) => name === 'appium');
|
||||
return requiredVersionPair ? (requiredVersionPair[1] as string | null) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the declared Appium server version of an extension is compatible
|
||||
* with a given server version. Extensions with no declared range (null) are considered compatible.
|
||||
*
|
||||
* @param serverVersion exact server version
|
||||
* @param extServerVersion server version or range declared inside an extension manifest. Can be null
|
||||
* @returns whether the versions are compatible
|
||||
*/
|
||||
function areVersionsCompatible(serverVersion: string, extServerVersion: string | null): boolean {
|
||||
return !extServerVersion || semver.satisfies(serverVersion, extServerVersion, {includePrerelease: true});
|
||||
return [npmPackage.version, requiredVersionPair ? (requiredVersionPair[1] as string | null) : null];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1391,7 +1239,7 @@ function areVersionsCompatible(serverVersion: string, extServerVersion: string |
|
||||
*
|
||||
* @param dstFolder The destination folder where the symlink should be created
|
||||
*/
|
||||
async function injectAppiumSymlink(dstFolder: string, logger: InfoSink): Promise<void> {
|
||||
async function injectAppiumSymlink(dstFolder: string, logger: AppiumLogger): Promise<void> {
|
||||
try {
|
||||
const symlinkPath = path.join(dstFolder, path.basename(appiumPackageRoot));
|
||||
if ((await fs.exists(dstFolder)) && !(await fs.exists(symlinkPath))) {
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
/* eslint-disable no-console */
|
||||
import type {Class, DriverType, ExtensionType, PluginType} from '@appium/types';
|
||||
import type {Args, CliExtensionCommand, CliExtensionSubcommand} from 'appium/types/index.js';
|
||||
import type {Args, CliExtensionCommand, CliExtensionSubcommand} from 'appium/types';
|
||||
|
||||
import {DRIVER_TYPE, PLUGIN_TYPE} from '../constants.js';
|
||||
import type {ExtensionConfig} from '../extension/extension-config.js';
|
||||
import {reloadManifest} from '../extension/index.js';
|
||||
import {isExtensionCommandArgs} from '../schema/cli-args-guards.js';
|
||||
import {withManifestLock} from '../utils/index.js';
|
||||
import DriverCliCommand from './driver-command.js';
|
||||
import PluginCliCommand from './plugin-command.js';
|
||||
import {errAndQuit, JSON_SPACES} from './utils.js';
|
||||
import {DRIVER_TYPE, PLUGIN_TYPE} from '../constants';
|
||||
import type {ExtensionConfig} from '../extension/extension-config';
|
||||
import {isExtensionCommandArgs} from '../schema/cli-args-guards';
|
||||
import DriverCliCommand from './driver-command';
|
||||
import PluginCliCommand from './plugin-command';
|
||||
import {errAndQuit, JSON_SPACES} from './utils';
|
||||
|
||||
export const commandClasses = Object.freeze({
|
||||
[DRIVER_TYPE]: DriverCliCommand,
|
||||
@@ -32,6 +30,9 @@ export async function runExtensionCommand<Cmd extends CliExtensionCommand, SubCm
|
||||
args: Args<Cmd, SubCmd>,
|
||||
config: ExtensionConfig<Cmd>,
|
||||
) {
|
||||
// TODO driver config file should be locked while any of these commands are
|
||||
// running to prevent weird situations
|
||||
let jsonResult: Record<string, unknown> = {};
|
||||
const {extensionType: type} = config; // NOTE this is the same as `args.subcommand`
|
||||
if (!isExtensionCommandArgs(args)) {
|
||||
throw new TypeError(`Cannot call ${type} command without a subcommand like 'install'`);
|
||||
@@ -42,36 +43,22 @@ export async function runExtensionCommand<Cmd extends CliExtensionCommand, SubCm
|
||||
if (suppressOutput) {
|
||||
json = true;
|
||||
}
|
||||
|
||||
// Serialize this against any other `driver`/`plugin` CLI command running (in this or another
|
||||
// process) against the same `APPIUM_HOME`, so concurrent commands can't race to read, mutate,
|
||||
// and write the same extension manifest out from under each other.
|
||||
const CommandClass = commandClasses[type] as ExtCommand<Cmd>;
|
||||
const cmd = new CommandClass({config, json} as any);
|
||||
try {
|
||||
return await withManifestLock<Record<string, unknown>>(config.appiumHome, async () => {
|
||||
// Refresh from disk while holding the lock, in case another process wrote to the manifest
|
||||
// between this process's startup read and now, and revalidate so derived state (installed
|
||||
// extensions, pending validation summary, duplicate-automationName tracking) is current too.
|
||||
await reloadManifest(config.manifest);
|
||||
|
||||
const CommandClass = commandClasses[type] as ExtCommand<Cmd>;
|
||||
const cmd = new CommandClass({config, json} as any);
|
||||
cmd.printPendingValidationSummary();
|
||||
const jsonResult = (await cmd.execute(args)) as Record<string, unknown>;
|
||||
|
||||
if (json && !suppressOutput) {
|
||||
console.log(JSON.stringify(jsonResult, null, JSON_SPACES));
|
||||
}
|
||||
|
||||
return jsonResult;
|
||||
});
|
||||
jsonResult = (await cmd.execute(args)) as Record<string, unknown>;
|
||||
} catch (err) {
|
||||
// in the suppress output case, we are calling this function internally and should
|
||||
// just throw instead of printing an error and ending the process
|
||||
if (suppressOutput) {
|
||||
throw err;
|
||||
}
|
||||
// `errAndQuit` exits the process, so this must run only once `withManifestLock` has already
|
||||
// released the lock -- never from inside its callback, or the lock would be left behind.
|
||||
errAndQuit(json, err);
|
||||
}
|
||||
|
||||
if (json && !suppressOutput) {
|
||||
console.log(JSON.stringify(jsonResult, null, JSON_SPACES));
|
||||
}
|
||||
|
||||
return jsonResult;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import type {DriverType, PluginType} from '@appium/types';
|
||||
import type {CliExtensionSubcommand} from 'appium/types/index.js';
|
||||
import type {CliExtensionSubcommand} from 'appium/types';
|
||||
import {ArgumentParser} from 'argparse';
|
||||
import type {SubArgumentParserOptions, SubparsersAction} from 'argparse';
|
||||
|
||||
@@ -16,12 +16,12 @@ import {
|
||||
PLUGIN_TYPE,
|
||||
SERVER_SUBCOMMAND,
|
||||
SETUP_SUBCOMMAND,
|
||||
} from '../constants.js';
|
||||
import {APPIUM_VER} from '../helpers/build.js';
|
||||
import type {ArgumentDefinitions} from '../schema/index.js';
|
||||
import {finalizeSchema, getAllArgSpecs, getArgSpec, hasArgSpec} from '../schema/index.js';
|
||||
import {setPath} from '../utils/index.js';
|
||||
import {getExtensionArgs, getServerArgs} from './args.js';
|
||||
} from '../constants';
|
||||
import {APPIUM_VER} from '../helpers/build';
|
||||
import {finalizeSchema, getAllArgSpecs, getArgSpec, hasArgSpec} from '../schema';
|
||||
import {setPath} from '../utils';
|
||||
import {getExtensionArgs, getServerArgs} from './args';
|
||||
import type {ArgumentDefinitions} from './args';
|
||||
import {
|
||||
DEFAULT_PLUGINS,
|
||||
determinePlatformName,
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
SUBCOMMAND_DESKTOP,
|
||||
SUBCOMMAND_MOBILE,
|
||||
SUBCOMMAND_RESET,
|
||||
} from './setup-command.js';
|
||||
} from './setup-command';
|
||||
|
||||
export const EXTRA_ARGS = 'extraArgs';
|
||||
|
||||
@@ -268,25 +268,24 @@ export class ArgParser {
|
||||
dest: `setupCommand`,
|
||||
});
|
||||
|
||||
const defaultPluginsString = DEFAULT_PLUGINS.join(', ');
|
||||
const parserSpecs = [
|
||||
{
|
||||
command: SUBCOMMAND_MOBILE,
|
||||
help:
|
||||
`The preset for mobile devices ` +
|
||||
`(drivers: ${getPresetDrivers(SUBCOMMAND_MOBILE).join(',')}; plugins: ${defaultPluginsString})`,
|
||||
`(drivers: ${getPresetDrivers(SUBCOMMAND_MOBILE).join(',')}; plugins: ${DEFAULT_PLUGINS})`,
|
||||
},
|
||||
{
|
||||
command: SUBCOMMAND_BROWSER,
|
||||
help:
|
||||
`The preset for desktop browsers ` +
|
||||
`(drivers: ${getPresetDrivers(SUBCOMMAND_BROWSER).join(',')}; plugins: ${defaultPluginsString})`,
|
||||
`(drivers: ${getPresetDrivers(SUBCOMMAND_BROWSER).join(',')}; plugins: ${DEFAULT_PLUGINS})`,
|
||||
},
|
||||
{
|
||||
command: SUBCOMMAND_DESKTOP,
|
||||
help:
|
||||
`The preset for desktop applications ` +
|
||||
`(drivers: ${getPresetDrivers(SUBCOMMAND_DESKTOP).join(',')}; plugins: ${defaultPluginsString})`,
|
||||
`(drivers: ${getPresetDrivers(SUBCOMMAND_DESKTOP).join(',')}; plugins: ${DEFAULT_PLUGINS})`,
|
||||
},
|
||||
{
|
||||
command: SUBCOMMAND_RESET,
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import {console, util} from '@appium/support';
|
||||
import type {ExtMetadata, ExtRecord, InstallType} from 'appium/types/index.js';
|
||||
import type {ExtMetadata, ExtRecord, InstallType} from 'appium/types';
|
||||
|
||||
import {KNOWN_PLUGINS} from '../constants.js';
|
||||
import {ExtensionCliCommand} from './extension-command.js';
|
||||
import {KNOWN_PLUGINS} from '../constants';
|
||||
import {ExtensionCliCommand} from './extension-command';
|
||||
import type {
|
||||
ExtensionArgs,
|
||||
ExtensionCommandOptions,
|
||||
ExtensionUpdateResult,
|
||||
PostInstallText,
|
||||
RunOutput,
|
||||
} from './extension-command.js';
|
||||
} from './extension-command';
|
||||
|
||||
const REQ_PLUGIN_FIELDS = ['pluginName', 'mainClass'];
|
||||
type PluginInstallOpts = {plugin: string; installType: InstallType; packageName?: string};
|
||||
|
||||
@@ -5,12 +5,12 @@ import type {
|
||||
CliCommandSetupSubcommand,
|
||||
CliExtensionCommand,
|
||||
CliExtensionSubcommand,
|
||||
} from 'appium/types/index.js';
|
||||
} from 'appium/types';
|
||||
|
||||
import {DESKTOP_BROWSERS, DESKTOP_DRIVERS, MOBILE_DRIVERS} from '../constants.js';
|
||||
import type {ExtensionConfig} from '../extension/extension-config.js';
|
||||
import {log} from '../logger.js';
|
||||
import {runExtensionCommand} from './extension.js';
|
||||
import {DESKTOP_BROWSERS, DESKTOP_DRIVERS, MOBILE_DRIVERS} from '../constants';
|
||||
import type {ExtensionConfig} from '../extension/extension-config';
|
||||
import {log} from '../logger';
|
||||
import {runExtensionCommand} from './extension';
|
||||
|
||||
/**
|
||||
* Subcommands of preset for setup
|
||||
@@ -31,7 +31,7 @@ const PRESET_PAIRS = Object.freeze({
|
||||
} as const);
|
||||
const DRIVERS_ONLY_MACOS = ['xcuitest', 'safari', 'mac2'];
|
||||
|
||||
const DRIVERS_ONLY_WINDOWS = ['wincore'];
|
||||
const DRIVERS_ONLY_WINDOWS = ['windows'];
|
||||
|
||||
/**
|
||||
* Plugin names listed in KNOWN_PLUGINS to install by default.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* eslint-disable no-console */
|
||||
|
||||
import {console as supportConsole} from '@appium/support';
|
||||
import yoctoSpinner from 'yocto-spinner';
|
||||
import ora from 'ora';
|
||||
|
||||
export const JSON_SPACES = 4;
|
||||
|
||||
@@ -82,13 +82,13 @@ export async function spinWith<T>(json: boolean, msg: string, fn: () => T | Prom
|
||||
if (json) {
|
||||
return await fn();
|
||||
}
|
||||
const spinner = yoctoSpinner({text: msg}).start();
|
||||
const spinner = ora(msg).start();
|
||||
try {
|
||||
const res = await fn();
|
||||
spinner.success();
|
||||
spinner.succeed();
|
||||
return res;
|
||||
} catch (err) {
|
||||
spinner.error();
|
||||
spinner.fail();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ export const MOBILE_DRIVERS = Object.freeze({
|
||||
|
||||
export const DESKTOP_DRIVERS = Object.freeze({
|
||||
mac2: 'appium-mac2-driver',
|
||||
wincore: 'appium-wincore-driver',
|
||||
windows: 'appium-windows-driver',
|
||||
} as const);
|
||||
|
||||
export const DESKTOP_BROWSERS = Object.freeze({
|
||||
@@ -75,11 +75,6 @@ export const CACHE_DIR_RELATIVE_PATH = path.join('node_modules', '.cache', 'appi
|
||||
*/
|
||||
export const PKG_HASHFILE_RELATIVE_PATH = path.join(CACHE_DIR_RELATIVE_PATH, 'package.hash');
|
||||
|
||||
/**
|
||||
* Relative path to lockfile used when installing an extension via `appium`
|
||||
*/
|
||||
export const INSTALL_LOCKFILE_RELATIVE_PATH = path.join(CACHE_DIR_RELATIVE_PATH, '.install.lock');
|
||||
|
||||
export const EXT_SUBCOMMAND_LIST = 'list';
|
||||
export const EXT_SUBCOMMAND_INSTALL = 'install';
|
||||
export const EXT_SUBCOMMAND_UNINSTALL = 'uninstall';
|
||||
@@ -115,8 +110,3 @@ export const BIDI_EVENT_NAME = 'bidiEvent';
|
||||
* The name of the insecure feature that allows retrieving the list of active server sessions
|
||||
*/
|
||||
export const SESSION_DISCOVERY_FEATURE = 'session_discovery';
|
||||
|
||||
/**
|
||||
* The name of the insecure feature that allows CORS requests from any host
|
||||
*/
|
||||
export const CORS_FEATURE = 'cors';
|
||||
|
||||
@@ -146,8 +146,7 @@ export class Doctor {
|
||||
this.log.info(`### Skipped fix ###`);
|
||||
return;
|
||||
} else {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
this.log.warn(`${message}`.replace(/\n$/g, ''));
|
||||
this.log.warn(`${err}`.replace(/\n$/g, ''));
|
||||
this.log.info(`### Fix did not succeed ###`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import {errors} from '@appium/base-driver';
|
||||
import {util} from '@appium/support';
|
||||
import type {DriverClass, DriverType, StringRecord} from '@appium/types';
|
||||
import type {ExtManifest, ExtName, ExtRecord} from 'appium/types/index.js';
|
||||
import type {ExtManifest, ExtName, ExtRecord} from 'appium/types';
|
||||
|
||||
import {DRIVER_TYPE} from '../constants.js';
|
||||
import {log} from '../logger.js';
|
||||
import {ExtensionConfig} from './extension-config.js';
|
||||
import {manifestValidator} from './manifest/index.js';
|
||||
import type {ExtManifestProblem, Manifest} from './manifest/index.js';
|
||||
import {DRIVER_TYPE} from '../constants';
|
||||
import {log} from '../logger';
|
||||
import type {ExtManifestProblem} from './extension-config';
|
||||
import {ExtensionConfig} from './extension-config';
|
||||
import type {Manifest} from './manifest';
|
||||
|
||||
export type MatchedDriver = {
|
||||
driver: DriverClass;
|
||||
@@ -81,27 +81,52 @@ export class DriverConfig extends ExtensionConfig<DriverType> {
|
||||
`Have you installed a driver that supports those ` +
|
||||
`capabilities? Run 'appium driver list --installed' to see. ` +
|
||||
`(Lower-level error: ${err.message})`;
|
||||
throw new errors.SessionNotCreatedError(msg, err);
|
||||
throw new Error(msg, {cause: err});
|
||||
}
|
||||
}
|
||||
|
||||
protected override getConfigProblems(extManifest: ExtManifest<DriverType>, extName: string): ExtManifestProblem[] {
|
||||
void extName;
|
||||
const problems = manifestValidator.getDriverManifestProblems(extManifest);
|
||||
// `?.`, not destructuring: a corrupted entry may be null/non-object (already reported above).
|
||||
const automationName = (extManifest as unknown as Record<string, unknown> | null | undefined)?.automationName;
|
||||
const problems: ExtManifestProblem[] = [];
|
||||
const {platformNames, automationName} = extManifest;
|
||||
|
||||
// Only track actual strings — `undefined` would make every automationName-less entry a "duplicate".
|
||||
if (typeof automationName === 'string') {
|
||||
if (this.knownAutomationNames.has(automationName)) {
|
||||
problems.push({
|
||||
err: 'Multiple drivers claim support for the same automationName',
|
||||
val: automationName,
|
||||
});
|
||||
if (!Array.isArray(platformNames)) {
|
||||
problems.push({
|
||||
err: 'Missing or incorrect supported platformNames list.',
|
||||
val: platformNames,
|
||||
});
|
||||
} else if (util.isEmpty(platformNames)) {
|
||||
problems.push({
|
||||
err: 'Empty platformNames list.',
|
||||
val: platformNames,
|
||||
});
|
||||
} else {
|
||||
for (const pName of platformNames) {
|
||||
if (typeof pName !== 'string') {
|
||||
problems.push({
|
||||
err: 'Incorrectly formatted platformName.',
|
||||
val: pName,
|
||||
});
|
||||
}
|
||||
}
|
||||
this.knownAutomationNames.add(automationName);
|
||||
}
|
||||
|
||||
if (typeof automationName !== 'string') {
|
||||
problems.push({
|
||||
err: 'Missing or incorrect automationName',
|
||||
val: automationName,
|
||||
});
|
||||
}
|
||||
|
||||
if (this.knownAutomationNames.has(automationName as string)) {
|
||||
problems.push({
|
||||
err: 'Multiple drivers claim support for the same automationName',
|
||||
val: automationName,
|
||||
});
|
||||
}
|
||||
|
||||
this.knownAutomationNames.add(automationName as string);
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import {createRequire} from 'node:module';
|
||||
import path from 'node:path';
|
||||
import {pathToFileURL} from 'node:url';
|
||||
|
||||
import {fs, util} from '@appium/support';
|
||||
import {fs, system, util} from '@appium/support';
|
||||
import type {ExtensionType, StringRecord} from '@appium/types';
|
||||
import type {ExtClass, ExtManifest, ExtName, ExtRecord} from 'appium/types/index.js';
|
||||
import type {SchemaObject} from 'ajv';
|
||||
import type {ExtClass, ExtManifest, ExtName, ExtRecord, InstallType} from 'appium/types';
|
||||
import {satisfies} from 'semver';
|
||||
|
||||
import type {
|
||||
@@ -12,19 +12,51 @@ import type {
|
||||
ExtensionListData,
|
||||
InstalledExtensionListData,
|
||||
ExtensionCliCommand,
|
||||
} from '../cli/extension-command.js';
|
||||
import {APPIUM_VER} from '../helpers/build.js';
|
||||
import {log} from '../logger.js';
|
||||
import type {SchemaObject} from '../schema/ajv.js';
|
||||
import {ALLOWED_SCHEMA_EXTENSIONS, isAllowedSchemaFileExtension, registerSchema} from '../schema/schema.js';
|
||||
import {capitalize, resolveFrom} from '../utils/index.js';
|
||||
import {INSTALL_TYPES, manifestValidator} from './manifest/index.js';
|
||||
import type {ExtManifestProblem, Manifest} from './manifest/index.js';
|
||||
} from '../cli/extension-command';
|
||||
import {APPIUM_VER} from '../helpers/build';
|
||||
import {log} from '../logger';
|
||||
import {ALLOWED_SCHEMA_EXTENSIONS, isAllowedSchemaFileExtension, registerSchema} from '../schema/schema';
|
||||
import {capitalize, resolveFrom} from '../utils';
|
||||
import type {Manifest} from './manifest';
|
||||
|
||||
const DEFAULT_ENTRY_POINT = 'index.js';
|
||||
// Counter for `APPIUM_RELOAD_EXTENSIONS` cache-busting; `Date.now()` alone can collide when two
|
||||
// reloads happen within the same millisecond, which would serve the stale cached module.
|
||||
let reloadCounter = 0;
|
||||
/**
|
||||
* "npm" install type
|
||||
* Used when extension was installed by npm package name
|
||||
* @remarks _All_ extensions are installed _by_ `npm`, but only this one means the package name was
|
||||
* used to specify it
|
||||
*/
|
||||
export const INSTALL_TYPE_NPM = 'npm';
|
||||
/**
|
||||
* "local" install type
|
||||
* Used when extension was installed from a local path
|
||||
*/
|
||||
export const INSTALL_TYPE_LOCAL = 'local';
|
||||
/**
|
||||
* "github" install type
|
||||
* Used when extension was installed via GitHub URL
|
||||
*/
|
||||
export const INSTALL_TYPE_GITHUB = 'github';
|
||||
/**
|
||||
* "git" install type
|
||||
* Used when extensions was installed via Git URL
|
||||
*/
|
||||
export const INSTALL_TYPE_GIT = 'git';
|
||||
/**
|
||||
* "dev" install type
|
||||
* Used when automatically detected as a working copy
|
||||
*/
|
||||
export const INSTALL_TYPE_DEV = 'dev';
|
||||
|
||||
export const INSTALL_TYPES = new Set<InstallType>([
|
||||
INSTALL_TYPE_GIT,
|
||||
INSTALL_TYPE_GITHUB,
|
||||
INSTALL_TYPE_LOCAL,
|
||||
INSTALL_TYPE_NPM,
|
||||
INSTALL_TYPE_DEV,
|
||||
]);
|
||||
|
||||
export type ExtManifestProblem = {err: string; val: unknown};
|
||||
|
||||
export type ExtManifestWithSchema<E extends ExtensionType> = ExtManifest<E> & {
|
||||
schema: NonNullable<ExtManifest<E>['schema']>;
|
||||
@@ -32,31 +64,6 @@ export type ExtManifestWithSchema<E extends ExtensionType> = ExtManifest<E> & {
|
||||
|
||||
export type ExtensionConfigMutationOpts = {write?: boolean};
|
||||
|
||||
/**
|
||||
* Results of the most recent {@linkcode ExtensionConfig.validate} call, not yet rendered anywhere.
|
||||
* `validate()` only computes this; call {@linkcode ExtensionConfig.printValidationSummary} to display it,
|
||||
* so the caller can pick a sink appropriate to its own output context (e.g. a JSON-mode-aware CLI
|
||||
* console, or the server's Winston-backed logger).
|
||||
*/
|
||||
interface ExtensionValidationSummary {
|
||||
/** Number of extensions considered; used only for pluralizing the summary's lead-in line. */
|
||||
checkedCount: number;
|
||||
errorSummaries: string[];
|
||||
warningSummaries: string[];
|
||||
}
|
||||
|
||||
/** Minimal logger shape needed to render a {@linkcode ExtensionValidationSummary}. */
|
||||
export type ValidationSummarySink = {
|
||||
warn(message?: string, ...args: any[]): void;
|
||||
error(message?: string, ...args: any[]): void;
|
||||
};
|
||||
|
||||
const EMPTY_VALIDATION_SUMMARY: ExtensionValidationSummary = {
|
||||
checkedCount: 0,
|
||||
errorSummaries: [],
|
||||
warningSummaries: [],
|
||||
};
|
||||
|
||||
/**
|
||||
* Shared configuration and validation for installed Appium extensions (drivers or plugins).
|
||||
* Subclasses fix the extension kind; do not instantiate this class directly.
|
||||
@@ -64,21 +71,13 @@ const EMPTY_VALIDATION_SUMMARY: ExtensionValidationSummary = {
|
||||
export abstract class ExtensionConfig<ExtType extends ExtensionType> {
|
||||
readonly extensionType: ExtType;
|
||||
readonly manifest: Manifest;
|
||||
/** Populated by {@linkcode ExtensionConfig.validate}; see {@linkcode ExtensionValidationSummary}. */
|
||||
private validationSummary: ExtensionValidationSummary = EMPTY_VALIDATION_SUMMARY;
|
||||
private listDataCache: ExtensionList<ExtType> | undefined;
|
||||
installedExtensions: ExtRecord<ExtType>;
|
||||
#listDataCache: ExtensionList<ExtType> | undefined;
|
||||
|
||||
protected constructor(extensionType: ExtType, manifest: Manifest) {
|
||||
this.extensionType = extensionType;
|
||||
this.manifest = manifest;
|
||||
}
|
||||
|
||||
/**
|
||||
* Live installed-extension map for this extension kind (same object the manifest holds).
|
||||
* Recomputed on every access so it stays in sync across a {@link Manifest.read} reload.
|
||||
*/
|
||||
get installedExtensions(): ExtRecord<ExtType> {
|
||||
return this.manifest.getExtensionData(this.extensionType);
|
||||
this.installedExtensions = manifest.getExtensionData(extensionType);
|
||||
}
|
||||
|
||||
/** Path to `extensions.yaml` after the manifest has been read; otherwise undefined. */
|
||||
@@ -120,17 +119,7 @@ export abstract class ExtensionConfig<ExtType extends ExtensionType> {
|
||||
let moduleObject: any;
|
||||
if (typeof argSchemaPath === 'string') {
|
||||
const schemaPath = await resolveFrom(appiumHome, path.join(pkgName, argSchemaPath));
|
||||
if (path.extname(schemaPath) === '.json') {
|
||||
// `import()` of JSON needs an import attribute Node versions disagree on the
|
||||
// syntax for; parsing directly avoids that entirely.
|
||||
moduleObject = JSON.parse(await fs.readFile(schemaPath, 'utf8'));
|
||||
} else {
|
||||
// Windows still requires a file URL (https://github.com/nodejs/node/issues/31710).
|
||||
// POSIX paths also need URL escaping for characters such as '#' and '%'.
|
||||
const importPath = pathToFileURL(schemaPath).href;
|
||||
const mod = (await import(importPath)) as Record<string, any>;
|
||||
moduleObject = 'default' in mod ? mod.default : mod;
|
||||
}
|
||||
moduleObject = require(schemaPath);
|
||||
} else {
|
||||
moduleObject = argSchemaPath;
|
||||
}
|
||||
@@ -291,7 +280,7 @@ export abstract class ExtensionConfig<ExtType extends ExtensionType> {
|
||||
*
|
||||
* @param extName - Installed extension key
|
||||
*/
|
||||
getInstallPath(extName: keyof ExtRecord<ExtType>): string {
|
||||
getInstallPath(extName: keyof ExtRecord<ExtType> & string): string {
|
||||
return (
|
||||
this.installedExtensions[extName]?.installPath ??
|
||||
path.join(this.appiumHome, 'node_modules', this.installedExtensions[extName].pkgName)
|
||||
@@ -306,25 +295,8 @@ export abstract class ExtensionConfig<ExtType extends ExtensionType> {
|
||||
async requireAsync(extName: ExtName<ExtType>): Promise<ExtClass<ExtType>> {
|
||||
const [reqPath, mainClass] = await this._resolveExtension(extName);
|
||||
log.debug(`Requiring ${this.extensionType} at ${reqPath}`);
|
||||
// Windows still requires a file URL (https://github.com/nodejs/node/issues/31710).
|
||||
// POSIX paths also need URL escaping for characters such as '#' and '%'.
|
||||
let importPath = pathToFileURL(reqPath).href;
|
||||
// note: this will only reload the entry point, not files it imports internally
|
||||
if (process.env.APPIUM_RELOAD_EXTENSIONS) {
|
||||
// For a CJS extension, `import()` delegates to Node's CJS loader, which caches by
|
||||
// resolved filename and ignores the query string appended below — evict it from
|
||||
// `require.cache` directly so it's actually re-evaluated. (No-op for a genuinely ESM
|
||||
// extension, since it was never in `require.cache` to begin with.)
|
||||
const req = createRequire(import.meta.url);
|
||||
const realEntryPath = await fs.realpath(reqPath);
|
||||
if (req.cache[realEntryPath]) {
|
||||
delete req.cache[realEntryPath];
|
||||
}
|
||||
// For an ESM extension, there's no public API to evict a module from ESM's registry, so
|
||||
// force a fresh copy via a unique specifier instead.
|
||||
importPath += `?reload=${reloadCounter++}`;
|
||||
log.debug(`Reloading ${this.extensionType} at ${reqPath}`);
|
||||
}
|
||||
// https://github.com/nodejs/node/issues/31710
|
||||
const importPath = system.isWindows() ? pathToFileURL(reqPath).href : reqPath;
|
||||
const mod = (await import(importPath)) as Record<string, ExtClass<ExtType>>;
|
||||
const MainClass = mod[mainClass];
|
||||
if (!MainClass) {
|
||||
@@ -361,8 +333,8 @@ export abstract class ExtensionConfig<ExtType extends ExtensionType> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates all entries in `exts`, records a summary (see {@linkcode ExtensionConfig.printValidationSummary}),
|
||||
* and removes keys that have blocking errors. Intended for subclasses’ `validate` implementation.
|
||||
* Validates all entries in `exts`, logs summaries, and removes keys that have blocking errors.
|
||||
* Intended for subclasses’ `validate` implementation.
|
||||
*/
|
||||
protected async _validate(exts: ExtRecord<ExtType>): Promise<ExtRecord<ExtType>> {
|
||||
const errorMap = new Map<string, ExtManifestProblem[]>();
|
||||
@@ -381,61 +353,47 @@ export abstract class ExtensionConfig<ExtType extends ExtensionType> {
|
||||
}
|
||||
|
||||
const {errorSummaries, warningSummaries} = this.getValidationResultSummaries(errorMap, warningMap);
|
||||
this.validationSummary = {checkedCount: errorMap.size, errorSummaries, warningSummaries};
|
||||
return exts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the summary from the most recent {@linkcode ExtensionConfig.validate} call via `sink`,
|
||||
* then clears it so a later call doesn't re-print the same summary. Errors take precedence:
|
||||
* warnings are only shown when there were no errors. No-op if there's nothing to report.
|
||||
*
|
||||
* @param sink - Where to write the summary; e.g. a JSON-mode-aware CLI console for extension
|
||||
* subcommands, or the server's own (by then Winston-backed) logger once it has taken over.
|
||||
*/
|
||||
printValidationSummary(sink: ValidationSummarySink): void {
|
||||
const {checkedCount, errorSummaries, warningSummaries} = this.validationSummary;
|
||||
this.validationSummary = EMPTY_VALIDATION_SUMMARY;
|
||||
|
||||
if (!util.isEmpty(errorSummaries)) {
|
||||
sink.error(
|
||||
log.error(
|
||||
`Appium encountered ${util.pluralize(
|
||||
'error',
|
||||
checkedCount,
|
||||
errorMap.size,
|
||||
true,
|
||||
)} while validating ${this.extensionType}s found in manifest ${this.manifestPath}`,
|
||||
);
|
||||
for (const summary of errorSummaries) {
|
||||
sink.error(summary);
|
||||
log.error(summary);
|
||||
}
|
||||
} else if (!util.isEmpty(warningSummaries)) {
|
||||
// only display warnings if there are no errors!
|
||||
sink.warn(
|
||||
log.warn(
|
||||
`Appium encountered ${util.pluralize(
|
||||
'warning',
|
||||
checkedCount,
|
||||
warningMap.size,
|
||||
true,
|
||||
)} while validating ${this.extensionType}s found in manifest ${this.manifestPath}`,
|
||||
);
|
||||
for (const summary of warningSummaries) {
|
||||
sink.warn(summary);
|
||||
log.warn(summary);
|
||||
}
|
||||
}
|
||||
return exts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches `appium driver|plugin list`-style data via the CLI command class; result is cached.
|
||||
*/
|
||||
protected async getListData(): Promise<ExtensionList<ExtType>> {
|
||||
if (this.listDataCache) {
|
||||
return this.listDataCache;
|
||||
if (this.#listDataCache) {
|
||||
return this.#listDataCache;
|
||||
}
|
||||
// Import here to avoid circular dependency with cli/extension
|
||||
const {commandClasses} = await import('../cli/extension.js');
|
||||
const CommandClass = (commandClasses as StringRecord)[this.extensionType];
|
||||
const cmd = new CommandClass({config: this, json: true}) as ExtensionCliCommand<ExtType>;
|
||||
const listData = await cmd.list({showInstalled: true, showUpdates: true});
|
||||
this.listDataCache = listData;
|
||||
this.#listDataCache = listData;
|
||||
return listData;
|
||||
}
|
||||
|
||||
@@ -471,7 +429,7 @@ export abstract class ExtensionConfig<ExtType extends ExtensionType> {
|
||||
const createPeerWarning = (reason: string): string =>
|
||||
`${extTypeText} "${extName}" (package \`${pkgName}\`) may be incompatible with the current version of Appium (v${APPIUM_VER}) due to ${reason}`;
|
||||
|
||||
if (typeof appiumVersion === 'string' && !satisfies(APPIUM_VER, appiumVersion, {includePrerelease: true})) {
|
||||
if (typeof appiumVersion === 'string' && !satisfies(APPIUM_VER, appiumVersion)) {
|
||||
const listData = await this.getListData();
|
||||
const extListData = listData[extName] as ExtensionListData<ExtType> | undefined;
|
||||
if (extListData?.installed) {
|
||||
@@ -555,7 +513,31 @@ export abstract class ExtensionConfig<ExtType extends ExtensionType> {
|
||||
/** Blocking issues for required manifest fields shared by all extensions (version, package name, main class). */
|
||||
protected getGenericConfigProblems(extManifest: ExtManifest<ExtType>, extName: string): ExtManifestProblem[] {
|
||||
void extName;
|
||||
return manifestValidator.getCommonManifestProblems(extManifest);
|
||||
const {version, pkgName, mainClass} = extManifest;
|
||||
const problems: ExtManifestProblem[] = [];
|
||||
|
||||
if (typeof version !== 'string') {
|
||||
problems.push({
|
||||
err: `Invalid or missing \`version\` field in my \`package.json\` and/or \`extensions.yaml\` (must be a string)`,
|
||||
val: version,
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof pkgName !== 'string') {
|
||||
problems.push({
|
||||
err: `Invalid or missing \`name\` field in my \`package.json\` and/or \`extensions.yaml\` (must be a string)`,
|
||||
val: pkgName,
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof mainClass !== 'string') {
|
||||
problems.push({
|
||||
err: `Invalid or missing \`appium.mainClass\` field in my \`package.json\` and/or \`mainClass\` field in \`extensions.yaml\` (must be a string)`,
|
||||
val: mainClass,
|
||||
});
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/** Driver- or plugin-specific blocking validation; override in subclasses when needed. */
|
||||
@@ -596,6 +578,11 @@ export abstract class ExtensionConfig<ExtType extends ExtensionType> {
|
||||
`Assumed entry point: '${entryPointFullPath}'`,
|
||||
);
|
||||
}
|
||||
// note: this will only reload the entry point
|
||||
if (process.env.APPIUM_RELOAD_EXTENSIONS && require.cache[entryPointFullPath]) {
|
||||
log.debug(`Removing ${entryPointFullPath} from require cache`);
|
||||
delete require.cache[entryPointFullPath];
|
||||
}
|
||||
return [entryPointFullPath, mainClass];
|
||||
}
|
||||
|
||||
@@ -609,7 +596,7 @@ export abstract class ExtensionConfig<ExtType extends ExtensionType> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a package `exports` field (string, `"."`, `"import"`, or `"default"`) to an ESM entry path.
|
||||
* Resolves a package `exports` field (string, `"."`, or `"import"`) to a relative entry path for ESM packages.
|
||||
*
|
||||
* @param exportsValue - `package.json` `exports` value or nested fragment
|
||||
*/
|
||||
@@ -622,16 +609,9 @@ export function resolveEsmEntryPoint(exportsValue: unknown): string | undefined
|
||||
}
|
||||
|
||||
const obj = exportsValue as Record<string, unknown>;
|
||||
if ('.' in obj) {
|
||||
return resolveEsmEntryPoint(obj['.']);
|
||||
}
|
||||
// Matching conditions are evaluated in package.json order, including an early default.
|
||||
for (const [condition, target] of Object.entries(obj)) {
|
||||
if (condition === 'import' || condition === 'default') {
|
||||
const entryPoint = resolveEsmEntryPoint(target);
|
||||
if (entryPoint) {
|
||||
return entryPoint;
|
||||
}
|
||||
for (const key of ['.', 'import'] as const) {
|
||||
if (obj[key]) {
|
||||
return resolveEsmEntryPoint(obj[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import {timing, util} from '@appium/support';
|
||||
import type {DriverClass, ExtensionType, PluginClass} from '@appium/types';
|
||||
import type {ExtClass} from 'appium/types/index.js';
|
||||
import type {ExtClass} from 'appium/types';
|
||||
import {asyncmap} from 'asyncbox';
|
||||
|
||||
import {USE_ALL_PLUGINS} from '../constants.js';
|
||||
import {log} from '../logger.js';
|
||||
import {withManifestLock, zip} from '../utils/index.js';
|
||||
import {DriverConfig} from './driver-config.js';
|
||||
import {Manifest} from './manifest/index.js';
|
||||
import {PluginConfig} from './plugin-config.js';
|
||||
import {USE_ALL_PLUGINS} from '../constants';
|
||||
import {log} from '../logger';
|
||||
import {zip} from '../utils';
|
||||
import {DriverConfig} from './driver-config';
|
||||
import {Manifest} from './manifest';
|
||||
import {PluginConfig} from './plugin-config';
|
||||
|
||||
export type ExtensionConfigs = {
|
||||
driverConfig: DriverConfig;
|
||||
@@ -18,22 +18,6 @@ export type ExtensionConfigs = {
|
||||
export type PluginNameMap = Map<PluginClass, string>;
|
||||
export type DriverNameMap = Map<DriverClass, string>;
|
||||
|
||||
/**
|
||||
* Re-reads `manifest` from disk and revalidates whichever `DriverConfig`/`PluginConfig`
|
||||
* singletons already exist for it, so their derived state (installed extensions, pending
|
||||
* validation summary, {@link DriverConfig}'s duplicate-`automationName` tracking) reflects the
|
||||
* freshly-read data rather than a stale pre-reload snapshot.
|
||||
*
|
||||
* Callers must run this under {@link withManifestLock} -- both because `manifest.read()` may
|
||||
* itself write the manifest (initialization, migration, or sync with installed packages), and
|
||||
* because anything a caller does afterward that depends on the result staying current (e.g.
|
||||
* writing the manifest back out) needs to stay in the same critical section.
|
||||
*/
|
||||
export async function reloadManifest(manifest: Manifest): Promise<void> {
|
||||
await manifest.read();
|
||||
await Promise.all([DriverConfig.getInstance(manifest)?.validate(), PluginConfig.getInstance(manifest)?.validate()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads extensions and creates `ExtensionConfig` instances.
|
||||
*
|
||||
@@ -41,15 +25,15 @@ export async function reloadManifest(manifest: Manifest): Promise<void> {
|
||||
* - Using the parsed extension data, creates/gets the `ExtensionConfig` subclass instances
|
||||
* - Returns these instances
|
||||
*
|
||||
* If `appiumHome` is needed, use `resolveAppiumHome` from `../utils/index.js`.
|
||||
* If `appiumHome` is needed, use `resolveAppiumHome` from the `env` module in `@appium/support`.
|
||||
*/
|
||||
export async function loadExtensions(appiumHome: string): Promise<ExtensionConfigs> {
|
||||
const manifest = Manifest.getInstance(appiumHome);
|
||||
await manifest.read();
|
||||
const driverConfig = DriverConfig.getInstance(manifest) ?? DriverConfig.create(manifest);
|
||||
const pluginConfig = PluginConfig.getInstance(manifest) ?? PluginConfig.create(manifest);
|
||||
|
||||
await withManifestLock(appiumHome, () => reloadManifest(manifest));
|
||||
|
||||
await Promise.all([driverConfig.validate(), pluginConfig.validate()]);
|
||||
return {driverConfig, pluginConfig};
|
||||
}
|
||||
|
||||
@@ -82,7 +66,7 @@ export async function getActivePlugins(
|
||||
? `You don't have any plugins installed yet.`
|
||||
: `Only the following ${
|
||||
Object.keys(pluginConfig.installedExtensions).length === 1 ? `plugin is` : `plugins are`
|
||||
} ` + `available: ${Object.keys(pluginConfig.installedExtensions).join(', ')}`;
|
||||
} ` + `available: ${Object.keys(pluginConfig.installedExtensions)}`;
|
||||
throw new Error(`Could not load the plugin '${pluginName}' because it is not installed. ${suffix}`);
|
||||
}
|
||||
}
|
||||
@@ -113,7 +97,7 @@ export async function getActiveDrivers(
|
||||
? `You don't have any drivers installed yet.`
|
||||
: `Only the following ${
|
||||
Object.keys(driverConfig.installedExtensions).length === 1 ? `driver is` : `drivers are`
|
||||
} ` + `available: ${Object.keys(driverConfig.installedExtensions).join(', ')}`;
|
||||
} ` + `available: ${Object.keys(driverConfig.installedExtensions)}`;
|
||||
throw new Error(`Could not load the driver '${driverName}' because it is not installed. ${suffix}`);
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -1,8 +1,8 @@
|
||||
import type {ManifestDataVersions} from 'appium/types/index.js';
|
||||
import type {ManifestDataVersions} from 'appium/types';
|
||||
|
||||
import {CURRENT_SCHEMA_REV, DRIVER_TYPE, PLUGIN_TYPE} from '../../constants.js';
|
||||
import {log} from '../../logger.js';
|
||||
import type {Manifest} from './manifest.js';
|
||||
import {CURRENT_SCHEMA_REV, DRIVER_TYPE, PLUGIN_TYPE} from '../constants';
|
||||
import {log} from '../logger';
|
||||
import type {Manifest} from './manifest';
|
||||
|
||||
const SCHEMA_REV_3 = 3;
|
||||
const SCHEMA_REV_4 = 4;
|
||||
+12
-76
@@ -1,23 +1,14 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import {fs, util} from '@appium/support';
|
||||
import {env, fs, util} from '@appium/support';
|
||||
import type {DriverType, ExtensionType, PluginType} from '@appium/types';
|
||||
import type {ExtManifest, ExtPackageJson, ExtRecord, InternalMetadata, ManifestData} from 'appium/types/index.js';
|
||||
import {asyncmap} from 'asyncbox';
|
||||
import type {ExtManifest, ExtPackageJson, ExtRecord, InternalMetadata, ManifestData} from 'appium/types';
|
||||
import * as YAML from 'yaml';
|
||||
|
||||
import {CURRENT_SCHEMA_REV, DRIVER_TYPE, PLUGIN_TYPE} from '../../constants.js';
|
||||
import {log} from '../../logger.js';
|
||||
import {
|
||||
hasAppiumDependency as checkHasAppiumDependency,
|
||||
packageDidChange,
|
||||
resolveManifestPath,
|
||||
} from '../../utils/index.js';
|
||||
import {INSTALL_TYPE_DEV, INSTALL_TYPE_NPM} from './install-types.js';
|
||||
import {migrate} from './migrations.js';
|
||||
import {manifestValidator} from './validator.js';
|
||||
|
||||
const MAX_CONCURRENT_FS_TASKS = 10;
|
||||
import {CURRENT_SCHEMA_REV, DRIVER_TYPE, PLUGIN_TYPE} from '../constants';
|
||||
import {packageDidChange} from '../utils';
|
||||
import {INSTALL_TYPE_DEV, INSTALL_TYPE_NPM} from './extension-config';
|
||||
import {migrate} from './manifest-migrations';
|
||||
|
||||
const CONFIG_DATA_DRIVER_KEY = `${DRIVER_TYPE}s` as const;
|
||||
const CONFIG_DATA_PLUGIN_KEY = `${PLUGIN_TYPE}s` as const;
|
||||
@@ -131,25 +122,13 @@ export class Manifest {
|
||||
}
|
||||
}
|
||||
|
||||
if (!shouldWrite) {
|
||||
const {valid, errors} = manifestValidator.validateManifestEnvelope(data);
|
||||
if (!valid) {
|
||||
log.warn(
|
||||
`Appium had trouble validating the extension installation cache file (${manifestPathResolved}); ` +
|
||||
`it will be reset. Specific error(s): ${manifestValidator.describeValidationErrors(errors)}`,
|
||||
);
|
||||
data = structuredClone(INITIAL_MANIFEST_DATA) as ManifestData;
|
||||
shouldWrite = true;
|
||||
}
|
||||
}
|
||||
|
||||
this.#data = data;
|
||||
|
||||
if (!shouldWrite && (data.schemaRev ?? 0) < CURRENT_SCHEMA_REV) {
|
||||
shouldWrite = await migrate(this);
|
||||
}
|
||||
|
||||
const hasAppiumDependency = await checkHasAppiumDependency(this.appiumHome);
|
||||
const hasAppiumDependency = await env.hasAppiumDependency(this.appiumHome);
|
||||
|
||||
if (shouldWrite || (hasAppiumDependency && (await packageDidChange(this.appiumHome)))) {
|
||||
shouldWrite = (await this.syncWithInstalledExtensions(hasAppiumDependency)) || shouldWrite;
|
||||
@@ -231,7 +210,10 @@ export class Manifest {
|
||||
|
||||
const queue: Promise<void>[] = [onMatch(path.join(this.#appiumHome, 'package.json'), true)];
|
||||
|
||||
const filepaths = await findNodeModulesPackageJsons(path.join(this.#appiumHome, 'node_modules'));
|
||||
const filepaths = await fs.glob('node_modules/{*,@*/*}/package.json', {
|
||||
cwd: this.#appiumHome,
|
||||
absolute: true,
|
||||
});
|
||||
for (const filepath of filepaths) {
|
||||
queue.push(onMatch(filepath));
|
||||
}
|
||||
@@ -342,7 +324,7 @@ export class Manifest {
|
||||
|
||||
async #setManifestPath(): Promise<string> {
|
||||
if (!this.#manifestPath) {
|
||||
const resolved = await resolveManifestPath(this.#appiumHome);
|
||||
const resolved = await env.resolveManifestPath(this.#appiumHome);
|
||||
this.#manifestPath = resolved;
|
||||
|
||||
if (path.relative(this.#appiumHome, resolved).startsWith('.')) {
|
||||
@@ -356,52 +338,6 @@ export class Manifest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds `package.json` paths for packages directly under `node_modules` (and one level deeper for
|
||||
* scoped `@foo/bar` packages). Unlike `fs.glob`, this follows symlinks, which is how `npm install
|
||||
* <local-path>` (and `npm link`) install packages.
|
||||
*/
|
||||
async function findNodeModulesPackageJsons(nodeModulesDir: string): Promise<string[]> {
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await fs.readdir(nodeModulesDir);
|
||||
} catch (err) {
|
||||
if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') {
|
||||
return [];
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const pkgJsonPathsByEntry = await asyncmap(
|
||||
entries.filter((entry) => !entry.startsWith('.')),
|
||||
async (entry): Promise<string[]> => {
|
||||
const entryPath = path.join(nodeModulesDir, entry);
|
||||
if (!entry.startsWith('@')) {
|
||||
const pkgJsonPath = path.join(entryPath, 'package.json');
|
||||
return (await fs.exists(pkgJsonPath)) ? [pkgJsonPath] : [];
|
||||
}
|
||||
|
||||
let scopedEntries: string[];
|
||||
try {
|
||||
scopedEntries = await fs.readdir(entryPath);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const scopedPkgJsonPaths = await asyncmap(
|
||||
scopedEntries.filter((scopedEntry) => !scopedEntry.startsWith('.')),
|
||||
async (scopedEntry) => {
|
||||
const pkgJsonPath = path.join(entryPath, scopedEntry, 'package.json');
|
||||
return (await fs.exists(pkgJsonPath)) ? pkgJsonPath : null;
|
||||
},
|
||||
{concurrency: MAX_CONCURRENT_FS_TASKS},
|
||||
);
|
||||
return scopedPkgJsonPaths.filter((pkgJsonPath) => pkgJsonPath !== null);
|
||||
},
|
||||
{concurrency: MAX_CONCURRENT_FS_TASKS},
|
||||
);
|
||||
return pkgJsonPathsByEntry.flat();
|
||||
}
|
||||
|
||||
function isExtension(value: unknown): value is ExtPackageJson<ExtensionType> {
|
||||
return (
|
||||
util.isPlainObject(value) &&
|
||||
@@ -1,11 +0,0 @@
|
||||
export {Manifest} from './manifest.js';
|
||||
export {
|
||||
INSTALL_TYPE_DEV,
|
||||
INSTALL_TYPE_GIT,
|
||||
INSTALL_TYPE_GITHUB,
|
||||
INSTALL_TYPE_LOCAL,
|
||||
INSTALL_TYPE_NPM,
|
||||
INSTALL_TYPES,
|
||||
} from './install-types.js';
|
||||
export type {EnvelopeValidationResult, ExtManifestProblem} from './validator.js';
|
||||
export {manifestValidator} from './validator.js';
|
||||
@@ -1,37 +0,0 @@
|
||||
import type {InstallType} from 'appium/types/index.js';
|
||||
|
||||
/**
|
||||
* "npm" install type
|
||||
* Used when extension was installed by npm package name
|
||||
* @remarks _All_ extensions are installed _by_ `npm`, but only this one means the package name was
|
||||
* used to specify it
|
||||
*/
|
||||
export const INSTALL_TYPE_NPM = 'npm';
|
||||
/**
|
||||
* "local" install type
|
||||
* Used when extension was installed from a local path
|
||||
*/
|
||||
export const INSTALL_TYPE_LOCAL = 'local';
|
||||
/**
|
||||
* "github" install type
|
||||
* Used when extension was installed via GitHub URL
|
||||
*/
|
||||
export const INSTALL_TYPE_GITHUB = 'github';
|
||||
/**
|
||||
* "git" install type
|
||||
* Used when extensions was installed via Git URL
|
||||
*/
|
||||
export const INSTALL_TYPE_GIT = 'git';
|
||||
/**
|
||||
* "dev" install type
|
||||
* Used when automatically detected as a working copy
|
||||
*/
|
||||
export const INSTALL_TYPE_DEV = 'dev';
|
||||
|
||||
export const INSTALL_TYPES = new Set<InstallType>([
|
||||
INSTALL_TYPE_GIT,
|
||||
INSTALL_TYPE_GITHUB,
|
||||
INSTALL_TYPE_LOCAL,
|
||||
INSTALL_TYPE_NPM,
|
||||
INSTALL_TYPE_DEV,
|
||||
]);
|
||||
@@ -1,42 +0,0 @@
|
||||
import type {SchemaObject} from '../../schema/ajv.js';
|
||||
|
||||
/**
|
||||
* Shallow shape of the parsed `extensions.yaml` document. Deliberately permissive about the
|
||||
* shape of individual `drivers`/`plugins` entries (see {@link commonExtManifestProblemsSchema}
|
||||
* and {@link driverExtManifestProblemsSchema}) so that old-but-valid manifest revisions are
|
||||
* never rejected here; that's `Manifest.read()`'s job before per-extension validation runs.
|
||||
*/
|
||||
export const manifestEnvelopeSchema: SchemaObject = {
|
||||
type: 'object',
|
||||
required: ['drivers', 'plugins'],
|
||||
properties: {
|
||||
drivers: {type: 'object'},
|
||||
plugins: {type: 'object'},
|
||||
schemaRev: {type: 'integer'},
|
||||
},
|
||||
};
|
||||
|
||||
/** Fields required of every extension manifest entry, regardless of driver/plugin kind. */
|
||||
export const commonExtManifestProblemsSchema: SchemaObject = {
|
||||
type: 'object',
|
||||
required: ['version', 'pkgName', 'mainClass'],
|
||||
properties: {
|
||||
version: {type: 'string'},
|
||||
pkgName: {type: 'string'},
|
||||
mainClass: {type: 'string'},
|
||||
},
|
||||
};
|
||||
|
||||
/** Additional fields required of driver manifest entries. */
|
||||
export const driverExtManifestProblemsSchema: SchemaObject = {
|
||||
type: 'object',
|
||||
required: ['automationName', 'platformNames'],
|
||||
properties: {
|
||||
automationName: {type: 'string'},
|
||||
platformNames: {
|
||||
type: 'array',
|
||||
minItems: 1,
|
||||
items: {type: 'string'},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -1,168 +0,0 @@
|
||||
import {Ajv} from '../../schema/ajv.js';
|
||||
import type {ErrorObject, ValidateFunction} from '../../schema/ajv.js';
|
||||
import {commonExtManifestProblemsSchema, driverExtManifestProblemsSchema, manifestEnvelopeSchema} from './schema.js';
|
||||
|
||||
export interface EnvelopeValidationResult {
|
||||
valid: boolean;
|
||||
errors: ErrorObject[];
|
||||
}
|
||||
|
||||
export type ExtManifestProblem = {err: string; val: unknown};
|
||||
|
||||
/**
|
||||
* Top-level manifest field an ajv error is about. For `required` errors, ajv reports the missing
|
||||
* field in `params.missingProperty` (since `instancePath` points at the object that's missing it,
|
||||
* not the field itself); for every other keyword, `instancePath` points at the offending field
|
||||
* directly, so its first segment is the field name (ignoring any array index after it, e.g. the
|
||||
* `0` in `/platformNames/0`).
|
||||
*/
|
||||
function topLevelProp(error: ErrorObject): string | undefined {
|
||||
if (error.keyword === 'required') {
|
||||
return error.params.missingProperty as string;
|
||||
}
|
||||
return error.instancePath.split('/').filter(Boolean)[0];
|
||||
}
|
||||
|
||||
/** Whether `errors` includes a failure of the root value itself (e.g. a string/array/null instead of an object). */
|
||||
function hasRootTypeError(errors: ErrorObject[]): boolean {
|
||||
return errors.some((error) => error.instancePath === '' && error.keyword === 'type');
|
||||
}
|
||||
|
||||
const MISSING_PLATFORM_NAMES_ERR = 'Missing or incorrect supported platformNames list.';
|
||||
const MISSING_AUTOMATION_NAME_ERR = 'Missing or incorrect automationName';
|
||||
|
||||
/** Validates parsed `extensions.yaml` and individual extension manifest entries via a dedicated Ajv instance. */
|
||||
class ManifestValidator {
|
||||
private readonly validateEnvelope: ValidateFunction;
|
||||
private readonly validateCommonProblems: ValidateFunction;
|
||||
private readonly validateDriverProblems: ValidateFunction;
|
||||
|
||||
constructor() {
|
||||
// Dedicated instance: manifest validation runs before `AppiumSchema` (lib/schema/schema.ts) is
|
||||
// finalized, so that singleton can't be reused here. No `format` keyword, so no ajv-formats.
|
||||
const ajv = new Ajv({allErrors: true});
|
||||
this.validateEnvelope = ajv.compile(manifestEnvelopeSchema);
|
||||
this.validateCommonProblems = ajv.compile(commonExtManifestProblemsSchema);
|
||||
this.validateDriverProblems = ajv.compile(driverExtManifestProblemsSchema);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the top-level shape of a parsed `extensions.yaml` document (before migration).
|
||||
*
|
||||
* @param data - Result of `YAML.parse()` on the manifest file contents
|
||||
*/
|
||||
validateManifestEnvelope(data: unknown): EnvelopeValidationResult {
|
||||
const valid = Boolean(this.validateEnvelope(data));
|
||||
return {valid, errors: valid ? [] : [...(this.validateEnvelope.errors ?? [])]};
|
||||
}
|
||||
|
||||
/** Human-readable summary of ajv errors, tolerating `message` being unset (it's optional on `ErrorObject`). */
|
||||
describeValidationErrors(errors: ErrorObject[]): string {
|
||||
return errors
|
||||
.map((error) => error.message ?? `${error.keyword} error at "${error.instancePath || '/'}"`)
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocking issues for manifest fields shared by all extensions (version, package name, main class).
|
||||
*
|
||||
* @param extManifest - Manifest entry for one extension
|
||||
*/
|
||||
getCommonManifestProblems(extManifest: unknown): ExtManifestProblem[] {
|
||||
// Stored in a variable: branching on the call directly narrows the negative branch to `never`.
|
||||
const valid: boolean = this.validateCommonProblems(extManifest);
|
||||
if (valid) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const errors = this.validateCommonProblems.errors ?? [];
|
||||
// A root type error means every field is missing; topLevelProp() can't attribute it to one.
|
||||
const props = hasRootTypeError(errors)
|
||||
? new Set(['version', 'pkgName', 'mainClass'])
|
||||
: new Set(errors.map(topLevelProp));
|
||||
|
||||
// Cast once (extManifest may be non-object/null/undefined), then read safely via `?.`.
|
||||
const manifest = extManifest as Record<string, unknown> | null | undefined;
|
||||
const problems: ExtManifestProblem[] = [];
|
||||
|
||||
if (props.has('version')) {
|
||||
problems.push({
|
||||
err: 'Invalid or missing `version` field in my `package.json` and/or `extensions.yaml` (must be a string)',
|
||||
val: manifest?.version,
|
||||
});
|
||||
}
|
||||
if (props.has('pkgName')) {
|
||||
problems.push({
|
||||
err: 'Invalid or missing `name` field in my `package.json` and/or `extensions.yaml` (must be a string)',
|
||||
val: manifest?.pkgName,
|
||||
});
|
||||
}
|
||||
if (props.has('mainClass')) {
|
||||
problems.push({
|
||||
err: 'Invalid or missing `appium.mainClass` field in my `package.json` and/or `mainClass` field in `extensions.yaml` (must be a string)',
|
||||
val: manifest?.mainClass,
|
||||
});
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocking issues for driver-specific manifest fields (automationName, platformNames).
|
||||
* Does not include the cross-driver duplicate-`automationName` check, which needs state
|
||||
* spanning multiple extensions and lives in {@link DriverConfig.getConfigProblems} instead.
|
||||
*
|
||||
* @param extManifest - Manifest entry for one driver
|
||||
*/
|
||||
getDriverManifestProblems(extManifest: unknown): ExtManifestProblem[] {
|
||||
// See the comment in `getCommonManifestProblems` about not narrowing on the call directly.
|
||||
const valid: boolean = this.validateDriverProblems(extManifest);
|
||||
if (valid) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const errors = this.validateDriverProblems.errors ?? [];
|
||||
// See the comment in `getCommonManifestProblems` about casting once and reading via `?.`.
|
||||
const manifest = extManifest as Record<string, unknown> | null | undefined;
|
||||
const platformNames = manifest?.platformNames;
|
||||
const automationName = manifest?.automationName;
|
||||
|
||||
// A root type error means both fields are missing; no per-property error to attribute either to.
|
||||
if (hasRootTypeError(errors)) {
|
||||
return [
|
||||
{err: MISSING_PLATFORM_NAMES_ERR, val: platformNames},
|
||||
{err: MISSING_AUTOMATION_NAME_ERR, val: automationName},
|
||||
];
|
||||
}
|
||||
|
||||
const problems: ExtManifestProblem[] = [];
|
||||
const platformNamesErrors = errors.filter((error) => topLevelProp(error) === 'platformNames');
|
||||
const automationNameErrors = errors.filter((error) => topLevelProp(error) === 'automationName');
|
||||
|
||||
const isMissingOrWrongType = platformNamesErrors.some(
|
||||
(error) => error.keyword === 'required' || (error.keyword === 'type' && error.instancePath === '/platformNames'),
|
||||
);
|
||||
const isEmpty = platformNamesErrors.some((error) => error.keyword === 'minItems');
|
||||
|
||||
if (isMissingOrWrongType) {
|
||||
problems.push({err: MISSING_PLATFORM_NAMES_ERR, val: platformNames});
|
||||
} else if (isEmpty) {
|
||||
problems.push({err: 'Empty platformNames list.', val: platformNames});
|
||||
} else {
|
||||
for (const error of platformNamesErrors) {
|
||||
if (error.keyword === 'type') {
|
||||
const index = Number(error.instancePath.split('/')[2]);
|
||||
problems.push({err: 'Incorrectly formatted platformName.', val: (platformNames as unknown[])[index]});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (automationNameErrors.length) {
|
||||
problems.push({err: MISSING_AUTOMATION_NAME_ERR, val: automationName});
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
}
|
||||
|
||||
export const manifestValidator = new ManifestValidator();
|
||||
@@ -1,11 +1,11 @@
|
||||
import {util} from '@appium/support';
|
||||
import type {PluginType} from '@appium/types';
|
||||
import type {ExtManifest, ExtName, ExtRecord} from 'appium/types/index.js';
|
||||
import type {ExtManifest, ExtName, ExtRecord} from 'appium/types';
|
||||
|
||||
import {PLUGIN_TYPE} from '../constants.js';
|
||||
import {log} from '../logger.js';
|
||||
import {ExtensionConfig} from './extension-config.js';
|
||||
import type {Manifest} from './manifest/index.js';
|
||||
import {PLUGIN_TYPE} from '../constants';
|
||||
import {log} from '../logger';
|
||||
import {ExtensionConfig} from './extension-config';
|
||||
import type {Manifest} from './manifest';
|
||||
|
||||
export class PluginConfig extends ExtensionConfig<PluginType> {
|
||||
private static readonly _instances = new WeakMap<Manifest, PluginConfig>();
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {fs, system, util} from '@appium/support';
|
||||
import type {BuildInfo} from 'appium/types/index.js';
|
||||
import type {BuildInfo} from 'appium/types';
|
||||
import axios from 'axios';
|
||||
import {exec} from 'teen_process';
|
||||
|
||||
import {npmPackage} from '../utils/index.js';
|
||||
import {npmPackage} from '../utils';
|
||||
|
||||
export const APPIUM_VER = npmPackage.version;
|
||||
|
||||
@@ -29,7 +29,7 @@ export async function getGitRev(useGithubApiFallback = false): Promise<string |
|
||||
if (fullGitPath) {
|
||||
try {
|
||||
const {stdout} = await exec(fullGitPath, ['rev-parse', 'HEAD'], {
|
||||
cwd: import.meta.dirname,
|
||||
cwd: __dirname,
|
||||
});
|
||||
return stdout.trim();
|
||||
} catch {}
|
||||
@@ -58,7 +58,7 @@ async function getGitTimestamp(commitSha: string, useGithubApiFallback = false):
|
||||
if (fullGitPath) {
|
||||
try {
|
||||
const {stdout} = await exec(fullGitPath, ['show', '-s', '--format=%ci', commitSha], {
|
||||
cwd: import.meta.dirname,
|
||||
cwd: __dirname,
|
||||
});
|
||||
return stdout.trim();
|
||||
} catch {}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import {errors, isStandardCap, isW3cCaps, processCapabilities} from '@appium/base-driver';
|
||||
import {errors, isW3cCaps, processCapabilities, STANDARD_CAPS} from '@appium/base-driver';
|
||||
import {util} from '@appium/support';
|
||||
import type {BaseDriverCapConstraints, Capabilities, Constraints, NSCapabilities, W3CCapabilities} from '@appium/types';
|
||||
|
||||
import {log as logger} from '../logger.js';
|
||||
import {mapKeys} from '../utils/index.js';
|
||||
import {log as logger} from '../logger';
|
||||
import {mapKeys} from '../utils';
|
||||
|
||||
const W3C_APPIUM_PREFIX = 'appium';
|
||||
const STANDARD_CAPS_LOWERCASE = new Set([...STANDARD_CAPS].map((cap) => cap.toLowerCase()));
|
||||
|
||||
/** Result of successfully parsing W3C capabilities for the inner driver. */
|
||||
export interface ParsedDriverCaps<C extends Constraints = BaseDriverCapConstraints> {
|
||||
@@ -24,7 +25,7 @@ export interface InvalidCaps<C extends Constraints = BaseDriverCapConstraints> {
|
||||
* Creates an error when a session receives non-W3C capabilities.
|
||||
*/
|
||||
export function makeNonW3cCapsError(): Error {
|
||||
return new errors.InvalidArgumentError(
|
||||
return new errors.SessionNotCreatedError(
|
||||
'Session capabilities format must comply to the W3C standard. Make sure your client is up to date. ' +
|
||||
'See https://www.w3.org/TR/webdriver/#new-session for more details.',
|
||||
);
|
||||
@@ -45,6 +46,7 @@ export function parseCapsForInnerDriver<C extends Constraints = BaseDriverCapCon
|
||||
}
|
||||
|
||||
let desiredCaps: Capabilities<C> = {} as Capabilities<C>;
|
||||
// eslint-disable-next-line prefer-const -- assigned in success path after try
|
||||
let processedW3CCapabilities: W3CCapabilities<C> | undefined;
|
||||
|
||||
w3cCapabilities = structuredClone(w3cCapabilities);
|
||||
@@ -52,25 +54,28 @@ export function parseCapsForInnerDriver<C extends Constraints = BaseDriverCapCon
|
||||
|
||||
if (!util.isEmpty(defaultCapabilities)) {
|
||||
for (const [defaultCapKey, defaultCapValue] of Object.entries(defaultCapabilities)) {
|
||||
// alwaysMatch already requires this key. Putting the default on firstMatch would make merge fail.
|
||||
if (
|
||||
util.isPlainObject(w3cCapabilities.alwaysMatch) &&
|
||||
hasOwnCapability(w3cCapabilities.alwaysMatch as Record<string, unknown>, defaultCapKey)
|
||||
) {
|
||||
let isCapAlreadySet = false;
|
||||
for (const firstMatchEntry of w3cCapabilities.firstMatch ?? []) {
|
||||
if (
|
||||
util.isPlainObject(firstMatchEntry) &&
|
||||
hasOwnCapability(firstMatchEntry as Record<string, unknown>, defaultCapKey)
|
||||
) {
|
||||
isCapAlreadySet = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
isCapAlreadySet =
|
||||
isCapAlreadySet ||
|
||||
(util.isPlainObject(w3cCapabilities.alwaysMatch) &&
|
||||
hasOwnCapability(w3cCapabilities.alwaysMatch as Record<string, unknown>, defaultCapKey));
|
||||
if (isCapAlreadySet) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (util.isEmpty(w3cCapabilities.firstMatch)) {
|
||||
w3cCapabilities.firstMatch = [{[defaultCapKey]: defaultCapValue}] as W3CCapabilities<C>['firstMatch'];
|
||||
}
|
||||
for (const firstMatchEntry of w3cCapabilities.firstMatch ?? []) {
|
||||
if (
|
||||
!util.isPlainObject(firstMatchEntry) ||
|
||||
hasOwnCapability(firstMatchEntry as Record<string, unknown>, defaultCapKey)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
(firstMatchEntry as Record<string, unknown>)[defaultCapKey] = defaultCapValue;
|
||||
} else {
|
||||
(w3cCapabilities.firstMatch[0] as Record<string, unknown>)[defaultCapKey] = defaultCapValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,7 +109,9 @@ export function insertAppiumPrefixes<C extends Constraints = BaseDriverCapConstr
|
||||
caps: Capabilities<C>,
|
||||
): NSCapabilities<C> {
|
||||
return mapKeys(caps as Record<string, unknown>, (_, key) =>
|
||||
isStandardCap(String(key)) || String(key).includes(':') ? String(key) : `${W3C_APPIUM_PREFIX}:${key}`,
|
||||
STANDARD_CAPS_LOWERCASE.has(String(key).toLowerCase()) || String(key).includes(':')
|
||||
? String(key)
|
||||
: `${W3C_APPIUM_PREFIX}:${key}`,
|
||||
) as NSCapabilities<C>;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import os from 'node:os';
|
||||
|
||||
export const V4_BROADCAST_IP = '0.0.0.0';
|
||||
export const V6_BROADCAST_IP = '::';
|
||||
|
||||
/**
|
||||
* Returns network interfaces for the given IP family.
|
||||
*
|
||||
* @param family - 4 for IPv4, 6 for IPv6, or null for all.
|
||||
*/
|
||||
export function fetchInterfaces(family: 4 | 6 | null = null): os.NetworkInterfaceInfo[] {
|
||||
let familyValue: (4 | 6 | string)[] | null = null;
|
||||
if (family === 4) {
|
||||
familyValue = [4, 'IPv4'];
|
||||
} else if (family === 6) {
|
||||
familyValue = [6, 'IPv6'];
|
||||
}
|
||||
const ifaces = Object.values(os.networkInterfaces()).filter(Boolean) as os.NetworkInterfaceInfo[][];
|
||||
return ifaces.flat().filter((info) => !familyValue || familyValue.includes(info.family as 4 | 6 | string));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the address is a broadcast IP (0.0.0.0 or ::).
|
||||
*/
|
||||
export function isBroadcastIp(address: string): boolean {
|
||||
return [V4_BROADCAST_IP, V6_BROADCAST_IP, `[${V6_BROADCAST_IP}]`].includes(address);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import {util} from '@appium/support';
|
||||
import type {ExternalDriver} from '@appium/types';
|
||||
|
||||
import type {AppiumDriver} from './appium.js';
|
||||
import {log as logger} from './logger.js';
|
||||
import type {AppiumDriver} from './appium';
|
||||
import {log as logger} from './logger';
|
||||
|
||||
const ALL_DRIVERS_MATCH = '*';
|
||||
const FEATURE_NAME_SEPARATOR = ':';
|
||||
|
||||
@@ -16,8 +16,8 @@ import type {
|
||||
RestMethodsToCommandsMap,
|
||||
} from '@appium/types';
|
||||
|
||||
import type {AppiumDriver} from './appium.js';
|
||||
import {mapValues} from './utils/index.js';
|
||||
import type {AppiumDriver} from './appium';
|
||||
import {mapValues} from './utils';
|
||||
|
||||
/**
|
||||
* Returns available REST and BiDi commands for base, driver and plugins.
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import {log as globalLog, type MessageObject} from '@appium/logger';
|
||||
import type {MessageObject} from '@appium/logger';
|
||||
import globalLog from '@appium/logger';
|
||||
import {fs, util} from '@appium/support';
|
||||
import type {ParsedArgs} from 'appium/types/index.js';
|
||||
import type {ParsedArgs} from 'appium/types';
|
||||
import {LRUCache} from 'lru-cache';
|
||||
import type {Logform, Logger} from 'winston';
|
||||
import {createLogger, format, transports} from 'winston';
|
||||
import type Transport from 'winston-transport';
|
||||
|
||||
import {adler32} from './utils/index.js';
|
||||
import {adler32} from './utils';
|
||||
|
||||
const LEVELS_MAP = {
|
||||
debug: 4,
|
||||
@@ -111,9 +112,8 @@ export async function init(args: ParsedArgs): Promise<void> {
|
||||
}
|
||||
}
|
||||
});
|
||||
// Only Winston produces output; avoid duplicate lines from the logger's default streams
|
||||
// Only Winston produces output; avoid duplicate lines from the logger's default stream
|
||||
globalLog.stream = null;
|
||||
globalLog.errorStream = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -172,10 +172,8 @@ export function parseWebhookUri(
|
||||
}
|
||||
const isSsl = url.protocol === HTTPS_PROTOCOL;
|
||||
const defaultPort = isSsl ? DEFAULT_HTTPS_WEBHOOK_PORT : DEFAULT_HTTP_WEBHOOK_PORT;
|
||||
// http.request looks up `[::1]` as a name and returns ENOTFOUND
|
||||
const host = url.hostname.startsWith('[') && url.hostname.endsWith(']') ? url.hostname.slice(1, -1) : url.hostname;
|
||||
return {
|
||||
host,
|
||||
host: url.hostname,
|
||||
port: url.port ? parseInt(url.port, 10) : defaultPort,
|
||||
path: `${url.pathname}${url.search}`,
|
||||
ssl: isSsl,
|
||||
@@ -206,7 +204,7 @@ async function createTransports(args: ParsedArgs): Promise<Transport[]> {
|
||||
|
||||
// Server args are normalized in main so we only see dest form (`loglevel`).
|
||||
// Fall back to schema default so Winston never sees undefined.
|
||||
const rawLogLevel = args.loglevel ?? 'info';
|
||||
const rawLogLevel = args.loglevel ?? 'debug';
|
||||
|
||||
if (rawLogLevel && rawLogLevel.includes(':')) {
|
||||
// --log-level arg can optionally provide diff logging levels for console and file, separated by a colon
|
||||
@@ -290,9 +288,9 @@ function formatLog(args: ParsedArgs, targetConsole: boolean): Logform.Format {
|
||||
|
||||
return format.printf((info: {timestamp?: string; message?: unknown}) => {
|
||||
if (targetConsole) {
|
||||
return `${args.logTimestamp ? `${info.timestamp} - ` : ''}${info.message as any}`;
|
||||
return `${args.logTimestamp ? `${info.timestamp} - ` : ''}${info.message}`;
|
||||
}
|
||||
return `${info.timestamp} ${info.message as any}`;
|
||||
return `${info.timestamp} ${info.message}`;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+12
-18
@@ -1,20 +1,14 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import './logsink.js'; // must run first: global npmlog / log sink setup (see logsink module)
|
||||
import './logger.js'; // load Appium logger immediately after logsink (order matters for log wiring)
|
||||
import './logsink'; // must run first: global npmlog / log sink setup (see logsink module)
|
||||
import './logger'; // load Appium logger immediately after logsink (order matters for log wiring)
|
||||
import {env} from '@appium/support';
|
||||
import type {AppiumServer} from '@appium/types';
|
||||
import type {
|
||||
Args,
|
||||
CliCommand,
|
||||
CliCommandServer,
|
||||
CliCommandSetupSubcommand,
|
||||
CliExtensionSubcommand,
|
||||
} from 'appium/types/index.js';
|
||||
import type {Args, CliCommand, CliCommandServer, CliCommandSetupSubcommand, CliExtensionSubcommand} from 'appium/types';
|
||||
|
||||
import {AppiumInitializer} from './bootstrap/appium-initializer.js';
|
||||
import {AppiumMainRunner} from './bootstrap/appium-main-runner.js';
|
||||
import type {ExtCommandInitResult, InitResult, ServerInitData} from './bootstrap/init-types.js';
|
||||
import {resolveAppiumHome as resolveAppiumHomeUtil} from './utils/index.js';
|
||||
import {AppiumInitializer} from './bootstrap/appium-initializer';
|
||||
import {AppiumMainRunner} from './bootstrap/appium-main-runner';
|
||||
import type {ExtCommandInitResult, InitResult, ServerInitData} from './bootstrap/init-types';
|
||||
|
||||
const initializer = new AppiumInitializer();
|
||||
const mainRunner = new AppiumMainRunner();
|
||||
@@ -46,16 +40,16 @@ export async function main<
|
||||
}
|
||||
|
||||
// NOTE: backwards compat for scripts referencing `build/lib/main.js` directly.
|
||||
// The executable is `../index.js`, so that module will typically not match here.
|
||||
if (import.meta.main) {
|
||||
// The executable is `../index.js`, so that module will typically be `require.main`.
|
||||
if (require.main === module) {
|
||||
void main();
|
||||
}
|
||||
|
||||
// Re-export helpers from the same package so `import { … } from 'appium'` stays a supported
|
||||
// programmatic API (this file is the package `types` entry). The monorepo does not import these
|
||||
// from `'appium'`; consumers use local paths or `@appium/support`. Dropping them is semver-major.
|
||||
export {readConfigFile} from './bootstrap/config-file.js';
|
||||
export {finalizeSchema, getSchema, validate} from './schema/schema.js';
|
||||
export const resolveAppiumHome = resolveAppiumHomeUtil;
|
||||
export {readConfigFile} from './bootstrap/config-file';
|
||||
export {finalizeSchema, getSchema, validate} from './schema/schema';
|
||||
export const resolveAppiumHome = env.resolveAppiumHome;
|
||||
|
||||
export type {ExtCommandInitResult, InitResult, ServerInitData};
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import AjvImport from 'ajv';
|
||||
import addFormatsImport from 'ajv-formats';
|
||||
|
||||
export type {ErrorObject, KeywordDefinition, SchemaObject, ValidateFunction} from 'ajv';
|
||||
|
||||
// `ajv`/`ajv-formats` are CJS with no ESM types; nodenext types their default imports as the
|
||||
// whole module namespace, so re-derive the real constructor/function types via indexed access
|
||||
// and cast the values to match.
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
|
||||
export type AjvCtor = (typeof import('ajv'))['default'];
|
||||
export type AjvInstance = InstanceType<AjvCtor>;
|
||||
export const Ajv = AjvImport as unknown as AjvCtor;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
|
||||
type AddFormatsFn = (typeof import('ajv-formats'))['default'];
|
||||
export const addFormats = addFormatsImport as unknown as AddFormatsFn;
|
||||
@@ -1,6 +1,6 @@
|
||||
import type {ExtensionType} from '@appium/types';
|
||||
|
||||
import {camelCase, kebabCase} from '../utils/index.js';
|
||||
import {camelCase, kebabCase} from '../utils';
|
||||
|
||||
/**
|
||||
* The original ID of the Appium config schema.
|
||||
|
||||
@@ -8,9 +8,9 @@ import type {
|
||||
CliCommandSetupSubcommand,
|
||||
CliExtensionCommand,
|
||||
CliExtensionSubcommand,
|
||||
} from 'appium/types/index.js';
|
||||
} from 'appium/types';
|
||||
|
||||
import {DRIVER_TYPE, PLUGIN_TYPE, SERVER_SUBCOMMAND, SETUP_SUBCOMMAND} from '../constants.js';
|
||||
import {DRIVER_TYPE, PLUGIN_TYPE, SERVER_SUBCOMMAND, SETUP_SUBCOMMAND} from '../constants';
|
||||
|
||||
type AnyArgs = Args<CliCommand, CliExtensionSubcommand | CliCommandSetupSubcommand | void>;
|
||||
|
||||
|
||||
@@ -2,18 +2,13 @@ import {util} from '@appium/support';
|
||||
import {type ArgumentOptions, ArgumentTypeError} from 'argparse';
|
||||
import type {JSONSchema7, JSONSchema7TypeName} from 'json-schema';
|
||||
|
||||
import {kebabCase} from '../utils/index.js';
|
||||
import type {ArgSpec} from './arg-spec.js';
|
||||
import {
|
||||
parseCsvLine,
|
||||
transformers,
|
||||
type AppiumCliTransformerName,
|
||||
type AppiumJSONSchemaKeywords,
|
||||
} from './cli-transformers.js';
|
||||
import {formatErrors} from './format-errors.js';
|
||||
import {flattenSchema, validate} from './schema.js';
|
||||
|
||||
export type ArgumentDefinitions = Map<[name: string] | [name: string, alias: string], ArgumentOptions>;
|
||||
import type {ArgumentDefinitions} from '../cli/args';
|
||||
import {kebabCase} from '../utils';
|
||||
import type {ArgSpec} from './arg-spec';
|
||||
import {parseCsvLine, transformers} from './cli-transformers';
|
||||
import {formatErrors} from './format-errors';
|
||||
import type {AppiumCliTransformerName, AppiumJSONSchemaKeywords} from './keywords';
|
||||
import {flattenSchema, validate} from './schema';
|
||||
|
||||
type AppiumJSONSchema = AppiumJSONSchemaKeywords & JSONSchema7;
|
||||
type ArgDef = [[string] | [string, string], ArgumentOptions];
|
||||
@@ -69,12 +64,7 @@ function getSchemaValidator<Coerced>(
|
||||
if (util.isEmpty(errors)) {
|
||||
return coerced;
|
||||
}
|
||||
// the error formatter needs the parsed data (not the raw string) to locate errors inside objects
|
||||
const data = util.isPlainObject(coerced) ? coerced : value;
|
||||
const formattedErrors = formatErrors(errors, data, {schemaId});
|
||||
const formattedErrorsStr =
|
||||
typeof formattedErrors === 'string' ? formattedErrors : formattedErrors.map((e) => e.error).join(', ');
|
||||
throw new ArgumentTypeError('\n\n' + formattedErrorsStr);
|
||||
throw new ArgumentTypeError('\n\n' + formatErrors(errors, value, {schemaId}));
|
||||
};
|
||||
}
|
||||
|
||||
@@ -114,15 +104,13 @@ function subSchemaToArgDef(subSchema: AppiumJSONSchema, argSpec: ArgSpec): ArgDe
|
||||
break;
|
||||
}
|
||||
case TYPENAMES.OBJECT: {
|
||||
argTypeFunction = getSchemaValidator(argSpec, (value: string) => {
|
||||
argTypeFunction = (value: string) => {
|
||||
const o = transformers.json(value);
|
||||
if (!util.isPlainObject(o)) {
|
||||
throw new ArgumentTypeError(
|
||||
`'${util.truncateString(JSON.stringify(o), {length: 100})}' must be a plain object`,
|
||||
);
|
||||
throw new ArgumentTypeError(`'${util.truncateString(String(o), {length: 100})}' must be a plain object`);
|
||||
}
|
||||
return o;
|
||||
});
|
||||
};
|
||||
break;
|
||||
}
|
||||
case TYPENAMES.ARRAY: {
|
||||
@@ -143,7 +131,7 @@ function subSchemaToArgDef(subSchema: AppiumJSONSchema, argSpec: ArgSpec): ArgDe
|
||||
}
|
||||
case TYPENAMES.NULL:
|
||||
default: {
|
||||
throw new TypeError(`Schema property "${arg}": \`${JSON.stringify(type)}\` type unknown or disallowed`);
|
||||
throw new TypeError(`Schema property "${arg}": \`${type}\` type unknown or disallowed`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -70,17 +70,6 @@ export const transformers = {
|
||||
},
|
||||
} as const;
|
||||
|
||||
export type AppiumCliTransformerName = keyof typeof transformers;
|
||||
|
||||
export interface AppiumJSONSchemaKeywords {
|
||||
appiumCliDest?: string;
|
||||
appiumCliDescription?: string;
|
||||
appiumCliAliases?: string[];
|
||||
appiumCliIgnored?: boolean;
|
||||
appiumCliTransformer?: AppiumCliTransformerName;
|
||||
appiumDeprecated?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `filepath` is an existing regular file.
|
||||
*
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
import type {NormalizedAppiumConfig} from '@appium/types';
|
||||
import betterAjvErrorsImport, {type IOutputError} from '@sidvind/better-ajv-errors';
|
||||
import betterAjvErrors, {type IOutputError} from '@sidvind/better-ajv-errors';
|
||||
import type {ErrorObject} from 'ajv';
|
||||
|
||||
import type {ErrorObject} from './ajv.js';
|
||||
import {getSchema} from './schema.js';
|
||||
|
||||
// `@sidvind/better-ajv-errors` has no `"type"` field in its own package.json, so TS's
|
||||
// nodenext resolution infers its extensionless `typings.d.ts` as CJS-format and types the
|
||||
// default import as the whole module namespace rather than the actual default export.
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
|
||||
type BetterAjvErrorsFn = (typeof import('@sidvind/better-ajv-errors'))['default'];
|
||||
const betterAjvErrors = betterAjvErrorsImport as unknown as BetterAjvErrorsFn;
|
||||
import {getSchema} from './schema';
|
||||
|
||||
/**
|
||||
* The string should be a raw JSON string.
|
||||
|
||||
@@ -1,32 +1,4 @@
|
||||
export type {ArgumentDefinitions} from './cli-args.js';
|
||||
export {toParserArgs} from './cli-args.js';
|
||||
export {
|
||||
isDriverCommandArgs,
|
||||
isExtensionCommandArgs,
|
||||
isPluginCommandArgs,
|
||||
isServerCommandArgs,
|
||||
isSetupCommandArgs,
|
||||
} from './cli-args-guards.js';
|
||||
export type {FormatConfigErrorsOptions, RawJson} from './format-errors.js';
|
||||
export {formatErrors} from './format-errors.js';
|
||||
export {
|
||||
ALLOWED_SCHEMA_EXTENSIONS,
|
||||
finalizeSchema,
|
||||
flattenSchema,
|
||||
getAllArgSpecs,
|
||||
getArgSpec,
|
||||
getDefaultsForExtension,
|
||||
getDefaultsForSchema,
|
||||
getSchema,
|
||||
hasArgSpec,
|
||||
isAllowedSchemaFileExtension,
|
||||
isFinalized,
|
||||
registerSchema,
|
||||
resetSchema,
|
||||
RoachHotelMap,
|
||||
SchemaFinalizationError,
|
||||
SchemaNameConflictError,
|
||||
SchemaUnknownSchemaError,
|
||||
SchemaUnsupportedSchemaError,
|
||||
validate,
|
||||
} from './schema.js';
|
||||
export * from './cli-args';
|
||||
export * from './cli-args-guards';
|
||||
export * from './format-errors';
|
||||
export * from './schema';
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
import type {KeywordDefinition} from './ajv.js';
|
||||
import {transformers} from './cli-transformers.js';
|
||||
import type {AppiumCliTransformerName} from './cli-transformers.js';
|
||||
import type {KeywordDefinition} from 'ajv';
|
||||
|
||||
import {transformers} from './cli-transformers';
|
||||
|
||||
export type AppiumCliTransformerName = keyof typeof transformers;
|
||||
|
||||
export interface AppiumJSONSchemaKeywords {
|
||||
appiumCliDest?: string;
|
||||
appiumCliDescription?: string;
|
||||
appiumCliAliases?: string[];
|
||||
appiumCliIgnored?: boolean;
|
||||
appiumCliTransformer?: AppiumCliTransformerName;
|
||||
appiumDeprecated?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collection of keyword definitions to add to the singleton `Ajv` instance.
|
||||
|
||||
@@ -3,13 +3,13 @@ import path from 'node:path';
|
||||
import {AppiumConfigJsonSchema} from '@appium/schema';
|
||||
import {util} from '@appium/support';
|
||||
import type {ExtensionType} from '@appium/types';
|
||||
import Ajv, {type ErrorObject, type SchemaObject, type ValidateFunction} from 'ajv';
|
||||
import addFormats from 'ajv-formats';
|
||||
|
||||
import {DRIVER_TYPE, PLUGIN_TYPE} from '../constants.js';
|
||||
import {bindAll, kebabCase, omitKeys, setPath} from '../utils/index.js';
|
||||
import {addFormats, Ajv} from './ajv.js';
|
||||
import type {AjvInstance, ErrorObject, SchemaObject, ValidateFunction} from './ajv.js';
|
||||
import {APPIUM_CONFIG_SCHEMA_ID, ArgSpec, SERVER_PROP_NAME} from './arg-spec.js';
|
||||
import {keywords} from './keywords.js';
|
||||
import {DRIVER_TYPE, PLUGIN_TYPE} from '../constants';
|
||||
import {bindAll, kebabCase, omitKeys, setPath} from '../utils';
|
||||
import {APPIUM_CONFIG_SCHEMA_ID, ArgSpec, SERVER_PROP_NAME} from './arg-spec';
|
||||
import {keywords} from './keywords';
|
||||
|
||||
type StrictSchemaObject = SchemaObject & {additionalProperties: false};
|
||||
type FlattenedSchema = {schema: SchemaObject; argSpec: ArgSpec}[];
|
||||
@@ -17,7 +17,6 @@ type ArgSpecDefaultValue = ArgSpec['defaultValue'];
|
||||
type NestedArgSpecDefaultValue = Record<string, Record<string, ArgSpecDefaultValue>>;
|
||||
type DefaultValues<Flattened extends boolean | undefined> = Record<
|
||||
string,
|
||||
// oxlint-disable-next-line typescript/no-redundant-type-constituents
|
||||
Flattened extends true ? ArgSpecDefaultValue : ArgSpecDefaultValue | NestedArgSpecDefaultValue
|
||||
>;
|
||||
type AllowedSchemaExtension = '.json' | '.js' | '.cjs';
|
||||
@@ -33,6 +32,7 @@ export class RoachHotelMap<K, V> extends Map<K, V> {
|
||||
return super.set(key, value);
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
override delete(_key: K): boolean {
|
||||
return false;
|
||||
}
|
||||
@@ -53,7 +53,7 @@ class AppiumSchema {
|
||||
[DRIVER_TYPE]: new Map(),
|
||||
[PLUGIN_TYPE]: new Map(),
|
||||
};
|
||||
#ajv: AjvInstance;
|
||||
#ajv: Ajv;
|
||||
#finalizedSchemas: Record<string, StrictSchemaObject> | null = null;
|
||||
|
||||
private constructor() {
|
||||
@@ -103,7 +103,7 @@ class AppiumSchema {
|
||||
/**
|
||||
* Configures and creates an Ajv instance.
|
||||
*/
|
||||
private static _instantiateAjv(): AjvInstance {
|
||||
private static _instantiateAjv(): Ajv {
|
||||
const ajv = addFormats(
|
||||
new Ajv({
|
||||
// without this not much validation actually happens
|
||||
@@ -169,23 +169,16 @@ class AppiumSchema {
|
||||
>) {
|
||||
for (const [extName, schema] of extensionSchemas.entries()) {
|
||||
const $ref = ArgSpec.toSchemaBaseRef(extType, extName);
|
||||
// Clone rather than mutate the registered schema in place: extensions whose schema is
|
||||
// freshly re-parsed on every manifest reload (an inline object, as opposed to one
|
||||
// `import()`ed from a file, which Node's module cache returns by the same reference every
|
||||
// time) would otherwise stop deep-equaling their own registered copy on a later
|
||||
// `registerSchema()` call, once this injects `$id`/`additionalProperties` -- causing a
|
||||
// false "conflicts with an existing schema" error and dropping the extension entirely.
|
||||
const finalizedSchema = structuredClone(schema) as StrictSchemaObject;
|
||||
(finalizedSchema as any).$id = $ref;
|
||||
(finalizedSchema as any).additionalProperties = false;
|
||||
(schema as any).$id = $ref;
|
||||
(schema as any).additionalProperties = false;
|
||||
baseSchema.properties.server.properties[extType].properties[extName] = {
|
||||
$ref,
|
||||
$comment: extName,
|
||||
};
|
||||
await ajv.validateSchema(finalizedSchema, true);
|
||||
addArgSpecs((finalizedSchema as any).properties, extType, extName);
|
||||
ajv.addSchema(finalizedSchema, $ref);
|
||||
finalizedSchemas[$ref] = finalizedSchema;
|
||||
await ajv.validateSchema(schema, true);
|
||||
addArgSpecs((schema as any).properties, extType, extName);
|
||||
ajv.addSchema(schema, $ref);
|
||||
finalizedSchemas[$ref] = schema as StrictSchemaObject;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,198 +0,0 @@
|
||||
import {createHash} from 'node:crypto';
|
||||
import {homedir} from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import {fs, util} from '@appium/support';
|
||||
import * as semver from 'semver';
|
||||
|
||||
import {type NormalizedPackageJson, readPackage} from './read-package.js';
|
||||
|
||||
/**
|
||||
* Path to the default `APPIUM_HOME` dir (`~/.appium`).
|
||||
*/
|
||||
export const DEFAULT_APPIUM_HOME: string = path.resolve(homedir(), '.appium');
|
||||
|
||||
/**
|
||||
* Basename of extension manifest file.
|
||||
*/
|
||||
export const MANIFEST_BASENAME = 'extensions.yaml';
|
||||
|
||||
/**
|
||||
* Relative path to extension manifest file from `APPIUM_HOME`.
|
||||
*/
|
||||
export const MANIFEST_RELATIVE_PATH = path.join('node_modules', '.cache', 'appium', MANIFEST_BASENAME);
|
||||
|
||||
/**
|
||||
* Resolves `true` if an `appium` dependency can be found somewhere in the given `cwd`.
|
||||
*/
|
||||
export async function hasAppiumDependency(cwd: string): Promise<boolean> {
|
||||
return Boolean(await findAppiumDependencyPackage(cwd));
|
||||
}
|
||||
|
||||
/**
|
||||
* Given `cwd`, use `npm` to find the closest package _or workspace root_, and return the path if the root depends upon `appium`.
|
||||
*
|
||||
* Looks at `dependencies` and `devDependencies` for `appium`.
|
||||
*/
|
||||
export const findAppiumDependencyPackage = util.memoize(async function findAppiumDependencyPackage(
|
||||
cwd: string = process.cwd(),
|
||||
acceptableVersionRange: string | semver.Range = '>=2.0.0-beta',
|
||||
): Promise<string | undefined> {
|
||||
const readPkg = async (root: string): Promise<string | undefined> => {
|
||||
let pkg: NormalizedPackageJson | undefined;
|
||||
try {
|
||||
pkg = await readPackageInDir(root);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (!pkg) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const version = semver.minVersion(
|
||||
String(pkg.dependencies?.appium ?? pkg.devDependencies?.appium ?? pkg.peerDependencies?.appium),
|
||||
);
|
||||
return version && semver.satisfies(version, acceptableVersionRange, {includePrerelease: true}) ? root : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
let currentDir = path.resolve(cwd);
|
||||
let isAtFsRoot = false;
|
||||
while (!isAtFsRoot) {
|
||||
const result = await readPkg(currentDir);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
currentDir = path.dirname(currentDir);
|
||||
isAtFsRoot = currentDir.length <= path.dirname(currentDir).length;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
/**
|
||||
* Read a `package.json` in dir `cwd`. If none is found, resolves with `undefined`.
|
||||
* @returns Parsed package data, or `undefined` when `package.json` is missing in `cwd`
|
||||
*/
|
||||
export const readPackageInDir = util.memoize(async function _readPackageInDir(
|
||||
cwd: string,
|
||||
): Promise<NormalizedPackageJson | undefined> {
|
||||
try {
|
||||
return await readPackage({cwd, normalize: true});
|
||||
} catch (err) {
|
||||
if (isMissingPackageJsonError(err)) {
|
||||
return undefined;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
|
||||
function isMissingPackageJsonError(err: unknown): boolean {
|
||||
return err instanceof Error && 'code' in err && (err as NodeJS.ErrnoException).code === 'ENOENT';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines location of Appium's "home" dir
|
||||
*
|
||||
* - If `APPIUM_HOME` is set in the environment, use that
|
||||
* - If we find a `package.json` in or above `cwd` and it has an `appium` dependency, use that.
|
||||
*
|
||||
* All returned paths will be absolute.
|
||||
*/
|
||||
export const resolveAppiumHome = util.memoize(async function _resolveAppiumHome(
|
||||
cwd: string = process.cwd(),
|
||||
): Promise<string> {
|
||||
if (!path.isAbsolute(cwd)) {
|
||||
throw new TypeError('`cwd` parameter must be an absolute path');
|
||||
}
|
||||
|
||||
if (process.env.APPIUM_HOME) {
|
||||
return path.resolve(cwd, process.env.APPIUM_HOME);
|
||||
}
|
||||
|
||||
return (await findAppiumDependencyPackage(cwd)) ?? DEFAULT_APPIUM_HOME;
|
||||
});
|
||||
|
||||
/**
|
||||
* Figure out manifest path based on `appiumHome`.
|
||||
*
|
||||
* The assumption is that, if `appiumHome` has been provided, it was resolved via {@link resolveAppiumHome `resolveAppiumHome()`}! If unsure,
|
||||
* don't pass a parameter and let `resolveAppiumHome()` handle it.
|
||||
*/
|
||||
export const resolveManifestPath = util.memoize(async function _resolveManifestPath(
|
||||
appiumHome?: string,
|
||||
): Promise<string> {
|
||||
return path.join(appiumHome ?? (await resolveAppiumHome()), MANIFEST_RELATIVE_PATH);
|
||||
});
|
||||
|
||||
/**
|
||||
* Relative path, from the user's home dir, to the directory holding manifest lockfiles.
|
||||
*
|
||||
* Deliberately `.cache/appium/locks`, NOT under {@link DEFAULT_APPIUM_HOME} (`~/.appium`): a
|
||||
* custom `APPIUM_HOME` is common, but the *default* one lives at exactly that path, so rooting
|
||||
* locks under it would reintroduce the read-only-`APPIUM_HOME` failure this is meant to avoid
|
||||
* whenever a preinstalled default home is made read-only as a whole.
|
||||
*/
|
||||
const MANIFEST_LOCKS_DIRNAME = path.join('.cache', 'appium', 'locks');
|
||||
|
||||
/**
|
||||
* Figure out the extension manifest lockfile path for `appiumHome`.
|
||||
*
|
||||
* Deliberately lives in a fixed location under the user's home dir (see
|
||||
* {@link MANIFEST_LOCKS_DIRNAME}), keyed by a hash of `appiumHome`'s canonicalized
|
||||
* (symlink-resolved) real path, rather than:
|
||||
* - alongside the manifest itself: a directory being unwritable doesn't imply the manifest
|
||||
* *file* inside it is (directory permissions gate creating/removing entries, not overwriting
|
||||
* an existing one), so a lock colocated with the manifest couldn't be relied on to actually be
|
||||
* creatable exactly when protection is needed most -- see the read-only `APPIUM_HOME` case.
|
||||
* - the OS temp dir: its value depends on `TMPDIR`/platform/user defaults, which can differ
|
||||
* between two processes protecting the very same `appiumHome`, silently defeating locking.
|
||||
* - the raw (non-canonicalized) `appiumHome` string: a symlink alias and its real target
|
||||
* otherwise hash to different lock identities despite being the same location on disk.
|
||||
*
|
||||
* This targets same-user coordination (concurrent CLI/server processes for one user); a single
|
||||
* `APPIUM_HOME` deliberately shared across *different* users' processes would need its lock
|
||||
* pointed at a location those users jointly have write access to, which is out of scope here.
|
||||
*
|
||||
* See caveat on {@link resolveManifestPath} about pre-resolving `appiumHome`.
|
||||
*/
|
||||
export const resolveManifestLockfilePath = util.memoize(async function _resolveManifestLockfilePath(
|
||||
appiumHome?: string,
|
||||
): Promise<string> {
|
||||
const rawHome = appiumHome ?? (await resolveAppiumHome());
|
||||
const resolvedHome = await fs.realpath(rawHome).catch(() => path.resolve(rawHome));
|
||||
const homeHash = createHash('sha256').update(resolvedHome).digest('hex').slice(0, 32);
|
||||
return path.join(homedir(), MANIFEST_LOCKS_DIRNAME, `${homeHash}.lock`);
|
||||
});
|
||||
|
||||
/**
|
||||
* Runs `behavior` under the cross-process lock guarding the extension manifest for `appiumHome`,
|
||||
* so callers can't race each other's manifest reads/writes. Covers the *entire* read-modify-write
|
||||
* cycle a caller needs protected -- e.g. a manifest reload plus whatever depends on it staying
|
||||
* current, such as re-validating extension configs or writing the manifest back out.
|
||||
*/
|
||||
export async function withManifestLock<T>(appiumHome: string, behavior: () => Promise<T> | T): Promise<T> {
|
||||
const lockFile = await resolveManifestLockfilePath(appiumHome);
|
||||
// The locks directory lives under the user's home dir, independent of `appiumHome`'s own
|
||||
// permissions, but may not exist yet on first use.
|
||||
await fs.mkdirp(path.dirname(lockFile));
|
||||
let acquired = false;
|
||||
try {
|
||||
return await util.getLockFileGuard<T>(lockFile)(() => {
|
||||
acquired = true;
|
||||
return behavior();
|
||||
});
|
||||
} catch (err) {
|
||||
if (!acquired && err instanceof Error && (err.cause as NodeJS.ErrnoException | undefined)?.code === 'EEXIST') {
|
||||
// A timeout does not prove the lock is abandoned. Never remove a potentially active lock.
|
||||
throw new Error(
|
||||
`${err.message} Another process may still be using APPIUM_HOME '${appiumHome}'. ` +
|
||||
`If a previous process exited unexpectedly, stop all Appium servers and extension CLI ` +
|
||||
`commands using this APPIUM_HOME before manually removing '${lockFile}', then retry.`,
|
||||
{cause: err},
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,6 @@
|
||||
export {
|
||||
DEFAULT_APPIUM_HOME,
|
||||
MANIFEST_BASENAME,
|
||||
MANIFEST_RELATIVE_PATH,
|
||||
findAppiumDependencyPackage,
|
||||
hasAppiumDependency,
|
||||
resolveAppiumHome,
|
||||
resolveManifestLockfilePath,
|
||||
resolveManifestPath,
|
||||
withManifestLock,
|
||||
} from './env.js';
|
||||
export {adler32} from './hash.js';
|
||||
export {isPackageChanged} from './is-package-changed.js';
|
||||
export type {IsPackageChangedOptions, IsPackageChangedResult} from './is-package-changed.js';
|
||||
export {npm, resolveFrom} from './npm.js';
|
||||
export type {ExecOpts, InstallPackageOpts, NpmExecResult, NpmInstallReceipt} from './npm.js';
|
||||
export {adler32} from './hash';
|
||||
export {isPackageChanged} from './is-package-changed';
|
||||
export type {IsPackageChangedOptions, IsPackageChangedResult} from './is-package-changed';
|
||||
export {
|
||||
bindAll,
|
||||
camelCase,
|
||||
@@ -30,6 +17,7 @@ export {
|
||||
pull,
|
||||
setPath,
|
||||
zip,
|
||||
} from './object.js';
|
||||
export {packageDidChange} from './package-changed.js';
|
||||
export {appiumPackageRoot, npmPackage} from './package-json.js';
|
||||
} from './object';
|
||||
export {packageDidChange} from './package-changed';
|
||||
export {appiumPackageRoot, npmPackage} from './package-json';
|
||||
export {resolveFrom} from './resolve-from';
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user