-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrecorder.js
710 lines (660 loc) · 20.9 KB
/
recorder.js
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
"use strict";
/**
Cypress.io action recorder used as a default one in the Cypress Support Pro plugin for IntelliJ platform.
See details here: https://plugins.jetbrains.com/plugin/13987-cypress-support-pro.
Derived from the code of KabaLabs / Cypress-Recorder (https://github.com/KabaLabs/Cypress-Recorder/).
*/
let recordedCode = ""
IntellijCypressRecorder.start = function () {
addDOMListeners();
}
IntellijCypressRecorder.stop = function () {
removeDOMListeners();
}
IntellijCypressRecorder.pullCode = function () {
let res = recordedCode
recordedCode = ""
return res
}
const EventType = {
CLICK: "click",
CHANGE: "change",
DBCLICK: "dbclick",
KEYDOWN: "keydown",
SUBMIT: "submit"
}
/**
* Parses DOM events into an object with the necessary data.
* @param event
* @returns {ParsedEvent}
*/
function parseEvent(event) {
var selector;
if (event.target.hasAttribute('data-cy'))
selector = "[data-cy=" + event.target.getAttribute('data-cy') + "]";
else if (event.target.hasAttribute('data-test'))
selector = "[data-test=" + event.target.getAttribute('data-test') + "]";
else if (event.target.hasAttribute('data-testid'))
selector = "[data-testid=" + event.target.getAttribute('data-testid') + "]";
else
selector = default_1(event.target);
var parsedEvent = {
selector: selector,
action: event.type,
tag: event.target.tagName,
value: event.target.value
};
if (event.target.hasAttribute('href'))
parsedEvent.href = event.target.href;
if (event.target.hasAttribute('id'))
parsedEvent.id = event.target.id;
if (parsedEvent.tag === 'INPUT')
parsedEvent.inputType = event.target.type;
if (event.type === 'keydown')
parsedEvent.key = event.key;
return parsedEvent;
}
/**
* Checks if DOM event was triggered by user; if so, it calls parseEvent on the data.
* @param event
*/
function handleEvent(event) {
if (event.isTrusted === true)
recordedCode += createBlock(parseEvent(event)) + "\n";
}
/**
* Helper functions that handle each action type.
* @param event
*/
function handleClick(event) {
return "cy.get('" + event.selector + "').click();";
}
function handleKeydown(event) {
switch (event.key) {
case 'Backspace':
return "cy.get('" + event.selector + "').type('{backspace}');";
case 'Escape':
return "cy.get('" + event.selector + "').type('{esc}');";
case 'ArrowUp':
return "cy.get('" + event.selector + "').type('{uparrow}');";
case 'ArrowRight':
return "cy.get('" + event.selector + "').type('{rightarrow}');";
case 'ArrowDown':
return "cy.get('" + event.selector + "').type('{downarrow}');";
case 'ArrowLeft':
return "cy.get('" + event.selector + "').type('{leftarrow}');";
default:
return null;
}
}
function handleChange(event) {
if (event.inputType === 'checkbox' || event.inputType === 'radio')
return null;
return "cy.get('" + event.selector + "').type('" + event.value.replace(/'/g, "\\'") + "');";
}
function handleDoubleclick(event) {
return "cy.get('" + event.selector + "').dblclick();";
}
function handleSubmit(event) {
return "cy.get('" + event.selector + "').submit();";
}
function createBlock(event) {
switch (event.action) {
case EventType.CLICK:
return handleClick(event);
case EventType.KEYDOWN:
return handleKeydown(event);
case EventType.CHANGE:
return handleChange(event);
case EventType.DBCLICK:
return handleDoubleclick(event);
case EventType.SUBMIT:
return handleSubmit(event);
default:
throw new Error("Unhandled event: " + event.action);
}
}
/**
* Returns the document root for the aut application.
* Since it's run inside the Cypress runner so the aut document root is expected to be in an iframe
*
* @returns {Document}
*/
function autDoc() {
return document.querySelector(".aut-iframe").contentDocument || document
}
/**
* Adds event listeners to the DOM.
*/
function addDOMListeners() {
Object.values(EventType).forEach(function (event) {
autDoc().addEventListener(event, handleEvent, {
capture: true,
passive: true
});
});
}
/**
* Removes event listeners from the DOM.
*/
function removeDOMListeners() {
Object.values(EventType).forEach(function (event) {
autDoc().removeEventListener(event, handleEvent, {capture: true});
});
}
// ************* The rest is inlined code of some utility packages **********************
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = {
label: 0, sent: function () {
if (t[0] & 1) throw t[1];
return t[1];
}, trys: [], ops: []
}, f, y, t, g;
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
return this;
}), g;
function verb(n) {
return function (v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {value: op[1], done: false};
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {value: op[0] ? op[1] : void 0, done: true};
}
};
var __values = (this && this.__values) || function (o) {
var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
if (m) return m.call(o);
return {
next: function () {
if (o && i >= o.length) o = void 0;
return {value: o && o[i++], done: !o};
}
};
};
var Limit;
(function (Limit) {
Limit[Limit["All"] = 0] = "All";
Limit[Limit["Two"] = 1] = "Two";
Limit[Limit["One"] = 2] = "One";
})(Limit || (Limit = {}));
var config;
var rootDocument;
function default_1(input, options) {
if (input.nodeType !== Node.ELEMENT_NODE) {
throw new Error("Can't generate CSS selector for non-element node type.");
}
if ('html' === input.tagName.toLowerCase()) {
return 'html';
}
var defaults = {
root: autDoc().body,
idName: function (name) {
return true;
},
className: function (name) {
return true;
},
tagName: function (name) {
return true;
},
attr: function (name, value) {
return false;
},
seedMinLength: 1,
optimizedMinLength: 2,
threshold: 1000,
};
config = __assign({}, defaults, options);
rootDocument = findRootDocument(config.root, defaults);
var path = bottomUpSearch(input, Limit.All, function () {
return bottomUpSearch(input, Limit.Two, function () {
return bottomUpSearch(input, Limit.One);
});
});
if (path) {
var optimized = sort(optimize(path, input));
if (optimized.length > 0) {
path = optimized[0];
}
return selector(path);
} else {
throw new Error("Selector was not found.");
}
}
function findRootDocument(rootNode, defaults) {
if (rootNode.nodeType === Node.DOCUMENT_NODE) {
return rootNode;
}
if (rootNode === defaults.root) {
return rootNode.ownerDocument;
}
return rootNode;
}
function bottomUpSearch(input, limit, fallback) {
var path = null;
var stack = [];
var current = input;
var i = 0;
var _loop_1 = function () {
var level = maybe(id(current)) || maybe.apply(void 0, attr(current)) || maybe.apply(void 0, classNames(current)) || maybe(tagName(current)) || [any()];
var nth = index(current);
if (limit === Limit.All) {
if (nth) {
level = level.concat(level.filter(dispensableNth).map(function (node) {
return nthChild(node, nth);
}));
}
} else if (limit === Limit.Two) {
level = level.slice(0, 1);
if (nth) {
level = level.concat(level.filter(dispensableNth).map(function (node) {
return nthChild(node, nth);
}));
}
} else if (limit === Limit.One) {
var node = (level = level.slice(0, 1))[0];
if (nth && dispensableNth(node)) {
level = [nthChild(node, nth)];
}
}
for (var _i = 0, level_1 = level; _i < level_1.length; _i++) {
var node = level_1[_i];
node.level = i;
}
stack.push(level);
if (stack.length >= config.seedMinLength) {
path = findUniquePath(stack, fallback);
if (path) {
return "break";
}
}
current = current.parentElement;
i++;
};
while (current && current !== config.root.parentElement) {
var state_1 = _loop_1();
if (state_1 === "break")
break;
}
if (!path) {
path = findUniquePath(stack, fallback);
}
return path;
}
function findUniquePath(stack, fallback) {
var paths = sort(combinations(stack));
if (paths.length > config.threshold) {
return fallback ? fallback() : null;
}
for (var _i = 0, paths_1 = paths; _i < paths_1.length; _i++) {
var candidate = paths_1[_i];
if (unique(candidate)) {
return candidate;
}
}
return null;
}
function selector(path) {
var node = path[0];
var query = node.name;
for (var i = 1; i < path.length; i++) {
var level = path[i].level || 0;
if (node.level === level - 1) {
query = path[i].name + " > " + query;
} else {
query = path[i].name + " " + query;
}
node = path[i];
}
return query;
}
function penalty(path) {
return path.map(function (node) {
return node.penalty;
}).reduce(function (acc, i) {
return acc + i;
}, 0);
}
function unique(path) {
switch (rootDocument.querySelectorAll(selector(path)).length) {
case 0:
throw new Error("Can't select any node with this selector: " + selector(path));
case 1:
return true;
default:
return false;
}
}
function id(input) {
var elementId = input.getAttribute('id');
if (elementId && config.idName(elementId)) {
return {
name: '#' + cssesc(elementId, {isIdentifier: true}),
penalty: 0,
};
}
return null;
}
function attr(input) {
var attrs = Array.from(input.attributes).filter(function (attr) {
return config.attr(attr.name, attr.value);
});
return attrs.map(function (attr) {
return ({
name: '[' + cssesc(attr.name, {isIdentifier: true}) + '="' + cssesc(attr.value) + '"]',
penalty: 0.5
});
});
}
function classNames(input) {
var names = Array.from(input.classList)
.filter(config.className);
return names.map(function (name) {
return ({
name: '.' + cssesc(name, {isIdentifier: true}),
penalty: 1
});
});
}
function tagName(input) {
var name = input.tagName.toLowerCase();
if (config.tagName(name)) {
return {
name: name,
penalty: 2
};
}
return null;
}
function any() {
return {
name: '*',
penalty: 3
};
}
function index(input) {
var parent = input.parentNode;
if (!parent) {
return null;
}
var child = parent.firstChild;
if (!child) {
return null;
}
var i = 0;
while (child) {
if (child.nodeType === Node.ELEMENT_NODE) {
i++;
}
if (child === input) {
break;
}
child = child.nextSibling;
}
return i;
}
function nthChild(node, i) {
return {
name: node.name + (":nth-child(" + i + ")"),
penalty: node.penalty + 1
};
}
function dispensableNth(node) {
return node.name !== 'html' && !node.name.startsWith('#');
}
function maybe() {
var level = [];
for (var _i = 0; _i < arguments.length; _i++) {
level[_i] = arguments[_i];
}
var list = level.filter(notEmpty);
if (list.length > 0) {
return list;
}
return null;
}
function notEmpty(value) {
return value !== null && value !== undefined;
}
function combinations(stack, path) {
var _i, _a, node;
if (path === void 0) {
path = [];
}
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!(stack.length > 0)) return [3 /*break*/, 5];
_i = 0, _a = stack[0];
_b.label = 1;
case 1:
if (!(_i < _a.length)) return [3 /*break*/, 4];
node = _a[_i];
return [5 /*yield**/, __values(combinations(stack.slice(1, stack.length), path.concat(node)))];
case 2:
_b.sent();
_b.label = 3;
case 3:
_i++;
return [3 /*break*/, 1];
case 4:
return [3 /*break*/, 7];
case 5:
return [4 /*yield*/, path];
case 6:
_b.sent();
_b.label = 7;
case 7:
return [2 /*return*/];
}
});
}
function sort(paths) {
return Array.from(paths).sort(function (a, b) {
return penalty(a) - penalty(b);
});
}
function optimize(path, input) {
var i, newPath;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!(path.length > 2 && path.length > config.optimizedMinLength)) return [3 /*break*/, 5];
i = 1;
_a.label = 1;
case 1:
if (!(i < path.length - 1)) return [3 /*break*/, 5];
newPath = path.slice();
newPath.splice(i, 1);
if (!(unique(newPath) && same(newPath, input))) return [3 /*break*/, 4];
return [4 /*yield*/, newPath];
case 2:
_a.sent();
return [5 /*yield**/, __values(optimize(newPath, input))];
case 3:
_a.sent();
_a.label = 4;
case 4:
i++;
return [3 /*break*/, 1];
case 5:
return [2 /*return*/];
}
});
}
function same(path, input) {
return rootDocument.querySelector(selector(path)) === input;
}
var object = {};
var hasOwnProperty = object.hasOwnProperty;
var merge = function merge(options, defaults) {
if (!options) {
return defaults;
}
var result = {};
for (var key in defaults) {
// `if (defaults.hasOwnProperty(key) { … }` is not needed here, since
// only recognized option names are used.
result[key] = hasOwnProperty.call(options, key) ? options[key] : defaults[key];
}
return result;
};
var regexAnySingleEscape = /[ -,\.\/;-@\[-\^`\{-~]/;
var regexSingleEscape = /[ -,\.\/;-@\[\]\^`\{-~]/;
var regexAlwaysEscape = /['"\\]/;
var regexExcessiveSpaces = /(^|\\+)?(\\[A-F0-9]{1,6})\x20(?![a-fA-F0-9\x20])/g;
// https://mathiasbynens.be/notes/css-escapes#css
var cssesc = function cssesc(string, options) {
options = merge(options, cssesc.options);
if (options.quotes != 'single' && options.quotes != 'double') {
options.quotes = 'single';
}
var quote = options.quotes == 'double' ? '"' : '\'';
var isIdentifier = options.isIdentifier;
var firstChar = string.charAt(0);
var output = '';
var counter = 0;
var length = string.length;
while (counter < length) {
var character = string.charAt(counter++);
var codePoint = character.charCodeAt();
var value = void 0;
// If it’s not a printable ASCII character…
if (codePoint < 0x20 || codePoint > 0x7E) {
if (codePoint >= 0xD800 && codePoint <= 0xDBFF && counter < length) {
// It’s a high surrogate, and there is a next character.
var extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) {
// next character is low surrogate
codePoint = ((codePoint & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000;
} else {
// It’s an unmatched surrogate; only append this code unit, in case
// the next code unit is the high surrogate of a surrogate pair.
counter--;
}
}
value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
} else {
if (options.escapeEverything) {
if (regexAnySingleEscape.test(character)) {
value = '\\' + character;
} else {
value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
}
// Note: `:` could be escaped as `\:`, but that fails in IE < 8.
} else if (/[\t\n\f\r\x0B:]/.test(character)) {
if (!isIdentifier && character == ':') {
value = character;
} else {
value = '\\' + codePoint.toString(16).toUpperCase() + ' ';
}
} else if (character == '\\' || !isIdentifier && (character == '"' && quote == character || character == '\'' && quote == character) || isIdentifier && regexSingleEscape.test(character)) {
value = '\\' + character;
} else {
value = character;
}
}
output += value;
}
if (isIdentifier) {
if (/^_/.test(output)) {
// Prevent IE6 from ignoring the rule altogether (in case this is for an
// identifier used as a selector)
output = '\\_' + output.slice(1);
} else if (/^-[-\d]/.test(output)) {
output = '\\-' + output.slice(1);
} else if (/\d/.test(firstChar)) {
output = '\\3' + firstChar + ' ' + output.slice(1);
}
}
// Remove spaces after `\HEX` escapes that are not followed by a hex digit,
// since they’re redundant. Note that this is only possible if the escape
// sequence isn’t preceded by an odd number of backslashes.
output = output.replace(regexExcessiveSpaces, function ($0, $1, $2) {
if ($1 && $1.length % 2) {
// It’s not safe to remove the space, so don’t.
return $0;
}
// Strip the space.
return ($1 || '') + $2;
});
if (!isIdentifier && options.wrap) {
return quote + output + quote;
}
return output;
};
// Expose default options (so they can be overridden globally).
cssesc.options = {
'escapeEverything': false,
'isIdentifier': false,
'quotes': 'single',
'wrap': false
};