-
-
Notifications
You must be signed in to change notification settings - Fork 28
/
Youch.js
381 lines (340 loc) · 8.67 KB
/
Youch.js
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
'use strict'
/*
* youch
*
* (c) Harminder Virk <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const fs = require('fs')
const path = require('path')
const cookie = require('cookie')
const Mustache = require('mustache')
const { fileURLToPath } = require('url')
const StackTracey = require('stacktracey')
const VIEW_PATH = './error.compiled.mustache'
const viewTemplate = fs.readFileSync(path.join(__dirname, VIEW_PATH), 'utf-8')
class Youch {
constructor (error, request, options = {}) {
this.options = options
this.options.postLines = options.postLines || 5
this.options.preLines = options.preLines || 5
this._filterHeaders = ['cookie', 'connection']
this.error = error
this.request = request
this.links = []
this.showAllFrames = false
}
/**
* Returns the source code for a given file. It unable to
* read file it resolves the promise with a null.
*
* @param {Object} frame
* @return {Promise}
*/
_getFrameSource (frame) {
let path = frame
.file
.replace(/dist\/webpack:\//g, '') // unix
.replace(/dist\\webpack:\\/g, '') // windows
/**
* We ignore the error when "fileURLToPath" is unable to parse
* the path, since returning the frame source is an optional
* thing
*/
try {
path = path.startsWith('file:') ? fileURLToPath(path) : path
} catch {
}
return new Promise((resolve) => {
fs.readFile(path, 'utf-8', (error, contents) => {
if (error) {
resolve(null)
return
}
const lines = contents.split(/\r?\n/)
const lineNumber = frame.line
resolve({
pre: lines.slice(
Math.max(0, lineNumber - (this.options.preLines + 1)),
lineNumber - 1
),
line: lines[lineNumber - 1],
post: lines.slice(lineNumber, lineNumber + this.options.postLines)
})
})
})
}
/**
* Parses the error stack and returns serialized
* frames out of it.
*
* @return {Object}
*/
_parseError () {
return new Promise((resolve, reject) => {
const stack = new StackTracey(this.error)
Promise.all(
stack.items.map(async (frame) => {
if (this._isNode(frame)) {
return Promise.resolve(frame)
}
return this._getFrameSource(frame).then((context) => {
frame.context = context
return frame
})
})
)
.then(resolve)
.catch(reject)
})
}
/**
* Returns the context with code for a given
* frame.
*
* @param {Object}
* @return {Object}
*/
_getContext (frame) {
if (!frame.context) {
return {}
}
return {
start: frame.line - (frame.context.pre || []).length,
pre: frame.context.pre.join('\n'),
line: frame.context.line,
post: frame.context.post.join('\n')
}
}
/**
* Returns classes to be used inside HTML when
* displaying the frames list.
*
* @param {Object}
* @param {Number}
*
* @return {String}
*/
_getDisplayClasses (frame) {
const classes = []
if (!frame.isApp) {
classes.push('native-frame')
}
return classes
}
/**
* Compiles the view using HTML
*
* @param {String}
* @param {Object}
*
* @return {String}
*/
_compileView (view, data) {
return Mustache.render(view, data)
}
/**
* Serializes frame to a usable error object.
*
* @param {Object}
*
* @return {Object}
*/
_serializeFrame (frame) {
return {
file: frame.fileRelative,
filePath: frame.file.startsWith('file:')
? fileURLToPath(frame.file).replaceAll('\\', '/')
: frame.file,
line: frame.line,
callee: frame.callee,
calleeShort: frame.calleeShort,
column: frame.column,
context: this._getContext(frame),
isModule: frame.thirdParty,
isNative: frame.native,
isApp: this._isApp(frame)
}
}
/**
* Returns whether frame belongs to nodejs
* or not.
*
* @return {Boolean} [description]
*/
_isNode (frame) {
if (frame.native) {
return true
}
const filename = frame.file || ''
if (filename.startsWith('node:')) {
return true
}
return false
// return !path.isAbsolute(filename) && filename[0] !== '.'
}
/**
* Returns whether code belongs to the app
* or not.
*
* @return {Boolean} [description]
*/
_isApp (frame) {
return !this._isNode(frame) && !this._isNodeModule(frame)
}
/**
* Returns whether frame belongs to a node_module or
* not
*
* @method _isNodeModule
*
* @param {Object} frame
*
* @return {Boolean}
*
* @private
*/
_isNodeModule (frame) {
return (frame.file || '').indexOf('node_modules/') > -1
}
/**
* Serializes stack to Mustache friendly object to
* be used within the view. Optionally can pass
* a callback to customize the frames output.
*
* @param {Object}
* @param {Function} [callback]
*
* @return {Object}
*/
_serializeData (stack, callback) {
callback = callback || this._serializeFrame.bind(this)
return {
message: this.error.message,
help: this.error.help,
cause: this.error.cause,
name: this.error.name,
status: this.error.status,
frames:
stack instanceof Array === true
? stack.filter((frame) => frame.file).map(callback)
: []
}
}
/**
* Returns a serialized object with important
* information.
*
* @return {Object}
*/
_serializeRequest () {
const headers = []
const cookies = []
if (this.request.headers) {
Object.keys(this.request.headers).forEach((key) => {
if (this._filterHeaders.indexOf(key) > -1) {
return
}
headers.push({
key: key.toUpperCase(),
value: this.request.headers[key]
})
})
if (this.request.headers.cookie) {
const parsedCookies = cookie.parse(this.request.headers.cookie || '')
Object.keys(parsedCookies).forEach((key) => {
cookies.push({ key, value: parsedCookies[key] })
})
}
}
return {
url: this.request.url,
httpVersion: this.request.httpVersion,
method: this.request.method,
connection: this.request.headers ? this.request.headers.connection : null,
headers,
cookies
}
}
/**
* Stores the link `callback` which
* will be processed when rendering
* the HTML view.
*
* @param {Function} callback
*
* @returns {Object}
*/
addLink (callback) {
if (typeof callback === 'function') {
this.links.push(callback)
return this
}
throw new Error('Pass a callback function to "addLink"')
}
/**
* Toggle the state of showing all frames by default
*/
toggleShowAllFrames () {
this.showAllFrames = !this.showAllFrames
return this
}
/**
* Returns error stack as JSON.
*
* @return {Promise}
*/
toJSON () {
return new Promise((resolve, reject) => {
this._parseError()
.then((stack) => {
resolve({
error: this._serializeData(stack)
})
})
.catch(reject)
})
}
/**
* Returns HTML representation of the error stack
* by parsing the stack into frames and getting
* important info out of it.
*
* @return {Promise}
*/
toHTML (templateState) {
return new Promise((resolve, reject) => {
this._parseError()
.then((stack) => {
let foundActiveFrame = false
const data = this._serializeData(stack, (frame, index) => {
const serializedFrame = this._serializeFrame(frame)
const classes = this._getDisplayClasses(serializedFrame)
/**
* Adding active class to first app framework
*/
if (!foundActiveFrame && (serializedFrame.isApp || index + 1 === stack.length)) {
classes.push('active')
foundActiveFrame = true
}
serializedFrame.classes = classes.join(' ')
return serializedFrame
})
if (templateState) {
Object.assign(data, templateState)
}
if (this.request) {
data.request = this._serializeRequest()
}
data.links = this.links.map((renderLink) => renderLink(data))
data.loadFA = !!data.links.find((link) => link.includes('fa-'))
data.showAllFrames = this.showAllFrames
return resolve(this._compileView(viewTemplate, data))
})
.catch(reject)
})
}
}
module.exports = Youch