mocha 6.1.0 → 6.1.4

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 (61) hide show
  1. package/CHANGELOG.md +1776 -1751
  2. package/LICENSE +22 -22
  3. package/README.md +105 -105
  4. package/bin/_mocha +10 -10
  5. package/bin/mocha +149 -149
  6. package/bin/options.js +10 -10
  7. package/browser-entry.js +191 -191
  8. package/index.js +3 -3
  9. package/lib/browser/growl.js +168 -168
  10. package/lib/browser/progress.js +119 -119
  11. package/lib/browser/template.html +18 -18
  12. package/lib/browser/tty.js +13 -13
  13. package/lib/cli/cli.js +69 -69
  14. package/lib/cli/commands.js +13 -13
  15. package/lib/cli/config.js +101 -101
  16. package/lib/cli/index.js +9 -9
  17. package/lib/cli/init.js +37 -37
  18. package/lib/cli/node-flags.js +86 -86
  19. package/lib/cli/one-and-dones.js +70 -70
  20. package/lib/cli/options.js +347 -347
  21. package/lib/cli/run-helpers.js +337 -337
  22. package/lib/cli/run-option-metadata.js +76 -76
  23. package/lib/cli/run.js +297 -297
  24. package/lib/context.js +101 -101
  25. package/lib/errors.js +141 -141
  26. package/lib/growl.js +136 -136
  27. package/lib/hook.js +46 -46
  28. package/lib/interfaces/bdd.js +118 -118
  29. package/lib/interfaces/common.js +191 -191
  30. package/lib/interfaces/exports.js +60 -60
  31. package/lib/interfaces/index.js +6 -6
  32. package/lib/interfaces/qunit.js +99 -99
  33. package/lib/interfaces/tdd.js +107 -107
  34. package/lib/mocha.js +843 -843
  35. package/lib/mocharc.json +10 -10
  36. package/lib/pending.js +12 -12
  37. package/lib/reporters/base.js +491 -491
  38. package/lib/reporters/doc.js +85 -85
  39. package/lib/reporters/dot.js +81 -81
  40. package/lib/reporters/html.js +390 -390
  41. package/lib/reporters/index.js +19 -19
  42. package/lib/reporters/json-stream.js +90 -90
  43. package/lib/reporters/json.js +135 -135
  44. package/lib/reporters/landing.js +108 -108
  45. package/lib/reporters/list.js +78 -78
  46. package/lib/reporters/markdown.js +112 -112
  47. package/lib/reporters/min.js +52 -52
  48. package/lib/reporters/nyan.js +276 -276
  49. package/lib/reporters/progress.js +104 -104
  50. package/lib/reporters/spec.js +99 -99
  51. package/lib/reporters/tap.js +294 -294
  52. package/lib/reporters/xunit.js +216 -216
  53. package/lib/runnable.js +496 -496
  54. package/lib/runner.js +1049 -1049
  55. package/lib/stats-collector.js +83 -83
  56. package/lib/suite.js +642 -642
  57. package/lib/test.js +51 -51
  58. package/lib/utils.js +897 -897
  59. package/mocha.css +326 -326
  60. package/mocha.js +8170 -8476
  61. package/package.json +630 -628
