source-map-support.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. var SourceMapConsumer = require('source-map').SourceMapConsumer;
  2. var path = require('path');
  3. var fs;
  4. try {
  5. fs = require('fs');
  6. if (!fs.existsSync || !fs.readFileSync) {
  7. // fs doesn't have all methods we need
  8. fs = null;
  9. }
  10. } catch (err) {
  11. /* nop */
  12. }
  13. // Only install once if called multiple times
  14. var errorFormatterInstalled = false;
  15. var uncaughtShimInstalled = false;
  16. // If true, the caches are reset before a stack trace formatting operation
  17. var emptyCacheBetweenOperations = false;
  18. // Supports {browser, node, auto}
  19. var environment = "auto";
  20. // Maps a file path to a string containing the file contents
  21. var fileContentsCache = {};
  22. // Maps a file path to a source map for that file
  23. var sourceMapCache = {};
  24. // Regex for detecting source maps
  25. var reSourceMap = /^data:application\/json[^,]+base64,/;
  26. // Priority list of retrieve handlers
  27. var retrieveFileHandlers = [];
  28. var retrieveMapHandlers = [];
  29. function isInBrowser() {
  30. if (environment === "browser")
  31. return true;
  32. if (environment === "node")
  33. return false;
  34. return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
  35. }
  36. function hasGlobalProcessEventEmitter() {
  37. return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
  38. }
  39. function handlerExec(list) {
  40. return function(arg) {
  41. for (var i = 0; i < list.length; i++) {
  42. var ret = list[i](arg);
  43. if (ret) {
  44. return ret;
  45. }
  46. }
  47. return null;
  48. };
  49. }
  50. var retrieveFile = handlerExec(retrieveFileHandlers);
  51. retrieveFileHandlers.push(function(path) {
  52. // Trim the path to make sure there is no extra whitespace.
  53. path = path.trim();
  54. if (path in fileContentsCache) {
  55. return fileContentsCache[path];
  56. }
  57. var contents = null;
  58. if (!fs) {
  59. // Use SJAX if we are in the browser
  60. var xhr = new XMLHttpRequest();
  61. xhr.open('GET', path, false);
  62. xhr.send(null);
  63. var contents = null
  64. if (xhr.readyState === 4 && xhr.status === 200) {
  65. contents = xhr.responseText
  66. }
  67. } else if (fs.existsSync(path)) {
  68. // Otherwise, use the filesystem
  69. contents = fs.readFileSync(path, 'utf8');
  70. }
  71. return fileContentsCache[path] = contents;
  72. });
  73. // Support URLs relative to a directory, but be careful about a protocol prefix
  74. // in case we are in the browser (i.e. directories may start with "http://")
  75. function supportRelativeURL(file, url) {
  76. if (!file) return url;
  77. var dir = path.dirname(file);
  78. var match = /^\w+:\/\/[^\/]*/.exec(dir);
  79. var protocol = match ? match[0] : '';
  80. return protocol + path.resolve(dir.slice(protocol.length), url);
  81. }
  82. function retrieveSourceMapURL(source) {
  83. var fileData;
  84. if (isInBrowser()) {
  85. try {
  86. var xhr = new XMLHttpRequest();
  87. xhr.open('GET', source, false);
  88. xhr.send(null);
  89. fileData = xhr.readyState === 4 ? xhr.responseText : null;
  90. // Support providing a sourceMappingURL via the SourceMap header
  91. var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
  92. xhr.getResponseHeader("X-SourceMap");
  93. if (sourceMapHeader) {
  94. return sourceMapHeader;
  95. }
  96. } catch (e) {
  97. }
  98. }
  99. // Get the URL of the source map
  100. fileData = retrieveFile(source);
  101. var re = /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/)[ \t]*$)/mg;
  102. // Keep executing the search to find the *last* sourceMappingURL to avoid
  103. // picking up sourceMappingURLs from comments, strings, etc.
  104. var lastMatch, match;
  105. while (match = re.exec(fileData)) lastMatch = match;
  106. if (!lastMatch) return null;
  107. return lastMatch[1];
  108. };
  109. // Can be overridden by the retrieveSourceMap option to install. Takes a
  110. // generated source filename; returns a {map, optional url} object, or null if
  111. // there is no source map. The map field may be either a string or the parsed
  112. // JSON object (ie, it must be a valid argument to the SourceMapConsumer
  113. // constructor).
  114. var retrieveSourceMap = handlerExec(retrieveMapHandlers);
  115. retrieveMapHandlers.push(function(source) {
  116. var sourceMappingURL = retrieveSourceMapURL(source);
  117. if (!sourceMappingURL) return null;
  118. // Read the contents of the source map
  119. var sourceMapData;
  120. if (reSourceMap.test(sourceMappingURL)) {
  121. // Support source map URL as a data url
  122. var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
  123. sourceMapData = new Buffer(rawData, "base64").toString();
  124. sourceMappingURL = source;
  125. } else {
  126. // Support source map URLs relative to the source URL
  127. sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
  128. sourceMapData = retrieveFile(sourceMappingURL);
  129. }
  130. if (!sourceMapData) {
  131. return null;
  132. }
  133. return {
  134. url: sourceMappingURL,
  135. map: sourceMapData
  136. };
  137. });
  138. function mapSourcePosition(position) {
  139. var sourceMap = sourceMapCache[position.source];
  140. if (!sourceMap) {
  141. // Call the (overrideable) retrieveSourceMap function to get the source map.
  142. var urlAndMap = retrieveSourceMap(position.source);
  143. if (urlAndMap) {
  144. sourceMap = sourceMapCache[position.source] = {
  145. url: urlAndMap.url,
  146. map: new SourceMapConsumer(urlAndMap.map)
  147. };
  148. // Load all sources stored inline with the source map into the file cache
  149. // to pretend like they are already loaded. They may not exist on disk.
  150. if (sourceMap.map.sourcesContent) {
  151. sourceMap.map.sources.forEach(function(source, i) {
  152. var contents = sourceMap.map.sourcesContent[i];
  153. if (contents) {
  154. var url = supportRelativeURL(sourceMap.url, source);
  155. fileContentsCache[url] = contents;
  156. }
  157. });
  158. }
  159. } else {
  160. sourceMap = sourceMapCache[position.source] = {
  161. url: null,
  162. map: null
  163. };
  164. }
  165. }
  166. // Resolve the source URL relative to the URL of the source map
  167. if (sourceMap && sourceMap.map) {
  168. var originalPosition = sourceMap.map.originalPositionFor(position);
  169. // Only return the original position if a matching line was found. If no
  170. // matching line is found then we return position instead, which will cause
  171. // the stack trace to print the path and line for the compiled file. It is
  172. // better to give a precise location in the compiled file than a vague
  173. // location in the original file.
  174. if (originalPosition.source !== null) {
  175. originalPosition.source = supportRelativeURL(
  176. sourceMap.url, originalPosition.source);
  177. return originalPosition;
  178. }
  179. }
  180. return position;
  181. }
  182. // Parses code generated by FormatEvalOrigin(), a function inside V8:
  183. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
  184. function mapEvalOrigin(origin) {
  185. // Most eval() calls are in this format
  186. var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  187. if (match) {
  188. var position = mapSourcePosition({
  189. source: match[2],
  190. line: +match[3],
  191. column: match[4] - 1
  192. });
  193. return 'eval at ' + match[1] + ' (' + position.source + ':' +
  194. position.line + ':' + (position.column + 1) + ')';
  195. }
  196. // Parse nested eval() calls using recursion
  197. match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
  198. if (match) {
  199. return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
  200. }
  201. // Make sure we still return useful information if we didn't find anything
  202. return origin;
  203. }
  204. // This is copied almost verbatim from the V8 source code at
  205. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
  206. // implementation of wrapCallSite() used to just forward to the actual source
  207. // code of CallSite.prototype.toString but unfortunately a new release of V8
  208. // did something to the prototype chain and broke the shim. The only fix I
  209. // could find was copy/paste.
  210. function CallSiteToString() {
  211. var fileName;
  212. var fileLocation = "";
  213. if (this.isNative()) {
  214. fileLocation = "native";
  215. } else {
  216. fileName = this.getScriptNameOrSourceURL();
  217. if (!fileName && this.isEval()) {
  218. fileLocation = this.getEvalOrigin();
  219. fileLocation += ", "; // Expecting source position to follow.
  220. }
  221. if (fileName) {
  222. fileLocation += fileName;
  223. } else {
  224. // Source code does not originate from a file and is not native, but we
  225. // can still get the source position inside the source string, e.g. in
  226. // an eval string.
  227. fileLocation += "<anonymous>";
  228. }
  229. var lineNumber = this.getLineNumber();
  230. if (lineNumber != null) {
  231. fileLocation += ":" + lineNumber;
  232. var columnNumber = this.getColumnNumber();
  233. if (columnNumber) {
  234. fileLocation += ":" + columnNumber;
  235. }
  236. }
  237. }
  238. var line = "";
  239. var functionName = this.getFunctionName();
  240. var addSuffix = true;
  241. var isConstructor = this.isConstructor();
  242. var isMethodCall = !(this.isToplevel() || isConstructor);
  243. if (isMethodCall) {
  244. var typeName = this.getTypeName();
  245. // Fixes shim to be backward compatable with Node v0 to v4
  246. if (typeName === "[object Object]") {
  247. typeName = "null";
  248. }
  249. var methodName = this.getMethodName();
  250. if (functionName) {
  251. if (typeName && functionName.indexOf(typeName) != 0) {
  252. line += typeName + ".";
  253. }
  254. line += functionName;
  255. if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
  256. line += " [as " + methodName + "]";
  257. }
  258. } else {
  259. line += typeName + "." + (methodName || "<anonymous>");
  260. }
  261. } else if (isConstructor) {
  262. line += "new " + (functionName || "<anonymous>");
  263. } else if (functionName) {
  264. line += functionName;
  265. } else {
  266. line += fileLocation;
  267. addSuffix = false;
  268. }
  269. if (addSuffix) {
  270. line += " (" + fileLocation + ")";
  271. }
  272. return line;
  273. }
  274. function cloneCallSite(frame) {
  275. var object = {};
  276. Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
  277. object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
  278. });
  279. object.toString = CallSiteToString;
  280. return object;
  281. }
  282. function wrapCallSite(frame) {
  283. if(frame.isNative()) {
  284. return frame;
  285. }
  286. // Most call sites will return the source file from getFileName(), but code
  287. // passed to eval() ending in "//# sourceURL=..." will return the source file
  288. // from getScriptNameOrSourceURL() instead
  289. var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  290. if (source) {
  291. var line = frame.getLineNumber();
  292. var column = frame.getColumnNumber() - 1;
  293. // Fix position in Node where some (internal) code is prepended.
  294. // See https://github.com/evanw/node-source-map-support/issues/36
  295. if (line === 1 && !isInBrowser() && !frame.isEval()) {
  296. column -= 62;
  297. }
  298. var position = mapSourcePosition({
  299. source: source,
  300. line: line,
  301. column: column
  302. });
  303. frame = cloneCallSite(frame);
  304. frame.getFileName = function() { return position.source; };
  305. frame.getLineNumber = function() { return position.line; };
  306. frame.getColumnNumber = function() { return position.column + 1; };
  307. frame.getScriptNameOrSourceURL = function() { return position.source; };
  308. return frame;
  309. }
  310. // Code called using eval() needs special handling
  311. var origin = frame.isEval() && frame.getEvalOrigin();
  312. if (origin) {
  313. origin = mapEvalOrigin(origin);
  314. frame = cloneCallSite(frame);
  315. frame.getEvalOrigin = function() { return origin; };
  316. return frame;
  317. }
  318. // If we get here then we were unable to change the source position
  319. return frame;
  320. }
  321. // This function is part of the V8 stack trace API, for more info see:
  322. // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
  323. function prepareStackTrace(error, stack) {
  324. if (emptyCacheBetweenOperations) {
  325. fileContentsCache = {};
  326. sourceMapCache = {};
  327. }
  328. return error + stack.map(function(frame) {
  329. return '\n at ' + wrapCallSite(frame);
  330. }).join('');
  331. }
  332. // Generate position and snippet of original source with pointer
  333. function getErrorSource(error) {
  334. var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
  335. if (match) {
  336. var source = match[1];
  337. var line = +match[2];
  338. var column = +match[3];
  339. // Support the inline sourceContents inside the source map
  340. var contents = fileContentsCache[source];
  341. // Support files on disk
  342. if (!contents && fs && fs.existsSync(source)) {
  343. contents = fs.readFileSync(source, 'utf8');
  344. }
  345. // Format the line from the original source code like node does
  346. if (contents) {
  347. var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
  348. if (code) {
  349. return source + ':' + line + '\n' + code + '\n' +
  350. new Array(column).join(' ') + '^';
  351. }
  352. }
  353. }
  354. return null;
  355. }
  356. function printErrorAndExit (error) {
  357. var source = getErrorSource(error);
  358. if (source) {
  359. console.error();
  360. console.error(source);
  361. }
  362. console.error(error.stack);
  363. process.exit(1);
  364. }
  365. function shimEmitUncaughtException () {
  366. var origEmit = process.emit;
  367. process.emit = function (type) {
  368. if (type === 'uncaughtException') {
  369. var hasStack = (arguments[1] && arguments[1].stack);
  370. var hasListeners = (this.listeners(type).length > 0);
  371. if (hasStack && !hasListeners) {
  372. return printErrorAndExit(arguments[1]);
  373. }
  374. }
  375. return origEmit.apply(this, arguments);
  376. };
  377. }
  378. exports.wrapCallSite = wrapCallSite;
  379. exports.getErrorSource = getErrorSource;
  380. exports.mapSourcePosition = mapSourcePosition;
  381. exports.retrieveSourceMap = retrieveSourceMap;
  382. exports.install = function(options) {
  383. options = options || {};
  384. if (options.environment) {
  385. environment = options.environment;
  386. if (["node", "browser", "auto"].indexOf(environment) === -1) {
  387. throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
  388. }
  389. }
  390. // Allow sources to be found by methods other than reading the files
  391. // directly from disk.
  392. if (options.retrieveFile) {
  393. if (options.overrideRetrieveFile) {
  394. retrieveFileHandlers.length = 0;
  395. }
  396. retrieveFileHandlers.unshift(options.retrieveFile);
  397. }
  398. // Allow source maps to be found by methods other than reading the files
  399. // directly from disk.
  400. if (options.retrieveSourceMap) {
  401. if (options.overrideRetrieveSourceMap) {
  402. retrieveMapHandlers.length = 0;
  403. }
  404. retrieveMapHandlers.unshift(options.retrieveSourceMap);
  405. }
  406. // Support runtime transpilers that include inline source maps
  407. if (options.hookRequire && !isInBrowser()) {
  408. var Module;
  409. try {
  410. Module = require('module');
  411. } catch (err) {
  412. // NOP: Loading in catch block to convert webpack error to warning.
  413. }
  414. var $compile = Module.prototype._compile;
  415. if (!$compile.__sourceMapSupport) {
  416. Module.prototype._compile = function(content, filename) {
  417. fileContentsCache[filename] = content;
  418. sourceMapCache[filename] = undefined;
  419. return $compile.call(this, content, filename);
  420. };
  421. Module.prototype._compile.__sourceMapSupport = true;
  422. }
  423. }
  424. // Configure options
  425. if (!emptyCacheBetweenOperations) {
  426. emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
  427. options.emptyCacheBetweenOperations : false;
  428. }
  429. // Install the error reformatter
  430. if (!errorFormatterInstalled) {
  431. errorFormatterInstalled = true;
  432. Error.prepareStackTrace = prepareStackTrace;
  433. }
  434. if (!uncaughtShimInstalled) {
  435. var installHandler = 'handleUncaughtExceptions' in options ?
  436. options.handleUncaughtExceptions : true;
  437. // Provide the option to not install the uncaught exception handler. This is
  438. // to support other uncaught exception handlers (in test frameworks, for
  439. // example). If this handler is not installed and there are no other uncaught
  440. // exception handlers, uncaught exceptions will be caught by node's built-in
  441. // exception handler and the process will still be terminated. However, the
  442. // generated JavaScript code will be shown above the stack trace instead of
  443. // the original source code.
  444. if (installHandler && hasGlobalProcessEventEmitter()) {
  445. uncaughtShimInstalled = true;
  446. shimEmitUncaughtException();
  447. }
  448. }
  449. };