3 This is a library to generate and consume the source map format
4 [described here][format].
6 This library is written in the Asynchronous Module Definition format, and works
7 in the following environments:
9 * Modern Browsers supporting ECMAScript 5 (either after the build, or with an
10 AMD loader such as RequireJS)
12 * Inside Firefox (as a JSM file, after the build)
14 * With NodeJS versions 0.8.X and higher
18 $ npm install source-map
20 ## Building from Source (for everywhere else)
22 Install Node and then run
24 $ git clone https://fitzgen@github.com/mozilla/source-map.git
30 $ node Makefile.dryice.js
32 This should spew a bunch of stuff to stdout, and create the following files:
34 * `dist/source-map.js` - The unminified browser version.
36 * `dist/source-map.min.js` - The minified browser version.
38 * `dist/SourceMap.jsm` - The JavaScript Module for inclusion in Firefox source.
42 ### Consuming a source map
48 names: ['bar', 'baz', 'n'],
49 sources: ['one.js', 'two.js'],
50 sourceRoot: 'http://example.com/www/js/',
51 mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
54 var smc = new SourceMapConsumer(rawSourceMap);
56 console.log(smc.sources);
57 // [ 'http://example.com/www/js/one.js',
58 // 'http://example.com/www/js/two.js' ]
60 console.log(smc.originalPositionFor({
64 // { source: 'http://example.com/www/js/two.js',
69 console.log(smc.generatedPositionFor({
70 source: 'http://example.com/www/js/two.js',
74 // { line: 2, column: 28 }
76 smc.eachMapping(function (m) {
81 ### Generating a source map
84 [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
86 #### With SourceNode (high level API)
89 function compile(ast) {
91 case 'BinaryExpression':
92 return new SourceNode(
96 [compile(ast.left), " + ", compile(ast.right)]
99 return new SourceNode(
107 throw new Error("Bad AST");
111 var ast = parse("40 + 2", "add.js");
112 console.log(compile(ast).toStringWithSourceMap({
116 // map: [object SourceMapGenerator] }
119 #### With SourceMapGenerator (low level API)
122 var map = new SourceMapGenerator({
123 file: "source-mapped.js"
139 console.log(map.toString());
140 // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
145 Get a reference to the module:
149 var sourceMap = require('source-map');
152 var sourceMap = window.sourceMap;
156 Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap);
159 ### SourceMapConsumer
161 A SourceMapConsumer instance represents a parsed source map which we can query
162 for information about the original file positions by giving it a file position
163 in the generated source.
165 #### new SourceMapConsumer(rawSourceMap)
167 The only parameter is the raw source map (either as a string which can be
168 `JSON.parse`'d, or an object). According to the spec, source maps have the
169 following attributes:
171 * `version`: Which version of the source map spec this map is following.
173 * `sources`: An array of URLs to the original source files.
175 * `names`: An array of identifiers which can be referrenced by individual
178 * `sourceRoot`: Optional. The URL root from which all sources are relative.
180 * `sourcesContent`: Optional. An array of contents of the original source files.
182 * `mappings`: A string of base64 VLQs which contain the actual mappings.
184 * `file`: Optional. The generated filename this source map is associated with.
186 #### SourceMapConsumer.prototype.computeColumnSpans()
188 Compute the last column for each generated mapping. The last column is
191 #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
193 Returns the original source, line, and column information for the generated
194 source's line and column positions provided. The only argument is an object with
195 the following properties:
197 * `line`: The line number in the generated source.
199 * `column`: The column number in the generated source.
201 * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
202 `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
203 element that is smaller than or greater than the one we are searching for,
204 respectively, if the exact element cannot be found. Defaults to
205 `SourceMapConsumer.GREATEST_LOWER_BOUND`.
207 and an object is returned with the following properties:
209 * `source`: The original source file, or null if this information is not
212 * `line`: The line number in the original source, or null if this information is
215 * `column`: The column number in the original source, or null or null if this
216 information is not available.
218 * `name`: The original identifier, or null if this information is not available.
220 #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
222 Returns the generated line and column information for the original source,
223 line, and column positions provided. The only argument is an object with
224 the following properties:
226 * `source`: The filename of the original source.
228 * `line`: The line number in the original source.
230 * `column`: The column number in the original source.
232 and an object is returned with the following properties:
234 * `line`: The line number in the generated source, or null.
236 * `column`: The column number in the generated source, or null.
238 #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
240 Returns all generated line and column information for the original source, line,
241 and column provided. If no column is provided, returns all mappings
242 corresponding to a either the line we are searching for or the next closest line
243 that has any mappings. Otherwise, returns all mappings corresponding to the
244 given line and either the column we are searching for or the next closest column
245 that has any offsets.
247 The only argument is an object with the following properties:
249 * `source`: The filename of the original source.
251 * `line`: The line number in the original source.
253 * `column`: Optional. The column number in the original source.
255 and an array of objects is returned, each with the following properties:
257 * `line`: The line number in the generated source, or null.
259 * `column`: The column number in the generated source, or null.
261 #### SourceMapConsumer.prototype.hasContentsOfAllSources()
263 Return true if we have the embedded source content for every source listed in
264 the source map, false otherwise.
266 In other words, if this method returns `true`, then `smc.sourceContentFor(s)`
267 will succeed for every source `s` in `smc.sources`.
269 #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
271 Returns the original source content for the source provided. The only
272 argument is the URL of the original source file.
274 If the source content for the given source is not found, then an error is
275 thrown. Optionally, pass `true` as the second param to have `null` returned
278 #### SourceMapConsumer.prototype.eachMapping(callback, context, order)
280 Iterate over each mapping between an original source/line/column and a
281 generated line/column in this source map.
283 * `callback`: The function that is called with each mapping. Mappings have the
284 form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
287 * `context`: Optional. If specified, this object will be the value of `this`
288 every time that `callback` is called.
290 * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
291 `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
292 the mappings sorted by the generated file's line/column order or the
293 original's source/line/column order, respectively. Defaults to
294 `SourceMapConsumer.GENERATED_ORDER`.
296 ### SourceMapGenerator
298 An instance of the SourceMapGenerator represents a source map which is being
301 #### new SourceMapGenerator([startOfSourceMap])
303 You may pass an object with the following properties:
305 * `file`: The filename of the generated source that this source map is
308 * `sourceRoot`: A root for all relative URLs in this source map.
310 * `skipValidation`: Optional. When `true`, disables validation of mappings as
311 they are added. This can improve performance but should be used with
312 discretion, as a last resort. Even then, one should avoid using this flag when
313 running tests, if possible.
315 #### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
317 Creates a new SourceMapGenerator based on a SourceMapConsumer
319 * `sourceMapConsumer` The SourceMap.
321 #### SourceMapGenerator.prototype.addMapping(mapping)
323 Add a single mapping from original source line and column to the generated
324 source's line and column for this source map being created. The mapping object
325 should have the following properties:
327 * `generated`: An object with the generated line and column positions.
329 * `original`: An object with the original line and column positions.
331 * `source`: The original source file (relative to the sourceRoot).
333 * `name`: An optional original token name for this mapping.
335 #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
337 Set the source content for an original source file.
339 * `sourceFile` the URL of the original source file.
341 * `sourceContent` the content of the source file.
343 #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
345 Applies a SourceMap for a source file to the SourceMap.
346 Each mapping to the supplied source file is rewritten using the
347 supplied SourceMap. Note: The resolution for the resulting mappings
348 is the minimium of this map and the supplied map.
350 * `sourceMapConsumer`: The SourceMap to be applied.
352 * `sourceFile`: Optional. The filename of the source file.
353 If omitted, sourceMapConsumer.file will be used, if it exists.
354 Otherwise an error will be thrown.
356 * `sourceMapPath`: Optional. The dirname of the path to the SourceMap
357 to be applied. If relative, it is relative to the SourceMap.
359 This parameter is needed when the two SourceMaps aren't in the same
360 directory, and the SourceMap to be applied contains relative source
361 paths. If so, those relative source paths need to be rewritten
362 relative to the SourceMap.
364 If omitted, it is assumed that both SourceMaps are in the same directory,
365 thus not needing any rewriting. (Supplying `'.'` has the same effect.)
367 #### SourceMapGenerator.prototype.toString()
369 Renders the source map being generated to a string.
373 SourceNodes provide a way to abstract over interpolating and/or concatenating
374 snippets of generated JavaScript source code, while maintaining the line and
375 column information associated between those snippets and the original source
376 code. This is useful as the final intermediate representation a compiler might
377 use before outputting the generated JS and source map.
379 #### new SourceNode([line, column, source[, chunk[, name]]])
381 * `line`: The original line number associated with this source node, or null if
382 it isn't associated with an original line.
384 * `column`: The original column number associated with this source node, or null
385 if it isn't associated with an original column.
387 * `source`: The original source's filename; null if no filename is provided.
389 * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
392 * `name`: Optional. The original identifier.
394 #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
396 Creates a SourceNode from generated code and a SourceMapConsumer.
398 * `code`: The generated code
400 * `sourceMapConsumer` The SourceMap for the generated code
402 * `relativePath` The optional path that relative sources in `sourceMapConsumer`
403 should be relative to.
405 #### SourceNode.prototype.add(chunk)
407 Add a chunk of generated JS to this source node.
409 * `chunk`: A string snippet of generated JS code, another instance of
410 `SourceNode`, or an array where each member is one of those things.
412 #### SourceNode.prototype.prepend(chunk)
414 Prepend a chunk of generated JS to this source node.
416 * `chunk`: A string snippet of generated JS code, another instance of
417 `SourceNode`, or an array where each member is one of those things.
419 #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
421 Set the source content for a source file. This will be added to the
422 `SourceMap` in the `sourcesContent` field.
424 * `sourceFile`: The filename of the source file
426 * `sourceContent`: The content of the source file
428 #### SourceNode.prototype.walk(fn)
430 Walk over the tree of JS snippets in this node and its children. The walking
431 function is called once for each snippet of JS and is passed that snippet and
432 the its original associated source's line/column location.
434 * `fn`: The traversal function.
436 #### SourceNode.prototype.walkSourceContents(fn)
438 Walk over the tree of SourceNodes. The walking function is called for each
439 source file content and is passed the filename and source content.
441 * `fn`: The traversal function.
443 #### SourceNode.prototype.join(sep)
445 Like `Array.prototype.join` except for SourceNodes. Inserts the separator
446 between each of this source node's children.
448 * `sep`: The separator.
450 #### SourceNode.prototype.replaceRight(pattern, replacement)
452 Call `String.prototype.replace` on the very right-most source snippet. Useful
453 for trimming whitespace from the end of a source node, etc.
455 * `pattern`: The pattern to replace.
457 * `replacement`: The thing to replace the pattern with.
459 #### SourceNode.prototype.toString()
461 Return the string representation of this source node. Walks over the tree and
462 concatenates all the various snippets together to one string.
464 #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
466 Returns the string representation of this tree of source nodes, plus a
467 SourceMapGenerator which contains all the mappings between the generated and
470 The arguments are the same as those to `new SourceMapGenerator`.
474 [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
476 Install NodeJS version 0.8.0 or greater, then run `node test/run-tests.js`.
478 To add new tests, create a new file named `test/test-<your new test name>.js`
479 and export your test functions with names that start with "test", for example
482 exports["test doing the foo bar"] = function (assert, util) {
487 The new test will be located automatically when you run the suite.
489 The `util` argument is the test utility module located at `test/source-map/util`.
491 The `assert` argument is a cut down version of node's assert module. You have
492 access to the following assertion functions:
504 (The reason for the restricted set of test functions is because we need the
505 tests to run inside Firefox's test suite as well and so the assert module is
506 shimmed in that environment. See `build/assert-shim.js`.)
508 [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
509 [feature]: https://wiki.mozilla.org/DevTools/Features/SourceMap
510 [Dryice]: https://github.com/mozilla/dryice