PrefixSource.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. var Source = require("./Source");
  7. var SourceNode = require("source-map").SourceNode;
  8. var REPLACE_REGEX = /\n(?=.|\s)/g;
  9. function cloneAndPrefix(node, prefix, append) {
  10. if(typeof node === "string") {
  11. var result = node.replace(REPLACE_REGEX, "\n" + prefix);
  12. if(append.length > 0) result = append.pop() + result;
  13. if(/\n$/.test(node)) append.push(prefix);
  14. return result;
  15. } else {
  16. var newNode = new SourceNode(
  17. node.line,
  18. node.column,
  19. node.source,
  20. node.children.map(function(node) {
  21. return cloneAndPrefix(node, prefix, append);
  22. }),
  23. node.name
  24. );
  25. newNode.sourceContents = node.sourceContents;
  26. return newNode;
  27. }
  28. };
  29. class PrefixSource extends Source {
  30. constructor(prefix, source) {
  31. super();
  32. this._source = source;
  33. this._prefix = prefix;
  34. }
  35. source() {
  36. var node = typeof this._source === "string" ? this._source : this._source.source();
  37. var prefix = this._prefix;
  38. return prefix + node.replace(REPLACE_REGEX, "\n" + prefix);
  39. }
  40. node(options) {
  41. var node = this._source.node(options);
  42. var prefix = this._prefix;
  43. var output = [];
  44. var result = new SourceNode();
  45. node.walkSourceContents(function(source, content) {
  46. result.setSourceContent(source, content);
  47. });
  48. var needPrefix = true;
  49. node.walk(function(chunk, mapping) {
  50. var parts = chunk.split(/(\n)/);
  51. for(var i = 0; i < parts.length; i += 2) {
  52. var nl = i + 1 < parts.length;
  53. var part = parts[i] + (nl ? "\n" : "");
  54. if(part) {
  55. if(needPrefix) {
  56. output.push(prefix);
  57. }
  58. output.push(new SourceNode(mapping.line, mapping.column, mapping.source, part, mapping.name));
  59. needPrefix = nl;
  60. }
  61. }
  62. });
  63. result.add(output);
  64. return result;
  65. }
  66. listMap(options) {
  67. var prefix = this._prefix;
  68. var map = this._source.listMap(options);
  69. return map.mapGeneratedCode(function(code) {
  70. return prefix + code.replace(REPLACE_REGEX, "\n" + prefix);
  71. });
  72. }
  73. updateHash(hash) {
  74. if(typeof this._source === "string")
  75. hash.update(this._source);
  76. else
  77. this._source.updateHash(hash);
  78. if(typeof this._prefix === "string")
  79. hash.update(this._prefix);
  80. else
  81. this._prefix.updateHash(hash);
  82. }
  83. }
  84. require("./SourceAndMapMixin")(PrefixSource.prototype);
  85. module.exports = PrefixSource;