GithubHelp home page GithubHelp logo

evanw / node-source-map-support Goto Github PK

View Code? Open in Web Editor NEW
2.1K 2.1K 222.0 1.04 MB

Adds source map support to node.js (for stack traces)

License: MIT License

HTML 1.84% CoffeeScript 2.55% JavaScript 95.61%

node-source-map-support's Introduction

Source Map Support

Build Status

This module provides source map support for stack traces in node via the V8 stack trace API. It uses the source-map module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process.

Installation and Usage

Node support

Node >=12.12.0

This package is no longer required as Node 12.12.0 introduced the --enable-source-maps flag. (unless you're using the vm module, as --enable-source-maps does not work with vm.runInThisContext).

Node <12.12.0
$ npm install source-map-support

Source maps can be generated using libraries such as source-map-index-generator. Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler):

//# sourceMappingURL=path/to/source.map

If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be respected (e.g. if a file mentions the comment in code, or went through multiple transpilers). The path should either be absolute or relative to the compiled file.

From here you have two options.

CLI Usage
node -r source-map-support/register compiled.js
Programmatic Usage

Put the following line at the top of the compiled file.

require('source-map-support').install();

It is also possible to install the source map support directly by requiring the register module which can be handy with ES6:

import 'source-map-support/register'

// Instead of:
import sourceMapSupport from 'source-map-support'
sourceMapSupport.install()

Note: if you're using babel-register, it includes source-map-support already.

It is also very useful with Mocha:

$ mocha --require source-map-support/register tests/

Browser support

This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and Error.prototype.stack will be incorrect without this library. Everything will just work if you deploy your source files using browserify. Just make sure to pass the --debug flag to the browserify command so your source maps are included in the bundled code.

This library also works if you use another build process or just include the source files directly. In this case, include the file browser-source-map-support.js in your page and call sourceMapSupport.install(). It contains the whole library already bundled for the browser using browserify.

<script src="browser-source-map-support.js"></script>
<script>sourceMapSupport.install();</script>

This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like RequireJS. Just list browser-source-map-support as a dependency:

<script>
  define(['browser-source-map-support'], function(sourceMapSupport) {
    sourceMapSupport.install();
  });
</script>

Options

This module installs two things: a change to the stack property on Error objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer:

require('source-map-support').install({
  handleUncaughtExceptions: false
});

This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, Meteor keeps all source maps cached in memory to avoid disk access.

require('source-map-support').install({
  retrieveSourceMap: function(source) {
    if (source === 'compiled.js') {
      return {
        url: 'original.js',
        map: fs.readFileSync('compiled.js.map', 'utf8')
      };
    }
    return null;
  }
});

The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment. In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'.

require('source-map-support').install({
  environment: 'node'
});

To support files with inline source maps, the hookRequire options can be specified, which will monitor all source files for inline source maps.

require('source-map-support').install({
  hookRequire: true
});

This monkey patches the require module loading chain, so is not enabled by default and is not recommended for any sort of production usage.

Demos

Basic Demo

original.js:

throw new Error('test'); // This is the original code

compiled.js:

require('source-map-support').install();

throw new Error('test'); // This is the compiled code
// The next line defines the sourceMapping.
//# sourceMappingURL=compiled.js.map

compiled.js.map:

{
  "version": 3,
  "file": "compiled.js",
  "sources": ["original.js"],
  "names": [],
  "mappings": ";;AAAA,MAAM,IAAI"
}

Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js):

$ node compiled.js

original.js:1
throw new Error('test'); // This is the original code
      ^
Error: test
    at Object.<anonymous> (original.js:1:7)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

TypeScript Demo

demo.ts:

declare function require(name: string);
require('source-map-support').install();
class Foo {
  constructor() { this.bar(); }
  bar() { throw new Error('this is a demo'); }
}
new Foo();

Compile and run the file using the TypeScript compiler from the terminal:

$ npm install source-map-support typescript
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
$ node demo.js

demo.ts:5
  bar() { throw new Error('this is a demo'); }
                ^
