Statistics
| Branch: | Tag: | Revision:

root / ui / static / snf / js / lib / stacktrace.js @ 8d08f18a

History | View | Annotate | Download (12.2 kB)

1
// Domain Public by Eric Wendelin http://eriwen.com/ (2008)
2
//                  Luke Smith http://lucassmith.name/ (2008)
3
//                  Loic Dachary <loic@dachary.org> (2008)
4
//                  Johan Euphrosine <proppy@aminche.com> (2008)
5
//                  Oyvind Sean Kinsey http://kinsey.no/blog (2010)
6
//                  Victor Homyakov <victor-homyakov@users.sourceforge.net> (2010)
7

    
8
/**
9
 * Main function giving a function stack trace with a forced or passed in Error
10
 *
11
 * @cfg {Error} e The error to create a stacktrace from (optional)
12
 * @cfg {Boolean} guess If we should try to resolve the names of anonymous functions
13
 * @return {Array} of Strings with functions, lines, files, and arguments where possible
14
 */
15
function printStackTrace(options) {
16
    options = options || {guess: true};
17
    var ex = options.e || null, guess = !!options.guess;
18
    var p = new printStackTrace.implementation(), result = p.run(ex);
19
    return (guess) ? p.guessAnonymousFunctions(result) : result;
20
}
21

    
22
printStackTrace.implementation = function() {
23
};
24

    
25
printStackTrace.implementation.prototype = {
26
    run: function(ex) {
27
        ex = ex || this.createException();
28
        // Do not use the stored mode: different exceptions in Chrome
29
        // may or may not have arguments or stack
30
        var mode = this.mode(ex);
31
        // Use either the stored mode, or resolve it
32
        //var mode = this._mode || this.mode(ex);
33
        if (mode === 'other') {
34
            return this.other(arguments.callee);
35
        } else {
36
            return this[mode](ex);
37
        }
38
    },
39

    
40
    createException: function() {
41
        try {
42
            this.undef();
43
            return null;
44
        } catch (e) {
45
            return e;
46
        }
47
    },
48

    
49
    /**
50
     * @return {String} mode of operation for the environment in question.
51
     */
52
    mode: function(e) {
53
        if (e['arguments'] && e.stack) {
54
            return (this._mode = 'chrome');
55
        } else if (e.message && typeof window !== 'undefined' && window.opera) {
56
            return (this._mode = e.stacktrace ? 'opera10' : 'opera');
57
        } else if (e.stack) {
58
            return (this._mode = 'firefox');
59
        }
60
        return (this._mode = 'other');
61
    },
62

    
63
    /**
64
     * Given a context, function name, and callback function, overwrite it so that it calls
65
     * printStackTrace() first with a callback and then runs the rest of the body.
66
     *
67
     * @param {Object} context of execution (e.g. window)
68
     * @param {String} functionName to instrument
69
     * @param {Function} function to call with a stack trace on invocation
70
     */
71
    instrumentFunction: function(context, functionName, callback) {
72
        context = context || window;
73
        var original = context[functionName];
74
        context[functionName] = function instrumented() {
75
            callback.call(this, printStackTrace().slice(4));
76
            return context[functionName]._instrumented.apply(this, arguments);
77
        };
78
        context[functionName]._instrumented = original;
79
    },
80

    
81
    /**
82
     * Given a context and function name of a function that has been
83
     * instrumented, revert the function to it's original (non-instrumented)
84
     * state.
85
     *
86
     * @param {Object} context of execution (e.g. window)
87
     * @param {String} functionName to de-instrument
88
     */
89
    deinstrumentFunction: function(context, functionName) {
90
        if (context[functionName].constructor === Function &&
91
                context[functionName]._instrumented &&
92
                context[functionName]._instrumented.constructor === Function) {
93
            context[functionName] = context[functionName]._instrumented;
94
        }
95
    },
96

    
97
    /**
98
     * Given an Error object, return a formatted Array based on Chrome's stack string.
99
     *
100
     * @param e - Error object to inspect
101
     * @return Array<String> of function calls, files and line numbers
102
     */
103
    chrome: function(e) {
104
        var stack = (e.stack + '\n').replace(/^\S[^\(]+?[\n$]/gm, '').
105
          replace(/^\s+at\s+/gm, '').
106
          replace(/^([^\(]+?)([\n$])/gm, '{anonymous}()@$1$2').
107
          replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}()@$1').split('\n');
108
        stack.pop();
109
        return stack;
110
    },
111

    
112
    /**
113
     * Given an Error object, return a formatted Array based on Firefox's stack string.
114
     *
115
     * @param e - Error object to inspect
116
     * @return Array<String> of function calls, files and line numbers
117
     */
118
    firefox: function(e) {
119
        return e.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^\(/gm, '{anonymous}(').split('\n');
120
    },
121

    
122
    /**
123
     * Given an Error object, return a formatted Array based on Opera 10's stacktrace string.
124
     *
125
     * @param e - Error object to inspect
126
     * @return Array<String> of function calls, files and line numbers
127
     */
128
    opera10: function(e) {
129
        var stack = e.stacktrace;
130
        var lines = stack.split('\n'), ANON = '{anonymous}', lineRE = /.*line (\d+), column (\d+) in ((<anonymous function\:?\s*(\S+))|([^\(]+)\([^\)]*\))(?: in )?(.*)\s*$/i, i, j, len;
131
        for (i = 2, j = 0, len = lines.length; i < len - 2; i++) {
132
            if (lineRE.test(lines[i])) {
133
                var location = RegExp.$6 + ':' + RegExp.$1 + ':' + RegExp.$2;
134
                var fnName = RegExp.$3;
135
                fnName = fnName.replace(/<anonymous function\:?\s?(\S+)?>/g, ANON);
136
                lines[j++] = fnName + '@' + location;
137
            }
138
        }
139

    
140
        lines.splice(j, lines.length - j);
141
        return lines;
142
    },
143

    
144
    // Opera 7.x-9.x only!
145
    opera: function(e) {
146
        var lines = e.message.split('\n'), ANON = '{anonymous}', lineRE = /Line\s+(\d+).*script\s+(http\S+)(?:.*in\s+function\s+(\S+))?/i, i, j, len;
147

    
148
        for (i = 4, j = 0, len = lines.length; i < len; i += 2) {
149
            //TODO: RegExp.exec() would probably be cleaner here
150
            if (lineRE.test(lines[i])) {
151
                lines[j++] = (RegExp.$3 ? RegExp.$3 + '()@' + RegExp.$2 + RegExp.$1 : ANON + '()@' + RegExp.$2 + ':' + RegExp.$1) + ' -- ' + lines[i + 1].replace(/^\s+/, '');
152
            }
153
        }
154

    
155
        lines.splice(j, lines.length - j);
156
        return lines;
157
    },
158

    
159
    // Safari, IE, and others
160
    other: function(curr) {
161
        var ANON = '{anonymous}', fnRE = /function\s*([\w\-$]+)?\s*\(/i, stack = [], fn, args, maxStackSize = 10;
162
        while (curr && stack.length < maxStackSize) {
163
            fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON;
164
            args = Array.prototype.slice.call(curr['arguments'] || []);
165
            stack[stack.length] = fn + '(' + this.stringifyArguments(args) + ')';
166
            curr = curr.caller;
167
        }
168
        return stack;
169
    },
170

    
171
    /**
172
     * Given arguments array as a String, subsituting type names for non-string types.
173
     *
174
     * @param {Arguments} object
175
     * @return {Array} of Strings with stringified arguments
176
     */
177
    stringifyArguments: function(args) {
178
        var slice = Array.prototype.slice;
179
        for (var i = 0; i < args.length; ++i) {
180
            var arg = args[i];
181
            if (arg === undefined) {
182
                args[i] = 'undefined';
183
            } else if (arg === null) {
184
                args[i] = 'null';
185
            } else if (arg.constructor) {
186
                if (arg.constructor === Array) {
187
                    if (arg.length < 3) {
188
                        args[i] = '[' + this.stringifyArguments(arg) + ']';
189
                    } else {
190
                        args[i] = '[' + this.stringifyArguments(slice.call(arg, 0, 1)) + '...' + this.stringifyArguments(slice.call(arg, -1)) + ']';
191
                    }
192
                } else if (arg.constructor === Object) {
193
                    args[i] = '#object';
194
                } else if (arg.constructor === Function) {
195
                    args[i] = '#function';
196
                } else if (arg.constructor === String) {
197
                    args[i] = '"' + arg + '"';
198
                }
199
            }
200
        }
201
        return args.join(',');
202
    },
203

    
204
    sourceCache: {},
205

    
206
    /**
207
     * @return the text from a given URL.
208
     */
209
    ajax: function(url) {
210
        var req = this.createXMLHTTPObject();
211
        if (!req) {
212
            return;
213
        }
214
        req.open('GET', url, false);
215
        req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
216
        req.send('');
217
        return req.responseText;
218
    },
219

    
220
    /**
221
     * Try XHR methods in order and store XHR factory.
222
     *
223
     * @return <Function> XHR function or equivalent
224
     */
225
    createXMLHTTPObject: function() {
226
        var xmlhttp, XMLHttpFactories = [
227
            function() {
228
                return new XMLHttpRequest();
229
            }, function() {
230
                return new ActiveXObject('Msxml2.XMLHTTP');
231
            }, function() {
232
                return new ActiveXObject('Msxml3.XMLHTTP');
233
            }, function() {
234
                return new ActiveXObject('Microsoft.XMLHTTP');
235
            }
236
        ];
237
        for (var i = 0; i < XMLHttpFactories.length; i++) {
238
            try {
239
                xmlhttp = XMLHttpFactories[i]();
240
                // Use memoization to cache the factory
241
                this.createXMLHTTPObject = XMLHttpFactories[i];
242
                return xmlhttp;
243
            } catch (e) {
244
            }
245
        }
246
    },
247

    
248
    /**
249
     * Given a URL, check if it is in the same domain (so we can get the source
250
     * via Ajax).
251
     *
252
     * @param url <String> source url
253
     * @return False if we need a cross-domain request
254
     */
255
    isSameDomain: function(url) {
256
        return url.indexOf(location.hostname) !== -1;
257
    },
258

    
259
    /**
260
     * Get source code from given URL if in the same domain.
261
     *
262
     * @param url <String> JS source URL
263
     * @return <Array> Array of source code lines
264
     */
265
    getSource: function(url) {
266
        if (!(url in this.sourceCache)) {
267
            this.sourceCache[url] = this.ajax(url).split('\n');
268
        }
269
        return this.sourceCache[url];
270
    },
271

    
272
    guessAnonymousFunctions: function(stack) {
273
        for (var i = 0; i < stack.length; ++i) {
274
            var reStack = /\{anonymous\}\(.*\)@(\w+:\/\/([\-\w\.\/]+)+(:\d+)?[^:]+):(\d+):?(\d+)?/;
275
            var frame = stack[i], m = reStack.exec(frame);
276
            if (m) {
277
                var file = m[1], lineno = m[4], charno = m[7] || 0; //m[7] is character position in Chrome
278
                if (file && this.isSameDomain(file) && lineno) {
279
                    var functionName = this.guessAnonymousFunction(file, lineno, charno);
280
                    stack[i] = frame.replace('{anonymous}', functionName);
281
                }
282
            }
283
        }
284
        return stack;
285
    },
286

    
287
    guessAnonymousFunction: function(url, lineNo, charNo) {
288
        var ret;
289
        try {
290
            ret = this.findFunctionName(this.getSource(url), lineNo);
291
        } catch (e) {
292
            ret = 'getSource failed with url: ' + url + ', exception: ' + e.toString();
293
        }
294
        return ret;
295
    },
296

    
297
    findFunctionName: function(source, lineNo) {
298
        // FIXME findFunctionName fails for compressed source
299
        // (more than one function on the same line)
300
        // TODO use captured args
301
        // function {name}({args}) m[1]=name m[2]=args
302
        var reFunctionDeclaration = /function\s+([^(]*?)\s*\(([^)]*)\)/;
303
        // {name} = function ({args}) TODO args capture
304
        // /['"]?([0-9A-Za-z_]+)['"]?\s*[:=]\s*function(?:[^(]*)/
305
        var reFunctionExpression = /['"]?([0-9A-Za-z_]+)['"]?\s*[:=]\s*function\b/;
306
        // {name} = eval()
307
        var reFunctionEvaluation = /['"]?([0-9A-Za-z_]+)['"]?\s*[:=]\s*(?:eval|new Function)\b/;
308
        // Walk backwards in the source lines until we find
309
        // the line which matches one of the patterns above
310
        var code = "", line, maxLines = 10, m;
311
        for (var i = 0; i < maxLines; ++i) {
312
            // FIXME lineNo is 1-based, source[] is 0-based
313
            line = source[lineNo - i];
314
            if (line) {
315
                code = line + code;
316
                m = reFunctionExpression.exec(code);
317
                if (m && m[1]) {
318
                    return m[1];
319
                }
320
                m = reFunctionDeclaration.exec(code);
321
                if (m && m[1]) {
322
                    //return m[1] + "(" + (m[2] || "") + ")";
323
                    return m[1];
324
                }
325
                m = reFunctionEvaluation.exec(code);
326
                if (m && m[1]) {
327
                    return m[1];
328
                }
329
            }
330
        }
331
        return '(?)';
332
    }
333
};