Completed
Push — master ( c02f49...bd7386 )
by Vitaly
33s
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
12
/*  ------------------------------------------------------------------------ */
13
14
class StackTracey extends Array {
15
16
    constructor (input, offset) {
17
18
        super ()
19
20
    /*  Fixes for Safari    */
21
22
        this.constructor = StackTracey
23
        this.__proto__   = StackTracey.prototype
24
25
    /*  new StackTracey ()            */
26
27
        if (!input) {
28
             input = new Error ()
29
             offset = (offset === undefined) ? 1 : offset }
30
31
    /*  new StackTracey (Error)      */
32
33
        if (input instanceof Error) {
34
            input = input[StackTracey.stack] || input.stack || '' }
35
36
    /*  new StackTracey (string)     */
37
38
        if (typeof input === 'string') {
39
            input = StackTracey.rawParse (input).slice (offset).map (StackTracey.extractEntryMetadata) }
40
41
    /*  new StackTracey (array)      */
42
43
        if (Array.isArray (input)) {
44
45
            this.length = input.length
46
            input.forEach ((x, i) => this[i] = x) }
47
    }
48
49
    static extractEntryMetadata (e) { const fileShort = StackTracey.shortenPath (e.file)
50
51
        return O.assign (e, {
52
53
            calleeShort: e.calleeShort || lastOf (e.callee.split ('.')),
54
            fileShort:   fileShort,
55
            fileName:    lastOf (e.file.split ('/')),
56
            thirdParty:  StackTracey.isThirdParty (fileShort) && !e.index
57
        })
58
    }
59
60
    static shortenPath (s) {
61
        return s.replace (isBrowser ? window.location.href : (process.cwd () + '/'), '')
62
                .replace (/^.*\:\/\/?\/?/, '')
63
    }
64
65
    static isThirdParty (shortPath) {
66
        return (shortPath[0] === '~')                          || // webpack-specific heuristic
67
               (shortPath[0] === '/')                          || // external source
68
               (shortPath.indexOf ('node_modules')      === 0) ||
69
               (shortPath.indexOf ('webpack/bootstrap') === 0)
70
    }
71
72
    static rawParse (str) {
73
74
        const lines = (str || '').split ('\n')
75
76
        const entries = lines.map (line => { line = line.trim ()
77
78
            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...
79
80
            if ((planA = line.match (/at (.+) \((.+)\)/)) ||
81
                (planA = line.match (/(.*)@(.*)/))) {
82
83
                callee         =  planA[1]
84
                native         = (planA[2] === 'native')
85
                fileLineColumn = (planA[2].match (/(.*):(.+):(.+)/) || []).slice (1) }
86
87
            else if ((planB = line.match (/^(at\s+)*(.+):([0-9]+):([0-9]+)/) )) {
88
                fileLineColumn = (planB).slice (2) }
89
90
            else {
91
                return undefined }
92
93
            return {
94
                beforeParse: line,
95
                callee:      callee || '',
96
                index:       isBrowser && (fileLineColumn[0] === window.location.href),
97
                native:      native || false,
98
                file:        fileLineColumn[0] || '',
99
                line:        parseInt (fileLineColumn[1] || '', 10) || undefined,
100
                column:      parseInt (fileLineColumn[2] || '', 10) || undefined } })
101
102
        return entries.filter (x => (x !== undefined))
103
    }
104
105
    withSource (i) {
106
        return this[i] && StackTracey.withSource (this[i])
107
    }
108
109
    static withSource (loc) {
110
111
        if (loc.sourceFile || (loc.file && loc.file.indexOf ('<') >= 0)) { // skip things like <anonymous> and stuff that was already fetched
112
            return loc }
113
114
        else {
115
            let resolved = getSource (loc.file).resolve (loc)
116
117
            if (resolved.sourceFile) {
118
                resolved.file = resolved.sourceFile.path
119
                resolved = StackTracey.extractEntryMetadata (resolved)
120
            }
121
122
            if (resolved.sourceLine && resolved.sourceLine.includes ('// @hide')) {
123
                resolved.sourceLine  = resolved.sourceLine.replace  ('// @hide', '')
124
                resolved.hide = true }
125
126
            return O.assign ({ sourceLine: '' }, loc, resolved)
127
        }
128
    }
129
130
    get withSources () {
131
        return new StackTracey (this.map (StackTracey.withSource))
132
    }
133
134
    get mergeRepeatedLines () {
135
        return new StackTracey (
136
            partition (this, e => e.file + e.line).map (
137
                group => {
138
                    return group.items.slice (1).reduce ((memo, entry) => {
139
                        memo.callee      = (memo.callee      || '<anonymous>') + ' → ' + (entry.callee      || '<anonymous>')
140
                        memo.calleeShort = (memo.calleeShort || '<anonymous>') + ' → ' + (entry.calleeShort || '<anonymous>')
141
                        return memo }, O.assign ({}, group.items[0])) }))
142
    }
143
144
    get clean () {
145
        return this.withSources.mergeRepeatedLines.filter ((e, i) => (i === 0) || !(e.thirdParty || e.hide))
146
    }
147
148
    at (i) {
149
        return O.assign ({
150
151
            beforeParse: '',
152
            callee:      '<???>',
153
            index:       false,
154
            native:      false,
155
            file:        '<???>',
156
            line:        0,
157
            column:      0
158
159
        }, this[i])
160
    }
161
162
    static locationsEqual (a, b) {
163
        return (a.file   === b.file) &&
164
               (a.line   === b.line) &&
165
               (a.column === b.column)
166
    }
167
168
    get pretty () {
169
170
        return asTable (this.withSources.map (
171
                            e => [  ('at ' + e.calleeShort.slice (0, 30)),
172
                                    (e.fileShort && (e.fileShort + ':' + e.line)) || '',
173
                                    ((e.sourceLine || '').trim () || '').slice (0, 80)      ]))
174
    }
175
176
    static resetCache () {
177
178
        getSource.resetCache ()
179
    }
180
181
    get asArray () {
182
183
    }
184
}
185
186
/*  Chaining helper for .isThirdParty
187
    ------------------------------------------------------------------------ */
188
189
(() => {
190
191
    const methods = {
192
193
        include (pred) {
194
195
            const f = StackTracey.isThirdParty
196
            O.assign (StackTracey.isThirdParty = (path => f (path) ||  pred (path)), methods)
197
        },
198
199
        except (pred) {
200
201
            const f = StackTracey.isThirdParty
202
            O.assign (StackTracey.isThirdParty = (path => f (path) && !pred (path)), methods)
203
        },
204
    }
205
206
    O.assign (StackTracey.isThirdParty, methods)
207
208
}) ()
209
210
/*  Array methods
211
    ------------------------------------------------------------------------ */
212
213
;['map', 'filter', 'slice', 'concat', 'reverse'].forEach (name => {
214
215
    StackTracey.prototype[name] = function (/*...args */) { // no support for ...args in Node v4 :(
216
        
217
        const arr = Array.from (this)
218
        return new StackTracey (arr[name].apply (arr, arguments))
219
    }
220
})
221
222
/*  A private field that an Error instance can expose
223
    ------------------------------------------------------------------------ */
224
225
StackTracey.stack = (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...
226
227
/*  ------------------------------------------------------------------------ */
228
229
module.exports = StackTracey
230
231
/*  ------------------------------------------------------------------------ */
232
233