beautify-stack.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. 'use strict';
  2. const StackUtils = require('stack-utils');
  3. const cleanStack = require('clean-stack');
  4. const debug = require('debug')('ava');
  5. // Ignore unimportant stack trace lines
  6. let ignoreStackLines = [];
  7. const avaInternals = /\/ava\/(?:lib\/|lib\/worker\/)?[\w-]+\.js:\d+:\d+\)?$/;
  8. const avaDependencies = /\/node_modules\/(?:append-transform|bluebird|empower-core|nyc|require-precompiled|(?:ava\/node_modules\/)?(?:babel-runtime|core-js))\//;
  9. const stackFrameLine = /^.+( \(.+:\d+:\d+\)|:\d+:\d+)$/;
  10. if (!debug.enabled) {
  11. ignoreStackLines = StackUtils.nodeInternals();
  12. ignoreStackLines.push(avaInternals);
  13. ignoreStackLines.push(avaDependencies);
  14. }
  15. const stackUtils = new StackUtils({internals: ignoreStackLines});
  16. function extractFrames(stack) {
  17. return stack
  18. .split('\n')
  19. .map(line => line.trim())
  20. .filter(line => stackFrameLine.test(line))
  21. .join('\n');
  22. }
  23. /**
  24. * Given a string value of the format generated for the `stack` property of a
  25. * V8 error object, return a string that contains only stack frame information
  26. * for frames that have relevance to the consumer.
  27. *
  28. * For example, given the following string value:
  29. *
  30. * ```
  31. * Error
  32. * at inner (/home/ava/ex.js:7:12)
  33. * at /home/ava/ex.js:12:5
  34. * at outer (/home/ava/ex.js:13:4)
  35. * at Object.<anonymous> (/home/ava/ex.js:14:3)
  36. * at Module._compile (module.js:570:32)
  37. * at Object.Module._extensions..js (module.js:579:10)
  38. * at Module.load (module.js:487:32)
  39. * at tryModuleLoad (module.js:446:12)
  40. * at Function.Module._load (module.js:438:3)
  41. * at Module.runMain (module.js:604:10)
  42. * ```
  43. *
  44. * ...this function returns the following string value:
  45. *
  46. * ```
  47. * inner (/home/ava/ex.js:7:12)
  48. * /home/ava/ex.js:12:5
  49. * outer (/home/ava/ex.js:13:4)
  50. * Object.<anonymous> (/home/ava/ex.js:14:3)
  51. * ```
  52. */
  53. module.exports = stack => {
  54. if (!stack) {
  55. return '';
  56. }
  57. stack = extractFrames(stack);
  58. // Workaround for https://github.com/tapjs/stack-utils/issues/14
  59. // TODO: fix it in `stack-utils`
  60. stack = cleanStack(stack);
  61. return stackUtils.clean(stack)
  62. // Remove the trailing newline inserted by the `stack-utils` module
  63. .trim();
  64. };