Giter Site home page Giter Site logo

source-map's Introduction

Source Map

NPM

This is a library to generate and consume the source map format described here.

Use with Node

$ npm install source-map

Use on the Web

<script src="https://unpkg.com/[email protected]/dist/source-map.js"></script>
<script>
  sourceMap.SourceMapConsumer.initialize({
    "lib/mappings.wasm": "https://unpkg.com/[email protected]/lib/mappings.wasm",
  });
</script>

Table of Contents

Examples

Consuming a source map

const rawSourceMap = {
  version: 3,
  file: "min.js",
  names: ["bar", "baz", "n"],
  sources: ["one.js", "two.js"],
  sourceRoot: "http://example.com/www/js/",
  mappings:
    "CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA",
};

const whatever = await SourceMapConsumer.with(rawSourceMap, null, consumer => {
  console.log(consumer.sources);
  // [ 'http://example.com/www/js/one.js',
  //   'http://example.com/www/js/two.js' ]

  console.log(
    consumer.originalPositionFor({
      line: 2,
      column: 28,
    })
  );
  // { source: 'http://example.com/www/js/two.js',
  //   line: 2,
  //   column: 10,
  //   name: 'n' }

  console.log(
    consumer.generatedPositionFor({
      source: "http://example.com/www/js/two.js",
      line: 2,
      column: 10,
    })
  );
  // { line: 2, column: 28 }

  consumer.eachMapping(function (m) {
    // ...
  });

  return computeWhatever();
});

Generating a source map

In depth guide: Compiling to JavaScript, and Debugging with Source Maps

With SourceNode (high level API)

function compile(ast) {
  switch (ast.type) {
    case "BinaryExpression":
      return new SourceNode(
        ast.location.line,
        ast.location.column,
        ast.location.source,
        [compile(ast.left), " + ", compile(ast.right)]
      );
    case "Literal":
      return new SourceNode(
        ast.location.line,
        ast.location.column,
        ast.location.source,
        String(ast.value)
      );
    // ...
    default:
      throw new Error("Bad AST");
  }
}

var ast = parse("40 + 2", "add.js");
console.log(
  compile(ast).toStringWithSourceMap({
    file: "add.js",
  })
);
// { code: '40 + 2',
//   map: [object SourceMapGenerator] }

With SourceMapGenerator (low level API)

var map = new SourceMapGenerator({
  file: "source-mapped.js",
});

map.addMapping({
  generated: {
    line: 10,
    column: 35,
  },
  source: "foo.js",
  original: {
    line: 33,
    column: 2,
  },
  name: "christopher",
});

console.log(map.toString());
// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'

API

Get a reference to the module:

// Node.js
var sourceMap = require("source-map");

// Browser builds
var sourceMap = window.sourceMap;

// Inside Firefox
const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");

SourceMapConsumer

A SourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source.

SourceMapConsumer.initialize(options)

When using SourceMapConsumer outside of node.js, for example on the Web, it needs to know from what URL to load lib/mappings.wasm. You must inform it by calling initialize before constructing any SourceMapConsumers.

The options object has the following properties:

  • "lib/mappings.wasm": A String containing the URL of the lib/mappings.wasm file, or an ArrayBuffer with the contents of lib/mappings.wasm.
sourceMap.SourceMapConsumer.initialize({
  "lib/mappings.wasm": "https://example.com/source-map/lib/mappings.wasm",
});

new SourceMapConsumer(rawSourceMap)

