streamAndGetSourceAndMap.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const createMappingsSerializer = require("./createMappingsSerializer");
  7. const streamChunks = require("./streamChunks");
  8. const streamAndGetSourceAndMap = (
  9. inputSource,
  10. options,
  11. onChunk,
  12. onSource,
  13. onName
  14. ) => {
  15. let code = "";
  16. let mappings = "";
  17. let sources = [];
  18. let sourcesContent = [];
  19. let names = [];
  20. const addMapping = createMappingsSerializer(
  21. Object.assign({}, options, { columns: true })
  22. );
  23. const finalSource = !!(options && options.finalSource);
  24. const { generatedLine, generatedColumn, source } = streamChunks(
  25. inputSource,
  26. options,
  27. (
  28. chunk,
  29. generatedLine,
  30. generatedColumn,
  31. sourceIndex,
  32. originalLine,
  33. originalColumn,
  34. nameIndex
  35. ) => {
  36. if (chunk !== undefined) code += chunk;
  37. mappings += addMapping(
  38. generatedLine,
  39. generatedColumn,
  40. sourceIndex,
  41. originalLine,
  42. originalColumn,
  43. nameIndex
  44. );
  45. return onChunk(
  46. finalSource ? undefined : chunk,
  47. generatedLine,
  48. generatedColumn,
  49. sourceIndex,
  50. originalLine,
  51. originalColumn,
  52. nameIndex
  53. );
  54. },
  55. (sourceIndex, source, sourceContent) => {
  56. while (sources.length < sourceIndex) {
  57. sources.push(null);
  58. }
  59. sources[sourceIndex] = source;
  60. if (sourceContent !== undefined) {
  61. while (sourcesContent.length < sourceIndex) {
  62. sourcesContent.push(null);
  63. }
  64. sourcesContent[sourceIndex] = sourceContent;
  65. }
  66. return onSource(sourceIndex, source, sourceContent);
  67. },
  68. (nameIndex, name) => {
  69. while (names.length < nameIndex) {
  70. names.push(null);
  71. }
  72. names[nameIndex] = name;
  73. return onName(nameIndex, name);
  74. }
  75. );
  76. const resultSource = source !== undefined ? source : code;
  77. return {
  78. result: {
  79. generatedLine,
  80. generatedColumn,
  81. source: finalSource ? resultSource : undefined
  82. },
  83. source: resultSource,
  84. map:
  85. mappings.length > 0
  86. ? {
  87. version: 3,
  88. file: "x",
  89. mappings,
  90. sources,
  91. sourcesContent:
  92. sourcesContent.length > 0 ? sourcesContent : undefined,
  93. names
  94. }
  95. : null
  96. };
  97. };
  98. module.exports = streamAndGetSourceAndMap;