@appium/base-driver 8.2.4 → 8.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/build/lib/basedriver/commands/find.js +4 -11
  2. package/build/lib/basedriver/commands/log.js +3 -6
  3. package/build/lib/basedriver/commands/session.js +18 -27
  4. package/build/lib/basedriver/commands/settings.js +4 -8
  5. package/build/lib/basedriver/commands/timeout.js +10 -15
  6. package/build/lib/basedriver/device-settings.js +14 -2
  7. package/build/lib/basedriver/driver.js +22 -20
  8. package/build/lib/basedriver/helpers.js +9 -9
  9. package/build/lib/express/express-logging.js +2 -2
  10. package/build/lib/express/idempotency.js +2 -2
  11. package/build/lib/helpers/capabilities.js +39 -0
  12. package/build/lib/index.js +3 -5
  13. package/build/lib/jsonwp-proxy/protocol-converter.js +18 -12
  14. package/build/lib/jsonwp-proxy/proxy.js +19 -12
  15. package/build/lib/protocol/protocol.js +36 -27
  16. package/build/lib/protocol/routes.js +67 -1
  17. package/build/test/basedriver/capabilities-specs.js +43 -1
  18. package/build/test/basedriver/capability-specs.js +126 -167
  19. package/build/test/basedriver/commands/log-specs.js +12 -5
  20. package/build/test/basedriver/driver-tests.js +11 -14
  21. package/build/test/basedriver/timeout-specs.js +7 -9
  22. package/build/test/express/server-e2e-specs.js +10 -5
  23. package/build/test/express/server-specs.js +22 -16
  24. package/build/test/express/static-specs.js +10 -5
  25. package/build/test/protocol/fake-driver.js +12 -15
  26. package/build/test/protocol/protocol-e2e-specs.js +16 -10
  27. package/build/test/protocol/routes-specs.js +2 -2
  28. package/lib/basedriver/commands/find.js +3 -6
  29. package/lib/basedriver/commands/log.js +2 -4
  30. package/lib/basedriver/commands/session.js +21 -22
  31. package/lib/basedriver/commands/settings.js +3 -5
  32. package/lib/basedriver/commands/timeout.js +9 -10
  33. package/lib/basedriver/device-settings.js +10 -1
  34. package/lib/basedriver/driver.js +25 -12
  35. package/lib/basedriver/helpers.js +13 -11
  36. package/lib/express/express-logging.js +1 -1
  37. package/lib/express/idempotency.js +1 -1
  38. package/lib/helpers/capabilities.js +25 -0
  39. package/lib/index.js +2 -2
  40. package/lib/jsonwp-proxy/protocol-converter.js +14 -13
  41. package/lib/jsonwp-proxy/proxy.js +16 -12
  42. package/lib/protocol/protocol.js +34 -29
  43. package/lib/protocol/routes.js +60 -1
  44. package/package.json +29 -22
  45. package/test/basedriver/capabilities-specs.js +34 -2
  46. package/test/basedriver/capability-specs.js +120 -146
  47. package/test/basedriver/commands/log-specs.js +12 -3
  48. package/test/basedriver/driver-tests.js +12 -7
  49. package/test/basedriver/timeout-specs.js +6 -11
  50. package/build/lib/protocol/sessions-cache.js +0 -88
  51. package/lib/protocol/sessions-cache.js +0 -74
@@ -1,45 +1,44 @@
1
1
  /* eslint-disable require-await */
2
2
  import _ from 'lodash';
3
- import log from '../logger';
4
3
  import { errors } from '../../protocol';
5
4
  import { util } from '@appium/support';
6
- import { processCapabilities, promoteAppiumOptions, APPIUM_OPTS_CAP, PREFIXED_APPIUM_OPTS_CAP } from '../capabilities';
5
+ import {
6
+ processCapabilities, promoteAppiumOptions, APPIUM_OPTS_CAP, PREFIXED_APPIUM_OPTS_CAP,
7
+ } from '../capabilities';
8
+ import { isW3cCaps } from '../../helpers/capabilities';
7
9
 
8
- let commands = {};
10
+ const commands = {};
9
11
 