Error: this is a demo
    at Foo.bar (demo.ts:5:17)
    at new Foo (demo.ts:4:24)
    at Object.<anonymous> (demo.ts:7:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

There is also the option to use -r source-map-support/register with typescript, without the need add the require('source-map-support').install() in the code base:

$ npm install source-map-support typescript
$ node_modules/typescript/bin/tsc  -sourcemap demo.ts
$ node -r source-map-support/register demo.js

demo.ts:5
  bar() { throw new Error('this is a demo'); }
                ^
Error: this is a demo
    at Foo.bar (demo.ts:5:17)
    at new Foo (demo.ts:4:24)
    at Object.<anonymous> (demo.ts:7:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:901:3

CoffeeScript Demo

demo.coffee:

require('source-map-support').install()
foo = ->
  bar = -> throw new Error 'this is a demo'
  bar()
foo()

Compile and run the file using the CoffeeScript compiler from the terminal:

$ npm install source-map-support coffeescript
$ node_modules/.bin/coffee --map --compile demo.coffee
$ node demo.js

demo.coffee:3
  bar = -> throw new Error 'this is a demo'
                     ^
Error: this is a demo
    at bar (demo.coffee:3:22)
    at foo (demo.coffee:4:3)
    at Object.<anonymous> (demo.coffee:5:1)
    at Object.<anonymous> (demo.coffee:1:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)

Tests

This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type mocha in the root directory). To run the manual tests:

License

This code is available under the MIT license.

node-source-map-support's People

Contributors

ardeois avatar dependabot[bot] avatar detachhead avatar evanw avatar fresheneesz avatar glasser avatar isaacs avatar joeyespo avatar josecolella avatar julien-f avatar kpdecker avatar kriszyp avatar ldesplat avatar legraphista avatar linusu avatar loicpoullain avatar marionebl avatar merott avatar mgroenhoff avatar michaelficarra avatar mohd-akram avatar mprobst avatar nickewansmith avatar pspeter3 avatar raine avatar scottweinstein avatar seanpoulter avatar simenb avatar timoxley avatar tomhughes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-source-map-support's Issues

Stack trace not clickable in webstorm

Hi,

I'm sure this is a tough issue and may not get priority to look into, but when i run node with source-map-support in webstorm (either from the terminal or as a run/debug configuration), the error references are not clickable to navigate to the source of the error.

Line numbers under Node are still wrong

I thought I had fixed this with 00cba19 but the fix was incorrect and relied on the last frame of the stack originating from module.js which is not always the case.

I am about to make a new PR which is much simpler and correctly handles evals.

Broken in Chrome 39+

It looks like the Chrome team did something funny in Chrome 39 (currently beta) that's breaking this library. It's also broken in Chrome 40 (Canary).

Repro steps:

git clone https://github.com/evanw/node-source-map-support.git
cd node-source-map-support
python -m SimpleHTTPServer 5544
open http://localhost:5544/browser-test/

See in the console:

Uncaught illegal access.

image

Source map support when running the bundle on a html reporter

Hey!, any ideas on how to make this work while uing the html reporter. My current setup has a local html file that is my reporter and that file I make it run either in the browser or in jenkins with https://github.com/metaskills/mocha-phantomjs which is very nice.
My problem is that if I try installing the node-source-map-support the reporter will complain since I'm trying to access local files from the browser, any suggestions for using this with this configuration?

I guess running a local tiny server would be a solution but wondering if there are other options for getting the source maps so it's more transparent.

Thanks!

Problem with sourceRoot when dealing with nested folder structure

Say that I have a project like this:

%project_root%
โ”œโ”€coffee
โ”‚  โ””โ”€sub_folder
โ”‚  โ”‚    โ””โ”€bar.coffee
โ”‚  โ””โ”€foo.coffee
โ”œโ”€js
โ”‚  โ””โ”€sub_folder
โ”‚  โ”‚    โ””โ”€bar.js
โ”‚  โ””โ”€foo.js
โ”œโ”€map
โ”‚  โ””โ”€sub_folder
โ”‚  โ”‚    โ””โ”€bar.js.map
โ”‚  โ””โ”€foo.js.map

If an error was thrown in bar.coffee, the source path would be wrong. There're several cases (tested on Windows, project folder is on drive X:):

sourceRoot Value Source path in error messages for foo.coffee Source path in error messages for sub_folder/bar.coffee
Not set %project_root%/map/foo.coffee %project_root%/map/sub_folder/bar.coffee
/src x:/src/foo.coffee x:/src/sub_folder/bar.coffee
./src %project_root%/map/src/foo.coffee %project_root%/map/src/sub_folder/bar.coffee
../src %project_root%/src/foo.coffee %project_root%/map/src/sub_folder/bar.coffee
__dirname + /src %project_root%/src/foo.coffee` %project_root%/src/sub_folder/bar.coffee

As you can see, only hard-code the absolute path of %project_root% will give us the correct behavior. But it is not very useful since those paths may not be valid on another system.

I think a possible solution would be to resolve sourceRoot path relative to map root instead of each map file's location (introduced by #4), when the sourceRoot is a relative path.

Unable to create multiple instances

It's possible that someone would need to install the module more than once to support different file retrievals. For example, using the babel CLI and it uses this module with in-memory source map look ups. However, someone that wants to add support for the rest of the application now can't. I propose removing the global overrides of retrieveFile, etc. and instead using an array of functions that resolve to the first supported.

Tests fail on Windows

Comparing stack traces containing file names fail on Windows because of backslashes in the filenames, and the carriage returns in the std(err|out)

How to troubleshoot when it has no effect?

When I throw an error, the stack trace line points to the built file, not the original one. (It makes no difference if I register source-map-support or not.)

I think everything is set up as per the instructions: I have a source map next to the built file, and a source mapping comment at the bottom of the built file that points to that source map. And the source map correctly points back to the original file. At the top of my script, I have require('source-map-support').install();. But it seems to have no effect.

Or maybe there is something wrong with my setup, but I can't tell. Is it possible to put source-map-support into some kind of 'strict' mode, so it errors noisily if it fails to find/parse a source map?

Synchronous XHR warning

When I source browser-source-map-support.js in Chrome 42, I get the following warning in the JS console:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.

sourcesContent is not supported

According to the spec, a source-map data can have a "sourcesContent" field to have all the source file contents in it.

Currently node-source-map-support does not support sourcesContent. Please consider to add its support.

Best,

Use with mocha

I'm trying to use your library with mocha. But I don't get it to work. I use Typescript and compile with source map support. And I require your library and install it as said in the docs before I run the mocha command.

async file access

If we're not going to exit the process, then we would want the file access to by async instead of sync. The sync file access could have a noticeable impact on a busy production server.

Remove the need to compile coffee to js?

Can I have souce-maps-support executing plain coffeescrit files?

myfile.coffee

do (require 'source-map-support').install

foo = ->
  throw new Error 'bar'

bash

coffee myfile.coffee

Automate tests in browsers

Currently browsers tests must be executed manually and are not integrated with Travis.

This is annoying to do and we often miss some failures when merging PRs.

api parity for node + browser (browser is missing .install() method)

right now there is no .install() method exposed on the browser version.

Please add this so the api is consistent across both platforms. If you have to add a stub "empty" .install() for browser, that'd be fine.

the reason why: I have a code.js file that runs in both browser and node, so having the api's be consistent is important (right now i get a null reference in browser when calling .install()

FYI, I do not use browserify, i am using AMD modules (and have amd modules working in node)

Stack trace URls not clickable

As noted in petkaantonov/bluebird#363, the file:line-number entries in the error stack trace generated by souce-map-support are not clickable in Chrome.

This is because source-map-support is generating:

Unhandled rejection Error: oops!
    at Route.willTransitionTo [as onEnter] (components/outcomes-component.js:29:21)

Instead of:

Unhandled rejection Error: oops!
    at Route.willTransitionTo [as onEnter] (http://localhost:8080/components/outcomes-component.js:29:21)

Prefixing the paths with the page origin should solve the problem.

Feature: Programmatically pass in stack string/object to be mapped

I'd like to distribute a node app, though I'm going to minify to obfuscate the source. I'd still like to be able to track down bugs though. I was going to PR this line: exports.wrapCallSite = wrapCallSite;, though maybe that's not that expose this functionality?

Browserify compatibility?

Hi, if possible this would be a great enhancement.

Currently Chrome doesn't seem to support .stack, would be great to have this working within the browser as well.

This is the error raised when doing:

sourceMapSupport = require('source-map-support')

source map stack trace 2

Any ideas if this would be possible?

Unnecessary when eval-ing CoffeeScript

CoffeeScriptRedux already maps back to the source when errors are throw while evaling a file.

$ cat demo.coffee
foo = ->
  bar = -> throw new Error 'this is a demo'
  bar()
foo()
$ bin/coffee -ei demo.coffee 

[redacted]/CoffeeScriptRedux/demo.coffee:7
      throw new Error('this is a demo');
            ^
Error: this is a demo
  at bar ([redacted]/CoffeeScriptRedux/demo.coffee:2:19, <js>:7:13)
  at foo ([redacted]/CoffeeScriptRedux/demo.coffee:3:3, <js>:9:12)
  at Object.<anonymous> ([redacted]/CoffeeScriptRedux/demo.coffee:4:3, <js>:11:3)
  at Object.<anonymous> ([redacted]/CoffeeScriptRedux/demo.coffee:4:6, <js>:12:3)
  at Module._compile (module.js:449:26)
  at runModule ([redacted]/CoffeeScriptRedux/lib/coffee-script/run.js:99:17)

$ 

Is there still a use for this in that case? Cool project, by the way.

Browser hangs on new Buffer(...).toString() for large source maps

Hello. Found this issue during investigation of #93. We're using webpack, so I'm guessing it might be related to webpack's Buffer browser polyfill? (I think it uses feross/buffer, which is what Browserify uses?)

For large source maps, the following line caused the browser (Chrome 44.0.2403.155 (64-bit)) to choke:

sourceMapData = new Buffer(rawData, "base64").toString();

I tweaked this to use window.atob when in the browser:

if (isInBrowser()) {
  sourceMapData = window.atob(rawData);
} else {
  sourceMapData = new Buffer(rawData, "base64").toString();
}

If you think that's a reasonable solution, I'm happy to set up a PR? (Haven't actually checked this change against the test suite yet though ๐Ÿ˜…)

mapSourcePosition returns invalid results when the line is not in the sourceMap

I have a custom compile-to-js language that automatically wraps the output in a universal module loader, among other things. This means that the generated JS file contains code and additional outer functions that are not present in the source.

For my simple compiler, these items have no translation in the map (I'm open to suggestions that this is not a good idea, but that is not the main focus here). Unfortunately, if the map does not contain a translation for a particular line, mapSourcePosition returns strange results:

> mapSourcePosition({
    source: "/home/simon/test/foo.js",
    line: 2,
    column: 2,
  }

Gives:

{
    source: "/home/simon/test"
    line: null,
    column: null,
}

This in turn results in strange stack traces with missing line numbers and directories instead of files:

TypeError: Object #<Object> has no method 'bar'
    at Object.define.test (/test/foo.jas:16:4)
    at Object.define (/home/simon/test)
    ...

3 possible ways this could be handled:

  1. Return the object like it does currently, but with a minor fix to keep the source set to null.
  2. Return null instead of any object.
  3. Return the source, line and column unmodified so the stack trace refers to the original file

In this specific case, the offending lines could be omitted from the stack trace completely, but this would seem like a bad idea in general.

Please note that I am calling mapSourcePosition directly, but the unhandledException event may need to change as well.

Thanks.

if require('coffee-script').register() is called after require('source-map-support').install() then source maps no longer function for exception traces

Here is the demo modified to demonstrate the issue:

require('source-map-support').install()
require("coffee-script").register()

foo = ->
  bar = -> throw new Error 'this is a demo'
  bar()
foo()

I encounter this problem because I have a module which is intended to 'require' some 'user' editable coffee-script configuration code -- if at any time after initializing source-map-support I later initialize the coffee-script support so that the node module loader can require .coffee files without pre-compiling, then the source-map-support exception rewriting behavior fails to function globally in my app ...

If I change the order the source-map-support and coffee-script modules are initialized in, then things work as expected:

require("coffee-script").register()
require('source-map-support').install()

foo = ->
  bar = -> throw new Error 'this is a demo'
  bar()
foo()

However this means I need to ensure that my process initializes the coffee-script module prior to initializing the source-map-support module -- even if enter my code through paths for which coffee-script support is not required at that time ... Particularly I encountered this issue when unit testing -- units tests give arbitrary entry points into my application's code where I wouldn't have thought I would need to initialize the coffee-script module unless/until its needed ... its a bit ugly that I must initialize coffee-script within the context of my unit tests so that I can enforce correct initialization order of the two modules ...

Is there a good workaround for this? The safest thing I can come up with is to add a new module which initializes both source-map-support and coffee-script in the correct order in my code -- and use that throughout my project's code anywhere I would've used require('source-map-support').install() ...

Application-provided "uncaughtException" handler ignored

I initially reported it here but was told to the problem applied to this project. My test case:

process.on('uncaughtException', function(error) {
  console.log("uncaught");
});                       
throw new Error("Argh");

With Node:

# node test.js                            
uncaught

With 6to5-node:

# 6to5-node test.js
/tmp/test.js:6
throw new Error("Argh");
      ^
Error: Argh
[...]

source-map-support uses deprecated XMLHttpRequest on main thread

FYI lately, Chrome warns me about something source-map-support does:

"Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."

It points to this bit of code:

function retrieveSourceMapURL(source) {
  var fileData;

  if (isInBrowser()) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', source, false);
    xhr.send(null);
    fileData = xhr.readyState === 4 ? xhr.responseText : null;

    // Support providing a sourceMappingURL via the SourceMap header
    var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
                          xhr.getResponseHeader("X-SourceMap");
    if (sourceMapHeader) {
      return sourceMapHeader;
    }
  }

Maybe this needs to be done differently in the future.

Refused to get unsafe header "SourceMap"

I'm trying to use this module in the browser in combination with bluebird and webpack.

I'm loading it via import 'source-map-support/register' and all builds fine but when I run the code in the browser I throws

Refused to get unsafe header "SourceMap"
Refused to get unsafe header "X-SourceMap"

any ideas what is going wrong here?

  • Chrome Version 43.0.2357.81 (64-bit) (Mac)
  • [email protected] node_modules/source-map-support

screen shot 2015-06-01 at 12 38 34
screen shot 2015-06-01 at 12 38 24

Incorrectly resolves absolute source mapping url as relative to file

The supportRelativeURL function always assumes mappings are relative, even when they may be an absolute URI.

Given:

  • Build 0.3.2 of source-map-support
  • a file of c:\dir\a.min.js
  • a url of file:///C:/dir/a.js

The result is C:\dir\file:\C:\dir\a.js when it should be C:\dir\a.js.

The issue stems from the fact node's path.resolve function does not interpret file URIs.

Why use Buffer as an implicit dependency?

โ˜๏ธ ๐Ÿ‘‰

sourceMapData = new Buffer(rawData, "base64").toString();

Background:
We (https://github.com/CartoDB/cartodb) suffered a Uncaught RangeError: Maximum call stack size exceeded exception on uncaught exceptions after upgrading browserify. I found some similar reported stuff here, e.g. #86 and #93, but after some investigation I found the culprit to be the implicit dependency of buffer used at the line above.

Since there's no reference to this module in this repo I presume that it's accessible through the browserify module? Considering it's a key piece for this module to work, why not define the dependency in this package?

That said, there's a fix but it's not yet released (v3.4.2), so my temporary workaround to this was to override the implicit dependency, see: https://github.com/CartoDB/cartodb/pull/5171/files The fix was released in buffer v3.4.2

cc @tanem who seem to have suffered similar issues, perhaps this also works for you

Regex RangeError for large sourcemaps

Hi. We're using webpack's devtool: #cheap-module-inline-source-map option to add an inline base64 encoded source map to the bottom of our main app file. There's a decent amount of code there, so the sourcemap is a pretty gigantic string.

We ended up seeing the following error in the console:

RangeError: Maximum call stack size exceeded
    at RegExp.exec (native)

Related to this regex:

var re = /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]+?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/)[ \t]*$)/mg;

Changing one character in the regex fixes the issue (...[^\s'"]+?... to ...[^\s'"]*?...):

var re = /(?:\/\/[@#][ \t]+sourceMappingURL=([^\s'"]*?)[ \t]*$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^\*]+?)[ \t]*(?:\*\/)[ \t]*$)/mg;

I haven't been able to figure out why that is yet though (e.g. I don't think there's any catastrophic backtracking going on in the original version?) ๐Ÿ˜•

Just wondering if anyone else can shed some light on this? Cheers. (PS this change also works for the version currently published to npm).

Source with inline sourcemaps

Hi,

I'm getting a different behavior with the same sourcemap either provided as external file or inline.
The external works well and provides an absolute path, the inline one just gives me the raw declaration.

Shouldn't this line be sourceMap.url || position.source ? At least it works consistently on my test.

Chrome Source Mapped Stack Debugging

Hi,

In Chrome, if one clicks on the filename-linenumber-column-number path in a stack trace, one is taken to that files under the sources tab, allowing easy debugging (setting breakpoints and such).

With source-map-support.browser.js included, the paths are correct (as per source map), but clicking them opens up the source file in a new tab.

Any way to rectify the behavior?

Best regards,
Oleg

are base64 dataurl's supported in sourceMappingURL?

Does node-source-map-support support inline sourcemaps encoded into data url's?

I'm writing ansible modules in javascript using webpack to package the javascript together into a standalone file. Ansible module's can be written in any language but must be contained in a single file -- hence the usage of webpack to run code on node ... It sounds strange perhaps, but its actually perfect for my usage and works well -- the only annoying thing is I haven't been able to get source-map to work for stack traces ...

Here's a simple example:

Input source:

require("source-map-support").install()

console.log("Hello");

throw Error("give me stack trace!")

And here's a gist showing what the webpack compiled version of the above src looks like ...

https://gist.githubusercontent.com/breathe/debf645ae49e5bd66768/raw/bab77313c1fde689645ff40e3b09fb768a3fb8b9/debug-sourcemap

Running the code in the gist above yields this output ... Any ideas?

Hello
Error: give me stack trace!
    at Error (native)
    at Object.eval (eval at <anonymous> (/Users/ncohen/software/ansible/sts-infrastructure/library/debug-sourcemap:49:2), <anonymous>:7:7)
    at Object.0 (/Users/ncohen/software/ansible/sts-infrastructure/library/debug-sourcemap:49:2)
    at __webpack_require__ (/Users/ncohen/software/ansible/sts-infrastructure/library/debug-sourcemap:21:30)
    at /Users/ncohen/software/ansible/sts-infrastructure/library/debug-sourcemap:41:18
    at Object.<anonymous> (/Users/ncohen/software/ansible/sts-infrastructure/library/debug-sourcemap:44:10)
    at Module._compile (module.js:430:26)
    at Object.Module._extensions..js (module.js:448:10)
    at Module.load (module.js:355:32)

Misleading sourceMappingURL detection within source

I append in transpiler the sourceMappingURL through the code...

code + '//# sourceMappingURL=' + sourcemap_path;

The sourceMappingURL match regexp detects it as url and tries to fetch "' + sourcemap_path;"... and for minified code is even worse...

Electron, nwjs and Brackets-Shell

Instead of detecting the browser I think that it would be better to detect a Node.js runtime since there are a number of projects that implements both.

This leads to uncaught exceptions not being fixed in Electron. Here is the offending line.

if (installHandler && !isInBrowser()) {
  process.on('uncaughtException', handleUncaughtExceptions);
}

It would be better to check for the process object:

if (installHandler && typeof process === 'object' && typeof process.on === 'function') {
  process.on('uncaughtException', handleUncaughtExceptions);
}

Can't get node-source-map-support to work on node

Me (and a colleague) have tried the basic demo from the readme in both node 0.12.7 and 0.10.38, but it doesn't show me the mapped stacktrace. The same occured when I integrated node-source-map-support in my project.

My stacktrace looks like this:

/tmp/smtest/compiled.js:3
throw new Error('test'); // This is the compiled code
      ^
Error: test
    at Object.<anonymous> (/tmp/smtest/compiled.js:3:7)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

Is this project broken or am I doing something wrong?

Integration with stack-chain

stack-chain provides a common stack to register functions manipulating (modifying, filtering or formatting) stack traces.

It is used by clarify and trace from the same author.

I wonder if using it could be a path to resolve conflicts with other libraries such as CoffeeScript (see #34).

TypeError: Cannot call method 'nameOrSourceURL' of undefined

Code:

require('source-map-support').install(handleUncaughtExceptions: false)
try
  f = new Function('x','return x+1)')
catch e
  console.info e.stack

will cause:

TypeError: Cannot call method 'nameOrSourceURL' of undefined
    at CallSiteGetEvalOrigin (native)
    at wrapCallSite (/Users/bearice/Projects/fanformed/www/node_modules/source-map-support/source-map-support.js:77:22)
    at /Users/bearice/Projects/fanformed/www/node_modules/source-map-support/source-map-support.js:104:26
    at Array.map (native)
    at Function.prepareStackTrace (/Users/bearice/Projects/fanformed/www/node_modules/source-map-support/source-map-support.js:103:24)
    at Object.<anonymous> (test.coffee:7:9)
    at Object.<anonymous> (test.coffee:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)

possilble fix:

Add a try-catch block at source-map-support.js:77

but i dont know why this happens since i didnt read V8's code

Invalid line numbers

Stack traces are producing incorrect line numbers.

Steps to reproduce:

uglifysanity.js:

console.log('1');
goober();
console.log('2');
console.log('3');
console.log('4');
console.log('5');

Then run it through uglify:

uglifyjs -c -m -o uglifysanity.min.js \
         --source-map uglifysanity.min.js.map \
         uglifysanity.js

Finally, test it in node:

require('source-map-support').install();
require('./uglifysanity.min');

And it produces this output:

.../uglifysanity.min.js:1
exports, require, module, __filename, __dirname) { console.log("1"),goober(),c
                                                                    ^

.../uglifysanity.js:6
console.log('5');                     <---------- Wrong line!
^
ReferenceError: goober is not defined
    at Object.<anonymous> (.../uglifysanity.js:6:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at [stdin]:5:1
    at Object.<anonymous> ([stdin]-wrapper:6:22)
    at Module._compile (module.js:456:26)

Expect this instead:

.../uglifysanity.js:2
goober();
^

In Chrome, this seems to work fine. Just not working in Node.js. I'm using [email protected] and [email protected] and Node v0.10.25.

Fragile isInBrowser test causes failures in node when window is stubbed

The isInBrowser test is too fragile and will break if anyone defines a global window object. This can happen when implementing other compatibility shims or for testing with jsdom, etc.

function isInBrowser() {
  return typeof window !== 'undefined';
}

This causes ReferenceError: XMLHttpRequest is not defined.

Checking against XMLHttpRequest would help in this specific case, but I'm still not sure of any proper convention for detecting browser vs node at runtime.

Thanks.

Publish a changelog and tag releases

It would be handy if this project published a changelog and tagged releases so I can easily see what has changed and upgrade to new versions.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.