/
index.ts
548 lines (484 loc) · 18.8 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
import fs from 'node:fs/promises'
import path from 'node:path'
import { URL } from 'node:url'
import cssValue from 'css-value'
import rgb2hex from 'rgb2hex'
import GraphemeSplitter from 'grapheme-splitter'
import logger from '@wdio/logger'
import isPlainObject from 'is-plain-obj'
import { UNICODE_CHARACTERS } from '@wdio/utils'
import type { ElementReference } from '@wdio/protocols'
import * as browserCommands from '../commands/browser.js'
import * as elementCommands from '../commands/element.js'
import querySelectorAllDeep from './thirdParty/querySelectorShadowDom.js'
import { ELEMENT_KEY, DEEP_SELECTOR, Key } from '../constants.js'
import { findStrategy } from './findStrategy.js'
import type { ElementFunction, Selector, ParsedCSSValue, CustomLocatorReturnValue } from '../types.js'
import type { CustomStrategyReference } from '../types.js'
const log = logger('webdriverio')
const INVALID_SELECTOR_ERROR = 'selector needs to be typeof `string` or `function`'
const IGNORED_COMMAND_FILE_EXPORTS = ['SESSION_MOCKS', 'CDP_SESSIONS']
declare global {
interface Window { __wdio_element: Record<string, HTMLElement> }
}
const scopes = {
browser: browserCommands,
element: elementCommands
}
const applyScopePrototype = (
prototype: Record<string, PropertyDescriptor>,
scope: 'browser' | 'element') => {
Object.entries(scopes[scope])
.filter(([exportName]) => !IGNORED_COMMAND_FILE_EXPORTS.includes(exportName))
.forEach(([commandName, command]) => {
prototype[commandName] = { value: command }
})
}
/**
* enhances objects with element commands
*/
export const getPrototype = (scope: 'browser' | 'element') => {
const prototype: Record<string, PropertyDescriptor> = {
/**
* used to store the puppeteer instance in the browser scope
*/
puppeteer: { value: null, writable: true }
}
/**
* register action commands
*/
applyScopePrototype(prototype, scope)
prototype.strategies = { value: new Map() }
return prototype
}
/**
* get element id from WebDriver response
* @param {?Object|undefined} res body object from response or null
* @return {?string} element id or null if element couldn't be found
*/
export const getElementFromResponse = (res: ElementReference) => {
/**
* a function selector can return null
*/
if (!res) {
return null
}
/**
* deprecated JSONWireProtocol response
*/
if ((res as any).ELEMENT) {
return (res as any as { ELEMENT: string }).ELEMENT
}
/**
* W3C WebDriver response
*/
if (res[ELEMENT_KEY]) {
return res[ELEMENT_KEY]
}
return null
}
/**
* traverse up the scope chain until browser element was reached
*/
export function getBrowserObject (elem: WebdriverIO.Element | WebdriverIO.Browser): WebdriverIO.Browser {
const elemObject = elem as WebdriverIO.Element
return (elemObject as WebdriverIO.Element).parent ? getBrowserObject(elemObject.parent) : elem as WebdriverIO.Browser
}
function sanitizeCSS (value?: string) {
/* istanbul ignore next */
if (!value) {
return value
}
return value.trim().replace(/'/g, '').replace(/"/g, '').toLowerCase()
}
/**
* parse css values to a better format
* @param {string} cssPropertyValue result of WebDriver call
* @param {string} cssProperty name of css property to parse
* @return {object} parsed css property
*/
export function parseCSS (cssPropertyValue: string, cssProperty?: string) {
const parsedValue: ParsedCSSValue = {
property: cssProperty,
value: cssPropertyValue.toLowerCase().trim(),
parsed: {}
}
if (parsedValue.value?.indexOf('rgb') === 0) {
/**
* remove whitespaces in rgb values
*/
parsedValue.value = parsedValue.value.replace(/\s/g, '')
/**
* parse color values
*/
const color = parsedValue.value
parsedValue.parsed = rgb2hex(parsedValue.value)
parsedValue.parsed.type = 'color'
const colorType = /[rgba]+/g.exec(color) || []
parsedValue.parsed[colorType[0] as 'rgb' | 'rgba'] = color
} else if (parsedValue.property === 'font-family') {
const font = cssValue(cssPropertyValue)
const string = parsedValue.value
const value = cssPropertyValue.split(/,/).map(sanitizeCSS)
parsedValue.value = sanitizeCSS(font[0].value as string || font[0].string)
parsedValue.parsed = { value, type: 'font', string }
} else {
/**
* parse other css properties
*/
try {
const value = cssValue(cssPropertyValue)
if (value.length === 1) {
parsedValue.parsed = value[0]
}
if (parsedValue.parsed.type && parsedValue.parsed.type === 'number' && parsedValue.parsed.unit === '') {
parsedValue.value = parsedValue.parsed.value
}
} catch (err: any) {
// TODO improve css-parse lib to handle properties like
// `-webkit-animation-timing-function : cubic-bezier(0.25, 0.1, 0.25, 1)
}
}
return parsedValue
}
/**
* check for unicode character or split string into literals
* @param {string} value text
* @return {Array} set of characters or unicode symbols
*/
export function checkUnicode (value: string, isDevTools = false) {
/**
* "Ctrl" key is specially handled based on OS in action class
*/
if (value === Key.Ctrl) {
return [value]
}
/**
* when sending emoji characters like 😄 or a value that is not a special character defined
* by the WebDriver protocol
*/
if (!Object.prototype.hasOwnProperty.call(UNICODE_CHARACTERS, value)) {
return new GraphemeSplitter().splitGraphemes(value)
}
if (isDevTools) {
return [value]
}
return [UNICODE_CHARACTERS[value as keyof typeof UNICODE_CHARACTERS]]
}
function fetchElementByJSFunction (
selector: ElementFunction,
scope: WebdriverIO.Browser | WebdriverIO.Element,
referenceId?: string
): Promise<ElementReference | ElementReference[]> {
if (!(scope as WebdriverIO.Element).elementId) {
return scope.execute(selector as any, referenceId)
}
/**
* use a regular function because IE does not understand arrow functions
*/
const script = (function (elem: HTMLElement, id: string) {
return (selector as any as Function).call(elem, id)
}).toString().replace('selector', `(${selector.toString()})`)
const args: (WebdriverIO.Element | string)[] = [scope as WebdriverIO.Element]
if (referenceId) {
args.push(referenceId)
}
return getBrowserObject(scope).execute(`return (${script}).apply(null, arguments)`, ...args)
}
export function isElement (o: Selector){
return (
typeof HTMLElement === 'object'
? o instanceof HTMLElement
: o && typeof o === 'object' && o !== null && (o as HTMLElement).nodeType === 1 && typeof (o as HTMLElement).nodeName==='string'
)
}
/**
* logic to find an element
*/
export async function findElement(
this: WebdriverIO.Browser | WebdriverIO.Element,
selector: Selector
) {
const browserObject = getBrowserObject(this)
/**
* check if shadow DOM integration is used
*/
if (!this.isDevTools && typeof selector === 'string' && selector.startsWith(DEEP_SELECTOR)) {
const notFoundError = new Error(`shadow selector "${selector.slice(DEEP_SELECTOR.length)}" did not return an HTMLElement`)
let elem: ElementReference | ElementReference[] = await browserObject.execute(
`return (${querySelectorAllDeep}).apply(null, arguments)`,
false,
selector.slice(DEEP_SELECTOR.length),
// hard conversion from element id to Element is done by browser driver
((this as WebdriverIO.Element).elementId ? this : undefined) as any as Element | Document
)
elem = Array.isArray(elem) ? elem[0] : elem
return getElementFromResponse(elem) ? elem : notFoundError
}
/**
* fetch element using custom strategy function
*/
if (selector && typeof selector === 'object' && typeof (selector as CustomStrategyReference).strategy === 'function') {
const { strategy, strategyName, strategyArguments } = selector as CustomStrategyReference
const notFoundError = new Error(`Custom Strategy "${strategyName}" did not return an HTMLElement`)
let elem = await browserObject.execute(strategy, ...strategyArguments)
elem = Array.isArray(elem) ? elem[0] : elem
return getElementFromResponse(elem) ? elem : notFoundError
}
/**
* fetch element using regular protocol command
*/
if (typeof selector === 'string' || isPlainObject(selector)) {
const { using, value } = findStrategy(selector as string, this.isW3C, this.isMobile)
return (this as WebdriverIO.Element).elementId
// casting to any necessary given weak type support of protocol commands
? this.findElementFromElement((this as WebdriverIO.Element).elementId, using, value) as any as ElementReference
: this.findElement(using, value) as any as ElementReference
}
/**
* fetch element with JS function
*/
if (typeof selector === 'function') {
const notFoundError = new Error(`Function selector "${selector.toString()}" did not return an HTMLElement`)
let elem = await fetchElementByJSFunction(selector, this)
elem = Array.isArray(elem) ? elem[0] : elem
return getElementFromResponse(elem) ? elem : notFoundError
}
/**
* handle DOM element transformation
* Note: this runs in the browser
*/
if (isElement(selector)) {
if (!window.__wdio_element) {
window.__wdio_element = {}
}
const notFoundError = new Error('DOM Node couldn\'t be found anymore')
const uid = Math.random().toString().slice(2)
window.__wdio_element[uid] = selector as HTMLElement
selector = ((id: string) => window.__wdio_element[id]) as any as ElementFunction
let elem = await fetchElementByJSFunction(selector, this, uid)
elem = Array.isArray(elem) ? elem[0] : elem
return getElementFromResponse(elem) ? elem : notFoundError
}
throw new Error(INVALID_SELECTOR_ERROR)
}
/**
* logic to find a elements
*/
export async function findElements(
this: WebdriverIO.Browser | WebdriverIO.Element,
selector: Selector
) {
const browserObject = getBrowserObject(this)
/**
* check if shadow DOM integration is used
*/
if (!this.isDevTools && typeof selector === 'string' && selector.startsWith(DEEP_SELECTOR)) {
const elems: ElementReference | ElementReference[] = await browserObject.execute(
`return (${querySelectorAllDeep}).apply(null, arguments)`,
true,
selector.slice(DEEP_SELECTOR.length),
// hard conversion from element id to Element is done by browser driver
((this as WebdriverIO.Element).elementId ? this : undefined) as any as Element | Document
)
const elemArray = Array.isArray(elems) ? elems : [elems]
return elemArray.filter((elem) => elem && getElementFromResponse(elem))
}
/**
* fetch elements using custom strategy function
*/
if (isPlainObject(selector) && typeof (selector as CustomStrategyReference).strategy === 'function') {
const { strategy, strategyArguments } = selector as CustomStrategyReference
const elems = await browserObject.execute(strategy, ...strategyArguments)
const elemArray = Array.isArray(elems) ? elems as ElementReference[] : [elems]
return elemArray.filter((elem) => elem && getElementFromResponse(elem))
}
/**
* fetch element using regular protocol command
*/
if (typeof selector === 'string' || isPlainObject(selector)) {
const { using, value } = findStrategy(selector as string, this.isW3C, this.isMobile)
return (this as WebdriverIO.Element).elementId
// casting to any necessary given weak type support of protocol commands
? this.findElementsFromElement((this as WebdriverIO.Element).elementId, using, value) as any as ElementReference[]
: this.findElements(using, value) as any as ElementReference[]
}
/**
* fetch element with JS function
*/
if (typeof selector === 'function') {
const elems = await fetchElementByJSFunction(selector, this)
const elemArray = Array.isArray(elems) ? elems as ElementReference[] : [elems]
return elemArray.filter((elem) => elem && getElementFromResponse(elem))
}
throw new Error(INVALID_SELECTOR_ERROR)
}
/**
* Strip element object and return w3c and jsonwp compatible keys
*/
export function verifyArgsAndStripIfElement(args: any) {
function verify (arg: any) {
if (arg && typeof arg === 'object' && arg.constructor.name === 'Element') {
const elem = arg as WebdriverIO.Element
if (!elem.elementId) {
throw new Error(`The element with selector "${elem.selector}" you are trying to pass into the execute method wasn't found`)
}
return {
[ELEMENT_KEY]: elem.elementId,
ELEMENT: elem.elementId
}
}
return arg
}
return !Array.isArray(args) ? verify(args) : args.map(verify)
}
/**
* getElementRect
*/
export async function getElementRect(scope: WebdriverIO.Element) {
const rect = await scope.getElementRect(scope.elementId)
const defaults = { x: 0, y: 0, width: 0, height: 0 }
/**
* getElementRect workaround for Safari 12.0.3
* if one of [x, y, height, width] is undefined get rect with javascript
*/
if (Object.keys(defaults).some((key: keyof typeof defaults) => rect[key] === undefined)) {
/* istanbul ignore next */
const rectJs = await getBrowserObject(scope).execute(function (this: Window, el: HTMLElement) {
if (!el || !el.getBoundingClientRect) {
return
}
const { left, top, width, height } = el.getBoundingClientRect()
return {
x: left + this.scrollX,
y: top + this.scrollY,
width,
height
}
}, scope as any as HTMLElement)
// try set proper value
Object.keys(defaults).forEach((key: keyof typeof defaults) => {
if (typeof rect[key] !== 'undefined') {
return
}
if (rectJs && typeof rectJs[key] === 'number') {
rect[key] = Math.floor(rectJs[key])
} else {
log.error('getElementRect', { rect, rectJs, key })
throw new Error('Failed to receive element rects via execute command')
}
})
}
return rect
}
export function getAbsoluteFilepath(filepath: string) {
return filepath.startsWith('/') || filepath.startsWith('\\') || filepath.match(/^[a-zA-Z]:\\/)
? filepath
: path.join(process.cwd(), filepath)
}
/**
* check if directory exists
*/
export async function assertDirectoryExists(filepath: string) {
const exist = await fs.access(path.dirname(filepath)).then(() => true, () => false)
if (!exist) {
throw new Error(`directory (${path.dirname(filepath)}) doesn't exist`)
}
}
/**
* check if urls are valid and fix them if necessary
* @param {string} url url to navigate to
* @param {Boolean} [retryCheck=false] true if an url was already check and still failed with fix applied
* @return {string} fixed url
*/
export function validateUrl (url: string, origError?: Error): string {
try {
const urlObject = new URL(url)
return urlObject.href
} catch (err: any) {
/**
* if even adding http:// doesn't help, fail with original error
*/
if (origError) {
throw origError
}
return validateUrl(`http://${url}`, new Error(`Invalid URL: ${url}`))
}
}
export async function hasElementId (element: WebdriverIO.Element) {
/*
* This is only necessary as isDisplayed is on the exclusion list for the middleware
*/
if (!element.elementId) {
const command = element.isReactElement
? element.parent.react$.bind(element.parent)
: element.isShadowElement
? element.parent.shadow$.bind(element.parent)
: element.parent.$.bind(element.parent)
element.elementId = (await command(element.selector as string)).elementId
}
/*
* if element was still not found it also is not displayed
*/
if (!element.elementId) {
return false
}
return true
}
export function addLocatorStrategyHandler(scope: WebdriverIO.Browser | WebdriverIO.MultiRemoteBrowser) {
return (name: string, func: (selector: string, root?: HTMLElement) => CustomLocatorReturnValue) => {
if (scope.strategies.get(name)) {
throw new Error(`Strategy ${name} already exists`)
}
scope.strategies.set(name, func)
}
}
/**
* Enhance elements array with data required to refetch it
* @param {object[]} elements elements
* @param {object} parent element or browser
* @param {string|Function} selector string or function, or strategy name for `custom$$`
* @param {string} foundWith name of the command elements were found with, ex `$$`, `react$$`, etc
* @param {Array} props additional properties required to fetch elements again
* @returns {object[]} elements
*/
export const enhanceElementsArray = (
elements: WebdriverIO.ElementArray,
parent: WebdriverIO.Browser | WebdriverIO.Element,
selector: Selector | ElementReference[] | WebdriverIO.Element[],
foundWith = '$$',
props: any[] = []
) => {
/**
* if we have an element collection, e.g. `const elems = $$([elemA, elemB])`
* we cna't assign a common selector to the element array
*/
if (!Array.isArray(selector)) {
elements.selector = selector
}
elements.parent = parent
elements.foundWith = foundWith
elements.props = props
return elements
}
/**
* is protocol stub
* @param {string} automationProtocol
*/
export const isStub = (automationProtocol?: string) => automationProtocol === './protocol-stub.js'
/**
* compare if an object (`base`) contains the same values as another object (`match`)
* @param {object} base object to compare to
* @param {object} match object that needs to match thebase
*/
export const containsHeaderObject = (
base: Record<string, string>,
match: Record<string, string>
) => {
for (const [key, value] of Object.entries(match)) {
if (typeof base[key] === 'undefined' || base[key] !== value) {
return false
}
}
return true
}