10
- // TODO: Remove jsonwpDesiredCapabilities and jsonwpRequiredCaps completely
11
- // since Appium 2.0 no longer supports them.
12
- commands.createSession = async function createSession (jsonwpDesiredCapabilities, jsonwpRequiredCaps, w3cCapabilities) {
12
+ commands.createSession = async function createSession (w3cCapabilities1, w3cCapabilities2, w3cCapabilities) {
13
13
  if (this.sessionId !== null) {
14
- throw new errors.SessionNotCreatedError('Cannot create a new session ' +
15
- 'while one is in progress');
14
+ throw new errors.SessionNotCreatedError('Cannot create a new session while one is in progress');
16
15
  }
17
16
 
18
- log.debug();
17
+ this.log.debug();
19
18
 
20
- if (!w3cCapabilities) {
19
+ // Historically the first two arguments were reserved for JSONWP capabilities.
20
+ // Appium 2 has dropped the support of these, so now we only accept capability
21
+ // objects in W3C format and thus allow any of the three arguments to represent
22
+ // the latter.
23
+ const originalCaps = [w3cCapabilities, w3cCapabilities1, w3cCapabilities2].find(isW3cCaps);
24
+ if (!originalCaps) {
21
25
  throw new errors.SessionNotCreatedError('Appium only supports W3C-style capability objects. ' +
22
26
  'Your client is sending an older capabilities format. Please update your client library.');
23
27
  }
24
28
 
25
- if (jsonwpDesiredCapabilities) {
26
- log.warn('Appium received (M)JSONWP desired capabilities in alongside the W3C capabilities; they will be ignored');
27
- }
28
-
29
29
  this.setProtocolW3C();
30
30
 
31
- this.originalCaps = _.cloneDeep(w3cCapabilities);
32
- log.debug(`Creating session with W3C capabilities: ${JSON.stringify(w3cCapabilities, null, 2)}`);
33
-
31
+ this.originalCaps = _.cloneDeep(originalCaps);
32
+ this.log.debug(`Creating session with W3C capabilities: ${JSON.stringify(originalCaps, null, 2)}`);
34
33
 
35
34
  let caps;
36
35
  try {
37
- caps = processCapabilities(w3cCapabilities, this.desiredCapConstraints, this.shouldValidateCaps);
36
+ caps = processCapabilities(originalCaps, this.desiredCapConstraints, this.shouldValidateCaps);
38
37
  if (caps[APPIUM_OPTS_CAP]) {
39
- log.debug(`Found ${PREFIXED_APPIUM_OPTS_CAP} capability present; will promote items inside to caps`);
38
+ this.log.debug(`Found ${PREFIXED_APPIUM_OPTS_CAP} capability present; will promote items inside to caps`);
40
39
  caps = promoteAppiumOptions(caps);
41
40
  }
42
- caps = fixCaps(caps, this.desiredCapConstraints);
41
+ caps = fixCaps(caps, this.desiredCapConstraints, this.log);
43
42
  } catch (e) {
44
43
  throw new errors.SessionNotCreatedError(e.message);
45
44
  }
@@ -79,7 +78,7 @@ commands.createSession = async function createSession (jsonwpDesiredCapabilities
79
78
  this.newCommandTimeoutMs = (this.caps.newCommandTimeout * 1000);
80
79
  }
81
80
 
82
- log.info(`Session created with session id: ${this.sessionId}`);
81
+ this.log.info(`Session created with session id: ${this.sessionId}`);
83
82
 
84
83
  return [this.sessionId, caps];
85
84
  };
@@ -115,7 +114,7 @@ commands.deleteSession = async function deleteSession (/* sessionId */) {
115
114
  this.sessionId = null;
116
115
  };
117
116
 
118
- function fixCaps (originalCaps, desiredCapConstraints = {}) {
117
+ function fixCaps (originalCaps, desiredCapConstraints = {}, log) {
119
118
  let caps = _.clone(originalCaps);
120
119
 
121
120
  // boolean capabilities can be passed in as strings 'false' and 'true'
@@ -1,17 +1,15 @@
1
- import log from '../logger';
2
-
3
- let commands = {};
1
+ const commands = {};
4
2
 
5
3
  commands.updateSettings = async function updateSettings (newSettings) {
6
4
  if (!this.settings) {
7
- log.errorAndThrow('Cannot update settings; settings object not found');
5
+ this.log.errorAndThrow('Cannot update settings; settings object not found');
8
6
  }
9
7
  return await this.settings.update(newSettings);
10
8
  };
11
9
 
12
10
  commands.getSettings = async function getSettings () {
13
11
  if (!this.settings) {
14
- log.errorAndThrow('Cannot get settings; settings object not found');
12
+ this.log.errorAndThrow('Cannot get settings; settings object not found');
15
13
  }
16
14
  return await this.settings.getSettings();
17
15
  };
@@ -1,4 +1,3 @@
1
- import log from '../logger';
2
1
  import { waitForCondition } from 'asyncbox';
3
2
  import _ from 'lodash';
4
3
  import { util } from '@appium/support';
@@ -11,7 +10,7 @@ const MIN_TIMEOUT = 0;
11
10
 
12
11
  commands.timeouts = async function timeouts (type, ms, script, pageLoad, implicit) {
13
12
  if (util.hasValue(type) && util.hasValue(ms)) {
14
- log.debug(`MJSONWP timeout arguments: ${JSON.stringify({type, ms})}}`);
13
+ this.log.debug(`MJSONWP timeout arguments: ${JSON.stringify({type, ms})}}`);
15
14
 
16
15
  switch (type) {
17
16
  case 'command':
@@ -32,7 +31,7 @@ commands.timeouts = async function timeouts (type, ms, script, pageLoad, implici
32
31
  }
33
32
 
34
33
  // Otherwise assume it is W3C protocol
35
- log.debug(`W3C timeout argument: ${JSON.stringify({script, pageLoad, implicit})}}`);
34
+ this.log.debug(`W3C timeout argument: ${JSON.stringify({script, pageLoad, implicit})}}`);
36
35
  if (util.hasValue(script)) {
37
36
  await this.scriptTimeoutW3C(script);
38
37
  }
@@ -66,9 +65,9 @@ commands.implicitWait = async function implicitWait (ms) {
66
65
 
67
66
  helpers.setImplicitWait = function setImplicitWait (ms) { // eslint-disable-line require-await
68
67
  this.implicitWaitMs = ms;
69
- log.debug(`Set implicit wait to ${ms}ms`);
68
+ this.log.debug(`Set implicit wait to ${ms}ms`);
70
69
  if (this.managedDrivers && this.managedDrivers.length) {
71
- log.debug('Setting implicit wait on managed drivers');
70
+ this.log.debug('Setting implicit wait on managed drivers');
72
71
  for (let driver of this.managedDrivers) {
73
72
  if (_.isFunction(driver.setImplicitWait)) {
74
73
  driver.setImplicitWait(ms);
@@ -106,9 +105,9 @@ commands.newCommandTimeout = async function newCommandTimeout (ms) { // eslint-d
106
105
 
107
106
  helpers.setNewCommandTimeout = function setNewCommandTimeout (ms) {
108
107
  this.newCommandTimeoutMs = ms;
109
- log.debug(`Set new command timeout to ${ms}ms`);
108
+ this.log.debug(`Set new command timeout to ${ms}ms`);
110
109
  if (this.managedDrivers && this.managedDrivers.length) {
111
- log.debug('Setting new command timeout on managed drivers');
110
+ this.log.debug('Setting new command timeout on managed drivers');
112
111
  for (let driver of this.managedDrivers) {
113
112
  if (_.isFunction(driver.setNewCommandTimeout)) {
114
113
  driver.setNewCommandTimeout(ms);
@@ -132,7 +131,7 @@ helpers.startNewCommandTimeout = function startNewCommandTimeout () {
132
131
  if (!this.newCommandTimeoutMs) return; // eslint-disable-line curly
133
132
 
134
133
  this.noCommandTimer = setTimeout(async () => {
135
- log.warn(`Shutting down because we waited ` +
134
+ this.log.warn(`Shutting down because we waited ` +
136
135
  `${this.newCommandTimeoutMs / 1000.0} seconds for a command`);
137
136
  const errorMessage = `New Command Timeout of ` +
138
137
  `${this.newCommandTimeoutMs / 1000.0} seconds ` +
@@ -143,7 +142,7 @@ helpers.startNewCommandTimeout = function startNewCommandTimeout () {
143
142
  };
144
143
 
145
144
  helpers.implicitWaitForCondition = async function implicitWaitForCondition (condFn) {
146
- log.debug(`Waiting up to ${this.implicitWaitMs} ms for condition`);
145
+ this.log.debug(`Waiting up to ${this.implicitWaitMs} ms for condition`);
147
146
  let wrappedCondFn = async (...args) => {
148
147
  // reset command timeout
149
148
  this.clearNewCommandTimeout();
@@ -151,7 +150,7 @@ helpers.implicitWaitForCondition = async function implicitWaitForCondition (cond
151
150
  return await condFn(...args);
152
151
  };
153
152
  return await waitForCondition(wrappedCondFn, {
154
- waitMs: this.implicitWaitMs, intervalMs: 500, logger: log
153
+ waitMs: this.implicitWaitMs, intervalMs: 500, logger: this.log
155
154
  });
156
155
  };
157
156
 
@@ -1,5 +1,9 @@
1
1
  import _ from 'lodash';
2
2
  import log from './logger';
3
+ import { node, util } from '@appium/support';
4
+ import { errors } from '../protocol/errors';
5
+
6
+ const MAX_SETTINGS_SIZE = 20 * 1024 * 1024; // 20 MB
3
7
 
4
8
  class DeviceSettings {
5
9
 
@@ -11,9 +15,14 @@ class DeviceSettings {
11
15
  // calls updateSettings from implementing driver every time a setting is changed.
12
16
  async update (newSettings) {
13
17
  if (!_.isPlainObject(newSettings)) {
14
- throw new Error(`Settings update should be called with valid JSON. Got ` +
18
+ throw new errors.InvalidArgumentError(`Settings update should be called with valid JSON. Got ` +
15
19
  `${JSON.stringify(newSettings)} instead`);
16
20
  }
21
+ if (node.getObjectSize({...this._settings, ...newSettings}) >= MAX_SETTINGS_SIZE) {
22
+ throw new errors.InvalidArgumentError(`New settings cannot be applied, because the overall ` +
23
+ `object size exceeds the allowed limit of ${util.toReadableSizeString(MAX_SETTINGS_SIZE)}`);
24
+ }
25
+
17
26
  for (const prop of _.keys(newSettings)) {
18
27
  if (!_.isUndefined(this._settings[prop])) {
19
28
  if (this._settings[prop] === newSettings[prop]) {
@@ -1,12 +1,11 @@
1
1
  import {
2
2
  Protocol, errors, determineProtocol, DELETE_SESSION_COMMAND,
3
3
  } from '../protocol';
4
- import { fs } from '@appium/support';
4
+ import { fs, logger, node } from '@appium/support';
5
5
  import { PROTOCOLS, DEFAULT_BASE_PATH } from '../constants';
6
6
  import os from 'os';
7
7
  import commands from './commands';
8
8
  import * as helpers from './helpers';
9
- import log from './logger';
10
9
  import DeviceSettings from './device-settings';
11
10
  import { desiredCapabilityConstraints } from './desired-caps';
12
11
  import { validateCaps } from './capabilities';
@@ -30,6 +29,7 @@ const EVENT_SESSION_QUIT_START = 'quitSessionRequested';
30
29
  const EVENT_SESSION_QUIT_DONE = 'quitSessionFinished';
31
30
  const ON_UNEXPECTED_SHUTDOWN_EVENT = 'onUnexpectedShutdown';
32
31
 
32
+
33
33
  class BaseDriver extends Protocol {
34
34
 
35
35
  /**
@@ -48,6 +48,8 @@ class BaseDriver extends Protocol {
48
48
  this.originalCaps = null; // To give the original capabilities to reset
49
49
  this.helpers = helpers;
50
50
 
51
+ this._log = null;
52
+
51
53
  // basePath is used for several purposes, for example in setting up
52
54
  // proxying to other drivers, since we need to know what the base path
53
55
  // of any incoming request might look like. We set it to the default
@@ -104,6 +106,17 @@ class BaseDriver extends Protocol {
104
106
  this.protocol = null;
105
107
  }
106
108
 
109
+ get log () {
110
+ if (!this._log) {
111
+ const instanceName = `${this.constructor.name}@${node.getObjectId(this).substring(0, 8)}`;
112
+ this._log = logger.getLogger(() =>
113
+ this.sessionId ? `${instanceName} (${this.sessionId.substring(0, 8)})` : instanceName
114
+ );
115
+ }
116
+
117
+ return this._log;
118
+ }
119
+
107
120
  /**
108
121
  * Set a callback handler if needed to execute a custom piece of code
109
122
  * when the driver is shut down unexpectedly. Multiple calls to this method
@@ -168,7 +181,7 @@ class BaseDriver extends Protocol {
168
181
  const ts = Date.now();
169
182
  const logTime = (new Date(ts)).toTimeString();
170
183
  this._eventHistory[eventName].push(ts);
171
- log.debug(`Event '${eventName}' logged at ${ts} (${logTime})`);
184
+ this.log.debug(`Event '${eventName}' logged at ${ts} (${logTime})`);
172
185
  }
173
186
 
174
187
  /*
@@ -214,10 +227,10 @@ class BaseDriver extends Protocol {
214
227
  let extraCaps = _.difference(_.keys(caps),
215
228
  _.keys(this._constraints));
216
229
  if (extraCaps.length) {
217
- log.warn(`The following capabilities were provided, but are not ` +
230
+ this.log.warn(`The following capabilities were provided, but are not ` +
218
231
  `recognized by Appium:`);
219
232
  for (const cap of extraCaps) {
220
- log.warn(` ${cap}`);
233
+ this.log.warn(` ${cap}`);
221
234
  }
222
235
  }
223
236
  }
@@ -230,8 +243,8 @@ class BaseDriver extends Protocol {
230
243
  try {
231
244
  validateCaps(caps, this._constraints);
232
245
  } catch (e) {
233
- log.errorAndThrow(new errors.SessionNotCreatedError(`The desiredCapabilities object was not valid for the ` +
234
- `following reason(s): ${e.message}`));
246
+ this.log.errorAndThrow(new errors.SessionNotCreatedError(`The desiredCapabilities object was not valid for the ` +
247
+ `following reason(s): ${e.message}`));
235
248
  }
236
249
 
237
250
  this.logExtraCaps(caps);
@@ -309,7 +322,7 @@ class BaseDriver extends Protocol {
309
322
 
310
323
  if (cmd === 'createSession') {
311
324
  // If creating a session determine if W3C or MJSONWP protocol was requested and remember the choice
312
- this.protocol = determineProtocol(...args);
325
+ this.protocol = determineProtocol(args);
313
326
  this.logEvent(EVENT_SESSION_INIT);
314
327
  } else if (cmd === DELETE_SESSION_COMMAND) {
315
328
  this.logEvent(EVENT_SESSION_QUIT_START);
@@ -381,7 +394,7 @@ class BaseDriver extends Protocol {
381
394
 
382
395
  validateLocatorStrategy (strategy, webContext = false) {
383
396
  let validStrategies = this.locatorStrategies;
384
- log.debug(`Valid locator strategies for this request: ${validStrategies.join(', ')}`);
397
+ this.log.debug(`Valid locator strategies for this request: ${validStrategies.join(', ')}`);
385
398
 
386
399
  if (webContext) {
387
400
  validStrategies = validStrategies.concat(this.webLocatorStrategies);
@@ -397,8 +410,8 @@ class BaseDriver extends Protocol {
397
410
  * preserving the timeout config.
398
411
  */
399
412
  async reset () {
400
- log.debug('Resetting app mid-session');
401
- log.debug('Running generic full reset');
413
+ this.log.debug('Resetting app mid-session');
414
+ this.log.debug('Running generic full reset');
402
415
 
403
416
  // preserving state
404
417
  let currentConfig = {};
@@ -411,7 +424,7 @@ class BaseDriver extends Protocol {
411
424
 
412
425
  try {
413
426
  await this.deleteSession(this.sessionId);
414
- log.debug('Restarting app');
427
+ this.log.debug('Restarting app');
415
428
  await this.createSession(undefined, undefined, this.originalCaps);
416
429
  } finally {
417
430
  // always restore state.
@@ -15,17 +15,17 @@ const ZIP_MIME_TYPES = [
15
15
  'multipart/x-zip',
16
16
  ];
17
17
  const CACHED_APPS_MAX_AGE = 1000 * 60 * 60 * 24; // ms
18
+ const MAX_CACHED_APPS = 1024;
18
19
  const APPLICATIONS_CACHE = new LRU({
19
- maxAge: CACHED_APPS_MAX_AGE, // expire after 24 hours
20
+ max: MAX_CACHED_APPS,
21
+ ttl: CACHED_APPS_MAX_AGE, // expire after 24 hours
20
22
  updateAgeOnGet: true,
21
23
  dispose: (app, {fullPath}) => {
22
24
  logger.info(`The application '${app}' cached at '${fullPath}' has ` +
23
25
  `expired after ${CACHED_APPS_MAX_AGE}ms`);
24
- setTimeout(async () => {
25
- if (fullPath) {
26
- await fs.rimraf(fullPath);
27
- }
28
- });
26
+ if (fullPath) {
27
+ fs.rimraf(fullPath);
28
+ }
29
29
  },
30
30
  noDisposeOnSet: true,
31
31
  });
@@ -35,11 +35,11 @@ const DEFAULT_BASENAME = 'appium-app';
35
35
  const APP_DOWNLOAD_TIMEOUT_MS = 120 * 1000;
36
36
 
37
37
  process.on('exit', () => {
38
- if (APPLICATIONS_CACHE.itemCount === 0) {
38
+ if (APPLICATIONS_CACHE.size === 0) {
39
39
  return;
40
40
  }
41
41
 
42
- const appPaths = APPLICATIONS_CACHE.values()
42
+ const appPaths = [...APPLICATIONS_CACHE.values()]
43
43
  .map(({fullPath}) => fullPath);
44
44
  logger.debug(`Performing cleanup of ${appPaths.length} cached ` +
45
45
  util.pluralize('application', appPaths.length));
@@ -151,7 +151,7 @@ async function isAppIntegrityOk (currentPath, expectedIntegrity = {}) {
151
151
  }
152
152
 
153
153
  /**
154
- * @typedef {Object} PostProcessOptions
154
+ * @typedef PostProcessOptions
155
155
  * @property {?Object} cachedAppInfo The information about the previously cached app instance (if exists):
156
156
  * - packageHash: SHA1 hash of the package if it is a file and not a folder
157
157
  * - lastModified: Optional Date instance, the value of file's `Last-Modified` header
@@ -171,13 +171,13 @@ async function isAppIntegrityOk (currentPath, expectedIntegrity = {}) {
171
171
  */
172
172
 
173
173
  /**
174
- * @typedef {Object} PostProcessResult
174
+ * @typedef PostProcessResult
175
175
  * @property {string} appPath The full past to the post-processed application package on the
176
176
  * local file system (might be a file or a folder path)
177
177
  */
178
178
 
179
179
  /**
180
- * @typedef {Object} ConfigureAppOptions
180
+ * @typedef ConfigureAppOptions
181
181
  * @property {(obj: PostProcessOptions) => (Promise<PostProcessResult|undefined>|PostProcessResult|undefined)} onPostProcess
182
182
  * Optional function, which should be applied
183
183
  * to the application after it is downloaded/preprocessed. This function may be async
@@ -193,6 +193,8 @@ async function isAppIntegrityOk (currentPath, expectedIntegrity = {}) {
193
193
  /**
194
194
  * Prepares an app to be used in an automated test. The app gets cached automatically
195
195
  * if it is an archive or if it is downloaded from an URL.
196
+ * If the downloaded app has `.zip` extension, this method will unzip it.
197
+ * The unzip does not work when `onPostProcess` is provided.
196
198
  *
197
199
  * @param {string} app Either a full path to the app or a remote URL
198
200
  * @param {string|string[]|ConfigureAppOptions} options
@@ -1,5 +1,5 @@
1
1
  import _ from 'lodash';
2
- import '@dabh/colors';
2
+ import '@colors/colors';
3
3
  import morgan from 'morgan';
4
4
  import log from './logger';
5
5
  import { MAX_LOG_BODY_LENGTH } from '../constants';
@@ -20,7 +20,7 @@ const MONITORED_METHODS = ['POST', 'PATCH'];
20
20
  const IDEMPOTENCY_KEY_HEADER = 'x-idempotency-key';
21
21
 
22
22
  process.on('exit', () => {
23
- const resPaths = IDEMPOTENT_RESPONSES.values()
23
+ const resPaths = [...IDEMPOTENT_RESPONSES.values()]
24
24
  .map(({response}) => response)
25
25
  .filter(Boolean);
26
26
  for (const resPath of resPaths) {
@@ -0,0 +1,25 @@
1
+ import _ from 'lodash';
2
+
3
+ function isW3cCaps (caps) {
4
+ if (!_.isPlainObject(caps)) {
5
+ return false;
6
+ }
7
+
8
+ const isFirstMatchValid = () => _.isArray(caps.firstMatch)
9
+ && !_.isEmpty(caps.firstMatch) && _.every(caps.firstMatch, _.isPlainObject);
10
+ const isAlwaysMatchValid = () => _.isPlainObject(caps.alwaysMatch);
11
+ if (_.has(caps, 'firstMatch') && _.has(caps, 'alwaysMatch')) {
12
+ return isFirstMatchValid() && isAlwaysMatchValid();
13
+ }
14
+ if (_.has(caps, 'firstMatch')) {
15
+ return isFirstMatchValid();
16
+ }
17
+ if (_.has(caps, 'alwaysMatch')) {
18
+ return isAlwaysMatchValid();
19
+ }
20
+ return false;
21
+ }
22
+
23
+ export {
24
+ isW3cCaps,
25
+ };
package/lib/index.js CHANGED
@@ -5,9 +5,9 @@ import * as driver from './basedriver/driver';
5
5
  import * as deviceSettings from './basedriver/device-settings';
6
6
 
7
7
  const { BaseDriver } = driver;
8
- const { DeviceSettings, BASEDRIVER_HANDLED_SETTINGS } = deviceSettings;
8
+ const { DeviceSettings } = deviceSettings;
9
9
 
10
- export { BaseDriver, DeviceSettings, BASEDRIVER_HANDLED_SETTINGS };
10
+ export { BaseDriver, DeviceSettings };
11
11
  export default BaseDriver;
12
12
 
13
13
 
@@ -5,9 +5,6 @@ import {
5
5
  MJSONWP_ELEMENT_KEY, W3C_ELEMENT_KEY, PROTOCOLS
6
6
  } from '../constants';
7
7
 
8
- const log = logger.getLogger('Protocol Converter');
9
-
10
-
11
8
  export const COMMAND_URLS_CONFLICTS = [
12
9
  {
13
10
  commandNames: ['execute', 'executeAsync'],
@@ -41,20 +38,24 @@ export const COMMAND_URLS_CONFLICTS = [
41
38
  jsonwpConverter: (w3cUrl) => {
42
39
  const w3cPropertyRegex = /\/element\/([^/]+)\/property\/([^/]+)/;
43
40
  const jsonwpUrl = w3cUrl.replace(w3cPropertyRegex, '/element/$1/attribute/$2');
44
- log.info(`Converting W3C '${w3cUrl}' to '${jsonwpUrl}'`);
45
41
  return jsonwpUrl;
46
42
  },
47
43
  w3cConverter: (jsonwpUrl) => jsonwpUrl // Don't convert JSONWP URL to W3C. W3C accepts /attribute and /property
48
44
  }
49
45
  ];
50
-
51
46
  const {MJSONWP, W3C} = PROTOCOLS;
47
+ const DEFAULT_LOG = logger.getLogger('Protocol Converter');
52
48
 
53
49
 
54
50
  class ProtocolConverter {
55
- constructor (proxyFunc) {
51
+ constructor (proxyFunc, log = null) {
56
52
  this.proxyFunc = proxyFunc;
57
53
  this._downstreamProtocol = null;
54
+ this._log = log;
55
+ }
56
+
57
+ get log () {
58
+ return this._log ?? DEFAULT_LOG;
58
59
  }
59
60
 
60
61
  set downstreamProtocol (value) {
@@ -107,7 +108,7 @@ class ProtocolConverter {
107
108
  let response, resBody;
108
109
 
109
110
  const timeoutRequestObjects = this.getTimeoutRequestObjects(body);
110
- log.debug(`Will send the following request bodies to /timeouts: ${JSON.stringify(timeoutRequestObjects)}`);
111
+ this.log.debug(`Will send the following request bodies to /timeouts: ${JSON.stringify(timeoutRequestObjects)}`);
111
112
  for (const timeoutObj of timeoutRequestObjects) {
112
113
  [response, resBody] = await this.proxyFunc(url, method, timeoutObj);
113
114
 
@@ -130,14 +131,14 @@ class ProtocolConverter {
130
131
  const bodyObj = util.safeJsonParse(body);
131
132
  if (_.isPlainObject(bodyObj)) {
132
133
  if (this.downstreamProtocol === W3C && _.has(bodyObj, 'name') && !_.has(bodyObj, 'handle')) {
133
- log.debug(`Copied 'name' value '${bodyObj.name}' to 'handle' as per W3C spec`);
134
+ this.log.debug(`Copied 'name' value '${bodyObj.name}' to 'handle' as per W3C spec`);
134
135
  return await this.proxyFunc(url, method, {
135
136
  ...bodyObj,
136
137
  handle: bodyObj.name,
137
138
  });
138
139
  }
139
140
  if (this.downstreamProtocol === MJSONWP && _.has(bodyObj, 'handle') && !_.has(bodyObj, 'name')) {
140
- log.debug(`Copied 'handle' value '${bodyObj.handle}' to 'name' as per JSONWP spec`);
141
+ this.log.debug(`Copied 'handle' value '${bodyObj.handle}' to 'name' as per JSONWP spec`);
141
142
  return await this.proxyFunc(url, method, {
142
143
  ...bodyObj,
143
144
  name: bodyObj.handle,
@@ -156,12 +157,12 @@ class ProtocolConverter {
156
157
  value = _.isString(text)
157
158
  ? [...text]
158
159
  : (_.isArray(text) ? text : []);
159
- log.debug(`Added 'value' property ${JSON.stringify(value)} to 'setValue' request body`);
160
+ this.log.debug(`Added 'value' property ${JSON.stringify(value)} to 'setValue' request body`);
160
161
  } else if (!util.hasValue(text) && util.hasValue(value)) {
161
162
  text = _.isArray(value)
162
163
  ? value.join('')
163
164
  : (_.isString(value) ? value : '');
164
- log.debug(`Added 'text' property ${JSON.stringify(text)} to 'setValue' request body`);
165
+ this.log.debug(`Added 'text' property ${JSON.stringify(text)} to 'setValue' request body`);
165
166
  }
166
167
  return await this.proxyFunc(url, method, Object.assign({}, bodyObj, {
167
168
  text,
@@ -236,11 +237,11 @@ class ProtocolConverter {
236
237
  ? jsonwpConverter(url)
237
238
  : w3cConverter(url);
238
239
  if (rewrittenUrl === url) {
239
- log.debug(`Did not know how to rewrite the original URL '${url}' ` +
240
+ this.log.debug(`Did not know how to rewrite the original URL '${url}' ` +
240
241
  `for ${this.downstreamProtocol} protocol`);
241
242
  break;
242
243
  }
243
- log.info(`Rewrote the original URL '${url}' to '${rewrittenUrl}' ` +
244
+ this.log.info(`Rewrote the original URL '${url}' to '${rewrittenUrl}' ` +
244
245
  `for ${this.downstreamProtocol} protocol`);
245
246
  return await this.proxyFunc(rewrittenUrl, method, body);
246
247
  }
@@ -12,8 +12,7 @@ import { formatResponseValue, formatStatus } from '../protocol/helpers';
12
12
  import http from 'http';
13
13
  import https from 'https';
14
14
 
15
-
16
- const log = logger.getLogger('WD Proxy');
15
+ const DEFAULT_LOG = logger.getLogger('WD Proxy');
17
16
  const DEFAULT_REQUEST_TIMEOUT = 240000;
18
17
  const COMPACT_ERROR_PATTERNS = [
19
18
  /\bECONNREFUSED\b/,
@@ -43,7 +42,12 @@ class JWProxy {
43
42
  };
44
43
  this.httpAgent = new http.Agent(agentOpts);
45
44
  this.httpsAgent = new https.Agent(agentOpts);
46
- this.protocolConverter = new ProtocolConverter(this.proxy.bind(this));
45
+ this.protocolConverter = new ProtocolConverter(this.proxy.bind(this), opts.log);
46
+ this._log = opts.log;
47
+ }
48
+
49
+ get log () {
50
+ return this._log ?? DEFAULT_LOG;
47
51
  }
48
52
 
49
53
  /**
@@ -166,7 +170,7 @@ class JWProxy {
166
170
  }
167
171
  }
168
172
 
169
- log.debug(`Proxying [${method} ${url || '/'}] to [${method} ${newUrl}] ` +
173
+ this.log.debug(`Proxying [${method} ${url || '/'}] to [${method} ${newUrl}] ` +
170
174
  (reqOpts.data ? `with body: ${truncateBody(reqOpts.data)}` : 'with no body'));
171
175
 
172
176
  const throwProxyError = (error) => {
@@ -187,7 +191,7 @@ class JWProxy {
187
191
  // If it cannot be coerced to an object then the response is wrong
188
192
  throwProxyError(data);
189
193
  }
190
- log.debug(`Got response with status ${status}: ${truncateBody(data)}`);
194
+ this.log.debug(`Got response with status ${status}: ${truncateBody(data)}`);
191
195
  isResponseLogged = true;
192
196
  const isSessionCreationRequest = /\/session$/.test(url) && method === 'POST';
193
197
  if (isSessionCreationRequest) {
@@ -195,7 +199,7 @@ class JWProxy {
195
199
  this.sessionId = data.sessionId || (data.value || {}).sessionId;
196
200
  }
197
201
  this.downstreamProtocol = this.getProtocolFromResBody(data);
198
- log.info(`Determined the downstream protocol as '${this.downstreamProtocol}'`);
202
+ this.log.info(`Determined the downstream protocol as '${this.downstreamProtocol}'`);
199
203
  }
200
204
  if (_.has(data, 'status') && parseInt(data.status, 10) !== 0) {
201
205
  // Some servers, like chromedriver may return response code 200 for non-zero JSONWP statuses
@@ -211,16 +215,16 @@ class JWProxy {
211
215
  if (util.hasValue(e.response)) {
212
216
  if (!isResponseLogged) {
213
217
  const error = truncateBody(e.response.data);
214
- log.info(util.hasValue(e.response.status)
218
+ this.log.info(util.hasValue(e.response.status)
215
219
  ? `Got response with status ${e.response.status}: ${error}`
216
220
  : `Got response with unknown status: ${error}`);
217
221
  }
218
222
  } else {
219
223
  proxyErrorMsg = `Could not proxy command to the remote server. Original error: ${e.message}`;
220
224
  if (COMPACT_ERROR_PATTERNS.some((p) => p.test(e.message))) {
221
- log.info(e.message);
225
+ this.log.info(e.message);
222
226
  } else {
223
- log.info(e.stack);
227
+ this.log.info(e.stack);
224
228
  }
225
229
  }
226
230
  throw new errors.ProxyRequestError(proxyErrorMsg, e.response?.data, e.response?.status);
@@ -256,7 +260,7 @@ class JWProxy {
256
260
  if (!commandName) {
257
261
  return await this.proxy(url, method, body);
258
262
  }
259
- log.debug(`Matched '${url}' to command name '${commandName}'`);
263
+ this.log.debug(`Matched '${url}' to command name '${commandName}'`);
260
264
 
261
265
  return await this.protocolConverter.convertAndProxy(commandName, url, method, body);
262
266
  }
@@ -318,10 +322,10 @@ class JWProxy {
318
322
  const reqSessionId = this.getSessionIdFromUrl(req.originalUrl);
319
323
  if (_.has(resBodyObj, 'sessionId')) {
320
324
  if (reqSessionId) {
321
- log.info(`Replacing sessionId ${resBodyObj.sessionId} with ${reqSessionId}`);
325
+ this.log.info(`Replacing sessionId ${resBodyObj.sessionId} with ${reqSessionId}`);
322
326
  resBodyObj.sessionId = reqSessionId;
323
327
  } else if (this.sessionId) {
324
- log.info(`Replacing sessionId ${resBodyObj.sessionId} with ${this.sessionId}`);
328
+ this.log.info(`Replacing sessionId ${resBodyObj.sessionId} with ${this.sessionId}`);
325
329
  resBodyObj.sessionId = this.sessionId;
326
330
  }
327
331
  }