From c50758519f67ee47cc5e1ff7a17c543bc3242eed Mon Sep 17 00:00:00 2001 From: Evan Wallace Date: Thu, 17 Jan 2013 23:56:20 -0800 Subject: [PATCH] initial commit --- README.md | 74 ++++++++++++++++++++++++ package.json | 14 +++++ source-map-support.js | 125 +++++++++++++++++++++++++++++++++++++++++ test.js | 128 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 341 insertions(+) create mode 100644 README.md create mode 100644 package.json create mode 100644 source-map-support.js create mode 100644 test.js diff --git a/README.md b/README.md new file mode 100644 index 0000000..336ee3c --- /dev/null +++ b/README.md @@ -0,0 +1,74 @@ +# Source Map Support + +This module provides source map support for stack traces in node via the [V8 stack trace API](http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi). It uses the [source-map](https://github.com/mozilla/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. This module takes effect globally and should be initialized by inserting a call to require('source-map-support') at the top of your code. + +### CoffeeScript Demo + +The following terminal commands show a stack trace in node with CoffeeScript filenames: + + $ cat > demo.coffee + + require 'source-map-support' + foo = -> + bar = -> throw new Error 'this is a demo' + bar() + foo() + + $ npm install source-map-support + $ git clone https://github.com/michaelficarra/CoffeeScriptRedux.git + $ cd CoffeeScriptRedux && npm install && cd .. + $ CoffeeScriptRedux/bin/coffee --js -i demo.coffee > demo.js + $ echo '//@ sourceMappingURL=demo.js.map' >> demo.js + $ CoffeeScriptRedux/bin/coffee --source-map -i demo.coffee > demo.js.map + $ node demo + + demo.coffee:4 + bar = -> throw new Error 'this is a demo' + ^ + Error: this is a demo + at bar (demo.coffee:4:19) + at foo (demo.coffee:5:3) + at Object. (demo.coffee:6:3) + at Object. (demo.coffee:6:6) + at Module._compile (module.js:449:26) + at Object.Module._extensions..js (module.js:467:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Module.runMain (module.js:492:10) + at process.startup.processNextTick.process._tickCallback (node.js:244:9) + +### TypeScript Demo + +The following terminal commands show a stack trace in node with TypeScript filenames: + + $ cat > demo.ts + + declare function require(name: string); + require('source-map-support'); + class Foo { + constructor() { this.bar(); } + bar() { throw new Error('this is a demo'); } + } + new Foo(); + + $ npm install source-map-support typescript + $ node_modules/typescript/bin/tsc -sourcemap demo.ts + $ node demo + + demo.ts:6 + bar() { throw new Error('this is a demo'); } + ^ + Error: this is a demo + at Foo.bar (demo.ts:6:16) + at new Foo (demo.ts:5:23) + at Object. (demo.ts:8) + at Module._compile (module.js:449:26) + at Object.Module._extensions..js (module.js:467:10) + at Module.load (module.js:356:32) + at Function.Module._load (module.js:312:12) + at Module.runMain (module.js:492:10) + at process.startup.processNextTick.process._tickCallback (node.js:244:9) + +### License + +This code is available under the [MIT license](http://opensource.org/licenses/MIT). diff --git a/package.json b/package.json new file mode 100644 index 0000000..35e5a23 --- /dev/null +++ b/package.json @@ -0,0 +1,14 @@ +{ + "name": "source-map-support", + "version": "0.1.0", + "main": "./source-map-support.js", + "scripts": { + "test": "node_modules/mocha/bin/mocha" + }, + "dependencies": { + "source-map": "0.1.8" + }, + "devDependencies": { + "mocha": "1.8.1" + } +} diff --git a/source-map-support.js b/source-map-support.js new file mode 100644 index 0000000..a8ff435 --- /dev/null +++ b/source-map-support.js @@ -0,0 +1,125 @@ +var SourceMapConsumer = require('source-map').SourceMapConsumer; +var path = require('path'); +var fs = require('fs'); + +function mapSourcePosition(cache, position) { + var sourceMap = cache[position.source]; + if (!sourceMap && fs.existsSync(position.source)) { + // Get the URL of the source map + var fileData = fs.readFileSync(position.source, 'utf8'); + var match = /\/\/@\s*sourceMappingURL=(.*)\s*$/.exec(fileData); + if (!match) return position; + var sourceMappingURL = match[1]; + + // Support source map URLs relative to the source URL + var dir = path.dirname(position.source); + sourceMappingURL = path.resolve(dir, sourceMappingURL); + + // Parse the source map + var sourceMap = cache[sourceMappingURL]; + if (!sourceMap && fs.existsSync(sourceMappingURL)) { + var sourceMapData = fs.readFileSync(sourceMappingURL, 'utf8'); + try { + sourceMap = new SourceMapConsumer(sourceMapData); + cache[position.source] = sourceMap; + } catch (e) { + } + } + } + return sourceMap ? sourceMap.originalPositionFor(position) : position; +} + +// Parses code generated by FormatEvalOrigin(), a function inside V8: +// https://code.google.com/p/v8/source/browse/trunk/src/messages.js +function mapEvalOrigin(cache, origin) { + // Most eval() calls are in this format + var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin); + if (match) { + var position = mapSourcePosition(cache, { + source: match[2], + line: match[3], + column: match[4] + }); + return 'eval at ' + match[1] + ' (' + position.source + ':' + + position.line + ':' + position.column + ')'; + } + + // Parse nested eval() calls using recursion + match = /^eval at ([^(]+) \((.+)\)$/.exec(origin); + if (match) { + return 'eval at ' + match[1] + ' (' + mapEvalOrigin(cache, match[2]) + ')'; + } + + // Make sure we still return useful information if we didn't find anything + return origin; +} + +function wrapCallSite(cache, frame) { + // Most call sites will return the source file from getFileName(), but code + // passed to eval() ending in "//@ sourceURL=..." will return the source file + // from getScriptNameOrSourceURL() instead + var source = frame.getFileName() || frame.getScriptNameOrSourceURL(); + if (source) { + var position = mapSourcePosition(cache, { + source: source, + line: frame.getLineNumber(), + column: frame.getColumnNumber() + }); + return { + __proto__: frame, + getFileName: function() { return position.source; }, + getLineNumber: function() { return position.line; }, + getColumnNumber: function() { return position.column; }, + getScriptNameOrSourceURL: function() { return position.source; } + }; + } + + // Code called using eval() needs special handling + var origin = frame.getEvalOrigin(); + if (origin) { + origin = mapEvalOrigin(cache, origin); + return { + __proto__: frame, + getEvalOrigin: function() { return origin; } + }; + } + + // If we get here then we were unable to change the source position + return frame; +} + +// This function is part of the V8 stack trace API, for more info see: +// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi +Error.prepareStackTrace = function(error, stack) { + // Store source maps in a cache so we don't load them more than once when + // formatting a single stack trace (don't cache them forever though in case + // the files change on disk and the user wants to see the updated mapping) + var cache = {}; + return error + stack.map(function(frame) { + return '\n at ' + wrapCallSite(cache, frame); + }).join(''); +}; + +// Mimic node's stack trace printing when an exception escapes the process +process.on('uncaughtException', function(error) { + var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack); + if (match) { + var cache = {}; + var position = mapSourcePosition(cache, { + source: match[1], + line: match[2], + column: match[3] + }); + if (fs.existsSync(position.source)) { + var contents = fs.readFileSync(position.source, 'utf8'); + var line = contents.split(/(?:\r\n|\r|\n)/)[position.line - 1]; + if (line) { + console.log('\n' + position.source + ':' + position.line); + console.log(line); + console.log(new Array(+position.column).join(' ') + '^'); + } + } + } + console.log(error.stack); + process.exit(); +}); diff --git a/test.js b/test.js new file mode 100644 index 0000000..b970c23 --- /dev/null +++ b/test.js @@ -0,0 +1,128 @@ +require('./source-map-support'); + +var SourceMapGenerator = require('source-map').SourceMapGenerator; +var assert = require('assert'); +var fs = require('fs'); + +// Create a source map +var sourceMap = new SourceMapGenerator({ + file: '.generated.js', + sourceRoot: '.' +}); +for (var i = 1; i <= 100; i++) { + sourceMap.addMapping({ + generated: { line: i, column: 1 }, + original: { line: 1000 + i, column: 100 + i }, + source: 'line' + i + '.js' + }); +} + +function compareStackTrace(source, expected) { + fs.writeFileSync('.generated.js.map', sourceMap); + fs.writeFileSync('.generated.js', 'exports.test = function() {' + + source.join('\n') + '};//@ sourceMappingURL=.generated.js.map'); + try { + delete require.cache[require.resolve('./.generated')]; + require('./.generated').test(); + } catch (e) { + expected = expected.join('\n'); + assert.equal(e.stack.slice(0, expected.length), expected); + } + fs.unlinkSync('.generated.js'); + fs.unlinkSync('.generated.js.map'); +} + +it('normal throw', function() { + compareStackTrace([ + 'throw new Error("test");' + ], [ + 'Error: test', + ' at Object.exports.test (./line1.js:1001:101)' + ]); +}); + +it('throw inside function', function() { + compareStackTrace([ + 'function foo() {', + ' throw new Error("test");', + '}', + 'foo();' + ], [ + 'Error: test', + ' at foo (./line2.js:1002:102)', + ' at Object.exports.test (./line4.js:1004:104)' + ]); +}); + +it('throw inside function inside function', function() { + compareStackTrace([ + 'function foo() {', + ' function bar() {', + ' throw new Error("test");', + ' }', + ' bar();', + '}', + 'foo();' + ], [ + 'Error: test', + ' at bar (./line3.js:1003:103)', + ' at foo (./line5.js:1005:105)', + ' at Object.exports.test (./line7.js:1007:107)' + ]); +}); + +it('eval', function() { + compareStackTrace([ + 'eval("throw new Error(\'test\')");' + ], [ + 'Error: test', + ' at Object.eval (eval at (./line1.js:1001:101))', + ' at Object.exports.test (./line1.js:1001:101)' + ]); +}); + +it('eval inside eval', function() { + compareStackTrace([ + 'eval("eval(\'throw new Error(\\"test\\")\')");' + ], [ + 'Error: test', + ' at Object.eval (eval at (eval at (./line1.js:1001:101)))', + ' at Object.eval (eval at (./line1.js:1001:101))', + ' at Object.exports.test (./line1.js:1001:101)' + ]); +}); + +it('eval inside function', function() { + compareStackTrace([ + 'function foo() {', + ' eval("throw new Error(\'test\')");', + '}', + 'foo();' + ], [ + 'Error: test', + ' at eval (eval at foo (./line2.js:1002:102))', + ' at foo (./line2.js:1002:102)', + ' at Object.exports.test (./line4.js:1004:104)' + ]); +}); + +it('eval with sourceURL', function() { + compareStackTrace([ + 'eval("throw new Error(\'test\')//@ sourceURL=sourceURL.js");' + ], [ + 'Error: test', + ' at Object.eval (sourceURL.js:1:7)', + ' at Object.exports.test (./line1.js:1001:101)' + ]); +}); + +it('eval with sourceURL inside eval', function() { + compareStackTrace([ + 'eval("eval(\'throw new Error(\\"test\\")//@ sourceURL=sourceURL.js\')");' + ], [ + 'Error: test', + ' at Object.eval (sourceURL.js:1:7)', + ' at Object.eval (eval at (./line1.js:1001:101))', + ' at Object.exports.test (./line1.js:1001:101)' + ]); +});