The only parameter is the raw source map (either as a string which can be JSON.parse'd, or an object). According to the spec, source maps have the following attributes:

  • version: Which version of the source map spec this map is following.

  • sources: An array of URLs to the original source files.

  • names: An array of identifiers which can be referenced by individual mappings.

  • sourceRoot: Optional. The URL root from which all sources are relative.

  • sourcesContent: Optional. An array of contents of the original source files.

  • mappings: A string of base64 VLQs which contain the actual mappings.

  • file: Optional. The generated filename this source map is associated with.

  • x_google_ignoreList: Optional. An additional extension field which is an array of indices refering to urls in the sources array. This is used to identify third-party sources, that the developer might want to avoid when debugging. Read more

The promise of the constructed souce map consumer is returned.

When the SourceMapConsumer will no longer be used anymore, you must call its destroy method.

const consumer = await new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
doStuffWith(consumer);
consumer.destroy();

Alternatively, you can use SourceMapConsumer.with to avoid needing to remember to call destroy.

SourceMapConsumer.with

Construct a new SourceMapConsumer from rawSourceMap and sourceMapUrl (see the SourceMapConsumer constructor for details. Then, invoke the async function f(SourceMapConsumer) -> T with the newly constructed consumer, wait for f to complete, call destroy on the consumer, and return f's return value.

You must not use the consumer after f completes!

By using with, you do not have to remember to manually call destroy on the consumer, since it will be called automatically once f completes.

const xSquared = await SourceMapConsumer.with(
  myRawSourceMap,
  null,
  async function (consumer) {
    // Use `consumer` inside here and don't worry about remembering
    // to call `destroy`.

    const x = await whatever(consumer);
    return x * x;
  }
);

// You may not use that `consumer` anymore out here; it has
// been destroyed. But you can use `xSquared`.
console.log(xSquared);

SourceMapConsumer.prototype.destroy()

Free this source map consumer's associated wasm data that is manually-managed.

consumer.destroy();

Alternatively, you can use SourceMapConsumer.with to avoid needing to remember to call destroy.

SourceMapConsumer.prototype.computeColumnSpans()

Compute the last column for each generated mapping. The last column is inclusive.

// Before:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" });
// [ { line: 2,
//     column: 1 },
//   { line: 2,
//     column: 10 },
//   { line: 2,
//     column: 20 } ]

consumer.computeColumnSpans();

// After:
consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" });
// [ { line: 2,
//     column: 1,
//     lastColumn: 9 },
//   { line: 2,
//     column: 10,
//     lastColumn: 19 },
//   { line: 2,
//     column: 20,
//     lastColumn: Infinity } ]

SourceMapConsumer.prototype.originalPositionFor(generatedPosition)

Returns the original source, line, and column information for the generated source's line and column positions provided. The only argument is an object with the following properties:

  • line: The line number in the generated source. Line numbers in this library are 1-based (note that the underlying source map specification uses 0-based line numbers -- this library handles the translation).

  • column: The column number in the generated source. Column numbers in this library are 0-based.

  • bias: Either SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND. Specifies whether to return the closest element that is smaller than or greater than the one we are searching for, respectively, if the exact element cannot be found. Defaults to SourceMapConsumer.GREATEST_LOWER_BOUND.

and an object is returned with the following properties:

  • source: The original source file, or null if this information is not available.

  • line: The line number in the original source, or null if this information is not available. The line number is 1-based.

  • column: The column number in the original source, or null if this information is not available. The column number is 0-based.

  • name: The original identifier, or null if this information is not available.

consumer.originalPositionFor({ line: 2, column: 10 });
// { source: 'foo.coffee',
//   line: 2,
//   column: 2,
//   name: null }

consumer.originalPositionFor({
  line: 99999999999999999,
  column: 999999999999999,
});
// { source: null,
//   line: null,
//   column: null,
//   name: null }

SourceMapConsumer.prototype.generatedPositionFor(originalPosition)

Returns the generated line and column information for the original source, line, and column positions provided. The only argument is an object with the following properties:

  • source: The filename of the original source.

  • line: The line number in the original source. The line number is 1-based.

  • column: The column number in the original source. The column number is 0-based.

and an object is returned with the following properties:

  • line: The line number in the generated source, or null. The line number is 1-based.

  • column: The column number in the generated source, or null. The column number is 0-based.

consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 });
// { line: 1,
//   column: 56 }

SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)

Returns all generated line and column information for the original source, line, and column provided. If no column is provided, returns all mappings corresponding to a either the line we are searching for or the next closest line that has any mappings. Otherwise, returns all mappings corresponding to the given line and either the column we are searching for or the next closest column that has any offsets.

The only argument is an object with the following properties:

  • source: The filename of the original source.

  • line: The line number in the original source. The line number is 1-based.

  • column: Optional. The column number in the original source. The column number is 0-based.

and an array of objects is returned, each with the following properties:

  • line: The line number in the generated source, or null. The line number is 1-based.

  • column: The column number in the generated source, or null. The column number is 0-based.

consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" });
// [ { line: 2,
//     column: 1 },
//   { line: 2,
//     column: 10 },
//   { line: 2,
//     column: 20 } ]

SourceMapConsumer.prototype.hasContentsOfAllSources()

Return true if we have the embedded source content for every source listed in the source map, false otherwise.

In other words, if this method returns true, then consumer.sourceContentFor(s) will succeed for every source s in consumer.sources.

