source-map-support.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. var SourceMapConsumer = require('source-map').SourceMapConsumer;
  2. var path = require('path');
  3. var fs = require('fs');
  4. // Only install once if called multiple times
  5. var alreadyInstalled = false;
  6. // If true, the caches are reset before a stack trace formatting operation
  7. var emptyCacheBetweenOperations = false;
  8. // Maps a file path to a string containing the file contents
  9. var fileContentsCache = {};
  10. // Maps a file path to a source map for that file
  11. var sourceMapCache = {};
  12. function isInBrowser() {
  13. return typeof window !== 'undefined';
  14. }
  15. function retrieveFile(path) {
  16. if (path in fileContentsCache) {
  17. return fileContentsCache[path];
  18. }
  19. try {
  20. // Use SJAX if we are in the browser
  21. if (isInBrowser()) {
  22. var xhr = new XMLHttpRequest();
  23. xhr.open('GET', path, false);
  24. xhr.send(null);
  25. var contents = xhr.readyState === 4 ? xhr.responseText : null;
  26. }
  27. // Otherwise, use the filesystem
  28. else {
  29. var contents = fs.readFileSync(path, 'utf8');
  30. }
  31. } catch (e) {
  32. var contents = null;
  33. }
  34. return fileContentsCache[path] = contents;
  35. }
  36. // Support URLs relative to a directory, but be careful about a protocol prefix
  37. // in case we are in the browser (i.e. directories may start with "http://")
  38. function supportRelativeURL(file, url) {
  39. if (!file) return url;
  40. var dir = path.dirname(file);
  41. var match = /^\w+:\/\/[^\/]*/.exec(dir);
  42. var protocol = match ? match[0] : '';
  43. return protocol + path.resolve(dir.slice(protocol.length), url);
  44. }
  45. function retrieveSourceMapURL(source) {
  46. var fileData;
  47. if (isInBrowser()) {
  48. var xhr = new XMLHttpRequest();
  49. xhr.open('GET', source, false);
  50. xhr.send(null);
  51. fileData = xhr.readyState === 4 ? xhr.responseText : null;
  52. // Support providing a sourceMappingURL via the SourceMap header
  53. var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
  54. xhr.getResponseHeader("X-SourceMap");
  55. if (sourceMapHeader) {
  56. return sourceMapHeader;
  57. }
  58. }
  59. // Get the URL of the source map
  60. fileData = retrieveFile(source);
  61. var match = /\/\/[#@]\s*sourceMappingURL=(.*)\s*$/m.exec(fileData);
  62. if (!match) return null;
  63. return match[1];
  64. };
  65. // Can be overridden by the retrieveSourceMap option to install. Takes a
  66. // generated source filename; returns a {map, optional url} object, or null if
  67. // there is no source map. The map field may be either a string or the parsed
  68. // JSON object (ie, it must be a valid argument to the SourceMapConsumer
  69. // constructor).
  70. function retrieveSourceMap(source) {
  71. var sourceMappingURL = retrieveSourceMapURL(source);
  72. if (!sourceMappingURL) return null;
  73. // Read the contents of the source map
  74. var sourceMapData;
  75. var dataUrlPrefix = "data:application/json;base64,";
  76. if (sourceMappingURL.slice(0, dataUrlPrefix.length).toLowerCase() == dataUrlPrefix) {
  77. // Support source map URL as a data url
  78. sourceMapData = new Buffer(sourceMappingURL.slice(dataUrlPrefix.length), "base64").toString();
  79. sourceMappingURL = null;
  80. } else {
  81. // Support source map URLs relative to the source URL
  82. sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
  83. sourceMapData = retrieveFile(sourceMappingURL, 'utf8');
  84. }
  85. if (!sourceMapData) {
  86. return null;
  87. }
  88. return {
  89. url: sourceMappingURL,
  90. map: sourceMapData
  91. };
  92. }
  93. function mapSourcePosition(position) {
  94. var sourceMap = sourceMapCache[position.source];
  95. if (!sourceMap) {
  96. // Call the (overrideable) retrieveSourceMap function to get the source map.
  97. var urlAndMap = retrieveSourceMap(position.source);
  98. if (urlAndMap) {
  99. sourceMap = sourceMapCache[position.source] = {
  100. url: urlAndMap.url,
  101. map: new SourceMapConsumer(urlAndMap.map)
  102. };
  103. // Load all sources stored inline with the source map into the file cache
  104. // to pretend like they are already loaded. They may not exist on disk.
  105. if (sourceMap.map.sourcesContent) {
  106. sourceMap.map.sources.forEach(function(source, i) {
  107. var contents = sourceMap.map.sourcesContent[i];
  108. if (contents) {
  109. var url = supportRelativeURL(sourceMap.url, source);
  110. fileContentsCache[url] = contents;
  111. }
  112. });
  113. }
  114. }
  115. }
  116. // Resolve the source URL relative to the URL of the source map
  117. if (sourceMap) {
  118. var originalPosition = sourceMap.map.originalPositionFor(position);
  119. // Only return the original position if a matching line was found. If no
  120. // matching line is found then we return position instead, which will cause
  121. // the stack trace to print the path and line for the compiled file. It is
  122. // better to give a precise location in the compiled file than a vague
  123. // location in the original file.
  124. if (originalPosition.source !== null) {
  125. originalPosition.source = supportRelativeURL(
  126. sourceMap.url, originalPosition.source);
  127. return originalPosition;
  128. }
  129. }
  130. return position;
  131. }
  132. // Parses code generated by FormatEvalOrigin(), a function inside V8:
  133. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
  134. function mapEvalOrigin(origin) {
  135. // Most eval() calls are in this format
  136. var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  137. if (match) {
  138. var position = mapSourcePosition({
  139. source: match[2],
  140. line: match[3],
  141. column: match[4] - 1
  142. });
  143. return 'eval at ' + match[1] + ' (' + position.source + ':' +
  144. position.line + ':' + (position.column + 1) + ')';
  145. }
  146. // Parse nested eval() calls using recursion
  147. match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
  148. if (match) {
  149. return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
  150. }
  151. // Make sure we still return useful information if we didn't find anything
  152. return origin;
  153. }
  154. // This is copied almost verbatim from the V8 source code at
  155. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
  156. // implementation of wrapCallSite() used to just forward to the actual source
  157. // code of CallSite.prototype.toString but unfortunately a new release of V8
  158. // did something to the prototype chain and broke the shim. The only fix I
  159. // could find was copy/paste.
  160. function CallSiteToString() {
  161. var fileName;
  162. var fileLocation = "";
  163. if (this.isNative()) {
  164. fileLocation = "native";
  165. } else {
  166. fileName = this.getScriptNameOrSourceURL();
  167. if (!fileName && this.isEval()) {
  168. fileLocation = this.getEvalOrigin();
  169. fileLocation += ", "; // Expecting source position to follow.
  170. }
  171. if (fileName) {
  172. fileLocation += fileName;
  173. } else {
  174. // Source code does not originate from a file and is not native, but we
  175. // can still get the source position inside the source string, e.g. in
  176. // an eval string.
  177. fileLocation += "<anonymous>";
  178. }
  179. var lineNumber = this.getLineNumber();
  180. if (lineNumber != null) {
  181. fileLocation += ":" + lineNumber;
  182. var columnNumber = this.getColumnNumber();
  183. if (columnNumber) {
  184. fileLocation += ":" + columnNumber;
  185. }
  186. }
  187. }
  188. var line = "";
  189. var functionName = this.getFunctionName();
  190. var addSuffix = true;
  191. var isConstructor = this.isConstructor();
  192. var isMethodCall = !(this.isToplevel() || isConstructor);
  193. if (isMethodCall) {
  194. var typeName = this.getTypeName();
  195. var methodName = this.getMethodName();
  196. if (functionName) {
  197. if (typeName && functionName.indexOf(typeName) != 0) {
  198. line += typeName + ".";
  199. }
  200. line += functionName;
  201. if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
  202. line += " [as " + methodName + "]";
  203. }
  204. } else {
  205. line += typeName + "." + (methodName || "<anonymous>");
  206. }
  207. } else if (isConstructor) {
  208. line += "new " + (functionName || "<anonymous>");
  209. } else if (functionName) {
  210. line += functionName;
  211. } else {
  212. line += fileLocation;
  213. addSuffix = false;
  214. }
  215. if (addSuffix) {
  216. line += " (" + fileLocation + ")";
  217. }
  218. return line;
  219. }
  220. function cloneCallSite(frame) {
  221. var object = {};
  222. Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
  223. object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
  224. });
  225. object.toString = CallSiteToString;
  226. return object;
  227. }
  228. function wrapCallSite(frame) {
  229. // Most call sites will return the source file from getFileName(), but code
  230. // passed to eval() ending in "//# sourceURL=..." will return the source file
  231. // from getScriptNameOrSourceURL() instead
  232. var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  233. if (source) {
  234. var position = mapSourcePosition({
  235. source: source,
  236. line: frame.getLineNumber(),
  237. column: frame.getColumnNumber() - 1
  238. });
  239. frame = cloneCallSite(frame);
  240. frame.getFileName = function() { return position.source; };
  241. frame.getLineNumber = function() { return position.line; };
  242. frame.getColumnNumber = function() { return position.column + 1; };
  243. frame.getScriptNameOrSourceURL = function() { return position.source; };
  244. return frame;
  245. }
  246. // Code called using eval() needs special handling
  247. var origin = frame.isEval() && frame.getEvalOrigin();
  248. if (origin) {
  249. origin = mapEvalOrigin(origin);
  250. frame = cloneCallSite(frame);
  251. frame.getEvalOrigin = function() { return origin; };
  252. return frame;
  253. }
  254. // If we get here then we were unable to change the source position
  255. return frame;
  256. }
  257. // This function is part of the V8 stack trace API, for more info see:
  258. // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
  259. function prepareStackTrace(error, stack) {
  260. if (emptyCacheBetweenOperations) {
  261. fileContentsCache = {};
  262. sourceMapCache = {};
  263. }
  264. return error + stack.map(function(frame) {
  265. return '\n at ' + wrapCallSite(frame);
  266. }).join('');
  267. }
  268. // Generate position and snippet of original source with pointer
  269. function getErrorSource(error) {
  270. var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
  271. if (match) {
  272. var source = match[1];
  273. var line = +match[2];
  274. var column = +match[3];
  275. // Support the inline sourceContents inside the source map
  276. var contents = fileContentsCache[source];
  277. // Support files on disk
  278. if (!contents && fs.existsSync(source)) {
  279. contents = fs.readFileSync(source, 'utf8');
  280. }
  281. // Format the line from the original source code like node does
  282. if (contents) {
  283. var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
  284. if (code) {
  285. return '\n' + source + ':' + line + '\n' + code + '\n' +
  286. new Array(column).join(' ') + '^';
  287. }
  288. }
  289. }
  290. return null;
  291. }
  292. // Mimic node's stack trace printing when an exception escapes the process
  293. function handleUncaughtExceptions(error) {
  294. if (!error || !error.stack) {
  295. console.log('Uncaught exception:', error);
  296. } else {
  297. var source = getErrorSource(error);
  298. if (source !== null) console.log(source);
  299. console.log(error.stack);
  300. }
  301. process.exit(1);
  302. }
  303. exports.wrapCallSite = wrapCallSite;
  304. exports.getErrorSource = getErrorSource;
  305. exports.mapSourcePosition = mapSourcePosition;
  306. exports.retrieveSourceMap = retrieveSourceMap;
  307. exports.install = function(options) {
  308. if (!alreadyInstalled) {
  309. alreadyInstalled = true;
  310. Error.prepareStackTrace = prepareStackTrace;
  311. // Configure options
  312. options = options || {};
  313. var installHandler = 'handleUncaughtExceptions' in options ?
  314. options.handleUncaughtExceptions : true;
  315. emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
  316. options.emptyCacheBetweenOperations : false;
  317. // Allow sources to be found by methods other than reading the files
  318. // directly from disk.
  319. if (options.retrieveFile)
  320. retrieveFile = options.retrieveFile;
  321. // Allow source maps to be found by methods other than reading the files
  322. // directly from disk.
  323. if (options.retrieveSourceMap)
  324. retrieveSourceMap = options.retrieveSourceMap;
  325. // Provide the option to not install the uncaught exception handler. This is
  326. // to support other uncaught exception handlers (in test frameworks, for
  327. // example). If this handler is not installed and there are no other uncaught
  328. // exception handlers, uncaught exceptions will be caught by node's built-in
  329. // exception handler and the process will still be terminated. However, the
  330. // generated JavaScript code will be shown above the stack trace instead of
  331. // the original source code.
  332. if (installHandler && !isInBrowser()) {
  333. process.on('uncaughtException', handleUncaughtExceptions);
  334. }
  335. }
  336. };