@testim/testim-cli 3.289.0 → 3.290.0-beta

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 (217) hide show
  1. package/cli.js +22390 -122
  2. package/cli.js.map +1 -0
  3. package/npm-shrinkwrap.json +8 -29129
  4. package/package.json +16 -10
  5. package/OverrideTestDataBuilder.js +0 -117
  6. package/agent/routers/cliJsCode/index.js +0 -13
  7. package/agent/routers/cliJsCode/router.js +0 -63
  8. package/agent/routers/cliJsCode/service.js +0 -705
  9. package/agent/routers/codim/router.js +0 -69
  10. package/agent/routers/codim/router.test.js +0 -60
  11. package/agent/routers/codim/service.js +0 -193
  12. package/agent/routers/general/index.js +0 -36
  13. package/agent/routers/hybrid/registerRoutes.js +0 -81
  14. package/agent/routers/index.js +0 -56
  15. package/agent/routers/playground/router.js +0 -77
  16. package/agent/routers/playground/service.js +0 -96
  17. package/agent/routers/standalone-browser/registerRoutes.js +0 -47
  18. package/agent/server.js +0 -150
  19. package/cdpTestRunner.js +0 -86
  20. package/chromiumInstaller.js +0 -91
  21. package/cli/isCiRun.js +0 -10
  22. package/cli/onExit.js +0 -65
  23. package/cli/writeStackTrace.js +0 -27
  24. package/cliAgentMode.js +0 -384
  25. package/codim/codim-cli.js +0 -91
  26. package/codim/codim-npm-package/index.ts +0 -427
  27. package/codim/codim-npm-package/package-lock.json +0 -14
  28. package/codim/codim-npm-package/package.json +0 -14
  29. package/codim/hybrid-utils.js +0 -28
  30. package/codim/measure-perf.js +0 -41
  31. package/codim/template.js/.idea/workspace.xml +0 -57
  32. package/codim/template.js/.vscode/launch.json +0 -53
  33. package/codim/template.ts/.idea/workspace.xml +0 -57
  34. package/codim/template.ts/.vscode/launch.json +0 -55
  35. package/commons/AbortError.js +0 -12
  36. package/commons/SeleniumPerfStats.js +0 -58
  37. package/commons/chrome-launcher.js +0 -15
  38. package/commons/chromedriverWrapper.js +0 -70
  39. package/commons/config.js +0 -39
  40. package/commons/constants.js +0 -67
  41. package/commons/detectDebugger.js +0 -19
  42. package/commons/featureAvailabilityService.js +0 -26
  43. package/commons/featureFlags.js +0 -132
  44. package/commons/getSessionPlayerRequire.js +0 -28
  45. package/commons/httpRequest.js +0 -261
  46. package/commons/httpRequestCounters.js +0 -98
  47. package/commons/httpRequestCounters.test.js +0 -38
  48. package/commons/initializeUserWithAuth.js +0 -55
  49. package/commons/lazyRequire.js +0 -105
  50. package/commons/logUtils.js +0 -15
  51. package/commons/logUtils.test.js +0 -21
  52. package/commons/logger.js +0 -178
  53. package/commons/mockNetworkRuleFileSchema.json +0 -140
  54. package/commons/npmWrapper.js +0 -174
  55. package/commons/npmWrapper.test.js +0 -374
  56. package/commons/performance-logger.js +0 -71
  57. package/commons/preloadTests.js +0 -29
  58. package/commons/prepareRunner.js +0 -85
  59. package/commons/prepareRunner.test.js +0 -144
  60. package/commons/prepareRunnerAndTestimStartUtils.js +0 -198
  61. package/commons/prepareRunnerAndTestimStartUtils.test.js +0 -73
  62. package/commons/requireWithFallback.js +0 -25
  63. package/commons/runnerFileCache.js +0 -204
  64. package/commons/socket/baseSocketServiceSocketIO.js +0 -197
  65. package/commons/socket/realDataService.js +0 -59
  66. package/commons/socket/realDataServiceSocketIO.js +0 -33
  67. package/commons/socket/remoteStepService.js +0 -55
  68. package/commons/socket/remoteStepServiceSocketIO.js +0 -61
  69. package/commons/socket/socketService.js +0 -175
  70. package/commons/socket/testResultService.js +0 -62
  71. package/commons/socket/testResultServiceSocketIO.js +0 -64
  72. package/commons/testimAnalytics.js +0 -40
  73. package/commons/testimCloudflare.js +0 -83
  74. package/commons/testimCloudflare.test.js +0 -185
  75. package/commons/testimCustomToken.js +0 -124
  76. package/commons/testimDesiredCapabilitiesBuilder.js +0 -647
  77. package/commons/testimNgrok.js +0 -90
  78. package/commons/testimNgrok.test.js +0 -140
  79. package/commons/testimServicesApi.js +0 -631
  80. package/commons/testimTunnel.js +0 -73
  81. package/commons/testimTunnel.test.js +0 -172
  82. package/commons/xhr2.js +0 -897
  83. package/coverage/SummaryToObjectReport.js +0 -19
  84. package/coverage/jsCoverage.js +0 -252
  85. package/credentialsManager.js +0 -142
  86. package/errors.js +0 -161
  87. package/executionQueue.js +0 -37
  88. package/fixLocalBuild.js +0 -24
  89. package/inputFileUtils.js +0 -103
  90. package/lib/coralogix-winston.transport.js +0 -99
  91. package/player/SeleniumProtocolError.js +0 -100
  92. package/player/WebDriverHttpRequest.js +0 -177
  93. package/player/WebdriverioWebDriverApi.js +0 -671
  94. package/player/appiumTestPlayer.js +0 -90
  95. package/player/chromeLauncherTestPlayer.js +0 -67
  96. package/player/constants.js +0 -332
  97. package/player/extensionTestPlayer.js +0 -32
  98. package/player/findElementStrategy.js +0 -154
  99. package/player/scripts/isElementDisplayed.js +0 -252
  100. package/player/seleniumTestPlayer.js +0 -140
  101. package/player/services/frameLocator.js +0 -170
  102. package/player/services/mobileFrameLocatorMock.js +0 -32
  103. package/player/services/playbackTimeoutCalculator.js +0 -175
  104. package/player/services/portSelector.js +0 -19
  105. package/player/services/tabService.js +0 -551
  106. package/player/services/tabServiceMock.js +0 -167
  107. package/player/services/windowCreationListener.js +0 -8
  108. package/player/stepActions/RefreshStepAction.js +0 -16
  109. package/player/stepActions/apiStepAction.js +0 -89
  110. package/player/stepActions/baseCliJsStepAction.js +0 -51
  111. package/player/stepActions/baseJsStepAction.js +0 -277
  112. package/player/stepActions/cliConditionStepAction.js +0 -11
  113. package/player/stepActions/cliJsStepAction.js +0 -11
  114. package/player/stepActions/dropFileStepAction.js +0 -34
  115. package/player/stepActions/evaluateExpressionStepAction.js +0 -52
  116. package/player/stepActions/extensionOnlyStepAction.js +0 -12
  117. package/player/stepActions/extractTextStepAction.js +0 -19
  118. package/player/stepActions/hoverStepAction.js +0 -55
  119. package/player/stepActions/inputFileStepAction.js +0 -199
  120. package/player/stepActions/jsCodeStepAction.js +0 -11
  121. package/player/stepActions/jsConditionStepAction.js +0 -11
  122. package/player/stepActions/locateStepAction.js +0 -159
  123. package/player/stepActions/mouseStepAction.js +0 -370
  124. package/player/stepActions/navigationStepAction.js +0 -29
  125. package/player/stepActions/nodePackageStepAction.js +0 -47
  126. package/player/stepActions/pixelValidationStepAction.js +0 -39
  127. package/player/stepActions/scripts/dispatchEvents.js +0 -282
  128. package/player/stepActions/scripts/doClick.js +0 -221
  129. package/player/stepActions/scripts/doDragPath.js +0 -225
  130. package/player/stepActions/scripts/doubleClick.js +0 -119
  131. package/player/stepActions/scripts/dropEvent.js +0 -63
  132. package/player/stepActions/scripts/focusElement.js +0 -46
  133. package/player/stepActions/scripts/html5dragAction.js +0 -56
  134. package/player/stepActions/scripts/html5dragActionV2.js +0 -312
  135. package/player/stepActions/scripts/runCode.js +0 -147
  136. package/player/stepActions/scripts/scroll.js +0 -90
  137. package/player/stepActions/scripts/selectOption.js +0 -51
  138. package/player/stepActions/scripts/setText.js +0 -415
  139. package/player/stepActions/scripts/wheel.js +0 -61
  140. package/player/stepActions/scrollStepAction.js +0 -96
  141. package/player/stepActions/selectOptionStepAction.js +0 -49
  142. package/player/stepActions/sfdcRecordedStepAction.js +0 -24
  143. package/player/stepActions/sfdcStepAction.js +0 -28
  144. package/player/stepActions/sleepStepAction.js +0 -12
  145. package/player/stepActions/specialKeyStepAction.js +0 -52
  146. package/player/stepActions/stepAction.js +0 -73
  147. package/player/stepActions/stepActionRegistrar.js +0 -111
  148. package/player/stepActions/submitStepAction.js +0 -12
  149. package/player/stepActions/tdkHybridStepAction.js +0 -18
  150. package/player/stepActions/textStepAction.js +0 -110
  151. package/player/stepActions/textValidationStepAction.js +0 -64
  152. package/player/stepActions/wheelStepAction.js +0 -41
  153. package/player/utils/cookieUtils.js +0 -39
  154. package/player/utils/eyeSdkService.js +0 -250
  155. package/player/utils/imageCaptureUtils.js +0 -267
  156. package/player/utils/screenshotUtils.js +0 -68
  157. package/player/utils/stepActionUtils.js +0 -90
  158. package/player/utils/windowUtils.js +0 -195
  159. package/player/webDriverUtils.js +0 -40
  160. package/player/webDriverUtils.test.js +0 -116
  161. package/player/webdriver.js +0 -976
  162. package/polyfills/Array.prototype.at.js +0 -13
  163. package/polyfills/index.js +0 -13
  164. package/processHandler.js +0 -79
  165. package/processHandler.test.js +0 -55
  166. package/reports/chromeReporter.js +0 -17
  167. package/reports/consoleReporter.js +0 -190
  168. package/reports/debugReporter.js +0 -82
  169. package/reports/jsonReporter.js +0 -55
  170. package/reports/junitReporter.js +0 -183
  171. package/reports/reporter.js +0 -166
  172. package/reports/reporterUtils.js +0 -54
  173. package/reports/teamCityReporter.js +0 -73
  174. package/runOptions.d.ts +0 -305
  175. package/runOptions.js +0 -1288
  176. package/runOptionsAgentFlow.js +0 -87
  177. package/runOptionsUtils.js +0 -60
  178. package/runner.js +0 -355
  179. package/runners/ParallelWorkerManager.js +0 -284
  180. package/runners/TestPlanRunner.js +0 -419
  181. package/runners/buildCodeTests.js +0 -159
  182. package/runners/runnerUtils.js +0 -81
  183. package/services/analyticsService.js +0 -96
  184. package/services/branchService.js +0 -29
  185. package/services/gridService.js +0 -357
  186. package/services/gridService.test.js +0 -357
  187. package/services/labFeaturesService.js +0 -64
  188. package/services/lambdatestService.js +0 -227
  189. package/services/lambdatestService.test.js +0 -353
  190. package/services/localRCASaver.js +0 -124
  191. package/stepPlayers/cliJsStepPlayback.js +0 -40
  192. package/stepPlayers/hybridStepPlayback.js +0 -140
  193. package/stepPlayers/nodePackageStepPlayback.js +0 -28
  194. package/stepPlayers/playwrightHybridStepPlayback.js +0 -61
  195. package/stepPlayers/puppeteerHybridStepPlayback.js +0 -76
  196. package/stepPlayers/remoteStepPlayback.js +0 -80
  197. package/stepPlayers/seleniumHybridStepPlayback.js +0 -84
  198. package/stepPlayers/tdkHybridStepPlayback.js +0 -112
  199. package/testRunHandler.js +0 -603
  200. package/testRunStatus.js +0 -567
  201. package/testimNpmDriver.js +0 -52
  202. package/utils/argsUtils.js +0 -91
  203. package/utils/argsUtils.test.js +0 -32
  204. package/utils/fsUtils.js +0 -174
  205. package/utils/index.js +0 -197
  206. package/utils/promiseUtils.js +0 -85
  207. package/utils/stringUtils.js +0 -98
  208. package/utils/stringUtils.test.js +0 -22
  209. package/utils/timeUtils.js +0 -25
  210. package/utils/utils.test.js +0 -27
  211. package/workers/BaseWorker.js +0 -498
  212. package/workers/BaseWorker.test.js +0 -186
  213. package/workers/WorkerAppium.js +0 -180
  214. package/workers/WorkerExtension.js +0 -192
  215. package/workers/WorkerExtensionSingleBrowser.js +0 -77
  216. package/workers/WorkerSelenium.js +0 -253
  217. package/workers/workerUtils.js +0 -20