// ...
if (consumer.hasContentsOfAllSources()) {
  consumerReadyCallback(consumer);
} else {
  fetchSources(consumer, consumerReadyCallback);
}
// ...

SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])

Returns the original source content for the source provided. The only argument is the URL of the original source file.

If the source content for the given source is not found, then an error is thrown. Optionally, pass true as the second param to have null returned instead.

consumer.sources;
// [ "my-cool-lib.clj" ]

consumer.sourceContentFor("my-cool-lib.clj");
// "..."

consumer.sourceContentFor("this is not in the source map");
// Error: "this is not in the source map" is not in the source map

consumer.sourceContentFor("this is not in the source map", true);
// null

SourceMapConsumer.prototype.eachMapping(callback, context, order)

Iterate over each mapping between an original source/line/column and a generated line/column in this source map.

  • callback: The function that is called with each mapping. Mappings have the form { source, generatedLine, generatedColumn, originalLine, originalColumn, name }

  • context: Optional. If specified, this object will be the value of this every time that callback is called.

  • order: Either SourceMapConsumer.GENERATED_ORDER or SourceMapConsumer.ORIGINAL_ORDER. Specifies whether you want to iterate over the mappings sorted by the generated file's line/column order or the original's source/line/column order, respectively. Defaults to SourceMapConsumer.GENERATED_ORDER.

consumer.eachMapping(function (m) {
  console.log(m);
});
// ...
// { source: 'illmatic.js',
//   generatedLine: 1,
//   generatedColumn: 0,
//   originalLine: 1,
//   originalColumn: 0,
//   name: null }
// { source: 'illmatic.js',
//   generatedLine: 2,
//   generatedColumn: 0,
//   originalLine: 2,
//   originalColumn: 0,
//   name: null }
// ...

SourceMapGenerator

An instance of the SourceMapGenerator represents a source map which is being built incrementally.

new SourceMapGenerator([startOfSourceMap])

You may pass an object with the following properties:

  • file: The filename of the generated source that this source map is associated with.

  • sourceRoot: A root for all relative URLs in this source map.

  • skipValidation: Optional. When true, disables validation of mappings as they are added. This can improve performance but should be used with discretion, as a last resort. Even then, one should avoid using this flag when running tests, if possible.

var generator = new sourceMap.SourceMapGenerator({
  file: "my-generated-javascript-file.js",
  sourceRoot: "http://example.com/app/js/",
});

SourceMapGenerator.fromSourceMap(sourceMapConsumer)

Creates a new SourceMapGenerator from an existing SourceMapConsumer instance.

  • sourceMapConsumer The SourceMap.
var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);

SourceMapGenerator.prototype.addMapping(mapping)

Add a single mapping from original source line and column to the generated source's line and column for this source map being created. The mapping object should have the following properties:

  • generated: An object with the generated line and column positions.

  • original: An object with the original line and column positions.

  • source: The original source file (relative to the sourceRoot).

  • name: An optional original token name for this mapping.

generator.addMapping({
  source: "module-one.scm",
  original: { line: 128, column: 0 },
  generated: { line: 3, column: 456 },
});

SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)

Set the source content for an original source file.

  • sourceFile the URL of the original source file.

  • sourceContent the content of the source file.

generator.setSourceContent(
  "module-one.scm",
  fs.readFileSync("path/to/module-one.scm")
);

SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])

Applies a SourceMap for a source file to the SourceMap. Each mapping to the supplied source file is rewritten using the supplied SourceMap. Note: The resolution for the resulting mappings is the minimum of this map and the supplied map.

  • sourceMapConsumer: The SourceMap to be applied.

  • sourceFile: Optional. The filename of the source file. If omitted, sourceMapConsumer.file will be used, if it exists. Otherwise an error will be thrown.

  • sourceMapPath: Optional. The dirname of the path to the SourceMap to be applied. If relative, it is relative to the SourceMap.

    This parameter is needed when the two SourceMaps aren't in the same directory, and the SourceMap to be applied contains relative source paths. If so, those relative source paths need to be rewritten relative to the SourceMap.

    If omitted, it is assumed that both SourceMaps are in the same directory, thus not needing any rewriting. (Supplying '.' has the same effect.)

SourceMapGenerator.prototype.toString()

Renders the source map being generated to a string.

generator.toString();
// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'

SourceNode

SourceNodes provide a way to abstract over interpolating and/or concatenating snippets of generated JavaScript source code, while maintaining the line and column information associated between those snippets and the original source code. This is useful as the final intermediate representation a compiler might use before outputting the generated JS and source map.

