選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

source-map-generator.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /* -*- Mode: js; js-indent-level: 2; -*- */
  2. /*
  3. * Copyright 2011 Mozilla Foundation and contributors
  4. * Licensed under the New BSD license. See LICENSE or:
  5. * http://opensource.org/licenses/BSD-3-Clause
  6. */
  7. var base64VLQ = require('./base64-vlq');
  8. var util = require('./util');
  9. var ArraySet = require('./array-set').ArraySet;
  10. var MappingList = require('./mapping-list').MappingList;
  11. /**
  12. * An instance of the SourceMapGenerator represents a source map which is
  13. * being built incrementally. You may pass an object with the following
  14. * properties:
  15. *
  16. * - file: The filename of the generated source.
  17. * - sourceRoot: A root for all relative URLs in this source map.
  18. */
  19. function SourceMapGenerator(aArgs) {
  20. if (!aArgs) {
  21. aArgs = {};
  22. }
  23. this._file = util.getArg(aArgs, 'file', null);
  24. this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
  25. this._skipValidation = util.getArg(aArgs, 'skipValidation', false);
  26. this._sources = new ArraySet();
  27. this._names = new ArraySet();
  28. this._mappings = new MappingList();
  29. this._sourcesContents = null;
  30. }
  31. SourceMapGenerator.prototype._version = 3;
  32. /**
  33. * Creates a new SourceMapGenerator based on a SourceMapConsumer
  34. *
  35. * @param aSourceMapConsumer The SourceMap.
  36. */
  37. SourceMapGenerator.fromSourceMap =
  38. function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
  39. var sourceRoot = aSourceMapConsumer.sourceRoot;
  40. var generator = new SourceMapGenerator({
  41. file: aSourceMapConsumer.file,
  42. sourceRoot: sourceRoot
  43. });
  44. aSourceMapConsumer.eachMapping(function (mapping) {
  45. var newMapping = {
  46. generated: {
  47. line: mapping.generatedLine,
  48. column: mapping.generatedColumn
  49. }
  50. };
  51. if (mapping.source != null) {
  52. newMapping.source = mapping.source;
  53. if (sourceRoot != null) {
  54. newMapping.source = util.relative(sourceRoot, newMapping.source);
  55. }
  56. newMapping.original = {
  57. line: mapping.originalLine,
  58. column: mapping.originalColumn
  59. };
  60. if (mapping.name != null) {
  61. newMapping.name = mapping.name;
  62. }
  63. }
  64. generator.addMapping(newMapping);
  65. });
  66. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  67. var sourceRelative = sourceFile;
  68. if (sourceRoot !== null) {
  69. sourceRelative = util.relative(sourceRoot, sourceFile);
  70. }
  71. if (!generator._sources.has(sourceRelative)) {
  72. generator._sources.add(sourceRelative);
  73. }
  74. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  75. if (content != null) {
  76. generator.setSourceContent(sourceFile, content);
  77. }
  78. });
  79. return generator;
  80. };
  81. /**
  82. * Add a single mapping from original source line and column to the generated
  83. * source's line and column for this source map being created. The mapping
  84. * object should have the following properties:
  85. *
  86. * - generated: An object with the generated line and column positions.
  87. * - original: An object with the original line and column positions.
  88. * - source: The original source file (relative to the sourceRoot).
  89. * - name: An optional original token name for this mapping.
  90. */
  91. SourceMapGenerator.prototype.addMapping =
  92. function SourceMapGenerator_addMapping(aArgs) {
  93. var generated = util.getArg(aArgs, 'generated');
  94. var original = util.getArg(aArgs, 'original', null);
  95. var source = util.getArg(aArgs, 'source', null);
  96. var name = util.getArg(aArgs, 'name', null);
  97. if (!this._skipValidation) {
  98. this._validateMapping(generated, original, source, name);
  99. }
  100. if (source != null) {
  101. source = String(source);
  102. if (!this._sources.has(source)) {
  103. this._sources.add(source);
  104. }
  105. }
  106. if (name != null) {
  107. name = String(name);
  108. if (!this._names.has(name)) {
  109. this._names.add(name);
  110. }
  111. }
  112. this._mappings.add({
  113. generatedLine: generated.line,
  114. generatedColumn: generated.column,
  115. originalLine: original != null && original.line,
  116. originalColumn: original != null && original.column,
  117. source: source,
  118. name: name
  119. });
  120. };
  121. /**
  122. * Set the source content for a source file.
  123. */
  124. SourceMapGenerator.prototype.setSourceContent =
  125. function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
  126. var source = aSourceFile;
  127. if (this._sourceRoot != null) {
  128. source = util.relative(this._sourceRoot, source);
  129. }
  130. if (aSourceContent != null) {
  131. // Add the source content to the _sourcesContents map.
  132. // Create a new _sourcesContents map if the property is null.
  133. if (!this._sourcesContents) {
  134. this._sourcesContents = Object.create(null);
  135. }
  136. this._sourcesContents[util.toSetString(source)] = aSourceContent;
  137. } else if (this._sourcesContents) {
  138. // Remove the source file from the _sourcesContents map.
  139. // If the _sourcesContents map is empty, set the property to null.
  140. delete this._sourcesContents[util.toSetString(source)];
  141. if (Object.keys(this._sourcesContents).length === 0) {
  142. this._sourcesContents = null;
  143. }
  144. }
  145. };
  146. /**
  147. * Applies the mappings of a sub-source-map for a specific source file to the
  148. * source map being generated. Each mapping to the supplied source file is
  149. * rewritten using the supplied source map. Note: The resolution for the
  150. * resulting mappings is the minimium of this map and the supplied map.
  151. *
  152. * @param aSourceMapConsumer The source map to be applied.
  153. * @param aSourceFile Optional. The filename of the source file.
  154. * If omitted, SourceMapConsumer's file property will be used.
  155. * @param aSourceMapPath Optional. The dirname of the path to the source map
  156. * to be applied. If relative, it is relative to the SourceMapConsumer.
  157. * This parameter is needed when the two source maps aren't in the same
  158. * directory, and the source map to be applied contains relative source
  159. * paths. If so, those relative source paths need to be rewritten
  160. * relative to the SourceMapGenerator.
  161. */
  162. SourceMapGenerator.prototype.applySourceMap =
  163. function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
  164. var sourceFile = aSourceFile;
  165. // If aSourceFile is omitted, we will use the file property of the SourceMap
  166. if (aSourceFile == null) {
  167. if (aSourceMapConsumer.file == null) {
  168. throw new Error(
  169. 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
  170. 'or the source map\'s "file" property. Both were omitted.'
  171. );
  172. }
  173. sourceFile = aSourceMapConsumer.file;
  174. }
  175. var sourceRoot = this._sourceRoot;
  176. // Make "sourceFile" relative if an absolute Url is passed.
  177. if (sourceRoot != null) {
  178. sourceFile = util.relative(sourceRoot, sourceFile);
  179. }
  180. // Applying the SourceMap can add and remove items from the sources and
  181. // the names array.
  182. var newSources = new ArraySet();
  183. var newNames = new ArraySet();
  184. // Find mappings for the "sourceFile"
  185. this._mappings.unsortedForEach(function (mapping) {
  186. if (mapping.source === sourceFile && mapping.originalLine != null) {
  187. // Check if it can be mapped by the source map, then update the mapping.
  188. var original = aSourceMapConsumer.originalPositionFor({
  189. line: mapping.originalLine,
  190. column: mapping.originalColumn
  191. });
  192. if (original.source != null) {
  193. // Copy mapping
  194. mapping.source = original.source;
  195. if (aSourceMapPath != null) {
  196. mapping.source = util.join(aSourceMapPath, mapping.source)
  197. }
  198. if (sourceRoot != null) {
  199. mapping.source = util.relative(sourceRoot, mapping.source);
  200. }
  201. mapping.originalLine = original.line;
  202. mapping.originalColumn = original.column;
  203. if (original.name != null) {
  204. mapping.name = original.name;
  205. }
  206. }
  207. }
  208. var source = mapping.source;
  209. if (source != null && !newSources.has(source)) {
  210. newSources.add(source);
  211. }
  212. var name = mapping.name;
  213. if (name != null && !newNames.has(name)) {
  214. newNames.add(name);
  215. }
  216. }, this);
  217. this._sources = newSources;
  218. this._names = newNames;
  219. // Copy sourcesContents of applied map.
  220. aSourceMapConsumer.sources.forEach(function (sourceFile) {
  221. var content = aSourceMapConsumer.sourceContentFor(sourceFile);
  222. if (content != null) {
  223. if (aSourceMapPath != null) {
  224. sourceFile = util.join(aSourceMapPath, sourceFile);
  225. }
  226. if (sourceRoot != null) {
  227. sourceFile = util.relative(sourceRoot, sourceFile);
  228. }
  229. this.setSourceContent(sourceFile, content);
  230. }
  231. }, this);
  232. };
  233. /**
  234. * A mapping can have one of the three levels of data:
  235. *
  236. * 1. Just the generated position.
  237. * 2. The Generated position, original position, and original source.
  238. * 3. Generated and original position, original source, as well as a name
  239. * token.
  240. *
  241. * To maintain consistency, we validate that any new mapping being added falls
  242. * in to one of these categories.
  243. */
  244. SourceMapGenerator.prototype._validateMapping =
  245. function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
  246. aName) {
  247. // When aOriginal is truthy but has empty values for .line and .column,
  248. // it is most likely a programmer error. In this case we throw a very
  249. // specific error message to try to guide them the right way.
  250. // For example: https://github.com/Polymer/polymer-bundler/pull/519
  251. if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
  252. throw new Error(
  253. 'original.line and original.column are not numbers -- you probably meant to omit ' +
  254. 'the original mapping entirely and only map the generated position. If so, pass ' +
  255. 'null for the original mapping instead of an object with empty or null values.'
  256. );
  257. }
  258. if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  259. && aGenerated.line > 0 && aGenerated.column >= 0
  260. && !aOriginal && !aSource && !aName) {
  261. // Case 1.
  262. return;
  263. }
  264. else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
  265. && aOriginal && 'line' in aOriginal && 'column' in aOriginal
  266. && aGenerated.line > 0 && aGenerated.column >= 0
  267. && aOriginal.line > 0 && aOriginal.column >= 0
  268. && aSource) {
  269. // Cases 2 and 3.
  270. return;
  271. }
  272. else {
  273. throw new Error('Invalid mapping: ' + JSON.stringify({
  274. generated: aGenerated,
  275. source: aSource,
  276. original: aOriginal,
  277. name: aName
  278. }));
  279. }
  280. };
  281. /**
  282. * Serialize the accumulated mappings in to the stream of base 64 VLQs
  283. * specified by the source map format.
  284. */
  285. SourceMapGenerator.prototype._serializeMappings =
  286. function SourceMapGenerator_serializeMappings() {
  287. var previousGeneratedColumn = 0;
  288. var previousGeneratedLine = 1;
  289. var previousOriginalColumn = 0;
  290. var previousOriginalLine = 0;
  291. var previousName = 0;
  292. var previousSource = 0;
  293. var result = '';
  294. var next;
  295. var mapping;
  296. var nameIdx;
  297. var sourceIdx;
  298. var mappings = this._mappings.toArray();
  299. for (var i = 0, len = mappings.length; i < len; i++) {
  300. mapping = mappings[i];
  301. next = ''
  302. if (mapping.generatedLine !== previousGeneratedLine) {
  303. previousGeneratedColumn = 0;
  304. while (mapping.generatedLine !== previousGeneratedLine) {
  305. next += ';';
  306. previousGeneratedLine++;
  307. }
  308. }
  309. else {
  310. if (i > 0) {
  311. if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
  312. continue;
  313. }
  314. next += ',';
  315. }
  316. }
  317. next += base64VLQ.encode(mapping.generatedColumn
  318. - previousGeneratedColumn);
  319. previousGeneratedColumn = mapping.generatedColumn;
  320. if (mapping.source != null) {
  321. sourceIdx = this._sources.indexOf(mapping.source);
  322. next += base64VLQ.encode(sourceIdx - previousSource);
  323. previousSource = sourceIdx;
  324. // lines are stored 0-based in SourceMap spec version 3
  325. next += base64VLQ.encode(mapping.originalLine - 1
  326. - previousOriginalLine);
  327. previousOriginalLine = mapping.originalLine - 1;
  328. next += base64VLQ.encode(mapping.originalColumn
  329. - previousOriginalColumn);
  330. previousOriginalColumn = mapping.originalColumn;
  331. if (mapping.name != null) {
  332. nameIdx = this._names.indexOf(mapping.name);
  333. next += base64VLQ.encode(nameIdx - previousName);
  334. previousName = nameIdx;
  335. }
  336. }
  337. result += next;
  338. }
  339. return result;
  340. };
  341. SourceMapGenerator.prototype._generateSourcesContent =
  342. function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
  343. return aSources.map(function (source) {
  344. if (!this._sourcesContents) {
  345. return null;
  346. }
  347. if (aSourceRoot != null) {
  348. source = util.relative(aSourceRoot, source);
  349. }
  350. var key = util.toSetString(source);
  351. return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
  352. ? this._sourcesContents[key]
  353. : null;
  354. }, this);
  355. };
  356. /**
  357. * Externalize the source map.
  358. */
  359. SourceMapGenerator.prototype.toJSON =
  360. function SourceMapGenerator_toJSON() {
  361. var map = {
  362. version: this._version,
  363. sources: this._sources.toArray(),
  364. names: this._names.toArray(),
  365. mappings: this._serializeMappings()
  366. };
  367. if (this._file != null) {
  368. map.file = this._file;
  369. }
  370. if (this._sourceRoot != null) {
  371. map.sourceRoot = this._sourceRoot;
  372. }
  373. if (this._sourcesContents) {
  374. map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
  375. }
  376. return map;
  377. };
  378. /**
  379. * Render the source map being generated to a string.
  380. */
  381. SourceMapGenerator.prototype.toString =
  382. function SourceMapGenerator_toString() {
  383. return JSON.stringify(this.toJSON());
  384. };
  385. exports.SourceMapGenerator = SourceMapGenerator;