Skip to content

Commit 7e250f9

Browse files
committed
Prefer the last //# sourceMappingURL in a file instead of the first
It seems like some Webpack setups (including mine) end up outputting several //# sourceMappingURL=... entries when both transpilation and bundling is in the picture. In general it seems like the safest bet to go for the last one, as most tools tend to append the comment to the end of the file. Thus the last one is most likely to pertain to the last operation that happened, be it transpilation, bundling, or uglification :)
1 parent 64ca313 commit 7e250f9

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

spec/stacktrace-gps-spec.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,21 @@ describe('StackTraceGPS', function() {
327327
}
328328
});
329329

330+
it('ignores all but the last sourceMappingURL in the file', function (done) {
331+
var source = 'var foo=function(){};\n//# sourceMappingURL=ignoreme.js.map\nfunction bar(){}var baz=eval("XXX");\n//@ sourceMappingURL=test.js.map';
332+
jasmine.Ajax.stubRequest('http://localhost:9999/test.min.js').andReturn({responseText: source});
333+
var sourceMap = '{"version":3,"sources":["./test.js"],"names":["foo","bar","baz","eval"],"mappings":"AAAA,GAAIA,KAAM,YACV,SAASC,QACT,GAAIC,KAAMC,KAAK","file":"test.min.js"}';
334+
jasmine.Ajax.stubRequest('http://localhost:9999/test.js.map').andReturn({responseText: sourceMap});
335+
336+
var stackframe = new StackFrame({args: [], fileName: 'http://localhost:9999/test.min.js', lineNumber: 1, columnNumber: 5});
337+
new StackTraceGPS().getMappedLocation(stackframe).then(callback, done.fail);
338+
339+
function callback(stackframe) {
340+
expect(stackframe).toEqual(new StackFrame({functionName: 'foo', args: [], fileName: 'http://localhost:9999/test.js', lineNumber: 1, columnNumber: 4}));
341+
done();
342+
}
343+
});
344+
330345
describe('given source and source map that resolves', function() {
331346
beforeEach(function() {
332347
var source = 'var foo=function(){};function bar(){}var baz=eval("XXX");\n//@ sourceMappingURL=test.js.map\n//# sourceURL=test.js';

stacktrace-gps.js

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -126,9 +126,14 @@
126126
}
127127

128128
function _findSourceMappingURL(source) {
129-
var m = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)\s*$/m.exec(source);
130-
if (m && m[1]) {
131-
return m[1];
129+
var sourceMappingUrlRegExp = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)\s*$/mg;
130+
var lastSourceMappingUrl;
131+
var matchSourceMappingUrl;
132+
while (matchSourceMappingUrl = sourceMappingUrlRegExp.exec(source)) {
133+
lastSourceMappingUrl = matchSourceMappingUrl[1];
134+
}
135+
if (lastSourceMappingUrl) {
136+
return lastSourceMappingUrl;
132137
} else {
133138
throw new Error('sourceMappingURL not found');
134139
}

0 commit comments

Comments
 (0)