source-map-support.js 16 KB

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