trace-mapping.umd.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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; index = i++) {
  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; index = i--) {
  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. recurse(parsed, mapUrl, mappings, sources, sourcesContent, names, 0, 0, Infinity, Infinity);
  198. const joined = {
  199. version: 3,
  200. file: parsed.file,
  201. names,
  202. sources,
  203. sourcesContent,
  204. mappings,
  205. };
  206. return exports.presortedDecodedMap(joined);
  207. };
  208. function recurse(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) {
  209. const { sections } = input;
  210. for (let i = 0; i < sections.length; i++) {
  211. const { map, offset } = sections[i];
  212. let sl = stopLine;
  213. let sc = stopColumn;
  214. if (i + 1 < sections.length) {
  215. const nextOffset = sections[i + 1].offset;
  216. sl = Math.min(stopLine, lineOffset + nextOffset.line);
  217. if (sl === stopLine) {
  218. sc = Math.min(stopColumn, columnOffset + nextOffset.column);
  219. }
  220. else if (sl < stopLine) {
  221. sc = columnOffset + nextOffset.column;
  222. }
  223. }
  224. addSection(map, mapUrl, mappings, sources, sourcesContent, names, lineOffset + offset.line, columnOffset + offset.column, sl, sc);
  225. }
  226. }
  227. function addSection(input, mapUrl, mappings, sources, sourcesContent, names, lineOffset, columnOffset, stopLine, stopColumn) {
  228. if ('sections' in input)
  229. return recurse(...arguments);
  230. const map = new TraceMap(input, mapUrl);
  231. const sourcesOffset = sources.length;
  232. const namesOffset = names.length;
  233. const decoded = exports.decodedMappings(map);
  234. const { resolvedSources, sourcesContent: contents } = map;
  235. append(sources, resolvedSources);
  236. append(names, map.names);
  237. if (contents)
  238. append(sourcesContent, contents);
  239. else
  240. for (let i = 0; i < resolvedSources.length; i++)
  241. sourcesContent.push(null);
  242. for (let i = 0; i < decoded.length; i++) {
  243. const lineI = lineOffset + i;
  244. // We can only add so many lines before we step into the range that the next section's map
  245. // controls. When we get to the last line, then we'll start checking the segments to see if
  246. // they've crossed into the column range. But it may not have any columns that overstep, so we
  247. // still need to check that we don't overstep lines, too.
  248. if (lineI > stopLine)
  249. return;
  250. // The out line may already exist in mappings (if we're continuing the line started by a
  251. // previous section). Or, we may have jumped ahead several lines to start this section.
  252. const out = getLine(mappings, lineI);
  253. // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the
  254. // map can be multiple lines), it doesn't.
  255. const cOffset = i === 0 ? columnOffset : 0;
  256. const line = decoded[i];
  257. for (let j = 0; j < line.length; j++) {
  258. const seg = line[j];
  259. const column = cOffset + seg[COLUMN];
  260. // If this segment steps into the column range that the next section's map controls, we need
  261. // to stop early.
  262. if (lineI === stopLine && column >= stopColumn)
  263. return;
  264. if (seg.length === 1) {
  265. out.push([column]);
  266. continue;
  267. }
  268. const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX];
  269. const sourceLine = seg[SOURCE_LINE];
  270. const sourceColumn = seg[SOURCE_COLUMN];
  271. out.push(seg.length === 4
  272. ? [column, sourcesIndex, sourceLine, sourceColumn]
  273. : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]]);
  274. }
  275. }
  276. }
  277. function append(arr, other) {
  278. for (let i = 0; i < other.length; i++)
  279. arr.push(other[i]);
  280. }
  281. function getLine(arr, index) {
  282. for (let i = arr.length; i <= index; i++)
  283. arr[i] = [];
  284. return arr[index];
  285. }
  286. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  287. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  288. const LEAST_UPPER_BOUND = -1;
  289. const GREATEST_LOWER_BOUND = 1;
  290. /**
  291. * Returns the encoded (VLQ string) form of the SourceMap's mappings field.
  292. */
  293. exports.encodedMappings = void 0;
  294. /**
  295. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  296. */
  297. exports.decodedMappings = void 0;
  298. /**
  299. * A low-level API to find the segment associated with a generated line/column (think, from a
  300. * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
  301. */
  302. exports.traceSegment = void 0;
  303. /**
  304. * A higher-level API to find the source/line/column associated with a generated line/column
  305. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  306. * `source-map` library.
  307. */
  308. exports.originalPositionFor = void 0;
  309. /**
  310. * Finds the source/line/column directly after the mapping returned by originalPositionFor, provided
  311. * the found mapping is from the same source and line as the originalPositionFor mapping.
  312. *
  313. * Eg, in the code `let id = 1`, `originalPositionAfter` could find the mapping associated with `1`
  314. * using the same needle that would return `id` when calling `originalPositionFor`.
  315. */
  316. exports.generatedPositionFor = void 0;
  317. /**
  318. * Iterates each mapping in generated position order.
  319. */
  320. exports.eachMapping = void 0;
  321. /**
  322. * Retrieves the source content for a particular source, if its found. Returns null if not.
  323. */
  324. exports.sourceContentFor = void 0;
  325. /**
  326. * A helper that skips sorting of the input map's mappings array, which can be expensive for larger
  327. * maps.
  328. */
  329. exports.presortedDecodedMap = void 0;
  330. /**
  331. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  332. * a sourcemap, or to JSON.stringify.
  333. */
  334. exports.decodedMap = void 0;
  335. /**
  336. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  337. * a sourcemap, or to JSON.stringify.
  338. */
  339. exports.encodedMap = void 0;
  340. class TraceMap {
  341. constructor(map, mapUrl) {
  342. this._decodedMemo = memoizedState();
  343. this._bySources = undefined;
  344. this._bySourceMemos = undefined;
  345. const isString = typeof map === 'string';
  346. if (!isString && map._decodedMemo)
  347. return map;
  348. const parsed = (isString ? JSON.parse(map) : map);
  349. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  350. this.version = version;
  351. this.file = file;
  352. this.names = names;
  353. this.sourceRoot = sourceRoot;
  354. this.sources = sources;
  355. this.sourcesContent = sourcesContent;
  356. const from = resolve(sourceRoot || '', stripFilename(mapUrl));
  357. this.resolvedSources = sources.map((s) => resolve(s || '', from));
  358. const { mappings } = parsed;
  359. if (typeof mappings === 'string') {
  360. this._encoded = mappings;
  361. this._decoded = undefined;
  362. }
  363. else {
  364. this._encoded = undefined;
  365. this._decoded = maybeSort(mappings, isString);
  366. }
  367. }
  368. }
  369. (() => {
  370. exports.encodedMappings = (map) => {
  371. var _a;
  372. return ((_a = map._encoded) !== null && _a !== void 0 ? _a : (map._encoded = sourcemapCodec.encode(map._decoded)));
  373. };
  374. exports.decodedMappings = (map) => {
  375. return (map._decoded || (map._decoded = sourcemapCodec.decode(map._encoded)));
  376. };
  377. exports.traceSegment = (map, line, column) => {
  378. const decoded = exports.decodedMappings(map);
  379. // It's common for parent source maps to have pointers to lines that have no
  380. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  381. if (line >= decoded.length)
  382. return null;
  383. return traceSegmentInternal(decoded[line], map._decodedMemo, line, column, GREATEST_LOWER_BOUND);
  384. };
  385. exports.originalPositionFor = (map, { line, column, bias }) => {
  386. line--;
  387. if (line < 0)
  388. throw new Error(LINE_GTR_ZERO);
  389. if (column < 0)
  390. throw new Error(COL_GTR_EQ_ZERO);
  391. const decoded = exports.decodedMappings(map);
  392. // It's common for parent source maps to have pointers to lines that have no
  393. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  394. if (line >= decoded.length)
  395. return OMapping(null, null, null, null);
  396. const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  397. if (segment == null)
  398. return OMapping(null, null, null, null);
  399. if (segment.length == 1)
  400. return OMapping(null, null, null, null);
  401. const { names, resolvedSources } = map;
  402. return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
  403. };
  404. exports.generatedPositionFor = (map, { source, line, column, bias }) => {
  405. line--;
  406. if (line < 0)
  407. throw new Error(LINE_GTR_ZERO);
  408. if (column < 0)
  409. throw new Error(COL_GTR_EQ_ZERO);
  410. const { sources, resolvedSources } = map;
  411. let sourceIndex = sources.indexOf(source);
  412. if (sourceIndex === -1)
  413. sourceIndex = resolvedSources.indexOf(source);
  414. if (sourceIndex === -1)
  415. return GMapping(null, null);
  416. const generated = (map._bySources || (map._bySources = buildBySources(exports.decodedMappings(map), (map._bySourceMemos = sources.map(memoizedState)))));
  417. const memos = map._bySourceMemos;
  418. const segments = generated[sourceIndex][line];
  419. if (segments == null)
  420. return GMapping(null, null);
  421. const segment = traceSegmentInternal(segments, memos[sourceIndex], line, column, bias || GREATEST_LOWER_BOUND);
  422. if (segment == null)
  423. return GMapping(null, null);
  424. return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);
  425. };
  426. exports.eachMapping = (map, cb) => {
  427. const decoded = exports.decodedMappings(map);
  428. const { names, resolvedSources } = map;
  429. for (let i = 0; i < decoded.length; i++) {
  430. const line = decoded[i];
  431. for (let j = 0; j < line.length; j++) {
  432. const seg = line[j];
  433. const generatedLine = i + 1;
  434. const generatedColumn = seg[0];
  435. let source = null;
  436. let originalLine = null;
  437. let originalColumn = null;
  438. let name = null;
  439. if (seg.length !== 1) {
  440. source = resolvedSources[seg[1]];
  441. originalLine = seg[2] + 1;
  442. originalColumn = seg[3];
  443. }
  444. if (seg.length === 5)
  445. name = names[seg[4]];
  446. cb({
  447. generatedLine,
  448. generatedColumn,
  449. source,
  450. originalLine,
  451. originalColumn,
  452. name,
  453. });
  454. }
  455. }
  456. };
  457. exports.sourceContentFor = (map, source) => {
  458. const { sources, resolvedSources, sourcesContent } = map;
  459. if (sourcesContent == null)
  460. return null;
  461. let index = sources.indexOf(source);
  462. if (index === -1)
  463. index = resolvedSources.indexOf(source);
  464. return index === -1 ? null : sourcesContent[index];
  465. };
  466. exports.presortedDecodedMap = (map, mapUrl) => {
  467. const clone = Object.assign({}, map);
  468. clone.mappings = [];
  469. const tracer = new TraceMap(clone, mapUrl);
  470. tracer._decoded = map.mappings;
  471. return tracer;
  472. };
  473. exports.decodedMap = (map) => {
  474. return {
  475. version: 3,
  476. file: map.file,
  477. names: map.names,
  478. sourceRoot: map.sourceRoot,
  479. sources: map.sources,
  480. sourcesContent: map.sourcesContent,
  481. mappings: exports.decodedMappings(map),
  482. };
  483. };
  484. exports.encodedMap = (map) => {
  485. return {
  486. version: 3,
  487. file: map.file,
  488. names: map.names,
  489. sourceRoot: map.sourceRoot,
  490. sources: map.sources,
  491. sourcesContent: map.sourcesContent,
  492. mappings: exports.encodedMappings(map),
  493. };
  494. };
  495. })();
  496. function OMapping(source, line, column, name) {
  497. return { source, line, column, name };
  498. }
  499. function GMapping(line, column) {
  500. return { line, column };
  501. }
  502. function traceSegmentInternal(segments, memo, line, column, bias) {
  503. let index = memoizedBinarySearch(segments, column, memo, line);
  504. if (found) {
  505. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  506. }
  507. else if (bias === LEAST_UPPER_BOUND)
  508. index++;
  509. if (index === -1 || index === segments.length)
  510. return null;
  511. return segments[index];
  512. }
  513. exports.AnyMap = AnyMap;
  514. exports.GREATEST_LOWER_BOUND = GREATEST_LOWER_BOUND;
  515. exports.LEAST_UPPER_BOUND = LEAST_UPPER_BOUND;
  516. exports.TraceMap = TraceMap;
  517. Object.defineProperty(exports, '__esModule', { value: true });
  518. }));
  519. //# sourceMappingURL=trace-mapping.umd.js.map