appium-android-driver 5.14.7 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/build/lib/commands/actions.d.ts +6 -224
  3. package/build/lib/commands/actions.d.ts.map +1 -1
  4. package/build/lib/commands/actions.js +306 -405
  5. package/build/lib/commands/actions.js.map +1 -1
  6. package/build/lib/commands/alert.d.ts +7 -9
  7. package/build/lib/commands/alert.d.ts.map +1 -1
  8. package/build/lib/commands/alert.js +24 -18
  9. package/build/lib/commands/alert.js.map +1 -1
  10. package/build/lib/commands/app-management.d.ts +7 -313
  11. package/build/lib/commands/app-management.d.ts.map +1 -1
  12. package/build/lib/commands/app-management.js +135 -293
  13. package/build/lib/commands/app-management.js.map +1 -1
  14. package/build/lib/commands/context.d.ts +8 -92
  15. package/build/lib/commands/context.d.ts.map +1 -1
  16. package/build/lib/commands/context.js +381 -439
  17. package/build/lib/commands/context.js.map +1 -1
  18. package/build/lib/commands/element.d.ts +8 -35
  19. package/build/lib/commands/element.d.ts.map +1 -1
  20. package/build/lib/commands/element.js +153 -136
  21. package/build/lib/commands/element.js.map +1 -1
  22. package/build/lib/commands/emu-console.d.ts +6 -48
  23. package/build/lib/commands/emu-console.d.ts.map +1 -1
  24. package/build/lib/commands/emu-console.js +19 -34
  25. package/build/lib/commands/emu-console.js.map +1 -1
  26. package/build/lib/commands/execute.d.ts +6 -5
  27. package/build/lib/commands/execute.d.ts.map +1 -1
  28. package/build/lib/commands/execute.js +77 -66
  29. package/build/lib/commands/execute.js.map +1 -1
  30. package/build/lib/commands/file-actions.d.ts +7 -128
  31. package/build/lib/commands/file-actions.d.ts.map +1 -1
  32. package/build/lib/commands/file-actions.js +183 -219
  33. package/build/lib/commands/file-actions.js.map +1 -1
  34. package/build/lib/commands/find.d.ts +8 -12
  35. package/build/lib/commands/find.d.ts.map +1 -1
  36. package/build/lib/commands/find.js +19 -23
  37. package/build/lib/commands/find.js.map +1 -1
  38. package/build/lib/commands/general.d.ts +9 -132
  39. package/build/lib/commands/general.d.ts.map +1 -1
  40. package/build/lib/commands/general.js +281 -312
  41. package/build/lib/commands/general.js.map +1 -1
  42. package/build/lib/commands/ime.d.ts +7 -10
  43. package/build/lib/commands/ime.d.ts.map +1 -1
  44. package/build/lib/commands/ime.js +47 -35
  45. package/build/lib/commands/ime.js.map +1 -1
  46. package/build/lib/commands/index.d.ts +27 -2
  47. package/build/lib/commands/index.d.ts.map +1 -1
  48. package/build/lib/commands/index.js +41 -19
  49. package/build/lib/commands/index.js.map +1 -1
  50. package/build/lib/commands/intent.d.ts +7 -417
  51. package/build/lib/commands/intent.d.ts.map +1 -1
  52. package/build/lib/commands/intent.js +104 -216
  53. package/build/lib/commands/intent.js.map +1 -1
  54. package/build/lib/commands/keyboard.d.ts +6 -5
  55. package/build/lib/commands/keyboard.d.ts.map +1 -1
  56. package/build/lib/commands/keyboard.js +16 -8
  57. package/build/lib/commands/keyboard.js.map +1 -1
  58. package/build/lib/commands/log.d.ts +7 -44
  59. package/build/lib/commands/log.d.ts.map +1 -1
  60. package/build/lib/commands/log.js +146 -108
  61. package/build/lib/commands/log.js.map +1 -1
  62. package/build/lib/commands/media-projection.d.ts +7 -143
  63. package/build/lib/commands/media-projection.d.ts.map +1 -1
  64. package/build/lib/commands/media-projection.js +113 -140
  65. package/build/lib/commands/media-projection.js.map +1 -1
  66. package/build/lib/commands/mixins.d.ts +740 -0
  67. package/build/lib/commands/mixins.d.ts.map +1 -0
  68. package/build/lib/commands/mixins.js +19 -0
  69. package/build/lib/commands/mixins.js.map +1 -0
  70. package/build/lib/commands/network.d.ts +7 -138
  71. package/build/lib/commands/network.d.ts.map +1 -1
  72. package/build/lib/commands/network.js +212 -254
  73. package/build/lib/commands/network.js.map +1 -1
  74. package/build/lib/commands/performance.d.ts +24 -70
  75. package/build/lib/commands/performance.d.ts.map +1 -1
  76. package/build/lib/commands/performance.js +144 -100
  77. package/build/lib/commands/performance.js.map +1 -1
  78. package/build/lib/commands/permissions.d.ts +8 -92
  79. package/build/lib/commands/permissions.d.ts.map +1 -1
  80. package/build/lib/commands/permissions.js +75 -87
  81. package/build/lib/commands/permissions.js.map +1 -1
  82. package/build/lib/commands/recordscreen.d.ts +7 -193
  83. package/build/lib/commands/recordscreen.d.ts.map +1 -1
  84. package/build/lib/commands/recordscreen.js +151 -182
  85. package/build/lib/commands/recordscreen.js.map +1 -1
  86. package/build/lib/commands/shell.d.ts +7 -7
  87. package/build/lib/commands/shell.d.ts.map +1 -1
  88. package/build/lib/commands/shell.js +40 -33
  89. package/build/lib/commands/shell.js.map +1 -1
  90. package/build/lib/commands/streamscreen.d.ts +9 -103
  91. package/build/lib/commands/streamscreen.d.ts.map +1 -1
  92. package/build/lib/commands/streamscreen.js +261 -218
  93. package/build/lib/commands/streamscreen.js.map +1 -1
  94. package/build/lib/commands/system-bars.d.ts +22 -90
  95. package/build/lib/commands/system-bars.d.ts.map +1 -1
  96. package/build/lib/commands/system-bars.js +76 -74
  97. package/build/lib/commands/system-bars.js.map +1 -1
  98. package/build/lib/commands/touch.d.ts +10 -29
  99. package/build/lib/commands/touch.d.ts.map +1 -1
  100. package/build/lib/commands/touch.js +301 -285
  101. package/build/lib/commands/touch.js.map +1 -1
  102. package/build/lib/commands/types.d.ts +978 -0
  103. package/build/lib/commands/types.d.ts.map +1 -0
  104. package/build/lib/commands/types.js +3 -0
  105. package/build/lib/commands/types.js.map +1 -0
  106. package/build/lib/constraints.d.ts +291 -0
  107. package/build/lib/constraints.d.ts.map +1 -0
  108. package/build/lib/{desired-caps.js → constraints.js} +103 -102
  109. package/build/lib/constraints.js.map +1 -0
  110. package/build/lib/driver.d.ts +68 -37
  111. package/build/lib/driver.d.ts.map +1 -1
  112. package/build/lib/driver.js +123 -80
  113. package/build/lib/driver.js.map +1 -1
  114. package/build/lib/helpers/android.d.ts +164 -0
  115. package/build/lib/helpers/android.d.ts.map +1 -0
  116. package/build/lib/helpers/android.js +819 -0
  117. package/build/lib/helpers/android.js.map +1 -0
  118. package/build/lib/helpers/index.d.ts +7 -0
  119. package/build/lib/helpers/index.d.ts.map +1 -0
  120. package/build/lib/helpers/index.js +29 -0
  121. package/build/lib/helpers/index.js.map +1 -0
  122. package/build/lib/helpers/types.d.ts +121 -0
  123. package/build/lib/helpers/types.d.ts.map +1 -0
  124. package/build/lib/helpers/types.js +3 -0
  125. package/build/lib/helpers/types.js.map +1 -0
  126. package/build/lib/helpers/unlock.d.ts +32 -0
  127. package/build/lib/helpers/unlock.d.ts.map +1 -0
  128. package/build/lib/helpers/unlock.js +273 -0
  129. package/build/lib/helpers/unlock.js.map +1 -0
  130. package/build/lib/helpers/webview.d.ts +74 -0
  131. package/build/lib/helpers/webview.d.ts.map +1 -0
  132. package/build/lib/helpers/webview.js +421 -0
  133. package/build/lib/helpers/webview.js.map +1 -0
  134. package/build/lib/index.d.ts +9 -0
  135. package/build/lib/index.d.ts.map +1 -0
  136. package/build/lib/index.js +37 -0
  137. package/build/lib/index.js.map +1 -0
  138. package/build/lib/method-map.d.ts +0 -8
  139. package/build/lib/method-map.d.ts.map +1 -1
  140. package/build/lib/method-map.js +63 -74
  141. package/build/lib/method-map.js.map +1 -1
  142. package/build/lib/stubs.d.ts +0 -1
  143. package/build/lib/stubs.d.ts.map +1 -1
  144. package/build/lib/stubs.js +1 -0
  145. package/build/lib/stubs.js.map +1 -1
  146. package/build/lib/utils.d.ts +1 -1
  147. package/build/lib/utils.d.ts.map +1 -1
  148. package/lib/commands/actions.js +351 -464
  149. package/lib/commands/alert.js +27 -17
  150. package/lib/commands/app-management.js +156 -314
  151. package/lib/commands/context.js +457 -441
  152. package/lib/commands/element.js +201 -157
  153. package/lib/commands/emu-console.js +25 -45
  154. package/lib/commands/execute.js +106 -90
  155. package/lib/commands/file-actions.js +222 -240
  156. package/lib/commands/find.ts +103 -0
  157. package/lib/commands/general.js +327 -339
  158. package/lib/commands/ime.js +50 -34
  159. package/lib/commands/{index.js → index.ts} +20 -24
  160. package/lib/commands/intent.js +108 -249
  161. package/lib/commands/keyboard.js +20 -8
  162. package/lib/commands/log.js +172 -116
  163. package/lib/commands/media-projection.js +134 -161
  164. package/lib/commands/mixins.ts +966 -0
  165. package/lib/commands/network.js +252 -281
  166. package/lib/commands/performance.js +203 -132
  167. package/lib/commands/permissions.js +108 -109
  168. package/lib/commands/recordscreen.js +212 -209
  169. package/lib/commands/shell.js +51 -40
  170. package/lib/commands/streamscreen.js +355 -289
  171. package/lib/commands/system-bars.js +92 -83
  172. package/lib/commands/touch.js +357 -294
  173. package/lib/commands/types.ts +1097 -0
  174. package/lib/{desired-caps.js → constraints.ts} +106 -103
  175. package/lib/{driver.js → driver.ts} +278 -132
  176. package/lib/helpers/android.ts +1143 -0
  177. package/lib/helpers/index.ts +6 -0
  178. package/lib/helpers/types.ts +134 -0
  179. package/lib/helpers/unlock.ts +329 -0
  180. package/lib/helpers/webview.ts +582 -0
  181. package/lib/index.ts +18 -0
  182. package/lib/method-map.js +87 -98
  183. package/lib/stubs.ts +0 -1
  184. package/package.json +26 -19
  185. package/build/index.js +0 -51
  186. package/build/lib/android-helpers.d.ts +0 -136
  187. package/build/lib/android-helpers.d.ts.map +0 -1
  188. package/build/lib/android-helpers.js +0 -855
  189. package/build/lib/android-helpers.js.map +0 -1
  190. package/build/lib/commands/coverage.d.ts +0 -5
  191. package/build/lib/commands/coverage.d.ts.map +0 -1
  192. package/build/lib/commands/coverage.js +0 -19
  193. package/build/lib/commands/coverage.js.map +0 -1
  194. package/build/lib/desired-caps.d.ts +0 -353
  195. package/build/lib/desired-caps.d.ts.map +0 -1
  196. package/build/lib/desired-caps.js.map +0 -1
  197. package/build/lib/unlock-helpers.d.ts +0 -38
  198. package/build/lib/unlock-helpers.d.ts.map +0 -1
  199. package/build/lib/unlock-helpers.js +0 -266
  200. package/build/lib/unlock-helpers.js.map +0 -1
  201. package/build/lib/webview-helpers.d.ts +0 -224
  202. package/build/lib/webview-helpers.d.ts.map +0 -1
  203. package/build/lib/webview-helpers.js +0 -528
  204. package/build/lib/webview-helpers.js.map +0 -1
  205. package/index.js +0 -24
  206. package/lib/android-helpers.js +0 -983
  207. package/lib/commands/coverage.js +0 -18
  208. package/lib/commands/find.js +0 -82
  209. package/lib/unlock-helpers.js +0 -278
  210. package/lib/webview-helpers.js +0 -602