new SourceNode([line, column, source[, chunk[, name]]])

  • line: The original line number associated with this source node, or null if it isn't associated with an original line. The line number is 1-based.

  • column: The original column number associated with this source node, or null if it isn't associated with an original column. The column number is 0-based.

  • source: The original source's filename; null if no filename is provided.

  • chunk: Optional. Is immediately passed to SourceNode.prototype.add, see below.

  • name: Optional. The original identifier.

var node = new SourceNode(1, 2, "a.cpp", [
  new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
  new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
  new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
]);

SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])

Creates a SourceNode from generated code and a SourceMapConsumer.

  • code: The generated code

  • sourceMapConsumer The SourceMap for the generated code

  • relativePath The optional path that relative sources in sourceMapConsumer should be relative to.

const consumer = await new SourceMapConsumer(
  fs.readFileSync("path/to/my-file.js.map", "utf8")
);
const node = SourceNode.fromStringWithSourceMap(
  fs.readFileSync("path/to/my-file.js"),
  consumer
);

SourceNode.prototype.add(chunk)

Add a chunk of generated JS to this source node.

  • chunk: A string snippet of generated JS code, another instance of SourceNode, or an array where each member is one of those things.
node.add(" + ");
node.add(otherNode);
node.add([leftHandOperandNode, " + ", rightHandOperandNode]);

SourceNode.prototype.prepend(chunk)

Prepend a chunk of generated JS to this source node.

  • chunk: A string snippet of generated JS code, another instance of SourceNode, or an array where each member is one of those things.
node.prepend("/** Build Id: f783haef86324gf **/\n\n");

SourceNode.prototype.setSourceContent(sourceFile, sourceContent)

Set the source content for a source file. This will be added to the SourceMap in the sourcesContent field.

  • sourceFile: The filename of the source file

  • sourceContent: The content of the source file

node.setSourceContent(
  "module-one.scm",
  fs.readFileSync("path/to/module-one.scm")
);

SourceNode.prototype.walk(fn)

Walk over the tree of JS snippets in this node and its children. The walking function is called once for each snippet of JS and is passed that snippet and the its original associated source's line/column location.

  • fn: The traversal function.
var node = new SourceNode(1, 2, "a.js", [
  new SourceNode(3, 4, "b.js", "uno"),
  "dos",
  ["tres", new SourceNode(5, 6, "c.js", "quatro")],
]);

node.walk(function (code, loc) {
  console.log("WALK:", code, loc);
});
// WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
// WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
// WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }

SourceNode.prototype.walkSourceContents(fn)

Walk over the tree of SourceNodes. The walking function is called for each source file content and is passed the filename and source content.

  • fn: The traversal function.
var a = new SourceNode(1, 2, "a.js", "generated from a");
a.setSourceContent("a.js", "original a");
var b = new SourceNode(1, 2, "b.js", "generated from b");
b.setSourceContent("b.js", "original b");
var c = new SourceNode(1, 2, "c.js", "generated from c");
c.setSourceContent("c.js", "original c");

var node = new SourceNode(null, null, null, [a, b, c]);
node.walkSourceContents(function (source, contents) {
  console.log("WALK:", source, ":", contents);
});
// WALK: a.js : original a
// WALK: b.js : original b
// WALK: c.js : original c

SourceNode.prototype.join(sep)

Like Array.prototype.join except for SourceNodes. Inserts the separator between each of this source node's children.

  • sep: The separator.
var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
var operand = new SourceNode(3, 4, "a.rs", "=");
var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");

var node = new SourceNode(null, null, null, [lhs, operand, rhs]);
var joinedNode = node.join(" ");

SourceNode.prototype.replaceRight(pattern, replacement)

Call String.prototype.replace on the very right-most source snippet. Useful for trimming white space from the end of a source node, etc.

  • pattern: The pattern to replace.

  • replacement: The thing to replace the pattern with.

// Trim trailing white space.
node.replaceRight(/\s*$/, "");

SourceNode.prototype.toString()

Return the string representation of this source node. Walks over the tree and concatenates all the various snippets together to one string.

var node = new SourceNode(1, 2, "a.js", [
  new SourceNode(3, 4, "b.js", "uno"),
  "dos",
  ["tres", new SourceNode(5, 6, "c.js", "quatro")],
]);

node.toString();
// 'unodostresquatro'

SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])

Returns the string representation of this tree of source nodes, plus a SourceMapGenerator which contains all the mappings between the generated and original sources.

