OriginalSource.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. var SourceNode = require("source-map").SourceNode;
  6. var SourceMapConsumer = require("source-map").SourceMapConsumer;
  7. var SourceListMap = require("source-list-map").SourceListMap;
  8. var Source = require("./Source");
  9. function isSplitter(c) {
  10. switch(c) {
  11. case 10: // \n
  12. case 13: // \r
  13. case 59: // ;
  14. case 123: // {
  15. case 125: // }
  16. return true;
  17. }
  18. return false;
  19. }
  20. function _splitCode(code) {
  21. var result = [];
  22. var i = 0, j = 0;
  23. for(; i < code.length; i++) {
  24. if(isSplitter(code.charCodeAt(i))) {
  25. while(isSplitter(code.charCodeAt(++i)));
  26. result.push(code.substring(j, i));
  27. j = i;
  28. }
  29. }
  30. if(j < code.length)
  31. result.push(code.substr(j));
  32. return result;
  33. }
  34. function OriginalSource(value, name) {
  35. Source.call(this);
  36. this._value = value;
  37. this._name = name;
  38. }
  39. module.exports = OriginalSource;
  40. OriginalSource.prototype = Object.create(Source.prototype);
  41. OriginalSource.prototype.constructor = OriginalSource;
  42. OriginalSource.prototype.source = function() {
  43. return this._value;
  44. };
  45. require("./SourceAndMapMixin")(OriginalSource.prototype);
  46. OriginalSource.prototype.node = function(options) {
  47. options = options || {};
  48. var sourceMap = this._sourceMap;
  49. var value = this._value;
  50. var name = this._name;
  51. var lines = value.split("\n");
  52. var node = new SourceNode(null, null, null,
  53. lines.map(function(line, idx) {
  54. var pos = 0;
  55. if(options.columns === false) {
  56. return new SourceNode(idx+1, 0, name,
  57. (line + (idx != lines.length-1 ? "\n" : ""))
  58. );
  59. }
  60. return new SourceNode(null, null, null,
  61. _splitCode(line + (idx != lines.length-1 ? "\n" : "")).map(function(item) {
  62. if(/^\s*$/.test(item)) return item;
  63. var res = new SourceNode(idx+1, pos, name, item);
  64. pos += item.length;
  65. return res;
  66. })
  67. );
  68. })
  69. );
  70. node.setSourceContent(name, value);
  71. return node;
  72. };
  73. OriginalSource.prototype.listMap = function(options) {
  74. return new SourceListMap(this._value, this._name, this._value)
  75. };
  76. OriginalSource.prototype.updateHash = function(hash) {
  77. hash.update(this._value);
  78. };