source: frontend/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 2 weeks ago

Fix frontend appearance

  • Property mode set to 100644
File size: 15.1 KB
Line 
1import { encode, decode } from '@jridgewell/sourcemap-codec';
2
3import resolver from './resolve';
4import maybeSort from './sort';
5import buildBySources from './by-source';
6import {
7 memoizedState,
8 memoizedBinarySearch,
9 upperBound,
10 lowerBound,
11 found as bsFound,
12} from './binary-search';
13import {
14 COLUMN,
15 SOURCES_INDEX,
16 SOURCE_LINE,
17 SOURCE_COLUMN,
18 NAMES_INDEX,
19 REV_GENERATED_LINE,
20 REV_GENERATED_COLUMN,
21} from './sourcemap-segment';
22import { parse } from './types';
23
24import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment';
25import type {
26 SourceMapV3,
27 DecodedSourceMap,
28 EncodedSourceMap,
29 InvalidOriginalMapping,
30 OriginalMapping,
31 InvalidGeneratedMapping,
32 GeneratedMapping,
33 SourceMapInput,
34 Needle,
35 SourceNeedle,
36 SourceMap,
37 EachMapping,
38 Bias,
39 XInput,
40 SectionedSourceMap,
41 Ro,
42} from './types';
43import type { Source } from './by-source';
44import type { MemoState } from './binary-search';
45
46export type { SourceMapSegment } from './sourcemap-segment';
47export type {
48 SourceMap,
49 DecodedSourceMap,
50 EncodedSourceMap,
51 Section,
52 SectionedSourceMap,
53 SourceMapV3,
54 Bias,
55 EachMapping,
56 GeneratedMapping,
57 InvalidGeneratedMapping,
58 InvalidOriginalMapping,
59 Needle,
60 OriginalMapping,
61 OriginalMapping as Mapping,
62 SectionedSourceMapInput,
63 SourceMapInput,
64 SourceNeedle,
65 XInput,
66 EncodedSourceMapXInput,
67 DecodedSourceMapXInput,
68 SectionedSourceMapXInput,
69 SectionXInput,
70} from './types';
71
72interface PublicMap {
73 _encoded: TraceMap['_encoded'];
74 _decoded: TraceMap['_decoded'];
75 _decodedMemo: TraceMap['_decodedMemo'];
76 _bySources: TraceMap['_bySources'];
77 _bySourceMemos: TraceMap['_bySourceMemos'];
78}
79
80const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
81const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
82
83export const LEAST_UPPER_BOUND = -1;
84export const GREATEST_LOWER_BOUND = 1;
85
86export { FlattenMap, FlattenMap as AnyMap } from './flatten-map';
87
88export class TraceMap implements SourceMap {
89 declare version: SourceMapV3['version'];
90 declare file: SourceMapV3['file'];
91 declare names: SourceMapV3['names'];
92 declare sourceRoot: SourceMapV3['sourceRoot'];
93 declare sources: SourceMapV3['sources'];
94 declare sourcesContent: SourceMapV3['sourcesContent'];
95 declare ignoreList: SourceMapV3['ignoreList'];
96
97 declare resolvedSources: string[];
98 declare private _encoded: string | undefined;
99
100 declare private _decoded: SourceMapSegment[][] | undefined;
101 declare private _decodedMemo: MemoState;
102
103 declare private _bySources: Source[] | undefined;
104 declare private _bySourceMemos: MemoState[] | undefined;
105
106 constructor(map: Ro<SourceMapInput>, mapUrl?: string | null) {
107 const isString = typeof map === 'string';
108 if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap;
109
110 const parsed = parse(map as Exclude<SourceMapInput, TraceMap>);
111
112 const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
113 this.version = version;
114 this.file = file;
115 this.names = names || [];
116 this.sourceRoot = sourceRoot;
117 this.sources = sources;
118 this.sourcesContent = sourcesContent;
119 this.ignoreList = parsed.ignoreList || (parsed as XInput).x_google_ignoreList || undefined;
120
121 const resolve = resolver(mapUrl, sourceRoot);
122 this.resolvedSources = sources.map(resolve);
123
124 const { mappings } = parsed;
125 if (typeof mappings === 'string') {
126 this._encoded = mappings;
127 this._decoded = undefined;
128 } else if (Array.isArray(mappings)) {
129 this._encoded = undefined;
130 this._decoded = maybeSort(mappings, isString);
131 } else if ((parsed as unknown as SectionedSourceMap).sections) {
132 throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
133 } else {
134 throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
135 }
136
137 this._decodedMemo = memoizedState();
138 this._bySources = undefined;
139 this._bySourceMemos = undefined;
140 }
141}
142
143/**
144 * Typescript doesn't allow friend access to private fields, so this just casts the map into a type
145 * with public access modifiers.
146 */
147function cast(map: unknown): PublicMap {
148 return map as any;
149}
150
151/**
152 * Returns the encoded (VLQ string) form of the SourceMap's mappings field.
153 */
154export function encodedMappings(map: TraceMap): EncodedSourceMap['mappings'] {
155 return (cast(map)._encoded ??= encode(cast(map)._decoded!));
156}
157
158/**
159 * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
160 */
161export function decodedMappings(map: TraceMap): Readonly<DecodedSourceMap['mappings']> {
162 return (cast(map)._decoded ||= decode(cast(map)._encoded!));
163}
164
165/**
166 * A low-level API to find the segment associated with a generated line/column (think, from a
167 * stack trace). Line and column here are 0-based, unlike `originalPositionFor`.
168 */
169export function traceSegment(
170 map: TraceMap,
171 line: number,
172 column: number,
173): Readonly<SourceMapSegment> | null {
174 const decoded = decodedMappings(map);
175
176 // It's common for parent source maps to have pointers to lines that have no
177 // mapping (like a "//# sourceMappingURL=") at the end of the child file.
178 if (line >= decoded.length) return null;
179
180 const segments = decoded[line];
181 const index = traceSegmentInternal(
182 segments,
183 cast(map)._decodedMemo,
184 line,
185 column,
186 GREATEST_LOWER_BOUND,
187 );
188
189 return index === -1 ? null : segments[index];
190}
191
192/**
193 * A higher-level API to find the source/line/column associated with a generated line/column
194 * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
195 * `source-map` library.
196 */
197export function originalPositionFor(
198 map: TraceMap,
199 needle: Needle,
200): OriginalMapping | InvalidOriginalMapping {
201 let { line, column, bias } = needle;
202 line--;
203 if (line < 0) throw new Error(LINE_GTR_ZERO);
204 if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
205
206 const decoded = decodedMappings(map);
207
208 // It's common for parent source maps to have pointers to lines that have no
209 // mapping (like a "//# sourceMappingURL=") at the end of the child file.
210 if (line >= decoded.length) return OMapping(null, null, null, null);
211
212 const segments = decoded[line];
213 const index = traceSegmentInternal(
214 segments,
215 cast(map)._decodedMemo,
216 line,
217 column,
218 bias || GREATEST_LOWER_BOUND,
219 );
220
221 if (index === -1) return OMapping(null, null, null, null);
222
223 const segment = segments[index];
224 if (segment.length === 1) return OMapping(null, null, null, null);
225
226 const { names, resolvedSources } = map;
227 return OMapping(
228 resolvedSources[segment[SOURCES_INDEX]],
229 segment[SOURCE_LINE] + 1,
230 segment[SOURCE_COLUMN],
231 segment.length === 5 ? names[segment[NAMES_INDEX]] : null,
232 );
233}
234
235/**
236 * Finds the generated line/column position of the provided source/line/column source position.
237 */
238export function generatedPositionFor(
239 map: TraceMap,
240 needle: SourceNeedle,
241): GeneratedMapping | InvalidGeneratedMapping {
242 const { source, line, column, bias } = needle;
243 return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false);
244}
245
246/**
247 * Finds all generated line/column positions of the provided source/line/column source position.
248 */
249export function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[] {
250 const { source, line, column, bias } = needle;
251 // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit.
252 return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true);
253}
254
255/**
256 * Iterates each mapping in generated position order.
257 */
258export function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void {
259 const decoded = decodedMappings(map);
260 const { names, resolvedSources } = map;
261
262 for (let i = 0; i < decoded.length; i++) {
263 const line = decoded[i];
264 for (let j = 0; j < line.length; j++) {
265 const seg = line[j];
266
267 const generatedLine = i + 1;
268 const generatedColumn = seg[0];
269 let source = null;
270 let originalLine = null;
271 let originalColumn = null;
272 let name = null;
273 if (seg.length !== 1) {
274 source = resolvedSources[seg[1]];
275 originalLine = seg[2] + 1;
276 originalColumn = seg[3];
277 }
278 if (seg.length === 5) name = names[seg[4]];
279
280 cb({
281 generatedLine,
282 generatedColumn,
283 source,
284 originalLine,
285 originalColumn,
286 name,
287 } as EachMapping);
288 }
289 }
290}
291
292function sourceIndex(map: TraceMap, source: string): number {
293 const { sources, resolvedSources } = map;
294 let index = sources.indexOf(source);
295 if (index === -1) index = resolvedSources.indexOf(source);
296 return index;
297}
298
299/**
300 * Retrieves the source content for a particular source, if its found. Returns null if not.
301 */
302export function sourceContentFor(map: TraceMap, source: string): string | null {
303 const { sourcesContent } = map;
304 if (sourcesContent == null) return null;
305 const index = sourceIndex(map, source);
306 return index === -1 ? null : sourcesContent[index];
307}
308
309/**
310 * Determines if the source is marked to ignore by the source map.
311 */
312export function isIgnored(map: TraceMap, source: string): boolean {
313 const { ignoreList } = map;
314 if (ignoreList == null) return false;
315 const index = sourceIndex(map, source);
316 return index === -1 ? false : ignoreList.includes(index);
317}
318
319/**
320 * A helper that skips sorting of the input map's mappings array, which can be expensive for larger
321 * maps.
322 */
323export function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap {
324 const tracer = new TraceMap(clone(map, []), mapUrl);
325 cast(tracer)._decoded = map.mappings;
326 return tracer;
327}
328
329/**
330 * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
331 * a sourcemap, or to JSON.stringify.
332 */
333export function decodedMap(
334 map: TraceMap,
335): Omit<DecodedSourceMap, 'mappings'> & { mappings: readonly SourceMapSegment[][] } {
336 return clone(map, decodedMappings(map));
337}
338
339/**
340 * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
341 * a sourcemap, or to JSON.stringify.
342 */
343export function encodedMap(map: TraceMap): EncodedSourceMap {
344 return clone(map, encodedMappings(map));
345}
346
347function clone<T extends string | readonly SourceMapSegment[][]>(
348 map: TraceMap | DecodedSourceMap,
349 mappings: T,
350): T extends string ? EncodedSourceMap : DecodedSourceMap {
351 return {
352 version: map.version,
353 file: map.file,
354 names: map.names,
355 sourceRoot: map.sourceRoot,
356 sources: map.sources,
357 sourcesContent: map.sourcesContent,
358 mappings,
359 ignoreList: map.ignoreList || (map as XInput).x_google_ignoreList,
360 } as any;
361}
362
363function OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping;
364function OMapping(
365 source: string,
366 line: number,
367 column: number,
368 name: string | null,
369): OriginalMapping;
370function OMapping(
371 source: string | null,
372 line: number | null,
373 column: number | null,
374 name: string | null,
375): OriginalMapping | InvalidOriginalMapping {
376 return { source, line, column, name } as any;
377}
378
379function GMapping(line: null, column: null): InvalidGeneratedMapping;
380function GMapping(line: number, column: number): GeneratedMapping;
381function GMapping(
382 line: number | null,
383 column: number | null,
384): GeneratedMapping | InvalidGeneratedMapping {
385 return { line, column } as any;
386}
387
388function traceSegmentInternal(
389 segments: SourceMapSegment[],
390 memo: MemoState,
391 line: number,
392 column: number,
393 bias: Bias,
394): number;
395function traceSegmentInternal(
396 segments: ReverseSegment[],
397 memo: MemoState,
398 line: number,
399 column: number,
400 bias: Bias,
401): number;
402function traceSegmentInternal(
403 segments: SourceMapSegment[] | ReverseSegment[],
404 memo: MemoState,
405 line: number,
406 column: number,
407 bias: Bias,
408): number {
409 let index = memoizedBinarySearch(segments, column, memo, line);
410 if (bsFound) {
411 index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
412 } else if (bias === LEAST_UPPER_BOUND) index++;
413
414 if (index === -1 || index === segments.length) return -1;
415 return index;
416}
417
418function sliceGeneratedPositions(
419 segments: ReverseSegment[],
420 memo: MemoState,
421 line: number,
422 column: number,
423 bias: Bias,
424): GeneratedMapping[] {
425 let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND);
426
427 // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in
428 // insertion order) segment that matched. Even if we did respect the bias when tracing, we would
429 // still need to call `lowerBound()` to find the first segment, which is slower than just looking
430 // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the
431 // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to
432 // match LEAST_UPPER_BOUND.
433 if (!bsFound && bias === LEAST_UPPER_BOUND) min++;
434
435 if (min === -1 || min === segments.length) return [];
436
437 // We may have found the segment that started at an earlier column. If this is the case, then we
438 // need to slice all generated segments that match _that_ column, because all such segments span
439 // to our desired column.
440 const matchedColumn = bsFound ? column : segments[min][COLUMN];
441
442 // The binary search is not guaranteed to find the lower bound when a match wasn't found.
443 if (!bsFound) min = lowerBound(segments, matchedColumn, min);
444 const max = upperBound(segments, matchedColumn, min);
445
446 const result = [];
447 for (; min <= max; min++) {
448 const segment = segments[min];
449 result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]));
450 }
451 return result;
452}
453
454function generatedPosition(
455 map: TraceMap,
456 source: string,
457 line: number,
458 column: number,
459 bias: Bias,
460 all: false,
461): GeneratedMapping | InvalidGeneratedMapping;
462function generatedPosition(
463 map: TraceMap,
464 source: string,
465 line: number,
466 column: number,
467 bias: Bias,
468 all: true,
469): GeneratedMapping[];
470function generatedPosition(
471 map: TraceMap,
472 source: string,
473 line: number,
474 column: number,
475 bias: Bias,
476 all: boolean,
477): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] {
478 line--;
479 if (line < 0) throw new Error(LINE_GTR_ZERO);
480 if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
481
482 const { sources, resolvedSources } = map;
483 let sourceIndex = sources.indexOf(source);
484 if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source);
485 if (sourceIndex === -1) return all ? [] : GMapping(null, null);
486
487 const bySourceMemos = (cast(map)._bySourceMemos ||= sources.map(memoizedState));
488 const generated = (cast(map)._bySources ||= buildBySources(decodedMappings(map), bySourceMemos));
489
490 const segments = generated[sourceIndex][line];
491 if (segments == null) return all ? [] : GMapping(null, null);
492
493 const memo = bySourceMemos[sourceIndex];
494
495 if (all) return sliceGeneratedPositions(segments, memo, line, column, bias);
496
497 const index = traceSegmentInternal(segments, memo, line, column, bias);
498 if (index === -1) return GMapping(null, null);
499
500 const segment = segments[index];
501 return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]);
502}
Note: See TracBrowser for help on using the repository browser.