The arguments are the same as those to new SourceMapGenerator.

var node = new SourceNode(1, 2, "a.js", [
  new SourceNode(3, 4, "b.js", "uno"),
  "dos",
  ["tres", new SourceNode(5, 6, "c.js", "quatro")],
]);

node.toStringWithSourceMap({ file: "my-output-file.js" });
// { code: 'unodostresquatro',
//   map: [object SourceMapGenerator] }

source-map's People

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  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

source-map's Issues

Only generate a mapping at a generated location for the most specific mapping

If we have the following mappings, should we generate them all in the source map or only the most specific mapping?

map.addMapping({
  generated: { line: 3, column: 5 }
});
map.addMapping({
  generated: { line: 3, column: 5 },
  original: { line: 6, column: 7 },
  source: 'foo.js'
});
map.addMapping({
  generated: { line: 3, column: 5 },
  original: { line: 6, column: 7 },
  source: 'foo.js',
  name: 'bar'
});

What should be the behavior if there is different original locations for the same generated position? Should we still use the most specific/detailed mapping and ignore the others?

Release new version

Hello,

could you please release a new version to NPM?

I'm trying to use SourceMapConsumer.prototype.generatedPositionFor as per published documentation, it's present in source code but not in currently published version.

Thanks.

Add more strict checks for `_sourceRoot` in `SourceMapGenerator`

We should be using == null so that only null and undefined don't pass the check, because someone could have a directory "0" as the source root and that would fail as it is now.

Don't need to worry about _sourcesContents because it is either null or an object and so implicit coercion to bool is fine.

cc @lydell

Clarify the minimum node version

There is a bit of a disconnect between the npm minimum node version and the readme version, 0.8 and 0.4 respectively. This is causing issues with uglify2 that otherwise would have a lower than 0.8 supported version.

Ideally the npm version could be reduced to a version prior to 0.8 but otherwise it would be helpful to have the same version listed in both locations.

MIT license

Can you add an MIT license to this package.

Question: does this module allow any kind of browser-side usage?

I'm trying to see if there's a way to use sourcemap info programatically in javascript on the browser-side. Specifically, exceptions still come out with the unmapped files and lines of code in the trace. I'd like to be able to convert those. Does this module provide any way to do this browser-side?

Ignore duplicate mappings in SourceMapGenerator.prototype.addMapping

Quoting @mishoo:

Let's take this statement: a = 1, the AST
hierarchy for it is something like:

AST_SimpleStatement {
body: AST_Assign {
left: AST_SymbolRef (a)
operator: "="
right: AST_Number (1)
}
}

If I output mapping for all nodes, we'll have a duplicate because the
AST_SimpleStatement's start token is a, which is the same start
token in fact for the AST_Assign and for the AST_SymbolRef. So I'd
output, say, 0,0->0,0 (name: "a") three times.

Is there an easy way to access the JS source map linked in a file as a JS object?

this is a question and not a bug, so please close as not relevant if you think so

In your example file, you show:

var smc = new SourceMapConsumer(rawSourceMap);

now, i have my source map file referenced in the js source as:

[js source code]
//@ sourceMappingURL=auth.js.map

is there a way to access the source map programatically, other than to

  1. load the js file with an xhr
  2. parse out the source url
  3. load the source url with xhr
  4. JSON.parse(sourceMap)

My question is if there's easier way, like an API myScriptTag.getSourceMap() or something other obvious i'm missing here?

Backward incompatible change in 0.1.33 breaks UglifyJS2 (and others?)

This commit causes this issue in UglifyJS2

Even the commit message says this is a backward-incompatible change. It breaks semantic versioning expectations such as UJS which depend on ~0.1.31 and assume no backward-incompatible changes.

Is it possible to revert this commit and release a 0.1.34, then start a new 0.2.0 with this commit?

(I'm not usually such a stickler for standards, but in the event that @mishoo neither fixes UJS to work with [email protected] nor fixes his dependency to [email protected], I'd like to be able to continue using UJS for my own project without having to resort to npm-shrinkwrap.)

Public interface to generated/source mappings

Is it possible to expose a public interface to the parsed mappings from SourceMapConsumer? I am working on a tool where I need to iterate over every mapping defined by a source map, and I would rather not deal with parsing myself, since it is already implemented in this project.

Example on using sourcemaps

Am I missing something as I can't seem to understand from the README on how to use the module to generate sourcemaps.

Can someone point me on how to use this module to generate sourcemaps?

`originalPositionFor(generatedPosition)` fails on string positions

