UNPKG

1.81 kBJavaScriptView Raw
1/** @license MIT License (c) copyright 2010-2014 original author or authors */
2/** @author Brian Cavalier */
3/** @author John Hann */
4
5(function(define) { 'use strict';
6define(function() {
7
8 var parse, captureStack, format;
9
10 if(Error.captureStackTrace) {
11 // Use Error.captureStackTrace if available
12 parse = function(e) {
13 return e && e.stack && e.stack.split('\n');
14 };
15
16 format = formatAsString;
17 captureStack = Error.captureStackTrace;
18
19 } else {
20 // Otherwise, do minimal feature detection to determine
21 // how to capture and format reasonable stacks.
22 parse = function(e) {
23 var stack = e && e.stack && e.stack.split('\n');
24 if(stack && e.message) {
25 stack.unshift(e.message);
26 }
27 return stack;
28 };
29
30 (function() {
31 var e = new Error();
32 if(typeof e.stack !== 'string') {
33 format = formatAsString;
34 captureStack = captureSpiderMonkeyStack;
35 } else {
36 format = formatAsErrorWithStack;
37 captureStack = useStackDirectly;
38 }
39 }());
40 }
41
42 function captureSpiderMonkeyStack(host) {
43 try {
44 throw new Error();
45 } catch(err) {
46 host.stack = err.stack;
47 }
48 }
49
50 function useStackDirectly(host) {
51 host.stack = new Error().stack;
52 }
53
54 function formatAsString(longTrace) {
55 return join(longTrace);
56 }
57
58 function formatAsErrorWithStack(longTrace) {
59 var e = new Error();
60 e.stack = formatAsString(longTrace);
61 return e;
62 }
63
64 // About 5-10x faster than String.prototype.join o_O
65 function join(a) {
66 var sep = false;
67 var s = '';
68 for(var i=0; i< a.length; ++i) {
69 if(sep) {
70 s += '\n' + a[i];
71 } else {
72 s+= a[i];
73 sep = true;
74 }
75 }
76 return s;
77 }
78
79 return {
80 parse: parse,
81 format: format,
82 captureStack: captureStack
83 };
84
85});
86}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));