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