-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
prepare-stack-trace.ts
232 lines (208 loc) · 6.55 KB
/
prepare-stack-trace.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/* Code borrowed and based on
* https://github.com/evanw/node-source-map-support/blob/master/source-map-support.js
*/
import { readFileSync, readdirSync } from "fs"
import { codeFrameColumns } from "@babel/code-frame"
import stackTrace from "stack-trace"
import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping"
import * as path from "path"
interface INullableMappedPosition {
source: string | null
line: number | null
column: number | null
name: string | null
}
export class ErrorWithCodeFrame extends Error {
codeFrame?: string = ``
constructor(error: Error) {
super(error.message)
// We must use getOwnProperty because keys like `stack` are not enumerable,
// but we want to copy over the entire error
Object.getOwnPropertyNames(error).forEach(key => {
this[key] = error[key]
})
}
}
export function prepareStackTrace(
error: Error,
sourceOfMainMap: string
): ErrorWithCodeFrame {
const newError = new ErrorWithCodeFrame(error)
// source point to single map, but with code splitting for build-html we need to handle more maps
// we use fact that all .map files will be in same dir as main one here
const bundleDir = path.dirname(sourceOfMainMap)
const bundleDirMapFiles = readdirSync(bundleDir)
.filter(fileName => fileName.endsWith(`.js.map`))
.map(fileName => path.join(bundleDir, fileName))
const maps = bundleDirMapFiles.map(
source => new TraceMap(readFileSync(source, `utf8`))
)
const stack = stackTrace
.parse(newError)
.map(frame => wrapCallSite(maps, frame))
.filter(
frame =>
`wasConverted` in frame &&
(!frame.getFileName() ||
!frame
.getFileName()
.match(/^webpack:\/+(lib\/)?(webpack\/|\.cache\/)/))
)
newError.codeFrame = getErrorSource(maps, stack[0])
newError.stack =
`${newError.name}: ${newError.message}\n` +
stack.map(frame => ` at ${frame}`).join(`\n`)
return newError
}
function getErrorSource(
maps: Array<TraceMap>,
topFrame: stackTrace.StackFrame | IWrappedStackFrame
): string {
let source
for (const map of maps) {
// TODO: Re-Add sourceContentFor behavior
source = null // map.sourceContentFor(topFrame.getFileName(), true)
if (source) {
break
}
}
return source
? codeFrameColumns(
source,
{
start: {
line: topFrame.getLineNumber(),
column: topFrame.getColumnNumber(),
},
},
{
highlightCode: true,
}
)
: ``
}
interface IWrappedStackFrame {
getFileName(): string
getLineNumber(): number
getColumnNumber(): number
getScriptNameOrSourceURL(): string
toString: typeof CallSiteToString
wasConverted: true
}
function wrapCallSite(
maps: Array<TraceMap>,
frame: stackTrace.StackFrame
): IWrappedStackFrame | stackTrace.StackFrame {
const source = frame.getFileName()
if (!source) return frame
const position = getPosition({ maps, frame })
if (!position.source) return frame
return {
getFileName: (): string => position.source || ``,
getLineNumber: (): number => position.line || 0,
getColumnNumber: (): number => (position.column || 0) + 1,
getScriptNameOrSourceURL: (): string => position.source || ``,
toString: CallSiteToString,
wasConverted: true,
}
}
function getPosition({
maps,
frame,
}: {
maps: Array<TraceMap>
frame: stackTrace.StackFrame
}): INullableMappedPosition {
if (frame.getFileName().includes(`webpack:`)) {
// if source-map-register is initiated, stack traces would already be converted
return {
column: frame.getColumnNumber() - 1,
line: frame.getLineNumber(),
source: frame
.getFileName()
.slice(frame.getFileName().indexOf(`webpack:`))
.replace(/webpack:\/+/g, `webpack://`),
name: null,
}
}
const line = frame.getLineNumber()
const column = frame.getColumnNumber()
for (const map of maps) {
const test = originalPositionFor(map, { line, column })
if (test.source) {
return test
}
}
return { source: null, column: null, line: null, name: null }
}
// This is copied almost verbatim from the V8 source code at
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js.
function CallSiteToString(): string {
// @ts-ignore
const _this = this // eslint-disable-line @typescript-eslint/no-this-alias
const self = _this as
| NodeJS.CallSite
| IWrappedStackFrame
| stackTrace.StackFrame
let fileName
let fileLocation = ``
if (`isNative` in self && self.isNative()) {
fileLocation = `native`
} else {
fileName =
(`getScriptNameOrSourceURL` in self && self.getScriptNameOrSourceURL()) ||
(`getFileName` in self && self.getFileName())
if (!fileName && `isEval` in self && self.isEval()) {
fileLocation = `${self.getEvalOrigin()}, `
}
if (fileName) {
fileLocation += fileName.replace(/^webpack:\/+(lib\/)?/, ``)
} else {
// Source code does not originate from a file and is not native, but we
// can still get the source position inside the source string, e.g. in
// an eval string.
fileLocation += `<anonymous>`
}
const lineNumber = `getLineNumber` in self ? self.getLineNumber() : null
if (lineNumber != null) {
fileLocation += `:${lineNumber}`
const columnNumber =
`getColumnNumber` in self ? self.getColumnNumber() : null
if (columnNumber) {
fileLocation += `:${columnNumber}`
}
}
}
let line = ``
const functionName = `getFunctionName` in self ? self.getFunctionName() : ``
let addSuffix = true
const isConstructor = `isConstructor` in self && self.isConstructor()
const methodName = `getMethodName` in self ? self.getMethodName() : ``
const typeName = `getTypeName` in self ? self.getTypeName() : ``
const isMethodCall =
methodName &&
!((`isToplevel` in self && self.isToplevel()) || isConstructor)
if (isMethodCall && functionName) {
if (typeName && functionName.indexOf(typeName) != 0) {
line += `${typeName}.`
}
line += functionName
if (
functionName.indexOf(`.` + methodName) !=
functionName.length - (methodName || ``).length - 1
) {
line += ` [as ${methodName}]`
}
} else if (typeName && !functionName) {
line += typeName + `.` + (methodName || `<anonymous>`)
} else if (isConstructor) {
line += `new ` + (functionName || `<anonymous>`)
} else if (functionName) {
line += functionName
} else {
line += fileLocation
addSuffix = false
}
if (addSuffix) line += ` (${fileLocation})`
return line
}