Debian Codegraph @

jridgewell-gen-mapping/src/gen-mapping.ts

raw
1 import { SetArray, put } from '@jridgewell/set-array';
2 import { encode } from '@jridgewell/sourcemap-codec';
3 import { TraceMap, decodedMappings } from '@jridgewell/trace-mapping';
4
5 import {
6 COLUMN,
7 SOURCES_INDEX,
8 SOURCE_LINE,
9 SOURCE_COLUMN,
10 NAMES_INDEX,
11 } from './sourcemap-segment';
12
13 import type { SourceMapInput } from '@jridgewell/trace-mapping';
14 import type { SourceMapSegment } from './sourcemap-segment';
15 import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types';
16
17 export type { DecodedSourceMap, EncodedSourceMap, Mapping };
18
19 export type Options = {
20 file?: string | null;
21 sourceRoot?: string | null;
22 };
23
24 const NO_NAME = -1;
25
26 /**
27 * A low-level API to associate a generated position with an original source position. Line and
28 * column here are 0-based, unlike `addMapping`.
29 */
30 export let addSegment: {
31 (
32 map: GenMapping,
33 genLine: number,
34 genColumn: number,
35 source?: null,
36 sourceLine?: null,
37 sourceColumn?: null,
38 name?: null,
39 content?: null,
40 ): void;
41 (
42 map: GenMapping,
43 genLine: number,
44 genColumn: number,
45 source: string,
46 sourceLine: number,
47 sourceColumn: number,
48 name?: null,
49 content?: string | null,
50 ): void;
51 (
52 map: GenMapping,
53 genLine: number,
54 genColumn: number,
55 source: string,
56 sourceLine: number,
57 sourceColumn: number,
58 name: string,
59 content?: string | null,
60 ): void;
61 };
62
63 /**
64 * A high-level API to associate a generated position with an original source position. Line is
65 * 1-based, but column is 0-based, due to legacy behavior in `source-map` library.
66 */
67 export let addMapping: {
68 (
69 map: GenMapping,
70 mapping: {
71 generated: Pos;
72 source?: null;
73 original?: null;
74 name?: null;
75 content?: null;
76 },
77 ): void;
78 (
79 map: GenMapping,
80 mapping: {
81 generated: Pos;
82 source: string;
83 original: Pos;
84 name?: null;
85 content?: string | null;
86 },
87 ): void;
88 (
89 map: GenMapping,
90 mapping: {
91 generated: Pos;
92 source: string;
93 original: Pos;
94 name: string;
95 content?: string | null;
96 },
97 ): void;
98 };
99
100 /**
101 * Same as `addSegment`, but will only add the segment if it generates useful information in the
102 * resulting map. This only works correctly if segments are added **in order**, meaning you should
103 * not add a segment with a lower generated line/column than one that came before.
104 */
105 export let maybeAddSegment: typeof addSegment;
106
107 /**
108 * Same as `addMapping`, but will only add the mapping if it generates useful information in the
109 * resulting map. This only works correctly if mappings are added **in order**, meaning you should
110 * not add a mapping with a lower generated line/column than one that came before.
111 */
112 export let maybeAddMapping: typeof addMapping;
113
114 /**
115 * Adds/removes the content of the source file to the source map.
116 */
117 export let setSourceContent: (map: GenMapping, source: string, content: string | null) => void;
118
119 /**
120 * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects
121 * a sourcemap, or to JSON.stringify.
122 */
123 export let toDecodedMap: (map: GenMapping) => DecodedSourceMap;
124
125 /**
126 * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects
127 * a sourcemap, or to JSON.stringify.
128 */
129 export let toEncodedMap: (map: GenMapping) => EncodedSourceMap;
130
131 /**
132 * Constructs a new GenMapping, using the already present mappings of the input.
133 */
134 export let fromMap: (input: SourceMapInput) => GenMapping;
135
136 /**
137 * Returns an array of high-level mapping objects for every recorded segment, which could then be
138 * passed to the `source-map` library.
139 */
140 export let allMappings: (map: GenMapping) => Mapping[];
141
142 // This split declaration is only so that terser can elminiate the static initialization block.
143 let addSegmentInternal: <S extends string | null | undefined>(
144 skipable: boolean,
145 map: GenMapping,
146 genLine: number,
147 genColumn: number,
148 source: S,
149 sourceLine: S extends string ? number : null | undefined,
150 sourceColumn: S extends string ? number : null | undefined,
151 name: S extends string ? string | null | undefined : null | undefined,
152 content: S extends string ? string | null | undefined : null | undefined,
153 ) => void;
154
155 /**
156 * Provides the state to generate a sourcemap.
157 */
158 export class GenMapping {
159 private _names = new SetArray();
160 private _sources = new SetArray();
161 private _sourcesContent: (string | null)[] = [];
162 private _mappings: SourceMapSegment[][] = [];
163 declare file: string | null | undefined;
164 declare sourceRoot: string | null | undefined;
165
166 constructor({ file, sourceRoot }: Options = {}) {
167 this.file = file;
168 this.sourceRoot = sourceRoot;
169 }
170
171 static {
172 addSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => {
173 return addSegmentInternal(
174 false,
175 map,
176 genLine,
177 genColumn,
178 source,
179 sourceLine,
180 sourceColumn,
181 name,
182 content,
183 );
184 };
185
186 maybeAddSegment = (
187 map,
188 genLine,
189 genColumn,
190 source,
191 sourceLine,
192 sourceColumn,
193 name,
194 content,
195 ) => {
196 return addSegmentInternal(
197 true,
198 map,
199 genLine,
200 genColumn,
201 source,
202 sourceLine,
203 sourceColumn,
204 name,
205 content,
206 );
207 };
208
209 addMapping = (map, mapping) => {
210 return addMappingInternal(false, map, mapping as Parameters<typeof addMappingInternal>[2]);
211 };
212
213 maybeAddMapping = (map, mapping) => {
214 return addMappingInternal(true, map, mapping as Parameters<typeof addMappingInternal>[2]);
215 };
216
217 setSourceContent = (map, source, content) => {
218 const { _sources: sources, _sourcesContent: sourcesContent } = map;
219 sourcesContent[put(sources, source)] = content;
220 };
221
222 toDecodedMap = (map) => {
223 const {
224 file,
225 sourceRoot,
226 _mappings: mappings,
227 _sources: sources,
228 _sourcesContent: sourcesContent,
229 _names: names,
230 } = map;
231 removeEmptyFinalLines(mappings);
232
233 return {
234 version: 3,
235 file: file || undefined,
236 names: names.array,
237 sourceRoot: sourceRoot || undefined,
238 sources: sources.array,
239 sourcesContent,
240 mappings,
241 };
242 };
243
244 toEncodedMap = (map) => {
245 const decoded = toDecodedMap(map);
246 return {
247 ...decoded,
248 mappings: encode(decoded.mappings as SourceMapSegment[][]),
249 };
250 };
251
252 allMappings = (map) => {
253 const out: Mapping[] = [];
254 const { _mappings: mappings, _sources: sources, _names: names } = map;
255
256 for (let i = 0; i < mappings.length; i++) {
257 const line = mappings[i];
258 for (let j = 0; j < line.length; j++) {
259 const seg = line[j];
260
261 const generated = { line: i + 1, column: seg[COLUMN] };
262 let source: string | undefined = undefined;
263 let original: Pos | undefined = undefined;
264 let name: string | undefined = undefined;
265
266 if (seg.length !== 1) {
267 source = sources.array[seg[SOURCES_INDEX]];
268 original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] };
269
270 if (seg.length === 5) name = names.array[seg[NAMES_INDEX]];
271 }
272
273 out.push({ generated, source, original, name } as Mapping);
274 }
275 }
276
277 return out;
278 };
279
280 fromMap = (input) => {
281 const map = new TraceMap(input);
282 const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot });
283
284 putAll(gen._names, map.names);
285 putAll(gen._sources, map.sources as string[]);
286 gen._sourcesContent = map.sourcesContent || map.sources.map(() => null);
287 gen._mappings = decodedMappings(map) as GenMapping['_mappings'];
288
289 return gen;
290 };
291
292 // Internal helpers
293 addSegmentInternal = (
294 skipable,
295 map,
296 genLine,
297 genColumn,
298 source,
299 sourceLine,
300 sourceColumn,
301 name,
302 content,
303 ) => {
304 const {
305 _mappings: mappings,
306 _sources: sources,
307 _sourcesContent: sourcesContent,
308 _names: names,
309 } = map;
310 const line = getLine(mappings, genLine);
311 const index = getColumnIndex(line, genColumn);
312
313 if (!source) {
314 if (skipable && skipSourceless(line, index)) return;
315 return insert(line, index, [genColumn]);
316 }
317
318 // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source
319 // isn't nullish.
320 assert<number>(sourceLine);
321 assert<number>(sourceColumn);
322
323 const sourcesIndex = put(sources, source);
324 const namesIndex = name ? put(names, name) : NO_NAME;
325 if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null;
326
327 if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) {
328 return;
329 }
330
331 return insert(
332 line,
333 index,
334 name
335 ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
336 : [genColumn, sourcesIndex, sourceLine, sourceColumn],
337 );
338 };
339 }
340 }
341
342 function assert<T>(_val: unknown): asserts _val is T {
343 // noop.
344 }
345
346 function getLine(mappings: SourceMapSegment[][], index: number): SourceMapSegment[] {
347 for (let i = mappings.length; i <= index; i++) {
348 mappings[i] = [];
349 }
350 return mappings[index];
351 }
352
353 function getColumnIndex(line: SourceMapSegment[], genColumn: number): number {
354 let index = line.length;
355 for (let i = index - 1; i >= 0; index = i--) {
356 const current = line[i];
357 if (genColumn >= current[COLUMN]) break;
358 }
359 return index;
360 }
361
362 function insert<T>(array: T[], index: number, value: T) {
363 for (let i = array.length; i > index; i--) {
364 array[i] = array[i - 1];
365 }
366 array[index] = value;
367 }
368
369 function removeEmptyFinalLines(mappings: SourceMapSegment[][]) {
370 const { length } = mappings;
371 let len = length;
372 for (let i = len - 1; i >= 0; len = i, i--) {
373 if (mappings[i].length > 0) break;
374 }
375 if (len < length) mappings.length = len;
376 }
377
378 function putAll(strarr: SetArray, array: string[]) {
379 for (let i = 0; i < array.length; i++) put(strarr, array[i]);
380 }
381
382 function skipSourceless(line: SourceMapSegment[], index: number): boolean {
383 // The start of a line is already sourceless, so adding a sourceless segment to the beginning
384 // doesn't generate any useful information.
385 if (index === 0) return true;
386
387 const prev = line[index - 1];
388 // If the previous segment is also sourceless, then adding another sourceless segment doesn't
389 // genrate any new information. Else, this segment will end the source/named segment and point to
390 // a sourceless position, which is useful.
391 return prev.length === 1;
392 }
393
394 function skipSource(
395 line: SourceMapSegment[],
396 index: number,
397 sourcesIndex: number,
398 sourceLine: number,
399 sourceColumn: number,
400 namesIndex: number,
401 ): boolean {
402 // A source/named segment at the start of a line gives position at that genColumn
403 if (index === 0) return false;
404
405 const prev = line[index - 1];
406
407 // If the previous segment is sourceless, then we're transitioning to a source.
408 if (prev.length === 1) return false;
409
410 // If the previous segment maps to the exact same source position, then this segment doesn't
411 // provide any new position information.
412 return (
413 sourcesIndex === prev[SOURCES_INDEX] &&
414 sourceLine === prev[SOURCE_LINE] &&
415 sourceColumn === prev[SOURCE_COLUMN] &&
416 namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME)
417 );
418 }
419
420 function addMappingInternal<S extends string | null | undefined>(
421 skipable: boolean,
422 map: GenMapping,
423 mapping: {
424 generated: Pos;
425 source: S;
426 original: S extends string ? Pos : null | undefined;
427 name: S extends string ? string | null | undefined : null | undefined;
428 content: S extends string ? string | null | undefined : null | undefined;
429 },
430 ) {
431 const { generated, source, original, name, content } = mapping;
432 if (!source) {
433 return addSegmentInternal(
434 skipable,
435 map,
436 generated.line - 1,
437 generated.column,
438 null,
439 null,
440 null,
441 null,
442 null,
443 );
444 }
445 const s: string = source;
446 assert<Pos>(original);
447 return addSegmentInternal(
448 skipable,
449 map,
450 generated.line - 1,
451 generated.column,
452 s,
453 original.line - 1,
454 original.column,
455 name,
456 content,
457 );
458 }