trace-mapping.umd.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@jridgewell/sourcemap-codec'), require('@jridgewell/resolve-uri')) :
  3. typeof define === 'function' && define.amd ? define(['exports', '@jridgewell/sourcemap-codec', '@jridgewell/resolve-uri'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.traceMapping = {}, global.sourcemapCodec, global.resolveURI));
  5. })(this, (function (exports, sourcemapCodec, resolveUri) { 'use strict';
  6. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  7. var resolveUri__default = /*#__PURE__*/_interopDefaultLegacy(resolveUri);
  8. function resolve(input, base) {
  9. // The base is always treated as a directory, if it's not empty.
  10. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  11. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  12. if (base && !base.endsWith('/'))
  13. base += '/';
  14. return resolveUri__default["default"](input, base);
  15. }
  16. /**
  17. * Removes everything after the last "/", but leaves the slash.
  18. */
  19. function stripFilename(path) {
  20. if (!path)
  21. return '';
  22. const index = path.lastIndexOf('/');
  23. return path.slice(0, index + 1);
  24. }
  25. const COLUMN = 0;
  26. const SOURCES_INDEX = 1;
  27. const SOURCE_LINE = 2;
  28. const SOURCE_COLUMN = 3;
  29. const NAMES_INDEX = 4;
  30. const REV_GENERATED_LINE = 1;
  31. const REV_GENERATED_COLUMN = 2;
  32. function maybeSort(mappings, owned) {
  33. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  34. if (unsortedIndex === mappings.length)
  35. return mappings;
  36. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  37. // not, we do not want to modify the consumer's input array.
  38. if (!owned)
  39. mappings = mappings.slice();
  40. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  41. mappings[i] = sortSegments(mappings[i], owned);
  42. }
  43. return mappings;
  44. }
  45. function nextUnsortedSegmentLine(mappings, start) {
  46. for (let i = start; i < mappings.length; i++) {
  47. if (!isSorted(mappings[i]))
  48. return i;
  49. }
  50. return mappings.length;
  51. }
  52. function isSorted(line) {
  53. for (let j = 1; j < line.length; j++) {
  54. if (line[j][COLUMN] < line[j - 1][COLUMN]) {
  55. return false;
  56. }
  57. }
  58. return true;
  59. }
  60. function sortSegments(line, owned) {
  61. if (!owned)
  62. line = line.slice();
  63. return line.sort(sortComparator);
  64. }
  65. function sortComparator(a, b) {
  66. return a[COLUMN] - b[COLUMN];
  67. }
  68. let found = false;
  69. /**
  70. * A binary search implementation that returns the index if a match is found.
  71. * If no match is found, then the left-index (the index associated with the item that comes just
  72. * before the desired index) is returned. To maintain proper sort order, a splice would happen at
  73. * the next index:
  74. *
  75. * ```js
  76. * const array = [1, 3];
  77. * const needle = 2;
  78. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  79. *
  80. * assert.equal(index, 0);
  81. * array.splice(index + 1, 0, needle);
  82. * assert.deepEqual(array, [1, 2, 3]);
  83. * ```
  84. */
  85. function binarySearch(haystack, needle, low, high) {
  86. while (low <= high) {
  87. const mid = low + ((high - low) >> 1);
  88. const cmp = haystack[mid][COLUMN] - needle;
  89. if (cmp === 0) {
  90. found = true;
  91. return mid;
  92. }
  93. if (cmp < 0) {
  94. low = mid + 1;
  95. }
  96. else {
  97. high = mid - 1;
  98. }
  99. }
  100. found = false;
  101. return low - 1;
  102. }
  103. function upperBound(haystack, needle, index) {
  104. for (let i = index + 1; i < haystack.length; i++, index++) {
  105. if (haystack[i][COLUMN] !== needle)
  106. break;
  107. }
  108. return index;
  109. }
  110. function lowerBound(haystack, needle, index) {
  111. for (let i = index - 1; i >= 0; i--, index--) {
  112. if (haystack[i][COLUMN] !== needle)
  113. break;
  114. }
  115. return index;
  116. }
  117. function memoizedState() {
  118. return {
  119. lastKey: -1,
  120. lastNeedle: -1,
  121. lastIndex: -1,
  122. };
  123. }
  124. /**
  125. * This overly complicated beast is just to record the last tested line/column and the resulting
  126. * index, allowing us to skip a few tests if mappings are monotonically increasing.
  127. */
  128. function memoizedBinarySearch(haystack, needle, state, key) {
  129. const { lastKey, lastNeedle, lastIndex } = state;
  130. let low = 0;
  131. let high = haystack.length - 1;
  132. if (key === lastKey) {
  133. if (needle === lastNeedle) {
  134. found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
  135. return lastIndex;
  136. }
  137. if (needle >= lastNeedle) {
  138. // lastIndex may be -1 if the previous needle was not found.
  139. low = lastIndex === -1 ? 0 : lastIndex;
  140. }
  141. else {
  142. high = lastIndex;
  143. }
  144. }
  145. state.lastKey = key;
  146. state.lastNeedle = needle;
  147. return (state.lastIndex = binarySearch(haystack, needle, low, high));
  148. }
  149. // Rebuilds the original source files, with mappings that are ordered by source line/column instead
  150. // of generated line/column.
  151. function buildBySources(decoded, memos) {
  152. const sources = memos.map(buildNullArray);
  153. for (let i = 0; i < decoded.length; i++) {
  154. const line = decoded[i];
  155. for (let j = 0; j < line.length; j++) {
  156. const seg = line[j];
  157. if (seg.length === 1)
  158. continue;
  159. const sourceIndex = seg[SOURCES_INDEX];
  160. const sourceLine = seg[SOURCE_LINE];
  161. const sourceColumn = seg[SOURCE_COLUMN];
  162. const originalSource = sources[sourceIndex];
  163. const originalLine = (originalSource[sourceLine] || (originalSource[sourceLine] = []));
  164. const memo = memos[sourceIndex];
  165. // The binary search either found a match, or it found the left-index just before where the
  166. // segment should go. Either way, we want to insert after that. And there may be multiple
  167. // generated segments associated with an original location, so there may need to move several
  168. // indexes before we find where we need to insert.
  169. const index = upperBound(originalLine, sourceColumn, memoizedBinarySearch(originalLine, sourceColumn, memo, sourceLine));
  170. insert(originalLine, (memo.lastIndex = index + 1), [sourceColumn, i, seg[COLUMN]]);
  171. }
  172. }
  173. return sources;
  174. }
  175. function insert(array, index, value) {
  176. for (let i = array.length; i > index; i--) {
  177. array[i] = array[i - 1];
  178. }
  179. array[index] = value;
  180. }
  181. // Null arrays allow us to use ordered index keys without actually allocating contiguous memory like
  182. // a real array. We use a null-prototype object to avoid prototype pollution and deoptimizations.
  183. // Numeric properties on objects are magically sorted in ascending order by the engine regardless of
  184. // the insertion order. So, by setting any numeric keys, even out of order, we'll get ascending
  185. // order when iterating with for-in.
  186. function buildNullArray() {
  187. return { __proto__: null };
  188. }
  189. const AnyMap = function (map, mapUrl) {
  190. const parsed = typeof map === 'string' ? JSON.parse(map) : map;
  191. if (!('sections' in parsed))
  192. return new TraceMap(parsed, mapUrl);
  193. const mappings = [];
  194. const sources = [];
  195. const sourcesContent = [];
  196. const names = [];
  197. const { sections } = parsed;
  198. let i = 0;
  199. for (; i < sections.length - 1; i++) {
  200. const no = sections[i + 1].offset;
  201. addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, no.line, no.column);
  202. }
  203. if (sections.length > 0) {
  204. addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, Infinity, Infinity);
  205. }
  206. const joined = {
  207. version: 3,
  208. file: parsed.file,
  209. names,
  210. sources,
  211. sourcesContent,
  212. mappings,
  213. };
  214. return exports.presortedDecodedMap(joined);
  215. };
  216. function addSection(section, mapUrl, mappings, sources, sourcesContent, names, stopLine, stopColumn) {
  217. const map = AnyMap(section.map, mapUrl);
  218. const { line: lineOffset, column: columnOffset } = section.offset;
  219. const sourcesOffset = sources.length;
  220. const namesOffset = names.length;
  221. const decoded = exports.decodedMappings(map);
  222. const { resolvedSources } = map;
  223. append(sources, resolvedSources);
  224. append(sourcesContent, map.sourcesContent || fillSourcesContent(resolvedSources.length));
  225. append(names, map.names);
  226. // If this section jumps forwards several lines, we need to add lines to the output mappings catch up.
  227. for (let i = mappings.length; i <= lineOffset; i++)
  228. mappings.push([]);
  229. // We can only add so many lines before we step into the range that the next section's map
  230. // controls. When we get to the last line, then we'll start checking the segments to see if
  231. // they've crossed into the column range.
  232. const stopI = stopLine - lineOffset;
  233. const len = Math.min(decoded.length, stopI + 1);
  234. for (let i = 0; i < len; i++) {
  235. const line = decoded[i];
  236. // On the 0th loop, the line will already exist due to a previous section, or the line catch up
  237. // loop above.
  238. const out = i === 0 ? mappings[lineOffset] : (mappings[lineOffset + i] = []);
  239. // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the
  240. // map can be multiple lines), it doesn't.
  241. const cOffset = i === 0 ? columnOffset : 0;
  242. for (let j = 0; j < line.length; j++) {
  243. const seg = line[j];
  244. const column = cOffset + seg[COLUMN];
  245. // If this segment steps into the column range that the next section's map controls, we need
  246. // to stop early.
  247. if (i === stopI && column >= stopColumn)
  248. break;
  249. if (seg.length === 1) {
  250. out.push([column]);
  251. continue;
  252. }
  253. const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];
  254. const sourceLine = seg[SOURCE_LINE];
  255. const sourceColumn = seg[SOURCE_COLUMN];
  256. if (seg.length === 4) {
  257. out.push([column, sourcesIndex, sourceLine, sourceColumn]);
  258. continue;
  259. }
  260. out.push([column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]);
  261. }
  262. }
  263. }
  264. function append(arr, other) {
  265. for (let i = 0; i < other.length; i++)
  266. arr.push(other[i]);
  267. }
  268. // Sourcemaps don't need to have sourcesContent, and if they don't, we need to create an array of
  269. // equal length to the sources. This is because the sources and sourcesContent are paired arrays,
  270. // where `sourcesContent[i]` is the content of the `sources[i]` file. If we didn't, then joined
  271. // sourcemap would desynchronize the sources/contents.
  272. function fillSourcesContent(len) {
  273. const sourcesContent = [];
  274. for (let i = 0; i < len; i++)
  275. sourcesContent[i] = null;
  276. return sourcesContent;
  277. }
  278. const INVALID_ORIGINAL_MAPPING = Object.freeze({
  279. source: null,
  280. line: null,
  281. column: null,
  282. name: null,
  283. });
  284. const INVALID_GENERATED_MAPPING = Object.freeze({
  285. line: null,
  286. column: null,
  287. });
  288. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  289. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  290. const LEAST_UPPER_BOUND = -1;
  291. const GREATEST_LOWER_BOUND = 1;
  292. /**
  293. * Returns the encoded (VLQ string) form of the SourceMap's mappings field.
  294. */
  295. exports.encodedMappings = void 0;
  296. /**
  297. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  298. */
  299. exports.decodedMappings = void 0;
  300. /**
  301. * A low-level API to find the segment associated with a generated line/column (think, from a
  302. * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
  303. */
  304. exports.traceSegment = void 0;
  305. /**
  306. * A higher-level API to find the source/line/column associated with a generated line/column
  307. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  308. * `source-map` library.
  309. */
  310. exports.originalPositionFor = void 0;
  311. /**
  312. * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided
  313. * the found mapping is from the same source and line as the originalPositionFor mapping.
  314. *
  315. * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1`
  316. * using the same needle that would return `id` when calling `originalPositionFor`.
  317. */
  318. exports.generatedPositionFor = void 0;
  319. /**
  320. * Iterates each mapping in generated position order.
  321. */
  322. exports.eachMapping = void 0;
  323. /**
  324. * A helper that skips sorting of the input map's mappings array, which can be expensive for larger
  325. * maps.
  326. */
  327. exports.presortedDecodedMap = void 0;
  328. /**
  329. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  330. * a sourcemap, or to JSON.stringify.
  331. */
  332. exports.decodedMap = void 0;
  333. /**
  334. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  335. * a sourcemap, or to JSON.stringify.
  336. */
  337. exports.encodedMap = void 0;
  338. class TraceMap {
  339. constructor(map, mapUrl) {
  340. this._decodedMemo = memoizedState();
  341. this._bySources = undefined;
  342. this._bySourceMemos = undefined;
  343. const isString = typeof map === 'string';
  344. if (!isString && map.constructor === TraceMap)
  345. return map;
  346. const parsed = (isString ? JSON.parse(map) : map);
  347. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  348. this.version = version;
  349. this.file = file;
  350. this.names = names;
  351. this.sourceRoot = sourceRoot;
  352. this.sources = sources;
  353. this.sourcesContent = sourcesContent;
  354. if (sourceRoot || mapUrl) {
  355. const from = resolve(sourceRoot || '', stripFilename(mapUrl));
  356. this.resolvedSources = sources.map((s) => resolve(s || '', from));
  357. }
  358. else {
  359. this.resolvedSources = sources.map((s) => s || '');
  360. }
  361. const { mappings } = parsed;
  362. if (typeof mappings === 'string') {
  363. this._encoded = mappings;
  364. this._decoded = undefined;
  365. }
  366. else {
  367. this._encoded = undefined;
  368. this._decoded = maybeSort(mappings, isString);
  369. }
  370. }
  371. }
  372. (() => {
  373. exports.encodedMappings = (map) => {
  374. var _a;
  375. return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = sourcemapCodec.encode(map._decoded)));
  376. };
  377. exports.decodedMappings = (map) => {
  378. return (map._decoded || (map._decoded = sourcemapCodec.decode(map._encoded)));
  379. };
  380. exports.traceSegment = (map, line, column) => {
  381. const decoded = exports.decodedMappings(map);
  382. // It's common for parent source maps to have pointers to lines that have no
  383. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  384. if (line >= decoded.length)
  385. return null;
  386. return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  387. };
  388. exports.originalPositionFor = (map, { line, column, bias }) => {
  389. line--;
  390. if (line < 0)
  391. throw new Error(LINE_GTR_ZERO);
  392. if (column < 0)
  393. throw new Error(COL_GTR_EQ_ZERO);
  394. const decoded = exports.decodedMappings(map);
  395. // It's common for parent source maps to have pointers to lines that have no
  396. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  397. if (line >= decoded.length)
  398. return INVALID_ORIGINAL_MAPPING;
  399. const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  400. if (segment == null)
  401. return INVALID_ORIGINAL_MAPPING;
  402. if (segment.length == 1)
  403. return INVALID_ORIGINAL_MAPPING;
  404. const { names, resolvedSources } = map;
  405. return {
  406. source: resolvedSources[segment[SOURCES_INDEX]],
  407. line: segment[SOURCE_LINE] + 1,
  408. column: segment[SOURCE_COLUMN],
  409. name: segment.length === 5 ? names[segment[NAMES_INDEX]] : null,
  410. };
  411. };
  412. exports.generatedPositionFor = (map, { source, line, column, bias }) => {
  413. line--;
  414. if (line < 0)
  415. throw new Error(LINE_GTR_ZERO);
  416. if (column < 0)
  417. throw new Error(COL_GTR_EQ_ZERO);
  418. const { sources, resolvedSources } = map;
  419. let sourceIndex = sources.indexOf(source);
  420. if (sourceIndex === -1)
  421. sourceIndex = resolvedSources.indexOf(source);
  422. if (sourceIndex === -1)
  423. return INVALID_GENERATED_MAPPING;
  424. const generated = (map._bySources || (map._bySources = buildBySources(exports.decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState)))));
  425. const memos = map._bySourceMemos;
  426. const segments = generated[sourceIndex][line];
  427. if (segments == null)
  428. return INVALID_GENERATED_MAPPING;
  429. const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND);
  430. if (segment == null)
  431. return INVALID_GENERATED_MAPPING;
  432. return {
  433. line: segment[REV_GENERATED_LINE] + 1,
  434. column: segment[REV_GENERATED_COLUMN],
  435. };
  436. };
  437. exports.eachMapping = (map, cb) => {
  438. const decoded = exports.decodedMappings(map);
  439. const { names, resolvedSources } = map;
  440. for (let i = 0; i < decoded.length; i++) {
  441. const line = decoded[i];
  442. for (let j = 0; j < line.length; j++) {
  443. const seg = line[j];
  444. const generatedLine = i + 1;
  445. const generatedColumn = seg[0];
  446. let source = null;
  447. let originalLine = null;
  448. let originalColumn = null;
  449. let name = null;
  450. if (seg.length !== 1) {
  451. source = resolvedSources[seg[1]];
  452. originalLine = seg[2] + 1;
  453. originalColumn = seg[3];
  454. }
  455. if (seg.length === 5)
  456. name = names[seg[4]];
  457. cb({
  458. generatedLine,
  459. generatedColumn,
  460. source,
  461. originalLine,
  462. originalColumn,
  463. name,
  464. });
  465. }
  466. }
  467. };
  468. exports.presortedDecodedMap = (map, mapUrl) => {
  469. const clone = Object.assign({}, map);
  470. clone.mappings = [];
  471. const tracer = new TraceMap(clone, mapUrl);
  472. tracer._decoded = map.mappings;
  473. return tracer;
  474. };
  475. exports.decodedMap = (map) => {
  476. return {
  477. version: 3,
  478. file: map.file,
  479. names: map.names,
  480. sourceRoot: map.sourceRoot,
  481. sources: map.sources,
  482. sourcesContent: map.sourcesContent,
  483. mappings: exports.decodedMappings(map),
  484. };
  485. };
  486. exports.encodedMap = (map) => {
  487. return {
  488. version: 3,
  489. file: map.file,
  490. names: map.names,
  491. sourceRoot: map.sourceRoot,
  492. sources: map.sources,
  493. sourcesContent: map.sourcesContent,
  494. mappings: exports.encodedMappings(map),
  495. };
  496. };
  497. })();
  498. function traceSegmentInternal(segments, memo, line, column, bias) {
  499. let index = memoizedBinarySearch(segments, column, memo, line);
  500. if (found) {
  501. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  502. }
  503. else if (bias === LEAST_UPPER_BOUND)
  504. index++;
  505. if (index === -1 || index === segments.length)
  506. return null;
  507. return segments[index];
  508. }
  509. exports.AnyMap = AnyMap;
  510. exports.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND;
  511. exports.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND;
  512. exports.TraceMap = TraceMap;
  513. Object.defineProperty(exports, '__esModule', { value: true });
  514. }));
  515. //# sourceMappingURL=trace-mapping.umd.js.map