source-map-support.js 20 KB

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