source-map-support.js 19 KB

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