1 | "use strict";
|
2 |
|
3 | const stackTrace = require(`stack-trace`);
|
4 |
|
5 | const {
|
6 | codeFrameColumns
|
7 | } = require(`@babel/code-frame`);
|
8 |
|
9 | const fs = require(`fs-extra`);
|
10 |
|
11 | const path = require(`path`);
|
12 |
|
13 | const chalk = require(`chalk`);
|
14 |
|
15 | const {
|
16 | isNodeInternalModulePath
|
17 | } = require(`gatsby-core-utils`);
|
18 |
|
19 | const gatsbyLocation = path.dirname(require.resolve(`gatsby/package.json`));
|
20 | const reduxThunkLocation = path.dirname(require.resolve(`redux-thunk/package.json`));
|
21 | const reduxLocation = path.dirname(require.resolve(`redux/package.json`));
|
22 |
|
23 | const getNonGatsbyCallSite = () => stackTrace.get().find(callSite => callSite && callSite.getFileName() && !callSite.getFileName().includes(gatsbyLocation) && !callSite.getFileName().includes(reduxLocation) && !callSite.getFileName().includes(reduxThunkLocation) && !isNodeInternalModulePath(callSite.getFileName()));
|
24 |
|
25 | const getNonGatsbyCodeFrame = ({
|
26 | highlightCode = true
|
27 | } = {}) => {
|
28 | const callSite = getNonGatsbyCallSite();
|
29 |
|
30 | if (!callSite) {
|
31 | return null;
|
32 | }
|
33 |
|
34 | const fileName = callSite.getFileName();
|
35 | const line = callSite.getLineNumber();
|
36 | const column = callSite.getColumnNumber();
|
37 | const code = fs.readFileSync(fileName, {
|
38 | encoding: `utf-8`
|
39 | });
|
40 | return {
|
41 | fileName,
|
42 | line,
|
43 | column,
|
44 | codeFrame: codeFrameColumns(code, {
|
45 | start: {
|
46 | line,
|
47 | column
|
48 | }
|
49 | }, {
|
50 | highlightCode
|
51 | })
|
52 | };
|
53 | };
|
54 |
|
55 | const getNonGatsbyCodeFrameFormatted = ({
|
56 | highlightCode = true
|
57 | } = {}) => {
|
58 | const possibleCodeFrame = getNonGatsbyCodeFrame({
|
59 | highlightCode
|
60 | });
|
61 |
|
62 | if (!possibleCodeFrame) {
|
63 | return null;
|
64 | }
|
65 |
|
66 | const {
|
67 | fileName,
|
68 | line,
|
69 | column,
|
70 | codeFrame
|
71 | } = possibleCodeFrame;
|
72 | return `File ${chalk.bold(`${fileName}:${line}:${column}`)}\n${codeFrame}`;
|
73 | };
|
74 |
|
75 | module.exports = {
|
76 | getNonGatsbyCodeFrame,
|
77 | getNonGatsbyCodeFrameFormatted
|
78 | };
|
79 |
|
\ | No newline at end of file |