-
Notifications
You must be signed in to change notification settings - Fork 421
/
Copy pathurl-handling.js
1416 lines (1308 loc) · 47.9 KB
/
url-handling.js
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// @flow
import queryString from 'query-string';
import {
stringifyCommittedRanges,
stringifyStartEnd,
parseCommittedRanges,
} from 'firefox-profiler/profile-logic/committed-ranges';
import {
stringifyTransforms,
parseTransforms,
} from 'firefox-profiler/profile-logic/transforms';
import {
assertExhaustiveCheck,
toValidTabSlug,
coerce,
ensureExists,
} from 'firefox-profiler/utils/flow';
import {
getThreadsKey,
toValidCallTreeSummaryStrategy,
} from 'firefox-profiler/profile-logic/profile-data';
import { oneLine } from 'common-tags';
import type {
UrlState,
TimelineTrackOrganization,
DataSource,
Pid,
Profile,
RawThread,
IndexIntoStackTable,
TabID,
TrackIndex,
CallNodePath,
ThreadIndex,
TimelineType,
SourceViewState,
AssemblyViewState,
NativeSymbolInfo,
} from 'firefox-profiler/types';
import {
decodeUintArrayFromUrlComponent,
encodeUintArrayForUrlComponent,
encodeUintSetForUrlComponent,
} from '../utils/uintarray-encoding';
import { tabSlugs } from '../app-logic/tabs-handling';
export const CURRENT_URL_VERSION = 10;
/**
* This static piece of state might look like an anti-pattern, but it's a relatively
* simple way to adjust whether we are pushing or replacing onto the history API.
* The history API is a singleton, and so here we're also using a singleton pattern
* to manage this bit of state.
*/
let _isReplaceState: boolean = false;
let _replaceHistoryCallCount: number = 0;
function _enableHistoryReplaceState(): void {
_replaceHistoryCallCount++;
_isReplaceState = true;
}
/**
* Only disable the replace state if the call count is 0.
*/
function _maybeDisableHistoryReplaceState(): void {
_replaceHistoryCallCount--;
if (_replaceHistoryCallCount < 0) {
throw new Error(
'_maybeDisableHistoryReplaceState was called more than _enableHistoryReplaceState which should never happen.'
);
}
if (_replaceHistoryCallCount === 0) {
_isReplaceState = false;
}
}
/**
* This function changes the behavior of the history API to replace the current state,
* rather than pushState. It applies the function synchronously.
*/
export function withHistoryReplaceStateSync(fn: () => void): void {
_enableHistoryReplaceState();
try {
fn();
} finally {
_maybeDisableHistoryReplaceState();
}
}
/**
* The asynchronous variant of `withHistoryReplaceStateSync`.
*/
export async function withHistoryReplaceStateAsync(
fn: () => Promise<void>
): Promise<void> {
_enableHistoryReplaceState();
try {
await fn();
} finally {
_maybeDisableHistoryReplaceState();
}
}
/**
* This function is consumed by the UrlManager so it knows how to interact with the
* history API. It's embedded here to avoid cyclical dependencies when importing files.
*/
export function getIsHistoryReplaceState(): boolean {
return _isReplaceState;
}
function getPathParts(urlState: UrlState): string[] {
const { dataSource } = urlState;
switch (dataSource) {
case 'none':
return [];
case 'compare':
// Special handling for CompareHome: we shouldn't append anything but the
// dataSource when the user is on the comparison form.
if (urlState.profilesToCompare === null) {
return ['compare'];
}
return ['compare', urlState.selectedTab];
case 'uploaded-recordings':
return ['uploaded-recordings'];
case 'from-browser':
case 'from-post-message':
case 'unpublished':
case 'from-file':
return [dataSource, urlState.selectedTab];
case 'public':
case 'local':
return [dataSource, urlState.hash, urlState.selectedTab];
case 'from-url':
return [
'from-url',
encodeURIComponent(urlState.profileUrl),
urlState.selectedTab,
];
default:
throw assertExhaustiveCheck(dataSource);
}
}
// Base query that only applies to full profile view.
type FullProfileSpecificBaseQuery = {|
globalTrackOrder: string, // "3201"
hiddenGlobalTracks: string, // "01"
hiddenLocalTracksByPid: string, // "1549-0w8~1593-23~1598-01~1602-02~1607-1"
localTrackOrderByPid: string, // "1549-780w6~1560-01"
tabID: TabID,
// The following values are legacy, and will be converted to track-based values. These
// value can't be upgraded using the typical URL upgrading process, as the full profile
// must be fetched to compute the tracks.
threadOrder: string, // "3-2-0-1"
hiddenThreads: string, // "0-1"
|};
// Base query that only applies to active tab profile view.
type ActiveTabProfileSpecificBaseQuery = {|
resources: null | void,
ctxId: TabID | void,
|};
// Base query that only applies to origins profile view.
type OriginsProfileSpecificBaseQuery = {||};
// "null | void" in the query objects are flags which map to true for null, and false
// for void. False flags do not show up the URL.
type BaseQuery = {|
v: number,
range: string, //
thread: string, // "3"
file: string, // Path into a zip file.
transforms: string,
profiles: string[],
profileName: string,
symbolServer: string,
view: string,
implementation: string,
timelineType: string,
sourceView: string,
assemblyView: string,
...FullProfileSpecificBaseQuery,
...ActiveTabProfileSpecificBaseQuery,
...OriginsProfileSpecificBaseQuery,
|};
type CallTreeQuery = {|
...BaseQuery,
search: string, // "js::RunScript"
invertCallstack: null | void,
ctSummary: string,
|};
type MarkersQuery = {|
...BaseQuery,
markerSearch: string, // "DOMEvent"
|};
type NetworkQuery = {|
...BaseQuery,
networkSearch?: string, // "DOMEvent"
|};
type StackChartQuery = {|
...BaseQuery,
search: string, // "js::RunScript"
invertCallstack: null | void,
showUserTimings: null | void,
ctSummary: string,
|};
type JsTracerQuery = {|
...BaseQuery,
summary: null | void,
|};
type Query =
| CallTreeQuery
| MarkersQuery
| NetworkQuery
| StackChartQuery
| JsTracerQuery;
type $MakeOptional = <T>(T) => T | void;
// Base query shape is needed for the typechecking during the URL query initialization.
type BaseQueryShape = $Shape<$ObjMap<BaseQuery, $MakeOptional>>;
// Full profile view and active tab profile view query shapes are for also
// typechecking during the query object initialization.
type FullProfileSpecificBaseQueryShape = $Shape<
$ObjMap<FullProfileSpecificBaseQuery, $MakeOptional>,
>;
type ActiveTabProfileSpecificBaseQueryShape = $Shape<
$ObjMap<ActiveTabProfileSpecificBaseQuery, $MakeOptional>,
>;
type OriginsProfileSpecificBaseQueryShape = $Shape<
$ObjMap<OriginsProfileSpecificBaseQuery, $MakeOptional>,
>;
// Query shapes for individual query paths. These are needed for QueryShape union type.
type CallTreeQueryShape = $Shape<$ObjMap<CallTreeQuery, $MakeOptional>>;
type MarkersQueryShape = $Shape<$ObjMap<MarkersQuery, $MakeOptional>>;
type NetworkQueryShape = $Shape<$ObjMap<NetworkQuery, $MakeOptional>>;
type StackChartQueryShape = $Shape<$ObjMap<StackChartQuery, $MakeOptional>>;
type JsTracerQueryShape = $Shape<$ObjMap<JsTracerQuery, $MakeOptional>>;
type QueryShape =
| CallTreeQueryShape
| MarkersQueryShape
| NetworkQueryShape
| StackChartQueryShape
| JsTracerQueryShape;
/**
* Take the UrlState and map it into a query string.
*/
export function getQueryStringFromUrlState(urlState: UrlState): string {
const { dataSource } = urlState;
switch (dataSource) {
case 'none':
case 'uploaded-recordings':
return '';
case 'compare':
// Special handling for CompareHome: we shouldn't append the default
// parameters when the user is on the comparison form.
if (urlState.profilesToCompare === null) {
return '';
}
break;
case 'public':
case 'local':
case 'from-browser':
case 'from-post-message':
case 'unpublished':
case 'from-file':
case 'from-url':
break;
default:
throw assertExhaustiveCheck(dataSource);
}
const { selectedThreads } = urlState.profileSpecific;
const selectedThreadsKey =
selectedThreads !== null ? getThreadsKey(selectedThreads) : null;
let ctxId;
let view;
const { timelineTrackOrganization } = urlState;
switch (timelineTrackOrganization.type) {
case 'full':
// Dont URL-encode anything.
break;
case 'active-tab':
view = timelineTrackOrganization.type;
ctxId = timelineTrackOrganization.tabID;
break;
case 'origins':
view = timelineTrackOrganization.type;
break;
default:
throw assertExhaustiveCheck(
timelineTrackOrganization,
'Unhandled TimelineTrackOrganization case'
);
}
// Start with the query parameters that are shown regardless of the active panel.
let baseQuery;
switch (timelineTrackOrganization.type) {
case 'full': {
// Add the full profile specific state query here.
baseQuery = ({}: FullProfileSpecificBaseQueryShape);
baseQuery.globalTrackOrder = convertGlobalTrackOrderToString(
urlState.profileSpecific.full.globalTrackOrder
);
baseQuery.hiddenGlobalTracks = convertHiddenGlobalTracksToString(
urlState.profileSpecific.full.hiddenGlobalTracks
);
baseQuery.hiddenLocalTracksByPid = convertHiddenLocalTracksByPidToString(
urlState.profileSpecific.full.hiddenLocalTracksByPid
);
baseQuery.localTrackOrderByPid = convertLocalTrackOrderByPidToString(
urlState.profileSpecific.full.localTrackOrderByPid,
urlState.profileSpecific.full.localTrackOrderChangedPids
);
baseQuery.tabID = urlState.profileSpecific.full.tabFilter ?? undefined;
break;
}
case 'active-tab': {
baseQuery = ({}: ActiveTabProfileSpecificBaseQueryShape);
baseQuery.resources = urlState.profileSpecific.activeTab
.isResourcesPanelOpen
? null
: undefined;
baseQuery.ctxId = ctxId || undefined;
break;
}
case 'origins':
baseQuery = ({}: OriginsProfileSpecificBaseQueryShape);
break;
default:
throw assertExhaustiveCheck(
timelineTrackOrganization,
`Unhandled GlobalTrack type.`
);
}
baseQuery = ({
...baseQuery,
range:
stringifyCommittedRanges(urlState.profileSpecific.committedRanges) ||
undefined,
thread:
selectedThreads === null
? undefined
: encodeUintSetForUrlComponent(selectedThreads),
file: urlState.pathInZipFile || undefined,
profiles: urlState.profilesToCompare || undefined,
view,
v: CURRENT_URL_VERSION,
profileName: urlState.profileName || undefined,
symbolServer: urlState.symbolServerUrl || undefined,
implementation:
urlState.profileSpecific.implementation === 'combined'
? undefined
: urlState.profileSpecific.implementation,
timelineType:
// The default is the cpu-category view, so only add it to the URL if it's
// the stack or category view.
urlState.profileSpecific.timelineType === 'cpu-category'
? undefined
: urlState.profileSpecific.timelineType,
}: BaseQueryShape);
// Depending on which panel is active, also show tab-specific query parameters.
let query: QueryShape;
const selectedTab = urlState.selectedTab;
switch (selectedTab) {
case 'stack-chart':
case 'flame-graph':
case 'function-list':
case 'calltree': {
if (selectedTab === 'stack-chart') {
// Stack chart uses all of the CallTree's query strings but also has an
// additional query string.
query = (baseQuery: StackChartQueryShape);
query.showUserTimings = urlState.profileSpecific.showUserTimings
? null
: undefined;
} else {
query = (baseQuery: CallTreeQueryShape);
}
query.search = urlState.profileSpecific.callTreeSearchString || undefined;
query.invertCallstack = urlState.profileSpecific.invertCallstack
? null
: undefined;
if (
selectedThreadsKey !== null &&
urlState.profileSpecific.transforms[selectedThreadsKey]
) {
query.transforms =
stringifyTransforms(
urlState.profileSpecific.transforms[selectedThreadsKey]
) || undefined;
}
query.ctSummary =
urlState.profileSpecific.lastSelectedCallTreeSummaryStrategy ===
'timing'
? undefined
: urlState.profileSpecific.lastSelectedCallTreeSummaryStrategy;
const { sourceView, assemblyView, isBottomBoxOpenPerPanel } =
urlState.profileSpecific;
if (isBottomBoxOpenPerPanel[selectedTab]) {
if (sourceView.sourceFile !== null) {
query.sourceView = sourceView.sourceFile;
}
if (assemblyView.isOpen && assemblyView.nativeSymbol !== null) {
query.assemblyView = stringifyAssemblyViewSymbol(
assemblyView.nativeSymbol
);
}
}
break;
}
case 'marker-table':
case 'marker-chart':
query = (baseQuery: MarkersQueryShape);
query.markerSearch =
urlState.profileSpecific.markersSearchString || undefined;
break;
case 'network-chart':
query = (baseQuery: NetworkQueryShape);
query.networkSearch =
urlState.profileSpecific.networkSearchString || undefined;
break;
case 'js-tracer': {
query = (baseQuery: JsTracerQueryShape);
const { timelineTrackOrganization } = urlState;
switch (timelineTrackOrganization.type) {
case 'full':
case 'origins':
// `null` adds the parameter to the query, while `undefined` doesn't.
query.summary = urlState.profileSpecific.full.showJsTracerSummary
? null
: undefined;
break;
case 'active-tab':
// JS Tracer isn't helpful for web developers.
break;
default:
throw assertExhaustiveCheck(
timelineTrackOrganization,
'Unhandled timelineTrackOrganization case'
);
}
break;
}
default:
throw assertExhaustiveCheck(selectedTab);
}
const qString = queryString.stringify(query, {
arrayFormat: 'bracket', // This uses parameters with brackets for arrays.
});
return qString;
}
export function urlFromState(urlState: UrlState): string {
const pathParts = getPathParts(urlState);
const qString = getQueryStringFromUrlState(urlState);
const { dataSource } = urlState;
if (dataSource === 'none') {
return '/';
}
const pathname =
pathParts.length === 0 ? '/' : '/' + pathParts.join('/') + '/';
return pathname + (qString ? '?' + qString : '');
}
export function ensureIsValidDataSource(
possibleDataSource: string | void
): DataSource {
// By casting `possibleDataSource` to a DataSource beforehand, we let Flow
// enforce that we look at all possible values.
const coercedDataSource = coerce<string, DataSource>(
possibleDataSource || 'none'
);
switch (coercedDataSource) {
case 'none':
case 'from-browser':
case 'from-post-message':
case 'unpublished':
case 'from-file':
case 'local':
case 'public':
case 'from-url':
case 'compare':
case 'uploaded-recordings':
return coercedDataSource;
default:
throw assertExhaustiveCheck(
coercedDataSource,
`Unexpected data source ${coercedDataSource}`
);
}
}
/**
* Define only the properties of the window.location object that the function uses
* so that it can be mocked in tests.
*/
type Location = {
pathname: string,
search: string,
hash: string,
};
/**
* Parse the window.location string to create the UrlState.
*
* `profile` parameter is nullable and optional. It's nullable because data sources
* like from-browser can't upgrade a url for a freshly captured profile. So we need
* to skip upgrading for these sources. It's also optional for both testing
* purposes and for places where we would like to do the upgrading without
* providing any profile.
*/
export function stateFromLocation(
location: Location,
profile?: Profile | null
): UrlState {
const { pathname, query } = upgradeLocationToCurrentVersion(
{
pathname: location.pathname,
hash: location.hash,
query: queryString.parse(location.search.substr(1), {
arrayFormat: 'bracket', // This uses parameters with brackets for arrays.
}),
},
profile
);
const pathParts = pathname.split('/').filter((d) => d);
const dataSource = ensureIsValidDataSource(pathParts[0]);
const selectedThreadsList: ThreadIndex[] =
// Either a single thread index, or a list separated by commas.
query.thread !== undefined
? decodeUintArrayFromUrlComponent(query.thread)
: [];
const selectedThreads =
selectedThreadsList.length !== 0 ? new Set(selectedThreadsList) : null;
const selectedThreadsKey =
selectedThreads !== null ? getThreadsKey(selectedThreads) : null;
// https://profiler.firefox.com/public/{hash}/calltree/
const hasProfileHash = ['local', 'public'].includes(dataSource);
// https://profiler.firefox.com/from-url/{url}/calltree/
const hasProfileUrl = ['from-url'].includes(dataSource);
// The selected tab is the last path part in the URL.
const selectedTabPathPart = hasProfileHash || hasProfileUrl ? 2 : 1;
let implementation = 'combined';
// Don't trust the implementation values from the user. Make sure it conforms
// to known values.
if (query.implementation === 'js' || query.implementation === 'cpp') {
implementation = query.implementation;
}
const transforms = {};
if (selectedThreadsKey !== null) {
transforms[selectedThreadsKey] = parseTransforms(query.transforms);
}
// oldTabID is used for the old active tab view that we had. We will remove
// it in the end, but have to keep this while we have the view.
let oldTabID = null;
if (query.ctxId && Number.isInteger(Number(query.ctxId))) {
oldTabID = Number(query.ctxId);
}
// tabID is used for the tab selector that we have in our full view.
let tabID = null;
if (query.tabID && Number.isInteger(Number(query.tabID))) {
tabID = Number(query.tabID);
}
const selectedTab =
toValidTabSlug(pathParts[selectedTabPathPart]) || 'calltree';
const sourceView: SourceViewState = {
scrollGeneration: 0,
libIndex: null,
sourceFile: null,
};
const assemblyView: AssemblyViewState = {
isOpen: false,
scrollGeneration: 0,
nativeSymbol: null,
allNativeSymbolsForInitiatingCallNode: [],
};
const isBottomBoxOpenPerPanel = {};
tabSlugs.forEach((tabSlug) => (isBottomBoxOpenPerPanel[tabSlug] = false));
if (query.sourceView) {
sourceView.sourceFile = query.sourceView;
isBottomBoxOpenPerPanel[selectedTab] = true;
}
if (query.assemblyView) {
const symbol = parseAssemblyViewSymbol(query.assemblyView);
if (symbol !== null) {
assemblyView.nativeSymbol = symbol;
assemblyView.allNativeSymbolsForInitiatingCallNode = [symbol];
assemblyView.isOpen = true;
isBottomBoxOpenPerPanel[selectedTab] = true;
}
}
const localTrackOrderByPid = convertLocalTrackOrderByPidFromString(
query.localTrackOrderByPid
);
const localTrackOrderChangedPids = new Set(localTrackOrderByPid.keys());
return {
dataSource,
hash: hasProfileHash ? pathParts[1] : '',
profileUrl: hasProfileUrl ? decodeURIComponent(pathParts[1]) : '',
profilesToCompare: query.profiles || null,
selectedTab,
pathInZipFile: query.file || null,
profileName: query.profileName,
symbolServerUrl: query.symbolServer || null,
timelineTrackOrganization: validateTimelineTrackOrganization(
query.view,
oldTabID
),
profileSpecific: {
implementation,
lastSelectedCallTreeSummaryStrategy: toValidCallTreeSummaryStrategy(
query.ctSummary || undefined
),
invertCallstack: query.invertCallstack === undefined ? false : true,
showUserTimings: query.showUserTimings === undefined ? false : true,
committedRanges: query.range ? parseCommittedRanges(query.range) : [],
selectedThreads,
callTreeSearchString: query.search || '',
markersSearchString: query.markerSearch || '',
networkSearchString: query.networkSearch || '',
transforms,
sourceView,
assemblyView,
isBottomBoxOpenPerPanel,
timelineType: validateTimelineType(query.timelineType),
full: {
showJsTracerSummary: query.summary === undefined ? false : true,
globalTrackOrder: convertGlobalTrackOrderFromString(
query.globalTrackOrder
),
hiddenGlobalTracks: convertHiddenGlobalTracksFromString(
query.hiddenGlobalTracks
),
hiddenLocalTracksByPid: convertHiddenLocalTracksByPidFromString(
query.hiddenLocalTracksByPid
),
localTrackOrderByPid,
localTrackOrderChangedPids,
tabFilter: tabID,
legacyThreadOrder: query.threadOrder
? query.threadOrder.split('-').map((index) => Number(index))
: null,
legacyHiddenThreads: query.hiddenThreads
? query.hiddenThreads.split('-').map((index) => Number(index))
: null,
},
activeTab: {
isResourcesPanelOpen: query.resources !== undefined,
},
},
};
}
function convertGlobalTrackOrderFromString(
rawString: string | null | void
): TrackIndex[] {
if (!rawString) {
return [];
}
return decodeUintArrayFromUrlComponent(rawString);
}
function convertGlobalTrackOrderToString(order: TrackIndex[]): string | void {
return encodeUintArrayForUrlComponent(order) || undefined;
}
function convertHiddenGlobalTracksFromString(
rawString: string | null | void
): Set<TrackIndex> {
if (!rawString) {
return new Set();
}
return new Set(decodeUintArrayFromUrlComponent(rawString));
}
function convertHiddenGlobalTracksToString(
hiddenGlobalTracks: Set<TrackIndex>
): string | void {
// Add the parameter hiddenGlobalTracks only when needed.
if (hiddenGlobalTracks.size > 0) {
return encodeUintSetForUrlComponent(hiddenGlobalTracks);
}
return undefined;
}
/**
* Hidden local tracks must have the track indexes plus the associated PID.
*
* Syntax: Pid-<encoded TrackIndex set>~Pid-<encoded TrackIndex set>
* Example: 124553-03~124554-1
*/
function convertHiddenLocalTracksByPidFromString(
rawText: string | null | void
): Map<Pid, Set<TrackIndex>> {
if (!rawText) {
return new Map();
}
const hiddenLocalTracksByPid = new Map();
for (const stringPart of rawText.split('~')) {
if (!stringPart.includes('-')) {
continue;
}
// TODO: handle escaped dashes and tildes in pid strings (#4512)
const pid = stringPart.slice(0, stringPart.indexOf('-'));
const hiddenTracksString = stringPart.slice(pid.length + 1);
const indexes = decodeUintArrayFromUrlComponent(hiddenTracksString);
if (indexes.every((n) => !isNaN(n))) {
hiddenLocalTracksByPid.set(pid, new Set(indexes));
}
}
return hiddenLocalTracksByPid;
}
function convertHiddenLocalTracksByPidToString(
hiddenLocalTracksByPid: Map<Pid, Set<TrackIndex>>
): string | void {
const strings = [];
for (const [pid, tracks] of hiddenLocalTracksByPid) {
if (tracks.size > 0) {
// TODO: escaped dashes and tildes in pids (#4512)
strings.push(`${pid}-${encodeUintSetForUrlComponent(tracks)}`);
}
}
// Only add to the query string if something was actually hidden.
return strings.join('~') || undefined;
}
/**
* Local tracks must have their track order associated by PID.
*
* Syntax: Pid-<encoded TrackIndex array>~Pid-<encoded TrackIndex array>
* Example: 124553-0w354~124554-1
*/
function convertLocalTrackOrderByPidFromString(
rawText: string | null | void
): Map<Pid, TrackIndex[]> {
if (!rawText) {
return new Map();
}
const localTrackOrderByPid = new Map();
for (const stringPart of rawText.split('~')) {
if (!stringPart.includes('-')) {
// There is no order to determine, let the URL validation create the
// default value.
continue;
}
// TODO: handle escaped dashes and tildes in pid strings (#4512)
const pid = stringPart.slice(0, stringPart.indexOf('-'));
const trackOrderString = stringPart.slice(pid.length + 1);
const indexes = decodeUintArrayFromUrlComponent(trackOrderString);
if (indexes.every((n) => !isNaN(n))) {
localTrackOrderByPid.set(pid, indexes);
}
}
return localTrackOrderByPid;
}
function convertLocalTrackOrderByPidToString(
localTrackOrderByPid: Map<Pid, TrackIndex[]>,
localTrackOrderChangedPids: Set<Pid>
): string | void {
const strings = [];
for (const pid of localTrackOrderChangedPids) {
const trackOrder = localTrackOrderByPid.get(pid);
if (!trackOrder) {
continue;
}
if (trackOrder.length > 0) {
// TODO: escaped dashes and tildes in pids (#4512)
strings.push(`${pid}-${encodeUintArrayForUrlComponent(trackOrder)}`);
}
}
return strings.join('~') || undefined;
}
// This Error class is used in other codepaths to detect the specific error of
// URL upgrading and react differently when this happens, compared to other
// errors.
// Exported for tests.
export class UrlUpgradeError extends Error {
name = 'UrlUpgradeError';
}
type ProcessedLocation = {|
pathname: string,
hash: string,
query: Query,
|};
type ProcessedLocationBeforeUpgrade = {|
...ProcessedLocation,
query: any,
|};
// URL upgrading is skipped if the profile argument is null.
// URL upgrading is performed if the profile argument is missing (undefined) or if it's an actual profile.
export function upgradeLocationToCurrentVersion(
processedLocation: ProcessedLocationBeforeUpgrade,
profile?: Profile | null
): ProcessedLocation {
// Forward /from-addon to /from-browser immediately, outside of the versioning process.
// This ensures compatibility with Firefox versions < 93.
// It's possible we get 2 '/' characters if the user changes their base-url
// preference in about:config, so we should handle this case so that we don't
// get errors later in the loading process.
processedLocation.pathname = processedLocation.pathname.replace(
/^\/+from-addon/,
'/from-browser'
);
const urlVersion = +processedLocation.query.v || 0;
if (profile === null || urlVersion === CURRENT_URL_VERSION) {
// Do not upgrade when either profile data is null or url is on the latest
// version already. Profile can be null only when the source could not provide
// that for upgrader and therefore upgrading step is not needed (e.g. 'from-browser').
return processedLocation;
}
if (urlVersion > CURRENT_URL_VERSION) {
throw new UrlUpgradeError(
`Unable to parse a url of version ${urlVersion}, most likely profiler.firefox.com needs to be refreshed. ` +
`The most recent version understood by this version of profiler.firefox.com is version ${CURRENT_URL_VERSION}.\n` +
'You can try refreshing this page in case profiler.firefox.com has updated in the meantime.'
);
}
// Convert to CURRENT_URL_VERSION, one step at a time.
for (
let destVersion = urlVersion + 1;
destVersion <= CURRENT_URL_VERSION;
destVersion++
) {
if (destVersion in _upgraders) {
const upgrader = _upgraders[destVersion];
upgrader(processedLocation, profile);
}
}
processedLocation.query.v = CURRENT_URL_VERSION;
return processedLocation;
}
// _upgraders[i] converts from version i - 1 to version i.
// Every "upgrader" takes the processedLocation as its first argument and mutates it.
// If available, the profile is passed as the second argument, for any upgraders that need it.
/* eslint-disable no-useless-computed-key */
const _upgraders: {|
[number]: (
location: ProcessedLocationBeforeUpgrade,
profile?: Profile
) => void,
|} = {
[1]: (processedLocation: ProcessedLocationBeforeUpgrade) => {
// Version 1 is the first versioned url. Do some best-effort upgrading from
// un-versioned URLs.
// If the pathname is '/', this could be a very old URL that has its information
// stored in the hash.
if (processedLocation.pathname === '/') {
const legacyQuery = Object.assign(
{},
processedLocation.query,
queryString.parse(processedLocation.hash)
);
if ('report' in legacyQuery) {
// Put the report into the pathname.
processedLocation.pathname = `/public/${legacyQuery.report}/calltree/`;
processedLocation.hash = '';
processedLocation.query = {};
}
}
// Instead of implementation filters, we used to have jsOnly flags.
if (processedLocation.query.jsOnly !== undefined) {
// Support the old URL structure that had a jsOnly flag.
delete processedLocation.query.jsOnly;
processedLocation.query.implementation = 'js';
}
// The transform stack was added. Convert the callTreeFilters into the new
// transforms format.
if (processedLocation.query.callTreeFilters) {
// Before: "callTreeFilters=prefix-0KV4KV5KV61KV7KV8K~postfixjs-xFFpUMl"
// After: "transforms=f-combined-0KV4KV5KV61KV7KV8K~f-js-xFFpUMl-i"
processedLocation.query.transforms =
processedLocation.query.callTreeFilters
.split('~')
.map((s) => {
const [type, val] = s.split('-');
switch (type) {
case 'prefix':
return `f-combined-${val}`;
case 'prefixjs':
return `f-js-${val}`;
case 'postfix':
return `f-combined-${val}-i`;
case 'postfixjs':
return `f-js-${val}-i`;
default:
return undefined;
}
})
.filter((f) => f)
.join('~');
delete processedLocation.query.callTreeFilters;
}
},
[2]: (processedLocation: ProcessedLocationBeforeUpgrade) => {
// Map the tab "timeline" to "stack-chart".
// Map the tab "markers" to "marker-table".
processedLocation.pathname = processedLocation.pathname
// Given: /public/e71ce9584da34298627fb66ac7f2f245ba5edbf5/timeline/
// Matches: $1^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.replace(/^(\/[^/]+\/[^/]+)\/timeline\/?/, '$1/stack-chart/')
// Given: /public/e71ce9584da34298627fb66ac7f2f245ba5edbf5/markers/
// Matches: $1^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.replace(/^(\/[^/]+\/[^/]+)\/markers\/?/, '$1/marker-table/');
},
[3]: (processedLocation: ProcessedLocationBeforeUpgrade) => {
const { query } = processedLocation;
// Removed "Hide platform details" checkbox from the stack chart.
if ('hidePlatformDetails' in query) {
delete query.hidePlatformDetails;
query.implementation = 'js';
}
},
[4]: (
processedLocation: ProcessedLocationBeforeUpgrade,
profile?: Profile
) => {
// 'js' implementation filter has been changed to include 'relevantForJS' label frames.
// Iterate through all transforms and upgrade the ones that has callNodePath with JS
// implementation filter, so they also include 'relevantForJS' label frames in their
// callNodePaths. For example, in a call stack like this: 'C++->JS->relevantForJS->JS'
// Previous callNodePath was 'JS,JS'. But now it has to be 'JS,relevantForJS,JS'.
const query = processedLocation.query;
const selectedThread: null | number =
query.thread === undefined ? null : +query.thread;
if (selectedThread === null || profile === undefined) {
return;
}
// Parse the transforms. NOTE: This is parsing according to today's transform
// URL encoding, which is different from the V3 transform encoding!
// Some transforms, such as the former "collapse-direct-recursion" transform,
// will not be preserved.
const transforms = parseTransforms(query.transforms);
if (!transforms || transforms.length === 0) {
// We don't have any transforms to upgrade.
return;
}
// The transform stack is for the selected thread.
// At the time this upgrader was written, there was only one selected thread.