I was sending in strings instead of numbers to the originalPositionFor function. This works unless the strings aren't exactly in the mappings. E.g. originalPositionFor({line:"8", column:"10"}) would work if the sourcemap contained that exact entry, but if it instead contained line 8, column 8 and line 8 column 12, it wouldn't find the sourcemap.

Please mention that line and column MUST be number (not strings) in the readme documentation.

Wrong sourceRoot handling?

From the spec:

Line 4: An optional source root, useful for relocating source files on a server or removing repeated values in the “sources” entry. This value is prepended to the individual entries in the “source” field.

The spec say that the sourceRoot is prepended, but mozilla/source-map concat it with an additional slash /.

Source Map version 3 support?

Just curious if source map version 3 support is on the roadmap? I ran across this error when trying to use source-map with a map that was generated using coffeescript 1.6.2:

Error: Unsupported version: 3
    at Object.SourceMapConsumer (/Users/smithclay/Dropbox/Code/sourcemap-proxy/node_modules/source-map/lib/source-map/source-map-consumer.js:62:13)
    at repl:1:35
    at REPLServer.self.eval (repl.js:111:21)
    at rli.on.e (repl.js:260:20)
    at REPLServer.self.eval (repl.js:118:5)
    at Interface.<anonymous> (repl.js:250:12)
    at Interface.EventEmitter.emit (events.js:88:17)
    at Interface._onLine (readline.js:199:10)
    at Interface._line (readline.js:517:8)
    at Interface._ttyWrite (readline.js:735:14)

Thanks!

support `sourcesContent` section

From the spec:

An optional list of source content, useful when the “source” can’t be hosted. The contents are listed in the same order as the sources in line 5. “null” may be used of some original sources should be retrieved by name.

Add check that URLs don't contain Windows path separators (`\`)

On widows file paths will include \ instead of / and source-map doesn’t convert slashes, but source map will work only with UNIX slashes.

We can fix it in app, but I think, that we need to fix it here, because every source-map node.js user must to repeat this fix.

Autoprefixer issue: nDmitry/grunt-autoprefixer#25

I can helps with PR, but how we should do this? Try to load path (it wil be in node.js and browserfy) and if path.sep == "\\" replace all \ to /?

Build instructions fail

Any hints?

$ node Makefile.dryice.js

module.js:340
throw err;
^
Error: Cannot find module 'dryice'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/work/source-map/Makefile.dryice.js:9:12)
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)

Modifying SourceMapGenerator mappings after creation

I'm running into an issue where there is no way to modify a mapping after addMapping(). I would like to be able to prepend some code to my JS string, and update the entire mapping (shift down by X lines and/or shift the first line over by Y columns). There does not appear to be any way to do this. I can code up a little function that does that, if you think it would be useful for others.

Null check should be undefined check?

In source-node.js:

if (aChunks !== null) this.add(aChunks);

from

function SourceNode(aLine, aColumn, aSource, aChunks) {
this.children = [];
this.line = aLine;
this.column = aColumn;
this.source = aSource;
if (aChunks !== null) this.add(aChunks);
}

If we call this function thus:
var n = new SourceNode(l, c, s);
the code calls add with 'undefined'.

This causes test-source-node.js to fail.

