Repository navigation
Expand file tree
/
Copy pathwindow-console.ts
More file actions
505 lines (463 loc) · 17.1 KB
/
Copy pathwindow-console.ts
File metadata and controls
505 lines (463 loc) · 17.1 KB
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
/* 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/. */
import { stripIndent, oneLine } from 'common-tags';
import type {
GetState,
Dispatch,
MixedObject,
Profile,
Thread,
Marker,
LogMarkerPayload,
} from 'firefox-profiler/types';
import { selectorsForConsole } from 'firefox-profiler/selectors';
import actions from 'firefox-profiler/actions';
import { shortenUrl } from 'firefox-profiler/utils/shorten-url';
import { createBrowserConnection } from 'firefox-profiler/app-logic/browser-connection';
import { formatTimestamp } from 'firefox-profiler/utils/format-numbers';
import { togglePseudoStrategy } from 'firefox-profiler/components/app/AppLocalizationProvider';
import type { ThemePreference } from 'firefox-profiler/utils/dark-mode';
import {
getThemePreference,
setThemePreference,
} from 'firefox-profiler/utils/dark-mode';
import { printSliceTree } from 'firefox-profiler/utils/slice-tree';
import type { CallTree } from 'firefox-profiler/profile-logic/call-tree';
import {
formatLogTimestamp,
formatLogStatement,
} from 'firefox-profiler/profile-logic/marker-data';
import { computeStringIndexMarkerFieldsByDataType } from 'firefox-profiler/profile-logic/marker-schema';
// Despite providing a good libdef for Object.defineProperty, Flow still
// special-cases the `value` property: if it's missing it throws an error. Using
// this indirection seems to work around this issue.
// See https://github.com/facebook/flow/issues/285
const defineProperty = Object.defineProperty;
export type ExtraPropertiesOnWindowForConsole = {
profile: Profile;
filteredThread: Thread;
callTree: CallTree;
filteredMarkers: Marker[];
selectedMarker: Marker | null;
experimental: {
enableEventDelayTracks(): void;
enableCPUGraphs(): void;
enableProcessCPUTracks(): void;
};
togglePseudoLocalization: (pseudoStrategy?: string) => void;
toggleTimelineType: (timelineType?: string) => void;
toggleDarkMode: () => void;
retrieveRawProfileDataFromBrowser: () => Promise<
MixedObject | ArrayBuffer | null
>;
saveToDisk: (
unknownObject: ArrayBuffer | unknown,
filename?: string
) => Promise<void>;
extractGeckoLogs: () => string;
totalMarkerDuration: (markers: any) => number;
activity: () => void;
shortenUrl: typeof shortenUrl;
getState: GetState;
selectors: typeof selectorsForConsole;
dispatch: Dispatch;
actions: typeof actions;
persistTooltips: boolean;
};
/**
* This function adds various values from the Redux Store to the window object so that
* people can access useful things.
*/
export function addDataToWindowObject(
getState: GetState,
dispatch: Dispatch,
target: Partial<ExtraPropertiesOnWindowForConsole> = window as {}
): ExtraPropertiesOnWindowForConsole {
defineProperty(target, 'profile', {
enumerable: true,
get() {
return selectorsForConsole.profile.getProfile(getState());
},
});
defineProperty(target, 'filteredThread', {
enumerable: true,
get() {
return selectorsForConsole.selectedThread.getFilteredThread(getState());
},
});
defineProperty(target, 'callTree', {
enumerable: true,
get() {
return selectorsForConsole.selectedThread.getCallTree(getState());
},
});
defineProperty(target, 'filteredMarkers', {
enumerable: true,
get() {
const state = getState();
const getMarker =
selectorsForConsole.selectedThread.getMarkerGetter(state);
const markerIndexes =
selectorsForConsole.selectedThread.getPreviewFilteredMarkerIndexes(
state
);
return markerIndexes.map(getMarker);
},
});
defineProperty(target, 'selectedMarker', {
enumerable: true,
get() {
return selectorsForConsole.selectedThread.getSelectedMarker(getState());
},
});
target.experimental = {
enableEventDelayTracks() {
const areEventDelayTracksEnabled = dispatch(
actions.enableEventDelayTracks()
);
if (areEventDelayTracksEnabled) {
console.log(stripIndent`
✅ The event delay tracks are now enabled and should be displayed in the timeline.
👉 Note that this is an experimental feature that might still have bugs.
💡 As an experimental feature their presence isn't persisted as a URL parameter like the other things.
`);
}
},
enableCPUGraphs() {
const areExperimentalCPUGraphsEnabled = dispatch(
actions.enableExperimentalCPUGraphs()
);
if (areExperimentalCPUGraphsEnabled) {
console.log(stripIndent`
✅ The CPU graphs are now enabled and should be displayed in the timeline.
👉 Note that this is an experimental feature that might still have bugs.
💡 As an experimental feature their presence isn't persisted as a URL parameter like the other things.
`);
}
},
enableProcessCPUTracks() {
const areExperimentalProcessCPUTracksEnabled = dispatch(
actions.enableExperimentalProcessCPUTracks()
);
if (areExperimentalProcessCPUTracksEnabled) {
console.log(stripIndent`
✅ The process CPU tracks are now enabled and should be displayed in the timeline.
👉 Note that this is an experimental feature that might still have bugs.
💡 As an experimental feature their presence isn't persisted as a URL parameter like the other things.
`);
}
},
};
target.togglePseudoLocalization = function (pseudoStrategy?: string) {
if (
pseudoStrategy !== undefined &&
pseudoStrategy !== 'accented' &&
pseudoStrategy !== 'bidi'
) {
console.log(stripIndent`
❗ The pseudo strategy "${pseudoStrategy}" is unknown.
💡 Valid strategies are: "accented" or "bidi".
Please try again 😊
`);
return;
}
togglePseudoStrategy(pseudoStrategy ?? null);
if (pseudoStrategy) {
console.log(stripIndent`
✅ The pseudo strategy "${pseudoStrategy}" is now enabled for the localization.
👉 To disable it, you can call togglePseudoLocalization() again without a parameter.
`);
} else {
console.log(stripIndent`
✅ The pseudo strategy is now disabled.
`);
}
};
target.toggleTimelineType = function (timelineType?: string) {
if (timelineType !== 'cpu-category' && timelineType !== 'stack') {
console.log(stripIndent`
❗ The timeline type "${timelineType}" is unknown.
💡 Valid types are: "cpu-category" or "stack".
Please try again 😊
`);
return;
}
dispatch(actions.changeTimelineType(timelineType));
console.log(stripIndent`
✅ The timeline type "${timelineType}" is now enabled for the timeline.
`);
};
target.toggleDarkMode = function () {
const current = getThemePreference();
let next: ThemePreference;
let message: string;
if (current === 'system') {
next = 'light';
message = '✅ Theme set to: light';
} else if (current === 'light') {
next = 'dark';
message = '✅ Theme set to: dark';
} else {
next = 'system';
message = '✅ Theme set to: system (follows OS preference)';
}
setThemePreference(next);
console.log(message);
};
target.retrieveRawProfileDataFromBrowser = async function (): Promise<
MixedObject | ArrayBuffer | null
> {
// Note that a new connection is created instead of reusing the one in the
// redux state, as an attempt to make it work even in the worst situations.
const browserConnectionStatus = await createBrowserConnection();
const browserConnection = actions.unwrapBrowserConnection(
browserConnectionStatus
);
const rawGeckoProfile = await browserConnection.getProfile({
onThirtySecondTimeout: () => {
console.log(
oneLine`
We were unable to connect to the browser within thirty seconds.
This might be because the profile is big or your machine is slower than usual.
Still waiting...
`
);
},
});
return rawGeckoProfile;
};
target.saveToDisk = async function (
unknownObject: ArrayBuffer | unknown,
filename?: string
) {
if (unknownObject === undefined || unknownObject === null) {
console.error("We can't save a null or undefined variable.");
return;
}
const arrayBufferOrString =
typeof unknownObject === 'string' ||
String(unknownObject) === '[object ArrayBuffer]'
? (unknownObject as string | ArrayBuffer)
: JSON.stringify(unknownObject);
const blob = new Blob([arrayBufferOrString], {
type: 'application/octet-stream',
});
const blobUrl = URL.createObjectURL(blob);
// Trigger the download programmatically
const downloadLink = document.createElement('a');
downloadLink.href = blobUrl;
downloadLink.download = filename ?? 'profile.data';
downloadLink.click();
// Clean up the URL object
URL.revokeObjectURL(blobUrl);
};
// This function extracts MOZ_LOGs saved as markers in a Firefox profile,
// using the MOZ_LOG canonical format.
target.extractGeckoLogs = function () {
const logs = [];
// This algorithm loops over the raw marker table instead of using the
// selectors so that the full marker list isn't generated for all the
// threads in the profile.
const profile = selectorsForConsole.profile.getProfile(getState());
const range =
selectorsForConsole.profile.getPreviewSelectionRange(getState());
// The schema tells us which payload fields hold string table indexes.
const stringIndexMarkerFieldsByDataType =
computeStringIndexMarkerFieldsByDataType(
selectorsForConsole.profile.getMarkerSchema(getState())
);
for (const thread of profile.threads) {
const { markers } = thread;
for (let i = 0; i < markers.length; i++) {
const startTime = markers.startTime[i];
if (
startTime !== null &&
markers.data[i]?.type === 'Log' &&
startTime >= range.start &&
startTime <= range.end
) {
const data = markers.data[i] as LogMarkerPayload;
const absoluteTs = profile.meta.startTime + startTime;
const strTimestamp = formatLogTimestamp(absoluteTs);
const processName = thread.processName ?? 'Unknown Process';
const stringArray = profile.shared.stringArray;
// For the new format the module name lives in the marker's name field.
// For the legacy format it is embedded in data.module; formatLogStatement
// handles that internally, so this value is not used in that case.
const moduleName = stringArray[markers.name[i]];
const statement = formatLogStatement(
strTimestamp,
processName,
thread.pid,
thread.name,
data,
moduleName,
stringArray,
stringIndexMarkerFieldsByDataType
);
if (statement !== null) {
logs.push(statement);
}
}
}
}
return logs.sort().join('\n');
};
target.totalMarkerDuration = function (markers: any) {
if (!Array.isArray(markers)) {
console.error('totalMarkerDuration expects an array of markers');
return 0;
}
let totalDuration = 0;
for (const marker of markers) {
if (
marker &&
typeof marker.start === 'number' &&
typeof marker.end === 'number'
) {
totalDuration += marker.end - marker.start;
}
// Skip markers with null end times (instant markers have no duration)
}
console.log(`Total marker duration: ${formatTimestamp(totalDuration)}`);
return totalDuration;
};
target.activity = function () {
const slices =
selectorsForConsole.selectedThread.getActivitySlices(getState());
if (slices) {
console.log(printSliceTree(slices).join('\n'));
}
};
target.shortenUrl = shortenUrl;
target.getState = getState;
target.selectors = selectorsForConsole;
target.dispatch = dispatch;
target.actions = actions;
// For debugging purposes, allow tooltips to persist. This aids in inspecting
// the DOM structure.
target.persistTooltips = false;
return target as any;
}
export function logFriendlyPreamble() {
/**
* Provide a friendly message to the end user to notify them that they can access certain
* values from the global window object. These variables are set in an ad-hoc fashion
* throughout the code.
*/
const intro = `font-size: 130%;`;
const bold = `font-weight: bold;`;
const link = `font-style: italic; text-decoration: underline;`;
const reset = '';
console.log(
// This is gratuitous, I know:
[
'%c __ _ __ ',
' / _(_) / _| ',
'| |_ _ _ __ ___| |_ _____ __ ',
"| _| | '__/ _ \\ _/ _ \\ \\/ / ",
'| | | | | | __/ || (_) > < __ _ _ ',
'|_| |_|_| \\___|_| \\___/_/\\_\\ / _(_) | ',
' ,. ,. _ __ _ __ ___ | |_ _| | ___ _ _ ',
" | \\ / | | '_ \\| '__/ _ \\| _| | |/ _ \\ '_| ",
' |/ \\ _ / \\| | |_) | | | (_) | | | | | __/ | ',
' | | | .__/|_| \\___/|_| |_|_|\\___|_| ',
' / - - \\ |_| ',
' ,- V__V -. ',
' -= __- * - .,=- ',
' `\\_ - _/ ',
" `-----' ",
].join('\n'),
'font-family: Menlo, monospace;'
);
console.log(
stripIndent`
%cThe following profiler information and tools are available via the console:%c
%cwindow.profile%c - The currently loaded profile
%cwindow.filteredThread%c - The current filtered thread
%cwindow.filteredMarkers%c - The current filtered and processed markers
%cwindow.selectedMarker%c - The selected processed marker in the current thread
%cwindow.callTree%c - The call tree of the current filtered thread
%cwindow.totalMarkerDuration%c - Calculate total duration of a marker array (e.g., totalMarkerDuration(filteredMarkers))
%cwindow.getState%c - The function that returns the current Redux state.
%cwindow.selectors%c - All the selectors that are used to get data from the Redux state.
%cwindow.dispatch%c - The function to dispatch a Redux action to change the state.
%cwindow.actions%c - All the actions that can be dispatched to change the state.
%cwindow.experimental%c - The object that holds flags of all the experimental features.
%cwindow.togglePseudoLocalization%c - Enable pseudo localizations by passing "accented" or "bidi" to this function, or disable using no parameters.
%cwindow.toggleTimelineType%c - Toggle timeline graph type by passing "cpu-category" or "stack".
%cwindow.toggleDarkMode%c - Cycle through theme preferences: system, light, dark.
%cwindow.retrieveRawProfileDataFromBrowser%c - Retrieve the profile attached to the current tab and returns it. Use "await" to call it, and use saveToDisk to save it.
%cwindow.extractGeckoLogs%c - Retrieve recorded logs in the current range, using the MOZ_LOG format. Use with "copy" or "saveToDisk".
%cwindow.saveToDisk%c - Saves to a file the parameter passed to it, with an optional filename parameter. You can use that to save the profile returned by "retrieveRawProfileDataFromBrowser" or the data returned by "extractGeckoLogs".
The profile format is documented here:
%chttps://github.com/firefox-devtools/profiler/blob/main/docs-developer/processed-profile-format.md%c
The CallTree class's source code is available here:
%chttps://github.com/firefox-devtools/profiler/blob/main/src/profile-logic/call-tree.ts%c
`,
// "The following profiler..."
intro,
reset,
// "window.profile"
bold,
reset,
// "window.filteredThread"
bold,
reset,
// "window.filteredMarkers"
bold,
reset,
// "window.selectedMarker"
bold,
reset,
// "window.callTree"
bold,
reset,
// "window.totalMarkerDuration"
bold,
reset,
// "window.getState"
bold,
reset,
// "window.selectors"
bold,
reset,
// "window.dispatch"
bold,
reset,
// "window.actions"
bold,
reset,
// "window.experimental"
bold,
reset,
// "window.togglePseudoLocalization"
bold,
reset,
// "window.toggleTimelineType"
bold,
reset,
// "window.toggleDarkMode"
bold,
reset,
// "window.retrieveRawProfileDataFromBrowser"
bold,
reset,
// "window.extractGeckoLogs"
bold,
reset,
// "window.saveToDisk"
bold,
reset,
// "processed-profile-format.md"
link,
reset,
// "call-tree.ts"
link,
reset
);
}
export function logDevelopmentTips() {
console.log('To debug tooltips, set window.persistTooltips to true.');
}