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