run-tests-in-browser.html:86test-source-node.js: test .add()
run-tests-in-browser.html:87--------------------------------------------------------------------------------
run-tests-in-browser.html:88TypeError: Expected a SourceNode, string, or an array of SourceNodes and strings. Got undefined
at SourceNode.SourceNode_add as add
at new SourceNode (http://localhost:8080/file/c/lib/source-map/source-node.js:38:32)
at Object.test .add() (http://localhost:8080/file/c/test/test-source-node.js:61:16)
at run (http://localhost:8080/file/c/test/run-tests-in-browser.html:66:31)
at http://localhost:8080/file/c/test/run-tests-in-browser.html:123:10
at Function.execCb (http://requirejs.org/docs/release/1.0.6/minified/require.js:28:478)
at p (http://requirejs.org/docs/release/1.0.6/minified/require.js:11:3)
at http://requirejs.org/docs/release/1.0.6/minified/require.js:12:242
at p (http://requirejs.org/docs/release/1.0.6/minified/require.js:12:133)
at http://requirejs.org/docs/release/1.0.6/minified/require.js:12:242

Questions

Thanks for a very useful package.
How does one read the location data while walking the AST nodes. That info is scattered in a very unstructured way.
is it necessary to map each column in each line. what does the browser or debugger do when there is a gap?
Please, clear a little fog in the documentation. What does 'Applies a SourceMap for a source file to the SourceMap.' mean? Are you calling three different things by the same name?
Thanks for any time you can spare.

Composing source maps

It should be easy to create source maps composed from other source maps.

For example, if we start out with a coffeescript file and compile it to readable js we get source map A. Then if we minify that js file, we get source map B. We should be able to take those source maps and compose them in to a single source map, mapping our coffee script file to the minified file.

SourceMapConsumer.originalPositionFor does not return correct value, unless at begining of mapping

SourceMapConsumer.originalPositionFor does not return the original position it returns the position of the start of the block in which that position is found.

i.e. (where x and y are constant)

SourceMapConsumer.originalPositionFor({line: y, column: x});

and

SourceMapConsumer.originalPositionFor({line: y, column: x + 1});

and

SourceMapConsumer.originalPositionFor({line: y, column: x + 2});

Will all yield the same result if the positions all fall inside the same mapping - the start position of the mapping, which is incorrect.

merge dryice into source-map ?

Hello,

  • dryice is small
  • dryice hasn't changed in a year
  • dryice is only used by one active project: source-map
  • there are plenty of alternative bundling tools (browserify and so on)

so maybe it's a good idea to maintain dryice within source-map instead of having it separated.

No change logs, nor git tags

Hello,

I use source-map and I've found its development is very active recently, but there are no change logs nor git tags so I cannot trace the changes. Can you employ them to the repo?

Cheers,

Question about source node 'name' field

If I understood correctly, the 'name' field should be used by a debugger to map mangled identifiers to their original name.

I have tried this in chrome but it still shows the mangled names, is there any browser that currently supports this feature?

Thanks

Building for browser fails

node Makefile.dryice.js errors out:

fs.js:550
  return binding.mkdir(pathModule._makeLong(path),
                 ^
Error: ENOENT, no such file or directory 'dist/test'
    at Object.fs.mkdirSync (fs.js:550:18)
    at ensureDir (/home/mishoo/Projects/Node.js/source-map/Makefile.dryice.js:129:8)
    at Object.<anonymous> (/home/mishoo/Projects/Node.js/source-map/Makefile.dryice.js:133:1)
    at Module._compile (module.js:454:26)
    at Object.Module._extensions..js (module.js:472:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:497:10)
    at process._tickCallback (node.js:325:13)

I'm not a Dryice user myself, just installed it via NPM. Not sure how to workaround the error..

Dependencies issues

Hello,

The last registered version in NPM is 0.1.8 (https://npmjs.org/package/source-map), this version doesn't exist anymore as a tag in this git repository, which causes dependencies issues for every node modules using it.

Please, can you tag it back,

Regards

Possible bug when parsing source maps

I'm getting an exception when parsing source map output by typescript, which was reported in typescript issue tracker here but I'm starting to consider this is a bug with this library since google chrome correctly parses the source map. To reproduce follow these steps:

install tsc and uglifyjs globally

npm install -g typescript uglifyjs

create two files, animal.ts:

module animals {

  export class Animal {
    private killed;

    kill() {
      this.killed = true;
    }
  }

}

and dog.ts:

module animals {

  class Dog extends Animal {
    bark() {
      console.log('bark');
    }
  }

}

then run these:

tsc -out all.js --sourcemap dog.ts animal.ts
uglifyjs --in-source-map all.js.map --source-map all.min.js.map -o all.min.js

An error is thrown on 'array-set.js' (No element indexed by 7)

It should create a minified js file that maps back to the two typescript files, but instead an exception is thrown in

Error in array-set when producing source maps.

I created a repo to reproduce the issue here, but here is the stack trace, it basically breaks in ./lib/array-set.js.

/Users/thlorenz/dev/js/projects/es6ify/tmp/node_modules/browserify/node_modules/browser-pack/node_modules/combine-source-map/node_modules/source-map/lib/source-map/array-set.js:83
    throw new Error('No element indexed by ' + aIdx);
          ^
Error: No element indexed by 1
    at ArraySet_at [as at] (/Users/thlorenz/dev/js/projects/es6ify/tmp/node_modules/browserify/node_modules/browser-pack/node_modules/combine-source-map/node_modules/source-map/lib/source-map/array-set.js:83:11)
    at SourceMapConsumer_parseMappings [as _parseMappings] (/Users/thlorenz/dev/js/projects/es6ify/tmp/node_modules/browserify/node_modules/browser-pack/node_modules/combine-source-map/node_modules/source-map/lib/source-map/source-map-consumer.js:158:44)
    at new SourceMapConsumer (/Users/thlorenz/dev/js/projects/es6ify/tmp/node_modules/browserify/node_modules/browser-pack/node_modules/combine-source-map/node_modules/source-map/lib/source-map/source-map-consumer.js:100:10)
    at module.exports (/Users/thlorenz/dev/js/projects/es6ify/tmp/node_modules/browserify/node_modules/browser-pack/node_modules/combine-source-map/lib/mappings-from-map.js:10:18)
    at Combiner._addExistingMap (/Users/thlorenz/dev/js/projects/es6ify/tmp/node_modules/browserify/node_modules/browser-pack/node_modules/combine-source-map/index.js:28:18)
    at Combiner.addFile (/Users/thlorenz/dev/js/projects/es6ify/tmp/node_modules/browserify/node_modules/browser-pack/node_modules/combine-source-map/index.js:58:12)
    at Stream.write (/Users/thlorenz/dev/js/projects/es6ify/tmp/node_modules/browserify/node_modules/browser-pack/index.js:42:23)
    at Stream.stream.write (/Users/thlorenz/dev/js/projects/es6ify/tmp/node_modules/browserify/node_modules/through/index.js:26:11)
    at Stream.ondata (stream.js:51:26)
    at Stream.EventEmitter.emit (events.js:95:17)

Can you release a new version?

Hi,

I'm using source-map for my tool on node.js, but have a problem on "hasOwnProperty", which has been fixed on the repository.

Can you release a new version to npmjs.org?

Thanks,
gfx

Regression from 0.1.32 to 0.1.33: SourceMapConsumer doesn't work for TypeScript-generated source maps

Take a simple TypeScript source file named greeter.ts:

class Greeter {
    constructor(public greeting: string) { }
    greet() {
    return "<h1>" + this.greeting + "</h1>";
    }
};
var greeter = new Greeter("Hello, world!");
var str = greeter.greet();
document.body.innerHTML = str;

Compile with this command:

tsc --sourcemap greeter.ts

This creates greeter.js:

var Greeter = (function () {
    function Greeter(greeting) {
    this.greeting = greeting;
    }
    Greeter.prototype.greet = function () {
    return "<h1>" + this.greeting + "</h1>";
    };
    return Greeter;
})();
;
var greeter = new Greeter("Hello, world!");
var str = greeter.greet();
document.body.innerHTML = str;
//# sourceMappingURL=greeter.js.map

and greeter.js.map:

{"version":3,"file":"greeter.js","sourceRoot":"","sources":["greeter.ts"],"names":["Greeter","Greeter.constructor","Greeter.greet"],"mappings":"AAAA;IACIA,iBAAYA,QAAuBA;QAAvBC,aAAeA,GAARA,QAAQA;AAAQA,IAAIA,CAACA;IACxCD,0BAAAA;QACIE,OAAOA,MAAMA,GAAGA,IAAIA,CAACA,QAAQA,GAAGA,OAAOA;IAC3CA,CAACA;IACLF,eAACA;AAADA,CAACA,IAAA;AAAA,CAAC;AACF,IAAI,OAAO,GAAG,IAAI,OAAO,CAAC,eAAe,CAAC;AAC1C,IAAI,GAAG,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;AACzB,QAAQ,CAAC,IAAI,CAAC,SAAS,GAAG,GAAG"}

Install source-map v0.1.32:

npm install [email protected]

Then you can run this script in node.js:

var SourceMapConsumer = require('source-map').SourceMapConsumer;

require('fs').readFile("greeter.js.map", 'utf8', function (err, data) {
    if (err) {
    console.log('Error: ' + err);
    return;
    }

    var smc = new SourceMapConsumer(JSON.parse(data));

    console.log(smc.originalPositionFor({
    line: 5,
    column: 3
    }));
});

and get this output:

{ source: 'greeter.ts',
  line: 2,
  column: 44,
  name: 'Greeter.constructor' }

Great. Looks fine. Then upgrade to source-map v0.1.33:

npm install [email protected]

Rerun the exact same node.js script, and the output is:

{ source: null, line: null, column: null, name: null }

I observed this bug on Ubuntu 13.10 with node.js v0.10.15 installed from the repos.

I was only able to reproduce this bug for source maps generated by TypeScript. Source maps generated by UglifyJS seem to work fine in v0.1.33.

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.