remapping.mjs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. import { decodedMappings, traceSegment, TraceMap } from '@jridgewell/trace-mapping';
  2. import { GenMapping, addSegment, setSourceContent, decodedMap, encodedMap } from '@jridgewell/gen-mapping';
  3. const SOURCELESS_MAPPING = {
  4. source: null,
  5. column: null,
  6. line: null,
  7. name: null,
  8. content: null,
  9. };
  10. const EMPTY_SOURCES = [];
  11. function Source(map, sources, source, content) {
  12. return {
  13. map,
  14. sources,
  15. source,
  16. content,
  17. };
  18. }
  19. /**
  20. * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
  21. * (which may themselves be SourceMapTrees).
  22. */
  23. function MapSource(map, sources) {
  24. return Source(map, sources, '', null);
  25. }
  26. /**
  27. * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
  28. * segment tracing ends at the `OriginalSource`.
  29. */
  30. function OriginalSource(source, content) {
  31. return Source(null, EMPTY_SOURCES, source, content);
  32. }
  33. /**
  34. * traceMappings is only called on the root level SourceMapTree, and begins the process of
  35. * resolving each mapping in terms of the original source files.
  36. */
  37. function traceMappings(tree) {
  38. const gen = new GenMapping({ file: tree.map.file });
  39. const { sources: rootSources, map } = tree;
  40. const rootNames = map.names;
  41. const rootMappings = decodedMappings(map);
  42. for (let i = 0; i < rootMappings.length; i++) {
  43. const segments = rootMappings[i];
  44. let lastSource = null;
  45. let lastSourceLine = null;
  46. let lastSourceColumn = null;
  47. for (let j = 0; j < segments.length; j++) {
  48. const segment = segments[j];
  49. const genCol = segment[0];
  50. let traced = SOURCELESS_MAPPING;
  51. // 1-length segments only move the current generated column, there's no source information
  52. // to gather from it.
  53. if (segment.length !== 1) {
  54. const source = rootSources[segment[1]];
  55. traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
  56. // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a
  57. // respective segment into an original source.
  58. if (traced == null)
  59. continue;
  60. }
  61. // So we traced a segment down into its original source file. Now push a
  62. // new segment pointing to this location.
  63. const { column, line, name, content, source } = traced;
  64. if (line === lastSourceLine && column === lastSourceColumn && source === lastSource) {
  65. continue;
  66. }
  67. lastSourceLine = line;
  68. lastSourceColumn = column;
  69. lastSource = source;
  70. // Sigh, TypeScript can't figure out source/line/column are either all null, or all non-null...
  71. addSegment(gen, i, genCol, source, line, column, name);
  72. if (content != null)
  73. setSourceContent(gen, source, content);
  74. }
  75. }
  76. return gen;
  77. }
  78. /**
  79. * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
  80. * child SourceMapTrees, until we find the original source map.
  81. */
  82. function originalPositionFor(source, line, column, name) {
  83. if (!source.map) {
  84. return { column, line, name, source: source.source, content: source.content };
  85. }
  86. const segment = traceSegment(source.map, line, column);
  87. // If we couldn't find a segment, then this doesn't exist in the sourcemap.
  88. if (segment == null)
  89. return null;
  90. // 1-length segments only move the current generated column, there's no source information
  91. // to gather from it.
  92. if (segment.length === 1)
  93. return SOURCELESS_MAPPING;
  94. return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
  95. }
  96. function asArray(value) {
  97. if (Array.isArray(value))
  98. return value;
  99. return [value];
  100. }
  101. /**
  102. * Recursively builds a tree structure out of sourcemap files, with each node
  103. * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
  104. * `OriginalSource`s and `SourceMapTree`s.
  105. *
  106. * Every sourcemap is composed of a collection of source files and mappings
  107. * into locations of those source files. When we generate a `SourceMapTree` for
  108. * the sourcemap, we attempt to load each source file's own sourcemap. If it
  109. * does not have an associated sourcemap, it is considered an original,
  110. * unmodified source file.
  111. */
  112. function buildSourceMapTree(input, loader) {
  113. const maps = asArray(input).map((m) => new TraceMap(m, ''));
  114. const map = maps.pop();
  115. for (let i = 0; i < maps.length; i++) {
  116. if (maps[i].sources.length > 1) {
  117. throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
  118. 'Did you specify these with the most recent transformation maps first?');
  119. }
  120. }
  121. let tree = build(map, loader, '', 0);
  122. for (let i = maps.length - 1; i >= 0; i--) {
  123. tree = MapSource(maps[i], [tree]);
  124. }
  125. return tree;
  126. }
  127. function build(map, loader, importer, importerDepth) {
  128. const { resolvedSources, sourcesContent } = map;
  129. const depth = importerDepth + 1;
  130. const children = resolvedSources.map((sourceFile, i) => {
  131. // The loading context gives the loader more information about why this file is being loaded
  132. // (eg, from which importer). It also allows the loader to override the location of the loaded
  133. // sourcemap/original source, or to override the content in the sourcesContent field if it's
  134. // an unmodified source file.
  135. const ctx = {
  136. importer,
  137. depth,
  138. source: sourceFile || '',
  139. content: undefined,
  140. };
  141. // Use the provided loader callback to retrieve the file's sourcemap.
  142. // TODO: We should eventually support async loading of sourcemap files.
  143. const sourceMap = loader(ctx.source, ctx);
  144. const { source, content } = ctx;
  145. // If there is a sourcemap, then we need to recurse into it to load its source files.
  146. if (sourceMap)
  147. return build(new TraceMap(sourceMap, source), loader, source, depth);
  148. // Else, it's an an unmodified source file.
  149. // The contents of this unmodified source file can be overridden via the loader context,
  150. // allowing it to be explicitly null or a string. If it remains undefined, we fall back to
  151. // the importing sourcemap's `sourcesContent` field.
  152. const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;
  153. return OriginalSource(source, sourceContent);
  154. });
  155. return MapSource(map, children);
  156. }
  157. /**
  158. * A SourceMap v3 compatible sourcemap, which only includes fields that were
  159. * provided to it.
  160. */
  161. class SourceMap {
  162. constructor(map, options) {
  163. const out = options.decodedMappings ? decodedMap(map) : encodedMap(map);
  164. this.version = out.version; // SourceMap spec says this should be first.
  165. this.file = out.file;
  166. this.mappings = out.mappings;
  167. this.names = out.names;
  168. this.sourceRoot = out.sourceRoot;
  169. this.sources = out.sources;
  170. if (!options.excludeContent) {
  171. this.sourcesContent = out.sourcesContent;
  172. }
  173. }
  174. toString() {
  175. return JSON.stringify(this);
  176. }
  177. }
  178. /**
  179. * Traces through all the mappings in the root sourcemap, through the sources
  180. * (and their sourcemaps), all the way back to the original source location.
  181. *
  182. * `loader` will be called every time we encounter a source file. If it returns
  183. * a sourcemap, we will recurse into that sourcemap to continue the trace. If
  184. * it returns a falsey value, that source file is treated as an original,
  185. * unmodified source file.
  186. *
  187. * Pass `excludeContent` to exclude any self-containing source file content
  188. * from the output sourcemap.
  189. *
  190. * Pass `decodedMappings` to receive a SourceMap with decoded (instead of
  191. * VLQ encoded) mappings.
  192. */
  193. function remapping(input, loader, options) {
  194. const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };
  195. const tree = buildSourceMapTree(input, loader);
  196. return new SourceMap(traceMappings(tree), opts);
  197. }
  198. export { remapping as default };
  199. //# sourceMappingURL=remapping.mjs.map