RawSource.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const streamChunksOfRawSource = require("./helpers/streamChunksOfRawSource");
  7. const Source = require("./Source");
  8. class RawSource extends Source {
  9. constructor(value, convertToString = false) {
  10. super();
  11. const isBuffer = Buffer.isBuffer(value);
  12. if (!isBuffer && typeof value !== "string") {
  13. throw new TypeError("argument 'value' must be either string of Buffer");
  14. }
  15. this._valueIsBuffer = !convertToString && isBuffer;
  16. this._value = convertToString && isBuffer ? undefined : value;
  17. this._valueAsBuffer = isBuffer ? value : undefined;
  18. this._valueAsString = isBuffer ? undefined : value;
  19. }
  20. isBuffer() {
  21. return this._valueIsBuffer;
  22. }
  23. source() {
  24. if (this._value === undefined) {
  25. this._value = this._valueAsBuffer.toString("utf-8");
  26. }
  27. return this._value;
  28. }
  29. buffer() {
  30. if (this._valueAsBuffer === undefined) {
  31. this._valueAsBuffer = Buffer.from(this._value, "utf-8");
  32. }
  33. return this._valueAsBuffer;
  34. }
  35. map(options) {
  36. return null;
  37. }
  38. /**
  39. * @param {object} options options
  40. * @param {function(string, number, number, number, number, number, number): void} onChunk called for each chunk of code
  41. * @param {function(number, string, string)} onSource called for each source
  42. * @param {function(number, string)} onName called for each name
  43. * @returns {void}
  44. */
  45. streamChunks(options, onChunk, onSource, onName) {
  46. if (this._value === undefined) {
  47. this._value = Buffer.from(this._valueAsBuffer, "utf-8");
  48. }
  49. if (this._valueAsString === undefined) {
  50. this._valueAsString =
  51. typeof this._value === "string"
  52. ? this._value
  53. : this._value.toString("utf-8");
  54. }
  55. return streamChunksOfRawSource(
  56. this._valueAsString,
  57. onChunk,
  58. onSource,
  59. onName,
  60. !!(options && options.finalSource)
  61. );
  62. }
  63. updateHash(hash) {
  64. if (this._valueAsBuffer === undefined) {
  65. this._valueAsBuffer = Buffer.from(this._value, "utf-8");
  66. }
  67. hash.update("RawSource");
  68. hash.update(this._valueAsBuffer);
  69. }
  70. }
  71. module.exports = RawSource;