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,582 @@
1
+ /**
2
+ * Webview-related helper functions
3
+ * @module
4
+ */
5
+
6
+ import {util} from '@appium/support';
7
+ import {StringRecord} from '@appium/types';
8
+ import axios from 'axios';
9
+ import B from 'bluebird';
10
+ import _ from 'lodash';
11
+ import LRU from 'lru-cache';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import {findAPortNotInUse} from 'portscanner';
15
+ import type {WebviewsMapping} from '../commands/types';
16
+ import type {AndroidDriverCaps} from '../driver';
17
+ import logger from '../logger';
18
+ import type {
19
+ DetailCollectionOptions,
20
+ GetWebviewsOpts,
21
+ WebViewDetails,
22
+ WebviewProc,
23
+ WebviewProps,
24
+ } from './types';
25
+ import type {ADB} from 'appium-adb';
26
+
27
+ const NATIVE_WIN = 'NATIVE_APP';
28
+ const WEBVIEW_WIN = 'WEBVIEW';
29
+ const CHROMIUM_WIN = 'CHROMIUM';
30
+ const WEBVIEW_BASE = `${WEBVIEW_WIN}_`;
31
+ const WEBVIEW_PID_PATTERN = new RegExp(`^${WEBVIEW_BASE}(\\d+)`);
32
+ const WEBVIEW_PKG_PATTERN = new RegExp(`^${WEBVIEW_BASE}([^\\d\\s][\\w.]*)`);
33
+ export const DEVTOOLS_SOCKET_PATTERN = /@[\w.]+_devtools_remote_?([\w.]+_)?(\d+)?\b/;
34
+ const CROSSWALK_SOCKET_PATTERN = /@([\w.]+)_devtools_remote\b/;
35
+ const CHROMIUM_DEVTOOLS_SOCKET = 'chrome_devtools_remote';
36
+ const CHROME_PACKAGE_NAME = 'com.android.chrome';
37
+ const KNOWN_CHROME_PACKAGE_NAMES = [
38
+ CHROME_PACKAGE_NAME,
39
+ 'com.chrome.beta',
40
+ 'com.chrome.dev',
41
+ 'com.chrome.canary',
42
+ ];
43
+ const DEVTOOLS_PORTS_RANGE = [10900, 11000];
44
+ const WEBVIEWS_DETAILS_CACHE = new LRU<string, WebViewDetails>({
45
+ max: 100,
46
+ updateAgeOnGet: true,
47
+ });
48
+ const CDP_REQ_TIMEOUT = 2000; // ms
49
+ const DEVTOOLS_PORT_ALLOCATION_GUARD = util.getLockFileGuard(
50
+ path.resolve(os.tmpdir(), 'android_devtools_port_guard'),
51
+ {timeout: 7, tryRecovery: true}
52
+ );
53
+
54
+ interface WebviewHelpers {
55
+ /**
56
+ * Take a webview name like WEBVIEW_4296 and use 'adb shell ps' to figure out
57
+ * which app package is associated with that webview. One of the reasons we
58
+ * want to do this is to make sure we're listing webviews for the actual AUT,
59
+ * not some other running app
60
+ *
61
+ * @param adb - an ADB instance
62
+ * @param webview - a webview process name
63
+ *
64
+ * @returns {Promise<string>} - the package name of the app running the webview
65
+ * @throws {Error} If there was a failure while retrieving the process name
66
+ */
67
+ procFromWebview: (adb: ADB, webview: string) => Promise<string>;
68
+
69
+ /**
70
+ * Parse webview names for getContexts
71
+ *
72
+ * @param webviewsMapping See note on getWebViewsMapping
73
+ * @param opts See note on getWebViewsMapping
74
+ * @returns a list of webview names
75
+ */
76
+ parseWebviewNames: (webviewsMapping: WebviewsMapping[], opts?: GetWebviewsOpts) => string[];
77
+
78
+ /**
79
+ * Get a list of available webviews mapping by introspecting processes with adb,
80
+ * where webviews are listed. It's possible to pass in a 'deviceSocket' arg, which
81
+ * limits the webview possibilities to the one running on the Chromium devtools
82
+ * socket we're interested in (see note on webviewsFromProcs). We can also
83
+ * direct this method to verify whether a particular webview process actually
84
+ * has any pages (if a process exists but no pages are found, Chromedriver will
85
+ * not actually be able to connect to it, so this serves as a guard for that
86
+ * strange failure mode). The strategy for checking whether any pages are
87
+ * active involves sending a request to the remote debug server on the device,
88
+ * hence it is also possible to specify the port on the host machine which
89
+ * should be used for this communication.
90
+ *
91
+ * @param adb - an ADB instance
92
+ */
93
+ getWebViewsMapping: (adb: ADB, opts?: GetWebviewsOpts) => Promise<WebviewsMapping[]>;
94
+
95
+ /**
96
+ * Retrieves web view details previously cached by `getWebviews` call
97
+ *
98
+ * @param adb ADB instance
99
+ * @param webview The name of the web view
100
+ * @returns Either `undefined` or the recent web view details
101
+ */
102
+ getWebviewDetails: (adb: ADB, webview: string) => WebViewDetails | undefined;
103
+
104
+ /**
105
+ * Create Chrome driver capabilities based on the provided
106
+ * Appium capabilities
107
+ *
108
+ * @param opts User-provided capabilities object
109
+ * @param deviceId The identifier of the Android device under test
110
+ * @returns The capabilities object.
111
+ * @see {@link https://chromedriver.chromium.org/capabilities Chromedriver docs} for more details
112
+ */
113
+
114
+ createChromedriverCaps: (
115
+ opts: any,
116
+ deviceId: string,
117
+ webViewDetails?: WebViewDetails | null
118
+ ) => object;
119
+ }
120
+
121
+ function toDetailsCacheKey(adb: ADB, webview: string): string {
122
+ return `${adb?.curDeviceId}:${webview}`;
123
+ }
124
+
125
+ /**
126
+ * This function gets a list of android system processes and returns ones
127
+ * that look like webviews
128
+ * See https://cs.chromium.org/chromium/src/chrome/browser/devtools/device/android_device_info_query.cc
129
+ * for more details
130
+ *
131
+ * @param adb - an ADB instance
132
+ *
133
+ * @returns a list of matching webview socket names (including the leading '@')
134
+ */
135
+ async function getPotentialWebviewProcs(adb: ADB): Promise<string[]> {
136
+ const out = (await adb.shell(['cat', '/proc/net/unix'])) as string;
137
+ const names: string[] = [];
138
+ const allMatches: string[] = [];
139
+ for (const line of out.split('\n')) {
140
+ // Num RefCount Protocol Flags Type St Inode Path
141
+ const [, , , flags, , st, , sockPath] = line.trim().split(/\s+/);
142
+ if (!sockPath) {
143
+ continue;
144
+ }
145
+ if (sockPath.startsWith('@')) {
146
+ allMatches.push(line.trim());
147
+ }
148
+ if (flags !== '00010000' || st !== '01') {
149
+ continue;
150
+ }
151
+ if (!DEVTOOLS_SOCKET_PATTERN.test(sockPath)) {
152
+ continue;
153
+ }
154
+
155
+ names.push(sockPath);
156
+ }
157
+ if (_.isEmpty(names)) {
158
+ logger.debug('Found no active devtools sockets');
159
+ if (!_.isEmpty(allMatches)) {
160
+ logger.debug(`Other sockets are: ${JSON.stringify(allMatches, null, 2)}`);
161
+ }
162
+ } else {
163
+ logger.debug(
164
+ `Parsed ${names.length} active devtools ${util.pluralize('socket', names.length, false)}: ` +
165
+ JSON.stringify(names)
166
+ );
167
+ }
168
+ // sometimes the webview process shows up multiple times per app
169
+ return _.uniq(names);
170
+ }
171
+
172
+ /**
173
+ * This function retrieves a list of system processes that look like webviews,
174
+ * and returns them along with the webview context name appropriate for it.
175
+ * If we pass in a deviceSocket, we only attempt to find webviews which match
176
+ * that socket name (this is for apps which embed Chromium, which isn't the
177
+ * same as chrome-backed webviews).
178
+ *
179
+ * @param adb - an ADB instance
180
+ * @param deviceSocket - the explictly-named device socket to use
181
+ */
182
+ async function webviewsFromProcs(
183
+ adb: any,
184
+ deviceSocket: string | null = null
185
+ ): Promise<WebviewProc[]> {
186
+ const socketNames = await getPotentialWebviewProcs(adb);
187
+ const webviews: {proc: string; webview: string}[] = [];
188
+ for (const socketName of socketNames) {
189
+ if (deviceSocket === CHROMIUM_DEVTOOLS_SOCKET && socketName === `@${deviceSocket}`) {
190
+ webviews.push({
191
+ proc: socketName,
192
+ webview: CHROMIUM_WIN,
193
+ });
194
+ continue;
195
+ }
196
+
197
+ const socketNameMatch = DEVTOOLS_SOCKET_PATTERN.exec(socketName);
198
+ if (!socketNameMatch) {
199
+ continue;
200
+ }
201
+ const matchedSocketName = socketNameMatch[2];
202
+ const crosswalkMatch = CROSSWALK_SOCKET_PATTERN.exec(socketName);
203
+ if (!matchedSocketName && !crosswalkMatch) {
204
+ continue;
205
+ }
206
+
207
+ if ((deviceSocket && socketName === `@${deviceSocket}`) || !deviceSocket) {
208
+ webviews.push({
209
+ proc: socketName,
210
+ webview: matchedSocketName
211
+ ? `${WEBVIEW_BASE}${matchedSocketName}`
212
+ : // @ts-expect-error: XXX crosswalkMatch can absolutely be null
213
+ `${WEBVIEW_BASE}${crosswalkMatch[1]}`,
214
+ });
215
+ }
216
+ }
217
+ return webviews;
218
+ }
219
+
220
+ /**
221
+ * Allocates a local port for devtools communication
222
+ *
223
+ * @param adb - ADB instance
224
+ * @param socketName - The remote Unix socket name
225
+ * @param webviewDevtoolsPort - The local port number or null to apply
226
+ * autodetection
227
+ * @returns The local port number if the remote socket has been forwarded
228
+ * successfully or `null` otherwise
229
+ * @throws {Error} If there was an error while allocating the local port
230
+ */
231
+ async function allocateDevtoolsPort(
232
+ adb: any,
233
+ socketName: string,
234
+ webviewDevtoolsPort: number | null = null
235
+ ): Promise<number> {
236
+ // socket names come with '@', but this should not be a part of the abstract
237
+ // remote port, so remove it
238
+ const remotePort = socketName.replace(/^@/, '');
239
+ let [startPort, endPort] = DEVTOOLS_PORTS_RANGE;
240
+ if (webviewDevtoolsPort) {
241
+ endPort = webviewDevtoolsPort + (endPort - startPort);
242
+ startPort = webviewDevtoolsPort;
243
+ }
244
+ logger.debug(
245
+ `Forwarding remote port ${remotePort} to a local ` + `port in range ${startPort}..${endPort}`
246
+ );
247
+ if (!webviewDevtoolsPort) {
248
+ logger.debug(
249
+ `You could use the 'webviewDevtoolsPort' capability to customize ` +
250
+ `the starting port number`
251
+ );
252
+ }
253
+ return (await DEVTOOLS_PORT_ALLOCATION_GUARD(async () => {
254
+ let localPort: number;
255
+ try {
256
+ localPort = await findAPortNotInUse(startPort, endPort);
257
+ } catch (e) {
258
+ throw new Error(
259
+ `Cannot find any free port to forward the Devtools socket ` +
260
+ `in range ${startPort}..${endPort}. You could set the starting port number ` +
261
+ `manually by providing the 'webviewDevtoolsPort' capability`
262
+ );
263
+ }
264
+ await adb.adbExec(['forward', `tcp:${localPort}`, `localabstract:${remotePort}`]);
265
+ return localPort;
266
+ })) as number;
267
+ }
268
+
269
+ /**
270
+ * This is a wrapper for Chrome Debugger Protocol data collection.
271
+ * No error is thrown if CDP request fails - in such case no data will be
272
+ * recorded into the corresponding `webviewsMapping` item.
273
+ *
274
+ * @param adb The ADB instance
275
+ * @param webviewsMapping The current webviews mapping
276
+ * !!! Each item of this array gets mutated (`info`/`pages` properties get added
277
+ * based on the provided `opts`) if the requested details have been
278
+ * successfully retrieved for it !!!
279
+ * @param opts If both `ensureWebviewsHavePages` and
280
+ * `enableWebviewDetailsCollection` properties are falsy then no details collection
281
+ * is performed
282
+ */
283
+ async function collectWebviewsDetails(
284
+ adb: ADB,
285
+ webviewsMapping: WebviewProps[],
286
+ opts: DetailCollectionOptions = {}
287
+ ): Promise<void> {
288
+ if (_.isEmpty(webviewsMapping)) {
289
+ return;
290
+ }
291
+
292
+ const {
293
+ webviewDevtoolsPort = null,
294
+ ensureWebviewsHavePages = null,
295
+ enableWebviewDetailsCollection = null,
296
+ } = opts;
297
+
298
+ if (!ensureWebviewsHavePages) {
299
+ logger.info(
300
+ `Not checking whether webviews have active pages; use the ` +
301
+ `'ensureWebviewsHavePages' cap to turn this check on`
302
+ );
303
+ }
304
+
305
+ if (!enableWebviewDetailsCollection) {
306
+ logger.info(
307
+ `Not collecting web view details. Details collection might help ` +
308
+ `to make Chromedriver initialization more precise. Use the 'enableWebviewDetailsCollection' ` +
309
+ `cap to turn it on`
310
+ );
311
+ }
312
+
313
+ if (!ensureWebviewsHavePages && !enableWebviewDetailsCollection) {
314
+ return;
315
+ }
316
+
317
+ // Connect to each devtools socket and retrieve web view details
318
+ logger.debug(`Collecting CDP data of ${util.pluralize('webview', webviewsMapping.length, true)}`);
319
+ const detailCollectors: Promise<void>[] = [];
320
+ for (const item of webviewsMapping) {
321
+ detailCollectors.push(
322
+ (async () => {
323
+ let localPort: number | undefined;
324
+ try {
325
+ localPort = await allocateDevtoolsPort(adb, item.proc, webviewDevtoolsPort);
326
+ if (enableWebviewDetailsCollection) {
327
+ item.info = await cdpInfo(localPort);
328
+ }
329
+ if (ensureWebviewsHavePages) {
330
+ item.pages = await cdpList(localPort);
331
+ }
332
+ } catch (e) {
333
+ logger.debug(e);
334
+ } finally {
335
+ if (localPort) {
336
+ try {
337
+ await adb.removePortForward(localPort);
338
+ } catch (e) {
339
+ logger.debug(e);
340
+ }
341
+ }
342
+ }
343
+ })()
344
+ );
345
+ }
346
+ await B.all(detailCollectors);
347
+ logger.debug(`CDP data collection completed`);
348
+ }
349
+
350
+ // https://chromedevtools.github.io/devtools-protocol/
351
+ async function cdpList(localPort: number): Promise<object[]> {
352
+ return (
353
+ await axios({
354
+ url: `http://127.0.0.1:${localPort}/json/list`,
355
+ timeout: CDP_REQ_TIMEOUT,
356
+ })
357
+ ).data;
358
+ }
359
+
360
+ // https://chromedevtools.github.io/devtools-protocol/
361
+ async function cdpInfo(localPort: number): Promise<object[]> {
362
+ return (
363
+ await axios({
364
+ url: `http://127.0.0.1:${localPort}/json/version`,
365
+ timeout: CDP_REQ_TIMEOUT,
366
+ })
367
+ ).data;
368
+ }
369
+
370
+ const WebviewHelpers: WebviewHelpers = {
371
+ async procFromWebview(adb: ADB, webview: string): Promise<string> {
372
+ const pidMatch = WEBVIEW_PID_PATTERN.exec(webview);
373
+ if (!pidMatch) {
374
+ throw new Error(`Could not find PID for webview '${webview}'`);
375
+ }
376
+
377
+ const pid = pidMatch[1];
378
+ logger.debug(`${webview} mapped to pid ${pid}`);
379
+ logger.debug(`Getting process name for webview '${webview}'`);
380
+ const pkg = await adb.getNameByPid(pid);
381
+ logger.debug(`Got process name: '${pkg}'`);
382
+ return pkg;
383
+ },
384
+
385
+ parseWebviewNames(
386
+ webviewsMapping: WebviewsMapping[],
387
+ {ensureWebviewsHavePages = true, isChromeSession = false}: GetWebviewsOpts = {}
388
+ ): string[] {
389
+ if (isChromeSession) {
390
+ return [CHROMIUM_WIN];
391
+ }
392
+
393
+ const result = [];
394
+ for (const {webview, pages, proc, webviewName} of webviewsMapping) {
395
+ if (ensureWebviewsHavePages && pages?.length === 0) {
396
+ logger.info(
397
+ `Skipping the webview '${webview}' at '${proc}' ` +
398
+ `since it has reported having zero pages`
399
+ );
400
+ continue;
401
+ }
402
+ if (webviewName) {
403
+ result.push(webviewName);
404
+ }
405
+ }
406
+ logger.debug(
407
+ `Found ${util.pluralize('webview', result.length, true)}: ${JSON.stringify(result)}`
408
+ );
409
+ return result;
410
+ },
411
+
412
+ async getWebViewsMapping(
413
+ adb: ADB,
414
+ {
415
+ androidDeviceSocket = null,
416
+ ensureWebviewsHavePages = true,
417
+ webviewDevtoolsPort = null,
418
+ enableWebviewDetailsCollection = true,
419
+ }: GetWebviewsOpts = {}
420
+ ): Promise<WebviewsMapping[]> {
421
+ logger.debug('Getting a list of available webviews');
422
+ const webviewsMapping = (await webviewsFromProcs(
423
+ adb,
424
+ androidDeviceSocket
425
+ )) as WebviewsMapping[];
426
+
427
+ await collectWebviewsDetails(adb, webviewsMapping, {
428
+ ensureWebviewsHavePages,
429
+ enableWebviewDetailsCollection,
430
+ webviewDevtoolsPort,
431
+ });
432
+
433
+ for (const webviewMapping of webviewsMapping) {
434
+ const {webview, info} = webviewMapping;
435
+ webviewMapping.webviewName = null;
436
+
437
+ let wvName = webview;
438
+ let process: {name: string; id: string | null} | undefined;
439
+ if (!androidDeviceSocket) {
440
+ const pkgMatch = WEBVIEW_PKG_PATTERN.exec(webview);
441
+ try {
442
+ // web view name could either be suffixed with PID or the package name
443
+ // package names could not start with a digit
444
+ const pkg = pkgMatch ? pkgMatch[1] : await WebviewHelpers.procFromWebview(adb, webview);
445
+ wvName = `${WEBVIEW_BASE}${pkg}`;
446
+ const pidMatch = WEBVIEW_PID_PATTERN.exec(webview);
447
+ process = {
448
+ name: pkg,
449
+ id: pidMatch ? pidMatch[1] : null,
450
+ };
451
+ } catch (e) {
452
+ logger.warn((e as Error).message);
453
+ continue;
454
+ }
455
+ }
456
+
457
+ webviewMapping.webviewName = wvName;
458
+ const key = toDetailsCacheKey(adb, wvName);
459
+ if (info || process) {
460
+ WEBVIEWS_DETAILS_CACHE.set(key, {info, process});
461
+ } else if (WEBVIEWS_DETAILS_CACHE.has(key)) {
462
+ WEBVIEWS_DETAILS_CACHE.delete(key);
463
+ }
464
+ }
465
+ return webviewsMapping;
466
+ },
467
+
468
+ getWebviewDetails(adb: ADB, webview: string): WebViewDetails | undefined {
469
+ const key = toDetailsCacheKey(adb, webview);
470
+ return WEBVIEWS_DETAILS_CACHE.get(key);
471
+ },
472
+
473
+ createChromedriverCaps(
474
+ opts: any,
475
+ deviceId: string,
476
+ webViewDetails?: WebViewDetails | null
477
+ ): object {
478
+ const caps: AndroidDriverCaps & {chromeOptions: StringRecord} = {chromeOptions: {}} as any;
479
+
480
+ const androidPackage =
481
+ opts.chromeOptions?.androidPackage ||
482
+ opts.appPackage ||
483
+ webViewDetails?.info?.['Android-Package'];
484
+ if (androidPackage) {
485
+ // chromedriver raises an invalid argument error when androidPackage is 'null'
486
+
487
+ caps.chromeOptions.androidPackage = androidPackage;
488
+ }
489
+ if (_.isBoolean(opts.chromeUseRunningApp)) {
490
+ caps.chromeOptions.androidUseRunningApp = opts.chromeUseRunningApp;
491
+ }
492
+ if (opts.chromeAndroidPackage) {
493
+ caps.chromeOptions.androidPackage = opts.chromeAndroidPackage;
494
+ }
495
+ if (opts.chromeAndroidActivity) {
496
+ caps.chromeOptions.androidActivity = opts.chromeAndroidActivity;
497
+ }
498
+ if (opts.chromeAndroidProcess) {
499
+ caps.chromeOptions.androidProcess = opts.chromeAndroidProcess;
500
+ } else if (webViewDetails?.process?.name && webViewDetails?.process?.id) {
501
+ caps.chromeOptions.androidProcess = webViewDetails.process.name;
502
+ }
503
+ if (_.toLower(opts.browserName) === 'chromium-webview') {
504
+ caps.chromeOptions.androidActivity = opts.appActivity;
505
+ }
506
+ if (opts.pageLoadStrategy) {
507
+ caps.pageLoadStrategy = opts.pageLoadStrategy;
508
+ }
509
+ const isChrome = _.toLower(caps.chromeOptions.androidPackage) === 'chrome';
510
+ if (_.includes(KNOWN_CHROME_PACKAGE_NAMES, caps.chromeOptions.androidPackage) || isChrome) {
511
+ // if we have extracted package from context name, it could come in as bare
512
+ // "chrome", and so we should make sure the details are correct, including
513
+ // not using an activity or process id
514
+ if (isChrome) {
515
+ caps.chromeOptions.androidPackage = CHROME_PACKAGE_NAME;
516
+ }
517
+ delete caps.chromeOptions.androidActivity;
518
+ delete caps.chromeOptions.androidProcess;
519
+ }
520
+ // add device id from adb
521
+ caps.chromeOptions.androidDeviceSerial = deviceId;
522
+
523
+ if (_.isPlainObject(opts.loggingPrefs) || _.isPlainObject(opts.chromeLoggingPrefs)) {
524
+ if (opts.loggingPrefs) {
525
+ logger.warn(
526
+ `The 'loggingPrefs' cap is deprecated; use the 'chromeLoggingPrefs' cap instead`
527
+ );
528
+ }
529
+ // @ts-expect-error Why are we using this if it's deprecated?
530
+ caps.loggingPrefs = opts.chromeLoggingPrefs || opts.loggingPrefs;
531
+ }
532
+ if (opts.enablePerformanceLogging) {
533
+ logger.warn(
534
+ `The 'enablePerformanceLogging' cap is deprecated; simply use ` +
535
+ `the 'chromeLoggingPrefs' cap instead, with a 'performance' key set to 'ALL'`
536
+ );
537
+ const newPref = {performance: 'ALL'};
538
+ // don't overwrite other logging prefs that have been sent in if they exist
539
+ // @ts-expect-error Why are we using this if it's deprecated?
540
+ caps.loggingPrefs = caps.loggingPrefs
541
+ ? // @ts-expect-error Why are we using this if it's deprecated?
542
+ Object.assign({}, caps.loggingPrefs, newPref)
543
+ : newPref;
544
+ }
545
+
546
+ if (opts.chromeOptions?.Arguments) {
547
+ // merge `Arguments` and `args`
548
+ opts.chromeOptions.args = [
549
+ ...(opts.chromeOptions.args || []),
550
+ ...opts.chromeOptions.Arguments,
551
+ ];
552
+ delete opts.chromeOptions.Arguments;
553
+ }
554
+
555
+ logger.debug(
556
+ 'Precalculated Chromedriver capabilities: ' + JSON.stringify(caps.chromeOptions, null, 2)
557
+ );
558
+
559
+ const protectedCapNames: string[] = [];
560
+ for (const [opt, val] of _.toPairs(opts.chromeOptions)) {
561
+ if (_.isUndefined(caps.chromeOptions[opt])) {
562
+ caps.chromeOptions[opt] = val;
563
+ } else {
564
+ protectedCapNames.push(opt);
565
+ }
566
+ }
567
+ if (!_.isEmpty(protectedCapNames)) {
568
+ logger.info(
569
+ 'The following Chromedriver capabilities cannot be overridden ' +
570
+ 'by the provided chromeOptions:'
571
+ );
572
+ for (const optName of protectedCapNames) {
573
+ logger.info(` ${optName} (${JSON.stringify(opts.chromeOptions[optName])})`);
574
+ }
575
+ }
576
+
577
+ return caps;
578
+ },
579
+ };
580
+
581
+ export {CHROMIUM_WIN, KNOWN_CHROME_PACKAGE_NAMES, NATIVE_WIN, WEBVIEW_BASE, WEBVIEW_WIN};
582
+ export default WebviewHelpers;
package/lib/index.ts ADDED
@@ -0,0 +1,18 @@
1
+ import {install} from 'source-map-support';
2
+ install();
3
+
4
+ import {AndroidDriver} from './driver';
5
+ export type * from './commands';
6
+ export {ANDROID_DRIVER_CONSTRAINTS as commonCapConstraints} from './constraints';
7
+ export * from './driver';
8
+ export {SETTINGS_HELPER_PKG_ID, default as androidHelpers} from './helpers/android';
9
+ export type * from './helpers/types';
10
+ export {
11
+ CHROMIUM_WIN,
12
+ NATIVE_WIN,
13
+ WEBVIEW_BASE,
14
+ WEBVIEW_WIN,
15
+ default as webviewHelpers,
16
+ } from './helpers/webview';
17
+
18
+ export default AndroidDriver;