source-map-support.js 17KB

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