get-user-code-frame.js 1.8 KB

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