package/lib/utils.js CHANGED
@@ -1,897 +1,897 @@
1
- 'use strict';
2
-
3
- /**
4
- * Various utility functions used throughout Mocha's codebase.
5
- * @module utils
6
- */
7
-
8
- /**
9
- * Module dependencies.
10
- */
11
-
12
- var fs = require('fs');
13
- var path = require('path');
14
- var util = require('util');
15
- var glob = require('glob');
16
- var he = require('he');
17
- var errors = require('./errors');
18
- var createNoFilesMatchPatternError = errors.createNoFilesMatchPatternError;
19
- var createMissingArgumentError = errors.createMissingArgumentError;
20
-
21
- var assign = (exports.assign = require('object.assign').getPolyfill());
22
-
23
- /**
24
- * Inherit the prototype methods from one constructor into another.
25
- *
26
- * @param {function} ctor - Constructor function which needs to inherit the
27
- * prototype.
28
- * @param {function} superCtor - Constructor function to inherit prototype from.
29
- * @throws {TypeError} if either constructor is null, or if super constructor
30
- * lacks a prototype.
31
- */
32
- exports.inherits = util.inherits;
33
-
34
- /**
35
- * Escape special characters in the given string of html.
36
- *
37
- * @private
38
- * @param {string} html
39
- * @return {string}
40
- */
41
- exports.escape = function(html) {
42
- return he.encode(String(html), {useNamedReferences: false});
43
- };
44
-
45
- /**
46
- * Test if the given obj is type of string.
47
- *
48
- * @private
49
- * @param {Object} obj
50
- * @return {boolean}
51
- */
52
- exports.isString = function(obj) {
53
- return typeof obj === 'string';
54
- };
55
-
56
- /**
57
- * Watch the given `files` for changes
58
- * and invoke `fn(file)` on modification.
59
- *
60
- * @private
61
- * @param {Array} files
62
- * @param {Function} fn
63
- */
64
- exports.watch = function(files, fn) {
65
- var options = {interval: 100};
66
- var debug = require('debug')('mocha:watch');
67
- files.forEach(function(file) {
68
- debug('file %s', file);
69
- fs.watchFile(file, options, function(curr, prev) {
70
- if (prev.mtime < curr.mtime) {
71
- fn(file);
72
- }
73
- });
74
- });
75
- };
76
-
77
- /**
78
- * Predicate to screen `pathname` for further consideration.
79
- *
80
- * @description
81
- * Returns <code>false</code> for pathname referencing:
82
- * <ul>
83
- * <li>'npm' package installation directory
84
- * <li>'git' version control directory
85
- * </ul>
86
- *
87
- * @private
88
- * @param {string} pathname - File or directory name to screen
89
- * @return {boolean} whether pathname should be further considered
90
- * @example
91
- * ['node_modules', 'test.js'].filter(considerFurther); // => ['test.js']
92
- */
93
- function considerFurther(pathname) {
94
- var ignore = ['node_modules', '.git'];
95
-
96
- return !~ignore.indexOf(pathname);
97
- }
98
-
99
- /**
100
- * Lookup files in the given `dir`.
101
- *
102
- * @description
103
- * Filenames are returned in _traversal_ order by the OS/filesystem.
104
- * **Make no assumption that the names will be sorted in any fashion.**
105
- *
106
- * @private
107
- * @param {string} dir
108
- * @param {string[]} [exts=['js']]
109
- * @param {Array} [ret=[]]
110
- * @return {Array}
111
- */
112
- exports.files = function(dir, exts, ret) {
113
- ret = ret || [];
114
- exts = exts || ['js'];
115
-
116
- fs.readdirSync(dir)
117
- .filter(considerFurther)
118
- .forEach(function(dirent) {
119
- var pathname = path.join(dir, dirent);
120
- if (fs.lstatSync(pathname).isDirectory()) {
121
- exports.files(pathname, exts, ret);
122
- } else if (hasMatchingExtname(pathname, exts)) {
123
- ret.push(pathname);
124
- }
125
- });
126
-
127
- return ret;
128
- };
129
-
130
- /**
131
- * Compute a slug from the given `str`.
132
- *
133
- * @private
134
- * @param {string} str
135
- * @return {string}
136
- */
137
- exports.slug = function(str) {
138
- return str
139
- .toLowerCase()
140
- .replace(/ +/g, '-')
141
- .replace(/[^-\w]/g, '');
142
- };
143
-
144
- /**
145
- * Strip the function definition from `str`, and re-indent for pre whitespace.
146
- *
147
- * @param {string} str
148
- * @return {string}
149
- */
150
- exports.clean = function(str) {
151
- str = str
152
- .replace(/\r\n?|[\n\u2028\u2029]/g, '\n')
153
- .replace(/^\uFEFF/, '')
154
- // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content
155
- .replace(
156
- /^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/,
157
- '$1$2$3'
158
- );
159
-
160
- var spaces = str.match(/^\n?( *)/)[1].length;
161
- var tabs = str.match(/^\n?(\t*)/)[1].length;
162
- var re = new RegExp(
163
- '^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}',
164
- 'gm'
165
- );
166
-
167
- str = str.replace(re, '');
168
-
169
- return str.trim();
170
- };
171
-
172
- /**
173
- * Parse the given `qs`.
174
- *
175
- * @private
176
- * @param {string} qs
177
- * @return {Object}
178
- */
179
- exports.parseQuery = function(qs) {
180
- return qs
181
- .replace('?', '')
182
- .split('&')
183
- .reduce(function(obj, pair) {
184
- var i = pair.indexOf('=');
185
- var key = pair.slice(0, i);
186
- var val = pair.slice(++i);
187
-
188
- // Due to how the URLSearchParams API treats spaces
189
- obj[key] = decodeURIComponent(val.replace(/\+/g, '%20'));
190
-
191
- return obj;
192
- }, {});
193
- };
194
-
195
- /**
196
- * Highlight the given string of `js`.
197
- *
198
- * @private
199
- * @param {string} js
200
- * @return {string}
201
- */
202
- function highlight(js) {
203
- return js
204
- .replace(/</g, '&lt;')
205
- .replace(/>/g, '&gt;')
206
- .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
207
- .replace(/('.*?')/gm, '<span class="string">$1</span>')
208
- .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
209
- .replace(/(\d+)/gm, '<span class="number">$1</span>')
210
- .replace(
211
- /\bnew[ \t]+(\w+)/gm,
212
- '<span class="keyword">new</span> <span class="init">$1</span>'
213
- )
214
- .replace(
215
- /\b(function|new|throw|return|var|if|else)\b/gm,
216
- '<span class="keyword">$1</span>'
217
- );
218
- }
219
-
220
- /**
221
- * Highlight the contents of tag `name`.
222
- *
223
- * @private
224
- * @param {string} name
225
- */
226
- exports.highlightTags = function(name) {
227
- var code = document.getElementById('mocha').getElementsByTagName(name);
228
- for (var i = 0, len = code.length; i < len; ++i) {
229
- code[i].innerHTML = highlight(code[i].innerHTML);
230
- }
231
- };
232
-
233
- /**
234
- * If a value could have properties, and has none, this function is called,
235
- * which returns a string representation of the empty value.
236
- *
237
- * Functions w/ no properties return `'[Function]'`
238
- * Arrays w/ length === 0 return `'[]'`
239
- * Objects w/ no properties return `'{}'`
240
- * All else: return result of `value.toString()`
241
- *
242
- * @private
243
- * @param {*} value The value to inspect.
244
- * @param {string} typeHint The type of the value
245
- * @returns {string}
246
- */
247
- function emptyRepresentation(value, typeHint) {
248
- switch (typeHint) {
249
- case 'function':
250
- return '[Function]';
251
- case 'object':
252
- return '{}';
253
- case 'array':
254
- return '[]';
255
- default:
256
- return value.toString();
257
- }
258
- }
259
-
260
- /**
261
- * Takes some variable and asks `Object.prototype.toString()` what it thinks it
262
- * is.
263
- *
264
- * @private
265
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
266
- * @param {*} value The value to test.
267
- * @returns {string} Computed type
268
- * @example
269
- * type({}) // 'object'
270
- * type([]) // 'array'
271
- * type(1) // 'number'
272
- * type(false) // 'boolean'
273
- * type(Infinity) // 'number'
274
- * type(null) // 'null'
275
- * type(new Date()) // 'date'
276
- * type(/foo/) // 'regexp'
277
- * type('type') // 'string'
278
- * type(global) // 'global'
279
- * type(new String('foo') // 'object'
280
- */
281
- var type = (exports.type = function type(value) {
282
- if (value === undefined) {
283
- return 'undefined';
284
- } else if (value === null) {
285
- return 'null';
286
- } else if (Buffer.isBuffer(value)) {
287
- return 'buffer';
288
- }
289
- return Object.prototype.toString
290
- .call(value)
291
- .replace(/^\[.+\s(.+?)]$/, '$1')
292
- .toLowerCase();
293
- });
294
-
295
- /**
296
- * Stringify `value`. Different behavior depending on type of value:
297
- *
298
- * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.
299
- * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.
300
- * - If `value` is an *empty* object, function, or array, return result of function
301
- * {@link emptyRepresentation}.
302
- * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of
303
- * JSON.stringify().
304
- *
305
- * @private
306
- * @see exports.type
307
- * @param {*} value
308
- * @return {string}
309
- */
310
- exports.stringify = function(value) {
311
- var typeHint = type(value);
312
-
313
- if (!~['object', 'array', 'function'].indexOf(typeHint)) {
314
- if (typeHint === 'buffer') {
315
- var json = Buffer.prototype.toJSON.call(value);
316
- // Based on the toJSON result
317
- return jsonStringify(
318
- json.data && json.type ? json.data : json,
319
- 2
320
- ).replace(/,(\n|$)/g, '$1');
321
- }
322
-
323
- // IE7/IE8 has a bizarre String constructor; needs to be coerced
324
- // into an array and back to obj.
325
- if (typeHint === 'string' && typeof value === 'object') {
326
- value = value.split('').reduce(function(acc, char, idx) {
327
- acc[idx] = char;
328
- return acc;
329
- }, {});
330
- typeHint = 'object';
331
- } else {
332
- return jsonStringify(value);
333
- }
334
- }
335
-
336
- for (var prop in value) {
337
- if (Object.prototype.hasOwnProperty.call(value, prop)) {
338
- return jsonStringify(
339
- exports.canonicalize(value, null, typeHint),
340
- 2
341
- ).replace(/,(\n|$)/g, '$1');
342
- }
343
- }
344
-
345
- return emptyRepresentation(value, typeHint);
346
- };
347
-
348
- /**
349
- * like JSON.stringify but more sense.
350
- *
351
- * @private
352
- * @param {Object} object
353
- * @param {number=} spaces
354
- * @param {number=} depth
355
- * @returns {*}
356
- */
357
- function jsonStringify(object, spaces, depth) {
358
- if (typeof spaces === 'undefined') {
359
- // primitive types
360
- return _stringify(object);
361
- }
362
-
363
- depth = depth || 1;
364
- var space = spaces * depth;
365
- var str = Array.isArray(object) ? '[' : '{';
366
- var end = Array.isArray(object) ? ']' : '}';
367
- var length =
368
- typeof object.length === 'number'
369
- ? object.length
370
- : Object.keys(object).length;
371
- // `.repeat()` polyfill
372
- function repeat(s, n) {
373
- return new Array(n).join(s);
374
- }
375
-
376
- function _stringify(val) {
377
- switch (type(val)) {
378
- case 'null':
379
- case 'undefined':
380
- val = '[' + val + ']';
381
- break;
382
- case 'array':
383
- case 'object':
384
- val = jsonStringify(val, spaces, depth + 1);
385
- break;
386
- case 'boolean':
387
- case 'regexp':
388
- case 'symbol':
389
- case 'number':
390
- val =
391
- val === 0 && 1 / val === -Infinity // `-0`
392
- ? '-0'
393
- : val.toString();
394
- break;
395
- case 'date':
396
- var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString();
397
- val = '[Date: ' + sDate + ']';
398
- break;
399
- case 'buffer':
400
- var json = val.toJSON();
401
- // Based on the toJSON result
402
- json = json.data && json.type ? json.data : json;
403
- val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';
404
- break;
405
- default:
406
- val =
407
- val === '[Function]' || val === '[Circular]'
408
- ? val
409
- : JSON.stringify(val); // string
410
- }
411
- return val;
412
- }
413
-
414
- for (var i in object) {
415
- if (!Object.prototype.hasOwnProperty.call(object, i)) {
416
- continue; // not my business
417
- }
418
- --length;
419
- str +=
420
- '\n ' +
421
- repeat(' ', space) +
422
- (Array.isArray(object) ? '' : '"' + i + '": ') + // key
423
- _stringify(object[i]) + // value
424
- (length ? ',' : ''); // comma
425
- }
426
-
427
- return (
428
- str +
429
- // [], {}
430
- (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end)
431
- );
432
- }
433
-
434
- /**
435
- * Return a new Thing that has the keys in sorted order. Recursive.
436
- *
437
- * If the Thing...
438
- * - has already been seen, return string `'[Circular]'`
439
- * - is `undefined`, return string `'[undefined]'`
440
- * - is `null`, return value `null`
441
- * - is some other primitive, return the value
442
- * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method
443
- * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.
444
- * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`
445
- *
446
- * @private
447
- * @see {@link exports.stringify}
448
- * @param {*} value Thing to inspect. May or may not have properties.
449
- * @param {Array} [stack=[]] Stack of seen values
450
- * @param {string} [typeHint] Type hint
451
- * @return {(Object|Array|Function|string|undefined)}
452
- */
453
- exports.canonicalize = function canonicalize(value, stack, typeHint) {
454
- var canonicalizedObj;
455
- /* eslint-disable no-unused-vars */
456
- var prop;
457
- /* eslint-enable no-unused-vars */
458
- typeHint = typeHint || type(value);
459
- function withStack(value, fn) {
460
- stack.push(value);
461
- fn();
462
- stack.pop();
463
- }
464
-
465
- stack = stack || [];
466
-
467
- if (stack.indexOf(value) !== -1) {
468
- return '[Circular]';
469
- }
470
-
471
- switch (typeHint) {
472
- case 'undefined':
473
- case 'buffer':
474
- case 'null':
475
- canonicalizedObj = value;
476
- break;
477
- case 'array':
478
- withStack(value, function() {
479
- canonicalizedObj = value.map(function(item) {
480
- return exports.canonicalize(item, stack);
481
- });
482
- });
483
- break;
484
- case 'function':
485
- /* eslint-disable guard-for-in */
486
- for (prop in value) {
487
- canonicalizedObj = {};
488
- break;
489
- }
490
- /* eslint-enable guard-for-in */
491
- if (!canonicalizedObj) {
492
- canonicalizedObj = emptyRepresentation(value, typeHint);
493
- break;
494
- }
495
- /* falls through */
496
- case 'object':
497
- canonicalizedObj = canonicalizedObj || {};
498
- withStack(value, function() {
499
- Object.keys(value)
500
- .sort()
501
- .forEach(function(key) {
502
- canonicalizedObj[key] = exports.canonicalize(value[key], stack);
503
- });
504
- });
505
- break;
506
- case 'date':
507
- case 'number':
508
- case 'regexp':
509
- case 'boolean':
510
- case 'symbol':
511
- canonicalizedObj = value;
512
- break;
513
- default:
514
- canonicalizedObj = value + '';
515
- }
516
-
517
- return canonicalizedObj;
518
- };
519
-
520
- /**
521
- * Determines if pathname has a matching file extension.
522
- *
523
- * @private
524
- * @param {string} pathname - Pathname to check for match.
525
- * @param {string[]} exts - List of file extensions (sans period).
526
- * @return {boolean} whether file extension matches.
527
- * @example
528
- * hasMatchingExtname('foo.html', ['js', 'css']); // => false
529
- */
530
- function hasMatchingExtname(pathname, exts) {
531
- var suffix = path.extname(pathname).slice(1);
532
- return exts.some(function(element) {
533
- return suffix === element;
534
- });
535
- }
536
-
537
- /**
538
- * Determines if pathname would be a "hidden" file (or directory) on UN*X.
539
- *
540
- * @description
541
- * On UN*X, pathnames beginning with a full stop (aka dot) are hidden during
542
- * typical usage. Dotfiles, plain-text configuration files, are prime examples.
543
- *
544
- * @see {@link http://xahlee.info/UnixResource_dir/writ/unix_origin_of_dot_filename.html|Origin of Dot File Names}
545
- *
546
- * @private
547
- * @param {string} pathname - Pathname to check for match.
548
- * @return {boolean} whether pathname would be considered a hidden file.
549
- * @example
550
- * isHiddenOnUnix('.profile'); // => true
551
- */
552
- function isHiddenOnUnix(pathname) {
553
- return path.basename(pathname)[0] === '.';
554
- }
555
-
556
- /**
557
- * Lookup file names at the given `path`.
558
- *
559
- * @description
560
- * Filenames are returned in _traversal_ order by the OS/filesystem.
561
- * **Make no assumption that the names will be sorted in any fashion.**
562
- *
563
- * @public
564
- * @memberof Mocha.utils
565
- * @todo Fix extension handling
566
- * @param {string} filepath - Base path to start searching from.
567
- * @param {string[]} extensions - File extensions to look for.
568
- * @param {boolean} recursive - Whether to recurse into subdirectories.
569
- * @return {string[]} An array of paths.
570
- * @throws {Error} if no files match pattern.
571
- * @throws {TypeError} if `filepath` is directory and `extensions` not provided.
572
- */
573
- exports.lookupFiles = function lookupFiles(filepath, extensions, recursive) {
574
- var files = [];
575
- var stat;
576
-
577
- if (!fs.existsSync(filepath)) {
578
- if (fs.existsSync(filepath + '.js')) {
579
- filepath += '.js';
580
- } else {
581
- // Handle glob
582
- files = glob.sync(filepath);
583
- if (!files.length) {
584
- throw createNoFilesMatchPatternError(
585
- 'Cannot find any files matching pattern ' + exports.dQuote(filepath),
586
- filepath
587
- );
588
- }
589
- return files;
590
- }
591
- }
592
-
593
- // Handle file
594
- try {
595
- stat = fs.statSync(filepath);
596
- if (stat.isFile()) {
597
- return filepath;
598
- }
599
- } catch (err) {
600
- // ignore error
601
- return;
602
- }
603
-
604
- // Handle directory
605
- fs.readdirSync(filepath).forEach(function(dirent) {
606
- var pathname = path.join(filepath, dirent);
607
- var stat;
608
-
609
- try {
610
- stat = fs.statSync(pathname);
611
- if (stat.isDirectory()) {
612
- if (recursive) {
613
- files = files.concat(lookupFiles(pathname, extensions, recursive));
614
- }
615
- return;
616
- }
617
- } catch (err) {
618
- // ignore error
619
- return;
620
- }
621
- if (!extensions) {
622
- throw createMissingArgumentError(
623
- util.format(
624
- 'Argument %s required when argument %s is a directory',
625
- exports.sQuote('extensions'),
626
- exports.sQuote('filepath')
627
- ),
628
- 'extensions',
629
- 'array'
630
- );
631
- }
632
-
633
- if (
634
- !stat.isFile() ||
635
- !hasMatchingExtname(pathname, extensions) ||
636
- isHiddenOnUnix(pathname)
637
- ) {
638
- return;
639
- }
640
- files.push(pathname);
641
- });
642
-
643
- return files;
644
- };
645
-
646
- /**
647
- * process.emitWarning or a polyfill
648
- * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options
649
- * @ignore
650
- */
651
- function emitWarning(msg, type) {
652
- if (process.emitWarning) {
653
- process.emitWarning(msg, type);
654
- } else {
655
- process.nextTick(function() {
656
- console.warn(type + ': ' + msg);
657
- });
658
- }
659
- }
660
-
661
- /**
662
- * Show a deprecation warning. Each distinct message is only displayed once.
663
- * Ignores empty messages.
664
- *
665
- * @param {string} [msg] - Warning to print
666
- * @private
667
- */
668
- exports.deprecate = function deprecate(msg) {
669
- msg = String(msg);
670
- if (msg && !deprecate.cache[msg]) {
671
- deprecate.cache[msg] = true;
672
- emitWarning(msg, 'DeprecationWarning');
673
- }
674
- };
675
- exports.deprecate.cache = {};
676
-
677
- /**
678
- * Show a generic warning.
679
- * Ignores empty messages.
680
- *
681
- * @param {string} [msg] - Warning to print
682
- * @private
683
- */
684
- exports.warn = function warn(msg) {
685
- if (msg) {
686
- emitWarning(msg);
687
- }
688
- };
689
-
690
- /**
691
- * @summary
692
- * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`)
693
- * @description
694
- * When invoking this function you get a filter function that get the Error.stack as an input,
695
- * and return a prettify output.
696
- * (i.e: strip Mocha and internal node functions from stack trace).
697
- * @returns {Function}
698
- */
699
- exports.stackTraceFilter = function() {
700
- // TODO: Replace with `process.browser`
701
- var is = typeof document === 'undefined' ? {node: true} : {browser: true};
702
- var slash = path.sep;
703
- var cwd;
704
- if (is.node) {
705
- cwd = process.cwd() + slash;
706
- } else {
707
- cwd = (typeof location === 'undefined'
708
- ? window.location
709
- : location
710
- ).href.replace(/\/[^/]*$/, '/');
711
- slash = '/';
712
- }
713
-
714
- function isMochaInternal(line) {
715
- return (
716
- ~line.indexOf('node_modules' + slash + 'mocha' + slash) ||
717
- ~line.indexOf(slash + 'mocha.js')
718
- );
719
- }
720
-
721
- function isNodeInternal(line) {
722
- return (
723
- ~line.indexOf('(timers.js:') ||
724
- ~line.indexOf('(events.js:') ||
725
- ~line.indexOf('(node.js:') ||
726
- ~line.indexOf('(module.js:') ||
727
- ~line.indexOf('GeneratorFunctionPrototype.next (native)') ||
728
- false
729
- );
730
- }
731
-
732
- return function(stack) {
733
- stack = stack.split('\n');
734
-
735
- stack = stack.reduce(function(list, line) {
736
- if (isMochaInternal(line)) {
737
- return list;
738
- }
739
-
740
- if (is.node && isNodeInternal(line)) {
741
- return list;
742
- }
743
-
744
- // Clean up cwd(absolute)
745
- if (/:\d+:\d+\)?$/.test(line)) {
746
- line = line.replace('(' + cwd, '(');
747
- }
748
-
749
- list.push(line);
750
- return list;
751
- }, []);
752
-
753
- return stack.join('\n');
754
- };
755
- };
756
-
757
- /**
758
- * Crude, but effective.
759
- * @public
760
- * @param {*} value
761
- * @returns {boolean} Whether or not `value` is a Promise
762
- */
763
- exports.isPromise = function isPromise(value) {
764
- return (
765
- typeof value === 'object' &&
766
- value !== null &&
767
- typeof value.then === 'function'
768
- );
769
- };
770
-
771
- /**
772
- * Clamps a numeric value to an inclusive range.
773
- *
774
- * @param {number} value - Value to be clamped.
775
- * @param {numer[]} range - Two element array specifying [min, max] range.
776
- * @returns {number} clamped value
777
- */
778
- exports.clamp = function clamp(value, range) {
779
- return Math.min(Math.max(value, range[0]), range[1]);
780
- };
781
-
782
- /**
783
- * Single quote text by combining with undirectional ASCII quotation marks.
784
- *
785
- * @description
786
- * Provides a simple means of markup for quoting text to be used in output.
787
- * Use this to quote names of variables, methods, and packages.
788
- *
789
- * <samp>package 'foo' cannot be found</samp>
790
- *
791
- * @private
792
- * @param {string} str - Value to be quoted.
793
- * @returns {string} quoted value
794
- * @example
795
- * sQuote('n') // => 'n'
796
- */
797
- exports.sQuote = function(str) {
798
- return "'" + str + "'";
799
- };
800
-
801
- /**
802
- * Double quote text by combining with undirectional ASCII quotation marks.
803
- *
804
- * @description
805
- * Provides a simple means of markup for quoting text to be used in output.
806
- * Use this to quote names of datatypes, classes, pathnames, and strings.
807
- *
808
- * <samp>argument 'value' must be "string" or "number"</samp>
809
- *
810
- * @private
811
- * @param {string} str - Value to be quoted.
812
- * @returns {string} quoted value
813
- * @example
814
- * dQuote('number') // => "number"
815
- */
816
- exports.dQuote = function(str) {
817
- return '"' + str + '"';
818
- };
819
-
820
- /**
821
- * Provides simplistic message translation for dealing with plurality.
822
- *
823
- * @description
824
- * Use this to create messages which need to be singular or plural.
825
- * Some languages have several plural forms, so _complete_ message clauses
826
- * are preferable to generating the message on the fly.
827
- *
828
- * @private
829
- * @param {number} n - Non-negative integer
830
- * @param {string} msg1 - Message to be used in English for `n = 1`
831
- * @param {string} msg2 - Message to be used in English for `n = 0, 2, 3, ...`
832
- * @returns {string} message corresponding to value of `n`
833
- * @example
834
- * var sprintf = require('util').format;
835
- * var pkgs = ['one', 'two'];
836
- * var msg = sprintf(
837
- * ngettext(
838
- * pkgs.length,
839
- * 'cannot load package: %s',
840
- * 'cannot load packages: %s'
841
- * ),
842
- * pkgs.map(sQuote).join(', ')
843
- * );
844
- * console.log(msg); // => cannot load packages: 'one', 'two'
845
- */
846
- exports.ngettext = function(n, msg1, msg2) {
847
- if (typeof n === 'number' && n >= 0) {
848
- return n === 1 ? msg1 : msg2;
849
- }
850
- };
851
-
852
- /**
853
- * It's a noop.
854
- * @public
855
- */
856
- exports.noop = function() {};
857
-
858
- /**
859
- * Creates a map-like object.
860
- *
861
- * @description
862
- * A "map" is an object with no prototype, for our purposes. In some cases
863
- * this would be more appropriate than a `Map`, especially if your environment
864
- * doesn't support it. Recommended for use in Mocha's public APIs.
865
- *
866
- * @public
867
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map|MDN:Map}
868
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Custom_and_Null_objects|MDN:Object.create - Custom objects}
869
- * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign|MDN:Object.assign}
870
- * @param {...*} [obj] - Arguments to `Object.assign()`.
871
- * @returns {Object} An object with no prototype, having `...obj` properties
872
- */
873
- exports.createMap = function(obj) {
874
- return assign.apply(
875
- null,
876
- [Object.create(null)].concat(Array.prototype.slice.call(arguments))
877
- );
878
- };
879
-
880
- /**
881
- * Creates a read-only map-like object.
882
- *
883
- * @description
884
- * This differs from {@link module:utils.createMap createMap} only in that
885
- * the argument must be non-empty, because the result is frozen.
886
- *
887
- * @see {@link module:utils.createMap createMap}
888
- * @param {...*} [obj] - Arguments to `Object.assign()`.
889
- * @returns {Object} A frozen object with no prototype, having `...obj` properties
890
- * @throws {TypeError} if argument is not a non-empty object.
891
- */
892
- exports.defineConstants = function(obj) {
893
- if (type(obj) !== 'object' || !Object.keys(obj).length) {
894
- throw new TypeError('Invalid argument; expected a non-empty object');
895
- }
896
- return Object.freeze(exports.createMap(obj));
897
- };
1
+ 'use strict';
2
+
3
+ /**
4
+ * Various utility functions used throughout Mocha's codebase.
5
+ * @module utils
6
+ */
7
+
8
+ /**
9
+ * Module dependencies.
10
+ */
11
+
12
+ var fs = require('fs');
13
+ var path = require('path');
14
+ var util = require('util');
15
+ var glob = require('glob');
16
+ var he = require('he');
17
+ var errors = require('./errors');
18
+ var createNoFilesMatchPatternError = errors.createNoFilesMatchPatternError;
19
+ var createMissingArgumentError = errors.createMissingArgumentError;
20
+
21
+ var assign = (exports.assign = require('object.assign').getPolyfill());
22
+
23
+ /**
24
+ * Inherit the prototype methods from one constructor into another.
25
+ *
26
+ * @param {function} ctor - Constructor function which needs to inherit the
27
+ * prototype.
28
+ * @param {function} superCtor - Constructor function to inherit prototype from.
29
+ * @throws {TypeError} if either constructor is null, or if super constructor
30
+ * lacks a prototype.
31
+ */
32
+ exports.inherits = util.inherits;
33
+
34
+ /**
35
+ * Escape special characters in the given string of html.
36
+ *
37
+ * @private
38
+ * @param {string} html
39
+ * @return {string}
40
+ */
41
+ exports.escape = function(html) {
42
+ return he.encode(String(html), {useNamedReferences: false});
43
+ };
44
+
45
+ /**
46
+ * Test if the given obj is type of string.
47
+ *
48
+ * @private
49
+ * @param {Object} obj
50
+ * @return {boolean}
51
+ */
52
+ exports.isString = function(obj) {
53
+ return typeof obj === 'string';
54
+ };
55
+
56
+ /**
57
+ * Watch the given `files` for changes
58
+ * and invoke `fn(file)` on modification.
59
+ *
60
+ * @private
61
+ * @param {Array} files
62
+ * @param {Function} fn
63
+ */
64
+ exports.watch = function(files, fn) {
65
+ var options = {interval: 100};
66
+ var debug = require('debug')('mocha:watch');
67
+ files.forEach(function(file) {
68
+ debug('file %s', file);
69
+ fs.watchFile(file, options, function(curr, prev) {
70
+ if (prev.mtime < curr.mtime) {
71
+ fn(file);
72
+ }
73
+ });
74
+ });
75
+ };
76
+
77
+ /**
78
+ * Predicate to screen `pathname` for further consideration.
79
+ *
80
+ * @description
81
+ * Returns <code>false</code> for pathname referencing:
82
+ * <ul>
83
+ * <li>'npm' package installation directory
84
+ * <li>'git' version control directory
85
+ * </ul>
86
+ *
87
+ * @private
88
+ * @param {string} pathname - File or directory name to screen
89
+ * @return {boolean} whether pathname should be further considered
90
+ * @example
91
+ * ['node_modules', 'test.js'].filter(considerFurther); // => ['test.js']
92
+ */
93
+ function considerFurther(pathname) {
94
+ var ignore = ['node_modules', '.git'];
95
+
96
+ return !~ignore.indexOf(pathname);
97
+ }
98
+
99
+ /**
100
+ * Lookup files in the given `dir`.
101
+ *
102
+ * @description
103
+ * Filenames are returned in _traversal_ order by the OS/filesystem.
104
+ * **Make no assumption that the names will be sorted in any fashion.**
105
+ *
106
+ * @private
107
+ * @param {string} dir
108
+ * @param {string[]} [exts=['js']]
109
+ * @param {Array} [ret=[]]
110
+ * @return {Array}
111
+ */
112
+ exports.files = function(dir, exts, ret) {
113
+ ret = ret || [];
114
+ exts = exts || ['js'];
115
+
116
+ fs.readdirSync(dir)
117
+ .filter(considerFurther)
118
+ .forEach(function(dirent) {
119
+ var pathname = path.join(dir, dirent);
120
+ if (fs.lstatSync(pathname).isDirectory()) {
121
+ exports.files(pathname, exts, ret);
122
+ } else if (hasMatchingExtname(pathname, exts)) {
123
+ ret.push(pathname);
124
+ }
125
+ });
126
+
127
+ return ret;
128
+ };
129
+
130
+ /**
131
+ * Compute a slug from the given `str`.
132
+ *
133
+ * @private
134
+ * @param {string} str
135
+ * @return {string}
136
+ */
137
+ exports.slug = function(str) {
138
+ return str
139
+ .toLowerCase()
140
+ .replace(/ +/g, '-')
141
+ .replace(/[^-\w]/g, '');
142
+ };
143
+
144
+ /**
145
+ * Strip the function definition from `str`, and re-indent for pre whitespace.
146
+ *
147
+ * @param {string} str
148
+ * @return {string}
149
+ */
150
+ exports.clean = function(str) {
151
+ str = str
152
+ .replace(/\r\n?|[\n\u2028\u2029]/g, '\n')
153
+ .replace(/^\uFEFF/, '')
154
+ // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content
155
+ .replace(
156
+ /^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/,
157
+ '$1$2$3'
158
+ );
159
+
160
+ var spaces = str.match(/^\n?( *)/)[1].length;
161
+ var tabs = str.match(/^\n?(\t*)/)[1].length;
162
+ var re = new RegExp(
163
+ '^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}',
164
+ 'gm'
165
+ );
166
+
167
+ str = str.replace(re, '');
168
+
169
+ return str.trim();
170
+ };
171
+
172
+ /**
173
+ * Parse the given `qs`.
174
+ *
175
+ * @private
176
+ * @param {string} qs
177
+ * @return {Object}
178
+ */
179
+ exports.parseQuery = function(qs) {
180
+ return qs
181
+ .replace('?', '')
182
+ .split('&')
183
+ .reduce(function(obj, pair) {
184
+ var i = pair.indexOf('=');
185
+ var key = pair.slice(0, i);
186
+ var val = pair.slice(++i);
187
+
188
+ // Due to how the URLSearchParams API treats spaces
189
+ obj[key] = decodeURIComponent(val.replace(/\+/g, '%20'));
190
+
191
+ return obj;
192
+ }, {});
193
+ };
194
+
195
+ /**
196
+ * Highlight the given string of `js`.
197
+ *
198
+ * @private
199
+ * @param {string} js
200
+ * @return {string}
201
+ */
202
+ function highlight(js) {
203
+ return js
204
+ .replace(/</g, '&lt;')
205
+ .replace(/>/g, '&gt;')
206
+ .replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
207
+ .replace(/('.*?')/gm, '<span class="string">$1</span>')
208
+ .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
209
+ .replace(/(\d+)/gm, '<span class="number">$1</span>')
210
+ .replace(
211
+ /\bnew[ \t]+(\w+)/gm,
212
+ '<span class="keyword">new</span> <span class="init">$1</span>'
213
+ )
214
+ .replace(
215
+ /\b(function|new|throw|return|var|if|else)\b/gm,
216
+ '<span class="keyword">$1</span>'
217
+ );
218
+ }
219
+
220
+ /**
221
+ * Highlight the contents of tag `name`.
222
+ *
223
+ * @private
224
+ * @param {string} name
225
+ */
226
+ exports.highlightTags = function(name) {
227
+ var code = document.getElementById('mocha').getElementsByTagName(name);
228
+ for (var i = 0, len = code.length; i < len; ++i) {
229
+ code[i].innerHTML = highlight(code[i].innerHTML);
230
+ }
231
+ };
232
+
233
+ /**
234
+ * If a value could have properties, and has none, this function is called,
235
+ * which returns a string representation of the empty value.
236
+ *
237
+ * Functions w/ no properties return `'[Function]'`
238
+ * Arrays w/ length === 0 return `'[]'`
239
+ * Objects w/ no properties return `'{}'`
240
+ * All else: return result of `value.toString()`
241
+ *
242
+ * @private
243
+ * @param {*} value The value to inspect.
244
+ * @param {string} typeHint The type of the value
245
+ * @returns {string}
246
+ */
247
+ function emptyRepresentation(value, typeHint) {
248
+ switch (typeHint) {
249
+ case 'function':
250
+ return '[Function]';
251
+ case 'object':
252
+ return '{}';
253
+ case 'array':
254
+ return '[]';
255
+ default:
256
+ return value.toString();
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Takes some variable and asks `Object.prototype.toString()` what it thinks it
262
+ * is.
263
+ *
264
+ * @private
265
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
266
+ * @param {*} value The value to test.
267
+ * @returns {string} Computed type
268
+ * @example
269
+ * type({}) // 'object'
270
+ * type([]) // 'array'
271
+ * type(1) // 'number'
272
+ * type(false) // 'boolean'
273
+ * type(Infinity) // 'number'
274
+ * type(null) // 'null'
275
+ * type(new Date()) // 'date'
276
+ * type(/foo/) // 'regexp'
277
+ * type('type') // 'string'
278
+ * type(global) // 'global'
279
+ * type(new String('foo') // 'object'
280
+ */
281
+ var type = (exports.type = function type(value) {
282
+ if (value === undefined) {
283
+ return 'undefined';
284
+ } else if (value === null) {
285
+ return 'null';
286
+ } else if (Buffer.isBuffer(value)) {
287
+ return 'buffer';
288
+ }
289
+ return Object.prototype.toString
290
+ .call(value)
291
+ .replace(/^\[.+\s(.+?)]$/, '$1')
292
+ .toLowerCase();
293
+ });
294
+
295
+ /**
296
+ * Stringify `value`. Different behavior depending on type of value:
297
+ *
298
+ * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.
299
+ * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.
300
+ * - If `value` is an *empty* object, function, or array, return result of function
301
+ * {@link emptyRepresentation}.
302
+ * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of
303
+ * JSON.stringify().
304
+ *
305
+ * @private
306
+ * @see exports.type
307
+ * @param {*} value
308
+ * @return {string}
309
+ */
310
+ exports.stringify = function(value) {
311
+ var typeHint = type(value);
312
+
313
+ if (!~['object', 'array', 'function'].indexOf(typeHint)) {
314
+ if (typeHint === 'buffer') {
315
+ var json = Buffer.prototype.toJSON.call(value);
316
+ // Based on the toJSON result
317
+ return jsonStringify(
318
+ json.data && json.type ? json.data : json,
319
+ 2
320
+ ).replace(/,(\n|$)/g, '$1');
321
+ }
322
+
323
+ // IE7/IE8 has a bizarre String constructor; needs to be coerced
324
+ // into an array and back to obj.
325
+ if (typeHint === 'string' && typeof value === 'object') {
326
+ value = value.split('').reduce(function(acc, char, idx) {
327
+ acc[idx] = char;
328
+ return acc;
329
+ }, {});
330
+ typeHint = 'object';
331
+ } else {
332
+ return jsonStringify(value);
333
+ }
334
+ }
335
+
336
+ for (var prop in value) {
337
+ if (Object.prototype.hasOwnProperty.call(value, prop)) {
338
+ return jsonStringify(
339
+ exports.canonicalize(value, null, typeHint),
340
+ 2
341
+ ).replace(/,(\n|$)/g, '$1');
342
+ }
343
+ }
344
+
345
+ return emptyRepresentation(value, typeHint);
346
+ };
347
+
348
+ /**
349
+ * like JSON.stringify but more sense.
350
+ *
351
+ * @private
352
+ * @param {Object} object
353
+ * @param {number=} spaces
354
+ * @param {number=} depth
355
+ * @returns {*}
356
+ */
357
+ function jsonStringify(object, spaces, depth) {
358
+ if (typeof spaces === 'undefined') {
359
+ // primitive types
360
+ return _stringify(object);
361
+ }
362
+
363
+ depth = depth || 1;
364
+ var space = spaces * depth;
365
+ var str = Array.isArray(object) ? '[' : '{';
366
+ var end = Array.isArray(object) ? ']' : '}';
367
+ var length =
368
+ typeof object.length === 'number'
369
+ ? object.length
370
+ : Object.keys(object).length;
371
+ // `.repeat()` polyfill
372
+ function repeat(s, n) {
373
+ return new Array(n).join(s);
374
+ }
375
+
376
+ function _stringify(val) {
377
+ switch (type(val)) {
378
+ case 'null':
379
+ case 'undefined':
380
+ val = '[' + val + ']';
381
+ break;
382
+ case 'array':
383
+ case 'object':
384
+ val = jsonStringify(val, spaces, depth + 1);
385
+ break;
386
+ case 'boolean':
387
+ case 'regexp':
388
+ case 'symbol':
389
+ case 'number':
390
+ val =
391
+ val === 0 && 1 / val === -Infinity // `-0`
392
+ ? '-0'
393
+ : val.toString();
394
+ break;
395
+ case 'date':
396
+ var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString();
397
+ val = '[Date: ' + sDate + ']';
398
+ break;
399
+ case 'buffer':
400
+ var json = val.toJSON();
401
+ // Based on the toJSON result
402
+ json = json.data && json.type ? json.data : json;
403
+ val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';
404
+ break;
405
+ default:
406
+ val =
407
+ val === '[Function]' || val === '[Circular]'
408
+ ? val
409
+ : JSON.stringify(val); // string
410
+ }
411
+ return val;
412
+ }
413
+
414
+ for (var i in object) {
415
+ if (!Object.prototype.hasOwnProperty.call(object, i)) {
416
+ continue; // not my business
417
+ }
418
+ --length;
419
+ str +=
420
+ '\n ' +
421
+ repeat(' ', space) +
422
+ (Array.isArray(object) ? '' : '"' + i + '": ') + // key
423
+ _stringify(object[i]) + // value
424
+ (length ? ',' : ''); // comma
425
+ }
426
+
427
+ return (
428
+ str +
429
+ // [], {}
430
+ (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end)
431
+ );
432
+ }
433
+
434
+ /**
435
+ * Return a new Thing that has the keys in sorted order. Recursive.
436
+ *
437
+ * If the Thing...
438
+ * - has already been seen, return string `'[Circular]'`
439
+ * - is `undefined`, return string `'[undefined]'`
440
+ * - is `null`, return value `null`
441
+ * - is some other primitive, return the value
442
+ * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method
443
+ * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.
444
+ * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`
445
+ *
446
+ * @private
447
+ * @see {@link exports.stringify}
448
+ * @param {*} value Thing to inspect. May or may not have properties.
449
+ * @param {Array} [stack=[]] Stack of seen values
450
+ * @param {string} [typeHint] Type hint
451
+ * @return {(Object|Array|Function|string|undefined)}
452
+ */
453
+ exports.canonicalize = function canonicalize(value, stack, typeHint) {
454
+ var canonicalizedObj;
455
+ /* eslint-disable no-unused-vars */
456
+ var prop;
457
+ /* eslint-enable no-unused-vars */
458
+ typeHint = typeHint || type(value);
459
+ function withStack(value, fn) {
460
+ stack.push(value);
461
+ fn();
462
+ stack.pop();
463
+ }
464
+
465
+ stack = stack || [];
466
+
467
+ if (stack.indexOf(value) !== -1) {
468
+ return '[Circular]';
469
+ }
470
+
471
+ switch (typeHint) {
472
+ case 'undefined':
473
+ case 'buffer':
474
+ case 'null':
475
+ canonicalizedObj = value;
476
+ break;
477
+ case 'array':
478
+ withStack(value, function() {
479
+ canonicalizedObj = value.map(function(item) {
480
+ return exports.canonicalize(item, stack);
481
+ });
482
+ });
483
+ break;
484
+ case 'function':
485
+ /* eslint-disable guard-for-in */
486
+ for (prop in value) {
487
+ canonicalizedObj = {};
488
+ break;
489
+ }
490
+ /* eslint-enable guard-for-in */
491
+ if (!canonicalizedObj) {
492
+ canonicalizedObj = emptyRepresentation(value, typeHint);
493
+ break;
494
+ }
495
+ /* falls through */
496
+ case 'object':
497
+ canonicalizedObj = canonicalizedObj || {};
498
+ withStack(value, function() {
499
+ Object.keys(value)
500
+ .sort()
501
+ .forEach(function(key) {
502
+ canonicalizedObj[key] = exports.canonicalize(value[key], stack);
503
+ });
504
+ });
505
+ break;
506
+ case 'date':
507
+ case 'number':
508
+ case 'regexp':
509
+ case 'boolean':
510
+ case 'symbol':
511
+ canonicalizedObj = value;
512
+ break;
513
+ default:
514
+ canonicalizedObj = value + '';
515
+ }
516
+
517
+ return canonicalizedObj;
518
+ };
519
+
520
+ /**
521
+ * Determines if pathname has a matching file extension.
522
+ *
523
+ * @private
524
+ * @param {string} pathname - Pathname to check for match.
525
+ * @param {string[]} exts - List of file extensions (sans period).
526
+ * @return {boolean} whether file extension matches.
527
+ * @example
528
+ * hasMatchingExtname('foo.html', ['js', 'css']); // => false
529
+ */
530
+ function hasMatchingExtname(pathname, exts) {
531
+ var suffix = path.extname(pathname).slice(1);
532
+ return exts.some(function(element) {
533
+ return suffix === element;
534
+ });
535
+ }
536
+
537
+ /**
538
+ * Determines if pathname would be a "hidden" file (or directory) on UN*X.
539
+ *
540
+ * @description
541
+ * On UN*X, pathnames beginning with a full stop (aka dot) are hidden during
542
+ * typical usage. Dotfiles, plain-text configuration files, are prime examples.
543
+ *
544
+ * @see {@link http://xahlee.info/UnixResource_dir/writ/unix_origin_of_dot_filename.html|Origin of Dot File Names}
545
+ *
546
+ * @private
547
+ * @param {string} pathname - Pathname to check for match.
548
+ * @return {boolean} whether pathname would be considered a hidden file.
549
+ * @example
550
+ * isHiddenOnUnix('.profile'); // => true
551
+ */
552
+ function isHiddenOnUnix(pathname) {
553
+ return path.basename(pathname)[0] === '.';
554
+ }
555
+
556
+ /**
557
+ * Lookup file names at the given `path`.
558
+ *
559
+ * @description
560
+ * Filenames are returned in _traversal_ order by the OS/filesystem.
561
+ * **Make no assumption that the names will be sorted in any fashion.**
562
+ *
563
+ * @public
564
+ * @memberof Mocha.utils
565
+ * @todo Fix extension handling
566
+ * @param {string} filepath - Base path to start searching from.
567
+ * @param {string[]} extensions - File extensions to look for.
568
+ * @param {boolean} recursive - Whether to recurse into subdirectories.
569
+ * @return {string[]} An array of paths.
570
+ * @throws {Error} if no files match pattern.
571
+ * @throws {TypeError} if `filepath` is directory and `extensions` not provided.
572
+ */
573
+ exports.lookupFiles = function lookupFiles(filepath, extensions, recursive) {
574
+ var files = [];
575
+ var stat;
576
+
577
+ if (!fs.existsSync(filepath)) {
578
+ if (fs.existsSync(filepath + '.js')) {
579
+ filepath += '.js';
580
+ } else {
581
+ // Handle glob
582
+ files = glob.sync(filepath);
583
+ if (!files.length) {
584
+ throw createNoFilesMatchPatternError(
585
+ 'Cannot find any files matching pattern ' + exports.dQuote(filepath),
586
+ filepath
587
+ );
588
+ }
589
+ return files;
590
+ }
591
+ }
592
+
593
+ // Handle file
594
+ try {
595
+ stat = fs.statSync(filepath);
596
+ if (stat.isFile()) {
597
+ return filepath;
598
+ }
599
+ } catch (err) {
600
+ // ignore error
601
+ return;
602
+ }
603
+
604
+ // Handle directory
605
+ fs.readdirSync(filepath).forEach(function(dirent) {
606
+ var pathname = path.join(filepath, dirent);
607
+ var stat;
608
+
609
+ try {
610
+ stat = fs.statSync(pathname);
611
+ if (stat.isDirectory()) {
612
+ if (recursive) {
613
+ files = files.concat(lookupFiles(pathname, extensions, recursive));
614
+ }
615
+ return;
616
+ }
617
+ } catch (err) {
618
+ // ignore error
619
+ return;
620
+ }
621
+ if (!extensions) {
622
+ throw createMissingArgumentError(
623
+ util.format(
624
+ 'Argument %s required when argument %s is a directory',
625
+ exports.sQuote('extensions'),
626
+ exports.sQuote('filepath')
627
+ ),
628
+ 'extensions',
629
+ 'array'
630
+ );
631
+ }
632
+
633
+ if (
634
+ !stat.isFile() ||
635
+ !hasMatchingExtname(pathname, extensions) ||
636
+ isHiddenOnUnix(pathname)
637
+ ) {
638
+ return;
639
+ }
640
+ files.push(pathname);
641
+ });
642
+
643
+ return files;
644
+ };
645
+
646
+ /**
647
+ * process.emitWarning or a polyfill
648
+ * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options
649
+ * @ignore
650
+ */
651
+ function emitWarning(msg, type) {
652
+ if (process.emitWarning) {
653
+ process.emitWarning(msg, type);
654
+ } else {
655
+ process.nextTick(function() {
656
+ console.warn(type + ': ' + msg);
657
+ });
658
+ }
659
+ }
660
+
661
+ /**
662
+ * Show a deprecation warning. Each distinct message is only displayed once.
663
+ * Ignores empty messages.
664
+ *
665
+ * @param {string} [msg] - Warning to print
666
+ * @private
667
+ */
668
+ exports.deprecate = function deprecate(msg) {
669
+ msg = String(msg);
670
+ if (msg && !deprecate.cache[msg]) {
671
+ deprecate.cache[msg] = true;
672
+ emitWarning(msg, 'DeprecationWarning');
673
+ }
674
+ };
675
+ exports.deprecate.cache = {};
676
+
677
+ /**
678
+ * Show a generic warning.
679
+ * Ignores empty messages.
680
+ *
681
+ * @param {string} [msg] - Warning to print
682
+ * @private
683
+ */
684
+ exports.warn = function warn(msg) {
685
+ if (msg) {
686
+ emitWarning(msg);
687
+ }
688
+ };
689
+
690
+ /**
691
+ * @summary
692
+ * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`)
693
+ * @description
694
+ * When invoking this function you get a filter function that get the Error.stack as an input,
695
+ * and return a prettify output.
696
+ * (i.e: strip Mocha and internal node functions from stack trace).
697
+ * @returns {Function}
698
+ */
699
+ exports.stackTraceFilter = function() {
700
+ // TODO: Replace with `process.browser`
701
+ var is = typeof document === 'undefined' ? {node: true} : {browser: true};
702
+ var slash = path.sep;
703
+ var cwd;
704
+ if (is.node) {
705
+ cwd = process.cwd() + slash;
706
+ } else {
707
+ cwd = (typeof location === 'undefined'
708
+ ? window.location
709
+ : location
710
+ ).href.replace(/\/[^/]*$/, '/');
711
+ slash = '/';
712
+ }
713
+
714
+ function isMochaInternal(line) {
715
+ return (
716
+ ~line.indexOf('node_modules' + slash + 'mocha' + slash) ||
717
+ ~line.indexOf(slash + 'mocha.js')
718
+ );
719
+ }
720
+
721
+ function isNodeInternal(line) {
722
+ return (
723
+ ~line.indexOf('(timers.js:') ||
724
+ ~line.indexOf('(events.js:') ||
725
+ ~line.indexOf('(node.js:') ||
726
+ ~line.indexOf('(module.js:') ||
727
+ ~line.indexOf('GeneratorFunctionPrototype.next (native)') ||
728
+ false
729
+ );
730
+ }
731
+
732
+ return function(stack) {
733
+ stack = stack.split('\n');
734
+
735
+ stack = stack.reduce(function(list, line) {
736
+ if (isMochaInternal(line)) {
737
+ return list;
738
+ }
739
+
740
+ if (is.node && isNodeInternal(line)) {
741
+ return list;
742
+ }
743
+
744
+ // Clean up cwd(absolute)
745
+ if (/:\d+:\d+\)?$/.test(line)) {
746
+ line = line.replace('(' + cwd, '(');
747
+ }
748
+
749
+ list.push(line);
750
+ return list;
751
+ }, []);
752
+
753
+ return stack.join('\n');
754
+ };
755
+ };
756
+
757
+ /**
758
+ * Crude, but effective.
759
+ * @public
760
+ * @param {*} value
761
+ * @returns {boolean} Whether or not `value` is a Promise
762
+ */
763
+ exports.isPromise = function isPromise(value) {
764
+ return (
765
+ typeof value === 'object' &&
766
+ value !== null &&
767
+ typeof value.then === 'function'
768
+ );
769
+ };
770
+
771
+ /**
772
+ * Clamps a numeric value to an inclusive range.
773
+ *
774
+ * @param {number} value - Value to be clamped.
775
+ * @param {numer[]} range - Two element array specifying [min, max] range.
776
+ * @returns {number} clamped value
777
+ */
778
+ exports.clamp = function clamp(value, range) {
779
+ return Math.min(Math.max(value, range[0]), range[1]);
780
+ };
781
+
782
+ /**
783
+ * Single quote text by combining with undirectional ASCII quotation marks.
784
+ *
785
+ * @description
786
+ * Provides a simple means of markup for quoting text to be used in output.
787
+ * Use this to quote names of variables, methods, and packages.
788
+ *
789
+ * <samp>package 'foo' cannot be found</samp>
790
+ *
791
+ * @private
792
+ * @param {string} str - Value to be quoted.
793
+ * @returns {string} quoted value
794
+ * @example
795
+ * sQuote('n') // => 'n'
796
+ */
797
+ exports.sQuote = function(str) {
798
+ return "'" + str + "'";
799
+ };
800
+
801
+ /**
802
+ * Double quote text by combining with undirectional ASCII quotation marks.
803
+ *
804
+ * @description
805
+ * Provides a simple means of markup for quoting text to be used in output.
806
+ * Use this to quote names of datatypes, classes, pathnames, and strings.
807
+ *
808
+ * <samp>argument 'value' must be "string" or "number"</samp>
809
+ *
810
+ * @private
811
+ * @param {string} str - Value to be quoted.
812
+ * @returns {string} quoted value
813
+ * @example
814
+ * dQuote('number') // => "number"
815
+ */
816
+ exports.dQuote = function(str) {
817
+ return '"' + str + '"';
818
+ };
819
+
820
+ /**
821
+ * Provides simplistic message translation for dealing with plurality.
822
+ *
823
+ * @description
824
+ * Use this to create messages which need to be singular or plural.
825
+ * Some languages have several plural forms, so _complete_ message clauses
826
+ * are preferable to generating the message on the fly.
827
+ *
828
+ * @private
829
+ * @param {number} n - Non-negative integer
830
+ * @param {string} msg1 - Message to be used in English for `n = 1`
831
+ * @param {string} msg2 - Message to be used in English for `n = 0, 2, 3, ...`
832
+ * @returns {string} message corresponding to value of `n`
833
+ * @example
834
+ * var sprintf = require('util').format;
835
+ * var pkgs = ['one', 'two'];
836
+ * var msg = sprintf(
837
+ * ngettext(
838
+ * pkgs.length,
839
+ * 'cannot load package: %s',
840
+ * 'cannot load packages: %s'
841
+ * ),
842
+ * pkgs.map(sQuote).join(', ')
843
+ * );
844
+ * console.log(msg); // => cannot load packages: 'one', 'two'
845
+ */
846
+ exports.ngettext = function(n, msg1, msg2) {
847
+ if (typeof n === 'number' && n >= 0) {
848
+ return n === 1 ? msg1 : msg2;
849
+ }
850
+ };
851
+
852
+ /**
853
+ * It's a noop.
854
+ * @public
855
+ */
856
+ exports.noop = function() {};
857
+
858
+ /**
859
+ * Creates a map-like object.
860
+ *
861
+ * @description
862
+ * A "map" is an object with no prototype, for our purposes. In some cases
863
+ * this would be more appropriate than a `Map`, especially if your environment
864
+ * doesn't support it. Recommended for use in Mocha's public APIs.
865
+ *
866
+ * @public
867
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map|MDN:Map}
868
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Custom_and_Null_objects|MDN:Object.create - Custom objects}
869
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign|MDN:Object.assign}
870
+ * @param {...*} [obj] - Arguments to `Object.assign()`.
871
+ * @returns {Object} An object with no prototype, having `...obj` properties
872
+ */
873
+ exports.createMap = function(obj) {
874
+ return assign.apply(
875
+ null,
876
+ [Object.create(null)].concat(Array.prototype.slice.call(arguments))
877
+ );
878
+ };
879
+
880
+ /**
881
+ * Creates a read-only map-like object.
882
+ *
883
+ * @description
884
+ * This differs from {@link module:utils.createMap createMap} only in that
885
+ * the argument must be non-empty, because the result is frozen.
886
+ *
887
+ * @see {@link module:utils.createMap createMap}
888
+ * @param {...*} [obj] - Arguments to `Object.assign()`.
889
+ * @returns {Object} A frozen object with no prototype, having `...obj` properties
890
+ * @throws {TypeError} if argument is not a non-empty object.
891
+ */
892
+ exports.defineConstants = function(obj) {
893
+ if (type(obj) !== 'object' || !Object.keys(obj).length) {
894
+ throw new TypeError('Invalid argument; expected a non-empty object');
895
+ }
896
+ return Object.freeze(exports.createMap(obj));
897
+ };