OriginalSource.js 2.0KB

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