-
Notifications
You must be signed in to change notification settings - Fork 779
/
audit.js
697 lines (618 loc) · 17.8 KB
/
audit.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
/*global Rule, Check, RuleResult, commons: true */
/*eslint no-unused-vars: 0*/
function getDefaultConfiguration(audit) {
'use strict';
var config;
if (audit) {
config = axe.utils.clone(audit);
// Commons are configured into axe like everything else,
// however because things go funky if we have multiple commons objects
// we're not using the copy of that.
config.commons = audit.commons;
} else {
config = {};
}
config.reporter = config.reporter || null;
config.rules = config.rules || [];
config.checks = config.checks || [];
config.data = { checks: {}, rules: {}, ...config.data };
return config;
}
function unpackToObject(collection, audit, method) {
'use strict';
var i, l;
for (i = 0, l = collection.length; i < l; i++) {
audit[method](collection[i]);
}
}
/**
* Constructor which holds configured rules and information about the document under test
*/
function Audit(audit) {
// defaults
this.brand = 'axe';
this.application = 'axeAPI';
this.tagExclude = ['experimental'];
this.defaultConfig = audit;
this._init();
// A copy of the "default" locale. This will be set if the user
// provides a new locale to `axe.configure()` and used to undo
// changes in `axe.reset()`.
this._defaultLocale = null;
}
/**
* Build and set the previous locale. Will noop if a previous
* locale was already set, as we want the ability to "reset"
* to the default ("first") configuration.
*/
Audit.prototype._setDefaultLocale = function() {
if (this._defaultLocale) {
return;
}
const locale = {
checks: {},
rules: {}
};
// XXX: unable to use `for-of` here, as doing so would
// require us to polyfill `Symbol`.
const checkIDs = Object.keys(this.data.checks);
for (let i = 0; i < checkIDs.length; i++) {
const id = checkIDs[i];
const check = this.data.checks[id];
const { pass, fail, incomplete } = check.messages;
locale.checks[id] = {
pass,
fail,
incomplete
};
}
const ruleIDs = Object.keys(this.data.rules);
for (let i = 0; i < ruleIDs.length; i++) {
const id = ruleIDs[i];
const rule = this.data.rules[id];
const { description, help } = rule;
locale.rules[id] = { description, help };
}
this._defaultLocale = locale;
};
/**
* Reset the locale to the "default".
*/
Audit.prototype._resetLocale = function() {
// If the default locale has not already been set, we can exit early.
const defaultLocale = this._defaultLocale;
if (!defaultLocale) {
return;
}
// Apply the default locale
this.applyLocale(defaultLocale);
};
/**
* Merge two check locales (a, b), favoring `b`.
*
* Both locale `a` and the returned shape resemble:
*
* {
* impact: string,
* messages: {
* pass: string | function,
* fail: string | function,
* incomplete: string | {
* [key: string]: string | function
* }
* }
* }
*
* Locale `b` follows the `axe.CheckLocale` shape and resembles:
*
* {
* pass: string,
* fail: string,
* incomplete: string | { [key: string]: string }
* }
*/
const mergeCheckLocale = (a, b) => {
let { pass, fail } = b;
// If the message(s) are Strings, they have not yet been run
// thru doT (which will return a Function).
if (typeof pass === 'string') {
pass = axe.imports.doT.compile(pass);
}
if (typeof fail === 'string') {
fail = axe.imports.doT.compile(fail);
}
return {
...a,
messages: {
pass: pass || a.messages.pass,
fail: fail || a.messages.fail,
incomplete:
typeof a.messages.incomplete === 'object'
? // TODO: for compleness-sake, we should be running
// incomplete messages thru doT as well. This was
// out-of-scope for runtime localization, but should
// eventually be addressed.
{ ...a.messages.incomplete, ...b.incomplete }
: b.incomplete
}
};
};
/**
* Merge two rule locales (a, b), favoring `b`.
*/
const mergeRuleLocale = (a, b) => {
let { help, description } = b;
// If the message(s) are Strings, they have not yet been run
// thru doT (which will return a Function).
if (typeof help === 'string') {
help = axe.imports.doT.compile(help);
}
if (typeof description === 'string') {
description = axe.imports.doT.compile(description);
}
return {
...a,
help: help || a.help,
description: description || a.description
};
};
/**
* Apply locale for the given `checks`.
*/
Audit.prototype._applyCheckLocale = function(checks) {
const keys = Object.keys(checks);
for (let i = 0; i < keys.length; i++) {
const id = keys[i];
if (!this.data.checks[id]) {
throw new Error(`Locale provided for unknown check: "${id}"`);
}
this.data.checks[id] = mergeCheckLocale(this.data.checks[id], checks[id]);
}
};
/**
* Apply locale for the given `rules`.
*/
Audit.prototype._applyRuleLocale = function(rules) {
const keys = Object.keys(rules);
for (let i = 0; i < keys.length; i++) {
const id = keys[i];
if (!this.data.rules[id]) {
throw new Error(`Locale provided for unknown rule: "${id}"`);
}
this.data.rules[id] = mergeRuleLocale(this.data.rules[id], rules[id]);
}
};
/**
* Apply the given `locale`.
*
* @param {axe.Locale}
*/
Audit.prototype.applyLocale = function(locale) {
this._setDefaultLocale();
if (locale.checks) {
this._applyCheckLocale(locale.checks);
}
if (locale.rules) {
this._applyRuleLocale(locale.rules);
}
};
/**
* Initializes the rules and checks
*/
Audit.prototype._init = function() {
var audit = getDefaultConfiguration(this.defaultConfig);
axe.commons = commons = audit.commons;
this.reporter = audit.reporter;
this.commands = {};
this.rules = [];
this.checks = {};
unpackToObject(audit.rules, this, 'addRule');
unpackToObject(audit.checks, this, 'addCheck');
this.data = {};
this.data.checks = (audit.data && audit.data.checks) || {};
this.data.rules = (audit.data && audit.data.rules) || {};
this.data.failureSummaries =
(audit.data && audit.data.failureSummaries) || {};
this.data.incompleteFallbackMessage =
(audit.data && audit.data.incompleteFallbackMessage) || '';
this._constructHelpUrls(); // create default helpUrls
};
/**
* Adds a new command to the audit
*/
Audit.prototype.registerCommand = function(command) {
'use strict';
this.commands[command.id] = command.callback;
};
/**
* Adds a new rule to the Audit. If a rule with specified ID already exists, it will be overridden
* @param {Object} spec Rule specification object
*/
Audit.prototype.addRule = function(spec) {
'use strict';
if (spec.metadata) {
this.data.rules[spec.id] = spec.metadata;
}
let rule = this.getRule(spec.id);
if (rule) {
rule.configure(spec);
} else {
this.rules.push(new Rule(spec, this));
}
};
/**
* Adds a new check to the Audit. If a Check with specified ID already exists, it will be
* reconfigured
*
* @param {Object} spec Check specification object
*/
Audit.prototype.addCheck = function(spec) {
/*eslint no-eval: 0 */
'use strict';
let metadata = spec.metadata;
if (typeof metadata === 'object') {
this.data.checks[spec.id] = metadata;
// Transform messages into functions:
if (typeof metadata.messages === 'object') {
Object.keys(metadata.messages)
.filter(
prop =>
metadata.messages.hasOwnProperty(prop) &&
typeof metadata.messages[prop] === 'string'
)
.forEach(prop => {
if (metadata.messages[prop].indexOf('function') === 0) {
metadata.messages[prop] = new Function(
'return ' + metadata.messages[prop] + ';'
)();
}
});
}
}
if (this.checks[spec.id]) {
this.checks[spec.id].configure(spec);
} else {
this.checks[spec.id] = new Check(spec);
}
};
/**
* Splits a given array of rules to two, with rules that can be run immediately and one's that are dependent on preloadedAssets
* @method getRulesToRun
* @param {Array<Object>} rules complete list of rules
* @param {Object} context
* @param {Object} options
* @return {Object} out, an object containing two arrays, one being list of rules to run now and list of rules to run later
* @private
*/
function getRulesToRun(rules, context, options) {
// entry object for reduce function below
const base = {
now: [],
later: []
};
// iterate through rules and separate out rules that need to be run now vs later
const splitRules = rules.reduce((out, rule) => {
// ensure rule can run
if (!axe.utils.ruleShouldRun(rule, context, options)) {
return out;
}
// does rule require preload assets - push to later array
if (rule.preload) {
out.later.push(rule);
return out;
}
// default to now array
out.now.push(rule);
// return
return out;
}, base);
// return
return splitRules;
}
/**
* Convenience method, that consturcts a rule `run` function that can be deferred
* @param {Object} rule rule to be deferred
* @param {Object} context context object essential to be passed into rule `run`
* @param {Object} options normalised options to be passed into rule `run`
* @param {Object} assets (optional) preloaded assets to be passed into rule and checks (if the rule is preload dependent)
* @return {Function} a deferrable function for rule
*/
function getDefferedRule(rule, context, options) {
// init performance timer of requested via options
let markStart;
let markEnd;
if (options.performanceTimer) {
markStart = 'mark_rule_start_' + rule.id;
markEnd = 'mark_rule_end_' + rule.id;
// mark start
axe.utils.performanceTimer.mark(markStart);
}
return (resolve, reject) => {
// invoke `rule.run`
rule.run(
context,
options,
// resolve callback for rule `run`
ruleResult => {
// if performance timer - mark end & measure
if (options.performanceTimer) {
axe.utils.performanceTimer.mark(markEnd);
axe.utils.performanceTimer.measure(
'rule_' + rule.id,
markStart,
markEnd
);
}
// resolve
resolve(ruleResult);
},
// reject callback for rule `run`
err => {
// if debug - construct error details
if (!options.debug) {
const errResult = Object.assign(new RuleResult(rule), {
result: axe.constants.CANTTELL,
description: 'An error occured while running this rule',
message: err.message,
stack: err.stack,
error: err
});
// resolve
resolve(errResult);
} else {
// reject
reject(err);
}
}
);
};
}
/**
* Runs the Audit; which in turn should call `run` on each rule.
* @async
* @param {Context} context The scope definition/context for analysis (include/exclude)
* @param {Object} options Options object to pass into rules and/or disable rules or checks
* @param {Function} fn Callback function to fire when audit is complete
*/
Audit.prototype.run = function(context, options, resolve, reject) {
'use strict';
this.normalizeOptions(options);
axe._selectCache = [];
// get a list of rules to run NOW vs. LATER (later are preload assets dependent rules)
const allRulesToRun = getRulesToRun(this.rules, context, options);
const runNowRules = allRulesToRun.now;
const runLaterRules = allRulesToRun.later;
// init a NOW queue for rules to run immediately
const nowRulesQueue = axe.utils.queue();
// construct can run NOW rules into NOW queue
runNowRules.forEach(rule => {
nowRulesQueue.defer(getDefferedRule(rule, context, options));
});
// init a PRELOADER queue to start preloading assets
const preloaderQueue = axe.utils.queue();
// defer preload if preload dependent rules exist
if (runLaterRules.length) {
preloaderQueue.defer((res, rej) => {
// handle both success and fail of preload
// and resolve, to allow to run all checks
axe.utils
.preload(options)
.then(preloadResults => {
// pluck first item in results (because it is a queue - meh!) and resolve
const assets = preloadResults[0];
res(assets);
})
.catch(err => {
// resolve as undefined, to allow rule.run to continue
console.warn(`Couldn't load preload assets: `, err);
const assets = undefined;
res(assets);
});
});
}
// defer now and preload queue to run immediately
const queueForNowRulesAndPreloader = axe.utils.queue();
queueForNowRulesAndPreloader.defer(nowRulesQueue);
queueForNowRulesAndPreloader.defer(preloaderQueue);
// invoke the now queue
queueForNowRulesAndPreloader
.then(nowRulesAndPreloaderResults => {
// interpolate results into separate variables
const assetsFromQueue = nowRulesAndPreloaderResults.pop();
if (assetsFromQueue && assetsFromQueue.length) {
// result is a queue (again), hence the index resolution
// assets is either an object of key value pairs of asset type and values
// eg: cssom: [stylesheets]
// or undefined if preload failed
const assets = assetsFromQueue[0];
// extend context with preloaded assets
if (assets) {
context = {
...context,
...assets
};
}
}
// the reminder of the results are RuleResults
const nowRulesResults = nowRulesAndPreloaderResults[0];
// if there are no rules to run LATER - resolve with rule results
if (!runLaterRules.length) {
// remove the cache
axe._selectCache = undefined;
// resolve
resolve(nowRulesResults.filter(result => !!result));
return;
}
// init a LATER queue for rules that are dependant on preloaded assets
const laterRulesQueue = axe.utils.queue();
runLaterRules.forEach(rule => {
const deferredRule = getDefferedRule(rule, context, options);
laterRulesQueue.defer(deferredRule);
});
// invoke the later queue
laterRulesQueue
.then(laterRuleResults => {
// remove the cache
axe._selectCache = undefined;
// resolve
resolve(
nowRulesResults.concat(laterRuleResults).filter(result => !!result)
);
})
.catch(reject);
})
.catch(reject);
};
/**
* Runs Rule `after` post processing functions
* @param {Array} results Array of RuleResults to postprocess
* @param {Mixed} options Options object to pass into rules and/or disable rules or checks
*/
Audit.prototype.after = function(results, options) {
'use strict';
var rules = this.rules;
return results.map(function(ruleResult) {
var rule = axe.utils.findBy(rules, 'id', ruleResult.id);
if (!rule) {
// If you see this, you're probably running the Mocha tests with the aXe extension installed
throw new Error(
'Result for unknown rule. You may be running mismatch aXe-core versions'
);
}
return rule.after(ruleResult, options);
});
};
/**
* Get the rule with a given ID
* @param {string}
* @return {Rule}
*/
Audit.prototype.getRule = function(ruleId) {
return this.rules.find(rule => rule.id === ruleId);
};
/**
* Ensure all rules that are expected to run exist
* @throws {Error} If any tag or rule specified in options is unknown
* @param {Object} options Options object
* @return {Object} Validated options object
*/
Audit.prototype.normalizeOptions = function(options) {
/* eslint max-statements: ["error", 22] */
'use strict';
var audit = this;
// Validate runOnly
if (typeof options.runOnly === 'object') {
if (Array.isArray(options.runOnly)) {
options.runOnly = {
type: 'tag',
values: options.runOnly
};
}
const only = options.runOnly;
if (only.value && !only.values) {
only.values = only.value;
delete only.value;
}
if (!Array.isArray(only.values) || only.values.length === 0) {
throw new Error('runOnly.values must be a non-empty array');
}
// Check if every value in options.runOnly is a known rule ID
if (['rule', 'rules'].includes(only.type)) {
only.type = 'rule';
only.values.forEach(function(ruleId) {
if (!audit.getRule(ruleId)) {
throw new Error('unknown rule `' + ruleId + '` in options.runOnly');
}
});
// Validate 'tags' (e.g. anything not 'rule')
} else if (['tag', 'tags', undefined].includes(only.type)) {
only.type = 'tag';
const unmatchedTags = audit.rules.reduce((unmatchedTags, rule) => {
return unmatchedTags.length
? unmatchedTags.filter(tag => !rule.tags.includes(tag))
: unmatchedTags;
}, only.values);
if (unmatchedTags.length !== 0) {
throw new Error(
'Could not find tags `' + unmatchedTags.join('`, `') + '`'
);
}
} else {
throw new Error(`Unknown runOnly type '${only.type}'`);
}
}
if (typeof options.rules === 'object') {
Object.keys(options.rules).forEach(function(ruleId) {
if (!audit.getRule(ruleId)) {
throw new Error('unknown rule `' + ruleId + '` in options.rules');
}
});
}
return options;
};
/*
* Updates the default options and then applies them
* @param {Mixed} options Options object
*/
Audit.prototype.setBranding = function(branding) {
'use strict';
let previous = {
brand: this.brand,
application: this.application
};
if (
branding &&
branding.hasOwnProperty('brand') &&
branding.brand &&
typeof branding.brand === 'string'
) {
this.brand = branding.brand;
}
if (
branding &&
branding.hasOwnProperty('application') &&
branding.application &&
typeof branding.application === 'string'
) {
this.application = branding.application;
}
this._constructHelpUrls(previous);
};
/**
* For all the rules, create the helpUrl and add it to the data for that rule
*/
function getHelpUrl({ brand, application }, ruleId, version) {
return (
axe.constants.helpUrlBase +
brand +
'/' +
(version || axe.version.substring(0, axe.version.lastIndexOf('.'))) +
'/' +
ruleId +
'?application=' +
application
);
}
Audit.prototype._constructHelpUrls = function(previous = null) {
var version = (axe.version.match(/^[1-9][0-9]*\.[0-9]+/) || ['x.y'])[0];
this.rules.forEach(rule => {
if (!this.data.rules[rule.id]) {
this.data.rules[rule.id] = {};
}
let metaData = this.data.rules[rule.id];
if (
typeof metaData.helpUrl !== 'string' ||
(previous && metaData.helpUrl === getHelpUrl(previous, rule.id, version))
) {
metaData.helpUrl = getHelpUrl(this, rule.id, version);
}
});
};
/**
* Reset the default rules, checks and meta data
*/
Audit.prototype.resetRulesAndChecks = function() {
'use strict';
this._init();
this._resetLocale();
};