[
  {
    "path": ".gitignore",
    "content": "node_modules\ndist\n"
  },
  {
    "path": ".npmignore",
    "content": "node_modules\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2016, James Salter\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n  list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n  this list of conditions and the following disclaimer in the documentation\n  and/or other materials provided with the distribution.\n\n* Neither the name of sourcemapped-stacktrace nor the names of its\n  contributors may be used to endorse or promote products derived from\n  this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "README.md",
    "content": "This is a simple module for applying source maps to JS stack traces in the browser. \n\n## The problem this solves\n\nYou have Error.stack() in JS (maybe you're logging a trace, or you're looking at\ntraces in Jasmine or Mocha), and you need to apply a sourcemap so you can\nunderstand whats happening because you're using some fancy compiled-to-js thing\nlike coffeescript or traceur. Unfortunately, the browser only applies sourcemaps when the\ntrace is viewed in its console, not to the underlying stack object, so you're\nout of luck.\n\n## Demo\n\nhttp://novocaine.github.io/sourcemapped-stacktrace-demo/public_html/smst.html\n\n## Install from npm\n\n```\nnpm install sourcemapped-stacktrace\n```\n\nhttps://www.npmjs.com/package/sourcemapped-stacktrace\n\nThe npm bundle contains dist/sourcemapped-stacktrace.js, if that's what you're\nafter. The built product is not held in this repo.\n\n## Setup\n\nInclude sourcemapped-stacktrace.js into your page using either an AMD module\nloader or a plain old script include. As an AMD module it exposes the method\n'mapStackTrace'. If an AMD loader is not found this function will be set on\nwindow.sourceMappedStackTrace.mapStackTrace.\n\n## API \n\n### mapStackTrace(stack, done [, opts])\n\nRe-map entries in a stacktrace using sourcemaps if available.\n\n**Arguments:**\n\n- *stack*: (str) The stacktrace from the browser.\n\n- *done*: Callback invoked with the transformed stacktrace (an Array of Strings) passed as the first argument\n\n- *opts*: Optional options object containing:\n  - *filter*: Function that filters each stacktrace line.\n              It is invoked with _(line)_ and should return truthy/ falsy value.\n              Sources which do not pass the filter won't be processed.\n  - *cacheGlobally*: Boolean. If `true`, sourcemaps are cached across multiple `mapStackTrace()` calls,\n                     allowing for better performance if called repeatedly, or when browser's cache is disabled.\n                     Defaults to `false`.\n  - *sync*: Boolean. Whether to use synchronous ajax to load the sourcemaps.\n\n**Supported browsers**\n  - Chrome\n  - Firefox\n  - Safari\n  - Internet Explorer 11 and up\n  - Microsoft Edge\n\n## Example\n\n```javascript\ntry {\n  // break something\n  bork();\n} catch (e) {\n  // pass e.stack to window.mapStackTrace\n  window.mapStackTrace(e.stack, function(mappedStack) {\n    // do what you want with mappedStack here\n    console.log(mappedStack.join(\"\\n\"));\n  }, {\n    filter: function (line) {\n      // process only sources containing `spec.js`\n      return /(spec\\.js)/.test(line);\n    }\n  });\n}\n```\n\n## Longer Explanation\n\nSeveral modern browsers support sourcemaps when viewing stack traces from errors in their native console, but as of the time of writing there is no support for applying a sourcemap to the (highly non-standardised) [Error.prototype.stack](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack). Error.prototype.stack can be used for logging errors and for displaying errors in test frameworks, and it is not very convenient to have unmapped traces in either of those use cases.\n\nThis module fetches all the scripts referenced by the stack trace, determines\nwhether they have an applicable sourcemap, fetches the sourcemap from the\nserver, then uses the [Mozilla source-map library](https://github.com/mozilla/source-map/) to do the mapping. Browsers that support sourcemaps don't offer a standardised sourcemap API, so we have to do all that work ourselves.\n\nThe nice part about doing it ourselves is that the library could be extended to\nwork in browsers that don't support sourcemaps, which could be good for\nlogging and debugging problems. Currently, only Chrome and Firefox are supported, but it\nwould be easy to support those formats by ripping off [stacktrace.js](https://github.com/stacktracejs/stacktrace.js/).\n\n## Known issues\n\n* Doesn't support exception formats of any browser other than Chrome and\n  Firefox\n* Only supports JS containing //# sourceMappingURL= declarations (i.e. no\n  support for the SourceMap: HTTP header (yet)\n* Some prominent sourcemap generators (including CoffeeScript, Traceur, Babel)\n  don't emit a list of 'names' in the source-map, which means that frames from transpiled code will have (unknown) instead of the original function name. Those generators should support this feature better.\n"
  },
  {
    "path": "demo/.babelrc",
    "content": "{\n  \"presets\": [\"es2015\"]\n}\n"
  },
  {
    "path": "demo/.gitignore",
    "content": "bork.babel.js\nbork_coffee.js\n*.map\nsourcemapped-stacktrace.js\n"
  },
  {
    "path": "demo/bork.es6",
    "content": "class BabelBorker {\n    bork() {\n        throw new Error(\"bork from es6\");\n    }\n}\n\nwindow.babel_bork = () => new BabelBorker().bork()\n"
  },
  {
    "path": "demo/bork_coffee.coffee",
    "content": "class CoffeeBorker\n  bork: () ->\n    throw new Error(\"Bork from coffeescript\")\n    \nwindow.coffee_bork = () -> new CoffeeBorker().bork()\n"
  },
  {
    "path": "demo/make.sh",
    "content": "# (don't forget to run npm install first, to update dist/smst.js)\nbabel bork.es6 -s true > bork.babel.js\ncoffee -c -m bork_coffee.coffee\ncp ../dist/sourcemapped-stacktrace.js .\n"
  },
  {
    "path": "demo/smst.html",
    "content": "<!DOCTYPE html>\n<html>\n  <!--<script type=\"text/javascript\"\n    src=\"https://rawgithub.com/novocaine/sourcemapped-stacktrace/master/dist/sourcemapped-stacktrace.js\"></script>-->\n  <script type=\"text/javascript\" src=\"sourcemapped-stacktrace.js\"></script>\n  <script type=\"text/javascript\" src=\"bork_coffee.js\"></script>\n  <script type=\"text/javascript\" src=\"bork.babel.js\"></script>\n<body>\n  <p>A demo of printing a stack trace from an error thrown within transpiled\n    code.\n  </p>\n\n  <button type=\"button\" onclick=\"errorAndPrint(coffee_bork)\">\n    Throw an error in sourcemapped code from coffeescript\n  </button>\n  <button type=\"button\" onclick=\"errorAndPrint(babel_bork)\">\n    Throw an error in sourcemapped code from babel\n  </button>\n\n  <p>Source-mapped Stack trace (pointing to original code):</p>\n\n  <pre id=\"mapped\">\n  </pre>\n\n  <p>Unmapped Stack trace (pointing to transpiled code):</p>\n\n  <pre id=\"unmapped\">\n  </pre>\n\n  <p>Alternatively, try throwing and not catching, to compare the trace in your\n  browser's console: </p>\n  <button type=\"button\" onclick=\"coffee_bork()\">Throw uncaught</button>\n\n    <script type=\"text/javascript\">\n      var errorAndPrint = function(bork_func) {\n        try {\n          bork_func();\n        } catch (e) {\n          // display unmapped trace\n          var unmapped = document.getElementById(\"unmapped\");\n          unmapped.innerHTML = \"\";\n          var unmappedNode = document.createTextNode(e.stack);\n          unmapped.appendChild(unmappedNode);\n\n          // invoke smst\n          sourceMappedStackTrace.mapStackTrace(e.stack, function(mappedStack) {\n            // mappedStack is an array of strings, one per frame in e.stack\n            var mappedElem = document.getElementById(\"mapped\");\n            mappedElem.innerHTML = \"\";\n            var textNode = document.createTextNode(e.message + \"\\n\" + \n              mappedStack.join(\"\\n\"));\n            mappedElem.appendChild(textNode);\n          });\n        }\n      }\n    </script>\n\n</body>\n</html>\n"
  },
  {
    "path": "index.d.ts",
    "content": "declare module 'sourcemapped-stacktrace' {\n\n    export interface MapStackTraceOptions {\n        /** Filter function applied to each stackTrace line. Lines which do not pass the filter won't be processesd. */\n        filter?: (line: string) => boolean\n        /** Whether to cache sourcemaps globally across multiple calls. */\n        cacheGlobally?: boolean\n        /** Whether to use synchronous ajax to load the sourcemaps. */\n        sync?: boolean\n    }\n    \n    /**\n     * Re-map entries in a stacktrace using sourcemaps if available.\n     *\n     * @param stack The stacktrace from the browser (`error.stack`).\n     * @param done Callback invoked with the transformed stacktrace.\n     * @param opts Options object.\n     */\n    export function mapStackTrace(stack: string | undefined, done: (mappedStack: string[]) => void, opts?: MapStackTraceOptions): void\n\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"sourcemapped-stacktrace\",\n  \"version\": \"1.1.11\",\n  \"homepage\": \"https://github.com/novocaine/sourcemapped-stacktrace\",\n  \"license\": \"BSD-3-Clause\",\n  \"author\": {\n    \"name\": \"James Salter\",\n    \"email\": \"iteration@gmail.com\"\n  },\n  \"main\": \"dist/sourcemapped-stacktrace.js\",\n  \"description\": \"A simple module for applying source maps to JS stack traces in the browser.\",\n  \"dependencies\": {\n    \"source-map\": \"0.5.6\"\n  },\n  \"devDependencies\": {\n    \"babel-preset-es2015\": \"^6.9.0\",\n    \"webpack\": \"^1.12.0\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"http://github.com/novocaine/sourcemapped-stacktrace\"\n  },\n  \"scripts\": {\n    \"prepublish\": \"webpack\"\n  }\n}\n"
  },
  {
    "path": "sourcemapped-stacktrace.js",
    "content": "/*\n * sourcemapped-stacktrace.js\n * created by James Salter <iteration@gmail.com> (2014)\n *\n * https://github.com/novocaine/sourcemapped-stacktrace\n *\n * Licensed under the New BSD license. See LICENSE or:\n * http://opensource.org/licenses/BSD-3-Clause\n */\n\n/*global define */\n\n// note we only include source-map-consumer, not the whole source-map library,\n// which includes gear for generating source maps that we don't need\ndefine(['source-map/lib/source-map-consumer'],\nfunction(source_map_consumer) {\n\n  var global_mapForUri = {};\n\n  /**\n   * Re-map entries in a stacktrace using sourcemaps if available.\n   *\n   * @param {str} stack - The stacktrace from the browser.\n   * @param {function} done - Callback invoked with the transformed stacktrace\n   *                          (an Array of Strings) passed as the first\n   *                          argument\n   * @param {Object} [opts] - Optional options object.\n   * @param {Function} [opts.filter] - Filter function applied to each stackTrace line.\n   *                                   Lines which do not pass the filter won't be processesd.\n   * @param {boolean} [opts.cacheGlobally] - Whether to cache sourcemaps globally across multiple calls.\n   * @param {boolean} [opts.sync] - Whether to use synchronous ajax to load the sourcemaps.\n   * @param {string} [opts.traceFormat] - If `error.stack` is formatted according to chrome or\n   *                                      Firefox's style.  Can be either `\"chrome\"`, `\"firefox\"`\n   *                                      or `undefined` (default).  If `undefined`, this library\n   *                                      will guess based on `navigator.userAgent`.\n   */\n  var mapStackTrace = function(stack, done, opts) {\n    var lines;\n    var line;\n    var mapForUri = {};\n    var rows = {};\n    var fields;\n    var uri;\n    var expected_fields;\n    var regex;\n    var skip_lines;\n\n    var fetcher = new Fetcher(opts);\n\n    var traceFormat = opts && opts.traceFormat;\n    if (traceFormat !== \"chrome\" && traceFormat !== \"firefox\") {\n      if (traceFormat) {\n        throw new Error(\"unknown traceFormat \\\"\" + traceFormat + \"\\\" :(\");\n      } else if (isChromeOrEdge() || isIE11Plus()) {\n        traceFormat = \"chrome\";\n      } else if (isFirefox() || isSafari()) {\n        traceFormat = \"firefox\";\n      } else {\n        throw new Error(\"unknown browser :(\");\n      }\n    }\n\n    if (traceFormat === \"chrome\") {\n      regex = /^ +at.+\\((.*):([0-9]+):([0-9]+)/;\n      expected_fields = 4;\n      // (skip first line containing exception message)\n      skip_lines = 1;\n    } else {\n      regex = /@(.*):([0-9]+):([0-9]+)/;\n      expected_fields = 4;\n      skip_lines = 0;\n    }\n\n    lines = stack.split(\"\\n\").slice(skip_lines);\n\n    for (var i=0; i < lines.length; i++) {\n      line = lines[i];\n      if ( opts && opts.filter && !opts.filter(line) ) continue;\n      \n      fields = line.match(regex);\n      if (fields && fields.length === expected_fields) {\n        rows[i] = fields;\n        uri = fields[1];\n        if (!uri.match(/<anonymous>/)) {\n          fetcher.fetchScript(uri);\n        }\n      }\n    }\n\n    fetcher.sem.whenReady(function() {\n      var result = processSourceMaps(lines, rows, fetcher.mapForUri, traceFormat);\n      done(result);\n    });\n  };\n\n  var isChromeOrEdge = function() {\n    return navigator.userAgent.toLowerCase().indexOf('chrome') > -1;\n  };\n\n  var isFirefox = function() {\n    return navigator.userAgent.toLowerCase().indexOf('firefox') > -1;\n  };  \n\n  var isSafari = function() {\n    return navigator.userAgent.toLowerCase().indexOf('safari') > -1;\n  };\n\t\t\n  var isIE11Plus = function() {\n   \treturn document.documentMode && document.documentMode >= 11;\n  };\n\n\n  var Semaphore = function() {\n    this.count = 0;\n    this.pending = [];\n  };\n\n  Semaphore.prototype.incr = function() {\n    this.count++;\n  };\n\n  Semaphore.prototype.decr = function() {\n    this.count--;\n    this.flush();\n  };\n\n  Semaphore.prototype.whenReady = function(fn) {\n    this.pending.push(fn);\n    this.flush();\n  };\n\n  Semaphore.prototype.flush = function() {\n    if (this.count === 0) {\n        this.pending.forEach(function(fn) { fn(); });\n        this.pending = [];\n    }\n  };\n\n\n  var Fetcher = function(opts) {\n    this.sem = new Semaphore();\n    this.sync = opts && opts.sync;\n    this.mapForUri = opts && opts.cacheGlobally ? global_mapForUri : {};\n  };\n\n  Fetcher.prototype.ajax = function(uri, callback) {\n    var xhr = createXMLHTTPObject();\n    var that = this;\n    xhr.onreadystatechange = function() {\n      if (xhr.readyState == 4) {\n        callback.call(that, xhr, uri);\n      }\n    };\n    xhr.open(\"GET\", uri, !this.sync);\n    xhr.send();\n  }\n\n  Fetcher.prototype.fetchScript = function(uri) {\n    if (!(uri in this.mapForUri)) {\n      this.sem.incr();\n      this.mapForUri[uri] = null;\n    } else {\n      return;\n    }\n\n    this.ajax(uri, this.onScriptLoad);\n  };\n\n  var absUrlRegex = new RegExp('^(?:[a-z]+:)?//', 'i');\n\n  Fetcher.prototype.onScriptLoad = function(xhr, uri) {\n    if (xhr.status === 200 || (uri.slice(0, 7) === \"file://\" && xhr.status === 0)) {\n      // find .map in file.\n      //\n      // attempt to find it at the very end of the file, but tolerate trailing\n      // whitespace inserted by some packers.\n      var match = xhr.responseText.match(\"//# [s]ourceMappingURL=(.*)[\\\\s]*$\", \"m\");\n      if (match && match.length === 2) {\n        // get the map\n        var mapUri = match[1];\n\n        var embeddedSourceMap = mapUri.match(\"data:application/json;(charset=[^;]+;)?base64,(.*)\");\n\n        if (embeddedSourceMap && embeddedSourceMap[2]) {\n          this.mapForUri[uri] = new source_map_consumer.SourceMapConsumer(atob(embeddedSourceMap[2]));\n          this.sem.decr();\n        } else {\n          if (!absUrlRegex.test(mapUri)) {\n            // relative url; according to sourcemaps spec is 'source origin'\n            var origin;\n            var lastSlash = uri.lastIndexOf('/');\n            if (lastSlash !== -1) {\n              origin = uri.slice(0, lastSlash + 1);\n              mapUri = origin + mapUri;\n              // note if lastSlash === -1, actual script uri has no slash\n              // somehow, so no way to use it as a prefix... we give up and try\n              // as absolute\n            }\n          }\n\n          this.ajax(mapUri, function(xhr) {\n            if (xhr.status === 200 || (mapUri.slice(0, 7) === \"file://\" && xhr.status === 0)) {\n              this.mapForUri[uri] = new source_map_consumer.SourceMapConsumer(xhr.responseText);\n            }\n            this.sem.decr();\n          });\n        }\n      } else {\n        // no map\n        this.sem.decr();\n      }\n    } else {\n      // HTTP error fetching uri of the script\n      this.sem.decr();\n    }\n  };\n\n  var processSourceMaps = function(lines, rows, mapForUri, traceFormat) {\n    var result = [];\n    var map;\n    var origName = traceFormat === \"chrome\" ? origNameChrome : origNameFirefox;\n    for (var i=0; i < lines.length; i++) {\n      var row = rows[i];\n      if (row) {\n        var uri = row[1];\n        var line = parseInt(row[2], 10);\n        var column = parseInt(row[3], 10);\n        map = mapForUri[uri];\n\n        if (map) {\n          // we think we have a map for that uri. call source-map library\n          var origPos = map.originalPositionFor(\n            { line: line, column: column });\n          result.push(formatOriginalPosition(origPos.source,\n            origPos.line, origPos.column, origPos.name || origName(lines[i])));\n        } else {\n          // we can't find a map for that url, but we parsed the row.\n          // reformat unchanged line for consistency with the sourcemapped\n          // lines.\n          result.push(formatOriginalPosition(uri, line, column, origName(lines[i])));\n        }\n      } else {\n        // we weren't able to parse the row, push back what we were given\n        result.push(lines[i]);\n      }\n    }\n\n    return result;\n  };\n\n  function origNameChrome(origLine) {\n    var match = / +at +([^ ]*).*/.exec(origLine);\n    return match && match[1];\n  }\n\n  function origNameFirefox(origLine) {\n    var match = /([^@]*)@.*/.exec(origLine);\n    return match && match[1];\n  }\n\n  var formatOriginalPosition = function(source, line, column, name) {\n    // mimic chrome's format\n    return \"    at \" + (name ? name : \"(unknown)\") +\n      \" (\" + source + \":\" + line + \":\" + column + \")\";\n  };\n\n  // xmlhttprequest boilerplate\n  var XMLHttpFactories = [\n\tfunction () {return new XMLHttpRequest();},\n\tfunction () {return new ActiveXObject(\"Msxml2.XMLHTTP\");},\n\tfunction () {return new ActiveXObject(\"Msxml3.XMLHTTP\");},\n\tfunction () {return new ActiveXObject(\"Microsoft.XMLHTTP\");}\n  ];\n\n  function createXMLHTTPObject() {\n      var xmlhttp = false;\n      for (var i=0;i<XMLHttpFactories.length;i++) {\n          try {\n              xmlhttp = XMLHttpFactories[i]();\n          }\n          catch (e) {\n              continue;\n          }\n          break;\n      }\n      return xmlhttp;\n  }\n\n  return {\n    mapStackTrace: mapStackTrace\n  }\n});\n"
  },
  {
    "path": "webpack.config.js",
    "content": "module.exports = {\n  context: __dirname,\n  entry: \"./sourcemapped-stacktrace.js\",\n  output: {\n    library: \"sourceMappedStackTrace\",\n    libraryTarget: \"umd\",\n    path: __dirname + \"/dist\",\n    filename: \"sourcemapped-stacktrace.js\"\n  }\n};\n"
  }
]