PrefixSource.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. var Source = require("./Source");
  6. var SourceNode = require("source-map").SourceNode;
  7. function PrefixSource(prefix, source) {
  8. Source.call(this);
  9. this._source = source;
  10. this._prefix = prefix;
  11. }
  12. module.exports = PrefixSource;
  13. PrefixSource.prototype = Object.create(Source.prototype);
  14. PrefixSource.prototype.constructor = PrefixSource;
  15. PrefixSource.prototype.source = function() {
  16. var node = typeof this._source === "string" ? this._source : this._source.source();
  17. var prefix = this._prefix;
  18. return prefix + node.replace(/\n(.)/g, "\n" + prefix + "$1");
  19. };
  20. require("./SourceAndMapMixin")(PrefixSource.prototype);
  21. PrefixSource.prototype.node = function(options) {
  22. var node = this._source.node(options);
  23. var append = [this._prefix];
  24. return new SourceNode(null, null, null, [
  25. cloneAndPrefix(node, this._prefix, append)
  26. ]);
  27. };
  28. PrefixSource.prototype.listMap = function(options) {
  29. var prefix = this._prefix;
  30. var map = this._source.listMap(options);
  31. map.mapGeneratedCode(function(code) {
  32. return prefix + code.replace(/\n(.)/g, "\n" + prefix + "$1");
  33. });
  34. return map;
  35. };
  36. PrefixSource.prototype.updateHash = function(hash) {
  37. if(typeof this._source === "string")
  38. hash.update(this._source);
  39. else
  40. this._source.updateHash(hash);
  41. if(typeof this._prefix === "string")
  42. hash.update(this._prefix);
  43. else
  44. this._prefix.updateHash(hash);
  45. };
  46. function cloneAndPrefix(node, prefix, append) {
  47. if(typeof node === "string") {
  48. var result = node.replace(/\n(.)/g, "\n" + prefix + "$1");
  49. if(append.length > 0) result = append.pop() + result;
  50. if(/\n$/.test(node)) append.push(prefix);
  51. return result;
  52. } else {
  53. var newNode = new SourceNode(
  54. node.line,
  55. node.column,
  56. node.source,
  57. node.children.map(function(node) {
  58. return cloneAndPrefix(node, prefix, append);
  59. }),
  60. node.name
  61. );
  62. newNode.sourceContents = node.sourceContents;
  63. return newNode;
  64. }
  65. };