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.

README.md 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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.
  196. * `column`: The column number in the generated source.
  197. * `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or
  198. `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest
  199. element that is smaller than or greater than the one we are searching for,
  200. respectively, if the exact element cannot be found. Defaults to
  201. `SourceMapConsumer.GREATEST_LOWER_BOUND`.
  202. and an object is returned with the following properties:
  203. * `source`: The original source file, or null if this information is not
  204. available.
  205. * `line`: The line number in the original source, or null if this information is
  206. not available.
  207. * `column`: The column number in the original source, or null if this
  208. information is not available.
  209. * `name`: The original identifier, or null if this information is not available.
  210. ```js
  211. consumer.originalPositionFor({ line: 2, column: 10 })
  212. // { source: 'foo.coffee',
  213. // line: 2,
  214. // column: 2,
  215. // name: null }
  216. consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 })
  217. // { source: null,
  218. // line: null,
  219. // column: null,
  220. // name: null }
  221. ```
  222. #### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)
  223. Returns the generated line and column information for the original source,
  224. line, and column positions provided. The only argument is an object with
  225. the following properties:
  226. * `source`: The filename of the original source.
  227. * `line`: The line number in the original source.
  228. * `column`: The column number in the original source.
  229. and an object is returned with the following properties:
  230. * `line`: The line number in the generated source, or null.
  231. * `column`: The column number in the generated source, or null.
  232. ```js
  233. consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 })
  234. // { line: 1,
  235. // column: 56 }
  236. ```
  237. #### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)
  238. Returns all generated line and column information for the original source, line,
  239. and column provided. If no column is provided, returns all mappings
  240. corresponding to a either the line we are searching for or the next closest line
  241. that has any mappings. Otherwise, returns all mappings corresponding to the
  242. given line and either the column we are searching for or the next closest column
  243. that has any offsets.
  244. The only argument is an object with the following properties:
  245. * `source`: The filename of the original source.
  246. * `line`: The line number in the original source.
  247. * `column`: Optional. The column number in the original source.
  248. and an array of objects is returned, each with the following properties:
  249. * `line`: The line number in the generated source, or null.
  250. * `column`: The column number in the generated source, or null.
  251. ```js
  252. consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" })
  253. // [ { line: 2,
  254. // column: 1 },
  255. // { line: 2,
  256. // column: 10 },
  257. // { line: 2,
  258. // column: 20 } ]
  259. ```
  260. #### SourceMapConsumer.prototype.hasContentsOfAllSources()
  261. Return true if we have the embedded source content for every source listed in
  262. the source map, false otherwise.
  263. In other words, if this method returns `true`, then
  264. `consumer.sourceContentFor(s)` will succeed for every source `s` in
  265. `consumer.sources`.
  266. ```js
  267. // ...
  268. if (consumer.hasContentsOfAllSources()) {
  269. consumerReadyCallback(consumer);
  270. } else {
  271. fetchSources(consumer, consumerReadyCallback);
  272. }
  273. // ...
  274. ```
  275. #### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])
  276. Returns the original source content for the source provided. The only
  277. argument is the URL of the original source file.
  278. If the source content for the given source is not found, then an error is
  279. thrown. Optionally, pass `true` as the second param to have `null` returned
  280. instead.
  281. ```js
  282. consumer.sources
  283. // [ "my-cool-lib.clj" ]
  284. consumer.sourceContentFor("my-cool-lib.clj")
  285. // "..."
  286. consumer.sourceContentFor("this is not in the source map");
  287. // Error: "this is not in the source map" is not in the source map
  288. consumer.sourceContentFor("this is not in the source map", true);
  289. // null
  290. ```
  291. #### SourceMapConsumer.prototype.eachMapping(callback, context, order)
  292. Iterate over each mapping between an original source/line/column and a
  293. generated line/column in this source map.
  294. * `callback`: The function that is called with each mapping. Mappings have the
  295. form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,
  296. name }`
  297. * `context`: Optional. If specified, this object will be the value of `this`
  298. every time that `callback` is called.
  299. * `order`: Either `SourceMapConsumer.GENERATED_ORDER` or
  300. `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over
  301. the mappings sorted by the generated file's line/column order or the
  302. original's source/line/column order, respectively. Defaults to
  303. `SourceMapConsumer.GENERATED_ORDER`.
  304. ```js
  305. consumer.eachMapping(function (m) { console.log(m); })
  306. // ...
  307. // { source: 'illmatic.js',
  308. // generatedLine: 1,
  309. // generatedColumn: 0,
  310. // originalLine: 1,
  311. // originalColumn: 0,
  312. // name: null }
  313. // { source: 'illmatic.js',
  314. // generatedLine: 2,
  315. // generatedColumn: 0,
  316. // originalLine: 2,
  317. // originalColumn: 0,
  318. // name: null }
  319. // ...
  320. ```
  321. ### SourceMapGenerator
  322. An instance of the SourceMapGenerator represents a source map which is being
  323. built incrementally.
  324. #### new SourceMapGenerator([startOfSourceMap])
  325. You may pass an object with the following properties:
  326. * `file`: The filename of the generated source that this source map is
  327. associated with.
  328. * `sourceRoot`: A root for all relative URLs in this source map.
  329. * `skipValidation`: Optional. When `true`, disables validation of mappings as
  330. they are added. This can improve performance but should be used with
  331. discretion, as a last resort. Even then, one should avoid using this flag when
  332. running tests, if possible.
  333. ```js
  334. var generator = new sourceMap.SourceMapGenerator({
  335. file: "my-generated-javascript-file.js",
  336. sourceRoot: "http://example.com/app/js/"
  337. });
  338. ```
  339. #### SourceMapGenerator.fromSourceMap(sourceMapConsumer)
  340. Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance.
  341. * `sourceMapConsumer` The SourceMap.
  342. ```js
  343. var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer);
  344. ```
  345. #### SourceMapGenerator.prototype.addMapping(mapping)
  346. Add a single mapping from original source line and column to the generated
  347. source's line and column for this source map being created. The mapping object
  348. should have the following properties:
  349. * `generated`: An object with the generated line and column positions.
  350. * `original`: An object with the original line and column positions.
  351. * `source`: The original source file (relative to the sourceRoot).
  352. * `name`: An optional original token name for this mapping.
  353. ```js
  354. generator.addMapping({
  355. source: "module-one.scm",
  356. original: { line: 128, column: 0 },
  357. generated: { line: 3, column: 456 }
  358. })
  359. ```
  360. #### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)
  361. Set the source content for an original source file.
  362. * `sourceFile` the URL of the original source file.
  363. * `sourceContent` the content of the source file.
  364. ```js
  365. generator.setSourceContent("module-one.scm",
  366. fs.readFileSync("path/to/module-one.scm"))
  367. ```
  368. #### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])
  369. Applies a SourceMap for a source file to the SourceMap.
  370. Each mapping to the supplied source file is rewritten using the
  371. supplied SourceMap. Note: The resolution for the resulting mappings
  372. is the minimum of this map and the supplied map.
  373. * `sourceMapConsumer`: The SourceMap to be applied.
  374. * `sourceFile`: Optional. The filename of the source file.
  375. If omitted, sourceMapConsumer.file will be used, if it exists.
  376. Otherwise an error will be thrown.
  377. * `sourceMapPath`: Optional. The dirname of the path to the SourceMap
  378. to be applied. If relative, it is relative to the SourceMap.
  379. This parameter is needed when the two SourceMaps aren't in the same
  380. directory, and the SourceMap to be applied contains relative source
  381. paths. If so, those relative source paths need to be rewritten
  382. relative to the SourceMap.
  383. If omitted, it is assumed that both SourceMaps are in the same directory,
  384. thus not needing any rewriting. (Supplying `'.'` has the same effect.)
  385. #### SourceMapGenerator.prototype.toString()
  386. Renders the source map being generated to a string.
  387. ```js
  388. generator.toString()
  389. // '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}'
  390. ```
  391. ### SourceNode
  392. SourceNodes provide a way to abstract over interpolating and/or concatenating
  393. snippets of generated JavaScript source code, while maintaining the line and
  394. column information associated between those snippets and the original source
  395. code. This is useful as the final intermediate representation a compiler might
  396. use before outputting the generated JS and source map.
  397. #### new SourceNode([line, column, source[, chunk[, name]]])
  398. * `line`: The original line number associated with this source node, or null if
  399. it isn't associated with an original line.
  400. * `column`: The original column number associated with this source node, or null
  401. if it isn't associated with an original column.
  402. * `source`: The original source's filename; null if no filename is provided.
  403. * `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see
  404. below.
  405. * `name`: Optional. The original identifier.
  406. ```js
  407. var node = new SourceNode(1, 2, "a.cpp", [
  408. new SourceNode(3, 4, "b.cpp", "extern int status;\n"),
  409. new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"),
  410. new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"),
  411. ]);
  412. ```
  413. #### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])
  414. Creates a SourceNode from generated code and a SourceMapConsumer.
  415. * `code`: The generated code
  416. * `sourceMapConsumer` The SourceMap for the generated code
  417. * `relativePath` The optional path that relative sources in `sourceMapConsumer`
  418. should be relative to.
  419. ```js
  420. var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8"));
  421. var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"),
  422. consumer);
  423. ```
  424. #### SourceNode.prototype.add(chunk)
  425. Add a chunk of generated JS to this source node.
  426. * `chunk`: A string snippet of generated JS code, another instance of
  427. `SourceNode`, or an array where each member is one of those things.
  428. ```js
  429. node.add(" + ");
  430. node.add(otherNode);
  431. node.add([leftHandOperandNode, " + ", rightHandOperandNode]);
  432. ```
  433. #### SourceNode.prototype.prepend(chunk)
  434. Prepend a chunk of generated JS to this source node.
  435. * `chunk`: A string snippet of generated JS code, another instance of
  436. `SourceNode`, or an array where each member is one of those things.
  437. ```js
  438. node.prepend("/** Build Id: f783haef86324gf **/\n\n");
  439. ```
  440. #### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)
  441. Set the source content for a source file. This will be added to the
  442. `SourceMap` in the `sourcesContent` field.
  443. * `sourceFile`: The filename of the source file
  444. * `sourceContent`: The content of the source file
  445. ```js
  446. node.setSourceContent("module-one.scm",
  447. fs.readFileSync("path/to/module-one.scm"))
  448. ```
  449. #### SourceNode.prototype.walk(fn)
  450. Walk over the tree of JS snippets in this node and its children. The walking
  451. function is called once for each snippet of JS and is passed that snippet and
  452. the its original associated source's line/column location.
  453. * `fn`: The traversal function.
  454. ```js
  455. var node = new SourceNode(1, 2, "a.js", [
  456. new SourceNode(3, 4, "b.js", "uno"),
  457. "dos",
  458. [
  459. "tres",
  460. new SourceNode(5, 6, "c.js", "quatro")
  461. ]
  462. ]);
  463. node.walk(function (code, loc) { console.log("WALK:", code, loc); })
  464. // WALK: uno { source: 'b.js', line: 3, column: 4, name: null }
  465. // WALK: dos { source: 'a.js', line: 1, column: 2, name: null }
  466. // WALK: tres { source: 'a.js', line: 1, column: 2, name: null }
  467. // WALK: quatro { source: 'c.js', line: 5, column: 6, name: null }
  468. ```
  469. #### SourceNode.prototype.walkSourceContents(fn)
  470. Walk over the tree of SourceNodes. The walking function is called for each
  471. source file content and is passed the filename and source content.
  472. * `fn`: The traversal function.
  473. ```js
  474. var a = new SourceNode(1, 2, "a.js", "generated from a");
  475. a.setSourceContent("a.js", "original a");
  476. var b = new SourceNode(1, 2, "b.js", "generated from b");
  477. b.setSourceContent("b.js", "original b");
  478. var c = new SourceNode(1, 2, "c.js", "generated from c");
  479. c.setSourceContent("c.js", "original c");
  480. var node = new SourceNode(null, null, null, [a, b, c]);
  481. node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); })
  482. // WALK: a.js : original a
  483. // WALK: b.js : original b
  484. // WALK: c.js : original c
  485. ```
  486. #### SourceNode.prototype.join(sep)
  487. Like `Array.prototype.join` except for SourceNodes. Inserts the separator
  488. between each of this source node's children.
  489. * `sep`: The separator.
  490. ```js
  491. var lhs = new SourceNode(1, 2, "a.rs", "my_copy");
  492. var operand = new SourceNode(3, 4, "a.rs", "=");
  493. var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()");
  494. var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]);
  495. var joinedNode = node.join(" ");
  496. ```
  497. #### SourceNode.prototype.replaceRight(pattern, replacement)
  498. Call `String.prototype.replace` on the very right-most source snippet. Useful
  499. for trimming white space from the end of a source node, etc.
  500. * `pattern`: The pattern to replace.
  501. * `replacement`: The thing to replace the pattern with.
  502. ```js
  503. // Trim trailing white space.
  504. node.replaceRight(/\s*$/, "");
  505. ```
  506. #### SourceNode.prototype.toString()
  507. Return the string representation of this source node. Walks over the tree and
  508. concatenates all the various snippets together to one string.
  509. ```js
  510. var node = new SourceNode(1, 2, "a.js", [
  511. new SourceNode(3, 4, "b.js", "uno"),
  512. "dos",
  513. [
  514. "tres",
  515. new SourceNode(5, 6, "c.js", "quatro")
  516. ]
  517. ]);
  518. node.toString()
  519. // 'unodostresquatro'
  520. ```
  521. #### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])
  522. Returns the string representation of this tree of source nodes, plus a
  523. SourceMapGenerator which contains all the mappings between the generated and
  524. original sources.
  525. The arguments are the same as those to `new SourceMapGenerator`.
  526. ```js
  527. var node = new SourceNode(1, 2, "a.js", [
  528. new SourceNode(3, 4, "b.js", "uno"),
  529. "dos",
  530. [
  531. "tres",
  532. new SourceNode(5, 6, "c.js", "quatro")
  533. ]
  534. ]);
  535. node.toStringWithSourceMap({ file: "my-output-file.js" })
  536. // { code: 'unodostresquatro',
  537. // map: [object SourceMapGenerator] }
  538. ```