forked from firefox-devtools/profiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl-handling.js
356 lines (322 loc) · 11.5 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
/* 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 {
stringifyRangeFilters,
parseRangeFilters,
} from './profile-logic/range-filters';
import {
stringifyTransforms,
parseTransforms,
} from './profile-logic/transforms';
import { assertExhaustiveCheck, toValidTabSlug } from './utils/flow';
import { oneLine } from 'common-tags';
import type { UrlState } from './types/reducers';
import type { DataSource } from './types/actions';
export const CURRENT_URL_VERSION = 3;
function dataSourceDirs(urlState: UrlState) {
const { dataSource } = urlState;
switch (dataSource) {
case 'from-addon':
return ['from-addon'];
case 'from-file':
return ['from-file'];
case 'local':
return ['local', urlState.hash];
case 'public':
return ['public', urlState.hash];
case 'from-url':
return ['from-url', encodeURIComponent(urlState.profileUrl)];
default:
return [];
}
}
// "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 = {
range?: string, //
thread?: string, // "3"
threadOrder?: string, // "3-2-0-1"
hiddenThreads?: string | void, // "0-1"
react_perf?: null, // Flag to activate react's UserTimings profiler.
transforms?: string,
};
type CallTreeQuery = BaseQuery & {
search?: string, // "js::RunScript"
invertCallstack?: null | void,
implementation?: string,
};
type MarkersQuery = BaseQuery & {
markerSearch?: string, // "DOMEvent"
};
type StackChartQuery = BaseQuery & {
search?: string, // "js::RunScript"
invertCallstack?: null | void,
implementation?: string,
};
type UrlObject = {
pathParts: string[],
query: Query,
};
type Query = BaseQuery | CallTreeQuery | MarkersQuery | StackChartQuery;
/**
* Take the UrlState and map it into a serializable UrlObject, that represents the
* target URL.
*/
export function urlStateToUrlObject(urlState: UrlState): UrlObject {
const { dataSource } = urlState;
if (dataSource === 'none') {
return {
pathParts: [],
query: {},
};
}
const pathParts = [...dataSourceDirs(urlState), urlState.selectedTab];
// Start with the query parameters that are shown regardless of the active tab.
const query: Object = {
range:
stringifyRangeFilters(urlState.profileSpecific.rangeFilters) || undefined,
thread: urlState.profileSpecific.selectedThread,
threadOrder: urlState.profileSpecific.threadOrder.join('-'),
file: urlState.pathInZipFile || undefined,
v: CURRENT_URL_VERSION,
};
// Add the parameter hiddenThreads only when needed
if (urlState.profileSpecific.hiddenThreads.length > 0) {
query.hiddenThreads = urlState.profileSpecific.hiddenThreads.join('-');
}
if (process.env.NODE_ENV === 'development') {
/* eslint-disable camelcase */
query.react_perf = null;
/* eslint-enable camelcase */
}
// Depending on which tab is active, also show tab-specific query parameters.
const selectedTab = urlState.selectedTab;
switch (selectedTab) {
case 'stack-chart':
case 'flame-graph':
case 'calltree': {
query.search = urlState.profileSpecific.callTreeSearchString || undefined;
query.invertCallstack = urlState.profileSpecific.invertCallstack
? null
: undefined;
query.implementation =
urlState.profileSpecific.implementation === 'combined'
? undefined
: urlState.profileSpecific.implementation;
const selectedThread = urlState.profileSpecific.selectedThread;
if (selectedThread !== null) {
query.transforms =
stringifyTransforms(
urlState.profileSpecific.transforms[selectedThread]
) || undefined;
}
break;
}
case 'marker-table':
query.markerSearch = urlState.profileSpecific.markersSearchString;
break;
case 'marker-chart':
break;
default:
assertExhaustiveCheck(selectedTab);
}
return { query, pathParts };
}
export function urlFromState(urlState: UrlState): string {
const { pathParts, query } = urlStateToUrlObject(urlState);
const { dataSource } = urlState;
if (dataSource === 'none') {
return '/';
}
const pathname =
pathParts.length === 0 ? '/' : '/' + pathParts.join('/') + '/';
const qString = queryString.stringify(query);
return pathname + (qString ? '?' + qString : '');
}
function getDataSourceFromPathParts(pathParts: string[]): DataSource {
const str = pathParts[0] || 'none';
// With this switch, flow is able to understand that we return a valid value
switch (str) {
case 'none':
case 'from-addon':
case 'from-file':
case 'local':
case 'public':
case 'from-url':
return str;
default:
throw new Error(`Unexpected data source ${str}`);
}
}
/**
* 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,
};
export function stateFromLocation(location: Location): UrlState {
const { pathname, query } = upgradeLocationToCurrentVersion({
pathname: location.pathname,
hash: location.hash,
query: queryString.parse(location.search.substr(1)),
});
const pathParts = pathname.split('/').filter(d => d);
const dataSource = getDataSourceFromPathParts(pathParts);
const selectedThread = query.thread !== undefined ? +query.thread : null;
// https://perf-html.io/public/{hash}/calltree/
const hasProfileHash = ['local', 'public'].includes(dataSource);
// https://perf-html.io/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 (selectedThread !== null) {
transforms[selectedThread] = query.transforms
? parseTransforms(query.transforms)
: [];
}
return {
dataSource,
hash: hasProfileHash ? pathParts[1] : '',
profileUrl: hasProfileUrl ? decodeURIComponent(pathParts[1]) : '',
selectedTab: toValidTabSlug(pathParts[selectedTabPathPart]) || 'calltree',
pathInZipFile: query.file || null,
profileSpecific: {
implementation,
invertCallstack: query.invertCallstack !== undefined,
rangeFilters: query.range ? parseRangeFilters(query.range) : [],
selectedThread: selectedThread,
callTreeSearchString: query.search || '',
threadOrder: query.threadOrder
? query.threadOrder.split('-').map(index => Number(index))
: [],
hiddenThreads: query.hiddenThreads
? query.hiddenThreads.split('-').map(index => Number(index))
: [],
markersSearchString: query.markerSearch || '',
transforms,
},
};
}
type ProcessedLocation = { pathname: string, hash: string, query: Object };
export function upgradeLocationToCurrentVersion(
processedLocation: ProcessedLocation
): ProcessedLocation {
const urlVersion = +processedLocation.query.v || 0;
if (urlVersion === CURRENT_URL_VERSION) {
return processedLocation;
}
if (urlVersion > CURRENT_URL_VERSION) {
throw new Error(
`Unable to parse a url of version ${urlVersion} - are you running an outdated version of perf.html? ` +
`The most recent version understood by this version of perf.html is version ${CURRENT_URL_VERSION}.\n` +
'You can try refreshing this page in case perf.html has updated in the meantime.'
);
}
// Convert to CURRENT_URL_VERSION, one step at a time.
for (
let destVersion = urlVersion;
destVersion <= CURRENT_URL_VERSION;
destVersion++
) {
if (destVersion in _upgraders) {
_upgraders[destVersion](processedLocation);
}
}
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 single argument and mutates it.
/* eslint-disable no-useless-computed-key */
const _upgraders = {
[0]: (processedLocation: ProcessedLocation) => {
// Version 1 is the first versioned url.
// 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';
}
},
[1]: (processedLocation: ProcessedLocation) => {
// 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: ProcessedLocation) => {
// 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: ProcessedLocation) => {
const { query } = processedLocation;
// Removed "Hide platform details" checkbox from the stack chart.
if ('hidePlatformDetails' in query) {
delete query.hidePlatformDetails;
query.implementation = 'js';
}
},
};
if (Object.keys(_upgraders).length - 1 !== CURRENT_URL_VERSION) {
throw new Error(oneLine`
CURRENT_URL_VERSION does not match the number of URL upgraders. If you added a
new upgrader, make sure and bump the CURRENT_URL_VERSION variable.
`);
}