-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathsourcemapped-stacktrace.js
292 lines (252 loc) · 8.81 KB
/
sourcemapped-stacktrace.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
/*
* sourcemapped-stacktrace.js
* created by James Salter <[email protected]> (2014)
*
* https://github.com/novocaine/sourcemapped-stacktrace
*
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/*global define */
// note we only include source-map-consumer, not the whole source-map library,
// which includes gear for generating source maps that we don't need
define(['source-map/lib/source-map-consumer'],
function(source_map_consumer) {
var global_mapForUri = {};
/**
* Re-map entries in a stacktrace using sourcemaps if available.
*
* @param {str} stack - The stacktrace from the browser.
* @param {function} done - Callback invoked with the transformed stacktrace
* (an Array of Strings) passed as the first
* argument
* @param {Object} [opts] - Optional options object.
* @param {Function} [opts.filter] - Filter function applied to each stackTrace line.
* Lines which do not pass the filter won't be processesd.
* @param {boolean} [opts.cacheGlobally] - Whether to cache sourcemaps globally across multiple calls.
* @param {boolean} [opts.sync] - Whether to use synchronous ajax to load the sourcemaps.
* @param {string} [opts.traceFormat] - If `error.stack` is formatted according to chrome or
* Firefox's style. Can be either `"chrome"`, `"firefox"`
* or `undefined` (default). If `undefined`, this library
* will guess based on `navigator.userAgent`.
*/
var mapStackTrace = function(stack, done, opts) {
var lines;
var line;
var mapForUri = {};
var rows = {};
var fields;
var uri;
var expected_fields;
var regex;
var skip_lines;
var fetcher = new Fetcher(opts);
var traceFormat = opts && opts.traceFormat;
if (traceFormat !== "chrome" && traceFormat !== "firefox") {
if (traceFormat) {
throw new Error("unknown traceFormat \"" + traceFormat + "\" :(");
} else if (isChromeOrEdge() || isIE11Plus()) {
traceFormat = "chrome";
} else if (isFirefox() || isSafari()) {
traceFormat = "firefox";
} else {
throw new Error("unknown browser :(");
}
}
if (traceFormat === "chrome") {
regex = /^ +at.+\((.*):([0-9]+):([0-9]+)/;
expected_fields = 4;
// (skip first line containing exception message)
skip_lines = 1;
} else {
regex = /@(.*):([0-9]+):([0-9]+)/;
expected_fields = 4;
skip_lines = 0;
}
lines = stack.split("\n").slice(skip_lines);
for (var i=0; i < lines.length; i++) {
line = lines[i];
if ( opts && opts.filter && !opts.filter(line) ) continue;
fields = line.match(regex);
if (fields && fields.length === expected_fields) {
rows[i] = fields;
uri = fields[1];
if (!uri.match(/<anonymous>/)) {
fetcher.fetchScript(uri);
}
}
}
fetcher.sem.whenReady(function() {
var result = processSourceMaps(lines, rows, fetcher.mapForUri, traceFormat);
done(result);
});
};
var isChromeOrEdge = function() {
return navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
};
var isFirefox = function() {
return navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
};
var isSafari = function() {
return navigator.userAgent.toLowerCase().indexOf('safari') > -1;
};
var isIE11Plus = function() {
return document.documentMode && document.documentMode >= 11;
};
var Semaphore = function() {
this.count = 0;
this.pending = [];
};
Semaphore.prototype.incr = function() {
this.count++;
};
Semaphore.prototype.decr = function() {
this.count--;
this.flush();
};
Semaphore.prototype.whenReady = function(fn) {
this.pending.push(fn);
this.flush();
};
Semaphore.prototype.flush = function() {
if (this.count === 0) {
this.pending.forEach(function(fn) { fn(); });
this.pending = [];
}
};
var Fetcher = function(opts) {
this.sem = new Semaphore();
this.sync = opts && opts.sync;
this.mapForUri = opts && opts.cacheGlobally ? global_mapForUri : {};
};
Fetcher.prototype.ajax = function(uri, callback) {
var xhr = createXMLHTTPObject();
var that = this;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback.call(that, xhr, uri);
}
};
xhr.open("GET", uri, !this.sync);
xhr.send();
}
Fetcher.prototype.fetchScript = function(uri) {
if (!(uri in this.mapForUri)) {
this.sem.incr();
this.mapForUri[uri] = null;
} else {
return;
}
this.ajax(uri, this.onScriptLoad);
};
var absUrlRegex = new RegExp('^(?:[a-z]+:)?//', 'i');
Fetcher.prototype.onScriptLoad = function(xhr, uri) {
if (xhr.status === 200 || (uri.slice(0, 7) === "file://" && xhr.status === 0)) {
// find .map in file.
//
// attempt to find it at the very end of the file, but tolerate trailing
// whitespace inserted by some packers.
var match = xhr.responseText.match("//# [s]ourceMappingURL=(.*)[\\s]*$", "m");
if (match && match.length === 2) {
// get the map
var mapUri = match[1];
var embeddedSourceMap = mapUri.match("data:application/json;(charset=[^;]+;)?base64,(.*)");
if (embeddedSourceMap && embeddedSourceMap[2]) {
this.mapForUri[uri] = new source_map_consumer.SourceMapConsumer(atob(embeddedSourceMap[2]));
this.sem.decr();
} else {
if (!absUrlRegex.test(mapUri)) {
// relative url; according to sourcemaps spec is 'source origin'
var origin;
var lastSlash = uri.lastIndexOf('/');
if (lastSlash !== -1) {
origin = uri.slice(0, lastSlash + 1);
mapUri = origin + mapUri;
// note if lastSlash === -1, actual script uri has no slash
// somehow, so no way to use it as a prefix... we give up and try
// as absolute
}
}
this.ajax(mapUri, function(xhr) {
if (xhr.status === 200 || (mapUri.slice(0, 7) === "file://" && xhr.status === 0)) {
this.mapForUri[uri] = new source_map_consumer.SourceMapConsumer(xhr.responseText);
}
this.sem.decr();
});
}
} else {
// no map
this.sem.decr();
}
} else {
// HTTP error fetching uri of the script
this.sem.decr();
}
};
var processSourceMaps = function(lines, rows, mapForUri, traceFormat) {
var result = [];
var map;
var origName = traceFormat === "chrome" ? origNameChrome : origNameFirefox;
for (var i=0; i < lines.length; i++) {
var row = rows[i];
if (row) {
var uri = row[1];
var line = parseInt(row[2], 10);
var column = parseInt(row[3], 10);
map = mapForUri[uri];
if (map) {
// we think we have a map for that uri. call source-map library
var origPos = map.originalPositionFor(
{ line: line, column: column });
result.push(formatOriginalPosition(origPos.source,
origPos.line, origPos.column, origPos.name || origName(lines[i])));
} else {
// we can't find a map for that url, but we parsed the row.
// reformat unchanged line for consistency with the sourcemapped
// lines.
result.push(formatOriginalPosition(uri, line, column, origName(lines[i])));
}
} else {
// we weren't able to parse the row, push back what we were given
result.push(lines[i]);
}
}
return result;
};
function origNameChrome(origLine) {
var match = / +at +([^ ]*).*/.exec(origLine);
return match && match[1];
}
function origNameFirefox(origLine) {
var match = /([^@]*)@.*/.exec(origLine);
return match && match[1];
}
var formatOriginalPosition = function(source, line, column, name) {
// mimic chrome's format
return " at " + (name ? name : "(unknown)") +
" (" + source + ":" + line + ":" + column + ")";
};
// xmlhttprequest boilerplate
var XMLHttpFactories = [
function () {return new XMLHttpRequest();},
function () {return new ActiveXObject("Msxml2.XMLHTTP");},
function () {return new ActiveXObject("Msxml3.XMLHTTP");},
function () {return new ActiveXObject("Microsoft.XMLHTTP");}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
return {
mapStackTrace: mapStackTrace
}
});