@@ -1,976 +0,0 @@
1
- /* eslint-disable arrow-body-style, no-shadow, @typescript-eslint/prefer-optional-chain, comma-spacing, no-empty, padded-blocks, semi, indent, unicorn/no-useless-promise-resolve-reject, default-param-last, comma-dangle, semi-style, consistent-return, radix, prefer-template, prefer-const, object-shorthand, no-trailing-spaces, operator-linebreak, no-else-return, unicorn/prefer-includes, prefer-arrow-callback, max-len, no-var */
2
-
3
- 'use strict';
4
-
5
- const _ = require('lodash');
6
- const logger = require('../commons/logger').getLogger('webdriver');
7
- const parser = require('ua-parser-js');
8
- const desiredCapabilitiesBuilder = require('../commons/testimDesiredCapabilitiesBuilder');
9
- const { SeleniumError, SeleniumCrashError } = require('../errors');
10
- const utils = require('../utils');
11
- const WebDriverApi = require('./WebdriverioWebDriverApi');
12
- const doubleClick = require('./stepActions/scripts/doubleClick');
13
- const dispatchFocus = require('./stepActions/scripts/focusElement');
14
- const { isOldProtocol } = require('./webDriverUtils');
15
- const featureFlags = require('../commons/featureFlags');
16
- const { W3C_ELEMENT_ID } = require('./constants');
17
-
18
- const [LEFT, RIGHT] = [0, 2];
19
- const { extractElementId, getCdpAddressForHost } = utils;
20
- const perf = require('../commons/performance-logger');
21
- const { SeleniumPerfStats, SELENIUM_PERF_MARKS } = require('../commons/SeleniumPerfStats');
22
-
23
- const codeSnippets = () => {
24
- const sessionPlayer = require('../commons/getSessionPlayerRequire').getSessionPlayer();
25
- return sessionPlayer.codeSnippets;
26
- };
27
- const locatorBuilderUtils = () => {
28
- const sessionPlayer = require('../commons/getSessionPlayerRequire').getSessionPlayer();
29
- return sessionPlayer.locatorBuilderUtils;
30
- };
31
- const playerUtils = () => {
32
- const sessionPlayer = require('../commons/getSessionPlayerRequire').getSessionPlayer();
33
- return sessionPlayer.utils;
34
- };
35
-
36
- async function getCdpAddress(initResult) {
37
- try {
38
- const debuggerHost = initResult?.value?.['goog:chromeOptions']?.debuggerAddress;
39
- if (!debuggerHost) {
40
- return undefined;
41
- }
42
- return await getCdpAddressForHost(debuggerHost);
43
- } catch (e) {
44
- logger.info('Error getting cdpAddress', e);
45
- return undefined;
46
- }
47
- }
48
- class WebDriver extends WebDriverApi {
49
- constructor() {
50
- super();
51
- this.started = false;
52
- this.keepAliveTimer = null;
53
- this.unsupportedActions = {};
54
- this._isAlive = false;
55
- this._keepAliveRequests = [];
56
- this.cdpUrl = undefined;
57
- this.browserClosedCallbacks = [];
58
- this.browserClosedFailedKeepAlives = 0;
59
- this.ignoreHiddenTagsText = false;
60
- }
61
-
62
- registerToClosedBrowser(callback) {
63
- this.browserClosedCallbacks.push(callback);
64
- }
65
-
66
- unregisterToClosedBrowser(callback) {
67
- this.browserClosedCallbacks = this.browserClosedCallbacks.filter(cb => cb !== callback);
68
- }
69
-
70
- // eslint-disable-next-line max-len, default-param-last
71
- async init(browserOptions, testName, testRunConfig, gridInfo, customExtensionLocalLocation, executionId, testResultId, seleniumPerfStats = new SeleniumPerfStats(), fastInit = false, lambdatestService) {
72
- this.browserClosedFailedKeepAlives = 0;
73
- this.ignoreHiddenTagsText = browserOptions?.company?.activePlan?.premiumFeatures?.ignoreHiddenTagsText;
74
- this.browserClosedCallbacks = [];
75
- // eslint-disable-next-line max-len
76
- const capabilities = desiredCapabilitiesBuilder.buildSeleniumOptions(browserOptions, testName, testRunConfig, gridInfo, customExtensionLocalLocation, executionId, testResultId, lambdatestService);
77
- if (capabilities.desiredCapabilities) {
78
- delete capabilities.desiredCapabilities.marionette;
79
- }
80
- if (capabilities.capabilities) {
81
- delete capabilities.capabilities.alwaysMatch.marionette;
82
- }
83
- this.initUnsupportedActions(lambdatestService?.isLambdatestRun());
84
- this.browserAndOS = null;
85
- this.seleniumPerfStats = seleniumPerfStats;
86
- const driverDelay = fastInit ? 0 : 1500;
87
- const focus = fastInit ? (() => { }) : () => this.executeJS('window.focus()');
88
- try {
89
- perf.log('before initClient in webdriver.js init');
90
- const initResult = await this.initClient(capabilities, testName, testResultId);
91
- perf.log('after initResult before getCdpAddress in init');
92
- this.cdpUrl = await getCdpAddress(initResult);
93
- perf.log('after getCdpAddress in webdriver.js init');
94
- logger.info(`init new session testName: ${testName}`, { sessionId: this.getSessionId(), testResultId });
95
- await utils.delay(driverDelay);
96
- await focus();
97
- perf.log('after focus and delay in webdriver.js init');
98
- } catch (err) {
99
- logger.error('failed to init webdriver', { err });
100
- if (err.seleniumStack) {
101
- const newError = new SeleniumError(err.seleniumStack);
102
- const isFreeCompany = browserOptions?.company?.activePlan?.plan === 'free';
103
- if (newError.message.includes('timed out waiting for a node') && isFreeCompany) {
104
- throw new Error('Our free grids are in full capacity, please try again or upgrade to our Professional plan');
105
- }
106
- throw newError;
107
- }
108
- throw new Error('failed to init client driver');
109
- }
110
- }
111
-
112
- initUnsupportedActions(isLambdatestRun) {
113
- if (isLambdatestRun) {
114
- this.unsupportedActions = {
115
- ...this.unsupportedActions,
116
- move: true,
117
- };
118
- }
119
- }
120
-
121
- isAlive() {
122
- return this._isAlive;
123
- }
124
-
125
- maxKeepAliveGap() {
126
- const slidingPairsWindow = (arr) => _.zip(_.dropRight(arr, 1), _.drop(arr, 1));
127
- const startTimeArray = this._keepAliveRequests.map(({ start }) => start).filter(Boolean);
128
- const timeGaps = slidingPairsWindow(startTimeArray).map(([a, b]) => b - a);
129
- return Math.max(...timeGaps);
130
- }
131
-
132
- isClosedBrowserError(err) {
133
- if (!err || !err.seleniumStack || !err.message) {
134
- return false;
135
- }
136
- return ((err.seleniumStack.type === 'UnknownError') &&
137
- (err.message.includes('CLIENT_STOPPED_SESSION') || err.message.includes('BROWSER_TIMEOUT') || err.message.includes('was terminated due to TIMEOUT'))) ||
138
- (err.seleniumStack.type === 'NoSuchWindow' && err.message.includes('window was already closed')) ||
139
- (err.seleniumStack.type === 'SelectorTimeoutError' && err.message.includes('chrome not reachable'));
140
- }
141
-
142
- start() {
143
- if (this.started) {
144
- return;
145
- }
146
- this.started = true;
147
- const that = this;
148
- const keepAlive = function () {
149
- function createKeepAliveRequestData(id) {
150
- that._keepAliveRequests.push({ start: Date.now(), id });
151
- }
152
- function updateKeepAliveRequestData(field, id) {
153
- (that._keepAliveRequests.find(item => item.id === id) || {})[field] = Date.now();
154
- }
155
-
156
- function checkKeepAliveScript() {
157
- return window.getTestimStatus && window.getTestimStatus();
158
- }
159
-
160
- if (that.queue.getQueueLength() > 0) {
161
- return Promise.resolve();
162
- }
163
-
164
- const requestId = utils.guid();
165
- createKeepAliveRequestData(requestId);
166
- return that.executeJS(checkKeepAliveScript)
167
- .then(() => {
168
- that._isAlive = true;
169
- updateKeepAliveRequestData('end', requestId);
170
- that.browserClosedFailedKeepAlives = 0;
171
- })
172
- .catch(err => {
173
- updateKeepAliveRequestData('error', requestId);
174
- if (err.seleniumStack && err.seleniumStack.type === 'UnexpectedAlertOpen') {
175
- that.browserClosedFailedKeepAlives = 0;
176
- logger.warn('close unexpected alert open');
177
- return that.alertAccept().catch(innerErr => logger.warn('failed to click on alert', { err: innerErr }));
178
- }
179
- logger.warn('err while getting testim status', { err });
180
- that._isAlive = false;
181
- if (that.isClosedBrowserError(err)) {
182
- that.browserClosedFailedKeepAlives++;
183
- const CLOSED_BROWSER_THRESHOLD_COUNT = 3;
184
- if (that.browserClosedFailedKeepAlives >= CLOSED_BROWSER_THRESHOLD_COUNT) {
185
- that.browserClosedCallbacks.forEach(cb => {
186
- try {
187
- cb(err);
188
- } catch { /* ignore */ }
189
- });
190
- }
191
- } else {
192
- that.browserClosedFailedKeepAlives = 0;
193
- }
194
- return undefined;
195
- });
196
- };
197
-
198
- this.keepAliveTimer = setInterval(keepAlive, 10000);
199
- }
200
-
201
- switchToLocatedFrame(locatedElement) {
202
- return this.getElement(locatedElement)
203
- .then(async el => {
204
- const elementId = extractElementId(el.value);
205
- await this.switchToFrame({ ELEMENT: elementId, [W3C_ELEMENT_ID]: elementId });
206
- return el;
207
- });
208
- }
209
-
210
- switchToFrame(el) {
211
- return this.frame(el);
212
- }
213
-
214
- switchToTopFrame() {
215
- return this.frame().catch(err => {
216
- if (err.message?.includes('ECONNREFUSED')) {
217
- throw new SeleniumCrashError();
218
- }
219
- throw err;
220
- });
221
- }
222
-
223
- /**
224
- * @returns {Promise<{ value: HTMLElement | { [W3C_ELEMENT_ID]: string } | { ELEMENT: string } }>}
225
- */
226
- getElement(locatedElement) {
227
- const perfId = this.seleniumPerfStats.markStart(SELENIUM_PERF_MARKS.GET_ELEMENT);
228
- if (typeof locatedElement === 'string' || typeof locatedElement === 'number') { // support testimId in the meanwhile for backwards compatibility
229
- return this.getElementBySelector(`[testim_dom_element_id='${locatedElement}']`)
230
- .finally(() => this.seleniumPerfStats.markEnd(perfId, SELENIUM_PERF_MARKS.GET_ELEMENT));
231
- }
232
- const getElementAtAut = (locatedElement && locatedElement.shadowPath && locatedElement.shadowPath.length) ||
233
- (featureFlags.flags.runGetElementCodeInAut.isEnabled() && this.isSafari());
234
-
235
- if (getElementAtAut) {
236
- return this.execute(`
237
- var fn = ${codeSnippets().getLocatedElementCode};
238
- return fn.apply(null, arguments);
239
- `, locatedElement
240
- ).finally(() => this.seleniumPerfStats.markEnd(perfId, SELENIUM_PERF_MARKS.GET_ELEMENT));
241
- }
242
-
243
- return this.getElementBySelector(`[testim_dom_element_id='${locatedElement && locatedElement.testimId}']`)
244
- .finally(() => this.seleniumPerfStats.markEnd(perfId, SELENIUM_PERF_MARKS.GET_ELEMENT));
245
- }
246
-
247
- executeJS(fn, args) {
248
- return this.execute(fn, args);
249
- }
250
-
251
- executeJSWithArray(fn, args) {
252
- args.unshift(fn);
253
- return this.execute.apply(this, args);
254
- }
255
-
256
- executeCodeAsync(fn, timeout, args) {
257
- return this.timeouts('script', timeout)
258
- .then(() => this.executeAsync(fn, args));
259
- }
260
-
261
- /** @type {import('clickim/src/background/stepActions/stepActionUtils').StepActionUtils['markDynamicParent']} */
262
- async markDynamicParent(target, dynamicParentId, frameHandler) {
263
- function setDynamicParentAttribute(data) {
264
- var attributeName = data.attributeName;
265
- var attributeValue = data.attributeValue;
266
- var element = getLocatedElement(data.locatedElement);
267
- if (!element) {
268
- throw new Error('could not find dynamic parent');
269
- }
270
- element.setAttribute(attributeName, attributeValue);
271
- }
272
-
273
- return this.executeJS(`
274
- var getLocatedElement = ${codeSnippets().getLocatedElementCode};
275
- var setDynamicParentAttribute = ${setDynamicParentAttribute.toString()};
276
- return setDynamicParentAttribute.apply(null, arguments)
277
- `, {
278
- attributeName: locatorBuilderUtils().DYNAMIC_PARENT_FIELD_NAME,
279
- attributeValue: dynamicParentId,
280
- locatedElement: target.locatedElement
281
- });
282
- }
283
-
284
- /** @return {Promise<{ value: { top: number; left: number } | null }>} */
285
- getLocatedElementRectWithPadding(locatedElement) {
286
- // this is here to conform with clickim's logic in frame offset calculations
287
- function getLocationCode(locatedElement) {
288
- var element = getLocatedElement(locatedElement);
289
- if (!element) {
290
- return null;
291
- }
292
- var paddingTop = parseInt(window.getComputedStyle(element).paddingTop.replace('px', ''), 10) || 0;
293
- var paddingLeft = parseInt(window.getComputedStyle(element).paddingLeft.replace('px', ''), 10) || 0;
294
- var rect = element.getBoundingClientRect();
295
- return { top: Math.round(rect.top + paddingTop), left: Math.round(rect.left + paddingLeft) };
296
- }
297
-
298
- return this.executeJS(`
299
- var getLocatedElement = ${codeSnippets().getLocatedElementCode};
300
- var getLocation = ${getLocationCode.toString()};
301
- return getLocation.apply(null, arguments)
302
- `, locatedElement);
303
- }
304
-
305
- getElementLocationWithPadding(locatedElement) {
306
- return this.getLocatedElementRectWithPadding(locatedElement);
307
- }
308
-
309
- /** @returns {Promise<{ value: null | Record<'bottom' | 'height' | 'x' | 'right' | 'y' | 'width', number> }>} */
310
- getLocatedElementRect(locatedElement) {
311
- function getLocationCode(locatedElement) {
312
- var element = getLocatedElement(locatedElement);
313
- if (!element) {
314
- return null;
315
- }
316
- var rect = element.getBoundingClientRect();
317
- return {
318
- bottom: Math.round(rect.bottom),
319
- height: Math.round(rect.height),
320
- x: Math.round(rect.left),
321
- right: Math.round(rect.right),
322
- y: Math.round(rect.top),
323
- width: Math.round(rect.width),
324
- };
325
- }
326
-
327
- return this.executeJS(`
328
- var getLocatedElement = ${codeSnippets().getLocatedElementCode};
329
- var getLocation = ${getLocationCode.toString()};
330
- return getLocation.apply(null, arguments)
331
- `, locatedElement);
332
- }
333
-
334
- getElementLocation(target) {
335
- return this.getLocatedElementRect(target.locatedElement);
336
- }
337
-
338
- getTargetText(target) {
339
- return this.getElementTextJS(target.locatedElement);
340
- }
341
-
342
- getElementTextJS(locatedElement) {
343
- function extractTextCode(locatedElement, ignoreHiddenTagsText) {
344
- // copy of utils.getElementTextContent to run inside content script
345
- // sadly .children doesn't work for SVG elements in IE11
346
- function clearTitleTags(node) {
347
- if (!node.childNodes || node.childNodes.length === 0) {
348
- return node;
349
- }
350
-
351
- var children = Array.apply(null, node.childNodes).filter(function (x) { return x.nodeType === Node.ELEMENT_NODE; });
352
- // eslint-disable-next-line prefer-arrow-callback
353
- children.forEach(function (child) {
354
- if (typeof child.tagName === 'string' && child.tagName.toLowerCase() === 'title') {
355
- node.removeChild(child);
356
- } else {
357
- clearTitleTags(child);
358
- }
359
- });
360
- return node;
361
- }
362
-
363
- function isTextElement(element) {
364
- var tagName = element.tagName;
365
- return (tagName === 'INPUT' || tagName === 'TEXTAREA');
366
- }
367
-
368
- function getFixedTextContent(element) {
369
- try { // fix for salesforce's custom-elements
370
- if (element.shadowRoot && Object.getOwnPropertyDescriptor(element.ownerDocument.defaultView.Node.prototype,'textContent').get.toString().indexOf('[native code]') === -1) {
371
- return element.shadowRoot.textContent.replace(/(\r\n|\n|\r)/gm, '');
372
- }
373
- // eslint-disable-next-line no-empty
374
- } catch (err) { }
375
- // eslint-disable-next-line prefer-arrow-callback
376
- if (ignoreHiddenTagsText && Array.prototype.some.call(element.children, function (elem) { return elem.hidden; })) {
377
- var dupElement = element.cloneNode(true);
378
- // eslint-disable-next-line prefer-arrow-callback
379
- var hiddenChildren = Array.prototype.filter.call(dupElement.children, function (elem) { return elem.hidden; });
380
- // eslint-disable-next-line prefer-arrow-callback
381
- hiddenChildren.forEach(function (child) {
382
- dupElement.removeChild(child);
383
- });
384
- return dupElement.textContent.replace(/(\r\n|\n|\r)/gm, '');
385
- }
386
- return element.textContent.replace(/(\r\n|\n|\r)/gm, '');
387
- }
388
-
389
- function getElementTextContent(element) {
390
- if (isTextElement(element)) {
391
- return element.value;
392
- } else if (element instanceof SVGElement) {
393
- var copyElement = element.cloneNode(true);
394
- return clearTitleTags(copyElement).textContent.replace(/(\r\n|\n|\r)/gm, '');
395
- } else {
396
- return getFixedTextContent(element);
397
- }
398
- }
399
-
400
- var element = getLocatedElement(locatedElement);
401
- return element ? getElementTextContent(element) : '';
402
- }
403
-
404
- return this.executeJS(`
405
- var getLocatedElement = ${codeSnippets().getLocatedElementCode};
406
- var extractText = ${extractTextCode.toString()};
407
- return extractText.apply(null, arguments)
408
- `, locatedElement, this.ignoreHiddenTagsText)
409
- .then(result => result.value);
410
- }
411
-
412
- getHTML(locateStep) {
413
- const getHTMLCode = codeSnippets().getHtmlCode(null, locateStep);
414
- const perfId = this.seleniumPerfStats.markStart(SELENIUM_PERF_MARKS.GET_HTML);
415
- return this.executeJS(getHTMLCode)
416
- .then(result => {
417
- this.seleniumPerfStats.markEnd(perfId, SELENIUM_PERF_MARKS.GET_HTML);
418
- return result.value;
419
- })
420
- .catch(err => {
421
- this.seleniumPerfStats.markEnd(perfId, SELENIUM_PERF_MARKS.GET_HTML);
422
- const testimInternalError = Object.assign(new Error(), { success: false, reason: err.toString(), errorType: 'internal-error' });
423
- if (!this.client.requestHandler.sessionID) {
424
- // we got here after the driver has been disposed of. It's impossible to run JavaScript on the page.
425
- testimInternalError.extraInfo = 'Inside getHtml catch and trying to check if in quirks mode - but the session has already terminated';
426
- throw testimInternalError;
427
- }
428
- throw testimInternalError;
429
- });
430
- }
431
-
432
- maximizeWithoutValidation() {
433
- return this.windowHandleMaximize();
434
- }
435
-
436
- setViewportSizeNEW(size, type) {
437
- const MAX_TRIES = 5;
438
-
439
- const getViewportSizeScript = function () {
440
- return {
441
- screenWidth: Math.floor(window.innerWidth || 0),
442
- screenHeight: Math.floor(window.innerHeight || 0)
443
- };
444
- };
445
-
446
- /**
447
- * to set viewport size properly we need to execute the process multiple times
448
- * since the difference between the inner and outer size changes when browser
449
- * switch between fullscreen modes or visibility of scrollbar
450
- */
451
- const _setViewportSize = (size, tryNo = 1) => {
452
- /**
453
- * get window size
454
- */
455
- return this.windowHandleSize()
456
- .then((windowHandleSize) => {
457
- /**
458
- * get viewport size
459
- */
460
- return this.execute(getViewportSizeScript)
461
- .then(viewportSize => {
462
- const widthDiff = windowHandleSize.value.width - viewportSize.value.screenWidth;
463
- const heightDiff = windowHandleSize.value.height - viewportSize.value.screenHeight;
464
- /**
465
- * change window size with indent
466
- */
467
- return this.windowHandleSize({
468
- width: size.width + widthDiff,
469
- height: size.height + heightDiff
470
- });
471
- })
472
- .then(() => this.execute(getViewportSizeScript))
473
- .then(res => {
474
- /**
475
- * if viewport size not equals desired size, execute process again
476
- */
477
- if (tryNo < MAX_TRIES && (res.value.screenWidth !== size.width || res.value.screenHeight !== size.height)) {
478
- return _setViewportSize(size, tryNo + 1);
479
- }
480
- });
481
- });
482
- };
483
-
484
- /**
485
- * parameter check
486
- */
487
- if (typeof size !== 'object' ||
488
- typeof size.width !== 'number' ||
489
- typeof size.height !== 'number' ||
490
- (typeof type !== 'undefined' && typeof type !== 'boolean')) {
491
- throw new Error('number or type of arguments don\'t agree with setViewportSize command');
492
- }
493
-
494
- const shouldIndent = (typeof type === 'undefined') ? true : type;
495
-
496
- return shouldIndent ? _setViewportSize(size) : this.windowHandleSize(size);
497
- }
498
-
499
- setViewportSize(width, height) {
500
- var type = true; //set to false to change window size, true (default) to change viewport size
501
- return this.setViewportSizeNEW({
502
- width: width,
503
- height: height
504
- }, type);
505
- }
506
-
507
- getBrowserMajorVersion(parse) {
508
- try {
509
- return parseInt(parse.browser.major, 10);
510
- } catch (err) {
511
- logger.error('failed to get browser version', { err: err });
512
- return 0;
513
- }
514
- }
515
-
516
- getBrowserAndOS() {
517
- function getBrowserName(ua, browserDetails) {
518
- var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
519
- if (/trident/i.test(M[1])) {
520
- return 'Internet Explorer ' + browserDetails.major;
521
- }
522
- if (M[1] === 'Chrome' && ua.match(/\bOPR\/(\d+)/) !== null) {
523
- return 'opera';
524
- }
525
- if (M[1] === 'Chrome' && ua.match(/\bEdge|Edg\/(\d+)/) !== null) {
526
- return 'edge';
527
- }
528
- M = M[2] ? [M[1], M[2]] : [ua.appName, ua.appVersion, '-?'];
529
- var tem = ua.match(/version\/(\d+)/i);
530
- if (tem !== null) {
531
- M.splice(1, 1, tem[1]);
532
- }
533
- return M[0].toLowerCase();
534
- }
535
-
536
- if (this.browserAndOS) {
537
- return Promise.resolve(this.browserAndOS);
538
- }
539
-
540
- // eslint-disable-next-line prefer-arrow-callback
541
- return this.executeJS(function () {
542
- if (typeof window === 'undefined' || !window.navigator || !window.navigator.userAgent) {
543
- return 'unknown';
544
- }
545
- return window.navigator.userAgent;
546
- }).then(userAgent => {
547
- const rawUserAgent = userAgent.value;
548
- const parse = parser(rawUserAgent);
549
- const osDetails = parse.os;
550
- this.browserAndOS = {
551
- os: osDetails.name + ' ' + osDetails.version,
552
- browserMajor: this.getBrowserMajorVersion(parse),
553
- browser: getBrowserName(userAgent.value, parse.browser),
554
- userAgent: rawUserAgent,
555
- browserVersion: parse.browser.version
556
- };
557
- return this.browserAndOS;
558
- });
559
- }
560
-
561
- getUserAgentInfo() {
562
- return this.executeJS(`return ${codeSnippets().getUserAgentInfo()}`)
563
- .then(result => result.value);
564
- }
565
-
566
- setValue(element, value) {
567
- return super.setValue(element, value);
568
- }
569
-
570
- getRelativeMoveActions(offsets, element) {
571
- const { rect, clickOffset } = offsets;
572
- const inViewCenter = this.inViewCenter(rect);
573
- const left = Math.floor(clickOffset.x - inViewCenter.x);
574
- const top = Math.floor(clickOffset.y - inViewCenter.y);
575
-
576
- if (!playerUtils().isWithinBounds(-inViewCenter.x, inViewCenter.x, left) ||
577
- !playerUtils().isWithinBounds(-inViewCenter.y, inViewCenter.y, top)) {
578
- // [NOTE] the code is not supposed to get here! - using center (0,0) instead of step offsets.
579
- // this is a fallback so the action will take place even if for some reason calculation went out of element..
580
- logger.warn('using center as fallback for offset');
581
- return this.getMoveActions(0, 0, element);
582
- }
583
- return this.getMoveActions(left, top, element);
584
- }
585
-
586
- computeAbsoluteMovement(offsets) {
587
- const { frameOffset, rect, clickOffset } = offsets;
588
- const fallbackLeft = rect.left + clickOffset.x + frameOffset.x;
589
- const fallbackTop = rect.top + clickOffset.y + frameOffset.y;
590
- return { x: fallbackLeft, y: fallbackTop };
591
- }
592
-
593
- actWithActionsAPI(offsets, button, element, actions) {
594
- const moveActions = this.getRelativeMoveActions(offsets, element);
595
- const clickActions = this.getClickActions(actions, button);
596
- return this.actions([{
597
- type: 'pointer',
598
- id: 'mouse',
599
- parameters: { pointerType: 'mouse' },
600
- actions: moveActions.concat(clickActions),
601
- }]).catch(err => {
602
- logger.error('tried to use element origin but failed because of visibility, trying absolute', err);
603
- const { x, y } = this.computeAbsoluteMovement(offsets);
604
- const moveActions = this.getMoveActions(x, y);
605
- return this.actions([{
606
- type: 'pointer',
607
- id: 'mouse',
608
- parameters: { pointerType: 'mouse' },
609
- actions: moveActions.concat(clickActions),
610
- }]);
611
- });
612
- }
613
-
614
- doubleClickWithActionsAPI(element, offsets) {
615
- return this.actWithActionsAPI(offsets, LEFT, element, ['pointerDown', 'pointerUp', 'pointerDown', 'pointerUp']);
616
- }
617
-
618
- doubleClickWithJS(eventData) {
619
- return this.executeCodeAsync(`
620
- var getLocatedElement = ${codeSnippets().getLocatedElementCode};
621
- var dispatchFocus = ${dispatchFocus.toString()};
622
- var doubleClick = ${doubleClick.toString()};
623
- var eventData = arguments[0];
624
- var done = arguments[1];
625
- return doubleClick.call(null, eventData, done);
626
- `, eventData.timeout, eventData);
627
- }
628
-
629
- // eslint-disable-next-line default-param-last
630
- getClickActions(types = [], button) {
631
- return types.map(type => ({ type: type, button }));
632
- }
633
- // eslint-disable-next-line default-param-last
634
- getClickActionList(types = [], button) {
635
- return [{
636
- type: 'pointer',
637
- id: 'mouse',
638
- actions: this.getClickActions(types, button),
639
- }];
640
- }
641
-
642
- leftClickWithActionsAPI(element, offsets) {
643
- return this.actWithActionsAPI(offsets, LEFT, element, ['pointerDown', 'pointerUp']);
644
- }
645
-
646
- rightClickWithActionsAPI(element, offsets) {
647
- return this.actWithActionsAPI(offsets, RIGHT, element, ['pointerDown', 'pointerUp']);
648
- }
649
-
650
- rightClick(element, offsets) {
651
- if (this.unsupportedActions.move) {
652
- return this.rightClickWithActionsAPI(element, offsets);
653
- }
654
- return super.rightClick(element)
655
- .catch(err => {
656
- if (isOldProtocol(err)) {
657
- this.unsupportedActions.move = true;
658
- return this.rightClickWithActionsAPI(element, offsets);
659
- }
660
- throw err;
661
- });
662
- }
663
-
664
- leftClick(element, offsets) {
665
- if (this.unsupportedActions.move) {
666
- return this.leftClickWithActionsAPI(element, offsets);
667
- }
668
- return super.leftClick(element)
669
- .catch(err => {
670
- if (isOldProtocol(err)) {
671
- this.unsupportedActions.move = true;
672
- return this.leftClickWithActionsAPI(element, offsets);
673
- }
674
- throw err;
675
- });
676
- }
677
-
678
- dragAndDropOldAPI(sourceSeleniumElement, destinationSeleniumElement) {
679
- return this.moveTo(extractElementId(sourceSeleniumElement))
680
- .then(() => this.buttonDown())
681
- .then(() => this.moveTo(extractElementId(destinationSeleniumElement)))
682
- .then(() => this.buttonUp());
683
- }
684
-
685
- calculateElementMiddlePoint(locatedElement, offset = { top: 0, left: 0 }) {
686
- return this.getLocatedElementRect(locatedElement).then(response => {
687
- if (!response || !response.value) {
688
- logger.warn(`could not find element for locatedElement ${locatedElement}`);
689
- throw new Error('could not calculate rect');
690
- }
691
- const { x, y, width, height } = response.value;
692
- return {
693
- x: offset.left + x + (width / 2),
694
- y: offset.top + y + (height / 2),
695
- };
696
- });
697
- }
698
-
699
- hover(seleniumElement, offsets) {
700
- // this will attempt to use the old api with moveTOObject (using the selector)
701
- // if the old api is unsupported, it will move absolutePoint, or calc the point using the seleniumElement and offset
702
- if (this.unsupportedActions.move) {
703
- return this.moveToElementWithActionsAPI(seleniumElement, offsets);
704
- }
705
-
706
- const { rect, clickOffset } = offsets;
707
- const center = this.inViewCenter(rect);
708
- // moveto element (actions and legacy) is always vs. the center of an element, so the offset needs to get fixed.
709
- const xOffset = Math.floor(clickOffset.x - center.x);
710
- const yOffset = Math.floor(clickOffset.y - center.y);
711
-
712
- return this.moveTo(extractElementId(seleniumElement), xOffset, yOffset)
713
- .catch(err => {
714
- if (isOldProtocol(err)) {
715
- this.unsupportedActions.move = true;
716
- return this.moveToElementWithActionsAPI(seleniumElement, offsets);
717
- }
718
-
719
- throw err;
720
- });
721
- }
722
-
723
- getMoveActions(x = 1, y = 1, origin = 'viewport', duration = 0) {
724
- // force x != 0 ,y != 0 because of Safari issues
725
- return [{ type: 'pointerMove', duration, x: Math.floor(x) || 1, y: Math.floor(y) || 1, origin }];
726
- }
727
-
728
- moveWithActionsAPI(point) {
729
- const actions = this.getMoveActions(point.x, point.y);
730
- return this.actions([{
731
- type: 'pointer',
732
- id: 'mouse',
733
- actions,
734
- }]);
735
- }
736
-
737
- moveToElementWithActionsAPI(seleniumElement, offsets) {
738
- return this.actions([{
739
- type: 'pointer',
740
- id: 'mouse',
741
- actions: this.getRelativeMoveActions(offsets, seleniumElement),
742
- }]).catch(err => {
743
- logger.error('tried to use element origin but failed because of visibility, trying location', err);
744
- const point = this.computeAbsoluteMovement(offsets);
745
- return this.moveWithActionsAPI(point);
746
- });
747
- }
748
-
749
- getDragCoordinates(events) {
750
- const mouseEvents = events.filter(e => e.event === 'mousemove' || e.event === 'pointermove');
751
-
752
- const first = _.first(mouseEvents).pointerPosition;
753
- const last = _.last(mouseEvents).pointerPosition;
754
-
755
- return {
756
- xDiff: last.screenX - first.screenX,
757
- yDiff: last.screenY - first.screenY,
758
- };
759
- }
760
-
761
- dragWithMoveTo(seleniumElement, xDiff, yDiff, xOffset, yOffset) {
762
- return this.moveTo(extractElementId(seleniumElement), xOffset, yOffset)
763
- .then(() => this.buttonDown())
764
- .then(() => this.moveTo(extractElementId(seleniumElement), xDiff, yDiff))
765
- .then(() => this.buttonUp());
766
- }
767
-
768
- dragWithActionsAPI(seleniumElement, xDiff, yDiff, xOffset, yOffset) {
769
- const goToDrag = this.getMoveActions(xOffset, yOffset, seleniumElement, 1);
770
- const startDrag = this.getClickActions(['pointerDown'], LEFT);
771
- const doDrag = this.getMoveActions(xDiff, yDiff, 'pointer', 1);
772
- const endDrag = this.getClickActions(['pointerUp'], LEFT);
773
- return this.actions([{
774
- type: 'pointer',
775
- id: 'mouse',
776
- actions: goToDrag.concat(startDrag).concat(doDrag).concat(endDrag),
777
- }]);
778
- }
779
-
780
- drag(seleniumElement, targetRect, xElementOffset, yElementOffset, events) {
781
- const { width, height } = targetRect;
782
- const midXRelative = (xElementOffset - width / 2 + 1);
783
- const midYRelative = (yElementOffset - height / 2);
784
- return this.getDragCoordinates(events)
785
- .then(coordinates => {
786
- const { xDiff, yDiff } = coordinates;
787
- if (this.unsupportedActions.move) {
788
- return this.dragWithActionsAPI(seleniumElement, xDiff, yDiff, midXRelative, midYRelative);
789
- }
790
- return this.dragWithMoveTo(seleniumElement, xDiff, yDiff, midXRelative, midYRelative)
791
- .catch(err => {
792
- if (isOldProtocol(err)) {
793
- this.unsupportedActions.move = true;
794
- return this.dragWithActionsAPI(seleniumElement, xDiff, yDiff, midXRelative, midYRelative);
795
- }
796
- throw err;
797
- });
798
- });
799
- }
800
-
801
- getMoveRelativeSequence(startLeft, startTop, endLeft, endTop) {
802
- const sqr = x => x * x;
803
- const distance = (p1, p2) => Math.sqrt(sqr(p1.x - p2.x) + sqr(p1.y - p2.y));
804
-
805
- const from = { x: startLeft, y: startTop };
806
- const to = { x: endLeft, y: endTop };
807
- const MOVE_EVENT_DIST = 10;
808
- const eventCount = Math.round(distance(from, to) / MOVE_EVENT_DIST);
809
-
810
- /* generate move events array */
811
- const moves = Array.apply([], new Array(eventCount))
812
- .map(() => ({
813
- x: Math.round((to.x - from.x) / eventCount),
814
- y: Math.round((to.y - from.y) / eventCount)
815
- }));
816
- return [{ x: 1, y: 1 }].concat(moves);
817
- }
818
-
819
- getMoveAbsoluteSequence(startLeft, startTop, endLeft, endTop) {
820
- const relativeMoves = this.getMoveRelativeSequence(startLeft, startTop, endLeft, endTop);
821
- return relativeMoves.reduce((newMoves, relativeMove) => {
822
- const lastMove = _.last(newMoves);
823
- return newMoves.concat({ x: Math.round(lastMove.x + relativeMove.x), y: Math.round(lastMove.y + relativeMove.y) });
824
- }, [{ x: Math.round(startLeft), y: Math.round(startTop) }]);
825
- }
826
-
827
- async dragAndDropWithGeneratedMoves(sourceSeleniumElement, destinationSeleniumElement, rectsAndOffsets) {
828
- const { fromRect, fromX, fromY, toRect, toX, toY } = rectsAndOffsets;
829
- const moveSequence = this.getMoveRelativeSequence(fromRect.left + fromX, fromRect.top + fromY, toRect.left + toX, toRect.top + toY);
830
-
831
- await this.moveTo(extractElementId(sourceSeleniumElement), Math.round(fromX), Math.round(fromY));
832
- await this.buttonDown();
833
- for (const movePosition of moveSequence) {
834
- await this.moveTo(null, movePosition.x, movePosition.y);
835
- }
836
- await this.moveTo(extractElementId(destinationSeleniumElement), Math.round(toX), Math.round(toY));
837
- return await this.buttonUp();
838
- }
839
-
840
- dragAndDropWithActionsAPIWithGeneratedMoves(rectsAndOffsets) {
841
- const { fromRect, fromX, fromY, toRect, toX, toY } = rectsAndOffsets;
842
- const startLeft = Math.round(fromRect.left + fromX);
843
- const startTop = Math.round(fromRect.top + fromY);
844
- const endLeft = Math.round(toRect.left + toX);
845
- const endTop = Math.round(toRect.top + toY);
846
- const moveSequence = this.getMoveAbsoluteSequence(fromRect.left + fromX, fromRect.top + fromY, toRect.left + toX, toRect.top + toY);
847
- const startMovePositionActions = this.getMoveActions(startLeft, startTop);
848
- const pointerDownActions = this.getClickActions(['pointerDown'], LEFT);
849
- const moveSequenceActions = _.flatMap(moveSequence, movePosition => this.getMoveActions(movePosition.x, movePosition.y));
850
- const endMovePositionActions = this.getMoveActions(endLeft, endTop);
851
- const pointerUpActions = this.getClickActions(['pointerUp'], LEFT);
852
- const actions = startMovePositionActions.concat(pointerDownActions).concat(moveSequenceActions).concat(endMovePositionActions).concat(pointerUpActions);
853
-
854
- return this.actions([{
855
- type: 'pointer',
856
- id: 'mouse',
857
- actions,
858
- }]);
859
- }
860
-
861
- dragAndDrop(sourceSeleniumElement, destinationSeleniumElement, rectsAndOffsets) {
862
- if (this.isSafari()) {
863
- if (this.unsupportedActions.move) {
864
- return this.dragAndDropWithActionsAPIWithGeneratedMoves(rectsAndOffsets);
865
- }
866
- return this.dragAndDropWithGeneratedMoves(sourceSeleniumElement, destinationSeleniumElement, rectsAndOffsets)
867
- .catch(err => {
868
- if (isOldProtocol(err)) {
869
- this.unsupportedActions.move = true;
870
- return this.dragAndDropWithActionsAPIWithGeneratedMoves(rectsAndOffsets);
871
- }
872
- throw err;
873
- });
874
- }
875
- if (this.unsupportedActions.move) {
876
- return this.dragAndDropWithActionsAPI(rectsAndOffsets);
877
- }
878
- return this.dragAndDropOldAPI(sourceSeleniumElement, destinationSeleniumElement)
879
- .catch(err => {
880
- if (isOldProtocol(err)) {
881
- this.unsupportedActions.move = true;
882
- return this.dragAndDropWithActionsAPI(rectsAndOffsets);
883
- }
884
- throw err;
885
- });
886
- }
887
-
888
- doubleClickFallback(element, eventData, offsets) {
889
- if (this.isSafari()) {
890
- return this.doubleClickWithJS(eventData);
891
- }
892
- return this.doubleClickWithActionsAPI(element, offsets);
893
- }
894
-
895
- doubleClick(element, eventData, offsets) {
896
- if (this.unsupportedActions.move || this.isSafari()) { // doDoubleClick API doesn't work in Safari browser
897
- return this.doubleClickFallback(element, eventData, offsets);
898
- }
899
- return this.moveTo(extractElementId(element))
900
- .then(() => this.doDoubleClick())
901
- .catch(err => {
902
- if (isOldProtocol(err)) {
903
- this.unsupportedActions.move = true;
904
- return this.doubleClickFallback(element, eventData, offsets);
905
- }
906
- throw err;
907
- });
908
- }
909
-
910
- dragAndDropWithActionsAPI(rectsAndOffsets) {
911
- const { fromRect, fromX, fromY, toRect, toX, toY } = rectsAndOffsets;
912
- const startLeft = Math.round(fromRect.left + fromX);
913
- const startTop = Math.round(fromRect.top + fromY);
914
- const endLeft = Math.round(toRect.left + toX);
915
- const endTop = Math.round(toRect.top + toY);
916
- return this.moveWithActionsAPI({ x: startLeft, y: startTop })
917
- .then(() => {
918
- const actions = this.getClickActionList(['pointerDown'], LEFT);
919
- return this.actions(actions);
920
- })
921
- .then(() => this.moveWithActionsAPI({ x: endLeft, y: endTop }))
922
- .then(() => {
923
- const actions = this.getClickActionList(['pointerUp'], LEFT);
924
- return this.actions(actions);
925
- });
926
- }
927
-
928
- getTabIds() {
929
- return this.windowHandles().then(r => r.value);
930
- }
931
-
932
- isVisible(el) {
933
- return this.elementIdDisplayed(extractElementId(el)).then(r => r.value);
934
- }
935
-
936
- getSource() {
937
- return this.source();
938
- }
939
-
940
- getElementRect(target) {
941
- const defaultLocation = { width: 0, height: 0, top: 0, left: 0 };
942
- return this.getElementLocation(target).catch((err) => logger.error('error getting element location', { err }))
943
- .then(loc => {
944
- if (loc?.value) {
945
- return {
946
- top: loc.value.y,
947
- left: loc.value.x,
948
- width: loc.value.width,
949
- height: loc.value.height,
950
- };
951
- }
952
- return defaultLocation;
953
- });
954
- }
955
-
956
- end() {
957
- logger.info('delete session', { sessionId: this.getSessionId() });
958
- if (!this.getSessionId()) {
959
- logger.warn('failed to close session because session is undefined');
960
- }
961
- clearInterval(this.keepAliveTimer);
962
- return super.end()
963
- .catch(() => {
964
- /* !!!!SILENCE!!!! */
965
- });
966
- }
967
-
968
- inViewCenter(rectangle) {
969
- return {
970
- x: rectangle.width / 2,
971
- y: rectangle.height / 2,
972
- };
973
- }
974
- }
975
-
976
- module.exports = WebDriver;