source-map.mjs 32 KB

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