source-map.umd.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sourceMap = {}));
  5. })(this, (function (exports) { 'use strict';
  6. const comma = ','.charCodeAt(0);
  7. const semicolon = ';'.charCodeAt(0);
  8. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  9. const intToChar = new Uint8Array(64); // 64 possible chars.
  10. const charToInteger = new Uint8Array(128); // z is 122 in ASCII
  11. for (let i = 0; i < chars.length; i++) {
  12. const c = chars.charCodeAt(i);
  13. charToInteger[c] = i;
  14. intToChar[i] = c;
  15. }
  16. // Provide a fallback for older environments.
  17. const td = typeof TextDecoder !== 'undefined'
  18. ? new TextDecoder()
  19. : typeof Buffer !== 'undefined'
  20. ? {
  21. decode(buf) {
  22. const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
  23. return out.toString();
  24. },
  25. }
  26. : {
  27. decode(buf) {
  28. let out = '';
  29. for (let i = 0; i < buf.length; i++) {
  30. out += String.fromCharCode(buf[i]);
  31. }
  32. return out;
  33. },
  34. };
  35. function decode(mappings) {
  36. const state = new Int32Array(5);
  37. const decoded = [];
  38. let line = [];
  39. let sorted = true;
  40. let lastCol = 0;
  41. for (let i = 0; i < mappings.length;) {
  42. const c = mappings.charCodeAt(i);
  43. if (c === comma) {
  44. i++;
  45. }
  46. else if (c === semicolon) {
  47. state[0] = lastCol = 0;
  48. if (!sorted)
  49. sort(line);
  50. sorted = true;
  51. decoded.push(line);
  52. line = [];
  53. i++;
  54. }
  55. else {
  56. i = decodeInteger(mappings, i, state, 0); // generatedCodeColumn
  57. const col = state[0];
  58. if (col < lastCol)
  59. sorted = false;
  60. lastCol = col;
  61. if (!hasMoreSegments(mappings, i)) {
  62. line.push([col]);
  63. continue;
  64. }
  65. i = decodeInteger(mappings, i, state, 1); // sourceFileIndex
  66. i = decodeInteger(mappings, i, state, 2); // sourceCodeLine
  67. i = decodeInteger(mappings, i, state, 3); // sourceCodeColumn
  68. if (!hasMoreSegments(mappings, i)) {
  69. line.push([col, state[1], state[2], state[3]]);
  70. continue;
  71. }
  72. i = decodeInteger(mappings, i, state, 4); // nameIndex
  73. line.push([col, state[1], state[2], state[3], state[4]]);
  74. }
  75. }
  76. if (!sorted)
  77. sort(line);
  78. decoded.push(line);
  79. return decoded;
  80. }
  81. function decodeInteger(mappings, pos, state, j) {
  82. let value = 0;
  83. let shift = 0;
  84. let integer = 0;
  85. do {
  86. const c = mappings.charCodeAt(pos++);
  87. integer = charToInteger[c];
  88. value |= (integer & 31) << shift;
  89. shift += 5;
  90. } while (integer & 32);
  91. const shouldNegate = value & 1;
  92. value >>>= 1;
  93. if (shouldNegate) {
  94. value = -0x80000000 | -value;
  95. }
  96. state[j] += value;
  97. return pos;
  98. }
  99. function hasMoreSegments(mappings, i) {
  100. if (i >= mappings.length)
  101. return false;
  102. const c = mappings.charCodeAt(i);
  103. if (c === comma || c === semicolon)
  104. return false;
  105. return true;
  106. }
  107. function sort(line) {
  108. line.sort(sortComparator$1);
  109. }
  110. function sortComparator$1(a, b) {
  111. return a[0] - b[0];
  112. }
  113. function encode(decoded) {
  114. const state = new Int32Array(5);
  115. let buf = new Uint8Array(1024);
  116. let pos = 0;
  117. for (let i = 0; i < decoded.length; i++) {
  118. const line = decoded[i];
  119. if (i > 0) {
  120. buf = reserve(buf, pos, 1);
  121. buf[pos++] = semicolon;
  122. }
  123. if (line.length === 0)
  124. continue;
  125. state[0] = 0;
  126. for (let j = 0; j < line.length; j++) {
  127. const segment = line[j];
  128. // We can push up to 5 ints, each int can take at most 7 chars, and we
  129. // may push a comma.
  130. buf = reserve(buf, pos, 36);
  131. if (j > 0)
  132. buf[pos++] = comma;
  133. pos = encodeInteger(buf, pos, state, segment, 0); // generatedCodeColumn
  134. if (segment.length === 1)
  135. continue;
  136. pos = encodeInteger(buf, pos, state, segment, 1); // sourceFileIndex
  137. pos = encodeInteger(buf, pos, state, segment, 2); // sourceCodeLine
  138. pos = encodeInteger(buf, pos, state, segment, 3); // sourceCodeColumn
  139. if (segment.length === 4)
  140. continue;
  141. pos = encodeInteger(buf, pos, state, segment, 4); // nameIndex
  142. }
  143. }
  144. return td.decode(buf.subarray(0, pos));
  145. }
  146. function reserve(buf, pos, count) {
  147. if (buf.length > pos + count)
  148. return buf;
  149. const swap = new Uint8Array(buf.length * 2);
  150. swap.set(buf);
  151. return swap;
  152. }
  153. function encodeInteger(buf, pos, state, segment, j) {
  154. const next = segment[j];
  155. let num = next - state[j];
  156. state[j] = next;
  157. num = num < 0 ? (-num << 1) | 1 : num << 1;
  158. do {
  159. let clamped = num & 0b011111;
  160. num >>>= 5;
  161. if (num > 0)
  162. clamped |= 0b100000;
  163. buf[pos++] = intToChar[clamped];
  164. } while (num > 0);
  165. return pos;
  166. }
  167. // Matches the scheme of a URL, eg "http://"
  168. const schemeRegex = /^[\w+.-]+:\/\//;
  169. /**
  170. * Matches the parts of a URL:
  171. * 1. Scheme, including ":", guaranteed.
  172. * 2. User/password, including "@", optional.
  173. * 3. Host, guaranteed.
  174. * 4. Port, including ":", optional.
  175. * 5. Path, including "/", optional.
  176. */
  177. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?/;
  178. /**
  179. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  180. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  181. *
  182. * 1. Host, optional.
  183. * 2. Path, which may inclue "/", guaranteed.
  184. */
  185. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/]*)?)?(\/?.*)/i;
  186. function isAbsoluteUrl(input) {
  187. return schemeRegex.test(input);
  188. }
  189. function isSchemeRelativeUrl(input) {
  190. return input.startsWith('//');
  191. }
  192. function isAbsolutePath(input) {
  193. return input.startsWith('/');
  194. }
  195. function isFileUrl(input) {
  196. return input.startsWith('file:');
  197. }
  198. function parseAbsoluteUrl(input) {
  199. const match = urlRegex.exec(input);
  200. return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/');
  201. }
  202. function parseFileUrl(input) {
  203. const match = fileRegex.exec(input);
  204. const path = match[2];
  205. return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path);
  206. }
  207. function makeUrl(scheme, user, host, port, path) {
  208. return {
  209. scheme,
  210. user,
  211. host,
  212. port,
  213. path,
  214. relativePath: false,
  215. };
  216. }
  217. function parseUrl(input) {
  218. if (isSchemeRelativeUrl(input)) {
  219. const url = parseAbsoluteUrl('http:' + input);
  220. url.scheme = '';
  221. return url;
  222. }
  223. if (isAbsolutePath(input)) {
  224. const url = parseAbsoluteUrl('http://foo.com' + input);
  225. url.scheme = '';
  226. url.host = '';
  227. return url;
  228. }
  229. if (isFileUrl(input))
  230. return parseFileUrl(input);
  231. if (isAbsoluteUrl(input))
  232. return parseAbsoluteUrl(input);
  233. const url = parseAbsoluteUrl('http://foo.com/' + input);
  234. url.scheme = '';
  235. url.host = '';
  236. url.relativePath = true;
  237. return url;
  238. }
  239. function stripPathFilename(path) {
  240. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  241. // paths. It's not a file, so we can't strip it.
  242. if (path.endsWith('/..'))
  243. return path;
  244. const index = path.lastIndexOf('/');
  245. return path.slice(0, index + 1);
  246. }
  247. function mergePaths(url, base) {
  248. // If we're not a relative path, then we're an absolute path, and it doesn't matter what base is.
  249. if (!url.relativePath)
  250. return;
  251. normalizePath(base);
  252. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  253. // path).
  254. if (url.path === '/') {
  255. url.path = base.path;
  256. }
  257. else {
  258. // Resolution happens relative to the base path's directory, not the file.
  259. url.path = stripPathFilename(base.path) + url.path;
  260. }
  261. // If the base path is absolute, then our path is now absolute too.
  262. url.relativePath = base.relativePath;
  263. }
  264. /**
  265. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  266. * "foo/.". We need to normalize to a standard representation.
  267. */
  268. function normalizePath(url) {
  269. const { relativePath } = url;
  270. const pieces = url.path.split('/');
  271. // We need to preserve the first piece always, so that we output a leading slash. The item at
  272. // pieces[0] is an empty string.
  273. let pointer = 1;
  274. // Positive is the number of real directories we've output, used for popping a parent directory.
  275. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  276. let positive = 0;
  277. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  278. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  279. // real directory, we won't need to append, unless the other conditions happen again.
  280. let addTrailingSlash = false;
  281. for (let i = 1; i < pieces.length; i++) {
  282. const piece = pieces[i];
  283. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  284. if (!piece) {
  285. addTrailingSlash = true;
  286. continue;
  287. }
  288. // If we encounter a real directory, then we don't need to append anymore.
  289. addTrailingSlash = false;
  290. // A current directory, which we can always drop.
  291. if (piece === '.')
  292. continue;
  293. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  294. // have an excess of parents, and we'll need to keep the "..".
  295. if (piece === '..') {
  296. if (positive) {
  297. addTrailingSlash = true;
  298. positive--;
  299. pointer--;
  300. }
  301. else if (relativePath) {
  302. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  303. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  304. pieces[pointer++] = piece;
  305. }
  306. continue;
  307. }
  308. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  309. // any popped or dropped directories.
  310. pieces[pointer++] = piece;
  311. positive++;
  312. }
  313. let path = '';
  314. for (let i = 1; i < pointer; i++) {
  315. path += '/' + pieces[i];
  316. }
  317. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  318. path += '/';
  319. }
  320. url.path = path;
  321. }
  322. /**
  323. * Attempts to resolve `input` URL/path relative to `base`.
  324. */
  325. function resolve$1(input, base) {
  326. if (!input && !base)
  327. return '';
  328. const url = parseUrl(input);
  329. // If we have a base, and the input isn't already an absolute URL, then we need to merge.
  330. if (base && !url.scheme) {
  331. const baseUrl = parseUrl(base);
  332. url.scheme = baseUrl.scheme;
  333. // If there's no host, then we were just a path.
  334. if (!url.host) {
  335. // The host, user, and port are joined, you can't copy one without the others.
  336. url.user = baseUrl.user;
  337. url.host = baseUrl.host;
  338. url.port = baseUrl.port;
  339. }
  340. mergePaths(url, baseUrl);
  341. }
  342. normalizePath(url);
  343. // If the input (and base, if there was one) are both relative, then we need to output a relative.
  344. if (url.relativePath) {
  345. // The first char is always a "/".
  346. const path = url.path.slice(1);
  347. if (!path)
  348. return '.';
  349. // If base started with a leading ".", or there is no base and input started with a ".", then we
  350. // need to ensure that the relative path starts with a ".". We don't know if relative starts
  351. // with a "..", though, so check before prepending.
  352. const keepRelative = (base || input).startsWith('.');
  353. return !keepRelative || path.startsWith('.') ? path : './' + path;
  354. }
  355. // If there's no host (and no scheme/user/port), then we need to output an absolute path.
  356. if (!url.scheme && !url.host)
  357. return url.path;
  358. // We're outputting either an absolute URL, or a protocol relative one.
  359. return `${url.scheme}//${url.user}${url.host}${url.port}${url.path}`;
  360. }
  361. function resolve(input, base) {
  362. // The base is always treated as a directory, if it's not empty.
  363. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  364. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  365. if (base && !base.endsWith('/'))
  366. base += '/';
  367. return resolve$1(input, base);
  368. }
  369. /**
  370. * Removes everything after the last "/", but leaves the slash.
  371. */
  372. function stripFilename(path) {
  373. if (!path)
  374. return '';
  375. const index = path.lastIndexOf('/');
  376. return path.slice(0, index + 1);
  377. }
  378. const COLUMN$1 = 0;
  379. const SOURCES_INDEX$1 = 1;
  380. const SOURCE_LINE$1 = 2;
  381. const SOURCE_COLUMN$1 = 3;
  382. const NAMES_INDEX$1 = 4;
  383. function maybeSort(mappings, owned) {
  384. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  385. if (unsortedIndex === mappings.length)
  386. return mappings;
  387. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  388. // not, we do not want to modify the consumer's input array.
  389. if (!owned)
  390. mappings = mappings.slice();
  391. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  392. mappings[i] = sortSegments(mappings[i], owned);
  393. }
  394. return mappings;
  395. }
  396. function nextUnsortedSegmentLine(mappings, start) {
  397. for (let i = start; i < mappings.length; i++) {
  398. if (!isSorted(mappings[i]))
  399. return i;
  400. }
  401. return mappings.length;
  402. }
  403. function isSorted(line) {
  404. for (let j = 1; j < line.length; j++) {
  405. if (line[j][COLUMN$1] < line[j - 1][COLUMN$1]) {
  406. return false;
  407. }
  408. }
  409. return true;
  410. }
  411. function sortSegments(line, owned) {
  412. if (!owned)
  413. line = line.slice();
  414. return line.sort(sortComparator);
  415. }
  416. function sortComparator(a, b) {
  417. return a[COLUMN$1] - b[COLUMN$1];
  418. }
  419. let found = false;
  420. /**
  421. * A binary search implementation that returns the index if a match is found.
  422. * If no match is found, then the left-index (the index associated with the item that comes just
  423. * before the desired index) is returned. To maintain proper sort order, a splice would happen at
  424. * the next index:
  425. *
  426. * ```js
  427. * const array = [1, 3];
  428. * const needle = 2;
  429. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  430. *
  431. * assert.equal(index, 0);
  432. * array.splice(index + 1, 0, needle);
  433. * assert.deepEqual(array, [1, 2, 3]);
  434. * ```
  435. */
  436. function binarySearch(haystack, needle, low, high) {
  437. while (low <= high) {
  438. const mid = low + ((high - low) >> 1);
  439. const cmp = haystack[mid][COLUMN$1] - needle;
  440. if (cmp === 0) {
  441. found = true;
  442. return mid;
  443. }
  444. if (cmp < 0) {
  445. low = mid + 1;
  446. }
  447. else {
  448. high = mid - 1;
  449. }
  450. }
  451. found = false;
  452. return low - 1;
  453. }
  454. function upperBound(haystack, needle, index) {
  455. for (let i = index + 1; i < haystack.length; i++, index++) {
  456. if (haystack[i][COLUMN$1] !== needle)
  457. break;
  458. }
  459. return index;
  460. }
  461. function lowerBound(haystack, needle, index) {
  462. for (let i = index - 1; i >= 0; i--, index--) {
  463. if (haystack[i][COLUMN$1] !== needle)
  464. break;
  465. }
  466. return index;
  467. }
  468. function memoizedState() {
  469. return {
  470. lastKey: -1,
  471. lastNeedle: -1,
  472. lastIndex: -1,
  473. };
  474. }
  475. /**
  476. * This overly complicated beast is just to record the last tested line/column and the resulting
  477. * index, allowing us to skip a few tests if mappings are monotonically increasing.
  478. */
  479. function memoizedBinarySearch(haystack, needle, state, key) {
  480. const { lastKey, lastNeedle, lastIndex } = state;
  481. let low = 0;
  482. let high = haystack.length - 1;
  483. if (key === lastKey) {
  484. if (needle === lastNeedle) {
  485. found = lastIndex !== -1 && haystack[lastIndex][COLUMN$1] === needle;
  486. return lastIndex;
  487. }
  488. if (needle >= lastNeedle) {
  489. // lastIndex may be -1 if the previous needle was not found.
  490. low = lastIndex === -1 ? 0 : lastIndex;
  491. }
  492. else {
  493. high = lastIndex;
  494. }
  495. }
  496. state.lastKey = key;
  497. state.lastNeedle = needle;
  498. return (state.lastIndex = binarySearch(haystack, needle, low, high));
  499. }
  500. const AnyMap = function (map, mapUrl) {
  501. const parsed = typeof map === 'string' ? JSON.parse(map) : map;
  502. if (!('sections' in parsed))
  503. return new TraceMap(parsed, mapUrl);
  504. const mappings = [];
  505. const sources = [];
  506. const sourcesContent = [];
  507. const names = [];
  508. const { sections } = parsed;
  509. let i = 0;
  510. for (; i < sections.length - 1; i++) {
  511. const no = sections[i + 1].offset;
  512. addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, no.line, no.column);
  513. }
  514. if (sections.length > 0) {
  515. addSection(sections[i], mapUrl, mappings, sources, sourcesContent, names, Infinity, Infinity);
  516. }
  517. const joined = {
  518. version: 3,
  519. file: parsed.file,
  520. names,
  521. sources,
  522. sourcesContent,
  523. mappings,
  524. };
  525. return presortedDecodedMap(joined);
  526. };
  527. function addSection(section, mapUrl, mappings, sources, sourcesContent, names, stopLine, stopColumn) {
  528. const map = AnyMap(section.map, mapUrl);
  529. const { line: lineOffset, column: columnOffset } = section.offset;
  530. const sourcesOffset = sources.length;
  531. const namesOffset = names.length;
  532. const decoded = decodedMappings(map);
  533. const { resolvedSources } = map;
  534. append(sources, resolvedSources);
  535. append(sourcesContent, map.sourcesContent || fillSourcesContent(resolvedSources.length));
  536. append(names, map.names);
  537. // If this section jumps forwards several lines, we need to add lines to the output mappings catch up.
  538. for (let i = mappings.length; i <= lineOffset; i++)
  539. mappings.push([]);
  540. // We can only add so many lines before we step into the range that the next section's map
  541. // controls. When we get to the last line, then we'll start checking the segments to see if
  542. // they've crossed into the column range.
  543. const stopI = stopLine - lineOffset;
  544. const len = Math.min(decoded.length, stopI + 1);
  545. for (let i = 0; i < len; i++) {
  546. const line = decoded[i];
  547. // On the 0th loop, the line will already exist due to a previous section, or the line catch up
  548. // loop above.
  549. const out = i === 0 ? mappings[lineOffset] : (mappings[lineOffset + i] = []);
  550. // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the
  551. // map can be multiple lines), it doesn't.
  552. const cOffset = i === 0 ? columnOffset : 0;
  553. for (let j = 0; j < line.length; j++) {
  554. const seg = line[j];
  555. const column = cOffset + seg[COLUMN$1];
  556. // If this segment steps into the column range that the next section's map controls, we need
  557. // to stop early.
  558. if (i === stopI && column >= stopColumn)
  559. break;
  560. if (seg.length === 1) {
  561. out.push([column]);
  562. continue;
  563. }
  564. const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX$1];
  565. const sourceLine = seg[SOURCE_LINE$1];
  566. const sourceColumn = seg[SOURCE_COLUMN$1];
  567. if (seg.length === 4) {
  568. out.push([column, sourcesIndex, sourceLine, sourceColumn]);
  569. continue;
  570. }
  571. out.push([column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX$1]]);
  572. }
  573. }
  574. }
  575. function append(arr, other) {
  576. for (let i = 0; i < other.length; i++)
  577. arr.push(other[i]);
  578. }
  579. // Sourcemaps don't need to have sourcesContent, and if they don't, we need to create an array of
  580. // equal length to the sources. This is because the sources and sourcesContent are paired arrays,
  581. // where `sourcesContent[i]` is the content of the `sources[i]` file. If we didn't, then joined
  582. // sourcemap would desynchronize the sources/contents.
  583. function fillSourcesContent(len) {
  584. const sourcesContent = [];
  585. for (let i = 0; i < len; i++)
  586. sourcesContent[i] = null;
  587. return sourcesContent;
  588. }
  589. const INVALID_ORIGINAL_MAPPING = Object.freeze({
  590. source: null,
  591. line: null,
  592. column: null,
  593. name: null,
  594. });
  595. Object.freeze({
  596. line: null,
  597. column: null,
  598. });
  599. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  600. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  601. const LEAST_UPPER_BOUND = -1;
  602. const GREATEST_LOWER_BOUND = 1;
  603. /**
  604. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  605. */
  606. let decodedMappings;
  607. /**
  608. * A higher-level API to find the source/line/column associated with a generated line/column
  609. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  610. * `source-map` library.
  611. */
  612. let originalPositionFor;
  613. /**
  614. * A helper that skips sorting of the input map's mappings array, which can be expensive for larger
  615. * maps.
  616. */
  617. let presortedDecodedMap;
  618. class TraceMap {
  619. constructor(map, mapUrl) {
  620. this._decodedMemo = memoizedState();
  621. this._bySources = undefined;
  622. this._bySourceMemos = undefined;
  623. const isString = typeof map === 'string';
  624. if (!isString && map.constructor === TraceMap)
  625. return map;
  626. const parsed = (isString ? JSON.parse(map) : map);
  627. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  628. this.version = version;
  629. this.file = file;
  630. this.names = names;
  631. this.sourceRoot = sourceRoot;
  632. this.sources = sources;
  633. this.sourcesContent = sourcesContent;
  634. if (sourceRoot || mapUrl) {
  635. const from = resolve(sourceRoot || '', stripFilename(mapUrl));
  636. this.resolvedSources = sources.map((s) => resolve(s || '', from));
  637. }
  638. else {
  639. this.resolvedSources = sources.map((s) => s || '');
  640. }
  641. const { mappings } = parsed;
  642. if (typeof mappings === 'string') {
  643. this._encoded = mappings;
  644. this._decoded = undefined;
  645. }
  646. else {
  647. this._encoded = undefined;
  648. this._decoded = maybeSort(mappings, isString);
  649. }
  650. }
  651. }
  652. (() => {
  653. decodedMappings = (map) => {
  654. return (map._decoded || (map._decoded = decode(map._encoded)));
  655. };
  656. originalPositionFor = (map, { line, column, bias }) => {
  657. line--;
  658. if (line < 0)
  659. throw new Error(LINE_GTR_ZERO);
  660. if (column < 0)
  661. throw new Error(COL_GTR_EQ_ZERO);
  662. const decoded = decodedMappings(map);
  663. // It's common for parent source maps to have pointers to lines that have no
  664. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  665. if (line >= decoded.length)
  666. return INVALID_ORIGINAL_MAPPING;
  667. const segment = traceSegmentInternal(decoded[line], map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  668. if (segment == null)
  669. return INVALID_ORIGINAL_MAPPING;
  670. if (segment.length == 1)
  671. return INVALID_ORIGINAL_MAPPING;
  672. const { names, resolvedSources } = map;
  673. return {
  674. source: resolvedSources[segment[SOURCES_INDEX$1]],
  675. line: segment[SOURCE_LINE$1] + 1,
  676. column: segment[SOURCE_COLUMN$1],
  677. name: segment.length === 5 ? names[segment[NAMES_INDEX$1]] : null,
  678. };
  679. };
  680. presortedDecodedMap = (map, mapUrl) => {
  681. const clone = Object.assign({}, map);
  682. clone.mappings = [];
  683. const tracer = new TraceMap(clone, mapUrl);
  684. tracer._decoded = map.mappings;
  685. return tracer;
  686. };
  687. })();
  688. function traceSegmentInternal(segments, memo, line, column, bias) {
  689. let index = memoizedBinarySearch(segments, column, memo, line);
  690. if (found) {
  691. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  692. }
  693. else if (bias === LEAST_UPPER_BOUND)
  694. index++;
  695. if (index === -1 || index === segments.length)
  696. return null;
  697. return segments[index];
  698. }
  699. /**
  700. * Gets the index associated with `key` in the backing array, if it is already present.
  701. */
  702. let get;
  703. /**
  704. * Puts `key` into the backing array, if it is not already present. Returns
  705. * the index of the `key` in the backing array.
  706. */
  707. let put;
  708. /**
  709. * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the
  710. * index of the `key` in the backing array.
  711. *
  712. * This is designed to allow synchronizing a second array with the contents of the backing array,
  713. * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`,
  714. * and there are never duplicates.
  715. */
  716. class SetArray {
  717. constructor() {
  718. this._indexes = { __proto__: null };
  719. this.array = [];
  720. }
  721. }
  722. (() => {
  723. get = (strarr, key) => strarr._indexes[key];
  724. put = (strarr, key) => {
  725. // The key may or may not be present. If it is present, it's a number.
  726. const index = get(strarr, key);
  727. if (index !== undefined)
  728. return index;
  729. const { array, _indexes: indexes } = strarr;
  730. return (indexes[key] = array.push(key) - 1);
  731. };
  732. })();
  733. const COLUMN = 0;
  734. const SOURCES_INDEX = 1;
  735. const SOURCE_LINE = 2;
  736. const SOURCE_COLUMN = 3;
  737. const NAMES_INDEX = 4;
  738. const NO_NAME = -1;
  739. /**
  740. * Same as `addMapping`, but will only add the mapping if it generates useful information in the
  741. * resulting map. This only works correctly if mappings are added **in order**, meaning you should
  742. * not add a mapping with a lower generated line/column than one that came before.
  743. */
  744. let maybeAddMapping;
  745. /**
  746. * Adds/removes the content of the source file to the source map.
  747. */
  748. let setSourceContent;
  749. /**
  750. * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
  751. * a sourcemap, or to JSON.stringify.
  752. */
  753. let toDecodedMap;
  754. /**
  755. * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
  756. * a sourcemap, or to JSON.stringify.
  757. */
  758. let toEncodedMap;
  759. // This split declaration is only so that terser can elminiate the static initialization block.
  760. let addSegmentInternal;
  761. /**
  762. * Provides the state to generate a sourcemap.
  763. */
  764. class GenMapping {
  765. constructor({ file, sourceRoot } = {}) {
  766. this._names = new SetArray();
  767. this._sources = new SetArray();
  768. this._sourcesContent = [];
  769. this._mappings = [];
  770. this.file = file;
  771. this.sourceRoot = sourceRoot;
  772. }
  773. }
  774. (() => {
  775. maybeAddMapping = (map, mapping) => {
  776. return addMappingInternal(true, map, mapping);
  777. };
  778. setSourceContent = (map, source, content) => {
  779. const { _sources: sources, _sourcesContent: sourcesContent } = map;
  780. sourcesContent[put(sources, source)] = content;
  781. };
  782. toDecodedMap = (map) => {
  783. const { file, sourceRoot, _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  784. removeEmptyFinalLines(mappings);
  785. return {
  786. version: 3,
  787. file: file || undefined,
  788. names: names.array,
  789. sourceRoot: sourceRoot || undefined,
  790. sources: sources.array,
  791. sourcesContent,
  792. mappings,
  793. };
  794. };
  795. toEncodedMap = (map) => {
  796. const decoded = toDecodedMap(map);
  797. return Object.assign(Object.assign({}, decoded), { mappings: encode(decoded.mappings) });
  798. };
  799. // Internal helpers
  800. addSegmentInternal = (skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name) => {
  801. const { _mappings: mappings, _sources: sources, _sourcesContent: sourcesContent, _names: names, } = map;
  802. const line = getLine(mappings, genLine);
  803. const index = getColumnIndex(line, genColumn);
  804. if (!source) {
  805. if (skipable && skipSourceless(line, index))
  806. return;
  807. return insert(line, index, [genColumn]);
  808. }
  809. const sourcesIndex = put(sources, source);
  810. const namesIndex = name ? put(names, name) : NO_NAME;
  811. if (sourcesIndex === sourcesContent.length)
  812. sourcesContent[sourcesIndex] = null;
  813. if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
  814. return;
  815. }
  816. return insert(line, index, name
  817. ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
  818. : [genColumn, sourcesIndex, sourceLine, sourceColumn]);
  819. };
  820. })();
  821. function getLine(mappings, index) {
  822. for (let i = mappings.length; i <= index; i++) {
  823. mappings[i] = [];
  824. }
  825. return mappings[index];
  826. }
  827. function getColumnIndex(line, genColumn) {
  828. let index = line.length;
  829. for (let i = index - 1; i >= 0; index = i--) {
  830. const current = line[i];
  831. if (genColumn >= current[COLUMN])
  832. break;
  833. }
  834. return index;
  835. }
  836. function insert(array, index, value) {
  837. for (let i = array.length; i > index; i--) {
  838. array[i] = array[i - 1];
  839. }
  840. array[index] = value;
  841. }
  842. function removeEmptyFinalLines(mappings) {
  843. const { length } = mappings;
  844. let len = length;
  845. for (let i = len - 1; i >= 0; len = i, i--) {
  846. if (mappings[i].length > 0)
  847. break;
  848. }
  849. if (len < length)
  850. mappings.length = len;
  851. }
  852. function skipSourceless(line, index) {
  853. // The start of a line is already sourceless, so adding a sourceless segment to the beginning
  854. // doesn't generate any useful information.
  855. if (index === 0)
  856. return true;
  857. const prev = line[index - 1];
  858. // If the previous segment is also sourceless, then adding another sourceless segment doesn't
  859. // genrate any new information. Else, this segment will end the source/named segment and point to
  860. // a sourceless position, which is useful.
  861. return prev.length === 1;
  862. }
  863. function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) {
  864. // A source/named segment at the start of a line gives position at that genColumn
  865. if (index === 0)
  866. return false;
  867. const prev = line[index - 1];
  868. // If the previous segment is sourceless, then we're transitioning to a source.
  869. if (prev.length === 1)
  870. return false;
  871. // If the previous segment maps to the exact same source position, then this segment doesn't
  872. // provide any new position information.
  873. return (sourcesIndex === prev[SOURCES_INDEX] &&
  874. sourceLine === prev[SOURCE_LINE] &&
  875. sourceColumn === prev[SOURCE_COLUMN] &&
  876. namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME));
  877. }
  878. function addMappingInternal(skipable, map, mapping) {
  879. const { generated, source, original, name } = mapping;
  880. if (!source) {
  881. return addSegmentInternal(skipable, map, generated.line - 1, generated.column, null, null, null, null);
  882. }
  883. const s = source;
  884. return addSegmentInternal(skipable, map, generated.line - 1, generated.column, s, original.line - 1, original.column, name);
  885. }
  886. class SourceMapConsumer {
  887. constructor(map, mapUrl) {
  888. const trace = (this._map = new AnyMap(map, mapUrl));
  889. this.file = trace.file;
  890. this.names = trace.names;
  891. this.sourceRoot = trace.sourceRoot;
  892. this.sources = trace.resolvedSources;
  893. this.sourcesContent = trace.sourcesContent;
  894. }
  895. originalPositionFor(needle) {
  896. return originalPositionFor(this._map, needle);
  897. }
  898. destroy() {
  899. // noop.
  900. }
  901. }
  902. class SourceMapGenerator {
  903. constructor(opts) {
  904. this._map = new GenMapping(opts);
  905. }
  906. addMapping(mapping) {
  907. maybeAddMapping(this._map, mapping);
  908. }
  909. setSourceContent(source, content) {
  910. setSourceContent(this._map, source, content);
  911. }
  912. toJSON() {
  913. return toEncodedMap(this._map);
  914. }
  915. toDecodedMap() {
  916. return toDecodedMap(this._map);
  917. }
  918. }
  919. exports.SourceMapConsumer = SourceMapConsumer;
  920. exports.SourceMapGenerator = SourceMapGenerator;
  921. Object.defineProperty(exports, '__esModule', { value: true });
  922. }));
  923. //# sourceMappingURL=source-map.umd.js.map