get-user-code-frame.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.getUserCodeFrame = getUserCodeFrame;
  6. // We try to load node dependencies
  7. let chalk = null;
  8. let readFileSync = null;
  9. let codeFrameColumns = null;
  10. try {
  11. const nodeRequire = module && module.require;
  12. readFileSync = nodeRequire.call(module, 'fs').readFileSync;
  13. codeFrameColumns = nodeRequire.call(module, '@babel/code-frame').codeFrameColumns;
  14. chalk = nodeRequire.call(module, 'chalk');
  15. } catch {
  16. // We're in a browser environment
  17. }
  18. // frame has the form "at myMethod (location/to/my/file.js:10:2)"
  19. function getCodeFrame(frame) {
  20. const locationStart = frame.indexOf('(') + 1;
  21. const locationEnd = frame.indexOf(')');
  22. const frameLocation = frame.slice(locationStart, locationEnd);
  23. const frameLocationElements = frameLocation.split(':');
  24. const [filename, line, column] = [frameLocationElements[0], parseInt(frameLocationElements[1], 10), parseInt(frameLocationElements[2], 10)];
  25. let rawFileContents = '';
  26. try {
  27. rawFileContents = readFileSync(filename, 'utf-8');
  28. } catch {
  29. return '';
  30. }
  31. const codeFrame = codeFrameColumns(rawFileContents, {
  32. start: {
  33. line,
  34. column
  35. }
  36. }, {
  37. highlightCode: true,
  38. linesBelow: 0
  39. });
  40. return `${chalk.dim(frameLocation)}\n${codeFrame}\n`;
  41. }
  42. function getUserCodeFrame() {
  43. // If we couldn't load dependencies, we can't generate the user trace
  44. /* istanbul ignore next */
  45. if (!readFileSync || !codeFrameColumns) {
  46. return '';
  47. }
  48. const err = new Error();
  49. const firstClientCodeFrame = err.stack.split('\n').slice(1) // Remove first line which has the form "Error: TypeError"
  50. .find(frame => !frame.includes('node_modules/')); // Ignore frames from 3rd party libraries
  51. return getCodeFrame(firstClientCodeFrame);
  52. }