You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

587 lines
19 KiB

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