@@ -0,0 +1,1143 @@
1
+ import {fs, tempDir, util} from '@appium/support';
2
+ import type {AppiumServer, StringRecord} from '@appium/types';
3
+ import {ADB} from 'appium-adb';
4
+ import {retryInterval, waitForCondition} from 'asyncbox';
5
+ import B from 'bluebird';
6
+ import {path as settingsApkPath} from 'io.appium.settings';
7
+ import _ from 'lodash';
8
+ import {EOL} from 'node:os';
9
+ import path from 'node:path';
10
+ import semver, {type SemVer} from 'semver';
11
+ import type {SetRequired, ValueOf} from 'type-fest';
12
+ import Bootstrap from '../bootstrap';
13
+ import type {UnlockType} from '../commands/types';
14
+ import type {AndroidDriver, AndroidDriverCaps, AndroidDriverOpts} from '../driver';
15
+ import logger from '../logger';
16
+ import type {ADBDeviceInfo, ADBLaunchInfo} from './types';
17
+ import Unlocker, {
18
+ FINGERPRINT_UNLOCK,
19
+ PASSWORD_UNLOCK,
20
+ PATTERN_UNLOCK,
21
+ PIN_UNLOCK,
22
+ PIN_UNLOCK_KEY_EVENT,
23
+ } from './unlock';
24
+ import {AndroidDriverConstraints} from '../constraints';
25
+
26
+ const MOCK_APP_IDS_STORE = '/data/local/tmp/mock_apps.json';
27
+ const PACKAGE_INSTALL_TIMEOUT_MS = 90000;
28
+ const HELPER_APP_INSTALL_RETRIES = 3;
29
+ const HELPER_APP_INSTALL_RETRY_DELAY_MS = 5000;
30
+ // https://cs.chromium.org/chromium/src/chrome/browser/devtools/device/android_device_info_query.cc
31
+ const CHROME_BROWSER_PACKAGE_ACTIVITY = {
32
+ chrome: {
33
+ pkg: 'com.android.chrome',
34
+ activity: 'com.google.android.apps.chrome.Main',
35
+ },
36
+ chromium: {
37
+ pkg: 'org.chromium.chrome.shell',
38
+ activity: '.ChromeShellActivity',
39
+ },
40
+ chromebeta: {
41
+ pkg: 'com.chrome.beta',
42
+ activity: 'com.google.android.apps.chrome.Main',
43
+ },
44
+ browser: {
45
+ pkg: 'com.android.browser',
46
+ activity: 'com.android.browser.BrowserActivity',
47
+ },
48
+ 'chromium-browser': {
49
+ pkg: 'org.chromium.chrome',
50
+ activity: 'com.google.android.apps.chrome.Main',
51
+ },
52
+ 'chromium-webview': {
53
+ pkg: 'org.chromium.webview_shell',
54
+ activity: 'org.chromium.webview_shell.WebViewBrowserActivity',
55
+ },
56
+ default: {
57
+ pkg: 'com.android.chrome',
58
+ activity: 'com.google.android.apps.chrome.Main',
59
+ },
60
+ } as const;
61
+ const SETTINGS_HELPER_PKG_ID = 'io.appium.settings';
62
+ const SETTING_NOTIFICATIONS_LISTENER_SERVICE = `${SETTINGS_HELPER_PKG_ID}/.NLService`;
63
+ const EMULATOR_PATTERN = /\bemulator\b/i;
64
+ // These constants are in sync with
65
+ // https://developer.apple.com/documentation/xctest/xcuiapplicationstate/xcuiapplicationstaterunningbackground?language=objc
66
+ const APP_STATE = {
67
+ NOT_INSTALLED: 0,
68
+ NOT_RUNNING: 1,
69
+ RUNNING_IN_BACKGROUND: 3,
70
+ RUNNING_IN_FOREGROUND: 4,
71
+ } as const;
72
+
73
+ function ensureNetworkSpeed(adb: ADB, networkSpeed: string) {
74
+ if (networkSpeed.toUpperCase() in adb.NETWORK_SPEED) {
75
+ return networkSpeed;
76
+ }
77
+ logger.warn(
78
+ `Wrong network speed param '${networkSpeed}', using default: ${adb.NETWORK_SPEED.FULL}. ` +
79
+ `Supported values: ${_.values(adb.NETWORK_SPEED)}`
80
+ );
81
+ return adb.NETWORK_SPEED.FULL;
82
+ }
83
+
84
+ function prepareAvdArgs(adb: ADB, opts: AndroidDriverOpts): string[] {
85
+ const {networkSpeed, isHeadless, avdArgs} = opts;
86
+ const result: string[] = [];
87
+ if (avdArgs) {
88
+ if (_.isArray(avdArgs)) {
89
+ result.push(...avdArgs);
90
+ } else {
91
+ result.push(...(util.shellParse(`${avdArgs}`) as string[]));
92
+ }
93
+ }
94
+ if (networkSpeed) {
95
+ result.push('-netspeed', ensureNetworkSpeed(adb, networkSpeed));
96
+ }
97
+ if (isHeadless) {
98
+ result.push('-no-window');
99
+ }
100
+ return result;
101
+ }
102
+
103
+ function toCredentialType(unlockType: UnlockType) {
104
+ const result = {
105
+ [PIN_UNLOCK]: 'pin',
106
+ [PIN_UNLOCK_KEY_EVENT]: 'pin',
107
+ [PASSWORD_UNLOCK]: 'password',
108
+ [PATTERN_UNLOCK]: 'pattern',
109
+ }[unlockType];
110
+ if (result) {
111
+ return result;
112
+ }
113
+ throw new Error(`Unlock type '${unlockType}' is not known`);
114
+ }
115
+
116
+ interface AndroidHelpers {
117
+ createBaseADB(opts?: AndroidDriverOpts): Promise<ADB>;
118
+
119
+ prepareEmulator(adb: ADB, opts?: any): Promise<void>;
120
+
121
+ /**
122
+ * Set and ensure the locale name of the device under test.
123
+ *
124
+ * @param adb - The adb module instance.
125
+ * @param language - Language. The language field is case insensitive, but Locale always canonicalizes to lower case.
126
+ * format: [a-zA-Z]{2,8}. e.g. en, ja : https://developer.android.com/reference/java/util/Locale.html
127
+ * @param country - Country. The country (region) field is case insensitive, but Locale always canonicalizes to upper case.
128
+ * format: [a-zA-Z]{2} | [0-9]{3}. e.g. US, JP : https://developer.android.com/reference/java/util/Locale.html
129
+ * @param script - Script. The script field is case insensitive but Locale always canonicalizes to title case.
130
+ * format: [a-zA-Z]{4}. e.g. Hans in zh-Hans-CN : https://developer.android.com/reference/java/util/Locale.html
131
+ * @throws {Error} If it failed to set locale properly
132
+ */
133
+ ensureDeviceLocale(adb: ADB, language?: string, country?: string, script?: string): Promise<void>;
134
+
135
+ getDeviceInfoFromCaps<Opts extends AndroidDriverOpts>(opts?: Opts): Promise<ADBDeviceInfo>;
136
+
137
+ createADB<Opts extends AndroidDriverOpts>(opts?: Opts): Promise<ADB>;
138
+
139
+ validatePackageActivityNames<Opts extends AndroidDriverOpts>(opts: Opts): void;
140
+ getLaunchInfo<Opts extends AndroidDriverOpts>(
141
+ adb: ADB,
142
+ opts: Opts
143
+ ): Promise<ADBLaunchInfo | undefined>;
144
+ resetApp<Opts extends AndroidDriverOpts>(
145
+ adb: ADB,
146
+ opts: SetRequired<Opts, 'appPackage' | 'app'>
147
+ ): Promise<void>;
148
+ installApk<Opts extends AndroidDriverOpts>(
149
+ adb: ADB,
150
+ opts: SetRequired<Opts, 'appPackage' | 'app'>
151
+ ): Promise<void>;
152
+
153
+ /**
154
+ * Installs an array of apks
155
+ * @param adb Instance of Appium ADB object
156
+ * @param opts Opts defined in driver.js
157
+ */
158
+ installOtherApks<Opts extends AndroidDriverOpts>(
159
+ apks: string[],
160
+ adb: ADB,
161
+ opts: SetRequired<Opts, 'appPackage' | 'app'>
162
+ ): Promise<void>;
163
+
164
+ /**
165
+ * Uninstall an array of packages
166
+ * @param adb Instance of Appium ADB object
167
+ * @param appPackages An array of package names to uninstall. If this includes `'*'`, uninstall all of 3rd party apps
168
+ * @param filterPackages An array of packages does not uninstall when `*` is provided as `appPackages`
169
+ */
170
+ uninstallOtherPackages(adb: ADB, appPackages: string[], filterPackages?: string[]): Promise<void>;
171
+
172
+ /**
173
+ * Get third party packages filtered with `filterPackages`
174
+ * @param adb Instance of Appium ADB object
175
+ * @param filterPackages An array of packages does not uninstall when `*` is provided as `appPackages`
176
+ * @returns An array of installed third pary packages
177
+ */
178
+ getThirdPartyPackages(adb: ADB, filterPackages?: string[]): Promise<string[]>;
179
+ /**
180
+ * @privateRemarks FIXME: return value is unknown to me
181
+ */
182
+ initUnicodeKeyboard(adb: ADB): Promise<any>;
183
+ setMockLocationApp(adb: ADB, app: string): Promise<void>;
184
+ resetMockLocation(adb: ADB): Promise<void>;
185
+ installHelperApp(adb: ADB, apkPath: string, packageId: string): Promise<void>;
186
+
187
+ /**
188
+ * Pushes and installs io.appium.settings app.
189
+ * Throws an error if the setting app is required
190
+ *
191
+ * @param adb - The adb module instance.
192
+ * @param throwError - Whether throw an error if Settings app fails to start
193
+ * @param opts - Driver options dictionary.
194
+ * @throws If throwError is true and something happens in installation step
195
+ */
196
+ pushSettingsApp(adb: ADB, throwError: boolean, opts: AndroidDriverOpts): Promise<void>;
197
+
198
+ /**
199
+ * Extracts string.xml and converts it to string.json and pushes
200
+ * it to /data/local/tmp/string.json on for use of bootstrap
201
+ * If app is not present to extract string.xml it deletes remote strings.json
202
+ * If app does not have strings.xml we push an empty json object to remote
203
+ *
204
+ * @param language - Language abbreviation, for example 'fr'. The default language
205
+ * is used if this argument is not defined.
206
+ * @param adb - The adb module instance.
207
+ * @param opts - Driver options dictionary.
208
+ * @returns The dictionary, where string resource identifiers are keys
209
+ * along with their corresponding values for the given language or an empty object
210
+ * if no matching resources were extracted.
211
+ */
212
+ pushStrings(
213
+ language: string | undefined,
214
+ adb: ADB,
215
+ opts: AndroidDriverOpts
216
+ ): Promise<StringRecord>;
217
+ unlock<D extends AndroidDriver, Caps extends AndroidDriverCaps>(
218
+ driver: D,
219
+ adb: ADB,
220
+ capabilities: Caps
221
+ ): Promise<void>;
222
+ verifyUnlock(adb: ADB, timeoutMs?: number | null): Promise<void>;
223
+ initDevice(adb: ADB, opts: AndroidDriverOpts): Promise<string | void>;
224
+ removeNullProperties(obj: any): void;
225
+ truncateDecimals(number: number, digits: number): number;
226
+ isChromeBrowser(browser?: string): boolean;
227
+ getChromePkg(browser: string): ValueOf<typeof CHROME_BROWSER_PACKAGE_ACTIVITY>;
228
+ removeAllSessionWebSocketHandlers(
229
+ server?: AppiumServer,
230
+ sessionId?: string | null
231
+ ): Promise<void>;
232
+ parseArray(cap: string | string[]): string[];
233
+
234
+ /**
235
+ * Validate desired capabilities. Returns true if capabilities are valid
236
+ *
237
+ * @param caps Capabilities
238
+ * @return Returns true if the capabilites are valid
239
+ * @throws {Error} If the caps has invalid capability
240
+ */
241
+ validateDesiredCaps(caps: AndroidDriverCaps): boolean;
242
+
243
+ /**
244
+ * Adjust the capabilities for a browser session
245
+ *
246
+ * @param caps - Current capabilities object
247
+ * !!! The object is mutated by this method call !!!
248
+ * @returns The same possibly mutated `opts` instance.
249
+ * No mutation is happening is the current session if
250
+ * appPackage/appActivity caps have already been provided.
251
+ * @privateRemarks In practice, this fn is only ever provided a `AndroidDriverOpts` object
252
+ */
253
+ adjustBrowserSessionCaps(caps: AndroidDriverCaps): AndroidDriverCaps;
254
+
255
+ /**
256
+ * Checks whether the current device under test is an emulator
257
+ *
258
+ * @param adb - appium-adb instance
259
+ * @param opts - driver options mapping
260
+ * @returns `true` if the device is an Android emulator
261
+ */
262
+ isEmulator(adb?: ADB, opts?: AndroidDriverOpts): boolean;
263
+ bootstrap: typeof Bootstrap;
264
+ unlocker: typeof Unlocker;
265
+ }
266
+
267
+ const AndroidHelpers: AndroidHelpers = {
268
+ async createBaseADB(opts) {
269
+ // filter out any unwanted options sent in
270
+ // this list should be updated as ADB takes more arguments
271
+ const {
272
+ adbPort,
273
+ suppressKillServer,
274
+ remoteAdbHost,
275
+ clearDeviceLogsOnStart,
276
+ adbExecTimeout,
277
+ useKeystore,
278
+ keystorePath,
279
+ keystorePassword,
280
+ keyAlias,
281
+ keyPassword,
282
+ remoteAppsCacheLimit,
283
+ buildToolsVersion,
284
+ allowOfflineDevices,
285
+ allowDelayAdb,
286
+ } = opts ?? {};
287
+ return await ADB.createADB({
288
+ adbPort,
289
+ suppressKillServer,
290
+ remoteAdbHost,
291
+ clearDeviceLogsOnStart,
292
+ adbExecTimeout,
293
+ useKeystore,
294
+ keystorePath,
295
+ keystorePassword,
296
+ keyAlias,
297
+ keyPassword,
298
+ remoteAppsCacheLimit,
299
+ buildToolsVersion,
300
+ allowOfflineDevices,
301
+ allowDelayAdb,
302
+ });
303
+ },
304
+
305
+ async prepareEmulator(adb, opts) {
306
+ const {
307
+ avd,
308
+ avdEnv: env,
309
+ language,
310
+ locale: country,
311
+ avdLaunchTimeout: launchTimeout,
312
+ avdReadyTimeout: readyTimeout,
313
+ } = opts;
314
+ if (!avd) {
315
+ throw new Error('Cannot launch AVD without AVD name');
316
+ }
317
+
318
+ const avdName = avd.replace('@', '');
319
+ let isEmulatorRunning = true;
320
+ try {
321
+ await adb.getRunningAVDWithRetry(avdName, 5000);
322
+ } catch (e) {
323
+ logger.debug(`Emulator '${avdName}' is not running: ${(e as Error).message}`);
324
+ isEmulatorRunning = false;
325
+ }
326
+ const args = prepareAvdArgs(adb, opts);
327
+ if (isEmulatorRunning) {
328
+ if (args.includes('-wipe-data')) {
329
+ logger.debug(`Killing '${avdName}' because it needs to be wiped at start.`);
330
+ await adb.killEmulator(avdName);
331
+ } else {
332
+ logger.debug('Not launching AVD because it is already running.');
333
+ return;
334
+ }
335
+ }
336
+ await adb.launchAVD(avd, {
337
+ args,
338
+ env,
339
+ language,
340
+ country,
341
+ launchTimeout,
342
+ readyTimeout,
343
+ });
344
+ },
345
+
346
+ async ensureDeviceLocale(adb, language, country, script) {
347
+ if (!_.isString(language) && !_.isString(country)) {
348
+ logger.warn(`setDeviceLanguageCountry requires language or country.`);
349
+ logger.warn(`Got language: '${language}' and country: '${country}'`);
350
+ return;
351
+ }
352
+
353
+ await adb.setDeviceLanguageCountry(language, country, script);
354
+
355
+ if (!(await adb.ensureCurrentLocale(language, country, script))) {
356
+ const message = script
357
+ ? `language: ${language}, country: ${country} and script: ${script}`
358
+ : `language: ${language} and country: ${country}`;
359
+ throw new Error(`Failed to set ${message}`);
360
+ }
361
+ },
362
+
363
+ async getDeviceInfoFromCaps(opts) {
364
+ // we can create a throwaway ADB instance here, so there is no dependency
365
+ // on instantiating on earlier (at this point, we have no udid)
366
+ // we can only use this ADB object for commands that would not be confused
367
+ // if multiple devices are connected
368
+ const adb = await AndroidHelpers.createBaseADB(opts);
369
+ let udid: string | undefined = opts?.udid;
370
+ let emPort: number | false | undefined;
371
+
372
+ // a specific avd name was given. try to initialize with that
373
+ if (opts?.avd) {
374
+ await AndroidHelpers.prepareEmulator(adb, opts);
375
+ udid = adb.curDeviceId;
376
+ emPort = adb.emulatorPort;
377
+ } else {
378
+ // no avd given. lets try whatever's plugged in devices/emulators
379
+ logger.info('Retrieving device list');
380
+ const devices = await adb.getDevicesWithRetry();
381
+
382
+ // udid was given, lets try to init with that device
383
+ if (udid) {
384
+ if (!_.includes(_.map(devices, 'udid'), udid)) {
385
+ logger.errorAndThrow(`Device ${udid} was not in the list of connected devices`);
386
+ }
387
+ emPort = adb.getPortFromEmulatorString(udid);
388
+ } else if (opts?.platformVersion) {
389
+ opts.platformVersion = `${opts.platformVersion}`.trim();
390
+
391
+ // a platform version was given. lets try to find a device with the same os
392
+ const platformVersion = semver.coerce(opts.platformVersion) || opts.platformVersion;
393
+ logger.info(`Looking for a device with Android '${platformVersion}'`);
394
+
395
+ // in case we fail to find something, give the user a useful log that has
396
+ // the device udids and os versions so they know what's available
397
+ const availDevices: string[] = [];
398
+ let partialMatchCandidate: StringRecord<string> | undefined;
399
+ // first try started devices/emulators
400
+ for (const device of devices) {
401
+ // direct adb calls to the specific device
402
+ adb.setDeviceId(device.udid);
403
+ const rawDeviceOS = await adb.getPlatformVersion();
404
+ // The device OS could either be a number, like `6.0`
405
+ // or an abbreviation, like `R`
406
+ availDevices.push(`${device.udid} (${rawDeviceOS})`);
407
+ const deviceOS = semver.coerce(rawDeviceOS) || rawDeviceOS;
408
+ if (!deviceOS) {
409
+ continue;
410
+ }
411
+
412
+ const semverPV = platformVersion as SemVer;
413
+ const semverDO = deviceOS as SemVer;
414
+
415
+ const bothVersionsCanBeCoerced = semver.valid(deviceOS) && semver.valid(platformVersion);
416
+ const bothVersionsAreStrings = _.isString(deviceOS) && _.isString(platformVersion);
417
+ if (
418
+ (bothVersionsCanBeCoerced && semverDO.version === semverPV.version) ||
419
+ (bothVersionsAreStrings && _.toLower(deviceOS) === _.toLower(platformVersion))
420
+ ) {
421
+ // Got an exact match - proceed immediately
422
+ udid = device.udid;
423
+ break;
424
+ } else if (!bothVersionsCanBeCoerced) {
425
+ // There is no point to check for partial match if either of version numbers is not coercible
426
+ continue;
427
+ }
428
+
429
+ if (
430
+ ((!_.includes(opts.platformVersion, '.') && semverPV.major === semverDO.major) ||
431
+ (semverPV.major === semverDO.major && semverPV.minor === semverDO.minor)) &&
432
+ // Got a partial match - make sure we consider the most recent
433
+ // device version available on the host system
434
+ ((partialMatchCandidate && semver.gt(deviceOS, _.values(partialMatchCandidate)[0])) ||
435
+ !partialMatchCandidate)
436
+ ) {
437
+ partialMatchCandidate = {[device.udid]: deviceOS as string};
438
+ }
439
+ }
440
+ if (!udid && partialMatchCandidate) {
441
+ udid = _.keys(partialMatchCandidate)[0];
442
+ adb.setDeviceId(udid);
443
+ }
444
+
445
+ if (!udid) {
446
+ // we couldn't find anything! quit
447
+ logger.errorAndThrow(
448
+ `Unable to find an active device or emulator ` +
449
+ `with OS ${opts.platformVersion}. The following are available: ` +
450
+ availDevices.join(', ')
451
+ );
452
+ throw new Error(); // unreachable; for TS
453
+ }
454
+
455
+ emPort = adb.getPortFromEmulatorString(udid);
456
+ } else {
457
+ // a udid was not given, grab the first device we see
458
+ udid = devices[0].udid;
459
+ emPort = adb.getPortFromEmulatorString(udid);
460
+ }
461
+ }
462
+
463
+ logger.info(`Using device: ${udid}`);
464
+ return {udid: udid as string, emPort: emPort as number | false};
465
+ },
466
+
467
+ async createADB(opts) {
468
+ // @ts-expect-error do not put arbitrary properties on opts
469
+ const {udid, emPort} = opts ?? {};
470
+ const adb = await AndroidHelpers.createBaseADB(opts);
471
+ adb.setDeviceId(udid);
472
+ if (emPort) {
473
+ adb.setEmulatorPort(emPort);
474
+ }
475
+
476
+ return adb;
477
+ },
478
+
479
+ validatePackageActivityNames(opts) {
480
+ for (const key of ['appPackage', 'appActivity', 'appWaitPackage', 'appWaitActivity']) {
481
+ const name = opts[key as keyof typeof opts];
482
+ if (!name) {
483
+ continue;
484
+ }
485
+
486
+ const match = /([^\w.*,])+/.exec(String(name));
487
+ if (!match) {
488
+ continue;
489
+ }
490
+
491
+ logger.warn(
492
+ `Capability '${key}' is expected to only include latin letters, digits, underscore, dot, comma and asterisk characters.`
493
+ );
494
+ logger.warn(
495
+ `Current value '${name}' has non-matching character at index ${match.index}: '${String(
496
+ name
497
+ ).substring(0, match.index + 1)}'`
498
+ );
499
+ }
500
+ },
501
+
502
+ async getLaunchInfo(adb, opts) {
503
+ if (!opts.app) {
504
+ logger.warn('No app sent in, not parsing package/activity');
505
+ return;
506
+ }
507
+ let {appPackage, appActivity, appWaitPackage, appWaitActivity} = opts;
508
+ const {app} = opts;
509
+
510
+ AndroidHelpers.validatePackageActivityNames(opts);
511
+
512
+ if (appPackage && appActivity) {
513
+ return;
514
+ }
515
+
516
+ logger.debug('Parsing package and activity from app manifest');
517
+ const {apkPackage, apkActivity} = await adb.packageAndLaunchActivityFromManifest(app);
518
+ if (apkPackage && !appPackage) {
519
+ appPackage = apkPackage;
520
+ }
521
+ if (!appWaitPackage) {
522
+ appWaitPackage = appPackage;
523
+ }
524
+ if (apkActivity && !appActivity) {
525
+ appActivity = apkActivity;
526
+ }
527
+ if (!appWaitActivity) {
528
+ appWaitActivity = appActivity;
529
+ }
530
+ logger.debug(`Parsed package and activity are: ${apkPackage}/${apkActivity}`);
531
+ return {appPackage, appWaitPackage, appActivity, appWaitActivity};
532
+ },
533
+
534
+ async resetApp(adb, opts) {
535
+ const {
536
+ app,
537
+ appPackage,
538
+ fastReset,
539
+ fullReset,
540
+ androidInstallTimeout = PACKAGE_INSTALL_TIMEOUT_MS,
541
+ autoGrantPermissions,
542
+ allowTestPackages,
543
+ } = opts ?? {};
544
+
545
+ if (!appPackage) {
546
+ throw new Error("'appPackage' option is required");
547
+ }
548
+
549
+ const isInstalled = await adb.isAppInstalled(appPackage);
550
+
551
+ if (isInstalled) {
552
+ try {
553
+ await adb.forceStop(appPackage);
554
+ } catch (ign) {}
555
+ // fullReset has priority over fastReset
556
+ if (!fullReset && fastReset) {
557
+ const output = await adb.clear(appPackage);
558
+ if (_.isString(output) && output.toLowerCase().includes('failed')) {
559
+ throw new Error(
560
+ `Cannot clear the application data of '${appPackage}'. Original error: ${output}`
561
+ );
562
+ }
563
+ // executing `shell pm clear` resets previously assigned application permissions as well
564
+ if (autoGrantPermissions) {
565
+ try {
566
+ await adb.grantAllPermissions(appPackage);
567
+ } catch (error) {
568
+ logger.error(
569
+ `Unable to grant permissions requested. Original error: ${(error as Error).message}`
570
+ );
571
+ }
572
+ }
573
+ logger.debug(
574
+ `Performed fast reset on the installed '${appPackage}' application (stop and clear)`
575
+ );
576
+ return;
577
+ }
578
+ }
579
+
580
+ if (!app) {
581
+ throw new Error(
582
+ `Either provide 'app' option to install '${appPackage}' or ` +
583
+ `consider setting 'noReset' to 'true' if '${appPackage}' is supposed to be preinstalled.`
584
+ );
585
+ }
586
+
587
+ logger.debug(`Running full reset on '${appPackage}' (reinstall)`);
588
+ if (isInstalled) {
589
+ await adb.uninstallApk(appPackage);
590
+ }
591
+ await adb.install(app, {
592
+ grantPermissions: autoGrantPermissions,
593
+ timeout: androidInstallTimeout,
594
+ allowTestPackages,
595
+ });
596
+ },
597
+
598
+ async installApk(adb, opts) {
599
+ const {
600
+ app,
601
+ appPackage,
602
+ fastReset,
603
+ fullReset,
604
+ androidInstallTimeout = PACKAGE_INSTALL_TIMEOUT_MS,
605
+ autoGrantPermissions,
606
+ allowTestPackages,
607
+ enforceAppInstall,
608
+ } = opts ?? {};
609
+
610
+ if (!app || !appPackage) {
611
+ throw new Error("'app' and 'appPackage' options are required");
612
+ }
613
+
614
+ if (fullReset) {
615
+ await AndroidHelpers.resetApp(adb, opts);
616
+ return;
617
+ }
618
+
619
+ const {appState, wasUninstalled} = await adb.installOrUpgrade(app, appPackage, {
620
+ grantPermissions: autoGrantPermissions,
621
+ timeout: androidInstallTimeout,
622
+ allowTestPackages,
623
+ enforceCurrentBuild: enforceAppInstall,
624
+ });
625
+
626
+ // There is no need to reset the newly installed app
627
+ const isInstalledOverExistingApp =
628
+ !wasUninstalled && appState !== adb.APP_INSTALL_STATE.NOT_INSTALLED;
629
+ if (fastReset && isInstalledOverExistingApp) {
630
+ logger.info(`Performing fast reset on '${appPackage}'`);
631
+ await AndroidHelpers.resetApp(adb, opts);
632
+ }
633
+ },
634
+
635
+ async installOtherApks(otherApps, adb, opts) {
636
+ const {
637
+ androidInstallTimeout = PACKAGE_INSTALL_TIMEOUT_MS,
638
+ autoGrantPermissions,
639
+ allowTestPackages,
640
+ } = opts;
641
+
642
+ // Install all of the APK's asynchronously
643
+ await B.all(
644
+ otherApps.map((otherApp) => {
645
+ logger.debug(`Installing app: ${otherApp}`);
646
+ return adb.installOrUpgrade(otherApp, undefined, {
647
+ grantPermissions: autoGrantPermissions,
648
+ timeout: androidInstallTimeout,
649
+ allowTestPackages,
650
+ });
651
+ })
652
+ );
653
+ },
654
+
655
+ async uninstallOtherPackages(adb, appPackages, filterPackages = []) {
656
+ if (appPackages.includes('*')) {
657
+ logger.debug('Uninstall third party packages');
658
+ appPackages = await AndroidHelpers.getThirdPartyPackages(adb, filterPackages);
659
+ }
660
+
661
+ logger.debug(`Uninstalling packages: ${appPackages}`);
662
+ await B.all(appPackages.map((appPackage) => adb.uninstallApk(appPackage)));
663
+ },
664
+
665
+ async getThirdPartyPackages(adb, filterPackages = []) {
666
+ try {
667
+ const packagesString = await adb.shell(['pm', 'list', 'packages', '-3']);
668
+ const appPackagesArray = packagesString
669
+ .trim()
670
+ .replace(/package:/g, '')
671
+ .split(EOL);
672
+ logger.debug(`'${appPackagesArray}' filtered with '${filterPackages}'`);
673
+ return _.difference(appPackagesArray, filterPackages);
674
+ } catch (err) {
675
+ logger.warn(
676
+ `Unable to get packages with 'adb shell pm list packages -3': ${(err as Error).message}`
677
+ );
678
+ return [];
679
+ }
680
+ },
681
+
682
+ async initUnicodeKeyboard(adb) {
683
+ logger.debug('Enabling Unicode keyboard support');
684
+
685
+ // get the default IME so we can return back to it later if we want
686
+ const defaultIME = await adb.defaultIME();
687
+
688
+ logger.debug(`Unsetting previous IME ${defaultIME}`);
689
+ const appiumIME = `${SETTINGS_HELPER_PKG_ID}/.UnicodeIME`;
690
+ logger.debug(`Setting IME to '${appiumIME}'`);
691
+ await adb.enableIME(appiumIME);
692
+ await adb.setIME(appiumIME);
693
+ return defaultIME;
694
+ },
695
+
696
+ async setMockLocationApp(adb, app) {
697
+ try {
698
+ if ((await adb.getApiLevel()) < 23) {
699
+ await adb.shell(['settings', 'put', 'secure', 'mock_location', '1']);
700
+ } else {
701
+ await adb.shell(['appops', 'set', app, 'android:mock_location', 'allow']);
702
+ }
703
+ } catch (err) {
704
+ logger.warn(`Unable to set mock location for app '${app}': ${(err as Error).message}`);
705
+ return;
706
+ }
707
+ try {
708
+ let pkgIds: string[] = [];
709
+ if (await adb.fileExists(MOCK_APP_IDS_STORE)) {
710
+ try {
711
+ pkgIds = JSON.parse(await adb.shell(['cat', MOCK_APP_IDS_STORE]));
712
+ } catch (ign) {}
713
+ }
714
+ if (pkgIds.includes(app)) {
715
+ return;
716
+ }
717
+ pkgIds.push(app);
718
+ const tmpRoot = await tempDir.openDir();
719
+ const srcPath = path.posix.join(tmpRoot, path.posix.basename(MOCK_APP_IDS_STORE));
720
+ try {
721
+ await fs.writeFile(srcPath, JSON.stringify(pkgIds), 'utf8');
722
+ await adb.push(srcPath, MOCK_APP_IDS_STORE);
723
+ } finally {
724
+ await fs.rimraf(tmpRoot);
725
+ }
726
+ } catch (e) {
727
+ logger.warn(`Unable to persist mock location app id '${app}': ${(e as Error).message}`);
728
+ }
729
+ },
730
+
731
+ async resetMockLocation(adb) {
732
+ try {
733
+ if ((await adb.getApiLevel()) < 23) {
734
+ await adb.shell(['settings', 'put', 'secure', 'mock_location', '0']);
735
+ return;
736
+ }
737
+
738
+ const thirdPartyPkgIdsPromise = AndroidHelpers.getThirdPartyPackages(adb);
739
+ let pkgIds = [];
740
+ if (await adb.fileExists(MOCK_APP_IDS_STORE)) {
741
+ try {
742
+ pkgIds = JSON.parse(await adb.shell(['cat', MOCK_APP_IDS_STORE]));
743
+ } catch (ign) {}
744
+ }
745
+ const thirdPartyPkgIds = await thirdPartyPkgIdsPromise;
746
+ // Only include currently installed packages
747
+ const resultPkgs = _.intersection(pkgIds, thirdPartyPkgIds);
748
+ if (_.size(resultPkgs) <= 1) {
749
+ await adb.shell([
750
+ 'appops',
751
+ 'set',
752
+ resultPkgs[0] ?? SETTINGS_HELPER_PKG_ID,
753
+ 'android:mock_location',
754
+ 'deny',
755
+ ]);
756
+ return;
757
+ }
758
+
759
+ logger.debug(`Resetting mock_location permission for the following apps: ${resultPkgs}`);
760
+ await B.all(
761
+ resultPkgs.map((pkgId) =>
762
+ (async () => {
763
+ try {
764
+ await adb.shell(['appops', 'set', pkgId, 'android:mock_location', 'deny']);
765
+ } catch (ign) {}
766
+ })()
767
+ )
768
+ );
769
+ } catch (err) {
770
+ logger.warn(`Unable to reset mock location: ${(err as Error).message}`);
771
+ }
772
+ },
773
+
774
+ async installHelperApp(adb, apkPath, packageId) {
775
+ // Sometimes adb push or adb instal take more time than expected to install an app
776
+ // e.g. https://github.com/appium/io.appium.settings/issues/40#issuecomment-476593174
777
+ await retryInterval(
778
+ HELPER_APP_INSTALL_RETRIES,
779
+ HELPER_APP_INSTALL_RETRY_DELAY_MS,
780
+ async function retryInstallHelperApp() {
781
+ await adb.installOrUpgrade(apkPath, packageId, {grantPermissions: true});
782
+ }
783
+ );
784
+ },
785
+
786
+ async pushSettingsApp(adb, throwError, opts) {
787
+ logger.debug('Pushing settings apk to device...');
788
+
789
+ try {
790
+ await AndroidHelpers.installHelperApp(adb, settingsApkPath, SETTINGS_HELPER_PKG_ID);
791
+ } catch (err) {
792
+ if (throwError) {
793
+ throw err;
794
+ }
795
+
796
+ logger.warn(
797
+ `Ignored error while installing '${settingsApkPath}': ` +
798
+ `'${(err as Error).message}'. Features that rely on this helper ` +
799
+ 'require the apk such as toggle WiFi and getting location ' +
800
+ 'will raise an error if you try to use them.'
801
+ );
802
+ }
803
+
804
+ // Reinstall would stop the settings helper process anyway, so
805
+ // there is no need to continue if the application is still running
806
+ if (await adb.processExists(SETTINGS_HELPER_PKG_ID)) {
807
+ logger.debug(
808
+ `${SETTINGS_HELPER_PKG_ID} is already running. ` +
809
+ `There is no need to reset its permissions.`
810
+ );
811
+ return;
812
+ }
813
+
814
+ const apiLevel = await adb.getApiLevel();
815
+ if (apiLevel >= 29) {
816
+ // https://github.com/appium/io.appium.settings#internal-audio--video-recording
817
+ try {
818
+ await adb.shell(['appops', 'set', SETTINGS_HELPER_PKG_ID, 'PROJECT_MEDIA', 'allow']);
819
+ } catch (err) {
820
+ logger.debug((err as Error).message);
821
+ }
822
+ try {
823
+ await adb.shell([
824
+ 'cmd',
825
+ 'notification',
826
+ 'allow_listener',
827
+ SETTING_NOTIFICATIONS_LISTENER_SERVICE,
828
+ ]);
829
+ } catch (err) {
830
+ logger.debug((err as Error).message);
831
+ }
832
+ }
833
+ if (apiLevel <= 23) {
834
+ // Android 6- devices should have granted permissions
835
+ // https://github.com/appium/appium/pull/11640#issuecomment-438260477
836
+ const perms = ['SET_ANIMATION_SCALE', 'CHANGE_CONFIGURATION', 'ACCESS_FINE_LOCATION'];
837
+ logger.info(`Granting permissions ${perms} to '${SETTINGS_HELPER_PKG_ID}'`);
838
+ await adb.grantPermissions(
839
+ SETTINGS_HELPER_PKG_ID,
840
+ perms.map((x) => `android.permission.${x}`)
841
+ );
842
+ }
843
+
844
+ // launch io.appium.settings app due to settings failing to be set
845
+ // if the app is not launched prior to start the session on android 7+
846
+ // see https://github.com/appium/appium/issues/8957
847
+ try {
848
+ await adb.requireRunningSettingsApp({
849
+ timeout: AndroidHelpers.isEmulator(adb, opts) ? 30000 : 5000,
850
+ });
851
+ } catch (err) {
852
+ logger.debug(err);
853
+ if (throwError) {
854
+ throw err;
855
+ }
856
+ }
857
+ },
858
+
859
+ async pushStrings(language, adb, opts) {
860
+ const remoteDir = '/data/local/tmp';
861
+ const stringsJson = 'strings.json';
862
+ const remoteFile = path.posix.resolve(remoteDir, stringsJson);
863
+
864
+ // clean up remote string.json if present
865
+ await adb.rimraf(remoteFile);
866
+
867
+ let app: string;
868
+ try {
869
+ app = opts.app || (await adb.pullApk(opts.appPackage!, opts.tmpDir!));
870
+ } catch (err) {
871
+ logger.info(
872
+ `Failed to pull an apk from '${opts.appPackage}' to '${opts.tmpDir}'. Original error: ${
873
+ (err as Error).message
874
+ }`
875
+ );
876
+ }
877
+
878
+ if (_.isEmpty(opts.appPackage) || !(await fs.exists(app!))) {
879
+ logger.debug(`No app or package specified. Returning empty strings`);
880
+ return {};
881
+ }
882
+
883
+ const stringsTmpDir = path.resolve(opts.tmpDir!, opts.appPackage!);
884
+ try {
885
+ logger.debug('Extracting strings from apk', app!, language, stringsTmpDir);
886
+ const {apkStrings, localPath} = await adb.extractStringsFromApk(
887
+ app!,
888
+ language,
889
+ stringsTmpDir
890
+ );
891
+ await adb.push(localPath, remoteDir);
892
+ return apkStrings;
893
+ } catch (err) {
894
+ logger.warn(
895
+ `Could not get strings, continuing anyway. Original error: ${(err as Error).message}`
896
+ );
897
+ await adb.shell(['echo', `'{}' > ${remoteFile}`]);
898
+ } finally {
899
+ await fs.rimraf(stringsTmpDir);
900
+ }
901
+ return {};
902
+ },
903
+
904
+ async unlock(driver, adb, capabilities) {
905
+ if (!(await adb.isScreenLocked())) {
906
+ logger.info('Screen already unlocked, doing nothing');
907
+ return;
908
+ }
909
+
910
+ logger.debug('Screen is locked, trying to unlock');
911
+ if (!capabilities.unlockType && !capabilities.unlockKey) {
912
+ logger.info(
913
+ `Neither 'unlockType' nor 'unlockKey' capability is provided. ` +
914
+ `Assuming the device is locked with a simple lock screen.`
915
+ );
916
+ await adb.dismissKeyguard();
917
+ return;
918
+ }
919
+
920
+ const {unlockType, unlockKey, unlockStrategy, unlockSuccessTimeout} =
921
+ Unlocker.validateUnlockCapabilities(capabilities);
922
+ if (
923
+ unlockKey &&
924
+ unlockType !== FINGERPRINT_UNLOCK &&
925
+ (_.isNil(unlockStrategy) || _.toLower(unlockStrategy) === 'locksettings') &&
926
+ (await adb.isLockManagementSupported())
927
+ ) {
928
+ await Unlocker.fastUnlock(adb, {
929
+ credential: unlockKey,
930
+ credentialType: toCredentialType(unlockType as UnlockType),
931
+ });
932
+ } else {
933
+ const unlockMethod = {
934
+ [PIN_UNLOCK]: Unlocker.pinUnlock,
935
+ [PIN_UNLOCK_KEY_EVENT]: Unlocker.pinUnlockWithKeyEvent,
936
+ [PASSWORD_UNLOCK]: Unlocker.passwordUnlock,
937
+ [PATTERN_UNLOCK]: Unlocker.patternUnlock,
938
+ [FINGERPRINT_UNLOCK]: Unlocker.fingerprintUnlock,
939
+ }[unlockType!];
940
+ await unlockMethod!(adb, driver, capabilities);
941
+ }
942
+ await AndroidHelpers.verifyUnlock(adb, unlockSuccessTimeout);
943
+ },
944
+
945
+ async verifyUnlock(adb, timeoutMs = null) {
946
+ try {
947
+ await waitForCondition(async () => !(await adb.isScreenLocked()), {
948
+ waitMs: timeoutMs ?? 2000,
949
+ intervalMs: 500,
950
+ });
951
+ } catch (ign) {
952
+ throw new Error('The device has failed to be unlocked');
953
+ }
954
+ logger.info('The device has been successfully unlocked');
955
+ },
956
+
957
+ async initDevice(adb, opts) {
958
+ const {
959
+ skipDeviceInitialization,
960
+ locale,
961
+ language,
962
+ localeScript,
963
+ unicodeKeyboard,
964
+ disableWindowAnimation,
965
+ skipUnlock,
966
+ mockLocationApp,
967
+ skipLogcatCapture,
968
+ logcatFormat,
969
+ logcatFilterSpecs,
970
+ } = opts;
971
+
972
+ if (skipDeviceInitialization) {
973
+ logger.info(`'skipDeviceInitialization' is set. Skipping device initialization.`);
974
+ } else {
975
+ if (AndroidHelpers.isEmulator(adb, opts)) {
976
+ // Check if the device wake up only for an emulator.
977
+ // It takes 1 second or so even when the device is already awake in a real device.
978
+ await adb.waitForDevice();
979
+ }
980
+ // pushSettingsApp required before calling ensureDeviceLocale for API Level 24+
981
+
982
+ // Some feature such as location/wifi are not necessary for all users,
983
+ // but they require the settings app. So, try to configure it while Appium
984
+ // does not throw error even if they fail.
985
+ const shouldThrowError = Boolean(
986
+ language ||
987
+ locale ||
988
+ localeScript ||
989
+ unicodeKeyboard ||
990
+ disableWindowAnimation ||
991
+ !skipUnlock
992
+ );
993
+ await AndroidHelpers.pushSettingsApp(adb, shouldThrowError, opts);
994
+ }
995
+
996
+ if (!AndroidHelpers.isEmulator(adb, opts)) {
997
+ if (mockLocationApp || _.isUndefined(mockLocationApp)) {
998
+ await AndroidHelpers.setMockLocationApp(adb, mockLocationApp || SETTINGS_HELPER_PKG_ID);
999
+ } else {
1000
+ await AndroidHelpers.resetMockLocation(adb);
1001
+ }
1002
+ }
1003
+
1004
+ if (language || locale) {
1005
+ await AndroidHelpers.ensureDeviceLocale(adb, language, locale, localeScript);
1006
+ }
1007
+
1008
+ if (skipLogcatCapture) {
1009
+ logger.info(`'skipLogcatCapture' is set. Skipping starting logcat capture.`);
1010
+ } else {
1011
+ await adb.startLogcat({
1012
+ format: logcatFormat,
1013
+ filterSpecs: logcatFilterSpecs,
1014
+ });
1015
+ }
1016
+
1017
+ if (unicodeKeyboard) {
1018
+ return await AndroidHelpers.initUnicodeKeyboard(adb);
1019
+ }
1020
+ },
1021
+
1022
+ removeNullProperties(obj) {
1023
+ for (const key of _.keys(obj)) {
1024
+ if (_.isNull(obj[key]) || _.isUndefined(obj[key])) {
1025
+ delete obj[key];
1026
+ }
1027
+ }
1028
+ },
1029
+
1030
+ truncateDecimals(number, digits) {
1031
+ const multiplier = Math.pow(10, digits),
1032
+ adjustedNum = number * multiplier,
1033
+ truncatedNum = Math[adjustedNum < 0 ? 'ceil' : 'floor'](adjustedNum);
1034
+
1035
+ return truncatedNum / multiplier;
1036
+ },
1037
+
1038
+ isChromeBrowser(browser) {
1039
+ return _.includes(Object.keys(CHROME_BROWSER_PACKAGE_ACTIVITY), (browser || '').toLowerCase());
1040
+ },
1041
+
1042
+ getChromePkg(browser) {
1043
+ return (
1044
+ CHROME_BROWSER_PACKAGE_ACTIVITY[
1045
+ browser.toLowerCase() as keyof typeof CHROME_BROWSER_PACKAGE_ACTIVITY
1046
+ ] || CHROME_BROWSER_PACKAGE_ACTIVITY.default
1047
+ );
1048
+ },
1049
+
1050
+ async removeAllSessionWebSocketHandlers(server, sessionId) {
1051
+ if (!server || !_.isFunction(server.getWebSocketHandlers)) {
1052
+ return;
1053
+ }
1054
+
1055
+ const activeHandlers = await server.getWebSocketHandlers(sessionId);
1056
+ for (const pathname of _.keys(activeHandlers)) {
1057
+ await server.removeWebSocketHandler(pathname);
1058
+ }
1059
+ },
1060
+
1061
+ parseArray(cap) {
1062
+ let parsedCaps: string | string[] | undefined;
1063
+ try {
1064
+ parsedCaps = JSON.parse(cap as string);
1065
+ } catch (ign) {}
1066
+
1067
+ if (_.isArray(parsedCaps)) {
1068
+ return parsedCaps;
1069
+ } else if (_.isString(cap)) {
1070
+ return [cap];
1071
+ }
1072
+
1073
+ throw new Error(`must provide a string or JSON Array; received ${cap}`);
1074
+ },
1075
+
1076
+ validateDesiredCaps(caps) {
1077
+ if (caps.browserName) {
1078
+ if (caps.app) {
1079
+ // warn if the capabilities have both `app` and `browser, although this is common with selenium grid
1080
+ logger.warn(
1081
+ `The desired capabilities should generally not include both an 'app' and a 'browserName'`
1082
+ );
1083
+ }
1084
+ if (caps.appPackage) {
1085
+ logger.errorAndThrow(
1086
+ `The desired should not include both of an 'appPackage' and a 'browserName'`
1087
+ );
1088
+ }
1089
+ }
1090
+
1091
+ if (caps.uninstallOtherPackages) {
1092
+ try {
1093
+ AndroidHelpers.parseArray(caps.uninstallOtherPackages);
1094
+ } catch (e) {
1095
+ logger.errorAndThrow(
1096
+ `Could not parse "uninstallOtherPackages" capability: ${(e as Error).message}`
1097
+ );
1098
+ }
1099
+ }
1100
+
1101
+ return true;
1102
+ },
1103
+
1104
+ adjustBrowserSessionCaps(caps) {
1105
+ const {browserName} = caps;
1106
+ logger.info(`The current session is considered browser-based`);
1107
+ logger.info(
1108
+ `Supported browser names: ${JSON.stringify(_.keys(CHROME_BROWSER_PACKAGE_ACTIVITY))}`
1109
+ );
1110
+ if (caps.appPackage || caps.appActivity) {
1111
+ logger.info(
1112
+ `Not overriding appPackage/appActivity capability values for '${browserName}' ` +
1113
+ 'because some of them have been already provided'
1114
+ );
1115
+ return caps;
1116
+ }
1117
+
1118
+ const {pkg, activity} = AndroidHelpers.getChromePkg(String(browserName));
1119
+ caps.appPackage = pkg;
1120
+ caps.appActivity = activity;
1121
+ logger.info(
1122
+ `appPackage/appActivity capabilities have been automatically set to ${pkg}/${activity} ` +
1123
+ `for '${browserName}'`
1124
+ );
1125
+ logger.info(
1126
+ `Consider changing the browserName to the one from the list of supported browser names ` +
1127
+ `or provide custom appPackage/appActivity capability values if the automatically assigned ones do ` +
1128
+ `not make sense`
1129
+ );
1130
+ return caps;
1131
+ },
1132
+
1133
+ isEmulator(adb, opts) {
1134
+ const possibleNames = [opts?.udid, adb?.curDeviceId];
1135
+ return !!opts?.avd || possibleNames.some((x) => EMULATOR_PATTERN.test(String(x)));
1136
+ },
1137
+ bootstrap: Bootstrap,
1138
+ unlocker: Unlocker,
1139
+ };
1140
+
1141
+ export const helpers = AndroidHelpers;
1142
+ export {APP_STATE, SETTINGS_HELPER_PKG_ID, ensureNetworkSpeed, prepareAvdArgs};
1143
+ export default AndroidHelpers;