Completed
Push — master ( da9a19...ff1544 )
by Vitaly
30s
created

stacktracey.js (3 issues)

1
"use strict";
2
3
/*  ------------------------------------------------------------------------ */
4
5
const O            = Object,
0 ignored issues
show
Comprehensibility Best Practice introduced by
You seem to be aliasing the built-in name Object as O. This makes your code very difficult to follow, consider using the built-in name directly.
Loading history...
6
      isBrowser    = (typeof window !== 'undefined') && (window.window === window) && window.navigator,
7
      lastOf       = x => x[x.length - 1],
8
      getSource    = require ('get-source'),
9
      partition    = require ('./impl/partition'),
10
      asTable      = require ('as-table'),
11
      nixSlashes   = x => x.replace (/\\/g, '/'),
12
      pathRoot     = isBrowser ? window.location.href : (nixSlashes (process.cwd ()) + '/')
13
14
/*  ------------------------------------------------------------------------ */
15
16
class StackTracey extends Array {
17
18
    constructor (input, offset) {
19
        
20
        const originalInput          = input
21
            , isParseableSyntaxError = input && (input instanceof SyntaxError && !isBrowser)
22
        
23
        super ()
24
25
    /*  Fixes for Safari    */
26
27
        this.constructor = StackTracey
28
        this.__proto__   = StackTracey.prototype
29
30
    /*  new StackTracey ()            */
31
32
        if (!input) {
33
             input = new Error ()
34
             offset = (offset === undefined) ? 1 : offset
35
        }
36
37
    /*  new StackTracey (Error)      */
38
39
        if (input instanceof Error) {
40
            input = input[StackTracey.stack] || input.stack || ''
41
        }
42
43
    /*  new StackTracey (string)     */
44
45
        if (typeof input === 'string') {
46
            input = StackTracey.rawParse (input).slice (offset).map (StackTracey.extractEntryMetadata)
47
        }
48
49
    /*  new StackTracey (array)      */
50
51
        if (Array.isArray (input)) {
52
53
            if (isParseableSyntaxError) {
54
                
55
                const rawLines = module.require ('util').inspect (originalInput).split ('\n')
56
                    , fileLine = rawLines[0].match (/^([^:]+):(.+)/)
57
58
                if (fileLine) {
59
                    input.unshift ({
60
                        file: nixSlashes (fileLine[1]),
61
                        line: fileLine[2],
62
                        column: (rawLines[2] || '').indexOf ('^') + 1,
63
                        sourceLine: rawLines[1],
64
                        callee: '(syntax error)',
65
                        syntaxError: true
66
                    })
67
                }
68
            }
69
70
            this.length = input.length
71
            input.forEach ((x, i) => this[i] = x)
72
        }
73
    }
74
75
    static extractEntryMetadata (e) {
76
        
77
        const fileRelative = StackTracey.relativePath (e.file || '')
78
79
        return O.assign (e, {
80
81
            calleeShort:  e.calleeShort || lastOf ((e.callee || '').split ('.')),
82
            fileRelative: fileRelative,
83
            fileShort:    StackTracey.shortenPath (fileRelative),
84
            fileName:     lastOf ((e.file || '').split ('/')),
85
            thirdParty:   StackTracey.isThirdParty (fileRelative) && !e.index
86
        })
87
    }
88
89
    static shortenPath (relativePath) {
90
        return relativePath.replace (/^node_modules\//, '')
91
                           .replace (/^webpack\/bootstrap\//, '')
92
    }
93
94
    static relativePath (fullPath) {
95
        return fullPath.replace (pathRoot, '')
96
                       .replace (/^.*\:\/\/?\/?/, '')
97
    }
98
99
    static isThirdParty (relativePath) {
100
        return (relativePath[0] === '~')                          || // webpack-specific heuristic
101
               (relativePath[0] === '/')                          || // external source
102
               (relativePath.indexOf ('node_modules')      === 0) ||
103
               (relativePath.indexOf ('webpack/bootstrap') === 0)
104
    }
105
106
    static rawParse (str) {
107
108
        const lines = (str || '').split ('\n')
109
110
        const entries = lines.map (line => { line = line.trim ()
111
112
            var callee, fileLineColumn = [], native, planA, planB
0 ignored issues
show
The assignment to variable fileLineColumn seems to be never used. Consider removing it.
Loading history...
113
114
            if ((planA = line.match (/at (.+) \((.+)\)/)) ||
115
                (planA = line.match (/(.*)@(.*)/))) {
116
117
                callee         =  planA[1]
118
                native         = (planA[2] === 'native')
119
                fileLineColumn = (planA[2].match (/(.*):(.+):(.+)/) || []).slice (1) }
120
121
            else if ((planB = line.match (/^(at\s+)*(.+):([0-9]+):([0-9]+)/) )) {
122
                fileLineColumn = (planB).slice (2) }
123
124
            else {
125
                return undefined }
126
127
        /*  Detect things like Array.reduce
128
            TODO: detect more built-in types            */
129
            
130
            if (callee && !fileLineColumn[0]) {
131
                const type = callee.split ('.')[0]
132
                if (type === 'Array') {
133
                    native = true
134
                }
135
            }
136
137
            return {
138
                beforeParse: line,
139
                callee:      callee || '',
140
                index:       isBrowser && (fileLineColumn[0] === window.location.href),
141
                native:      native || false,
142
                file:        nixSlashes (fileLineColumn[0] || ''),
143
                line:        parseInt (fileLineColumn[1] || '', 10) || undefined,
144
                column:      parseInt (fileLineColumn[2] || '', 10) || undefined } })
145
146
        return entries.filter (x => (x !== undefined))
147
    }
148
149
    withSource (i) {
150
        return this[i] && StackTracey.withSource (this[i])
151
    }
152
153
    static withSource (loc) {
154
155
        if (loc.sourceFile || (loc.file && loc.file.indexOf ('<') >= 0)) { // skip things like <anonymous> and stuff that was already fetched
156
            return loc
157
            
158
        } else {
159
160
            let resolved = getSource (loc.file || '').resolve (loc)
161
            
162
            if (!resolved.sourceFile.error) {
163
                resolved.file = nixSlashes (resolved.sourceFile.path)
164
                resolved = StackTracey.extractEntryMetadata (resolved)
165
            }
166
167
            if (!resolved.sourceLine.error && resolved.sourceLine.includes ('// @hide')) {
168
                resolved.sourceLine         = resolved.sourceLine.replace  ('// @hide', '')
169
                resolved.hide               = true
170
            }
171
172
            return O.assign ({ sourceLine: '' }, loc, resolved)
173
        }
174
    }
175
176
    get withSources () {
177
        return new StackTracey (this.map (StackTracey.withSource))
178
    }
179
180
    get mergeRepeatedLines () {
181
        return new StackTracey (
182
            partition (this, e => e.file + e.line).map (
183
                group => {
184
                    return group.items.slice (1).reduce ((memo, entry) => {
185
                        memo.callee      = (memo.callee      || '<anonymous>') + ' → ' + (entry.callee      || '<anonymous>')
186
                        memo.calleeShort = (memo.calleeShort || '<anonymous>') + ' → ' + (entry.calleeShort || '<anonymous>')
187
                        return memo }, O.assign ({}, group.items[0])) }))
188
    }
189
190
    get clean () {
191
        return this.withSources.mergeRepeatedLines.filter ((e, i) => (i === 0) || !(e.thirdParty || e.hide || e.native))
192
    }
193
194
    at (i) {
195
        return O.assign ({
196
197
            beforeParse: '',
198
            callee:      '<???>',
199
            index:       false,
200
            native:      false,
201
            file:        '<???>',
202
            line:        0,
203
            column:      0
204
205
        }, this[i])
206
    }
207
208
    static locationsEqual (a, b) {
209
        return (a.file   === b.file) &&
210
               (a.line   === b.line) &&
211
               (a.column === b.column)
212
    }
213
214
    get pretty () {
215
216
        const trimEnd   = (s, n) => s && ((s.length > n) ? (s.slice (0, n-1) + '…') : s)   
217
        const trimStart = (s, n) => s && ((s.length > n) ? ('…' + s.slice (-(n-1))) : s)
218
219
        return asTable (this.withSources.map (
220
                            e => [
221
                                ('at ' + trimEnd (e.calleeShort, 30)),
222
                                trimStart ((e.fileShort && (e.fileShort + ':' + e.line)) || '', 40),
223
                                trimEnd (((e.sourceLine || '').trim () || ''), 80)
224
                            ]))
225
    }
226
227
    static resetCache () {
228
229
        getSource.resetCache ()
230
    }
231
}
232
233
/*  Chaining helper for .isThirdParty
234
    ------------------------------------------------------------------------ */
235
236
(() => {
237
238
    const methods = {
239
240
        include (pred) {
241
242
            const f = StackTracey.isThirdParty
243
            O.assign (StackTracey.isThirdParty = (path => f (path) ||  pred (path)), methods)
244
        },
245
246
        except (pred) {
247
248
            const f = StackTracey.isThirdParty
249
            O.assign (StackTracey.isThirdParty = (path => f (path) && !pred (path)), methods)
250
        },
251
    }
252
253
    O.assign (StackTracey.isThirdParty, methods)
254
255
}) ()
256
257
/*  Array methods
258
    ------------------------------------------------------------------------ */
259
260
;['map', 'filter', 'slice', 'concat', 'reverse'].forEach (name => {
261
262
    StackTracey.prototype[name] = function (/*...args */) { // no support for ...args in Node v4 :(
263
        
264
        const arr = Array.from (this)
265
        return new StackTracey (arr[name].apply (arr, arguments))
266
    }
267
})
268
269
/*  A private field that an Error instance can expose
270
    ------------------------------------------------------------------------ */
271
272
StackTracey.stack = /* istanbul ignore next */ (typeof Symbol !== 'undefined') ? Symbol.for ('StackTracey') : '__StackTracey'
0 ignored issues
show
The variable Symbol seems to be never declared. If this is a global, consider adding a /** global: Symbol */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
273
274
/*  ------------------------------------------------------------------------ */
275
276
module.exports = StackTracey
277
278
/*  ------------------------------------------------------------------------ */
279
280