source-map-support.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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') && (typeof XMLHttpRequest === 'function'));
  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. } else {
  115. sourceMap = sourceMapCache[position.source] = {
  116. url: null,
  117. map: null
  118. };
  119. }
  120. }
  121. // Resolve the source URL relative to the URL of the source map
  122. if (sourceMap && sourceMap.map) {
  123. var originalPosition = sourceMap.map.originalPositionFor(position);
  124. // Only return the original position if a matching line was found. If no
  125. // matching line is found then we return position instead, which will cause
  126. // the stack trace to print the path and line for the compiled file. It is
  127. // better to give a precise location in the compiled file than a vague
  128. // location in the original file.
  129. if (originalPosition.source !== null) {
  130. originalPosition.source = supportRelativeURL(
  131. sourceMap.url, originalPosition.source);
  132. return originalPosition;
  133. }
  134. }
  135. return position;
  136. }
  137. // Parses code generated by FormatEvalOrigin(), a function inside V8:
  138. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
  139. function mapEvalOrigin(origin) {
  140. // Most eval() calls are in this format
  141. var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  142. if (match) {
  143. var position = mapSourcePosition({
  144. source: match[2],
  145. line: match[3],
  146. column: match[4] - 1
  147. });
  148. return 'eval at ' + match[1] + ' (' + position.source + ':' +
  149. position.line + ':' + (position.column + 1) + ')';
  150. }
  151. // Parse nested eval() calls using recursion
  152. match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
  153. if (match) {
  154. return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
  155. }
  156. // Make sure we still return useful information if we didn't find anything
  157. return origin;
  158. }
  159. // This is copied almost verbatim from the V8 source code at
  160. // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
  161. // implementation of wrapCallSite() used to just forward to the actual source
  162. // code of CallSite.prototype.toString but unfortunately a new release of V8
  163. // did something to the prototype chain and broke the shim. The only fix I
  164. // could find was copy/paste.
  165. function CallSiteToString() {
  166. var fileName;
  167. var fileLocation = "";
  168. if (this.isNative()) {
  169. fileLocation = "native";
  170. } else {
  171. fileName = this.getScriptNameOrSourceURL();
  172. if (!fileName && this.isEval()) {
  173. fileLocation = this.getEvalOrigin();
  174. fileLocation += ", "; // Expecting source position to follow.
  175. }
  176. if (fileName) {
  177. fileLocation += fileName;
  178. } else {
  179. // Source code does not originate from a file and is not native, but we
  180. // can still get the source position inside the source string, e.g. in
  181. // an eval string.
  182. fileLocation += "<anonymous>";
  183. }
  184. var lineNumber = this.getLineNumber();
  185. if (lineNumber != null) {
  186. fileLocation += ":" + lineNumber;
  187. var columnNumber = this.getColumnNumber();
  188. if (columnNumber) {
  189. fileLocation += ":" + columnNumber;
  190. }
  191. }
  192. }
  193. var line = "";
  194. var functionName = this.getFunctionName();
  195. var addSuffix = true;
  196. var isConstructor = this.isConstructor();
  197. var isMethodCall = !(this.isToplevel() || isConstructor);
  198. if (isMethodCall) {
  199. var typeName = this.getTypeName();
  200. var methodName = this.getMethodName();
  201. if (functionName) {
  202. if (typeName && functionName.indexOf(typeName) != 0) {
  203. line += typeName + ".";
  204. }
  205. line += functionName;
  206. if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
  207. line += " [as " + methodName + "]";
  208. }
  209. } else {
  210. line += typeName + "." + (methodName || "<anonymous>");
  211. }
  212. } else if (isConstructor) {
  213. line += "new " + (functionName || "<anonymous>");
  214. } else if (functionName) {
  215. line += functionName;
  216. } else {
  217. line += fileLocation;
  218. addSuffix = false;
  219. }
  220. if (addSuffix) {
  221. line += " (" + fileLocation + ")";
  222. }
  223. return line;
  224. }
  225. function cloneCallSite(frame) {
  226. var object = {};
  227. Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
  228. object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
  229. });
  230. object.toString = CallSiteToString;
  231. return object;
  232. }
  233. function wrapCallSite(frame) {
  234. // Most call sites will return the source file from getFileName(), but code
  235. // passed to eval() ending in "//# sourceURL=..." will return the source file
  236. // from getScriptNameOrSourceURL() instead
  237. var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  238. if (source) {
  239. var position = mapSourcePosition({
  240. source: source,
  241. line: frame.getLineNumber(),
  242. column: frame.getColumnNumber() - 1
  243. });
  244. frame = cloneCallSite(frame);
  245. frame.getFileName = function() { return position.source; };
  246. frame.getLineNumber = function() { return position.line; };
  247. frame.getColumnNumber = function() { return position.column + 1; };
  248. frame.getScriptNameOrSourceURL = function() { return position.source; };
  249. return frame;
  250. }
  251. // Code called using eval() needs special handling
  252. var origin = frame.isEval() && frame.getEvalOrigin();
  253. if (origin) {
  254. origin = mapEvalOrigin(origin);
  255. frame = cloneCallSite(frame);
  256. frame.getEvalOrigin = function() { return origin; };
  257. return frame;
  258. }
  259. // If we get here then we were unable to change the source position
  260. return frame;
  261. }
  262. // This function is part of the V8 stack trace API, for more info see:
  263. // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
  264. function prepareStackTrace(error, stack) {
  265. if (emptyCacheBetweenOperations) {
  266. fileContentsCache = {};
  267. sourceMapCache = {};
  268. }
  269. return error + stack.map(function(frame) {
  270. return '\n at ' + wrapCallSite(frame);
  271. }).join('');
  272. }
  273. // Generate position and snippet of original source with pointer
  274. function getErrorSource(error) {
  275. var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
  276. if (match) {
  277. var source = match[1];
  278. var line = +match[2];
  279. var column = +match[3];
  280. // Support the inline sourceContents inside the source map
  281. var contents = fileContentsCache[source];
  282. // Support files on disk
  283. if (!contents && fs.existsSync(source)) {
  284. contents = fs.readFileSync(source, 'utf8');
  285. }
  286. // Format the line from the original source code like node does
  287. if (contents) {
  288. var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
  289. if (code) {
  290. return '\n' + source + ':' + line + '\n' + code + '\n' +
  291. new Array(column).join(' ') + '^';
  292. }
  293. }
  294. }
  295. return null;
  296. }
  297. // Mimic node's stack trace printing when an exception escapes the process
  298. function handleUncaughtExceptions(error) {
  299. if (!error || !error.stack) {
  300. console.log('Uncaught exception:', error);
  301. } else {
  302. var source = getErrorSource(error);
  303. if (source !== null) console.log(source);
  304. console.log(error.stack);
  305. }
  306. process.exit(1);
  307. }
  308. exports.wrapCallSite = wrapCallSite;
  309. exports.getErrorSource = getErrorSource;
  310. exports.mapSourcePosition = mapSourcePosition;
  311. exports.retrieveSourceMap = retrieveSourceMap;
  312. exports.install = function(options) {
  313. if (!alreadyInstalled) {
  314. alreadyInstalled = true;
  315. Error.prepareStackTrace = prepareStackTrace;
  316. // Configure options
  317. options = options || {};
  318. var installHandler = 'handleUncaughtExceptions' in options ?
  319. options.handleUncaughtExceptions : true;
  320. emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
  321. options.emptyCacheBetweenOperations : false;
  322. // Allow sources to be found by methods other than reading the files
  323. // directly from disk.
  324. if (options.retrieveFile)
  325. retrieveFile = options.retrieveFile;
  326. // Allow source maps to be found by methods other than reading the files
  327. // directly from disk.
  328. if (options.retrieveSourceMap)
  329. retrieveSourceMap = options.retrieveSourceMap;
  330. // Provide the option to not install the uncaught exception handler. This is
  331. // to support other uncaught exception handlers (in test frameworks, for
  332. // example). If this handler is not installed and there are no other uncaught
  333. // exception handlers, uncaught exceptions will be caught by node's built-in
  334. // exception handler and the process will still be terminated. However, the
  335. // generated JavaScript code will be shown above the stack trace instead of
  336. // the original source code.
  337. if (installHandler && !isInBrowser()) {
  338. process.on('uncaughtException', handleUncaughtExceptions);
  339. }
  340. }
  341. };