-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathindex.js
More file actions
511 lines (447 loc) · 19.9 KB
/
index.js
File metadata and controls
511 lines (447 loc) · 19.9 KB
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
/* Event listeners + custom commands for Cypress */
const browserStackLog = (message) => {
if (!Cypress.env('BROWSERSTACK_LOGS')) return;
cy.task('browserstack_log', message);
}
// Default commands (fallback) - includes 'scroll' for server compatibility
const defaultCommandsToWrap = ['visit', 'click', 'type', 'request', 'dblclick', 'rightclick', 'clear', 'check', 'uncheck', 'select', 'trigger', 'selectFile', 'scrollIntoView', 'scroll', 'scrollTo', 'blur', 'focus', 'go', 'reload', 'submit', 'viewport', 'origin'];
// Valid Cypress commands that can actually be overwritten (excludes 'scroll')
const validCypressCommands = ['visit', 'click', 'type', 'request', 'dblclick', 'rightclick', 'clear', 'check', 'uncheck', 'select', 'trigger', 'selectFile', 'scrollIntoView', 'scrollTo', 'blur', 'focus', 'go', 'reload', 'submit', 'viewport', 'origin'];
// Determine effective commands based on server response
let effectiveCommandsToWrap = defaultCommandsToWrap;
let isBuildEndOnlyMode = false;
// Check if server provided specific commands via environment variables
if (Cypress.env('ACCESSIBILITY_BUILD_END_ONLY') === 'true') {
// Server explicitly wants build-end-only scanning
effectiveCommandsToWrap = [];
isBuildEndOnlyMode = true;
browserStackLog('[A11Y] Server enabled build-end-only mode - disabling all command scanning');
} else if (Cypress.env('ACCESSIBILITY_COMMANDS_TO_WRAP')) {
try {
const serverCommands = JSON.parse(Cypress.env('ACCESSIBILITY_COMMANDS_TO_WRAP'));
if (Array.isArray(serverCommands)) {
if (serverCommands.length === 0) {
// Empty array = build-end only
effectiveCommandsToWrap = [];
isBuildEndOnlyMode = true;
browserStackLog('[A11Y] Server provided empty commands - enabling build-end-only mode');
} else {
// Use server-provided command list
effectiveCommandsToWrap = serverCommands.map(cmd => cmd.name || cmd);
isBuildEndOnlyMode = false;
browserStackLog(`[A11Y] Using server commands: ${effectiveCommandsToWrap.join(', ')}`);
}
}
} catch (error) {
browserStackLog(`[A11Y] Error parsing server commands, using defaults: ${error.message}`);
}
} else {
browserStackLog('[A11Y] No server commands provided, using default command list');
}
// Filter to only include VALID Cypress commands that are also in effective commands
const commandToOverwrite = validCypressCommands.filter(cmd =>
effectiveCommandsToWrap.includes(cmd)
);
browserStackLog(`[A11Y] Commands to wrap: ${commandToOverwrite.length} out of ${validCypressCommands.length} valid commands`);
browserStackLog(`[A11Y] Build-end-only mode: ${isBuildEndOnlyMode}`);
/*
Overrriding the cypress commands to perform Accessibility Scan before Each command
- runCutomizedCommand is handling both the cases of subject available in cypress original command
and chaning available from original cypress command.
*/
const performModifiedScan = (originalFn, Subject, stateType, ...args) => {
let customChaining = cy.wrap(null).performScan();
const changeSub = (args, stateType, newSubject) => {
if (stateType !== 'parent') {
return [newSubject, ...args.slice(1)];
}
return args;
}
const runCustomizedCommand = () => {
if (!Subject) {
let orgS1, orgS2, cypressCommandSubject = null;
if((orgS2 = (orgS1 = cy).subject) !==null && orgS2 !== void 0){
cypressCommandSubject = orgS2.call(orgS1);
}
customChaining.then(()=> cypressCommandSubject).then(() => {originalFn(...args)});
} else {
let orgSC1, orgSC2, timeO1, cypressCommandChain = null, setTimeout = null;
if((timeO1 = args.find(arg => arg !== null && arg !== void 0 ? arg.timeout : null)) !== null && timeO1 !== void 0) {
setTimeout = timeO1.timeout;
}
if((orgSC1 = (orgSC2 = cy).subjectChain) !== null && orgSC1 !== void 0){
cypressCommandChain = orgSC1.call(orgSC2);
}
customChaining.performScanSubjectQuery(cypressCommandChain, setTimeout).then({timeout: 30000}, (newSubject) => originalFn(...changeSub(args, stateType, newSubject)));
}
}
runCustomizedCommand();
}
const performScan = (win, payloadToSend) =>
new Promise(async (resolve, reject) => {
const isHttpOrHttps = /^(http|https):$/.test(win.location.protocol);
if (!isHttpOrHttps) {
return resolve();
}
const isBuildEndOnly = Cypress.env('ACCESSIBILITY_BUILD_END_ONLY') === 'true';
function findAccessibilityAutomationElement() {
return win.document.querySelector("#accessibility-automation-element");
}
function waitForScannerReadiness(retryCount = 100, retryInterval = 100) {
return new Promise(async (resolve, reject) => {
let count = 0;
const intervalID = setInterval(async () => {
if (count > retryCount) {
clearInterval(intervalID);
return reject(
new Error(
"Accessibility Automation Scanner is not ready on the page."
)
);
} else if (findAccessibilityAutomationElement()) {
clearInterval(intervalID);
return resolve("Scanner set");
} else {
count += 1;
}
}, retryInterval);
});
}
function startScan() {
function onScanComplete() {
win.removeEventListener("A11Y_SCAN_FINISHED", onScanComplete);
return resolve();
}
win.addEventListener("A11Y_SCAN_FINISHED", onScanComplete);
// Enhanced event with mode information
const scanEvent = new CustomEvent("A11Y_SCAN", {
detail: {
...payloadToSend,
scanMode: isBuildEndOnlyMode ? "comprehensive-build-end" : "incremental",
timestamp: Date.now()
}
});
if (isBuildEndOnlyMode) {
browserStackLog(`[A11Y] Starting comprehensive build-end scan`);
} else {
browserStackLog(`[A11Y] Starting incremental scan`);
}
win.dispatchEvent(scanEvent);
}
if (findAccessibilityAutomationElement()) {
startScan();
} else {
waitForScannerReadiness()
.then(startScan)
.catch(async (err) => {
return resolve("Scanner is not ready on the page after multiple retries. performscan");
});
}
})
const getAccessibilityResultsSummary = (win) =>
new Promise((resolve) => {
const isHttpOrHttps = /^(http|https):$/.test(window.location.protocol);
if (!isHttpOrHttps) {
return resolve();
}
function findAccessibilityAutomationElement() {
return win.document.querySelector("#accessibility-automation-element");
}
function waitForScannerReadiness(retryCount = 30, retryInterval = 100) {
return new Promise((resolve, reject) => {
let count = 0;
const intervalID = setInterval(() => {
if (count > retryCount) {
clearInterval(intervalID);
return reject(
new Error(
"Accessibility Automation Scanner is not ready on the page."
)
);
} else if (findAccessibilityAutomationElement()) {
clearInterval(intervalID);
return resolve("Scanner set");
} else {
count += 1;
}
}, retryInterval);
});
}
function getSummary() {
function onReceiveSummary(event) {
win.removeEventListener("A11Y_RESULTS_SUMMARY", onReceiveSummary);
return resolve(event.detail);
}
win.addEventListener("A11Y_RESULTS_SUMMARY", onReceiveSummary);
const e = new CustomEvent("A11Y_GET_RESULTS_SUMMARY");
win.dispatchEvent(e);
}
if (findAccessibilityAutomationElement()) {
getSummary();
} else {
waitForScannerReadiness()
.then(getSummary)
.catch((err) => {
return resolve();
});
}
})
const getAccessibilityResults = (win) =>
new Promise((resolve) => {
const isHttpOrHttps = /^(http|https):$/.test(window.location.protocol);
if (!isHttpOrHttps) {
return resolve();
}
function findAccessibilityAutomationElement() {
return win.document.querySelector("#accessibility-automation-element");
}
function waitForScannerReadiness(retryCount = 30, retryInterval = 100) {
return new Promise((resolve, reject) => {
let count = 0;
const intervalID = setInterval(() => {
if (count > retryCount) {
clearInterval(intervalID);
return reject(
new Error(
"Accessibility Automation Scanner is not ready on the page."
)
);
} else if (findAccessibilityAutomationElement()) {
clearInterval(intervalID);
return resolve("Scanner set");
} else {
count += 1;
}
}, retryInterval);
});
}
function getResults() {
function onReceivedResult(event) {
win.removeEventListener("A11Y_RESULTS_RESPONSE", onReceivedResult);
return resolve(event.detail);
}
win.addEventListener("A11Y_RESULTS_RESPONSE", onReceivedResult);
const e = new CustomEvent("A11Y_GET_RESULTS");
win.dispatchEvent(e);
}
if (findAccessibilityAutomationElement()) {
getResults();
} else {
waitForScannerReadiness()
.then(getResults)
.catch((err) => {
return resolve();
});
}
});
const saveTestResults = (win, payloadToSend) =>
new Promise( (resolve, reject) => {
try {
const isHttpOrHttps = /^(http|https):$/.test(win.location.protocol);
if (!isHttpOrHttps) {
resolve("Unable to save accessibility results, Invalid URL.");
return;
}
function findAccessibilityAutomationElement() {
return win.document.querySelector("#accessibility-automation-element");
}
function waitForScannerReadiness(retryCount = 30, retryInterval = 100) {
return new Promise((resolve, reject) => {
let count = 0;
const intervalID = setInterval(async () => {
if (count > retryCount) {
clearInterval(intervalID);
return reject(
new Error(
"Accessibility Automation Scanner is not ready on the page."
)
);
} else if (findAccessibilityAutomationElement()) {
clearInterval(intervalID);
return resolve("Scanner set");
} else {
count += 1;
}
}, retryInterval);
});
}
function saveResults() {
function onResultsSaved(event) {
return resolve();
}
win.addEventListener("A11Y_RESULTS_SAVED", onResultsSaved);
const e = new CustomEvent("A11Y_SAVE_RESULTS", {
detail: payloadToSend,
});
win.dispatchEvent(e);
}
if (findAccessibilityAutomationElement()) {
saveResults();
} else {
waitForScannerReadiness()
.then(saveResults)
.catch(async (err) => {
return resolve("Scanner is not ready on the page after multiple retries. after run");
});
}
} catch(error) {
browserStackLog(`Error in saving results with error: ${error.message}`);
return resolve();
}
})
const shouldScanForAccessibility = (attributes) => {
if (Cypress.env("IS_ACCESSIBILITY_EXTENSION_LOADED") !== "true") return false;
const extensionPath = Cypress.env("ACCESSIBILITY_EXTENSION_PATH");
const isHeaded = Cypress.browser.isHeaded;
if (!isHeaded || (extensionPath === undefined)) return false;
let shouldScanTestForAccessibility = true;
if (Cypress.env("INCLUDE_TAGS_FOR_ACCESSIBILITY") || Cypress.env("EXCLUDE_TAGS_FOR_ACCESSIBILITY")) {
try {
let includeTagArray = [];
let excludeTagArray = [];
if (Cypress.env("INCLUDE_TAGS_FOR_ACCESSIBILITY")) {
includeTagArray = Cypress.env("INCLUDE_TAGS_FOR_ACCESSIBILITY").split(";")
}
if (Cypress.env("EXCLUDE_TAGS_FOR_ACCESSIBILITY")) {
excludeTagArray = Cypress.env("EXCLUDE_TAGS_FOR_ACCESSIBILITY").split(";")
}
const fullTestName = attributes.title;
const excluded = excludeTagArray.some((exclude) => fullTestName.includes(exclude));
const included = includeTagArray.length === 0 || includeTags.some((include) => fullTestName.includes(include));
shouldScanTestForAccessibility = !excluded && included;
} catch (error) {
browserStackLog(`Error while validating test case for accessibility before scanning. Error : ${error.message}`);
}
}
return shouldScanTestForAccessibility;
}
// Only wrap commands if not in build-end-only mode and we have commands to wrap
if (!isBuildEndOnlyMode && commandToOverwrite.length > 0) {
browserStackLog(`[A11Y] Wrapping ${commandToOverwrite.length} commands for accessibility scanning`);
commandToOverwrite.forEach((command) => {
Cypress.Commands.overwrite(command, (originalFn, ...args) => {
const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest || Cypress.mocha.getRunner().suite.ctx._runnable;
const shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
const state = cy.state('current'), Subject = 'getSubjectFromChain' in cy;
const stateName = state === null || state === void 0 ? void 0 : state.get('name');
let stateType = null;
if (!shouldScanTestForAccessibility || (stateName && stateName !== command)) {
return originalFn(...args);
}
if(state !== null && state !== void 0){
stateType = state.get('type');
}
browserStackLog(`[A11Y] Performing command-level scan for: ${command}`);
performModifiedScan(originalFn, Subject, stateType, ...args);
});
});
browserStackLog(`[A11Y] Successfully wrapped ${commandToOverwrite.length} commands for accessibility scanning`);
} else {
browserStackLog(`[A11Y] Command wrapping disabled - using build-end-only scanning mode`);
}
afterEach(() => {
const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest;
cy.window().then(async (win) => {
let shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
if (!shouldScanTestForAccessibility) return cy.wrap({});
// Determine current scanning mode
const currentMode = isBuildEndOnlyMode ? 'build-end-only' : 'command-plus-end';
browserStackLog(`[A11Y] Starting final scan in ${currentMode} mode`);
// Perform final scan (this happens regardless of mode)
cy.wrap(performScan(win), {timeout: 30000}).then(() => {
try {
let os_data;
if (Cypress.env("OS")) {
os_data = Cypress.env("OS");
} else {
os_data = Cypress.platform === 'linux' ? 'mac' : "win"
}
let filePath = '';
if (attributes.invocationDetails !== undefined && attributes.invocationDetails.relativeFile !== undefined) {
filePath = attributes.invocationDetails.relativeFile;
} else if (attributes.prevAttempts && attributes.prevAttempts.length > 0) {
filePath = (attributes.prevAttempts[0].invocationDetails && attributes.prevAttempts[0].invocationDetails.relativeFile) || '';
}
let testRunUuid = null;
cy.task('get_test_run_uuid', { testIdentifier: attributes.title })
.then((response) => {
if (response && response.testRunUuid) {
testRunUuid = response.testRunUuid;
}
const payloadToSend = {
"thTestRunUuid": testRunUuid,
"thBuildUuid": Cypress.env("BROWSERSTACK_TESTHUB_UUID"),
"thJwtToken": Cypress.env("BROWSERSTACK_TESTHUB_JWT"),
"scanMode": currentMode,
"buildEndOnly": isBuildEndOnlyMode
};
browserStackLog(`[A11Y] Saving results for ${currentMode} mode`);
browserStackLog(`[A11Y] Payload: ${JSON.stringify(payloadToSend)}`);
return cy.wrap(saveTestResults(win, payloadToSend), {timeout: 30000});
}).then(() => {
browserStackLog(`[A11Y] Successfully completed ${currentMode} accessibility scanning and saved results`);
})
} catch (er) {
browserStackLog(`Error in saving results with error: ${er.message}`);
}
})
});
})
Cypress.Commands.add('performScan', () => {
try {
const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest || Cypress.mocha.getRunner().suite.ctx._runnable;
const shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
if (!shouldScanTestForAccessibility) {
browserStackLog(`Not a Accessibility Automation session, cannot perform scan.`);
return cy.wrap({});
}
cy.window().then(async (win) => {
browserStackLog(`Performing accessibility scan`);
cy.wrap(performScan(win), {timeout:30000});
});
} catch(error) {
browserStackLog(`Error in performing scan with error: ${error.message}`);
}
})
Cypress.Commands.add('getAccessibilityResultsSummary', () => {
try {
const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest || Cypress.mocha.getRunner().suite.ctx._runnable;
const shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
if (!shouldScanTestForAccessibility) {
browserStackLog(`Not a Accessibility Automation session, cannot retrieve Accessibility results summary.`);
return cy.wrap({});
}
cy.window().then(async (win) => {
await performScan(win);
browserStackLog('Getting accessibility results summary');
return await getAccessibilityResultsSummary(win);
});
} catch(error) {
browserStackLog(`Error in getting accessibilty results summary with error: ${error.message}`);
}
});
Cypress.Commands.add('getAccessibilityResults', () => {
try {
const attributes = Cypress.mocha.getRunner().suite.ctx.currentTest || Cypress.mocha.getRunner().suite.ctx._runnable;
const shouldScanTestForAccessibility = shouldScanForAccessibility(attributes);
if (!shouldScanTestForAccessibility) {
browserStackLog(`Not a Accessibility Automation session, cannot retrieve Accessibility results.`);
return cy.wrap({});
}
/* browserstack_accessibility_automation_script */
cy.window().then(async (win) => {
await performScan(win);
browserStackLog('Getting accessibility results');
return await getAccessibilityResults(win);
});
} catch(error) {
browserStackLog(`Error in getting accessibilty results with error: ${error.message}`);
}
});
if (!Cypress.Commands.hasOwnProperty('_browserstackSDKQueryAdded')) {
Cypress.Commands.addQuery('performScanSubjectQuery', function (chaining, setTimeout) {
this.set('timeout', setTimeout);
return () => cy.getSubjectFromChain(chaining);
});
Cypress.Commands._browserstackSDKQueryAdded = true;
}