-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy pathsources.ts
1267 lines (1082 loc) · 40.7 KB
/
sources.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import { inject, injectable } from 'inversify';
import { xxHash32 } from 'js-xxhash';
import { relative } from 'path';
import { NullableMappedPosition, SourceMapConsumer } from 'source-map';
import { URL } from 'url';
import * as nls from 'vscode-nls';
import Cdp from '../cdp/api';
import { MapUsingProjection } from '../common/datastructure/mapUsingProjection';
import { EventEmitter } from '../common/events';
import { ILogger, LogTag } from '../common/logging';
import { once } from '../common/objUtils';
import { forceForwardSlashes, isSubdirectoryOf, properResolve } from '../common/pathUtils';
import { delay, getDeferred } from '../common/promiseUtil';
import { ISourceMapMetadata, SourceMap } from '../common/sourceMaps/sourceMap';
import { CachingSourceMapFactory, ISourceMapFactory } from '../common/sourceMaps/sourceMapFactory';
import { InlineScriptOffset, ISourcePathResolver } from '../common/sourcePathResolver';
import * as sourceUtils from '../common/sourceUtils';
import { prettyPrintAsSourceMap } from '../common/sourceUtils';
import * as utils from '../common/urlUtils';
import { AnyLaunchConfiguration } from '../configuration';
import Dap from '../dap/api';
import { IDapApi } from '../dap/connection';
import { sourceMapParseFailed } from '../dap/errors';
import { IInitializeParams } from '../ioc-extras';
import { IStatistics } from '../telemetry/classification';
import { extractErrorDetails } from '../telemetry/dapTelemetryReporter';
import { IResourceProvider } from './resourceProvider';
import { ScriptSkipper } from './scriptSkipper/implementation';
import { IScriptSkipper } from './scriptSkipper/scriptSkipper';
import { Script } from './threads';
const localize = nls.loadMessageBundle();
// This is a ui location which corresponds to a position in the document user can see (Source, Dap.Source).
export interface IUiLocation {
lineNumber: number; // 1-based
columnNumber: number; // 1-based
source: Source;
}
function isUiLocation(loc: unknown): loc is IUiLocation {
return (
typeof (loc as IUiLocation).lineNumber === 'number' &&
typeof (loc as IUiLocation).columnNumber === 'number' &&
!!(loc as IUiLocation).source
);
}
const getFallbackPosition = () => ({
source: null,
line: null,
column: null,
name: null,
lastColumn: null,
isSourceMapLoadFailure: true,
});
type ContentGetter = () => Promise<string | undefined>;
// Each source map has a number of compiled sources referncing it.
type SourceMapData = { compiled: Set<ISourceWithMap>; map?: SourceMap; loaded: Promise<void> };
export const enum SourceConstants {
/**
* Extension of evaluated sources internal to the debugger. Sources with
* this suffix will be ignored when displaying sources or stacktracees.
*/
InternalExtension = '.cdp',
/**
* Extension of evaluated REPL source. Stack traces which include frames
* from this suffix will be truncated to keep only frames from code called
* by the REPL.
*/
ReplExtension = '.repl',
}
export type SourceMapTimeouts = {
// This is a source map loading delay used for testing.
load: number;
// When resolving a location (e.g. to show it in the debug console), we wait no longer than
// |resolveLocation| timeout for source map to be loaded, and fallback to original location
// in the compiled source.
resolveLocation: number;
// When pausing before script with source map, we wait no longer than |sourceMapMinPause| timeout
// for source map to be loaded and breakpoints to be set. This usually ensures that breakpoints
// won't be missed.
sourceMapMinPause: number;
// Normally we only give each source-map sourceMapMinPause time to load per sourcemap. sourceMapCumulativePause
// adds some additional time we spend parsing source-maps, but it's spent accross all source-maps in that // // // session
sourceMapCumulativePause: number;
// When sending multiple entities to debug console, we wait for each one to be asynchronously
// processed. If one of them stalls, we resume processing others after |output| timeout.
output: number;
};
/** Gets whether the URL is a compiled source containing a webpack HMR */
const isWebpackHMR = (url: string) => url.endsWith('.hot-update.js');
const defaultTimeouts: SourceMapTimeouts = {
load: 0,
resolveLocation: 2000,
sourceMapMinPause: 1000,
output: 1000,
sourceMapCumulativePause: 10000,
};
// Represents a text source visible to the user.
//
// Source maps flow (start with compiled1 and compiled2). Two different compiled sources
// reference to the same source map, and produce two different resolved urls leading
// to different source map sources. This is a corner case, usually there is a single
// resolved url and a single source map source per each sourceUrl in the source map.
//
// ------> sourceMapUrl -> SourceContainer._sourceMaps -> SourceMapData -> map
// | | |
// | compiled1 - - - - - - - source1 <-- resolvedUrl1 <-- sourceUrl <----
// | |
// compiled2 - - - - - - - - - - source2 <-- resolvedUrl2 <-- sourceUrl <----
//
// compiled1 and source1 are connected (same goes for compiled2 and source2):
// compiled1._sourceMapSourceByUrl.get(sourceUrl) === source1
// source1._compiledToSourceUrl.get(compiled1) === sourceUrl
//
export class Source {
public readonly sourceReference: number;
private readonly _name: string;
private readonly _fqname: string;
/**
* Function to retrieve the content of the source.
*/
private readonly _contentGetter: ContentGetter;
private readonly _container: SourceContainer;
/**
* Hypothesized absolute path for the source. May or may not actually exist.
*/
public readonly absolutePath: string;
public sourceMap?: ISourceWithMap['sourceMap'];
// This is the same as |_absolutePath|, but additionally checks that file exists to
// avoid errors when page refers to non-existing paths/urls.
private readonly _existingAbsolutePath: Promise<string | undefined>;
private readonly _scriptIds: Cdp.Runtime.ScriptId[] = [];
/**
* @param inlineScriptOffset Offset of the start location of the script in
* its source file. This is used on scripts in HTML pages, where the script
* is nested in the content.
* @param contentHash Optional hash of the file contents. This is used to
* check whether the script we get is the same one as what's on disk. This
* can be used to detect in-place transpilation.
* @param runtimeScriptOffset Offset of the start location of the script
* in the runtime *only*. This differs from the inlineScriptOffset, as the
* inline offset of also reflected in the file. This is used to deal with
* the runtime wrapping the source and offsetting locations which should
* not be shown to the user.
*/
constructor(
container: SourceContainer,
public readonly url: string,
absolutePath: string | undefined,
contentGetter: ContentGetter,
sourceMapUrl?: string,
public readonly inlineScriptOffset?: InlineScriptOffset,
public readonly runtimeScriptOffset?: InlineScriptOffset,
contentHash?: string,
) {
this.sourceReference = container.getSourceReference(url);
this._contentGetter = once(contentGetter);
this._container = container;
this.absolutePath = absolutePath || '';
this._fqname = this._fullyQualifiedName();
this._name = this._humanName();
this.setSourceMapUrl(sourceMapUrl);
this._existingAbsolutePath = sourceUtils.checkContentHash(
this.absolutePath,
// Inline scripts will never match content of the html file. We skip the content check.
inlineScriptOffset || runtimeScriptOffset ? undefined : contentHash,
container._fileContentOverridesForTest.get(this.absolutePath),
);
}
private setSourceMapUrl(sourceMapUrl?: string) {
if (!sourceMapUrl) {
this.sourceMap = undefined;
return;
}
this.sourceMap = {
url: sourceMapUrl,
sourceByUrl: new Map(),
metadata: {
sourceMapUrl,
compiledPath: this.absolutePath || this.url,
},
};
}
addScriptId(scriptId: Cdp.Runtime.ScriptId): void {
this._scriptIds.push(scriptId);
}
scriptIds(): Cdp.Runtime.ScriptId[] {
return this._scriptIds;
}
async content(): Promise<string | undefined> {
let content = await this._contentGetter();
// pad for the inline source offset, see
// https://github.com/microsoft/vscode-js-debug/issues/736
if (this.inlineScriptOffset?.lineOffset) {
content = '\n'.repeat(this.inlineScriptOffset.lineOffset) + content;
}
return content;
}
mimeType(): string {
return 'text/javascript';
}
/**
* Pretty-prints the source. Generates a beauitified source map if possible
* and it hasn't already been done, and returns the created map and created
* ephemeral source. Returns undefined if the source can't be beautified.
*/
public async prettyPrint(): Promise<{ map: SourceMap; source: Source } | undefined> {
if (!this._container) {
return undefined;
}
if (isSourceWithMap(this) && this.sourceMap.url.endsWith('-pretty.map')) {
const map = this._container._sourceMaps.get(this.sourceMap?.url)?.map;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return map && { map, source: [...this.sourceMap.sourceByUrl!.values()][0] };
}
const content = await this.content();
if (!content) {
return undefined;
}
// Eval'd scripts have empty urls, give them a temporary one for the purpose
// of the sourcemap. See #929
const baseUrl = this.url || `eval://${this.sourceReference}.js`;
const sourceMapUrl = baseUrl + '-pretty.map';
const basename = baseUrl.split(/[\/\\]/).pop() as string;
const fileName = basename + '-pretty.js';
const map = await prettyPrintAsSourceMap(fileName, content, baseUrl, sourceMapUrl);
if (!map) {
return undefined;
}
// Note: this overwrites existing source map.
this.setSourceMapUrl(sourceMapUrl);
const asCompiled = this as ISourceWithMap;
const sourceMap: SourceMapData = {
compiled: new Set([asCompiled]),
map,
loaded: Promise.resolve(),
};
this._container._sourceMaps.set(sourceMapUrl, sourceMap);
await this._container._addSourceMapSources(asCompiled, map);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return { map, source: [...asCompiled.sourceMap.sourceByUrl.values()][0] };
}
/**
* Returns a DAP representation of the source.
*/
async toDap(): Promise<Dap.Source> {
return this.toDapShallow();
}
/**
* Returns a DAP representation without including any nested sources.
*/
public async toDapShallow(): Promise<Dap.Source> {
const existingAbsolutePath = await this._existingAbsolutePath;
const dap: Dap.Source = {
name: this._name,
path: this._fqname,
sourceReference: this.sourceReference,
presentationHint: this.blackboxed() ? 'deemphasize' : undefined,
origin: this.blackboxed() ? localize('source.skipFiles', 'Skipped by skipFiles') : undefined,
};
if (existingAbsolutePath) {
dap.sourceReference = 0;
dap.path = existingAbsolutePath;
}
return dap;
}
existingAbsolutePath(): Promise<string | undefined> {
return this._existingAbsolutePath;
}
async prettyName(): Promise<string> {
const path = await this._existingAbsolutePath;
if (path) return path;
return this._fqname;
}
/**
* Gets the human-readable name of the source.
*/
private _humanName() {
if (utils.isAbsolute(this._fqname)) {
for (const root of this._container.rootPaths) {
if (isSubdirectoryOf(root, this._fqname)) {
return forceForwardSlashes(relative(root, this._fqname));
}
}
}
return this._fqname;
}
/**
* Returns a pretty name for the script. This is the name displayed in
* stack traces and returned through DAP if the file does not verifiably
* exist on disk.
*/
private _fullyQualifiedName(): string {
if (!this.url) {
return '<eval>/VM' + this.sourceReference;
}
if (this.url.endsWith(SourceConstants.ReplExtension)) {
return 'repl';
}
if (this.absolutePath.startsWith('<node_internals>')) {
return this.absolutePath;
}
if (utils.isAbsolute(this.url)) {
return this.url;
}
const parsedAbsolute = utils.fileUrlToAbsolutePath(this.url);
if (parsedAbsolute) {
return parsedAbsolute;
}
let fqname = this.url;
try {
const tokens: string[] = [];
const url = new URL(this.url);
if (url.protocol === 'data:') {
return '<eval>/VM' + this.sourceReference;
}
if (url.hostname) {
tokens.push(url.hostname);
}
if (url.port) {
tokens.push('\uA789' + url.port); // : in unicode
}
if (url.pathname) {
tokens.push(/^\/[a-z]:/.test(url.pathname) ? url.pathname.slice(1) : url.pathname);
}
const searchParams = url.searchParams?.toString();
if (searchParams) {
tokens.push('?' + searchParams);
}
fqname = tokens.join('');
} catch (e) {
// ignored
}
if (fqname.endsWith('/')) {
fqname += '(index)';
}
if (this.inlineScriptOffset) {
fqname += `\uA789${this.inlineScriptOffset.lineOffset + 1}:${
this.inlineScriptOffset.columnOffset + 1
}`;
}
return fqname;
}
/**
* Gets whether this script is blackboxed (part of the skipfiles).
*/
public blackboxed(): boolean {
return this._container.isSourceSkipped(this.url);
}
}
/**
* A Source that has an associated sourcemap.
*/
export interface ISourceWithMap extends Source {
readonly sourceMap: {
url: string;
metadata: ISourceMapMetadata;
// When compiled source references a source map, we'll generate source map sources.
// This map |sourceUrl| as written in the source map itself to the Source.
// Only present on compiled sources, exclusive with |_origin|.
sourceByUrl: Map<string, SourceFromMap>;
};
}
/**
* A Source generated from a sourcemap. For example, a TypeScript input file
* discovered from its compiled JavaScript code.
*/
export class SourceFromMap extends Source {
// Sources generated from the source map are referenced by some compiled sources
// (through a source map). This map holds the original |sourceUrl| as written in the
// source map, which was used to produce this source for each compiled.
public readonly compiledToSourceUrl = new Map<ISourceWithMap, string>();
}
export const isSourceWithMap = (source: unknown): source is ISourceWithMap =>
!!source && source instanceof Source && !!source.sourceMap;
const isOriginalSourceOf = (compiled: Source, original: Source) =>
original instanceof SourceFromMap && original.compiledToSourceUrl.has(compiled as ISourceWithMap);
export interface IPreferredUiLocation extends IUiLocation {
isMapped: boolean;
unmappedReason?: UnmappedReason;
}
export enum UnmappedReason {
/** The map has been disabled temporarily, due to setting a breakpoint in a compiled script */
MapDisabled,
/** The source in the UI location has no map */
HasNoMap,
/** The location cannot be source mapped due to an error loading the map */
MapLoadingFailed,
/** The location cannot be source mapped due to its position not being present in the map */
MapPositionMissing,
/**
* The location cannot be sourcemapped, due to not having a sourcemap,
* failing to load the sourcemap, not having a mapping in the sourcemap, etc
*/
CannotMap,
}
const maxInt32 = 2 ** 31 - 1;
@injectable()
export class SourceContainer {
/**
* Project root path, if set.
*/
public readonly rootPaths: string[] = [];
/**
* Mapping of CDP script IDs to Script objects.
*/
private readonly scriptsById: Map<Cdp.Runtime.ScriptId, Script> = new Map();
private onSourceMappedSteppingChangeEmitter = new EventEmitter<boolean>();
private onScriptEmitter = new EventEmitter<Script>();
private _dap: Dap.Api;
private _sourceByOriginalUrl: Map<string, Source> = new MapUsingProjection(s => s.toLowerCase());
private _sourceByReference: Map<number, Source> = new Map();
private _sourceMapSourcesByUrl: Map<string, SourceFromMap> = new Map();
private _sourceByAbsolutePath: Map<string, Source> = utils.caseNormalizedMap();
// All source maps by url.
_sourceMaps: Map<string, SourceMapData> = new Map();
private _sourceMapTimeouts: SourceMapTimeouts = defaultTimeouts;
// Test support.
_fileContentOverridesForTest = new Map<string, string>();
/**
* Map of sources with maps that are disabled temporarily. This can happen
* if stepping stepping in or setting breakpoints in disabled files.
*/
private readonly _temporarilyDisabledSourceMaps = new Set<ISourceWithMap>();
/**
* Map of sources with maps that are disabled for the length of the debug
* session. This can happen if manually disabling sourcemaps for a file
* (as a result of a missing source, for instance)
*/
private readonly _permanentlyDisabledSourceMaps = new Set<ISourceWithMap>();
/**
* Fires when a new script is parsed.
*/
public readonly onScript = this.onScriptEmitter.event;
private readonly _statistics: IStatistics = { fallbackSourceMapCount: 0 };
/*
* Gets an iterator for all sources in the collection.
*/
public get sources() {
return this._sourceByReference.values();
}
/**
* Gets statistics for telemetry
*/
public statistics(): IStatistics {
return this._statistics;
}
private _doSourceMappedStepping = this.launchConfig.sourceMaps;
/**
* Gets whether source stepping is enabled.
*/
public get doSourceMappedStepping() {
return this._doSourceMappedStepping;
}
/**
* Sets whether source stepping is enabled.
*/
public set doSourceMappedStepping(enabled: boolean) {
if (enabled !== this._doSourceMappedStepping) {
this._doSourceMappedStepping = enabled;
this.onSourceMappedSteppingChangeEmitter.fire(enabled);
}
}
/**
* Fires whenever `doSourceMappedStepping` is changed.
*/
public readonly onSourceMappedSteppingChange = this.onSourceMappedSteppingChangeEmitter.event;
constructor(
@inject(IDapApi) dap: Dap.Api,
@inject(ISourceMapFactory) private readonly sourceMapFactory: ISourceMapFactory,
@inject(ILogger) private readonly logger: ILogger,
@inject(AnyLaunchConfiguration) private readonly launchConfig: AnyLaunchConfiguration,
@inject(IInitializeParams) private readonly initializeConfig: Dap.InitializeParams,
@inject(ISourcePathResolver) public readonly sourcePathResolver: ISourcePathResolver,
@inject(IScriptSkipper) public readonly scriptSkipper: ScriptSkipper,
@inject(IResourceProvider) private readonly resourceProvider: IResourceProvider,
) {
this._dap = dap;
const mainRootPath = 'webRoot' in launchConfig ? launchConfig.webRoot : launchConfig.rootPath;
if (mainRootPath) {
// Prefixing ../ClientApp is a workaround for a bug in ASP.NET debugging in VisualStudio because the wwwroot is not properly configured
this.rootPaths = [mainRootPath, properResolve(mainRootPath, '..', 'ClientApp')];
}
scriptSkipper.setSourceContainer(this);
this.setSourceMapTimeouts({
...this.sourceMapTimeouts(),
...launchConfig.timeouts,
});
}
setSourceMapTimeouts(sourceMapTimeouts: SourceMapTimeouts) {
this._sourceMapTimeouts = sourceMapTimeouts;
}
sourceMapTimeouts(): SourceMapTimeouts {
return this._sourceMapTimeouts;
}
setFileContentOverrideForTest(absolutePath: string, content?: string) {
if (content === undefined) this._fileContentOverridesForTest.delete(absolutePath);
else this._fileContentOverridesForTest.set(absolutePath, content);
}
/**
* Returns DAP objects for every loaded source in the container.
*/
public async loadedSources(): Promise<Dap.Source[]> {
const promises: Promise<Dap.Source>[] = [];
for (const source of this._sourceByReference.values()) promises.push(source.toDap());
return await Promise.all(promises);
}
/**
* Gets the Source object by DAP reference, first by sourceReference and
* then by path.
*/
public source(ref: Dap.Source): Source | undefined {
if (ref.sourceReference) return this._sourceByReference.get(ref.sourceReference);
if (ref.path) return this._sourceByAbsolutePath.get(ref.path);
return undefined;
}
/**
* Gets whether the source is skipped.
*/
public isSourceSkipped(url: string): boolean {
return this.scriptSkipper.isScriptSkipped(url);
}
/**
* Adds a new script to the source container.
*/
public addScriptById(script: Script) {
this.scriptsById.set(script.scriptId, script);
this.onScriptEmitter.fire(script);
}
/**
* Gets a script by its script ID.
*/
public getScriptById(scriptId: string) {
return this.scriptsById.get(scriptId);
}
/**
* Gets a source by its original URL from the debugger.
*/
public getSourceByOriginalUrl(url: string) {
return this._sourceByOriginalUrl.get(url);
}
/**
* Gets the source preferred source reference for a script. We generate this
* determistically so that breakpoints have a good chance of being preserved
* between reloads; previously, we had an incrementing source reference, but
* this led to breakpoints being lost when the debug session got restarted.
*
* Note that the reference returned from this function is *only* used for
* files that don't exist on disk; the ones that do exist always are
* rewritten to source reference ID 0.
*/
public getSourceReference(url: string): number {
let id = xxHash32(url) & maxInt32; // xxHash32 is a u32, mask again the max positive int32 value
for (let i = 0; i < 0xffff; i++) {
if (!this._sourceByReference.has(id)) {
return id;
}
if (id === maxInt32) {
// DAP spec says max reference ID is 2^31 - 1, int32
id = 0;
}
id++;
}
this.logger.assert(false, 'Max iterations exceeding for source reference assignment');
return id; // conflicts, but it's better than nothing, maybe?
}
/**
* This method returns a "preferred" location. This usually means going
* through a source map and showing the source map source instead of a
* compiled one. We use timeout to avoid waiting for the source map for too long.
*/
public async preferredUiLocation(uiLocation: IUiLocation): Promise<IPreferredUiLocation> {
let isMapped = false;
let unmappedReason: UnmappedReason | undefined = UnmappedReason.CannotMap;
if (this._doSourceMappedStepping) {
while (true) {
if (!isSourceWithMap(uiLocation.source)) {
break;
}
const sourceMap = this._sourceMaps.get(uiLocation.source.sourceMap.url);
if (
!this.logger.assert(
sourceMap,
`Expected to have sourcemap for loaded source ${uiLocation.source.sourceMap.url}`,
)
) {
break;
}
await Promise.race([sourceMap.loaded, delay(this._sourceMapTimeouts.resolveLocation)]);
if (!sourceMap.map) return { ...uiLocation, isMapped, unmappedReason };
const sourceMapped = this._sourceMappedUiLocation(uiLocation, sourceMap.map);
if (!isUiLocation(sourceMapped)) {
unmappedReason = isMapped ? undefined : sourceMapped;
break;
}
uiLocation = sourceMapped;
isMapped = true;
unmappedReason = undefined;
}
}
return { ...uiLocation, isMapped, unmappedReason };
}
/**
* This method shows all possible locations for a given one. For example, all
* compiled sources which refer to the same source map will be returned given
* the location in source map source. This method does not wait for the
* source map to be loaded.
*/
currentSiblingUiLocations(uiLocation: IUiLocation, inSource?: Source): IUiLocation[] {
return this._uiLocations(uiLocation).filter(
uiLocation => !inSource || uiLocation.source === inSource,
);
}
/**
* Clears all sources in the container.
*/
clear(silent: boolean) {
this.scriptsById.clear();
for (const source of this._sourceByReference.values()) {
this.removeSource(source, silent);
}
this._sourceByReference.clear();
if (this.sourceMapFactory instanceof CachingSourceMapFactory) {
this.sourceMapFactory.invalidateCache();
}
}
/**
* Returns all the possible locations the given location can map to or from,
* taking into account source maps.
*/
private _uiLocations(uiLocation: IUiLocation): IUiLocation[] {
return [
...this.getSourceMapUiLocations(uiLocation),
uiLocation,
...this.getCompiledLocations(uiLocation),
];
}
/**
* Returns all UI locations the given location maps to.
*/
private getSourceMapUiLocations(uiLocation: IUiLocation): IUiLocation[] {
if (!isSourceWithMap(uiLocation.source) || !this._doSourceMappedStepping) return [];
const map = this._sourceMaps.get(uiLocation.source.sourceMap.url)?.map;
if (!map) return [];
const sourceMapUiLocation = this._sourceMappedUiLocation(uiLocation, map);
if (!isUiLocation(sourceMapUiLocation)) return [];
const r = this.getSourceMapUiLocations(sourceMapUiLocation);
r.push(sourceMapUiLocation);
return r;
}
private _sourceMappedUiLocation(
uiLocation: IUiLocation,
map: SourceMap,
): IUiLocation | UnmappedReason {
const compiled = uiLocation.source;
if (!isSourceWithMap(compiled)) {
return UnmappedReason.HasNoMap;
}
if (
this._temporarilyDisabledSourceMaps.has(compiled) ||
this._permanentlyDisabledSourceMaps.has(compiled)
) {
return UnmappedReason.MapDisabled;
}
const entry = this.getOptiminalOriginalPosition(
map,
rawToUiOffset(uiLocation, compiled.inlineScriptOffset),
);
if ('isSourceMapLoadFailure' in entry) {
return UnmappedReason.MapLoadingFailed;
}
if (!entry.source) {
return UnmappedReason.MapPositionMissing;
}
const source = compiled.sourceMap.sourceByUrl.get(entry.source);
if (!source) {
return UnmappedReason.MapPositionMissing;
}
return {
lineNumber: entry.line || 1,
columnNumber: entry.column ? entry.column + 1 : 1, // adjust for 0-based columns
source: source,
};
}
private getCompiledLocations(uiLocation: IUiLocation): IUiLocation[] {
if (!(uiLocation.source instanceof SourceFromMap)) {
return [];
}
let output: IUiLocation[] = [];
for (const [compiled, sourceUrl] of uiLocation.source.compiledToSourceUrl) {
const sourceMap = this._sourceMaps.get(compiled.sourceMap.url);
if (!sourceMap || !sourceMap.map) {
continue;
}
const entry = this.sourceMapFactory.guardSourceMapFn(
sourceMap.map,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
() => sourceUtils.getOptimalCompiledPosition(sourceUrl, uiLocation, sourceMap.map!),
getFallbackPosition,
);
if (!entry) {
continue;
}
const { lineNumber, columnNumber } = uiToRawOffset(
{
lineNumber: entry.line || 1,
columnNumber: (entry.column || 0) + 1, // correct for 0 index
},
compiled.inlineScriptOffset,
);
const compiledUiLocation: IUiLocation = {
lineNumber,
columnNumber,
source: compiled,
};
output = output.concat(compiledUiLocation, this.getCompiledLocations(compiledUiLocation));
}
return output;
}
/**
* Gets the best original position for the location in the source map.
*/
public getOptiminalOriginalPosition(sourceMap: SourceMap, uiLocation: LineColumn) {
return this.sourceMapFactory.guardSourceMapFn<NullableMappedPosition>(
sourceMap,
() => {
const glb = sourceMap.originalPositionFor({
line: uiLocation.lineNumber,
column: uiLocation.columnNumber - 1,
bias: SourceMapConsumer.GREATEST_LOWER_BOUND,
});
if (glb.line !== null) {
return glb;
}
return sourceMap.originalPositionFor({
line: uiLocation.lineNumber,
column: uiLocation.columnNumber - 1,
bias: SourceMapConsumer.LEAST_UPPER_BOUND,
});
},
getFallbackPosition,
);
}
/**
* Adds a new source to the collection.
*/
public async addSource(
url: string,
contentGetter: ContentGetter,
sourceMapUrl?: string,
inlineSourceRange?: InlineScriptOffset,
runtimeScriptOffset?: InlineScriptOffset,
contentHash?: string,
): Promise<Source> {
const absolutePath = await this.sourcePathResolver.urlToAbsolutePath({ url });
this.logger.verbose(LogTag.RuntimeSourceCreate, 'Creating source from url', {
inputUrl: url,
absolutePath,
});
const source = new Source(
this,
url,
absolutePath,
contentGetter,
sourceMapUrl &&
this.sourcePathResolver.shouldResolveSourceMap({
sourceMapUrl,
compiledPath: absolutePath || url,
})
? sourceMapUrl
: undefined,
inlineSourceRange,
runtimeScriptOffset,
this.launchConfig.enableContentValidation ? contentHash : undefined,
);
this._addSource(source);
return source;
}
private async _addSource(source: Source) {
const existingByUrl = source.url && this._sourceByOriginalUrl.get(source.url);
if (existingByUrl && !isOriginalSourceOf(existingByUrl, source)) {
this.removeSource(existingByUrl, true);
}
this._sourceByOriginalUrl.set(source.url, source);
this._sourceByReference.set(source.sourceReference, source);
if (source instanceof SourceFromMap) {
this._sourceMapSourcesByUrl.set(source.url, source);
}
// Some builds, like the Vue starter, generate 'metadata' files for compiled
// files with query strings appended to deduplicate them, or nested inside
// of internal prefixes. If we see a duplicate entries for an absolute path,
// take the shorter of them.
const existingByPath = this._sourceByAbsolutePath.get(source.absolutePath);
if (
existingByPath === undefined ||
existingByPath.url.length >= source.url.length ||
isOriginalSourceOf(existingByPath, source)
) {
this._sourceByAbsolutePath.set(source.absolutePath, source);
}
this.scriptSkipper.initializeSkippingValueForSource(source);
source.toDap().then(dap => this._dap.loadedSource({ reason: 'new', source: dap }));
if (!isSourceWithMap(source)) {
return;
}
const existingSourceMap = this._sourceMaps.get(source.sourceMap.url);
if (existingSourceMap) {
existingSourceMap.compiled.add(source);
if (existingSourceMap.map) {
// If source map has been already loaded, we add sources here.
// Otheriwse, we'll add sources for all compiled after loading the map.
await this._addSourceMapSources(source, existingSourceMap.map);
}
return;
}
const deferred = getDeferred<void>();
const sourceMap: SourceMapData = { compiled: new Set([source]), loaded: deferred.promise };
this._sourceMaps.set(source.sourceMap.url, sourceMap);
try {
sourceMap.map = await this.sourceMapFactory.load(source.sourceMap.metadata);
} catch (urlError) {
if (this.initializeConfig.clientID === 'visualstudio') {
// On VS we want to support loading source-maps from storage if the web-server doesn't serve them
const originalSourceMapUrl = source.sourceMap.metadata.sourceMapUrl;
try {
const sourceMapAbsolutePath = await this.sourcePathResolver.urlToAbsolutePath({
url: originalSourceMapUrl,
});
if (sourceMapAbsolutePath) {
source.sourceMap.metadata.sourceMapUrl =
utils.absolutePathToFileUrl(sourceMapAbsolutePath);
}
sourceMap.map = await this.sourceMapFactory.load(source.sourceMap.metadata);
this._statistics.fallbackSourceMapCount++;
this.logger.info(
LogTag.SourceMapParsing,
`Failed to process original source-map; falling back to storage source-map`,
{
fallbackSourceMapUrl: source.sourceMap.metadata.sourceMapUrl,
originalSourceMapUrl,
originalSourceMapError: extractErrorDetails(urlError),
},
);
} catch {}
}
if (!sourceMap.map) {
this._dap.output({
output: sourceMapParseFailed(source.url, urlError.message).error.format + '\n',
category: 'stderr',
});
return deferred.resolve();