You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

742 lines
24 KiB

  1. # Source Map
  2. [![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)
  3. [![NPM](https://nodei.co/npm/source-map.png?downloads=true&downloadRank=true)](https://www.npmjs.com/package/source-map)
  4. This is a library to generate and consume the source map format
  5. [described here][format].
  6. [format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
  7. ## Use with Node
  8. $ npm install source-map
  9. ## Use on the Web
  10. <script src="https://raw.githubusercontent.com/mozilla/source-map/master/dist/source-map.min.js" defer></script>
  11. --------------------------------------------------------------------------------
  12. <!-- `npm run toc` to regenerate the Table of Contents -->
  13. <!-- START doctoc generated TOC please keep comment here to allow auto update -->
  14. <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
  15. ## Table of Contents
  16. - [Examples](#examples)
  17. - [Consuming a source map](#consuming-a-source-map)
  18. - [Generating a source map](#generating-a-source-map)
  19. - [With SourceNode (high level API)](#with-sourcenode-high-level-api)
  20. - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api)
  21. - [API](#api)
  22. - [SourceMapConsumer](#sourcemapconsumer)
  23. - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap)
  24. - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans)
  25. - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition)
  26. - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition)
  27. - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition)
  28. - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources)
  29. - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing)
  30. - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order)
  31. - [SourceMapGenerator](#sourcemapgenerator)
  32. - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap)
  33. - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer)
  34. - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping)
  35. - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent)
  36. - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath)
  37. - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring)
  38. - [SourceNode](#sourcenode)
  39. - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name)
  40. - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath)
  41. - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk)
  42. - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk)
  43. - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent)
  44. - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn)
  45. - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn)
  46. - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep)
  47. - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement)
  48. - [SourceNode.prototype.toString()](#sourcenodeprototypetostring)
  49. - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap)
  50. <!-- END doctoc generated TOC please keep comment here to allow auto update -->
  51. ## Examples
  52. ### Consuming a source map
  53. ```js
  54. var rawSourceMap = {
  55. version: 3,
  56. file: 'min.js',
  57. names: ['bar', 'baz', 'n'],
  58. sources: ['one.js', 'two.js'],
  59. sourceRoot: 'http://example.com/www/js/',
  60. mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'
  61. };
  62. var smc = new SourceMapConsumer(rawSourceMap);
  63. console.log(smc.sources);
  64. // [ 'http://example.com/www/js/one.js',
  65. // 'http://example.com/www/js/two.js' ]
  66. console.log(smc.originalPositionFor({
  67. line: 2,
  68. column: 28
  69. }));
  70. // { source: 'http://example.com/www/js/two.js',
  71. // line: 2,
  72. // column: 10,
  73. // name: 'n' }
  74. console.log(smc.generatedPositionFor({
  75. source: 'http://example.com/www/js/two.js',
  76. line: 2,
  77. column: 10
  78. }));
  79. // { line: 2, column: 28 }
  80. smc.eachMapping(function (m) {
  81. // ...
  82. });
  83. ```
  84. ### Generating a source map
  85. In depth guide:
  86. [**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)
  87. #### With SourceNode (high level API)
  88. ```js
  89. function compile(ast) {
  90. switch (ast.type) {
  91. case 'BinaryExpression':
  92. return new SourceNode(
  93. ast.location.line,
  94. ast.location.column,
  95. ast.location.source,
  96. [compile(ast.left), " + ", compile(ast.right)]
  97. );
  98. case 'Literal':
  99. return new SourceNode(
  100. ast.location.line,
  101. ast.location.column,
  102. ast.location.source,
  103. String(ast.value)
  104. );
  105. // ...
  106. default:
  107. throw new Error("Bad AST");
  108. }
  109. }
  110. var ast = parse("40 + 2", "add.js");
  111. console.log(compile(ast).toStringWithSourceMap({
  112. file: 'add.js'
  113. }));
  114. // { code: '40 + 2',
  115. // map: [object SourceMapGenerator] }
  116. ```
  117. #### With SourceMapGenerator (low level API)
  118. ```js
  119. var map = new SourceMapGenerator({
  120. file: "source-mapped.js"
  121. });
  122. map.addMapping({
  123. generated: {
  124. line: 10,
  125. column: 35
  126. },
  127. source: "foo.js",
  128. original: {
  129. line: 33,
  130. column: 2
  131. },
  132. name: "christopher"
  133. });
  134. console.log(map.toString());
  135. // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}'
  136. ```
  137. ## API
  138. Get a reference to the module:
  139. ```js
  140. // Node.js
  141. var sourceMap = require('source-map');
  142. // Browser builds
  143. var sourceMap = window.sourceMap;
  144. // Inside Firefox
  145. const sourceMap = require("devtools/toolkit/sourcemap/source-map.js");
  146. ```
  147. ### SourceMapConsumer
  148. A SourceMapConsumer instance represents a parsed source map which we can query
  149. for information about the original file positions by giving it a file position
  150. in the generated source.
  151. #### new SourceMapConsumer(rawSourceMap)
  152. The only parameter is the raw source map (either as a string which can be
  153. `JSON.parse`'d, or an object). According to the spec, source maps have the
  154. following attributes:
  155. * `version`: Which version of the source map spec this map is following.
  156. * `sources`: An array of URLs to the original source files.
  157. * `names`: An array of identifiers which can be referenced by individual
  158. mappings.
  159. * `sourceRoot`: Optional. The URL root from which all sources are relative.
  160. * `sourcesContent`: Optional. An array of contents of the original source files.
  161. * `mappings`: A string of base64 VLQs which contain the actual mappings.
  162. * `file`: Optional. The generated filename this source map is associated with.
  163. ```js
  164. var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData);
  165. ```
  166. #### SourceMapConsumer.prototype.computeColumnSpans()
  167. Compute the last column for each generated mapping. The last column is
  168. inclusive.
  169. ```js
  170. // Before:
  171. consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
  172. // [ { line: 2,
  173. // column: 1 },
  174. // { line: 2,
  175. // column: 10 },
  176. // { line: 2,
  177. // column: 20 } ]
  178. consumer.computeColumnSpans();
  179. // After:
  180. consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" })
  181. // [ { line: 2,
  182. // column: 1,
  183. // lastColumn: 9 },
  184. // { line: 2,
  185. // column: 10,
  186. // lastColumn: 19 },
  187. // { line: 2,
  188. // column: 20,
  189. // lastColumn: Infinity } ]
  190. ```
  191. #### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)
  192. Returns the original source, line, and column information for the generated
  193. source's line and column positions provided. The only argument is an object with
  194. the following properties:
  195. * `line`: The line number in the generated source. Line numbers in
  196. this library are 1-based (note that the underlying source map
  197. specification uses 0-based line numbers -- this library handles the
  198. translation).
  199. * `column`: The column number in the generated source. Column numbers
  200. in this library are 0-based.
  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`.
  206. and an object is returned with the following properties:
  207. * `source`: The original source file, or null if this information is not
  208. available.
  209. * `line`: The line number in the original source, or null if this information is
  210. not available. The line number is 1-based.
  211. * `column`: The column number in the original source, or null if this
  212. information is not available. The column number is 0-based.
  213. * `name`: The original identifier, or null if this information is not available.
  214. ```js
  215. consumer.originalPositionFor({ line: 2, column: 10 })
  216. // { source: 'foo.coffee',
  217. // line: 2,
  218. // column: 2,
  219. // name: null }
  220. consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
  221. // { source: null,
  222. // line: null,
  223. // column: null,
  224. // name: null }
  225. ```
  226. #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
  227. Returns the generated line and column information for the original source,
  228. line, and column positions provided. The only argument is an object with
  229. the following properties:
  230. * `source`: The filename of the original source.
  231. * `line`: The line number in the original source. The line number is
  232. 1-based.
  233. * `column`: The column number in the original source. The column
  234. number is 0-based.
  235. and an object is returned with the following properties:
  236. * `line`: The line number in the generated source, or null. The line
  237. number is 1-based.
  238. * `column`: The column number in the generated source, or null. The
  239. column number is 0-based.
  240. ```js
  241. consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
  242. // { line: 1,
  243. // column: 56 }
  244. ```
  245. #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
  246. Returns all generated line and column information for the original source, line,
  247. and column provided. If no column is provided, returns all mappings
  248. corresponding to a either the line we are searching for or the next closest line
  249. that has any mappings. Otherwise, returns all mappings corresponding to the
  250. given line and either the column we are searching for or the next closest column
  251. that has any offsets.
  252. The only argument is an object with the following properties:
  253. * `source`: The filename of the original source.
  254. * `line`: The line number in the original source. The line number is
  255. 1-based.
  256. * `column`: Optional. The column number in the original source. The
  257. column number is 0-based.
  258. and an array of objects is returned, each with the following properties:
  259. * `line`: The line number in the generated source, or null. The line
  260. number is 1-based.
  261. * `column`: The column number in the generated source, or null. The
  262. column number is 0-based.
  263. ```js
  264. consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
  265. // [ { line: 2,
  266. // column: 1 },
  267. // { line: 2,
  268. // column: 10 },
  269. // { line: 2,
  270. // column: 20 } ]
  271. ```
  272. #### SourceMapConsumer.prototype.hasContentsOfAllSources()
  273. Return true if we have the embedded source content for every source listed in
  274. the source map, false otherwise.
  275. In other words, if this method returns `true`, then
  276. `consumer.sourceContentFor(s)` will succeed for every source `s` in
  277. `consumer.sources`.
  278. ```js
  279. // ...
  280. if (consumer.hasContentsOfAllSources()) {
  281. consumerReadyCallback(consumer);
  282. } else {
  283. fetchSources(consumer, consumerReadyCallback);
  284. }
  285. // ...
  286. ```
  287. #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
  288. Returns the original source content for the source provided. The only
  289. argument is the URL of the original source file.
  290. If the source content for the given source is not found, then an error is
  291. thrown. Optionally, pass `true` as the second param to have `null` returned
  292. instead.
  293. ```js
  294. consumer.sources
  295. // [ "my-cool-lib.clj" ]
  296. consumer.sourceContentFor("my-cool-lib.clj")
  297. // "..."
  298. consumer.sourceContentFor("this is not in the source map");
  299. // Error: "this is not in the source map" is not in the source map
  300. consumer.sourceContentFor("this is not in the source map", true);
  301. // null
  302. ```
  303. #### SourceMapConsumer.prototype.eachMapping(callback, context, order)
  304. Iterate over each mapping between an original source/line/column and a
  305. generated line/column in this source map.
  306. * `callback`: The function that is called with each mapping. Mappings have the
  307. form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
  308. name }`
  309. * `context`: Optional. If specified, this object will be the value of `this`
  310. every time that `callback` is called.
  311. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
  312. `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
  313. the mappings sorted by the generated file's line/column order or the
  314. original's source/line/column order, respectively. Defaults to
  315. `SourceMapConsumer.GENERATED_ORDER`.
  316. ```js
  317. consumer.eachMapping(function (m) { console.log(m); })
  318. // ...
  319. // { source: 'illmatic.js',
  320. // generatedLine: 1,
  321. // generatedColumn: 0,
  322. // originalLine: 1,
  323. // originalColumn: 0,
  324. // name: null }
  325. // { source: 'illmatic.js',
  326. // generatedLine: 2,
  327. // generatedColumn: 0,
  328. // originalLine: 2,
  329. // originalColumn: 0,
  330. // name: null }
  331. // ...
  332. ```
  333. ### SourceMapGenerator
  334. An instance of the SourceMapGenerator represents a source map which is being
  335. built incrementally.
  336. #### new SourceMapGenerator([startOfSourceMap])
  337. You may pass an object with the following properties:
  338. * `file`: The filename of the generated source that this source map is
  339. associated with.
  340. * `sourceRoot`: A root for all relative URLs in this source map.
  341. * `skipValidation`: Optional. When `true`, disables validation of mappings as
  342. they are added. This can improve performance but should be used with
  343. discretion, as a last resort. Even then, one should avoid using this flag when
  344. running tests, if possible.
  345. ```js
  346. var generator = new sourceMap.SourceMapGenerator({
  347. file: "my-generated-javascript-file.js",
  348. sourceRoot: "http://example.com/app/js/"
  349. });
  350. ```
  351. #### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
  352. Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
  353. * `sourceMapConsumer` The SourceMap.
  354. ```js
  355. var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
  356. ```
  357. #### SourceMapGenerator.prototype.addMapping(mapping)
  358. Add a single mapping from original source line and column to the generated
  359. source's line and column for this source map being created. The mapping object
  360. should have the following properties:
  361. * `generated`: An object with the generated line and column positions.
  362. * `original`: An object with the original line and column positions.
  363. * `source`: The original source file (relative to the sourceRoot).
  364. * `name`: An optional original token name for this mapping.
  365. ```js
  366. generator.addMapping({
  367. source: "module-one.scm",
  368. original: { line: 128, column: 0 },
  369. generated: { line: 3, column: 456 }
  370. })
  371. ```
  372. #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
  373. Set the source content for an original source file.
  374. * `sourceFile` the URL of the original source file.
  375. * `sourceContent` the content of the source file.
  376. ```js
  377. generator.setSourceContent("module-one.scm",
  378. fs.readFileSync("path/to/module-one.scm"))
  379. ```
  380. #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
  381. Applies a SourceMap for a source file to the SourceMap.
  382. Each mapping to the supplied source file is rewritten using the
  383. supplied SourceMap. Note: The resolution for the resulting mappings
  384. is the minimum of this map and the supplied map.
  385. * `sourceMapConsumer`: The SourceMap to be applied.
  386. * `sourceFile`: Optional. The filename of the source file.
  387. If omitted, sourceMapConsumer.file will be used, if it exists.
  388. Otherwise an error will be thrown.
  389. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap
  390. to be applied. If relative, it is relative to the SourceMap.
  391. This parameter is needed when the two SourceMaps aren't in the same
  392. directory, and the SourceMap to be applied contains relative source
  393. paths. If so, those relative source paths need to be rewritten
  394. relative to the SourceMap.
  395. If omitted, it is assumed that both SourceMaps are in the same directory,
  396. thus not needing any rewriting. (Supplying `'.'` has the same effect.)
  397. #### SourceMapGenerator.prototype.toString()
  398. Renders the source map being generated to a string.
  399. ```js
  400. generator.toString()
  401. // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
  402. ```
  403. ### SourceNode
  404. SourceNodes provide a way to abstract over interpolating and/or concatenating
  405. snippets of generated JavaScript source code, while maintaining the line and
  406. column information associated between those snippets and the original source
  407. code. This is useful as the final intermediate representation a compiler might
  408. use before outputting the generated JS and source map.
  409. #### new SourceNode([line, column, source[, chunk[, name]]])
  410. * `line`: The original line number associated with this source node, or null if
  411. it isn't associated with an original line. The line number is 1-based.
  412. * `column`: The original column number associated with this source node, or null
  413. if it isn't associated with an original column. The column number
  414. is 0-based.
  415. * `source`: The original source's filename; null if no filename is provided.
  416. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
  417. below.
  418. * `name`: Optional. The original identifier.
  419. ```js
  420. var node = new SourceNode(1, 2, "a.cpp", [
  421. new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
  422. new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
  423. new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
  424. ]);
  425. ```
  426. #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
  427. Creates a SourceNode from generated code and a SourceMapConsumer.
  428. * `code`: The generated code
  429. * `sourceMapConsumer` The SourceMap for the generated code
  430. * `relativePath` The optional path that relative sources in `sourceMapConsumer`
  431. should be relative to.
  432. ```js
  433. var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
  434. var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
  435. consumer);
  436. ```
  437. #### SourceNode.prototype.add(chunk)
  438. Add a chunk of generated JS to this source node.
  439. * `chunk`: A string snippet of generated JS code, another instance of
  440. `SourceNode`, or an array where each member is one of those things.
  441. ```js
  442. node.add(" + ");
  443. node.add(otherNode);
  444. node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
  445. ```
  446. #### SourceNode.prototype.prepend(chunk)
  447. Prepend a chunk of generated JS to this source node.
  448. * `chunk`: A string snippet of generated JS code, another instance of
  449. `SourceNode`, or an array where each member is one of those things.
  450. ```js
  451. node.prepend("/** Build Id: f783haef86324gf **/\n\n");
  452. ```
  453. #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
  454. Set the source content for a source file. This will be added to the
  455. `SourceMap` in the `sourcesContent` field.
  456. * `sourceFile`: The filename of the source file
  457. * `sourceContent`: The content of the source file
  458. ```js
  459. node.setSourceContent("module-one.scm",
  460. fs.readFileSync("path/to/module-one.scm"))
  461. ```
  462. #### SourceNode.prototype.walk(fn)
  463. Walk over the tree of JS snippets in this node and its children. The walking
  464. function is called once for each snippet of JS and is passed that snippet and
  465. the its original associated source's line/column location.
  466. * `fn`: The traversal function.
  467. ```js
  468. var node = new SourceNode(1, 2, "a.js", [
  469. new SourceNode(3, 4, "b.js", "uno"),
  470. "dos",
  471. [
  472. "tres",
  473. new SourceNode(5, 6, "c.js", "quatro")
  474. ]
  475. ]);
  476. node.walk(function (code, loc) { console.log("WALK:", code, loc); })
  477. // WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
  478. // WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
  479. // WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
  480. // WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
  481. ```
  482. #### SourceNode.prototype.walkSourceContents(fn)
  483. Walk over the tree of SourceNodes. The walking function is called for each
  484. source file content and is passed the filename and source content.
  485. * `fn`: The traversal function.
  486. ```js
  487. var a = new SourceNode(1, 2, "a.js", "generated from a");
  488. a.setSourceContent("a.js", "original a");
  489. var b = new SourceNode(1, 2, "b.js", "generated from b");
  490. b.setSourceContent("b.js", "original b");
  491. var c = new SourceNode(1, 2, "c.js", "generated from c");
  492. c.setSourceContent("c.js", "original c");
  493. var node = new SourceNode(null, null, null, [a, b, c]);
  494. node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
  495. // WALK: a.js : original a
  496. // WALK: b.js : original b
  497. // WALK: c.js : original c
  498. ```
  499. #### SourceNode.prototype.join(sep)
  500. Like `Array.prototype.join` except for SourceNodes. Inserts the separator
  501. between each of this source node's children.
  502. * `sep`: The separator.
  503. ```js
  504. var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
  505. var operand = new SourceNode(3, 4, "a.rs", "=");
  506. var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
  507. var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
  508. var joinedNode = node.join(" ");
  509. ```
  510. #### SourceNode.prototype.replaceRight(pattern, replacement)
  511. Call `String.prototype.replace` on the very right-most source snippet. Useful
  512. for trimming white space from the end of a source node, etc.
  513. * `pattern`: The pattern to replace.
  514. * `replacement`: The thing to replace the pattern with.
  515. ```js
  516. // Trim trailing white space.
  517. node.replaceRight(/\s*$/, "");
  518. ```
  519. #### SourceNode.prototype.toString()
  520. Return the string representation of this source node. Walks over the tree and
  521. concatenates all the various snippets together to one string.
  522. ```js
  523. var node = new SourceNode(1, 2, "a.js", [
  524. new SourceNode(3, 4, "b.js", "uno"),
  525. "dos",
  526. [
  527. "tres",
  528. new SourceNode(5, 6, "c.js", "quatro")
  529. ]
  530. ]);
  531. node.toString()
  532. // 'unodostresquatro'
  533. ```
  534. #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
  535. Returns the string representation of this tree of source nodes, plus a
  536. SourceMapGenerator which contains all the mappings between the generated and
  537. original sources.
  538. The arguments are the same as those to `new SourceMapGenerator`.
  539. ```js
  540. var node = new SourceNode(1, 2, "a.js", [
  541. new SourceNode(3, 4, "b.js", "uno"),
  542. "dos",
  543. [
  544. "tres",
  545. new SourceNode(5, 6, "c.js", "quatro")
  546. ]
  547. ]);
  548. node.toStringWithSourceMap({ file: "my-output-file.js" })
  549. // { code: 'unodostresquatro',
  550. // map: [object SourceMapGenerator] }
  551. ```